Search is not available for this dataset
project
stringlengths
1
235
source
stringclasses
16 values
language
stringclasses
48 values
content
stringlengths
909
64.8M
lookbook
ruby
Ruby
[![](.github/assets/lookbook_logo.svg)](https://lookbook.build) A UI development environment for Ruby on Rails applications. **[Documentation](https://lookbook.build)  |  [Demo site](http://demo.lookbook.build/lookbook)** [![Gem version](https://img.shields.io/gem/v/lookbook)](https://rubygems.org/gems/lookbook) [![CI status](https://github.com/ViewComponent/lookbook/actions/workflows/ci.yml/badge.svg)](https://github.com/ViewComponent/lookbook/actions/workflows/ci.yml) --- Lookbook combines a powerful **component browser** and **preview system** with an **integrated documentation engine** to help teams build robust, modular, maintainable user interfaces. [**Learn more →**](https://lookbook.build) --- [![Lookbook UI](.github/assets/lookbook_ui.png)](http://lookbook.build/) Development --- Lookbook is implemented as an isolated [Rails Engine](https://guides.rubyonrails.org/engines.html) and uses [ViewComponent](https://viewcomponent.org), [Tailwind](https://tailwindcss.com/) and [Alpine](https://alpinejs.dev/) for its UI. This repository contains: * The Lookbook source code ([`/app`](https://github.com/ViewComponent/lookbook/tree/main/app), [`/lib`](https://github.com/ViewComponent/lookbook/tree/main/lib), [`/config`](https://github.com/ViewComponent/lookbook/tree/main/config), etc) * The Lookbook [documentation site](#docs-site) source code and content ([`/docs`](https://github.com/ViewComponent/lookbook/tree/main/docs)). * A [test suite](#testing) with a 'runable' dummy app ([`/spec`](https://github.com/ViewComponent/lookbook/tree/main/spec)). ### Documentation site The [Lookbook docs site](https://lookbook.build) is built using [Bridgetown](https://www.bridgetownrb.com/) and the source files can be found in the `./docs` directory. To preview changes locally you can run a development version of the docs site: 1. Clone this repo 2. Install dependencies: `bundle install` 3. Start the app: `bin/docs` 4. Visit <http://localhost:4000### Testing Lookbook uses [RSpec](https://relishapp.com/rspec) for testing. Tests can be run using the `rake spec` or `bundle exec rspec` commands. The dummy app that the tests are being run against can be viewed by running the `bin/dummy` command and then browsing to <http://localhost:9292/lookbook### Releases Lookbook uses [Release It!](https://github.com/release-it/release-it) to automate the release process. Running `npm run release` will start the process of publishing a new release and walks though all the steps from picking a version number to publishing the updated gem. Publishing a release requires write permissions for this repository (ViewComponent/lookbook) and 2FA publish permissions for Lookbook on RubyGems. Contributing --- Lookbook is an un-funded open source project and contributions of all types and sizes are most welcome! Please take the time to read over the [Contributing](./CONTRIBUTING.md) guide before making your first contribution and if anything isn't clear then [start a discussion](https://github.com/ViewComponent/lookbook/discussions) and we will do our best to help you out. Contributors --- Lookbook was created by [<NAME>](https://github.com/allmarkedup) and continues to grow & improve thanks to the ideas, suggestions and hard work of all of [these excellent humans](https://github.com/ViewComponent/lookbook/graphs/contributors): [![](https://contrib.rocks/image?repo=ViewComponent/lookbook&columns=14)](https://github.com/ViewComponent/lookbook/graphs/contributors) License --- The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
github.com/gdamore/tcell
go
Go
README [¶](#section-readme) --- ``` = tcell image:https://img.shields.io/travis/gdamore/tcell.svg?label=linux[Linux Status,link="https://travis-ci.org/gdamore/tcell"] image:https://img.shields.io/appveyor/ci/gdamore/tcell.svg?label=windows[Windows Status,link="https://ci.appveyor.com/project/gdamore/tcell"] image:https://img.shields.io/badge/license-APACHE2-blue.svg[Apache License,link="https://github.com/gdamore/tcell/blob/master/LICENSE"] image:https://img.shields.io/badge/godoc-reference-blue.svg[GoDoc,link="https://godoc.org/github.com/gdamore/tcell"] image:http://goreportcard.com/badge/gdamore/tcell[Go Report Card,link="http://goreportcard.com/report/gdamore/tcell"] image:https://img.shields.io/discord/639503822733180969?label=discord[Discord,link="https://discord.gg/urTTxDN"] image:https://codecov.io/gh/gdamore/tcell/branch/master/graph/badge.svg[codecov,link="https://codecov.io/gh/gdamore/tcell"] [cols="2",grid="none"] |=== |_Tcell_ is a _Go_ package that provides a cell based view for text terminals, like _xterm_. It was inspired by _termbox_, but includes many additional improvements. a|[.right] image::logos/tcell.png[float="right"] |=== ## Examples * https://github.com/gdamore/proxima5[proxima5] - space shooter (https://youtu.be/jNxKTCmY_bQ[video]) * https://github.com/gdamore/govisor[govisor] - service management UI (http://2.bp.blogspot.com/--OsvnfzSNow/Vf7aqMw3zXI/AAAAAAAAARo/uOMtOvw4Sbg/s1600/Screen%2BShot%2B2015-09-20%2Bat%2B9.08.41%2BAM.png[screenshot]) * mouse demo - included mouse test (http://2.bp.blogspot.com/-fWvW5opT0es/VhIdItdKqJI/AAAAAAAAATE/7Ojc0L1SpB0/s1600/Screen%2BShot%2B2015-10-04%2Bat%2B11.47.13%2BPM.png[screenshot]) * https://github.com/gdamore/gomatrix[gomatrix] - converted from Termbox * https://github.com/zyedidia/micro/[micro] - lightweight text editor with syntax-highlighting and themes * https://github.com/viktomas/godu[godu] - simple golang utility helping to discover large files/folders. * https://github.com/rivo/tview[tview] - rich interactive widgets for terminal UIs * https://github.com/marcusolsson/tui-go[tui-go] - UI library for terminal apps (_deprecated_) * https://github.com/rgm3/gomandelbrot[gomandelbrot] - Mandelbrot! * https://github.com/senorprogrammer/wtf[WTF]- Personal information dashboard for your terminal * https://github.com/browsh-org/browsh[browsh] - A fully-modern text-based browser, rendering to TTY and browsers (https://www.youtube.com/watch?v=HZq86XfBoRo[video]) * https://github.com/sachaos/go-life[go-life] - Conway's Game of Life. * https://github.com/gcla/gowid[gowid] - compositional widgets for terminal UIs, inspired by urwid * https://termshark.io[termshark] - a terminal UI for tshark, inspired by Wireshark, built on gowid * https://github.com/MichaelS11/go-tetris[go-tetris] - Go Tetris with AI option * https://github.com/junegunn/fzf[fzf] - A command-line fuzzy finder * https://github.com/esimov/ascii-fluid[ascii-fluid] - A terminal based ASCII fluid simulation controlled by webcam * https://gitlab.com/tslocum/cbind[cbind] - Provides key event encoding, decoding and handling * https://github.com/spinzed/tpong[tpong] - The old-school Pong remade in terminal ## Pure Go Terminfo Database _Tcell_ includes a full parser and expander for terminfo capability strings, so that it can avoid hard coding escape strings for formatting. It also favors portability, and includes support for all POSIX systems. The database is also flexible & extensible, and can modified by either running a program to build the entire database, or an entry for just a single terminal. ## More Portable _Tcell_ is portable to a wide variety of systems. _Tcell_ is believed to work with all of the systems officially supported by golang with the exception of nacl (which lacks any kind of a terminal interface). (Plan9 is not supported by _Tcell_, but it is experimental status only in golang.) _Tcell_ is pure Go, without any need for CGO. ## No Async IO _Tcell_ is able to operate without requiring `SIGIO` signals (unlike _termbox_), or asynchronous I/O, and can instead use standard Go file objects and Go routines. This means it should be safe, especially for use with programs that use exec, or otherwise need to manipulate the tty streams. This model is also much closer to idiomatic Go, leading to fewer surprises. ## Rich Unicode & non-Unicode support _Tcell_ includes enhanced support for Unicode, including wide characters and combining characters, provided your terminal can support them. Note that Windows terminals generally don't support the full Unicode repertoire. It will also convert to and from Unicode locales, so that the program can work with UTF-8 internally, and get reasonable output in other locales. _Tcell_ tries hard to convert to native characters on both input and output, and on output _Tcell_ even makes use of the alternate character set to facilitate drawing certain characters. ## More Function Keys _Tcell_ also has richer support for a larger number of special keys that some terminals can send. ## Better Color Handling _Tcell_ will respect your terminal's color space as specified within your terminfo entries, so that for example attempts to emit color sequences on VT100 terminals won't result in unintended consequences. In legacy Windows mode, _Tcell_ supports 16 colors, bold, dim, and reverse, instead of just termbox's 8 colors with reverse. (Note that there is some conflation with bold/dim and colors.) Modern Windows 10 can benefit from much richer colors however. _Tcell_ maps 16 colors down to 8, for terminals that need it. (The upper 8 colors are just brighter versions of the lower 8.) ## Better Mouse Support _Tcell_ supports enhanced mouse tracking mode, so your application can receive regular mouse motion events, and wheel events, if your terminal supports it. (Note: The Windows 10 Terminal application suffers from a flaw in this regard, and does not support mouse interaction. The stock Windows 10 console host fired up with cmd.exe or PowerShell works fine however.) ## _Termbox_ Compatibility A compatibility layer for _termbox_ is provided in the `compat` directory. To use it, try importing `github.com/gdamore/tcell/termbox` instead. Most _termbox-go_ programs will probably work without further modification. ## Working With Unicode Internally Tcell uses UTF-8, just like Go. However, Tcell understands how to convert to and from other character sets, using the capabilities of the `golang.org/x/text/encoding packages`. Your application must supply them, as the full set of the most common ones bloats the program by about 2MB. If you're lazy, and want them all anyway, see the `encoding` sub-directory. ## Wide & Combining Characters The `SetContent()` API takes a primary rune, and an optional list of combining runes. If any of the runes is a wide (East Asian) rune occupying two cells, then the library will skip output from the following cell, but care must be taken in the application to avoid explicitly attempting to set content in the next cell, otherwise the results are undefined. (Normally wide character is displayed, and the other character is not; do not depend on that behavior.) Experience has shown that the vanilla Windows 8 console application does not support any of these characters properly, but at least some options like _ConEmu_ do support Wide characters. ## Colors _Tcell_ assumes the ANSI/XTerm color model, including the 256 color map that XTerm uses when it supports 256 colors. The terminfo guidance will be honored, with respect to the number of colors supported. Also, only terminals which expose ANSI style `setaf` and `setab` will support color; if you have a color terminal that only has `setf` and `setb`, please let me know; it wouldn't be hard to add that if there is need. ## 24-bit Color _Tcell_ _supports true color_! (That is, if your terminal can support it, _Tcell_ can accurately display 24-bit color.) To use 24-bit color, you need to use a terminal that supports it. Modern xterm and similar teminal emulators can support this. As terminfo lacks any way to describe this capability, we fabricate the capability for terminals with names ending in `*-truecolor`. The stock distribution ships with a database that defines `xterm-truecolor`. To try it out, set your `TERM` variable to `xterm-truecolor`. When using TrueColor, programs will display the colors that the programmer intended, overriding any "`themes`" you may have set in your terminal emulator. (For some cases, accurate color fidelity is more important than respecting themes. For other cases, such as typical text apps that only use a few colors, its more desirable to respect the themes that the user has established.) If you find this undesirable, you can either use a `TERM` variable that lacks the `TRUECOLOR` setting, or set `TCELL_TRUECOLOR=disable` in your environment. ## Performance Reasonable attempts have been made to minimize sending data to terminals, avoiding repeated sequences or drawing the same cell on refresh updates. ## Terminfo (Not relevent for Windows users.) The Terminfo implementation operates with two forms of database. The first is the built-in go database, which contains a number of real database entries that are compiled into the program directly. This should minimize calling out to database file searches. The second is in the form of JSON files, that contain the same information, which can be located either by the `$TCELLDB` environment file, `$HOME/.tcelldb`, or is located in the Go source directory as `database.json`. These files (both the Go and the JSON files) can be generated using the mkinfo.go program. If you need to regnerate the entire set for some reason, run the mkdatabase.sh file. The generation uses the infocmp(1) program on the system to collect the necessary information. The `mkinfo.go` program can also be used to generate specific database entries for named terminals, in case your favorite terminal is missing. (If you find that this is the case, please let me know and I'll try to add it!) _Tcell_ requires that the terminal support the `cup` mode of cursor addressing. Terminals without absolute cursor addressability are not supported. This is unlikely to be a problem; such terminals have not been mass produced since the early 1970s. ## Mouse Support Mouse support is detected via the `kmous` terminfo variable, however, enablement/disablement and decoding mouse events is done using hard coded sequences based on the XTerm X11 model. As of this writing all popular terminals with mouse tracking support this model. (Full terminfo support is not possible as terminfo sequences are not defined.) On Windows, the mouse works normally. Mouse wheel buttons on various terminals are known to work, but the support in terminal emulators, as well as support for various buttons and live mouse tracking, varies widely. Modern _xterm_, macOS _Terminal_, and _iTerm_ all work well. ## Testablity There is a `SimulationScreen`, that can be used to simulate a real screen for automated testing. The supplied tests do this. The simulation contains event delivery, screen resizing support, and capabilities to inject events and examine "`physical`" screen contents. ## Platforms ### POSIX (Linux, FreeBSD, macOS, Solaris, etc.) For mainstream systems with a suitably well defined system call interface to tty settings, everything works using pure Go. For the remainder (right now means only Solaris/illumos) we use POSIX function calls to manage termios, which implies that CGO is required on those platforms. ### Windows Windows console mode applications are supported. Unfortunately _mintty_ and other _cygwin_ style applications are not supported. Modern console applications like ConEmu, as well as the Windows 10 console itself, support all the good features (resize, mouse tracking, etc.) I haven't figured out how to cleanly resolve the dichotomy between cygwin style termios and the Windows Console API; it seems that perhaps nobody else has either. If anyone has suggestions, let me know! Really, if you're using a Windows application, you should use the native Windows console or a fully compatible console implementation. ### Plan9 and Native Client (Nacl) The nacl and plan9 platforms won't work, but compilation stubs are supplied for folks that want to include parts of this in software targetting those platforms. The Simulation screen works, but as Tcell doesn't know how to allocate a real screen object on those platforms, `NewScreen()` will fail. If anyone has wisdom about how to improve support for either of these, please let me know. PRs are especially welcome. ### Commercial Support _Tcell_ is absolutely free, but if you want to obtain commercial, professional support, there are options. [cols="2",align="center",frame="none", grid="none"] |=== ^.^| image:logos/tidelift.png[100,100] a| https://tidelift.com/[Tidelift] subscriptions include support for _Tcell_, as well as many other open source packages. ^.^| image:logos/staysail.png[100,100] a| mailto:<EMAIL>[Staysail Systems, Inc.] offers direct support, and custom development around _Tcell_ on an hourly basis. ^.^| image:logos/patreon.png[100,100] a|I also welcome donations at https://www.patreon.com/gedamore/[Patreon], if you just want to make a contribution. |=== ``` Documentation [¶](#section-documentation) --- [Rendered for](https://go.dev/about#build-context) linux/amd64 windows/amd64 darwin/amd64 js/wasm ### Overview [¶](#pkg-overview) Package tcell provides a lower-level, portable API for building programs that interact with terminals or consoles. It works with both common (and many uncommon!) terminals or terminal emulators, and Windows console implementations. It provides support for up to 256 colors, text attributes, and box drawing elements. A database of terminals built from a real terminfo database is provided, along with code to generate new database entries. Tcell offers very rich support for mice, dependent upon the terminal of course. (Windows, XTerm, and iTerm 2 are known to work very well.) If the environment is not Unicode by default, such as an ISO8859 based locale or GB18030, Tcell can convert input and output, so that your terminal can operate in whatever locale is most convenient, while the application program can just assume "everything is UTF-8". Reasonable defaults are used for updating characters to something suitable for display. Unicode box drawing characters will be converted to use the alternate character set of your terminal, if native conversions are not available. If no ACS is available, then some ASCII fallbacks will be used. Note that support for non-UTF-8 locales (other than C) must be enabled by the application using RegisterEncoding() -- we don't have them all enabled by default to avoid bloating the application unneccessarily. (These days UTF-8 is good enough for almost everyone, and nobody should be using legacy locales anymore.) Also, actual glyphs for various code point will only be displayed if your terminal or emulator (or the font the emulator is using) supports them. A rich set of keycodes is supported, with support for up to 65 function keys, and various other special keys. ### Index [¶](#pkg-index) * [Constants](#pkg-constants) * [Variables](#pkg-variables) * [func GetEncoding(charset string) encoding.Encoding](#GetEncoding) * [func RegisterEncoding(charset string, enc encoding.Encoding)](#RegisterEncoding) * [func SetEncodingFallback(fb EncodingFallback)](#SetEncodingFallback) * [type AttrMask](#AttrMask) * [type ButtonMask](#ButtonMask) * [type CellBuffer](#CellBuffer) * + [func (cb *CellBuffer) Dirty(x, y int) bool](#CellBuffer.Dirty) + [func (cb *CellBuffer) Fill(r rune, style Style)](#CellBuffer.Fill) + [func (cb *CellBuffer) GetContent(x, y int) (rune, []rune, Style, int)](#CellBuffer.GetContent) + [func (cb *CellBuffer) Invalidate()](#CellBuffer.Invalidate) + [func (cb *CellBuffer) Resize(w, h int)](#CellBuffer.Resize) + [func (cb *CellBuffer) SetContent(x int, y int, mainc rune, combc []rune, style Style)](#CellBuffer.SetContent) + [func (cb *CellBuffer) SetDirty(x, y int, dirty bool)](#CellBuffer.SetDirty) + [func (cb *CellBuffer) Size() (int, int)](#CellBuffer.Size) * [type Color](#Color) * + [func FindColor(c Color, palette []Color) Color](#FindColor) + [func GetColor(name string) Color](#GetColor) + [func NewHexColor(v int32) Color](#NewHexColor) + [func NewRGBColor(r, g, b int32) Color](#NewRGBColor) * + [func (c Color) Hex() int32](#Color.Hex) + [func (c Color) RGB() (int32, int32, int32)](#Color.RGB) * [type EncodingFallback](#EncodingFallback) * [type Event](#Event) * [type EventError](#EventError) * + [func NewEventError(err error) *EventError](#NewEventError) * + [func (ev *EventError) Error() string](#EventError.Error) + [func (ev *EventError) When() time.Time](#EventError.When) * [type EventHandler](#EventHandler) * [type EventInterrupt](#EventInterrupt) * + [func NewEventInterrupt(data interface{}) *EventInterrupt](#NewEventInterrupt) * + [func (ev *EventInterrupt) Data() interface{}](#EventInterrupt.Data) + [func (ev *EventInterrupt) When() time.Time](#EventInterrupt.When) * [type EventKey](#EventKey) * + [func NewEventKey(k Key, ch rune, mod ModMask) *EventKey](#NewEventKey) * + [func (ev *EventKey) Key() Key](#EventKey.Key) + [func (ev *EventKey) Modifiers() ModMask](#EventKey.Modifiers) + [func (ev *EventKey) Name() string](#EventKey.Name) + [func (ev *EventKey) Rune() rune](#EventKey.Rune) + [func (ev *EventKey) When() time.Time](#EventKey.When) * [type EventMouse](#EventMouse) * + [func NewEventMouse(x, y int, btn ButtonMask, mod ModMask) *EventMouse](#NewEventMouse) * + [func (ev *EventMouse) Buttons() ButtonMask](#EventMouse.Buttons) + [func (ev *EventMouse) Modifiers() ModMask](#EventMouse.Modifiers) + [func (ev *EventMouse) Position() (int, int)](#EventMouse.Position) + [func (ev *EventMouse) When() time.Time](#EventMouse.When) * [type EventResize](#EventResize) * + [func NewEventResize(width, height int) *EventResize](#NewEventResize) * + [func (ev *EventResize) Size() (int, int)](#EventResize.Size) + [func (ev *EventResize) When() time.Time](#EventResize.When) * [type EventTime](#EventTime) * + [func (e *EventTime) SetEventNow()](#EventTime.SetEventNow) + [func (e *EventTime) SetEventTime(t time.Time)](#EventTime.SetEventTime) + [func (e *EventTime) When() time.Time](#EventTime.When) * [type Key](#Key) * [type ModMask](#ModMask) * [type Screen](#Screen) * + [func NewConsoleScreen() (Screen, error)](#NewConsoleScreen) + [func NewScreen() (Screen, error)](#NewScreen) + [func NewTerminfoScreen() (Screen, error)](#NewTerminfoScreen) * [type SimCell](#SimCell) * [type SimulationScreen](#SimulationScreen) * + [func NewSimulationScreen(charset string) SimulationScreen](#NewSimulationScreen) * [type Style](#Style) * + [func (s Style) Background(c Color) Style](#Style.Background) + [func (s Style) Blink(on bool) Style](#Style.Blink) + [func (s Style) Bold(on bool) Style](#Style.Bold) + [func (s Style) Decompose() (fg Color, bg Color, attr AttrMask)](#Style.Decompose) + [func (s Style) Dim(on bool) Style](#Style.Dim) + [func (s Style) Foreground(c Color) Style](#Style.Foreground) + [func (s Style) Italic(on bool) Style](#Style.Italic) + [func (s Style) Normal() Style](#Style.Normal) + [func (s Style) Reverse(on bool) Style](#Style.Reverse) + [func (s Style) Underline(on bool) Style](#Style.Underline) ### Constants [¶](#pkg-constants) ``` const ( ColorGrey = [ColorGray](#ColorGray) ColorDimGrey = [ColorDimGray](#ColorDimGray) ColorDarkGrey = [ColorDarkGray](#ColorDarkGray) ColorDarkSlateGrey = [ColorDarkSlateGray](#ColorDarkSlateGray) ColorLightGrey = [ColorLightGray](#ColorLightGray) ColorLightSlateGrey = [ColorLightSlateGray](#ColorLightSlateGray) ColorSlateGrey = [ColorSlateGray](#ColorSlateGray) ) ``` These are aliases for the color gray, because some of us spell it as grey. ``` const ( // EncodingFallbackFail behavior causes GetEncoding to fail // when it cannot find an encoding. EncodingFallbackFail = [iota](/builtin#iota) // EncodingFallbackASCII behaviore causes GetEncoding to fall back // to a 7-bit ASCII encoding, if no other encoding can be found. EncodingFallbackASCII // EncodingFallbackUTF8 behavior causes GetEncoding to assume // UTF8 can pass unmodified upon failure. Note that this behavior // is not recommended, unless you are sure your terminal can cope // with real UTF8 sequences. EncodingFallbackUTF8 ) ``` ``` const ( KeyBackspace = [KeyBS](#KeyBS) KeyTab = [KeyTAB](#KeyTAB) KeyEsc = [KeyESC](#KeyESC) KeyEscape = [KeyESC](#KeyESC) KeyEnter = [KeyCR](#KeyCR) KeyBackspace2 = [KeyDEL](#KeyDEL) ) ``` These keys are aliases for other names. ``` const ( RuneSterling = '£' RuneDArrow = '↓' RuneLArrow = '←' RuneRArrow = '→' RuneUArrow = '↑' RuneBullet = '·' RuneBoard = '░' RuneCkBoard = '▒' RuneDegree = '°' RuneDiamond = '◆' RuneGEqual = '≥' RunePi = 'π' RuneHLine = '─' RuneLantern = '§' RunePlus = '┼' RuneLEqual = '≤' RuneLLCorner = '└' RuneLRCorner = '┘' RuneNEqual = '≠' RunePlMinus = '±' RuneS1 = '⎺' RuneS3 = '⎻' RuneS7 = '⎼' RuneS9 = '⎽' RuneBlock = '█' RuneTTee = '┬' RuneRTee = '┤' RuneLTee = '├' RuneBTee = '┴' RuneULCorner = '┌' RuneURCorner = '┐' RuneVLine = '│' ) ``` The names of these constants are chosen to match Terminfo names, modulo case, and changing the prefix from ACS_ to Rune. These are the runes we provide extra special handling for, with ASCII fallbacks for terminals that lack them. ### Variables [¶](#pkg-variables) ``` var ( // ErrTermNotFound indicates that a suitable terminal entry could // not be found. This can result from either not having TERM set, // or from the TERM failing to support certain minimal functionality, // in particular absolute cursor addressability (the cup capability) // is required. For example, legacy "adm3" lacks this capability, // whereas the slightly newer "adm3a" supports it. This failure // occurs most often with "dumb". ErrTermNotFound = [terminfo](/github.com/gdamore/tcell@v1.4.0/terminfo).[ErrTermNotFound](/github.com/gdamore/tcell@v1.4.0/terminfo#ErrTermNotFound) // ErrNoScreen indicates that no suitable screen could be found. // This may result from attempting to run on a platform where there // is no support for either termios or console I/O (such as nacl), // or from running in an environment where there is no access to // a suitable console/terminal device. (For example, running on // without a controlling TTY or with no /dev/tty on POSIX platforms.) ErrNoScreen = [errors](/errors).[New](/errors#New)("no suitable screen available") // ErrNoCharset indicates that the locale environment the // program is not supported by the program, because no suitable // encoding was found for it. This problem never occurs if // the environment is UTF-8 or UTF-16. ErrNoCharset = [errors](/errors).[New](/errors#New)("character set not supported") // ErrEventQFull indicates that the event queue is full, and // cannot accept more events. ErrEventQFull = [errors](/errors).[New](/errors#New)("event queue full") ) ``` ``` var ColorNames = map[[string](/builtin#string)][Color](#Color){}/* 146 elements not displayed */ ``` ColorNames holds the written names of colors. Useful to present a list of recognized named colors. ``` var ColorValues = map[[Color](#Color)][int32](/builtin#int32){}/* 379 elements not displayed */ ``` ColorValues maps color constants to their RGB values. ``` var KeyNames = map[[Key](#Key)][string](/builtin#string){}/* 118 elements not displayed */ ``` KeyNames holds the written names of special keys. Useful to echo back a key name, or to look up a key from a string value. ``` var RuneFallbacks = map[[rune](/builtin#rune)][string](/builtin#string){ [RuneSterling](#RuneSterling): "f", [RuneDArrow](#RuneDArrow): "v", [RuneLArrow](#RuneLArrow): "<", [RuneRArrow](#RuneRArrow): ">", [RuneUArrow](#RuneUArrow): "^", [RuneBullet](#RuneBullet): "o", [RuneBoard](#RuneBoard): "#", [RuneCkBoard](#RuneCkBoard): ":", [RuneDegree](#RuneDegree): "\\", [RuneDiamond](#RuneDiamond): "+", [RuneGEqual](#RuneGEqual): ">", [RunePi](#RunePi): "*", [RuneHLine](#RuneHLine): "-", [RuneLantern](#RuneLantern): "#", [RunePlus](#RunePlus): "+", [RuneLEqual](#RuneLEqual): "<", [RuneLLCorner](#RuneLLCorner): "+", [RuneLRCorner](#RuneLRCorner): "+", [RuneNEqual](#RuneNEqual): "!", [RunePlMinus](#RunePlMinus): "#", [RuneS1](#RuneS1): "~", [RuneS3](#RuneS3): "-", [RuneS7](#RuneS7): "-", [RuneS9](#RuneS9): "_", [RuneBlock](#RuneBlock): "#", [RuneTTee](#RuneTTee): "+", [RuneRTee](#RuneRTee): "+", [RuneLTee](#RuneLTee): "+", [RuneBTee](#RuneBTee): "+", [RuneULCorner](#RuneULCorner): "+", [RuneURCorner](#RuneURCorner): "+", [RuneVLine](#RuneVLine): "|", } ``` RuneFallbacks is the default map of fallback strings that will be used to replace a rune when no other more appropriate transformation is available, and the rune cannot be displayed directly. New entries may be added to this map over time, as it becomes clear that such is desirable. Characters that represent either letters or numbers should not be added to this list unless it is certain that the meaning will still convey unambiguously. As an example, it would be appropriate to add an ASCII mapping for the full width form of the letter 'A', but it would not be appropriate to do so a glyph representing the country China. Programs that desire richer fallbacks may register additional ones, or change or even remove these mappings with Screen.RegisterRuneFallback Screen.UnregisterRuneFallback methods. Note that Unicode is presumed to be able to display all glyphs. This is a pretty poor assumption, but there is no easy way to figure out which glyphs are supported in a given font. Hence, some care in selecting the characters you support in your application is still appropriate. ### Functions [¶](#pkg-functions) #### func [GetEncoding](https://github.com/gdamore/tcell/blob/v1.4.0/encoding.go#L115) [¶](#GetEncoding) ``` func GetEncoding(charset [string](/builtin#string)) [encoding](/golang.org/x/text/encoding).[Encoding](/golang.org/x/text/encoding#Encoding) ``` GetEncoding is used by Screen implementors who want to locate an encoding for the given character set name. Note that this will return nil for either the Unicode (UTF-8) or ASCII encodings, since we don't use encodings for them but instead have our own native methods. #### func [RegisterEncoding](https://github.com/gdamore/tcell/blob/v1.4.0/encoding.go#L71) [¶](#RegisterEncoding) ``` func RegisterEncoding(charset [string](/builtin#string), enc [encoding](/golang.org/x/text/encoding).[Encoding](/golang.org/x/text/encoding#Encoding)) ``` RegisterEncoding may be called by the application to register an encoding. The presence of additional encodings will facilitate application usage with terminal environments where the I/O subsystem does not support Unicode. Windows systems use Unicode natively, and do not need any of the encoding subsystem when using Windows Console screens. Please see the Go documentation for golang.org/x/text/encoding -- most of the common ones exist already as stock variables. For example, ISO8859-15 can be registered using the following code: ``` import "golang.org/x/text/encoding/charmap" ... RegisterEncoding("ISO8859-15", charmap.ISO8859_15) ``` Aliases can be registered as well, for example "8859-15" could be an alias for "ISO8859-15". For POSIX systems, the tcell package will check the environment variables LC_ALL, LC_CTYPE, and LANG (in that order) to determine the character set. These are expected to have the following pattern: ``` $language[.$codeset[@$variant] ``` We extract only the $codeset part, which will usually be something like UTF-8 or ISO8859-15 or KOI8-R. Note that if the locale is either "POSIX" or "C", then we assume US-ASCII (the POSIX 'portable character set' and assume all other characters are somehow invalid.) Modern POSIX systems and terminal emulators may use UTF-8, and for those systems, this API is also unnecessary. For example, Darwin (MacOS X) and modern Linux running modern xterm generally will out of the box without any of this. Use of UTF-8 is recommended when possible, as it saves quite a lot processing overhead. Note that some encodings are quite large (for example GB18030 which is a superset of Unicode) and so the application size can be expected ot increase quite a bit as each encoding is added. The East Asian encodings have been seen to add 100-200K per encoding to the application size. #### func [SetEncodingFallback](https://github.com/gdamore/tcell/blob/v1.4.0/encoding.go#L105) [¶](#SetEncodingFallback) ``` func SetEncodingFallback(fb [EncodingFallback](#EncodingFallback)) ``` SetEncodingFallback changes the behavior of GetEncoding when a suitable encoding is not found. The default is EncodingFallbackFail, which causes GetEncoding to simply return nil. ### Types [¶](#pkg-types) #### type [AttrMask](https://github.com/gdamore/tcell/blob/v1.4.0/attr.go#L19) [¶](#AttrMask) ``` type AttrMask [int](/builtin#int) ``` AttrMask represents a mask of text attributes, apart from color. Note that support for attributes may vary widely across terminals. ``` const ( AttrBold [AttrMask](#AttrMask) = 1 << (25 + [iota](/builtin#iota)) AttrBlink AttrReverse AttrUnderline AttrDim AttrItalic AttrNone [AttrMask](#AttrMask) = 0 // Just normal text. ) ``` Attributes are not colors, but affect the display of text. They can be combined. #### type [ButtonMask](https://github.com/gdamore/tcell/blob/v1.4.0/mouse.go#L80) [¶](#ButtonMask) ``` type ButtonMask [int16](/builtin#int16) ``` ButtonMask is a mask of mouse buttons and wheel events. Mouse button presses are normally delivered as both press and release events. Mouse wheel events are normally just single impulse events. Windows supports up to eight separate buttons plus all four wheel directions, but XTerm can only support mouse buttons 1-3 and wheel up/down. Its not unheard of for terminals to support only one or two buttons (think Macs). Old terminals, and true emulations (such as vt100) won't support mice at all, of course. ``` const ( Button1 [ButtonMask](#ButtonMask) = 1 << [iota](/builtin#iota) // Usually left mouse button. Button2 // Usually the middle mouse button. Button3 // Usually the right mouse button. Button4 // Often a side button (thumb/next). Button5 // Often a side button (thumb/prev). Button6 Button7 Button8 WheelUp // Wheel motion up/away from user. WheelDown // Wheel motion down/towards user. WheelLeft // Wheel motion to left. WheelRight // Wheel motion to right. ButtonNone [ButtonMask](#ButtonMask) = 0 // No button or wheel events. ) ``` These are the actual button values. #### type [CellBuffer](https://github.com/gdamore/tcell/blob/v1.4.0/cell.go#L37) [¶](#CellBuffer) ``` type CellBuffer struct { // contains filtered or unexported fields } ``` CellBuffer represents a two dimensional array of character cells. This is primarily intended for use by Screen implementors; it contains much of the common code they need. To create one, just declare a variable of its type; no explicit initialization is necessary. CellBuffer is not thread safe. #### func (*CellBuffer) [Dirty](https://github.com/gdamore/tcell/blob/v1.4.0/cell.go#L97) [¶](#CellBuffer.Dirty) ``` func (cb *[CellBuffer](#CellBuffer)) Dirty(x, y [int](/builtin#int)) [bool](/builtin#bool) ``` Dirty checks if a character at the given location needs an to be refreshed on the physical display. This returns true if the cell content is different since the last time it was marked clean. #### func (*CellBuffer) [Fill](https://github.com/gdamore/tcell/blob/v1.4.0/cell.go#L169) [¶](#CellBuffer.Fill) ``` func (cb *[CellBuffer](#CellBuffer)) Fill(r [rune](/builtin#rune), style [Style](#Style)) ``` Fill fills the entire cell buffer array with the specified character and style. Normally choose ' ' to clear the screen. This API doesn't support combining characters, or characters with a width larger than one. #### func (*CellBuffer) [GetContent](https://github.com/gdamore/tcell/blob/v1.4.0/cell.go#L65) [¶](#CellBuffer.GetContent) ``` func (cb *[CellBuffer](#CellBuffer)) GetContent(x, y [int](/builtin#int)) ([rune](/builtin#rune), [][rune](/builtin#rune), [Style](#Style), [int](/builtin#int)) ``` GetContent returns the contents of a character cell, including the primary rune, any combining character runes (which will usually be nil), the style, and the display width in cells. (The width can be either 1, normally, or 2 for East Asian full-width characters.) #### func (*CellBuffer) [Invalidate](https://github.com/gdamore/tcell/blob/v1.4.0/cell.go#L87) [¶](#CellBuffer.Invalidate) ``` func (cb *[CellBuffer](#CellBuffer)) Invalidate() ``` Invalidate marks all characters within the buffer as dirty. #### func (*CellBuffer) [Resize](https://github.com/gdamore/tcell/blob/v1.4.0/cell.go#L143) [¶](#CellBuffer.Resize) ``` func (cb *[CellBuffer](#CellBuffer)) Resize(w, h [int](/builtin#int)) ``` Resize is used to resize the cells array, with different dimensions, while preserving the original contents. The cells will be invalidated so that they can be redrawn. #### func (*CellBuffer) [SetContent](https://github.com/gdamore/tcell/blob/v1.4.0/cell.go#L45) [¶](#CellBuffer.SetContent) ``` func (cb *[CellBuffer](#CellBuffer)) SetContent(x [int](/builtin#int), y [int](/builtin#int), mainc [rune](/builtin#rune), combc [][rune](/builtin#rune), style [Style](#Style)) ``` SetContent sets the contents (primary rune, combining runes, and style) for a cell at a given location. #### func (*CellBuffer) [SetDirty](https://github.com/gdamore/tcell/blob/v1.4.0/cell.go#L124) [¶](#CellBuffer.SetDirty) ``` func (cb *[CellBuffer](#CellBuffer)) SetDirty(x, y [int](/builtin#int), dirty [bool](/builtin#bool)) ``` SetDirty is normally used to indicate that a cell has been displayed (in which case dirty is false), or to manually force a cell to be marked dirty. #### func (*CellBuffer) [Size](https://github.com/gdamore/tcell/blob/v1.4.0/cell.go#L82) [¶](#CellBuffer.Size) ``` func (cb *[CellBuffer](#CellBuffer)) Size() ([int](/builtin#int), [int](/builtin#int)) ``` Size returns the (width, height) in cells of the buffer. #### type [Color](https://github.com/gdamore/tcell/blob/v1.4.0/color.go#L28) [¶](#Color) ``` type Color [int32](/builtin#int32) ``` Color represents a color. The low numeric values are the same as used by ECMA-48, and beyond that XTerm. A 24-bit RGB value may be used by adding in the ColorIsRGB flag. For Color names we use the W3C approved color names. Note that on various terminals colors may be approximated however, or not supported at all. If no suitable representation for a color is known, the library will simply not set any color, deferring to whatever default attributes the terminal uses. ``` const ( // ColorDefault is used to leave the Color unchanged from whatever // system or teminal default may exist. ColorDefault [Color](#Color) = -1 // ColorIsRGB is used to indicate that the numeric value is not // a known color constant, but rather an RGB value. The lower // order 3 bytes are RGB. ColorIsRGB [Color](#Color) = 1 << 24 ) ``` ``` const ( ColorBlack [Color](#Color) = [iota](/builtin#iota) ColorMaroon ColorGreen ColorOlive ColorNavy ColorPurple ColorTeal ColorSilver ColorGray ColorRed ColorLime ColorYellow ColorBlue ColorFuchsia ColorAqua ColorWhite Color16 Color17 Color18 Color19 Color20 Color21 Color22 Color23 Color24 Color25 Color26 Color27 Color28 Color29 Color30 Color31 Color32 Color33 Color34 Color35 Color36 Color37 Color38 Color39 Color40 Color41 Color42 Color43 Color44 Color45 Color46 Color47 Color48 Color49 Color50 Color51 Color52 Color53 Color54 Color55 Color56 Color57 Color58 Color59 Color60 Color61 Color62 Color63 Color64 Color65 Color66 Color67 Color68 Color69 Color70 Color71 Color72 Color73 Color74 Color75 Color76 Color77 Color78 Color79 Color80 Color81 Color82 Color83 Color84 Color85 Color86 Color87 Color88 Color89 Color90 Color91 Color92 Color93 Color94 Color95 Color96 Color97 Color98 Color99 Color100 Color101 Color102 Color103 Color104 Color105 Color106 Color107 Color108 Color109 Color110 Color111 Color112 Color113 Color114 Color115 Color116 Color117 Color118 Color119 Color120 Color121 Color122 Color123 Color124 Color125 Color126 Color127 Color128 Color129 Color130 Color131 Color132 Color133 Color134 Color135 Color136 Color137 Color138 Color139 Color140 Color141 Color142 Color143 Color144 Color145 Color146 Color147 Color148 Color149 Color150 Color151 Color152 Color153 Color154 Color155 Color156 Color157 Color158 Color159 Color160 Color161 Color162 Color163 Color164 Color165 Color166 Color167 Color168 Color169 Color170 Color171 Color172 Color173 Color174 Color175 Color176 Color177 Color178 Color179 Color180 Color181 Color182 Color183 Color184 Color185 Color186 Color187 Color188 Color189 Color190 Color191 Color192 Color193 Color194 Color195 Color196 Color197 Color198 Color199 Color200 Color201 Color202 Color203 Color204 Color205 Color206 Color207 Color208 Color209 Color210 Color211 Color212 Color213 Color214 Color215 Color216 Color217 Color218 Color219 Color220 Color221 Color222 Color223 Color224 Color225 Color226 Color227 Color228 Color229 Color230 Color231 Color232 Color233 Color234 Color235 Color236 Color237 Color238 Color239 Color240 Color241 Color242 Color243 Color244 Color245 Color246 Color247 Color248 Color249 Color250 Color251 Color252 Color253 Color254 Color255 ColorAliceBlue ColorAntiqueWhite ColorAquaMarine ColorAzure ColorBeige ColorBisque ColorBlanchedAlmond ColorBlueViolet ColorBrown ColorBurlyWood ColorCadetBlue ColorChartreuse ColorChocolate ColorCoral ColorCornflowerBlue ColorCornsilk ColorCrimson ColorDarkBlue ColorDarkCyan ColorDarkGoldenrod ColorDarkGray ColorDarkGreen ColorDarkKhaki ColorDarkMagenta ColorDarkOliveGreen ColorDarkOrange ColorDarkOrchid ColorDarkRed ColorDarkSalmon ColorDarkSeaGreen ColorDarkSlateBlue ColorDarkSlateGray ColorDarkTurquoise ColorDarkViolet ColorDeepPink ColorDeepSkyBlue ColorDimGray ColorDodgerBlue ColorFireBrick ColorFloralWhite ColorForestGreen ColorGainsboro ColorGhostWhite ColorGold ColorGoldenrod ColorGreenYellow ColorHoneydew ColorHotPink ColorIndianRed ColorIndigo ColorIvory ColorKhaki ColorLavender ColorLavenderBlush ColorLawnGreen ColorLemonChiffon ColorLightBlue ColorLightCoral ColorLightCyan ColorLightGoldenrodYellow ColorLightGray ColorLightGreen ColorLightPink ColorLightSalmon ColorLightSeaGreen ColorLightSkyBlue ColorLightSlateGray ColorLightSteelBlue ColorLightYellow ColorLimeGreen ColorLinen ColorMediumAquamarine ColorMediumBlue ColorMediumOrchid ColorMediumPurple ColorMediumSeaGreen ColorMediumSlateBlue ColorMediumSpringGreen ColorMediumTurquoise ColorMediumVioletRed ColorMidnightBlue ColorMintCream ColorMistyRose ColorMoccasin ColorNavajoWhite ColorOldLace ColorOliveDrab ColorOrange ColorOrangeRed ColorOrchid ColorPaleGoldenrod ColorPaleGreen ColorPaleTurquoise ColorPaleVioletRed ColorPapayaWhip ColorPeachPuff ColorPeru ColorPink ColorPlum ColorPowderBlue ColorRebeccaPurple ColorRosyBrown ColorRoyalBlue ColorSaddleBrown ColorSalmon ColorSandyBrown ColorSeaGreen ColorSeashell ColorSienna ColorSkyblue ColorSlateBlue ColorSlateGray ColorSnow ColorSpringGreen ColorSteelBlue ColorTan ColorThistle ColorTomato ColorTurquoise ColorViolet ColorWheat ColorWhiteSmoke ColorYellowGreen ) ``` Note that the order of these options is important -- it follows the definitions used by ECMA and XTerm. Hence any further named colors must begin at a value not less than 256. #### func [FindColor](https://github.com/gdamore/tcell/blob/v1.4.0/colorfit.go#L25) [¶](#FindColor) ``` func FindColor(c [Color](#Color), palette [][Color](#Color)) [Color](#Color) ``` FindColor attempts to find a given color, or the best match possible for it, from the palette given. This is an expensive operation, so results should be cached by the caller. #### func [GetColor](https://github.com/gdamore/tcell/blob/v1.4.0/color.go#L1009) [¶](#GetColor) ``` func GetColor(name [string](/builtin#string)) [Color](#Color) ``` GetColor creates a Color from a color name (W3C name). A hex value may be supplied as a string in the format "#ffffff". #### func [NewHexColor](https://github.com/gdamore/tcell/blob/v1.4.0/color.go#L1003) [¶](#NewHexColor) ``` func NewHexColor(v [int32](/builtin#int32)) [Color](#Color) ``` NewHexColor returns a color using the given 24-bit RGB value. #### func [NewRGBColor](https://github.com/gdamore/tcell/blob/v1.4.0/color.go#L998) [¶](#NewRGBColor) ``` func NewRGBColor(r, g, b [int32](/builtin#int32)) [Color](#Color) ``` NewRGBColor returns a new color with the given red, green, and blue values. Each value must be represented in the range 0-255. #### func (Color) [Hex](https://github.com/gdamore/tcell/blob/v1.4.0/color.go#L975) [¶](#Color.Hex) ``` func (c [Color](#Color)) Hex() [int32](/builtin#int32) ``` Hex returns the color's hexadecimal RGB 24-bit value with each component consisting of a single byte, ala R << 16 | G << 8 | B. If the color is unknown or unset, -1 is returned. #### func (Color) [RGB](https://github.com/gdamore/tcell/blob/v1.4.0/color.go#L988) [¶](#Color.RGB) ``` func (c [Color](#Color)) RGB() ([int32](/builtin#int32), [int32](/builtin#int32), [int32](/builtin#int32)) ``` RGB returns the red, green, and blue components of the color, with each component represented as a value 0-255. In the event that the color cannot be broken up (not set usually), -1 is returned for each value. #### type [EncodingFallback](https://github.com/gdamore/tcell/blob/v1.4.0/encoding.go#L84) [¶](#EncodingFallback) ``` type EncodingFallback [int](/builtin#int) ``` EncodingFallback describes how the system behavees when the locale requires a character set that we do not support. The system always supports UTF-8 and US-ASCII. On Windows consoles, UTF-16LE is also supported automatically. Other character sets must be added using the RegisterEncoding API. (A large group of nearly all of them can be added using the RegisterAll function in the encoding sub package.) #### type [Event](https://github.com/gdamore/tcell/blob/v1.4.0/event.go#L23) [¶](#Event) ``` type Event interface { // When reports the time when the event was generated. When() [time](/time).[Time](/time#Time) } ``` Event is a generic interface used for passing around Events. Concrete types follow. #### type [EventError](https://github.com/gdamore/tcell/blob/v1.4.0/errors.go#L55) [¶](#EventError) ``` type EventError struct { // contains filtered or unexported fields } ``` An EventError is an event representing some sort of error, and carries an error payload. #### func [NewEventError](https://github.com/gdamore/tcell/blob/v1.4.0/errors.go#L71) [¶](#NewEventError) ``` func NewEventError(err [error](/builtin#error)) *[EventError](#EventError) ``` NewEventError creates an ErrorEvent with the given error payload. #### func (*EventError) [Error](https://github.com/gdamore/tcell/blob/v1.4.0/errors.go#L66) [¶](#EventError.Error) ``` func (ev *[EventError](#EventError)) Error() [string](/builtin#string) ``` Error implements the error. #### func (*EventError) [When](https://github.com/gdamore/tcell/blob/v1.4.0/errors.go#L61) [¶](#EventError.When) ``` func (ev *[EventError](#EventError)) When() [time](/time).[Time](/time#Time) ``` When returns the time when the event was created. #### type [EventHandler](https://github.com/gdamore/tcell/blob/v1.4.0/event.go#L51) [¶](#EventHandler) ``` type EventHandler interface { HandleEvent([Event](#Event)) [bool](/builtin#bool) } ``` EventHandler is anything that handles events. If the handler has consumed the event, it should return true. False otherwise. #### type [EventInterrupt](https://github.com/gdamore/tcell/blob/v1.4.0/interrupt.go#L23) [¶](#EventInterrupt) ``` type EventInterrupt struct { // contains filtered or unexported fields } ``` EventInterrupt is a generic wakeup event. Its can be used to to request a redraw. It can carry an arbitrary payload, as well. #### func [NewEventInterrupt](https://github.com/gdamore/tcell/blob/v1.4.0/interrupt.go#L39) [¶](#NewEventInterrupt) ``` func NewEventInterrupt(data interface{}) *[EventInterrupt](#EventInterrupt) ``` NewEventInterrupt creates an EventInterrupt with the given payload. #### func (*EventInterrupt) [Data](https://github.com/gdamore/tcell/blob/v1.4.0/interrupt.go#L34) [¶](#EventInterrupt.Data) ``` func (ev *[EventInterrupt](#EventInterrupt)) Data() interface{} ``` Data is used to obtain the opaque event payload. #### func (*EventInterrupt) [When](https://github.com/gdamore/tcell/blob/v1.4.0/interrupt.go#L29) [¶](#EventInterrupt.When) ``` func (ev *[EventInterrupt](#EventInterrupt)) When() [time](/time).[Time](/time#Time) ``` When returns the time when this event was created. #### type [EventKey](https://github.com/gdamore/tcell/blob/v1.4.0/key.go#L45) [¶](#EventKey) ``` type EventKey struct { // contains filtered or unexported fields } ``` EventKey represents a key press. Usually this is a key press followed by a key release, but since terminal programs don't have a way to report key release events, we usually get just one event. If a key is held down then the terminal may synthesize repeated key presses at some predefined rate. We have no control over that, nor visibility into it. In some cases, we can have a modifier key, such as ModAlt, that can be generated with a key press. (This usually is represented by having the high bit set, or in some cases, by sending an ESC prior to the rune.) If the value of Key() is KeyRune, then the actual key value will be available with the Rune() method. This will be the case for most keys. In most situations, the modifiers will not be set. For example, if the rune is 'A', this will be reported without the ModShift bit set, since really can't tell if the Shift key was pressed (it might have been CAPSLOCK, or a terminal that only can send capitals, or keyboard with separate capital letters from lower case letters). Generally, terminal applications have far less visibility into keyboard activity than graphical applications. Hence, they should avoid depending overly much on availability of modifiers, or the availability of any specific keys. #### func [NewEventKey](https://github.com/gdamore/tcell/blob/v1.4.0/key.go#L243) [¶](#NewEventKey) ``` func NewEventKey(k [Key](#Key), ch [rune](/builtin#rune), mod [ModMask](#ModMask)) *[EventKey](#EventKey) ``` NewEventKey attempts to create a suitable event. It parses the various ASCII control sequences if KeyRune is passed for Key, but if the caller has more precise information it should set that specifically. Callers that aren't sure about modifier state (most) should just pass ModNone. #### func (*EventKey) [Key](https://github.com/gdamore/tcell/blob/v1.4.0/key.go#L69) [¶](#EventKey.Key) ``` func (ev *[EventKey](#EventKey)) Key() [Key](#Key) ``` Key returns a virtual key code. We use this to identify specific key codes, such as KeyEnter, etc. Most control and function keys are reported with unique Key values. Normal alphanumeric and punctuation keys will generally return KeyRune here; the specific key can be further decoded using the Rune() function. #### func (*EventKey) [Modifiers](https://github.com/gdamore/tcell/blob/v1.4.0/key.go#L77) [¶](#EventKey.Modifiers) ``` func (ev *[EventKey](#EventKey)) Modifiers() [ModMask](#ModMask) ``` Modifiers returns the modifiers that were present with the key press. Note that not all platforms and terminals support this equally well, and some cases we will not not know for sure. Hence, applications should avoid using this in most circumstances. #### func (*EventKey) [Name](https://github.com/gdamore/tcell/blob/v1.4.0/key.go#L206) [¶](#EventKey.Name) ``` func (ev *[EventKey](#EventKey)) Name() [string](/builtin#string) ``` Name returns a printable value or the key stroke. This can be used when printing the event, for example. #### func (*EventKey) [Rune](https://github.com/gdamore/tcell/blob/v1.4.0/key.go#L60) [¶](#EventKey.Rune) ``` func (ev *[EventKey](#EventKey)) Rune() [rune](/builtin#rune) ``` Rune returns the rune corresponding to the key press, if it makes sense. The result is only defined if the value of Key() is KeyRune. #### func (*EventKey) [When](https://github.com/gdamore/tcell/blob/v1.4.0/key.go#L54) [¶](#EventKey.When) ``` func (ev *[EventKey](#EventKey)) When() [time](/time).[Time](/time#Time) ``` When returns the time when this Event was created, which should closely match the time when the key was pressed. #### type [EventMouse](https://github.com/gdamore/tcell/blob/v1.4.0/mouse.go#L37) [¶](#EventMouse) ``` type EventMouse struct { // contains filtered or unexported fields } ``` EventMouse is a mouse event. It is sent on either mouse up or mouse down events. It is also sent on mouse motion events - if the terminal supports it. We make every effort to ensure that mouse release events are delivered. Hence, click drag can be identified by a motion event with the mouse down, without any intervening button release. On some terminals only the initiating press and terminating release event will be delivered. Mouse wheel events, when reported, may appear on their own as individual impulses; that is, there will normally not be a release event delivered for mouse wheel movements. Most terminals cannot report the state of more than one button at a time -- and some cannot report motion events unless a button is pressed. Applications can inspect the time between events to resolve double or triple clicks. #### func [NewEventMouse](https://github.com/gdamore/tcell/blob/v1.4.0/mouse.go#L69) [¶](#NewEventMouse) ``` func NewEventMouse(x, y [int](/builtin#int), btn [ButtonMask](#ButtonMask), mod [ModMask](#ModMask)) *[EventMouse](#EventMouse) ``` NewEventMouse is used to create a new mouse event. Applications shouldn't need to use this; its mostly for screen implementors. #### func (*EventMouse) [Buttons](https://github.com/gdamore/tcell/blob/v1.4.0/mouse.go#L51) [¶](#EventMouse.Buttons) ``` func (ev *[EventMouse](#EventMouse)) Buttons() [ButtonMask](#ButtonMask) ``` Buttons returns the list of buttons that were pressed or wheel motions. #### func (*EventMouse) [Modifiers](https://github.com/gdamore/tcell/blob/v1.4.0/mouse.go#L57) [¶](#EventMouse.Modifiers) ``` func (ev *[EventMouse](#EventMouse)) Modifiers() [ModMask](#ModMask) ``` Modifiers returns a list of keyboard modifiers that were pressed with the mouse button(s). #### func (*EventMouse) [Position](https://github.com/gdamore/tcell/blob/v1.4.0/mouse.go#L63) [¶](#EventMouse.Position) ``` func (ev *[EventMouse](#EventMouse)) Position() ([int](/builtin#int), [int](/builtin#int)) ``` Position returns the mouse position in character cells. The origin 0, 0 is at the upper left corner. #### func (*EventMouse) [When](https://github.com/gdamore/tcell/blob/v1.4.0/mouse.go#L46) [¶](#EventMouse.When) ``` func (ev *[EventMouse](#EventMouse)) When() [time](/time).[Time](/time#Time) ``` When returns the time when this EventMouse was created. #### type [EventResize](https://github.com/gdamore/tcell/blob/v1.4.0/resize.go#L22) [¶](#EventResize) ``` type EventResize struct { // contains filtered or unexported fields } ``` EventResize is sent when the window size changes. #### func [NewEventResize](https://github.com/gdamore/tcell/blob/v1.4.0/resize.go#L30) [¶](#NewEventResize) ``` func NewEventResize(width, height [int](/builtin#int)) *[EventResize](#EventResize) ``` NewEventResize creates an EventResize with the new updated window size, which is given in character cells. #### func (*EventResize) [Size](https://github.com/gdamore/tcell/blob/v1.4.0/resize.go#L40) [¶](#EventResize.Size) ``` func (ev *[EventResize](#EventResize)) Size() ([int](/builtin#int), [int](/builtin#int)) ``` Size returns the new window size as width, height in character cells. #### func (*EventResize) [When](https://github.com/gdamore/tcell/blob/v1.4.0/resize.go#L35) [¶](#EventResize.When) ``` func (ev *[EventResize](#EventResize)) When() [time](/time).[Time](/time#Time) ``` When returns the time when the Event was created. #### type [EventTime](https://github.com/gdamore/tcell/blob/v1.4.0/event.go#L30) [¶](#EventTime) ``` type EventTime struct { // contains filtered or unexported fields } ``` EventTime is a simple base event class, suitable for easy reuse. It can be used to deliver actual timer events as well. #### func (*EventTime) [SetEventNow](https://github.com/gdamore/tcell/blob/v1.4.0/event.go#L45) [¶](#EventTime.SetEventNow) ``` func (e *[EventTime](#EventTime)) SetEventNow() ``` SetEventNow sets the time of occurrence for the event to the current time. #### func (*EventTime) [SetEventTime](https://github.com/gdamore/tcell/blob/v1.4.0/event.go#L40) [¶](#EventTime.SetEventTime) ``` func (e *[EventTime](#EventTime)) SetEventTime(t [time](/time).[Time](/time#Time)) ``` SetEventTime sets the time of occurrence for the event. #### func (*EventTime) [When](https://github.com/gdamore/tcell/blob/v1.4.0/event.go#L35) [¶](#EventTime.When) ``` func (e *[EventTime](#EventTime)) When() [time](/time).[Time](/time#Time) ``` When returns the time stamp when the event occurred. #### type [Key](https://github.com/gdamore/tcell/blob/v1.4.0/key.go#L282) [¶](#Key) ``` type Key [int16](/builtin#int16) ``` Key is a generic value for representing keys, and especially special keys (function keys, cursor movement keys, etc.) For normal keys, like ASCII letters, we use KeyRune, and then expect the application to inspect the Rune() member of the EventKey. ``` const ( KeyRune [Key](#Key) = [iota](/builtin#iota) + 256 KeyUp KeyDown KeyRight KeyLeft KeyUpLeft KeyUpRight KeyDownLeft KeyDownRight KeyCenter KeyPgUp KeyPgDn KeyHome KeyEnd KeyInsert KeyDelete KeyHelp KeyExit KeyClear KeyCancel KeyPrint KeyPause KeyBacktab KeyF1 KeyF2 KeyF3 KeyF4 KeyF5 KeyF6 KeyF7 KeyF8 KeyF9 KeyF10 KeyF11 KeyF12 KeyF13 KeyF14 KeyF15 KeyF16 KeyF17 KeyF18 KeyF19 KeyF20 KeyF21 KeyF22 KeyF23 KeyF24 KeyF25 KeyF26 KeyF27 KeyF28 KeyF29 KeyF30 KeyF31 KeyF32 KeyF33 KeyF34 KeyF35 KeyF36 KeyF37 KeyF38 KeyF39 KeyF40 KeyF41 KeyF42 KeyF43 KeyF44 KeyF45 KeyF46 KeyF47 KeyF48 KeyF49 KeyF50 KeyF51 KeyF52 KeyF53 KeyF54 KeyF55 KeyF56 KeyF57 KeyF58 KeyF59 KeyF60 KeyF61 KeyF62 KeyF63 KeyF64 ) ``` This is the list of named keys. KeyRune is special however, in that it is a place holder key indicating that a printable character was sent. The actual value of the rune will be transported in the Rune of the associated EventKey. ``` const ( KeyCtrlSpace [Key](#Key) = [iota](/builtin#iota) KeyCtrlA KeyCtrlB KeyCtrlC KeyCtrlD KeyCtrlE KeyCtrlF KeyCtrlG KeyCtrlH KeyCtrlI KeyCtrlJ KeyCtrlK KeyCtrlL KeyCtrlM KeyCtrlN KeyCtrlO KeyCtrlP KeyCtrlQ KeyCtrlR KeyCtrlS KeyCtrlT KeyCtrlU KeyCtrlV KeyCtrlW KeyCtrlX KeyCtrlY KeyCtrlZ KeyCtrlLeftSq // Escape KeyCtrlBackslash KeyCtrlRightSq KeyCtrlCarat KeyCtrlUnderscore ) ``` These are the control keys. Note that they overlap with other keys, perhaps. For example, KeyCtrlH is the same as KeyBackspace. ``` const ( KeyNUL [Key](#Key) = [iota](/builtin#iota) KeySOH KeySTX KeyETX KeyEOT KeyENQ KeyACK KeyBEL KeyBS KeyTAB KeyLF KeyVT KeyFF KeyCR KeySO KeySI KeyDLE KeyDC1 KeyDC2 KeyDC3 KeyDC4 KeyNAK KeySYN KeyETB KeyCAN KeyEM KeySUB KeyESC KeyFS KeyGS KeyRS KeyUS KeyDEL [Key](#Key) = 0x7F ) ``` These are the defined ASCII values for key codes. They generally match with KeyCtrl values. #### type [ModMask](https://github.com/gdamore/tcell/blob/v1.4.0/key.go#L263) [¶](#ModMask) ``` type ModMask [int16](/builtin#int16) ``` ModMask is a mask of modifier keys. Note that it will not always be possible to report modifier keys. ``` const ( ModShift [ModMask](#ModMask) = 1 << [iota](/builtin#iota) ModCtrl ModAlt ModMeta ModNone [ModMask](#ModMask) = 0 ) ``` These are the modifiers keys that can be sent either with a key press, or a mouse event. Note that as of now, due to the confusion associated with Meta, and the lack of support for it on many/most platforms, the current implementations never use it. Instead, they use ModAlt, even for events that could possibly have been distinguished from ModAlt. #### type [Screen](https://github.com/gdamore/tcell/blob/v1.4.0/screen.go#L20) [¶](#Screen) ``` type Screen interface { // Init initializes the screen for use. Init() [error](/builtin#error) // Fini finalizes the screen also releasing resources. Fini() // Clear erases the screen. The contents of any screen buffers // will also be cleared. This has the logical effect of // filling the screen with spaces, using the global default style. Clear() // Fill fills the screen with the given character and style. Fill([rune](/builtin#rune), [Style](#Style)) // SetCell is an older API, and will be removed. Please use // SetContent instead; SetCell is implemented in terms of SetContent. SetCell(x [int](/builtin#int), y [int](/builtin#int), style [Style](#Style), ch ...[rune](/builtin#rune)) // GetContent returns the contents at the given location. If the // coordinates are out of range, then the values will be 0, nil, // StyleDefault. Note that the contents returned are logical contents // and may not actually be what is displayed, but rather are what will // be displayed if Show() or Sync() is called. The width is the width // in screen cells; most often this will be 1, but some East Asian // characters require two cells. GetContent(x, y [int](/builtin#int)) (mainc [rune](/builtin#rune), combc [][rune](/builtin#rune), style [Style](#Style), width [int](/builtin#int)) // SetContent sets the contents of the given cell location. If // the coordinates are out of range, then the operation is ignored. // // The first rune is the primary non-zero width rune. The array // that follows is a possible list of combining characters to append, // and will usually be nil (no combining characters.) // // The results are not displayd until Show() or Sync() is called. // // Note that wide (East Asian full width) runes occupy two cells, // and attempts to place character at next cell to the right will have // undefined effects. Wide runes that are printed in the // last column will be replaced with a single width space on output. SetContent(x [int](/builtin#int), y [int](/builtin#int), mainc [rune](/builtin#rune), combc [][rune](/builtin#rune), style [Style](#Style)) // SetStyle sets the default style to use when clearing the screen // or when StyleDefault is specified. If it is also StyleDefault, // then whatever system/terminal default is relevant will be used. SetStyle(style [Style](#Style)) // ShowCursor is used to display the cursor at a given location. // If the coordinates -1, -1 are given or are otherwise outside the // dimensions of the screen, the cursor will be hidden. ShowCursor(x [int](/builtin#int), y [int](/builtin#int)) // HideCursor is used to hide the cursor. Its an alias for // ShowCursor(-1, -1). HideCursor() // Size returns the screen size as width, height. This changes in // response to a call to Clear or Flush. Size() ([int](/builtin#int), [int](/builtin#int)) // PollEvent waits for events to arrive. Main application loops // must spin on this to prevent the application from stalling. // Furthermore, this will return nil if the Screen is finalized. PollEvent() [Event](#Event) // PostEvent tries to post an event into the event stream. This // can fail if the event queue is full. In that case, the event // is dropped, and ErrEventQFull is returned. PostEvent(ev [Event](#Event)) [error](/builtin#error) // PostEventWait is like PostEvent, but if the queue is full, it // blocks until there is space in the queue, making delivery // reliable. However, it is VERY important that this function // never be called from within whatever event loop is polling // with PollEvent(), otherwise a deadlock may arise. // // For this reason, when using this function, the use of a // Goroutine is recommended to ensure no deadlock can occur. PostEventWait(ev [Event](#Event)) // EnableMouse enables the mouse. (If your terminal supports it.) EnableMouse() // DisableMouse disables the mouse. DisableMouse() // HasMouse returns true if the terminal (apparently) supports a // mouse. Note that the a return value of true doesn't guarantee that // a mouse/pointing device is present; a false return definitely // indicates no mouse support is available. HasMouse() [bool](/builtin#bool) // Colors returns the number of colors. All colors are assumed to // use the ANSI color map. If a terminal is monochrome, it will // return 0. Colors() [int](/builtin#int) // Show makes all the content changes made using SetContent() visible // on the display. // // It does so in the most efficient and least visually disruptive // manner possible. Show() // Sync works like Show(), but it updates every visible cell on the // physical display, assuming that it is not synchronized with any // internal model. This may be both expensive and visually jarring, // so it should only be used when believed to actually be necessary. // // Typically this is called as a result of a user-requested redraw // (e.g. to clear up on screen corruption caused by some other program), // or during a resize event. Sync() // CharacterSet returns information about the character set. // This isn't the full locale, but it does give us the input/output // character set. Note that this is just for diagnostic purposes, // we normally translate input/output to/from UTF-8, regardless of // what the user's environment is. CharacterSet() [string](/builtin#string) // The display string should be the same width as original rune. // This makes it possible to register two character replacements // for full width East Asian characters, for example. // // It is recommended that replacement strings consist only of // 7-bit ASCII, since other characters may not display everywhere. RegisterRuneFallback(r [rune](/builtin#rune), subst [string](/builtin#string)) // UnregisterRuneFallback unmaps a replacement. It will unmap // the implicit ASCII replacements for alternate characters as well. // When an unmapped char needs to be displayed, but no suitable // glyph is available, '?' is emitted instead. It is not possible // to "disable" the use of alternate characters that are supported // by your terminal except by changing the terminal database. UnregisterRuneFallback(r [rune](/builtin#rune)) // CanDisplay returns true if the given rune can be displayed on // this screen. Note that this is a best guess effort -- whether // your fonts support the character or not may be questionable. // Mostly this is for folks who work outside of Unicode. // // If checkFallbacks is true, then if any (possibly imperfect) // fallbacks are registered, this will return true. This will // also return true if the terminal can replace the glyph with // one that is visually indistinguishable from the one requested. CanDisplay(r [rune](/builtin#rune), checkFallbacks [bool](/builtin#bool)) [bool](/builtin#bool) // Resize does nothing, since its generally not possible to // ask a screen to resize, but it allows the Screen to implement // the View interface. Resize([int](/builtin#int), [int](/builtin#int), [int](/builtin#int), [int](/builtin#int)) // HasKey returns true if the keyboard is believed to have the // key. In some cases a keyboard may have keys with this name // but no support for them, while in others a key may be reported // as supported but not actually be usable (such as some emulators // that hijack certain keys). Its best not to depend to strictly // on this function, but it can be used for hinting when building // menus, displayed hot-keys, etc. Note that KeyRune (literal // runes) is always true. HasKey([Key](#Key)) [bool](/builtin#bool) // Beep attempts to sound an OS-dependent audible alert and returns an error // when unsuccessful. Beep() [error](/builtin#error) } ``` Screen represents the physical (or emulated) screen. This can be a terminal window or a physical console. Platforms implement this differerently. #### func [NewConsoleScreen](https://github.com/gdamore/tcell/blob/v1.4.0/console_stub.go#L21) [¶](#NewConsoleScreen) ``` func NewConsoleScreen() ([Screen](#Screen), [error](/builtin#error)) ``` NewConsoleScreen returns a console based screen. This platform doesn't have support for any, so it returns nil and a suitable error. #### func [NewScreen](https://github.com/gdamore/tcell/blob/v1.4.0/screen.go#L204) [¶](#NewScreen) ``` func NewScreen() ([Screen](#Screen), [error](/builtin#error)) ``` NewScreen returns a default Screen suitable for the user's terminal environment. #### func [NewTerminfoScreen](https://github.com/gdamore/tcell/blob/v1.4.0/tscreen.go#L42) [¶](#NewTerminfoScreen) ``` func NewTerminfoScreen() ([Screen](#Screen), [error](/builtin#error)) ``` NewTerminfoScreen returns a Screen that uses the stock TTY interface and POSIX termios, combined with a terminfo description taken from the $TERM environment variable. It returns an error if the terminal is not supported for any reason. For terminals that do not support dynamic resize events, the $LINES $COLUMNS environment variables can be set to the actual window size, otherwise defaults taken from the terminal database are used. #### type [SimCell](https://github.com/gdamore/tcell/blob/v1.4.0/simulation.go#L73) [¶](#SimCell) ``` type SimCell struct { // Bytes is the actual character bytes. Normally this is // rune data, but it could be be data in another encoding system. Bytes [][byte](/builtin#byte) // Style is the style used to display the data. Style [Style](#Style) // Runes is the list of runes, unadulterated, in UTF-8. Runes [][rune](/builtin#rune) } ``` SimCell represents a simulated screen cell. The purpose of this is to track on screen content. #### type [SimulationScreen](https://github.com/gdamore/tcell/blob/v1.4.0/simulation.go#L37) [¶](#SimulationScreen) ``` type SimulationScreen interface { // InjectKeyBytes injects a stream of bytes corresponding to // the native encoding (see charset). It turns true if the entire // set of bytes were processed and delivered as KeyEvents, false // if any bytes were not fully understood. Any bytes that are not // fully converted are discarded. InjectKeyBytes(buf [][byte](/builtin#byte)) [bool](/builtin#bool) // InjectKey injects a key event. The rune is a UTF-8 rune, post // any translation. InjectKey(key [Key](#Key), r [rune](/builtin#rune), mod [ModMask](#ModMask)) // InjectMouse injects a mouse event. InjectMouse(x, y [int](/builtin#int), buttons [ButtonMask](#ButtonMask), mod [ModMask](#ModMask)) // SetSize resizes the underlying physical screen. It also causes // a resize event to be injected during the next Show() or Sync(). // A new physical contents array will be allocated (with data from // the old copied), so any prior value obtained with GetContents // won't be used anymore SetSize(width, height [int](/builtin#int)) // GetContents returns screen contents as an array of // cells, along with the physical width & height. Note that the // physical contents will be used until the next time SetSize() // is called. GetContents() (cells [][SimCell](#SimCell), width [int](/builtin#int), height [int](/builtin#int)) // GetCursor returns the cursor details. GetCursor() (x [int](/builtin#int), y [int](/builtin#int), visible [bool](/builtin#bool)) [Screen](#Screen) } ``` SimulationScreen represents a screen simulation. This is intended to be a superset of normal Screens, but also adds some important interfaces for testing. #### func [NewSimulationScreen](https://github.com/gdamore/tcell/blob/v1.4.0/simulation.go#L26) [¶](#NewSimulationScreen) ``` func NewSimulationScreen(charset [string](/builtin#string)) [SimulationScreen](#SimulationScreen) ``` NewSimulationScreen returns a SimulationScreen. Note that SimulationScreen is also a Screen. #### type [Style](https://github.com/gdamore/tcell/blob/v1.4.0/style.go#L35) [¶](#Style) ``` type Style [int64](/builtin#int64) ``` Style represents a complete text style, including both foreground and background color. We encode it in a 64-bit int for efficiency. The coding is (MSB): <7b flags><1b><24b fgcolor><7b attr><1b><24b bgcolor>. The <1b> is set true to indicate that the color is an RGB color, rather than a named index. This gives 24bit color options, if it ever becomes truly necessary. However, applications must not rely on this encoding. Note that not all terminals can display all colors or attributes, and many might have specific incompatibilities between specific attributes and color combinations. The intention is to extend styles to support paletting, in which case some flag bit(s) would be set, and the foreground and background colors would be replaced with a palette number and palette index. To use Style, just declare a variable of its type. ``` const StyleDefault [Style](#Style) = 0 ``` StyleDefault represents a default style, based upon the context. It is the zero value. #### func (Style) [Background](https://github.com/gdamore/tcell/blob/v1.4.0/style.go#L60) [¶](#Style.Background) ``` func (s [Style](#Style)) Background(c [Color](#Color)) [Style](#Style) ``` Background returns a new style based on s, with the background color set as requested. ColorDefault can be used to select the global default. #### func (Style) [Blink](https://github.com/gdamore/tcell/blob/v1.4.0/style.go#L105) [¶](#Style.Blink) ``` func (s [Style](#Style)) Blink(on [bool](/builtin#bool)) [Style](#Style) ``` Blink returns a new style based on s, with the blink attribute set as requested. #### func (Style) [Bold](https://github.com/gdamore/tcell/blob/v1.4.0/style.go#L99) [¶](#Style.Bold) ``` func (s [Style](#Style)) Bold(on [bool](/builtin#bool)) [Style](#Style) ``` Bold returns a new style based on s, with the bold attribute set as requested. #### func (Style) [Decompose](https://github.com/gdamore/tcell/blob/v1.4.0/style.go#L69) [¶](#Style.Decompose) ``` func (s [Style](#Style)) Decompose() (fg [Color](#Color), bg [Color](#Color), attr [AttrMask](#AttrMask)) ``` Decompose breaks a style up, returning the foreground, background, and other attributes. #### func (Style) [Dim](https://github.com/gdamore/tcell/blob/v1.4.0/style.go#L111) [¶](#Style.Dim) ``` func (s [Style](#Style)) Dim(on [bool](/builtin#bool)) [Style](#Style) ``` Dim returns a new style based on s, with the dim attribute set as requested. #### func (Style) [Foreground](https://github.com/gdamore/tcell/blob/v1.4.0/style.go#L50) [¶](#Style.Foreground) ``` func (s [Style](#Style)) Foreground(c [Color](#Color)) [Style](#Style) ``` Foreground returns a new style based on s, with the foreground color set as requested. ColorDefault can be used to select the global default. #### func (Style) [Italic](https://github.com/gdamore/tcell/blob/v1.4.0/style.go#L117) [¶](#Style.Italic) added in v1.4.0 ``` func (s [Style](#Style)) Italic(on [bool](/builtin#bool)) [Style](#Style) ``` Italic returns a new style based on s, with the italic attribute set as requested. #### func (Style) [Normal](https://github.com/gdamore/tcell/blob/v1.4.0/style.go#L93) [¶](#Style.Normal) ``` func (s [Style](#Style)) Normal() [Style](#Style) ``` Normal returns the style with all attributes disabled. #### func (Style) [Reverse](https://github.com/gdamore/tcell/blob/v1.4.0/style.go#L124) [¶](#Style.Reverse) ``` func (s [Style](#Style)) Reverse(on [bool](/builtin#bool)) [Style](#Style) ``` Reverse returns a new style based on s, with the reverse attribute set as requested. (Reverse usually changes the foreground and background colors.) #### func (Style) [Underline](https://github.com/gdamore/tcell/blob/v1.4.0/style.go#L130) [¶](#Style.Underline) ``` func (s [Style](#Style)) Underline(on [bool](/builtin#bool)) [Style](#Style) ``` Underline returns a new style based on s, with the underline attribute set as requested.
github.com/chenquan/diskusage
go
Go
README [¶](#section-readme) --- ### diskusage [![]()](https://www.buymeacoffee.com/chenquan) [![Release](https://img.shields.io/github/v/release/chenquan/diskusage.svg?style=flat-square)](https://github.com/chenquan/diskusage) [![Download](https://goproxy.cn/stats/github.com/chenquan/diskusage/badges/download-count.svg)](https://github.com/chenquan/diskusage) [![GitHub](https://img.shields.io/github/license/chenquan/diskusage)](https://github.com/chenquan/diskusage/blob/v1.2.2/LICENSE) English | [简体中文](https://github.com/chenquan/diskusage/blob/v1.2.2/README-CN.md) 💥A tool for showing disk usage. (Linux, MacOS and Windows) ![](https://github.com/chenquan/diskusage/raw/v1.2.2/image/linux-pipe-more.png) ![](https://github.com/chenquan/diskusage/raw/v1.2.2/image/only-dir.png) ![](https://github.com/chenquan/diskusage/raw/v1.2.2/image/interactive.png) #### 😜installation ``` go install github.com/chenquan/diskusage@latest ``` or [download](https://github.com/chenquan/diskusage/releases). #### 👏how to use ``` $ diskusage -h A tool for showing disk usage. GitHub: https://github.com/chenquan/diskusage Issues: https://github.com/chenquan/diskusage/issues Usage: diskusage [flags] Examples: 1.The maximum display unit is GB: diskusage -u G 2.Only files named doc or docx are counted: a.diskusage -t doc,docx b.diskusage -f ".+\.(doc|docx)$" 3.Supports color output to pipeline: a.diskusage -c always | less -R b.diskusage -c always | more 4.Displays a 2-level tree structure: diskusage -d 2 5.Specify the directory /usr: diskusage --dir /usr 6.Export disk usage to file: diskusage > diskusage.txt Flags: -a, --all display all directories, otherwise only display folders whose usage size is not 0 -c, --color string set color output mode. optional: auto, always, ignore (default "auto") -d, --depth int shows the depth of the tree directory structure (default 1) --dir string directory path (default "./") -D, --directory only display directory -f, --filter string regular expressions are used to filter files -h, --help help for diskusage -l, --limit int limit the number of files and directories displayed (default 9223372036854775807) -r, --recursion automatically calculate directory depth, for recursively traversing all sub directories -t, --type strings only count certain types of files (default all) -u, --unit string displayed units. optional: B(Bytes), K(KB), M(MB), G(GB), T(TB) (default "M") -v, --version version for diskusage -w, --worker int number of workers searching the directory (default 32) ``` #### 👀example 1. Only files named doc or docx are counted: `diskusage -t doc,docx` or `diskusage -f ".+\.(doc|docx)$"` 2. The maximum display unit is GB: `diskusage -u G` 3. Supports color output to pipeline: `diskusage -c always | less -R` or `diskusage -c always | more` If you like or are using this project to learn or start your solution, please give it a star⭐. Thanks! Documentation [¶](#section-documentation) --- ![The Go Gopher](/static/shared/gopher/airplane-1200x945.svg) There is no documentation for this package.
termcolor
rust
Rust
Crate termcolor === This crate provides a cross platform abstraction for writing colored text to a terminal. Colors are written using either ANSI escape sequences or by communicating with a Windows console. Much of this API was motivated by use inside command line applications, where colors or styles can be configured by the end user and/or the environment. This crate also provides platform independent support for writing colored text to an in memory buffer. While this is easy to do with ANSI escape sequences (because they are in the buffer themselves), it is trickier to do with the Windows console API, which requires synchronous communication. In ANSI mode, this crate also provides support for writing hyperlinks. Organization --- The `WriteColor` trait extends the `io::Write` trait with methods for setting colors or resetting them. `StandardStream` and `StandardStreamLock` both satisfy `WriteColor` and are analogous to `std::io::Stdout` and `std::io::StdoutLock`, or `std::io::Stderr` and `std::io::StderrLock`. `Buffer` is an in memory buffer that supports colored text. In a parallel program, each thread might write to its own buffer. A buffer can be printed to using a `BufferWriter`. The advantage of this design is that each thread can work in parallel on a buffer without having to synchronize access to global resources such as the Windows console. Moreover, this design also prevents interleaving of buffer output. `Ansi` and `NoColor` both satisfy `WriteColor` for arbitrary implementors of `io::Write`. These types are useful when you know exactly what you need. An analogous type for the Windows console is not provided since it cannot exist. Example: using `StandardStream` --- The `StandardStream` type in this crate works similarly to `std::io::Stdout`, except it is augmented with methods for coloring by the `WriteColor` trait. For example, to write some green text: ``` use std::io::Write; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; let mut stdout = StandardStream::stdout(ColorChoice::Always); stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; writeln!(&mut stdout, "green text!")?; ``` Note that any text written to the terminal now will be colored green when using ANSI escape sequences, even if it is written via stderr, and even if stderr had previously been set to `Color::Red`. Users will need to manage any color changes themselves by calling `WriteColor::set_color`, and this may include calling `WriteColor::reset` before the program exits to a shell. Example: using `BufferWriter` --- A `BufferWriter` can create buffers and write buffers to stdout or stderr. It does *not* implement `io::Write` or `WriteColor` itself. Instead, `Buffer` implements `io::Write` and `io::WriteColor`. This example shows how to print some green text to stderr. ``` use std::io::Write; use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor}; let mut bufwtr = BufferWriter::stderr(ColorChoice::Always); let mut buffer = bufwtr.buffer(); buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; writeln!(&mut buffer, "green text!")?; bufwtr.print(&buffer)?; ``` Detecting presence of a terminal --- In many scenarios when using color, one often wants to enable colors automatically when writing to a terminal and disable colors automatically when writing to anything else. The typical way to achieve this in Unix environments is via libc’s `isatty` function. Unfortunately, this notoriously does not work well in Windows environments. To work around that, the recommended solution is to use the standard library’s `IsTerminal` trait. It goes out of its way to get it as right as possible in Windows environments. For example, in a command line application that exposes a `--color` flag, your logic for how to enable colors might look like this: ``` use std::io::IsTerminal; use termcolor::{ColorChoice, StandardStream}; let preference = argv.get_flag("color").unwrap_or("auto"); let mut choice = preference.parse::<ColorChoice>()?; if choice == ColorChoice::Auto && !std::io::stdin().is_terminal() { choice = ColorChoice::Never; } let stdout = StandardStream::stdout(choice); // ... write to stdout ``` Currently, `termcolor` does not provide anything to do this for you. Structs --- * AnsiSatisfies `WriteColor` using standard ANSI escape sequences. * BufferWrite colored text to memory. * BufferWriterWrites colored buffers to stdout or stderr. * BufferedStandardStreamLike `StandardStream`, but does buffered writing. * ColorChoiceParseErrorAn error that occurs when parsing a `ColorChoice` fails. * ColorSpecA color specification. * HyperlinkSpecA hyperlink specification. * NoColorSatisfies `WriteColor` but ignores all color options. * ParseColorErrorAn error from parsing an invalid color specification. * StandardStreamSatisfies `io::Write` and `WriteColor`, and supports optional coloring to either of the standard output streams, stdout and stderr. * StandardStreamLock`StandardStreamLock` is a locked reference to a `StandardStream`. Enums --- * ColorThe set of available colors for the terminal foreground/background. * ColorChoiceColorChoice represents the color preferences of an end user. Traits --- * WriteColorThis trait describes the behavior of writers that support colored output. Crate termcolor === This crate provides a cross platform abstraction for writing colored text to a terminal. Colors are written using either ANSI escape sequences or by communicating with a Windows console. Much of this API was motivated by use inside command line applications, where colors or styles can be configured by the end user and/or the environment. This crate also provides platform independent support for writing colored text to an in memory buffer. While this is easy to do with ANSI escape sequences (because they are in the buffer themselves), it is trickier to do with the Windows console API, which requires synchronous communication. In ANSI mode, this crate also provides support for writing hyperlinks. Organization --- The `WriteColor` trait extends the `io::Write` trait with methods for setting colors or resetting them. `StandardStream` and `StandardStreamLock` both satisfy `WriteColor` and are analogous to `std::io::Stdout` and `std::io::StdoutLock`, or `std::io::Stderr` and `std::io::StderrLock`. `Buffer` is an in memory buffer that supports colored text. In a parallel program, each thread might write to its own buffer. A buffer can be printed to using a `BufferWriter`. The advantage of this design is that each thread can work in parallel on a buffer without having to synchronize access to global resources such as the Windows console. Moreover, this design also prevents interleaving of buffer output. `Ansi` and `NoColor` both satisfy `WriteColor` for arbitrary implementors of `io::Write`. These types are useful when you know exactly what you need. An analogous type for the Windows console is not provided since it cannot exist. Example: using `StandardStream` --- The `StandardStream` type in this crate works similarly to `std::io::Stdout`, except it is augmented with methods for coloring by the `WriteColor` trait. For example, to write some green text: ``` use std::io::Write; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; let mut stdout = StandardStream::stdout(ColorChoice::Always); stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; writeln!(&mut stdout, "green text!")?; ``` Note that any text written to the terminal now will be colored green when using ANSI escape sequences, even if it is written via stderr, and even if stderr had previously been set to `Color::Red`. Users will need to manage any color changes themselves by calling `WriteColor::set_color`, and this may include calling `WriteColor::reset` before the program exits to a shell. Example: using `BufferWriter` --- A `BufferWriter` can create buffers and write buffers to stdout or stderr. It does *not* implement `io::Write` or `WriteColor` itself. Instead, `Buffer` implements `io::Write` and `io::WriteColor`. This example shows how to print some green text to stderr. ``` use std::io::Write; use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor}; let mut bufwtr = BufferWriter::stderr(ColorChoice::Always); let mut buffer = bufwtr.buffer(); buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; writeln!(&mut buffer, "green text!")?; bufwtr.print(&buffer)?; ``` Detecting presence of a terminal --- In many scenarios when using color, one often wants to enable colors automatically when writing to a terminal and disable colors automatically when writing to anything else. The typical way to achieve this in Unix environments is via libc’s `isatty` function. Unfortunately, this notoriously does not work well in Windows environments. To work around that, the recommended solution is to use the standard library’s `IsTerminal` trait. It goes out of its way to get it as right as possible in Windows environments. For example, in a command line application that exposes a `--color` flag, your logic for how to enable colors might look like this: ``` use std::io::IsTerminal; use termcolor::{ColorChoice, StandardStream}; let preference = argv.get_flag("color").unwrap_or("auto"); let mut choice = preference.parse::<ColorChoice>()?; if choice == ColorChoice::Auto && !std::io::stdin().is_terminal() { choice = ColorChoice::Never; } let stdout = StandardStream::stdout(choice); // ... write to stdout ``` Currently, `termcolor` does not provide anything to do this for you. Structs --- * AnsiSatisfies `WriteColor` using standard ANSI escape sequences. * BufferWrite colored text to memory. * BufferWriterWrites colored buffers to stdout or stderr. * BufferedStandardStreamLike `StandardStream`, but does buffered writing. * ColorChoiceParseErrorAn error that occurs when parsing a `ColorChoice` fails. * ColorSpecA color specification. * HyperlinkSpecA hyperlink specification. * NoColorSatisfies `WriteColor` but ignores all color options. * ParseColorErrorAn error from parsing an invalid color specification. * StandardStreamSatisfies `io::Write` and `WriteColor`, and supports optional coloring to either of the standard output streams, stdout and stderr. * StandardStreamLock`StandardStreamLock` is a locked reference to a `StandardStream`. Enums --- * ColorThe set of available colors for the terminal foreground/background. * ColorChoiceColorChoice represents the color preferences of an end user. Traits --- * WriteColorThis trait describes the behavior of writers that support colored output. Trait termcolor::WriteColor === ``` pub trait WriteColor: Write { // Required methods fn supports_color(&self) -> bool; fn set_color(&mut self, spec: &ColorSpec) -> Result<()>; fn reset(&mut self) -> Result<()>; // Provided methods fn is_synchronous(&self) -> bool { ... } fn set_hyperlink(&mut self, _link: &HyperlinkSpec<'_>) -> Result<()> { ... } fn supports_hyperlinks(&self) -> bool { ... } } ``` This trait describes the behavior of writers that support colored output. Required Methods --- #### fn supports_color(&self) -> bool Returns true if and only if the underlying writer supports colors. #### fn set_color(&mut self, spec: &ColorSpec) -> Result<()Set the color settings of the writer. Subsequent writes to this writer will use these settings until either `reset` is called or new color settings are set. If there was a problem setting the color settings, then an error is returned. #### fn reset(&mut self) -> Result<()Reset the current color settings to their original settings. If there was a problem resetting the color settings, then an error is returned. Note that this does not reset hyperlinks. Those need to be reset on their own, e.g., by calling `set_hyperlink` with [`HyperlinkSpec::none`]. Provided Methods --- #### fn is_synchronous(&self) -> bool Returns true if and only if the underlying writer must synchronously interact with an end user’s device in order to control colors. By default, this always returns `false`. In practice, this should return `true` if the underlying writer is manipulating colors using the Windows console APIs. This is useful for writing generic code (such as a buffered writer) that can perform certain optimizations when the underlying writer doesn’t rely on synchronous APIs. For example, ANSI escape sequences can be passed through to the end user’s device as is. #### fn set_hyperlink(&mut self, _link: &HyperlinkSpec<'_>) -> Result<()Set the current hyperlink of the writer. The typical way to use this is to first call it with a `HyperlinkSpec::open` to write the actual URI to a tty that supports [OSC-8]. At this point, the caller can now write the label for the hyperlink. This may include coloring or other styles. Once the caller has finished writing the label, one should call this method again with `HyperlinkSpec::close`. If there was a problem setting the hyperlink, then an error is returned. This defaults to doing nothing. #### fn supports_hyperlinks(&self) -> bool Returns true if and only if the underlying writer supports hyperlinks. This can be used to avoid generating hyperlink URIs unnecessarily. This defaults to `false`. Implementations on Foreign Types --- ### impl WriteColor for Sink #### fn supports_color(&self) -> bool #### fn supports_hyperlinks(&self) -> bool #### fn set_color(&mut self, _: &ColorSpec) -> Result<()#### fn set_hyperlink(&mut self, _: &HyperlinkSpec<'_>) -> Result<()#### fn reset(&mut self) -> Result<()### impl<'a, T: ?Sized + WriteColor> WriteColor for &'a mut T #### fn supports_color(&self) -> bool #### fn supports_hyperlinks(&self) -> bool #### fn set_color(&mut self, spec: &ColorSpec) -> Result<()#### fn set_hyperlink(&mut self, link: &HyperlinkSpec<'_>) -> Result<()#### fn reset(&mut self) -> Result<()#### fn is_synchronous(&self) -> bool ### impl<T: ?Sized + WriteColor> WriteColor for Box<T#### fn supports_color(&self) -> bool #### fn supports_hyperlinks(&self) -> bool #### fn set_color(&mut self, spec: &ColorSpec) -> Result<()#### fn set_hyperlink(&mut self, link: &HyperlinkSpec<'_>) -> Result<()#### fn reset(&mut self) -> Result<()#### fn is_synchronous(&self) -> bool Implementors --- ### impl WriteColor for Buffer ### impl WriteColor for BufferedStandardStream ### impl WriteColor for StandardStream ### impl<'a> WriteColor for StandardStreamLock<'a### impl<W: Write> WriteColor for Ansi<W### impl<W: Write> WriteColor for NoColor<WStruct termcolor::Ansi === ``` pub struct Ansi<W>(/* private fields */); ``` Satisfies `WriteColor` using standard ANSI escape sequences. Implementations --- ### impl<W: Write> Ansi<W#### pub fn new(wtr: W) -> Ansi<WCreate a new writer that satisfies `WriteColor` using standard ANSI escape sequences. #### pub fn into_inner(self) -> W Consume this `Ansi` value and return the inner writer. #### pub fn get_ref(&self) -> &W Return a reference to the inner writer. #### pub fn get_mut(&mut self) -> &mut W Return a mutable reference to the inner writer. Trait Implementations --- ### impl<W: Debug> Debug for Ansi<W#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 🔬This is a nightly-only experimental API. (`can_vector`)Determines if this `Write`r has an efficient `write_vectored` implementation. Self: Sized, Creates a “by reference” adapter for this instance of `Write`. Returns true if and only if the underlying writer supports colors.#### fn supports_hyperlinks(&self) -> bool Returns true if and only if the underlying writer supports hyperlinks. Returns true if and only if the underlying writer must synchronously interact with an end user’s device in order to control colors. By default, this always returns `false`. Read moreAuto Trait Implementations --- ### impl<W> RefUnwindSafe for Ansi<W>where W: RefUnwindSafe, ### impl<W> Send for Ansi<W>where W: Send, ### impl<W> Sync for Ansi<W>where W: Sync, ### impl<W> Unpin for Ansi<W>where W: Unpin, ### impl<W> UnwindSafe for Ansi<W>where W: UnwindSafe, Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"Ansi<W>":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.Ansi.html\" title=\"struct termcolor::Ansi\">Ansi</a>&lt;W&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;W: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a>&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"struct.Ansi.html\" title=\"struct termcolor::Ansi\">Ansi</a>&lt;W&gt;</span>"} Struct termcolor::Buffer === ``` pub struct Buffer(/* private fields */); ``` Write colored text to memory. `Buffer` is a platform independent abstraction for printing colored text to an in memory buffer. When the buffer is printed using a `BufferWriter`, the color information will be applied to the output device (a tty on Unix and a console on Windows). A `Buffer` is typically created by calling the `BufferWriter.buffer` method, which will take color preferences and the environment into account. However, buffers can also be manually created using `no_color`, `ansi` or `console` (on Windows). Implementations --- ### impl Buffer #### pub fn no_color() -> Buffer Create a buffer that drops all color information. #### pub fn ansi() -> Buffer Create a buffer that uses ANSI escape sequences. #### pub fn is_empty(&self) -> bool Returns true if and only if this buffer is empty. #### pub fn len(&self) -> usize Returns the length of this buffer in bytes. #### pub fn clear(&mut self) Clears this buffer. #### pub fn into_inner(self) -> Vec<u8Consume this buffer and return the underlying raw data. On Windows, this unrecoverably drops all color information associated with the buffer. #### pub fn as_slice(&self) -> &[u8] Return the underlying data of the buffer. #### pub fn as_mut_slice(&mut self) -> &mut [u8] Return the underlying data of the buffer as a mutable slice. Trait Implementations --- ### impl Debug for Buffer #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn write(&mut self, buf: &[u8]) -> Result<usizeWrite a buffer into this writer, returning how many bytes were written. 🔬This is a nightly-only experimental API. (`can_vector`)Determines if this `Write`r has an efficient `write_vectored` implementation. Read more1.0.0 · source#### fn write_all(&mut self, buf: &[u8]) -> Result<(), ErrorAttempts to write an entire buffer into this writer. Self: Sized, Creates a “by reference” adapter for this instance of `Write`. #### fn supports_color(&self) -> bool Returns true if and only if the underlying writer supports colors.#### fn supports_hyperlinks(&self) -> bool Returns true if and only if the underlying writer supports hyperlinks. Returns true if and only if the underlying writer must synchronously interact with an end user’s device in order to control colors. By default, this always returns `false`. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for Buffer ### impl Send for Buffer ### impl Sync for Buffer ### impl Unpin for Buffer ### impl UnwindSafe for Buffer Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","Buffer":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.Buffer.html\" title=\"struct termcolor::Buffer\">Buffer</a></code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"struct.Buffer.html\" title=\"struct termcolor::Buffer\">Buffer</a></span>"} Struct termcolor::BufferWriter === ``` pub struct BufferWriter { /* private fields */ } ``` Writes colored buffers to stdout or stderr. Writable buffers can be obtained by calling `buffer` on a `BufferWriter`. This writer works with terminals that support ANSI escape sequences or with a Windows console. It is intended for a `BufferWriter` to be put in an `Arc` and written to from multiple threads simultaneously. Implementations --- ### impl BufferWriter #### pub fn stdout(choice: ColorChoice) -> BufferWriter Create a new `BufferWriter` that writes to stdout with the given color preferences. On Windows, if coloring is desired and a Windows console could not be found, then ANSI escape sequences are used instead. The specific color/style settings can be configured when writing to the buffers themselves. #### pub fn stderr(choice: ColorChoice) -> BufferWriter Create a new `BufferWriter` that writes to stderr with the given color preferences. On Windows, if coloring is desired and a Windows console could not be found, then ANSI escape sequences are used instead. The specific color/style settings can be configured when writing to the buffers themselves. #### pub fn separator(&mut self, sep: Option<Vec<u8>>) If set, the separator given is printed between buffers. By default, no separator is printed. The default value is `None`. #### pub fn buffer(&self) -> Buffer Creates a new `Buffer` with the current color preferences. A `Buffer` satisfies both `io::Write` and `WriteColor`. A `Buffer` can be printed using the `print` method. #### pub fn print(&self, buf: &Buffer) -> Result<()Prints the contents of the given buffer. It is safe to call this from multiple threads simultaneously. In particular, all buffers are written atomically. No interleaving will occur. Trait Implementations --- ### impl Debug for BufferWriter #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for BufferWriter ### impl Send for BufferWriter ### impl Sync for BufferWriter ### impl Unpin for BufferWriter ### impl UnwindSafe for BufferWriter Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"Buffer":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.Buffer.html\" title=\"struct termcolor::Buffer\">Buffer</a></code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"struct.Buffer.html\" title=\"struct termcolor::Buffer\">Buffer</a></span>"} Struct termcolor::BufferedStandardStream === ``` pub struct BufferedStandardStream { /* private fields */ } ``` Like `StandardStream`, but does buffered writing. Implementations --- ### impl BufferedStandardStream #### pub fn stdout(choice: ColorChoice) -> BufferedStandardStream Create a new `BufferedStandardStream` with the given color preferences that writes to standard output via a buffered writer. On Windows, if coloring is desired and a Windows console could not be found, then ANSI escape sequences are used instead. The specific color/style settings can be configured when writing via the `WriteColor` trait. #### pub fn stderr(choice: ColorChoice) -> BufferedStandardStream Create a new `BufferedStandardStream` with the given color preferences that writes to standard error via a buffered writer. On Windows, if coloring is desired and a Windows console could not be found, then ANSI escape sequences are used instead. The specific color/style settings can be configured when writing via the `WriteColor` trait. Trait Implementations --- ### impl Debug for BufferedStandardStream #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn write(&mut self, b: &[u8]) -> Result<usizeWrite a buffer into this writer, returning how many bytes were written. 🔬This is a nightly-only experimental API. (`can_vector`)Determines if this `Write`r has an efficient `write_vectored` implementation. Read more1.0.0 · source#### fn write_all(&mut self, buf: &[u8]) -> Result<(), ErrorAttempts to write an entire buffer into this writer. Self: Sized, Creates a “by reference” adapter for this instance of `Write`. #### fn supports_color(&self) -> bool Returns true if and only if the underlying writer supports colors.#### fn supports_hyperlinks(&self) -> bool Returns true if and only if the underlying writer supports hyperlinks. Returns true if and only if the underlying writer must synchronously interact with an end user’s device in order to control colors. By default, this always returns `false`. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for BufferedStandardStream ### impl Send for BufferedStandardStream ### impl Sync for BufferedStandardStream ### impl Unpin for BufferedStandardStream ### impl UnwindSafe for BufferedStandardStream Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"BufferedStandardStream":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.BufferedStandardStream.html\" title=\"struct termcolor::BufferedStandardStream\">BufferedStandardStream</a></code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"struct.BufferedStandardStream.html\" title=\"struct termcolor::BufferedStandardStream\">BufferedStandardStream</a></span>"} Struct termcolor::ColorChoiceParseError === ``` pub struct ColorChoiceParseError { /* private fields */ } ``` An error that occurs when parsing a `ColorChoice` fails. Trait Implementations --- ### impl Clone for ColorChoiceParseError #### fn clone(&self) -> ColorChoiceParseError Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for ColorChoiceParseError ### impl Send for ColorChoiceParseError ### impl Sync for ColorChoiceParseError ### impl Unpin for ColorChoiceParseError ### impl UnwindSafe for ColorChoiceParseError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct termcolor::ColorSpec === ``` pub struct ColorSpec { /* private fields */ } ``` A color specification. Implementations --- ### impl ColorSpec #### pub fn new() -> ColorSpec Create a new color specification that has no colors or styles. #### pub fn fg(&self) -> Option<&ColorGet the foreground color. #### pub fn set_fg(&mut self, color: Option<Color>) -> &mut ColorSpec Set the foreground color. #### pub fn bg(&self) -> Option<&ColorGet the background color. #### pub fn set_bg(&mut self, color: Option<Color>) -> &mut ColorSpec Set the background color. #### pub fn bold(&self) -> bool Get whether this is bold or not. Note that the bold setting has no effect in a Windows console. #### pub fn set_bold(&mut self, yes: bool) -> &mut ColorSpec Set whether the text is bolded or not. Note that the bold setting has no effect in a Windows console. #### pub fn dimmed(&self) -> bool Get whether this is dimmed or not. Note that the dimmed setting has no effect in a Windows console. #### pub fn set_dimmed(&mut self, yes: bool) -> &mut ColorSpec Set whether the text is dimmed or not. Note that the dimmed setting has no effect in a Windows console. #### pub fn italic(&self) -> bool Get whether this is italic or not. Note that the italic setting has no effect in a Windows console. #### pub fn set_italic(&mut self, yes: bool) -> &mut ColorSpec Set whether the text is italicized or not. Note that the italic setting has no effect in a Windows console. #### pub fn underline(&self) -> bool Get whether this is underline or not. Note that the underline setting has no effect in a Windows console. #### pub fn set_underline(&mut self, yes: bool) -> &mut ColorSpec Set whether the text is underlined or not. Note that the underline setting has no effect in a Windows console. #### pub fn strikethrough(&self) -> bool Get whether this is strikethrough or not. Note that the strikethrough setting has no effect in a Windows console. #### pub fn set_strikethrough(&mut self, yes: bool) -> &mut ColorSpec Set whether the text is strikethrough or not. Note that the strikethrough setting has no effect in a Windows console. #### pub fn reset(&self) -> bool Get whether reset is enabled or not. reset is enabled by default. When disabled and using ANSI escape sequences, a “reset” code will be emitted every time a `ColorSpec`’s settings are applied. Note that the reset setting has no effect in a Windows console. #### pub fn set_reset(&mut self, yes: bool) -> &mut ColorSpec Set whether to reset the terminal whenever color settings are applied. reset is enabled by default. When disabled and using ANSI escape sequences, a “reset” code will be emitted every time a `ColorSpec`’s settings are applied. Typically this is useful if callers have a requirement to more scrupulously manage the exact sequence of escape codes that are emitted when using ANSI for colors. Note that the reset setting has no effect in a Windows console. #### pub fn intense(&self) -> bool Get whether this is intense or not. On Unix-like systems, this will output the ANSI escape sequence that will print a high-intensity version of the color specified. On Windows systems, this will output the ANSI escape sequence that will print a brighter version of the color specified. #### pub fn set_intense(&mut self, yes: bool) -> &mut ColorSpec Set whether the text is intense or not. On Unix-like systems, this will output the ANSI escape sequence that will print a high-intensity version of the color specified. On Windows systems, this will output the ANSI escape sequence that will print a brighter version of the color specified. #### pub fn is_none(&self) -> bool Returns true if this color specification has no colors or styles. #### pub fn clear(&mut self) Clears this color specification so that it has no color/style settings. Trait Implementations --- ### impl Clone for ColorSpec #### fn clone(&self) -> ColorSpec Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> ColorSpec Returns the “default value” for a type. #### fn eq(&self, other: &ColorSpec) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Eq for ColorSpec ### impl StructuralEq for ColorSpec ### impl StructuralPartialEq for ColorSpec Auto Trait Implementations --- ### impl RefUnwindSafe for ColorSpec ### impl Send for ColorSpec ### impl Sync for ColorSpec ### impl Unpin for ColorSpec ### impl UnwindSafe for ColorSpec Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct termcolor::HyperlinkSpec === ``` pub struct HyperlinkSpec<'a> { /* private fields */ } ``` A hyperlink specification. Implementations --- ### impl<'a> HyperlinkSpec<'a#### pub fn open(uri: &'a [u8]) -> HyperlinkSpec<'aCreates a new hyperlink specification. #### pub fn close() -> HyperlinkSpec<'aCreates a hyperlink specification representing no hyperlink. #### pub fn uri(&self) -> Option<&'a [u8]Returns the URI of the hyperlink if one is attached to this spec. Trait Implementations --- ### impl<'a> Clone for HyperlinkSpec<'a#### fn clone(&self) -> HyperlinkSpec<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl<'a> RefUnwindSafe for HyperlinkSpec<'a### impl<'a> Send for HyperlinkSpec<'a### impl<'a> Sync for HyperlinkSpec<'a### impl<'a> Unpin for HyperlinkSpec<'a### impl<'a> UnwindSafe for HyperlinkSpec<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct termcolor::NoColor === ``` pub struct NoColor<W>(/* private fields */); ``` Satisfies `WriteColor` but ignores all color options. Implementations --- ### impl<W: Write> NoColor<W#### pub fn new(wtr: W) -> NoColor<WCreate a new writer that satisfies `WriteColor` but drops all color information. #### pub fn into_inner(self) -> W Consume this `NoColor` value and return the inner writer. #### pub fn get_ref(&self) -> &W Return a reference to the inner writer. #### pub fn get_mut(&mut self) -> &mut W Return a mutable reference to the inner writer. Trait Implementations --- ### impl<W: Debug> Debug for NoColor<W#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 🔬This is a nightly-only experimental API. (`can_vector`)Determines if this `Write`r has an efficient `write_vectored` implementation. Read more1.0.0 · source#### fn write_all(&mut self, buf: &[u8]) -> Result<(), ErrorAttempts to write an entire buffer into this writer. Self: Sized, Creates a “by reference” adapter for this instance of `Write`. Returns true if and only if the underlying writer supports colors.#### fn supports_hyperlinks(&self) -> bool Returns true if and only if the underlying writer supports hyperlinks. Returns true if and only if the underlying writer must synchronously interact with an end user’s device in order to control colors. By default, this always returns `false`. Read moreAuto Trait Implementations --- ### impl<W> RefUnwindSafe for NoColor<W>where W: RefUnwindSafe, ### impl<W> Send for NoColor<W>where W: Send, ### impl<W> Sync for NoColor<W>where W: Sync, ### impl<W> Unpin for NoColor<W>where W: Unpin, ### impl<W> UnwindSafe for NoColor<W>where W: UnwindSafe, Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"NoColor<W>":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.NoColor.html\" title=\"struct termcolor::NoColor\">NoColor</a>&lt;W&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;W: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a>&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"struct.NoColor.html\" title=\"struct termcolor::NoColor\">NoColor</a>&lt;W&gt;</span>"} Struct termcolor::ParseColorError === ``` pub struct ParseColorError { /* private fields */ } ``` An error from parsing an invalid color specification. Implementations --- ### impl ParseColorError #### pub fn invalid(&self) -> &str Return the string that couldn’t be parsed as a valid color. Trait Implementations --- ### impl Clone for ParseColorError #### fn clone(&self) -> ParseColorError Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn eq(&self, other: &ParseColorError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Eq for ParseColorError ### impl StructuralEq for ParseColorError ### impl StructuralPartialEq for ParseColorError Auto Trait Implementations --- ### impl RefUnwindSafe for ParseColorError ### impl Send for ParseColorError ### impl Sync for ParseColorError ### impl Unpin for ParseColorError ### impl UnwindSafe for ParseColorError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct termcolor::StandardStream === ``` pub struct StandardStream { /* private fields */ } ``` Satisfies `io::Write` and `WriteColor`, and supports optional coloring to either of the standard output streams, stdout and stderr. Implementations --- ### impl StandardStream #### pub fn stdout(choice: ColorChoice) -> StandardStream Create a new `StandardStream` with the given color preferences that writes to standard output. On Windows, if coloring is desired and a Windows console could not be found, then ANSI escape sequences are used instead. The specific color/style settings can be configured when writing via the `WriteColor` trait. #### pub fn stderr(choice: ColorChoice) -> StandardStream Create a new `StandardStream` with the given color preferences that writes to standard error. On Windows, if coloring is desired and a Windows console could not be found, then ANSI escape sequences are used instead. The specific color/style settings can be configured when writing via the `WriteColor` trait. #### pub fn lock(&self) -> StandardStreamLock<'_Lock the underlying writer. The lock guard returned also satisfies `io::Write` and `WriteColor`. This method is **not reentrant**. It may panic if `lock` is called while a `StandardStreamLock` is still alive. Trait Implementations --- ### impl Debug for StandardStream #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn write(&mut self, b: &[u8]) -> Result<usizeWrite a buffer into this writer, returning how many bytes were written. 🔬This is a nightly-only experimental API. (`can_vector`)Determines if this `Write`r has an efficient `write_vectored` implementation. Read more1.0.0 · source#### fn write_all(&mut self, buf: &[u8]) -> Result<(), ErrorAttempts to write an entire buffer into this writer. Self: Sized, Creates a “by reference” adapter for this instance of `Write`. #### fn supports_color(&self) -> bool Returns true if and only if the underlying writer supports colors.#### fn supports_hyperlinks(&self) -> bool Returns true if and only if the underlying writer supports hyperlinks. Returns true if and only if the underlying writer must synchronously interact with an end user’s device in order to control colors. By default, this always returns `false`. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for StandardStream ### impl Send for StandardStream ### impl Sync for StandardStream ### impl Unpin for StandardStream ### impl UnwindSafe for StandardStream Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"StandardStream":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.StandardStream.html\" title=\"struct termcolor::StandardStream\">StandardStream</a></code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"struct.StandardStream.html\" title=\"struct termcolor::StandardStream\">StandardStream</a></span>","StandardStreamLock<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.StandardStreamLock.html\" title=\"struct termcolor::StandardStreamLock\">StandardStreamLock</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"struct.StandardStreamLock.html\" title=\"struct termcolor::StandardStreamLock\">StandardStreamLock</a>&lt;'a&gt;</span>"} Struct termcolor::StandardStreamLock === ``` pub struct StandardStreamLock<'a> { /* private fields */ } ``` `StandardStreamLock` is a locked reference to a `StandardStream`. This implements the `io::Write` and `WriteColor` traits, and is constructed via the `Write::lock` method. The lifetime `'a` refers to the lifetime of the corresponding `StandardStream`. Trait Implementations --- ### impl<'a> Debug for StandardStreamLock<'a#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 🔬This is a nightly-only experimental API. (`can_vector`)Determines if this `Write`r has an efficient `write_vectored` implementation. Read more1.0.0 · source#### fn write_all(&mut self, buf: &[u8]) -> Result<(), ErrorAttempts to write an entire buffer into this writer. Self: Sized, Creates a “by reference” adapter for this instance of `Write`. Returns true if and only if the underlying writer supports colors.#### fn supports_hyperlinks(&self) -> bool Returns true if and only if the underlying writer supports hyperlinks. Returns true if and only if the underlying writer must synchronously interact with an end user’s device in order to control colors. By default, this always returns `false`. Read moreAuto Trait Implementations --- ### impl<'a> RefUnwindSafe for StandardStreamLock<'a### impl<'a> !Send for StandardStreamLock<'a### impl<'a> Sync for StandardStreamLock<'a### impl<'a> Unpin for StandardStreamLock<'a### impl<'a> UnwindSafe for StandardStreamLock<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum termcolor::Color === ``` pub enum Color { Black, Blue, Green, Red, Cyan, Magenta, Yellow, White, Ansi256(u8), Rgb(u8, u8, u8), // some variants omitted } ``` The set of available colors for the terminal foreground/background. The `Ansi256` and `Rgb` colors will only output the correct codes when paired with the `Ansi` `WriteColor` implementation. The `Ansi256` and `Rgb` color types are not supported when writing colors on Windows using the console. If they are used on Windows, then they are silently ignored and no colors will be emitted. This set may expand over time. This type has a `FromStr` impl that can parse colors from their human readable form. The format is as follows: 1. Any of the explicitly listed colors in English. They are matched case insensitively. 2. A single 8-bit integer, in either decimal or hexadecimal format. 3. A triple of 8-bit integers separated by a comma, where each integer is in decimal or hexadecimal format. Hexadecimal numbers are written with a `0x` prefix. Variants --- ### Black ### Blue ### Green ### Red ### Cyan ### Magenta ### Yellow ### White ### Ansi256(u8) ### Rgb(u8, u8, u8) Trait Implementations --- ### impl Clone for Color #### fn clone(&self) -> Color Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### type Err = ParseColorError The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<Color, ParseColorErrorParses a string `s` to return a value of this type. #### fn eq(&self, other: &Color) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for Color ### impl Eq for Color ### impl StructuralEq for Color ### impl StructuralPartialEq for Color Auto Trait Implementations --- ### impl RefUnwindSafe for Color ### impl Send for Color ### impl Sync for Color ### impl Unpin for Color ### impl UnwindSafe for Color Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum termcolor::ColorChoice === ``` pub enum ColorChoice { Always, AlwaysAnsi, Auto, Never, } ``` ColorChoice represents the color preferences of an end user. The `Default` implementation for this type will select `Auto`, which tries to do the right thing based on the current environment. The `FromStr` implementation for this type converts a lowercase kebab-case string of the variant name to the corresponding variant. Any other string results in an error. Variants --- ### Always Try very hard to emit colors. This includes emitting ANSI colors on Windows if the console API is unavailable. ### AlwaysAnsi AlwaysAnsi is like Always, except it never tries to use anything other than emitting ANSI color codes. ### Auto Try to use colors, but don’t force the issue. If the console isn’t available on Windows, or if TERM=dumb, or if `NO_COLOR` is defined, for example, then don’t use colors. ### Never Never emit colors. Trait Implementations --- ### impl Clone for ColorChoice #### fn clone(&self) -> ColorChoice Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. The default is `Auto`. #### fn default() -> ColorChoice Returns the “default value” for a type. #### type Err = ColorChoiceParseError The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<ColorChoice, ColorChoiceParseErrorParses a string `s` to return a value of this type. #### fn eq(&self, other: &ColorChoice) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for ColorChoice ### impl Eq for ColorChoice ### impl StructuralEq for ColorChoice ### impl StructuralPartialEq for ColorChoice Auto Trait Implementations --- ### impl RefUnwindSafe for ColorChoice ### impl Send for ColorChoice ### impl Sync for ColorChoice ### impl Unpin for ColorChoice ### impl UnwindSafe for ColorChoice Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.
gopkg.in/alexedwards/scs.v1
go
Go
README [¶](#section-readme) --- ### SCS: A HTTP Session Manager [![godoc](https://godoc.org/github.com/alexedwards/scs?status.png)](https://godoc.org/github.com/alexedwards/scs) [![go report card](https://goreportcard.com/badge/github.com/alexedwards/scs)](https://goreportcard.com/report/github.com/alexedwards/scs) SCS is a fast and lightweight HTTP session manager for Go. It features: * Built-in PostgreSQL, MySQL, Redis, Memcached, encrypted cookie and in-memory storage engines. Custom storage engines are also supported. * Supports OWASP good-practices, including absolute and idle session timeouts and easy regeneration of session tokens. * Fast and very memory-efficient performance. * Type-safe and sensible API for managing session data. Safe for concurrent use. * Automatic saving of session data. **Recent changes:** Release v1.0.0 made breaking changes to the package layout and API. If you need the old version please vendor [release v0.1.1](https://github.com/alexedwards/scs/releases/tag/v0.1.1). #### Installation & Usage Install with `go get`: ``` $ go get github.com/alexedwards/scs ``` ##### Basic use ``` package main import ( "io" "net/http" "github.com/alexedwards/scs" ) // Initialize a new encrypted-cookie based session manager and store it in a global // variable. In a real application, you might inject the session manager as a // dependency to your handlers instead. The parameter to the NewCookieManager() // function is a 32 character long random key, which is used to encrypt and // authenticate the session cookies. var sessionManager = scs.NewCookieManager("u46IpCV9y5Vlur8YvODJEhgOY8m9JVE4") func main() { // Set up your HTTP handlers in the normal way. mux := http.NewServeMux() mux.HandleFunc("/put", putHandler) mux.HandleFunc("/get", getHandler) // Wrap your handlers with the session manager middleware. http.ListenAndServe(":4000", sessionManager.Use(mux)) } func putHandler(w http.ResponseWriter, r *http.Request) { // Load the session data for the current request. Any errors are deferred // until you actually use the session data. session := sessionManager.Load(r) // Use the PutString() method to add a new key and associated string value // to the session data. Methods for many other common data types are also // provided. The session data is automatically saved. err := session.PutString(w, "message", "Hello world!") if err != nil { http.Error(w, err.Error(), 500) } } func getHandler(w http.ResponseWriter, r *http.Request) { // Load the session data for the current request. session := sessionManager.Load(r) // Use the GetString() helper to retrieve the string value for the "message" // key from the session data. The zero value for a string is returned if the // key does not exist. message, err := session.GetString("message") if err != nil { http.Error(w, err.Error(), 500) } io.WriteString(w, message) } ``` SCS provides a wide range of functions for working with session data. * `Put…` and `Get…` methods for storing and retrieving a variety of common data types and custom objects. * `Pop…` methods for one-time retrieval of common data types (and custom objects) from the session data. * `Keys` returns an alphabetically-sorted slice of all keys in the session data. * `Exists` returns whether a specific key exists in the session data. * `Remove` removes an individual key and value from the session data. * `Clear` removes all data for the current session. * `RenewToken` creates a new session token. This should be used before privilege changes to help avoid session fixation. * `Destroy` deletes the current session and instructs the browser to delete the session cookie. A full list of available functions can be found in [the GoDoc](https://godoc.org/github.com/alexedwards/scs/#pkg-index). ##### Customizing the session manager The session manager can be configured to customize its behavior. For example: ``` sessionManager = scs.NewCookieManager("u46IpCV9y5Vlur8YvODJEhgOY8m9JVE4") sessionManager.Lifetime(time.Hour) // Set the maximum session lifetime to 1 hour. sessionManager.Persist(true) // Persist the session after a user has closed their browser. sessionManager.Secure(true) // Set the Secure flag on the session cookie. ``` A full list of available settings can be found in [the GoDoc](https://godoc.org/github.com/alexedwards/scs/#pkg-index). ##### Using a different session store The above examples use encrypted cookies to store session data, but SCS also supports a range of server-side stores. | Package | | | --- | --- | | [stores/boltstore](https://godoc.org/github.com/alexedwards/scs/stores/boltstore) | BoltDB-based session store | | [stores/buntstore](https://godoc.org/github.com/alexedwards/scs/stores/buntstore) | BuntDB based session store | | [stores/cookiestore](https://godoc.org/github.com/alexedwards/scs/stores/cookiestore) | Encrypted-cookie session store | | [stores/dynamostore](https://godoc.org/github.com/alexedwards/scs/stores/dynamostore) | DynamoDB-based session store | | [stores/memstore](https://godoc.org/github.com/alexedwards/scs/stores/memstore) | In-memory session store | | [stores/mysqlstore](https://godoc.org/github.com/alexedwards/scs/stores/mysqlstore) | MySQL-based session store | | [stores/pgstore](https://godoc.org/github.com/alexedwards/scs/stores/pgstore) | PostgreSQL-based storage eninge | | [stores/qlstore](https://godoc.org/github.com/alexedwards/scs/stores/qlstore) | QL-based session store | | [stores/redisstore](https://godoc.org/github.com/alexedwards/scs/stores/redisstore) | Redis-based session store | | [stores/memcached](https://godoc.org/github.com/alexedwards/scs/stores/memcachedstore) | Memcached-based session store | ##### Compatibility SCS is designed to be compatible with Go's `net/http` package and the `http.Handler` interface. If you're using the [Echo](https://echo.labstack.com/) framework, the [official session middleware](https://echo.labstack.com/middleware/session) for Echo is likely to be a better fit for your application. ##### Examples * [RequireLogin middleware](https://gist.github.com/alexedwards/6eac2f19b9b5c064ca90f756c32f94cc) Documentation [¶](#section-documentation) --- ### Index [¶](#pkg-index) * [Variables](#pkg-variables) * [type Manager](#Manager) * + [func NewCookieManager(key string) *Manager](#NewCookieManager) + [func NewManager(store Store) *Manager](#NewManager) * + [func (m *Manager) AddToContext(ctx context.Context, session *Session) context.Context](#Manager.AddToContext) + [func (m *Manager) Domain(s string)](#Manager.Domain) + [func (m *Manager) HttpOnly(b bool)](#Manager.HttpOnly) + [func (m *Manager) IdleTimeout(t time.Duration)](#Manager.IdleTimeout) + [func (m *Manager) Lifetime(t time.Duration)](#Manager.Lifetime) + [func (m *Manager) Load(r *http.Request) *Session](#Manager.Load) + [func (m *Manager) LoadFromContext(ctx context.Context) *Session](#Manager.LoadFromContext) + [func (m *Manager) Multi(next http.Handler) http.Handler](#Manager.Multi) + [func (m *Manager) Name(s string)](#Manager.Name) + [func (m *Manager) Path(s string)](#Manager.Path) + [func (m *Manager) Persist(b bool)](#Manager.Persist) + [func (m *Manager) SameSite(s string)](#Manager.SameSite) + [func (m *Manager) Secure(b bool)](#Manager.Secure) + [func (m *Manager) Use(next http.Handler) http.Handler](#Manager.Use) * [type Session](#Session) * + [func (s *Session) Clear(w http.ResponseWriter) error](#Session.Clear) + [func (s *Session) Destroy(w http.ResponseWriter) error](#Session.Destroy) + [func (s *Session) Exists(key string) (bool, error)](#Session.Exists) + [func (s *Session) GetBool(key string) (bool, error)](#Session.GetBool) + [func (s *Session) GetBytes(key string) ([]byte, error)](#Session.GetBytes) + [func (s *Session) GetFloat(key string) (float64, error)](#Session.GetFloat) + [func (s *Session) GetInt(key string) (int, error)](#Session.GetInt) + [func (s *Session) GetInt64(key string) (int64, error)](#Session.GetInt64) + [func (s *Session) GetObject(key string, dst interface{}) error](#Session.GetObject) + [func (s *Session) GetString(key string) (string, error)](#Session.GetString) + [func (s *Session) GetTime(key string) (time.Time, error)](#Session.GetTime) + [func (s *Session) Keys() ([]string, error)](#Session.Keys) + [func (s *Session) PopBool(w http.ResponseWriter, key string) (bool, error)](#Session.PopBool) + [func (s *Session) PopBytes(w http.ResponseWriter, key string) ([]byte, error)](#Session.PopBytes) + [func (s *Session) PopFloat(w http.ResponseWriter, key string) (float64, error)](#Session.PopFloat) + [func (s *Session) PopInt(w http.ResponseWriter, key string) (int, error)](#Session.PopInt) + [func (s *Session) PopInt64(w http.ResponseWriter, key string) (int64, error)](#Session.PopInt64) + [func (s *Session) PopObject(w http.ResponseWriter, key string, dst interface{}) error](#Session.PopObject) + [func (s *Session) PopString(w http.ResponseWriter, key string) (string, error)](#Session.PopString) + [func (s *Session) PopTime(w http.ResponseWriter, key string) (time.Time, error)](#Session.PopTime) + [func (s *Session) PutBool(w http.ResponseWriter, key string, val bool) error](#Session.PutBool) + [func (s *Session) PutBytes(w http.ResponseWriter, key string, val []byte) error](#Session.PutBytes) + [func (s *Session) PutFloat(w http.ResponseWriter, key string, val float64) error](#Session.PutFloat) + [func (s *Session) PutInt(w http.ResponseWriter, key string, val int) error](#Session.PutInt) + [func (s *Session) PutInt64(w http.ResponseWriter, key string, val int64) error](#Session.PutInt64) + [func (s *Session) PutObject(w http.ResponseWriter, key string, val interface{}) error](#Session.PutObject) + [func (s *Session) PutString(w http.ResponseWriter, key string, val string) error](#Session.PutString) + [func (s *Session) PutTime(w http.ResponseWriter, key string, val time.Time) error](#Session.PutTime) + [func (s *Session) Remove(w http.ResponseWriter, key string) error](#Session.Remove) + [func (s *Session) RenewToken(w http.ResponseWriter) error](#Session.RenewToken) + [func (s *Session) Token() string](#Session.Token) + [func (s *Session) Touch(w http.ResponseWriter) error](#Session.Touch) * [type Store](#Store) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) ``` var CookieName = "session" ``` Deprecated: Please use the Manager.Name() method to change the name of the session cookie. ``` var ErrTypeAssertionFailed = [errors](/errors).[New](/errors#New)("type assertion failed") ``` ErrTypeAssertionFailed is returned by operations on session data where the received value could not be type asserted or converted into the required type. ### Functions [¶](#pkg-functions) This section is empty. ### Types [¶](#pkg-types) #### type [Manager](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L14) [¶](#Manager) ``` type Manager struct { // contains filtered or unexported fields } ``` Manager is a session manager. #### func [NewCookieManager](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L135) [¶](#NewCookieManager) ``` func NewCookieManager(key [string](/builtin#string)) *[Manager](#Manager) ``` #### func [NewManager](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L20) [¶](#NewManager) ``` func NewManager(store [Store](#Store)) *[Manager](#Manager) ``` NewManager returns a pointer to a new session manager. #### func (*Manager) [AddToContext](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L131) [¶](#Manager.AddToContext) added in v1.3.0 ``` func (m *[Manager](#Manager)) AddToContext(ctx [context](/context).[Context](/context#Context), session *[Session](#Session)) [context](/context).[Context](/context#Context) ``` AddToContext adds session data to a given context.Context object. #### func (*Manager) [Domain](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L41) [¶](#Manager.Domain) ``` func (m *[Manager](#Manager)) Domain(s [string](/builtin#string)) ``` Domain sets the 'Domain' attribute on the session cookie. By default it will be set to the domain name that the cookie was issued from. #### func (*Manager) [HttpOnly](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L47) [¶](#Manager.HttpOnly) ``` func (m *[Manager](#Manager)) HttpOnly(b [bool](/builtin#bool)) ``` HttpOnly sets the 'HttpOnly' attribute on the session cookie. The default value is true. #### func (*Manager) [IdleTimeout](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L57) [¶](#Manager.IdleTimeout) ``` func (m *[Manager](#Manager)) IdleTimeout(t [time](/time).[Duration](/time#Duration)) ``` IdleTimeout sets the maximum length of time a session can be inactive before it expires. For example, some applications may wish to set this so there is a timeout after 20 minutes of inactivity. The inactivity period is reset whenever the session data is changed (but not read). By default IdleTimeout is not set and there is no inactivity timeout. #### func (*Manager) [Lifetime](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L66) [¶](#Manager.Lifetime) ``` func (m *[Manager](#Manager)) Lifetime(t [time](/time).[Duration](/time#Duration)) ``` Lifetime sets the maximum length of time that a session is valid for before it expires. The lifetime is an 'absolute expiry' which is set when the session is first created and does not change. The default value is 24 hours. #### func (*Manager) [Load](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L112) [¶](#Manager.Load) ``` func (m *[Manager](#Manager)) Load(r *[http](/net/http).[Request](/net/http#Request)) *[Session](#Session) ``` Load returns the session data for the current request. #### func (*Manager) [LoadFromContext](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L117) [¶](#Manager.LoadFromContext) added in v1.3.0 ``` func (m *[Manager](#Manager)) LoadFromContext(ctx [context](/context).[Context](/context#Context)) *[Session](#Session) ``` LoadFromContext returns session data from a given context.Context object. #### func (*Manager) [Multi](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L140) [¶](#Manager.Multi) added in v1.1.0 ``` func (m *[Manager](#Manager)) Multi(next [http](/net/http).[Handler](/net/http#Handler)) [http](/net/http).[Handler](/net/http#Handler) ``` #### func (*Manager) [Name](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L73) [¶](#Manager.Name) added in v1.1.0 ``` func (m *[Manager](#Manager)) Name(s [string](/builtin#string)) ``` Name sets the name of the session cookie. This name should not contain whitespace, commas, semicolons, backslashes, the equals sign or control characters as per RFC6265. #### func (*Manager) [Path](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L80) [¶](#Manager.Path) ``` func (m *[Manager](#Manager)) Path(s [string](/builtin#string)) ``` Path sets the 'Path' attribute on the session cookie. The default value is "/". Passing the empty string "" will result in it being set to the path that the cookie was issued from. #### func (*Manager) [Persist](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L91) [¶](#Manager.Persist) ``` func (m *[Manager](#Manager)) Persist(b [bool](/builtin#bool)) ``` Persist sets whether the session cookie should be persistent or not (i.e. whether it should be retained after a user closes their browser). The default value is false, which means that the session cookie will be destroyed when the user closes their browser. If set to true, explicit 'Expires' and 'MaxAge' values will be added to the cookie and it will be retained by the user's browser until the given expiry time is reached. #### func (*Manager) [SameSite](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L107) [¶](#Manager.SameSite) added in v1.4.0 ``` func (m *[Manager](#Manager)) SameSite(s [string](/builtin#string)) ``` SameSite sets the 'SameSite' attribute on the session cookie. The default value is nil; setting no SameSite attribute. Allowed values are "Lax" and "Strict". Note that "" (empty-string) causes SameSite to NOT be set -- don't confuse this with the cookie's 'SameSite' attribute (without Lax/Strict), which would default to "Strict". #### func (*Manager) [Secure](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L98) [¶](#Manager.Secure) ``` func (m *[Manager](#Manager)) Secure(b [bool](/builtin#bool)) ``` Secure sets the 'Secure' attribute on the session cookie. The default value is false. It's recommended that you set this to true and serve all requests over HTTPS in production environments. #### func (*Manager) [Use](https://github.com/alexedwards/scs/blob/v1.4.1/manager.go#L144) [¶](#Manager.Use) added in v1.1.0 ``` func (m *[Manager](#Manager)) Use(next [http](/net/http).[Handler](/net/http#Handler)) [http](/net/http).[Handler](/net/http#Handler) ``` #### type [Session](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L27) [¶](#Session) ``` type Session struct { // contains filtered or unexported fields } ``` Session contains data for the current session. #### func (*Session) [Clear](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L649) [¶](#Session.Clear) ``` func (s *[Session](#Session)) Clear(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter)) [error](/builtin#error) ``` Clear removes all data for the current session. The session token and lifetime are unaffected. If there is no data in the current session this operation is a no-op. #### func (*Session) [Destroy](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L713) [¶](#Session.Destroy) ``` func (s *[Session](#Session)) Destroy(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter)) [error](/builtin#error) ``` Destroy deletes the current session. The session token and accompanying data are deleted from the session store, and the client is instructed to delete the session cookie. Any further operations on the session in the same request cycle will result in a new session being created. A new empty session will be created for any client that subsequently tries to use the destroyed session token. #### func (*Session) [Exists](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L613) [¶](#Session.Exists) ``` func (s *[Session](#Session)) Exists(key [string](/builtin#string)) ([bool](/builtin#bool), [error](/builtin#error)) ``` Exists returns true if the given key is present in the session data. #### func (*Session) [GetBool](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L232) [¶](#Session.GetBool) ``` func (s *[Session](#Session)) GetBool(key [string](/builtin#string)) ([bool](/builtin#bool), [error](/builtin#error)) ``` GetBool returns the bool value for a given key from the session data. The zero value for a bool (false) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted to a bool. #### func (*Session) [GetBytes](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L478) [¶](#Session.GetBytes) ``` func (s *[Session](#Session)) GetBytes(key [string](/builtin#string)) ([][byte](/builtin#byte), [error](/builtin#error)) ``` GetBytes returns the byte slice ([]byte) value for a given key from the session data. The zero value for a slice (nil) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to []byte. #### func (*Session) [GetFloat](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L376) [¶](#Session.GetFloat) ``` func (s *[Session](#Session)) GetFloat(key [string](/builtin#string)) ([float64](/builtin#float64), [error](/builtin#error)) ``` GetFloat returns the float64 value for a given key from the session data. The zero value for an float (0) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a float64. #### func (*Session) [GetInt](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L277) [¶](#Session.GetInt) ``` func (s *[Session](#Session)) GetInt(key [string](/builtin#string)) ([int](/builtin#int), [error](/builtin#error)) ``` GetInt returns the int value for a given key from the session data. The zero value for an int (0) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a int. #### func (*Session) [GetInt64](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L326) [¶](#Session.GetInt64) ``` func (s *[Session](#Session)) GetInt64(key [string](/builtin#string)) ([int64](/builtin#int64), [error](/builtin#error)) ``` GetInt64 returns the int64 value for a given key from the session data. The zero value for an int (0) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a int64. #### func (*Session) [GetObject](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L534) [¶](#Session.GetObject) ``` func (s *[Session](#Session)) GetObject(key [string](/builtin#string), dst interface{}) [error](/builtin#error) ``` GetObject reads the data for a given session key into an arbitrary object (represented by the dst parameter). It should only be used to retrieve custom data types that have been stored using PutObject. The object represented by dst will remain unchanged if the key does not exist. The dst parameter must be a pointer. #### func (*Session) [GetString](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L187) [¶](#Session.GetString) ``` func (s *[Session](#Session)) GetString(key [string](/builtin#string)) ([string](/builtin#string), [error](/builtin#error)) ``` GetString returns the string value for a given key from the session data. The zero value for a string ("") is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a string. #### func (*Session) [GetTime](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L427) [¶](#Session.GetTime) ``` func (s *[Session](#Session)) GetTime(key [string](/builtin#string)) ([time](/time).[Time](/time#Time), [error](/builtin#error)) ``` GetTime returns the time.Time value for a given key from the session data. The zero value for a time.Time object is returned if the key does not exist (this can be checked for with the time.IsZero method). An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a time.Time. #### func (*Session) [Keys](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L593) [¶](#Session.Keys) ``` func (s *[Session](#Session)) Keys() ([][string](/builtin#string), [error](/builtin#error)) ``` Keys returns a slice of all key names present in the session data, sorted alphabetically. If the session contains no data then an empty slice will be returned. #### func (*Session) [PopBool](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L258) [¶](#Session.PopBool) ``` func (s *[Session](#Session)) PopBool(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string)) ([bool](/builtin#bool), [error](/builtin#error)) ``` PopBool removes the bool value for a given key from the session data and returns it. The zero value for a bool (false) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted to a bool. #### func (*Session) [PopBytes](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L510) [¶](#Session.PopBytes) ``` func (s *[Session](#Session)) PopBytes(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string)) ([][byte](/builtin#byte), [error](/builtin#error)) ``` PopBytes removes the byte slice ([]byte) value for a given key from the session data and returns it. The zero value for a slice (nil) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a []byte. #### func (*Session) [PopFloat](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L404) [¶](#Session.PopFloat) ``` func (s *[Session](#Session)) PopFloat(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string)) ([float64](/builtin#float64), [error](/builtin#error)) ``` PopFloat removes the float64 value for a given key from the session data and returns it. The zero value for an float (0) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a float64. #### func (*Session) [PopInt](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L305) [¶](#Session.PopInt) ``` func (s *[Session](#Session)) PopInt(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string)) ([int](/builtin#int), [error](/builtin#error)) ``` PopInt removes the int value for a given key from the session data and returns it. The zero value for an int (0) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a int. #### func (*Session) [PopInt64](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L354) [¶](#Session.PopInt64) ``` func (s *[Session](#Session)) PopInt64(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string)) ([int64](/builtin#int64), [error](/builtin#error)) ``` PopInt64 remvoes the int64 value for a given key from the session data and returns it. The zero value for an int (0) is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a int64. #### func (*Session) [PopObject](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L578) [¶](#Session.PopObject) ``` func (s *[Session](#Session)) PopObject(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string), dst interface{}) [error](/builtin#error) ``` PopObject removes the data for a given session key and reads it into a custom object (represented by the dst parameter). It should only be used to retrieve custom data types that have been stored using PutObject. The object represented by dst will remain unchanged if the key does not exist. The dst parameter must be a pointer. #### func (*Session) [PopString](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L213) [¶](#Session.PopString) ``` func (s *[Session](#Session)) PopString(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string)) ([string](/builtin#string), [error](/builtin#error)) ``` PopString removes the string value for a given key from the session data and returns it. The zero value for a string ("") is returned if the key does not exist. An ErrTypeAssertionFailed error is returned if the value could not be type asserted to a string. #### func (*Session) [PopTime](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L456) [¶](#Session.PopTime) ``` func (s *[Session](#Session)) PopTime(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string)) ([time](/time).[Time](/time#Time), [error](/builtin#error)) ``` PopTime removes the time.Time value for a given key from the session data and returns it. The zero value for a time.Time object is returned if the key does not exist (this can be checked for with the time.IsZero method). An ErrTypeAssertionFailed error is returned if the value could not be type asserted or converted to a time.Time. #### func (*Session) [PutBool](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L250) [¶](#Session.PutBool) ``` func (s *[Session](#Session)) PutBool(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string), val [bool](/builtin#bool)) [error](/builtin#error) ``` PutBool adds a bool value and corresponding key to the session data. Any existing value for the key will be replaced. #### func (*Session) [PutBytes](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L498) [¶](#Session.PutBytes) ``` func (s *[Session](#Session)) PutBytes(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string), val [][byte](/builtin#byte)) [error](/builtin#error) ``` PutBytes adds a byte slice ([]byte) value and corresponding key to the the session data. Any existing value for the key will be replaced. #### func (*Session) [PutFloat](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L396) [¶](#Session.PutFloat) ``` func (s *[Session](#Session)) PutFloat(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string), val [float64](/builtin#float64)) [error](/builtin#error) ``` PutFloat adds an float64 value and corresponding key to the session data. Any existing value for the key will be replaced. #### func (*Session) [PutInt](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L297) [¶](#Session.PutInt) ``` func (s *[Session](#Session)) PutInt(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string), val [int](/builtin#int)) [error](/builtin#error) ``` PutInt adds an int value and corresponding key to the session data. Any existing value for the key will be replaced. #### func (*Session) [PutInt64](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L346) [¶](#Session.PutInt64) ``` func (s *[Session](#Session)) PutInt64(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string), val [int64](/builtin#int64)) [error](/builtin#error) ``` PutInt64 adds an int64 value and corresponding key to the session data. Any existing value for the key will be replaced. #### func (*Session) [PutObject](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L559) [¶](#Session.PutObject) ``` func (s *[Session](#Session)) PutObject(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string), val interface{}) [error](/builtin#error) ``` PutObject adds an arbitrary object and corresponding key to the the session data. Any existing value for the key will be replaced. The val parameter must be a pointer to your object. PutObject is typically used to store custom data types. It encodes the object into a gob and then into a base64-encoded string which is persisted by the session store. This makes PutObject (and the accompanying GetObject and PopObject functions) comparatively expensive operations. Because gob encoding is used, the fields on custom types must be exported in order to be persisted correctly. Custom data types must also be registered with gob.Register before PutObject is called (see <https://golang.org/pkg/encoding/gob/#Register>). #### func (*Session) [PutString](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L205) [¶](#Session.PutString) ``` func (s *[Session](#Session)) PutString(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string), val [string](/builtin#string)) [error](/builtin#error) ``` PutString adds a string value and corresponding key to the the session data. Any existing value for the key will be replaced. #### func (*Session) [PutTime](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L447) [¶](#Session.PutTime) ``` func (s *[Session](#Session)) PutTime(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string), val [time](/time).[Time](/time#Time)) [error](/builtin#error) ``` PutTime adds an time.Time value and corresponding key to the session data. Any existing value for the key will be replaced. #### func (*Session) [Remove](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L627) [¶](#Session.Remove) ``` func (s *[Session](#Session)) Remove(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter), key [string](/builtin#string)) [error](/builtin#error) ``` Remove deletes the given key and corresponding value from the session data. If the key is not present this operation is a no-op. #### func (*Session) [RenewToken](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L678) [¶](#Session.RenewToken) ``` func (s *[Session](#Session)) RenewToken(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter)) [error](/builtin#error) ``` RenewToken creates a new session token while retaining the current session data. The session lifetime is also reset. The old session token and accompanying data are deleted from the session store. To mitigate the risk of session fixation attacks, it's important that you call RenewToken before making any changes to privilege levels (e.g. login and logout operations). See <https://www.owasp.org/index.php/Session_fixation> for additional information. #### func (*Session) [Token](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L179) [¶](#Session.Token) added in v1.4.0 ``` func (s *[Session](#Session)) Token() [string](/builtin#string) ``` Token returns the token value that represents given session data. NOTE: The method returns the empty string if session hasn't yet been written to the store. If you're using the CookieStore this token will change each time the session is modified. #### func (*Session) [Touch](https://github.com/alexedwards/scs/blob/v1.4.1/session.go#L748) [¶](#Session.Touch) added in v1.1.0 ``` func (s *[Session](#Session)) Touch(w [http](/net/http).[ResponseWriter](/net/http#ResponseWriter)) [error](/builtin#error) ``` Touch writes the session data in order to update the expiry time when an Idle Timeout has been set. If IdleTimeout is not > 0, then Touch is a no-op. #### type [Store](https://github.com/alexedwards/scs/blob/v1.4.1/store.go#L6) [¶](#Store) ``` type Store interface { // Delete should remove the session token and corresponding data from the // session store. If the token does not exist then Delete should be a no-op // and return nil (not an error). Delete(token [string](/builtin#string)) (err [error](/builtin#error)) // Find should return the data for a session token from the session store. // If the session token is not found or is expired, the found return value // should be false (and the err return value should be nil). Similarly, tampered // or malformed tokens should result in a found return value of false and a // nil err value. The err return value should be used for system errors only. Find(token [string](/builtin#string)) (b [][byte](/builtin#byte), found [bool](/builtin#bool), err [error](/builtin#error)) // Save should add the session token and data to the session store, with // the given expiry time. If the session token already exists, then the data // and expiry time should be overwritten. Save(token [string](/builtin#string), b [][byte](/builtin#byte), expiry [time](/time).[Time](/time#Time)) (err [error](/builtin#error)) } ``` Store is the interface for session stores.
CB2
cran
R
Package ‘CB2’ October 12, 2022 Type Package Title CRISPR Pooled Screen Analysis using Beta-Binomial Test Version 1.3.4 Date 2020-07-23 Description Provides functions for hit gene identification and quantification of sgRNA (single- guided RNA) abundances for CRISPR (Clustered Regularly Interspaced Short Palindromic Re- peats) pooled screen data analysis. Details are in Jeong et al. (2019) <doi:10.1101/gr.245571.118> and Bag- gerly et al. (2003) <doi:10.1093/bioinformatics/btg173>. Depends R (>= 3.5.0) License MIT + file LICENSE LazyData true Imports Rcpp (>= 0.12.16), metap, magrittr, dplyr, tibble, stringr, ggplot2, tidyr, glue, pheatmap, tools, readr, parallel, R.utils LinkingTo Rcpp, RcppArmadillo Suggests testthat, knitr, rmarkdown RoxygenNote 7.1.1 Encoding UTF-8 VignetteBuilder knitr NeedsCompilation yes Author <NAME> [aut, cre] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2020-07-24 09:42:24 UTC R topics documented: calc_mappabilit... 2 Evers_CRISPRn_RT11... 3 fit_a... 3 get_CP... 4 join_count_and_desig... 5 measure_gene_stat... 5 measure_sgrna_stat... 6 plot_corr_heatma... 8 plot_count_distributio... 8 plot_dotplo... 9 plot_PC... 10 quan... 10 run_estimatio... 11 run_sgrna_quan... 12 Sanson_CRISPRn_A37... 13 calc_mappability A function to calculate the mappabilities of each NGS sample. Description A function to calculate the mappabilities of each NGS sample. Usage calc_mappability(count_obj, df_design) Arguments count_obj A list object is created by ‘run_sgrna_quant‘. df_design The table contains a study design. Examples library(CB2) library(magrittr) library(tibble) library(dplyr) library(glue) FASTA <- system.file("extdata", "toydata", "small_sample.fasta", package = "CB2") ex_path <- system.file("extdata", "toydata", package = "CB2") df_design <- tribble( ~group, ~sample_name, "Base", "Base1", "Base", "Base2", "High", "High1", "High", "High2") %>% mutate(fastq_path = glue("{ex_path}/{sample_name}.fastq")) cb2_count <- run_sgrna_quant(FASTA, df_design) calc_mappability(cb2_count, df_design) Evers_CRISPRn_RT112 A benchmark CRISPRn pooled screen data from Evers et al. Description A benchmark CRISPRn pooled screen data from Evers et al. Usage data(Evers_CRISPRn_RT112) Format The data object is a list and contains below information: count The count matrix from Evers et al.’s paper and contains the CRISPRn screening result using RT112 cell-line. It contains three different replicates for T0 (before) and contains different three replicates for T1 (after). egenes The list of 46 essential genes used in Evers et al.’s study. ngenes The list of 47 non-essential genes used in Evers et al.’s study. design The data.frame contains study design. sg_stat The data.frame contains the sgRNA-level statistics. gene_stat The data.frame contains the gene-level statistics. Source https://www.ncbi.nlm.nih.gov/pubmed/27111720 fit_ab A C++ function to perform a parameter estimation for the sgRNA- level test. It will estimate two different parameters ‘phat‘ and ‘vhat,‘ and we assume input count data follows the beta-binomial distribu- tion. Dr. <NAME> initially implemented this code in Matlab, and it has been rewritten it in C++ for the speed-up. Description A C++ function to perform a parameter estimation for the sgRNA-level test. It will estimate two different parameters ‘phat‘ and ‘vhat,‘ and we assume input count data follows the beta-binomial distribution. Dr. <NAME> initially implemented this code in Matlab, and it has been rewritten it in C++ for the speed-up. Usage fit_ab(xvec, nvec) Arguments xvec a matrix contains sgRNA read counts. nvec a vector contains the library size. get_CPM A function to normalize sgRNA read counts. Description A function to normalize sgRNA read counts. Usage get_CPM(sgcount) Arguments sgcount The input table contains read counts of sgRNAs for each sample A function to calculate the CPM (Counts Per Million) (required) Value a normalized CPM table will be returned Examples library(CB2) data(Evers_CRISPRn_RT112) get_CPM(Evers_CRISPRn_RT112$count) join_count_and_design A function to join a count table and a design table. Description A function to join a count table and a design table. Usage join_count_and_design(sgcount, df_design) Arguments sgcount The input matrix contains read counts of sgRNAs for each sample. df_design The table contains a study design. Value A tall-thin and combined table of the sgRNA read counts and study design will be returned. Examples library(CB2) data(Evers_CRISPRn_RT112) head(join_count_and_design(Evers_CRISPRn_RT112$count, Evers_CRISPRn_RT112$design)) measure_gene_stats A function to perform gene-level test using a sgRNA-level statistics. Description A function to perform gene-level test using a sgRNA-level statistics. Usage measure_gene_stats(sgrna_stat, logFC_level = "sgRNA") Arguments sgrna_stat A data frame created by ‘measure_sgrna_stats’ logFC_level The level of ‘logFC’ value. It can be ‘gene’ or ‘sgRNA’. Value A table contains the gene-level test result, and the table contains these columns: • ‘gene’: Theg gene name to be tested. • ‘n_sgrna’: The number of sgRNA targets the gene in the library. • ‘cpm_a’: The mean of CPM of sgRNAs within the first group. • ‘cpm_b’: The mean of CPM of sgRNAs within the second group. • ‘logFC’: The log fold change of the gene between two groups. Taking the mean of sgRNA ‘logFC’s is default, and ‘logFC‘ is calculated by ‘log2(cpm_b+1) - log2(cpm_a+1)’ if ‘logFC_level’ parameter is set to ‘gene’. • ‘p_ts’: The p-value indicates a difference between the two groups at the gene-level. • ‘p_pa’: The p-value indicates enrichment of the first group at the gene-level. • ‘p_pb’: The p-value indicates enrichment of the second group at the gene-level. • ‘fdr_ts’: The adjusted P-value of ‘p_ts’. • ‘fdr_pa’: The adjusted P-value of ‘p_pa’. • ‘fdr_pb’: The adjusted P-value of ‘p_pb’. Examples data(Evers_CRISPRn_RT112) measure_gene_stats(Evers_CRISPRn_RT112$sg_stat) measure_sgrna_stats A function to perform a statistical test at a sgRNA-level Description A function to perform a statistical test at a sgRNA-level Usage measure_sgrna_stats( sgcount, design, group_a, group_b, delim = "_", ge_id = NULL, sg_id = NULL ) Arguments sgcount This data frame contains read counts of sgRNAs for the samples. design This table contains study design. It has to contain ‘group.‘ group_a The first group to be tested. group_b The second group to be tested. delim The delimiter between a gene name and a sgRNA ID. It will be used if only rownames contains sgRNA ID. ge_id The column name of the gene column. sg_id The column/columns of sgRNA identifiers. Value A table contains the sgRNA-level test result, and the table contains these columns: • ‘sgRNA’: The sgRNA identifier. • ‘gene’: The gene is the target of the sgRNA • ‘n_a’: The number of replicates of the first group. • ‘n_b’: The number of replicates of the second group. • ‘phat_a’: The proportion value of the sgRNA for the first group. • ‘phat_b’: The proportion value of the sgRNA for the second group. • ‘vhat_a’: The variance of the sgRNA for the first group. • ‘vhat_b’: The variance of the sgRNA for the second group. • ‘cpm_a’: The mean CPM of the sgRNA within the first group. • ‘cpm_b’: The mean CPM of the sgRNA within the second group. • ‘logFC’: The log fold change of sgRNA between two groups. • ‘t_value’: The value for the t-statistics. • ‘df’: The value of the degree of freedom, and will be used to calculate the p-value of the sgRNA. • ‘p_ts’: The p-value indicates a difference between the two groups. • ‘p_pa’: The p-value indicates enrichment of the first group. • ‘p_pb’: The p-value indicates enrichment of the second group. • ‘fdr_ts’: The adjusted P-value of ‘p_ts’. • ‘fdr_pa’: The adjusted P-value of ‘p_pa’. • ‘fdr_pb’: The adjusted P-value of ‘p_pb’. Examples library(CB2) data(Evers_CRISPRn_RT112) measure_sgrna_stats(Evers_CRISPRn_RT112$count, Evers_CRISPRn_RT112$design, "before", "after") plot_corr_heatmap A function to show a heatmap sgRNA-level corrleations of the NGS samples. Description A function to show a heatmap sgRNA-level corrleations of the NGS samples. Usage plot_corr_heatmap(sgcount, df_design, cor_method = "pearson") Arguments sgcount The input matrix contains read counts of sgRNAs for each sample. df_design The table contains a study design. cor_method A string parameter of the correlation measure. One of the three - "pearson", "kendall", or "spearman" will be the string. Value A pheatmap object contains the correlation heatmap library(CB2) data(Evers_CRISPRn_RT112) plot_corr_heatmap(Evers_CRISPRn_RT112$count, Ev- ers_CRISPRn_RT112$design) plot_count_distribution A function to plot read count distribution. Description A function to plot read count distribution. Usage plot_count_distribution(sgcount, df_design, add_dots = FALSE) Arguments sgcount The input matrix contains read counts of sgRNAs for each sample. df_design The table contains a study design. add_dots The function will display dots of sgRNA counts if it is set to ‘TRUE‘. Value A ggplot2 object contains a read count distribution plot for ‘sgcount‘. Examples library(CB2) data(Evers_CRISPRn_RT112) cpm <- get_CPM(Evers_CRISPRn_RT112$count) plot_count_distribution(cpm, Evers_CRISPRn_RT112$design) plot_dotplot A function to visualize dot plots for a gene. Description A function to visualize dot plots for a gene. Usage plot_dotplot(sgcount, df_design, gene, ge_id = NULL, sg_id = NULL) Arguments sgcount The input matrix contains read counts of sgRNAs for each sample. df_design The table contains a study design. gene The gene to be shown. ge_id A name of the column contains gene names. sg_id A name of the column contains sgRNA IDs. Value A ggplot2 object contains dot plots of sgRNA read counts for a gene. Examples library(CB2) data(Evers_CRISPRn_RT112) plot_dotplot(get_CPM(Evers_CRISPRn_RT112$count), Evers_CRISPRn_RT112$design, "RPS7") plot_PCA A function to plot the first two principal components of samples. Description This function will perform a principal component analysis, and it returns a ggplot object of the PCA plot. Usage plot_PCA(sgcount, df_design) Arguments sgcount The input matrix contains read counts of sgRNAs for each sample. df_design The table contains a study design. Value A ggplot2 object contains a PCA plot for the input. library(CB2) data(Evers_CRISPRn_RT112) plot_PCA(Evers_CRISPRn_RT112$count, Evers_CRISPRn_RT112$design) quant A C++ function to quantify sgRNA abundance from NGS samples. Description A C++ function to quantify sgRNA abundance from NGS samples. Usage quant(ref_path, fastq_path, verbose = FALSE) Arguments ref_path the path of the annotation file and it has to be a FASTA formatted file. fastq_path a list of the FASTQ files. verbose Display some logs during the quantification if it is set to ‘true‘. run_estimation A function to perform a statistical test at a sgRNA-level, deprecated. Description A function to perform a statistical test at a sgRNA-level, deprecated. Usage run_estimation( sgcount, design, group_a, group_b, delim = "_", ge_id = NULL, sg_id = NULL ) Arguments sgcount This data frame contains read counts of sgRNAs for the samples. design This table contains study design. It has to contain ‘group.‘ group_a The first group to be tested. group_b The second group to be tested. delim The delimiter between a gene name and a sgRNA ID. It will be used if only rownames contains sgRNA ID. ge_id The column name of the gene column. sg_id The column/columns of sgRNA identifiers. Value A table contains the sgRNA-level test result, and the table contains these columns: • ‘sgRNA’: The sgRNA identifier. • ‘gene’: The gene is the target of the sgRNA • ‘n_a’: The number of replicates of the first group. • ‘n_b’: The number of replicates of the second group. • ‘phat_a’: The proportion value of the sgRNA for the first group. • ‘phat_b’: The proportion value of the sgRNA for the second group. • ‘vhat_a’: The variance of the sgRNA for the first group. • ‘vhat_b’: The variance of the sgRNA for the second group. • ‘cpm_a’: The mean CPM of the sgRNA within the first group. • ‘cpm_b’: The mean CPM of the sgRNA within the second group. • ‘logFC’: The log fold change of sgRNA between two groups. • ‘t_value’: The value for the t-statistics. • ‘df’: The value of the degree of freedom, and will be used to calculate the p-value of the sgRNA. • ‘p_ts’: The p-value indicates a difference between the two groups. • ‘p_pa’: The p-value indicates enrichment of the first group. • ‘p_pb’: The p-value indicates enrichment of the second group. • ‘fdr_ts’: The adjusted P-value of ‘p_ts’. • ‘fdr_pa’: The adjusted P-value of ‘p_pa’. • ‘fdr_pb’: The adjusted P-value of ‘p_pb’. run_sgrna_quant A function to run a sgRNA quantification algorithm from NGS sample Description A function to run a sgRNA quantification algorithm from NGS sample Usage run_sgrna_quant(lib_path, design, map_path = NULL, ncores = 1, verbose = FALSE) Arguments lib_path The path of the FASTA file. design A table contains the study design. It must contain ‘fastq_path‘ and ‘sample_name.‘ map_path The path of file contains gene-sgRNA mapping. ncores The number that indicates how many processors will be used with a paralleliza- tion. The parallelization will be enabled if users do not set the parameter as ‘-1“ (it means the full physical cores will be used) or greater than ‘1‘. verbose Display some logs during the quantification if it is set to ‘TRUE‘ Value It will return a list, and the list contains three elements. The first element (‘count’) is a data frame contains the result of the quantification for each sample. The second element (‘total’) is a numeric vector contains the total number of reads of each sample. The last element (‘sequence’) a data frame contains the sequence of each sgRNA in the library. Examples library(CB2) library(magrittr) library(tibble) library(dplyr) library(glue) FASTA <- system.file("extdata", "toydata", "small_sample.fasta", package = "CB2") ex_path <- system.file("extdata", "toydata", package = "CB2") df_design <- tribble( ~group, ~sample_name, "Base", "Base1", "Base", "Base2", "High", "High1", "High", "High2") %>% mutate(fastq_path = glue("{ex_path}/{sample_name}.fastq")) cb2_count <- run_sgrna_quant(FASTA, df_design) Sanson_CRISPRn_A375 A benchmark CRISPRn pooled screen data from Sanson et al. Description A benchmark CRISPRn pooled screen data from Sanson et al. Usage data(Sanson_CRISPRn_A375) Format The data object is a list and contains below information: count The count matrix from Sanson et al.’s paper and contains the CRISPRn screening result using A375 cell-line. It contains a sample of plasimd, and three biological replicates after three weeks. egenes The list of 1,580 essential genes used in Sanson et al.’s study. ngenes The list of 927 non-essential genes used in Sanson et al.’s study. design The data.frame contains study design. Source https://www.ncbi.nlm.nih.gov/pubmed/30575746
aigc_store
rust
Rust
Crate aigc_store === Storage of core types using RocksDB. Re-exports --- * `pub use crate::lmdb::*;` Modules --- * leaf_setThe Aigc leaf_set implementation. Compact (roaring) bitmap representing the set of leaf positions that exist and are not currently pruned in the MMR. * lmdbStorage of core types using LMDB. * pmmrImplementation of the persistent Backend for the prunable MMR tree. * prune_listThe Aigc “Prune List” implementation. * typesCommon storage-related types Functions --- * read_bitmapRead Bitmap from a file * save_via_temp_fileCreates temporary file with name created by adding `temp_suffix` to `path`. Applies writer function to it and renames temporary file into original specified by `path`. * to_keyBuild a db key from a prefix and a byte vector identifier. * to_key_u64Build a db key from a prefix and a byte vector identifier and numeric identifier * u64_to_keyBuild a db key from a prefix and a numeric identifier. Crate aigc_store === Storage of core types using RocksDB. Re-exports --- * `pub use crate::lmdb::*;` Modules --- * leaf_setThe Aigc leaf_set implementation. Compact (roaring) bitmap representing the set of leaf positions that exist and are not currently pruned in the MMR. * lmdbStorage of core types using LMDB. * pmmrImplementation of the persistent Backend for the prunable MMR tree. * prune_listThe Aigc “Prune List” implementation. * typesCommon storage-related types Functions --- * read_bitmapRead Bitmap from a file * save_via_temp_fileCreates temporary file with name created by adding `temp_suffix` to `path`. Applies writer function to it and renames temporary file into original specified by `path`. * to_keyBuild a db key from a prefix and a byte vector identifier. * to_key_u64Build a db key from a prefix and a byte vector identifier and numeric identifier * u64_to_keyBuild a db key from a prefix and a numeric identifier. Module aigc_store::lmdb === Storage of core types using LMDB. Structs --- * BatchBatch to write multiple Writeables to db in an atomic manner. * PrefixIteratorAn iterator based on key prefix. Caller is responsible for deserialization of the data. * StoreLMDB-backed store facilitating data access and serialization. All writes are done through a Batch abstraction providing atomicity. Enums --- * ErrorMain error type for this lmdb Constants --- * ALLOC_CHUNK_SIZE_DEFAULTnumber of bytes to grow the database by when needed * ALLOC_CHUNK_SIZE_DEFAULT_TESTAnd for test mode, to avoid too much disk allocation on windows Functions --- * option_to_not_foundunwraps the inner option by converting the none case to a not found error Module aigc_store::leaf_set === The Aigc leaf_set implementation. Compact (roaring) bitmap representing the set of leaf positions that exist and are not currently pruned in the MMR. Structs --- * LeafSetCompact (roaring) bitmap representing the set of positions of leaves that are currently unpruned in the MMR. Module aigc_store::pmmr === Implementation of the persistent Backend for the prunable MMR tree. Structs --- * PMMRBackendPMMR persistent backend implementation. Relies on multiple facilities to handle writing, reading and pruning. Constants --- * PMMR_FILESThe list of PMMR_Files for internal purposes Functions --- * clean_files_by_prefixQuietly clean a directory up based on a given prefix. If the file was accessed within cleanup_duration_seconds from the beginning of the function call, it will not be deleted. To delete all files, set cleanup_duration_seconds to zero. Module aigc_store::prune_list === The Aigc “Prune List” implementation. Maintains a set of pruned root node positions that define the pruned and compacted “gaps” in the MMR data and hash files. The root itself is maintained in the hash file, but all positions beneath the root are compacted away. All positions to the right of a pruned node must be shifted the appropriate amount when reading from the hash and data files. Structs --- * PruneListMaintains a list of previously pruned nodes in PMMR, compacting the list as parents get pruned and allowing checking whether a leaf is pruned. Given a node’s position, computes how much it should get shifted given the subtrees that have been pruned before. Module aigc_store::types === Common storage-related types Structs --- * AppendOnlyFileWrapper for a file that can be read at any position (random read) but for which writes are append only. Reads are backed by a memory map (mmap(2)), relying on the operating system for fast access and caching. The memory map is reallocated to expand it when new writes are flushed. * DataFileData file (MMR) wrapper around an append-only file. * SizeEntryRepresents a single entry in the size_file. Offset (in bytes) and size (in bytes) of a variable sized entry in the corresponding data_file. i.e. To read a single entry from the data_file at position p, read the entry in the size_file to obtain the offset (and size) and then read those bytes from the data_file. Enums --- * SizeInfoAre we dealing with “fixed size” data or “variable size” data in a data file? Function aigc_store::read_bitmap === ``` pub fn read_bitmap<P: AsRef<Path>>(file_path: P) -> Result<Bitmap> ``` Read Bitmap from a file Function aigc_store::save_via_temp_file === ``` pub fn save_via_temp_file<F, P, E>( path: P, temp_suffix: E, writer: F ) -> Result<(), Error>where F: FnMut(&mut File) -> Result<(), Error>, P: AsRef<Path>, E: AsRef<OsStr>, ``` Creates temporary file with name created by adding `temp_suffix` to `path`. Applies writer function to it and renames temporary file into original specified by `path`. Function aigc_store::to_key === ``` pub fn to_key<K: AsRef<[u8]>>(prefix: u8, k: K) -> Vec<u8``` Build a db key from a prefix and a byte vector identifier. {"Vec<u8>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html\" title=\"struct alloc::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html\" title=\"struct alloc::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/alloc/trait.Allocator.html\" title=\"trait core::alloc::Allocator\">Allocator</a>,</span></span>"} Function aigc_store::to_key_u64 === ``` pub fn to_key_u64<K: AsRef<[u8]>>(prefix: u8, k: K, val: u64) -> Vec<u8``` Build a db key from a prefix and a byte vector identifier and numeric identifier {"Vec<u8>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html\" title=\"struct alloc::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html\" title=\"struct alloc::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/alloc/trait.Allocator.html\" title=\"trait core::alloc::Allocator\">Allocator</a>,</span></span>"} Function aigc_store::u64_to_key === ``` pub fn u64_to_key(prefix: u8, val: u64) -> Vec<u8``` Build a db key from a prefix and a numeric identifier. {"Vec<u8>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html\" title=\"struct alloc::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html\" title=\"struct alloc::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/alloc/trait.Allocator.html\" title=\"trait core::alloc::Allocator\">Allocator</a>,</span></span>"}
skpr
cran
R
Package ‘skpr’ June 16, 2023 Title Design of Experiments Suite: Generate and Evaluate Optimal Designs Date 2023-06-15 Version 1.4.0 Description Generates and evaluates D, I, A, Alias, E, T, and G optimal designs. Supports genera- tion and evaluation of blocked and split/split-split/.../N-split plot designs. Includes paramet- ric and Monte Carlo power evaluation functions, and supports calculating power for censored re- sponses. Provides a framework to evaluate power using functions provided in other pack- ages or written by the user. Includes a Shiny graphical user interface that displays the underly- ing code used to create and evaluate the design to improve ease-of-use and make analy- ses more reproducible. For details, see Morgan-Wall et al. (2021) <doi:10.18637/jss.v099.i01>. Copyright Institute for Defense Analyses Depends R (>= 3.0.2), shiny License GPL-3 RoxygenNote 7.2.3 Imports utils, iterators, stats, lme4, Rcpp (>= 0.11.0), rintrojs, shinythemes, foreach, doParallel, survival, future, promises, shinyjs, car, viridis, magrittr, lmerTest, methods, lazyeval, progress, gt, scales, doRNG LinkingTo Rcpp, RcppEigen Suggests testthat, mbest, ggplot2, lmtest, cli, gridExtra Encoding UTF-8 URL https://github.com/tylermorganwall/skpr, https://tylermorganwall.github.io/skpr/ BugReports https://github.com/tylermorganwall/skpr/issues NeedsCompilation yes Author <NAME> [aut, cre], <NAME> [aut] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2023-06-16 16:10:02 UTC R topics documented: calculate_power_curve... 2 contr.simple... 4 eval_desig... 5 eval_design_custom_m... 9 eval_design_m... 12 eval_design_survival_m... 17 gen_desig... 21 get_attribut... 28 get_optimalit... 29 get_power_curve_outpu... 30 plot_correlation... 31 plot_fd... 32 print.skpr_eval_outpu... 33 print.skpr_power_curve_outpu... 34 skprGU... 35 skprGUIbrowse... 35 skprGUIserve... 36 %>... 36 calculate_power_curves Calculate Power Curves Description Calculate and optionally plot power curves for different effect sizes and trial counts. This function takes a Usage calculate_power_curves( trials, effectsize = 1, candidateset = NULL, model = NULL, alpha = 0.05, gen_args = list(), eval_function = "eval_design", eval_args = list(), random_seed = 123, iterate_seed = FALSE, plot_results = TRUE, auto_scale = TRUE, x_breaks = NULL, y_breaks = seq(0, 1, by = 0.1), ggplot_elements = list() ) Arguments trials A numeric vector indicating the trial(s) used when computing the power curve. If a single value, this will be fixed and only ‘effectsize‘ will be varied. effectsize Default ‘1‘. A numeric vector indicating the effect size(s) used when computing the power curve. If a single value, this will be fixed and only ‘trials‘ will be var- ied. If using a length-2 effect size with ‘eval_design_mc()‘ (such as a binomial probability interval), the effect size pairs can be input as entries in a list. candidateset Default ‘NULL‘. The candidate set (see ‘gen_design()‘ documentation for more information). Provided to aid code completion: can also be provided in ‘gen_args‘. model Default ‘NULL‘. The model (see ‘gen_design()‘ and ‘eval_design()‘ documen- tation for more information). Provided to aid code completion: can also be provided in ‘gen_args‘/‘eval_args‘. alpha Default ‘0.05‘. The allowable Type-I error rate (see ‘eval_design()‘ documen- tation for more information). Provided to aid code completion: can also be provided in ‘eval_args‘. gen_args Default ‘list()‘. A list of argument/value pairs to specify the design generation parameters for ‘gen_design()‘. eval_function Default ‘"eval_design"‘. A string (or function) specifying the skpr power eval- uation function. Can also be ‘"eval_design_mc"‘, ‘"eval_design_survival_mc"‘, and ‘"eval_design_custom_mc"‘. eval_args Default ‘list()‘. A list of argument/value pairs to specify the design power eval- uation parameters for ‘eval_function‘. random_seed Default ‘123‘. The random seed used to generate and then evaluate the design. The seed is set right before design generation. iterate_seed Default ‘FALSE‘. This will iterate the random seed with each new design. Set this to ‘TRUE‘ to add more variability to the design generation process. plot_results Default ‘TRUE‘. Whether to print out a plot of the power curves in addition to the data frame of results. Requires ‘ggplot2‘. auto_scale Default ‘TRUE‘. Whether to automatically scale the y-axis to 0 and 1. x_breaks Default ‘NULL‘, automaticly generated by ggplot2. y_breaks Default ‘seq(0,1,by=0.1)‘. Y-axis breaks. ggplot_elements Default ‘list()‘. Extra ‘ggplot2‘ elements to customize the plot, passed in as elements in a list. Value A data.frame of power values with design generation information. Examples if(skpr:::run_documentation()) { cand_set = expand.grid(brew_temp = c(80, 85, 90), altitude = c(0, 2000, 4000), bean_sun = c("low", "partial", "high")) #Plot power for a linear model with all interactions calculate_power_curves(trials=seq(10,60,by=1), candidateset = cand_set, model = ~.*., alpha = 0.05, effectsize = 1, eval_function = "eval_design") } if(skpr:::run_documentation()) { #Add multiple effect sizes calculate_power_curves(trials=seq(10,60,by=1), candidateset = cand_set, model = ~.*., alpha = 0.05, effectsize = c(1,2), eval_function = "eval_design") } if(skpr:::run_documentation()) { #Generate power curve for a binomial model calculate_power_curves(trials=seq(50,150,by=10), candidateset = cand_set, model = ~., effectsize = c(0.6,0.9), eval_function = "eval_design_mc", eval_args = list(nsim = 100, glmfamily = "binomial")) } if(skpr:::run_documentation()) { #Generate power curve for a binomial model and multiple effect sizes calculate_power_curves(trials=seq(50,150,by=10), candidateset = cand_set, model = ~., effectsize = list(c(0.5,0.9),c(0.6,0.9)), eval_function = "eval_design_mc", eval_args = list(nsim = 100, glmfamily = "binomial")) } contr.simplex Orthonormal Contrast Generator Description Generates orthonormal (orthogonal and normalized) contrasts. Each row is the vertex of an N- dimensional simplex. The only exception are contrasts for the 2-level case, which return 1 and -1. Usage contr.simplex(n, size = NULL) Arguments n The number of levels in the catagorical variable. If this is a factor or character vector, ‘n‘ will be ‘length(n)‘ size Default ‘1‘. The length of the simplex vector. Value A matrix of Orthonormal contrasts. Examples contr.simplex(4) eval_design Calculate Power of an Experimental Design Description Evaluates the power of an experimental design, for normal response variables, given the design’s run matrix and the statistical model to be fit to the data. Returns a data frame of parameter and effect powers. Designs can consist of both continuous and categorical factors. By default, eval_design assumes a signal-to-noise ratio of 2, but this can be changed with the effectsize or anticoef parameters. Usage eval_design( design, model = NULL, alpha = 0.05, blocking = NULL, anticoef = NULL, effectsize = 2, varianceratios = NULL, contrasts = contr.sum, conservative = FALSE, reorder_factors = FALSE, detailedoutput = FALSE, advancedoptions = NULL, ... ) Arguments design The experimental design. Internally, eval_design rescales each numeric col- umn to the range [-1, 1], so you do not need to do this scaling manually. model The model used in evaluating the design. If this is missing and the design was generated with skpr, the generating model will be used. It can be a subset of the model used to generate the design, or include higher order effects not in the original design generation. It cannot include factors that are not present in the experimental design. alpha Default ‘0.05‘. The specified type-I error. blocking Default ‘NULL‘. If ‘TRUE‘, eval_design will look at the rownames (or block- ing columns) to determine blocking structure. Default FALSE. anticoef The anticipated coefficients for calculating the power. If missing, coefficients will be automatically generated based on the effectsize argument. effectsize Default ‘2‘. The signal-to-noise ratio. For continuous factors, this specifies the difference in response between the highest and lowest levels of the factor (which are -1 and +1 after eval_design normalizes the input data), assuming that the root mean square error is 1. If you do not specify anticoef, the anticipated co- efficients will be half of effectsize. If you do specify anticoef, effectsize will be ignored. varianceratios Default ‘NULL‘. The ratio of the whole plot variance to the run-to-run variance. If not specified during design generation, this will default to 1. For designs with more than one subplot this ratio can be a vector specifying the variance ratio for each subplot (comparing to the run-to-run variance). Otherwise, it will use a single value for all strata. contrasts Default contr.sum. The function to use to encode the categorical factors in the model matrix. If the user has specified their own contrasts for a categorical factor using the contrasts function, those will be used. Otherwise, skpr will use ‘contr.sum‘. conservative Specifies whether default method for generating anticipated coefficents should be conservative or not. ‘TRUE‘ will give the most conservative estimate of power by setting all but one (or multiple if they are equally low) level in each categorical factor’s anticipated coefficients to zero. Default ‘FALSE‘. reorder_factors Default ‘FALSE‘. If ‘TRUE‘, the levels will be reordered to generate the most conservative calculation of effect power. The function searches through all pos- sible reference levels for a given factor and chooses the one that results in the lowest effect power. The reordering will be presenting in the output when ‘de- tailedoutput = TRUE‘. detailedoutput If ‘TRUE“, return additional information about evaluation in results. Default FALSE. advancedoptions Default ‘NULL‘. A named list with parameters to specify additional attributes to calculate. Options: ‘aliaspower‘ gives the degree at which the Alias matrix should be calculated. ... Additional arguments. Details This function evaluates the power of experimental designs. If the design is has no blocking or restrictions on randomization, the model assumed is: y = Xβ + . If the design is a split-plot design, the model is as follows: y = Xβ + Zbi + ij , Here, y is the vector of experimental responses, X is the model matrix, β is the vector of model coefficients, Zi are the blocking indicator, bi is the random variable associated with the ith block, and  is a random variable normally distributed with zero mean and unit variance (root-mean-square error is 1.0). eval_design calculates both parameter power as well as effect power, defined as follows: 1) Parameter power is the probability of rejecting the hypothesis H0 : βi = 0, where βi is a single parameter in the model 2) Effect power is the probability of rejecting the hypothesis H0 : β1 = β2 = ... = βn 0 for all n coefficients for a categorical factor. The two power types are equivalent for continuous factors and two-level categorical factors, but they will differ for categorical factors with three or more levels. For split-plot designs, the degrees of freedom are allocated to each term according to the algorithm given in "Mixed-Effects Models in S and S-PLUS" (Pinheiro and Bates, pp. 91). When using conservative = TRUE, eval_design first evaluates the power with the default (or given) coefficients. Then, for each multi-level categorical, it sets all coefficients to zero except the level that produced the lowest power, and then re-evaluates the power with this modified set of anticipated coefficients. If there are two or more equal power values in a multi-level categorical, two of the lowest equal terms are given opposite sign anticipated coefficients and the rest (for that categorical factor) are set to zero. Value A data frame with the parameters of the model, the type of power analysis, and the power. Several design diagnostics are stored as attributes of the data frame. In particular, the modelmatrix attribute contains the model matrix that was used for power evaluation. This is especially useful if you want to specify the anticipated coefficients to use for power evaluation. The model matrix provides the order of the model coefficients, as well as the encoding used for categorical factors. Examples #Generating a simple 2x3 factorial to feed into our optimal design generation #of an 11-run design. factorial = expand.grid(A = c(1, -1), B = c(1, -1), C = c(1, -1)) optdesign = gen_design(candidateset = factorial, model= ~A + B + C, trials = 11, optimality = "D", repeats = 100) #Now evaluating that design (with default anticipated coefficients and a effectsize of 2): eval_design(design = optdesign, model= ~A + B + C, alpha = 0.2) #Evaluating a subset of the design (which changes the power due to a different number of #degrees of freedom) eval_design(design = optdesign, model= ~A + C, alpha = 0.2) #We do not have to input the model if it's the same as the model used #During design generation. Here, we also use the default value for alpha (`0.05`) eval_design(optdesign) #Halving the signal-to-noise ratio by setting a different effectsize (default is 2): eval_design(design = optdesign, model= ~A + B + C, alpha = 0.2, effectsize = 1) #With 3+ level categorical factors, the choice of anticipated coefficients directly changes the #final power calculation. For the most conservative power calculation, that involves #setting all anticipated coefficients in a factor to zero except for one. We can specify this #option with the "conservative" argument. factorialcoffee = expand.grid(cost = c(1, 2), type = as.factor(c("Kona", "Colombian", "Ethiopian", "Sumatra")), size = as.factor(c("Short", "Grande", "Venti"))) designcoffee = gen_design(factorialcoffee, ~cost + size + type, trials = 29, optimality = "D", repeats = 100) #Evaluate the design, with default anticipated coefficients (conservative is FALSE by default). eval_design(designcoffee) #Evaluate the design, with conservative anticipated coefficients: eval_design(designcoffee, conservative = TRUE) #which is the same as the following, but now explicitly entering the coefficients: eval_design(designcoffee, anticoef = c(1, 1, 1, 0, 0, 1, 0)) #You can also evaluate the design with higher order effects, even if they were not #used in design generation: eval_design(designcoffee, model = ~cost + size + type + cost * type) #Generating and evaluating a split plot design: splitfactorialcoffee = expand.grid(caffeine = c(1, -1), cost = c(1, 2), type = as.factor(c("Kona", "Colombian", "Ethiopian", "Sumatra")), size = as.factor(c("Short", "Grande", "Venti"))) coffeeblockdesign = gen_design(splitfactorialcoffee, ~caffeine, trials = 12) coffeefinaldesign = gen_design(splitfactorialcoffee, model = ~caffeine + cost + size + type, trials = 36, splitplotdesign = coffeeblockdesign, blocksizes = 3) #Evaluating design (blocking is automatically detected) eval_design(coffeefinaldesign, 0.2, blocking = TRUE) #Manually turn blocking off to see completely randomized design power eval_design(coffeefinaldesign, 0.2, blocking = FALSE) #We can also evaluate the design with a custom ratio between the whole plot error to #the run-to-run error. eval_design(coffeefinaldesign, 0.2, varianceratios = 2) #If the design was generated outside of skpr and thus the row names do not have the #blocking structure encoded already, the user can add these manually. For a 12-run #design with 4 blocks, here is a vector indicated the blocks: blockcolumn = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4) #If we wanted to add this blocking structure to the design coffeeblockdesign, we would #add a column with the format "Block1", "Block2", "Block3" ... and each one will be treated #as a separate blocking layer. coffeeblockdesign$Block1 = blockcolumn #By default, skpr will throw out the blocking columns unless the user specifies `blocking = TRUE`. eval_design(coffeeblockdesign, blocking=TRUE) eval_design_custom_mc Monte Carlo power evaluation for experimental designs with user- supplied libraries Description Evaluates the power of an experimental design, given its run matrix and the statistical model to be fit to the data, using monte carlo simulation. Simulated data is fit using a user-supplied fitting library and power is estimated by the fraction of times a parameter is significant. Returns a data frame of parameter powers. Usage eval_design_custom_mc( design, model = NULL, alpha = 0.05, nsim, rfunction, fitfunction, pvalfunction, anticoef, effectsize = 2, contrasts = contr.sum, coef_function = coef, calceffect = FALSE, parameternames = NULL, advancedoptions = NULL, parallel = FALSE, parallelpackages = NULL, ... ) Arguments design The experimental design. Internally, eval_design_custom_mc rescales each numeric column to the range [-1, 1]. model The model used in evaluating the design. If this is missing and the design was generated with skpr, the generating model will be used. It can be a subset of the model used to generate the design, or include higher order effects not in the original design generation. It cannot include factors that are not present in the experimental design. alpha Default ‘0.05‘. The type-I error. p-values less than this will be counted as sig- nificant. nsim The number of simulations. rfunction Random number generator function. Should be a function of the form f(X, b), where X is the model matrix and b are the anticipated coefficients. fitfunction Function used to fit the data. Should be of the form f(formula, X, contrasts) where X is the model matrix. If contrasts do not need to be specified for the user supplied library, that argument can be ignored. pvalfunction Function that returns a vector of p-values from the object returned from the fitfunction. anticoef The anticipated coefficients for calculating the power. If missing, coefficients will be automatically generated based on effectsize. effectsize The signal-to-noise ratio. Default 2. For a gaussian model, and for continu- ous factors, this specifies the difference in response between the highest and lowest levels of a factor (which are +1 and -1 after normalization). More pre- cisely: If you do not specify anticoef, the anticipated coefficients will be half of effectsize. If you do specify anticoef, effectsize will be ignored. contrasts Default contr.sum. Function used to generate the contrasts encoding for cate- gorical variables. If the user has specified their own contrasts for a categorical factor using the contrasts function, those will be used. Otherwise, skpr will use contr.sum. coef_function Function that, when applied to a fitfunction return object, returns the estimated coefficients. calceffect Default ‘FALSE‘. Calculates effect power for a Type-III Anova (using the car package) using a Wald test. this ratio can be a vector specifying the variance ratio for each subplot. Otherwise, it will use a single value for all strata. To work, the fit returned by ‘fitfunction‘ must have a method compatable with the car package. parameternames Vector of parameter names if the coefficients do not correspond simply to the columns in the model matrix (e.g. coefficients from an MLE fit). advancedoptions Default ‘NULL‘. Named list of advanced options. ‘advancedoptions$anovatype‘ specifies the Anova type in the car package (default type ‘III‘), user can change to type ‘II‘). ‘advancedoptions$anovatest‘ specifies the test statistic if the user does not want a ‘Wald‘ test–other options are likelyhood-ratio ‘LR‘ and F-test ‘F‘. ‘advancedoptions$progressBarUpdater‘ is a function called in non-parallel simulations that can be used to update external progress bar.‘advancedoptions$GUI‘ turns off some warning messages when in the GUI. If ‘advancedoptions$save_simulated_responses = TRUE‘, the dataframe will have an attribute ‘simulated_responses‘ that con- tains the simulated responses from the power evaluation. parallel If TRUE, uses all cores available to speed up computation of power. Default FALSE. parallelpackages A vector of strings listing the external packages to be input into the parallel package. ... Additional arguments. Value A data frame consisting of the parameters and their powers. The parameter estimates from the simulations are stored in the ’estimates’ attribute. Examples #To demonstrate how a user can use their own libraries for Monte Carlo power generation, #We will recreate eval_design_survival_mc using the eval_design_custom_mc framework. #To begin, first let us generate the same design and random generation function shown in the #eval_design_survival_mc examples: basicdesign = expand.grid(a = c(-1, 1)) design = gen_design(candidateset = basicdesign, model = ~a, trials = 100, optimality = "D", repeats = 100) #Random number generating function rsurvival = function(X, b) { Y = rexp(n = nrow(X), rate = exp(-(X %*% b))) censored = Y > 1 Y[censored] = 1 return(survival::Surv(time = Y, event = !censored, type = "right")) } #We now need to tell the package how we want to fit our data, #given the formula and the model matrix X (and, if needed, the list of contrasts). #If the contrasts aren't required, "contrastslist" should be set to NULL. #This should return some type of fit object. fitsurv = function(formula, X, contrastslist = NULL) { return(survival::survreg(formula, data = X, dist = "exponential")) } #We now need to tell the package how to extract the p-values from the fit object returned #from the fit function. This is how to extract the p-values from the survreg fit object: pvalsurv = function(fit) { return(summary(fit)$table[, 4]) } #And now we evaluate the design, passing the fitting function and p-value extracting function #in along with the standard inputs for eval_design_mc. d = eval_design_custom_mc(design = design, model = ~a, alpha = 0.05, nsim = 100, fitfunction = fitsurv, pvalfunction = pvalsurv, rfunction = rsurvival, effectsize = 1) #This has the exact same behavior as eval_design_survival_mc for the exponential distribution. eval_design_mc Monte Carlo Power Evaluation for Experimental Designs Description Evaluates the power of an experimental design, given the run matrix and the statistical model to be fit to the data, using monte carlo simulation. Simulated data is fit using a generalized linear model and power is estimated by the fraction of times a parameter is significant. Returns a data frame of parameter powers. Usage eval_design_mc( design, model = NULL, alpha = 0.05, blocking = NULL, nsim = 1000, glmfamily = "gaussian", calceffect = TRUE, effect_anova = TRUE, varianceratios = NULL, rfunction = NULL, anticoef = NULL, firth = FALSE, effectsize = 2, contrasts = contr.sum, parallel = FALSE, adjust_alpha_inflation = FALSE, detailedoutput = FALSE, progress = TRUE, advancedoptions = NULL, ... ) Arguments design The experimental design. Internally, eval_design_mc rescales each numeric column to the range [-1, 1]. model The model used in evaluating the design. If this is missing and the design was generated with skpr, the generating model will be used. It can be a subset of the model used to generate the design, or include higher order effects not in the original design generation. It cannot include factors that are not present in the experimental design. alpha Default ‘0.05‘. The type-I error. p-values less than this will be counted as sig- nificant. blocking Default ‘NULL‘. If ‘TRUE‘, eval_design_mc will look at the rownames (or blocking columns) to determine blocking structure. Default FALSE. nsim Default ‘1000‘. The number of Monte Carlo simulations to perform. glmfamily Default ‘gaussian‘. String indicating the family of distribution for the ‘glm‘ function ("gaussian", "binomial", "poisson", or "exponential"). calceffect Default ‘TRUE‘. Whether to calculate effect power. This calculation is more expensive than parameter power, so turned off (if not needed) can greatly speed up calculation time. effect_anova Default ‘TRUE‘, whether to a Type-III Anova or a likelihood ratio test to cal- culate effect power. If ‘TRUE‘, effect power will be calculated using a Type-III Anova (using the car package) and a Wald test. If ‘FALSE‘, a likelihood ratio test (using a reduced model for each effect) will performed using the ‘lmtest‘ package. If ‘firth = TRUE‘, this will be set to ‘FALSE‘ automatically. varianceratios Default ‘NULL‘. The ratio of the whole plot variance to the run-to-run variance. If not specified during design generation, this will default to 1. For designs with more than one subplot this ratio can be a vector specifying the variance ratio for each subplot (comparing to the run-to-run variance). Otherwise, it will use a single value for all strata. rfunction Default ‘NULL‘.Random number generator function for the response variable. Should be a function of the form f(X, b, delta), where X is the model matrix, b are the anticipated coefficients, and delta is a vector of blocking errors. Typically something like rnorm(nrow(X), X * b + delta, 1). You only need to specify this if you do not like the default behavior described below. anticoef Default ‘NULL‘.The anticipated coefficients for calculating the power. If miss- ing, coefficients will be automatically generated based on the effectsize argu- ment. firth Default ‘FALSE‘. Whether to apply the firth correction (via the ‘mbest‘ pack- age) to a logistic regression. This setting also automatically sets ‘effect_lr = TRUE‘. effectsize Helper argument to generate anticipated coefficients. See details for more info. If you specify anticoef, effectsize will be ignored. contrasts Default contr.sum. The contrasts to use for categorical factors. If the user has specified their own contrasts for a categorical factor using the contrasts function, those will be used. Otherwise, skpr will use contr.sum. parallel Default ‘FALSE‘. If ‘TRUE‘, uses all cores available to speed up computation. WARNING: This can slow down computation if nonparallel time to complete the computation is less than a few seconds. adjust_alpha_inflation Default ‘FALSE‘. If ‘TRUE‘, this will run the simulation twice: first to calculate the empirical distribution of p-values under the null hypothesis and find the true Type-I error cutoff that corresponds to the desired Type-I error rate, and then again given effect size to calculate power values. detailedoutput Default ‘FALSE‘. If ‘TRUE‘, return additional information about evaluation in results. progress Default ‘TRUE‘. Whether to include a progress bar. advancedoptions Default ‘NULL‘. Named list of advanced options. ‘advancedoptions$anovatype‘ specifies the Anova type in the car package (default type ‘III‘), user can change to type ‘II‘). ‘advancedoptions$anovatest‘ specifies the test statistic if the user does not want a ‘Wald‘ test–other options are likelyhood-ratio ‘LR‘ and F-test ‘F‘. ‘advancedoptions$progressBarUpdater‘ is a function called in non-parallel simulations that can be used to update external progress bar.‘advancedoptions$GUI‘ turns off some warning messages when in the GUI. If ‘advancedoptions$save_simulated_responses = TRUE‘, the dataframe will have an attribute ‘simulated_responses‘ that con- tains the simulated responses from the power evaluation. ... Additional arguments. Details Evaluates the power of a design with Monte Carlo simulation. Data is simulated and then fit with a generalized linear model, and the fraction of simulations in which a parameter is significant (its p-value, according to the fit function used, is less than the specified alpha) is the estimate of power for that parameter. First, if blocking = TURE, the random noise from blocking is generated with rnorm. Each block gets a single sample of Gaussian random noise, with a variance as specified in varianceratios, and that sample is copied to each run in the block. Then, rfunction is called to generate a simu- lated response for each run of the design, and the data is fit using the appropriate fitting function. The functions used to simulate the data and fit it are determined by the glmfamily and blocking arguments as follows. Below, X is the model matrix, b is the anticipated coefficients, and d is a vector of blocking noise (if blocking = FALSE then d = 0): glmfamily blocking rfunction fit "gaussian" F rnorm(mean = X %*% b + d, sd = 1) lm "gaussian" T rnorm(mean = X %*% b + d, sd = 1) lme4::lmer "binomial" F rbinom(prob = 1/(1+exp(-(X %*% b + d)))) glm(family = "binomial") "binomial" T rbinom(prob = 1/(1+exp(-(X %*% b + d)))) lme4::glmer(family = "binomial") "poisson" F rpois(lambda = exp((X %*% b + d))) glm(family = "poisson") "poisson" T rpois(lambda = exp((X %*% b + d))) lme4::glmer(family = "poisson") "exponential" F rexp(rate = exp(-(X %*% b + d))) glm(family = Gamma(link = "log")) "exponential" T rexp(rate = exp(-(X %*% b + d))) lme4:glmer(family = Gamma(link = "log")) Note that the exponential random generator uses the "rate" parameter, but skpr and glm use the mean value parameterization (= 1 / rate), hence the minus sign above. Also note that the gaussian model assumes a root-mean-square error of 1. Power is dependent on the anticipated coefficients. You can specify those directly with the anticoef argument, or you can use the effectsize argument to specify an effect size and skpr will auto- generate them. You can provide either a length-1 or length-2 vector. If you provide a length-1 vector, the anticipated coefficients will be half of effectsize; this is equivalent to saying that the linear predictor (for a gaussian model, the mean response; for a binomial model, the log odds ratio; for an exponential model, the log of the mean value; for a poisson model, the log of the expected response) changes by effectsize when a continuous factor goes from its lowest level to its highest level. If you provide a length-2 vector, the anticipated coefficients will be set such that the mean response (for a gaussian model, the mean response; for a binomial model, the probability; for an exponential model, the mean response; for a poisson model, the expected response) changes from effectsize[1] to effectsize[2] when a factor goes from its lowest level to its highest level, assuming that the other factors are inactive (their x-values are zero). The effect of a length-2 effectsize depends on the glmfamily argument as follows: For glmfamily = 'gaussian', the coefficients are set to (effectsize[2] - effectsize[1]) / 2. For glmfamily = 'binomial', the intercept will be 1/2 * log(effectsize[1] * effectsize[2] / (1 - effectsize[1]) / (1 - effectsize[2])), and the other coefficients will be 1/2 * log(effectsize[2] * (1 - effectsize[1]) / (1 - effectsize[2]) / effectsize[1]). For glmfamily = 'exponential' or 'poisson', the intercept will be 1 / 2 * (log(effectsize[2]) + log(effectsize[1])), and the other coefficients will be 1 / 2 * (log(effectsize[2]) - log(effectsize[1])). Value A data frame consisting of the parameters and their powers, with supplementary information stored in the data frame’s attributes. The parameter estimates from the simulations are stored in the "es- timates" attribute. The "modelmatrix" attribute contains the model matrix that was used for power evaluation, and also provides the encoding used for categorical factors. If you want to specify the anticipated coefficients manually, do so in the order the parameters appear in the model matrix. Examples #We first generate a full factorial design using expand.grid: factorialcoffee = expand.grid(cost = c(-1, 1), type = as.factor(c("Kona", "Colombian", "Ethiopian", "Sumatra")), size = as.factor(c("Short", "Grande", "Venti"))) if(skpr:::run_documentation()) { #And then generate the 21-run D-optimal design using gen_design. designcoffee = gen_design(factorialcoffee, model = ~cost + type + size, trials = 21, optimality = "D") } if(skpr:::run_documentation()) { #To evaluate this design using a normal approximation, we just use eval_design #(here using the default settings for contrasts, effectsize, and the anticipated coefficients): eval_design(design = designcoffee, model = ~cost + type + size, 0.05) } if(skpr:::run_documentation()) { #To evaluate this design with a Monte Carlo method, we enter the same information #used in eval_design, with the addition of the number of simulations "nsim" and the distribution #family used in fitting for the glm "glmfamily". For gaussian, binomial, exponential, and poisson #families, a default random generating function (rfunction) will be supplied. If another glm #family is used or the default random generating function is not adequate, a custom generating #function can be supplied by the user. Like in `eval_design()`, if the model isn't entered, the #model used in generating the design will be used. eval_design_mc(designcoffee, nsim = 100, glmfamily = "gaussian") } if(skpr:::run_documentation()) { #We see here we generate approximately the same parameter powers as we do #using the normal approximation in eval_design. Like eval_design, we can also change #effectsize to produce a different signal-to-noise ratio: eval_design_mc(design = designcoffee, nsim = 100, glmfamily = "gaussian", effectsize = 1) } if(skpr:::run_documentation()) { #Like eval_design, we can also evaluate the design with a different model than #the one that generated the design. eval_design_mc(design = designcoffee, model = ~cost + type, alpha = 0.05, nsim = 100, glmfamily = "gaussian") } if(skpr:::run_documentation()) { #And here it is evaluated with additional interactions included: eval_design_mc(design = designcoffee, model = ~cost + type + size + cost * type, 0.05, nsim = 100, glmfamily = "gaussian") } if(skpr:::run_documentation()) { #We can also set "parallel = TRUE" to use all the cores available to speed up #computation. eval_design_mc(design = designcoffee, nsim = 10000, glmfamily = "gaussian", parallel = TRUE) } if(skpr:::run_documentation()) { #We can also evaluate split-plot designs. First, let us generate the split-plot design: factorialcoffee2 = expand.grid(Temp = c(1, -1), Store = as.factor(c("A", "B")), cost = c(-1, 1), type = as.factor(c("Kona", "Colombian", "Ethiopian", "Sumatra")), size = as.factor(c("Short", "Grande", "Venti"))) vhtcdesign = gen_design(factorialcoffee2, model = ~Store, trials = 6, varianceratio = 1) htcdesign = gen_design(factorialcoffee2, model = ~Store + Temp, trials = 18, splitplotdesign = vhtcdesign, blocksizes = rep(3, 6), varianceratio = 1) splitplotdesign = gen_design(factorialcoffee2, model = ~Store + Temp + cost + type + size, trials = 54, splitplotdesign = htcdesign, blocksizes = rep(3, 18), varianceratio = 1) #Each block has an additional noise term associated with it in addition to the normal error #term in the model. This is specified by a vector specifying the additional variance for #each split-plot level. This is equivalent to specifying a variance ratio of one between #the whole plots and the run-to-run variance for gaussian models. #Evaluate the design. Note the decreased power for the blocking factors. eval_design_mc(splitplotdesign, blocking = TRUE, nsim = 100, glmfamily = "gaussian", varianceratios = c(1, 1, 1)) } if(skpr:::run_documentation()) { #We can also use this method to evaluate designs that cannot be easily #evaluated using normal approximations. Here, we evaluate a design with a binomial response and see #whether we can detect the difference between each factor changing whether an event occurs #70% of the time or 90% of the time. factorialbinom = expand.grid(a = c(-1, 1), b = c(-1, 1)) designbinom = gen_design(factorialbinom, model = ~a + b, trials = 90, optimality = "D") eval_design_mc(designbinom, ~a + b, alpha = 0.2, nsim = 100, effectsize = c(0.7, 0.9), glmfamily = "binomial") } if(skpr:::run_documentation()) { #We can also use this method to determine power for poisson response variables. #Generate the design: factorialpois = expand.grid(a = as.numeric(c(-1, 0, 1)), b = c(-1, 0, 1)) designpois = gen_design(factorialpois, ~a + b, trials = 70, optimality = "D") #Evaluate the power: eval_design_mc(designpois, ~a + b, 0.05, nsim = 100, glmfamily = "poisson", anticoef = log(c(0.2, 2, 2))) } #The coefficients above set the nominal value -- that is, the expected count #when all inputs = 0 -- to 0.2 (from the intercept), and say that each factor #changes this count by a factor of 4 (multiplied by 2 when x= +1, and divided by 2 when x = -1). #Note the use of log() in the anticipated coefficients. eval_design_survival_mc Evaluate Power for Survival Design Description Evaluates power for an experimental design in which the response variable may be right- or left- censored. Power is evaluated with a Monte Carlo simulation, using the survival package and survreg to fit the data. Split-plot designs are not supported. Usage eval_design_survival_mc( design, model = NULL, alpha = 0.05, nsim = 1000, distribution = "gaussian", censorpoint = NA, censortype = "right", rfunctionsurv = NULL, anticoef = NULL, effectsize = 2, contrasts = contr.sum, parallel = FALSE, detailedoutput = FALSE, advancedoptions = NULL, ... ) Arguments design The experimental design. Internally, all numeric columns will be rescaled to [-1, +1]. model The model used in evaluating the design. If this is missing and the design was generated with skpr, the generating model will be used. It can be a subset of the model used to generate the design, or include higher order effects not in the original design generation. It cannot include factors that are not present in the experimental design. alpha Default ‘0.05‘. The type-I error. p-values less than this will be counted as sig- nificant. nsim The number of simulations. Default 1000. distribution Distribution of survival function to use when fitting the data. Valid choices are described in the documentation for survreg. Supported options are "exponen- tial", "lognormal", or "gaussian". Default "gaussian". censorpoint The point after/before (for right-censored or left-censored data, respectively) which data should be labelled as censored. Default NA for no censoring. This argument is used only by the internal random number generators; if you supply your own function to the rfunctionsurv parameter, then this parameter will be ignored. censortype The type of censoring (either "left" or "right"). Default "right". rfunctionsurv Random number generator function. Should be a function of the form f(X, b), where X is the model matrix and b are the anticipated coefficients. This function should return a Surv object from the survival package. You do not need to provide this argument if distribution is one of the supported choices and you are satisfied with the default behavior described below. anticoef The anticipated coefficients for calculating the power. If missing, coefficients will be automatically generated based on the effectsize argument. effectsize Helper argument to generate anticipated coefficients. See details for more info. If you specify anticoef, effectsize will be ignored. contrasts Default contr.sum. Function used to encode categorical variables in the model matrix. If the user has specified their own contrasts for a categorical factor using the contrasts function, those will be used. Otherwise, skpr will use contr.sum. parallel If TRUE, uses all cores available to speed up computation of power. Default FALSE. detailedoutput If TRUE, return additional information about evaluation in results. Default FALSE. advancedoptions Default NULL. Named list of advanced options. Pass ‘progressBarUpdater‘ to include function called in non-parallel simulations that can be used to update external progress bar. ... Any additional arguments to be passed into the survreg function during fitting. Details Evaluates the power of a design with Monte Carlo simulation. Data is simulated and then fit with a survival model (survival::survreg), and the fraction of simulations in which a parameter is significant (its p-value is less than the specified alpha) is the estimate of power for that parameter. If not supplied by the user, rfunctionsurv will be generated based on the distribution argument as follows: distribution generating function "gaussian" rnorm(mean = X %*% b, sd = 1) "exponential" rexp(rate = exp(-X %*% b)) "lognormal" rlnorm(meanlog = X %*% b, sdlog = 1) In each case, if a simulated data point is past the censorpoint (greater than for right-censored, less than for left-censored) it is marked as censored. See the examples below for how to construct your own function. Power is dependent on the anticipated coefficients. You can specify those directly with the anticoef argument, or you can use the effectsize argument to specify an effect size and skpr will auto- generate them. You can provide either a length-1 or length-2 vector. If you provide a length-1 vector, the anticipated coefficients will be half of effectsize; this is equivalent to saying that the linear predictor (for a gaussian model, the mean response; for an exponential model or lognormal model, the log of the mean value) changes by effectsize when a continuous factor goes from its lowest level to its highest level. If you provide a length-2 vector, the anticipated coefficients will be set such that the mean response changes from effectsize[1] to effectsize[2] when a factor goes from its lowest level to its highest level, assuming that the other factors are inactive (their x-values are zero). The effect of a length-2 effectsize depends on the distribution argument as follows: For distribution = 'gaussian', the coefficients are set to (effectsize[2] - effectsize[1]) / 2. For distribution = 'exponential' or 'lognormal', the intercept will be 1 / 2 * (log(effectsize[2]) + log(effectsize[1])), and the other coefficients will be 1 / 2 * (log(effectsize[2]) - log(effectsize[1])). Value A data frame consisting of the parameters and their powers. The parameter estimates from the simu- lations are stored in the ’estimates’ attribute. The ’modelmatrix’ attribute contains the model matrix and the encoding used for categorical factors. If you manually specify anticipated coefficients, do so in the order of the model matrix. Examples #These examples focus on the survival analysis case and assume familiarity #with the basic functionality of eval_design_mc. #We first generate a simple 2-level design using expand.grid: basicdesign = expand.grid(a = c(-1, 1)) design = gen_design(candidateset = basicdesign, model = ~a, trials = 15) #We can then evaluate the power of the design in the same way as eval_design_mc, #now including the type of censoring (either right or left) and the point at which #the data should be censored: eval_design_survival_mc(design = design, model = ~a, alpha = 0.05, nsim = 100, distribution = "exponential", censorpoint = 5, censortype = "right") #Built-in Monte Carlo random generating functions are included for the gaussian, exponential, #and lognormal distributions. #We can also evaluate different censored distributions by specifying a custom #random generating function and changing the distribution argument. rlognorm = function(X, b) { Y = rlnorm(n = nrow(X), meanlog = X %*% b, sdlog = 0.4) censored = Y > 1.2 Y[censored] = 1.2 return(survival::Surv(time = Y, event = !censored, type = "right")) } #Any additional arguments are passed into the survreg function call. As an example, you #might want to fix the "scale" argument to survreg, when fitting a lognormal: eval_design_survival_mc(design = design, model = ~a, alpha = 0.2, nsim = 100, distribution = "lognormal", rfunctionsurv = rlognorm, anticoef = c(0.184, 0.101), scale = 0.4) gen_design Generate optimal experimental designs Description Creates an experimental design given a model, desired number of runs, and a data frame of candidate test points. gen_design chooses points from the candidate set and returns a design that is optimal for the given statistical model. Usage gen_design( candidateset, model, trials, splitplotdesign = NULL, blocksizes = NULL, optimality = "D", augmentdesign = NULL, repeats = 20, custom_v = NULL, varianceratio = 1, contrast = contr.simplex, aliaspower = 2, minDopt = 0.8, k = NA, parallel = FALSE, timer = TRUE, add_blocking_columns = FALSE, randomized = TRUE, advancedoptions = NULL ) Arguments candidateset A data frame of candidate test points; each run of the optimal design will be chosen (with replacement) from this candidate set. Each row of the data frame is a candidate test point. Each row should be unique. Usually this is a full factorial test matrix generated for the factors in the model unless there are disallowed combinations of runs. Factors present in the candidate set but not present in the model are stripped out, and the duplicate entries in the candidate set are removed. Disallowed combinations can be specified by simply removing them from the candidate set. Disallowed combinations between a hard-to-change and an easy-to-change factor are detected by comparing an internal candidate set generated by the unique levels present in the candidate set and the split plot design. Those points are then excluded from the search. If a factor is continuous, its column should be type numeric. If a factor is categorical, its column should be type factor or character. model The statistical model used to generate the test design. trials The number of runs in the design. splitplotdesign If ‘NULL‘, a fully randomized design is generated. If not NULL, a split-plot design is generated, and this argument specifies the design for all of the fac- tors harder to change than the current set of factors. Each row corresponds to a block in which the harder to change factors will be held constant. Each row of splitplotdesign will be replicated as specified in blocksizes, and the opti- mal design is found for all of the factors given in the model argument, taking into consideration the fixed and replicated hard-to-change factors. If blocksizes is missing, ‘gen_design‘ will attempt to allocate the runs in the most balanced de- sign possible, given the number of blocks given in the argument ‘splitplotdesign‘ and the total number of ‘trials‘. blocksizes Default ‘NULL‘. Specifies the block size(s) for design generation. If only one number is passed, ‘gen_design()‘ will create blocks of the specified size, and if the total number of run specified in ‘trials‘ is not divisible by the number, ‘gen_design()‘ will attempt to allocate the runs in the most balanced design pos- sible. If a list is passed, each entry in the list will specify an additional layer of blocking. If ‘splitplotdesign‘ is not ‘NULL‘, this argument specifies the number of subplots within each whole plot (each whole plot corresponding to a row in the ‘splitplotdesign‘ data.frame). optimality Default ‘D‘. The optimality criterion used in generating the design. Full list of supported criteria: "D", "I", "A", "ALIAS", "G", "T", "E", or "CUSTOM". If "CUSTOM", user must also define a function of the model matrix named ‘cus- tomOpt‘ in their namespace that returns a single value, which the algorithm will attempt to optimize. For ‘CUSTOM‘ optimality split-plot designs, the user must instead define ‘customBlockedOpt‘, which should be a function of the model matrix and the variance-covariance matrix. For information on the algorithm behind Alias-optimal designs, see Jones and Nachtsheim. "Efficient Designs With Minimal Aliasing." Technometrics, vol. 53, no. 1, 2011, pp. 62-71. augmentdesign Default NULL. A ‘data.frame‘ of runs that are fixed during the optimal search process. The columns of ‘augmentdesign‘ must match those of the candidate set. The search algorithm will search for the optimal ‘trials‘ - ‘nrow(augmentdesign)‘ remaining runs. repeats Default ‘20‘. The number of times to repeat the search for the best optimal design. custom_v Default ‘NULL‘. The user can pass a custom variance-covariance matrix to be used during blocked design generation. varianceratio Default ‘1‘. The ratio between the block and run-to-run variance for a given stratum in a split plot/blocked design. This requires a design passed into ‘split- plotdesign‘, so it will be overridden to ‘1‘ if no split plot design is entered. contrast Default ‘contr.simplex‘, an orthonormal sum contrast. Function used to generate the encoding for categorical variables. aliaspower Default ‘2‘. Degree of interactions to be used in calculating the alias matrix for alias optimal designs. minDopt Default ‘0.8‘. Minimum value for the D-Optimality of a design when searching for Alias-optimal designs. k Default ‘NA‘. For D-optimal designs, this changes the search to a k-exchange algorithm Johnson and Nachtsheim. "Some Guidelines for Constructing Exact D-Optimal Designs on Convex Design Spaces." Technometrics, vol. 25, 1983, pp. 271-277. This exchanges only the k lowest variance runs in the design at each search iteration. Lower numbers can result in a faster search, but are less likely tofind an optimal design. Values of ‘k >= n/4‘ have been shown empiri- cally to generate similar designs to the full search. When ‘k == trials‘, this re- sults in the default modified Federov’s algorithm. A ‘k‘ of 1 is a form of Wynn’s algorithm Wynn. "Results in the Theory and Construction of D-Optimum Exper- imental Designs," Journal of the Royal Statistical Society, Ser. B,vol. 34, 1972, pp. 133-14. parallel Default ‘FALSE‘. If ‘TRUE‘, the optimal design search will use all the avail- able cores. This can lead to a substantial speed-up in the search for complex designs. If the user wants to set the number of cores manually, they can do this by setting options("cores") to the desired number. NOTE: If you have installed BLAS libraries that include multicore support (e.g. Intel MKL that comes with Microsoft R Open), turning on parallel could result in reduced performance. timer Default ‘FALSE‘. If ‘TRUE‘, will print an estimate of the optimal design search time. add_blocking_columns Default ‘FALSE‘. The blocking structure of the design will be indicated in the row names of the returned design. If ‘TRUE‘, the design also will have extra columns to indicate the blocking structure. If no blocking is detected, no columns will be added. randomized Default ‘TRUE‘, due to the intrinsic randomization of the design search algo- rithm. If ‘FALSE‘, the randomized design will be re-ordered from left to right. advancedoptions Default ‘NULL‘. An named list for advanced users who want to adjust the opti- mal design algorithm parameters. Advanced option names are ‘design_search_tolerance‘ (the smallest fractional increase below which the design search terminates), ‘alias_tie_power‘ (the degree of the aliasing matrix when calculating optimality tie-breakers), ‘alias_tie_tolerance‘ (the smallest absolute difference in the opti- mality criterion where designs are considered equal before considering the alias- ing structure), ‘alias_compare“ (which if set to FALSE turns off alias tie break- ing completely), ‘aliasmodel‘ (provided if the user does not want to calculate Alias-optimality using all ‘aliaspower‘ interaction terms), and ‘progressBarUp- dater“ (a function called in non-parallel optimal searches that can be used to update an external progress bar). Finally, there’s ‘g_efficiency_method‘, which sets the method used to calculate G-efficiency (default is "random" for a ran- dom Monte Carlo sampling of the design space, "optim" for to use simulated annealing, or "custom" to explicitly define the points in the design space, which is the fastest method and the only way to calculate prediction variance with dis- allowed combinations). With this, there’s also ‘g_efficiency_samples‘, which specifies the number of random samples (default 1000 if ‘g_efficiency_method = "random"‘), attempts at simulated annealing (default 1 if ‘g_efficiency_method = "optim"‘), or a data.frame defining the exact points of the design space if ‘g_efficiency_method = "custom"‘. Details Split-plot designs can be generated with repeated applications of gen_design; see examples for details. Value A data frame containing the run matrix for the optimal design. The returned data frame contains supplementary information in its attributes, which can be accessed with the ‘get_attributes()‘ and ‘get_optimality()‘ functions. Examples #Generate the basic factorial candidate set with expand.grid. #Generating a basic 2 factor candidate set: basic_candidates = expand.grid(x1 = c(-1, 1), x2 = c(-1, 1)) #This candidate set is used as an input in the optimal design generation for a #D-optimal design with 11 runs. design = gen_design(candidateset = basic_candidates, model = ~x1 + x2, trials = 11) #We can also use the dot formula to automatically use all of the terms in the model: design = gen_design(candidateset = basic_candidates, model = ~., trials = 11) #Here we add categorical factors, specified by using "as.factor" in expand.grid: categorical_candidates = expand.grid(a = c(-1, 1), b = as.factor(c("A", "B")), c = as.factor(c("High", "Med", "Low"))) #This candidate set is used as an input in the optimal design generation. design2 = gen_design(candidateset = categorical_candidates, model = ~a + b + c, trials = 19) #We can also increase the number of times the algorithm repeats #the search to increase the probability that the globally optimal design was found. design2 = gen_design(candidateset = categorical_candidates, model = ~a + b + c, trials = 19, repeats = 100) #We can perform a k-exchange algorithm instead of a full search to help speed up #the search process, although this can lead to less optimal designs. Here, we only #exchange the 10 lowest variance runs in each search iteration. if(skpr:::run_documentation()) { design_k = gen_design(candidateset = categorical_candidates, model = ~a + b + c, trials = 19, repeats = 100, k = 10) } #To speed up the design search, you can turn on multicore support with the parallel option. #You can also customize the number of cores used by setting the cores option. By default, #all cores are used. if(skpr:::run_documentation()) { options(cores = 2) design2 = gen_design(categorical_candidates, model = ~a + b + c, trials = 19, repeats = 1000, parallel = TRUE) } #You can also use a higher order model when generating the design: design2 = gen_design(categorical_candidates, model = ~a + b + c + a * b * c, trials = 12, repeats = 10) #To evaluate a response surface design, include center points #in the candidate set and include quadratic effects (but not for the categorical factors). quad_candidates = expand.grid(a = c(1, 0, -1), b = c(-1, 0, 1), c = c("A", "B", "C")) gen_design(quad_candidates, ~a + b + I(a^2) + I(b^2) + a * b * c, 20) #The optimality criterion can also be changed: gen_design(quad_candidates, ~a + b + I(a^2) + I(b^2) + a * b * c, 20, optimality = "I", repeats = 10) gen_design(quad_candidates, ~a + b + I(a^2) + I(b^2) + a * b * c, 20, optimality = "A", repeats = 10) #A blocked design can be generated by specifying the `blocksizes` argument. Passing a single #number will create designs with blocks of that size, while passing multiple values in a list #will specify multiple layers of blocking. #Specify a single layer gen_design(quad_candidates, ~a + b + c, 21, blocksizes=3, add_blocking_column=TRUE) #Manually specify the block sizes for a single layer, must add to `trials`` gen_design(quad_candidates, ~a + b + c, 21, blocksizes=c(4,3,2,3,3,3,3), add_blocking_column=TRUE) #Multiple layers of blocking gen_design(quad_candidates, ~a + b + c, 21, blocksizes=list(7,3), add_blocking_column=TRUE) #Multiple layers of blocking, specified individually gen_design(quad_candidates, ~a + b + c, 21, blocksizes=list(7,c(4,3,2,3,3,3,3)), add_blocking_column=TRUE) #A split-plot design can be generated by first generating an optimal blocking design using the #hard-to-change factors and then using that as the input for the split-plot design. #This generates an optimal subplot design that accounts for the existing split-plot settings. splitplotcandidateset = expand.grid(Altitude = c(-1, 1), Range = as.factor(c("Close", "Medium", "Far")), Power = c(1, -1)) hardtochangedesign = gen_design(splitplotcandidateset, model = ~Altitude, trials = 11, repeats = 10) #Now we can use the D-optimal blocked design as an input to our full design. #Here, we add the easy to change factors from the candidate set to the model, #and input the hard-to-change design along with the new number of trials. `gen_design` will #automatically allocate the runs in the blocks in the most balanced way possible. designsplitplot = gen_design(splitplotcandidateset, ~Altitude + Range + Power, trials = 33, splitplotdesign = hardtochangedesign, repeats = 10) #If we want to allocate the blocks manually, we can do that with the argument `blocksizes`. This #vector must sum to the number of `trials` specified. #Putting this all together: designsplitplot = gen_design(splitplotcandidateset, ~Altitude + Range + Power, trials = 33, splitplotdesign = hardtochangedesign, blocksizes = c(4, 2, 3, 4, 2, 3, 4, 2, 3, 4, 2), repeats = 10) #The split-plot structure is encoded into the row names, with a period #demarcating the blocking level. This process can be repeated for arbitrary #levels of blocking (i.e. a split-plot design can be entered in as the hard-to-change #to produce a split-split-plot design, which can be passed as another #hard-to-change design to produce a split-split-split plot design, etc). #In the following, note that the model builds up as we build up split plot strata. splitplotcandidateset2 = expand.grid(Location = as.factor(c("East", "West")), Climate = as.factor(c("Dry", "Wet", "Arid")), Vineyard = as.factor(c("A", "B", "C", "D")), Age = c(1, -1)) #6 blocks of Location: temp = gen_design(splitplotcandidateset2, ~Location, trials = 6, varianceratio = 2, repeats = 10) #Each Location block has 2 blocks of Climate: temp = gen_design(splitplotcandidateset2, ~Location + Climate, trials = 12, splitplotdesign = temp, blocksizes = 2, varianceratio = 1, repeats = 10) #Each Climate block has 4 blocks of Vineyard: temp = gen_design(splitplotcandidateset2, ~Location + Climate + Vineyard, trials = 48, splitplotdesign = temp, blocksizes = 4, varianceratio = 1, repeats = 10) #Each Vineyard block has 4 runs with different Age: if(skpr:::run_documentation()) { splitsplitsplitplotdesign = gen_design(splitplotcandidateset2, ~Location + Climate + Vineyard + Age, trials = 192, splitplotdesign = temp, blocksizes = 4, varianceratio = 1, add_blocking_columns = TRUE) } #gen_design also supports user-defined optimality criterion. The user defines a function #of the model matrix named customOpt, and gen_design will attempt to generate a design #that maximizes that function. This function needs to be in the global environment, and be #named either customOpt or customBlockedOpt, depending on whether a split-plot design is being #generated. customBlockedOpt should be a function of the model matrix as well as the #variance-covariance matrix, vInv. Due to the underlying C + + code having to call back to the R #environment repeatedly, this criterion will be significantly slower than the built-in algorithms. #It does, however, offer the user a great deal of flexibility in generating their designs. #We are going to write our own D-optimal search algorithm using base R functions. Here, write #a function that calculates the determinant of the information matrix. gen_design will search #for a design that maximizes this function. customOpt = function(currentDesign) { return(det(t(currentDesign) %*% currentDesign)) } #Generate the whole plots for our split-plot design, using the custom criterion. candlistcustom = expand.grid(Altitude = c(10000, 20000), Range = as.factor(c("Close", "Medium", "Far")), Power = c(50, 100)) htcdesign = gen_design(candlistcustom, model = ~Altitude + Range, trials = 11, optimality = "CUSTOM", repeats = 10) #Now define a function that is a function of both the model matrix, #as well as the variance-covariance matrix vInv. This takes the blocking structure into account #when calculating our determinant. customBlockedOpt = function(currentDesign, vInv) { return(det(t(currentDesign) %*% vInv %*% currentDesign)) } #And finally, calculate the design. This (likely) results in the same design had we chosen the #"D" criterion. design = gen_design(candlistcustom, ~Altitude + Range + Power, trials = 33, splitplotdesign = htcdesign, blocksizes = 3, optimality = "CUSTOM", repeats = 10) #gen_design can also augment an existing design. Input a dataframe of pre-existing runs #to the `augmentdesign` argument. Those runs in the new design will be fixed, and gen_design #will perform a search for the remaining `trials - nrow(augmentdesign)` runs. candidateset = expand.grid(height = c(10, 20), weight = c(45, 55, 65), range = c(1, 2, 3)) design_to_augment = gen_design(candidateset, ~height + weight + range, 5) #As long as the columns in the augmented design match the columns in the candidate set, #this design can be augmented. augmented_design = gen_design(candidateset, ~height + weight + range, 16, augmentdesign = design_to_augment) #A design's diagnostics can be accessed via the `get_optimality()` function: get_optimality(augmented_design) #And design attributes can be accessed with the `get_attribute()` function: get_attribute(design) #A correlation color map can be produced by calling the plot_correlation command with the output #of gen_design() if(skpr:::run_documentation()) { plot_correlations(design2) } #A fraction of design space plot can be produced by calling the plot_fds command if(skpr:::run_documentation()) { plot_fds(design2) } #Evaluating the design for power can be done with eval_design, eval_design_mc (Monte Carlo) #eval_design_survival_mc (Monte Carlo survival analysis), and #eval_design_custom_mc (Custom Library Monte Carlo) get_attribute Get attribute values Description Returns one or more of underlying attributes used in design generation/evaluation Usage get_attribute(output, attr = NULL, round = TRUE) Arguments output The output of either ‘gen_design()‘ or ‘eval_design()‘/‘eval_design_mc()“ attr Default ‘NULL‘. Return just the specific value requested. Potential values are ‘model.matrix‘ for model used, ‘moments.matrix‘, ‘variance.matrix‘, ‘alias.matrix‘, ‘correlation.matrix‘, and ‘model‘ for the model used in the evaluation/generation of the design. round Default ‘TRUE‘. Rounds off values smaller than the magnitude ‘1e-15“ in the ‘correlation.matrix‘ and ‘alias.matrix‘ matrix attributes. Value A list of attributes. Examples # We can extract the attributes of a design from either the output of `gen_design()` # or the output of `eval_design()` factorialcoffee = expand.grid(cost = c(1, 2), type = as.factor(c("Kona", "Colombian", "Ethiopian", "Sumatra")), size = as.factor(c("Short", "Grande", "Venti"))) designcoffee = gen_design(factorialcoffee, ~cost + size + type, trials = 29, optimality = "D", repeats = 100) #Extract a list of all attributes get_attribute(designcoffee) #Get just one attribute get_attribute(designcoffee,"model.matrix") # Extract from `eval_design()` output power_output = eval_design(designcoffee, model = ~cost + size + type, alpha = 0.05, detailedoutput = TRUE) get_attribute(power_output,"correlation.matrix") get_optimality Get optimality values Description Returns a list of optimality values (or one value in particular). Note: The choice of contrast will effect the ‘G‘ efficiency value, and ‘gen_design()‘ and ‘eval_design()‘ by default set different contrasts (‘contr.simplex‘ vs ‘contr.sum‘). Usage get_optimality(output, optimality = NULL, calc_g = FALSE) Arguments output The output of either gen_design or eval_design/eval_design_mc. optimality Default ‘NULL‘. Return just the specific optimality requested. calc_g Default ‘FALSE‘. Whether to calculate the g-efficiency. Value A dataframe of optimality conditions. ‘D‘, ‘A‘, and ‘G‘ are efficiencies (value is out of 100). ‘T‘ is the trace of the information matrix, ‘E‘ is the minimum eigenvalue of the information matrix, ‘I‘ is the average prediction variance, and ‘Alias‘ is the trace of the alias matrix. Examples # We can extract the optimality of a design from either the output of `gen_design()` # or the output of `eval_design()` factorialcoffee = expand.grid(cost = c(1, 2), type = as.factor(c("Kona", "Colombian", "Ethiopian", "Sumatra")), size = as.factor(c("Short", "Grande", "Venti"))) designcoffee = gen_design(factorialcoffee, ~cost + size + type, trials = 29, optimality = "D", repeats = 100) #Extract a list of all attributes get_optimality(designcoffee) #Get just one attribute get_optimality(designcoffee,"D") # Extract from `eval_design()` output power_output = eval_design(designcoffee, model = ~cost + size + type, alpha = 0.05, detailedoutput = TRUE) get_optimality(power_output) get_power_curve_output Get Power Curve Warnings and Errors Description Gets the warnings and errors from ‘calculate_power_curves()‘ output. Usage get_power_curve_output(power_curve) Arguments power_curve The output from ‘calculate_power_curves()‘ Value A list of data.frames containing warning/error information Examples #Generate sample if(skpr:::run_documentation()) { calculate_power_curves(trials=seq(50,150,by=20), candidateset = expand.grid(x=c(-1,1),y=c(-1,1)), model = ~., effectsize = list(c(0.5,0.9),c(0.6,0.9)), eval_function = eval_design_mc, eval_args = list(nsim = 100, glmfamily = "binomial")) } plot_correlations Plots design diagnostics Description Plots design diagnostics Usage plot_correlations( genoutput, model = NULL, customcolors = NULL, pow = 2, custompar = NULL, standardize = TRUE ) Arguments genoutput The output of either gen_design or eval_design/eval_design_mc model Default ‘NULL‘. Defaults to the model used in generating/evaluating the design, augmented with 2-factor interactions. If specified, it will override the default model used to generate/evaluate the design. customcolors A vector of colors for customizing the appearance of the colormap pow Default 2. The interaction level that the correlation map is showing. custompar Default NULL. Custom parameters to pass to the ‘par‘ function for base R plot- ting. standardize Default ‘TRUE‘. Whether to standardize (scale to -1 and 1 and center) the continuous numeric columns. Not standardizing the numeric columns can in- crease multi-collinearity (predictors that are correlated with other predictors in the model). Value Silently returns the correlation matrix with the proper row and column names. Examples #We can pass either the output of gen_design or eval_design to plot_correlations #in order to obtain the correlation map. Passing the output of eval_design is useful #if you want to plot the correlation map from an externally generated design. #First generate the design: candidatelist = expand.grid(cost = c(15000, 20000), year = c("2001", "2002", "2003", "2004"), type = c("SUV", "Sedan", "Hybrid")) cardesign = gen_design(candidatelist, ~(cost+type+year)^2, 30) plot_correlations(cardesign) #We can also increase the level of interactions that are shown by default. plot_correlations(cardesign, pow = 3) #You can also pass in a custom color map. plot_correlations(cardesign, customcolors = c("blue", "grey", "red")) plot_correlations(cardesign, customcolors = c("blue", "green", "yellow", "orange", "red")) plot_fds Fraction of Design Space Plot Description Creates a fraction of design space plot Usage plot_fds( genoutput, model = NULL, continuouslength = 11, plot = TRUE, yaxis_max = NULL, description = "Fraction of Design Space" ) Arguments genoutput The design, or the output of the power evaluation functions. This can also be a list of several designs, which will result in all of them being plotted in a row (for easy comparison). model Default ‘NULL‘. The model, if ‘NULL‘ it defaults to the model used in ‘eval_design‘ or ‘gen_design‘. continuouslength Default ‘11‘. The precision of the continuous variables. Decrease for faster (but less precise) plotting. plot Default ‘TRUE‘. Whether to plot the FDS, or just calculate the cumulative dis- tribution function. yaxis_max Default ‘NULL‘. Manually set the maximum value of the prediction variance. description Default ‘Fraction of Design Space‘. The description to add to the plot. If a vector and multiple designs passed to genoutput, it will be the description for each plot. Value Plots design diagnostics, and invisibly returns the vector of values representing the fraction of design space plot. If multiple designs are passed, this will return a list of all FDS vectors. Examples #We can pass either the output of gen_design or eval_design to plot_correlations #in order to obtain the correlation map. Passing the output of eval_design is useful #if you want to plot the correlation map from an externally generated design. #First generate the design: candidatelist = expand.grid(X1 = c(1, -1), X2 = c(1, -1)) design = gen_design(candidatelist, ~(X1 + X2), 15) plot_fds(design) print.skpr_eval_output Print evaluation information Description Prints design evaluation information below the data.frame of power values Note: If options("skpr.ANSI") is ‘NULL‘ or ‘TRUE‘, ANSI codes will be used during printing to prettify the output. If this is ‘FALSE‘, only ASCII will be used. Usage ## S3 method for class 'skpr_eval_output' print(x, ...) Arguments x The x of the evaluation functions in skpr ... Additional arguments. Examples #Generate/evaluate a design and print its information factorialcoffee = expand.grid(cost = c(1, 2), type = as.factor(c("Kona", "Colombian", "Ethiopian", "Sumatra")), size = as.factor(c("Short", "Grande", "Venti"))) designcoffee = gen_design(factorialcoffee, ~cost + size + type, trials = 29, optimality = "D", repeats = 100) eval_design(designcoffee) print.skpr_power_curve_output Print evaluation information Description Prints design evaluation information below the data.frame of power values Note: If options("skpr.ANSI") is ‘NULL‘ or ‘TRUE‘, ANSI codes will be used during printing to prettify the output. If this is ‘FALSE‘, only ASCII will be used. Usage ## S3 method for class 'skpr_power_curve_output' print(x, ...) Arguments x The x of the evaluation functions in skpr ... Additional arguments. Examples #Generate/evaluate a design and print its information factorialcoffee = expand.grid(cost = c(1, 2), type = as.factor(c("Kona", "Colombian", "Ethiopian", "Sumatra")), size = as.factor(c("Short", "Grande", "Venti"))) coffee_curves = calculate_power_curves(candidateset = factorialcoffee, coffee_curves skprGUI Graphical User Interface for skpr Description skprGUI provides a graphical user interface to skpr, within R Studio. Usage skprGUI(inputValue1, inputValue2) Arguments inputValue1 Required by Shiny inputValue2 Required by Shiny Examples #Type `skprGUI()` to begin skprGUIbrowser skprGUIbrowser Description skprGUI provides a graphical user interface to skpr, in an external browser. Usage skprGUIbrowser() Examples #Type `skprGUIbrowser()` to begin skprGUIserver Graphical User Interface for skpr Description skprGUI provides a graphical user interface to skpr, within R Studio. Usage skprGUIserver(inputValue1, inputValue2) Arguments inputValue1 Required by Shiny inputValue2 Required by Shiny Examples #Type `skprGUIserver()` to begin %>% re-export magrittr pipe operator Description re-export magrittr pipe operator
neatStats
cran
R
Package ‘neatStats’ December 7, 2022 Title Neat and Painless Statistical Reporting Version 1.13.3 Date 2022-12-07 Description User-friendly, clear and simple statistics, primarily for publication in psychological science. The main functions are wrappers for other packages, but there are various additions as well. Every relevant step from data aggregation to reportable printed statistics is covered for basic experimental designs. URL https://github.com/gasparl/neatstats Depends R (>= 3.6.0) Imports viridis, fBasics, data.table, bayestestR, pROC, MBESS, car, ez, Exact, BayesFactor, ggplot2, ggpubr, logspline, grDevices, stats, graphics Suggests rmarkdown, knitr, rstudioapi License BSD_2_clause + file LICENSE Encoding UTF-8 RoxygenNote 7.2.2 VignetteBuilder knitr NeedsCompilation no Author <NAME> [aut, cre] (<https://orcid.org/0000-0001-9401-4830>), <NAME> [ctb] (<https://orcid.org/0000-0003-1658-9086>), <NAME> [ctb] (<https://orcid.org/0000-0003-0270-096X>) Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2022-12-07 20:50:02 UTC R topics documented: aggr_nea... 2 anova_nea... 5 ci_from_... 12 corr_nea... 14 dems_nea... 16 enu... 19 excl_nea... 20 mean_c... 21 mon_con... 22 mon_nea... 23 norm_test... 24 path_nea... 25 peek_nea... 26 plot_nea... 28 props_nea... 36 rbind_loo... 40 read_di... 43 r... 45 roc_nea... 46 sd_c... 48 s... 49 table_nea... 49 t_nea... 51 var_test... 56 aggr_neat Aggregation, descriptives Description Returns aggregated values per group for given variable. Serves as argument in the table_neat function. Usage aggr_neat( dat, values, method = mean, group_by = NULL, filt = NULL, sep = "_", prefix = NULL, new_name = NULL, round_to = 2 ) Arguments dat A data frame (or a data.table, or the name of either as string). values The vector of numbers from which the statistics are to be calculated, or the name of the column in the dat data frame, that contains the vector. method Function of string. If function, uses the values to calculate the returned value for the given function (e.g. means, as per default, using the mean function). Such a function may return a vector of results as well; see Examples. If string, one of two internal functions will be used. If the string end with "+sd", e.g., "mean+sd", the function preceding the "+" sign will be calculated along with the standard deviation, displayed in a single column, rounded as set in the round_to argument. (This is primarily for use in the table_neat function for summary tables.) If the string does not end with "+sd", a ratio for the occurrences of given elements will be calculated. Multiple elements can by given as a vector of strings. The number of occurrences of these elements will be the numerator (div- idend), while the entire column length (i.e., number of all elements) will be the denominator (divisor). For example, if a column contains elements "correct", "incorrect", "tooslow", the ratio of "correct" to all other elements (i.e., including elements "correct", "incorrect", and "tooslow") can be written simply as method = "correct". The complementary ratio, of "incorrect" and "tooslow", can be written as method = "incorrect, tooslow". (Hint: filter to get ratios of subgroups, e.g. to include only "correct" and "incorrect" elements, and calculate their ratio; see below.) group_by String, or vector of strings: the name(s) of the column(s) in the dat data frame, containing the vector(s) of factors by which the statistics are grouped. filt An expression to filter, by column values, the entire dat data frame before per- forming the aggregation. The expression should use column names alone; see Examples. sep String (underscore "_" by default) for separating group names (and prefix, if given). prefix NULL (default) or string. String specifies a prefix for each group type under the group column. new_name NULL (default) or string. String specifies new name for the variable to be used as column title. If NULL, the name will be "aggr_value" (or, if used with table_neat, the input variable name is used). round_to Number of digits after the decimal point to round to, when using "+sd" in method. Value A data.table with the statistics per group, with a single column ("aggr_group") indicating the grouping. See Also table_neat to create full tables using multiple variables Examples data("mtcars") # load base R example dataset # overall means and SDs for wt (Weight) aggr_neat(mtcars, wt) # rename column aggr_neat(mtcars, wt, new_name = 'weight') # grouped by cyl (Number of cylinders) aggr_neat(mtcars, wt, group_by = 'cyl') # grouped by cyl and gear aggr_neat(mtcars, wt, group_by = c('cyl', 'gear')) # prefix for group names aggr_neat(mtcars, wt, group_by = 'cyl', prefix = 'cyl') # filter to only have cyl larger than 4 aggr_neat(mtcars, wt, group_by = 'cyl', filt = cyl > 4) # filter to only have hp (Gross horsepower) smaller than 200 aggr_neat(mtcars, wt, group_by = 'cyl', filt = hp < 200) # combine two filters above, and add prefix aggr_neat( mtcars, wt, group_by = 'cyl', filt = (hp < 200 & cyl > 4), prefix = 'filtered' ) # add SD (and round output numbers to 2) aggr_neat(mtcars, wt, group_by = 'cyl', method = 'mean+sd', round_to = 2) # now medians instead of means aggr_neat(mtcars, wt, group_by = 'cyl', method = median) # with SD aggr_neat(mtcars, wt, group_by = 'cyl', method = 'median+sd', round_to = 1) # overall ratio of gear 4 (Number of gears) aggr_neat(mtcars, gear, method = '4') # overall ratio of gear 4 and 5 aggr_neat(mtcars, gear, method = '4, 5') # same ratio calculated per each cyl aggr_neat(mtcars, gear, group_by = 'cyl', method = '4, 5') # per each cyl and per vs (engine type) aggr_neat(mtcars, gear, group_by = c('cyl', 'vs'), method = '4, 5') # ratio of gear 3 per gear 3 and 5 aggr_neat( mtcars, gear, group_by = 'cyl', method = '3', filt = gear %in% c(3, 5) ) anova_neat Comparison of Multiple Means: ANOVA Description Analysis of variance (ANOVA) F-test results with appropriate Welch’s and epsilon corrections where applicable (unless specified otherwise), including partial eta squared effect sizes with con- fidence intervals (CIs), generalized eta squared, and inclusion Bayes factor based on matched models (BFs). Usage anova_neat( data_per_subject, values, within_ids = NULL, between_vars = NULL, ci = 0.9, norm_tests = "none", norm_plots = FALSE, var_tests = FALSE, bf_added = FALSE, bf_sample = 10000, test_title = "--- neat ANOVA ---", welch = TRUE, e_correction = NULL, type = 2, white.adjust = FALSE, hush = FALSE, plot_means = FALSE, ... ) Arguments data_per_subject Data frame. Should contain all values (measurements/observations) in a single row per each subject. values Vector of strings; column name(s) in the data_per_subject data frame. Each column should contain a single dependent variable: thus, to test repeated (within- subject) measurements, each specified column should contain one measurement. within_ids NULL (default), string, or named list. In case of no within-subject factors, leave as NULL. In case of a single within subject factor, a single string may be given to optionally provide custom name for the within-subject factor (note: this is a programming variable name, so it should not contain spaces, etc.); other- wise (if left NULL) this one within-subject factor will always just be named "within_factor". In case of multiple within-subject factors, each factor must be specified as a named list element, each with a vector of strings that distin- guish the levels within that factors. The column names given as values should always contain one (and only one) of these strings within each within-subject factor, and thus they will be assigned the appropriate level. For example, values = 'rt_s1_neg, rt_s1_pos,rt_s2_neg, rt_s2_pos' could have within_ids = list( session = c('s1','s2'), valence = c('pos', 'neg'). (Note: the strings for distinguishing must be unambiguous. E.g., for values apple_a and apple_b, do not set levels c('a','b'), because 'a' is also found in apple_b. In this case, you could choose levels c('_a','_b') to make sure the values are correctly distinguished.) See also Examples. between_vars NULL (default; in case of no between-subject factors) or vector of strings; column name(s) in the data_per_subject data frame. Each column should contain a single between-subject independent variable (representing between-subject fac- tors). ci Numeric; confidence level for returned CIs. (Default: .9; Lakens, 2014; Steiger, 2004.) norm_tests Normality tests for the pooled ANOVA residuals ("none" by default, giving no tests). Any or all of the following character input is accepted (as a single string or a character vector; case-insensitive): "W" (Shapiro-Wilk), "K2" (D’Agostino), "A2" (Anderson-Darling), "JB" (Jarque-Bera); see norm_tests. The option "all" (or TRUE) selects all four previous tests at the same time. norm_plots If TRUE, displays density, histogram, and Q-Q plots (and scatter plots for paired tests) for the pooled residuals. var_tests Logical, FALSE by default. If TRUE (and there are any between-subject factors), runs variance equality tests via var_tests for all combinations of the between- subject factors within each level of within-subject factor combinations; see De- tails. bf_added Logical. If TRUE (default), inclusion Bayes factor is calculated and displayed. (Note: with multiple factors and/or larger dataset, the calculation can take con- siderable time.) bf_sample Number of samples used to estimate Bayes factor (10000 by default). test_title String, "--- neat ANOVA ---" by default. Simply displayed in printing preced- ing the statistics. welch If TRUE (default), calculates Welch’s ANOVA via stats::oneway.test in case of a single factor (one-way) between-subject design. If FALSE, calculates via ez::ezANOVA in such cases too (i.e., same as in case of every other design). e_correction NULL (default) or one of the following strings: 'gg', 'hf', or 'none'. If set to 'gg', Greenhouse-Geisser correction is applied in case of repeated measures (regardless of violation of sphericity). If set to 'hf', Huynh-Feldt correction is applied. If set to 'none', no correction is applied. If NULL, Greenhouse- Geisser correction is applied when Mauchly’s sphericity test is significant and the Greenhouse-Geisser epsilon is not larger than .75, while Huynh-Feldt cor- rection is applied when Mauchly’s sphericity test is significant and the Greenhouse- Geisser epsilon is larger than .75 (see Girden, 1992). type Sum of squares type specified as a number: 1, 2, or 3. Set to 2 by default (which is generally recommended, see e.g. Navarro, 2019, Chapter 16). white.adjust If not FALSE (default) uses a heteroscedasticity-corrected coefficient covariance matrix; the various values of the argument specify different corrections ("hc0", "hc1", "hc2", "hc3", or "hc4"). See the documentation for car::hccm for details. If set to TRUE then the "hc3" correction is selected. hush Logical. If TRUE, prevents printing any details to console. plot_means Logical (FALSE by default). If TRUE, creates plots of means by factor, by passing data and factor information to plot_neat. ... Any additional arguments will be passed on to plot_neat. Details The Bayes factor (BF) is always calculated with the default rscaleFixed of 0.5 ("medium") and rscaleRandom of 1 ("nuisance"). BF supporting null hypothesis is denoted as BF01, while that supporting alternative hypothesis is denoted as BF10. When the BF is smaller than 1 (i.e., supports null hypothesis), the reciprocal is calculated (hence, BF10 = BF, but BF01 = 1/BF). When the BF is greater than or equal to 10000, scientific (exponential) form is reported for readability. (The original full BF number is available in the returned named vector as bf.) Mauchly’s sphericity test is returned for repeated measures with more than two levels. If Mauchly’s test is significant, epsilon correction may be applied (see the e_correction parameter). Variance equality tests (if var_tests is TRUE): Brown-Forsythe and Fligner-Killeen tests are per- formed for each within-subject factor level (or, in case of several factors, each combination) via var_tests. Note that variance testing is generally not recommended (see e.g., Zimmerman, 2004). In case of a one-way between-subject ANOVA, Welch-corrected results are reported by default, which corrects for unequal variances. In case of multiple between-subject factors, the white.adjust parameter can be set to TRUE (or "hc3") to apply "hc3" correction for unequal variances. In case of a mixed ANOVA (both between-subject and within-subject factors), if the tests are significant and the data is unbalanced (unequal group sample sizes), you should either consider the results respectively or choose a different test. In case of multiple values (column names) that match identical levels for all factors, the given columns will be merged into a single column taking the mean value of all these columns. (This is to simplify "dropping" a within-subject factor and retesting the remaining factors.) Explicit warning messages are shown in each such case. Value Prints ANOVA statistics (including, for each model, F-test with partial eta squared and its CI, gen- eralized eta squared, and BF, as specified via the corresponding parameters) in APA style. Fur- thermore, when assigned, returns all calculated information details for each effect (as stat_list), normality and variance tests (if any), etc. Note The F-tests are calculated via ez::ezANOVA, including Mauchly’s sphericity test. (But Welch’s ANOVA is calculated in case of one-way between-subject designs via stats::oneway.test, unless the welch parameter is set to FALSE.) Confidence intervals are calculated, using the F value, via MBESS::conf.limits.ncf, convert- ing noncentrality parameters to partial eta squared as ncp/(ncp+ df_nom+df_denom+1) (Smithson, 2003). Generalized eta squared is to facilitate potential subsequent meta-analytical comparisons (see Lak- ens, 2013). The inclusion Bayes factor based on matched models is calculated via bayestestR::bayesfactor_inclusion, (with match_models = TRUE, and using an BayesFactor::anovaBF object for models input). References <NAME>. (1992). ANOVA: Repeated measures. Newbury Park, CA: Sage. <NAME>. (2007). Methods for the behavioral, educational, and social sciences: An R package. Behavior Research Methods, 39(4), 979-984. doi:10.3758/BF03192993 <NAME>. (2013). Calculating and reporting effect sizes to facilitate cumulative science: A practi- cal primer for t-tests and ANOVAs. Frontiers in Psychology, 4. https://doi.org/10.3389/fpsyg.2013.00863 <NAME>. (2014). Calculating confidence intervals for Cohen’s d and eta-squared using SPSS, R, and Stata [Blog post]. Retrieved from http://daniellakens.blogspot.com/2014/06/calculating-confidence-inter html <NAME>. (2017). Bayes like a Baws: Interpreting Bayesian Repeated Measures in JASP [Blog post]. Retrieved from https://www.cogsci.nl/blog/interpreting-bayesian-repeated-measures-in-jasp <NAME>. 2015. Handbook of Biological Statistics (3rd ed.). Sparky House Publishing, Baltimore, Maryland. Retrieved from http://www.biostathandbook.com <NAME>. (2010). Alternatives to F-test in one way ANOVA in case of heterogeneity of variances (a simulation study). Psychological Test and Assessment Modeling, 52(4), 343-353. <NAME>. (2019). Learning Statistics with R: A Tutorial for Psychology Students and Other Beginners (Version 0.6.1). Retrieved from https://learningstatisticswithr.com/ <NAME>. (2003). Confidence intervals. <NAME>: Sage Publications. <NAME>. (2004). Beyond the F test: effect size confidence intervals and tests of close fit in the analysis of variance and contrast analysis. Psychological Methods, 9(2), 164-182. doi:10.1037/ 1082989X.9.2.164 <NAME>. (2004). A note on preliminary tests of equality of variances. British Journal of Mathematical and Statistical Psychology, 57(1), 173–181. https://doi.org/10.1348/000711004849222 See Also plot_neat, t_neat Examples # assign random data in a data frame for illustration # (note that the 'subject' is only for illustration; since each row contains the # data of a single subject, no additional subject id is needed) dat_1 = data.frame( subject = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), grouping1 = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 2), grouping2 = c(1, 2, 1, 2, 2, 1, 1, 1, 2, 1), value_1_a = c(36.2, 45.2, 41, 24.6, 30.5, 28.2, 40.9, 45.1, 31, 16.9), value_2_a = c(-14.1, 58.5, -25.5, 42.2, -13, 4.4, 55.5, -28.5, 25.6, -37.1), value_1_b = c(83, 71, 111, 70, 92, 75, 110, 111, 110, 85), value_2_b = c(8.024, -14.162, 3.1, -2.1, -1.5, 0.91, 11.53, 18.37, 0.3, -0.59), value_1_c = c(27.4,-17.6,-32.7, 0.4, 37.2, 1.7, 18.2, 8.9, 1.9, 0.4), value_2_c = c(7.7, -0.8, 2.2, 14.1, 22.1, -47.7, -4.8, 8.6, 6.2, 18.2) ) head(dat_1) # see what we have # For example, numbers '1' and '2' in the variable names of the values can # denote sessions in an experiment, such as '_1' for first session, and '_2 for # second session'. The letters '_a', '_b', '_c' could denote three different # types of techniques used within each session, to be compared to each other. # See further below for a more verbose but more meaningful example data. # get the between-subject effect of 'grouping1' anova_neat(dat_1, values = 'value_1_a', between_vars = 'grouping1') # main effects of 'grouping1', 'grouping2', and their interactions anova_neat(dat_1, values = 'value_1_a', between_vars = c('grouping1', 'grouping2')) # repeated measures: # get the within-subject effect for 'value_1_a' vs. 'value_1_b' anova_neat(dat_1, values = c('value_1_a', 'value_1_b')) # same, but give the factor a custom variable name, and omit BF for speed anova_neat( dat_1, values = c('value_1_a', 'value_1_b'), within_ids = 'a_vs_b', bf_added = FALSE ) # or anova_neat( dat_1, values = c('value_1_a', 'value_1_b'), within_ids = 'letters', bf_added = FALSE ) # within-subject effect for 'value_1_a' vs. 'value_1_b' vs. 'value_1_c' anova_neat( dat_1, values = c('value_1_a', 'value_1_b', 'value_1_c'), bf_added = FALSE ) # within-subject main effect for 'value_1_a' vs. 'value_1_b' vs. 'value_1_c', # between-subject main effect 'grouping1', and the interaction of these two main # effects anova_neat( dat_1, values = c('value_1_a', 'value_1_b', 'value_1_c'), between_vars = 'grouping1', bf_added = FALSE ) # within-subject 'number' main effect for variables with number '1' vs. number # '2' ('value_1_a' and 'value_1_b' vs. 'value_2_a' and 'value_2_b'), 'letter' # main effect for variables with final letterr 'a' vs. final letter 'b' # ('value_1_a' and 'value_2_a' vs. 'value_1_b' and 'value_2_b'), and the # 'letter' x 'number' interaction anova_neat( dat_1, values = c('value_1_a', 'value_2_a', 'value_1_b', 'value_2_b'), within_ids = list( letters = c('_a', '_b'), numbers = c('_1', '_2') ), bf_added = FALSE ) # same as above, but now including between-subject main effect 'grouping2' and # its interactions anova_neat( dat_1, values = c('value_1_a', 'value_2_a', 'value_1_b', 'value_2_b'), within_ids = list( letters = c('_a', '_b'), numbers = c('_1', '_2') ), between_vars = 'grouping2', bf_added = FALSE ) # same as above, but now creating a plot of means # y_title passed add an example title (label) for the Y axis anova_neat( dat_1, values = c('value_1_a', 'value_2_a', 'value_1_b', 'value_2_b'), within_ids = list( letters = c('_a', '_b'), numbers = c('_1', '_2') ), between_vars = 'grouping2', bf_added = FALSE, plot_means = TRUE, y_title = 'Example Y Title' ) # same as above, but collapsing means over the removed "numbers" factor anova_neat( dat_1, values = c('value_1_a', 'value_2_a', 'value_1_b', 'value_2_b'), within_ids = list( letters = c('_a', '_b') ), between_vars = 'grouping2', bf_added = FALSE, plot_means = TRUE, y_title = 'Example Y Title' ) # In real datasets, these could of course be more meaningful. For example, let's # say participants rated the attractiveness of pictures with low or high levels # of frightening and low or high levels of disgusting qualities. So there are # four types of ratings: # 'low disgusting, low frightening' pictures # 'low disgusting, high frightening' pictures # 'high disgusting, low frightening' pictures # 'high disgusting, high frightening' pictures # this could be meaningfully assigned e.g. as below pic_ratings = data.frame( subject = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), rating_fright_low_disgust_low = c(36.2,45.2,41,24.6,30.5,28.2,40.9,45.1,31,16.9), rating_fright_high_disgust_low = c(-14.1,58.5,-25.5,42.2,-13,4.4,55.5,-28.5,25.6,-37.1), rating_fright_low_disgust_high = c(83,71,111,70,92,75,110,111,110,85), rating_fright_high_disgust_high = c(8.024,-14.162,3.1,-2.1,-1.5,0.91,11.53,18.37,0.3,-0.59) ) head(pic_ratings) # see what we have # the same logic applies as for the examples above, but now the # within-subject differences can be more meaningfully specified, e.g. # 'disgust_low' vs. 'disgust_high' for levels of disgustingness, while # 'fright_low' vs. 'fright_high' for levels of frighteningness anova_neat( pic_ratings, values = c( 'rating_fright_low_disgust_low', 'rating_fright_high_disgust_low', 'rating_fright_low_disgust_high', 'rating_fright_high_disgust_high' ), within_ids = list( disgustingness = c('disgust_low', 'disgust_high'), frighteningness = c('fright_low', 'fright_high') ), bf_added = FALSE ) # the results are the same as for the analogous test for the 'dat_1' data, only # with different names # now let's say the ratings were done in two separate groups pic_ratings = data.frame( subject = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), group_id = c(1, 2, 1, 2, 2, 1, 1, 1, 2, 1), rating_fright_low_disgust_low = c(36.2,45.2,41,24.6,30.5,28.2,40.9,45.1,31,16.9), rating_fright_high_disgust_low = c(-14.1,58.5,-25.5,42.2,-13,4.4,55.5,-28.5,25.6,-37.1), rating_fright_low_disgust_high = c(83,71,111,70,92,75,110,111,110,85), rating_fright_high_disgust_high = c(8.024,-14.162,3.1,-2.1,-1.5,0.91,11.53,18.37,0.3,-0.59) ) # now test the effect and interactions of 'group_id' anova_neat( pic_ratings, values = c( 'rating_fright_low_disgust_low', 'rating_fright_high_disgust_low', 'rating_fright_low_disgust_high', 'rating_fright_high_disgust_high' ), within_ids = list( disgustingness = c('disgust_low', 'disgust_high'), frighteningness = c('fright_low', 'fright_high') ), between_vars = 'group_id', bf_added = FALSE ) # again, same results as with 'dat_1' (using 'grouping2' as group_id) ci_from_p CI from p value Description Calculates approximate confidence interval (CI) for any given difference, based on the difference value and p value, according to Altman & Bland (2011). Usage ci_from_p(diff, p_value, ci = 0.95) Arguments diff Difference (number) around which the CI is to be calculated. p_value The p value for CI calculation. ci Numeric; confidence level for the returned CIs (.95 per default). Value CI limits as named numeric vector with two elements. Note Check the Altman & Bland (2011) paper for details! (The calculation for proportions is not imple- mented here.) References <NAME>., & <NAME>. (2011). How to obtain the confidence interval from a P value. Bmj, 343(d2090). doi:10.1136/bmj.d2090 Examples # Example 1 # calculate proportion difference test proptest_stat = prop.test(x = c(49, 40), n = c(50, 50)) # calculate proportion difference my_diff = 49/50-40/50 # calculate approximate CI ci_from_p(my_diff, proptest_stat$p.value) # returned CI should be very similar to the actual CI proptest_stat$conf.int # Example 2 # generate random data v1 = stats::rnorm(190, 40, 60) v2 = stats::rnorm(170, 50, 45) # calculate t-test ttest_stat = stats::t.test(v1, v2) # calculate mean difference my_diff = mean(v1) - mean(v2) # calculate approximate CI ci_from_p(my_diff, ttest_stat$p.value) # returned CI should be similar to the actual CI ttest_stat$conf.int corr_neat Correlation Statistics Description Pearson correlation results including confidence interval (CI) and correlation Bayes factor (BF). For non-parametric version, Spearman’s rank correlation results along with corresponding rank-based BFs (as per van Doorn et al., 2020). Usage corr_neat( var1, var2, nonparametric = FALSE, ci = 0.95, bf_added = FALSE, direction = NULL, round_r = 3, for_table = FALSE, sb_correction = FALSE, hush = FALSE ) Arguments var1 Numeric vector; numbers of the first variable. var2 Numeric vector; numbers of the second variable. nonparametric Logical (FALSE by default). If TRUE, uses nonparametric tests (Spearman’s rank correlation, including BFs; see Details). ci Numeric; confidence level for the returned CI, as implemented in cor.test. bf_added Logical. If TRUE (default), Bayes factor is calculated and displayed. direction NULL or string; optionally specifies one-sided test: either "negative" (negative correlation expected) or "positive" (positive correlation expected). (Short forms also work, e.g. "p", "pos", "neg", etc.) If NULL (default), the test is two-sided. round_r Number to round to the correlation and its CI. for_table Logical. If TRUE, omits the confidence level display from the printed text. sb_correction Logical. If TRUE, applies Spearman-Brown correction (2 * r / (1+r)) to the correlation (including CI). hush Logical. If TRUE, prevents printing any details to console. Details The Bayes factor (BF) is calculated with the default r-scale of 1/3 for parametric test, and with the default r-scale of 1 for nonparametric test. BF supporting null hypothesis is denoted as BF01, while that supporting alternative hypothesis is denoted as BF10. When the BF is smaller than 1 (i.e., supports null hypothesis), the reciprocal is calculated (hence, BF10 = BF, but BF01 = 1/BF). When the BF is greater than or equal to 10000, scientific (exponential) form is reported for readability. (The original full BF number is available in the returned named vector as bf.)#’ Value Prints correlation statistics (including CI and BF) in APA style. Furthermore, when assigned, re- turns a named vector with the following elements: r (Pearson correlation), p (p value), bf (Bayes factor). Note The correlation and CI is calculated via stats::cor.test. The parametric Bayes factor is calculated via BayesFactor::correlationBF. The nonparamet- ric (rank-based) Bayes factor is a contribution by <NAME>; the original source code is available via https://osf.io/gny35/. References <NAME>. (1910). Some experimental results in the correlation of mental abilities. British Journal of Psychology, 1904-1920, 3(3), 296-322. doi:10.1111/j.20448295.1910.tb00207.x <NAME>., <NAME>, & <NAME>. (2013). The reliability of a two-item scale: Pearson, Cronbach, or Spearman-Brown? International Journal of Public Health, 58(4), 637-642. doi:10.1007/ s0003801204163 <NAME>. (1910). Correlation calculated from faulty data. British Journal of Psychology, 1904- 1920, 3(3), 271-295. doi:10.1111/j.20448295.1910.tb00206.x <NAME>., <NAME>., <NAME>., & <NAME>. (2020). Bayesian rank-based hypothesis testing for the rank sum test, the signed rank test, and Spearman’s rho. Journal of Applied Statistics, 1–23. doi:10.1080/02664763.2019.1709053 See Also t_neat Examples # assign two variables v1 = c(11, 15, 19, 43, 53, -4, 34, 8, 33, -1, 54 ) v2 = c(4, -2, 23, 13, 32, 16, 3, 29, 37, -4, 65 ) corr_neat(v1, v2) # prints statistics # one-sided, and omitting the "95% CI" part corr_neat(v1, v2, direction = 'pos', for_table = TRUE) # print statistics and assign main results results = corr_neat(v1, v2, direction = 'pos') results['p'] # get precise p value dems_neat Demographics Description Prints participant count, age mean and SD, and gender ratio, from given dataset. Usage dems_neat( data_per_subject, group_by = NULL, gender_col = NULL, age_col = NULL, male = "male", female = "female", percent = FALSE, round_perc = 0, show_fem = NULL, age_range = FALSE, age_min = NULL, age_max = NULL ) Arguments data_per_subject Data frame from which demographics are to be calculated. Should contain columns named as "age" and as "gender" (or, alternatively, "sex"). Alterna- tively, these columns can be specified via the gender_col and age_col param- eters. The age column must contain only numbers or NA, while gender column must contain only 1 (= male) or 2 (= female), either as numbers or as strings, or NA. Alternatively, different gender coding can be set via the parameters male and female (but 1/2 will be checked for first in any case). group_by Optionally the name(s) of column(s) from the data frame provided as data_per_subject to group by. gender_col Optionally the name of column from the data frame that contains the gender (sex) information. age_col Optionally the name of column from the data frame that contains the age infor- mation. male Alternative code for male: by default, it is the string "male". Whatever string is given, its abbreviations will also be accepted (e.g. "m"). (Lettercases do not matter, e.g. Male or MALE are both evaluated same as male.) female Alternative code for female: by default, it is the string "female". Whatever string is given, its abbreviations will also be accepted (e.g. "fem"). (Lettercases do not matter.) percent Logical. If TRUE, gender ratios (and the "unknown" ratios based on NA values) are presented as percentage. If FALSE, they are presented as counts (i.e., numbers of subjects). round_perc Number to round to, when using percentages. show_fem Logical or NULL. If TRUE, the numbers of both male and female are displayed. If FALSE, only the number of males is displayed. If NULL (default), only the number of males is displayed when there are no unknown cases, but both numbers are displayed when there are any unknown cases. age_range Logical, FALSE by default. If TRUE, also displays age range per group (minimum and maximum ages). age_min If numeric given, removes all ages below (exclusive!) the given number before any age calculation.#’ age_max If numeric given, removes all ages above (exclusive!) the given number before any age calculation. Details If gender_col and/or age_col are not specified, the function will first look for columns named precisely "age" and as "gender". If either is not found, the function looks for the same names but with any lettercase (e.g. "AGE" or "Gender"). If still no "gender" column is found, the function looks for "sex" column in the same manner. If no column is found for either, all related values will be counted as "unknown" (NA). If NA values are found in either the age or gender column, the ratio (or count) of unknown cases will be displayed everywhere. Otherwise it will simply not be displayed anywhere. Examples # below is an illustrative example dataset # (the "subject" and "measure_x" columns are not used in the function) dat = data.frame( subject = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), conditions = c('x', 'y', 'x', 'y', 'y', 'x', 'x', 'x', 'y', 'x'), gender = c(2, 2, 1, 2, 1, 2, 2, 2, 1, 1), age = c(6, 7, 8.5, 6, 5, 16.5, 17, 16, 45.8, 77), measure_x = c(83, 71, 111, 70, 92, 75, 110, 111, 110, 85), stringsAsFactors = TRUE ) # print demographics (age and gender) per "conditions": dems_neat(dat, group_by = 'conditions') # replace unlikely ages with NAs dems_neat(dat, group_by = 'conditions', age_min = 8, age_max = 50) # remove only high values, and display age ranges dems_neat(dat, group_by = 'conditions', age_max = 45, age_range = TRUE) # another dataset, with some missing values dat = data.frame( subject = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), conditions = c('x', 'y', 'x', 'y', 'y', 'x', 'x', 'x', 'y', 'x'), gender = c(2, 2, NA, NA, 1, 1, 1, 2, NA, NA), age = c(6, 7, 8.5, 6, 5, 16, NA, 16, 45, 77), measure_x = c(83, 71, 111, 70, 92, 75, 110, 111, 110, 85), stringsAsFactors = TRUE ) # again print demographics per "conditions": dems_neat(dat, group_by = 'conditions') # another dataset, with no "age"/"gender" columns dat = data.frame( subject = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), conditions = c('x', 'y', 'x', 'y', 'y', 'x', 'x', 'x', 'y', 'x'), geschlecht = c(2, 2, NA, NA, 1, 1, 1, 2, NA, NA), alter = c(6, 7, 8.5, 6, 5, 16, NA, 16, 45, 77), measure_y = c(83, 71, 111, 70, 92, 75, 110, 111, 110, 85), stringsAsFactors = TRUE ) # the following will return "unknowns" dems_neat(dat, group_by = 'conditions') # gender column specified dems_neat(dat, group_by = 'conditions', gender_col = 'geschlecht') # both columns specified dems_neat(dat, group_by = 'conditions', age_col = 'alter', gender_col = 'geschlecht') enum Enumerate Description Aids enumeration and merging (via rbind_loop) in loops: adds numbers to a vector input, and indicates loop start for rbind_loop. Usage enum(items, hush = FALSE, enumerate = TRUE) Arguments items The items to be enumerated in the loop. hush Logical. If TRUE (default), prints "Loop started." when executed. enumerate Logical. If TRUE (default), adds numbering to the input vector (in item pairs, see Examples). If FALSE, returns the original input. Value Vector with numbers added (if so set). See Also rbind_loop Examples my_vector = c('aa', 'bb', 'cxyz', 'last') for (item in enum(my_vector)) { print(item) } # just to show what enum() returns enum(my_vector) excl_neat Exclusion Description Filters dataset by rows (normally: subjects, observations) and prints the numbers of excluded rows and remaining rows. Returns the filtered dataset and (optionally) also the excluded rows. Usage excl_neat( dat, filt, excluded = FALSE, group_by = NULL, sort_by = "exclusion", hush = FALSE ) Arguments dat Data frame to be filtered. filt An expression to use for filtering, by column values, the dat data frame. (Only the rows for which the filter expression is TRUE will be kept.) excluded Logical; FALSE by default. If TRUE, the function returns not only the filtered data frame, but also a data frame containing the excluded rows. The returned object in this case will be a list with two elements: (1) the filtered data frame named filtered, and (2) the data frame with excluded rows named excluded (see Examples). group_by String, or vector of strings: the name(s) of the column(s) in the dat data frame, containing the vector(s) of factors by which the printed counts are grouped. sort_by String; specifies whether the printed counts should be sorted by exclusion (de- fault; "exclusion" or its short forms, e.g. "excl"), or by the factors given for group_by (for this, give any other string, e.g. "conditions"). If NULL (default). hush Logical. If TRUE, prevents printing counts to console. Value A data frame with the rows for which the filt expression is TRUE, or, optionally, a list with this data frame plus a data frame with the excluded rows. At the same time, prints, by default, the count of remaining and excluded rows. See Also aggr_neat Examples data("mtcars") # load base R example dataset # filter mtcars for mpg > 20 excl_neat(mtcars, mpg > 20) # assign the same mtcars_filtered = excl_neat(mtcars, mpg > 20) # (mtcars_filtered now contains the filtered subset) # return and assign excluded rows too mtcars_filtered_plus_excluded = excl_neat(mtcars, mpg > 20, excluded = TRUE) # print filtered data frame print(mtcars_filtered_plus_excluded$filtered) # print data frame with excluded rows print(mtcars_filtered_plus_excluded$excluded) # group printed count by cyl excl_neat(mtcars, mpg > 20, group_by = 'cyl') # sort output by grouping excl_neat(mtcars, mpg > 20, group_by = 'cyl', sort_by = 'group') # group by cyl amd carb excl_neat(mtcars, mpg > 15, group_by = c('cyl', 'carb')) # longer filter expression excl_neat(mtcars, mpg > 15 & gear == 4, group_by = 'cyl',) mean_ci Confidence Interval of Mean Description Calculates confidence interval of a vector of numbers. Usage mean_ci(x, distance_only = TRUE, ci = 0.95) Arguments x Numeric vector. distance_only Logical. If TRUE (default), the function returns only the distance between the mean and either confidence interval limit. Otherwise returns the confidence interval (i.e., both limits). ci Numeric; confidence level for returned CI. Value Distance of limit or confidence interval (as named vector). See Also se, plot_neat, sd_ci Examples myvec = c(11, 15, 19, 43, 53, -4, 34, 8, 33, -1, 54 ) mean_ci( myvec, FALSE ) mean_ci( myvec, FALSE, ci = .80 ) mean_ci( myvec, ci = .80 ) mon_conv Monitor Screen Unit Conversion Description Given a specific monitor object, converts specified screen units to other specified units. The possible units to convert from and to: "cm" (centimeters), "pix" (pixels), or "deg" (degrees of visual angle). Usage mon_conv(mon_obj, value, from, to) Arguments mon_obj Monitor object, as assigned with mon_neat. value Number; value (magnitude) of the given unit to convert from. (Can be vector as well.) from String; unit ("cm", "pix", or "deg") to convert from. to String; unit ("cm", "pix", or "deg") to convert to. Value Number (magnitude) in the given output (to) unit. See Also mon_neat Examples # assign monitor with 50 cm distance, screen width 52 cm and 1920 pixels my_mon = mon_neat(distance = 50, mon_width_cm = 52, mon_width_pixel = 1920) # convert 30.4 pixels to degrees of visual angle, for the specified monitor mon_conv(my_mon, 30.4, 'pix', 'deg') # returns 0.9434492 (degrees) # convert 0.94 degrees of visual angle to pixels mon_conv(my_mon, 0.94, 'deg', 'pix') # returns 30.28885 (pixels) # convert 10 degrees of visual angle to cm mon_conv(my_mon, 10, from = 'deg', to = 'cm') # convert 8.748866 cm to pixels mon_conv(my_mon, 8.748866, from = 'cm', to = 'pix') mon_neat Monitor Object Description Assigns a monitor object, storing distance and width parameters. Usage mon_neat(distance, mon_width_cm, mon_width_pixel) Arguments distance Viewing distance in cm (from eyes to screen). mon_width_cm Monitor screen width in cm. mon_width_pixel Monitor screen width in pixels. Value A monitor object with the specified parameters, to be used in the mon_conv function. See Also mon_conv Examples # assign monitor with 57 cm viewing distance, screen width 52 cm and 1920 pixels my_mon = mon_neat(distance = 57, mon_width_cm = 52, mon_width_pixel = 1920) norm_tests Normality Tests and Plots Description Performs normality tests and creates related plots (histogram, density, Q-Q). This is primarily a sub- function of t_neat and anova_neat, but here it is available separately for other potential purposes. Usage norm_tests( var1, var2 = NULL, pair = FALSE, norm_tests = "all", alpha = 0.05, plots = FALSE, aspect_ratio = 1, hush = FALSE ) Arguments var1 Numeric vector; numbers of any given variable. var2 Optional numeric vector (or NULL); numbers of a second variable. pair Logical; only matters if var2 is not null. In that case, if TRUE each normality test is performed for the difference values between the two variables in case of paired samples, or, if FALSE, separately for each of the two variables for unpaired samples. norm_tests Normality tests. Any or all of the following character input is accepted (as a single string or a character vector; case-insensitive): "W" (Shapiro-Wilk), "K2" (D’Agostino), "A2" (Anderson-Darling), "JB" (Jarque-Bera); see Notes. The option "all" (default value) selects all four previous tests at the same time. alpha Numeric (.05 by default), alpha level: if any p value if below this alpha level, the function returns TRUE, otherwise FALSE. plots Logical: if TRUE adds histogram, density, and Q-Q plots. (Note: in case of paired samples, Q-Q plots are plotted on a separate figure. In RStudio, press on "Previous plot" under "Plots" to see these Q-Q plots.) aspect_ratio Aspect ratio of the plots: 1 (1/1) by default. (Set to NULL for dynamic aspect ratio.) hush Logical. If TRUE, prevents printing any details to console. Value Prints normality tests, and displays plots if so specified. Returns TRUE if any of the specified tests has p value below the specified alpha, otherwise returns FALSE. Note Normality tests are all calculated via fBasics::NormalityTests, selected based on the recom- mendation of Lakens (2015), quoting Yap and Sim (2011, p. 2153): "If the distribution is sym- metric with low kurtosis values (i.e. symmetric short-tailed distribution), then the D’Agostino and Shapiro-Wilkes tests have good power. For symmetric distribution with high sample kurtosis (sym- metric long-tailed), the researcher can use the JB, Shapiro-Wilkes, or Anderson-Darling test." See urlhttps://github.com/Lakens/perfect-t-test for more details. References <NAME>. (2015). The perfect t-test (version 1.0.0). Retrieved from https://github.com/Lakens/perfect- t-test. doi:10.5281/zenodo.17603 <NAME>., & <NAME>. (2011). Comparisons of various types of normality tests. Journal of Statistical Computation and Simulation, 81(12), 2141–2155. doi:10.1080/00949655.2010.520163 See Also t_neat Examples norm_tests(stats::rnorm(100)) # should be normal... path_neat Script Path Description Gives, in RStudio, the path to the script file in which it is executed. Usage path_neat(subdir = "") Arguments subdir String, optional. Subdirectory relative to the script’s path. Value Script file’s path as string. If subdir is given, it is appended to the original path. Examples # assuming the given script is at path "C:/script_folder/" path_neat('') # returns "C:/script_folder/" path_neat('my_subdir/misc/') # returns "C:/script_folder/my_subdir/misc/" # Note: the returned string can be used as argument for base::setwd() # e.g. setwd( path_neat() ) # sets working directory to the script's path peek_neat Cursory Summaries and Plots per Group Description Cursory summaries and plots per group. Usage peek_neat( dat, values, group_by = NULL, filt = NULL, sep = ", ", collapse = NULL, f_print = FALSE, f_plot = NULL, iqr_times = 3, round_to = 4, group_n = TRUE, ... ) Arguments dat Data frame (or name of data frame as string). values String, or vector of strings: the name(s) of the column(s) in the dat data frame, containing the vector(s) of values. group_by String, or vector of strings: the name(s) of the column(s) in the dat data frame, containing the vector(s) of factors by which the statistics are grouped. filt An expression to filter, by column values, the entire dat data frame before per- forming the aggregation. The expression should use column names alone; see Examples. sep String (comma by default) for separating group names. collapse Decides how to handle multiple columns of values. If NULL (default), displays each column of values as separate groups. Alternatively, any function can be given using which the columns are collapsed into a single column. For example, if mean is given for this parameter, a single column will be calculated based on the means of all given values columns. (NA is always ignored.) f_print Printing function; see details. f_plot Plotting function; see details. (Provide string to skip plotting.) iqr_times The multiplication of IQR to calculate Tukey’s fences, when using default f_print function (set to TRUE); see Details. The default is 3 to spot Tukey’s "far outliers" (e.g. by comparing the fences with min and max values). (Note that the usual fences, e.g. for box plots, use 1.5). round_to Number of significant fractional digits to round to, when using default f_print function (set to TRUE). group_n Logical. If TRUE, adds sample sizes (n) per group to plots when using default f_plot (NULL). ... Any arguments to be passed to the f_plot function. Details If set to TRUE, prints to console the following data (per group): mean; 95 median; quantile_1st and quantile_3rd (first and third quantiles); "Tukey’s fences" as fence_low and fence_upp; min- imum and maximum values (min, max); number of NAs (na). Tukey’s fences are the upper and lower limits with distances of X times the IQR from the actual IQR, where X is specified via the iqr_times parameter. Returns (invisibly) the same values, unrounded, via a data frame. If alternative f_print is given, prints whatever value is returned from the given function (and attempts, if possible, to create a data frame). Creates and displays box plot(s) (per group) by default, along with overlayed violin plot (densities proportionate to sample sizes). If alternative f_plot is given, the first argument will be the values per group, and all plots will be arranged into a single plot and displayed together. To skip plotting, just give any character as argument (e.g. "none" or just ""). Value Data frame with the printed values (if possible). Examples data("mtcars") # load base R example dataset # overall info for wt (Weight) peek_neat(mtcars, 'wt', f_print = TRUE) #' # now groupped by cyl (Number of cylinders) peek_neat(mtcars, 'wt', group_by = 'cyl') # grouped by cyl and gear peek_neat(mtcars, 'wt', group_by = c('cyl', 'gear'), f_print = TRUE) # filter to only have cyl larger than 4 peek_neat(mtcars, 'wt', group_by = 'cyl', filt = cyl > 4) # without plots peek_neat(mtcars, 'wt', group_by = 'cyl', f_plot = "", f_print = TRUE) # with histogramms etc, using plot_neat peek_neat(mtcars, 'wt', group_by = 'cyl', f_plot = plot_neat) # with Q-Q plots, via ggpubr peek_neat(mtcars, 'wt', group_by = 'cyl', f_plot = ggpubr::ggqqplot) # skewness and kurtosis data via psych ## Not run: info_df = peek_neat( mtcars, 'wt', group_by = 'cyl', f_print = psych::describe, f_plot = "" ) info_df # contains all data returns by psych::describe ## End(Not run) plot_neat Plots of Means and of Dispersion Description Primarily for line and bar plots for factorial designs. Otherwise (if no data_per_subject is given) descriptive dispersion plots (histogram, density, or box plots) for a continuous variable. (For the latter, only the parameters values, parts, part_colors, and binwidth are used, the rest are ignored.) Usage plot_neat( data_per_subject = NULL, values = NULL, within_ids = NULL, between_vars = NULL, factor_names = NULL, value_names = NULL, y_title = NULL, reverse = FALSE, panels = NULL, type = "line", dodge = NULL, bar_colors = "viridis", line_colors = "viridis", row_number = 1, method = mean, eb_method = neatStats::mean_ci, numerics = FALSE, hush = FALSE, parts = c("h", "d", "n", "b"), part_colors = NULL, binwidth = NULL ) Arguments data_per_subject Data frame containing all values (measurements/observations for a factorial de- sign) in a single row per each subject. Otherwise, if no data frame is given (de- fault: NULL), histogram, density, or box plots will be returned for a continuous variable (numeric vector). values For plots of means (factorial designs): vector of strings; column name(s) in the data_per_subject data frame. Each column should contain a single dependent variable: thus, to plot repeated (within-subject) measurements, each specified column should contain one measurement. For descriptive dispersion plots (if data_per_subject is NULL), a numeric vector is expected. within_ids NULL (default), string, or named list. In case of no within-subject factors, leave as NULL. In case of a single within subject factor, a single string may be given to optionally provide custom name for the within-subject factor (note: this is a programming variable name, so it should not contain spaces, etc.); other- wise (if left NULL) this one within-subject factor will always just be named "within_factor". In case of multiple within-subject factors, each factor must be specified as a named list element, each with a vector of strings that distin- guish the levels within that factors. The column names given as values should always contain one (and only one) of these strings within each within-subject factor, and thus they will be assigned the appropriate level. For example, values = 'rt_s1_neg, rt_s1_pos,rt_s2_neg, rt_s2_pos' could have within_ids = list( session = c('s1','s2'), valence = c('pos', 'neg'). (Note: the strings for distinguishing must be unambiguous. E.g., for values apple_a and apple_b, do not set levels c('a','b'), because 'a' is also found in apple_b. In this case, you could choose levels c('_a','_b') to make sure the values are correctly distinguished.) See also Examples. between_vars NULL (default; in case of no between-subject factors) or vector of strings; column name(s) in the data_per_subject data frame. Each column should contain a single between-subject independent variable (representing between-subject fac- tors). factor_names NULL or named vector. In a named vector, factor names (either within or be- tween) can be given a different name for display, in a dictionary style, using original factor name as the name of a vector element, and the element’s value (as string) for the new name. For example, to change a factor named "condition" to "High vs. low arousal", the vector may be given (in this case with a single element) as factor_names = c(condition = "High vs. low arousal"). value_names NULL or named vector. Same as factor_names, but regarding the factor values. For example, to change values "high_a" and "low_a" to "High" and "Low" for display, the vector may be given as value_names = c(high_a = "High",low_a = "Low"). y_title NULL (default) or string. Optionally given title for the y axis. reverse Logical (default: FALSE). If TRUE, reverses the default grouping of variables within the figure, or within each panel, in case of multiple panels. (The default grouping is decided automatically by given factor order, but always starting, when applicable, with within-subject factors: first factor is split to adjacent bars, or vertically aligned dots in case of line plot.) panels NULL or string. Optionally gives the factor name by which the plot is to be split into different panels, in case of three factors. (By default, the third given factor is used.) type Strong: "line" (default) or "bar". The former gives line plot, the latter gives bar plot. dodge Number. Specifies the amount by which the adjacent bars or dots ’dodge’ each other (i.e., are displaced compared to each other). (Default is 0.1 for line plots, and 0.9 for bar plots.) bar_colors Vector of strings, specifying colors from which all colors for any number of differing adjacent bars are interpolated. (If the number of given colors equal the number of different bars, the precise colors will correspond to each bar.) The default 'viridis' gives a color gradient based on viridis. (In case of a single factor, the first given colors is taken.) line_colors Vector of strings, specifying colors from which all colors for any number of differing vertically aligned dots and corresponding lines are interpolated. The default 'viridis' gives a color gradient based on viridis. (In case of a single factor, the first given colors is taken.) row_number Number. In case of multiple panels, the number of rows in which the panels should be arranged. For example, with the default row_number = 1, all panels will be displayed in one vertically aligned row. method A function (default: mean) for the calculation of the main statistics (bar or dot heights). eb_method A function (default: mean_ci for 95 the calculation of the error bar size (as a single value used for both directions of the error bar). If set to NULL, no error bar is displayed.#’ numerics If FALSE (default), returns ggplot object. If set to TRUE, returns only the numeric aggregated data per grouping factors, as specified by method and eb_method functions. If set to any string (e.g. "both"), returns the numeric aggregated data and at the same time draws the plot. hush Logical. If TRUE, prevents printing aggregated values. parts For dispersion plots only (if no data_per_subject is given). A vector of char- acters that specify which types of overlayed types to plot: "h" for histogram, "d" for density, "n" normally distributed density (using the mean and standard deviation of the given variable), "b" for boxplot. (All are included by default: parts = c("h", "d", "n", "b")). part_colors For dispersion plots only (if no data_per_subject is given). A named that can specify and thereby override default colors and alpha (transparency) of each plot type. Colors can be given by adding "c" to the plot type letter, e.g. c(hc = "blue") for blue histogram. Alpha can be given by adding "a" to the plot type letter, e.g. c(ha = 0) for completely transparent histogram. Any number may be given: e.g. a dark red transparent histogram with green boxplot would be part_colors = c(hc = "#cc0000", ha = 0.1, bc = "green"). binwidth For dispersion plots only (if no data_per_subject is given). Binwidth for histograms. If NULL (default), Freedman–Diaconis rule is used if it produces at least 10 bins – otherwise 1bandwidth is calculated for 10 bins. Value By default, a ggplot plot object. (This object may be further modified or adjusted via regular ggplot methods.) If so set (numerics), aggregated values as specified by the methods. Note More than three factors is not allowed: it would make little sense and it would be difficult to clearly depict in a simple figure. (However, you can build an appropriate graph using ggplot directly; but you can also just divide the data to produce several three-factor plots, after which you can use e.g. ggpubr’s ggarrange to easily collate the plots.) See Also anova_neat, mean_ci, se Examples # assign random data in a data frame for illustration # (note that the 'subject' is only for illustration; since each row contains the # data of a single subject, no additional subject id is needed) dat_1 = data.frame( subject = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14), grouping1 = c(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2), grouping2 = c(1, 2, 1, 2, 2, 1,2, 1,2,1, 1, 1, 2, 1), value_1_a = c(36.2, 45.2, 41, 24.6, 30.5, 28.2, 40.9, 45.1, 31, 16.9, 40.1, 42.1, 41, 12.9), value_2_a = c(-14.1, 58.5,-25.5, 42.2,-13, 4.4, 55.5,-28.5, 25.6,-37.1, 55.1,-38.5, 28.6,-34.1), value_1_b = c(83, 71, 111, 70, 92, 75, 110, 111, 110, 85, 132, 121, 151, 95), value_2_b = c(8.024,-14.162, 3.1,-2.1,-1.5, 0.91, 11.53, 18.37, 0.3,-0.59, 12.53, 13.37, 2.3,-3), value_1_c = c(27.4, -17.6, -32.7, 0.4, 37.2, 1.7, 18.2, 8.9, 1.9, 0.4, 2.7, 14.2, 3.9, 4.9), value_2_c = c(7.7,-0.8, 2.2, 14.1, 22.1,-47.7,-4.8, 8.6, 6.2, 18.2,-6.8, 5.6, 7.2, 13.2) ) head(dat_1) # see what we have # plot for factors 'grouping1', 'grouping2' plot_neat( data_per_subject = dat_1, values = 'value_1_a', between_vars = c('grouping1', 'grouping2') ) # same as above, but with bars and renamed factors plot_neat( data_per_subject = dat_1, values = 'value_1_a', between_vars = c('grouping1', 'grouping2'), type = 'bar', factor_names = c(grouping1 = 'experimental condition', grouping2 = 'gender') ) # same, but with different (lighter) gray scale bars plot_neat( dat_1, values = 'value_1_a', between_vars = c('grouping1', 'grouping2'), type = 'bar', factor_names = c(grouping1 = 'experimental condition', grouping2 = 'gender'), bar_colors = c('#555555', '#BBBBBB') ) # same, but with red and blue bars plot_neat( dat_1, values = 'value_1_a', between_vars = c('grouping1', 'grouping2'), type = 'bar', factor_names = c(grouping1 = 'experimental condition', grouping2 = 'gender'), bar_colors = c('red', 'blue') # equals c('#FF0000', '#0000FF') ) # within-subject factor for 'value_1_a' vs. 'value_1_b' vs. 'value_1_c' # (automatically named 'within_factor'), between-subject factor 'grouping1' plot_neat( dat_1, values = c('value_1_a', 'value_1_b', 'value_1_c'), between_vars = c('grouping1', 'grouping2') ) # same, but panelled by 'within_factor' plot_neat( dat_1, values = c('value_1_a', 'value_1_b', 'value_1_c'), between_vars = c('grouping1', 'grouping2'), panels = 'within_factor' ) # same, but SE for error bars instead of (default) SD plot_neat( dat_1, values = c('value_1_a', 'value_1_b', 'value_1_c'), between_vars = c('grouping1', 'grouping2'), panels = 'within_factor', eb_method = se ) # same, but 95% CI for error bars instead of SE # (arguably more meaningful than SEs) plot_neat( dat_1, values = c('value_1_a', 'value_1_b', 'value_1_c'), between_vars = c('grouping1', 'grouping2'), panels = 'within_factor', eb_method = mean_ci ) # same, but using medians and Median Absolute Deviations plot_neat( dat_1, values = c('value_1_a', 'value_1_b', 'value_1_c'), between_vars = c('grouping1', 'grouping2'), panels = 'within_factor', method = stats::median, eb_method = stats::mad ) # within-subject factor 'number' for variables with number '1' vs. number '2' # ('value_1_a' and 'value_1_b' vs. 'value_2_a' and 'value_2_b'), factor 'letter' # for variables with final letter 'a' vs. final letter 'b' ('value_1_a' and # 'value_2_a' vs. 'value_1_b' and 'value_2_b') plot_neat( dat_1, values = c('value_1_a', 'value_2_a', 'value_1_b', 'value_2_b'), within_ids = list( letters = c('_a', '_b'), numbers = c('_1', '_2') ) ) # same as above, but now including between-subject factor 'grouping2' plot_neat( dat_1, values = c('value_1_a', 'value_2_a', 'value_1_b', 'value_2_b'), within_ids = list( letters = c('_a', '_b'), numbers = c('_1', '_2') ), between_vars = 'grouping2' ) # same as above, but renaming factors and values for display plot_neat( dat_1, values = c('value_1_a', 'value_2_a', 'value_1_b', 'value_2_b'), within_ids = list( letters = c('_a', '_b'), numbers = c('_1', '_2') ), between_vars = 'grouping2', factor_names = c(numbers = 'session (first vs. second)'), value_names = c( '_1' = 'first', '_2' = 'second', '1' = 'group 1', '2' = 'group 2' ) ) # In real datasets, these could of course be more meaningful. For example, let's # say participants rated the attractiveness of pictures with low or high levels # of frightening and low or high levels of disgusting qualities. So there are # four types of ratings: # 'low disgusting, low frightening' pictures # 'low disgusting, high frightening' pictures # 'high disgusting, low frightening' pictures # 'high disgusting, high frightening' pictures # this could be meaningfully assigned e.g. as below pic_ratings = data.frame( subject = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), rating_fright_low_disgust_low = c(36.2, 45.2, 41, 24.6, 30.5, 28.2, 40.9, 45.1, 31, 16.9), rating_fright_high_disgust_low = c(-14.1, 58.5,-25.5, 42.2,-13, 4.4, 55.5,-28.5, 25.6,-37.1), rating_fright_low_disgust_high = c(83, 71, 111, 70, 92, 75, 110, 111, 110, 85), rating_fright_high_disgust_high = c(8.024,-14.162, 3.1,-2.1,-1.5, 0.91, 11.53, 18.37, 0.3,-0.59) ) head(pic_ratings) # see what we have # the same logic applies as for the examples above, but now the # within-subject differences can be more meaningfully specified, e.g. # 'disgust_low' vs. 'disgust_high' for levels of disgustingness, while # 'fright_low' vs. 'fright_high' for levels of frighteningness plot_neat( pic_ratings, values = c( 'rating_fright_low_disgust_low', 'rating_fright_high_disgust_low', 'rating_fright_low_disgust_high', 'rating_fright_high_disgust_high' ), within_ids = list( disgustingness = c('disgust_low', 'disgust_high'), frighteningness = c('fright_low', 'fright_high') ) ) # now let's say the ratings were done in two separate groups pic_ratings = data.frame( subject = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), group_id = c(1, 2, 1, 2, 2, 1, 1, 1, 2, 1), rating_fright_low_disgust_low = c(36.2, 45.2, 41, 24.6, 30.5, 28.2, 40.9, 45.1, 31, 16.9), rating_fright_high_disgust_low = c(-14.1, 58.5,-25.5, 42.2,-13, 4.4, 55.5,-28.5, 25.6,-37.1), rating_fright_low_disgust_high = c(83, 71, 111, 70, 92, 75, 110, 111, 110, 85), rating_fright_high_disgust_high = c(8.024,-14.162, 3.1,-2.1,-1.5, 0.91, 11.53, 18.37, 0.3,-0.59) ) # now include the 'group_id' factor in the plot plot_neat( pic_ratings, values = c( 'rating_fright_low_disgust_low', 'rating_fright_high_disgust_low', 'rating_fright_low_disgust_high', 'rating_fright_high_disgust_high' ), within_ids = list( disgustingness = c('disgust_low', 'disgust_high'), frighteningness = c('fright_low', 'fright_high') ), between_vars = 'group_id' ) ## DISPERSION PLOTS plot_neat(values = rnorm(100)) # with smaller binwidth (hence more bins) plot_neat(values = rnorm(100), binwidth = 0.2) # without normal distribution line plot_neat(values = rnorm(100), parts = c('h', 'd', 'b')) # without histrogram plot_neat(values = rnorm(100), parts = c('d', 'n', 'b')) # blue density, fully opaque histogram plot_neat(values = rnorm(100), part_colors = c(dc = 'blue', ha = 1)) props_neat Difference of Two Proportions Description Comparison of paired and unpaired proportions. For unpaired: Pearson’s chi-squared test or unconditional exact test, including confidence interval (CI) for the proportion difference, and corresponding independent multinomial contingency table Bayes factor (BF). (Cohen’s h and its CI are also calculated.) For paired tests, classical (asymptotic) McNemar test (optionally with mid-P as well), including confidence interval (CI) for the proportion difference. Usage props_neat( var1 = NULL, var2 = NULL, case1 = NULL, case2 = NULL, control1 = NULL, control2 = NULL, prop1 = NULL, prop2 = NULL, n1 = NULL, n2 = NULL, pair = FALSE, greater = NULL, ci = NULL, bf_added = FALSE, round_to = 3, exact = FALSE, inverse = FALSE, yates = FALSE, midp = FALSE, h_added = FALSE, for_table = FALSE, hush = FALSE ) Arguments var1 First variable containing classifications, in ’group 1’, for the first proportion (see Examples). If given (strictly necessary for paired proportions), proportions will be defined using var1 and var2 (see Details). To distinguish classification (’cases’ and ’controls’; e.g. positive outcomes vs. negative outcomes), any two specific characters (or numbers) can be used. However, more than two different elements (apart from NAs) will cause error. var2 Second variable containing classifications in, ’group 2’, for the second propor- tion, analogously to var1. case1 Number of ’cases’ (as opposed to ’controls’; e.g. positive outcomes vs. negative outcomes) in ’group 1’. As counterpart, either control numbers or sample sizes needs to be given (see Details). case2 Number of ’cases’ in ’group 2’. control1 Number of ’controls’ in ’group 1’. As counterpart, case numbers need to be given (see Details). control2 Number of ’controls’ in ’group 2’. prop1 Proportion in ’group 1’. As counterpart, sample sizes need to be given (see Details). prop2 Proportion in ’group 2’. n1 Number; sample size of ’group 1’. n2 Number; sample size of ’group 2’. pair Logical. Set TRUE for paired proportions (McNemar, mid-P), or FALSE (default) for unpaired (chi squared, or unconditional exact test). Note: paired data must be given in var1 and var2. greater NULL or string (or number); optionally specifies one-sided exact test: either "1" (case1/n1 proportion expected to be greater than case2/n2 proportion) or "2" (case2/n2 proportion expected to be greater than case1/n1 proportion). If NULL (default), the test is two-sided. ci Numeric; confidence level for the returned CIs (proportion difference and Co- hen’s h). bf_added Logical. If TRUE, Bayes factor is calculated and displayed. (Always two-sided!) round_to Number to round to the proportion statistics (difference and CIs). exact Logical, FALSE by default. If TRUE, unconditional exact test is calculated and displayed, otherwise the default Pearson’s chi-squared test. inverse Logical, FALSE by default. When var1 and var2 are given to calculate propor- tion from, by default the factors’ frequency determines which are ’cases’ and which are ’controls’ (so that the latter are more frequent). If the inverse argu- ment is TRUE, it reverses the default proportion direction. yates Logical, FALSE by default. If TRUE, Yates’ continuity correction is applied to the chi-squared (unpaired) or the McNemar (paired) test. Some authors advise this correction for certain specific cases (e.g., small sample), but evidence does not seem to support this (<NAME> & Ruxton, 2020). midp Logical, FALSE by default. If TRUE, displays an additional ’mid-P’ p value (using the formula by <NAME> & Ruxton, 2020) for McNemar’s test (Fagerland et al., 2013). This provides better control for Type I error (less false positive findings) than the classical McNemar test, while it is also probably not much less robust (<NAME> & Ruxton, 2020). h_added Logical. If TRUE, Cohen’s h and its CI are calculated and displayed. (FALSE by default.) for_table Logical. If TRUE, omits the confidence level display from the printed text. hush Logical. If TRUE, prevents printing any details to console. Details The proportion for the two groups can be given using any of the following combinations (a) two vectors (var1 and var2), (b) cases and controls, (c) cases and sample sizes, or (d) proportions and sample sizes. Whenever multiple combinations are specified, only the first parameters (as given in the function and in the previous sentence) will be taken into account. The Bayes factor (BF), in case of unpaired samples, is always calculated with the default r-scale of 0.707. BF supporting null hypothesis is denoted as BF01, while that supporting alternative hypothesis is denoted as BF10. When the BF is smaller than 1 (i.e., supports null hypothesis), the reciprocal is calculated (hence, BF10 = BF, but BF01 = 1/BF). When the BF is greater than or equal to 10000, scientific (exponential) form is reported for readability. (The original full BF number is available in the returned named vector as bf.) Value Prints exact test statistics (including proportion difference with CI, and BF) in APA style. Fur- thermore, when assigned, returns a named vector with the following elements: z (Z), p (p value), prop_diff (raw proportion difference), h (Cohen’s h), bf (Bayes factor). Note Barnard’s unconditional exact test is calculated via Exact::exact.test ("z-pooled"). The CI for the proportion difference in case of the exact test is calculated based on the p value, as described by Altman and Bland (2011). In case of extremely large or extremely small p values, this can be biased and misleading. The Bayes factor is calculated via BayesFactor::contingencyTableBF, with sampleType = "indepMulti", as appropriate when both sample sizes (n1 and n2) are known in advance (as it normally happens). (For details, see contingencyTableBF, or e.g. ’Chapter 17 Bayesian statistics’ in Navarro, 2019.) References <NAME>., & <NAME>. (2011). How to obtain the confidence interval from a P value. Bmj, 343(d2090). doi:10.1136/bmj.d2090 <NAME>. (1947). Significance tests for 2x2 tables. Biometrika, 34(1/2), 123-138. doi:10.1093/ biomet/34.12.123 <NAME>., <NAME>., & <NAME>. (2013). The McNemar test for binary matched-pairs data: Mid-p and asymptotic are better than exact conditional. BMC Medical Research Methodol- ogy, 13(1), 91. doi:10.1186/147122881391 <NAME>., <NAME>., & <NAME>. (2009). Recommended tests for association in 2x2 tables. Statistics in medicine, 28(7), 1159-1175. doi:10.1002/sim.3531 <NAME>. (2019). Learning statistics with R. https://learningstatisticswithr.com/ <NAME>., & <NAME>. (2020). Effective use of the McNemar test. Behavioral Ecology and Sociobiology, 74(11), 133. doi:10.1007/s0026502002916y <NAME>., & <NAME>. (1985). Exact unconditional sample sizes for the 2 times 2 binomial trial. Journal of the Royal Statistical Society: Series A (General), 148(4), 317-327. doi:10.2307/2981892 Examples # example data set.seed(1) outcomes_A = sample(c(rep('x', 490), rep('y', 10))) outcomes_B = sample(c(rep('x', 400), rep('y', 100))) # paired proportion test (McNemar) props_neat(var1 = outcomes_A, var2 = outcomes_B, pair = TRUE) # unpaired chi test for the same data (two independent samples assumed) # Yates correction applied # cf. http://www.sthda.com/english/wiki/two-proportions-z-test-in-r props_neat( var1 = outcomes_A, var2 = outcomes_B, pair = FALSE, yates = TRUE ) # above data given differently for unpaired test # (no Yates corrrection) props_neat( case1 = 490, case2 = 400, control1 = 10, control2 = 100 ) # again differently props_neat( case1 = 490, case2 = 400, n1 = 500, n2 = 500 ) # other example data outcomes_A2 = c(rep(1, 707), rep(0, 212), rep(1, 256), rep(0, 144)) outcomes_B2 = c(rep(1, 707), rep(0, 212), rep(0, 256), rep(1, 144)) # paired test # cf. https://www.medcalc.org/manual/mcnemartest2.php props_neat(var1 = outcomes_A2, var2 = outcomes_B2, pair = TRUE) # show reverse proportions (otherwise the same) props_neat( var1 = outcomes_A2, var2 = outcomes_B2, pair = TRUE, inverse = TRUE ) # two different sample sizes out_chi = props_neat( case1 = 40, case2 = 70, n1 = 150, n2 = 170 ) # exact test out_exact = props_neat( case1 = 40, case2 = 70, n1 = 150, n2 = 170, exact = TRUE ) # the two p values are just tiny bit different print(out_chi) # p 0.00638942 print(out_exact) # p 0.006481884 # one-sided test props_neat( case1 = 40, case2 = 70, n1 = 150, n2 = 170, greater = '2' ) rbind_loop Merge by Columns in Loops Description Merges rows by columns in a loop using the enum function. On first iteration, indicated by enum, initiates a new data.table with the data to merge as first row. On all following iterations, adds data to merge as subsequent rows (using data.table::rbindlist). Usage rbind_loop(merged, ..., hush = FALSE) Arguments merged The name of the data.table for the merged data (without quotes). ... Any number of data to be merged. Each argument must be one of the following: a data.frame (or data.table) with either single row or two column; a named vector or a named list (with single elements); or a single value with parameter name (e.g. date = 1989 or id = "jdoe"). Data with two columns will be trans- posed using first column as column names and second column as corresponding values. See Details, Examples. hush Logical. If TRUE (default), prints message when the data frame for merging is initiated. Details In each call, all data passed to the function (via ...) will be merged into a single row, and that single row will be added to the "merged" data table. See an extensive example via https://github.com/gasparl/neatstats. See Also enum Examples my_vector = c('aa', 'bb', 'cxyz', 'last') for (elem in enum(my_vector)) { cat(elem, fill = TRUE) rbind_loop( merged_data, # data frame name for merging item = elem[2], number = elem[1], whatever = paste0('number (', elem[1], ')') ) } # merged_data now contains all merged rows print(merged_data) # item number whatever # 1 aa 1 number (1) # 2 bb 2 number (2) # 3 cxyz 3 number (3) # 4 last 4 number (4) # example with other data types for (elem in enum(my_vector)) { cat(elem, fill = TRUE) dframe1 = data.frame(item = elem[2], number = elem[1]) print(elem[1]) asnum = as.numeric(elem[1]) dframe2 = data.frame( my_cols = c('index', 'squared', 'multiple'), my_vals = c(elem[1], asnum ** 2, asnum * 10) ) my_list = list(ls_item = elem[2], ls_num = elem[1]) my_vec = c(v_item = elem[2], v_num = elem[1]) rbind_loop( merged_data, dframe1, # data frame with single row dframe2, # data frame with two columns my_list, # named list my_vec, # named vector single_val = elem[2], # single element constant = "whatever" # other single element ) } # again merged_data contains all merged rows # (previous content, if any, were removed) print(merged_data) # example with differring columns for (elem in enum(my_vector)) { cat(elem, fill = TRUE) dframe = data.frame(item = elem[2], number = elem[1]) asnum = as.numeric(elem[1]) if (asnum %% 2 == 0) { dframe$sqr = asnum ** 2 } rbind_loop(merged_data, dframe) } # merged_data contains all new merged rows # with NAs where sqr was not added print(merged_data) # example with data.table added library('data.table') for (elem in enum(my_vector)) { cat(elem, fill = TRUE) dframe = data.frame(item = elem[2], number = elem[1]) asnum = as.numeric(elem[1]) dtable = data.table(item2 = paste('DT', elem[2]), number2 = asnum + 9) if (asnum %% 2 == 0) { dframe$sqr = asnum ** 2 } rbind_loop(merged_data, dframe, dtable) } print(merged_data) # an extensive example to show how to collect and aggregate raw data is # available via the README file at the repository: # https://github.com/gasparl/neatstats read_dir Read and Merge Files from Directory Description Reads data files from any given directory as data frames and merges them into a single data frame (using data.table::rbindlist). Usage read_dir( pattern = "*[.]", path = ".", reader_function = data.table::fread, ..., subdirs = FALSE, filt = NULL, hush = FALSE ) Arguments pattern Regular expression ("regex"; as string or NULL) for selecting files (passed to the list.files function). The default NULL means that all files at the specified path will be read in. To select, for example, a specific extension like ".txt", the pattern can be given as "\.txt$" (for CSV files, "\.csv$", etc.). Files ending with e.g. "group2.txt" can be specified as "group2\.txt$". Files starting with "exp3" can be specified as "^exp3". Files starting with "exp3" AND ending with ".txt" extension can be specified as "^exp3.*\.txt$". To read in a single file, specify the full filename (e.g. "exp3_subject46_group2.txt"). (See ?regex for more details.) path Path to the directory from which the files should be selected and read. The de- fault "." means the current working directory (as returned by getwd()). Either specify correct working directory in advance (see setwd, path_neat), or oth- erwise enter relative or full paths (e.g. "C:/research" or "/home/projects", etc.). reader_function A function to be used for reading the files, data.table::fread by default. ... Any arguments to be passed on to the chosen reader_function. subdirs Logical (FALSE by default). If TRUE, searches files in subdirectories as well (relative to the given path). filt An expression to filter, by column values, each data file after it is read and before it is merged with the other data. (The expression should use column names alone; see Examples.) hush Logical. If FALSE (default), prints lists all data file names as they are being read (along with related warnings). Note This function is very similar to the readbulk::read_bulk function. One important difference however is the data.table use, which greatly speeds up the process. Another important difference is the possibility of file selection based on any regex pattern. Furthermore, this function allows pre-filtering by file (see filt). Data files could include significant amount of unnecessary data, and filtering prevents these to be merged. See Also data.table::rbindlist Examples # first, set current working directory # e.g. to script's path with setwd(path_neat()) # read all text files in currect working directory merged_df = read_dir("\\.txt$") # merged_df now has all data # to use utils::read.table for reading (slower than fread) # (with some advisable options passed to it) merged_df = read_dir( '\\.txt$', reader_function = read.table, header = TRUE, fill = TRUE, quote = "\"", stringsAsFactors = FALSE ) ro Neat rounding Description Rounds a given number to given number of digits after the decimal point, returning it as string, with trailing zeros when applicable. Usage ro(num, round_to = 2, leading_zero = TRUE, signi = FALSE) Arguments num Number to be rounded. round_to Number of fractional digits (i.e., digits after the decimal point), to round to. leading_zero Logical, TRUE by default. If FALSE, omits leading zero (e.g. returns ".17" instead of "0.17"). signi Logical, FALSE by default. If TRUE, rounds to a fractional digit that allows at least the first N non-zero digits displayed in all numbers, where N is specified by the round_to parameter. (See base:formatC) Value Number as string: num rounded to round_to digits, with trailing zeros when applicable. Examples ro( 1.2345 ) # returns "1.23" ro( 0.12345, 1 ) # returns "0.1" ro( 12.3, 4 ) # returns "12.3000" # examples with vectors to_round = c(1000, 100, 0.1, 0.01, 0.001, 0.0001) ro(to_round) ro(to_round, 3) ro(to_round, 3, leading_zero = FALSE) ro(to_round, 3, signi = TRUE) to_round2 = c(1230.000, 100, 0.012, 0.01, 0.123, 0.012340) ro(to_round2, 3) ro(to_round2, 3, signi = TRUE) ro(to_round2, 2, signi = TRUE) ro(to_round2, 1, signi = TRUE) ro(to_round2, 9, signi = TRUE) roc_neat Difference of Two Areas Under the Curves Description Comparison of two areas under the receiver operating characteristic curves (AUCs) and plotting any number of ROC curves. Usage roc_neat( roc1, roc2 = NULL, pair = FALSE, greater = NULL, ci = NULL, hush = FALSE, plot_rocs = FALSE, roc_labels = "", cutoff_auto = TRUE, cutoff_custom = NULL ) Arguments roc1 Receiver operating characteristic (ROC) object, or, for plotting only, a list including any number of such ROC objects. roc2 Receiver operating characteristic (ROC) object, or, for plotting only, leave it as NULL (default) and provide list for the first parameter (roc1). pair Logical. If TRUE, the test is conducted for paired samples. Otherwise (default) for independent samples. greater NULL or string (or number); optionally specifies one-sided test: either "1" (roc1 AUC expected to be greater than roc2 AUC) or "2" (roc2 AUC expected to be greater than roc2 AUC). If NULL (default), the test is two-sided. ci Numeric; confidence level for the returned CIs (raw difference). hush Logical. If TRUE, prevents printing any details to console (and plotting). plot_rocs Logical. If TRUE, plots and returns ROC curves. roc_labels Optional character vector to provide legend label texts (in the order of the pro- vided ROC objects) for the ROC plot. cutoff_auto Logical. If TRUE (default), optimal cutoffs on the ROC plots are displayed. cutoff_custom Custom cutoff to be indicated on the plot can be given here in a list. The list index must exactly correspond to the index of the list index of the AUC (given in roc1) for which the given cutoff is intended. Value Prints DeLong’s test results for the comparison of the two given AUCs in APA style, as well as corresponding CI for the AUC difference. Furthermore, when assigned, returns a list with stat (D value), p (p value), and, when plot is added, ROC plot. Note The main test statistics are calculated via pROC::roc.test as DeLong’s test (for both paired and unpaired). The roc_neat function merely prints it in APA style. The CI is calculated based on the p value, as described by Altman and Bland (2011). The ROC object may be calculated via t_neat, or directly with pROC::roc. References <NAME>., & <NAME>. (2011). How to obtain the confidence interval from a P value. Bmj, 343(d2090). doi:10.1136/bmj.d2090 DeLong, <NAME>., <NAME>., & <NAME>. (1988). Comparing the areas under two or more correlated receiver operating characteristic curves: a nonparametric approach. Biometrics, 44(3), 837-845. doi:10.2307/2531595 <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2011). pROC: an open-source package for R and S+ to analyze and compare ROC curves. BMC bioinfor- matics, 12(1), 77. doi:10.1186/147121051277 See Also t_neat Examples # calculate first AUC (from v1 and v2) v1 = c(191, 115, 129, 43, 523,-4, 34, 28, 33,-1, 54) v2 = c(4,-2, 23, 13, 32, 16, 3, 29, 37,-4, 65) results1 = t_neat(v1, v2, auc_added = TRUE) # calculate second AUC (from v3 and v4) v3 = c(14.1, 58.5, 25.5, 42.2, 13, 4.4, 55.5, 28.5, 25.6, 37.1) v4 = c(36.2, 45.2, 41, 24.6, 30.5, 28.2, 40.9, 45.1, 31, 16.9) results2 = t_neat(v3, v4, auc_added = TRUE) # one-sided comparison of the two AUCs roc_neat(results1$roc_obj, results2$roc_obj, greater = "1") # create a list of randomlz generated AUCs set.seed(1) aucs_list = list() for (i in 1:4) { aucs_list[[i]] = t_neat(rnorm(50, (i-1)), rnorm(50), auc_added = TRUE, hush = TRUE)$roc_obj } # depict AUCs (recognized as list) roc_neat(aucs_list) # with custom cutoffs depicted roc_neat(aucs_list, cutoff_custom = list(0.2), cutoff_auto = FALSE) roc_neat(aucs_list, cutoff_custom = list(.1, c(-.5, 0), NULL, c(.7, 1.6)), cutoff_auto = FALSE) roc_neat(aucs_list, cutoff_custom = list(.6, NULL, NULL, 1.1)) sd_ci Confidence Interval of Standard Deviation Description Calculates the SD confidence interval of a vector of numbers. Usage sd_ci(x, ci = 0.95) Arguments x Numeric vector. ci Numeric; confidence level for returned CI. Value SD confidence interval (as named vector). See Also mean_ci, plot_neat Examples myvec = c(11, 15, 19, 43, 53, -4, 34, 8, 33, -1, 54 ) sd_ci( myvec ) sd_ci( myvec, ci = .80 ) se Standard Error of Mean Description Simply calculates the standard error of a vector of numbers. Usage se(x) Arguments x Numeric vector. Value Standard error. See Also mean_ci, plot_neat Examples se( c(11, 15, 19, 43, 53, -4, 34, 8, 33, -1, 54 ) ) table_neat Table, descriptives Description Creates a neat means (or similar descriptives) and standard deviations table, using aggr_neat func- tions as arguments. Alternatively, merges and transposes data frames into rows. Usage table_neat( values_list, group_by = NULL, group_per = "rows", to_clipboard = FALSE, method = "mean+sd", transpose = FALSE ) Arguments values_list Data frames as returned from the aggr_neat function: variables from which the statistics for the table are to be calculated. The group_by, method, and prefix parameters are ignored when they are given in the table_neat function; see Details and also an extensive example via https://github.com/gasparl/neatstats. group_by String, or vector of strings: the name(s) of the column(s) in the dat given data frame, containing the vector(s) of factors by which the statistics are grouped. (Overwrites group_by in aggr_neat; see Details.) group_per String, "rows" or "columns". If set to "columns" (or just "c" or "col", etc.), each column contains statistics for one group. Otherwise (default), each row contains statistics for one group. to_clipboard Logical. If TRUE, the table is copied to the clipboard (default: FALSE). method Function or string; overwrites the method argument in aggr_neat when used within this function. See method in the aggr_neat function for details. Default value: "mean+sd" (to calculate means and standard deviations table). transpose Logical (default: FALSE) or string. If TRUE or string, ignores all other parameters (except values_list), but merges all values from given list of data frames (as returned from the aggr_neat) and transposes them into a single row, using, by default, the "aggr_group" column values for new headers (corresponding to the output of aggr_neat; see Examples). However, a string given as argument for the transpose parameter can also specify a custom column name. Details The values, round_to, and new_name arguments given in the aggr_neat function are always ap- plied. However, the prefix parameter will be overwritten as NULL. If new_name in aggr_neat is NULL, the given input variable names will be used instead of "aggr_value". Furthermore, the group_by or method given in the aggr_neat function are only applied when no arguments are given in the table_neat function for the identical parameters (group_by or medians). If either parameter is given in the table_neat function, all separately given respective argument(s) in the aggr_neat function(s) are ignored. Value Returns a data frame with means or medians and SDs per variable and per group. See Also aggr_neat for more related details Examples data("mtcars") # load base R example dataset # overall means and SDs table for disp (Displacement) and hp (Gross horsepower) table_neat(list(aggr_neat(mtcars, disp), aggr_neat(mtcars, hp))) # means and SDs table for mpg (Miles/(US) gallon), wt (Weight), and hp (Gross horsepower) # grouped by cyl (Number of cylinders) # each measure rounded to respective optimal number of digits # wt renamed to weight (for the column title) table_neat(list( aggr_neat(mtcars, mpg, round_to = 1), aggr_neat(mtcars, wt, new_name = 'weight', round_to = 2), aggr_neat(mtcars, hp, round_to = 0) ), group_by = 'cyl') # same as above, but with medians, and with groups per columns table_neat( list( aggr_neat(mtcars, mpg, round_to = 1), aggr_neat(mtcars, wt, new_name = 'weight', round_to = 2), aggr_neat(mtcars, hp, round_to = 0) ), group_by = 'cyl', method = 'median+sd', group_per = 'columns' ) # an extensive example to show how to collect and aggregate raw data is # available via the README file at the repository: # https://github.com/gasparl/neatstats t_neat Difference of Two Means and Area Under the Curve Description Welch’s t-test results including Cohen’s d with confidence interval (CI), Bayes factor (BF), and area under the receiver operating characteristic curve (AUC). For non-parametric version, Wilcoxon test results (Mann–Whitney U test, aka "Wilcoxon rank-sum test", for independent sam- ples; Wilcoxon signed-rank test for paired samples; including nonparametric "location difference estimate" (see stats::wilcox.test); along with corresponding rank-based BFs as per van Doorn et al., 2020). Usage t_neat( var1, var2, pair = FALSE, nonparametric = FALSE, greater = NULL, norm_tests = "latent", norm_plots = FALSE, ci = NULL, bf_added = FALSE, bf_rscale = sqrt(0.5), bf_sample = 1000, auc_added = FALSE, cutoff = NULL, r_added = TRUE, for_table = FALSE, test_title = NULL, round_descr = 2, round_auc = 3, auc_greater = "1", cv_rep = FALSE, cv_fold = 10, hush = FALSE, plots = FALSE, rug_size = 4, aspect_ratio = 1, y_label = "density estimate", x_label = "\nvalues", factor_name = NULL, var_names = c("1", "2"), reverse = FALSE ) Arguments var1 Numeric vector; numbers of the first variable. var2 Numeric vector; numbers of the second variable. pair Logical. If TRUE, all tests (t, BF, AUC) are conducted for paired samples. If FALSE (default) for independent samples. nonparametric Logical (FALSE by default). If TRUE, uses nonparametric (rank-based, "Wilcoxon") t-tests (including BFs; see Notes). greater NULL or string (or number); optionally specifies one-sided tests (t and BF): either "1" (var1 mean expected to be greater than var2 mean) or "2" (var2 mean expected to be greater than var1 mean). If NULL (default), the test is two-sided. norm_tests Normality tests. Any or all of the following character input is accepted (as a single string or a character vector; case-insensitive): "W" (Shapiro-Wilk), "K2" (D’Agostino), "A2" (Anderson-Darling), "JB" (Jarque-Bera); see Notes. Two other options are "all" (same as TRUE; to choose all four previous tests at the same time) or "latent" (default value; prints all tests only if nonparametric is set to FALSE and any of the four tests gives a p value below .05). Each normality test is performed for the difference values between the two variables in case of paired samples, or for each of the two variables for unpaired samples. Set to "none" to disable (i.e., not to perform any normality tests). norm_plots If TRUE, displays density, histogram, and Q-Q plots (and scatter plots for paired tests) for each of the two variable (and differences for pairwise observations, in case of paired samples). ci Numeric; confidence level for returned CIs for Cohen’s d and AUC. bf_added Logical. If TRUE (default), Bayes factor is calculated and displayed. bf_rscale The scale of the prior distribution (0.707 by default). bf_sample Number of samples used to estimate Bayes factor (1000 by default). More sam- ples (e.g. 10000) take longer time but give more stable BF. auc_added Logical (FALSE by default). If TRUE, AUC is calculated and displayed. Includes TPR and TNR, i.e., true positive and true negative rates, i.e. sensitivity and specificity, using an optimal value, i.e. threshold, that provides maximal TPR and TNR. These values may be cross-validated: see cv_rep. (Note that what is designated as "positive" or "negative" depends on the scenario: this function always assumes var1 as positive and var2 as negative. If your scenario or pref- erence differs, you can simply switch the names or values when reporting the results.) cutoff Numeric. Custom cutoff value for AUC TPR and TNR, also to be depicted in the plot. In case of multiple given, the first is used for calculations, but all will be depicted in the plot. r_added Logical. If TRUE (default), Pearson correlation is calculated and displayed in case of paired comparison. for_table Logical. If TRUE, omits the confidence level display from the printed text. test_title NULL or string. If not NULL, simply displayed in printing preceding the statistics. (Useful e.g. to distinguish several different comparisons inside a function or a for loop.) round_descr Number to round to the descriptive statistics (means and SDs). round_auc Number to round to the AUC and its CI. auc_greater String (or number); specifies which variable is expected to have greater values for ’cases’ as opposed to ’controls’: "1" (default; var1 expected to be greater for ’cases’ than var2 mean) or "2" (var2 expected to be greater for ’cases’ than var1). Not to be confused with one-sided tests; see Details. cv_rep FALSE (default), TRUE, or numeric. If TRUE or numeric, a cross-validation is performed for the calculation of TPRs and TNRs. Numeric value specifies the number of repetitions, while, if TRUE, it defaults to 100 repetitions. In each repetition, the data is divided into k random parts ("folds"; see cv_fold), and the optimal accuracy is obtained k times from a k-1 training set (var1 and var2 truncated to equal length, if needed, in each case within each repetition), and the TPR and TNR are calculated from the remaining test set (different each time). cv_fold Numeric. The number of folds into which the data is divided for cross-validation (default: 10). hush Logical. If TRUE, prevents printing any details to console. plots Logical (or NULL). If TRUE, creates a combined density plot (i.e., Gaussian kernel density estimates) from the two variables. Includes dashed vertical lines to indicate means of each of the two variables. If nonparametric is set to TRUE, medians are calculated for these dashed lines instead of means. When auc_added is TRUE (and the AUC is at least .5), the best threshold value for clas- sification (maximal differentiation accuracy using Youden’s index) is added to the plot as solid vertical line. (In case of multiple best thresholds with identical overall accuracy, all are added.) If NULL, same as if TRUE except that histogram is added to the background. rug_size Numeric (4 by default): size of the rug ticks below the density plot. Set to 0 (zero) to omit rug plotting. aspect_ratio Aspect ratio of the plots: 1 (1/1) by default. (Set to NULL for dynamic aspect ratio.) y_label String or NULL; the label for the y axis. (Default: "density estimate".) x_label String or NULL; the label for the x axis. (Default: "values".) factor_name String or NULL; factor legend title. (Default: NULL.) var_names A vector of two strings; the variable names to be displayed in the legend. (De- fault: c("1", "2").) reverse Logical. If TRUE, reverses the order of variable names displayed in the legend. Details The Bayes factor (BF) supporting null hypothesis is denoted as BF01, while that supporting alterna- tive hypothesis is denoted as BF10. When the BF is smaller than 1 (i.e., supports null hypothesis), the reciprocal is calculated (hence, BF10 = BF, but BF01 = 1/BF). When the BF is greater than or equal to 10000, scientific (exponential) form is reported for readability. (The original full BF number is available in the returned named vector as bf.) For simplicity, Cohen’s d is reported for nonparametric tests too: you may however want to consider reporting alternative effect sizes in this case. The original pROC::auc function, by default, always returns an AUC greater than (or equal to) .5, assuming that the prediction based on values in the expected direction work correctly at least at chance level. This however may be confusing. Consider an example where we measure the heights of persons in a specific small sample and expect that greater height predicts masculine gender. The results are, say, 169, 175, 167, 164 (cm) for one gender, and 176, 182, 179, 165 for the other. If the expectation is correct (the second, greater values are for males), the AUC is .812. However, if in this particular population females are actually taller than males, the AUC is in fact .188. To keep things clear, the t_neat function always makes an assumption about which variable is expected to be greater for correct classification ("1" by default; i.e., var1; to be specified as auc_greater = "2" for var2 to be expected as greater). For this example, if the first (smaller) variables are given as var1 for females, and second (larger), variables are given as var2 for males, we have to specify auc_greater = "2" to indicate the expectation of larger values for males. (Or, easier, just add the expected larger values as var1.) Value Prints t-test statistics (including Cohen’s d with CI, BF, and AUC, as specified via the corresponding parameters) in APA style. Furthermore, when assigned, returns a list, that contains a named vector ’stats’ with the following elements: t (t value), p (p value), d (Cohen’s d), bf (Bayes factor), auc (AUC), accuracy (overall accuracy using the optimal classification threshold), and youden (Youden’s index: specificity + sensitivity - 1). The latter three are NULL when auc_added is FALSE. When auc_added is TRUE, there are also two or three additional elements of the list. One is ’roc_obj’, which is a roc object, to be used e.g. with the roc_neat function. Another is ’best_thresholds’, which contains the best threshold value(s) for classification, along with corresponding specificity and sensitivity. The third ’cv_results’ contains the results, if any, of the cross-validation of TPRs and TNRs (means per repetition). Finally, if plots is TRUE (or NULL), the plot is displayed as well as returned as a ggplot object, named t_plot. Note The Welch’s t-test is calculated via stats::t.test. #’Normality tests are all calculated via fBasics::NormalityTests, selected based on the recom- mendation of Lakens (2015), quoting Yap and Sim (2011, p. 2153): "If the distribution is sym- metric with low kurtosis values (i.e. symmetric short-tailed distribution), then the D’Agostino and Shapiro-Wilkes tests have good power. For symmetric distribution with high sample kurtosis (sym- metric long-tailed), the researcher can use the JB, Shapiro-Wilkes, or Anderson-Darling test." See urlhttps://github.com/Lakens/perfect-t-test for more details. Cohen’s d and its confidence interval are calculated, using the t value, via MBESS::ci.smd for independent samples (as standardized mean difference) and via MBESS::ci.sm for paired samples (as standardized mean). The parametric Bayes factor is calculated via BayesFactor::ttestBF. The nonparametric (rank- based) Bayes factor is a contribution by <NAME>; the original source code is available via https://osf.io/gny35/. The correlation and its CI are calculated via stats::cor.test, and is always two-sided, always with 95 percent CI. For more, use corr_neat. The AUC and its CI are calculated via pROC::auc, and the accuracy at optimal threshold via pROC::coords (x = "best"); both using the object pROC::roc. References <NAME>., <NAME>., & <NAME>. (2017). Why psychologists should by default use Welch’s t-test instead of Student’s t-test. International Review of Social Psychology, 30(1). doi:10.5334/irsp.82 <NAME>. (2007). Methods for the behavioral, educational, and social sciences: An R package. Behavior Research Methods, 39(4), 979-984. doi:10.3758/BF03192993 <NAME>. (2015). The perfect t-test (version 1.0.0). Retrieved from https://github.com/Lakens/perfect- t-test. doi:10.5281/zenodo.17603 <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2011). pROC: an open-source package for R and S+ to analyze and compare ROC curves. BMC bioinfor- matics, 12(1), 77. doi:10.1186/147121051277 <NAME>., <NAME>., <NAME>., & <NAME>. (2020). Bayesian rank-based hypothesis testing for the rank sum test, the signed rank test, and Spearman’s rho. Journal of Applied Statistics, 1–23. doi:10.1080/02664763.2019.1709053 <NAME>., & <NAME>. (2011). Comparisons of various types of normality tests. Journal of Statistical Computation and Simulation, 81(12), 2141–2155. doi:10.1080/00949655.2010.520163 See Also corr_neat, roc_neat Examples # assign two variables (numeric vectors) v1 = c(191, 115, 129, 43, 523,-4, 34, 28, 33,-1, 54) v2 = c(4,-2, 23, 13, 32, 16, 3, 29, 37,-4, 65) t_neat(v1, v2) # prints results as independent samples t_neat(v1, v2, pair = TRUE) # as paired samples (r added by default) t_neat(v1, v2, pair = TRUE, greater = "1") # one-sided t_neat(v1, v2, pair = TRUE, auc_added = TRUE ) # AUC included # print results and assign returned list results = t_neat(v1, v2, pair = TRUE) results$stats['bf'] # get precise BF value var_tests Variance Equality Tests Description Displayed sample sizes and SDs and performs Brown-Forsythe and Fligner-Killeen variance equal- ity tests (tests of homogeneity of variances) per group combinations. This is primarily a subfunction of anova_neat, but here it is available separately for other potential purposes. Usage var_tests(xvar, group_by, dat = NULL, hush = FALSE, sep = ", ") Arguments xvar Either a numeric vector (numbers of any given variable), or, if dat is given, a column name specifying the variable in the given data frame. group_by Either a vector of factors with which to group the xvar values, or, if dat is given, one or more column names specifying the columns in the given data frame. dat Either NULL or a data frame from which the respective column names should be selected for xvar and group. hush Logical. If TRUE, prevents printing any details to console. sep String (underscore "_" by default) for separating group names. Value Prints test results. Note Brown-Forsythe test (i.e., Levene’s test using medians) is calculated via car::leveneTest. Fligner- Killeen test, which may be more robust (i.e., less affected by non-normal distribution), is calculated via stats::fligner.test. (See also Conover et al., 1981, p. 360.) References Brown, <NAME>. & <NAME>. (1974). Robust tests for the equality of variances. Journal of the American Statistical Association, 69, pp. 364-367. <NAME>., <NAME>., & <NAME>. (1981). A comparative study of tests for homo- geneity of variances, with applications to the outer continental shelf bidding data. Technometrics, 23, 351–361. <NAME>. & <NAME>. (1976). Distribution-free two-sample tests for scale. ‘Journal of the American Statistical Association. 71(353), 210-213. <NAME>. & <NAME>. (2019) An R Companion to Applied Regression, Third Edition, Sage. Levene, H. (1960). Robust tests for equality of variances. In <NAME>, <NAME>, et al. (eds.). Contributions to Probability and Statistics: Essays in Honor of Harold Hotelling. Stanford Univer- sity Press. pp. 278–292. See Also anova_neat Examples data("ToothGrowth") # load base R example dataset # the statistics of the four functions below should match var_tests(ToothGrowth$len, ToothGrowth$supp) var_tests('len', 'supp', ToothGrowth) car::leveneTest(len ~ supp, data = ToothGrowth) stats::fligner.test(len ~ supp, ToothGrowth) # again the results below should match each other var_tests(ToothGrowth$len, interaction(ToothGrowth$supp, ToothGrowth$dose)) var_tests('len', c('supp', 'dose'), ToothGrowth) car::leveneTest(len ~ supp * as.factor(dose), data = ToothGrowth) stats::fligner.test(len ~ interaction(supp, dose), ToothGrowth)
homebrew_astrometry_net.jsonl
personal_doc
Unknown
If you have astronomical imaging of the sky with celestial coordinates you do not know—or do not trust—then Astrometry.net is for you. Input an image and we'll give you back astrometric calibration meta-data, plus lists of known objects falling inside the field of view. We have built this astrometric calibration service to create correct, standards-compliant astrometric meta-data for every useful astronomical image ever taken, past and future, in any state of archival disarray. We hope this will help organize, annotate and make searchable all the world's astronomical information. For more specifics about the current state of the project, see the presentation by Roweis to Google Pittsburgh, available here (ppt) or here (pdf). We are building an “astrometry engine” to create correct, standards-compliant astrometric meta data for every useful astronomical image ever taken, past and future, in any state of archival disarray. The astrometry engine will take any image and return the astrometry world coordinate system (WCS)—ie, a standards-based description of the (usually nonlinear) transformation between image coordinates and sky coordinates—with absolutely no “false positives” (but maybe some “no answers”). It will do its best, even when the input image has no—or totally incorrect—meta-data. We intend to install the engine for real-time operation on the web, at observatories, at plate-scanning projects, and at data archives. The removal of astrometry as a barrier to using legacy and badly archived (or not archived) data will greatly extend astronomical time baselines into the past, and greatly increase time sampling for sources all over the sky. It facilitates work with distributed, heterogeneous data sets. It also provides a channel for professional and amateur astronomers to collaborate, as the installation of correct WCS makes currently hard-to-access amateur imaging data interoperable with professional projects. We have elucidated and solved a fundamental computer science problem in the field of geometric hashing: the fast and efficient search for matches to patches of a two-dimensional set of points, when the patch to be matched has unknown location, scale, orientation, and completeness or contamination, as well as realistic errors. Efficient and robust algorithms for this matching problem will be the basis for attacking many highly non-trivial problems in pattern matching, data analysis, and computer vision. If there are a few thousand US ground-based observing programs anually with a person-week or so spent on astrometry, an astrometry engine would effectively pay the entire astrophysics community a few million US dollars per year in perpetuity. The engine will be made freely mirror-able anywhere by anyone, and we will provide support for mirroring. We will also provide our algorithms and code to the public. By setting the engine loose on historical, scanned, and amateur data, we will enlarge, test, and improve astronomy's burgeoning public data archives, for science and education. Albanian translation provided by Ermira Beqiri, hosted by NPIFinder.com. Belorussian translation provided by <NAME>, hosted by fatcow. Romanian translation provided by Irina Vasilescu. Russian translation provided by <NAME>, hosted by Everycloudtech. Date: 2011-01-01 Categories: Tags: ## Principal investigators ## Core team members * <NAME> (GSOC 2011; Caltech) * <NAME> (GSOC 2011; Maryland) * <NAME> (deceased) * <NAME> (Etsy) ## Contributors, past collaborators, and friends * <NAME> (Berkeley) * <NAME> (NYU) * <NAME> (NYU) * <NAME> (Harvard) * <NAME> (Bunker Ranch Observatory) * <NAME> (formerly at Toronto) * <NAME> (UC Santa Barbara) * <NAME> (formerly at NYU) * <NAME> (Google) * <NAME> (UCSD) * <NAME> (Google, UC Davis) * <NAME> (formerly at Toronto) * <NAME> (Pittsburgh) Date: 2007-01-01 Categories: Tags: In the images below, the red circles are stars our algorithm automatically detects in the image, and the green circles are stars from our master index which appear in the query image. Nebulae, constellations and other objects can be automatically overlayed on the image after it has been solved. A shot of the Great Nebula, by <NAME> (c.2006), from astropix.com A scanned plate from Harvard CFA's historical archive. An amateur shot of M100, by <NAME> (c.2007) from flickr.com A beautiful image of Bode's nebula (c.2007) by <NAME>, from starlightfriend.de ## News * 2011 Aug 17: We are beta on the web! * As we hoped, our awesome GSOC interns Chen and Lalimarmo fixed up our web presence, added openID authentication, and created a data-sharing and idea-sharing system for our users. We are now running open on the web; if you want to check it out, see our use-the-code page. * 2011 Jun 06: The start of our Summer of Code. * Google Summer of Code interns <NAME> and <NAME> started work on Astrometry.net's web services today, with a meet-up in New York City. Chen and Lalimarmo made a pretty hard cut—we had many GSOC applications from around the world—so they are very capable open-source developers. The goal is to move from alpha to beta and have a proper API, along with much more (and much more fun) functionality for our users. Go team! * 2011 Apr 01: Comet 17P/Holmes. * We released a somewhat light-hearted paper and got some good press, notably Wired and New Scientist. * 2011 Mar 24: We're doing Google Summer of Code. * Interested in applying? Contact gsoc at astrometry.net for details. * 2010 Sep 02: Feige 85 re-found. * Rare white dwarf Feige 85 was published in 1958 with an approximate and slightly worng position, causing it to be > lost to white dwarf researchers forever. Today <NAME> (McMaster) and friends put a grabbed image of a finding chart into Astrometry.net and re-found it! It turns out the star is (boringly named and unrecognized) 2MASS J13362125+0822335. See Slacker Astronomy for more details. Later they also recovered lost M7 star HaroChavira 62 by the same method. * 2010 Jan 12: <NAME>, 1972–2010. * <NAME> (NYU, Google, Toronto), the co-PI of Astrometry.net, died today. He had an immense impact on machine learning and computational statistics, but also on astronomy, where his contributions—including Astrometry.net—were truly disruptive. He was a great scholar and a great friend. * 2009 Oct 14: Astrometry.net paper finished. * The long-awaited paper on Astrometry.net finally appears on astro-ph as arXiv:0910.2233. We are also submitting it to AJ. Please cite this paper (or the AJ version, when it appears) in any work that uses Astrometry.net. Thanks! * 2009 Sep 11: Lang successfully defends his PhD. * <NAME>'s thesis is on Astrometry.net. At the defense are <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and exam chair and, coincidentally, UofT astronomer <NAME>. A good time, and a bit of champagne, was had by all. * 2009 June 26: DeepSky processes 14 million images; PTF adopts Astrometry.net. * <NAME> of the DeepSky team wrote us email summarizing his results with an enormous data set: > For DeepSky we have successfully processed 14M images, and we just finished up with all of this the past week! This was ∼70TB of data we went through in the past year. The images were 2048X600 pixels with 0.858 arcsec/pix... This is 5 years of all-sky data (∼20,000 sq deg/yr) hit quite a few times. In the same email he went on to say that the Palomar Transient Factory has adopted Astrometry.net in its pipeline processing. * 2009 February 18: Interview with Flickr developer blog * In a blog post on the Flickr developer blog Christopher was interviewed about topics ranging from how amateur astronomers are contributing to science, the workings of Astrometry.net, and the experience of hooking it all up to Flickr. This led also to our first appearance on Slashdot. * 2008 November 6: Astrometry.net Flickr group makes front page of reddit * In addition to being featured in reddit, we were also covered in kottke, and O'Reilly's Make magazine blog. * 2008 October 21: Hogg and Dustin propose > theory of everything * Automated calibration (that is, what the Astrometry.net service does) is the first step towards automated joint scientific analysis of heterogeneous imaging: automated science, as it were. We wrote this up for a European workshop on data analysis. Check it out at our bibliography. * 2008 July 6: Flickr group adds annotations * Images solved in the flickr group are now annotated. Major objects are being labeled on new images being submitted to the group. An example on a picture of M42. * 2008 May 7: Blind Date paper finished. * The paper documenting our new system for determining the date-of-origin of historical imagery using only pixel data and the known proper motions of catalog stars has been finished. Check it out on the arXiv or at our bibliography. * 2008 April 4: We added meta-data to a video. * The FIREBall balloon-borne UV telescope put a video from its guider camera on YouTube. We ripped the video to images, annotated the images with meta-data, and re-built the video. Watch it here. * 2008 March 20: Clean USNO-B data released. * The data generated by our "Clean USNO-B" project has been released. Find it here. * 2007 September 12: Version 0.1 of the code is released. * All the code used in the alpha-test web service, all the code used to solve the > Astronomy Pictures of the Day , and all the code used to solve and recover SDSS and GALEX data has been released to code requestors. If you would like to obtain the code for yourself—or become an alpha-tester—please hit the > use menu link. * 2007 September 10: We recovered > lost SDSS data on Messier 71. * Substantial telescope data acquisition system glitches caused the Sloan Digital Sky Survey automatic astrometric calibration pipelines to fail on the imaging run covering Milky Way globular cluster Messier 71 (among many other things). Astrometry.net astrometrically calibrated one field from the SDSS run blind (that is, with no prior information about pointing), and the SDSS pipelines were then able to bootstrap solutions for the entire run off of that one Astrometry.net solution. * 2007 July 29: Astrometry.net Flickr group created. * An astrometry group was created on Flickr. Images submitted to the group are solved in a fully automated fashion using the astrometry.net blind solver and the Flickr API. Any Flickr user can submit to the group. * 2007 April 16: We are live! Alpha testing has started. * We have started alpha testing with a limited number of development collaborators who will help us work out the kinks and improve the system. We are reliably solving images from about 10 arcmin up to 100 degree scales including over a hundred examples from the Astronomy Picture of the Day. (We are still not producing high precision WCS and are still solving all images "blind", but both of those will change soon.) Our next milestone will be to put out a code release which will allow users to compile (and modify) the entire system on their local hardware. * 2007 February 14: We solved today's > Astronomy Picture of the Day blind. * In preparation for going alpha, we have been running random images through the system. We added jpeg capabilities so we can deal with web images as well as professional images. To test the system, we ran the Astronomy Picture of the Day for Valentine's Day, which was, of course, of the rosette nebula. We solved it—that is, automatically determined its location on the sky and orientation—right out of the box. * 2007 January 18: We solved 7077 GALEX/NUV fields blind. * We ran 7077 fields from the GALEX All-Sky Imaging Survey, near-ultraviolet (NUV) channel, through a cascade of blind solving attempts and got all but 8 of them, with no false positives, for a success rate of nearly 99.9 percent. We built our indexes with a blue-biased subsample of the USNO-B1.0 catalog. The GALEX far-ultraviolet (FUV) channel is much more challenging because only a small fraction of FUV sources can be associated with sources in the USNO-B1.0 catalog. * 2006 December 4: We solved 35,000 SDSS u-band and z-band fields blind. * The blind solver—which finds WCS for images with no meta-data—is optimized for r-band images. However, we discovered today that it works pretty well in other bands. Without any changes to account for band differences, our system, which now gets 99.6 percent of SDSS r-band fields right (with no false positives), gets 96.9 percent of u-band fields (with no false positives), and 99.3 percent of z-band fields (with no false positives). This gives us some confidence that a multi-wavelength system will be possible, though with the exception of some GALEX testing, we have not yet ventured outside the optical. * 2006 September 28: Roweis presented the current status of the project at Google Pittsburgh. * Roweis's presentation focused on the computer-science and machine-learning aspects of the project. You can read the presentation materials here (ppt) or here (pdf). * 2006 July 2: We solved 336,554 SDSS r-band fields blind. * Today we ran a set of 336,554 SDSS fields through the blind solver, and have a total success rate higher than 99 percent. We don't know the exact success rate yet, because many of the 1,976 failures are fields that are out-of-focus, inside small holes in the USNO-B1.0 catalog, or subject to other problems for which we are not responsible. (Yes, we are solving a subset of all of the fields, not just the science-grade fields!) The entire set of fields solves overnight on a University of Toronto computer cluster. * 2005 October 26: We solved our first GALEX/NUV field blind. * Today we re-solved the astrometry (ie, we determined the pointing, rotation, and scale) for a single GALEX near-UV image from the All-sky Imaging Survey using the x,y positions of sources from the GALEX pipeline and the USNO-B1.0 catalog and nothing else. The source positions were given to us by <NAME> (Columbia) who withheld all information about the image pointing, rotation, and scale. The only thing we assumed is that the image is larger than about 30 arcmin in diameter. * 2005 September 5: We achieved robust WCS optimization (prototype). * We have created a system (not yet even ready for beta release) that takes an x,y list of compact sources in an image and an approximate WCS and produces as precise WCS as is possible given the USNO-B1.0 catalog. The WCS is fit including > Spitzer Imaging Polynomial distortions to the user-chosen SIP polynomial order. This code works on SDSS images (fields), typical HST/ACS images, and (we have learned since) GALEX images. * 2005 July 28: We solved our first SDSS r-band field blind. * Today we re-solved the astrometry (ie, we determined the pointing, rotation, and scale) for our first SDSS r-band image (field) using the x,y positions of stars from the SDSS pipeline and the USNO-B1.0 catalog and nothing else. We took the stellar positions from the SDSS pre-calibration pipeline, so we had no access to the RA, Dec positions nor even the calibrated magnitudes of the stars we used. The only things we assumed were (a) that the field is in the North Galactic Cap (one-quarter of the sky) and (b) that the image is of order 10 arcmin in diameter. ### Astronomical data ### Software Date: 2002-01-01 Categories: Tags: b"Bibliography\n Published work by our group\n In reverse chronological order:\n \n <NAME>. & <NAME>., 2011, Searching for comets on the World Wide Web: The orbit of 17P/Holmes from the behavior of photographers The Astronomical Journal 144, 46. BibtexWe (re-)discover a comet by doing an image search on the Web.\n <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>., 2010, Astrometry.net: Blind astrometric calibration of arbitrary astronomical images, The Astronomical Journal 139, 1782&#8211;1800. Bibtex Bibtex@ADSWe say what we've been doing all these years.\n <NAME>., <NAME>., <NAME>., & <NAME>., 2009, Measuring the undetectable: Proper motions and parallaxes of very faint sources, The Astronomical Journal, 137 4400&#8211;4411.By simultaneous modeling of the individual-epoch images in a multi-epoch (time series) imaging data set, we show that we can measure proper motions of stars well below the magnitude level (brightness) at which they can be detected in each individual image. By this method we discover a set of new, very cool brown dwarfs (objects too low in mass to start hydrogen burning and become stars).\n <NAME>. & <NAME>., 2008, Astronomical imaging: The theory of everything, Classification and Discovery in Large Astronomical Surveys, <NAME> (ed.), AIP Conference Proceedings 1082, 331&#8211;338.We present an argument that astronomical catalogs should be explicitly created as image models, and that the best-fit or highest likelihood model of the data is also the best possible astronomical catalog. A model of this form is a platform for automated discovery, because it is capable of identifying informative failures of the model in new data at the pixel level, or as statistical anomalies in the joint distribution of residuals from many images.\n <NAME>., <NAME>., <NAME>., & <NAME>., 2008, Blind Date: Using proper motions to determine the ages of historical images, The Astronomical Journal, 136 1490&#8211;1501.Using only raw pixel data and known catalog proper motions, it is possible to accurately estimate the date of origin of historical imagery. This allows us to retrieve lost meta-data, improve astrometric calibration, and re-estimate proper motions.\n <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>., 2008, Automated Astrometry, Astronomical Data Analysis Software and Systems XVII, <NAME>, <NAME>, and <NAME>, eds., ASP Conference Series 394, 27&#8211;34.A summary of the project as of 2007 September, aimed at astronomers with an interest in software.\n <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>., 2008, Cleaning the USNO-B Catalog through automatic detection of optical artifacts, The Astronomical Journal 135 414&#8211;422.The USNO-B Catalog of astrometric standards contains about 2 percent spurious entries that are caused by diffraction spikes and circular reflection halos around bright stars in the original imaging data. We use computer vision techniques to identify and remove them. Our code and data are available here.\n <NAME>., 2004, New algorithms for automated astrometry [PDF], MSc Thesis, University of Toronto.Harvey shows that solution to the blind astrometry problem (ie, no first guess at image pointing, rotation, or scale) is possible for at least some kinds of data. Two methods are implemented.\n \n Published work by other groups\n In alphabetical order:\n \n <NAME>., 1986, A pattern-matching algorithm for two-dimensional coordinate lists, The Astronomical Journal 91 1244&#8211;1248.This is the first published algorithm for matching image stars to catalog stars that does not depend on image scale. The method makes use of triangles, with many triangles contributing to each solution. The scaling (with the number of stars n) is bad, but the project is similar in spirit to ours.\n <NAME>., 1993, Pattern recognition of star constellations for spacecraft applications, IEEE Aerospace and Electronic Systems Magazine 8 (no 1) 33&#8211;39.Liebe shows that the blind astrometry problem is easily solved when (a) you have a camera with a large field of view (tens of deg), (b) you know exactly the image scale (ie, your images are calibrated in deg), and (c) you are working with the brightest 1000 or so stars on the sky. The method involves matching triangles of stars.\n P&#225;<NAME>. & <NAME>., 2006 Astrometry in wide-field surveys, The Publications of the Astronomical Society of the Pacific 118 1474&#8211;1483.This is similar in spirit to Groth (1986), but includes a very impressive (and successful) test on real-world data.\n <NAME>., <NAME>., <NAME>., & <NAME>., 2004, Cleaning sky survey data bases using Hough transform and renewal string approaches, Monthly Notices of the Royal Astronomical Society 347 36&#8211;51They present clever techniques for the automatic detection of common defects in plate-based astronomical catalogs.\n <NAME>., <NAME>., <NAME>., & <NAME>., 1995, FOCAS Automatic Catalog Matching Algorithms, Publications of the Astronomical Society of the Pacific 107 1119&#8211;1128An implementation of a method similar to that of Groth (1986).\n \n Background material\n In alphabetical order:\n \n <NAME>. & <NAME>., 2002, Representations of celestial coordinates in FITS, Astronomy & Astrophysics 395 1077&#8211;1122.This paper, along with its companion (Greisen & Calabretta 2002, below), sets down the basic FITS WCS standard for astronomical images. The basic WCS standard allows for various simple spherical-to-planar image projections for the purposes of making sky maps.\n G&#243;<NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>., 2005, HEALPIX: A framework for high resolution discretization and fast analysis of data distributed on the sphere, The Astrophysical Journal 622 759&#8211;771. \n <NAME>. & <NAME>. 2002, Representations of world coordinates in FITS, Astronomy & Astrophysics 395 1061&#8211;1075. \n <NAME>. et al, 2003, The USNO-B Catalog, The Astronomical Journal 125 984&#8211;993.The explanatory paper for the USNO-B1.0 astrometric catalog, on which all of our work is based, either directly or indirectly.\n <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>., 2005, The SIP Convention for Representing Distortion in FITS Image Headers, in ASP Conf. Ser. 347: Astronomical Data Analysis Software and Systems XIV, <NAME>., <NAME>., & <NAME>., eds., 491&#8211;498.This paper clearly walks the user through the very sensible SIP extension to the TAN option in the WCS standard.\n <NAME>., <NAME>., & <NAME>., 1981, FITS: A flexible image transport system, Astronomy & Astrophysics Supplement Series 44 363&#8211;370." ## Bibliography ### Published work by our group In reverse chronological order: * <NAME>. & <NAME>., 2011, Searching for comets on the World Wide Web: The orbit of 17P/Holmes from the behavior of photographers The Astronomical Journal 144, 46. Bibtex We (re-)discover a comet by doing an image search on the Web. * <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>., 2010, Astrometry.net: Blind astrometric calibration of arbitrary astronomical images, The Astronomical Journal 139, 1782–1800. Bibtex Bibtex@ADS We say what we've been doing all these years. * <NAME>., <NAME>., <NAME>., & <NAME>., 2009, Measuring the undetectable: Proper motions and parallaxes of very faint sources, The Astronomical Journal, 137 4400–4411. By simultaneous modeling of the individual-epoch images in a multi-epoch (time series) imaging data set, we show that we can measure proper motions of stars well below the magnitude level (brightness) at which they can be detected in each individual image. By this method we discover a set of new, very cool brown dwarfs (objects too low in mass to start hydrogen burning and become stars). * <NAME>. & <NAME>., 2008, Astronomical imaging: The theory of everything, Classification and Discovery in Large Astronomical Surveys, C.<NAME> (ed.), AIP Conference Proceedings 1082, 331–338. We present an argument that astronomical catalogs should be explicitly created as image models, and that the best-fit or highest likelihood model of the data is also the best possible astronomical catalog. A model of this form is a platform for automated discovery, because it is capable of identifying informative failures of the model in new data at the pixel level, or as statistical anomalies in the joint distribution of residuals from many images. * <NAME>., <NAME>., <NAME>., & <NAME>., 2008, Blind Date: Using proper motions to determine the ages of historical images, The Astronomical Journal, 136 1490–1501. Using only raw pixel data and known catalog proper motions, it is possible to accurately estimate the date of origin of historical imagery. This allows us to retrieve lost meta-data, improve astrometric calibration, and re-estimate proper motions. * <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>., 2008, Automated Astrometry, Astronomical Data Analysis Software and Systems XVII, <NAME>, <NAME>, and <NAME>, eds., ASP Conference Series 394, 27–34. A summary of the project as of 2007 September, aimed at astronomers with an interest in software. * <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>., 2008, Cleaning the USNO-B Catalog through automatic detection of optical artifacts, The Astronomical Journal 135 414–422. The USNO-B Catalog of astrometric standards contains about 2 percent spurious entries that are caused by diffraction spikes and circular reflection halos around bright stars in the original imaging data. We use computer vision techniques to identify and remove them. Our code and data are available here. * <NAME>., 2004, New algorithms for automated astrometry [PDF], MSc Thesis, University of Toronto. Harvey shows that solution to the blind astrometry problem (ie, no first guess at image pointing, rotation, or scale) is possible for at least some kinds of data. Two methods are implemented. ### Published work by other groups * <NAME>., 1986, A pattern-matching algorithm for two-dimensional coordinate lists, The Astronomical Journal 91 1244–1248. This is the first published algorithm for matching image stars to catalog stars that does not depend on image scale. The method makes use of triangles, with many triangles contributing to each solution. The scaling (with the number of stars n) is bad, but the project is similar in spirit to ours. * <NAME>., 1993, Pattern recognition of star constellations for spacecraft applications, IEEE Aerospace and Electronic Systems Magazine 8 (no 1) 33–39. Liebe shows that the blind astrometry problem is easily solved when (a) you have a camera with a large field of view (tens of deg), (b) you know exactly the image scale (ie, your images are calibrated in deg), and (c) you are working with the brightest 1000 or so stars on the sky. The method involves matching triangles of stars. * <NAME>. & <NAME>., 2006 Astrometry in wide-field surveys, The Publications of the Astronomical Society of the Pacific 118 1474–1483. This is similar in spirit to Groth (1986), but includes a very impressive (and successful) test on real-world data. * <NAME>., <NAME>., <NAME>., & <NAME>., 2004, Cleaning sky survey data bases using Hough transform and renewal string approaches, Monthly Notices of the Royal Astronomical Society 347 36–51 They present clever techniques for the automatic detection of common defects in plate-based astronomical catalogs. * <NAME>., <NAME>., <NAME>., & <NAME>., 1995, FOCAS Automatic Catalog Matching Algorithms, Publications of the Astronomical Society of the Pacific 107 1119–1128 An implementation of a method similar to that of Groth (1986). ### Background material * <NAME>. & <NAME>., 2002, Representations of celestial coordinates in FITS, Astronomy & Astrophysics 395 1077–1122. This paper, along with its companion (Greisen & Calabretta 2002, below), sets down the basic FITS WCS standard for astronomical images. The basic WCS standard allows for various simple spherical-to-planar image projections for the purposes of making sky maps. * <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>., 2005, HEALPIX: A framework for high resolution discretization and fast analysis of data distributed on the sphere, The Astrophysical Journal 622 759–771. * <NAME>. & <NAME>. 2002, Representations of world coordinates in FITS, Astronomy & Astrophysics 395 1061–1075. * <NAME> al, 2003, The USNO-B Catalog, The Astronomical Journal 125 984–993. The explanatory paper for the USNO-B1.0 astrometric catalog, on which all of our work is based, either directly or indirectly. * <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>., 2005, The SIP Convention for Representing Distortion in FITS Image Headers, in ASP Conf. Ser. 347: Astronomical Data Analysis Software and Systems XIV, Shop<NAME>., Brit<NAME>., & E<NAME>., eds., 491–498. This paper clearly walks the user through the very sensible SIP extension to the TAN option in the WCS standard. * <NAME>., <NAME>., & <NAME>., 1981, FITS: A flexible image transport system, Astronomy & Astrophysics Supplement Series 44 363–370. Cleaned USNO-B Catalog: The USNO-B Catalog of astrometric standards contains about 2 percent spurious entries that are caused by diffraction spikes and circular reflection halos around bright stars in the original imaging data. We used computer vision techniques to identify and remove them. Information about getting the clean catalog is available here. Quad index files: If you have obtained our code and are seeking the index files necessary to run it, see the instructions at our> use the code page. There are three options for using the Astrometry.net software: Images can be calibrated through a user-friendly web service, on the flickr photo-sharing site, or by a downloadable software package for the computer-savvy. web: The beta version of our web service is operating at nova.astrometry.net, where you can submit images for astrometric calibration. Note that this beta system is somewhat unstable; you should not use this with any expectation that your data will be preserved long-term. If you have questions about using the web service, ask questions on the Google Group. flickr: If you are a member of flickr (free) you can upload images to flickr and submit them to the astrometry group to have them solved. We check for new images roughly once an hour, and images that have been run through the solver will receive a comment with the solve details and are also annotated. This photo of M81 and M82 is an example of a solved photo with annotations. For more information on flickr and how to use it see the flickr FAQ. download: If you want to try downloading and building our software on your local Linux, unix, or Mac box, (also reported to work under Cygwin in Windows) then package:
github.com/luizalabs/tapi
go
Go
README [¶](#section-readme) --- ### Teresa [![Release](https://img.shields.io/github/release/luizalabs/teresa.svg?style=flat-square)](https://github.com/luizalabs/teresa/releases/latest) [![Software License](https://img.shields.io/badge/license-apache-brightgreen.svg?style=flat-square)](https://github.com/luizalabs/tapi/blob/v0.34.0/LICENSE.md) [![Build Status](https://img.shields.io/travis/luizalabs/teresa/master.svg?style=flat-square)](https://travis-ci.org/luizalabs/teresa) [![codecov](https://img.shields.io/codecov/c/github/luizalabs/teresa/master.svg?style=flat-square%22)](https://codecov.io/gh/luizalabs/teresa) [![Go Report Card](https://goreportcard.com/badge/github.com/luizalabs/teresa?style=flat-square)](https://goreportcard.com/report/github.com/luizalabs/teresa) Teresa is an extremely simple platform as a service that runs on top of [Kubernetes](https://github.com/kubernetes/kubernetes). It uses a client-server model: the client sends high level commands (create application, deploy, etc.) to the server, which translates them to the Kubernetes API. #### Server Installation Server requirements: * Kubernetes cluster (>= 1.9) * database backend to store users and teams (SQLite or MySQL) * storage for build artifacts (AWS S3 or minio) * rsa keys for token signing * (optional) TLS encryption key and certificate The recommended installation method uses the [helm](https://github.com/kubernetes/helm) package manager, for instance to install using S3 and MySQL (recommended): ``` $ openssl genrsa -out teresa.rsa $ export TERESA_RSA_PRIVATE=`base64 -w0 teresa.rsa` $ openssl rsa -in teresa.rsa -pubout > teresa.rsa.pub $ export TERESA_RSA_PUBLIC=`base64 -w0 teresa.rsa.pub` $ helm repo add luizalabs http://helm.k8s.magazineluiza.com $ helm install luizalabs/teresa \ --namespace teresa \ --set rsa.private=$TERESA_RSA_PRIVATE \ --set rsa.public=$TERESA_RSA_PUBLIC \ --set aws.key.access=xxxxxxxx \ --set aws.key.secret=xxxxxxxx \ --set aws.region=us-east-1 \ --set aws.s3.bucket=teresa \ --set db.name=teresa \ --set db.hostname=dbhostname \ --set db.username=teresa \ --set db.password=xxxxxxxx \ --set rbac.enabled=true ``` Look [here](https://github.com/luizalabs/tapi/blob/v0.34.0/helm/README.md) for more information about helm options. You need to create an admin user to perform [user and team management](https://github.com/luizalabs/tapi/blob/v0.34.0/FAQ.md): ``` $ export POD_NAME=$(kubectl get pods -n teresa -l "app=teresa" -o jsonpath="{.items[0].metadata.name}") $ kubectl exec $POD_NAME -it -n teresa -- ./teresa-server create-super-user --email <EMAIL> --password xxxxxxxx ``` #### QuickStart Read the first sections of the [FAQ](https://github.com/luizalabs/tapi/blob/v0.34.0/FAQ.md). #### Homebrew Teresa Client Run the following in your command-line: ``` $ brew tap luizalabs/teresa-cli $ brew install teresa ``` #### Snap Teresa Client Run the following in your command-line: ``` $ sudo snap install teresa-cli ``` None
github.com/go-playground/mold/v4
go
Go
README [¶](#section-readme) --- ### Package mold ![Project status](https://img.shields.io/badge/version-4.5.0-green.svg) [![Build Status](https://travis-ci.org/go-playground/mold.svg?branch=v2)](https://travis-ci.org/go-playground/mold) [![Coverage Status](https://coveralls.io/repos/github/go-playground/mold/badge.svg?branch=v2)](https://coveralls.io/github/go-playground/mold?branch=v2) [![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/mold)](https://goreportcard.com/report/github.com/go-playground/mold) [![GoDoc](https://godoc.org/github.com/go-playground/mold?status.svg)](https://godoc.org/github.com/go-playground/mold) ![License](https://img.shields.io/dub/l/vibe-d.svg) Documentation [¶](#section-documentation) --- ### Index [¶](#pkg-index) * [Variables](#pkg-variables) * [func HasValue(field reflect.Value) bool](#HasValue) * [type ErrInvalidTag](#ErrInvalidTag) * + [func (e *ErrInvalidTag) Error() string](#ErrInvalidTag.Error) * [type ErrInvalidTransformValue](#ErrInvalidTransformValue) * + [func (e *ErrInvalidTransformValue) Error() string](#ErrInvalidTransformValue.Error) * [type ErrInvalidTransformation](#ErrInvalidTransformation) * + [func (e *ErrInvalidTransformation) Error() string](#ErrInvalidTransformation.Error) * [type ErrUndefinedTag](#ErrUndefinedTag) * + [func (e *ErrUndefinedTag) Error() string](#ErrUndefinedTag.Error) * [type FieldLevel](#FieldLevel) * [type Func](#Func) * [type InterceptorFunc](#InterceptorFunc) * [type StructLevel](#StructLevel) * [type StructLevelFunc](#StructLevelFunc) * [type Transform](#Transform) * [type Transformer](#Transformer) * + [func New() *Transformer](#New) * + [func (t *Transformer) Field(ctx context.Context, v interface{}, tags string) (err error)](#Transformer.Field) + [func (t *Transformer) Register(tag string, fn Func)](#Transformer.Register) + [func (t *Transformer) RegisterAlias(alias, tags string)](#Transformer.RegisterAlias) + [func (t *Transformer) RegisterInterceptor(fn InterceptorFunc, types ...interface{})](#Transformer.RegisterInterceptor) + [func (t *Transformer) RegisterStructLevel(fn StructLevelFunc, types ...interface{})](#Transformer.RegisterStructLevel) + [func (t *Transformer) SetTagName(tagName string)](#Transformer.SetTagName) + [func (t *Transformer) Struct(ctx context.Context, v interface{}) error](#Transformer.Struct) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) ``` var ( // ErrInvalidDive describes an invalid dive tag configuration ErrInvalidDive = [errors](/errors).[New](/errors#New)("invalid dive tag configuration") // ErrUndefinedKeysTag describes an undefined keys tag when and endkeys tag defined ErrUndefinedKeysTag = [errors](/errors).[New](/errors#New)("'" + endKeysTag + "' tag encountered without a corresponding '" + keysTag + "' tag") // ErrInvalidKeysTag describes a misuse of the keys tag ErrInvalidKeysTag = [errors](/errors).[New](/errors#New)("'" + keysTag + "' tag must be immediately preceeded by the '" + diveTag + "' tag") ) ``` ### Functions [¶](#pkg-functions) #### func [HasValue](https://github.com/go-playground/mold/blob/v4.5.0/util.go#L31) [¶](#HasValue) ``` func HasValue(field [reflect](/reflect).[Value](/reflect#Value)) [bool](/builtin#bool) ``` HasValue determines if a reflect.Value is it's default value ### Types [¶](#pkg-types) #### type [ErrInvalidTag](https://github.com/go-playground/mold/blob/v4.5.0/errors.go#L33) [¶](#ErrInvalidTag) ``` type ErrInvalidTag struct { // contains filtered or unexported fields } ``` ErrInvalidTag defines a bad value for a tag being used #### func (*ErrInvalidTag) [Error](https://github.com/go-playground/mold/blob/v4.5.0/errors.go#L39) [¶](#ErrInvalidTag.Error) ``` func (e *[ErrInvalidTag](#ErrInvalidTag)) Error() [string](/builtin#string) ``` Error returns the InvalidTag error text #### type [ErrInvalidTransformValue](https://github.com/go-playground/mold/blob/v4.5.0/errors.go#L45) [¶](#ErrInvalidTransformValue) ``` type ErrInvalidTransformValue struct { // contains filtered or unexported fields } ``` An ErrInvalidTransformValue describes an invalid argument passed to Struct or Var. (The argument passed must be a non-nil pointer.) #### func (*ErrInvalidTransformValue) [Error](https://github.com/go-playground/mold/blob/v4.5.0/errors.go#L50) [¶](#ErrInvalidTransformValue.Error) ``` func (e *[ErrInvalidTransformValue](#ErrInvalidTransformValue)) Error() [string](/builtin#string) ``` #### type [ErrInvalidTransformation](https://github.com/go-playground/mold/blob/v4.5.0/errors.go#L64) [¶](#ErrInvalidTransformation) ``` type ErrInvalidTransformation struct { // contains filtered or unexported fields } ``` ErrInvalidTransformation describes an invalid argument passed to `Struct` or `Field` #### func (*ErrInvalidTransformation) [Error](https://github.com/go-playground/mold/blob/v4.5.0/errors.go#L69) [¶](#ErrInvalidTransformation.Error) ``` func (e *[ErrInvalidTransformation](#ErrInvalidTransformation)) Error() [string](/builtin#string) ``` Error returns ErrInvalidTransformation message #### type [ErrUndefinedTag](https://github.com/go-playground/mold/blob/v4.5.0/errors.go#L22) [¶](#ErrUndefinedTag) ``` type ErrUndefinedTag struct { // contains filtered or unexported fields } ``` ErrUndefinedTag defines a tag that does not exist #### func (*ErrUndefinedTag) [Error](https://github.com/go-playground/mold/blob/v4.5.0/errors.go#L28) [¶](#ErrUndefinedTag.Error) ``` func (e *[ErrUndefinedTag](#ErrUndefinedTag)) Error() [string](/builtin#string) ``` Error returns the UndefinedTag error text #### type [FieldLevel](https://github.com/go-playground/mold/blob/v4.5.0/field_level.go#L6) [¶](#FieldLevel) ``` type FieldLevel interface { // Transformer represents a subset of the current *Transformer that is executing the current transformation. Transformer() [Transform](#Transform) // // Parent returns the top level parent of the current value return by Field() // // This is used primarily for having the ability to nil out pointer type values. // // NOTE: that is there are several layers of abstractions eg. interface{} of interface{} of interface{} this // function returns the first interface{} // Parent() [reflect](/reflect).[Value](/reflect#Value) // Field returns the current field value being modified. Field() [reflect](/reflect).[Value](/reflect#Value) // Param returns the param associated wth the given function modifier. Param() [string](/builtin#string) } ``` FieldLevel represents the interface for field level modifier function #### type [Func](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L26) [¶](#Func) ``` type Func func(ctx [context](/context).[Context](/context#Context), fl [FieldLevel](#FieldLevel)) [error](/builtin#error) ``` Func defines a transform function for use. #### type [InterceptorFunc](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L36) [¶](#InterceptorFunc) added in v4.1.0 ``` type InterceptorFunc func(current [reflect](/reflect).[Value](/reflect#Value)) (inner [reflect](/reflect).[Value](/reflect#Value)) ``` InterceptorFunc is a way to intercept custom types to redirect the functions to be applied to an inner typ/value. eg. sql.NullString, the manipulation should be done on the inner string. #### type [StructLevel](https://github.com/go-playground/mold/blob/v4.5.0/struct_level.go#L6) [¶](#StructLevel) ``` type StructLevel interface { // Transformer represents a subset of the current *Transformer that is executing the current transformation. Transformer() [Transform](#Transform) // // Parent returns the top level parent of the current value return by Struct(). // // This is used primarily for having the ability to nil out pointer type values. // // NOTE: that is there are several layers of abstractions eg. interface{} of interface{} of interface{} this // function returns the first interface{}. // Parent() [reflect](/reflect).[Value](/reflect#Value) // Struct returns the value of the current struct being modified. Struct() [reflect](/reflect).[Value](/reflect#Value) } ``` StructLevel represents the interface for struct level modifier function #### type [StructLevelFunc](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L32) [¶](#StructLevelFunc) ``` type StructLevelFunc func(ctx [context](/context).[Context](/context#Context), sl [StructLevel](#StructLevel)) [error](/builtin#error) ``` StructLevelFunc accepts all values needed for struct level manipulation. Why does this exist? For structs for which you may not have access or rights to add tags too, from other packages your using. #### type [Transform](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L20) [¶](#Transform) ``` type Transform interface { Struct(ctx [context](/context).[Context](/context#Context), v interface{}) [error](/builtin#error) Field(ctx [context](/context).[Context](/context#Context), v interface{}, tags [string](/builtin#string)) [error](/builtin#error) } ``` Transform represents a subset of the current *Transformer that is executing the current transformation. #### type [Transformer](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L40) [¶](#Transformer) ``` type Transformer struct { // contains filtered or unexported fields } ``` Transformer is the base controlling object which contains all necessary information #### func [New](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L51) [¶](#New) ``` func New() *[Transformer](#Transformer) ``` New creates a new Transform object with default tag name of 'mold' #### func (*Transformer) [Field](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L193) [¶](#Transformer.Field) ``` func (t *[Transformer](#Transformer)) Field(ctx [context](/context).[Context](/context#Context), v interface{}, tags [string](/builtin#string)) (err [error](/builtin#error)) ``` Field applies the provided transformations against the variable #### func (*Transformer) [Register](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L79) [¶](#Transformer.Register) ``` func (t *[Transformer](#Transformer)) Register(tag [string](/builtin#string), fn [Func](#Func)) ``` Register adds a transformation with the given tag NOTES: - if the key already exists, the previous transformation function will be replaced. - this method is not thread-safe it is intended that these all be registered before hand #### func (*Transformer) [RegisterAlias](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L101) [¶](#Transformer.RegisterAlias) ``` func (t *[Transformer](#Transformer)) RegisterAlias(alias, tags [string](/builtin#string)) ``` RegisterAlias registers a mapping of a single transform tag that defines a common or complex set of transformations to simplify adding transforms to structs. NOTE: this function is not thread-safe it is intended that these all be registered before hand #### func (*Transformer) [RegisterInterceptor](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L139) [¶](#Transformer.RegisterInterceptor) added in v4.1.0 ``` func (t *[Transformer](#Transformer)) RegisterInterceptor(fn [InterceptorFunc](#InterceptorFunc), types ...interface{}) ``` RegisterInterceptor registers a new interceptor functions agains one or more types. This InterceptorFunc allows one to intercept the incoming to to redirect the application of modifications to an inner type/value. eg. sql.NullString #### func (*Transformer) [RegisterStructLevel](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L124) [¶](#Transformer.RegisterStructLevel) ``` func (t *[Transformer](#Transformer)) RegisterStructLevel(fn [StructLevelFunc](#StructLevelFunc), types ...interface{}) ``` RegisterStructLevel registers a StructLevelFunc against a number of types. Why does this exist? For structs for which you may not have access or rights to add tags too, from other packages your using. NOTES: - this method is not thread-safe it is intended that these all be registered prior to any validation #### func (*Transformer) [SetTagName](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L70) [¶](#Transformer.SetTagName) ``` func (t *[Transformer](#Transformer)) SetTagName(tagName [string](/builtin#string)) ``` SetTagName sets the given tag name to be used. Default is "trans" #### func (*Transformer) [Struct](https://github.com/go-playground/mold/blob/v4.5.0/mold.go#L146) [¶](#Transformer.Struct) ``` func (t *[Transformer](#Transformer)) Struct(ctx [context](/context).[Context](/context#Context), v interface{}) [error](/builtin#error) ``` Struct applies transformations against the provided struct
ink_lang_codegen
rust
Rust
Trait ink_lang_codegen::CodeGenerator === ``` pub trait CodeGenerator: Sized { type Generator: From<Self> + GenerateCode; } ``` Types for which code can be generated by this crate. Required Associated Types --- #### type Generator: From<Self> + GenerateCode The underlying generator generating the code. Implementations on Foreign Types --- ### impl<'a> CodeGenerator for &'a Contract #### type Generator = Contract<'a### impl<'a> CodeGenerator for &'a InkTraitDefinition #### type Generator = TraitDefinition<'a### impl<'a> CodeGenerator for &'a InkTest #### type Generator = InkTest<'a### impl<'a> CodeGenerator for &'a ChainExtension #### type Generator = ChainExtension<'a### impl<'a> CodeGenerator for &'a SelectorMacro<SelectorId#### type Generator = SelectorId<'a### impl<'a> CodeGenerator for &'a SelectorMacro<SelectorBytes#### type Generator = SelectorBytes<'a### impl<'a> CodeGenerator for &'a Blake2x256Macro #### type Generator = Blake2x256<'aImplementors --- Function ink_lang_codegen::generate_code === ``` pub fn generate_code<T>(entity: T) -> TokenStream2where     T: CodeGenerator, ``` Generates the entire code for the given ink! contract.
qmvs
cran
R
Package ‘qmvs’ April 4, 2023 Version 0.2.0 Title Queueing Model of Visual Search Author <NAME> [aut, cre], <NAME> [aut, cre] Description The queueing model of visual search models the accuracy and response time data in a vi- sual search experiment using queueing models with finite customer population and stopping cri- teria of completing the service for finite number of customers. It implements the conceptualiza- tion of a hybrid model proposed by Moore and Wolfe (2001), in which visual stimuli en- ter the processing one after the other and then are identified in parallel. This package pro- vides functions that simulate the specified queueing process and calculate the Wasserstein dis- tance between the empirical response times and the model prediction. Maintainer <NAME> <<EMAIL>> Imports stats Depends R (>= 3.0) Suggests License GPL (>= 3) NeedsCompilation yes URL Repository CRAN Date/Publication 2023-04-04 15:40:05 UTC R topics documented: distanc... 2 LqDis... 4 queu... 5 si... 6 distance Calculation of the Wasserstein metric between an empirical data set and a data set similated by the queueing model of visual search Description WM calculates a distance between the empirical and simulated response time on a given number of trials in an experiment using standard visual search paradigm. WMdiffresp takes both correct and incorrect response times into account. WMdiffrespweight takes both correct and incorrect response times into account and weights the distances of correct and incoreect response times with the relative frequencies of the data. WMdiffrespshift takes both correct and incorrect response times into ac- count and assumes different non-decision times for no and yes responses. WMdiffrespshiftweight takes both correct and incorrect response times into account assuming different non-decision times for no and yes responses and weights the distances with the relative frequencies of the data. Usage WM(par, esterrorpar, c, k, pr, N, empRT, old=FALSE) WMdiffresp(par, esterrorpar, c, k, pr, N, empRT, empresp, old=FALSE, seed=0) WMdiffrespweight(par, esterrorpar, c, k, pr, N, empRT, empresp, old=FALSE, seed=0) WMdiffrespshift(par, esterrorpar, c, k, pr, N, empRT, empresp, old=FALSE, seed=0) WMdiffrespshiftweight(par, esterrorpar, c, k, pr, N, empRT, empresp, old=FALSE, sep_shift = TRUE, wcorrect = NULL, seed=0) Arguments par A vector of length 3 or 4, equals (miat, mst, Tres) if non-decision time is as- sumed to be the same for no and yes responses (as in WM, WMdiffresp and WMdiffrespweight) and (miat, mst, Tresn, Tresy) otherwise (as in WMdiffrespshift and WMdiffrespshiftweight). esterrorpar A vector of length 5. Estimates of the accuracy-related parameters (α, β, a1 , a2 , b) c A natural number representing the number of parallel servers of the system. k A natural number representing the total number of stimuli in the display (set size). pr Logical. If pr is TRUE, the function simulates data on target present trials; if pr is FALSE, it simulates data on target absent trials. N A natural number representing the number of simulation runs. empRT A vector of empirical response times collected under given target presence and set size condition. empresp A vector of empirical responses collected under given target presence and set size condition. old Logical. If old is TRUE, the simulation is implemented by R code; if old is FALSE, it is implemented by C code. Only for comparison of speed. Default option is FALSE. sep_shift Logical. Shall separate shifts be used for positive and negative answers? wcorrect Logical or NULL. Weighing of the positive responses in the convex combination of Lq distances between empirical and theoretical distributions for the positive and negativ answers separately. seed The random seed used in the simulation. Value A positive number. WMdiffresp returns the sum of the distances associated with correct and in- correct response times, WMdiffrespweight the sum of the weighted distances. WMdiffrespshift the sum of the distances associated with correct and incorrect response times, assuming different non-decision times for no and yes responses. WMdiffrespshiftweight the weighted sum. Author(s) <NAME>, <<EMAIL>>,https://www.xing.com/profile/Yiqi_Li3, <NAME>,<<EMAIL> //www.wim.uni-mannheim.de/schlather/ References Li, Yiqi (2020) Visual search as a queueing process. Doctoral dissertation, University of Mannheim. See Also queue, LqDist, sim, Examples simdata1 <- sim.ny(par = c(30, 200, 250, 350), esterrorpar = c(-2.67, 0.0094, 0.0299, 0.0020, 1.13), c = 4, k = 12, N = 10000, pr = TRUE, seed = 0) simdata2 <- sim.ny(par = c(30, 200, 250, 350), esterrorpar = c(-2.67, 0.0094, 0.0299, 0.0020, 1.13), c = 4, k = 12, N = 10000, pr = TRUE, seed = 12345) WM(par = c(30, 200, 300), esterrorpar = c(-2.67, 0.0094, 0.0299, 0.0020, 1.13), c = 4, k = 12, pr = TRUE, N = 10000, empRT = simdata2[,1], old=FALSE) WMdiffresp(par = c(30, 200, 300), esterrorpar = c(-2.67, 0.0094, 0.0299, 0.0020, 1.13), c = 4, k = 12, pr = TRUE, N = 10000, empRT = simdata2[,1], empresp = simdata2[,2], old=FALSE) WMdiffrespweight(par = c(30, 200, 300), esterrorpar = c(-2.67, 0.0094, 0.0299, 0.0020, 1.13), c = 4, k = 12, pr = TRUE, N = 10000, empRT = simdata2[,1], empresp = simdata2[,2], old=FALSE) WMdiffrespshift(par = c(30, 200, 250, 350), esterrorpar = c(-2.67, 0.0094, 0.0299, 0.0020, 1.13), c = 4, k = 12, pr = TRUE, N = 10000, empRT = simdata2[,1], empresp = simdata2[,2], old=FALSE) WMdiffrespshiftweight(par = c(30, 200, 250, 350), esterrorpar = c(-2.67, 0.0094, 0.0299, 0.0020, 1.13), c = 4, k = 12, pr = TRUE, N = 10000, empRT = simdata2[,1], empresp = simdata2[,2], old=FALSE) LqDist Calculation of the distance between two data sets Description LqDist calculates the Wasserstein metric or Kolmogorov-Smirnov distance between two data sets. Usage LqDist(E1, E2, q=1) Arguments E1, E2 Vectors of data between which a distance is to calculate. q Option for the distance measure. If q equals 1, the Wasserstein metric will be calculated. If q equals Inf, the Kolmogorov-Smirnov distance will be calcu- lated. Default option is 1. Value A positive number. Author(s) <NAME>, <<EMAIL>>,https://www.xing.com/profile/Yiqi_Li3, <NAME>,<<EMAIL> //www.wim.uni-mannheim.de/schlather/ References Li, Yiqi (2020) Visual search as a queueing process. Doctoral dissertation, University of Mannheim. See Also distance, Examples simdata1 <- sim.ny(par = c(30, 200, 250, 350), esterrorpar = c(-2.67, 0.0094, 0.0299, 0.0020, 1.13), c = 4, k = 12, N = 10000, pr = TRUE, seed = 0) simdata2 <- sim.ny(par = c(30, 200, 250, 350), esterrorpar = c(-2.67, 0.0094, 0.0299, 0.0020, 1.13), c = 4, k = 12, N = 10000, pr = TRUE, seed = 12345) simcorrectRT1 <- subset(simdata1, simdata1[,2] == TRUE, select = 1) simcorrectRT2 <- subset(simdata2, simdata2[,2] == TRUE, select = 1) LqDist(simcorrectRT1, simcorrectRT2, q=1) queue Simulation of the queueing model of visual search Description queue simulates the response and response time on a single trial in an experiment using standard visual search paradigm. Usage queue(miat, mst, c, pr, L, misidd, misidt, arrival, serving, tposition, old=FALSE) Arguments miat A positive number representing the scale parameter of the exponential distribu- tion of interarrival times, i.e., the mean interarrival time. mst A positive number representing the scale parameter of the exponential distribu- tion of service times, i.e., the mean service time. c A natural number representing the number of parallel servers of the system. pr Logical. If pr is TRUE, the function simulates data on target present trials; if pr is FALSE, it simulates data on target absent trials. L A natural number representing the number of stimuli that have been identified to terminate the queueing process. misidd Logical vector of length k. Here, FALSE means correct identification and T RU E misidentification of a distractor. misidt Logical. Here, FALSE means correct identification and TRUE misidentification of the target. arrival A vector of length set size. Elements must be exponentially distributed random numbers with rate 1. serving A vector of length set size. Elements must be exponentially distributed random numbers with rate 1. tposition A natural number representing the position of the target in the queue, in target present case less or equal to set size, in target absent case equal to set size +1. old Logical. If old is TRUE, the simulation is implemented by R code; if old is FALSE, it is implemented by C code. Only for comparison of speed. Default option is FALSE. Value A numeric vector of length 5 indicating the number of visual items processed, the mean processing time of a single item, the maximum of processing time of a single item, the system response time and the response. Author(s) <NAME>, <<EMAIL>>,https://www.xing.com/profile/Yiqi_Li3, <NAME>,<<EMAIL> //www.wim.uni-mannheim.de/schlather/ References Li, Yiqi (2020) Visual search as a queueing process. Doctoral dissertation, University of Mannheim. <NAME>.,and <NAME>. (2001) Getting beyond the serial/parallel debate in visual search: A hybrid approach. In Shapiro, K.L. The Limits of Attention: Temporal Constraints on Human Infor- mation Processing. Oxford University Press doi:10.1093/acprof:oso/9780198505150.003.0009 See Also sim, distance, Examples queue(miat = 30, mst = 200, c = 4, pr = TRUE, L = 12, misidd = rep(0L, 12), misidt = 0, arrival = rexp(12), serving = rexp(12), tposition = 7, old=FALSE) sim Simulation of the queueing model of visual search Description sim.ny simulates a data set containing the responses and response times on either target present or target absent trials under specified set size level in an experiment using standard visual search paradigm, whereby the non-decision time for yes and no options are represented by two different parameters. Usage sim.ny(par, esterrorpar, c, k, pr, N, empRT, seed=0) Arguments par A vector of length 3 or 4, equals (miat, mst, Tres) if non-decision time is as- sumed to be the same for no and yes responses (as in WM, WMdiffresp and WMdiffrespweight) and (miat, mst, Tresn, Tresy) otherwise (as in WMdiffrespshift and WMdiffrespshiftweight). esterrorpar A vector of length 5. Estimates of the accuracy-related parameters (α, β, a1 , a2 , b) c A natural number representing the number of parallel servers of the system. k A natural number representing the total number of stimuli in the display (set size). pr Logical. If pr is TRUE, the function simulates data on target present trials; if pr is FALSE, it simulates data on target absent trials. N A natural number representing the number of simulation runs. empRT A vector of empirical response times collected under given target presence and set size condition. seed The random seed used in the simulation. Value A N × 2 matrix. The first column contains the simulated response times and the second colum the corresponding simulated responses. Author(s) <NAME>, <<EMAIL>>,https://www.xing.com/profile/Yiqi_Li3, <NAME>,<<EMAIL> //www.wim.uni-mannheim.de/schlather/ References Li, Yiqi (2020) Visual search as a queueing process. Doctoral dissertation, University of Mannheim. See Also queue Examples sim.ny(par = c(30, 200, 250, 350), esterrorpar = c(-2.67, 0.0094, 0.0299, 0.0020, 1.13), c = 4, k = 12, pr = TRUE, N = 10000, seed = 0)
curve2e
ctan
TeX
# Package curve2e user manual <NAME> claudio dot beccari at gmail dot com Version 2.3.1 - Last revised 2023-07-04 ###### Abstract This file contains the user manual of the curve2e extension package to the pict2e bundle; the latter was described by Lamport himself in the 1994 second edition of his LaTeX handbook. Please take notice that on April 2011 a package pict2e upgraded version has been released that incorporates some of the commands defined in early versions of this package curve2e; apparently there are no conflicts, because this package contains only the advanced features that extend the above package. Since this extension redefines some commands and introduces some more drawing facilities (that allow to draw circular arcs and arbitrary curves with the minimum of user intervention) the user needs a user manual that contains several actual examples; this auxiliary manual is contained in file curve2e-manual.pdf. The software available to show the drawing code and its result after compilation is incompatible with the usual LaTeX ltxdoc class for code documentation, therefore a separate user manual has been made available. If the user wants to explore the curve2e code and its documentation s/he has available the curve2e.pdf file. Either file is readable by entering in a terminal window the command texdoc curve2e-manual or texdoc curve2e.pdf; please do not forget the extension when you want to read the code documentation. ###### Contents * 1 Installation * 2 Package pict2e and this extension curve2e * 3 Summary and examples of new commands * 4 Remarks * 5 Acknowledgements ## 1 Installation If LaTeX system was installed with a LaTeX Live or a MiKTeX complete and updated distribution this package is already installed; in order to verify open a terminal or command prompt window and use it to enter the texdoc curve2e-manual; as soon as the command is executed a screen window should open displaying this manual. If this does not happen, either you misspelt the command (it happens more often than not), or your installation is not complete and updated. I suggest you to use your computer installation facilities to install this bundle. Otherwise, download this curve2e.zip package from one of the CTAN (Comprehensive TeX Archive Network) archives, to your downloads folder. Before doing anything else verify if you have a _personal_ texmf tree; if not, create one reading you distribution instruction; let us assume that your personal texmf archive is in HOME/texmf (on Windows change the slash with a backslash) and HOME is a path starting from the root of you hard disk and going though several other folders. On Windows 10 it might be C:\Users\YourName; on Linux it might simply be ~; on Mac it would be ~/\Library, but sometimes the HOME might be different, especially on Windows platforms. Create the following subfolders: 1. HOME/texmf/source/latex/curve2e/ 2. HOME/texmf/doc/latex/curve2e/ 3. HOME/texmf/tex/latex/curve2e/ Now move file curve2e.zip to the.../source/latex/curve2e/ folder; then decompress the.zip file with the software you have available on your platform. Run pdflatex on the.dtx file; then do the same with the curve2e-manual.tex. You might need to repeat these compilations two or three times in order to have the table of contents and all the references correctly connected. This done move the.pdf files to the.../doc/latex/curve2e/ folder. and move the.sty files to the.../tex/latex/curve2e/ folder. Clear the.../source/latex/curve2e/ folder from the auxiliary files, all those remaining in the folder except those that have the extensions.zip,.dtx,.tex, and.txt. Read the README.txt file. If your TeX system is correctly set up, your files in your personal tree should be immediately usable; probably you have to create the file-name database with MiKTeX; in this case read the documentation of your MiKTeX installation to discover how to do it. Remember to delete all these subfolders if you decide to install a complete updated version of your favourite distribution, and you'd better keep it updated approximately once every 7 or 10 days. This is much simpler than to struggle with these manual operations. ## 2 Package pict2e and this extension curve2e Package pict2e was announced in issue 15 of latexnews around December 2003; it was declared that the new package would replace the dummy one that had been accompanying every release of LaTeX 2\({}_{\mathcal{E}}\) since its beginnings in 1994. The dummy package was just issuing an info message that simply announced the temporary unavailability of the real package. Eventually Gasslein and Niepraschk implemented what Lamport himself had already documented in the second edition of his LaTeX handbook, it was a LaTeX package that contained the macros capable of removing all the limitations contained in the standard commands of the original picture environment; specifically what follows. 1. The line and vector slopes were limited to the ratios of relative prime one-digit integers of magnitude not exceeding 6 for lines and 4 for vectors. 2. Filled and unfilled full circles were limited by the necessarily limited number of specific glyphs contained in the special LaTeX picture fonts. 3. Quarter circles radii were also limited for the same reason. 4. Ovals (rectangles with rounded corners) could not be too small because of the unavailability of small radius quarter circles, nor could be too large, in the sense that after a certain radius the rounded corners remained the same curvature and would not increase proportionally to the oval size. 5. Vector tips had only one possible shape and matched the limited number of vector slopes. 6. For circles and inclined lines and vectors just two possible thicknesses were available. Package pict2e removes most if not all the above limitations. 1. Line and vector slopes are virtually unlimited; the only remaining limitation is that the direction coefficients must be three-digit integer numbers; they need not be relatively prime; with the 2009 upgrade even this limitation was removed and now slope coefficients can be any fractional number whose magnitude does not exceed 16 384, the maximum dimension in points that TEX can handle. 2. Filled and unfilled circles can be of any size. 3. Ovals can be designed with any specified corner curvature and there is virtually no limitation to such curvatures; of course corner radii should not exceed half the lower value between the base and the height of the oval. 4. There are two shapes for the arrow tips; the triangular one traditional with TEX vectors, or the arrow tip with PostScript style. 5. The \(\backslash\)linethickness command changes the thickness of all lines, straight, curved, vertical, horizontal, arrow tipped, et cetera. This specific extension package curve2e adds the following features. 1. Point coordinates can be specified with macros; this is similar to "naming" points; it eases editing the user's graphic work, because points that are used several times are specified with a single macro; it also eases the transmission of coordinates between different macros and environments. It is also important for the following feature, described in the following entry.. 2. Point coordinates my be specified in both cartesian and polar form: internally they are handled as cartesian coordinates, but the user can specify his/her points also in polar form. In order to avoid confusion with other graphic packages, curve2e uses the usual comma separated couple \(\langle x,y\rangle\) of integer or fractional numbers for cartesian coordinates, and the couple \(\langle\theta\rangle\):\(\langle\rho\rangle\) for polar coordinates (the angle preceding the radius). All graphic object commands accept polar or cartesian coordinates at the choice of the user who may use for each object the formalism s/he prefers. Also the \(\backslash\)put and \(\backslash\)multiput commands have been redefined so as to accept cartesian or polar coordinates. Of course the user should pay attention to the meaning of cartesian vs. polar coordinates. Both imply a displacement with respect to the actual origin of the axes. So when a circle center is placed at coordinates \(a,b\) with a normal \(\backslash\)put command, the circle is placed exactly in that point; with a normal \(\backslash\)put command the same happens if coordinates \(\alpha\):\(\rho\) are specified. But if the \put command is nested into another \put command, the current origin of the axes is displaced -- this is obvious and the purpose of nesting \put commands is exactly that. But if a segment is specified so that its ending point is at a specific distance and in specific direction from its starting point, polar coordinates appear to be the most convenient to use; in this case, though, the origin of the axes becomes the starting point of the segment, therefore the segment might be drawn in a strange way. Attention has been paid to avoid such misinterpretation, but maybe some unusual situation may not have come to my mind; feedback is very welcome. Meanwhile pay attention when you use polar coordinates. 3. At user level most if not all coordinate pairs and slope pairs are treated as _ordered pairs_, that is _complex numbers_; in practice the user does not notice any difference from what s/he was used to, but all the mathematical treatment to be applied to these entities is coded as complex number operations, since complex numbers may be viewed non only as ordered pairs, but also as vectors or as roto-amplification operators. 4. Commands for setting the line terminations were introduced; the user can chose between square or rounded caps; the default is set to rounded caps; now this feature is directly available with \pic2e. 5. Commands for specifying the way two straight or curves lines join to one another. 6. Originally the \line macro was redefined so as to allow large (up to three digits) integer direction coefficients, but maintaining the same syntax as in the original picture environment; now \pic2e removes the integer number limitations and allows fractional values, initially implemented by curve2e; now direction coefficients may be specified in polar form. 7. A new macro \Line was originally defined by curve2e so as to avoid the need to specify the horizontal projection of inclined lines; now this functionality is available directly with \pic2e; but this curve2e macro name now conflicts with the \pic2e 2009 version; therefore its name is changed to \Line and supposedly it will not be used very often, if ever, by the end user (but it is used within this package macros). 8. A new macro \LINE was defined in order to join two points specified with their coordinates; this is now the normal behaviour of the \Line macro of \pic2e, so that in this package \LINE is now renamed \segment; there is no need to use the \put command with this segment specification. 9. A new macro \DashLine (alias: \Dline) is defined in order to draw dashed lines joining any two given points; the dash length and gap (equal to one another) get specified through one of the macro arguments. The starting point may be specified in cartesian or polar form; the end point in cartesian format specifies the desired end point; but, if the second point is in polar form, it is meant _relative to the starting point_, not as an absolute end point. See the examples further on. 10. A similar new macro \Dotline is defined in order to draw dotted straight lines as a sequence of equally spaced dots, where the gap can be specified by the user; such straight line may have any inclination, as well as the above dashed lines. Polar coordinates for the second point have the same relative meaning as specified for the \Dashline macro. The dot diameter may be specified with an optional argument; by default this diameter equals the \(\lit{1pt}\) width. 11. Similar macros are redefined for vectors; Vector redefines the original macro but with the vector slope limitations removed and the vector direction may be given in polar form; Vector gets specified with its two horizontal and vertical components in analogy with LLine; VECTOR joins two specified points (without using the \put command) with the arrow pointing to the second point. VVECTOR may be available if used with a sufficiently recent LaTeX kernel version; it draws a vector between two given points, with arrow tips at both ends. 12. A new macro \polyline for drawing polygonal lines is defined that accepts from two vertices up to an arbitrary (reasonably limited) number of them (available now also in pict2e); here it is redefined so as to allow an optional specification of the way segments for the polyline are joined to one another. Vertices may be specified with polar coordinates and are always relative to the preceding point. 13. The pict2e \polygon macro draws closed polylines (in practice general polygons) has been redefined in such a way that it can accept the various vertices specified with (relative) polar coordinates. The polygon* macro produces a color filled polygon; the default color is black, but a different color may be specified with the usual \color command given within the same group where \polygon* is enclosed. 14. A new macro \Arc is defined in order to draw an arc with arbitrary radius and arbitrary aperture (angle amplitude); this amplitude is specified in sexagesimal degrees, not in radians; a similar functionality is now achieved with the \arc macro of pict2e, which provides also the starred version \arc* that fills up with the current color the sector generated by a circular arc. It must be noticed that the syntax is slightly different, so that it's reasonable that these commands, in spite of producing identical arcs, might be more comfortable with this or that syntax. 15. Two new macros \VectorArc and \VectorARC (alias \VVectorArc) are defined in order to draw circular arcs with an arrow at one or both ends. 16. A new macro \Curve is defined so as to draw arbitrary curved lines by means of cubic Bezier splines; the \Curve macro requires only the curve nodes and the directions of the tangents at each node. The starred version fills up the interior of the curve with the current color. 17. The above \Curve macro is a recursive macro that can draw an unlimited (reasonably limited) number of connected Bezier spline arcs with specification of the tangent direction at the interpolation nodes. It is possible to use a lower level macro \CbezierTo that does the same but lets the user specify the control points of each arc; it is more difficult to use but it is more performant.\Curve recognises also an optional argument to set a direction change, that is a cusp. 18. The basic macros used within the cumulative \Curve macro can be used individually in order to draw any curve, one cubic arc at the time; but they are intended for internal use, even if it is not prohibited to use them; by themselves such arcs are not different form those used by Curve, but the final command, \FillCurve, should be used in place of \CurveFinish, so as to fill up the closed path with the locally specified color; see figure 11. It is much more convenient to use the starred version of the \Curve macro. The pict2e package already defines macros such as \moveto, \lineto, \curveto,\closepath, \fillpath, and \strokepath; curve2e just redefines them so as to accept also polar coordinates; of course these macros can be used by the end user, and sometimes they perform better than the macros defined in this package, because the user has a better control on the position of the Bezier splines control points; in this case the control points are sort of rigid. It would be very useful to resort to the hobby package, but its macros are compatible with those of the tikz and pgf packages, not withcurve2e; an interface should be created in order to deal with the hobby package, but this has not been done yet. In order to make the necessary calculations many macros have been defined so as to use complex number arithmetics to manipulate point coordinates, directions (unit vectors, also known as'versors'), rotations and the like. In the first versions of this package the trigonometric functions were also defined in a way that the author believed to be more efficient than those defined by the trig package; in any case the macro names were sufficiently different to accommodate both definition sets in the same LaTeX run. With the progress of the LaTeX3 language, package \(\mathsf{xfp}\) functionalities have become available, and any sort of calculations can be done floating point decimal numbers; therefore the most common algebraic, irrational and transcendental functions can be computed in the background with the stable internal floating point facilities. We maintain some computation with complex number algebra, but use the xfp functionalities for other computations. Many aspects of this extension could be fine tuned for better performance; many new commands could be defined in order to further extend this extension. If the new service macros are accepted by other TeX and LaTeX programmers, this version could become the start for a real extension of the pict2e package or even become a part of it. Actually some macros have already been included in the pict2e package. The \(\mathsf{Curve}\) algorithm, as said before, might be redefined so as to use the macros introduced by the hobby package, that implements for the tikz and pgf packages the same functionalities that <NAME> implemented for the METAFONT and METAPOST programs. For these reasons I suppose that every enhancement should be submitted to Gallein, Niepraschk, and Tkadlec who are the prime maintainers of pict2e; they are the only ones who can decide whether or not to incorporate new macros in their package. ## 3 Summary and examples of new commands This package curve2e extends the power of pict2e with the following modifications and the following new commands. 1. This package curve2e calls directly the LaTeX packages color and pict2e; it passes to the latter one any possible option that it can receive; actually the only options that make sense for pict2e are those concerning the arrow tip shapes, either LaTeX (default) or PostScript styled, because it is assumed that if this package is used, the original LaTeX commands are of no interest: see the pict2e documentation in order to find the correct options pict2e can receive. If the user wants to use the xcolor package, it has to load it _before_ curve2e. 2. Since they are used very much in the following examples, we recall some commands to label certain drawing elements, such as points, lines, arcs,and similar lines, and to insert legends in some figures. They are \legenda, \Zbox and \Pbox; their syntax is the following: \legenda(\(\langle\)coordinates\(\rangle\)){\(\langle\)formula\(\rangle\)} \Zbox(\langle\)coordinates\(\rangle\)){\(\langle\)position\(\rangle\)}{\(\langle\)formula\(\rangle\)}{\(\langle\)dot diameter\(\rangle\)} \Pbox(\langle\)coordinates\(\rangle\){\(\langle\)position\(\rangle\)}{\(\langle\)text\}{\langle\)text\}{\langle\)text\}{\langle\)text\}{\langle\)dot diameter\(\rangle\}{\langle\)*\(\rangle\)<\(\langle\)angle\(\rangle\)>} They are described in any up to date documentation of curve2e. 3. The user is offered new commands in order to control the line terminators and the line joins; specifically: * \roundcap: the line is terminated with a semicircle; * \squaredcap: the line is terminated with a half square; * \roundjoin: two lines are joined with a rounded join; * \beveljoin: two lines are joined with a level join; * \miterjoin: two lines are joined with a miter join. All the above commands should respect the intended range; but since they act at the PostScript or PDF level, not at TeX level, it might be necessary to issue the necessary commands in order to restore the previous terminator or join; in other words, groups and environments do not have any influence on these commands. 4. The commands \linethickness{\(\langle\)thickness\(\rangle\)} \thickness{\thinlines} \defaultlinethickness{\(\langle\)thickness\(\rangle\)} always redefine the internal \@wholewidth and \@halfwidth so that the latter ones always refer to a full width and to a half of it in this way if you issue the command \defaultlinethickness{2pt} all thin lines will be drawn with a thickness of \(1\,\mathrm{pt}\) while, if a drawing command directly refers to the internal value \@wholewidth, its line will be drawn with a thickness of \(2\,\mathrm{pt}\). If one issues the declaration \thinlines all lines will be drawn with a \(1\,\mathrm{pt}\) width, but if a command refers to the internal value \@halfwidth the line will be drawn with a thickness of \(0.5\,\mathrm{pt}\). The command \linethickness redefines the above internals but does not change the default width value; all these width specifications apply to all lines, straight ones, curved ones, circles, ovals, vectors, dashed lines, and so on. It's better to recall that \thinlines and \thickness are declarations that do not take arguments; on theposite the other commands, as shown in the above syntax medallion, accept a specific thickness value, that is either a length specification complete of its units, or a dimensional expression. 5. Straight lines and vectors are redefined in such a way that fractional slope coefficients may be specified; the zero length line and vector does not produce errors and is ignored; the zero length vectors draw only the arrow tips. 6. New line and vector macros are defined that avoid the necessity of specifying the horizontal component; \put(3,4){\LIne(25,15)} specifies a segment that starts at point \(3,4)\) and goes to point \(3+25,4+15); the command \segment(3,4)(28,19) achieves the same result without the need of using the \put command. Therefore \LIne is just for internal usage, rather than a user command. Now curve2e has available also the "arc vectors" with the arrow tips at one or at both ends. The \segment syntax is \segment(\segment(\(\mathit{starting\ point}\))) The same applies to the vector commands \Vector and \VECTOR and \VPECTOR; the latter command behaves as \VECTOR but draws a vector with arrow tips at both ends; furthermore this command is available only with main versions 2 or higher of curve2e. \put(\(\mathit{starting\ point}\))\{\Vector\(\mathit{vector\ cartesian\ or\ polar\ components}\}\)\VPECTOR(\(\langle\mathit{starting\ point}\rangle\))(\(\langle\mathit{ending\ point}\rangle\))\VPECTOR(\(\langle\mathit{starting\ point}\rangle\))\(\langle\mathit{ending\ point}\rangle\)) Experience has shown that the commands intended to join two specified points are particularly useful; see figure 1. 7. The \polyline command has already been introduced in pict2e: in curve2e it is redefined so as to accept also polar coordinates; this new version of \polyline accepts also an optional argument to specify how two consecutive segments join together; it accepts an unlimited list of point coordinates, possibly stored in macros, enclosed within round parentheses; the command draws a sequence of connected segments that join in order the specified points; the syntax is: See figure 2 where a regular pentagon is drawn; usage of polar coordinates is also shown; please notice how polar coordinates act in this figure. Examples of using polar and cartesian coordinates are shown in figure 3. Notice the \AutoGrid macro that draws the grid of mesh lines that are very useful to seti objects at the right positions. The lines are 10\unitlenght apart. A similar example may be obtained with the \polygon macro that does not require to terminate the polyline at the starting point. Figure 4 shows how to get a coloured filled pentagon. Figure 1: Three (displaced) identical vectors obtained with the three vector macros; a double tipped vector is also shown. * The new command \Dashline (alias: \Dline for backwards compatibility): \Dashline((_first point_)) (_second point_) {_dash and gap length_} } draws a dashed line containing as many dashes as possible, just as long as specified, and separated by a gap exactly the same size; actually, in order to make an even gap-dash sequence, the desired dash length is used to do some computations in order to find a suitable length, close to the one specified, such that the distance of the end points is evenly divided in equally sized dashes and gaps. The end points may be anywhere in the drawing area, without any constraint on the slope of the joining segment. The desired dash length is specified as a fractional multiple of \unitlength; see figure 5. Another example of usage of cartesian and polar coordinates usage is shown in figure 3 together with its code. * Analogous to \Dashline, a new command \Dotline draws a dotted line with the syntax: \Dotline(\(\langle\)_first point_)) (\(\langle\)_end point_) {_dot gap_} Figure 4: A pentagon obtained by means of the \polygon* command; vertex coordinates are in relative polar form. Figure 3: Use of cartesian and absolute polar coordinates. The \Zbox macro is just a shortcut to set a small dot with a (math) legend close to it. Figure 2: Polygonal line obtained by means of the \polyline command; vertex coordinates are in polar form. See figures 5 and 7 for examples. 10. \GraphGrid and \AutoGrid are commands that draw a red grid under the drawing with lines separated 10\unitlengths apart; it is described only with a comma separated couple of numbers, representing the base and the height of the grid, see figure 5; it's better to specify multiples of ten and the grid can be placed anywhere in the drawing canvas by means of \put, whose cartesian coordinates are multiples of 10; nevertheless the grid line distance is rounded to the nearest multiple of 10, while the point coordinates specified to \put are not rounded at all; therefore some care should be used to place the working grid on the drawing canvas. \GraphGrid(\(\mathit{grad\ base,\ grid\ height}\)) \AutoGrid This grid is intended as an aid while drawing; even if you sketch your drawing on millimetre paper, the drawing grid turns out to be very useful; one must only delete or comment out the command when the drawing is finished. Several examples of usage of such grid are shown in several figures. \Autogrid does not require arguments, but requires the canvas dimensions and offsets to be specified as multiples of 10; if the latter are specified they are simply ignored. 11. New trigonometric function macros have been computed by means of the functionalities of the xfp included in the LaTeX kernel. The difference with the other existing macros is that angles are specified in sexagesimal degrees, so that the users need not transform to radians. The computations are done taking into account that "abnormal" values that can occasionally be avoided, for example \(\tan 90^{\circ}\) must be avoided and replaced with a suitably large number, because the TeX system does not handle "infinity". These trigonometric functions are used within the complex number macros; but if the user wants to use them the syntax is the following: \SinOf(\(\mathit{angle}\))to\(\mathit{\langle\mathit{control\ sequence}\rangle}\) \CosOf(\(\mathit{angle}\))to\(\mathit{\langle\mathit{control\ sequence}\rangle}\) \TanOf\(\langle\mathit{angle}\))to\(\langle\mathit{\langle\mathit{control\ sequence}\rangle}\) Figure 5: Dashed lines and graph grid The _control sequence_ may then be used, for example, as a multiplying factor of a length. 12. Arcs can be drawn as simple circular arcs, or with one or two arrows at their ends (curved vectors); the syntax is: \Arc(\(\(\mathit{center}\)))(\(\(\mathit{starting\ point}\)))\{\(\langle\mathit{angle}\rangle\)} \VectorArc(\(\langle\mathit{center}\rangle\)))(\(\(\mathit{starting\ point}\)))\{\(\langle\mathit{angle}\rangle\)} \VectorARC(\(\langle\mathit{center}\rangle\))(\(\(\mathit{starting\ point}\)))\{\(\langle\mathit{angle}\rangle\)} \VVectorArc(\(\langle\mathit{center}\rangle\))(\(\langle\mathit{starting\ point}\rangle\))\{\(\langle\mathit{angle}\rangle\)} If the angle is specified numerically it must be enclosed in braces, while if it is specified with a control sequence the braces (curly brackets) are not necessary. The above macro \Arc draws a simple circular arc without arrows; \VectorArc draws an arc with an arrow tip at the ending point; \VectorARC (alias \VVVectorArc) draws an arc with arrow tips at both ends; see figure 8. Notice that the starting point may be specified with polar coordinates; differently to cartesian coordinates, that are absolute with respect with the drawing axes, the polar ones are relative to the center of the arcs with or without vector tips. 13. The available commands allow to create the drawings necessary to prove some geometrical theorems; for example let us prove the Pitagora's theorem. Figure 9 displays a right triangle with its hypothenuse laying horizontally; its vertices are labeled A, B, and C, being A the right angle vertex. The height relative to the hypothenuse intersects this side in point H, and divides the whole triangle ABC, in two similar smaller ones \HC, and\ABH. Segments CH, andHB, add to the whole hypothenuse length. Figure 9 displays also the square CBDE, built on the hypothenuse and divided in two rectangles \CHFE, and \HBDF, where HF is the continuation of the height line. Figure 6: Different length dashed lines with the same nominal dash length; notice the relative polar coordinates used for the dashed lines starting at the grid lower right vertex. The lengths of the original right triangle sides are \(a,b,c\) as marked on the figure; Point H divides the hypothenuse of length \(c\) in two shorter segments of lengths \(d,e\), respectively, as marked in the figure Since the three triangles are similar, we can set up the relationships between their sides: \[d:a=a:c\Longrightarrow d=a^{2}/c\] \[e:b=b:c\Longrightarrow e=b^{2}/c\] Therefore rectangle CHFE area equals \(c\cdot d=c\cdot a^{2}/c=a^{2}\). Similarly rectangle HBDF area equals \(c\cdot e=c\cdot b^{2}/c=b^{2}\). The square built on the hypothenuse has an area equal to \(c^{2}\); therefore it is \[c^{2}=a^{2}+b^{2}\] which proves the Pitagora's theorem. 14. A multitude of commands have been defined in order to manage complex numbers; actually complex numbers are represented as a comma separated Figure 8: Arcs and curved vectors Figure 7: Different length dotted lines with the same nominal dot gap; again notice the relative polar coordinates for the dotted lines starting at the grid lower right vertex. pair of fractional numbers; internally these macros use only the cartesian form, and output, unless differently specified is also in cartesian form; but input can be in polar form. They are used to address specific points in the drawing plane, but also as operators so as to scale and rotate other objects. In the following \(\langle\)_vector_\(\rangle\) means a comma separated pair of fractional numbers, \(\langle\)_vector macro_\(\rangle\) means a macro that contains a comma separated pair of fractional numbers; \(\langle\)_angle macro_\(\rangle\) means a macro that contains the angle of a vector in sexagesimal degrees; \(\langle\)_argument_\(\rangle\) means a brace delimited numeric value, even a macro; \(\langle\)_numeric macro_\(\rangle\) means a macro that contains a fractional number; _macro_ is a valid macro name, i.e. a backslash followed by letters, or anything else that can receive a definition. A _direction_ of a vector is its versor; the angle of a vector is the angle between the vector and the positive \(x\) axis in counterclockwise direction, as it is used in the Euler formula \(\vec{v}=M\mathrm{e}^{\mathrm{i}\varphi}\). Figure 9: Geometrical construction to prove Pitagora’s theorem 15. General curves can be drawn with the pict2e macro \curve but it requires the specification of the third-order Bezier-spline control points; sometimes it's better to be very specific with the control points and there is no other means to do a decent graph; sometimes the curves to be drawn are not so tricky and a general set of macros can be defined so as to compute the control points, while letting the user specify only the nodes through which the curve must pass, and the tangent direction of the curve in such nodes. Such commands are the following: * \Curve draws a sequence of arcs as explained above, using third order (cubic) Bezier splines. The starred version of this command fills the internal part of the curve with the current color; if the last arc finishes where the fist arc starts, it is clear what is the interior; if it does not, the driver (not the code of this package, but the driver between this code and the physical representation on paper or screen) assumes a straight line closure of the whole path. The syntax offers several variants but it is substantially the following: \Curve(\(\langle\)_node_\(\rangle\))<\(\langle\)_direction_\(\rangle\)>... (\(\langle\)_node_\(\rangle\))<\(\langle\)_direction_\(\rangle\)>... (\(\langle\)_node_\(\rangle\))<\(\langle\)_direction_\(\rangle\)>... \(\langle\)_direction_\(\rangle\)>[\(\langle\)_new direction_\(\rangle\)] (\(\langle\)_node_\(\rangle\))... See some more explanation below. * \Curve is similar to \Curve, but with second order (quadratic) Bezier splines. The starred version fills the interior with the current color. Its syntax si similar to that of \Curve. *\CurveBetween draws a single cubic Bezier spline between two given nodes and with two given direction vectors. This macro is similar to \Curve, but it is used to draw a third order Bezier curve between just two nodes and require just two directions *\CEeizerBetween draws a single cubic Bezier spline between two given nodes, with two given direction versors along which the control node distances are specified. This is the most general macro (rather difficult to use) with which not only the arc end points are specified but also the control nodes coordinates are given. It is similar to \CurveBetween but the control points of the single arc can be specified; the arc is perfect, but the syntax is more complicated. See below for examples. The main macro is \Curve and must be followed by an "unlimited" sequence of node-direction coordinates as a quadruple defined as \[\(\(\mathit{node}\)\(\mathit{coordinates})\)\(\diamond\)\(\langle\)\(\mathit{direction}\)\(\mathit{vector})\)\(\rangle\) Possibly if a sudden change of direction has to be performed (cusp) another item can be inserted after one of those quadruples in the form \[\ldots(\langle\ldots\rangle)\)\(\diamond\)\(\langle\ldots\rangle\)\(\triangleright\)\(\langle\)\(\mathit{new}\)\(\mathit{direction}\)\(\mathit{vector})\)\(\}\)\(\{\langle\ldots\rangle\)\(\diamond\)\(\langle\ldots\rangle\)\(\succ\)\(\ldots\) Sometimes it is necessary to specify the "tension" or the "looseness" of a specific Bezier arc; such tension parameters range from 0 (zero) to 4; the zero value implies a very stiff arc, as if it was a string subject to a high tension (i.e. with zero looseness); a value of 4 implies a very low tension (very high looseness), almost as if the string was not subject to any tension. In METAFONT or METAPOST language such a concept is used very often; in this package, where the Hobby algorithms are not used, the parameter value appears to mean the opposite of tension. A couple of comma separated tension values may be optionally used, they Figure 11: Coloring the inside of a closed path drawn with \Curve* Figure 10: A heart shaped curve with cusps drawn with \Curve are separated with a semicolon from the direction vector, and they apply to the arc terminating with the last node; their specification must precede any possible change of tangent according to this syntax1: Footnote 1: The tension may be specified only for cubic splines, because the quadratic ones do not use enough parameters to control the tension; not all commands for drawing cubic splines accept this optional tension specification. \(\ldots\)(_(node)_) <(_direction vector_);_(_start tension_),_(_end tension_)> (_node_) <(_direction_)> \(\ldots\) The \(\backslash\)Curve macro does not (still) have facilities for cycling the path, that is to close the path from the last specified node-direction to the first specified node-direction; but, as already mentioned, if the ending node of the last arc does not coincide with the starting node of the first arc, a straight line is assumed to join such nodes; this line does not get drawn, but with starred commands no lines are drawn because only the interior is coloured. The tangent direction need not be specified with a unit vector, although only its direction is relevant; the scaling of the specified direction vector to a unit vector is performed by the macro itself. Therefore one cannot specify the fine tuning of the curve convexity as it can be done with other programs or commands, as, for example, with METAFONT or the pgf/tikz package and environment. See figure 10 for an example. With the starred version of \Curve, instead of stroking the contour, the macro fills up the contour with the selected current color, see figure 11. Figure 12 shows a geometric construction that contains the geometric elements and symbols used to determine the parameters of a cubic spline required to draw a quarter circle. This construction contains many of the commands described so far. To show what you can do with \CurveBetween see the code and result shown in figure 13. Notice the effect of changing the directions at both or at the end nodes of a single cubic spline. The directions are conveniently expressed with unit vectors described by polar coordinates. The \CurveBetween macro is built on \CBezierBetween; this latter command is very complicated to describe and its use is reserved to experienced users; its syntax is described in the code documentation file cureve2e.pdf; the reader is encouraged to examine it in case s/he is willing to use it. A little more complicated is the use of the \GEezierBetween macro, figure 14. The directions are specified with unit vectors in polar form; the control points are specified by adding their distances from their neighbouring nodes; actually the right distance is maintained to the value 1, while the left one increases from 4 to 10. The black line corresponds to the standard \CurveBetween where the default distance is computed to trace an arc of a circle and is approximately 3.5. In figure 15 the effect of tension specification is shown. The red line corresponds to the default tension, since the tension values are not specified. The black lines correspond to the various values used in the various commands to the \Curve macro. With a tension of zero, the spline is almost coincident with the horizontal base line of the frame. Increasing the parameter value to 4.5, the curved becomes taller and taller, until it wraps itself displaying an evident loop. We would say that the value of 2 is a reasonable maximum one and that increasing that value is just to obtain special effects. \unitlength=0.007\textwidth \begin{picture}(100,90)(-50,-50) \put(-50,0){vector(1,0){100}}\put(50,1){makebox(0,0)[br]{$x$}}% \put(20,-1){makebox(0,0)[t]{$s$}}% \put(0,0){circle*{2}}put(-1,-1){makebox(0,0)[tr]{$M$}}% \legenda(12,-45){s=\overline{MP_2}=R\sin\theta}% \put(0,-50){vector(0,1){90}}% \put(1,40){makebox(0,0)[tl]{$y$}}% \put(0,-40){circle*{2}}put(1,-41){makebox(0,0)[tl]{$C$}}% \segment(0,-40)(-40,0){segment(0,-40)(40,0)% \put(-41,1){makebox(0,0)[br]{$P_1$}}\put(-40,0){circle*{2}}% \put(41,1){makebox(0,0)[bl]{$P_2$}}\put(40,0){circle*{2}}% \put(0,0){linethickness{1pt}Arc(0,-40)(40,0){90}% \segment(-40,0)(-20,20){-20,20}{circle*{2}}% \put(-20,21.5){makebox(0,0)[bl]{$C$_1$}}% \segment(40,0)(20,20){20,20}{circle*{2}}% \put(20,21.5){makebox(0,0)[bl]{$C$_2$}}% \put(0,-40){put(0,56.5685){circle*{2}}% \put(1,58){makebox(0,0)[bl]{$P$}}}% \VectorARC(0,-40)(15,-25){45}put(10,-18){makebox(0,0)[c]{$}{theta$}}% \VectorARC(40,0)(20,0){-45}put(19,5){makebox(0,0)[r]{$}{theta$}}% \VectorARC(-40,0)(-20,0){45}put(-19,5){makebox(0,0)[l]{$}{theta$}}% \put(-20,-18){makebox(0,0)[bl]{$R$}}% \put(-32,13){makebox(0,0)[bl]{$K$}}% \put(32,13){makebox(0,0)[br]{$K$}}% \end{picture} \(\theta\)\(\unitlength=0.1\textwidth \begin{picture}(10,3) \CurveBetween0,Oand10,OWithDirs1,land{1,-1} \color{red}% \CbcezierBetween0,OAnd10,OWithDirs45:1And-45:1UsingDists4And{1} \CbcezierBetween0,OAnd10,OWithDirs45:1And-45:1UsingDists6And{1} \CbcezierBetween0,OAnd10,OWithDirs45:1And-45:1UsingDists8And{1} \CbcezierBetween0,OAnd10,OWithDirs45:1And-45:1UsingDists10And{1} \CbcezierBetween0,OAnd10,OWithDirs45:1And-45:1UsingDists12And{1} \end{picture} ``` Figure 16 displays two approximations of a sine wave; Bezier splines can approximate transcendental curves, but the approximation may be a poor one, depending on the approximated curve, when few arcs are used to draw it. With arcs specified with more complicated macros the approximation is better even with a lower number of arcs. With many arcs it is Figure 14: Comparison between similar arcs drawn with \CurveBetween with the default tension values (black) and with several tension values specified (red) Figure 13: Curves between two points with different start and end slopes repeated, for example, to set them on a curved line, instead of on a straight line, as shown in figure 18. In this figure we show the code for the picture shown there. The red grid is nothing new, except that it displays the traditional \multiput used in this code, shown in a previous example, produces exactly the same result. But for what concerns the four "graphs" on the grid, it displays an alignment of black dots along the diagonal of the grid (again traditional \multiput rendered with the new version); a number of blue dots along a parabola; another number of magenta coloured dots alined along a half sine wave; a number of little green squares aligned along a \(-15\)\(\circ\) sloping line starting from the center of the grid; notice the polar values that are used as polar relative coordinate increments. A new command \xmultiput (not available with the previous versions of curve2e) is extended with respect to the original \multiput; it is defined by using some L3 functions; in particular the cycling counter is accessible to the LaTeX commands and it is stepped up from 1 to the value specified in the proper command argument (in the original command it starts from that value and is stepped down to zero). See the figure on page 19 to inspect its usage. It is important to notice that if the command\rotatebox has to be used, as in the example of figure 19, the package graphicx should be also loaded, because curve2e does not load it. Th \xmultiput syntax is the is similar to that of \multiput but besides the stepping up or down of the iteration counter, it can access and modify certain internal with the commands that appear in the \(\mathit{handler}\) argument. Actually this \(\langle\mathit{handler}\rangle\) is available also with \multiput. In both cases the handler can be defined to modify some internals, including the iteration counter only for \xmultipot, but also the \R and \D internals; \R contains the coordinates where to put the \(\langle\mathit{object}\rangle\), while \D, if set, contains the angle of rotation of the object. The code and picture examples Figure 18: Some examples of the \(\langle\mathit{handler}\rangle\) optional argument in figures 18 and 19 show some examples of usage through its _handler_) code.. 17. This implementation of curve2e includes an extension to package xfp, in the sense that adds three more L3 commands: \ftptest, \fpdownhile, \fpwhiledo to the two already contained and documented in the latter package. The syntax of such new commands is the following \ftptest{_test_}{_true_}{_false_} \ftpdownhile{_test_}{_operations_to_be_repeated_} \ftpwhiledo{_test_}{_operations_to_be_repeated_} The macro \ftptest requires two further arguments that contain what to do if the _test_ is true, and what to do if the _test_ is false. The _test_ is a logical expressions that connects math relation expressions, even floating point ones, by means of _logical operators_; such operators are |1, &&, and!, respectively for OR, AND, NOT; math relation expressions contain relation operators, even negated ones: for example!< means "not lower than", which is equivalent to "equal or grater than", i.e. =>. The logical expression is parsed left to right and normal parentheses may be used to alter this sequence. The logical operators work also between logical variables, therefore the _test_) may contain an interesting mixture of relation and logical operators. Before using \fpdownhile and \fpwhiledo, the arguments of _test_ depends on must be set so that the test is true; during the execution of the _operations to be repeated_) there must be some setting that eventually renders the _test_) false. The user should pay attention to set the elements that _test_) depends on, because the risk is to enter an infinite loop and end up with some error message stating that the working memory of the program is full. Notice that \fpdownhile first puts the _operations to be repeated_) into the work flow then checks the _test_) and possibly repeats the cycle; on the opposite, \fpwhiledo first checks the _test_) then possibly inserts Figure 19: Usage example of the \xmmultinput command the (_operations to be repeated_) and cycles. Evidently with the same \(\langle\mathit{test}\rangle\) the two while cycles produce different results with a little, but important difference: if the input data are macros defined by previous computations, there is no guarantee that the \(\langle\mathit{test}\rangle\) is initially true; if it sis false, fpwhiledo does not do anything, while \(\langle\)fpdowhile executes one cycle and produces in the output stream something that might be nonsense. Cycles done with \(\langle\)fpwhiledo should be safer and should be preferred. Nevertheless such commands are very useful also for drawing graphics; the \(\langle\)xmultiput command already makes use of such L3 functions. As an example of use, we show how to plot a mathematical function expressed in parametric form: \[\begin{cases}x=f_{1}(t)\\ y=f_{2}(t)\end{cases}\] The plot is executed with a piecewise linear approximation of the curve; if the \(t\) steps are sufficiently small, the plot turns out to be very nice; here we show an example where we plot a Lissajous curve with two sinusoids of different periods. We start by defining the Lissajous function with arguments to specify the parameter \(t\), the sinusoid amplitudes \(A_{1},A_{2}\), the respective "frequencies", by means of integer multiples of a unit pulsation, \(N_{1},N_{2}\), and the initial phases \(\phi_{1},\phi_{2}\) of such sinusoids. It is better to keep apart the input of the curve coefficients from the actual curve argument/parameter and output point coordinates: \def\LissajousCoefs#1,#2,#3,#4,#5,#6!{\% \edef\LAu{#1}\edef\LNu{#2}\edef\LFu{#3}\% \edef\LAd{#4}\edef\LNd{#5}\edef\LFd{#6}\} \def\LissajousCode#1#2{\% \edef\X{\fpeval{\LAu*cosd(\LNu*#1+\LFu)}}\% \edefY{\fpeval{\LAd*cosd(\LNd*#1+\LFd)}}\% \CopyVect\X,\Y to#2\ignorespaces} As it is shown, the coefficients are specified as a comma separated list; the! list terminator is taken care by the actual drawing command. Then the curve drawing command requires the coefficient specification only the first time it is used; some messages2 are output if the coefficients have been "forgotten". Footnote 2: Here it would be better to have available a “Macro Error” message; such a macro is not available, but it would be possible to define it by means of the \GenericError macro provided by the LaTeX2e kernel. Here we skip this definition in order to avoid overloading this documentation with such details. \NewDocumentCommand\Lissajous{m o m}{\IfValueTF{#2}{\LissajousCoefs#2!\relax} \LissajousCode{#1}{\#3}\% \Lissname LAu}endcsname \LissajousCode{#1}{\#3}\% \else\PackageError{curve2e}%The syntax is the following: \Lissajous{\(\langle\mathit{in}\rangle\}\,\texttt{[}\langle A_{1}\rangle,\langle N_{1} \rangle,\langle\phi_{1}\rangle,\langle A_{2}\rangle,\langle N_{2}\rangle,\langle \phi_{2}\rangle\texttt{[}\langle P_{\mathrm{out}}\rangle\] where \(\langle P_{\mathrm{out}}\rangle\) is a macro that gets defined with the cartesian coordinates of the computed output point. Arguments \(\langle\mathit{in}\rangle\) (the \(t\) parameter) and \(\langle P_{\mathrm{out}}\rangle\) (the comput coordinates) need not be enclosed within braces if they are given as macros; actually the code shown in figure 20 shows such procedure that renders the input code simpler to read. After this definition the diagram is plotted in figure 20. For the independent variable \(t\), the parameter of the Lissajous parametric equations, it is better to work with degrees instead of radians, and with integer numbers, so that the whole range from \(0^{\circ}\) to \(360^{\circ}\) is certainly spanned. Notice the braces that include the code for the Lissajous diagram; they may be useful to render that group suitable to be \put somewhere else than with its center at the origin of the canvas axes, and/or to be used as the second argument of a \rotatebox{\(\langle\mathit{angle}\rangle\)} command so as to rotate the whole diagram. 18. Another useful application of \fpdowhile is the following: when making a diagram the axes should get suitable labeled ticks in order to show the graduations; the label of each tick should lay close to the axis on the other side than the tick. It is also necessary to know if the axis to be marked is horizontal or vertical, since in the former case each tick is vertical, while in the latter case it is horizontal. The example in figure 27 shows both the code and its usage. The syntax of the \Tbox macro is the following. \Tbox(\langle\mathit{coordinates}\rangle\}\,\texttt{[}\langle\mathit{reference} \rangle\texttt{]}\,\texttt{[}\langle\mathit{label}\rangle\texttt{]}\,\texttt{[} \langle\mathit{size}\rangle\texttt{]}\,\texttt{<}\langle\mathit{direction} \rangle\texttt{>}\] where \(\langle\mathit{coordinates}\rangle\) indicates the position of the tick base along its axis; \(\langle\mathit{reference}\rangle\) is a letter, either \(\mathtt{t}\) (if the axis is on top of the label) or \(\mathtt{b}\)(if Figure 20: A Lissajous diagram <centering<unitlength=0.00%linewidth <begin{picture}(100,70)(-50,-10)% <AutoGrid <thickness <VECTOR(-50,0)(50,0)>%box(50,0)[br]{x}[Opt]% <VECTOR(0,0)(0,60)>%box(0,60)[tl]{y}[Opt]% % {\def\Coord{-40}% <fpdowhile{\Coord<=40}{\}def\X{\fpeval{round(\Coord/20,1)}}% <Tbox(\Coord,0)[t]{\X}[1.5mm]<V>\def\Coord{\fpeval{\Coord+10}}}% % <def\Coord{10}% <fpdowhile{\Coord<=50}{\}def\Y{\fpeval{round(\Coord/20,1)}}% <Tbox(0,\Coord)[r]{\Y}[1.5mm]<H>\def\Coord{\fpeval{\Coord+10}}}% >% % <{\color{blue}\}linethickness{1.5pt}% <Curve(-40,0)<1,0>(0,20)<45:1>% Parabola: y=0.25(x_2)^2 <Curve(0,20)<1,0>(20,0)<0,-1>% Quarter circle: x^2+y^2=1 <Curve(20,0)<0,1>(40,34.64)<49:1>% Hyperbola:x^2-y^=1 <thinlines <Dashline(0,0)(45,45){2}% asymptote <end{picture} Figure 21: The code to draw a diagram with labeled axes Remarks In spite of the relative simplicity of the macros contained in this package, the described macros, as well as the original ones included in the pict2e package, allow to produce fine drawings that were unconceivable with the original LaTeX picture environment. Leslie Lamport himself announced an extension to his environment when LaTeX\(2_{\overline{e}}\) was first released in 1994; in the ltnews newsletter of December 2003, the first implementation of Lamport's extension was announced; the first version of this package curve2e was issued in 2006. It was time to have a better drawing environment; this package is a simple attempt to follow the initial path while further extending the drawing facilities. There are other packages in the ctan archives that deal with tracing curves of various kinds. PSTricks and pgf/tikz are the most powerful ones. And they are becoming the standard for computer drawing. Their documentation is huge and the multitude of extra modules to perform special tasks is countless. Therefore they are difficult to use; when the user gets used to their particular syntax and got sufficient familiarity with several modules, s/he can use these bundles very comfortably. This difficulty in becoming a TikZ or PS expert is why I think a simpler drawing machinery should be appreciated. I admit it: I like the _picture_ environment; and I like to deal with simple codes so as to create my own macros. But there is also curves that is intended to draw almost anything by using little dots or other symbols partially superimposed to one another. It uses only quadratic Bezier curves and the curve tracing is easy by specifying only the curve nodes, without specifying the control nodes; with a suitable package option, it is possible to reduce the memory usage by using short straight segments drawn with the PostScript facilities offered by the dvips driver. Another package, ebezier performs about the same as curve2e but draws its Bezier curves by using little dots partially superimposed to one another. The documentation is quite interesting since it explains very clearly what exactly are the Bezier splines. Apparently ebezier should be used only for DVI output without recourse to PostScript or PDF machinery. The picture package extends the performance of the _picture_ environment (extended with pict2e) by accepting coordinates and lengths in real absolute dimensions, not only as multiples of unitlength; it provides commands to extend that functionality to other packages. In certain circumstances it may be very useful. Package xpicture builds over the _picture_ LaTeX environment so as to allow to draw the usual curves that are part of an introductory analytic geometry course; lines, circles, parabolas, ellipses, hyperbolas, and polynomials; the syntax is rather comfortable, although it is not a simple extension of the _picture_ own syntax; for all these curves it uses the quadratic Bezier splines. Package hobby extends the cubic Bezier spline handling with the algorithms <NAME> created for METAFONT and METAPOST. But by now this package interfaces very well with tikz; it has not (yet) been adapted to the common _picture_ environment extended with pict2e, and, why not, with curve2e. If you are interested in further extensions of curve2e, besides creating yourself the macros you need, examine the euclideangeometry package; I created it in order to have available further functionalities useful to deal with more complicated geometrical constructions. Another small extension is graphpaper by which users can produce themselves drawing paper with bilinear coordinates, semi-logarithmic and bi-logarithmic coordinates, polar linear or semilogarithmic coordinates, and Smith charts. They are an extension chain of the packages that extend the picture environment: graphpaper calls euclideangeometry which calls curve2e which calls pict2e. I find all this very useful. Of corse these packages and their documentation are all contained in TeX Live. I am about to complete a book on electromagnetism and electronic circuit theory: it contains some 300 drawings, diagrams, electronic circuits. I created them with curve2e and some macros based on this picture extension package. The graphics of my book are pretty nice, and I am sure that a professional technical artist can draw better ones, but such an artist would be very expensive and the process would require a lot of time to correct, modify, add details, and so on, while doing things by oneself is certainly a better solution. Packages tikz/pgfplots and PStricks? Certainly they are very good and much more powerful, but, besides being sort of difficult to learn to use, they require a lot of working memory and more often than not I ran out of computer memory. ## 5 Acknowledgements I wish to express my deepest thanks to <NAME> who spotted some errors and very kindly submitted them to me so that I was able to correct them. I collaborated extensively with <NAME> in order to implement a better real long division so as to get correctly the quotient fractional part and to avoid as much as possible any numeric overflow; many Josef's ideas are incorporated in the macro that was implemented in the previous version of this package, although the macro used by Josef was slightly different. Both versions aim/aimed at a better accuracy and at widening the operand ranges. In this version of curve2e I abandoned our long division macro, and substituted it with the floating point division provided by the xfp package functionalities that are now part of the TeX kernel. <NAME> spotted a fault in the kernel definition of \linethickness that heavily influenced also curve2e; see in the code documentation curve2e.pdf file. Many thanks to <NAME> who spotted a sneaky bug in the updated \Arc macro; for arcs not wider that \(180^{\circ}\) it worked properly, while for larger angle apertures it produced syntax errors. It was just a typo, but very sneaky. Thanks also to <NAME> and <NAME> who suggested a small but crucial modification in order to have curve2e work smoothly also with XeTeX (XeLaTeX). Actually if pict2e, version 0.2x or later, dated 2009/08/05 or later, is being used, such modification is not necessary any more, but it is true that it becomes imperative when legacy versions were used. Many thanks also to <NAME> who spotted an inconsistency in the design of vectors with PostScript style arrow tips with large line width settings, that did not show up with LaTeX styled ones.
polyphony-http
ruby
Ruby
Polyphony - Easy Concurrency for Ruby === [![Gem Version](https://badge.fury.io/rb/polyphony-http.svg)](http://rubygems.org/gems/polyphony-http) [![Modulation Test](https://github.com/digital-fabric/polyphony-http/workflows/Tests/badge.svg)](https://github.com/digital-fabric/polyphony-http/actions?query=workflow%3ATests) [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/digital-fabric/polyphony-http/blob/master/LICENSE) [DOCS](https://dfab.gitbook.io/polyphony) | [EXAMPLES](examples) > Polyphony | pəˈlɪf(ə)ni | *Music* - the style of simultaneously combining a number of parts, each forming an individual melody and harmonizing with each other. What is Polyphony --- Polyphony is a library for building concurrent applications in Ruby. Polyphony harnesses the power of [Ruby fibers](https://ruby-doc.org/core-2.5.1/Fiber.html) to provide a cooperative, sequential coprocess-based concurrency model. Under the hood, Polyphony uses [libev](https://github.com/enki/libev) as a high-performance event reactor that provides timers, I/O watchers and other asynchronous event primitives. Polyphony makes it possible to use normal Ruby built-in classes like `IO`, and `Socket` in a concurrent fashion without having to resort to threads. Polyphony takes care of context-switching automatically whenever a blocking call like `Socket#accept` or `IO#read` is issued. Features --- * **Full-blown, integrated, high-performance HTTP 1 / HTTP 2 / WebSocket server with TLS/SSL termination, automatic ALPN protocol selection, and body streaming**. * Co-operative scheduling of concurrent tasks using Ruby fibers. * High-performance event reactor for handling I/O events and timers. * Natural, sequential programming style that makes it easy to reason about concurrent code. * Abstractions and constructs for controlling the execution of concurrent code: coprocesses, supervisors, cancel scopes, throttling, resource pools etc. * Code can use native networking classes and libraries, growing support for third-party gems such as `pg` and `redis`. * Use stdlib classes such as `TCPServer`, `TCPSocket` and * HTTP 1 / HTTP 2 client agent with persistent connections. * Competitive performance and scalability characteristics, in terms of both throughput and memory consumption. Prior Art --- Polyphony draws inspiration from the following, in no particular order: * [nio4r](https://github.com/socketry/nio4r/) and [async](https://github.com/socketry/async) (Polyphony's C-extension code is largely a spinoff of [nio4r's](https://github.com/socketry/nio4r/tree/master/ext)) * [EventMachine](https://github.com/eventmachine/eventmachine) * [Trio](https://trio.readthedocs.io/) * [Erlang supervisors](http://erlang.org/doc/man/supervisor.html) (and actually, Erlang in general) Documentation --- The complete documentation for Polyphony could be found on the [Polyphony website](https://dfab.gitbook.io/polyphony).
json-tabularize
readthedoc
Unknown
json_tabularize Release 1.0.3 <NAME> Jun 02, 2022 CONTENTS 1.1 installatio... 3 1.2 command lin... 3 i ii json_tabularize, Release 1.0.3 Get arbitrarily nested JSON into tabular format This is a tool for converting many different JSON formats into tabular JSON. You can then use other tools to turn those into nice things like HTML, CSV, etc. Here’s a motivating example of where to use this: >>> bball = {'leagues': [ { 'league': 'American', 'teams': [ { 'name': 'foo', 'players': [ ] }, { 'name': 'bar', 'players': [ ] } ], }, { 'league': 'National', 'teams': [ { 'name': 'baz', 'players': [ ] } ] } ]} This JSON has a regular structure, and it would be reasonable to try converting this into a table. However, algorithms like normalize_json from pandas can’t fully normalize it, but rather puts everything in one row: >>> import pandas as pd >>> pd.json_normalize(bball, ['leagues', 'teams', 'players']) name hits at-bats 0 alice [1] [3] 1 carol [1] [2] 2 bob [2] [3] This is pretty good, but it results in loss of information, and you have to spend some time troubleshooting and reading the documentation to be able to use it. Let’s try using my algorithm: >>> pd.DataFrame(build_tab(bball)) leagues.teams.players.name leagues.league leagues.teams.name leagues.teams.players. ˓→hits leagues.teams.players.at-bats (continues on next page) json_tabularize, Release 1.0.3 (continued from previous page) 0 alice American foo ␣ ˓→1 3 1 carol American bar ␣ ˓→1 2 2 bob National baz ␣ ˓→2 3 All the information has been retained. Note that pandas is NOT a dependency of this package. Another advantage of this algorithm is that it recognizes all of the following formats as tables: >>> {'a': [1, 2], 'b': ['a', 'b']} # this is a table >>> [{'a': 1, 'b': 'a'}, {'a': 2, 'b': 'b'}] # also a table >>> [[1, 'a'], [2, 'b']] # yep, still a table The program infers table formats without user input. Limitations: 1. This algorithm only works on JSON that has one or fewer possible tables within it. 2. All arrays must be lists. 3. This won’t recognize a single flat list or dict as a table. 4. You must have GenSON installed. In conclusion, you should still use pandas for the 95+% of “tabularizable” real-world JSON that can be fully normalized into a table by pandas.read_json or pandas.json_normalize, but this package exists for those other rare cases. Note: This project is under active development. Features to be added soon: 1. Tools for getting more than one table out of the same JSON document. 2. Tools for converting the tabular JSON directly into other formats. CHAPTER ONE TABLE OF CONTENTS 1.1 installation Probably the easiest way to install this package is using pip.: C:\Users\mjols\Python39>python -m pip install json_tabularize 1.2 command line json_tabularize is most conveniently used from the command line. You can run the package directly like so: C:/Users/mjols/Python39> more baseball2.json [ {"name": "foo", "players": [ {"name": "alice", "hits": [3, 4, 2, 5], "at-bats": [4, 3, 3, 6]}, {"name": "bob", "hits": [-2, 0, 4, 6], "at-bats": [1, 3, 5, 6]} ] }, {"name": "bar", "players": [ {"name": "carol", "hits": [7, 3, 0, 5], "at-bats": [8, 4, 6, 6]}, {"name": "dave", "hits": [1, 0, 4, 10], "at-bats": [1, 3, 6, 11]} ] } ] C:/Users/mjols/Python39> python -m json_tabularize baseball2.json [ (continues on next page) json_tabularize, Release 1.0.3 (continued from previous page) { "players.name": "alice", "name": "foo", "players.hits": 3, "players.at-bats": 4 }, { "players.name": "alice", "name": "foo", "players.hits": 4, "players.at-bats": 3 }, { "players.name": "alice", "name": "foo", "players.hits": 2, "players.at-bats": 3 }, { "players.name": "alice", "name": "foo", "players.hits": 5, "players.at-bats": 6 }, { "players.name": "bob", "name": "foo", "players.hits": -2, "players.at-bats": 1 }, { "players.name": "bob", "name": "foo", "players.hits": 0, "players.at-bats": 3 }, { "players.name": "bob", "name": "foo", "players.hits": 4, "players.at-bats": 5 }, { "players.name": "bob", "name": "foo", "players.hits": 6, "players.at-bats": 6 }, { "players.name": "carol", "name": "bar", "players.hits": 7, (continues on next page) 4 Chapter 1. Table of Contents json_tabularize, Release 1.0.3 (continued from previous page) "players.at-bats": 8 }, { "players.name": "carol", "name": "bar", "players.hits": 3, "players.at-bats": 4 }, { "players.name": "carol", "name": "bar", "players.hits": 0, "players.at-bats": 6 }, { "players.name": "carol", "name": "bar", "players.hits": 5, "players.at-bats": 6 }, { "players.name": "dave", "name": "bar", "players.hits": 1, "players.at-bats": 1 }, { "players.name": "dave", "name": "bar", "players.hits": 0, "players.at-bats": 3 }, { "players.name": "dave", "name": "bar", "players.hits": 4, "players.at-bats": 6 }, { "players.name": "dave", "name": "bar", "players.hits": 10, "players.at-bats": 11 } ] json_tabularize, Release 1.0.3 6 Chapter 1. Table of Contents CHAPTER TWO INDICES AND TABLES • genindex • modindex • search 7
stuart-client-ruby
ruby
Ruby
[![Codeship Status for StuartApp/stuart-client-ruby](https://app.codeship.com/projects/bacc9100-b159-0137-6e98-0e2ebd2815ea/status?branch=master)](https://app.codeship.com/projects/363050) Stuart Ruby Client === For a complete documentation of all endpoints offered by the Stuart API, you can visit [Stuart API documentation](https://api-docs.stuart.com/). Install --- ``` $ gem install stuart-client-ruby ``` Usage --- ### Initialize HTTP client ``` require 'stuart-client-ruby' environment = [Stuart](/gems/stuart-client-ruby/Stuart "Stuart (module)")::[Infrastructure](/gems/stuart-client-ruby/Stuart/Infrastructure "Stuart::Infrastructure (module)")::[Environment](/gems/stuart-client-ruby/Stuart/Infrastructure/Environment "Stuart::Infrastructure::Environment (class)")::[SANDBOX](/gems/stuart-client-ruby/Stuart/Infrastructure/Environment#SANDBOX-constant "Stuart::Infrastructure::Environment::SANDBOX (constant)") api_client_id = 'c6058849d0a056fc743203acb8e6a850dad103485c3edc51b16a9260cc7a7689' # can be found here: https://admin.sandbox.stuart.com/client/api api_client_secret = '<KEY>' # can be found here: https://admin.sandbox.stuart.com/client/api auth = [Stuart](/gems/stuart-client-ruby/Stuart "Stuart (module)")::[Infrastructure](/gems/stuart-client-ruby/Stuart/Infrastructure "Stuart::Infrastructure (module)")::[Authenticator](/gems/stuart-client-ruby/Stuart/Infrastructure/Authenticator "Stuart::Infrastructure::Authenticator (class)").[new](/gems/stuart-client-ruby/Stuart/Infrastructure/Authenticator#initialize-instance_method "Stuart::Infrastructure::Authenticator#initialize (method)")(environment, api_client_id, api_client_secret) http_client = [Stuart](/gems/stuart-client-ruby/Stuart "Stuart (module)")::[Infrastructure](/gems/stuart-client-ruby/Stuart/Infrastructure "Stuart::Infrastructure (module)")::[HttpClient](/gems/stuart-client-ruby/Stuart/Infrastructure/HttpClient "Stuart::Infrastructure::HttpClient (class)").[new](/gems/stuart-client-ruby/Stuart/Infrastructure/HttpClient#initialize-instance_method "Stuart::Infrastructure::HttpClient#initialize (method)")(auth) ``` ### Custom requests #### Example: create a job ``` job = { job: { transport_type: "bike", pickups: [ { address: "46 Boulevard Barbès, 75018 Paris", comment: "Wait outside for an employee to come.", contact: { firstname: "Martin", lastname: "Pont", phone: "+33698348756", company: "KFC Paris Barbès" } } ], dropoffs: [ { address: "156 rue de Charonne, 75011 Paris", package_description: "Red packet.", client_reference: "12345678ABCDE", # must be unique comment: "code: 3492B. 3e étage droite. Sonner à Durand.", contact: { firstname: "Alex", lastname: "Durand", phone: "+33634981209", company: "Durand associates." } } ] } } http_client.perform_post '/v2/jobs', JSON.generate(job) ``` #### Example: get a list of jobs ``` http_client.perform_get('/v2/jobs') ``` ### Release process 1. Review the Gem version in lib/stuart-client-ruby/version.rb 2. Create and publish a Git tag with the version defined in lib/stuart-client-ruby/version.rb Example: ``` git tag v1.2.0-rc.1 git push origin --tags ``` 3. The workflow [workflows/publish.yml](https://github.com/StuartApp/stuart-client-ruby/actions/workflows/publish.yml) should start and publish the new version to Rubygems <https://rubygems.org/gems/stuart-client-ruby>
configurable-react-scripts
npm
JavaScript
Configurable react-scripts === Latest version of original react-scripts: 0.9.0 ⚠️ Warning --- This is **not** a fork of [`create-react-app`](https://github.com/facebookincubator/create-react-app). It's just a fork of `react-scripts` with possible modification of webpack config. Why I've built this? --- Create-react-app is great. It is so great I've migrated most of my apps from different boilerplates. But I've always find something I missed. In first app, I've needed support of CSS-modules, so I've created my custom react-scripts with scope `@svrcekmichal/react-scripts`. Everything was great for a while, until I've needed to add LESS, so I published new version. In second app I've been using Relay, so I've added Relay to my package. As you can see, it started growing, but I've added it and pretend everything is fine. In third app I wanted to test styled-components and I wanted to add custom babel plugin fore better react-devtools. That's the point where everything in me broken. I've started to search for better alternatives and opened npms.io. I found 164+ packages with or withous scope which handled most of the time same stuff. LESS, SASS, CSS-modules, css variables etc. This is all stuff which can be added with few lines of code to webpack config. And here I am, and you are here too. Probably with the same problem. ☢ DANGER ☢ --- There is multiple reasons why not to do it this way! This solution was proposed multiple times before, so I link few PRs where is everything better explained. [#99](https://github.com/facebookincubator/create-react-app/issues/99) [#145](https://github.com/facebookincubator/create-react-app/issues/145) [#460](https://github.com/facebookincubator/create-react-app/issues/460) [#481](https://github.com/facebookincubator/create-react-app/issues/481) [#1060](https://github.com/facebookincubator/create-react-app/issues/1060) [#1103](https://github.com/facebookincubator/create-react-app/issues/1103) [#1111](https://github.com/facebookincubator/create-react-app/issues/1111) As [@gaearon](https://github.com/gaearon) mentioned multiple times there, it's not good idea to extend it. From my point of view, I'm giving you gun, so try not to shot yourself, because probably nobody will help you. When you modify something, be completely sure what you doing! Instalation --- ``` create-react-app my-app --scripts-version configurable-react-scripts ``` Usage --- To modify webpack config create `webpack.config.js` file in your project directory. Add following body and modify whatever you want inside function body. First argument is original config from `react-scripts`, second is for target only dev or only prod features. Don't forget to return modified config! ``` module.exports = function(webpackConfig, isDevelopment) {   //here you can modify webpack config   return webpackConfig;} ``` Examples --- I've added example with Relay. It can be seen in `examples` folder. If you can, I will accept any PR with features like LESS, SASS, CSS-modules etc. Readme --- ### Keywords none
networkDynamic
cran
R
Package ‘networkDynamic’ February 16, 2023 Version 0.11.3 Date 2023-02-15 Title Dynamic Extensions for Network Objects Type Package Depends R (>= 3.0.0), network (>= 1.17.0) Imports statnet.common, methods, networkLite Suggests testthat LinkingTo network Description Simple interface routines to facilitate the handling of network objects with complex in- tertemporal data. This is a part of the ``statnet'' suite of packages for network analysis. License GPL-3 LazyLoad yes URL https://statnet.org/ NeedsCompilation yes Author <NAME> [aut], <NAME> [aut], <NAME> [aut], <NAME> [aut, cre], <NAME> [ctb], <NAME> [ctb], <NAME> [ctb], <NAME> [ctb], <NAME> [ctb], <NAME> [ctb], <NAME> [ctb] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2023-02-16 08:20:02 UTC R topics documented: networkDynamic-packag... 2 activat... 3 activity.attribut... 7 add.method... 8 add.vertices.activ... 10 adjust.activit... 12 age.a... 13 as.data.frame.networkDynami... 15 as.network.networkDynami... 17 as.networkDynami... 18 attribute.activity.function... 19 cls33_10_16_9... 25 delete.activit... 27 duration.matri... 28 get.dyads.activ... 30 get.network... 31 get.timing.inf... 33 is.activ... 35 nd_test_net... 37 net.obs.perio... 38 network.collaps... 39 network.dynamic.chec... 42 network.extension... 43 network.extrac... 46 networkDynami... 49 Newcom... 53 persistent.id... 54 print.networkDynami... 58 read.so... 59 reconcile.activit... 60 spells.overla... 61 when.vertex.attrs.matc... 63 windsurfer... 64 networkDynamic-package Dynamic Extensions for Network Objects Description Simple interface routines to facilitate the handling of dynamic network objects with different types of temporal data. This allows the user to create, store and query networks that change over time. Changes include edges that form and dissolve over time, and vertices that enter or leave the network. The package also includes support for defining and querying temporally changing attributes of vertices, edges, and network properties. Details Package: networkDynamic Type: Package Version: 0.7 Date: 2014-09-25 Depends: network License: GPL-3 LazyLoad: yes The networkDynamic package provides support for a simple family of dynamic extensions to the network class; these employ the standard network attribute functionality (and hence the resulting objects are still compatible with all conventional routines), but greatly facilitate the practical storage, manipulation and query of dynamic network data. The basis for the dynamic extensions is described in activity.attribute. Dynamic attributese are explained in attribute.activity.functions. Id systems which are persistent throughout manipulations and changes in network size are explained in persistent.ids. Other core routines can be found in the links below. Additional example data sets can be found in the networkDynamicData package. Author(s) Originally created by <NAME> <<EMAIL>>, Current Maintainer: <NAME> <EMAIL> Contributions from: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, StevenGoodreau <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL> <NAME> <<EMAIL>> With support from the statnet team https://statnet.org See Also activity.attribute, activate, is.active, network.extract, network.extensions network activate Dynamic Activation and Inactivation of Edges and Vertices Description activate and deactivate set spells of activity and inactivity respectively for elements (edges and vertices) in a dynamic network. Usage activate.edges(x, onset = NULL, terminus = NULL, length = NULL, at = NULL, e = seq_along(x$mel)) activate.vertices(x, onset = NULL, terminus = NULL, length = NULL, at = NULL, v = seq_len(network.size(x))) deactivate.edges(x, onset = NULL, terminus = NULL, length = NULL, at = NULL, e = seq_along(x$mel)) deactivate.vertices(x, onset = NULL, terminus = NULL, length = NULL, at = NULL, v = seq_len(network.size(x)), deactivate.edges = FALSE) Arguments x an object of class network. onset an optional vector of timepoints that specifies the starts of the interval(s). This must be accompanied by one of terminus or length. terminus an optional vector of timepoints that specifies the ends of the interval(s). This must be accompanied by one of onset or length. length an optional vector of interval lengths for the interval(s). This must be accompa- nied by one of onset or terminus. at optional, one or more time points to be activated. e optional, one or more IDs indicating edges to be modified. Ids can be repeated to indicate multiple time values per element. v optional, one or more IDs indicating vertices to be modified. Ids can be repeated to indicate multiple time values per element. deactivate.edges optional, TRUE setting will automatically deactivate all the edges associated with the vertex being deactivated Details An element in a dynamically extended network class is considered to be either “active” or “inac- tive” at any point in time, with the substantive meaning of “activity” determined by the specific application context. The activate and deactivate functions provide an interface for controlling the state of the elements in a dynamic network. activate.edges and activate.vertices have identical behavior, except for the elements they modify (the same is true for the deactivate.* functions). There are several ways to specify the activity spell, and the general syntax rules are described at activity.attribute. Activity can be set for a single time point, using either at, or by setting onset=terminus. Activity can be set for an interval [onset,terminus), using a valid combination of the onset, terminus and length attributes. This allows for a wide range of options when specifying spells, but a correct specification must use only one of these forms: at onset and terminus onset and length terminus and length or, you can provide no timing information If provided with no timing information, the element is activated/deactivated from -Inf to Inf. The specified interval spans the period from the onset (inclusive) to the terminus (exclusive), so [onset,terminus). There are some special behaviors associated with the arguments Inf and -Inf. • The open-ended interval c(-Inf,x) includes -Inf. For consistency, we also allow the open- ended interval c(x, Inf) to include Inf. Thus [onset, terminus) will be interpreted as [onset, terminus] when terminus = Inf. • The arguments Inf or -Inf are only valid when used to specify an interval, they can not be used to specify status at a time point using at. In addition, they cannot be paired with themselves in a call. That is, both (Inf,Inf) and (-Inf,-Inf) are not valid specifications for any spell. • Both deactivate.*(x) and deactivate.*(x, -Inf, Inf) create the null spell – specify- ing inactivity over the entire time span. Note that by convention the null spell is stored as (Inf,Inf). Calling the activation/deactivation functions with a vector of spell modifiers and a vector of ele- ments to be modified (for example, at=c(1,3,5 7), v=c(1:4)) allows multiple elements in the network to be activated/deactivated simultaneously (note, not multiple spells for a single element). The spell modifiers are applied sequentially to the selected elements. If the length of the spell vec- tor is less than the number of elements, the spell modifiers are recycled as needed. When multiple network elements are activated in a single call, the spell modifiers must all be of one type, either at, or a valid mix of onset, terminus and length. The activate.* and deactivate.* functions in general modify spells in similar, if opposite, ways. However, there are some behaviors that are specific to each function. • Effects on an element that has no existing activity attributes. – For activate: the element is marked as being inactive before the onset time, then active for the specified spell, then inactive from the terminus on. – For deactivate: the element is marked as being active before the onset time, then inactive for the specified spell, then active from the terminus on (i.e., the opposite of activate.*. • Effects of the at specification. – For activate: the element is activated at that time point. – For deactivate: the element is deactivated at the time point, but only if the time point is currently activated as a 0-length spell. Currently, there is no support for activating multiple spells for a single element in a single call. To activate 2 spells for a node, for example, one must call activate.vertices twice. It is advisable to remove duplicate edges or vertices from the e or v input vectors. Edge/vertex activity is tracked through an attribute called (eponymously) “active”, and which is explained in more detail under activity.attribute. This may be modified or otherwise accessed using standard class methods (e.g., get.edge.attribute), as well as the specialized methods described here. Value None. (But all four commands modify their arguments as a side-effect.) Note This function may not be entirely stable in the long run, since it makes explicit reference to internal elements of the network object; some syntactic changes could occur in the future. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> References ~put references to the literature/web site here ~ See Also is.active Examples triangle <- network.initialize(3) # create a toy network add.edge(triangle,1,2) # add an edge between vertices 1 and 2 add.edge(triangle,2,3) # add more edges add.edge(triangle,3,1) # turn on all edges at time 1 only (0 length spell) activate.edges(triangle,at=1) # activate edge (1,2) from t=2 to t=3 activate.edges(triangle,onset=2, terminus=3, e=get.edgeIDs(triangle,v=1,alter=2)) # activate edge (2,3) from t=4 for 2 time lengths activate.edges(triangle,onset=4, length=2, e=get.edgeIDs(triangle,v=2,alter=3)) deactivate.edges(triangle, at=2, e=1) # does not work since the spell is not 0-length is.active(triangle, at=2, e=1:3) deactivate.edges(triangle, e=1, onset=2, length=0.1) # this deactivates the vertex is.active(triangle, at=2, e=1:3) # this activates edges 2 and 3 at time 5 activate.edges(triangle, e=2:3, at=5) # this activates edge 1 at multiple times; deactivate.edges(triangle) activate.edges(triangle, e=c(1,1,1), at=6:8) is.active(triangle, at=6, e=1:3) is.active(triangle, at=7, e=1:3) is.active(triangle, at=8, e=1:3) # this activates vertex 1 for two spells, (0,1) and (3,4) test <- network.initialize(3) activate.vertices(test,onset=0:3,terminus=1:4,v=c(1,2,3,1)) get.vertex.activity(test, as.spellList=TRUE) activity.attribute Activity Attributes for Dynamically Extended Networks Description Dynamically extended networks are networkDynamic class objects (extensions of network objects) whose vertex and edge elements include timing information. This page describes the types of timing information currently available, and the general syntax for setting or querying this information. Details Currently, each edge and vertex in a dynamically extended network is presumed to be in one of two states at any given point in time: (“active” or “inactive”). The state of a network element (i.e., edge or vertex) is governed by an attribute with the name “active”, which is considered a reserved term for purposes of this package. The activity attribute consists of a two-column numeric matrix. Each row contains an activity spell, and the two columns encode onset and terminus times respectively. Elements are presumed inactive until the onset of their first activity spell, and are likewise presumed inactive after the termination of their last active spell. Spells are taken to span the period from the onset (inclusive) to the terminus (exclusive), so [on- set,terminus). They must be consecutive, ordered forward in time, and strictly non-overlapping. The syntax for defining or querying spells can specify either an instantaneous time point or an interval. The commands for this include at=, onset=, terminus= and length=. Any numeric values may be used in the interval specifications, including Inf and -Inf, (with some restrictions, see below). A spell with onset=-Inf represents onset censoring. A spell with terminus=Inf represents terminus censoring. Inf and -Inf cannot be used with the at specification. Similarly, onset can not be Inf and terminus can not be -Inf. The general syntax rules for specifying spells are as follows: To specify a spell as a single time point: • use the at argument, or • use onset=terminus. To specify a spell as a particular interval, one of the following combinations of onset, terminus and length is required: • onset and terminus • onset and length • terminus and length The special “null” spell is used to designate elements that are never active (i.e., have no valid activity spells). These can only be set by the deactivate function (see activity.attribute) and by convention are stored as c(Inf,Inf). “Null” spells are incompatible with other spells, and should be replaced whenever an activation enters the element’s event history. Although it is possible to access and modify the activity spells using network attribute methods (e.g., get.edge.attribute) it is not recommended, and extreme care should be taken to preserve the structure of the spell matrix. The preferred way to modify the spells of a network element is with the activate related methods. Vertices and edges with specific activity ranges can be selected using network.extensions. In addition, a number of special functions are also provided to simplify common tasks related to the active attribute (noted below). Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> See Also is.active, activate, activate.vertices,activate.edges, deactivate.vertices,deactivate.edges,network.exte Examples triangle <- network.initialize(3) # create a toy network activate.vertices(triangle,onset=1,terminus=5,v=1) activate.vertices(triangle,onset=1,terminus=10,v=2) activate.vertices(triangle,onset=4,terminus=10,v=3) deactivate.vertices(triangle,onset=2, length=2, v=1) get.vertex.activity(triangle) # vertex spells add.methods PID-aware versions of functions for adding edges and vertices to net- workDynamic objects Description The methods (add.vertices.networkDynamic, add.edge.networkDynamic, add.edges.networkDynamic) override their network-package counterparts in order to permit assigning persistent.ids to newly- added elements if the pid is defined. They can be defined by the user with the vertex.pids argu- ment, or, if not specified, a unique random id will be generated. (Note that any new values added by default to a vertex.names pid will not be numeric.) Usage ## S3 method for class 'networkDynamic' add.vertices(x, nv, vattr = NULL, last.mode = TRUE, vertex.pid = NULL, ...) ## S3 method for class 'networkDynamic' add.edges(x, tail, head, names.eval = NULL, vals.eval = NULL, edge.pid = NULL, ...) ## S3 method for class 'networkDynamic' add.edge(x, tail, head, names.eval = NULL, vals.eval = NULL, edge.check = FALSE, edge.pid = NULL, ...) Arguments x an object of class network or networkDynamic (see add.vertices in network) nv number of vertices to be added. (see add.vertices in network) vattr optionally, a list of attributes with one entry per new vertex. (see add.vertices in network), not interpreted as a dynamic attribute last.mode logical; should the new vertices be added to the last (rather than the first) mode of a bipartite network? (see add.vertices in network) vertex.pid a vector of vertex.pids to be assigned to the newly-added vertices edge.pid a vector of edge.pids to be assigned to the newly-added edges names.eval see add.edges in network), not interpreted as a dynamic attribute vals.eval see add.edges in network), not interpreted as a dynamic attribute edge.check see add.edges in network) head see add.edges in network) tail see add.edges in network) ... possible additional arguments Details The networkDynamic versions of these methods call the network versions internally. See persis- tent.ids for additional details about the PID mechanism. Value • add.verticies (invisibly) returns a reference to the network with the new vertices added. Pids will be added/created if a vertex.pid attribute is set. • add.edge and add.edges (invisibly) return a reference to the network with the new edges added. Pids will be added/created if a vertex.pid attribute is set. Note Adding edges via the extraction/replacement operators [,] bypasses the pid code and will break the edge pids defined for the network. Similarly, add.vertices.active and add.edges.active do not yet support including pids. Author(s) lxwang, skyebend, the statnet team See Also See also persistent.ids, add.vertices, add.edge, add.edges in network. Examples # add vertices while using vertex.names as pids nd <- as.networkDynamic(network.initialize(3)) set.network.attribute(nd,"vertex.pid","vertex.names") add.vertices(nd,nv=2,vertex.pid=c(4,5)) # specify pids for two new vertices network.vertex.names(nd) # peek at pids # add vertices and edges w/ auto-generated pids nd <- as.networkDynamic(network.initialize(3)) initialize.pids(nd) get.vertex.attribute(nd,'vertex.pid') # peek at pids add.vertices(nd,nv=2) # silently generate pids for vertices get.vertex.attribute(nd,'vertex.pid') # peek at pids add.edges(nd,1,2) # silently generate a pid for the edge get.edge.attribute(nd,'edge.pid') add.vertices.active add.verticies.active, add.edges.active Description Convenience functions for adding a set of verticies (or edges) and setting them to be active in a single call Usage ## S3 method for class 'active' add.vertices(x, nv, vattr = NULL, last.mode = TRUE, onset = NULL, terminus = NULL, length = NULL, at = NULL, ...) ## S3 method for class 'active' add.edges(x, tail, head, names.eval = NULL, vals.eval = NULL, onset = NULL, terminus = NULL, length = NULL, at = NULL, ...) Arguments x an object of class network or networkDynamic. nv the number of vertices to add tail a vector of vertex IDs corresponding to the tail (source, ego) of each edge to be added head a vector of vertex IDs corresponding to the head (target, alter) of each edge to be added onset an optional vector of time points that specifies the starts of the interval(s). This must be accompanied by one of terminus or length. terminus an optional vector of time points that specifies the ends of the interval(s). This must be accompanied by one of onset or length. length an optional vector of interval lengths for the interval(s). This must be accompa- nied by one of onset or terminus. at optional, one or more time points to be activated. names.eval optional list of length equal to the number of edges, with each element contain- ing a list of names for the attributes of the corresponding edge. not currently interpreted in a dynamic context, but passed directly to add.edges vals.eval an optional list of lists of edge attribute values (matching names.eval). Not currently interpreted in a dynamic context, but passed directly to add.edges vattr optionally, a list of attributes with one entry per new vertex. not currently inter- preted in a dynamic context, but passed directly to add.vertices last.mode logical; should the new vertices be added to the last (rather than the first) mode of a bipartite network? ... possible future additional arguments Details Essentially a wrapper for a call to add.vertices and activate.vertices or add.edges and activate.edges when setting up a network object. These are not the S3 methods that their name appears to imply, since there is no "active" class. See add.edges.networkDynamic, etc. Value The passed in network object with class set to networkDynamic and the specified number of new vertices or edges added and activated Note Order of arguments was changed in version 1.9 for S3 method consistency. Does not currently support the multiple-vertex head- and tail-sets of add.edges or add.edge. Author(s) <NAME> <<EMAIL>> See Also See Also as activate.vertices, activate.edges,add.vertices,add.edges Examples nw <- network.initialize(5) activate.vertices(nw,onset=0,terminus=10) network.size(nw) # just 5 nodes # add some new nodes with times add.vertices.active(nw,2,onset=10,terminus=12) network.size(nw) # now we have 7 nodes # add 2 edges edges, and activate them add.edges(nw, tail=c(1,2),head=c(2,3)) activate.edges(nw,onset=0,terminus=10,e=1:2) # instead add and activate at the same time add.edges.active(nw, tail=c(3,4),head=c(4,5),onset=10,terminus=12) adjust.activity Adjust the activity ranges in all of the spells of a networkDynamic object Description Transforms the values of all the activity spells of vertices and edges, as well as spells of dynamic TEA attributes (and the net.obs.period if it exists). Usage adjust.activity(nd, offset = 0, factor = 1) Arguments nd networkDynamic object to be modified offset numeric value to be added (or subtracted) to all spell values factor numeric factor for multiplying all spell values Details Spell values are modified by first adding the value of offset and then multiplying by factor. If a net.obs.period attribute exists, it’s observation spell values are transformed, and the time.increment value is multiplied by factor. Value The nd argument is modified in place and returned invisibly. Author(s) <EMAIL> See Also See also activity.attribute, attribute.activity.functions and net.obs.period Examples # convert steps of an imaginary discrete sim # with each steps corresponding to 1 day # into decimal 'years' since 1990 sim<-network.initialize(5) activate.vertices(sim,onset=0,terminus=2546) add.edges.active(sim,head=1:4,tail=2:5,onset=0,terminus=2546) set.network.attribute(sim,'net.obs.period',list( observations=list(c(0,2546)),mode="discrete", time.increment=1,time.unit="step")) # do the transformation adjust.activity(sim,offset=1990*365.25,factor=1/365.25) # modify the 'units' of net.obs.period obs <-get.network.attribute(sim,'net.obs.period') obs$time.unit<-'year' set.network.attribute(sim,'net.obs.period',obs) # peek at the new values as.data.frame(sim) get.network.attribute(sim,'net.obs.period') age.at Age of active edges or vertices at a query time point Description Reports the age of edges or vertices at a specific time point. More precisely, the duration of time between the query time point and the onset of the activity spell active at that point. Usage edges.age.at(nD, at, e = seq_along(nD$mel), active.default = TRUE) dyads.age.at(nD, at, tails, heads, active.default=TRUE, format.out = c("vector", "edgelist", "matrix")) vertices.age.at(nD, at, v=seq_len(network.size(nD)), active.default=TRUE) Arguments nD a networkDynamic object to be evaluated at numeric query time point which edge or vertex ages should be evaluated at e numeric vector of edges ids for which ages / durations should be reported v numeric vector of vertex ids for which ages / durations should be reported tails numeric vector of vertex ids incident on the ’tail’ of edges for which ages / durations should be reported heads numeric vector of vertex ids incident on the ’head’ of edges for which ages / durations should be reported active.default logical, if TRUE edges or vertices with no activity specified will be considered always active (see is.active) format.out character value indicating out the output should be structured. vector returns output as a vector, edgelist returns a 3-column matrix in which the first columns are the tail and head vertex ids of the edge and the 3rd column is the age, matrix returns an adjacency matrix with the edge ages as values. Details Edges or vertices that are not active at time at will return NA. For edges or vertices with multiple activity spells, this function does not report the total duration of activity across all spells, only the duration from the start of the spell with which the at point intersects. dyads.age.at reports the age of edges corresponding to each dyad (tail,head). It cannot be used with hypergraphic or multiplex networks because a pair of vertex ids may not uniquely correspond to an edge. If tails and heads are not specified, they will default to the tails and heads of all existing (but not necessarily active) edges in the network. Ordering and index position should correspond to valid.eids. Value By default, a numeric vector indicating the age of the network element at the query time point, or NA if the element is not active or (in the case of edges) deleted. Elements of the vector return correspond to the values of e or v or (tails,heads) respectively. Author(s) skyebend See Also See also get.edge.activity, is.active Examples # set up an example network for testing test<-network.initialize(5) add.edges(test,tail = 1:4,head=2:5 ) activate.edges(test,onset=0:2,terminus=c(2,3,3),e=1:3) activate.vertices(test,v = 1:4,onset=-3:0,terminus=5:8) # how old are each of the edges at time point 2.0 ? edges.age.at(test,at=2.0) # how old is vertex id 2 time point 3 vertices.age.at(test,at=3, v=2) # how old are the edges [1,2] and [3,4] at time point 2 dyads.age.at(test,at=2,tails=c(1,3),heads=c(2,4)) dyads.age.at(test,at=2,format.out='matrix') as.data.frame.networkDynamic Extracts the edge timing information from a networkDynamic object and represent as a data.frame. Description Creates a data.frame giving lists of edges and their activity spells corresponding to the networkDynamic object. An observation window may be specified, and edge spells with values outside the window will be omitted or truncated/censored to the observation window bounds. Usage ## S3 method for class 'networkDynamic' as.data.frame(x, row.names = NULL, optional = FALSE, e =seq_along(x$mel), start = NULL, end = NULL, active.default=TRUE,...) Arguments x a networkDynamic object row.names ignored optional ignored e vector of edge ids that should be included in the output. start optional, numeric onset-censoring time: time at which the network was first observed. Edge spells with earlier onset times are given this as their onset time (and marked as left censored). See Details for the default values. end optional right-censoring time: time at which the network was last observed. Edge spells with larger terminus are given this as their terminus time (and marked as right censored). See Details for the default values. active.default logical indicating if edges with no defined activity spells should be considered active by default (and appear as a row in output) ... possible additional arguments Details Exports the edge dynamics of a networkDynamic object as a data.frame giving a table of edges with their activity spells, including whether an activity spell was “censored” (onset or termination was not observed within the observation window). If a net.obs.period attribute exists, the max- imal and minimal values will be used as censoring times by default. Censoring times can also be provided using the start and end arguments (which will override net.obs.period), and censoring can be prevented by setting start=-Inf, end=Inf. Edge spells that exceed the censoring bounds will have their onset and/or terminus time appropriately truncated to match and will be marked as censored. Spells which are fully outside the censoring bounds will be deleted and the corresponding rows will not be returned. Note that the spell overlap rules mean that when edge spells are modeled as momentary events (onset==terminus), any events have onset==terminus==end of the the observation window will not be returned. This will likely be the case for networks created by the networkDynamic converter function. Value A data.frame containing timed relational information describing the networkDynamic object, hav- ing the following columns: onset, terminus Onset and terminus times of an edge, respectively, if not censored, and left and right censoring times, if censored. tail, head Tail and head of the edge. onset.censored, terminus.censored TRUE if onset/terminus time is censored. duration the duration (terminus-onset) of each spell, evaluated after censoring edge.id the id of the edge the row corresponds to The output data.frame will be sorted by edge.id, onset,terminus. This means that for most (non- multiplex) networks the group of spells for a specific edge will appear in sequential lines of output, but the overall output is not in a temporal order. Note Vertex and attribute activity are not included in the returned data.frame. If an edge has multiple activity spells, it will have multiple rows in the output. When output in censored, it may not match values returned by get.edge.activity See Also See Also as get.edge.activity,get.vertex.activity Examples net <-network.initialize(3) net[1,2]<-1; net[2,3]<-1; ## censoring activate.edges(net,onset=1,terminus=Inf,e=1) activate.edges(net,onset=2,terminus=3,e=2) activate.vertices(net, onset=1, terminus=Inf, v=1) as.data.frame(net) as.network.networkDynamic Remove ‘networkDynamic’ class name from networkDynamic object. Description Changes the class of a networkDynamic object to a plain network object while leaving all attributes (including dynamic attributes) intact. Usage ## S3 method for class 'networkDynamic' as.network(x, ...) Arguments x A networkDynamic object that will have its class name stripped. ... Possible additional arguments Details The primary use-case for this method is to force some other S3 method (like simulate in the tergm package, plot, or print) to use ’network’ instead of ’networkDynamic’ in method dispatching. Dynamic features data structures be left intact but not recognized by corresponding methods, so effectively broken. Value Returns the original network with the networkDynamic class name removed but all other attributes unchanged Author(s) <NAME> See Also See Also as network.extract for extracting parts of a networkDynamic, and network.collapse for extracting part of a networkDynamic as a static network. as.networkDynamic for the inverse operation (adding the networkDynamic class to a static network). Examples test<-network.initialize(2) add.edges.active(test,tail=1,head=2,onset=1,terminus=2) is.networkDynamic(test) test<-as.network(test) is.networkDynamic(test) as.networkDynamic as.networkDynamic Description The as.networkDynamic generic provides a very basic conversion to networkDynamic from other network types. It is generally recommended to use the networkDynamic function instead of as.networkDynamic, because networkDynamic provides a number of additional features for handling temporal informa- tion. Usage ## S3 method for class 'networkDynamic' as.networkDynamic(object,...) ## S3 method for class 'network' as.networkDynamic(object,...) ## S3 method for class 'networkLite' as.networkDynamic(object,...) Arguments object a network, networkLite, or networkDynamic object ... ignored Details as.networkDynamic.network converts a network object into a networkDynamic object by adding a networkDynamic class. as.networkDynamic.networkLite converts a networkLite object into a networkDynamic object by first converting it to a network object and then adding a networkDynamic class. (networkLites are a backend data structure used in some EpiModel and statnet packages, providing improved performance for certain applications, especially when working with vertex and edge attributes that can be stored as atomic vectors. Currently, networkLites come with the restriction that the net- work attributes hyper, multiple, and loops must be FALSE. See networkLite-package for more information.) Such conversions between network types are used when starting a dynamic simulation from a cross- sectional network and returning the simulation history as a dynamic network, as done in the tergm package for example. Value For as.networkDynamic.network the input object is returned with a networkDynamic class added. For as.networkDynamic.networkLite, the input object is converted to a network object and then the networkDynamic class is added. For as.networkDynamic.networkDynamic the input object is returned unchanged. Author(s) Pavel, <NAME> <<EMAIL>> See Also For the inverse (removing the networkDynamic class) see as.network.networkDynamic and as.networkLite.network (which applies to networkDynamics). For extracting cross-sectional information from a networkDynamic (which is often more appropriate than simply removing the networkDynamic class), see network.collapse and network.extract. For more general construction of networkDynamics, see networkDynamic. Examples nd <- as.networkDynamic(network.initialize(3)) class(nd) is.networkDynamic(nd) nwL <- networkLite::networkLite(3) nwD <- as.networkDynamic(nwL) class(nwD) is.networkDynamic(nwD) attribute.activity.functions Functions to activate and query dynamic attributes on vertices, edges, and networks Description These functions set, query and modify attributes of networkDynamic objects used to represent val- ues which change over time. These dynamic or "temporally extended attributes" are stored as standard attributes with a specially defined structure. Usage activate.vertex.attribute(x, prefix, value, onset = NULL, terminus = NULL, length = NULL, at = NULL, v = seq_len(network.size(x)), dynamic.only = FALSE) activate.edge.attribute(x, prefix, value, onset = NULL, terminus = NULL, length = NULL, at = NULL, e = seq_along(x$mel), dynamic.only = FALSE) activate.edge.value(x, prefix, value, onset = NULL, terminus = NULL, length = NULL, at = NULL, e = seq_along(x$mel), dynamic.only = FALSE) activate.network.attribute(x, prefix, value, onset = NULL, terminus = NULL, length = NULL, at = NULL, dynamic.only = FALSE) ## S3 method for class 'active' get.vertex.attribute(x, prefix, onset = NULL, terminus = NULL, length = NULL, at = NULL, rule = c("any", "all","earliest","latest"), na.omit = FALSE, null.na = TRUE, active.default = TRUE, dynamic.only = FALSE, require.active = FALSE, return.tea = FALSE, unlist = TRUE, ...) ## S3 method for class 'active' get.edge.attribute(x, prefix, onset = NULL, terminus = NULL, length = NULL, at = NULL, rule = c("any", "all","earliest","latest"), active.default = TRUE, dynamic.only = FALSE, require.active = FALSE, return.tea = FALSE, unlist = TRUE, ..., el) ## S3 method for class 'active' get.edge.value(x, prefix, onset = NULL, terminus = NULL, length = NULL, at = NULL, rule = c("any", "all","earliest","latest"), active.default = TRUE, dynamic.only = FALSE, require.active = FALSE, return.tea = FALSE, unlist = TRUE, ...) ## S3 method for class 'active' get.network.attribute(x, prefix, onset = NULL, terminus = NULL,length = NULL, at = NULL, rule = c("any", "all","earliest","latest"), dynamic.only = FALSE, return.tea=FALSE, unlist=TRUE, ...) deactivate.vertex.attribute (x, prefix, onset=NULL, terminus=NULL, length = NULL, at = NULL, v = seq_len(network.size(x)), dynamic.only = FALSE) deactivate.edge.attribute (x, prefix, onset = NULL, terminus = NULL, length = NULL, at = NULL, e = seq_along(x$mel), dynamic.only = FALSE) deactivate.network.attribute(x, prefix, onset = NULL, terminus = NULL, length = NULL, at = NULL, dynamic.only = FALSE) ## S3 method for class 'active' list.vertex.attributes(x, onset = NULL, terminus = NULL,length = NULL, at = NULL, na.omit = FALSE, rule = c("any", "all"), v = seq_len(network.size(x)), require.active = FALSE, active.default = TRUE, dynamic.only = FALSE, ...) ## S3 method for class 'active' list.edge.attributes(x, onset = NULL, terminus = NULL,length = NULL, at = NULL, na.omit = FALSE, rule = c("any", "all"), e = seq_along(x$mel), require.active = FALSE, active.default = TRUE, dynamic.only = FALSE, ...) ## S3 method for class 'active' list.network.attributes(x, onset = NULL, terminus = NULL,length = NULL, at = NULL, na.omit = FALSE, rule = c("any", "all"), dynamic.only = FALSE, ...) Arguments x a networkDynamic object prefix character string for the name of the attribute to be stored (will be stored as pre- fix.active) value an object that is the value of the attribute to be stored. If value is a list, it is assumed that each element corresponds to an index in v. onset an optional vector of time-points that specifies the starts of the interval(s) at which the value argument should be considered active for each vertex/edge. terminus an optional vector of time-points that specifies the ends of the interval(s) at which the value argument should be considered active for each vertex/edge. length an optional vector of interval lengths for the interval(s) which should be ac- tivated for each vertex/edge. This must be accompanied by one of onset or terminus. at optional, one or more time points (corresponding to vertices/edges) at which values should be activated for each vertex/edge v optional, one or more IDs indicating which vertices should have the TEA at- tribute added (default is all vertices) e optional, one or more edge IDs indicating which edge should have the TEA attribute added. Default is all edges. Note: Currently values of e correspond to elements of x$mel, including null elements from deleted edges. So if some edges have been deleted from the network, e may need to be padded out appro- priately and can be longer than network.edgecount(x). dynamic.only If dynamic.only==TRUE, only TEAs are considered; otherwise, non-TEA at- tributes are also employed (with activity as defined by active.default). require.active logical. If TRUE, NA will be returned instead of an attribute value if the associ- ated vertex or edge is inactive for the query period. When vertex or edge activity has not be explicitly set, the state is controlled by active.default. active.default logical; should underlying vertices or edges without an activity attribute be re- garded as active by default? na.omit logical; should values from missing vertices/edges be removed? (implemented for vertices, but removal means that the index may not correspond to vertex.id for returned values) null.na logical; should NULL values be replaced with NAs? rule a character string indicating how the attribute activity spells should be matched against the query spell for this query: • any (default) match attribute values if they overlap with any part of the query interval. • all match an attribute value only if it overlaps with the entire query inter- val, • earliest match a single value corresponding to the earliest attribute over- laping any part of the query spell, • latest match a single value corresponding to the earliest attribute overlap- ing any part of the query spell. return.tea logical; if return.tea=TRUE, will return an (appropriately truncated) activity attribute- a list with the first element a list of values and the second element the spell matrix of corresponding spell(s) matching according to rule. Also sets unlist=FALSE and dynamic.only=TRUE. unlist logical; should retrieved attributes be unlisted prior to being returned? Setting to FALSE is necessary to correctly fetch list objects stored as attributes. ... possible additional arguments el unused argument that exists solely for consistency with network; do not use this argument! Details These functions provide easy ways to work with temporally extended attributes, making it possible to store attributes on a dynamic network that should be represented as changing values and different points in time. Because the serve as wrappers for get.*.attribute and set.*.attribute, many of the arguments are directly passed through. The activate.*.attribute methods act as a cross between activate.* set.*.attribute methods. They are used to activate an attribute for a given spell, and in so doing set a value for that spell. The corresponding deactivate methods are more straightforward, deactivating the attribute over a set interval (and removing any spells/values as needed). A dynamic or Temporally Extended Attribute (TEA) is an edge, vertex, or network attribute satis- fying the following properties: 1. Its name consists of an arbitrary prefix, together with the suffix ".active". 2. Its value consists of a two-element list, whose respective contents must be maintained in order as follows: • a. A list of value entries, such that the ith list element is the value of the attribute for the ith spell in the associated activity matrix. An attribute not active at any given point in time is defined as having a value of NA (but the reverse is not true – an active attribute can also take a value of NA). • b. A two-column numeric matrix, conforming to the specifications for activity attributes in the networkDynamic package. Every active spell indicated in the activity matrix must correspond to exactly one entry of the associated value list, and these must be maintained in order (i.e., the value of the attribute for the ith active spell is the ith element in the value list). There are several ways to specify the activity spell, and the general syntax rules are described at activity.attribute. Activity can be set for a single time point, using either at, or by setting onset=terminus. Activity can be set for an interval [onset,terminus), using a valid combination of the onset, terminus and length attributes. This allows for a wide range of options when specifying spells, but a correct specification must use only one of these forms: at onset and terminus onset and length terminus and length If the set and deactivate functions are provided with no timing information, the element is acti- vated/deactivated from -Inf to Inf. The specified interval spans the period from the onset (inclu- sive) to the terminus (exclusive), so [onset,terminus). For more details, see activate The get query functions will give an error if no timing information is provided. When the activity arguments have a length greater than 1, the elements are assumed to correspond to the vertex or edge ids that should have that activity specified, not to the elements of value. In other words, it is possible to use one function call to activate multiple values on multiple vertices with a different activity time on each vertex, but it is not possible to activate multiple values at multiple times on a single vertex with one call. activate.edge.value is a wrapper for activate.edge.attribute. When the attribute query has a non-zero duration (i.e. length > 0, or onset!=terminus) it is possible that the query spell will match against multiple attribute values for each network element. If multiple values match and return.tea=FALSE, a warning will be generated and only the earliest value will be returned. To avoid the warning, this behavior (or its opposite) can be specified by setting rule='earliest' or rule='latest'. Value The set methods modify their network argument internally and also invisibly return a reference to the modified network. The get methods return the attribute object appropriate for the time range specified query spell parameters. If query results in multiple values and return.tea=FALSE only the first (earliest) is returned along with a warning. Note that get.edge.value.active returns NULL if no attributes names match, where get.vertex.attribute.active returns NAs. Also of null.na=FALSE and unlist=TRUE, the index position for returned values may not correspond to the vertex.id because NULL values will be omited. Note Attribute activity is only checked against vertex and edge activity during fetching if require.active=TRUE. Otherwise the attributes for a vertex can take values (be active) when the vertex itself is inac- tive. Likewise for edges. The because they must check all attributes on all network elements, the list.*.active functions are generally more computationally expensive that a get call for checking if a specific attribute exists. Note that get.edge.attribute.active currently calls get.edge.attribute.active and does not support a list of edges as input. Author(s) skyebend, ayn, carter, pavel, martina, steve See Also See Also as set.vertex.attribute, get.vertex.attribute,list.vertex.attributes,activate.vertices, activity.attribute, activate Examples #initialize network test<-network.initialize(5) #activate vertex attribute test<-activate.vertex.attribute(test,"letter","a",onset=0,terminus=1) test<-activate.vertex.attribute(test,"number","4",onset=1,terminus=2) test<-activate.vertex.attribute(test,"number","5",onset=2,terminus=3) #list active/all vertex attributes list.vertex.attributes.active(test, onset=0,terminus=3,dynamic.only=TRUE) list.vertex.attributes.active(test, onset=1,terminus=3,dynamic.only=FALSE) #get values for specific vertex attribute get.vertex.attribute.active(test,"letter",onset=2,terminus=3) #deactive vertex attribute test <- deactivate.vertex.attribute(test, "letter", onset=0, terminus=3) list.vertex.attributes.active(test, onset=0,terminus=3,dynamic.only=TRUE) #initialize edges test[1,2]<-1 test[2,3]<-1 #activate edge attribute test<-activate.edge.attribute(test,"number",1,onset=0,terminus=2) test<-activate.edge.attribute(test,"number",5,onset=2,terminus=5) test<-activate.edge.attribute(test,"letter","a",onset=1,terminus=4) #list edge attributes list.edge.attributes.active(test, onset=0,terminus=4,dynamic.only=TRUE) list.edge.attributes.active(test, onset=0,terminus=4,dynamic.only=FALSE) #get values for specific edge attribute get.edge.value.active(test,"number",onset=3,terminus=4) #deactive edge attribute test <- deactivate.edge.attribute(test, "letter", onset=0, terminus=3) list.edge.attributes.active(test, onset=0,terminus=3,dynamic.only=TRUE) #activate network attribute test <- activate.network.attribute(test,"alist",list("a","b"),onset=1,terminus=2) test <- activate.network.attribute(test,"alist",list("c","d"),onset=2,terminus=3) test <- activate.network.attribute(test,"aspace",list("1","2"),onset=1,terminus=2) test <- activate.network.attribute(test,"aspace",list("3","4"),onset=2,terminus=3) #list network attributes list.network.attributes.active(test, onset=0,terminus=3,dynamic.only=TRUE) list.network.attributes.active(test, onset=0,terminus=3,dynamic.only=FALSE) #get values for specific network attribute get.network.attribute.active(test,"alist",at=2.5,unlist=FALSE) #deactive network attribute test <- deactivate.network.attribute(test, "alist", onset=0, terminus=3) list.network.attributes.active(test, onset=0,terminus=3,dynamic.only=TRUE) # activate multiple values on multiple vertices at multiple times test<-network.initialize(3) activate.vertex.attribute(test,"letters",c("a","b","c"),onset=c(0,1,2),terminus=c(1,2,3)) # peek at TEA structure using non-TEA attribute query get.vertex.attribute(test,"letters.active",unlist=FALSE) # compare different 'rules' test<-network.initialize(1) activate.vertex.attribute(test,'color','red',onset=0,terminus=1) activate.vertex.attribute(test,'color','green',onset=1,terminus=2) activate.vertex.attribute(test,'color','blue',onset=2,terminus=3) get.vertex.attribute.active(test,'color',onset=0,terminus=3) get.vertex.attribute.active(test,'color',onset=0,terminus=3,return.tea=TRUE) get.vertex.attribute.active(test,'color',onset=0,terminus=3,rule='earliest') get.vertex.attribute.active(test,'color',onset=0,terminus=3,rule='latest') cls33_10_16_96 <NAME>’s Streaming Classroom Interactions Dataset Description A dynamic network object describing continuous time streams of social interactions between teach- ers and students in a classroom observed by <NAME> in 1996. Usage data(McFarland_cls33_10_16_96) Format The format is is a networkDynamic object named cls33_10_16_96 with node and edge activ- ity.attributes defined by spell matricies and associated vertex attributes and dynamic edge attributes. Details The dynamic network object has 20 vertices and directed edges and covers a time range of 0.0 to 49.0 minutes of class time. The vertex attribute gender gives gender (’M’ or ’F’) of each person and type gives a crude role (’grade11’,’grade12’,’instructor’). The original dataset id for the vertices is included as data_id and defined as a persistent.id. The edges include a dynamic attribute (TEA) interaction_type with values ’saction’, ’social’ and ’task’ (see explanation below) and a weight assigned by the reacher to that interaction (direct comunication is given more weight than indirect ’broadcast’ communication). A .son formatted input file with the same data as well as seperate tsv files for vertices and edges are located in the /inst/extdata directory. The data for these classroom interactions consists of streaming observations of conversation turns. The conversation turns were recorded as pairs of senders and receivers and for types of content. Speakers were viewed as directing their communication in one of two fashions: (1) indirect sound- ings, such as lectures (where a teacher addresses all students); and (2) direct interactions that are focused on particular others. Each type of directional speech is viewed as having different forms of network reception - indirect speech reaches all bystanders as passive hearers and directed speech reaches the focal person as an active co-author of the conversation (Goffman 1981). Two types of interaction are found to prevail in classroom contexts: task and sociable (McFarland, in press). Task interactions are those behaviors that pertain to the ongoing teacher prescribed task (content is academic). In contrast, sociable interactions concern everyday concerns of adolescents’ social lives, such as parties, dating, social outings, plans, etc. While the content is the key distinc- tion, it is often the case that these speech acts are distinguishable in style as well, where sociable behaviors are more play-like, fast-paced, and free than the more constrained academic styles of speech during lessons (Cazden 1988). Last, observations also recorded when task and sociable forms of interaction were laminated with evaluative meaning. Such evaluations were seen as being either positive or negative - either giving praise or attempting a reprimand (Ridgeway and Johnson). The class (#33) is an economics class composed of 11th and 12th graders at a magnet high school. On this day, economics has two teachers. The first is the usual teacher and the second is a busi- nessman who donates his time a couple days a month to assist the class with their lesson on stock investments. After a minute of undefined class time, the two teachers prescribe collaborative group work and assist students in conducting it. The students are assigned groups within which they are to study the stock market and make mock investments they can follow over time. The groups compete with each other over the course of the semester to see who can make the greatest profit. The network narrative for the class opens with the teacher trying to focus student attention and then lecturing while the visiting professional assists each group. The teacher prescribes group work but continues to lecture, thereby preventing the desired social routine from fully taking effect. Eventu- ally the students are doing group projects while the adults move from group to group, facilitating their progress, and stabilizing interaction patterns. The routine of group work is basically character- ized by dyadic task and social interactions that persist in multiple clusters. Not all persons engage in these groups, and a couple students sit quietly by themselves. The group work routine breaks down as social activity increases within the groups’, and then the teacher emits broadcast sanctions in an effort to redirect student attention back on task (16 minutes). The task breaks down again at the end of class, but this time because the adults make closing announcements. So the network illustrates that teachers are involved in this task engaging their students as they monitor interaction. When students become too social, a teacher usually arrives, disperses the group, and then reforms it via task interactions (revolution in type of behavior, McFarland 2004). Hence, the “dance” here entails relatively bounded groups of individuals that free-associate over tasks and drift into social affairs, and teachers who refocus affairs by indirect means of broadcasts or by direct means of directed speech. Source Dr. <NAME>, Stanford University https://ed.stanford.edu/faculty/mcfarland References McFarland, <NAME>. 2005. “Why Work When You Can Play? Dynamics of Formal and Informal Organization in Classrooms.” Chapter 8 in The Social Organization of Schooling, edited by Larry Hedges and <NAME> (pp. 147-174). New York: Russell Sage Foundation. McFarland, <NAME>. 2004. “Resistance as a Social Drama - A Study of Change-Oriented Encoun- ters.” American Journal of Sociology 109 (6): 1249-1318. McFarland, <NAME>. 2001. “Student Resistance: How the Formal and Informal Organization of Classrooms Facilitate Everyday Forms of Student Defiance.” American Journal of Sociology 107 (3): 612-78. McFarland, <NAME>. and <NAME>. 2003. “Classroom Structuration: A Study of Network Stabilization.” Working paper, Stanford University. Examples data(McFarland_cls33_10_16_96) delete.activity Remove Timing Information in a Dynamically Extended Network Ob- ject Description Removes the activity spells of a given set of vertices or edges. Usage delete.edge.activity(x, e=seq_along(x$mel)) delete.vertex.activity(x, v=seq_len(network.size(x))) Arguments x an object, of class network or networkDynamic. e the edges of x that will have their timing information deleted; default = all. v the vertices of x that will have their timing information deleted; default = all. Details Though the timing information of the edges and/or vertices may be removed, other networkDy- namic methods will assume activity or inactivity across all time points, based on the argument active.default. Value An object with the same class as x, equivalent to x without the activity spells of the edges e or the vertices v. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> See Also activate Examples library(networkDynamic) data(flo) net1 <- network(flo) activate.edges(net1) activate.vertices(net1) net2 <- net1 delete.edge.activity(net1, e=seq(2,40,2)) delete.edge.activity(net2) delete.vertex.activity(net2) is.active(net1, at=0, e=c(1,2), active.default=FALSE) is.active(net1, at=0, e=c(1,2), active.default=TRUE) is.active(net2, at=0, e=1:16, active.default=FALSE) is.active(net2, at=0, e=1:16, active.default=TRUE) duration.matrix Construct a edge spells list from base network and toggle list. Description Given a network object and a toggle list, it will construct a list of edges and activity spells and return that as a data frame. The network object does not need to have edges; it only needs to have enough vertices to cover all the edges specified in the toggle list. The toggle list should be a three column matrix or data frame, where the first column is the toggle time, the second column is the tail vertex id of the edge, and the third column is the head vertex id of the edge. A toggle represents a switch from active state to inactive, or vice-versa. Usage duration.matrix(nw0, changes, start, end) Arguments nw0 an object of class network changes a matrix or data frame, listing the toggles for edges as specified in the above description start integer, specifies the starting time of the network’s dynamic activity end integer, specifies the ending time of the network’s dynamic activity Value Returns a data frame that lists the edge spells specified by the toggles. The columns in the data frame are start end tail head left.censored right.censored duration. Left and right censoring and duration are calculated automatically from the toggle list and the start and end times. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> See Also as.networkDynamic Examples library(networkDynamic) # duration matrix test net <-network.initialize(3) net[1,2]<-1; net[2,3]<-1; net[1,3]<-1; class(net) # toggle list: time, tail, head tog=matrix(c(1,1,2, 1,2,3, 2,1,2, 4,1,3, 4,1,2), ncol=3, byrow=TRUE) networkDynamic:::duration.matrix(net, tog, 0, 5) get.dyads.active Return the set of vertex ids of edges active at a given time Description Constructs a matrix, essentially an edgelist, of the pairs of vertices connected by edges active within the query spell. Usage get.dyads.active(nD, onset = NULL, terminus = NULL, length = NULL, at = NULL, rule = c("any", "all", "earliest", "latest"), active.default = TRUE) Arguments nD networkDynamic object to be queried onset optional numeric value giving onset time of query spell terminus optional numeric value giving terminus time of query spell length optional numeric value giving length (duration) of query spell at optional numeric value giving single time point to query rule a character string indicating the definition of "active" for this query: any (de- fault) to define active as any active spell during the interval, or all to define active as being active over the entire interval. For this functions, the values of earliest and latest are equivalent to any and are only included for consis- tency. active.default logical; should elements without an activity attribute be regarded as active by default? Default to TRUE Details Uses is.active internally. The ordering of matrix rows is arbitrary. The ordering of vertices in non-directed networks corresponds to how they were set in the data structure (i.e. does not enforce i > j) If no edges are active or exist, a matrix with zero rows will be returned. Value Returns a two-column numeric matrix in which the first column gives a tail vertex.id and the second column gives the head vertex.id and each row corresponds to the existence of an active relationship between the vertices for the given query spell. Note This function does not support hypergraphic networks. Author(s) skyebend See Also See also is.active Examples data(windsurfers) get.dyads.active(windsurfers,onset=2,terminus=3) get.networks Obtain a list of collapsed networks sampled periodically from a net- workDynamic object Description Given a start time, end time, and increment (or vectors of onsets and termini) to express sampling intervals, return a list of collapsed networks from a networkDynamic object. Usage get.networks(dnet, start = NULL, end = NULL, time.increment = NULL, onsets=NULL, termini=NULL,...) Arguments dnet A networkDynamic object with possible vertex, edge, network, and attribute spell information. start numeric value giving the start of the sampling interval end numeric value giving the end of the sampling interval time.increment value for the offset (and duration) between sucessive samples. Will default to 1 if not otherwise specified onsets A numeric vector containing the onset times of the networks to be extracted. This must be accompanied by termini of the same length. termini A numeric vector containing the terminus times of the networks to be extracted. This must be accompanied by onsets of the same length. ... Additional arguments to network.collapse (such as rule,active.default,retain.all.vertices) Details The sampling ("slicing") intervals may be defined using either the start, end, and time.increment parameters, or by providing parallel vectors of onsets and termini. If values are not specefied but a net.obs.period attribute exists to describe the ’natural’ sampling parameters, start and end will defult to the max an min of the observations element, with time.increment set to its corresponding value in the net.obs.period. Value A list of static network objects corresponding to the specified sampling intervals of the networkDynamic Note See Note in network.collapse. Author(s) <NAME>, <NAME> See Also See Also as network.collapse for obtaining a slice of static network, network.extract for ex- tracting sub-ranges of a networkDynamic, get.vertex.attribute.active for more on TEA at- tributes, and as.network.networkDynamic for stripping the the networkDynamic class from an object. Examples # create a networkDynamic with some basic activity and time extended attributes (TEA) test <- network.initialize(5) add.edges.active(test, tail=c(1,2,3), head=c(2,3,4),onset=0,terminus=1) activate.edges(test,onset=3,terminus=5) activate.edges(test,onset=-2,terminus=-1) activate.edge.attribute(test,'weight',5,onset=3,terminus=4) activate.edge.attribute(test,'weight',3,onset=4,terminus=5,e=1:2) # obtain the list of networks list <- get.networks(test,start=0, end=5) # aggregate over a longer time period with specified rule list <- get.networks(test,start=0, end=6,time.increment=2,rule='latest') # use 'at' style extraction of momentary slices via onsets & termini list <- get.networks(test,onsets=0:5,termini=0:5) # ensure that all networks returned will be the same size list <- get.networks(test,onsets=0:5,termini=0:5,retain.all.vertices=TRUE) # find out how many edges in each sampling point with apply sapply(get.networks(test,start=0,end=5),network.edgecount) # generate a list of matrices lapply(get.networks(test,start=0,end=5),as.matrix) get.timing.info Retrieve the timing information present in a networkDynamic. Description These methods return either the activity spells of each vertex or edge or the unique time points at which edges and vertices become active or inactive. Finds all of the unique time points at which the edges and/or vertices become active or inactive. Usage get.change.times(x, vertex.activity=TRUE, edge.activity=TRUE, ignore.inf=TRUE, vertex.attribute.activity = TRUE, edge.attribute.activity = TRUE, network.attribute.activity = TRUE) get.vertex.activity(x, v=seq_len(network.size(x)), as.spellList=FALSE, active.default=TRUE) get.edge.activity(x, e=seq_along(x$mel), as.spellList=FALSE, active.default=TRUE) Arguments x an object, of class network or networkDynamic. vertex.activity logical, whether the times at which vertices become active or inactive is to be returned. edge.activity logical, whether the times at which edges become active or inactive is to be returned. vertex.attribute.activity logical, whether the times attached to any dynamic vertex attributes should be returned edge.attribute.activity logical, whether the times attached to any dynamic edge attributes should be returned network.attribute.activity logical, whether the times attached to any dynamic network attributes should be returned ignore.inf logical, whether Inf value will be ignored or not. e IDs for the edges whose activity spells are wanted. v IDs for the vertices whose activity spells are wanted. as.spellList should data be returned in spell matrix form? TODO: should this be callsed as.spellmatrix instead? active.default logical, should edges / vertices with no spell activity defined be treated as always active (TRUE) and included in output, or never active (FALSE) and skipped. Value For the get.change.times function, the default settings return a vector of all of the finite time points at which any edge or any vertex becomes active or inactive, or any of their dynamic attributes change. If only one of the logical arguments, say vertex.activity, is set to FALSE, then the time points for the corresponding parts of the data structure will not be returned. If both are FALSE, numeric(0) is returned. For the get.vertex.activity and get.edge.activity functions, a list of activity spells is re- turned with each list element corresponding to the id of the vertex or edge. Deleted edges will appear as NULL entries, as will any spell marked as inactive with the ’null’ (Inf,Inf) spell. If the argument as.spellList=TRUE the activity spells are instead formatted as a data.frame and in- clude additional columns to indicate possible onset- and terminus-censoring. Any ’null’ spells and deleted edges will be omited. For get.vertex.activity the columns are [onset,terminus,vertex.id,onset.censored,terminus.censored,durat For get.edge.activity the columns are [onset, terminus, tail, head, onset.censored, terminus.censored, duration, edge.id] . The data.frames will be sorted by id, onset, terminus. If a net.obs.period network attribute is set, the range of its $observations element is substituted in for the -Inf and Inf values that otherwise indicate the onset- and terminus-censored observations. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>>,skyebend See Also See also activity.attribute,net.obs.period,as.data.frame.networkDynamic Examples library(networkDynamic) data(flo) net1 <- network(flo) activate.edges(net1, onset=1:20, terminus=101:120) activate.vertices(net1, at=seq(2,32,2)) get.change.times(net1) get.edge.activity(net1) get.edge.activity(net1,as.spellList=TRUE) get.vertex.activity(net1) a <-network.initialize(5) activate.vertices(a,onset=0,terminus=Inf) get.change.times(a,ignore.inf=FALSE) is.active Determine Activation State of Edges and Vertices Description Query the activity state of one or more network elements (edges or vertices) for either a single time point or an extended interval. Usage is.active(x, onset = NULL, terminus = NULL, length = NULL, at = NULL, e = NULL, v = NULL, rule = c("any", "all","earliest","latest"), active.default = TRUE) Arguments x an object of class network. onset an optional vector of timepoints that specifies the start of the queried interval(s). This must be accompanied by one of terminus or length. terminus an optional vector of timepoints that specifies the end of the queried interval(s). This must be accompanied by one of onset or length. length an optional vector of interval lengths for the queried interval(s). This must be accompanied by one of onset or terminus. at an optional vector of single time point(s) to query. e a vector of edge IDs to evaluate. v a vector of vertex IDs to evaluate. rule a character string indicating the definition of "active" for this query: any (de- fault) to define active as any active spell during the interval, or all to define active as being active over the entire interval. Because we are only testing for activity, the values of earliest and latest are equivilent to any and are only included for compatibility with calling functions. active.default logical; should elements without an activity attribute be regarded as active by default? Details This function can be used to query the activity status of an element at single time point, or over an interval. The specification of timepoints and intervals is the same as for the activate function. The general rules are discussed in activity.attribute. To query status at a single time point, use one of the following: • the at argument, or • set onset=terminus. To query status over a particular interval, one of the following valid combinations of onset, terminus and length is required: • onset and terminus. • onset and length. • terminus and length. • or, you can specify no information. If the query is specified with no timing information the spell is defined as (-Inf,Inf). The query interval spans the period from the onset (inclusive) to the terminus (exclusive), so [onset,terminus). There are some special behaviors associated with the arguments Inf and -Inf. • The open-ended interval c(-Inf,x) includes -Inf. For consistency, we also allow the open- ended interval c(x, Inf) to include Inf. Thus [onset, terminus) will be interpreted as [onset, terminus] when terminus = Inf. • Queries for intervals specified by c(Inf, Inf) or c(-Inf, -Inf) are ignored. If the e argument includes edge ids corresponding to deleted edges, a warning will be generated because the length of the output vector will not match the vector of edge ids. In this case it is a good idea to use valid.eids to determine the edge ids. Value A logical vector indicating the activity states of vertices or edges. In the case of vertices, the elements of the vector correspond to the vertex ids provided via the v paramter. In the edges case, if the network has deleted edges, they will be omited from the result so the elements of the vector may not correspond to the eids provided via the e parameter. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> See Also activity.attribute, activate, valid.eids Examples triangle <- network.initialize(3) # create a toy network add.edge(triangle,1,2) # add an edge between vertices 1 and 2 add.edge(triangle,2,3) # add more edges add.edge(triangle,3,1) # turn on all edges at time 1 only (0 length spell) activate.edges(triangle,at=1) # activate edge (1,2) from t=2 to t=3 activate.edges(triangle,onset=2, terminus=3, e=get.edgeIDs(triangle,v=1,alter=2)) # activate edge (2,3) from t=4 for 2 time lengths activate.edges(triangle,onset=4, length=2, e=get.edgeIDs(triangle,v=2,alter=3)) # are the edges active at a particular time? is.active(triangle, at=1, e=1:3) is.active(triangle, at=4, e=seq_along(triangle$mel)) # delete an edge delete.edges(triangle,e=2) is.active(triangle, at=4, e=seq_along(triangle$mel)) # gives warning, and only two values returned, which edges are they? # much safer to use is.active(triangle, at=4, e=valid.eids(triangle)) nd_test_nets networkDynamic testing networks Description A list of networkDynamic objects to be used for testing package functions. Each network exempli- fies a possible extreme case for the data structure representation. Usage data(nd_test_nets) Format A list of networkDynamic objects. Each element is named with a short description Details This list of networks is intended for testing purposes. Each element is a network with a different unusual configuration of the networkDynamic data structure. The idea is that the items on the list can be used when testing functions that use networkDynamic objects to make sure that they can properly handle (or explicitly reject) a wide range of network configurations and parameter settings. A short description of each test case can be printed with names(nd_test_nets). Note that these test cases are intended for checking that functions process the data structures without error, but in most cases the networks are too trivial to be useful in testing algorithm results. Examples data(nd_test_nets) # print the list of test cases names(nd_test_nets) # check that network.size.active works # (or at least doesn't fail) # for many types of networks lapply(nd_test_nets,network.size.active,at=1) net.obs.period Network attribute describing the observation properties of a network- Dynamic object Description net.obs.period is an optional network-level attribute that gives meta-information about the char- acteristics of the observations, time range and temporal model of a networkDynamic object. Format If the attribute is present, it is required to have a specific structure. It is a 4-element list with named values. • the observations element is a list of two-elment spell vectors that give the onset and terminus of the time period(s) during which the network was observed or simulated • mode A string indicating the temporal model of the network: either discrete or continuous • time.increment is an indicator of the ‘natural’ time unit for iterating over the network (pri- marily useful for discrete time models) • time.unit is the name of the unit used by all of the spells in the object: often set to step for discrete simulations. Details Some functions that work with networkDynamic objects need to know information about the ob- servation design of the network. Is it discrete or continuous time model? When did the observation (or simulation) of the network processes start and end? What are the time units? This information may be stored in the optional net.obs.period network attribute. Some examples of possible net.obs.period values for various networks: • for an stergm output it might be: list(observations=list(c(0,100)),mode="discrete", time.increment=1,time.unit="step") • For Lin’s windsurfers , which is missing all observations on day 25: list(observations=list(c(0,25),c(26,31)), time.increment=1,time.unit="day") • For McFarland’s classroom data: list(observations=list(c(0,55),),mode="continuous", time.increment=NA,time.unit="minute") • A fictitious instantaneous panel example : list(observations=list(c(0,0),c(21,21),c(56.5,56.5),c(68,68)) time.increment=0,time.unit="seconds") The values of the net.obs.period object are not checked for consistency with activity spells of the network itself. References Link to page on statnet wiki? See Also Several of the networkDynamic converter functions set the net.obs.period attribute on their out- put object. See also activity.attribute Examples nd<-network.initialize(5) activate.vertices(nd,onset=0,terminus=100) set.network.attribute(nd,'net.obs.period',list(observations=list(c(0,100)), mode="discrete", time.increment=1,time.unit="step")) # find the overall `expected' time range for the object range(get.network.attribute(nd,'net.obs.period')$observations) network.collapse Convert a time range of a networkDynamic object into a static network object. Description This function provides an easy way to sensibly collapse the time-related information in a networkDynamic object and return a plain network object with a set of vertices, edges, and attributes that appro- priately correspond to those appearing in the original networkDynamic object during the query interval. Usage network.collapse(dnet, onset = NULL, terminus = NULL, at = NULL, length = NULL, rule = c("any", "all","earliest","latest"), active.default = TRUE, retain.all.vertices=FALSE, rm.time.info=TRUE, ...) dnet%k%at Arguments dnet A networkDynamic object with possible vertex, edge, network, and attribute spell information. onset optionally, the start of the specified interval. This must be accompanied by one of terminus or length. terminus optionally, the end of the specified interval. This must be accompanied by one of onset or length. length optionally, the length of the specified interval. This must be accompanied by one of onset or terminus. at optionally, a single time point. rule a text string for defining “active” for this call: any if elements active at any time during the interval are to be used, or all if elements must be active over the entire interval. The value earliest behaves like any but specifies that when multiple attribute values are encountered, only the earliest will be returned. The value latest behaves like any but specifies that when multiple attribute values are encountered, only the latest will be returned. active.default logical; should elements without an activity attribute be regarded as active by default? retain.all.vertices logical; should the extracted network retain all vertices, ignoring the vertex ac- tivity spells of x in order to ensure that the network returned has the same size as dnet? rm.time.info logical; if TRUE, the net.obs.period attribute will be removed (if it exists), and the activity summary attributes activity.count and activity.duration will not be attached to edges and vertices ... Possible additional arguments (not yet invented) to handle aggregation of at- tributes. Details First performs a network.extract on the passed networkDynamic object with the specified time range to get the appropriate set of active edges. Extracts appropriate values from any dynamic at- tributes and stores them as static attributes and optionally (if rm.time.info=FALSE) computes some crude summary attributes for edge and vertex spells (activity.count, activity.duration),. Then removes all activity.attribute and dynamic.attributes information and returns a plain network without the networkDynamic class. The %k% operator (‘K’ for kollapse) is a shortcut for the ’at’ version of network.collapse. If no temporal arguments are specified, defaults to collapsing entire time range of the input network (onset=-Inf,terminus=Inf). Original network is not modified. Arbitrary attribute values may be returned when query spells with a duration are used for continuous time networks (i.e. anything other than ’at’) or query spells that don’t line up with the discrete units for discrete time networks are used. If a query spell intersects with multiple attribute values, a warn- ing will be produced and only the earliest value will be used (see get.vertex.attribute.active). To avoid ambiguity (and the warning), appropriate handling can be specified by setting rule='earliest' or rule='latest' to indicate which of the multiple values should be returned. The duration values returned for edges do not account for any potential ‘censoring’ of observations in the original network. Value A new ’static’ network object corresponding to the specified time range of the networkDynamic argument. If the original network contained dynamic TEA attributes (i.e. ’weight.active’), the appropriate (if possible) value is queried and stored as a non-TEA attribute (’weight’). Note This function may be quite computationally expensive if the network contains lots of attributes. For many tasks it is possible to avoid collapsing the network by using is.active, the dynamic network.extensions, and the attribute.activity.functions. Author(s) <NAME> See Also See also network.extract for extracting sub-ranges of a networkDynamic, get.vertex.attribute.active for more on TEA attributes, and as.network.networkDynamic for stripping the the networkDy- namic class from an object without the expense of modifying or removing the activity attributes. Examples # create a network with some basic activity test<-network.initialize(5) add.edges.active(test, tail=c(1,2,3), head=c(2,3,4),onset=0,terminus=1) activate.edges(test,onset=3,terminus=5) activate.edges(test,onset=-2,terminus=-1) # collapse the whole thing net <-network.collapse(test) is.networkDynamic(net) get.vertex.attribute(net,'activity.duration') get.edge.value(net,'activity.count') get.edge.value(net,'activity.duration') # add a dynamic edge attribute activate.edge.attribute(test,'weight',5,onset=3,terminus=4) activate.edge.attribute(test,'weight',3,onset=4,terminus=5) # collapse with an interval query net3<-network.collapse(test,onset=3,terminus=4) get.edge.value(net3,'weight') # note that if we use a query that intersects mutiple # attribute values it will generate a warning. # try commented line below: # net3<-network.collapse(test,onset=3,terminus=5) # but should be safe from attribute issues when # collapsing with a point query net3<-network.collapse(test,at=3) get.edge.value(net3,'weight') # can use operator version for point query instead net3<-test%k%4.5 get.edge.value(net3,'weight') network.dynamic.check Verify a Dynamically Extended Network Object Description Checks a networkDynamic object for any activity information that is not correctly specified. Usage network.dynamic.check(x, verbose = TRUE, complete = TRUE) is.networkDynamic(x) Arguments x an object, hopefully of class networkDynamic. verbose logical; should output messages be printed to the user? complete logical; should a complete test be ran, including checks of the activity matrices for edges and vertices, versus a check of only edge activity invovling non-active vertices Details Currently, network.dynamic.check runs three types of checks on an input object: 1. If a complete test is run, vertex spell matrices and edge spell matrices (if any) are checked for legality, specifically these are checked for correct dimensionality and proper spell ordering. 2. If vertex and edge spell matrices are correctly specified or assumed to be using complete=FALSE, incident vertices of active edges (if any) are checked to ensure that they are also active during the specified period(s). 3. If a complete test is run, and any TEA attributes are attached to the network, vertices or edges, they will be checked for correct structure. If spell matrices are only acted upon by network or networkDynamic methods, there is no need to run a complete test - correct dimensionality and spell ordering are guaranteed. is.networkDynamic checks if its argument has the class ’networkDynamic’. Value For network.dynamic.check: A list of logical vectors, one for each network component checked: • $vertex.checks : Whether the spell matrix of each vertex (if any) is correctly specified • $edge.checks : Whether the spell matrix of each edge (if any) is correctly specified • $dyad.checks : Corresponding to edges, whether the incident vertices of each edge are active when the edge is active • $vertex.tea.checks : Corresponding to vertices, whether the vertex has correctly formed TEA attributes • $edge.tea.checks : Corresponding to edges, whether the edge has correctly formed TEA attributes • $network.tea.checks : Single boolean, whether the network TEA attributes are formed correctly • $net.obs.period.check : NULL, if no net.obs.period network attribute is present, oth- erwise a single boolean, whether the attribute is formed correctly. For is.networkDynamic: a boolean which is true if the class matches Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> See Also activity.attribute, net.obs.period Examples test <-network.initialize(2) # make a network # only activate one vertex activate.vertices(test,onset=2,length=5,v=1) test[1,2] <-1 # add an edge between the verticies # activate the edge for a spell not including vertex spell activate.edges(test,onset=0,terminus=7, e=1) network.dynamic.check(test) # find the bad edge # name a vertex attrible like a TEA but with the wrong structure set.vertex.attribute(test,'letters','a') network.dynamic.check(test) network.extensions Dynamically Extended Core Network Functions Description Various core functions from the network package, with specialized extensions for handling dynamic data. Usage get.edgeIDs.active(x, v, onset = NULL, terminus = NULL, length = NULL, at = NULL, alter = NULL, neighborhood = c("out", "in", "combined"), rule = c("any", "all", "earliest", "latest"), na.omit = TRUE, active.default = TRUE) get.edges.active(x, v, onset = NULL, terminus = NULL, length = NULL, at = NULL, alter = NULL, neighborhood = c("out", "in", "combined"), rule = c("any", "all", "earliest", "latest"), na.omit = TRUE, active.default = TRUE) get.neighborhood.active(x, v, onset = NULL, terminus = NULL, length = NULL, at = NULL, type = c("out", "in", "combined"), rule = c("any", "all", "earliest", "latest"), na.omit = TRUE, active.default = TRUE) is.adjacent.active(x, vi, vj, onset = NULL, terminus = NULL, length = NULL, at = NULL, rule = c("any", "all", "earliest", "latest"), na.omit = FALSE, active.default = TRUE) ## S3 method for class 'active' network.dyadcount(x, onset = NULL, terminus = NULL, length = NULL, at = NULL, rule = c("any", "all", "earliest", "latest"), na.omit = TRUE, active.default = TRUE,...) ## S3 method for class 'active' network.edgecount(x, onset = NULL, terminus = NULL, length = NULL, at = NULL, rule = c("any", "all", "earliest", "latest"), na.omit = TRUE, active.default = TRUE,...) ## S3 method for class 'active' network.naedgecount(x, onset = NULL, terminus = NULL, length = NULL, at = NULL, rule = c("any", "all", "earliest", "latest"), active.default = TRUE,...) ## S3 method for class 'active' network.size(x, onset = NULL, terminus = NULL, length = NULL, at = NULL, rule = c("any", "all", "earliest", "latest"), active.default = TRUE,...) Arguments x an object of class network v a required vertex ID. vi an optional vertex ID (tail). vj an optional vertex ID (head). onset an optional start time for the selection interval. This must be accompanied by one of terminus or length. terminus an optional end time for the selection interval. This must be accompanied by one of onset or length. length the length of the selection interval. This must be accompanied by one of onset or terminus at a time point for selecting edges/vertices. alter optionally, the ID of another vertex. neighborhood a text string that indicates whether we are interested in in-edges, out-edges, or both (relative to v). type a text string that functions as neighborhood, above, for vertex neighborhoods. rule a text string for defining “active” for this call: any (default) to select elements appearing at any time during the specified interval, or all to select only elements active for the entire interval. For these functions, the values of earliest and latest are equivalent to any and are only included for consistency. na.omit logical; should we omit missing edges? active.default logical; should elements without an activity attribute be regarded as active by default? ... possible additional argumenets Details These functions are “dynamically extended” versions of their standard network counterparts. As such, conventional aspects of their behavior can be found on their respective manual pages (see below). In all cases, the sole difference between the extended and non-extended versions lies in the ability of the user to specify a time point (or interval), such that only vertices and edges active at the indicated time (or during the indicated interval) are employed by the routine. For elements (edges and vertices) lacking an activity attribute, the active.default argument de- termines appropriate treatment. By default, all such elements are considered active. Value The return value matches that of the original function, suitably filtered. Note The current temporal implementation of these routines will be slower compared to the non-temporal versions. Do not use them unless you have to. Author(s) <NAME> <<EMAIL>> References <NAME>. (2008). “network: a Package for Managing Relational Data in R.” Journal of Statistical Software, 24(2). https://www.jstatsoft.org/v24/i02/ See Also network.extract, is.active, get.edgeIDs, get.edges, get.neighborhood, is.adjacent, network.dyadcount, network.edgecount, network.naedgecount, network.size Examples ## is.adjacent.active triangle <- network.initialize(3) # create a toy network add.edge(triangle,1,2) # add an edge between vertices 1 and 2 add.edge(triangle,2,3) # add a more edges add.edge(triangle,3,1) is.adjacent.active(triangle,vi=1,vj=2,onset=2,length=1) ## get.edges.active net <-network.initialize(5) net[1,2]<-1; net[2,3]<-1; activate.edges(net,onset=1,terminus=Inf,e=1) activate.edges(net,onset=2,terminus=3,e=2) get.edges.active(net,v=2,at=1) get.edges.active(net,v=2,at=1, neighborhood="combined") get.edges.active(net,v=2,at=2, neighborhood="combined") ## get the ids of the active edges instead (could be multiple incident edges) get.edgeIDs.active(net,v=2,at=2) ## or get ids of the active nodes in a vertex neighborhood get.neighborhood.active(net,v=2,at=2) # returns both edges get.edges.active(net,v=2,onset=1, terminus=3, neighborhood="combined", rule='any') # returns only one edge (e=2) get.edges.active(net,v=2,onset=1, terminus=3, neighborhood="combined", rule='all') ## network.edgecount.active network.edgecount.active(net, at=1, active.default=FALSE) network.edgecount.active(net, at=2, active.default=FALSE) network.edgecount.active(net, at=5, active.default=FALSE) network.extract Temporal Extracts/Cross-sections of Dynamically Extended Network Objects Description Given a networkDynamic and a specified time point (or interval), return a reduced networkDynamic that only contains the vertices and edges active at the given point or over the given interval. Usage network.extract(x, onset = NULL, terminus = NULL, length = NULL, at = NULL, rule = c("any", "all"), active.default = TRUE, retain.all.vertices = FALSE, trim.spells=FALSE) x %t% at Arguments x an object of class network. onset optionally, the start of the specified interval. This must be accompanied by one of terminus or length. terminus optionally, the end of the specified interval. This must be accompanied by one of onset or length. length optionally, the length of the specified interval. This must be accompanied by one of onset or terminus. at optionally, a single time point. rule a text string for defining “active” for this call: any if elements active at any time during the interval are to be used, or all if elements must be active over the entire interval. active.default logical; should elements without an activity attribute be regarded as active by default? retain.all.vertices logical; should the extracted network retain all vertices, ignoring the vertex ac- tivity spells of x in order to ensure that the network returned has the same size as x? trim.spells logical; should the spells of vertices, edges and their attributes in the extracted network be trimmed to match the query range? (Sensible thing to do, but could be expensive) Details For the purposes of extraction, edges are only considered active over some interval if: the edge itself is active over this time period, and both of the incident vertices are also active over the given time period. When retain.all.vertices=FALSE (the default), the function has the following behavior: • If at is used to specify the spell of interest, the returned network consists of all edges and vertices active at that time point. • If an interval is supplied to specify the spell (via onset and one of terminus or length), edges and vertices active over the specified interval are used. If rule="any", then edges and vertices active at any time during the interval are returned; otherwise, only those active during the entire period are returned. Vertices in the extracted network will have the same order as the original network, with inactive vertices removed. When retain.all.vertices=TRUE • All vertices are preserved in the output net to preserved network size and ids. • if trim.spells=TRUE, ’retained’ vertices will be marked as inactive (they will have ’null’ spell (Inf,Inf)) • Edges that are active (by the specified rule) during the specified spell are included in the returned network (same as above.) • Edges with one or more inactive vertices still will be removed (even if the vertex is being ’retained’ to preserve network size) If a net.obs.period network attribute is present, its observation spells will be truncated by the onset and terminus of extraction. If the onset and terminus do not intersect with any observation spells, the ‘$observations‘ component will be set to the ‘null‘ spell c(Inf,Inf). %t% (the temporal cross-section operator) is a simplified (and less flexible) wrapper for network.extract that returns the network of active vertices and edges at a given time point. Value A networkDynamic object containing the active edges and vertices for the specified spell, when retain.all.vertices=FALSE, otherwise the network object containing all vertices, and only those edges active for the specified spell. Note Note that only active vertices are included by default (retain.all.vertices=FALSE). As a result, the size of the extracted network may be smaller than the original. Vertex and edge ids will be translated, but may not correspond to their original values. If it is necessary to maintain the identities of vertices, see persistent.ids. Author(s) <NAME> <<EMAIL>>, skyebend See Also is.active, activity.attribute, network.extensions, and get.inducedSubgraph for a re- lated non-temporal version, network.collapse to squish a networkDynamic object into a static network Examples triangle <- network.initialize(3) # create a toy network # add edges with activity # first add an edge between vertices 1 and 2 add.edges.active(triangle,onset=0,terminus=10,tail=1,head=2) # add a more edges add.edges.active(triangle,onset=0,length=4,tail=2,head=3) add.edges.active(triangle,at=4.5,tail=3,head=1) # specify some vertex activity activate.vertices(triangle,onset=0,terminus=10) deactivate.vertices(triangle,onset=1,terminus=2,v=3) degree<-function(x){as.vector(rowSums(as.matrix(x)) + colSums(as.matrix(x)))} # handmade degree function degree(triangle) # degree of each vertex, ignoring time degree(network.extract(triangle,at=0)) degree(network.extract(triangle,at=1)) # just look at t=1 degree(network.extract(triangle,at=2)) degree(network.extract(triangle,at=5)) # watch out for empty networks! they are just an empty list t10 <- network.extract(triangle,at=10) t10 # notice difference between 'at' syntax and 'onset,terminus' # when network is not in discrete time degree(network.extract(triangle,at=4)) degree(network.extract(triangle,onset=4,terminus=5)) # the %t% (time) operator is like an alias for the 'at' extraction syntax degree(triangle%t%4) par(mfrow=c(2,2)) #show multiple plots plot(triangle,main='ignoring dynamics',displaylabels=TRUE) plot(network.extract(triangle,onset=1,terminus=2),main='at time 1',displaylabels=TRUE) plot(network.extract(triangle,onset=2,terminus=3),main='at time 2',displaylabels=TRUE) plot(network.extract(triangle,onset=5,terminus=6),main='at time 5',displaylabels=TRUE) networkDynamic Convert various forms of network timing information into networkDy- namic objects. Description Converts various forms of temporal data (spell matrices, togles, lists of networks ) describing dy- namics of vertices and edges into networkDynamic objects. Usage networkDynamic(base.net = NULL, edge.toggles = NULL, vertex.toggles =NULL, edge.spells = NULL, vertex.spells = NULL, edge.changes = NULL, vertex.changes = NULL, network.list = NULL, onsets = NULL, termini = NULL, vertex.pid = NULL, start = NULL, end = NULL, net.obs.period=NULL,verbose=TRUE,create.TEAs = FALSE, edge.TEA.names=NULL,vertex.TEA.names=NULL,...) Arguments base.net A network (or network-coearceable) object which will be used to define network- level properties (directedness,etc) of the output network. When constructing from toggles, the edges in base.net give the initially active set of edges and ver- tices that the activity states will be toggled from. Network and vertex attributes of base.net will be copied to output (unless they are overwritten by dynamic attributes with the same names) edge.spells A matrix or data.frame of spells specifying edge timing. Assumed to be [on- set,terminus,tail vertex.id, head vertex.id]. Any additional columns can loaded as dynamic attributes (see edge.TEA.names) vertex.spells A matrix or data.frame of spells specifying vertex timing. Assumed to be [on- set,terminus,vertex.id] edge.toggles A matrix or data.frame of toggles giving a sequence of activation and deactiva- tion times for toggles. Columns are assumed to be [toggle time, tail vertex id of the edge, head vertex id of the edge]. vertex.toggles A matrix or data.frame of toggles giving a sequence of activation and deactiva- tion times for vertices. Column order assumed to be [time,vertex.id] edge.changes A matrix or data.frame of edge changes with at least 4 columns, assumed to be [time, tail, head, direction] vertex.changes A matrix or data.frame of vertex changes with at least 3 columns, assumed to be [time, vertex.id,direction] network.list a list of network objects assumed to describe sequential panels of network ob- servations. Network sizes may vary if some vertices are only active in certain panels. See onsets, termini, vertex.pid. If base.net not specified, first element of list will be used as base.net. Network, vertex, and edge attributes will be converted to TEAs if create.TEAs=TRUE. onsets an optional array of onset times to be assigned to the network panels of net- work.list. defaults to seq(from=0,length=length(network.list)-1) termini an optional array of terminus times to be assigned to the network panels of network.list defaults to seq(from=1,length=length(network.list) vertex.pid an optional name of a vertex attribute to be used as a unique vertex identifier when constructing from a network list with different sized networks. start Optional argument to indicate the earliest time at which any changes in the net- work could have been observed or simulated; any spells before this time point are considered onset-censored. end Optional argument to indicate the latest time at which any changes in the net- work could have been observed or simulated; any spells after this time point are considered terminus-censored. net.obs.period Optional argument. A structured list for providing additional information about when and how the network was observed. verbose Logical, If TRUE (default), status message will be printed about the assumptions made in the conversion process. create.TEAs If TRUE, Dynamic TEA attributes will be created corresponding to the static attributes appear on the network elements of network.list edge.TEA.names an optional vector of names for the dynamic (TEA) edge attributes to be im- ported from the extra columns of edge.spells (if create.TEAs=TRUE) vertex.TEA.names an optional vector of names for the dynamic (TEA) vertex attributes to be im- ported from the extra columns of vertex.spells (if create.TEAs=TRUE) ... Additional arguments controlling the creating of the network or processing of attached data objects. Details This function provides ways to convert multiple forms of timing information for vertices and edges into network dynamic objects. Converting from lists of networks: If the timing information is provided in the form of a lists of networks (specified by the network.list argument ) the assumption is that each network is a discrete ‘panel’ observation indicating the active set vertices and edges. By default, each observa- tion is assumed to span a unit interval, (so the 1st goes from 0 to 1, 2nd from 1-2, etc). However, the onset and termini of each observation panel can be explicitly specified via the onsets and termini arguments. If the networks in network.list vary in size, the name of a vertex attribute to be used as a persistent id must be specified using the vertex.pid attribute so that the vertices in each network can be matched up correctly. If create.TEAs=TRUE, dynamic attributes will be created for any (non-default) attributes appearing in the list of networks. Otherwise, network and vertex attributes will be copied from the network specified via base.net. If base.net is not spec- ified, the first element of network.list will be used. A net.obs.period will be constructed to describe the range of observations used to construct the network, or one can be specified directly using the net.obs.period argument. Converting from matrices of spells, changes or toggles: Alternatively, timing information for edges and vertices can be provided separately as matrices or data.frames in the forms of tables of spells, changes, or toggles. For vertices, the arguments are vertex.spells, vertex.changes or vertex.toggles. The columns for each argument have a specific order and function, in- dicated in the argument definitions above. Edge arguments are named similarly edge.spells, edge.changes or edge.toggles. The vertex ids and ‘head’ and ‘tail’ ids must be integer index ids. Network properties (number of vertices, bipartite, directedness, etc) can currently be spec- ified by including a base.net argument to be used as a template, network and vertex attributes will be copied from base.net as well. If only edge information is provided, the network size will be imputed from the set of edge endpoints. In the edge.toggles case, the edges present in base.net provide the initial state to be toggled from. If a net.obs.period is not specified directly using the net.obs.period argument one will be constructed. Since the correct observation information is not known it may not describe the data accurately. Spells data will be assumed to be ’continuous’ and where toggles and changes will be assumed to be ’discrete’ and the net.obs.period$observations may include infinate values indicating unknown bounds. When constructing a network with separate sources of data for vertex and edge timing, edge and vertex activity will not be made consistent if input data is inconsistent – edges may be ac- tive when their incident vertices are inactive, etc. These situations can be detected using the network.dynamic.check function and possible resolved using one of the reconcile.activity functions. Curently, dynamic attributes (TEAs, see attribute.activity.functions) for edges or ver- tices (with onset and termination times matching those of the edge or vertex spell) can be loaded in by by setting create.TEAs=TRUE and including additional columns in the edge.spells or vertex.spells argument and specifying a vector of names for the attributes with edge.TEA.names or vertex.TEA.names. Note that when using a data.frame to pass in non-numeric attributes, the default behavior of converting strings to factors should be avoided. Value A networkDynamic object with vertex and edge timing specified by the input data. It will also print out information about the assumptions it makes while constructing the network. Note This function provides the features that were formerly (in versions < 0.4) called using as.networkDynamic.* syntax. Author(s) <NAME> <EMAIL>, skyebend, statnet team See Also See Also as get.edge.activity,get.vertex.activity, network.dynamic.check Examples # construct network out of a list of panels of varying sizes # omiting missing day 25 data(windsurferPanels) dynBeach<-networkDynamic(network.list=beach[-25], vertex.pid="vertex.names", onsets=c(1:24,26:31),termini=c(2:25,27:32)) # read in tsv files for vertex and edge spells and # construct network of McFarland classroom interaction data # see ?cls33_10_16_96 for more info about this data set # read vertex data rawVerts<-read.table(paste(path.package('networkDynamic'), "/extdata/cls33_10_16_96_vertices.tsv",sep=''),header=TRUE) # peek at column headings to find ids and times names(rawVerts) # read in interation (edge) data rawEdges<-read.table(paste(path.package('networkDynamic'), "/extdata/cls33_10_16_96_edges.tsv",sep=''),header=TRUE) # peek at column headings to find ids and times names(rawEdges) # construct network using vertex and edge timing information cls33 <-networkDynamic(vertex.spells=rawVerts[,c(3,4,1)], edge.spells=rawEdges[,c(3,4,1,2)]) # add in the unchanging vertex attribute data set.vertex.attribute(cls33,"sex",as.vector(rawVerts$sex)) set.vertex.attribute(cls33,"role",as.vector(rawVerts$role)) ## Not run: # takes 5 seconds, too slow for CRAN checks # loop over edge data to add the dynamic attributes on the edge for(r in 1:nrow(rawEdges)){ # get the id of the edge from its tail and head eid <- get.edgeIDs(cls33,v=rawEdges$from_vertex_id[r], alter=rawEdges$to_vertex_id[r]) activate.edge.attribute(cls33,'interaction_type',rawEdges$interaction_type[r], onset=rawEdges$start_minute[r],terminus=rawEdges$end_minute[r],e=eid) activate.edge.attribute(cls33,'weight',rawEdges$weight[r], onset=rawEdges$start_minute[r],terminus=rawEdges$end_minute[r],e=eid) } # convert the set of newcomb panels with rank weights data(newcomb) newRankDyn <-networkDynamic(network.list=newcomb.rank) get.network.attribute.active(newRankDyn,'title',at=3) as.matrix(network.collapse(newRankDyn,at=5),attrname='rank') ## End(Not run) Newcomb Newcomb’s Fraternity Networks Description These 14 networks record weekly sociometric preference rankings from 17 men attending the Uni- versity of Michigan in the fall of 1956; Data were collected longitudinally over 15 weeks, although data from week 9 are missing. The men were recruited to live in off-campus (fraternity) housing, rented for them as part of the Michigan Group Study Project supervised by <NAME> from 1953 to 1956. All were incoming transfer students with no prior acquaintance of one another. The data set contains two longitudinal networks as network.list. newcomb.rank is a network.list object with 14 networks. Each network is complete and the edge value rank is the preference of the ith men for the jth man from 1 through 16. A 1 indicates first preference, and no ties were allowed. newcomb is a network.list object that has binary edge values but is similar in structure to newcomb.rank and derived from it. Each network has a tie from the ith men to the jth man if i had a preference for j of 8 or less. Otherwise there is not tie from i to j. Note that since these are ranks, the degree of each vertex (and the total number of edges) does not vary over time Usage data(newcomb) Details Use data(package="netdata") to get a full list of networks. Licenses and Citation If the source of the data set does not specified otherwise, this data set is protected by the Creative Commons License https://creativecommons.org/licenses/by-nc-nd/2.5/. When publishing results obtained using this data set the original authors should be cited. In addition this package should be cited as: <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. 2003 statnet: An R package for the Statistical Modeling of Social Networks https://statnet.org/ and the source should be cited as: <NAME> and <NAME> (2006): Pajek datasets http://vlado.fmf.uni-lj.si/pub/networks/data/ Source http://vlado.fmf.uni-lj.si/pub/networks/data/ucinet/ucidata.htm#newfrat References See the link above. <NAME>. (1961). The acquaintance process. New York: Holt, Reinhard and Winston.\ <NAME>. (1958). A longitudinal study of interpersonal attraction in a natural group setting. Unpublished doctoral dissertation, University of Michigan.\ <NAME>., <NAME>. and <NAME>. (1977). Social structure from multiple networks, I. Blockmodels of roles and positions. American Journal of Sociology, 81, 730-780. See Also network, sna Examples data(newcomb) persistent.ids Use and manipulate persistent ids of network elements Description Persistent ids (pids) are unique values attached to vertices or edges which remain unchanged through- out network manipulation and extraction processes. The “vertex.pid” of a vertex is an overall data- set id, unlike the “vertex.id” which is an index dependent on network size. These functions provide ways to look up vertex.pids from vertex.ids (and the other way around) and also provide necessary modifications to some standard network functions to safely work with pids. Usage get.vertex.id(nd, pid) get.vertex.pid(nd, id) get.edge.id(nd, pid) get.edge.pid(nd, id) initialize.pids(nd) vertex.pid.check(nd) edge.pid.check(nd) Arguments nd a network or networkDynamic object to be modified pid persistent id(s) of the network element(s) for which the network-specific id(s) should be returned id network-specific (index) id(s) of the network element for which the persistent id(s) should be returned Details The persistent id functionality is an optional feature of networkDynamic objects. If a network-level attribute named vertex.pid exists, its value is required to be the name of a vertex attribute that can safely be used as a vertex.pid. If it is set to NULL, pids will be ignored. A vertex.pid must have a unique value for all vertices. Persistent ids for edges function in the same way, except the attribute is named edge.pid. Some existing network code uses the vertex.names attributes of networks as a persistent id without checking that it is unique. It is possible to indicate that vertex.names can safely be used as a vertex.pid by setting vertex.pid to 'vertex.names' The function initialize.pids can be used to create a set of pids on all existing vertices (named vertex.pid and edges named edge.pid). The pids are currently initialized with pseudo-random hex strings using the tempfile function (something like '4ad912252bc2'). It is especially useful if called after a network object as been constructed and before any extractions are performed. The element addition functions (add.vertices) override their network-package counterparts in order to permit assigning pids to newly-added elements if the pid is defined. They can be defined by the user with the vertex.pids argument, or, if not specified, a unique random id will be generated. (Note that any new values added by default to a vertex.names pid will not be numeric.) Some of the import/conversion methods may set pids. See network. User-specified pids are checked for uniqueness. The the current auto-generated pid implementation produces ids that are unique within the current network. They are also almost certain to be unique within an R session (so that vertices will have a unique id if added and removed) and quite likely across sessions, but we need more details on the tempfile’s implementation. With the exception of the "check" utilities, all of these functions modify their network argument in place. Value Get methods: • get.vertex.id returns the vertex.id(s) of vertices corresponding to the vertex.pid(s) pro- vided. • get.vertex.pid returns the vertex.pid(s) of vertices corresponding to the vertex.id(s) pro- vided. • get.edge.id returns the edge.id(s) of edge corresponding to the edge.pid(s) provided. • get.edge.pid returns the edge.pid(s) of edges corresponding to the edge.id(s) provided. Each of the above return NA values where no match is found. • vertex.pid.check throws an error if the vertex.pid is found to not meet specifications. Otherwise returns TRUE or FALSE and gives a warning if vertex.pid does not exist • edge.pid.check throws an error if the edge.pid is found to not meet specifications. Other- wise returns TRUE or FALSE and gives a warning if edge.pid does not exist Note Adding edges via the extraction/replacement operators [,] bypasses the pid code and will break the edge pids defined for the network. Similarly, add.vertices.active and add.edges.active do not yet support including pids. Author(s) lxwang, skyebend, the statnet team See Also See also add.vertices in network. Examples # use vertex.names as a persistent id net<-network.initialize(5) set.network.attribute(net, 'vertex.pid','vertex.names') # find original vertex corresponding to vertex in smaller extracted net haystack<-network.initialize(30) activate.vertices(haystack,v=10:20) # hide a needle somewhere in the haystack set.vertex.attribute(haystack,'needle',TRUE,v=sample(1:30,1)) # set up the persistand ids with defaults initialize.pids(haystack) # some hay is removed over time ... newstack<-network.extract(haystack,at=100,active.default=FALSE) network.size(newstack) # we find the needle! needleId <-which(get.vertex.attribute(newstack,'needle')) needleId # which vertex is the corresponding one in original stack? oldId<-get.vertex.id(haystack,get.vertex.pid(newstack,needleId)) oldId # check if we got it right.. get.vertex.attribute(haystack,'needle')[oldId] # one reason you wouldn't want to use ordinary vertex.names net<-network.initialize(3) add.vertices(net,3) network.vertex.names(net) # but if you make it a persistant id, new names will be created net<-network.initialize(3) set.network.attribute(net,'vertex.pid','vertex.names') add.vertices(net,3) network.vertex.names(net) # try with edges and add/remove vertices net <-network.initialize(10) add.edges(net,1:9,2:10) set.edge.attribute(net,'test',"you found me!",e=7) initialize.pids(net) changed<-net add.vertices(changed,5) delete.vertices(changed,c(1,3,5,15)) delete.edges(changed,eid=1:3) # which edge in changed corresponds to edge 7 in net? network.edgecount(changed) get.edge.id(changed,get.edge.pid(net,7)) # actually, they are the same because of NULL edges in edgelist get.edge.attribute(changed,'test',unlist=FALSE)[[7]] # however, the ids of the vertices have changed changed$mel[[7]]$inl net$mel[[7]]$inl # do they still match up? get.vertex.pid(changed,changed$mel[[7]]$inl)==get.vertex.pid(net,net$mel[[7]]$inl) print.networkDynamic Provide a view of a networkDynamic object including timing informa- tion Description Prints out some very basic descriptive stats about the network’s dynamics, and the the normal in- formation printed for network objects. Usage ## S3 method for class 'networkDynamic' print(x, ...) Arguments x an object of class networkDynamic including dynamic relational information ... Details Prints some info about the number of time events in a networkDynamic object, then calls print.network Value Returns the networkDynamic object passed to the function. Note Only prints out the network information without any dynamic data. Author(s) Pavel See Also print.network Examples library(networkDynamic) data(flo) net1 <- network(flo) activate.edges(net1, onset=1:20, terminus=101:120) activate.vertices(net1, at=seq(2,32,2)) print(net1) read.son Read .son-formatted (SoNIA) input files containing longitudinal net- work data and create a corresponding networkDynamic object Description A .son file is a tab-separated text file with two sections, the first describing node attribute events and the second arc attribute events. Each section has a set of defined column names as a header. See the SoNIA file specification for more information: https://sourceforge.net/p/sonia/wiki/Son_ format/. Usage read.son(file, guess.TEA=TRUE) Arguments file path to the file to be read guess.TEA logical: should the parser guess that non-changing attribute values are intended to be static instead of TEAs? Details Uses networkDynamic internally to build a dynamic network out of an array of vertex spells and an array of edge spells. Vertex and edge attributes will be attached, usually as TEA. However, If the values of an attribute never change, they will be attached as a static attribute. This is convenient but will be incorrect if a value was intended to be defined for only a single spell matching with the vertex activation. Setting guess.TEA=FALSE will force all attributes to be loaded as TEAs (slower). Value A network dynamic object with vertex and edge durations and attributes corresponding the the spells defined in the input file. Note The current version of this function does not support reading clusters. Author(s) <NAME> References https://sourceforge.net/p/sonia/wiki/Son_format/. See Also See Also networkDynamic Examples classroom<-read.son(system.file('extdata/cls33_10_16_96.son',package='networkDynamic')) reconcile.activity Modify the activity spells of vertices to match incident edges or the other way around Description When networkDynamic objects are created from real-world data it is often the case that activity in- formation for vertices and edges may not come from the same source and may not match up exactly. Vertices may be inactive when incident edges are active, etc. The reconcile.vertex.activity function modifies the activity of a network’s vertices acording to the mode specified, while reconcile.edge.activity performs similar operations for edges. Usage reconcile.vertex.activity(net, mode = c ("expand.to.edges", "match.to.edges", "encompass.edges"), edge.active.default = TRUE) reconcile.edge.activity(net, mode = c("match.to.vertices", "reduce.to.vertices"), active.default = TRUE) Arguments net a networkDynamic object mode string indicating the method for reconciling edge.active.default boolean, should edges with no definied activity be considered active? active.default boolean, should vertices with no definied activity be considered active? Details The mode argument takes the following values: match.to.edges vertices will be modified so as to be only active when incident edges are active. Existing vertex spells are deleted. • expand.to.edges vertices activity will be expanded to include the activity periods of any incident edges (still permits isolated vertices). Existing vertex spells are preserved. • encompass.edges vertices activity will be modified so that it has a single spell beginning with the earliest incident edge activity, and encompasses the last edge activity. (Note that this implies that isolated vertices will become inactive). • match.to.vertices edges will be modified so as to be active whenever all incident vertices are active. Existing inactive edges will be activated if necessary. • reduce.to.vertices edges will be modified so as to have no active spells when incident vertices are inactive. Inactive edges will not be activated. Value The input networkDynamic object is modified in place and returned invisibly. Author(s) skyebend, lxwang Examples nd<-network.initialize(6) add.edges.active(nd,tail=1:3,head=2:4,onset=1,terminus=3) add.edges.active(nd,tail=4,head=1,onset=5,terminus=7) add.edge(nd,tail=1,head=6) # before get.vertex.activity(nd,as.spellList=TRUE) reconcile.vertex.activity(nd) # after get.vertex.activity(nd,as.spellList=TRUE) # induce edge activity for known vertex timing nd<-network.initialize(4,directed=FALSE) activate.vertices(nd,onset=1:4,terminus=3:6) nd[,]<-1 get.edge.activity(nd,as.spellList=TRUE) reconcile.edge.activity(nd, mode="reduce.to.vertices") get.edge.activity(nd,as.spellList=TRUE) spells.overlap Functions to compare and search spell intervals Description spells.overlap checks if two spells overlap at all, spells.hit searches a spell matrix for an overlapping spell Usage spells.overlap(s1, s2) spells.hit(needle, haystack) search.spell(needle, haystack) Arguments s1 First spell for in the comparison, must be a two-element numeric vector in the form [onset,terminus] s2 Second spell for in the comparison, must be a two-element numeric vector in the form [onset,terminus] needle The query spell used in the search, must be a two-element numeric vector in the form [onset,terminus] haystack The spell matrix to be searched by needle. Must be two column numeric matrix meeting the order specifications of a spell matrix. See activity.attribute Details Spell overlap is defined as true if one of the following conditions sets is met, otherwise false: onset1 >= onset2 AND onset1 < terminus2 terminus1 > onset2 AND terminus1 <= terminus2 onset1 <= onset2 AND terminus1 >= terminus2 Value spells.overlap returns a boolean indicating if the two spells overlap or not. spells.hit returns the integer row index of the first (earliest) spell in haystack that overlaps with needle, or -1 if no overlaps are found search.spell returns a vector containing the row indices of spells in haystack that overlap with needle, or numeric(0) if none found Author(s) <EMAIL> See Also See Also activity.attribute Examples a <- c(1,3) b <- c(2,5.5) c <- c(-1,10) d <- c(4,4) spells.overlap(a,b) spells.overlap(b,c) spells.overlap(a,d) spellmat <- rbind(c(0,1), c(1,2), c(2,3)) spells.hit(c(1,2),spellmat) when.vertex.attrs.match return the times at which the TEA attributes of elements of a network match a value Description The functions query the TEA attributes of network elements (vertices or edges) and return the time that each element matches the specified value. The match operator defaults to ’==’, but other binary comparison operators that return logical, such as ’>’ or even ’%in%’ can be used as well. Usage when.vertex.attrs.match(nd, attrname, value, match.op = "==", rule = "earliest", no.match = Inf, v = seq_len(network.size(nd))) when.edge.attrs.match(nd, attrname, value, match.op = "==", rule = "earliest", no.match = Inf, e = seq_along(nd$mel)) Arguments nd a networkDynamic object attrname character name of the TEA attribute to be queried value the value to be passed to the comparison operator to be matched against the TEA values match.op the binary operator to be used in determining a match (defaults to ’==’) rule character giving the name of the rule to determine what value should be returned from the spell of matching attributes. Options are 'earliest' (the default) and 'latest' which will return the onset and terminus of the spell respectively. no.match The value to be returned when the TEA attribute never matches value. Default is Inf, NA may be useful as well. v possible numeric vector of vertex ids indicating a subset of vertices to be queried e possible numeric vector of edge ids indicating a subset of edges to be queried Details The no.match argument is included to make it possible for user to distinguish cases where the attribute is missing from the network element (which will return NA) from cases where the value of the attribute never matches value according to the operation match.op Value A numeric vector of attribute onset times (if rule='earliest') or termination times (if rule='latest') Note this is a draft implementation, suggestions on function and argument names welcome. Author(s) skyebend See Also See also attribute.activity.functions Examples # create a network with TEA attribute net<-network.initialize(5) net<-activate.vertex.attribute(net,'test','A',onset=0,terminus=2) net<-activate.vertex.attribute(net,'test','B',onset=2,terminus=3) net<-activate.vertex.attribute(net,'test','C',onset=4,terminus=5) net<-activate.vertex.attribute(net,'weight',0,onset=-Inf,terminus=Inf) net<-activate.vertex.attribute(net,'weight',-1,at=6,v=2) # when does 'test' take the value 'B' for each vertex? when.vertex.attrs.match(net,'test',value='B') # when is the terminus of when 'test' takes a value 'A' or 'C'? when.vertex.attrs.match(net,'test',value=c('A','C'),match.op='%in%',rule='latest') # when does 'weight' first take a value less than 0? when.vertex.attrs.match(net,'weight',value=0,match.op='<') windsurfers Lin Freeman’s Dynamic Network of Windsurfer Social Interactions Description A dynamic network object describing daily social interactions between windsurfers on California beaches over a months time. Collected by <NAME> in 1988. Usage data(windsurfers) Format The format is is a networkDynamic object with node and edge activity.attributes defined by spell matricies. Details The data in this network was originally collected and analyzed in aggregate by Freeman et al. (1988) and has since been used in a number of influential articles (see Cornwell, 2009; Hummon and Doreian, 2003; Zeggelink et al., 1996, etc.). While this network is typically analyzed in aggregate, it was originally collected as a dynamically evolving network (where the vertex set is composed of windsurfers and the edge set is composed of interpersonal communication). The network was collected daily (sampled at two time points each day) for 31 days (August 28, 1986 to September 27,1986). From Almquist and Butts, 201: "Individuals were tracked with a unique ID, and were divided by Freeman et al. into those we will here call, ’regulars’ (N = 54) – frequent attendees who were well-integrated into the social life of the beach community – and ’irregulars’ (N = 41) on ethnographic grounds. The former category was further broken down by the researchers into two groups, Group 1 (N = 22) and Group 2 (N = 21), with 11 individuals not classified as belonging to either Group 1 or Group 2. Altogether, the union of vertex sets (Vmax ) consists of 95 individuals. On any given day during the observation period, the number of windsurfers appearing on the beach ranged from 3 to 37, with the number of communication ties per day ranging from 0 to 96." The dynamicNetwork object was created from a list of network objects (length 31, but there is one missing entry index 25 marked with an NA). Each list entry is labeled 828, 829 ... 927 – this corresponds to the date the network was collected. Vertex attributes include: group1, group2, regular, vertex.names – group1, group2, and regular are ethnographically defined (and are simply dummies in this case, i.e., 0/1), and vertex.names is the original code number used by Lin. This are static vertex attributes. The original set of static networks have been merged into a single dynamic network object with vertex activity coded in a spell matrix following the conventions of networkDynamic objects. There is very high daily turnover of who is present on the beach on each day. Several dynamic network level attributes (e.g., list.network.attributes) have been added by Zack Almquist. These include: • atmp atmospheric temperature. • cord Grid location on the beach. • day simply the Monday/Tuesday/etc labeling. • gst ground surface temperature (celsius). • week week is the position within the month (e.g., first week in august) • wspd Wind speed from noaa.gov. • wvht Wave height noaa.gov. atm, gst, wspd, wvht are from the national atmospheric data (noaa.gov) and come from the closest beach that had accurate weather data. Day of week is relevant because weekly periodicity of the nodeset is quite high. Source Dr. <NAME> (Research Professor UCI) and <NAME> (Graduate Student, UCI) References Almquist, <NAME>. and Butts, <NAME>. (2011). "Logistic Network Regression for Scalable Analysis of Networks with Joint Edge/Vertex Dynamics." IMBS Technical Report MBS 11-03, University of California, Irvine. <NAME>., <NAME>., <NAME>., 1988. "On human social intelligence." Journal of Social Biological Structure 11, 415–425. Examples data(windsurfers) data(windsurferPanels)
orf
cran
R
Package ‘orf’ October 14, 2022 Type Package Title Ordered Random Forests Version 0.1.4 Date 2022-07-21 Author <NAME> [aut, cre], <NAME> [ctb] Maintainer <NAME> <<EMAIL>> Description An implementation of the Ordered Forest estimator as developed in Lechner & Okasa (2019) <arXiv:1907.02436>. The Ordered Forest flexibly estimates the conditional probabilities of models with ordered categorical outcomes (so-called ordered choice models). Additionally to common machine learning algorithms the 'orf' package provides functions for estimating marginal effects as well as statistical inference thereof and thus provides similar output as in standard econometric models for ordered choice. The core forest algorithm relies on the fast C++ forest implementation from the 'ranger' package (Wright & Ziegler, 2017) <arXiv:1508.04409>. License GPL-3 Encoding UTF-8 LazyData true Depends R (>= 2.10) Imports ggplot2, ranger, Rcpp, stats, utils, xtable RoxygenNote 7.2.1 Suggests knitr, rmarkdown, testthat VignetteBuilder knitr URL https://github.com/okasag/orf BugReports https://github.com/okasag/orf/issues LinkingTo Rcpp NeedsCompilation yes Repository CRAN Date/Publication 2022-07-23 22:40:02 UTC R topics documented: orf-packag... 2 margin... 3 margins.or... 4 odat... 6 or... 8 plot.or... 11 predict.or... 12 print.margins.or... 13 print.or... 14 print.orf.predictio... 15 summary.margins.or... 16 summary.or... 18 summary.orf.predictio... 19 orf-package orf: Ordered Random Forests Description An implementation of the Ordered Forest estimator as developed in Lechner & Okasa (2019). The Ordered Forest flexibly estimates the conditional probabilities of models with ordered categorical outcomes (so-called ordered choice models). Additionally to common machine learning algorithms the orf package provides functions for estimating marginal effects as well as statistical inference thereof and thus provides similar output as in standard econometric models for ordered choice. The core forest algorithm relies on the fast C++ forest implementation from the ranger package (Wright & Ziegler, 2017). Author(s) <NAME>, <NAME> References • <NAME>., & <NAME>. (2019). Random Forest Estimation of the Ordered Choice Model. arXiv preprint arXiv:1907.02436. https://arxiv.org/abs/1907.02436 • <NAME>., <NAME>., <NAME>., & <NAME>. (2021). Predicting Match Outcomes in Football by an Ordered Forest Estimator. A Modern Guide to Sports Economics. Edward Elgar Publishing, 335-355. doi:10.4337/9781789906530.00026 • <NAME>. & <NAME>. (2017). ranger: A fast implementation of random forests for high dimensional data in C++ and R. J Stat Softw 77:1-17. doi:10.18637/jss.v077.i01. Examples ## Ordered Forest require(orf) # load example data data(odata) # specify response and covariates Y <- as.numeric(odata[, 1]) X <- as.matrix(odata[, -1]) # estimate Ordered Forest with default settings orf_fit <- orf(X, Y) # print output of the orf estimation print(orf_fit) # show summary of the orf estimation summary(orf_fit) # plot the estimated probability distributions plot(orf_fit) # predict with the estimated orf predict(orf_fit) # estimate marginal effects of the orf margins(orf_fit) margins Marginal Effects Description S3 generic method for estimation of marginal effects of an Ordered Forest objects of class orf. Usage margins(forest, eval = NULL, inference = NULL, window = NULL, newdata = NULL) Arguments forest estimated Ordered Forest object of class orf eval string, defining evaluation point for marginal effects. These can be one of "mean", "atmean", or "atmedian". (Default is "mean") inference logical, if TRUE inference on marginal effects will be conducted (default is inherited from the orf object) window numeric, share of standard deviation of X to be used for evaluation of the marginal effect (default is 0.1) newdata numeric matrix X containing the new observations for which the marginal ef- fects should be estimated Author(s) <NAME> See Also margins.orf, summary.margins.orf and print.margins.orf Examples ## Ordered Forest require(orf) # load example data data(odata) # specify response and covariates Y <- as.numeric(odata[, 1]) X <- as.matrix(odata[, -1]) # estimate Ordered Forest orf_fit <- orf(X, Y) # estimate default marginal effects of the orf orf_margins <- margins(orf_fit) margins.orf Marginal Effects for the Ordered Forest Description S3 method for estimation of marginal effects of an Ordered Forest objects of class orf. Usage ## S3 method for class 'orf' margins(forest, eval = NULL, inference = NULL, window = NULL, newdata = NULL) Arguments forest estimated Ordered Forest object of class orf eval string, defining evaluation point for marginal effects. These can be one of "mean", "atmean", or "atmedian". (Default is "mean") inference logical, if TRUE inference on marginal effects will be conducted (default is inherited from the orf object) window numeric, share of standard deviation of X to be used for evaluation of the marginal effect (default is 0.1) newdata numeric matrix X containing the new observations for which the marginal ef- fects should be estimated Details margins.orf estimates marginal effects at the mean, at the median, or the mean marginal effects, depending on the eval argument. It is advised to increase the number of subsampling replications in the supplied orf object as the estimation of the marginal effects is a more demanding exercise than a simple Ordered Forest estimation/prediction. Additionally to the estimation of the marginal effects, the weight-based inference for the effects is supported as well. Note, that the inference procedure is much more computationally exhausting exercise due to the computation of the forest weights. Additionally, the evaluation window for the marginal effects can be regulated through the window argument. Furthermore, new data for which marginal effects should be computed can be supplied as well as long as it lies within the support of X. Value object of type margins.orf with following elements info info containing forest inputs and data used effects marginal effects variances variances of marginal effects errors standard errors of marginal effects tvalues t-values of marginal effects pvalues p-values of marginal effects Author(s) <NAME> See Also summary.margins.orf, print.margins.orf Examples ## Ordered Forest require(orf) # load example data data(odata) # specify response and covariates Y <- as.numeric(odata[, 1]) X <- as.matrix(odata[, -1]) # estimate Ordered Forest orf_fit <- orf(X, Y) # estimate marginal effects of the orf (default) orf_margins <- margins(orf_fit) # estimate marginal effects evaluated at the mean orf_margins <- margins(orf_fit, eval = "atmean") # estimate marginal effects with inference # (orf object has to be estimated with honesty and subsampling) orf_margins <- margins(orf_fit, inference = TRUE) # estimate marginal effects with custom window size orf_margins <- margins(orf_fit, window = 0.5) # estimate marginal effects for some new data (within support of X) orf_margins <- margins(orf_fit, newdata = X[1:10, ]) # estimate marginal effects with all custom settings orf_margins <- margins(orf_fit, eval = "atmedian", inference = TRUE, window = 0.5, newdata = X[1:10, ]) odata Simulated Example Dataset Description A simulated example dataset with ordered categorical outcome variable containing different types of covariates for illustration purposes. Usage odata Format A data frame with 1000 rows and 5 variables Details For the exact data generating process, see the example below. Value Y ordered outcome, classes 1, 2, and 3 X1 continuous covariate, N(0,1) X2 categorical covariate, values 1, 2, and 3 X3 binary covariate, values 0 and 1 X4 continuous covariate, N(0,10) Examples # generate example data # set seed for replicability set.seed(123) # number of observations n <- 1000 # various covariates X1 <- rnorm(n, 0, 1) # continuous X2 <- rbinom(n, 2, 0.5) # categorical X3 <- rbinom(n, 1, 0.5) # dummy X4 <- rnorm(n, 0, 10) # noise # bind into matrix X <- as.matrix(cbind(X1, X2, X3, X4)) # deterministic component deterministic <- X1 + X2 + X3 # generate continuous outcome with logistic error Y <- deterministic + rlogis(n, 0, 1) # thresholds for continuous outcome cuts <- quantile(Y, c(0, 1/3, 2/3, 1)) # discretize outcome into ordered classes 1, 2, 3 Y <- as.numeric(cut(Y, breaks = cuts, include.lowest = TRUE)) # save data as a dataframe odata <- as.data.frame(cbind(Y, X)) # end of data generating orf Ordered Forest Estimator Description An implementation of the Ordered Forest estimator as developed in Lechner & Okasa (2019). The Ordered Forest flexibly estimates the conditional probabilities of models with ordered categorical outcomes (so-called ordered choice models). Additionally to common machine learning algorithms the orf package provides functions for estimating marginal effects as well as statistical inference thereof and thus provides similar output as in standard econometric models for ordered choice. The core forest algorithm relies on the fast C++ forest implementation from the ranger package (Wright & Ziegler, 2017). Usage orf( X, Y, num.trees = 1000, mtry = NULL, min.node.size = NULL, replace = FALSE, sample.fraction = NULL, honesty = TRUE, honesty.fraction = NULL, inference = FALSE, importance = FALSE ) Arguments X numeric matrix of features Y numeric vector of outcomes num.trees scalar, number of trees in a forest, i.e. bootstrap replications (default is 1000 trees) mtry scalar, number of randomly selected features (default is the squared root of num- ber of features, rounded up to the nearest integer) min.node.size scalar, minimum node size, i.e. leaf size of a tree (default is 5 observations) replace logical, if TRUE sampling with replacement, i.e. bootstrap is used to grow the trees, otherwise subsampling without replacement is used (default is set to FALSE) sample.fraction scalar, subsampling rate (default is 1 for bootstrap and 0.5 for subsampling) honesty logical, if TRUE honest forest is built using sample splitting (default is set to TRUE) honesty.fraction scalar, share of observations belonging to honest sample not used for growing the forest (default is 0.5) inference logical, if TRUE the weight based inference is conducted (default is set to FALSE) importance logical, if TRUE variable importance measure based on permutation is con- ducted (default is set to FALSE) Details The Ordered Forest function, orf, estimates the conditional ordered choice probabilities, i.e. P[Y=m|X=x]. Additionally, weight-based inference for the probability predictions can be conducted as well. If inference is desired, the Ordered Forest must be estimated with honesty and subsampling. If predic- tion only is desired, estimation without honesty and with bootstrapping is recommended for optimal prediction performance. In order to estimate the Ordered Forest user must supply the data in form of matrix of covariates X and a vector of outcomes ’codeY to the orf function. These data inputs are also the only inputs that must be specified by the user without any defaults. Further optional arguments include the classical forest hyperparameters such as number of trees, num.trees, number of randomly selected features, mtry, and the minimum leaf size, min.node.size. The forest building scheme is regulated by the replace argument, meaning bootstrapping if replace = TRUE or subsampling if replace = FALSE. For the case of subsampling, sample.fraction argument regulates the subsampling rate. Further, honest forest is estimated if the honesty argument is set to TRUE, which is also the default. Similarly, the fraction of the sample used for the honest estimation is regulated by the honesty.fraction argument. The default setting conducts a 50:50 sample split, which is also generally advised to follow for optimal performance. Inference procedure of the Ordered Forest is based on the forest weights and is controlled by the inference argument. Note, that such weight-based inference is computationally demanding exercise due to the estimation of the forest weights and as such longer computation time is to be expected. Lastly, the importance argument turns on and off the permutation based variable importance. orf is compatible with standard R commands such as predict, margins, plot, summary and print. For further details, see examples below. Value object of type orf with following elements forests saved forests trained for orf estimations (inherited from ranger) info info containing forest inputs and data used predictions predicted values for class probabilities variances variances of predicted values importance weighted measure of permutation based variable importance accuracy oob measures for mean squared error and ranked probability score Author(s) <NAME> References • <NAME>., & <NAME>. (2019). Random Forest Estimation of the Ordered Choice Model. arXiv preprint arXiv:1907.02436. https://arxiv.org/abs/1907.02436 • <NAME>., <NAME>., <NAME>., & <NAME>. (2021). Predicting Match Outcomes in Football by an Ordered Forest Estimator. A Modern Guide to Sports Economics. Edward Elgar Publishing, 335-355. doi:10.4337/9781789906530.00026 • <NAME>. & <NAME>. (2017). ranger: A fast implementation of random forests for high dimensional data in C++ and R. J Stat Softw 77:1-17. doi:10.18637/jss.v077.i01. See Also summary.orf, plot.orf predict.orf, margins.orf Examples ## Ordered Forest require(orf) # load example data data(odata) # specify response and covariates Y <- as.numeric(odata[, 1]) X <- as.matrix(odata[, -1]) # estimate Ordered Forest with default parameters orf_fit <- orf(X, Y) # estimate Ordered Forest with own tuning parameters orf_fit <- orf(X, Y, num.trees = 2000, mtry = 3, min.node.size = 10) # estimate Ordered Forest with bootstrapping and without honesty orf_fit <- orf(X, Y, replace = TRUE, honesty = FALSE) # estimate Ordered Forest with subsampling and with honesty orf_fit <- orf(X, Y, replace = FALSE, honesty = TRUE) # estimate Ordered Forest with subsampling and with honesty # with own tuning for subsample fraction and honesty fraction orf_fit <- orf(X, Y, replace = FALSE, sample.fraction = 0.5, honesty = TRUE, honesty.fraction = 0.5) # estimate Ordered Forest with subsampling and with honesty and with inference # (for inference, subsampling and honesty are required) orf_fit <- orf(X, Y, replace = FALSE, honesty = TRUE, inference = TRUE) # estimate Ordered Forest with simple variable importance measure orf_fit <- orf(X, Y, importance = TRUE) # estimate Ordered Forest with all custom settings orf_fit <- orf(X, Y, num.trees = 2000, mtry = 3, min.node.size = 10, replace = TRUE, sample.fraction = 1, honesty = FALSE, honesty.fraction = 0, inference = FALSE, importance = FALSE) plot.orf Plot of the Ordered Forest Description plot the probability distributions estimated by the Ordered Forest object of class orf Usage ## S3 method for class 'orf' plot(x, ...) Arguments x estimated Ordered Forest object of class orf ... further arguments (currently ignored) Details plot.orf generates probability distributions, i.e. density plots of estimated ordered probabilities by the Ordered Forest for each outcome class considered. The plots effectively visualize the estimated probability density in contrast to a real observed ordered outcome class and as such provide a visual inspection of the overall in-sample estimation accuracy. The dashed lines locate the means of the respective probability distributions. Author(s) <NAME> Examples # Ordered Forest require(orf) # load example data data(odata) # specify response and covariates Y <- as.numeric(odata[, 1]) X <- as.matrix(odata[, -1]) # estimate Ordered Forest orf_fit <- orf(X, Y) # plot the estimated probability distributions plot(orf_fit) predict.orf Prediction of the Ordered Forest Description Prediction for new observations based on estimated Ordered Forest of class orf Usage ## S3 method for class 'orf' predict(object, newdata = NULL, type = NULL, inference = NULL, ...) Arguments object estimated Ordered Forest object of class orf newdata numeric matrix X containing the observations for which the outcomes should be predicted type string, specifying the type of the prediction, These can be either "probs" or "p" for probabilities and "class" or "c" for classes. (Default is "probs"). inference logical, if TRUE variances for the predictions will be estimated (only feasible for probability predictions). ... further arguments (currently ignored) Details predict.orf estimates the conditional ordered choice probabilities, i.e. P[Y=m|X=x] for new data points (matrix X containing new observations of covariates) based on the estimated Ordered Forest object of class orf. Furthermore, weight-based inference for the probability predictions can be conducted as well. If inference is desired, the supplied Ordered Forest must be estimated with honesty and subsampling. If prediction only is desired, estimation without honesty and with bootstrapping is recommended for optimal prediction performance. Additionally to the probability predictions, class predictions can be estimated as well using the type argument. In this case, the predicted classes are obtained as classes with the highest predicted probability. Value object of class orf.prediction with following elements info info containing forest inputs and data used predictions predicted values variances variances of predicted values Author(s) <NAME> See Also summary.orf.prediction, print.orf.prediction Examples # Ordered Forest require(orf) # load example data data(odata) # specify response and covariates for train and test idx <- sample(seq(1, nrow(odata), 1), 0.8*nrow(odata)) # train set Y_train <- as.numeric(odata[idx, 1]) X_train <- as.matrix(odata[idx, -1]) # test set Y_test <- as.numeric(odata[-idx, 1]) X_test <- as.matrix(odata[-idx, -1]) # estimate Ordered Forest orf_fit <- orf(X_train, Y_train) # predict the probabilities with the estimated orf orf_pred <- predict(orf_fit, newdata = X_test) # predict the probabilities with estimated orf together with variances orf_pred <- predict(orf_fit, newdata = X_test, inference = TRUE) # predict the classes with estimated orf orf_pred <- predict(orf_fit, newdata = X_test, type = "class") print.margins.orf Print of the Ordered Forest Marginal Effects Description print of estimated marginal effects of the Ordered Forest of class margins.orf Usage ## S3 method for class 'margins.orf' print(x, ...) Arguments x estimated Ordered Forest Marginal Effect object of type margins.orf ... further arguments (currently ignored) Details print.margins.orf provides a first glimpse of the Ordered Forest marginal effects, printed directly to the R console. The printed information contains the results for the marginal effects for each covariate and each outcome class. Author(s) <NAME> Examples ## Ordered Forest require(orf) # load example data data(odata) # specify response and covariates Y <- as.numeric(odata[, 1]) X <- as.matrix(odata[, -1]) # estimate Ordered Forest orf_fit <- orf(X, Y) # estimate marginal effects of the orf orf_margins <- margins(orf_fit) # print marginal effects print(orf_margins) print.orf Print of the Ordered Forest Description print of an estimated Ordered Forest object of class orf Usage ## S3 method for class 'orf' print(x, ...) Arguments x estimated Ordered Forest object of class orf ... further arguments (currently ignored) Details print.orf provides a first glimpse of the Ordered Forest estimation, printed directly to the R con- sole. The printed information contains the main inputs of the orf function. Author(s) <NAME> Examples # Ordered Forest require(orf) # load example data data(odata) # specify response and covariates Y <- as.numeric(odata[, 1]) X <- as.matrix(odata[, -1]) # estimate Ordered Forest orf_fit <- orf(X, Y) # print output of the orf estimation print(orf_fit) print.orf.prediction Print of the Ordered Forest Prediction Description print of Ordered Forest predictions of class orf.prediction Usage ## S3 method for class 'orf.prediction' print(x, ...) Arguments x predicted Ordered Forest object of class orf.prediction ... further arguments (currently ignored) Details print.orf.prediction provides a first glimpse of the Ordered Forest prediction, printed directly to the R console. The printed information contains the main inputs of the predict.orf function. Author(s) <NAME> Examples # Ordered Forest require(orf) # load example data data(odata) # specify response and covariates for train and test idx <- sample(seq(1, nrow(odata), 1), 0.8*nrow(odata)) # train set Y_train <- as.numeric(odata[idx, 1]) X_train <- as.matrix(odata[idx, -1]) # test set Y_test <- as.numeric(odata[-idx, 1]) X_test <- as.matrix(odata[-idx, -1]) # estimate Ordered Forest orf_fit <- orf(X_train, Y_train) # predict the probabilities with the estimated orf orf_pred <- predict(orf_fit, newdata = X_test) # print the prediction object print(orf_pred) summary.margins.orf Summary of the Ordered Forest Marginal Effects Description summary of estimated marginal effects of the Ordered Forest of class margins.orf Usage ## S3 method for class 'margins.orf' summary(object, latex = FALSE, ...) Arguments object estimated Ordered Forest Marginal Effect object of type margins.orf latex logical, if TRUE latex coded summary will be generated (default is FALSE) ... further arguments (currently ignored) Details summary.margins.orf provides estimation results of the Ordered Forest marginal effects. The summary contains the results for the marginal effects for each covariate and each outcome class, optionally with inference as well. Furthermore, summary output as a LaTeX table is supported in order to directly extract the results for the documentation. Author(s) <NAME> Examples ## Ordered Forest require(orf) # load example data data(odata) # specify response and covariates Y <- as.numeric(odata[, 1]) X <- as.matrix(odata[, -1]) # estimate Ordered Forest orf_fit <- orf(X, Y) # estimate marginal effects of the orf orf_margins <- margins(orf_fit) # summary of marginal effects summary(orf_margins) # summary of marginal effects coded in LaTeX summary(orf_margins, latex = TRUE) summary.orf Summary of the Ordered Forest Description summary of an estimated Ordered Forest object of class orf Usage ## S3 method for class 'orf' summary(object, latex = FALSE, ...) Arguments object estimated Ordered Forest object of class orf latex logical, if TRUE latex coded summary will be generated (default is FALSE) ... further arguments (currently ignored) Details summary.orf provides a short summary of the Ordered Forest estimation, including the input in- formation regarding the values of hyperparameters as well as the output information regarding the prediction accuracy. Author(s) <NAME> Examples # Ordered Forest require(orf) # load example data data(odata) # specify response and covariates Y <- as.numeric(odata[, 1]) X <- as.matrix(odata[, -1]) # estimate Ordered Forest orf_fit <- orf(X, Y) # show summary of the orf estimation summary(orf_fit) # show summary of the orf estimation coded in LaTeX summary(orf_fit, latex = TRUE) summary.orf.prediction Summary of the Ordered Forest Prediction Description summary of Ordered Forest predictions of class orf.prediction Usage ## S3 method for class 'orf.prediction' summary(object, latex = FALSE, ...) Arguments object predicted Ordered Forest object of class orf.prediction latex logical, if TRUE latex coded summary will be generated (default is FALSE) ... further arguments (currently ignored) Details summary.orf.prediction provides a main summary of the Ordered Forest prediction, includ- ing the input information regarding the values of hyperparameters as well as the inputs of the predict.orf function. Author(s) <NAME> Examples # Ordered Forest require(orf) # load example data data(odata) # specify response and covariates for train and test idx <- sample(seq(1, nrow(odata), 1), 0.8*nrow(odata)) # train set Y_train <- as.numeric(odata[idx, 1]) X_train <- as.matrix(odata[idx, -1]) # test set Y_test <- as.numeric(odata[-idx, 1]) X_test <- as.matrix(odata[-idx, -1]) # estimate Ordered Forest orf_fit <- orf(X_train, Y_train) # predict the probabilities with the estimated orf orf_pred <- predict(orf_fit, newdata = X_test) # summary of the prediction object summary(orf_pred) # show summary of the orf prediction coded in LaTeX summary(orf_pred, latex = TRUE)
github.com/neurosnap/sentences
go
Go
README [¶](#section-readme) --- [![release](https://github.com/neurosnap/sentences/actions/workflows/release.yml/badge.svg)](https://github.com/neurosnap/sentences/actions/workflows/release.yml) [![GODOC](https://godoc.org/github.com/nathany/looper?status.svg)](https://godoc.org/github.com/neurosnap/sentences) ![MIT](https://img.shields.io/packagist/l/doctrine/orm.svg) [![Go Report Card](https://goreportcard.com/badge/github.com/neurosnap/sentences)](https://goreportcard.com/report/github.com/neurosnap/sentences) Documentation [¶](#section-documentation) --- ### Overview [¶](#pkg-overview) Package sentences is a golang package that will convert a blob of text into a list of sentences. This package attempts to support a multitude of languages: Czech, Danish, Dutch, English, Estonian, Finnish, French, German, Greek, Italian, Norwegian, Polish, Portuguese, Slovene, Spanish, Swedish, and Turkish. An unsupervised multilingual sentence boundary detection library for golang. The goal of this library is to be able to break up any text into a list of sentences in multiple languages. The way the punkt system accomplishes this goal is through training the tokenizer with text in that given language. Once the likelihoods of abbreviations, collocations, and sentence starters are determined, finding sentence boundaries becomes easier. There are many problems that arise when tokenizing text into sentences, the primary issue being abbreviations. The punkt system attempts to determine whether a word is an abbreviation, an end to a sentence, or even both through training the system with text in the given language. The punkt system incorporates both token- and type-based analysis on the text through two different phases of annotation. Original research article: <http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=BAE5C34E5C3B9DC60DFC4D93B85D8BB1?doi=10.1.1.85.5017&rep=rep1&type=pdf### Index [¶](#pkg-index) * [func IsCjkPunct(r rune) bool](#IsCjkPunct) * [type AnnotateTokens](#AnnotateTokens) * + [func NewAnnotations(s *Storage, p PunctStrings, word WordTokenizer) []AnnotateTokens](#NewAnnotations) * [type DefaultPunctStrings](#DefaultPunctStrings) * + [func NewPunctStrings() *DefaultPunctStrings](#NewPunctStrings) * + [func (p *DefaultPunctStrings) HasSentencePunct(text string) bool](#DefaultPunctStrings.HasSentencePunct) + [func (p *DefaultPunctStrings) NonPunct() string](#DefaultPunctStrings.NonPunct) + [func (p *DefaultPunctStrings) Punctuation() string](#DefaultPunctStrings.Punctuation) * [type DefaultSentenceTokenizer](#DefaultSentenceTokenizer) * + [func NewSentenceTokenizer(s *Storage) *DefaultSentenceTokenizer](#NewSentenceTokenizer) + [func NewTokenizer(s *Storage, word WordTokenizer, lang PunctStrings) *DefaultSentenceTokenizer](#NewTokenizer) * + [func (s *DefaultSentenceTokenizer) AnnotateTokens(tokens []*Token, annotate ...AnnotateTokens) []*Token](#DefaultSentenceTokenizer.AnnotateTokens) + [func (s *DefaultSentenceTokenizer) AnnotatedTokens(text string) []*Token](#DefaultSentenceTokenizer.AnnotatedTokens) + [func (s *DefaultSentenceTokenizer) SentencePositions(text string) []int](#DefaultSentenceTokenizer.SentencePositions) + [func (s *DefaultSentenceTokenizer) Tokenize(text string) []*Sentence](#DefaultSentenceTokenizer.Tokenize) * [type DefaultTokenGrouper](#DefaultTokenGrouper) * + [func (p *DefaultTokenGrouper) Group(tokens []*Token) [][2]*Token](#DefaultTokenGrouper.Group) * [type DefaultWordTokenizer](#DefaultWordTokenizer) * + [func NewWordTokenizer(p PunctStrings) *DefaultWordTokenizer](#NewWordTokenizer) * + [func (p *DefaultWordTokenizer) FirstLower(t *Token) bool](#DefaultWordTokenizer.FirstLower) + [func (p *DefaultWordTokenizer) FirstUpper(t *Token) bool](#DefaultWordTokenizer.FirstUpper) + [func (p *DefaultWordTokenizer) HasPeriodFinal(t *Token) bool](#DefaultWordTokenizer.HasPeriodFinal) + [func (p *DefaultWordTokenizer) HasSentEndChars(t *Token) bool](#DefaultWordTokenizer.HasSentEndChars) + [func (p *DefaultWordTokenizer) HasUnreliableEndChars(t *Token) bool](#DefaultWordTokenizer.HasUnreliableEndChars) + [func (p *DefaultWordTokenizer) IsAlpha(t *Token) bool](#DefaultWordTokenizer.IsAlpha) + [func (p *DefaultWordTokenizer) IsCoordinatePartOne(t *Token) bool](#DefaultWordTokenizer.IsCoordinatePartOne) + [func (p *DefaultWordTokenizer) IsCoordinatePartTwo(t *Token) bool](#DefaultWordTokenizer.IsCoordinatePartTwo) + [func (p *DefaultWordTokenizer) IsEllipsis(t *Token) bool](#DefaultWordTokenizer.IsEllipsis) + [func (p *DefaultWordTokenizer) IsInitial(t *Token) bool](#DefaultWordTokenizer.IsInitial) + [func (p *DefaultWordTokenizer) IsListNumber(t *Token) bool](#DefaultWordTokenizer.IsListNumber) + [func (p *DefaultWordTokenizer) IsNonPunct(t *Token) bool](#DefaultWordTokenizer.IsNonPunct) + [func (p *DefaultWordTokenizer) IsNumber(t *Token) bool](#DefaultWordTokenizer.IsNumber) + [func (p *DefaultWordTokenizer) Tokenize(text string, onlyPeriodContext bool) []*Token](#DefaultWordTokenizer.Tokenize) + [func (p *DefaultWordTokenizer) Type(t *Token) string](#DefaultWordTokenizer.Type) + [func (p *DefaultWordTokenizer) TypeNoPeriod(t *Token) string](#DefaultWordTokenizer.TypeNoPeriod) + [func (p *DefaultWordTokenizer) TypeNoSentPeriod(t *Token) string](#DefaultWordTokenizer.TypeNoSentPeriod) * [type Ortho](#Ortho) * [type OrthoContext](#OrthoContext) * + [func (o *OrthoContext) Heuristic(token *Token) int](#OrthoContext.Heuristic) * [type PunctStrings](#PunctStrings) * [type Sentence](#Sentence) * + [func (s Sentence) String() string](#Sentence.String) * [type SentenceTokenizer](#SentenceTokenizer) * [type SetString](#SetString) * + [func (ss SetString) Add(str string)](#SetString.Add) + [func (ss SetString) Array() []string](#SetString.Array) + [func (ss SetString) Has(str string) bool](#SetString.Has) + [func (ss SetString) Remove(str string)](#SetString.Remove) * [type Storage](#Storage) * + [func LoadTraining(data []byte) (*Storage, error)](#LoadTraining) + [func NewStorage() *Storage](#NewStorage) * + [func (p *Storage) IsAbbr(tokens ...string) bool](#Storage.IsAbbr) * [type Token](#Token) * + [func NewToken(token string) *Token](#NewToken) * + [func (p *Token) String() string](#Token.String) * [type TokenBasedAnnotation](#TokenBasedAnnotation) * + [func (a *TokenBasedAnnotation) Annotate(tokens []*Token) []*Token](#TokenBasedAnnotation.Annotate) * [type TokenExistential](#TokenExistential) * [type TokenFirst](#TokenFirst) * [type TokenGrouper](#TokenGrouper) * [type TokenParser](#TokenParser) * [type TokenType](#TokenType) * [type TypeBasedAnnotation](#TypeBasedAnnotation) * + [func NewTypeBasedAnnotation(s *Storage, p PunctStrings, e TokenExistential) *TypeBasedAnnotation](#NewTypeBasedAnnotation) * + [func (a *TypeBasedAnnotation) Annotate(tokens []*Token) []*Token](#TypeBasedAnnotation.Annotate) * [type WordTokenizer](#WordTokenizer) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) This section is empty. ### Functions [¶](#pkg-functions) #### func [IsCjkPunct](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L299) [¶](#IsCjkPunct) added in v1.0.7 ``` func IsCjkPunct(r [rune](/builtin#rune)) [bool](/builtin#bool) ``` ### Types [¶](#pkg-types) #### type [AnnotateTokens](https://github.com/neurosnap/sentences/blob/v1.1.2/annotate.go#L11) [¶](#AnnotateTokens) ``` type AnnotateTokens interface { Annotate([]*[Token](#Token)) []*[Token](#Token) } ``` AnnotateTokens is an interface used for the sentence tokenizer to add properties to any given token during tokenization. #### func [NewAnnotations](https://github.com/neurosnap/sentences/blob/v1.1.2/annotate.go#L44) [¶](#NewAnnotations) ``` func NewAnnotations(s *[Storage](#Storage), p [PunctStrings](#PunctStrings), word [WordTokenizer](#WordTokenizer)) [][AnnotateTokens](#AnnotateTokens) ``` NewAnnotations is the default AnnotateTokens struct that the tokenizer uses #### type [DefaultPunctStrings](https://github.com/neurosnap/sentences/blob/v1.1.2/punctuation.go#L14) [¶](#DefaultPunctStrings) ``` type DefaultPunctStrings struct{} ``` DefaultPunctStrings are used to detect punctuation in the sentence tokenizer. #### func [NewPunctStrings](https://github.com/neurosnap/sentences/blob/v1.1.2/punctuation.go#L17) [¶](#NewPunctStrings) ``` func NewPunctStrings() *[DefaultPunctStrings](#DefaultPunctStrings) ``` NewPunctStrings creates a default set of properties #### func (*DefaultPunctStrings) [HasSentencePunct](https://github.com/neurosnap/sentences/blob/v1.1.2/punctuation.go#L32) [¶](#DefaultPunctStrings.HasSentencePunct) ``` func (p *[DefaultPunctStrings](#DefaultPunctStrings)) HasSentencePunct(text [string](/builtin#string)) [bool](/builtin#bool) ``` HasSentencePunct does the supplied text have a known sentence punctuation character? #### func (*DefaultPunctStrings) [NonPunct](https://github.com/neurosnap/sentences/blob/v1.1.2/punctuation.go#L22) [¶](#DefaultPunctStrings.NonPunct) ``` func (p *[DefaultPunctStrings](#DefaultPunctStrings)) NonPunct() [string](/builtin#string) ``` NonPunct regex string to detect non-punctuation. #### func (*DefaultPunctStrings) [Punctuation](https://github.com/neurosnap/sentences/blob/v1.1.2/punctuation.go#L27) [¶](#DefaultPunctStrings.Punctuation) ``` func (p *[DefaultPunctStrings](#DefaultPunctStrings)) Punctuation() [string](/builtin#string) ``` Punctuation characters #### type [DefaultSentenceTokenizer](https://github.com/neurosnap/sentences/blob/v1.1.2/sentence_tokenizer.go#L15) [¶](#DefaultSentenceTokenizer) ``` type DefaultSentenceTokenizer struct { *[Storage](#Storage) [WordTokenizer](#WordTokenizer) [PunctStrings](#PunctStrings) Annotations [][AnnotateTokens](#AnnotateTokens) } ``` DefaultSentenceTokenizer is a sentence tokenizer which uses an unsupervised algorithm to build a model for abbreviation words, collocations, and words that start sentences and then uses that model to find sentence boundaries. #### func [NewSentenceTokenizer](https://github.com/neurosnap/sentences/blob/v1.1.2/sentence_tokenizer.go#L23) [¶](#NewSentenceTokenizer) ``` func NewSentenceTokenizer(s *[Storage](#Storage)) *[DefaultSentenceTokenizer](#DefaultSentenceTokenizer) ``` NewSentenceTokenizer are the sane defaults for the sentence tokenizer #### func [NewTokenizer](https://github.com/neurosnap/sentences/blob/v1.1.2/sentence_tokenizer.go#L41) [¶](#NewTokenizer) ``` func NewTokenizer(s *[Storage](#Storage), word [WordTokenizer](#WordTokenizer), lang [PunctStrings](#PunctStrings)) *[DefaultSentenceTokenizer](#DefaultSentenceTokenizer) ``` NewTokenizer wraps around DST doing the work for customizing the tokenizer #### func (*DefaultSentenceTokenizer) [AnnotateTokens](https://github.com/neurosnap/sentences/blob/v1.1.2/sentence_tokenizer.go#L59) [¶](#DefaultSentenceTokenizer.AnnotateTokens) ``` func (s *[DefaultSentenceTokenizer](#DefaultSentenceTokenizer)) AnnotateTokens(tokens []*[Token](#Token), annotate ...[AnnotateTokens](#AnnotateTokens)) []*[Token](#Token) ``` AnnotateTokens given a set of tokens augmented with markers for line-start and paragraph-start, returns an iterator through those tokens with full annotation including predicted sentence breaks. #### func (*DefaultSentenceTokenizer) [AnnotatedTokens](https://github.com/neurosnap/sentences/blob/v1.1.2/sentence_tokenizer.go#L70) [¶](#DefaultSentenceTokenizer.AnnotatedTokens) ``` func (s *[DefaultSentenceTokenizer](#DefaultSentenceTokenizer)) AnnotatedTokens(text [string](/builtin#string)) []*[Token](#Token) ``` AnnotatedTokens are the fully annotated word tokens. This allows for adhoc adjustments to the tokens #### func (*DefaultSentenceTokenizer) [SentencePositions](https://github.com/neurosnap/sentences/blob/v1.1.2/sentence_tokenizer.go#L87) [¶](#DefaultSentenceTokenizer.SentencePositions) ``` func (s *[DefaultSentenceTokenizer](#DefaultSentenceTokenizer)) SentencePositions(text [string](/builtin#string)) [][int](/builtin#int) ``` SentencePositions returns an array of positions instead of returning an array of sentences. #### func (*DefaultSentenceTokenizer) [Tokenize](https://github.com/neurosnap/sentences/blob/v1.1.2/sentence_tokenizer.go#L120) [¶](#DefaultSentenceTokenizer.Tokenize) ``` func (s *[DefaultSentenceTokenizer](#DefaultSentenceTokenizer)) Tokenize(text [string](/builtin#string)) []*[Sentence](#Sentence) ``` Tokenize splits text input into sentence tokens. #### type [DefaultTokenGrouper](https://github.com/neurosnap/sentences/blob/v1.1.2/token.go#L14) [¶](#DefaultTokenGrouper) ``` type DefaultTokenGrouper struct{} ``` DefaultTokenGrouper is the default implementation of TokenGrouper #### func (*DefaultTokenGrouper) [Group](https://github.com/neurosnap/sentences/blob/v1.1.2/token.go#L17) [¶](#DefaultTokenGrouper.Group) ``` func (p *[DefaultTokenGrouper](#DefaultTokenGrouper)) Group(tokens []*[Token](#Token)) [][2]*[Token](#Token) ``` Group is the primary logic for implementing TokenGrouper #### type [DefaultWordTokenizer](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L66) [¶](#DefaultWordTokenizer) ``` type DefaultWordTokenizer struct { [PunctStrings](#PunctStrings) } ``` DefaultWordTokenizer is the default implementation of the WordTokenizer #### func [NewWordTokenizer](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L71) [¶](#NewWordTokenizer) ``` func NewWordTokenizer(p [PunctStrings](#PunctStrings)) *[DefaultWordTokenizer](#DefaultWordTokenizer) ``` NewWordTokenizer creates a new DefaultWordTokenizer #### func (*DefaultWordTokenizer) [FirstLower](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L195) [¶](#DefaultWordTokenizer.FirstLower) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) FirstLower(t *[Token](#Token)) [bool](/builtin#bool) ``` FirstLower is true if the token's first character is lowercase #### func (*DefaultWordTokenizer) [FirstUpper](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L185) [¶](#DefaultWordTokenizer.FirstUpper) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) FirstUpper(t *[Token](#Token)) [bool](/builtin#bool) ``` FirstUpper is true if the token's first character is uppercase. #### func (*DefaultWordTokenizer) [HasPeriodFinal](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L246) [¶](#DefaultWordTokenizer.HasPeriodFinal) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) HasPeriodFinal(t *[Token](#Token)) [bool](/builtin#bool) ``` HasPeriodFinal is true if the last character in the word is a period #### func (*DefaultWordTokenizer) [HasSentEndChars](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L251) [¶](#DefaultWordTokenizer.HasSentEndChars) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) HasSentEndChars(t *[Token](#Token)) [bool](/builtin#bool) ``` HasSentEndChars finds any punctuation excluding the period final #### func (*DefaultWordTokenizer) [HasUnreliableEndChars](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L286) [¶](#DefaultWordTokenizer.HasUnreliableEndChars) added in v1.1.0 ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) HasUnreliableEndChars(t *[Token](#Token)) [bool](/builtin#bool) ``` Find any punctuation that might mean the end of a sentence but doesn't have to #### func (*DefaultWordTokenizer) [IsAlpha](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L225) [¶](#DefaultWordTokenizer.IsAlpha) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) IsAlpha(t *[Token](#Token)) [bool](/builtin#bool) ``` IsAlpha is true if the token text is all alphabetic. #### func (*DefaultWordTokenizer) [IsCoordinatePartOne](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L230) [¶](#DefaultWordTokenizer.IsCoordinatePartOne) added in v1.1.2 ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) IsCoordinatePartOne(t *[Token](#Token)) [bool](/builtin#bool) ``` IsCoordinatePartTwo is true if the token text might be the second part of a coordiate. #### func (*DefaultWordTokenizer) [IsCoordinatePartTwo](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L235) [¶](#DefaultWordTokenizer.IsCoordinatePartTwo) added in v1.1.2 ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) IsCoordinatePartTwo(t *[Token](#Token)) [bool](/builtin#bool) ``` IsCoordinatePartTwo is true if the token text might be the second part of a coordiate. #### func (*DefaultWordTokenizer) [IsEllipsis](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L205) [¶](#DefaultWordTokenizer.IsEllipsis) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) IsEllipsis(t *[Token](#Token)) [bool](/builtin#bool) ``` IsEllipsis is true if the token text is that of an ellipsis. #### func (*DefaultWordTokenizer) [IsInitial](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L215) [¶](#DefaultWordTokenizer.IsInitial) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) IsInitial(t *[Token](#Token)) [bool](/builtin#bool) ``` IsInitial is true if the token text is that of an initial. #### func (*DefaultWordTokenizer) [IsListNumber](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L220) [¶](#DefaultWordTokenizer.IsListNumber) added in v1.1.0 ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) IsListNumber(t *[Token](#Token)) [bool](/builtin#bool) ``` IsInitial is true if the token text is that of a list number. #### func (*DefaultWordTokenizer) [IsNonPunct](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L240) [¶](#DefaultWordTokenizer.IsNonPunct) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) IsNonPunct(t *[Token](#Token)) [bool](/builtin#bool) ``` IsNonPunct is true if the token is either a number or is alphabetic. #### func (*DefaultWordTokenizer) [IsNumber](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L210) [¶](#DefaultWordTokenizer.IsNumber) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) IsNumber(t *[Token](#Token)) [bool](/builtin#bool) ``` IsNumber is true if the token text is that of a number. #### func (*DefaultWordTokenizer) [Tokenize](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L77) [¶](#DefaultWordTokenizer.Tokenize) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) Tokenize(text [string](/builtin#string), onlyPeriodContext [bool](/builtin#bool)) []*[Token](#Token) ``` Tokenize breaks text into words while preserving their character position, whether it starts a new line, and new paragraph. #### func (*DefaultWordTokenizer) [Type](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L152) [¶](#DefaultWordTokenizer.Type) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) Type(t *[Token](#Token)) [string](/builtin#string) ``` Type returns a case-normalized representation of the token. #### func (*DefaultWordTokenizer) [TypeNoPeriod](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L163) [¶](#DefaultWordTokenizer.TypeNoPeriod) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) TypeNoPeriod(t *[Token](#Token)) [string](/builtin#string) ``` TypeNoPeriod is the type with its final period removed if it has one. #### func (*DefaultWordTokenizer) [TypeNoSentPeriod](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L172) [¶](#DefaultWordTokenizer.TypeNoSentPeriod) ``` func (p *[DefaultWordTokenizer](#DefaultWordTokenizer)) TypeNoSentPeriod(t *[Token](#Token)) [string](/builtin#string) ``` TypeNoSentPeriod is the type with its final period removed if it is marked as a sentence break. #### type [Ortho](https://github.com/neurosnap/sentences/blob/v1.1.2/ortho.go#L42) [¶](#Ortho) ``` type Ortho interface { Heuristic(*[Token](#Token)) [int](/builtin#int) } ``` Ortho creates a promise for structs to implement an orthogonal heuristic method. #### type [OrthoContext](https://github.com/neurosnap/sentences/blob/v1.1.2/ortho.go#L47) [¶](#OrthoContext) ``` type OrthoContext struct { *[Storage](#Storage) [PunctStrings](#PunctStrings) [TokenType](#TokenType) [TokenFirst](#TokenFirst) } ``` OrthoContext determines whether a token is capitalized, sentence starter, etc. #### func (*OrthoContext) [Heuristic](https://github.com/neurosnap/sentences/blob/v1.1.2/ortho.go#L57) [¶](#OrthoContext.Heuristic) ``` func (o *[OrthoContext](#OrthoContext)) Heuristic(token *[Token](#Token)) [int](/builtin#int) ``` Heuristic decides whether the given token is the first token in a sentence. #### type [PunctStrings](https://github.com/neurosnap/sentences/blob/v1.1.2/punctuation.go#L6) [¶](#PunctStrings) ``` type PunctStrings interface { NonPunct() [string](/builtin#string) Punctuation() [string](/builtin#string) HasSentencePunct([string](/builtin#string)) [bool](/builtin#bool) } ``` PunctStrings implements all the functions necessary for punctuation strings. They are used to detect punctuation in the sentence tokenizer. #### type [Sentence](https://github.com/neurosnap/sentences/blob/v1.1.2/sentence_tokenizer.go#L109) [¶](#Sentence) ``` type Sentence struct { Start [int](/builtin#int) `json:"start"` End [int](/builtin#int) `json:"end"` Text [string](/builtin#string) `json:"text"` } ``` Sentence container to hold sentences, provides the character positions as well as the text for that sentence. #### func (Sentence) [String](https://github.com/neurosnap/sentences/blob/v1.1.2/sentence_tokenizer.go#L115) [¶](#Sentence.String) ``` func (s [Sentence](#Sentence)) String() [string](/builtin#string) ``` #### type [SentenceTokenizer](https://github.com/neurosnap/sentences/blob/v1.1.2/sentence_tokenizer.go#L7) [¶](#SentenceTokenizer) ``` type SentenceTokenizer interface { AnnotateTokens([]*[Token](#Token), ...[AnnotateTokens](#AnnotateTokens)) []*[Token](#Token) Tokenize([string](/builtin#string)) []*[Sentence](#Sentence) } ``` SentenceTokenizer interface is used by the Tokenize function, can be extended to correct sentence boundaries that punkt misses. #### type [SetString](https://github.com/neurosnap/sentences/blob/v1.1.2/storage.go#L7) [¶](#SetString) ``` type SetString map[[string](/builtin#string)][int](/builtin#int) ``` SetString is an implementation of a set of strings probably not the best way to do this but oh well. #### func (SetString) [Add](https://github.com/neurosnap/sentences/blob/v1.1.2/storage.go#L10) [¶](#SetString.Add) ``` func (ss [SetString](#SetString)) Add(str [string](/builtin#string)) ``` Add adds a string key to the set #### func (SetString) [Array](https://github.com/neurosnap/sentences/blob/v1.1.2/storage.go#L29) [¶](#SetString.Array) ``` func (ss [SetString](#SetString)) Array() [][string](/builtin#string) ``` Array returns and array of keys from the set #### func (SetString) [Has](https://github.com/neurosnap/sentences/blob/v1.1.2/storage.go#L20) [¶](#SetString.Has) ``` func (ss [SetString](#SetString)) Has(str [string](/builtin#string)) [bool](/builtin#bool) ``` Has checks whether a key exists in the set #### func (SetString) [Remove](https://github.com/neurosnap/sentences/blob/v1.1.2/storage.go#L15) [¶](#SetString.Remove) ``` func (ss [SetString](#SetString)) Remove(str [string](/builtin#string)) ``` Remove deletes a string key from the set #### type [Storage](https://github.com/neurosnap/sentences/blob/v1.1.2/storage.go#L41) [¶](#Storage) ``` type Storage struct { AbbrevTypes [SetString](#SetString) `json:"AbbrevTypes"` Collocations [SetString](#SetString) `json:"Collocations"` SentStarters [SetString](#SetString) `json:"SentStarters"` OrthoContext [SetString](#SetString) `json:"OrthoContext"` } ``` Storage stores data used to perform sentence boundary detection with punkt This is where all the training data gets stored for future use #### func [LoadTraining](https://github.com/neurosnap/sentences/blob/v1.1.2/storage.go#L51) [¶](#LoadTraining) ``` func LoadTraining(data [][byte](/builtin#byte)) (*[Storage](#Storage), [error](/builtin#error)) ``` LoadTraining is the primary function to load JSON training data. By default, the sentence tokenizer loads in english automatically, but other languages could be loaded into a binary file using the `make <lang>` command. #### func [NewStorage](https://github.com/neurosnap/sentences/blob/v1.1.2/storage.go#L63) [¶](#NewStorage) ``` func NewStorage() *[Storage](#Storage) ``` NewStorage creates the default storage container #### func (*Storage) [IsAbbr](https://github.com/neurosnap/sentences/blob/v1.1.2/storage.go#L73) [¶](#Storage.IsAbbr) ``` func (p *[Storage](#Storage)) IsAbbr(tokens ...[string](/builtin#string)) [bool](/builtin#bool) ``` IsAbbr detemines if any of the tokens are an abbreviation #### type [Token](https://github.com/neurosnap/sentences/blob/v1.1.2/token.go#L38) [¶](#Token) ``` type Token struct { Tok [string](/builtin#string) Position [int](/builtin#int) SentBreak [bool](/builtin#bool) ParaStart [bool](/builtin#bool) LineStart [bool](/builtin#bool) Abbr [bool](/builtin#bool) // contains filtered or unexported fields } ``` Token stores a token of text with annotations produced during sentence boundary detection. #### func [NewToken](https://github.com/neurosnap/sentences/blob/v1.1.2/token.go#L62) [¶](#NewToken) ``` func NewToken(token [string](/builtin#string)) *[Token](#Token) ``` NewToken is the default implementation of the Token struct #### func (*Token) [String](https://github.com/neurosnap/sentences/blob/v1.1.2/token.go#L77) [¶](#Token.String) ``` func (p *[Token](#Token)) String() [string](/builtin#string) ``` String is the string representation of Token #### type [TokenBasedAnnotation](https://github.com/neurosnap/sentences/blob/v1.1.2/annotate.go#L84) [¶](#TokenBasedAnnotation) ``` type TokenBasedAnnotation struct { *[Storage](#Storage) [PunctStrings](#PunctStrings) [TokenParser](#TokenParser) [TokenGrouper](#TokenGrouper) [Ortho](#Ortho) } ``` TokenBasedAnnotation performs a token-based classification (section 4) over the given tokens, making use of the orthographic heuristic (4.1.1), collocation heuristic (4.1.2) and frequent sentence starter heuristic (4.1.3). #### func (*TokenBasedAnnotation) [Annotate](https://github.com/neurosnap/sentences/blob/v1.1.2/annotate.go#L93) [¶](#TokenBasedAnnotation.Annotate) ``` func (a *[TokenBasedAnnotation](#TokenBasedAnnotation)) Annotate(tokens []*[Token](#Token)) []*[Token](#Token) ``` Annotate iterates groups tokens in pairs of two and then iterates over them to apply token annotation #### type [TokenExistential](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L33) [¶](#TokenExistential) ``` type TokenExistential interface { // True if the token text is all alphabetic. IsAlpha(*[Token](#Token)) [bool](/builtin#bool) // True if the token text is that of an ellipsis. IsEllipsis(*[Token](#Token)) [bool](/builtin#bool) // True if the token text is that of an initial. IsInitial(*[Token](#Token)) [bool](/builtin#bool) // True if the token text is that of an number as part of a list. IsListNumber(*[Token](#Token)) [bool](/builtin#bool) // True if the token text is that of a number. IsNumber(*[Token](#Token)) [bool](/builtin#bool) // True if the token is either a number or is alphabetic. IsNonPunct(*[Token](#Token)) [bool](/builtin#bool) // True if the token is first part of a coordinate. IsCoordinatePartOne(*[Token](#Token)) [bool](/builtin#bool) // True if the token is second part of a coordinate. IsCoordinatePartTwo(*[Token](#Token)) [bool](/builtin#bool) // Does this token end with a period? HasPeriodFinal(*[Token](#Token)) [bool](/builtin#bool) // Does this token end with a punctuation and a quote? HasSentEndChars(*[Token](#Token)) [bool](/builtin#bool) // Does this token end with ambigiuous punctuation? HasUnreliableEndChars(*[Token](#Token)) [bool](/builtin#bool) } ``` TokenExistential are helpers to determine what type of token we are dealing with. #### type [TokenFirst](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L25) [¶](#TokenFirst) ``` type TokenFirst interface { // True if the token's first character is lowercase FirstLower(*[Token](#Token)) [bool](/builtin#bool) // True if the token's first character is uppercase. FirstUpper(*[Token](#Token)) [bool](/builtin#bool) } ``` TokenFirst are helpers to determine the case of the token's first letter #### type [TokenGrouper](https://github.com/neurosnap/sentences/blob/v1.1.2/token.go#L9) [¶](#TokenGrouper) ``` type TokenGrouper interface { Group([]*[Token](#Token)) [][2]*[Token](#Token) } ``` TokenGrouper two adjacent tokens together. #### type [TokenParser](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L59) [¶](#TokenParser) ``` type TokenParser interface { [TokenType](#TokenType) [TokenFirst](#TokenFirst) [TokenExistential](#TokenExistential) } ``` TokenParser is the primary token interface that determines the context and type of a tokenized word. #### type [TokenType](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L16) [¶](#TokenType) ``` type TokenType interface { Type(*[Token](#Token)) [string](/builtin#string) // The type with its final period removed if it has one. TypeNoPeriod(*[Token](#Token)) [string](/builtin#string) // The type with its final period removed if it is marked as a sentence break. TypeNoSentPeriod(*[Token](#Token)) [string](/builtin#string) } ``` TokenType are helpers to get the type of a token #### type [TypeBasedAnnotation](https://github.com/neurosnap/sentences/blob/v1.1.2/annotate.go#L28) [¶](#TypeBasedAnnotation) ``` type TypeBasedAnnotation struct { *[Storage](#Storage) [PunctStrings](#PunctStrings) [TokenExistential](#TokenExistential) } ``` TypeBasedAnnotation performs the first pass of annotation, which makes decisions based purely based on the word type of each word: * '?', '!', and '.' are marked as sentence breaks. * sequences of two or more periods are marked as ellipsis. * any word ending in '.' that's a known abbreviation is marked as an abbreviation. * any other word ending in '.' is marked as a sentence break. Return these annotations as a tuple of three sets: * sentbreak_toks: The indices of all sentence breaks. * abbrev_toks: The indices of all abbreviations. * ellipsis_toks: The indices of all ellipsis marks. #### func [NewTypeBasedAnnotation](https://github.com/neurosnap/sentences/blob/v1.1.2/annotate.go#L35) [¶](#NewTypeBasedAnnotation) ``` func NewTypeBasedAnnotation(s *[Storage](#Storage), p [PunctStrings](#PunctStrings), e [TokenExistential](#TokenExistential)) *[TypeBasedAnnotation](#TypeBasedAnnotation) ``` NewTypeBasedAnnotation creates an instance of the TypeBasedAnnotation struct #### func (*TypeBasedAnnotation) [Annotate](https://github.com/neurosnap/sentences/blob/v1.1.2/annotate.go#L54) [¶](#TypeBasedAnnotation.Annotate) ``` func (a *[TypeBasedAnnotation](#TypeBasedAnnotation)) Annotate(tokens []*[Token](#Token)) []*[Token](#Token) ``` Annotate iterates over all tokens and applies the type annotation on them #### type [WordTokenizer](https://github.com/neurosnap/sentences/blob/v1.1.2/word_tokenizer.go#L10) [¶](#WordTokenizer) ``` type WordTokenizer interface { [TokenParser](#TokenParser) Tokenize([string](/builtin#string), [bool](/builtin#bool)) []*[Token](#Token) } ``` WordTokenizer is the primary interface for tokenizing words
@types/activex-access
npm
JavaScript
[Installation](#installation) === > `npm install --save @types/activex-access` [Summary](#summary) === This package contains type definitions for activex-access (<https://msdn.microsoft.com/en-us/library/dn142571.aspx>). [Details](#details) === Files were exported from <https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/activex-access>. ### [Additional Details](#additional-details) * Last updated: Tue, 17 Oct 2023 21:12:30 GMT * Dependencies: [@types/activex-adodb](https://npmjs.com/package/@types/activex-adodb), [@types/activex-dao](https://npmjs.com/package/@types/activex-dao), [@types/activex-interop](https://npmjs.com/package/@types/activex-interop), [@types/activex-office](https://npmjs.com/package/@types/activex-office), [@types/activex-vbide](https://npmjs.com/package/@types/activex-vbide), [activex-helpers](https://npmjs.com/package/activex-helpers) [Credits](#credits) === These definitions were written by [<NAME>](https://github.com/zspitz). Readme --- ### Keywords none
openbook_rheinwerk-verlag_de_c_von_a_bis_z
free_programming_book
C
Copyright © Rheinwerk Verlag GmbH 2009Für Ihren privaten Gebrauch dürfen Sie die Online-Version natürlich ausdrucken. Ansonsten unterliegt das Openbook denselben Bestimmungen, wie die gebundene Ausgabe: Das Werk einschlieÃlich aller seiner Teile ist urheberrechtlich geschützt.Alle Rechte vorbehalten einschlieÃlich der Vervielfältigung, Ãbersetzung, Mikroverfilmung sowie Einspeicherung und Verarbeitung in elektronischen Systemen.Nutzungsbestimmungen | Datenschutz | ImpressumRheinwerk Verlag GmbH, Rheinwerkallee 4, 53227 Bonn, Tel.: 0228.42150.0, Fax 0228.42150.77, <EMAIL>Cookie-Einstellungen ändern Copyright © Rheinwerk Verlag GmbH 2009Für Ihren privaten Gebrauch dürfen Sie die Online-Version natürlich ausdrucken. Ansonsten unterliegt das Openbook denselben Bestimmungen, wie die gebundene Ausgabe: Das Werk einschlieÃlich aller seiner Teile ist urheberrechtlich geschützt. Alle Rechte vorbehalten einschlieÃlich der Vervielfältigung, Ãbersetzung, Mikroverfilmung sowie Einspeicherung und Verarbeitung in elektronischen Systemen.Nutzungsbestimmungen | Datenschutz | Impressum Rheinwerk Verlag GmbH, Rheinwerkallee 4, 53227 Bonn, Tel.: 0228.42150.0, Fax 0228.42150.77, <EMAIL>Cookie-Einstellungen ändern Bei der Flut an Büchern, die es zur Programmiersprache C mittlerweile gibt, stellt sich natürlich die Frage: Warum sollten Sie sich gerade für dieses Buch entscheiden? Nach mehrjähriger Erfahrung mit C weià ich, dass es schwierig ist, aus der groÃen Menge von Büchern immer das richtige oder das mit dem passenden Schwerpunkt zu finden. Spätestens nach dem dritten oder vierten Buch wird es ärgerlich, denn gut ein Drittel des Buchs ist mit Bibliotheksreferenzen und Werkzeugbeschreibungen gespickt. Zudem ist es immer häufiger so, dass viele Bücher ähnlich aufgebaut sind wie die Bibel von Kernighan&Ritchie, den Erfindern und Entwicklern von C. Dazu fällt mir ein interessantes Zitat von Johann Wolfgang von Goethe ein: Alles Gescheite ist schon gedacht worden. Man muss nur versuchen, es noch einmal zu denken. Dieses Buch, das Sie in den Händen halten, verspricht Ihnen C pur auf allen Seiten. Es ist ein reines C-Werk, das quasi bei Adam und Eva anfängt und sich auch nicht scheut, auf komplexere Themen einzugehen. Es soll keine Konkurrenz für viele andere gute Bücher sein, sondern es soll sie ergänzen. Ich habe mich durchgehend bemüht, nicht nur für eine bestimmte Zielgruppe zu schreiben. Es soll keines der Sorte Bücher sein, die sich ausschlieÃlich an den Anfänger oder den Fortgeschrittenen richten, sondern soll für beide hilfreich sein. Am Titel lässt sich schon erkennen, dass Einsteiger oder Umsteiger angesprochen sind. Der fortgeschrittene Leser kann mit diesem Buch sein Wissen vertiefen. Ich empfehle dieses Buch einfach jedem, der sich intensiv mit C befassen will oder muss. Da dieses Buch als Online-Kurs im Internet verfügbar war (und es immer noch ist), wurden die Struktur und der Inhalt – dank der Hinweise vieler Kursteilnehmer – immer mehr verfeinert und verbessert. Die einzelnen Kapitel sind jeweils ähnlich gegliedert. Zuerst erfolgt eine Erklärung, worum es geht, und dann schlieÃt sich, falls erforderlich, eine Syntaxbeschreibung an. Ich habe besonders darauf geachtet, dass Sie zu jedem Kapitel möglichst viele ausführbare Listings vorfinden, die anschlieÃend – wenn erforderlich – erklärt werden. In den Kapiteln selbst finden sich oft verschiedene Tipps und Hinweise. AuÃerdem finden Sie auf dieser Webseite weiterführende Links zu den einzelnen Kapiteln, alle Quellcodes des Buchs zum Herunterladen und Anleitungen zu verschiedenen Compilern. In den ersten 20 Kapiteln des Buchs lernen Sie alle Grundlagen zu C kennen. Ab Kapitel 21, so gesehen im zweiten Teil des Buchs, folgen die fortgeschrittenen Themen. Dort behandele ich dynamische Datenstrukturen (Kapitel 21) und verschiedene Algorithmen (Kapitel 22). Ein beliebter, aber leider selten in der Literatur zu findender Aspekt ist die Programmierung von Webanwendungen mit der CGI-Schnittstelle in C (Kapitel 23). Ein weiteres interessantes Thema ist die Programmierung eigener Datenbank-Clients mit der C-API von MySQL (Kapitel 24). Kapitel 25 ist der Netzwerkprogrammierung und der Cross-Plattform-Entwicklung gewidmet. Neu ist in dieser dritten Auflage mit dem Kapitel 26 ein Abschnitt zur Thread-Programmierung (genauer gesagt zu den POSIX-Threads) hinzugekommen. Mein Dank, dass ich dieses Buch überhaupt realisieren konnte, gilt meiner <NAME> und meinem Sohn Jonathan, die mich immer wieder motiviert haben, obwohl ich in den letzten drei Monaten kaum noch Zeit für sie hatte. AuÃerdem möchte ich mich bei den Mitarbeitern des Verlags bedanken, besonders bei meiner Lektorin <NAME>-Lemoine, die das Projekt erst ermöglicht hat. Weitere Personen, die mir beim Schreiben des Buchs mit Rat und Tat zur Seite gestanden haben und denen ich sehr zu Dank verpflichtet bin, sind <NAME>, <NAME> und <NAME>äuser. ## Vorwort zur 3. Auflage Es ist an der Zeit für die dritte Runde und eine stark verbesserte und erweiterte Auflage des Fachbuchs zur C-Programmierung. Zwar ist mit der Thread-Programmierung ein weiteres neues Kapitel hinzugekommen, aber das Hauptaugenmerk bei der Bearbeitung dieser dritten Auflage lag darauf, endlich komplett den derzeitig aktuellen C99-Standard in dieses Buch einzubinden. Ebenso wurde ein neuer Anhang (B) hinzugefügt mit einer Ãbersicht zu allen in der C-Standardbibliothek vorhandenen Funktionen, Makros, Konstanten und Typen. Hier wurde nichts ausgelassen. Ich wünsche Ihnen viel Spaà mit diesem Buch. Sollten während des Lesens Unklarheiten oder Fragen aufkommen, so scheuen Sie sich nicht, mir eine E-Mail zu schicken. Ich freue mich über ein Feedback von Ihnen. Jü<NAME> (<EMAIL>) ## Bin ich hier richtig? Vor dem Kauf dieses Buches haben Sie sich sicher Gedanken darüber gemacht, in welcher Programmiersprache Sie Ihr Wissen weiter vertiefen wollen: C, C++, Python, Java, um nur einige der Hochsprachen zu nennen. Falls Sie in einem Forum diese Frage gestellt haben oder bekannte Programmierer danach gefragt haben, so haben Sie sicher genauso viele unterschiedliche Antworten bekommen, wie es Leute gab, die Ihnen geantwortet haben. Diese Meinungen können also recht weit auseinanderklaffen. Viele Leute raten von C ab, da C keinen objektorientierten Ansatz mitbringt und man sich um die Speicherverwaltung selbst kümmern muss, was einige Gefahren mit sich bringt. Ich bin der Meinung, dass Sie mit C eine gute Wahl getroffen haben. Die Tatsache, dass man bei C vieles selbst von Hand erledigen muss, sehe ich eher als Vorteil an. Durch den Umgang mit diesen Unbequemlichkeiten stellt sich ein hohes Verständnis für das Betriebssystem und die Arbeitsweise Ihres Computers ein. C-Programmierung schafft so eine solide Grundlage, die es Ihnen ermöglicht, andere Sprachen schnell zu verstehen, zu erlernen und einzusetzen, da Sie ein grundsätzliches Verständnis von dem haben, was der Computer im Hintergrund tatsächlich macht. Aber C ist in meinen Augen keinesfalls eine Sprache, die nur zum Einstieg und Lernen der Programmierung dient. Im Gegenteil, mit C können Sie im Grunde alles programmieren – auch einen eigenen objektorientierten Ansatz oder eine komfortable Speicherverwaltung. Nicht ohne Grund sind fast alle modernen Betriebssysteme in C geschrieben. Mit C bieten sich Ihnen also alle Möglichkeiten – als Grundlage zum Erlernen weiterer Sprachen oder als Programmiersprache für den täglichen Einsatz und für groÃe Projekte. Viel Spaà mit Ihrem neuen Buch und herzlich willkommen in der »Das muss doch irgendwie gehen«-Welt. <NAME> <NAME> ist freier Programmierer, Systemadministrator und Webdesigner. Um zu verstehen, warum in C ein Standard eingeführt wurde, müssen Sie etwas zur Geschichte dieser Sprache wissen. ## 1.1 Ãbersicht zu C Mit C lernen Sie eine Programmiersprache, die auf fast allen Betriebssystemen zur Verfügung steht. Besser noch, anders als bei vielen anderen Sprachen (beispielsweise BASIC) steht Ihnen auf den verschiedensten Plattformen eine genormte Standard-C-Bibliothek zur Verfügung. Dank dieser einheitlichen Implementierung und der sehr guten Geschwindigkeit der damit erstellten Programme ist und bleibt C wohl noch für eine sehr lange Zeit eine sehr populäre Sprache – und das sowohl im kommerziellen als auch (vor allem) im Open-Source-Bereich. C wird auch liebevoll als High-Level-Assembler bezeichnet. Dies resultiert auch daher, dass der Kern (besser bekannt als Kernel) aller gängigen Betriebssysteme in C (und natürlich Assembler) geschrieben wurde – weshalb sich C hervorragend zur Systemprogrammierung eignet. Dank einer einfachen Struktur und des geringen Umfangs der Sprache gestaltet sich die Portierung eines C-Compilers auf andere neue Prozessorplattformen im Vergleich mit anderen Sprachen weniger aufwendig, weshalb sich der Aufwand vom kleinsten Mikrocontroller bis zum High-End-Rechner immer lohnt. Somit können Sie sich sicher sein, dass Sie – egal für welche Plattform Sie programmieren – immer einen C-Compiler dafür bekommen, und somit bleibt Ihnen auch eine prozessorspezifische Programmierung in Assembler erspart. Meistens können Sie Ihre Anwendung, die Sie für ein bestimmtes System geschrieben haben, (mit kleinen Ãnderungen) auf eine andere Plattform übernehmen. Und dass die Programme, die in C geschrieben sind, dann auch noch einen verhältnismäÃig geringen Umfang haben (nur Assembler-Programme sind kleiner), macht C zu einer sehr interessanten Sprache in den Bereichen Embedded Systems und Mikrocontroller-Programmierung, wo Speicherplatz sehr kostbar ist. Trotzdem will ich hier nichts schönreden. C zu können und zu verwenden hat in vielen Bereichen erhebliche Vorteile gegenüber anderen Sprachen – Sie lernen also hier in keiner Weise etwas Ãberflüssiges –, aber sofern Sie sich intensiver mit der Anwendungsentwicklung auseinandersetzen wollen bzw. müssen, werden Sie über kurz oder lang nicht um eine objektorientierte Programmiersprache wie C++, Java oder C# herumkommen. Der Vorteil von objektorientiertem Code besteht in einer besseren Wartbarkeit, einer Entwurfsunterstützung und einem besseren Abstraktionsniveau. Allerdings sollte der Umstieg von C auf C++ (oder auch Java) keine allzu groÃe Hürde sein, da die Sprache C++ aus C hervorgegangen ist und um die Möglichkeiten der objektorientierten und generischen Programmierung erweitert wurde. Ein C-Programm wird gewöhnlich mithilfe eines Compilers aus einer oder mehreren einfachen Textdateien zu Objektcodedateien übersetzt. Mehrere Objektcodedateien wiederum werden anschlieÃend von einem Linker (auch Binder genannt) zu einer ausführbaren Datei gebunden. Jedes ausführbare C-Programm besitzt eine Hauptfunktion (in C wird sie main() genannt). Natürlich können Sie auch eigene Bibliotheken erstellen und diese in einem Archiv zusammenfassen. Bibliotheken wiederum können Sie bei einem späteren Bindevorgang des Linkers wieder verwenden, damit diese zum Programm hinzugebunden werden. Das Ziel von Kapitel 2 ist es, Ihnen einen ersten Ãberblick über den Aufbau eines Programms zu verschaffen. AuÃerdem zeige ich Ihnen, wie Sie das Programm ausführbar machen, also übersetzen. Voraussetzung für dieses Kapitel ist, dass bereits ein Compiler installiert wurde. ## 2.1 Der beste Lernerfolg Vielleicht haben Sie schon ein wenig in diesem Buch geblättert und sich die hinteren Kapitel angesehen. Wenn Sie gerade dabei sind, C zu lernen und gerade dann, wenn C Ihre erste Programmiersprache ist, dürfte vieles auf den hinteren Seiten ein wenig kryptisch auf Sie wirken. Als Vergleich könnte ich jetzt eine beliebige Fremdsprache nehmen, die Sie gerade lernen wollen. Wenn Sie dabei die hinteren Kapitel Ihres Lehrbuchs ansehen, wird es Ihnen genauso gehen wie mit diesem Buch: Sie werden mit den Fremdwörtern auch noch nichts anfangen können. Den besten Lernerfolg erzielen Sie also, indem Sie das Buch von vorn nach hinten durcharbeiten. Wer C wirklich lernen will, sollte die Programme auch in der Praxis ausführen. Ideal wäre es natürlich, wenn Sie die Beispiele abtippen und ein wenig damit experimentieren, eventuell sogar mit Absicht Fehler einbauen und sich die Meldungen des Compilers ansehen, mit dem Ziel, möglichst viel daraus zu lernen. Falls Sie hoffen, dieses Buch in wenigen Tagen durchgearbeitet zu haben und dann ein Profi zu sein, werden Sie schnell enttäuscht sein. Programmieren zu lernen, dauert ein wenig länger. Wenn Sie aber Geduld haben und immer am Ball bleiben, ist der Grundstein einer Programmiererkarriere gelegt. Das Programmierenlernen beruht wie vieles im Leben auf dem Prinzip »Versuch und Irrtum«. In (ANSI) C werden zwei Zeichensätze unterschieden: zum einen der Zeichensatz, der bei Quelldateien verwendet werden darf, und zum anderen ein Ausführungszeichensatz, der beim Ausführen des Programms interpretiert wird. ## 3.1 Zeichensätze Zunächst wird in C zwischen dem Basic-Zeichensatz, dem Ausführungszeichensatz und den Trigraph-Zeichen unterschieden. Der Basic-Zeichensatz beinhaltet Zeichen, die beim Schreiben von Quellcode verwendet werden können. Der Ausführungszeichensatz hingegen enthält Zeichen, die erst bei der Ausführung des Programms interpretiert werden. Häufig sind beide Zeichensätze identisch. Erweiterter Zeichensatz | | --- | | ### 3.1.1 Basic-Zeichensatz Folgende Zeichen stehen Ihnen zum Programmieren in der Sprache C zur Verfügung (dies gilt auch für den Ausführungszeichensatz): * die zehn Dezimalziffern: 1 2 3 4 5 6 7 8 9 0 * die Buchstaben des englischen Alphabets: * A B C D E F G H I J K L M N O P Q R S T U V W X Y Z * a b c d e f g h i j k l m n o p q r s t u v w x y z * die folgenden Grafiksymbole: * ! " % & / ( ) [ ] { } \ ? = * ’ # + * ~ – _ . : ; , | < > ^ * die Whitespace-Zeichen: Leerzeichen, Tabulatorzeichen, neue Zeile, neue Seite Auf manchen PCs (aber nicht bei ANSI C) kann auch das Dollarzeichen ($) verwendet werden. ### 3.1.2 Ausführungszeichensatz (Steuerzeichen) Beim Ausführungszeichensatz kommen zu den oben aufgeführten Zeichen noch weitere hinzu, die in diesem Abschnitt beschrieben werden. Zuvor soll ein weiteres Programm analysiert werden. Dazu gehen Sie genauso vor wie schon in Kapitel 2: Tippen Sie das Listing in einem Texteditor ab, speichern Sie es ab, und übersetzen Sie es anschlieÃend mit dem Compiler. Hier das Programmbeispiel zur Demonstration: > /* steuerzeichen.c */ #include <stdio.h> int main(void) { printf("Ein akustisches Signal mit : (\\a)\a"); printf("\nEin Backspace mit : (\\b) | \bx\n"); printf("Ein Zeilenvorschub mit : (\\t) |\tx"); printf("\n\tC\n\ti\n\ts\n\tt\n\ttoll\n"); printf("\t u\n\t n\n\t d\n"); printf("\t macht SpaÃ\n"); return 0; } Nach dem Ãbersetzen und Starten des Programms sieht die Ausgabe folgendermaÃen aus: Abbildung 3.1 Steuerzeichen im Einsatz Hier können Sie die Auswirkungen von Steuerzeichen, auch Escape-Sequenzen (zu Deutsch »Flucht-Sequenzen«) genannt, sehen. Diese Zeichen sind nicht druckbare Zeichen in sogenannten char-Konstanten. Und wie der Name (Steuerzeichen) besagt und das Programm soeben gezeigt hat, können Sie damit die Ausgabe auf dem Bildschirm beeinflussen. Diese Zeichen gehören zum Ausführungszeichensatz. Steuerzeichen beginnen immer mit einem Backslash (\), auf den eine Konstante folgt. Der Compiler behandelt diese Steuerzeichen wie ein einziges Zeichen. Tabelle 3.1 führt die möglichen Steuerzeichen und ihre Bedeutung auf. Hierzu noch ein Listing, das zeigt, wie Sie auÃer mit dem Newline-Zeichen (\n) noch einen Zeilenvorschub auslösen könnten: > /* newline.c */ #include <stdio.h> int main(void) { printf("Darstellung von Newline \\n \n"); printf("Mögliche Ausführung von Newline\n"); printf("Mit hexadezimaler Angabe : \\xa \xa"); printf("Mit oktaler Wertangabe : \\012 \012"); printf("Mit dezimaler Angabe : 10%c",10); printf("Hallo\0Ich bin nicht mehr lesbar\n"); return 0; } Dass auch ein Zeilenvorschub bei \xa , \012 und 10 vorgenommen wurde, liegt daran, dass alle diese Zeichen intern den Wert 10 darstellen. Und wenn Sie sich die ASCII-Code-Tabelle (in Anhang A.2) ansehen, können Sie erkennen, dass alle diese Werte in derselben Zeile stehen und das newline-Zeichen darstellen. Dass bei der letzten printf()-Anweisung der Text nur bis »Hallo« ausgegeben wird, liegt am Steuerzeichen '\0', mit dem eine Stringkonstante terminiert (abgeschlossen) wird. Wird das Beispiel mit einer höheren Warnstufe übersetzt (beispielsweise mit dem Flag -Wall beim GCC), wird der Compiler über diese Zeile sowieso »meckern«, weil es einfach keinen Sinn macht, hier das Zeichen '\0' einzubetten. Dazu später mehr. ### 3.1.3 Trigraph-Zeichen Als Trigraph bezeichnet man in der Linguistik eine Kombination aus drei Schriftzeichen, die als Einheit behandelt werden, z. B. unser »sch«. In ANSI C wurden neun solche Drei-Zeichen-Sequenzen verwendet, die alle mit ?? beginnen. Trigraph-Zeichen wurden eingeführt, um in C-Quelltexten bestimmte Sonderzeichen zu ersetzen, die auf manchen Tastaturen nicht vorhanden sind. Heute besteht kaum noch eine Notwendigkeit zur Verwendung von Trigraph-Zeichen in C, da auf aktuellen Computersystemen der komplette ASCII-Zeichensatz verfügbar ist. In der folgenden Tabelle finden Sie die verfügbaren Trigraph-Zeichenketten und die Erklärung, für welches Zeichen diese stehen. Trigraph-Zeichen | Zeichen | | --- | --- | | | | | | | | | | | | | | | | | | | Somit würde beispielsweise das »Hallo Welt«-Programm mit Trigraph-Zeichen folgendermaÃen aussehen: > // halloTrigraph.c ??=include <stdio.h> int main( void ) ??< printf("<NAME>"); return 0; ??Einige Compiler verarbeiten Trigraph-Zeichen nicht direkt, weil auf dem Rechner, auf dem der Compiler ausgeführt wird, die Eingabe aller Zeichen des C-Zeichensatzes erlaubt ist. Bei solchen Compilern (beispielsweise beim Borland-Compiler) liegen dann entweder spezielle Hilfsprogramme (z. B. TRIGRAPH.EXE) bei, oder Sie müssen ein bestimmtes Compiler-Flag (z. B. -trigraphs) verwenden. Beim GNU-GCC müssen Sie das Beispiel zudem im C99-Standard (mit der Compiler-Option -std=c99) übersetzen. Um auf den nächsten Seiten etwas mehr mit den Programmen machen zu können, benötigen Sie Kenntnisse in der einfacheren (hier formatierten) Ein- und Ausgabe. Die in diesem Kapitel vorgestellten Funktionen printf() und scanf() sind recht gut für diesen Einstieg geeignet, stellen allerdings keinesfalls das Nonplusultra in C dar. Ganz im Gegenteil: Beide Funktionen sind eher als sicherheitskritisch zu betrachten und in der Praxis mit Vorsicht zu genieÃen (Stichwort: »Format String Exploits«). ## 4.1 Formatierte Eingabe mit »scanf()« Betrachten wir zunächst die Syntax dieser Funktion: ``` //benötigter include für diesen Befehl #include <stdio.hint scanf(const char * restric format, ...); ``` Mit der Funktion scanf() können Werte unterschiedlicher Datentypen formatiert eingelesen werden. Eingelesen wird dabei von der Standardeingabe (stdin). Mit Standardeingabe ist normalerweise die Tastatur gemeint. Hierzu ein Beispiel mit der Funktion scanf(): ``` /* scanf1.c */ #include <stdio.hint main (void) { int i; /* ein ganzzahliger Datentyp */ printf("Bitte geben Sie eine Zahl ein : "); scanf("%d",&i); /* Wartet auf die Eingabe. */ printf("Die Zahl, die Sie eingegeben haben, war %d\n",i); return 0; } ``` Wenn das Programm korrekt abläuft, wird nach einer Zahl gefragt. Jetzt gibt der Anwender eine Zahl ein und drückt . AnschlieÃend gibt das Programm die Zahl, die eingegeben wurde, auf dem Bildschirm aus und wird beendet. Abbildung 4.1 Eine einfache Zahleneingabe mit »scanf()« Bildlich können Sie sich diesen Vorgang folgendermaÃen vorstellen: Abbildung 4.2 Programm-Ein-/Ausgabe mit »scanf()« und »printf()« scanf() ist ähnlich aufgebaut wie printf(). Wie bei printf() werden hier zwei Klammern und zwei Hochkommata verwendet. Es wird also formatiert eingelesen. Das Formatzeichen %d steht für die formatierte Eingabe einer dezimalen Zahl. Was aber bedeutet hier das Zeichen »&«? ### 4.1.1 Der Adressoperator »&« Den Adressoperator »&« jetzt schon besser zu verstehen, kann nicht schaden. Später, wenn das Thema »Zeiger« (Pointer; siehe Kapitel 12) besprochen wird, kann dieses Vorverständnis von Nutzen sein. Sollte dieser Abschnitt Ihnen ein wenig fremd vorkommen, ist das kein Grund zur Sorge. Eine Variable kann in die vier folgenden Einzelteile zerlegt werden: * Datentyp * Name der Variable * Speicheradresse der Variable * Wert der Variable Im Programmbeispiel von oben heiÃt das konkret: Der Datentyp ist int, der Name ist i, und die Adresse wird während der Laufzeit zugewiesen (darauf haben Sie keinen Einfluss). Die Speicheradresse sei hier z. B. 0000:123A. Der Wert ist der, den Sie mit scanf() noch eingeben mussten. Wurde jetzt z. B. 5 eingegeben, ist dieser Speicherplatz wie folgt belegt: Abbildung 4.3 Eine Variable im Speicher (vereinfacht dargestellt) Das &-Zeichen ist nichts anderes als der Adressoperator. Dies bedeutet hier, dass der Variablen i vom Typ int mit der Speicheradresse 0000:123A der Wert 5 zugewiesen wird. Oder einfacher: Verschicken Sie eine E-Mail an jemanden, ohne die E-Mail-Adresse anzugeben? Was beim Einlesen einer Zeichenkette richtig ist, ist bei anderen Datentypen wie Ganz- oder Gleitpunktzahlen wieder falsch: > /* FALSCH, da Adressoperator & fehlt */ scanf("%d", zahl); /* Richtig, denn eine Zeichenkette benötigt keinen Adressoperator. */ scanf("%s", string); Auch wenn scanf() das Gegenstück zu printf() ist und sich beide in ihrer Schreibweise ähneln, sollten Sie nicht auf die Idee kommen, Folgendes zu schreiben: > /* FALSCH */ scanf("Bitte geben Sie eine Zahl ein: %d\n", &zahl); Das funktioniert deshalb nicht, weil scanf() für die Standardeingabe programmiert ist und printf() für die Standardausgabe. Wobei die Standardausgabe auf der Kommandozeile auch umgeleitet werden kann. ### 4.1.2 Probleme und deren Behandlung mit »scanf()« Ein häufiges Problem, das auftritt, wenn Sie scanf() für die Eingabe verwenden, ist die Pufferung. Diese ist je nach System und Anwendung zeilen- oder vollgepuffert. Dies gilt wiederum nicht für die Standardfehlerausgabe (stderr), die laut ANSI C niemals vollgepuffert sein darf. Bevor ich weiter erkläre, sollten Sie folgendes Programm testen: > /* scanf2.c */ #include <stdio.h> int main(void) { char a,b,c; printf("1. Buchstabe : "); scanf("%c",&a); printf("2. Buchstabe : "); scanf("%c",&b); printf("3. Buchstabe : "); scanf("%c",&c); printf("Sie gaben ein : %c %c %c ",a,b,c); return 0; } Folgendes könnte nun vom Programm auf den Bildschirm ausgegeben werden: Abbildung 4.4 Ein mögliches Problem mit »scanf()« unter Linux Was ist hier passiert? Warum wird der zweite Buchstabe immer übersprungen? Wie gesagt, das Problem ist hier die Pufferung. Und in C gibt es keinen Befehl (wie etwa chomp bei Perl), um das letzte Zeichen zu entfernen. In diesem Beispiel wurde als erster Buchstabe »a« eingegeben und gedrückt. Dieses (ASCII-Code = 10 = \n = newline) befindet sich immer noch im Puffer der Standardeingabe und wird automatisch für das zweite Zeichen verwendet. Was können Sie dagegen tun? Hier gibt es ein paar Möglichkeiten, die allerdings auch systemabhängig sind: # Möglichkeit 1 Sie benutzen die Funktion fflush() zum Entleeren des Tastaturpuffers. Möglicherweise gelingt dies nicht auf jedem Betriebssystem (speziell nicht unter Linux): > /* scanf3.c */ #include <stdio.h> int main(void) { char a,b,c; printf("1. Buchstabe : "); scanf("%c",&a); fflush(stdin); printf("2. Buchstabe : "); scanf("%c",&b); fflush(stdin); printf("3. Buchstabe : "); scanf("%c",&c); printf("Sie gaben ein : %c %c %c ",a,b,c); return 0; } # Möglichkeit 2 Sie benutzen eine do while-Schleife und ziehen das Newline-Zeichen aus dem Puffer heraus: > /* scanf4.c */ #include <stdio.h> int main(void) { char a, b, c; printf("1. Buchstabe : "); do {scanf("%c",&a);} while ( getchar() != '\n' ); printf("2. Buchstabe : "); do {scanf("%c",&b);} while ( getchar() != '\n' ); printf("3. Buchstabe : "); do {scanf("%c",&c);} while ( getchar() != '\n' ); printf("%c %c %c\n", a, b, c); return 0; } Mehr zur do while-Schleife finden Sie in Abschnitt 8.9. # Möglichkeit 3 Sie verwenden scanf() erst gar nicht (wie dies in der Praxis aus Sicherheitsgründen zu empfehlen ist) und greifen auf eine der vielen anderen Standardeingabe-Funktionen zurück. Ideal wäre es beispielsweise, die Funktion fgets() zum Einlesen zu verwenden und diese Eingabe mit der Funktion sscanf() in ein entsprechendes Format zu konvertieren (siehe auch Abschnitt 16.23). Ein entsprechendes Beispiel könnte so aussehen: > /* scanf5.c */ #include <stdio.h> int main(void) { char ch; char buf[2]; printf("Ein Zeichen bitte : "); fgets(buf, 2, stdin); sscanf(buf, "%c", &ch); printf("Das Zeichen : %c\n",ch); return 0; } ### 4.1.3 Ãberprüfen auf das richtige Format Um sicherzugehen, dass der Benutzer auch das Richtige eingegeben hat, können (müssen) Sie den Rückgabewert von scanf() überprüfen: > /* scanf6.c */ #include <stdio.h> int main(void) { char a; int b, check; printf("Bitte Eingabe machen (Zeichen/Zahl): "); check = scanf("%c %d",&a, &b); printf("check = %d \n",check); return 0; } Der Rückgabewert von scanf() ist dabei immer die Anzahl der erfolgreich gelesenen Werte. Der Wert 0 hingegen wird zurückgegeben, wenn es zu keiner Ãbereinstimmung mit dem geforderten Formatzeichen gekommen ist. In diesem Beispiel erwartet scanf() die Eingabe eines Zeichens (%c) und einer Dezimalzahl (%d). Wenn beide Eingaben richtig gemacht wurden, sollte die folgende printf()-Anweisung den Wert »2« ausgeben. Mit einer kleinen Ãberprüfung können Sie das Programm verbessern, um ein undefiniertes Verhalten für die Weiterarbeit zu verhindern: > /* scanf7.c */ #include <stdio.h> int main(void) { int a, b, check; printf("Bitte zwei Zahlen eingeben: "); check = scanf("%d %d",&a ,&b); fflush(stdin); /* unter Linux entfernen */ //getchar(); /* für Linux */ /* Ist check gleich 2, war die Eingabe richtig. */ if(check == 2) printf("Beide Zahlen richtig %d und %d\n",a ,b); /* ... nicht richtig, also war die 2. Zahl falsch. */ else if(check == 1) { printf("Die 2.Zahl hat das falsche Format!!\n"); printf("Bitte Eingabe wiederholen: "); /* noch ein Versuch */ check = scanf("%d",&b); fflush(stdin); if(check) printf("Eingabe Ok. Ihre Zahlen %d %d\n",a,b); else printf("Leider nochmals falsch\n"); } else printf("Die erste oder beide Eingaben waren falsch!\n" ); return 0; } Bei fehlerfreier Ausführung liefert die scanf()-Funktion die Anzahl der Zeichen zurück, die erfolgreich gelesen, konvertiert und gespeichert wurden. Wenn die erste Eingabe von scanf() im Beispiel schon fehlerhaft ist, wird die zweite Eingabe gar nicht mehr beachtet. Daher gibt scanf() dann 0 zurück, da gar keine Zeichen gespeichert werden konnten. Abbildung 4.5 Die Ãberprüfung des Rückgabewertes von »scanf()« ### 4.1.4 Zusammenfassung zu »scanf()« Die Funktion scanf() liest zeichenweise eine Folge von Eingabefeldern ein. Für jedes Eingabefeld muss eine Adresse vorhanden sein, wobei das Eingabefeld mit dem Datentyp der Adresse übereinstimmen muss. Bei Erfolg liefert scanf() die Anzahl der erfolgreich eingelesenen Felder zurück. Konnten keine Felder korrekt eingelesen werden, gibt scanf() als Rückgabewert 0 zurück. Für den Fall, dass bei der Eingabe schon ein Fehler auftrat, bevor die Daten überhaupt gelesen werden konnten, wird EOF zurückgegeben. Folgende Zeichen werden bei scanf() als Eingabefelder akzeptiert: * alle Zeichen bis zum nächsten Whitespace * alle Zeichen bis zu einer bestimmten Feldbreite von n * alle Zeichen bis zu dem ersten Zeichen, das nicht mehr in ein entsprechendes Format konvertiert werden konnte Whitespace | | --- | | Anmerkung für den Anfänger | | --- | | In diesem Kapitel erfahren Sie alles zu den einzelnen Datentypen in C, ohne die sich wohl kaum ein Programm realisieren lassen würde. Zu den Grundlagen der C-Programmierung gehört auch die Kenntnis der einzelnen Datentypen. Datentypen sind, wie der Name schon vermuten lässt, Arten von Variablen, in denen Sie Daten speichern können, um zu einem späteren Zeitpunkt wieder darauf zurückzugreifen. Diese Variablen bestehen aus zwei Teilen: dem Datentyp, der eine bestimmte Menge Arbeitsspeicher zugewiesen bekommt, und dem Namen der Variable, mit dem dieser Datentyp im Programm angesprochen werden kann. Als Basisdatentypen werden einfache vordefinierte Datentypen bezeichnet. Dies umfasst in der Regel Zahlen (int, short int, long int, float, double und long double), Zeichen (char, wchar_t) und den (Nichts-)Typ (void). ## 5.1 Deklaration und Definition Beginnen wir mit dem etwas unbequemeren Abschnitt. Die Begriffe Deklaration und Definition werden oft durcheinandergebracht oder auch als ein und dasselbe verwendet. Mit einer Deklaration machen Sie den Compiler mit einem Namen (Bezeichner) bekannt und verknüpfen diesen Namen mit einem Typ. Der Typ wiederum beinhaltet die Informationen über die Art der Bezeichner und bestimmt somit implizit die Aktionen, die auf dem Speicherobjekt zulässig sind. Bei einer Ganzzahl z. B. sind hierbei die arithmetischen Operationen +, -, *, / als Aktionen zulässig. Die Syntax einer einfachen Deklaration sieht somit immer wie folgt aus: > Typ name; Typ name1, name2, name3; Mit Typ geben Sie immer den Datentyp an, und name ist immer der Bezeichner. Natürlich können Sie, wie Sie im zweiten Beispiel sehen, auch mehrere Bezeichner eines Typs durch Kommata voneinander trennen. Mit einer Deklaration geben Sie dem Compiler nur Informationen zum Typ bekannt. Bis dahin wurde noch keine Zeile Maschinencode erzeugt, geschweige denn ein Speicherobjekt (Variable) angelegt. Für das konkrete Speicherobjekt im Programm bzw. in dem ausführbaren Code wird die Definition vereinbart. Somit ist jede Definition gleichzeitig auch eine Deklaration. Gleiches gilt auch häufig andersherum, beispielsweise gibt die Deklaration einer Variable vom Datentyp int in der folgenden ausgeführten Art > int i; den Namen des Speicherobjekts bekannt und vereinbart somit auch den Speicherplatz für das Objekt. Ebenso kann der Name einer Variablen mit dem Speicherklassenattribut extern vereinbart werden, ohne dass ein Objekt erzeugt wird. Damit kann es für jedes Objekt im Programm zwar beliebig viele Deklarationen geben, aber nur eine einzige Definition. # Was ist eine Variable? Eine Variable ist eine Stelle (Adresse) im Hauptspeicher (RAM), an der Sie einen Wert ablegen können und gegebenenfalls später wieder darauf zurückgreifen können. Neben einer Adresse hat eine Variable auch einen Namen, genauer gesagt einen Bezeichner, mit dem man auf diesen Wert namentlich zugreifen kann. Und natürlich belegt eine Variable auch eine gewisse GröÃe des Hauptspeichers, was man mit dem Typ der Variablen mitteilt. Rein syntaktisch kann man das wie folgt ausdrücken: > long lvar; Hier haben Sie eine Variable mit dem Namen (Bezeichner) lvar vom Typ long, der üblicherweise vier Bytes (auf 32-Bit-Systemen) im Hauptspeicher (RAM) belegt. Wo (d. h. an welcher Speicheradresse) im Arbeitsspeicher Speicherplatz für diese Variable reserviert wird – hier vier Bytes –, können Sie nicht beeinflussen. Zum Berechnen und Weiterverarbeiten von Variableninhalten gibt _$ret_es viele Operatoren in C. Im Folgenden wird die Verwendung solcher Operatoren besprochen. ## 6.1 Exkurs zu Operatoren Damit auch Nicht-Mathematiker oder Hobby-Programmierer verstehen, wie sich Operatoren unterscheiden, hierzu beginnen wir mit einem kleinen Exkurs. Operatoren werden hinsichtlich der Zahl ihrer Operanden unterschieden: * unär – der Operator hat einen Operanden. * binär – der Operator hat zwei Operanden. * ternär – der Operator hat drei Operanden. In C werden Sie vorwiegend mit unären und binären Operatoren arbeiten. Es gibt aber auch einen ternären Operator. Des Weiteren wird unterschieden, welche Position der Operator einnimmt: * Infix – der Operator steht zwischen den Operanden. * Präfix – der Operator steht vor den Operanden. * Postfix – der Operator steht hinter den Operanden. Vorwiegend werden Sie es mit der Infix-Schreibweise zu tun haben. Einige unäre Operatoren können sowohl in der Präfix- als auch in der Postfix-Schreibweise verwendet werden. Und schlieÃlich werden die Operatoren noch hinsichtlich der Assoziativität differenziert. Als Assoziativität wird die Auswertungsreihenfolge bezeichnet, in der Operanden in einem Ausdruck ausgewertet werden. Dabei gibt es folgende Assoziativitäten der Operatoren: * Linksassoziativität * Rechtsassoziativität Der GroÃteil der Operatoren in C ist linksassoziativ. Das bedeutet z. B., dass bei folgendem Ausdruck > var1 + var2 - var3; zuerst var1 mit var2 addiert wird. AnschlieÃend wird var3 von der Summe subtrahiert. Wären die Operatoren rechtsassoziativ, würde zuerst var3 von var2 subtrahiert und danach das Ergebnis mit var1 addiert werden. Ist dies erwünscht, müssen Klammern gesetzt werden: > var1 + (var2 - var3); Nachdem diese sprachlichen Stolpersteine beseitigt sind, können wir uns mit den einzelnen Operatoren in der Programmiersprache C befassen. In diesem Kapitel erfahren Sie, wie in C bestimmte Datentypen in andere konvertiert werden und wie Sie dies selbst beeinflussen können. Wenn Sie in C einen Datentyp in einen anderen konvertieren (umwandeln), vollziehen Sie ein Type-Casting. Es gibt zwei Möglichkeiten, den Datentyp zu ändern: * Der Compiler nimmt eine automatische Konvertierung von einem zum anderen Datentyp vor. Dies geschieht, wenn Sie z. B. einem int-Wert einen float-Wert zuweisen. Man spricht dabei von einer impliziten Datentypumwandlung. * Der Programmierer kann die Konvertierung des Datentyps durch eine explizite Typumwandlung erzwingen. Bei beiden Vorgehensweisen wird vorausgesetzt, dass der Compiler eine Typumwandlung auch wirklich unterstützt. ## 7.1 Implizite Datentypumwandlung Wenn man in Ausdrücken Operanden unterschiedlicher Datentypen miteinander über Operanden verknüpft, sind implizite Datentypumwandlungen nötig. Wie diese implizite (automatische) Umwandlung vor sich geht und worauf Sie gegebenenfalls achten müssen, soll in den folgenden Abschnitten näher erläutert werden. ### 7.1.1 Implizites »char« nach »int« Ein char wird bei Bewertungen und Berechnungen immer in ein int umgewandelt. Es wird mit nichts Kleinerem gerechnet als mit int. Nehmen wir beispielsweise folgende Berechnung: > char val1 = 10, val2 = 20, val3; val3 = val1 + val2; Zwar haben Sie hier char-Datentypen verwendet, aber der Compiler führt hier trotzdem eine implizite Datentypumwandlung nach int durch. Daraus kann man ableiten, dass int und char beliebig mischbar sind. Diese »char nach int«-Umwandlung ist auch von Bedeutung beim Einlesen einzelner Zeichen und beim Ãberprüfen auf EOF. ### 7.1.2 Implizites »float« nach »double« Dasselbe, was ich schon zuvor über »char nach int« geschrieben habe, gilt für implizite Umwandlungen von float nach double. Auch hierbei wird bei Berechnungen ein float automatisch in ein double konvertiert. Daher erfolgen alle Berechnungen immer mit derselben Genauigkeit. ### 7.1.3 Implizite Umwandlung in einen komplexen Gleitpunkttyp Bei einer Umwandlung einer reellen Gleitpunktzahl oder ganzen Zahl in einen komplexen Gleitpunkttyp (C99) erhält der Realteil den Wert der reellen Gleitpunktzahl bzw. ganzen Zahl. Der Imaginärteil hingegen ist 0. Bei der Umwandlung von komplexen Gleitpunkttypen in einen anderen komplexen Typ wird der Typ wie bei den reellen Gegenstücken umgewandelt. ### 7.1.4 Ãbliche arithmetische Datentypumwandlung Die Operanden eines binären Operators dürfen in C einen unterschiedlichen skalaren Datentyp besitzen. Durch die übliche arithmetische Datentypumwandlung wird dabei implizit ein gemeinsamer Datentyp gebildet. Dazu wird die ganzzahlige Erweiterung ausgeführt. Treten danach noch Operanden mit verschieden Typen auf, wird in den Typ desjenigen Operanden umgewandelt, der in der nebenstehenden Hierarchie am weitesten oben steht. Das Ergebnis ist ebenfalls von diesem Typ. Für die Hierarchie von ganzzahligen Typen gelten folgende Regeln: * Bei ganzzahligen Standardtypen gilt folgende Rangfolge: > char < short < int < long < long long * Die Rangfolge bei ganzzahligen Typen ist unabhängig vom Vorzeichen. Der Typ int hat beispielsweise denselben Rang wie signed int und unsigned int. * Der Rang eines Standardtyps ist immer gröÃer als der Rang eines erweiterten ganzzahligen Typs in <stdint.h> (C99) mit gleicher Breite. So ist der Rang von int höher als der von int_least32_t, obwohl beide die gleiche Breite besitzen. Bei der Hierarchie von Gleitpunkttypen gelten folgende Regeln: * Die Rangfolge der Gleitpunkttypen sieht folgendermaÃen aus: > float < double < long double * bzw. für die komplexen Gegenstücke: > float _Complex < double _Complex < long double _Complex * Gleitpunkttypen haben immer einen höheren Rang als ganzzahlige Typen. Bei der Zuweisung wird der rechte Operand immer in den Typ des linken Operanden umgewandelt. Dabei werden überzählige (Nachkomma-)Stellen oder höherwertige Bits, die nicht mehr Platz haben, einfach abgeschnitten: Es wird nicht gerundet. Wenn der Originalwert im neuen Typ nicht mehr darstellbar ist, findet ein Ãberlauf statt, und das Ergebnis hat mit dem Originalwert meist nicht mehr viel gemein. Bezogen auf diese Aussage, finden Sie in der folgenden Tabelle eine Zusammenfassung, was passiert, wenn Sie einem Datentyp (linker Operand) einen anderen Datentyp (rechter Operand) zuweisen (Operator). Typ | Operand | Typ | Umwandlung | | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | Bei der üblichen arithmetischen Datentypumwandlung gibt es folgende Punkte, die Sie unbedingt beachten sollten: * Bei der Umwandlung von höherwertigen Datentypen in niederwertigere Datentypen kann es zu Informationsverlust kommen. * Der Verleich von signed- und unsigned-Typen kann falsch sein. So kann beispielsweise -1 > 1U wahr sein. * Die Division zweiter int-Werte gibt immer nur einen Ganzzahlanteil zurück. Hier findet keine automatische Konvertierung in eine Gleitpunktzahl statt. * die Umwandlung eines negativen Wertes in einen Typ ohne Vorzeichen * Bei der Umwandlung von ganz groÃen Zahlen (beispielsweise long long) in einen Gleitpunkttyp kann es passieren, dass die Genauigkeit nicht mehr ausreicht, um die Zahl genau darzustellen. Hierzu noch ein einfaches Listing mit solchen üblichen arithmetischen Datentypumwandlungen: > /* implizitCasts.c */ #include <stdio.h> int main(void) { // Nachkommateil wird weggelassen. int float2int = 3.8; // Höherwertige Bits werden abgeschnitten. char int2char = 1000; float char2float = 'A'; float long2float = 444444444; printf("float2int : %d\n", float2int ); printf("int2char : %c\n", int2char ); printf("char2float: %f\n", char2float ); printf("long2float: %f\n", long2float ); return 0; } Bei mir gibt das Programm beispielsweise Folgendes aus: > float2int : 3 int2char : à char2float: 65.000000 long2float: 444444448.000000 Mit dem bisherigen Wissen können Sie die Programme immer nur sequenziell ablaufen lassen. Sie laufen also immer Zeile für Zeile ab. In diesem Kapitel wird nun der sequenzielle Programmfluss gebrochen. Sie haben folgende drei Möglichkeiten, um den sequenziellen Programmfluss zu ändern: * Verzweigungen: Im Programm wird eine Bedingung definiert, die entscheidet, an welcher Stelle das Programm fortgesetzt werden soll. * Schleifen (Iteration): Ein Anweisungsblock wird so oft wiederholt, bis eine bestimmte Abbruchbedingung erfüllt wird. * Sprünge: Die Programmausführung wird mithilfe von Sprungmarken an einer anderen Position fortgesetzt. Obwohl sie nach wie vor möglich sind, werden Sprünge in einem Programm mittlerweile als schlechter Stil angesehen. Sie sind auch nicht notwendig. Mit dem bisher Gesagten meine ich direkte Sprünge. Mit Schlüsselwörtern wie return, break, continue, exit und der Funktion abort() können jedoch kontrollierte Sprünge ausgeführt werden. ## 8.1 Verzweigungen mit der »if«-Bedingung Die if-Bedingung hat folgende Syntax: > if(BEDINGUNG == wahr) { Anweisung1; } Anweisung2; Wenn die Bedingung zwischen den Klammern des if-Schlüsselwortes wahr (true) ist, wird Anweisung1 im Anweisungsblock ausgeführt. AnschlieÃend wird das Programm bei Anweisung2, also nach dem Anweisungsblock, fortgesetzt. Ist die Bedingung unwahr (false), wird Anweisung1 nicht ausgeführt, und das Programm fährt sofort mit Anweisung2 fort. ### 8.1.1 Anweisungsblock In einem Anweisungsblock werden Anweisungen (mindestens eine) zusammengefasst. Als Anweisungsblock gelten alle Anweisungen, die zwischen geschweiften Klammern ({}) stehen. Anweisungsblöcke lassen sich auch ineinander verschachteln. Es empfiehlt sich daher, beim Erstellen eines Programms auf eine saubere Strukturierung (d. h. entsprechendes Einrücken bei den Anweisungen eines Blocks) zu achten, um den Ãberblick zu wahren. Den Programmablauf der if-Bedingung können Sie sich schematisch so vorstellen wie in Abbildung 8.1 (die Darstellung wird auch als Programmablaufplan bezeichnet): Abbildung 8.1 Programmablaufplan zur »if«-Anweisung Sehen Sie sich dazu das folgende Programmbeispiel an: > /* if1.c */ #include <stdio.h> int main(void) { unsigned int alter; printf("Wie alt sind Sie: "); scanf("%u", &alter); /* ... noch jünger als 18? */ if(alter < 18) { printf("Sie sind noch nicht volljährig\n"); } printf("Bye\n"); return 0; } Das Programm fordert Sie auf, Ihr Alter einzugeben. In der Bedingung if(zahl < 18) wird überprüft, ob Sie jünger als 18 Jahre sind. Sind Sie jünger, wird die printf()-Anweisung im Anweisungsblock mit entsprechender Ausgabe bearbeitet. Wurde aber ein Wert eingegeben, der gröÃer oder gleich 18 ist, wird nur die printf()-Anweisung hinter dem Anweisungsblock ausgeführt, die »Bye« ausgibt. Abbildung 8.2 zeigt den Programmablaufplan zu diesem Beispiel: Abbildung 8.2 Programmablaufplan zum Listing Jetzt soll das Programm um einige if-Bedingungen erweitert werden: > /* if2.c */ #include <stdio.h> int main(void) { unsigned int alter; printf("Wie alt sind Sie: "); scanf("%u", &alter); if(alter < 18) { printf("Sie sind noch nicht volljährig\n"); } if(alter > 18) { printf("Sie sind volljährig\n"); } if(alter == 18) { printf("Den Führerschein schon bestanden?\n"); } printf("Bye\n"); return 0; } Es ist offensichtlich, wie das Programm vorgeht: Sie geben das Alter ein, und mithilfe der einzelnen if-Bedingungen testet es, ob die eingegebene Zahl gröÃer, kleiner oder gleich 18 ist. Bevor das Programm etwas genauer analysiert wird, sollten Sie sich eine Tabelle mit den bisher verwendeten Vergleichsoperatoren und ihrer jeweiligen Bedeutung ansehen. Vergleichsoperator | Bedeutung | | --- | --- | | | | | | | | | | | | | Zurück zum Programm. Die erste Anweisung > if(alter < 18) testet, ob die Zahl, die Sie eingegeben haben, kleiner als 18 ist. Ist die Bedingung wahr, springt das Programm unmittelbar in den für diese Bedingung geschriebenen Anweisungsblock, der in den geschweiften Klammern steht. Falls also die eingegebene Zahl kleiner als 18 ist, wird der Anweisungsblock > { printf("Sie sind noch nicht volljährig\n"); } ausgeführt. Besteht der Anweisungsblock hinter der Kontrollstruktur lediglich aus einer einzigen Anweisung, so können die geschweiften Klammern auch weggelassen werden: > if(alter < 18) printf("Sie sind noch nicht volljährig\n"); Diese Schreibweise ist korrekt und wird auch häufig verwendet. Sie sollten sich jedoch klarmachen, dass sie sehr leicht zur Fehlerquelle werden kann – nämlich dann, wenn Sie eine weitere Anweisung hinzufügen wollen, die auch nur in dem Fall ausgeführt werden soll, wenn die if-Bedingung wahr ist, wie etwa im folgenden Beispiel: > if(alter < 18) printf("Sie sind noch nicht volljährig\n"); printf("Sollte nur erscheinen, wenn (alter < 18)!\n"); Wenn – wie hier – dann die geschweiften Klammern vergessen werden, wird die zweite printf()-Anweisung immer ausgeführt, da die if-Bedingung im Wahr-Fall wirklich nur eine weitere Anweisung ausführt. Korrekt müsste es folgendermaÃen aussehen: > if(alter < 18) { printf("Sie sind noch nicht volljährig\n"); printf("Sollte nur erscheinen, wenn (alter < 18)!\n"); } Jetzt wird auch die zweite Anweisung nur ausgeführt, wenn die if-Bedingung wahr ist. Die nächsten beiden if-Bedingungen verhalten sich analog. Hiermit wird getestet, ob die eingegebene Zahl für das Alter kleiner bzw. gleich 18 ist. Sollte sich einer dieser Fälle als wahr herausstellen, so wird ebenfalls der jeweils zugehörige Anweisungsblock ausgeführt. Funktionen werden nicht nur in C, sondern auch in vielen anderen Programmiersprachen verwendet. Wenn Sie von einer anderen Sprache zu C gewechselt haben, kennen Sie Funktionen möglicherweise auch unter den Namen »Subroutine«, »Unterprogramm« oder »Subfunktion«. ## 9.1 Was sind Funktionen? Funktionen sind kleine Unterprogramme, mit denen Sie Teilprobleme einer gröÃeren Aufgabe lösen können. In der Praxis können Sie sich das so vorstellen: Eine Funktion führt eine komplizierte Berechnung aus, eine andere Funktion schreibt das Ergebnis der Berechnung in eine Datei, und wieder eine andere überprüft das Ergebnis auf Fehler. Die parallele Ausführung von Funktionen ist in ANSI C allerdings nicht möglich. Funktionen werden also in der Regel wie normale Anweisungen auch nur sequenziell, das heiÃt nacheinander, ausgeführt. In diesem Kapitel erfahren Sie einiges zum Präprozessor. Der Präprozessor ist ein Teil des Compilers, der noch vor der Ãbersetzung einige Ãnderungen am Quelltext vornimmt. Wenn in der Sprache C ein Programm übersetzt (kompiliert und gelinkt) werden soll, dann wird, bevor der Compiler den Quelltext verarbeitet, von einem besonderen Teil des Compilers – dem Präprozessor – ein zusätzlicher Ãbersetzungslauf durchgeführt. Bei Präprozessor-Direktiven steht immer das Zeichen # am Anfang der Zeile. AuÃerdem darf pro Zeile nur eine Direktive eingesetzt werden. Folgendes ist also nicht erlaubt: > #include <stdio.h> #include <stdlib.hKommentare hingegen dürfen sehr wohl hinter einer Direktive stehen: > #include <stdio.h> /* Headerdatei für Standardfunktionen */ Die folgenden Arbeiten fallen für den Präprozessor neben der Quelltextersetzung ebenfalls an: * Stringliterale werden zusammengefasst (konkateniert). * Zeilenumbrüche mit einem Backslash am Anfang werden entfernt. * Kommentare werden entfernt und durch Leerzeichen ersetzt. * Whitespace-Zeichen zwischen Tokens werden gelöscht. Des Weiteren gibt es Aufgaben für den Präprozessor, die vom Programmierer gesteuert werden können: * Header- und Quelldateien in den Quelltext kopieren (#include) * symbolische Konstanten einbinden (#define) * bedingte Kompilierung (#ifdef, #elseif, ...) Auf die Präprozessor-Direktiven, die Sie als Programmierer selbst steuern können, gehe ich auf den folgenden Seiten ein. ## 10.1 Einkopieren von Dateien mittels »#include« Die Direktive #include kopiert andere, benannte (Include-)Dateien in das Programm ein. Meistens handelt es sich dabei um Headerdateien mit der Extension *.h oder *.hpp. Hier sehen Sie die Syntax der Präprozessor-Direktive include: > #include <header > #include "header" Der Präprozessor entfernt die include-Zeile und ersetzt diese durch den Quelltext der include-Datei. Der Compiler erhält anschlieÃend einen modifizierten Text zur Ãbersetzung. Natürlich können Sie damit eigene Headerdateien schreiben und diese einkopieren lassen. Sie haben beispielsweise eine Headerdatei geschrieben und diese im Verzeichnis /HOME/MYOWNHEADERS unter dem Namen meinheader.h gespeichert. Dann müssen Sie diese Headerdatei am Anfang des Quelltextes mit > #include "/home/myownheaders/meinheader.h" einkopieren. Dabei muss dasjenige Verzeichnis angegeben werden, in dem die Headerdatei gespeichert wurde. Steht die Headerdatei hingegen zwischen eckigen Klammern (wie dies bei Standardbibliotheken meistens der Fall ist), also so: > #include <datei.hso wird die Headerdatei datei.h im implementierungsdefinierten Pfad gesucht. Dieser Pfad befindet sich in dem Pfad, in dem sich die Headerdateien Ihres Compilers befinden. Steht die Headerdatei zwischen zwei Hochkommata, also so: > #include "datei.h" so wird diese im aktuellen Arbeitsverzeichnis oder in dem Verzeichnis gesucht, das mit dem Compiler-Aufruf -I angegeben wurde – vorausgesetzt, Sie übersetzen das Programm in der Kommandozeile. Sollte diese Suche erfolglos sein, so wird in denselben Pfaden gesucht, als wäre #include <datei.h> angegeben. Abbildung 10.1 zeigt die einzelnen Schritte, durch die aus dem Quellcode eine ausführbare Datei wird (von oben nach unten). Abbildung 10.1 Von der Quelldatei zur ausführbaren Datei Tabelle 10.1 enthält eine Ãbersicht der Standard-Headerdateien, die von ANSI C vorgeschrieben sind: Beim C99-Standard (bzw. C95) sind dann noch folgende Headerdateien neu hinzugekommen (sie sind allerdings nicht in allen Compilern vorhanden): Bisher habe ich mich bei den speicherorientierten Strukturelementen auf einfache Datentypen beschränkt. Bei den Aufgaben wurden lediglich ganze Zahlen (char, short, int, long) bzw. FlieÃkommazahlen (float, double, long double) besprochen. In diesem Kapitel erfahren Sie nun etwas über zusammengesetzte Datenstrukturen, kurz Arrays. Mit Arrays haben Sie die Möglichkeit, eine geordnete Folge von Werten eines bestimmten Typs abzuspeichern und zu bearbeiten. Arrays werden auch als Vektoren, Felder oder Reihungen bezeichnet. ## 11.1 Arrays deklarieren Die Syntax zur Deklaration eines Arrays sieht wie folgt aus: > Datentyp Arrayname[Anzahl_der_Elemente]; Als Datentyp geben Sie an, von welchem Datentyp die Elemente des Arrays sein sollen. Der Arrayname ist frei wählbar, mit denselben Einschränkungen für Bezeichner wie bei Variablen. Mit Anzahl_der_Elemente wird die Anzahl der Elemente angegeben, die im Array gespeichert werden können. Man spricht dabei auch vom Indexwert. Ein Array, das aus Elementen unterschiedlicher Datentypen besteht, gibt es in C nicht. Angesprochen wird das gesamte Array mit allen Komponenten über den Array-Namen. Die einzelnen Elemente eines Arrays werden durch den Array-Namen und einen Indexwert (in eckigen Klammern) verwendet. Der Indexwert selbst wird über eine Ordinalzahl (Ganzzahl) angegeben und fängt bei null an zu zählen. Anhand der folgenden Zeile wird ein Array jetzt näher untersucht: > int i[5]; Durch diese Deklaration wird Platz für fünf Variablen im Array i vom Datentyp int im Speicher reserviert. In diesem Array können somit fünf Integerwerte gespeichert werden (siehe Abbildung 11.1). Wie Sie in der Abbildung sehen, wurde ein Array vom Typ int deklariert. Mit dieser Deklaration wurde automatisch auch Speicherplatz für fünf int-Werte reserviert. Bei vier Bytes für eine int-Variable (je nach System) würden 20 Bytes im Arbeitsspeicher des Rechners belegt werden. Demnach benötigt ein Array wie z. B. double abc[2000] 16.000 Bytes. Alte C-Compiler hatten bei groÃen Arrays Probleme mit der Speicherverwaltung, da der Speicher auf 64 KB beschränkt war. (Es gab natürlich Tricks, diese Schwierigkeiten zu umgehen, darauf soll hier aber nicht näher eingegangen werden.) Bei modernen 32-Bit-Compilern dürften Sie in der Praxis wohl nie an irgendwelche Grenzen stoÃen. Abbildung 11.1 Anordnung eines Arrays mit fünf Werten In diesem Kapitel geht es um das vielleicht wichtigste und vielseitigste Thema in der Programmiersprache C: die Zeiger. Dabei handelt es sich allerdings um ein Thema, das oft nicht auf Anhieb verstanden wird. Aber ist die Zeigerarithmetik erst einmal klar, erscheinen die Hürden der fortgeschrittenen Kapitel nicht mehr so hoch. Also: Ist das Thema Zeiger kein Problem mehr, ist es auch die Programmiersprache C nicht mehr. Im Grunde sind Zeiger aber gar nicht so kompliziert, wie sie oft dargestellt werden. Zeiger sind im Prinzip nichts anderes als ganz normale Variablen, die statt Datenobjekten wie Zahlen, Zeichen oder Strukturen eben Adressen eines bestimmten Speicherbereichs beinhalten. Was können Sie mit Zeigern auf Adressen so alles machen? Hierzu ein kleiner Ãberblick über die Anwendungsgebiete von Zeigern: * Speicherbereiche können dynamisch reserviert, verwaltet und wieder gelöscht werden. * Mit Zeigern können Sie Datenobjekte direkt (call-by-reference) an Funktionen übergeben. * Mit Zeigern lassen sich Funktionen als Argumente an andere Funktionen übergeben. * Rekursive Datenstrukturen wie Listen und Bäume lassen sich fast nur mit Zeigern erstellen. * Es lässt sich ein typenloser Zeiger (void *) definieren, womit Datenobjekte beliebigen Typs verarbeitet werden können. Auf den nächsten Seiten erläutere ich erst einmal die Grundlagen der Zeiger (die häufig auch Pointer genannt werden). Im Laufe des Buchs werden dann die zuvor genannten Punkte besprochen. Ich empfehle Ihnen, sich für dieses Kapitel viel Zeit zu nehmen. Es stellt auf jeden Fall die Grundlage für den Fortgang des Buchs und Ihre Karriere als C-Programmierer dar. ## 12.1 Zeiger deklarieren Die Deklaration eines Zeigers hat die folgende Syntax: > Datentyp *zeigervariable; Der Datentyp des Zeigers muss vom selben Datentyp wie der sein, auf den er zeigt (referenziert). Das Sternchen vor zeigervariable kennzeichnet den Datentyp als Zeiger. Im Fachjargon heiÃt dieser Operator Indirektionsoperator. Die Position für das Sternchen befindet sich zwischen dem Datentyp und dem Zeigernamen. Beispiel: > int *zeiger1; int* zeiger2; char *zeiger3; char* zeiger4; float *zeiger5; Hier sehen Sie zwei verschiedene Schreibweisen, wobei beide richtig sind; es hat sich aber folgende eingebürgert: > int *zeiger1; int *zeiger2; int *zeiger3; Mit dieser Schreibweise wird der gemachte Fehler deutlicher: > int *zeiger1 ,zeiger2; Hier wurde nur ein Zeiger deklariert, was auch recht schnell zu sehen ist. Bei der folgenden Schreibweise ist dieser Fehler nicht mehr so eindeutig zu erkennen: > int* zeiger1 ,zeiger2; Hier könnte man fälschlicherweise annehmen, es seien zwei Zeiger deklariert worden. Am besten verwenden Sie also die übliche Schreibweise. Damit können Sie sich einige Probleme ersparen. In der heutigen »Look&Feel«-Zeit scheinen Kommandozeilenprogramme schon ein wenig veraltet zu sein. Die nächste Generation wird mit Begriffen wie »Kommandozeile« oder »Konsole« wohl nichts mehr anzufangen wissen. Wenn aber z. B. ältere Programme überholt werden müssen, wird der Umgang mit der Kommandozeile wieder wichtig. Bei Betriebssystemen wie Linux, UNIX oder FreeBSD ist es nach wie vor üblich (teilweise sogar unerlässlich), sehr viel mit einer Kommandozeile zu arbeiten. Beim Schreiben eines Konsolenprogramms für Linux/UNIX oder MS-DOS (Eingabeaufforderung) sind Kommandozeilenparameter immer noch eines der wichtigsten Konzepte. Da Konsolenprogramme keine grafische Oberfläche besitzen, stellt die Kommandozeile die wichtigste Schnittstelle zwischen dem Anwender und dem Programm dar. ## 13.1 Argumente an die Hauptfunktion übergeben Um einem Programm beim Start Argumente zu übergeben, wird eine parametrisierte Hauptfunktion benötigt. Ihre Syntax sieht wie folgt aus: > int main(int argc, char *argv[]) { /* ... */ } Diese Hauptfunktion main() besitzt zwei Parameter mit den Namen argc und argv. Die Namen dieser Parameter sind so nicht vorgeschrieben. Sie können genauso gut Folgendes schreiben: > int main(int argumenten_zaehler, char *argumenten_vektor[]) { /* ... */ } Der erste Parameter beinhaltet die Anzahl von Argumenten, die dem Programm beim Start übergeben wurden. Dabei handelt es sich um einen Integerwert. Im zweiten Parameter stehen die einzelnen Argumente. Diese werden als Strings in einer Stringtabelle gespeichert. Folgendes Beispiel demonstriert dies: > /* argument.c */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i; for(i=0; i < argc; i++) { printf("argv[%d] = %s ", i, argv[i]); printf("\n"); } return EXIT_SUCCESS; } Das Listing wurde z. B. unter dem Namen argument.c gespeichert und anschlieÃend übersetzt. Wenn Sie das Programm starten, wird auf dem Bildschirm der Programmname ausgegeben: > argv[0] = argument Starten Sie das Programm jetzt nochmals mit folgender Eingabe (argument sei wieder der Programmname): > argument <NAME> Abbildung 13.1 zeigt die Ausgabe, die Sie dann erhalten. Abbildung 13.1 Argumente aus der Kommandozeile auswerten In argv[0] befindet sich meistens der Programmname, das muss aber nicht so sein. Ein Beispiel: > char *argv_for_new_app[] = {"ganzAndererName", ....argumente}; char *application = "/bin/bash"; execve(application, argv_for_new_app, envp); Somit ist in argv[0] der Bash nun eben »ganzAndererName« zu lesen. Das ist u. a. ein effektiver Workaround für DOS/Windows-Plattformen, die keine Symlinks haben (d. h., manche Programme erkennen ihre Funktion an argv[0]). Die einzelnen Argumente, die dem Programm übergeben werden, müssen immer durch mindestens ein Leerzeichen getrennt sein. Wenn Sie zum Beispiel > argument HalloWelt schreiben, wäre die Ausgabe stattdessen: > argv[0] = argument argv[1] = HalloWelt Der Parameter int argc zählt die Anzahl der Strings, die dem Programm beim Aufruf mitgegeben wurden. Dazu ein Beispiel: > /* arg_counter.c */ #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { printf("Insgesamt %d Argumente\n", argc-1); printf("Letztes Argument: %s\n", argv[argc-1]); return EXIT_SUCCESS; } Bei diesem Beispiel werden die Anzahl der Argumente und das letzte Argument ausgegeben. Als Programmaufruf dient etwa: > argument abc xyz In der Stringtabelle char **argv befinden sich die Strings, die Sie in Abbildung 13.2 sehen. Abbildung 13.2 Inhalt der Stringtabelle »argv« Falls dezimale Werte anstelle von Strings als Argumente übergeben werden, handelt es sich dabei weiterhin um Strings. Wird der dezimale Wert benötigt, so muss der String erst in einen solchen Wert konvertiert werden. Hier sehen Sie ein Beispiel einer solchen Konvertierung: > /* calc.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { int i, j ; long y, erg; if(argc < 4) { printf("Benötige mindestens 4 Argumente!\n"); printf("Aufruf: %s <zahl><op><zahl> ...\n", *argv); return EXIT_FAILURE; } /* 1.Zahl in einen Integer konvertieren*/ erg = strtol(argv[1], NULL, 10); if( erg == 0 ) { printf("Keine gültige Ganzzahl ... \n"); return EXIT_FAILURE; } for(i = 1; i < argc-1; i += 2) { for(j=i+1; j < i+2; j++) { y = strtol(argv[i+2], NULL, 10); if( y == 0 ) { printf("Keine gültige Ganzzahl ... \n"); printf("argc: %d (%s)?!\n", i+2, argv[i+2]); return EXIT_FAILURE; } if(strcmp(argv[j],"+") == 0) erg += y; else if(strcmp(argv[j],"-") == 0) erg -= y; else if(strcmp(argv[j], "x") == 0) erg *= y; else if(strcmp(argv[j],"/") == 0) erg/=y; else { printf("Ungültiger Operand: %s\n", argv[j]); return EXIT_FAILURE; } } } printf("%ld\n",erg); return EXIT_SUCCESS; } Damit lassen sich einfache Rechenoperationen ausführen. Im Folgenden soll eine solche Eingabe demonstriert werden (der Programmname sei hierfür calc): > calc 5 + 5 - 9 x 10 / 2 Intern sieht diese Eingabe so aus: Abbildung 13.3 Einzelne Argumente für Rechenoperationen auswerten Hier wurden zehn Argumente eingegeben, wobei jedes dieser zehn Argumente ein Stringende-Zeichen (\0) besitzt. Somit besitzt der Parameter int argc in der Funktion main() den Wert 9. Beachten Sie bei der Eingabe, dass nach jedem Zeichen ein Leerzeichen folgt. Folgendes würde nicht funktionieren: > calc 5+5-9x10/2 /* falsch, nur ein Argument*/ Mit > if(argc < 4) { printf("Benötige mindestens 4 Argumente!\n"); printf("Aufruf: %s <zahl><op><zahl> ...\n", *argv); return EXIT_FAILURE; } wird getestet, ob weniger als vier Argumente eingegeben wurden. Falls dies zutrifft, wird eine entsprechende Fehlermeldung auf dem Bildschirm ausgegeben und das Programm beendet. Wenn die Mindestanzahl von Argumenten gegeben ist, folgt als Nächstes die Konvertierung der Argumente: > erg = strtol(argv[1], NULL, 10); Hierbei wird mit der Funktion strtol der String in argv[1] in eine dezimale Zahl konvertiert. Im ersten Fall wird der String "5" in den Integerwert 5 umgewandelt. Die Funktion strtol() ist in der Headerdatei <stdlib.h> deklariert. Mehr zu strtol() und weiteren ähnlichen Funktionen erwartet Sie in Kapitel 20, »Weitere Headerdateien und ihre Funktionen (ANSI C)«. Weiter mit dem Programmablauf bei den for-Schleifen: > for(i = 1; i < argc-1; i += 2) { for(j=i+1; j < i+2; j++) { y = strtol(argv[i+2], NULL, 10); Die erste for-Schleife durchläuft die ungeraden Zahlen des Feldindex, in dem sich (bei richtiger Anwendung des Programms) dezimale Zahlen befinden: [1]="5", [3]="5", [5]="9", [7]="10", [9]="2". Die zweite for-Schleife durchläuft die geraden Zahlen und dient den Operatoren +, -, * und / ([2]="+", [4]="–", [6]="*", [8]="/"). Danach bekommt die Variable y den dezimalen Wert der Zeichenkette argv[3], der wiederum mit strtol() konvertiert wird. Jetzt erfolgt die Auswertung des Operators: > if(strcmp(argv[j],"+") == 0) erg += y; Entspricht argv[2] dem Additionszeichen "+"? In dem Fall ist das zweite Argument tatsächlich das Zeichen "+". Daher kann jetzt der erste Wert (zweites Argument) mit dem zweiten Wert (viertes Argument) addiert (drittes Argument) werden. Der Wert wird in der Variablen erg zwischengespeichert. Genauso läuft dies mit den nächsten Zahlen und Operatoren ab, bis keine Argumente (Zahlen oder Operatoren) mehr vorhanden sind. Bisher legen Sie Daten wie Arrays in einem statischen Speichersegment im Programm ab. Wenn sich allerdings die Anzahl der Elemente zur Laufzeit verändert oder ein Speicher nicht dauerhaft benötigt wird, ist ein solcher statischer Speicher nicht geeignet. In diesem Kapitel erfahren Sie daher, wie Sie Speicherblöcke mit variabler GröÃe zur Laufzeit des Programms anfordern können. Bisher wurde die Speicherverwaltung in Variablendefinitionen versteckt. Sie mussten sich so zwar keine Gedanken über die Verwaltung machen, aber spätestens dann, wenn Sie neuen Speicher für weitere Daten benötigten, musste der Code umgeschrieben werden. Es kann auch Probleme mit der Gültigkeit einer Variablen geben. Eine Variable existiert nur in dem Anweisungsblock, in dem sie deklariert wurde. Die Gültigkeit des Speicherbereichs dieser Variablen verfällt, sobald dieser Anweisungsblock verlassen wird. Ausnahmen stellen globale und als static deklarierte Variablen dar. Bei der dynamischen Speicherverwaltung gibt es diese Probleme nicht mehr. Zur dynamischen Speicherverwaltung wird ein Zeiger mithilfe der Funktion malloc() verwendet. Mit dieser Funktion geben Sie an, wie viel Speicherplatz reserviert werden soll. Der Zeiger verweist bei erfolgreicher Reservierung auf die Anfangsadresse des reservierten Speicherblocks. Die Aufgabe des Programmierers ist es, dafür zu sorgen, dass es immer einen Zeiger gibt, der auf diese Anfangsadresse verweist. Der so reservierte Speicher bleibt so lange erhalten, bis dieser entweder explizit mit der Funktion free() freigegeben wird oder bis das Programm sich beendet. Sie müssen natürlich einen gewissen Aufwand betreiben, um die dynamische Speicherverwaltung zu realisieren. Wenn Sie dabei unvorsichtig zu Werke gehen, haben Sie schnell eine Zugriffsverletzung mit einem Zeiger verursacht. Ebenfalls zu Problemen kann es kommen, wenn Sie bei einem Programm immer wieder Speicher reservieren und dieser niemals mehr freigegeben wird. Man spricht dabei von Speicherlecks (engl. Memory Leaks). Wie diese und andere Probleme vermieden werden, erfahren Sie in den folgenden Abschnitten. ## 14.1 Das Speicherkonzept Bevor gezeigt wird, wie Speicher dynamisch reserviert werden kann, folgt ein Exkurs über das Speicherkonzept von laufenden Programmen. Ein Programm besteht aus den vier Speicherbereichen, die in Tabelle 14.1 aufgeführt sind. Speicherbereich | Verwendung | | --- | --- | | | | | | | | | # Code-Speicher Der Code-Speicher wird in den Arbeitsspeicher geladen, und von dort aus werden die Maschinenbefehle der Reihe nach in den Prozessor (genauer gesagt in die Prozessor-Register) geschoben und ausgeführt. # Daten-Speicher Im Daten-Speicher befinden sich alle statischen Daten, die bis zum Programmende verfügbar sind (globale und statische Variablen). # Stack-Speicher Im Stack-Speicher werden die Funktionsaufrufe mit ihren lokalen Variablen verwaltet. In Abschnitt 9.20.1, »Exkurs: Stack«, bin ich schon näher auf den Stack eingegangen. # Heap-Speicher Dem Heap-Speicher gebührt in diesem Kapitel das Hauptinteresse. Ãber ihn wird die dynamische Speicherreservierung mit Funktionen wie malloc() erst realisiert. Der Heap funktioniert ähnlich wie der Stack. Bei einer Speicheranforderung erhöht sich der Heap-Speicher, und bei einer Freigabe wird er wieder verringert. Wenn ein Speicher angefordert wurde, sieht das Betriebssystem nach, ob sich im Heap noch genügend zusammenhängender freier Speicher dieser GröÃe befindet. Bei Erfolg wird die Anfangsadresse des passenden Speicherblocks zurückgegeben. Bisher wurden mit den Arrays Datenstrukturen desselben Typs verwendet. In dem folgenden Kapitel werden jetzt unterschiedliche Datentypen zu einer Struktur zusammengefasst. AnschlieÃend können Sie auf diese Struktur zugreifen wie auf einfache Variablen. ## 15.1 Struktur deklarieren Als Beispiel dient hier ein Programm zur Verwaltung von Adressdaten mit folgenden Variablen: > char vname[20]; char nname[20]; long PLZ; char ort[20]; int geburtsjahr; Bei Ihrem jetzigen Kenntnisstand müsste jeder einzelne Parameter extra bearbeitet werden, sei es das Einlesen, Bearbeiten oder Ausgeben von Daten. Die Entwickler der Programmiersprache C haben zum Glück auch daran gedacht. Sie müssen einfach alle Variablen in eine Struktur verpacken. Bei den Adressdaten sieht dies dann so aus: > struct adres { char vname[20]; char nname[20]; long PLZ; char ort[20]; int geburtsjahr; } adressen; Alle Daten wurden in einer Struktur (struct) namens adres zusammengefasst. Die Sichtbarkeit und die Lebensdauer von Strukturen entsprechen exakt der Sichtbarkeit und Lebensdauer von einfachen Variablen. Der Inhalt der Struktur adres wird in geschweiften Klammern zusammengefasst. Am Ende der geschweiften Klammern steht der Variablen-Bezeichner (adressen), mit dem auf die Struktur zugegriffen wird. Zur Deklaration einer Struktur in C dient folgende Syntax: > struct typNAME { Datentyp1; Datentyp2; ......... /* Liste der Strukturelemente */ Datentyp_n; } Variablen_Bezeichner; Strukturelemente sind im Prinzip nichts anderes als normale Variablen, die als Teil einer Struktur definiert werden. Als Datentypen kommen alle bekannten Typen in Frage – natürlich und vor allem auch Zeiger und Strukturen selbst. Folgende Struktur können Sie sich im Speicher so vorstellen: > struct index { int seite; char titel[30]; }; Abbildung 15.1 Strukturelemente der Struktur »index« In diesem Beispiel wurde eine Struktur vom Typ index deklariert. Diese Struktur kann einen int-Wert und einen String von 30 Zeichen Länge aufnehmen. Folglich wäre die GesamtgröÃe der Struktur 34 Bytes (auf 16-Bit-Systemen entsprechend 32 Bytes). Was wäre eine Programmiersprache, ohne dass Daten gespeichert werden können – zum Beispiel auf einen Datenträger? In diesem sehr umfangreichen Kapitel geht es ausschlieÃlich um den Fluss der Daten. Gemeint sind damit die Eingabe und Ausgabe von Daten. ## 16.1 Was ist eine Datei? Häufig wendet man elementare Datei-E/A-Funktionen (E/A steht für Eingabe/Ausgabe) an, ohne sich Gedanken darüber zu machen, was eine Datei eigentlich ist. Im Prinzip können Sie sich eine Datei als ein riesengroÃes char-Array vorstellen. Das char-Array besteht dabei aus einer Folge von Bits und Bytes – unabhängig davon, ob es sich um eine Textdatei oder eine ausführbare Datei handelt. Sehen Sie sich mit einem Hex-Editor einmal eine ausführbare Datei aus der Sicht des Computers an. Wenn Sie dasselbe mit einer Textdatei machen, werden Sie feststellen, dass es keine gravierenden Unterschiede zwischen den beiden Dateien gibt. Es wird dabei von einem Byte Stream oder einfach kurz von einem Stream gesprochen. Das Ermitteln der Eigenschaften einer Datei oder das Ãffnen und Auslesen eines Verzeichnisses sind systemabhängig. Denn jedes Betriebssystem verwaltet Dateien und Verzeichnisse auf andere Art. Daher wird in Büchern oft auf dieses Thema verzichtet. In diesem Kapitel versuche ich, es so universell wie möglich zu behandeln. ## 17.1 Attribute einer Datei ermitteln – »stat()« Der Funktion stat() wird die Adresse der Struktur struct stat übergeben. Aus dieser Struktur können die Attribute der Datei ausgelesen werden. Die Syntax dazu lautet: > #include <sys/stat.h> /* LINUX/UNIX */ #include <sys/types.h> /* LINUX/UNIX */ #include <sys\stat.h> /* MS-DOS/WINDOWS */ int stat(const char *pfad, struct stat *puffer); Mit stat() werden somit die Attribute der Datei, die Sie mit pfad angeben, in die Adresse der Strukturvariablen puffer geschrieben. Ein Beispiel: > struct stat attribut; stat("testprogramm.txt", &attribut); ... if(attribut.st_mode & S_IFCHR) printf("Datei ist eine Gerätedatei"); Hiermit wird getestet, ob die Datei testprogramm.txt eine Gerätedatei ist. Es folgt eine Auflistung der einzelnen Variablen der Struktur struct stat, in der sich die jeweiligen Attribute zu einer Datei befinden. Dabei ist wiederum anzumerken, dass es Unterschiede zwischen Linux/UNIX und MS-DOS/Windows gibt. Tabelle 17.1 enthält die einzelnen Elemente der Struktur stat. ### 17.1.1 »stat()« – »st_mode« Mit dem Strukturelement short st_mode in der Struktur stat können Sie die Dateiart erfragen. Dazu verknüpfen Sie den bitweisen UND-Operator (&) und den in st_mode gespeicherten Wert mit einer der Konstanten aus Tabelle 17.2. POSIX schreibt diese Konstanten allerdings nicht vor. Bei Linux/UNIX-Systemen könnten diese Konstanten auch als entsprechende Makros in der Headerdatei <sys/stat.h> implementiert sein. Der Makroname entspricht dabei dem Konstantennamen (S_IFREG(), S_IFDIR(), S_IFCHR(), S_ISBLK(), S_ISFIFO(), S_IS–LINK() und S_ISSOCK()). Alle diese Makros geben 1 zurück, wenn Entsprechendes zutrifft, ansonsten 0. Im folgenden Listing können Sie über Argumente aus der Kommandozeile beliebig viele Dateien dahingehend abfragen, ob es sich um eine reguläre Datei (S_IFREG), eine zeichenorientierte Gerätedatei (S_IFCHR) oder ein Verzeichnis (S_IFDIR) handelt. > /* file_chk.c */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #else #include <sys\stat.h> #endif int main(int argc, char *argv[]) { struct stat attribut; if(argc == 1) { printf("%s = ",*argv); if(stat(*argv, &attribut) == -1) { fprintf(stderr,"Fehler bei stat ...\n"); return EXIT_FAILURE; } if(attribut.st_mode & S_IFREG) printf("Reguläre Datei\n"); else if(attribut.st_mode & S_IFDIR) printf("Directory\n"); else if(attribut.st_mode & S_IFCHR) printf("Gerätedatei\n"); else printf("Unbekannte Datei\n"); } else { while(*++argv) { printf("%s = ",*argv); if(stat(*argv, &attribut) == -1) { fprintf(stderr,"Fehler bei stat (2)...\n"); return EXIT_FAILURE; } if(attribut.st_mode & S_IFREG) printf("Reguläre Datei\n"); else if(attribut.st_mode & S_IFDIR) printf("Directory\n"); else if(attribut.st_mode & S_IFCHR) printf("Gerätedatei\n"); else printf("Unbekannte Datei\n"); }/* Ende while */ } return EXIT_SUCCESS; } Abbildung 17.1 Erfragen der Dateiart mit »st_mode« Zuerst werden in der Schleife mit > if(stat(*argv, &attribut) == -1) die Attribute der Datei *argv in die Adresse der Strukturvariablen attribut geschrieben. AnschlieÃend werden einige Attribute mit den folgenden Zeilen abgefragt, um zu ermitteln, um welche Dateiart es sich hierbei handelt: > if(attribut.st_mode & S_IFREG) printf("Reguläre Datei\n"); else if(attribut.st_mode & S_IFDIR) printf("Directory\n"); else if(attribut.st_mode & S_IFCHR) printf("Gerätedatei\n"); else printf("Unbekannte Datei\n"); Danach fährt die Programmausführung mit dem nächsten Argument in der Kommandozeile fort. Wenn sich das Listing bei Ihnen nicht übersetzen lässt und Sie unter Linux/UNIX arbeiten, sollten Sie es mit den entsprechenden Makros probieren: > if( S_IFREG(attribut.st_mode) ) printf("Reguläre Datei\n"); else if( S_IFDIR(attribut.st_mode) ) printf("Directory\n"); else if( S_IFCHR(attribut.st_mode) ) printf("Gerätedatei\n"); else printf("Unbekannte Datei\n"); Mit dem Strukturelement st_mode in der Struktur stat lassen sich die Zugriffsrechte einer Datei ebenfalls abfragen. Dies funktioniert genauso wie bei der Abfrage der Dateiart. Zudem müssen Sie den bitweisen UND-Operator (&) mit einer der unter Linux/UNIX vorgegebenen Konstanten verknüpfen (siehe Tabelle 17.3). Konstante | Bedeutung | Benutzerklasse | | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | Bei MS-DOS/Windows gibt es zum Erfragen der Zugriffsrechte die Möglichkeiten, die Tabelle 17.4 aufführt. Hierzu ein Beispiel für Linux/UNIX: > /* check_rwx.c */ #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char *argv[]) { struct stat attribut; int i; char l_rwx[10]; char rwx[] = "rwxrwxrwx"; int bits[] = { S_IRUSR,S_IWUSR,S_IXUSR, /* Zugriffsrechte User */ S_IRGRP,S_IWGRP,S_IXGRP, /* Zugriffsrechte Gruppe */ S_IROTH,S_IWOTH,S_IXOTH /* Zugriffsrechte der Rest */ }; while(*++argv) { /* einzelne Argumente durchlaufen */ l_rwx[0]='\0'; printf("%18s = ",*argv); if(stat(*argv, &attribut) == -1) { fprintf(stderr,"Fehler bei stat?!?...\n"); return EXIT_FAILURE; } for(i = 0; i < 9; i++) { /* wenn nicht 0, dann gesetzt */ if(attribut.st_mode & bits[i]) l_rwx[i]=rwx[i]; /*r,w oder x*/ else l_rwx[i] = '-'; /*wenn nicht gesetzt, dann '-'*/ } l_rwx[9]='\0'; printf("%s\n",l_rwx); }/*Ende while*/ return EXIT_SUCCESS; } Abbildung 17.2 Ausgabe der Zugriffsrechte unter Linux/UNIX Dieses Listing stellt eine einfache Methode dar, wie die Zugriffsrechte einer Datei oder eines Verzeichnisses in gewohnter Linux-Manier ausgegeben werden können. Bei MS-DOS/Windows können Sie so vorgehen: > if(attribut.st_mode & S_IREAD) { /* Datei darf nur gelesen werden */ } else if(attribut.st_mode & S_IWRITE) { /* Datei darf beschrieben werden */ } else if(attribut.st_mode & S_IEXEC) { /* Datei ist eine ausführbare (bsp. *.exe */ } Wird hingegen bei Linux/UNIX die oktale Darstellung der Zugriffsrechte benötigt, können Sie dies folgendermaÃen erreichen: > /* permission_oct.c */ #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char *argv[]) { struct stat attribut; while(*++argv) { /* einzelne Argumente durchlaufen */ printf("%18s = ",*argv); if(stat(*argv, &attribut) == -1) { fprintf(stderr,"Fehler bei stat?!?...\n"); return EXIT_FAILURE; } printf("%o\n", attribut.st_mode & 0777); } return EXIT_SUCCESS; } ### 17.1.2 »stat()« – »st_size« Kommen wir nun zu einem weiteren Parameter der Struktur stat. Um die GröÃe einer Datei in Bytes zu ermitteln, kann die Strukturvariable st_size verwendet werden. Ein Wert wird aber nur für reguläre Dateien und Verzeichnisse (bei MS-DOS/Windows 0 für Verzeichnisse) zurückgegeben. Beim Filesystem werden dabei nicht die einzelnen Bytes angegeben, sondern immer ganze Blöcke von Bytes. Typische BlockgröÃen sind 512 oder 1024 Bytes. Das bedeutet, die Variable von st_size gibt nicht den physikalischen Speicher einer Datei aus, den diese wirklich belegt. Das folgende Programm gibt die GröÃe aller Dateien auf dem Bildschirm aus, die Sie in der Kommandozeile angeben. > /* size.c */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ #include <sys/stat.h> #include <sys/types.h> #else #include <sys\stat.h> #endif int main(int argc, char *argv[]) { struct stat attribut; unsigned long sizeofall=0; if(argc == 1) { if(stat(*argv, &attribut) == -1) { fprintf(stderr,"Fehler bei stat....\n"); return EXIT_FAILURE; } else { printf("GröÃe von %s = %ld Bytes\n", *argv,attribut.st_size); return EXIT_SUCCESS; } } else { while(*++argv) { if(stat(*argv, &attribut) == -1) { fprintf(stderr,"Fehler bei stat....\n"); return EXIT_FAILURE; } else { printf("GröÃe von %s = %ld Bytes\n", *argv,attribut.st_size); sizeofall += attribut.st_size; } } } printf("GröÃe aller Dateien in der " " Kommandozeile = %ld Bytes",sizeofall); printf("= %ld KB\n",sizeofall/=1024); return EXIT_SUCCESS; } Abbildung 17.3 GröÃe von Dateien mit »st_size« ermitteln Wie ich bereits erwähnt habe, gelingt es unter Windows/MS-DOS nicht, die GröÃe eines Verzeichnisses zu erhalten. Bei UNIX/Linux hingegen funktioniert das schon, da Verzeichnisse hier wie normale Dateien behandelt werden. ### 17.1.3 »stat()« – »st_atime«, »st_mtime« und »st_ctime« Um spezielle Zeitdaten einer Datei abzufragen, befinden sich in der Struktur stat folgende Variablen: * st_atime = Zeit des letzten Zugriffs * st_mtime = Zeit der letzten Ãnderung des Dateiinhalts * st_ctime = Zeit der letzten Inode-Ãnderung Die Unterscheidung dieser drei Zeitattribute trifft nur für Linux/UNIX zu. Bei MS-DOS/Windows bedeuten alle drei Zeiten dasselbe: nämlich den Zeitpunkt, zu dem die Datei das letzte Mal geändert wurde. Dazu ein Beispiel: Von allen Dateien, die Sie in der Kommandozeile eingeben, wird die Zeit des letzten Zugriffs und die Zeit der letzten Ãnderung ausgegeben: > /* ch_time.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> #ifdef __unix__ #include <sys/stat.h> #include <sys/types.h> #else #include <sys\stat.h> #endif int main(int argc, char *argv[]) { struct stat attribut; unsigned long sizeofall=0; if(argc == 1) { if(stat(*argv, &attribut) == -1) { fprintf(stderr,"Fehler bei stat....\n"); return EXIT_FAILURE; } else { printf("Groesse von %s = %ld Bytes\n", *argv,attribut.st_size); printf("letzter Zugriff : %s", ctime(&attribut.st_atime)); printf("letzte Aenderung: %s", ctime(&attribut.st_mtime)); return EXIT_SUCCESS; } } else { while(*++argv) { if(stat(*argv, &attribut) == -1) { fprintf(stderr,"Fehler bei stat....\n"); return EXIT_FAILURE; } else { printf("Groesse von %s = %ld Bytes\n", *argv,attribut.st_size); printf("letzter Zugriff : %s", ctime(&attribut.st_atime)); printf("letzte Aenderung: %s\n", ctime(&attribut.st_mtime)); sizeofall += attribut.st_size; } } } printf("Groesse aller Dateien in der " "Kommandozeile = %ld Bytes",sizeofall); printf("= %ld KB\n",sizeofall/=1024); return EXIT_SUCCESS; } Abbildung 17.4 Abfragen verschiedener Zeitdaten unter Linux Das Programm wurde mit dem vorherigen Beispiel vermischt. Auf diese Weise wird gleichzeitig die GröÃe der Datei inklusive der letzten Ãnderung und des letzten Zugriffs auf die Datei ausgegeben. Unter Linux lässt sich auÃerdem mithilfe der Variablen st_atime und st_mtime beim Kopieren einer Datei verhindern, dass diese beiden Werte verändert werden. Gemeint ist damit Folgendes: Wenn Sie eine Datei beispielsweise mit cp kopieren, werden normalerweise alle drei Werte auf das aktuelle Datum gesetzt. Wollen Sie das Datum des Originals erhalten (letzter Zugriff und Ãnderung des Inhalts), können Sie folgendermaÃen vorgehen: > /* manipulate_time.c */ #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <utime.h> #include <fcntl.h> int main(int argc, char *argv[]) { FILE *q,*z; struct stat attribut; char buf[1024]; int i; struct utimbuf zeit; /* siehe Funktion utimes() */ if(stat(argv[1],&attribut) < 0) { fprintf(stderr, "Fehler bei stat ...\n"); return EXIT_FAILURE; } zeit.actime = attribut.st_atime; zeit.modtime= attribut.st_mtime; q=fopen(argv[1],"r"); z=fopen(argv[2],"w"); if(q == NULL || z == NULL) { fprintf(stderr,"Fehler bei fopen ...\n"); return EXIT_FAILURE; } while( (i=fread(buf, 1, 1024, q)) > 0 ) fwrite(buf, 1, i, z); /* Wichtig!!! Ohne den Stream zu schlieÃen, wird die * aktuelle Zeit verwendet, da die Datei erst nach * return 0 beendet wird. */ fclose(q); fclose(z); /* Jetzt die Zeit von quelle in ziel eintragen */ if(utime(argv[2], &zeit) < 0) { printf("Fehler bei utime() ...\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } Kopieren Sie einmal eine Datei mittels cp, und sehen Sie sich die Zeiten mit ls –l, ls -lu und ls -lc an. Bei der Ãberprüfung der Zeitangabe werden Sie feststellen, dass alle drei Zeitdaten auf dieselbe Zeit gesetzt wurden. Wiederholen Sie dies nun mit dem eben geschriebenen Programm. Bei einem erneuten Blick auf die Zeitdaten sind die Variablen st_atime und st_mtime jetzt identisch mit der Originaldatei. Hätten Sie in diesem Listing fclose() nicht oder erst nach der Funktion utime() verwendet, so würde wieder der aktuelle Zeitstempel gesetzt, da dies den letzten Zugriff darstellt. Wollen Sie herausfinden, welche von zwei Dateien älter ist, können Sie dies mit der Strukturvariablen st_mtime ermitteln: > /* older_file.c */ #include <sys/stat.h> #include <stdio.h> #include <time.h> #include <stdlib.h> time_t st_mTime(char *name) { struct stat s; if (stat(name, &s)) { perror(name); exit(EXIT_FAILURE); } return s.st_mtime; } int main(int argc, char *argv[]) { time_t t1, t2; if (argc == 3) { t1 = st_mTime(argv[1]), t2 = st_mTime(argv[2]); if(t1 != t2) printf("%s ist %s wie %s\n" ,argv[1],(t1>t2?"neuer":"älter"),argv[2]); else printf("Beide Dateien sind gleich alt\n"); } else { fprintf(stderr, "Verwendung %s datei1 datei2\n",argv[0]); return EXIT_FAILURE; } return EXIT_SUCCESS; } In diesem Listing wurde die Headerdatei <time.h> verwendet, um den Rückgabetyp time_t zu verwenden. Zu dieser Headerdatei finden Sie im Buch noch einen eigenen Abschnitt (19.1). ### 17.1.4 »stat()« – »st_gid« und »st_uid« Um herauszufinden, wer der Eigentümer und der Gruppeneigentümer einer Datei ist, können Sie sich der Variablen st_uid (Eigentümer) und st_gid (Gruppeneigentümer) bedienen. Hierzu das Listing: > /* ugid.c */ #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char *argv[]){ struct stat attribut; while(*++argv) { if(stat(*argv,&attribut) < 0) { fprintf(stderr, "Fehler bei stat ...\n"); return EXIT_FAILURE; } printf("\n%18s\n", *argv); printf("USER-ID : %d\n", attribut.st_uid); printf("GROUP-ID : %d\n\n", attribut.st_gid); } return EXIT_SUCCESS; } ### 17.1.5 »stat()« – »st_nlink«, »st_ino« Weitere Informationen zu einer Datei unter Linux lassen sich mit den Variablen st_nlink (Anzahl der Links) und st_ino (Inode-Nummer der Datei) ausgeben: > /* link_ino.c */ #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char *argv[]){ struct stat attribut; while(*++argv) { if(stat(*argv,&attribut) < 0) { fprintf(stderr, "Fehler bei stat ...\n"); return EXIT_FAILURE; } printf("\n%18s\n",*argv); printf("Anzahl Links : %d\n",attribut.st_nlink); printf("Inode Nummer : %d\n\n",attribut.st_ino); } return EXIT_SUCCESS; } ### 17.1.6 »stat()« – »st_dev«, »st_rdev« Die Strukturvariablen st_dev und st_rdev sind recht nützlich für Gerätedateien. Bei MS-DOS/Windows haben beide Variablen dieselbe Bedeutung: * st_dev – enthält für jeden Dateinamen die Gerätenummer des Filesystems, in dem sich diese Dateien und ihr zugehöriger Inode befinden. (Windows/MS-DOS und Linux/UNIX). * st_rdev – hat nur für zeichen- und blockorientierte Gerätedateien einen definierten Wert, nämlich die Gerätenummer des zugeordneten Geräts. Die majornummer legt den Gerätetyp fest, während der minornummer der entsprechende Gerätetreiber übergeben wird. So werden verschiedene Geräte des gleichen Typs unterschieden (nur Linux/UNIX). Das Folgende ist ein Beispielprogramm nur für MS-DOS/Windows. Das Programm liefert zu angegebenen Dateinamen den Laufwerksnamen zurück: > /* lfwrk.c */ #include <stdio.h> #include <stdlib.h> #include <sys\stat.h> int main(int argc, char *argv[]) { struct stat laufwerknr; if(argc==1) { fprintf(stderr, "usage:%s Datei1 Datei2 Datei3\n", *argv); return EXIT_FAILURE; } while(*++argv) { printf("%s = Laufwerk : ",*argv); if(stat(*argv, &laufwerknr) == -1) { fprintf(stderr,"..Fehler bei stat...!\n"); return EXIT_FAILURE; } else printf("%c (%d)\n", laufwerknr.st_dev + 'A',laufwerknr.st_dev); } return EXIT_SUCCESS; } Abbildung 17.5 Ermittlung des Laufwerks, in dem sich die Datei befindet Ein kurze Erklärung zu: > laufwerknr.st_dev + 'A' Da der PC die Laufwerke nicht – wie Sie es gewohnt sind – mit > A:\ = 1. Diskettenlaufwerk B:\ = 2. Diskettenlaufwerk C:\ = 1.Festplatte D:\ = 2.Festplatte oder CD-ROM-Laufwerk ................usw. bis Z:\ falls vorhanden erkennt, sondern mit Nummern wie > 0 = 1. Diskettenlaufwerk 1 = 2. Diskettenlaufwerk 2 = 1.Festplatte 3 = 2.Festplatte oder CD-ROM-Laufwerk wurde einfach die dezimale Ziffer 0 + 'A' hinzuaddiert. Dies gelingt, weil das Zeichen 'A' intern für den Wert 65 steht (siehe ASCII-Tabelle) und anschlieÃend auch das Formatzeichen char für 65 (%c = char) ausgegeben wird. Somit wird z. B. für das Laufwerk 2 der Buchstabe C zurückgegeben (2+'A' = 67; ASCII-codiert = 'C'). Das Beispiel dazu für Linux/UNIX sieht so aus: > /* b_c_file.c */ #include <sys/sysmacros.h> #include <sys/stat.h> #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { struct stat statpuffer; if(argc == 1) { fprintf(stderr, "usage: %s Datei1 Datei2 ....\n", *argv); return EXIT_FAILURE; } while(*++argv) { printf("%s: ",*argv); if(stat(*argv, &statpuffer) == -1) fprintf(stderr,"Fehler bei stat...\n"); else { printf("dev = %2d/%2d",major(statpuffer.st_dev), minor(statpuffer.st_dev)); if(S_ISCHR(statpuffer.st_mode)|| S_ISBLK(statpuffer.st_mode)) { printf("-> rdev = %2d/%2d (%s", major(statpuffer.st_rdev), minor(statpuffer.st_rdev), (S_ISCHR(statpuffer.st_mode))?"zeichen" :"block"); printf("orientiert"); } } printf("\n"); } return EXIT_SUCCESS; } Vielleicht noch ein Wort zu dieser Zeile: > if(S_ISCHR(statpuffer.st_mode)|| S_ISBLK(statpuffer.st_mode)) Hiermit wird überprüft, ob es sich um eine zeichenorientierte (S_ISCHR) oder eine blockorientierte (S_ISBLK) Gerätedatei handelt. Es erfolgt dann eine entsprechende Ausgabe. In diesem Kapitel lernen Sie Möglichkeiten kennen, wie Sie Funktionen mit einer variablen Anzahl von Argumenten aufrufen können. Dass in C Funktionen mit variabel langen Argumentlisten aufgerufen werden können, dürfte Ihnen an Funktionen wie printf() oder scanf() bereits aufgefallen sein. Die Deklaration von printf() sieht wie folgt aus: > int printf(const char* format, ...); Anhand dieser Deklaration erkennen Sie auch, dass printf() mindestens ein festes Argument (const char *format) und eine variable Anzahl optionaler Argumente erwartet. Die variable Anzahl optionaler Argumente erkennen Sie an den drei Punkten, dem zweiten Parameter von printf(). Diese drei Punkte werden Ellipse genannt. Die Verwendung von printf() ohne weitere Argumente kennen Sie ja: > printf("ohne weitere Argumente\n"); Jetzt folgt dasselbe mit zwei Argumenten: > printf("Ich habe %d %s\n", argument2, argument1); Anhand der beiden Formatzeichen %d und %s ist jetzt bekannt, dass dort zwei Argumente folgen. ## 18.1 Makros in <stdarg.h> – »va_list«, »va_arg«, »va_start« und »va_end« Damit Sie eigene Funktionen mit einer variablen Argumentliste schreiben können, sind in der Headerdatei <stdarg.h> folgende vier Makros deklariert: Date: 2009-02-20 Categories: Tags: In der C-Standard-Bibliothek sind einige Funktionen enthalten, mit denen Sie die Zeit bestimmen können. Die Zeit umfasst dabei das Datum und die Uhrzeit. ## 19.1 Die Headerdatei <time.hEs folgen einige Standardfunktionen der Headerdatei <time.h>, in denen Routinen für Zeit und Datum deklariert sind. Tabelle 19.1 gibt Ihnen einen kurzen Ãberblick über die speziellen (primitiven) Datentypen in dieser Headerdatei und ihre Bedeutungen. Laut ANSI-C-Standard sollten in der Struktur tm folgende Komponenten enthalten sein: »struct tm«-Variable | Bedeutung | | --- | --- | | | | | | | | | | | | | | | | | | | Auf Linux-Systemen sind auÃerdem noch folgende Komponenten vorhanden: > long int tm_gmtoff; tm_gmtoff gibt die Sekunden östlich von UTC bzw. den negativen Wert westlich von UTC für die Zeitzonen an. UTC steht für Universal Time Coordinated und dient als Bezeichnung für eine auf der gesamten Erde einheitliche Zeitskala. Die Universal Time ist identisch mit der Greenwich Mean Time (GMT). Diese Angabe kann aber auch unter > long int __tm_gmtoff vorliegen. Ebenfalls nur bei Linux ist folgende Komponente enthalten: > const char *tm_zone; Diese Variable enthält den Namen der aktuellen Zeitzone. Diese kann auch in folgender Schreibweise angegeben sein: > const char *__tm_zone; ### 19.1.1 Konstanten in der Headerdatei <time.hFolgende zwei Konstanten sind in der Headerdatei <time.h> deklariert: * CLOCKS_PER_SEC – Die Konstante enthält die Anzahl von clock_t-Einheiten pro Sekunde. * NULL – Das ist derselbe NULL-Zeiger, den Sie schon in der Headerdatei <stdio.h> kennengelernt haben. ### 19.1.2 Datums- und Zeitfunktionen in <time.hDie Zeit, mit der der Systemkern arbeitet, ist die Anzahl der Sekunden, die seit dem 1. Januar 1970, 00:00:00 Uhr, vergangen sind. Diese Zeit wird immer mit dem Datentyp time_t dargestellt und enthält das Datum und die Uhrzeit. Diese Zeit kann mit der Funktion > time_t time(time_t *zeitzeiger); ermittelt werden. Wird für den Parameter zeitzeiger kein NULL-Zeiger verwendet, befindet sich an dieser Adresse die aktuelle Systemzeit. Hierzu folgt nun ein kleines Listing, das die Zeit in Sekunden fortlaufend seit dem 1. Januar 1970 um 00:00:00 Uhr mithilfe der Funktion time() ausgibt: > /* time1.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> #ifdef __unix__ #define clrscr() printf("\x1B[2J") #else #include <stdlib.h> #define clrscr() system("cls") #endif int main(void) { time_t t; time(&t); while(1) { clrscr(); printf("%ld\n",t); printf("Mit <STRG><C> bzw. <STRG><D> beenden!! "); time(&t); } return EXIT_SUCCESS; } Ob es nach dem »Jahr 2000«-Problem zum Jahre 2038 zum nächsten Problem kommt, bleibt noch offen. Bei vielen Rechnern ist time_t als long implementiert, womit Platz für etwa 2 Milliarden Sekunden wäre. Dies wäre im Jahr 2038 erreicht. Der Standard schreibt hier nicht vor, welchen Wert time_t haben soll, und somit ist der Wertebereich von der Implementierung abhängig. # »localtime()« und »gmtime()« – Umwandeln von »time_t« in »struct tm« Die Ausgabe der Sekunden als Zeitformat ist nicht gerade originell. Sie könnten jetzt anfangen, Funktionen zu schreiben, mit denen der Rückgabewert der Funktion time() in ein entsprechendes Format umgerechnet wird. Oder Sie verwenden bereits geschriebene Standardfunktionen wie: > struct tm *localtime(const time_t *zeitzeiger); struct tm *gmtime(const time_t *zeitzeiger); Beide Funktionen liefern als Rückgabewert die Adresse einer Zeitangabe vom Typ struct tm. Diese Struktur wurde bereits zu Beginn dieses Kapitels behandelt. Die Funktion localtime() wandelt die Kalenderzeit der Adresse time_t *zeitzeiger in lokale Ortszeit um – unter der Berücksichtigung von Sommer- und Winterzeit. gmtime() dagegen wandelt die Kalenderzeit in die UTC-Zeit um. Hierzu ein Beispiel, das die Eingabe eines Geburtsdatums erwartet und anschlieÃend das Alter in Jahren, Monaten und Tagen ausgibt: > /* time2.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> struct tm *tmnow; void today(void) { time_t tnow; time(&tnow); tmnow = localtime(&tnow); printf("Heute ist der "); printf("%d.%d.%d\n", tmnow->tm_mday, tmnow->tm_mon + 1, tmnow->tm_year + 1900); } int main(void) { int tag, monat, jahr; unsigned int i=0, tmp; printf("Bitte gib Deinen Geburtstag ein!\n"); printf("Tag : "); scanf("%d", &tag); printf("Monat : "); scanf("%d", &monat); printf("Jahr (jjjj) : "); scanf("%d", &jahr); today(); if(tmnow->tm_mon < monat) { i = 1; tmp=tmnow->tm_mon+1-monat; monat=tmp+12; } else { tmp=tmnow->tm_mon+1-monat; monat=tmp; } if(monat == 12) { monat = 0; i = 0; } printf("Sie sind %d Jahre %d Monat(e) %d Tag(e) alt\n", tmnow->tm_year+1900-jahr-i,monat, tmnow->tm_mday-tag); return EXIT_SUCCESS; } Abbildung 19.1 Verwendung der Funktion »localtime()« Eine Anmerkung zur if else-Bedingung im Programm: Diese war erforderlich, damit im Monatsdatum kein negativer Wert zurückgegeben wird und Sie nicht auf einmal 1 Jahr älter sind. # »mktime()« – Umwandeln von »struct tm« in »time_t« Kommen wir jetzt zum Gegenstück der Funktionen localtime() und gmtime(): > time_t mktime(struct tm *zeitzeiger); Auf diese Weise wird eine Zeit im struct tm-Format wieder in eine Zeit im time_t-Format umgewandelt. Ist die Kalenderzeit nicht darstellbar, gibt diese Funktion –1 zurück. Die echten Werte der Komponenten tm_yday und tm_wday in zeitzeiger werden ignoriert. Die ursprünglichen Werte der Felder, tm_sec, tm_min, tm_hour, tm_mday und tm_mon, sind nicht auf den durch die tm-Struktur festgelegten Bereich beschränkt. Befinden sich die Felder nicht im korrekten Bereich, werden diese angepasst. Das heiÃt konkret: Wird z. B. das fehlerhafte Datum 38.3.2001 eingegeben, muss die Funktion mktime() dieses Datum richtig setzen. Bei richtiger Rückgabe erhalten Sie entsprechende Werte für tm_yday und tm_wday. Der zulässige Bereich für die Kalenderzeit liegt zwischen dem 1. Januar 1970, 00:00:00 Uhr, und dem 19. Januar 2038, 03:14:07 Uhr. Ein Beispiel soll zeigen, wie Sie den genauen Wochentag durch diese Funktion ermitteln können: > /* time3.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> char *wday[] = { "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "??????" }; int main(void) { struct tm time_check; int year, month, day; /* Jahr, Monat und Tag eingeben zum * Herausfinden des Wochentags */ printf("Jahr : "); scanf("%d", &year); printf("Monat: "); scanf("%d", &month); printf("Tag : "); scanf("%d", &day); /* Wir füllen unsere Struktur struct tm time_check * mit Werten. */ time_check.tm_year = year - 1900; time_check.tm_mon = month - 1; time_check.tm_mday = day; /* 00:00:01 Uhr */ time_check.tm_hour = 0; time_check.tm_min = 0; time_check.tm_sec = 1; time_check.tm_isdst = -1; if(mktime(&time_check) == -1) time_check.tm_wday = 7; /* = unbekannter Tag */ /* Der Tag des Datums wird ausgegeben. */ printf("Dieser Tag ist/war ein %s\n", wday[time_check.tm_wday]); return EXIT_SUCCESS; } # »asctime()« und »ctime()« – Umwandeln von Zeitformaten in einen String Mit zwei Funktionen können die beiden Zeitformen struct tm und time_t in einen String konvertiert werden. Hier sehen Sie die Syntax der beiden: > char *asctime(struct tm *zeitzeiger); char *ctime(const time_t *zeitzeiger); Auch dazu ein kleines Beispiel in einem Listing: > /* time4.c */ #include <stdio.h> #include <time.h> #include <string.h> #include <stdlib.h> int main(int argc, char **argv) { FILE *datei; time_t time1; struct tm *time2; char zeit[25]; int c; if(argc<2) { printf("Bitte eingeben : %s textdatei.txt\n",*argv); return EXIT_FAILURE; } if((datei = fopen(*++argv,"w+")) == NULL) { printf("Konnte Datei : %s nicht öffnen!!!!\n",*argv); return EXIT_FAILURE; } printf("Eingabe machen (mit '#' beenden)\n>"); /* Wir schreiben in unsere Datei und beenden diese * mit dem Zeichen '#'. */ while((c=getchar()) != '#') putc(c, datei); putc('\n', datei); /* zuerst time_t-Format */ time(&time1); printf("Heute ist %s und Sie haben eben die " "Datei %s geschlossen\n",ctime(&time1), *argv); /* jetzt struct tm-Format mit asctime() */ time1=time(NULL); time2=localtime(&time1); strcpy(zeit,asctime(time2)); /* Das Datum schreiben wir in die Datei ... */ fprintf(datei,"%s\n",zeit); fclose(datei); return EXIT_SUCCESS; } Dieses Listing gibt zum einen das heutige Datum mit der Funktion ctime() auf dem Bildschirm aus und schreibt zum anderen den Rückgabewert der Funktion asctime() in eine Textdatei. # »difftime()« – Differenz zweier Zeiten Wird eine Differenz zwischen zwei Zeiten benötigt, lässt sich diese mit der folgenden Funktion ermitteln: > double difftime(time_t zeit1, time_t zeit0); Diese Funktion liefert die Differenz von zeit1 minus zeit0 als double-Wert zurück. Hierzu ein einfaches und kurzes Beispiel: > /* time5.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { time_t start, stop; double diff; printf("Einen Augenblick bitte ...\n"); start=time(NULL); while((diff=difftime(stop=time(NULL),start)) != 5); printf("%.1f sek. vorbei!!\n",diff); return EXIT_SUCCESS; } Das Programm wartet fünf Sekunden, bis es einen entsprechenden Text ausgibt. Bei > while((diff=difftime(stop=time(NULL),start)) !=5); wurde die Funktion time() gleich in der Funktion difftime() ausgeführt. Natürlich ist dies nicht so gut lesbar, aber es erfüllt denselben Zweck wie: > while((diff=difftime(stop,start)) != 5) stop=time(NULL); # »clock()« – Verbrauchte CPU-Zeit für ein Programm Eine weitere häufig gestellte Frage lautet: Wie kann ich herausfinden, wie lange das Programm schon läuft? Sie können dies mit folgender Funktion ermitteln: > clock_t clock(void); Diese Funktion liefert die verbrauchte CPU-Zeit seit dem Programmstart zurück. Falls die CPU-Zeit nicht verfügbar ist, gibt die Funktion –1 zurück. Wenn Sie die CPU-Zeit in Sekunden benötigen, muss der Rückgabewert dieser Funktion durch CLOCKS_PER_SEC dividiert werden; Beispiel: > /* runtime.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { clock_t prgstart, prgende; int c; prgstart=clock(); printf("Geben Sie etwas ein, und beenden Sie mit #\n"); printf("\n > "); while((c=getchar())!= '#') putchar(c); prgende=clock(); printf("Die Programmlaufzeit betrug %.2f Sekunden\n", (float)(prgende-prgstart) / CLOCKS_PER_SEC); return EXIT_SUCCESS; } Abbildung 19.2 Verbrauchte Zeit eines Programms mit »clock()« ermitteln Damit dürfte es Ihnen nicht schwerfallen, die Nutzungsdauer eines Programms herauszubekommen. # »strftime()« – »struct tm« in einen benutzerdefinierten String umwandeln Als Nächstes folgt eine Funktion, die Sie als die sprintf()-Funktion für Zeit- und Datumswerte ansehen können. Die Syntax lautet: > size_t strftime(char * restrict puffer, int maxzeichen, const char * restrict format, struct tm * restrict zeitzeiger); So kann die Kalenderzeit aus struct tm *zeitzeiger in einem entsprechenden Format in die Adresse puffer geschrieben werden. Folgende Umwandlungsvorgaben können Sie dabei verwenden: Format |  wird ersetzt durch  | Beispiel | | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Das folgende Listing zeigt, wie diese Angaben verwendet werden können: > /* time6.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { struct tm *zeit; time_t sekunde; char string[80]; time(&sekunde); zeit = localtime(&sekunde); strftime(string, 80, "Es ist %H Uhr und %M Minuten (%Z) %A, %B %Y",zeit); printf("%s\n",string); return EXIT_SUCCESS; } Es wird übrigens empfohlen, bei der formatierten Zeitausgabe des Jahres %Y statt %y zu verwenden, um Probleme mit dem Datum ab dem Jahr 2000 zu vermeiden. Abbildung 19.3 fasst alle Funktionen, die Sie hier kennengelernt haben, anhand ihrer Beziehungen zueinander zusammen. Abbildung 19.3 Datums- und Zeitfunktionen im Ãberblick In diesem Kapitel werden Funktionen aus den Standard-Headerdateien näher erläutert, die bisher noch nicht oder nur zu kurz zur Sprache gekommen sind. Alle Headerdateien sind vom ANSI-C-Komitee vorgeschrieben und somit auf allen Systemen vorhanden. ## 20.1 <assert.h> – Testmöglichkeiten und Fehlersuche Mit der Funktion > #include <assert.h> void assert(int ausdruck); können Ausdrücke aus einem Programm auf logische Fehler getestet werden. Ist ausdruck gleich 0, wird das Programm mit einer Fehlermeldung beendet. Genauer gesagt: Erst wird eine Fehlermeldung auf stderr ausgegeben, etwa: > Assertion failed: ausdruck, file filename, line nnn Der Dateiname und die Zeilennummern stammen von den Präprozessor-Makros __FILE__ und __LINE__. Danach wird die Ausführung des Prozesses mit der Funktion abort() beendet. Ein einfaches Beispiel: Es werden zwei Zahlen durch einander dividiert. Dabei darf keine der Zahlen eine Null oder ein negativer Wert sein. AuÃerdem soll der Teiler nicht gröÃer als der Nenner sein. Hier sehen Sie das Listing: > /* assertion1.c */ #include <stdio.h> #include <stdlib.h> #include <assert.h> int divide(int zahl1, int zahl2) { assert( (zahl1 >= 0 && zahl1 >= zahl2) && (zahl2 >= 0) ); return zahl1 / zahl2; } int main(void) { printf("%d / %d = %d\n",5,2,divide(5,2)); printf("%d / %d = %d\n",3,4,divide(3,4)); printf("%d / %d = %d\n",4,4,divide(4,4)); return EXIT_SUCCESS; } Das Programm wird durch den Funktionsaufruf divide(3,4) mit folgender Fehlermeldung abgebrochen: > Assertion failed: assert( (zahl1>=0 && zahl1>=zahl2) && (zahl2>=0) ), file:Pfad_zur_Datei.c, line 6 Diese Art, Programme zu testen, eignet sich sehr gut für gröÃere Projekte. Damit Sie nicht den ganzen Code durchsuchen müssen, um anschlieÃend bei der Fertigstellung des Programms die assert()-Anweisungen zu entfernen, müssen Sie nur das Makro > NDEBUG angeben, und der Compiler ignoriert alle assert()-Aufrufe. NDEBUG muss allerdings noch vor der Headerdatei > #include <assert.hangegeben werden. Bei dem folgenden Beispiel wird die assert()-Anweisung ignoriert: > /* assertion2.c */ #include <stdio.h> #include <stdlib.h> #define NDEBUG #include <assert.h> int divide(int zahl1, int zahl2) { assert( (zahl1 >= 0 && zahl1 >= zahl2) && (zahl2 >= 0) ); return zahl1 / zahl2; } int main(void) { printf("%d / %d = %d\n",5,2,divide(5,2)); printf("%d / %d = %d\n",3,4,divide(3,4)); printf("%d / %d = %d\n",4,4,divide(4,4)); return EXIT_SUCCESS; } In diesem Kapitel werden die Themen Strukturen, Zeiger und dynamische Speicherverwaltung vermischt. Was auf den ersten Blick ein wenig kompliziert aussieht – und es auch manches Mal ist –, erweist sich, sobald Sie es beherrschen, als eine enorme Erleichterung. ## 21.1 Lineare Listen (einfach verkettete Listen) In Kapitel 14, »Dynamische Speicherverwaltung«, habe ich den Umgang mit dynamisch zugeordnetem Speicher näher erläutert. »Dynamisch« heiÃt, dass zur Laufzeit des Programms Speicher vom Heap alloziert wird. Der Hauptsinn von dynamischen Datenstrukturen besteht darin, dass eine Struktur mit einem Zeiger vom Typ der Struktur selbst definiert wird. Gehen wir einmal von folgender Struktur einer Angestelltenliste aus: > struct datum { int tag; int monat; int jahr; }; struct angestellt{ char name[20]; char vorname[20]; struct datum alter; struct datum eingest; long gehalt; }; Eine solche Struktur wurde ja bereits behandelt und stellt somit nichts Neues mehr dar. Jetzt soll diese Struktur erweitert werden: ``` struct datum { int tag; int monat; int jahr; }; struct angestellt { char name[20]; char vorname[20]; struct datum alter; struct datum eingest; long gehalt; struct angestellt *next; }; ``` Folgende Zeile dürfte Ihnen am Ende der Struktur angestellt aufgefallen sein: > struct angestellt *next; Das Besondere an diesem Zeiger ist, dass er ein Zeiger auf eine Adresse ist, die denselben Typ wie die Struktur selbst (struct angestellt) beinhaltet. Mit diesem Zeiger können somit einzelne Strukturen miteinander verkettet werden. Der next-Zeiger verweist immer auf die Adresse des nächsten Elements, das wiederum eine Struktur mit denselben Elementen und ebenfalls wieder einen weiteren Zeiger beinhaltet. Sie können dabei eine gewisse Ãhnlichkeit mit den Arrays von Strukturen erkennen – wobei hier das nächste Element mithilfe eines Zeigers statt mit dem Indizierungsoperator angesprochen wird und Sie zuvor noch für das nächste Element einen Speicherplatz reservieren müssen. AuÃerdem wird noch ein Ende für die Kette benötigt. Dazu verwenden Sie einfach den next-Zeiger und übergeben diesem einen NULL-Zeiger: > struct angestellt *next = NULL; Somit würde die Struktur angestellt aussehen wie in Abbildung 21.1 dargestellt. Abbildung 21.1 Eine Struktur für eine einfach verkettete Liste Nochmals: Der Zeiger struct angestellt *next zeigt nicht auf sich selbst, sondern auf eine Adresse des nächsten Elements vom selben Typ. (Zur Erinnerung: Zeiger dereferenzieren eine Adresse und keinen Wert.) In diesem Beispiel wird zunächst auf NULL verwiesen, da noch keine Daten eingegeben wurden. In Kapitel 15, »Strukturen«, habe ich bereits gezeigt, wie Sie auf die einzelnen Elemente einer Struktur zugreifen können, zum Beispiel: > struct angestellt a; AnschlieÃend wird mit a.name, a.vorname oder a.alter usw. auf die einzelnen Strukturelemente zugegriffen. Ãhnlich funktioniert dies, wenn nicht mit einer Strukturvariablen, sondern mit Zeigern auf eine Struktur gearbeitet wird: > struct angestellt *structzeiger; Der Zugriff auf die einzelnen Elemente der Struktur sieht dann so aus: > (*structzeiger).name (*structzeiger).vorname (*structzeiger).alter Diese Schreibweise ist allerdings nicht allzu lesefreundlich und birgt die Gefahr, Fehler zu machen. Zum Glück haben die Compiler-Bauer einen extra Operator geschaffen, der eine Kombination aus Dereferenzierung und Elementzugriff ist: > -Da der ->-Operator die Form eines Zeigers hat, ist dieser auch noch einfacher zu lesen. Somit ergibt sich folgende Schreibweise für den Zugriff auf die einzelnen Strukturelemente: > structzeiger->name structzeiger->vorname structzeiger->alter Theoretisch könnten Sie jetzt einen Datensatz nach dem anderen anhängen. Aber irgendwann wollen Sie den Datensatz auch wieder ausgeben oder sortieren. Deshalb benötigt die Kette einen Anfang, d. h. eine Anfangsadresse, mit der die Liste beginnt. Also ist ein weiterer Zeiger der Struktur angestellt erforderlich, in dem sich die Anfangsadresse befindet: > struct angestellt *anfang; Da zu Beginn des Programms noch kein Datensatz eingegeben wurde, verweist dieser Zeiger zunächst auch auf NULL. Bisher sieht die Struktur demnach so aus: > struct datum { int tag; int monat; int jahr; }; struct angestellt { char name[20]; char vorname[20]; struct datum alter; struct datum eingest; long gehalt; struct angestellt *next; }; struct angestellt *next = NULL; struct angestellt *anfang = NULL; Jetzt folgt eine Funktion, mit der Sie Adresssätze aneinanderhängen können. Die Funktion anhaengen() ist sehr ausführlich kommentiert: > /* linear_list1.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 20 struct datum { int tag; int monat; int jahr; }; struct angestellt { char name[MAX]; char vorname[MAX]; struct datum alter; struct datum eingest; long gehalt; struct angestellt *next; }; struct angestellt *next = NULL; struct angestellt *anfang=NULL; /* Wir hängen einen Datensatz an oder geben einen neuen ein: * n=name,v=vornam,at=alter.tage,am=alter.monat,aj=alter.jahr * eint=eigestellt tag,einm=eingestellt monat,einj=eingest. * Jahr g=gehalt */ void anhaengen(char *n, char *v, int at, int am, int aj, int eint, int einm, int einj, long g) { /* Zeiger zum Zugriff auf die einzelnen Elemente * der Struktur*/ struct angestellt *zeiger; /* Wir fragen ab, ob es schon ein Element in der Liste * gibt. Wir suchen das Element, auf das unser Zeiger * *anfang zeigt. Falls *anfang immer noch auf NULL zeigt, * bekommt *anfang die Adresse unseres 1. Elements und ist * somit der Kopf (Anfang) unserer Liste. */ if(anfang == NULL) { /* Wir reservieren Speicherplatz für unsere Struktur * für das erste Element der Liste. */ if((anfang = malloc(sizeof(struct angestellt))) == NULL) { fprintf(stderr, "Kein Speicherplatz vorhanden " "fuer anfang\n"); return; } strcpy(anfang->name, n); strcpy(anfang->vorname, v); anfang->alter.tag = at; anfang->alter.monat = am; anfang->alter.jahr = aj; anfang->eingest.tag = eint; anfang->eingest.monat = einm; anfang->eingest.jahr = einj; anfang->gehalt = g; /* Somit haben wir unseren Anfang der Liste. Von nun an * zeigt der Zeiger anfang immer auf das Element vor ihm. * Da dies aber jetzt das 1. Element der Liste war, zeigt * der Zeiger anfang auf den Zeiger next. next zeigt am * Ende immer wieder NULL. */ anfang->next=NULL; } /* Es scheint schon mindestens ein Element in der Liste * vorhanden zu sein, da der Anfang nicht == NULL ist. * Jetzt suchen wir so lange nach dem nächsten Element, * bis der *next-Zeiger auf NULL zeigt. Somit haben wir * das Ende der Liste gefunden und können einen neuen * Datensatz anhängen. */ else { zeiger=anfang; /* Wir zeigen auf das 1. Element. */ while(zeiger->next != NULL) zeiger=zeiger->next; /* Wir reservieren einen Speicherplatz für das letzte * Element der Liste und hängen es an. */ if((zeiger->next = malloc(sizeof(struct angestellt))) == NULL) { fprintf(stderr,"Kein Speicherplatz fuer das " "letzte Element\n"); return; } zeiger=zeiger->next; /* zeiger auf neuen Speicherplatz */ strcpy(zeiger->name,n); strcpy(zeiger->vorname,v); zeiger->alter.tag=at; zeiger->alter.monat=am; zeiger->alter.jahr=aj; zeiger->eingest.tag=eint; zeiger->eingest.monat=einm; zeiger->eingest.jahr=einj; /* Wir terminieren wieder unsere Datenstruktur. */ zeiger->gehalt=g; zeiger->next=NULL; } } /* Funktion zur Eingabe der Daten */ void eingabe(void) { char nam[MAX],vorn[MAX]; int atag,amon,ajahr,eintag,einmon,einjahr; long gehalt; printf("Name........................: "); fgets(nam, MAX, stdin); printf("Vorname.....................: "); fgets(vorn, MAX, stdin); printf("Alter...........(tt.mm.jjjj): "); scanf("%2d.%2d.%4d",&atag,&amon,&ajahr); printf("Eingestellt am..(tt.mm.jjjj): "); scanf("%2d.%2d.%4d",&eintag,&einmon,&einjahr); printf("Monatsgehalt................: "); scanf("%ld",&gehalt); getchar(); /* eingegebenen Datensatz hinten anhängen */ anhaengen(nam, vorn, atag, amon, ajahr, eintag, einmon, einjahr, gehalt); } int main(void) { while(1) eingabe(); return EXIT_SUCCESS; } Zuerst wird die Funktion eingabe() zur Eingabe der einzelnen Daten aufgerufen. Diese eingegebenen Variablen werden anschlieÃend als Argument an die Parameter der Funktion anhaengen() übergeben. Bei der Funktion ist die Zeile > zeiger=zeiger->next; sehr wichtig. Es wird davon ausgegangen, dass bereits ein Element eingegeben wurde und das nächste somit das zweite Element in der Liste ist. Wenn jetzt zeiger nicht auf die Adresse von zeiger->next verweisen würde, wäre dies zwar kein syntaktischer Fehler, aber es würde immer wieder die erste Struktur überschrieben werden. Mit der folgenden Zeile wird es überhaupt erst möglich, dass die while-Schleife funktioniert, um wieder neue Daten einzugeben: > zeiger->next=NULL; Sonst würde die while-Schleife mit der Abfrage, ob zeiger auf next zeigt, niemals korrekt abbrechen, da niemals auf NULL verwiesen würde: > while(zeiger->next != NULL) zeiger=zeiger->next; Dies soll jetzt bildlich dargestellt werden. Es wurden bereits zwei Personen eingegeben. Somit sind folglich zwei Datensätze vorhanden (siehe Abbildung 21.2). Abbildung 21.2 Eine verkettete Liste mit zwei Datensätzen Hier erkennen Sie auch, dass der Strukturzeiger anfang immer auf das erste Element der Liste zeigt. Der Strukturzeiger next im letzten Element zeigt immer auf NULL und zeigt somit immer das Ende der Kette an. Als Nächstes soll eine Funktion erstellt werden, mit der Sie einzelne Elemente in der Liste löschen können. Der Speicherplatz wird dabei wie üblich mit der Funktion free() freigegeben. ### 21.1.1 Erstes Element der Liste löschen Falls das erste Element in der Liste gelöscht werden soll, ist dies nicht allzu schwierig. Dabei muss nur ein Zeiger vom Typ struct angestellt auf die Adresse von anfang->next zeigen (zweites Element). AnschlieÃend kann mit free(anfang) der Speicher freigegeben werden. Zum Schluss bekommt der Zeiger anfang die Adresse des Zeigers anfang->next. So werden Sie in der Praxis das erste Element in der Liste los: > /* Funktion zum Löschen */ void loesche(char *wen) { struct angestellt *zeiger; /* Ist überhaupt ein Element vorhanden? */ if(anfang != NULL) { /* Ist unser 1. Element das von uns gesuchte (wen[])? */ if(strcmp(anfang->name,wen) == 0) { zeiger=anfang->next; Es sei jetzt der Fall gegeben, dass das erste Element in der Liste das momentan gesuchte ist, das gelöscht werden soll. Somit ergibt sich im Augenblick folgender Zustand: Abbildung 21.3 Ein Zeiger auf das nächste Element vom Anfang Jetzt folgt der Aufruf: > free(anfang); Damit wird der Speicherplatz freigegeben, auf den der Zeiger anfang verweist: Abbildung 21.4 Speicherplatz des ersten Elements wird freigegeben. Wenn Sie es jetzt hierbei belassen, sind die restlichen Daten der Kette wohl verloren, da es keinen Anfang mehr gibt. Es muss noch die Adresse des Zeigers zeiger an den Zeiger anfang übergeben werden: > anfang=zeiger; Damit ergibt sich das folgende finale Bild: Abbildung 21.5 Der Zeiger des ersten Elements bekommt eine neue Adresse. ### 21.1.2 Ein beliebiges Element in der Liste löschen Das erste Element in der Liste zu löschen war nicht schwer. Anders sieht es aus, wenn ein Element irgendwo in der Liste entfernt werden muss. Dafür wird ein Zeiger mehr benötigt: einer, der auf die Adresse verweist, die sich vor dem zu löschenden Element befindet, und ein weiterer Zeiger, der auf das nächste Element nach dem zu löschenden Element zeigt. Hier folgt eine kurze Zusammenfassung der bisherigen Funktion loesche(): > /* Funktion zum Löschen */ void loesche(char *wen) { struct angestellt *zeiger, *zeiger1; /* Ist überhaupt ein Element vorhanden? */ if(anfang != NULL) { /* Ist unser 1. Element das von uns gesuchte (wen[])? */ if(strcmp(anfang->name,wen) == 0) { zeiger=anfang->next; free(anfang); anfang=zeiger; } else { /* Es ist nicht das 1. Element zu löschen. Wir suchen in * der weiteren Kette, ob das zu löschende Element vor- * handen ist. */ zeiger=anfang; Daraus ergibt sich momentan folgende »Grundstellung«: Abbildung 21.6 Auf der Suche nach dem zu löschenden Element Es wird der Einfachheit halber davon ausgegangen, dass das gesuchte Element das zweite in der Liste sei (siehe Abbildung 21.6). Das Stückchen Quellcode, das nach einem bestimmten Namen in der Liste sucht, sieht folgendermaÃen aus: > while(zeiger->next != NULL) { zeiger1=zeiger->next; /* Ist die Adresse von zeiger1 der gesuchte Name? */ if(strcmp(zeiger1->name,wen) == 0) { /* Falls ja, dann ... */ Bildlich ergibt sich daraus folgender Stand: Abbildung 21.7 Element zum Löschen gefunden Die Adresse, auf die zeiger1 zeigt, ist das gesuchte Element in der Liste, das gelöscht werden soll. Bevor Sie jetzt den Speicherplatz freigeben können, benötigt das Element in der Liste, auf das zeiger verweist, eine Adresse für den next-Zeiger, damit die Kette nicht abreiÃt: > zeiger->next=zeiger1->next; free(zeiger1); break; } zeiger=zeiger1; } /* Ende while */ } /* Ende else */ } /* Ende if(anfang != NULL) */ else printf("Es sind keine Daten zum Löschen vorhanden!!!\n"); } Sehen wir uns dies etwas genauer an: > zeiger->next=zeiger1->next; In Worten: Der Zeiger zeiger, der auf die Adresse der nächsten (next) Datenstruktur zeigt (zum jetzigen Zeitpunkt zeigt zeiger->next ja noch auf das zu löschende Element, auf das der Zeiger zeiger1 zeigt), bekommt jetzt die Adresse, auf die der next-Zeiger des zu löschenden Elements (zeiger1) verweist. Anhand einer Grafik ist das einfacher zu verstehen: Abbildung 21.8 Das zu löschende Element wird ausgehängt. So wird das zu löschende Element ausgehängt. Jetzt kann der Speicherplatz freigegeben werden: > free(zeiger1); Somit ergibt sich folgendes Bild: Abbildung 21.9 Der Speicherplatz des zu löschenden Elements wurde freigegeben. ### 21.1.3 Elemente der Liste ausgeben Die Funktion zur Ausgabe der einzelnen Elemente in der Liste lässt sich recht einfach erstellen. Zuerst übergeben Sie einem Zeiger die Anfangsadresse der Liste und durchlaufen mit > while(zeiger != NULL) die Liste so lange, bis der Zeiger zeiger auf NULL verweist – was das Ende der Liste darstellt. Hier sehen Sie die komplette Funktion zur Ausgabe der verketteten Liste: > void ausgabe(void) { struct angestellt *zeiger = anfang; printf("||=====================================" "==================||\n"); printf("|%10cName%10c |Geburtsdatum|" "Eingestellt|Gehalt|\n",' ',' '); printf("||=====================================" "==================||\n"); while(zeiger != NULL) { printf("|%12s,%-12s| %02d.%02d.%04d|" "%02d.%02d.%04d|%06ld|\n", zeiger->name,zeiger->vorname,zeiger->alter.tag, zeiger->alter.monat,zeiger->alter.jahr, zeiger->eingest.tag,zeiger->eingest.monat, zeiger->eingest.jahr,zeiger->gehalt); printf("|-----------------------------------" "----------------------|\n"); zeiger=zeiger->next; } } Und jetzt sehen Sie das gesamte Programm inklusive der main()-Funktion: > /* linear_list2.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 20 struct datum{ int tag; int monat; int jahr; }; struct angestellt{ char name[MAX]; char vorname[MAX]; struct datum alter; struct datum eingest; long gehalt; struct angestellt *next; }; struct angestellt *next = NULL; struct angestellt *anfang = NULL; /* Wir hängen einen Datensatz an oder geben einen neuen ein: * n=name,v=vornam,at=alter.tage,am=alter.monat,aj=alter.jahr * eint=eigestellt tag,einm=eingestellt monat, * einj=eingest. Jahr g=gehalt */ void anhaengen(char *n, char *v, int at, int am, int aj, int eint, int einm, int einj, long g) { /* Zeiger zum Zugriff auf die einzelnen Elemente * der Struktur */ struct angestellt *zeiger; /* Wir fragen ab, ob es schon ein Element in der Liste * gibt. Wir suchen das Element, auf das unser Zeiger * *anfang zeigt. Falls *anfang immer noch auf NULL zeigt, * bekommt *anfang die Adresse unseres 1. Elements und ist * somit der Kopf (Anfang) unserer Liste. */ if(anfang == NULL) { /* Wir reservieren Speicherplatz für unsere Struktur * für das erste Element der Liste. */ if((anfang = malloc(sizeof(struct angestellt))) == NULL) { fprintf(stderr, "Kein Speicherplatz vorhanden " "für anfang\n"); return; } strcpy(anfang->name, n); strcpy(anfang->vorname, v); anfang->alter.tag = at; anfang->alter.monat = am; anfang->alter.jahr = aj; anfang->eingest.tag = eint; anfang->eingest.monat = einm; anfang->eingest.jahr = einj; anfang->gehalt = g; /* Somit haben wir unseren Anfang der Liste. Von nun an * zeigt der Zeiger anfang immer auf das Element vor ihm. * Da dies aber jetzt das 1. Element der Liste war, zeigt * der Zeiger anfang auf den Zeiger next. next zeigt am * Ende immer wieder auf NULL. */ anfang->next=NULL; } /* Es scheint schon mindestens ein Element in der Liste * vorhanden zu sein, da der Anfang nicht == NULL ist. * Jetzt suchen wir so lange nach dem nächsten Element, * bis der *next-Zeiger auf NULL zeigt. Somit haben wir * das Ende der Liste gefunden und können einen neuen * Datensatz anhängen. */ else { zeiger=anfang; /* Wir zeigen auf das 1. Element. */ while(zeiger->next != NULL) zeiger=zeiger->next; /* Wir reservieren einen Speicherplatz für das letzte * Element der Liste und hängen es an. */ if((zeiger->next = malloc(sizeof(struct angestellt))) == NULL) { fprintf(stderr,"Kein Speicherplatz für das " "letzte Element\n"); return; } zeiger=zeiger->next; /* zeiger auf neuen Speicherplatz */ strcpy(zeiger->name,n); strcpy(zeiger->vorname,v); zeiger->alter.tag=at; zeiger->alter.monat=am; zeiger->alter.jahr=aj; zeiger->eingest.tag=eint; zeiger->eingest.monat=einm; zeiger->eingest.jahr=einj; /* Wir terminieren wieder unsere Datenstruktur. */ zeiger->gehalt=g; zeiger->next=NULL; } } /* Funktion zum Löschen einer Datei */ void loesche(char *wen) { struct angestellt *zeiger, *zeiger1; /* Ist überhaupt ein Element vorhanden? */ if(anfang != NULL) { /* Ist unser 1. Element das von uns gesuchte (wen[])? */ if(strcmp(anfang->name,wen) == 0) { zeiger=anfang->next; free(anfang); anfang=zeiger; } else { /* Es ist nicht das 1. Element zu löschen. * Wir suchen in der weiteren Kette, ob das zu * löschende Element vorhanden ist. */ zeiger=anfang; while(zeiger->next != NULL) { zeiger1=zeiger->next; /* Ist die Adresse von zeiger1 * der gesuchte Name? */ if(strcmp(zeiger1->name,wen) == 0) { /* Falls ja, dann ... */ zeiger->next=zeiger1->next; free(zeiger1); break; } zeiger=zeiger1; } /* Ende while */ } /* Ende else */ } /* Ende if(anfang != NULL) */ else printf("Es sind keine Daten zum Loeschen vorhanden!!!\n"); } /* Funktion zum Ausgeben der Dateien */ void ausgabe(void) { struct angestellt *zeiger = anfang; printf("||=====================================" "==================||\n"); printf("|%10cName%10c |Geburtsdatum|" "Eingestellt|Gehalt|\n",' ',' '); printf("||=====================================" "==================||\n"); while(zeiger != NULL) { printf("|%12s,%-12s| %02d.%02d.%04d|" "%02d.%02d.%04d|%06ld|\n", zeiger->name,zeiger->vorname,zeiger->alter.tag, zeiger->alter.monat,zeiger->alter.jahr, zeiger->eingest.tag,zeiger->eingest.monat, zeiger->eingest.jahr,zeiger->gehalt); printf("|-----------------------------------" "----------------------|\n"); zeiger=zeiger->next; } } /* Funktion zur Eingabe der Daten */ void eingabe(void) { char nam[MAX],vorn[MAX]; int atag,amon,ajahr,eintag,einmon,einjahr; long gehalt; char *ptr; printf("Name........................: "); fgets(nam, MAX, stdin); ptr = strrchr(nam, '\n'); *ptr = '\0'; printf("Vorname.....................: "); fgets(vorn, MAX, stdin); ptr = strrchr(vorn, '\n'); *ptr = '\0'; printf("Alter...........(tt.mm.jjjj): "); scanf("%2d.%2d.%4d",&atag,&amon,&ajahr); printf("Eingestellt am..(tt.mm.jjjj): "); scanf("%2d.%2d.%4d",&eintag,&einmon,&einjahr); printf("Monatsgehalt................: "); scanf("%ld",&gehalt); getchar(); anhaengen(nam, vorn, atag, amon, ajahr, eintag, einmon, einjahr, gehalt); } int main(void) { int wahl; char dname[MAX]; do { printf("\n1 : Eingabe\n"); printf("2 : Ausgabe\n"); printf("3 : Namen loeschen\n"); printf("9 : Ende\n"); printf("Ihre Wahl : "); scanf("%d",&wahl); getchar(); switch(wahl) { case 1 : eingabe(); break; case 2 : ausgabe(); break; case 3 : printf("Der Name zum Loeschen: "); fgets(dname, MAX, stdin); loesche(strtok(dname, "\n")); break; case 9 : break; default: printf("Falsche Eingabe!!!\n"); } } while(wahl != 9); return EXIT_SUCCESS; } Dem Programm fehlen noch einige Optionen, und die Optik lässt auch sehr zu wünschen übrig. Auf den nächsten Seiten wird dieses Programm noch erheblich ausgebaut. ### 21.1.4 Eine vollständige Liste auf einmal löschen Auch die Funktion, mit der alle Elemente einer Liste auf einmal gelöscht werden können, ist nicht schwierig zu implementieren. Hier der Quellcode: > void loesche_alles(void) { struct angestellt *zeiger, *zeiger1; /* Ist überhaupt eine Liste zum Löschen vorhanden? */ if(anfang != NULL) { /* Es ist eine vorhanden. */ zeiger=anfang->next; while(zeiger != NULL) { zeiger1=anfang->next->next; anfang->next=zeiger1; free(zeiger); zeiger=zeiger1; } /* Jetzt löschen wir erst den Anfang der Liste. */ free(anfang->next); free(anfang); anfang=NULL; printf("Liste erfolgreich geloescht!!\n"); } else fprintf(stderr,"Keine Liste zum Loeschen vorhanden!!\n"); } Zuerst wird überprüft, ob überhaupt eine Liste zum Löschen vorhanden ist. AnschlieÃend bekommt der Zeiger zeiger die Adresse des zweiten Elements (siehe Abbildung 21.10). Abbildung 21.10 Zeiger auf das nächste Element vom Anfang Jetzt wird mit > anfang->next=zeiger1; dem next-Zeiger des ersten Elements die Adresse übergeben, auf die zeiger1 verweist (siehe Abbildung 21.11). Hiermit wurde das Element mit der Adresse, auf die der Zeiger zeiger zeigt, ausgehängt. Jetzt kann der Speicher freigegeben werden: > free(zeiger); Mit free(zeiger) geben Sie den Speicher für das Element in der Liste endgültig frei. Jetzt bekommt noch der Zeiger zeiger die Adresse von zeiger1, damit die Liste weiterhin ordentlich verkettet bleibt. Somit sieht es nun folgendermaÃen aus (siehe Abbildung 21.12). Abbildung 21.12 Speicherplatz wurde freigegeben. Es geht wieder von Neuem in der while-Schleife los, wie im Folgenden bildlich ohne weitere Kommentare dargestellt ist (siehe Abbildung 21.13). Abbildung 21.13 Den Zeiger wieder auf das nächste Element vom Anfang setzen, dann aushängen und Speicherplatz freigeben Die Abbruchbedingung für die while-Schleife wäre nun erreicht. Der Zeiger zeiger verweist jetzt auf NULL. Am Ende muss nur noch der Anfang gelöscht werden: > free(anfang->next); free(anfang); anfang=NULL; Zur Sicherheit wird dem Zeiger auf das erste Element noch der NULL-Zeiger übergeben, da selbst dann, wenn der Speicher freigegeben ist, der Zeiger anfang immer noch auf die ursprüngliche Speicherstelle zeigt. Dabei kann es leicht zu Programmierfehlern kommen. ### 21.1.5 Element in die Liste einfügen Nun folgt eine Funktion zum sortierten Einfügen eines neuen Elements in die Liste. Die Elemente (Nachnamen) sollen alphabetisch eingefügt werden. Dazu gibt es folgende vier Möglichkeiten, die beim Einfügen eines neuen Elements auftreten können: 1. | Es ist noch kein Element in der Liste vorhanden, und das eingegebene ist das erste Element. | | --- | --- | 2. | Das eingegebene Element ist das gröÃte und wird somit hinten angehängt. | | --- | --- | 3. | Das eingegebene Element ist das kleinste und wird ganz an den Anfang eingefügt. | | --- | --- | 4. | Die letzte Möglichkeit ist gleichzeitig auch die schwierigste. Das Element muss irgendwo in der Mitte eingefügt werden. | | --- | --- | Die folgende Funktion überprüft, welche der Möglichkeiten zutrifft, und führt dann entsprechende Arbeiten aus. Zuerst der Funktionskopf: > void sortiert_eingeben(char *n, char *v, int at, int am, int aj, int et, int em, int ej, long geh) { struct angestellt *zeiger, *zeiger1; Jetzt muss überprüft werden, ob überhaupt ein Element in der Liste vorhanden ist: > if(anfang == NULL) anhaengen(n,v,at,am,aj,et,em,ej,geh); Falls noch kein Element in der Liste vorhanden ist, wird die Funktion anhaengen() mit entsprechenden Argumenten aufgerufen. Es befindet sich bereits mindestens ein Element in der Liste. Somit beginnt die Suche danach mit: > zeiger=anfang; while(zeiger != NULL && (strcmp(zeiger->name,n) < 0)) zeiger=zeiger->next; Die einzelnen Elemente in der Liste werden so lange durchlaufen, bis entweder das Ende erreicht ist (zeiger == NULL) oder bis das neue Element gröÃer oder gleich dem Namen ist, auf den der zeiger verweist. Auf jeden Fall wird die Schleife unterbrochen. Jetzt muss überprüft werden, warum die Schleife abgebrochen wurde. Zuerst wird nachgesehen, ob keine Ãbereinstimmung stattgefunden hat, und das neue Element somit ganz hinten angehängt wird: > if(zeiger == NULL) anhaengen(n,v,at,am,aj,et,em,ej,geh); In diesem Fall ist das neue Element das gröÃte und wird mit der Funktion anhaengen() am Ende angefügt. Die nächste Möglichkeit: Das neue Element ist das kleinste und muss ganz an den Anfang der Liste platziert werden: > else if(zeiger == anfang) { anfang=malloc(sizeof(struct angestellt)); strcpy(anfang->name,n); strcpy(anfang->vorname,v); anfang->alter.tag=at; anfang->alter.monat=am; anfang->alter.jahr=aj; anfang->eingest.tag=et; anfang->eingest.monat=em; anfang->eingest.jahr=ej; anfang->gehalt=geh; anfang->next=zeiger; } Dies sieht bildlich folgendermaÃen aus: > else if(zeiger == anfang) Abbildung 21.14 Ein neues Element wird am Anfang eingefügt. > anfang=malloc(sizeof(struct angestellt)); Abbildung 21.15 Für das neue Element wird Speicherplatz reserviert. > anfang->next=zeiger; Abbildung 21.16 Das neue Element wird am Anfang eingefügt. Jetzt fehlt noch die schwierigste Möglichkeit: Das Element muss irgendwo in der Mitte eingefügt werden: > else { zeiger1=anfang; /* Wir suchen das Element, das vor dem Zeiger * zeiger steht. */ while(zeiger1->next != zeiger) zeiger1=zeiger1->next; zeiger=malloc(sizeof(struct angestellt)); strcpy(zeiger->name,n); strcpy(zeiger->vorname,v); zeiger->alter.tag=at; zeiger->alter.monat=am; zeiger->alter.jahr=aj; zeiger->eingest.tag=et; zeiger->eingest.monat=em; zeiger->eingest.jahr=ej; zeiger->gehalt=geh; /* Wir fügen das neue Element ein. */ zeiger->next=zeiger1->next; zeiger1->next=zeiger; } Als Beispiel wird ein neues Element zwischen dem zweiten und dem dritten Element eingefügt. Bildlich ergibt sich dadurch folgender Stand (siehe Abbildung 21.17). Abbildung 21.17 Ein Zeiger befindet sich eine Position hinter dem neuen Element, das eingefügt werden soll. Der Zeiger zeiger verweist somit auf das dritte Element. Jetzt wird mit > while(zeiger1->next != zeiger) zeiger1=zeiger1->next; die Adresse des Elements ermittelt, das vor dem Zeiger zeiger steht: Abbildung 21.18 Ein Zeiger befindet sich jetzt vor dem einzufügenden Element. Für das neue Element wird jetzt zunächst Speicherplatz benötigt: > zeiger=malloc(sizeof(struct angestellt)); Abbildung 21.19 Speicherplatz für das neu einzufügende Element reservieren Nun muss das neue Element in die Liste eingehängt werden. Dies geschieht in zwei Schritten: Der next-Zeiger des neuen Elements bekommt die Adresse, auf die auch der next-Zeiger von zeiger1 verweist: > zeiger->next=zeiger1->next; Es ergibt sich folgendes Bild: Abbildung 21.20 So lassen Sie den »next«-Zeiger des neuen Elements auf die Adresse des »next«-Zeigers seines Vorgängers verweisen. Jetzt muss noch der next-Zeiger von zeiger1 auf die Adresse des neuen Elements zeigen: > zeiger1->next=zeiger Abbildung 21.21 So lassen Sie den »next«-Zeiger des Vorgängers auf das neue Element verweisen. Hier sehen Sie die vollständige Funktion sortiert_eingeben(): > void sortiert_eingeben(char *n, char *v, int at, int am, int aj, int et, int em, int ej, long geh) { struct angestellt *zeiger, *zeiger1; /* Ist es das 1. Element der Liste? */ if(anfang==NULL) anhaengen(n,v,at,am,aj,et,em,ej,geh); /* Es ist nicht das 1. Element. Wir suchen so lange, bis das * gesuchte Element gefunden wird oder wir auf NULL stoÃen */ else { zeiger=anfang; while(zeiger != NULL && (strcmp(zeiger->name,n) < 0)) zeiger=zeiger->next; /* Falls der Zeiger auf NULL zeigt, können wir unser * Element hinten anhängen, da unser neues Element das * "gröÃte" zu sein scheint. */ if(zeiger==NULL) anhaengen(n,v,at,am,aj,et,em,ej,geh); /* Ist unser neues Element das kleinste und somit * kleiner als das 1. Element, so müssen wir es an * den Anfang setzen. */ else if(zeiger==anfang) { anfang=malloc(sizeof(struct angestellt)); if(NULL == anfang) { fprintf(stderr, "Kein Speicher\n"); return; } strcpy(anfang->name,strtok(n, "\n")); strcpy(anfang->vorname,strtok(v, "\n")); anfang->alter.tag=at; anfang->alter.monat=am; anfang->alter.jahr=aj; anfang->eingest.tag=et; anfang->eingest.monat=em; anfang->eingest.jahr=ej; anfang->gehalt=geh; anfang->next=zeiger; } /* Die letzte Möglichkeit ist, dass wir das Element * irgendwo in der Mitte einfügen müssen. */ else { zeiger1=anfang; /* Wir suchen das Element, das vor dem * Zeiger zeiger steht. */ while(zeiger1->next != zeiger) zeiger1=zeiger1->next; zeiger=malloc(sizeof(struct angestellt)); if(NULL == zeiger) { fprintf(stderr, "Kein Speicher"); return; } strcpy(zeiger->name,strtok(n, "\n")); strcpy(zeiger->vorname,strtok(v, "\n")); zeiger->alter.tag=at; zeiger->alter.monat=am; zeiger->alter.jahr=aj; zeiger->eingest.tag=et; zeiger->eingest.monat=em; zeiger->eingest.jahr=ej; zeiger->gehalt=geh; /* Wir fügen das neue Element ein. */ zeiger->next=zeiger1->next; zeiger1->next=zeiger; } //Ende else } //Ende else } Das Programm wird in den nächsten Abschnitten noch verwendet und erweitert. Den kompletten Quellcode des Programms bis hierher (linear_list3.c) können Sie von https://www.rheinwerk-verlag.de/2132 herunterladen oder – noch besser – Sie versuchen diese Funktion selbst einzubauen. Das Ziel dieses Kapitels ist es nicht, Ihnen eine ganze Palette von Algorithmen vorzustellen, sondern nur einige grundlegende der Informatik. Um es mit diesem Thema aufzunehmen, brauchen Sie schon einige Erfahrung in der Programmierung mit C. Sie sollten alle Grundlagen von C bereits kennen. Vor allem sollten Sie wissen, was Arrays und verkettete Listen sind und wie Sie diese in der Praxis verwenden können. Sofern Sie also einige dieser Themen noch nicht ganz verstehen oder übersprungen haben, empfehle ich Ihnen, sich diesen nochmals zu widmen, bevor Sie mit diesem Kapitel beginnen. AuÃerdem ist ein wenig Eigenmotivation gefordert, die Themen zu verstehen – und vor allem Praxis. Wenn Sie dieses Kapitel durchgelesen und die Algorithmen (hoffentlich) eingesetzt haben, dann besitzen Sie ein gutes Fundament, um sich tiefergehend mit der Materie zu befassen. ## 22.1 Was sind Algorithmen? Ein Algorithmus hat keinerlei Bezug zum Betriebssystem und ist auch nicht von irgendeiner Bibliothek abhängig. Ein Algorithmus ist nichts anderes als ein Verfahren, das verwendet wird, um ein Problem unter bestimmten Voraussetzungen durch eine endliche Anzahl von Schritten zu lösen. Mit »Verfahren« meine ich hier natürlich Quellcode. Da es viele verschiedene Algorithmen gibt, ist es nicht immer einfach, den richtigen zur rechten Zeit zu verwenden. Dies ist abhängig vom Problemfall und von der Erfahrung des Programmierers mit einem bestimmten Algorithmus. Meistens ist es sinnvoll, verschiedene Algorithmen zu testen und eine Laufzeitanalyse (Profiling) zu erstellen – insbesondere dann, wenn Ihnen der Algorithmus unbekannt ist und Sie nicht wissen, welche Anforderungen dieser stellt. CGI (Common Gateway Interface) ist, einfach ausgedrückt, eine Schnittstelle, mit der Sie z. B. Anwendungen für das Internet schreiben können. ## 23.1 Was ist CGI? Im Laufe dieses Kapitels werden Sie diese Frage detaillierter beantwortet bekommen, aber ein kurzer Anriss des Themas wird schon hier gegeben. Ein CGI (Common Gateway Interface) ist eine Schnittstelle, mit der Sie z. B. Anwendungen für das Internet schreiben können. Diese CGI-Anwendungen laufen dabei auf einem (Web-)Server (wie beispielsweise dem Apache) und werden von einer HTML-Webseite meist mithilfe eines Webbrowsers aufgerufen. Die Daten erhält diese CGI-Anwendung entweder von der HTML-Seite selbst (POST-Verfahren) – beispielsweise über ein Eingabeformular – oder direkt über die URL (GET-Verfahren). Das Verfahren der CGI-Schnittstelle ist ziemlich einfach. Die Daten werden ganz normal von der Standardeingabe (stdin) oder von den Umgebungsvariablen empfangen und wenn nötig über die Standardausgabe (stdout) ausgegeben. Meistens handelt es sich dabei um ein dynamisch erzeugtes HTML-Dokument, das Sie in Ihrem Browser betrachten können. Sind diese Voraussetzungen gegeben, können CGI-Anwendungen praktisch mit jeder Programmiersprache erstellt werden. Das CGI-Programm selbst, das Sie erstellen, ist ein ausführbares Programm auf dem Webserver, das nicht von einem normalen User gestartet wird, sondern vom Webserver als ein neuer Prozess (siehe Abbildung 23.1). Die Kombination von MySQL und der C-API ist ein sehr reizvolles, aber leider auch selten behandeltes Thema. Dieses Kapitel sorgt für Abhilfe und bietet Ihnen eine Einführung in MySQL und die C-API. ## 24.1 Aufbau eines Datenbanksystems Dieser Abschnitt ist sehr wichtig, sofern Sie noch keinerlei Erfahrungen mit Datenbanksystemen gemacht haben. Hier werden die grundlegenden Prinzipien von Datenbanken erklärt. Als C-Programmierer werden Sie sich fragen, »Warum benötige ich eine Datenbank? Ich kann doch einfach ein Programm unter Verwendung von binären Bäumen entwickeln, womit die Nutzung einer Datenbank überflüssig wird.« Und Sie werden sich wundern – vereinfacht arbeitet MySQL auch so, nur mit einer anderen Beziehung: einer relationalen. Sicherlich, das könnten Sie auch programmieren, schlieÃlich wurde MySQL in der Programmiersprache C geschrieben. Wozu sollten Sie aber das Rad neu erfinden? AuÃerdem erweist es sich als recht schwieriges Unterfangen, ein eigenes relationales Datenbankprogramm zu schreiben. ### 24.1.1 Warum wurde ein Datenbanksystem (DBS) entwickelt? Vor der Zeit der Datenbanken wurden Daten mit selbst entwickelten Programmen in Dateien gespeichert. Diese Programme waren zumeist an die Bedürfnisse einer Firma bzw. eines Anwenders angepasst. Schlimmer noch, teilweise wurden die Programme für die einzelnen Abteilungen bis hin zum einzelnen Mitarbeiter konfiguriert. Probleme waren dabei vorprogrammiert: <NAME> konnte nicht auf die Datei »x« zugreifen, die Herr Müller erstellt hatte, da <NAME> im Gegensatz zu Herrn Müller ein modifiziertes Programm besaÃ. In diesem Fall hatte <NAME> zwei Möglichkeiten: Entweder er lieà das Programm vom Programmierer wieder anpassen (das war noch die Blütezeit für Programmierer, als immer Arbeit vorhanden war) oder er ging zu Herrn Müller, um sich von diesem die Daten zu besorgen. Doch als Herr Müller den Datensatz abrufen wollte, fand er ihn nicht mehr. Nach einigen Recherchen stellte sich heraus, dass <NAME> diesen Datensatz gelöscht hatte, da sie dachte, er würde nicht mehr benötigt. Da beim Zugriff auf gemeinsame Daten (auch File Sharing genannt) ein enormer Wartungsaufwand entstand, was häufig zu hohen Kosten führte, wurden Datenbanksysteme entwickelt. Ein Datenbanksystem hat gegenüber dem traditionellen Dateisystem die folgenden Vorteile: * Der Benutzer kann auf die Daten zugreifen, ohne dass er wissen muss, wie die einzelnen Daten organisiert sind. * Der Benutzer kann (fast) ohne Kenntnisse Daten löschen, hinzufügen, ändern oder erweitern. Der Benutzer muss nicht einmal wissen, um welche Datenbank es sich handelt. * Das Datenbanksystem sorgt dafür, dass ein unbedachter Benutzer Daten nicht einfach löschen kann oder doppelte Daten zweimal gespeichert werden. * Ein gutes Datenbanksystem ist portabel. Das bedeutet, das System organisiert den Datenbestand so, dass andere Programme und Systeme mithilfe von Schnittstellen auf diese Daten zurückgreifen können. * Datensätze werden so optimiert, dass sie geringeren Speicherplatz erfordern und eine schnellere Zugriffszeit haben. ### 24.1.2 Das Datenbank-Management-System (DBMS) Das Datenbank-Management-System (kurz DBMS) ist die Schnittstelle, mit der der Benutzer Mittel zu Verfügung gestellt bekommt, um mit der Datenbank zu kommunizieren. Durch das DBMS wird beim Ãndern, Hinzufügen, Löschen oder Erweitern immer die Korrektheit der Datenbestände überprüft. Greift der Benutzer zum Beispiel auf einen Datensatz in der Datenbank zurück, wird zuerst nach einem gewissen Schema des DBMS auf den Datenbestand zugegriffen. AnschlieÃend werden dem Benutzer diese Daten so serviert, wie er sie sich von der Anforderung wünscht. Dadurch entsteht eine Art Datenunabhängigkeit, die in einem DBMS deshalb so wichtig ist, weil dadurch die physische Speicherung einer Datenbank beliebig geändert werden kann, ohne die logische Struktur der Daten zu verändern. In Abbildung 24.1 können Sie das Drei-Schichten-Modell erkennen. Um es kurz zu halten: Es handelt sich dabei schlicht um die Trennung von Benutzer, DBMS und Datenspeicherung. Die externe Schicht beschreibt alle Möglichkeiten, die der Benutzer hat, um auf die Datenbank zuzugreifen (Programme, Funktionen und Schnittstellen). Die konzeptionelle Schicht beschreibt das Datenmodell (hier das relationale Modell). Mit diesem Modell wird beschrieben, wie auf die Daten zugriffen wird und in welchem Zusammenhang diese zueinander stehen. Die interne Schicht ist die tiefste Schicht und stellt die Ebene der Datenpräsentation dar – also, wie und wo die Daten gespeichert werden. Abbildung 24.1 Die drei Ebenen eines Datenbanksystems Noch ein paar Sätze zur logischen Struktur: Als C-Programmierer kennen Sie ja Strukturen. Folgende Struktur dient jetzt als Beispiel: > struct file{ char name[MAX]; char vame[MAX]; int old; struct file *l; struct file *r; }; Das Programm mit dieser Struktur läuft jahrelang bei Ihrem Kunden mit unzähligen Adressen. Jetzt wünscht Ihr Kunde, dass Sie den Datenbestand für int old entfernen und zwei andere Strukturvariablen dafür einsetzen. Sie müssen jetzt das Programm umschreiben, müssen den Datenbestand neu anpassen, und noch einiges mehr ist dabei zu beachten – eine Menge Arbeit also. Mit dem DBMS lässt sich dies ohne Mühe mit ein oder zwei Befehlen erledigen. Der Benutzer kommuniziert allerdings nicht direkt mit dem DBMS, sondern mit einer Schnittstelle, die sich noch vor dem DBMS befindet, dem DBCI (Data Base Communication Interface). Sie können hier eindeutig das Client/Server-Prinzip wiedererkennen, wobei der Server-Teil sich um die Verwaltung und Verarbeitung von Daten kümmert und der Client-Teil mit dem Benutzer zu tun hat. Er gewährleistet die komfortable Eingabe, einfaches Auslesen und mehr. Abbildung 24.2 zeigt das Beispiel grafisch. Abbildung 24.2 MySQL-Datenbanksystem Der Client kann jetzt ein Webbrowser sein, der ein CGI-Programm startet, mit dem auf die Datenbank zugegriffen wird, eine Java-Applikation mit der Schnittstelle JDBC (Java Database Connectivity), ein C-Programm mit der ODBC-Schnittstelle (Open DataBase Connectivity), ein Perl-Skript mit dem DBI-Modul oder auch der Datenbank-Client mysql. Wie auch immer Sie auf das DBMS zugreifen, der Server verarbeitet die Anfrage des Clients und schickt gesammelte Daten an ihn zurück. Und die Sprache, mit der hier kommuniziert wird, heiÃt SQL (Structured Query Language). SQL ist eine genormte Datenbanksprache, die in der Regel jede Datenbank versteht. Es gibt natürlich auch Client-Programme, die Sie verwenden können, ohne ein Wort SQL zu verstehen. Das Client-Programm sorgt in diesem Fall für die Kommunikation zwischen Server und Benutzer. Als ein C-Programmierer sollte es Ihr Ziel sein, ein solches Client-Programm zu entwickeln. ### 24.1.3 Relationale Datenbank MySQL ist eine Datenbank, die auf dem relationalen Konzept aufbaut. Das bedeutet, dass zwischen den Daten, die in Tabellen gespeichert werden, bestimmte Beziehungen bestehen. Sie können die Daten mit Zusammenhängen zu anderen Daten speichern. Folgende Beziehungen sind jetzt zwischen verschiedenen Datensätzen möglich: Beziehung | Bedeutung | | --- | --- | | | | | | | Wenn Sie das relationale Konzept hier nicht so richtig verstanden haben, macht dies für den weiteren Verlauf des Buchs nichts aus. Es sollte nur der Vollständigkeit halber erwähnt werden. ### 24.1.4 Eigene Clients mit C für SQL mithilfe der ODBC-API entwickeln In diesem Buch wird nur beschrieben, wie Sie eigene Clients für die MySQL-Datenbank mit der C-API (Application Programming Interface) schreiben können. Sie können zwar für jede Datenbank mit C eigene Client-Programme erstellen, nur liefert jede Datenbank dafür spezielle und leider unterschiedliche Funktionen. Wollen Sie Client-Programme schreiben, die mit jedem Datenbanksystem zusammenarbeiten, so benötigen Sie die ODBC-API, die eine reine C-Schnittstelle ist. Der ODBC-Treiber muss zuvor besorgt und installiert werden. Er klinkt sich dann zwischen die Client-Anwendung und das DBMS ein. Sendet der Client eine Anforderung an den Server, verarbeitet der ODBC-Treiber zuerst die Anfrage und gibt sie in entsprechender Form an den Server (DBMS) weiter, damit dieser die Anfrage versteht. Der Server antwortet anschlieÃend dem Client, wiederum durch den ODBC-Treiber. Wenn Sie so wollen, dient ODBC also als Dolmetscher für verschiedene Datenbanken mit dem Client-Programm. Heute gibt es kaum noch eine Anwendung ohne eine gewisse Netzwerkfunktionalität. Wie Sie ein einfaches Client/Server-Beispiel erstellen können – und das auch noch auf den verschiedensten Plattformen –, zeigt Ihnen dieses Kapitel. Die Netzwerkprogrammierung gehört nicht unbedingt zu den einfacheren Themen in der Programmierung. Auch wenn Ihnen dieses Kapitel den Eindruck verschafft, es sei alles nicht so schwer, sollten Sie sich nicht täuschen lassen: Sie erhalten hier lediglich einen Einblick in die Welt der Netzwerkprogrammierung. Allerdings erscheint es mir sehr wichtig, Ihnen diese Basis mitzugeben, da heutzutage kaum noch eine Anwendung ohne Netzwerkfunktionalität angeboten wird. Sicherlich stellt sich zunächst die Frage, wie man die Netzwerkprogrammierung in einem Buch behandelt, das sich primär mit der Erstellung von portablen Programmen befasst. Prallen hier mit der Netzwerkprogrammierung unter MS-Windows und den UNIX-Varianten (Linux) nicht zwei verschiedene Welten aufeinander? Im Verlaufe des Kapitels werden Sie merken, dass die grundlegenden Prinzipien dieselben sind – und die Funktionsnamen sind zum Teil sogar die gleichen. Und darum geht es auch im zweiten Teil dieses Kapitels, bei der Cross-Plattform-Entwicklung. Dabei werden Sie erfahren, wie Sie sinnvoll portable Headerdateien bzw. Bibliotheken erstellen können, die auf den verschiedensten Plattformen ausführbar sind (hier MS-Windows und Linux/UNIX) – natürlich wiederum anhand von Beispielen zur Netzwerkprogrammierung. ## 25.1 Begriffe zur Netzwerktechnik Bevor ich Sie in die Netzwerkprogrammierung einführe, möchte ich Ihnen hier noch einige Begriffe der Netzwerktechnik etwas näherbringen, damit Sie anschlieÃend bei der Programmierung nicht ins Straucheln geraten. Sollten Sie mit den Begriffen der Netzwerktechnik bereits vertraut sein, können Sie diesen Abschnitt selbstverständlich überfliegen. ### 25.1.1 IP-Nummern Die IP-Nummer (IP – Internet Protokoll) ist mit einer Telefonnummer vergleichbar. Unter dieser Nummer sind Sie im Internet für alle anderen Teilnehmer erreichbar. Daher ist es auch verständlich, dass diese Nummer eindeutig sein muss, sodass keine Adresskonflikte auftreten können. # Statische und dynamische IP-Nummern Bei den IP-Nummern unterscheidet man (sofern man von einem Unterschied sprechen kann) zwischen einer statischen und einer dynamischen IP-Nummer. Rechner, die ständig im Internet sind, um etwa einen bestimmten Service anzubieten, benötigen meistens eine statische IP-Nummer. Man spricht von einer statischen IP-Nummer, wenn einem Rechner einmal eine Nummer zugeteilt wird und sich diese anschlieÃend nicht mehr ändert. Natürlich können Sie sich auch eine eigene IP-Nummer geben lassen (beispielsweise um einen eigenen Webserver zu betreiben). Dazu müssen Sie sich über einen Internet Provider oder besser gleich über das Network Information Center (NIC) eine solche Nummer zuteilen lassen. Für Privatpersonen bzw. mittelständische Firmen lohnt sich dies allerdings recht selten – da eine feste IP-Nummer auch ihren Preis hat. Gewöhnlich wird Ihnen, wenn Sie sich ins Internet einwählen, jedes Mal eine neue dynamische IP-Adresse erteilt. Sie wählen sich praktisch ins Internet ein und Ihr Internet Service Provider teilt Ihnen so eine dynamische IP-Adresse zu. Neben dem geringeren Verbrauch von IP-Adressen wird auch der Admin-Aufwand erheblich verringert. Dies trifft besonders bei gröÃeren lokalen Netzwerken zu. Hierbei muss der Admin nicht jede einzelne statische IP-Adresse ins Netzwerk integrieren, sondern meistens übernimmt eine Software die Verteilung der dynamischen IP-Adressen. # IPv4- und IPv6-Nummern Im Augenblick setzen sich die IP-Nummern (IPv4) noch aus vier Zahlen (32 Bit) zwischen 0 und 255 zusammen. Dadurch sind mit IPv4 Adressierungen zwischen 0.0.0.0 und 255.255.255.255 möglich – was etwa 4 Milliarden Adressen wären. Allerdings nur theoretisch – da diverse Nummern, beispielsweise mit der Endung 0 und 255, für andere Zwecke vergeben sind. Und 4 Milliarden IP-Adressen sind in der Tat nicht viele – wenn man diese Zahl mit der Weltbevölkerung vergleicht. Somit musste eine andere Lösung gefunden werden – die auch schon längst mit IPv6 gefunden wurde. In IPv6 sind die Adressen 128 Bit lang, anstatt der 32 Bit in IPv4. Damit lassen sich natürlich erheblich mehr IP-Adressen darstellen. IPv6 ist allerdings noch nicht eingeführt und immer noch für unbestimmte Zeit Zukunftsmusik. Wenn IPv6 eingeführt wird, werden Sie sich auch an eine andere Schreibweise gewöhnen müssen, die auf den ersten Blick ein wenig komplexer erscheint. Schreibt man beispielsweise eine IPv6-Adresse vollständig aus, ergeben sich sieben Doppelpunkte getrennt durch Hexadezimalzahlen: 2ffd:345:34b:33:432:e23:a:2 Diese Schreibweise kann durch die Zusammenfassung von Nullen noch vereinfacht werden. So kann beispielsweise eine Gruppe von aufeinanderfolgenden Nullen durch zwei Doppelpunkte (::) angegeben werden. Dies ist beispielsweise auch nötig bzw. der Fall, wenn die Kompatibilität zu IPv4-Adressen gewahrt werden muss. Da beispielsweise bei einer IPv4-Adresse, die in IPv6 konvertiert wird, die ersten sechs Gruppen mit Nullen beziffert sind (IPv4: xxx.xxx.xxx.xxx konvertiert zu IPv6: 0:0:0:0:0:0:xxxx:xxxx), kann man es sich auch hier mit der Doppelpunktregelung einfacher machen (0:0:0:0:0:0:xxxx:xxxx; Gruppe von Nullen durch :: ersetzen ::xxxx:xxxx). Und damit man bei der Konvertierung nicht dauernd auch noch den hexadezimalen Wert der IPv4-Adresse zur IPv6-Adresse umrechnen muss (oder errechnen lässt), ist es auch erlaubt, dass die letzten beiden Ziffern dezimal (also aus den vier Zahlen wie in IPv4) angegeben werden können (also als 0:0:0:0:0:0:xxx.xxx.xxx.xxx oder auch als ::xxx.xxx.xxx.xxx). ### 25.1.2 Portnummer Bei den Internetprotokollen TCP/IP und UDP/IP sind neben den IP-Nummern, mit denen ein Rechner spezifiziert wird, auch noch sogenannte Portnummern (16 Bit lang; 0 bis 65535) vorhanden. Mit den Portnummern wird ein bestimmter Service (Dienst) auf dem Rechner spezifiziert. Jeder Service (Dienst) hat dabei gewöhnlich eine eigene Portnummer. Die bekannteste Portnummer z. B. dürfte 80 (HTTP-Dienst) sein: Ãber diesen Port unterhält sich gewöhnlich der Webserver mit dem Webbrowser. Entsprechend der Portnummer reagiert also auch der Rechner mit einem entsprechenden Dienst und dem damit verknüpften Protokoll. Bei Firewalls lassen sich die Portnummern verwenden, um gewisse Nachrichten herauszufiltern. Ebenfalls lassen sich dabei bestimmte Dienste auf dem Rechner sperren, indem einfach entschieden wird, welche Ports durchgelassen werden und welche nicht. Man kann sich die Ports gern als Türen vorstellen – lässt man andauernd die Tür offen stehen, braucht man sich nicht über ungebetene Gäste wundern. Selbstverständlich sind die Ports auch (teilweise) standardisiert. Besonders die ersten 1023 Portnummern werden beispielsweise von der IANA (Internet Assigned Numbers Authority) kontrolliert und zugewiesen. Unter Linux/UNIX können diese ersten 1023 Portnummern in der Regel meistens nur durch den Superuser verwendet werden. Hier finden sich die Portnummern vieler Standard-Anwendungen wieder. Beispielsweise wird FTP über Port 21 abgewickelt, TELNET über Port 23 oder der Internetverkehr (HTTP) über Port 80. Natürlich sind die Portnummern unter 1024 auch ein beliebtes Ziel für Hacker. ### 25.1.3 Host- und Domainname Zwar wissen Sie jetzt, dass im Internet alles über IP-Nummern erreichbar ist, aber wenn Sie sich mit diesen Nummern durchs WWW hangeln müssten, wäre das Internet wohl heute nicht so erfolgreich. Deshalb wird an die Nummern noch zusätzlich ein Name vergeben, der aus dem Host- und dem Domainnamen (und eventuell einer Top-Level-Domain; TLD) besteht (hostname.domainname.tld; beispielsweise www.pronix.de). Der Domainname ist der Name, mit dem Sie eine Webseite (beispielsweise pronix.de) im Internet ansprechen. Ein Domainname wird von hinten nach vorne aufgelöst. Somit steht das de für die Top-Level-Domain (wie der Name sagt, das, was ganz vorne steht). Die Top-Level-Domain bezeichnet die Herkunft und/oder die Zugehörigkeit (.com, .gov, .net etc.), in unserem Beispiel de für Deutschland. Nach der Top-Level-Domain folgt weiter links der eigentliche Domainname, der im Beispiel pronix lautet. Der Hostname ist somit die niedrigste Instanz eines Domainnamens, da dieser ja von hinten nach vorne aufgelöst wird. Der Hostname ist somit der erste Teil in der Leseweise. Gewöhnlich lautet im Internet der Hostname www (www.pronix.de) – allerdings spricht nichts dagegen, den Host auch anders zu benennen. Es wird nämlich nur empfohlen, weil sich viele Anwender an das www gewöhnt haben. Genauso gut könnten Sie auch abc.pronix.de verwenden. ### 25.1.4 Nameserver Einfach ausgedrückt ist ein Nameserver ein Rechner, der für die Umsetzung von Rechnernamen in IP-Nummern verantwortlich ist. Im Internet beispielsweise ist dies mit einem Telefonbuch vergleichbar, in dem der Name des Teilnehmers in die Telefonnummer aufgelöst wird. Der Dienst, der Ihnen diese Arbeit im Internet abnimmt, wird als Domain Name System (DNS) bezeichnet. Bei kleineren Netzwerken wie einem Intranet, werden die lokalen IP-Nummern meistens in Form einer Tabelle in einer Datei hinterlegt. ### 25.1.5 Das IP-Protokoll Das IP-Protokoll ist dafür verantwortlich, dass die Datenpakete von einem Sender über mehrere Netze zum Empfänger transportiert werden. Die Ãbertragung des IP-Protokolls findet paketorientiert und verbindungslos statt. Es wird dabei nicht garantiert, dass die Pakete in der richtigen Reihenfolge oder überhaupt beim Empfänger ankommen. Ebenfalls liefert es keine Empfangsbestätigung vom Empfänger an den Sender zurück. Die maximale Länge eines IP-Paketes ist auf 65.535 Bytes beschränkt. Da das IP-Protokoll auch für das IP-Routing durch ein Netzwerk verantwortlich ist, kann dieses Protokoll die einzelnen Stationen auch anhand der IP-Adresse identifizieren. Da es ja keine Garantie gibt, dass die Daten ans Ziel gelangen, gibt es im IP-Header des IP-Paketes ein Time-to-Live-Feld (TTL), in dem die Lebensdauer eines Datagramms (hier des Pakets) festgelegt wird. Das TTL-Feld sorgt dafür, dass die Datenpakete nicht unendlich durch das Netz irren und den Datenverkehr belasten. Ist die im TTL-Feld angegebene Lebensdauer abgelaufen, wird das Datenpaket verworfen. Abbildung 25.1 Das IP-Protokoll und die assoziierten Verbindungen ### 25.1.6 TCP und UDP Aufbauend auf das IP-Protokoll gibt es zwei wichtige Transportprotokolle: TCP/IP (TCP – Transmission Control Protocol) und UDP/IP (UDP – User Datagram Protocol). Beide Protokolle sind auf der Transport-Ebene angesiedelt. Der Vorteil von TCP ist, dass eine zuverlässige Datenübertragung garantiert wird. Dabei wird beispielsweise sichergestellt, dass ein Paket, das nach einer gewissen Zeit nicht beim Empfänger angekommen ist, erneut gesendet wird. Ebenso garantiert TCP, dass die Datenpakete auch in der Reihenfolge geliefert werden, in der sie losgeschickt wurden. Zusammengefasst erhalten Sie beim TCP-Protokoll eine Ende-zu-Ende-Kontrolle (Peer-to-Peer), ein Verbindungsmanagement (nach dem sogenannten Handshake-Prinzip), eine Zeitkontrolle, eine Flusskontrolle sowie eine Fehlerbehandlung der Verbindung. Man spricht bei TCP von einem verbindungsorientierten Transportprotokoll. Das UPD-Protokoll hingegen verwendet einen verbindungslosen Datenaustausch zwischen den einzelnen Rechnern. Mit UDP haben Sie in Ihren Anwendungen die direkte Möglichkeit, Datagramme zu senden. Allerdings gibt es keine Garantie, dass ein Datagramm beim Empfänger abgeliefert wird. Ebenso wenig ist es gegeben, dass die Datagramme in der richtigen Reihenfolge ankommen (es ist sogar möglich, dass Datagramme mehrfach ankommen). Der Vorteil davon, dass bei UDP weniger Verwaltungsaufwand betrieben werden muss, ist natürlich ein höherer Datendurchsatz, der mit TCP nicht möglich ist. UDP ist beispielsweise recht interessant für Videoübertragung oder bei Netzwerkspielen. In diesen Anwendungsbereichen ist es nicht so schlimm, wenn das eine oder andere Datenpaket mal nicht ankommt. Die UDP-Strategie kann man gern mit dem Motto »Erst schieÃen, dann fragen« vergleichen. ### 25.1.7 Was sind Sockets? Ein Socket ist eine bidirektionale (Vollduplex-)Software-Struktur, die zur Netzwerk- oder Interprozesskommunikation verwendet wird. Somit ist ein Socket eine Schnittstelle zwischen einem Prozess (Ihrer Anwendung) und einem Transportprotokoll, was meistens das TCP- oder UDP-Protokoll ist. In den RFCs ist ein Socket als ein 5-Tupel aus Ziel- und Quell-IP-Adresse, Ziel- und Quell-Port und dem Netzwerkprotokoll beschrieben. Sockets werden in UDP und TCP verwendet. RFC | | --- | | Seit 1983 verwendet BSD die Netzwerk-Sockets in seiner Berkeley Sockets API. Linux, Solaris und viele andere UNIX-Varianten verwenden ebenfalls die BSD-Sockets. Der Zugriff auf ein Socket erfolgt ähnlich wie auf Dateien mit einem Filedeskriptor – nur mit dem Unterschied, dass es bei Sockets nicht um Dateien geht, sondern um Kommunikationskanäle. MS-Windows verwendet eine ähnliche API wie in den Berkeley Sockets, die Windows Sockets (kurz Winsock). Der Trend des Megahertz-Wahns scheint derzeit ein wenig rückläufig zu sein, und stattdessen ist es schick geworden, mehrere Prozessoren in einen Rechner einzubauen. Allerdings nützen solche Multiprozessor-Systeme nur dann etwas, wenn auch die Programme dafür erstellt wurden. Wie das geht, erfahren Sie in diesem Kapitel. ## 26.1 Parallelität Die Werbung der Computerbranche versucht zurzeit kräftig, sogenannte Dual- bzw. Quad-Core-PCs an den Mann (oder die Frau) zu bringen. Mittlerweile ist schon in jedem Discounter-PC ein solcher Prozessor eingebaut. Dabei wird einem versprochen, dass man mit zwei Prozessoren die doppelte Rechenleistung erhält, weil ja die Rechenaufgaben auf zwei Prozessoren aufgeteilt werden. Zwei Prozessoren bringen also die doppelte Leistung? Nein, hier hat man die Rechnung ohne den Wirt gemacht. Zunächst machen solche Multiprozessorsysteme so viel Sinn, wie wenn man zwei Autos in der Garage stehen hat – man kann auch nur eines gleichzeitig fahren. Um also beide oder gegebenenfalls mehrere Prozessoren zu verwenden, muss auch die Software dafür geschrieben sein. Auch wenn die Software für Multi-Prozessorsysteme angepasst wurde, kann man noch lange nicht sagen, um welchen Faktor (auch Speedup genannt) die Software schneller läuft. Es gibt mehrere Faktoren, von denen es abhängt, um wie viel das Programm letztendlich schneller läuft: Kann beispielsweise der Prozessor die Daten aus seinem eigenen schnellen Cache holen, oder müssen diese immer aus dem langsamen Arbeitsspeicher geholt werden? Dies hängt von der Cache-GröÃe des Prozessors ab. Hinzu kommen auch GröÃe, Topologie und Bandbreite des Speichers. Es gibt auch Situationen, in denen man mit der seriellen Programmierung genauso gute Ergebnisse erzielen kann wie mit der parallelen. Zusammengefasst lässt sich sagen, dass man den gewonnenen Geschwindigkeitsfaktor der Software erst im laufenden Betrieb ermitteln kann. Fakt ist auf jeden Fall, dass sich die Multiprozessorsysteme künftig auch auf gewöhnlichen Workstation-Rechnern verbreiten werden. Ein guter Grund also, sich mit der Entwicklung paralleler Software zu befassen. ### 26.1.1 Single-Prozessorsysteme Damit Programme tatsächlich parallel laufen, müssen mehrere Prozessoren vorhanden sein. Trotzdem ist es auch möglich, dass Single-Prozessorsysteme von der parallelen Programmierung profitieren. So teilen sich bei einer parallelen Anwendung beispielsweise alle einzelnen Threads das Codesegment, das Datensegment, den Heap und alle anderen Zustandsdaten, die ein gewöhnlicher Prozess besitzt. Somit sind mehrere Threads leichtgewichtiger als mehrere Prozesse. ### 26.1.2 Hyperthreading Hyperthreading wird häufig mit Multithreading in einen Topf geworfen. Nun hat Hyperthreading aber zunächst nichts mit zwei Prozessoren zu tun und wird trotzdem bei der Entwicklung von Multithreading-Anwendungen verwendet. Die Technologie Hyperthreading wurde von Intel mit den Prozessoren Pentium III, Pentium 4 und Xeon eingeführt, aber auch AMD hat entsprechende Prozessoren auf dem Markt. Mit dieser Technologie wird der Durchsatz von Multithreaded-Anwendungen im Multitasking erhöht, indem sie die Auslastung der On-Chip-Ressourcen erhöht, die in der Intel-NetBurst-Mikroarchitektur verfügbar sind. Ein typischer Thread belastet nur etwa 35 % der NetBurst-Ausführungsressourcen. Hyperthreading erhöht die Auslastung durch notwendige Logik und Ressourcen, die der CPU hinzugefügt werden. Für die Aufteilung der einkommenden Daten auf den freien Raum sorgen somit zwei logische Prozessoren, die vom Betriebssystem mittels klassischer Multiprocessing-Verfahren verwaltet werden. NetBurst | | --- | | Ich will hier nicht mit dem Fachchinesisch weitermachen – es lässt sich auch einfacher erklären. Mit Hyperthreading wird dem Betriebssystem ein zweiter logischer Prozessor vorgegaukelt. Dazu wird intern einfach das Register der CPU verdoppelt und es werden zwei getrennte Recorder- und Store-Buffer eingebaut. Allerdings teilen sich die beiden virtuellen Prozessoren die Funktionseinheiten, sodass es rein logisch nicht möglich ist, dass Befehle zweier Threads gleichzeitig ausgeführt werden. Aber in der Praxis stellte sich heraus, dass diese Technik manchmal genauso effektiv ist, als befänden sich zwei physikalische Prozessoren im System. Daher werden in der Praxis auch Prozessoren, die Hyperthreading implementiert haben, als parallele Systeme anerkannt. In diesem Kapitel werden zwei Themen angesprochen, die vielleicht auf den ersten Blick nicht allzu interessant erscheinen: Buffer Overflows und Memory Leaks. Da diese beiden Probleme jedoch leider häufiger in Erscheinung treten, sollte sich jeder ernsthafte Programmierer mit ihnen auseinandersetzen. Ein Aspekt, der oft übersehen wird, ist die sicherheitsbezogene Programmierung. Programmierer setzen oft Funktionen ein, von denen sie zwar wissen, dass diese nicht ganz sicher sind, aber sie wissen nicht, was diese unsicheren Funktionen bewirken können. Sie haben nach langjähriger Programmiererfahrung zwar jeden Algorithmus im Kopf und ihnen kann keiner etwas vormachen, sie verwenden aber trotzdem weiter diese Funktionen, weil sie sie eben immer verwenden und nicht so genau wissen, was daran schlimm sein soll. Denn das Programm läuft doch. Richtig? – Nein, falsch! Auch wenn der Konkurrenzkampf und der Zeitdruck bei der Fertigstellung eines Projekts heutzutage enorm sind, sollten Sie diese Einstellung überdenken und sich ernsthaft mit diesem Thema befassen. Diese zunächst unscheinbaren Unsicherheiten von Beginn an zu berücksichtigen, ist ein Bestandteil von vorausschauender Programmentwicklung und trägt wesentlich zur Qualitätssicherung Ihrer Programme bei. Auf diese Weise begegnen Sie schon im Vorfeld unvorhersehbarem Ãrger, und nachträglich entstehen hohe Kosten. Ein Szenario: Sie haben für eine Firma ein Programm zur Verwaltung von Daten geschrieben. In der Firma haben einige gewiefte Mitarbeiter einen Weg gefunden, mithilfe Ihres Programms aus dem Verwaltungsprogramm zu springen, wodurch sie ins System gelangen und allerlei Unfug anrichten. Der Kunde wird mit Sicherheit kein Programm mehr von Ihnen entwickeln lassen. Also haben Sie auf jeden Fall schon einen Imageschaden. Da Sie aber versprochen haben, sich um das Problem zu kümmern, müssen Sie alles andere erst einmal stehen und liegen lassen. Damit haben Sie schon kostbare Zeit verloren, die Sie für andere Projekte hätten nutzen können. Da noch weitere Kunden dieses Produkt verwenden, müssen Sie auch diese informieren. Jetzt ist es an der Zeit, ein Bugfix (Patch) zu schreiben, den der Kunde einspielen muss, um den Fehler zu beheben. Wenn Sie Glück haben, kann der Kunde das Programm unterbrechen und den Patch einspielen. Sollte der Kunde aber rund um die Uhr auf das Programm angewiesen sein, entstehen ihm Ausfallkosten. Nachdem Sie den Patch aufgespielt haben, treten andere unerwartete Probleme mit dem Programm auf. Somit folgt dem Patch ein weiterer, womit wieder Zeit, Geld und Image verloren gehen. Ich denke, dass jedem schon einmal ein ähnliches Szenario mit einem Programm widerfahren ist. Die meisten solcher Sicherheitsprobleme treten mit Programmen auf, die in C geschrieben wurden. Dies heiÃt allerdings nicht, dass C eine unsichere Sprache ist, sondern es bedeutet nur, dass sie eine der am häufigsten eingesetzten Sprachen ist. Viele Systemtools, Server, Datenbanken, aber auch grafische Oberflächen sind in C geschrieben. Sie sehen also, dass es sich durchaus lohnt, diese Themen aufzugreifen und bei der Entwicklung von Programmen zu berücksichtigen. ## 27.1 Buffer-Overflow (Speicherüberlauf) Eines der bekanntesten und am häufigsten auftretenden Sicherheitsprobleme ist der Buffer-Overflow (dt.: Speicherüberlauf, Pufferüberlauf), häufig auch als Buffer Overrun bezeichnet. Geben Sie einmal in einer Internet-Suchmaschine den Begriff »Buffer-Overflow« ein, und Sie werden angesichts der enormen Anzahl von Ergebnissen überrascht sein. Es gibt unzählige Programme, die für einen Buffer-Overflow anfällig sind. Das Ziel des Angreifers ist es dabei, den Buffer-Overflow auszunutzen, um in das System einzubrechen. Die Aufgabe dieses Abschnitts ist es nicht, Ihnen beizubringen, wie Sie Programme hacken können, sondern zu erklären, was ein Buffer-Overflow ist, wie dieser ausgelöst wird und was Sie als Programmierer beachten müssen, damit Ihr Programm nicht anfällig dafür ist. Für den Buffer-Overflow ist immer der Programmierer selbst verantwortlich. Der Overflow kann überall dort auftreten, wo Daten von der Tastatur, dem Netzwerk oder einer anderen Quelle aus in einen Speicherbereich mit statischer GröÃe ohne eine Längenüberprüfung geschrieben werden. Hier sehen Sie ein solches Negativbeispiel: > /* bufferoverflow1.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char *str = "0123456789012"; char buf[10]; strcpy(buf, str); printf("%s",buf); return EXIT_SUCCESS; } Hier wurde ein Buffer-Overflow mit der Funktion strcpy() erzeugt. Es wird dabei versucht, in den char-Vektor, der Platz für 10 Zeichen reserviert hat, mehr als diese 10 Zeichen zu kopieren. Abbildung 27.1 Pufferüberlauf mit der Funktion »strcpy()« Die Auswirkungen eines Buffer Overflows sind stark vom Betriebssystem abhängig. Häufig stürzt dabei das Programm ab, weil Variablen mit irgendwelchen Werten überschrieben wurden. Manches Mal bekommen Sie aber auch nach Beendigung des Programms eine Fehlermeldung zurück, etwa Speicherzugriffsfehler. Dies wird ausgegeben, wenn z. B. die Rücksprungadresse des Programms überschrieben wurde und das Programm irgendwo in eine unerlaubte Speicheradresse springt. Wird aber bewusst diese Rücksprungadresse manipuliert und auf einen speziell von Ihnen erstellten Speicherbereich verwiesen bzw. gesprungen, der echten Code enthält, haben Sie einen sogenannten Exploit erstellt. ### 27.1.1 Speicherverwaltung von Programmen Ein Programm besteht aus drei Speichersegmenten, die im Arbeitsspeicher liegen. Der Prozessor (CPU) holt sich die Daten und Anweisungen aus diesem Arbeitsspeicher. Damit der Prozessor unterscheiden kann, ob es sich bei den Daten um Maschinenbefehle oder den Datenteil mit den Variablen handelt, werden diese Speicherbereiche in einzelne Segmente aufgeteilt. In Abbildung 27.2 sind die einzelnen Segmente schematisch dargestellt. Abbildung 27.2 Speicherverwaltung – die einzelnen Segmente * Code-Segment (Text-Segment) – Hier befinden sich die Maschinenbefehle, die vom Prozessor beim HOLEN-Zyklus eingelesen werden – oder einfacher gesagt: der Programmcode selbst. Das Code-Segment lässt sich nicht manipulieren, hat eine feste GröÃe und ist gegen Ãberschreiben geschützt. * Heap-Segment (Daten-Segment) – Hier liegen die Variablen (extern, static), Felder (Arrays) und Tabellen des Programms. Der Maschinenbefehl, der diese Daten benötigt, greift auf dieses Segment zu. * Stack-Segment – Hier befinden sich dynamische Variablen und Rücksprungadressen von Funktionen. Dieser Bereich dient auch dem schnellen Zwischenspeichern von Daten und Parameterübergaben. Es sei hierbei noch erwähnt, dass der Stack-Bereich nach unten und der Heap nach oben anwächst. Der Stack ist auch das Angriffsziel für einen Buffer-Overflow. ### 27.1.2 Der Stack-Frame Für jede Funktion steht ein sogenannter Stack-Frame im Stack zur Verfügung, in dem die lokalen Variablen gespeichert werden. Wichtiger noch: Im Stack befinden sich Registerinhalte des Prozessors, die vor dem Funktionsaufruf gesichert wurden. Sie sind nötig, um bei Beendigung der Funktion auf die aufrufende Funktion zurückspringen zu können. Beispielsweise wird in der main()-Funktion die Funktion mit den Parametern my_func(wert1, wert2) aufgerufen: > /* stackframe.c */ #include <stdio.h> #include <stdlib.h> void my_func(int wert1, int wert2) { int summe; summe = wert1+wert2; printf("Summe: %d \n",summe); } int main(void) { my_func(10,29); return 0; } Dies geschieht jetzt – ohne zu sehr ins Detail zu gehen – in folgenden Schritten auf dem Stack: 1. | Mit dem Assembler-Befehl PUSH werden die Parameter wert1 und wert2 auf den Stack geschrieben. | | --- | --- | 2. | Mit dem Assembler-Befehl CALL wird die Position des Maschinencodes gesichert, damit bei Beendigung der Funktion my_func() wieder in die main()-Funktion zurückgesprungen werden kann. Dies wird mithilfe des Befehlszeigers (Instruction Pointer, kurz: IP) realisiert. Genau genommen wird diese Adresse mithilfe des Befehlszeigers, des Code-Segments (CS) (CS:IP) und des Basis-Pointers (BP) erzeugt. Dies ist die Rücksprungadresse, die mit CS:IP und BP dargestellt wird. | | --- | --- | 3. | Jetzt werden die lokalen Variablen der Funktion my_func() eingerichtet, und die Funktion arbeitet die einzelnen Befehle ab. | | --- | --- | 4. | Am Schluss, wenn diese Funktion beendet ist, springt sie wieder zur main()-Funktion zurück. Dies geschieht mit dem Assembler-Befehl RET, der auf die vom Stack gesicherte Adresse zurückspringt, die aus CS:IP und BP gebildet wird. | | --- | --- | ### 27.1.3 Rücksprungadresse manipulieren In diesem Abschnitt folgt ein Beispiel, das zeigt, wie die Rücksprungadresse manipuliert werden kann. Es ist hierbei nicht Ziel und Zweck, Ihnen eine Schritt-für-Schritt-Anleitung zur Programmierung eines Exploits an die Hand zu geben und bewusst einen Buffer-Overflow zu erzeugen, sondern Ihnen soll vor Augen geführt werden, wie schnell und unbewusst kleine Unstimmigkeiten im Quellcode Hackern Tür und Tor öffnen können – einige Kenntnisse der Funktionsweise von Assemblern vorausgesetzt. Zur Demonstration des folgenden Beispiels werden der Compiler gcc und der Diassembler objdump verwendet. Das Funktionieren dieses Beispiels ist nicht auf allen Systemen garantiert, da bei den verschiedenen Betriebssystemen zum Teil unterschiedlich auf den Stack zugegriffen wird. Folgendes Listing sei gegeben: > /* bufferoverflow2.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> void overflow(void) { char zeichen[5]; strcpy(zeichen, "1234567"); /*Ãberlauf*/ } int main(void) { printf("Mein 1.Buffer Overflow\n"); overflow(); return EXIT_SUCCESS; } Ãbersetzen Sie das Programm, und verwenden Sie anschlieÃend den Diassembler, um sich den Maschinencode und den Assembler-Code des Programms anzusehen. Hierfür wird der Diassembler objdump verwendet, der auf fast jedem System vorhanden sein dürfte. Rufen Sie den Diassembler mit folgender Option in der Kommandozeile auf: > objdump -d bufferoverflow2 Jetzt sollte in etwa folgende Ausgabe auf dem Bildschirm erscheinen (gekürzt): > ... 08048490 <overflow>: 8048490: 55 push %ebp 8048491: 89 e5 mov %esp,%ebp 8048493: 83 ec 18 sub $0x18,%esp 8048496: 83 ec 08 sub $0x8,%esp 8048499: 68 44 85 04 08 push $0x8048544 804849e: 8d 45 e8 lea 0xffffffe8(%ebp),%eax 80484a1: 50 push %eax 80484a2: e8 d9 fe ff ff call 8048380 <_init+0x78> 80484a7: 83 c4 10 add $0x10,%esp 80484aa: 89 ec mov %ebp,%esp 80484ac: 5d pop %ebp 80484ad: c3 ret 80484ae: 89 f6 mov %esi,%esi ... In der linken Spalte befindet sich der Adressspeicher. An der Adresse »08048490« fängt in diesem Beispiel die Funktion overflow() an. Diese Adresse wurde zuvor etwa von der main()-Funktion mit > 80484c6: e8 c5 ff ff ff call 8048490 <overflowaufgerufen. In der zweiten Spalte befindet sich der Maschinencode (Opcode). Dieser Code ist schwer für den Menschen nachvollziehbar. Aber alle Zahlen haben ihre Bedeutung. So steht z. B. die Zahl »55« für push %ebp, was den Basis-Pointer auf dem Stack sichert, und »5d« entfernt den Basis-Pointer wieder vom Stack. »c3« bedeutet ret, also return. Mit »c3« wird also wieder an die Rücksprungadresse gesprungen, die in der main()-Funktion ebenfalls auf den Stack gepusht wurde. Häufig finden Sie den Maschinencode »90« (nop), der nichts anderes macht, als Zeit des Prozessors zu vertrödeln. In der dritten Spalte befindet sich der Assembler-Code, beispielsweise: > add $0x10,%esp mov %ebp,%esp Es ist wichtig, dass Sie verstehen, woraus ein Programm eigentlich besteht. Ein einfaches C-Konstrukt wie die for-Schleife wird z. B. in Hunderte kleine Maschinencodes (Opcodes) zerlegt. Vielleicht wissen Sie nun, wenn Sie das nächste Mal mit einem Hexeditor ein Programm öffnen, ein bisschen mehr darüber, was diese Zahlen (Maschinencode) und Zeilen (Adressen) bedeuten. Um es gleich vorwegzunehmen: Dies hier wird kein Assembler-Kurs oder Ãhnliches. Das Thema ist recht komplex. Ãbersetzen Sie das Programm von eben nochmals mit: > gcc -S -o bufferoverflow2.s bufferoverflow2.c Jetzt befindet sich im Verzeichnis eine Assembler-Datei (*.s oder *.asm) des Programms. Wir wollen uns diese in gekürzter Fassung ansehen: > main: pushl %ebp ;Framepointer auf dem Stack movl %esp, %ebp ;Stackpointer(esp) in Framepointer(ebp) kopieren subl $8, %esp ;Stackpointer um 8 Bytes verringern subl $12, %esp ;Stackpointer um 12 Bytes verringern für ausgabe printf pushl $.LC1 ;Den String "Mein 1.Buffer Overflow\n" call printf ;Funktion printf aufrufen addl $16, %esp ;Stackpointer um 16 Bytes erhoehen call overflow ;overflow aufrufen, Rücksprungadresse auf dem ;Stack movl $0, %eax movl %ebp, %esp popl %ebp ret overflow: pushl %ebp ;Wieder ein Framepointer auf dem Stack movl %esp, %ebp ;Stackpointer(esp) in Framepointer(ebp) ;kopieren subl $24, %esp ;Stackpointer-24Bytes subl $8, %esp ;Stackpointer-8Bytes pushl $.LC0 ;Den String "1234567" auf dem Stack leal -24(%ebp), %eax ;Laden des Offsets zu eax pushl %eax ;eax auf dem Stack call strcpy ;Funktion strcpy aufrufen addl $16, %esp ;16 Bytes vom Stack freigeben movl %ebp, %esp ;Stackpointer in Framepointer kopieren popl %ebp ;Framepointer wieder vom Stack ret ;Zurueck zur main-Funktion Dies ist ein kleiner Ãberblick über die Assembler-Schreibweise des Programms. Hier ist ja nur die Rücksprungadresse des Aufrufs call overflow von Interesse. Da Sie jetzt wissen, wie Sie an die Rücksprungadresse eines Programms herankommen, können Sie nun ein Programm schreiben, bei dem der Buffer-Overflow, der ja hier durch die Funktion strcpy() ausgelöst wird, zum Ãndern der Rücksprungadresse genutzt wird. Es wird dabei im Fachjargon von Buffer-Overflow Exploit gesprochen. Bei dem folgenden Beispiel soll die Rücksprungadresse manipuliert werden: > /* bufferoverflow3.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> void funktion(int temp,char *array) { char puffer[5]; strcpy(puffer, array); printf("%s\n",puffer); } int main(void) { int wert; wert=0; funktion(7,"hallo"); wert=1; printf("%d\n",wert); } Das Ziel soll es nun sein, die Funktion funktion() aufzurufen und die Rücksprungadresse zu wert=1; zu überspringen, sodass printf() als Wert 0 anstatt 1 ausgibt. Nach dem Funktionsaufruf sieht der Stack so aus: Abbildung 27.3 Der aktuelle Zustand des Stacks Wie kommen Sie nun am einfachsten zur Rücksprungadresse? Mit einem Zeiger. Also benötigen Sie zuerst einen Zeiger, der auf diese Rücksprungadresse verweist. AnschlieÃend manipulieren Sie die Adresse der Rücksprungadresse, auf die der Pointer zeigt, und zwar so, dass die Wertzuweisung wert=1 übersprungen wird: > /* bufferoverflow4.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> void funktion(int tmp,char *array) { char puffer[5]; int *pointer; strcpy(puffer, array); printf("%s\n",puffer); /* Pointer auf dem Stack um 4 Bytes zurücksetzen. Sollte jetzt auf die Rücksprungadresse zeigen. */ pointer=&tmp-1; /*Rücksprungadresse, auf die Pointer zeigt, 10 Bytes weiter*/ *pointer=*pointer+10; } int main(void) { int a; a=0; funktion(7,"hallo"); a=1; printf("wert = %d\n",a); return EXIT_SUCCESS; } Die einfachste Möglichkeit, auf die Rücksprungadresse zurückzugreifen, besteht darin, um die SpeichergröÃe der Variablen temp in der Funktion rückwärts zu springen. > pointer=&tmp-1; Jetzt können Sie die Rücksprungadresse manipulieren, auf die der pointer zeigt: > *pointer=*pointer+10; Abbildung 27.4 Der Zeiger verweist auf die Rücksprungadresse. Warum habe ich hier die Rücksprungadresse um 10 Bytes erhöht? Dazu müssen Sie wieder objdump einsetzen (ohne Opcodes im Beispiel): > objdump -d bufferoverflow4 080484e0 <main>: ... 80484f7: call 8048490 <funktion> ;Aufruf funktion 80484fc: add $0x10,%esp ;Stack wieder freigeben 80484ff: movl $0x1,0xfffffffc(%ebp) ;wert=1 8048506: sub $0x8,%esp 8048509: pushl 0xfffffffc(%ebp) ;printf vorbereiten 804850c: push $0x804859e 8048511: call 8048360 <_init+0x58> ;printf aufrufen ... Die zu überspringende Adresse liegt in diesem Fall ja zwischen »80484ff« und »8048509«. Somit ergibt sich folgende Rechnung: > 8048509 - 80484ff = A A ist der hexdezimale Wert für 10. Hiermit haben Sie die Rücksprungadresse Ihres eigenen Programms manipuliert. Das Ziel dieser Manipulation ist es aber selten (wie hier dargestellt), die Rücksprungadresse zu ändern, um den Programmcode an einer beliebigen Stelle weiter auszuführen, sondern meistens wird dabei die CPU mit einem eigenen Maschinencode gefüttert. Dabei wird der Maschinencode in einer Variablen auf dem Stack geschrieben und die Rücksprungadresse auf die Startadresse eines fremden Programmcodes gesetzt. Hat der fremde Maschinencode keinen Platz in der Variablen, kann auch der Heap verwendet werden. Beendet sich hierbei die Funktion, wird durch RET auf die Rücksprungadresse gesprungen, die Sie bereits manipuliert haben, und der Hacker kann nun bestimmte Codesequenzen ausführen. Ihnen dies jetzt zu demonstrieren, würde zum einen den Umfang des Kapitels bei Weitem sprengen und vor allem am Thema vorbeigehen. Zum anderen würde dies neben der gründlichen Kenntnis von C auch gute Kenntnisse im Assembler-Bereich (und unter Linux u. a. auch der Shell-Programmierung) erfordern. Zusammengefasst lassen sich Buffer Overflows für folgende Manipulationen ausnutzen: * Inhalte von Variablen, die auf dem Stack liegen, können verändert werden. Stellen Sie sich das einmal bei einer Funktion vor, die ein Passwort vom Anwender abfragt. * Die Rücksprungadresse wird manipuliert, sodass das Programm an einer beliebigen Stelle im Speicher mit der Maschinencodeausführung fortfährt. Meistens ist dies die Ausführung des vom Angreifer präparierten Codes. Für die Ausführung von fremdem Code werden wiederum die Variablen auf dem Stack, eventuell auch auf dem Heap verwendet. * Dasselbe Schema lässt sich auch mit Zeigern auf Funktionen anwenden. Dabei ist theoretisch nicht einmal ein Buffer-Overflow erforderlich, sondern es reicht die Speicheradresse, an der sich diese Funktion befindet. Die Daten, die für die Ausführung von fremdem Code nötig sind, werden vorzugsweise wieder in einer Variablen gespeichert. ### 27.1.4 GegenmaÃnahmen zum Buffer-Overflow während der Programmerstellung Steht Ihr Projekt in den Startlöchern, haben Sie Glück. Wenn Sie diesen Abschnitt durchgelesen haben, ist die Gefahr recht gering, dass Sie während der Programmerstellung eine unsichere Funktion implementieren. Die meisten Buffer Overflows werden mit den Funktionen der Standard-Bibliothek erzeugt. Das Hauptproblem dieser unsicheren Funktionen ist, dass keine Längenüberprüfung der Ein- bzw. Ausgabe vorhanden ist. Daher wird empfohlen, sofern diese Funktionen auf dem System vorhanden sind, alternative Funktionen zu verwenden, die diese Längenüberprüfung durchführen. Falls es in Ihrem Programm auf Performance ankommt, muss jedoch erwähnt werden, dass die Funktionen mit der n-Alternative (etwa strcpy -> strncpy) langsamer sind als die ohne. Hierzu folgt ein Ãberblick zu anfälligen Funktionen und geeigneten GegenmaÃnahmen, die getroffen werden können. # Unsicheres Einlesen von Eingabestreams # Unsichere Funktionen zur Stringbearbeitung # Unsichere Funktionen zur Bildschirmausgabe # Weitere unsichere Funktionen im Ãberblick Unsichere Funktion | Bemerkung | | --- | --- | | | | | Abhängig von Betriebssystem und Compiler gibt es noch eine Menge mehr solcher unsicherer Funktionen. Die wichtigsten wurden aber hier erwähnt. Generell sollte man immer alle printf()- und scanf()-Funktionen mit Vorsicht und Bedacht verwenden. Häufig lässt es sich hier beispielsweise wesentlich sicherer mit fwrite() oder fread() arbeiten, und die Konversion kann man dabei auch selbst machen. Wenigstens sollte man aber ein Frame um die »unsichereren« Funktionen bauen, die entsprechende Längenüberprüfungen durchführen, wie beispielsweise folgendes Listing zeigen soll: > /* check_before_sprintf.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 10 void check_bevore_sprintf(char *quelle, int max) { if(strlen(quelle) < MAX) return; else abort(); /* abort zum Debugger */ } int main(void) { char *ptr1 = "123456789"; char *ptr2 = "1234567890"; char string[MAX]; check_bevore_sprintf(ptr1, MAX); sprintf(string, "%s", ptr1); printf("string: %s\n", string); /* Boom!!! */ check_bevore_sprintf(ptr2, MAX); sprintf(string, "%s", ptr2); printf("string: %s\n", string); return EXIT_SUCCESS; } Einige Programmierer gehen sogar so weit, dass sie alle printf- und scanf-Funktionen aus ihren fertigen Programmen verbannen. Diese Entwickler scheuen auch nicht die Arbeit, hierzu eigene Funktionen (bzw. eine Bibliothek) zu schreiben, die die Benutzereingaben oder Eingabedatei scannen. ### 27.1.5 GegenmaÃnahmen zum Buffer-Overflow, wenn das Programm fertig ist Wenn das Programm bereits fertig ist, und Sie es noch nicht der Ãffentlichkeit zugänglich gemacht haben, können Sie sich die Suchen-Funktion des Compilers zunutze machen oder eine eigene Funktion schreiben. Im Folgenden sehen Sie einen solchen Ansatz. Das Listing gibt alle gefährlichen Funktionen, die in der Stringtabelle danger eingetragen sind, auf dem Bildschirm aus. > /* danger.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 255 char *danger[] = { "scanf", "sscanf", "fscanf", "gets", "strcat", "strcpy", "printf", "fprintf", "sprintf", "vsprintf", "system", NULL /* usw. */ }; int main(int argc, char **argv) { FILE *fp; char puffer[MAX]; int i, line=1; if(argc < 2) { printf("Anwendung: %s <datei.c>\n\n", argv[0]); return EXIT_FAILURE; } if ( (fp=fopen(argv[1], "r+")) == NULL) { printf("Konnte Datei nicht zum Lesen oeffnen\n"); return EXIT_FAILURE; } while( (fgets(puffer, MAX, fp)) != NULL) { i=0; while(danger[i] != NULL) { if( (strstr(puffer,danger[i])) !=0 ) printf("%s gefunden in Zeile %d\n", danger[i],line); i++; } line++; } fclose(fp); return EXIT_SUCCESS; } Eine weitere Möglichkeit ist es, eine sogenannte Wrapper-Funktion zu schreiben. Eine Wrapper-Funktion können Sie sich als Strumpf vorstellen, den Sie einer anfälligen Funktion überziehen. Als Beispiel dient hier die Funktion gets(): > /* wrap_gets.c */ #include <stdio.h> #include <stdlib.h> #define MAX 10 /* Damit es keine Kollision mit gets aus stdio.h gibt. */ #define gets(c) Gets(c) void Gets(char *z) { int ch; int counter=0; while((ch=getchar()) != '\n') { z[counter++]=ch; if(counter >= MAX) break; } z[counter] = '\0'; /* Terminieren */ } int main(int argc, char **argv) { char puffer[MAX]; printf("Eingabe : "); gets(puffer); printf("puffer = %s\n",puffer); return EXIT_SUCCESS; } Zuerst musste vor dem Compiler-Lauf die Funktion gets() mit > #define gets(c) Gets(c) ausgeschaltet werden. Jetzt kann statt der echten gets()-Version die Wrapper-Funktion Gets() verwendet werden. Genauso kann dies bei den anderen gefährlichen Funktionen gemacht werden – beispielsweise mit der Funktion strcpy(): > /* wrap_strcpy.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 10 /* Damit es keine Kollision mit strcpy in string.h gibt */ #define strcpy Strcpy #define DEBUG /* #undef DEBUG */ void Strcpy(char *ziel, char *quelle) { int counter; #ifdef DEBUG /* DEBUG-INFO */ size_t size = strlen(quelle)+1; if( size > MAX ) printf("DEBUG-INFO: Pufferueberlaufversuch\n"); /* DEBUG-INFO Ende */ #endif for(counter=0; quelle[counter] != '\0' && counter < MAX-1; counter++) ziel[counter]=quelle[counter]; /* terminieren */ ziel[counter] = '\0'; } int main(int argc, char **argv) { char puffer[MAX]; strcpy(puffer, "0123456789012345678"); printf("puffer = %s\n",puffer); return EXIT_SUCCESS; } Hier wird zum Beispiel noch eine DEBUG-Info mit ausgegeben, falls dies erwünscht ist. Ansonsten muss einfach die Direktive undef auskommentiert werden. ### 27.1.6 Programme und Tools zum Buffer-Overflow Es gibt z. B. auf dem Linux-Sektor zwei gute Bibliotheken, StackShield und StackGuard. Beide Bibliotheken arbeiten etwa nach demselben Prinzip. Beim Aufruf einer Funktion greifen diese Bibliotheken ein und sichern die Rücksprungadresse. Dafür wird natürlich ein extra Code am Anfang und Ende des Funktionsaufrufs eingefügt. Wird hierbei versucht, die Rücksprungadresse zu manipulieren, schreibt das Programm eine Warnung in das Syslog des Systems und beendet sich. Die Voraussetzung dafür, dass Sie eine der beiden Bibliotheken verwenden können, ist, dass Sie im Besitz des Quellcodes des Programms sind, das Sie vor einem Buffer-Overflow schützen wollen. Denn das Programm muss mit den Bibliotheken von StackShield und StackGuard neu übersetzt werden. Einen anderen Weg geht die Bibliothek libsafe. Sie entfernt gefährliche Funktionsaufrufe und ersetzt sie durch sichere Versionen. Diese besitzen zusätzlich noch einen Schutz vor dem Ãberschreiben des Stack-Frames. Firmen mit einem etwas gröÃeren Geldbeutel sei das Programm Insure++ von Parasoft ans Herz gelegt. Das Programm lässt sich als Testversion einige Zeit kostenlos ausprobieren. Der Anschaffungspreis rechnet sich im Laufe der Zeit allemal. Das Programm ist für alle gängigen Systeme erhältlich und kann auÃer dem Buffer-Overflow noch eine Menge weiterer Fehler aufdecken. Einige davon sind: * Speicherfehler * Speicherlecks * Speicherreservierungsfehler * Verwendung uninitialisierter Variablen * falsche Variablendefinitionen * Zeigerfehler * Bibliothekenfehler * logische Fehler ### 27.1.7 Ausblick Buffer Overflows werden wohl in Zukunft noch vielen Programmierern Probleme bereiten und noch länger eines der häufigsten Angriffsziele von Hackern darstellen. Daher lohnt es, sich mit diesem Thema zu befassen. Es wird wohl noch eine Generation dauern, bis Betriebssysteme auf den Markt kommen, die solche Probleme von selbst erkennen und ausgrenzen. Erste Ansätze dazu gibt es zwar schon (Solaris), aber clevere Programmierer haben bereits einen Weg gefunden, auch diese auszuhebeln. Nun haben Sie das Buch gelesen und überlegen sich, wie Sie jetzt wohl weitermachen können. Ein paar Tipps dazu kann ich Ihnen auf den folgenden Seiten geben. Wenn Sie das Buch ganz gelesen und durchgearbeitet haben, können Sie sich jetzt als fortgeschrittenen Programmierer in C bezeichnen. Der Weg zum Guru ist also nicht mehr weit. Mit der Sprache C haben Sie sich die allgemeinen Grundlagen der Programmierung angeeignet, doch was kommt jetzt? Mit C allein wird wohl kaum jemand noch seinen Lebensunterhalt verdienen. Gewöhnlich gehen Programmierer im Anschluss folgende Wege: * Sie steigen in die Systemprogrammierung von Linux oder Windows ein (besonders Wissensdurstige können natürlich auch gleich mit beiden Systemen anfangen). Dabei wird vorausgesetzt, dass Sie die Sprache C beherrschen (dies dürfte nach der Lektüre dieses Buches kein Problem mehr sein) und dass Sie sich mit dem entsprechenden Betriebssystem auskennen. Sofern Sie ein Linux-Fetischist sind, kann ich Ihnen mein aktuelles Buch »Linux-UNIX-Programmierung« empfehlen. * Sie lernen C++. Um mit der Programmiersprache C++ anzufangen, kann es (entgegen einiger anderer Meinungen) von Vorteil sein, dass Sie die Sprache C bereits beherrschen. Es ist aber nicht unbedingt notwendig. C++ kann auch unabhängig von C erlernt werden. Als Einstieg könnte ich Ihnen mein Buch »C++ von A bis Z« empfehlen, das ebenfalls beim Rheinwerk Verlag erschienen ist. ## 28.1 GUI-Programmierung – grafische Oberflächen Da Ihnen nach diesem Buch nun Tür und Tor offen stehen, werden sich einige Programmierer auch gern einmal an die »grafische« Programmierung heranwagen wollen, was ohne Weiteres zu empfehlen ist. Allerdings ist aller Anfang auch hier schwer. »Schwer« ist hierbei nicht die Verwendung einer entsprechenden Bibliothek, sondern eher den Ãberblick zu wahren bzw. den Einstieg zu finden. Bevor Sie sich an die »grafische« Programmierung heranwagen, sollten Sie erst mal überdenken, welche Art von »grafischer« Programmierung Sie einsetzen wollen. Generell unterscheide ich hierbei drei verschiedene Arten der »grafischen« Programmierung. ### 28.1.1 Low-Level-Grafikprogrammierung Damit bezeichne ich die tiefste Ebene der »grafischen« Programmierung. Hierbei müssen Sie sich um alle Details selbst kümmern. Sie wollen praktisch jeden Punkt, jede Linie und jedes kleine Detail (genauer die Grafik-Primitiven) selbst zeichnen. Gewöhnlich greifen Sie dabei auf die systemnächste Grafikschnittstelle des Betriebssystems zu. Unter MS-Windows wäre dies die Win32-API, und unter Linux/UNIX ist es die Xlib (auch als X11 bekannt). Fast alle höheren Grafik-Bibliotheken bauen auf dieser Ebene auf. Häufig wird hierbei als Programmiersprache C verwendet. Sehr gut geeignet ist diese systemnahe Grafikschnittstelle zum Entwickeln einer eigenen Spiele-Bibliothek oder eines Windowmanagers, mit dem Sie Ihrer Oberfläche ein eigenes Look & Feel verpassen können (beispielsweise KDE oder GNOME unter Linux). Der Nachteil, wenn Sie diese niedrige Ebene verwenden, ist eine sehr lange Einarbeitungszeit sowie langer und komplizierter Quellcode. AuÃerdem sind gute Mathematikkenntnisse erforderlich, und die Programmierung ist systemabhängig. Die Low-Level-Grafikprogrammierung ist also für Anfänger nur bedingt geeignet. Natürlich haben Sie hiermit den Vorteil, dass Sie eine eigene schlanke Bibliothek entwickeln können, die Ihren Vorstellungen entspricht. Des Weiteren lernen Sie dabei, wie grafische Oberflächen aufgebaut sind, was Ihnen auf jeden Fall zu einem besseren Verständnis beim Verwenden einer anderen grafischen Bibliothek verhilft. Dabei werden Sie feststellen, dass das Prinzip einer grafischen Bibliothek immer dasselbe bleibt. ### 28.1.2 High-Level-Grafikprogrammierung Alle Grafikbibliotheken der höheren Ebene basieren meistens auf der niedrigeren Ebene (Win32 bzw. X11). Bei solchen Bibliotheken können Sie vieles mit lediglich einem Funktionsaufruf erledigen. Alle unangenehmen Arbeiten werden Ihnen abgenommen. Häufig wird dabei auch Systemabhängiges versteckt bzw. eine Cross-Plattform-Bibliothek dafür angeboten. Damit lassen sich viele Bibliotheken der höheren Ebene auch auf mehreren Systemen verwenden. Vorwiegend werden solche Bibliotheken verwendet, um die auf dem System basierenden typischen Look&Feel-Anwendungen wie »Outlook« bzw. »Kmail« zu entwickeln – also typische fensterbasierende Anwendungen. Hierbei ist die Programmiersprache nicht mehr von primärer Bedeutung, da es häufig Schnittstellen für mehrere Sprachen gibt (für C bzw. C++ gibt es generell immer eine Schnittstelle). Meistens wird einer solchen Bibliothek auch eine Dokumentation mitgegeben, womit die Einarbeitung wesentlich leichter fällt. Bekannte Beispiele für eine solche Bibliothek wären unter MS-Windows MFC (Microsoft Foundation Classes), eine objektorientierte Version der Win32-API, und OWL, die Borland-Alternative zu MFC. Unter MS-Windows gibt es eine Menge freier Bibliotheken zur High-Level-Grafikprogrammierung (beispielsweise GTK+, Qt usw.). Unter Linux werden vorwiegend die Bibliotheken GTK+ und die GNOME-Lib (für GNOME) oder Qt für den KDE-Desktop verwendet. Allerdings gibt es auch hier eine Menge Alternativen. Der Nachteil von solchen höheren Bibliotheken ist, dass die Anwendungen manchmal etwas »fett« werden und eine Menge unnötigen Ballast mit sich herumtragen. Allerdings überwiegt der Vorteil, dass das Erstellen einer Anwendung wesentlich schneller und komfortabler von der Hand geht (ein wenig Einarbeitungszeit vorausgesetzt). Voraussetzung ist allerdings immer, dass sich der Programmierer mit seinem Werkzeug (besonders mit dem Compiler und Linker) auskennt. Dies ist beispielsweise nicht gegeben, wenn er schon daran scheitert, eine einfachste (Hallo-Welt-)Anwendung mit dieser Bibliothek zu übersetzen. # RAD-Tools Noch einfacher wird es dem Programmierer mit sogenannten RAD-Tools (Rapid Application Development) oder auch GUI-Designern gemacht. Hierbei ist es fast möglich, ohne Programmierkenntnisse eine grafische Anwendung zusammenzuklicken. Die GTK+-Bibliothek bietet beispielsweise mit GLADE ein solches Tool an. In den meisten C#-Compilern ist ebenfalls ein solches Tool vorhanden. Zwar werden die RAD-Tools immer besser und nehmen dem Programmierer eine Menge Arbeit ab, aber wenn es um Details geht, sind weiterhin Programmierkenntnisse notwendig. Ein Mix aus beidem (RAD-Tool und dem Programmieren »von Hand«) führt wohl zum besten Ergebnis. ### 28.1.3 Multimedia-Grafikprogrammierung Ebenfalls basierend auf der niedrigen Ebene sind sogenannte Multimedia-Bibliotheken aufgebaut. Multimedia-Bibliotheken werden vorwiegend zur Programmierung von Spielen, Demos aber auch in der Filmindustrie zum Einfügen von Spezialeffekten verwendet. Bei diesen Bibliotheken werden dem Programmierer eine Menge Arbeiten abgenommen – und vieles lässt sich mit einem Funktionsaufruf realisieren. Auch bei diesen Bibliotheken gibt es einige »systemunabhängige« Vertreter wie beispielsweise OpenGL, Allegro oder SDL, die auf vielen Plattformen vorhanden sind. Die Programmiersprache ist nicht unbedingt von Bedeutung, da es häufig die eine oder andere Schnittstelle zu anderen Sprachen gibt, aber in der Praxis werden die meisten Spiele, Demos bzw. Multimedia-Anwendungen in C/C++ erstellt. Viele dieser Bibliotheken sind sehr gut dokumentiert, und es sind häufig auch eine Menge Quellcodes und Demos zum Studieren vorhanden. Zu DirectX (dem »Platzhirsch«, mit dem sehr viele (aber nicht nur) Spiele programmiert werden) gibt es mittlerweile eine Menge deutschsprachiger Literatur, weshalb hier der Einstieg besonders leicht fällt. Allerdings ist DirectX eine Microsoft-eigene Bibliothek und eben nur unter diesem System ausführbar. Voraussetzungen für die Multimedia-Programmierung sind sehr gute Mathematikkenntnisse (lineare Algebra), räumliches Denken (sofern Sie sich für die 3D-Programmierung interessieren) und sehr viel Zeit;-). Wie es sich für ein anständiges Buch gehört, finden Sie hier im Anhang einige Tabellen und Auflistungen wie die Rangfolge der Operatoren, eine ASCII-Code-Tabelle, reservierte Schlüsselwörter in C und die Standard-Headerdateien. ## A.1 Rangfolge der Operatoren In der folgenden Tabelle werden die Operatoren von C und ihre Assoziativität (die Bindung der Operanden) in absteigender Reihenfolge aufgelistet. Operatoren derselben Prioritätsklasse haben dieselbe Rangstufe. Operator | Bedeutung/Name | Assoziativität | | --- | --- | --- | 1. Priorität | | | | | | | | | | | | | | 2. Priorität | | | | | | | | | | | | | | | | | | | | | | 3. Priorität | | | | | | | | 4. Priorität | | | | | | 5. Priorität | | | | | | 6. Priorität | | | | | | | | | | 7. Priorität | | | | | | 8. Priorität | | | | 9. Priorität | | | | 10. Priorität | | | | 11. Priorität | | | | 12. Priorität | | | | 13. Priorität | | | | 14. Priorität | | | | | | | | 15. Priorität | | | | In diesem Kapitel finden Sie eine Ãbersicht zu allen Funktionen der C-Standard-Bibliothek, alphabetisch sortiert nach den Headerdateien. Hierbei wird auch wieder die aktuelle C99-Syntax mit den restrict-Zeigern verwendet. 1989 wurde der Standard zum ersten Mal veröffentlicht, weshalb auch hierbei vom C89-Standard die Rede ist. Teil des ANSI-C-Standards sind die Software-Bibliotheken (besser bekannt unter dem Begriff ANSI C Standard Library). ## B.1 <assert.hIn <assert.h> ist nur das Funktionsmakro assert() definiert: > void assert( int expression ); Das Makro bewertet den Ausdruck expression und bricht das Programm mit einer Fehlermeldung auf stderr und der Funktion abort() ab, wenn das Ergebnis falsch (0) ist. Wenn Sie mit dem Testen des Programms fertig sind, müssen Sie lediglich vor dem Inkludieren von <assert.h> das Makro NDEBUG setzen, dann werden alle assert()-Aufrufe ignoriert. Stichwortverzeichnis ! ! (Operator) != (Operator) #define-Anweisung #elif-Anweisung #else-Anweisung #endif-Anweisung #error-Anweisung #ifdef-Anweisung #include-Anweisung #line-Anweisung #pragma-Anweisung #pragma pack #undef-Anweisung #undef-Anweisung % (Operator) %= (Operator) (type)Operator * (Operator) *= (Operator) + (Operator) ++ (Operator) += (Operator) - (Operator) -- (Operator) -= (Operator) -> (Operator) -> (Operator) . (Operator) / (Operator) /= (Operator) == (Operator) ?:(Operator) < (Operator) <= (Operator) <assert.h>-Headerdatei;Headerdatei <complex.h>-Headerdatei <complex.h>-Headerdatei <ctype.h>-Headerdatei <errno.h>-Headerdatei <fenv.h>-Headerdatei <float.h>-Headerdatei <inttypes.h>-Headerdatei <inttypes.h>-Headerdatei <iso646.h>-Headerdatei (C 99) <limits.h>-Headerdatei <locale.h>-Headerdatei;Headerdatei <math.h>-Headerdatei <setjmp.h>-Headerdatei;Headerdatei <signal.h>-Headerdatei;Headerdatei <stdarg.h>-Headerdatei;Headerdatei <stdbool.h>-Headerdatei <stdint.h>-Headerdatei (C 99) <stdio.h>-Headerdatei;Headerdatei <stdlib.h>-Headerdatei;Headerdatei <string.h>-Headerdatei;Headerdatei <string.h>-Headerdatei;Headerdatei <sys/stat.h>-Headerdatei;Headerdatei <sys/stat.h>-Headerdatei;Headerdatei <tgmath.h>-Headerdatei <tgmath.h>-Headerdatei <time.h>-Headerdatei;Headerdatei <wchar.h>-Headerdatei <wchar.h>-Headerdatei << (Operator) > (Operator) >= (Operator) >> (Operator) ^ (Operator) _Complex _exit() _IOFBF _IOLBF _IONBF __attribut__ __cplusplus Makro __DATE__ Makro __FILE__ __FILE__ Makro __func__ (C99) __LINE__ __LINE__ Makro __STDC__ Makro __STD_HOSTED__ (C 99) __STD_VERSION__ (C 99) __TIME__ Makro __VA_ARGS__ | (Operator) || (Operator) ~ (Operator) A Abnormale Programmbeendigung abort() abort() abs() Absolutwert Absolutwert Absolutwert accept() access() acos() Adressoperator Adressoperator AF_BLUETOOTH AF_INET AF_INET6 AF_IRDA AF_UNIX Algorithmen alloca() ALTER TABLE and and and_eq ANSI ANSI–C-Standard, C89-Standard ANSI–C-Standard, C99-Standard Anweisungsblock Anweisungsblock Apache Webserver Apache Webserver, htdocs-Verzeichnis Apache Webserver, installieren Arcuscosinus Arcussinus Arcustangens Arcustangens Array, Anzahl der Elemente ermitteln Array, Bereichsüberschreitung Array, deklarieren Array, dynamisch Array, dynamisch Array, Funktionsübergabe Array, Funktionsübergabe als Kopie Array, Gültigkeitsbereich Array, Indizierungsoperator Array, Initialisierung und Zugriff Array, mehrdimensional Array, mehrdimensional Array, Rückgabe aus Funktion Array, Strukturen Array, Vergleichen Array, von Tastatur einlesen Array und Zeiger Array und Zeiger Array und Zeiger ASCII-Zeichensatz asctime() asin() assert() atan() atan2() atexit() atof() atoi() atol() Attribute einer Datei Aufzählungstyp, enum Ausgeglichener Binärbaum auto AVL-Baum B Bäume B-Baum Backtracking Basisdatentyp, Definition Basisdatentyp, Deklaration Bedingte Kompilierung Bedingung, else Bedingung, else if Bedingung, if Bedingungsoperator Begrenzer Begrenzer, geschweifte Klammern Begrenzer, Gleichheitszeichen (=) Begrenzer, Komma (,) Begrenzer, Semikolon (;) Bezeichner Bezeichner Big Endian Bildschirm löschen Binäre Bäume Binäre Bäume, Ast, Kante Binäre Bäume, ausgleichen Binäre Bäume, AVL-Baum Binäre Bäume, B-Baum Binäre Bäume, Blatt Binäre Bäume, Elternzeiger Binäre Bäume, entartet Binäre Bäume, Knoten Binäre Bäume, Teilbaum Binäre Bäume, Threads Binäre Bäume, Tiefe Binäre Bäume, Wurzel Binäre Suche bind() bitand Bitfelder Bitfelder, anonym Bitmanipulationen, Bits abfragen Bitmanipulationen, Bits löschen Bitmanipulationen, Bits setzen bitor Bitweise Operatoren Blockweise (binär), lesen Blockweise (binär), schreiben Boyer-Moore-Algorithmus braces break Breitzeichen Breitzeichen bsearch() Bubble Sort Buffer Overflow Buffer Overflow, anfällige Funktionen Buffer Overflow, fgets() Buffer Overflow, GegenmaÃnahmen Buffer Overflow, gets() Buffer Overflow, gets() Buffer Overflow, printf() Buffer Overflow, printf() Buffer Overflow, Programme und Tools Buffer Overflow, scanf() Buffer Overflow, scanf() Buffer Overflow, sprintf() Buffer Overflow, strcat() Buffer Overflow, strcat() Buffer Overflow, strcpy() Buffer Overflow, strcpy() Buffer Overflow, strcpy() Buffer Overflow, Wrapper-Funktion BUFSIZ Byte Stream C C-API, MySQL C1x C89-Standard cabs() cacos() call-by-reference call-by-reference call-by-value calloc() carg() casin() casinh() Casting catan() ccos() ccosh() ccosh() cexp() CGI CGI, Anwendung ausführen CGI, Anwendung erstellen CGI, Ausgabe CGI, CGI-Schnittstelle CGI, CGI-Schnittstelle CGI, CONTENT_LENGTH CGI, Eingabe CGI, Eingabe dekodieren CGI, Eingabe parsen CGI, Filehandle CGI, Formular-Tags CGI, Gästebuch CGI, GET-Methode CGI, GET-Methode CGI, getenv() CGI, HTTP-Protokoll CGI, HTTP Request CGI, Methode auswerten CGI, mit der MySQL-C-API CGI, POST-Methode CGI, POST-Methode CGI, Query-String CGI, QUERY_STRING CGI, Request Header CGI, Server Response CGI, Statuscode CGI, Umgebungsvariablen CGI, Zugriffsrechte char CHAR_BIT CHAR_MAX CHAR_MIN chdir() cimag() clock() clock() CLOCKS_PER_SEC CLOCKS_PER_SEC clock_t clog() close() close() closedir() closesocket() clrearerr() clrscr() compl complex conj() connect() const continue copysign() cos() cosh() cosh() Cosinus cpow() cproj() creal() creat() CREATE DATABASE CREATE TABLE Cross-Plattform-Entwicklung Cross-Plattform-Entwicklung, Abstraktion Layer csin() csinh() csqrt() CSV-Datei CSV-Datei ctan() ctanh() ctanh() ctime() curly brackets D Datei Datei, öffnen Datei, öffnen Datei, öffnen Datei, öffnen (Low Level) Datei, Attribute Datei, Binärmodus Datei, Eigentümer Datei, EOF-Flag Datei, erstellen (Low Level) Datei, erstellen (Low Level) Datei, Fehler-Flag Datei, GröÃe Datei, Gruppeneigentümer Datei, Inode-Ãnderung Datei, löschen Datei, Lesen (blockweise, binär) Datei, Lesen (formatiert) Datei, Lesen (Low Level) Datei, Lesen einer Zeile Datei, Lesen eines Zeichens Datei, Lesen eines Zeichens Datei, neu anlegen Datei, positionieren Datei, positionieren Datei, positionieren (Low Level) Datei, Pufferung Datei, Pufferung Datei, schlieÃen Datei, schlieÃen (Low Level) Datei, schreiben (blockweise, binär) Datei, schreiben (formatiert) Datei, schreiben (Low Level) Datei, schreiben einer Zeile Datei, schreiben eines Zeichens Datei, schreiben eines Zeichens Datei, temporäre Datei, Textmodus Datei, umbenennen Datei, Zugriffsrechte Datei, Zugriffsrechte Datei, Zugriffsrechte Datei, Zugriffszeit Dateiarten Dateiarten, st_mode Dateiarten, S_IFCHR Dateiarten, S_IFDIR Dateiarten, S_IFREG Dateiarten, S_ISBLK Dateiarten, S_ISFIFO Dateiarten, S_ISLINK Dateiarten, S_ISSOCK Datenbanksystem Datenbanksystem, relationales Modell Datentyp, char Datentyp, double Datentyp, float Datentyp, int Datentyp, long Datentyp, long double Datentyp, short Datum Datum, tm-Struktur DBL_DIG DBL_EPSILON DBL_MANT_DIG DBL_MAX DBL_MAX_10_EXP DBL_MAX_EXP DBL_MIN DBL_MIN_10_EXP DBL_MIN_EXP DBMS DBMS, Drei-Schichten-Modell Deadlock default DELETE FROM <NAME> Dereferenzierungsoperator Differenzen C und C++, sizeof-Operator difftime() dirent-Struktur div() div_t Domainname Doppelt verkettete Listen double im Detail do while-Schleife DROP DATABASE DROP TABLE Dynamische Arrays Dynamische Arrays, zweidimensional Dynamische Datenstrukturen Dynamische Speicherverwaltung E EDOM EILSEQ EILSEQ Ein-/Ausgabe-Funktionen, höhere Ebene Ein-/Ausgabe-Funktionen, niedrigere Ebene Einfach verkettete Listen Elementare Datentypen Elementkennzeichnungsoperator else-Bedingung else if-Bedingung Endlosschleife Entarteter Binärbaum Entwicklungsumgebung enum EOF EOF EOF ERANGE erf() erfc() errno exit() EXIT_FAILURE EXIT_SUCCESS exp() exp() exp2() EXPLAIN Exponentialfunktionen extern extern F fabs() fabs() Fakultät fclose() fdim() fdopen() FD_CLR() FD_ISSET() FD_SET() FD_ZERO() feclearexcept() fegetexceptflag() fegetround() Fehlerausgabe Fehlerausgabe, perror() Fehlerausgabe, strerror() feof() feraiseexcept() ferror() fesetexceptflag() fesetround() fetestexcept() FE_ALL_EXCEPT FE_DIVBYZERO FE_DOWNWARD FE_INEXACT FE_INVALID FE_OVERFLOW FE_TONEAREST FE_TOWARDZERO FE_UNDERFLOW FE_UPWARD fflush() fflush() fgetc() fgetpos() fgets() fgets() fgetwc() fgetws() Fibonacci-Zahlen File-Deskriptor FILE-Struktur fileno() FlieÃkommazahlen float im Detail floor() FLT_DIG FLT_EPSILON FLT_MANT_DIG FLT_MAX FLT_MAX_10_EXP FLT_MAX_EXP FLT_MIN FLT_MIN_10_EXP FLT_MIN_EXP FLT_RADIX fma() fmax() fmin() fmod() fopen() FOPEN_MAX FOPEN_MAX for-Schleife Formatierte Ausgabe, fprintf() Formatierte Ausgabe, printf() Formatierte Ausgabe, sprintf() Formatierte Ein-/Ausgabe Formatierte Ein-/Ausgabe, Umwandlungsvorgaben Formatierte Eingabe, fscanf() Formatierte Eingabe, scanf() Formatierte Eingabe, sscanf() Formatierungsanweisung Format String Exploits Formatstring von printf() Formular, Auswahlliste Formular, Beginn und Ende Formular, Checkbox Formular, Eingabefeld Formular, Passwort-Feld Formular, Radiobutton Formular, Reset-Button Formular, Submit-Button Formular, Textfeld fpclassify() fpos_t fprintf() fputc() fputs() fputwc() fputws() FP_INFINITE FP_NAN FP_NORMAL FP_SUBNORMAL FP_ZERO fread() free() free() free(), Makro Freispeicherverwaltung Freispeicherverwaltung, Best-Fit-Verfahren Freispeicherverwaltung, Buddy-Verfahren Freispeicherverwaltung, First-Fit-Verfahren Freispeicherverwaltung, Next-Fit-Verfahren Freispeicherverwaltung, Quick-Fit-Verfahren Freispeicherverwaltung, Worst-Fit-Verfahren freopen() frexp() fscanf() fseek() fsetpos() ftell() Funktion, Ãbergabe eines Arrays Funktion, Argument Funktion, Array als Rückgabewert Funktion, call-by-reference Funktion, call-by-value Funktion, Definition von Funktionen Funktion, Funktionsaufruf Funktion, Funktionsdeklaration Funktion, main() Funktion, Parameter Funktion, Rückgabewert Funktion, Rekursion Funktion, Speicherklassen Funktion, Speicherklassen Funktion, Struktur (call-by-reference) Funktion, Struktur (call-by-value) Funktion, Struktur als Rückgabewert Funktion, Vorwärtsdeklaration Funktion, Zeiger als Rückgabewert Funktionen, inline Funktionen, mehrdimensionale Arrays fwrite() G Gammafunktionen Ganzzahlen Ganzzahlen, char Ganzzahlen, int Ganzzahlen, long Ganzzahlen, short Ganzzahlkonstanten Geltungsbereich von Variablen Genauigkeit von Gleitpunktzahlen getc() getch() getchar() getcwd() getenv() getenv() gethostbyname() gets() getservbyname() getwc() getwchar() Gleitpunktkonstanten Gleitpunktzahlen, double Gleitpunktzahlen, float Gleitpunktzahlen, Genauigkeit Gleitpunktzahlen, long double Gleitpunktzahlen, numerische Gleitpunktprobleme Gleitpunktzahlen-Umgebung gmtime() goto GröÃe, Datei (st_size) GröÃter gemeinsamer Teiler GUI-Programmierung H Hashing Hashing, direkte Adressierung Hashing, Hash-Funktion Hashing, Hash-Funktion Hashing, Hash-Tabelle Hashing, von Strings Heap Heap Heap Hostname HTML HTML, Formular-Tags HTML, Tag htonl() htons() HTTP-Protokoll HTTP-Protokoll HUGE_VAL Hyperbolische Funktionen Hyperthreading hypot() I IEEE-Standard 754 if-Bedingung ilogb() imaxabs() imaxdiv() INADDR_ANY Indizierungsoperator Indizierungsoperator inline inline INSERT INTO Insertion Sort int intmax_t intmax_t intN_t intptr_t int_fastN_t int_leastN_t INT_MAX INT_MIN IP-Nummer IP-Nummer, dynamisch IP-Nummer, statisch IP-Protokoll IPv4 IPv6 isalnum() isalpha() isascii() isblank() iscntrl() isdigit() isfinite() isgraph() isgreater() isgreaterequal() isinf() isless() islessequal() islessgreater() islower() isnan() isnormal() isprint() ispunct() isspace() isunordered() isupper() iswalnum() iswalpha() iswblank() iswcntrl() iswctype() iswdigit() iswgraph() iswlower() iswprint() iswpunct() iswspace() iswupper() iswxdigit() isxdigit() itoa() J jmp_buf K Karp-Rabin-Algorithmus KMP-Algorithmus Kommandozeile Kommandozeile, Argumente Kommandozeile, Optionen Kommandozeilenprozessor Konstante Konstante, Betriebssystem Konstante, Compiler L labs() Laufzeitmessung lconv-Struktur LDBL_DIG LDBL_EPSILON LDBL_MANT_DIG LDBL_MAX LDBL_MAX_10_EXP LDBL_MAX_EXP LDBL_MIN LDBL_MIN_10_EXP LDBL_MIN_EXP ldexp() ldiv() ldiv_t lgamma() LIFO-Prinzip Lineare Suche Linksassoziativität listen() Literale Little-Endian LLONG_MAX LLONG_MIN llrint() llround() load_defaults() localeconv() localtime() log() log() log1p() log2() log10() Logarithmus Logarithmus logb() Logische Operatoren Logische Operatoren long long double long double longjmp() long long LONG_MAX LONG_MIN Loopback-Interface lrint() lround() lseek() M main() main()-Funktion MAKEWORD() Makro Makro malloc() malloc(), Typen-Casting Maschinencode Maximum mbstate_t MB_LEN_MAX memchr() memcmp() memcmp() memcpy() memmove() Memory Leak Memory Leak Memory Leak Memory Leak, Bibliotheken und Tools Memory Leak, GegenmaÃnahmen memset() memset() Minimum mkdir() mktime() modf() Modulo-Operator MSQL_UNIX_SOCKET Multibyte-Zeichen Multibyte-Zeichen MySQL MySQL, Befehle MySQL, Bibliothek MySQL, C-API MySQL, C-API MySQL, Datentypen MySQL, eigene Clientprogramme MySQL, Headerdateien MySQL, Installation MySQL, libmysql.dll MySQL, libmysql.dll MySQL, libmysql.lib MySQL, Server starten MySQL-C-API, Anfrage an den Server MySQL-C-API, CGI-Anwendung MySQL-C-API, Daten ausgeben MySQL-C-API, Datenbank auswählen MySQL-C-API, Daten hinzufügen MySQL-C-API, Daten hinzufügen MySQL-C-API, Daten löschen MySQL-C-API, Daten suchen MySQL-C-API, Daten suchen MySQL-C-API, Datentypen MySQL-C-API, Daten verändern MySQL-C-API, Daten vom Server holen MySQL-C-API, Fehlerüberprüfung MySQL-C-API, Feldwert ermitteln MySQL-C-API, Funktionsübersicht MySQL-C-API, Kommandozeilen-Argumente MySQL-C-API, MYSQL-Handle MySQL-C-API, MYSQL_FIELD-Struktur MySQL-C-API, MYSQL_RES-Struktur MySQL-C-API, Serverantwort auswerten MySQL-C-API, Verbindung herstellen MySQL-C-API, Verbindung schlieÃen MySQL-Clientprogramme, mit Borland-Compiler MySQL-Clientprogramme, mit gcc MySQL-Clientprogramme, mit Visual C++ MySQL-Clientprogramme, Probleme beim Erstellen mysql_affected_rows() mysql_affected_rows() mysql_change_user() mysql_character_set_name() mysql_close() mysql_close() mysql_connect() mysql_create_db() mysql_data_seek() mysql_debug() mysql_drop_db() mysql_dump_debug_info() mysql_eof() mysql_errno() mysql_errno() mysql_error() mysql_error() mysql_escape_string() mysql_fetch_field() mysql_fetch_field() mysql_fetch_fields() mysql_fetch_field_direct() mysql_fetch_lengths() mysql_fetch_row() mysql_fetch_row() mysql_field_count() mysql_field_seek() mysql_field_seek() mysql_field_tell() mysql_field_tell() mysql_free_result() mysql_free_result() mysql_get_client_info() mysql_get_host_info() mysql_get_proto_info() mysql_get_server_info() mysql_info() mysql_init() mysql_init() mysql_insert_id() mysql_kill() mysql_list_dbs() mysql_list_fields() mysql_list_processes() mysql_list_tables() mysql_num_fields() mysql_num_fields() mysql_num_rows() mysql_num_rows() mysql_options() mysql_ping() mysql_query() mysql_query() mysql_real_connect() mysql_real_connect() mysql_real_escape_string() mysql_real_query() mysql_real_query() mysql_real_query() mysql_reload() mysql_row_seek() mysql_row_tell() mysql_select_db() mysql_select_db() mysql_shutdown() mysql_stat() mysql_store_result() mysql_store_result() MYSQL_TCP_PORT mysql_thread_id() mysql_thread_safe() mysql_use_result() N Nameserver nan() NDEBUG nearbyint() NetBurst Netzwerkprogrammierung Netzwerkprogrammierung, Client/Server-Prinzip Netzwerkprogrammierung, Linux Netzwerkprogrammierung, Windows Netzwerktechnik Netzwerktechnik, Domainname Netzwerktechnik, Hostname Netzwerktechnik, IP-Nummer Netzwerktechnik, IP-Protokoll Netzwerktechnik, IPv4 Netzwerktechnik, IPv6 Netzwerktechnik, Loopback-Interface Netzwerktechnik, Nameserver Netzwerktechnik, OSI-Schichtmodell Netzwerktechnik, Portnummer Netzwerktechnik, Sockets Netzwerktechnik, TCP Netzwerktechnik, UDP nextafter() nexttoward() Normalverteilung not not Notationsstil not_eq ntohl() ntohs() NULL NULL NULL NULL O objdump ODBC-Schnittstelle offsetof-Makro Opcode open() opendir() OpenMP OPEN_MAX Operatoren, arithmetische Operatoren, bitweise Operatoren, Dekrement Operatoren, Inkrement Operatoren, logische Operatoren, Zuweisungs- or or or_eq O_APPEND O_BINARY O_CREAT O_EXCL O_NOCTTY O_NONBLOCK O_RDONLY O_RDWR O_SYNC O_TEXT O_TRUNC O_WRONLY P Paging Paralleles Rechnen Parameter, von main() Pattern Matching perror() Portabel, getch() Portabel, Verzeichnis ausgeben Portnummer POSIX-Thread-Bibliothek pow() Präprozessor Präprozessor-Direktiven, define Präprozessor-Direktiven, elif Präprozessor-Direktiven, else Präprozessor-Direktiven, endif Präprozessor-Direktiven, error Präprozessor-Direktiven, ifdef Präprozessor-Direktiven, include Präprozessor-Direktiven, line Präprozessor-Direktiven, pragma Präprozessor-Direktiven, undef printf() Profiler Profiler, gprof Programmbeendigung Programmbeendigung, abort() Programmbeendigung, atexit() Programmbeendigung, exit() Programmbeendigung, _exit() Prozess Pthreads pthread_cleanup_pop() pthread_cleanup_push() pthread_create() pthread_exit() pthread_join() pthread_t ptrdiff_t Pufferüberlauf Pufferung Pufferung, Einstellen Punktoperator putc() putchar() puts() putwc() putwchar() Q qsort() qsort() Quadratwurzel Queues Queues, get() Queues, put() Quicksort R Rückgabewert beim Beenden Rückgabewert von Funktionen Rückgabewert von main() Rücksprungadresse manipulieren raise() rand() RAND_MAX read() Read-only-Zeiger readdir() realloc() Rechtsassoziativität recv() recvfrom() register Reguläre Ausdrücke Rekursion Relationale Beziehung remainder() remove() remquo() rename() restrict return rewind() rewinddir() rint() rmdir() round() Rundungsfunktionen S scalbln() scalbn() scanf() SCHAR_MAX SCHAR_MIN Schlüsselwörter Schlüsselwörter, in C Schleife, do while Schleife, Endlosschleife Schleife, for Schleife, while seekdir() SEEK_CUR SEEK_CUR SEEK_END SEEK_END SEEK_SET SEEK_SET select() select(), FD_CLR() select(), FD_ISSET() select(), FD_SET() select(), FD_ZERO() SELECT ... FROM Selektion Sort send() sendto() setbuf() setjmp() setlocale() setvbuf() Shellsort Shellsort, Distanzfolgen short SHOW DATABASE SHOW TABLES SHRT_MAX SHRT_MIN Sicheres Programmieren Sicheres Programmieren, Buffer Overflow Sicheres Programmieren, Memory Leak Sicherheitsprobleme vermeiden signal() Signal, SIGABRT Signal, SIGABRT Signal, SIGFPE Signal, SIGILL Signal, SIGINT Signal, SIGINT Signal, SIGSEGV Signal, SIGTERM Signal, SIG_DFL Signal, SIG_ERR Signal, SIG_IGN Signalkonzept signed sin() sinh() sinh() Sinus sizeof-Operator sizeof-Operator sizeof-Operator size_t size_t snprintf() socket() Socketprogrammierung Socketprogrammierung, accept() Socketprogrammierung, Adresse festlegen (binden) Socketprogrammierung, bind() Socketprogrammierung, Client-Anwendung Socketprogrammierung, Client/Server-Anwendung Socketprogrammierung, Client/Server-Prinzip Socketprogrammierung, close() Socketprogrammierung, closesocket() Socketprogrammierung, connect() Socketprogrammierung, Daten empfangen Socketprogrammierung, Datenformate Socketprogrammierung, Daten senden Socketprogrammierung, gethostbyname() Socketprogrammierung, hostent Socketprogrammierung, htonl() Socketprogrammierung, htons() Socketprogrammierung, IPv4 nach IPv6 ändern Socketprogrammierung, Linux Socketprogrammierung, listen() Socketprogrammierung, mehrere Clients gleichzeitig Socketprogrammierung, ntohl() Socketprogrammierung, ntohs() Socketprogrammierung, Portabilität Socketprogrammierung, Puffer Socketprogrammierung, recv() Socketprogrammierung, recvfrom() Socketprogrammierung, RFC-Dokumente Socketprogrammierung, select() Socketprogrammierung, send() Socketprogrammierung, sendto() Socketprogrammierung, servent Socketprogrammierung, Server-Anwendung Socketprogrammierung, Serverhauptschleife Socketprogrammierung, Sicherheit Socketprogrammierung, sockaddr_in Socketprogrammierung, socket() Socketprogrammierung, Socket anlegen Socketprogrammierung, Socket freigeben Socketprogrammierung, TCP-Echo-Server Socketprogrammierung, Verbindung annehmen Socketprogrammierung, Verbindung herstellen Socketprogrammierung, Warteschlange einrichten Socketprogrammierung, Windows Sockets Sortieralgorithmus Sortieralgorithmus, analysieren Sortieralgorithmus, Bubble Sort Sortieralgorithmus, Insertion Sort Sortieralgorithmus, qsort() Sortieralgorithmus, Quicksort Sortieralgorithmus, Selektion Sort Sortieralgorithmus, Shellsort Sortieren Sortieren, qsort() Speicher allozieren, alloca() Speicher allozieren, calloc() Speicher allozieren, malloc() Speicher allozieren, realloc() Speicher freigeben, free() Speicher freigeben, free() Speicherhierarchie Speicherleck Speicherverwaltung sprintf() Sprung, longjmp() Sprung, setjmp() Sprunganweisung, break Sprunganweisung, continue SQL SQL, Befehle SQL, Crashkurs SQL, Daten abfragen SQL, Datenbank anlegen SQL, Datenbank ausgeben SQL, Datenbank auswählen SQL, Datenbank löschen SQL, Daten eingeben SQL, Daten löschen SQL, Datensatz SQL, Datentypen SQL, Daten verändern SQL, DDL-Anweisungen SQL, DML-Anweisungen SQL, SQL-Kommandos SQL, Tabelle anlegen SQL, Tabelle anzeigen SQL, Tabelle löschen SQL, Tabellen-Details SQL, Tabelle verändern sqrt() srand() sscanf() Stack Stack Stack Stack Stack, debuggen Stack, pop() Stack, push() Stack-Frame Stackrahmen Standard-Headerdateien Standard-Streams Standard-Streams, umleiten Startup-Code stat() stat-Struktur stat-Struktur, st_atime stat-Struktur, st_ctime stat-Struktur, st_dev stat-Struktur, st_gid stat-Struktur, st_ino stat-Struktur, st_mode stat-Struktur, st_mtime stat-Struktur, st_nlink stat-Struktur, st_rdev stat-Struktur, st_size stat-Struktur, st_uid static static STDC FENV_ACCESS stderr STDERR_FILENO stdin STDIN_FILENO stdout STDOUT_FILENO Steuerzeichen strcat() strchr() strcmp() strcpy() strcspn() Stream Stream Stream strerror() strftime() String, einlesen String, lesen (formatiert) String, Lesen einer Zeile String, reguläre Ausdrücke String, schreiben (formatiert) String, Schreiben einer Zeile String, Stringmatching String, umwandeln in numerischen Wert Stringende-Zeichen Stringkonstante Stringkonstante Stringmatching-Algorithmus Stringmatching-Algorithmus, Boyer-Moore-Algorithmus Stringmatching-Algorithmus, Brute Force Stringmatching-Algorithmus, Karp-Rabin-Algorithmus Stringmatching-Algorithmus, Knuth/Morris/Pratt-Algorithmus Stringmatching-Algorithmus, naiver Algorithmus Stringmatching-Algorithmus, reguläre Ausdrücke Strings Strings aneinander hängen, strcat() Strings aneinander hängen, strncat() Stringtabelle Stringtabelle strlen() strncmp() strncpy() strpbrk() strrchr() strspn() strstr() strtod() strtof() strtoimax() strtok() strtol() strtold() strtoll() strtoul() strtoumax() struct Struktur, an Funktion übergeben Struktur, Array Struktur, Attribute verändern Struktur, Bitfelder Struktur, deklarieren Struktur, Initialisierung und Zugriff Struktur, in Struktur Struktur, Lebensdauer Struktur, offsetof-Makro Struktur, Rückgabewert von Funktion Struktur, Union Struktur, vergleichen Strukturelemente Strukturen Suchalgorithmus Suchalgorithmus Suchalgorithmus, binärer Suchbaum Suchalgorithmus, binäre Suche Suchalgorithmus, binäre Suche Suchalgorithmus, Hashing Suchalgorithmus, lineare Suche Suchen Suchen, bsearch() Suchen in einem String, strchr() Suchen in einem String, strcspn() Suchen in einem String, strpbrk() Suchen in einem String, strrchr() Suchen in einem String, strspn() Suchen in einem String, strstr() switch-Anweisung Symbole Symbolische Konstante system() Systemprogrammierung S_IEXEC S_IREAD S_IREAD S_IRGRP S_IRGRP S_IROTH S_IROTH S_IRUSR S_IRUSR S_IRWXG S_IRWXO S_IRWXU S_ISGID S_ISUID S_ISVTX S_IWGRP S_IWGRP S_IWOTH S_IWOTH S_IWRITE S_IWRITE S_IWUSR S_IWUSR S_IXGRP S_IXGRP S_IXOTH S_IXOTH S_IXUSR S_IXUSR T tan() Tangens tanh() tanh() Tastatur-Puffer leeren TCP TCP-Echo-Server TCP-Echo-Server, Client TCP-Echo-Server, Server telldir() Temporäre Datei, mkstemp() Temporäre Datei, tmpfile() Temporäre Datei, tmpnam() tgamma() Tic Tac Toe time() time_t tm-Struktur tmpfile() tmpnam() TMP_MAX toascii() tolower() toupper() towctrans() towlower() towupper() Trial-and-Error-Prinzip Trigraph-Zeichen trunc() Typendefinition, typedef Typumwandlung, explizit Typumwandlung, implizit U UCHAR_MAX UDP UDP-Anwendung, Client UDP-Anwendung, Server uintmax_t uintmax_t uintN_t uintptr_t uint_fastN_t uint_leastN_t UINT_MAX ULLONG_MAX ULONG_MAX Umgebungsvariablen, getenv() Ungenauigkeit bei Gleitpunktzahlen ungetc() ungetwc() Unicode union UNIX unsigned UPDATE URL USE USHRT_MAX V Variable Argumentliste bei Funktionen Variablen, deklarieren Variablen, global Variablen, Lebensdauer Variablen, Lebensdauer Variablen, lokal Variablen, Speicherklassen Variablen, statisch Variablen, Typ-Qualifizierer Variadic Makro va_arg va_copy va_end va_list va_start Vergleichsoperatoren Verkettete Listen, doppelt Verkettete Listen, einfach Verkettete Listen, Queues Verkettete Listen, Stack Verzeichnis, Arbeits- Verzeichnis, erstellen Verzeichnis, Funktionen Verzeichnis, löschen Verzeichnis, lesen Verzeichnis, positionieren Verzeichnis, wechseln Verzeichnis, zum Lesen öffnen vfprintf() void void-Zeiger volatile volatile vprintf() vsnprintf() vsprintf() W Warteschlange WCHAR_MAX WCHAR_MIN wchar_t wchar_t wcsftime() wctrans() wctype() Webprogrammierung, clientseitig Webprogrammierung, serverseitig Webserver, Apache Webserver, HTTPD WEOF while-Schleife Whitespace Win32-Konsole Winsock Winsock, initialisieren wint_t wmemchr() wmemcmp() wmemcpy() wmemmove() wmemset() Wrapper-Funktion write() WSACleanup() WSAStartup() Wurzelfunktionen X xor xor_eq Z Zeichen Zeichen, lesen Zeichen, lesen Zeichen, lesen Zeichen, schreiben Zeichen, schreiben Zeichen, umwandeln in GroÃbuchstaben Zeichen, umwandeln in Kleinbuchstaben Zeichen, zurückschieben Zeichenkette Zeichenkette Zeichenklassifizierung Zeichenkonstanten Zeichensatz, Basic-Zeichensatz Zeichensatz, international Zeichensatz, national Zeichensatz, OEM Zeichensatz, Steuerzeichen Zeiger Zeiger, als Rückgabewert Zeiger, auf Funktionen Zeiger, call-by-reference Zeiger, deklarieren Zeiger, Dereferenzierung Zeiger, die auf andere Zeiger verweisen Zeiger, dynamisches Zeigerarray Zeiger, initialisieren Zeiger, NULL Zeiger, ptrdiff_t Zeiger, read-only Zeiger, restrict Zeiger, restrict Zeiger, SpeichergröÃe Zeiger, SpeichergröÃe Zeiger, void Zeigerarithmetik Zeiger auf Strings Zeiger auf Zeiger Zeiger und Array Zeiger und Array Zeiger und Array Zeilenweise lesen Zeilenweise lesen, bestimmte Zeile auslesen Zeilenweise lesen, newline entfernen Zeilenweise lesen, suchen nach Stringfolge Zeilenweise lesen, suchen nach Wörtern Zeilenweise lesen, suchen und ersetzen Zeilenweise lesen, von Zeile x bis y lesen Zeilenweise schreiben Zeit Zeit, tm-Struktur Zeit, Zeitraum berechnen Zeiten einer Datei Zeiten einer Datei, Inode-Ãnderung Zeiten einer Datei, Zugriffszeit Zufallszahlen, rand() Zufallszahlen, srand() Zugriffsrechte Zugriffsrechte Ihre Meinung Wie hat Ihnen das Openbook gefallen? Wir freuen uns immer über Ihre Rückmeldung. Schreiben Sie uns gerne Ihr Feedback als E-Mail an <EMAIL>. Stichwortverzeichnis ! ! (Operator) != (Operator) #define-Anweisung #elif-Anweisung #else-Anweisung #endif-Anweisung #error-Anweisung #ifdef-Anweisung #include-Anweisung #line-Anweisung #pragma-Anweisung #pragma pack #undef-Anweisung #undef-Anweisung % (Operator) %= (Operator) (type)Operator * (Operator) *= (Operator) + (Operator) ++ (Operator) += (Operator) - (Operator) -- (Operator) -= (Operator) -> (Operator) -> (Operator) . (Operator) / (Operator) /= (Operator) == (Operator) ?:(Operator) < (Operator) <= (Operator) <assert.h>-Headerdatei;Headerdatei <complex.h>-Headerdatei <complex.h>-Headerdatei <ctype.h>-Headerdatei <errno.h>-Headerdatei <fenv.h>-Headerdatei <float.h>-Headerdatei <inttypes.h>-Headerdatei <inttypes.h>-Headerdatei <iso646.h>-Headerdatei (C 99) <limits.h>-Headerdatei <locale.h>-Headerdatei;Headerdatei <math.h>-Headerdatei <setjmp.h>-Headerdatei;Headerdatei <signal.h>-Headerdatei;Headerdatei <stdarg.h>-Headerdatei;Headerdatei <stdbool.h>-Headerdatei <stdint.h>-Headerdatei (C 99) <stdio.h>-Headerdatei;Headerdatei <stdlib.h>-Headerdatei;Headerdatei <string.h>-Headerdatei;Headerdatei <string.h>-Headerdatei;Headerdatei <sys/stat.h>-Headerdatei;Headerdatei <sys/stat.h>-Headerdatei;Headerdatei <tgmath.h>-Headerdatei <tgmath.h>-Headerdatei <time.h>-Headerdatei;Headerdatei <wchar.h>-Headerdatei <wchar.h>-Headerdatei << (Operator) > (Operator) >= (Operator) >> (Operator) ^ (Operator) _Complex _exit() _IOFBF _IOLBF _IONBF __attribut__ __cplusplus Makro __DATE__ Makro __FILE__ __FILE__ Makro __func__ (C99) __LINE__ __LINE__ Makro __STDC__ Makro __STD_HOSTED__ (C 99) __STD_VERSION__ (C 99) __TIME__ Makro __VA_ARGS__ | (Operator) || (Operator) ~ (Operator) A Abnormale Programmbeendigung abort() abort() abs() Absolutwert Absolutwert Absolutwert accept() access() acos() Adressoperator Adressoperator AF_BLUETOOTH AF_INET AF_INET6 AF_IRDA AF_UNIX Algorithmen alloca() ALTER TABLE and and and_eq ANSI ANSI–C-Standard, C89-Standard ANSI–C-Standard, C99-Standard Anweisungsblock Anweisungsblock Apache Webserver Apache Webserver, htdocs-Verzeichnis Apache Webserver, installieren Arcuscosinus Arcussinus Arcustangens Arcustangens Array, Anzahl der Elemente ermitteln Array, Bereichsüberschreitung Array, deklarieren Array, dynamisch Array, dynamisch Array, Funktionsübergabe Array, Funktionsübergabe als Kopie Array, Gültigkeitsbereich Array, Indizierungsoperator Array, Initialisierung und Zugriff Array, mehrdimensional Array, mehrdimensional Array, Rückgabe aus Funktion Array, Strukturen Array, Vergleichen Array, von Tastatur einlesen Array und Zeiger Array und Zeiger Array und Zeiger ASCII-Zeichensatz asctime() asin() assert() atan() atan2() atexit() atof() atoi() atol() Attribute einer Datei Aufzählungstyp, enum Ausgeglichener Binärbaum auto AVL-Baum B Bäume B-Baum Backtracking Basisdatentyp, Definition Basisdatentyp, Deklaration Bedingte Kompilierung Bedingung, else Bedingung, else if Bedingung, if Bedingungsoperator Begrenzer Begrenzer, geschweifte Klammern Begrenzer, Gleichheitszeichen (=) Begrenzer, Komma (,) Begrenzer, Semikolon (;) Bezeichner Bezeichner Big Endian Bildschirm löschen Binäre Bäume Binäre Bäume, Ast, Kante Binäre Bäume, ausgleichen Binäre Bäume, AVL-Baum Binäre Bäume, B-Baum Binäre Bäume, Blatt Binäre Bäume, Elternzeiger Binäre Bäume, entartet Binäre Bäume, Knoten Binäre Bäume, Teilbaum Binäre Bäume, Threads Binäre Bäume, Tiefe Binäre Bäume, Wurzel Binäre Suche bind() bitand Bitfelder Bitfelder, anonym Bitmanipulationen, Bits abfragen Bitmanipulationen, Bits löschen Bitmanipulationen, Bits setzen bitor Bitweise Operatoren Blockweise (binär), lesen Blockweise (binär), schreiben Boyer-Moore-Algorithmus braces break Breitzeichen Breitzeichen bsearch() Bubble Sort Buffer Overflow Buffer Overflow, anfällige Funktionen Buffer Overflow, fgets() Buffer Overflow, GegenmaÃnahmen Buffer Overflow, gets() Buffer Overflow, gets() Buffer Overflow, printf() Buffer Overflow, printf() Buffer Overflow, Programme und Tools Buffer Overflow, scanf() Buffer Overflow, scanf() Buffer Overflow, sprintf() Buffer Overflow, strcat() Buffer Overflow, strcat() Buffer Overflow, strcpy() Buffer Overflow, strcpy() Buffer Overflow, strcpy() Buffer Overflow, Wrapper-Funktion BUFSIZ Byte Stream C C-API, MySQL C1x C89-Standard cabs() cacos() call-by-reference call-by-reference call-by-value calloc() carg() casin() casinh() Casting catan() ccos() ccosh() ccosh() cexp() CGI CGI, Anwendung ausführen CGI, Anwendung erstellen CGI, Ausgabe CGI, CGI-Schnittstelle CGI, CGI-Schnittstelle CGI, CONTENT_LENGTH CGI, Eingabe CGI, Eingabe dekodieren CGI, Eingabe parsen CGI, Filehandle CGI, Formular-Tags CGI, Gästebuch CGI, GET-Methode CGI, GET-Methode CGI, getenv() CGI, HTTP-Protokoll CGI, HTTP Request CGI, Methode auswerten CGI, mit der MySQL-C-API CGI, POST-Methode CGI, POST-Methode CGI, Query-String CGI, QUERY_STRING CGI, Request Header CGI, Server Response CGI, Statuscode CGI, Umgebungsvariablen CGI, Zugriffsrechte char CHAR_BIT CHAR_MAX CHAR_MIN chdir() cimag() clock() clock() CLOCKS_PER_SEC CLOCKS_PER_SEC clock_t clog() close() close() closedir() closesocket() clrearerr() clrscr() compl complex conj() connect() const continue copysign() cos() cosh() cosh() Cosinus cpow() cproj() creal() creat() CREATE DATABASE CREATE TABLE Cross-Plattform-Entwicklung Cross-Plattform-Entwicklung, Abstraktion Layer csin() csinh() csqrt() CSV-Datei CSV-Datei ctan() ctanh() ctanh() ctime() curly brackets D Datei Datei, öffnen Datei, öffnen Datei, öffnen Datei, öffnen (Low Level) Datei, Attribute Datei, Binärmodus Datei, Eigentümer Datei, EOF-Flag Datei, erstellen (Low Level) Datei, erstellen (Low Level) Datei, Fehler-Flag Datei, GröÃe Datei, Gruppeneigentümer Datei, Inode-Ãnderung Datei, löschen Datei, Lesen (blockweise, binär) Datei, Lesen (formatiert) Datei, Lesen (Low Level) Datei, Lesen einer Zeile Datei, Lesen eines Zeichens Datei, Lesen eines Zeichens Datei, neu anlegen Datei, positionieren Datei, positionieren Datei, positionieren (Low Level) Datei, Pufferung Datei, Pufferung Datei, schlieÃen Datei, schlieÃen (Low Level) Datei, schreiben (blockweise, binär) Datei, schreiben (formatiert) Datei, schreiben (Low Level) Datei, schreiben einer Zeile Datei, schreiben eines Zeichens Datei, schreiben eines Zeichens Datei, temporäre Datei, Textmodus Datei, umbenennen Datei, Zugriffsrechte Datei, Zugriffsrechte Datei, Zugriffsrechte Datei, Zugriffszeit Dateiarten Dateiarten, st_mode Dateiarten, S_IFCHR Dateiarten, S_IFDIR Dateiarten, S_IFREG Dateiarten, S_ISBLK Dateiarten, S_ISFIFO Dateiarten, S_ISLINK Dateiarten, S_ISSOCK Datenbanksystem Datenbanksystem, relationales Modell Datentyp, char Datentyp, double Datentyp, float Datentyp, int Datentyp, long Datentyp, long double Datentyp, short Datum Datum, tm-Struktur DBL_DIG DBL_EPSILON DBL_MANT_DIG DBL_MAX DBL_MAX_10_EXP DBL_MAX_EXP DBL_MIN DBL_MIN_10_EXP DBL_MIN_EXP DBMS DBMS, Drei-Schichten-Modell Deadlock default DELETE FROM <NAME> Dereferenzierungsoperator Differenzen C und C++, sizeof-Operator difftime() dirent-Struktur div() div_t Domainname Doppelt verkettete Listen double im Detail do while-Schleife DROP DATABASE DROP TABLE Dynamische Arrays Dynamische Arrays, zweidimensional Dynamische Datenstrukturen Dynamische Speicherverwaltung E EDOM EILSEQ EILSEQ Ein-/Ausgabe-Funktionen, höhere Ebene Ein-/Ausgabe-Funktionen, niedrigere Ebene Einfach verkettete Listen Elementare Datentypen Elementkennzeichnungsoperator else-Bedingung else if-Bedingung Endlosschleife Entarteter Binärbaum Entwicklungsumgebung enum EOF EOF EOF ERANGE erf() erfc() errno exit() EXIT_FAILURE EXIT_SUCCESS exp() exp() exp2() EXPLAIN Exponentialfunktionen extern extern F fabs() fabs() Fakultät fclose() fdim() fdopen() FD_CLR() FD_ISSET() FD_SET() FD_ZERO() feclearexcept() fegetexceptflag() fegetround() Fehlerausgabe Fehlerausgabe, perror() Fehlerausgabe, strerror() feof() feraiseexcept() ferror() fesetexceptflag() fesetround() fetestexcept() FE_ALL_EXCEPT FE_DIVBYZERO FE_DOWNWARD FE_INEXACT FE_INVALID FE_OVERFLOW FE_TONEAREST FE_TOWARDZERO FE_UNDERFLOW FE_UPWARD fflush() fflush() fgetc() fgetpos() fgets() fgets() fgetwc() fgetws() Fibonacci-Zahlen File-Deskriptor FILE-Struktur fileno() FlieÃkommazahlen float im Detail floor() FLT_DIG FLT_EPSILON FLT_MANT_DIG FLT_MAX FLT_MAX_10_EXP FLT_MAX_EXP FLT_MIN FLT_MIN_10_EXP FLT_MIN_EXP FLT_RADIX fma() fmax() fmin() fmod() fopen() FOPEN_MAX FOPEN_MAX for-Schleife Formatierte Ausgabe, fprintf() Formatierte Ausgabe, printf() Formatierte Ausgabe, sprintf() Formatierte Ein-/Ausgabe Formatierte Ein-/Ausgabe, Umwandlungsvorgaben Formatierte Eingabe, fscanf() Formatierte Eingabe, scanf() Formatierte Eingabe, sscanf() Formatierungsanweisung Format String Exploits Formatstring von printf() Formular, Auswahlliste Formular, Beginn und Ende Formular, Checkbox Formular, Eingabefeld Formular, Passwort-Feld Formular, Radiobutton Formular, Reset-Button Formular, Submit-Button Formular, Textfeld fpclassify() fpos_t fprintf() fputc() fputs() fputwc() fputws() FP_INFINITE FP_NAN FP_NORMAL FP_SUBNORMAL FP_ZERO fread() free() free() free(), Makro Freispeicherverwaltung Freispeicherverwaltung, Best-Fit-Verfahren Freispeicherverwaltung, Buddy-Verfahren Freispeicherverwaltung, First-Fit-Verfahren Freispeicherverwaltung, Next-Fit-Verfahren Freispeicherverwaltung, Quick-Fit-Verfahren Freispeicherverwaltung, Worst-Fit-Verfahren freopen() frexp() fscanf() fseek() fsetpos() ftell() Funktion, Ãbergabe eines Arrays Funktion, Argument Funktion, Array als Rückgabewert Funktion, call-by-reference Funktion, call-by-value Funktion, Definition von Funktionen Funktion, Funktionsaufruf Funktion, Funktionsdeklaration Funktion, main() Funktion, Parameter Funktion, Rückgabewert Funktion, Rekursion Funktion, Speicherklassen Funktion, Speicherklassen Funktion, Struktur (call-by-reference) Funktion, Struktur (call-by-value) Funktion, Struktur als Rückgabewert Funktion, Vorwärtsdeklaration Funktion, Zeiger als Rückgabewert Funktionen, inline Funktionen, mehrdimensionale Arrays fwrite() G Gammafunktionen Ganzzahlen Ganzzahlen, char Ganzzahlen, int Ganzzahlen, long Ganzzahlen, short Ganzzahlkonstanten Geltungsbereich von Variablen Genauigkeit von Gleitpunktzahlen getc() getch() getchar() getcwd() getenv() getenv() gethostbyname() gets() getservbyname() getwc() getwchar() Gleitpunktkonstanten Gleitpunktzahlen, double Gleitpunktzahlen, float Gleitpunktzahlen, Genauigkeit Gleitpunktzahlen, long double Gleitpunktzahlen, numerische Gleitpunktprobleme Gleitpunktzahlen-Umgebung gmtime() goto GröÃe, Datei (st_size) GröÃter gemeinsamer Teiler GUI-Programmierung H Hashing Hashing, direkte Adressierung Hashing, Hash-Funktion Hashing, Hash-Funktion Hashing, Hash-Tabelle Hashing, von Strings Heap Heap Heap Hostname HTML HTML, Formular-Tags HTML, Tag htonl() htons() HTTP-Protokoll HTTP-Protokoll HUGE_VAL Hyperbolische Funktionen Hyperthreading hypot() I IEEE-Standard 754 if-Bedingung ilogb() imaxabs() imaxdiv() INADDR_ANY Indizierungsoperator Indizierungsoperator inline inline INSERT INTO Insertion Sort int intmax_t intmax_t intN_t intptr_t int_fastN_t int_leastN_t INT_MAX INT_MIN IP-Nummer IP-Nummer, dynamisch IP-Nummer, statisch IP-Protokoll IPv4 IPv6 isalnum() isalpha() isascii() isblank() iscntrl() isdigit() isfinite() isgraph() isgreater() isgreaterequal() isinf() isless() islessequal() islessgreater() islower() isnan() isnormal() isprint() ispunct() isspace() isunordered() isupper() iswalnum() iswalpha() iswblank() iswcntrl() iswctype() iswdigit() iswgraph() iswlower() iswprint() iswpunct() iswspace() iswupper() iswxdigit() isxdigit() itoa() J jmp_buf K Karp-Rabin-Algorithmus KMP-Algorithmus Kommandozeile Kommandozeile, Argumente Kommandozeile, Optionen Kommandozeilenprozessor Konstante Konstante, Betriebssystem Konstante, Compiler L labs() Laufzeitmessung lconv-Struktur LDBL_DIG LDBL_EPSILON LDBL_MANT_DIG LDBL_MAX LDBL_MAX_10_EXP LDBL_MAX_EXP LDBL_MIN LDBL_MIN_10_EXP LDBL_MIN_EXP ldexp() ldiv() ldiv_t lgamma() LIFO-Prinzip Lineare Suche Linksassoziativität listen() Literale Little-Endian LLONG_MAX LLONG_MIN llrint() llround() load_defaults() localeconv() localtime() log() log() log1p() log2() log10() Logarithmus Logarithmus logb() Logische Operatoren Logische Operatoren long long double long double longjmp() long long LONG_MAX LONG_MIN Loopback-Interface lrint() lround() lseek() M main() main()-Funktion MAKEWORD() Makro Makro malloc() malloc(), Typen-Casting Maschinencode Maximum mbstate_t MB_LEN_MAX memchr() memcmp() memcmp() memcpy() memmove() Memory Leak Memory Leak Memory Leak Memory Leak, Bibliotheken und Tools Memory Leak, GegenmaÃnahmen memset() memset() Minimum mkdir() mktime() modf() Modulo-Operator MSQL_UNIX_SOCKET Multibyte-Zeichen Multibyte-Zeichen MySQL MySQL, Befehle MySQL, Bibliothek MySQL, C-API MySQL, C-API MySQL, Datentypen MySQL, eigene Clientprogramme MySQL, Headerdateien MySQL, Installation MySQL, libmysql.dll MySQL, libmysql.dll MySQL, libmysql.lib MySQL, Server starten MySQL-C-API, Anfrage an den Server MySQL-C-API, CGI-Anwendung MySQL-C-API, Daten ausgeben MySQL-C-API, Datenbank auswählen MySQL-C-API, Daten hinzufügen MySQL-C-API, Daten hinzufügen MySQL-C-API, Daten löschen MySQL-C-API, Daten suchen MySQL-C-API, Daten suchen MySQL-C-API, Datentypen MySQL-C-API, Daten verändern MySQL-C-API, Daten vom Server holen MySQL-C-API, Fehlerüberprüfung MySQL-C-API, Feldwert ermitteln MySQL-C-API, Funktionsübersicht MySQL-C-API, Kommandozeilen-Argumente MySQL-C-API, MYSQL-Handle MySQL-C-API, MYSQL_FIELD-Struktur MySQL-C-API, MYSQL_RES-Struktur MySQL-C-API, Serverantwort auswerten MySQL-C-API, Verbindung herstellen MySQL-C-API, Verbindung schlieÃen MySQL-Clientprogramme, mit Borland-Compiler MySQL-Clientprogramme, mit gcc MySQL-Clientprogramme, mit Visual C++ MySQL-Clientprogramme, Probleme beim Erstellen mysql_affected_rows() mysql_affected_rows() mysql_change_user() mysql_character_set_name() mysql_close() mysql_close() mysql_connect() mysql_create_db() mysql_data_seek() mysql_debug() mysql_drop_db() mysql_dump_debug_info() mysql_eof() mysql_errno() mysql_errno() mysql_error() mysql_error() mysql_escape_string() mysql_fetch_field() mysql_fetch_field() mysql_fetch_fields() mysql_fetch_field_direct() mysql_fetch_lengths() mysql_fetch_row() mysql_fetch_row() mysql_field_count() mysql_field_seek() mysql_field_seek() mysql_field_tell() mysql_field_tell() mysql_free_result() mysql_free_result() mysql_get_client_info() mysql_get_host_info() mysql_get_proto_info() mysql_get_server_info() mysql_info() mysql_init() mysql_init() mysql_insert_id() mysql_kill() mysql_list_dbs() mysql_list_fields() mysql_list_processes() mysql_list_tables() mysql_num_fields() mysql_num_fields() mysql_num_rows() mysql_num_rows() mysql_options() mysql_ping() mysql_query() mysql_query() mysql_real_connect() mysql_real_connect() mysql_real_escape_string() mysql_real_query() mysql_real_query() mysql_real_query() mysql_reload() mysql_row_seek() mysql_row_tell() mysql_select_db() mysql_select_db() mysql_shutdown() mysql_stat() mysql_store_result() mysql_store_result() MYSQL_TCP_PORT mysql_thread_id() mysql_thread_safe() mysql_use_result() N Nameserver nan() NDEBUG nearbyint() NetBurst Netzwerkprogrammierung Netzwerkprogrammierung, Client/Server-Prinzip Netzwerkprogrammierung, Linux Netzwerkprogrammierung, Windows Netzwerktechnik Netzwerktechnik, Domainname Netzwerktechnik, Hostname Netzwerktechnik, IP-Nummer Netzwerktechnik, IP-Protokoll Netzwerktechnik, IPv4 Netzwerktechnik, IPv6 Netzwerktechnik, Loopback-Interface Netzwerktechnik, Nameserver Netzwerktechnik, OSI-Schichtmodell Netzwerktechnik, Portnummer Netzwerktechnik, Sockets Netzwerktechnik, TCP Netzwerktechnik, UDP nextafter() nexttoward() Normalverteilung not not Notationsstil not_eq ntohl() ntohs() NULL NULL NULL NULL O objdump ODBC-Schnittstelle offsetof-Makro Opcode open() opendir() OpenMP OPEN_MAX Operatoren, arithmetische Operatoren, bitweise Operatoren, Dekrement Operatoren, Inkrement Operatoren, logische Operatoren, Zuweisungs- or or or_eq O_APPEND O_BINARY O_CREAT O_EXCL O_NOCTTY O_NONBLOCK O_RDONLY O_RDWR O_SYNC O_TEXT O_TRUNC O_WRONLY P Paging Paralleles Rechnen Parameter, von main() Pattern Matching perror() Portabel, getch() Portabel, Verzeichnis ausgeben Portnummer POSIX-Thread-Bibliothek pow() Präprozessor Präprozessor-Direktiven, define Präprozessor-Direktiven, elif Präprozessor-Direktiven, else Präprozessor-Direktiven, endif Präprozessor-Direktiven, error Präprozessor-Direktiven, ifdef Präprozessor-Direktiven, include Präprozessor-Direktiven, line Präprozessor-Direktiven, pragma Präprozessor-Direktiven, undef printf() Profiler Profiler, gprof Programmbeendigung Programmbeendigung, abort() Programmbeendigung, atexit() Programmbeendigung, exit() Programmbeendigung, _exit() Prozess Pthreads pthread_cleanup_pop() pthread_cleanup_push() pthread_create() pthread_exit() pthread_join() pthread_t ptrdiff_t Pufferüberlauf Pufferung Pufferung, Einstellen Punktoperator putc() putchar() puts() putwc() putwchar() Q qsort() qsort() Quadratwurzel Queues Queues, get() Queues, put() Quicksort R Rückgabewert beim Beenden Rückgabewert von Funktionen Rückgabewert von main() Rücksprungadresse manipulieren raise() rand() RAND_MAX read() Read-only-Zeiger readdir() realloc() Rechtsassoziativität recv() recvfrom() register Reguläre Ausdrücke Rekursion Relationale Beziehung remainder() remove() remquo() rename() restrict return rewind() rewinddir() rint() rmdir() round() Rundungsfunktionen S scalbln() scalbn() scanf() SCHAR_MAX SCHAR_MIN Schlüsselwörter Schlüsselwörter, in C Schleife, do while Schleife, Endlosschleife Schleife, for Schleife, while seekdir() SEEK_CUR SEEK_CUR SEEK_END SEEK_END SEEK_SET SEEK_SET select() select(), FD_CLR() select(), FD_ISSET() select(), FD_SET() select(), FD_ZERO() SELECT ... FROM Selektion Sort send() sendto() setbuf() setjmp() setlocale() setvbuf() Shellsort Shellsort, Distanzfolgen short SHOW DATABASE SHOW TABLES SHRT_MAX SHRT_MIN Sicheres Programmieren Sicheres Programmieren, Buffer Overflow Sicheres Programmieren, Memory Leak Sicherheitsprobleme vermeiden signal() Signal, SIGABRT Signal, SIGABRT Signal, SIGFPE Signal, SIGILL Signal, SIGINT Signal, SIGINT Signal, SIGSEGV Signal, SIGTERM Signal, SIG_DFL Signal, SIG_ERR Signal, SIG_IGN Signalkonzept signed sin() sinh() sinh() Sinus sizeof-Operator sizeof-Operator sizeof-Operator size_t size_t snprintf() socket() Socketprogrammierung Socketprogrammierung, accept() Socketprogrammierung, Adresse festlegen (binden) Socketprogrammierung, bind() Socketprogrammierung, Client-Anwendung Socketprogrammierung, Client/Server-Anwendung Socketprogrammierung, Client/Server-Prinzip Socketprogrammierung, close() Socketprogrammierung, closesocket() Socketprogrammierung, connect() Socketprogrammierung, Daten empfangen Socketprogrammierung, Datenformate Socketprogrammierung, Daten senden Socketprogrammierung, gethostbyname() Socketprogrammierung, hostent Socketprogrammierung, htonl() Socketprogrammierung, htons() Socketprogrammierung, IPv4 nach IPv6 ändern Socketprogrammierung, Linux Socketprogrammierung, listen() Socketprogrammierung, mehrere Clients gleichzeitig Socketprogrammierung, ntohl() Socketprogrammierung, ntohs() Socketprogrammierung, Portabilität Socketprogrammierung, Puffer Socketprogrammierung, recv() Socketprogrammierung, recvfrom() Socketprogrammierung, RFC-Dokumente Socketprogrammierung, select() Socketprogrammierung, send() Socketprogrammierung, sendto() Socketprogrammierung, servent Socketprogrammierung, Server-Anwendung Socketprogrammierung, Serverhauptschleife Socketprogrammierung, Sicherheit Socketprogrammierung, sockaddr_in Socketprogrammierung, socket() Socketprogrammierung, Socket anlegen Socketprogrammierung, Socket freigeben Socketprogrammierung, TCP-Echo-Server Socketprogrammierung, Verbindung annehmen Socketprogrammierung, Verbindung herstellen Socketprogrammierung, Warteschlange einrichten Socketprogrammierung, Windows Sockets Sortieralgorithmus Sortieralgorithmus, analysieren Sortieralgorithmus, Bubble Sort Sortieralgorithmus, Insertion Sort Sortieralgorithmus, qsort() Sortieralgorithmus, Quicksort Sortieralgorithmus, Selektion Sort Sortieralgorithmus, Shellsort Sortieren Sortieren, qsort() Speicher allozieren, alloca() Speicher allozieren, calloc() Speicher allozieren, malloc() Speicher allozieren, realloc() Speicher freigeben, free() Speicher freigeben, free() Speicherhierarchie Speicherleck Speicherverwaltung sprintf() Sprung, longjmp() Sprung, setjmp() Sprunganweisung, break Sprunganweisung, continue SQL SQL, Befehle SQL, Crashkurs SQL, Daten abfragen SQL, Datenbank anlegen SQL, Datenbank ausgeben SQL, Datenbank auswählen SQL, Datenbank löschen SQL, Daten eingeben SQL, Daten löschen SQL, Datensatz SQL, Datentypen SQL, Daten verändern SQL, DDL-Anweisungen SQL, DML-Anweisungen SQL, SQL-Kommandos SQL, Tabelle anlegen SQL, Tabelle anzeigen SQL, Tabelle löschen SQL, Tabellen-Details SQL, Tabelle verändern sqrt() srand() sscanf() Stack Stack Stack Stack Stack, debuggen Stack, pop() Stack, push() Stack-Frame Stackrahmen Standard-Headerdateien Standard-Streams Standard-Streams, umleiten Startup-Code stat() stat-Struktur stat-Struktur, st_atime stat-Struktur, st_ctime stat-Struktur, st_dev stat-Struktur, st_gid stat-Struktur, st_ino stat-Struktur, st_mode stat-Struktur, st_mtime stat-Struktur, st_nlink stat-Struktur, st_rdev stat-Struktur, st_size stat-Struktur, st_uid static static STDC FENV_ACCESS stderr STDERR_FILENO stdin STDIN_FILENO stdout STDOUT_FILENO Steuerzeichen strcat() strchr() strcmp() strcpy() strcspn() Stream Stream Stream strerror() strftime() String, einlesen String, lesen (formatiert) String, Lesen einer Zeile String, reguläre Ausdrücke String, schreiben (formatiert) String, Schreiben einer Zeile String, Stringmatching String, umwandeln in numerischen Wert Stringende-Zeichen Stringkonstante Stringkonstante Stringmatching-Algorithmus Stringmatching-Algorithmus, Boyer-Moore-Algorithmus Stringmatching-Algorithmus, Brute Force Stringmatching-Algorithmus, Karp-Rabin-Algorithmus Stringmatching-Algorithmus, Knuth/Morris/Pratt-Algorithmus Stringmatching-Algorithmus, naiver Algorithmus Stringmatching-Algorithmus, reguläre Ausdrücke Strings Strings aneinander hängen, strcat() Strings aneinander hängen, strncat() Stringtabelle Stringtabelle strlen() strncmp() strncpy() strpbrk() strrchr() strspn() strstr() strtod() strtof() strtoimax() strtok() strtol() strtold() strtoll() strtoul() strtoumax() struct Struktur, an Funktion übergeben Struktur, Array Struktur, Attribute verändern Struktur, Bitfelder Struktur, deklarieren Struktur, Initialisierung und Zugriff Struktur, in Struktur Struktur, Lebensdauer Struktur, offsetof-Makro Struktur, Rückgabewert von Funktion Struktur, Union Struktur, vergleichen Strukturelemente Strukturen Suchalgorithmus Suchalgorithmus Suchalgorithmus, binärer Suchbaum Suchalgorithmus, binäre Suche Suchalgorithmus, binäre Suche Suchalgorithmus, Hashing Suchalgorithmus, lineare Suche Suchen Suchen, bsearch() Suchen in einem String, strchr() Suchen in einem String, strcspn() Suchen in einem String, strpbrk() Suchen in einem String, strrchr() Suchen in einem String, strspn() Suchen in einem String, strstr() switch-Anweisung Symbole Symbolische Konstante system() Systemprogrammierung S_IEXEC S_IREAD S_IREAD S_IRGRP S_IRGRP S_IROTH S_IROTH S_IRUSR S_IRUSR S_IRWXG S_IRWXO S_IRWXU S_ISGID S_ISUID S_ISVTX S_IWGRP S_IWGRP S_IWOTH S_IWOTH S_IWRITE S_IWRITE S_IWUSR S_IWUSR S_IXGRP S_IXGRP S_IXOTH S_IXOTH S_IXUSR S_IXUSR T tan() Tangens tanh() tanh() Tastatur-Puffer leeren TCP TCP-Echo-Server TCP-Echo-Server, Client TCP-Echo-Server, Server telldir() Temporäre Datei, mkstemp() Temporäre Datei, tmpfile() Temporäre Datei, tmpnam() tgamma() Tic Tac Toe time() time_t tm-Struktur tmpfile() tmpnam() TMP_MAX toascii() tolower() toupper() towctrans() towlower() towupper() Trial-and-Error-Prinzip Trigraph-Zeichen trunc() Typendefinition, typedef Typumwandlung, explizit Typumwandlung, implizit U UCHAR_MAX UDP UDP-Anwendung, Client UDP-Anwendung, Server uintmax_t uintmax_t uintN_t uintptr_t uint_fastN_t uint_leastN_t UINT_MAX ULLONG_MAX ULONG_MAX Umgebungsvariablen, getenv() Ungenauigkeit bei Gleitpunktzahlen ungetc() ungetwc() Unicode union UNIX unsigned UPDATE URL USE USHRT_MAX V Variable Argumentliste bei Funktionen Variablen, deklarieren Variablen, global Variablen, Lebensdauer Variablen, Lebensdauer Variablen, lokal Variablen, Speicherklassen Variablen, statisch Variablen, Typ-Qualifizierer Variadic Makro va_arg va_copy va_end va_list va_start Vergleichsoperatoren Verkettete Listen, doppelt Verkettete Listen, einfach Verkettete Listen, Queues Verkettete Listen, Stack Verzeichnis, Arbeits- Verzeichnis, erstellen Verzeichnis, Funktionen Verzeichnis, löschen Verzeichnis, lesen Verzeichnis, positionieren Verzeichnis, wechseln Verzeichnis, zum Lesen öffnen vfprintf() void void-Zeiger volatile volatile vprintf() vsnprintf() vsprintf() W Warteschlange WCHAR_MAX WCHAR_MIN wchar_t wchar_t wcsftime() wctrans() wctype() Webprogrammierung, clientseitig Webprogrammierung, serverseitig Webserver, Apache Webserver, HTTPD WEOF while-Schleife Whitespace Win32-Konsole Winsock Winsock, initialisieren wint_t wmemchr() wmemcmp() wmemcpy() wmemmove() wmemset() Wrapper-Funktion write() WSACleanup() WSAStartup() Wurzelfunktionen X xor xor_eq Z Zeichen Zeichen, lesen Zeichen, lesen Zeichen, lesen Zeichen, schreiben Zeichen, schreiben Zeichen, umwandeln in GroÃbuchstaben Zeichen, umwandeln in Kleinbuchstaben Zeichen, zurückschieben Zeichenkette Zeichenkette Zeichenklassifizierung Zeichenkonstanten Zeichensatz, Basic-Zeichensatz Zeichensatz, international Zeichensatz, national Zeichensatz, OEM Zeichensatz, Steuerzeichen Zeiger Zeiger, als Rückgabewert Zeiger, auf Funktionen Zeiger, call-by-reference Zeiger, deklarieren Zeiger, Dereferenzierung Zeiger, die auf andere Zeiger verweisen Zeiger, dynamisches Zeigerarray Zeiger, initialisieren Zeiger, NULL Zeiger, ptrdiff_t Zeiger, read-only Zeiger, restrict Zeiger, restrict Zeiger, SpeichergröÃe Zeiger, SpeichergröÃe Zeiger, void Zeigerarithmetik Zeiger auf Strings Zeiger auf Zeiger Zeiger und Array Zeiger und Array Zeiger und Array Zeilenweise lesen Zeilenweise lesen, bestimmte Zeile auslesen Zeilenweise lesen, newline entfernen Zeilenweise lesen, suchen nach Stringfolge Zeilenweise lesen, suchen nach Wörtern Zeilenweise lesen, suchen und ersetzen Zeilenweise lesen, von Zeile x bis y lesen Zeilenweise schreiben Zeit Zeit, tm-Struktur Zeit, Zeitraum berechnen Zeiten einer Datei Zeiten einer Datei, Inode-Ãnderung Zeiten einer Datei, Zugriffszeit Zufallszahlen, rand() Zufallszahlen, srand() Zugriffsrechte Zugriffsrechte Ihre Meinung Wie hat Ihnen das Openbook gefallen? Wir freuen uns immer über Ihre Rückmeldung. Schreiben Sie uns gerne Ihr Feedback als E-Mail an <EMAIL>. ### ! ! (Operator) != (Operator) #define-Anweisung #elif-Anweisung #else-Anweisung #endif-Anweisung #error-Anweisung #ifdef-Anweisung #include-Anweisung #line-Anweisung #pragma-Anweisung #pragma pack % (Operator) %= (Operator) (type)Operator * (Operator) *= (Operator) + (Operator) ++ (Operator) += (Operator) - (Operator) -- (Operator) -= (Operator) . (Operator) / (Operator) /= (Operator) == (Operator) ?:(Operator) < (Operator) <= (Operator) <assert.h>-Headerdatei;Headerdatei <ctype.h>-Headerdatei <errno.h>-Headerdatei <fenv.h>-Headerdatei <float.h>-Headerdatei <iso646.h>-Headerdatei (C 99) <limits.h>-Headerdatei <locale.h>-Headerdatei;Headerdatei <math.h>-Headerdatei <setjmp.h>-Headerdatei;Headerdatei <signal.h>-Headerdatei;Headerdatei <stdarg.h>-Headerdatei;Headerdatei <stdbool.h>-Headerdatei <stdint.h>-Headerdatei (C 99) <stdio.h>-Headerdatei;Headerdatei <stdlib.h>-Headerdatei;Headerdatei <time.h>-Headerdatei;Headerdatei << (Operator) > (Operator) >= (Operator) >> (Operator) ^ (Operator) _Complex _exit() _IOFBF _IOLBF _IONBF __attribut__ __cplusplus Makro __DATE__ Makro __FILE__ __FILE__ Makro __func__ (C99) __LINE__ __LINE__ Makro __STDC__ Makro __STD_HOSTED__ (C 99) __STD_VERSION__ (C 99) __TIME__ Makro __VA_ARGS__ | (Operator) || (Operator) ~ (Operator) ### A Abnormale Programmbeendigung abs() accept() access() acos() AF_BLUETOOTH AF_INET AF_INET6 AF_IRDA AF_UNIX Algorithmen alloca() ALTER TABLE and_eq ANSI ANSI–C-Standard, C89-Standard ANSI–C-Standard, C99-Standard Apache Webserver Apache Webserver, htdocs-Verzeichnis Apache Webserver, installieren Arcuscosinus Arcussinus Array, Anzahl der Elemente ermitteln Array, Bereichsüberschreitung Array, deklarieren Array, Funktionsübergabe Array, Funktionsübergabe als Kopie Array, Gültigkeitsbereich Array, Indizierungsoperator Array, Initialisierung und Zugriff Array, Rückgabe aus Funktion Array, Strukturen Array, Vergleichen Array, von Tastatur einlesen ASCII-Zeichensatz asctime() asin() assert() atan() atan2() atexit() atof() atoi() atol() Attribute einer Datei Aufzählungstyp, enum Ausgeglichener Binärbaum auto AVL-Baum ### B Bäume B-Baum Backtracking Basisdatentyp, Definition Basisdatentyp, Deklaration Bedingte Kompilierung Bedingung, else Bedingung, else if Bedingung, if Bedingungsoperator Begrenzer Begrenzer, geschweifte Klammern Begrenzer, Gleichheitszeichen (=) Begrenzer, Komma (,) Begrenzer, Semikolon (;) Big Endian Bildschirm löschen Binäre Bäume Binäre Bäume, Ast, Kante Binäre Bäume, ausgleichen Binäre Bäume, AVL-Baum Binäre Bäume, B-Baum Binäre Bäume, Blatt Binäre Bäume, Elternzeiger Binäre Bäume, entartet Binäre Bäume, Knoten Binäre Bäume, Teilbaum Binäre Bäume, Threads Binäre Bäume, Tiefe Binäre Bäume, Wurzel Binäre Suche bind() bitand Bitfelder Bitfelder, anonym Bitmanipulationen, Bits abfragen Bitmanipulationen, Bits löschen Bitmanipulationen, Bits setzen bitor Bitweise Operatoren Blockweise (binär), lesen Blockweise (binär), schreiben Boyer-Moore-Algorithmus braces break bsearch() Bubble Sort Buffer Overflow Buffer Overflow, anfällige Funktionen Buffer Overflow, fgets() Buffer Overflow, GegenmaÃnahmen Buffer Overflow, Programme und Tools Buffer Overflow, sprintf() Buffer Overflow, Wrapper-Funktion BUFSIZ Byte Stream ### C C-API, MySQL C1x C89-Standard cabs() cacos() call-by-value calloc() carg() casin() casinh() Casting catan() ccos() cexp() CGI CGI, Anwendung ausführen CGI, Anwendung erstellen CGI, Ausgabe CGI, CONTENT_LENGTH CGI, Eingabe CGI, Eingabe dekodieren CGI, Eingabe parsen CGI, Filehandle CGI, Formular-Tags CGI, Gästebuch CGI, getenv() CGI, HTTP-Protokoll CGI, HTTP Request CGI, Methode auswerten CGI, mit der MySQL-C-API CGI, Query-String CGI, QUERY_STRING CGI, Request Header CGI, Server Response CGI, Statuscode CGI, Umgebungsvariablen CGI, Zugriffsrechte char CHAR_BIT CHAR_MAX CHAR_MIN chdir() cimag() clock_t clog() closedir() closesocket() clrearerr() clrscr() compl complex conj() connect() const continue copysign() cos() Cosinus cpow() cproj() creal() creat() CREATE DATABASE CREATE TABLE Cross-Plattform-Entwicklung Cross-Plattform-Entwicklung, Abstraktion Layer csin() csinh() csqrt() ctan() ctime() curly brackets ### D Datei Datei, Attribute Datei, Binärmodus Datei, Eigentümer Datei, EOF-Flag Datei, Fehler-Flag Datei, GröÃe Datei, Gruppeneigentümer Datei, Inode-Ãnderung Datei, löschen Datei, Lesen (blockweise, binär) Datei, Lesen (formatiert) Datei, Lesen einer Zeile Datei, neu anlegen Datei, positionieren (Low Level) Datei, schlieÃen Datei, schlieÃen (Low Level) Datei, schreiben (blockweise, binär) Datei, schreiben (formatiert) Datei, schreiben (Low Level) Datei, schreiben einer Zeile Datei, temporäre Datei, Textmodus Datei, umbenennen Datei, Zugriffszeit Dateiarten Dateiarten, st_mode Dateiarten, S_IFCHR Dateiarten, S_IFDIR Dateiarten, S_IFREG Dateiarten, S_ISBLK Dateiarten, S_ISFIFO Dateiarten, S_ISLINK Dateiarten, S_ISSOCK Datenbanksystem Datenbanksystem, relationales Modell Datentyp, char Datentyp, double Datentyp, float Datentyp, int Datentyp, long Datentyp, long double Datentyp, short Datum Datum, tm-Struktur DBL_DIG DBL_EPSILON DBL_MANT_DIG DBL_MAX DBL_MAX_10_EXP DBL_MAX_EXP DBL_MIN DBL_MIN_10_EXP DBL_MIN_EXP DBMS DBMS, Drei-Schichten-Modell Deadlock default DELETE FROM <NAME> Dereferenzierungsoperator Differenzen C und C++, sizeof-Operator difftime() dirent-Struktur div() div_t Domainname Doppelt verkettete Listen double im Detail do while-Schleife DROP DATABASE DROP TABLE Dynamische Arrays Dynamische Arrays, zweidimensional Dynamische Datenstrukturen Dynamische Speicherverwaltung ### E EDOM Ein-/Ausgabe-Funktionen, höhere Ebene Ein-/Ausgabe-Funktionen, niedrigere Ebene Einfach verkettete Listen Elementare Datentypen Elementkennzeichnungsoperator else-Bedingung else if-Bedingung Endlosschleife Entarteter Binärbaum Entwicklungsumgebung enum ERANGE erf() erfc() errno exit() EXIT_FAILURE EXIT_SUCCESS exp2() EXPLAIN Exponentialfunktionen ### F Fakultät fclose() fdim() fdopen() FD_CLR() FD_ISSET() FD_SET() FD_ZERO() feclearexcept() fegetexceptflag() fegetround() Fehlerausgabe Fehlerausgabe, perror() Fehlerausgabe, strerror() feof() feraiseexcept() ferror() fesetexceptflag() fesetround() fetestexcept() FE_ALL_EXCEPT FE_DIVBYZERO FE_DOWNWARD FE_INEXACT FE_INVALID FE_OVERFLOW FE_TONEAREST FE_TOWARDZERO FE_UNDERFLOW FE_UPWARD fgetc() fgetpos() fgetwc() fgetws() Fibonacci-Zahlen File-Deskriptor FILE-Struktur fileno() FlieÃkommazahlen float im Detail floor() FLT_DIG FLT_EPSILON FLT_MANT_DIG FLT_MAX FLT_MAX_10_EXP FLT_MAX_EXP FLT_MIN FLT_MIN_10_EXP FLT_MIN_EXP FLT_RADIX fma() fmax() fmin() fmod() fopen() for-Schleife Formatierte Ausgabe, fprintf() Formatierte Ausgabe, printf() Formatierte Ausgabe, sprintf() Formatierte Ein-/Ausgabe Formatierte Ein-/Ausgabe, Umwandlungsvorgaben Formatierte Eingabe, fscanf() Formatierte Eingabe, scanf() Formatierte Eingabe, sscanf() Formatierungsanweisung Format String Exploits Formatstring von printf() Formular, Auswahlliste Formular, Beginn und Ende Formular, Checkbox Formular, Eingabefeld Formular, Passwort-Feld Formular, Radiobutton Formular, Reset-Button Formular, Submit-Button Formular, Textfeld fpclassify() fpos_t fprintf() fputc() fputs() fputwc() fputws() FP_INFINITE FP_NAN FP_NORMAL FP_SUBNORMAL FP_ZERO fread() free(), Makro Freispeicherverwaltung Freispeicherverwaltung, Best-Fit-Verfahren Freispeicherverwaltung, Buddy-Verfahren Freispeicherverwaltung, First-Fit-Verfahren Freispeicherverwaltung, Next-Fit-Verfahren Freispeicherverwaltung, Quick-Fit-Verfahren Freispeicherverwaltung, Worst-Fit-Verfahren freopen() frexp() fscanf() fseek() fsetpos() ftell() Funktion, Ãbergabe eines Arrays Funktion, Argument Funktion, Array als Rückgabewert Funktion, call-by-reference Funktion, call-by-value Funktion, Definition von Funktionen Funktion, Funktionsaufruf Funktion, Funktionsdeklaration Funktion, main() Funktion, Parameter Funktion, Rückgabewert Funktion, Rekursion Funktion, Struktur (call-by-reference) Funktion, Struktur (call-by-value) Funktion, Struktur als Rückgabewert Funktion, Vorwärtsdeklaration Funktion, Zeiger als Rückgabewert Funktionen, inline Funktionen, mehrdimensionale Arrays fwrite() ### G Gammafunktionen Ganzzahlen Ganzzahlen, char Ganzzahlen, int Ganzzahlen, long Ganzzahlen, short Ganzzahlkonstanten Geltungsbereich von Variablen Genauigkeit von Gleitpunktzahlen getc() getch() getchar() getcwd() gethostbyname() gets() getservbyname() getwc() getwchar() Gleitpunktkonstanten Gleitpunktzahlen, double Gleitpunktzahlen, float Gleitpunktzahlen, Genauigkeit Gleitpunktzahlen, long double Gleitpunktzahlen, numerische Gleitpunktprobleme Gleitpunktzahlen-Umgebung gmtime() goto GröÃe, Datei (st_size) GröÃter gemeinsamer Teiler GUI-Programmierung ### H Hashing Hashing, direkte Adressierung Hashing, Hash-Tabelle Hashing, von Strings Hostname HTML HTML, Formular-Tags HTML, Tag htonl() htons() HUGE_VAL Hyperbolische Funktionen Hyperthreading hypot() ### I IEEE-Standard 754 if-Bedingung ilogb() imaxabs() imaxdiv() INADDR_ANY INSERT INTO Insertion Sort int intN_t intptr_t int_fastN_t int_leastN_t INT_MAX INT_MIN IP-Nummer IP-Nummer, dynamisch IP-Nummer, statisch IP-Protokoll IPv4 IPv6 isalnum() isalpha() isascii() isblank() iscntrl() isdigit() isfinite() isgraph() isgreater() isgreaterequal() isinf() isless() islessequal() islessgreater() islower() isnan() isnormal() isprint() ispunct() isspace() isunordered() isupper() iswalnum() iswalpha() iswblank() iswcntrl() iswctype() iswdigit() iswgraph() iswlower() iswprint() iswpunct() iswspace() iswupper() iswxdigit() isxdigit() itoa() ### J jmp_buf ### K Karp-Rabin-Algorithmus KMP-Algorithmus Kommandozeile Kommandozeile, Argumente Kommandozeile, Optionen Kommandozeilenprozessor Konstante Konstante, Betriebssystem Konstante, Compiler ### L labs() Laufzeitmessung lconv-Struktur LDBL_DIG LDBL_EPSILON LDBL_MANT_DIG LDBL_MAX LDBL_MAX_10_EXP LDBL_MAX_EXP LDBL_MIN LDBL_MIN_10_EXP LDBL_MIN_EXP ldexp() ldiv() ldiv_t lgamma() LIFO-Prinzip Lineare Suche Linksassoziativität listen() Literale Little-Endian LLONG_MAX LLONG_MIN llrint() llround() load_defaults() localeconv() localtime() log1p() log2() log10() logb() longjmp() LONG_MAX LONG_MIN Loopback-Interface lrint() lround() lseek() ### M main() main()-Funktion MAKEWORD() malloc() malloc(), Typen-Casting Maschinencode Maximum mbstate_t MB_LEN_MAX memchr() memcpy() memmove() Memory Leak, Bibliotheken und Tools Memory Leak, GegenmaÃnahmen Minimum mkdir() mktime() modf() Modulo-Operator MSQL_UNIX_SOCKET MySQL MySQL, Befehle MySQL, Bibliothek MySQL, Datentypen MySQL, eigene Clientprogramme MySQL, Headerdateien MySQL, Installation MySQL, libmysql.lib MySQL, Server starten MySQL-C-API, Anfrage an den Server MySQL-C-API, CGI-Anwendung MySQL-C-API, Daten ausgeben MySQL-C-API, Datenbank auswählen MySQL-C-API, Daten löschen MySQL-C-API, Datentypen MySQL-C-API, Daten verändern MySQL-C-API, Daten vom Server holen MySQL-C-API, Fehlerüberprüfung MySQL-C-API, Feldwert ermitteln MySQL-C-API, Funktionsübersicht MySQL-C-API, Kommandozeilen-Argumente MySQL-C-API, MYSQL-Handle MySQL-C-API, MYSQL_FIELD-Struktur MySQL-C-API, MYSQL_RES-Struktur MySQL-C-API, Serverantwort auswerten MySQL-C-API, Verbindung herstellen MySQL-C-API, Verbindung schlieÃen MySQL-Clientprogramme, mit Borland-Compiler MySQL-Clientprogramme, mit gcc MySQL-Clientprogramme, mit Visual C++ MySQL-Clientprogramme, Probleme beim Erstellen mysql_change_user() mysql_character_set_name() mysql_connect() mysql_create_db() mysql_data_seek() mysql_debug() mysql_drop_db() mysql_dump_debug_info() mysql_eof() mysql_escape_string() mysql_fetch_fields() mysql_fetch_field_direct() mysql_fetch_lengths() mysql_field_count() mysql_get_client_info() mysql_get_host_info() mysql_get_proto_info() mysql_get_server_info() mysql_info() mysql_insert_id() mysql_kill() mysql_list_dbs() mysql_list_fields() mysql_list_processes() mysql_list_tables() mysql_options() mysql_ping() mysql_real_escape_string() mysql_reload() mysql_row_seek() mysql_row_tell() mysql_shutdown() mysql_stat() MYSQL_TCP_PORT mysql_thread_id() mysql_thread_safe() mysql_use_result() ### N Nameserver nan() NDEBUG nearbyint() NetBurst Netzwerkprogrammierung Netzwerkprogrammierung, Client/Server-Prinzip Netzwerkprogrammierung, Linux Netzwerkprogrammierung, Windows Netzwerktechnik Netzwerktechnik, Domainname Netzwerktechnik, Hostname Netzwerktechnik, IP-Nummer Netzwerktechnik, IP-Protokoll Netzwerktechnik, IPv4 Netzwerktechnik, IPv6 Netzwerktechnik, Loopback-Interface Netzwerktechnik, Nameserver Netzwerktechnik, OSI-Schichtmodell Netzwerktechnik, Portnummer Netzwerktechnik, Sockets Netzwerktechnik, TCP Netzwerktechnik, UDP nextafter() nexttoward() Normalverteilung Notationsstil not_eq ntohl() ntohs() ### O objdump ODBC-Schnittstelle offsetof-Makro Opcode open() opendir() OpenMP OPEN_MAX Operatoren, arithmetische Operatoren, bitweise Operatoren, Dekrement Operatoren, Inkrement Operatoren, logische Operatoren, Zuweisungs- or_eq O_APPEND O_BINARY O_CREAT O_EXCL O_NOCTTY O_NONBLOCK O_RDONLY O_RDWR O_SYNC O_TEXT O_TRUNC O_WRONLY ### P Paging Paralleles Rechnen Parameter, von main() Pattern Matching perror() Portabel, getch() Portabel, Verzeichnis ausgeben Portnummer POSIX-Thread-Bibliothek pow() Präprozessor Präprozessor-Direktiven, define Präprozessor-Direktiven, elif Präprozessor-Direktiven, else Präprozessor-Direktiven, endif Präprozessor-Direktiven, error Präprozessor-Direktiven, ifdef Präprozessor-Direktiven, include Präprozessor-Direktiven, line Präprozessor-Direktiven, pragma Präprozessor-Direktiven, undef printf() Profiler Profiler, gprof Programmbeendigung Programmbeendigung, abort() Programmbeendigung, atexit() Programmbeendigung, exit() Programmbeendigung, _exit() Prozess Pthreads pthread_cleanup_pop() pthread_cleanup_push() pthread_create() pthread_exit() pthread_join() pthread_t ptrdiff_t Pufferüberlauf Pufferung Pufferung, Einstellen Punktoperator putc() putchar() puts() putwc() putwchar() ### Q Quadratwurzel Queues Queues, get() Queues, put() Quicksort ### R Rückgabewert beim Beenden Rückgabewert von Funktionen Rückgabewert von main() Rücksprungadresse manipulieren raise() rand() RAND_MAX read() Read-only-Zeiger readdir() realloc() Rechtsassoziativität recv() recvfrom() register Reguläre Ausdrücke Rekursion Relationale Beziehung remainder() remove() remquo() rename() restrict return rewind() rewinddir() rint() rmdir() round() Rundungsfunktionen ### S scalbln() scalbn() scanf() SCHAR_MAX SCHAR_MIN Schlüsselwörter Schlüsselwörter, in C Schleife, do while Schleife, Endlosschleife Schleife, for Schleife, while seekdir() select() select(), FD_CLR() select(), FD_ISSET() select(), FD_SET() select(), FD_ZERO() SELECT ... FROM Selektion Sort send() sendto() setbuf() setjmp() setlocale() setvbuf() Shellsort Shellsort, Distanzfolgen short SHOW DATABASE SHOW TABLES SHRT_MAX SHRT_MIN Sicheres Programmieren Sicheres Programmieren, Buffer Overflow Sicheres Programmieren, Memory Leak Sicherheitsprobleme vermeiden signal() Signal, SIGFPE Signal, SIGILL Signal, SIGSEGV Signal, SIGTERM Signal, SIG_DFL Signal, SIG_ERR Signal, SIG_IGN Signalkonzept signed sin() Sinus snprintf() socket() Socketprogrammierung Socketprogrammierung, accept() Socketprogrammierung, Adresse festlegen (binden) Socketprogrammierung, bind() Socketprogrammierung, Client-Anwendung Socketprogrammierung, Client/Server-Anwendung Socketprogrammierung, Client/Server-Prinzip Socketprogrammierung, close() Socketprogrammierung, closesocket() Socketprogrammierung, connect() Socketprogrammierung, Daten empfangen Socketprogrammierung, Datenformate Socketprogrammierung, Daten senden Socketprogrammierung, gethostbyname() Socketprogrammierung, hostent Socketprogrammierung, htonl() Socketprogrammierung, htons() Socketprogrammierung, IPv4 nach IPv6 ändern Socketprogrammierung, Linux Socketprogrammierung, listen() Socketprogrammierung, mehrere Clients gleichzeitig Socketprogrammierung, ntohl() Socketprogrammierung, ntohs() Socketprogrammierung, Portabilität Socketprogrammierung, Puffer Socketprogrammierung, recv() Socketprogrammierung, recvfrom() Socketprogrammierung, RFC-Dokumente Socketprogrammierung, select() Socketprogrammierung, send() Socketprogrammierung, sendto() Socketprogrammierung, servent Socketprogrammierung, Server-Anwendung Socketprogrammierung, Serverhauptschleife Socketprogrammierung, Sicherheit Socketprogrammierung, sockaddr_in Socketprogrammierung, socket() Socketprogrammierung, Socket anlegen Socketprogrammierung, Socket freigeben Socketprogrammierung, TCP-Echo-Server Socketprogrammierung, Verbindung annehmen Socketprogrammierung, Verbindung herstellen Socketprogrammierung, Warteschlange einrichten Socketprogrammierung, Windows Sockets Sortieralgorithmus Sortieralgorithmus, analysieren Sortieralgorithmus, Bubble Sort Sortieralgorithmus, Insertion Sort Sortieralgorithmus, qsort() Sortieralgorithmus, Quicksort Sortieralgorithmus, Selektion Sort Sortieralgorithmus, Shellsort Sortieren Sortieren, qsort() Speicher allozieren, alloca() Speicher allozieren, calloc() Speicher allozieren, malloc() Speicher allozieren, realloc() Speicherhierarchie Speicherleck Speicherverwaltung sprintf() Sprung, longjmp() Sprung, setjmp() Sprunganweisung, break Sprunganweisung, continue SQL SQL, Befehle SQL, Crashkurs SQL, Daten abfragen SQL, Datenbank anlegen SQL, Datenbank ausgeben SQL, Datenbank auswählen SQL, Datenbank löschen SQL, Daten eingeben SQL, Daten löschen SQL, Datensatz SQL, Datentypen SQL, Daten verändern SQL, DDL-Anweisungen SQL, DML-Anweisungen SQL, SQL-Kommandos SQL, Tabelle anlegen SQL, Tabelle anzeigen SQL, Tabelle löschen SQL, Tabellen-Details SQL, Tabelle verändern sqrt() srand() sscanf() Stack, debuggen Stack, pop() Stack, push() Stack-Frame Stackrahmen Standard-Headerdateien Standard-Streams Standard-Streams, umleiten Startup-Code stat() stat-Struktur stat-Struktur, st_atime stat-Struktur, st_ctime stat-Struktur, st_dev stat-Struktur, st_gid stat-Struktur, st_ino stat-Struktur, st_mode stat-Struktur, st_mtime stat-Struktur, st_nlink stat-Struktur, st_rdev stat-Struktur, st_size stat-Struktur, st_uid STDC FENV_ACCESS stderr STDERR_FILENO stdin STDIN_FILENO stdout STDOUT_FILENO Steuerzeichen strcat() strchr() strcmp() strcpy() strcspn() strerror() strftime() String, einlesen String, lesen (formatiert) String, Lesen einer Zeile String, reguläre Ausdrücke String, schreiben (formatiert) String, Schreiben einer Zeile String, Stringmatching String, umwandeln in numerischen Wert Stringende-Zeichen Stringmatching-Algorithmus Stringmatching-Algorithmus, Boyer-Moore-Algorithmus Stringmatching-Algorithmus, Brute Force Stringmatching-Algorithmus, Karp-Rabin-Algorithmus Stringmatching-Algorithmus, Knuth/Morris/Pratt-Algorithmus Stringmatching-Algorithmus, naiver Algorithmus Stringmatching-Algorithmus, reguläre Ausdrücke Strings Strings aneinander hängen, strcat() Strings aneinander hängen, strncat() strlen() strncmp() strncpy() strpbrk() strrchr() strspn() strstr() strtod() strtof() strtoimax() strtok() strtol() strtold() strtoll() strtoul() strtoumax() struct Struktur, an Funktion übergeben Struktur, Array Struktur, Attribute verändern Struktur, Bitfelder Struktur, deklarieren Struktur, Initialisierung und Zugriff Struktur, in Struktur Struktur, Lebensdauer Struktur, offsetof-Makro Struktur, Rückgabewert von Funktion Struktur, Union Struktur, vergleichen Strukturelemente Strukturen Suchalgorithmus, binärer Suchbaum Suchalgorithmus, Hashing Suchalgorithmus, lineare Suche Suchen Suchen, bsearch() Suchen in einem String, strchr() Suchen in einem String, strcspn() Suchen in einem String, strpbrk() Suchen in einem String, strrchr() Suchen in einem String, strspn() Suchen in einem String, strstr() switch-Anweisung Symbole Symbolische Konstante system() Systemprogrammierung S_IEXEC S_IRWXG S_IRWXO S_IRWXU S_ISGID S_ISUID S_ISVTX ### T tan() Tangens Tastatur-Puffer leeren TCP TCP-Echo-Server TCP-Echo-Server, Client TCP-Echo-Server, Server telldir() Temporäre Datei, mkstemp() Temporäre Datei, tmpfile() Temporäre Datei, tmpnam() tgamma() Tic Tac Toe time() time_t tm-Struktur tmpfile() tmpnam() TMP_MAX toascii() tolower() toupper() towctrans() towlower() towupper() Trial-and-Error-Prinzip Trigraph-Zeichen trunc() Typendefinition, typedef Typumwandlung, explizit Typumwandlung, implizit ### U UCHAR_MAX UDP UDP-Anwendung, Client UDP-Anwendung, Server uintN_t uintptr_t uint_fastN_t uint_leastN_t UINT_MAX ULLONG_MAX ULONG_MAX Umgebungsvariablen, getenv() Ungenauigkeit bei Gleitpunktzahlen ungetc() ungetwc() Unicode union UNIX unsigned UPDATE URL USE USHRT_MAX ### V Variable Argumentliste bei Funktionen Variablen, deklarieren Variablen, global Variablen, lokal Variablen, Speicherklassen Variablen, statisch Variablen, Typ-Qualifizierer Variadic Makro va_arg va_copy va_end va_list va_start Vergleichsoperatoren Verkettete Listen, doppelt Verkettete Listen, einfach Verkettete Listen, Queues Verkettete Listen, Stack Verzeichnis, Arbeits- Verzeichnis, erstellen Verzeichnis, Funktionen Verzeichnis, löschen Verzeichnis, lesen Verzeichnis, positionieren Verzeichnis, wechseln Verzeichnis, zum Lesen öffnen vfprintf() void void-Zeiger vprintf() vsnprintf() vsprintf() ### W Warteschlange WCHAR_MAX WCHAR_MIN wcsftime() wctrans() wctype() Webprogrammierung, clientseitig Webprogrammierung, serverseitig Webserver, Apache Webserver, HTTPD WEOF while-Schleife Whitespace Win32-Konsole Winsock Winsock, initialisieren wint_t wmemchr() wmemcmp() wmemcpy() wmemmove() wmemset() Wrapper-Funktion write() WSACleanup() WSAStartup() Wurzelfunktionen ### X xor xor_eq ### Z Zeichen Zeichen, umwandeln in GroÃbuchstaben Zeichen, umwandeln in Kleinbuchstaben Zeichen, zurückschieben Zeichenklassifizierung Zeichenkonstanten Zeichensatz, Basic-Zeichensatz Zeichensatz, international Zeichensatz, national Zeichensatz, OEM Zeichensatz, Steuerzeichen Zeiger Zeiger, als Rückgabewert Zeiger, auf Funktionen Zeiger, call-by-reference Zeiger, deklarieren Zeiger, Dereferenzierung Zeiger, die auf andere Zeiger verweisen Zeiger, dynamisches Zeigerarray Zeiger, initialisieren Zeiger, NULL Zeiger, ptrdiff_t Zeiger, read-only Zeiger, void Zeigerarithmetik Zeiger auf Strings Zeiger auf Zeiger Zeilenweise lesen Zeilenweise lesen, bestimmte Zeile auslesen Zeilenweise lesen, newline entfernen Zeilenweise lesen, suchen nach Stringfolge Zeilenweise lesen, suchen nach Wörtern Zeilenweise lesen, suchen und ersetzen Zeilenweise lesen, von Zeile x bis y lesen Zeilenweise schreiben Zeit Zeit, tm-Struktur Zeit, Zeitraum berechnen Zeiten einer Datei Zeiten einer Datei, Inode-Ãnderung Zeiten einer Datei, Zugriffszeit Zufallszahlen, rand() Zufallszahlen, srand() # 1.2 Der ANSI-C-Standard ## 1.2 Der ANSI-C-Standard C wurde 1972 von <NAME> und <NAME> erfunden, wobei »erfunden« nicht ganz der richtige Ausdruck ist. C wurde aufgrund einiger Einschränkungen der Vorgängersprache B implementiert und hauptsächlich für das Betriebssystem UNIX entwickelt. Denn vorher war UNIX vollständig in Assembler programmiert. Als die ersten frei erhältlichen Compiler für C erschienen, war der Siegeszug nicht mehr aufzuhalten. C wurde im Zusammenhang mit UNIX zur erfolgreichsten Sprache überhaupt. C wurde aber nicht entwickelt, um Software zu schreiben, sondern für Programmierer, die Compiler entwickelten. Und genau da lag das Problem. Jeder Compiler-Hersteller kochte sein eigenes Süppchen und erweiterte die Programmiersprache um einige Funktionen oder lieà die eine oder andere bestehende Funktion wegfallen. Mit der Zeit entstanden immer mehr unterschiedliche C-Dialekte, und eine Portierung von einem zum anderen System kam dem Neuschreiben eines Programms gleich. SchlieÃlich fand sich eine Gruppe von Compiler-, Hardware- und Software-Entwicklern zusammen, mit der Absicht, das Problem der Vielfalt der Sprachendialekte zu beheben. Das American National Standard Institute (kurz ANSI) rief 1983 ein Komitee namens X3J11 ins Leben, das die Aufgabe bekam, die Sprache C zu standardisieren. ANSI-Standards | | --- | | Das Komitee entwickelte einen Entwurf für einen gemeinsamen Standard und dessen Einhaltung. 1989 war es dann endlich so weit: Der Entwurf wurde vorgelegt und auch von der International Standards Organization (ISO) übernommen. In der Kurzform hieà er C89-Standard (ANSI-Standard X3.159–1989). Teil des ANSI-C-Standards sind die Software-Bibliotheken (besser bekannt unter dem Begriff ANSI C standard library). Natürlich wurden nicht immer nur Headerdateien hinzugefügt, sondern auch die wesentlichen Schwächen von C verbessert. Dies muss an dieser Stelle erwähnt werden, da häufig auf Titeln von Büchern zu lesen ist: »Entspricht dem neuen C99-Standard«. Häufig bezieht sich diese Aussage auf die wesentlichen Verbesserungen von C und nicht auf die neuen Bibliotheken. Der aktuelle C99-Standard (ISO/IEC 9899:1999) ist mittlerweile bei vielen Compilerherstellern angekommen und gröÃtenteils implementiert. Sofern Sie den Standard lesen wollen, müssen Sie diesen käuflich erwerben, da es keine Online-Version davon gibt. Der ISO-Standard wird in Genf unter folgender Adresse vertrieben: > ISO Distribution Case Postale 56 CH-1211 Geneve 20 Suisse Sie können allerdings auch eine Rationale via FTP von ftp.uu.net beziehen. Im Verzeichnis doc/standards/ansi/X3.159–1989 finden Sie eine entsprechende Postscript-Datei, die auch von Silicon Press (ISBN 0–929306–07–4) vertrieben wird. Rationale | | --- | | Seit 2007 arbeitet das Standardisierungskomitee an einer neuen Revision des C–Standards. Derzeit wird dieser Standard als C1x bezeichnet. Daraus kann man zumindest schlieÃen, dass dieser Standard irgendwann im Jahre 2010 bis 2019 erscheinen dürfte. Fakt ist auf jeden Fall, dass dann auch die Thread-Programmierung im Standard implementiert sein wird, was gerade angesichts der Mehrprozessorsysteme unumgänglich wird. Es dürfte wohl auch zu erwarten sein, dass der neue C1x-Standard neue Funktionen für eingebettete Systeme, verschiedene Zeichensätze (Unicode-Unterstützung), Funktionen für eine dynamische Speicherreservierung und Ãberprüfung von Speicher- bzw. Pufferüberläufen usw. enthalten wird. ### 1.2.1 Welcher C-Standard wird in diesem Buch verwendet? Den einen oder anderen dürfte diese Ãberschrift etwas verwirren, da sich das Buch doch als C99-Standard-konform gibt. Das ist schon richtig, das Buch hier beschreibt auch den C99-Standard. Nur leider schaffen es einige Compiler-Hersteller nicht (darunter auch solche GröÃen wie Microsoft oder Borland; Stand 2009) den C99-Standard komplett zu implementieren. So bleibt mir in diesem Buch nichts anders übrig, als immer wieder darauf hinzuweisen, dass dies oder jenes eben dem C99-Standard entspricht und somit auch nur bei Compilern funktioniert, die diesen Standard implementiert haben. Besonders hervorzuheben bezüglich der Unterstützung des C99-Standards sind hier die Compiler GCC, Sun Studio (Software), Open Watcom C Compiler und Intel C/C++. ### 1.2.2 Der Vorteil des ANSI-C-Standards Der Hauptvorteil des ANSI-C-Standards ist die Portabilität von C-Programmen. Das bedeutet: Wenn Sie ein Programm auf Plattform A geschrieben haben und übersetzen, lässt sich dieses Programm auch auf Plattform B übersetzen. Natürlich ist damit eine Neuübersetzung des Quellcodes gemeint und nicht das ausführbare Programm. ANSI-C-Compiler gibt es für über 40 Systeme, vom kleinsten 8-Bit-Computer bis hin zum Superrechner. Nicht portabel hingegen sind hardwarenahe bzw. betriebssystemspezifische Operationen. Wenn Sie zum Beispiel ein Programm für UNIX/Linux schreiben, das die Grafikkarte anspricht, wird das Programm seine Ausführung auf anderen Systemen verweigern. Es gibt natürlich noch eine Reihe von weiteren Standards, die aber in diesem Buch nicht behandelt werden. # 1.3 Der POSIX-Standard ## 1.3 Der POSIX-Standard Der POSIX-Standard ist mittlerweile viel zu mächtig, um ihn zu ignorieren. Zwar werden Sie in diesem Buch damit kaum in Berührung kommen, aber in Anbetracht der Tatsache, dass viele Leser auch unter Linux/UNIX arbeiten und daher zwangsläufig früher oder später (meistens früher) mit POSIX in Kontakt kommen, sollten hier ein paar Zeilen darüber verloren werden. POSIX (Portable Operating System Interface for UniX) ist ein von der IEEE entwickeltes standardisiertes Applikationsebeneninterface, das die Schnittstelle zwischen einer Applikation und dem Betriebssystem UNIX darstellt. Sämtliche UNIX-Derivate halten sich mehr oder weniger an die in IEEE1003.1 (1990) und IEEE1003.2 (1992) festgelegten Standards, die heute die globale Industrienorm DIN/EN/ISO/IEC 9945 bilden. Der POSIX-Standard P1003.1 beinhaltete Standardkomponenten wie den Betriebssystemkern und C-Bibliotheken. Heute halten sich mehr oder weniger alle UNIX/Linux-Varianten an den POSIX-Standard. Selbst Microsoft Windows bietet eine POSIX-konforme Schnittstelle an, da vor allem in den USA POSIX eine wesentliche Voraussetzung der IT-Ausschreibungen im militärischen und öffentlichen Bereich ist. Natürlich existiert nicht nur ein POSIX-Standard für den Betriebssystemkern und die C-Bibliotheken. Weitere Standardkomponenten sind in Tabelle 1.1 aufgelistet. Bezeichnung | Bedeutung | | --- | --- | | | | | | | | | | | | | | | Auch wenn alle nur noch von »objektorientiert« reden, gibt es noch eine Menge guter Gründe dafür, C zu lernen. Hier sind einige davon: * Wenn Sie unter Linux/UNIX programmieren wollen oder müssen, kommen Sie ohnehin nicht um C herum. Das Betriebssystem ist zum gröÃten Teil in C implementiert. * C bietet die Konstrukte höherer Programmiersprachen. Beherrschen Sie C, dann ist es nicht mehr schwer, andere Programmiersprachen wie z. B. C++ oder Java zu erlernen. * Hardwarenahe Programmierung wird zumeist in C ausgeführt. * In C geschriebene Programme können einfach auf andere Systeme portiert werden. * C++ ist die Erweiterung zu C. Somit können Sie fast alles hier Gelernte später in C++ wiederverwenden. * In C lassen sich Programme schreiben, die schnell in der Ausführung sind und wenig Ressourcen benötigen. * Der Sprachumfang ist sehr klein: Der kleinste bekannte C-Compiler besteht aus 3742 Bytes C-Code und kann sich selbst kompilieren. * Es gibt einen Präprozessor zur Spracherweiterung und bedingten Ãbersetzung. Natürlich gibt es auch einige Nachteile der Programmiersprache C: * Eine allzu groÃe Freiheit beim Kodieren kann dazu führen, dass schwer lesbarer Code geschrieben wird. * Als Anfänger haben Sie bereits direkten Zugriff auf die Hardware und können somit vieles durcheinander bringen, wenn Sie nicht wissen, was Sie genau tun. * Fehler, die bei anderen Sprachen beim Compiler-Lauf abgeschaltet werden, werden unter Umständen nicht gefunden. Meist treten solche Fehler erst dann auf, wenn das Programm bereits freigegeben wurde. Nicht erwähnt wurde die gröÃte Stärke von C – die gleichzeitig bei unbedachtem Einsatz die gröÃte Schwäche ist: die uneingeschränkte Freiheit des Programmierers, mit Zeigern und Speicherstrukturen zu arbeiten. Es soll jedoch nicht unerwähnt bleiben, dass immer noch die meisten Programme in C geschrieben sind. Wenn solche Programme den Bedürfnissen einer Anwendergruppe angepasst oder allgemein verbessert werden müssen, sind gute C–Kenntnisse von Vorteil. Es stellt sich doch immer wieder heraus, dass viele (C–)Programmierer hauptsächlich damit beschäftigt sind, Fehler (Speicherlecks, Pufferüberläufe usw.) auszubügeln. # 1.5 C in diesem Buch ## 1.5 C in diesem Buch Im Rahmen dieses Buchs werde ich mich nicht ausschlieÃlich mit ANSI C befassen. In manchen Kapiteln ist das einfach nicht möglich. Aber ich werde die Programme – sofern das möglich ist – so schreiben, dass diese auf den gängigen Betriebssystemen wie Windows, MS-DOS unter einer Win32-Konsole (besser bekannt als MS-DOS-Eingabeaufforderung) oder Linux-artigen Systemen ausführbar sind. Falls ein Kapitel nicht dem ANSI-C-Standard entspricht, weise ich am Anfang gesondert darauf hin. # 1.6 Was benötige ich für C? ## 1.6 Was benötige ich für C? Leider ist aller Anfang schwer und erfordert Geduld. Bis Sie anfangen können, C zu lernen, brauchen Sie noch ein paar Dinge. Im Normalfall kosten sie aber kein Geld. ### 1.6.1 Texteditor Zuerst benötigen Sie einen beliebigen ASCII-Texteditor. Und davon gibt es ungefähr so viele wie Sand am Meer, egal für welches System. Ob Sie Emacs für UNIX oder unter MS-DOS den Dinosaurier Edit verwenden, bleibt Ihnen überlassen. Ich empfehle, einen Editor zu verwenden, der in der Lage ist, die Syntax von C farbig hervorzuheben. Dies erhöht die Ãbersichtlichkeit des Programms enorm. ### 1.6.2 Compiler Wenn der Quellcode mit dem Editor geschrieben und abgespeichert wurde, benötigen Sie als Nächstes einen Compiler. Dieser macht aus einer Quelldatei eine Objektdatei (Maschinencodedatei). Auf die genauen Arbeitsschritte eines Compilers (und des meist integrierten Linkers) gehe ich noch im Verlauf des Buches ein. Mittlerweile sind eine Menge Compiler kostenlos verfügbar. Viele davon lassen sich aus dem Internet herunterladen – und das für alle gängigen Betriebssysteme. Im Unterschied zu Microsoft-Betriebssystemen wird bei der Installation von Linux der GNU-GCC-Compiler normalerweise standardmäÃig mitinstalliert. Auswahl des Compilers | | --- | | ### 1.6.3 All-in-one – die Entwicklungsumgebung Die sogenannten Entwicklungsumgebungen werden immer beliebter. Wie der Name schon sagt, befindet sich alles, was Sie zum Programmieren benötigen, in einer Umgebung, also einem Fenster. Sie müssen nicht mehr mühevoll von einem zum anderen Fenster klicken, und Sie verlieren bei umfangreicheren Projekten nicht die Ãbersicht. Natürlich befindet sich in einer Entwicklungsumgebung mehr als nur der Compiler und ein ASCII-Texteditor. Weitere Hilfsprogramme, die Sie in einer solchen Umgebung typischerweise finden, sind: * ASCII-Texteditor * Compiler * Projektverwaltung * Debugger * Profiler * Versionskontrolle Solche Programm-Pakete haben aber meistens auch ihren Preis. Produkte von Borland und Microsoft kosten ab 100 Euro in der Standardversion bis zu ein paar Tausend Euro. Wenn Sie noch Anfänger sind, reicht es völlig aus, sich zunächst einen Ãberblick mithilfe der kostenlos erhältlichen Compiler zu verschaffen. Natürlich ist hier anzumerken, dass es mittlerweile auch einige kostenlose Varianten von Entwicklungsumgebungen gibt. Besonders zu erwähnen ist dabei die Code::Blocks-Entwicklungsumgebung, die für Microsoft-Systeme erhältlich ist. Für Linux existieren noch viel mehr gute Möglichkeiten, die keinen Eurocent kosten. # 1.7 Welcher Compiler und welches Betriebssystem? ## 1.7 Welcher Compiler und welches Betriebssystem? Wie ich bereits erwähnt habe, behandelt dieses Buch vorwiegend den ANSI-C-Standard und ist somit nicht von einem Compiler bzw. von dem Betriebssystem abhängig. Alle Listings in diesem Buch wurden auf mehreren gängigen Systemen und Compilern getestet. Natürlich ist es dennoch nicht auszuschlieÃen, dass es in Einzelfällen zu Fehlermeldungen kommen kann. In solch einem Fall würde ich mich über eine Mail von Ihnen freuen, damit dieses Problem bei der nächsten Auflage des Buchs beseitigt werden kann. # 2.2 »Hallo Welt« in C ## 2.2 »Hallo Welt« in C Obligatorisch ist es, mit dem berühmten »Hallo Welt«-Programm in C zu beginnen. Das Ziel dieses Programms ist es, die Textfolge »Hallo Welt« auf dem Bildschirm auszugeben. Tippen Sie im Texteditor (bzw. in der Entwicklungsumgebung) folgendes Programm ein: > /* hallo.c */ #include <stdio.h> int main (void) { printf("Hallo Welt\n"); return 0; } Zunächst wird das Programm in einem Verzeichnis, wo auch immer das Programm zur Ausführung gebracht werden soll, mit der Endung (Extension) *.c abgespeichert (wobei das Sternchen für den beliebigen Namen des Programms steht). Jetzt müssen Sie das Programm übersetzen (kompilieren). Dieser Vorgang kann von Compiler zu Compiler verschieden ablaufen. Bei einer Entwicklungsumgebung muss dabei häufig nur der Button Compile oder Kompilieren angeklickt werden. In einer Konsole wird das Programm mit der Kommandozeile übersetzt. Als Ergebnis findet sich im Verzeichnis ein ausführbares Programm namens hallo bzw. hallo.exe (sollten Sie das Programm hallo.c genannt haben). Diese Datei kann jetzt wie jede andere ausführbare Datei in der Kommandozeile gestartet werden. Abbildung 2.1 »Hallo Welt« in einem Konsolenfenster unter MS-DOS Bei Entwicklungsumgebungen dürfte meistens ein Klick auf Ausführen bzw. Run reichen. Wenn die Zeichenfolge »Hallo Welt« auf dem Bildschirm ausgegeben wird, ist es geschafft. Sie haben das erste Programm geschrieben und erfolgreich übersetzt! Abbildung 2.2 Das Programm »Hallo Welt« in einer Konsole unter Linux # 2.3 Analyse des Programms ## 2.3 Analyse des Programms Jetzt werden wir das erste Programm in seine einzelnen Bestandteile zerlegen und es uns Schritt für Schritt ansehen. > #include <stdio.hinclude ist kein direkter Bestandteil der Sprache C, sondern ein Befehl des Präprozessors. Der Präprozessor ist ein Teil des Compilers, der nicht das Programm übersetzt, sondern kontrollierend nicht bleibende Ãnderungen im Programmtext vornimmt. Diese Ãnderungen sind jedoch nur temporär. Präprozessorbefehle erkennen Sie am vorangestellten #-Zeichen. Kompilieren Sie das Programm noch einmal ohne #include <stdio.h>, dann sollte eine Fehlermeldung folgen, wie z. B. die folgende: > Error. function 'printf' should have a prototype. printf() kommt doch im Programm vor? Richtig. printf() ist eine (Standard–)Funktion, die in #include <stdio.h> deklariert ist. include-Dateien nennt man auch Headerdateien. Suchen Sie das Verzeichnis INCLUDE auf Ihrem System (unter Linux ist das typischerweise /usr/include oder /usr/bin/include und bei MS Windows z. B. C:\Name_des_Compilers\include), und Sie werden noch viele andere Headerdateien darin entdecken, die später noch Verwendung finden. Die Abkürzung stdio steht für Standard-Input/Output, also Standard-Ein-/Ausgabe. Ich werde noch öfter auf die Headerdateien eingehen, die ohnehin in jedem Programm benötigt werden. Später werden Sie auch eigene Headerdateien entwerfen und im Programm einbinden. Sehen wir uns nun weiter die Programmausführung an: > int main(void) Hier beginnt das Hauptprogramm. Eine main-Funktion wird immer benötigt, damit der Compiler weiÃ, wo er beginnen muss, das Programm zu übersetzen. Auch wenn später mehrere Module (Funktionen), also mehrere Quellcode-Dateien, kompiliert werden (d. h. zu einer ausführbaren Datei gebunden werden), benötigen Sie immer eine main-Funktion. main heiÃt auf Deutsch so viel wie »Hauptfunktion«. Das void in der main()-Funktion steht für einen »leeren« Datentyp (mehr dazu später). void könnten Sie hier auch ganz weglassen – allerdings soll hier nicht unerwähnt bleiben, dass () und (void) in C++ nicht dasselbe sind. Sofern Sie also Ihre Programme erweitern wollen, sollten Sie es gleich mit angeben. int steht für eine Ganzzahl. Im Fall einer Funktion bedeutet dies, dass sie einen Rückgabewert hat, der vom Typ int ist. In diesem Programm bekommt die main-Funktion den Rückgabewert 0 durch folgenden Aufruf: > return 0; Das bedeutet: Das Programm wurde ordnungsgemäà beendet. Es wird also mit return hier der Funktion main der Wert 0 zurückgegeben. Genaueres dazu (zur main()-Funktion und deren Rückgabewerten) erfahren Sie in einem späteren Kapitel. Wir machen zunächst mit > { printf("....."); } weiter. Zwischen den geschweiften Klammern steht der Anweisungsblock. Das heiÃt, in diesem Block befinden sich alle Anweisungen, die die Funktion int main() auszuführen hat. Natürlich können innerhalb eines Anweisungsblocks weitere Anweisungsblöcke verwendet werden. Das hört sich komplizierter an, als es ist. Darauf gehe ich später noch ein. Und was geschieht in diesem Anweisungsblock? > printf("Hallo Welt\n"); printf() ist eine Funktion, die in der Headerdatei stdio.h deklariert ist, wie bereits erwähnt wurde. Deswegen kann der Compiler, wenn Sie diese Headerdatei nicht im Programm angegeben haben, nichts mit printf() anfangen. Mit der Funktion printf() kann eine beliebige Stringkonstante formatiert auf dem Bildschirm ausgegeben werden. Die Stringkonstante, in diesem Fall »Hallo Welt«, die ausgegeben wird, steht immer zwischen zwei Hochkommata ("Stringkonstante"). Es ist nicht erlaubt, eine Stringkonstante über das Zeilenende fortzusetzen, wie etwa im folgenden Beispiel: > printf("Dies ist in C nicht erlaubt"); Es gibt aber eine Ausnahme von dieser Regel: indem Sie einen \ (Backslash) setzen. Hierzu ein Beispiel: > printf("Hier ist die Ausnahme von der Regel \ dies hier ist erlaubt, dank Backslash"); Sie sollten aber dabei beachten, dass alle Leerzeichen nach dem Backslash in der nächsten Zeile ebenfalls bei der Ausgabe berücksichtigt werden. Das Zeichen '\n' in der Funktion von printf() ist ein Steuerzeichen. Es bedeutet newline und erzeugt auf dem Bildschirm einen Zeilenvorschub, wie er mit der Tastatur durch die Taste ausgelöst wird. Kommen wir jetzt zum Semikolon (;): Es wird hauptsächlich dazu verwendet, das Ende einer Anweisung anzuzeigen. Der Compiler weià dann, dass hier das Ende der Anweisung von printf()ist, und fährt nach der Abarbeitung der Anweisung mit der nächsten Zeile bzw. Anweisung fort. Natürlich hat das Semikolon keine Wirkung, wenn es in einer Stringkonstante verwendet wird: > printf("Hallo; Welt\n"); Ausgabe: > Hallo; Welt # 3.2 Symbole von C ## 3.2 Symbole von C Wie in jeder anderen Sprache auch, gibt es in C einige gültige Symbole, die Sie kennen sollten. ### 3.2.1 Bezeichner Den Begriff Bezeichner verwendet man für Namen von Objekten im Programm. Dazu gehören Variablen, Funktionen usw. Ein gültiger Bezeichner darf aus beliebigen Buchstaben, Ziffern und dem Zeichen _ (Unterstrich) bestehen. Allerdings darf das erste Zeichen niemals eine Ziffer sein. Beachten Sie auÃerdem, dass C++ zwischen GroÃ- und Kleinbuchstaben (englisch: case sensitive) unterscheidet. Somit sind »Hallo«, »hallo« und »HALLO« drei verschiedene Bezeichner. Regeln für Bezeichner | | --- | | ### 3.2.2 Schlüsselwörter Schlüsselwörter sind Bezeichner mit einer vorgegebenen Bedeutung in C. Sie dürfen nicht anderweitig verwendet werden. So dürfen Sie beispielsweise keine Variable mit dem Bezeichner »int« verwenden, da es auch einen Basisdatentyp hierzu gibt. Der Compiler würde sich ohnehin darüber beschweren. Eine Liste der Schlüsselwörter in C finden Sie in Anhang A.3. ### 3.2.3 Literale Als Literale werden Zahlen, Zeichenketten und Wahrheitswerte im Quelltext bezeichnet, die ebenfalls nach einem bestimmten Muster aufgebaut sein müssen. Man kann auch sagen: Literale sind von einer Programmiersprache definierte Zeichenfolgen zur Darstellung der Werte von Basistypen. # Ganzzahlen Man unterscheidet bei Ganzzahlen zwischen Dezimal-, Oktal- und Hexadezimalzahlen, für die folgende Regeln gelten: * Dezimalzahlen (Basis 10) – Eine Dezimalzahl besteht aus einer beliebig langen Ziffernreihe aus den Zeichen 0 bis 9. Die erste Ziffer darf allerdings keine 0 sein. * Oktalzahlen (Basis 8) – Eine Oktalzahl hingegeben beginnt immer mit einer 0, gefolgt mit einer Reihe von Oktalzahlen (0–7). * Hexadezimalzahlen (Basis 16) – Eine Hexadezimalzahl beginnt immer mit der Sequenz 0x bzw. 0X, gefolgt von einer Reihe von Hexadezimalzahlen (0–F = 0 1 2 3 4 5 6 7 8 9 A B C D E F (oder Kleinbuchstaben: a b c d e f)). Man kann hinter den Dezimal-, Oktal- und Hexadezimalzahlen noch ein Suffix anhängen, um den Wertebereich einer Zahl genauer zu spezifizieren. Das Suffix u bzw. U deutet beispielsweise an, dass es sich um eine vorzeichenlose (unsigned) Zahl handelt. l bzw. L gibt an, dass es sich um eine long-Zahl handelt. In Tabelle 3.3 sehen Sie einige Beispiele, wobei die Zahlen in einer Reihe immer gleichwertig sind. Dezimalzahl | Oktalzahl | Hexadezimalzahl | | --- | --- | --- | | | | | | | | | | # FlieÃkommazahlen Wie eine korrekte FlieÃkommazahl dargestellt wird, wird in Abschnitt 5.8 genauer beschrieben, wenn es um die Basistypen von FlieÃkommazahlen geht. Wie bei den Ganzzahlen können Sie den FlieÃkommazahlen ebenfalls ein Suffix hinzufügen. Mit dem Suffix f oder F kennzeichnen Sie eine FlieÃkommazahl mit einer einfachen Genauigkeit. Das Suffix l oder L hingegen deutet auf eine FlieÃkommazahl mit erhöhter Genauigkeit hin. # Einzelne Zeichen Ein Zeichenliteral wird zwischen einfache Hochkommata (Single Quotes) eingeschlossen ('A', 'B', 'C', ... '$', '&' usw.). Wenn Sie nichtdruckbare Zeichen wie beispielsweise einen »Tabulator« oder »Zeilenvorschub« darstellen wollen, müssen Sie eine Escape-Sequenz (auch Steuerzeichen genannt) verwenden. Escape-Sequenzen werden mit einem Backslash (\) eingeleitet (z. B. ein Tabulator = '\t' oder ein Zeilenvorschub = '\n'). # Zeichenketten Eine Zeichenkette (häufig auch String genannt) ist eine Sequenz von Zeichen, die zwischen doppelte Hochkommata (Double Quotes) gestellt werden (beispielsweise "Ich bin eine Zeichenkette"). Es ist im Zusammenhang mit einer Zeichenkette sehr wichtig zu wissen, dass jede dieser Ketten um ein Zeichen länger ist, als (sichtbar) dargestellt. Gewöhnlich werden Zeichenketten durch das Zeichen mit dem ASCII-Wert 0 (nicht der dezimalen Null) abgeschlossen (0x00 oder als einzelnes Zeichen '\0'). Diese ASCII-0 kennzeichnet immer das Ende einer Zeichenkette. Somit enthält beispielsweise die Zeichenkette "C++" vier Zeichen, weil am Ende auch das Zeichen 0x00 (oder auch '\0') abgelegt ist. ### 3.2.4 Einfache Begrenzer Um die Symbole voneinander zu trennen, benötigt man in C Begrenzer. In diesem Abschnitt wird nur auf einfache Begrenzer hingewiesen. Weitere solcher Begrenzer werden Sie im Verlauf des Buches näher kennenlernen. # Das Semikolon (;) Der wichtigste Begrenzer dürfte das Semikolon ; (Plural: Semikola und Semikolons) sein, das auch Strichpunkt genannt wird. Es dient als Abschluss einer Anweisung. Jeder Ausdruck, der mit einem solchen Semikolon endet, wird als Anweisung behandelt. Der Compiler weià dann, dass hier das Ende der Anweisung ist, und fährt nach der Abarbeitung der Anweisung (Befehl) mit der nächsten Zeile bzw. Anweisung fort. Natürlich hat das Semikolon keine Wirkung, wenn es in einer Stringkonstante verwendet wird: > "Hallo; Welt" # Komma Mit dem Komma trennt man gewöhnlich die Argumente einer Funktionsparameterliste oder bei der Deklaration mehrere Variablen desselben Typs. # Geschweifte Klammern Zwischen den geschweiften Klammern (amerikanisches Englisch: braces, britisches Englisch: curly brackets) wird der Anweisungsblock zusammengefasst. In diesem Block befinden sich alle Anweisungen (abgeschlossen mit einem Semikolon), die in einer Funktion ausgeführt werden sollen. Beispielsweise sind beim Listing hallo.c alle Anweisungen der main-Funktion zwischen den geschweiften Klammern zusammengefasst: > int main(void) { printf("Hal<NAME>!"); return 0; } Hier wird lediglich die Textfolge »Hal<NAME>!« auf dem Bildschirm ausgegeben und mit return der Wert 0 an den aufrufenden Prozess zurückgegeben. Mehr zur main-Funktion und deren Rückgabewert erfahren Sie etwas später in den Abschnitten 9.16 und 9.17. # Das Gleichheitszeichen (=) Mit dem Gleichheitszeichen trennt man die Variablendeklaration von den Initialisierungslisten: > Typ bezeichner = wert; ### 3.2.5 Kommentare Kommentare sind Textteile in einem C-Quelltext, die vom Compiler ignoriert werden. Kommentare können an einer beliebigen Stelle im Quelltext stehen. Kommentare können auf eine Programmzeile beschränkt sein oder sich über mehrere Zeilen erstrecken. In den weiteren Programmen, die jetzt folgen, wird es häufiger vorkommen, dass der Quellcode dokumentiert ist, genauer gesagt, dass Kommentare eingefügt sind. Diese Kommentare werden vom Compiler ignoriert. Wie Sie Ihren Quellcode dokumentieren, bleibt letztlich Ihnen selbst überlassen. Sie können beliebig viel, alles oder auch gar nichts dokumentieren. # Wann sind Kommentare sinnvoll? Kommentare sind eigentlich immer sinnvoll. Wenn Sie vorhaben sollten, ein gröÃeres Projekt zu verwirklichen, kann sich dies über mehrere Monate hinausziehen. Um das Stückchen Quellcode, das Sie vor einem Monat geschrieben haben, nicht immer wieder von Neuem verstehen zu müssen, können Sie ein paar Kommentare mit Erklärungen einfügen. In einer Gruppe ist es ohnehin unerlässlich, mit Kommentaren zu arbeiten, damit jeder den Code des anderen besser versteht und nachvollziehen kann. Hierzu ein Beispiel: > /* kommentare.c */ #include <stdio.h> int main (void) { //Beginn des Hauptprogramms int i = 10; //Variable int mit dem Namen i und Wert 10 printf("%d",i); //Gibt die Zahl 10 aus. printf("\n"); //Springt eine Zeile weiter. printf("10"); //Gibt den String "10" aus. return 0; /* Hier sehen Sie noch eine 2. Möglichkeit, Kommentare einzufügen. Dieser Kommentar wird mit einem Slash- Sternchen eröffnet und mit einem Sternchen-Slash wieder beendet. Alles dazwischen wird vom Compiler ignoriert. */ } Kommentare sind nicht schwer zu verstehen. Sie werden einfach hinter zwei // oder zwischen /* Hier steht der Kommentar */ geschrieben. Häufig werden Kommentare vor Funktionen geschrieben. Ein guter Stil könnte so aussehen: > /****************************** * * * Beschreibung der Funktion * * Parameter1 : ... * * Parameter2 : ... * * Rückgabewert : ... * * * ******************************/ In den Kommentaren können Sie beliebige Zeichen verwenden, also auch deutsche Umlaute oder das Dollarzeichen. # Welche Kommentar-Schreibweise? – // oder /* */ Da Sie zwei Möglichkeiten haben, Kommentare zum Programm hinzuzufügen, stellt sich die Frage, welche Methode von den beiden die bessere ist. Die folgende Schreibweise wurde erst im Oktober 1999 zum C99-Standard hinzugefügt: > // Kommentar Dieser Stil war zuvor nur für C++ erlaubt und im C89-Standard nicht zugelassen. Problematisch könnte dies werden, wenn Sie einen etwas älteren Compiler verwenden. Er würde einen solchen Kommentar als Fehler bemängeln und sich weigern, das Programm zu übersetzen. Etwas müssen Sie auÃerdem noch beachten, wenn Sie die Schreibweise // verwenden. Sehen Sie sich dazu folgendes Listing an: > /* kommentare_fehler.c */ #include <stdio.h> int main(void) { //das Programm befindet sich im Pfad C:\programme\ printf("Hallo Welt\n"); return 0; } »Hallo Welt« wird niemals ausgegeben. Der Grund dafür ist, dass die Zeile mit dem Kommentar mit einem Backslash endet. Achten Sie also darauf, dies zu vermeiden, denn die Suche nach diesem Fehler könnte unnötig Zeit kosten. Wenn Sie auÃerdem eine etwas höhere Warnstufe des Compilers (beispielsweise das Flag -Wall beim GCC) verwenden, wird dieser Sie auch darauf hinweisen, dass der Kommentar nicht in Ordnung ist (beispielsweise mit warning: multi-line comment). # 4.2 Formatierte Ausgabe mit »printf()« ## 4.2 Formatierte Ausgabe mit »printf()« Die Syntax von printf() sieht so aus: ``` #include <stdio.hint printf(const char * restrict format, ...); ``` Der Rückgabewert von printf() ist die Anzahl der Zeichen, die ausgegeben werden (ohne das Terminierungszeichen '\0'), oder im Fehlerfall EOF. Folgendes Beispiel demonstriert dies: > /* printf1.c */ #include <stdio.h> int main(void) { int zeichen; zeichen = printf("<NAME>"); printf(" enthaelt %d Zeichen\n", zeichen); // 10 Zeichen return 0; } printf() bekommt mindestens einen Parameter, nämlich den Formatstring. Dieser Formatstring besteht wiederum aus einem Ausgabetext (Stringkonstante), der nullterminiert ist (\0), und/oder aus einer Formatanweisung. Abbildung 4.6 »printf()«, in seine einzelnen Bestandteile zergliedert Bei dem Formatstring handelt es sich um eine Zeichenkette beliebiger Länge. Zum Beispiel: > printf("Ich bin der Formatstring in der printf-Anweisung"); Die Funktion printf() wird bei der Ausführung von rechts nach links abgearbeitet. Dabei sucht die Funktion nach einem Ausgabetext (Stringkonstante) und Formatanweisungen. Diese Formatanweisung wird von printf() dann mit entsprechenden Parametern der variablen Liste ausgegeben. Formatanweisungen beginnen alle mit einem %-Zeichen. Dahinter folgt ein Buchstabe, der den Datentyp des Formates angibt. %d steht z. B. für eine dezimale Ganzzahl. Die Formatanweisung lässt sich natürlich noch erweitert formatieren. Bevor ich die einzelnen und erweiterten Formatanweisungen vorstelle, folgt erst einmal ein Kapitel, das zeigt, was für Datentypen Sie überhaupt zur Verfügung haben. Die Ausgabe von printf() muss übrigens nicht ausschlieÃlich auf dem Bildschirm erfolgen. Sie können die Standardausgabe (stdout) auch in eine Datei umleiten: > /* printf2.c */ #include <stdio.h> int main(void) { printf("Diese Ausgabe soll in einer Textdatei stehen\n"); return 0; } Ãbersetzen Sie dieses Programm wie gewohnt, und starten Sie es, indem Sie in einer Konsole Folgendes eingeben (als Programmname sei hier out gegeben): `$ out > test.txt` Jetzt befindet sich im aktuellen Verzeichnis eine Datei namens test.txt mit dem Inhalt, den printf() normalerweise auf dem Bildschirm ausgegeben hätte. # 5.2 Der Datentyp »int« (Integer) ## 5.2 Der Datentyp »int« (Integer) Der Datentyp int muss, gemäà ANSI C, mindestens eine GröÃe von zwei Byte aufweisen. Mit diesen zwei Bytes lässt sich ein Zahlenraum von -32768 bis +32767 beschreiben. Mit dem Datentyp int lassen sich nur Ganzzahlen darstellen. Die Abkürzung int steht für Integer. Hier kommen Sie auch gleich mit betriebssystemspezifischen Eigenheiten in Berührung. Auf 16-Bit-Systemen mag das eben Gesagte zutreffen. Dort ist ein Integer (int) auch wirklich zwei Bytes groÃ. Manch einer wird aber sagen: 16-Bit-Systeme sind doch Schnee von gestern und eigentlich nur noch für MS-DOS- und Windows-3.1-Compiler relevant. Denken Sie aber daran, dass es noch andere Programmierplattformen neben Linux und MS Windows gibt (besonders wären hier die Embedded Systems und Mikrocontroller hervorzuheben), wo C seine Stärken ausspielen kann! Linux, Windows (ab Windows 95) und Macintosh sind alles schon Betriebssysteme auf 32-Bit-Basis. 32 Bit entsprechen vier Byte. Somit erstreckt sich der Zahlenraum auf 32-Bit-Systemen von -2147483648 bis +2147483647. Ein int hat somit laut Standard die natürliche GröÃe, die von der »Ausführ-Umgebung« vorgeschlagen wird. Das wären dann z. B. auf einer PDP10-Maschine 36 Bit, auf einem Pentium 4 32 Bit und auf einem beliebigen 64-Bit-Prozessor-System eben 64 Bit. Tabelle 5.1 gibt einen kurzen Ãberblick über den Datentyp int und seinen möglichen Wertebereich auf den verschiedenen Systemen: # 5.3 Variablen verwenden ## 5.3 Variablen verwenden Wie Sie Datentypen in der Praxis verwenden, also deklarieren und mit Werten initialisieren können, soll jetzt grundsätzlich anhand des Datentyps int erläutert werden. Für andere Datentypen, die noch behandelt werden, gilt dies entsprechend. Sehen wir uns dazu ein Listing an: > /* deklarieren.c */ #include <stdio.h> int main(void) { int a; // Deklaration int b; int c; a = 5; // Initialisieren b = 100; c = 12345; printf("Wert von int a=%d ,b=%d, c=%d\n", a, b, c); return 0; } Hier werden drei int-Variablen mit den Bezeichnern a, b und c deklariert. Die Auswahl der Bezeichner bleibt dabei Ihnen überlassen. In kleinen Programmbeispielen ist die Verwendung sogenannter sprechender Namen für Bezeichner nicht unbedingt erforderlich, dennoch empfehle ich Ihnen, aussagekräftige Namen (z. B. ZuFallsZahl, statt einfach nur z) zu verwenden. Damit behalten Sie bei gröÃeren Projekten den Ãberblick. Hier bekommt a den Wert 5, b den Wert 100 und c den Wert 12345 zugewiesen. Die Zuweisung eines Werts wird das Initialisieren einer Variable genannt. Den Wert einer Variablen übergibt man mit dem =-Operator (er wird auch Zuweisungsoperator genannt). Folgende Schreibweisen sind dabei erlaubt: > int wert = 5; // wert=5 int wert1 = 10, wert2 = 20; // wert1=10 ,wert2=20 // wert1=nicht initialisiert, wert2=33 int wert1, wert2 = 33; int wert1; int wert2 = wert1 = 10; // wert1=10, wert2=10 Jetzt folgt die Beschreibung der Ausgabe mit printf() (siehe Abbildung 5.1). Sicherlich ist Ihnen %d im Formatstring aufgefallen. Das Prozentzeichen ist ein Formatzeichen. Der Compiler sieht jetzt nach, um welches Format es sich dabei handelt. Im Beispiel ist es das d (für dezimal). Sie können auch das Formatzeichen %i anstelle von %d benutzen. Für einige ist das leichter zu verstehen, da das i für Integer steht. Hiermit wird also eine Ganzzahl (int) ausgegeben. Hinter dem Ende der Hochkommata befindet sich jetzt der Variablenname a. Damit wird der Wert von int a an der Position ausgegeben, an der sich das Formatzeichen %d befindet. Gleiches geschieht mit den anderen beiden int-Werten für b und c. Die Initialisierung dieser Werte kann aber auch noch anders bewerkstelligt werden: > /* initialisieren.c */ #include <stdio.h> int main(void) { int a=5; int b=100, c=12345; printf("Wert von int a=%d ,b=%d, c=%d\n", a, b, c); return 0; } Abbildung 5.1 Der Ablauf der Funktion »printf()« Wie Sie hier sehen, kann die Wertzuweisung schon während der Deklaration vorgenommen werden. Es können auch alle Werte auf einmal zugewiesen werden, wie es bei int b und int c geschehen ist. Die Werte müssen mit einem Komma getrennt werden. Wenn eine Variable nicht mit einem Wert initialisiert wurde und Sie diese dennoch ausgeben, ist die Ausgabe des Werts undefiniert. Das heiÃt, es ist nicht vorhersehbar, welcher Wert ausgegeben wird. # Erlaubte Bezeichner Im Folgenden gehe ich nochmals detaillierter auf die erlaubten Bezeichner ein. Mit dem Begriff Bezeichner werden Namen für Variablen, Funktionen, Datentypen und Makros zusammengefasst. Damit Sie bei der Namensvergabe von Variablen oder (später) Funktionen keine Probleme bekommen, müssen Sie bei deren Angabe folgende Regeln beachten: * Ein Bezeichner darf aus einer Folge von Buchstaben, Dezimalziffern und Unterstrichen bestehen. Einige Beispiele: * var8, _var, _666, var_fuer_100tmp, VAR, Var * C unterscheidet zwischen GroÃ- und Kleinbuchstaben. * Var, VAr, VAR, vAR, vaR, var * Hierbei handelt es sich jeweils um verschiedene Bezeichner. * Das erste Zeichen darf keine Dezimalzahl sein. * Die Länge des Bezeichners ist beliebig lang. Nach ANSI-C-Standard sind aber nur die ersten 31 Zeichen von Bedeutung. Allerdings können viele Compiler auch zwischen mehr Zeichen unterscheiden. Die reservierten Schlüsselwörter in C dürfen logischerweise auch nicht als Bezeichner verwendet werden. Folgende Schlüsselwörter sind in C reserviert: > auto break case char complex const continue default do double else enum extern float for goto if imaginary inline int long register restrict return short signed sizeof static struct switch typedef union unsigned void volatile while Die Schlüsselwörter, die hier nicht fett dargestellt wurden, sind erst bei den neueren Compilern (C99) vorhanden. # 5.4 Der Datentyp »long« ## 5.4 Der Datentyp »long« Der Datentyp long entspricht wie der Datentyp int auch einer Ganzzahlvariablen. Bei 16-Bit-Systemen hat dieser Typ einen gröÃeren Zahlenbereich und verbraucht somit auch mehr Speicherplatz als der Datentyp int. Hier ein Vergleich mit dem Datentyp int auf einem 16-Bit-System: Den Datentyp long können Sie benutzen, wenn Berechnungen mit gröÃeren Zahlen durchführt werden. Das Formatzeichen ist hier %ld oder %li, von »long dezimal« bzw. »long integer«. long ist also nichts anderes als ein gröÃeres int, und genauso kann es auch benutzt werden. Mit dem Datentyp long kann der Datentyp int auf 16-Bit-Systemen modifiziert werden, sodass der Wertebereich von int vergröÃert wird: > long int a; Jetzt stellt sich die Frage, welche Daseinsberechtigung hat der Datentyp long dann eigentlich noch auf 32-Bit-Systemen? long hat ja auf diesen Systemen dieselbe GröÃe und denselben Wertebereich wie der Datentyp int. Die Antwort könnte lauten: Es gibt ihn aus Kompatibilitätsgründen, damit alte Programme, die für 16-Bit-Rechner geschrieben wurden, auch noch auf einem 32-Bit-Rechner laufen bzw. übersetzt werden können. Das gilt auch für den umgekehrten Fall. Dies sollten Sie beachten, wenn Sie ein Programm für ein 32-Bit-System geschrieben haben und es dann auf ein 16-Bit-System portieren wollen. In diesem Fall ist es empfehlenswert, den Datentyp long zu verwenden. Sollte bei einem Programm auf dem 16-Bit-Rechner eine Zahl, z. B. »1000000«, vorkommen, und es wurde der Datentyp int verwendet, wird das Programm mit falschen Werten rechnen und möglicherweise völlig unvorhergesehene Reaktionen zeigen. # 5.5 Der Datentyp »long long« ## 5.5 Der Datentyp »long long« Neu (seit dem C99-Standard) ist der erweiterte long-Datentyp. long long ist ein 64 Bit (8 Byte) breiter Datentyp, der einen Wertebereich von –9.223.372.036.854.755.808 bis +9.223.372.036.854.755.807 darstellen kann. # 5.6 Der Datentyp »short« ## 5.6 Der Datentyp »short« Nach der Betrachtung der Typen int und long stellt sich die Frage: Was ist, wenn ich gar keine so groÃe Ganzzahl benötige? Beziehungsweise, was ist, wenn das Programm nicht so viel Speicherplatz verbrauchen darf? Dafür gibt es den Datentyp short, der genauso verwendet wird wie schon int und long. Hier die Angaben zu short: Ab dem C99-Standard finden sich in der Headerdatei <stdint.h> weitere Ganzzahldatentypen, die mit vorgegebener Breite verwendet werden. Mit vorgegebener Breite ist die Anzahl der Bits zur Darstellung des Werts gemeint, die dieser Typ verwenden darf. Hier die Typen im Ãberblick: Typen, die mit u (unsigned) beginnen, sind vorzeichenlos. Von den in der Tabelle aufgelisteten Typen wiederum werden vom C99-Standard nur int_leastN_t, int_fastN_t und intmax_t und deren unsigned-Gegenstücke gefordert. Die anderen beiden Typen sind optional und müssen nicht implementiert sein. Die maximalen und minimalen Limits dieser Ganzzahltypen sind ebenfalls in der Headerdatei <stdint.h> deklariert. Bei den Namen der Limits brauchen Sie nur den Typnamen groÃschreiben und das Suffix _t gegen _MIN bzw. _MAX austauschen. So lautet beispielsweise der Makroname für den minimalen bzw. maximalen int_least32_t-Wert INT_LEAST32_MIN bzw, INT_LEAST32_MAX. Hierzu ein einfaches Listing als Beispiel: > /* stdint.c */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> int main(void) { int_least8_t i8; int_least32_t i32; int_least64_t i64; // beispielsweise Linux: -128 und 127 printf("int_least8_t/Max. : %d; Min : %d\n", INT_LEAST8_MAX, INT_LEAST8_MIN ); // beispielsweise Linux: -2147483648 und 2147483647 printf("int_least32_t/Max.: %d; Min : %d\n", INT_LEAST32_MIN, INT_LEAST32_MAX ); // beispielsweise Linux: -9223372036854775808 und // 9223372036854775807 printf("int_least64_t/Max.: %lld; Min: %lld\n", INT_LEAST64_MIN, INT_LEAST64_MAX ); return EXIT_SUCCESS; } Im Grunde sind diese erweiterten Typen in der Headerdatei <stdint.h> nur Synonyme für Standardtypen. So sind beispielsweise in <stdin.h> folgende Zeilen enthalten: > // ... typedef signed char int_least8_t; typedef short int int_least16_t; typedef int int_least32_t; // ... Abhängig von der WortgröÃe ist dann beispielsweise int_least64_t als long int oder long long int implementiert. ### 5.7.1 <inttypes.h> (C99) Auch der Header <inttypes.h> inkludiert die Headerdatei <stdint.h> und verwendet hier die ganzzahligen Datentypen mit einer bestimmten Breite – ganz besonders die Typen intmax_t und uintmax_t, womit die gröÃtmöglichen Typen dargestellt werden. Neben einigen Funktionen beinhaltet diese Headerdatei auch Makros, die als Konvertierungsspezifizierer im Formatstring von printf() und scanf() verwendet werden können. Hierfür gibt es für jeden in <stdint.h> definierten Typ bestimmter Breite ein entsprechendes Makro mit dem Präfix PRI (für printf()) oder SCN (für scanf()), gefolgt vom Konvertierungspezifizierer d, i, o oder x und dem Typnamen. Im Falle von beispielsweise int_least8_t sehen die Konvertierungsspezifizierer für printf() und scanf() wie folgt aus: > SCNdLEAST8 // für scanf() PRIdLEAST8 // für printf() Oder für den Typ int_fast32_t: > SCNdFAST32 // für scanf() PRIdFAST32 // für printf() In der Praxis sieht die Verwendung der Konvertierungsspezifizierer für Typen einer bestimmten Breite, die in der Headerdatei <inttypes.h> als Makro definiert sind, wie folgt aus: > /* inttypes.c */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <inttypes.h> int main(void) { int_least8_t i8; int_least32_t i32; printf("Wert für int_least8_t eingeben : "); scanf("%" SCNdLEAST8 , &i8 ); printf("Wert für int_least32_t eingeben: "); scanf("%" SCNdLEAST32 , &i32 ); printf("i8 : " "%10" PRIdLEAST8 "\n", i8 ); printf("i32 : " "%10" PRIdLEAST32 "\n", i32 ); return EXIT_SUCCESS; } Die Konvertierung funktioniert hier mit einer Verkettung der Stringliterale "%" und dem entsprechenden Konvertierungsspezifizierer. # 5.8 Die Gleitpunkttypen »float« und »double« ## 5.8 Die Gleitpunkttypen »float« und »double« Jetzt kommen wir zu den Gleitpunkttypen (Floatingpoint). Mit ihnen wird es möglich, genauere Berechnungen mit Nachkommastellen auszuführen. Hier wieder zuerst eine kleine Ãbersicht: Name | GröÃe | Wertebereich | Genauigkeit | Formatzeichen | | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | Beachten Sie, dass die GröÃenangaben und Wertebereiche dieser Typen komplett implementierungsabhängig sind. Es ist lediglich gewährleistet, dass bei float, double und long double (hier von links nach rechts) jeder Typ den Wert des vorherigen aufnehmen kann. Angewendet wird dieser Datentyp genauso wie int und alle anderen Datentypen, die Sie bereits kennen. Hierzu eine kurze Erklärung, warum es Gleitpunkttyp und nicht Gleitkommatyp heiÃt. Dies liegt daran, dass die Programmiersprache C in den USA entwickelt wurde. Und dort wird anstatt eines Kommas zwischen den Zahlen ein Punkt verwendet (man spricht von floating point variables): > float a=1,5; /* FALSCH */ float b=1.5; /* RICHTIG */ Das Komma verwenden die US-Amerikaner wiederum genauso wie Europäer den Punkt bei gröÃeren Zahlen. Folgendes Beispiel schreiben wir (Europäer) so: > 1.234.567 Und die US-Amerikaner schreiben dies wiederum so: > 1,234,567 Dazu ein Beispiel. Es wird ein Programm geschrieben, das die Fläche eines Rechtecks berechnet. > /* rectangle.c */ #include <stdio.h> int main(void) { /* Deklaration */ float flaeche, l, b; printf("Berechnung der Flaeche eines Rechtecks\n"); /* Werte einlesen */ printf("Laenge des Rechtecks: "); scanf("%f",&l); printf("Breite des Rechtecks: "); scanf("%f",&b); /* Fläche berechnen */ flaeche = l * b; printf("Flaeche des Rechtecks betraegt : %f\n",flaeche); return 0; } Bei diesem Listing wird der Anwender nach der Länge und der Breite einer rechteckigen Fläche gefragt. Diese Gleitpunktzahl wird mithilfe von scanf() eingelesen und an die Adressen der Variablen l und b übergeben. AnschlieÃend wird dieser Wert zur Berechnung verwendet. Das Ergebnis wird am Schluss des Programms auf dem Bildschirm ausgegeben. Beachten Sie im Zusammenhang mit Gleitpunktzahlen auch Folgendes: Wenn Sie zwei verschiedene Variablen z. B. int und float miteinander durch Operatoren verknüpfen, erhalten Sie das Ergebnis vom genaueren Datentyp dieser beiden Variablen zurück. Ein Beispiel: > /* divide.c */ #include <stdio.h> int main(void) { float f = 5.0; int i = 2; printf("%f\n",f/i); // Ergebnis = 2.500000 return 0; } Die Ausgabe des Programms ist »2.500000«, weil der genauere der beiden Datentypen hier vom Typ float ist. ### 5.8.1 Gleitpunkttypen im Detail Bei Gleitpunkttypen wird auch von Zahlen mit gebrochenem Anteil (reellen Zahlen) gesprochen. Der C-Standard schreibt hierbei nicht vor, wie die interne Darstellung von reellen Gleitpunktzahlen erfolgen muss. Dies hängt von den Entwicklern der Compiler ab. Meistens wird aber der IEEE-Standard 754 verwendet (IEEE – Institute of Electrical and Electronics Engineers). In der Regel kann es dem Programmierer egal sein, wie Gleitpunktzahlen auf seinem System dargestellt werden. Trotzdem folgt hier für den interessierten Programmierer eine kurze Erklärung der internen Darstellung von Gleitpunktzahlen, ohne dass wir uns zu sehr in den Details verlieren wollen. Gleitpunktzahlen werden halb logarithmisch dargestellt. Das heiÃt, die Darstellung einer reellen Gleitpunktzahl basiert auf einer Zerteilung in ein Vorzeichen, eine Mantisse und einen Exponenten zur Basis 2. Für echte Mathematiker sei gesagt, dass der Begriff »Mantisse« hier nichts mit einer Mantisse eines Logarithmus gemeinsam hat. Die Genauigkeit nach dem Komma der Gleitpunktzahl hängt von der Anzahl der Bits ab, die der entsprechende reelle Datentyp in seiner Mantisse speichern kann. Der Wertebereich hingegen wird durch die Anzahl der Bits für den Exponenten festgelegt. Hierzu folgen die Speicherbelegungen der einzelnen reellen Gleitpunktzahlen im IEEE-Format. ### 5.8.2 »float« im Detail float ist eine 32-Bit-Zahl. Diese 32 Bit teilen sich folgendermaÃen auf: Abbildung 5.2 »float« im Detail * Vorzeichen-(Vz-)Bit (1 Bit): In Bit 31 wird das Vorzeichen der Zahl gespeichert. Ist dieses 0, dann ist die Zahl positiv, bei 1 ist sie negativ. * Exponent (8 Bits): In Bit 23 bis 30 wird der Exponent mit einer Verschiebung (Bias) der Zahl gespeichert (Bias bei float 127). ### 5.8.3 »double« im Detail Beim Datentyp double ist es ähnlich wie bei float. double ist eine 64-Bit-Zahl mit doppelter Genauigkeit. double ist folgendermaÃen aufgeteilt: Abbildung 5.3 »double« im Detail * Vorzeichen-Bit (1 Bit): In Bit 63 wird das Vorzeichen der Zahl gespeichert. Ist dieses 0, dann ist die Zahl positiv, bei 1 ist sie negativ. * Exponent (11 Bit): In Bit 52 bis 62 wird der Exponent mit einer Verschiebung (Bias) der Zahl gespeichert (Bias bei double 1023). ### 5.8.4 long double Wird dem Datentyp double das Schlüsselwort long vorangestellt, erhalten Sie eine 80-Bit-Zahl mit einer noch höheren Genauigkeit. Wenn Sie long double mit dem sizeof-Operator auf seine SpeichergröÃe in Bytes überprüft haben, dürften Sie sicherlich verwundert sein, dass der Datentyp auf 32-Bit-Systemen 12 Bytes beansprucht. Auf einem 32-Bit-System werden dazu einfach zwei Füllbytes angefügt. Auf 16-Bit-Systemen beansprucht long double weiterhin 10 Bytes Speicher. Auf einer HP-UX-Maschine hingegen benötigt long double gar 16 Bytes an Speicher. Dabei werden aber alle 128 Bits genutzt, und somit lässt sich eine Genauigkeit von 33 Stellen anzeigen. ### 5.8.5 Einiges zu n-stelliger Genauigkeit Eine FlieÃkommazahl mit 6-stelliger Genauigkeit wie float kann sechs Dezimalstellen nicht immer korrekt unterscheiden. Wenn beispielsweise die Zahl vor dem Komma (z. B. »1234,1234«) bereits vier Stellen besitzt, so kann sie nach dem Komma nur noch zwei Stellen unterscheiden. Somit wären die Gleitpunktzahlen 1234,12345 und 1234,123999 als float-Zahlen für den Computer nicht voneinander zu unterscheiden. Mit 6-stelliger Genauigkeit sind die signifikanten Stellen von links nach rechts gemeint. Der Typ float ist also ungeeignet für kaufmännische und genaue wissenschaftliche Berechnungen. Dazu folgendes Beispiel: > /* floating.c */ #include <stdio.h> int main(void) { float x=1.1234; float dollar=100000.12; float end_float; double y=1.1234; double DOLLAR=100000.12; double end_double; printf("%f Euro mit float\n",end_float=dollar*x); printf("%f Euro mit double\n",end_double=DOLLAR*y); return 0; } Hier werden zwei verschiedene Ergebnisse zurückgegeben. Die Differenz mag minimal sein, doch bei Börsenberechnungen könnte eine solche Ungenauigkeit durchaus Millionen von Euro kosten, und in der Astronomie wäre der Mond wohl heute noch nicht erreicht. Abbildung 5.4 Darstellung von FlieÃkommazahlen mit »double« und »float« float ist nach sechs Dezimalstellen am Ende. Mit double haben Sie dagegen die Möglichkeit, eine auf 15 Stellen genaue Zahl zu erhalten, und mit long double bekommen Sie eine 19-stellige. Was ist zu tun, wenn diese Genauigkeit nicht ausreichen sollte? In diesem Fall müssen Sie sich nach sogenannten Festkomma-Algorithmen umsehen. Denn Festkomma-Darstellungen wie die BCD-Arithmetik gibt es in C nicht. BCD-Arithmetik | | --- | | # 5.9 Numerische Gleitpunktprobleme ## 5.9 Numerische Gleitpunktprobleme Vorsicht ist geboten vor Ungenauigkeiten durch die binäre Darstellung von Gleitpunktzahlen. Reelle Zahlen können im Gleitpunktformat nicht immer exakt dargestellt werden. Das liegt daran, dass die Gleitpunktsemantik so implementiert ist, wie es der Prozessor berechnet. Würde man dafür eine extra Funktion für den Compiler schreiben, wäre die Berechnungsdauer systemabhängig. Würde die Berechnung beispielsweise bei einem Pentium-Prozessor optimal ablaufen, könnte sie bei einem Athlon wiederum katastrophale Laufzeiten haben. Dadurch kann es bei der Berechnung von arithmetischen Ausdrücken zu Ungenauigkeiten kommen (wie weiter oben schon gezeigt wurde). AchtungZahlen im Gleitpunktformat sollten nie auf Gleichheit überprüft werden! Folgendes Programm wird in eine Endlosschleife laufen, da die Zahl 0.1 nie exakt dargestellt werden kann: > /* never_ending.c */ #include <stdio.h> int main(void) { float i=0.0; for (i=0.0; i != 1.0; i += 0.1) printf("%f",i); return 0; } Sicherer ist es, wenn Sie dieses Beispiel so überprüfen: > /* equal_float.c */ #include <stdio.h> int main(void) { float i=0.0; for (i=0.0; i < 0.9999 || i > 1.0001; i += 0.1) printf("%f",i); return 0; } HinweisFür Vergleiche von reellen Gleitpunktzahlen stehen auch Makros zur Verfügung. Mehr dazu können Sie in Abschnitt 20.3.6, »Makro zum Vergleich mit reellen Zahlen«, nachlesen. HinweisFür den Fall, dass sich jemand näher mit der Gleitpunktdarstellung auf verschiedenen Systemen auseinandersetzen will (muss), hier ein Link dazu: http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/index.html Natürlich kann ich jetzt nicht einfach schreiben, dass Sie sich in Acht nehmen sollen, wenn Sie Gleitpunktzahlen für Ihre Berechnungen verwenden, sondern hier wird wohl eine informatiker-gerechte Erklärung nötig sein. Zunächst mal möchte ich Ihnen das Gleitpunktformat beschreiben, das aus einem Vorzeichen, einem Dezimalbruch und einem Exponenten besteht: +-f.fff x 10+-e Zunächst finden Sie mit +- das Vorzeichen, gefolgt vom Dezimalbruch mit den vier Stellen f.fff und am Ende den Exponenten mit einer Stelle (+-e ). Die Zahlen werden gewöhnlich im E-Format (+-f.fffE+-e ) geschrieben. Zwar hat das IEEE das Gleitpunktformat standardisiert, aber leider halten sich nicht alle Computer daran. So wird beispielsweise die Zahl 1.0 wie im E-Format mit +1.000E+0 beschrieben oder –0.006321 mit –6.321E-3 und die 0.0 mit +0.000E+0. So weit, so gut. Wenn Sie beispielsweise 2 /6 + 2 /6 rechnen, kommen Sie wohl auf das Ergebnis 4 /6. Richtig für Sie, aber hier geht das Dilemma Gleitpunktzahlen und Rundungsfehler schon los. 2 /6 ist im E-Format gleich +3.333E-1. Addieren Sie nun +3.333E-1 mit +3.333E-1, erhalten Sie als Ergebnis +6.666E-1 (bzw. 0.6666). Gut, aber leider falsch, denn 4 /6 sind im E-Format +6.667E-1, aber nicht wie berechnet +6.666E-1. Mit derartigen Rundungsfehlern haben viele Computer ihre Probleme. Daher schon der erste Ratschlag: Sollten Sie eine Software entwickeln, mit der Geld verwaltet wird, und Sie wollen bzw. können dabei auf keine anderen Bibliotheken bzw. BCD-Arithmetiken zurückgreifen, dann sollten Sie die Beträge niemals im Gleitpunktformat verwenden (hierzulande also niemals mit Euro und Cent wie 1,99 Â). Hier empfiehlt es sich, zur Berechnung die Geldbeträge in Cent als Integerzahl zu verwenden, da sonst bei immer intensiveren Berechnungen Rundungsfehler gemacht werden und somit eine falsche Berechnung garantiert ist. Man kann nicht mal ganz genau sagen, wie genau eine solche gebrochene Zahl ist, weil dies von der Art der Berechnung abhängt. Beispielsweise führen Subtraktionen mehrerer ähnlicher Zahlen zu einem ungenaueren Ergebnis. HinweisUm sich also mit den Problemen der Gleitpunktzahlen auseinanderzusetzen, müssen Sie sich mit Themen wie »numerischer Analyse« oder BCD-Arithmetik befassen. Allerdings sind dies Themen, die weit über dieses Buch hinausgehen würden. # 5.10 Komplexe Gleitpunkttypen – <complex.h## 5.10 Komplexe Gleitpunkttypen – <complex.hMit dem C99-Standard wurden auch komplexe Gleitpunkttypen eingeführt. Diese Typen sind in der Headerdatei <complex.h> definiert. Eine komplexe Zahl wird hierbei als Paar aus Real- und Imaginärteil dargestellt, die auch mit den Funktionen creal() und cimag() ausgegeben werden können. Beide Teile der komplexen Zahl bestehen entweder aus den Typen float, double oder long double. Daher gibt es wie auch bei den reellen Gleitpunktzahlen folgende drei komplexe Gleitpunkttypen: > float _Complex double _Complex long double _Complex Da komplexe Zahlen einen Real- und einen Imaginärteil haben, beträgt die GröÃe des Datentyps in der Regel das Doppelte wie bei den grundlegenden Datentypen. Ein float _Complex benötigt somit 8 Bytes, weil ja im Grunde zwei float-Elemente benötigt werden. Folgendes Listing soll das verdeutlichen: > /* complex.c */ #include <stdio.h> #include <stdlib.h> #include <complex.h> int main(void) { float f1 = 1.0; float complex fc = 2.0 + 3.0*I; // 4 Bytes printf("sizeof(float) : %d\n", sizeof(float)); // 8 Bytes (realer und imaginärer Teil) printf("sizeof(float complex) : %d\n", sizeof(float complex)); // Ausgabe vom Real- und Imaginärteil printf("%f + %f\n", creal(fc), cimag(fc)); return EXIT_SUCCESS; } Um nicht die umständliche Schreibweise mit dem Unterstrich _Complex verwenden zu müssen, ist in der Headerdatei <complex.h> das Makro complex definiert, womit Sie anstelle des Schlüsselworts _Complex auch complex verwenden können: > float complex // gleich wie float _Complex double complex // gleich wie double _Complex long double complex // gleich wie long double _Complex Des Weiteren ist in der Headerdatei das Makro I definiert, das die imaginäre Einheit mit dem Typ const float complex darstellt. Vielleicht hierzu eine kurze Hintergrundinformation zu komplexen Gleitpunktzahlen. Eine komplexe Zahl zVal wird beispielsweise folgendermaÃen in einem kartesischen Koordinatensystem dargestellt: zVal = xVal + yVal * I xVal und yVal sind hierbei reelle Zahlen, und I ist der imaginäre Teil. Die Zahl xVal wird hierbei als realer Teil betrachtet, und yVal ist der imaginäre Teil von zVal. Kartesisches Koordinatensystem | | --- | | Noch mehr zu den komplexen Gleitpunkttypen und deren mathematischen Funktionen erfahren Sie ab Abschnitt 20.3, »Mathematische Funktionen«. # 5.11 Der Datentyp »char« ## 5.11 Der Datentyp »char« Der Datentyp char kann auf zwei logisch völlig unterschiedliche Arten verwendet werden. Zum einen dient er zur Darstellung von einzelnen Zeichen wie 'a', 'A', 'b', 'B', '5', '7', '§' usw. für Tastatureingabe und Bildschirmausgabe. Zum anderen kann char genutzt werden, um kleine Ganzzahlen zu verarbeiten, wobei gesagt werden muss, dass dafür der Wertebereich relativ klein ist. Hier die Ãbersicht dazu: NameGröÃeWertebereichFormatzeichenchar1 Byte–128  +127 bzw. 0  255%c HinweisEin Byte besteht nicht zwangsläufig aus 8 Bits. Es gab früher auch Maschinen, die z. B. 9 Bits als kleinsten adressierbaren Typ hatten. Des Weiteren gibt es z. B. DSPs, bei denen ein Byte 32 Bits groà ist. Damit kann ein char auch von 231 ... 231-1 gehen. Der ANSI-C-Standard schreibt hierbei nämlich nur Folgendes vor: »Alle Speicherobjekte in C müssen durch eine gleichmäÃige Sequenz von Bytes mit mindestens 8 Bits Breite darstellbar sein. Ein char, egal ob jetzt signed oder unsigned, belegt exakt ein Byte.« Dies kann beispielsweise bei einer 36-Bit-Maschine bedeuten, dass ein Byte mit 9, 12, 18 oder 36 Bits definiert ist, da all diese Nummern den gleichen Teiler haben und nicht weniger als 8 Bits breit sind – und somit beide Bedingungen des ANSIC-C-Standards einhalten. Mehr zu einem Byte finden Sie hier: HinweisWie viele Bits ein char auf Ihrem System nun hat, ist im Makro CHAR_BIT (limits.h) definiert. Aber egal, wie viele Bits ein char hat, ein sizeof(char) muss immer eins (ein Byte) ergeben! An dieser Stelle will ich zum besseren Verständnis etwas weiter ausholen. Der Computer ist eigentlich dumm. Er kennt nichts anderes als die Zustände 0 für »aus« und 1 für »ein«. Dies entspricht etwa einem Lichtschalter, den Sie ein- oder ausschalten können. Im Fall von char wären dies acht Lichtschalter. Sehen wir uns dazu zuerst die mögliche GröÃe der Datentypen an: > GröÃe von char 1 Byte = 8 Bit GröÃe von short 2 Byte = 16 Bit GröÃe von int 2 oder 4 Byte = 16 Bit oder 32 Bit GröÃe von long 4 Byte = 32 Bit GröÃe von float 4 Byte = 32 Bit GröÃe von double 8 Byte = 64 Bit GröÃe von long double 10 Byte = 80 Bit Abbildung 5.5 Einzelne Bits der Datentypen im Ãberblick Betrachten Sie den Datentyp char, der ja meistens aus acht einzelnen Bits besteht. Diese acht Bits sollen nun ein Byte darstellen (wie dies am häufigsten auch anzutreffen ist) (siehe Abbildung 5.6). Abbildung 5.6 Ein Byte (Datentyp »char«) Jedes dieser acht Bits kann einen bestimmten Wert darstellen (siehe Abbildung 5.7). Abbildung 5.7 Diese Zahlen ergeben sich durch die Potenzen von 2. Der PC kann doch nur zwei Zahlen darstellen. Woher kommen dann diese Werte? Sie werden aus der Potenz von 2 berechnet (27 +26 +25 +24 +23 +22 +21 +20 ). Würden Sie jetzt hier Bit 0 und Bit 1 auf 1 setzen, also »Licht an«, würde der Wert 3 dargestellt. Dieser errechnet sich ebenfalls wieder aus den Potenzen: 0*27 +0*26 +0*25 +0*24 +0*23 +0*22 +1*21 +1*20 = 3 Ein Beispiel: Der Dezimalwert dieser Zusammensetzung der einzelnen Bits beträgt 66 (0*27 +1*26 +0*25 +0*24 +0*23 +0*22 +1*21 +0*20 = 66). Es müssen nur die einzelnen Bits zusammengezählt werden, die gesetzt (also 1) sind. Wenn Sie jetzt die ASCII-Code-Tabelle in Anhang A.2 betrachten und unter dem dezimalen Wert 66 nachsehen, stellen Sie fest, dass 66 für das groÃe 'B' steht. Es geht nämlich hier bei char nicht um den int-Wert, sondern um das Zeichen, das diesem dezimalen Wert in der ASCII-Tabelle entspricht. Abbildung 5.8 Dualdarstellung des dezimalen Werts 66 Die ASCII-Code-Tabelle ist eine Tabelle, an die sich alle Programmierer der Welt halten müssen. Sie enthält alle Zeichen, die der Computer darstellen kann. Kommen wir nun nach diesem kleinen Ausflug ins Dualsystem zurück zum Thema dieses Kapitels, dem Datentyp char. Hier ein kleines Listing: > /* playing_char.c */ #include <stdio.h> int main(void) { char a = 'A'; char b = 65; int c = 65; int d; printf("a = %c\n",a); printf("b = %c\n",b); // Ãberrascht? printf("c = %c\n",c); // Nochmals :) d = a + b + c; // Rechenbeispiel printf("d = %d\n",d); d = 'a' + 'A'; printf("d = %d\n",d); printf("char a = %c und %d\n",a,a); printf("char b = %c und %d\n",b,b); printf("int c = %c und %d\n",c,c); return 0; } Der Programmablauf sieht etwa folgendermaÃen aus: Abbildung 5.9 Das Programm bei der Ausführung unter Linux Kommen wir jetzt zur Zeile: > char a = 'A'; Wenn Sie char ein Zeichen zuweisen wollen, muss es zwischen zwei einzelnen Hochkommata stehen ('A'). Folgende Varianten sind nicht möglich bzw. falsch: > // falsch, in doppelte Hochkommata == String char a = "A"; // falsch, Variablenzuweisung char a = A; /* schlechter Stil, da nicht gleich durchschaubar ist, ob der * Programmierer hier den ASCII-Buchstaben oder den * dezimalen Wert verwenden will */ char b = 65; Hier sehen Sie auch gleich die andere Möglichkeit, char einen Wert zuzuweisen. Für den PC sind der Wert 65 und das Zeichen 'A' identisch. Beide haben dieselbe Bitdarstellung: Abbildung 5.10 Bitdarstellung des Dezimalwerts 65 und des Zeichens ‘A‘ Dies bestätigt auch die Ausgabe im Programm: > printf("a = %c\n", a); printf("b = %c\n", b); Auch wenn es hier so aussieht: In C gibt es keinen Datentyp, mit dem Sie echte Zeichen wie 'A', 'B' oder 'C' speichern können. Daher stehen diese Zeichen auch zwischen einzelnen Anführungszeichen. Sie geben zwar Folgendes an: > char a = 'A'; aber nach der Ãbersetzung des Compilers sieht dies so aus: > char a = 65; Verwenden Sie jetzt im Programm das Formatierungszeichen %c, wird der Wert 65 anhand der ASCII-Code-Tabelle kodiert. Wird hierbei das Formatierungszeichen %d verwendet, würde dieser Wert nicht kodiert und in seiner tatsächlichen Form ausgegeben, wobei »tatsächliche Form« natürlich rein optisch gemeint ist. In Wirklichkeit wäre die tatsächliche Form eine Zahlenkolonne von Einsen und Nullen. Für den PC gelten weiterhin nur Bits und Bytes. Und wie Sie gesehen haben, funktioniert das analog auch mit dem Datentyp int. AchtungAuch wenn Sie char oder unsigned char für kleine Ganzzahlwerte verwenden könnten, ist von dieser Möglichkeit abzuraten. Dies vor allem, weil in C nicht festgelegt ist, ob dieser Datentyp mit oder ohne Vorzeichen interpretiert wird. Es könnte ähnlich wie bei int auf verschiedenen Systemen zu unterschiedlichem Verhalten oder gar zu Fehlern führen (siehe Abschnitt 7.1 zu int). HinweisDen Zeichentyp char kann man zwar auch mit signed oder unsigned spezifizieren, beachten Sie aber, dass char, unsigned char und signed char drei verschiedene Typen sind! Des Weiteren hängt es von der Compiler-Implementierung ab, ob char auch negative Zahlen aufnehmen kann. # 5.12 Nationale contra internationale Zeichensätze ## 5.12 Nationale contra internationale Zeichensätze Der ASCII-Zeichensatz (American Standard Code for Information Interchange) wurde von US-amerikanischen Ingenieuren entwickelt. Zur damaligen Zeit wurde als achtes Bit das Paritätsbit benutzt, womit nur noch sieben Bits zur Verfügung standen; also gab es Platz für 128 Zeichen und Sonderzeichen. Nun fehlte der Platz für westeuropäische und slawische Zeichen (von der japanischen Schrift mit über 40.000 Zeichen und der kyrillischen Schrift ganz zu schweigen). Man beschränkte sich also auf die Zeichen, die im Englischen benötigt wurden. Als die Europäer mit ihren landestypischen Zeichen ebenfalls in die ASCII-Tabelle aufgenommen werden wollten, war es schon zu spät. Wie Sie an der ASCII-Code-Tabelle sehen können, befinden sich unter den 128 Zeichen, die in 7 Bits Platz haben, keine Umlaute wie zum Beispiel »äöüÃÃÃÃë oder landestypische Zeichen anderer europäischer Länder wie etwa französische. Jetzt war die ISO (International Organisation for Standardization) gefragt. Der ASCII-Zeichensatz wurde auf 8 Bits erweitert und unter der Bezeichnung »utf-8«, »ISO-8859-2« usw. etabliert. Der westeuropäische Standard ist in der »ISO-8859-1« erfasst. Damit lassen sich folgende Zeichen darstellen: > /* iso_ascii.c */ #include <stdio.h> int main(void) { int i; for(i=0; i < 254; i++) { if(i==27) // ESC-Zeichen ignorieren continue; printf(" |%d : %c| ",i,i); } return 0; } Die deutschen Sonderzeichen in oktaler Form können auch folgendermaÃen ausgegeben werden (unter einer MS-Windows-Konsole): > /* umlaute.c */ #include <stdio.h> int main(void) { printf("R\204tsel, \231l, \232berfall\n"); printf("Umlaute oktal : \204\216\224\231\201\232\341\n"); return 0; } Das Problem mit den deutschen Sonderzeichen unter der Windows-Konsole ist, dass diese nicht den gewöhnlichen Windows-Zeichensatz verwendet, sondern einen OEM-Zeichensatz. Deshalb müssen Sie in diesem Fall einen Umweg machen. Mit Linux haben Sie dieses Problem nicht. Um in diesem Zusammenhang nochmals auf char zurückzukommen: Der Wertebereich von char ist auÃerdem auch abhängig von dem Zeichensatz, der vom eingesetzten Rechner und dessen Betriebssystem verwendet wird. Hierbei sind folgende Zeichensätze (Codes) verbreitet (ohne hier zu sehr ins Detail zu gehen): Zeichensatz | Ordinalwert | Speicherbedarf | Bemerkung | | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | Die Zeichensätze mit einem Speicherbedarf von maximal 8 Byte werden in C gewöhnlich mit dem Datentyp char dargestellt. Für den Unicode-Zeichensatz wird der Datentyp wchar_t verwendet. Im Zusammenhang mit den verschiedenen Zeichensätzen sind folgende Probleme zu beachten: * Die Ordnung der Zeichen kann sich in den verschiedenen Zeichensätzen unterscheiden. * Einem Ordinalwert können in unterschiedlichen Zeichensätzen verschiedene Zeichen entsprechen. # 5.13 Der Breitzeichen-Typ »wchar_t« ## 5.13 Der Breitzeichen-Typ »wchar_t« Ganz klar: Für die Zeichensätze mancher Sprachen wie beispielsweise der chinesischen mit über tausend Zeichen ist der Datentyp char zu klein. Für die Darstellung beliebiger landesspezifischer Zeichensätze kann daher der Breitzeichen-Typ wchar_t (wide char = breite Zeichen) aus der Headerdatei <stddef.h> verwendet werden. Der Datentyp wchar_t ist wie char und int ein integraler Datentyp und hat eine GröÃe von 2 Bytes (ist aber zunehmend auch mit 4 Bytes zu finden), womit natürlich erheblich mehr Zeichen aufgenommen werden können. Bei der Deklaration eines solchen Zeichens muss vor den einzelnen Anführungszeichen noch das Präfix L gestellt werden: > wchar_t ch = L'Z'; Entsprechend wird auch beim Formatzeichen für die Ausgabe oder Eingabe eines wchar_t ein l vor dem c verwendet (%lc): > print("%lc", ch); Das folgende Beispiel soll Ihnen zeigen, wie Sie wchar_t in der Praxis verwenden können: > /* widechar.c */ #include <stdio.h> #include <stddef.h> int main(void) { wchar_t ch1=L'Z'; wchar_t ch2; printf("Bitte ein Zeichen eingeben: "); scanf("%lc", &ch2); printf("%lc %lc\n", ch1, ch2); printf("wchar_t: %d Bytes\n", sizeof(wchar_t)); return 0; } Die GröÃe von wchar_t lässt sich hierbei nicht exakt beschreiben (meistens 2 oder 4 Bytes). Es lässt sich lediglich mit Sicherheit sagen, dass wchar_t mindestens so groà wie char und höchstens so groà wie long ist. wchar_t muss auf jeden Fall mindestens so groà sein, um alle Werte des gröÃten unterstützten Zeichensatzes aufnehmen zu können. # 5.14 Multibyte-Zeichen ## 5.14 Multibyte-Zeichen Neben den Breitzeichen unterstützt der C-Standard mit den Multibyte-Zeichen noch eine zweite Möglichkeit, Zeichen zu repräsentieren, die nicht mehr in einem Byte darstellbar sind. Im Gegensatz zu den Breitzeichen, die immer die gleiche Anzahl Bits verwenden, können Multibyte-Zeichen unterschiedlich lang sein. Wenn Sie beispielsweise bei einem Breitzeichen-Typ ein Zeichen vom Basic-Zeichensatz verwenden, hat das Breitzeichen immer eine feste Breite (abhängig von der Implementierung sind dies meistens 2 oder 4 Bytes). Bei einem Multibyte-Zeichen hingegen haben Zeichen vom Basic-Zeichensatz tatsächlich nur ein Byte. Der Vorteil von Multibyte-Zeichen gegenüber Breitzeichen besteht klar darin, keinen Speicherplatz zu verschenken. Es macht beispielsweise keinen Sinn, wenn Sie für einen erweiterten Zeichensatz für jedes Zeichen vier Bytes verschwenden, auch wenn Sie vorwiegend nur Zeichen aus dem Basic-Zeichensatz verwenden würden, die ja eigentlich in einem Byte darstellbar sind. In Multibyte-Zeichen sind somit beispielsweise die ASCII-Zeichen in nur einem Byte gespeichert, und wenn Sie andere Zeichen benötigen, dann haben diese eben auch nur so viel Speicherplatz, wie diese wirklich benötigen. Der Nachteil daran ist, dass bei den Multibyte-Zeichen die Anzahl der Bytes je nach benötigtem Zeichen variieren kann, was natürlich auch die Arbeit damit erheblich schwieriger macht. # 5.15 Boolescher Wert – <stdbool.h## 5.15 Boolescher Wert – <stdbool.hIm C99-Standard wurde mit _Bool ein boolescher Wert eingeführt. Glücklicherweise existiert für den Typ _Bool in der Headerdatei <stdbool.h> das Makro bool, sodass Sie den Bezeichner bool wie in C++ verwenden können. Allerdings müssen Sie hierfür dann extra die Headerdatei <stdbool.h> inkludieren. Boolesche Werte sind Elemente einer booleschen Algebra, die einen von zwei möglichen Werte annehmen kann. Dieses Wertepaar hängt von der Anwendung ab und lautet entweder wahr/falsch, true/false oder eben 1/0. In C/C++ kann hierfür das Wertepaar true (für wahr) und false (für falsch) verwendet werden, die beide in der Headerdatei <stdbool.h> mit der Konstante 1 und 0 definiert sind. Natürlich können Sie hierfür auch das Paar 1 und 0 als Dezimalwert verwenden: > #include <stdbool.h> // ... // Schalter auf wahr setzen _Bool b1 = 1; // Schalter auf unwahr setzen _Bool b2 = 0; // benötigt <stdbool.h> bool b3 = true; // wahr // benötigt <stdbool.h> bool b4 = false; // unwahr Ob die Wahrheitswerte true oder false in <stdbool.h> überhaupt vorhanden sind, lässt sich mit dem Makro __bool_true_false_are_defined überprüfen. Gibt dieses Makro 1 zurück, stehen Ihnen true und false zur Verfügung: > if( __bool_true_false_are_defined ) print("true/false sind vorhanden\n"); # 5.16 Vorzeichenlos und vorzeichenbehaftet Date: 2010-07-01 Categories: Tags: ## 5.16 Vorzeichenlos und vorzeichenbehaftet Mit dem Schlüsselwort unsigned weisen Sie den Compiler an, dass er einen Datentyp vorzeichenlos behandeln soll. Dadurch erhöht sich auch der Wertebereich der positiven Zahlen. Mit dem Schlüsselwort signed bewirken Sie genau das Gegenteil. signed ist bei allen Datentypen voreingestellt. Das bedeutet, dass folgende Schreibweisen die gleiche Bedeutung haben: > int a; signed int a; // Auch möglich, weil signed ein Synonym von signed int ist signed a; Es gibt auÃerdem die Regel, dass zu jedem signed-Typ ein unsigned-Gegenstück existiert. Natürlich haben sowohl signed- als auch unsigned-Werte dieselbe Ausrichtung und auch dieselbe GröÃe. Bei beiden Typen gilt zusätzlich, dass diese nicht überlaufen können. Wird jeweils ein Wert aufgenommen, der um 1 gröÃer als der maximale Wert ist, wird der Wert um den jeweiligen Typ reduziert. Bei einem signed short mit dem Wert +32768 bedeutet dies, dass dieser wieder mit dem Wert –32768 anfangen würde. Selbiges gilt natürlich auch beim unsigned-Gegenstück, nur dass hierbei beispielsweise der Wert 65536 wieder mit dem Wertebereich 0 anfangen würde. Am besten sehen Sie sich dazu die folgende Tabelle an, in der sich alle Datentypen befinden, die Sie bisher kennengelernt haben. Dazu nochmals char als Beispiel. Manch einer wird sich vorhin gedacht haben: »Warum kann ich mit char nur Werte zwischen –128 und 127 darstellen?« Denn wenn alle Bits gesetzt sind und Sie nachrechnen, ist das Ergebnis der Summe 255. Doch es müssen ja auch negative Werte dargestellt werden, etwa –100. Wenn das Schlüsselwort unsigned vor einen Datentyp gestellt wird, sind keine negativen Zahlen mehr möglich. Somit verdoppelt sich aber der positive Wert der Zahl. Sollten Sie z. B. zwei Zahlen subtrahieren, und es kommt ein negatives Ergebnis heraus, und es wurde vor dem Datentyp des Ergebnisses das Schlüsselwort unsigned gesetzt, so wird das Minus der negativen Zahl ignoriert, und es wird eine positive Zahl daraus. »Und was ist mit wchar_t?«, werden sich einige hier fragen. Hierzu müssen Sie wissen, dass es bei wchar_t kein explizites signed oder unsigned gibt. Abhängig vom unterliegenden Typen ist wchar_t entweder signed oder unsigned. # 5.17 Limits für Ganzzahl- und Gleitpunktdatentypen ## 5.17 Limits für Ganzzahl- und Gleitpunktdatentypen Jetzt haben Sie eine Menge über Datentypen und ihre Eigenschaften erfahren. Häufig hieà es jedoch, auf bestimmten Systemen hat Datentyp x die GröÃe y. Wenn Sie jetzt erfahren wollen, welchen maximalen oder minimalen Wert der Datentyp int z. B. auf Ihrem System besitzt, können Sie die Konstanten in den Standard-Headerdateien <limits.h> und <float.h> abfragen bzw. ausgeben. Mit folgendem Listing ist es möglich, alle Limits des Datentyps int auf Ihrem System abzufragen: > /* int_limit.c */ #include <stdio.h> #include <limits.h> int main(void) { printf("int-Wert mindestens : %d\n", INT_MIN); printf("int-Wert maximal : %d\n", INT_MAX); printf("unsigned int max. : %u\n", UINT_MAX); printf("int benötigt %d Byte (%d Bit) Speicher\n", sizeof(int), sizeof(int) * CHAR_BIT); return 0; } Genauso wie in diesem Beispiel können Sie auch die anderen Limit-Eigenschaften der Datentypen abfragen – vorausgesetzt, Sie binden die Headerdatei <limits.h> mit ein. Tabelle 5.10 führt die Limits für ganzzahlige Datentypen in der Headerdatei <limits.h> auf: Benötigen Sie hingegen Limit-Werte für Gleitpunktzahlen, gibt die Headerdatei <float.h> Auskunft. Darin finden Sie u. a. Konstanten mit allen Limits und Eigenschaften, die für Gleitpunktdatentypen entscheidend sind. Das folgende Listing gibt alle Limits und Eigenschaften für den Datentyp float auf Ihrem System aus: > /* float_limit.c */ #include <stdio.h> #include <float.h> #include <limits.h> //für CHAR_BIT int main(void) { printf("Limits und Eigenschaften von float\n"); printf("----------------------------------\n"); printf("Bytes: %d\n", sizeof(float)); printf("Bit : %d\n", sizeof(float) * CHAR_BIT ); printf("Basis-Exponenten-Darstellung: %d\n", FLT_RADIX); printf("Anzahl Mantissenstellen : %d\n", FLT_MANT_DIG); printf("Anzahl Dezimalziffern : %d\n", FLT_DIG); printf("Kl. neg. FLT_RADIX-Exponent: %d\n", FLT_MIN_EXP); printf("Kl. neg. Zehnerexponent : %d\n", FLT_MIN_10_EXP); printf("GröÃter FLT_RADIX-Exponent : %d\n", FLT_MAX_EXP); printf("GröÃter Zehnerexponent : %d\n", FLT_MAX_10_EXP); printf("GröÃter endl. float-Wert : %f\n", FLT_MAX); printf("Kleinster endl. float-Wert : %f\n", FLT_MIN); return 0; } Die folgende Tabelle zeigt die Limits und Eigenschaften von Gleitpunktdatentypen, die in der Headerdatei <float.h> deklariert sind: Natürlich gilt auch bei der Verwendung der Konstanten, die sich in der Headerdatei <float.h> befinden, dass die entsprechende Headerdatei mit eingebunden wird. # 5.18 Der Typ »void« ## 5.18 Der Typ »void« Der Typ void ist kein echter Datentyp und wird überall dort verwendet, wo kein Wert benötigt wird oder vorhanden ist. Bei Funktionen (mehr dazu siehe Kapitel 9, »Funktionen«) wird void verwendet, wenn eine Funktion keinen Wert zurückgibt oder die Funktion keinen Parameter hat, beispielsweise so: > // Funktion ohne Rückgabewert void func1( const char *str ) { /* ... */ } // Funktion ohne Parameter int func2( void ) { /* ... */ } Das andere Anwendungsgebiet von void sind typenlose Zeiger bzw. genauer gesagt void-Zeiger (void *). Solche Zeiger werden häufig bei der Deklaration von Funktionen verwendet, die mit unterschiedlichen Typen von Zeigern aufgerufen werden und auch wieder unterschiedliche Typen zurückgeben können. Mehr dazu finden Sie in Abschnitt 12.11, »void-Zeiger«. # 5.19 Konstanten ## 5.19 Konstanten Eine Konstante ist entweder eine ganzzahlige Konstante, eine Gleitpunktkonstante, eine Zeichenkonstante oder ein Stringliteral. Jede Konstante besteht aus einem Typ, der sich aus dem Wert und seiner Schreibweise ergibt. ### 5.19.1 Ganzzahlkonstanten Ganzzahlige Konstanten können als Dezimalzahl, als Oktalzahl oder als Hexadezimalzahl dargestellt werden. Die dezimale Konstante kann durch folgende Datentypen dargestellt werden: > int, unsigned long, long, long long Oktale und hexadezimale Konstanten lassen sich mit folgenden Datentypen darstellen: > int, unsigned int, long, unsigned long, unsigned long long Der Typ der Konstante lässt sich übrigens auch mit dem Suffix L oder l für long, ll oder LL für long long und u oder U für unsigned-Konstanten beschreiben. Tabelle 5.12 enthält einige Beispiele ganzzahliger Konstanten. dezimal | hexadezimal | oktal | Typ | | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | ### 5.19.2 Gleitpunktkonstanten Eine Gleitpunktkonstante ist eine Folge von Dezimalziffern mit einem Gleitpunkt. Gleitpunktkonstanten müssen stets mit einem Gleitpunkt oder der Angabe von e oder E gekennzeichnet werden. Wird kein Suffix angegeben, ist die Konstante vom Typ double. Mit dem Suffix f oder F ist der Typ der Konstante float, und mit dem Suffix l oder L wird daraus ein long double. Auch hierzu einige Beispiele: ### 5.19.3 Zeichenkonstanten Zeichenkonstanten bestehen aus einem Zeichen, das zwischen zwei einfache Hochkommata eingeschlossen wird. Zeichenkonstanten sind intern vom Typ int und werden durch entsprechenden Zeichencode (ASCII-Code) dargestellt. Einige Beispiele für Zeichenkonstanten sind: > 'a', 'b', '\t', '\n', 'x' Wollen Sie eine Zeichenkonstante vom Typ wchar_t verwenden, müssen Sie das Präfix L voranstellen: > L'a', L'b', L'\t', L'\n', L'x' ### 5.19.4 Stringliterale (Stringkonstante) Ein Stringliteral ist ein char-Array, das mit dem schlieÃenden Stringende-Zeichen \0 gespeichert wird. AuÃerdem werden Stringliterale zwischen zwei doppelte Hochkommata gestellt. Beispiele: > "Hallo Welt", "Hallo\nWelt\n" Sofern Sie auch hierbei sogenannte Wide-String-Literale definieren wollen, muss auch hier das Präfix L vorangestellt werden: L"<NAME>", L"Hallo\nWelt\n" Mehr zu den Strings im Allgemeinen erfahren Sie in Kapitel 11, »Arrays«. Sie haben oben für Datentypen auch die Umwandlungsvorgaben, also Formatzeichen kennengelernt. Es lässt sich damit aber noch eine Menge mehr anstellen. Die Formatierungszeichen (oder auch Formatierungsanweisung genannt) beginnen immer – wie schon bei scanf() und printf() – mit dem Zeichen % und beziehen sich dann auch auf das oder die nachfolgenden Argumente. Mit > scanf("%d",&a); wird beispielsweise auf die Eingabe eines Integerwerts gewartet. Dies erkennen Sie am Formatierungszeichen %d. Folglich wird durch > %c ein char-Zeichen anhand der ASCII-Code-Tabelle in einen Buchstaben umgewandelt (genauer kodiert). Aber auÃer den bereits erwähnten Umwandlungszeichen können noch weitere Umwandlungsvorgaben festgelegt werden. Bei der formatierten Ausgabe mit Funktionen, wie z. B. printf(), fprintf(), vprintf()und sprintf(), haben Sie noch folgende Möglichkeiten: % F W G L U Die Bedeutung der einzelnen Buchstaben ist: * F = [Formatierungszeichen] * W = [Weite] * G = [Genauigkeit] * L = [Längenangabe] * U = [Umwandlungszeichen] Die Formatierungszeichen sind die Zeichen eines bestimmten Typs, die Sie ausgeben können. In Tabelle 5.14 sehen Sie die Liste. Einige wurden bereits verwendet: Formatierungszeichen | Ausgegeben wird (eine) | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Beim Einlesen eines Zeichens, eines numerischen Werts oder einer Zeichenkette gelten bei der formatierten Eingabe mit Funktionen wie etwa scanf(), sscanf(), fscanf() dieselben Umwandlungszeichen wie bei printf(). Hierbei können Sie aber auch noch eine Suchmengenkonvertierung verwenden: Umwandlungszeichen | Es wird eingelesen, | | --- | --- | | | | | Diese Suchmengenkonvertierung kann durch Zeichen des Formatierungstyps s (String, Zeichenkette) ersetzt werden. Dabei wird die Menge von Zeichen eingeschlossen, die sich zwischen den Klammern befindet. Beispiel: > /* suchmenge1.c */ #include <stdio.h> int main(void) { char str[20]; printf("Bitte geben Sie nur Zahlen ein: "); scanf("%[0-9]", str); printf("%s\n",str); return 0; } Abbildung 5.11 Suchmengenkonvertierung mit »scanf()« In diesem Beispiel werden Sie aufgefordert, nur Zahlen einzugeben. scanf() liest so lange Zahlen ein, bis das erste Zeichen nicht zwischen 0 bis 9 ist. Beachten Sie bitte, dass es sich hierbei um keine reellen Zahlen handelt, sondern um einen String. Wünschen Sie eine reelle Zahl, müssen Sie den String mit einer entsprechenden Funktion konvertieren. Mehr dazu folgt später beim Thema Strings (siehe Abschnitt 11.13). Ist das erste Zeichen der Suchmenge ein Caret (^), wird die Suchmenge invertiert, sodass alle ASCII-Zeichen zulässig sind, auÃer denen, die in den Klammern angegeben sind. Auch hierzu ein Beispiel: > /* suchmenge2.c */ #include <stdio.h> int main(void) { char str[20]; printf("Eingabe (keine Buchstaben wie x,y und z): "); scanf("%19[^xyz]", str); printf("%s\n",str); return 0; } Hierbei liest scanf() so lange ein, bis es auf das Zeichen 'x', 'y' oder 'z' trifft. Zusätzlich wurde hier festgelegt, dass scanf() nach mehr als 19 Zeichen ebenfalls abbricht (aus Sicherheitsgründen sollten Sie scanf() in der Praxis immer mit einer Längenangabe verwenden). Weitere Beispiele: > %[A-Z] //alle GroÃbuchstaben von A bis Z %[a-z] //alle Kleinbuchstaben von a bis z //Alle GroÃ- und Kleinbuchstaben von A bis F (Hexadezimalzahlen) %[a-fA-F] Wenn Sie wie in diesen Beispielen den Bindestrich verwenden, müssen Sie folgende Regeln beachten: * Das Zeichen vor dem Bindestrich muss lexikalisch vor dem darauf folgenden Zeichen liegen. Es ist also nicht möglich, [C-A] anzugeben. * Der Bindestrich darf nicht das letzte oder erste Zeichen sein (es sei denn, es wird nach dem ASCII-Zeichen des Bindestrichs gesucht). Formatierungszeichen sind ausschlieÃlich für die formatierte Ausgabe gedacht, wie mit printf(), fprintf(), sprintf() und vprintf(). Folgende Flags stehen dafür zur Verfügung: Flag | Bedeutung | | --- | --- | | | | | | | | | | | Die Flags müssen nach dem %-Zeichen stehen, und falls es sinnvoll ist, können mehrere Flags gleichzeitig verwendet werden. Als Nächstes betrachten wir die Ausgabe der Weite. Folgende zwei Angaben lassen sich dazu verwenden: Angaben | Bedeutung | | --- | --- | | | | | Folgendes Programm soll die Ausgabe der Weite demonstrieren: > /* weite.c */ #include <stdio.h> int main(void) { int i=10; printf("%5d\n",i); printf("%*d\n",i,i); return 0; } Falls Sie eine nicht vorhandene oder zu kleine Weitenangabe vornehmen, bewirkt dies nicht, dass die Zahlen beschnitten werden bzw. mehr Zeichen enthalten. Beispiel: > printf("%2d\n",100); // Ausgabe: 100 printf("%4d\n",100); // Ausgabe: 100 In beiden Fällen wird die Zahl 100 ausgegeben, egal, welche Längenangabe getroffen wird. Beim formatierten Einlesen gilt Folgendes als Weitenangabe: > scanf("%2d\n",&zahl); Falls Sie jetzt nach dieser scanf()-Eingabe-Aufforderung mehr als zwei Ziffern eingeben, z. B. 100, so wird in diesem Fall die letzte 0 nicht mit eingelesen, und der Wert der Variable zahl ist 10. Kommen wir jetzt zur Genauigkeitsangabe der formatierten Ausgabe. Der genauen Schreibweise geht ein Punkt voran: printf("%.2f\n",3.143234); // Ausgabe 3.14 Hiermit wird die Gleitpunktzahl »3.143234« als »3.14« ausgegeben. Das heiÃt aber nicht, dass sich der Wert der Zahl verändert hat, sondern dies bezieht sich nur auf die formatierte Ausgabe. Die Zahl wird also nicht auf- oder abgerundet. So bewirkt z. B. die Ausgabe von printf("%.2d\n",1000); // Ausgabe 1000 nicht, dass 10 ausgegeben wird. In diesem Fall wird dennoch die Zahl 1000 ausgegeben. Hingegen wird bei Strings dieser Bereich wiederum beschnitten. Zur Verdeutlichung ein weiteres Beispiel: > /* formatieren .c */ #include <stdio.h> int main (void) { char text[]="Tiefstand"; printf("|01234567890123456789|\n"); printf("|%s|\n",text); printf("|%20s|\n",text); printf("|%-20s|\n",text); printf("|%20s|\n",text+4); printf("|%20.4s|\n",text); printf("|%-20.4s|\n",text); printf("|%-20s|\n",text+4); return 0; } Abbildung 5.12 Formatierte Ausgabe mit Angabe der Weite Zum Schluss sind jetzt noch die einzelnen Längenangaben und ihre jeweiligen Auswirkungen vorzustellen. Im Fachjargon spricht man auch von einer Argumenttyp-Modifikation. Modifikation | Auswirkung | | --- | --- | | | | | | | | | | | | | | | Hierzu ein einfaches Listing, das einige dieser Argumenttyp-Modifikationen in der Praxis demonstrieren soll: > /* typmodifikation.c */ #include <stdio.h> int main (void) { short sval; double dval; long long llval; signed char cval; printf("Ein short-Wert : "); scanf("%hd", &sval); printf("Ein double-Wert : "); scanf("%lf", &dval); printf("Ein long long-Wert : "); scanf("%Ld", &llval); printf("Ein char-Wert : "); scanf("%hhd", &cval); printf("Der short-Wert ist %hd\n", sval); printf("Der double-Wert ist %lf\n", dval); printf("Der long long-Wert ist %Ld\n", llval); printf("Der char-Wert ist %hhd\n", cval); return 0; } # 6.2 Arithmetische Operatoren ## 6.2 Arithmetische Operatoren Für arithmetische Operationen (mathematische Gleichungen) gibt es folgende arithmetische Operatoren: Für arithmetische Operatoren gelten folgende Regeln: * Die Punkt-vor-Strich-Regelung: * und / binden also stärker als + und -. In der Praxis heiÃt dies: 5 + 5 * 5 ergibt 30 und nicht, wie eventuell erwartet, 50. Wenn zuerst 5 + 5 berechnet werden soll, verwenden Sie Klammern. Diese binden dann stärker als die Rechenzeichen; also (5 + 5) * 5 = 50. * Arithmetische Operatoren sind binäre Operatoren. Binäre Operatoren arbeiten immer mit zwei Operanden, also <Operand><Operator><Operand>. Ein Programmbeispiel verdeutlicht den Sachverhalt: > /* arithmetik.c */ #include <stdio.h> int main(void) { int zahl1,zahl2,zahl3; int ergeb; zahl1=10; zahl2=20; zahl3=30; printf("Zahl 1= %d\n",zahl1); printf("Zahl 2= %d\n",zahl2); printf("Zahl 3= %d\n",zahl3); // Möglichkeit 1: zuerst Berechnung, dann Ausgabe ergeb=zahl1+zahl2+zahl3; printf("Summe aller Zahlen:%d\n",ergeb); // Möglichkeit 2: wie oben, nur mit Ausgabe in einem Schritt ergeb=zahl3-zahl2; printf("%d - %d = %d\n",zahl3,zahl2,ergeb); /* Möglichkeit 3: mit Anzeige * und Berechnung am Ende der * 'printf'-Anweisung */ printf("%d * %d = %d\n",zahl1,zahl1,zahl1*zahl1); // Möglichkeit 4: weitere 'printf'-Berechnung printf("Zahl 3 / Zahl 1 =%d\n",zahl3/zahl1); // Möglichkeit 5: wieder eine mit 'printf' printf("Zahl 1 + x-Beliebige Zahl =%d\n",zahl1+11); // Ein Klammerbeispiel ergeb=(zahl1+zahl2)/zahl3; printf("(%d + %d)/%d = %d\n",zahl1,zahl2,zahl3,ergeb); return 0; } Wie Sie in diesem Beispiel sehen, kann die Berechnung auch in der printf-Anweisung ausgeführt werden. ### 6.2.1 Dividieren von Ganzzahlen Wenn zwei Ganzzahlen wie z. B. 4/3 dividiert werden, bekommen Sie als Ergebnis 1 zurück. Der Grund ist ganz einfach, denn der Datentyp int entspricht einer Ganzzahlvariablen und schneidet daher den nicht ganzzahligen Rest einfach ab. Wird der Rest benötigt, können Sie den Modulo-Operator verwenden. Der Modulo-Operator hat % als Zeichen. Das ist doch das Formatierungszeichen der Funktionen printf() und scanf()? Nein, denn das eine hat mit dem anderen nichts zu tun. Das Formatierungszeichen von printf() und scanf() wird immer zwischen zwei Hochkommata geschrieben ("%d"). Der Modulo-Operator % ist ein Rechenoperator, genau genommen ein integraler Rechenoperator, der zwischen zwei Operanden steht. Hier ein kleines Programmbeispiel: > /* modulo.c */ #include <stdio.h> int main(void) { int x=5; int y=2; x=x%y; printf("Der Rest von 5/2=%d\n",x); /* Rest=1 */ return 0; } Eventuell ist der Nutzen dieses Operators nicht sofort ersichtlich. Seine Verwendung wird in späteren Beispielen noch deutlicher gemacht. Zunächst noch ein weiteres Beispiel für den Modulo-Operator: > /* zeit.c */ #include <stdio.h> int main(void) { int sekunden,minuten; printf("Bitte geben Sie die Zeit in Sekunden ein :"); scanf("%d",&sekunden); minuten=sekunden/60; sekunden=sekunden%60; printf("genauer = %d min. %d sek.\n", minuten, sekunden); return 0; } Zuerst werden die eingegebenen Sekunden durch 60 dividiert, womit Sie die Minuten erhalten. AnschlieÃend wird der Modulo-Operator benutzt, um den Divisionsrest zu berechnen – in diesem Beispiel also die restlichen Sekunden. Abbildung 6.1 Rechenbeispiel mit dem Modulo-Operator # 6.3 Erweiterte Darstellung arithmetischer Operatoren ## 6.3 Erweiterte Darstellung arithmetischer Operatoren Die arithmetischen Operatoren, die im vorangegangenen Abschnitt verwendet wurden, lassen sich auch noch in anderer Form darstellen, und zwar in einer kürzeren Schreibweise: Erweiterte Darstellung | Bedeutung | | --- | --- | | | | | | | | | | | Das Rechenzeichen und das darauf folgende = verkörpern eigentlich nur eine verkürzte Schreibweise von: > Zahl = Zahl <operand> Zahl Es wird dabei auch von einem Zuweisungsoperator gesprochen. Somit sind die folgenden Schreibweisen gleichwertig: > printf("Die Fläche beträgt : %d\n", x *= x); printf("Die Fläche beträgt : %d\n", x = x * x); Zur Verdeutlichung ein Programm: > /* arithmetik2.c */ #include <stdio.h> int main(void) { int x=2, y=4, z=6; printf("x=%d\n",x); printf("y=%d\n",y); printf("z=%d\n",z); printf("%d\n",x+=y); printf("%d\n",z+=y); printf("%d\n",z+=x); printf("x=%d\n",x); // x wurde verändert. printf("y=%d\n",y); // y bleibt gleich. printf("z=%d\n",z); // z wurde verändert. return 0; } # 6.4 Inkrement- und Dekrement-Operatoren ## 6.4 Inkrement- und Dekrement-Operatoren Bei einem Inkrement oder Dekrement wird der Wert einer Variablen um 1 erhöht bzw. heruntergezählt. Diese Operatoren werden in C folgendermaÃen geschrieben: Dabei gibt es für diese Operatoren jeweils zwei Möglichkeiten: Verwendung | Bezeichnung | | --- | --- | | | | | | | | | Folgende Unterschiede gibt es zwischen der Postfix- bzw. Präfix-Schreibweise: * Die Postfix-Schreibweise erhöht bzw. verringert den Wert von var, gibt aber noch den alten Wert an den aktuellen Ausdruck weiter. * Die Präfix-Schreibweise erhöht bzw. verringert den Wert von var und gibt diesen Wert sofort an den aktuellen Ausdruck weiter. Hierzu ein Beispiel: > /* incr.c */ #include <stdio.h> int main(void) { int i=1; printf("i=%d\n",i); // i=1 i++; printf("i=%d\n",i); // i=2 printf("i=%d\n",i++); // i=2 printf("i=%d\n",i); // i=3 printf("i=%d\n",++i); // i=4 return 0; } Abbildung 6.2 Verwendung des Inkrement-Operators Analog verhält es sich mit dem Dekrement-Operator (--). Der Inkrement- und der Dekrement-Operator werden vorwiegend bei Schleifen genutzt. Beide Operatoren sind unärer Natur. # 6.5 Bit-Operatoren ## 6.5 Bit-Operatoren Mithilfe von Bit-Operatoren können Sie direkt auf die binäre Darstellung der Zahlen zurückgreifen. Zuerst eine kurze Ãbersicht, welche Bit-Operatoren es gibt: Bit-Operator | Bedeutung | | --- | --- | | | | | | | | | | | | | Wie schon bei den arithmetischen Operatoren steht Ihnen auch bei den bitweisen Operatoren die erweiterte Zuweisungsschreibweise zur Verfügung. ### 6.5.1 Bitweises UND Steht der &-Operator zwischen zwei Operanden, so handelt es sich um den bitweisen UND-Operator. Dieser ist leicht mit dem unären Adressoperator (siehe scanf()) zu verwechseln. Der Operator wird hauptsächlich dafür verwendet, einzelne Bits gezielt zu löschen. Folgendes Programmbeispiel soll dies demonstrieren: > /* and.c */ #include <stdio.h> int main(void) { int x=55; printf("x=%d\n",x); x= x&7; printf("x=%d\n",x); /* x=7 */ return 0; } Nach der Ausführung des Programms werden Sie sich fragen, warum die Verknüpfung mit dem UND-Operator zum Ergebnis 7 führt. Sehen Sie sich dies wieder in der Bitdarstellung an (unter Verwendung der ersten 8 Bits): Abbildung 6.3 Verwendung des bitweisen UND-Operators Dabei gelten per Definition folgende Regeln für den bitweisen UND-Operator: BitA | BitB | BitA&BitB | | --- | --- | --- | | | | | | | | | | | | | Mit dem bitweisen UND-Operator lässt sich sehr gut testen, ob eine Zahl gerade oder ungerade ist. Es muss nur Bit 0 (bzw. das 1. Bit) daraufhin überprüft werden, ob es gesetzt (ungerade, also = 1) oder nicht gesetzt (gerade, also = 0) ist. Folgendes Beispiel demonstriert dies: > /* gerade.c */ #include <stdio.h> int main(void) { int x; printf("Bitte geben Sie eine Zahl ein: "); scanf("%d",&x); if(x&1) // Ist das erste Bit gesetzt? printf("Eine ungerade Zahl\n"); else // Nein, es ist nicht gesetzt. printf("Eine gerade Zahl\n"); return 0; } ### 6.5.2 Bitweises ODER Mit dem bitweisen ODER-Operator können Sie gezielt zusätzliche Bits setzen. Verwendet wird dieser wie schon zuvor der bitweise UND-Operator: > char x = 1; x = x|126; // x=127 Auch hierzu die Bitdarstellung: Abbildung 6.4 Verwendung des bitweisen ODER-Operators Für den ODER-Operator gilt folgende Verknüpfungstabelle: BitA | BitB | (BitA|BitB) | | --- | --- | --- | | | | | | | | | | | | | ### 6.5.3 Bitweises XOR Der exklusive ODER-Operator XOR liefert nur dann eine 1 zurück, wenn beide Bits unterschiedlich sind. Er ist sehr gut geeignet, um Bits umzuschalten. Alle gesetzten Bits werden gelöscht und alle gelöschten gesetzt. Hier sehen Sie ein Beispiel: > char x=20; x = x^55; // x=35 In binärer Darstellung ergibt sich aus dieser Operation folgendes Bild: Abbildung 6.5 Verwendung des exklusiven ODER-Operators XOR Für XOR-Verknüpfungen gilt folgende Verknüpfungstabelle: BitA | BitB | BitA^BitB | | --- | --- | --- | | | | | | | | | | | | | ### 6.5.4 Bitweises Komplement Der NOT-Operator (~) wirkt sich auf Zahlen so aus, dass er jedes einzelne Bit invertiert. Bei vorzeichenbehafteten Datentypen entspricht das einer Negation mit anschlieÃender Subtraktion von 1: > char x=20; x=~x; /* x= -21 */ Für den NOT-Operator gilt folgende Verknüpfungstabelle: BitA | ~BitA | | --- | --- | | | | | ### 6.5.5 Linksverschiebung Mit einer Linksverschiebung (<<) werden alle Bits einer Zahl um n Stellen nach links gerückt. Die rechts entstehenden Leerstellen werden mit 0 aufgefüllt. Hier sehen Sie ein Beispiel für eine Linksverschiebung: > /* shift_left.c */ #include <stdio.h> int main(void) { char x=8; printf("x=%d\n",x); x<<=1; // Alle Bits um 1 Stelle nach links printf("x=%d\n",x); return 0; } Warum aus dem Wert 8 eine 16 wurde, wird aus der folgenden Bitdarstellung ersichtlich: Abbildung 6.6 Bitverschiebung nach links Sie werden es bemerkt haben: Hier wurde eine Multiplikation durchgeführt. Auf diese Weise können Zahlen sehr gut potenziert werden. Die Bitstelle um eine Position nach links zu rücken, bedeutet mathematisch eine Multiplikation mit 2. Bei Einrückung um zwei Stellen nach links wird mit 4 multipliziert, bei drei Stellen mit 8, bei vier Stellen mit 16 usw. Solche Bitverschiebungen können – abhängig vom System – bis zu 40(!)-mal schneller ablaufen als normale arithmetische Berechnungen im Stil von 4*x. ### 6.5.6 Rechtsverschiebung Die Rechtsverschiebung mit dem >>-Operator ist das Gegenstück zur Linksverschiebung (<<). Damit können Sie statt einer Multiplikation mit 2 eine Division durch 2 bewirken. Ansonsten gilt das Gleiche wie für die Linksverschiebung. ### 6.5.7 Rezept für Fortgeschrittene Oft ist eine Funktion wünschenswert, mit der eine Zahl daraufhin getestet wird, ob ein bestimmtes Bit gesetzt ist, oder mit der sich gezielt einzelne Bits setzen oder löschen lassen. Hierzu ein Listing mit entsprechenden Funktionen: > /* playing_bits.c */ #include <stdio.h> #define BYTE unsigned char /* Funktion : Bit_Test() * val : der Wert, den es zu testen gilt * bit : Bitnummer, die abgefragt wird, ob gesetzt (0-7) * Rückgabewert : (1)=Bit gesetzt; (0)=Bit nicht gesetzt */ int Bit_Test(BYTE val, BYTE bit) { BYTE test_val = 0x01; /* dezimal 1 / binär 0000 0001 */ /* Bit an entsprechende Pos. schieben */ test_val = (test_val << bit); /* 0=Bit nicht gesetzt; 1=Bit gesetzt */ if ((val & test_val) == 0) return 0; /* nicht gesetzt */ else return 1; /* gesetzt */ } /* Funktion : Bit_Set() * val : Wert, bei dem das Bit gesetzt werden soll * bit : Bitnummer, die gesetzt werden soll (0-7) * Rückgabewert : keiner */ void Bit_Set(BYTE *val, BYTE bit) { BYTE test_val = 0x01; /* dezimal 1 / binär 0000 0001 */ /* Bit an entsprechende Pos. schieben */ test_val = (test_val << bit); *val = (*val | test_val); /* Bit an Pos. bit setzen */ } /* Funktion : Bit_Clear() * val : Wert, bei dem das Bit gelöscht werden soll * bit : Bitnummer, die gelöscht werden soll (0-7) * Rückgabewert : keiner */ void Bit_Clear(BYTE *val, BYTE bit) { BYTE test_val = 0x01; /* dezimal 1 / binär 0000 0001 */ /* Bit an entsprechende Pos. schieben */ test_val = (test_val << bit); *val = (*val & (~test_val)); /* Bit an Pos. bit löschen*/ } int main(void) { BYTE wert = 0; /* Test, ob Bit 0 gesetzt ist */ printf("%s\n",Bit_Test(wert, 0)?"gesetzt":"nicht gesetzt"); Bit_Set(&wert, 0); /* Bit 0 setzen */ /* Wieder testen, ob Bit 0 gesetzt ist */ printf("%s\n",Bit_Test(wert, 0)?"gesetzt":"nicht gesetzt"); Bit_Clear(&wert, 0); /* Bit 0 wieder löschen */ /* Wieder testen, ob Bit 0 gesetzt ist */ printf("%s\n",Bit_Test(wert, 0)?"gesetzt":"nicht gesetzt"); return 0; } Die Funktionen können Sie natürlich Ihren eigenen Bedürfnissen entsprechend anpassen. Sie dienen nur als Anregung für weitere Spielereien mit Bits und Bytes. # 6.6 Makros für logische Operatoren und Bit-Operatoren – <iso646.h## 6.6 Makros für logische Operatoren und Bit-Operatoren – <iso646.hSeit dem C99-Standard finden Sie in der Headerdatei <iso646.h> einige Makros, die Sie als alternative Schreibweise für logische Operatoren und Bit-Operatoren nutzen können. In der folgenden Tabelle finden Sie einen Ãberblick zu den Makros. Konstante in <iso646.h> | Operator | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | Das bitweise XOR (exklusiver ODER-Operator, wie in Abschnitt 6.5.3) können Sie beispielsweise mit dem Makro xor wie folgt verwenden: ``` #include <iso646.h> ... char x = 20; x = x xor 55; // Alternative zu: x = x^55 ``` # 6.7 Der »sizeof«-Operator ## 6.7 Der »sizeof«-Operator Der Operator sizeof gibt Auskunft über die GröÃe eines Datentyps in Byte. Der sizeof-Operator wird später noch häufiger zur dynamischen Speicherreservierung verwendet. Zur Erklärung des sizeof-Operators folgt hier wieder ein Programmbeispiel: > /* sizeof_type.c */ #include <stdio.h> int main(void) { printf("char : %d Byte\n" , sizeof(char)); printf("int : %d Bytes\n", sizeof(int)); printf("long : %d Bytes\n", sizeof(long int)); printf("float : %d Bytes\n", sizeof(float)); printf("double : %d Bytes\n", sizeof(double)); printf("66 : %d Bytes\n", sizeof(66)); printf("Hallo : %d Bytes\n", sizeof("Hallo")); printf("A : %d Bytes\n", sizeof((char)'A')); printf("34343434 : %d Bytes\n", sizeof(34343434)); return 0; } Abbildung 6.7 Verwendung des »sizeof«-Operators Das Programm macht nichts anderes, als Ihnen die GröÃe, die der Datentyp belegt, in Byte auszugeben. Zum Beispiel: 'A' benötigt ein Byte Speicherplatz, da 'A' vom Typ char ist. Bei sizeof("Hello") sollten Sie sich jetzt noch keine Gedanken darüber machen, warum dieses Wort sechs Byte Speicher benötigt, obwohl es nur aus fünf Zeichen besteht. Das sechste Byte wird für das Stringende-Zeichen verwendet. Hier geht es im Augenblick lediglich um den sizeof-Operator. Jetzt fällt es sicher nicht mehr schwer, zu verstehen, wie Sie mit dem sizeof-Operator Speicherplatz reservieren können. Sie müssen dazu lediglich abfragen, wie viel Speicherplatz ein Datentyp benötigt, und den ermittelten Wert dann einer anderen Variablen (genauer: einem Zeiger) übergeben. Des Weiteren wird der sizeof-Operator zur Portierbarkeit von Programmen auf verschiedenen Systemen verwendet. Wie Sie bereits erfahren haben, gibt es Systeme, auf denen ein int-Wert eine SpeichergröÃe von zwei Byte hat. Auf anderen Systemen beträgt die GröÃe von int wiederum vier Byte. Als Beispiel dient folgender Pseudocode: > BRAUCHE_SPEICHER_PLATZ = (Datentyp)sizeof(4); Der Datentyp BRAUCHE_SPEICHER_PLATZ benötigt hier Speicherplatz der GröÃe eines int-Werts, in diesem Fall vier Bytes. Wenn das Programm jetzt beispielsweise auf ein anderes System portiert werden soll, auf dem der Datentyp int eine GröÃe von zwei Byte hat, dann könnte dies zu Problemen führen. Aus diesem Grund ist es besser, dem Compiler zur Ãbersetzungszeit diese Aufgabe zu überlassen. Dies geschieht folgendermaÃen (Pseudocode): > BRAUCHE_SPEICHER_PLATZ = (Datentyp)sizeof(int); Somit können Sie sicher sein, dass das Programm auf jedem System läuft und die richtige Menge an Speicherplatz reserviert. ### 6.7.1 C versus C++ Im Programmbeispiel des sizeof-Operators dürfte Ihnen folgende Zeile aufgefallen sein: > printf("A : %d Bytes\n", sizeof((char)'A')); Da in C ein Zeichenliteral vom Typ int ist, musste ich hier eine Typenumwandlung nach char machen. In C++ würde folgende Zeile auch 1 Byte ausgeben: > printf("A : %d Bytes\n", sizeof('A')); # 7.2 Explizite Datentypumwandlung mit dem »cast«–Operator ## 7.2 Explizite Datentypumwandlung mit dem »cast«–Operator Da die implizite Datentypumwandlung häufig zu Fehlern bzw. unerwünschten Ergebnissen führen kann, gibt es noch die explizite Datentypumwandlung, womit der Variablentyp mit cast-Operator durchgeführtwerden kann. Dieses explizite Casten des Datentyps wird quasi entgegen der Compiler-Regeln erzwungen. Der cast-Operator besteht aus einem eingeschlossenen gültigen Datentyp. Die Syntax einer expliziten Typumwandlung sieht folgendermaÃen aus: > (typ) ausdruck; Dabei wird zuerst der ausdruck ausgewertet, und anschlieÃend wird dieser Wert in einen Datentyp typ umgewandelt. Das folgende Beispiel zeigt das implizite und das explizite Type-Casting im Vergleich: > /* casting.c */ #include <stdio.h> int main(void) { int x = 5, y = 2; float z; // Implizite Datentypumwandlung z = x / y; printf("%f\n", z); // = 2.000000 // Explizite Datentypumwandlung z = (float) x / (float) y; printf("%f\n", z); // = 2.500000 return 0; } gibt das Ergebnis »2.000000« aus. Das ist leicht nachvollziehbar, denn es werden zwei int-Werte dividiert. int-Werte können keinen Wert nach dem Komma darstellen. Dass hier das Ergebnis dennoch vom Typ float ist, verdanken Sie dem impliziten Type-Casting des Compilers. konvertiert die beiden Datentypen int explizit in float-Typen. Deshalb erhalten Sie als Ergebnis »2.500000« zurück. Wichtig ist dabei, dass x und y im Programm weiterhin vom Datentyp int sind. Das »Casten« des Datentyps ist nur während dieser einen Ausführung gültig. Es hätte auch gereicht, nur einen dieser beiden Typen zu casten, denn wenn Sie zwei verschiedene Variablen miteinander durch Operatoren verknüpfen, bekommen Sie das Ergebnis des genaueren Typs dieser beiden Variablen zurück: > z = (float) x / y; /* Ergebnis = 2.50000 */ Aber Achtung, falls Sie vorhaben, Gleitpunktzahlen in Ganzzahlen umzuwandeln – etwa folgendermaÃen: > long x; float z = 5.5; x = (long) z; Hier wird der Wert nach dem Komma abgeschnitten. Falls Sie einen Wert umwandeln wollen, der gröÃer als seine Zielgruppe ist, liegt ein undefiniertes Verhalten vor. Wird z. B. ein float-Wert in einen short-Wert konvertiert, könnte das zu Problemen führen, denn der float-Wert hat eine GröÃe von vier Bytes und der short-Wert eine von zwei Bytes. Mit niedrigeren Werten mag dies zufällig funktionieren: > short x; float z = 25.0; x = (short) z; Sollte der Wert von float z. B. »1000000.0« betragen, wird dies nicht mehr gelingen, denn der Wert »1000000« ist nicht mehr mit 16 Bit (= 2 Bytes) darstellbar. Das Gleiche gilt auch für Casts von double nach float oder von long double nach double. # 8.2 Die Verzweigung mit »else if« ## 8.2 Die Verzweigung mit »else if« Was ist, wenn die erste Bedingung im Listing zuvor wahr ist, d. h. die Zahl gröÃer als 18 ist? Dann nimmt das Programm als nächsten Schritt dennoch die Ãberprüfung vor, ob die Zahl kleiner als 18 und gleich 18 ist. Das ist eigentlich nicht mehr notwendig. Sie können dies mit else if verbessern: > else if(alter > 18) { printf("Sie sind volljährig\n"); } else if(alter == 18) { printf("Den Führerschein schon bestanden?\n"); } Hier sehen Sie die Syntax dazu: > if(BEDINGUNG1 == wahr) { Anweisung1; } else if(BEDINGUNG2 == wahr) { Anweisung2; } Anweisung3; Ist die Bedingung1 wahr, wird die Anweisung1 im Anweisungsblock ausgeführt, und die Kontrollstruktur ist fertig. Ist Bedingung1 nicht wahr, wird die Bedingung2 überprüft. Ist Bedingung2 wahr, wird Anweisung2 ausgeführt, und das Programm endet. Ist aber auch Bedingung 2 nicht wahr, wird die Anweisung 3 ausgeführt. Das Programmbeispiel sieht in der neuen Fassung so aus: > /* if3.c */ #include <stdio.h> int main(void) { unsigned int alter; printf("Wie alt sind Sie: "); scanf("%u", &alter); if(alter < 18) { printf("Sie sind noch nicht volljährig\n"); } else if(alter > 18) { printf("Sie sind volljährig\n"); } else if(alter == 18) { printf("Den Führerschein schon bestanden?\n"); } printf("Bye\n"); return 0; } Abbildung 8.3 zeigt den Programmablaufplan dazu: Abbildung 8.3 Programmablaufplan mit »if else if« # 8.3 Die Verzweigung mit »else« ## 8.3 Die Verzweigung mit »else« Eigentlich hätten Sie sich im vorangegangenen Programmbeispiel folgende Bedingung sparen können: > else if(alter == 18) Denn wenn die Variable alter nicht gröÃer als 18 und auch nicht kleiner als 18 ist, kann diese nur noch gleich 18 sein. Um sich eine solche Bedingung zu ersparen, gibt es die else-Verzweigung, was so viel heiÃt wie Ansonsten nimm mich oder Andernfalls tue das Folgende: Sie könnten also die Zeile else if(alter == 18) ersetzen durch: > else { printf("Den Führerschein schon bestanden?\n"); } Die Syntax der if else-Verzweigung sieht folgendermaÃen aus: > if(BEDINGUNG == wahr) { Anweisung1; } else { Anweisung2; } Sehen Sie sich hierzu auch den Programmablaufplan an: Abbildung 8.4 Programmablaufplan mit »else« Umgeschrieben sieht das Listing jetzt wie folgt aus: > /* if4.c */ #include <stdio.h> int main(void) { unsigned int alter; printf("Wie alt sind Sie: "); scanf("%u", &alter); if(alter < 18) { printf("Sie sind noch nicht volljährig\n"); } else if(alter > 18) { printf("Sie sind volljährig\n"); } else { printf("Den Führerschein schon bestanden?\n"); } printf("Bye\n"); return 0; } Jetzt haben Sie die einzelnen Bedingungen im Programm optimal gestellt. Wird z. B. für das Alter der Wert 16 eingegeben, führt das Programm den entsprechenden Anweisungsblock aus. Danach folgen keine weiteren Ãberprüfungen. Wird hingegen für das Alter der Wert 20 genannt, ersparen Sie sich wenigstens die letzte Ãberprüfung, ob das Alter gleich 18 ist, und der entsprechende Anweisungsblock wird ausgeführt. Trifft keine dieser Bedingungen zu, wird der else-Anweisungsblock ausgeführt. Für das bessere Verständnis zeigt Abbildung 8.5 einen Programmablaufplan zu diesem Listing. Abbildung 8.5 Programmablaufplan zum Listing Häufig wird der Fehler gemacht, hinter eine Bedingungsanweisung ein Semikolon zu setzen: > else if(alter > 18); //Fehler (das Semikolon) { printf("Sie sind volljährig\n"); } Der Compiler wird Ihnen in solchen Fällen die Fehlermeldung ausgeben, dass else hier fehl am Platze ist. Denn einer else-Verzweigung muss immer ein if bzw. else if vorausgehen. Sie können probeweise im Listing hinter der else-Verzweigung ein Semikolon setzen. Das Programm wird dann immer ausgeben, dass die Variable gleich 18 ist. Dies wird zusätzlich ausgegeben, auch wenn eine der vorangegangenen Bedingungen bereits wahr gewesen ist. Es ist auch möglich, mehrere Anweisungen bzw. Anweisungsblöcke ineinander zu verschachteln. Das heiÃt, eine Anweisung mit Anweisungsblock steht innerhalb einer Anweisung mit Anweisungsblock. Ein Beispiel: > /* if5.c */ #include <stdio.h> int main(void) { unsigned int alter; printf("Wie alt sind Sie: "); scanf("%u", &alter); if(alter <= 18) { if(alter == 18) { printf("Den Führerschein schon bestanden?\n"); } else { printf("Sie sind noch nicht volljährig\n"); } } else { printf("Sie sind volljährig\n"); } printf("Bye\n"); return 0; } Das Listing bewirkt das Gleiche wie schon das Beispiel zuvor. Mit der Anweisung > if(alter <= 18) wird überprüft, ob alter kleiner oder gleich 18 ist. Sollte das der Fall sein, verzweigt das Programm weiter in den Anweisungsblock mit der Abfrage, ob alter gleich 18 ist. Wenn nicht, ist alter kleiner als 18. Sollte die Zahl aber gröÃer als 18 sein, geht es gleich zur else-Verzweigung weiter. Wie Sie die Anweisungsblöcke anordnen, bleibt Ihnen letztlich selbst überlassen. Sehen Sie sich dennoch einmal folgendes (Negativ-)Beispiel an: > /* if6.c */ #include <stdio.h> int main(void) { unsigned int alter; printf("Wie alt sind Sie: "); scanf("%u", &alter); if(alter <= 18){ if(alter == 18){ printf("Den Führerschein schon bestanden?\n");} else{ printf("Sie sind noch nicht volljährig\n"); }} else{printf("Sie sind volljährig\n");} printf("Bye\n"); return 0; } Das Programm ist zwar nicht falsch, aber dennoch etwas unübersichtlich. # 8.4 Der !-Operator (logischer Operator) ## 8.4 Der !-Operator (logischer Operator) Den logischen !-Operator (NOT-Operator) haben Sie eben schon kennengelernt. Dieser Operator wird oft falsch verstanden, weswegen ihm ein eigenes Kapitel gewidmet ist. Der !-Operator ist ein unärer Operator und kann einen Wert bzw. eine Bedingung negieren. Dies bedeutet, er kann aus »wahr« »falsch« machen und umgekehrt. Dazu ein Programmbeispiel: > /* logic_not1.c */ #include <stdio.h> int main(void) { int checknummer; printf("Bitte geben Sie Ihren Code-Schlüssel ein: "); scanf("%d", &checknummer); if( ! (checknummer == 4711) ) { printf("Error - Falscher Code-Schlüssel \n"); } else { printf("Success - Login erfolgreich \n"); } return 0; } Zur Erklärung der if-Bedingung im Programm: > if( !(checknummer == 4711) ) Hier wird der Ausdruck zwischen den Klammern geprüft. Das bedeutet, der !–Operator überprüft den Wert in der Klammer und gibt 1 (wahr) zurück, falls der Wert in der Klammer nicht 4711 ist. Ist der Wert aber gleich 4711, dann wird 0 (falsch) zurückgegeben. Das Programm fährt daraufhin mit der else-Verzweigung fort und gibt aus, dass Sie die richtige Zahl eingegeben haben. Tabelle 8.2 zeigt die verschiedenen Verwendungsmöglichkeiten. Anweisung | == | Anweisung | | --- | --- | --- | | | | | | | | | | | | | Hier sehen Sie ein weiteres Programmbeispiel zur Verdeutlichung: > /* logic_not2.c */ #include <stdio.h> int main(void) { int zahl1, zahl2; printf("Bitte Zahl 1 eingeben: "); scanf("%d", &zahl1); printf("Bitte Zahl 2 eingeben: "); scanf("%d", &zahl2); if(!zahl1) printf("Error: Der Wert ist gleich 0!! \n"); else if(!zahl2) printf("Error: Der Wert ist gleich 0!! \n"); else printf("%d/%d = %f \n", zahl1, zahl2, (float) zahl1/zahl2); return 0; } Sie vermeiden mit diesem Programm eine Division durch 0. Sollte also keine der beiden Zahlen dem Wert 0 entsprechen, wird mit (float) zahl1/zahl2 eine Division durchgeführt. Sie verwenden hier ein explizites Type-Casting, damit der Wert nach dem Komma nicht einfach abgeschnitten wird. # 8.5 Logisches UND (&&) – logisches ODER (||) ## 8.5 Logisches UND (&&) – logisches ODER (||) Sie haben sicher schon bemerkt, dass es in C viele Operatoren gibt. So ist die Sprache zwar unter Umständen schwerer lesbar, aber auch schneller, vielseitiger und effektiver zu programmieren. Sobald Sie die Operatoren kennengelernt haben, werden Sie diese sehr zu schätzen wissen. Mit dem logischen ODER-Operator (||) werden Operanden so miteinander verknüpft, dass der Ausdruck »wahr« zurückliefert, wenn mindestens einer der Operanden wahr ist. > if( (Bedingung1) || (Bedingung2) ) /* mindestens eine der Bedingungen ist wahr */ else /* keine Bedingung ist wahr */ Sehen Sie sich dazu in Abbildung 8.6 den Programmablaufplan des logischen ODER-Operators an. Abbildung 8.6 Der Programmablaufplan des logischen ODER-Operators Jetzt wird der Operator in dem Programm eingesetzt, das Sie beim logischen NICHT-Operator zuvor verwendet haben: > /* logic_or.c */ #include <stdio.h> int main(void) { int zahl1, zahl2; printf("Bitte Zahl 1 eingeben: "); scanf("%d", &zahl1); printf("Bitte Zahl 2 eingeben: "); scanf("%d", &zahl2); if( (!zahl1) || (!zahl2) ) printf("Error: Einer der Werte ist gleich 0!!! \n"); else printf("%d/%d = %f \n", zahl1, zahl2, (float)zahl1/zahl2); return 0; } Die if-Konstruktion des Programms sieht so aus: > if( (!zahl1) || (!zahl2) ) In Worten ausgedrückt, sähe das etwa folgendermaÃen aus: Ist der Wert zahl1 gleich 0 ODER der Wert zahl2 gleich 0, dann ist die Bedingung wahr, und Sie haben eine 0 eingegeben. Sollte die erste Bedingung (!zahl1) schon wahr sein, so wird die zweite Bedingung (!zahl2) gar nicht mehr überprüft: Dies können Sie auch am Programmablaufplan erkennen. Analog verhält es sich mit dem logischen UND-Operator (&&). Das Ergebnis dieser verknüpften Operanden gibt nur dann »wahr« zurück, wenn alle Operanden wahr sind. Den Programmablaufplan des logischen UND-Operators sehen Sie in Abbildung 8.7. Abbildung 8.7 Programmablaufplan des logischen UND-Operators Wiederum folgt zur Verdeutlichung ein Programmbeispiel: > /* logic_and.c */ #include <stdio.h> int main(void) { int zahl; printf("Geben Sie einen Wert zwischen 10 und 20 ein: "); scanf("%d", &zahl); if( (zahl >= 10) && (zahl <= 20) ) printf("Danke für die Eingabe! \n"); else printf("Falsche Eingabe! \n"); return 0; } In der Zeile > if( (zahl >= 10) && (zahl <= 20) ) prüfen Sie, ob die eingegebene Zahl einen Wert zwischen 10 und 20 besitzt. In Worten: Ist es wahr, dass die Zahl gröÃer oder gleich 10 ist UND die Zahl auch kleiner gleich 20 ist, dann ist die Bedingung wahr. Natürlich können Sie mit dem &&-Operator und dem ||-Operator weitere Bedingungen miteinander verknüpfen. Allerdings sollten Sie dabei die Lesbarkeit eines solchen Konstrukts im Auge behalten. # 8.6 Der Bedingungsoperator »?:« ## 8.6 Der Bedingungsoperator »?:« Der Bedingungsoperator ?: ist ein ternärer Operator (der einzige in ANSI C). Im Prinzip repräsentiert dieser Operator nichts anderes als eine Kurzform der if else-Anweisung. Seine Syntax sieht so aus: > <BEDINGUNG> ? <ANWEISUNG 1> : <ANWEISUNG 2Wenn die BEDINGUNG wahr ist, wird die ANWEISUNG1 ausgeführt. Ansonsten wird ANWEISUNG2 ausgeführt. Der Programmablaufplan ist identisch mit dem der if else-Anweisung. Sie benötigen beispielsweise von zwei Zahlen den höheren Wert? Mit dem Bedingungsoperator ?: könnten Sie folgendermaÃen arbeiten: > max = (a>b) ?a :b; Diese Schreibweise ist äquivalent zu der folgenden: > if(a > b) max=a; else max=b; Ein Listing soll das Prinzip verdeutlichen: > /* max_val.c */ #include <stdio.h> int main(void) { int a=5,b=10; int max; max = (a > b) ? a : b; printf("Der gröÃte Wert ist %d \n", max); return 0; } Natürlich ist es auch hier möglich, die einzelnen Ausdrücke ineinander zu verschachteln: > /* more_max_val.c */ #include <stdio.h> int main(void) { int a=8, b=3, c=76, big; printf("Die gröÃte Zahl ist...."); big = (a>b) ? ((a>c) ?a :c) : ((b>c) ?b :c); printf("..%d\n", big); return 0; } Auch hier kann bei mehrfacher Verschachtelung die Ãbersichtlichkeit und Nachvollziehbarkeit des Programms leiden. Hier wären if else-Anweisungen besser geeignet. Sehen Sie sich folgende Codezeile näher an: > big = (a>b) ? ((a>c) ?a :c) : ((b>c) ?b :c); Bevor die Variable big einen Wert zugewiesen bekommt, werden zuerst folgende Bedingungen überprüft: Ist der Wert von a gröÃer als der von b, wird überprüft, ob der Wert von a auch gröÃer als der von c ist. Ist das der Fall, so ist a der gröÃte Wert. Ist dies nicht der Fall, ist c der gröÃte Wert. Sollte aber in der ersten Bedingung a nicht gröÃer als b sein, so wird überprüft, ob b gröÃer als c ist. Ist b gröÃer als c, haben Sie den gröÃten Wert gefunden. Ist b nicht gröÃer als c, bleibt nur noch c als gröÃte Zahl übrig. Häufig wird der Bedingungsoperator auch wie folgt verwendet: > printf("Bitte geben Sie eine Zahl ein: "); scanf("%d",&zahl); printf("Die Zahl, die Sie eingegeben haben, ist "); (zahl%2) ? printf("ungerade \n") : printf("gerade \n"); # 8.7 Fallunterscheidung: die »switch«-Verzweigung ## 8.7 Fallunterscheidung: die »switch«-Verzweigung Was ist zu tun, wenn unterschiedliche Bedingungen mehrere verschiedene Zahlen beachten sollen? Sie könnten entsprechend viele if-Anweisungen verwenden. Aber warum so umständlich, wenn es auch einfacher geht? Für solche Aufgaben gibt es die Fallunterscheidung mit switch, was auf Deutsch so viel wie »Schalter« heiÃt. Die Syntax von switch sieht so aus: > switch(AUSDRUCK) { AUSDRUCK_1 : anweisung_1 AUSDRUCK_2 : anweisung_2 AUSDRUCK_3 : anweisung_3 ... AUSDRUCK_n : anweisung_n } Der AUSDRUCK in den Klammern nach switch wird im darauf folgenden Anweisungsblock ausgewertet. Sollte der AUSDRUCK==AUSDRUCK_1 sein, so wird anweisung_1 ausgeführt. Sollte aber AUSDRUCK==AUSDRUCK_2 sein, so wird die anweisung_2 ausgeführt usw. Hier ist ein Programm, das Sie nach den Zahlen 1 – 5 fragt: > /* switch1.c */ #include <stdio.h> int main(void) { int a; printf("Bitte eine Zahl von 1-5 eingeben: "); scanf("%d", &a); switch(a) { case 1: printf("Das war eins \n"); break; case 2: printf("Das war zwei \n"); break; case 3: printf("Das war drei \n"); break; case 4: printf("Das war vier \n"); break; case 5: printf("Das war fünf \n"); break; } /* Ende switch */ return 0; } Nach der Eingabe einer Zahl wird diese im Schalter ausgewertet mit: > switch(a) Die Auswertung steht wieder in einem Anweisungsblock in geschweiften Klammern. Zuerst wird > case 1: printf("Das war eins \n"); ausgewertet. case heiÃt auf Deutsch »Fall«. Zuerst wird geprüft, ob der Fall, der in switch(a) steht, zutrifft (also hier, ob a==1). Wenn ja, wird das Programm den entsprechenden Text ausgeben. > break; Die break-Anweisung am Ende eines jeden Falls bedeutet: Ab hier springt das Programm aus dem Anweisungsblock heraus und setzt seine Ausführung nach dem switch-Anweisungsblock fort. In unserem Fall endet das Programm dann bereits. Wenn break nicht nach jedem Fall angegeben wird, wird der nächste Fall auch ausgegeben. Sehen Sie sich einen Programmablaufplan dazu an (siehe Abbildung 8.8). Das Weglassen von break kann aber durchaus gewollt sein. Dies hat den Vorteil, dass Sie in gewisser Weise auf mehrere Fälle gleichartig reagieren können. Das obige Programm wird leicht abgewandelt: > /* switch2.c */ #include <stdio.h> int main(void) { int a; printf("Bitte eine Zahl von 1-5 eingeben: "); scanf("%d", &a); switch(a) { case 1: printf("Das war eins oder..."); case 2: printf("...zwei \n"); break; case 3: printf("Das war drei \n"); break; case 4: printf("Das war vier..."); case 5: printf("...oder fünf \n"); break; } /* Ende switch */ return 0; } Abbildung 8.8 Programmablaufplan zur »switch«-Fallunterscheidung Geben Sie in diesem Programm beispielsweise den Wert 4 für die Variable a ein, so trifft sowohl der Fall case 4 als auch case 5 zu, weil bei der Fallunterscheidung case 4 das break nach der printf()-Ausgabe weggelassen wurde. Ebenso würde sich das Programm verhalten, wenn Sie den Wert 1 eingegeben hätten. ### 8.7.1 default Jetzt stellt sich die Frage, was geschieht, wenn Sie einen anderen Wert als 1 bis 5 eingeben. Das Programm einfach ohne eine Meldung zu beenden, ist unschön, denn auch bei falschen Werten sollte eine Reaktion erfolgen. Dafür gibt es das Schlüsselwort default. Testen Sie es gleich in einem Programm: > /* switch3.c */ #include <stdio.h> int main(void) { int a,b; char opera; printf("Grundrechenarten \n"); printf(" (zahl)(Operator)(zahl) ohne Leerzeichen \n"); printf("Rechnung bitte eingeben : "); scanf("%d%c%d", &a, &opera, &b); /* Bsp.: 10+12 */ switch(opera) { case '+': printf("%d + %d = %d \n",a ,b ,a+b); break; case '-': printf("%d - %d = %d \n", a, b, a-b); break; case '*': printf("%d * %d = %d \n", a, b, a*b); break; case '/': printf("%d / %d = %d \n", a, b, a/b); break; default: printf("%c? kein Rechenoperator \n", opera); } /* Ende switch */ return 0; } Jetzt haben Sie auch gesehen, wie es möglich ist, jedes beliebige darstellbare ASCII-Zeichen mit case zu überprüfen. Einzelne Zeichen werden – wie beim Programm mit den Operatoren eben verwendet – zwischen einzelne Hochkommata gestellt. Natürlich wäre es auch denkbar, statt > case '+': printf("%d + %d = %d \n", a, b, a+b); eben > case 43 : printf("%d + %d = %d \n", a, b, a+b); zu verwenden, da ja das Zeichen '+' den dezimalen Wert 43 hat (siehe ASCII-Tabelle). Sie könnten auch die Oktalzahl 053 oder die Hexzahl 2B verwenden. Hier ist die Schreibweise für die Hexzahl von '+': > case 0x2B: printf("%d + %d = %d \n", a, b, a+b); Im Programm haben Sie gesehen, wie default verwendet wurde: > default: printf("'%c' ist kein Rechenoperator \n", opera); Falls Sie keine gültigen Rechenoperatoren eingegeben haben, bekommen Sie eine entsprechende Meldung. default bedeutet hier: Falls eine passende case-Verzweigung fehlt, nimm immer das Folgende. Wenn also keine case-Anweisung greift, dann wird der Code-Block nach default ausgeführt (man spricht oft vom sogenannten Default-Verhalten, wenn der default-Block ausgeführt wird). Sie werden in einem späteren Abschnitt (8.9) noch sehen, dass sich die switch-Verzweigung hervorragend für den Aufbau eines einfachen Menüs in einer Konsolenanwendung eignet. # 8.8 Die »while«-Schleife ## 8.8 Die »while«-Schleife Mit Schleifen können Sie Anweisungsblöcke mehrfach hintereinander ausführen lassen. Das Grundgerüst der Schleifenbedingung while sieht folgendermaÃen aus: > while(Bedingung == wahr) { /* Abarbeiten von Befehlen, bis Bedingung ungleich wahr */ } Ist die Bedingung, die in den Klammern nach while folgt, wahr, so wird der Anweisungsblock in geschwungenen Klammern (oft auch »curly brackets« genannt) ausgeführt. Diese Anweisungen werden so oft ausgeführt, bis die Bedingung in den Klammern falsch, also unwahr ist. Den zugehörigen Programmablaufplan sehen Sie in Abbildung 8.9. Ãblicherweise läuft die while-Schleife in drei Schritten ab: * Initialisierung – Die Schleifenvariable bekommt einen Wert. * Bedingung – Die Schleifenvariable wird daraufhin überprüft, ob eine bestimmte Bedingung bereits erfüllt ist. * Reinitialisieren – Die Schleifenvariable erhält einen anderen Wert. Abbildung 8.9 Programmablaufplan der »while«-Schleife In der Praxis sieht dies etwa so aus: > int var=0; // Initialisieren while(var < 10) { // Solange var kleiner als 10 - Bedingung // weitere Anweisungen var++; // Reinitialisieren } Jetzt folgt ein Listing mit einer while-Schleife: > /* while1.c */ #include <stdio.h> int main(void) { int zahl=1, tmp=0; while(zahl <= 10) { tmp=tmp+zahl; printf("%d+",zahl++); /* Zahl + 1 */ } printf("\b = %d\n",tmp); return 0; } Das Programm führt die while-Schleife so lange aus, bis die Variable zahl kleiner oder gleich 10 ist. Hier ein kurzer Durchgang des Programms Schritt für Schritt: > while(zahl<=10) Ist die Zahl kleiner oder gleich 10? Die Zahl hat den Wert 1, also wird in den Anweisungsblock gesprungen. Hier wird zuerst die Addition tmp=tmp+zahl durchgeführt. Somit ist der Wert von tmp 1. Jetzt wird die Variable zahl um 1 erhöht (zahl++). Der while-Anweisungsblock endet, und das Programm springt zurück zum Anfang der while-Anweisung. Es erfolgt eine erneute Ãberprüfung daraufhin, ob die Zahl immer noch kleiner oder gleich 10 ist. Da sie jetzt den Wert 2 hat, geht es wie vorher schon im Anweisungsblock weiter. Das wird so lange wiederholt, bis zahl den Wert 11 erreicht hat. Denn dann ist die Bedingung, ob zahl kleiner oder gleich 10 ist, falsch (unwahr). Das Programm läuft nach dem while-Anweisungsblock weiter und gibt das Ergebnis 55 aus. ### 8.8.1 Endlosschleife (»while«) Die while-Schleife wird oft absichtlich in Form einer Endlosschleife implementiert. Für das Beenden einer Endlosschleife sorgt dann nicht die Schleifenbedingung, sondern das Schlüsselwort break. Mit der break-Anweisung können Sie die Schleife jederzeit verlassen. Hier sehen Sie ein Beispiel für eine Endlosschleife: > /* while2.c */ #include <stdio.h> int main(void) { int zahl, summe=0; printf("Summenberechnung\nBeenden der Eingabe mit 0 \n"); while(1) { /* Endlosschleife, denn: 1 ist immer wahr */ printf("Bitte Wert eingeben > "); scanf("%d", &zahl); if(zahl == 0) /* Haben wir 0 eingegeben ...? */ break; /* ... dann raus aus der Schleife */ else summe+=zahl; } printf("Die Summe aller Werte beträgt: %d\n", summe); return 0; } Die Zeile > while(1) verkörpert die Endlosschleife. Der Inhalt dieser Schleife ist immer wahr, da Sie hier den Wert 1 haben. Sie könnten dort jede beliebige Zahl auÃer 0 hinschreiben. Sie haben in den vorangegangenen Kapiteln gesehen, dass 1 (und alle anderen Werte ungleich 0) für »wahr« (true) und 0 für »unwahr« (false) steht. Zurück zu dem Programm. Sie werden so lange aufgefordert, eine Zahl einzugeben, bis Sie den Wert 0 verwenden: > if(zahl == 0) /* Falls 0 eingegeben wurde ... */ break; /* ... dann Schleife verlassen */ Hat die Variable zahl den Wert 0, wird mit der Anweisung break aus dem Anweisungsblock herausgesprungen. ### 8.8.2 Fehlervermeidung bei »while«-Schleifen Natürlich können Sie mit Schleifen auch diverse Fehler machen. Im Folgenden sollen daher einige häufig auftretende Fehler angesprochen werden. SchlieÃen Sie eine Schleife niemals mit einem Semikolon ab. Folgendes Beispiel erzeugt ungewollt eine Endlosschleife: > int x=0; while(x > 10); /* Fehler durch Semikolon am Ende */ { printf("Der Wert von x beträgt %d\n", x); x++; } Die Variable x wird niemals im Anweisungsblock inkrementiert werden, da die while-Schleife nichts anderes tut, als ständig die Bedingung zu prüfen, ob x gröÃer als 10 ist. Vermeiden Sie auÃerdem – wenn möglich – Ãberprüfungen auf Gleichheit in den Schleifen: > int x=2; while(x == 10) { printf("Der Wert von x beträgt %d \n", x); x*=x; } Die Bedingung der while-Schleife wird nie erfüllt. Verwenden Sie in einem solchen Fall besser die Ãberprüfung auf kleiner oder gleich, etwa wie folgt: > while(x <= 10) Eine weitere Fehlerquelle können die logischen Operatoren in der while-Schleife darstellen, wie das folgende Programmbeispiel verdeutlicht: > /* while3.c */ #include <stdio.h> int main(void) { int zahl1=0, zahl2=0; while((zahl1++ < 5) || (zahl2++ < 5) ) printf("Wert von zahl1: %d zahl2: %d \n ", zahl1, zahl2); return 0; } Da hier der erste Ausdruck fünfmal wahr ist, wird wegen des logischen ODER-Operators der zweite Ausdruck nicht ausgewertet. Erst dann, wenn der erste Ausdruck unwahr, also 5 ist, wird der zweite Ausdruck fünfmal durchlaufen. Als Nebeneffekt wird aber gleichzeitig der erste Ausdruck bei jedem Schleifendurchlauf inkrementiert. Und so kommt es, dass die Variable zahl1 am Ende den Wert 10 hat, statt 5 wie ursprünglich beabsichtigt. # 8.9 Die »do while«-Schleife ## 8.9 Die »do while«-Schleife Die Schleife do while verhält sich wie die while-Schleife, nur dass die Bedingung am Ende des Anweisungsblocks überprüft wird. Hier die Syntax: > do { /* Anweisungen */ } while(BEDINGUNG == wahr); Der Anweisungsblock wird mit dem Schlüsselwort do eingeleitet. Im Block werden dann Anweisungen ausgeführt. Am Ende des Anweisungsblocks steht der bereits bekannte Ausdruck while, bei dem überprüft wird, ob die angegebene Bedingung wahr ist. Ist die Bedingung wahr, wird der Anweisungsblock erneut ausgeführt, und es beginnt wieder bei do. Wenn die Bedingung unwahr ist, geht es hinter der while-Bedingung weiter. Achten Sie auch darauf, dass Sie die do while-Schleife am Ende von while mit einem Semikolon abschlieÃen. Das Semikolon zu vergessen, ist ein häufig gemachter Fehler. Abbildung 8.10 zeigt den Programmablaufplan zur do while-Schleife. Abbildung 8.10 Programmablaufplan der »do while«-Schleife Zur Veranschaulichung sehen Sie hier ein weiteres Listing: > /* do_while1.c */ #include <stdio.h> #include <stdlib.h> /* für die Bibliotheksfunktion rand() */ int main(void) { int ratezahl, count=0, erraten=0; int zufall = rand() % 10; /* Pseudo-Zufallszahl von 1-10 */ do { printf("Zahleingabe bitte (1-10): "); scanf("%d", &ratezahl); if(ratezahl==zufall) { /* Zahl richtig geraten ... ? */ erraten=1; /* Ja, die Zahl ist richtig */ count++; } else { (ratezahl > zufall) ? printf("kleiner\n") : printf("grösser\n"); count++; } } while( (erraten != 1) && (count != 3) ); if(erraten == 0) { printf("Sie haben 3 Chancen vertan ;) \n"); printf("Die Zahl wäre %d gewesen: \n", zufall); } else printf("Mit %d Versuchen erraten!\n",count); return 0; } In diesem Programm wird die Headerdatei > #include<stdlib.hfür die Funktion > rand() % 10; verwendet, womit eine (Pseudo-)Zufallszahl zwischen 1 und 10 erzeugt wurde, deren Wert Sie an die Variable zufall übergeben. Die do while-Schleife wird so lange wiederholt, bis die beiden Ausdrücke in while wahr sind: > while( (erraten != 1) && (count != 3) ); Die Bedingung für das Spiel lautet also: Sie haben maximal 3 Versuche (count != 3), in denen Sie die Zahl erraten müssen. Solange Sie die Variable von erraten auf dem Wert 0 UND den Zähler für die Versuche count noch nicht auf 3 stehen haben, beginnt der Anweisungsblock wieder von Neuem. Ist eine dieser Bedingungen unwahr, haben Sie entweder die Zahl erraten oder mehr als drei Versuche benötigt. Dies wird anschlieÃend nach dem Anweisungsblock ausgewertet. Aber warum lassen Sie nicht den Computer eine Zahl raten, die Sie sich ausgedacht haben? »Künstliche Intelligenz« und »zu kompliziert« denken Sie? Solch ein Spiel lässt sich einfacher realisieren, als Sie glauben. Hier ist das Spiel andersherum: > /* do_while2.c */ #include <stdio.h> int main(void) { char response; printf("Denk Dir eine Nummer zwischen 1 und 100 aus.\n"); printf("Das errate ich in 7 oder weniger Versuchen \n\n"); do { int lo = 1, hi = 100; int guess; while (lo <= hi) { guess = (lo + hi) / 2; printf("Ist es %d ",guess); printf(" ((h)oeher/(n)iedriger/(j)a): "); fflush(stdout); scanf("%c%*c",&response); if (response == 'h') lo = guess + 1; else if (response == 'n') hi = guess - 1; else if (response != 'j') printf("Erraten ... :-)"); else break; } /* Resultat ausgeben */ if (lo > hi) printf("Du schummelst!\n"); else printf("Deine Nummer lautet: %d\n",guess); printf("Noch ein Spiel (j)a/nein : "); fflush(stdout); scanf("%c%*c",&response); } while( response == 'j' ); return 0; } Der Computer errät dabei Ihre Zahl immer in maximal sieben Versuchen. Verwendet wird dabei ein sogenanntes »Teile und herrsche«-Prinzip. Die Variable guess erhält durch die Berechnung (lo+hi)/2 zuerst den Wert 50. Ist die von Ihnen gesuchte Zahl jetzt höher, erhält die Variable lo einen neuen Wert mit guess+1, also 51. Somit beginnt das Teilen und Herrschen von Neuem mit (lo+hi)/2, in Zahlen: (51+100)/2, also 75. Ist jetzt die gesuchte Zahl niedriger, bekommt hi einen neuen Wert mit guess-1. Es ergibt sich beim nächsten Schleifendurchlauf (lo+hi)/2, in Zahlen: (51+74)/2, also 62. Und so weiter, bis die Zahl erraten wurde. Auf dieses »Teile-und-herrsche-Prinzip« werden Sie noch einige Male in diesem Buch stoÃen. Ein weiteres praktisches Anwendungsbeispiel der do while-Schleife ist ein Benutzermenü für die Konsole: > /* do_while3.c */ #include <stdio.h> int main(void) { int auswahl; do { printf("-1- Auswahl1\n"); printf("-2- Auswahl2\n"); printf("-3- Auswahl3\n"); printf("-4- Programmende \n\n"); printf("\n\n Ihre Auswahl: "); scanf("%d", &auswahl); switch(auswahl) { case 1 : printf("\n Das war Auswahl 1 \n"); break; case 2 : printf("\n Das war Auswahl 2 \n"); break; case 3 : printf("\n Das war Auswahl 3 \n"); break; case 4 : printf("\n Programmende \n"); break; default : printf("\n Unbekannte Auswahl \n"); } } while(auswahl!=4); return 0; } Meist stellt sich nach einem solchen Menübeispiel die Frage, wie der Bildschirm gelöscht werden kann. In ANSI C ist aber keine Funktion dafür vorgesehen. Das bedeutet, dass es von Compiler und Betriebssystem abhängt, ob eine (nicht standardisierte) Funktion hierfür existiert. Wenn Sie eine solche verwenden wollen, halten Sie Ausschau nach Funktionen wie clrscr() für Microsoft Windows oder nach der Bibliothek <ncurses.h> für Linux/UNIX. # 8.10 Die »for«-Schleife ## 8.10 Die »for«-Schleife Mit der for-Schleife können Sie – wie schon mit der while-Schleife – Anweisungsblöcke mehrfach hintereinander ausführen. Der Unterschied ist jedoch, dass bei der for-Schleife die Initialisierung, die Bedingung und die Reinitialisierung der Schleifenvariable schon in der for-Anweisung erfolgen. Die Syntax zur for-Schleife: > for(Initialisierung; Bedingung; Reinitialisierung) { /* Anweisungen */ } Beim Ablauf der for-Schleife wird in der Regel zuerst die Schleifenvariable initialisiert. Dies geschieht aber nur einmal, unabhängig davon, wie oft sich die Schleife wiederholt. Danach findet typischerweise eine Bedingungsüberprüfung statt. Ergibt diese »wahr«, geht die Ausführung im Anweisungsblock mit weiteren Anweisungen weiter. Hat der Anweisungsblock alle Anweisungen ausgeführt, wird die Reinitialisierung der Schleifenvariable ausgeführt. Dann wird erneut die Schleifen-Bedingung überprüft, und alles beginnt von vorn. Die for-Schleife wird beendet, wenn die Schleifenbedingung nicht mehr wahr ist. Die Arbeitsweise einer for-Schleife lässt sich gut anhand des folgenden Beispiels demonstrieren: > /* for1.c */ #include <stdio.h> int main(void) { int i; for(i=1; i <= 5; i++) printf("for(i=1; %d <= 5; %d++) \n", i, i); return 0; } Das Programm zeigt jeweils den aktuellen Variableninhalt von i in der for-Schleife. Wie Sie in diesem Beispiel gesehen haben, kann auch bei den Schleifen der Anweisungsblock mit den geschweiften Klammern weggelassen werden, wenn dieser nur aus einer Anweisung besteht. Der Programmablaufplan der for-Schleife ist in Abbildung 8.11 dargestellt. Mit for-Schleifen lassen sich aber nicht nur Schleifen zum Dekrementieren (––) bzw. Inkrementieren (++) realisieren. Sie können in der for-Schleife auch weitere Rechenoperationen vornehmen. Hier sehen Sie ein Programm, das immer die letzte Dezimalstelle eines Werts abschneidet. Die Ergebniszahl soll danach spiegelverkehrt ausgegeben werden: > /* for2.c */ #include <stdio.h> int main(void) { int zahl; for(zahl=1234; zahl >= 1; zahl/=10) printf("%d", zahl%10); printf("\n"); return 0; } # Typische Fehler bei der Verwendung einer »for«-Schleife * Ein häufiger Fehler ist, das Semikolon zwischen der Initialisierung, der Bedingung und der Reinitialisierung der Schleifenvariable zu vergessen. > for(i=1 i<=5 i++) /* korrekt-> */ for(i=1; i<=5; i++) * Natürlich sollten Sie auch nicht den Fehler machen, am Ende der Schleife ein Semikolon zu setzen; auÃer es ist gewollt. > for(i=1; i<=5; i++); /* korrekt-> */ for(i=1; i<=5; i++){ } * Und das Wichtigste ist, für die richtige Abbruchbedingung zu sorgen, da sonst das Programm die for-Schleife nicht mehr verlässt. Man spricht dann von einer Endlosschleife. > for(i=2; i!=5; i+=2) /* korrekt-> */ for(i=2; i<=5; i+=2) Abbildung 8.11 Programmablaufplan der »for«-Schleife ### 8.10.1 Einsatzmöglichkeiten der »for«-Schleife Als Anregung und Ãbung zeige ich Ihnen im Anschluss 10 verschiedene Möglichkeiten der Verwendung einer for-Schleife. # 1. Möglichkeit > /* for3.c */ #include <stdio.h> int main(void) { int sek; for(sek = 5; sek > 0; sek--) printf("%d Sekunden!\n", sek); printf("Die Zeit ist abgelaufen! \n"); return 0; } Hier benutzen Sie den Dekrement-Operator zum Rückwärtszählen. Die Schleife zählt so lange rückwärts, bis der Wert sek gleich 0 ist. # 2. Möglichkeit > /* for4.c */ #include <stdio.h> int main(void) { int n; for(n = 0; n <= 60; n = n + 10) printf("%d\n",n); return 0; } Sie können innerhalb der Schleife nicht nur inkrementieren und dekrementieren, sondern auch rechnen. In diesem Fall werden die Zahlen in 10er-Schritten ausgegeben – von 0 bis 60. # 3. Möglichkeit > /* for5.c */ #include <stdio.h> int main(void) { char ch; for(ch = 'A'; ch <= 'Z'; ch++) printf("%c, ", ch); printf("\n"); return 0; } Diese Möglichkeit funktioniert auch sehr gut mit dem Datentyp char. Dann wird das Alphabet in GroÃbuchstaben ausgegeben. # 4. Möglichkeit > /* for6.c */ #include <stdio.h> int main(void) { int cube; for(cube = 1; cube * cube * cube <= 216; cube++) printf("n=%d Volumen : %d \n", cube, cube*cube*cube); return 0; } Als Abbruchbedingung können Sie ebenso eine Berechnung verwenden. In diesem Fall soll das Volumen eines Würfels bis zur GröÃe von maximal 216 berechnet werden. Die Abbruchbedingung ist also erreicht, wenn cube bis 7 hochgezählt wurde, da 7 * 7 * 7 gröÃer ist als 216. # 5. Möglichkeit > /* for7.c */ #include <stdio.h> int main(void) { double zs; for(zs = 100.0; zs < 150.0; zs = zs * 1.1) printf("%.2f\n", zs); return 0; } Bei dieser Möglichkeit werden immer 10 % vom jeweiligen Gesamtwert berechnet. Sie haben zum Beispiel 100  auf der Bank und bekommen darauf 10 % Zinsen im Jahr. Sie wollen wissen, nach wie vielen Jahren der Betrag in die Nähe von 150  kommt. # 6. Möglichkeit > /* for8.c */ #include <stdio.h> int main(void) { int x,y=50; for(x = 0; y <= 75; y = (++x*5) + 50) printf("%d\n", y); return 0; } Diese etwas komplex anmutende Schleife tut nichts anderes, als einen Wert in 5er-Schritten von 50–75 auszugeben. Zuerst wird in den Klammern (x*5) berechnet und anschlieÃend 50 addiert. Da x sich bei jedem Durchlauf um den Wert 1 erhöht und mit 5 multipliziert wird, ergeben sich Werte in 5er-Sprüngen. # 7. Möglichkeit > /* for9.c */ #include <stdio.h> int main(void) { int x = 2, y; for(y=2; x<20;) { x = x * y; printf("%d\n", x++); } return 0; } Sie sehen hier, dass nicht unbedingt alle Variablen einer for-Schleife deklariert werden müssen. Lediglich die beiden Semikolons müssen immer in der for-Schleife stehen. # 8. Möglichkeit > /* for10.c */ #include <stdio.h> int main(void) { for(;;) printf("Endlosschleife!!\n"); return 0; } Hier ein Beispiel, bei dem überhaupt nichts in der for-Schleife steht. Wenn Sie dieses Programm ausführen, wird so lange der String Endlosschleife auf dem Bildschirm ausgegeben, bis Sie das Programm selbst gewaltsam abbrechen. Die Schreibweise for(;;) ist gleichwertig mit while(1). Beides sind Formen von Endlosschleifen. # 9. Möglichkeit > /* for11.c */ #include <stdio.h> int main(void) { int n; for( printf("Bitte eine Zahl eingeben: "); n!=5; ) scanf("%d", &n); printf("Diese Zahl wollte ich\n"); return 0; } Hier benutzen Sie die for-Schleife zur Abfrage einer Zahl. Die Schleife wird beendet, wenn Sie die Zahl 5 eingeben. # 10. Möglichkeit > /* for12.c */ #include <stdio.h> int main(void) { int n1, n2; for(n1 = 1, n2 = 2; n1 <= 10; n1++) printf("%d\n",n1*n2); return 0; } Es ist auch möglich, mehrere Werte innerhalb einer for-Schleife zu initialisieren. Natürlich war dies nur eine Auswahl von Verwendungsmöglichkeiten einer for-Schleife. Der Abschnitt sollte jedoch zeigen, wie flexibel sich for-Schleifen verwenden lassen. # 8.11 Kontrollierte Sprünge ## 8.11 Kontrollierte Sprünge Es gibt vier Möglichkeiten, eine Ablaufstruktur (wie etwa Schleifen, Funktionen, Bedingungen oder gar das Programm) unmittelbar zu verlassen. Ãber sie kann aber nicht in eine bestimmte Anweisung verzweigt werden, sondern lediglich zur nächsten Ablaufstruktur. * continue – damit beenden Sie bei Schleifen nur den aktuellen Schleifendurchlauf. * break – beendet die Schleife oder eine Fallunterscheidung. Befindet sich break in mehreren geschachtelten Schleifen, wird nur die innerste verlassen. * exit – beendet das komplette Programm. * return – beendet die Iteration und die Funktion, in der return aufgerufen wird. Im Fall der main()-Funktion würde dies das Ende des Programms bedeuten. Es sei angemerkt, dass exit und return keine schleifentypischen Anweisungen sind – im Gegensatz zu break und continue. Auf continue und break gehe ich jetzt noch etwas genauer ein. ### 8.11.1 continue Die continue-Anweisung beendet nur die aktuelle Schleifenausführung. Das bedeutet, dass ab dem Aufruf von continue im Anweisungsblock der Schleife alle anderen Anweisungen übersprungen werden und die Programmausführung zur Schleife mit der nächsten Ausführung zurückspringt: > /* continue1.c */ #include <stdio.h> int main(void) { int i; for(i = 1; i <= 20; i++) { if(i % 2) /* Rest bedeutet ungerade Zahl. */ continue; /* printf überspringen */ printf("%d ", i); } printf("\n"); return 0; } Bei diesem Beispiel überprüfen Sie, ob es sich bei der Variable i um eine ungerade Zahl handelt. In diesem Fall wird die continue-Anweisung ausgeführt. Die printf-Anweisung wird dabei übersprungen, und es geht zum nächsten Schleifendurchlauf. Die Ausgabe des Programms bestätigt Ihnen, dass nur die geraden Zahlen durchkommen. So konnten Sie sich mit continue praktisch eine else-Anweisung sparen. Bitte achten Sie bei continue auf die folgenden eventuell ungünstigen Seiteneffekte: > /* continue2.c */ #include <stdio.h> int main(void) { int i=2; while(i <= 10) { if(i % 2) /* Rest bedeutet ungerade Zahl. */ continue; /* printf überspringen */ printf("%d ", i); i++; } return 0; } Dieses Programm hätte dasselbe ausführen sollen wie schon das Programmbeispiel zuvor – mit dem Unterschied, dass es sich hier um eine Endlosschleife handelt. Denn sobald > if(i % 2) wahr ist, also der Wert ungerade ist, springt das Programm wieder zum Schleifenanfang. Die Iteration (i++) wird danach nie mehr ausgeführt, da sich der Wert der Variable i nicht mehr ändern kann und somit immer ungerade bleibt. ### 8.11.2 break Bisher haben Sie die break-Anweisung nur bei der switch case-Verzweigung verwendet. Mit break können aber auch Schleifen vorzeitig beendet werden. Allerdings sollte dies nur ausnahmsweise erfolgen. Denn im Regelfall sollten Sie eine Schleife immer mit einer Bedingung beenden. # 8.12 Direkte Sprünge mit »goto« ## 8.12 Direkte Sprünge mit »goto« Ich habe mir lange überlegt, ob ich goto überhaupt in diesem Buch erwähnen soll, da die Verwendung von goto gemeinhin als sehr schlechter Stil angesehen wird und Sie diesen Befehl nach Möglichkeit nicht benutzen sollten. Da ich aber ein möglichst vollständiges Werk zur Sprache C vorlegen wollte, habe ich das goto-Thema als Ergänzung hinzugefügt. Der goto-Sprungbefehl gilt heute bei vielen Programmierern als verpönt. Die Geschichte von goto begann damit, dass es für die Programmiersprache C keine genauen Zeilennummern wie in anderen Programmiersprachen gab. Mit der goto-Label-Anweisung konnte man ein genaues Sprungziel festlegen. Es ist dabei egal, ob das Sprungziel vor oder nach dem goto-Statement im Programm aufgeführt ist. Die einzige Bedingung ist dabei, dass die Sprunganweisungen und Marken in derselben Funktion liegen müssen. Nützlich (dies sei vorsichtig betont) kann goto sein, um aus tief verschachtelten Schleifen herauszuspringen oder diese als Reaktion auf Programmfehler zu verlassen. Die Syntax für goto sieht folgendermaÃen aus: > goto LABEL; LABEL : Anweisung; Mit goto LABEL wird zur Marke LABEL gesprungen, und die dortigen Anweisungen werden ausgeführt. Ein Beispiel zu goto: > /* goto.c */ #include <stdio.h> int main(void) { int i,j,k; for(i=1; i<10; i++) { for(j=1; j<10; j++) { for(k=1; k<10; k++) { printf("Tiefe Verschachtelungsebene\n"); goto RAUS; } } } RAUS : printf("Mit einem Sprung raus hier \n"); return 0; } In diesem Beispiel wird, sobald Sie in der innersten Verschachtelung angekommen sind, mittels der goto-Sprunganweisung zum Label RAUS gesprungen, das sich am Ende des Programms befindet. Warum also ist goto so verpönt? Aus Performance-Gründen! Durch goto wird der normale Ablauf des Programms einfach unterbrochen. Ein weiterer Grund, goto nicht zu verwenden, ist folgender: Wenn mit goto in einen Anweisungsblock gesprungen wird, der lokale Variablen beinhaltet, ist das Verhalten systemabhängig. Es gibt wohl kaum ein Problem, das sich nicht auch ohne goto lösen lässt. Man kann sagen, dass ein goto mit einem Sprung nach vorne nichts ausmacht. Von einem goto, das aber zurückspringt, kann nur abgeraten werden. In solch einem Fall (wenn Sie also zurückspringen wollen) können Sie die do while-Schleife als bessere Alternative verwenden. Sprünge über Funktionsgrenzen hinweg sind mit goto ohnehin nicht möglich. Dafür gibt es die Funktionen setjmp und longjmp. # 8.13 Notationsstil ## 8.13 Notationsstil Ich möchte noch ein paar Sätze zur Notationsform von strukturierten Anweisungen verlieren. Als Beispiel soll die for-Schleife verwendet werden. Folgende Stile finden Sie häufiger vor: ### 8.13.1 K&R-Stil > for(i=0; i < 10; i++){ /* Anweisungen */ } ### 8.13.2 Whitesmith-Stil ### 8.13.3 Allman-Stil ### 8.13.4 GNU EMACS-Stil ### 8.13.5 Der Stil des Autors ;) (K&R-like) Welchen Notationsstil Sie letztendlich verwenden, ist wohl eine Frage des eigenen Geschmacks. Arbeiten Sie allerdings an einem gröÃeren Projekt mit mehreren Personen, so sollte der Stil vorher abgesprochen werden, um eine Vermischung zu vermeiden. # 9.2 Wozu dienen Funktionen? ## 9.2 Wozu dienen Funktionen? Funktionen haben eine Menge Vorteile. Einige der wichtigsten sind: * Mit Funktionen lässt sich der Quellcode besser lesen. * Der Code kann durch Erstellen einer Funktionsbibliothek wiederverwertet werden. * Ständig sich wiederholende Routinen können in eine Funktion gepackt werden und müssen nicht immer wieder neu geschrieben werden. * Fehler und Veränderungen lassen sich daher auch schneller finden bzw. ausbessern, da der Code nur an einer Stelle bearbeitet werden muss. Im Laufe dieses Kapitels gehe ich noch ein wenig genauer auf die Vorteile ein. # 9.3 Definition von Funktionen ## 9.3 Definition von Funktionen Die allgemeine Syntax für Funktionen sieht folgendermaÃen aus: > [Spezifizierer] Rückgabetyp Funktionsname(Parameter) { /* Anweisungsblock mit Anweisungen */ } Wenn Sie sich die Syntax ansehen, erkennen Sie darin vielleicht auch die Hauptfunktion main(): > int main(void) Eine Funktionsdefinition wird in folgende Bestandteile gegliedert: * Rückgabetyp – Hier legen Sie den Datentyp des Rückgabewerts fest. Dabei dürfen Sie alle Datentypen verwenden, die Sie bisher kennengelernt haben. Eine Funktion ohne Rückgabewert wird als void deklariert. Sollten Sie einmal keinen Rückgabetyp angeben, so wird automatisch eine Funktion mit Rückgabewert vom Datentyp int erzeugt. * Funktionsname – Dies ist ein eindeutiger Funktionsname, mit dem Sie die Funktion von einer anderen Stelle aus im Programmcode aufrufen können. Für den Funktionsnamen selbst gelten dieselben Regeln wie für Variablen. AuÃerdem sollten Sie auch keine Funktionsnamen der Laufzeitbibliothek verwenden, wie z. B. printf(). * Parameter – Die Parameter einer Funktion sind optional. Sie werden durch einen Datentyp und einen Namen spezifiziert und durch ein Komma getrennt. Wird kein Parameter verwendet, können Sie zwischen die Klammern entweder void schreiben oder gar nichts. * Anweisungsblock – Der Anweisungsblock behält dieselbe Funktion wie immer (in der main()-Funktion). In diesem werden also wie gehabt Deklarationen und Anweisungen ausgeführt. * Spezifizierer – AuÃerdem lassen sich bei Funktionen auch sogenannte Speicherklassen-Spezifizierer verwenden. Mehr hierzu finden Sie im entsprechenden Abschnitt. # 9.4 Funktionsaufruf ## 9.4 Funktionsaufruf Nach so viel Theorie wird es Zeit für die Praxis. Zunächst wird eine einfache Funktion erstellt, die nur einen Text auf dem Bildschirm ausgibt: > void hilfe(void) { printf("Ich bin die Hilfsfunktion\n"); } Die Funktion hat keinen Rückgabetyp und keine(n) Parameter. Aufgerufen wird sie zum Beispiel mit > hilfe(); innerhalb der main()-Funktion. Sehen Sie sich den Quellcode dazu an: > /* func1.c */ #include <stdio.h> void hilfe(void) { printf("Ich bin die Hilfsfunktion\n"); } int main(void) { hilfe(); return 0; } Durch den Aufruf von hilfe() in der main()-Funktion wird die Funktion hilfe ausgeführt und gibt einen Text auf dem Bildschirm aus. Eine Grafik soll dies veranschaulichen: Abbildung 9.1 Der Ablauf bei einem Funktionsaufruf Sie können es sich etwa so vorstellen: Durch den Funktionsaufruf wird zuerst zur ersten Anweisung der Funktion gesprungen. Nach der letzten Anweisung in der Funktion können Sie sich einen Rücksprungbefehl hinzudenken. Mit diesem Rücksprungbefehl wird zur nächsten Anweisung nach dem Funktionsaufruf zurückgesprungen. # 9.5 Funktionsdeklaration ## 9.5 Funktionsdeklaration Damit der Compiler überhaupt von einer Funktion Kenntnis nimmt, muss diese vor ihrem Aufruf deklariert werden. Im vorangegangenen Beispiel ist das automatisch geschehen. Zuerst wurde die Funktion hilfe() und anschlieÃend die main()-Funktion definiert. Sie können aber auch Funktionen schreiben, die hinter der main()-Funktion stehen: > /* func2.c */ #include <stdio.h> void hilfe(void); int main(void) { hilfe(); return 0; } void hilfe(void) { printf("Ich bin die Hilfsfunktion\n"); } Da hier die Funktion hilfe() erst hinter der main()-Funktion geschrieben wurde, müssen Sie den Compiler zur Ãbersetzungszeit mit dieser Funktion bekannt machen. Sonst kann der Compiler in der main()-Funktion mit hilfe() nichts anfangen. Dies stellen Sie mit einer sogenannten Vorwärtsdeklaration sicher: > void hilfe(void); Die Deklaration wird im Gegensatz zur Funktionsdefinition mit einem Semikolon abgeschlossen. Funktionsdeklarationen sollten aber nicht nur dann vorgenommen werden, wenn die Funktionen hinter die main()-Funktion geschrieben werden. Es ist ja auch möglich, dass eine Funktion andere Funktionen aufruft. Funktionen können Sie auch als unterschiedliche Formen der main()-Funktion betrachten. Sehen Sie sich im Beispiel an, was gemeint ist: > /* func3.c */ #include <stdio.h> void func1(void); void func2(void); void func3(void); void func1(void) { printf("Ich bin func1 \n"); func3(); } void func2(void) { printf("Ich bin func2 \n"); } void func3(void) { printf("Ich bin func3 \n"); func2(); } int main(void) { func1(); return 0; } Hätten Sie hier keine Vorwärtsdeklaration mit > void func1(void); void func2(void); void func3(void); vorgenommen, hätte der Compiler beim Ãbersetzen (Kompilieren) Probleme mit der Funktion func1() gehabt. Denn in func1() steht der Funktionsaufruf func3(). Dem Compiler ist bis dahin eine solche Funktion noch unbekannt, da diese erst weiter unten im Quellcode implementiert wird. Ein weiterer Grund für die Erstellung einer Vorwärtsdeklaration ist der Austausch von Funktionen über die Dateigrenzen hinweg. Aber dazu später mehr in Abschnitt 9.19, »Getrenntes Kompilieren von Quelldateien«. # 9.6 Lokale Variablen ## 9.6 Lokale Variablen Die lokalste Variable ist immer die Variable im Anweisungsblock. Sehen Sie sich kurz ein Beispiel an: > /* lokal_var1.c */ #include <stdio.h> int main(void) { int i = 333; if(i == 333) { int i = 111; printf("%d\n",i); /* 111 */ } printf("%d\n",i); /* 333 */ return 0; } Zunächst übergeben Sie am Anfang des Programms der Variablen i den Wert 333. In der if-Bedingung wird der Wert auf 333 überprüft. AnschlieÃend wird erneut eine Variable i erstellt, der Sie jetzt den Wert 111 übergeben. Die Ausgabe im Anweisungsblock von if ist somit 111. Die Ausgabe auÃerhalb des Anweisungsblocks if ist aber wieder 333. Aber ganz so einfach will ich es Ihnen nicht machen. Schreiben Sie das Programm nochmal neu: > /* lokal_var2.c */ #include <stdio.h> int main(void) { int i = 333; if(i == 333) { i = 111; printf("%d\n",i); /* 111 */ } printf("%d\n",i); /* 111 */ return 0; } Sie haben hier im Gegensatz zum vorherigen Beispiel den Wert der Variablen i im if-Anweisungsblock auf 111 gesetzt, aber keine neue lokale Variable i definiert. Hier folgt nochmals ein Beispiel, das aber keine Schule machen sollte: > /* lokal_var3.c */ #include <stdio.h> int main(void) { int i=333; if(i == 333) { int i = 666; { i = 111; printf("%d\n",i); /* 111 */ } printf("%d\n",i); /* 111 */ } printf("%d\n",i); /* 333 */ return 0; } Lokale Variablen, die in einem Anweisungsblock definiert wurden, sind auÃerhalb dieses Anweisungsblocks nicht gültig. Funktionen sind im Prinzip nichts anderes als Anweisungsblöcke. Sehen Sie sich folgendes Beispiel an: > /* func4.c */ #include <stdio.h> void aendern(void) { int i = 111; printf("In der Funktion aendern: %d\n",i); } int main(void) { int i=333; printf("%d\n",i); aendern(); printf("%d\n",i); return 0; } Hier gilt dasselbe wie schon im vorherigen Beispiel. Die neu definierte Variable i in der Funktion aendern() hat keinen Einfluss auf die gleichnamige Variable i in der main()-Funktion. Bringen Sie zum Beispiel die Funktion in die folgende Form: > void aendern(void) { i = 111; printf("In der Funktion aendern: %d\n",i); } In diesem Fall würde sich das Programm nicht übersetzen lassen, da die Variable i noch nicht deklariert wurde. In einer Funktion müssen Sie eine Variable vor ihrer Verwendung zuerst deklarieren. Aber es gibt eine Möglichkeit, dem Compiler mitzuteilen, dass eine Variable für alle Funktionen gültig ist. # 9.7 Globale Variablen ## 9.7 Globale Variablen Globale Variablen können Sie sich als Vorwärtsdeklarationen von Funktionen vorstellen. Und wie der Name schon sagt, sind globale Variablen für alle Funktionen gültig. Hier ein Beispiel: > /* func5.c */ #include <stdio.h> int i=333; /* globale Variable */ void aendern(void) { i = 111; printf("In der Funktion aendern: %d\n",i); /* 111 */ } int main(void) { printf("%d\n",i); /* 333 */ aendern(); printf("%d\n",i); /* 111 */ return 0; } Natürlich gilt auch hier die Regel, dass bei gleichnamigen Variablen die lokalste Variable den Zuschlag erhält. Beispiel: > /* func6.c */ #include <stdio.h> int i=333; /* globale Variable i */ void aendern(void) { i = 111; /* Ãndert die globale Variable. */ printf("In der Funktion aendern: %d\n",i); /* 111 */ } int main(void) { int i = 444; printf("%d\n",i); /* 444 */ aendern(); printf("%d\n",i); /* 444 */ return 0; } In diesem Beispiel nimmt die main()-Funktion wieder keine Notiz von der globalen Variablen i, da eine lokalere Variable mit demselben Namen vorhanden ist. Dabei können auch unangenehme Fehler auftreten, wenn Sie bei längeren Programmen zwei Variablen – eine globale und ein lokale – mit demselben Namen haben. Deshalb sollten Sie sich folgenden Satz zu Herzen nehmen: # 9.8 Statische Variablen ## 9.8 Statische Variablen Bevor ich Ihnen die statischen Variablen erkläre, sollten Sie sich zunächst folgendes Programmbeispiel ansehen: > /* func7.c */ #include <stdio.h> void inkrement(void) { int i = 1; printf("Wert von i: %d\n",i); i++; } int main(void) { inkrement(); inkrement(); inkrement(); return 0; } Wenn Sie das Programm ausführen, wird dreimal ausgegeben, dass der »Wert von i: 1« ist. Allerdings muss man doch hier davon ausgehen, dass der Programmierer andere Absichten hatte, da er doch den Wert der Variable i am Ende der Funktion inkrementiert. Dass dies nicht funktioniert, hat mit der Speicherverwaltung des Stacks zu tun. Mehr zu diesem Thema finden Sie in Abschnitt 9.20.1, »Exkurs: Stack«. Jetzt können Sie bei diesem Programm vor die Variable das Schlüsselwort static schreiben. Ãndern Sie also diese Funktion: > void inkrement(void) { static int i = 1; printf("Wert von i : %d\n",i); i++; } Damit werden für die Variable i tatsächlich die Werte 1, 2 und 3 ausgegeben. Dies haben Sie dem Schlüsselwort static zu verdanken. Denn statische Variablen verlieren bei Beendigung ihres Bezugsrahmens (also bei Beendigung der Funktion) nicht ihren Wert, sondern behalten diesen bei. Dass dies gelingt, liegt daran, dass statische Variablen nicht im Stacksegment der CPU, sondern im Datensegment gespeichert werden. Aber Achtung: Statische Variablen müssen schon bei ihrer Deklaration initialisiert werden! # 9.9 Schlüsselwörter für Variablen – Speicherklassen ## 9.9 Schlüsselwörter für Variablen – Speicherklassen Es gibt noch weitere Schlüsselwörter in C für Variablen auÃer static, sogenannte Speicherklassen, die hier in Kurzform erwähnt werden sollen. Das Thema Speicherklassen gehört eigentlich in das Kapitel über Variablen, hätte einen Anfänger zu Beginn aber nur verwirrt. Mit den Speicherklassen legen Sie den Geltungsbereich in der Datei, die Lebensdauer und die Bindung einer Variablen fest. Für Variablen gibt es zwei Möglichkeiten der Lebensdauer: * Die statische Lebensdauer – die Variable wird zu Programmbeginn einmal deklariert sowie initialisiert und existiert während der gesamten Programmausführung. * Die automatische Lebensdauer – die Variable wird beim Eintritt in den Anweisungsblock, in dem sie definiert ist, neu erzeugt und beim Verlassen des Anweisungsblocks wieder gelöscht. Jetzt folgt ein Ãberblick über die zusätzlichen Speicherklassen-Spezifizierer (einschlieÃlich static). ### 9.9.1 auto Der Name kommt daher, dass durch das Voranstellen des Schlüsselworts auto die Variable automatisch angelegt und auch automatisch wieder gelöscht wird, ohne dass sich der Programmierer darum kümmern muss. Der Bezugsrahmen von auto ist derselbe wie bei lokalen Variablen. So ist zum Beispiel > int zahl = 5; dasselbe wie: > auto int zahl = 5; Folglich ist das Schlüsselwort auto überflüssig. ### 9.9.2 extern Befindet sich die Variable in einer anderen Datei, wird das Schlüsselwort extern davor gesetzt. Diese Speicherklasse wird für Variablen verwendet, die im gesamten Programm verwendet werden können. ### 9.9.3 register Das Schlüsselwort register wird heute eigentlich überhaupt nicht mehr benutzt. Der Bezugsrahmen ist derselbe wie bei auto und lokalen Variablen. Durch Voransetzen des Schlüsselworts register weisen Sie den Compiler an, eine Variable so lange wie möglich im Prozessorregister (CPU-Register) zu halten, um dann blitzschnell darauf zugreifen zu können. Denn Prozessorregister arbeiten wesentlich schneller als Arbeitsspeicher. Allgemein wird vom Gebrauch von register abgeraten, denn ob und welche Variable der Compiler in dem schnellen Prozessorregister hält, entscheidet er letztlich selbst. Somit ist das Schlüsselwort eigentlich nicht erforderlich. ### 9.9.4 static Das Schlüsselwort static wird vor immer währenden Variablen mit einem beschränkten Geltungsbereich gesetzt. # 9.10 Typ-Qualifizierer ## 9.10 Typ-Qualifizierer AuÃer der Speicherklasse, die Sie für eine Variable festlegen können, können Sie auch den Typ eines Objekts näher spezifizieren. ### 9.10.1 volatile Mit dem Schlüsselwort volatile modifizieren Sie eine Variable so, dass der Wert dieser Variablen vor jedem Zugriff neu aus dem Hauptspeicher eingelesen werden muss. Meistens wird volatile bei der Treiberprogrammierung eingesetzt. Hier sehen Sie ein Beispiel, bei dem ein Programm diejenigen Ergebnisse in einer Schleife überprüft, die ins Register der CPU abgelegt wurden: > do { printf("Gerät X wird überprüft ...\n"); } while(reg & (STATUS_A|STATUS_B) == 0); printf("Gerät X Status ... [OK]\n"); Manche Compiler erkennen jetzt an der while-Schleife, dass hier immer die gleiche Adresse überprüft wird, und optimieren die do while-Schleife einfach weg. Dieser Vorgang wird dann nur einmal durchgeführt, da die Schleife weg ist. Wird dabei die Hardware nicht erkannt, entsteht ein Problem. Somit gilt für Variablen, die mit volatile deklariert sind, dass diese ohne jede Optimierung neu aus dem Hauptspeicher geladen werden und neue Werte auch sofort wieder dort abgelegt werden. ### 9.10.2 const Mit dem Typ-Qualifizierer const definieren Sie eine Konstante. Dies ist eine Variable, deren Wert im Laufe der Programmausführung nicht mehr geändert werden darf. > const int wert = 10; wert += 5; /* Fehler */ # 9.11 Geltungsbereich von Variablen ## 9.11 Geltungsbereich von Variablen Die Lebensdauer und der Geltungsbereich von Variablen hängen somit von zwei Punkten ab: * von der Position der Deklaration einer Variablen * vom Speicherklassen-Spezifizierer, der vor einer Variablen steht Je nachdem, an welcher Stelle eine Variable in einer Quelldatei deklariert wurde, gibt es folgende Geltungsbereiche: Abbildung 9.2 Geltungsbereiche von Variablen * Block (block scope): Wird eine Variable in einem Anweisungsblock ({}) deklariert, reichen der Geltungsbereich und die Lebensdauer dieser Variablen vom Anfang des Anweisungsblocks bis zu seinem Ende. * Funktion (local scope): Wird eine Variable in einer Funktion deklariert, reichen der Geltungsbereich und die Lebensdauer vom Anfang des Funktionsblocks bis zu seinem Ende. Es sei denn, in der Funktion wird eine Variable innerhalb eines Blocks deklariert. Dann gilt diese Variable nur noch in diesem Block. * Datei (file scope): Wird eine Variable auÃerhalb von Funktionen und Anweisungsblöcken deklariert, reichen Geltungsbereich und Lebensdauer vom Punkt der Deklaration bis zum Dateiende. Wie Sie im Abschnitt über lokale Variablen erfahren haben, gilt auÃerdem, dass die äuÃere Deklaration nicht mehr sichtbar ist, wenn eine Variable mit demselben Namen in einem inneren Block deklariert wird. Beim Verlassen des inneren Blocks ist die äuÃere Variable wieder sichtbar, und die innere Variable gibt es nicht mehr. Der Geltungsbereich und die Lebensdauer von Variablen können noch auf eine andere Weise verändert werden, nämlich mithilfe des Speicherklassen-Spezifizierers (siehe Tabelle 9.1). Position | Speicherklasse | Lebensdauer | Geltungsbereich | | --- | --- | --- | --- | | | | | | | | | | | | | # 9.12 Speicherklassen-Spezifizierer für Funktionen ## 9.12 Speicherklassen-Spezifizierer für Funktionen Natürlich sind die zusätzlichen Speicherklassen bei Funktionen im Vergleich zu Variablen nur beschränkt einsetzbar, da Funktionen ja nur global definiert werden können. Im Folgenden stelle ich die Speicherklassen vor, die Sie den Funktionen voranstellen können, und erkläre ihre Bedeutung. ### 9.12.1 extern Wenn Sie bei der Deklaration einer Funktion die Speicherklasse nicht angeben, ist diese automatisch mit extern gesetzt. Solche Funktionen können sich auch in einer anderen Quelldatei befinden. Dann speziell empfiehlt es sich, dieses Schlüsselwort zu verwenden (auch wenn dies nicht nötig wäre). Dieser Hinweis kann hilfreich für den Programmierer sein, weil er sofort weiÃ, worum es sich handelt. extern zu setzen dient also nicht der Verbesserung bzw. Optimierung des Quellcodes, sondern ist ein Hinweis für dessen Leser. ### 9.12.2 static Wenn Sie einer Funktion das Schlüsselwort static zuweisen, können Sie diese Funktion nur innerhalb der Datei nutzen, in der sie definiert wurde. Es ist somit das Gegenteil des Schlüsselworts extern. ### 9.12.3 volatile volatile ist zwar keine Speicherklasse, sollte aber hier trotzdem erwähnt werden. Mit volatile verhindern Sie (analog zu Variablen), dass der Compiler den Quellcode optimiert und die Funktion immer wieder neu aus dem Hauptspeicher gelesen werden muss. Nach diesen etwas theoretischen, aber wichtigen Themen geht es wieder zurück zum eigentlichen Thema des Kapitels: den Funktionen. # 9.13 Datenaustausch zwischen Funktionen ## 9.13 Datenaustausch zwischen Funktionen Für den Austausch von Daten kennen Sie bisher nur die Möglichkeit, globale Variablen zu verwenden. Eine globale Variable ist jeweils eine gemeinsame Variable für alle Funktionen: > /* func8.c */ #include <stdio.h> static int zahl; void verdoppeln(void); void halbieren(void); void verdoppeln(void) { zahl *= 2; printf("Verdoppelt: %d\n", zahl); } void halbieren(void) { zahl /= 2; printf("Halbiert: %d\n", zahl); } int main(void) { int wahl; printf("Bitte geben Sie eine Zahl ein: "); scanf("%d",&zahl); printf("Wollen Sie diese Zahl\n"); printf("\t1.)verdoppeln\n\t2.)halbieren\n\nIhre Wahl: "); scanf("%d",&wahl); switch(wahl) { case 1 : verdoppeln(); break; case 2 : halbieren(); break; default : printf("Unbekannte Eingabe\n"); } return 0; } Dieses Programm weist keinerlei Fehler auf. Nur wirkt es etwas störend, dass eine globale Variable für alle Funktionen verwendet wurde. Zum einen wissen Sie, dass es besser wäre, die Variable lokal zu halten. Zum anderen kann das Programm auf diese Art schnell unübersichtlich werden. Als Beispiel dient hier ein Programm, das sich über mehrere Dateien verteilt, bei dem Sie auf folgende Funktion stoÃen: > void berechnung(void) { V = l * b * h / 4; x = V * V; } Es erscheint alles eindeutig, nicht wahr? Natürlich ist es das nicht, denn es lässt sich anhand dieser Berechnung überhaupt nicht erkennen, um welchen Datentyp es sich handelt. Um also den Datentyp zu ermitteln, müssen Sie nach seiner Deklaration suchen. Einfach ausgedrückt heiÃt das, dass Sie eine Funktion so programmieren müssen, dass diese auch für eine allgemeine Verwendung ausgelegt ist. Dafür gibt es in der Regel zwei Möglichkeiten, die Sie am besten auch beide nutzen. * Funktionen mit Wertübergabe (Parameter) * Funktionen mit Wertrückgabe Mit der Wertübergabe durch Parameter übergeben Sie einer Funktion Daten (Datenfluss in die Funktion hinein), und mit der Wertrückgabe geben Sie Daten aus einer Funktion heraus (Datenfluss aus der Funktion heraus). Die Funktion arbeitet somit als eine Art Schnittstelle. # 9.14 Wertübergabe an Funktionen (call-by-value) ## 9.14 Wertübergabe an Funktionen (call-by-value) Hier folgt ein Beispiel, das zeigt, wie Sie einer Funktion Daten übergeben können: > /* func9.c */ #include <stdio.h> void verdoppeln(int); void halbieren(int); void halbieren(int zahl) { zahl /= 2; printf("Halbiert : %d\n", zahl); } void verdoppeln(int zahl) { zahl *= 2; printf("Verdoppelt : %d\n", zahl); } int main(void) { int wahl, z; printf("Bitte geben Sie eine Zahl ein : "); scanf("%d",&z); printf("Wollen Sie diese Zahl\n"); printf("\t1.)verdoppeln\n\t2.)halbieren\n\nIhre Wahl : "); scanf("%d",&wahl); switch(wahl) { case 1 : verdoppeln(z); break; case 2 : halbieren(z); break; default : printf("Unbekannte Eingabe\n"); } return 0; } An der Deklaration der Funktion können Sie schon erkennen, dass die Funktion einen Parameter vom Datentyp int verwendet. AuÃerdem fällt auf, dass die globale Variable verschwunden ist und in der main()-Funktion wieder auftaucht. Werfen Sie einmal einen Blick auf eine Funktion: > void halbieren(int zahl) { zahl /= 2; printf("Halbiert : %d\n",zahl); } Es handelt sich also um eine Funktion, die als Parameter einen int-Wert übernimmt. Das bedeutet, dass Sie die Funktion halbieren() nur mit einem Argument vom Typ int aufrufen können. Andernfalls meldet der Compiler einen Fehler. Aufgerufen wird diese Funktion (von einer anderen Funktion aus) mit einem Argument, auch formaler Parameter genannt. Im gezeigten Beispiel sieht der Funktionsaufruf mit Argument folgendermaÃen aus: > halbieren(zahl); Dann wird für die aufrufende Funktion ein Stack-Rahmen (dynamischer Speicherbereich) angelegt. In diesem Speicherbereich wird Speicher für diejenigen Parameter reserviert, die die Funktion beinhaltet. Der Parameter, den Sie der Funktion durch das Argument übergeben haben, wird auch initialisiert. Damit steht der Funktion das Argument z auch mit dem gleichen Wert für die Funktion halbieren() (nur mit dem Namen zahl) als Kopie zur Verfügung. Die Funktion kann nun mit den Parametern ganz normal arbeiten. Der Parameter einer Funktion ist bei einer sogenannten Call-by-value-Ãbergabe eine Kopie des Werts, mit dessen Argument Sie die Funktion aufgerufen haben. Fassen wir die vier Schritte zusammen, wie der Datenfluss bei der Ãbergabe von Argumenten abläuft: 1. | Bei der Funktionsdefinition wird die Parameterliste festgelegt (formale Parameterliste). | | --- | --- | 2. | Die Funktion wird von einer anderen Funktion mit dem Argument aufgerufen (sie muss mit dem Typ des formalen Parameters übereinstimmen). | | --- | --- | 3. | Für die Funktion wird ein dynamischer Speicherbereich (im Stack) angelegt. | | --- | --- | 4. | Jetzt kann die Funktion mit den Parametern arbeiten. | | --- | --- | Neben call-by-value existiert auch call-by-reference, womit statt einem Wert eine Adresse kopiert wird. Diese Art des Aufrufs wird im Zusammenhang mit Zeigern näher besprochen (Kapitel 12). Natürlich können Sie auch mehrere Parameter in einer Funktion verwenden. Als Anwendungsbeispiel soll im Folgenden der gregorianische Kalender in den julianischen umgerechnet werden. Dieses Verfahren wird vorwiegend in der Astronomie und Raumfahrt genutzt. Der julianische Kalender beginnt mit der ägyptischen Berechnung seit dem 1.1.4713 vor Christus. Mit dem julianischen Datum lassen sich sehr gut Sonnen- bzw. Mondfinsternisse berechnen: > /* greg2jul.c */ #include <stdio.h> /* Umrechnung vom gregorianischen zum julianischen Datum */ void greg2jul(int tag, int monat, int jahr) { int k, l, jd; k = (monat - 14) / 12; l = jahr + k + 4800; jd = tag - 32075 + 1461 *l / 4 + 367 * ((monat-2-12*k) / 12) - 3 * ((l+100) / 100) / 4; printf(" sind %d Tage vergangen\n",jd); } int main(void) { int tag,monat,jahr; printf("Eingabe (Tag) : "); scanf("%d",&tag); printf("Eingabe (Monat): "); scanf("%d",&monat); printf("Eingabe (Jahr) : "); scanf("%d",&jahr); printf("Seit dem 1.1.4713 v.Chr. bis %2d.%2d.%4d", tag,monat,jahr); greg2jul(tag, monat, jahr); return 0; } Wichtig ist dabei, dass Sie darauf achten, die Argumente beim Funktionsaufruf in der richtigen Reihenfolge anzugeben. Vertauschte Werte führen zu falschen Berechnungen. Die Parameter könnten auch von unterschiedlichen Datentypen sein, was der Compiler im Fall der Vertauschung in den meisten Fällen aber moniert: > /* func10.c */ #include <stdio.h> void mixed(int x, char y, float z) { printf("Stückzahl : %d ",x); printf("Klasse : %c ",y); printf("Preis : %.2f Euro\n",z); } int main(void) { mixed(6, 'A', 5.5f); mixed(9, 'B', 4.3f); return 0; } # 9.15 Der Rückgabewert von Funktionen ## 9.15 Der Rückgabewert von Funktionen Jetzt haben Sie gesehen, wie es möglich ist, Daten an eine Funktion zu übergeben. Nun wollen Sie natürlich noch wissen, wie eine Funktion so geschrieben wird, dass sie Daten an den Aufrufer zurückgibt. Zunächst benötigen Sie eine Funktionsdefinition mit einem Rückgabewert. Als Rückgabewert können Sie jeden beliebigen Datentyp verwenden, zum Beispiel: > int bignum(int a, int b) { if(a > b) return a; else if(a < b) return b; else return 0; /* Beide Zahlen gleich groÃ. */ } Sie erkennen an dieser Funktion durch das Voranstellen des Datentyps, dass hier der Rückgabewert ein Integer ist. Und in der Funktion selbst wird mit der Anweisung > return WERT; ein Wert an die aufrufende Funktion zurückgeliefert. Diese return-Anweisung dient aber nicht nur dazu, der aufrufenden Funktion einen Wert zurückzuliefern, sondern setzt zugleich das Ende einer Funktion fest. Bei return wird also die Kontrolle an die aufrufende Funktion zurückgegeben. Dabei kann ein Wert zurückgegeben werden. Jetzt wird noch der Aufrufer selbst mit seinen Argumenten benötigt: > int big; ... big = bignum(wert1, wert2); Damit wird der Variablen big, die zwingend vom Datentyp int sein muss, der Rückgabewert der Funktion bignum() zugewiesen. Das vollständige Programm sähe dann folgendermaÃen aus: > /* bignum.c */ #include <stdio.h> int bignum(int a, int b) { if(a > b) return a; else if(a < b) return b; else return 0; /* Beide Zahlen sind gleich groÃ. */ } int main(void) { int wert1, wert2, big; printf("Bitte einen Wert eingeben: "); scanf("%d",&wert1); printf("Bitte noch einen Wert eingeben: "); scanf("%d",&wert2); big = bignum(wert1, wert2); if(big != 0) printf("%d ist die gröÃere der beiden Zahlen\n",big); else printf("Beide Zahlen haben denselben Wert\n"); return 0; } Im weiteren Verlauf werden Sie einige Möglichkeiten von Funktionen mit verschiedensten Rückgabewerten kennenlernen. # 9.16 Die Hauptfunktion »main()« ## 9.16 Die Hauptfunktion »main()« Gemäà dem ANSI-C-Standard muss mindestens eine Funktion in einem Programm den Namen main() besitzen. Diese Funktion ist auch die erste, die beim Programmstart ausgeführt wird. Geben Sie der main()-Funktion einen anderen Rückgabewert als int, könnte ein C99-Standard-konformer Compiler ein undefiniertes Verhalten zeigen. In einigen (vorwiegend älteren) Büchern finden Sie die main()-Funktion mitunter in folgender Schreibweise: > void main(void) { } Nach einem älteren C-Standard ist dies auch richtig. Läuft ein Compiler aber nach dem neuesten C99-Standard, wird eine Warnung ausgegeben werden, dass die main()-Funktion einen Rückgabewert erwartet. Die main()-Funktion lautet (nach dem C99-Standard) richtig: > int main(void) { return 0; // Muss nicht verwendet werden. } Weiterhin ist auch eine Variante mit zwei Parametern erlaubt: > int main(int argc, char *argv[]) { return 0; // Muss nicht verwendet werden. } Näheres zu dieser Schreibweise erfahren Sie später in Kapitel 13, »Kommandozeilenargumente«. Der Rückgabewert, der der main()-Funktion zugewiesen wird, dient dazu, dass der Startup-Code dem Betriebssystem und der Umgebung mitteilt, ob das Programm ordnungsgemäà beendet wurde oder nicht (abhängig vom Rückgabewert). In folgenden Fällen liegt ein undefiniertes Verhalten beim Beenden der main()-Funktion vor: * kein Rückgabewert bei Verwendung von void main() * Verwendung von _exit() im Programm Wichtig ist in diesem Zusammenhang die Bedeutung des Begriffs »Startup-Code«. Der Startup-Code wird zu Beginn des Prozesses erzeugt (meist in Assembler) und dient zum Beenden eines Prozesses. Beim Beenden der main()-Funktion wird wieder zum Startup-Code zurückgesprungen. Er ruft dann die exit()-Funktion auf. Die exit()-Funktion führt dann noch einige Aufräumarbeiten aus (z. B. Freigabe des Speicherplatzes von benutzten Variablen des Programms). Zuletzt wird der Prozess mit der Funktion _exit() endgültig beendet. Abbildung 9.3 zeigt den Programmablauf bei Beendigung des Programms. Abbildung 9.3 Vom Start bis zum Ende eines Programms # 9.17 Rückgabewert beim Beenden eines Programms ## 9.17 Rückgabewert beim Beenden eines Programms Ãber dieses Thema wurden bereits ganze Threads in diversen Foren gefüllt. Generell ist der Rückgabewert beim Beenden eines Programms abhängig von der Umgebung des Betriebssystems. Unter Linux/UNIX beispielsweise bedeutet ein Rückgabewert von 0, dass ein Programm erfolgreich beendet wurde; alles andere bedeutet eben, dass irgendetwas schiefgelaufen ist. Andere Betriebssysteme wiederum können allerdings auch einen anderen Rückgabewert als erfolgreiche Beendigung erwarten – was bedeutet, dass es hierbei keinen portablen Standard gibt. Dennoch gibt es mit den Makros EXIT_SUCCESS und EXIT_FAILURE einen recht zuverlässigen Weg, um ein Programm zu beenden. Beide Makros sind in der Headerdatei <stdlib.h> definiert und schon seit dem C89-Standard vorhanden. Damit müssen Sie sich nicht mehr darum kümmern, welchen Wert auf welchem System Sie denn nun zurückgeben müssen, um zu melden, ob sich eine Anwendung erfolgreich oder eben nicht erfolgreich beendet hat. Bei einem erfolgreichen Ende geben Sie einfach EXIT_SUCCESS zurück und bei einem Fehler EXIT_FAILURE. Natürlich müssen Sie auch die Headerdatei <stdlib.h> mit einbinden. Hierzu ein Beispiel, wie Sie diese beiden Makros sinnvoll einsetzen können: > /* exit_code.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int val, ret; printf("Bitte Eingabe machen : "); ret = scanf("%d", &val); if(ret != 1) { printf("Fehler bei scanf()-Eingabe\n"); return EXIT_FAILURE; } if(val < 0) { printf("Fehler - Negative Zahl\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } ### 9.17.1 Programmende auswerten Jeder will Ihnen sagen, dass ein Programm bei erfolgreicher Beendigung 0 und bei einem Fehler etwas ungleich 0 zurückgeben soll. Aber wie man dies anschlieÃend auswerten kann, erfährt man eigentlich selten. Ich will Ihnen hier jeweils einen Weg für MS-Windows und einen für Linux/Unix zeigen, wie Sie das Programmende auswerten können. Als Beispiel dient das Listing exit_code.c aus dem vorherigen Abschnitt. # MS-Windows/MS-DOS Unter MS-Windows/MS-DOS kommt man hier mit der Batch-Programmierung recht weit. Eine Batch-Datei hat die Endung *.bat und ist in Windows und MS-DOS standardmäÃig integriert. Zum Erstellen von Batch-Dateien ist ein gewöhnlicher ASCII-Editor (wie beispielsweise Notepad) ausreichend. Die Befehle einer solchen Datei werden zeilenweise abgearbeitet. Viele DOS-Progamme liefern beim Beenden einen sogenannten Errorlevel. Dieser kann die Werte 0 bis 255 annehmen. Auch hier bedeutet gewöhnlich ein Errorlevel ungleich 0, dass ein Fehler aufgetreten ist. In unserem Fall bedeutet dies: Gibt unser Programm 0 zurück, ist der Errorlevel auch 0. Geben wir aus unserem Programm 1 zurück, dann ist der Errorlevel ebenfalls 1 usw. Einen solchen Errorlevel können Sie mit einer üblichen if-Bedingung im Batch-Skript abfragen, zum Beispiel so: > if errorlevel 1 goto eins Ist hier beispielsweise der Rückgabewert des Programms 1, dann wird zum Label eins gesprungen. Ein solches Label wird folgendermaÃen angegeben: > :eins Hinter diesem Label können Sie jetzt entsprechend auf den Errorlevel reagieren. Hierzu zeige ich Ihnen nun ein Batch-Skript, welches den Rückgabewert von unserem Programm exit_code.exe auswertet (Kommentare werden mit den Zeichen :: eingeleitet): > :: Programmname: check.bat :: keine Anzeige der Eingabe (auch nicht von echo) @echo off :: Programm starten exit_code.exe :: Errorlevel auswerten if errorlevel 1 goto eins if errorlevel 0 goto null :: Errorlevel 1 :eins echo Fehler: Ende-Status ist 1 goto ende :null echo Alles Ok: Ende-Status ist 0 goto ende :ende PAUSE Durch die Verwendung von PAUSE am Ende können Sie die Batch-Datei check.bat auch per Mausklick starten, vorausgesetzt, das Programm exit_code.exe und das Batch-Skript befinden sich im selben Verzeichnis. Hier sehen Sie das Batch-Skript (per Mausklick) bei der Ausführung: > Bitte Eingabe machen : x Fehler bei scanf()-Eingabe Fehler: Ende-Status ist 1 Drücken Sie eine beliebige Taste . . . Bitte Eingabe machen : 5 Alles Ok: Ende-Status ist 0 Drücken Sie eine beliebige Taste . . . # Linux/Unix Bei Linux/Unix gibt es für die Beendigung eines Shellskripts oder Programms, das zuletzt ausgeführt wurde, die automatische Shellvariable $?. Die Bedeutung dieser Variable ist im Grunde dieselbe, wie eben schon bei Errorlevel unter Windows/MS-DOS erwähnt wurde. Selbst die Erstellung des Shellskripts dafür gestaltet sich recht ähnlich – nur dass die Shell von Linux/Unix schon um einiges mächtiger ist. Das Shellskript sieht wie folgt aus: > # Rückgabewert Ãberprüfen # Name: check.sh # Programm starten ./exit_code # Rückgabewert in ret ret=$? # Rückgabewert: 0 if [ ret -eq 0 ] then echo "Alles Ok: Rückgabewert war 0" fi # Rückgabewert: 1 if [ ret -eq 1 ] then echo "Fehler: Rückgabewert war 1" fi Dieses Shellskript muss nur noch ausführbar gemacht werden. Das Programm sieht bei der Ausführung so aus (hier wird auch davon ausgegangen, dass sich das Shellskript check.sh im selben Verzeichnis wie das auszuführende Programm befindet): > $ chmod u+x check.sh $ ./check.sh Bitte Eingabe machen : x Fehler bei scanf()-Eingabe Fehler: Rückgabewert war 1 $ ./check.sh Bitte Eingabe machen : 5 Alles Ok: Rückgabewert war 0 # 9.18 Funktionen der Laufzeitbibliothek ## 9.18 Funktionen der Laufzeitbibliothek Funktionen wie printf() oder scanf() sind solche Funktionen, wie Sie sie in den Kapiteln zuvor schon gesehen und verwendet haben. Dies sind zum Beispiel Funktionen der Laufzeitbibliothek <stdio.h>, die jedem Compiler beigefügt sind. Diese Funktionen werden bereits als Objektcode mit Ihrem Compiler mitgeliefert. Sie müssen dem Compiler jedoch trotzdem bekannt gemacht werden, und zwar mit den Headerdateien der Funktionen: > #include <stdio.hNatürlich gibt es auÃer den Funktionen printf() und scanf() noch eine Menge mehr Funktionen in der Headerdatei <stdio.h>. Alle können in einem Programm verwendet werden, sobald die entsprechende Headerdatei inkludiert wurde. Es ist gängige Praxis, nachzusehen, welche nützlichen Funktionen einer Headerdatei in einem Programm verwendet werden können, bevor Funktionen selbst neu programmiert werden. Sehen Sie sich die <stdio.h> ruhig einmal näher mit einem Editor an. Sie ist unter Linux/UNIX für gewöhnlich im Verzeichnis /usr/include und unter Windows oft im Verzeichnis C:\Pfad_zum_Compiler\include zu finden. Auch gibt es bei ANSI–C-Compilern noch eine Menge mehr Headerdateien, die wiederum fertige Funktionen beinhalten. Den entsprechenden Objektcode zu den Headerdateien der Laufzeitbibliothek finden Sie im LIB-Verzeichnis des Compilers. Wenn Sie die Headerdatei <stdio.h> mit einem Texteditor ansehen, werden Sie darin die Funktionsdefinitionen von z. B. printf() finden: > int printf(const char *format, ...); Der dem Compiler nachgeschaltete Linker sorgt dafür, dass diese Funktionen automatisch in das Programm mit eingebunden werden. # 9.19 Getrenntes Kompilieren von Quelldateien ## 9.19 Getrenntes Kompilieren von Quelldateien Für kleinere Programme, deren kompletter Quelltext in einer Datei geschrieben wurde, können Sie beim Kompilieren weiterhin wie bisher verfahren. Bei zunehmend gröÃeren Programmen könnten jedoch folgende Probleme auftreten: * Das Editieren und das Kompilieren dauern länger. * Der Quelltext wird unübersichtlich und schwieriger zu verstehen. * Teamarbeit wird erschwert. Ich werde dieses Beispiel anhand des GNU-Compilers gcc demonstrieren. Mit anderen Compilern dürfte dieser Vorgang ähnlich ablaufen. Bei Entwicklungsumgebungen müssen Sie dabei ein neues Projekt anlegen und die einzelnen Quelldateien zum Projekt hinzufügen. Im Folgenden sehen Sie ein Beispiel zum getrennten Kompilieren mit drei Programm-Modulen, die zu Demonstrationszwecken sehr kurz gehalten sind: > /*main.c*/ #include <stdio.h> #include <stdlib.h> extern void modul1(void); extern void modul2(void); int main(void) { modul1(); modul2(); return EXIT_SUCCESS; } /*modul1.c*/ void modul1(void) { printf("Ich bin das Modul 1\n"); } /*modul2.c*/ void modul2(void) { printf("Ich bin Modul 2\n"); } Jetzt haben Sie drei Dateien, die zusammen kompiliert und gelinkt werden müssen. Zuerst wird dazu der Schalter -c verwendet. Das bewirkt, dass die einzelnen Dateien zwar übersetzt werden, der Linkerlauf dabei aber nicht gestartet wird: > gcc -c main.c gcc -c modul1.c gcc -c modul2.c Jetzt befinden sich drei Objektdateien (*.obj oder *.o) im Verzeichnis, in dem kompiliert wurde. Diese drei Objektdateien können Sie mit folgender Anweisung zu einer ausführbaren Datei linken: > gcc main.o modul1.o modul2.o Jetzt befindet sich im Verzeichnis die Datei a.out. Dies ist die ausführbare Datei, das fertige Programm. Der Name a.out wird standardmäÃig vom Compiler verwendet. Mit dem Schalter -o können Sie auch einen eigenen Namen vorgeben: > gcc -o myapp main.o modul1.o modul2.o Sollten Sie gcc unter Windows verwenden, fügen Sie beim Programmnamen myapp die Extension *.exe hinzu (myapp.exe). Wenn Sie jetzt die Datei main.c ändern müssen, brauchen Sie nur diese neu zu übersetzen: > gcc -c main.c und können anschlieÃend die einzelnen Dateien wieder zusammenlinken: > gcc main.o modul1.o modul2.o Das nochmalige Kompilieren der anderen Dateien entfällt, da deren Code nicht geändert wurde und deshalb die unveränderten *.o-Dateien neu verlinkt werden können. Bei groÃen und sehr groÃen Projekten führt dieses Vorgehen zu deutlich kürzeren Kompilierzeiten. Natürlich versteht es sich von selbst, dass sich in einer der Dateien die main()-Funktion befinden muss. Abbildung 9.4 zeigt den ganzen Vorgang noch einmal grafisch. Abbildung 9.4 Ãbersetzen mehrerer Quelldateien # 9.20 Rekursive Funktionen (Rekursion) ## 9.20 Rekursive Funktionen (Rekursion) Kurz gesagt ist eine Rekursion eine Funktion, die sich selbst aufruft und sich selbst immer wieder neu definiert. Damit sich aber eine Rekursion nicht unendlich oft selbst aufruft, sondern irgendwann auch zu einem Ergebnis kommt, benötigen Sie unbedingt eine sogenannte Abbruchbedingung. Sonst kann es irgendwann passieren, dass Ihr Computer abstürzt, da eine Funktion, die sich immer wieder selbst aufruft, eine Rücksprungadresse, den Wert der Variablen und – falls noch nicht freigegeben – den Rückgabewert speichert. Der dafür zur Verfügung stehende Speicher (Stack) wird so aber unweigerlich irgendwann voll sein beziehungsweise überlaufen (Stacküberlauf oder Stack-Overflow). ### 9.20.1 Exkurs: Stack Der Stack wurde bereits öfter erwähnt. Er soll deshalb im Folgenden näher betrachtet werden. Der Stack dient dazu, den Speicherbereich für Funktionsaufrufe zu verwalten. Dieser Speicherbereich ist dynamisch, was bedeutet, dass der Speicher bei Bedarf automatisch anwächst und wieder schrumpft. Der Compiler, der diesen Stack verwaltet, legt hier alle Daten ab, die er zur Verwaltung von Funktionsaufrufen benötigt. Wenn eine Funktion aufgerufen wird, erweitert der Compiler den Stack um einen Datenblock. In diesem Datenblock werden die Parameter, die lokalen Variablen und die Rücksprungadresse zur aufrufenden Funktion angelegt. Dieser Datenblock wird als Stack-Frame oder Stackrahmen bezeichnet. Der Datenblock bleibt so lange bestehen, bis diese Funktion wieder endet. Wird in ihm aber eine weitere Funktion aufgerufen, wird ein weiterer Datenblock auf den (richtig wäre: unter den) aktuellen gepackt. Der Stack wächst nach unten an. Am Anfang des Stacks befindet sich der Startup-Code, der die main()-Funktion aufruft, die eine Position unter dem Startup-Code liegt. An unterster Stelle befindet sich immer die aktuelle Funktion, die gerade ausgeführt wird. Eine Position – oder besser: einen Datenblock – darüber liegt die aufrufende Funktion in der Wartestellung. Sie wartet auf die Beendigung der nächsten aufgerufenen Funktion. Mit diesem Wissen über den Stack können Sie sich wieder den Rekursionen widmen. ### 9.20.2 Rekursionen und der Stack Mit Rekursionen haben Sie die Möglichkeit, den Computer zu etwas zu bewegen, was ihn intelligenter erscheinen lässt. Ein Beispiel wäre etwa Schach. Wenn Sie einen Zug machen, gehen Sie zuerst alle Möglichkeiten durch, um den Gegner in Bedrängnis bzw. den gegnerischen König in Gefahr zu bringen oder gar schachmatt zu setzen. Das ist eine logische Denkweise des Menschen. Mit einer Rekursion ist es ebenfalls möglich, den Computer eine Situation so oft durchgehen zu lassen, bis er auf eine Lösung kommt – oder auch nicht. Man spricht dabei vom »Trial and Error«-Verfahren (Versuch und Irrtum). Ein Beispiel: Sie bedrohen den König des Computers. Der Computer geht dann alle Züge durch, um den König aus dieser Bedrohung zu befreien, und dann, in einem zweiten Schritt, geht er nochmals alle Züge durch, die Sie als Nächstes theoretisch machen könnten. Wie viele Züge er untersucht, richtet sich danach, wie tief die Rekursion gehen soll. Zum besseren Verständnis folgt ein konkretes Beispiel. Eine Funktion soll zwei Zahlen dividieren. Der ganzzahlige Rest der Division soll angegeben werden. Zum Beispiel: 10/2=5 oder 10/3=3 Rest 1. Das Programm darf aber nicht die Operatoren / und % verwenden. Die Lösung soll die Form einer rekursiven Funktion haben: > int divide(int x, int y) { if(x >= y) return (1 + divide(x - y, y)); if(x) printf("Zahl nicht teilbar -> Rest: %d -> ", x); return 0; } Hier ein Fall, in dem der Funktion beispielsweise die Werte x=8 und y=2 übergeben werden: > /* Funktionsaufruf */ printf("8/2 = Ergebnis : %d\n", divide(8, 2)); Innerhalb der Funktion wird zunächst die Abbruchbedingung überprüft: > if(x >= y) Da die Bedingung für x=8 und y=2 wahr ist, wird die nächste Anweisung ausgeführt: > return 1 + divide(x - y, y); Die Funktion gibt mittels return die Summe 1+divide(x-y,x) zurück. Damit wird, bevor das Ergebnis endgültig zurückgegeben wird, die Funktion divide erneut aufgerufen. Die Funktion ruft sich also selbst auf. Hiermit beginnt die Rekursion. Aber was passiert jetzt mit dem Rückgabewert 1? Sehen Sie sich das Beispiel zum besseren Verständnis in Abbildung 9.5 an. Abbildung 9.5 Erster rekursiver Aufruf Auf den Stack wurde zuerst die main()-Funktion gelegt, da diese zuerst die Funktion divide() aufgerufen hat. Hier ist quasi gespeichert, wie Ihr Programm wieder zur main()-Funktion zurückkommt. Sie können sich das in etwa so vorstellen: Bei jedem Funktionsaufruf in einem Programm – unabhängig davon, ob rekursiv oder nicht – wird der aktuelle Zustand der main()-Funktion eingefroren und auf dem Stack abgelegt. Damit das Programm weiÃ, wo die Adresse der main()-Funktion ist, wird auf dem Stack eine Rücksprungadresse mit abgelegt. Kommen wir zurück zur Programmausführung des konkreten Beispiels. Die Funktion hat sich also selbst mit der Anweisung > return 1 + divide(x - y, y); aufgerufen; in Zahlen also: divide(8-2,2), mit den Werten x=8 und y=2. Im abermaligen Funktionsaufruf wird erneut überprüft: > if(x >= y) Da x=6 und y=2 und somit die if-Abfrage wieder wahr ist, geht die Programmausführung wieder in der nächsten Zeile weiter. Es folgt ein erneuter Selbstaufruf der Funktion divide(): > return 1 + divide(x - y, y); Also wird Folgendes auf dem Stack abgelegt (siehe Abbildung 9.6). Abbildung 9.6 Zweiter rekursiver Aufruf Nun liegt auf dem Stack zweimal der Rückgabewert 1, inklusive der Rücksprungadressen (diese sind hier nicht mit abgebildet). Jetzt wiederholt sich das ganze Spiel noch zweimal, bis es auf dem Stack so aussieht wie in Abbildung 9.7 gezeigt. Der Funktionswert für x im Aufruf der Funktion ist mittlerweile auf 2 reduziert worden. Danach wird erneut die Funktion divide() aufgerufen, und zwar mit den Werten: > divide(2-2,2) Abbildung 9.7 Der Stack nach vier rekursiven Aufrufen Jetzt wird die Abbruchbedingung aktiv: > if(x >= y) Denn jetzt ist x=0 und y=2, und somit wird die Programmausführung nicht mehr in der nächsten Zeile fortgesetzt. Die nächste Abfrage > if(x) dient dazu, den Rest auszugeben, falls x ungleich 0 sein sollte. In unserem Beispiel gibt es keinen Rest. Es wird also der Wert 0 (return 0) zurückgegeben. Das Programm muss nun zur nächsten Rücksprungadresse gehen, da sich die Funktion ja beendet hat. Sehen Sie sich anhand von Abbildung 9.8 nochmals den Stack an. Der Rückgabewert 0 wurde von dem Funktionsaufruf divide(2-2,2) erzeugt. Dorthin führt auch die Rücksprungadresse, also return 0+1. Die nächste Rücksprungadresse wurde von divide(4-2,2) erzeugt, also folgt return 0+1+1; anschlieÃend folgt return 0+1+1+1 und zuletzt return 0+1+1+1+1. Die main-Funktion bekommt dann den Rückgabewert 0+1+1+1+1, also 4, und das ist auch korrekt, denn 8/2 ist 4. Abbildung 9.8 Die Abbruchbedingung greift jetzt ein. Abbildung 9.9 Addieren der einzelnen Rückgabewerte auf dem Stack Sie werden sich möglicherweise fragen, welche Vorteile ein solches Programm gegenüber einem Programm in der folgenden Form hat: > /* divide.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int x = 8, y = 2; printf("%d ", x/y); if(x % y) printf("Rest = %d\n",x%y); return EXIT_SUCCESS; } Dieses Programm erfüllt doch denselben Zweck und ist einfacher! Sie haben recht: Das rekursive Programm ist zum einen schwieriger und zum anderen langsamer, da ständig etwas auf den Stack geschoben und wieder von ihm geholt werden muss. Kurz gesagt: Die rekursive Lösung ist die schlechtere in diesem Beispiel. Schlimmer noch, die rekursive Lösung verbraucht viel Speicherplatz zum Anlegen von Parametern, lokalen Variablen, Rückgabewerten und Rücksprungadressen. Ein Beispiel: Sie wollen die Zahl 1.000.000 durch 2 teilen. Für die zwei Parameter x und y benötigen Sie schon acht Byte pro Aufruf. Für den Rückgabewert (return 1) werden weitere vier Bytes benötigt, genauso wie für die Rücksprungadresse. Das heiÃt, Sie verwenden für eine Ablage auf dem Stack 16 Byte. Wenn Sie die Zahl 1.000.000 durch 2 teilen, bedeutet dies, dass auf dem Stack 500.000 Werte zu je 16 Bytes liegen. Das sind ca. 7,6 Megabyte Arbeitsspeicher, die Sie durch eine rekursive Lösung eines solch einfachen Problems verschwenden. Warum also Rekursionen anwenden, wenn die direkte Lösung oftmals die bessere ist? In späteren Programmen werden Sie einige Beispiele kennenlernen (sogenannte binäre Bäume), die ohne Rekursion nicht so einfach realisierbar wären. Die Rekursion will ich Ihnen anhand von einigen Beispielen noch näher erläutern. Die verwendeten Programme sollen nur die Rekursion verdeutlichen. Es ist einleuchtend, dass die Programme ansonsten auch einfacher und meistens besser lösbar sind. Es sind typische, klassische Beispiele. ### 9.20.3 Fakultät In diesem Beispiel soll eine Funktion geschrieben werden, die die Fakultät der Zahl n berechnet. Die Fakultät der Zahl 6 ist zum Beispiel: 1*2*3*4*5*6=720. Die Fakultät von 10 ist 1*2*3*4*5*6*7*8*9*10=3.628.800. Wie schreiben Sie die Funktion am besten? Zuerst benötigen Sie eine Abbruchbedingung. Es muss lediglich überprüft werden, ob die Zahl, von der Sie die Fakultät berechnen wollen, ungleich 0 ist: > /* fakul.c */ #include <stdio.h> #include <stdlib.h> long fakul(long n) { if(n) return n * fakul(n-1); return 1; } int main(void) { printf("Fakultät von 5 = %ld\n",fakul(5)); printf("Fakultät von 9 = %ld\n",fakul(9)); return EXIT_SUCCESS; } Die Funktion rechnet so lange n*n-1, bis n den Wert 0 hat. Denn n*0 würde sonst das Ergebnis 0 ergeben. Bei fakul(5) wären dies dann 5*4*3*2*1=120, wobei n*1 eigentlich auch eingespart werden kann, denn mit n*1 wird sich der Wert nicht ändern. Natürlich will ich Ihnen die alternative direkte Lösung des Problems nicht vorenthalten: > long fakul(int n) { int x = n; while(--x) n *= x; return n; } ### 9.20.4 Fibonacci-Zahlen Die Fibonacci-Zahlen sollen rekursiv berechnet werden. Fibonacci-Zahlen sind z. B. 1, 2, 3, 5, 8, 13, 21, ... Errechnet werden können sie mittels ... 1+2=3, 2+3=5, 3+5=8, 5+8=13. Die Formel lautet also: F(n+2)=F(n+1) +F(n) Der Code dazu sieht so aus: ``` /* fibo.c */ #include <stdio.h> #include <stdlib.hlong fibo(long n) { if(n) return (n <= 2) ? n : fibo(n-2) + fibo(n-1); return 0; } int main(void) { long f; long i=0; printf("Wie viele Fibonacci-Zahlen wollen Sie ausgeben:"); scanf("%ld",&f); while(i++ < f) printf("F(%ld) = %ld\n", i, fibo(i)); return EXIT_SUCCESS; } ``` ### 9.20.5 GröÃter gemeinsamer Teiler (GGT) Nun folgt ein Listing zum Ermitteln des gröÃten gemeinsamen Teilers zweier Zahlen. Natürlich wird dafür der rekursive Weg eingeschlagen. Auch hier muss zuerst eine Abbruchbedingung gefunden werden. Sie haben drei Möglichkeiten zum Errechnen des GGT zweier Zahlen: > ist Zahl1 == Zahl2 dann Ergebnis = Zahl1 ist Zahl1 > Zahl2 dann Ergebnis = ggT(Zahl1-Zahl2, Zahl2) ist Zahl1 < Zahl2 dann Ergebnis = ggT(Zahl1, Zahl2-Zahl1) Das Programm sieht folgendermaÃen aus: > /* ggt1.c */ #include <stdio.h> #include <stdlib.h> unsigned long ggt(unsigned long a, unsigned long b) { if(a==b) return a; else if(a < b) return ggt(a, b-a); else return ggt(a-b, b); } int main(void) { unsigned long a, b; printf("ggt = gröÃter gemeinsamer Teiler\n"); printf("Zahl 1: "); scanf("%lu",&a); printf("Zahl 2: "); scanf("%lu",&b); printf("Der ggT von %lu und %lu ist %lu\n", a, b, ggt(a,b)); return EXIT_SUCCESS; } Beispiel: Sie geben für a=10 und für b=3 ein. Abbildung 9.10 zeigt, welche Wertepaare auf den Stack gelegt werden, bis das Programm den GGT von 1 zurückgibt. Abbildung 9.10 Rekursive Ermittlung des gröÃten gemeinsamen Teilers Eine alternative direkte Lösung wäre gewesen: ``` /* ggt2.c */ #include <stdio.h> #include <stdlib.hunsigned long ggt(unsigned long a, unsigned long b) { unsigned long count; if(a==b) return a; else if( (a % b) == 0) return b; else for(count = b; count > 0; count--) { if( ( (a % count) + (b % count) ) == 0) return count; } return 0; } int main(void) { unsigned long a, b, c; printf("ggt = größter gemeinsamer Teiler\n"); printf("Zahl 1: "); scanf("%lu",&a); printf("Zahl 2: "); scanf("%lu",&b); if(a<b) { /* a und b vertauschen */ c=a; a=b; b=c; } printf("Der ggT von %lu und %lu ist %lu\n", a, b, ggt(a,b)); return EXIT_SUCCESS; } ``` Nun soll der gröÃte gemeinsame Teiler von beliebig vielen Zahlen ermittelt werden. Die Schwierigkeit besteht bei diesem Beispiel aber nicht in der rekursiven Funktion, sondern in der main()-Funktion. Sie könnten die Funktion GGT, wie diese eben geschrieben wurde, benutzen, ohne sie zu verändern. Zuvor möchte ich Ihnen aber noch eine zweite Möglichkeit demonstrieren, wie Sie den GGT ermitteln können. Hier ist die Funktion dazu: > unsigned long ggt(unsigned long a, unsigned long b) { if(b==0) return a; return ggt(b, a % b); } Jetzt lassen sich womöglich die Vorteile einer Rekursion erkennen. Die rekursive Funktion erfüllt den gleichen Zweck wie die beiden Funktionen GGT zuvor. Mit return ggt(b, a%b) rufen Sie die Funktion erneut auf. Wenn a%b==0 ergibt, haben Sie ja den GGT durch b an a übergeben. Hier sehen Sie die main()-Funktion zum Ermitteln des GGT mehrerer Zahlen: > /* ggt3.c */ #include <stdio.h> #include <stdlib.h> unsigned long ggt(unsigned long a, unsigned long b) { if(b == 0) return a; return ggt(b, a % b); } int main(void) { unsigned long a, b; printf("ggt = gröÃter gemeinsamer Teiler(mit 0 beenden)\n"); printf("Zahl> "); scanf("%lu", &a); printf("Zahl> "); scanf("%lu", &b); a=ggt(a, b); while(1) { printf("Zahl> "); scanf("%lu", &b); if(b==0) break; a=ggt(a, b); } printf("-------->ggt = %lu\n", a); return EXIT_SUCCESS; } An dem Programm wurde nicht viel verändert. Es kam lediglich die while-Schleife hinzu, die Sie mit der Eingabe 0 beenden können. Wichtig ist, dass Sie bei jedem Schleifendurchlauf den gröÃten gemeinsamen Teiler an a und die neue Zahl an b übergeben. Somit wird immer der GGT aller Zahlen aktualisiert. Als letztes Beispiel will ich Ihnen zeigen, wie Sie eine rekursive Funktion zum Umwandeln von Dezimalzahlen nach Dualzahlen verwenden können. Um beispielsweise aus der Zahl 10 die entsprechende Dualzahl 1010 zu machen, ist folgender Vorgang nötig: > -> Solange die Zahl ungleich null -> -> Zahl % 2 = kein Rest dann 0 oder = Rest dann 1 -> -> Zahl = Zahl / 2 Auf die Zahl 10 angewendet, sieht dieser Vorgang wie folgt aus: > 10/2 = 5 kein Rest -> 0 5/2 = 2 Rest 1 -> 1 2/2 = 1 kein Rest -> 0 1/2 = 0 Rest 1 -> 1 Damit liegen auf dem Stack (umgekehrte Reihenfolge): > 1 0 1 0 Hier sehen Sie das Listing dazu: > /* dez2bin.c */ #include <stdio.h> #include <stdlib.h> #define ulong unsigned long void dez2bin(ulong dez) { if(dez) { dez2bin(dez / 2); printf("%lu", dez % 2); } } int main(void) { ulong dezimal; printf("Dezimalzahl in Dualzahl konvertieren\n"); printf("Welche Zahl : "); scanf("%lu",&dezimal); printf("Dezimal = %lu Dual = ",dezimal); dez2bin(dezimal); printf("\n"); return EXIT_SUCCESS; } Dies genügt nun zum Thema Funktionen. In Kapitel 18, »Arbeiten mit variablen langen Argumentlisten – <stdarg.h>«, wird es wieder aufgegriffen, wenn es darum geht, Funktionen mit beliebig vielen Parametern zu erstellen. Dafür müssen wir jedoch zuerst die Zeiger besprechen. # 9.21 »inline«-Funktionen ## 9.21 »inline«-Funktionen inline-Funktionen sind dem C++-Programmierer ja bereits wohlbekannt und stehen mit dem C99-Standard auch dem C-Programmierer zur Verfügung. Um eine Funktion als inline-Funktion zu präsentieren, muss nur das Schlüsselwort inline vorangestellt werden: > /* inliner.c */ #include <stdio.h> #include <stdlib.h> static inline void xchange(int *z1, int *z2) { int tmp; tmp = *z2; *z2 = *z1; *z1 = tmp; } static inline void print(int *z1, int *z2) { printf("%d :: %d\n", *z1, *z2); } int main(void) { int zahl1 = 123, zahl2 = 321; print(&zahl1, &zahl2); xchange(&zahl1, &zahl2); print(&zahl1, &zahl2); return EXIT_SUCCESS; } inline-Funktionen stellen eine sinnvolle Alternative zu parametrisierten define-Makros da. Der Code einer inline-Funktion wird vom Compiler direkt an der Stelle eingefügt, wo der Aufruf stattfindet. Damit entfällt der Sprung in ein Unterprogramm. Das heiÃt, die Sicherung der Rücksprungadresse, der Sprung zur Funktion und nach der Ausführung der Sprung zurück zur gespeicherten Rücksprungadresse entfallen. Dadurch ist die Ausführung einer inline-Funktion genauso schnell, als würde der Code direkt an der Stelle eingefügt. Die inline-Funktionen sollten aber möglichst klein gehalten werden. Werden zu viele Anweisungen verwendet, kann der Compiler das Schlüsselwort inline auch ignorieren und es als eine normale Funktion behandeln. Das Schlüsselwort inline ist nämlich für den Compiler nur ein Hinweis und kein Befehl. Wann der Compiler eine Funktion als inline behandelt und verwendet, entscheidet dieser selbst. Dass im Listing die inline-Funktion mit dem Spezifizierer static deklariert wurde, liegt daran, dass die Definition einer inline-Funktion in der Ãbersetzungseinheit vorhanden sein muss, wo diese verwendet wird. Der Nachteil an der inline-Funktion, die mit static deklariert ist, ist, dass Sie hierbei keine veränderbaren Speicherobjekte mit statischer Lebensdauer verwenden können. In der Praxis wird daher die Deklaration (!) einer inline-Funktion in eine externe Headerdatei ohne inline geschrieben und zusätzlich mit dem Schlüsselwort extern versehen, um so der kompletten Ãbersetzungseinheit zur Verfügung zu stehen, die diese Headerdatei inkludiert. > /* inline.h */ #ifndef INLINE_H #define INLINE_H extern void xchange(int *z1, int *z2); extern void print(int *z1, int *z2); #endif Jetzt können Sie auch die inline-Funktionen wie gewöhnliche Funktionen verwenden: > /* inliner2.c */ #include <stdio.h> #include <stdlib.h> #include "inline.h" inline void xchange(int *z1, int *z2) { int tmp; tmp = *z2; *z2 = *z1; *z1 = tmp; } inline void print(int *z1, int *z2) { printf("%d :: %d\n", *z1, *z2); } int main(void) { int zahl1 = 123, zahl2 = 321; print(&zahl1, &zahl2); xchange(&zahl1, &zahl2); print(&zahl1, &zahl2); return EXIT_SUCCESS; } # 10.2 Makros und Konstanten – »#define« ## 10.2 Makros und Konstanten – »#define« Mit #define ist es möglich, Zeichenketten anzugeben, die vor der Ãbersetzung des Programms gegen eine andere Zeichenkette ausgetauscht werden. Sie erinnern sich sicherlich aus dem vorangegangenen Kapitel daran, wie ein Programm übersetzt wird. Auch hier wird durch das Zeichen # bewirkt, dass der Präprozessor zuerst seine Arbeit verrichtet, bevor das werdende Programm vom Compiler in Assembler und dann in Maschinensprache übersetzt wird. Die Syntax der define-Direktive sieht so aus: > #define Bezeichner Ersatzbezeichner #define Bezeichner(Bezeichner_Liste) Ersatzbezeichner Bei der ersten Syntaxbeschreibung wird eine symbolische Konstante und im zweiten Fall ein Makro definiert. ### 10.2.1 Symbolische Konstanten mit »#define« Hier sehen Sie ein erstes Programmbeispiel, das eine symbolische Konstante definiert: > /* define1.c */ #include <stdio.h> #include <stdlib.h> #define EINS 1 int main(void) { printf("%d\n",EINS); return EXIT_SUCCESS; } Im Programm wird jede symbolische Konstante EINS mit dem Wert 1 definiert. Wenn Sie das Programm übersetzen, werden vor der Kompilierung alle Namen mit EINS im Quelltext vom Präprozessor durch den Wert 1 ersetzt. Die Konstante EINS müssen Sie nicht wie im Beispiel ausdrücklich in groÃen Buchstaben schreiben. Dies dient nur der besseren Ãbersicht. Aber Achtung, Folgendes funktioniert nicht: > printf("EINS"); In diesem Fall wird tatsächlich der String "EINS" auf dem Bildschirm ausgegeben und nicht der Wert 1. Das bedeutet, hier wird die Konstante EINS nicht durch 1 ersetzt. Welchen Vorteil haben solche Defines? Das soll das folgende Programm demonstrieren: > /* kreisber.c */ #include <stdio.h> #include <stdlib.h> /* Bei Linux muss für math.h das Compiler-Flag -lm * mit angegeben werden: * gcc -o synkonst2 symkonst2.c -lm */ #include <math.h> #define PI 3.1415926f /* Programm zur Berechnung von Kreisfläche(A), Durchmesser(d) * und Umfang(U) und Durchmesser aus Umfang */ void kreisflaeche(void) { float A,d; printf("Durchmesser des Kreises eingeben: "); scanf("%f", &d); A = d*d*PI / 4; printf("Die Kreisfläche beträgt %f\n", A); } void durchmesser(void) { float A, d; printf("Kreisfläche des Kreises eingeben: "); scanf("%f", &A); d =(float) sqrt((double)4*A/PI); printf("Der Duchmesser des Kreises ist %f\n", d); } void kreisumfang(void) { float U, d; printf("Durchmesser des Kreises eingeben: "); scanf("%f", &d); U = d * PI; printf("Der Umfang des Kreises beträgt %f\n", U); } void d2umfang(void) { float U,d; printf("Umfang des Kreises eingeben: "); scanf("%f",&U); d = U/PI; printf("Der Durchmesser des Kreises beträgt %f\n", d); } int main(void) { kreisflaeche(); durchmesser(); kreisumfang(); d2umfang(); return EXIT_SUCCESS; } In diesem Programm werden einfache Berechnungen von kreisförmigen Flächen durchgeführt. Statt PI an jeder Stelle im Programm erneut festzulegen, ist hier die textliche Ersetzung mittels define besser geeignet. Dadurch wird auch garantiert, dass stets der gleiche Wert überall im Programm verwendet wird. Sollten Sie z. B. eine genauere Angabe von PI benötigen, so müssen Sie nur die symbolische Konstante ändern. Einen weiteren Vorteil bietet z. B. die Verwendung bestimmter Konstanten, etwa einer Landeswährung. Falls eine Ãnderung erforderlich wird, kann diese ohne viel Aufwand für das gesamte Programm an einer zentralen Stelle vorgenommen werden. Sie können bei Makrodefinitionen auch auf früher definierte Namen zurückgreifen, wie im folgenden Beispiel: > #define PI 3.141592653 #define PI_2 PI*2 Hier wird zuerst PI definiert und in der nächsten Zeile der Wert von PI*2, der textlich durch PI_2 ersetzt wird. Mit der #define-Direktive können nicht nur Zahlen als symbolische Konstanten festgelegt werden, sondern auch Strings. Beispiel: > #include <stdio.h> #define GANZZAHL int #define SCHREIB printf( #define END ); #define EINGABE scanf( #define ENDESTART return 0; #define NEUEZEILE printf("\n"); #define START int main() #define BLOCKANFANG { #define BLOCKENDE } Mit diesen Festlegungen wurde mit minimalem Aufwand eine eigene kleine Programmiersprache erzeugt! Ein Programm in der neuen Sprache könnte zum Beispiel so aussehen: > START BLOCKANFANG GANZZAHL zahl; SCHREIB "<NAME>" END NEUEZEILE SCHREIB "Zahleingabe: " END EINGABE "%d", &zahl END SCHREIB "Die Zahl war %d", zahl END ENDESTART BLOCKENDE Hier wurde nicht wirklich eine neue Programmiersprache erzeugt. Statt int main() wird in dem Programm einfach START geschrieben, oder statt return 0 wird ENDESTART geschrieben. Der Präprozessor ersetzt vor der Ãbersetzung des Compilers die Pseudo-Sprache wieder nach C. Diese Pseudo-Sprache soll jetzt in eine eigene Headerdatei gepackt werden. Legen Sie dazu eine neue Quelldatei mit folgendem Inhalt an: > /* mysyntax.h */ #ifndef MYSYNTAX_H #define MYSYNTAX_H #include <stdio.h> #include <stdlib.h> #define GANZZAHL int #define SCHREIB printf( #define END ); #define EINGABE scanf( #define ENDESTART return EXIT_SUCCESS; #define NEUEZEILE printf("\n"); #define START int main() #define BLOCKANFANG { #define BLOCKENDE } #endif /*MYSYNTAX_H*/ Speichern Sie diese Codezeilen unter dem Namen MYSYNTAX.H. Jetzt folgt noch das Hauptprogramm inklusive der neuen Headerdatei: > /* mein_C.c */ #include "mysyntax.h" START BLOCKANFANG GANZZAHL zahl; SCHREIB "<NAME>" END NEUEZEILE SCHREIB "Zahleingabe: " END EINGABE "%d", &zahl END SCHREIB "Die Zahl war %d", zahl END NEUEZEILE ENDESTART BLOCKENDE Speichern Sie das Hauptprogramm im selben Verzeichnis, in dem sich auch mysyntax.h befindet. Den Namen für das Hauptprogramm können Sie frei wählen, zum Beispiel: mein_C.c. Ãbersetzen Sie dieses Programm. Befindet sich die Headerdatei mysyntax.h in einem anderen Verzeichnis als das Hauptprogramm, muss dies dem Compiler mitgeteilt werden. Befindet sich die Headerdatei z. B. in /home/myhome/myheader, wird dies dem Präprozessor wie folgt mitgeteilt: > #include "/home/myhome/myheader/mysyntax.h" Auf MS Windows-Systemen muss das so aussehen (C:\ sei Ihr Arbeitslaufwerk): > #include "c:\Programme\mysyntax.h" ### 10.2.2 Makros mit »#define« Weiterhin haben Sie die Möglichkeit, mit der define-Direktive parametrisierte Makros zu schreiben. Ein Beispiel: > /* define2.c */ #include <stdio.h> #include <stdlib.h> #define KLEINER_100(x) ((x) < 100) void klHundert(int zahl) { if(KLEINER_100(zahl)) printf("Ja! Die Zahl ist kleiner als 100!\n"); else printf("Die Zahl ist gröÃer als 100!\n"); } int main(void) { int b = 99; klHundert(b); return EXIT_SUCCESS; } Ein parametrisiertes Makro erkennen Sie daran, dass unmittelbar nach dem Makronamen eine Klammer folgt: > #define KLEINER_100(x) ((x) < 100) Alleinstehende Makros benötigen bei Verwendung im Programm kein Semikolon am Ende der Zeile. Daran lassen sich Makros auch oft erkennen. Es wird zwar nicht vom Compiler moniert, wenn Sie dennoch Semikolons setzen; es ist aber nicht erforderlich. Im betrachteten Fall haben Sie den formalen Parameter x. Dieser kann auf der rechten Seite des Makros beliebig oft verwendet werden. Dabei müssen Sie beachten, dass dieser formale Parameter ebenfalls auf der rechten Seite in Klammern stehen muss. Folgende Definition wäre falsch: > #define KLEINER_100(x) (x < 100) da sich hier der Parameter x nicht zwischen Klammern befindet. Die Zeile > if(KLEINER_100(zahl)) sieht nach dem Präprozessorlauf, also vor der eigentlichen Kompilierung, so aus: > if((zahl) < 100) Eine weitere, häufig eingesetzte Variante dieser Art ist: > #define MAX(x,y) ( (x)<=(y) ?(y) :(x) ) Hier werden gleich zwei Argumente als Parameter verwendet. Beide Parameter werden durch ein Komma voneinander getrennt. Bei diesem Makro wird die gröÃere der beiden Dezimalzahlen ermittelt. Ein weiteres Beispiel: > #define TAUSCHE(x,y) { \ int j; \ j=x; x=y; y=j; \ } Mit diesem Makro werden zwei Integer-Werte vertauscht. Wie sich ein Makro mit mehreren Statements über mehrere Zeilen erstrecken kann, lässt sich an diesem Beispiel ebenfalls erkennen. Bei der Makrodefinition muss an jedem Zeilenende ein Backslash geschrieben werden. Lange Makros, auf die häufig zugegriffen wird, können allerdings den Code unnötig aufblähen. In solch einem Fall sind Funktionen besser geeignet. Hierzu ein Negativ-Beispiel: > /* bad_define1.c */ #include <stdio.h> #include <stdlib.h> #define VIEL_TEXT "TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText\n" int main(void) { printf(VIEL_TEXT); printf(VIEL_TEXT); printf(VIEL_TEXT); return EXIT_SUCCESS; } Dieses Programm würde nach dem Präprozessorlauf und vor dem Compilerlauf folgendermaÃen aussehen: > /* bad_define2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { printf("TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText\n"); printf("TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText\n"); printf("TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText\n"); return EXIT_SUCCESS; } Jetzt dasselbe Beispiel mit einer Funktion, die in diesem Fall die effizientere Methode darstellt: > /* without_define.c */ #include <stdio.h> #include <stdlib.h> void viel_text(void) { printf("TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText"\ "TextTextTextTextTextTextTextTextTextText\n"); } int main(void) { viel_text(); viel_text(); viel_text(); return EXIT_SUCCESS; } Die define-Direktive ist im Ãbrigen eine rein für die Programmiersprache C gedachte Direktive. Ein reiner C++-Compiler wird define deshalb nicht erkennen und kompilieren. Die meisten Compiler kennen aber sowohl C als auch C++. In der Regel sollten hier also keine Probleme beim Kompilieren auftreten. Dies nur ergänzend zum Thema, falls Sie die Grundlagen in C kennenlernen wollen, um anschlieÃend mit C++ fortzufahren. Unter C++ und dem neuen ANSI-C99-Standard können kleinere Funktionsmakros auÃerdem durch inline-Funktionen ersetzt werden. # 10.3 Bedingte Kompilierung ## 10.3 Bedingte Kompilierung Zu diesem Unterkapitel muss erwähnt werden, dass viele der beschriebenen Vorgehensweisen nicht dem ANSI-C-Standard entsprechen. Da aber Programmierer oft ihre Programme auch auf andere Systeme portieren wollen, gehe ich hier dennoch näher auf die Thematik ein. Hierzu betrachten wir die Syntax zur bedingten Ãbersetzung: > #ifdef symbol #ifdef ( symbol ) #elif symbol #elif ( symbol ) #else #endif Diese Direktiven werden eingesetzt, um zu überprüfen, ob ein Symbol zuvor schon mit #define definiert wurde. Ist symbol definiert, liefern diese Direktiven 1 zurück, ansonsten 0. Abgeschlossen wird eine bedingte Ãbersetzung mit der Direktive #endif. Sie haben im vorangegangenen Kapitel (bei der selbst geschriebenen Headerdatei) schon einen kurzen Einblick in die bedingte Kompilierung erhalten. Hierzu ein einfaches Beispiel: > /* clrscr.c */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ #define clrscr() printf("\x1B[2J") #elif __BORLANDC__ && __MSDOS__ #include <conio.h> #elif __WIN32__ || _MSC_VER #define clrscr() system("cls") #else #define clrscr() printf("clrscr() - Fehler!!\n") #endif int main(void) { /* universale Routine zum Löschen des Bildschirms */ clrscr(); return EXIT_SUCCESS; } Hier wird vor der Ãbersetzung festgelegt, welche Routine zum Löschen des Bildschirms benutzt werden soll. Mit > #ifdef __unix__ überprüft der Präprozessor, ob das Programm auf einem UNIX-artigen System läuft. Wenn das der Fall ist, dann wird mit > #define clrscr() printf("\x1B[2J") die Routine zum Löschen des Bildschirms definiert, da diese eben nur unter UNIX/Linux funktioniert. Falls es sich nicht um ein UNIX-System handelt, wird mit > #elif __BORLANDC__ && __MSDOS__ überprüft, ob das Programm mit einem Borland-Compiler und unter MS-DOS übersetzt wird. Ist das der Fall, dann wird das Löschen des Bildschirms durch eine in der Headerdatei #include <conio.h> definierte Funktion mit demselbem Namen vorgenommen. AnschlieÃend wird überprüft, ob das Programm in einem Win32-Fenster läuft oder mit dem Visual C++-Compiler übersetzt wird. > #elif __WIN32__ || _MSC_VER #define clrscr() system("cls") Trifft keiner der geprüften Fälle zu, wird eine entsprechende Ausgabe erzeugt: > #else #define clrscr() printf("clrscr()-Fehler!!\n") Abgeschlossen wird diese bedingte Kompilierung mit: > #endif Durch die bedingte Kompilierung besteht die Möglichkeit, Programme einfacher auf andere Systeme zu portieren. Die bedingte Kompilierung lässt sich auch anders verwenden: > /* t_system.c */ #include <stdio.h> #include <stdlib.h> #ifdef __MSDOS__ int main(void) { printf("Programm läuft unter MSDOS \n"); return EXIT_SUCCESS; } #elif __WIN32__ || _MSC_VER int main(void) { printf("Programm läuft unter Win32\n"); return EXIT_SUCCESS; } #elif __unix__ || __linux__ int main(void) { printf("Programm läuft unter UNIX/LINUX\n"); return EXIT_SUCCESS; } #else int main(void) { printf("Unbekanntes Betriebssystem!!\n"); return EXIT_SUCCESS; } #endif Hier wurden mehrere main()-Funktionen verwendet. Auf dem System, für das die bedingte Kompilierung gilt, wird die entsprechende main-Funktion auch ausgeführt. Abbildung 10.2 Bedingte Kompilierung – das Programm läuft unter Win32. Abbildung 10.3 Bedingte Kompilierung – das Programm läuft unter Linux/UNIX. Sie können die bedingte Kompilierung mit if else-Abfragen vergleichen. Um compiler-spezifische Abfragen zu tätigen, gibt es folgende Compiler-Konstanten: Konstante | Compiler | | --- | --- | | | | | | | | | | | | | | | | | | | Denken Sie daran, dass diese Konstanten nicht vom ANSI-C-Gremium vorgeschrieben sind! Für die bedingte Kompilierung mit Betriebssystemen finden sich folgende Konstanten: Konstante | Betriebssystem | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | Es gibt sicherlich noch weitere Konstanten. Die hier genannten zählen zu den gängigsten. Sehen Sie sich ein anderes Programmbeispiel dazu an: > /* sektor.c */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ || linux #define SEKTORSIZE 4096 #elif __MSDOS__ || __WIN32__ || _MSC_VER #define SEKTORSIZE 512 #else #define SEKTORSIZE 0 #endif void sect(long size) { long kb,s=SEKTORSIZE; if(s == 0) printf("Unbekanntes System\n"); else if(s==4096) printf("UNIXsystem : "); else printf("DOS/Win32 : "); kb = size * s; printf("%ld Sektoren = %ld B\n", size, kb); } int main(void) { long sector; printf("Wie viele Sektoren: "); scanf("%ld",&sector); sect(sector); return EXIT_SUCCESS; } Dies ist ein Beispiel zum Thema Portabilität. Auf MS-DOS/Win32 beträgt die GröÃe eines Sektors auf der Festplatte 512 KB. Auf UNIX-Systemen hingegen beträgt sie meist 4096 KB (unter BSD für gewöhnlich 1024 KB) pro Sektor. Sie müssen nur am Anfang des Programms dem Präprozessor die Anweisung geben, für welches System er die GröÃe einer bestimmten Anzahl von Sektoren ausgeben soll. Folgende Schreibweisen sind im Ãbrigen identisch: > #ifdef MAKRO /* ist identisch mit */ #if defined MAKRO Des Weiteren gibt es eine Direktive, die es Ihnen ermöglicht, zu überprüfen, ob etwas nicht definiert wurde: > #ifndef __STDIO_H #define __STDIO_H #endif Hier überprüft der Präprozessor, ob er die Headerdatei <stdio.h> noch nicht eingebunden hat. Das ist zum Beispiel erforderlich, wenn mehrere Headerdateien und Module benutzt werden, die <stdio.h> benötigen. Somit würden alle Makros in der Headerdatei <stdio.h> mehrmals definiert werden, was im schlimmsten Fall sogar einen Fehler auslösen kann. Mit der eben geschriebenen Struktur wird dies vermieden. Auch zu dieser Direktive gibt es eine alternative Schreibweise: > #ifndef MAKRO /* ist dasselbe wie */ #if !defined MAKRO Folgende vordefinierten Makros werden von ANSI C vorgeschrieben: Hier sehen Sie ein Beispiel zur Verwendung dieser vordefinierten Makros: > /* direktiven.c */ #include <stdio.h> #include <stdlib.h> #if defined __STDC__ #define isstd_c() printf("ANSI-C-Compiler\n") #else #define isstd_c() printf("Kein ANSI-C-Compiler\n") #endif int main(void) { printf("Zeile %d in Datei %s\n",__LINE__,__FILE__); printf("Ãbersetzt am %s um %s\n",__DATE__,__TIME__); #line 999 "asdf.c" printf("Zeile %d in Datei %s\n",__LINE__,__FILE__); isstd_c(); /* Ist es ein ANSI-C-Compiler ? */ return EXIT_SUCCESS; } Im Programm wurde gleich eine weitere neue Präprozessor-Direktive eingesetzt: > #line Zeilennummer dateinamen.c Damit wird bewirkt, dass die nächste Zeile der Datei dateiname.c mit der Zeile Zeilennummer (also 999) beginnt. Diese Präprozessor-Direktive beeinflusst das Programm selbst nicht, sondern nur die Nummerierung der einzelnen Zeilen. Sie wird verwendet, um einem Programm Zeilennummern für Querverweise oder Fehlermeldungen zu übergeben. Diese Direktive wird vorwiegend von Programmen wie lex oder yacc verwendet, die C-Quelltexte erzeugen. AuÃer den vordefinierten Makros (wie __LINE__, __FILE__, __DATE__, __TIME__ und __STDC__) sind im C99-Standard weitere drei Makros hinzugekommen (siehe Tabelle 10.6). Einen Präprozessortest auf C99-Kompatibilität können Sie somit wie folgt durchführen: > #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L // C99-kompatibler Quellcode. #else // nicht C99-kompatibler Quellcode #endif Hier sehen Sie ein weiteres Beispiel mit dem Makro __func__, das sich prima zum Debuggen von Programmen eignet: > /* stdmakro.c */ #include <stdio.h> #include <stdlib.h> void eine_funktion(void) { printf("Name der Funktion: %s\n",__func__); } int main(void) { eine_funktion(); return EXIT_SUCCESS; } # 10.5 Ersetzung eines Makroparameters durch einen String ## 10.5 Ersetzung eines Makroparameters durch einen String Ist in einem Ersetzungstext vor dem Parameter das Zeichen # gesetzt, werden beim Aufruf des Makros das # und der Parameter durch den entsprechenden String ersetzt: > #define ausgabe(variable) printf(#variable"=%d\n",variable) Hier wird der Variablen zahl der Wert 10 (int Zahl=10;) übergeben. Steht im Programm beispielsweise: > ausgabe(Zahl); dann wandelt dies der Präprozessor zunächst um in: > printf("Zahl"" = %d\n", Zahl); Tatsächlich verhält sich der Ausdruck so, als würde Folgendes in der Zeile stehen: > printf("Zahl = %d\n", Zahl); Hierzu ein kleines Programmbeispiel, in dem diese Technik verwendet wird: > /* replace_makrparam.c */ #include <stdio.h> #include <stdlib.h> /* Bei Linux muss für math.h das Compiler-Flag -lm * mit angegeben werden: * gcc -o strkont strkont.c -lm */ #include <math.h> #define wurzel(zahl)\ printf(#zahl" von %f = %f\n",zahl,sqrt(zahl)) #define summe(zahl1,zahl2)\ printf(#zahl1 "+" #zahl2 " = %d\n",zahl1+zahl2) #define gibaus(string)\ printf(#string"\n") #define wertvon(zahl,format)\ printf(#zahl" = "format"\n",zahl) int main(void) { float Wurzel; int Wert1 = 100, Wert2 = 150, integer = 20; char character = 's'; float floating = 5.550f; printf("Zahl eingeben : "); scanf("%f",&Wurzel); wurzel(Wurzel); summe(Wert1,Wert2); gibaus(Hallo Welt); wertvon(character,"%c"); wertvon(integer,"%d"); wertvon(floating,"%f"); return EXIT_SUCCESS; } Abbildung 10.4 Ersetzung eines Makroparameters durch einen String Um ein Makro bzw. eine symbolische Konstante, die mit #define definiert wurde, wieder aufzuheben, müssen Sie im Programm nur > #undef makroname schreiben. Eine Makrodefinition gilt von deren Festlegung (#define) bis zum Programmende oder bis zur nächsten #undef-Direktive. Ein Beispiel: > /* undef.c */ #include <stdio.h> #include <stdlib.h> #define NUM 10 int main(void) { printf("Wert für symb. Konstante NUM: %d\n",NUM); /* 10 */ #ifdef NUM #undef NUM /* symb. Konstante aufheben */ #endif #define NUM 100 /* symb. Konstante wieder neu definieren */ printf("Wert für symb. Konstante NUM: %d\n",NUM); /* 100 */ return EXIT_SUCCESS; } Hätten Sie die symbolische Konstante NUM vor der Neudefinition nicht mit undef aufgehoben, hätte dies eine Warnung des Compilers zur Folge. Mit > #error "Fehlermeldung" wird eine Stringkonstante Fehlermeldung in der entsprechenden Zeile ausgegeben; zum Beispiel so: > /* nicht_fertig.c */ #include <stdio.h> #include <stdlib.h> #define FERTIG int main(void) { printf("Programmstart!\n"); #ifdef FERTIG #error "Das Programm ist noch nicht fertig gestellt!!\n" #endif printf("Programmende"); return EXIT_SUCCESS; } Wenn Sie versuchen, das Programm zu kompilieren, wird folgende Fehlermeldung des Compilers ausgegeben: > Das Programm ist noch nicht fertig gestellt!! Das Programm lässt sich somit auch nicht kompilieren. Damit kann z. B. vermieden werden, dass ein noch nicht ganz fertiggestellter bzw. nicht fehlerfreier Codeabschnitt verwendet wird. Das kann bei einem Projekt, an dem mehrere Leute arbeiten, praktisch sein. Aber es lassen sich damit auch Fehlermeldungen ausgeben, die im Zusammenhang mit der Expansion von Makros festgestellt wurden. Zum Beispiel: > /* nicht_gerade.c */ #include <stdio.h> #include <stdlib.h> #define MAX 101 int main(void) { printf("Programmstart\n"); #if (MAX % 2) == 1 #error "symb. Konstante MAX muss eine gerade Zahl sein!\n" #endif printf("Programmende\n"); return EXIT_SUCCESS; } Dieses Programm lässt sich erst übersetzen, wenn Sie der symbolischen Konstante MAX einen geraden Wert übergeben. # 10.8 »#pragma« ## 10.8 »#pragma« #pragma-Direktiven sind compiler-spezifisch, also von Compiler zu Compiler verschieden. Wenn ein Compiler eine bestimmte #pragma-Direktive nicht kennt, wird diese ignoriert. Mithilfe dieser Pragmas können Compiler-Optionen definiert werden, ohne mit anderen Compilern in Konflikt zu geraten. Da das Verhalten von #pragma-Anweisungen stark systemabhängig ist, werde ich darauf hier nicht näher eingehen. # 11.2 Initialisierung und Zugriff auf Arrays ## 11.2 Initialisierung und Zugriff auf Arrays In dem folgenden Listing wird gezeigt, wie ein Array mit Werten initialisiert wird und wie darauf zugegriffen werden kann: > /* array1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int i[5]; /* Array mit 5 int-Elementen */ /* Wertzuweisungen des Arrays */ i[0] = 5; i[1] = 100; i[2] = 66; i[3] = 77; i[4] = 1500; /*Ausgabe der einzelnen Array-Elemente*/ printf("Array-Element i[0]= %d\n", i[0]); printf("Array-Element i[1]= %d\n", i[1]); printf("Array-Element i[2]= %d\n", i[2]); printf("Array-Element i[3]= %d\n", i[3]); printf("Array-Element i[4]= %d\n", i[4]); return EXIT_SUCCESS; } Bei diesem Beispiel wurde an alle fünf Feldelemente ein Wert mithilfe des Indizierungsoperators [] übergeben. Und wie der Name des Operators schon sagt, dient dieser dem indizierten Zugriff auf Datentypen, die typischerweise hintereinander im Speicher abgelegt sind. Warum lautet der Index des letzten Elements [4] und nicht [5]? Für den Computer ist die Zahl 0 auch ein Wert, und somit fängt dieser stets bei 0 an zu zählen: Abbildung 11.2 Ein Array mit Werten initialisieren Sie sehen hier 5 Zahlen: 0, 1, 2, 3 und 4. Befände sich im Programm die Zeile > i[5] = 111; printf("i[5] = %d\n",i[5]); würde versucht, auf einen nicht reservierten Speicher zuzugreifen. Es wurde aber nur Speicher für fünf Adressen vom Datentyp int reserviert. Gefährlicher kann das werden, wenn dies in einer for-Schleife geschieht. Wird hier der Indexbereich überschritten, kann es passieren, dass mit falschen Werten weitergearbeitet wird. Hier ein Beispiel für einen Fehler, der leider oft gemacht wird: > /* array2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int test[10]; int i; for(i = 0; i <= 10; i++) /* !!Bereichsüberschreitung!! */ test[i] = i; for(i = 0; i <= 10; i++) printf("%d, ", test[i]); printf("\n"); return EXIT_SUCCESS; } Das Programm macht nichts anderes, als das Array test[10] mit 11(!) Werten zu initialisieren, und anschlieÃend werden diese Werte auf dem Bildschirm ausgegeben. Haben Sie den Fehler schon gefunden? Der Fehler liegt in der for-Schleife: > for(i = 0; i <= 10; i++) Die for-Schleife wird insgesamt elfmal durchlaufen: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Es kann (oder besser es wird) bei diesem Programm passieren, dass test[10] tatsächlich den Wert 10 enthält. Sobald aber irgendwo im Programm diese Speicheradresse für eine andere Variable benötigt wird, wird der aktuelle Wert von test[10] überschrieben. Es kann also nicht garantiert werden, dass der Wert von test[10] erhalten bleibt, was zwangsläufig zu ungewollten Effekten und schwer aufzuspürenden Fehlern im Programm führt. Wenn Sie das Programm gegenwärtig ausführen wollen, ohne dass solch ein Fehler auftritt, müssen Sie nur den Zuweisungsoperator aus den beiden for-Schleifen entfernen: > for(i = 0; i < 10; i++) /* ohne '='-Zeichen richtig */ In dem Programm haben Sie gesehen, wie auf ein Array zugegriffen werden kann, um es mit Werten zu initialisieren: > for(i = 0; i < 10; i++) test[i] = i; Damit wird die Schleife abgebrochen, sobald i den Wert 10 erreicht. Generell ist also bei der Verwendung von Arrays im Zusammenhang mit Schleifen Vorsicht geboten, und Sie müssen genau darauf achten, dass der Wertebereich des Feldes nicht unter- bzw. überschritten wird. Solche Unter- oder Ãberschreitungen werden vom Compiler nicht überprüft oder moniert. Statt einer konstanten Ganzzahl wurde hier die Variable i verwendet. Das funktioniert deshalb, weil diese Variable vom Datentyp int ist und somit auch einer Ordinalzahl entspricht. Die Variable wird von der for-Schleife bei jedem Durchlauf um den Wert eins erhöht (inkrementiert). Daraus ergibt sich, dass als Index nur Ganzzahlwerte erlaubt sind. Oftmals wird zur Bezeichnung des Index auch eine define-Konstante verwendet, wie das folgende Beispiel demonstriert: > /* array3.c */ #include <stdio.h> #include <stdlib.h> #define SIZE 10 int main(void) { int zahlen[SIZE] = { 0 }; printf("Anz. Elemente : %d\n", sizeof(zahlen) / sizeof(int)); return EXIT_SUCCESS; } Solche Konstanten können die Lesbarkeit bei längeren Programmen erheblich verbessern und tragen dazu bei, Fehler zu vermeiden. Ein weiterer Vorteil entsteht, wenn Sie die Anzahl der Elemente des Arrays erhöhen wollen. Sie müssen nur den Wert der define-Konstante ändern und nicht mühsam im Programm danach suchen. Arrays lassen sich auch anders, nämlich direkt bei der Deklaration, initialisieren. Die Werte müssen dabei zwischen geschweiften Klammern stehen: > int numbers[] = { 1, 2, 4, 5, 9 }; Wenn Sie das Array so initialisieren, können Sie die GröÃe des Arrays auch weglassen. C kümmert sich darum, dass genügend Speicher zur Verfügung steht. Die einzelnen Initializer werden immer mit einem Komma getrennt und stehen in geschweiften Klammern. Dadurch ist das Feld wie folgt mit Werten belegt: > numbers[0] = 1; numbers[1] = 2; numbers[2] = 4; numbers[3] = 5; numbers[4] = 9; Natürlich können Sie trotzdem die GröÃe des Arrays angeben. Bei einem gröÃeren Array hat diese Initialisierung den Vorteil, dass Sie alle anderen Werte gleich mit 0 vorbelegen können. Anstatt eine for-Schleife zu schreiben, wie etwa: > int bigarray[1000]; for(i = 0; i < 1000; i++) bigarray[i] = 0; lässt sich das auch einfacher formulieren: > int bigarray[1000] = { 0 }; Hier wurde nur das Array mit dem Index [0], also bigarray[0], mit dem Wert 0 initialisiert. Die restlichen 999, die nicht ausdrücklich initialisiert wurden, werden jedoch automatisch ebenfalls mit dem Wert 0 besetzt. Dies kann aber noch ganz anders gelöst werden, und zwar unter Verwendung der folgenden Funktion: > /* Beschreibung der Funktion, siehe Abschnitt 20.8 */ #include <string.h> void *memset(void *adres, int zeichen, size_t n); Mit der Funktion memset() wird der Wert von zeichen in jedes der ersten n Zeichen des Speicherbereichs mit der Adresse adres geschrieben. Das sieht dann wie folgt aus: > int bigarray[1000]; memset(bigarray, 0, sizeof(bigarray)); Wenn Sie das jetzt nicht nachvollziehen können: Ein paar Seiten später werden Sie es besser verstehen. Tatsächlich handelt es sich hier auch um einen Spezialfall der Verwendung von memset(), da sich dieses Verfahren nur mit dem Wert 0 auf ein int-Array anwenden lässt. Das liegt daran, dass memset() bitweise arbeitet. Bei einem int-Array auf einem 32-Bit-System würde dies bei 4 Bytes den Wert 16843009 bedeuten (alle Bits auf 1). Hier noch ein weiteres Beispiel zur Initialisierung von Arrays: > double inhalt[100] = { 2.4, 2.8, 9.45, 10.99 }; Hiermit wurden folgende Werte initialisiert: > inhalt[0] = 2.4 inhalt[1] = 2.8 inhalt[2] = 9.45 inhalt[3] = 10.99 inhalt[4] = 0.0 inhalt[5] = 0.0 ... inhalt[97] = 0.0 inhalt[98] = 0.0 inhalt[99] = 0.0 Ab inhalt[4] bis inhalt[99] werden alle Werte automatisch mit 0.0 initialisiert. Leider ist es nicht möglich, den Inhalt eines Arrays mit einem anderen konstanten Wert auÃer 0 zu initialisieren. ### 11.2.1 Gültigkeitsbereich von Arrays Der Gültigkeitsbereich von Arrays richtet sich danach, ob es sich dabei um ein statisches, globales oder ein normales (lokales) Array handelt. Betrachten Sie zur Verdeutlichung ein kleines Beispielprogramm: > /* array4.c */ #include <stdio.h> #include <stdlib.h> int wert_global[5]; int main(void) { static int wert_static[5]; int wert_auto[5]; int i; for(i = 0; i < 5; i++) printf("%d:\t%10d\t%10d\t%10d\n", i, wert_global[i], wert_static[i], wert_auto[i] ); return EXIT_SUCCESS; } Abbildung 11.3. zeigt die Ausgabe des Programms am Bildschirm. Abbildung 11.3 Gültigkeitsbereich von Variablen Das Programm gibt für das globale und für das mit dem Schlüsselwort static deklarierte Array jeweils den Wert 0 aus. Das automatische Array wert_auto hingegen gibt einen undefinierten Wert zurück. Daraus lässt sich schlieÃen, dass globale und mit static deklarierte Arrays automatisch mit 0 initialisiert werden. Das Verhalten des Programms ändert sich, wenn die Automatic-Variable (wert_auto) mit mindestens einem Wert initialisiert wird: > /* array5.c */ #include <stdio.h> #include <stdlib.h> int wert_global[5]; int main(void) { static int wert_static[5]; int wert_auto[5] = { 0 }; /* Array mit 0 initialisiert */ int i; for(i = 0; i < 5; i++) printf("%d:\t%10d\t%10d\t%10d\n", i, wert_global[i], wert_static[i], wert_auto[i] ); return EXIT_SUCCESS; } Es wurde hier nur die Zeile > int wert_auto[5] = { 0 }; verändert und wert_auto[0] mit dem Wert 0 initialisiert. Die Ausgabe des Programms zeigt jetzt (erwartungsgemäÃ) die initialisierten Werte. Abbildung 11.4 Gültigkeitsbereich von Variablen # 11.3 Arrays vergleichen ## 11.3 Arrays vergleichen Mithilfe des Indizierungsoperators [] können Sie zwei int-Arrays auf Gleichheit überprüfen: > /* array6.c */ #include <stdio.h> #include <stdlib.h> #define MAX 10 int main(void) { int i; int array1[MAX], array2[MAX]; for(i = 0; i < MAX; i++) { array1[i] = i; array2[i] = i; } array2[5] = 100; /* array2 an Pos. 5 verändern */ for(i = 0; i < MAX; i++) { if( array1[i] == array2[i] ) continue; else { printf("Unterschied an Position %d\n",i); break; } } return EXIT_SUCCESS; } Mit der Zeile > if( array1[i] == array2[i] ) werden die einzelnen Werte array1[i] und array2[i] miteinander verglichen. Es werden also alle Elemente der Arrays durchlaufen und verglichen. Folgendes funktioniert allerdings nicht: > if( array1 == array2 ) Ganze Arrays lassen sich nicht miteinander vergleichen. In diesem Fall wurden lediglich zwei Speicheradressen verglichen. Für den Vergleich vollständiger bzw. kompletter Arrays gibt es folgende Funktion: > #include <string.h> int memcmp(const void *adr1, const void *adr2, size_t n); Diese Funktion vergleicht n Zeichen aus Adresse adr1 und Adresse adr2. Sind beide Speicherbereiche gleich, liefert die Funktion den Wert 0 zurück (zur weiteren Beschreibung dieser Funktion siehe Abschnitt 20.8, »<string.h> – die mem -Funktionen zur Speichermanipulation.« Hierzu ein Beispiel mit der Funktion memcmp(): > /* array7.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 10 int main(void) { int i; int array1[MAX]; int array2[MAX]; for(i = 0; i < MAX; i++) { array1[i] = i; array2[i] = i; } array2[5] = 100; /* Verändert array2 an Pos. 5. */ if(memcmp(array1, array2, sizeof(array1)) == 0 ) printf("Beide Arrays haben den gleichen Inhalt\n"); else printf("Die Arrays sind unterschiedlich\n"); return EXIT_SUCCESS; } # 11.4 Anzahl der Elemente eines Arrays ermitteln ## 11.4 Anzahl der Elemente eines Arrays ermitteln Wie lässt sich die Anzahl der Elemente eines Arrays ermitteln? Dies kann mit dem sizeof-Operator realisiert werden, den Sie bereits kennengelernt haben. Mit ihm lässt sich die GröÃe eines Datentyps in Byte ermitteln. Folgendes Array soll als Beispiel dienen: > int zahlen[] = { 3,6,3,5,6,3,8,9,4,2,7,8,9,1,2,4,5 }; Jetzt soll der sizeof-Operator auf dieses Array angewendet werden: > /* array8.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int zahlen[] = {3,6,3,5,6,3,8,9,4,2,7,8,9,1,2,4,5}; printf("Anzahl der Elemente: %d\n", sizeof(zahlen)); return EXIT_SUCCESS; } Bei der Ausführung des Programms erhalten Sie auf einem 16-Bit-System als Ergebnis den Wert 34 und auf einem 32-Bit-System den Wert 68. Dass dieser Wert nicht der Anzahl der Elemente entspricht, ist leicht nachvollziehbar. Der Wert 34 bzw. 68 stellt in diesem Beispiel zunächst nur die GröÃe des Arrays in Byte dar. Damit die Anzahl der Elemente bestimmt werden kann, muss dieser Wert durch die GröÃe des Array-Datentyps geteilt werden: > /* array9.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int zahlen[] = {3,6,3,5,6,3,8,9,4,2,7,8,9,1,2,4,5}; printf("Anz. Elemente : %d\n", sizeof(zahlen) / sizeof(int)); return EXIT_SUCCESS; } Damit haben Sie die richtige Anzahl der Elemente (17) ermittelt. # 11.5 Ãbergabe von Arrays an Funktionen ## 11.5 Ãbergabe von Arrays an Funktionen Um Arrays an Funktionen zu übergeben, gehen Sie ähnlich wie bei Variablen vor. Die Funktionsdeklaration sieht folgendermaÃen aus: > void function(int feld[], int n_Anzahl) Auffällig ist hier, dass der Indexwert für die GröÃe des Arrays nicht angegeben wird. Das liegt daran, dass der Funktion nicht bekannt ist, wie viele Elemente das Array besitzt. Daher ist es empfehlenswert, der Funktion die Anzahl der Elemente als Argument mitzugeben, wie auch im Beispiel oben bei der Deklaration der Variablen n_Anzahl zu sehen ist. Hierbei kommen Sie zum ersten Mal mit Zeigern in Berührung. Arrays werden bei einer Funktion nicht wie Variablen (call-by-value) kopiert, sondern als Zeiger übergeben (call-by-reference, siehe Kapitel 12, »Zeiger (Pointer)«). Somit muss die Funktion nicht notwendigerweise eine Kopie für das übergebene Array anlegen (wie sonst üblich), sondern arbeitet lediglich mit der (Anfangs-)Adresse des Arrays. Es ist also nicht zwingend erforderlich, die GröÃe des Arrays als Parameter an eine Funktion zu übergeben, da auf diese Weise von der Anfangsadresse eines Arrays aus sequenziell alle Elemente des Arrays erreicht werden können. Dieser enge Zusammenhang zwischen Arrays und Pointern wird in Kapitel 12 und teilweise auch in Kapitel 14 ausführlich erklärt. Aufgerufen wird die Funktion mit folgenden Argumenten: > #define MAX 100 ... function(feld, MAX); Damit bekommt die Funktion function() die Anfangsadresse des Arrays feld übergeben. Es wäre auch folgender Funktionsaufruf möglich: > function(&feld[0], MAX); Auch hier wird der Funktion die Anfangsadresse übergeben, also die Adresse des ersten Elements des Arrays. Hier sehen Sie ein Beispiel dazu: > /* array10.c */ #include <stdio.h> #include <stdlib.h> #define MAX 10 void function(int feld[], int n_anzahl) { int i; for(i = 0; i < n_anzahl; i++) printf("%d; ", feld[i]); printf("\n"); } int main(void) { int val[MAX]; int i; for(i = 0; i < MAX; i++) val[i] = i+1; function(val, MAX); return EXIT_SUCCESS; } So weit, so gut. Wenn Sie jetzt aber bereits ein wenig Erfahrung mit C haben bzw. Ihnen das Thema Zeiger nicht ganz fremd ist, werden Sie sich wohl fragen, warum hier die Array-Deklaration so einfach mit einer Zeiger-Deklaration als formalem Parameter austauschbar ist? Dies hat den einfachen Grund, dass Arrays sofort in Zeiger umgewandelt werden (zerfallen) und somit nie wirklich ein Array an eine Funktion übergeben wird. Besonders Anfänger verwirrt dieser Umstand recht häufig, aber diese Umwandlung gilt wirklich nur für die formalen Parameter einer Funktion! Jetzt ist Ihnen zwar bekannt, dass ein Array an eine Funktion als Referenz (auf eine Adresse) übergeben wird. Wie aber ist vorzugehen, wenn ein Array unbedingt als Kopie übergeben werden soll? Sie können das Array in eine Struktur verpacken und dann an die Funktion übergeben. Näheres zu den Strukturen erfahren Sie weiter unten. Für den Fall der Fälle folgt hier das Beispiel dazu: > /* array11.c */ #include <stdio.h> #include <stdlib.h> struct array{ int wert[3]; }; void output_array(struct array z) { int i; for(i = 0; i < sizeof(struct array) / sizeof(int); i++) printf("%d\t", z.wert[i]); printf("\n"); } int main(void) { struct array new_array; new_array.wert[0] = 10; new_array.wert[1] = 20; new_array.wert[2] = 30; /* call-by-value */ output_array(new_array); return EXIT_SUCCESS; } # 11.6 Arrays aus Funktionen zurückgeben ## 11.6 Arrays aus Funktionen zurückgeben Arrays können nicht als Rückgabetyp von Funktionen definiert werden. Auch dazu bedienen wir uns des bekannten Tricks, Arrays in eine Struktur zu verpacken. Hierzu ein Listing zur Demonstration: > /* array12.c */ #include <stdio.h> #include <stdlib.h> struct array{ int wert[3]; }; struct array init_array(void) { int i; struct array z; for(i = 0; i < sizeof(struct array) / sizeof(int); i++) { printf("Wert %d eingeben: ",i); scanf("%d",&z.wert[i]); } return z; } void output_array(struct array z) { int i; for(i = 0; i < sizeof(struct array) / sizeof(int); i++) printf("%d\t", z.wert[i]); printf("\n"); } int main(void) { struct array new_array; /* Array als Rückgabewert in einer Struktur verschachtelt */ new_array=init_array(); /* call-by-value */ output_array(new_array); return EXIT_SUCCESS; } Die letzten beiden Listings dürften einen Programmierneuling ein wenig verwirrt haben, da zur Demonstration Strukturen verwendet wurden, die erst später in Kapitel 15 behandelt werden. # 11.7 Programmbeispiel zu den Arrays ## 11.7 Programmbeispiel zu den Arrays Das folgende, etwas umfangreichere Beispiel zeigt, welche Möglichkeiten die Verwendung von Arrays bietet. Das Beispielprogramm wertet eine Statistik für zwei FuÃballmannschaften aus, und zwar das Tore- und Punkteverhältnis der letzten fünf Spiele, die beide Mannschaften gegeneinander gespielt haben: > /* array13.c */ #include <stdio.h> #include <stdlib.h> /* Bilanz aus 5 Spielen */ #define SPIELE 5 #define WIN 3 #define LOSE 0 #define REMIS 1 /* Alle Elemente mit 0 initialisieren */ int Bayern[SPIELE] = { 0 }; int Borussia[SPIELE]= { 0 }; /* Funktion zum Zählen der Punkte */ void punkte(int bm[], int bd[], int count) { if(bm[count] > bd[count]) { bm[count] = WIN; /* 3 Punkte für Bayern */ bd[count] = LOSE; } else if(bm[count] < bd[count]) { bm[count] = LOSE; bd[count] = WIN; /* 3 Punkte für Borussia */ } else if(bm[count] == bd[count]) { bm[count] = REMIS; /* 1 Punkt für jeden - unentschieden */ bd[count] = REMIS; } } int main(void) { unsigned int tor1, tor2; unsigned int tmptor1 = 0, tmptor2 = 0; unsigned int punkte_bay = 0, punkte_bor = 0; unsigned int count=0; /* Indexzaehler */ /* Eingabe des Anwenders */ printf("Eingabe der letzten %d Spiele\n", SPIELE); while(count != SPIELE) { printf("%d. Spiel : Bayern - Borrusia\n", count+1); printf("Tor(e) Bayern : "); scanf("%2u", &tor1); Bayern[count] = tor1; printf("Tor(e) Borussia : "); scanf("%2u", &tor2); Borussia[count] = tor2; tmptor1 += tor1; /*Tore zaehlen Bayern*/ tmptor2 += tor2; /*Tore zaehlen Borussia*/ /* Werte an Funktion punkte() uebergeben */ punkte(Bayern, Borussia, count); /* Punkte zaehlen */ punkte_bay += Bayern[count]; punkte_bor += Borussia[count]; /* Nächstes Spiel */ count++; } /* Ausgabe der Statistik */ printf("\n\nStatistik der letzten %d Spiele\n\n", SPIELE); printf("Bayern - Borussia\n"); printf("Punkte : %2d : %2d\n", punkte_bay, punkte_bor); printf("Tore : %2d : %2d\n", tmptor1, tmptor2); return EXIT_SUCCESS; } Die Bildschirmausgabe des Programms könnte (abhängig von den Eingabewerten) z. B. so aussehen wie in Abbildung 11.5. Abbildung 11.5 Ausgabe des Programmbeispiels Das Programm soll nun Schritt für Schritt erläutert werden. > int Bayern[SPIELE] = { 0 }; int Borussia[SPIELE]= { 0 }; Hier wird jeweils ein Array mit dem Wert 0 initialisiert. Sehr wichtig im Programm ist folgende Variable: > unsigned int count = 0; Mit ihr wird die Anzahl der gespielten Spiele gezählt. In der while-Schleife der Hauptfunktion werden Sie aufgefordert, das Endergebnis jedes einzelnen Spiels einzugeben. Der Wert wird an die Arrays mittels > Bayern[count] = tor1; ... Borussia[count] = tor2; übergeben. War das erste Ergebnis beispielsweise 2:1 für Bayern, dann bekommen die Elemente mit dem Index 0 folgende Werte: > Bayern[0] = 2; ... Borussia[0] = 1; Diese beiden Werte werden danach mit der Anzahl absolvierter Spiele an die Funktion void punkte(...) übergeben: > punkte(Bayern, Borussia, count); Tatsächlich werden hier die Anfangsadressen der Arrays an die Funktion punkte() übergeben. Dort wird mit if else-Anweisungen überprüft, welcher der beiden Werte höher ist. Dabei ist das aktuelle Ergebnis von Interesse, das mit dem Index [count] angegeben ist. Im konkreten Beispiel (2:1) wäre folgende Bedingung wahr: > if(bm[count] > bd[count]) { bm[count] = WIN; /* 3 Punkte für Bayern */ bd[count] = LOSE; } Somit werden den Elementen der Arrays folgende Werte zugewiesen: > bm[0] = 3 /* Punkte für Bayern */ bd[0] = 0 /* Punkte für Borussia */ Wenn Borussia siegen sollte, überprüft die Funktion punkte() die nächste Bedingung. Die letzte else-if-Anweisung steht für ein Unentschieden beider Mannschaften, und jeder bekommt einen Punkt. Danach fährt das Programm mit der while-Schleife der Hauptfunktion fort. Dort wird mit > count++; der Indexzähler um 1 erhöht, und es kommt die nächste Abfrage der Werte für: > Bayern[1]=... und Borussia[1]=... Es werden so lange Werte eingegeben, bis > while(count != SPIELE) unwahrheitsgemäà abbricht. Das ist der Fall, sobald count == SPIELE wird, also 5 Spiele gespielt wurden. AnschlieÃend wird die Gesamtpunktzahl von jedem Team auf dem Bildschirm ausgegeben. Zur Vergabe von Punkten wurden hier symbolische Konstanten verwendet, falls sich im Reglement wieder einmal etwas in der Punktevergabe ändert. # 11.8 Einlesen von Array-Werten ## 11.8 Einlesen von Array-Werten Einlesen können Sie die vom Benutzer eingegebenen Werte für ein Array beispielsweise mit scanf(), z. B. folgendermaÃen: > /* array14.c */ #include <stdio.h> #include <stdlib.h> #define MAX 5 int main(void) { int i; int array[MAX]; for(i = 0; i < MAX; i++) { printf("%d. Zahl > ", i+1); scanf("%d", &array[i]); } printf("Sie haben eingegeben: "); for(i = 0; i < MAX; i++) printf("%d ", array[i]); printf("\n"); return EXIT_SUCCESS; } Sie müssen lediglich mithilfe des Indizierungsoperators das Indexfeld verwenden, das Sie mit einem Wert versehen wollen. # 11.9 Mehrdimensionale Arrays ## 11.9 Mehrdimensionale Arrays Arrays, wie sie bisher besprochen wurden, können Sie sich als einen Strang von hintereinander aufgereihten Zahlen vorstellen. Man spricht dann von eindimensionalen Arrays oder Feldern. Es ist aber auch möglich, Arrays mit mehr als nur einer Dimension zu verwenden: > int Matrix[4][5]; /* Zweidimensional - 4 Zeilen x 5 Spalten */ Hier wurde z. B. ein zweidimensionales Array mit dem Namen Matrix definiert. Dies entspricht im Prinzip einem Array, dessen Elemente wieder Arrays sind. Sie können sich dieses Feld wie bei einer Tabellenkalkulation vorstellen (siehe Abbildung 11.6). Abbildung 11.6 Ein zweidimensionales Array (4 Zeilen à 5 Spalten) ### 11.9.1 Mehrdimensionale Arrays initialisieren Werte bei mehrdimensionalen Arrays werden ähnlich übergeben wie bei einem eindimensionalen Array. Hier sehen Sie zum Beispiel eine Deklaration mit sofortiger Initialisierung von Werten: > /* 4 Zeilen 5 Spalten */ int Matrix[4][5] = { {10,20,30,40,50}, {15,25,35,45,55}, {20,30,40,50,60}, {25,35,45,55,65}}; Dadurch ergibt sich die Belegung des Feldes, die Sie in Abbildung 11.7 sehen. Abbildung 11.7 Ein zweidimensionales Array, mit Werten initialisiert Wie bei den normalen Arrays lassen sich die einzelnen Elemente mithilfe des Feldindex initialisieren. Wollen Sie beispielsweise das Element mit dem Wert 60 in 100 ändern, dann geht das wie folgt: > Matrix[2][4] = 100; Hier wurde zum Beispiel der Inhalt von Matrix[2][4] verändert. Wollen Sie das Element mit dem Wert 65 in 66 umändern, dann wird folgender Feldindex verwendet: > Matrix[3][4] = 66; Eine weitere Möglichkeit zur Initialisierung von mehrdimensionalen Arrays ist folgende: > int Matrix[4][4] = { {0}, {1}, {0,1}, {0,0,1} }; Hiermit besitzen alle Feldelemente, die nicht ausdrücklich initialisiert wurden, automatisch den Wert 0. Die Belegung des Feldes sieht also so aus wie in Abbildung 11.8. Abbildung 11.8 Ein zweidimensionales Array (4 à 4) In der Praxis werden mehrdimensionale Arrays bei verschiedensten Arten von Berechnungen benötigt oder bei 2D-Darstellungen von Grafiken. Das folgende Programm demonstriert die Anwendung eines mehrdimensionalen Arrays: > /* md_array1.c */ #include <stdio.h> #include <stdlib.h> #define VOL1 3 /* Anzahl Felder erste Dimension - Zeilen */ #define VOL2 4 /* Anzahl Felder zweite Dimension - Spalten */ int main(void) { int i,j; int myarray[VOL1][VOL2]; /* [3][4] */ /* Eingabe der Array-Elemente */ for(i=0; i < VOL1; i++) { for(j=0; j < VOL2; j++) { printf("Wert für myarray[%d][%d]:", i, j); scanf("%d", &myarray[i][j]); } } printf("\nAusgabe von myarray[%d][%d]...\n\n", VOL1, VOL2); for(i=0; i < VOL1; i++) { for(j=0; j < VOL2; j++) { printf("\t%4d ",myarray[i][j]); } printf("\n\n"); } return EXIT_SUCCESS; } Das Programm tut nichts anderes, als den Anwender nach Ganzzahlen abzufragen, um diese Werte im zweidimensionalen Array zu speichern und wieder auszugeben. Um dies zu realisieren, wird eine äuÃere und innere for-Schleife verwendet. Die äuÃere for-Schleife dient dabei zur Inkrementierung der Variablen im linken Indizierungsoperator (oder, aus der Sicht einer Tabellenkalkulation, in der Zeile). Die innere for-Schleife inkrementiert den Wert im rechten Indizierungsoperator (und somit in der Spalte). Im nächsten Beispielprogramm soll ein kleines Zeitkonto für einen Arbeitgeber verwaltet werden. Damit sollen einige Arbeitszeitberechnungen durchgeführt werden. > /* md_array2.c */ #include <stdio.h> #include <stdlib.h> #define ARBEITER 3 #define TAGE 5 int zeitkonto[ARBEITER][TAGE]; /* Fehlerausgabe */ void error(int n) { printf("%d (?) Falsche Eingabe!!\n",n); } /* -1- Ausgabe der Wochenarbeitszeit je Arbeiter */ void ArbeiterWochenStunden(void) { int i,j,tmp; for(i=0; i < ARBEITER; i++) { tmp=0; printf("Wochenarbeitszeit von Arbeiter Nr. %d\n", i+1); printf("-------------------------------------\n"); for(j=0; j < TAGE; j++) { printf("|%d Std.", zeitkonto[i][j]); tmp += zeitkonto[i][j]; } printf("| = Ges. %d Std.\n\n",tmp); } } /* -2- Durchschnittszeiten pro Tag in der Woche je Arbeiter */ void ArbeiterTagesDurchschnitt(void) { int i,j,tmp; for(i=0; i < ARBEITER; i++) { tmp=0; printf("Durchschn. pro Tag/Woche Arbeiter: %d\n",i+1); printf("-------------------------------------------\n"); for(j=0; j < TAGE; j++) { tmp+=zeitkonto[i][j]; } printf("Durchschn. v. Arbeiter %d p. Tag: %.1f " "Std/Tag\n\n" , i+1, (float)tmp / TAGE); } } /* -3- Durchschnittszeit aller Arbeiter pro Tag */ void TeamTagesDurchschnitt(void) { int i,j,tmp; for(i=0; i < TAGE; i++) { tmp=0; printf("Durchschn. Arbeitszeit aller Mitarbeiter pro " "Tag %d = ", i+1); for(j=0; j < ARBEITER; j++) { tmp += zeitkonto[j][i]; } printf("%.1f Std.\n\n",(float)tmp/ARBEITER); } } /* -4- Gesamtstunden aller Arbeiter in der Woche */ void TeamWochenStunden(void) { int i, j, tmp=0; printf("Gesamtstunden aller Arbeiter in der Woche\n"); printf("-----------------------------------------\n"); for(i=0; i < ARBEITER; i++) { for(j=0; j < TAGE; j++) { tmp+=zeitkonto[i][j]; } } printf("Gesamtstunden aller Arbeiter i. d. Woche: " " %d Std.\n" , tmp); } /* Stundenübersicht eines einzelnen Arbeiters */ void ArbeiterStundenUebersicht(void) { int arb,tag; printf("Welcher Arbeiter: "); scanf("%d", &arb); printf("Welcher Tag: "); scanf("%d", &tag); if(arb > ARBEITER) { printf("Die Firma hat nur %d Arbeiter\n", ARBEITER); return; } else if(tag > TAGE) { printf("Es werden nur %d Tage gespeichert\n", TAGE); return; } printf("Arbeiter Nr.%d hat am Tag %d : ", arb, tag); printf("%d Stunden gearbeitet!\n\n", zeitkonto[arb-1][tag-1]); } int main(void) { int abfrage, i, j; for(i=0; i < TAGE; i++) { printf("\n\tTag %d in der Woche\n",i+1); printf("\t-------------------\n\n"); for(j=0; j < ARBEITER; j++) { printf("Arbeiter Nr.%d in Std.: ",j+1); scanf("%d",&zeitkonto[j][i]); if(zeitkonto[j][i] > 24) printf("Ein Tag hat nur 24 Stunden?\n"); } } do { printf("\n\n"); printf("\t-1- Stundenwoche\n"); printf("\t-2- Durchschnitt/Tag\n"); printf("\t-3- Durchschnitt aller Arbeiter/Tag\n"); printf("\t-4- Stunden aller Arbeiter/Woche\n"); printf("\t-5- Einzelauswahl eines Arbeiters\n"); printf("\t-6- ENDE\n"); printf("\n\tIhre Wahl : "); scanf("%1d",&abfrage); printf("\n"); switch(abfrage) { case 1 : ArbeiterWochenStunden(); break; case 2 : ArbeiterTagesDurchschnitt(); break; case 3 : TeamTagesDurchschnitt(); break; case 4 : TeamWochenStunden(); break; case 5 : ArbeiterStundenUebersicht(); break; case 6 : break; default : error(abfrage); } } while(abfrage != 6); return EXIT_SUCCESS; } Die Bildschirmausgabe des Programms könnte zum Beispiel so aussehen wie in Abbildung 11.9. Es fällt auf, dass die Funktionen immer in etwa gleich aufgebaut sind. Auf eine entsprechende korrekte Feldindexierung muss natürlich geachtet werden. In der Funktion ArbeiterStundenUebersicht() wird demonstriert, wie gezielt auf ein Element eines Arrays zugegriffen werden kann. Das Programm ist natürlich noch verbesserungswürdig. Warnungen, dass ein Arbeiter zu viel oder zu wenig arbeitet, die Information, ob ein Arbeiter krank war, oder die Anweisung, dass Stunden als Gleitpunktzahlen angegeben werden sollen, sind nur einige Vorschläge dazu. Abbildung 11.9 Die Stundenverwaltung des Personals in Aktion Tatsächlich sind Arrays zwar sehr komfortabel in der Anwendung, sie sind jedoch sehr unflexibel, was die Anzahl der Elemente angeht. Die Anzahl der Elemente muss zum Zeitpunkt der Implementierung schon festgelegt werden, da sich ein Feld nicht ohne Mehraufwand dynamisch zur Laufzeit des Programms vergröÃern oder verkleinern lässt. Das bedeutet, dass die Menge der im Array zu speichernden Daten schon vor Ablauf des Programms bekannt sein oder zumindest überdimensioniert werden muss. Wenn das Array im vorgestellten Beispiel für 1000 Mitarbeiter dimensioniert würde, wäre das Programm nicht mehr benutzbar, sobald mehr als 1000 Mitarbeiter verwaltet werden sollen. Eine Lösungsmöglichkeit besteht darin, das Array sehr groà zu dimensionieren, um von vornherein sehr groÃe Grenzen vorzugeben, etwa MitarbeiterArray[100000]. Dieser Ansatz kostet aber sehr viel (möglicherweise) ungenutzten Arbeitsspeicher, der das Programm unter Umständen stark verlangsamt. Da aus Performance-Gründen generell stets möglichst wenig Arbeitsspeicher von Programmen belegt werden soll, gelten Arrays bei groÃen Datenmengen oder bei stark wechselnder Anzahl der Daten als nicht so effizient wie etwa verkettete Listen. In Kapitel 21, »Dynamische Datenstrukturen«, gehe ich auf die Datenverwaltung mit verketteten Listen näher ein. # Tic Tac Toe Ein weiteres interessantes Beispiel zur Demonstration von zweidimensionalen Arrays ist das wohl allseits bekannte Spiel »Tic Tac Toe«. Sie benötigen dabei lediglich ein Kästchen von 3 à 3 Feldern. Dies lässt sich prima mit einem zweidimensionalen Array darstellen: Sie verwenden eine Dimension für die Reihe und eine weitere für die Spalte. > char TicTacToe[3][3] = { {' ',' ',' '}, {' ',' ',' '}, {' ',' ',' '} }; Ein kurze Beschreibung des Spiels: Ein Spieler hat das Zeichen X und ein anderer das Zeichen O. Nach einem Zug ist der andere Spieler an der Reihe. Gewonnen hat der Spieler, der zuerst drei gleiche Zeichen (X oder O) in der Waagerechten, in der Senkrechten oder in der Diagonalen hat. Es gibt insgesamt acht Stellungsmöglichkeiten, um das Spiel zu gewinnen. Diese gilt es zu überprüfen. Es gibt auÃerdem noch eine neunte Möglichkeit, nämlich die, dass alle Felder besetzt sind, aber keiner der beiden Spieler gewonnen hat. Hier ist der vollständige Quellcode dazu: > /* tictactoe.c */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ #define clrscr() printf("\x1B[2J") #elif __BORLANDC__ && __MSDOS__ #include <conio.h> #elif __WIN32__ || _MSC_VER #define clrscr() system("cls") #else #define clrscr() printf("clrscr() - Fehler!!\n") #endif #define X 'X' #define O 'O' #define LEER ' ' #define GAME_OVER 0 #define A_WINNER 1 #define CONTINUE 2 /* Inhalt des 3 x 3 groÃen Felds */ char TicTacToe[3][3] = { {' ',' ',' '}, {' ',' ',' '}, {' ',' ',' '} }; /* Spieler1 hat das Zeichen 'X'. */ char Spieler1 = X; /* Spieler2 hat das Zeichen 'O'. */ char Spieler2 = O; /* Anzahl der Felder, die besetzt werden können */ unsigned int felder = 9; /* Funktionsprototypen */ void print_spielfeld(void); char neuer_zug(char); int if_win(void); /* Gibt den aktuellen Zustand des Spielfelds aus. */ void print_spielfeld(void) { int i; clrscr(); printf(" 1 2 3 \n +---+---+---+\n"); for(i = 0; i < 3; i++) { printf(" %d | ",i+1); printf("%c",TicTacToe[i][0]); printf(" | "); printf("%c",TicTacToe[i][1]); printf(" | "); printf("%c",TicTacToe[i][2]); printf(" | \n"); if(i != 2) { printf(" +---+---+---+\n"); } else { printf(" +---+---+---+\n"); } } } /* Führt einen neuen Zug aus. * char ch: Zeichen des Spielers, der an der Reihe ist, 'X' * oder 'O' * Rückgabewert: Zeichen des Spielers, der eben an der Reihe war. * Falls ein Feld besetzt ist, wird der Rückgabewert vertauscht, * damit der aktuelle Spieler nochmals seinen Zug machen kann. * Hat ein Spieler gewonnen, gibt die Funktion die * symbolische Konstante GAME_OVER zurück. */ char neuer_zug(char ch) { unsigned int row, colum; printf("\nSpieler \"%c\" ist an der Reihe\n\n",ch); printf("Zeile (1-3): "); scanf("%u",&row); printf("Spalte (1-3): "); scanf("%u",&colum); if(TicTacToe[row-1][colum-1] == LEER) { /* Zeichen in das mehrdimensionale Array */ TicTacToe[row-1][colum-1] = ch; print_spielfeld(); /* Haben wir schon einen Gewinner? */ if(if_win() == A_WINNER) return GAME_OVER; } else { /* Ein bereits besetztes Feld */ print_spielfeld(); printf("\n!!! Feld ist bereits gesetzt !!!\n"); return (ch == X) ?O :X; } /* Sind bereits alle Felder besetzt? */ if(--felder > 0) return ch; else { printf("\nAlle Felder sind besetzt - Unentschieden\n"); return GAME_OVER; } } /* Auswertung aller Möglichkeiten, um einen Gewinner zu ermitteln. * Rückgabewert: symb. Konstante A_WINNER, falls ein Gewinner * ermittelt wurde, oder die symbolische Konstante CONTINUE zum * Weiterspielen */ int if_win(void) { /* Zuerst Spieler1 'X' */ if(TicTacToe[0][0] == Spieler1 && TicTacToe[0][1] == Spieler1 && TicTacToe[0][2] == Spieler1 || TicTacToe[1][0] == Spieler1 && TicTacToe[1][1] == Spieler1 && TicTacToe[1][2] == Spieler1 || TicTacToe[2][0] == Spieler1 && TicTacToe[2][1] == Spieler1 && TicTacToe[2][2] == Spieler1 || TicTacToe[0][0] == Spieler1 && TicTacToe[1][0] == Spieler1 && TicTacToe[2][0] == Spieler1 || TicTacToe[0][1] == Spieler1 && TicTacToe[1][1] == Spieler1 && TicTacToe[2][1] == Spieler1 || TicTacToe[0][2] == Spieler1 && TicTacToe[1][2] == Spieler1 && TicTacToe[2][2] == Spieler1 || TicTacToe[0][0] == Spieler1 && TicTacToe[1][1] == Spieler1 && TicTacToe[2][2] == Spieler1 || TicTacToe[0][2] == Spieler1 && TicTacToe[1][1] == Spieler1 && TicTacToe[2][0] == Spieler1) { printf("Spieler1 hat gewonnen\n"); return A_WINNER; } /* Jetzt Spieler2 'O' */ else if( TicTacToe[0][0] == Spieler2 && TicTacToe[0][1] == Spieler2 && TicTacToe[0][2] == Spieler2 || TicTacToe[1][0] == Spieler2 && TicTacToe[1][1] == Spieler2 && TicTacToe[1][2] == Spieler2 || TicTacToe[2][0] == Spieler2 && TicTacToe[2][1] == Spieler2 && TicTacToe[2][2] == Spieler2 || TicTacToe[0][0] == Spieler2 && TicTacToe[1][0] == Spieler2 && TicTacToe[2][0] == Spieler2 || TicTacToe[0][1] == Spieler2 && TicTacToe[1][1] == Spieler2 && TicTacToe[2][1] == Spieler2 || TicTacToe[0][2] == Spieler2 && TicTacToe[1][2] == Spieler2 && TicTacToe[2][2] == Spieler2 || TicTacToe[0][0] == Spieler2 && TicTacToe[1][1] == Spieler2 && TicTacToe[2][2] == Spieler2 || TicTacToe[0][2] == Spieler2 && TicTacToe[1][1] == Spieler2 && TicTacToe[2][0] == Spieler2) { printf("Spieler2 hat gewonnen\n"); return A_WINNER; } return CONTINUE; } int main(void) { char check = X; /* Leeres Spielfeld ausgeben */ print_spielfeld(); do { /* War Spieler mit dem Zeichen 'X' gerade dran ... */ /* ... dann ist jetzt Spieler mit dem Zeichen 'O' dran ...*/ if(check==X) { check=neuer_zug(O); } else { /* ... ansonsten der Spieler mit dem Zeichen 'X'. */ check=neuer_zug(X); } } while( check != GAME_OVER ); return EXIT_SUCCESS; } Abbildung 11.10 Das Spiel »Tic Tac Toe« für die Konsole Wenn Sie jetzt noch Lust und viel Zeit haben, können Sie sich ja hinsetzen und eine Funktion basteln, um gegen den Computer antreten zu können, also eine eigene KI programmieren. Dabei können Sie so ähnlich vorgehen wie bei der Funktion if_win(). Künstliche Intelligenz | | --- | | # Dreidimensionale Arrays Zur Veranschaulichung folgt hier ein Beispiel dafür, wie ein dreidimensionales Array direkt mit Werten initialisiert werden kann: > int dreid[2][3][4]={{{6,7,4,3},{6,4,6,9},{3,4,6,7}}, {{7,8,6,4},{5,99,3,5},{4,6,7,8}}}; Hier ist eine geschweifte Klammer hinzugekommen: > int dreid[][][]= {1.Feldindex{2.Feldindex{3.Feldindex}}}; Wenn zum Beispiel auf die erste Zahl zugegriffen werden soll, geschieht das folgendermaÃen: > dreid[0][0][0] /* erste Zahl 6 */ Auf die Zahl 99 greifen Sie so zu: > dreid[1][1][1] /* die Zahl 99 */ Ein Beispiel dazu erspare ich mir, da Sie in der Regel selten mit einem solchen Array zu tun haben. AuÃerdem lässt sich ein dreidimensionales Array nur recht schwer vorstellen. ### 11.9.2 Ãbergabe von zwei- bzw. mehrdimensionalen Arrays an Funktionen Unschön an den vorangegangenen Beispielen mit den zweidimensionalen Arrays war, dass der Speicher immer global definiert wurde. Allerdings ist es auch hier immer ein wenig verwirrend, wenn man ein zweidimensionales Array an eine Funktion übergeben will – da ein zweidimensionales Array (oder auch Array auf Array) in einen Zeiger auf Arrays zerfällt – und nicht, wie man vielleicht vermuten würde, in einen Zeiger auf einem Zeiger! Wollen Sie also ein zweidimensionales Array wie folgt an eine Funktion übergeben: > int val[ZEILE][SPALTE]; function(val); dann sollte die Funktion so aussehen: > /* 1. Möglichkeit : * automatische Umsetzung, wird vom Compiler vorgenommen */ void function( int feld[][SPALTE] ) { ... } // ODER : /* 2. Möglichkeit: * explizite Umsetzung */ void function( int (*ptr)[SPALTE] ) { /* ptr ist ein Zeiger auf das Array der Länge SPALTE */ ... } Da eine aufgerufene Funktion keinen Speicher für ein Array bereitstellt, muss die gesamte GröÃe des Arrays (erste Dimension) nicht angegeben werden – weshalb hier die (Dimension) Zeile weggefallen ist. Allerdings müssen die weiteren Dimensionen (zweite, dritte etc.), wie im Beispiel mit SPALTE, immer mit angegeben werden. Hierzu zeige ich noch ein einfaches Beispiel, das demonstriert, wie Sie ein zweidimensionales Array an eine Funktion übergeben können: > /* md_array3.c */ #include <stdio.h> #include <stdlib.h> #define DIM1 5 #define DIM2 5 void function(int feld[][DIM2], int dim1) { int i, j; for(i = 0; i < dim1; i++) { for(j = 0; j < DIM2; j++) { printf("%d; ", feld[i][j]); } printf("\n"); } printf("\n"); } int main(void) { int val[DIM1][DIM2]; int i, j; for(i = 0; i < DIM1; i++) for(j = 0; j < DIM2; j++) val[i][j] = i+j; function(val, DIM1); return EXIT_SUCCESS; } # 11.10 Arrays in Tabellenkalkulation einlesen (*.CSV–Dateien) ## 11.10 Arrays in Tabellenkalkulation einlesen (*.CSV–Dateien) Kommaseparate Werte (CSV, engl. comma separate values) lassen sich sehr gut mithilfe von Arrays erstellen. Ich möchte Ihnen ein kurzes Beispiel dafür zeigen, wie mehrdimensionale Arrays in einer Tabellenkalkulation wie »Excel« oder »Kspread« eingelesen werden. Betrachten wir zuerst ein kleines Programm, das einen beliebigen Aktienstand der letzten vier Wochen bereitstellt: > /* md_array4.c */ #include <stdio.h> #include <stdlib.h> #define WOCHEN 4 #define TAGE 7 float stand[WOCHEN][TAGE] = { { 12.3f,13.8f,14.1f,12.2f,15.4f,16.5f,14.3f }, { 15.4f,13.6f,13.6f,14.6f,15.6f,16.3f,19.5f }, { 20.5f,20.4f,21.5f,23.4f,21.4f,23.5f,25.7f }, { 25.5f,26.6f,24.3f,26.5f,26.9f,23.6f,25.4f } }; int main(void) { int i, j; printf("Tag;Montag;Dienstag;Mittwoch;Donnerstag; " "Freitag;Samstag;Sonntag"); for(i=0; i < WOCHEN; i++) { printf("\nWoche%d;",i); for(j=0;j < TAGE; j++) { printf("%.2f;",stand[i][j]); } } return EXIT_SUCCESS; } Die Kommata zwischen den einzelnen Elementen des Feldes stand sind wichtig für CSV-Dateien. Kompilieren Sie das Programm, und starten Sie es in der Kommandozeile mit: programmname > november.csv Damit wird die Ausgabe des Programms programmname in eine Datei namens november.csv umgeleitet, die auch gleich neu erstellt wird. Jetzt befindet sich im Verzeichnis eine CSV-Datei mit dem Namen november.csv und folgendem Inhalt: > Tag;Montag;Dienstag;Mittwoch;Donnerstag;Freitag;Samstag;Sonntag Woche0;12.30;13.80;14.10;12.20;15.40;16.50;14.30; Woche1;15.40;13.60;13.60;14.60;15.60;16.30;19.50; Woche2;20.50;20.40;21.50;23.40;21.40;23.50;25.70; Woche3;25.50;26.60;24.30;26.50;26.90;23.60;25.40; Starten Sie ein Tabellenkalkulationsprogramm wie Excel oder KSpread, und öffnen Sie die CSV-Datei damit. Die eingelesenen Werte sehen in Excel beispielsweise so aus, wie in Abbildung 11.11 gezeigt. Abbildung 11.11 Eine CSV-Datei, mit Excel geöffnet Dieses Thema wird nochmals ausführlicher in Kapitel 16, »Ein-/Ausgabe-Funktionen«, behandelt. # 11.11 Strings/Zeichenketten (»char«-Array) Date: 2011-11-01 Categories: Tags: ## 11.11 Strings/Zeichenketten (»char«-Array) Arrays vom Datentyp char werden Strings genannt. Ein String ist eine Kette von einzelnen char-Zeichen mit einer abschlieÃenden 0 (was nicht mit dem Zeichen '0' gleichzusetzen ist). char-Arrays sind typischerweise eindimensional. Viele Programmierer, die auf die Programmiersprache C stoÃen, sind verwundert, dass es keinen eigenen Datentyp für einen String gibt. Für ein char-Array gelten nicht nur die Einschränkungen der herkömmlichen Arrays, sondern es existiert auch das Problem der maximalen Länge von Arrays. Diese scheinbare Unflexibilität kann später, wenn sie effektiv eingesetzt wird, sehr ressourcensparend und schnell sein. Belassen Sie es aber erst einmal in den nächsten Kapiteln bei den etwas eingeschränkten char-Arrays. Mit dem char-Array können Zeichenfolgen dargestellt und verarbeitet werden. Damit können Sie Benutzerschnittstellen und Textdateien verarbeiten und erstellen. Eine Form der Stringkonstante wurde schon öfter in diesem Buch verwendet: > printf("Ich bin die Stringkonstante"); Generell lässt sich Folgendes sagen: Alles, was sich zwischen zwei Hochkommata befindet, gilt als Stringkonstante. Die Deklaration eines char-Arrays ist identisch mit der bisher bekannten Form der Array-Deklaration: > char string_array[100]; Im obigen Beispiel wird ein Array vom Datentyp char angelegt, das 100 einzelne Zeichen speichern kann. Dabei muss die GröÃe des Array-Feldes nicht mehr ausdrücklich mit angegeben werden: > const char hallo[] = { 'H', 'a', 'l', 'l', 'o', ' ', 'W', 'e', 'l', 't', '\n', '\0' }; Diese Schreibweise ist ebenfalls absolut korrekt, aber sehr umständlich. Daher können Sie ein char-Array auch anders, nämlich als einen String (dt. Zeichenkette), deklarieren: > const char hallo[] = { "<NAME>\n" }; Beide Variationen sind absolut gleichwertig. Abbildung 11.12 zeigt die rechnerinterne Darstellung des Strings. Abbildung 11.12 Der String »Hallo Welt« ist ein einfaches »char«-Array. Diese Zeichenkette benötigt zwölf Elemente (genauer: zwölf Bytes). Wenn Sie aber die Deklaration zu hallo[] genauer betrachten, werden Sie feststellen, dass hierfür eigentlich nur elf Zeichen erforderlich wären. Welche Bedeutung hat das zwölfte Zeichen? Bei einem String benötigen Sie immer ein Stringende-Zeichen, das das Ende eines Strings anzeigt. Das ist die Bedeutung des Zeichens '\0'. Das versehentliche Weglassen des Zeichens ist eine häufige Fehlerquelle, wenn beispielsweise Speicher für n Zeichen reserviert werden soll. Generell muss also bei einem Bedarf von n Zeichen immer für n+1 Zeichen Platz im Array reserviert werden. Hierzu ein kurzes Listing: > /* string1.c */ #include <stdio.h> #include <stdlib.h> char hello1[] = { "<NAME>\n" }; char output[] = { "Ich bin lesbar \0 Ich nicht mehr" }; char deznu[] = { "Mich siehst du 0 Mich und die Null auch" }; int main(void) { printf("%s",hello1); printf("%s\n",output); printf("%s\n",deznu); return EXIT_SUCCESS; } Dieses Beispiel zeigt auch, wie Sie für die formatierte Ausgabe von Zeichenketten die Formatangabe %s verwenden können (s = String). Daher benötigt ein String ein Ende-Kennungszeichen. Bei dem String > char output[] = {"Ich bin lesbar \0 Ich nicht mehr"}; werden nur die Zeichen bis '\0' angezeigt. Der hintere Teil des Strings existiert nur im Arbeitsspeicher. Da zuvor das Zeichen für das Ende des Strings '\0' steht, wird dieser Teil nie auf dem Bildschirm ausgegeben. Im nächsten Beispiel > char deznu[] = {"Mich siehst du 0 Mich und die Null auch"}; wird der ganze String ausgegeben, weil das Zeichen '0' nicht gleichzusetzen ist mit dem Zeichen '\0'. Es wurde bereits erwähnt, dass es auch möglich ist, auf die einzelnen Zeichen eines Strings zuzugreifen. Wenn Sie einen String beispielsweise mithilfe einer for-Schleife auf seine Länge hin überprüfen wollen, prüfen Sie lediglich auf das Zeichen '\0'. Hier ein Beispiel dazu: > /* string2.c */ #include <stdio.h> #include <stdlib.h> char hello1[] = { "<NAME>" }; char output[] = { "Ich bin lesbar \0 Ich nicht mehr" }; char deznu[] = { "Mich siehst du 0 Mich und die Null auch" }; int main(void) { int i; printf("%c", output[0]); /* I */ printf("%c'", hello1[9]); /* t */ printf("%c ", deznu[5]); /* s */ printf("%c", hello1[7]); /* Gibt das Zeichen 'e' aus */ printf("%c", output[12]); /* a */ printf("%c", deznu[5]); /* s */ deznu[1] = 'y'; /* aus 'i' wird 'y' */ printf("%c\n", deznu[1]); /* y */ for(i=0; hello1[i] != '\0'; i++); printf("Länge von '%s' = %d Zeichen\n", hello1, i); for(i=0; output[i] != '\0'; i++); printf("Länge von '%s' = %d Zeichen\n", output, i); for(i=0; deznu[i] != '\0'; i++); printf("Länge von '%s' = %d Zeichen\n", deznu, i); return EXIT_SUCCESS; } Hier werden mit dem Feldindex einzelne Zeichen ausgegeben, genau wie bei den Arrays mit Zahlen. In diesem Fall wird der Text »It's easy« ausgegeben. Es ist natürlich auch möglich, den Inhalt zu verändern, etwa so wie in der Zeile > deznu[1] = 'y'; AnschlieÃend wird mit > for(i=0; hello1[i] != '\0'; i++); die Anzahl der Zeichen hochgezählt, die sich im String hello1[ ] ohne \0 befinden. Die Abbruchbedingung > hello1[i] != '\0'; ist so lange wahr, bis der Inhalt von hello1[i] == '\0' ist. In diesem Beispiel wäre das bei hello1[11]der Fall, da sich hier das Zeichen '\0' befindet. Beachten Sie hier, dass hinter der for-Schleife ein Semikolon steht. Es gibt in diesem Fall keinen Anweisungsblock zur for-Schleife. Hier wird die Variable i so lange hochgezählt, bis das Stringende-Zeichen '\0' erreicht wird. Gleiches gilt für die anderen beiden Strings. ### 11.11.1 Vom String zur Binärzahl Oben habe ich behauptet, dass es in C keine Datentypen gibt, die Zeichen darstellen können. Die Zeichen wurden mithilfe der ASCII-Code-Tabelle kodiert. Wie verhält sich dies jetzt mit der folgenden Stringkonstante? > char str[] = { "Hallo!\n" }; Wird dieser String in seine einzelnen Zeichen zerlegt, ergibt sich die Zeile: > /* gleichwertig zu "Hallo!\n" */ char str[] = { 'H', 'a', 'l', 'l', 'o', '!', '\n', '\0' }; Werden die einzelnen Zeichen jetzt anhand der ASCII-Code-Tabelle dekodiert, sieht der String schon anders aus: > char str[] = { 72, 97, 108, 108, 111, 33, 10, 0 }; Theoretisch könnten Sie den String auch so angeben und ausgeben lassen, wie das folgende Listing demonstriert: > /* string3.c */ #include <stdio.h> #include <stdlib.h> int main(void) { /* Hallo!\n ... */ char str[] = { 72, 97, 108, 108, 111, 33, 10, 0 }; printf("%s\n",str); return EXIT_SUCCESS; } Wenn Sie jetzt noch die einzelnen Werte in Binärzahlen umrechnen, können Sie den String aus der Sicht des Computers betrachten: > 0100100001100001011011000110110001101111001000010000101000000000 Diese Erklärung soll Ihnen nur zeigen, dass Zeichenketten nicht magischer sind als ganz normale Zahlen-Arrays und in gewisser Hinsicht auch solche sind. Sie wollen einen Beweis? Bitte sehr: ``` /* string4.c */ #include <stdio.h> #include <stdlib.hint main(void) { int i; int str[] = { 72, 97, 108, 108, 111, 33, 10, 0 }; for(i = 0; i < sizeof(str) / sizeof(int); i++) printf("%c", str[i]); return EXIT_SUCCESS; } ``` Ein kleines Programm demonstriert im Folgenden den Umgang mit Strings. Das Programm durchläuft eine Zeichenkette und wandelt alle Stringfolgen "und" in GroÃbuchstaben um: > /* string5.c */ #include <stdio.h> #include <stdlib.h> char undbig[] = { "Hund und Katze sind nicht ohne " "Grund des Menschen beste Freunde\n" }; int main(void) { int i; for(i=0; undbig[i] != '\0'; i++) { if(undbig[i-1]==' '&& (undbig[i]=='u' ||undbig[i]=='U')) { if(undbig[i+1]=='n'&&undbig[i+2]=='d'&&undbig[i+3]==' '){ undbig[i] = 'U'; /* n in GroÃbuchstaben konvertieren (N) */ undbig[i+1] -= 32; /* d in GroÃbuchstaben konvertieren (D) */ undbig[i+2] -= 32; } } } printf("%s", undbig); return EXIT_SUCCESS; } Zu Beginn des Programms sehen Sie, wie Sie eine Stringkonstante über mehrere Zeilen schreiben können: > char array[] = { "Eine Zeichenkette über" "2 Zeilen\n" }; /* Alternative */ char array[] = { "Eine Zeichenkette über \ 2 Zeilen"}; Beide Schreibweisen erfüllen den gleichen Zweck. Fahren wir mit der ersten for-Schleife des Programms fort: > for(i=0; undbig[i] != '\0'; i++) Hier wird der String zeichenweise durchlaufen, bis das Stringende-Zeichen '\0' gefunden wird. Bei der nächsten Anweisung > if(undbig[i-1] == ' ' && (undbig[i]=='u' || undbig[i]=='U')) wird überprüft, ob das Zeichen, bei dem sich der Feldindex gerade befindet, ein kleines 'u' oder ein groÃes 'U' und das Zeichen davor ein Whitespace-Zeichen (Leerzeichen) ist. Falls nicht, wird i in der for-Schleife um den Wert 1 inkrementiert. Wird ein 'u' oder 'U' gefunden, folgt die Ãberprüfung > if(undbig[i+1]=='n' && undbig[i+2]=='d' && undbig[i+3]==' ') daraufhin, ob die nächsten beiden Zeichen 'n' und 'd' sind und ob sich dahinter ebenfalls ein Whitespace-Zeichen befindet. Falls dies ebenso zutrifft, wurde eine Zeichenfolge "und" gefunden. Dann werden die einzelnen Zeichen geändert: > undbig[i] = 'U'; undbig[i+1] -= 32; /* 'n' - 32 */ undbig[i+2] -= 32; /* 'd' - 32 */ Sehen Sie sich zum besseren Verständnis auch die ASCII-Tabelle in Anhang A.2 an. Sehen Sie nach, welche Dezimalwerte die Zeichen 'n' und 'd' haben. In Dezimalwerten würden die Subtraktionen der Werte so aussehen: > 110-32=78 und 100-32=68 In der ASCII-Tabelle sind 'N' = 78 und 'D' = 68. # 11.12 Einlesen von Strings ## 11.12 Einlesen von Strings Die Verarbeitung von Strings ist nicht so leicht, wie Sie vielleicht zunächst vermuten würden. Sehen Sie sich zur Veranschaulichung folgendes Programm an: > /* string6.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char string[100]; printf("Geben Sie ein paar Wörter ein: "); scanf("%99s", &string[0]); printf("Ihre Eingabe: %s\n",string); return EXIT_SUCCESS; } Nehmen wir an, dass folgende Eingabe vorgenommen wurde: > Programmieren in C macht Spass Folgende Ausgabe bekommen Sie dabei auf dem Bildschirm zu sehen: Abbildung 11.13 Probleme beim Einlesen von Strings mit »scanf« Wo sind die restlichen Zeichen? Das Problem wird hier von der Funktion scanf() verursacht. Denn scanf() liest lediglich bis zum ersten Leerzeichen ein. Also wird eine andere Funktion zum (sicheren) Einlesen von Zeichenketten benötigt. Gut geeignet wäre die Funktion fgets(), die in Abschnitt 16.16 noch genauer erklärt wird. Kurz zur Syntax von fgets(): > #include <stdio.h> char *fgets(char *string,int anzahl_zeichen,FILE *stream); Diese Funktion soll jetzt gegen die Funktion scanf() im Programmbeispiel ausgetauscht werden: > /* string7.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char str[100]; printf("Geben Sie ein paar Wörter ein : "); fgets(str, 100, stdin); printf("Ihre Eingabe: %s\n",str); return EXIT_SUCCESS; } Bei diesem Beispiel werden mit fgets() vom Stream stdin maximal 100 Zeichen in das char-Array str eingelesen, beginnend mit der Anfangsadresse von str. Der Vorteil von fgets() ist dabei, dass mit dieser Funktion keine gefährlichen sogenannten Pufferüberläufe (Buffer-Overflows) passieren können. Sollten Sie in diesem Beispiel 120 Zeichen eingegeben haben, liest fgets() davon 98 sichtbare Zeichen plus Newline-Zeichen (\n) plus Stringende-Zeichen (\0) ein. fgets() hängt am Ende des Strings immer ein \n-Zeichen an. Zum Einlesen von Strings noch ein Programmbeispiel: > /* string8.c */ #include <stdio.h> #include <stdlib.h> /*Passwort*/ const char p[]= { "123xyz456" }; int check_passwort(char passw[]) { int i, n = sizeof(p) / sizeof(char); for(i=0; i < n; i++) if(passw[i] != p[i]) return 0; /* Falsches Passwort */ return 1; /* Richtiges Passwort */ } int main(void) { char Name[20], passwort[10]; printf("Login-Name : "); fgets(Name, 20, stdin); printf("Passwort : "); fgets(passwort, 10, stdin); if( check_passwort(passwort) == 1) printf("Willkommen im System %s\n",Name); else printf("Falsches Passwort! Systemzugriff verweigert.\n"); return EXIT_SUCCESS; } Hier haben Sie ein Programm für eine einfache Passwort-Abfrage, die innerhalb der Funktion check_passwort ausgeführt wird. Die Funktion durchläuft n Zeichen. Stimmen alle eingegebenen Zeichen überein, gibt die Funktion 1 zurück. Stimmt ein Zeichen nicht überein, beendet sich die Funktion mit dem Rückgabewert 0. In Kapitel 12, »Zeiger (Pointer)«, werden Sie noch mehr über Strings erfahren. # 11.13 Die Standard-Bibliothek <string.hDate: 2010-11-13 Categories: Tags: ## 11.13 Die Standard-Bibliothek <string.hIm weiteren Verlauf dieses Buchs werden Sie öfter Funktionen der Headerdatei <string.h> verwenden. Darin sind viele nützliche Funktionen enthalten, die die Arbeit mit Strings vereinfachen. Die Headerdatei <string.h> entspricht dem ANSI-C-Standard und dürfte somit im Lieferumfang der meisten Compiler vorhanden sein, sofern sie ANSI-C-kompatibel sind. ### 11.13.1 »strcat()« – Strings aneinanderhängen Um einen String an einen anderen zu hängen, können Sie die Funktion strcat() (string catenation) verwenden. > char *strcat(char *s1, const char *s2); Damit wird s2 an das Ende von s1 angehängt, wobei (logischerweise) das Stringende-Zeichen '\0' am Ende von String s1 überschrieben wird. Voraussetzung ist auch, dass der String s2 Platz in s1 hat. Abbildung 11.14 » strcat()« – zwei Strings aneinanderhängen Hier sehen Sie ein Beispiel zu strcat(): > /* stringcat.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char ziel[30] = "Hallo "; char name[20]; printf("Wie heissen Sie: "); fgets(name, 20, stdin); strcat(ziel, name); printf("%s",ziel); return EXIT_SUCCESS; } ### 11.13.2 »strchr()« – ein Zeichen im String suchen Wollen Sie in einem String nach einem bestimmten Zeichen suchen, eignet sich die Funktion strchr() (string char). Hier ist ihre Syntax: > char *strchr(const char *s, int ch); Diese Funktion gibt die Position im String s beim ersten Auftreten von ch zurück. Tritt das Zeichen ch nicht auf, wird NULL zurückgegeben. Ein Beispiel: > /* strchr.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str[] = "Ein String mit Worten"; printf("%s\n",strchr(str, (int)'W')); return EXIT_SUCCESS; } Hiermit wird ab dem Auftreten des Buchstabens 'W' der komplette String ausgegeben. ### 11.13.3 »strcmp()« – Strings vergleichen Für das lexikografische Vergleichen zweier Strings kann die Funktion strcmp() verwendet werden. Die Syntax lautet: > int strcmp(const char *s1, const char *s2); Sind beide Strings identisch, gibt diese Funktion 0 zurück. Ist der String s1 kleiner als s2, ist der Rückgabewert kleiner als 0; und ist s1 gröÃer als s2, dann ist der Rückgabewert gröÃer als 0. Ein Beispiel: > /* strcmp.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> void String_Vergleich(char s1[], char s2[]) { int ret = strcmp (s1, s2); if(ret == 0) printf("%s == %s\n", s1, s2); else printf("%s %c %s\n",s1,( (ret < 0) ?'<' :'>'), s2); } int main(void) { char str1[] = "aaa"; char str2[] = "aab"; char str3[] = "abb"; String_Vergleich(str1, str2); String_Vergleich(str1, str3); String_Vergleich(str3, str2); String_Vergleich(str1, str1); return EXIT_SUCCESS; } ### 11.13.4 »strcpy()« – einen String kopieren Wollen Sie einen String in einen adressierten char-Vektor kopieren, können Sie die Funktion strcpy() (string copy) nutzen. Die Syntax lautet: > char *strcpy(char *s1, const char *s2); Dass hierbei der String-Vektor s1 groà genug sein muss, versteht sich von selbst. Bitte beachten Sie dabei, dass das Ende-Zeichen '\0' auch Platz in s1 benötigt. Hierzu ein Beispiel: > /* strcpy.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char ziel_str[50]; char str1[] = "Das ist "; char str2[] = "ein "; char str3[] = "Teststring"; strcpy(ziel_str, str1); /* Ein umständliches Negativbeispiel */ strcpy(&ziel_str[8], str2); /* So ist es einfacher und sicherer */ strcat(ziel_str, str3); printf("%s\n",ziel_str); return EXIT_SUCCESS; } In diesem Beispiel haben Sie gesehen, dass es auch möglich ist, mit strcpy() Strings aneinanderzuhängen: strcpy(&ziel_str[8], str2); Nur ist das umständlich, und schlieÃlich gibt es dafür die Funktion strcat(). Beim Betrachten der Funktion strcpy() fällt auÃerdem auf, dass hierbei ebenfalls nicht überprüft wird, wie viele Zeichen in den Zielstring kopiert werden, mit denen wieder auf einen undefinierten Speicherbereich zugegriffen werden kann. Daher ist auch die Funktion strcpy() eine gefährliche Funktion, wenn diese falsch eingesetzt wird. Hierzu sei wieder auf den Abschnitt 27.1, »Buffer-Overflow (Speicherüberlauf)«, verwiesen. ### 11.13.5 »strcspn()« – einen Teilstring ermitteln Wollen Sie die Länge eines Teilstrings bis zum Auftreten eines bestimmten Zeichens ermitteln, eignet sich die Funktion strcspn(). Die Syntax lautet: > int strcspn(const char *s1, const char *s2); Sobald ein Zeichen, das in s2 angegeben wurde, im String s1 vorkommt, liefert diese Funktion die Position dazu zurück. Ein Beispiel: > /* strcspn.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char string[] = "Das ist ein Teststring"; int pos; pos = strcspn( string, "Ttg" ); printf("Erstes Auftreten von T, t oder g an Pos.: %d\n",pos); return EXIT_SUCCESS; } ### 11.13.6 »strlen()« – Länge eines Strings ermitteln Um die Länge eines Strings zu ermitteln, kann die Funktion strlen() (string length) eingesetzt werden. Die Syntax lautet: > size_t strlen(const char *s1); Damit wird die Länge des adressierten Strings s1 ohne das abschlieÃende Stringende-Zeichen zurückgegeben. Das Beispiel zu strlen(): > /* strlen.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char string[] = "Das ist ein Teststring"; size_t laenge; laenge = strlen(string); printf("Der String \"%s\" hat %d Zeichen\n",string, laenge); return EXIT_SUCCESS; } ### 11.13.7 »strncat()« – String mit n Zeichen aneinanderhängen strncat() ist die gleiche Funktion wie strcat(), nur dass hiermit n Zeichen angehängt werden. Die Syntax lautet: > char *strncat(char *s1, const char *s2, size_t n); Diese Funktion ist aus Sicherheitsgründen der Funktion strcat() vorzuziehen. Ein Beispiel: > /* strncat.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 15 int main(void) { char string[MAX] = "Hallo "; char puffer[20]; /* Vorhandenen Platz in string ermitteln */ size_t len = MAX - strlen(string)+1; printf("Ihr Name: "); fgets(puffer, 20, stdin); strncat(string, puffer, len); printf("%s",string); return EXIT_SUCCESS; } Damit ist sichergestellt, dass nicht mehr in einen undefinierten Speicherbereich geschrieben wird. ### 11.13.8 »strncmp()« – n Zeichen von zwei Strings miteinander vergleichen Diese Funktion arbeitet genauso wie die Funktion strcmp(), nur mit dem Unterschied, dass n Zeichen miteinander verglichen werden. Die Syntax lautet: > int strncmp(const char *s1, const char *s2, size_t n); Hiermit werden also die ersten n Zeichen von s1 und die ersten n Zeichen von s2 lexikografisch miteinander verglichen. Der Rückgabewert ist dabei derselbe wie schon bei strcmp(). Ein Beispiel: > /* strncmp.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str1[] = "aaaa"; char str2[] = "aabb"; int i; for(i = strlen(str1); i > 0; i--) { if(strncmp( str1, str2, i) != 0) printf("Die ersten %d Zeichen der Strings " "sind nicht gleich\n",i); else { printf("Ab Zeichen %d sind " "beide Strings gleich\n",i); /* Weitere Vergleiche sind nicht mehr nötig */ break; } } return EXIT_SUCCESS; } ### 11.13.9 »strncpy()« – String mit n Zeichen kopieren Die sicherere Alternative zur Funktion strcpy() lautet strncpy(), die n Zeichen kopiert. Der Ablauf der Funktion ist hingegen wieder derselbe wie bei strcpy(). Die Syntax lautet: > char *strncpy(char *s1, const char *s2, size_t n); Hier werden n Zeichen aus dem String s2 in den String s1 ohne das '\0'-Zeichen kopiert. Das Beispiel: > /* strncpy.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 20 int main(void) { char str1[MAX]; char str2[] = "Ein Teststring, der laenger" " als 20 Zeichen ist"; /* MAX-Zeichen in str1 kopieren */ strncpy(str1, str2, MAX-1); /* Wichtig, String am Ende terminieren !! */ str1[MAX-1] = '\0'; printf("%s\n",str1); return EXIT_SUCCESS; } ### 11.13.10 »strpbrk()« – nach dem Auftreten bestimmter Zeichen suchen Die Funktion strpbrk() arbeitet ähnlich wie strcspn(), nur dass hierbei nicht die Länge eines Teilstrings ermittelt wird, sondern das erste Auftreten eines Zeichens in einem String, das im Suchstring enthalten ist. Die Syntax lautet: > char *strpbrk( const char *s1, const char *s2); Ein Beispiel dazu: > /* strpbrk.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str1[]="Das ist ein Teststring"; char str2[]="ie"; printf("%s\n",strpbrk(str1, str2)); return EXIT_SUCCESS; } ### 11.13.11 »strrchr()« – das letzte Auftreten eines bestimmten Zeichens im String suchen Die Funktion strrchr() ähnelt der Funktion strchr(), nur dass hierbei das erste Auftreten des Zeichens von hinten, genauer gesagt des letzten Zeichens, ermittelt wird. Die Syntax lautet: > char *strrchr(const char *s, int ch); Die Funktion fgets() hängt beim Einlesen eines Strings immer das Newline-Zeichen am Ende an. Manchmal ist das nicht erwünscht. Wir suchen mit strrchr() danach und überschreiben diese Position mit dem '\0'-Zeichen: > /* strrchr.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char string[20]; char *ptr; printf("Eingabe machen: "); fgets(string, 20 , stdin); /* Zeiger auf die Adresse des Zeichens \n */ ptr = strrchr(string, '\n'); /* Zeichen mit \0 überschreiben */ *ptr = '\0'; printf("%s",string); return EXIT_SUCCESS; } ### 11.13.12 »strspn()« – das erste Auftreten eines Zeichens, das nicht vorkommt Die Funktion strspn() gibt die Position des ersten Auftretens eines Zeichens an, das nicht vorkommt. Die Syntax lautet: > int strspn(const char *s1, const char *s2); Ein Beispiel dazu: > /* strspn.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char string[] = "75301234-2123"; int pos = strspn(string, "0123456789"); printf("Position, welche keine Ziffer ist:"); printf(" %d\n",pos); /* 8 */ return EXIT_SUCCESS; } Dieses Beispiel liefert Ihnen die Position des Zeichens zurück, das keine Ziffer ist. ### 11.13.13 »strstr()« – einen String nach dem Auftreten eines Teilstrings durchsuchen Mit der Funktion strstr() können Sie einen String daraufhin untersuchen, ob ein bestimmter Teilstring auftritt. Die Syntax ist: > char *strstr(const char *s1, const char *s2); Damit wird der String s1 nach einem String mit der Teilfolge s2 ohne '\0' durchsucht. Ein Beispiel: > /* strstr.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char string[] = "Das ist ein Teststring"; char suchstring[] = "ein"; if( strstr(string, suchstring) != NULL) printf("Suchstring \"%s\" gefunden\n", suchstring); return EXIT_SUCCESS; } ### 11.13.14 »strtok()« – einen String anhand bestimmter Zeichen zerlegen Mit der Funktion strtok() können Sie einen String anhand von Tokens in einzelne Teilstrings zerlegen. Die Syntax sieht so aus: > char *strtok(char *s1, const char *s2); Damit wird der String s1 durch das Token getrennt, das sich in s2 befindet. Ein Token ist ein String, der keine Zeichen aus s2 enthält. Ein Beispiel: > /* strtok.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char string[] = "Ein Teststring mit mehreren Worten\n" "und mehreren Zeilen.\t Ende\n"; int i=1; char *ptr; ptr = strtok(string, "\n\t "); while(ptr != NULL) { printf("% d. Wort: %s\n",i++,ptr); ptr = strtok(NULL, "\n\t "); } return EXIT_SUCCESS; } Mit der Zeile > ptr = strtok(string, "\n\t "); würde nur das erste Wort anhand eines der Whitspace-Zeichen Newline, Tabulator oder Space getrennt werden. Der String wird jetzt von der Funktion strtok() zwischengespeichert. Wollen Sie jetzt den String mit weiteren Aufrufen zerlegen, müssen Sie NULL verwenden. > ptr = strtok(NULL, "\n\t "); Dabei gibt jeder Aufruf das Token zurück. Das jeweilige Trennzeichen wird dabei mit '\0' überschrieben. In diesem Beispiel ist die Schleife zu Ende, wenn strtok() den NULL-Zeiger zurückliefert. Allmählich ist es an der Zeit, dass Sie lernen, mit Zeigern zu arbeiten. Lesen Sie in Kapitel 12 weiter. # 12.2 Zeiger initialisieren ## 12.2 Zeiger initialisieren Hier beginnt eine gefährliche Operation. Wird im Programm ein Zeiger verwendet, der zuvor nicht initialisiert wurde, kann dies zu schwerwiegenden Fehlern führen – sogar bis zum Absturz eines Betriebssystems (bei 16-Bit-Systemen). Die Gefahr ist, dass bei einem Zeiger, der nicht mit einer gültigen Adresse initialisiert wurde und auf den jetzt zurückgegriffen werden soll, stattdessen einfach auf irgendeine Adresse im Arbeitsspeicher zurückgegriffen wird. Wenn sich in diesem Speicherbereich wichtige Daten oder Programme bei der Ausführung befinden, kommt es logischerweise zu Problemen. Um das Prinzip der Zeiger zu verstehen, müssen Sie nochmals zurück zu den normalen Datentypen springen, beispielsweise zu folgender Initialisierung: > int x = 5; Durch diese Initialisierung ergibt sich im Arbeitsspeicher folgendes Bild: Abbildung 12.1 Darstellung einer Variablen im Arbeitsspeicher Die Adresse ist eine erfundene Adresse im Arbeitsspeicher, auf die Sie keinen Einfluss haben. Diese wird vom System beim Start des Programms vergeben. Damit der Rechner weiÃ, von wo er den Wert einer Variablen auslesen soll, wird eine Adresse benötigt. Ebenso sieht es mit der Initialisierung einer Variablen aus, falls dieser ein Wert zugewiesen wird. Der Name einer Variablen ist der Name, den Sie bei der Deklaration selbst festgelegt haben. Der Wert 5 wurde zu Beginn des Programms definiert. Dieser Block oben hat eine SpeichergröÃe von vier Bytes (int = vier Bytes oder, auf 16-Bit-Systemen, zwei Bytes). Hundertprozentig stimmt diese Analyse eines Datentyps nicht. Es gibt noch einige weitere Attribute, die ein Datentyp besitzt, und zwar folgende: * Wann bekommt die Variable ihren Speicherplatz zugeordnet? (Das ist abhängig vom Schlüsselwort static oder auto.) * Wie lange bleibt der Speicherort dieser Variablen gültig? * Wer kann diesen Wert ändern bzw. abrufen? (Das ist abhängig vom Gültigkeitsbereich und von der Sichtbarkeit der Variablen: global, lokal, Schlüsselwort const.) * Wann wird die Variable gespeichert? (Das ist abhängig vom Schlüsselwort volatile.) Dies dient allerdings hier nur zur Information, denn die Dinge sollten jetzt nicht komplizierter gemacht werden, als sie sind. Benötigen Sie die Adresse einer Variablen im Arbeitsspeicher, dann kann diese mit dem Formatzeichen %p und dem Adressoperator & abgefragt und ausgegeben werden: > /* ptr1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int x = 5; printf("Die Adresse von x ist %p \n",&x); return EXIT_SUCCESS; } In diesem Beispiel wurde mithilfe des Adressoperators und des Formatzeichens %p die aktuelle Speicheradresse der Variablen x ausgegeben. Jetzt ist auch klar, warum scanf() eine Fehlermeldung ausgibt, wenn kein Adressoperator mit angegeben wird: > scanf("%d",x); /* Wohin damit ...??? */ Das wäre dasselbe, als wenn der Postbote einen Brief zustellen soll, auf dem sich keine Anschrift befindet. Der Brief wird niemals sein Ziel erreichen. Genauso läuft es in Ihrem PC ab, egal ob Sie jetzt ein Computerspiel spielen oder ein Textverarbeitungsprogramm verwenden. Jedes Speicherobjekt, das Sie definieren, hat eine Adresse, einen Namen und eine bestimmte SpeichergröÃe (je nach Datentyp). Der Wert ist der einzige dieser vier Angaben, der zur Laufzeit festgelegt oder verändert werden kann. Wie kann jetzt einem Zeiger die Adresse einer Variablen übergeben werden? Dies soll das folgende Beispiel demonstrieren: > /* ptr2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int abfrage; int Kapitel1 = 5; int Kapitel2 = 60; int Kapitel3 = 166; int Nachtrag = 233; int *Verzeichnis; /* Zeiger */ do { printf("\tINDEXREGISTER VOM BUCH\n"); printf("\t*******************************\n\n"); printf("\t-1- Kapitel 1\n"); printf("\t-2- Kapitel 2\n"); printf("\t-3- Kapitel 3\n"); printf("\t-4- Nachtrag\n"); printf("\t-5- Ende\n"); printf("\n"); printf("\tAuswahl : "); scanf("%d",&abfrage); printf("\tKapitel %d finden Sie auf ",abfrage); switch(abfrage) { case 1 : Verzeichnis =& Kapitel1; printf("Seite %d\n", *Verzeichnis); break; case 2 : Verzeichnis =& Kapitel2; printf("Seite %d\n", *Verzeichnis); break; case 3 : Verzeichnis =& Kapitel3; printf("Seite %d\n", *Verzeichnis); break; case 4 : Verzeichnis =& Nachtrag; printf("Seite %d\n", *Verzeichnis); break; default : printf("Seite ???\n"); break; } } while(abfrage < 5); return EXIT_SUCCESS; } Der Zeiger des Programms ist: > int *Verzeichnis; Hiermit wurde ein Zeiger mit dem Namen Verzeichnis deklariert. Bis zur switch-Verzweigung geschieht so weit nichts Neues. Aber dann finden Sie in der ersten case-Anweisung: Verzeichnis =& Kapitel1; Abbildung 12.2 Programm zur Verwendung der Zeiger in Aktion Damit wird dem Zeiger Verzeichnis die Adresse der Variablen Kapitel1 übergeben. Dies können Sie am Adressoperator & erkennen, der sich vor der Variablen Kapitel1 befindet. Falls Sie den Adressoperator vor der Variablen Kapitel1 vergessen, wird der Compiler das Programm nicht übersetzen, da ein Zeiger eine Adresse und nicht den Wert einer Variablen haben will. Zu diesem Beispiel folgt ein kleiner Ausschnitt, der verdeutlicht, was im Speicher alles geschieht: > int Kapitel1 = 5; int Kapitel2 = 60; int Kapitel3 = 166; int Nachtrag = 233; int *Verzeichnis; Abbildung 12.3 Darstellung im Arbeitsspeicher Zunächst erfolgt beispielsweise die Adressübergabe der Variablen Kapitel1 an den Zeiger Verzeichnis mit dem Adressoperator: > Verzeichnis =& Kapitel1; Abbildung 12.4 Der Zeiger verweist hier auf die Adresse der Variablen »Kapitel1«. Daran lässt sich erkennen, wie der Zeiger Verzeichnis die Adresse der Variablen Kapitel1 enthält. Ein wenig anders sieht es dann hiermit aus: > printf("Seite %d\n", *Verzeichnis); Hier kommt zum ersten Mal der Indirektionsoperator (*) ins Spiel. Dieser dereferenziert den Wert der Adresse, mit der der Zeiger zuvor mit > Verzeichnis =& Kapitel1; initialisiert wurde. Lassen Sie bei der Ausgabe einfach einmal den Indirektionsoperator weg: > printf("Seite %d\n", Verzeichnis); /* ohne ’*’ */ Ãbersetzen Sie dieses Programm erneut, und lassen Sie sich das Verzeichnis von Kapitel1 ausgeben. Es wird irgendeine Zahl ausgegeben, nur nicht die Zahl 5. Warum? Eine Umänderung der Zeile > printf("Seite %d\n", *Verzeichnis); in > printf("Adressen %p %p\n", *Verzeichnis, Kapitel1); zeigt mehr. Jetzt soll wieder das erste Kapitel bei der Abfrage verwendet werden. Danach müssten beide Male dieselben Adressen ausgegeben werden. Mit Verzeichnis =& Kapitel1 wurde doch nur die Adresse übergeben. Und im Zeiger selbst befindet sich auch nur die Adresse von Kapitel1. Ohne den Indirektionsoperator ist der Zeiger hier nutzlos. Nur mit diesem Operator können Sie auf den Inhalt einer Variablen mithilfe eines Zeigers zugreifen. Wenn Sie den Zeiger jetzt auf Kapitel3 (Verzeichnis =& Kapitel3) verweisen lassen, ergibt sich folgender Stand im Arbeitsspeicher: Abbildung 12.5 Der Zeiger verweist jetzt auf die Adresse von »Kapitel3«. Zum besseren Verständnis folgt dazu ein weiteres Programm, das die Verwendung von Zeigern detaillierter darstellen soll. Es ist ein lehrreiches Beispiel, und es lohnt sich, es zu studieren: > /* ptr3.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int x=5; int *y; printf("Adresse x=%p, Wert x=%d\n", &x, x); /* Führt bei manchen Systemen zum Programmabsturz, * ggf. auskommentieren. */ printf("Adresse *y=%p, Wert *y=%d(unsinn)\n", &y, *y); printf("\ny=&x;\n\n"); /* y hat jetzt die Adresse von x. */ y =& x; printf("Adresse x=%p, Wert x=%d\n", &x, x); printf("Adresse *y=%p, Wert *y=%d\n", &y, *y); printf("\nAdresse, auf die y zeigt, ist %p\n", y); printf("und das ist die Adresse von x = %p\n", &x); printf("\nACHTUNG!!!\n\n"); *y=10; printf("*y=10\n\n"); printf("Adresse x=%p, Wert x=%d\n", &x, x); printf("Adresse *y=%p, Wert *y=%d\n", &y, *y); printf("\nAdresse, auf die y zeigt, ist %p\n", y); printf("weiterhin die Adresse von x (%p)\n", &x); return EXIT_SUCCESS; } Abbildung 12.6 Die Ausgabe des Programms unter Linux Folgende Zeile dürfte Ihnen bei diesem Programm aufgefallen sein: > *y = 10; Hiermit wird der Wert der Variablen x dereferenziert. Mit dieser Dereferenzierung kann jederzeit auf den Wert der Variablen x zugegriffen werden. Dadurch kann mithilfe eines Zeigers der Inhalt der Variablen verändert werden, und zwar so, als würden Sie direkt darauf zugreifen. Die folgenden Abbildungen verdeutlichen den Verlauf. > int x = 5; int *y; Abbildung 12.7 Speicheradressierung der Variablen »x« und des Zeigers »y« > y =& x; Abbildung 12.8 Der Zeiger »y« verweist jetzt auf die Adresse von Variable »x«. > *y = 10; Abbildung 12.9 Dereferenzierung der Variablen »x« Somit gilt: Wenn Sie mit dem Indirektionsoperator den Wert einer Variablen auslesen können, dann kann damit auch die Variable verändert werden. Das Wichtigste ist, dass Sie verstehen, dass einem Zeiger kein Wert übergeben wird, sondern eine Adresse (ich wiederhole mich), um anschlieÃend mit dem Wert dieser Adresse zu arbeiten. Aber Achtung, das folgende Programm könnte böse Folgen haben: > /* ptr4.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int *y; *y=10; printf("Der Wert von *y ist %d\n", *y); return EXIT_SUCCESS; } Dem Zeiger y wurde hier zuvor keine gültige Adresse zugewiesen. Dies bedeutet, dass dem Zeiger y beim Start des Programms eine Adresse zur Verfügung steht, die durch ein zufälliges Bitmuster vom Linker erzeugt wurde. Das Programm kann theoretisch sogar korrekt ablaufen. Irgendwann kann (wird) es jedoch ein vollkommen falsches Ergebnis zurückliefern. Auch könnte es sein, dass auf einen Speicherbereich zugegriffen wird, der bereits Daten beinhaltet. Dies könnte zu erheblichen Problemen bei der Programmausführung bis hin zum Absturz führen. Solche Fehler können Sie vermeiden, indem Sie einen nicht verwendeten Zeiger mit NULL initialisieren und vor der Verwendung des Zeigers eine Ãberprüfung auf NULL durchführen. Der Wert oder genauer der Zeiger NULL ist meistens eine Konstante, die mit dem Wert 0 definiert ist: > #define NULL (void *)0 Einfach ausgedrückt handelt es sich bei diesem NULL-Zeiger um einen Ich-zeige-auf-keine-gültige-Adresse-Wert. Hier sehen Sie das Erwähnte in der Praxis: > /* ptr5.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int *y=NULL; /* Zeiger mit NULL initialisieren */ if(y == NULL) { printf("Der Zeiger besitzt keine gültige Adresse\n"); return EXIT_FAILURE; } else *y = 10; return EXIT_SUCCESS; } Ein Tipp zu einer sichereren Ãberprüfung von: > if(y == NULL) Es kann dabei schnell passieren, dass Sie statt einer Ãberprüfung auf NULL den Zeiger mit NULL initialisieren: > if(y = NULL) /* Fehler */ Mit folgender Ãberprüfung kann Ihnen dieser Fehler nicht mehr unterlaufen: > if(NULL == y) Denn sollten Sie NULL den Zeiger y zuweisen wollen, wird der Compiler das Programm nicht übersetzen, da dies rein syntaktisch falsch ist. Natürlich geht dies auch umgekehrt. Sie können einer normalen Variablen auch den Wert eines Zeigers übergeben, auf den dieser zeigt. Beispiel: > /* ptr6.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int *ptr; int var=10, tmp; /* ptr zeigt auf Adresse von var. */ ptr =& var; /* Variable tmp bekommt den Wert, den ptr dereferenziert. */ tmp = *ptr; /* tmp=10 */ *ptr = 100; /* Inhalt von var wird verändert var=100. */ if(var > 50) /* Ist var gröÃer als 50 ... ? */ var = tmp; /* ... wieder den alten Wert */ printf("var=%d\t*ptr=%d\n",var, *ptr); /* var=10 *ptr=10 */ return EXIT_SUCCESS; } Wichtig ist allerdings dabei, dass Sie den Indirektionsoperator verwenden. Denn dieser dereferenziert den Wert, auf den der Zeiger zeigt: > tmp = *ptr; /* tmp=10 */ Sollten Sie den Indirektionsoperator vergessen, lässt sich das Programm ohnehin nicht übersetzen, denn es würde ja versucht werden, der Variablen tmp eine Adresse zu übergeben. Hier ein schneller Ãberblick zum Zugriff und zur Dereferenzierung von Zeigern: > // Deklaration int *ptr; int var, var2; // Initialisieren: ptr bekommt die Adresse von var. ptr =& var; // Dereferenzierung : var bekommt den Wert 100 zugewiesen. *ptr=100; // var2 mit demselben Wert wie var initialisieren var2 = *ptr; *ptr+=100; // Dereferenzierung: var wird um 100 erhöht. (*ptr)++; // Dereferenzierung: var hat jetzt den Wert 201. (*ptr)--; // var hat wieder den Wert 200. ptr=&var2; // ptr zeigt auf var2. printf("%d", *ptr); // Gibt Wert von var2 aus. printf("%p", &ptr); // Gibt Adresse von ptr aus. printf("%p", ptr); // Gibt Adresse von var2 aus. Sicherlich sind Ihnen im Beispiel auch die Klammern bei den Zeilen > (*ptr)++; // Dereferenzierung: var hat jetzt den Wert 201. (*ptr)--; // var hat wieder den Wert 200. aufgefallen. Diese waren nötig, da die Operatoren ++ und -- einen höheren Rang haben als der Indirektionsoperator (*) (siehe Anhang A.1, »Rangfolge der Operatoren«). Wenn Sie diese Klammerung vergessen, kann das fatale Folgen haben. ### 12.2.1 SpeichergröÃe von Zeigern Ich komme bei der Speicherverwaltung zwar nochmals genauer auf dieses Thema zurück, aber es soll hier schon einmal kurz erwähnt werden. Die GröÃe eines Zeigers hängt nicht von dem Datentyp ab, auf den dieser verweist. Das ist schlieÃlich nicht notwendig, denn Zeiger sollen ja keine Werte, sondern Adressen speichern. Und zur Speicherung von Adressen werden in der Regel zwei oder vier Bytes benötigt. Der Beweis: > /* ptr7.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char *v; int *w; float *x; double *y; void *z; printf("%d\t %d\t %d\t %d\t %d \n", sizeof(v),sizeof(w), sizeof(x), sizeof(y), sizeof(z)); return EXIT_SUCCESS; } Zeiger auf 64-Bit-Architekturen | | --- | | Sicherlich stellt sich die Frage, warum man Zeiger dann überhaupt typisieren sollte, wenn der Speicherverbrauch immer gleich ist. Dies ist ziemlich wichtig in C. Nur dadurch lässt sich in C die Zeigerarithmetik realisieren. Denn nur durch das Wissen um die SpeichergröÃe des assoziierten Typs kann die Adresse des Vorgänger- oder Nachfolgeelementes berechnet werden. Darüber hinaus ermöglicht die Typisierung von Zeigern dem Compiler, Verletzungen der Typkompatibilität zu erkennen. # 12.3 Zeigerarithmetik ## 12.3 Zeigerarithmetik Folgende Rechenoperationen können mit einem Zeiger und auf dessen Adresse verwendet werden: * Ganzzahlwerte erhöhen * Ganzzahlwerte verringern * inkrementieren * dekrementieren Wenn Sie Folgendes eingeben würden: > int *ptr; int wert; ptr =& wert; ptr += 10; Auf welche Adresse zeigt dann der Zeiger ptr? 10 Bytes von der Variablen wert entfernt? Nein, ein Zeiger wird immer um den Wert der GröÃe des Datentyps erhöht bzw. heruntergezählt. Auf einem 32-Bit-System würde der Zeiger auf eine Stelle verweisen, die 40 Bytes von der Anfangsadresse der Variablen wert entfernt ist. Solch eine Erhöhung der Adresse ist ohnehin sehr gefährlich, da der Zeiger danach höchstwahrscheinlich nicht mehr auf einen reservierten Speicherbereich zeigt. Des Weiteren sind bei Verwendung eines Zeigers natürlich auch die Vergleichsoperatoren <, >, !=, ==, <= und => erlaubt. Die Verwendung ist aber hierbei nur sinnvoll, wenn die Zeiger auf Elemente eines Arrays zeigen. Zeiger können letztendlich auch auf andere Zeiger verweisen: > int *ptr1; int *ptr2; ptr1 = ptr2; In diesem Fall zeigen beide Zeiger auf dieselbe Adresse. Dies ist ein wenig verwirrend. Daher folgt ein kleines Beispiel dazu: > /* ptr8.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int wert=10; int *ptr1; int *ptr2; ptr1 = &wert; ptr2 = ptr1; printf("ptr1 verweist auf %p\n", ptr1); printf("Wert in %p ist %d\n\n", ptr1, *ptr1); printf("ptr2 verweist auf %p\n", ptr2); printf("Wert in %p ist %d\n\n", ptr2, *ptr2); printf("Adresse von ptr1 : %p\n", &ptr1); printf("Adresse von ptr2 : %p\n", &ptr2); printf("Adresse von wert : %p\n\n", &wert); printf("ptr1 [%p] -> [%p] = [%d]\n", &ptr1, ptr1, *ptr1); printf("ptr2 [%p] -> [%p] = [%d]\n", &ptr2, ptr2, *ptr2); return EXIT_SUCCESS; } Bei diesem Programm verweisen beide Zeiger auf denselben Wert (genauer gesagt auf dieselbe Adresse), nämlich auf die Adresse der Variablen wert. Mit ptr2 = ptr1 bekommt ptr2 dieselbe Adresse zugewiesen, auf die schon ptr1 zeigt. Auffällig ist hierbei auch, dass kein Adressoperator verwendet wird. Dieser wird nicht benötigt, da der Wert eines Zeigers schon eine Adresse ist und ein Zeiger auch einen Wert als Adresse erwartet. Würde jetzt > *ptr1 = 11; im Programm eingefügt, würde der Wert der Variablen wert auf 11 geändert, und somit wäre die Ausgabe des Programms immer 11. Falls Sie > wert = 20; schreiben, werden auch die beiden Zeiger (mit Verwendung des Dereferenzierungsoperators) 20 ausgeben, da die Zeiger ja weiterhin auf die Speicheradresse der Variablen wert zeigen. Abbildung 12.10 Ein Zeiger bekommt die Adresse eines anderen Zeigers. ### 12.4.1 Subtraktion zweier Zeiger In der Standard-Headerdatei <stddef.h> befindet sich ein primitiver Datentyp ptrdiff_t, der meist mit int deklariert ist. Dieser wird verwendet, um das Ergebnis aus der Subtraktion zweier Zeiger zurückzugeben. Diese Subtraktion wird verwendet, um zu berechnen, wie weit zwei Zeiger zum Beispiel in einem Vektorelement voneinander entfernt sind. Näheres über den Zusammenhang von Arrays bzw. Strings und Zeigern können Sie in Abschnitt 12.7 lesen. Hier sehen Sie ein einfaches Listing: > /* ptr9.c */ #include <stdio.h> #include <stddef.h> /* für ptrdiff_t */ #include <stdlib.h> int main(void) { char *ptr1, *ptr2; ptrdiff_t diff; /* Primitiver Datentyp */ char string[] = { "<NAME>\n" }; /* ptr2 auf Anfangsadresse von string */ ptr2 = string; /* ptr1 6 Bytes weiter von der Adresse ptr2 platzieren */ ptr1 = ptr2 + 6; /* Wie weit liegen beide Zeiger voneinander entfernt? */ diff = ptr1-ptr2; // Nach dem neuen C99-Standard können Sie die formatierte // Ausgabe auch mit dem Argumenttyp-Modifikator t für // ptrdiff_t verwenden, also %td anstatt %d. printf("Differenz der beiden Zeiger : %d Bytes\n",diff); printf("%s",ptr1); /* Welt */ printf("%s",ptr2); /* Hallo Welt */ return EXIT_SUCCESS; } Mit der Zeile > ptr1 = ptr2 + 6; lassen Sie den Zeiger ptr1 auf die Adresse string[6] zeigen. ptr2 zeigt hingegen weiterhin auf die Anfangsadresse des Strings (string[0]). Die Differenz dieser beiden Zeiger beträgt 6 Bytes, da diese so weit voneinander entfernt sind. # 12.5 Typensicherung bei der Dereferenzierung ## 12.5 Typensicherung bei der Dereferenzierung Zeiger sind in C streng typisiert. Sie können einen Zeiger vom Datentyp int nicht auf die Adresse eines double-Werts zeigen lassen, wie im folgenden Beispiel zu sehen ist: > /* ptr10.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int *int_ptr; double double_wert=999.999; int_ptr=&double_wert; printf("*int_ptr=%d double=%f\n", *int_ptr, double_wert); return EXIT_SUCCESS; } Die Ausgabe des Zeigers wird irgendwelchen Unsinn ergeben. Es ist aber auch möglich, die Typensicherung durch explizite Typumwandlung oder über einen void-Zeiger zu umgehen. Aber dazu später mehr. # 12.6 Zeiger als Funktionsparameter (call–by–reference) ## 12.6 Zeiger als Funktionsparameter (call–by–reference) Funktionen, die mit einem oder mehreren Parametern definiert werden und mit return einen Rückgabewert zurückliefern, haben wir bereits verwendet (call-by-value). Der Nachteil dieser Methode ist, dass bei jedem Aufruf erst einmal alle Parameter kopiert werden müssen, sodass diese Variablen der Funktion anschlieÃend als lokale Variablen zur Verfügung stehen. Betrachten Sie beispielsweise folgendes Programm: > /* ptr11.c */ #include <stdio.h> #include <stdlib.h> #define PI 3.141592f float kreisflaeche(float wert) { return (wert = wert * wert * PI); } int main(void) { float radius, flaeche; printf("Berechnung einer Kreisfläche!!\n\n"); printf("Bitte den Radius eingeben : "); scanf("%f", &radius); flaeche = kreisflaeche(radius); printf("\nDie Kreisfläche beträgt : %f\n", flaeche); return EXIT_SUCCESS; } In solch einem Fall bietet es sich an, statt der Variablen radius einfach nur die Adresse der Variablen als Argument zu übergeben. Die Ãbergabe von Adressen als Argument einer Funktion wird call-by-reference genannt. Das Prinzip sehen Sie im abgeänderten Programmbeispiel: > /* ptr12.c */ #include <stdio.h> #include <stdlib.h> #define PI 3.141592f void kreisflaeche(float *wert) { *wert = ( (*wert) * (*wert) * PI ); } int main(void) { float radius; printf("Berechnung einer Kreisfläche!!\n\n"); printf("Bitte den Radius eingeben : "); scanf("%f", &radius); /* Adresse von radius als Argument an kreisflaeche() */ kreisflaeche(&radius); printf("\nDie Kreisfläche beträgt : %f\n", radius); return EXIT_SUCCESS; } Statt einer Variablen als Argument wurde in diesem Beispiel einfach die Adresse der Variablen radius übergeben. Bildlich können Sie sich das Prinzip so vorstellen: > float radius; /* Wir geben einfach mal 5.5 ein */ Abbildung 12.11 Die Variable »radius« bekommt den Wert 5.5. > kreisflaeche(&radius); Abbildung 12.12 Adresse als Funktionsparameter (call-by-reference) > *wert = (*wert) * (*wert) * PI; Abbildung 12.13 In der Funktion wird mit der Referenz gerechnet. In diesem Beispiel übergeben Sie mit dem Funktionsaufruf > kreisflaeche(&radius); die Adresse der Variablen radius als Referenz an die Funktion: > void kreisflaeche(float *wert) In der Funktion kreisflaeche() befindet sich als Parameter ein Zeiger namens wert vom Typ float. Der Zeiger wert in der Funktion kreisflaeche() bekommt durch den Funktionsaufruf kreisflache(&radius) die Adresse der Variablen radius zugewiesen. Jetzt, da der Zeiger in der Funktion die Adresse kennt, kann mit dem Dereferenzierungsoperator, der ja auf den Wert von radius zeigt, gerechnet werden: > *wert= (*wert) * (*wert) * PI; Die Klammerung bei der Berechnung kann auch weggelassen werden. Sie dient der besseren Ãbersicht. Ohne den Dereferenzierungsoperator würde lediglich mit einer Adresse gerechnet werden. Die meisten Compiler geben ohnehin eine Fehlermeldung aus. Es wird Ihnen sicherlich aufgefallen sein, dass bei der Funktion keine Rückgabe mehr mit return erfolgt und der Rückgabetyp void ist. Das liegt daran, dass bei jeder Neuübersetzung des Programms jeder Variablen eine Adresse zugewiesen wird, die sich während der Laufzeit des Programms nicht mehr ändern lässt. Da die Funktion die Adresse der Variablen radius bekommt, wird auch in der Funktion der Wert dieser Variablen verändert. Weil hierbei mit der Variablen radius und dem Zeiger wert mit derselben Adresse gearbeitet wird, entfällt eine Rückgabe an den Aufrufer. ### 12.6.1 Zeiger als Rückgabewert Natürlich ist es auch möglich, einen Zeiger als Rückgabewert einer Funktion zu deklarieren, so wie das bei vielen Funktionen der Standard-Bibliothek gemacht wird. Funktionen, die mit einem Zeiger als Rückgabetyp deklariert sind, geben logischerweise auch nur die Anfangsadresse des Rückgabetyps zurück. Die Syntax dazu sieht folgendermaÃen aus: > Zeiger_Rückgabetyp *Funktionsname(Parameter) Das Verfahren mit Zeigern als Rückgabewert von Funktionen wird häufig bei Strings oder Strukturen verwendet und ist eine effiziente Methode, Datenobjekte aus einer Funktion zurückzugeben. Speziell bei Strings ist dies die einzige Möglichkeit, eine ganze Zeichenkette aus einer Funktion zurückzugeben. Natürlich ist sie es nicht wirklich. Tatsächlich wird ja nur die Anfangsadresse, also das erste Zeichen an den Aufrufer zurückgegeben. Hierzu ein recht einfaches Beispiel: > /* ptr13.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 255 char *eingabe(char *str) { char input[MAX]; printf("Bitte \"%s\" eingeben: ",str); fgets(input, MAX, stdin); return strtok(input, "\n"); } int main(void) { char *ptr; ptr = eingabe("Vorname"); printf("Hallo %s\n", ptr); ptr = eingabe("Nachname"); printf("%s, interssanter Nachname\n", ptr); return EXIT_SUCCESS; } Der Funktion eingabe() wird hierbei als Argument die Adresse eines Strings übergeben. In der Funktion werden Sie aufgefordert, einen Namen einzugeben. Die Anfangsadresse des Strings geben Sie mit folgender Zeile zurück: > return strtok(input, "\n"); Die Funktion strtok() liefert ja selbst als Rückgabewert einen char-Zeiger zurück. Da die Funktion fgets() beim Einlesen von der Standardeingabe das Newline-Zeichen mit einliest, haben Sie hierbei gleich zwei Fliegen mit einer Klappe geschlagen. Das Newline-Zeichen wird mit strtok() entfernt, und die Funktion liefert auch gleich die Anfangsadresse des Strings input als Rückgabewert zurück, den Sie direkt mit return weiterverwenden. Doch Vorsicht, Folgendes funktioniert nicht: > char *eingabe(char *str) { char input[MAX]; printf("Bitte \"%s\" eingeben: ", str); fgets(input, MAX, stdin); return input; } Normalerweise sollte hier der Compiler schon melden, dass etwas nicht stimmt. Spätestens aber dann, wenn Sie das Beispiel ausführen, werden Sie feststellen, dass anstatt des Strings, den Sie in der Funktion eingabe() eingegeben haben, nur Datenmüll ausgegeben wird. Wenn Sie die Geschichte mit den Funktionen und dem Stack (in Abschnitt 9.20.1, »Exkurs: Stack«) gelesen haben, wissen Sie, dass beim Aufruf einer Funktion ein Stack verwendet wird, auf dem alle benötigten Daten einer Funktion (die Parameter, die lokalen Variablen und die Rücksprungadresse) angelegt werden (die Rede ist vom Stack-Frame). Dieser Stack-Frame bleibt nun so lange bestehen, bis sich die Funktion wieder beendet. Die Funktion eingabe() gibt eben einen solchen Speicherbereich (lokales Feld) zurück, der sich ebenfalls auf diesem Stack-Frame befindet bzw. befand – und somit bei Beendigung der Funktion nicht mehr vorhanden ist. Wollen Sie also einen Zeiger auf einen Speicherbereich zurückgeben, haben Sie folgende Möglichkeiten. Sie verwenden * einen statischen Puffer (static), * einen beim Aufruf der Funktion als Argument übergebenen Puffer oder * einen mittels malloc() reservierten Speicher (siehe Kapitel 16, »Ein-/Ausgabe-Funktionen«). Das folgende Beispiel soll alle drei Möglichkeiten demonstrieren: > /* ptr14.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* Fehler: Funktion gibt die Adresse * einer lokalen Variablen zurück. */ char *test1(void){ char buffer[10]; strcpy(buffer, "testwert"); return buffer; } /* Möglichkeit1: Statische Variable */ char *test2(void){ static char buffer[10]; strcpy(buffer, "testwert"); return buffer; } /* Möglichkeit2: Speicher vom Heap verwenden */ char *test3(void){ char *buffer = (char *) malloc(10); strcpy(buffer, "testwert"); return buffer; } /* Möglichkeit3: Einen Zeiger als Argument übergeben */ char *test4(char *ptr){ char buffer[10]; ptr = buffer; strcpy(buffer, "testwert"); return ptr; } int main(void) { char *ptr; ptr = test1(); printf("test1: %s\n", ptr); // meistens Datenmüll ptr = test2(); printf("test2: %s\n", ptr); ptr = test3(); printf("test3: %s\n", ptr); test4(ptr); printf("test4: %s\n", ptr); return EXIT_SUCCESS; } # 12.7 Array und Zeiger ## 12.7 Array und Zeiger Um Irrtümer gleich zu vermeiden: Arrays und Zeiger sind nicht das Gleiche, auch wenn dies im Verlauf dieses Kapitels den Anschein hat. Ein Zeiger ist die Adresse einer Adresse, während ein Array-Name nur eine Adresse darstellt. Dieser Irrtum, dass Array und Zeiger dasselbe sind, beruht häufig darauf, dass Array- und Zeigerdeklarationen als formale Parameter einer Funktion austauschbar sind, weil hierbei (und nur hierbei) ein Array in einen Zeiger zerfällt. Diese automatische »Vereinfachung« erschwert einem Anfänger das Verständnis jedoch. Weiterhin verstärkt wird dieses Missverständnis, wenn ein Zeiger auf einem Speicherblock, der mit malloc() dynamisch Speicher reserviert, wie ein Array verwendet wird (da der Speicherblock auch mit [] verwendet werden kann). Zuerst folgt ein Beispiel, wie mit Zeigern auf ein Array zugegriffen werden kann: > /* arr_ptr1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int element[8]= { 1, 2, 4, 8, 16, 32, 64, 128 }; int *ptr; int i; ptr = element; printf("Der Wert, auf den *ptr zeigt, ist %d\n", *ptr); printf("Durch *ptr+1 zeigt er jetzt auf %d\n", *(ptr+1)); printf("*(ptr+3) = %d\n", *(ptr+3)); printf("\nJetzt alle zusammen : \n"); for(i=0; i<8; i++) printf("element[%d]=%d \n", i, *(ptr+i)); return EXIT_SUCCESS; } Durch die Anweisung > ptr = element; wird dem Zeiger ptr die Adresse des Arrays element übergeben. Dies funktioniert ohne den Adressoperator, da laut ANSI-C-Standard der Array-Name immer als Zeiger auf das erste Array-Element angesehen wird. Hier sind der Beweis und das Beispiel dazu: > /* arr_ptr2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int element[8] = { 1, 2, 4, 8, 16, 32, 64, 128 }; int i; printf("*element = %d\n", *element); printf("*(element+1) = %d\n", *(element+1)); printf("*(element+3) = %d\n", *(element+3)); printf("\nJetzt alle zusammen : \n"); for(i=0; i<8; i++) printf("*(element+%d) = %d \n", i, *(element+i)); return EXIT_SUCCESS; } Leider sind es aber exakt solche Programmbeispiele, durch die der Eindruck entsteht, Arrays und Zeiger seien gleichwertig. Warum dies nicht so ist, habe ich bereits am Anfang erklärt. Wenn Sie in dem eben gezeigten Beispiel unbedingt einen Adressoperator verwenden wollen, können Sie dies auch so schreiben: > ptr =& element[0]; /* identisch zu ptr=element */ Auf beide Arten wird dem Zeiger die Anfangsadresse des ersten Elements vom Array mit dem Index [0] übergeben. Der Verlauf des Programms soll jetzt genauer analysiert werden. > *(ptr+1); Mit dieser Anweisung wird aus dem Array element der Wert 2 ausgegeben, also element[1]. Wieso dies so ist, möchte ich Ihnen wieder anhand einiger Grafiken veranschaulichen. > int *ptr; ... int element[8] = { 1, 2, 4, 8, 16, 32, 64, 128 }; Abbildung 12.14 Visuelle Darstellung des Zeigers und des Arrays im Speicher Das Array hat die Speicheradresse 0022FF60 bis 0022FF7C und eine GesamtgröÃe von 32 Bytes (auf 16-Bit-Systemen: 16 Bytes). Ein Element hat die GröÃe von vier Bytes, da int vier Bytes groà ist (auf 32-Bit-Rechnern). Daher erfolgt auch die Adressierung immer in Vierer-Schritten. Durch die Anweisung > ptr = element /* oder */ ptr =& element[0] sieht es im Speicher folgendermaÃen aus: Abbildung 12.15 Der Zeiger »ptr« verweist auf das erste Array-Element. Damit verweist der Zeiger auf das erste Element im Array (oder genauer: auf die Speicheradresse des ersten Elements). Danach wird mit > *(ptr+1); die Adresse 0022FF60 um vier Bytes erhöht. Genauso läuft dies auch mit den Arrays intern ab, wenn der Indexzähler erhöht wird. Damit der Zeiger tatsächlich auf die nächste Adresse zeigt, muss ptr+1 zwischen Klammern stehen, weil Klammern eine höhere Bindungskraft als der Dereferenzierungsoperator haben und somit zuerst ausgewertet werden. Sollten Sie die Klammern vergessen, würde nicht auf die nächste Adresse verwiesen, sondern auf den Wert, auf den der Zeiger ptr zeigt, und dieser wird um eins erhöht. Jetzt zeigt der Zeiger ptr durch *(ptr+1) auf: Abbildung 12.16 Die Adresse des Zeigers wurde erhöht. Somit wäre die Ausgabe 2. Kommen wir jetzt zur nächsten Anweisung: > *(ptr+3); Hiermit wird der Wert der Adresse auf 0022FF6C erhöht. Deshalb wird auch der Wert 8 ausgegeben: Abbildung 12.17 Nach einer weiteren Erhöhung der Adresse des Zeigers Um also auf das n-te Element eines Arrays zuzugreifen, haben Sie die folgenden Möglichkeiten: > int array[10]; // Deklaration int *pointer1, *pointer2; pointer1 = array; // pointer1 auf Anfangsadresse von array pointer2 = array + 3; // pointer2 auf 4.Element von array array[0] = 99; // array[0] pointer1[1] = 88; // array[1] *(pointer1+2) = 77; // array[2] *pointer2 = 66; // array[3] Dasselbe gilt auch für Funktionsaufrufe von Array-Namen. Einen Array-Parameter in Funktionen können Sie auf zwei Arten deklarieren: > int funktion(int elemente[]) // Gleichwertig mit ... int funktion(int *elemente) Also kann eine Funktion mit folgenden Argumenten aufgerufen werden: > int werte[] = { 1, 2, 3, 5, 8 }; int *pointer; pointer = werte; funktion(werte); // 1. Möglichkeit funktion(&werte[0]); // 2. Möglichkeit funktion(pointer); // 3. Möglichkeit Natürlich ist es auch möglich, die Adresse des n-ten Elements an eine Funktion zu übergeben: > funktion(&werte[2]); // Adresse vom 3.Element an funktion Hierzu ein kleines Beispiel: > /* arr_ptr3.c */ #include <stdio.h> #include <stdlib.h> void funktion(int *array, int n_array) { int i; for(i=0; i < n_array; i++) printf("%d ",array[i]); printf("\n"); } int main(void) { int werte[] = { 1, 2, 3, 5, 8, 13, 21 }; funktion(werte, sizeof(werte) / sizeof(int)); return EXIT_SUCCESS; } Wie sieht es aber mit dem Laufzeitverhalten aus? Was passiert, wenn die Funktion mit Feldindex verwendet wird? > void funktion(int array[], int n_array) Compiler optimieren den Code bei der Ãbersetzung in der Regel selbst. Die Umwandlung eines Feldindex in einen Zeiger macht dem Compiler heutzutage keine Probleme mehr. Somit dürfte es keine bemerkbaren Laufzeitverluste bei der Verwendung des Indizierungsoperators geben. # 12.8 Zeiger auf Strings ## 12.8 Zeiger auf Strings Alles, was bisher zu den Zeigern mit Arrays gesagt wurde, gilt auch für Zeiger auf Strings. Häufig wird dabei irrtümlicherweise von einem Zeiger gesprochen, der auf einen String verweist. Dieses Missverständnis entsteht durch folgende Deklaration: > char *string = "<NAME>"; Dies ist eine Stringkonstante, auf die ein Zeiger zeigt. Genauer: Der Zeiger zeigt auf die Anfangsadresse dieser Konstanten, den Buchstaben 'H' – genauer, auf die Adresse des Buchstabens 'H'. Hierzu ein Beispiel: > /* str_ptr1.c */ #include <stdio.h> #include <stdlib.h> void funktion(char *str) { printf("%s\n",str); } int main(void) { char *string = "<NAME>"; funktion(string); printf("Anfangsadresse auf die *string zeigt = %p\n",string); printf("Der Inhalt dieser Anfangsadresse = %c\n",*string); return EXIT_SUCCESS; } Wie diese Funktion hier werden übrigens alle ANSI-C-Funktionen deklariert, die Zeichenketten verarbeiten. All diese Funktionen (printf() zum Beispiel) bekommen als Argument nur die Anfangsadresse einer Zeichenkette übergeben. AnschlieÃend lesen diese Funktionen Zeichen für Zeichen aus, bis sie auf das Stringende-Zeichen '\0' treffen. Dabei dürfte Ihnen bei einem genaueren Blick auffallen, dass bei vielen Funktionen die Variablen-Parameter mit dem Schlüsselwort const deklariert sind. ### 12.8.1 Zeiger auf konstante Objekte (Read-only-Zeiger) Zeiger, die als Zusatz das Schlüsselwort const enthalten, sind sogenannte Read-only-Zeiger. Das bedeutet, dass auf diese Zeiger nur lesend zugegriffen werden kann. Angenommen, die Syntax von printf() ist in der Headerdatei <stdio.h> folgendermaÃen deklariert: > int printf (const char*, ...); Mit dieser Angabe kann aus dem Parameter der Funktion printf() nur gelesen werden. Es ist also nicht möglich, diesen Inhalt irgendwie mit einem anderen Zeiger zu manipulieren. Hierzu ein Beispiel: > /* const_ptr.c */ #include <stdio.h> #include <stdlib.h> void funktion1(char *str) { char *ptr; ptr = str+5; *ptr = '-'; } int main(void) { char string1[] = "<NAME>\n"; funktion1(string1); printf("%s\n",string1); return EXIT_SUCCESS; } Hier wird die Zeichenfolge Hallo Welt in der Funktion manipuliert. Zwischen Hallo und Welt wird in der Funktion ein Bindestrich eingefügt. Wollen Sie dies vermeiden, müssen Sie nur die Funktionsdeklaration ändern: > void funktion1(const char *str) Sie können jetzt zwar die einzelnen Inhalte der Zeichenkette lesen, aber nicht mehr in der Funktion ändern. AuÃerhalb der Funktion ist der Schreibschutz natürlich wieder aufgehoben. # 12.9 Zeiger auf Zeiger und Stringtabellen ## 12.9 Zeiger auf Zeiger und Stringtabellen »Zeiger auf Zeiger« sind ein recht schwieriges Thema, aber es zu verstehen, lohnt sich. Die Syntax von Zeigern auf Zeiger sieht so aus: > datentyp **bezeichner; Was heiÃt jetzt »Zeiger auf Zeiger« genau? Sie haben einen Zeiger, der auf einen Zeiger zeigt, der auf eine Variable zeigt, und auf diese Variable zurückgreifen kann. Im Fachjargon wird dabei von einer mehrfachen Indirektion gesprochen. Theoretisch ist es auch möglich, Zeiger auf Zeiger auf Zeiger usw. zu verwenden. In der Praxis machen allerdings solche mehrfachen Indirektionen kaum noch Sinn. Meistens verwenden Sie Zeiger auf Zeiger, also zwei Dimensionen. Das Haupteinsatzgebiet von Zeigern auf Zeiger ist die dynamische Erzeugung von mehrdimensionalen Arrays wie beispielsweise Matrizenberechnungen. Aber darauf gehe ich in Kapitel 14, »Dynamische Speicherverwaltung«, ein. Sehen wir uns zuerst ein Beispiel zu diesem komplexen Thema an: > /* ptrptr1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int wert = 10; /* ptr ist ein Zeiger auf int wert. */ int *ptr=&wert; /* ptr_ptr ist ein Zeiger auf den Zeiger int *ptr. */ int **ptr_ptr =& ptr; printf("*ptr : %d\n",*ptr); printf("**ptr_ptr : %d\n", **ptr_ptr); /* Verändert den Wert, auf den int *ptr zeigt. */ **ptr_ptr = 100; printf("*ptr : %d\n",*ptr); printf("**ptr_ptr : %d\n", **ptr_ptr); /* Verändert nochmals den Wert. */ *ptr = 200; printf("*ptr : %d\n",*ptr); printf("**ptr_ptr : %d\n", **ptr_ptr); return EXIT_SUCCESS; } Wichtig in diesem Beispiel ist, dass Sie bei der Veränderung der Variablen den doppelten Indirektionsoperator (**) einsetzen, genauso wie bei der Deklaration des Zeigers auf einen Zeiger. Hätten Sie nämlich anstatt > **ptr_ptr = 100; Folgendes geschrieben: > *ptr_ptr = 100; würde der Zeiger ptr_ptr auf die Speicheradresse 100 verweisen. Und dies ist zumeist irgendwo im Nirwana des Speichers. Wie gesagt, in Kapitel 14 wird dieses Thema nochmals aufgegriffen, und es wird Ihnen dort einiges sinnvoller erscheinen. ### 12.9.1 Stringtabellen Um es jetzt noch komplizierter zu machen, will ich gleich noch die Stringtabellen hinzunehmen, die den Zeigern auf Zeiger nicht unähnlich sind (aber nicht dasselbe sind!). Ein Beispiel: Folgende Stringkonstanten sollen nach Alphabet sortiert werden (ohne Verwendung der Headerdatei <string.h>): > "Zeppelin", "Auto", "Amerika", "Programmieren" Sie wissen ja noch, dass *ptr dieselbe Anfangsadresse wie ptr[0] repräsentiert. Und Gleiches gilt jetzt auch für: > **ptrptr und *ptrptr[0] Damit haben Sie ein Array von Zeigern. Und so würde dies im Beispiel aussehen: > char *sort[] = { "Zeppelin", "Auto", "Amerika", "Programmieren" }; Hier haben Sie eine sogenannte Stringtabelle. Wie kann jetzt auf die einzelnen Strings einer Stringtabelle zugegriffen werden? Dazu ein kleines Beispiel: > /* ptrptr2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char *sort[] = { "Zeppelin", "Auto", "Amerika", "Programmieren" }; printf("%s\n", sort[1]); /* Auto */ printf("%s ", (sort[2]+2)); /* erika */ printf("%s %s\n", (sort[0]+6), sort[2]); /* in Amerika */ printf("%.5s\n", (sort[3]+5-2)); /* gramm */ return EXIT_SUCCESS; } Abbildung 12.18 Verwendung einer Stringtabelle Der Zugriff auf die Stringtabelle erfolgt ähnlich wie bei den mehrdimensionalen Arrays. Die erste Ausgabe > printf("%s\n", sort[1]); gibt das Wort »Auto« auf dem Bildschirm aus. Daher kann davon ausgegangen werden, dass bei > sort[0] = "Zeppelin" sort[1] = "Auto" sort[2] = "Amerika" sort[3] = "Programmieren" mithilfe des Indizierungsoperators auf die Anfangsadressen der einzelnen Zeichenketten verwiesen wird. Mit der zweiten Anweisung > printf("%s ", (sort[2] + 2) ); wird der Name »erika« ausgegeben. Das lässt sich so erklären: sort[2] repräsentiert die Anfangsadresse von »Amerika« also »A«. Danach kommt +2 hinter dem Feldindex hinzu. Der Zeiger, der ohne +2 weiterhin auch auf den Anfang von »Amerika« gezeigt hätte, zeigt jetzt auf den dritten Buchstaben des Wortes, also auf »e«. Oder genauer: auf die Adresse von »e«. Mit dem Formatzeichen %s wird anschlieÃend veranlasst, dass der String von dieser Adresse an auf dem Bildschirm ausgegeben wird. Genauso verläuft dies bei der nächsten Ausgabe. Die Schreibweise > printf("%s\n", (sort[3] + 5 - 2) ); dient nur der Demonstration, dass es so auch geht. Natürlich lässt sich das leichter lesen mit: > printf("%s\n", (sort[3] + 3) ); Das Programm soll nochmals anhand von Adressen demonstriert werden: > /* ptrptr3.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char *sort[] = { "Zeppelin", "Auto", "Amerika", "Programmieren" }; printf("%p = %c\n", **sort, **sort); printf("%p = %c\n", *sort[0], *sort[0]); printf("%p = %c\n", *(sort[0]+0), *(sort[0]+0)); printf("%p = %s\n", sort[0], sort[0]); printf("%p = %s\n", *sort, *sort); printf("%p = %s\n", (sort[0]+1), (sort[0]+1)); printf("%p = %s\n", (sort[0]+2), (sort[0]+2)); printf("*sort = %p, **sort = %p\n", *sort, **sort); return EXIT_SUCCESS; } Abbildung 12.19 Ausgabe der Adressen einer Stringtabelle Bei den ersten drei Ausgaben > printf("%p = %c\n", **sort, **sort); printf("%p = %c\n", *sort[0], *sort[0]); printf("%p = %c\n", *(sort[0]+0), *(sort[0]+0)); wurden immer die (Anfangs-)Adressen und Inhalte verwendet, auf die der zweite Zeiger zeigt – was die Ausgabe auch bestätigt. AnschlieÃend wird nur die Adresse des ersten Zeigers benutzt: > printf("%p = %s\n", sort[0], sort[0]); printf("%p = %s\n", *sort, *sort); Der Inhalt ist bei Benutzung von einem Zeiger natürlich derselbe wie bei der Benutzung von zwei Zeigern. Aber bei der Ãbersetzung des Programms haben beide Zeiger eine andere Adresse. Die Ausgabe von > printf("*sort = %p, **sort = %p\n", *sort, **sort); bestätigt alles dies erneut. Jeder einzelne Zeiger benötigt also seinen Speicherplatz und somit auch eine eigene Adresse. Ich versuche, es noch einmal anders zu erklären: > *(* (Variable + x) +y) Hiermit wird auf das y-te Zeichen im x-ten String gezeigt. Bei dem Programm sieht dies so aus: > *(* (sort + 1) +2) oder auch – wie schon bekannt – so: > *( (sort[1]) +2) Hiermit würde auf das 3-te Zeichen im 2-ten String verwiesen, was hierbei dem Zeichen »t« vom String »Auto« entspricht. Jetzt soll diese Stringtabelle nach Alphabet sortiert werden. Dabei wird nicht die ganze Textzeile verlagert und unnötig hin- und herkopiert, sondern es müssen lediglich die Zeiger in die richtige Reihenfolge gebracht werden: > /* ptrptr4.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char *sort[] = { "Zeppelin", "Auto", "Amerika", "Programmieren" }; int i,j; char *temp; for(i = 0; i < 4; i++) { for(j = i + 1; j < 4; j++) { if( (strcmp(sort[i],sort[j]) > 0) ) { temp=sort[i]; sort[i]=sort[j]; sort[j]=temp; } } } for(i = 0; i < 4; i++) printf("%s\n", sort[i]); return EXIT_SUCCESS; } Bei diesem Sortieralgorithmus handelt es sich um »Selektion Sort«. Die folgenden Zeilen sortieren die Felder mit Zeigern: > for(i = 0; i < 4; i++) { for(j = i + 1; j < 4; j++) { if( (strcmp(sort[i],sort[j]) > 0) ) { temp=sort[i]; sort[i]=sort[j]; sort[j]=temp; } } } Zuerst wird das erste Element in der Stringtabelle mit allen anderen verglichen. So wird das kleinste Element gefunden, das an den Anfang gestellt wird. Danach wird das zweite Element mit allen vor ihm liegenden verglichen. Dies geht so weiter bis zum letzten Element in der Stringtabelle. Mehr zu den Algorithmen finden Sie in Kapitel 22. Das Wichtigste – wie schon mehrmals erwähnt wurde – ist, dass Zeiger für Adressen da sind und sonst nichts. Beispielsweise bedeutet > char *text[500]; nichts anderes als ein char-Array mit 500 char-Zeigern. Genauer gesagt, kann jeder dieser 500 Zeiger z. B. auf einen String (char-Array) zeigen. Beweis gefällig? Bitte sehr: > /* ptrptr5.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char *text[500]; char str1[] = "Text1"; char str2[] = "Text2"; char str3[] = "Text3"; text[0] = str1; text[1] = str2; text[2] = str3; printf("%s %s %s\n", text[0], text[1], text[2]); return EXIT_SUCCESS; } In diesem Beispiel wurde den ersten drei Zeigern jeweils die Anfangsadresse einer Stringkonstante übergeben. Mit einfachen Arrays war dies nicht ausführbar. Natürlich ist es jetzt noch nicht möglich, die Anfangsadresse eines zur Laufzeit erstellten Textes so zuzuweisen. Dazu brauchen Sie Kenntnisse in der dynamischen Speicherverwaltung. Als es darum ging, Strings zu sortieren, konnte mithilfe der Zeiger auf die Anfangsadresse der Strings wesentlich effektiver (schneller) sortiert werden, als wenn dies mit dem ganzen String gemacht würde. Dies rührt daher, dass ja nur Adressen auf einem String benutzt werden. Und anstatt > char *sort1 = "Zeppelin"; char *sort2 = "Auto" ; char *sort3 = "Amerika"; char *sort4 = "Programmieren"; zu schreiben, ist doch diese Schreibweise > char *sort[] = { "Zeppelin", "Auto", "Amerika", "Programmieren" }; viel effektiver und kürzer. Hier sind es vier Zeiger auf ein char-Array, die auf die Anfangsadresse eines jeden einzelnen Wortes zeigen. Folgende Vorteile ergeben sich für den Programmierer, wenn er Stringtabellen verwendet: * Mit Stringtabellen wird das Programm übersichtlicher. * Es wird Speicherplatz gespart. * Die Verwaltung von Stringtabellen ist einfacher und effizienter. * Sollte ein Programm in mehreren Sprachen geschrieben werden, kann dies leichter lokalisiert werden. Hier ein Beispiel, wie Sie Stringtabellen effektiv einsetzen können: > /* ptrptr6.c */ #include <stdio.h> #include <stdlib.h> #define ASK 0 #define WORDS 1 #define START 2 #define ENGLISH 1 #ifdef GERMAN const char *language[] = { "Du sprichst Deutsch?", "Einige Worte: ", "Feuer", "Erde", "Wasser", "Luft", "Leben", NULL }; #elif ENGLISH const char *language[] = { "Do you speak english?", "Some words: ", "Fire", "earth", "water", "air", "life", NULL }; #else /* FRENCH */ const char *language[] = { "Tu parle francais?", "quelques mots: ", "Le feu", "La terre", "de l'eau", "de l'air", "La vie", NULL }; #endif int main(void) { int i; printf("%s\n", language[ASK]); printf("%s\n",language[WORDS]); for(i = START; language[i] != NULL; i++) printf("\t%s,\n", language[i]); return EXIT_SUCCESS; } Hierbei handelt es sich um ein einfaches Listing, das mit bedingter Kompilierung ein Programm in entsprechender Sprache übersetzt. In diesem Beispiel wurde mit > #define ENGLISH 1 die Sprache auf Englisch eingestellt. Bei Ausgabe des Programms wird dies auch bestätigt. Müssen Sie jetzt eine Version für Ihren spanischen Kollegen schreiben, müssen Sie nur nach der Stringtabelle suchen und entsprechende Einträge übersetzen und hinzufügen. So entsteht ohne allzu groÃen Aufwand ein internationales Programm: > #ifdef GERMAN const char *language[] = { "Du sprichst Deutsch?", "Einige Worte: ", "Feuer", "Erde", "Wasser", "Luft", "Leben", NULL }; #elif ENGLISH const char *language[] = { "Do you speak english?", "Some words: ", "Fire", "earth", "water", "air", "life", NULL }; #elif FRENCH const char *language[] = { "Tu parle francais?", "quelques mots: ", "Le feu", "La terre", "de l'eau", "de l'air", "La vie", NULL }; #else /* ESPANOL */ const char *language[] = { "Habla Usted espanol", "algunas palabras: ", "Fuego", "tierra", "agua", "aire", "vida", NULL }; #endif Mit Stringtabellen lassen sich auch komfortabel Fehlermeldungen auf dem Bildschirm ausgeben: > char *fehlermeldung[] = { "Mangel an Speicherplatz", "Speicherbereichsüberschreitung", "Wertbereichsüberschreitung", "Die Syntax scheint falsch", "Zugriff verweigert - keine Rechte", "Zugriff verweigert - falsches Passwort", "Unbekannter Fehler trat auf" }; Zugegriffen wird auf die einzelnen Fehlermeldungen mit dem Feldindex von Nr.[0]-[6]. »Zugriff verweigert – keine Rechte« beispielsweise ist somit fehlermeldung[4]. Nach diesem Abschnitt über Zeiger auf Zeiger und den Stringtabellen kommen sicherlich jetzt die einen oder anderen Fragen auf. Vor allem wurden die Beispiele immer nur mit konstanten Werten gegeben. Um sich also wirklich effektiv und sinnvoll mit dem Thema auseinanderzusetzen, müssen Sie sich noch ein wenig gedulden, bis Sie zur (ich wiederhole mich) dynamischen Speicherverwaltung gelangen (Kapitel 14). # 12.10 Zeiger auf Funktionen ## 12.10 Zeiger auf Funktionen Mit den Zeigern können Sie auch auf Maschinencode von anderen Funktionen zeigen, die schlieÃlich ebenfalls eine Anfangsadresse im Speicher besitzen. Ein einfaches Beispiel dazu: > /* ptr_func1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int (*ptr) (const char*, ...); ptr=printf; (*ptr)("Hallo Welt\n"); return EXIT_SUCCESS; } Jetzt eine Erklärung zur folgenden Schreibweise: > int (*ptr)(const char*, ...); Dies ist ein Zeiger auf eine Funktion, die einen variablen, langen String erhält und einen int-Wert zurückgibt. Die Funktion printf() zum Beispiel ist eine solche Funktion: > int printf (const char*, ...); Daher bekommt der Zeiger die Adresse dieser Funktion mit folgender Anweisung: > ptr = printf; Jetzt können Sie die Funktion printf() mit dem Zeiger aufrufen: > (*ptr)("<NAME>\n"); Die erste Klammerung des Zeigers ptr ist wichtig. Würden Sie diese weglassen, dann würden Sie ptr als eine Funktion deklarieren, die einen int-Zeiger zurückgibt. Sie können den (Funktions-)Zeiger auch auf eine andere Funktion zeigen lassen, mit demselben Rückgabewert und dem- bzw. denselben Argument(en). Hier sehen Sie das Listing von eben mit weiteren Adressierungen: > /* ptr_func2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int (*ptr)(const char*, ...); int zahl; ptr=printf; (*ptr)("Bitte eine Zahl eingeben: "); ptr=scanf; (*ptr)("%d",&zahl); ptr=printf; (*ptr)("Die Zahl lautet %d\n",zahl); return EXIT_SUCCESS; } Dieses Beispiel sollte natürlich keine Schule machen und Ihnen nur zeigen, wie Sie mit Zeigern auf Funktionen zeigen können. Zeiger auf Funktionen können ganz nützlich sein. Sie können die Zeiger in einem Feld speichern und eine Sprungtabelle daraus machen. Damit ist gemeint, dass die einzelnen Funktionen mit einem Feldindex angesprochen werden können, ähnlich wie bei den Stringtabellen – also ein Array von Funktionen, wenn Sie so wollen. Dazu soll das Listing von eben wieder herhalten: > /* ptr_func3.c */ #include <stdio.h> #include <stdlib.h> #define INPUT 0 #define OUTPUT 1 int main(void) { int (*ptr[])(const char *, ...) = { scanf, printf }; int zahl; (*ptr[OUTPUT])("Bitte eine Zahl eingeben: "); (*ptr[INPUT])("%d",&zahl); (*ptr[OUTPUT])("Die Zahl lautet %d\n",zahl); return EXIT_SUCCESS; } Viel verändert hat sich hierbei nicht. Statt > int (*ptr)(const char*, ...); wurde hier einfach noch ein Indizierungsoperator hinzugefügt. Am Ende befinden sich zwischen den geschweiften Klammern noch die einzelnen Funktionen, auf die Sie im Programm mithilfe des Indizierungsoperators und dem entsprechenden Index zurückgreifen können: > int (*ptr[])(const char *, ...) = { scanf, printf }; In diesem Beispiel zeigt (*ptr[0]) auf die Adresse der Funktion scanf(), und (*ptr[1]) zeigt auf die Funktion printf(). Im Programm wurden hierbei symbolische Konstanten verwendet, um diese beiden Funktionen besser auseinanderzuhalten. Voraussetzung dafür, dass diese Zeiger auf Funktionen auch funktionieren, ist immer, dass der Rückgabewert (hier vom Typ int) und der/die Parameter der Funktion (hier (const char *, ...)) übereinstimmen. Sie können hierbei nicht einfach zusätzlich z. B. die Funktion fgets() zum Einlesen von Strings anhängen: > /* falsch */ int (*ptr[])(const char *, ...) = { scanf, printf, fgets }; Die Funktion fgets() erwartet andere Argumente, hier (const char *, ...). Wenn es möglich ist, mit Zeigern auf Funktionen der Standard-Bibliothek zu zeigen, dann ist es selbstverständlich auch möglich, mit Zeigern auf selbst geschriebene Funktionen zu zeigen. > /* ptr_func4.c */ #include <stdio.h> #include <stdlib.h> /* Bei Linux für math.h das Compiler-Flag -lm mit angeben: * gcc -o programm programm.c -lm */ #include <math.h> /* sqrt() */ int addition(int zahl) { int y; printf("%d+>", zahl); scanf("%d", &y); fflush(stdin); return zahl += y; } int subtraktion(int zahl) { int y; printf("%d->", zahl); scanf("%d", &y); fflush(stdin); return zahl -= y; } int division(int zahl) { int y; printf("%d/>",zahl); scanf("%d", &y); fflush(stdin); return zahl /= y; } int multiplikation(int zahl) { int y; printf("%d*>",zahl); scanf("%d", &y); fflush(stdin); return zahl *= y; } int sqrtw(int zahl) { double x=sqrt((double)zahl); printf("(sqrt)%f>", x); return (int)x; } int (*rechenfunk[]) (int) = { addition, subtraktion, division, multiplikation, sqrtw }; int main(void) { char op; static int zahl; printf("no.>"); scanf("%d",&zahl); do { printf(" op>"); scanf("%c",&op); fflush(stdin); switch(op) { case '+': printf("%d", zahl = (*rechenfunk[0])(zahl)); break; case '-': printf("%d", zahl = (*rechenfunk[1])(zahl)); break; case '/': printf("%d", zahl = (*rechenfunk[2])(zahl)); break; case '*': printf("%d", zahl = (*rechenfunk[3])(zahl)); break; case 'q': printf("%d", zahl = (*rechenfunk[4])(zahl)); break; default : printf("op '=','+','-','/','*','q'\n"); } } while(op != '='); printf("Gesamtergebnis=%d\n",zahl); return EXIT_SUCCESS; } Abbildung 12.20 Zeiger auf selbst geschriebene Funktionen Dieses Programm stellt einen kleinen Taschenrechner dar, der allerdings stark verbesserungswürdig ist. Es können fünf Rechenoperationen wie Addition, Subtraktion, Multiplikation, Division und die Quadratwurzel verwendet werden. Es wird so lange gerechnet, bis das =-Zeichen eingegeben wurde. Hierzu folgt ein kurzer Trocken-Durchlauf. Nachdem das Programm gestartet wurde, sollte auf dem Bildschirm Folgendes erscheinen: > no.Hier geben Sie die erste Zahl ein und drücken , beispielsweise die Zahl 8. AnschlieÃend geht es in der do while-Schleife weiter. Jetzt erscheint auf dem Bildschirm: > opHier muss der Rechenoperator eingegeben werden: entweder +, -, *, / oder q. In diesem Beispiel soll es eine Addition sein, also geben Sie das +-Zeichen ein und drücken . Danach wird das Zeichen im switch-Schalter darauf geprüft, ob es sich dabei um ein gültiges Zeichen handelt. In diesem Fall wäre das: > case '+': printf("%d", zahl = (*rechenfunk[0])(zahl)); Hiermit wird die Rechenfunktion mit dem Index [0] aufgerufen. Dieser Funktion wird als Parameter der Wert der Variablen zahl übergeben. Sehen Sie sich dazu die Funktionstabelle an: > int (*rechenfunk[]) (int) = { addition, subtraktion, division, multiplikation, sqrtw }; Die Rechenfunktion mit dem Index [0] ist die Funktion addition. subtraktion hat den Index [1], division den Index [2] usw. In der Funktion addition() geben Sie dann eine Zahl ein, mit der der übergebene Wert addiert werden soll, beispielsweise die Zahl 2, und anschlieÃend drücken Sie wieder : > 10 opJetzt kann ein weiterer Operator verwendet oder mit dem =-Zeichen das Programm beendet werden. # 12.11 void-Zeiger ## 12.11 void-Zeiger Ein Zeiger auf void ist ein typenloser und vielseitiger Zeiger. Wenn der Datentyp des Zeigers noch nicht feststeht, wird der void-Zeiger verwendet. void-Zeiger haben den Vorteil, dass Sie diesen eine beliebige Adresse zuweisen können. AuÃerdem kann ein void-Zeiger durch eine explizite Typumwandlung in jeden anderen beliebigen Datentyp umgewandelt werden. Beispielsweise: > /* void_ptr1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int a = 10; char *string = "void-Zeiger"; void *ptr; /* void-Zeiger auf Variable int a */ ptr = (int *)&a; printf("ptr = %p a=%p\n",ptr,&a); /* void-Zeiger auf string */ ptr = (char *)string; printf("ptr = %p string = %p\n",ptr,string); return EXIT_SUCCESS; } Natürlich sollten Sie darauf achten, dass Sie für das Casting einen Zeiger angeben und nicht etwa einen Datentyp: > /* Richtig */ ptr=(typ *)&ptr2; /* Falsch: typ ist kein Zeiger, sondern eine Variable */ ptr=(typ)&ptr2; Zwar wurde hier im Beispiel ein Cast von void * nach datentyp * gemacht, aber dies ist in C nicht unbedingt nötig – C++ allerdings macht sehr wohl einen Unterschied und braucht einen Cast von void * nach datentyp *. Würden Sie im Beispiel oben die Casts entfernen und das Beispiel als C++-Projekt übersetzen (was bei vielen Compilern unter MS-Windows häufig voreingestellt ist), würde der Compiler eine Warnung ausgeben, wie beispielsweise: > [Warning]: In function int main : invalid conversion from `void*' to ` int*` Und genau diese Warnmeldung lässt viele Programmierer vermuten, dass etwas am Listing falsch sei und man den void-Pointer immer casten müsste. Sofern Sie Ihren Compiler nicht davon überzeugen können, dass Sie gern ein C-Projekt schreiben würden, sollten Sie meiner Meinung nach dem sanften Druck des Compilers nachgeben (auch wenn das Programm tut, was es tun soll und ohne Problem ausgeführt werden kann) und ihm sein Cast geben – da dies ja auch nicht unbedingt »falsch« ist. SchlieÃlich zählt zu einem der oberen Gebote eines Programmierers, dass man niemals Warnmeldungen eines Compilers ignorieren soll. Vorwiegend findet ein void-Zeiger Anwendung in Funktionen, die mit unterschiedlichen Zeigern aufgerufen werden können. Beispielsweise ist die Funktion memcmp() in der Headerdatei <string.h> folgendermaÃen angegeben: > int memcmp (const void*, const void*, size_t); Somit kann diese Funktion mit unterschiedlichen Zeigertypen verwendet werden, wie das folgende Beispiel zeigt: > /* void_ptr2.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str1[]="Hallo"; char str2[]="Hallo"; int num1[] = { 1,2,3,4,5,6 }; int num2[] = { 1,3,5,7,9,1 }; int cmp; /* Casts sind nicht unbedingt nötig. */ cmp=memcmp( (char *)str1, (char *)str2, sizeof(str1)); if(cmp ==0) printf("Beide Strings sind gleich\n"); else printf("Die Strings sind nicht gleich\n"); /* Casts sind nicht unbedingt nötig. */ cmp=memcmp((int *)num1,(int *)num2, sizeof(num1)/sizeof(int)); if(cmp == 0) printf("Der Inhalt der beiden Zahlenarrays ist gleich\n"); else printf("Die Zahlenarrays sind unterschiedlich\n"); return EXIT_SUCCESS; } Die Umwandlung in einen entsprechenden Zeigertyp findet mit einem einfachen Type-Casting statt – was auch hier nicht unbedingt nötig gewesen wäre (siehe den Abschnitt vor dem Listing). Für einige ist es verwirrend, wie ein leerer Zeiger (void, dt. leer) einfach so in irgendeinen Datentyp gecastet werden kann, weil sie gelernt haben, dass int vier Bytes Speicher hat, double acht Bytes Speicher und void eben keinen. Dabei ist void eigentlich auch nicht ganz leer. Wenn Sie mit void den sizeof-Operator verwenden, erfahren Sie, dass void ein Byte an Speicher benötigt. Aber erinnern Sie sich nochmals an den Anfang des Kapitels, bei dem Sie den sizeof-Operator auf alle Typen von Zeigern verwendet haben: Da habe ich gesagt, dass alle Zeiger, egal welchen Typs, einen Speicherbedarf von vier Bytes (32 Bit) haben. Mehr ist auch nicht erforderlich, um eine Speicheradresse zu speichern. Ebenso sieht es mit dem void-Zeiger aus. Dieser benötigt wie alle anderen Zeiger vier Byte Speicherplatz. > /* void_ptr3.c */ #include <stdio.h> #include <stdlib.h> int main(void) { void *void_ptr; printf("%d Byte\n", sizeof(void_ptr)); return EXIT_SUCCESS; } Wollen Sie den Typ, auf den der void-Zeiger verweist, dereferenzieren, wird die Sache ein wenig komplizierter. Dafür benötigen Sie einen weiteren Zeiger: > /* void_ptr4.c */ #include <stdio.h> #include <stdlib.h> int main(void) { void *void_ptr; int wert = 10; void_ptr=(int *)&wert; *(int *)void_ptr = 100; printf("%d\n",wert); /* 100 */ return EXIT_SUCCESS; } Da der gecastete void-Zeiger allein noch nicht dereferenziert werden kann, wird hier einfach ein weiterer Zeiger verwendet: > *(int *)void_ptr = 100; Jetzt denken Sie sicherlich darüber nach, welchen Vorteil eigentlich ein void-Zeiger hat? Bei dem Beispiel, in dem die Funktion memcmp() verwendet wurde, ist der Vorteil eigentlich schon klar. Anstatt für jeden Datentyp eine eigene Funktion zu schreiben, wird einfach der void-Zeiger verwendet, und der Funktion kann es egal sein, mit welchem Datentyp sie verwendet wird. Wichtig ist dabei nur, dass die Funktion (logischerweise) entsprechend universell geschrieben wurde. Sie können nicht einfach einer Funktion, die mit der Funktion strcmp() einzelne Strings vergleicht, als Argument die Anfangsadresse eines int-Arrays übergeben. Es wurde ja bereits erwähnt, dass Zeiger und Arrays zwar eine gewisse Ãhnlichkeit in ihrer Anwendung aufweisen, aber deswegen noch lange nicht gleich sind – geschweige denn untereinander austauschbar sind. Dennoch wird häufig beides in einen Topf geworfen. > /* ptr_versus_array1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int var[] = { 123, 456, 789}; printf("*var : %d; var[0] : %d\n", *var, var[0]); return EXIT_SUCCESS; } Wenn Sie dieses Beispiel übersetzen, verstehen Sie, worauf ich hinaus will. Die Angaben von var[0] und *var repräsentieren ja dieselbe Adresse. Somit stehen Ihnen also zwei Möglichkeiten zur Verfügung. Damit Sie bei diesem Wirrwarr noch die Ãbersicht behalten können, folgt jetzt eine Tabelle, die die Verwandtschaft zwischen den Zeigern und den Arrays verdeutlicht. Falls Sie wieder einmal einen Quellcode finden, bei dem Sie nicht wissen, was das nun wieder sein soll, blättern Sie einfach zu diesen Tabellen. Es sollen folgende Werte für die erste Tabelle verwendet werden: > int n=3; int array[5]={ 0 }; /* eindim. Array mit Platz für 5 Werte*/ int *ptr = array; /* int-Zeiger verweist jetzt auf array[0] */ Folgendes ist jetzt gleichwertig in Bezug auf den Zugriff von Werten. Betrachten wir zuerst die Möglichkeiten des Zugriffs auf das erste Element: Als Nächstes folgt die Möglichkeit des Zugriffs auf das n-te Element: Die nächste Tabelle zeigt alle möglichen Zugriffe auf die Anfangsadresse: Jetzt folgt die Tabelle für den Zugriff auf die Speicheradresse des n-ten Elements: Nun folgt noch ein Listing, das alle Punkte nochmals demonstriert: > /* ptr_versus_array2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int n=3; /* eindim. Array mit Platz für 5 Werte */ int array[5]={ 1,2,3,4,5 }; /* int-Zeiger verweist jetzt auf array[0] */ int *ptr = array; /* 4 Möglichkeiten, um auf das erste Element zuzugreifen */ printf("%d ", *ptr); printf("%d ", ptr[0]); printf("%d ", *array); printf("%d\n", array[0]); /* 4 Möglichkeiten, um auf das n-te Element zuzugreifen */ printf("%d ", *(ptr+n)); printf("%d ", ptr[n]); printf("%d ", *(array+n)); printf("%d\n", array[n]); /* 4 Möglichkeiten, um auf die Anfangsadresse zuzugreifen */ printf("%p ", ptr); printf("%p ", &ptr[0]); printf("%p ", array); printf("%p\n", &array[0]); /* 4 Möglichkeiten, um auf die Adresse des n-ten Elements zuzugreifen */ printf("%p " , ptr+n); printf("%p ", &ptr[n]); printf("%p ", array+n); printf("%p\n", &array[n]); return EXIT_SUCCESS; } # 12.13 Der »restrict«-Zeiger ## 12.13 Der »restrict«-Zeiger Mit dem C99-Standard wurde der Typqualifizierer restrict neu eingeführt. Mit diesem Schlüsselwort können Sie Zeiger qualifizieren, sogenannte restrict-Zeiger. Der restrict-Zeiger hat eine enge Beziehung zu dem Speicherobjekt, auf das er verweist. Mit dem Qualifizierer geben Sie quasi vor, dass während der Lebensdauer des Zeigers das Speicherobjekt, auf das dieser verweist, nicht verändert werden kann und der Zugriff nur über diesen restrict-Zeiger erfolgen darf. Einfachstes Beispiel: > int * restrict iRptr = malloc (sizeof (int) ); Damit geben Sie praktisch vor, dass Sie den von malloc() zurückgegebenen reservierten Speicher nur mit dem Zeiger iRptr verwenden. Wohlgemerkt: Mit dem Qualifizierer restrict geben Sie nur dem Compiler das Versprechen, dass Sie auf das Speicherobjekt ausschlieÃlich mit diesem Zeiger zurückgreifen. Jede Manipulation auÃerhalb des restrict-Zeigers, und sei es nur lesend, ist unzulässig. Zu überprüfen, ob der restrict-Zeiger richtig verwendet wird, Sie also nur über diesen Zeiger auf ein Speicherobjekt zugreifen, ist Ihre Aufgabe. Der Compiler kann nicht überprüfen, ob Sie Ihr Versprechen eingehalten haben. Fall Sie die Regeln nicht einhalten, gibt es zwar keine Fehlermeldung des Compilers und häufig auch keine Probleme bei der Ausführung des Programms, aber dennoch ist das Verhalten laut Standard undefiniert. Abgesehen davon: Mit oder ohne den restrict-Zeiger bleibt die Ausführung des Programms dieselbe. Der Vorteil des restrict-Zeigers ist es, dass Sie es dem Compiler ermöglichen, Optimierungen des Maschinencodes durchzuführen, die sonst bei Zeigern zu Problemen führen können. Allerdings muss der Compiler auch diesem Hinweis nicht nachkommen und kann den Qualifizierer restrict auch ignorieren. Der restrict-Zeiger kann auch sehr gut bei Funktionen verwendet werden, um anzuzeigen, dass sich zwei Zeiger in der Parameterliste nicht überlappen dürfen, sprich, dasselbe Speicherobjekt verwenden. Beispielsweise ist bei > int flaeche( int * w, int * b ) { /* ... * / } nicht klar angegeben, ob sich die beiden Speicherobjekte, auf die die Zeiger w und h verweisen, überlappen dürfen oder nicht. Mit dem neuen Qualifizierer restrict ist dies jetzt sofort erkennbar: > int flaeche( int * restrict w, int * restrict b ) { /* ... * / } Wird trotzdem versucht, die Funktion mit sich überlappenden Speicherobjekte aufzurufen, ist das weitere Verhalten undefiniert. Ein ungültiger Aufruf kann beispielsweise wie folgt aussehen: > int val, x=20, y=10; // Unzulässig, wegen den restrict-Zeigern, // zwei gleiche Speicherobjekte werden verwendet, // die sich somit überlappen val = flaeche( &x, &x ); // OK, zwei verschiedene Speicherobjekte val = flaeche( &x, &y ); Vom restrict-Zeiger wird mittlerweile auch rege in der Standard-Bibliothek Gebrauch gemacht. Beispielsweise sieht die Syntax der Funktion strncpy() wie folgt aus: > #include <string.h> char *strncpy( char * restrict s1, const char * restrict s2, size_t n ); Die Funktion kopiert n Bytes vom Quellarray s2 in das Zielarray s1. Dadurch, dass die beiden Zeiger als restrict deklariert sind, müssen Sie beim Aufruf der Funktion beachten, dass die Zeiger nicht auf dieselben Speicherobjekte verweisen, sprich. sich nicht überlappen. Betrachten Sie dazu folgendes Beispiel: > char arr1[20]; char arr2[] = { "<NAME>" }; // Ok, 10 Zeichen von arr2 nach arr1 kopieren strncpy( arr1, arr2, 10 ); arr1[10] = '\0' // Unzulässig, Speicherbereiche überlappen sich, // das gibt nur Datensalat. strncpy( arr1, arr1, 5 ); Ein weiteres klassisches Beispiel von Funktionen der Standardbibliothek sind die Funktionen memcyp() und memmove() in der Headerdatei <string.h>. Die Syntax der Funktionen lautet: > #include <string.h> void *memcpy( void * restrict s1, const void * restrict s2, size_t n ); void *memmove( void *s1, const void *s2, size_t n); Bei diesen beiden Funktionen kann man sehr schön sehen, dass sich bei memcpy() der Quell- und der Zielbereich nicht überlappen dürfen, weil sonst die restrict-Regel verletzt würde. Bei der anderen Standardfunktion memmove() hingegen dürfen sich der Quell- und der Zielbereich überlappen. Der Taschenrechner, wie Sie ihn eben programmiert haben, macht in der heutigen Zeit wenig Sinn. Sinnvoller und (immer noch) sehr häufig verwendet werden Kommandozeilenargumente, um Schalter auszuwerten, etwa so: > rm --help Damit wird eine kurze Hilfsanleitung des Programms rm angezeigt. Meistens handelt es sich dabei um eine kurze Beschreibung, mit welchen Optionen (Schaltern) das Programm aufgerufen werden kann und was diese bewirken. Das Programm rm ist in der UNIX-Welt beheimatet und dient zum Löschen von Dateien und Verzeichnissen. Beispielsweise wird mit den Schaltern -rf > rm -rf verzeichnis ein ganzes Verzeichnis rekursiv ohne Nachfrage gelöscht. Dazu folgt jetzt ein Beispiel. Auf (fast) jedem System gibt es das Programm echo, mit dem Sie einen Text auf die Standardausgabe schicken können. Beispielsweise wird mit > echo Hallo Welt »Hallo Welt« auf dem Bildschirm ausgegeben. Das folgende Programm ist ein eigenes Echo, myecho, mit dem der Text mithilfe von Schaltern spiegelverkehrt, in GroÃ- oder Kleinbuchstaben ausgegeben werden kann. Folgende Schalter werden verwendet: > void show_help(void) { printf("\nProgrammaufruf: myecho [OPTION] STRING\n"\ "Programm gibt den Text in gewünschter Form auf"\ "dem Bildschirm aus\n\n nFolgende Optionen stehen"\ "Ihnen zur Verfügung:\n\n"\ "\t-r Text wird spiegelverkehrt ausgegeben\n"\ "\t-g Text wird in Grossbuchstaben ausgegeben\n"\ "\t-s Text wird in Kleinbuchstaben ausgegeben\n "\ "\t-h Dieser Text\n" "\t-v Versionsnummer\n\n"); } Hier sehen Sie den vollständigen Quellcode: > /* myecho.c */ #include <stdio.h> #include <string.h> #include <ctype.h> /* tolower(), toupper(), isalpha() */ #include <stdlib.h> #define FALSE 0 #define TRUE 1 #define BUF 4096 void show_help(void) { printf("\nProgrammaufruf: myecho [OPTION] STRING\n"\ "Programm gibt den Text in gewünschter Form auf"\ "dem Bildschirm aus\n\nFolgende Optionen stehen"\ "Ihnen zur Verfügung:\n\n"\ "\t-r Text wird spiegelverkehrt ausgegeben\n"\ "\t-g Text wird in Grossbuchstaben ausgegeben\n"\ "\t-s Text wird in Kleinbuchstaben ausgegeben\n "\ "\t-h Dieser Text\n" "\t-v Versionsnummer\n\n"); } int getopt(char *argument, char *option) { if( argument[0]=='-' && argument[1]==option[0] ) return TRUE; return FALSE; } void spiegeln(char *string) { char *reverse = string; while(*reverse++); while(reverse-- != string) printf("%c",*reverse); printf("\n"); } void larger(char *string) { char *large=string; while(*large) printf("%c",(isalpha(*large))?toupper(*large++):*large++); printf("\n"); } void smaller(char *string) { char *small=string; while(*small) printf("%c",(isalpha(*small))?tolower(*small++):*small++); printf("\n"); } int main(int argc, char *argv[]) { int counter=3; char buffer[BUF]; size_t len=0; if(argc == 1 || getopt(argv[1],"h") == TRUE ) { show_help(); return EXIT_FAILURE; } else if(getopt(argv[1],"v") == TRUE) { printf("Version 1.0\n"); return EXIT_SUCCESS; } else if(argc < 3) { show_help(); return EXIT_FAILURE; } len=strlen(argv[2])+1; /* ab argv[2] bis argv[n] alle Elemente in buffer */ if(len > BUF) { printf("Der String enthält zu viele Zeichen\n"); return EXIT_FAILURE; } strcpy(buffer,argv[2]); while(argv[counter] != NULL) { len += strlen(argv[counter])+2; if(len > BUF) { printf("Der Puffer ist bereits voll\n"); break; } strcat(buffer, " "); strcat(buffer, argv[counter++]); } if(getopt(argv[1],"r") == TRUE) spiegeln(buffer); else if(getopt(argv[1],"g") == TRUE) larger(buffer); else if(getopt(argv[1],"s") == TRUE) smaller(buffer); else show_help(); return EXIT_SUCCESS; } Als Kernstück in diesem Programm dient die Funktion getopt(): > int getopt(char *argument, char *option) { if( argument[0]=='-' && argument[1]==option[0] ) return TRUE; return FALSE; } Damit wird überprüft, ob der String mit dem Schalterzeichen (-) beginnt und ob für option eine Option vorhanden ist: > if(getopt(argv[1],"s") == TRUE) Hier wird beispielsweise überprüft, ob der Schalter s verwendet wurde. Falls dies zutrifft, wird TRUE zurückgegeben, andernfalls FALSE. Alle anderen Funktionen dienen nur zur Verzierung des Programms, das Sie natürlich weiter ausbauen können. Hier wurden auÃerdem Funktionen der Standard-Headerdatei <ctype.h> verwendet, die zur Ãberprüfung und Konvertierung von einzelnen Zeichen dienen. Die Funktion isalpha() überprüft, ob es sich um ein Zeichen des Alphabets handelt. Ist dies der Fall, liefert diese Funktion 1 zurück. Die Funktion tolower() macht aus einem groÃen Buchstaben einen kleinen, und toupper() macht aus einem kleinen Buchstaben wieder einen groÃen. Mehr zu dieser Headerdatei und den darin enthaltenen Funktionen erfahren Sie später. # 14.2 Speicherallokation mit »malloc()« ## 14.2 Speicherallokation mit »malloc()« Ich habe bereits kurz erwähnt, mit welcher Funktion Speicher dynamisch reserviert werden kann. Es wird dabei auch von einer Speicherallokation (allocate, dt. zuweisen) gesprochen. Die Syntax dieser Funktion sieht so aus: > #include <stdlib.h> void *malloc(size_t size); Bei erfolgreichem Aufruf liefert die Funktion malloc() die Anfangsadresse mit der GröÃe size Bytes vom Heap zurück. Da die Funktion einen void-Zeiger zurückliefert, hängt diese nicht von einem Datentyp ab. Hierzu ein Beispiel: > /* malloc1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int *p; p = malloc(sizeof(int)); if(p != NULL) { *p=99; printf("Allokationerfolgreich ... \n"); } else { printf("Kein virtueller RAM mehr verfügbar ...\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } Nach der Deklaration eines int-Zeigers wurde diesem mit > p = malloc(sizeof(int)); eine Anfangsadresse eines Speicherbereichs der GröÃe int zugewiesen. Bei Erfolg zeigt der Zeiger p auf den Anfang des reservierten Speicherbereichs. Ist dabei etwas schiefgegangen, zeigt der Zeiger auf NULL, und es wird ausgegeben, dass kein Speicherplatz reserviert werden konnte. Abbildung 14.1 verdeutlicht den Programmablauf anhand einer Grafik. Abbildung 14.1 Dynamisch reservierter Speicher vom Heap Na gut, ich denke, das beeindruckt Sie nicht besonders. Zur Laufzeit eines Programms Speicherplatz für einen int-Wert reservieren mit solch einem Aufwand? Gut, dann reservieren Sie eben mehr Speicherplatz für mehrere int-Werte: > p = malloc(2 * sizeof(int)); Hiermit reservieren Sie Speicherplatz für zwei int-Werte vom Heap. Hier sehen Sie das Beispiel als Listing: > /* malloc2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int *p = malloc(2 * sizeof(int)); if(p != NULL) { *p=99; /* alternativ auch p[0] = 99 */ *(p+1) = 100; /* alternativ auch p[1] = 100 */ printf("Allokation erfolgreich ... \n"); } else { printf("Kein virtueller RAM mehr verfügbar ...\n"); return EXIT_FAILURE; } printf("%d %d\n", p[0], p[1]); /* Sie können die Werte auch so ausgeben lassen. */ printf("%d %d\n", *p, *(p+1)); return EXIT_SUCCESS; } Abbildung 14.2 soll den Sachverhalt veranschaulichen. Abbildung 14.2 Speicher für mehrere Elemente dynamisch anfordern Der Sachverhalt, warum *p und p[0] oder *(p+1) und p[1] auf dasselbe Element zugreifen, wurde in Kapitel 12, »Zeiger (Pointer)«, geklärt. Blättern Sie notfalls einfach zu den Tabellen am Ende von Kapitel 12 zurück. # 14.3 Das NULL-Mysterium ## 14.3 Das NULL-Mysterium Ein NULL-Zeiger wird zurückgeliefert, wenn malloc() nicht mehr genügend zusammenhängenden Speicher finden kann. Der NULL-Zeiger ist ein vordefinierter Zeiger, dessen Wert sich von einem regulären Zeiger unterscheidet. Er wird vorwiegend bei Funktionen zur Anzeige und Ãberprüfung von Fehlern genutzt, die einen Zeiger als Rückgabewert zurückgeben. ### 14.3.1 NULL für Fortgeschrittene Sicherlich haben Sie sich schon einmal gefragt, was es mit NULL auf sich hat. Wenn Sie dann in einem Forum nachgefragt haben, könnten Sie beispielsweise dreierlei Antworten zurückbekommen haben: * Es gibt keinen NULL-Zeiger, sondern nur NULL, und das ist eben 0. Sicherlich gibt es noch einige Antworten mehr hierzu. Aber es ist doch ziemlich verwirrend, ob jetzt NULL eben 0 ist oder ein Zeiger auf 0 – und wo ist dabei eigentlich der Unterschied? Ein integraler konstanter Ausdruck mit dem Wert 0 wird zu einem NULL-Zeiger, wenn dieser einem Zeiger zugewiesen oder auf Gleichheit mit einem Zeiger geprüft wird. Damit ergeben sich die folgenden möglichen defines für NULL: > #define NULL 0 #define NULL 0L #define NULL (void *) 0 Am häufigsten sieht man das Makro NULL als (void *) 0 implementiert, was den Vorteil hat, dass einem gegebenenfalls bei der Ãbersetzung die Arbeit abgenommen wird. Allerdings sollten Sie – egal wie NULL nun implementiert ist – auf eine Typumwandlung von NULL verzichten, denn schlieÃlich kann NULL ja auch nur 0 oder 0L sein. Der Compiler muss zur Ãbersetzungszeit selbst feststellen, wann ein NULL-Zeiger benötigt wird, und eben den entsprechenden Typ dafür eintragen. Somit ist es ohne Weiteres möglich, folgende Vergleiche zu verwenden (beide Versionen erfüllen denselben Zweck): > /* null_ptr1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char *ptr1 = NULL; char *ptr2 = 0; if(ptr1 != NULL){ /* ... */ } if(ptr2 != 0) { /* ... */ } return EXIT_SUCCESS; } Bei einem Funktionsargument allerdings ist ein solcher Zeiger-Kontext nicht unbedingt feststellbar. Hier kann ein Compiler eventuell nicht feststellen, ob der Programmierer hier 0 (als Zahl) oder eben den NULL-Zeiger meint. Hier ein Beispiel, das zeigt, worauf ich hinaus will: > execl ("/bin/sh", "sh", "-c", "ls", 0); Der (UNIX)-Systemaufruf execl() erwartet eine Liste variabler Länge mit Zeigern auf char, die mit einem NULL-Zeiger abgeschlossen werden. Der Compiler kann hierbei allerdings nicht feststellen, ob der Programmierer hier mit 0 den NULL-Zeiger meint; daher wird sich der Compiler in diesem Fall für die Zahl 0 entscheiden. In diesem Fall müssen Sie unbedingt eine Typumwandlung nach char* durchführen – oder eben den NULL-Zeiger verwenden: > execl ("/bin/sh", "sh", "-c", "ls", (char *)0); // ... oder ... execl ("/bin/sh", "sh", "-c", "ls", NULL); Dieser Fall ist besonders bei einer variablen Argumentenliste (wie sie hier mit execl() vorliegt) wichtig. Denn hier funktioniert alles (auch ohne ein Type-Casting) bis zum Ende der explizit festgelegten Parameter. Alles was danach folgt, wird nach den Regeln für die Typenerweiterung behandelt, und es wird eine ausdrückliche Typumwandlung erforderlich. Da es sowieso kein Fehler ist, den NULL-Zeiger als Funktionsargument einer expliziten Typumwandlung zu unterziehen, ist man bei regelmäÃiger Verwendung (eines expliziten Casts) immer auf der sicheren Seite, wenn dann mal Funktionen mit einer variablen Argument-Anzahl verwendet werden. Bei einem »normalen« Funktionsprototypen hingegen werden die Argumente weiterhin anhand ihrer zugehörigen Parameter im Prototyp umgewandelt. Verwenden Sie hingegen keinen Funktionsprototyp im selben Gültigkeitsbereich, wird auch hier eine explizite Umwandlung benötigt. ### 14.3.2 Was jetzt – NULL, 0 oder \0 ... ? Ob Sie jetzt NULL oder 0 verwenden, ist eine Frage des Stils und des Progammierers. Viele Programmierer halten NULL für eine sinnlose Neuerung, auf die man gern verzichten kann (wozu soll man eine 0 hinter NULL verstecken) – andere wiederum entgegnen dem, dass man mit NULL besser unterscheiden kann, ob denn nun ein Zeiger gemeint ist oder nicht. Denn Folgendes wird der Compiler bemängeln, wenn NULL als (void *)0 implementiert ist: > /* null_ptr2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int *ptr = NULL; int i = NULL; // falsch return EXIT_SUCCESS; } Intern nach dem Präprozessorlauf würde aus der Zeile > int i = NULL; Folgendes gemacht: > int i = (void *) 0; Dies ist ein klarer Regelverstoà und somit unzulässig. Irgendwie bringen dann die Anfänger noch das Terminierungszeichen \0 (NULL) mit in diese Geschichte ein (ich begreife zwar nicht wie, aber es geschieht ...). Vielleicht wird dabei das ASCII-Zeichen NUL mit NULL verwechselt. Allerdings kann man \0 nicht mit NULL vergleichen. \0 garantiert beispielsweise laut Standard, dass alle Bits auf 0 gesetzt sind (NULL tut das nicht). ### 14.3.3 Zusammengefasst Aufgrund der häufigen Nachfragen zu NULL habe ich mich bewusst entschieden, dass Thema etwas breiter aufzurollen. Vielleicht ist der eine oder andere jetzt total verwirrt. Daher folgen hier zwei Regeln zum Umgang mit NULL, die Sie einhalten sollten, damit Sie auf der sicheren Seite sind: * Wollen Sie im Quelltext einen NULL-Zeiger verwenden, dann können Sie entweder eben diesen Null-Zeiger mit der Konstante 0 oder eben das Makro NULL verwenden. * Verwenden Sie hingegen 0 oder NULL als Argument eines Funktionsaufrufes, wenden Sie am besten die von der Funktion erwartete explizite Typumwandlung an. # 14.4 Speicherreservierung und ihre Probleme ## 14.4 Speicherreservierung und ihre Probleme Bei einem Aufruf der Funktion malloc() muss die GröÃe des zu reservierenden Speichers in Bytes angegeben werden. Damit ist die GröÃe des Speicherobjekts gemeint, das durch einen Zeiger referenziert werden soll. Für die dynamische Speicherzuweisung haben Sie folgende drei Möglichkeiten: * als numerische Konstante: * p = malloc(sizeof(2)); * Hiermit werden vier Bytes (!) reserviert, auf deren Anfangsadresse der Zeiger p verweist. Es werden nicht – wie vielleicht irrtümlicherweise angenommen – zwei Bytes reserviert, sondern es wird eben so viel Speicher reserviert, wie es dem Datentyp im sizeof-Operator auf dem jeweiligen System entspricht. Der Wert 2 entspricht gewöhnlich auf 32-Bit-Rechnern 4 Bytes (int). Somit kann die Verwendung einer numerischen Konstante sehr verwirrend sein. * Angabe des Datentyps mithilfe des sizeof-Operators: * Diese Möglichkeit hat einen Nachteil. Was ist, wenn Sie statt int-Werten auf einmal double-Werte benötigen? Dann müssen Sie mühsam alle Speicherzuweisungen ändern in: * p = malloc(sizeof(double)); * Sie können auch den dereferenzierten Zeiger selbst für den sizeof-Operator verwenden: * Aber Achtung: Wehe, Sie vergessen den Dereferenzierungsoperator (*) wie im folgenden Listing: > /* malloc3.c */ #include <stdio.h> #include <stdlib.h> int main(void) { double *p1,*p2; p1 = malloc(sizeof(p1)); // Fehler p2 = malloc(sizeof(p2)); // Fehler if(p1 != NULL && p2 != NULL) { *p1 = 5.15; printf("p1 = %f\n",*p1); *p2 = 10.99; printf("p2 = %f\n",*p2); } return EXIT_SUCCESS; } Wenn Sie »Glück« haben, stürzt das Programm ab. Im schlimmsten Fall funktioniert das Programm und gibt die richtigen Zahlen aus. Das wäre aber purer Zufall. Denn ohne den Dereferenzierungsoperator wird nicht ein double-Wert an malloc() übergeben, sondern die GröÃe des Zeigers. Und diese beträgt immer vier (bei 32-Bit-Rechnern) statt der erforderlichen acht Bytes. Wenn jetzt ein anderer Wert an diese Adresse gelangt, ist der weitere Verlauf des Programms nicht absehbar. Es kommt zu einer sogenannten Ãberlappung der Speicherbereiche. ## 14.5 »free()« – Speicher wieder freigeben Wenn Sie Speicher vom Heap angefordert haben, sollten Sie diesen auch wieder zurückgeben. Der allozierte Speicher wird mit folgender Funktion freigegeben: > #include <stdlib.h> void free (void *p) Der Speicher wird übrigens auch ohne einen Aufruf von free() freigegeben, wenn sich das Programm beendet. Ein Beispiel zu free(): > /* free1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int *p = malloc(sizeof(int)); if(p != NULL) { *p=99; printf("Allokation erfolgreich ... \n"); } else { printf("Kein virtueller RAM mehr verfügbar ... \n"); return EXIT_FAILURE; } if(p != NULL) free(p); return EXIT_SUCCESS; } Es wird hier auch überprüft, dass nur wirklich reservierter Speicherplatz wieder freigegeben wird. Der mit free() freigegebene Speicherplatz wird danach zwar als frei markiert, aber p zeigt immer noch auf die ursprüngliche Speicherstelle. Hier sehen Sie das Beispiel: > /* free2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int *p = malloc(sizeof(int)); if(p != NULL) { *p=99; printf("Allokation erfolgreich ... \n"); } else { printf("Kein virtueller RAM mehr verfügbar ... \n"); return EXIT_FAILURE; } printf("vor free() *p = %d\n", *p); if(p != NULL) free(p); printf("nach free() *p = %d\n", *p); return EXIT_SUCCESS; } Wenn Sie absolut sicher sein wollen, dass der Zeiger nichts mehr zurückgibt, dann übergeben Sie dem Zeiger nach der Freigabe von Speicher einfach den NULL-Zeiger: > free(p); p = NULL; Dies können Sie wie folgt in ein Makro verpacken: > #define my_free(x) free(x); x = NULL Was malloc() und die weiteren Speicherallokationsfunktionen so bedeutend und wichtig macht, ist die Möglichkeit, von jedem beliebigen Datentyp Speicher anfordern zu können – sind es nun einfache Datentypen wie Strings, Arrays oder komplexe Strukturen. Natürlich können Sie auch Speicherplatz für ein char-Array zur Laufzeit anfordern. Das folgende Beispiel demonstriert dies: > /* malloc4.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define BUF 80 int main(void) { char puffer[BUF]; char *dyn_string; printf("Ein Text mit max. 80 Zeichen: "); fgets(puffer, BUF, stdin); dyn_string = malloc(strlen(puffer) + 1); if(dyn_string != NULL) strncpy(dyn_string, puffer, strlen(puffer) + 1); else { printf("Konnte keinen Speicherplatz reservieren\n"); return EXIT_FAILURE; } printf("%s",dyn_string); free(dyn_string); return EXIT_SUCCESS; } Wobei erwähnt werden muss, dass diese Art, dynamisch Speicher für einen Text zu reservieren, noch recht unflexibel ist. Mit > dyn_string = malloc(strlen(puffer) + 1); wird exakt so viel Speicher angefordert, wie zuvor mit fgets() in den String puffer eingelesen wurde. Im Verlauf des Buchs in Abschnitt 16.25, »Ein fortgeschrittenes Thema«, werden Sie erfahren, wie Sie viel effektiver dynamischen Speicher für Text anfordern. Denn bei diesem Beispiel hätten Sie es ja gleich beim char-Array puffer belassen können. # 14.6 Die Freispeicherverwaltung ## 14.6 Die Freispeicherverwaltung Ohne mich hier zu sehr in die Details der Freispeicherverwaltung zu verstricken, soll dieses Thema kurz behandelt werden. Als Programmierer kann es Ihnen im Prinzip egal sein, wie ein Betriebssystem seinen Speicher reserviert. Aber wenn Sie irgendwann professionelle Programme schreiben, die häufig Speicher vom Heap anfordern, wäre manches Mal ein wenig Hintergrundwissen wünschenswert. AuÃer dem Hauptspeicher und dem Festplattenspeicher gibt es noch weitere Möglichkeiten, Daten zu speichern und zu verarbeiten. Es wird dabei von einer Speicherhierarchie gesprochen, die sich in die folgenden sechs Schichten aufteilt: * Prozessor-Register * First Level Cache der CPU (On-chip-Cache, 8–64 KB) * Second Level Cache der CPU (128–512 KB) * Hauptspeicher (RAM, z. B. 128–512 MB) * Sekundärspeicher (Festplatte, 10–120 GB) * Tertiärspeicher (Magnetband, 20–160 GB) Als C-Programmierer bedienen Sie sich allerdings vorwiegend vom Hauptspeicher. Das Betriebssystem verwendet dabei das sogenannte Paging zur Verwaltung des Speichers. Als Paging wird die Unterteilung des virtuellen Speichers in Seiten (Pages) und des physischen Speichers in Seitenrahmen (Page Frames) bezeichnet. Die GröÃe einer Seite beträgt bei den gängigen Betriebssystemen 512 KB oder 1024 KB. Ein virtuelles Speichersystem ist erforderlich, damit auch mehrere Programme laufen können, die nicht alle in den physischen Speicher (echter vorhandener Speicher, RAM) passen würden. Dafür stellt Ihnen das Betriebssystem eine sogenannte Adresskonvention zur Verfügung, mit der aus einer virtuellen Adresse wieder eine physische Adresse wird. Denn mit virtuellen Adressen allein könnte kein Programm laufen. In Abschnitt 14.1 haben Sie bereits etwas über den Heap erfahren. Sie wissen, dass der Heap ein zusammenhängender Speicherplatz im Arbeitsspeicher ist, von dem Sie als Programmierer Speicher allozieren können. Das Betriebssystem verwaltet diesen Speicherbereich als eine Kette von freien Speicherblöcken, die nach aufsteigenden Speicheradressen sortiert ist. Jeder dieser Blöcke enthält Informationen wie die Gesamtlänge oder den nächsten freien Block. Benötigen Sie jetzt Speicherplatz, durchläuft das Betriebssystem diesen Speicherblock nach verschiedenen Verfahren. Dabei wird von einer prozessinternen Freispeicherverwaltung gesprochen. ### 14.6.1 Prozessinterne Freispeicherverwaltung Durch einen Aufruf von malloc() sucht das Betriebssystem jetzt einen zusammenhängenden Speicherblock, der den Anforderungen entspricht. Auf der Suche nach diesem Speicherplatz gibt es verschiedene Strategien bzw. Algorithmen, die im Betriebssystem (genauer: im Kernel) implementiert sind. Als Beispiel dienen freie Speicherbereiche, die so im System angeordnet sind, wie Sie es in Abbildung 14.3 sehen. Abbildung 14.3 Freie Speicherbereiche im System Sie fordern jetzt von diesen freien Speicherbereichen mit der Funktion malloc() folgende Speicherblöcke an: > ptr1 = malloc(10); ptr2 = malloc(12); ptr3 = malloc(9); Anhand des freien Speicherbereichs (siehe Abbildung 14.3) und den drei Speicheranforderungen will ich Ihnen die einzelnen Verfahren erklären. # First-Fit-Verfahren Beim First-Fit-Verfahren durchläuft die Speicherverwaltung die Liste der Reihe nach und alloziert den erstbesten freien Bereich, der groà genug ist. Somit sieht die Speicherbelegung im First-Fit-Verfahren so aus wie in Abbildung 14.4 gezeigt. Abbildung 14.4 First-Fit-Verfahren # Next-Fit-Verfahren Das Next-Fit-Verfahren funktioniert wie First-Fit, nur merkt sich das Next-Fit-Verfahren die aktuelle Position und fährt bei der nächsten Suche nach freiem Speicher von dieser Position aus fort. # Best-Fit-Verfahren Beim Best-Fit-Verfahren wird die gesamte Speicherliste durchsucht, bis ein kleinstmögliches Loch gefunden wird. Mit diesem Verfahren wird eine optimale Speicherausnutzung garantiert. Abbildung 14.5 Best-Fit-Verfahren # Worst-Fit-Verfahren Das Worst-Fit-Verfahren ist das Gegenteil von Best-Fit. Dabei wird in der Liste nach dem gröÃten verfügbaren freien Bereich gesucht, und dieser wird verwendet. Abbildung 14.6 Worst-Fit-Verfahren # Quick-Fit-Verfahren Das Quick-Fit-Verfahren unterhält getrennte Listen für freie Bereiche gebräuchlicher GröÃe. # Buddy-Verfahren Das Buddy-Verfahren verwendet für jede SpeichergröÃe eine eigene Liste. Die Zeiger auf die Listenköpfe werden dabei in einem Array zusammengefasst. Bei diesem Verfahren werden nur Blöcke von Zweierpotenzen verwendet (1 Byte, 2 Byte, 4 Byte, 8 Byte, 16 Byte, 32 Byte, 64 Byte,  , 512 Byte, 1 KB,  , 512 KB, 1 MB,  ). Wird Speicher angefordert, der nicht diesem Block entspricht, wird ein Block mit der nächsten Zweierpotenz verwendet. Die Blöcke werden auÃerdem dahingehend markiert, ob sie zur Anwendung frei sind. Ist bei Speicheranforderung kein gewünschter Block frei, wird ein Block in zwei gleich groÃe Blöcke aufgeteilt. # Freigabe von Speicher Der Speicherplatz, der wieder freigegeben wird, wird nicht an das Betriebssystem zurückgegeben, sondern in die Freispeicherliste eingehängt. Nach diesem Ausflug, der schon mehr in Richtung Programmierung von Betriebssystemen ging, nun kehren wir wieder zur Praxis zurück. # 14.7 Dynamische Arrays ## 14.7 Dynamische Arrays Wenn mit der Funktion malloc() ein zusammenhängender Speicherbereich reserviert werden kann, dann muss es auch möglich sein, Speicher für ein Array während der Laufzeit zu reservieren. Bei einem zusammenhängenden Speicher können Sie davon ausgehen, dass dieser in einem Block (lückenlos) zur Verfügung gestellt wird. In dem folgenden Beispiel wird ein solches dynamisches Array erzeugt: > /* dyn_array1.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { int *value; int size, i = 0; printf("Wie viele Werte benötigen Sie : "); scanf("%d", &size); value = malloc(size*sizeof(int)); if( NULL == value ) { printf("Fehler bei malloc....\n"); return EXIT_FAILURE; } while( i < size ) { printf("Wert für value[%d] eingeben : ", i); scanf("%d", &value[i]); i++; } printf("Hier Ihre Werte\n"); for(i=0; i < size; i++) printf("value[%d] = %d\n", i, value[i]); return EXIT_SUCCESS; } Abbildung 14.7 Dynamisch erzeugtes Array Mit > value = malloc(size*sizeof(int)); wird ein zusammenhängender Speicherbereich mit size int-Werten reserviert. Danach werden mit > while(i < size) { printf("Wert für value[%d] eingeben : ", i); scanf("%d", &value[i]); i++; } diesem Speicherbereich Werte zugewiesen. Zum besseren Verständnis zeige ich hier dasselbe Programm nochmals, aber statt mit Arrays nun mit Zeigern: > /* dyn_array2.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { int *value; int size, i=0; printf("Wie viele Werte benötigen Sie : "); scanf("%d", &size); value = malloc(size*sizeof(int)); if(NULL == value) { printf("Fehler bei malloc...!!\n"); return EXIT_FAILURE; } while(i < size) { printf("Wert für value[%d] eingeben : ",i); scanf("%d",(value+i)); i++; } printf("Hier Ihre Werte\n"); for(i=0; i<size; i++) printf("value[%d] = %d\n", i, *(value+i)); return EXIT_SUCCESS; } Da *value, value[0] und *(value+1), value[1] immer auf dieselbe Speicheradresse verweisen, ist es egal, wie darauf zugegriffen wird. Das Programm ist jetzt etwas unflexibel. Was ist, wenn Sie für fünf weitere Elemente Speicherplatz benötigen? Mit der Funktion realloc() wäre dies recht einfach zu realisieren. Aber diese Funktion steht jetzt noch nicht zur Debatte. Die Speicherzuweisung ist auch mit malloc() möglich, wenn auch etwas umständlicher. Hier sehen Sie das Beispiel: > /* dyn_array3.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { int *value,*temp; int i=0, more; int size, merker = 0; printf("Wie viele Werte benötigen Sie : "); scanf("%d", &size); value = (int *)malloc(size*sizeof(int)); if(NULL == value) { printf("Fehler bei malloc...!! n"); return EXIT_FAILURE; } do { while(merker < size) { printf("Wert für value[%d] eingeben : ",merker); scanf("%d",&value[merker]); merker++; } printf("Neuen Platz reservieren (0=Ende) : "); scanf("%d",&more); temp = malloc(size*sizeof(int)); if(NULL == temp) { printf("Kann keinen Speicher mehr reservieren!\n"); return EXIT_FAILURE; } for(i=0; i<size; i++) temp[i]=value[i]; size+=more; value = malloc(size * sizeof(int)); if(NULL == value) { printf("Kann keinen Speicher mehr reservieren!\n"); return EXIT_SUCCESS; } for(i=0; i<size; i++) value[i]=temp[i]; }while(more!=0); printf("Hier Ihre Werte\n"); for(i=0; i<size; i++) printf("value[%d] = %d\n" ,i ,value[i]); return EXIT_SUCCESS; } Abbildung 14.8 Ein dynamisch reserviertes Array dynamisch erweitern Bevor Sie für das bereits dynamisch reservierte Array erneut Speicherplatz reservieren können, müssen Sie die bereits eingegebenen Werte erst einmal in ein temporär alloziertes Array zwischenspeichern. Danach kann neuer Speicherplatz für das Array reserviert werden, in den anschlieÃend die Werte aus dem temporären Array zurückkopiert werden. Das alles ist ziemlich aufwendig. Ihnen das jetzt anhand eines char-Arrays (Strings) zu demonstrieren, erspare ich mir zunächst. # 14.8 Speicher dynamisch reservieren mit »realloc()« und »calloc()« ## 14.8 Speicher dynamisch reservieren mit »realloc()« und »calloc()« In der Headerdatei <stdlib.h> sind noch zwei weitere Funktionen zum dynamischen Reservieren von Speicher deklariert. Hier sehen Sie die Syntax zu diesen Funktionen: > void *calloc(size_t anzahl, size_t groesse); void *realloc(void *zgr, size_t neuegroesse); Die Funktion calloc() ist der Funktion malloc() sehr ähnlich, nur dass es bei der Funktion calloc() nicht einen, sondern zwei Parameter gibt. Im Gegensatz zu malloc() können Sie mit calloc() noch die anzahl von Speicherobjekten angeben, die reserviert werden soll. Wird z. B. für 100 Objekte vom Typ int Speicherplatz benötigt, so erledigen Sie dies mit calloc() folgendermaÃen: > int *zahlen; zahlen = calloc(100,sizeof(int)); AuÃerdem werden mit der Funktion calloc() alle Werte des allozierten Speicherbereichs automatisch mit dem Wert 0 initialisiert. Bei malloc() hat der reservierte Speicherplatz zu Beginn einen undefinierten Wert. Allerdings können Gleitpunkt- und Zeiger-Nullen auch ganz anders dargestellt werden, weshalb man sich auf solchen Feldern nicht auf die Nullen verlassen kann. Gleichwertig zu calloc() verhält sich auÃerdem folgendes Code-Konstrukt mit malloc(): > ptr = calloc(100, sizeof(int)); // Alternative dafür mit malloc(); erfüllt denselben Zweck ptr = malloc(100 * sizeof(int)); memset(ptr, 0, 100 * sizeof(int)); Da calloc() auÃer den beiden eben genannten Unterschieden genauso funktioniert wie die Funktion malloc(), gehe ich nicht mehr näher darauf ein. Interessanter ist dagegen die dynamische Speicherreservierung mit der Funktion realloc(). Mit dieser Funktion ist es möglich, während des laufenden Programms so viel Speicher zu reservieren, wie Sie benötigen. Des Weiteren können Sie sich darauf verlassen, dass ein neuer Pool mit malloc() erstellt wird und die ganzen Ergebnisse herüberkopiert werden, wenn im aktuellen Speicherblock nicht mehr genügend freier Speicher vorhanden ist. Mit realloc() ist es noch einfacher, z. B. dynamische Arrays zu programmieren. Die Anfangsadresse des dynamischen Arrays ist diejenige, auf die der Zeiger (zgr) zeigt. Der Parameter neuegroesse dient dazu, einen bereits zuvor allozierten Speicherplatz auf neuegroesse Bytes zu vergröÃern. Die Funktion realloc() ermöglicht es auch, den Speicherplatz zu verkleinern. Dazu wird einfach der hintere Teil des Speicherblocks freigegeben, während der vordere Teil unverändert bleibt. Bei einer VergröÃerung des Speicherplatzes mit realloc() behält der vordere Teil auf jeden Fall seinen Wert, und der neue Teil wird einfach hinten angehängt. Dieser angehängte Wert ist aber wie bei malloc() undefiniert. Hier sehen Sie ein kleines Beispiel dafür, wie ein Array mit der Funktion realloc() dynamisch erstellt wird: > /* realloc1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int n=0, max=10, z,i; int *zahlen=NULL; /* Wir reservieren Speicher für 10 int-Werte mit calloc. */ zahlen = calloc(max, sizeof(int)); if(NULL == zahlen) { printf("Kein virtueller RAM mehr vorhanden ... !"); return EXIT_FAILURE; } printf("Zahlen eingeben --- Beenden mit 0\n"); /* Endlossschleife */ while(1) { printf("Zahl (%d) eingeben : ", n+1); scanf("%d", &z); if(z==0) break; /* Reservierung von Speicher während der Laufzeit * des Programms mit realloc */ if(n >= max) { max += max; zahlen = realloc(zahlen,max*sizeof(int)); if(NULL == zahlen) { printf("Kein virtueller RAM mehr vorhanden ... !"); return EXIT_FAILURE; } printf("Speicherplatz reserviert " " (%d Bytes)\n", sizeof(int) * max); } zahlen[n++] = z; } printf("Folgende Zahlen wurden eingegeben ->\n\n"); for(i = 0; i < n; i++) printf("%d ", zahlen[i]); printf("\n"); free(zahlen); return EXIT_SUCCESS; } Den benötigten Speicherbedarf könnten Sie in diesem Beispiel auch einzeln allozieren. Die einfache Anwendung dieser Funktion soll nicht darüber hinwegtäuschen, dass auch hier erst der alte Speicherbereich temporär zwischengespeichert werden muss, so wie bei der Funktion malloc(). In diesem Fall ist es aber einfacher, da Sie sich nicht mehr selbst darum kümmern müssen. Im Beispiel wurde der Speicherplatz nach jedem erneuten Allozieren mit calloc() gleich verdoppelt (max += max). Dies ist nicht optimal. Benötigt ein Programm z. B. täglich 500 double-Werte, wäre es am sinnvollsten, erst nach 500 double-Werten neuen Speicher zu allozieren. Somit müsste das Programm nur einmal am Tag neuen Speicher bereitstellen. Dasselbe Beispiel lässt sich recht ähnlich und einfach auch auf char-Arrays umschreiben. Das folgende Listing demonstriert die dynamische Erweiterung eines Strings: > /* dyn_string1.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define BUF 255 int main(void) { size_t len; char *str = NULL; char puffer[BUF]; printf("Ein dynamisches char-Array für Strings\n"); printf("Eingabe machen : "); fgets(puffer, BUF, stdin); str = malloc(strlen(puffer)+1); if(NULL == str) { printf("Kein virtueller RAM mehr vorhanden ... !"); return EXIT_FAILURE; } strcpy(str, puffer); printf("Weitere Eingabe oder beenden mit \"END\"\n>"); /* Endlossschleife */ while(1) { fgets(puffer, BUF, stdin); /* Abbruchbedingung */ if(strcmp(puffer,"end\n")==0 || strcmp(puffer,"END\n")==0) break; /* aktuelle Länge von str zählen für realloc */ len = strlen(str); /* neuen Speicher für str anfordern */ str = realloc(str,strlen(puffer)+len+1); if(NULL == str) { printf("Kein virtueller RAM mehr vorhanden ... !"); return EXIT_FAILURE; } /* Hinten anhängen */ strcat(str, puffer); } printf("Ihre Eingabe lautete: \n"); printf("%s", str); free(str); return EXIT_SUCCESS; } Beim char-Array läuft es so ähnlich ab wie schon im Beispiel mit den int-Werten zuvor. Sie müssen allerdings immer darauf achten, dass bei erneuter Speicheranforderung mit realloc() das Stringende-Zeichen berücksichtigt wird (+1). Ansonsten ist der Vorgang recht simpel: String einlesen, Zeichen zählen, erneut Speicher reservieren und hinten anhängen. Die Funktion alloca() ist nicht vom ANSI-C-Standard vorgeschrieben. Da diese Funktion bei vielen Compilern vorhanden ist, soll sie hier kurz erwähnt werden. Die Syntax zu alloca() lautet: > void *alloca(size_t size); Bei Linux/UNIX befindet sich alloca() in der Headerdatei <stdlib.h>, und unter MS-DOS/Windows sollte sich diese Funktion in der Headerdatei <malloc.h> befinden. alloca() kann bezüglich der Verwendung mit malloc() verglichen werden, aber mit dem Unterschied, dass alloca() den Speicherplatz nicht vom Heap, sondern vom Stack anfordert. Die Funktion alloca() vergröÃert den Stack-Bereich (Stack Frame) der aktuellen Funktion. alloca() hat auÃerdem den Vorteil, dass der Speicherplatz nicht extra mit free() freigegeben werden muss, da dieser automatisch beim Verlassen der Funktion freigegeben wird. Ganz im Gegenteil, es darf hierbei nicht einmal »gefree()t« werden, da der alloca()-Block nicht von dem malloc()-Pool kommt, sondern eben vom Stack. Ein free() hätte dabei böse Folgen. Die Funktion alloca() wird ansonsten genauso verwendet wie die Funktion malloc(). ## 14.10 »free()« – Speicher wieder freigeben Die Syntax der Funktion zur Freigabe von Speicher lautet: > #include <stdlib.h> void free(void *zeiger); free() wurde bereits des Ãfteren verwendet. Diese Funktion dient zur Freigabe von Speicher, der zuvor mit Funktionen wie malloc(), calloc() oder realloc() angefordert wurde. Folgendes sollten Sie bei dieser Funktion aber noch beachten: * Falls ein Speicherbereich freigegeben wird, der nicht zuvor mit malloc(), calloc() oder realloc() alloziert wurde, kann dies katastrophale Folgen haben. Die ganze Speicherverwaltung kann so aus dem Tritt gebracht werden. Daher sollten Sie darauf achten, dass wirklich nur Speicherplatz freigegeben wird, der auch alloziert wurde. * Speicher, den Sie mit free() freigeben, wird während der Laufzeit des Prozesses nicht wirklich an den Kern zurückgegeben, sondern in einem sogenannten malloc()-Pool gehalten, um bei Bedarf während des laufenden Prozesses wieder darauf zurückgreifen zu können. Erst, wenn der Prozess beendet wurde, geht der Speicher wieder zurück an den Kern. Beim Allozieren des Speichers mit malloc() wird der Aspekt, den Speicher wieder freizugeben, häufig vernachlässigt. In den Beispielen dieses Buchs dürfte ein vergessenes free() nicht allzu tragisch sein, da ein Programm, das sich beendet, seinen Speicherplatz gewöhnlich automatisch wieder freigibt (bei einem gut programmierten Betriebssystem). Schlimmer dürfte der Fall aber bei sogenannten Server-Programmen sein, die oft wochen- bzw. jahrelang laufen müssen. Das Programm wird zwangsweise immer langsamer. Man spricht dabei von Memory Leaks (Speicherlecks). Das passiert sicherlich nur Anfängern? Das ist leider ganz und gar nicht so. Nicht umsonst verdienen sich viele Softwarehersteller eine goldene Nase mit Programmen, die solche und andere Programmierfehler entdecken. Memory Leaks gehören neben Buffer Overflows zu den Fehlern, die C-Programmierer am häufigsten machen. Mehr zu Memory Leaks finden Sie im gleichnamigen Abschnitt 27.2. # 14.11 Zweidimensionale dynamische Arrays ## 14.11 Zweidimensionale dynamische Arrays In Abschnitt 12.9 haben Sie gelesen, dass das Anwendungsgebiet von Zeigern auf Zeiger unter anderem das dynamische Erstellen von Matrizen ist. Ich will Sie jetzt nicht quälen und als Thema die Matrizenberechnung nehmen, sondern ich werde nur einfache Speicherreservierungen mit Zeilen und Spalten vornehmen: > int matrix[zeile][spalte]; Um also für ein zweidimensionales Array mit beliebig vielen Zeilen und Spalten Speicher zu reservieren, benötigen Sie zuerst Platz für die Zeile. Und zu jeder dieser Zeilen wird nochmals Platz für die Spalte benötigt. Beim Freigeben des Speichers muss dies in umgekehrter Reihenfolge geschehen. Hier folgt das vollständige Listing dazu: > /* 2D_dyn_array.c */ #include <stdio.h> #include <stdlib.h> #define BUF 255 int main(void) { int i, j, zeile, spalte; /* Matrix ist Zeiger auf int-Zeiger. */ int ** matrix; printf("Wie viele Zeilen : "); scanf("%d", &zeile); printf("Wie viele Spalten: "); scanf("%d", &spalte); /* Speicher reservieren für die int-Zeiger (=zeile) */ matrix = malloc(zeile * sizeof(int *)); if(NULL == matrix) { printf("Kein virtueller RAM mehr vorhanden ... !"); return EXIT_FAILURE; } /* jetzt noch Speicher reservieren für die einzelnen Spalten * der i-ten Zeile */ for(i = 0; i < zeile; i++) { matrix[i] = malloc(spalte * sizeof(int)); if(NULL == matrix[i]) { printf("Kein Speicher mehr fuer Zeile %d\n",i); return EXIT_FAILURE; } } /* mit beliebigen Werten initialisieren */ for (i = 0; i < zeile; i++) for (j = 0; j < spalte; j++) matrix[i][j] = i + j; /* matrix[zeile][spalte] */ /* Inhalt der Matrix entsprechend ausgeben */ for (i = 0; i < zeile; i++) { for (j = 0; j < spalte; j++) printf("%d ",matrix[i][j]); printf("\n"); } /* Speicherplatz wieder freigeben. * Wichtig! In umgekehrter Reihenfolge. */ /* Spalten der i-ten Zeile freigeben */ for(i = 0; i < zeile; i++) free(matrix[i]); /* Jetzt können die leeren Zeilen freigegeben werden. */ free(matrix); return EXIT_SUCCESS; } Zugegeben, das Listing hat es in sich. Für einige dürfte es etwas undurchsichtig erscheinen, wie aus **matrix nun matrix[zeile][spalte] wird. Am besten sehen Sie sich einfach einmal an, was bei folgender Speicherreservierung geschehen ist: > matrix = malloc(zeile * sizeof(int)); Als Beispiel soll eine 4Ã3-Matrix erstellt werden, also vier Zeilen und drei Spalten. Abbildung 14.9 Reservierung des Speichers für die Zeile (erste Dimension) Nachdem Sie den Speicher für die einzelnen Zeilen reserviert haben, können Sie als Nächstes Speicher für die einzelnen Spalten reservieren. > for(i = 0; i < zeile; i++) { matrix[i] = malloc(spalte * sizeof(int)); if(NULL == matrix[i]) { printf("Kein Speicher mehr fuer Zeile %d\n",i); return EXIT_FAILURE; } } Somit ergibt sich im Speicher dann das finale Bild aus Abbildung 14.10. Abbildung 14.10 Nach der Reservierung des Speichers für die Spalte Sicherlich erinnern Sie sich noch an die Demonstration des gleichwertigen Zugriffs auf ein Speicherobjekt mithilfe eines Zeigers und eines Arrays in Kapitel 12, »Zeiger (Pointer)«. Auch bei den Zeigern auf Zeiger und den zweidimensionalen Arrays gibt es einige äquivalente Fälle. Sie finden sie in Tabelle 14.2 aufgelistet. Zugriff auf  | Möglichkeit 1 | Möglichkeit 2 | Möglichkeit 3 | | --- | --- | --- | --- | | | | | | | | | | | | | | | | | # 14.12 Wenn die Speicherallokation fehlschlägt Date: 2014-12-01 Categories: Tags: ## 14.12 Wenn die Speicherallokation fehlschlägt In den vergangenen Abschnitten wurde die Speicherallokation folgendermaÃen verwendet: > /* nomem1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int *ptr; ptr = malloc(100); if(NULL == ptr) { printf("Kein virtueller RAM mehr vorhanden ... !"); return EXIT_FAILURE; } return EXIT_SUCCESS; } Auf den ersten Blick scheint dieser Code auch in Ordnung zu sein. Es wird überprüft, ob die Funktion malloc() erfolgreich Speicher allozieren konnte. Stellen Sie sich jetzt vor, Sie arbeiten an einem Textverarbeitungsprogramm und haben ein paar Seiten Text zusammengestellt, den es jetzt abzuspeichern gilt. Das Programm alloziert noch Speicherplatz für den gesamten Text, bevor dieser in eine Datei abgespeichert werden kann. Jetzt, in diesem Moment, schreibt das Programm die Fehlerausgabe auf den Bildschirm und beendet sich. Der Text ist futsch und die Nerven des Anwenders auch. Es ist also kein guter Stil, ein Programm einfach zu beenden, wenn die Speicherallokation fehlschlägt. Hier folgen jetzt einige theoretische Tipps dazu, was Sie tun können, wenn eine Speicheranforderung nicht erfüllt werden konnte. ### 14.12.1 Speicheranforderung reduzieren Kann partout kein Speicherblock einer bestimmten GröÃe angefordert werden, sollten Sie die Speicheranforderung ein wenig reduzieren. Vielleicht kann das System einfach keinen groÃen zusammenhängenden Block finden. Wie Sie die erneute Speicheranforderung reduzieren, bleibt Ihnen selbst überlassen. Eine Möglichkeit wäre es, den angeforderten Speicher durch zwei zu teilen. Ein Beispiel dazu: > /* red_mem.c */ #include <stdio.h> #include <stdlib.h> #define MIN_LEN 256 int main(void) { int *ptr; char jn; static size_t len = 8192; /* Speicheranforderung */ do { ptr = malloc(len); /* Speicher konnte nicht alloziert werden. */ if(ptr == NULL) { len /= 2; /* Versuchen wir es mit der Hälfte. */ ptr = malloc(len); if(ptr == NULL) { printf("Konnte keinen Speicher allozieren. " " Weiter versuchen? (j/n): "); scanf("%c", &jn); fflush(stdin); } } else /* Erfolg. Speicherreservierung - Schleifenende */ break; /* so lange weiterprobieren, bis 'n' gedrückt wurde oder * len weniger als MIN_LEN beträgt */ } while(jn != 'n' && len > MIN_LEN); if(len <= MIN_LEN) printf("Speicheranforderung abgebrochen!!\n"); return EXIT_SUCCESS; } Gelingt die Speicheranforderung hierbei nicht, wird der angeforderte Speicher um die Hälfte reduziert. Bei einem erneuten Versuch und eventuellem Scheitern wird der angeforderte Speicher wieder um die Hälfte reduziert. Dies setzt sich so lange fort, bis MIN_LEN Speicherplatzanforderung unterschritten wird oder der Anwender zuvor mit dem Buchstaben 'n' abbrechen will. Dies ist natürlich nur eine von vielen Strategien, die Sie anwenden können. ### 14.12.2 Speicheranforderungen aufteilen So einfach wie im Beispiel eben werden Sie es aber höchstwahrscheinlich nicht haben. Was ist, wenn die Länge eines Strings oder die GröÃe einer Struktur bereits feststeht? Sie können nicht für einen String der Länge n einfach n/2 Bytes Speicherplatz anfordern. SchlieÃlich soll ja nicht nur der halbe Text gespeichert werden. Wenn es Ihnen dabei nicht allzu sehr auf die Geschwindigkeit ankommt, könnten Sie die Funktion realloc() verwenden: > /* more_mem.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUF 8192 int main(void) { char *buffer; int reserviert=0; int i; static size_t len = BUF; /* Speicheranforderung */ buffer = malloc(sizeof("Hallo Welt")); strcpy(buffer, "<NAME>"); while(reserviert != BUF && len != 0) { buffer = realloc(buffer, len); /* Speicher konnte nicht alloziert werden. */ if(buffer == NULL) { len /= 2; /* Versuchen wir es mit der Hälfte. */ } else { reserviert += len; } } for(i = 0; i < reserviert; i++) buffer[i] = 'x'; buffer[i]='\0'; printf("\n%s\n",buffer); return EXIT_FAILURE; } Dieses Listing erweist sich als ein hartnäckiger Fall der Speicherallokation. Im String buffer soll zusätzlicher Speicherplatz von 8192 Bytes reserviert werden. Gelingt dies nicht, teilt das Programm diesen Happen in zwei Teile auf und versucht es erneut. Diese Aufteilung geht so weit, dass eventuell byteweise Speicherplatz reserviert wird. Damit Sie auch eine Abbruchbedingung im Programm haben, wird die Anzahl des erfolgreich reservierten Speichers mitgezählt. Die Funktion realloc() wird dazu verwendet, dass der neu allozierte Speicher jeweils hinten angefügt wird. ### 14.12.3 Einen Puffer konstanter GröÃe verwenden Das Problem hat vielleicht nichts mit der dynamischen Speicherallokation zu tun, aber manches Mal ist die dynamische Speicherreservierung fehl am Platze. Ãberdenken Sie das Programm dahingehend, ob es nicht sinnvoller wäre, ein char-Array konstanter GröÃe zu verwenden. Ein einfaches Beispiel ist das Kopieren zweier Dateien. ### 14.12.4 Zwischenspeichern auf Festplatte vor der Allokation Wenn möglich, sollten Sie vor zeitkritischen oder umfangreichen Speicherallokationen Daten auf die Festplatte zwischenspeichern. Sie könnten zum Beispiel sehr viel früher im Programm Speicher dafür allozieren. Bevor eine umfangreiche Allokation für kritische Daten erfolgt, können Sie diesen Speicher verwenden, um Daten darin zwischenzuspeichern und auf die Festplatte zu schreiben. Im Allgemeinen gilt es, nur so viele Daten im virtuellen Speicher (RAM) zu beherbergen, wie auch wirklich nötig sind. Eine weitere Strategie ist es, vor einer Speicherallokation einen bereits reservierten Speicherbereich auf die Festplatte zu schreiben (temporäre Datei) und diesen Speicherblock für die nachfolgende Allokation freizugeben. Womit wir auch gleich beim nächsten Punkt wären. ### 14.12.5 Nur so viel Speicher anfordern wie nötig Um eine optimale Speicherausnutzung zu erhalten, sollten Sie mit dem Speicher geizen wie Dagobert Duck mit seinen Talern. Wenn immer nur der benötigte Speicher oder kleine Speicherblöcke angefordert werden, erreichen Sie auÃerdem die beste Performance. Speicher sparen können Sie schon bei der Auswahl des Datentyps bei der Entwicklung des Programms. Benötigen Sie zum Beispiel unbedingt einen double-Wert im Programm? Reicht ein float nicht aus? Bei umfangreichen Strukturen sollten Sie sich fragen, ob alle Strukturelemente wirklich erforderlich sind. Müssen Berechnungen zwischengespeichert werden? Ein Beispiel ist der Matrixzugriff von matrix[x][y]. Das Ergebnis müsste dabei nicht gespeichert werden. Sie können auch einen Funktionsaufruf vornehmen, der Ihnen das berechnet (matrix(x, y)). # 15.2 Initialisierung und Zugriff auf Strukturen ## 15.2 Initialisierung und Zugriff auf Strukturen Auf die einzelnen Variablen einer Struktur greifen Sie mithilfe des Punktoperators (.) zu. Ansonsten erfolgen die Initialisierung und der Zugriff wie bei normalen Variablen. Beispielsweise: > /* struct1.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> struct index { int seite; char titel[30]; }; int main(void) { struct index lib; lib.seite = 23; strcpy(lib.titel, "C-Programmieren"); printf("%d, %s\n",lib.seite, lib.titel); return EXIT_SUCCESS; } Abbildung 15.2 Strukturelemente wurden mit Werten initialisiert. Mit > struct index lib; wird eine Struktur mit der Bezeichnung lib vom Typ index deklariert. Diese Extra-Deklaration hätten Sie auch mit folgender Schreibweise erzielt: > struct index { int seite; char titel[30]; } lib; Wenn Sie den Typnamen dieser Struktur nicht benötigen, kann sie auch ohne deklariert werden: > struct { int seite; char titel[30]; } lib; Es spricht auch nichts dagegen, mehrere Typen auf einmal zu deklarieren: > struct index { int seite; char titel[30]; } lib1, lib2, lib3; Hiermit wurden drei Variablen vom Typ index deklariert. Strukturen können natürlich ebenso wie normale Datentypen direkt bei der Deklaration mit Werten initialisiert werden: > struct index { int seite; char titel[30]; } lib = { 308, "Strukturen" }; Oder auch bei der Deklaration in der main()-Funktion: > struct index lib = { 55, "Einführung in C" }; Zur Demonstration folgt ein Listing, das zeigt, wie Sie auf den Inhalt einer Struktur zugreifen können: > /* struct2.c */ #include <stdio.h> #include <stdlib.h> #define MAX 30 struct adres { char vname[MAX]; char nname[MAX]; long PLZ; char ort[MAX]; int geburtsjahr; } adressen; /* Funktion zur Ausgabe des Satzes */ void ausgabe(struct adres x) { printf("\n\nSie gaben ein:\n\n"); printf("Vorname.........:%s", x.vname); printf("Nachname........:%s", x.nname); printf("Postleitzahl....:%ld\n",x.PLZ); printf("Ort.............:%s", x.ort); printf("Geburtsjahr.....:%d\n", x.geburtsjahr); } int main(void) { printf("Vorname : "); fgets(adressen.vname, MAX, stdin); printf("Nachname : "); fgets(adressen.nname, MAX, stdin); printf("Postleitzahl : "); do { scanf("%5ld",&adressen.PLZ); } while(getchar()!= '\n'); printf("Wohnort : "); fgets(adressen.ort, MAX, stdin); printf("Geburtsjahr : "); do { scanf("%4d",&adressen.geburtsjahr); } while(getchar()!='\n' ); ausgabe(adressen); return EXIT_SUCCESS; } Abbildung 15.3 Einlesen und Ausgeben von Strukturen Die erste Eingabe in der main()-Funktion lautet: > fgets(adressen.vname, MAX, stdin); Damit wird der Vorname eingelesen. Der Zugriff erfolgt über den Namen der Struktur, gefolgt vom Punktoperator. Dahinter folgt das entsprechende Strukturelement, das diese Daten erhalten soll. Dies funktioniert genauso, wenn Sie einen String direkt mit der Funktion strcpy() in ein Strukturelement einkopieren wollen: > strcpy(adressen.vname , "Tux"); Die direkte Initialisierung numerischer Werte an Strukturelementen lässt sich ebenfalls variablentypisch durchführen: > adressen.PLZ = 89000; Wenn Sie alle Strukturelemente eingegeben haben, wird die Funktion ausgabe() aufgerufen: > ausgabe(adressen); Als Argument erhält diese Funktion die Struktur adressen. Danach werden die einzelnen Elemente der Struktur auf dem Bildschirm ausgegeben. Eine weitere Möglichkeit, die Struktur im Listing sofort mit einem Inhalt zu initialisieren, ist diese: > stuct adres { char vname[20]; char nname[20]; long PLZ; char ort[20]; int geburtsjahr; } adressen = {"Ernest", "Hemming" ,3434, "Havanna" ,1913}; Folgende Wertzuweisung von Strukturen sollten Sie allerdings vermeiden: > struct { int a1; int a2; int a3; } werte1, werte2; werte1.a1 = 8; werte1.a2 = 16; werte1.a3 = 32; werte2 = werte1; // Bitte vermeiden Sie solche Zuweisungen. Das ist in C zwar erlaubt, kann aber zu Fehlern führen, wenn ein Compiler dies nicht unterstützt. Sicherer wäre die folgende Möglichkeit: > memcpy(&werte2, &wert1, sizeof(werte1)); Dies soll nur ein Hinweis sein und keine Vorschrift! Es folgt ein kleiner Tipp, wie Sie sich die Strukturen vielleicht noch besser vorstellen können. Als Vergleich dienen dazu die Variablen int x und char c (siehe Tabelle 15.1). Typ | Name | | --- | --- | | | | | | | Wird die Variable x mit einem Wert initialisiert, gehen Sie bekannterweise so vor: > x = 1999; Bei einer Struktur kommt noch ein kleiner Zusatz hinzu: > adressen.geburtsjahr = 1999; # Bestimmte Elemente initialisieren Ab dem C99-Standard ist es auch möglich, nur bestimmte Elemente einer Struktur zu initialisieren. Als Initialisierer wird hierbei ein sogenannter Elementbezeichner verwendet. Verwenden wir beispielsweise nochmals folgende Struktur: > stuct adres { char vname[20]; char nname[20]; long PLZ; char ort[20]; int geburtsjahr; }; Sind Ihnen in diesem Fall z. B. nur die Angaben zum Nachnamen und Ort bekannt, können Sie folgendermaÃen die Elemente nname und ort initialisieren: > struct adres adressen = { .nname = "Wolf", .ort = "Mering" }; Um also bestimmte Elemente in einer Struktur zu initialisieren, sieht der Elementebezeichner für ein Strukturelement immer folgendermaÃen aus: > .strukturelement = wert // Elementbezeichner Selbst auf die Reihenfolge müssen Sie hierbei nicht achten. Sie können also auch folgendermaÃen bestimmte Elemente der Struktur mit dem Elementbezeichner initialisieren: > struct adres adressen = { .ort = "Mering", .PLZ = 12345, .nname = "Wolf", }; Geben Sie die Elemente in der vorgegebenen Reihenfolge an, können Sie natürlich wieder auf dem Elementbezeichner verzichten. Kennen Sie beispielsweise in unserer Beispielstruktur den Vornamen, Nachnamen und den Wohnort, können Sie auf die Angaben von .vname und .nname verzichten, weil diese jeweils das erste und zweite Element in der Struktur sind. Erst für .ort benötigen Sie wieder einen Elementbezeichner. Hier das Beispiel: > struct adres adressen = { "Jürgen", // geht automatisch an vname "Wolf", // geht automatisch an nname .ort = "Mering" // nötig, weil das 3. Element PLZ ist }; Das funktioniert natürlich auch anders. Kennen Sie beispielsweise nur die Postleitzahlen, den Ort und das Geburtsjahr, brauchen Sie nur den Elementbezeichner von .PLZ verwenden. Die restlichen beiden Angaben können Sie, in der richtigen Reihenfolge gesetzt, wieder ohne Elementbezeichner verwenden: > struct adres adressen = { .PLZ = 1234, "Mering", // geht autmatisch an ort 1974 // geht automatisch an geburtsjahr }; Zum Schluss stellt sich noch die Frage, was mit den Strukturelementen passiert, die nicht initialisiert wurden? Alle diese Elemente ohne einen Initialisierer bekommen automatisch den Wert 0. Hierzu folgt noch ein einfaches Beispiel, das die Möglichkeit demonstrieren soll, bestimmte Elemente einer Struktur zu initialisieren: > /* struct_init_c99.c */ #include <stdio.h> #include <stdlib.h> #define MAX 30 struct adres { char vname[MAX]; char nname[MAX]; long PLZ; char ort[MAX]; int geburtsjahr; }; /*Funktion zur Ausgabe des Satzes*/ void ausgabe(struct adres x) { printf("\n\nSie gaben ein:\n\n"); printf("Vorname.........:%s\n", x.vname); printf("Nachname........:%s\n", x.nname); printf("Postleitzahl....:%ld\n",x.PLZ); printf("Ort.............:%s\n", x.ort); printf("Geburtsjahr.....:%d\n", x.geburtsjahr); } int main(void) { struct adres adressen1 = { "Jürgen", "Wolf", .ort = "Mering" }; struct adres adressen2 = { .ort = "Mering", .PLZ = 1234, .nname = "Wolf", }; struct adres adressen3 = { .PLZ = 1234, "Mering", 1974 }; ausgabe(adressen1); ausgabe(adressen2); ausgabe(adressen3); return EXIT_SUCCESS; } # 15.3 Strukturen als Wertübergabe an eine Funktion ## 15.3 Strukturen als Wertübergabe an eine Funktion Anhand des Funktionsaufrufs vom Beispiel zuvor konnten Sie sehen, dass Strukturen genauso wie jeder andere Datentyp per call-by-value an Funktionen übergeben werden können. Die Funktion bekommt dabei eine Kopie der vollständigen Struktur übergeben. Das Anlegen einer Kopie kann bei häufigen Funktionsaufrufen mit umfangreichen Strukturen die Laufzeit des Programms erheblich beeinträchtigen. Um diesen Mehraufwand zu sparen, empfehle ich Ihnen, Zeiger auf Strukturen als Parameter zu verwenden. Das folgende Listing soll dies demonstrieren: > /* struct3.c */ #include <stdio.h> #include <stdlib.h> #define MAX 30 struct adres { char vname[MAX]; char nname[MAX]; long PLZ; char ort[MAX]; int geburtsjahr; } adressen; /* Funktion zur Ausgabe des Satzes */ void ausgabe(struct adres *struct_ptr) { printf("\n\nSie gaben ein:\n\n"); printf("Vorname.........:%s",(*struct_ptr).vname); printf("Nachname........:%s",(*struct_ptr).nname); printf("Postleitzahl....:%ld\n",(*struct_ptr).PLZ); printf("Ort.............:%s",(*struct_ptr).ort); printf("Geburtsjahr.....:%d\n",(*struct_ptr).geburtsjahr); } int main(void) { printf("Vorname : "); fgets(adressen.vname, MAX, stdin); printf("Nachname : "); fgets(adressen.nname, MAX, stdin); printf("Postleitzahl : "); do { scanf("%5ld",&adressen.PLZ); } while(getchar()!= '\n'); printf("Wohnort : "); fgets(adressen.ort, MAX, stdin); printf("Geburtsjahr : "); do { scanf("%4d",&adressen.geburtsjahr); } while(getchar()!='\n' ); ausgabe(&adressen); return EXIT_SUCCESS; } Dies ist dasselbe Listing wie oben, nur wird dieses Mal das Argument der Funktion ausgabe() mit call-by-reference übergeben: > ausgabe(&adressen); Die Funktion ausgabe() selbst musste dabei auch ein wenig verändert werden: > void ausgabe(struct adres *struct_ptr) { printf("\n\nSie gaben ein:\n\n"); printf("Vorname.........:%s",(*struct_ptr).vname); printf("Nachname........:%s",(*struct_ptr).nname); printf("Postleitzahl....:%ld\n",(*struct_ptr).PLZ); printf("Ort.............:%s",(*struct_ptr).ort); printf("Geburtsjahr.....:%d\n",(*struct_ptr).geburtsjahr); } AuÃer dem Zeiger struct_ptr als Parameter, der auf eine Struktur vom Typ adress zeigen kann, musste auch der Zugriff auf die Strukturelemente geändert werden. Dass Sie bei Call-by-reference-Variablen mit dem Dereferenzierungsoperator arbeiten müssen, ist Ihnen ja bekannt. Da aber hier der Punktoperator verwendet wird, muss der Referenzzeiger struct_ptr zwischen zwei Klammern gestellt werden, da der Ausdruck zwischen den Klammern die höhere Bindungskraft hat und zuerst ausgewertet wird: > printf("Vorname.........:%s",(*struct_ptr).vname); Die Hersteller von C haben aber auch gemerkt, dass eine solche Schreibweise – speziell dann, wenn mehrere Referenzen folgen – schwer lesbar ist. Daher wurde der sogenannte Elementkennzeichnungsoperator (->) eingeführt. Mit diesem würde die Ausgabe des Vornamens folgendermaÃen vorgenommen werden: > printf("Vorname.........:%s", struct_ptr->vname; Dies lässt sich auch recht einfach lesen, da dieser Operator wie ein Pfeil oder auch ein Zeiger aussieht. Diesen Operator werden Sie noch häufiger in diesem Buch benötigen, als Ihnen lieb sein wird – speziell, wenn es um die dynamischen Datenstrukturen geht (siehe das gleichnamige Kapitel 21). # 15.4 Strukturen als Rückgabewert einer Funktion ## 15.4 Strukturen als Rückgabewert einer Funktion Wie bei der Werteübergabe von Strukturen sollten Sie auch bei der Werterückgabe von Strukturen Zeiger verwenden. Dafür soll wieder das eben geschriebene Listing verwendet werden. Es fehlt nämlich noch eine Funktion zur Eingabe der einzelnen Strukturelemente. Hier sehen Sie das Listing mit der Funktion eingabe(), die die Anfangsadresse der Struktur zurückgibt: > /* struct4.c */ #include <stdio.h> #include <stdlib.h> #define MAX 30 struct adres { char vname[MAX]; char nname[MAX]; long PLZ; char ort[MAX]; int geburtsjahr; }; /* Funktion zur Ausgabe des Satzes */ void ausgabe(struct adres *struct_ptr) { printf("\n\nSie gaben ein:\n\n"); printf("Vorname.........:%s",struct_ptr->vname); printf("Nachname........:%s",struct_ptr->nname); printf("Postleitzahl....:%ld\n",struct_ptr->PLZ); printf("Ort.............:%s",struct_ptr->ort); printf("Geburtsjahr.....:%d\n",struct_ptr->geburtsjahr); } struct adres *eingabe(void) { static struct adres *adressen; adressen = malloc(sizeof(struct adres)); printf("Vorname : "); fgets(adressen->vname, MAX, stdin); printf("Nachname : "); fgets(adressen->nname, MAX, stdin); printf("Postleitzahl : "); do {scanf("%ld",&adressen->PLZ);} while(getchar()!= '\n'); printf("Wohnort : "); fgets(adressen->ort, MAX, stdin); printf("Geburtsjahr : "); do { scanf("%d",&adressen->geburtsjahr); }while(getchar()!='\n' ); return adressen; } int main(void) { struct adres *adresse1, *adresse2; adresse1=eingabe(); adresse2=eingabe(); ausgabe(adresse1); ausgabe(adresse2); return EXIT_SUCCESS; } Bei diesem Listing verwenden Sie bereits nur noch Zeiger und kommen zum ersten Mal mit den dynamischen Datenstrukturen in Berührung. Aufgerufen wird diese Funktion zur Eingabe von Strukturelementen mit: > adresse1 = eingabe(); Einen Adressoperator benötigen Sie hier nicht, da Sie ja bereits einen Zeiger verwenden. Und da Sie hier einen Zeiger verwenden, benötigen Sie in der Funktion erst einmal Speicherplatz für eine Struktur. Dieser wird mit der Funktion malloc() angefordert: > static struct adres *adressen; adressen = malloc(sizeof(struct adres)); Jetzt können Sie mithilfe des Elementkennzeichnungsoperators die Daten der einzelnen Strukturelemente einlesen. Am Ende der Funktion wird die Adresse dieser reservierten und mit neuem Inhalt versehenen Struktur mit return an den Aufrufer zurückgegeben. In der main()-Funktion zeigt jetzt der Zeiger adresse1 auf diesen Speicherbereich. Hinweis für Anfänger | | --- | | Natürlich lässt sich eine Funktion mit Strukturen als Rückgabewert auch einfacher deklarieren: > struct typNAME Funktionsname() # 15.5 Strukturen vergleichen ## 15.5 Strukturen vergleichen Es gibt leider keinen portablen oder sinnvollen Weg, um zwei Strukturen direkt miteinander zu vergleichen. Das Problem besteht darin, dass ein Compiler aus Optimierungsgründen Lücken zwischen den einzelnen Elementen lassen kann. Mehr zu diesem sogenannten Padding erfahren Sie in Abschnitt 15.12, »Attribute von Strukturen verändern (nicht ANSI C)«. Es bleibt Ihnen also letztendlich nichts anderes übrig, als eine eigene Funktion zu schreiben. Hier sehen Sie ein Beispiel dafür, wie Sie vorgehen können: > /* struct5.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 30 struct adres { char vname[MAX]; char nname[MAX]; long PLZ; char ort[MAX]; int geburtsjahr; }; int cmp_structs(struct adres *str1, struct adres *str2) { /* Vorname gleich und */ if(strcmp(str1->vname, str2->vname) == 0 && /* Nachname gleich und */ strcmp(str1->nname, str2->nname) == 0 && /* Postleitzahl gleich und */ (str1->PLZ-str2->PLZ) == 0 && /* Wohnort gleich und */ strcmp(str1->ort, str2->ort) == 0 && /* geburtsjahr gleich */ (str1->geburtsjahr-str2->geburtsjahr) == 0) return 0; /* Beide Strukturen gleich */ else return 1; /* Strukturen nicht gleich */ } int main(void) { struct adres adresse1={"John","Leroy",1234,"New York",1980 }; struct adres adresse2={"John","Leroy",1234,"New York",1980 }; if(cmp_structs(&adresse1, &adresse2) == 0) printf("Beide Strukturen sind gleich?!?!\n"); else printf("Die Strukturen weisen Unterschiede auf\n"); return EXIT_SUCCESS; } # 15.6 Arrays von Strukturen ## 15.6 Arrays von Strukturen Bei Arrays von Strukturen gilt dasselbe Prinzip wie im Abschnitt zuvor dargestellt. Die Wertzuweisung funktioniert ebenfalls wie bei den normalen Arrays, nämlich mithilfe des Indizierungsoperators ([]). Hierzu ein Beispiel: > /* struct_arr1.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> struct index { int seite; char titel[30]; }; int main(void) { int i; struct index lib[3]; lib[0].seite=312; strcpy(lib[0].titel, "Arrays von Strukturen"); lib[1].seite=320; strcpy(lib[1].titel, "Strukturen in Strukturen"); lib[2].seite=900; strcpy(lib[2].titel, "Anhang"); for(i=0; i<3; i++) printf("Seite %3d\t %-30s\n", lib[i].seite, lib[i].titel); return EXIT_SUCCESS; } Abbildung 15.4 Array von Strukturen Abbildung 15.4 verdeutlicht dies nochmals. Auch hierbei erfolgt die Initialisierung der einzelnen Werte über den Punktoperator. Ein Fehler, der dabei oft gemacht wird, ist folgende falsche Wertübergabe: > // falsche Position des Feldindex strcpy(lib.titel[1], "Hallo"); //falsch strcpy(lib[1].titel, "Hallo"); //richtig Der Variablenname der Struktur lautet schlieÃlich lib und nicht titel. Jetzt soll das Listing zur Adressverwaltung erweitert werden. Diesmal wird das Programm so umgeschrieben, dass es mit Arrays von Strukturen ausgeführt wird: > struct adres { /*Variablen*/ } adressen[100]; In dieser Struktur von Arrays lassen sich somit 100 Daten von Adressen speichern. Hier sehen Sie das vollständige Listing: > /* struct_arr2.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 30 static int x = 0; struct adres { char vname[MAX]; char nname[MAX]; long PLZ; char ort[MAX]; int geburtsjahr; } adressen[100]; void Eingabe(int nr, struct adres neu[]) { printf("Vorname : "); fgets(neu[nr].vname, MAX, stdin); printf("Nachname : "); fgets(neu[nr].nname, MAX, stdin); printf("Postleitzahl: "); do { scanf("%5ld",&neu[nr].PLZ); } while(getchar()!= '\n'); printf("Wohnort : "); fgets(neu[nr].ort, MAX, stdin); printf("Geburtsjahr : "); do { scanf("%4d",&neu[nr].geburtsjahr); }while(getchar()!= '\n'); } void Suche(struct adres search[], char buchstabe, int nr) { int i; for(i = 0; i <= nr; i++) { if(search[i].nname[0] == buchstabe) { printf("\n\nGefunden unter Buchstabe " ":\"%c\"\n\n", buchstabe); printf("Vorname......:%s",search[i].vname); printf("Nachname.....:%s",search[i].nname); printf("Postleitzahl.:%ld\n",search[i].PLZ); printf("Ort..........:%s",search[i].ort); printf("Geburtsjahr..:%d\n", search[i].geburtsjahr); printf("\n\tWeiter mit <ENTER>\n"); getchar(); } } } void Ausgabe(struct adres all[],int nr) { int i; for(i = 0; i < nr; i++) { printf("Vorname.........:%s",all[i].vname); printf("Nachname........:%s",all[i].nname); printf("Postleitzahl....:%ld\n",all[i].PLZ); printf("Ort.............:%s",all[i].ort); printf("Geburtsjahr.....:%d\n\n",all[i].geburtsjahr); if((!(i%2))&& i!=0) { printf("\n\tWeiter mit <Enter>\n\n"); getchar(); } } } void Sort(struct adres sort[], int nr) { int i,j; struct adres *temp; temp = malloc(sizeof(struct adres *)); if(NULL == temp) { printf("Konnte keinen Speicher reservieren...\n"); return; } for(i = 0; i < nr; i++) { for(j=i+1;j<nr;j++) { if(strcmp(sort[i].nname, sort[j].nname) > 0) { *temp=sort[j]; sort[j]=sort[i]; sort[i]=*temp; } } } printf(".....Sortiert!!\n\n"); } int main(void) { int auswahl; char c; do { printf("-1- Neue Adresse eingeben\n"); printf("-2- Bestimmte Adresse ausgeben\n"); printf("-3- Alle Adressen ausgeben\n"); printf("-4- Adressen sortieren\n"); printf("-5- Programm beenden\n"); printf("\nIhre Auswahl : "); scanf("%d",&auswahl); /* fflush(stdin); */ getchar(); switch(auswahl) { case 1 : Eingabe(x++,adressen); break; case 2 : printf("Anfangsbuchstabe des Nachnamens :"); do { scanf("%c",&c); } while(getchar()!= '\n'); Suche(adressen,c,x); break; case 3 : Ausgabe(adressen,x); break; case 4 : Sort(adressen,x); break; case 5 : printf("Ende....\n"); break; default: printf("Falsche Eingabe\n"); } }while(auswahl <5); return EXIT_SUCCESS; } Der erste Funktionsaufruf des Programms lautet: > Eingabe(x++, adressen); Damit wird die Funktion Eingabe() zur Eingabe eines Adresssatzes aufgerufen. Als Argument wird dieser Funktion die globale Variable x und die Struktur adressen vom Typ struct adres übergeben. Die globale Variable x dient als Zähler und Indexfeld und gibt an, wie viele und welche Strukturen gespeichert wurden. Der Funktionskopf sieht so aus: > void Eingabe(int nr, struct adres neu[]) Wenn Sie das Buch genau durchgelesen haben, wissen Sie, dass Sie auch folgende Schreibweise hätten verwenden können: > /* struct adres *neu und struct adres neu[]==call-by-reference */ void Eingabe(int nr, struct adres *neu) Jetzt werden die ersten Daten in die Struktur eingegeben: > printf("Vorname : "); fgets(neu[nr].vname, MAX, stdin); fgets() liest den Vornamen des ersten Adresssatzes ein. Genauso werden auch die nächsten Daten an den einzelnen Strukturelementen übergeben. Danach können Sie einen zweiten Adresssatz eingeben. Benötigen Sie z. B. den Nachnamen des 20. Adresssatzes (falls vorhanden), können Sie diesen wie folgt ausgeben lassen: > printf("%s", adressen[19].nname); Die zweite Funktion des Programms lautet: > Suche(adressen, c, x); Sie stellt eine primitive Suchfunktion nach dem Anfangsbuchstaben des Nachnamens dar. Die Funktion erhält als Argument die Anfangsadresse des ersten Struktur-Arrays, den Anfangsbuchstaben des Nachnamens (c) und den Indexzähler für die Anzahl der vorhandenen Strukturen (x). > void Suche(struct adres search[], char buchstabe, int nr) Die Suche selbst ist relativ einfach aufgebaut: > for(i = 0; i <= nr; i++) { if(search[i].nname[0] == buchstabe) In der for-Schleife wird die Anzahl der vorhandenen Adressen hochgezählt, um jeden Adresssatz mit dem eingegebenen Anfangsbuchstaben des Nachnamens zu vergleichen. Als Beispiel sei der Buchstabe »M« gegeben. Der Programmablauf sieht damit folgendermaÃen aus: > for...i=0 if(search[0].nname[0] == 'M') falls ja, werden dessen Daten ausgegeben for..i++ ..i<=nr if(search[1].nname[0] == 'M') falls ja, werden dessen Daten ausgegeben for..i++..i<=nr if(search[2].nname[0] == 'M') usw. Diese Suchfunktion sucht nur anhand des ersten Buchstabens des Nachnamens. Bei der Suche nach ganzen Namen ist die Implementierung nicht viel komplizierter. Dazu verwenden Sie am besten die Funktion strcmp() aus der Headerdatei <string.h>. Die Funktion Ausgabe() ist die einfachste von allen. Hiermit wird lediglich der Indexzähler hochgezählt, um alle vorhandenen Adressen auf dem Bildschirm auszugeben. Als etwas schwieriger dürfte sich die Sortierfunktion erweisen: > void Sort(struct adres sort[], int nr) So wird ein Zeiger temp vom Typ struct adres * definiert: > struct adres *temp; temp = malloc(sizeof(struct adres *)); Dieser dient als temporärer Zwischenspeicher zum Austausch zweier Strukturen. Damit dieser Zwischenspeicher auch verwendet werden kann, muss Speicherplatz von der GröÃe der Struktur reserviert werden. Danach wird die Struktur mit dem Algorithmus Selektion Sort nach dem Anfangsbuchstaben des Nachnamens sortiert: > for(i = 0; i < nr; i++) { for(j=i+1;j<nr;j++) { if(strcmp(sort[i].nname, sort[j].nname) > 0) { *temp=sort[j]; sort[j]=sort[i]; sort[i]=*temp; } } } Bei den Strukturen von Arrays tritt irgendwann das gleiche Problem wie bei den Arrays auf. Nach 100 Adressen ist bei diesem Programmbeispiel Schluss. Dann müssen Sie sich wieder Gedanken über neuen Speicherplatz machen. Vom Aufwand einmal abgesehen, sind Struktur-Arrays eine erhebliche Bremse für ein Programm. Nehmen wie das Sortieren als Beispiel: Alle Elemente einer Struktur müssen erst in einen temporären, extra reservierten Speicher kopiert werden. Danach müsste Speicherplatz für neue Elemente der Struktur reserviert werden. Jetzt können Sie die Daten aus dem temporären Speicher wieder zurückkopieren, und zwar in den neu angelegten Speicher für Strukturen von Arrays – von dem Fall, dass ein Element mitten in der Liste gelöscht werden soll, ganz zu schweigen. SchlieÃlich müssen Sie diese Lücke auch wieder füllen. Somit müssten Sie z. B. alle Daten hinter dem gelöschten Element eine Position nach vorn setzen. Wenn dies bei einer Datenbank mit mehreren Tausend Adressen geschieht, wäre die Laufzeit katastrophal. Wie Sie diesen Aufwand umgehen und sich das Leben einfacher machen können, erfahren Sie in Kapitel 21, »Dynamische Datenstrukturen«. # 15.7 Strukturen in Strukturen (Nested Structures) ## 15.7 Strukturen in Strukturen (Nested Structures) Neben der Kombination von Arrays und Strukturen können auch Strukturen innerhalb von Strukturen verwendet werden. Ein einfaches Beispiel sind Uhrzeit und Datum: > struct uhrzeit { unsigned int stunde; unsigned int minute; unsigned int sekunde; }; struct datum { unsigned int tag; unsigned int monat; int jahr; }; struct termin { struct datum d; struct uhrzeit z; } t; Anhand von Abbildung 15.5 lässt sich deutlich erkennen, was »Strukturen in Strukturen« bedeutet. Es wird dabei auch von Nested Structures gesprochen. Abbildung 15.5 Strukturen in Strukturen Der Zugriff auf die einzelnen Strukturen ist ein wenig aufwendiger. Hier sehen Sie ein Programmbeispiel, wie auf die einzelnen Elemente und die gesamte Struktur zugegriffen werden kann: > /* nested_struct1.c */ #include <stdio.h> #include <stdlib.h> struct uhrzeit { unsigned int stunde; unsigned int minute; unsigned int sekunde; }; struct datum { unsigned int tag; unsigned int monat; int jahr; }; struct termin { struct datum d; struct uhrzeit z; } t; int main(void) { /* Termin am 19.12.2004 um 20:15 Uhr */ struct termin t = { {19, 12, 2004}, {20, 15, 0} }; printf("Termin am "); printf("%u.%u.%d um ", t.d.tag, t.d.monat, t.d.jahr); printf("%u.%u.%u0 Uhr \n\n", t.z.stunde, t.z.minute, t.z.sekunde); printf("Neuen Termin eingeben !!\n\n"); printf("Tag.............: "); scanf("%u",&t.d.tag); printf("Monat...........: "); scanf("%u",&t.d.monat); printf("Jahr............: "); scanf("%d",&t.d.jahr); printf("\n"); printf("Stunde..........: "); scanf("%u",&t.z.stunde); printf("Minuten.........: "); scanf("%u",&t.z.minute); printf("Sekunden........: "); scanf("%u",&t.z.sekunde); printf("\n"); printf("Neuer Termin am "); printf("%02u.%02u.%04d um ",t.d.tag, t.d.monat, t.d.jahr); printf("%02u.%02u.%02u Uhr \n", t.z.stunde, t.z.minute, t.z.sekunde); return EXIT_SUCCESS; } Dieser geringe Mehraufwand stellt eher eine Erleichterung dar. Zuerst werden in diesem Programm zur Demonstration die Werte direkt übergeben: > struct termin t = {{19,12,2004},{20,15,0}}; /* struct termin t = {{struct datum}{struct uhrzeit}} */ Danach werden die Werte über die Tastatur eingelesen, z. B. die Minuten: > scanf("%u", &t.z.minute); Das Listing wird kaum jemanden überfordern. Daher soll das Programm zur Adressverwaltung mit dem eben gezeigten Programm verbunden werden. Damit hätte die Struktur termin folgendes Aussehen: > struct termin { struct datum d; struct uhrzeit z; struct adressen a; } t[20]; Abbildung 15.6 Eine weitere Struktur wurde zur Struktur hinzugefügt. So können Sie 20 Termine mit Datum, Uhrzeit und der Adresse verwalten. Hier folgt das vollständige Listing: > /* nested_struct2.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 30 /* Zähler Termine */ static int dates = 0; /* Zähler Adressen */ static int nr = 0; struct uhrzeit { unsigned int stunde; unsigned int minute; unsigned int sekunde; }; struct datum { unsigned int tag; unsigned int monat; int jahr; }; struct adressen { char vname[MAX]; char nname[MAX]; long PLZ; char ort[MAX]; int geburtsjahr; } xyz[100]; struct termin { struct datum d; struct uhrzeit z; struct adressen a; } t[20]; /* Funktionsprototypen */ void newdate(struct termin *); int suche(char *); void listdate(struct termin *,int); void replacedate(struct termin *,int); void sortdate(struct termin *,int); void Eingabe(struct adressen *); void Ausgabe(struct adressen *); void Sortadress(struct adressen *); void newdate(struct termin *t) { int auswahl,ret; char such_name[MAX]; printf("Tag.......: "); scanf("%u",&t[dates].d.tag); printf("Monat.....: "); scanf("%u",&t[dates].d.monat); printf("Jahr......: "); scanf("%d",&t[dates].d.jahr); printf("---------------------\n"); printf("Stunde....: "); scanf("%u",&t[dates].z.stunde); printf("Minute(n).: "); scanf("%u",&t[dates].z.minute); printf("---------------------\n"); printf("\nTermin mit :\n -1- Neuer Adresse\n"); printf(" -2- Vorhandener Adresse\n"); printf("Ihre Auswahl : "); do { scanf("%d",&auswahl); } while(getchar()!= '\n'); if(auswahl == 1) { printf("Vorname.....: "); fgets(t[dates].a.vname, MAX, stdin); printf("Nachname....: "); fgets(t[dates].a.nname, MAX, stdin); printf("Postleitzahl: "); do { scanf("%ld",&t[dates].a.PLZ); } while(getchar()!= '\n'); printf("ORT.........: "); fgets(t[dates].a.ort, MAX, stdin); printf("Geburtsjahr..: "); do { scanf("%d",&t[dates].a.geburtsjahr); } while(getchar()!= '\n'); /* Neue Adresse kommt auch zum neuen Adresssatz. */ strcpy(xyz[nr].vname, strtok(t[dates].a.vname, "\n")); strcpy(xyz[nr].nname, strtok(t[dates].a.nname, "\n")); xyz[nr].PLZ = t[dates].a.PLZ; strcpy(xyz[nr].ort, t[dates].a.ort); xyz[nr].geburtsjahr=t[dates].a.geburtsjahr; dates++; nr++; } else { printf("Bitte geben Sie den Nachnamen ein : "); fgets(such_name, MAX, stdin); ret = suche(strtok(such_name,"\n")); if( ret == -1 ) { printf("Kein Eintrag vorhanden : %s ???", such_name); return; } strcpy(t[dates].a.vname,xyz[ret].vname); strcpy(t[dates].a.nname,xyz[ret].nname); t[dates].a.PLZ=xyz[ret].PLZ; strcpy(t[dates].a.ort,xyz[ret].ort); t[dates].a.geburtsjahr=xyz[ret].geburtsjahr; dates++; } } int suche(char *suchname) { int pos, found = 0; for(pos = 0; pos <= nr; pos++) { if(strcmp(xyz[pos].nname,suchname) == 0) { found = 1; break; } } if(found) return pos; else return -1; } void listdate(struct termin *list, int dates) { int i; for(i = 0; i < dates; i++) { printf("Nr. %d: ", i+1); printf("Termin am %02u.%02u.%04d ", list[i].d.tag, list[i].d.monat, list[i].d.jahr); printf("um %02u.%02u Uhr\n", list[i].z.stunde, list[i].z.minute); printf("mit %s %s\n\n", list[i].a.vname, list[i].a.nname); } } void replacedate(struct termin *aendern, int nt) { if(nt <= dates && nt < 20) { printf("Bitte neue Terminzeit eingeben!!\n"); printf("Tag..........: "); scanf("%u",&aendern[nt].d.tag); printf("Monat........: "); scanf("%u",&aendern[nt].d.monat); printf("Jahr.........: "); scanf("%d",&aendern[nt].d.jahr); printf("------------------------\n"); printf("Stunden......: "); scanf("%u",&aendern[nt].z.stunde); printf("Minuten......: "); scanf("%u",&aendern[nt].z.minute); } else printf("Falsche Eingabe : %d\n", nt); } void sortdate(struct termin *sort, int dates) { struct termin *temp; int i,j; temp = malloc(sizeof(struct termin *)); if(NULL == temp) { printf("Konnte keinen Speicher reservieren ...\n"); return; } for(i = 0; i < dates; i++) { for(j = i + 1; j < dates; j++) { if(sort[i].d.jahr > sort[j].d.jahr) { *temp=sort[j]; sort[j]=sort[i]; sort[i]=*temp; } } } printf("... sortiert!!\n"); } void Eingabe(struct adressen *neu) { unsigned int size; printf("Vorname : "); fgets(neu[nr].vname, MAX, stdin); /* newline-Zeichen entfernen */ size = strlen(neu[nr].vname); neu[nr].vname[size-1] = '\0'; printf("Nachname : "); fgets(neu[nr].nname, MAX, stdin); /* newline-Zeichen entfernen */ size = strlen(neu[nr].nname); neu[nr].nname[size-1] = '\0'; printf("Postleitzahl: "); do { scanf("%ld",&neu[nr].PLZ); } while(getchar()!= '\n'); printf("Wohnort : "); fgets(neu[nr].ort, MAX, stdin); printf("Geburtsjahr : "); do { scanf("%d",&neu[nr].geburtsjahr); } while(getchar()!= '\n'); nr++; } void Ausgabe(struct adressen *all) { int i; for(i = 0; i < nr; i++) { printf("Vorname.........:%s\n", all[i].vname); printf("Nachname........:%s\n", all[i].nname); printf("Postleitzahl....:%ld\n", all[i].PLZ); printf("Ort.............:%s", all[i].ort); printf("Geburtsjahr.....:%d\n\n", all[i].geburtsjahr); if( (!(i%2)) && i!=0) { // fflush(stdin); printf("\n\tWeiter mit <Enter>\n\n"); getchar(); } } } void Sortadress(struct adressen *sort) { struct adressen *temp; int i,j; temp = malloc(sizeof(struct adressen *)); if(NULL == temp) { printf("Konnte keinen Speicher reservieren ...\n"); return; } for(i = 0; i < nr; i++) { for(j = i + 1; j < nr; j++) { if(strcmp(sort[i].nname, sort[j].nname)>0) { *temp=sort[j]; sort[j]=sort[i]; sort[i]=*temp; } } } printf("... sortiert!!\n"); } int main(void) { int eingabe,aendern; do { printf("\tTerminverwaltung\n"); printf("\t----------------\n\n"); printf("\t-1- Neuer Termin\n"); printf("\t-2- Termine auflisten\n"); printf("\t-3- Termin ändern\n"); printf("\t-4- Termine sortieren\n"); printf("\t-5- Neue Adresse eingeben\n"); printf("\t-6- Adressen ausgeben\n"); printf("\t-7- Adressen sortieren\n"); printf("\t-8- Programm beenden\n"); printf("\n\tIhre Auswahl : "); scanf("%d",&eingabe); /* fflush(stdin); */ getchar(); switch(eingabe) { case 1 : newdate(t); break; case 2 : listdate(t,dates); break; case 3 : listdate(t,dates); printf("Welchen Termin ändern(Nr.?):"); scanf("%d",&aendern); replacedate(t,--aendern); break; case 4 : sortdate(t,dates); break; case 5 : Eingabe(xyz); break; case 6 : Ausgabe(xyz); break; case 7 : Sortadress(xyz); break; default : break; } } while(eingabe < 8); printf("Bye\n"); return EXIT_SUCCESS; } Eine kurze Erklärung: Bei der ersten Funktion newdate() wird zuerst der neue Termin eingegeben. AnschlieÃend wird erfragt, ob ein neuer Adresseintrag für den Termin vorgenommen werden soll oder ob ein bereits vorhandener Adresssatz verwendet wird. Die nächste Funktion listdate() listet die Termine auf. Mit der Funktion replacedate() kann ein Termin verschoben werden. Die Funktion sortdate() wurde ebenfalls schon ähnlich verwendet. Hier wurde nur nach Jahresdatum sortiert. Als Ãbung können Sie dies ja bis auf die Minute genau umschreiben. Der Rest des Programms wurde zum Teil schon bei der Adressverwaltung erklärt. Die Suchfunktion wurde dabei verändert. Diese sucht jetzt nach einem ganzen Nachnamen, nicht mehr nur nach dem Anfangsbuchstaben. Dem Programm fehlen noch eine Menge Fehlerüberprüfungen bei der Eingabe. Auf diese wurde aus Gründen der Ãbersichtlichkeit jedoch verzichtet (Sie können sie zur Ãbung ja selbst schreiben). Abbildung 15.7 Das Terminverwaltungsprogramm während der Ausführung # 15.8 Kurze Zusammenfassung zu den Strukturen ## 15.8 Kurze Zusammenfassung zu den Strukturen Da das Kapitel über Strukturen recht umfangreich ist, fasse ich hier nochmals einige Punkte zusammen. Der Datensatz einer Struktur wird folgendermaÃen zusammengefasst: > struct daten { int var1; char var2[100]; }; Hiermit haben Sie eine Struktur mit dem Namen daten mit zwei Elementen (var1, var2) deklariert. Eine Variable dieses Strukturtyps können Sie folgendermaÃen deklarieren: > // Variable vom Typ struct daten struct daten d1; // ein Zeiger auf eine Struktur vom Typ struct daten struct daten *d2; // Struktur-Array mit 10 Elementen vom Typ struct daten struct daten d3[10]; Weiterhin können Sie diese Variablen vom Typ struct daten auch so deklarieren: > struct daten { int var1; char var2[100]; } d1, *d2, d3[10]; Die Initialisierung einer Strukturvariablen kann über eine Initialisierungsliste erfolgen, die für jedes Element einen Anfangswert enthält: > struct daten d1 = { 111, "Test" }; Nach dem neuen C99-Standard können bestimmte Elemente der Struktur mit dem Elementbezeichner in der Form .strukturelement initialisiert werden. Alle anderen Elemente ohne Initialisierer haben automatisch den Wert 0: > // var1 hat automatisch den Wert 0. struct daten d1 { .var2 = "Test" } Auf ein einzelnes Strukturelement greifen Sie mit dem Punktoperator zu: > struct daten d1; d1.var1 = 111; stcpy(d1.var2, "Test"); // Array von Strukturen d3[2].var1 = 123; // 3. Element des Struktur-Arrays stcpy(d3[2].var2, "Test"); Wenn Sie Zeiger auf Strukturen nutzen, greifen Sie auf die einzelnen Elemente mithilfe des Pfeiloperators zu: > struct daten *d2; ... d2->var1 = 111; stcpy(d2->var2, "Test"); # 15.9 Unions ## 15.9 Unions Eine weitere Möglichkeit, Daten zu strukturieren, sind Unions (auch Varianten genannt). Abgesehen von einem anderen Schlüsselwort, bestehen zwischen Unions und Strukturen keine syntaktischen Unterschiede. Der Unterschied liegt in der Art und Weise, wie mit dem Speicherplatz der Daten umgegangen wird. Hier sehen Sie ein Beispiel für die Speicherplatzbelegung einer Struktur: > struct test1 { char a; int b; double c; }; Abbildung 15.8 Speicherbelegung bei einer Struktur Diese Struktur benötigt 16 Byte an Speicher. Jetzt folgt das gleiche Beispiel mit dem Schlüsselwort union: > union test2 { char a; int b; double c; }; Intern sieht dies mit union folgendermaÃen aus: Abbildung 15.9 Speicherbelegung einer Struktur mit dem Schlüsselwort »union« Hier sehen Sie ein Listing, das den Unterschied demonstrieren soll: > /* union1.c */ #include <stdio.h> #include <stdlib.h> struct test1 { char a; int b; double c; }; union test2 { char a; int b; double c; }; int main(void) { printf("struct benoetigt %d Bytes\n", sizeof(struct test1)); printf("Union benoetigt %d Bytes\n", sizeof(union test2)); return EXIT_SUCCESS; } Sie sehen richtig: Die Struktur mit dem Schlüsselwort union besitzt jetzt nur noch acht Bytes. Dies verursachen das Schlüsselwort union und das gröÃte Element in der Struktur, double. Dieser ersparte Speicherplatz wird allerdings mit dem Nachteil erkauft, dass immer nur ein Element in dieser Struktur verwendet werden kann. Beispielsweise wird dem Strukturelement int b der Wert 100 übergeben: > text.b = 100; Somit beträgt die SpeichergröÃe der Struktur trotzdem acht Bytes für einen Integer, da der gröÃte Datentyp in der union nämlich double lautet. Ãbergeben Sie jetzt an double c den Wert 10.55: > text.c = 10.55; Jetzt können Sie auf den Wert von int b nicht mehr zugreifen, da dieser von double c überlappt wurde. Zwar kann es immer noch sein, dass int b weiterhin den Wert 100 ausgibt, aber dies wäre Zufall, denn der Speicherbereich wurde überdeckt. Das Verhalten ist in diesem Fall undefiniert. Welchen Vorteil hat es, wenn immer auf ein Element einer Struktur zugegriffen werden kann? Der wesentliche Vorteil liegt in der Anwendung von Union zum Einsparen von Speicherplatz bei der Verarbeitung groÃer Strukturen; beispielsweise bei Strukturen, wo bestimmte Elemente niemals miteinander auftreten. Ein Beispiel wäre ein Computerspiel, bei dem immer einer gegen einen, Auge um Auge, kämpft. In dem folgenden Codeabschnitt wurde eine Struktur mit vier verschiedenen Gegnercharakteren erstellt: > struct gegner { union { struct { char name[20]; int power; unsigned char leben; unsigned int geschwindigkeit; } fighter1; struct { char name[20]; int power; unsigned char leben; unsigned int geschwindigkeit; } fighter2; struct { char name[20]; int power; unsigned char leben; unsigned int geschwindigkeit; } fighter3; struct { char name[20]; int power; unsigned char leben; unsigned int geschwindigkeit; } fighter4; }; } dat; Damit wird immer nur auf eine Struktur zugegriffen, was in diesem Beispiel ausreichend ist, denn es sollten immer nur die Daten eines Gegners im Speicher sein – eben die, die im Augenblick nötig sind. So könnten Sie z. B. den fighter4 mit Werten initialisieren: > strcpy(dat.fighter4.name, "Superman"); dat.fighter4.power = 5; dat.fighter4.leben = 1; dat.fighter4.geschwindigkeit = NORMAL; Der Zugriff auf die einzelnen Elemente erfolgt wie bei den normalen Strukturen. Kommen wir zum Programm der Adressverwaltung zurück, denn dieses eignet sich auch prima für eine Union: > struct adres { union { struct { char vname[20]; char nname[20]; long PLZ; char ort[20]; int geburtsjahr; } privat; struct { char vname[20]; char nname[20]; long PLZ; char ort[20]; char sternzeichen[20]; int geburtsjahr; } geschaeftlich; }; } adressen[100]; Hiermit können 100 Adressen gespeichert werden. Mithilfe dieser Union wird das Private vom Geschäftlichen getrennt. Natürlich können Sie mit dem Schlüsselwort union auch ein Array von Unions realisieren. Der Zugriff und die Initialisierung erfolgen genau so, wie ich bei den Strukturen bereits beschrieben habe; ein Beispiel: > /* union2.c */ #include <stdio.h> #include <stdlib.h> union number { float x; int y; }; int main(void) { union number mixed[2]; mixed[0].x = 1.123; mixed[1].y = 123; mixed[2].x = 2.345; printf("%.2f\t%d\t%.2f\n", mixed[0].x, mixed[1].y, mixed[2].x); return EXIT_SUCCESS; } Wenn Sie eine Union initialisieren, erlaubt ANSI C nur einen Initialisierer. StandardmäÃig bedeutet dies, dass immer das erste Element der Union initialisiert wird: > union 2_D { int x; int y; }; // coordinate.x hat den Wert 123 union 2_D coordinate = { 123 }; Haben Sie eine Union bereits initialisiert und weisen Sie einem anderem Union-Element einen Wert zu, wird der Wert des anderen Union-Elements überschrieben: > union 2_D { int x; int y; }; ... union 2_D coordinate; coordinate.x = 20; ... coordinate.y = 40; // Element x wird hier überschrieben. Laut dem C99-Standard können Sie auch bei den Unions (wie bei den Strukturen) den Elementbezeichner verwenden, um festzulegen, welches Element in der Union initialisiert werden soll: > union 2_D { int x; int y; }; ... union 2_D coordinate = { .y = 99 }; Beim Zuweisen eines vorhandenen und initialisierten Union-Objektes an ein anderes wird das neue Union-Objekt mit demselben Typ initialisiert: > // wird mit dem vorhandenen Objekt desselben // Typs initialisiert union 2_D coordinate2 = coordinate; # 15.10 Der Aufzählungstyp »enum« ## 15.10 Der Aufzählungstyp »enum« Das Schlüsselwort enum dient zur Aufzählung von Konstanten. Mit dieser Struktur lassen sich beim Programmstart eine Reihe von Konstanten festlegen. Ein Beispiel: > /* enum1.c */ #include <stdio.h> #include <stdlib.h> enum zahl { NU_LL, EINS, ZWEI, DREI, VIER}; int main(void) { enum zahl x; x=NU_LL; printf("%d\n",x); x=EINS; printf("%d\n",x); x=ZWEI; printf("%d\n",x); x=DREI; printf("%d\n",x); x=VIER; printf("%d\n",x); return EXIT_SUCCESS; } Bei Ausführung des Programms werden die Zahlen von null bis vier auf dem Bildschirm ausgegeben. Die Aufzählung lautet hier: > enum zahl { NU_LL, EINS, ZWEI, DREI, VIER }; In der Regel beginnt der Aufzählungstyp, sofern nicht anders angegeben, mit 0; also NU_LL=0. Das nächste Feld hat, wenn nicht anders angegeben, den Wert 1. Somit ist EINS auch 1. Gleichbedeutend hätte man dies auch so schreiben können: > enum zahl { NU_LL=0, EINS=1 ,ZWEI=2 ,DREI=3 ,VIER=4 }; Wird enum hingegen so benutzt: > enum farben { rot, gelb=6, blau, gruen }; würden folgende Konstanten definiert werden: > enum farben { 0, 6, 7, 8 }; Die Farbe gelb wurde mit dem Wert 6 initialisiert. Die Steigerung des Werts zur nächsten Konstante beträgt bei enum immer plus eins. Somit hat die Konstante blau den Wert 7 und gruen den Wert 8. Häufig wird enum zur Nachbildung der booleschen Variablen verwendet. Hier sehen Sie das Beispiel dazu: > /* enum2.c */ #include <stdio.h> #include <stdlib.h> enum BOOL { FALSE, TRUE }; int main(void) { int zahl; printf("Gib mir eine Zahl (0-9): "); if( (scanf("%d",&zahl)) == FALSE ) printf("Das war keine Zahl!\n"); else printf("Vielen Dank!\n"); if( (zahl==7) == TRUE) printf("Wow, die 7, meine Lieblingszahl\n"); return EXIT_SUCCESS; } Der Aufzählungstyp enum dient der besseren Lesbarkeit eines Programms. BOOL (in C++ gibt es diesen Datentyp wirklich) könnten Sie aber auch als Makro implementieren: > #define BOOL int #define FALSE 0 #define TRUE 1 Es gibt also viele Wege, die ans Ziel führen. Die zwölf Monate eines Jahres könnten Sie mit enum beispielsweise so realisieren: > enum Monate { JAN=1, FEB, MAR, APR, MAI, JUN, JUL, AUG, SEP, OKT, NOV, DEC } Oder mit define so: > #define JAN 1 #define FEB 2 #define MAR 3 #define APR 4 #define MAI 5 ... Bei beiden Beispielen wurden die einzelnen Monate als Konstanten definiert. Worin besteht dann der Unterschied zwischen enum und einer Reihe von Präprozessor-Defines? Ironischerweise besteht kaum ein Unterschied. Geplant war (laut ANSI-C-Standard) enum, um ohne Casts verschiedene integrale Typen vermischen zu können, was ja sonst in der Regel einen Compiler-Fehler zur Folge hat. So hätten eine Menge Programmierfehler aufgefangen werden können. Aber enum hat auch Vorteile: * Zahlenwerte werden automatisch zugewiesen. * Debugger-Werte von enum-Variablen können symbolisch dargestellt werden. * enum unterliegt auch der Sichtbarkeitsregel von C. # 15.11 Typendefinition mit »typedef« ## 15.11 Typendefinition mit »typedef« Mit dem Schlüsselwort typedef kann ein neuer Bezeichner für einen einfachen Datentyp verwendet werden. Die Syntax einer einfachen Typendefinition sieht so aus: > typedef Typendefinition Bezeichner; Damit lässt sich die Lesbarkeit eines Programms erheblich verbessern. Diese Typendefinition mit typedef soll anhand des Adressprogramms demonstriert werden. Hier sehen Sie das Listung dazu: ``` /* typedef1.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 30 static int x; struct adres { char vname[MAX]; char nname[MAX]; long PLZ; char ort[MAX]; int geburtsjahr; } adressen[100]; typedef struct adres ADRESSE; void Eingabe(int nr, ADRESSE *neu) { printf("Vorname : "); fgets(neu[nr].vname, MAX, stdin); printf("Nachname : "); fgets(neu[nr].nname, MAX, stdin); printf("Postleitzahl: "); do { scanf("%5ld",&neu[nr].PLZ); } while(getchar()!= '\n'); printf("Wohnort : "); fgets(neu[nr].ort, MAX, stdin); printf("Geburtsjahr : "); do { scanf("%4d",&neu[nr].geburtsjahr); } while(getchar()!= '\n'); } void Suche(ADRESSE *search, char buchstabe, int nr) { int i; for(i = 0; i <= nr; i++) { if(search[i].nname[0] == buchstabe) { printf("\n\nGefunden unter Buchstabe :\"%c\"\n\n", buchstabe); printf("Vorname.......:%s",search[i].vname); printf("Nachname......:%s",search[i].nname); printf("Postleitzahl..:%ld\n",search[i].PLZ); printf("Ort...........:%s",search[i].ort); printf("Geburtsjahr...:%d\n",search[i].geburtsjahr); printf("\n\tWeiter mit <ENTER>\n"); getchar(); } } } void Ausgabe(ADRESSE *all, int nr) { int i; for(i = 0; i < nr; i++) { printf("Vorname.........:%s",all[i].vname); printf("Nachname........:%s",all[i].nname); printf("Postleitzahl....:%ld\n",all[i].PLZ); printf("Ort.............:%s",all[i].ort); printf("Geburtsjahr.....:%d\n\n",all[i].geburtsjahr); if( (!(i%2)) && i!=0) { //fflush(stdin); printf("\n\tWeiter mit <Enter>\n\n"); getchar(); } } } void Sort(ADRESSE *sort,int nr) { ADRESSE *temp; int i,j; temp = malloc(sizeof(ADRESSE *)); if(NULL == temp) { printf("Konnte keinen Speicher reservieren ...\n"); return; } for(i = 0; i < nr; i++) { for(j=i+1;j<nr;j++) { if(strcmp(sort[i].nname, sort[j].nname)>0) { *temp=sort[j]; sort[j]=sort[i]; sort[i]=*temp; } } } printf("... sortiert!!\n"); } int main(void) { int auswahl; char c; do { printf("-1- Neue Adresse eingeben\n"); printf("-2- Bestimmte Adresse ausgeben\n"); printf("-3- Alle Adressen ausgeben\n"); printf("-4- Adressen sortieren\n"); printf("-5- Programm beenden\n"); printf("\nIhre Auswahl : "); scanf("%d",&auswahl); /* fflush(stdin); */ getchar(); switch(auswahl) { case 1 : Eingabe(x++,adressen); break; case 2 : printf("Anfangsbuchstabe Nachnamen :"); do { scanf("%c",&c); } while(getchar()!= '\n'); Suche(adressen,c,x); break; case 3 : Ausgabe(adressen,x); break; case 4 : Sort(adressen,x); break; default: break; } } while(auswahl < 5); return EXIT_SUCCESS; } ``` Dank der neuen Typdefinition > typedef struct adres ADRESSE; kann auf die Struktur jetzt mit > ADRESSE neueadressen[100]; zugegriffen werden. Dies lässt sich bei längeren Programmen wesentlich einfacher lesen. Vor allem ist dies sinnvoll, wenn mehrere Strukturen vorhanden sind, die einander vom Aufbau sehr ähnlich sind. Die Typdefinition im Programm lieÃe sich auch noch anders definieren: > typedef struct adres { char vname[20]; char nname[20]; long PLZ; char ort[20]; int geburtsjahr; } ADRESSE; ... ADRESSE adressen[100]; Die Typdefinition kann ebenso auf andere Variablen angewendet werden. Recht häufig sind folgende Definitionen zu sehen: > typedef unsigned char BYTE; // 1 Byte = 8 BIT typedef unsigned int WORD; // 1 WORD = 16 BIT typedef unsigned long DWORD; // 1 DOUBLE WORD = 32 BIT typedef unsigned double QWORD; // 1 QUAD WORD = 64 BIT typedef unsigned int uint; typedef unsigned char uchar; Zum Beispiel ist danach die folgende Schreibweise > uint wert1, wert2; äquivalent zu: > unsigned int wert1,wert2; Das Schlüsselwort typedef wird ebenfalls dazu benutzt, sogenannte primitive Datentypen zu erzeugen. Wozu soll das gut sein? Nehmen wir als Beispiel den primitiven Datentyp uclock_t (primitive Datentypen enden normalerweise immer mit _t). Dieser ist in der Headerdatei <time.h> definiert mit: > typedef long uclock_t; Auf einem anderen System sieht diese Definition vielleicht so aus: > typedef unsigned int uclock_t; Die primitiven Datentypen machen ein Programm portabler. Dadurch müssen Sie sich nicht mit den Datentypen bei der Portierung auf andere Systeme auseinandersetzen. Wenn Sie ein Programm beispielsweise auf einem 32-Bit-System programmiert haben und dies anschlieÃend auf einem 16-Bit-System getestet wird, kann die Suche nach dem Fehler einer falschen Werteausgabe frustrierend sein. Wie schon mit enum oder define wird mit typedef das Programm nicht etwa besser oder schneller, sondern es dient auch hier lediglich dazu, dass sich Ihr Programm besser lesen, schreiben und auf andere Systeme portieren lässt. Der Speicherplatz für eine Struktur wird – wie schon bei den Arrays – lückenlos im Hauptspeicher abgelegt. Damit das System schneller auf diese Daten im Hauptspeicher zurückgreifen kann, werden diese in durch zwei oder in durch vier teilbare Adressen angeordnet. Dies hängt vom Betriebssystem ab. Dabei wird einiges an Speicherplatz verschwendet. Zur Demonstration dient das folgende Programm: > /* alignment1.c */ #include <stdio.h> #include <stdlib.h> struct speicher { char x; int z; }; int main(void) { struct speicher test; printf("%u Bytes\n",sizeof(test)); return EXIT_SUCCESS; } Auf 32-Bit-Systemen dürfte diese Struktur acht Byte benötigen. Und dies, obwohl es eigentlich fünf Byte sein sollten (char + int = 5 Byte). Abbildung 15.10 Speicherabbild mit einer Struktur mit unbenannten Lücken Abbildung 15.10 stellt ein Vier-Byte-Alignment dar, wie es bei den meisten Systemen der Fall sein wird. Dabei entsteht eine Lücke von drei Byte (grau gefärbt), die ungenutzt bleibt. Es wird hier auch vom Padding (Auffüllen, Polsterung) des Speichers gesprochen. Viele Compiler besitzen daher einen speziellen Schalter, mit dem diese Lücke entfernt werden kann. Wobei ich gleich anmerken muss, dass dies nicht ANSI-C-konform, sondern compiler-abhängig ist. Mit dem Schalter > __attribut__ können dem Compiler mehrere Informationen zu einer Funktion, zu Variablen oder Datentypen übergeben werden. Um damit eine lückenlose Speicherbelegung zu erreichen, könnten Sie das Attribut packed verwenden. Sollte dieser Schalter bei Ihrem Compiler nicht funktionieren, können Sie auch das Pragma pack verwenden: > #pragma pack(n) Für n kann hier der Wert 1, 2, 4, 8 oder 16 angegeben werden. Je nachdem, welche Angabe Sie dabei machen, wird jedes Strukturelement nach dem ersten kleineren Elementtyp oder auf n Byte abgespeichert. Beim Testen auf verschiedenen Systemen und unterschiedlichen Compilern gab es keine Probleme mit dem #pragma pack. Die Option __attribut__ hingegen wurde nicht von jedem Compiler erkannt. Wie Sie dabei vorgehen, müssen Sie letztendlich selbst herausfinden. Hier folgt das Beispiel dazu: > /* alignment2.c */ #include <stdio.h> #include <stdlib.h> /* Lässt sich dieses Listing nicht übersetzen, * entfernen Sie __attribute__((packed)) und * verwenden stattdessen #pragma pack(1). */ /* #pragma pack(1) */ struct speicher { char x; int z; } __attribute__ ((packed)); int main(void) { struct speicher test; printf("%u Bytes\n",sizeof(test)); return EXIT_SUCCESS; } Damit benötigt die Struktur tatsächlich 5 Byte. Dies funktioniert bei manchen Compilern auch bei den enum-Aufzählungen: > /* alignment3.c */ #include <stdio.h> #include <stdlib.h> /* #pragma pack(1); */ enum{TRUE,FALSE}__attribute__ ((packed)); int main(void) { printf("%u Bytes\n",sizeof(TRUE)); return EXIT_SUCCESS; } Das Beispiel funktionierte beim Testen allerdings nur mit dem gcc-Compiler. In diesem Fall wird durch packed ein 1-Byte-Alignment angelegt. Das ist gegenüber den vier Bytes ohne packed beachtlich. Diese Werte können natürlich von System zu System unterschiedlich sein. Bei den Vorteilen, die mit packed oder dem Pragma pack erzielt werden, sollten Sie auch die Nachteile beachten. Wenn diese Daten (struct speicher) auf einem System mit fünf Bytes pro Struktur in einer Datei gespeichert werden, kann es passieren, dass diese Daten auf einem anderen System falsch angezeigt werden, weil das System vielleicht dort die Option packed nicht kennt und einfach ignoriert. AuÃerdem könnten Low-Level-Funktionen fehlschlagen, da sich die Daten wegen des Alignments nicht dort befinden, wo die Funktionen diese vermutet. # 15.13 Bitfelder ## 15.13 Bitfelder Bitfelder sind Strukturelemente, die mit weniger als 1 Byte in eine Struktur gepackt werden können. Laut ANSI C müssen die einzelnen Elemente von Bitfeldern vom Datentyp int oder unsigned int sein. Als Beispiel soll hier ein Roboter für eine FlieÃbandproduktion programmiert werden. Der Roboter muss ein bestimmtes Produkt von Position A nach Position B transportieren. Dazu sind folgende Arbeitsabläufe erforderlich: 1. | Produkt zum Befördern vorhanden (Sensor 1 = aktiv). Wenn ja  | | --- | --- | 2. | Produkt erfassen und hochheben und auf das FlieÃband legen. Wenn Produkt auf FlieÃband liegt (Sensor 2 = aktiv), dann ... | | --- | --- | 3. | FlieÃband bewegen (Schalter 1) und warten, bis Produkt beim Sensor 3 ankommt. Dann wieder prüfen, ob ein Produkt auf Sensor 1 vorhanden ist. Falls an Sensor 1 ein Produkt vorhanden ist, alles wieder von vorn. | | --- | --- | Dieser Vorgang soll auch überprüft werden, und bei einem Fehler wird ein Fehlercode ausgegeben, für den es eine entsprechende Stringtabelle gibt. AuÃerdem wird dazu eine Anzeige benötigt. Es wird davon ausgegangen, dass der Roboter bereits mit dem PC verbunden ist. Hier sehen Sie die Struktur des Roboters: > struct robo { unsigned char sensor1; unsigned char sensor2; unsigned char sensor3; unsigned char schalter; unsigend int Ausgabe; } Roboter1; Mit dieser Struktur benötigt der Roboter 48 Bits (6 Bytes bzw. 8 Bytes wegen des Alignments des Betriebssystems). Wenn jetzt noch mehrere Roboter hinzukommen, ist das eine Speicherplatzverschwendung, und Speicherplatz ist bei solchen Systemen meistens kostbar. Häufig ist bei solchen Automatisierungsrobotern nicht unbegrenzt Speicherplatz vorhanden. Bei den Sensoren und Schaltern benötigen Sie in der Regel nur zwei Schaltstellungen: 1 für »betätigt« und 0 für »unbetätigt«. In C ist es auch möglich, einzelne Bits einer Struktur mit sogenannten Bitfeldern anzusprechen. Die Deklaration eines solchen Bitfelds hat folgende Syntax: > Typ Elementname : Breite ; Für den Typ können Sie einen beliebigen Ganzzahltyp wie int, signed int, unsigned int oder _Bool verwenden. Sie können auch Typqualifizierer nutzen. Den Elementnamen benötigen Sie, um auf das Bitfeld zugreifen zu können. Sie können auch ein anonymes Bitfeld ohne Elementnamen definieren. Solche namenlosen Bitfelder dienen zum Auffüllen eines Bitfeldes, um die Bitzahl auf ein bestimmtes Rechnerwort einzustellen. Mit Breite geben Sie die Anzahl der Bits an, die für das Element verwendet werden sollen. Hierbei muss ein ganzzahliger positiver Ausdruck verwendet werden. Ein Bitfeld mit einer Breite von n kann auÃerdem 2n verschiedene Werte speichern. Solche Bitfelder haben auÃerdem den Vorteil, dass sie wie gewöhnliche Struktur- bzw. Union-Elemente mit dem Elementnamen angesprochen werden. Bezogen auf das Beispiel unseres Automatisierungsroboters sieht dies folgendermaÃen aus: > struct robo { unsigned int sensor1:1; unsigned int sensor2:1; unsigned int sensor3:1; unsigned int schalter:1; unsigned int Ausgabe:4; } Roboter1; Jetzt benötigt die Struktur im Grunde nur noch acht Bits (ein Byte). Wenn Sie allerdings mit sizeof prüfen, werden Sie feststellen, dass dieses Bitfeld trotzdem vier Byte belegt. Dies liegt daran, dass das kleinstmögliche Rechnerwort, das der Compiler für ein Bitfeld reserviert, sizeof(int) groà ist. Die restlichen drei Bytes in diesem Beispiel sind praktisch leer. Gleiches gilt hierbei natürlich auch, wenn Sie beispielsweise ein Bitfeld mit 40 Bits (fünf Bytes) erstellen. Hier muss der Compiler ein weiteres Rechnerwort (sizeof(int)) reservieren, sodass das fünfte Byte am Anfang des nächsten Rechnerworts liegt und somit insgesamt 8 Bytes benötigt werden. Hier sehen Sie das Beispiel dazu: > /* bitfields.c */ #include <stdio.h> #include <stdlib.h> enum{ OFF, ON }; struct robo { unsigned int Sensor1:1; unsigned int Sensor2:1; unsigned int Sensor3:1; unsigned int Schalter:1; unsigned int Ausgabe:4; } Roboter1; char *msg[7] = { "Kein Signal an Sensor 1!\n", "Kein Signal an Sensor 2!\n", "Kein Signal an Sensor 3!\n", "Schalter 1 nicht betätigt!\n", "Notaus betätigt!\n", "Kein Strom!\n" }; int main(void) { int anzahl; do { printf("Wie viele Produkte von Pos.A nach Pos.B : "); do{ scanf("%d",&anzahl); } while(getchar() != '\n'); while((anzahl>0) && (anzahl--)) { /* Sollte durch echte Schnittstelle ersetzt werden. */ Roboter1.Sensor1=ON; printf("Sensor 1 ist aktiv\n"); if(Roboter1.Sensor1 == ON) printf("Produkt wird aufgenommen und " "zum FlieÃband transportiert\n"); else { /* Fehler: Sensor 1 nicht aktiv * Fehlermeldung ausgeben */ Roboter1.Ausgabe = 0; printf("%s\n", msg[Roboter1.Ausgabe]); } /* Sollte durch echte Schnittstelle ersetzt werden. */ Roboter1.Sensor2=ON; printf("Sensor 2 ist aktiv\n"); if(Roboter1.Sensor2 == ON) { printf("Produkt ist auf dem FlieÃband\n"); printf("Bitte >>ENTER<< drücken" " für den Schalter\n"); getchar(); printf("Schalter ist eingeschaltet!\n"); /* Sollte durch echte Schnittstelle * ersetzt werden. */ Roboter1.Schalter=ON; } else { Roboter1.Ausgabe=1; printf("%s\n",msg[Roboter1.Ausgabe]); Roboter1.Ausgabe=3; printf("%s\n", msg[Roboter1.Ausgabe]); } /* Sollte durch echte Schnittstelle * ersetzt werden. */ Roboter1.Sensor3=ON; printf("Sensor 3 aktiv\n"); if(Roboter1.Sensor3 == ON) { printf("Produkt am Ziel angekommen!\n"); printf("Schalter für FlieÃband auf OFF\n"); printf("Roboter wieder betriebsbereit\n"); printf("Weiter mit >>ENTER<<\n"); getchar(); Roboter1.Schalter=OFF; } else { Roboter1.Ausgabe = 2; printf("%s\n", msg[Roboter1.Ausgabe]); } } } while(anzahl > 0); Roboter1.Sensor1=OFF; Roboter1.Sensor2=OFF; Roboter1.Sensor3=OFF; Roboter1.Ausgabe=0; printf("%s\n",msg[Roboter1.Ausgabe]); return EXIT_SUCCESS; } Abbildung 15.11 Der Roboter im Einsatz Dass die Struktur robo hier vier Bytes und nicht ein Byte groà ist, liegt am Alignment des Betriebssystems. Hier kann der Speicherplatz mit dem Keyword attribute oder dem Pragma pack auf ein Byte zusammengepackt werden. Vorausgesetzt, der Compiler unterstützt dies: > //#pragma pack(1) struct robo { unsigned Sensor1:1; unsigned Sensor2:1; unsigned Sensor3:1; unsigned Schalter:1; unsigned Ausgabe:4; } __attribute__ ((packed)) Roboter1; Abbildung 15.12 zeigt diese Struktur nochmals schematisch. Abbildung 15.12 Bitbelegung der einzelnen Bitfelder der Struktur »robo« Das Dumme an diesem Beispiel ist, dass es zu gar nichts taugt, da keine Verbindung mit einem Roboter besteht. Zeilen wie > Roboter1.Sensor1=ON; Roboter1.Sensor2=ON; müssen selbst eingegeben werden. Daher folgt jetzt ein ausführbares Beispiel, das zeigt, was eine Schnittstelle bzw. eine Adresse zum PC genau ist. Es wird der Druckerstatus am Port LPT1 überprüft. Das Listing ist nur unter MS-DOS ausführbar und nicht ANSI-C-konform: > /* check_printer.c */ #include <stdio.h> #include <stdlib.h> #include <dos.h> /* 0x378 ist die Adresse der Schnittstelle von LPT1. */ #define LPT1_PORT 0x378 struct status { unsigned :3; /* Bit 0-2 nicht verwendet */ unsigned fehler :1; /* 0=Druckerfehler */ unsigned online :1; /* 1=Drucker online */ unsigned papier :1; /* 1=kein Papier */ unsigned empfang:1; /* Empfangsbestätigung */ unsigned busy :1; /* Drucker bereit */ } LPT1_status; /* Status am LPT1-Port auslesen */ void druckerstatus(char *statuszeiger) { *statuszeiger = inp( LPT1_PORT+1 ) & 0xF8; } int main(void) { druckerstatus( (char *) &LPT1_status); if(LPT1_status.busy && LPT1_status.online) { printf("Drucker ist bereit!\n"); return EXIT_SUCCESS; } else if(!LPT1_status.online) printf("Drucker nicht online!\n"); else if(LPT1_status.papier) printf("Kein Papier vorhanden!\n"); else printf("Drucker ist nicht bereit!\n"); return EXIT_SUCCESS; } Die Adresse 0x378 stellt die Adresse des Ports LPT1 dar. Das Statusregister, das hier überprüft wird, sieht so intern aus, wie in Abbildung 15.13 dargestellt. Diese Struktur ähnelt der Struktur, die oben bei den Robotern verwendet wurde. Die Bits 0–2 werden nicht verwendet. Die Bits 3–7 geben anschlieÃend den Status des Druckers zurück – je nachdem, welche Bits gesetzt sind und welche nicht. Die Funktion druckerstatus() liefert den Status zurück. Neu ist bei diesem Programm: > unsigned:3; Hiermit werden drei Bits ohne Namen definiert. Im Beispiel sind es die ersten drei Bits, die ungenutzt bleiben. Sie können im Programm nicht verwendet werden und werden als anonyme Bitfelder bezeichnet. Abbildung 15.13 Bitbelegung eines Druckers am LPT1-Port unter MS-DOS # 15.14 Das »offsetof«-Makro ## 15.14 Das »offsetof«-Makro Um den Abstand der einzelnen Strukturelemente in Bytes zu ermitteln, können Sie das Makro offsetof() verwenden, das in der Headerdatei <stddef.h> deklariert ist. Hier sehen Sie die Syntax dazu: > #include <stddef.h> size_t offsetof(struktur, name_strukturelement); Das Makro liefert, wie schon erwähnt, den Abstand vom Anfang der Struktur bis zu dem Strukturelement, das als zweites Argument angegeben ist. Ist das Makro auf Ihrem System nicht vorhanden, so lässt es sich ohne groÃen Aufwand selbst implementieren: > #define offsetof(struct_type, member) \ (size_t) &(((struct_type *)0)->member) Ein einfaches Listing dazu: > /* offsetof.c */ #include <stdio.h> #include <stdlib.h> #include <stddef.h> #define MAX 15 struct data{ char datei[MAX]; unsigned int flag; char eigentuemer[MAX]; char passwort[MAX]; }; int main(void) { struct data newfile = { "testfile", 0, "its_me", "believe" }; printf("Vom Anfang zur Strukturvariable flag : %d Bytes\n", offsetof(struct data, flag)); printf("Vom Anfang zur Strukturvariable owner : %d Bytes\n", offsetof(struct data, eigentuemer)); printf("Vom Anfang zur Strukturvariable passwort: %d Bytes\n", offsetof(struct data, passwort)); return EXIT_SUCCESS; } Sie erhalten hier jeweils den Abstand in Bytes vom Anfang der Struktur bis zum jeweiligen Strukturelement. # 16.2 Formatierte und unformatierte Ein-/Ausgabe ## 16.2 Formatierte und unformatierte Ein-/Ausgabe In C besteht die Möglichkeit, von zwei verschiedenen Ebenen aus auf eine Datei zuzugreifen: zum einen von der höheren Ebene (High-Level) aus und zum anderen von der niedrigeren Ebene (Low-Level). Mit der höheren Ebene kann wesentlich komfortabler und vor allem portabler programmiert werden. Die Funktionen der höheren Ebene entsprechen dem ANSI-C-Standard. Zu den Vorteilen der höheren Ebene gehören z. B. eine formatierte Ein- und Ausgabe und ein optimal eingestellter Puffer. Der Puffer ist ein Bereich im Arbeitsspeicher, der als Vermittler zwischen Daten und Zielort fungiert. Der Unterschied zwischen der höheren und der niedrigeren Ebene besteht in der Form, wie die Daten in einem Stream von der Quelle zum Ziel übertragen werden. Bei der höheren Ebene ist der Stream eine formatierte Dateneinheit (wie z. B. mit printf()). Hingegen handelt es sich bei der niedrigeren Ebene um einen unformatierten Byte-Stream. # 16.3 Standard-Streams ## 16.3 Standard-Streams Streams sind einfache Datenströme, mit denen Daten von der Quelle zum Ziel bewegt werden. Es gibt Standard-Streams in C wie die Standardeingabe (stdin), die Standardausgabe (stdout) und die Standardfehlerausgabe (stderr). Auf sie gehe ich in Abschnitt 16.10, »Standard-Streams in C«, noch genauer ein. Beim Start eines Programms sind die Standard-Streams stdin, stdout und stderr weder byte- noch wide-orientiert. # 16.4 Höhere Ein-/Ausgabe-Funktionen ## 16.4 Höhere Ein-/Ausgabe-Funktionen Beginnen wir mit einem kleinen Ãberblick über die Funktionen, die in der Headerdatei <stdio.h> deklariert sind und zur formatierten Ein-/Ausgabe verwendet werden (siehe Tabelle 16.1). All diese Funktionen werden Sie auf den nächsten Seiten etwas genauer kennenlernen und anwenden. # 16.5 Datei (Stream) öffnen – »fopen« ## 16.5 Datei (Stream) öffnen – »fopen« Die Bearbeitung von Dateien erfolgt in C immer zeichenorientiert. Da Dateien zunächst nichts anderes sind als eine unstrukturierte Folge von Einzelzeichen, spielt es keine Rolle, mit welcher Art von Daten gearbeitet wird. Erst bei der Verarbeitung der Daten bekommen die Einzelzeichen eine Bedeutung und eine Struktur. Zuerst soll eine einfache Textdatei zum Lesen geöffnet werden. Dabei gehen Sie folgendermaÃen vor: > FILE *datei; ... datei = fopen("textdatei.txt", "r"); Es wurde eine Textdatei mit dem Namen textdatei.txt geöffnet. Mithilfe des Zeigers datei vom Typ FILE wird dabei ein Lese-Stream zu dieser Textdatei eingerichtet. Die Syntax der Funktion fopen() lautet: > #include <stdio.h> FILE *fopen( const char * restrict pfadname, const char * restrict modus); Als Pfadangabe (pfadname) ist jeder zulässige String erlaubt. Sollten Sie unter einem Microsoft-Betriebssystem programmieren, kann auch eine Laufwerksangabe erfolgen. Die maximale Stringlänge für pfadname ist in der Konstante FILENAME_MAX deklariert, die sich ebenso in der Headerdatei <stdio.h> befindet. Mit modus geben Sie an, wie auf den Stream zugegriffen wird. Im Beispiel wurde der Modus "r" (für read) zum Lesen von der Datei verwendet. Auf die einzelnen möglichen Modi gehe ich gleich ein. Wenn beim Ãffnen einer Datei alles planmäÃig verlief, wird der FILE-Zeiger zurückgegeben. Bei einem Fehler erhalten Sie hingegen den NULL-Zeiger zurück. Der FILE-Zeiger – es wird ja auch von einem FILE-Stream gesprochen – ist eine Struktur, die in der Headerdatei <stdio.h> deklariert ist. Diese Struktur beinhaltet alle Informationen, die für die höheren Datei-E/A-Funktionen benötigt werden, beispielsweise: * den Puffer – die Anfangsadresse, den aktuellen Zeiger, die GröÃe * den File-Deskriptor (mehr dazu bei den Funktionen der niedrigeren Ebene) * die Position des Schreib- oder Lesezeigers * die Fehler- und EOF-Flags Natürlich können Sie auch mehrere Dateien auf einmal öffnen: > FILE *datei, *datei2; ... // Datei textdatei.txt zum Lesen öffnen datei = fopen("textdatei.txt", "r"); // Datei textdat2.txt zum Lesen öffnen datei2 = fopen("textdat2.txt", "r"); Kommen wir jetzt zu einem ausführbaren Beispiel der Funktion fopen(): > /* fopen1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { FILE *datei; /* Bitte Pfad und Dateinamen anpassen */ datei = fopen("test.txt", "r"); if(NULL == datei) { printf("Konnte Datei \"test.txt\" nicht öffnen!\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } Das Programm öffnet (falls vorhanden) die Datei test.txt. Konnte diese Datei nicht geöffnet werden bzw. ist sie nicht vorhanden, dann liefert die Funktion fopen() den NULL-Zeiger zurück. In diesem Beispiel muss sich die Datei test.txt im selben Verzeichnis befinden wie das ausführbare Programm. Liegt die Datei test.txt hingegen im Verzeichnis C:\Dokumentationen\Texte\test.txt dann muss das erste Argument in der Funktion fopen() folgendermaÃen aussehen: > datei = fopen("c:\\Dokumentationen\\Texte\\test.txt", "r"); Bei Microsoft-Systemen müssen Sie darauf achten, dass statt nur einem Backslash zwei (\\) geschrieben werden, um das Zeichen '\' anzuzeigen. Bei Linux/UNIX ist das einfacher. Ist das Verzeichnis > /home/Texte/test.txt dann muss sich Folgendes im ersten Argument befinden: > datei = fopen("/home/Texte/test.txt", "r"); Unter UNIX/Linux gibt es auÃerdem keine Laufwerksbezeichnung, da dort jedes Gerät – egal ob Festplatte, CD/DVD-ROM oder Diskette – als Datei betrachtet werden kann. Es gibt noch weitere Unterschiede zwischen diesen beiden Betriebssystemen. Tabelle 16.2 zeigt eine Gegenüberstellung von Linux/UNIX und Microsoft-Systemen. Eigenschaft | Linux | MS-Windows | | --- | --- | --- | | | | | | | ### 16.5.1 Modus für »fopen()« AuÃer dem Lesezugriff ("r"), den Sie bereits verwendet haben, gibt es eine Reihe weiterer Zugriffsmöglichkeiten auf einen Stream. Tabelle 16.3 enthält einen Ãberblick über die vorhandenen Modi und deren Bedeutung. Damit dieses Buch auch als Referenz zu gebrauchen ist, bietet Tabelle 16.4 eine schnellere Ãbersicht über die einzelnen Modi. Bewirkt | r | w | a | r+ | w+ | a+ | | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | An diese Modi können auÃerdem zwei weitere Zeichen angehängt werden, die zwischen Text- und Binärdateien unterscheiden (siehe Tabelle 16.5). Zusätzlicher Modus | Bedeutung | | --- | --- | | | | | Lassen Sie ich kurz den Unterschied zwischen Textdateien und Binärdateien erläutern: Textdateien sind für den Menschen mit einem Editor lesbar, wogegen Binärdateien bzw. binäre Zeichen (0,1) die Sprache bilden, die der Computer versteht. Für einen Menschen sind Binärdateien kaum lesbar. Daher bestehen Textdateien immer aus sichtbaren ASCII-Zeichen und ein paar Steuercodes, wie etwa Zeilenschaltungen oder Tabulatoren. Für die Bearbeitung reiner Textdateien ist der Modus t gedacht. Da bei MS-DOS ein Zeilenende mit der Sequenz \r\n angezeigt wird und bei Linux nur durch ein einzelnes \n, führen Compiler für MS-DOS/Windows im Textmodus t folgende Konvertierung durch: * Beim Schreiben in eine Textdatei wird ein \n automatisch in ein \r\n konvertiert. * Beim Lesen einer Textdatei wird ein \r\n in ein einzelnes \n konvertiert. * Beim Lesen einer Textdatei wird die Tastenkombination + (unter MS-Windows/DOS) und + (unter Linux/UNIX) als Dateiende interpretiert und liefert automatisch EOF (End Of File). Im Binärmodus wird diese Konvertierung nicht vorgenommen. Bei Linux/UNIX bedeutet das b nichts, wie in Tabelle 16.5 schon erwähnt wurde, und wird bei Verwendung ignoriert. Unter Linux wird auÃerdem jede Datei binär gespeichert. Den Namen der zu öffnenden Datei können Sie natürlich auch mithilfe von Argumenten aus der Kommandozeile angeben. Ein Beispiel: > /* fopen2.c */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *datei; if(argc < 2) { printf("Verwendung : %s [datei_zum_Oeffnen]\n", *argv); return EXIT_FAILURE; } datei = fopen(argv[1], "r"); if(datei != NULL) printf("Datei erfolgreich geöffnet\n"); else { printf("Fehler beim Ãffnen der Datei"); return EXIT_FAILURE; } return EXIT_SUCCESS; } Zuerst wird überprüft, ob zwei Argumente in der Kommandozeile eingegeben wurden. Ist dies nicht der Fall, wird eine entsprechende Fehlermeldung ausgegeben. Ansonsten wird versucht, die Datei zu öffnen, die Sie in der Kommandozeile mit dem zweiten Argument angegeben haben. Tritt dabei ein Fehler auf, liegt dies meistens an einer falschen Pfadangabe oder unzureichenden Rechten einer Datei. ### 16.5.2 Maximale Anzahl geöffneter Dateien – »FOPEN_MAX« Bei einem Programm, bei dem sehr viele Dateien gleichzeitig geöffnet werden, sollten Sie eine Ãberprüfung mit der Konstante FOPEN_MAX aus der Headerdatei <stdio.h> vornehmen. Diese Konstante legt fest, wie viele Dateien gleichzeitig pro Prozess geöffnet werden dürfen. Testen können Sie dies z. B. so: > /* fopen3.c */ #include <stdio.h> #include <stdlib.h> int main(void) { printf("Max. offene Dateien : %d\n",FOPEN_MAX); return EXIT_SUCCESS; } Hinweis für Fortgeschrittene | | --- | | Damit alles reibungslos mit dem erfolgreich zurückgegebenen Stream verläuft und Sie problemlos in Dateien schreiben bzw. aus diesen lesen können, müssen Sie bei der Anwendung der Funktion fopen() noch folgende Punkte berücksichtigen: * Fehlerflags und EOF-Flags werden beim Ãffnen einer Datei zurückgesetzt. * Wollen Sie, nachdem Sie aus einem Stream gelesen haben, in diesen schreiben, so geht dies nur, wenn Sie vorher eine der folgenden Funktionen verwenden: fflush(), fsetpos(), fseek() oder rewind(). * Wollen Sie aus einem Stream lesen, in den Sie zuvor geschrieben haben, dann müssen Sie eine der Funktionen fsetpos(), fseek() oder rewind() verwenden; auÃer es wurde das Dateiende (EOF) gelesen. Machen Sie sich keine Sorgen, falls Sie diese Punkte noch nicht verstanden haben – Sie werden auf den nächsten Seiten aufgeklärt. # 16.6 Zeichenweise lesen und schreiben – »getchar()« und »putchar()« ## 16.6 Zeichenweise lesen und schreiben – »getchar()« und »putchar()« Um zeichenweise aus dem Stream stdin (Standardeingabe) zu lesen und zeichenweise auf stdout (Standardausgabe) zu schreiben, können Sie folgende Funktionen verwenden: > #include <stdio.h> // Lesen (zeichenweise) von stdin int getchar(); // Schreiben (zeichenweise) auf stdout int putchar(int c); getchar() dient zum Einlesen einzelner Zeichen von der Standardeingabe; normalerweise ist dies die Tastatur. Ein wenig verwirrend dürfte der Rückgabewert der Funktion getchar() sein, da dieser vom Datentyp int ist. Das liegt daran, dass ein char vor der Verwendung eines Ausdrucks in ein int konvertiert wird. Etwas genauer: Das Problem der Verwendung von int liegt in der Konstante EOF (End of File), die das Ende einer Eingabe anzeigt. EOF ist eine define-Konstante, die in der Headerdatei <stdio.h> mit dem Wert –1 deklariert ist, damit sie nicht mit den normalen ASCII-Zeichen kollidiert. Früher, als noch 127 Zeichen verwendet wurden, war das kein Problem. Heute sind die Werte der Zeichen gröÃer als 127, um zum Beispiel Umlaute wie ä, ö, ü und à ausgeben zu können. Ist char dabei mit unsigned deklariert, könnten Zeichen zwischen 0 ... 255 Platz darin finden. Es ist dann aber kein Platz mehr für EOF (-1). Daher wurde einfach der Rückgabewert von getchar() als int deklariert, und damit können sowohl die 255 Zeichen als auch das EOF übermittelt werden – das Problem war gelöst. Hierzu ein Listing: > /* echo_char.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int c; while( (c = getchar()) !='.') putchar(c); return EXIT_SUCCESS; } Wenn hierbei mehrere Zeichen eingegeben werden und gedrückt wird, wird der Text Zeichen für Zeichen auf dem Bildschirm ausgegeben. Dies geschieht so lange, bis ein einzelnes Zeichen dem eines Punktes entspricht. Dann ist die while-Bedingung unwahr. Sie können als Abbruchbedingung auch EOF angeben: > while((c = getchar()) != EOF); Hiermit werden so lange Zeichen eingelesen, bis die Tastenkombination + (unter MS-Systemen) oder + (unter Linux) gedrückt wird, die EOF nachbildet. Hinweis für Programmierneulinge | | --- | | Neben den byte-orientierten Funktionen getchar() und putchar() gibt es natürlich auch dieselben Funktionen für breite Zeichen. Hier sehen Sie die Syntax dazu: > #include <wchar.h> // breite Zeichen von stdin (zeichenweise) einlesen wint_t getwchar(); // breite Zeichen auf stdout (zeichenweise) ausgeben wint_t putwchar(wint_t wc); Der primitive Datentyp wint_t ist ein ganzzahliger Typ, der mindestens den Wertebereich des Typs wchar_t speichern kann. Zusätzlich kann wint_t auch den Wert WEOF speichern. WEOF ist ein Makro (ebenfalls vom Typ win_t) und ist ein Wert, der nicht mit einem erweiterten breiten Zeichensatz übereinstimmt. WEOF ist also das breite Gegenstück zu EOF, mit dem Unterschied, dass der Wert von WEOF nicht negativ sein muss. Hier sehen Sie das breite Gegenbeispiel zum Listing echo_char.c mit wide-orientierten Streams: > /* echo_wchar.c */ #include <stdlib.h> #include <wchar.h> int main(void) { wint_t c; while( (c = getwchar()) != L'.') putwchar(c); return EXIT_SUCCESS; } Zur Funktion getchar() noch ein Listing: > /* count_char.c */ #include <stdio.h> #include <stdlib.h> int main (void) { int c,counter=0; printf("Bitte Eingabe machen:"); /* Eingabe machen, bis mit Return beendet wird */ while((c=getchar()) != '\n') { /* Leerzeichen und Tabulatorzeichen nicht mitzählen */ if( (c != ' ') && (c != '\t') ) counter++; /* counter erhöhen */ } /* Gibt die Anzahl eingegeb. Zeichen von 0 bis counter-1 aus. * Mit counter-1 wird das Zeichen '\0' nicht mitgezählt. */ printf("Anzahl der Zeichen beträgt %d Zeichen\n", counter-1); return EXIT_SUCCESS; } Mit diesem Listing werden alle darstellbaren Zeichen gezählt, die Sie über die Tastatur eingeben. Leerzeichen und Tabulatoren werden jedoch nicht mitgezählt. ### 16.6.1 Ein etwas portableres »getch()« Die folgende Frage wurde mir bereits unzählige Male gestellt: Wie kann ich den Programmablauf anhalten, bis eine bestimmte Taste gedrückt wird? Dafür gibt es leider keinen standardisierten Weg. Aber um Sie jetzt nicht im Regen stehen zu lassen, folgt hierfür ein etwas portableres getch(), das sowohl unter Linux/UNIX als auch unter MS-Windows funktioniert. Ihnen diese Funktion speziell unter Linux/UNIX näher zu erklären, würde ein wenig zu weit führen. Bei MS-Windows gibt es dabei nicht viel zu sagen, nur dass die Headerdatei <conio.h> mit eingebunden werden muss, da sich darin diese Funktion befindet. Hier der Quellcode: > /* portable_getch.c */ #include <stdio.h> #include <stdlib.h> /* ... übersetzt unter Linux/UNIX? */ #ifdef __unix__ #include <termios.h> #include <unistd.h> static struct termios new_io; static struct termios old_io; /* Funktion schaltet das Terminal in den cbreak-Modus: */ /* Kontrollflag ECHO und ICANON auf 0 setzen */ /* Steuerzeichen: Leseoperation liefert 1 Byte VMIN=1 VTIME=1 */ int cbreak(int fd) { /*Sichern unseres Terminals*/ if((tcgetattr(fd, &old_io)) == -1) return -1; new_io = old_io; /* Wir verändern jetzt die Flags für den cbreak-Modus. */ new_io.c_lflag = new_io.c_lflag & ~(ECHO|ICANON); new_io.c_cc[VMIN] = 1; new_io.c_cc[VTIME]= 0; /*Jetzt setzen wir den cbreak-Modus*/ if((tcsetattr(fd, TCSAFLUSH, &new_io)) == -1) return -1; return 1; } int getch(void) { int c; if(cbreak(STDIN_FILENO) == -1) { printf("Fehler bei der Funktion cbreak ... \n"); exit(EXIT_FAILURE); } c = getchar(); /* alten Terminal-Modus wiederherstellen */ tcsetattr(STDIN_FILENO, TCSANOW, &old_io); return c; } /* ... oder wird das Programm unter MS-Windows übersetzt? */ #elif __WIN32__ || _MSC_VER || __MS_DOS__ #include <conio.h> #endif int main(void) { int zeichen; printf("Bitte 'q' drücken, um das Programm zu beenden!\n"); /* Wartet auf das Zeichen q. */ while(( zeichen=getch() ) != 'q'); return EXIT_SUCCESS; } # 16.7 Zeichenweise lesen und schreiben – »putc()«/»fputc()« und »getc()«/»fgetc()« ## 16.7 Zeichenweise lesen und schreiben – »putc()«/»fputc()« und »getc()«/»fgetc()« Die Funktionen getc() und fgetc() sind das dateiorientierte Gegenstück zu getchar(). Sie werden verwendet, um einzelne Zeichen aus einem Stream zu lesen, der zuvor mit fopen() geöffnet wurde. Der Unterschied zwischen getc() und fgetc() besteht darin, dass fgetc() als eine Funktion implementiert ist und getc() ein Makro sein darf. Hier sehen Sie die Syntax dazu: > #include <stdio.h> int getc(FILE *datei); int fgetc(FILE *datei); Folgende beiden Schreibweisen sind dabei identisch: > // Liest ein Zeichen aus der Standardeingabe. getchar(); // Liest ebenfalls ein Zeichen aus der Standardeingabe. fgetc(stdin); Dazu folgt ein Listing, das eine Datei zum Lesen öffnet und anschlieÃend den Inhalt der Datei Zeichen für Zeichen auf dem Bildschirm ausgibt. Eingelesen wird so lange, bis das Zeichen für Dateiende oder Fehler erreicht wird (EOF). > /* fgetc1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int c; FILE *datei; datei=fopen("test.txt", "r"); if(datei != NULL) { while( (c=fgetc(datei)) != EOF) putchar(c); } else { printf("Konnte Datei nicht finden bzw. öffnen!\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } Bei diesem Programm wird zuerst versucht, eine Textdatei im Lesemodus zu öffnen. Falls dies gelungen ist, wird der Text zeichenweise ausgelesen mit > while( (c=fgetc(datei)) != EOF) und mit putchar() zeichenweise auf dem Bildschirm ausgegeben, bis ein Fehler oder EOF auftritt. Das Programm soll nun ein wenig erweitert werden: > /* fgetc2.c */ #include <stdio.h> #include <stdlib.h> void read_char(FILE *stream) { int c; while( (c=fgetc(stream)) !=EOF) putchar(c); } int main(int argc, char **argv) { FILE *datei; char filename[255]; /* Falls die Datei zum Ãffnen nicht * als Argument übergeben wurde ... */ if(argc < 2) { printf("Welche Datei wollen Sie öffnen : "); scanf("%s",filename); datei = fopen(filename ,"r"); if(datei != NULL) read_char(datei); else { printf("Fehler beim Ãffnen von %s\n",filename); return EXIT_FAILURE; } } else { datei=fopen(argv[1],"r"); if(datei != NULL) read_char(datei); else { printf("Konnte %s nicht öffnen!\n",argv[1]); return EXIT_FAILURE; } } return EXIT_SUCCESS; } In diesem Beispiel kann die Datei, die es zu öffnen gilt, entweder über die Kommandozeile eingegeben werden oder erst nach dem Start des Programms. Es empfiehlt sich, diese Schreibweise allgemein für Konsolenprogramme zu verwenden. Damit ist zumindest sichergestellt, dass auch Anwender, die mit dem Programm nicht vertraut sind, es bedienen können. Als Nächstes betrachten wir das Gegenstück der Funktionen getc() und fgetc(). Für die beiden Funktionen putc() und fputc() gilt hinsichtlich ihres Unterschieds dasselbe wie bei getc() und fgetc(). fputc() ist somit als Funktion implementiert, und putc() darf ein Makro sein. Mit putc()/fputc() kann zeichenweise in einen Stream geschrieben werden. Die Syntax dieser Funktionen lautet: > #include <stdio.h> int putc(int quelle, FILE *ziel); int fputc(int quelle, FILE *ziel) ; Damit wird das Zeichen quelle in den Stream ziel geschrieben. Der Rückgabewert ist das Zeichen in quelle oder bei einem Fehler bzw. am Dateiende EOF. Dazu ein Listing, mit dem Sie eine Datei zeichenweise kopieren können: > /* copy_char4char.c */ #include <stdio.h> #include <stdlib.h> int main(void) { FILE *quelle, *ziel; int c; char name_q[255], name_z[255]; printf("Name der Quelldatei : "); scanf("%s",name_q); quelle=fopen(name_q,"rb"); if(quelle == NULL) { printf("Konnte %s nicht finden bzw. öffnen!\n",name_q); return EXIT_FAILURE; } else { printf("Name der Zieldatei : "); scanf("%s",name_z); ziel=fopen(name_z,"w+b"); if(ziel==NULL) { printf("Konnte Zieldatei nicht erzeugen!\n"); return EXIT_FAILURE; } else { /* Wir kopieren zeichenweise von quelle nach ziel. */ while( (c=getc(quelle)) != EOF) putc(c,ziel); } } return EXIT_SUCCESS; } In diesem Beispiel werden zwei Streams verwendet – einer, mit dem die Datei geöffnet wird, um daraus zu lesen, und ein zweiter, mit dem in eine weitere geöffnete Datei geschrieben wird: > FILE *quelle, *ziel; Passend werden diese Streams quelle und ziel benannt. Zuerst wird eine Datei zum Lesen im "rb"-Modus geöffnet. AnschlieÃend erfolgt eine Abfrage, wie die Zieldatei heiÃen soll. Falls die Zieldatei nicht existiert, wird diese erzeugt. Andernfalls wird diese Datei einfach überschrieben, da der Modus "w+" verwendet wurde. Hier wird auÃerdem der binäre Modus eingesetzt, da der Inhalt in diesem Fall beim Kopieren nicht von Interesse ist. Unter UNIX/Linux hat das b für den Binärmodus keine Bedeutung und wird somit ignoriert: > ziel = fopen(name_z, "w+b"); AnschlieÃend wird überprüft, ob die Datei zum Schreiben im Binärmodus geöffnet werden konnte. Danach kann zeichenweise von der Quelldatei gelesen und in die Zieldatei geschrieben werden: > while( (c=getc(quelle)) != EOF) putc(c,ziel); Wenn alles problemlos verlaufen ist, wurde eine exakte Kopie der Quelldatei erstellt – mit dem Namen, der als Zieldatei angegeben wurde. Dazu ein weiteres Beispiel, wann eine zeichenweise Abarbeitung von Daten sinnvoller erscheint. Jeder, der an einer Webseite arbeitet, kennt das Problem: Viel Text muss ins HTML-Format konvertiert werden. Wird dabei einmal das Zeichen '<' vergessen, das ein HTML-Tag einleitet, ist manchmal der vollständige Text bis zum nächsten mit '>' schlieÃenden Tag futsch. Das folgende Programm soll alle Sonderzeichen in das HTML-Format konvertieren. Folgende Regeln gelten: > Ersetze das Zeichen ä durch die Zeichenfolge &auml; Ersetze das Zeichen à durch die Zeichenfolge &Auml; Ersetze das Zeichen ö durch die Zeichenfolge &ouml; Ersetze das Zeichen à durch die Zeichenfolge &Ouml; Ersetze das Zeichen ü durch die Zeichenfolge &uuml; Ersetze das Zeichen à durch die Zeichenfolge &Uuml; Ersetze das Zeichen à durch die Zeichenfolge &szlig; Ersetze das Zeichen < durch die Zeichenfolge &lt; Ersetze das Zeichen > durch die Zeichenfolge &gt; Ersetze das Zeichen & durch die Zeichenfolge &amp; Ersetze das Zeichen " durch die Zeichenfolge &quot; Der Quellcode dazu lautet: > /* txt2html_example.c */ #include <stdio.h> #include <stdlib.h> /* nchars = Anzahl der Zeichen */ /* tag = Sonderzeichen in HTML */ /* ziel = Datei, in die geschrieben wird */ void sonderzeichen(int nchars, char *tag, FILE *ziel) { int i; char zeichen; for(i = 0; i < nchars; i++) { zeichen = tag[i]; putc(zeichen, ziel); } } int main(int argc, char **argv) { FILE *q, *z; int zeichen; if(argc < 3) { printf("Benutzung : %s quelle ziel\n", *argv); return EXIT_FAILURE; } q = fopen(argv[1], "r"); z = fopen(argv[2], "w"); if(q == NULL || z == NULL) { printf("Fehler bei Oeffnen einer Datei ...\n"); return EXIT_FAILURE; } while((zeichen=getc(q)) != EOF) { if(zeichen=='<') sonderzeichen(4,"&lt;", z); else if(zeichen=='>') sonderzeichen(4,"&gt;", z); else if(zeichen=='\"') sonderzeichen(6,"&quot;",z); else if(zeichen=='&') sonderzeichen(5,"&amp;",z); else if(zeichen=='ä') sonderzeichen(6 ,"&auml;",z); else if(zeichen=='Ã') sonderzeichen(6 ,"&Auml;",z); else if(zeichen=='ö') sonderzeichen(6 ,"&ouml;",z); else if(zeichen=='Ã') sonderzeichen(6 ,"&Ouml;",z); else if(zeichen=='ü') sonderzeichen(6 ,"&uuml;",z); else if(zeichen=='Ã') sonderzeichen(6 ,"&Uuml;",z); else if(zeichen=='Ã') sonderzeichen(6 ,"&szlig;",z); else putc(zeichen, z); } return EXIT_SUCCESS; } Schon haben Sie mit ein paar Zeilen Code die Light-Version eines Text2Html-Konverters geschrieben. Natürlich gibt es auch bei den byte-orientierten Funktionen fgetc/getc bzw. fputc/putc die Gegenstücke für breite Zeichen. Die Syntax dazu lautet: > #include <wchar.h> // Breite Zeichen lesen wint_t fgetwc( FILE *fp ); wint_t getwc( FILE *fp ); // Breite Zeichen schreiben wint_t fputwc( wchar_t wc, FILE *fp ); wint_t putwc( wchar_t wc, FILE *fp ); Ansonsten gilt für die breiten Gegenstücke dasselbe, was ich schon zuvor bei den Funktionen getwchar() und putwchar() gesagt habe. # 16.8 Datei (Stream) schlieÃen – »fclose()« ## 16.8 Datei (Stream) schlieÃen – »fclose()« Die Funktion fclose() schlieÃt eine Datei (Stream), die zuvor mit fopen() geöffnet wurde. Was soll das bringen? Wenn sich ein Programm beendet, schlieÃen sich automatisch alle noch offenen Streams. Es gibt zwei gute Gründe, dies dennoch selbst zu tun: * Die Anzahl der geöffneten Dateien ist begrenzt. Sie ist in der Konstante FOPEN_MAX in der Headerdatei <stdio.h> deklariert. Wird versucht, FOPEN_MAX+1 Dateien zu öffnen, dann schlägt dies fehl. Mit fclose() kann wieder ein FILE-Zeiger freigegeben werden. * Wenn eine Datei im Schreibmodus geöffnet wurde, wird diese erst beschrieben, wenn der Puffer voll ist. Ist der Puffer nur teilweise voll und das Programm beendet sich mit einem Fehler, dann sind die Daten im Puffer verloren. Die Syntax von fclose() ist: > #include <stdio.h> int fclose(FILE *f); Hiermit wird der Stream geschlossen, und f vom Typ FILE ist wieder für weitere Verwendungen freigegeben. Hierzu ein kleines Listing: > /* fclose.c */ #include <stdio.h> #include <stdlib.h> int main(void) { FILE *quell,*ziel; char quellname[20],zielname[20]; int c, wahl; printf("Bitte geben Sie den Namen der Zieldatei an : "); scanf("%19s",zielname); if( (ziel=fopen(zielname,"a+")) == NULL) { printf("Konnte \"%s\" nicht erstellen bzw. finden!\n", zielname); printf("...oder Sie haben unzureichende Rechte \n"); return EXIT_FAILURE; } do { printf("Welche Datei wollen Sie in " "die Zieldatei schreiben,\n"); printf("bzw. anhängen (name.xxx) : "); scanf("%19s",quellname); quell= fopen(quellname,"r"); if(NULL == quell) { printf("Konnte %s nicht öffnen!\n",quellname); return EXIT_FAILURE; } else { while((c=getc(quell)) != EOF) putc(c,ziel); fclose(quell); } printf("Weitere Datei an %s anhängen (1=ja/2=nein): ", zielname); scanf("%1d",&wahl); } while(wahl == 1); return EXIT_SUCCESS; } Zuerst wird eine Datei geöffnet oder – falls noch nicht vorhanden – neu erstellt. Diese Datei wird im Modus "a+" geöffnet, womit die schreibenden Daten immer an das Ende der Datei angehängt werden. AnschlieÃend werden in der do while-Schleife Dateien zum Lesen mit dem Modus "r" geöffnet, um den Inhalt immer an das Ende der Zieldatei zu hängen. Danach wird diese Datei wieder geschlossen: > fclose(quell); Damit ist der Zeiger quell wieder frei zum Ãffnen einer anderen Datei. Jetzt kann erneut eine Datei geöffnet werden, um diese wieder an das Ende der Zieldatei zu hängen. Der Modus "a+" eignet sich prima zum Erstellen einer Logdatei oder etwa um zu kontrollieren, was die Mitarbeiter so alles mit und an dem PC treiben. Das Programm soll wieder ein wenig flexibler gemacht werden. Wird z. B. > programm alles.txt name1.txt name2.txt home/C1/adressen.txt eingegeben, werden die Dateien mit den Namen name1.txt, name2.txt und die Datei im Verzeichnis /home/C1/adressen.txt in einer neu erstellten Datei, hier alles.txt, angehängt. Das Schema das Aufrufs lautet also: > <Programmname><Ziel><Quelle1><Quelle2><Quelle_n> Die Verwendung von zwei Streams (FILE *quelle,*ziel) in Verbindung mit der Funktion fclose() wird im folgenden Beispiel dargestellt. > /* file_cat.c */ #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { FILE *quell,*ziel; char c; int i; if(argc < 3) { printf("Fehler!!!!\n"); printf("Mindestens 3 Argumente angeben :\n"); printf("<Programmname><Ziel><Quelle1>" "(<Quelle2><Quelle_n>) \n"); return EXIT_FAILURE; } ziel = fopen(argv[1], "a+"); if(ziel == NULL) { printf("Konnte \"%s\" nicht erstellen bzw. nicht" " finden!\n", argv[1]); return EXIT_FAILURE; } for(i = 2; i < argc; i++) { if(argv[i] != NULL) { quell = fopen(argv[i], "r"); if(NULL == quell) { printf("Konnte %s nicht öffnen\n", argv[i]); return EXIT_FAILURE; } else { while((c=getc(quell)) != EOF) putc(c,ziel); fclose(quell); } } } fclose(ziel); return EXIT_SUCCESS; } fprintf() und fscanf() sind die dateiorientierten Gegenstücke zu den Funktionen printf() und scanf(). Ihre Syntax sieht so aus: > #include <stdio.h> int fprintf(FILE *f, const char * restrict format, ...); int fscanf(FILE *f, const char * restrict format, ...); Natürlich würde mit > fscanf(stdin, "%d", &x); fprintf(stdout, "<NAME>\n"); dasselbe erreicht wie mit: > scanf("%d", &x); printf("<NAME>\n"); Beide Schreibweisen lesen bzw. schreiben formatiert auf die Streams stdin bzw. stdout. fprintf() werden gern benutzt, um durch den Stream stderr eine Meldung auf die Standardfehlerausgabe (Bildschirm) ungepuffert auszugeben. Ein klassischer Fall von fprintf() und fscanf() ist das formatierte Einlesen einer CSV-Datei, die Sie mit Tabellenkalkulationsprogrammen erzeugen und ansehen können. Das Thema wurde in Kapitel 11, »Arrays«, bereits einmal erwähnt. Folgende CSV-Logdatei soll protokolliert werden. Darin steht, wer wann und wie lange am System eingeloggt war: > 20:23,12.11.2001,20:50,12.11.2001,Pinguin 12:13,13.11.2001,15:29,13.11.2001,root 16:33,13.11.2001,20:23,13.11.2001,Mr.X 23:11,13.11.2001,01:12,14.11.2001,root 10:22,14.11.2001,12:14,14.11.2001,Spock 16:33,14.11.2001,20:21,14.11.2001,Scotty Die Kommas stellen dabei Trennzeichen dar. Folgende Variablen werden benötigt: > Uhrzeit eingeloggt, Datum, Uhrzeit ausgeloggt, Datum, User Der Name dieser Datei sei log.csv. Um diese Datei auszulesen, sollen die beiden Funktionen fprintf() und fscanf() eingesetzt werden. Hier sehen Sie den Quellcode zum Einlesen und Ausgeben der Logdatei: > /* csv_log.c */ #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { FILE *CSV; int login_hour, login_min; int date_day, date_mon, date_year; char name[40]; int logout_hour, logout_min; int date_dayx, date_monx, date_yearx; if(argc < 2) { fprintf(stderr, "Verwendung : %s datei.csv\n", *argv); return EXIT_FAILURE; } CSV = fopen(argv[1], "r"); if(NULL == CSV) { fprintf(stderr, "Fehler beim Oeffnen ...\n"); return EXIT_FAILURE; } /* Nun lesen Sie formatiert von der Datei ein ... */ while((fscanf(CSV,"%d:%d,%d.%d.%d,%d:%d,%d.%d.%d,%s\n", &login_hour,&login_min,&date_day,&date_mon,&date_year, &logout_hour,&logout_min,&date_dayx,&date_monx, &date_yearx,name)) != EOF ) fprintf(stdout,"User:%s\nLogin um:%d:%d Uhr am %d.%d.%d\n" "Logout um : %d:%d Uhr am %d.%d.%d\n\n", name,login_hour,login_min,date_day,date_mon,date_year, logout_hour,logout_min,date_dayx,date_monx, date_yearx); return EXIT_SUCCESS; } Meistens lässt sich das Einlesen solcher Dateien allerdings nicht so leicht realisieren wie hier dargestellt. Folgendes Beispiel ist schon wesentlich komplexer: > 20:23,12.11.2001,"pinguin",20:50,12.11.2001 Versuchen Sie es zunächst ruhig selbst, diese Zeile mit fscanf() einzulesen. Das Problem liegt in diesem Beispiel beim String pinguin und den doppelten Hochkommata. Hier folgt die Möglichkeit, wie der User pinguin ohne GänsefüÃchen ausgelesen wird: ``` char begrenzer; ... while((fscanf(CSV,"%d:%d,%d.%d.%d,\"%[^'\"]%c,%d:%d,%d.%d.%d\n", &login_hour,&login_min,&date_day,&date_mon,&date_year, name,&begrenzer,&logout_hour,&logout_min, &date_dayx,&date_monx,&date_yearx)) != EOF ) ``` Auf den ersten Blick mag dies zwar logisch sein, aber darauf muss man erst einmal kommen. Zwar ist dieser Ansatz, CSV-Dateien einzulesen, schon recht praktisch, doch er ist vollkommen inflexibel. Das Programm liest nur CSV-Dateien aus, deren Anordnung Sie kennen. Das würde heiÃen, für jede CSV-Datei müssten Sie den Code ändern, damit dieser wie eine Schablone in seine Form passt. Gut eignet sich auch fprintf() zum Erstellen von dynamischen Textdateien. Hierzu ein Beispiel, wie Sie dynamisch Webseiten erstellen können. Dafür wird zuvor einfach der Text2HTML-Konverter aus Abschnitt 16.7 erweitert: > /* txt2html.c */ #include <stdio.h> #include <stdlib.h> void html_head(FILE *ziel) { fprintf(ziel, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD" " HTML 4.0 Transitional//EN\">\n"); fprintf(ziel,"<html><head><title>Test-Webseite" "</title></head><body>\n"); fprintf(ziel,"<pre>\n"); fprintf(ziel,"<p style=\"margin-right:0.8cm; " " margin-left:0.5cm\" align=\"justify\">\n"); } void html_end(FILE *ziel) { fprintf(ziel,"</pre></p></body></html>\n"); } void sonderzeichen(int nchars, char *tag, FILE *ziel) { int i; char zeichen; for(i = 0; i < nchars; i++) { zeichen = tag[i]; putc(zeichen, ziel); } } int main(int argc, char **argv) { FILE *q, *z; int zeichen; if(argc < 3) { printf("Benutzung : %s quelle ziel\n",*argv); return EXIT_FAILURE; } q = fopen(argv[1], "r"); z = fopen(argv[2], "w"); if(q == NULL || z == NULL) { printf("Fehler bei fopen() ... "); return EXIT_SUCCESS; } /* Kopfzeile für HTML-Dokument */ html_head(z); while( (zeichen=getc(q)) != EOF) { if(zeichen=='<') sonderzeichen(4,"&lt;", z); else if(zeichen=='>') sonderzeichen(4,"&gt;", z); else if(zeichen=='\"') sonderzeichen(6,"&quot;",z); else if(zeichen=='&') sonderzeichen(5,"&amp;",z); else if(zeichen=='ä') sonderzeichen(6 ,"&auml;",z); else if(zeichen=='Ã') sonderzeichen(6 ,"&Auml;",z); else if(zeichen=='ö') sonderzeichen(6 ,"&ouml;",z); else if(zeichen=='Ã') sonderzeichen(6 ,"&Ouml;",z); else if(zeichen=='ü') sonderzeichen(6 ,"&uuml;",z); else if(zeichen=='Ã') sonderzeichen(6 ,"&Uuml;",z); else if(zeichen=='Ã') sonderzeichen(6 ,"&szlig;",z); else if(zeichen=='\n') /* Zeilenumbruch */ sonderzeichen(4, "<br>", z); else if(zeichen==' ') /* Leerzeichen */ sonderzeichen(6, " ", z); else putc(zeichen, z); } /* Ende von HTML-Datei */ html_end(z); return EXIT_SUCCESS; } Geben Sie nun in der Kommandozeile Folgendes ein (der Programmname sei t2html): > t2html myfile.txt myfile.hmtl Jetzt finden Sie im Verzeichnis eine HTML-Datei namens myfile.html, die aus der Datei myfile.txt mit dem Programm t2html erzeugt wurde. Diese HTML-Datei können Sie nun mit Ihrem Lieblingsbrowser öffnen und ansehen. # 16.10 Standard-Streams in C Date: 2016-10-01 Categories: Tags: ## 16.10 Standard-Streams in C Für jedes ausführbare Programm werden die folgenden Standard-Streams bereitgestellt: * stdin – Standardeingabe * stdout – Standardausgabe * stderr – Standardfehlerausgabe In der Regel ist der Stream stdin für die Eingabe über die Tastatur eingestellt. Für die Ausgabe auf dem Bildschirm sind die Streams stdout und stderr eingerichtet. Der Unterschied zwischen stdout und stderr besteht darin, dass stderr nicht gepuffert wird – im Gegensatz zu stdout. Daher liest jedes scanf() und fscanf() > scanf("%s", string); fscanf(stdin,"%s", string); von der Standardeingabe (Tastatur), und jedes printf() und fprintf() > printf("Hallo Welt\n"); fprintf(stdout, "Hallo Welt\n"); fprintf(stderr, "Fehler im Programm\n"); wird auf dem Bildschirm ausgegeben. Abbildung 16.1 Standard-Streams in C ### 16.10.1 Standard-Streams umleiten Mit dem folgenden Listing will ich Ihnen zeigen, wie Sie diese Streams umleiten können: > /* umleitung.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int c; while((c=getc(stdin)) != EOF) putc(c,stdout); return EXIT_SUCCESS; } Es wird so lange von stdin (Tastatur) eingelesen, bis EOF ( + bei Windows/MS-DOS und + bei UNIX) erzeugt wird. Wenn Sie drücken, wird die Eingabe auf stdout (Bildschirm) ausgegeben. Diese Standard-Streams lassen sich aber auch umleiten, etwa mit folgender Eingabe in der Kommandozeile: programmname < test.txt Abbildung 16.2 Standardeingabe umleiten (»stdin«) Mit dieser Umleitung wurde die Datei test.txt über die Standardeingabe (stdin) zum Programm umgeleitet. Damit lässt sich allerdings nun keine Eingabe mehr über die Tastatur vornehmen. Natürlich kann die Standardausgabe ebenso umgeleitet werden: > programmname < test.txt > kopietext.txt Abbildung 16.3 Standardeingabe und Standardausgabe umgeleitet Die Datei test.txt wird damit auf die Standardeingabe (stdin) und die Datei kopiertext.txt auf die Standardausgabe (stdout) umgeleitet. In diesem Fall wird gar nichts mehr auf dem Bildschirm ausgegeben, da die Standardausgabe (stdout) zu kopiertext.txt umgeleitet wurde. Natürlich wäre auch eine solche Umleitung möglich: > programmname > text.txt Hier wurde nur die Standardausgabe umgeleitet. Damit würde alles, was mit der Tastatur eingegeben wurde, in die Datei test.txt anstatt auf den Bildschirm geschrieben. Abbildung 16.4 Standardausgabe umgeleitet Auf Systemen, die den POSIX-Standard erfüllen (UNIX, Linux, FreeBSD ...), aber mittlerweile auch auf vielen anderen Compilern, sollten Sie statt der Standard-Streams stdin, stdout und stderr folgende Konstanten benutzen: * STDIN_FILENO für stdin * STDOUT_FILENO für stdout * STDERR_FILENO für stderr Diese Konstanten sind in der Headerdatei <unistd.h> deklariert, die daher im Programm mit eingebunden werden muss. In diesem Abschnitt folgen einige Funktionen, die nicht so häufig verwendet werden, aber durchaus von Bedeutung sind. Denn gerade die Fehlerbehandlung wird bei Programmen oft vernachlässigt. Zuerst die Syntax zu feof(): > #include <stdio.h> int feof(FILE *datei); Mit dieser Funktion können Sie einen Stream daraufhin testen, ob das EOF-Flag gesetzt ist oder nicht. Hierzu ein Beispiel: > /* feof.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int c; while( (c = getc(stdin)) ) if(feof(stdin) != 0) break; else putc(c,stdout); return EXIT_SUCCESS; } Das Programm dürfte Ihnen noch vom Abschnitt zuvor bekannt sein. Statt > while( (c=getc(stdin)) != EOF) wurde Folgendes geschrieben: > while(c = getc(stdin)) if(feof(stdin) != 0) Anstatt zu testen, ob der Wert der Variablen c demjenigen von EOF entspricht, wurde mit feof() geprüft, ob das EOF-Flag gesetzt ist. Falls nicht, gibt die Funktion 0 zurück, falls aber EOF gesetzt ist, gibt die Funktion ungleich 0 zurück. Wird die Funktion feof() bei längeren Programmen nochmals benötigt, muss vorher mit > clearerr(stdin); das EOF-Flag des entsprechenden Streams wieder auf 0 gesetzt werden. Natürlich können Sie anstatt des Streams stdin auch jeden anderen offenen Stream verwenden. Die Syntax von ferror() lautet: > #include <stdio.h> int ferror(FILE *datei); Die Funktion ferror() ist ähnlich wie feof(), nur dass die Datei auf das Fehler-Flag überprüft wird. Auch hier ist im Prinzip der Aufruf > if((quelle=fopen(argv[1],"r")) == NULL) gleichwertig zu: > quelle=fopen(argv[1], "r"); if(ferror(quelle)) Auch bei ferror() muss bei nochmaliger Verwendung die Funktion clearerr() verwendet werden, um das Fehler-Flag zurückzusetzen. Die Syntax von clearerr() lautet: > #include <stdio.h> void clearerr(FILE *datei); clearerr() dient zum Zurücksetzen des EOF- und des Fehler-Flags bei Streams. Mit der Funktion ungetc() können Sie das zuletzt gelesene Zeichen wieder zurück in den Stream schieben. Die Syntax lautet: > #include <stdio.h> int ungetc(int ch, FILE *datei); ungetc() schiebt das zuletzt mit der Funktion fgetc() oder fread() gelesene Zeichen ch in den Stream datei zurück. Im Fall eines Fehlers gibt diese Funktion EOF zurück. Damit ist das Zeichen ch das erste, das beim nächsten Lesen aus dem Stream datei wieder gelesen wird. Dies gilt allerdings nicht mehr, wenn vor dem nächsten Lesevorgang eine der Funktionen fflush(), rewind(), fseek() oder fsetpos() aufgerufen wurde. Ein Beispiel zu ungetc() wäre das Auslesen einer ständig wachsenden Textdatei. Das Programm liest zeichenweise aus einem Stream und gibt die Daten auch zeichenweise wieder auf die Standardausgabe aus, bis EOF erreicht wird. AnschlieÃend wird das zuletzt gelesene Zeichen (nicht EOF) wieder zurück in den Stream geschoben. Das Ganze wird in einer Endlosschleife ausgeführt. Hier sehen Sie den Code dazu: > /* grown_file.c */ #include <stdio.h> #include <stdlib.h> /* bitte anpassen */ #define DATEI "datei.txt" int main(void) { FILE *fp; int c; fp = fopen(DATEI, "r"); if(fp == NULL) { fprintf(stderr, "Konnte %s nicht öffnen\n", DATEI); return EXIT_SUCCESS; } while(1) { while( (c=fgetc(fp)) ) { /* zeichenweise einlesen */ if(c == EOF) /* Ist es EOF. */ ungetc(c,fp); /* letztes Zeichen zurück */ else fputc(c, stdout); /* ausgeben */ } } /* Wird nie erreicht. */ fclose(fp); return EXIT_SUCCESS; } Bei diesem Listing wird davon ausgegangen, dass eine Datei mit dem Namen datei.txt im selben Verzeichnis wie das Listing existiert. Der Inhalt dieser Datei sei folgender: > Eine Zeile in der Textdatei Die zweite Zeile ist diese hier Ãbersetzen Sie das Listing, und starten Sie das Programm. Ãffnen Sie jetzt die Textdatei datei.txt, und fügen Sie einen weiteren Text ein, zum Beispiel: > Eine Zeile in der Textdatei Die zweite Zeile ist diese hier Diese Zeile ist neu hinzugekommen Speichern Sie diesen Text wieder, und beachten Sie die weitere Ausführung des Programms. Die neu hinzugekommene Zeile wird ebenfalls ausgegeben. Theoretisch lieÃen sich damit in einem Netzwerk einzelne Dateien überwachen. Anstelle der Ausgabe auf dem Bildschirm könnte hierfür eine Nachricht an den Administrator geschickt werden. Vermutlich stellen Sie sich die Frage, wie es möglich ist, dass trotz eines EOF-Flags das Programm tadellos arbeitet, ohne beispielsweise die Funktion clearerr() aufzurufen. Das liegt daran, dass die Funktion ungetc() das EOF-Flag löscht und somit immer wieder nach dem Erreichen des Dateiendes ein Zeichen zurückschieben kann. ungetc() kann aber keine EOF-Konstante zurückschieben. Auch hierfür gibt es wieder die Version für breite Zeichen mit folgender Syntax: > #include <wchar.h> wint_t ungetwc( wint_t wc, FILE *fp ); Anstatt EOF wird hier im Fehlerfall natürlich WEOF zurückgeliefert. Ansonsten gilt dasselbe wie bei der byte-orientierten Version ungetc(). # 16.13 (Tastatur-)Puffer leeren – »fflush()« ## 16.13 (Tastatur-)Puffer leeren – »fflush()« Diese Funktion dürfte Ihnen aus Abschnitt 4.1, »Formatierte Eingabe mit Âscanf()«, bekannt vorkommen, als es darum ging, ein im Tastaturpuffer befindliches Zeichen wie '\n' (Newline-Zeichen) zu entfernen. Die Syntax von fflush(): > #include <stdio.h> int fflush(FILE *datei); Mit fflush() werden alle Inhalte von einem noch nicht geleerten Puffer eines Streams übertragen, die dem FILE-Zeiger datei zugeordnet sind (oder auch Standard-Streams). Das heiÃt kurz und bündig, die dem Stream zugeordneten Puffer werden geleert. Falls die Datei zum Schreiben geöffnet ist, werden die sich noch im Puffer befindlichen Zeichen physikalisch in die Datei geschrieben. War eine Datei zum Lesen geöffnet, werden die noch nicht gelesenen Zeichen im Eingabepuffer gelöscht. fflush() gibt bei Erfolg 0 zurück, andernfalls EOF. Es scheint aber nicht ganz klar, ob dies auch für Linux gültig ist. Auf Linux-Systemen will fflush() partout nicht funktionieren. Nehmen Sie etwa folgendes Programm: > /* fflush.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char x,y; printf("Bitte einen Buchstaben eingeben : "); scanf("%c",&x); fflush(stdin); printf("Bitte noch einen Buchstaben eingeben : "); scanf("%c",&y); printf("Sie gaben ein %c und %c \n",x,y); return EXIT_SUCCESS; } Sie können das Programm so verbiegen und verdrehen, wie Sie wollen, immer wird die zweite Ausgabe durch das sich im Puffer befindliche '\n'-Zeichen überdruckt. Das Argument von fflush() kann auch NULL sein. Ist dies der Fall, entleert fflush() die Ausgabepuffer aller Streams des Programms. Bei ungepuffertem Datenverkehr hat fflush() keine Wirkung. Der ANSI-C-Standard schreibt aber auch nicht vor, wie die Funktion fflush() auf den Stream stdin zu reagieren hat. Das Verhalten ist somit nicht definiert und kann funktionieren oder auch nicht. # 16.14 Stream positionieren – »fseek()«, »rewind()« und »ftell()« ## 16.14 Stream positionieren – »fseek()«, »rewind()« und »ftell()« Wenn Sie eine Datei öffnen, verweist ein Indikator für die Dateiposition (genauer gesagt der Schreib-/Lesezeiger) auf den Anfang der Datei, genauer gesagt auf das erste Zeichen mit der Position 0. Sie können sich dies gern wie bei einem gewöhnlichen char-Array vorstellen, wo jedes Zeichen an einer bestimmten Position ist. Nur dann, wenn Sie eine Datei im Anhängemodus (a bzw. a+) öffnen, verweist der Schreib-/Lesezeiger auf das Ende der Datei. Mit jeder Lese- oder Schreiboperation erhöht sich auch der Schreib-/Lesezeiger um die Anzahl der übertragenen Zeichen. Wenn Sie diesen sequenziellen Arbeitsfluss von Dateien ändern wollen, müssen Sie Funktionen für einen wahlfreien Dateizugriff verwenden. Hierfür stehen die Funktionen fseek(), rewind() und fsetpos() zur Verfügung. Zuerst die Syntax von fseek(): > #include <stdio.h> int fseek(FILE *datei, long offset, int origin); Mit fseek() kann der Schreib-/Lesezeiger des Streams datei verschoben werden. Die Positionierung wird mit offset und origin angegeben. origin gibt den Bezugspunkt an, von wo ab der Schreib-/Lesezeiger verschoben werden soll. offset gibt an, wie weit von diesem Bezugspunkt aus der Dateizeiger verschoben wird. Für origin sind drei symbolische Konstanten in der Headerdatei <stdio.h> deklariert (siehe Tabelle 16.6). Symbol | Wert | Offset-Rechnung ab | | --- | --- | --- | | | | | | | | | | Das folgende kleine Beispiel demonstriert die Funktionsweise von fseek(): > /* fseek.c */ #include <stdio.h> #include <stdlib.h> int main(void) { FILE *quelle, *fehler; int c; char datei[20]; long pos = 0; printf("Welche Datei wollen Sie oeffnen : "); scanf("%s",datei); fflush(stdin); if( (quelle=fopen(datei,"a+")) == NULL) { if((fehler=fopen("fehler.log","a+")) != NULL) { fprintf(fehler,"Konnte %s nicht oeffnen\n",datei); fprintf(stderr,"Konnte %s nicht oeffnen\n",datei); return EXIT_FAILURE; } fprintf(stderr,"Konnte %s nicht oeffnen\n",datei); return EXIT_FAILURE; } /* Das Zeichen '*' soll das Ende unserer Eingabe markieren. */ printf("Eingabe machen und mit '*' beenden\n"); while( (c=getc(stdin)) != '*') putc(c,quelle); /* Sie setzen den Zeiger quelle an den Anfang der Datei. */ fseek(quelle, 0L, SEEK_SET); /* Sie geben die ganze Datei auf dem Bildschirm aus. */ printf("\nAusgabe der kompletten Datei : \n"); while( (c=getc(quelle)) != EOF) putc(c,stdout); /* Zur Demonstration gehen Sie von der aktuellen Position * 10 Zeichen zurück und geben die letzten 10 Zeichen aus. */ printf("\nDie letzten 10 Zeichen : "); fseek(quelle, -10L, SEEK_CUR); while( (c=getc(quelle)) != EOF) putc(c,stdout); /* Sie legen selbst fest, wie viele Zeichen wir vom Start aus * einrücken wollen. */ printf("\nAnzahl der Stellen einruecken (vom Anfang): "); scanf("%ld",&pos); fflush(stdin); fseek(quelle, 0L, SEEK_SET); fseek(quelle, pos,SEEK_CUR); while( (c=getc(quelle)) != EOF) putc(c,stdout); return EXIT_SUCCESS; } Abbildung 16.5 Verschieben des Schreib-/Lesezeigers mit der Funktion »fseek()« Zuerst wird eine Datei geöffnet. Falls dies nicht gelingt, wird eine Datei mit dem Namen fehler.log beschrieben. AnschlieÃend wird so lange eine Eingabe gemacht, bis das Zeichen '*' eingegeben wurde. Die Eingabe wird an das Ende der Datei gehängt, oder es wird, falls keine Datei vorhanden ist, eine entsprechende Datei erzeugt ("a+"-Modus). Dann wird mit > fseek(quelle, 0L, SEEK_SET); der Schreib-/Lesezeiger des Streams quelle an den Anfang der Datei gesetzt, da SEEK_SET als Anfang der Datei deklariert ist. Wenn stattdessen Folgendes verwendet würde > fseek(quelle, 10L, SEEK_SET); wäre der Schreib-/Lesezeiger vom Anfang der Datei um zehn Bytes nach vorn verschoben, also dann zehn Zeichen vom Dateianfang entfernt. AnschlieÃend wird die vollständige Datei auf dem Bildschirm ausgegeben. Jetzt befindet sich der Schreib-/Lesezeiger am Ende der Datei. Als Nächstes wird mit > fseek(quelle, -10L, SEEK_CUR); der Schreib-/Lesezeiger um zehn Stellen von der aktuellen Position (SEEK_CUR) zurückgeschoben. Es ist also auch möglich, negative Werte für offset anzugeben. Dabei werden die zehn letzten Zeichen auf dem Bildschirm ausgegeben. Dann erfolgt eine Abfrage, um wie viele Stellen der Schreib-/Lesezeiger des Streams quelle vom Anfang der Datei verschoben werden soll. Dies wird gleich programmtechnisch umgesetzt mit: > fseek(quelle, pos,SEEK_CUR); Benötigen Sie die aktuelle Position des Schreib-/Lesezeigers im Stream datei, können Sie diesen mit der Funktion ftell() ermitteln. Die Syntax lautet: > long ftell(FILE *datei); Falls dabei ein Fehler auftritt, liefert diese Funktion einen Wert kleiner als 0 zurück. Bei Erfolg gibt sie die aktuelle Position des Schreib-/Lesezeigers in Byte zurück. Die Funktion ftell() können Sie ebenso einsetzen, um die GröÃe einer Datei in Byte zu ermitteln: > /* ftell.c */ #include <stdio.h> #include <stdlib.h> int main(void) { FILE *quelle; char datei[20]; printf("Welche Datei wollen Sie oeffnen : "); scanf("%s",datei); if( (quelle=fopen(datei, "r")) == NULL) { fprintf(stderr, "Konnte %s nicht oeffnen\n", datei); return EXIT_FAILURE; } /* Wir setzen den FILE-Zeiger ans Ende der Datei. */ fseek(quelle, 0L, SEEK_END); printf("Die Datei ist %ld Bytes gross!!\n", ftell(quelle)); return EXIT_SUCCESS; } Nachdem mit fseek() der FILE-Zeiger an das Ende der Datei positioniert wurde, kann mit ftell() die Position und auch die GröÃe in Byte abgefragt werden. ftell() liefert als Rückgabewert den Datentyp long. Es existiert auch eine andere Möglichkeit, den Schreib-/Lesezeiger wieder zurück an den Anfang der Datei zu setzen. Statt mit > fseek(quelle, 0L, SEEK_SET); kann dies auch mit der folgenden Funktion realisiert werden: > rewind(quelle); Beide Funktionen erfüllen denselben Zweck. Die Syntax von rewind() lautet: > #include <stdio.h> void rewind(FILE *datei); # 16.15 Stream positionieren – »fsetpos()«, »fgetpos()« ## 16.15 Stream positionieren – »fsetpos()«, »fgetpos()« Neben den Funktionen fseek() und ftell() gibt es noch eine weitere Möglichkeit zum Positionieren eines Schreib-/Lesezeigers. Wobei diese beiden Funktionen häufig gar nicht mehr erwähnt werden, da sie nicht mehr bieten als fseek() und ftell(). Die Syntax der beiden Funktionen sieht so aus: > #include <stdio.h> int fsetpos(FILE *datei, const fpos_t *pos); int fgetpos(FILE *datei, fpos_t *pos); Mit fsetpos() wird der Schreib-/Lesezeiger auf die Adresse von pos gesetzt. Die »Variable« fpos_t ist ein sogenannter primitiver Datentyp. Die Adresse, die für pos verwendet wird, sollte mit dem Aufruf der Funktion fgetpos() ermittelt werden. Hierzu ein Beispiel: > /* fpos.c */ #include <stdio.h> #include <stdlib.h> int main(void) { FILE *quelle; int c; char datei[20]; fpos_t pos; printf("Welche Datei wollen Sie oeffnen : "); scanf("%s",datei); if( (quelle=fopen(datei,"r")) == NULL) { fprintf(stderr, "Konnte %s nicht oeffnen!!\n", datei); return EXIT_FAILURE; } /* Wir lesen die aktuelle Position unseres FILE-Zeigers. */ fgetpos(quelle,&pos); printf("Der Positionszeiger zeigt auf Byte : %ld\n",pos); while( (c=getc(quelle)) != EOF) putc(c,stdout); printf("Groesse der Datei= Byte : %ld\n", ftell(quelle)); /* Wir setzen den FILE-Zeiger wieder an den Anfang der Datei. */ fsetpos(quelle,&pos); printf("Wir sind wieder an Position %ld\n",pos); return EXIT_SUCCESS; } Nachdem eine Datei zum Lesen geöffnet wurde, wird mit > fgetpos(quelle,&pos); die aktuelle Position des FILE-Zeigers quelle ermittelt. Die Position steht anschlieÃend in dem zu Beginn des Programms festgelegten Datentyp: > fpos_t pos; Die Adresse wird mit dem Adressoperator (&) in der Funktion fgetpos() an pos übergeben. Danach wird die Datei ausgelesen, mitsamt der GröÃe in Byte. Mit > fsetpos(quelle,&pos); wird der Stream-Zeiger wieder an den Dateianfang gesetzt. Dies hätten Sie auch mit folgender Funktion erreichen können: > rewind(quelle); Richtig eingesetzt sind diese beiden Funktionen recht nützlich, falls eine bestimmte Position in der Datei gespeichert wird, um später wieder zu ihr zurückzuspringen. # 16.16 Zeilenweise Ein-/Ausgabe von Streams Date: 2016-01-16 Categories: Tags: ## 16.16 Zeilenweise Ein-/Ausgabe von Streams ### 16.16.1 Zeilenweise lesen mit »gets()«/»fgets()« Nun folgen die Funktionen zum zeilenweisen Lesen und Schreiben von einem oder in einen Stream. Betrachten wir zuerst die Funktionen zum zeilenweisen Lesen: > #include <stdio.h> char *gets(char *puffer); char *fgets(char *puffer, int n, FILE *datei); wchar_t *fgetws( wchar_t *puffer, int n, FILE *datei); Mit fgets() (und der Version für breite Zeichen, fgetws()) werden zeilenweise n – 1 Zeichen vom Eingabe-Stream datei bis zum nächsten Newline-Zeichen gelesen. Die gelesene Zeile befindet sich in der Adresse von puffer mit dem Newline-Zeichen '\n' (bzw. L'\n') und dem abschlieÃenden '\0'-Zeichen (bzw. L'\0'). Mit gets() können Sie ebenso zeilenweise einlesen, allerdings nur von der Standardeingabe (stdin) und mit dem Unterschied, dass bei gets() das Newline-Zeichen durch das '\0'-Zeichen ersetzt wird. Alle drei Versionen liefern bei Erfolg das Argument puffer oder bei einem Fehler einen NULL-Zeiger zurück. Auch ein NULL-Zeiger wird zurückgeliefert, wenn das Dateiende erreicht wurde, ohne dass ein Zeichen gelesen wurde. gets() ist eine unsichere Funktion, weshalb es hierfür keine Version für breite Zeichen gibt. Ein Beispiel für die Verwendung von gets() wäre: > /* gets.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char name[20]; printf("Bitte geben Sie Ihren Namen ein : "); gets(name); /* Gefährlich */ printf("Hallo %s\n",name); return EXIT_SUCCESS; } Unter Linux/UNIX wird der Compiler bei diesem Programm vernünftigerweise eine Warnung ausgeben. Die Warnung, diese Funktion nicht zu verwenden, ist in Ordnung, aber vielleicht sollte ich gerade für Anfänger auch noch den Grund und die Alternativen bei der Fehlermeldung mit angeben. Da die Funktion gets() nicht die Anzahl der einzugebenden Zeichen überprüft, kann dies zu einem Pufferüberlauf (Buffer-Overflow) führen. Deshalb sollten Sie auf keinen Fall gets(), sondern die Funktion fgets() verwenden. Wenn Sie die Syntax von fgets() betrachten, bemerken Sie, dass sich darin auÃer der Zieladresse, in der die Daten eingelesen werden, zusätzlich ein Stream (FILE Zeiger) und ein Integer-Wert befinden, der die Anzahl der einzulesenden Zeichen festlegt. Mit fgets werden somit n Zeichen oder wird bis zum nächsten Newline ('\n') aus dem Stream in die Adresse von puffer gelesen, wobei der Stream eine beliebig geöffnete Datei oder auch die Standardeingabe (stdin) sein kann. Hierzu sehen Sie das vorige Beispiel mit fgets(): > /* fgets1.c */ #include <stdio.h> #include <stdlib.h> #define MAX 20 int main(void) { char name[MAX]; printf("Bitte geben Sie Ihren Namen ein : "); fgets(name, MAX, stdin); printf("Hallo %s",name); return EXIT_SUCCESS; } Sollten hier mehr als 20 Zeichen eingegeben werden, läuft das Programm trotzdem für immer anstandslos. Es werden 20 Zeichen bzw. 18 darstellbare Zeichen + '\n' + '\0' an den String name übergeben. Ein Vorteil ist, dass mit fgets() nicht nur von stdin gelesen werden kann, sondern auch von einem beliebigen Stream. Hier folgt ein Beispiel, wie Sie mit fgets() zeilenweise aus einer Datei lesen können: > /* fgets2.c */ #include <stdio.h> #include <stdlib.h> #define ZEILENLAENGE 80 int main(void) { FILE *quelle; char puffer[ZEILENLAENGE], name[20]; printf("Welche Datei wollen Sie zum Lesen öffnen: "); scanf("%s",name); if( (quelle=fopen(name,"r")) == NULL) { fprintf(stderr, "Kann %s nicht oeffnen\n", name); return EXIT_FAILURE; } while(fgets(puffer, ZEILENLAENGE, quelle)) fputs(puffer, stdout); return EXIT_SUCCESS; } Weil beim Einlesen vom Stream der Standardeingabe (stdin) mit fgets() auch das '\n'-Zeichen mit eingelesen wird, verwenden einige Programmierer – sei es aus Faulheit oder mangelndem Wissen – die Funktion gets(), obwohl sie wissen, dass sie diese Funktion nicht verwenden sollten. Häufig haben diese Programmierer Probleme mit dem Newline-Zeichen am Ende von Stringvergleichen, wie das folgende Beispiel zeigt: > /* fgets3.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define PASSWORT "Schiller" #define MAX 10 int main(void) { char pswd[MAX]; printf("Passwort: "); fgets(pswd, MAX, stdin); if(strcmp(PASSWORT, pswd) == 0) printf("Willkommen\n"); else printf("Passwort falsch\n"); return EXIT_SUCCESS; } Auch wenn hier der Benutzer das richtige Passwort eingibt, schlägt der Stringvergleich fehl, weil fgets() das Newline-Zeichen mit einliest. Dieses Problem lässt sich mit ein paar Zeilen Code beheben: > /* fgets4.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define PASSWORT "Schiller" #define MAX 10 void chomp(char *str) { size_t p=strlen(str); /* '\n' mit '\0' überschreiben */ str[p-1]='\0'; } int main(void) { char pswd[MAX]; printf("Passwort: "); fgets(pswd, MAX, stdin); /* ... letztes Zeichen vor \0 entfernen */ chomp(pswd); if(strcmp(PASSWORT, pswd) == 0) printf("Willkommen\n"); else printf("Passwort falsch\n"); return EXIT_SUCCESS; } Die Funktion chomp() tut nichts anderes, als das letzte Zeichen vor dem Terminierungszeichen '\0' zu entfernen. Dabei wird die Anzahl der Zeichen mit der Funktion strlen() gezählt. Zieht man von diesem Wert eins ab und verwendet ihn als Indexzähler mit dem Indizierungsoperator, befinden Sie sich ein Zeichen vor '\0'. ### 16.16.2 Zeilenweise schreiben mit »puts()«/»fputs()« Hier sehen Sie die Syntax der drei schreibenden Gegenstücke zu gets(), fgets() und fgetws(): > #include <stdio.h> int puts(const char *puffer); int fputs(const char *puffer, FILE *datei); int fputws(const wchar_t *puffer, FILE *datei); Mit puts() wird der null-terminierte String puffer auf dem Bildschirm (stdout) ausgegeben. AuÃerdem gibt puts() am Ende der Zeichenkette noch ein Newline-Zeichen mit aus, was die Funktion fputs() (bzw. fputws()) hingegen nicht macht. Im Gegensatz zu puts(), mit dem Sie nur auf die Standardausgabe (stdout) schreiben können, verwendet fputs() (bzw. die Version für breite Zeichen, fputws()), den geöffneten Ausgabe-Stream datei, in den geschrieben wird. Als Ausgabe-Stream ist eine Datei zulässig, die im Schreibmodus geöffnet wurde, oder auch die Standardausgabe (stdout). Das abschlieÃende Null-Zeichen wird von fputs() und fputws() nicht in den Ausgabe-Stream geschrieben. Der Rückgabewert von allen drei Funktionen ist im Falle eines Fehlers EOF (bzw. WEOF) oder bei Erfolg eine nicht-negative Ganzzahl. > /* fputs.c */ #include <stdio.h> #include <stdlib.h> #define ZEILENLAENGE 80 int main(void) { FILE *quelle, *kopie; char puffer[ZEILENLAENGE], name[20]; printf("Welche Datei wollen Sie zum Lesen öffnen: "); scanf("%s",name); if( (quelle=fopen(name,"r")) == NULL) { fprintf(stderr,"Kann %s nicht oeffnen\n",name); return EXIT_FAILURE; } if( (kopie=fopen("kopie.txt","w")) == NULL) { fprintf(stderr,"Kann kopie.txt nicht oeffnen\n"); return EXIT_FAILURE; } while(fgets(puffer,ZEILENLAENGE,quelle)) { fputs(puffer, kopie); puts(puffer); } return EXIT_SUCCESS; } fputs() wird hier eingesetzt, um den Puffer, der mit fgets() ausgelesen wurde, in eine Datei namens kopie.txt zu schreiben. puts() hingegen gibt alles auf dem Bildschirm aus. Somit wird eine Zeile in die Datei kopie.txt geschrieben und dasselbe gleich nochmals auf dem Bildschirm ausgegeben. ### 16.16.3 Zeilenweise vom Stream einlesen mit »getline()« (nicht ANSI C) Den Benutzern des GNU-GCC-Compilers sei noch die Funktion getline() ans Herz gelegt. Sie gehört zwar nicht zum Umfang von ANSI C, jedoch wird in The GNU C Library Reference Manual unter www.gnu.org explizit darauf verwiesen. Warum diese Funktion so besonders ist, wird im Anschluss erläutert. Die Funktion getline() kann als Ersatz für die E/A-Funktion fgets() verwendet werden oder noch allgemeiner – für das Einlesen einer Zeile von einem Stream. Zunächst aber sehen wir uns die Syntax der Funktion an, die in <stdio.h> deklariert ist: > ssize_t getline (char **lineptr, size_t *n, FILE *stream) Die Funktion liest eine Zeile inklusive dem Newline ('\n') und dem Stringende-Zeichen ('\0') in einen Puffer ein und speichert die Adresse des Puffers in *lineptr. Bevor Sie getline() aufrufen, sollten Sie in *lineptr die Adresse eines zuvor mit malloc() allozierten Puffers der Länge *n Bytes bereitstellen. Jetzt kommt der eigentliche Clou an der Sache: Ist der übergebene Puffer groà genug, erhalten Sie in etwa den Zustand, den Sie auch mit der Funktion fgets() erreichen können. Ist dies aber nicht der Fall, verhält sich getline() nicht wie fgets() und hört bei Ãberschreitung der angegebenen PuffergröÃe einfach auf, die Zeile einzulesen. Vielmehr wird der Puffer innerhalb der Funktion auf die erforderliche GröÃe mit realloc() angepasst. Wenn Sie sich dieses Szenario nun noch mit der Funktion gets() vorstellen, ist das eigenständige Kürzen der einzulesenden Zeile, wie es bei fgets() geschehen würde, noch das geringere Ãbel. Das war aber noch nicht alles. Wird *lineptr vor dem Aufruf mit einem NULL-Zeiger initialisiert und *n auf 0 gesetzt, übernimmt getline() die Bereitstellung des Speichers für die Zeile vollkommen selbstständig, und Sie müssen sich um nichts weiter kümmern. Die Funktion gibt die Anzahl der eingelesenen Zeichen inklusive des Zeilentrennzeichens ('\n'), aber ohne das abschlieÃende Terminierungszeichen ('\0') zurück – bei einem Fehler oder bei EOF erhalten Sie von getline() –1. Wenn Sie getline() verwenden wollen, müssen Sie die Konstante _GNU_SOURCE vor allen include-Anweisungen definieren. Laut der GNU-Dokumentation ist diese Funktion der empfohlene Weg, Zeilen vom Stream zu lesen. Sie gilt als die sicherste ihrer Art. In diesem Zusammenhang sei aber nochmals auf The GNU C Library Reference Manual verwiesen. Hier sehen Sie ein einfaches Beispiel für den Fall, dass Sie die Bereitstellung des Puffers vollständig getline() überlassen wollen: > /* getline.c */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <stddef.h> int main(void) { FILE *fd; /* bitte die Datei und eventuell den Pfad anpassen */ char *datei = "/home/user/testdatei.txt"; int nRet; size_t *t = malloc(0); char **gptr = malloc(sizeof(char*)); *gptr = NULL; if ( (fd = fopen(datei,"r")) == NULL) { fprintf(stderr, "\nKonnte Datei %s nicht öffnen!", datei); return EXIT_FAILURE; } while( (nRet=getline(gptr, t, fd)) > 0) fputs(*gptr,stdout); return EXIT_SUCCESS; } ### 16.16.4 Rezepte für zeilenweises Einlesen und Ausgeben Es folgen jetzt einige nützliche Listings, die häufig zum zeilenweisen Einlesen und Ausgeben benötigt werden. Es sind Beispiele, die sich mit Problemen wie den folgenden befassen: * Wie kann ich die n-te Zeile auslesen? * Wie kann ich alle Zeilen ausgeben, die eine bestimmte Stringfolge enthalten? * Suchen und Ersetzen in einer Textdatei (nur ganze Wörter, keine Teilstrings) # Wie kann ich die n-te Zeile auslesen? > /* read_nline.c */ #include <stdio.h> #include <stdlib.h> #define BUF 255 char temp[BUF]; char puffer[BUF]; /* Auslesen der n-ten Zeile */ char *getsline_number(int n, FILE *file) { int i; for(i = 0; i < n-1; i++) if(fgets(temp, BUF, file) == NULL) /* Bis zur n-ten Zeile lesen */ return NULL; /* Zeile scheint nicht zu existieren. */ /* Stream ist jetzt in der n-ten Zeile. */ if(fgets(puffer,BUF,file) == NULL) return NULL; /* Zeile scheint nicht zu existieren. */ return puffer; /* Zeile an Aufrufer zurückgeben */ } int main(int argc, char *argv[]) { FILE *f; unsigned int line; char *linenr; if(argc < 2) { fprintf(stderr, "Verwendung : %s datei\n",*argv); return EXIT_FAILURE; } f = fopen(argv[1],"r"); if(f == NULL) { printf("Fehler beim Ãffnen"); return EXIT_FAILURE; } printf("Welche Zeile wollen Sie lesen : "); scanf("%d",&line); linenr=getsline_number(line, f); if(linenr == NULL) { fprintf(stderr, "Fehler beim Lesen der" " %d-ten Zeile??\n",line); return EXIT_FAILURE; } printf("Zeile %d : %s\n", line, linenr); return EXIT_SUCCESS; } > /* read_line_n2n.c */ #include <stdio.h> #include <stdlib.h> #define BUF 255 char temp[BUF]; char puffer[BUF]; int i; /* Zeilenzähler */ /* Lesen von Zeile n1 bis Zeile n2 */ char *getsline_number(int n1,int n2, FILE *file) { for(i = 0; i < n1-1; i++) /* Bis zur n1-ten Zeile lesen */ if(fgets(temp, BUF, file) == NULL) return NULL; /* Zeile scheint nicht zu existieren. */ /* Jetzt beginnt das eigentliche Lesen. */ printf("\n\n"); for(i = n1; i <= n2; i++) { if(fgets(puffer,BUF,file) == NULL) /* Stream ist jetzt in der n-ten Zeile. */ return NULL; /* Zeile scheint nicht zu existieren. */ printf("Zeile %d : %s", i, puffer); } } int main(int argc, char *argv[]) { FILE *f; int line1, line2; char *linenr; if(argc < 2) { fprintf(stderr, "Verwendung : %s datei\n", *argv); return EXIT_FAILURE; } f = fopen(argv[1],"r"); if(f == NULL) { printf("Fehler bei fopen()...\n"); return EXIT_FAILURE; } printf("von Zeile wollen Sie lesen : "); scanf("%d", &line1); printf("bis Zeile wollen Sie lesen : "); scanf("%d", &line2); if(line2 < line1) { fprintf(stderr, "bis-Zeile kann nicht " "groesser sein als von-Zeile!\n"); return EXIT_FAILURE; } linenr=getsline_number(line1,line2, f); if(linenr == NULL) { fprintf(stderr, "Fehler beim Lesen " "der %d-ten Zeile??\n",i); return EXIT_FAILURE; } printf("\n"); return EXIT_SUCCESS; } # Wie kann ich alle Zeilen ausgeben, die eine bestimmte Stringfolge enthalten? > /* search_string.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define BUF 255 int main(int argc, char *argv[]) { FILE *f; char searchstring[BUF], puffer[BUF]; int counter = 1; if(argc < 2) { fprintf(stderr, "Verwendung : %s datei\n", *argv); return EXIT_FAILURE; } f = fopen(argv[1], "r"); if(f == NULL) { printf("Fehler bei fopen()... \n"); return EXIT_FAILURE; } printf("Wonach suchen Sie in %s : ", argv[1]); scanf("%s", searchstring); printf("\n"); while( fgets(puffer, BUF, f) != NULL ) { if(strstr(puffer,searchstring) != 0) printf("Zeile %d : %s",counter,puffer); counter++; } printf("\n"); return EXIT_SUCCESS; } Der Nachteil an diesem Beispiel ist, dass strstr() praktisch alle Stringfolgen ausgibt. Suchen Sie beispielsweise nach der Stringfolge »int«, dann gibt strstr() auch »wahr« aus, wenn die Folge »printf«, »fprintf«, »Lint«, »Mint«  lautet. Wenn dies so gewollt ist, dann ist es in Ordnung. Falls nicht, muss mit strtok() ein Worttrenner eingebaut werden. > /* search_word.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUF 255 /* Anpassen nach Bedarf... */ const char trennzeichen[] = ".;,:\"\' "; int main(int argc, char *argv[]) { FILE *f; char searchstring[BUF]; char puffer[BUF], puffer_bak[BUF]; int counter=1; char *wort; if(argc < 2) { fprintf(stderr, "Verwendung : %s datei\n",*argv); return EXIT_FAILURE; } f=fopen(argv[1],"r"); if(f == NULL) { printf("Fehler bei fopen()..."); return EXIT_FAILURE; } printf("Wonach suchen Sie in %s : ",argv[1]); scanf("%s", searchstring); printf("\n"); while(fgets(puffer, BUF, f) != NULL) { strcpy(puffer_bak, puffer); wort = strtok(puffer, trennzeichen); while(wort != NULL) { if(strcmp(wort,searchstring) == 0) printf("Zeile %d : %s",counter,puffer_bak); wort = strtok(NULL,trennzeichen); } counter++; } printf("\n"); return EXIT_SUCCESS; } # Suchen und Ersetzen in einer Textdatei (nur ganze Wörter, keine Teilstrings) > /* search_and_replace.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #define STRING_MAX 8192 int wort_begrenzer(char c) { return (c == ' ' || c == '\n' || c == '\t' || c == '\0' || c == '.' || c == ',' || c == ';' || c == '!' ||c == '?'); } /* Newline von fgets() entfernen */ void chomp(char *str) { size_t p=strlen(str); str[p-1] = '\0'; } int main(int argc, char *argv[]) { FILE *file, *copy; char alt_string[STRING_MAX+1],neu_string[STRING_MAX+1], such_wort[STRING_MAX+1],replace_wort[STRING_MAX+1], *zgr; char puffer[STRING_MAX+1]; int such_wortlen, i=0,w; size_t len=0; if(argc < 2) { fprintf(stderr, "Verwendung: %s datei\n", *argv); return EXIT_FAILURE; } file = fopen(argv[1],"r"); /* Datei zum Lesen öffnen */ copy = fopen(argv[1],"r+"); /* Datei zum Schreiben öffnen */ if(file == NULL || copy == NULL) { printf("Fehler bei fopen()...\n"); return EXIT_FAILURE; } alt_string[0]='\0'; /* kompletten String in alt_string legen ... */ /* Bitte ggf. selbst durch dynamische Speicherverwaltung * genügend Platz schaffen! */ while( (fgets(puffer,STRING_MAX+1,file)) != NULL ) { len += strlen(puffer)+1; if(len < STRING_MAX) strcat(alt_string, puffer); else { printf("Puffergroesse ueberschritten!\n"); break; } } neu_string[0]='\0'; printf("Welches Wort wollen Sie ersetzen : "); fgets(such_wort, STRING_MAX, stdin ); chomp(such_wort); such_wortlen = strlen(such_wort); /* Länge des Suchwortes */ for(w = 0; w < such_wortlen; w++) /* nach Wortbegrenzern duchlaufen ... */ if(wort_begrenzer(such_wort[w])) { printf("Keine Wortbegrenzer im Suchwort!!!\n"); return EXIT_FAILURE; } printf("Durch welches Wort wollen Sie ersetzen : "); fgets(replace_wort, STRING_MAX, stdin); chomp(replace_wort); i = 0; while(1){ if( (zgr=strstr(&alt_string[i], such_wort)) == NULL) { /* Kein Wort zu ersetzen */ strcat(neu_string, &alt_string[i]); break; } else { /*..ansonsten von Byte i bis zgr in neu_string*/ strncat(neu_string, &alt_string[i], zgr-&alt_string[i]); /* jetzt überprüfen, ob wir ein Wort haben und * keinen Teilstring oder ob das Wort am Anfang steht */ if( (zgr-&alt_string[0]==0 || wort_begrenzer( *(zgr-1))) && wort_begrenzer( *(zgr+such_wortlen))) { strcat(neu_string, replace_wort); /* Nach ersetztem Wort den Zeiger setzen ... */ i += zgr + such_wortlen-&alt_string[i]; } else { strncat(neu_string, zgr, 1); i += zgr + 1-&alt_string[i]; } } } /* Ende while(1) */ /* Für Testausgabe ... */ /* printf("Neuer String : %s\n",neu_string); */ strcpy(alt_string, neu_string); /* Achtung jetzt wirds ernst, * für Testausgabe in Kommentar setzen. */ fputs(alt_string, copy); neu_string[0] = '\0'; return EXIT_SUCCESS; } # 16.17 Blockweise lesen und schreiben – »fread()« und »fwrite()« Date: 2017-01-16 Categories: Tags: ## 16.17 Blockweise lesen und schreiben – »fread()« und »fwrite()« Diese beiden Funktionen lassen sich nicht so recht in ein Thema der Datei-E/A einordnen – weder in den höheren Standardfunktionen (High Level) noch in den niedrigeren Funktionen (Low-Level). Mit fread() und fwrite() wird eine Datei nicht als strukturierte Textdatei und auch nicht als unformatierter Bytestrom betrachtet. Die Dateien werden im Binärmodus bearbeitet und haben eine feste Satzstruktur. Das heiÃt, die Funktionen fread() und fwrite() tun nichts anderes, als ganze Blöcke binär zu lesen und zu schreiben. Das Gute an diesen beiden Funktionen ist ihre einfache Anwendung. Der Nachteil ist aber, dass die Daten der Datei, die fwrite() schreibt, nicht portabel, sondern plattformabhängig sind. Wollen Sie zum Beispiel mit diesen Funktionen Hauptspeicherinhalte direkt in eine Datei schreiben, könnten aufgrund eines anderen Alignments Probleme auftreten. Dies kommt daher, weil ein Member-Alignment in anderen Strukturen eine andere Byte-Reihenfolge bei Ganzzahlen oder eine unterschiedliche interne Darstellung von FlieÃkommazahlen haben könnte. Dieses Problem kann schon bei unterschiedlichen Compilern auftreten! Ist es also wichtig, dass die Daten auch auf anderen Systemen gelesen werden können, haben Sie folgende zwei Möglichkeiten: * Die bessere Lösung wäre es, eine einfache ASCII-Textdatei zu verwenden, die mit fprintf() geschrieben und mit fscanf() gelesen wird. Ãhnlich wird übrigens auch bei Netzwerkprotokollen vorgegangen. Zwar sind Textdateien meistens gröÃer, und die Ein-/Ausgabe läuft ein wenig langsamer ab, aber der Vorteil, die einfachere Handhabung der Daten, macht diese Nachteile wieder wett. * Sie überprüfen, ob es sich dabei um eine Big-Endian- oder Little-Endian-Maschine handelt. Diese Funktionen ergänzen das Sortiment der Lese- und Schreibfunktionen hervorragend. Denn mit fgets() und fputs() lassen sich, wegen der besonderen Bedeutung der Zeichen '\0' und '\n' in ihnen, schlecht ganze Blöcke von Daten lesen bzw. schreiben. Ebenso ist es nicht sinnvoll, Daten Zeichen für Zeichen zu verarbeiten, wie dies bei den Funktionen fputc() und fgetc() geschieht. AuÃerdem ist es naheliegend, dass sich diese beiden Funktionen hervorragend zum Lesen und Schreiben von Strukturen eignen. ### 16.17.1 Blockweise lesen – »fread()« Die Syntax der Funktion lautet wie folgt: > size_t fread(void *puffer, size_t blockgroesse, size_t blockzahl, FILE *datei); fread() liest blockzahl-Speicherobjekte, von denen jedes die GröÃe von blockgroesse Bytes hat, aus dem Stream datei, der zuvor geöffnet wurde, in die Adresse von puffer. Für puffer muss dementsprechend viel Platz zur Verfügung stehen. Der Rückgabewert ist die Anzahl der gelesenen Speicherobjekte. Ist die Anzahl kleiner als blockzahl, wurde entweder das Dateiende erreicht, oder es trat ein Fehler auf. Abbildung 16.6 Blockweises Lesen mit »fread()« Nehmen wir an, wir haben eine Datei namens wert.dat, deren Inhalte aus Integerwerten bestehen. Werden z. B. die ersten zehn Werte benötigt, sieht der Quellcode folgendermaÃen aus: > /* fread.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int puffer[10]; FILE *quelle; int i; quelle = fopen("wert.dat", "r+b"); if(quelle != NULL) fread(&puffer, sizeof(int), 10, quelle); for(i = 0; i < 10; i++) printf("Wert %d = %d\n", i, puffer[i]); return EXIT_SUCCESS; } Folgende Zeile soll wie oben interpretiert werden: > fread(&puffer, sizeof(int), 10, quelle); fread() liest 10 Datenobjekte mit der GröÃe von je sizeof(int) Bytes aus dem Stream quelle in die Adresse von puffer. Ein wenig undurchsichtig dürfte der Parameter void *puffer bei fread() und fwrite() erscheinen. Mit dem void-Zeiger haben Sie den Vorteil, dass diesem Parameter ein Zeiger beliebigen Datentyps übergeben werden kann. In Kapitel 12, »Zeiger (Pointer)«, haben wir dies bereits durchgenommen. ### 16.17.2 Blockweise schreiben – »fwrite()« Kommen wir jetzt zur Funktion fwrite(): > size_t fwrite(const void *puffer,size_t blockgroesse, size_t blockzahl, FILE *datei); Mit fwrite() werden blockzahl-Speicherobjekte, von denen jedes blockgroesse Bytes groà ist, von der Adresse puffer in den Ausgabe-Stream datei geschrieben. Der Rückgabewert ist auch hier die Anzahl der geschriebenen Speicherobjekte. Ist die Anzahl kleiner als blockzahl, dann ist ein Fehler aufgetreten. Abbildung 16.7 Blockweise schreiben mit »fwrite()« Wieder ein Beispiel: > struct { char name[20]; char vornam[20]; char wohnort[30]; int alter; int plz; char Strasse[30]; } adressen; FILE *quelle; strcpy(adressen.name, "Barack"); strcpy(adressen.vornam, "Obama"); strcpy(adressen.wohnort, "Washington D.C"); adressen.alter = 55; adressen.plz = 23223; ... if((quelle=fopen("adres.dat", "w+b")) == NULL) ... fwrite(&adressen, sizeof(struct adressen), 1, quelle); Hier wird mit fwrite() aus der Adresse adressen ein Speicherobjekt mit der GröÃe von sizeof(struct adressen) Bytes in den Stream quelle geschrieben. Als Beispiel zu den Funktionen fread() und fwrite() folgt ein kleines Adressenverwaltungsprogramm ohne irgendwelche besonderen Funktionen, um nicht vom eigentlichen Thema abzulenken: > /* fread_fwrite.c */ #include <stdio.h> #include <stdlib.h> struct { char vorname[20]; char nachname[30]; char strasse[30]; char hausnummer[5]; char plz[7]; char ort[30]; char sternzeichen[30]; char alter[3]; } adressen; void speichern(void) { FILE *save = fopen("adressen.dat","r+b"); if( NULL == save ) { save = fopen("adressen.dat","w+b"); if( NULL == save ) { fprintf(stderr,"Kann \"adressen.dat\" nicht öffnen!\n"); return; } } /* FILE-Zeiger save auf das Ende der Datei setzen */ fseek(save, 0, SEEK_END); /* Wir schreiben eine Adresse ans Ende von "adressen.dat". */ if(fwrite(&adressen, sizeof(adressen), 1, save) != 1) { fprintf(stderr, "Fehler bei fwrite...!!!\n"); return; } /* Wir geben unseren FILE-Zeiger wieder frei. */ fclose(save); } void ausgabe(void) { FILE *output = fopen("adressen.dat","r+b"); if( NULL == output ) { fprintf(stderr,"Kann \"adressen.dat\" nicht öffnen!\n"); return; } /* Wir lesen alle Adressen aus "adressen.dat". */ while(fread(&adressen, sizeof(adressen), 1, output) == 1) { printf("Vorname...........: %s",adressen.vorname); printf("Nachname..........: %s",adressen.nachname); printf("Strasse...........: %s",adressen.strasse); printf("Hausnummer........: %s",adressen.hausnummer); printf("Postleitzahl......: %s",adressen.plz); printf("Ort...............: %s",adressen.ort); printf("Sternzeichen......: %s",adressen.sternzeichen); printf("Alter.............: %s",adressen.alter); printf("\n\n"); } fclose(output); } void eingabe(void) { printf("Vorname...........:"); fgets(adressen.vorname, sizeof(adressen.vorname), stdin); printf("Nachname..........:"); fgets(adressen.nachname, sizeof(adressen.nachname),stdin); printf("Strasse...........:"); fgets(adressen.strasse, sizeof(adressen.strasse), stdin); printf("Hausnummer........:"); fgets(adressen.hausnummer,sizeof(adressen.hausnummer),stdin); printf("Postleitzahl......:"); fgets(adressen.plz, sizeof(adressen.plz), stdin); printf("Ort...............:"); fgets(adressen.ort, sizeof(adressen.ort), stdin); printf("Sternzeichen......:"); fgets(adressen.sternzeichen,sizeof(adressen.sternzeichen), stdin ); printf("Alter.............:"); fgets(adressen.alter, sizeof(adressen.alter), stdin); speichern(); } int main(void) { int wahl; do { printf("Was wollen Sie machen:\n\n"); printf("-1- Neuen Datensatz hinzufuegen\n"); printf("-2- Alle Datensaetze ausgeben\n"); printf("-3- Programm beenden\n\n"); printf("Ihre Auswahl : "); do { scanf("%d",&wahl); } while(getchar() != '\n'); switch(wahl) { case 1 : eingabe(); break; case 2 : ausgabe(); break; case 3 : printf("...Programm wird beendet\n"); break; default: printf(">>%d<< ???\n",wahl); } } while(wahl != 3); return; } Zuerst wurde eine Struktur mit dem Namen adressen deklariert. In der Funktion speichern() wird, falls vorhanden, die Datei adressen.dat geöffnet. Ansonsten wird diese Datei erstellt: > FILE *save = fopen("adressen.dat","r+b"); if( NULL == save ) { save = fopen("adressen.dat","w+b"); if( NULL == save ) { Gleich darauf wird der Stream save an das Ende der Datei adressen.dat positioniert: > fseek(save, 0, SEEK_END); Jetzt kann der Adressensatz in die Datei geschrieben werden: > if(fwrite(&adressen, sizeof(adressen), 1, save) != 1) Nochmals eine Erklärung von fwrite(): * &adressen – Anfangsadresse der Struktur adressen, welche am Programmbeginn deklariert und in der Funktion eingabe() mit Werten initialisiert wurde * sizeof(struct adressen) – GröÃe (BlockgröÃe) in Byte, die vorgibt, wie viel auf einmal in den Stream save geschrieben werden soll * 1 – Anzahl der Blöcke von der GröÃe sizeof(adressen), die in den Stream save geschrieben werden * save – Stream, der zuvor geöffnet wurde, und in den geschrieben wird Diese Anweisung wurde in eine if-Bedingung gepackt, die eine Fehlerausgabe vornimmt, falls weniger als ein Block geschrieben wird. Mit der Funktion ausgabe() wird diese Datei jetzt über fread() blockweise ausgelesen und der Inhalt auf dem Bildschirm ausgegeben: > while(fread(&adressen, sizeof(adressen), 1, output) == 1) Es wird so lange ausgelesen, bis kein ganzer Block der GröÃe sizeof(adressen) mehr vorhanden ist. Auch hierzu bekommen Sie eine genauere Erläuterung von fread(): * &adressen – Hierhin wird der Block der GröÃe sizeof(adressen), auf die der FILE-Zeiger output zeigt, »geschoben«. Natürlich handelt es sich auch hier um die Struktur adressen, die durch den Aufruf von fread() mit dementsprechenden Werten initialisiert wird. * sizeof(adressen) – GröÃe des Blocks, der gelesen werden soll * 1 – Anzahl der Blöcke, die gelesen werden * output – Stream, aus dem gelesen wird ### 16.17.3 Big Endian und Little Endian Ich habe bereits erwähnt, dass die Funktionen fread() und fwrite() nicht portabel und somit plattformabhängig sind. Sollten Sie also Programme schreiben wollen, die auf den verschiedensten Systemen laufen sollen, bleibt Ihnen nur die Wahl, diese Funktionen nicht zu verwenden, oder Sie finden heraus, auf welchem System genau sie laufen sollen. Unterschieden werden die Systeme dabei nach Little Endian und Big Endian. Little Endian und Big Endian sind zwei Methoden, wie die einzelnen Bytes im Speicher angeordnet sind. Little Endian und Big Endian unterscheiden sich durch die Anordnung des most significant byte und des least significant byte. Bei einer Word-GröÃe der CPU von vier Bytes wird das rechte Ende als least significant byte und das linke Ende als most significant byte bezeichnet. Das least significant byte stellt dabei die niedrigeren Werte und das most significant byte die gröÃeren Werte in einem Word dar. Als Beispiel dient jetzt folgende Hex-Zahl: > 22CCDDEE Auf den unterschiedlichen Systemen wird diese Hex-Zahl im Speicher folgendermaÃen abgelegt: Adresse | 0x12345 | 0x12346 | 0x12347 | 0x12348 | | --- | --- | --- | --- | --- | | | | | | | | | | | Um jetzt herauszufinden, auf was für einem System das Programm ausgeführt wird, müssen Sie diese Hex-Zahl in einen Speicher schreiben, der Platz für eine Wortbreite bietet und das erste Byte mithilfe von Bit-Operationen überprüfen. Hier sehen Sie das Listing dazu: > /* endian.c */ #include <stdio.h> #include <stdlib.h> typedef unsigned int WORD; typedef unsigned char BYTE; int main(void) { /* Word in den Speicher schreiben */ WORD Word = 0x22CCDDEE; /* Zeiger auf ein Byte */ BYTE *Byte; /* Word-Zeiger auf Byte-Zeiger casten */ Byte = (BYTE *) &Word; /* Speicherinhalt nach Adressen von links nach rechts * ausgeben. * byte[0]byte[1]byte[2]byte[3] * 22 CC DD EE Speicherinhalt bei Little Endian * EE DD CC 22 Speicherinhalt bei Big Endian */ /* Ist Byte[0] == 11 */ if(Byte[0] == ((Word >> 0) & 0xFF)) printf("Little Endian Architecture\n"); /* oder ist Byte[0] == CC */ if(Byte[0] == ((Word >> 24) & 0xFF)) printf("Big Endian Architecture\n"); return EXIT_SUCCESS; } Mit > if(Byte[0] == ((Word >> 0) & 0xFF)) werden die ersten acht Bits (ein Byte) mithilfe einer Maske (FF == 256 == 1 Byte) gezielt getestet. Werden bei dem Ausdruck ((Word >> 0) & 0xFF)) praktisch keine Bits auf 0 gesetzt und stimmt danach der ausgewertete Ausdruck mit Byte[0] überein, haben Sie ein Little-Endian-System. Bei der zweiten Bedingung ist es dasselbe, nur wird dabei das vierte Byte (d. h. das 24. bis 32. Bit) verwendet. Zu den Little-Endian-Systemen gehören z. B.: * Intel-CPUs * DEC Alpha * VAX Big-Endian-Systeme sind zum Beispiel: * Motorola MC68000 (Amiga, Atari) * SPARC CPUs (SUN) * IBM PowerPC Einen faden Nachgeschmack hat diese Methode allerdings dann doch. Jetzt wissen Sie zwar, ob es sich um ein Little- oder Big-Endian-System handelt, aber nun müssen Sie sich dennoch selbst darum kümmern, dass die einzelnen Bytes richtig gelesen und geschrieben werden. Damit ist gemeint, dass Sie die Bits selbst verschieben müssen. Aber dies ist ein Thema, das den Rahmen dieses Buchs sprengen würde. # 16.18 Datei (Stream) erneut öffnen – »freopen()« ## 16.18 Datei (Stream) erneut öffnen – »freopen()« Die Syntax von freopen() lautet: > #include <stdio.h> FILE *freopen( const char * restrict pfad, const char * restrict modus, FILE * restrict datei ); Mit freopen() wird zuerst versucht, den Stream datei zu schlieÃen. Fehler beim SchlieÃen werden dabei ignoriert. Danach wird dem FILE-Zeiger die Datei zugeordnet, die in pfad angegeben wurde. Als modus können dieselben Modi verwendet werden wie bei der Funktion fopen(). Um es deutlicher auszudrücken: Sie erzeugen mit freopen() keinen neuen Stream, sondern verwenden einen vorhandenen Stream, der mit dem dritten Argument angegeben wird. Die Funktion wird für die Umlenkung eines Streams verwendet. Als Rückgabewert erhalten Sie bei Erfolg einen Zeiger auf den mit der Datei verbundenen Stream oder im Fehlerfall den Nullzeiger. Hierzu ein Beispiel: > /* freopen1.c */ #include <stdio.h> #include <stdlib.h> #define MAX 80 int main(void) { FILE *quelle; char datei1[20], datei2[20]; char puffer[MAX]; printf("Welche Datei wollen Sie als erste lesen : "); scanf("%19s",datei1); printf("Welche Datei wollen Sie anschlieÃend lesen : "); scanf("%19s",datei2); quelle=fopen(datei1,"r"); if( NULL == quelle ) { fprintf(stderr, "Fehler beim Oeffnen von %s\n", datei1); return EXIT_FAILURE; } while(fgets(puffer,MAX,quelle) != NULL) fputs(puffer,stdout); printf("\n"); freopen(datei2,"r",quelle); while(fgets(puffer,MAX,quelle) != NULL) fputs(puffer,stdout); return EXIT_SUCCESS; } Mit der Zeile > freopen(datei2,"r",quelle); wurde ein SchlieÃen der Datei mit fclose() und ein Ãffnen der Datei datei2 gespart. Da über freopen() die Datei mit dem FILE-Zeiger (datei1) automatisch geschlossen wurde, wird dem FILE-Zeiger quelle gleich die Datei mit dem Pfad datei2 übergeben. So wird freopen() aber nicht unbedingt angewandt. Da freopen() nicht überprüft, ob der Stream ordnungsgemäà geschlossen wurde, rate ich auch davon ab. Ein Fehler wird schlicht ignoriert. freopen() wird hauptsächlich dazu benutzt, die Standard-Streams stdin, stdout und stderr zu verbinden – in einfachen Worten: die Streams der Ein-/Ausgabe umzuleiten. Hierzu sehen Sie ein einfaches Beispiel: > /* freopen2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { printf("Wir schreiben eine Datei \"log.txt\"\n"); freopen("log.txt","a+",stdout); printf("Dieser Text steht in der Datei \"log.txt\"\n"); return EXIT_SUCCESS; } Hier wird z. B. die Standardausgabe in die Datei log.txt umgeleitet. Das erste printf() wird noch auf dem Bildschirm ausgegeben. Das zweite wird dagegen in die Datei log.txt umgeleitet, die sich hier im selben Verzeichnis wie das Programm befinden sollte. # 16.19 Datei löschen oder umbenennen – »remove()« und »rename()« Date: 2019-01-16 Categories: Tags: ## 16.19 Datei löschen oder umbenennen – »remove()« und »rename()« Manchmal ist es erforderlich, eine Datei zu löschen bzw. diese umzubenennen. ### 16.19.1 remove() Zum Löschen einer Datei können Sie die Funktion remove() verwenden. Die Syntax lautet: > #include <stdio.h> int remove(const char *pfadname); Bei Erfolg gibt diese Funktion 0 und bei Misserfolg –1 zurück. Voraussetzungen für ein erfolgreiches Löschen sind auÃerdem der richtige Pfad und auch entsprechende Zugriffsrechte auf die Datei. Hier sehen Sie ein kurzes Beispiel zu remove(): > /* a_remover.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char pfad[100]; printf("Welche Datei wollen Sie löschen?\n"); printf("Bitte wenn nötig gültigen Pfad angeben.\n"); printf("Eingabe :> "); scanf("%99s",pfad); if((remove(pfad)) < 0) { fprintf(stderr, "Fehler beim Löschen von %s", pfad); return EXIT_FAILURE; } return EXIT_SUCCESS; } Wollen Sie sichergehen, dass eine Datei nicht mehr wiederhergestellt werden kann, empfiehlt es sich, den Inhalt der Datei zuerst zu »zerstören«, ehe Sie mit remove() die Datei löschen. Der einfachste Weg ist es, den ganzen Inhalt mit irgendwelchen Zeichen zu beschreiben. Im folgenden Beispiel wurde dies mit fwrite() und dem Stringende-Zeichen '\0' durchgeführt: > /* shreeder.c */ #include <stdio.h> #include <stdlib.h> void my_remove(char *rm) { unsigned long size; FILE *rem=fopen(rm, "w+b"); if(rem != NULL) { fseek(rem, 0L, SEEK_END); /* Stream an das Dateiende */ size=ftell(rem); /* GröÃe in Bytes ermitteln */ /* kompletten Inhalt mit \0 überschreiben */ fwrite((char *)'\0', 1, size, rem); /* damit die Datei gelöscht werden kann, schliessen */ fclose(rem); remove(rm); /* Jetzt weg damit */ } } int main(void) { char datei[] = "test.txt"; my_remove(datei); return EXIT_SUCCESS; } Jetzt ist es zwar einigen Experten noch möglich, die Datei wiederherzustellen, doch am Inhalt der Datei dürften sich auch diese die Zähne ausbeiÃen. ### 16.19.2 rename() Mit der Funktion rename() kann eine Datei umbenannt werden. Die Syntax dafür lautet: > #include <stdio.h> int rename(const char *altname, const char *neuname); Wenn alles richtig verlief, gibt die Funktion 0, ansonsten bei einem Fehler –1 zurück. Ein kurzes Listing zeigt, wie rename() angewendet wird: > /* a_renamer.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char alt[20],neu[20]; printf("Welche Datei wollen Sie umbenennen : "); scanf("%19s",alt); printf("Wie soll die Datei heissen: "); scanf("%19s",neu); if( (rename(alt,neu)) < 0) { fprintf(stderr, "Fehler beim Umbenennen von %s", alt); return EXIT_FAILURE; } return EXIT_SUCCESS; } Sollte eine Datei umbenannt werden und einen Namen erhalten, der bereits vorhanden ist, ist das Verhalten systemabhängig. Die Funktionen rename() und remove() funktionieren unter UNIX/Linux-Systemen aber nur, wenn Sie ausreichende Zugriffsrechte für diese Datei besitzen. Unter Windows/MS-DOS ist dies teilweise noch zweitrangig. # 16.20 Pufferung einstellen – »setbuf()« und »setvbuf()« Date: 2020-01-16 Categories: Tags: ## 16.20 Pufferung einstellen – »setbuf()« und »setvbuf()« Eine kurze Erklärung zur Pufferung: Die Standardeinstellung ist bei ANSI-C-Compilern die Vollpufferung. Dies ist auch sinnvoller und schneller als keine Pufferung, da weniger Lese- und Schreiboperationen etwa auf der Festplatte oder dem Arbeitsspeicher stattfinden. Die PuffergröÃe ist abhängig vom Compiler, liegt aber meistens bei 512 und 4096 Bytes. Die GröÃe ist in der Headerdatei <stdio.h> mit der Konstante BUFSIZ angegeben. Bei einer Pufferung, die zeichenweise eingestellt ist, würde ein Kopiervorgang zum Beispiel so ablaufen: > -> Lese aus Datei ein Zeichen <- Schreibe in eine Datei ein Zeichen -> Lese aus Datei ein Zeichen <- Schreibe in eine Datei ein Zeichen -> Lese aus Datei ein Zeichen <- Schreibe in eine Datei ein Zeichen .... usw. Zeichen für Zeichen Bei einer Datei mit 100 Bytes wären das 100 Zugriffe zum Lesen im Wechsel mit 100 Zugriffen zum Schreiben. Bei Vollpufferung läuft dies so: Es wird so lange gelesen, bis der Puffer voll ist (BUFSIZE), und dann wird geschrieben. Im obigen Beispiel würde bei Vollpufferung einmal gelesen und einmal geschrieben. Um hier selbst in die Pufferung eingreifen zu können, stehen Ihnen die Funktionen setbuf() oder setvbuf() zur Verfügung. ### 16.20.1 Die Funktion »setbuf()« Mit der Funktion setbuf() wird einer Datei ein Dateipuffer zugeordnet. Die Syntax lautet: > #include <stdio.h> void setbuf(FILE * restrict datei, char * restrict puffer); Der geöffnete Stream datei erhält durch setbuf() den Puffer puffer. Die GröÃe des Puffers wird durch den Wert von BUFSIZ vorgegeben. Die symbolische Konstante BUFSIZ befindet sich in der Headerdatei <stdio.h>. Wie groà BUFSIZ auf Ihrem System ist, ermitteln Sie mit folgendem Listing: > /* bufsize.c */ #include <stdio.h> #include <stdlib.h> int main(void) { printf("Die max. Groesse des Puffers: %d\n",BUFSIZ); return EXIT_SUCCESS; } Der Wert für BUFSIZ dürfte in der Regel 256 KB, 512 KB oder auch 4096 KB betragen. Dies ist abhängig vom System und vom Compiler. Geben Sie hingegen für puffer den NULL-Zeiger an, erfolgt die Datenübertragung ungepuffert. Das würde eine Ãbertragung Zeichen für Zeichen bedeuten und natürlich erheblich mehr Zeit beanspruchen, da jedes einzelne Zeichen gelesen und anschlieÃend wieder geschrieben wird. Sie müssen die Funktion setbuf() unmittelbar nach dem Ãffnen einer Datei aufrufen – noch vor einer Lese- oder Schreiboperation. Zur Demonstration folgt ein Listing, das gepuffertes und ungepuffertes Kopieren von Daten vergleicht. AuÃerdem werden dabei die Funktionen getc() und putc() zum Lesen und Schreiben verwendet, die zwar zeichenweise arbeiten, aber dennoch vom Puffer abhängig sind. Hier das Listing: > /* test_setbuffer.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define DATEIGROESSE 10000000L #define DATEI1 "test.1" #define DATEI2 "test.2" void copy1(char *quelle, char *ziel) { FILE *q,*z; int c; time_t t1 = time(NULL); printf("Kopiere zeichenweise mit getc() und putc()\n"); q=fopen(quelle, "rb"); if( q != NULL) { z = fopen(ziel, "wb"); if(NULL == z) { fprintf(stderr,"Fehler beim Ãffnen (%s)\n",ziel); exit(EXIT_FAILURE); } } else { fprintf(stderr, "Fehler beim Ãffnen von %s\n", quelle); exit(EXIT_FAILURE); } while((c=getc(q)) != EOF) putc(c,z); fclose(q); fclose(z); printf("Zeit = %d sec.\n",time(NULL)-t1); } void copy2(char *quelle, char *ziel) { FILE *q,*z; static char puffer1[BUFSIZ]; static char puffer2[BUFSIZ]; int c; time_t t1 = time(NULL); printf("Gepuffertes Kopieren mit setbuf(stream,BUFSIZE)\n"); q=fopen(quelle,"rb"); if(q != NULL) { z = fopen(ziel, "wb"); if(NULL == z) { fprintf(stderr,"Fehler beim Ãffnen (%s)\n",ziel); exit(EXIT_FAILURE); } } else { fprintf(stderr, "Fehler beim Ãffnen von %s\n", quelle); exit(EXIT_FAILURE); } setbuf(q,puffer1); setbuf(z,puffer2); while((c=getc(q)) != EOF) putc(c,z); fclose(q); fclose(z); printf("Zeit = %d sec.\n",time(NULL)-t1); } void copy3(char *quelle, char *ziel) { FILE *q,*z; int c; time_t t1 = time(NULL); printf("Ungepuffertes Kopieren mit setbuf(stream, NULL)\n"); q = fopen(quelle, "rb"); if(q != NULL) { z = fopen(ziel, "wb"); if(NULL == z) { fprintf(stderr, "Fehler beim Ãffnen (%s)\n", ziel); exit(EXIT_FAILURE); } } else { fprintf(stderr, "Fehler beim Ãffnen von %s\n", quelle); exit(EXIT_FAILURE); } setbuf(q,NULL); setbuf(z,NULL); while((c=getc(q)) != EOF) putc(c,z); fclose(q); fclose(z); printf("Zeit = %d sec.\n",time(NULL)-t1); } void erzeuge_datei(void) { FILE *create = fopen(DATEI1, "wb"); if(NULL == create) { fprintf(stderr, "Konnte keine Datei erzeugen\n"); exit(EXIT_FAILURE); } fseek(create,DATEIGROESSE-1,SEEK_SET); putc('x',create); fclose(create); } int main(void) { printf("Datei %s wird erzeugt\n", DATEI1); erzeuge_datei(); copy1(DATEI1,DATEI2); copy2(DATEI1,DATEI2); copy3(DATEI1,DATEI2); remove(DATEI1); remove(DATEI2); return EXIT_SUCCESS; } Abbildung 16.8 Zeitvergleiche mit gepufferter und ungepufferter Einstellung Zuerst wird eine Datei von zehn Megabyte GröÃe mit der Funktion erzeuge_datei() angelegt. AnschlieÃend wird die erzeugte Datei test.1 in die Datei test.2 kopiert, ohne die Funktion setbuf() zu verwenden (Funktion copy1()). Als Nächstes wird die Funktion copy2() verwendet, bei der zum ersten Mal setbuf() eingesetzt wird. Als PufferungsgröÃe wird hierbei die Konstante BUFSIZ verwendet. Der Zeitverbrauch ist wieder derselbe wie zuvor ohne setbuf(). Also können Sie sich setbuf() mit der GröÃe von BUFSIZ ersparen, da dies die Standardeinstellung für die Funktionen getc() und putc() zu sein scheint. Als Letztes wurde die Funktion copy3() ausgeführt, bei der der Puffer auf NULL gesetzt wird. Somit wird ungepuffert kopiert. Das dauert natürlich eine Weile, da nach jedem Lesezugriff pro Byte gleich wieder ein Schreibzugriff erfolgt. Am Ende werden diese beiden Dateien mittels remove() wieder gelöscht, damit nicht unnötig Datenmüll auf der Platte übrig bleibt. ### 16.20.2 Die Funktion »setvbuf()« Zur Puffereinstellung kann aber auch die Funktion setvbuf() eingesetzt werden, die ähnlich wie setbuf() funktioniert. Hierzu lautet die Syntax: > #include <stdio.h> int setvbuf(FILE * restrict datei,char * restrict puffer,int modus, size_t puffergroesse); Wenn alles in Ordnung ging, liefert diese Funktion 0 zurück, andernfalls einen Wert ungleich 0. Die ersten beiden Parameter (FILE *datei,char *puffer) haben dieselbe Bedeutung wie schon bei der Funktion setbuf(). Zusätzlich stehen hier für den Parameter modus drei symbolische Konstanten zur Verfügung (siehe Tabelle 16.8). Puffertyp (Modus) | Bedeutung | | --- | --- | | | | | | | Falls hierbei für puffer NULL angegeben wird, alloziert die Funktion einen eigenen Speicher der GröÃe puffergrösse. Das hört sich komplexer an, als es ist. setbuf() ohne Pufferung verwenden Sie beispielsweise so: > setbuf(quelle,NULL); Hiermit wurde für den Stream quelle die Pufferung abgeschaltet (ungepuffert). Mit setvbuf() würde dies so erreicht: > setvbuf(quelle, NULL, _IONBF, BUFSIZ); Für den Stream quelle wurde der Puffer nun ebenso abgeschaltet. Wenn Sie die Pufferung auf z. B. 50 KB einstellen wollen, um Daten vom Stream quelle zum Stream ziel zu kopieren, so ergeben sich bei setvbuf() folgende Argumente: > setvbuf(quelle, NULL, _IOFBF, 50000L); setvbuf(ziel, NULL, _IOFBF, 50000L); Für eine zeilenweise Pufferung könnten Sie folgende Angaben machen: > setvbuf(quelle, NULL, _IOLBF, 80); setvbuf(ziel, NULL, _IOLBF, 80); So werden von quelle nach ziel mindestens 80 Zeichen kopiert, oder es wird bis zum nächsten Newline-Zeichen (\n) kopiert. Sie haben auf diese Weise mit der Funktion setvbuf() die Möglichkeit, einen Dateipuffer bestimmter Länge zuzuordnen. # 16.21 Temporäre Dateien erzeugen – »tmpfile()« und »tmpnam()« Date: 2021-01-16 Categories: Tags: ## 16.21 Temporäre Dateien erzeugen – »tmpfile()« und »tmpnam()« Wollen Sie Daten während der Laufzeit eines Programms temporär zwischenspeichern, müssen Sie nicht extra eine neue Datei erstellen. Dafür gibt es in C spezielle Funktionen. Mit der Funktion tmpnam() kann ein eindeutiger Name für eine temporäre Datei erzeugt werden. Die Syntax sieht wie folgt aus: > #include <stdio.h> char *tmpnam(char *zgr); Ein eindeutiger Name heiÃt, dass es sich um keinen Namen einer bereits existierenden Datei handelt. Insgesamt können mit TMP_MAX eindeutige Namen erzeugt werden. TMP_MAX ist in der Headerdatei <stdio.h> deklariert. Mit folgendem Programm können Sie herausfinden, wie viele temporäre Dateien auf Ihrem System erzeugt werden können: > /* tmpmax.c */ #include <stdio.h> #include <stdlib.h> int main(void) { printf("TMP_MAX = %u\n", TMP_MAX); return EXIT_SUCCESS; } Wird die Funktion tmpnam() hingegen so verwendet: > tmpnam(NULL); dann wird die Datei in einem static-Speicherbereich untergebracht, und die Adresse wird als Funktionswert wiedergegeben. Das bedeutet, dass nachfolgende Aufrufe der Funktion tmpnam() dieselbe Adresse einnehmen. Aus diesem Grund sollte zuerst umkopiert werden, um die alte Adresse nicht zu überschreiben. Sollte tmpnam() ohne den NULL-Zeiger aufgerufen werden, wird für zgr ein Adressbereich adressiert, der L_tmpnam Zeichen aufnehmen kann. L_tmpnam ist ebenso in der Headerdatei <stdio.h> deklariert. > /* Ltmpnam.c */ #include <stdio.h> #include <stdlib.h> int main(void) { printf("L_tmpnam= %d Zeichen\n", L_tmpnam); return EXIT_SUCCESS; } Kommen wir jetzt zur Funktion tmpfile(). Die Syntax lautet: > #include <stdio.h> FILE *tmpfile(void); Mit tmpfile() wird eine temporäre Datei im Binärmodus ("wb+") zum Lesen und Schreiben geöffnet. Die Datei mit einem eindeutigen Namen wird entweder beim SchlieÃen der Datei mit fclose() oder bei der ordnungsgemäÃen Beendigung des Programms automatisch gelöscht. Wenn das Programm abnormal beendet wurde, hängt es von der Implementierung ab, ob die temporäre Datei gelöscht wird oder nicht. Kann tmpfile() keine temporäre Datei öffnen, gibt diese Funktion einen Nullzeiger zurück. Wie auch schon bei tmpnam() können bei einem Programm laut C99-Standard mindestens TMP_MAX temporäre Dateien erzeugt werden. Jetzt ist es Zeit, diese Funktionen anhand eines Programmbeispiels zu demonstrieren: > /* a_tempfile.c */ #include <stdio.h> #include <stdlib.h> char string[] = { "Dies ist der String für die Testdatei\n" "Diese Zeile ist ein Lückenfüller !!!!\n" "Aber diese Zeile soll verändert werden\n" "Hier könnten noch viele Zeilen mehr stehen\n" }; void create_text_file(void) { FILE *out = fopen("test.txt", "w"); if(NULL == out) exit(EXIT_FAILURE); fputs(string, out); fclose(out); } int main(void) { FILE *in, *out; char line[80], *tmp; int line_nr = 1; /* Es wird eine Datei mit dem Inhalt string erzeugt. */ create_text_file(); /* Die Datei zum Ãndern wird zum Lesen geöffnet. */ in = fopen("test.txt", "r"); if(NULL == in) { fprintf(stderr, "Konnte Datei nicht erzeugen!\n"); return EXIT_FAILURE; } tmp = tmpnam(NULL); /* temporäre Datei erzeugen */ /* temporäre Datei zum Schreiben öffnen */ out = fopen(tmp, "w"); if(NULL == out) { fprintf(stderr, "Konnte Datei nicht öffnen!\n"); return EXIT_FAILURE;; } /* aus der Datei zeilenweise lesen und in * temporäre Datei schreiben */ while( NULL != fgets(line, 80, in)) { /* Es soll die dritte Zeile geändert werden. */ if(line_nr == 3) fputs("Ein veränderte Zeile!\n", out); else fputs(line, out); line_nr++; } fclose(in); fclose(out); remove("test.txt"); /* Original löschen */ rename(tmp, "test.txt"); /* temporäre Datei umbenennen */ return EXIT_SUCCESS; } Das Programm demonstriert den Einsatz temporärer Dateien recht eindrücklich. Es wird zuerst eine Textdatei test.txt erzeugt, die mit dem Inhalt von string beschrieben wird. Diese Datei wird jetzt zum Lesen geöffnet. AnschlieÃend wird mit tmpnam() eine temporäre Datei erzeugt. Durch das Argument NULL befindet sich diese Datei im static-Speicherbereich. Diese temporäre Datei öffnen Sie nun zum Schreiben. In der while()-Schleife wird Zeile für Zeile aus der Datei gelesen und in die temporäre Datei geschrieben. Ist die dritte Zeile erreicht, wird diese geändert. Danach geht es wieder Zeile für Zeile weiter, bis keine mehr vorhanden ist. Am Ende des Programms wird die Originaldatei gelöscht und die temporäre Datei in diese umbenannt. Das Listing stellt eine einfache Möglichkeit dar, eine Textdatei zu verändern. Dies kann z. B. recht sinnvoll sein, wenn Sie ein Textverarbeitungsprogramm entwickeln wollen und dabei eine Funktion einbauen, die alle 10 Minuten eine Sicherungskopie vom Originaltext erstellt. Die meisten guten Textverarbeitungsprogramme besitzen dieses Feature. Jetzt will ich Ihnen auch noch ein Listing mit der Funktion tmpfile() zeigen: > /* more_tempfile.c */ #include <stdio.h> #include <stdlib.h> int main(void) { FILE *tmp; int i; char tempdatei[L_tmpnam], zeile[1000]; printf("Demo-Funktion tmpnam ...\n"); for(i = 1; i <= 4; i++) { if(i%2==0) { printf("%20d. %s\n",i,tmpnam(NULL)); } else { tmpnam(tempdatei); printf("%20d. %s\n",i,tempdatei); } } printf("Demo Funktion tmpfile ...\n"); tmp=tmpfile(); if( NULL == tmp ) { fprintf(stderr,"Fehler bei tmpfile\n"); return EXIT_FAILURE; } /* Wir schreiben mit fputs in die temporäre * Datei, auf die tmp zeigt. */ fputs("Dieser Text wird in die temporäre" " Datei geschrieben\n", tmp); rewind(tmp); if(fgets(zeile,sizeof(zeile),tmp) == NULL) { fprintf(stderr, "Fehler bei fgets ...\n"); return EXIT_FAILURE; } printf("%s\n",zeile); return EXIT_SUCCESS; } Als Erstes wird in diesem Programm die Funktion tmpnam() demonstriert. Sie erzeugen zwei temporäre Dateien mit dem NULL-Zeiger und zwei ohne. AnschlieÃend erstellen Sie eine temporäre Datei und schreiben mit fputs() einen Text in diese. Danach lesen Sie aus der angefertigten temporären Datei, auf die der FILE-Zeiger tmp zeigt. Bei ordentlichem Beenden wird diese temporäre Datei auch wieder gelöscht. Zum Beweis, dass auch tatsächlich eine temporäre Datei erzeugt wurde, können Sie vor der Zeile > if(fgets(zeile,sizeof(zeile),tmp) == NULL) aus der temporären Datei lesen und das Programm mit exit() abbrechen, etwa so: > rewind(tmp); exit (1); if(fgets(zeile,sizeof(zeile),tmp) == NULL) Nun sollte sich in dem Verzeichnis, in dem Sie das Programm ausführen, eine Datei mit folgendem Textinhalt befinden: > Dieser Text wird in die temporäre Datei geschrieben ### 16.21.1 »mkstemp()« – sichere Alternative für Linux/UNIX (nicht ANSI C) Beim Ãbersetzen mit Linux/UNIX bekommen Sie bei tmpnam() eine Warnung angezeigt, diese Funktion nicht zu verwenden. Es wird Ihnen geraten, die Funktion mkstemp() einzusetzen. Diese Warnung wird deshalb ausgegeben, weil die Funktion tmpnam() einen eindeutigen Namen zurückgibt. In der Zeit zwischen der Erzeugung des Namens und dem Ãffnen der Datei könnte theoretisch eine Datei mit demselben Namen untergeschoben werden. > int mkstemp(char *template) ; Die Funktion mkstemp() erzeugt einen temporären Dateinamen und öffnet diese Datei mittels open() und dem Flag 0_EXCL gleich für Sie. Bei Erfolg gibt Ihnen diese Funktion einen File-Deskriptor zum Lesen und Schreiben auf diese temporäre Datei zurück. Dank des Flags O_EXCL ist sichergestellt, dass die so erzeugte temporäre Datei wirklich einzigartig ist. Die geöffnete Datei verwendet den Modus 0600 und ist standardmäÃig nur dem Eigentümer vorbehalten. Wenn andere User darauf zugreifen sollen (dürfen), müssen Sie das ändern (z. B. mit fchmod(), fchown()). mkstemp() liefert bei einem Fehler –1 zurück, wenn die Datei nicht erzeugt oder geöffnet werden kann. # 16.22 Fehlerbehandlung Date: 2022-01-16 Categories: Tags: ## 16.22 Fehlerbehandlung Wenn bei einem Systemaufruf ein Fehler auftritt, wird in der globalen Variable errno ein entsprechender Fehlerwert gesetzt. Mit den beiden Funktionen strerror() und perror() können Sie diese Systemfehlermeldung ausgeben lassen. Die Variable errno ist in der Headerdatei <errno.h> definiert. Dabei ist es nicht vorgeschrieben, ob errno eine globale Variable (vom Typ int) oder ein Makro ist, das einen modifizierbaren L-Wert vom Typ int hat. Ebenfalls in der Headerdatei <errno.h> sind die Konstanten (Fehlernummern) deklariert, die die Variable errno annehmen kann. Jede dieser Konstanten beginnt mit dem GroÃbuchstaben »E«. Diese Fehlernummern sind allerdings, abgesehen von drei Konstanten, system- und compiler-abhängig. Tabelle 16.9 enthält die drei Konstanten, die auf allen Systemen gleich und vorhanden sind. Weitere – allerdings wie schon erwähnt, system- und compiler-abhängige – Konstanten und ihre Bedeutungen sind in Tabelle 16.10 aufgeführt. Fehlercode | Bedeutung | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Dies dürften jetzt nicht alle gewesen sein bzw. auf anderen Systemen wieder zu viele. Sie sollten in der Headerdatei <errno.h> oder unter Linux auf der Manpage intro nachsehen. Die Variable errno wird beim Programmstart normalerweise auf 0 gesetzt, da es keine Fehlernummer mit dem Wert 0 gibt. Deshalb sollte errno jedes Mal, wenn eine Systemfunktion aufgerufen wird, wieder auf 0 gesetzt werden. ### 16.22.1 Fehlerausgabe mit »perror()« Im ersten Beispiel wird die Funktion perror() verwendet. Sehen sie sich zuerst die Syntax zu dieser Funktion an: > #include <stdio.h> void perror(const char *meldung); Wenn für meldung kein NULL-Zeiger angegeben wurde, wird der String meldung mit anschlieÃendem Doppelpunkt, gefolgt von einer zu errno gehörenden Fehlermeldung, ausgegeben (mit abschlieÃendem '\n'). Rufen Sie hingegen diese Funktion mit dem NULL-Zeiger auf, wird nur eine zu errno gehörende Fehlermeldung ausgegeben. Geschrieben wird diese Fehlermeldung auf die Standardfehlerausgabe (stderr). > /* perror.c */ #include <stdio.h> #include <stdlib.h> int main(void) { FILE *fp; fp = fopen("keinedatei.dat", "r"); if (NULL == fp) { perror("Kann nicht aus Datei lesen "); return EXIT_FAILURE; } return EXIT_SUCCESS; } Das Programm versucht, die Datei keinedatei.dat zu öffnen. Falls diese nicht existiert, wird eine entsprechende Fehlermeldung ausgegeben: > Kann nicht aus Datei lesen : No such file or directory Der Funktion perror() kann auch ein NULL-Zeiger übergeben werden: > perror(NULL); In diesem Fall würde nur das Folgende ausgegeben: > No such file or directory (ENOENT) ### 16.22.2 Fehlerausgabe mit »strerror()« Das Gleiche soll jetzt auch mit der Funktion strerror() realisiert werden. Die Syntax der Funktion lautet: > #include <string.h> char *strerror(int error_nr); Die Funktion liefert als Rückgabewert einen Zeiger auf einen String, der zur Systemfehlermeldung der Variablen errno passt. Der Parameter error_nr beinhaltet in der Regel die Fehlervariable von errno. > /* strerror.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> int main(void) { FILE *fp; fp = fopen("keinedatei.dat", "r"); if (NULL == fp) { fprintf(stderr, "%s\n", strerror(errno)); return EXIT_FAILURE; } return EXIT_SUCCESS; } Das Programm läuft genauso ab wie das Programm zuvor mit perror(). Mit dem nun folgenden Programm wird eine Datei mit dem Namen testfile erstellt. Zuerst soll die Datei zum Lesen geöffnet werden. AnschlieÃend wird mit > if(errno == ENOENT) überprüft, ob die Variable errno den Wert der Konstante ENOENT hat. Wenn ja, bedeutet dies, dass keine solche Datei existiert, und sie soll somit neu angelegt werden. Sollte es Probleme beim Anlegen dieser Datei geben, so wird dies mit dem nächsten perror()-Aufruf ausgegeben. > /* isfile.c */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #define ESUCCESS 0 int main(void) { FILE *fp; fp = fopen("testfile", "r"); if(errno == ENOENT) { /* errno wieder zurücksetzen */ errno = ESUCCESS; fp = fopen ("testfile", "w"); if(NULL == fp) { perror(NULL); return EXIT_FAILURE; } else printf("Datei \"testfile\" angelegt\n"); } else printf("Datei \"testfile\" exisitiert bereits\n"); fclose(fp); return EXIT_SUCCESS; } Die Funktion sprintf() ist in der Headerdatei <stdio.h> deklariert und nicht – wie häufig irrtümlicherweise angenommen – in <string.h>. Sie arbeitet genauso wie printf(), nur dass statt der Ausgabe auf dem Bildschirm formatiert in einen String geschrieben wird. So lassen sich verschiedene Formatelemente formatiert in einen String schreiben. Die Syntax dazu lautet: > int sprintf( char * restrict target_string, const char * restrict format, ...); int snprintf( char * restrict target_string, size_t n const char * restrict format, ...); Mit dem ersten Parameter target_string wird die Adresse des Zielstrings angegeben. Das zweite und die weiteren Argumente von sprintf() haben dieselbe Bedeutung wie schon bei der Funktion printf(). snprintf() funktioniert genauso wie sprintf(), nur werden hierbei nicht mehr als n Bytes in den Zielstring target_string geschrieben. Diese Funktion eignet sich besonders gut, wenn Sie Zahlen in einen String konvertieren wollen. Zudem schreibt sie am Ende das '\0'-Zeichen. Dazu ein kurzes Listing: > /* sprint.c */ #include <stdio.h> #include <stdlib.h> #define BUF 255 int main(void) { char string1[BUF]; char string2[BUF]; int anzahl = 10; char gegenstand[] = "Kartoffel"; float liter = 1.55f; char fluessigkeit[] = "Limo"; sprintf(string1, "%d kg %s\n",anzahl,gegenstand); sprintf(string2, "%.2f Liter %s\n",liter,fluessigkeit); printf("%s",string1); printf("%s",string2); return EXIT_SUCCESS; } Abbildung 16.9 Formatiert in einen String schreiben Die Funktion sscanf() stellt das Gegenstück zur Funktion sprintf() dar. Sie funktioniert genauso wie scanf(), nur liest sscanf() die Formatelemente nicht von der Tastatur ein, sondern von einem String. Die Syntax sieht so aus: > int sscanf( const char * restrict quell_string, const char * restrict format, ...); Im ersten Argument befindet sich der Quellstring, von dem anschlieÃend die Eingabezeichen mit den Formatbezeichnern des zweiten Arguments in die Variablenliste eingelesen werden. Am Dateiende oder bei einem Fehler gibt diese Funktion EOF zurück. Damit können Strings wieder in Zahlen umgewandelt werden. Hier sehen Sie ein Beispiel zu sscanf(): > /* sscanf.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char **argv) { int count = 1, check, temp, summe = 0; if (argc < 2) { fprintf(stderr, "Verwendung: %s Integer" " Integer [Integer_n]\n", *argv); return EXIT_FAILURE; } while(count < argc) { /* einzelne Argumente in Integerwerte konvertieren */ check = sscanf(argv[count], "%d", &temp); /* ungültiges Argument wird ignoriert */ if(check == EOF) count++; else { summe += temp; count++; } } printf("Summe aller Ganzzahlen der Argumente: %d\n", summe); return EXIT_SUCCESS; } Mit diesem Listing werden die Ganzzahlen, die dem Programm beim Aufruf über die Kommandozeile als Argumente mitgegeben wurden, als Summe berechnet. Die einzelnen Argumente werden mit der folgenden Zeile in Integerwerte konvertiert: > check = sscanf(argv[count], "%d", &temp); Zur Verdeutlichung folgt hier noch ein weiteres Beispiel mit den beiden Funktionen sprintf() und sscanf(): > /* form.c */ #include <stdio.h> #include <stdlib.h> #define NUMITEMS 4 char *namen[4] = { "Jürgen", "Fatma", "Gismo", "Jonathan" }; int main(void) { int schleife; char temp[4][80]; char name[20]; int alter; long lohn; /* Wir erstellen Namen, Alter und Gehalt. Alter und Gehalt * werden durch Zufallszahlen erzeugt. Mit sprintf schreiben * wir die Daten formatiert nach int temp. */ for (schleife = 0; schleife < NUMITEMS; ++schleife) sprintf(temp[schleife], "%s %d %ld" ,namen[schleife], rand()%20+18, rand()+27500L); /* Wir erstellen eine Kopfzeile. */ printf("%4s | %-20s | %5s | %9s\n", "#","Name","Alter","Gehalt"); printf(" ----------------------------------------" "----------\n"); /* Mit sscanf lesen wir die Daten formatiert aus temp aus, * und zwar dort, wo wir zuvor mit sprintf die Daten * formatiert geschrieben haben. */ for (schleife=0; schleife < NUMITEMS; ++schleife) { sscanf(temp[schleife],"%s %d %ld",(char*)&name,&alter,&lohn); printf("%4d | %-20s | %5d | %9ld\n", schleife+1,name,alter,lohn); } return EXIT_SUCCESS; } Abbildung 16.10 Formatiertes Schreiben in einen und Lesen aus einem String Dies ist ein recht praktisches Beispiel. Zuerst wird mit sprintf() formatiert in das zweidimensionale Array temp geschrieben und anschlieÃend mit sscanf() wieder formatiert ausgelesen. # 16.25 Ein fortgeschrittenes Thema ## 16.25 Ein fortgeschrittenes Thema Mittlerweile haben Sie ja in diesem Buch schon einiges gelernt. Aber irgendwie waren alle Themen doch sehr theoretisch. Ich habe vorwiegend gezeigt, wie Sie eine Funktion einsetzen können und was dabei beachtet werden muss. Daher soll in diesem Abschnitt einmal etwas Praktisches gemacht werden, womit einige C-typische Stärken aufgezeigt werden können. Es muss auch erwähnt werden, dass dieses Programmbeispiel Ihnen einiges an Wissen abverlangt. Im Listing werden aber keine Konstrukte von C verwendet, mit denen Sie bisher noch nichts zu tun hatten. Wenn Sie so wollen, stellt dieses Programm eine Art Zwischenprüfung Ihrer Kenntnisse in C dar. Es soll gezeigt werden – wie Sie einen Text einer Datei dynamisch in den Speicher lesen können; wie dies bei Textverarbeitungsprogrammen geschieht. Eine einfache Textdatei ist dabei so strukturiert wie in Abbildung 16.11 gezeigt. Abbildung 16.11 Einfache Strukturierung einer Textdatei Sicher ist dies nur eine einfache Strukturierung einer Textdatei. In der Regel fehlen hierbei z. B. noch die Absätze oder die Seitenzahlen. Aber für unseren Fall genügt dies. Folgende Funktionen benötigen Sie für diese Aufgabe: * eine Funktion, die eine Datei zum zeilenweisen Lesen öffnet * eine Funktion, die dynamischen Speicher für einen String anfordert * eine Funktion, die den dynamischen Speicher erweitert (eine Zeile hinzufügt) * eine Funktion, die die GröÃe einer Zeile anpasst und überflüssigen Speicher wieder freigibt * eine Funktion, die den dynamischen Speicher verringert * eine Funktion, die allozierten Speicher freigibt Hier folgt jetzt das vollständige Listing, das sehr ausführlich kommentiert ist: > /* dyn_text.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* symbolische Konstanten */ #define LINE 255 #define ALLOC_LINE 10 enum { SUCCESS, ERROR }; /* Funktionsprototypen */ int read_file(char ***, char *, int *); char **alloc_string_array(int, int); int zeilen_hinzu_fuegen(char ***, int, int, int); int string_anpassen(char **, int); int string_groesse_veraendern(char **, int, int); void free_string_array(char **, int); /* ***array == Ein Zeiger auf einen Zeiger einer Zeile mit * einem Zeiger auf die Länge der Zeile (*array[zeile][länge]) * *fname == Name der zu öffnenden Datei * *zeile_n == Zeiger auf Anzahl Zeilen * Rückgabewert: SUCCESS wenn kein Fehler, ansonsten ERROR */ int read_file(char ***array, char *fname, int *zeile_n) { char puffer[LINE] = {0}; /* Puffer zum zeilenweisen Einlesen */ char *newline = NULL; /* Zeiger für neue Zeile */ FILE *f; /* Datei, die geöffnet werden soll*/ int error = SUCCESS; /* Fehlerstatus */ int zeile = 0; /* aktuelle Zeile */ int absatz_n; *zeile_n = 0; /* erste Zeile mit 0 initialisieren */ /* Speicher anfordern für ALLOC_LINE Zeilen a LINE Zeichen */ *array = alloc_string_array(ALLOC_LINE, LINE); if(NULL != *array) { f = fopen(fname, "r"); /* Datei fname zum Lesen öffnen */ if(NULL != f) { *zeile_n = ALLOC_LINE; absatz_n = 0; /* solange kein Fehler auftritt, zeilenweise einlesen */ while(0 == error && NULL != fgets(puffer, LINE, f)) { newline = strchr(puffer, '\n'); if(NULL != newline) /* Newline-Zeichen gegen * Terminierungszeichen austauschen */ *newline = '\0'; strcat( (*array)[zeile], puffer); if(NULL != newline) { absatz_n = 1; zeile++; /* Haben wir noch Platz im Speicher * für weitere Zeilen? */ if(zeile >= *zeile_n) { /* Nein, dann anfügen. */ if(0 == zeilen_hinzu_fuegen( array, *zeile_n, ALLOC_LINE, LINE) ) error = ERROR; else /* Anzahl der Zeilen + 10 */ *zeile_n += ALLOC_LINE; } } /* kein Newline-Zeichen, dann Zeile länger als LINE * Zeichen, String der Länge anpassen -> Speicher * anfordern */ else { absatz_n++; if(0 == string_groesse_veraendern( *array, zeile, absatz_n * LINE)) error = ERROR; } }/*while*/ fclose(f); /* Wir sind am Ende vom Einlesen, oder ein Fehler trat auf. * Es muss/müssen allerdings noch die übrige(n) Zeile(n) in * den Speicher eingelesen werden. */ if(0 == error && *zeile_n > zeile) { if(0 == zeilen_hinzu_fuegen( array, *zeile_n, zeile-*zeile_n, 0)) error = ERROR; *zeile_n = zeile; } } else /* Datei fname konnte nicht geöffnet werden. */ error = ERROR; } else /* Es konnte kein Speicher alloziert werden. */ error = ERROR; if(error != 0) { /* im Fall eines Fehlers Speicher wieder freigeben * und Anzahl Zeilen auf 0 setzen */ free_string_array(*array, *zeile_n); *zeile_n = 0; } else string_anpassen(*array, *zeile_n); return error; } /* zeilen_n == Anzahl Zeilen, wie viele reserviert werden sollen * laenge == Speicherplatz für die Länge jeder Zeile, * die angefordert wird * Rückgabewert: Anfangsadresse des reservierten Speichers vom * String-Array (array[zeile][laenge]) */ char **alloc_string_array(int zeilen_n, int laenge) { char **array = NULL; int zeile; int ret = SUCCESS; if(zeilen_n > 0 && laenge > 0) { /* Speicher für zeilen_n Zeilen reservieren */ array = malloc(zeilen_n * sizeof(*array)); if(NULL != array) { for(zeile=0; zeile < zeilen_n; zeile++) { /* Für jede zeile_n Zeile laenge Bytes * Speicher reservieren */ array[zeile] = malloc( laenge * sizeof(*array[zeile]) ); if(NULL == array[zeile]) ret = ERROR; else /*in jeder Zeile erstes Zeichen mit \0 initialisieren*/ array[zeile][0] = '\0'; } if(ERROR == ret) { /* Bei Fehler Speicher freigeben */ free_string_array(array, zeilen_n); array = NULL; } } } return array; } /* ***array == Ein Zeiger auf einen Zeiger einer Zeile mit * einem Zeiger auf die Länge der Zeile ( *array[zeile][länge]) * alt_n_zeilen == Anzahl akt. Zeilen im Speicher * n_zeilen_hinzu == Anzahl Zeilen, für die neuer Speicherplatz * reserviert werden soll. Bei negativen Werten werden n Zeilen * entfernt * init_laenge == Speicherplatz für die Länge jeder Zeile, die * angefordert wird * Rückgabewert: 1 wenn Ok, ansonsten 0 */ int zeilen_hinzu_fuegen(char ***array_ptr, int alt_n_zeilen, int n_zeilen_hinzu, int init_laenge) { char **ptr; int ret = 1; int zeile; int anzahl_alte_zeilen = alt_n_zeilen; /* ein negativer Wert bedeutet Zeilen entfernen */ if(n_zeilen_hinzu < 0) { for(zeile=anzahl_alte_zeilen-1; zeile >= anzahl_alte_zeilen+n_zeilen_hinzu; zeile--) free( (*array_ptr)[zeile]); } /* Speicher für einzelne Zeilen reservieren */ ptr=realloc( *array_ptr, (anzahl_alte_zeilen+n_zeilen_hinzu)*sizeof(**array_ptr)); if(NULL != ptr) { *array_ptr = ptr; for(zeile=anzahl_alte_zeilen; ret && zeile < anzahl_alte_zeilen+n_zeilen_hinzu; zeile++) { /* Anzahl der Zeichen, die jede Zeile * aufnehmen kann, reservieren */ (*array_ptr)[zeile] = malloc(init_laenge); if( NULL != (*array_ptr)[zeile]) /* in jeder Zeile das erste Zeichen mit \ * 0 initialisieren */ (*array_ptr)[zeile][0] = '\0'; else ret = 0; } } else ret = 0; return ret; } /* **array_ptr == Ein Zeiger auf das String-Array * array[zeile][laenge] * zeile_n == Anzahl Zeilen, die angepasst werden * Rückgabewert bei Erfolg 0, ansonsten gröÃer als 0 */ int string_anpassen(char **array_ptr, int zeile_n) { int zeile; int anzahl_zeichen; int fehlschlag = 0; for(zeile = 0; zeile < zeile_n; zeile++) { /* Funktion strlen liest das Terminierungszeichen * '\0' nicht mit -> daher +1 */ anzahl_zeichen = strlen(array_ptr[zeile])+1; if(0 == string_groesse_veraendern( array_ptr, zeile, anzahl_zeichen)) fehlschlag++; } return fehlschlag; } /* **array_ptr == Ein Zeiger (Adresse) auf das String-Array * array[zeile][laenge] * zeile == Zeile, die verändert werden soll * neu_laenge == Anzahl Zeichen, die für die Zeile verändert * werden soll * Rückgabewert bei Erfolg SUCCESS, ansonsten bei Fehler ERROR */ int string_groesse_veraendern(char **array, int zeile, int neu_laenge) { char *ptr; int ret = SUCCESS; ptr = realloc(array[zeile], neu_laenge); if(ptr != NULL) array[zeile] = ptr; else ret = ERROR; return ret; } /* **array_ptr == Ein Zeiger (Adresse) auf das String-Array * array[zeile][laenge] * n_zeile == Anzahl Zeilen, die freigegeben werden sollen*/ void free_string_array(char **array, int n_zeilen) { int zeile; if(array != NULL) { for(zeile= 0; zeile < n_zeilen; zeile++) { if(array[zeile] != NULL) free(array[zeile]); } } free(array); } int main(void) { char **array = NULL; char datei[255]; int zeilen=0, i, auswahl, n, m; do { printf("Was wollen Sie tun?\n\n"); printf("-1- Datei komplett in den Speicher einlesen\n"); printf("-2- Inhalt der Datei im Speicher ausgeben\n"); printf("-3- Datei im Speicher von Zeile n bis m ausgeben\n"); printf("-4- Den Speicher wieder freigeben\n"); printf("-5- Ende\n\n"); printf("Ihre Wahl : < >\b\b"); scanf("%d",&auswahl);fflush(stdin); switch(auswahl) { case 1 : printf("Datei angeben( mit Pfadangabe ): "); scanf("%254s",datei); fflush(stdin); if( (read_file(&array, datei, &zeilen))==ERROR) printf("Fehler beim Lesen in Speicher!!!\n"); break; case 2 : if(zeilen == 0) printf("Keine Daten vorhanden!\n"); else for(i=0; i<=zeilen-1; i++) printf("%s\n",array[i]); break; case 3 : printf("Zeilenbeginn: "); scanf("%d",&n); fflush(stdin); if(n > 0 && n <= zeilen-1) { printf("bis zur Zeile: "); scanf("%d",&m); fflush(stdin); if(m >= n && m <= zeilen-1) { for(i=n; i<=m-1; i++) printf("%s\n",array[i]); } else printf("??>>%d<<??\n",m); } else printf("??>>%d<<??\n",n); break; case 4 : free_string_array(array, zeilen); zeilen=0; break; default: break; } } while(auswahl != 5); return EXIT_SUCCESS; } # 16.26 Low-Level-Datei-I/O-Funktionen (nicht ANSI C) ## 16.26 Low-Level-Datei-I/O-Funktionen (nicht ANSI C) Mit den Funktionen der höheren Ebene (High-Level) wurde auf die Daten mit einem hohen Abstraktionsniveau zugegriffen. Das bedeutet, die Daten eines Programms wurden formatiert ausgegeben oder eingelesen. Bei der niedrigeren Ebene (Low-Level) wird auf einem tieferen Niveau gearbeitet. Der Zugriff auf die Daten findet als eine Folge von unstrukturierten Bytes statt und bietet somit die Möglichkeit, Bytesequenzen vorgegebener Länge einzulesen oder auszugeben. Nicht nur die Namen der Funktionen der höheren und der niedrigeren Ebene sind ähnlich, auch ihre Abarbeitung ist es – nur mit einem, aber sehr prinzipiellen Unterschied, der etwas verwirrend ist. Während beim High-Level-Dateizugriff mit einem FILE-Zeiger (Stream) auf die Datei zugegriffen wird, geschieht dies auf der niedrigeren Ebene mit einem sogenannten File-Deskriptor. Dieser Deskriptor ist kein Zeiger wie bei der höheren Ebene, sondern ein normaler int-Wert, der beim Ãffnen einer Datei zurückgegeben wird. Die höheren Dateifunktionen bauen auf den Funktionen der niedrigeren Ebene auf. Die niedrigere Ebene ist also die Grundlage der höheren Funktionen in der Standard-Bibliothek. Doch allein die Funktionen der niedrigeren Ebene arbeiten ungepuffert. Wenn zum Beispiel Bibliotheksfunktionen wie printf() oder scanf() zum Aus- bzw. Eingeben benutzt werden, verwenden Sie eigentlich die Systemfunktionen write() und read(). Dies sind Funktionen (Systemfunktionen) im Low-Level-Bereich. Also ist es egal, ob fgets(), fputs(), gets(), puts(), putc(), getc() usw. eingesetzt werden, all diese Funktionen bauen auf Systemfunktionen auf. Natürlich ist anzumerken, dass diese Funktionen der niedrigeren Ebene systemabhängig sind und somit nicht dem ANSI-C-Standard entsprechen können. Das heiÃt konkret, dass es Probleme mit der Portabilität der Programme geben kann. ### 16.26.1 Datei öffnen – »open()« Ãffnen Sie eine Datei mit der Funktion open(), so wird der Datei ein Deskriptor – auch File-Deskriptor genannt – zugeordnet. Ein File-Deskriptor ist eine positive kleine Zahl, die vom Betriebssystem vergeben wird. Ãber diesen Deskriptor geben Sie an, ob gelesen oder geschrieben werden soll. Mit der Funktion open() kann zudem auch gleich eine Datei angelegt werden. Hier sehen Sie die Syntax mit den dazugehörenden Headerdateien, die mit eingebunden werden müssen, für Linux/UNIX: > #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> int open(const char *pfad, int modus); int open(const char *pfadname, int flags, mode_t zugriffsrechte); Die Syntax mit Headerdateien für Windows/MS-DOS sieht so aus: > #include <fcntl.h> #include <io.h> #include <sys\stat.h> int open(const char *pfad, int modus); int open(const char *pfadname, int flags, mode_t zugriffsrechte); Als Pfadangabe müssen Sie den absoluten oder relativen Pfad der Datei angeben, die geöffnet werden soll. Da der Prototyp (unter Linux/UNIX zumindest) in Wirklichkeit korrekt open(const char *, int, ...) lautet, kann je nach Situation das dritte Argument auch wegfallen. Beim Modus gibt es mehrere Varianten, aber diese sind systemabhängig. Einer der drei Modi, die in Tabelle 16.11 aufgeführt sind, muss immer angegeben werden. Dies sieht dann unter Linux/UNIX folgendermaÃen aus: > int fh; if((fh = open("/home/programmname", O_RDONLY)) != -1) oder unter Windows/MS-DOS: > if((fh = open("c:\\config.sys", O_RDONLY)) != -1) In den beiden Beispielen wird eine Datei nur zum Lesen geöffnet. Bei einem dieser drei genannten Modi können Sie mit dem bitweisen ODER-Zeichen (|) weitere Aktionen verknüpfen. Dies sieht dann so aus: > if((fh = open("c:\\test.sys", O_WRONLY|O_CREAT)) != -1) Hiermit wird eine Datei zum Schreiben geöffnet. Existiert diese Datei nicht, so wird sie erzeugt (O_CREAT). Existiert diese Datei, so wird der zusätzliche Modus O_CREATE ignoriert. Tabelle 16.12 zeigt die zusätzlichen Modi, die für Linux/UNIX und Windows/MS-DOS darüber hinaus zur Verfügung stehen. Beispielsweise wird mit > if((fh = open("/home/Name.txt", O_WRONLY | O_TRUNC)) != -1) erreicht, dass die Datei Name.txt zum Schreiben geöffnet wird. Der Inhalt dieser Datei wird gelöscht, und sie kann neu beschrieben werden. Tabelle 16.13 listet weitere Modi auf, die nur für Linux/UNIX zur Verfügung stehen. Für Windows/MS-DOS gibt es die Extra-Modi, die in Tabelle 16.14 aufgelistet sind. Jetzt folgen noch einige Modi, mit denen die Zugriffsrechte auf eine Datei erteilt werden können. Die Modi für Windows/MS-DOS sehen Sie in Tabelle 16.15. Mit folgender Zeile wird z. B. eine Datei erzeugt, die nur gelesen werden darf: > if((fh=open("new.xxx", O_CREAT , S_IREAD)) == -1) Wenn das Lesen und Schreiben erlaubt sein sollen, sieht dies so aus: > if((fh=open("new.xxx",O_CREAT, S_IREAD|S_IWRITE)) == -1) Diese drei Zugriffsrechte für Windows/MS-DOS stehen in der Headerdatei <sys\stat.h>. Für Linux/UNIX können Sie folgende Zugriffsrechte erteilen, die sich in der Headerdatei <sys/stat.h> befinden. Tabelle 16.16 enthält die Modi für Zugriffsrechte unter Linux/UNIX. AuÃerdem sollten Sie noch wissen, dass bei Verwendung des Flags O_CREAT die Zugriffsrechte unter Linux/UNIX nicht unbedingt gewährt werden müssen, da die Einschränkungsmaske die Vergabe von Rechten verhindern kann (wird) – und somit die Rechte selbst. Aus diesem Grund wurde mithilfe der Funktion umask() die Maske zur Wegnahme von Rechte-Bits auf 0 gesetzt, womit alle Zugriffsrechte in dieser Maske erlaubt werden. Im folgenden Listing soll eine Datei zum Lesen und Schreiben geöffnet werden. Existiert diese nicht, wird eine neue Datei erzeugt. Falls sie existiert, wird der Inhalt gelöscht und neu beschrieben. Hier sehen Sie den Quellcode, der portabel gehalten wurde: > /* open1.c */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #ifdef __unix__ #include <unistd.h> #elif __MSDOS__ || __WIN32__ || _MSC_VER #include <io.h> #endif int main(void) { int fh; if((fh=open("adress.txt", O_RDWR|O_CREAT|O_TRUNC))==-1) { perror("Fehler bei open()"); return EXIT_FAILURE; } close(fh); return EXIT_SUCCESS; } Falls Sie jetzt noch die Zugriffsrechte auf diese Datei vergeben wollen, muss für Linux/UNIX die Headerdatei <sys/stat.h> und für MS-DOS/Windows <sys\stat.h> eingebunden werden (beachten Sie den Slash und Backslash). Soll beispielsweise der User unter Linux diese Datei nur lesen dürfen, so muss nur mithilfe des ODER-Operators der Modus S_IRUSR hinzugefügt werden: > // alle Zugriffsrechte der Einschränkungsmaske erlauben umask(0); open("adress.txt", O_RDWR|O_CREAT|O_TRUNC, S_IRUSR)) == -1) Ein weiteres Beispiel mit open() ist z. B. das Aufrufen von Programmen aus der Kommandozeile: > /* open2.c */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #ifdef __unix__ #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #elif __MSDOS__ || __WIN32__ || _MSC_VER #include <io.h> #include <sys\stat.h> #endif int main(int argc, char *argv[]) { int fh; if( (fh=open(*++argv,O_RDONLY)) == -1) perror(*argv); else close(fh); return EXIT_SUCCESS; } In diesem Beispiel wird eine Datei zum Lesen geöffnet, deren Name als zweites Argument in der Kommandozeile angegeben wurde. Falls die Datei nicht existiert, wird eine entsprechende Fehlermeldung wie > Programmname : No such File in Directory ausgegeben. Danach wird der File-Deskriptor wieder geschlossen. Falls die Datei, die eben aufgerufen wurde, nicht existiert, aber anschlieÃend erzeugt werden soll, dann ist dies so möglich: > /* open3.c */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #ifdef __unix__ #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #elif __MSDOS__ || __WIN32__ || _MSC_VER #include <io.h> #include <sys\stat.h> #endif int main(int argc,char *argv[]) { int fh; if(*++argv == NULL) return EXIT_FAILURE; /* keine Argumente vorhanden */ if( (fh = open(*argv, O_RDONLY)) == -1) if( (fh = open(*argv,O_RDWR|O_CREAT)) == -1) perror(*argv); close(fh); return EXIT_SUCCESS; } Hiermit wird zuerst versucht, die Datei zu öffnen. Falls die Datei nicht existiert, wird sie gleich zum Lesen und Schreiben erzeugt. Bei der Erläuterung der Low-Level-Datei-E/A-Funktionen konnten Sie schon erkennen, warum eher auf die höhere Ebene zurückgegriffen wird. Wer auf mehreren Systemen programmiert, kann schnell durcheinanderkommen. Was bei dem einen System gelingt, ist bei dem anderen nicht machbar. Andererseits ist es durchaus hilfreich, beim Erzeugen einer Datei die Zugriffsrechte von Beginn an festzulegen (das gilt speziell unter Linux/UNIX). Daraus ergibt sich, dass Low-Level-Datei-E/A-Funktionen vorwiegend zur Systemprogrammierung eingesetzt werden. Vor allem für Linux/UNIX-Programmierer ist diese Art, eine Datei (auch Gerätedateien) zu öffnen, eine sehr wichtige Schnittstelle. Beispielsweise kann man hier mit folgendem einfachen Code-Konstrukt etwas auf dem Drucker ausgeben lassen: > int fd; // Drucker auf /dev/lp0 zum Schreiben öffnen fd = open("/dev/lp0", O_WRONLY); if(fd >= 0) // drucken ... write(fd, buf, buf_size); close(fd); ### 16.26.2 Datei schlieÃen – »close()« close() dient dazu, eine Datei mit dem Deskriptor fh zu schlieÃen, die zuvor mit open() oder create() geöffnet bzw. erzeugt wurde. Denn auch mit der Funktion open() kann nur eine bestimmte Anzahl von Dateien gleichzeitig geöffnet werden. Die Anzahl der maximal offenen Dateien ist in der Konstante OPEN_MAX deklariert. Hier sehen Sie die Syntax zu close(): > int close(int fh); Der Rückgabewert der Funktion ist bei Fehler –1, ansonsten 0. Hierzu noch ein kurzes Listing: > /* close.c */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #ifdef __unix__ #include <unistd.h> #elif __MSDOS__ || __WIN32__ || _MSC_VER #include <io.h> #endif int main(void) { int fh; if((fh=open("adressen.txt", O_RDONLY | O_CREAT)) == -1) { perror("Fehler bei open"); return EXIT_FAILURE; } if((close(fh)) == -1) printf("Fehler beim Schliessen der Datei\n"); else printf("Datei wurde ordentlich geschlossen\n"); return EXIT_SUCCESS; } Sie öffnen hier mit open() eine Datei zum Lesen. Falls diese nicht existiert, wird eine neue erzeugt. Danach wird der Deskriptor wieder mit einer Ãberprüfung geschlossen, ob der SchlieÃvorgang ordnungsgemäà verlief. Beim Programmende schlieÃen sich die offenen Deskriptoren selbst. ### 16.26.3 Datei erzeugen – »creat()« AuÃer mit open() kann auch mit der Funktion creat() eine neue Datei angelegt werden. Die Syntax von creat() sieht bei Linux/UNIX so aus: > #include <fcntl.h> #inlcude <sys/types.h> #include <sys/stat.h> int creat(const char *pfad, int modus); und unter Windows/MS-DOS so: > #include <fcntl.h> #inlcude <io.h> #include <sys\stat.h> int creat(const char *pfad, int modus); creat() arbeitet genauso wie die Funktion open(). pfad ist der Name der neu anzulegenden Datei mit dem Pfad. Mit modus sind die Modi gemeint, die im Abschnitt zu open() geschildert wurden. Existiert eine Datei bereits, wird diese geöffnet und geleert. Mit der Funktion open() und den Modi O_CREAT und O_TRUNC erreichen Sie dasselbe wie mit creat(). Und somit ist die Funktion creat() eigentlich völlig überflüssig und umständlich, da eine neu mit creat() angelegte Datei nur beschrieben werden kann. Um diese Datei lesen zu können, muss sie zuerst mit close() geschlossen werden, um sie anschlieÃend mit open() zum Lesen zu öffnen. creat() wurde zu einer Zeit benötigt, als die Funktion open() noch nicht die Angabe von O_CREAT kannte. Jetzt bleibt die Funktion natürlich weiterhin bestehen, da sonst alte Programme, die zu dieser Zeit entwickelt wurden, ohne Ãnderung am Quellcode nicht mehr übersetzt werden können. ### 16.26.4 Schreiben und Lesen – »write()« und »read()« Wir betrachten zuerst die Syntax der Funktion write (): > #include <unistd.h> /* für UNIX/LINUX */ #include <io.h> /* für MS-DOS */ int write(int fh, const void *puffer, size_t bytezahl); Mit der Funktion write() wird unformatiert in die Datei mit dem File-Deskriptor fh geschrieben. Um den geeigneten File-Deskriptor zu erhalten, muss die Datei zuvor mit open() oder create() geöffnet werden. Dann schreibt write() von der Datei mit dem fh-File-Deskriptor bytezahl Bytes in die Speicheradresse von puffer. Dieser ist wieder ein typenloser void-Zeiger und kann somit jeden beliebigen Datentyp annehmen. Bei einem Fehler liefert diese Funktion den Wert –1 zurück, ansonsten die Anzahl der erfolgreich geschriebenen Bytes. Hierzu ein einfaches Beispiel mit write(): > /* write1.c */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #ifdef __unix__ #include <unistd.h> #elif __MSDOS__ || __WIN32__ || _MSC_VER #include <io.h> #endif int main(void) { int fh; char puffer[100]; strcpy(puffer,"Dieser Text steht in \"test.txt\"\n"); if((fh=open("test.txt",O_RDWR|O_CREAT|O_TRUNC)) == -1) { perror(NULL); return EXIT_FAILURE; } if((write(fh, &puffer, sizeof(puffer))) == -1) { perror("Fehler bei write"); return EXIT_FAILURE; } printf("Erfolgreich in \"test.txt\" geschrieben\n"); return EXIT_SUCCESS; } Zuerst wird mit strcpy() ein String in das Array puffer kopiert. Danach wird mit open() die Datei test.txt geöffnet bzw. erzeugt. In den von open() zurückgegebenen File-Deskriptor werden dann mit der Funktion write() von der Adresse puffer Bytes der Anzahl sizeof(puffer) geschrieben. Die Funktion write() eignet sich genauso wie fwrite() dazu, ganze Strukturen auf einmal zu schreiben, wie das folgende Listing demonstriert: > /* write2.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #ifdef __linux__ #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #elif __MSDOS__ || __WIN32__ || _MSC_VER #include <io.h> #include <sys\stat.h> #endif #define MAXADRESSEN 10 #define MAX 30 struct kunde { char name[MAX]; char vorname[MAX]; int kundenummer; char ort[MAX]; char strasse[MAX]; int hausnummer; int vorwahl; int telefonnr; }; struct kunde k[MAXADRESSEN]; static int counter=0; void neukunde(void) { int fh; if(counter==MAXADRESSEN) printf("Kein Speicherplatz mehr frei!!!\n"); else { printf("Name...................: "); fgets(k[counter].name, MAX, stdin); printf("Vorname................: "); fgets(k[counter].vorname, MAX, stdin); k[counter].kundenummer=counter; printf("Ort....................: "); fgets(k[counter].ort, MAX, stdin); printf("Strasse................: "); fgets(k[counter].strasse, MAX, stdin); printf("Hausnummer.............: "); do { scanf("%d",&k[counter].hausnummer); } while(getchar() != '\n'); printf("Vorwahl................: "); do { scanf("%d",&k[counter].vorwahl); } while(getchar() != '\n'); printf("Telefonnummer..........: "); do { scanf("%d",&k[counter].telefonnr); } while(getchar() != '\n'); if((fh=creat("kunden.dat",S_IREAD|S_IWRITE)) == -1) printf("Konnte\"kunden.dat\" nicht öffnen\n"); else if((write(fh,&k,sizeof(k))) == -1) printf("Konnte nicht in \"kunden.dat\" schreiben\n"); else counter++; } } int main(void) { int wahl; do { printf("\t1: Neuen Kunden eingeben\n\n"); /* printf("\t2: Kunden ausgeben\n\n"); */ printf("\t3: Programmende\n\n"); printf("\tEingabe :> "); do { scanf("%d",&wahl); } while(getchar() != '\n'); switch(wahl) { case 1 : neukunde(); break; /* case 2 : lese(); break; */ case 3 : printf("bye\n"); break; default : printf("Falsche Eingabe!!!\n"); } } while(wahl != 3); return EXIT_SUCCESS; } Zuerst werden in der Funktion neukunde() die Daten an die Struktur übergeben. AnschlieÃend wird mit > if((fh=creat("kunden.dat",S_IREAD|S_IWRITE)) == -1) eine Datei namens kunden.dat zum Lesen und Schreiben erzeugt. Jetzt kann mit > else if((write(fh,&k,sizeof(k))) == -1) in diese Datei über den File-Deskriptor fh von der Adresse struct kunde k mit der GröÃe der Struktur (sizeof(k)) geschrieben werden. AnschlieÃend wird counter inkrementiert. Ein wenig verwirrend können die if else-Bedingungen sein. Aber bei Korrektheit werden alle drei ausgeführt, solange keine der Bedingungen –1 zurückliefert. Jetzt befindet sich im Verzeichnis, in dem das Programm ausgeführt wird, eine Datei namens kunden.dat. Wird diese Datei mit einem Texteditor geöffnet, könnte man meinen, das Schreiben mit write() hätte nicht geklappt. Aber wie ich bereits erwähnt habe, wird unformatiert in eine Datei geschrieben. Und dies lässt sich nun mal nicht mit einem Texteditor lesen. Anmerkung | | --- | | Jetzt folgt das Gegenstück zur Funktion write(). Zuerst die Syntax: > int read(int fh, const void *puffer, site_t bytezahl); Mit der Funktion read() werden bytezahl Bytes aus der Datei mit dem File-Deskriptor fh gelesen. Die Daten werden an derAdresse von puffer abgelegt. Zuvor muss natürlich die Datei mit open() geöffnet werden. Auch hier liefert die Funktion bei einem Fehler –1, ansonsten, wenn alles richtig verlief, die Anzahl gelesener Bytes zurück. Hierzu sehen Sie ein Listing, das eine Datei kopiert: > /* read1.c */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #ifdef __unix__ #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #elif __MSDOS__ || __WIN32__ || _MSC_VER #include <io.h> #include <sys\stat.h> #endif #define MAXBYTES 1024 int main(int argc, char *argv[]) { int in,out,count; char buffer[MAXBYTES]; if(argc < 3) { printf("Aufruf: programmname quelldatei zieldatei\n"); return EXIT_FAILURE; } if( (in=open(*++argv ,O_RDONLY)) == -1) printf("Fehler open %s\n", (char *)argv); if( (out=open(*++argv, O_WRONLY | O_TRUNC | O_CREAT)) == -1) printf("Fehler open %s\n", (char *)argv); while( (count = read(in, buffer, MAXBYTES)) ) write(out,buffer,count); close(in); close(out); return EXIT_SUCCESS; } Damit wird die Datei, die als zweites Argument in der Kommandozeile angegeben wird, in die Datei kopiert, die als drittes Argument angegeben wird. Jetzt soll das erste Programm aus dem vorigen Abschnitt zu write() mit der Funktion read() ergänzt werden: > /* read2.c */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #ifdef __unix__ #include <unistd.h> #elif __MSDOS__ || __WIN32__ || _MSC_VER #include <io.h> #include <sys\stat.h> #endif int main(void) { int fh; char puffer[100]; char pufferneu[100]; strcpy(puffer,"Dieser Text steht in \"test.txt\"\n"); if( (fh = open("test.txt",O_RDWR|O_CREAT|O_TRUNC)) == -1) { perror(NULL); return EXIT_FAILURE; } if((write(fh, &puffer, sizeof(puffer))) == -1) { perror("Fehler bei write"); return EXIT_FAILURE; } close(fh); if( (fh = open("test.txt",O_RDONLY)) == -1) { perror(NULL); return EXIT_FAILURE; } if( (read(fh, &pufferneu, sizeof(pufferneu))) == -1) { perror("Fehler bei read"); return EXIT_FAILURE; } printf("%s" ,pufferneu); close(fh); return EXIT_SUCCESS; } Bis zur Funktion write() ist das so weit nichts Neues für Sie. Mit read() wird hier die GröÃe von sizeof(pufferneu) Bytes mit dem File-Deskriptor fh in die Adresse von pufferneu gelegt. Das Programm dürfte keinem mehr Kopfzerbrechen bereiten. Daher soll auch das zweite obige Listing mit der Funktion read() bestückt werden. SchlieÃlich wollen Sie die Daten, die geschrieben wurden, auch wieder lesen können: > /* read3.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #ifdef __unix__ #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #elif __MSDOS__ || __WIN32__ || _MSC_VER #include <io.h> #include <sys\stat.h> #endif #define MAXADRESSEN 10 #define MAX 30 struct kunde { char name[MAX]; char vorname[MAX]; int kundenummer; char ort[MAX]; char strasse[MAX]; int hausnummer; int vorwahl; int telefonnr; }; struct kunde k[MAXADRESSEN]; static int counter=0; void neukunde(void) { int fh; if(counter==MAXADRESSEN) printf("Kein Speicherplatz mehr frei!!!\n"); else { printf("Name...................: "); fgets(k[counter].name, MAX, stdin); printf("Vorname................: "); fgets(k[counter].vorname, MAX, stdin); k[counter].kundenummer=counter; printf("Ort....................: "); fgets(k[counter].ort, MAX, stdin); printf("Strasse................: "); fgets(k[counter].strasse, MAX, stdin); printf("Hausnummer.............: "); do { scanf("%d",&k[counter].hausnummer); } while(getchar() != '\n'); printf("Vorwahl................: "); do { scanf("%d",&k[counter].vorwahl); } while(getchar() != '\n'); printf("Telefonnummer..........: "); do { scanf("%d",&k[counter].telefonnr); } while(getchar() != '\n'); if((fh=open("kunden.dat",O_CREAT|O_RDWR)) == -1) printf("Konnte\"kunden.dat\" nicht öffnen\n"); else if((write(fh,&k,sizeof(k))) == -1) printf("Konnte nicht in \"kunden.dat\" schreiben\n"); else counter++; } } void lese(void) { int fh; int num; printf("Bitte geben Sie die Kundennummer ein : "); scanf("%d",&num); if( (fh = open("kunden.dat",O_RDONLY)) == -1) { perror("Kann Kundendatei nicht öffnen"); exit(EXIT_FAILURE); } read(fh,&k,sizeof(k)); printf("\n\n"); printf("Name..........%s",k[num].name); printf("Vorname.......%s",k[num].vorname); printf("Kundennummer..%d\n",k[num].kundenummer); printf("Wohnort.......%s",k[num].ort); printf("Strasse.......%s",k[num].strasse); printf("Hausnummer....%d\n",k[num].hausnummer); printf("Vorwahl.......%d\n",k[num].vorwahl); printf("Telefonnum....%d\n",k[num].telefonnr); } int main(void) { int wahl; do { printf("\t1: Neuen Kunden eingeben\n\n"); printf("\t2: Kunden ausgeben\n\n"); printf("\t3: Programmende\n\n"); printf("\tEingabe :> "); do { scanf("%d",&wahl); }while(getchar() != '\n'); switch(wahl) { case 1 : neukunde(); break; case 2 : lese(); break; case 3 : printf("bye\n"); break; default: printf("Falsche Eingabe!!!\n"); } } while(wahl != 3); return EXIT_SUCCESS; } Das Datenprogramm ist wieder um eine Funktion reicher geworden, nämlich um lese(). Bei dieser wird mit > if((fh=open("kunden.dat", O_RDONLY)) == -1) die Kundendatei zum Lesen geöffnet und mit > read(fh,&k,sizeof(k)); ausgelesen sowie anschlieÃend auf dem Bildschirm ausgegeben. Ein paar Zeilen noch zum File-Deskriptor. Die folgende Anwendung des File-Deskriptors ist bekannt: > write(fh, &puffer, sizeof(puffer)); read(fh, &puffer, sizeof(puffer)); Aber statt des File-Deskriptors fh können logischerweise auch Ganzzahlen verwendet werden. Die in Tabelle 16.17 genannten Ziffern sind allerdings fest belegt, da sie vordefinierte Deskriptoren sind. Ein Listing dazu: > /* deskriptor_nr1.c */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ #include <unistd.h> #elif __MSDOS__ || __WIN32__ || _MSC_VER #include <io.h> #endif int main(void) { char puffer[100]; read(0, &puffer, sizeof(puffer)); printf("%s",puffer); return EXIT_SUCCESS; } Mit read(0, &puffer, sizeof(puffer)) wird aus der Standardeingabe (stdin) in die Adresse des Puffers gelesen, also von der Tastatur. Anhand der Ausgabe können Sie auch die Eigenheiten der niedrigeren Ebene erkennen. Hier wird nicht automatisch ein Stringende-Zeichen angehängt, darum müssen Sie sich selbst kümmern. Dasselbe kann auch mit write() auf dem Bildschirm vorgenommen werden: > /* deskriptor_nr2.c */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ #include <unistd.h> #elif __MSDOS__ || __WIN32__ || _MSC_VER #include <io.h> #endif int main(void) { char puffer[] = "Ich werde im Low-Level-I/O ausgegeben"; write(1, &puffer, sizeof(puffer)); return EXIT_SUCCESS; } Da der File-Deskriptor manchmal so verwendet wird, sollte dies hier nicht unerwähnt bleiben. ### 16.26.5 File-Deskriptor positionieren – »lseek()« lseek() ist dieselbe Funktion, die bei der höheren Ebene fseek() hieÃ, und dient zum Verschieben des File-Deskriptors in der geöffneten Datei. Die Syntax von lseek() lautet: > #inlcude <unistd.h> /* für UNIX */ #include <sys/types.h> /* für UNIX */ #inlcude <io.h> /* für MS-DOS/WIN */ long lseek(int fh, long offset, int wie); Die Datei, in der der File-Deskriptor verschoben werden soll, wird mit dem File-Deskriptor fh angegeben, der natürlich zuvor mit open() geöffnet bzw. erzeugt wurde. Um wie viele Bytes der File-Deskriptor von der Position wie verschoben werden soll, wird mit offset angegeben. Die Angaben von wie sind dieselben wie schon bei fseek(). Tabelle 16.18 zeigt, welche Möglichkeiten zur Verfügung stehen. Als Rückgabewert gibt diese Funktion den Wert der aktuellen Position des File-Deskriptors zurück: > long aktuelle_position; aktuelle_position = lseek(fh, 0L, SEEK_CUR); Bei einem Fehler gibt diese Funktion –1 zurück. lseek() sollte allerdings nicht auf kleiner als 0 geprüft werden, sondern auf –1, da es durchaus sein kann, dass es Gerätedateien gibt, die einen negativen Wert zurückliefern. Weitere Möglichkeiten von lseek() sind: Deskriptor auf den Dateianfang setzen: > lseek(fh, 0L, SEEK_SET); Deskriptor um 100 Bytes von der aktuellen Position nach vorn versetzen: > lseek(fh, 100L, SEEK_CUR); Deskriptor um 10 Bytes von der aktuellen Position zurücksetzen: > lseek(fh, -10L, SEEK_CUR); Deskriptor auf das letzte Byte setzen (nicht EOF): > lseek(fh, -1L, SEEK_END); Ein Beispiel zu lseek() kann ich mir sparen, da diese Funktion genauso eingesetzt wird wie fseek(); nur dass anstatt eines Streams hierbei ein File-Deskriptor verwendet wird. ### 16.26.6 File-Deskriptor von einem Stream – »fileno()« Manchmal benötigen Sie von einem offenen Stream den File-Deskriptor. Die Syntax dieser Funktion lautet: > int fileno(FILE *fz); fileno() ist erforderlich, falls eine Datei mit fopen() geöffnet wurde, um den Stream für Funktionen einzusetzen, die einen File-Deskriptor benötigen (z. B. Funktionen wie dup(), dup2() oder fcntl()). Hier sehen Sie ein Listing dazu: > /* fileno.c */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ #include <unistd.h> #else #include <io.h> #endif int main(void) { FILE *fz; int fd,fd2; char datei[255]; printf("File-Deskriptoren zu stdin, stdout und stderr : "); printf("%d, %d und %d\n", fileno(stdin),fileno(stdout),fileno(stderr)); printf("Welche Datei wollen Sie öffnen : "); scanf("%s",datei); fz=fopen(datei, "r"); if(!fz) { perror(NULL); return EXIT_FAILURE; } fd = fileno(fz); printf("File-Deskriptor zur Datei %s lautet %d\n",datei,fd); fd2=dup(fd); printf("File-Deskriptor, der kopiert wurde, lautet %d\n",fd2); return EXIT_SUCCESS; } Zu Beginn des Programms werden erst die File-Deskriptoren zu stdin, stdout und stderr ausgegeben, diese sollten immer 0, 1 und 2 sein. AnschlieÃend wird der File-Deskriptor in einer von Ihnen geöffneten Datei ausgegeben. Dieser File-Deskriptor wird jetzt mit der Funktion dup() dupliziert und ebenfalls auf dem Bildschirm ausgegeben. ### 16.26.7 Stream von File-Deskriptor – »fdopen()« Mit der Funktion fdopen() erhalten Sie aus einem File-Deskriptor einen FILE-Zeiger: > #include <stdio.h> FILE *fdopen(int fd, const char *modus); fdopen() ist das Gegenstück zu fileno(). Als modus, wie die Datei geöffnet wird, können dieselben Modi wie bei der Funktion open() genutzt werden. fdopen() wird oft auf File-Deskriptoren angewandt, die von Funktionen zurückgegeben werden, die Pipes oder Kommunikationskanäle in Netzwerken einrichten. Das kommt daher, weil einige Funktionen (open(), dup(), dup2(), fcntl(), pipe(), ...) in Netzwerken nichts mit Streams anfangen können und File-Deskriptoren benötigen. Um aber wieder aus Deskriptoren einen Stream (FILE-Zeiger) zu erzeugen, ist die Funktion fdopen() erforderlich. Hierzu ein kurzes Beispiel: > /* fdopen.c */ #include <stdio.h> #include <stdlib.h> #ifdef __linux__ #include <unistd.h> #else #include <io.h> #endif int main(void) { FILE *fz, *fz2; int fd,fd2; char datei[255]; printf("Welche Datei wollen Sie erzeugen: "); scanf("%s",datei); fz=fopen(datei, "w+"); if(!fz) perror(NULL); fd = fileno(fz); printf("File-Deskriptor zur Datei %s lautet %d\n",datei,fd); fd2=dup(fd); printf("Der File-Deskriptor, der kopiert wurde %d\n\n",fd2); printf("Wir wollen einen STREAM oeffnen....\n"); fz2 = fdopen(fd2, "w"); if(!fz2) perror(NULL); fprintf(fz,"Dieser Text steht in %s\n",datei); fprintf(fz2,"Dieser Text steht auch in %s\n",datei); fprintf(stdout,"Es wurde etwas in die " "Datei %s geschrieben",datei); return EXIT_SUCCESS; } Die beiden Funktionen fileno() und fdopen() werden vorwiegend in der Netzwerkprogrammierung eingesetzt. Mit der Funktion access() können Sie feststellen, ob ein Prozess bestimmte Berechtigungen für den Zugriff auf eine Datei hat. Die Syntax zur Funktion access() lautet: > #include <unistd.h> /* für UNIX/LINUX */ #include <io.h> /* für MS-DOS */ int access(const char *pfad, int modus); So wird überprüft, ob der pfad der Datei existiert und die Zugriffsrechte laut modus besitzt. Folgende Zugriffsrechte (Modi) existieren (siehe Tabelle 17.5). Bei Erfolg gibt diese Funktion den Wert 0 zurück, ansonsten – bei einem Fehler –1. Das folgende Listing überprüft die Zugriffsrechte aller in der Kommandozeile eingegebenen Programme mit der Funktion access(): > /* check_access.c */ #ifdef __unix__ #include <unistd.h> #define EXIST F_OK #define EXEC X_OK #define WRITE W_OK #define READ R_OK #else #include <io.h> #define EXIST 00 #define EXEC 01 #define WRITE 02 #define READ 04 #endif #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if(argc == 1) { fprintf(stderr, "Mindestens eine Datei angeben!\n"); return EXIT_FAILURE; } while(*++argv) { printf("%s : \n", *argv); /* Existiert die Datei? */ if(access(*argv, EXIST) != -1) { /* Lesen und Schreiben nicht erlaubt */ if(access(*argv, WRITE|READ) == -1) { /* Nur lesen? */ if(access(*argv, READ) != -1) printf("... ist lesbar\n"); /* Nur schreiben? */ else if(access(*argv, WRITE) != -1) printf("... ist schreibbar\n"); } else printf("ist Lesen und Schreiben erlaubt\n"); /* Datei ausführbar? */ if(access(*argv, EXEC) != -1) printf("... ist ausführbar\n"); } else { fprintf(stderr, "...existiert nicht\n"); return EXIT_FAILURE; } } return EXIT_SUCCESS; } Zuerst wird überprüft, ob die Datei überhaupt existiert: > if(access(*argv, EXIST) != -1) Ob die Datei zum Lesen und Schreiben freigegeben ist, wird anschlieÃend mit der folgenden Zeile überprüft: > if(access(*argv, WRITE|READ) != -1) Trifft dies nicht zu, werden die einzelnen Zugriffsmöglichkeiten getestet: > if(access(*argv, READ) != -1) printf("... ist lesbar\n"); else if(access(*argv, WRITE) != -1) printf("... ist schreibbar\n"); Die Ãberprüfung, ob die Datei ausführbar ist, mit > if(access(*argv, EXEC) != -1) kann bei Windows/MS-DOS entfernt werden, da sie nur unter UNIX/Linux einen Sinn ergibt. In diesem Listing wurden die Konstanten der einzelnen Zugriffsrechte hinter Makros versteckt, damit das Programm möglichst portabel bleibt. Unter Linux/UNIX werden übrigens nur die ersten drei User-Bits der UID überprüft (rwx), also die Zugriffsrechte des Datei-Eigentümers. Es ist auch möglich, access() mit mehreren Konstanten zu verknüpfen: > if( (access(*argv,F_OK|R_OK) ) != -1) /* if( (access(*argv,00|04) ) != -1) */ Hier wird z. B. ermittelt, ob die Datei existiert und ob für sie Leserechte vorhanden sind. # 17.3 Verzeichnisfunktionen ## 17.3 Verzeichnisfunktionen Bei den bisherigen ANSI-C-Funktionen konnte es Ihnen egal sein, wie ein Dateisystem aufgebaut ist. Es gibt zwar einige systemabhängige Faktoren, die zu beachten sind (beispielsweise das Trennzeichen von Verzeichnisnamen), aber meistens sind diese Funktionen so universell implementiert, dass es dennoch nicht zu Problemen kommt. Bei einem Zugriff auf Verzeichnisse ist es leider nicht mehr so einfach. Hierbei werden meist POSIX-konforme Funktionen verwendet, die vorwiegend in der UNIX-Welt beheimatet sind. Keine Sorge, auch MS-Windows-Anwender können diese Funktionen nutzen. In vielen Compilern unter diesem System sind diese Funktionen integriert. ### 17.3.1 Verzeichnis erstellen, löschen und wechseln – »mkdir()«, »rmdir« und »chdir« > #include <sys/types.h> /* Linux/UNIX */ #include <sys/stat.h> /* Linux/UNIX */ #include <dir.h> /* MS-DOS/WIN */ int mkdir(const char *pfad, [int modus]); Mit der Funktion mkdir() wird ein neues Verzeichnis mit dem Namen pfad angelegt. Zusätzlich werden in dem neuen Verzeichnis automatisch auch das Arbeitsverzeichnis (Working Directory) (.) und das Eltern-Verzeichnis (Parent Directory) (..) mit angelegt. Die Zugriffsrechte können über modus vergeben werden. Dies gilt aber nur für Linux/UNIX und nicht für Windows/MS-DOS. Die Modi unter Linux/UNIX entnehmen Sie bitte der Manpage von chmod(). Hierzu sehen Sie als Beispiel ein Listing, mit dem ein neues Verzeichnis erstellt wird. > /* create_dir.c */ #ifdef __unix__ #include <sys/types.h> #include <sys/stat.h> #define MODUS ,0711) #elif __WIN32__ || _MS_DOS_ #include <dir.h> #define MODUS ) #else #include <direct.h> /* Visual C++ */ #define MODUS ) #endif #include <stdio.h> #include <stdlib.h> int main(void) { char pfadname[200]; printf("Wie soll der neue Ordner heissen: "); scanf("%199s",pfadname); if(mkdir(pfadname MODUS == -1) /*Nicht schön, aber portabler*/ printf("Konnte kein neues Verzeichnis erstellen\n"); else printf("Neues Verzeichnis namens %s erstellt\n",pfadname); return EXIT_SUCCESS; } Wurde das Programm ausgeführt, sollte sich im benannten Verzeichnis ein neuer Ordner mit dem eingegebenen Namen befinden. Unter Linux/UNIX muss auÃerdem beachtet werden, dass für den modus auch die Ausführrechte (Execute-Bits) gesetzt sind, um auch Zugriff auf das neue Verzeichnis zu haben. Sofern versucht wird, ein Verzeichnis zu erstellen, das bereits existiert, wird dies fehlschlagen. errno wird dann auf einen entsprechenden Wert gesetzt (EEXIST). Als Nächstes soll in das eben erstellte Verzeichnis gewechselt werden. Dies gelingt mit der Funktion chdir(). Die Syntax von chdir() sieht so aus: > #include <unistd.h> /* Linux/UNIX */ #include <dir.h> /* MS-DOS/WIN */ int chdir(const char *pfad); Mit chdir() wird in das Arbeitsverzeichnis gewechselt, das jedes ablaufende Programm besitzt. Bei einem Fehler gibt diese Funktion –1 zurück, ansonsten 0. In dem folgenden Listing wird erst ein neues Verzeichnis erstellt, und danach wird mit chdir() in das erstellte Verzeichnis gewechselt und darin eine Textdatei erzeugt. > /* change_dir.c */ #ifdef __linux__ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #define MODUS ,0711) #elif _WIN32__ || _MS_DOS_ #include <dir.h> #define MODUS ) #else #include <direct.h> #define MODUS ) #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> int main(void) { char pfadname[200]; printf("Wie soll der neue Ordner heissen : "); scanf("%199s",pfadname); if(mkdir(pfadname MODUS == -1) printf("Konnte kein neues Verzeichnis erstellen\n"); else { printf("Neues Verzeichnis namens %s erstellt\n", pfadname); printf(" --> (%s)\n", strerror(errno)); } /* Jetzt wollen wir in das neue Verzeichnis wechseln. */ if(chdir(pfadname) == -1) { printf("Konnte nicht in das Verzeichnis wechseln\n"); return EXIT_FAILURE; } else printf("Erfolgreich nach %s gewechselt!\n", pfadname); /* testfile im Verzeichnis erstellen*/ fopen("testfile", "w"); return EXIT_SUCCESS; } Jetzt sollte sich in dem eben erzeugten Verzeichnis eine Datei namens testfile befinden. Es dürfte Ihnen aufgefallen sein, dass das Programm, wenn es sich beendet, automatisch wieder in das Verzeichnis des Elternprozesses zurückwechselt. Wenn Sie mehrmals in einem Programm Verzeichnisse erstellen müssen und in diese wechseln, schreiben Sie besser eine Funktion wie z. B.: > int makedir(char *dir) { if(mkdir(dir, 0755) != -1) /* Windows/MS-DOS ohne 0755 */ if(chdir(dir) != -1) return OK; return ERROR; } Wollen Sie ein Verzeichnis wieder löschen, können Sie die Funktion rmdir() verwenden. Die Syntax von rmdir() lautet: > #include <unistd.h> /* UNIX/Linux */ #include <dir.h> /* MS-DOS */ int rmdir(const char *pfad); Mit rmdir() kann ein Verzeichnis (rmdir steht für remove directory) gelöscht werden. Unter Linux/UNIX setzt dies allerdings voraus, dass dieses Verzeichnis auÃer dem (.) und (..) keinen anderen Eintrag mehr beinhaltet. Bei Erfolg gibt diese Funktion 0 zurück und bei einem Fehler –1. Dazu soll das Programm, das eben verwendet wurde, erweitert werden. Das Verzeichnis, das erstellt wurde, in das gewechselt wurde und in dem eine Datei erzeugt wurde, soll am Ende des Programms wieder gelöscht werden. Hier sehen Sie das Listing dazu: > /* remove_dir.c */ #ifdef __linux__ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #define MODUS ,0711) #elif _WIN32__ || _MS_DOS_ #include <dir.h> #define MODUS ) #else #include <direct.h> #define MODUS ) #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> int makedir(char *dir) { if(mkdir(dir MODUS != -1) if(chdir(dir) != -1) return 0; return -1; } int main(void) { char pfadname[200]; printf("Wie soll der neue Ordner heissen : "); scanf("%199s",pfadname); if(makedir(pfadname) == -1) { printf("Konnte kein neues Verzeichnis erstellen\n"); printf(" --> (%s)\n", strerror(errno)); } /* testfile im Verzeichnis erstellen */ fopen("testfile","w"); if(rmdir(pfadname) == -1) { printf("Konnte Verzeichnis %s nicht loeschen!!\n",pfadname); printf(" --> (%s)\n", strerror(errno)); } return EXIT_SUCCESS; } Unter MS-DOS/Windows wird das Listing problemlos funktionieren. Mit Linux/UNIX kann das Verzeichnis nicht gelöscht werden, da sich dort noch eine Datei befindet. Das Verzeichnis muss also zuvor leer sein. Das vollständige Verzeichnis lässt sich mit folgendem Shell-Aufruf leeren: > rmdir Verzeichnis | rm -rf Verzeichnis Im Listing kann dieser Aufruf folgendermaÃen eingesetzt werden: > /* remove_dir_unix.c */ #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> int main(void) { char pfadname[200]; char deletefiles[200]; printf("Welchen Ordner wollen Sie löschen : "); scanf("%189s",pfadname); strcpy(deletefiles,"rm -rf "); strcat(deletefiles,pfadname); strcat(deletefiles,"/*"); printf("%s\n",deletefiles); system(deletefiles); if(rmdir(pfadname) == -1) { printf("Konnte Verzeichnis %s nicht löschen!!\n",pfadname); printf(" --> (%s)\n", strerror(errno)); } return EXIT_SUCCESS; } ### 17.3.2 In das Arbeitsverzeichnis wechseln – »getcwd()« Mit der Funktion getcwd() lässt sich der Name des Arbeitsverzeichnisses (Working Directory) ermitteln. Die Syntax von getcwd() lautet: > #include <unistd.h> /* Linux/UNIX */ #include <dir.h> /* MS-DOS/WIN */ char *getcwd(char *puffer, int puffergroesse); Die Funktion schreibt in die Speicheradresse puffer den Pfadnamen des Arbeitsverzeichnisses mit abschlieÃendem '\0'. Mit puffergroesse wird die GröÃe des Puffers angegeben. Die Funktion gibt bei Erfolg den Pfadnamen des Arbeitsverzeichnisses an puffer zurück oder bei einem Fehler NULL. Hier sehen Sie ein Beispiel dafür, wie diese Funktion verwendet wird: > /* working_D.c */ #ifdef __unix__ #include <unistd.h> #elif __WIN32__ || _MS_DOS_ #include <dir.h> #else #include <direct.h> /* Visual C++ */ #endif #include <stdio.h> #include <stdlib.h> int main(void) { char puffer[200]; if(getcwd(puffer,sizeof(puffer)) == NULL) { fprintf(stderr, "Fehler bei getcwd ...\n"); return EXIT_FAILURE; } printf("Working-Directory: %s\n", puffer); return EXIT_SUCCESS; } Für Linux/UNIX gilt auÃerdem: Wechseln Sie in ein Verzeichnis, das ein symbolischer Link auf ein anderes Verzeichnis ist, so wird in das Verzeichnis gewechselt, auf das der symbolische Link zeigt. Ein praktisches Beispiel unter Linux: Der User hat den Namen seines Home-Verzeichnisses vergessen. Er muss aber jetzt wieder in das Verzeichnis wechseln. Welches das ist, kann er mit der Eingabe des Shellbefehls env (Environment) oder mit der C-Funktion getenv()herausfinden. Hier sehen Sie das Listing: > /* go_home.c */ #ifdef __unix__ #include <unistd.h> #elif __WIN32__ || _MS_DOS_ #include <dir.h> #else #include <direct.h> /* Visual C++ */ #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 200 int main(void) { char puffer[MAX]; char home[MAX]; if( getenv("HOME") == NULL ) { printf("getenv(\"HOME\") findet nichts\n"); return EXIT_FAILURE; } /* das Heimatverzeichnis nach home */ strncpy(home, getenv("HOME"), MAX-1); home[MAX-1] = '\0'; /* Working Directory lesen */ if(getcwd(puffer,sizeof(puffer)) == NULL) { fprintf(stderr, "Fehler bei getcwd ...\n"); return EXIT_FAILURE; } /* Sind wir schon im Heimatverzeichnis? */ if(strcmp(home,puffer) == 0) printf("Wir sind daheim : %s\n",puffer); else { /* Nicht, dann wechseln wir ins Heimatverzeichnis. */ chdir(home); /* Der Beweis: */ printf("back at home: %s \n", getcwd(puffer,sizeof(puffer))); } return EXIT_SUCCESS; } ### 17.3.3 Verzeichnisse öffnen, lesen und schlieÃen – »opendir()«, »readdir()« und »closedir()« Um Verzeichnisse zu lesen, ist in der Headerdatei mit #include <dirent.h> eine interne Struktur namens DIR deklariert. Der Inhalt dieser Struktur ist hier jetzt nicht von Interesse, sondern es geht um die folgenden Funktionen, die mit der Struktur arbeiten. # »opendir()« – ein Verzeichnis öffnen Wir beginnen mit der Funktion opendir(): > #include <sys/types.h> #include <dirent.h> DIR *opendir(const char *dirname); Bei Erfolg wird mit dieser Funktion das Verzeichnis dirname geöffnet, auf dessen Adresse dann der DIR-Zeiger verweist. Ansonsten wird bei einem Fehler NULL zurückgegeben. Der DIR-Zeiger wird jetzt verwendet, um den Inhalt eines Verzeichnisses auszulesen. Dies wird jetzt gleich mit der Funktion readdir() vorgenommen. # »readdir()« – aus einem Verzeichnis lesen Die Syntax von readdir() lautet: > #include <sys/types.h> #include <dirent.h> struct dirent *readdir(DIR *dir); Bei einem Fehler gibt diese Funktion ebenfalls NULL zurück. Ansonsten gibt sie eine Adresse der Struktur dirent zurück, die Folgendes beinhaltet: > struct dirent { long d_ino; /* i-node Nr. (bei Windows/MS-DOS immer 0) */ unsigned short d_reclen; /* (bei Windows/MS-DOS immer 0) */ unsigned short d_namlen; /* Länge des Namens in d_name */ char *d_name; /* Dateiname mit abschlieÃendem '\0' */ }; In der Praxis kann die Funktion readdir() so verwendet werden: > DIR *dir; struct dirent *dirzeiger; /* Verzeichnis öffnen */ if((dir=opendir(dirname)) != NULL) /* komplettes Verzeichnis Eintrag für Eintrag auslesen */ while((dirzeiger=readdir(dir)) != NULL) printf("%s\n",(*dirzeiger).d_name); Es wird zuerst mit opendir() ein Verzeichnis geöffnet und danach mit readdir() der komplette Inhalt des Verzeichnisses ausgegeben. # »rewinddir()« – Verzeichnis-Zeiger auf den Anfang zurücksetzen Mit der Funktion rewinddir() wird der Lesezeiger wieder an den Anfang der Namensliste des Verzeichnisses zurückgesetzt. Die Syntax von rewinddir() lautet: > #include <sys/types.h> #include <dirent.h> void rewinddir(DIR *dir); # »closedir()« – Verzeichnis schlieÃen Am Ende wird dann mit der Funktion closedir() das Verzeichnis geschlossen, das mit opendir() geöffnet wurde. Bei Erfolg gibt diese Funktion 0 und bei Fehler –1 zurück. Die Syntax lautet: > #include <sys/types.h> #inlcude <dirent.h> int closedir(DIR *dir); Hier folgt ein ausführbares Beispiel, das alle Funktionen in Aktion demonstriert: > /* read_dir.c */ #include <sys/types.h> #include <dirent.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { DIR *dir; struct dirent *dirzeiger; if(argc != 2) { fprintf(stderr,"Benutzung : %s Directory\n", argv[0]); return EXIT_FAILURE; } /* das Verzeichnis öffnen */ if((dir=opendir(argv[1])) == NULL) { fprintf(stderr,"Fehler bei opendir ...\n"); return EXIT_FAILURE; } /* das komplette Verzeichnis auslesen */ while((dirzeiger=readdir(dir)) != NULL) printf("%s\n",(*dirzeiger).d_name); /* Lesezeiger wieder schlieÃen */ if(closedir(dir) == -1) printf("Fehler beim SchlieÃen von %s\n", argv[1]); return EXIT_SUCCESS; } Mit diesem Programm wird das vollständige Verzeichnis ausgegeben, das Sie über die Kommandozeile angeben. # »telldir()« und »seekdir()« – Positionierung im Verzeichnis Auf einigen Systemen gibt es zusätzlich noch die Funktion telldir(): > #include <sys/types.h> #include <sys/dirent.h> off_t telldir(DIR *dirptr) Diese Funktion liefert zu einem mit readdir() gelesenen Verzeichnis die Position des Lesezeigers zurück. Mit der Funktion seekdir() lässt sich die Position des DIR-Zeigers verschieben: > #include <sys/types.h> #include <sys/dirent.h> void seekdir(DIR *dirptr, off_t pos) Damit wird der mit opendir() geöffnete Lesezeiger (dirptr) auf die Position pos gesetzt, die Sie zuvor mit der Funktion telldir() ermittelt haben. Hierzu noch ein kurzer Ausschnitt dieser beiden Funktionen: > off_t pos; /* aktuelle Position im Verzeichnis ermitteln */ pos = telldir(dir_ptr); /* viele Funktionen */ ... /* zur aktuellen Position zurückspringen */ seekdir(dir_ptr, pos); # Probleme mit der Portabilität Ein Problem bei Funktionen wie opendir(), readdir() oder closedir() ist, dass sie POSIX-konform und aus diesem Grund häufig nicht bei Compilern für MS-Windows implementiert sind. Unter UNIX-artigen Systemen müssen Sie sich wegen dieser Funktionen keine Gedanken machen. Um also unter MS-Windows, genauer gesagt unter WIN32, ein vollständiges Verzeichnis auszugeben, müssen Sie auf die Windows-Systemprogrammierung zurückgreifen. Die Windows-Programmierung hier genauer zu erläutern, würde den Rahmen des Kapitels oder gar des Buchs sprengen. Aber zu Anschauungszwecken folgt hier eine portablere Lösung, mit der Sie ein vollständiges Verzeichnis ausgeben lassen können: > /* portabel_readdir.c */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ #include <dirent.h> #include <sys/types.h> /* UNIX-Funktion zum Ausgeben des kompletten Verzeichnisses */ void list_dir(const char *path) { DIR *dirptr; struct dirent *dir; if ((dirptr=opendir(path)) == NULL) return; while((dir=readdir(dirptr)) != NULL) printf("%s\n",dir->d_name); closedir(dirptr); } #elif __WIN32__ || _MSC_VER #include <windows.h> /* Win32-Funktion zum Ausgeben des kompletten Verzeichnisses */ void list_dir(const char *path) { WIN32_FIND_DATA dir; HANDLE fhandle; char directory[256]; /* unsicher, besser wäre - falls vorhanden - snprintf() */ sprintf(directory,"%s\*.*",path); /* Handle auf das Verzeichnis directory */ if ((fhandle=FindFirstFile(directory,&dir)) != INVALID_HANDLE_VALUE) { do { /* Verzeichnis auslesen */ printf("%s\n", dir.cFileName); } while(FindNextFile(fhandle,&dir)); } FindClose(fhandle); } #endif int main(int argc,char *argv[]) { if (argc < 2) list_dir("."); else list_dir(argv[1]); return EXIT_SUCCESS; } Bei der Win32-Funktion wurden hier die MS-DOS-ähnlichen Funktionen findfirst() und findnext() verwendet. Die Funktion FindFirstFile() gibt ein Filehandle auf die erste Datei im Verzeichnis zurück, während FindNextFile() das Handle immer um eine Position weitersetzt, bis keine Dateien mehr im Verzeichnis zum Lesen vorhanden sind. FindClose() schlieÃt das Filehandle wieder. # 18.2 Die Argumentliste am Anfang oder Ende kennzeichnen ## 18.2 Die Argumentliste am Anfang oder Ende kennzeichnen Diese vier Makros werden Sie jetzt anwenden. Es soll eine Funktion geschrieben werden, die eine variable Anzahl von Argumenten erhält. Die Argumente (Ganzzahlen) werden dabei alle zu einer Summe addiert. Hier sehen Sie das Listing: > /* vargs1.c */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> int add(int zahlen, ...) { va_list zeiger; int zahl; va_start(zeiger,zahlen); do { zahl = va_arg(zeiger,int); zahlen += zahl; } while(zahl != 0); va_end(zeiger); return zahlen; } int main(void) { int erg; printf("%d\n",add(11,12,13,0)); printf("%d\n",add(99,66,33,22,11,0)); erg = add(10, 13, 11, 0) + add(9, 8, 11, 0); printf("%d\n",erg); return EXIT_SUCCESS; } Der Aufruf der Funktion erfolgt mit: > printf("%d\n",add(11,12,13,0)); Hier wird die Funktion add() mit den Argumenten 11, 12, 13 und 0 aufgerufen. Die Zahl 0 am Ende stellt die Abbruchbedingung dar. Zunächst wird der Argumentzeiger angelegt, mit dem die Liste der optionalen Argumente durchlaufen wird: > va_list zeiger; Der Argumentzeiger erhält jetzt mithilfe des Makros va_start() die Position des ersten optionalen Arguments: > va_start(zeiger,zahlen); Ohne diesen Aufruf wäre kein Zugriff auf die weiteren optionalen Argumente möglich. Man könnte auch sagen, der Datentyp zeiger verweist auf die Anfangsadresse der ersten Zahl in der Argumentliste. AnschlieÃend wird in der do while-Schleife der Wert zurückgeliefert, auf den der Argumentzeiger gerade verweist. > zahl=va_arg(zeiger,int); In diesem Beispiel ist dies die Zahl 12. Diese Zahl wird zu dem ersten Wert von zahlen (11) addiert. AuÃerdem wird nach dem Aufruf von va_arg() der Argumentzeiger auf das nachfolgende Argument gesetzt. Ist die Bedingung der Schleife wahr (zahl != 0), fährt das Programm mit zahl=va_arg(zeiger,int), genauer gesagt dem nächsten Wert (13), fort und addiert diesen wieder mit zahlen. Beim nächsten Durchgang ist die while-Bedingung unwahr (zahl==0), und die Liste wird beendet mit: > va_end(zeiger); Anhand des ersten Funktionsaufrufs können Sie sich dies grafisch so vorstellen: Abbildung 18.1 Zugriff einzelner Werte bei einer variablen Argumentliste Jetzt soll das Programm so umgeschrieben werden, dass mit einer bestimmten Anzahl von Argumenten gearbeitet wird: > /* vargs2.c */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> void print_zahlen(int anzahl, ...) { va_list zeiger; int zahl; int i; printf("Es werden %d Zahlen ausgegeben\n",anzahl); va_start(zeiger,anzahl); for(i = 1; i <= anzahl; i++) { zahl=va_arg(zeiger,int); printf("%d\t",zahl); } printf("\n"); va_end(zeiger); } int main(void) { print_zahlen(4,3,2,4,7); print_zahlen(6,11,22,33,44,55,66); return EXIT_SUCCESS; } Das Programm ist ähnlich aufgebaut wie im Beispiel zuvor, nur dass hier als Abbruchbedingung das erste Argument verwendet wurde. In dem Funktionsaufruf > print_zahlen(6, 11, 22, 33, 44, 55, 66); wird durch das erste Argument gekennzeichnet, dass die Funktion mit 6 Argumenten vom Typ int aufgerufen wird. Dies ist auch die Abbruchbedingung für die for-Schleife in der Funktion print_zahlen(). Diese Makros sind natürlich noch deutlich vielseitiger, als Beispiel sei die Funktion strcat() zum Anhängen eines Strings an einen anderen genannt. Häufig würden Sie sicherlich gern mehrere Strings auf einmal an einen anderen hängen. Dabei mussten Sie bislang immer mehrere strcat()-Aufrufe ausführen. Mit dem eben gezeigten Beispiel kann dies jetzt in einem Schritt realisiert werden: > strxcat(3, string, string1, string2); Hiermit werden die beiden Strings string1 und string2 an den String string gehängt. Die Anzahl der Strings wird am Anfang der Argumentliste gekennzeichnet. Hierzu das Listing: > /* strxcat.c */ #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #define MAX 50 void strxcat(int n_strings, ...) { va_list zeiger; char *quelle, *ziel, *p; va_start(zeiger,n_strings); /* nun auf den Zielstring */ ziel = va_arg(zeiger,char *); p = ziel; /* am Ende vom Zielstring */ ziel+=strlen(ziel); if( (ziel-p) > MAX) { printf("!!!Maximale Anzahl an Zeichen ueberschritten!!!\n"); return; } while(--n_strings > 0) { /* Quelle einlesen */ quelle = va_arg(zeiger, char *); /* jetzt Zeichen für Zeichen an ziel */ while(*quelle) { *ziel++ = *quelle++; if( (ziel-p) > MAX) { printf("!Maximale Anzahl an Zeichen ueberschritten!\n"); exit(EXIT_FAILURE); } } } *ziel = '\0'; } int main(void) { char string[MAX] = "Test : "; char string2[] = " Und"; strxcat(3, string, "hallo " , "welt"); printf("%s\n",string); strxcat(5, string, string2, " noch", " ein", " Test"); printf("%s\n",string); /*Und nun ein Fehler mit Absicht*/ strxcat(4, string , " Ueberlauf", " von", " MAX"); printf("%s\n",string); return EXIT_SUCCESS; } Abbildung 18.2 Mehrere Strings auf einmal aneinanderhängen Hier wurde auch eine Sicherung eingebaut, um sich vor sogenannten Pufferüberläufen zu schützen. # 18.3 »vprintf()«, »vsprintf()«, »vfsprintf()« und »vsnsprintf()« ## 18.3 »vprintf()«, »vsprintf()«, »vfsprintf()« und »vsnsprintf()« Mit dem Makro va_arg werden die variablen Parameter einzeln verarbeitet. Mit den beiden Funktionen vprintf() und vfprintf() kann die ganze Liste in einem Stück übernommen werden. Dazu wird der Makroname va_arg nicht mehr benötigt. Hier sehen Sie die Syntax von vprintf(): > #include <stdio.h> #include <stdarg.h> int vprintf(const char * restrict format, va_list artPtr); Jetzt soll hiermit die Funktion printf() nachgebildet werden. Der Code sieht so aus: > /* my_printf.c */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> static void myprintf(char *string, ...) { va_list argzeiger; va_start(argzeiger,string); vprintf(string,argzeiger); va_end(argzeiger); } int main(void) { char hallo[] = "Hallo vprintf\n"; myprintf("Hier ein Beispiel von vprintf...."); myprintf("\n"); myprintf("%d * %d = %d\n",10,10,10*10); myprintf("%s",hallo); return EXIT_SUCCESS; } Der einzige Unterschied zu den vorigen Beispielen ist, dass hier anstatt va_arg() die Funktion vprintf() benutzt wird. Diese Funktion übernimmt den ganzen String in einem Stück. Natürlich macht dieses Programm wenig Sinn. vprintf() eignet sich sehr gut, um eigene Fehlermeldungsroutinen zu schreiben. Ein Beispiel: > /* error_handling.c */ #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #define MAXWERT 8192 enum{ WARN, ERROR, EXIT, MISC }; /* Stringtabelle mit Fehlerausgaben */ const char *error[] = { "Fehlerhafte Eingabe\n", "Maximaler Wertebereich ueberschritten\n", "Nagativer Wert wurde eingegeben\n" }; void fehler(int kennung, const char *format, ...) { va_list vargzeiger; va_start(vargzeiger,format); switch(kennung) { case 0 : printf("\nAchtung: "); vprintf(format,vargzeiger); break; case 1 : printf("\nFehler : "); vprintf(format,vargzeiger); break; case 2 : printf("\nProgrammabbruch : "); vprintf(format,vargzeiger); exit(EXIT_FAILURE); case 3 : vprintf(format,vargzeiger); break; default : printf("\nFalscher Funktionsaufruf\n"); } va_end(vargzeiger); } int main(void) { int zahl, ret; printf("Eine Zahl zwischen 0-8192: "); ret=scanf("%d",&zahl); /* fehlerhafte Eingabe vorgenommen */ if(ret == 0) fehler(EXIT, error[0]); /* Zahl gröÃer als Maximalwert */ else if(zahl > MAXWERT) fehler(WARN, error[1]); /* negative Zahl */ else if(zahl < 0) fehler(ERROR, error[2]); /* alles in bester Ordnung */ else fehler(MISC, "Eingabe ist in Ordnung\n"); return EXIT_SUCCESS; } Damit kann jederzeit mit dem Funktionsaufruf > fehler(kennungsnummer,"Fehler - Unbekannter Fehler"); eine bestimmte Fehlermeldung auf dem Bildschirm ausgegeben werden – je nachdem, welche Kennungsnummer an die Funktion fehler() übergeben wurde. In diesem Beispiel wurden die Fehlernummern in enum-Variablen gekleidet und die entsprechende Fehlerausgabe in eine Stringtabelle. Das dateiorientierte Gegenstück zu vprintf() ist die Funktion vfprintf() mit folgender Syntax: > #include <stdio.h> #include <stdarg.h> int vfprintf( FILE * restrict f, const char * restrict puffer, va_list argPtr); Diese Funktion ist gleichbedeutend mit der Funktion vprintf(), nur dass Sie dabei noch formatiert in einen Stream oder aber auch auf die Standardausgabe schreiben können mit: > vfprintf(stdout, format, vargzeiger); // gleichwertig zu ... vprintf(format, vargzeiger); Zudem existiert noch die Funktion vsprintf(), die ähnlich wie sprintf() funktioniert. Ihre Syntax lautet: > #include <stdio.h> #include <stdarg.h> int vsprintf( const char * restrict puffer, const char * restrict format, va_list argPtr); Damit kann eine variabel lange Argumentliste formatiert in einen String geschrieben werden. Hier sehen Sie ein kurzes Beispiel: > /* vsprintf.c */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> /* Bei Linux die Bibliothek math.h extra hinzulinken (-lm) * gcc -o programm programm.c -lm */ #include <math.h> static void float2string(char *string, char *dezimal, ...) { va_list argzeiger; va_start(argzeiger,dezimal); vsprintf(string,dezimal,argzeiger); va_end(argzeiger); } int main(void) { char string[100]; float zahl = 20.0; float2string(&string[0],"string-> %.6f <-string",sqrt(zahl)); printf("%s\n",string); return EXIT_SUCCESS; } Ab dem C99-Standard ist mit vsnprintf() auch die snprintf()-Alternative mit einer variablen Argumentliste neu hinzugekommen. Die Syntax dieser Funktion sieht so aus: > #include <stdio.h> #include <stdarg.h> int vsnprintf( const char * restrict puffer, size_t n const char * restrict format, va_list argPtr ); Zwar wurden die Funktionen vprintf(), vfprintf(), vsprintf() und vsnsprintf() recht kurz abgehandelt, aber im Grunde arbeiten all diese Funktionen auf die gleiche Art und Weise wie ihre Gegenstücke printf(), fprintf(), sprintf() und snprintf(), nur dass der letzte Parameter immer ein Argumentzeiger vom Typ va_list ist, womit zusätzlich zur bereits vorhandenen Funktion der Gegenstücke auch noch optionale Argumente möglich sind. Um die Argumentliste verwenden zu können, muss diese immer zuerst mit va_start() initialisiert und am Ende mit va_end() beendet werden. va_arg() wird hier nicht benötigt, weil dieses Makro intern von den Funktionen verwendet wird. # 18.4 Variadic Makros – __VA_ARGS__ ## 18.4 Variadic Makros – __VA_ARGS__ Ab dem C99-Standard haben Sie die Möglichkeit, ein Makro mit variablen Argumenten zu definieren und aufzurufen. Zugegeben, dieser Abschnitt hätte auch gut zu Kapitel 10, »Präprozessor-Direktiven«, gepasst, aber ich habe mich dann doch entschieden, dieses Thema hier aufzunehmen. Das Prinzip ist denkbar einfach. Beim Aufruf eines Makros fasst der Präprozessor alle optionalen Argumente zu einem Argument zusammen. Hierzu wurde der Bezeichner __VA_ARGS__ eingeführt, der im Ersatztext die zusammengefassten optionalen Argumente enthält. Allerdings darf der Bezeichner __VA_ARGS__ nur im Ersatztext der Makrodefinition verwendet werden. __VA_ARGS__ kann dort wie fast ein gewöhnlicher Parameter verwendet werden. Der Unterschied ist, dass der Parameter durch sämtliche Argumente ersetzt wird und nicht nur durch ein Argument. Hier folgt ein einfaches Beispiel dafür, wie Sie ein Makro erstellen können, das eine variable Anzahl von Argumenten verwendet: > /* variadic1.c */ #include <stdio.h> #include <stdlib.h> #define errprintf(...) fprintf(stderr, __VA_ARGS__) int main(void) { const char str[] = "ein Argument"; int val = 10; errprintf("Hallo Welt %d %s\n", val, str); errprintf("Fehler!! Zeile: %d (%s)\n", __LINE__, __DATE__ ); return EXIT_SUCCESS; } Das Prinzip ist recht einfach. Der Makroaufruf > errprintf("Hallo Welt %d %s\n", val, str); sieht nach dem Ersetzen des Textes in __VA_ARGS__ wie folgt aus: > fprintf(stderr, "Hallo Welt %d %s\n", val, str); Anstatt die Ausgabe auf den Standard-Stream stderr auszugeben, können Sie selbstverständlich auch eine Datei dafür verwenden – vorausgesetzt natürlich, Sie haben eine entsprechende Datei mit FILE-Zeiger zum Schreiben geöffnet. Dies ist ein eleganter und einfacher Weg, um ein Programm mitzuprotokollieren, indem bestimmte Dinge in einer Logdatei geschrieben werden. Hierzu ein weiteres Beispiel, das noch einige Möglichkeiten demonstrieren soll, ein Makro mit variablen Argumenten zu nutzen: > /* variadic2.c */ #include <stdio.h> #include <stdlib.h> #define fprintf_log(...) fprintf(fp, __VA_ARGS__) #define errprintf(...) fprintf(stderr, __VA_ARGS__) #define checkerror(x, ...) if(!(x)) { \ fprintf(stderr, __VA_ARGS__); } #define LOGFILE "logfile.txt" static FILE *fp; void openLog(void) { fp = fopen(LOGFILE, "w+"); if( NULL == fp ) { errprintf("%s:%d: Konnte Logdatei nicht oeffnen\n", __func__, __LINE__); exit(EXIT_FAILURE); } } int main(void) { char name[80]; int val, check; openLog(); fprintf_log("(%s/%s): Programmstart\n", __DATE__, __TIME__); printf("Bitte Namen eingeben: "); fgets( name, 80, stdin); // Die Eingabe wird mitprotokolliert. fprintf_log("Eingabe \"name\": %s", name); printf("Bitte eine Ganzzahl eingeben: "); check = scanf("%d", &val); // Wird nur ausgeführt, wenn die // Eingabe bei scanf() falsch war. checkerror(check, "Die Eingabe war falsch\n"); return EXIT_SUCCESS; } Mit dem ersten Makro > #define fprintf_log(...) fprintf(fp, __VA_ARGS__) können Sie eine variable Anzahl von Argumenten in den Stream fp schreiben – vorausgesetzt natürlich, der Stream fp wurde vorher zum Schreiben geöffnet, was in diesem Beispiel in der Funktion openLog() realisiert wurde. Mit fprintf_log() können Sie somit alles im Programm mitprotokollieren, was Ihnen sinnvoll erscheint. Ebenfalls recht praktisch ist das folgende Makro: > #define checkerror(x, ...) if(!(x)) { \ fprintf(stderr, __VA_ARGS__); } Hier wurde noch ein zusätzlicher Parameter verwendet, womit anschlieÃend mit if überprüft wird, ob das Makro überhaupt ausgeführt werden soll. In diesem Fall wird das Makro nur dann ausgeführt, wenn der zusätzliche Parameter x gleich 0 ist. Im Listing wurde dies bei der scanf()-Eingabe verwendet: > int check; check = scanf("%d", &val); checkerror(check, "Die Eingabe war falsch\n"); Wurde bei scanf() eine falsche Eingabe gemacht, beispielsweise ein Zeichen anstatt einer Ganzzahl eingegeben, ist der Wert von check gleich 0. Und beim Aufruf von checkerror() wird dieser scanf()-Rückgabewert als erster Parameter übergeben. Somit würde das Makro checkerror() im Falle eines Fehlers nach der Ersetzung wie folgt aussehen: > if(!(check)) { fprintf(stderr, "Die Eingabe war falsch\n"); } Im selben Verzeichnis wie das Listing variadic2.c finden Sie auÃerdem noch die Logdatei logfile.txt, die Sie nach Beendigung des Programms in einem Editor Ihrer Wahl betrachten können. # 19.2 Laufzeitmessung (Profiling) ## 19.2 Laufzeitmessung (Profiling) Für kleinere Programme können Sie eine Laufzeitmessung mit der Funktion clock() vornehmen. Für gröÃere und umfangreiche Projekte ist diese Funktion aber weniger geeignet. Bei solchen speziellen Fällen sollten Sie extra Programme einsetzen, die für diese geschrieben wurden – sogenannte Profiler. Ein Profiler ist ein eigenständiges Programm, das Sie zur Laufzeitanalyse verwenden können. Der Vorteil dieses Werkzeugs ist, dass Sie mit ihm auch einzelne Funktionen analysieren können. So lässt sich schnell herausfinden, welcher Teil des Quellcodes mehr Zeit als gewöhnlich beansprucht. Ein Profiler ist ebenfalls ein Standardwerkzeug für Codetuning-Freaks. Bei den kommerziellen Entwicklungsumgebungen ist der Profiler im Normalfall mit dabei. Es gibt aber auch einen kostenlosen Kommandozeilen-Profiler, den GNU-Profiler gprof, der für alle gängigen Systeme erhältlich ist. Es ist nicht die Aufgabe dieses Buchs, Ihnen die Werkzeuge der Programmierung näher zu erläutern, dennoch will ich kurz auf die Verwendung des Profilers gprof unter Einsatz des gcc-Compilers eingehen. Für andere Profiler lesen Sie bitte die jeweilige Dokumentation der Online-Hilfe. Als Erstes benötigen Sie einen fehlerfreien Quellcode, den Sie analysieren wollen. Dann müssen Sie den Quellcode mit dem Compiler-Flag -pg übersetzen: > gcc -pg programmname.c Jetzt befindet sich im Verzeichnis eine Datei namens a.out (unter Windows/MS-DOS auch a.exe). Diese Datei ist die ausführbare Datei für Ihren Quellcode. Starten Sie jetzt das ausführbare Programm a.out. Nun werden die Profiling-Informationen in die Datei gmon.out geschrieben, die sich jetzt ebenfalls im Verzeichnis befindet. Nach Programmende können Sie gprof zur Auswertung der Datei gmon.out aufrufen. Die Ausgabe, die häufig etwas länger ist, leiten Sie am besten in eine Datei um: > gprof ./a.out > test_prof.txt Die Textdatei test_prof.txt können Sie jetzt mit einem Editor Ihrer Wahl öffnen. Diese Datei beinhaltet wiederum zwei Dateien. Der erste Teil nennt * die verbrauchte Rechenzeit der Funktionen und * die Anzahl der Aufrufe von Funktionen. Im zweiten Teil sehen Sie, wie sich die Rechenzeit von Funktionen auf die von ihnen aufgerufenen Unterfunktionen verteilt. Mehr zum Werkzeug gprof erfahren Sie in der entsprechenden Dokumentation. # 20.2 <ctype.h> – Zeichenklassifizierung und Umwandlung ## 20.2 <ctype.h> – Zeichenklassifizierung und Umwandlung In der Headerdatei <ctype.h> befinden sich Funktionen, mit denen einzelne Zeichen überprüft oder umgewandelt werden können. Die Headerdatei <wchar.h> hingegen enthält die Deklarationen der Gegenstücke für Breitzeichen. In Tabelle 20.1 finden Sie die Syntax der einzelnen Funktionen und die Beschreibungen: Funktion in <ctype.h> | Funktion in <wctype.h> | Beschreibung | | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Alle Funktionen in der Tabelle erwarten ein int- bzw. wint_t-Argument, dessen Wert als EOF (bzw. WEOF) oder unsigned char bzw. wchar_t darstellbar sein muss. Bei Erfolg geben diese Funktionen einen Wert ungleich 0 zurück. Tritt ein Fehler auf, ist der Rückgabewert immer 0. In der Headerdatei <wctype.h> sind auÃerdem noch zwei erweiterbare Funktionen vorhanden, um breite Zeichen zu überprüfen. Die Syntax dieser Funktionen lautet: > int iswctype(wint_t wc, wctype_t desc); wctype_t wctype(const char *property); Mit diesen Funktionen können Sie mindestens dieselben Tests wie in Tabelle 20.1 durchführen. Hierbei müssen Sie lediglich für property das Präfix isw weglassen. Somit ist eine Ãberprüfung für ein Breitzeichen wc gleichwertig mit den Tests im Kommentar dahinter: > iswctype(wc, wctype("alnum")) // iswalnum(wc) iswctype(wc, wctype("alpha")) // iswalpha(wc) iswctype(wc, wctype("blank")) // iswblank(wc) iswctype(wc, wctype("cntrl")) // iswcntrl(wc) iswctype(wc, wctype("digit")) // iswdigit(wc) iswctype(wc, wctype("graph")) // iswgraph(wc) iswctype(wc, wctype("lower")) // iswlower(wc) iswctype(wc, wctype("print")) // iswprint(wc) iswctype(wc, wctype("punct")) // iswpunct(wc) iswctype(wc, wctype("space")) // iswspace(wc) iswctype(wc, wctype("upper")) // iswupper(wc) iswctype(wc, wctype("xdigit")) // iswxdigit(wc) Der Vorteil dieser Implementierung liegt auf der Hand. Es ist ohne gröÃeren Aufwand möglich, zusätzliche Strings für property zu definieren, die für bestimmte locale-spezifische Zeichen nötig sind. So, wie es Funktionen für die Klassifizierung von breiten Zeichen gibt, existieren auch Funktionen für die Umwandlung von Breitzeichen. Die Syntax dieser Funktionen lautet: > wint_t towctrans(wint_t wc, wctrans_t desc); wctrans_t wctrans(const char *property); Hierbei können Sie für property die Strings tolower und toupper verwenden. Somit ist eine Umwandlung für ein Breitzeichen wc gleichwertig mit der Umwandlung im Kommentar dahinter: > towctrans(wc, wctrans("tolower")) // towlower(wc) towctrans(wc, wctrans("toupper")) // towupper(wc) Zur Demonstration der einzelnen Funktionen folgt jetzt ein Listing, das normale byte-orientierte Zeichen verwendet: > /* big_small.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> /* Prototypen */ void grosschrift(char *, char *); void kleinschrift(char *, char *); void international(char *,char *); void oeffne_dateien(char *, char *, FILE **, FILE **); void grosschrift(char *arg2, char *arg3) { FILE *in,*out; int c; oeffne_dateien(arg2,arg3,&in,&out); while((c=getc(in)) != EOF) { if(islower(c)) putc(toupper(c),out); else putc(c,out); } } void kleinschrift(char *arg2, char *arg3) { FILE *in,*out; int c; oeffne_dateien(arg2,arg3,&in,&out); while((c=getc(in)) != EOF) { if(isupper(c)) putc(tolower(c),out); else putc(c,out); } } void international(char *arg2, char *arg3) { FILE *in,*out; int c; oeffne_dateien(arg2,arg3,&in,&out); while((c=getc(in)) != EOF) { if(isascii(c)==0) putc(toascii(c),out); else putc(c,out); } } void oeffne_dateien(char *quelle, char *ziel, FILE **input, FILE **output) { if((*input=fopen(quelle,"r+")) == NULL) { printf("Fehler beim Oeffnen (Lesen) von %s\n", quelle); exit(EXIT_FAILURE); } if((*output=fopen(ziel,"w+")) == NULL) { printf("Fehler beim Oeffnen (Schreiben) von %s\n", ziel); exit(EXIT_FAILURE); } } int main(int argc, char *argv[]) { if(argc<4) { printf("Verwendung: " "Programmname -[Schalter] datei.txt Zieldatei.txt\n" "für -[Schalter] : -b (komplette Textdatei in Grossschrift)\n" " -s (komplette Textdatei in Kleinschrift)\n" " -i (nationale Zeichen zu ASCII-Zeichen\n"); return EXIT_FAILURE; } if(strcmp(argv[1],"-b")==0) grosschrift(argv[2],argv[3]); else if(strcmp(argv[1],"-s")==0) kleinschrift(argv[2],argv[3]); else if(strcmp(argv[1],"-i")==0) international(argv[2],argv[3]); else { printf("Verwendung: " "Programmname -[Schalter] datei.txtZieldatei.txt\n" "für -[Schalter] : -b (komplette Textdatei in Grossschrift)\n" " -s (komplette Textdatei in Kleinschrift)\n" " -i (nationale Zeichen zu ASCII-Zeichen\n"); return EXIT_SUCCESS; } return EXIT_SUCCESS; } Mit diesem Code können Sie bei einer Textdatei jeden Buchstaben in einen groÃen, einen kleinen oder ein ASCII-Zeichen umwandeln. # 20.3 Mathematische Funktionen – <math.h>, <tgmath.h> und <complex.h## 20.3 Mathematische Funktionen – <math.h>, <tgmath.h> und <complex.hDie Standard-Bibliothek beinhaltet mittlerweile eine gewaltige Sammlung von mathematischen Funktionen. Die meisten dieser Funktionen sind in der Headerdatei <math.h> deklariert. Die meisten dieser Funktionen sind für Gleitpunktzahlen und zum Teil auch für komplexe Gleitpunkttypen (aus der Headerdatei <complex.h>) geeignet. Zwar bietet die Standard-Bibliothek auch einige Funktionen für ganzzahlige Typen, diese sind aber alle vorwiegend in der Headerdatei <stdlib.h> bzw. für den Typ intmax_t in <inttypes.h> deklariert. Des Weiteren sind in der Headerdatei <tgmath.h> typengenerische Makros definiert, mit denen es möglich ist, mathematische Funktionen mit einem einheitlichen Namen, unabhängig vom Typ der Argumente, aufzurufen. Um mit den anschlieÃenden Tabellen nicht den Rahmen des Buches zu sprengen, werden zur besseren Ãbersicht nur die Funktionen für die Gleitpunkttypen double und double _Complex aufgelistet. Zu jeder dieser Funktionen gibt es auch eine Version mit float bzw. float _Complex und eine Version für long double bzw. long double _Complex. Die Versionen von float bzw. float _Complex haben das Suffix f am Ende des Funktionsnamens, und die Versionen für long double bzw. long double _Complex haben das Suffix l am Ende. Sofern Sie allerdings die Headerdatei <tgmath.h> verwenden, können Sie dies auÃer Acht lassen. Mehr dazu erfahren Sie in Abschnitt 20.3.4. Wenn ich beispielsweise die Funktion zum Ziehen der Quadratwurzel für reelle Zahlen wie folgt aufliste: > double sqrt(double zahl); dann existieren von dieser Funktion noch die Versionen: > float sqrtf(float zahl); long double sqrtl(long double zahl); Gleiches gilt auch für die aufgelistete komplexe Gleitpunkttyp-Version, nur dass diese Funktionen noch zusätzlich mit dem Präfix c beginnen: ``` double complex csqrt(double complex z); ``` Auch von dieser Version gibt es noch zwei weitere Versionen: > float complex csqrtf(float complex z); long double complex csqrtl(long double complex z); Hinweis für Linux-User | | --- | | ### 20.3.1 Funktionen für reelle und komplexe Gleitpunkttypen In Tabelle 20.2 finden Sie Funktionen aus der Headerdatei <complex.h> und <math.h>, die Sie für reelle und komplexe Gleitpunkttypen verwenden können. ### 20.3.2 Funktionen nur für reelle Gleitpunkttypen Die Funktionen in Tabelle 20.3 stehen nur für reelle Gleitpunkttypen zur Verfügung und sind in der Headerdatei <math.h> definiert. ### 20.3.3 Funktionen nur für komplexe Gleitpunkttypen Zum Schluss fehlt nur noch die Tabelle mit den mathematischen Funktionen aus der Headerdatei <complex.h>, die nur für komplexe Gleitpunkttypen vorhanden sind. Hierzu folgt ein einfaches Beispiel, das diese Funktionen in der Praxis demonstrieren soll. Da immer noch diverse Compiler den C99-Standard implementiert haben und somit komplexe Zahlen nicht verwenden können, habe ich hier das Makro zur Ãberprüfung auf den neueren C99-Standard verwendet. > /* mathematik1.c */ #include <stdio.h> #include <stdlib.h> /* bei Linux das Compiler-Flag -lm mit angeben */ #include <math.h> #if __STDC_VERSION__ >= 19901L #include <complex.h> #endif int main(void) { double i=5.5, pi; #if __STDC_VERSION__ >= 19901L double complex c; #endif // Berechnungen mit reellen Zahlen printf("Quadratwurzel von %f = %f\n",i,sqrt(i)); printf("Der Sinus von %f = %f\n",i,sin(i)); printf("Der Tangens von %f = %f\n",i,tan(i)); printf("Der Cosinus von %f = %f\n",i,cos(i)); #if __STDC_VERSION__ >= 19901L // Berechnung mit komplexen Zahlen pi = 4 * atan(1.0); c = cexp(I * pi); printf("%f + %f * i\n", creal(c), cimag(c)); #endif return EXIT_SUCCESS; } Sollte der double-Wert nicht mehr richtig darstellbar sein, geben all diese Funktionen die Konstante HUGE_VAL zurück, die ebenfalls in der Headerdatei <math.h> deklariert ist. Für die float- bzw. long double-Funktionen sind für die Makros HUGE_VALF und HUGE_VALL definiert. ### 20.3.4 Typengenerische Makros – <tgmath.hWollen Sie beispielsweise eine Funktion zum Ziehen der Quadratwurzel verwenden, so mussten Sie, abhängig vom Datentyp, zwischen sechs verschiedenen Varianten mit sqrtf(), sqrt(), sqrtl(), csqrtf(), csqrt() und csqrtl() unterscheiden. Mit den typengenerischen Makros in <tgmath.h> brauchen Sie sich darum keine Gedanken mehr machen. Hier müssen Sie lediglich die Funktionen der double- bzw. double complex-Variante kennen, und ein Aufruf von sqrt() führt automatisch die entsprechende Erweiterung aus. Rufen Sie beispielsweise sqrt() mit einem float complex-Argument aus, wird automatisch die Erweiterung csqrtf() ausgeführt. Hierzu folgt ein Beispiel, das diese typengenerischen Makros demonstrieren soll. In diesem Beispiel wird für alle reellen und komplexen Gleitpunkttypen die Funktion sqrt() zum Ziehen der Quadratwurzel aufgerufen, was ohne die typengenerischen Makros nicht möglich gewesen wäre (und bei Compilern, die den C99-Standard nicht vollständig unterstützen, auch nicht möglich ist). Hier sehen Sie das Listing: > /* mathematik2.c */ #include <stdio.h> #include <stdlib.h> /* bei Linux den Compiler-Flag -lm mit angeben */ #include <tgmath.h> int main(void) { float f = 1.1; double d=2.2; long double ld = 3.3; float complex fc = 1.0 + 2.0*I, fcval; double complex dc = 4.0 + 2.0*I, dcval; long double complex ldc = 8.0 + 9.0*I, ldcval; // Berechnungen mit reellen Zahlen printf("Quadratwurzel von %f = %f\n",f,sqrt(f)); printf("Quadratwurzel von %f = %f\n",d,sqrt(d)); printf("Quadradwurzel von %Lf = %Lf\n",ld,sqrt(ld)); fcval = sqrt(fc); printf("Quadratwurzel von %f + %fi = Lf\n", creal(fcval), cimag(fcval)); dcval = sqrt(dc); printf("Quadratwurzel von %f + %fi\n", creal(dcval), cimag(dcval)); ldcval = sqrt(ldc); printf("Quadratwurzel von %Lf + %Lfi\n", creal(ldcval), cimag(ldcval)); return EXIT_SUCCESS; } ### 20.3.5 Gleitpunktwerte klassifizieren Ein weiteres interessantes Feature sind Makros zur Bestimmung der Kategorie von Gleitpunktzahlen. Seit dem C99-Standard werden die Gleitpunktzahlen in folgende fünf Kategorieren unterteilt (Konstanten aus der Headerdatei <math.h>): Abfragen, in welche Kategorie eine bestimmte Gleitpunktzahl fällt, können Sie mit den folgenden Makros vornehmen: Intern werden alle diese Makros jedoch mithilfe des Makros fpclassify() ausgewertet. Selbstverständlich können Sie fpclassify() auch mithilfe der vordefinierten Konstanten wie folgt verwenden: > if ( fpclassify(x) == FP_NORMAL ) { /*  */ } // ... gleichwertig zu ... if( isnormal(x) ) { /* ... */ } ### 20.3.6 Makro zum Vergleichen von reellen Zahlen Makros zum Vergleichen von Gleitpunktzahlen sind nicht unbedingt nötig. In Abschnitt 5.9, »Numerische Gleitpunktprobleme«, haben Sie bereits erfahren, dass abgesehen von Gleichheit (==) alle Vergleiche von Gleitpunktzahlen möglich sind. Dennoch gibt es noch ein Problem, das hier nicht angesprochen wurde: Ist einer der Werte keine gültige Gleitpunktzahl, lassen sich die Operanden nicht miteinander vergleichen und es wird die Exception FE_INVALID ausgelöst. Wollen Sie vermeiden, dass diese Exception ausgelöst wird, müssen Sie die entsprechenden Makros aus der Headerdatei <math.h> verwenden. Die Makros führen einen stillen Vergleich der Operanden durch, womit keine Exception ausgelöst wird. Tabelle 20.7 zeigt die entsprechenden Makros und deren Bedeutung. ### 20.3.7 Zugriff auf die Gleitpunkt-Umgebung – <fenv.hIn der Headerdatei <fenv.h> (für Floating Environment = Gleitpunktumgebung) wurden zwei neue Typen, mehrere Makros und einige Funktionen zum Testen auf Fehlersituationen beim Rechnen mit Gleitpunktzahlen implementiert. Diese Umgebung enthält die Systemvariable fexcept_t, die von Gleitpunkt-Exceptions-Funktionen gesetzt werden kann, und die Variable fenv_t, die für den Kontrollmodus (beispielsweise des Rundungsverhaltens) verwendet wird. Die Headerdatei <fenv.h> ist erst seit dem C99-Standard vorhanden. Um mit dem Programm auf diese Gleitpunkt-Umgebung zuzugreifen, empfiehlt es sich, dies dem Compiler mit dem Pragma STDC FENV_ACCESS mitzuteilen: > // Compiler informieren, damit dieser // Optimierungen verhindert #pragma STDC FENV_ACCESS ON # Zugriff auf die Exception-Statusflags Für den Zugriff auf die Exception-Statusflags von Gleitpunktzahlen stehen Ihnen mehrere Funktionen zur Verfügung, die in Tabelle 20.8 aufgelistet sind. Zur genauen Identifizierung der Exception-Statusflags sind in der Headerdatei <fenv.h> folgende Exceptions als ganzzahlige Makros implementiert: Hierzu ein einfaches Beispiel, in dem wir zunächst alle Exception-Statusflags mit der Funktion fegetexceptflag() sichern. AnschlieÃend lösen wir mit Absicht mit einer Division durch 0 die Exception FE_DIVBYZERO aus, was die Ãberprüfung mit fetestexcept() auch bestätigt. AnschlieÃend stellen wir die zuvor gesicherte Gleitpunkt-Umgebung mit fesetexceptflag() wieder im Ursprungszustand her. Hier sehen Sie das Listing dazu (das natürlich nur bei C99-konformen Compilern läuft): > /* mathematik3.c */ #include <stdio.h> #include <stdlib.h> /* bei Linux den Compiler-Flag -lm mit angeben */ #include <math.h> #include <fenv.h> #pragma STDC FENV_ACCESS ON int main(void) { double d1=0, d2=1.0, dges; fexcept_t flagp; // Exception-Statusflags sichern fegetexceptflag(&flagp, FE_ALL_EXCEPT ); // mit Absicht eine Division durch 0 auslösen dges = d2 / d1; if( fetestexcept( FE_DIVBYZERO ) ) { printf("Exception ausgelöst: Divsion durch 0 !\n"); } // Exception-Statusflags wiederherstellen fesetexceptflag(&flagp, FE_ALL_EXCEPT); // Sollte jetzt nicht mehr ausgeführt werden. if( fetestexcept( FE_DIVBYZERO ) ) { printf("Exception ausgelöst: Divsion durch 0 !\n"); } return EXIT_SUCCESS; } # Rundungsmodus Neben den Exception-Statusflags können Sie auch das Rundungsverhalten der Gleitpunktarithmetik mit Funktionen und Makros der Headerdatei <fenv.h> einrichten. Hier sind die beiden dazu nötigen Funktionen: > // Gibt den aktuellen Rundungsmodus zurück, // gewöhnlich ist hier FE_TONEAREST eingestellt. int fegetround(void); // Setzt den Rundungsmodus auf round // Mögliche Modi dazu finden Sie in der Tabelle 20.10. int fesetround(int round); In der Headerdatei <fenv.h> sind die in Tabelle 20.10 aufgelisteten Makros definiert, die von fegetround() zurückgegeben bzw. mit fesetround() gesetzt werden können. Die Verwendung ist entsprechend einfach: > #include <fenv.h> ... int save; ... // Rundungsmodus sichern save = fegetround(); // neuen Rundungsmodus festlegen fesetround(FE_UPWARD); ... ... // Rundungsmodus wiederherstellen fesetround(save); # Zugriff auf die komplette Gleitpunktumgebung Es gibt auch noch Funktionen, mit denen Sie auf die komplette Gleitpunkt-Umgebung zugreifen können: > // Gleitpunkt-Umgebung speichern int fegetenv(fenv_t *envp); // Gleitpunkt-Umgebung in einen Non-Stop-Modus setzen. // Hierbei unterbricht eine Exception nicht die // Programmausführung. int feholdexcept(fenv_t *envp); // Gleitpunkt-Umgebung wiederherstellen int fesetenv(const fenv_t *envp); // eine gespeicherte Gleitpunkt-Umgebung wiederherstellen // und alle zur Laufzeit gesetzten Exceptions erneut auslösen int feupdateenv(const fenv_t *envp); # 20.4 <stdlib.h## 20.4 <stdlib.hIn der Headerdatei <stdlib.h> befinden sich auÃer den Funktionen zum Allozieren von Speicherplatz noch weitere nützliche Funktionen. ### 20.4.1 Programmbeendigung – »exit()«, »_exit()«, »atexit()« und »abort()« Zur normalen Beendigung eines Programms können Sie auÃer return folgende Funktion verwenden: > void exit(int status); Laut ANSI-C-Standard ist es egal, ob ein Programm mit der Funktion exit() oder return beendet wird – mit dem Unterschied, dass über exit()das Programm von einer beliebigen Position im Code aus beendet werden kann. Bei return gelingt dies nur in der main()-Funktion. Der Ablauf von exit() lässt sich so erklären: Bei Programmbeendigung mit exit() werden zuvor alle gefüllten Puffer geleert, alle geöffneten Dateien geschlossen und alle temporären Dateien gelöscht, die mit der Funktion tmpfile() angelegt wurden. AnschlieÃend wird die Routine _exit() aufgerufen, und das Programm beendet sich. Bei exit() gelten die gleichen Rückgabewerte wie beim Beenden der main()-Funktion mittels return. Ein Rückgabewert von 0 bedeutet, dass ein Programm ordentlich beendet wurde – ein Wert ungleich 0 hingegen sagt aus, dass etwas nicht ordnungsgemäà abgeschlossen wurde. Da dies, wie schon in Abschnitt 9.17 erwähnt wurde, nicht unbedingt so implementiert sein muss, sind Sie auch hier mit den Standard-C-Makros EXIT_SUCCESS (für eine erfolgreiche Beendigung) und EXIT_FAILURE (bei einem Fehler) als Parameter für exit()auf der sicheren Seite. Theoretisch kann die Funktion _exit auch gleich aufgerufen werden. Dies entspricht allerdings nicht dem ANSI-C-Standard. Hier sehen Sie die Syntax: > #include <unistd.h> /* unter Linux/UNIX */ #include <stdlib.h> /* unter MS-DOS */ void _exit(int status); Damit werden die oben genannten »Aufräumarbeiten« nicht vorgenommen. Eine weitere Funktion für Beendigungsroutinen in der Headerdatei <stdlib.h> ist die Funktion atexit(). Die Syntax sieht so aus: > #include <stdlib.h> int atexit(void (*funktion) (void)); Mit atexit() wird ein sogenannter Funktionshandler eingerichtet. Alle Funktionen, die in atexit() angegeben sind, werden in einer Funktionsliste eingetragen und bei Beendigung des Programms in umgekehrter Reihenfolge ausgeführt, also nach dem LIFO-Prinzip (Last In First Out). Laut ANSI C können insgesamt 32 solcher Funktionen verwendet werden. Hierzu ein Beispiel: > /* atexit1.c */ #include <stdio.h> #include <stdlib.h> void funktion1(void) { printf("Die Funktion funktion1 wurde aufgerufen\n"); } void funktion2(void) { printf("Die Funktion funktion2 wurde aufgerufen\n"); } int main(void) { atexit(funktion1); atexit(funktion2); printf("Wir beenden unser Programm\n"); exit(EXIT_FAILURE); printf("Dies wird nicht mehr ausgegeben\n"); return EXIT_SUCCESS; } Solch ein Beispiel macht natürlich wenig Sinn. Sie können atexit() beispielsweise verwenden, um Logdateien zu schreiben, etwa wenn der User das Programm beendet oder wenn ein Programm mit einem Fehler beendet wurde. Oder Sie können noch diverse Aufräumarbeiten durchführen, wie es im folgenden Beispiel geschieht: > /* atexit2.c */ #include <stdio.h> #include <stdlib.h> char *memPtr; void free_malloc(void) { /* Wurde überhaupt Speicher reserviert? */ if(memPtr == NULL) printf("Kein Speicher war reserviert!!!\n"); else { free(memPtr); printf("Speicher wurde freigegeben!!\n"); } } int main(void) { memPtr =(char *) malloc(10000); if(memPtr==NULL) printf("Konnte keinen Speicher reservieren\n"); if(atexit (free_malloc) != 0) printf("Konnte Funktionshandler nicht einrichten\n"); /* Nach vielen Zeilen Code beenden wir das Programm. */ printf("Ein Fehler - Programm wird beendet - \n"); exit(EXIT_FAILURE); printf("Wird nicht mehr ausgegeben\n"); return EXIT_SUCCESS; } Die nächste Funktion zur Beendigung (oder in diesem Fall besser gesagt zur abnormalen Beendigung eines Programms) ist die Funktion abort(). Die Syntax lautet: > #include <stdlib.h> void abort(void); Diese Funktion bewirkt – wie der Name schon sagt – eine abnormale Programmbeendigung. abort() schickt dem aufrufenden Prozess das Signal SIGABRT. Dieses Signal sollte niemals ignoriert werden. Hier ein Mini-Beispiel dazu: > /* abort.c */ #include <stdio.h> #include <stdlib.h> int main(void) { abort(); return EXIT_SUCCESS; } Das Programm wird mit folgender Fehlermeldung beendet: > Abnormal Programm termination Hier wurde die Fehlerausgabe über stderr realisiert. Im Gegensatz zur Funktion exit() gibt es bei der Funktion abort() keine Vorgaben, ob der Ausgabepuffer geleert oder die temporären Dateien automatisch gelöscht werden. Somit ist diese Funktion nicht für Programme geeignet, die auf mehreren Systemen laufen müssen. Ebenso werden nach einem abort()-Aufruf die Funktionen, die mit atexit() eingerichtet wurden, nicht mehr ausgeführt. POSIX.1 hingegen schreibt vor, dass zumindest alle noch offenen Standard-E/A-Streams mit fclose() ordentlich geschlossen werden müssen. ### 20.4.2 Strings in numerische Werte konvertieren Müssen Sie einen String in einen numerischen Wert konvertieren, gibt es hierfür in der Headerdatei <stdlib.h> gleich mehrere Funktionen. Einen String in einen int-Wert umwandeln können Sie mit folgender Funktion: > int atoi(char *string); Ein String kann in einen long int-Wert mit der Funktion > long int atol(char *string); umgewandelt werden, und soll ein double-Wert aus einem String werden, dann ist diese Funktion verfügbar: > double atof(char *string); Es soll ein Programm geschrieben werden, das z. B. folgende Eingabe von der Kommandozeile verarbeiten kann: > typen 5 5.55 A 255555 3E234 Die Ausgabe sollte dann so aussehen: Abbildung 20.1 Strings in numerische Werte konvertieren Hier sind der Quellcode und die Funktionen atof() und atol(): > /* string2val1.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <float.h> #include <limits.h> int main(int argc, char *argv[]) { if(argc==1) { printf("Keine Zahlen zum Auswerten vorhanden!\n"); return EXIT_FAILURE; } while(*++argv) { if(strchr(*argv,'.') || strchr(*argv,'e') || strchr(*argv,'E')) { if(((atof(*argv)) <= FLT_MAX)&& ((atof(*argv)) >= FLT_MIN)) { printf("\n%s ist ein float-Wert\n", *argv); printf("Maximaler float-Wert:%f\n", FLT_MAX); printf("Kleinster pos. float-Wert : %f\n" , FLT_MIN); } else if(((atof(*argv)) <= DBL_MAX)&& ((atof(*argv)) >= DBL_MIN)) { printf("\n%s ist ein double-Wert\n", *argv); printf("Max. double-Wert:%f\n", DBL_MAX); printf("Kleinster pos. double-Wert : %f\n", DBL_MIN); } } else if(((atol(*argv)) < SHRT_MAX)&& ((atol(*argv))>SHRT_MIN) && (atol(*argv) != 0)) { printf("\n%s ist ein short int-Wert\n",*argv); printf("Maximaler short int-Wert: %d\n",SHRT_MAX); printf("Kleinster short int-Wert: %d\n",SHRT_MIN); } else if(((atol(*argv)) < LONG_MAX) && ((atol(*argv)) > LONG_MIN) && (atol(*argv) != 0)) { printf("\n%s ist ein long-Wert\n",*argv); printf("Maximaler long-Wert : %ld\n",LONG_MAX); printf("Kleinster long-Wert : %ld\n",LONG_MIN); } else printf("\nUnbekannter Typ (%s)!\n",*argv); } return EXIT_SUCCESS; } Es wurde hier nicht auf alle Datentypen geprüft, und anderweitig ist das Programm auch nicht wasserdicht. Aber dies würde den Rahmen dieses Kapitels sprengen. Hier wurden auÃerdem die (ANSI-C-)Konstanten aus den Headerdateien <float.h> und <limits.h> verwendet, damit das Programm auch auf jedem System läuft – egal, welche Grenzen gesetzt sind. ### 20.4.3 Bessere Alternative – Strings in numerische Werte konvertieren Sicherlich ist Ihnen an der Methode (im Listing string2va1.c) mit atof() bzw. atol() aufgefallen, dass diese Funktionen recht unflexibel sind und vor allem das Manko haben, keinen Fehler bei der Eingabe feststellen zu können. Eine häufig gestellte Frage lautet nämlich, wie man prüfen könne, ob der richtige Datentyp eingegeben wurde. Und genau diese »bessere« Alternative stellt Ihnen die Standard-Bibliothek mit den Funktionen strtod() und strtol() zur Verfügung. Beide Funktionen sind ebenfalls in der Headerdatei <stdlib.h> enthalten. Zuerst die Funktion strtod(): > double strtod( const char * restrict string, char ** restrict endptr ); strtod() konvertiert einen String in einen double-Wert. strtod() bricht die Analyse beim ersten Zeichen ab, das nicht mehr als Teil eines double-Werts interpretiert werden kann. Solange der Parameter endptr nicht NULL ist, wird *endptr von strtod() auf das Zeichen innerhalb von string gesetzt, durch das die Analyse abgebrochen wurde (*endptr=&abbruch_zeichen). > long strtol( const char * restrict string, char ** restrict endptr, int basis ); strtol() konvertiert einen String in einen long-Wert. basis legt das Zahlensystem fest, in das die Zahl umgewandelt werden soll (Basis = 8 ist Oktalzahl, Basis = 16 (0–9, A–F) ist eine Hexadezimalzahl, Basis = 10 ist das Dezimalsystem). Für basis sind Werte von 2 bis 36 möglich. Für endptr können Sie den NULL-Zeiger angeben. Falls kein NULL-Zeiger angegeben wird, zeigt endptr auf den Rest des long-Werts (sollte einer übrig bleiben). Für diese Funktion gibt es auch den unsigned-Bruder mit derselben Bedeutung: > unsigned long strtoul(const char *string, char **end_ptr,int basis); Im Falle eines Fehlers liefern all diese Funktionen 0 zurück. Wird der Wertebereich des zu konvertierenden Typs unter- bzw. überschritten (bei long sind dies LONG_MIN bzw. LONG_MAX), wird errno auf ERANGE gesetzt. Somit können Sie, wenn der Rückgabewert der Funktionen nicht 0, der end_ptr gleich NULL und die Fehlervariable errno nicht ERANGE ist, mit ziemlicher Sicherheit davon ausgehen, dass die von Ihnen eingegebene Zahl richtig ist (eine 100 %ige Garantie gibt es aber nicht). Hier ein kurzes Beispiel, das den gleichwertigen Fall von atol() und strtol() demonstrieren soll: > /* string2val2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char string1[] = "256Vorrat"; char string2[]= "128Benoetigt"; long zahl1, zahl2; zahl1 = atol(string1); zahl2 = strtol(string2, NULL, 10); printf("zahl1: %ld; zahl2: %ld\n", zahl1, zahl2); return EXIT_SUCCESS; } Hierbei wird »korrekterweise« einmal die Zahl 256 und einmal 128 ausgegeben. Beide Funktionen konvertieren also bis zum ersten Zeichen, das nicht mehr zum Datentyp gehört. Was aber, wenn eine derartige Eingabe überprüft werden soll – denn eigentlich sind ja beide Strings keine »korrekten« Zahlen, sondern nur Strings, die eben Zahlen beinhalten bzw. die mit Zahlen beginnen. Eben hier ist atol() am Ende. Mit strtol() hingegen haben Sie hierbei noch den zweiten Parameter, der Ihnen dabei helfen wird. Daher soll hier ein Beispiel erstellt werden, das jeweils zweimal die Eingabe eines Strings erfordert und überprüft, ob es sich dabei um einen »echten« long-Wert handelt (strtol()), und noch eine Funktion hat, die überprüft, ob sich der String korrekt in einen double-Wert konvertieren lässt (mit strtod()). > /* check_input.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #define CHARS 20 void chomp(char *str) { size_t p=strlen(str); /* '\n' mit '\0' ueberschreiben */ str[p-1]='\0'; } void is_long(char *str) { static long val; char *stop_ptr = NULL; val = strtoul(str, &stop_ptr, 10); if(errno == ERANGE) { printf("Werteueber- bzw. unterlauf!!!\n"); exit(EXIT_FAILURE); } if(!val) { printf("Wert konnte nicht umgewandelt werden\n"); exit(EXIT_FAILURE); } if(*stop_ptr) { printf("Kein korrekter long-Wert: %s\n", str); printf("Fehler der Umwandlung ab Pos.: %s\n", stop_ptr); printf("Umgewandelt ---> %ld\n", val); } else printf("Yeah! Korrekter long-Wert : %ld\n", val); } void is_double(char *str) { static double val; char *stop_ptr = NULL; val = strtod(str, &stop_ptr); if(errno == ERANGE) { printf("Werteueber- bzw. unterlauf!!!\n"); exit(EXIT_FAILURE); } if(!val) { printf("Wert konnte nicht umgewandelt werden\n"); exit(EXIT_FAILURE); } if(*stop_ptr) { printf("Kein korrekter double-Wert: %s\n", str); printf("Fehler der Umwandlung ab Pos.: %s\n", stop_ptr); printf("Umgewandelt ---> %lf\n", val); } else printf("Yeah! Korrekter double-Wert : %lf\n", val); } int main(void) { char val[CHARS]; /* Testen eines long-Wertes */ printf("Bitte geben Sie einen long-Wert ein : "); fgets(val, CHARS, stdin); chomp(val); is_long(val); /* Gleiches nochmals mit einem double-Wert */ printf("Bitte geben Sie einen double-Wert ein : "); fgets(val, CHARS, stdin); chomp(val); is_double(val); return EXIT_SUCCESS; } Sofern Sie jetzt hierbei auf andere Typen wie beispielsweise int überprüfen wollen, müssen Sie dazu die Limit-Konstanten der Headerdatei <limits.h> (beispielsweise INT_MIN oder INT_MAX) verwenden und mit dem long-konvertieren Wert vergleichen. Eine häufige Frage lautet: Wo ist itoa(), oder wie kann ich einen Integerwert in einen String konvertieren? itoa() ist keine ANSI-C-Standardfunktion, und daher hängt es vom Compiler ab, ob diese Funktion vorhanden ist oder nicht. Sollten Sie aber portabel bleiben müssen, macht diese Funktion ohnehin keinen Sinn. Also basteln Sie sich diese Funktion selbst zusammen: > /* my_itoa.c */ #include <stdio.h> #include <stdlib.h> char *my_itoa(int wert, int laenge) { char *ret =(char *) malloc(laenge+1 * sizeof(char)); int i; for(i =0; i < laenge; i++) { ret[laenge-i-1] = (wert % 10) + 48; wert = wert / 10; } ret[laenge]='\0'; return ret; } int main(void) { printf("%s\n", my_itoa(1234,4)); printf("%s\n", my_itoa(5432,6)); return EXIT_SUCCESS; } Falls für die Länge zu viele Zahlen angegeben wurden, werden diese mit voranstehenden Nullen gefüllt. Da ich in diesem Kapitel nur auf die Funktionen zum Konvertieren zwischen Zahlen und Strings aus der Headerdatei <stdlib.h> eingegangen bin, es aber auch weitere Funktionen für breite Zeichen in <wchar.h> und ganzzahlige Typen maximaler Breite in <inttypes.h> gibt (siehe Anhang B), folgt hier eine Tabelle mit einem Ãberblick, mit welcher Funktion Sie am besten einen String in welchen Typ konvertieren. String zu... | <stdlib.h> | <inttypes.h> 1) | <wchar.h> 1) | | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ### 20.4.4 Zufallszahlen Die Funktion > int rand(void); liefert eine Pseudo-Zufallszahl im Bereich 0 bis RAND_MAX zurück, beispielsweise mit: > /* zufall1.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int zufallszahl, i; for(i = 0; i < 5; i++) printf("Die Zufallszahl lautet %d\n", zufallszahl=rand()); return EXIT_SUCCESS; } Bei Ausführung des Listings werden fünf verschiedene Zufallszahlen zwischen 0 und RAND_MAX ausgegeben. Aber spätestens, wenn das Programm jetzt ein zweites Mal gestartet wird, merken Sie, dass sich diese Zufallszahlen immer wiederholen. Das Problem an der Funktion rand() ist, dass diese immer denselben Startpunkt zur Berechnung der Zufallszahl benutzt. Anders dagegen die Funktion: > void srand(unsigned int startwert); Mit ihr kann der Startpunkt für die Zufallszahl selbst bestimmt werden. Ein Beispiel: > /* zufall2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int zufallszahl, i, startpunkt; printf("Geben Sie irgendeine Zahl ein : "); scanf("%d",&startpunkt); srand(startpunkt); for(i = 0; i < 5; i++) printf("Die Zufallszahl lautet %d\n", zufallszahl=rand()); return EXIT_SUCCESS; } Jetzt wollen Sie aber sicher nicht andauernd einen Startwert für den Zufallsgenerator eingeben. Zum einen ist dies umständlich, und zum anderen bekommen Sie wieder dieselbe Zahl zurück, sollte zweimal der gleiche Wert eingegeben werden. Was eignet sich also besser als die Funktion time() für den Startwert. Und wie gehen Sie vor, falls eine Zufallszahl im Bereich zwischen 1 und 10 benötigt wird? Hier eignet sich der Modulo-Operator bestens. Ein entsprechendes Beispiel wäre: > /* zufall3.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { int zufallszahl, i; srand(time(NULL)); for(i = 0; i < 5; i++) printf("Zufallszahl lautet %d\n", zufallszahl=rand()%10+1); return EXIT_SUCCESS; } Jetzt erhalten Sie schon etwas bessere Zufallszahlen im Bereich zwischen 1 und 10. ### 20.4.5 Absolutwerte, der Quotient und der Rest von Divisionen Um Absolutwerte von Ganzzahlen zu ermitteln, können zwei Funktionen verwendet werden: > long int labs(long int zahl); int abs(int zahl); So erhalten Sie den Absolutwert zum ganzzahligen Argument zahl: > /* absolut.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int zahl = 5; printf("%d\n", abs(zahl-20)); return EXIT_SUCCESS; } Werden der Quotient und der Rest einer Division benötigt, können folgende Funktionen verwendet werden: > div_t div(int zaehler, int nenner); ldiv_t ldiv(long int zaehler, long int nenner); div_t und ldiv_t sind Strukturtypen mit folgendem Inhalt: > typedef struct{ int quot; /* quotient */ int rem; /* remainder */ } div_t; ... bzw. ... > typedef struct{ long int quot; /* quotient */ long int rem; /* remainder */ } ldiv_t; Damit berechnen Sie zaehler/nenner. Der Rest des Werts steht in rem, falls die Rechnung ungenau ist, und der Quotient befindet sich in quot. Ein Beispiel: > /* division.c */ #include <stdio.h> #include <stdlib.h> int main(void) { div_t x = div(10,3); printf("10 div 3 = %d Rest %d\n", x.quot, x.rem); return EXIT_SUCCESS; } Diese Funktion macht im Prinzip nichts anderes, als Folgendes zu berechnen: > quot = zaehler / nenner; rem = zaehler % nenner; Neu ab dem C99-Standard sind auch die entsprechenden Gegenstücke imaxabs() und imaxdiv() für den Typ intmax_t. Beide Funktionen sind in der Headerdatei <inttypes.h> definiert und haben folgende Syntax: > #include <inttypes.h> intmax_t imaxabs(intmax_t j); imaxdiv_t imaxdiv(intmax_t numer, intmax_t denom); ### 20.4.6 Suchen und Sortieren – »qsort()« und »bsearch()« Mit der Funktion qsort() kann ein Array der Wahl nach beliebigen Kriterien sortiert werden. Die qsort()-Funktion basiert auf dem Quicksort-Algorithmus von <NAME>. Hier sehen Sie die Syntax von qsort() ausführlich dokumentiert: > void qsort( void *array, // Anfangsadresse des Vektors size_t n, // Anzahl der Elemente zum Sortieren size_t size, // GröÃe des Datentyps, der sortiert wird // Jetzt folgt die Vergleichsfunktion int (*vergleich_func)(const void*, const void*) ); Die Bedeutungen der einzelnen Parameter dürften klar sein – bis auf die Vergleichsfunktion. Diese müssen Sie selbst implementieren. Hierzu ein einfaches Beispiel mit der Funktion qsort(): > /* qsort.c */ #include <stdio.h> #include <stdlib.h> /* Vergleichsfunktion */ int cmp(const void *ptr1, const void *ptr2) { if( *(int *)ptr1 < *(int *)ptr2 ) return -1; else if( *(int *)ptr1 > *(int *)ptr2 ) return 1; else return 0; /* Beide Elemente sind gleich. */ } int main(void) { int wert[] = { 2, 5, 2, 7, 6, 4, 2 }; int i; printf("Daten vor dem Sortieren\n"); for(i = 0; i < sizeof(wert)/sizeof(int); i++) printf("%d\t", wert[i]); printf("\n"); /* jetzt sortieren mit qsort() */ qsort(wert, sizeof(wert)/sizeof(int), sizeof(int), cmp); printf("Daten nach dem Sortieren mit qsort()\n"); for(i = 0; i < sizeof(wert)/sizeof(int); i++) printf("%d\t", wert[i]); printf("\n"); return EXIT_SUCCESS; } Das Listing sortiert das unsortierte Integer-Feld wert; die Ausgabe des Programms bestätigt dies. Wollen Sie ein Element wieder in Ihrem sortierten Vektor finden, dann können Sie die Funktion bsearch() verwenden. bsearch steht für »binäre Suche« und sucht die Elemente, indem es mit der Suche im mittleren Bereich eines Arrays beginnt und je nach Resultat mit der Suche auf der linken oder rechten Hälfte fortfährt. Genaueres dazu erfahren Sie in Kapitel 22, »Algorithmen«. Wird ein entsprechendes Element gefunden, liefert diese Funktion die Adresse zurück. Wird kein entsprechendes Element gefunden, dann wird der NULL-Zeiger zurückgegeben. Hier folgt die Syntax: > void *bsearch( const void *key, // gesuchte Elemente const void *array, // Anfangsadresse der Tabelle zum Suchen size_t n, // Anzahl der Elemente size_t size, // ElementgröÃe // Jetzt folgt die Vergleichsfunktion int (*vergleich_func)(const void*, const void*) ); Die Syntax ist also der Funktion qsort() recht ähnlich. Zur Abwechslung soll aber hier nach einem String in einer Stringtabelle gesucht werden, die Sie zuvor noch mit qsort() sortieren. > /* bsearch.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* Anzahl der Strings */ #define MAX 5 /* Vergleichsfunktion für zwei Strings */ int cmp_str(const void *s1, const void *s2) { return (strcmp(*(char **)s1, *(char **)s2)); } int main(void) { char *daten[MAX], puffer[80], *ptr, *key_ptr, **key_ptrptr; int count; /* Wörter eingeben */ printf("Geben Sie %d Wörter ein\n", MAX); for (count = 0; count < MAX; count++) { printf("Wort %d: ", count+1); fgets(puffer, 80, stdin); /* Speicher für das Wort Nummer count reservieren */ daten[count] = (char *) malloc(strlen(puffer)+1); strcpy(daten[count], strtok(puffer,"\n") ); } /* die einzelnen Wörter sortieren */ qsort(daten, MAX, sizeof(daten[0]), cmp_str); /* sortierte Daten ausgeben */ for (count = 0; count < MAX; count++) printf("\nWort %d: %s", count+1, daten[count]); /* jetzt nach einem Wort suchen */ printf("\n\nNach welchem Wort wollen Sie suchen: "); fgets(puffer, 80, stdin); /* Zur Suche übergeben Sie zuerst den puffer an key, * danach benötigen Sie einen weiteren Zeiger, der * auf diesen Such-Schlüssel zeigt */ key_ptr = strtok(puffer, "\n"); key_ptrptr = &key_ptr; /* Der Zeiger ptr bekommt die Adresse des Suchergebnisses. */ ptr =(char *) bsearch(key_ptrptr, daten, MAX, sizeof(daten[0]), cmp_str); if(NULL == ptr) printf("Kein Ergebnis stimmt mit %s überein\n", puffer); else printf("%s wurde gefunden\n", puffer); return EXIT_SUCCESS; } ### 20.4.7 system() Um aus einem lauffähigen Programm ein anderes Programm zu starten, steht Ihnen die Funktion system() zur Verfügung. Die Syntax lautet: > #include <stdlib.h> int system(const char *kommandozeile); Beim Ausführen der Funktion system() übergeben Sie den String kommandozeile an den Kommandozeilenprozessor. Konnte der Aufruf erfolgreich ausgeführt werden, gibt die Funktion einen Wert ungleich 0 zurück, ansonsten –1. Für den String kommandozeile können Sie alles angeben, was auch in der Kommandozeile erlaubt ist. Um zu testen, ob auf Ihrem System der Kommandozeilenprozessor überhaupt zur Verfügung steht, müssen Sie die Funktion system() mit dem NULL-Zeiger aufrufen: > if(system(NULL) == 0) { // Kommandozeilenprozessor steht nicht zur Verfügung } else { // Kommandozeilenprozessor ist bereit } Wird dabei ein Wert ungleich null zurückgegeben, können Sie die Funktion system() ohne Bedenken verwenden. Zum Abschluss folgt ein einfaches Beispiel zur Funktion system(). Auf jedem System gibt es einen Kommandozeilenbefehl, mit dem sich das vollständige Verzeichnis auflisten lässt. Unter Linux/UNIX ist dies ls, und unter Windows/MS-DOS heiÃt das Kommando dir. Im folgenden Listing soll dieses Kommando auf dem jeweiligen System mithilfe der Funktion system() ausgeführt werden. > /* list_dir.c */ #include <stdio.h> #include <stdlib.h> #ifdef __unix__ #define KOMMANDO system("ls -C") #else #define KOMMANDO system("dir /w") #endif int main(void) { if( system(NULL) == 0) { fprintf(stderr,"Kein Kommandozeilenprozessor vorhanden \n"); return EXIT_FAILURE; } else KOMMANDO; return EXIT_SUCCESS; } Nicht besprochen in diesem Abschnitt wurde die Funktion der Headerdatei <stdlib.h>, mit der Sie Multi-Byte-Zeichen bearbeiten können, da diese recht selten benötigt wird. Die Funktion getenv(), mit der Sie Umgebungsvariablen auslesen können, wird in Kapitel 23, »CGI mit C«, besprochen. # 20.5 <locale.h> – länderspezifische Eigenheiten ## 20.5 <locale.h> – länderspezifische Eigenheiten In ANSI C sind auch Funktionen vorhanden, die länderspezifische Eigenheiten wie beispielsweise die Formatierung von Geldbeträgen beachten. Dabei handelt es sich um zwei Funktionen und mehrere Makros, die recht selten Beachtung finden. Wenn Sie ein Programm starten, werden die lokalen Aspekte zunächst nicht berücksichtigt und das Programm wird somit mit den Standard-Einstellungen der Umgebung gestartet. Die Funktion, mit der Sie ein Programm mit den lokalen Eigenheiten zur Laufzeit anpassen können, lautet: > #include <locale.h> char *setlocale( int kategorie, const char *name ); Manchmal will man nicht die kompletten lokalen Aspekte berücksichtigen, daher wurde die Kategorie (erstes Argument) folgendermaÃen aufgeteilt: Angabe für »name« | Bedeutung | | --- | --- | | | | | | | Hierzu folgt ein einfaches Beispiel, mit dem die lokale Umgebung ermittelt und anschlieÃend entsprechend dem Einsatzgebiet des Compilers verändert und zum Schluss wiederhergestellt wird. > /* my_setlocale.c */ #include <stdio.h> #include <locale.h> #define KOMMA 3.3223 int main(void) { char *local_save = setlocale(LC_ALL, NULL); char *local; printf("Lokale Umgebung: %s (Standard)\n", local_save); printf("Gleitpunkt: %f\n",KOMMA); local = setlocale( LC_ALL, ""); printf("Neue lokale Umgebung: %s\n", local); printf("Gleitpunkt: %f\n",KOMMA); printf("Standard-Umgebung wiederherstellen\n"); local = setlocale( LC_ALL, local_save); printf("Lokale Umgebung: %s (wiederhergestellt)\n", local); return 0; } Benötigen Sie auÃerdem Informationen für die Formatierung von numerischen Werten wie z. B. des Dezimalpunkts oder des Währungssymbols, steht Ihnen noch folgende Funktion zur Verfügung: > #include <locale.h> struct lconv *localeconv( void ); Die Funktion füllt eine Struktur namens lconv mit der aktuell gesetzten länderspezifischen Umgebung. Diese Struktur beinhaltet folgende Mitglieder: # 20.6 Nicht-lokale Sprünge – <setjmp.h## 20.6 Nicht-lokale Sprünge – <setjmp.hIn C sind Sprünge über Funktionsgrenzen hinweg nicht erlaubt. Das heiÃt genau: Funktionen werden immer an den direkten Ausrufer zurückgegeben. Wenn z. B. Funktion 1 die Funktion 2 aufruft, kehrt Funktion 2 immer zuerst zur Funktion 1 zurück – eben in der umgekehrten Reihenfolge wie die einzelnen Funktionen auf (genauer: unter) dem Stack abgelegt wurden. Erst dann kann Funktion 1 zu ihrem Aufrufer zurückkehren. Ein Beispiel: > /* call_func.c */ #include <stdio.h> #include <stdlib.h> void func1(void); void func2(void); void func3(void); void func4(void); void func1(void) { printf("Funktion 1 ist aufgerufen!\n"); func2(); } void func2(void) { printf("Funktion 2 ist aufgerufen!\n"); func3(); } void func3(void) { printf("Funktion 3 ist aufgerufen!\n"); func4(); } void func4(void) { printf("Funktion 4 ist aufgerufen!\n"); } int main(void) { func1(); return EXIT_SUCCESS; } Das Programm ruft in der main()-Funktion zuerst func1() auf, func1() ruft anschlieÃend func2() auf, func2() ruft danach func3() auf, und func3() ruft am Ende func4() auf. AnschlieÃend kehren die einzelnen Funktionen wieder in der Reihenfolge func3(), func2() und func1() zur main()-Funktion zurück. Was wäre jetzt, wenn in func2() eine Berechnung durchgeführt wird und der Wert dieser Berechnung nicht mehr dem entspricht, den der Nutzer sich versprochen hat? Trotzdem werden sinnloserweise noch func3() und func4() aufgerufen und ausgeführt. Die Frage lautet also: Wie kann man z. B. von func2() zur main()-Funktion zurückspringen, die Funktionen func3() und func4() auslassen und auch nicht mehr über func1() zur main()-Funktion zurückkehren? Abbildung 20.2 Rückkehr von Funktionen bei einem normalen Verlauf Dafür können Sie die Funktionen der Headerdatei <setjmp.h> verwenden. Hier sehen Sie die Syntax: > #include <setjmp.h> jmp_buf env; // primitiver Datentyp jmp_buf int setjmp(jmp_buf env); void longjmp(jmp_buf env, int wert); Der Datentyp jmp_buf env ist eine Art Puffer, der den mit setjmp(env) eingefrorenen Programmzustand enthält und den Sie mit der Funktion longjmp(env,1) wiederherstellen können. jmp_buf enthält zum Beispiel die CPU-Registerinhalte (CS, DS, SS und ES), den Stackpointer (SP), den Instruktionspointer (IP) usw. – alle Informationen eben, die erforderlich sind, um den gleichen Zustand wiederherzustellen, der vor dem Aufruf von setjmp() vorlag. Mit setjmp() werden, wie eben schon erwähnt, alle Informationen, die im Augenblick vorliegen, auf einen Stack gelegt. Der Aufruf von setjmp() lautet: > if(setjmp(env) == 0) Beim ersten Aufruf von setjmp() liefert die Funktion den Wert 0 zurück. Beim zweiten Aufruf durch longjmp(env) liefert die Funktion auf jeden Fall einen Wert ungleich 0 zurück. Mit der Funktion longjmp() kehren Sie dann an diese Programmstelle zurück, die Sie mit setjmp(env) auf dem Stack abgelegt haben. Dies geschieht mit folgendem Aufruf: > longjmp(env,1); Nochmals alles zusammengefasst: > ... jmp_buf programmzustand; ... if(setjmp(programmzustand) == 0) printf("Programmzustand auf den Stack gelegt\n"); else printf("Rücksprung mit longjmp erfolgt\n"); ... // viele, viele Funktionen später longjmp(programmzustand,1); Als Erstes legen Sie hier mit setjmp() den Programmzustand auf den Stack. AnschlieÃend, viele Funktionen später, wird mit longjmp() dieser Zustand wiederhergestellt und springt zurück zu setjmp(). Dieses Mal ist der Rückgabewert von setjmp() aber nicht mehr 0, und daher fährt das Programm hinter der else-Anweisung fort. Jetzt soll alles in einem Programm verwendet werden, ohne komplizierte Berechnungen oder Ãhnliches. Es wird einfach abgefragt, wie viele Funktionen ausgeführt werden sollen, und das Programm springt nach der gewünschten Anzahl der Funktionen mit einem Aufruf von longjmp() zur main()-Funktion zurück: > /* setjmp.c */ #include <stdio.h> #include <stdlib.h> #include <setjmp.h> void func1(int); void func2(int); void func3(int); void func4(void); jmp_buf env; static int zahl; void func1(int zahl) { printf("Funktion 1 ist aufgerufen!\n"); if(zahl == 1) longjmp(env, 1); func2(zahl); } void func2(int zahl) { printf("Funktion 2 ist aufgerufen!\n"); if(zahl == 2) longjmp(env, 2); func3(zahl); } void func3(int zahl) { printf("Funktion 3 ist aufgerufen!\n"); if(zahl == 3) longjmp(env, 3); func4(); } void func4(void) { printf("Funktion 4 ist aufgerufen!\n"); } int main(void) { printf("Wie viele Funktionen sollen ausgefuehrt werden : "); scanf("%d",&zahl); if(setjmp(env) == 0) func1(zahl); else printf("Ruecksprung durch longjmp von Funktion %d!\n",zahl); return EXIT_SUCCESS; } Die Funktionen setjmp() und longjmp() haben übrigens nichts mit der Anweisung goto gemeinsam. Es hat sich als recht nützlich erwiesen, setjmp() und longjmp() bei Fehlerbehandlungen einzusetzen. # 20.7 <signal.h## 20.7 <signal.hSignale sind nicht vorhersehbare Ereignisse, die zu einem nicht vorhersagbaren Zeitpunkt auftreten können, also asynchrone Ereignisse. Nach dem ANSI-C-Standard gibt es folgende Signale, die vorkommen können: Unter Linux gibt es deutlich mehr Signale (ca. 30). Mit dem Befehl > kill -l wird eine Liste der Signale unter Linux/UNIX ausgegeben. Tritt ein Signal auf, haben Sie folgende Möglichkeiten, darauf zu reagieren: * Eintragen einer selbst geschriebenen Funktion * Ignorieren des Signals (geht aber nicht mit SIGKILL) * Verwenden der voreingestellten Default-Funktion (Bei den ANSI-C-Signalen ist dies immer eine Beendigung des Programms.) Um auf die Signale zu reagieren, existiert ein sogenanntes Signalkonzept. Dabei richtet ein Prozess einen sogenannten Signalhandler ein. Dieser Signalhandler teilt – wenn das Signal auftritt – dem Systemkern mit, was er zu tun hat. Ein solcher Handler kann mit der Funktion signal() eingerichtet werden. Hier ihre Syntax: > #include <signal.h> void(*signal(int signr, void(*sighandler)(int)))(int); Einen solchen Prototyp zu lesen, ist fast unmöglich. Aus diesem Grund wurde die Funktion in der Headerdatei <signal.h> wie folgt vereinfacht: > typedef void (*__p_sig_fn_t)(int); __p_sig_fn_t signal(int, __p_sig_fn_t); Somit sieht der Prototyp folgendermaÃen aus: > signalfunktion *signal(int signalnummer, signalfunktion *sighandler); Mit dem Parameter signalnummer legen Sie die Nummer des Signals fest, für die ein Signalhandler eingerichtet werden soll. Dies ist dann eines der Signale, die Sie soeben in Tabelle 20.15 kennengelernt haben (bzw. unter Linux diejenigen, die mit kill -l aufgelistet wurden). Für den Parameter sighandler sind zwei Konstanten in der Headerdatei <signal.h> deklariert: SIG_DFL und SIG_IGN. Mit SIG_DFL wird die Default-Aktion ausgeführt, was meist die Beendigung des Prozesses bedeutet. Ein Beispiel: > signal(SIGINT, SIG_DFL); Falls Sie die Tastenkombination + drücken, wird die Default-Einstellung des Signals SIGINT ausgeführt. Und die Default-Einstellung schreibt vor, dass das Programm beendet wird. Als zweite Möglichkeit können Sie Folgendes eingeben: > signal(SIGINT, SIG_IGN); Drücken Sie jetzt die Tastenkombination + , passiert gar nichts. Das Signal SIGINT wird mit der Angabe von SIG_IGN ignoriert. Als dritte Möglichkeit können Sie das Signal SIGINT abfangen und die Adresse einer eigenen Funktion übergeben, die ausgeführt werden soll, wenn die Tastenkombination + betätigt wurde: > signal(SIGINT,funktionsaufruf); Jetzt wird es Zeit, dass Sie sich ansehen, wie die Funktion signal() in der Praxis eingesetzt wird: > /* signal1.c */ #include <stdio.h> #include <stdlib.h> #include <signal.h> void sigfunc(int sig) { int c; if(sig != SIGINT) return; else { printf("\nWollen Sie das Programm beenden (j/n) : "); c=getchar(); if(c == 'j') exit (EXIT_FAILURE); else return; } } int main(void) { int i; signal(SIGINT, sigfunc); while(1) { printf("Mit STRG+C beenden"); for(i = 0; i <= 48; i++) printf("\b"); } return EXIT_SUCCESS; } Mit der Anweisung > signal(SIGINT, sigfunc); wird ein Signalhandler für das Signal SIGINT eingerichtet, der beim Auftreten dieses Signals die Funktion sigfunc aufrufen soll. Ein einfaches Beispiel bietet auch das Erstellen einer eigenen kleinen Shell. Die einzelnen Shellbefehle werden in einer Endlosschleife abgearbeitet. Mit der Tastenkombination + lösen Sie dabei einen Neustart der Shell aus. Dieser Sprung (Neustart) wird mit den Funktionen der Headerdatei <setjmp.h> realisiert. Hier sehen Sie das Beispiel dazu: > /* a_simple_shell.c */ #include <stdio.h> #include <string.h> #include <signal.h> #include <setjmp.h> #include <stdlib.h> #define MAX 255 #define OK 0 jmp_buf restart; void ctrlc(int sig) { signal(sig, ctrlc); /* zurück zur Kommandozeile */ longjmp(restart, 1); return; } int main(void) { char *command; /* Installiere den Signalhandler. */ signal(SIGINT, ctrlc); if(setjmp(restart) != 0) printf("\n\nShell neu gestartet ...\n\n"); else printf("\n\nShell gestartet ...\n\n"); for (;;) { /* Hier können Sie machen, was Sie wollen. */ char puffer[MAX]; printf("$~> "); fgets(puffer, MAX, stdin); command = strtok(puffer, "\n"); if( strcmp(command, "test") == OK ) printf("Ihr Befehl lautete \"test\"\n"); else if( strcmp(command, "help") == OK ) printf("Brauchen Sie Hilfe?\n"); /* usw. eine Menge mehr Shellbefehle ... */ else if( strcmp(command, "exit") == OK ) exit (EXIT_SUCCESS); else { printf("\nUnbekannter Shellbefehl\n"); printf("Bekannte Befehle: test, help, exit\n\n"); } } return EXIT_SUCCESS; } Dies ist eine einfache Schnittstelle einer eigenen Shell. Logischerweise müssen Sie statt der Ausgabe von Texten Ihre selbst geschriebenen Funktionen implementieren. Hier sehen Sie ein weiteres Beispiel zu signal() mit dem Signal SIGABRT: > /* sigabort.c */ #include <stdio.h> #include <stdlib.h> #include <signal.h> void sigfunc(int sig) { if(sig == SIGABRT) printf("Demonstration von SIGABRT\n"); } int main(void) { signal(SIGABRT, sigfunc); abort(); return EXIT_SUCCESS; } Um zu testen, ob der Aufruf der Funktion signal() überhaupt erfolgreich war, befindet sich in der Headerdatei <signal.h> der Fehlercode SIG_ERR, der mit dem Wert –1 definiert ist. Wollen Sie also die Funktion signal() auf Fehler überprüfen, sollte dies so aussehen: > if( signal(SIGINT,sigfunc) == SIG_ERR) { /* Fehler beim Aufruf von signal */ Es ist auch möglich, mit der Funktion raise()ein Signal an ein ausführendes Programm zu senden. Die Syntax der Funktion lautet: > int raise(int signr); Damit können Sie ein Signal mit der signr an das Programm senden. Ein kurzes Beispiel: > /* raise_signal.c */ #include <stdio.h> #include <stdlib.h> #include <signal.h> void sigfunc(int sig) { if(sig == SIGINT) printf("SIGINT wurde ausgeloest\n"); } int main(void) { signal(SIGINT,sigfunc); printf("Mit ENTER SIGINT ausloesen\n"); getchar(); /* SIGINT auslösen */ raise(SIGINT); return EXIT_SUCCESS; } Unter Linux/UNIX verwendet man allerdings in der Praxis ein etwas anderes Signalkonzept, da die signal()-Funktion von ANSI C hier einige Schwächen besitzt. Mehr dazu können Sie wieder meinem Buch »Linux-UNIX-Programmierung« entnehmen, das Sie auch auf meiner Webseite zum Online-Lesen vorfinden. # 20.8 <string.h> – die »mem «-Funktionen zur Speichermanipulation ## 20.8 <string.h> – die »mem «-Funktionen zur Speichermanipulation Die meisten Stringfunktionen wurden bereits an früherer Stelle behandelt. Aber einige Funktionen habe ich Ihnen bislang noch vorenthalten. Mit den mem...-Funktionen in der Headerdatei <string.h> können Sie ganze Speicherblöcke kopieren, vergleichen, initialisieren und durchsuchen. ### 20.8.1 »memchr()« – Suche nach einzelnen Zeichen Die Syntax lautet: > void *memchr(const void *buffer, int c, size_t n); Diese Funktion sucht in den ersten n Bytes in buffer nach dem Zeichen c. Sollten Sie den ganzen String durchsuchen wollen, können Sie die Funktion strchr() verwenden. Tritt dabei ein Fehler auf oder wird das Zeichen nicht gefunden, gibt diese NULL zurück. Ein Beispiel: > /* memchr.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str[] = "Have a lot of fun"; char *p; char ch = 'l'; p = (char *) memchr(str, ch, 10); if(NULL == p) printf("%c kommt nicht in den ersten 10 Bytes vor\n", ch); else printf("%c gefunden an Pos. %d\n", ch, p-str); return EXIT_SUCCESS; } ### 20.8.2 »memcmp()« – bestimmte Anzahl von Bytes vergleichen Die Syntax lautet: > int memcmp( const void *s1, const void *s2, size_t n); Mit memcmp() werden die ersten n Bytes im Puffer s1 mit dem Puffer s2 lexikografisch verglichen. Der Rückgabewert ist derselbe wie schon bei strcmp(). Ist s1 gröÃer als s2, ist der Rückgabewert kleiner als 0. Ist s2 gröÃer als s1, ist die Rückgabe gröÃer als 0, und bei Gleichheit beider Speicherbereiche wird 0 zurückgegeben. > /* memcmp.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str1[] = "Have a lot of fun"; char str2[] = "Have more than a lot of fun"; int check, i; for(i = 4; i <= 10; i+=6) { check = memcmp( str1, str2, i); if(check == 0) printf("Vergleich %d Bytes: " "Beide Strings sind gleich\n", i); else printf("Die ersten %d Bytes sind " "unterschiedlich\n", i); } return EXIT_SUCCESS; } ### 20.8.3 »memcpy()« – bestimmte Anzahl von Bytes kopieren Die Syntax lautet: > void *memcpy(void *dest, const void *src, size_t n); Mit der Funktion memcpy() können Sie n Bytes aus dem Puffer src in den Puffer dest kopieren. Die Funktion gibt die Anfangsadresse von dest zurück. > /* memcpy.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str[] = "Ein Wort, das hier nicht hingehört: Mist!"; char replace[] = "M***"; char *ptr; ptr = strstr(str, "Mist"); memcpy(ptr, replace, strlen(replace)); printf("%s\n",str); return EXIT_SUCCESS; } ### 20.8.4 »memmove()« – bestimmte Anzahl von Bytes kopieren Die Syntax lautet: > void *memmove(void *dest, const void* src, size_t n); Die Funktion erfüllt denselben Zweck wie die Funktion memcpy() – mit einem einzigen, aber gravierenden Unterschied: memmove() stellt sicher, dass im Fall einer Ãberlappung der Speicherbereiche der Ãberlappungsbereich zuerst gelesen und dann überschrieben wird. Auch die Rückgabewerte sind bei memmove() dieselben wie bei memcpy(). > /* memmove.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str[21] = "1234567890"; /* Den kompletten String nehmen und * 10 Bytes weiter als Kopie ablegen */ memmove(str+10, str, sizeof(str)-1); printf("%s\n",str); return EXIT_SUCCESS; } ### 20.8.5 »memset()« – Speicherbereich mit bestimmten Zeichen auffüllen Die Syntax lautet: > void *memset(void *dest, int ch, unsigned int n); Mit dieser Funktion füllen Sie die ersten n Bytes der Adresse dest mit den Zeichen ch auf. > /* memset.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char credit_card[21] = "123456-aiex"; char *ptr = strchr(credit_card, '-'); *ptr++; /* die letzten vier Zeichen der Kreditkartennummer * nicht angeben */ memset(ptr, '*', 4); printf("%s\n",credit_card); return EXIT_SUCCESS; } # 21.2 Doppelt verkettete Listen ## 21.2 Doppelt verkettete Listen Im Gegensatz zu den einfach verketteten Listen haben doppelt verkettete Listen zusätzlich noch einen Zeiger auf den Vorgänger. Soll z. B. erst ein Element in der Liste gelöscht werden und wird gleich darauf auf den Vorgänger des gelöschten Elements zugegriffen, müsste bei der einfach verketteten Liste der vollständige Satz von Neuem durchlaufen werden. Mit der doppelt verketteten Liste kann hingegen sofort auf den Vorgänger zugegriffen werden. Zur Realisierung doppelt verketteter Listen muss nur der Struktur bei der Deklaration ein weiterer Zeiger hinzugefügt werden: > struct angestellt{ char name[20]; char vorname[20]; struct datum alter; struct datum eingest; long gehalt; struct angestellt *next; /* Nachfolger */ struct angestellt *previous; /* Vorgänger */ }; AuÃerdem sollten Sie noch einen Zeiger auf das letzte Element definieren. Wird z. B. nach einem Namen mit dem Anfangsbuchstaben »Z« gesucht, wäre es doch reine Zeitverschwendung, die Liste von vorn zu durchlaufen. Also gäbe es noch folgende Angaben: ``` struct angestellt *anfang; struct angestellt *ende; ``` Die Initialisierung mit NULL soll gleich in eine Funktion verpackt werden: > void start(void) { anfang = ende = NULL; } So sieht die Struktur jetzt mit dem Extra-Zeiger auf seinen Vorgänger aus (siehe Abbildung 21.22). Abbildung 21.22 Struktur einer doppelt verketteten Liste Bevor all dies in die Praxis umgesetzt wird, noch schnell ein Bild dazu, wie Sie sich eine doppelt verkettete Liste vorstellen können (siehe Abbildung 21.23). Abbildung 21.23 Doppelt verkettete Liste Auf den kommenden Seiten werden die Funktionen, die im Abschnitt über die einfach verketteten Listen verwendet wurden, umgeschrieben, damit diese mit doppelt verketteten Listen eingesetzt werden können. Sie müssen dabei immer darauf achten, dass jetzt jedes Element in der Liste auch einen Vorgänger besitzt. Wir beginnen mit der Funktion anhaengen(): > void anhaengen(char *n, char *v, int at, int am, int aj, int eint, int einm, int einj, long g) { /* Zeiger zum Zugriff auf die einzelnen Elemente * der Struktur */ struct angestellt *zeiger, *zeiger1; /* Wurde schon Speicher für den ende-Zeiger bereitgestellt? */ if(ende == NULL) { if((ende=malloc(sizeof(struct angestellt))) == NULL) { printf("Konnte keinen Speicherplatz für ende " "reservieren\n"); return; } } /* Wir fragen ab, ob es schon ein Element in der Liste gibt. * Wir suchen das Element, auf das unser Zeiger *anfang * zeigt. Falls *anfang immer noch auf NULL zeigt, bekommt * *anfang die Adresse unseres 1. Elements und ist somit der * Kopf (Anfang) unserer Liste. */ if(anfang == NULL) { /* Wir reservieren Speicherplatz für unsere * Struktur für das erste Element der Liste. */ if((anfang =malloc(sizeof(struct angestellt))) == NULL) { fprintf(stderr,"Kein Speicherplatz vorhanden " "fuer anfang\n"); return; } strcpy(anfang->name,strtok(n, "\n")); strcpy(anfang->vorname,strtok(v, "\n")); anfang->alter.tag=at; anfang->alter.monat=am; anfang->alter.jahr=aj; anfang->eingest.tag=eint; anfang->eingest.monat=einm; anfang->eingest.jahr=einj; anfang->gehalt=g; Bis hierhin stellt diese Funktion nichts Neues dar. Es wird davon ausgegangen, dass sich noch kein Element in der Liste befindet, und Sie fügen nun das erste Element ein: > anfang->next=NULL; ende=anfang; ende->previous=NULL; } Der next-Zeiger vom ersten Element zeigt zunächst auf gar nichts (NULL). Der ende-Zeiger, der auf das letzte Element verweist, zeigt am Anfang zunächst auf das erste Element, das gleichzeitig ja auch das letzte der Liste ist. Der previous-Zeiger, der auf den Vorgänger zeigen soll, verweist ebenso auf NULL. Genauso gut hätten Sie anstatt ende->previous=NULL auch anfang->previous=NULL schreiben können. Beides hätte denselben Effekt gehabt. Kommen wir jetzt zur zweiten Möglichkeit – das neue Element wird hinten angehängt: > else { zeiger=anfang; /* Wir zeigen auf das 1. Element. */ while(zeiger->next != NULL) zeiger=zeiger->next; /* Wir reservieren einen Speicherplatz für das letzte * Element der Liste und hängen es an. */ if((zeiger->next = malloc(sizeof(struct angestellt))) == NULL) { fprintf(stderr, "Kein Speicherplatz fuer " "letztes Element\n"); return; } zeiger1=zeiger; zeiger=zeiger->next; /* zeiger auf neuen Speicherplatz */ strcpy(zeiger->name,strtok(n, "\n")); strcpy(zeiger->vorname,strtok(v, "\n")); zeiger->alter.tag=at; zeiger->alter.monat=am; zeiger->alter.jahr=aj; zeiger->eingest.tag=eint; zeiger->eingest.monat=einm; zeiger->eingest.jahr=einj; zeiger->gehalt=g; Auch am Anfang bleibt beim Hintenanhängen alles beim Alten – bis auf den zeiger1, der wie zeiger auf das momentan (noch) letzte Element zeigt. AnschlieÃend verweist man den Zeiger zeiger auf den neuen Speicherplatz, der zuvor mit malloc() reserviert wurde (siehe Abbildung 21.24). Abbildung 21.24 Ein neues Element wurde hinten mit einfacher Verkettung angefügt. Die weiteren Schritte zum Einfügen des neuen Elements sind: > zeiger->next=NULL; ende=zeiger; zeiger->previous=zeiger1; zeiger1->next=zeiger; } Der next-Zeiger des neuen Elements bekommt den NULL-Zeiger. Der ende-Zeiger verweist auf das neue Element, da es das letzte Element in der Liste ist. Zusätzlich bekommt das neue Element auch die Adresse des Vorgängers, auf die zeiger1 verweist. Und zeiger1->next bekommt noch die Adresse des neuen Elements zeiger übergeben. Somit ergibt sich folgendes Bild: Abbildung 21.25 Ein neues Element wurde hinten mit doppelter Verkettung angefügt. Schwieriger wird die nächste Funktion, nämlich das Löschen eines Elements in der Liste: > void loesche(char *wen) { struct angestellt *zeiger, *zeiger1, *zeiger2; /* Ist überhaupt ein Element vorhanden? */ if(anfang != NULL) { /* Ist unser 1. Element das von uns gesuchte (wen[])? */ if(strcmp(anfang->name,wen) == 0) { zeiger=anfang->next; if(zeiger == NULL) { free(anfang); anfang=NULL; ende=NULL; return; } zeiger->previous=NULL; free(anfang); anfang=zeiger; } Die erste Möglichkeit: Das erste Element ist das gesuchte und soll gelöscht werden. Als Erstes lassen Sie einen Zeiger auf die zukünftige Anfangsdatei zeigen – natürlich vorausgesetzt, es ist mehr als ein Element vorhanden. Falls nicht (if(zeiger == NULL)), wird die Anweisung der if-Bedingung aktiv. Abbildung 21.26 zeigt den momentanen Stand. Abbildung 21.26 Das erste Element in der Liste (»anfang«) soll gelöscht werden. Es wird davon ausgegangen, dass bereits mehrere Elemente in der Liste vorhanden sind. Also folgt nur noch: > zeiger->previous=NULL; free(anfang); anfang=zeiger; ... und schon ist das erste Element in der Liste gelöscht: Abbildung 21.27 Das erste Element in der Liste wurde gelöscht. Die zweite Möglichkeit ist, dass das zu löschende Element das letzte in der Liste ist: > else if(strcmp(ende->name,wen) == 0) { zeiger=ende->previous; zeiger->next=NULL; zeiger1=ende; ende=zeiger; free(zeiger1); } Da der Vorgang ähnlich wie beim ersten Element abläuft, kann dieser auf einem Blatt Papier zur Ãbung selbst aufgezeichnet werden. Weiter geht es mit der dritten Möglichkeit: Das zu löschende Element ist irgendwo zwischendrin: > zeiger=anfang; while(zeiger->next != NULL) { zeiger1=zeiger->next; /* Ist die Adresse von zeiger1 der gesuchte Name? */ if(strcmp(zeiger1->name,wen) == 0) { /* Falls ja, dann ... */ zeiger->next=zeiger1->next; zeiger2=zeiger1->next; zeiger2->previous=zeiger; free(zeiger1); break; } zeiger=zeiger1; } Wir nehmen hier wieder an, dass das zu löschende Element gefunden wurde und dass es das zweite Element ist (im Bild mit del gekennzeichnet): Abbildung 21.28 Das Element, auf das »zeiger1« verweist, soll gelöscht werden. zeiger1 verweist auf das zu löschende Element. Dieses Element muss jetzt ausgehängt werden. Die weiteren Schritte sind somit: > zeiger->next=zeiger1->next; Abbildung 21.29 Zu löschendes Element zum Teil aushängen > zeiger2=zeiger1->next; Abbildung 21.30 Ein Zeiger auf den Vorgänger des zu löschenden Elements > zeiger2->previous=zeiger; Abbildung 21.31 Das zu löschende Element wurde komplett ausgehängt. > free(zeiger1); Abbildung 21.32 Speicherplatz freigegeben Der Vorgang lässt sich anhand der Grafiken recht einfach nachvollziehen. Hier folgt die vollständige Funktion zur Ãbersicht: > /* Funktion zum Löschen einer Datei */ void loesche(char *wen) { struct angestellt *zeiger, *zeiger1, *zeiger2; /* Ist überhaupt ein Element vorhanden? */ if(anfang != NULL) { /* Ist unser 1. Element das von uns gesuchte (wen[])? */ if(strcmp(anfang->name,wen) == 0) { zeiger=anfang->next; if(zeiger == NULL) { free(anfang); anfang=NULL; ende=NULL; return; } zeiger->previous=NULL; free(anfang); anfang=zeiger; } /* Ist das letzte Element das von uns gesuchte? */ else if(strcmp(ende->name,wen) == 0) { zeiger=ende->previous; zeiger->next=NULL; zeiger1=ende; ende=zeiger; free(zeiger1); } else { /* Es ist nicht das 1. Element zu löschen. * Wir suchen in der weiteren Kette, ob das zu * löschende Element vorhanden ist. */ zeiger=anfang; while(zeiger->next != NULL) { zeiger1=zeiger->next; /* Ist die Adresse von zeiger1 * der gesuchte Name? */ if(strcmp(zeiger1->name,wen) == 0) { /* Falls ja, dann ... */ zeiger->next=zeiger1->next; zeiger2=zeiger1->next; zeiger2->previous=zeiger; free(zeiger1); break; } zeiger=zeiger1; } } } else printf("Es sind keine Daten zum Loeschen vorhanden!!!\n"); } Die Funktionen eingabe() und ausgabe() müssen nicht verändert werden. Die Funktion loesche_alles() ist ebenfalls relativ einfach umzuschreiben. Es muss lediglich die ganze Liste durchlaufen werden, und dabei müssen alle bis auf das erste und letzte Element gelöscht werden: > void loesche_alles(void) { struct angestellt *zeiger, *zeiger1; /* Ist überhaupt eine Liste zum Löschen vorhanden? */ if(anfang != NULL) { /* Es ist eine vorhanden ... */ zeiger=anfang->next; while(zeiger != NULL) { zeiger1=anfang->next->next; if(zeiger1 == NULL) break; anfang->next=zeiger1; zeiger1->previous=anfang; free(zeiger); zeiger=zeiger1; } Abbildung 21.33 Momentane Zeigerstellung der Funktion »loesche_alles()« Die if-Abfrage, ob der Zeiger zeiger1 auf NULL zeigt, wird als Abbruchbedingung benutzt, da – falls das wahr sein sollte – nur noch zwei Elemente in der Liste vorhanden sind. Genauso gut hätten Sie dies mit der while-Abfrage vornehmen können: while(zeiger->next != NULL). Zu dieser Funktion sehen wir uns den Ablauf an. Zuerst wird das Element, auf das zeiger verweist, ausgehängt: > anfang->next=zeiger1; zeiger1->previous=anfang; Danach kann der Speicherplatz, auf den zeiger zeigt, mit free() freigegeben werden. Es ergibt sich in Abbildung 21.35. Abbildung 21.35 Speicherplatz wurde freigegeben. Hier endet die while-Schleife, da zeiger1=anfang->next->next jetzt auf NULL zeigt. Jetzt müssen nur noch die letzten beiden Elemente in der Liste gelöscht werden: > free(anfang); free(ende); anfang=NULL; ende=NULL; Dazu müssen Sie den Speicherplatz freigeben, auf den anfang und ende zeigen. AnschlieÃend bekommen die Zeiger anfang und ende den NULL-Zeiger. Die Funktion loesche_alles() sieht komplett so aus: > void loesche_alles(void) { struct angestellt *zeiger, *zeiger1; /* Ist überhaupt eine Liste zum Löschen vorhanden? */ if(anfang != NULL) { /* Es ist eine vorhanden ... */ zeiger=anfang->next; while(zeiger != NULL) { zeiger1=anfang->next->next; if(zeiger1 == NULL) break; anfang->next=zeiger1; zeiger1->previous=anfang; free(zeiger); zeiger=zeiger1; } /* Jetzt löschen wir erst den Anfang der Liste und * dann das Ende der Liste. */ free(anfang); free(ende); anfang=NULL; ende=NULL; printf("Liste erfolgreich geloescht!!\n"); } else fprintf(stderr, "Keine Liste zum Loeschen vorhanden!!\n"); } Als Nächstes soll die Funktion sortiert_eingeben() umgeschrieben werden, damit diese für doppelt verkettete Listen verwendet werden kann: > void sortiert_eingeben(char *n, char *v, int at, int am, int aj, int et, int em, int ej, long geh) { struct angestellt *zeiger, *zeiger1; /* Ist es das 1. Element der Liste? */ if(anfang==NULL) anhaengen(n,v,at,am,aj,et,em,ej,geh); /* Es ist nicht das 1. Element. Wir suchen nun so lange, bis * das gesuchte Element gefunden wird oder wir auf NULL * stoÃen. */ else { zeiger=anfang; while(zeiger != NULL && (strcmp(zeiger->name,n) < 0 ) ) zeiger=zeiger->next; /* Falls der Zeiger auf NULL zeigt, können wir * unser Element hinten anhängen, da unser neues Element * das "gröÃte" zu sein scheint. */ if(zeiger==NULL) anhaengen(n,v,at,am,aj,et,em,ej,geh); /* Ist unser neues Element das kleinste und somit * kleiner als das 1. Element, so müssen wir es an den * Anfang hängen. */ else if(zeiger == anfang) { anfang=malloc(sizeof(struct angestellt)); if(NULL == anfang) { fprintf(stderr, "Kein Speicherplatz vorhanden!!!\n"); return; } strcpy(anfang->name,strtok(n, "\n") ); strcpy(anfang->vorname,strtok(v, "\n") ); anfang->alter.tag=at; anfang->alter.monat=am; anfang->alter.jahr=aj; anfang->eingest.tag=et; anfang->eingest.monat=em; anfang->eingest.jahr=ej; anfang->gehalt=geh; anfang->next=zeiger; anfang->previous=NULL; } Die Erklärung dafür, ob es sich hier um das einzige, das erste oder das letzte Element der Liste handelt, können Sie bei der Funktion anhaengen() in Abschnitt 21.1, »Lineare Listen (einfach verkettete Listen)«, nachlesen. Viel interessanter ist es, wie ein Element irgendwo dazwischen eingefügt wird. Hier sehen Sie zunächst den weiteren Codeverlauf: > else { zeiger1=anfang; /* Wir suchen das Element, das vor dem * Zeiger zeiger steht. */ while(zeiger1->next != zeiger) zeiger1=zeiger1->next; zeiger=malloc(sizeof(struct angestellt)); if(NULL == zeiger) { fprintf(stderr, "Kein Speicherplatz vorhanden!!!\n"); return; } strcpy(zeiger->name, strtok(n, "\n") ); strcpy(zeiger->vorname, strtok(v, "\n") ); zeiger->alter.tag=at; zeiger->alter.monat=am; zeiger->alter.jahr=aj; zeiger->eingest.tag=et; zeiger->eingest.monat=em; zeiger->eingest.jahr=ej; zeiger->gehalt=geh; /* Wir fügen das neue Element ein */ zeiger->next=zeiger1->next; zeiger->previous=zeiger1; zeiger1->next=zeiger; zeiger1->next->previous=zeiger; } /* Ende else */ Wir gehen davon aus, dass die Position für das neue Element bereits ermittelt wurde und dass sich zeiger1 vor diesem Element befindet. Somit ergibt sich folgender Zustand: Abbildung 21.36 Neues Element einfügen Jetzt soll das neue Element, auf das zeiger verweist, zwischen dem zweiten und dem dritten Element eingefügt werden. Die weiteren Schritte sind: > zeiger->next=zeiger1->next; Abbildung 21.37 Zeiger auf den Nachfolger des neuen Elements > zeiger->previous=zeiger1; Abbildung 21.38 Zeiger auf den Vorgänger des neuen Elements > zeiger1->next=zeiger; zeiger1->next->previous=zeiger; Abbildung 21.39 Zeiger vom Vorgänger und Nachfolger zum neuen Element Das soll es vorerst mit dem Abschnitt »Doppelt verkettete Listen« gewesen sein. Wenn Sie folgende Ratschläge zu diesem Thema beherzigen, dürften keine Probleme zu erwarten sein: * Wenn Sie Zeiger benutzen, müssen Sie immer darauf achten, dass diese auf einen gültigen Speicherbereich (Adresse) zeigen. Ein häufiges Missverständnis bei Zeigern ist es, dass z. B. mit zeiger1=zeiger kein Wert an zeiger1 übergeben wird, sondern die Adresse, auf die zeiger verweist. Daher empfiehlt es sich, so oft wie möglich Fehlerüberprüfungen einzubauen. * Sie sollten aussagekräftige Namen für einen Zeiger verwenden. Beispiele: next, previous, anfang oder ende. Dies ist eine enorme Erleichterung, wenn das Programm Fehler hat und nach ihnen gesucht werden muss. Denn unter anfang->next=ende können Sie sich mehr vorstellen als unter a–>n=e. * Einer der häufigsten Fehler ist ein Zeiger, der auf einen unerlaubten Speicherplatz zeigt. Daher lohnt es, sich die Zeit zu nehmen, den Ablauf des Programms auf einem Stück Papier zu zeichnen, um ihn besser nachvollziehen zu können. Gerade bei doppelt verketteten Listen passiert es ziemlich schnell, dass Sie ein Glied der Kette vergessen. Meist wird dieser Fehler am Anfang gar nicht bemerkt, denn der Compiler kann bei Ãbersetzung des Programms ja noch nicht wissen, ob ein Zeiger ins Nirwana verweist. * And last but not least: Sie sollten immer den Rückgabewert überprüfen, wenn Speicherplatz reserviert wird. Denn alles, was schiefgehen kann, wird irgendwann einmal schiefgehen. Das vollständige Listing (double_list.c) finden Sie selbstverständlich auf der Buch-CD. Dem Listing wurden noch einige Funktionen, unter anderem das Laden oder Speichern von Daten auf der Festplatte, hinzugefügt. # 21.3 Stacks nach dem LIFO-(Last-in-First-out-)Prinzip ## 21.3 Stacks nach dem LIFO-(Last-in-First-out-)Prinzip Der Stack ist ebenfalls eine Datenstruktur von verketteten Listen, nur dass hierbei die Anordnung der einzelnen Elemente ein wenig anders ist. Der Stack funktioniert nach dem LIFO-Prinzip (Last-in-First-out), was bedeutet, dass die Daten, die als letzte eingefügt wurden, als erste wieder vom Stack genommen werden – etwa wie bei einem Stapel schmutziger Teller, die Sie abwaschen. Sie haben bei einem Stack also immer nur Zugriff auf das oberste Element. Verwenden könnten Sie das Prinzip beispielsweise zum rückgängigen Löschen einer Operation. Im Prinzip besteht ein Stack aus zwei grundlegenden Funktionen: * push() – ein neues Element auf dem Stack ablegen * pop() – holt das oberste Element wieder vom Stack herunter Abbildung 21.40 Der Stack und seine grundlegende Funktion Als Beispiel dient wieder das Programm, das Sie schon im Abschnitt zuvor entwickelt haben. Hierzu soll eine Funktion erstellt werden, die gelöschte Datensätze auf einen Stack ablegt und bei Bedarf diese Aktion wieder rückgängig machen kann. An der Struktur selbst ändert sich nichts. Hier sehen Sie nochmals die Struktur zur Erinnerung: > struct angestellt { char name[20]; char vorname[20]; struct datum alter; struct datum eingest; long gehalt; struct angestellt *next; // Nachfolger struct angestellt *previous; // Vorgänger }; Hinzu kommen zwei neue globale Strukturzeiger vom Typ angestellt: > struct angestellt *stack_ptr, *stack_help; Für den Stack soll hier eine Unterlage erstellt werden, auf der alle anderen Elemente abgeladen werden. Dafür wird eine Funktion erstellt, die eine Auflage erstellt und den Stack initialisiert. > int stackinit(void) { if((stack_ptr= malloc(sizeof(struct angestellt))) != NULL) { stack_ptr->next = NULL; strcpy(stack_ptr->name,"dummy"); strcpy(stack_ptr->vorname,"dummy"); stack_ptr->alter.tag=0; stack_ptr->alter.monat=0; stack_ptr->alter.jahr=0; stack_ptr->eingest.tag=0; stack_ptr->eingest.monat=0; stack_ptr->eingest.jahr=0; stack_ptr->gehalt=0; return 1; } else return 0; } Zuerst wird Speicherplatz für die »Auflagefläche« der weiteren Elemente, die noch folgen werden, reserviert. Als Inhalt für die Auflagefläche werden einfach irgendwelche Werte verwendet. Der Zeiger stack_ptr verweist jetzt auf diese Auflagefläche (siehe Abbildung 21.41). Abbildung 21.41 Ein »leerer« Stack Danach folgt die Funktion push(), mit der ein Element auf den Stack geladen werden kann. Die Funktion push() soll im Programm dann aufgerufen werden, wenn der User einen Datensatz aus der Liste löscht. Praktisch bedeutet dies, dass überall im Programm, wo Sie mit free() einen Speicherplatz freigeben würden, die Funktion push() platziert wird. > int push(struct angestellt *neu) { neu->next = stack_ptr->next; stack_ptr->next=neu; return 1; } Der Speicherplatz für die Elemente, die auf dem Stack abgelegt werden, muss nicht mehr reserviert werden, da dies ja schon beim Einfügen des Elements in der verketteten Liste vorgenommen wurde. Natürlich müssen Sie dabei auch die Funktion loesche() abändern, damit diese wirklich den Speicherplatz nicht mehr mittels free() hergibt. Der Funktion push() wird einfach diese Adresse als Argument (struct angestellt *neu) übergeben. Beachten Sie bitte, falls Sie vorhaben, den Stack in ein anderes Programm zu implementieren, dass Sie für die Speicherverwaltung der Daten selbst verantwortlich sind. Die erste Zeile in der Funktion sieht so aus: > neu->next = stack_ptr->next; Damit verweist der next-Zeiger des neuen Elements auf die Adresse von stack_ptr->next, was zunächst der NULL-Zeiger ist, wie Sie hier erkennen können: Abbildung 21.42 Ein neues Element auf den Stack legen AnschlieÃend bekommt die »Auflagefläche« die Adresse des neuen Elements: > stack_ptr->next=neu; Abbildung 21.43 Der Stack nach dem Funktionsaufruf »push()« Bei einem erneuten Aufruf der Funktion push() würde der Stack folgendermaÃen aussehen: Abbildung 21.44 Der Stack nach einem weiteren »push« Das erste Element im Stapel, vom DUMMY-Element abgesehen, zeigt immer auf NULL, da es auch das letzte ist, das wieder vom Stapel entfernt wird. Als Nächstes folgt die Funktion zum rückgängigen Löschen eines Datensatzes. Diese Funktion verwendet den Zeiger stack_ptr->next, um an die Daten heranzukommen, die oben auf dem Stack liegen. Sind die Daten ausgelesen, werden sie wieder in die verkettete Liste eingefügt. > void rueckgaengig_loeschen(void) { char n[20],vn[20]; int at,am,aj,et,em,ej; long geh; if(stack_ptr->next != NULL) { strcpy(n,stack_ptr->next->name); strcpy(vn,stack_ptr->next->vorname); at=stack_ptr->next->alter.tag; am=stack_ptr->next->alter.monat; aj=stack_ptr->next->alter.jahr; et=stack_ptr->next->eingest.tag; em=stack_ptr->next->eingest.monat; ej=stack_ptr->next->eingest.jahr; geh=stack_ptr->next->gehalt; sortiert_eingeben(n,vn,at,am,aj,et,em,ej,geh); /* jetzt runter damit vom Stack */ pop(); } else { printf("Kein Element mehr vorhanden zu \"Rückgängig" " Löschen\"\n"); printf("<ENTER>"); getchar(); } } Am Ende kann das oberste Element vom Stack wieder entfernt werden, wie dies hier bei der Funktion rueckgaengig_loeschen() mit der Funktion pop() geschieht. Jetzt müssen Sie noch die Funktion pop() schreiben: > void pop(void) { stack_help = stack_ptr->next; stack_ptr->next=stack_help->next; printf("%s\n",stack_help->vorname); free(stack_help); } Zuerst bekommt der Zeiger stack_help die Adresse des obersten Elements (stack_ptr->next) auf dem Stapel: Abbildung 21.45 Das oberste Element soll vom Stack entfernt werden. Danach folgt eine kleine Stolperstelle, die häufig für Verwirrung sorgt: > stack_ptr->next=stack_help->next; Aber dafür ist es nun mal ein Stapel. Wird das oberste Element entfernt, welches ist dann das nächste Element, das oben liegt? Richtig, eines darunter. Und so sieht es nach dieser Zeile aus: Abbildung 21.46 Das oberste Element vom Stack »aushängen« Jetzt kann der Speicherplatz, auf den der Zeiger stack_help verweist, freigegeben werden: > free(stack_help); Abbildung 21.47 Den Speicherplatz des obersten Elements freigeben Hierzu folgt jetzt das vollständige finale Listing von Kapitel 21 mit allen Funktionen, die in diesem Kapitel geschrieben wurden: > /* datenstruktur_final.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 20 struct datum{ int tag; int monat; int jahr; }; struct angestellt{ char name[MAX]; char vorname[MAX]; struct datum alter; struct datum eingest; long gehalt; struct angestellt *next; struct angestellt *previous; }; /* globale Variablen */ struct angestellt *next, *anfang, *ende, *stack_ptr, *stack_help; static int counter=0; static char datname[] = "personal.dat"; /* Prototypen der Funktionen */ void start(void); void anhaengen(char *,char *,int,int,int,int,int,int,long); void loesche(char *); void ausgabe(void); void eingabe(void); void loesche_alles(void); void sortiert_eingeben(char *,char *, int,int,int,int,int,int,long); int vergleiche(struct angestellt *, struct angestellt *); int laden(FILE *); void speichern(FILE *); int datei_oeffnen_lesen(FILE **); int datei_oeffnen_erstellen(FILE **); int datei_oeffnen_lesen_schreiben(FILE **); int stackinit(void); int push(struct angestellt *); void pop(void); /* Startadressen für die Zeiger next, anfang und ende */ void start(void) { next=anfang=ende=NULL; if((ende= malloc(sizeof(struct angestellt))) == NULL) { printf("Konnte keinen Speicherplatz für ende " "reservieren\n"); exit(EXIT_FAILURE); } } /* "Auflagefläche" für stack_ptr. Wir benutzen * einen Stack, um loeschen() rückgängig zu machen. */ int stackinit(void) { if((stack_ptr= malloc(sizeof(struct angestellt))) != NULL) { stack_ptr->next = NULL; strcpy(stack_ptr->name,"dummy"); strcpy(stack_ptr->vorname,"dummy"); stack_ptr->alter.tag=0; stack_ptr->alter.monat=0; stack_ptr->alter.jahr=0; stack_ptr->eingest.tag=0; stack_ptr->eingest.monat=0; stack_ptr->eingest.jahr=0; stack_ptr->gehalt=0; return 1; } else return 0; } /* Funktion zum Ablegen von gelöschten Dateien, um sie bei Bedarf * rückgängig zu machen */ int push(struct angestellt *neu) { neu->next = stack_ptr->next; stack_ptr->next=neu; return 1; } /* Funktion zum Freigeben eines Elements vom Stack */ void pop(void) { stack_help = stack_ptr->next; stack_ptr->next=stack_help->next; free(stack_help); } /* Wir hängen einen Datensatz an oder geben einen neuen ein: * n=name,v=vornam,at=alter.tage,am=alter.monat,aj=alter.jahr * eint=eigestellt tag,einm=eingestellt monat,einj=eingest. jahr * g=gehalt */ void anhaengen(char *n, char *v, int at, int am, int aj, int eint, int einm, int einj, long g) { /* Zeiger für den Zugriff auf die einzelnen * Elemente der Struktur */ struct angestellt *zeiger, *zeiger1; /* Wurde schon Speicher für den ende-Zeiger bereitgestellt? */ if(ende == NULL) { if((ende= malloc(sizeof(struct angestellt))) == NULL) { printf("Konnte keinen Speicherplatz für ende " "reservieren\n"); exit(EXIT_FAILURE); } } /* Wir fragen ab, ob es schon ein Element in der Liste gibt. * Wir suchen das Element, auf das unser Zeiger *anfang zeigt. * Falls *anfang immer noch auf NULL zeigt, bekommt *anfang * die Adresse unseres 1. Elements und ist somit der Kopf * (Anfang) unserer Liste. */ if(anfang == NULL) { /* Wir reservieren Speicherplatz für unsere Struktur * für das erste Element der Liste. */ if((anfang = malloc(sizeof(struct angestellt))) == NULL) { fprintf(stderr,"Kein Speicherplatz vorhanden " "fuer anfang\n"); return; } counter++; strcpy(anfang->name,strtok(n, "\n") ); strcpy(anfang->vorname,strtok(v, "\n") ); anfang->alter.tag=at; anfang->alter.monat=am; anfang->alter.jahr=aj; anfang->eingest.tag=eint; anfang->eingest.monat=einm; anfang->eingest.jahr=einj; anfang->gehalt=g; /* Somit haben wir unseren Anfang der Liste. Von nun * an zeigt der Zeiger anfang immer auf das Element * vor ihm. Da dies aber jetzt das 1. Element der Liste * war, zeigt der Zeiger anfang auf den Zeiger next. * next zeigt am Ende immer wieder NULL. Da es das erste * Element der Liste ist, zeigt somit ende auf * dasselbe Element wie anfang. Und das Element vor dem * 1. Element ist somit NULL. */ anfang->next=NULL; ende=anfang; ende->previous=NULL; } /* Es scheint schon mindestens ein Element in der Liste * vorhanden zu sein, da der Anfang nicht == NULL ist. * Jetzt suchen wir so lange nach dem nächsten Element, * bis der *next-Zeiger auf NULL zeigt. Somit haben * wir das Ende der Liste gefunden und können einen * neuen Datensatz anhängen. */ else { zeiger=anfang; /* Wir zeigen auf das 1. Element. */ while(zeiger->next != NULL) zeiger=zeiger->next; /* Wir reservieren einen Speicherplatz für das * letzte Element der Liste und hängen es an. */ if((zeiger->next = malloc(sizeof(struct angestellt))) == NULL) { fprintf(stderr, "Kein Speicherplatz fuer " "letztes Element\n"); return; } zeiger1=zeiger; zeiger=zeiger->next; /* zeiger auf neuen Speicherplatz */ counter++; strcpy(zeiger->name, strtok(n, "\n") ); strcpy(zeiger->vorname,strtok(v, "\n") ); zeiger->alter.tag=at; zeiger->alter.monat=am; zeiger->alter.jahr=aj; zeiger->eingest.tag=eint; zeiger->eingest.monat=einm; zeiger->eingest.jahr=einj; zeiger->gehalt=g; zeiger->next=NULL; ende=zeiger; zeiger->previous=zeiger1; zeiger1->next=zeiger; } } /* Funktion zum Löschen einer Datei */ void loesche(char *wen) { struct angestellt *zeiger ,*zeiger1, *zeiger2; /* Ist überhaupt ein Element vorhanden? */ if(anfang != NULL) { /* Ist unser 1. Element das von uns gesuchte (wen[])? */ if(strcmp(anfang->name,wen) == 0) { zeiger=anfang->next; if(zeiger == NULL) { push(anfang); anfang=NULL; ende=NULL; counter--; return; } push(anfang); zeiger->previous=NULL; /* free(anfang); */ counter--; anfang=zeiger; } /* Ist das letzte Element das von uns gesuchte? */ else if(strcmp(ende->name, wen) == 0) { zeiger=ende->previous; zeiger->next=NULL; zeiger1=ende; ende=zeiger; push(zeiger1); /* free(zeiger1); */ counter--; } else { /* Es ist nicht das 1. Element zu löschen. * Wir suchen in der weiteren Kette, ob das zu * löschende Element vorhanden ist. */ zeiger=anfang; while(zeiger->next != NULL) { zeiger1=zeiger->next; /* Ist die Adresse von zeiger1 der gesuchte Name? */ if(strcmp(zeiger1->name,wen) == 0) { /* Falls ja, dann ... */ zeiger->next=zeiger1->next; zeiger2=zeiger1->next; zeiger2->previous=zeiger; push(zeiger1); counter--; break; } zeiger=zeiger1; } } } else printf("Es sind keine Daten zum Loeschen vorhanden\n"); } /* Funktion zum Ausgeben der Dateien */ void ausgabe(void) { struct angestellt *zeiger = anfang; printf("||===================================================" "====||\n"); printf("|%10cName%10c |Geburtsdatum|Eingestellt|Gehalt|\n" ,' ',' '); printf("||===================================================" "====||\n"); while(zeiger != NULL) { printf("|%12s,%-12s| %02d.%02d.%04d| %02d.%02d.%04d|" "%06ld|\n", zeiger->name,zeiger->vorname, zeiger->alter.tag, zeiger->alter.monat, zeiger->alter.jahr,zeiger->eingest.tag, zeiger->eingest.monat,zeiger->eingest.jahr, zeiger->gehalt); printf("|---------------------------------------------" "------------|\n"); zeiger=zeiger->next; } printf("\n\nWeiter mit <ENTER>\n"); getchar(); } /* Funktion zur Eingabe der Daten */ void eingabe(void) { char nam[MAX],vorn[MAX]; int atag,amon,ajahr,eintag,einmon,einjahr; long gehalt; char *ptr; printf("Name........................: "); fgets(nam, MAX, stdin); ptr = strrchr(nam, '\n'); *ptr = '\0'; printf("Vorname.....................: "); fgets(vorn, MAX, stdin); ptr = strrchr(vorn, '\n'); *ptr = '\0'; printf("Alter...........(tt.mm.jjjj): "); scanf("%2d.%2d.%4d",&atag,&amon,&ajahr); printf("Eingestellt am..(tt.mm.jjjj): "); scanf("%2d.%2d.%4d",&eintag,&einmon,&einjahr); printf("Monatsgehalt................: "); scanf("%ld",&gehalt); getchar(); sortiert_eingeben(nam, vorn, atag, amon, ajahr, eintag, einmon, einjahr, gehalt); } /* Funktion zum Löschen der gesamten Liste */ void loesche_alles(void) { struct angestellt *zeiger, *zeiger1; /* Ist überhaupt eine Liste zum Löschen vorhanden? */ if(anfang != NULL) { /* Es ist eine vorhanden ... */ zeiger=anfang->next; while(zeiger != NULL) { zeiger1=anfang->next->next; if(zeiger1 == NULL) break; anfang->next=zeiger1; zeiger1->previous=anfang; push(zeiger); zeiger=zeiger1; } /* Jetzt löschen wir erst den Anfang der Liste * und das Ende der Liste. */ push(anfang); push(ende); anfang=NULL; ende=NULL; counter=0; printf("Liste erfolgreich geloescht!!\n"); } else fprintf(stderr,"Keine Liste zum Loeschen vorhanden!!\n"); } void sortiert_eingeben(char *n, char *v, int at, int am, int aj, int et, int em, int ej, long geh ) { struct angestellt *zeiger, *zeiger1, *zeiger2; zeiger2=malloc(sizeof(struct angestellt)); if(NULL == zeiger2) { fprintf(stderr, "Speicherplatzmangel\n"); return; } strcpy(zeiger2->name,strtok(n, "\n") ); strcpy(zeiger2->vorname,strtok(v, "\n") ); zeiger2->alter.tag=at; zeiger2->alter.monat=am; zeiger2->alter.jahr=aj; zeiger2->eingest.tag=et; zeiger2->eingest.monat=em; zeiger2->eingest.jahr=ej; zeiger2->gehalt=geh; /* Ist es das 1. Element der Liste? */ if(anfang==NULL) anhaengen(n,v,at,am,aj,et,em,ej,geh); /* Es ist nicht das 1. Element. Wir suchen nun so lange, * bis das gesuchte Element gefunden wird oder wir auf * NULL stoÃen. */ else { zeiger=anfang; while(zeiger != NULL && (vergleiche(zeiger,zeiger2)<0)) zeiger=zeiger->next; /* Falls der Zeiger auf NULL zeigt, können wir unser * Element hinten anhängen, da unser neues Element das * "gröÃte" zu sein scheint. */ if(zeiger==NULL) anhaengen(n,v,at,am,aj,et,em,ej,geh); /* Ist unser neues Element das kleinste und somit * kleiner als das 1. Element, so müssen wir es an * den Anfang hängen. */ else if(zeiger==anfang && (vergleiche(zeiger,zeiger2))) { anfang=malloc(sizeof(struct angestellt)); if(NULL == anfang) { fprintf(stderr, "Speicherplatzmangel\n"); return; } counter++; strcpy(anfang->name, strtok(n, "\n") ); strcpy(anfang->vorname, strtok(v, "\n") ); anfang->alter.tag=at; anfang->alter.monat=am; anfang->alter.jahr=aj; anfang->eingest.tag=et; anfang->eingest.monat=em; anfang->eingest.jahr=ej; anfang->gehalt=geh; anfang->next=zeiger; anfang->previous=NULL; } /* Die letzte Möglichkeit ist, dass wir das Element * irgendwo in der Mitte einfügen müssen. */ else if(vergleiche(zeiger,zeiger2)) { zeiger1=anfang; /* Wir suchen das Element, das vor dem Zeiger * zeiger steht. */ while(zeiger1->next != zeiger) zeiger1=zeiger1->next; zeiger=malloc(sizeof(struct angestellt)); if(NULL == zeiger) { fprintf(stderr, "Speicherplatzmangel\n"); return; } counter++; strcpy(zeiger->name, strtok(n, "\n") ); strcpy(zeiger->vorname, strtok(v, "\n") ); zeiger->alter.tag=at; zeiger->alter.monat=am; zeiger->alter.jahr=aj; zeiger->eingest.tag=et; zeiger->eingest.monat=em; zeiger->eingest.jahr=ej; zeiger->gehalt=geh; /* Wir fügen das neue Element ein. */ zeiger->next=zeiger1->next; zeiger->previous=zeiger1; zeiger1->next=zeiger; zeiger1->next->previous=zeiger; } else { printf("Name wurde nicht eingefuegt!!! " "(Weiter mit <ENTER>"); getchar(); } } } /* Funktion zum Vergleichen von Nachname und bei Gleichheit * Vorname. Somit wird bei gleichem Nachnamen nach dem Anfangs- * buchstaben des Vornamens sortiert. */ int vergleiche(struct angestellt *n1, struct angestellt *n2) { int z = strcmp(n1->name,n2->name); /* Falls z einen Wert ungleich 0 hat, gibt es den Namen noch * nicht. Somit können wir den Wert an die Funktion * zurückgeben, den wir durch strcmp erhalten haben. */ if(z) return z; /* Wenn diese Funktion ausgeführt wird, so existiert dieser * Name schon. Somit vergleichen wir die Vornamen. */ return(strcmp(n1->vorname,n2->vorname)); } /* die gesamte Liste in der Datei "personal.dat" speichern */ void speichern(FILE *datei) { struct angestellt *zeiger; /* im "w+" - Modus öffnen */ if(datei_oeffnen_lesen_schreiben(&datei)) { zeiger=anfang; while(zeiger != NULL) { fwrite(zeiger,sizeof(struct angestellt),1,datei); zeiger=zeiger->next; } } fclose(datei); } /* Beim Start des Programms alle Elemente aus der Datei * "personal.dat" laden. "Laden" ist nicht ganz richtig. * Wir lesen zuerst die einzelnen Elemente aus der Datei * "personal.dat" und übergeben jedes einzelne Element * an die Funktion sortiert_eingeben. */ int laden(FILE *datei) { struct angestellt zeiger; if(datei_oeffnen_lesen(&datei)) { while(fread(&zeiger,sizeof(struct angestellt),1,datei)) { sortiert_eingeben(zeiger.name,zeiger.vorname, zeiger.alter.tag,zeiger.alter.monat, zeiger.alter.jahr,zeiger.eingest.tag, zeiger.eingest.monat,zeiger.eingest.jahr, zeiger.gehalt ); } return 1; } return 0; } /* Funktion zum Ãffnen einer Datei im Nur-Lesen-Modus "r" */ int datei_oeffnen_lesen(FILE **datei) { if((*datei = fopen(datname,"r")) == NULL) { fprintf(stderr,"Konnte \"personal.dat\" " "nicht oeffnen!\n"); printf("<ENTER>"); getchar(); return 0; } return 1; } /* Falls die Datei "personal.dat" noch nicht existiert, wird sie * erzeugt. */ int datei_oeffnen_erstellen(FILE **datei) { if((*datei = fopen(datname,"w+")) == NULL) { printf("Konnte \"personal.dat\" nicht erstellen\n"); return 0; } return 1; } /* Datei zum Lesen und Schreiben öffnen. Der Inhalt der Datei * wird dabei überschrieben. */ int datei_oeffnen_lesen_schreiben(FILE **datei) { if((*datei = fopen(datname,"w+")) == NULL) { printf("Kann \"personal.dat\" nicht zum" " beschreiben oeffnen!\n"); printf("<ENTER>"); getchar(); return 0; } return 1; } /* Funktion, um einen Löschvorgang rückgängig zu machen */ void rueckgaengig_loeschen(void) { char n[MAX],vn[MAX]; int at,am,aj,et,em,ej; long geh; if(stack_ptr->next != NULL) { strcpy(n, stack_ptr->next->name); strcpy(vn,stack_ptr->next->vorname); at=stack_ptr->next->alter.tag; am=stack_ptr->next->alter.monat; aj=stack_ptr->next->alter.jahr; et=stack_ptr->next->eingest.tag; em=stack_ptr->next->eingest.monat; ej=stack_ptr->next->eingest.jahr; geh=stack_ptr->next->gehalt; sortiert_eingeben(n,vn,at,am,aj,et,em,ej,geh); pop(); } else { printf("Kein Element mehr vorhanden zum" " \"Rueckgängig Loeschen\"\n"); printf("<ENTER>"); getchar(); } } int main(void) { int wahl; char dname[MAX]; FILE *datei; struct angestellt *emptystack; /* Stack mit dummy initialisieren */ stackinit(); if(laden(datei)) ; else if(datei_oeffnen_erstellen(&datei)) { start(); printf("\"personal.dat\" neu erstellt\n"); printf("<ENTER>"); getchar(); fclose(datei); } else { fprintf(stderr,"Konnte \"personal.dat\" weder" " erstellen noch finden\n"); return EXIT_FAILURE; } do { printf("Personaldaten - Verwaltung\n"); printf("==========================\n"); printf("1 : Eingabe\n"); printf("2 : Ausgabe\n"); printf("3 : Namen loeschen\n"); printf("4 : Alles loeschen\n"); printf("5 : Speichern\n"); printf("6 : Rueckgängig Loeschen\n"); printf("0 : Ende\n"); printf("Sie haben %d Leute an Personal\n",counter); printf("Ihre Wahl : "); scanf("%d",&wahl); getchar(); switch(wahl) { case 1 : eingabe(); break; case 2 : ausgabe(); break; case 3 : printf("Welchen Namen : "); fgets(dname, MAX, stdin); loesche( strtok(dname, "\n") ); break; case 4 : loesche_alles(); break; case 5 : speichern(datei); break; case 6 : rueckgaengig_loeschen(); break; case 0 : break; default : printf("Falsche Eingabe!!!\n"); } } while(wahl != 0); /* Wir entleeren unseren stack_ptr. */ while((emptystack=stack_ptr->next) != NULL) pop(); free(stack_ptr); return EXIT_SUCCESS; } In diesem Listing ist der Einsatz der Funktionen push() und pop() noch einigermaÃen überschaubar. Bei umfangreichen Projekten passiert es aber schnell, dass man den Ãberblick vor lauter push() und pop() verliert. Damit Sie dann im Fall der Fälle beim Debuggen Ihres Quellcodes wenigstens beim Stack den Ãberblick behalten, sollten Sie die Anzahl der Pushs und Pops mitzählen und entsprechend reagieren. Ein mögliches Beispiel könnte dabei so aussehen: > /* count_push_pop.c */ #include <stdio.h> #include <stdlib.h> #define DEBUG 1 #ifdef DEBUG int push_cnt=0, pop_cnt=0; #endif void push(void) { #ifdef DEBUG push_cnt++; printf("Anzahl push : %d\n", push_cnt); #endif /* Ausführung von push */ } void pop(void) { #ifdef DEBUG pop_cnt++; printf("\t\tAnzahl pop : %d\n", pop_cnt); if(pop_cnt > push_cnt) printf("Schwerer Fehler: pop_cnt darf nie groesser" " als push_cnt sein\n"); #endif /* Ausführung von pop */ } int main(void) { push(); push(); pop(); push(); pop(); pop(); pop(); /* Fehler */ return EXIT_SUCCESS; } # 21.4 Queues nach dem FIFO-Prinzip ## 21.4 Queues nach dem FIFO-Prinzip Eine weitere Art der abstrakten Datenstrukturen sind Queues (dt.: Warteschlangen). Queues können Sie sich vorstellen wie eine Warteschlange an der Einkaufskasse. Der Kunde, der sich als Erster angestellt hat, kommt auch als Erster dran. Alle anderen Kunden müssen sich immer hinten anstellen und warten, bis sie an der Reihe sind (sollten sie zumindest). Die Operationen einer Queue (Element hineinschieben und Element herausholen) werden Put und Get genannt. Im Gegensatz zum Stack erscheinen die Elemente in der gleichen Reihenfolge, in der sie hineingesteckt wurden. Eine Queue wird deshalb auch First-in-First-out-Datenstruktur (FIFO-Datenstruktur) genannt. Als Modell einer Queue können Sie sich ein Rohr vorstellen, das an beiden Enden offen ist. An einem Ende werden neue Elemente hineingeschoben, am anderen Ende werden sie wieder entnommen. Wie auch schon der Stack setzt sich die Queue aus zwei grundlegenden Funktionen zusammen: * get() – ein neues Element wird am Ende der Queue angefügt. * put() – ein Element wird am anderen Ende entnommen. Abbildung 21.48 verdeutlicht das Prinzip einer Queue: Abbildung 21.48 Eine Warteschlange und ihre Funktionen »get()« und »put()« In der Praxis können Sie Queues recht vielseitig einsetzen. Eine interessante Lösung für das umfangreiche Listing, das Sie in Abschnitt 21.3 erstellt haben, wäre, das Speichern von Daten mithilfe einer Queue zu realisieren. Sinn macht dies vor allem bei einem System, bei dem mehrere User gleichzeitig auf Daten zugreifen müssen – insbesondere dann, wenn mehrere User versuchen, gleichzeitig in dieselbe Datei zu schreiben. Mit den Queues können Sie dabei sogenannte Deadlocks vermeiden. Deadlock | | --- | | Keine Sorge, ich werde das Thema hier nicht wieder auf das mittlerweile schon recht umfangreiche Listing ausweiten. Wenn Sie wollen, können Sie den Suchbegriff »Queues C« einmal in eine Suchmaschine eingeben. Sie werden dabei eine Menge Anwendungsbeispiele – auch betriebssystemspezifische – finden. Ein Szenario: Damit ein Arzt sich einen Ãberblick darüber verschaffen kann, ob noch Patienten im Wartezimmer sind und vor allem welcher Patient als Nächstes an der Reihe ist, soll ein Programm geschrieben werden. Die Daten eines neuen Patienten werden von der Assistentin am Empfang eingegeben. Zuerst schreiben wir die Funktion zum Initialisieren einer Warteschlange: > int schlange_init(void) { if((dummy= malloc(sizeof(struct reservierung))) != NULL) { strcpy(dummy->name,"dummy"); strcpy(dummy->vorname,"dummy"); dummy->nummer=0; dummy->previous=NULL; return 1; } else { fprintf(stderr, "Konnte keinen Speicher " "reservieren!!\n"); return 0; } } Auch hierzu wird als Kopf eine Art dummy verwendet. Dieser zeigt immer den Anfang der Warteschlange an. Zuerst wird ein Speicherplatz für dummy reserviert und anschlieÃend mit sinnlosen Werten initialisiert. Der previous-Zeiger zeigt somit am Anfang wieder auf NULL: Abbildung 21.49 Eine »leere« Warteschlange Als Nächstes wird eine Funktion benötigt, die ein neues Element immer an das Ende der Warteschlange hängt: > int put(struct reservierung *neu) { struct reservierung *zeiger; /* Ist es das 1. Element in der Schlange? */ if(dummy->previous == NULL) { /* Es ist das 1. Element. */ dummy->previous=neu; neu->previous=NULL; return 1; } /* Es ist nicht das 1. Element. */ else { zeiger=dummy; /* Wir suchen das Ende der Schlange */ while(zeiger->previous != NULL) zeiger=zeiger->previous; zeiger->previous=neu; neu->previous=NULL; return 1; } } Zuerst wird überprüft, ob sich hinter dem Anfang der Warteschlange ein Element befindet. Das ist am Anfang nicht der Fall, und somit wird ein neues Element hinten angefügt: > dummy->previous=neu; Das neue Element zeigt hinter sich momentan noch auf gar nichts. Hier sehen Sie den aktuellen Stand: Abbildung 21.50 Ein neues Element wird hinten angefügt. Falls dummy schon hinter sich auf ein Element zeigt, wird mit > zeiger=dummy; while(zeiger->previous != NULL) zeiger=zeiger->previous; die Warteschlange von vorn bis zum Ende durchlaufen, bis zeiger->previous auf das Ende der Warteschlange (NULL) verweist. AnschlieÃend wird, wie schon das erste Element der Warteschlange, das neue Element hinten angehängt. Als Nächstes wird noch eine Funktion benötigt, um das eingefügte Element in der Warteschlange wieder zu entfernen und das zweite Element in der Warteschlange zum ersten zu machen. Hier sehen Sie die Funktion dazu: > void get(void) { struct reservierung *zeiger; /* Ist überhaupt etwas in der Schlange? */ if(dummy->previous != NULL) { /*Es ist...!*/ zeiger=dummy->previous; dummy->previous=zeiger->previous; free(zeiger); } else fprintf(stderr,"Es sind keine Patienten " "im Wartezimmer.....\n"); } Zuerst wird überprüft, ob überhaupt ein Nachfolger von dummy vorhanden ist. Falls nicht, ist die Liste leer. Ist die Liste nicht leer, dann bekommt ein Zeiger die Adresse des ersten Elements in der Warteschlange: > zeiger=dummy->previous; Abbildung 21.51 Das zuerst eingefügte Element entfernen Bevor Sie das erste Element, auf das der Zeiger zeiger verweist, mit free(zeiger) freigeben können, muss noch eine Zeile Code eingefügt werden, damit das (noch) zweite Element zum ersten Element in der Warteschlange wird: > dummy->previous=zeiger->previous; Abbildung 21.52 Das zuerst eingefügte Element »aushängen« > free(zeiger); Abbildung 21.53 Speicherplatz des ersten Elements wurde freigegeben. Dies sind alle Funktionen einer Warteschlange. Jetzt folgt das Demonstrationsprogramm, das diese Funktionen einsetzt und natürlich enorm erweiterbar ist: > /* queues.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 20 struct reservierung { char name[MAX]; char vorname[MAX]; int rnummer; struct reservierung *previous; }; struct reservierung *dummy; static int nummer = 1; int schlange_init(void) { if((dummy=malloc(sizeof(struct reservierung))) != NULL) { strcpy(dummy->name,"dummy"); strcpy(dummy->vorname,"dummy"); dummy->rnummer=0; dummy->previous=NULL; return 1; } else { fprintf(stderr,"Konnte keinen Speicher reservieren!!\n"); return 0; } } /* Wir hängen ein neues Element an das Ende der Schlange. */ int put(struct reservierung *neu) { struct reservierung *zeiger; /* Ist es das 1. Element in der Schlange? */ if(dummy->previous == NULL) { /* Es ist das 1. Element. */ dummy->previous=neu; neu->previous=NULL; return 1; } /* Es ist nicht das 1. Element. */ else { zeiger=dummy; /* Wir suchen das Ende der Schlange. */ while(zeiger->previous != NULL) zeiger=zeiger->previous; zeiger->previous=neu; neu->previous=NULL; return 1; } } /* Wir benötigen das 1. Element der Liste, das wir auch als 1. * eingegeben haben. */ void get(void) { struct reservierung *zeiger; /* Ist überhaupt etwas in der Schlange? */ if(dummy->previous != NULL) { /* Es ist...! */ zeiger=dummy->previous; dummy->previous=zeiger->previous; free(zeiger); } else fprintf(stderr,"Es sind keine Patienten " "im Wartezimmer.....\n"); } void eingabe(void) { struct reservierung *neu; char n[MAX],vn[MAX]; if((neu=(struct reservierung *) malloc(sizeof(struct reservierung))) != NULL) { printf("Name.....: "); fgets(n, MAX, stdin); strcpy(neu->name, strtok(n,"\n")); printf("Vorname..: "); fgets(vn, MAX, stdin); strcpy(neu->vorname,strtok(vn,"\n")); printf("Nummer...: "); printf("%d\n",neu->rnummer = nummer++); neu->previous=NULL; put(neu); } } void ausgabe(void) { if(dummy->previous != NULL) { printf("\n%s, %s Nummer.: %d \n\n", dummy->previous->name,dummy->previous->vorname, dummy->previous->rnummer); get(); } else printf("Keine Patienten im Wartezimmer vorhanden!!!\n"); } int main(void) { int wahl; schlange_init(); do { printf("-1- Reservierung eingeben\n"); printf("-2- Naechster Patient\n"); printf("-3- Programmende\n\n"); printf("Ihre Wahl : "); scanf("%d",&wahl); getchar(); switch(wahl) { case 1 : eingabe(); break; case 2 : ausgabe(); break; case 3 : if(dummy->previous != NULL) { printf("Es sind noch Patienten" " im Wartezimmer!!!\n"); wahl = 4; /* Abhauen gilt nicht */ } break; case 4 : break; default : printf("Falsche Eingabe!!\n\n"); } } while(wahl != 3); printf("\n\nFeierabend\n"); return EXIT_SUCCESS; } Hiermit ist der Abschnitt »Lineare Listen« erst einmal beendet. Später, in Kapitel 22, »Algorithmen«, wird dieses Wissen um den Bereich der binären Bäume erweitert. # 21.5 Dynamisches Array mit flexiblen Elementen ## 21.5 Dynamisches Array mit flexiblen Elementen Neu ab dem C99-Standard ist auch die Möglichkeit, das letzte Element in einer Struktur als unvollständiges Array ohne Längenangabe zu deklarieren. Dieses Feature kann man sich zunutze machen, um beispielsweise ein dynamisches Array zu erstellen. Hier sehen Sie ein Beispiel für ein solch flexibles Element: ``` typedef struct { int len; int iarray[]; } Vint_t; ``` Sie müssen hierbei allerdings berücksichtigen, dass flexible Elemente nicht bei der GröÃe der Struktur beachtet werden. Das Alignment (Füllbyte) wird hierbei trotzdem eingehalten. Um hier also beispielsweise für die Struktur Vint_t Speicher zu reservieren, müssen Sie beachten, dass Sie extra für das flexible Element ebenfalls Speicherplatz reservieren. Folgendes reicht also nicht aus: > Vint_t *Viptr = malloc ( sizeof( Vint_t) ); Hier haben Sie zwar Speicher für die Struktur reserviert, aber nicht für die flexiblen Elemente. Somit muss die Allokation von Speicher wie folgt aussehen: ``` #define LEN 10 // Anzahl flexibler Elemente ... Vint_t *Viptr = malloc ( sizeof(Vint_t) + LEN*sizeof(int) ); Viptr->len = LEN; ``` Hier folgt ein komplettes Beispiel dazu. Es wird Platz für eine Struktur vom Typ Vint_t mit 10 flexiblen Elementen reserviert. Die Elemente werden in der Schleife mit einem sinnlosen Wert versehen und anschlieÃend innerhalb einer anderen Schleife wieder ausgegeben. > /* flexibel.c */ #include <stdio.h> #include <stdlib.h> #define LEN 10 typedef struct { int len; int iarray[]; } Vint_t; int main(void) { Vint_t *Viptr = malloc(sizeof(Vint_t) + LEN*sizeof(int)); Viptr->len = LEN; for( int i = 0; i < Viptr->len; i++ ) Viptr->iarray[i] = i*i; for( int i = 0; i < Viptr->len; i++ ) printf("Viptr->iarray[%d]: %3d\n", i ,Viptr->iarray[i]); return EXIT_SUCCESS; } Eine Initialisierung von flexiblen Elementen ist laut C99-Standard nicht erlaubt. Ein Beispiel dafür wäre: > // Gemäà C99-Standard nicht zulässig Vint_t Viarr1 = { 4, { 1, 2, 4, 8 }}; # 22.2 Wie setze ich Algorithmen ein? ## 22.2 Wie setze ich Algorithmen ein? Egal, ob Sie jetzt Arrays oder verkettete Listen verwenden, die Algorithmen in den folgenden Abschnitten lassen sich meist mit wenigen Anpassungen implementieren – daher auch die Voraussetzung, dass Sie mit den Grundlagen der Programmierung in C gut vertraut sind. Aber deshalb haben Sie schlieÃlich dieses Buch gekauft. # 22.3 Sortieralgorithmen ## 22.3 Sortieralgorithmen Viele Programme und Computer (Server) erledigen oft den lieben langen Tag nichts anderes, als Daten zu sortieren. Wenn Sie das Sortieren verstanden haben, wird es Ihnen nicht mehr schwerfallen, andere Algorithmen zu verstehen. Das Sortieren könnte man sozusagen auch als »Basics für Algorithmen« bezeichnen. Hier einige Typen von Sortieralgorithmen: * Internes Sortieren – internes Sortieren findet innerhalb des RAMs (Arbeitsspeicher) statt. Dabei werden meist Daten an das Programm geschickt und werden sortiert wieder ausgegeben. * Externes Sortieren – beim externen Sortieren werden externe Speicherquellen (Festplatte, Streamer, Tape, ...) verwendet. Während des externen Sortierens werden zahlreiche Lese- und Schreibzugriffe auf externe Quellen ausgeführt. Externes Sortieren wird genutzt, wenn die Daten zum Sortieren nicht auf einmal im RAM verarbeitet werden können. * Vergleichendes Sortieren – dabei wird häufig ein Schlüssel zum Sortieren verwendet. Dieser Schlüssel besteht meist nur aus einem kleinen Teil der Daten, der das Sortieren steuert. * Stabiles Sortieren – stabil wird sortiert, wenn z. B. eine Arbeitnehmerliste, die nach Alphabet sortiert ist, nach Gehalt sortiert wird, ohne dass dabei die alphabetische Liste durcheinandergerät. Im Folgenden werden häufig Arrays zum Sortieren verwendet. Diese sollten Sie sich als Schlüssel einer Datenstruktur vorstellen. Die Funktionen sind so aufgebaut, dass sie jederzeit mit ein wenig Tipparbeit an die eigenen Bedürfnisse angepasst werden können. Primär geht es darum, Ihnen die einzelnen Sortierverfahren näherzubringen, speziell deren Funktionen. Die Implementierung ist zumeist problemabhängig und richtet sich nach der Art der Daten, die es zu sortieren gilt. ### 22.3.1 »Selection Sort« – sortieren durch Auswählen Der erste Sortieralgorithmus ist Selection Sort. Dieser Algorithmus sucht sich als Erstes das kleinste Element in der Liste, merkt es sich und tauscht es gegen das Element am Anfang aus, sodass sich dann das kleinste Element ganz am Anfang befindet. Als Nächstes wird das zweitkleinste Element in der Liste gesucht und wird gegen das an zweiter Stelle platzierte Element der Liste ausgetauscht usw. Auf diese Weise haben immer die Elemente auf der linken Seite der aktuellen Position einen festen Platz und werden nicht mehr geändert. Abbildung 22.1 verdeutlicht den Vorgang: Abbildung 22.1 Sortieren durch Auswählen Der Quellcode dazu sieht so aus: > /* selektion.c */ #include <stdio.h> #include <stdlib.h> void selection(int *array, int elemente) { int index,index_klein, wert, wert_klein; /* Schleife wird von links nach rechts durchlaufen. */ for(index = 0; index < elemente; index++) { /* aktuelle Position */ wert=index; /* Schleife läuft durch bis ein kleineres Element als * die aktuelle Position gefunden wurde oder bis zum Ende, * was bedeutet, die aktuelle Position ist schon * das kleinste Element. */ for(index_klein = index+1; index_klein <= elemente; index_klein++) { /* Ein kleineres Element gefunden? */ if(array[index_klein] < array[wert]) /* Neues kleinstes Element */ wert=index_klein; } /* kleinstes Element an die aktuelle * Position falls nötig */ if(wert != index) { wert_klein=array[wert]; array[wert]=array[index]; array[index]=wert_klein; } } } int main(void) { int i; /* das Array zum Sortieren */ int test_array[] = { 5, 2, 7, 9, 1, 4, 3, 8, 6 }; int N = sizeof(test_array)/sizeof(int); selection(test_array, N-1); for(i = 0; i < N; i++) printf("%d ", test_array[i]); printf("\n"); return EXIT_SUCCESS; } Natürlich können Sie mit Selection Sort auch andersherum sortieren, also vom gröÃten Element abwärts. In diesem Fall muss nur die if-Abfrage geändert werden: > if(array[index_klein] > array[wert]) Der Vorteil von Selection Sort liegt darin, dass jedes Element höchstens einmal bewegt wird. ### 22.3.2 Insertion Sort Das Prinzip von Insertion Sort (Sortieren durch direktes Einfügen) ist relativ einfach. Die einzelnen Elemente werden wieder von vorne nach hinten durchlaufen. Von der aktuellen Position aus wird jedes Element von rechts nach links weitergereicht – und das so lange, bis das bewegte Element gröÃer oder gleich dem Element ist, das an der im Augenblick abgefragten Position liegt. Der Platz für das Element, das verschoben wird, ist frei. Diese Lücke wird mit dem entsprechenden Wert an der richtigen Stelle gefüllt. Bildlich können Sie sich Insertion Sort folgendermaÃen vorstellen: Abbildung 22.2 Insertion Sort Der folgende Quellcode soll diesen Algorithmus noch verständlicher machen: > /* insertion.c */ #include <stdio.h> #include <stdlib.h> void insertion(int *array, int elemente) { int index,index_klein,wert_klein; /* Schleife von links-1 nach rechts */ for(index=1; index<=elemente; index++) { /* aktuelle Position zwischenspeichern */ wert_klein=array[index]; /* Kleineren Wert als wert_klein suchen. Schleife läuft * von aktueller Position von rechts nach links durch. */ for( index_klein=index; array[index_klein-1] > wert_klein&&index_klein > 0; index_klein-- ) /* wenn Vorgänger gröÃer als aktuelles * Element in wert_klein */ array[index_klein] = array[index_klein-1]; /* gespeichertes Element an neue Position -> * Lücke auffüllen */ array[index_klein]=wert_klein; } } int main(void) { int i; /* das Array zum Sortieren */ int test_array[] = { 5, 2, 7, 9, 1, 4, 3, 8, 6 }; int N = sizeof(test_array)/sizeof(int); insertion(test_array, N-1); for(i = 0; i < N; i++) printf("%d ", test_array[i]); printf("\n"); return EXIT_SUCCESS; } Abbildung 22.3 Geklammerte Werte symbolisieren den Elementetausch. Das aktuelle Element wird hier in wert_klein gespeichert. Jetzt wird so lange umdisponiert, bis entweder ein Element kleiner als wert_klein ist oder bis Sie am Anfang des Arrays (Index 0) angekommen sind (was bedeuten würde, dass wert_klein das kleinste Element im Array ist). Wie auch schon bei Selection Sort sind die Elemente bei Insertion Sort auf der linken Seite sortiert; nur mit dem Unterschied, dass dies noch keine endgültige Stellung wie bei Selection Sort bedeutet. ### 22.3.3 Bubble Sort Bubble Sort ist ein recht einfaches Sortierverfahren. Dabei wird das vollständige Array durchlaufen, und jedes Mal – wenn notwendig – werden die benachbarten Elemente miteinander vertauscht. Nach jedem Durchlauf bekommt immer das letzte Element einen festen Platz. Daher macht es auch Sinn, eine rückwärts zählende Schleife von dieser Position an einzusetzen. Hier sehen Sie den Quellcode zu Bubble Sort: > /* bubble.c */ #include <stdio.h> #include <stdlib.h> void bubble(int *array, int elemente) { int i,temp; while(elemente--) for(i = 1; i <= elemente; i++) if(array[i-1] > array[i]) { temp=array[i]; array[i]=array[i-1]; array[i-1]=temp; } } int main(void) { int i; /* das Array zum Sortieren */ int test_array[] = { 5, 2, 7, 9, 1, 4, 3, 8, 6 }; int N = sizeof(test_array)/sizeof(int); bubble(test_array, N); for(i = 0; i < N; i++) printf("%d ", test_array[i]); printf("\n"); return EXIT_SUCCESS; } Da nach jedem Durchlauf das gröÃte Element ganz nach rechts geholt wird und dies nicht mehrmals verglichen werden sollte, wurde von dieser Position aus eine rückwärts zählende Schleife eingesetzt: > while(elemente--) Abbildung 22.4 zeigt die Arbeitsweise von Bubble Sort: Abbildung 22.4 »Bubble Sort« in Aktion Auf die letzten Durchläufe wurde in der Darstellung verzichtet, da keine Daten mehr verschoben werden. ### 22.3.4 Shellsort Shellsort ist eine Erweiterung von Insertion Sort. Anstatt jedes benachbarte Element wie bei Insertion Sort zu vergleichen und zu sortieren, vergleicht Shellsort jedes n-te Element (bei beliebigem Anfangselement). Damit ist es möglich, Elemente zu sortieren, die in gröÃeren Entfernungen voneinander liegen. Ist der Abstand für n beispielsweise 4, dann setzen sich folgende Gruppen von Elementen mit dem Index 0, 4, 8, 12  und 1, 5, 9, 13  2, 6, 10, 14  3, 7, 11, 15  usw. zusammen. Diese Gruppen werden einzeln sortiert. Danach wird n verringert, und dann werden die Gruppen n-1 sortiert. Dies geschieht so lange, bis n==1 ist und somit im letzten Durchlauf keine Unterteilung mehr stattfindet. Ist n gleich von Anfang an 1, könnten Sie sich den Aufwand sparen, da dies dem »Insertion Sort«-Algorithmus entspräche. Natürlich hängt n von den Werten ab, die sortiert werden. Man spricht dabei von Distanzfolgen. Je besser diese Folge ist, desto schneller werden die Daten sortiert. Die Suche nach der optimalen Folge ist Aufgabe des Programmierers. Hier sehen Sie den Quellcode zu Shellsort: > /* shellsort.c */ #include <stdio.h> #include <stdlib.h> void shellsort (int *array, int elemente) { int i, j, temp, n; /* Anfangswert für die Distanz errechnen */ for ( n = 1; n <= elemente/9; n = 3*n+1); for (; n > 0; n /= 3) { for (i = n; i <= elemente; i++) { temp = array[i]; /* GröÃer als temp und nicht elemente * sowie >= und nicht > */ for(j = i; j >= n && array[j-n] > temp; j -= n) { array[j] = array[j-n]; } array[j] = temp; } } } int main(void) { int i; /* das Array zum Sortieren */ int test_array[] = { 5, 0, 2, 7, 9, 1, 4, 3, 8, 6 }; int N = sizeof(test_array)/sizeof(int); shellsort(test_array, N-1); for(i = 0; i < N; i++) printf("%d ", test_array[i]); printf("\n"); return EXIT_SUCCESS; } Jetzt soll gezeigt werden, wie Sie die optimale Distanzfolge von Daten für Shellsort ermitteln. Es wird ein Array mit 10 Millionen Elementen erstellt, das Zahlen in absteigender Reihenfolge enthält. In diesem Fall müssten alle Elemente bei der Sortierung ausgetauscht werden. Getestet wird mithilfe einer Schleife und den Distanzfolgen von 2 bis 10. Für das Profiling wird hierbei die Funktion clock() verwendet, die für diesen Zweck vollkommen ausreichen dürfte (mehr zum Profiling entnehmen Sie bitte dem entsprechenden Abschnitt 19.2, »Laufzeitmessung (Profiling)«). Hier sehen Sie das Beispiel mit den verschiedenen Distanzfolgen: > /* profile_shellsort.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX 10000000 #define MAX_TEST 10 /* das Array zum Sortieren */ int test_array[MAX]; void init_test_array(void) { int i,j; for(i = MAX, j = 0; i >= 0; i--,j++) test_array[j] = i; } void shellsort(int *array, int elemente, int distanz) { int i, j, temp, n = elemente; for(; n > 0; n /= distanz) for (i = n; i <= elemente; i++) { temp = array[i]; /* GröÃer als temp und nicht elemente * sowie >= und nicht > */ for(j = i; j >= n && array[j-n] > temp; j -= n) { array[j] = array[j-n]; } array[j] = temp; } } int main(void) { int distanz_folge; float zeit; clock_t start, ende; for(distanz_folge =2; distanz_folge <= MAX_TEST; distanz_folge++) { init_test_array(); start = clock(); shellsort(test_array, MAX-1, distanz_folge); ende = clock(); /* Ergebnis der Laufzeitmessung in Sekunden */ zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Die Laufzeitmessung der Distanzfolge " " %d ergab %2.2f Sekunden\n" ,distanz_folge,zeit); } return EXIT_SUCCESS; } Je nach Power des Rechners erhalten Sie folgende Ausgabe (als Beispiel ein 1700–MHz-Pentium 4 mit 256 MB RAM): Abbildung 22.5 Ermitteln der optimalen Distanzfolge von Shellsort In diesem Fall scheint eine Distanzfolge zwischen 3 und 6 das optimale Ergebnis zu liefern. Diese Tests der Laufzeitmessungen mit Shellsort werden Sie wohl immer durchführen müssen, da bisher noch niemand in der Lage war, Shellsort genau zu analysieren. Aber verglichen mit Insertion Sort läuft Shellsort immer schneller ab. Zum Vergleich kann hierbei Insertion Sort (Distanzfolge = 1) mit eingebaut werden. Dabei sollte aber die Anzahl der Elemente reduziert werden, weil Insertion Sort eine Weile mit ihnen beschäftigt sein wird. ### 22.3.5 Quicksort Ein oft eingesetzter Algorithmus ist Quicksort, da seine Implementierung nicht allzu schwer ist. Aufgrund ihrer häufigen Verwendung wurde diese Funktion in die ANSI-C-Bibliothek mit aufgenommen (qsort). Quicksort funktioniert nach dem Prinzip »Teile und herrsche«, also rekursiv. Die Daten werden immer in zwei Teile zerlegt und wieder sortiert. Diese zwei Teile werden wiederum jeweils in zwei Teile zerlegt und sortiert usw., bis die Daten sortiert sind. Die Rekursion beendet sich, wenn das Teilstück aus nur noch einem Element besteht. Hier sehen Sie den Quellcode von Quicksort: > /* quicksort.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX 50000 /* das Array zum Sortieren */ int test_array[MAX]; void my_qsort(int*, int*); void init_test_array(void) { int i, j; for(i = MAX,j=0; i >= 0; i--,j++) test_array[j] = i; } void print_test_array(void) { int i; for(i=0;i<MAX; i++) printf("%d ",test_array[i]); } /* Die Funktion erhält einen Zeiger auf das erste * und einen zweiten Zeiger auf das letzte Element. * Hier werden dazu die Namen »links« und »rechts« verwendet. */ void my_qsort(int *links, int *rechts) { int *ptr1 = links; int *ptr2 = rechts; int w, x; /* x bekommt die Anfangsadresse der * Mitte von links und rechts. * Anstatt der Bitverschiebung hätten Sie * auch einfach »geteilt durch 2« rechnen können. */ x = *(links + (rechts - links >> 1)); do { while(*ptr1 < x) ptr1++; while(*ptr2 > x) ptr2--; if(ptr1 > ptr2) break; w = *ptr1; *ptr1 = *ptr2; *ptr2 = w; } while(++ptr1 <= --ptr2); if(links < ptr2) my_qsort(links, ptr2); if(ptr1 < rechts) my_qsort(ptr1, rechts); } int main(void) { init_test_array(); my_qsort(test_array, test_array+MAX); print_test_array(); return EXIT_SUCCESS; } Im Gegensatz zu den anderen bisher verwendeten Algorithmen sieht dieser schon ein wenig kryptischer aus. Daher soll er auch etwas genauer analysiert werden. Wir gehen von folgenden unsortierten Werten aus: Abbildung 22.6 Werte sollen mit »Quicksort« sortiert werden. Aufgerufen wird die Funktion mit: > my_qsort(test_array, test_array+MAX); Somit zeigt in der Funktion my_qsort() der Zeiger links auf die Anfangsadresse von test_array, nämlich den Wert 20. Der rechte Zeiger verweist auf das Ende des Arrays, also den Wert 320. In der Funktion übernehmen zwei Zeiger diese Adressen: > int *ptr1 = links; int *ptr2 = rechts; Durch die darauf folgende Berechnung > x = *(links + (rechts - links >> 1)); bekommt die Variable x zunächst den Wert 100 zugewiesen. Denn im Klartext ergibt diese Rechnung auf Zahlen bezogen: > x = *(0 + (7 - 0 / 2)); Das Ergebnis dieser Berechnung beträgt 3, und die Zahl mit dem Index [3] lautet 100. Weiter geht es mit folgender Zeile: > while(*ptr1 < x) ptr1++; Der Zeiger ptr1 wird jetzt so lange inkrementiert, bis er auf ein Element zeigt, das gröÃer als oder gleich dem Element von x ist. Im aktuellen Beispiel ist dies der Wert 400. Abbildung 22.7 »ptr1« ist auf einen Wert gestoÃen, der gröÃer als »x« ist. Genauso verläuft dies mit dem Zeiger ptr2: > while(*ptr2 > x) ptr2--; Dieser wird so lange dekrementiert, bis er auf ein Element zeigt, das kleiner als oder gleich dem von x ist. Abbildung 22.8 »ptr2« ist auf einen Wert gestoÃen, der kleiner als »x« ist. Als Nächstes wird überprüft, ob ptr1 schon weiter ist als ptr2. Trifft dies zu, wird die do while-Schleife abgebrochen. Hier stimmt dies aber nicht, und somit werden die beiden Elemente, auf die ptr1 und ptr2 zeigen, vertauscht: > w = *ptr1; *ptr1 = *ptr2; *ptr2 = w; Abbildung 22.9 Werte von »ptr1« und »ptr2« tauschen Jetzt bewegen sich die beiden Zeiger mit > ++ptr1 <= --ptr2 aufeinander zu. Abbildung 22.10 Die Zeiger nähern sich einander. Danach folgen wieder: > while(*ptr1 < x) ptr1++; while(*ptr2 > x) ptr2--; Die Bedingung für den Zeiger ptr1 trifft bereits nach der ersten Inkrementierung zu (100<60), und der zweite Zeiger wird gar nicht dekrementiert (70>100). So ergibt sich folgender Zustand: Abbildung 22.11 Wieder wurden zwei Werte ausgemacht, wo »ptr1« nicht kleiner und »ptr2« nicht gröÃer als »x« sind. Jetzt werden wieder beide Elemente ausgetauscht: Abbildung 22.12 »ptr1«und »ptr2« nach dem Wertetausch Danach werden beide Zeiger wieder aufeinander zu bewegt, sodass sich jetzt folgendes Bild ergibt (siehe Abbildung 22.13). Abbildung 22.13 »ptr1« und »ptr2« treffen aufeinander. Nach den beiden Zeilen > while(*ptr1 < x) ptr1++; while(*ptr2 > x) ptr2--; ist jetzt die if-Bedingung (ptr1 > ptr2) wahr und bricht mit break die do while-Schleife ab. Folgender Zustand liegt dabei vor (siehe Abbildung 22.14). Abbildung 22.14 Ein Teilungsprozess findet statt. Damit wurde der erste Teilungsprozess beendet. Daran lässt sich auch schon feststellen, dass alles, was sich links von der Teilungslinie befindet, gröÃer, und alles, was rechts davon liegt, kleiner ist. Der Algorithmus funktioniert auch, wenn der Wert der Variablen x beispielsweise einem Wert entspricht, der weiter auÃen liegt. Die optimale Bedingung ist eine Teilung in der Mitte. Abbildung 22.15 Quicksort ist von der Anordnung der Daten abhängig. Nach der ersten Teilung sind nun weitere Schritte notwendig. Oder einfacher ausgedrückt: Im Prinzip sind nur noch zwei Schritte zu beachten: Es muss derselbe Vorgang für die linke und rechte Seite vorgenommen werden. In diesem Beispiel sind das die Zeilen: > if(links < ptr2) my_qsort(links, ptr2); if(ptr1 < rechts) my_qsort(ptr1, rechts); Damit wird der weitere Vorgang rekursiv für beide Seiten ausgeführt – und zwar so lange, bis die Adresse links kleiner als ptr2 und die Adresse rechts gröÃer als ptr1 ist. Einfach ausgedrückt ist dies der Fall, wenn kein Teilungsprozess mehr möglich ist. ### 22.3.6 qsort() Sollten Sie in der Praxis vorhaben, den qsort()-Algorithmus einzusetzen, können Sie auch den Quicksort-Algorithmus qsort() verwenden, der in der Standard-Headerdatei <stdlib.h> implementiert ist. Dieser läuft zumeist stabiler und sicherer ab als die Eigenkreation, da Fehler bei der Implementierung seltener sind. Die Syntax von qsort() lautet: > void qsort(void *base, size_t num, size_t size, int (*cmp)(void *elem1, void *elem2)); base ist die Adresse des ersten Elements in der Liste oder in einem Array, das es zu sortieren gilt. Die Anzahl der Elemente geben Sie mit num und die GröÃe der einzelnen Elemente mit size an. cmp ist eine Adresse auf eine Vergleichsfunktion, die Sie selbst implementieren müssen. SchlieÃlich kann qsort() nicht von vornherein wissen, welche Art von Daten (Strukturen, Arrays, Strings  ) Sie sortieren wollen. So bleibt qsort() immer für den Allgemeingebrauch verfügbar. Hierzu zeige ich die Funktion qsort() der Standard-Bibliothek im Zeitvergleich mit unserer Eigenkreation: > /* profile_quicksort.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX 5000000 /* das Array zum Sortieren */ int test_array[MAX]; void my_qsort(int*, int*); void init_test_array(void) { int i, j; for(i = MAX,j=0; i >= 0; i--,j++) test_array[j] = i; } /* Vergleichsfunktion für qsort() */ int cmp_integer(const void *wert1, const void *wert2) { return (*(int*)wert1 - *(int*)wert2); } /* Die Funktion erhält einen Zeiger auf das erste * und einen zweiten Zeiger auf das letzte Element. * Hier werden die Namen »links« und »rechts« verwendet. */ void my_qsort(int *links, int *rechts) { int *ptr1 = links; int *ptr2 = rechts; int w, x; /* x bekommt die Anfangsadresse der * Mitte von »links« und »rechts« * Statt der Bitverschiebung hätten Sie * auch einfach »geteilt durch 2« rechnen können. */ x = *(links + (rechts - links >> 1)); do { while(*ptr1 < x) ptr1++; while(*ptr2 > x) ptr2--; if(ptr1 > ptr2) break; w = *ptr1; *ptr1 = *ptr2; *ptr2 = w; }while(++ptr1 <= --ptr2); if(links < ptr2) my_qsort(links, ptr2); if(ptr1 < rechts) my_qsort(ptr1, rechts); } int main(void) { clock_t start,ende; init_test_array(); start = clock(); qsort(test_array, MAX, sizeof(int), cmp_integer); ende = clock(); printf("qsort() der Standard-Library: %.2f\n", (float)(ende-start) / (float)CLOCKS_PER_SEC); init_test_array(); start = clock(); my_qsort(test_array, test_array+MAX); ende = clock(); printf("Selbst geschriebene Quicksort-Funktion %.2f\n", (float)(ende-start) / (float)CLOCKS_PER_SEC); return EXIT_SUCCESS; } ### 22.3.7 Zusammenfassung der Sortieralgorithmen Jetzt werden die Sortieralgorithmen ein wenig analysiert. Es soll ein Beispiel erstellt werden, mit dem drei verschiedene Zustände von Daten sortiert werden. * Zuerst sollen Daten sortiert werden, bei denen das gröÃte Element ganz am Anfang ist und absteigend das kleinste Element ganz am Ende. * AnschlieÃend sollen Daten sortiert werden, die bereits in sortierter Form vorliegen. Denn es kann ja immer mal vorkommen, dass <NAME> die Daten sortiert hat und <NAME>üller wieder mal nichts davon weià und diese nochmals sortiert. * Im letzten Beispiel werden Daten sortiert, die mit Zufallsdaten belegt werden. Die Anzahl der Elemente ist in einem solchen Fall natürlich auch entscheidend. Es werden dafür 1000, 10.000 und am Schluss 100.000 Elemente verwendet, die nach den vorhandenen Zuständen sortiert werden sollen. Das Programm wurde der Ãbersicht halber etwas zusammengepresst. Es ist nur die Ausgabe des Programms von Interesse. Leiten Sie die Standardausgabe am besten in eine Textdatei um, indem Sie im Programm noch vor der for-Schleife in der main()- Funktion Folgendes eingeben: > freopen("benchmark.txt", "a+", stdout); Dies kann jetzt – abhängig vom Rechner – etwas dauern. Hier sehen Sie das kleine Benchmark dazu mit einigen Sortieralgorithmen: > /* sortbenchmark.c */ #include <stdio.h> #include <time.h> #include <stdlib.h> #define MAX 100000 /* ein Array von groÃen zu kleinen Werten sortieren */ int test_array[MAX]; void init_test_array(int elements) { int i, j; for(i = elements,j=0; i >= 0; i--,j++) test_array[j] = i; } /* ein bereits sortiertes Array */ void init_test_array2(int elements) { int i; for(i = 0; i <= elements; i++) test_array[i] = i; } /* ein Array mit (Pseudo)-Zufallszahlen */ void init_test_array3(int elements) { int i; for(i = 0; i <= elements; i++) test_array[i] = rand(); } /* Vergleichsfunktion für qsort() */ int cmp_integer(const void *wert1, const void *wert2) { return (*(int*)wert1 - *(int*)wert2); } /* Die Funktion erhält einen Zeiger auf das erste * und einen zweiten Zeiger auf das letzte Element. * Hier werden die Namen »links« und »rechts« verwendet. */ void my_qsort(int *links, int *rechts) { int *ptr1 = links; int *ptr2 = rechts; int w, x; /* x bekommt die Anfangsadresse der * Mitte von »links« und »rechts«. * Statt der Bitverschiebung hätten Sie * auch einfach »geteilt durch 2« rechnen können. */ x = *(links + (rechts - links >> 1)); do { while(*ptr1 < x) ptr1++; while(*ptr2 > x) ptr2--; if(ptr1 > ptr2) break; w = *ptr1; *ptr1 = *ptr2; *ptr2 = w; } while(++ptr1 <= --ptr2); if(links < ptr2) my_qsort(links, ptr2); if(ptr1 < rechts) my_qsort(ptr1, rechts); } void shellsort (int *array, int elemente) { int i, j, temp, n; /* Anfangswert für die Distanz errechnen */ for ( n = 1; n <= elemente/9; n = 3*n+1); for (; n > 0; n /= 3) { for (i = n; i <= elemente; i++) { temp = array[i]; /* GröÃer als temp und nicht elemente * sowie >= und nicht > */ for(j = i; j >= n && array[j-n] > temp; j -= n) { array[j] = array[j-n]; } array[j] = temp; } } } void selection(int *array, int elemente) { int i, j, mini, temp; for(i = 0; i < elemente; i++) { mini=i; for(j=i+1; j <= elemente; j++) { if(array[j] < array[mini]) mini=j; } temp=array[mini]; array[mini]=array[i]; array[i]=temp; } } void insertion(int *array, int elemente) { int i, j, temp; for(i = 1; i <= elemente; i++) { temp=array[i]; /* aktuelles Element zwischenspeichern */ for(j=i; array[j-1] > temp && j > 0; j--) /* solange der Vorgänger gröÃer ist als das * aktuelle Element in temp ... */ array[j] = array[j-1]; /* gespeichertes Element an neue Position */ array[j]=temp; } } void bubble(int *array, int elemente) { int i, temp; while(elemente--) for(i = 1; i <= elemente; i++) if(array[i-1] > array[i]) { temp=array[i]; array[i]=array[i-1]; array[i-1]=temp; } } int main(void) { int i; int elemente=1000; float zeit; clock_t start, ende; /* freopen("log.txt","a+",stdout); */ for(i=1; i<=3; i++, elemente*=10){ printf("\n\nSortieren von %d Elementen\n\n",elemente); printf("\n%d. Versuch : alle %d Elemente muessen " "sortiert werden\n\n",i,elemente); /* Selectionsort */ init_test_array(elemente); start = clock(); selection(test_array, elemente-1); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Selectionsort: %.2f Sekunden\n",zeit); /* Insertionsort */ init_test_array(elemente); start = clock(); insertion(test_array, elemente-1); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Insertionsort: %.2f Sekunden\n",zeit); /* Bubblesort */ init_test_array(elemente); start = clock(); bubble(test_array, elemente); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Bubblesort : %.2f Sekunden\n",zeit); /* Shellsort */ init_test_array(elemente); start = clock(); shellsort(test_array, elemente-1); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Shellsort : %.2f Sekunden\n",zeit); /* Quicksort */ if(elemente < 50000){ init_test_array(elemente); start = clock(); my_qsort(test_array, test_array+elemente); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Quicksort : %.2f Sekunden\n",zeit); } /* qsort aus der Standard-Bibliothek <stdlib.h> */ init_test_array(elemente); start = clock(); qsort(test_array, elemente, sizeof(int), cmp_integer); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("qsort : %.2f Sekunden\n",zeit); /* 2. Versuch, eine bereits sortierte Liste */ printf("\n%d. Versuch : keins der %d Elemente muss " "sortiert werden\n\n",i,elemente); /* Selectionsort */ init_test_array2(elemente); start = clock(); selection(test_array, elemente-1); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Selectionsort: %.2f Sekunden\n",zeit); /* Insertionsort */ init_test_array2(elemente); start = clock(); insertion(test_array, elemente-1); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Insertionsort: %.2f Sekunden\n",zeit); /* Bubblesort */ init_test_array2(elemente); start = clock(); bubble(test_array, elemente); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Bubblesort : %.2f Sekunden\n",zeit); /* Shellsort */ init_test_array2(elemente); start = clock(); shellsort(test_array, elemente-1); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Shellsort : %.2f Sekunden\n",zeit); /* Quicksort */ init_test_array2(elemente); start = clock(); my_qsort(test_array, test_array+elemente); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Quicksort : %.2f Sekunden\n",zeit); /* qsort aus der Standard-Bibliothek <stdlib.h> */ init_test_array2(elemente); start = clock(); qsort(test_array, elemente, sizeof(int), cmp_integer); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("qsort : %.2f Sekunden\n",zeit); /* 3. Versuch Zufallsdaten */ printf("\n%d. Versuch : %d Zufallszahlen muessen" "sortiert werden\n\n",i,elemente); /* Selectionsort */ init_test_array3(elemente); start = clock(); selection(test_array, elemente-1); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Selectionsort: %.2f Sekunden\n",zeit); /* Insertionsort */ init_test_array3(elemente); start = clock(); insertion(test_array, elemente-1); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Insertionsort: %.2f Sekunden\n",zeit); /* Bubblesort */ init_test_array3(elemente); start = clock(); bubble(test_array, elemente); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Bubblesort : %.2f Sekunden\n",zeit); /* Shellsort */ init_test_array3(elemente); start = clock(); shellsort(test_array, elemente-1); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Shellsort : %.2f Sekunden\n",zeit); /* Quicksort */ init_test_array3(elemente); start = clock(); my_qsort(test_array,test_array+elemente); ende = clock(); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("Quicksort : %.2f Sekunden\n",zeit); /* qsort aus der Standard-Bibliothek <stdlib.h> */ init_test_array3(elemente); start = clock(); qsort(test_array, elemente, sizeof(int), cmp_integer); zeit = (float)(ende-start) / (float)CLOCKS_PER_SEC; printf("qsort : %.2f Sekunden\n",zeit); }/* Ende for */ return EXIT_SUCCESS; } In Tabelle 22.1 finden Sie eine Analyse der einzelnen Sortierfunktionen. Bei einigen Algorithmen wurde die Anzahl der Elemente nochmals erhöht, da diese bei den Anforderungen eine kaum nennenswerte Zeit benötigen. Anzahl | Zustand | Selektion | Insertion | Bubble | Shell | my_qsort | qsort() | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Mithilfe dieser Analyse können Sie sich nun ein etwas detaillierteres Bild von der Effizienz der einzelnen Algorithmen machen. Natürlich sollten Sie diese Laufzeitmessung nicht allzu genau nehmen. Für eine exaktere und genauere Messung sollten Sie auf jeden Fall einen Profiler einsetzen. Denn das Programm zur Laufzeitmessung ist während der Ausführung sicherlich nicht das einzige Programm, das gerade auf Ihrem System läuft. Die Frage nach dem besten Algorithmus lässt sich allerdings auch mit solch einer Analyse nicht exakt klären. Diese ist auch sehr abhängig von der Verteilung und Art der Daten, die es zu sortieren gilt. AuÃerdem ist es auch möglich, die einzelnen Algorithmen weiter zu optimieren. Beim Thema Algorithmen kommen Sie nicht darum herum, weitere Literatur zurate zu ziehen. # 22.4 Suchalgorithmen – Grundlage zur Suche ## 22.4 Suchalgorithmen – Grundlage zur Suche Eine weitere grundlegende Arbeit, die ein PC zu verrichten hat, ist die Suche nach Daten. Daten mit bestimmten Informationen müssen aus einer groÃen Menge gespeicherter Informationen gefunden werden. Ein gutes Beispiel für die Suche ist eine Suchmaschine wie beispielsweise google.de, die sich mittlerweile zu einer der schnellsten und besten Suchmaschinen gemausert hat, und zwar dank eines Top-Algorithmus. Idealerweise verfügt jeder Datensatz unter anderem auch über einen bestimmten Schlüssel. Er wird bei der Suche nach einem Datensatz verwendet, beispielsweise so: > struct data { char ort[MAX]; unsigned int postleitzahlen; }; Dieses Beispiel stellt ein Verzeichnis für Postleitzahlen dar. Der Schlüssel ist in diesem Fall die Postleitzahl. Wird die Postleitzahl gefunden, gibt die Suche den zugehörigen Ort aus. Eine Voraussetzung der Suche ist natürlich ein vorangegangenes Sortieren. SchlieÃlich werden Daten ja sortiert, um sich die Suche zu erleichtern. Mithilfe der Suche lassen sich folgende Operationen durchführen: * Daten initialisieren * Daten einfügen * Daten löschen * Daten sortieren Anhand dieser Operationen können Sie erkennen, dass ohne Suche kaum eine richtige Datenorganisation möglich ist. ### 22.4.1 Lineare Suche Die einfachste und bequemste Form der Suche von Daten ist die lineare Suche (sequenzielle Suche). Bei der sequenziellen Suche werden die Daten vom Anfang bis zum Ende durchlaufen, bis ein Datensatz mit dem Suchergebnis übereinstimmt. Die lineare Suche hat folgende Vorteile: * einfachste Implementierung und Erstellung mit verketteten Listen oder Arrays * Es kann auch in nicht sortierten Daten gesucht werden. * Eine bereits sortierte Liste bleibt auch dann sortiert, wenn ein neues Element eingefügt wird. Der Nachteil der linearen Suche ist klar – bei einem groÃen Datensatz dauert die Suche ein wenig länger – speziell dann, wenn sich das gesuchte Element am Ende der Liste befindet. Hier sehen Sie ein einfaches Beispiel für eine sequenzielle Suche: > /* simple_search.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 255 struct plz{ char ort[MAX]; unsigned int postleit; }; struct plz postleitzahlen[100]; static int N; /* initialisieren */ void init(void) { N = 0; postleitzahlen[N].postleit = 0; strcpy(postleitzahlen[N].ort, "init"); } void einfuegen(unsigned int p, char *o) { postleitzahlen[++N].postleit = p; strcpy(postleitzahlen[N].ort, o); } void suche(unsigned int key) { int i; for(i=0; i<=N; i++) if(postleitzahlen[i].postleit == key) { printf("Der Ort zur Postleitzahl %d : %s\n", key,postleitzahlen[i].ort); return; } printf("Für den Wert %d konnte keine Postleitzahl " "gefunden werden!\n",key); } int main(void) { int wahl; unsigned int search, post; char new_ort[MAX]; init(); do { printf("-1- Postleitzahl suchen\n"); printf("-2- Postleitzahl hinzufuegen\n"); printf("-3- Ende\n\n"); printf("Ihre Wahl : "); scanf("%d",&wahl); getchar(); if(wahl == 1) { printf("Welche Postleitzahl suchen Sie : "); scanf("%5u",&search); suche(search); } else if(wahl == 2) { printf("Neue Postleitzahl : "); scanf("%5u",&post); getchar(); printf("Ort für PLZ %d : ",post); fgets(new_ort, MAX, stdin); einfuegen(post, strtok(new_ort, "\n") ); } } while(wahl!=3); return EXIT_SUCCESS; } Natürlich kann die Suche auch so verändert werden, dass zu einem Ort die Postleitzahl gesucht wird. Dazu muss nur die Suchfunktion ein wenig umgeschrieben werden: > void suche(char *o) { int n=N; int i; for(i=0; i<=N; i++) if(strcmp(postleitzahlen[i].ort,o) == 0) { printf("Der Ort zur Postleitzahl %d : %s\n", key,postleitzahlen[i].ort); return; } printf("Für den Wert %s konnte keine Postleitzahl " "gefunden werden!\n",o); } In den einfachsten Fällen – bei wenigen Daten – dürfte die lineare Suche völlig ausreichend sein. ### 22.4.2 Binäre Suche Die binäre Suche eignet sich sehr gut bei etwas gröÃeren Datensätzen. Sie arbeitet nach dem Prinzip »Teile und herrsche«. Der vollständige Datensatz wird (sortiert!) in zwei Teile zerlegt. Ist das aktuelle Element gröÃer als das gesuchte, wird mit dem Element, das links vom aktuellen Element liegt, verglichen. Ist das aktuelle kleiner, wird mit dem Element rechts verglichen. Ist die Suche erfolglos, wird die Liste wieder in zwei Teile aufgeteilt – natürlich unter der Bedingung, dass das Element in der Mitte gröÃer oder kleiner als das gesuchte ist. Im schlechtesten Fall wird das erste oder das letzte Element gesucht. Diese Art der Suche scheint für reine Suchergebnisse optimal zu sein. Sollten Sie aber vorhaben, Elemente in den Datensatz einzufügen, ist das schnelle Suchergebnis wieder dahin. Beim Einfügen eines neuen Elements muss wieder dafür gesorgt sein, dass die Liste sortiert bleibt. Hierzu folgt das Beispiel, das voraussetzt, dass die Liste bereits sortiert ist. Eine Sortierfunktion können Sie ja zur Ãbung selbst implementieren. > /* bin_search.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 255 struct plzn{ char ort[MAX]; unsigned int plz; }; struct plzn postleitzahlen[100]; static int N; /* initialisieren */ void init(void) { N = 0; postleitzahlen[N].plz = 0; strcpy(postleitzahlen[N].ort, "dummy"); } void einfuegen(unsigned int p, char *o) { postleitzahlen[++N].plz = p; strcpy(postleitzahlen[N].ort, o); } int binaere_suche(unsigned int key) { int l=1; int r=N; int x; while(r >= l) { x=(l+r)/2; if(key < postleitzahlen[x].plz) /* kleiner? */ r=x-1; /* Rechte Seite ist nicht mehr so interessant. */ else /* dann halt gröÃer */ l=x+1; /* Linke Seite ist nicht mehr so interessant. */ if(key == postleitzahlen[x].plz) return x; /* gefunden; x = Position */ } return -1; /* nicht gefunden */ } int main(void) { int wahl, ret; unsigned int search, post; char new_ort[MAX]; init(); do { printf("-1- Postleitzahl suchen\n"); printf("-2- Postleitzahl hinzufuegen\n"); printf("-3- Ende\n\n"); printf("Ihre Wahl : "); scanf("%d",&wahl); getchar(); if(wahl == 1) { printf("Welche Postleitzahl suchen Sie : "); scanf("%5u",&search); ret=binaere_suche(search); if(ret == -1) printf("Kein Ergebnis auf Ihre Anfrage!\n"); else printf("Die Antwort auf %d : " "%s\n",search,postleitzahlen[ret].ort); } else if(wahl == 2) { printf("Neue Postleitzahl : "); scanf("%5u",&post); getchar(); printf("Ort für PLZ %d : ",post); fgets(new_ort, MAX, stdin); einfuegen(post, strtok(new_ort, "\n") ); } } while(wahl!=3); return EXIT_SUCCESS; } Die binäre Suche eignet sich also für eine kleinere, bereits sortierte Datenmenge hervorragend. ### 22.4.3 Binäre (Such-)Bäume Binäre Suchbäume dürfen wohl als die Methode der Informatik schlechthin angesehen werden. Binäre Bäume sind im Prinzip den verketteten Listen sehr ähnlich, allerdings mit dem Unterschied, dass binäre Bäume nicht linear angeordnet sind. Hierzu zwei Grafiken, die das verdeutlichen sollen: Abbildung 22.16 Doppelt verkettete Liste Abbildung 22.17 Binärer Baum Welchen Vorteil bietet hierbei der binäre Baum? Am besten ist, Sie zählen die Schritte, die benötigt werden, um vom Anfang des Baums bis zum Wert 5 zu gelangen. Dasselbe machen Sie jetzt mit der verketteten Liste. Der Anfang (Wurzel) beim binären Baum ist hier die Ziffer 3. Mit binären Suchbäumen lassen sich also die Suchwege erheblich verkürzen. Bei solch kleinen Beispielen ist das nicht der Rede wert, aber je gröÃer der Datenbestand wird, desto stärker wirkt sich dies auf die Performance aus. Zudem ist bei der grafischen Darstellung des binären Baums auffällig, dass alle Werte, die sich auf der linken Seite befinden, kleiner sind, und dass sich die gröÃeren Werte auf der rechten Seite befinden. Aber dazu gleich mehr. # Grundbegriffe von binären Bäumen Der Begriff Baum (engl. Tree) wurde hier verwendet, da diese Struktur die Form eines Baums hat, der allerdings auf den Kopf gestellt ist. Auch die einzelnen Elemente heiÃen ähnlich wie die eines Baums. Bäume sind hierarchische Datenstrukturen, die folgendermaÃen aufgeteilt werden: Abbildung 22.18 Gliederung eines binären Baums Ein Baum besteht aus folgenden Elementen: * Wurzel (engl. root) – Dieser Knoten ist der einzige, der keinen Vorgänger besitzt. Wie bei einem echten Baum können Sie sich das als Wurzel vorstellen – nur dass in der Informatik die Wurzel oben ist. * Ast, Kante (engl. edges) – Jeder Baum besteht aus einzelnen Knoten, die mit einem Ast verbunden sind. * Knoten (engl. node) – Knoten sind die eigentlichen Elemente, die über alle Informationen wie Daten und Zeiger zum rechten und linken Knoten verfügen. Ein Knoten ist die Struktur selbst. Beim binären Baum hat jeder Knoten nicht mehr als zwei Nachfolger (daher auch »bi« = zwei). Es gibt zwar auch Bäume mit mehreren Nachfolgern, allerdings handelt es sich dann nicht mehr um einen binären Baum. * Blatt (engl. leaf ) – Blätter sind Knoten, die keinen Nachfolger besitzen. * Teilbaum – Ein Knoten mit einem linken und einem rechten Nachfolger wird als Teilbaum bezeichnet. * Tiefe (engl. level) – Als Tiefe wird die Anzahl der Nachfolgeroperationen bezeichnet, die erforderlich sind, um von der Wurzel des Baums zu einem bestimmten Knoten zu gelangen. Die Tiefe n kann dann 2n –1 einzelne Knoten beinhalten. Mit diesem Grundwissen können Sie beginnen, einen binären Baum zu programmieren. Zuerst wird die Struktur eines Knotens benötigt: > struct knoten { int wert; struct knoten *links; struct knoten *rechts; }; Damit der Umfang des Beispiels nicht zu sehr anwächst, begnügen wir uns hier mit der Eingabe eines Werts (int wert) in die Struktur. AuÃer dem int-Wert besitzt die Struktur noch jeweils einen Zeiger auf den linken und einen auf den rechten Nachfolger des Knotens. Somit können Sie sich die Struktur vom Typ knoten so vorstellen: Abbildung 22.19 Die Datenstruktur eines binären Baumes ### 22.4.4 Elemente im binären Baum einordnen Als Erstes wird eine Funktion benötigt, mit der Werte in den binären Baum eingeordnet werden. Die kleineren Werte sollen dabei immer auf der linken Seite und die gröÃeren Werte auf der rechten Seite eingeordnet werden. Hier folgt nochmals die Struktur. Es wurde auÃerdem mit typedef ein neuer Datentyp namens KNOTEN definiert: > struct knoten { int wert; struct knoten *links; struct knoten *rechts; }; typedef struct knoten KNOTEN; KNOTEN *einordnen(KNOTEN *zeiger) { //---->Funktionen ... Folgende drei Möglichkeiten können beim Einordnen in den binären Baum auftreten: 1. | Es befindet sich noch kein Element (genauer: es fehlt noch die Wurzel – root) im Baum, und das eingefügte ist das erste Element und somit die Wurzel des Baums: | | --- | --- | | 2. | Der neue Wert ist kleiner als die Wurzel bzw. bei weiterem Verlauf kleiner als der Knoten, und somit wird der neue Wert links von der Wurzel bzw. dem Knoten eingeordnet: | | --- | --- | | 3. | Die dritte und letzte Möglichkeit: Der Wert des neuen Elements ist gröÃer als die Wurzel bzw. der Knoten. Somit kommt dieses auf die rechte Seite der Wurzel bzw. des Knotens: | | --- | --- | | Hier sehen Sie die vollständige Funktion zum Einordnen eines neuen Elements in den binären Baum mitsamt der main()-Funktion: > /* btree1.c */ #include <stdio.h> #include <stdlib.h> struct knoten{ int wert; struct knoten *links; struct knoten *rechts; }; typedef struct knoten KNOTEN; /* globale Variable */ int zahl; KNOTEN *einordnen(KNOTEN *zeiger) { if(zeiger == NULL) { zeiger = malloc(sizeof(KNOTEN)); if(zeiger==NULL) { printf("Konnte keinen Speicherplatz reservieren!\n"); exit (EXIT_FAILURE); } zeiger->wert=zahl; zeiger->links=zeiger->rechts=NULL; } else if(zeiger->wert >= zahl) zeiger->links=einordnen(zeiger->links); else if(zeiger->wert < zahl) zeiger->rechts=einordnen(zeiger->rechts); return (zeiger); } int main(void) { KNOTEN *wurzel=NULL; do { printf("Bitte Zahl eingeben : "); scanf("%d",&zahl); wurzel=einordnen(wurzel); } while(zahl != 0); return EXIT_SUCCESS; } Nun betrachten wir den theoretischen Ablauf des Programms: Das Programm wurde gestartet, und der erste Wert sei die 10. Jetzt wird mit wurzel=einordnen(wurzel) die Funktion aufgerufen. Bei der ersten Eingabe trifft gleich die erste if-Bedingung zu: if(zeiger == NULL) Womit die Zahl 10 das erste Element und gleichzeitig die Wurzel des Baums ist. Die beiden Zeiger links und rechts bekommen den NULL-Zeiger zugewiesen: Abbildung 22.20 Die Wurzel des Baums Als Nächstes sei die Zahl 8 gegeben. Wieder wird über die main()-Funktion die Funktion einordnen() aufgerufen. Dieses Mal ist es aber (zeiger==NULL) falsch, denn das erste Element bzw. die Wurzel des Baums ist die Zahl 10. Die nächste else if-Bedingung ist: > else if(zeiger->wert >= zahl) Das trifft zu, denn zeiger->wert (10) ist gröÃer als die eingegebene Zahl. Es folgt der erste Funktionsselbstaufruf: > zeiger->links=einordnen(zeiger->links); Jetzt soll der Zeiger zeiger, der auf links verweist, die Adresse vom erneuten Funktionsaufruf einordnen(zeiger->links) zugewiesen bekommen. Alles beginnt wieder von vorn: > if(zeiger==NULL) Und tatsächlich zeigt der Zeiger zeiger jetzt auf NULL, da er ja zuvor durch den erneuten Aufruf die Adresse von der linken Seite des ersten Elements (10) erhalten hat. Also wird erst Speicher alloziert und dann das neue Element eingefügt. Der linke und der rechte Zeiger des neuen Elements bekommen wieder jeweils den NULL-Zeiger zugewiesen: Abbildung 22.21 Kleinere Elemente wie die Wurzel kommen auf die linke Seite. Als Nächstes sei die Zahl 9 gegeben. Im ersten Durchlauf wird > else if(zeiger->wert >= zahl) zeiger->links=einordnen(zeiger->links); wie schon zuvor ausgeführt. Jetzt verweist der Zeiger zeiger auf die Adresse mit dem Wert 8. Also ist zeiger==NULL nicht wahr, und die Bedingung > else if(zeiger->wert >= zahl) ist auch nicht wahr, denn zeiger->wert (8) ist dieses Mal nicht gröÃer oder gleich der aktuellen Zahl (9). Die nächste else if-Anweisung > else if(zeiger->wert < zahl) ist jetzt wahr, denn (8 < 9) trifft zu. Dies ist der zweite rekursive Funktionsaufruf (einer liegt ja schon auf dem Stack): > zeiger->rechts=einordnen(zeiger->rechts); Jetzt bekommt der Zeiger zeiger, der auf rechts verweist, die Adresse von einordnen(zeiger->rechts). Das ist übrigens auch der Grund, weshalb die Funktion einen Rückgabewert vom Typ KNOTEN * hat. Auf zum erneuten Durchlauf der Funktion: zeiger==NULL trifft jetzt zu, also wurde der Platz für das neue Element gefunden: Abbildung 22.22 Das neue Element ist kleiner als die Wurzel, aber gröÃer als der Nachfolgerknoten. Als Nächstes sei die Zahl 20 gegeben. Hierzu soll eine Grafik genügen, die Sie als Ãbung selbst durchgehen können: Abbildung 22.23 Elemente, die gröÃer als die Wurzel sind, kommen auf die rechte Seite. ### 22.4.5 Binäre Bäume traversieren Die einzelnen Knoten, die zuvor erzeugt wurden, werden nun besucht bzw. in diesem Fall ausgeben. Dies wird Traversieren der Bäume genannt. Es gibt zwei gängige Möglichkeiten, die Bäume zu traversieren. Zur Demonstration wird der eben erstellte binäre Baum verwendet: 1. | Die erste Variante ist die Preorder-Traversierung. Gemäà der Preorder-Traversierung wird zuerst die Wurzel mit dem Wert 10 besucht, anschlieÃend der Knoten mit dem Wert 8. Es folgt der Knoten mit dem Wert 9. Als Letztes wird der Knoten mit dem Wert 20 besucht. Diese Preorder-Taktik läuft wie folgt ab: »Besuche die Wurzel, dann besuche den linken Unterbaum, als Nächstes besuche den rechten Unterbaum.« Die Funktion, die das Verfahren realisiert, sieht so aus: | | --- | --- | | 2. | Die zweite Möglichkeit ist die sogenannte Inorder-Traversierung. Bei dieser Möglichkeit werden die Knoten in folgender Reihenfolge besucht: | | --- | --- | | Es ist kaum eine Ãnderung zur Preorder-Traversierung festzustellen, nur dass bei der Inorder-Traversierung zuerst mit dem am weitesten links unten liegenden Knoten oder Blatt angefangen wird und beim Preorder mit der Wurzel. Es gibt noch eine dritte Möglichkeit: »Besuche den linken Unterbaum, besuche den rechten Unterbaum und dann besuche die Wurzel.« Diese Methode benötigen Sie eigentlich nur bei Postfix-Notationen. ### 22.4.6 Löschen eines Elements im binären Baum Jetzt folgt ein etwas komplizierteres Problem: das Löschen eines Elements im Baum. Hierbei gibt es erneut drei Möglichkeiten: 1. | Die einfachste Form ist die Entfernung eines Blatts, da dieses keinen Nachfolger mehr hat. | | --- | --- | 2. | Die zweite Möglichkeit ist die Entfernung eines Knotens mit nur einem Nachfolger. | | --- | --- | 3. | Die letzte Möglichkeit ist gleichzeitig auch die schwierigste. Es muss ein Knoten gelöscht werden, der zwei Nachfolger hat. | | --- | --- | Zuerst benötigen Sie eine Funktion, die den zu löschenden Knoten sucht: > void loesche(KNOTEN **zeiger, int such) { if((*zeiger) == NULL) printf("Baum ist leer\n"); else if((*zeiger)->wert == such) /* Gefunden! */ loesche_knoten(zeiger); else if((*zeiger)->wert >= such) loesche(&((*zeiger)->links),such); else loesche(&((*zeiger)->rechts),such); } Der Funktion loesche() werden als Argumente die Wurzel (zeiger) und der zu suchende Wert (such) übergeben. Als Erstes wird überprüft, ob überhaupt eine Wurzel vorhanden ist (if((*zeiger) == NULL)). Danach wird getestet, ob der Wert schon gefunden wurde (else if((*zeiger)->wert == such)). Wurde der Wert gefunden, wird die Funktion loesche_knoten() mit dem zeiger auf den gefundenen Wert aufgerufen. Als Nächstes (falls der Knoten noch nicht gefunden wurde) wird überprüft, ob der Wert, auf den der Zeiger zeiger verweist, gröÃer oder gleich dem gesuchten Wert such ist (else if((*zeiger)->wert >= such) ). Ist dies der Fall, ist der gesuchte Wert kleiner als der, auf den der Zeiger zeiger verweist, und muss sich somit auf der linken Seite der aktuellen Adresse zeiger befinden (loesche(&((*zeiger)–> links),such)). Hier erfolgt der erste rekursive Aufruf mit dem Adressoperator. Die letzte else-Anweisung ergibt sich dadurch, dass der gesuchte Wert gröÃer als der ist, auf den der Zeiger zeiger gerade verweist. In diesem Fall wird auf der rechten Seite mit dem rekursiven Aufruf (loesche(&((*zeiger)-> rechts),such)) weiter gesucht. Es wird jetzt davon ausgegangen, dass der Knoten gefunden wurde, und nun wird die Funktion loesche_knoten(zeiger) aufgerufen: > void loesche_knoten(KNOTEN **zeiger) { KNOTEN *temp; int tempwert; if(globale_wurzel == *zeiger) { printf("Kann die Wurzel nicht loeschen!!\n"); return; } if((*zeiger)!=NULL) { /* Blatt! */ if((*zeiger)->links==NULL && (*zeiger)->rechts==NULL) { free(*zeiger); *zeiger=NULL; } else if((*zeiger)->links==NULL) { /* Nur rechter Nachfolger */ temp = *zeiger; *zeiger=(*zeiger)->rechts; free(temp); } else if((*zeiger)->rechts==NULL) { /* Nur linker Nachfolger */ temp = *zeiger; *zeiger=(*zeiger)->links; free(temp); } else { /* 2 Nachfolger, wir suchen Ersatzelement */ suche_ersatz(&tempwert, &((*zeiger)->rechts)); (*zeiger)->wert=tempwert; } } } Zunächst wird überprüft, ob der gefundene Wert die Wurzel ist. In diesem Fall wird kein Element gelöscht und die Funktion beendet (dazu unten mehr). Als Nächstes wird getestet, ob das zu löschende Element ein Blatt ist (ein Element ohne Nachfolger): > if((*zeiger)->links==NULL && (*zeiger)->rechts==NULL) Falls es ein Blatt ist, wird es entfernt. Ansonsten wird mit den nächsten beiden else if-Bedingungen ermittelt, ob das zu löschende Element einen rechten oder linken Nachfolger hat. Die letzte und die schwierigste Möglichkeit ist, dass der zu löschende Knoten zwei Nachfolger besitzt. Dafür wird am besten eine spezielle Funktion geschrieben, die für den zu löschenden Knoten ein Ersatzelement sucht: > else { /* 2 Nachfolger, wir suchen Ersatzelement */ suche_ersatz(&tempwert, &((*zeiger)->rechts)); (*zeiger)->wert=tempwert; } Hier wird ein Ersatzelement auf der rechten Seite gesucht. Die Funktion suche_ersatz() sieht so aus: > void suche_ersatz(int *neuwert, KNOTEN **zeiger) { KNOTEN *temp; if(*zeiger != NULL) { if((*zeiger)->links==NULL) { neuwert=(*zeiger)->wert; temp=*zeiger; *zeiger=(*zeiger)->rechts; free(temp); } else suche_ersatz(neuwert, &((*zeiger)->links)); } } Die Funktion suche_ersatz() läuft jetzt durch einen rekursiven Aufruf (suche_ersatz(neuwert, &((*zeiger)->links));) so lange die linke Seite des Baums hinab, bis die Bedingung (if((*zeiger)->links==NULL)) wahr ist. Dann wurde ein Ersatzelement gefunden, auf das gleich der Zeiger *neuwert verweist. Das vollständige Listing (btree2.c) – mit einigen zusätzlichen Funktionen – finden Sie natürlich wieder auf der Buch-CD. ### 22.4.7 Ein binärer Suchbaum in der Praxis Jetzt soll der binäre Suchbaum mit dem Postleitzahlen-Programm verwendet werden. Zuerst wird die grundlegende Knotenstruktur für den binären Baum festgelegt: > struct binaer_knoten{ char ort[255]; unsigned int plz; struct binaer_knoten *links; struct binaer_knoten *rechts; }; Jetzt schreiben wir eine spezielle Struktur für den Baum: > struct binaer_baum{ struct binear_knoten *root; unsigned int counter; }; Dank dieser Struktur werden die rekursiven Aufrufe des vorigen Beispiels aufgehoben. Dies ist möglich, weil beim ersten Aufruf der Funktion als Argument immer die Adresse der Wurzel des Baums mit übergeben wird. Als Nächstes benötigen Sie eine Funktion, um den binären Baum zu initialisieren: > struct binaer_baum *init(void) { struct binaer_baum *baum =malloc(sizeof *baum); if(baum == NULL) { fprintf(stderr, "Speicherplatzmangel!!!\n"); return NULL; } else { /* initialisieren */ baum->root = NULL; baum->counter=0; return baum; } } Es folgt eine Funktion zum Einfügen einzelner Knoten in den binären Baum ohne einen rekursiven Funktionsaufruf: > int einfuegen(struct binaer_baum *baum, unsigned int p, char *o){ struct binaer_knoten *knoten, **neu; neu =(struct binaer_knoten **) &baum->root; knoten= (struct binaer_knoten *) baum->root; for(;;) { if(knoten == NULL) { /* Haben wir einen freien Platz gefunden? */ knoten = *neu = malloc(sizeof *knoten); if(knoten != NULL) { /* Daten einfügen */ knoten->plz = p; strcpy(knoten->ort, o); knoten->links=knoten->rechts=NULL; baum->counter++; /* Beendet die Funktion erfolgreich. */ return 1; } else { fprintf(stderr, "Speicherplatzmangel\n"); return 0; } } /* Ist die aktuelle Postleitzahl gröÃer? */ else if(p > knoten->plz) { /* Dann gehts rechts weiter im Baum. */ neu = &knoten->rechts; knoten = knoten->rechts; } else { /* Der letzte Fall, die aktuelle PLZ ist kleiner, */ /* dann eben nach links weiter im Baum. */ neu = &knoten->links; knoten = knoten->links; } } } Das Thema binäre Bäume ist erheblich einfacher, wenn die Rekursion beseitigt wird. Wichtig ist bei dieser Funktion, dass sich die Endlosschleife auch irgendwann einmal beendet. In diesem Beispiel beendet sich die Funktion bei Erfolg mit dem Rückgabewert 1 (return 1), wenn das neue Element eingefügt wurde. Bei Mangel an Speicherplatz gibt diese Funktion 0 zurück. Das Einfügen eines neuen Elements berücksichtigt übrigens keine doppelten Einträge. Dies können Sie zur Ãbung gern selbst nachtragen. Jetzt soll die Suchfunktion erstellt werden (um die es ja eigentlich in diesem Kapitel geht). Begonnen wird an der Wurzel (root) des Baums. Ist das gesuchte Element gröÃer, geht die Suche auf der rechten Seite des Baums weiter. Ist das gesuchte Element kleiner, wird auf der linken Seite weitergesucht. Bei einem perfekt ausgeglichenen Baum führt dies zu optimalen Ergebnissen. Hier sehen Sie die Suchfunktion, die sich relativ einfach erstellen lässt: > void binaere_suche_plz(const struct binaer_baum *baum, unsigned int p) { const struct binaer_knoten *knoten; /* zuerst an die Wurzel */ knoten = (struct binaer_knoten *) baum->root; for(;;) { if(knoten == NULL) { printf("Keine erfolgreiche Suche!\n"); return; } if(p == knoten->plz) { /* Gefunden */ printf("Ort zu Postleitzahl %d : %s\n", p,knoten->ort); return; } else if(p > knoten->plz) /* Gesuchtes Element gröÃer: */ knoten=knoten->rechts; /* rechts am Baum weiter. */ else /* Gesuchtes Element kleiner: */ knoten=knoten->links; /* links am Baum weiter. */ } } Mit dieser Funktion haben Sie auch schon die Grundlage für das Löschen eines Elements im Baum geschaffen. Nur müssen Sie anstatt > if(p == knoten->plz) { /* Gefunden */ printf("Ort zu Postleitzahl %d : %s\n", p,knoten->ort); return; } break verwenden, um nach der for-Schleife weitere Operationen durchzuführen: > if(p == knoten->plz) /* Gefunden */ break; Das Löschen eines Elements im binären Baum wurde ja schon einmal präsentiert. Da aber schon beim Einfügen eines Knotens auf weitere Funktionsaufrufe, insbesondere Rekursionen, verzichtet wurde, soll auch die Funktion zum Löschen eines Knotens entsprechend umgeschrieben werden, und zwar so, dass alle Operationen in dieser Funktion ausgeführt werden. Hier sehen Sie die Funktion: > int bin_delete(struct binaer_baum *baum, unsigned int p) { /* pointer_z ist das zu löschende Element */ struct binaer_knoten **pointer_q, *pointer_z, *pointer_y, *pointer_x; pointer_q = (struct binaer_knoten **)&baum->root; pointer_z = (struct binaer_knoten *)baum->root; for(;;) { if(pointer_z == NULL) return 0; else if(p == pointer_z->plz) /* zu löschendes Element gefunden */ break; else if(p > pointer_z->plz) { /* Das zu löschende Element ist gröÃer. */ pointer_q = &pointer_z->rechts; /* rechts weitersuchen */ pointer_z = pointer_z->rechts; } else { /* Das zu löschende Element ist kleiner. */ pointer_q = &pointer_z->links; /* links weitersuchen */ pointer_z = pointer_z->links; } } /* Hierher kommen wir nur durch ein break. */ /* Jetzt müssen wir das zu löschende Element untersuchen. * pointer_z hat rechts keinen Nachfolger, somit können wir * es austauschen gegen den linken Nachfolger ... */ if(pointer_z->rechts == NULL) *pointer_q = pointer_z->links; else { /* pointer_z hat einen rechten Nachfolger, aber * keinen linken. */ pointer_y = pointer_z->rechts; if(pointer_y->links == NULL) { /* pointer_z->rechts hat keinen linken Nachfolger ... */ pointer_y->links = pointer_z->links; *pointer_q = pointer_y; } else { /* Es gibt einen linken Nachfolger. */ pointer_x = pointer_y->links; /* Jetzt suchen wir so lange, bis es keinen linken * Nachfolger mehr gibt */ while(pointer_x->links != NULL) { pointer_y = pointer_x; pointer_x = pointer_y->links; } /* Jetzt haben wir alle Punkte zusammen und * können diese verknüpfen. */ pointer_y->links = pointer_x->rechts; pointer_x->links = pointer_z->links; pointer_x->rechts = pointer_z->rechts; *pointer_q = pointer_x; } } /* Zu guter Letzt können wir pointer_z freigeben. */ baum->counter--; free(pointer_z); return 1; } Zugegeben, auf den ersten Blick dürfte diese Funktion etwas abschreckend wirken. Aber zeichnen Sie sich einen binären Baum auf ein Blatt Papier, und gehen Sie dabei diese Funktion Schritt für Schritt durch: Sie werden sich wundern, wie einfach diese Funktion im Gegensatz zur rekursiven Variante ist. Zum Schluss folgt hier noch der vollständige Quellcode zu diesem Abschnitt: > /* btree3.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 255 struct binaer_knoten{ char ort[MAX]; unsigned int plz; struct binaer_knoten *links; struct binaer_knoten *rechts; }; struct binaer_baum{ struct binear_knoten *root; unsigned int counter; }; struct binaer_baum *init(void) { struct binaer_baum *baum =malloc(sizeof *baum); if(baum == NULL) { fprintf(stderr, "Speicherplatzmangel!!!\n"); return NULL; } else { /*Initialisieren*/ baum->root = NULL; baum->counter=0; return baum; } } int einfuegen(struct binaer_baum *baum, unsigned int p, char *o){ struct binaer_knoten *knoten, **neu; neu =(struct binaer_knoten **) &baum->root; knoten= (struct binaer_knoten *) baum->root; for(;;) { if(knoten == NULL) { /* Haben wir einen freien Platz gefunden? */ knoten = *neu =malloc(sizeof *knoten); if(knoten != NULL) { /* Daten einfuegen */ knoten->plz = p; strcpy(knoten->ort, o); knoten->links=knoten->rechts=NULL; baum->counter++; /* Beendet die Funktion erfolgreich. */ return 1; } else { fprintf(stderr, "Speicherplatzmangel\n"); return 0; } } /* Ist die aktuelle Postleitzahl gröÃer? */ else if(p > knoten->plz) { /* Dann gehts rechts weiter im Baum. */ neu = &knoten->rechts; knoten = knoten->rechts; } else { /* Der letzte Fall, die aktuelle PLZ ist kleiner, */ /* dann eben nach links weiter im Baum. */ neu = &knoten->links; knoten = knoten->links; } } } void binaere_suche_plz(const struct binaer_baum *baum, unsigned int p) { const struct binaer_knoten *knoten; /* zuerst an die Wurzel */ knoten = (struct binaer_knoten *) baum->root; for(;;) { if(knoten == NULL) { printf("Keine erfolgreiche Suche!\n"); return; } if(p == knoten->plz) { /* Gefunden */ printf("Ort zu Postleitzahl %d : %s\n", p,knoten->ort); return; } else if(p > knoten->plz) /* Gesuchtes Element gröÃer: */ knoten=knoten->rechts; /* rechts am Baum weiter. */ else /* Gesuchtes Element kleiner: */ knoten=knoten->links; /* links am Baum weiter. */ } } int bin_delete(struct binaer_baum *baum, unsigned int p) { /* pointer_z ist das zu löschende Element. */ struct binaer_knoten **pointer_q, *pointer_z, *pointer_y, *pointer_x; pointer_q = (struct binaer_knoten **)&baum->root; pointer_z = (struct binaer_knoten *)baum->root; for(;;) { if(pointer_z == NULL) return 0; else if(p == pointer_z->plz) /* zu löschendes Element gefunden */ break; else if(p > pointer_z->plz) { /* Das zu löschende Element ist gröÃer. */ pointer_q = &pointer_z->rechts; /* rechts weitersuchen */ pointer_z = pointer_z->rechts; } else { /* Das zu löschende Element ist kleiner. */ pointer_q = &pointer_z->links; /* links weitersuchen */ pointer_z = pointer_z->links; } } /* Hierher kommen wir nur durch ein break. */ /* Jetzt müssen wir das zu löschende Element untersuchen. * pointer_z hat rechts keinen Nachfolger, somit können wir * es austauschen gegen den linken Nachfolger ... */ if(pointer_z->rechts == NULL) *pointer_q = pointer_z->links; else { /* pointer_z hat einen rechten Nachfolger, aber * keinen linken. */ pointer_y = pointer_z->rechts; if(pointer_y->links == NULL) { /* pointer_z->rechts hat keinen linken Nachfolger ... */ pointer_y->links = pointer_z->links; *pointer_q = pointer_y; } else { /* Es gibt einen linken Nachfolger. */ pointer_x = pointer_y->links; /* Jetzt suchen wir so lange, bis es keinen linken * Nachfolger mehr gibt. */ while(pointer_x->links != NULL) { pointer_y = pointer_x; pointer_x = pointer_y->links; } /* Jetzt haben wir alle Punkte zusammen und * können diese verknüpfen. */ pointer_y->links = pointer_x->rechts; pointer_x->links = pointer_z->links; pointer_x->rechts = pointer_z->rechts; *pointer_q = pointer_x; } } /* Zu guter Letzt können wir pointer_z freigeben. */ baum->counter--; free(pointer_z); return 1; } int main(void) { struct binaer_baum *re; char o[MAX]; unsigned int p; int wahl, r; re = init(); if(re == NULL) { printf("Konnte keinen neuen binaeren Baum erzeugen!\n"); return EXIT_FAILURE; } else printf("Binaerbaum wurde erfolgreich initialisiert\n"); do { printf("\n-1- Neue PLZ hinzufuegen\n"); printf("-2- PLZ suchen\n"); printf("-3- PLZ loeschen\n"); printf("-4- Ende\n\n"); printf("Ihre Wahl : "); scanf("%d",&wahl); if(wahl == 1) { printf("Bitte geben Sie eine neue PLZ ein : "); do{ scanf("%5u",&p); }while( (getchar()) != '\n' ); printf("Der Ort dazu : "); fgets(o, MAX, stdin); r=einfuegen(re, p, strtok(o, "\n") ); if(r == 0) return EXIT_FAILURE; } else if(wahl == 2) { printf("Für welche PLZ suchen Sie einen Ort : "); scanf("%5u",&p); binaere_suche_plz(re, p); } else if(wahl == 3) { printf("Welche PLZ wollen Sie loeschen : "); scanf("%5d",&p); bin_delete(re, p); } } while(wahl != 4); return EXIT_SUCCESS; } ### 22.4.8 Binäre Suchbäume mit Eltern-Zeiger und Threads Es gibt noch mehrere andere Wege, binäre Bäume zu implementieren, um sich z. B. das Traversieren des Baums zu erleichtern. Bereits gesehen haben Sie das Durchlaufen der Bäume mittels Preorder- und Inorder-Traversierung. Wenn Sie aber das Durchlaufen (Traversieren) eines Baums iterativ und nicht mehr rekursiv vornehmen wollen, können Sie die Struktur um einen Zeiger zum Elternknoten erweitern: > struct binaer_knoten{ char ort[255]; unsigned int plz; struct binaer_knoten *links; struct binaer_knoten *rechts; struct binaer_knoten *eltern; }; Jetzt kann jeder Knoten sein Umfeld kontrollieren. Dieser Eltern-Zeiger vereinfacht das Traversieren des Baums, doch der Schreibaufwand für das Programm steigt. AuÃerdem wird auch das Einfügen und Löschen eines Elements verlangsamt, da ein Zeiger mehr verwaltet werden muss. Dem Eltern-Zeiger der Wurzel übergeben Sie hingegen den NULL-Zeiger. Mit Threads (Threading) haben Sie die Möglichkeit, einen Baum noch schneller zu traversieren. Denn anstatt zu überprüfen, ob der linke oder rechte Teil eines Knotens leer (NULL) ist, was zu einer schlechteren Laufzeit führen könnte, müssen Sie nur zwei Extra-Bits (Bit-Felder) in die Struktur einfügen: > struct binaer_knoten{ char ort[255]; unsigned int plz; struct binaer_knoten *links; struct binaer_knoten *rechts; unsigned linker_thread:1; unsigned rechter_thread:1; }; Wenn sich z. B. auf der linken Seite eines Knotens ein weiterer Knoten befindet, steht das Bit linker_tread auf 1. Falls sich dort noch kein Knoten befindet, steht es auf 0. Natürlich lässt sich auf diese Weise nicht generell eine bessere Laufzeit garantieren, da diese davon abhängt, wie der Compiler Bit-Felder optimiert. Aber eine Erleichterung dürfte es auf jeden Fall darstellen. ### 22.4.9 Ausgeglichene Binärbäume Es gibt leider einen negativen Aspekt bei den binären Bäumen, die Sie eben kennengelernt haben. Betrachten Sie bitte den Binärbaum aus Abbildung 22.24. Abbildung 22.24 Entarteter Binärbaum Bei diesem Beispiel handelt es sich tatsächlich um einen binären Baum und nicht, wie Sie vielleicht vermuten würden, um einen verkettete Liste. Der Baum hat die Tiefe 4 und könnte normalerweise 15 Elemente aufnehmen (24–1). Es handelt sich dabei um einen entarteten Baum. So etwas kann passieren, wenn ein relativ kleiner oder groÃer Wert als Wurzel des Baums verwendet wird. Zugegeben, dieses Beispiel ist ein ungünstiger Fall, aber es könnte dazu kommen. Es gibt, um entartete Binärbäume auszugleichen, Algorithmen, die allerdings nicht einfach zu verstehen sind. Aber was heiÃt perfekt ausbalanciert (ausgeglichen) im Sinne von Binärbäumen? Ein Binärbaum ist perfekt ausgeglichen, wenn sich die Höhen (oder auch Tiefen) der linken und rechten Teilbäume höchstens um den Wert 1 unterscheiden. Solche Bäume werden AVL-Bäume genannt. Um also Probleme zu vermeiden, müssen Sie den Baum immer ausgeglichen halten. Dies ist allerdings auch mit einem erhöhten Speicheraufwand verbunden. Denn wenn ein neues Element eingefügt oder ein Element gelöscht wird, kann es sein, dass der komplette Baum wieder neu organisiert werden muss. Diesen Aufwand sollten Sie jedoch nur betreiben, wenn es denn tatsächlich auf ein schnelleres Suchergebnis ankommt. Ein solches schnelleres Suchergebnis wird durch die Verkürzung der Pfadlänge erreicht. ### 22.4.10 Algorithmen für ausgeglichene Bäume – eine Ãbersicht Zu diesem Thema könnte man ganze Bücher schreiben. Einige weiterführende Hinweise sollen zu den binären Bäumen dennoch gegeben werden. # AVL-Bäume Ein AVL-Baum (AVL nach seinen Erfindern Adelson-Velsky und Landis) ist ein Suchbaum, dessen Knoten sich in der Höhe (Tiefe) von derjenigen der Teilbäume um höchstens 1 unterscheidet, also ein perfekt ausbalancierter Baum. Wird diese Bedingung verletzt, muss eine Ausgleichsfunktion ausgeführt werden. Folgende drei Bedingungen können dabei auftreten (auch Balance-Grad genannt): * balance > 0 – Der rechte Teilbaum besitzt eine gröÃere Höhe als der linke. * balance < 0 – Der linke Teilbaum besitzt eine gröÃere Höhe als der rechte. * balance = 0 – Die Teilbäume haben die gleiche Höhe und sind optimal ausbalanciert. Dieser Zustand wird angestrebt. Um gegen diese Verletzung vorzugehen, werden sogenannte Rotationen vorgenommen. Dabei müssen Sie zwischen rechtsseitiger Rotation (betrifft die rechte Seite des Teilbaums eines Knotens) und linksseitiger Rotation (betrifft die linke Seite des Teilbaums eines Knotens) unterscheiden. AuÃerdem gibt es noch einfache und doppelte Rotationen. Dass all diese Operationen sehr rechenintensiv sind, lässt sich wohl leicht erschlieÃen. # B-Bäume (Bayerbäume) Wenn Sie sich für die Programmierung einer eigenen Datenbank interessieren, dann sollten Sie sich mit diesem Baum befassen. Der B-Baum wird durch eine variable Anzahl von Elementen (Blättern) pro Knoten an die BlockgröÃe des Dateisystems angepasst. Dadurch ist eine effektive und optimale Geschwindigkeitsausnutzung auf verschiedenen Systemen möglich. Die einzelnen Knoten eines B-Baums sind nicht immer belegt und variieren zwischen dem Kleinst- und dem Höchstwert. Somit ist immer Platz für Ãnderungen von Strukturen bei Manipulationen (Einfügen, Löschen, Ãndern  ) an der Datenbank vorhanden. Dies waren lange noch nicht alle Algorithmen, mit denen Sie ausgeglichene Bäume erstellen können. Zu erwähnen sind hier noch die Top-Down 2-3-4-Bäume und die Rot-Schwarz-Bäume. # 22.5 Hashing (Zerhacken) ## 22.5 Hashing (Zerhacken) Das Hashing ist eine bekannte Methode zum Suchen und Speichern von Datensätzen mithilfe einer Tabelle, bei der ein Schlüssel in eine Tabellenadresse umgewandelt wird. Durch diese Umwandlung kann bei einer Suche sofort auf diese Tabellenadresse gesprungen werden, ohne den vollständigen Datensatz (bei binärer Suche einen Teil des Datensatzes) zu durchlaufen. Die Ziele beim Hashing sind dabei eine effizientere Nutzung der verfügbaren Speicherkapazität und ein schnellerer Zugriff. ### 22.5.1 Wann wird Hashing verwendet? Das beste Beispiel für Hashing sind Symboltabellen, bei denen Werte durch jedes Element mit einer dynamischen Menge von Strings assoziiert werden. So geschieht dies etwa beim Compiler. So kann ein Compiler alle Variablen eines Programms am effizientesten verwalten. Ein weiteres Beispiel ist die (verräterische) Autovervollständigung des Browsers oder auch der Cache des Webbrowsers, der den Verlauf speichert. Ein simples Beispiel für Hashing ist die Zählung von Wörtern, die in einem Text vorkommen. Abfragen, die auf ein digitales Wörterbuch angewendet werden, können mit Hashing ebenso effizient gestaltet werden wie die Programmierung von groÃen Datenbanken. Denn in diesen Fällen ist es wirklich geboten, unglaublich viele Daten in kurzer Zeit zu durchsuchen. ### 22.5.2 Was ist für das Hashing erforderlich? * Eine Hash-Funktion – mit der Hash-Funktion wird eine eindeutige Adresse erzeugt, die die Position des Datensatzes in der Hash-Tabelle bestimmt. * Eine Hash-Tabelle – in der Hash-Tabelle befinden sich die eindeutigen Adressen. Eine Suchanfrage wird zunächst mit der Hash-Funktion in eine Tabellenadresse umgewandelt. Mit dieser eindeutigen Adresse wird im Anschluss der Datensatz in der Hash-Tabelle gesucht. Die Hash-Funktion wird in der Praxis meist mit einem Array passender GröÃe angegeben, das zur Kompilierzeit angelegt wird. Einfach ausgedrückt: Eine Hash-Tabelle mit 10 Elementen ist ein Array mit verketteten Listen – mit der GröÃe von 10 * ArraygröÃe. In jedem Index dieses Arrays könnte eine verkettete Liste sein. Das soll jetzt in der Praxis untersucht werden. Hier wird wieder das Postleitzahlen-Beispiel verwendet: > struct plz{ char ort[MAX]; unsigned int postleit; struct plz *next; }; Die Hash-Tabelle, die jetzt für die verkettete Liste verwendet wird, sieht wie folgt aus: > struct plz *hash_tabelle[MAX_HASH]; Um es einfach zu halten, wird eine niedrige ArraygröÃe verwendet: > #define MAX_HASH 10 Abbildung 22.25 zeigt die aktuelle Hash-Tabelle in grafischer Dargestellung: Abbildung 22.25 Leere Hash-Tabelle Jetzt benötigen Sie eine Funktion, um einen neuen Datensatz zum Hash hinzuzufügen: > struct plz *insert(char *o, unsigned int p) { struct plz *pointer; /* Hash-Wert (bucket) an hash_adresse (0-9) */ int hash_adresse = hash_funktion(o); / *printf("%d\n",hash_adresse); */ /* Zeiger auf errechnete Tabellenadresse * durch hash_funktion */ pointer = hash_tabelle[hash_adresse]; /* Wir suchen freien Platz für einen neuen Eintrag * in hash_tabelle[hash_adresse] */ while(pointer != NULL) { if(strcmp(o, pointer->ort) == 0) /* Stadt gleich? */ if(pointer->postleit == p) { /* Postleitzahlen gleich? */ printf("%s mit PLZ %d ist bereits vorhanden\n",o,p); /* doppelte Einträge vermeiden */ return pointer; } pointer=pointer->next; } /* Speicher für neues Element allozieren */ pointer = malloc(sizeof(struct plz)); if(pointer == NULL) { printf("Kein Speicher für neue PLZ vorhanden\n"); return NULL; } strcpy(pointer->ort, o); pointer->postleit = p; pointer->next = hash_tabelle[hash_adresse]; hash_tabelle[hash_adresse] = pointer; return pointer; } Die Funktion wird jetzt Schritt für Schritt erläutert. Wir beginnen mit: > int hash_adresse = hash_funktion(o); Hiermit bekommt die Variable hash_adresse einen errechneten Hash-Wert, der logischerweise zwischen 0 und 9 liegen muss, da die Hash-Tabelle 10 Slots besitzt. Nehmen wir an, dass der Funktion insert() folgende Werte übergeben wurden: > insert("Augsburg", 86163); Die Hash-Funktion errechnet in diesem Beispiel aus dem String "Augsburg" den Wert 6. Somit kommt der String "Augsburg" in den Index (Slot) 6 der Hash-Tabelle. Auf diesen Slot soll jetzt erst ein Zeiger verweisen: > /* Zeiger auf errechnete Tabellenadresse * durch hash_funktion */ pointer = hash_tabelle[hash_adresse]; Bildlich sieht dies wie folgt aus: Abbildung 22.26 Zeiger auf errechneten Index Jetzt muss ein freier Speicherplatz für die neuen Daten gesucht werden: > while(pointer != NULL) { if(strcmp(o, pointer->ort) == 0) /* Stadt gleich? */ if(pointer->postleit == p) { /* Postleitzahlen gleich? */ printf("%s mit PLZ %d ist bereits vorhanden\n",o,p); /* Doppelte Einträge vermeiden */ return pointer; } pointer=pointer->next; } Im ersten Fall ist dies recht trivial. Also kann der neue Datensatz gleich in die Hash-Tabelle eingefügt werden mit: > strcpy(pointer->ort, o); pointer->postleit = p; pointer->next = hash_tabelle[hash_adresse]; hash_tabelle[hash_adresse] = pointer; Jetzt befindet sich das erste Element in der Hash-Tabelle. Grafisch dargestellt sieht dies dann so aus: Abbildung 22.27 Ein erster Datensatz wurde hinzugefügt. Nun folgt ein weiterer Datensatz: > insert("Friedberg", 86316); Die Hash-Funktion, die Ihnen immer noch vorenthalten wurde, errechnet hierbei den Index (Slot) 8. Darauf sieht die Hash-Tabelle nach dem Abarbeiten der Funktion insert() so aus: Abbildung 22.28 Ein weiterer Datensatz wurde hinzugefügt. Kommen wir jetzt zu einem speziellen Fall beim Hashing. Es wird folgender neue Datensatz eingefügt: > insert("Stuttgart", 70190); Die Hash-Funktion errechnet aus dem String "Stuttgart" den Indexwert 8. Beim Betrachten der Abbildung 22.29 können Sie erkennen, dass Slot 8 bereits einen Inhalt hat ("Friedberg"). Dies wird Kollision genannt, und es bedeutet, dass die Hash-Funktion zu unterschiedlichen Schlüsseln gleiche Werte liefern kann. Deshalb wurde ja auch eine lineare verkettete Liste verwendet. Somit wird der neue Datensatz einfach hinter "Friedberg" eingefügt. In der Informatik wird dies als Synonymkette bezeichnet. Abbildung 22.29 Ein Datensatz wurde nach einer Kollision hinzugefügt. ### 22.5.3 Hash-Funktion Anhand dieses Beispiels dürfte klar sein, dass der Hash-Funktion eine entscheidende Rolle zufällt. Wie Sie eine solche Funktion schreiben, bleibt Ihnen selbst überlassen. Sie könnten sogar eine Funktion schreiben, die Zufallszahlen zwischen 0 und 9 zurückliefert. Doch was nutzt eine solche Funktion, wenn 90 % der Zufallszahlen zum Beispiel zwischen 2 und 4 liegen? Die restlichen Slots werden dabei kaum verwendet. Für tatsächlich effektive Hash-Berechnungen existieren drei Methoden: * Divisionsmethode * Mittquadratmethode * Zerlegungsmethode # Divisionsmethode key = key mod m Für m sollten Sie idealerweise eine Primzahl so nahe wie möglich am höchsten Index wählen. # Mittquadratmethode key = I I ist key, wobei führende und endende Ziffern entfernt werden müssen. Beispielsweise: > H(3206) = 32062 = 10278436 Von dem Wert 10278436 werden abwechselnd rechts und links die Ziffern abgeschnitten, bis ein Wert entsteht, der kleiner als der Index ist. Wenn z. B. eine Hash-Tabelle mit dem Index 10 deklariert wurde, sieht der Wert aus dem Schlüssel 10278436 wie folgt aus: > 1027 [8] 436 = 8 # Zerlegungsmethode Man zerlegt den Schlüssel, bis er eine gültige Adresse hat. Als Beispiel verwenden wir den Schlüssel 135612: > 135612 = [13]+[56]+[12]= 81 = [8]+[1] = 9 Der Schlüssel wurde zerlegt, bis er als gültige Adresse den Wert 9 besitzt. # Hashing von Strings Ein bewährter Hash-Algorithmus für Strings erzeugt einen Hash-Wert, in dem er jedes Byte des Strings zum Vielfachen des Strings hinzuaddiert. Eine Multiplikation verteilt die einzelnen Bits des Bytes auf den bisher berechneten Wert. Tests haben ergeben, dass sich bei Strings die Werte 31 und 37 als gute Multiplikatoren erwiesen haben, die auch für das Programmbeispiel verwendet werden. Theoretisch könnten Sie sich das Beispiel anhand des Postleitzahlen-Listings so vorstellen. Für String "Stuttgart" wurden die Postleitzahlen 70190 eingetragen: > hash_tabelle["Stuttgart"] = 70190; Dies ist eigentlich ein Array mit dem Indexwert als String. In der Praxis ist dies in C natürlich nicht möglich. Dafür schreiben Sie ja auch die Hash-Funktion. Die passende Hash-Funktion für das Programmbeispiel sieht so aus: > /* die Hash-Funktion zur Berechnung des * Hash-Werts eines Strings */ int hash_funktion(char *string) { unsigned int hash_adresse; unsigned char *pointer; hash_adresse = 0; pointer = (unsigned char *) string; while(*pointer != '\0') { hash_adresse = M * hash_adresse + *pointer; pointer++; } return hash_adresse % MAX_HASH; } Um sicherzustellen, dass auch positive Hash-Adressen für die Hash-Tabelle zurückgeliefert werden, wird unsigned verwendet. Es ist relativ schwierig, eine optimale Hash-Funktion zu finden. In solch einem Fall müssen Sie so lange testen, bis Sie mit dem Ergebnis zufrieden sind. Hier sehen Sie das vollständige Programm, das das Hashing mit getrennter Verkettung demonstrieren soll: > /* hashing.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_HASH 10 #define M 31 struct plz{ char ort[255]; unsigned int postleit; struct plz *next; }; struct plz *hash_tabelle[MAX_HASH]; struct plz *insert(char *, unsigned int); void search_in_hash(char *); int hash_funktion(char *); struct plz *insert(char *o, unsigned int p) { struct plz *pointer; /* Hash-Wert (bucket) an hash_adresse (0-9) */ int hash_adresse = hash_funktion(o); /* printf("%d\n",hash_adresse); */ /* Zeiger auf errechnete Tabellenadresse * durch hash_funktion */ pointer = hash_tabelle[hash_adresse]; /* Wir suchen freien Platz für einen neuen Eintrag * in hash_tabelle[hash_adresse] */ while(pointer != NULL) { if(strcmp(o, pointer->ort) == 0) /* Stadt gleich? */ if(pointer->postleit == p) { /* Postleitzahlen gleich? */ printf("%s mit PLZ %d ist bereits vorhanden\n",o,p); /* doppelte Einträge vermeiden */ return pointer; } pointer=pointer->next; } /* Speicher für neues Element allozieren */ pointer = malloc(sizeof(struct plz)); if(pointer == NULL) { printf("Kein Speicher für neue PLZ vorhanden\n"); return NULL; } strcpy(pointer->ort, o); pointer->postleit = p; pointer->next = hash_tabelle[hash_adresse]; hash_tabelle[hash_adresse] = pointer; return pointer; } /* Funktion zur Suche in der Hash-Tabelle */ void search_in_hash(char *o) { struct plz *pointer; /* Hash-Wert (bucket) an hash_adresse (0-9) */ int hash_adresse = hash_funktion(o); /* printf("%d\n",hash_adresse); */ /* Zeiger auf errechnete Tabellenadresse * durch hash_funktion */ pointer = hash_tabelle[hash_adresse]; /* Jetzt wollen wir nachsehen, ob es für o einen * Eintrag in der Tabelle gibt. */ while(pointer != NULL) { if(strcmp(pointer->ort, o) == 0) printf("PLZ fuer %s ist %d\n",o,pointer->postleit); pointer = pointer->next; } } /* die Hash-Funktion zur Berechnung des Hash-Werts * eines Strings */ int hash_funktion(char *string) { unsigned int hash_adresse; unsigned char *pointer; hash_adresse = 0; pointer = (unsigned char *)string; while(*pointer != '\0') { hash_adresse = M * hash_adresse + *pointer; pointer++; } return hash_adresse % MAX_HASH; } int main(void) { /* einfügen */ insert("Friedberg", 86316); insert("Augsburg", 86136); insert("Stuttgart", 71345); /* suchen */ search_in_hash("Augsburg"); search_in_hash("Friedberg"); search_in_hash("Stuttgart"); return EXIT_SUCCESS; } Die Suchfunktion search_in_hash() ist ähnlich wie insert(). Daher erkläre ich sie nicht weiter. Wichtig ist es aber auch, zu erwähnen (auch wenn dies eigentlich logisch sein sollte), dass jede Funktion, die Sie hinzufügen (suchen, sortieren, löschen, einfügen, ...), dieselbe Hash-Funktion verwenden muss. ### 22.5.4 Hashing mit direkter Adressierung Es ist auch möglich, die einzelnen Hashes direkt zu adressieren, sofern Sie abschätzen können, wie viele Elemente eingefügt werden. Dafür wird eine Tabelle verwendet, die nur Zeiger auf die anderen Stellen im Speicher abgelegter Datensätze enthält. Die direkte Adressierung lässt sich folgendermaÃen realisieren (Pseudocode): > while(Schlüssel_stimmt_nicht_überein) { if(Schlüssel_stimmt_überein) { printf("gefunden"); return; } else if(Speicherplatz leer) { printf("nicht gefunden"); return; } weiter_an_die_nächste_Position; } Der Vorteil der direkten Adressierung besteht in der gröÃeren Schnelligkeit. Der groÃe Nachteil ist aber die fixe TabellengröÃe. Sofern Sie die Menge der Daten abschätzen können, ist diese kein Nachteil. Bei Datenbanken, bei denen die Menge der Daten vom Anwendungsfall abhängt, ist die direkte Adressierung nicht sinnvoll. ### 22.5.5 Vergleich von Hashing mit binären Bäumen Vorteile des Hashings: * einfach zu implementieren * schnelle Suchergebnisse Vorteile binärer Bäume: * Garantie für Leistungsfähigkeit auch im ungünstigsten Fall * unterstützt viele weitere Operationen (z. B. das Sortieren) * dynamisch (Bei binären Bäumen ist im Gegensatz zum Hashing keine Information über die Anzahl der Einfügungen nötig.) # 22.6 String-Matching ## 22.6 String-Matching Textverarbeitungsprogramme verwenden für die Bearbeitung von Texten Zeichenkettenfolgen in Form von einzelnen Buchstaben, Nummern oder Sonderzeichen. Wenn Sie einen Texteditor oder Ãhnliches entwickeln wollen, werden Sie auch Funktionen wie das Suchen von Strings oder Teilstrings benötigen; oder etwa die Syntaxhervorhebung einer bestimmten Programmiersprache. Eine weitere Möglichkeit ist das Pattern Matching, das Sie vielleicht aus Perl oder von den Linux-Shells kennen. Für solche und weitere Anwendungsmöglichkeiten werden String-Matching-Algorithmen genutzt. Sie funktionieren nach folgendem Prinzip: In einer Textzeichenfolge, wie etwa dem Text in diesem Buch, soll mit einem Suchmuster die Häufigkeit der enthaltenen N-Zeichen und M-Zeichen verglichen werden. Das Ziel des Kapitels ist es nicht, die Algorithmen anhand mathematischer Formeln zu erklären, sondern eher, die Algorithmen so zu erklären, dass Sie das Prinzip verstehen, nach dem sie funktionieren. Als Schnittstelle zu diesen Beispielen soll eine Struktur verwendet werden, die die Daten von der Kommandozeile nimmt und für eventuelle Auswertungen speichert. > struct datei{ char name[LEN]; /* Name der Datei */ int gefunden; /* Anzahl gefunden */ }; typedef struct datei DATEI; Sie können diese Struktur gern um weitere Informationen wie die Position der Fundstelle erweitern. In den Beispielen wird jeweils ein Array von Strukturen verwendet. In der Praxis können Sie auch verkettete Listen einsetzen. Der Aufruf der Programme lautet hierbei immer: > programmname suchstring datei1 ... bis datei_n Bei all den Zusätzen sollten Sie dennoch das Hauptaugenmerk auf die einzelnen Algorithmen richten. Alle Matching-Algorithmen suchen nach einer bestimmten Textfolge. Sofern Sie an ganzen Wörtern interessiert sind, können Sie den Algorithmus entsprechend anpassen. Dabei sollten Sie darauf achten, dass vor und nach dem Suchstring alle Whitespace-Zeichen beachtet werden (Newline, Tabulator und Space). ### 22.6.1 Brute-Force-Algorithmus Der einfachste Algorithmus liegt auf der Hand. Es werden alle infrage kommenden Positionen des Musters in einem Text überprüft, bis das Muster mit dem Text übereinstimmt oder das Ende des Texts gekommen ist. Das komplette Muster wird also beim Vergleich des Texts um eine Position nach vorn gezählt. Dies ist ein Brute-Force-Algorithmus (oder auch grober Algorithmus oder naiver Algorithmus). Abbildung 22.30 zeigt das simple Beispiel. Abbildung 22.30 Ablauf des Brute-Force-Algorithmus Hier sehen Sie den Quellcode zu diesem einfachen String-Matching-Algorithmus: > /* bruteforce.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define LEN 255 #define MAX_DAT 10 #define MAX_LINE 4096 #define LINE "---------------------------------------\n" struct datei{ char name[LEN]; /* Name der Datei */ int gefunden; /* Anzahl gefunden */ }; typedef struct datei DATEI; /* int i = der Textzählerstand * int j = der Musterzählerstand */ int BruteForce(char *muster, char *text) { int i = 0, j, cnt = 0; int m=strlen(muster); /* Länge Muster */ int n=strlen(text); /* Länge Text */ while (i<=n-m) { /* solange i kleiner als n-m */ /* solange Muster und Text gleich j++ */ for(j=0; j<m && muster[j]==text[i+j]; j++); if(j==m) { /* Ist die Länge von j gleich der vom Muster? */ printf("Pos. %3d, ",i); cnt++; } i++; /* im Text eine Position weiter */ } return cnt; } int main(int argc, char *argv[]) { DATEI suche[MAX_DAT]; char suchstring[LEN]; char read_line[MAX_LINE]; FILE *f; int i, j , ret, zeile; if(argc < 3) { fprintf(stderr, "Verwendung: %s suchstring datei1" " <datei2> - <datei%d>\n",argv[0],MAX_DAT); return EXIT_FAILURE; } strncpy(suchstring, argv[1], LEN); /* Kommandozeilen-Argumente auswerten */ for(i=2,j=0; j < MAX_DAT && i < argc; i++,j++) { strncpy(suche[j].name, argv[i], LEN); suche[j].gefunden = 0; } for(i = 0; i < argc-2; i++) { f = fopen(suche[i].name, "r"); if(f == NULL) { perror(NULL); continue; } zeile = 0; printf("\nDatei \"%s\": \n",suche[i].name); while( fgets(read_line, MAX_LINE, f) != NULL) { zeile++; ret = BruteForce(suchstring, read_line); if(ret != 0) { suche[i].gefunden+=ret; printf(" in Zeile %d\n",zeile); ret = 0; } } printf("Suchergebnisse in \"%s\": %d\n", suche[i].name, suche[i].gefunden); printf(LINE); fclose(f); } return EXIT_SUCCESS; } Wenn wir als Beispiel den Suchstring "ex" und als Muster "a example text" verwenden, wird die innere for-Schleife dabei nur dreimal inkrementiert, und zwar bei jedem Vorkommen des Buchstabens 'e'. Zweimal wird ein Ergebnis gefunden. Die Laufzeit des Algorithmus hängt natürlich vom Suchmuster ab, aber im Durchschnitt hat der Brute-Force-Algorithmus immer ein lineares Zeitverhalten. ### 22.6.2 Der Algorithmus von Knuth/Morris/Pratt (KMP) Der Nachteil des Brute-Force-Algorithmus ist der, dass dieser stur Zeichen für Zeichen, Position um Position vergleicht. Die Programmierer Knuth, Morris und Pratt, nach denen dieser Algorithmus auch benannt ist, haben diesen Algorithmus verbessert (verfeinert). Sie hatten die Idee, die Fehlvergleiche (sogenanntes Missmatch) in den weiteren Algorithmus mit einzubeziehen. Als Beispiel sei diese Textfolge gegeben (text): > lu lalalala lule lulalalas Der Suchstring (suchmuster) lautet alalas. Der Vorgang beginnt wie beim Brute-Force-Algorithmus: Abbildung 22.31 Auf der Suche nach dem Suchstring »alalas« – Start Hier haben Sie zwischen text[i] und suchmuster[j] keine Ãbereinstimmung. Daher kann suchmuster um eine Position weitergeschoben werden: Abbildung 22.32 Keine Ãbereinstimmung – der Suchstring wandert eine Position weiter. Dies wird so lange wiederholt, bis zwei gleiche Zeichen aufeinandertreffen: Abbildung 22.33 Das erste Zeichen stimmt überein. Solange text[i] jetzt gleich mit suchmuster[j] ist, werden i und j inkrementiert: Abbildung 22.34 Nach fünf Zeichen tritt ein Fehlvergleich auf. An Position text[9] und suchmuster[5] tritt hier eine Ungleichheit auf. Beim Brute-Force-Algorithmus würde jetzt das Muster wieder um eine Position nach vorn gesetzt werden. Und genau hier greift der Algorithmus von Knuth, Morris und Pratt ein. Die kleinstmögliche Verschiebung, bei der »alalas« sich mit sich selbst deckt, ist um zwei Stellen: Abbildung 22.35 Kleinstmögliche Verschiebung des Suchstrings selbst Im nächsten Schritt werden dabei auch zwei Stellen weitergeschoben, da Sie ja nun wissen, dass sich der Anfang nicht überlappt. Genauer gesagt: Sie wissen es jetzt, weil ich es Ihnen gesagt habe, wissen aber nicht, wie dies programmtechnisch geschieht. Hierfür ist eine Vorlaufphase erforderlich. Aber dazu gleich mehr. Abbildung 22.36 Verschiebung um zwei Stellen anstatt um eine In der Theorie hört sich das alles natürlich recht interessant an. Aber es in die Praxis umzusetzen, ist wesentlich komplizierter. Wie realisieren Sie eine kleinstmögliche Verschiebung um den Suchstring (suchmuster) selbst? Da die Berechnung einer solchen Verschiebung nicht vom Text abhängig ist, in dem die Suche stattfindet, sondern nur vom Suchtext (suchmuster), kann sie schon vor der eigentlichen Suche erstellt werden. Es wird dabei von einer Vorlaufphase (Preprocessing) gesprochen. Hier sehen Sie den Algorithmus, der eine Sprungtabelle aus dem Suchstring selbst für den eigentlichen Suchalgorithmus erstellt: > void init_next(char *suchmuster, int m) { int i, j; i = 0; j = next[0] = -1; /* solange i kleiner als der Suchstring ist */ while (i < m) { while (j > -1 && suchmuster[i] != suchmuster[j]) j = next[j]; i++; j++; if (suchmuster[i] == suchmuster[j]) next[i] = next[j]; else next[i] = j; } } Um nochmals zum Szenario zu kommen: Sie verwenden gerade einen Brute-Force-Algorithmus und vergleichen einzelne Zeichen. Findet jetzt ein Missmatch (suchmuster!=text) statt, wird in den bisher gefundenen und übereinstimmenden Zeichen von hinten ein String mit maximaler (L) Länge gesucht, der zugleich Anfang eines weiteren Strings ist. Danach wird das Zeichen mit L+1 (=next[j]) und dem i-ten Zeichen im Text verglichen. Dafür gibt es zwei Möglichkeiten: * Das Zeichen next[j] des Suchstrings stimmt mit dem i-ten Zeichen des Texts überein. Somit wird entweder ganz normal wie beim Brute-Force-Algorithmus fortgefahren, bis der ganze String gefunden wurde oder erneut ein Missmatch auftritt. In diesem Fall wird genauso fortgefahren wie beim ersten Missmatch. * Das Zeichen next[j] des Suchstrings stimmt nicht mit dem i-ten Zeichen des Texts überein. next[j] wird somit um den Wert 1 reduziert, und der Vergleich geht weiter. Tritt wieder ein Missmatch auf, wird next[j] dekrementiert, bis das erste Zeichen des Suchstrings erreicht wurde. In diesem Fall wird i inkrementiert, und das Ganze beginnt von vorn. Mit next[i] = j stellen Sie sicher, dass j-1 die Länge des gröÃten Endstücks, aber auch das Anfangsstück des Suchstrings ist. Ist suchmuster[i] gleich suchmuster[j], wird mit next[++i]=++j der Wert zugewiesen, da das next-Array immer das nächste Zeichen beinhaltet. Ist dies nicht der Fall, werden der Anfangsteil und der längste Endteil mit dem Muster verglichen, bis es zu einem positiven Vergleich zwischen muster[i] und muster[j] kommt. Nun folgt noch der eigentliche Algorithmus mit dem Suchstring und dem Textbeispiel, das eben verwendet wurde (alalas). > /* kmp.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 4096 void init_next(char *, int); void kmpSearch(char *, char *); int next[MAX]; /* i = Position im Text */ /* j = Position im Muster */ void kmpSearch(char *muster, char *text) { int i=0, j=0; int m=strlen(muster); /* Länge Muster */ int n=strlen(text); /* Länge Text */ init_next(muster, m); /* Tabelle für next berechnen */ while (i<n) { /* solange wir nicht am Ende vom Text sind */ while (j>=0 && text[i]!=muster[j])j=next[j]; i++; j++; if (j==m) { printf("Gefunden an Pos. %d\n", i-j); j = next[j]; } } } void init_next(char *muster, int m) { int i, j; i = 0; j = next[0] = -1; /* solange i kleiner als der Suchstring ist */ while (i < m) { while (j > -1 && muster[i] != muster[j]) j = next[j]; i++; j++; (muster[i] == muster[j]) ? (next[i]=next[j]) : (next[i]=j); } } int main(void) { kmpSearch("alalas", "lu lalalala lule lulalalas"); return EXIT_SUCCESS; } Das vollständige Listing des »Brute-Force-Algorithmus« umgeschrieben auf das Programmbeispiel: > /* kmpsearch.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define LEN 255 #define MAX_DAT 10 #define MAX_LINE 4096 #define MAX 255 #define LINE "_______________________________________\n" struct datei{ char name[LEN]; /* Name der Datei */ int gefunden; /* Anzahl gefunden */ }; typedef struct datei DATEI; int next[MAX]; int kmp_Search(char *, char *); void init_next(char *, int); int kmp_Search(char *muster, char *text) { int i=0, j=0, cnt=0; int m=strlen(muster); /* Länge Muster */ int n=strlen(text); /* Länge Text */ init_next(muster, m); /* Tabelle für next berechnen */ while (i<n) { /* solange wir nicht am Ende vom Text sind */ while (j>=0 && text[i]!=muster[j])j=next[j]; i++; j++; if (j==m) { printf("Gefunden an Pos. %d\n", i-j); cnt++; j=next[j]; } } return cnt; } void init_next(char *muster, int m) { int i, j; i = 0; j = next[0] = -1; /* solange i kleiner als der Suchstring ist */ while (i < m) { while (j > -1 && muster[i] != muster[j]) j = next[j]; i++; j++; (muster[i]==muster[j]) ? (next[i]=next[j]) : (next[i]=j); } } int main(int argc, char **argv) { DATEI suche[MAX_DAT]; char suchstring[LEN]; char read_line[MAX_LINE]; FILE *f; int i, j , ret, zeile; if(argc < 3) { fprintf(stderr, "Verwendung: %s suchstring datei1 " "<datei2> ... <datei%d>\n",argv[0],MAX_DAT); return EXIT_FAILURE; } strncpy(suchstring, argv[1], LEN); /* Kommandozeilen-Argumente auswerten */ for(i=2,j=0; j < MAX_DAT && i < argc; i++,j++) { strncpy(suche[j].name, argv[i], LEN); suche[j].gefunden = 0; } for(i = 0; i < argc-2; i++) { f = fopen(suche[i].name, "r"); if(f == NULL) { perror(NULL); continue; } zeile = 0; printf("\nDatei \"%s\": \n",suche[i].name); while( fgets(read_line, MAX_LINE, f) != NULL) { zeile++; ret = kmp_Search(suchstring, read_line); if(ret != 0) { suche[i].gefunden+=ret; printf(" in Zeile %d\n",zeile); ret=0; } } printf("Suchergebnisse in \"%s\": %d\n", suche[i].name, suche[i].gefunden); printf(LINE); fclose(f); } return EXIT_SUCCESS; } Der eine oder andere wird mir jetzt entgegnen, dass Kapitel sei viel zu schwer für ein Einsteiger-Buch. Im Prinzip muss ich dem zustimmen. Allerdings möchte ich zum Knuth-Morris-Pratt-Algorithmus sagen, dass ich hierbei versucht habe, diesen Algorithmus möglichst einfach zu erklären, ohne viele technische Begriffe aus der Welt der Mathematik und Informatik. AuÃerdem soll nicht unerwähnt bleiben, dass der Knuth-Morris-Pratt-Algorithmus immer noch einer der leichteren String-Matching-Algorithmen ist. ### 22.6.3 Weitere String-Matching-Algorithmen # <NAME> Der Boyer-Moore-Algorithmus ähnelt dem Brute-Force-Algorithmus und ist eine weitere Verbesserung gegenüber dem Knuth-Morris-Pratt-Algorithmus. Auch mit diesem Algorithmus werden Verschiebungen vorgenommen, und nicht mehr infrage kommende Verschiebungen werden übersprungen. Hierfür sind gleich zwei Vorlaufphasen (Preprocessing) notwendig – genauer gesagt zwei Heuristiken, die die Schrittweite bei der nächsten Verschiebung vorschlagen: * Schlechter-Buchstabe-Heuristik – Dabei wird untersucht, ob ein Zeichen im Text, das nicht mehr mit dem Pattern übereinstimmt, an einer anderen Stelle im Pattern vorkommt, und dann wird eine entsprechende Schrittweite vorgeschlagen. * Gutes-Suffix-Heuristik – Dabei wird untersucht, ob das Suffix des Patterns, das mit dem Text übereinstimmt, an einer anderen Stelle vorkommt, und dann wird auch hier eine entsprechende Schrittweite vorgeschlagen. # Karp Rabin Beim Karp-Rabin-Algorithmus wird jeder mögliche String des Musters in eine Hash-Tabelle eingetragen. Dafür wird eine spezielle Hash-Funktion geschrieben, die die Eigenschaft hat, dass sie bei dem Text für Startindex i effizient aus dem vorhergehenden Hash-Wert (Startindex = i-1) berechnet werden kann. Sind dabei zwei Hash-Werte gleich, wird wie beim Brute-Force-Algorithmus vorgegangen. Dies funktioniert nach folgendem Pseudocode: > hash_pattern = hash_wert_des_pattern hash_text = hash_wert_der_ersten_m_Zeichen_im_text do { if(hash_pattern == hash_text) bruteforce_vergleich hash_text = hash_wert_der_nächsten_m_Zeichen_des_Textes } while(Text_zu_Ende || bruteforce == wahr); # 22.7 Pattern Matching (reguläre Ausdrücke) ## 22.7 Pattern Matching (reguläre Ausdrücke) Jeder, der mit einer UNIX/Linux-Maschine zu tun hat, kennt wohl die regulären Ausdrücke. Reguläre Ausdrücke sind auch eine Form der Suche nach Zeichenketten, nur erheblich komfortabler und komplexer. Der Begriff »regulärer Ausdruck« stammt von dem Sprachwissenschaftler Noam Chomsky und wird in der Informatik verwendet. Es gibt zwar mehrere Varianten von regulären Ausdrücken, doch haben alle dasselbe Ziel. Bei einem regulären Ausdruck geht es darum, Muster aus Buchstaben zu beschreiben, und dies zusammen mit Wiederholungen, Alternativen und Abkürzungen für Zeichenklassifizierungen wie Ziffern oder Buchstaben. Das bekannteste Beispiel, mit dem sogar MS-DOS klarkommt und das jeder kennen dürfte, ist die Wildcard (*): > dir t*.txt oder unter UNIX: > ls -l t*.txt So werden alle Textdateien ausgegeben, die mit »t« beginnen und mit ».txt« enden: > text.txt test.txt total.txt Reguläre Ausdrücke sind keine Funktionen, sondern es handelt sich um eine echte Sprache mit formaler Grammatik, bei der jeder Ausdruck eine präzise Bedeutung hat. Hierzu folgen einige Funktionen in der Praxis, wobei diejenigen, die mit den regulären Ausdrücken überhaupt nicht vertraut sind, einen kleinen Einblick erhalten, und Anwender, die reguläre Ausdrücke schon häufiger verwendet haben, sehen werden, wie reguläre Ausdrücke in C geschrieben werden können. Es sei darauf hingewiesen, dass es sich dabei nicht um eine umfassende Anleitung zu regulären Ausdrücken handelt, sondern vielmehr um einen kurzen Ãberblick. Das Programm, das erstellt werden soll, liest Zeile für Zeile aus einer Datei aus. Die erste Funktion, die das Pattern Matching einleitet, sieht so aus: > int pmatch(char *ausdruck, char *text) { #ifdef __unix__ if(ausdruck[0] == '^') #elif __WIN32__ if(ausdruck[0] == '#') #endif return match(ausdruck+1, text); else { for( ; *text != '\0'; *text++) if(match(ausdruck, text)) return 1; } return 0; } Zuerst wird überprüft, ob der zu matchende Ausdruck am Anfang einer Zeile vorkommt. Dies ist gegeben, wenn der Ausdruck mit dem Zeichen '^' beginnt. Beispielsweise geben Sie als Suchstring folgenden Ausdruck an: > ^hallo Somit müssen die ersten fünf Zeichen einer Zeile in text mit der Zeichenfolge "hallo" übereinstimmen. Beispiele: > hallo welt wie gehts (Gefunden, da am Anfang der Zeile) hallo welt wie gehts (Missmatch -> nicht gefunden) Im Fall des Zeichens '^' muss der zu matchende Ausdruck inkrementiert werden, damit dieses Zeichen nicht mit verglichen wird. Bei Nichtverwendung des Zeichens '^' wird die Matching-Funktion ganz normal – Zeichen für Zeichen – aufgerufen. Jetzt folgt die Matching-Funktion match(): > int match(char *ausdruck, char *text) { if(ausdruck[0] == '\0') return 1; if(ausdruck[1] == '*') return wildcard(ausdruck[0], ausdruck+2, text); if(ausdruck[0] == '$' && ausdruck[1] == '\0') return *text == '\0'; if(*text != '\0' && (ausdruck[0]== '.'|| ausdruck[0] == *text) ) return match(ausdruck+1, text+1); return 0; } Zuerst wird getestet, ob das Ende des Patterns schon gekommen ist ('\0'). Danach wird überprüft, ob eine Wildcard (*) angegeben ist. Falls ja, wird die entsprechende Funktion aufgerufen, worauf in Kürze eingegangen wird. Das Zeichen '$' bedeutet beim Matching Zeilenende. Als Beispiel dient uns folgende Zeile: > match und$ *.txt Damit werden alle Ausdrücke gefunden, bei denen die Zeile mit »und« endet. Einige Beispiele: > Ein Text, der mit und endet und /* Gefunden */ Der Text endet nicht mit und und. /* Missmatch */ qwert asdf qwert asdf qwert und /* Gefunden */ und was jetzt /* Missmatch */ Um zu überprüfen, dass nicht nach dem Zeichen '$' gesucht wird, sondern dass es auch wirklich das gewünschte »und« am Ende der Zeile ist (in diesem Fall) ist, wird gleich darauf getestet, ob das nächste Zeichen des Ausdrucks das Endzeichen '\0' ist. Die nächste Ãberprüfung > if(*text != '\0' &&(ausdruck[0] == '.' || ausdruck[0] == *text)) testet, ob nicht schon das Ende gekommen ist, und das nächste Zeichen ein beliebiges sein darf (.) oder das Zeichen im Ausdruck mit demjenigen im Text übereinstimmt. Der Punkt steht somit für ein beliebiges Zeichen, abgesehen vom Zeichenende. Falls diese Bedingung zutrifft, wird die Funktion rekursiv erneut mit den nächsten Zeichen aufgerufen. Der rekursive Aufruf erfolgt so lange, bis eine der Bedingungen in dieser Funktion einen return-Wert (0 == keine Ãbereinstimmung oder 1 == Ãbereinstimmung gefunden) zurückliefert. Jetzt die (primitive) Wildcard-Funktion: > int wildcard(int c, char *ausdruck, char *text) { for( ;*text != '\0' && (*text == c || c == '.'); *text++) if(match(ausdruck, text)) return 1; return 0; } Zugegeben, dies ist eine schwache Wildcard-Funktion; aber sie funktioniert. Was bedeutet aber dieses Sternchen beim Pattern Matching? Der Stern zeigt an, dass das letzte Zeichen (oder der Inhalt) mindestens einmal oder mehrmals vorkommen kann, aber nicht vorkommen muss. Zum Abschluss sehen Sie noch das vollständige Listing: > /* regular_expression.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUF 4096 int pmatch(char *, char *); int match(char *, char *); int wildcard(int, char *, char *); int my_grep(char *, FILE *, char *); int pmatch(char *ausdruck, char *text) { if(ausdruck[0] == '^') return match(ausdruck+1, text); for( ; *text != '\0'; *text++) if(match(ausdruck, text)) return 1; return 0; } int match(char *ausdruck, char *text) { if(ausdruck[0] == '\0') return 1; #ifdef __unix__ if(ausdruck[1] == '*') #elif __WIN32__ if(ausdruck[1] == '~') #endif return wildcard(ausdruck[0], ausdruck+2, text); if(ausdruck[0] == '$' && ausdruck[1] == '\0') return *text == '\0'; if(*text != '\0' && ( ausdruck[0] == '.' || ausdruck[0] == *text)) return match(ausdruck+1, text+1); return 0; } int wildcard(int c, char *ausdruck, char *text) { for( ;*text != '\0' && (*text == c || c == '.'); *text++) if(match(ausdruck, text)) return 1; return 0; } int my_grep(char *ausdruck, FILE *f, char *name) { int n, nmatch=0; int line=0; char buffer[BUF]; while(fgets(buffer, sizeof(buffer), f) != NULL) { line++; n = strlen(buffer); if(n > 0 && buffer[n-1] == '\n') buffer[n-1] = '\0'; if(pmatch(ausdruck, buffer)) { nmatch++; if(name != NULL) printf("%d. ",line); } } if(nmatch!=0) printf("Zeile in der Datei %s (insg.%d)\n\n",name,nmatch); return nmatch; } int main(int argc, char *argv[]) { int i, nmatch=0; FILE *f; if(argc <= 2) { fprintf(stderr, "Verwendung des Programms : " "%s pattern quelle\n\n",*argv); return EXIT_FAILURE; } else { for(i = 2; i < argc; i++) { f = fopen(argv[i], "r"); if(NULL == f) { fprintf(stderr, "Konnte %s nicht " "oeffnen\n",argv[i]); continue; } if(my_grep(argv[1],f, argv[i]) > 0) nmatch++; fclose(f); } } printf("%d Dateien mit passenden Pattern %s gefunden\n", nmatch, argv[1] ); return EXIT_SUCCESS; } Hier folgen noch ein paar Matching-Beispiele zum Programm (der Programmname sei match und der Name der Datei test.txt). Folgende Textdatei soll gematcht werden: > ist ist ist. Matching | Gefunden in Zeile | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | Sie sehen schon, was für einen gewaltigen Funktionsumfang Sie mit wenigen Zeilen Code auf die Beine stellen können. Dabei stellt das Programm und das bisher vorgestellte Pattern Matching nur einen Bruchteil dessen dar, wozu Pattern Matching wirklich in der Lage ist. Sollten Sie also für Ihr Programm reguläre Ausdrücke benötigen, können Sie eigene Funktionen schreiben oder auf entsprechende Funktionen der Headerdatei <regex.h> zugreifen. Allerdings entsprechen diese Funktionen dem POSIX-Standard und sind vorwiegend in der UNIX-Welt zu Hause. MS-Windows-Anwender können diese Bibliothek aber zum Beispiel mit dem gcc-Compiler unter der Cygwin-Umgebung auch verwenden. # 22.8 Backtracking ## 22.8 Backtracking Backtracking ist ein Verfahren, das nach dem Trial-and-Error-Prinzip (Versuch und Irrtum) ausgeführt wird. Damit wird versucht, aus Teillösungen systematisch zu einer Komplettlösung zu kommen. Steht man beispielsweise bei einer Teillösung vor einer Sackgasse, werden einzelne bzw. mehrere Schritte wieder rückgängig gemacht. Gerät man wieder in eine Sackgasse, werden eben nochmals entsprechend viele Schritte zurück gemacht. Dieser Vorgang wird so lange wiederholt, bis man zu einer Lösung des Problems kommt oder feststellen muss, dass es zu diesem Problem keine Lösung gibt. ### 22.8.1 Der Weg durch den Irrgarten Das Prinzip soll anhand eines simplen Beispiels demonstriert werden. Wir erstellen ein Spielfeld mit Hindernissen (»*«). An der einen Ecke des Spielfeldes befindet sich »Mister C«, der Hunger hat. Auf der anderen Ecke befindet sich etwas zum Essen (»o«). Sie sollen nun mittels Backtracking Mister »C« über die Hindernisse »*« zum Essen »o« führen. Das Ganze sieht folgendermaÃen aus: > ################################################# #C * # # * * # # # # * * * * # # * * # # * * * * # # # # * * * * * # # * # # * * * # # * * * # # * * * o# ################################################# Das Spielfeld soll mit einem zweidimensionalen char-Array mit 15 Zeilen und 50 Spalten dargestellt werden: > // 15 Zeilen; 50 Spalten char spielfeld[15][50]; Mister C selbst soll sich erst mal in vier verschiedene Richtungen bewegen können: Abbildung 22.37 Koordinatensystem für Mister C Somit benötigen Sie vier verschiedene Funktionsaufrufe: jeweils einen für die Richtung +x (eine Zeile nach unten), -x (eine Zeile nach oben), +y (eine Spalte nach rechts) und -y (eine Spalte nach links). In der Praxis sehen diese Aufrufe folgendermaÃen aus: > step(x, y+1); step(x+1, y); step(x-1, y); step(x, y-1); Natürlich handelt es sich hierbei um Funktionsselbstaufrufe (Rekursionen). Für die optische Darstellung (Ausgabe des Spielfeldes) sollten Sie hierbei auch noch die alten Positionen von x und y als Argumente bzw. Parameter verwenden: > step(x, y+1, xalt=x, yalt=y); step(x+1, y, xalt=x, yalt=y); step(x-1, y, xalt=x, yalt=y); step(x, y-1, xalt=x, yalt=y); Als Nächstes müssen Sie bestimmen, in welche Richtung Mister C zuerst gehen soll. Im zweidimensionalen Array gesehen, befindet sich Mister C an Position [1][1] und das Essen an Position [13][48]. Somit können Sie selbst entscheiden, ob Sie zuerst nach rechts (y+1) oder nach unten (x+1) gehen wollen. Im Beispiel wurde die »Verstärkt-nach-rechts-gehen«-Strategie verwendet. Bevor wir Mister C also nach rechts schicken (y+1), müssen Sie zuerst überprüfen, ob sich in dieser Richtung ein Hindernis (»*«) befindet und ob Sie diese Spalte nicht schon einen Funktionsaufruf zuvor besucht haben (yalt!=y+1). Sind diese beiden Bedingungen erfüllt, können Sie den ersten rekursiven Funktionsaufruf starten (step(x,y+1,x,y)). Entscheidend für das Backtracking ist nun der Rückgabewert des rekursiven Funktionsaufrufes. Wird 1 zurückgegeben, wird der eben aufgerufene Zug ausgeführt. Hier ist der eben beschriebene Weg »nach rechts«: > if( y+1<49 && spielfeld[x][y+1] !='*' && yalt!=y+1 && step(x,y+1,x,y) ) return 1; Die nächsten drei Funktionsaufrufe mitsamt den Ãberprüfungen sehen recht ähnlich aus, nur dass diese eben für eine andere Richtung bestimmt sind: > else if( x+1<14 && spielfeld[x+1][y] !='*' && xalt!=x+1 && step(x+1,y,x,y)) return 1; else if( x-1>0 && spielfeld[x-1][y] !='*' && xalt!=x-1 && step(x-1,y,x,y) ) return 1; else if( y-1>0 && spielfeld[x][y-1] !='*' && yalt!=y-1 && step(x,y-1,x,y) ) return 1; Falls keiner dieser vier Aufrufe erfolgreich war, wird an den vorangegangenen Funktionsaufruf der Wert 0 (return 0) zurückgegeben, womit eben dieser Zug nicht ausgeführt wird. Die Abbruchbedingung ist erreicht, wenn sich Mister C an der Position des Essens (»o«) befindet. »Abgebrochen« wird aber auch, wenn das Labyrinth zu komplex ist und unser Mister C partout nicht ans Ziel finden will oder er in einer Sackgasse feststeckt, aus der es kein Zurück mehr gibt. Leider bedeutet dieser Abbruch auch einen Stack-Ãberlauf. Hierzu die komplette Funktion step(): > int step(int x, int y, int xalt, int yalt) { printf("<ENTER>"); getchar(); if(spielfeld[x][y] == 'O') { /* Sind wir am Ziel? */ spielfeld[x][y] = 'C'; spielfeld[xalt][yalt] = ' '; showspielfeld(); printf("<NAME> ist zu Hause!\n"); exit (EXIT_SUCCESS); } else if(spielfeld[x][y] == ' ') { spielfeld[x][y] = 'C'; spielfeld[xalt][yalt] = ' '; showspielfeld(); // ... nach rechts if( y+1<49 && spielfeld[x][y+1] !='*' && yalt!=y+1 && step(x,y+1,x,y) ) return 1; // ... nach unten else if( x+1<14 && spielfeld[x+1][y] !='*' && xalt!=x+1 && step(x+1,y,x,y) ) return 1; // ... nach oben else if( x-1>0 && spielfeld[x-1][y] !='*' && xalt!=x-1 && step(x-1,y,x,y) ) return 1; // ... nach links else if( y-1>0 && spielfeld[x][y-1] !='*' && yalt!=y-1 && step(x,y-1,x,y) ) return 1; } return 0; } Zum besseren Verständnis sollen hier ein paar Durchläufe gemacht werden. Aufgerufen wird die Funktion in main() mit: > step(1,1,1,1); Somit sieht es auf dem Spielfeld beispielsweise wie folgt aus: <NAME> befindet sich an Position [1][1] im Spielfeld. Zuerst wird in der Funktion step() überprüft, ob er bereits sein Ziel erreicht hat (was im Moment nicht der Fall ist): > if(spielfeld[x][y] == 'O') Als Nächstes müssen Sie überprüfen, ob die Position [1][1] überhaupt frei ist: > else if(spielfeld[x][y] == ' ' ) Ist diese Position frei, dann kann Mister C dort hingesetzt werden, und es sieht wie in der eben gezeigten Position aus. Jetzt wird überprüft, in welche Richtung Mister C gehen kann: > // ... nach rechts if( y+1<49 && spielfeld[x][y+1] !='*' && yalt!=y+1 && step(x,y+1,x,y) ) Im Beispiel ist die Richtung y+1 frei und wurde zuvor auch nicht besucht. Somit befindet sich auf dem Stack nun folgender Funktionsaufruf: > step(1, 1+1, 1, 1) Um ausgeführt zu werden, benötigt dieser Funktionsaufruf ja den Rückgabewert 1. Gehen wir mal ein paar Schritte nach vorn, wo Mister C zum ersten Mal auf ein Hindernis prallt. Folgende Funktionsaufrufe wurden bis dahin getätigt (auf dem Stack von oben nach unten): > step(1,3+1,1,1) step(1,2+1,1,1) step(1,1+1,1,1) Nun sieht das Ganze bildlich folgendermaÃen aus: Hier kommt zum ersten Mal nicht mehr die erste if-Anweisung zum Zuge, da spielfeld[x+1][y] != '*' nicht mehr zutrifft. Die nächste Ãberprüfung sieht so aus: > // ... nach unten else if( x+1<14 && spielfeld[x+1][y] != '*' && xalt != x+1 && step(x+1,y,x,y) ) Hier scheint es wieder weiterzugehen. Somit wird als Nächstes eine Zeile nach unten gesprungen, womit sich Mister C an Position [2][3] befindet: ``` ##################### # * # C * * # * * * #* * * ``` Sie können das Beispiel gern noch ein paar Schritte weiter durchgehen. Mit dem folgenden Beispiel können Sie den Weg von Mister C im echten Leben betrachten: > /* mister_c1.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> #ifdef __unix__ #define clrscr() printf("\x1B[2J") #elif __BORLANDC__ && __MSDOS__ #include <conio.h> #elif __WIN32__ || _MSC_VER #define clrscr() system("cls") #else #define clrscr() printf("clrscr() - Fehler!!\n") #endif #define HINDERNISSE 100 char spielfeld[15][50]; void createspielfeld(void) { int i, j, x, y; for(i=0, j=0; j < 50; j++) spielfeld[i][j] = '#'; for(i=1 ;i < 15; i++) for(j=0;j<50;j++) { if(j==0 || j==49) spielfeld[i][j] = '#'; else spielfeld[i][j] = ' '; if(i==13 && j==48) spielfeld[i][j] = 'O'; } for(i=14,j=0;j<50;j++) spielfeld[i][j] = '#'; for(i=0;i<=HINDERNISSE;i++) { x=rand()%14; y=rand()%48; if(x<15&&y<50 && x>0&&y>0) spielfeld[x][y] = '*'; } spielfeld[1][1]=' '; } void showspielfeld(void) { int i, j; clrscr(); for(i=0; i < 15; i++) for(j=0;j<50;j++) { printf("%c",spielfeld[i][j]); if(j==49) printf("\n"); } } int step(int x, int y, int xalt, int yalt) { printf("<ENTER>"); getchar(); if(spielfeld[x][y] == 'O') { /* Sind wir am Ziel? */ spielfeld[x][y] = 'C'; spielfeld[xalt][yalt] = ' '; showspielfeld(); printf("Mister C ist zu Hause!\n"); exit (EXIT_SUCCESS); } else if(spielfeld[x][y] == ' ') { spielfeld[x][y] = 'C'; spielfeld[xalt][yalt] = ' '; showspielfeld(); /* ... nach rechts */ if( y+1<49 && spielfeld[x][y+1] !='*' && yalt!=y+1 && step(x,y+1,x,y) ) return 1; /* ... nach unten */ else if( x+1<14 && spielfeld[x+1][y] !='*' && xalt!=x+1 && step(x+1,y,x,y) ) return 1; /* ... nach oben */ else if( x-1>0 && spielfeld[x-1][y] !='*' && xalt!=x-1 && step(x-1,y,x,y) ) return 1; /* ... nach links */ else if( y-1>0 && spielfeld[x][y-1] !='*' && yalt!=y-1 && step(x,y-1,x,y) ) return 1; } return 0; } int main(void) { createspielfeld(); step(1,1,1,1); return EXIT_SUCCESS; } Das Programm bei der Ausführung: Abbildung 22.38 Mister C auf der Suche nach dem Essen Dieser Code ist sehr stark auf Rechtsdrang ausgerichtet. Befindet sich Mister C an einer anderen Position, müssen Sie eben das Backtracking den Umständen anpassen. Wenn Sie im Beispiel die Anzahl der Hindernisse erhöhen, werden Sie merken, dass Mister C irgendwann keinen Ausweg mehr findet, obwohl es rein theoretisch noch welche gibt – sprich, Mister C dreht sich im Kreise. Um dieses Problem zu umgehen, können Sie entweder den Quellcode noch etwas verkomplizieren oder Sie statten Mister C mit weiteren Fähigkeiten aus. Hierfür würde sich beispielsweise eignen, dass sich Mister C auch in die diagonalen Richtungen bewegen kann. Abbildung 22.39 Mehr Bewegungsfreiheit für Mister C Somit hätten Sie jetzt folgende vier neue Bewegungen, die Sie in den Code einbauen müssten: > rechtshoch(x-1,y+1) rechtsrunter(x+1,y+1) linksrunter(x+1,y-1) linkshoch(x-1,y-1) Als Nächstes gilt es auch hier wieder festzulegen, in welcher Reihenfolge diese (jetzt acht) Bewegungen überprüft und ausgeführt werden sollen, um ans Ziel zu kommen. Da sich das Ziel rechts unten befindet, sollten Sie auch wieder diese Richtung als erste Priorität benutzen. Hierfür schlage ich folgenden Weg vor: > if(rechts=frei) else if(rechtsrunter=frei) else if(rechtsoben=frei) else if(nachunten=frei) else if(linksrunter=frei) else if(oben=frei) else if(links=frei) else if(linksoben=frei) else return 0 Umgeschrieben auf die Funktion step() sieht dies wie folgt aus: > int step(int x, int y, int xalt, int yalt) { printf("<ENTER>"); getchar(); if(spielfeld[x][y] == 'O') { /* Sind wir am Ziel? */ spielfeld[x][y] = 'C'; spielfeld[xalt][yalt] = ' '; showspielfeld(); printf("Mister 'C' ist zu Hause!\n"); exit (EXIT_SUCCESS); } else if(spielfeld[x][y]==' ') { spielfeld[x][y]='C'; spielfeld[xalt][yalt]=' '; showspielfeld(); /* rechts */ if( y+1<49 && spielfeld[x][y+1] != '*' && yalt!=y+1 && step(x,y+1,x,y) ) return 1; /* rechts unten */ else if( y+1<49 && x+1<14 && spielfeld[x+1][y+1] !='*' && xalt!=x+1 && yalt!=y+1 && step(x+1,y+1,x,y) ) return 1; /*rechts oben*/ else if( x-1>0 && y+1<49 && spielfeld[x-1][y+1]!='*' && xalt!=x-1 && yalt!=y+1 && step(x-1,y+1,x,y)) return 1; /* nach unten */ else if( x+1<14 && spielfeld[x+1][y] !='*' && xalt!=x+1 && step(x+1,y,x,y) ) return 1; /* links runter */ else if(x+1<14 && y-1>0 && spielfeld[x+1][y-1]!='*' && xalt!=x+1 && yalt!=y-1 && step(x+1,y-1,x,y)) return 1; /* nach oben */ else if( x-1>0 && spielfeld[x-1][y] !='*' && xalt!=x-1 && step(x-1,y,x,y)) return 1; /* nach links */ else if( y-1>0 && spielfeld[x][y-1] !='*' && yalt!=y-1 && step(x,y-1,x,y)) return 1; /* links oben */ else if( x-1>0 && y-1>0 && spielfeld[x-1][y-1] !='*' && xalt!=x-1 && yalt!=y-1 && step(x-1,y-1,x,y)) return 1; } spielfeld[x][y] = ' '; return 0; } Wenn Sie diese Funktion in das vorige Beispiel einbauen, werden Sie merken, dass Mister C es nun schon mit mehreren Hindernissen aufnehmen kann. Aber ab einer gewissen Anzahl von Hindernissen scheitert Mister C auch hier wieder – und dies, obwohl wir noch nicht in eine Sackgasse gekommen sind. Also benötigen Sie noch eine Funktion, die sich merkt, ob ein Feld bereits besucht wurde oder nicht. Dies stellt sich als einfaches Unterfangen dar, indem man einfach ein weiteres zweidimensionales Array verwendet: > int besucht[15][50]; Alle Felder werden erst einmal mit dem Wert 0 initialisiert. Im Programmverlauf müssen Sie anschlieÃend nur noch die Position, die bereits besucht wurde, mit dem Wert 1 versehen. Allerdings bedeutet dies auch, dass Sie in jeder Richtung eine weitere Bedingung in der Funktion step() überprüfen müssen. Hier sehen Sie den kompletten Quellcode mit einem »intelligenten« Mister C: > /* mister_c2.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> #ifdef __unix__ #define clrscr() printf("\x1B[2J") #elif __BORLANDC__ && __MSDOS__ #include <conio.h> #elif __WIN32__ || _MSC_VER #define clrscr() system("cls") #else #define clrscr() printf("clrscr() - Fehler!!\n") #endif #define HINDERNISSE 200 char spielfeld[15][50]; /* 1=besucht,0=nicht besucht */ int besucht[15][50]; void createspielfeld(void) { int i, j, x, y; for(i=0, j=0; j < 50; j++) spielfeld[i][j] = '#'; for(i=1 ;i < 15; i++) for(j=0;j<50;j++) { if(j==0 || j==49) spielfeld[i][j] = '#'; else spielfeld[i][j] = ' '; if(i==13 && j==48) spielfeld[i][j] = 'O'; } for(i=14,j=0;j<50;j++) spielfeld[i][j] = '#'; for(i=0;i<=HINDERNISSE;i++) { x=rand()%14; y=rand()%48; if(x<15&&y<50 && x>0&&y>0) spielfeld[x][y] = '*'; } spielfeld[1][1] = ' '; for(i=0; i<15; i++) for(j=0; j<50; j++) besucht[i][j] = 0; } void showspielfeld(void) { int i, j; clrscr(); for(i=0; i < 15; i++) for(j=0;j<50;j++) { printf("%c",spielfeld[i][j]); if(j==49) printf("\n"); } } int step(int x, int y, int xalt, int yalt) { printf("<ENTER>"); getchar(); if(spielfeld[x][y] == 'O') { /* Sind wir am Ziel? */ spielfeld[x][y] = 'C'; spielfeld[xalt][yalt] = ' '; showspielfeld(); printf("Mister 'C' ist zu Hause!\n"); exit (EXIT_SUCCESS); } else if(spielfeld[x][y] == ' ') { besucht[x][y] = 1; spielfeld[x][y]='C'; spielfeld[xalt][yalt]=' '; showspielfeld(); /* rechts */ if( y+1<49 && spielfeld[x][y+1] !='*' && yalt!=y+1 &&besucht[x][y+1]!=1 && step(x,y+1,x,y)) return 1; /* rechts unten */ else if( y+1<49 && x+1<14 && spielfeld[x+1][y+1] !='*' && xalt!=x+1 && yalt!=y+1 && besucht[x+1][y+1]!=1 && step(x+1,y+1,x,y)) return 1; /* rechts oben */ else if( x-1>0 && y+1<49 && spielfeld[x-1][y+1]!='*' && xalt!=x-1 && yalt!=y+1 && besucht[x-1][y+1]!=1 && step(x-1,y+1,x,y) ) return 1; /* nach unten */ else if( x+1<14 && spielfeld[x+1][y] !='*' && xalt!=x+1 && besucht[x+1][y]!=1 && step(x+1,y,x,y) ) return 1; /* links unten */ else if( x+1<14 && y-1>0 && spielfeld[x+1][y-1]!='*' && xalt!=x+1 && yalt!=y-1 && besucht[x+1][y-1]!=1 && step(x+1,y-1,x,y) ) return 1; /* nach oben */ else if( x-1>0 && spielfeld[x-1][y] !='*' && xalt!=x-1 && besucht[x-1][y]!=1 && step(x-1,y,x,y) ) return 1; /* nach links */ else if( y-1>0 && spielfeld[x][y-1] !='*' && yalt!=y-1 && besucht[x][y-1]!=1 && step(x,y-1,x,y) ) return 1; /* links oben */ else if( x-1>0 && y-1>0 && spielfeld[x-1][y-1] !='*' && xalt!=x-1 && yalt!=y-1 && besucht[x-1][y-1]!=1 && step(x-1,y-1,x,y) ) return 1; } spielfeld[x][y]=' '; return 0; } int main(void) { createspielfeld(); step(1,1,1,1); return EXIT_SUCCESS; } Auch wenn Ihnen das ganze Thema recht komplex erscheinen mag, so entspricht dies doch einem logischen Ablauf. Man muss eben 1 zurückgeben, wenn der Weg, den man probiert hat, ans Ziel führt. Befindet man sich in einer Sackgasse, muss man einen anderen Wert zurückgeben (in diesem Beispiel 0). AuÃerdem sollte man einen Weg, den man schon einmal gegangen ist, nicht nochmals zurückgehen (da dieser bekanntlich nicht zum Ziel führt). Mit dieser Strategie kommen Sie durch einen beliebig komplexen Irrgarten immer ans Ziel (sofern ein Weg zum Ziel existiert und der Irrgarten nicht so komplex ist, dass es einen Stack-Ãberlauf gibt). ### 22.8.2 Das 8-Dame-Problem Ein etwas weiter verbreitetes Beispiel für das Backtracking ist das 8-Dame-Problem. Die Aufgabe lautet: »Positionieren Sie 8 Damen auf einem Schachbrett so, dass diese sich nicht gefährden.« Für diejenigen, die es nicht wissen: Die Dame kann von ihrer aktuellen Position aus beliebig viele Felder in der gleichen Spalte, in der gleichen Reihe oder in den Diagonalen rücken – was bedeutet, dass in diesen Richtungen keine andere Dame stehen darf. Versuchen Sie es mal auf dem Schachbrett nachzuahmen. Es gibt exakt 92 Möglichkeiten. Sie haben hierbei die Möglichkeit, ein zweidimensionales Array für das Schachbrett zu verwenden, aber da sich zwei Damen in der gleichen Reihe oder Spalte sowieso bedrohen würden, können Sie sich das ersparen. Da die erste Dame, die Sie setzen, keine Bedrohung zu befürchten hat, setzen wir diese gleich an die rechte obere Ecke. Somit könnte der Funktionsaufruf wie folgt aussehen: > int schachbrett[8]; int i; for(i = 0; i < 8; i++) schachbrett[i] = 0; /* Dame an die linke obere Ecke */ dame(schachbrett, 7); Hierzu nun ein Teil der Funktion dame(): > int dame(int *schachbrett, int position) { int x = 1; static int counter = 1; while(x<=8) { schachbrett[position] = x; Der Wert x dient zur Identifizierung der einzelnen Damen. Jede Dame bekommt eine Nummer. Des Weiteren dient dieser Wert auch noch zur Ãberprüfung, ob eine Dame in der Diagonalen gefährdet wird. Aber dazu später mehr. Mit der Zeile > schachbrett[position] = x; bekommt das Feld 7 (genauer Feld 8, aber da hier 0 ebenfalls als erstes Feld präsent ist, eben 0 bis 7 anstatt 1 bis 8) rechts oben den Wert 1: Abbildung 22.40 Die erste Dame wurde rechts oben gesetzt (1). Als Nächstes benötigen Sie eine Funktion, um zu testen, ob die Dame mit der Nummer 1 auf der Reihe, Spalte und Diagonalen mit einer anderen Dame kollidiert: > if(!dame_in_gefahr(schachbrett)) Der Funktion übergeben Sie lediglich die Daten vom Schachbrett. Im ersten Durchlauf wird die Bedingung logischerweise wahr sein – d. h., die Dame ist nicht in Gefahr. Jetzt müssen Sie überprüfen, ob Sie nicht schon an Position 0 angekommen sind (bildlich wäre das, in einer Spalte ganz unten angekommen zu sein): > if(position) Falls Sie noch nicht die ganze Spalte durch haben, beginnt ab hier der erste rekursive Aufruf (und eine Erhöhung des Stacks): > // die nächste Dame setzen if(dame(schachbrett,position-1)) return 1; Nochmals die Funktion bis hierher im Ãberblick: > int dame(int *schachbrett, int position) { int x = 1; static int counter = 1; while(x <= 8) { schachbrett[position]=x; if(!dame_in_gefahr(schachbrett)) { if(position) { /* die nächste Dame ... */ if(dame(schachbrett,position-1)) return 1; /* Dame an diese Position setzen */ } else return 1; Mit dem erneuten Funktionsaufruf sieht die Situation folgendermaÃen auf dem Schachbrett aus: Abbildung 22.41 Erster rekursiver Funktionsaufruf – eine weitere Dame Jetzt ist eine Dame an Position 7 in Gefahr, und folgende Bedingung trifft nicht zu: > if(!dame_in_gefahr(schachbrett)) Folglich wird der Zähler x um 1 inkrementiert: > x++; Bildlich dargestellt, ergibt sich nun durch folgende Code-Zeile folgender Zustand auf dem Schachbrett: > schachbrett[position]=x; Abbildung 22.42 Ein weiterer Zug der zweiten Dame Auch in dieser Stellung liegt eine Kollision vor. Also wird x nochmals inkrementiert, womit Sie folgenden Zustand vorfinden: Abbildung 22.43 Ein weiterer Zug, und es ist keine Kollision mehr vorhanden. Jetzt gefährden sich beide Damen nicht mehr, und somit wird wieder ein erneuter rekursiver Funktionsaufruf ausgeführt. Der Stand der aktuellen Funktion wird wieder auf den Stack getan (zweite Funktion auf dem Stack) und wartet wiederum auf ihren Einsatz. Jetzt geht das Spiel von Neuem los. Der nächste Schritt sieht bildlich so aus (siehe Abbildung 22.44). Abbildung 22.44 Der zweite rekursive Funktionsaufruf von »dame()« Da die Dame in den nächsten drei Reihen sowieso kollidiert, überspringen wir diese drei Schritte, wo jeweils der Wert von x dreimal inkrementiert wird, bis folgende Stellung erreicht wurde: Abbildung 22.45 Es ist keine Kollision mehr vorhanden. Wohl gemerkt heiÃt das noch lange nicht, dass dies die endgültige Stellung darstellt, da alle diese Funktionsaufrufe noch auf dem Stack liegen und darauf warten, was mit ihnen passieren soll (1 = bleibt so; 0 = weitersuchen). Nach weiteren rekursiven Funktionsaufrufen passiert endlich etwas: Abbildung 22.46 Noch gibt es keine Kollision. Der nächste Funktionsaufruf (für die erste Spalte) wird nun den Wert 0 zurückgeben, da sich in der ersten Spalte keine Dame platzieren lässt, ohne dass diese sich mit einer anderen gefährdet. Jetzt »trackt« unsere Funktion zur zweiten Spalte »back«. Der Wert von x, der auf dem Stack gespeichert wurde, betrug in der zweiten Spalte 6, somit wird dieser wieder inkrementiert und es geht in Zeile 7 (zweite Spalte) weiter. Dort findet eine weitere Kollision statt, ebenso wie in der Zeile 8 (zweite Spalte). Somit bekommt auch der Aufrufer der zweiten Spalte den Wert 0 zurück, und unser Programm nimmt seine Ausführung in der dritten Spalte (von links) und der vierten Zeile (Wert von x ist hier 4) wieder auf. Weitere Inkrementierungen in dieser Spalte bringen auch keinen Erfolg, sondern nur weitere Kollisionen. Dies geht so lange weiter zurück, bis entweder keine Kollision mehr stattfindet (dann geht es wieder »nach vorne« weiter) oder die Bedingung > if(position) unwahr wird. Das heiÃt, wir sind am Ende angekommen. Dies wird mit einem return 1 bestätigt: > if(position) { if(dame(schachbrett,position-1)) return 1; //Dame an diese Position setzten } else return 1; //Wir sind fertig, wir haben eine Lösung ... oder aber auch, wenn Sie alle 92 Möglichkeiten ausgeben wollen. Wir benutzten Letzteres. Ich empfehle Ihnen, um das ganze Programm besser zu verstehen, es Schritt für Schritt auf einem Schachbrett nachzuspielen. Hierzu noch das komplette Listing, das das 8-Dame-Problem programmtechnisch auflöst: > /* 8dame.c */ #include <stdio.h> #include <stdlib.h> int dame_in_gefahr(int *schachbrett) { /* x==nach unten; y==nach rechts */ int x,y; for(x=0; x<7; x++) /* Ist auf feld[x] eine Dame? */ if(schachbrett[x]) for(y=x+1; y<=7; y++) /* Ist auf feld[y] eine Dame? */ if(schachbrett[y]) { /* Wir überprüfen, ob die beiden * Damen kollidieren. */ /* Sind beide Damen in derselben Zeile? */ if(schachbrett[x]==schachbrett[y]) return 1; /* Kollision in gleicher Zeile */ /* Diagonal? */ if(abs(x-y)==abs(schachbrett[x]-schachbrett[y])) return 2; /* Kollision in der Diagonalen */ } return 0; /* keine Kollision! */ } int dame(int *schachbrett, int position) { int x = 1, i; static int counter = 1; while(x <= 8) { /* Wir setzen die Dame mit der * Nummer x an feld[position]. */ schachbrett[position]=x; if(!dame_in_gefahr(schachbrett)) { if(position) { /* die nächste Dame */ if(dame(schachbrett,position-1)) return 1; /* Dame an diese Position setzen */ } else { printf("Loesungs-Nr.%2d : ", counter++); for(i=0; i<8; i++) printf("(%d,%d)", i+1, schachbrett[i]); printf("\n"); } } x++; } schachbrett[position] = 0; return 0; } int main(void) { int schachbrett[8], x; for(x=0; x < 8; x++) schachbrett[x] = 0; dame(schachbrett,7); return EXIT_SUCCESS; } In der Zeile > if(abs(x-y)==abs(schachbrett[x]-schachbrett[y])) wird eine absolute Zahl berechnet, das heiÃt beispielsweise, der absolute Wert von 2–6 ist 4 und nicht –4. Diese Berechnung und Bedingung dient dazu, zu überprüfen, ob in der Diagonalen eine Kollision mit einer Dame stattfindet. Hier sehen Sie noch eine der 92 möglichen Lösungen: Abbildung 22.47 Keine Dame ist gefährdet. # 23.2 Vorteile von CGIs in C ## 23.2 Vorteile von CGIs in C Es ist unumstritten, dass aufgrund mächtiger String-Verarbeitungsmöglichkeiten Perl die Sprache ist, die am häufigsten für das Schreiben von CGI-Skripten verwendet wird. Perl ist (meiner Meinung nach) einfacher zu lernen als C, und der Aufwand beim Programmieren hält sich bei Perl in Grenzen. Wo Sie in C ganze Routinen schreiben müssen, kommt Perl gerade einmal mit ein bis zwei Zeilen aus. Es ist aber nicht der Zweck dieses Buches, die Vor- und Nachteile diverser Programmiersprachen zu diskutieren. Abbildung 23.1 Der Ablauf in einer CGI-Schnittstelle Einige Vorteile von CGI-Anwendungen, die in C erstellt wurden, sollen aber doch erwähnt werden: * Es finden weniger Zugriffe auf den Server statt, auf dem sich das CGI-Skript befindet. Das heiÃt, es muss nicht erst ein Interpreter gestartet werden, der das Skript übersetzen muss. * C ist eine schnelle und systemnahe Sprache. Daher ist die Lade- und Initialisierungszeit gegenüber der Ausführzeit ausgeglichener als bei anderen Sprachen. * Die Programme sind recht klein. * Für alle Betriebssysteme gibt es einen Compiler. * Da der Quelltext bei Executables nicht offen ist, lassen sich Sicherheitsfunktionen hervorragend verstecken. Gerade diesen Sicherheitsaspekt gilt es besonders hervorzuheben. # 23.3 Andere Techniken der Webprogrammierung ## 23.3 Andere Techniken der Webprogrammierung Der Hauptgrund für den ungebremsten Boom des World Wide Web ist vor allem die Plattformunabhängigkeit der Beziehung zwischen dem Server und dem Client. Es muss dabei nicht auf das Betriebssystem, die Computerhardware oder die Netzwerkkonfiguration geachtet werden, solange Server und Client denselben Protokollstandard verwenden. Dank der einheitlichen Protokolle (HTTP, FTP  ) stieg die Verfügbarkeit unterschiedlicher Webserver, Webbrowser, Programmiersprachen und Scripting-Technologien explosionsartig an. Die Webtechnologien werden in zwei funktionelle Kategorien (serverseitig und clientseitig) und drei konzeptionelle Schichten (Darstellungsschicht, Verarbeitungsschicht, Speicherschicht) eingeteilt. Auf den folgenden Seiten gehe ich etwas genauer darauf ein. # 23.4 Das dreistufige Webanwendungsdesign ## 23.4 Das dreistufige Webanwendungsdesign ### 23.4.1 Darstellungsschicht Die erste Stufe der Webprogrammierung ist die Darstellungsschicht. Dies stellt auch immer noch die am weitesten verbreitete Schicht dar. Der Webbrowser fordert mit dem HTTP-Protokoll eine Datei vom Webserver an. Der Webserver schickt dem Browser anschlieÃend diese Datei, was meistens die Darstellung einer einfachen Webseite ist. Zur Darstellungsschicht gehört das ganze Look & Feel einer Seite, wie etwa Mausklicks, Lesevorgänge usw., eben einfach alle Interaktionen des Nutzers. Die Darstellungsschicht wird mithilfe von Webscripting-Sprachen wie z. B. HTML oder JavaScript erarbeitet. Dabei handelt es sich um interpretierte Sprachen, die erst beim Zugriff der Webseite auf den Webserver analysiert werden. ### 23.4.2 Verarbeitungsschicht In der Verarbeitungsschicht finden Vorgänge wie Fehlerprüfungen, Plausibilitätsprüfung und Auswertung der Formularfelder statt. Wird z. B. eine E-Mail aus einer Webanwendung verschickt, wird in der Verarbeitungsschicht überprüft, ob die Eingaben richtig sind. Danach wird koordiniert, mit welchem E-Mail-Programm diese Mail versendet wird. In der Verarbeitungsschicht werden natürlich noch eine Menge anderer Arbeiten verrichtet. Dazu erfahren Sie ja im Laufe dieses Kapitels mehr. Die Verarbeitungsschicht wird häufig mit interpretierten Scripting-Sprachen wie Perl, PHP, ASP und Programmiersprachen wie C/C++ erledigt. Interpretierte Sprachen sind bei gewissen Verarbeitungsvorgängen recht langsam und werden daher auf der Serverseite ausgeführt. Und um nochmals auf das Beispiel mit dem E-Mail-Programm zurückzukommen: Auf der Serverseite ist dabei sichergestellt, dass die E-Mail mit einem bestimmten Programm (meistens mit dem Programm sendmail) versendet wird. Auf der Seite des Clients würde das wiederum voraussetzen, dass der Nutzer dieses Programm auf seinem Computer installiert hat. Das ist nicht unbedingt benutzerfreundlich. ### 23.4.3 Speicherschicht Irgendwann werden Sie auch Daten speichern wollen. Es gibt viele Gründe, Daten zu speichern, seien es Statistiken, Berechnungen oder Registrierungsdaten. Und je komplexer und umfangreicher die Daten werden, die Sie zu speichern beabsichtigen, umso besser muss die Lösung sein. Für einen simplen Besucherzähler reicht eine Textdatei aus, da sich darin immer nur eine Zahl befindet. Aber sobald Sie Anwendungen wie einen Online-Shop erstellen wollen, kommen Sie um eine Datenbank nicht mehr herum. Denn müssen Sie dabei Daten ändern, löschen oder Teile der Daten extrahieren, ist dies bei einer Datenbank häufig mit wenig Code zu bewerkstelligen. Heutzutage stehen auch eine Menge Datenbanklösungen für herstellerspezifische Erweiterungen zur Verfügung. Und vor allem: Viele dieser Lösungen kosten kaum Geld. Mehr dazu erfahren Sie in Kapitel 24, »MySQL und C«. # 23.5 Clientseitige Programmierung ## 23.5 Clientseitige Programmierung Es gibt mittlerweile zahlreiche Programmiertechniken, die dem Webprogrammierer auf der Clientseite zur Verfügung stehen. Einige von diesen sind systemabhängig und daher für die Webprogrammierung weniger nützlich. Hier folgt ein kleiner Ãberblick über clientseitige Skriptsprachen und deren Vor- bzw. Nachteile. ### 23.5.1 JavaScript JavaScript ist eine Untermenge von Java, die direkt im Webbrowser implementiert ist. Mit JavaScript können Sie Formulare prüfen, rechnen, Fenster maÃgenau öffnen und noch viel mehr. Der Nachteil von JavaScript: Wenn das Script auf dem einen Browser läuft, kann es bei dem anderen dazu führen, dass nicht einmal die Webseite dargestellt wird. Und ein weiterer Nachteil: Der Surfer kann JavaScript ganz abschalten. Wenn Sie dann noch die ganze Navigation auf JavaScript aufbauen, war die Arbeit umsonst. Und den Surfer sehen Sie wahrscheinlich auch nie wieder. Sollten Sie also JavaScript für Ihre Webseite wählen, vergessen Sie niemals, <noscript></noscript> zu verwenden. Dies bedeutet für Webbrowser, die kein JavaScript verstehen, dass der Code zwischen diesen Tags ausgeführt wird. Auf JavaScript folgten noch eine Menge unterschiedlicher Variationen von Microsoft wie Jscript und VBScript, wobei Jscript eine Erweiterung von JavaScript ist und VBScript auf der Syntax von Visual Basic beruht. Wer vorhat, eine dieser beiden Skriptsprachen einzusetzen, schlieÃt allerdings Surfer mit anderen Systemen aus. ### 23.5.2 Java-Applets Java hat übrigens mit JavaScript bis auf die Namensähnlichkeit nichts gemeinsam. Java ist eine vollständige Programmiersprache, eine Weiterentwicklung zu C++, die von SUN herausgebracht wurde. Damit können aufwendige Menüs bis hin zu interaktiven Spielen im Web erzeugt werden. Der Vorteil von Java-Applets sind die Plattformunabhängigkeit und die Sicherheit, da der Code nicht einsehbar ist. # 23.6 Serverseitige Programmierung ## 23.6 Serverseitige Programmierung Heute gibt es zahlreiche Möglichkeiten, serverseitige Anwendungen zu programmieren. Es gibt mittlerweile unzählig viele Schnittstellen, mit denen dynamische Webseiten auf dem Webserver generiert und gesendet werden. Es existieren dabei zwei Arten von serverseitiger Webprogrammierung: Die eine stützt sich auf kompilierte Objekte, und die andere verwendet das Modell der Skriptsprachen. Der Unterschied zwischen diesen beiden Arten ist einfach, aber trotzdem eindeutig. Skriptsprachen werden auf dem Webserver von einem Interpreter zur Laufzeit analysiert. Kompilierte Objekte liegen auf dem Webserver schon ausführbereit vor und müssen nur noch gestartet werden. Somit laufen Skriptsprachen in der Regel etwas langsamer als kompilierter Code ab. Das Ziel der serverseitigen Programmierung bleibt allerdings immer dasselbe – dynamisch erzeugter HTML-Code soll in Form einer Webseite in Ihrem Browser ausgegeben werden. Nun soll auf die CGI-Schnittstelle eingegangen werden. CGI wird häufig als eine Programmiersprache bezeichnet, was es aber nicht ist. CGI ist ein standardisiertes Gateway, das eine Schnittstelle zwischen einem Webserver und dem serverseitigen Code darstellt. Dass CGI immer noch so populär ist, verdankt diese Schnittstelle ihrer Vielsprachigkeit. Sie können praktisch mit jeder Programmiersprache, die etwas ausgeben kann, CGI-Skripte schreiben. Der einzige Nachteil von CGI ist der Verarbeitungsaufwand eines Skripts, da jede CGI-Anfrage einen separaten Prozess in einem separaten Speicherbereich auf dem Webserver benötigt. Diesen Nachteil haben die Entwickler von Webservern allerdings nicht auf sich beruhen lassen, und sie haben fleiÃig an einer Lösung des Problems gearbeitet. Die Entwickler brachten webserverspezifische APIs (Application Programming Interfaces) heraus. Diese APIs waren voll im Webserver integriert und liefen auch in der Regel schneller ab als einfache Skripte. Der Nachteil solcher APIs ist aber, dass diese mit einem Webserver »verschweiÃt« sind. Sie machen also nur für Webserver Sinn, die auf mehreren Systemen erhältlich sind (z. B. Apache). Zu solchen Standalone-Skriptsprachen zählen etwa ASP (Active Server Pages), JSP (Java Server Pages), CFML (Cold Fusion Markup Language) und letztendlich die immer populärere (oder schon populärste) Skriptsprache PHP. Aber auch für Perl gibt es Standalone-CGI-Anwendungen wie z. B. mod_perl oder FastCGI. # 23.7 Der Webserver ## 23.7 Der Webserver ### 23.7.1 Das Client/Server-Modell des Internets Das Internet oder genauer das World Wide Web wurde nach dem Client/Server-Prinzip entwickelt. Der Webbrowser ist in dieser Architektur der Client. Geben Sie z. B. in den Webbrowser die Adresse http://www.pronix.de/ ein, ruft der Browser Dienste im Web ab. In diesem Fall wird eine HTTP-Anforderung über das Netzwerk verschickt. Mit dem HTTP-Protokoll haben Sie jetzt Zugriff auf Dateien von Servern in Netzwerken. Der Server oder genauer der Webserver verarbeitet nun die Anfrage des Clients. Dabei ist der Standort des Webservers egal. Dieser kann sich im selben Gebäude, auf der anderen Seite der Erde oder auch auf demselben Computer befinden. Meistens besteht die Aufgabe des Webservers im Internet darin, ein angefordertes Dokument an den Client zurückzuschicken, beispielsweise HTML-Daten zur Darstellung einer Webseite. Der Webserver wird häufig auch als HTTP-Dämon (Hypertext Transfer Protocol Daemon) bezeichnet. Abbildung 23.2 stellt den Vorgang einer solchen Transaktion bildlich dar: Abbildung 23.2 Transaktion einer HTTP-Anfrage ### 23.7.2 Serverimplementierung Bevor Sie sich, sei es privat oder für eine Organisation, für eine Webpräsenz entscheiden, müssen Sie zunächst überlegen, wie oder mit wem Sie ins Web gehen. Entscheidend für die Organisationsstrategie werden wohl die Kosten und der Zweck Ihrer Präsenz sein. In der Regel werden Sie sich für eine der zwei gebräuchlichsten Strategien zur Webserverimplementierung entscheiden: * Hosting-Service – Der Webserver wird remote über den Internet Service Provider (ISP) unterstützt. * Schlüsselfertige Lösungen – Dies ist eine komplette Soft- und Harwarelösung, die lokal am physischen Standort verwaltet wird. ### 23.7.3 Hosting-Services Die meisten Anwender dürften sich für einen Hosting-Service entscheiden. Dabei geht der Kunde über einen Web Service Provider (WSP) ins Netz. Verwechseln Sie aber den WSP nicht mit dem Internet Service Provider (ISP). Mit dem ISP wählen Sie sich ins Internet ein, mit einem WSP richten Sie Ihre Internetpräsenz ein. Allerdings bieten heute viele ISPs auch schon Hosting-Services an. Sie bekommen z. B. bei groÃen ISPs wie AOL oder T-Online auch schon 10 MB Platz für eine Internetpräsenz. Dabei müssen Sie aber auf Extras und eine eigene Domain wie www.mein_wunschname.de verzichten. Bei den vielen Hosting-Services, die es mittlerweile im Netz gibt, ist es schon schwer, sich einen Ãberblick zu verschaffen. Da Sie wahrscheinlich die Beispiele im Buch erst einmal am lokalen Rechner testen, müssen Sie sich jetzt noch keine Gedanken darüber machen, wo Sie Ihre Webseite hosten. Aber Sie sollten, falls Sie eigene Skripte auf den Webserver hochladen wollen, darauf achten, dass bei den Leistungen Dinge dabei sind wie: eigene CGIs ausführen, PHP ausführen, Zugriff auf eine MySQL-Datenbank haben. Gute Hosting-Services kosten so in etwa 10 bis 50 Euro monatlich. Geben Sie einfach in einer Suchmaschine den Begriff »Hosting-Service« ein, und Sie bekommen unzählige Ergebnisse zurück. Die Vorteile solcher Hosting-Services sind ganz klar der günstige Preis und die Tatsache, dass Sie keinerlei Verwaltungsaufgaben und Aufwand haben und somit über keinerlei technische Erfahrung mit Webservern verfügen müssen. Ebenso ist ein enormer Vorteil, dass die meisten Hosting-Services eine Bereitschaft rund um die Uhr, an sieben Tagen in der Woche bieten. ### 23.7.4 Schlüsselfertige Lösung Bei einer schlüsselfertigen Lösung handelt es sich um eine vollständige in sich geschlossene Soft- und Hardwarelösung. Der Vorteil gegenüber dem Hosting-Service liegt darin, dass Sie bei einem technischen Problem nicht vom WSP abhängig sind. Es wird dabei praktisch nur noch ein Server am Netzwerk und am Stromnetz angeschlossen, und Sie sind im Web. Dabei ist aber schon ein gewisses Maà an Know-how notwendig. Solche Server-Applikationen sind vorwiegend für kleinere bis mittlere Organisationen gedacht. Die Konfiguration des Webservers wird meistens über den Client, den Webbrowser, vorgenommen, der mit einer einfach zu bedienenden Oberfläche ausgestattet ist. Oft wird bei der Software Linux als Betriebssystem und Apache als Webserver verwendet, da bei beiden kaum lizenzrechtliche Bestimmungen beachtet werden müssen. ### 23.7.5 Weitere Möglichkeiten Theoretisch haben Sie aber auch die Möglichkeit, einen Server von zu Hause aus zu betreiben. Dabei installieren Sie einen Webserver auf Ihrem PC. Danach wählen Sie sich ins Internet ein und bekommen meist eine dynamische IP-Adresse. Unter dieser IP-Adresse können jetzt die Surfer Ihre Webseite ansteuern und das Internetangebot auch nutzen. Der Vorteil: Diese Lösung kostet keinen Cent. Aber bei einer ständig wechselnden IP-Adresse Ihrer Webseite dürfte wohl kaum ein Websurfer Ihre Seite finden. Dieses Problem können Sie theoretisch mit kostenlosen Diensten wie www.dyndns.org beheben. Damit können Sie sich auch ohne DENIC eine Webadresse einrichten lassen – wobei logischerweise die Bandbreite der Besucher, die sich gleichzeitig auf Ihrer Seite tummeln können, beschränkt ist. Aber probieren macht gewöhnlich SpaÃ, und so lernen Sie auch noch einiges dabei. Eine weitere Möglichkeit stellt das Intranet dar, ob nun privat oder geschäftlich. Wenn Sie das Glück haben, in einer Firma ein gröÃeres Intranet zu betreiben, können Sie schalten und walten, wie Sie wollen. DENIC | | --- | | ### 23.7.6 Apache 1995 schlossen sich mehrere Entwickler zusammen, um den damals dominierenden, aber sehr fehlerhaften Webserver NCSA weiterzuentwickeln. Was dabei herauskam, wurde wegen der vielen Fehlerbehebungen (Patches) »a patchy Server« oder einfach »Apache« genannt. # Warum Apache? Warum in diesem Kapitel der Apache-Webserver verwendet wird, lässt sich recht einfach erklären. Der Apache ist für viele Systeme erhältlich, und ist für ein System einmal keine Binary-Version vorhanden, können Sie den Quellcode, der in C geschrieben wurde und frei vorliegt, auf dem System anpassen und übersetzen (kompilieren) lassen. Natürlich können Sie sich auch auf gängigen Systemen Ihre eigene Version des Apache zusammenbasteln. Der zweite Grund: Apache liegt in freier Form vor. In freier Form heiÃt, der Quellcode liegt offen, somit werden Sicherheitslücken schneller gefunden als bei Webservern, bei denen Sie sich auf den Hersteller verlassen müssen. Und der dritte Grund ist auch der ausschlaggebende: Der Apache ist der am meisten verwendete Webserver im Internet, wie folgende Auswertung von der Webseite http://www.netcraft.com/survey zeigt: Abbildung 23.3 Verwendete Webserver im Internet And last, but not least: Apache ist kostenlos. Der Webserver finanziert sich durch die Apache Software Foundation, der groÃe Firmen wie IBM gewisse Beträge spenden und so die Weiterentwicklung des Webservers unterstützen. Firmen und Entwickler, die dieses Projekt unterstützen wollen, sind immer willkommen. Mehr dazu finden Sie unter http://www.apache.org. # Apache installieren und testen Damit Sie in den folgenden Abschnitten die Beispiele auf Ihrem lokalen Rechner testen können, müssen Sie zunächst Apache auf dem System installieren, sofern dies noch nicht geschehen ist. Es empfiehlt sich im Allgemeinen, die CGI-Anwendungen zuerst auf einem lokalen Rechner zu testen, ehe Sie sie im Web der Ãffentlichkeit vorstellen. Den Vorgang der Installation zeige ich anhand der Binary-Version des Apache, da dies wohl die Installationsart ist, die am häufigsten verwendet wird. Für eine Beschreibung, wie Sie mit dem Sourcecode einen persönlichen Apache erstellen können, sei die Homepage http://www.apache.org empfohlen. In der Regel kann der Apache auf jeder Windows-Version ohne Probleme betrieben werden. Die Funktionalität kann hierbei für Windows 2000 (w2k), Windows Server 2003 (R2), Windows XP (SP2 und SP3) und Windows Vista garantiert werden. Nicht mehr offiziell unterstützt wird Windows 98SE, obgleich auch hier der Apache noch läuft. Für die Installation können Sie sich zwar die aktuellste Version von Apache von der offiziellen Apache-Webseite (http://www.apache.org/) herunterladen, aber ich empfehle Ihnen, sofern Sie noch nie etwas mit Webservern zu tun gehabt haben, hierfür das Komplettpaket XAMPP für Windows. Der Vorteil des Pakets ist, dass Sie sich für den Hausgebrauch keine Gedanken um die Konfigurationen machen müssen, und auÃerdem sind neben dem Apache auch gleich MySQL, PHP, phpMyAdmin, FileZilla FTP Server und der Mercury E-Mail-Server dabei. Und um das alles zu steuern, gibt es auch gleich mit dem XAMPP Control Panel eine grafische Oberfläche dazu. Die aktuellste Version können Sie sich von der Webseite http://www.apachefriends.org/ herunterladen und mithilfe des Installers installieren. Nach der Installation von XAMPP können Sie über das XAMPP Control Panel die Server starten und stoppen (siehe Abbildung 23.4). Hier können Sie auch gleich die Server als Dienst installieren bzw. deinstallieren, wenn Sie die Checkbox des entsprechenden Servers aktivieren bzw. deaktivieren. Abbildung 23.4 Das XAMPP Control Panel zum Starten und Stoppen der Server Für dieses Kapitel benötigen Sie zunächst nur den Apache als Webserver. Daher reicht es aus, wenn Sie nur diesen über den Button Start ausführen. Wenn Sie jetzt XAMPP installiert haben und den Apache-Server gestartet haben, können Sie den Webbrowser öffnen und hier die Adresse http://localhost eingeben und mit bestätigen. Jetzt sollten Sie die Ansicht aus Abbildung 23.5 erhalten. Abbildung 23.5 Der Apache-Webserver läuft – hier können Sie auÃerdem auch gleich einige Tests und Demos ausführen. # Linux Die Installation unter Linux gestaltet sich recht einfach, da der Apache-Webserver in der Regel mit der Distribution mitgeliefert wird. Das heiÃt, Sie müssen nur noch das Paket von Ihrer Linux-Distribution nachinstallieren. Abbildung 23.6 Paketauswahl bei der Ubuntu-Distribution mit der Paketverwaltung »Synaptic« Natürlich können Sie auch die neueste Version des Apache herunterladen und installieren, was allerdings für die Beispiele dieses Buchs nicht nötig ist. Diese wurden unter anderem auch mit dem Apache der Version 1.3 und 2.2 getestet. Als Nächstes müssen Sie gegebenenfalls den Webserver in einer Konsole mit folgendem Befehl starten: > $ sudo /etc/init.d/apache2 start [sudo] password for user: ****** * Starting web server apache2 [ OK ] $ Sollte dies nicht funktionieren, können Sie mit Administrator-Rechten das apache2ctl-Skript verwenden, um Apache zu starten. Dann sollte es mit folgendem Aufruf klappen: > $ sudo apache2ctl start [sudo] password for user: ****** * Starting web server apache2 [ OK ] $ Das Steuerskript apache2ctl ist die empfohlene Methode, um den Apache zu steuern. Mit welchem Parameter dabei Apache gesteuert wird, können Sie Tabelle 23.1 entnehmen. Wenn Sie Apache installiert und gestartet haben, können Sie den Webbrowser öffnen und hier die Adresse http://localhost eingeben und mit bestätigen. Die Startseite des Apache kann von Distribution zu Distribution unterschiedlich aussehen (siehe Abbildung 23.7). Abbildung 23.7 Schnörkellos, aber klar: die Antwortseite bei Ubuntu # htdocs-Verzeichnis Die BegrüÃungsseite in den verschiedensten Sprachen finden Sie im htdocs-Verzeichnis. Bei den vielen verschiedenen Distributionen und Betriebssystemen ist es gar nicht so einfach, das Verzeichnis zu finden. Gerade bei Linux/Unix-Systemen, wo vieles selbst kompiliert wird, hängt das Verzeichnis (auch als Direktive DocumentRoot bekannt) vom vordefinierten Layout ab. In Tabelle 23.2 finden Sie einige dieser vordefinierten Layouts (ohne Garantie auf Vollständigkeit). System/Distribution | Verzeichnis | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Unter Windows kann der Pfad ebenfalls recht unterschiedlich sein. Bei XAMPP beispielsweise finden Sie das htdocs-Verzeichnis in c:\xampp\htdocs bzw. c:\Programme\xampp\htdocs. Wenn Sie jetzt eine HTML-Seite auf dem lokalen Webserver speichern und mit einem Webbrowser betrachten wollen, müssen Sie dazu nur die Webseiten, Bilder und, falls benötigt, weitere Unterordner im htdocs-Verzeichnis des Apache-Servers ablegen. Erstellen Sie z. B. eine HTML-Seite mit dem Namen testseite.html und speichern diese im htdocs-Verzeichnis, dann können Sie diese Seite mit einem Browser über die URL http://localhost/testseite.html aufrufen und anzeigen. # Apache für CGI-Anwendungen konfigurieren Wenn Sie irgendetwas beim Apache konfigurieren müssen, ist die Konfigurationsdatei httpd.conf Ihre erste Anlaufstelle. Bei Linux/Unix benötigen Sie zum Editieren dieser Datei natürlich Administratorrechte. Bei vielen Distributionen wird der Dateiname httpd.conf gar nicht mehr verwendet, sondern die Datei heiÃt apache2.conf. Auch der Pfad zur Konfigurationsdatei des Apache lässt sich nicht auf Anhieb genau nennen. So finden Sie beispielsweise bei Windows mit XAMPP die Konfigurationsdatei im xampp-Verzeichnis unter C:\Pfad_zu_XAMPP\apache\conf und bei Linux (hier beispielsweise bei Ubuntu) im Verzeichnis /etc/apache2. Allerdings kann dieser Pfad auch woanders liegen. Enorm von Bedeutung ist hier die Direktive ScriptAlias, mit der Sie den Namen für das CGI-Verzeichnis (traditionell lautet der Name cgi-bin) und den Pfad dahin festlegen. StandardmäÃig ist dieses Verzeichnis ein anderes als das DocumentRoot-Verzeichnis (das htdocs-Verzeichnis). Gewöhnlich wird dieses Verzeichnis mit dem Modul mod_alias (bzw. alias_module) und der Direktive ScriptAlias bereitgestellt. Beispielsweise sieht diese Zeile bei XAMPP unter Microsoft Windows wie folgt aus: > ScriptAlias /cgi-bin/ "C:/xampp/cgi-bin/" Und unter Linux so: > ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" Hier wurde der traditionelle Name cgi-bin verwendet, gefolgt vom Verzeichnis, wo sich dieses befindet und wo Sie (hier bspw. /var/www/cgi-bin/) Ihre CGI-Anwendungen ausführen können. Die Werte können Sie selbstverständlich an Ihre Bedürfnisse anpassen. Ein Zugriff auf http://localhost/cgi-bin/test.cgi entspricht dann praktisch unter Windows einem Zugriff auf C:\xampp\cgi-bin\test.cgi bzw. bei Linux einem Zugriff auf /var/www/cgi-bin/test.cgi. Hier sehen Sie eine erste CGI-Anwendung, die Sie in Ihrem Webbrowser zum Testen starten können: > /* time.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> /* die Kopfzeile eines Standard-HTML-Dokuments; * Titel: String, der als Titel erscheinen soll */ void print_html_header(char *titel) { printf("<html><head>\n"); printf("<title>%s</title>\n",titel); printf("</head><body>\n"); } /* das Ende eines HTML-Dokuments */ void print_html_end(void) { printf("</body></html>\n"); } /* damit überhaupt ein HTML-Dokument ausgegeben wird */ void print_header(void) { printf("Content-Type: text/html\n\n"); } void print_time(void) { time_t zeit; time(&zeit); printf("Aktuelle Systemzeit: "); printf("%s\n",ctime(&zeit)); } int main(void) { print_header(); print_html_header("Hallo Welt in CGI mit Zeit\n"); print_time(); print_html_end(); return EXIT_SUCCESS; } Die Funktion print_html_header() enthält die Kopfdaten eines HTML-Dokuments. Der String, den Sie der Funktion übergeben, wird als Titel der HTML-Seite verwendet. Und die Funktion print_html_end() enthält das Ende eines HTML-Dokuments. Zur Zeile print_header() erfahren Sie später mehr. Mit der Funktion print_time() wird die aktuelle Systemzeit ausgegeben. Da sich diese zwischen den Funktionen print_html_header() und print_html_end() befindet, also im Body-Teil des HTML-Dokuments, stellt die Ausgabe praktisch den Inhalt der HTML-Seite dar. Jetzt soll dieses CGI-Programm mit dem Webbrowser Ihrer Wahl aufgerufen werden. Ein CGI-Programm erstellen und starten Sie in den folgenden Schritten (der Programmname sei time.c): 1. | Ãbersetzen Sie den Quellcode wie gewohnt. | | --- | --- | 2. | Verändern Sie die Extension der ausführbaren Datei. Bei Linux hat diese binäre Datei keine Extension, und Sie sollten eine hinzufügen. Aus time wird hierbei time.cgi. Unter Windows läuft dies ähnlich ab, aus time.exe machen Sie time.cgi. Es kann dabei vorkommen, dass Ihr System Sie warnt, das Programm sei danach nicht mehr ausführbar. Das können Sie ignorieren. | | --- | --- | 3. | Kopieren Sie die übersetzte Datei in das cgi-bin-Verzeichnis des Webservers. Unter Linux/Unix werden Sie hierbei Administratorrechte benötigen, um auf das Verzeichnis schreibend zugreifen zu können. | | --- | --- | 4. | CGIZugriffsrechteUnter Linux müssen Sie noch die Zugriffsrechte der Datei time.cgi ändern. Ein einfaches chmod a+x time.cgi sollte dabei reichen (voraussichtlich werden Superuser-Rechte dazu benötigt). | | --- | --- | 5. | Jetzt können Sie einen Webbrowser Ihrer Wahl starten und, falls es nicht schon geschehen ist, den Apache-Webserver ebenfalls. | | --- | --- | 6. | Jetzt wird es Zeit, die CGI-Anwendung zu starten. Geben Sie in der Adressleiste Ihres Browser folgende URL ein: | | --- | --- | Wenn alles richtig verlaufen ist, müssten Sie folgende Ausgabe auf Ihrem Bildschirm erhalten: Abbildung 23.8 Ausgabe der Systemzeit mit Mozilla (SUSE Linux) # Troubleshooting Sollten Sie die CGI-Anwendung nicht zum Laufen bekommen, sehen Sie in der folgenden Checkliste nach, welche möglichen Ursachen dies haben könnte: * Haben Sie die Zugriffsrechte auf die CGI-Anwendung richtig gesetzt? Wenn Sie keine Rechte auf die Datei haben, sollten Sie dies nachholen. * Liegt ein Fehler im Programm vor? Meistens bekommen Sie dabei von Ihrem Webbrowser einen Fehler mit der Nummer 500 zurück. * Führen Sie das Programm in der Kommandozeile aus, und achten Sie auf die Ausgabe. * Haben Sie die richtige URL im Browser eingegeben? * Testen Sie nochmals, ob der Webserver richtig oder überhaupt läuft (http://localhost/). * Ein Blick ins Apache-Log kann auch nicht schaden. In der Regel ist dies in /var/log/apache/ zu finden. Interessant sind hier die Dateien error.log und access.log. Gerade beim Testen von neuen CGIs sollten Sie durch Eingabe in einer Konsole tail -f /var/log/apache/error.log mitlaufen lassen. Alle Fehlermeldungen, die dann über stderr ausgegeben werden, tauchen im Log auf. Bevor Sie jetzt weitere CGI-Anwendungen erstellen, benötigen Sie noch ein wenig Grundwissen zum HTTP-Protokoll. # 23.8 Das HTTP-Protokoll Date: 2014-03-01 Categories: Tags: ## 23.8 Das HTTP-Protokoll Das Hypertext Transfer Protocol (kurz HTTP) ist das Protokoll, mit dem sich der Webbrowser und der Webserver über das Internet miteinander unterhalten. Und da CGI auf dem HTTP-Protokoll aufbaut, ist es recht sinnvoll, sich auch ein wenig damit auszukennen. Natürlich ist es nicht meine Absicht, Ihnen alles über das Thema mitzuteilen, sondern nur das Wichtigste. Sollten Sie mehr Informationen benötigen, kann ich Ihnen die Webseite www.w3.org/Protocols/ empfehlen. ### 23.8.1 Web-Protokolle Der Sinn dieses Abschnitts ist es, zu erklären, wo das HTTP-Protokoll seinen Platz in der Netzwerktechnik hat. Es gibt natürlich weitaus mehr Protokolle für das Web als nur HTTP. Beispiele wären das File-Transfer-Protokoll (besser bekannt als FTP), das TELNET-Protokoll, das Simple-Mail-Transfer-Protokoll (SMTP) und noch eine Menge mehr. Für Sie als CGI-Programmierer ist das HTTP-Protokoll am meisten von Interesse. ### 23.8.2 Wozu dienen Protokolle? Im Prinzip können Sie die Protokolle der Netzwerktechnik mit Sprachen vergleichen. In aller Welt sprechen die Menschen gut tausend verschiedene Sprachen. Wenn Sie sich mit jedem Menschen auf der Welt unterhalten wollten, müssten Sie alle diese Sprachen beherrschen – ein schwieriges Unterfangen. Würde dasselbe auf Computer angewendet, lieÃe sich wohl kaum noch eine Webseite darstellen. Sie würden dann wahrscheinlich eine Fehlermeldung erhalten wie: Diese Webseite kann nicht angezeigt werden, da Ihr System das Protokoll nicht versteht. ### 23.8.3 Was ist ein Protokoll? Protokolle sind eine Mischung aus Kommunikationsregeln und Nachrichtenformaten, deren Regeln vernetzte Computer befolgen müssen, wenn Sie Daten miteinander austauschen wollen. Werden z. B. Daten von Computer Ernie zum Computer Bert versendet, so werden diese zunächst in eine Nachricht verpackt. Diese Nachricht wird in einer bestimmten Kommunikationsregel des Protokolls definiert. In der Kommunikationsregel wird z. B. beschrieben, wie die Nachricht beim Zielrechner Bert behandelt werden soll, wenn ein Fehler bei der Ãbertragung auftritt. Zur Ãbertragung von Daten wird das IP-Protokoll (Internet Protocol) verwendet. Die Sprache der Computer ist nicht ganz so komplex wie die des Menschen. Der Computer verständigt sich mit anderen Gleichgesinnten durch die Binärzahlen 0 und 1. Trotz dieser universellen Sprache sind nicht alle Computer vom gleichen Typ. Angefangen bei unterschiedlicher Hardware bis hin zu einem anderen Betriebssystem kann es dabei ziemliche Verständigungsprobleme geben. Und Protokolle sind sozusagen die Dolmetscher, die die Probleme der Kommunikation lösen. Damit ist es erst möglich, dass sich unterschiedliche Computertypen mit unterschiedlichen Betriebssystemen verständigen können. ### 23.8.4 Normen für die Netzwerktechnik Damit jetzt die vernetzten Computer mit einheitlichen Protokollen miteinander kommunizieren können, musste zunächst eine einheitliche Netzwerktechnik entwickelt werden. Eine Normung war auch allmählich notwendig, denn durch die fortschreitende Entwicklung von Netzwerkkomponenten kamen im Laufe der Zeit immer mehr herstellerspezifische Netzwerke und Protokolle zustande. Dass dabei mit zunehmender Vernetzung immer mehr Probleme auftraten, liegt auf der Hand. 1978 hat sich dann ein Gremium mit dem Namen ISO (International Organization for Standardization) zusammengefunden, mit dem Ziel, eine Schnittstelle zu standardisieren, die für die Vernetzung von PCs in Betracht kommen könnte. Es dauerte danach weitere sechs Jahre, bis das ISO-Komitee einen Standard bekanntgab. Der Standard wurde Open System Interconnection (kurz OSI) genannt. Mit OSI wurde festgelegt, wie die Kommunikation der unterschiedlichen Rechner mit diversen Protokollen stattzufinden hat. ### 23.8.5 Das OSI-Schichtenmodell Mit Einführung des OSI-Modells wurden endlich einheitliche Produkte für den Netzwerkeinsatz entwickelt, da die Hersteller gezwungen waren, sich an diesen Vorgaben zu orientieren. Es muss aber hinzugefügt werden, dass dies allein noch lange keine Realisierung aller Standards bedeutet. Beim OSI-Referenzmodell handelt es sich um ein geprüftes und bewährtes Modell für die Hard- und Softwareentwicklung. Ob und wie die Hersteller dieses Modell anwenden, bleibt immer noch deren Angelegenheit. Das genormte OSI-Schichtenmodell wurde auf sieben Schichten verteilt. Jede Schicht hat dabei ihre eigene Aufgabe. Abbildung 23.9 gibt einen kurzen Ãberblick über diese sieben Schichten und die Protokolle, die die einzelnen Schichten nutzen können. Abbildung 23.9 Das OSI-Schichtenmodell und die Protokolle Nicht abgebildet sind hier die UDP-Protokolle. Das HTTP-Protokoll (in der Abbildung grau eingefärbt), das Sie zur CGI-Programmierung verwenden, ist über dem TCP-Protokoll angesiedelt. Der gesamte Webverkehr verläuft über das TCP/IP-Protokoll. ### 23.8.6 Die Elemente einer URL Häufig begegnen Sie einer URL (Uniform Resource Locator), deren Bedeutung einem zunächst fremd erscheint. Betrachten Sie folgende URL: Diese URL soll jetzt in ihre Einzelteile zerlegt werden. # »http« (Schema) http ist das verwendete Protokoll, über das der Webbrowser mit dem Webserver kommuniziert. Es gibt natürlich noch mehr Protokolle auÃer dem HTTP. Mehr dazu erfahren Sie gleich bei den Ports. Danach folgt der Rechnername. # »www.pronix.de« (Rechnername) Bei www.pronix.de handelt es sich um den Namen des Rechners, auf dem sich die Webseite oder das Dokument befindet. Dies kann aber auch eine IP-Adresse (beispielsweise http://127.0.0.1) und muss nicht immer ein Domainname (http://www.pronix.de) sein. # »80« (Portnummer) Der Webserver nimmt hier über Port 80 einen Auftrag entgegen. Dass dieser Port bei der URL nicht angegeben werden muss, liegt daran, dass Port 80 der voreingestellte Port des HTTP-Protokolls ist. Die Daten müssen aber nicht immer über Port 80 übertragen werden. Sie können genauso gut einen Server konfigurieren, mit dem Sie Daten über den Port 85 empfangen können. Folgende Ports und ihre Protokolle sind in der Regel voreingestellt: Protokoll | Port | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | # »/cgi/name.cgi« (Pfadangabe) Damit wird der Ort des gespeicherten Dokuments auf dem Webserver bezeichnet. # »?vorname=Clint&nachname=East« (Query-String) Der Query-String kann aus mehreren Paaren von Namen und den dazugehörenden Werten bestehen. Die einzelnen Paare werden mit dem Zeichen & voneinander getrennt. Die Variable und der Wert werden mit einem = getrennt. In diesem Beispiel haben Sie folgende zwei Paare: > Variable des ersten Paars: vorname; Wert des ersten Paars: Clint Variable des zweiten Paars: nachname;Wert des zweiten Paars: East Der Query-String wird noch ausführlicher behandelt. ### 23.8.7 Client-Anfrage – HTTP-Request (Browser-Request) Das Erste bei einer HTTP-Verbindung ist immer die Anfrage (HTTP-Request) des Webbrowsers an den Webserver. Wenn Sie beispielsweise in Ihrem Browser die URL eingeben und drücken, schickt der Browser eine Anfrage an den Webserver, die aus zwei Teilen besteht: zum einen aus der Anforderungszeile und zum anderen aus den Header-Feldern. Das sieht dann so aus: > GET /index.html HTTP/1.1 Host: www.pronix.de Accept: image/gif, image/jpeg, image/pjpeg, */* Accept-Language: de Connection: Keep-Alive User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Referer: ... ... Die erste Zeile ist die sogenannte Request-Zeile: > GET /index.html HTTP/1.1 GET ist dabei die Request-Methode, mit der eine Ressource vom Server angefordert wird, ohne dass dabei irgendwelche Daten auf dem Server verändert werden. GET ist die Standard-Methode, wenn ein Browser per HTTP ein Dokument anfordert. In diesem Beispiel wird die Datei index.html angefordert. Das Protokoll, durch das der Webbrowser und der Webserver sich unterhalten sollen, ist hier HTTP mit der Versionsnummer 1.1. Eine andere häufig verwendete Request-Methode ist POST. Im Wesentlichen unterscheiden sich diese beiden Methoden zur Datenübermittlung in der Art, wie die Daten an den Webserver übergeben werden. Um Ihnen den Unterschied zwischen den beiden Request-Methoden GET und POST etwas deutlicher zu machen, folgt hier eine kurze theoretische Beschreibung. # GET Hier soll bei einem HTML-Formular einfach die Eingabe eines Textfeldes ausgewertet werden. Ich verwende hierfür folgenden HTML-Code: > <form action="http://localhost/cgi-bin/auswert.cgi" method=get> <b>Bitte geben Sie Ihren Namen ein : </b> <input value="hallo" name="Textfeld" size="20"> <input type=submit value="abschicken"> </formDadurch entsteht das folgende Textfeld mit einem Button: Abbildung 23.10 Eingabefeld mit Button Mit der Zeile > <form action="http://localhost/cgi-bin/auswert.cgi" method=getfordern Sie das CGI-Programm auswert.cgi mit der Methode GET (method=get) an. Dabei können Sie auch gleich sehen, wie Sie die Methode des HTTP-Requests bestimmen können. Beim Drücken des Buttons wird die CGI-Anwendung auf dem Server aufgerufen. Ein Blick auf die URL des Webbrowsers zeigt Folgendes: Den Query-String können Sie jetzt auf dem Webserver mit der CGI-Anwendung auswert.cgi aus der gleichnamigen Umgebungsvariablen QUERY_STRING auslesen. In dieser Variablen befindet sich jetzt folgender String: > QUERY_STRING= Textfeld=hallo # POST Wollen Sie das Gleiche mit der POST-Methode machen, müssen Sie nur Folgendes im HTML-Code umändern: > <form action="http://localhost/cgi-bin/auswert.cgi" method=postJetzt befindet sich in der URL, beim Klicken des Buttons, kein Query-String mehr. In diesem Beispiel müssen Sie die Umgebungsvariable CONTENT_LENGTH nach der Anzahl der Bytes abfragen, die diese Nachricht enthält. AnschlieÃend können Sie CONTENT_LENGTH Bytes von der Standardeingabe (stdin) einlesen – zum Beispiel mit fgets(): > fgets(puffer, CONTENT_LENGTH, stdin); Danach befindet sich die komplette Eingabe (Textfeld=IhrName) vom HTML-Formular im String puffer. Sowohl bei der Methode GET als auch bei der POST-Methode liegen die Daten kodiert vor und müssen noch dekodiert werden. Wie das geht, erfahren Sie in Kürze. # Weitere Methoden Es gibt noch einige weitere Methoden, auf die ich hier aber nicht eingehe. Diese Methoden werden in der Praxis kaum eingesetzt. Hier nur ein schneller Ãberblick zu den weiteren möglichen Anforderungen, die Sie an den Webserver stellen könnten: * HEAD – holt nur die HTTP-Header und keinen Inhalt vom Webserver. * PUT – erzeugt eine Ressource auf dem Server. * DELETE – löscht eine Ressource auf dem Server. * OPTIONS – dient zur Abfrage der möglichen Request-Methoden des Servers. # Request Header AuÃer der Request-Zeile schickt der Browser dem Webserver noch einige Informationen, den sogenannten Request-Header, mit. Diese Informationen bestehen aus dem Feldnamen, der mit einem Doppelpunkt von seinem Wert getrennt wird. Dazu nochmals zur Erinnerung das Beispiel eines HTTP-Request, das Sie weiter oben schon gesehen haben: ``` GET /index.html HTTP/1.1 Host: www.pronix.de Accept: image/gif, image/jpeg, image/pjpeg, */* Accept-Language: de Connection: Keep-Alive User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Referer: ... ``` In diesem Beispiel ist das Fettgedruckte der Request-Header. In Tabelle 23.4 finden Sie einen Ãberblick zu einigen HTTP-Request-Headern. Diese Informationen schicken Sie praktisch immer mit, wenn Sie mit einem Webbrowser unterwegs sind und eine neue Webseite vom Webserver anfordern. Request-Header | Bedeutung | | --- | --- | | | | | | | | | | | Request-Header Bedeutung Host Der Host ist der Zielrechner, auf dem sich das angeforderte Dokument befindet. Content-Length Damit der Server weiÃ, wie viele Daten er aus dem Nachrichten-Body des HTTP-Requests lesen soll, wird dieser Header verwendet. Natürlich gilt dies nur für den POST-Request (siehe POST). Bei einer Anforderung mit der Methode GET wird dieses Feld nicht mit angegeben. Content-Type Besitzt ein Request einen Nachrichten-Body, muss der Content-Type-Header mitgeschickt werden. Damit wird der Medientyp des Nachrichten-Bodys angegeben. User-Agent Darin befinden sich Angaben darüber, mit welchem Webbrowser und Betriebssystem die Anfrage vorgenommen wurde – wobei diese Angaben nicht immer stimmen müssen. Viele Programme und auch Webbrowser bieten eine Option an, diesen Header zu manipulieren. Referer Darin befindet sich in der Regel die URL, die der Anwender zuletzt besucht hat. Wenn der User aber eine URL direkt in den Webbrowser eingibt oder ein Bookmark verwendet, befindet sich nichts in diesem Header. Accept Es gibt mehrere Accept-Header. Darin schickt der Browser dem Server Daten, welche Arten von Response (Antworten vom Server) er verstehen kann. Zum Beispiel:Accept: Liste der Medientypen, die der Browser (Client) akzeptiert. Accept-Charset: Liste der Zeichensätze, die der Browser akzeptiert. Accept-Language: Sprachen, die der Browser akzeptiert. Cookies Damit teilt der Browser dem Server mit, ob er Cookies akzeptiert. Deaktivieren Sie zum Beispiel in Ihrem Browser die Cookies, so wird dieser Header nicht mitgeschickt. Der Server kann, falls Cookies akzeptiert werden, ein Cookie setzen. ### 23.8.8 Serverantwort (Server-Response) Nachdem Sie einen HTTP-Request des Webbrowsers ausführlich durchgearbeitet haben, wird Ihnen der Webserver auch irgendwann mit einer HTTP-Response antworten. Die Antwort besteht aus einer Statuszeile, ebenfalls aus einigen Header-Feldern und häufig auch aus einem Nachrichten-Body. Hier sehen Sie ein Antwort-Beispiel des Webservers: > HTTP/1.1 200 OK Date: Wed, 30 Oct 2002 01:21:22 GMT Server: Apache/1.3.14 Last Modified: Tue, 29 Oct 2002 22:21:19 GMT Content-Length: 2232 Content-Type: text/html <html> ... </html# Der Statuscode In der ersten Zeile, der Statuszeile, wird auÃer dem Protokoll mit der Versionsnummer ein dreistelliger Statuscode angegeben. > HTTP/1.1 200 OK Anhand dieses Statuscodes bekommt der Webbrowser die Antwort auf seine Anforderung. In diesem Beispiel wird der Statuscode 200 zurückgegeben, was einem erfolgreichen Request vorangeht. Recht häufig dürfte Ihnen der Statuscode 404 im Internet begegnet sein. Dieser wird zurückgegeben, wenn das angeforderte Dokument nicht gefunden wurde. Hierzu folgt ein Ãberblick über die möglichen Statuscodes. Tabelle 23.5 listet die fünf Gruppen von Codes auf, die anhand der ersten Ziffer unterschieden werden. Statusbereich | Bedeutung | | --- | --- | | | | | | | | | | | Tabelle 23.6 zeigt die in der Praxis etwas häufiger auftretenden Statuscodes und ihre Bedeutungen: Statuscode | Bedeutung | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | # Server-Header Es folgt eine kurze Beschreibung der gängigsten HTTP-Server-Header, die der Webserver dem Webbrowser sendet. Server-Header | Bedeutung | | --- | --- | | | | | | | | | | | | | | | ### 23.8.9 Zusammenfassung Jetzt haben Sie mit dem HTTP-Protokoll das schwierigste und wahrscheinlich auch langweiligste Kapitel hinter sich. Im Laufe der nächsten Seiten wird Ihnen einiges, was Ihnen vielleicht noch nicht so klar ist, in einem anderen Licht erscheinen. Speziell in den nächsten Abschnitten werden Sie sehen, wie Sie mit CGI-Anwendungen und dem HTTP-Webserver zusammenarbeiten können, um dynamische Webseiten zu erstellen. # 23.9 Das Common Gateway Interface (CGI) ## 23.9 Das Common Gateway Interface (CGI) Damit Sie CGI-Anwendungen auf einem Server ausführen können, muss dafür eine bestimmte Umgebung erzeugt werden. CGI erzeugt diese Umgebung. In diesem Abschnitt geht es darum, welche Umgebung Ihnen CGI zur Verfügung stellt und wie Sie damit arbeiten können. ### 23.9.1 Filehandles Den Standard-Filehandles stdin und stdout fällt bei CGI-Anwendungen eine besondere Rolle zu: * stdin – Erhält der Webserver eine Anfrage (HTTP-Request) mit der POST-Methode vom Webbrowser, eine CGI-Anwendung zu starten, wird der Nachrichten-Body über stdin an die CGI-Anwendung weitergeleitet. Ãber die Standardeingabe können Sie nun Content-Length-Bytes einlesen. Diese eingelesenen Daten liegen allerdings noch in kodierter Form vor und müssen erst noch dekodiert werden. * stdout – Auf stdout geben CGI-Anwendungen ihre Daten aus. Die Ausgabe beim Apache-Webserver ist dabei ungepuffert. Einfacher geht es eigentlich kaum. Daten vom Webbrowser für die CGI-Anwendung werden einfach über die Standardeingabe (stdin) eingelesen, und Daten für den Webbrowser (z. B. die Darstellung einer Webseite) werden über die Standardausgabe (stdout) ausgegeben. Und hier greifen Sie ein. Sie sind mit einer dazwischenliegenden CGI-Anwendung für den Datenfluss verantwortlich. Was die Standardfehlerausgabe (stderr) bei CGI-Anwendungen macht, ist nicht festgelegt und hängt somit von den einzelnen Webservern ab. Zumindest beim Apache werden Ausgaben in das in der httpd.conf angegebene error.log geleitet. ### 23.9.2 CGI-Umgebungsvariablen In den sogenannten Umgebungsvariablen befinden sich Informationen zum Webserver und zum Client (Browser). Die CGI-Umgebungsvariablen werden aus drei verschiedenen Quellen erzeugt: * dem HTTP-Anfrage-Paket * dem Webserver * dem HTTP-Anfrage-Header des Webbrowsers Einige der Umgebungsvariablen werden dabei aus einer Kombination dieser drei Quellen gesetzt. Hier folgt ein Ãberblick zu einigen Standard-Umgebungsvariablen auf dem Webserver: CGI-Umgebungsvariable | Bedeutung | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Weitere Header-Variablen, die Ihnen Apache zur Verfügung stellt, sind die vom Client (Webbrowser) bei der Anfrage gesendeten Variablen. Alle diese Header-Variablen sind gleich aufgebaut: HTTP_Name_des_Headers. Tabelle 23.9 zeigt einige dieser Variablen im Ãberblick: Header-Variablen | Bedeutung | | --- | --- | | | | | | | | | | | | | | | Um jetzt auf die Umgebungsvariablen zuzugreifen, wird die ANSI-C-Funktion getenv() verwendet: > #include <stdlib.h> char *getenv(const char *str); Ist die Umgebungsvariable str vorhanden, wird ein Zeiger auf den Inhalt dieser Umgebungsvariable zurückgegeben. Wenn die Umgebungsvariable nicht vorhanden ist, wird NULL zurückgegeben. Wollen Sie beispielsweise abfragen, von welchem Betriebssystem und welchem Webbrowser die Anfrage gestellt wurde, können Sie wie folgt vorgehen: > /* browser.c */ #include <stdio.h> #include <stdlib.h> /* die Kopfzeile eines Standard-HTML-Dokuments; * titel: String, der als Titel erscheinen soll */ void print_html_header(char *titel) { printf("<html><head>\n"); printf("<title>%s</title>\n",titel); printf("</head><body><pre>\n"); } /* das Ende eines HTML-Dokuments */ void print_html_end(void) { printf("</pre></body></html>\n"); } /* damit überhaupt ein HTML-Dokument ausgegeben wird */ void print_header(void) { printf("Content-Type: text/html\n\n"); } int main(void) { char *p; print_header(); print_html_header("Wer bin ich?"); p = getenv("HTTP_USER_AGENT"); if(p!=NULL) printf("Sie browsen mit : %s\n",p); else printf("Konnte HTTP_USER_AGENT nicht ermitteln!\n"); print_html_end(); return EXIT_SUCCESS; } Wenn Sie diese CGI-Anwendung wieder aufrufen (der Name sei browser.cgi), und zwar mit http://localhost/cgi-bin/browser.cgi, dann sollten Sie im Browser einen String vorfinden wie z. B.: > Sie browsen mit : Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8 (.NET CLR 3.5.30729) oder: > Sie browsen mit : Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5) Gecko/2008121622 Ubuntu/8.10 (intrepid) Firefox/3.0.5 Die Abfrage aller Umgebungsvariablen soll jetzt in eine Funktion gepackt werden. Das folgende Listing gibt alle vorhandenen Umgebungsvariablen auf dem Browser aus: > /* env.c */ #include <stdio.h> #include <stdlib.h> /* Listing gibt alle vorhandenen Environment-Variablen aus. */ char *env[] = { "AUTH_TYPE", "CONTENT_LENGTH", "CONTENT_TYPE", "GATEWAY_INTERFACE", "HTTP_ACCEPT", "HTTP_CONNECTION", "HTTP_HOST", "HTTP_REFERER", "HTTP_USER_AGENT", "PATH_INFO", "PATH_TRANSLATET", "QUERY_STRING", "REMOTE_ADDR", "REMOTE_HOST", "REMOTE_IDENT", "REMOTE_USER", "REQUEST_METHOD", "SCRIPT_NAME", "SERVER_NAME", "SERVER_PORT", "SERVER_PROTOCOL", "SERVER_SOFTWARE" , NULL }; /* die Kopfzeile eines Standard-HTML-Dokuments; * titel: String, der als Titel erscheinen soll */ void print_html_header(char *titel) { printf("<html><head>\n"); printf("<title>%s</title>\n",titel); printf("</head><body><pre>\n"); } /* das Ende eines HTML-Dokuments */ void print_html_end(void) { printf("</pre></body></html>\n"); } /* damit überhaupt ein HTML-Dokument ausgegeben wird */ void print_header(void) { printf("Content-Type: text/html\n\n"); } /* Inhalt der Environment-Variable ausgeben */ void environment(const char *s) { char *p; p = getenv(s); printf ("%s", s); if(p!=NULL) printf (" = %s", p); else printf(" = (<i>keine Angaben</i>)"); printf ("<BR>\n"); } int main(void) { int i; print_header(); print_html_header("CGI-Umgebungsvariablen ausgeben - 2\n"); for(i=0; env[i] != NULL; i++) environment(env[i]); print_html_end(); return EXIT_SUCCESS; } Abbildung 23.11 Ausgabe der Umgebungsvariablen Dreh- und Angelpunkt ist die Funktion environment(), die mit einem entsprechenden String als Argument aufgerufen wird. Die Strings wurden in diesem Beispiel alle in eine Stringtabelle verpackt. In environment() werden in einer Schleife alle Umgebungsvariablen abgefragt und ausgegeben. ### 23.9.3 CGI-Ausgabe Wenn Ihre CGI-Anwendung etwas ausgeben soll, müssen Sie mindestens eine Headerzeile ausgeben. Der Webserver erledigt dann den Rest, wie zum Beispiel die Ausgabe weiterer Header. Von den drei folgenden Headern muss mindestens einer angegeben werden. # Content-Type-Dokumente ausgeben Wollen Sie, dass Ihre CGI-Anwendung ein bestimmtes Dokument ausgibt, müssen Sie dem Webserver erst mitteilen, um was für ein Dokument es sich handelt. Meistens werden Sie ein HTML-Dokument ausgeben wollen. Dies wird mit folgender Angabe erledigt: > printf("Content-Type: text/html\n\n"); Die beiden Newline-Zeichen am Ende sind enorm wichtig. Damit wird dem Webserver angezeigt, dass es sich um die letzte Headerzeile handelt. Wenn der Webserver diese Leerzeile erhält, kann er dem Webbrowser seine Daten schicken. Meistens ist dies das Anzeigen einer HTML-Webseite. Natürlich lassen sich mit dem Content-Type-Header noch unzählig viele andere Dokumente neben den HTML-Dokumenten ausgeben. # »Status« – Statuscode ausgeben Damit können Sie angeben, welchen Statuscode der Webserver an den Webbrowser als Response schicken soll. Welche unterschiedlichen Statuscodes Sie verwenden können, wissen Sie bereits. Wollen Sie zum Beispiel den Statuscode 403 (Forbidden) an den Webbrowser senden, und zwar derart, dass der Surfer keinen Zugriff auf diese Seite hat, können Sie so vorgehen: > printf("Status: 403"); # »Location« – Weiterleiten an ein anderes Dokument Wollen Sie mithilfe einer CGI-Anwendung nicht ein Dokument ausgeben, sondern zu einem anderen Dokument weiterleiten, können Sie dazu den Location-Header verwenden. Dieser lässt sich beispielsweise ideal einsetzen, wenn sich die URL eines Dokuments geändert hat. Anwenden können Sie den Header so: > printf("Location: umleitungs_ziel.html\n\n"); Bitte bedenken Sie auch, dass es immer noch Surfer mit älteren Browsern gibt, die eine automatische Weiterleitung nicht unterstützen. Schreiben Sie dafür ein paar extra Zeilen HTML-Code mit einem Link zum Weiterklicken. Hierzu folgt jetzt ein Programmbeispiel, das Surfern mit bestimmten IP-Adressen (REMOTE_ADDR) den Zugang auf die Webseite verweigert. Falls aber die IP-Adresse Zugang hat, wird der Surfer zu einer entsprechenden URL weitergeleitet. > /* location.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> /* Listing fragt REMOTE_ADDR ab. Lässt sich der Wert nicht * auslesen, gibt das CGI-Programm den Statuscode 500 zurück. * Ansonsten werden die verbotenen IP-Adressen in forbidden mit * REMOTE_ADDR überprüft und entsprechende MaÃnahmen getroffen. */ /* die Liste der IP-Adressen, die keinen Zugriff auf die Seite * haben sollen */ char *forbidden[] = { "127.0.0.1", "168.123.6.1", NULL }; /* Weiterleitung zu einer URL; * url ist die URL, zu der Sie den User weiterleiten. */ void print_location(char *url) { printf("Location: %s\n\n", url); /* für den Fall, dass ein alter Browser keine * automatische Weiterleitung unterstützt */ printf("Content-Type: text/html\n\n"); printf("<html><head>\n"); printf("<title>Weiterleitung zu %s</title>\n",url); printf("</head><body><pre>\n"); printf("Weiter gehts <a href=\"%s\">hier</a>",url); printf("</pre></body></html>\n"); } /* Statuscode zurückgeben */ void print_status(char *status) { printf("Status: %s", status); } int main(void) { char *p; int i; /* IP-Adresse ermitteln */ p = getenv("REMOTE_ADDR"); if( p == NULL) { /* Fehler bei getenv-Abfrage */ print_status("500"); return EXIT_FAILURE; } for(i=0; forbidden[i] != NULL; i++) if(strcmp(p, forbidden[i]) == 0) { /* Diese IP hat keinen Zutritt */ print_status("403"); return EXIT_FAILURE; } /* Ok, der User wird auf die Willkommen-Seite weitergeleitet. * Die URL an Ihre Bedürfnisse anpassen */ print_location("http://localhost/welcome.html"); return EXIT_SUCCESS; } Zuerst überprüft die CGI-Anwendung die IP-Adresse des Surfers. Sollte es dabei schon zu Problemen kommen, wird der Fehlercode 500 zurückgegeben, ein Serverfehler also. Ansonsten wird die Stringtabelle forbidden durchlaufen und mit strcmp() und dem Rückgabewert von getenv() verglichen. Bei der IP-Adresse 127.0.0.1 handelt es sich um die Adresse des localhost. Wenn Sie die Anwendung auf Ihrem System testen wollen, handelt es sich um Ihre eigene IP-Adresse. In diesem Fall sollten Sie den Statuscode 403 (Forbidden) vom Browser zurückbekommen. Der letzte Fall leitet Sie an die URL http://localhost/welcome.html weiter, die sich im Beispiel im htdocs-Verzeichnis befindet. AuÃerdem empfehle ich Ihnen, die Daten der Stringtabelle forbidden in einer extra Datei zu speichern. Diese Datei können Sie dann beim Ausführen der CGI-Anwendung zum Lesen öffnen, auslesen und mit REMOTE_ADDR überprüfen. Eine extra Datei ist deshalb sinnvoller, weil Sie beim Hinzufügen von weiteren IP-Adressen nicht das komplette Listing neu übersetzen müssen. # 23.10 HTML-Formulare Date: 2023-10-01 Categories: Tags: ## 23.10 HTML-Formulare Mit den Umgebungsvariablen allein könnten Sie schon ein ganzes Arsenal von CGI-Anwendungen schreiben. Aber irgendwann werden Sie auch Daten eines HTML-Formulars auswerten wollen. Und darum geht es in diesem Abschnitt, nämlich um das Erstellen eines solchen Formulars. Natürlich handelt es sich dabei nur um einen groben Ãberblick. ### 23.10.1 Die Tags und ihre Bedeutung Jetzt lernen Sie einige HTML-Tags kennen, mit denen Sie sogenannte Webformulare erstellen können. # <form>-Tag Dieses Tag werden Sie bei jedem Formular verwenden. Alle anderen Formular-Tags stehen zwischen den Tags <form> und </form>: > <form> ... Formularinhalt ... </formFolgende zwei Attribute des <form>-Tags sind von besonderem Interesse: * method – Wie der Name schon sagt, legen Sie damit fest, mit welcher Request-Methode Sie die CGI-Anwendung aufrufen. Meistens dürften dies die Methoden GET oder POST sein. Wird keine Methode angegeben, wird die GET-Methode verwendet. * action – Damit geben Sie die URL der CGI-Anwendung an, mit der Sie beabsichtigen, die Formulareingaben zu bearbeiten. Somit könnte das <form>-Tag folgendermaÃen aussehen: > <form action="./cgi-bin/auswert.cgi" method="POST"> ... Formularinhalt ... </form# <input>-Tag Mit dem <input>-Tag können Sie eine Menge Formularobjekte erzeugen. Unterschieden werden diese durch das type-Attribut. Besonders wichtig für CGI-Anwendungen ist auÃerdem das Attribut name. Damit können Sie beim Auswerten eines Formulars auf den übergebenen Wert zugreifen. Wir betrachten im Folgenden die einzelnen Typen des <input>-Tags. # <input type="text"Abbildung 23.12 Einzeiliges Eingabefeld So wird es gemacht: > <input type=text name="name" size=32 maxlength=32 value="dein name"# <input type="password"Abbildung 23.13 Einzeiliges Passwortfeld <input type=password value="abcdefg" size=16, maxlength=16# <input type="radio"Abbildung 23.14 Radiobuttons So wird es gemacht: > <input type="radio" name="essen" value="Pizza" checked> Pizza<br> <input type="radio" name="essen" value="Pommes"> Pommes<br> <input type="radio" name="essen" value="Salat"> Salat<br# <input type="checkbox"Abbildung 23.15 Checkboxen So wird es gemacht: > <input type="checkbox" name="zusatz" value="10000"> Nachnahme (+6 Euro)<br> <input type="checkbox" name="zusatz" value="20000"> Express (+2 Euro)<br> <input type="checkbox" name="zusatz" value="30000"> Versichert(+2 Euro)<br# <input type="submit"> und <input type="reset"Abbildung 23.16 Schaltflächen (Buttons) So wird es gemacht: > <input type="Submit" name="sub" value="Abschicken"> <input value="Zurücksetzen" type="reset"# <texarea>-Tag Abbildung 23.17 Mehrzeiliges Textfeld So wird es gemacht: > <textarea name="textform" cols="32" rows="6">Textinhalt </textarea# <select>-Tag Mit dem <select>-Tag können zwei unterschiedliche Arten von Listen erzeugt werden – welche Art, das bestimmen Sie mit dem Attribut size. Geben Sie für dieses Attribut den Wert 1 an, erstellen Sie ein Aufklappmenü. Geben Sie diesem Attribut beispielsweise den Wert 5, so haben Sie eine Scrollliste mit fünf sichtbaren Elementen. Als Beispiel: > size=1 Abbildung 23.18 Listen (Aufklappmenü) ``` Seite bewerten: <select name="Bewertung" size="1"> <option>Note 1</option> <option>Note 2</option> <option>Note 3</option> <option>Note 4</option> <option>Note 5</option> <option>Note 6</option> </select> ``` Die zweite Möglichkeit: > size= (>1) Abbildung 23.19 Listen (Scrollbox) ``` Seite bewerten: <select name="Bewertung" size="4"> <option>Note 1</option> <option>Note 2</option> <option>Note 3</option> <option selected>Note 4</option> <option>Note 5</option> <option>Note 6</option> </select> ``` Zu diesen Tags gibt es natürlich noch eine Menge weiterer Attribute und Optionen. # 23.11 CGI-Eingabe Date: 2023-11-01 Categories: Tags: ## 23.11 CGI-Eingabe ### 23.11.1 Die Anfrage des Clients an den Server In den Abschnitten zur Client-Anfrage und zu den Formular-Tags habe ich die zwei vorwiegend in der Praxis eingesetzten Methoden zum Empfangen von Daten schon erwähnt (POST, GET). Diese Methoden werde ich jetzt anhand des folgenden HTML-Formulars genauer erläutern: > <html> <head> <title>Eine einfache Auswertung</title> </head> <body> <h1><center> <b><u>Formular</u></b></center></h1><br><br> <form action=http://localhost/cgi-bin/auswert.cgi method=get> <center><b>Bitte geben Sie Ihren Namen ein :</b><br> <input name="Textfeld" size="20"> </input> <input type=submit value="abschicken"></center> </form> </body> </htmlAbbildung 23.20 Eingabeformular Von ganz besonderem Interesse ist hier das <form>-Tag. Sobald Sie auf den Button abschicken klicken, wird mit dem Attribut action ein Prozess, nämlich die CGI-Anwendung auswert.cgi, auf dem Webserver gestartet. Darin unterscheiden sich beide Methoden nicht. Da im HTML-Beispiel hier die Methode GET (method=get) verwendet wurde, soll diese auch als Erste behandelt werden. # Arbeitsweise von GET Bei der GET-Methode hängt der Browser die Zeichenkette am Ende der URL an. Bei einer Eingabe der Zeichenkette "hallo" hat die URL folgendes Aussehen: Der Webserver ist jetzt dafür verantwortlich, diese Zeichenkette wieder zu entfernen, und übergibt diese an die Umgebungsvariable QUERY_STRING: > QUERY_STRING = Textfeld=hallo Jetzt sind Sie an der Reihe, mit dem CGI-Programm die Umgebungsvariable QUERY_STRING auszuwerten. Die GET-Möglichkeit stellt dabei die einfachste Art dar. Es herrscht hierbei immer noch der Irrglaube, dass mit der GET-Methode nur 255 bzw. 1024 Bytes verarbeitet werden können. Diese GröÃe wird aber vom Webserver vorgegeben und beträgt mindestens 255 Bytes bis zu 8192 Bytes. # Arbeitsweise von POST Wollen Sie statt der Methode GET die Methode POST verwenden, müssen Sie nur im HTML-Formular die Zeile > <form action="http://... /cgi-bin/auswert.cgi" method=getumändern in: ``` <form action="http://.. /cgi-bin/auswert.cgi" method=post > ``` Bei der POST-Methode werden die Daten nicht in einer der Umgebungsvariablen abgelegt, sondern in der Standardeingabe (stdin). Sie können somit die CGI-Anwendung so schreiben, als würde die Eingabe von der Tastatur gemacht. Die Länge des kodierten Strings befindet sich in der Umgebungsvariablen CONTENT_LENGTH. AuÃerdem wird noch die Umgebungsvariable CONTENT_TYPE verwendet, damit die CGI-Anwendung weiÃ, um was für eine Art Dokument es sich handelt. # POST- oder GET-Methode programmtechnisch auswerten Damit die CGI-Anwendung jetzt weiÃ, ob die Daten mit der Methode GET oder POST gesendet wurden, benötigen Sie eine Funktion, die die Umgebungsvariable REQUEST_METHOD auswertet und den Inhalt (String), sei es nun vom QUERY_STRING oder von der Standardeingabe, an den Aufrufer zurückgibt. > /* Funktion liest Daten in der POST- oder GET-Methode ein. * Rückgabewert: String puffer mit den Daten * bei Fehler : NULL */ char *getdata(void) { unsigned long size; char *puffer = NULL; char *request = getenv("REQUEST_METHOD"); char *cont_len; char *cgi_string; /* zuerst die Request-Methode überprüfen */ if( NULL == request ) return NULL; else if( strcmp(request, "GET") == 0 ) { /* die Methode GET -> Query String abholen */ cgi_string = getenv("QUERY_STRING"); if( NULL == cgi_string ) return NULL; else { puffer =(char *) Strdup(cgi_string); return puffer; /* Rückgabewert an den Aufrufer */ } } else if( strcmp(request, "POST") == 0 ) { /* die Methode POST -> Länge des Strings * ermitteln (CONTENT_LENGTH) */ cont_len = getenv("CONTENT_LENGTH"); if( NULL == cont_len) return NULL; else { /* String CONTENT_LENGTH in * unsigned long umwandeln */ size = (unsigned long) atoi(cont_len); if(size <= 0) return NULL; /* Keine Eingabe!?!? */ } /* jetzt lesen wir die Daten von stdin ein */ puffer = (char *) malloc(size+1); if( NULL == puffer ) return NULL; else { if( NULL == fgets(puffer, size+1, stdin) ) { free(puffer); return NULL; } else /* Rückgabewerte an den Ausrufer */ return puffer; } } else /* Weder die GET- noch die POST-Methode * wurden verwendet. */ return NULL; } /* Da die Funktion strdup() in der Headerdatei <string.h> keine * ANSI-C-Funktion ist, schreiben wir eine eigene. */ char *Strdup(const char *str) { char *p; if(NULL == str) return NULL; else { p = malloc(strlen(str)+1); if(NULL == p) return NULL; else strcpy(p, str); } return p; } Es wurde auÃerdem eine extra Funktion für Strdup() geschrieben, da die vorhandene strdup() in der Headerdatei <string.h> nicht zum ANSI-C-Standard gehört. Sie können diese eben erstellten Funktionen gern in einer CGI-Anwendung testen und ausführen. Falls Sie die CGI-Anwendung getestet und etwa folgende Eingabe in einem Webformular gemacht haben: > Jürgen "pronix" Wolf erscheint anschlieÃend im Webbrowser folgende Zeile: > Textfeld=J%FCrgen+%22pronix%22+Wolf Wir sind also noch ein wenig vom gewünschten Ergebnis entfernt. ### 23.11.2 Eingabe parsen Sie können zwar jetzt die Eingabe vom Client empfangen, aber Sie müssen den String noch lesefreundlich dekodieren. Hier folgt ein Ãberblick zu den Zeichen, die eine besondere Bedeutung haben und die Sie als Programmierer von CGI-Anwendungen berücksichtigen müssen. * & – Die einzelnen Formularelemente (sofern es mehrere sind) werden mit diesem Zeichen getrennt. * = – Mit diesem Zeichen werden die Variable/Wert-Paare voneinander getrennt. > Textfeld J%FCrgen+%22pronix%22+Wolf * + – Damit werden die Leerzeichen der eingegebenen Daten getrennt. > Textfeld J%Fcrgen %22pronix%22 Wolf * %XX – Bei einem Prozentzeichen, auf das zwei hexadezimale Ziffern folgen, handelt es sich um ASCII-Zeichen mit dem dezimalen Wert von 128 bis 255. Diese hexadezimalen Ziffern müssen in ASCII-Zeichen dekodiert werden. > Textfeld Jürgen pronix Wolf In Tabelle 23.18 finden Sie Steuerzeichen und weitere Zeichen sowie ihre hexadezimale Darstellung im Ãberblick: Zeichen | Hexadezimale Darstellung | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Jetzt wollen Sie natürlich auch wissen, wie Sie dies in der Praxis dekodieren können. Folgende Funktionen sind dazu zunächst nötig: * kodierte Zeichen (Prozentzeichen, gefolgt von zwei Hexzahlen) dekodieren * alle Leerzeichen, die mit + angegeben sind, in ein echtes Leerzeichen konvertieren Alle anderen Schritte folgen in den nächsten Funktionen. Betrachten wir zunächst die Funktionen, mit denen die hexadezimalen Zahlen in ASCII-Werte und die +-Zeichen in echte Leerzeichen konvertiert werden: > /* Wandelt einzelne Hexzeichen (%xx) in ASCII-Zeichen * und kodierte Leerzeichen (+) in echte Leerzeichen um. */ void hex2ascii(char *str) { int x, y; for(x=0,y=0; str[y] != '\0'; ++x,++y) { str[x] = str[y]; /* Ein hexadezimales Zeichen? */ if(str[x] == '%') { str[x] = convert(&str[y+1]); y += 2; } /* Ein Leerzeichen? */ else if( str[x] == '+') str[x]=' '; } /* geparsten String sauber terminieren */ str[x] = '\0'; } /* Funktion konvertiert einen String von zwei hexadezimalen * Zeichen und gibt das einzelne dafür stehende Zeichen zurück. */ char convert(char *hex) { char ascii; /* erster Hexawert */ ascii = (hex[0] >= 'A' ? ((hex[0] & 0xdf) - 'A')+10 : (hex[0] - '0')); ascii <<= 4; /* Bitverschiebung schneller als ascii*=16 */ /* zweiter Hexawert */ ascii += (hex[1] >= 'A' ? ((hex[1] & 0xdf) - 'A')+10 : (hex[1] - '0')); return ascii; } Sollten Sie die Funktionen wieder in der Praxis testen wollen, können Sie dies tun. Jetzt bekommen Sie die Eingabe des Formulars im Klartext ausgegeben: > Textfeld=Jürgen "pronix" Wolf Im nächsten Schritt benötigen Sie eine Funktion, die diese beiden Werte auseinanderhält und zwischenspeichert. In diesem Beispiel wurde nur eine Variable (Textfeld) mit dem Wert (Jürgen "pronix" Wolf) verwendet. Die nun folgende Funktion sollte in diesem Zusammenhang allgemeingültig und auch später wiederverwendbar sein. Daher kommen Sie nicht um die Programmierung einer dynamischen Liste herum. Folgende Struktur soll hierfür verwendet werden: > struct CGI_DATEN { char *variable; char *wert; struct CGI_DATEN *next; }; struct CGI_DATEN *ende = NULL; Die Daten einer einzelnen CGI-Eingabe werden anhand des '='-Zeichens getrennt (variable=wert). Somit muss dieses Zeichen auch geparst werden. Und für den Fall (so ist es meistens), dass mehrere Variablen/Werte-Paare übermittelt werden, müssen Sie auch das Zeichen '&' parsen, das die Paare voneinander trennt (variable1=wert&variable2=wert). Eine Menge Arbeit liegt damit vor Ihnen. Hier sehen Sie die komplette Funktion: > struct CGI_DATEN *erstellen(char *str) { char* s; char* res; /* Irgendwo gibt es auch eine Grenze, hier sind * MAX_PAARE erlaubt. */ char *paare[MAX_PAARE]; struct CGI_DATEN *ptr_daten = NULL; struct CGI_DATEN *ptr_anfang = NULL; int i=0, j=0; /* Zuerst werden die Variablen/Werte-Paare anhand * des Zeichens '&' getrennt, sofern es mehrere sind. */ s=str; res=strtok(s,"&"); while( res != NULL && i < MAX_PAARE) { /* Wert von res dynamisch in char **pair speichern. */ paare[i] = (char *)malloc(strlen(res)+1); if(paare[i] == NULL) return NULL; paare[i] = res; res=strtok(NULL,"&"); i++; } /* Jetzt werden die Variablen von den Werten getrennt und * an die Struktur CGI_DATEN übergeben. */ while ( i > j ) { /* Das erste Element? */ if(ptr_anfang == NULL) { ptr_anfang =(struct CGI_DATEN *) malloc(sizeof (struct CGI_DATEN *)); if( ptr_anfang == NULL ) return NULL; res = strtok( paare[j], "="); ptr_anfang->variable = malloc(strlen(res)+1); if( ptr_anfang->variable == NULL ) return NULL; ptr_anfang->variable = res; res = strtok(NULL, "\0"); ptr_anfang->wert = malloc(strlen(res)+1); if( ptr_anfang->wert == NULL ) return NULL; ptr_anfang->wert = res; /* printf("%s %s<br>", * ptr_anfang->variable, ptr_anfang->wert); */ ptr_anfang->next = malloc(sizeof (struct CGI_DATEN *)); if(ptr_anfang->next == NULL) return NULL; ptr_daten = ptr_anfang->next; j++; } else { /* die restlichen Elemente */ res = strtok( paare[j], "="); ptr_daten->variable = malloc(strlen(res)+1); if(ptr_daten->variable == NULL) return NULL; ptr_daten->variable = res; res = strtok(NULL, "\0"); ptr_daten->wert = malloc(strlen(res)+1); if(ptr_daten->wert == NULL) return NULL; ptr_daten->wert = res; /* printf("%s %s<br>", * ptr_daten->variable, ptr_daten->wert); */ ptr_daten->next = malloc(sizeof (struct CGI_DATEN *)); if( ptr_daten->next == NULL ) return NULL; ptr_daten = ptr_daten->next; j++; } } ende = ptr_daten; /* Anfangsadresse der Liste struct CGI_DATEN zurückgeben */ return ptr_anfang; } Hiermit haben Sie eine Funktion erstellt, die für alle Fälle gerüstet ist. Jetzt benötigen Sie nur noch eine Funktion, die den Speicherplatz der dynamischen Liste wieder freigibt. Diese finden Sie im folgenden Programmbeispiel. # 23.12 Ein Gästebuch ## 23.12 Ein Gästebuch Um alle Funktionen jetzt zu demonstrieren, soll ein einfaches Gästebuch erstellt werden. Ich denke, so etwas kennt jeder. Folgende Dateien benötigen Sie dafür: * das HTML-Formular, in das sich der Besucher einträgt * die CGI-Anwendung, die diesen Eintrag einliest, auswertet und bearbeitet * die HTML-Datei, mit der das Gästebuch angezeigt wird In diesem Beispiel wurde auch gleich die HTML-Datei, die die Einträge anzeigt, zur Datenspeicherung verwendet, um das Programm ein wenig kürzer zu halten. Bei einem umfangreichen Gästebuch würden sich dafür eine extra Datei oder eine Datenbank anbieten. ### 23.12.1 Das HTML-Formular (»guestbook.html«) > <html> <head> <title>Eintrag ins Gästebuch</title> </head> <body text="#000000" bgcolor="#FFFFFF" link="#FF0000" alink="#FF0000" vlink="#FF0000"> <h3>Formular zum Eintragen ins Gästebuch</h3> <pre> <form action="http://localhost/cgi-bin/auswert.cgi" method=post> <b>Name : </b> <input value="IhrName" name="Name" size="20"> <b>E-Mail : </b> <input value="Mailadresse@mail" name="E-Mail" size="20"> <b>Bewertung dieser Webseite : </b> <select name="Bewertung" size="3"> <option>Note 1</option><option>Note 2</option> <option selected>Note 3</option><option>Note 4</option> <option>Note 5</option><option>Note 6</option> </select><br> <b>Ihr Eintrag :</b> <textarea name="textform" cols="32" rows="6">Textinhalt </textarea> <b>Ihre Programmierkenntnis : </b> <input type="checkbox" name="programmieren" value="C/C++">C/C++ <input type="checkbox" name="programmieren" value="Perl">Perl <input type="checkbox" name="programmieren" value="Visual Basic"> Visual Basic <input type="reset"><input type=submit value="Abschicken"> </form> </pre> </body> </htmlDer Ort, wo Sie diese Datei speichern, ist in der Regel auf dem lokalen System nicht so wichtig. Wichtiger ist, dass die Angaben zum Aufrufen der CGI-Anwendung stimmen: > <form action="http://localhost/cgi-bin/auswert.cgi" method=postAbbildung 23.21 Das HTML-Formular ### 23.12.2 Das CGI-Programm (»auswert.cgi«) > /* auswert.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_PAARE 255 void print_location(char *); char *getdata(); char *Strdup(const char *); void hex2ascii(char *); char convert(char *); struct CGI_DATEN *erstellen(char *); void printf_error(char *); struct CGI_DATEN { char *variable; char *wert; struct CGI_DATEN *next; }; struct CGI_DATEN *ende = NULL; /* Weiterleitung zu einer URL; * url ist die URL, wohin Sie den User weiterleiten. */ void print_location(char *url) { printf("Location: %s\n", url); /* für den Fall, dass ein alter Browser keine automatische Weiterleitung unterstützt */ printf("Content-Type: text/html\n\n"); printf("<html><head>\n"); printf("<title>Weiterleitung zu %s</title>\n",url); printf("</head><body>\n"); printf("Weiter gehts <a href=\"%s\">hier</a>",url); printf("</body></html>\n"); } /* * Funktion liest Daten in der POST- oder GET-Methode ein. * Rückgabewert: String puffer mit den Daten * bei Fehler : NULL */ char *getdata(void) { unsigned long size; char *puffer = NULL; char *request = getenv("REQUEST_METHOD"); char *cont_len; char *cgi_string; /* zuerst die Request-Methode überprüfen */ if( NULL == request ) return NULL; else if( strcmp(request, "GET") == 0 ) { /* Die Methode GET -> Query-String abholen */ cgi_string = getenv("QUERY_STRING"); if( NULL == cgi_string ) return NULL; else { puffer = (char *) Strdup(cgi_string); return puffer; /* Rückgabewert an den Aufrufer */ } } else if( strcmp(request, "POST") == 0 ) { /* die Methode POST -> Länge des Strings * ermitteln (CONTENT_LENGTH) */ cont_len = getenv("CONTENT_LENGTH"); if( NULL == cont_len) return NULL; else { /* String CONTENT_LENGTH in unsigned long umwandeln */ size = (unsigned long) atoi(cont_len); if(size <= 0) return NULL; /* Keine Eingabe!?!? */ } /* jetzt lesen wir die Daten von stdin ein */ puffer =(char *) malloc(size+1); if( NULL == puffer ) return NULL; else { if( NULL == fgets(puffer, size+1, stdin) ) { free(puffer); return NULL; } else /* Rückgabewerte an den Aufrufer */ return puffer; } } /* Weder die GET-Methode noch die POST-Methode wurden verwendet. */ else return NULL; } /* Da die Funktion strdup() in der Headerdatei <string.h> keine * ANSI-C-Funktion ist, schreiben wir eine eigene. */ char *Strdup(const char *str) { char *p; if(NULL == str) return NULL; else { p = (char *)malloc(strlen(str)+1); if(NULL == p) return NULL; else strcpy(p, str); } return p; } /* Wandelt einzelne Hexzeichen (%xx) in ASCII-Zeichen * und kodierte Leerzeichen (+) in echte Leerzeichen um. */ void hex2ascii(char *str) { int x,y; for(x=0,y=0; str[y] != '\0'; ++x,++y) { str[x] = str[y]; /* Ein hexadezimales Zeichen? */ if(str[x] == '%') { str[x] = convert(&str[y+1]); y += 2; } /* Ein Leerzeichen? */ else if( str[x] == '+') str[x]=' '; } /* geparsten String sauber terminieren */ str[x] = '\0'; } /* Funktion konvertiert einen String von zwei hexadezimalen * Zeichen und gibt das einzelne dafür stehende Zeichen zurück. */ char convert(char *hex) { char ascii; /* erster Hexawert */ ascii = (hex[0] >= 'A' ? ((hex[0] & 0xdf) - 'A')+10 : (hex[0] - '0')); ascii <<= 4; /* Bitverschiebung schneller als ascii*=16 */ /* zweiter Hexawert */ ascii += (hex[1] >= 'A' ? ((hex[1] & 0xdf) - 'A')+10 : (hex[1] - '0')); return ascii; } /* Liste aus Variable/Wert-Paaren erstellen * Rückgabewert: Anfangsadresse der Liste * Bei Fehler: NULL */ struct CGI_DATEN *erstellen(char *str) { char* s; char* res; /* Irgendwo gibt es auch eine Grenze, hier sind MAX_PAARE erlaubt. */ char *paare[MAX_PAARE]; struct CGI_DATEN *ptr_daten = NULL; struct CGI_DATEN *ptr_anfang = NULL; int i=0, j=0; /* Zuerst werden die Variablen/Werte-Paare anhand des Zeichens * '&' getrennt, sofern es mehrere sind. */ s=str; res=strtok(s,"&"); while( res != NULL && i < MAX_PAARE) { /* Wert von res dynamisch in char **pair speichern */ paare[i] = (char *)malloc(strlen(res)+1); if(paare[i] == NULL) return NULL; paare[i] = res; res=strtok(NULL,"&"); i++; } /* Jetzt werden die Variablen von den Werten getrennt und * an die Struktur CGI_DATEN übergeben. */ while ( i > j ) { /* Das erste Element? */ if(ptr_anfang == NULL) { ptr_anfang =(struct CGI_DATEN *) malloc(sizeof (struct CGI_DATEN *)); if( ptr_anfang == NULL ) return NULL; res = strtok( paare[j], "="); if(res == NULL) return NULL; ptr_anfang->variable = (char *) malloc(strlen(res)+1); if( ptr_anfang->variable == NULL ) return NULL; ptr_anfang->variable = res; res = strtok(NULL, "\0"); if(res == NULL) return NULL; ptr_anfang->wert = (char *) malloc(strlen(res)+1); if( ptr_anfang->wert == NULL ) return NULL; ptr_anfang->wert = res; /* printf("%s %s<br>", * ptr_anfang->variable, ptr_anfang->wert); */ ptr_anfang->next =(struct CGI_DATEN *) malloc(sizeof (struct CGI_DATEN *)); if(ptr_anfang->next == NULL) return NULL; ptr_daten = ptr_anfang->next; j++; } else { /* die restlichen Elemente */ res = strtok( paare[j], "="); if(res == NULL) return NULL; ptr_daten->variable =(char *) malloc(strlen(res)+1); if(ptr_daten->variable == NULL) return NULL; ptr_daten->variable = res; res = strtok(NULL, "\0"); if(res == NULL) return NULL; ptr_daten->wert =(char *) malloc(strlen(res)+1); if(ptr_daten->wert == NULL) return NULL; ptr_daten->wert = res; /* printf("%s %s<br>", * ptr_daten->variable, ptr_daten->wert); */ ptr_daten->next = (struct CGI_DATEN *) malloc(sizeof (struct CGI_DATEN *)); if( ptr_daten->next == NULL ) return NULL; ptr_daten = ptr_daten->next; j++; } } ende = ptr_daten; /* Anfangsadresse der Liste struct CGI_DATEN zurückgeben */ return ptr_anfang; } void loeschen(struct CGI_DATEN *daten) { struct CGI_DATEN *next = NULL; while(daten != ende) { next = daten->next; if(daten->variable != NULL) free(daten); daten=next; } } void printf_error(char *str) { printf("Content-Type: text/html\n\n"); printf("<html><head>\n"); printf("<title>CGI-Fehlermeldung</title>\n"); printf("</head><body>\n"); printf("%s",str); printf("</body></html>\n"); } int main(void) { char *str; struct CGI_DATEN *cgi; struct CGI_DATEN *free_cgi; FILE *f; /* Eingabe einlesen */ str = getdata(); if(str == NULL) { printf_error("Fehler beim Einlesen von der " "Formulareingabe"); return EXIT_FAILURE; } /* Hexzeichen in ASCII-Zeichen konvertieren und aus '+' * Leerzeichen machen */ hex2ascii(str); /* Liste der Formualardaten erstellen */ cgi = erstellen(str); free_cgi = cgi; if (cgi == NULL) { printf_error("Fehler beim Erstellen der " "Variablen/Werte-Liste\n"); return EXIT_FAILURE; } /* Datei zum Schreiben öffnen */ /* Bitte den Pfad anpassen: beispielsweise unter SUSE Linux: * f = fopen("/srv/www/htdocs/gaeste.html", "r+"); * und WICHTIG: Schreibrechte auf diese Datei vergeben */ f = fopen("gaeste.html", "r+"); if(f == NULL) { printf_error("Konnte Datei gaeste.html nicht zum " "Schreiben oeffnen\n"); return EXIT_FAILURE; } else { /* Stream vor </body></html> */ fseek(f, -14, SEEK_END); fprintf(f, "<hr><br>"); /* Eine horizontale Linie */ /* Name */ if(cgi->wert != NULL) fprintf(f, "Name: %s E-Mail: ",cgi->wert); cgi = cgi->next; /* Mailadresse */ if(cgi->wert != NULL) fprintf(f, "<a href=\"mailto:%s\">%s</a> ", cgi->wert,cgi->wert); cgi = cgi->next; /* Bewertung */ if(cgi->wert != NULL) fprintf(f, "Bewertung : %s",cgi->wert); cgi = cgi->next; /* Eintrag */ if( cgi->wert != NULL) { fprintf(f, "<p><b>Der Eintrag : </b>"); fprintf(f, "%s",cgi->wert); } cgi = cgi->next; /* Programmierkenntnis(se) */ if(cgi->wert != NULL) { fprintf(f, "<br><br>Programmierkenntnisse : "); while(cgi->wert != NULL && strcmp(cgi->variable,"programmieren") == 0 ) { fprintf(f, "%s ",cgi->wert); cgi = cgi->next; } } fprintf(f, "</p></body></html>"); fclose(f); } /* Speicher wieder freigeben */ loeschen(free_cgi); /* Auch hier müssen Sie die Pfadangabe ggf. anpassen. */ print_location("http://localhost/gaeste.html"); return EXIT_SUCCESS; } Wichtig in diesem Listing ist der Pfad zum Ãffnen der Datei gaeste.html > f = fopen("gaeste.html", "r+"); den Sie gegebenenfalls anpassen müssen. Bei dieser Angabe wird davon ausgegangen, dass sich das HTML-Dokument im cgi-bin-Verzeichnis befindet. Das funktioniert aber nicht auf jedem System. Beispielsweise bei SUSE 8.2 sieht der Pfad auf meinem System wie folgt aus: > f = fopen("/srv/www/htdocs/gaeste.html","r+"); ... vorausgesetzt, die Datei gaeste.html befindet sich auch im entsprechenden Verzeichnis. Denken Sie auch an die Angabe und Ãnderung des Pfades, wenn Sie die CGI-Anwendung ins Web stellen. Der zweite wichtige Pfad in dieser Anwendung ist der folgende: > print_location("http://localhost/gaeste.html"); Auch hier muss der Speicherort der Datei gaeste.html richtig angegeben werden. Im Beispiel bedeutet dies, dass sich die Datei im htdocs-Verzeichnis des Webservers befindet. Dies sollte hier erwähnt werden, da ich aus Erfahrung weiÃ, dass dies eine der häufigsten Ursachen dafür ist, warum eine CGI-Anwendung nicht auf Anhieb funktioniert. ### 23.12.3 Das HTML-Gästebuch (»gaeste.html«) > <html> <head> <title>Gästebuch</title> </head> <body> <center><h1> Einträge im Gästebuch</h1></center><br> </body></htmlDies ist die Datei, in der die CGI-Anwendung auswert.cgi neue Daten schreibt. Daher muss der Speicherort der Datei mit den Angaben der Funktionen fopen() und print_location() im Programm auswert.cgi übereinstimmen. AuÃerdem benötigen Sie das Schreibrecht auf diese Datei, das Sie mit chmod nachträglich vergeben können (chmod a+rwx gaeste.html). # Das Beispiel ausführen In diesem Beispiel wird davon ausgegangen, dass sich die Dateien auswert.cgi und gaeste.html im cgi-bin-Verzeichnis befinden. Bitte passen Sie die Pfade im Listing auswert.c an Ihre Bedürfnisse an. Starten Sie als Erstes wieder Ihren Lieblingswebbrowser, und öffnen Sie die HTML-Datei guestbook.html. Befindet sich diese beispielsweise im htdocs-Verzeichnis des Webservers, können Sie diese Datei mit folgender URL aufrufen: Jetzt sollte die HTML-Seite erscheinen, und zwar mit dem Formular aus Abbildung 23.22. Abbildung 23.22 Eingabeformular des Gästebuchs Wenn Sie alle Daten eingetragen haben, klicken Sie auf den Abschicken-Button, und das CGI-Programm auswert.cgi verrichtet seine Arbeit. Gleich darauf leitet das CGI-Programm Sie zur Seite gaeste.html weiter, wo Sie sich den neuen Eintrag ansehen können. Zugegeben, das Layout entspricht nicht mehr dem heutigen Standard, aber darum geht es hierbei nicht. Abbildung 23.23 Einträge im Gästebuch # 23.13 Ausblick ## 23.13 Ausblick Sie wissen jetzt, wie Sie CGI-Anwendungen in C erstellen und anwenden können. Sollten Sie beabsichtigen, eine eigene CGI-Bibliothek zu schreiben, wissen Sie ja nun, wie Sie dabei vorgehen können. Haben Sie keine Lust, eine Bibliothek zu schreiben, greifen Sie einfach auf eine bereits vorhandene Bibliothek zurück. Ich kann Ihnen die cgic-Bibliothek von Thomas Boutell empfehlen. Diese entspricht zum einen dem ANSI-C-Standard und ist zum anderen vielfach erprobt. Die Bibliothek können Sie mitsamt einer guten und ausführlichen Dokumentation von der Webseite http://www.boutell.com/cgic/ herunterladen. Sie werden im nächsten Kapitel mit MySQL nochmals auf die CGI-Schnittstelle zurückgreifen und die hier erstellten Funktionen verwenden. # 24.2 MySQL installieren ## 24.2 MySQL installieren ### 24.2.1 Linux Die Installation unter Linux gestaltet sich wieder relativ einfach. Ein Download sollte eigentlich nicht erforderlich sein, da MySQL in der Regel jeder Linux-Distribution beiliegt. Bei der Suche nach MySQL in Ihrer Linux-Distribution wird Ihnen auffallen, dass – abhängig von der Distribution – meistens noch eine Reihe weiterer Pakete vorhanden sind. Neben dem MySQL-Server (meistens mysql–server) sollten Sie auch mysql-client und libmysql installiert haben. Wie die Pakete genau heiÃen, hängt teilweise auch von der Distribution ab. Wenn alle Pakete installiert wurden, können Sie den Datenbankserver starten. Unter Ubuntu genügt hierzu beispielsweise der Befehl (bei vielen anderen Distributionen funktioniert das auch als Root und ohne sudo): > $ sudo /etc/init.d/mysql start [sudo] password for user: ****** * Starting MySQL database server mysqld [ OK ] Stoppen können Sie den Server wiederum mit: ``` $ sudo /etc/init.d/mysql stop * Stopping MySQL database server mysqld [ OK ] ``` Bei anderen Distributionen (beispielsweise RedHat, Fedora, Mandrake) kann das Verzeichnis zum Script auch /etc/rc.d/init.d/ sein. Bei der FreeBSD kann der MySQL Server auch mit folgendem Befehl vom Superuser gestartet bzw. gestoppt werden: > $ /usr/local/etc/rc.d/mysql-server start Starting service MySQL done $ /usr/local/etc/rc.d/mysql-server stop Shutting down service mysql done Mit dem Befehl restart am Ende (anstatt mit start oder stop) können Sie den MySQL-Server neu starten lassen. Die Installation unter Windows verläuft ähnlich einfach, nur dass Sie hier das Binary zunächst von http://www.mysql.de herunterladen müssen. AnschlieÃend finden Sie einen anwenderfreundlichen Installer, mit dem Sie MySQL Klick für Klick installieren können. Sie müssen lediglich den Anweisungen auf dem Bildschirm folgen. Damit Sie anschlieÃend auch MySQL-Anwendungen erstellen können, müssen Sie hierbei auch die Bibliothek und Headerdateien mitinstallieren. Mit dem typischen Klick für Klick auf Next geschieht dies leider nicht automatisch, sodass Sie bei der Option, was Sie alles installieren wollen, anstatt Typical bzw. Standard hier Custom bzw. Benutzerdefiniert auswählen müssen und bei den Developer-Components die Option C Include Files / Lib Files aktivieren. Zunächst sollten Sie sich hier den MySQL-Server von http://www.mysql.de/ heruntergeladen, um eben die Bibliothek und Headerdateien (im lib- und include-Verzeichnis) für unsere MySQL-Anwendungen zu verwenden. Sie können jetzt natürlich jederzeit wieder das XAMPP Control Panel verwenden, um MySQL zu starten bzw. stoppen. Alternativ können Sie aber auch, wenn Sie beispielsweise kein XAMPP verwenden wollen oder können, den MySQL-Server mit dem MySQL Server Instance Configuration Wizard einrichten und konfigurieren. Hierzu müssen Sie einfach den Anweisungen auf dem Bildschirm folgen. Hierbei kann der MySQL-Server dann auch gleich als Dienst eingerichtet werden. ### 24.2.2 Den Client »mysql« starten Der Client (oder besser die SQL-Shell) mysql ist im Standardumfang von MySQL enthalten und quasi das wichtigste Werkzeug, um mit MySQL in der Kommandozeile zu arbeiten. Die MySQL-Shell soll jetzt aufgerufen werden. Starten Sie hierfür, falls das noch nicht geschehen ist, den MySQL-Server. Da das Werkzeug mysql eine gewaltige Anzahl von Optionen besitzt, können Sie es auch mit dem Flag -help aufrufen, um sich einen Ãberblick zu verschaffen. FolgendermaÃen können Sie den Client beispielsweise starten: > $ mysql -uroot -p -hlocalhost Enter password: ***** ... mysql Sie starten hierbei die MySQL-Shell mit dem User root und dem Host localhost. Sie können sich von Haus aus als Benutzer root mit dem MySQL-Server verbinden. Das sollte eigentlich auch logisch sein, denn sonst hätten Sie keinen Zugriff auf den MySQL-Server. Mit der Option -p werden Sie interaktiv nach dem Passwort gefragt. Alternativ funktioniert dies natürlich auch bei Windows mit (beispielsweise befindet sich mysql.exe im Pfad C:\xampp\mysql\bin): > C:\xampp\mysql\bin\mysql.exe -uroot -p -hlocalhost Für den Fall, dass Sie noch kein Passwort vergeben haben, können Sie die Option -p hier auch weglassen. Jetzt sehen Sie den Eingabecursor: > mysqlWenn Sie nun quit eingeben, können Sie den Client wieder verlassen. Das Client-Programm mysql, das Sie gerade gestartet haben, wird verwendet, um SQL-Anweisungen an den Datenbankserver zu übermitteln. In der Praxis kann dafür auch das Tool phpMyAdmin verwendet werden, mit dem eine vollständige Administration der MySQL-Datenbank mithilfe des Webbrowsers möglich ist. Das Tool wird über PHP-Dokumente und das HTTP-Protokoll aufgerufen und lässt sich somit auf allen Betriebssystemen mit dem Webbrowser verwenden. # mysqladmin Wollen Sie ein Passwort ändern oder vergeben, können Sie dies recht komfortabel mit dem Client mysqladmin (beispielsweise mysqladmin.exe) realisieren. Beispielsweise können Sie folgendermaÃen ein Passwort für den User root vergeben: ``` $ mysqladmin -uroot password k4p6m3o3 ``` Hier haben Sie dem User root das Passwort k4p6m3o3 gegeben. Natürlich können Sie das Passwort so auch jederzeit wieder mit mysqladmin ändern: > $ mysqladmin -uroot -pk4p6m3o3 password Jürgen $ mysql -uroot -pk4p6m3o3 -hlocalhost ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) $ mysql -uroot -pJürgen -hlocalhost Welcome to the MySQL monitor. Commands end with ; or \g. ... Hiermit haben Sie das Passwort k4p6m3o3 in das Passwort Jürgen umgeändert. Sie sollten sich natürlich ein anderes Passwort einfallen lassen. Es empfiehlt sich allerdings auf Produktivsystemen nicht diesen Befehl abzusetzen. Falls es jemand schafft, Root-Rechte auf dem Server zu erlangen, kann er somit das Hauptpasswort für die DB aus der /root/.bash_history auslesen (erste Anlaufstelle für Cracker). Es ist sinnvoller, das Passwort im mysql-Monitor mit den Grant-Funktionen zu ändern oder mit einem > mysql > USE mysql; mysql > UPDATE user SET Password=PASSWORD('neues_password') > WHERE User='root'; und danach mit ``` mysql > FLUSH PRIVILEGES; ``` die User-Datenbank neu einzulesen. # 24.3 Crashkurs (My)SQL ## 24.3 Crashkurs (My)SQL Um mit MySQL arbeiten zu können, werden Sie nun einige grundlegende Sprachelemente kennenlernen. Vieles wird Ihnen als C-Programmierer ohnehin nicht schwerfallen. Natürlich soll hier nicht die ganze Palette von SQL-Kommandos verwendet werden, sondern nur eine ausgewählte Anzahl, die Sie in die Lage versetzt, eine Datenbankstruktur aufzubauen und die zugehörigen Abfragen zu formulieren. ### 24.3.1 Was ist SQL? Um es gleich vorweg zu nehmen: SQL ist keine Programmiersprache. SQL steht für Structured Query Language und gliedert sich in zwei Teile: * DDL-Anweisungen (Data Definition Language) – Diese Anweisungen dienen zum Aufsetzen der Datenbankstruktur. * DML-Anweisungen (Data Manipulation Language) – Diese Anweisungen beziehen sich auf die Manipulation von Daten. ### 24.3.2 Die Datentypen von (My)SQL Genauso wie in C gibt es bei MySQL Datentypen. Aufgeteilt werden diese in numerische Datentypen, Datentypen für Strings und Datentypen für Datum und Zeit. Wir beginnen mit einer kurzen Ãbersicht zu den Datentypen für Ganzzahlen (Integer-Datentypen) mit deren Bereichsangabe: Wie schon in C können Sie auch in MySQL mit dem Schlüsselwort UNSIGNED das Vorzeichenbit setzen. Für Gleitpunktzahlen stehen Ihnen folgende Datentypen zur Verfügung: Für Strings (Zeichenketten) können Sie gleich mehrere Datentypen einsetzen, die sich – abgesehen vom Namen – hauptsächlich durch die Anzahl der Zeichen unterscheiden, die sie aufnehmen können: Datentyp | Speicherbedarf | Erkärung | | --- | --- | --- | | | | | | | | | | | | | | | | | | | Die BLOP-Datentypen sind für Binärdaten gedacht. Zu guter Letzt folgen noch einige MySQL-Datentypen für Datum und Zeit: Anhand eines Beispiels sollen Sie in die SQL-Sprache eingeführt werden. Starten Sie zuerst wieder den Client mysql mit: > mysql -u root -h localhost ### 24.3.3 Eine Datenbank erzeugen Bevor Sie mit einer Datenbank arbeiten, müssen Sie zunächst eine neue erzeugen. Dies können Sie mit folgendem Befehl erreichen: > CREATE DATABASE dvd_archiv; Abbildung 24.3 Eine Datenbank wurde erstellt. Mit diesem SQL-Kommando erzeugen Sie eine neue Datenbank mit dem Namen dvd_archiv. Wie Sie es bereits von C her kennen, wird der Befehl mit einem Semikolon abgeschlossen. Existiert eine Datenbank bereits, wird eine Fehlermeldung mit ausgegeben. Wollen Sie eine Bedingung beim Anlegen einer neuen Datenbank erstellen, können Sie so vorgehen: > CREATE DATABASE IF NOT EXISTS dvd_archiv; Mit IF NOT EXISTS wird erst überprüft, ob eine Datenbank mit dem Namen dvd_archiv noch nicht vorhanden ist. Ist dies der Fall, wird der Befehl CREATE DATABASE ausgeführt. ### 24.3.4 Eine Datenbank löschen Als Nächstes soll die neu erstellte Datenbank wieder gelöscht werden. Falls Sie den Namen der neu erstellten Datenbank vergessen haben, lassen Sie sich am besten einen Ãberblick aller Datenbanken geben. Hierfür verwenden Sie den SQL-Befehl: > SHOW DATABASES; Abbildung 24.4 Anzeigen aller vorhandenen Datenbanken Jetzt ist es also wieder Zeit, die Datenbank dvd_archiv zu löschen: > DROP DATABASE dvd_archiv; Wollen Sie auch hier eine Fehlermeldung mit einer Bedingung abfangen, können Sie das Löschen auch so schreiben: > DROP DATABASE IF EXISTS dvd_archiv; Hiermit wird nur dann versucht, die Datenbank zu löschen, wenn diese auch existiert. Erstellen Sie wieder die Datenbank dvd_archiv, damit Sie mit den folgenden Beispielen weitermachen können. ### 24.3.5 Datenbank wechseln Wenn Sie zwischen verschiedenen Datenbanken wechseln wollen, können Sie den Befehl USE verwenden. Beispiel: > USE dvd_archiv; ### 24.3.6 Eine Tabelle erstellen Nachdem Sie eine Datenbank erstellt haben, wollen Sie sicherlich auch Daten darin speichern. Zuerst müssen Sie aber noch eine Tabelle anlegen. Eine Tabelle erzeugen Sie mit folgender SQL-Anweisung: > CREATE TABLE filmdaten ( titel CHAR(255), hauptrolle CHAR(255), gedreht YEAR ); Mit diesem SQL-Kommando erstellen Sie in der Tabelle filmdaten die Spalten titel mit dem Datentyp CHAR(255), hauptrolle mit dem Datentyp CHAR(255) und gedreht mit dem Datentyp YEAR. Die Tabelle (Datensatz) mit dem Namen filmdaten (maximal sind 64 Zeichen erlaubt) wird in der Datenbank dvd_archiv erzeugt – vorausgesetzt, Sie sind mit USE zur entsprechenden Datenbank gewechselt. Als Inhalt der Tabelle wurden drei Variablen deklariert: zwei Datentypen für Strings mit jeweils 255 Zeichen, die den Titel (titel) und den Hauptdarsteller (hauptrolle) eines bestimmten Films enthalten, sowie ein Datentyp, der das Jahresdatum des Films speichern kann. Die Schreibweise, die hier verwendet wurde, ist nicht unbedingt so vorgeschrieben. Die Tabelle kann auch mit einer Zeile auf einmal erzeugt werden: > CREATE TABLE filmdaten (titel CHAR(255),hauptrolle CHAR(255), gedreht YEAR); Die Syntax setzt sich aber immer folgendermaÃen zusammen: > CREATE TABLE tbl (Spaltenname Datentyp_der_Spalte, Spaltenname Datentyp_der_Spalte, Spaltenname Datentyp_der_Spalte); Im Gegensatz zu C wird also hier der Bezeichner vor dem Datentyp geschrieben. ### 24.3.7 Die Tabelle anzeigen Einen Ãberblick zu der Tabelle, die Sie mit CREATE erstellt haben, können Sie sich wieder mit dem SQL-Kommando SHOW anzeigen lassen: > SHOW TABLES; ### 24.3.8 Tabellendefinition überprüfen Wissen Sie nicht mehr genau, was Sie alles in der Tabelle angegeben haben, können Sie sich mit dem Befehl EXPLAIN einen Ãberblick verschaffen: > EXPLAIN filmdaten; Abbildung 24.5 Ãberprüfen der Tabellendefinition ### 24.3.9 Tabelle löschen Benötigen Sie eine Tabelle nicht mehr, können Sie diese mit demselben SQL-Befehl wie zum Löschen einer Datenbank entfernen: > DROP TABLE IF EXISTS filmdaten; Wobei IF EXISTS hier wieder optional ist. Sie sehen, wie einfach es ist, mit MySQL etwas zu löschen. Daher ist es oft sinnvoll, regelmäÃig ein Backup einer Datenbank durchzuführen. Wenn Sie ein Backup erstellen wollen, können Sie sich den Client mysqldump ansehen, der ebenfalls bei einer normalen MySQL-Installation dabei ist. Wollen Sie beispielsweise die vollständige MySQL-Datenbank sichern, dann geben Sie Folgendes im Prompt ein: > mysqldump -u root -p -opt -all -databases > my_backup.sql Nach dieser Eingabe müssen Sie noch schnell Ihr Passwort eingeben, und die Daten sind gesichert. Wollen Sie das Backup wiederherstellen, können Sie dies mit dem Client mysql so erreichen: > mysql -u root -p < my_backup.sql ### 24.3.10 Struktur einer Tabelle ändern Jetzt wollen Sie die Struktur einer Tabelle ändern. Dies können Sie unabhängig davon, ob diese Tabelle schon Daten beinhaltet, mit dem SQL-Kommando ALTER vornehmen. In der Tabelle filmdaten fehlt noch die Altersbeschränkung der einzelnen Filme. Diese soll jetzt hinter der Reihe hauptrolle eingefügt werden: > ALTER TABLE filmdaten ADD fsk TINYINT AFTER hauptrolle; Bei gewissen Englischkenntnissen lässt sich diese Zeile doch schon fast wie ein Satz lesen: »Ãndere Tabelle filmdaten und füge fsk vom Typ TINYINT hinter hauptrolle hinzu.« Mit dem SQL-Kommando ALTER lässt sich noch so manches mehr anstellen. Wollen Sie etwa ein Element in der Tabelle entfernen, schreiben Sie: > ALTER TABLE filmdaten DROP fsk; Hier würde zum Beispiel die Spalte fsk von der Tabelle filmdaten entfernt. Eine Spaltenbezeichnung können Sie mit folgendem Kommando ändern: > ALTER TABLE filmdaten CHANGE fsk alter INT; Hiermit würden Sie die Spalte fsk in alter umbenennen. AuÃerdem ist das neue Element jetzt vom Datentyp INT. Falls Sie beim Titel der Tabelle filmdaten mehr als 255 Zeichen eingeben wollen, schreiben Sie: > ALTER TABLE filmdaten MODIFY titel CHAR(300); Das ALTER-Kommando ist sehr vielfältig einsetzbar, sodass es sich lohnen würde, dieses Kommando noch genauer zu untersuchen. ### 24.3.11 Datensätze eingeben Mit dem Kommando INSERT können Sie Daten in die Tabelle einfügen. Es gibt drei Möglichkeiten, wie INSERT verwendet werden kann. In diesem Abschnitt folgt zunächst die einfachste Variante. Jetzt fügen Sie Ihre ersten Daten in die Tabelle filmdaten ein: > INSERT INTO filmdaten (titel, hauptrolle, fsk, gedreht) VALUES (’<NAME>’, ’<NAME>’, 16, 2001); Wichtig ist, dass der Inhalt in der zweiten Klammerung mit der Reihenfolge der ersten Klammerung der Tabelle übereinstimmen muss. Sie könnten diese Daten auch in einer anderen Reihenfolge in die Tabelle einlesen: > INSERT INTO filmdaten (hauptrolle, titel, gedreht, fsk) VALUES (’<NAME>’, ’<NAME>’, 2001, 16); Sie müssen also immer darauf achten, dass die in VALUES angegebenen Werte mit denen der ersten Klammerung übereinstimmen. Sie können natürlich auch mehrere Daten auf einmal in eine Tabelle einfügen: > INSERT INTO filmdaten (titel, hauptrolle, fsk, gedreht) VALUES (’Braveheart’, ’<NAME>’, 16, 1998), (’Hello Mr. President’, ’<NAME>’, 6, 1995); Die einzelnen Datensätze der Tabelle werden dabei jeweils durch Kommata getrennt. Die Strings wurden hier zwar zwischen einzelne Hochkommata gestellt, können bei MySQL aber auch – wie Sie es aus C kennen – zwischen doppelte Hochkommata gestellt werden. ### 24.3.12 Datensätze auswählen Jetzt kommen wir zum wohl wichtigsten und am meisten angewandten Befehl in SQL: SELECT. Mit SELECT können Sie aus einer oder mehreren Tabellen Informationen zusammentragen. Zuerst sollen mittels SELECT alle Daten der Tabelle filmdaten angezeigt werden: > SELECT * FROM filmdaten; Abbildung 24.6 Datensätze selektieren Das Sternchen steht hier als ein Platzhalter für alle in der Tabelle vorhandenen Spalten. Dieser Platzhalter hat dieselbe Bedeutung, als wenn Sie Folgendes schreiben würden: > SELECT titel, hauptrolle, fsk, gedreht FROM filmdaten; Auch hiermit werden alle Daten einer Tabelle ausgegeben. Mit FROM geben Sie die Tabelle an, die selektiert werden soll. Interessieren Sie sich nur für die Titel der Filme, können Sie SELECT folgendermaÃen verwenden: > SELECT titel FROM filmdaten; Wollen Sie hingegen nur die Daten der Filme ausgeben, bei denen <NAME> der Hauptdarsteller ist, verwenden Sie zusätzlich das SQL-Kommando WHERE: > SELECT * FROM filmdaten WHERE hauptrolle=’<NAME>’; Falls Sie nicht mehr genau wissen, wie der Hauptdarsteller geschrieben wird, verwenden Sie Folgendes: > SELECT * FROM filmdaten WHERE hauptrolle LIKE ‘Mel%’; Hier wurde der Unschärfe-Operator LIKE eingesetzt. Wollen Sie alle Filme sortiert nach Datum ausgeben lassen, erreichen Sie dies mit: > SELECT * FROM filmdaten ORDER BY gedreht ASC; Mit dem SQL-Befehl ORDER BY sagen Sie dem Server, dass er die Daten geordnet ausgeben soll; in welcher Reihenfolge das geschieht, geben Sie mit ASC (aufsteigend) oder DESC (absteigend) an. Sie können natürlich auch die Vergleichsoperatoren verwenden, die Sie bereits von C her kennen. ### 24.3.13 Ein fortgeschrittenes Szenario Ein Blick auf Ihre Datenbank dvd_archiv zeigt Ihnen, dass Sie einige Filme verliehen haben. Leider wissen Sie nicht mehr, an wen. Da Sie sich ein wenig mit MySQL auskennen, lösen Sie das Problem mit der Datenbank. Zuerst erstellen Sie eine neue Tabelle kontakt in der Datenbank dvd_archiv: > CREATE TABLE kontakt(nname CHAR(30), vname CHAR(30), telefon BIGINT); Als Nächstes geben Sie die Daten für die Tabelle kontakt ein: > INSERT INTO kontakt(nname, vname, telefon) VALUES (’Meier’, ’Hans’, 12345676), (’Müller’, ’Franz’, 3691215), (’Schiller’, ’Johann’, 48121620); Jetzt benötigen Sie noch eine Tabelle, in der sich die Filme befinden, die Sie verliehen haben, zusammen mit der Information, an wen sie verliehen wurden: > CREATE TABLE verliehen(name CHAR(30), titel CHAR(255)); Sie lernen jetzt eine weitere Methode kennen, wie Sie Datensätze mit INSERT einlesen können: > INSERT INTO verliehen (name, titel) SELECT kontakt.nname, filmdaten.titel FROM kontakt, filmdaten WHERE filmdaten.titel = ’Der Patriot’ AND kontakt.nname = ’Meier’; Hier fügen Sie mittels SELECT Daten in die Tabelle verliehen ein. Mit den Zeilen kontakt.nname und filmdaten.titel haben Sie eine Verknüpfung zweier Tabellen realisiert und zum ersten Mal Kontakt mit dem relationalen Modell gehabt. Denn obwohl beide Tabellen physisch voneinander getrennt sind, können diese mit SELECT verknüpft werden. Neu ist auch die logische AND-Verknüpfung, die Sie als C-Programmierer als && kennen. Wenn Sie nun einen Blick auf die Tabelle verliehen werfen, befindet sich jetzt darin tatsächlich der Titel des Films und der Name, an wen Sie den Film verliehen haben: > SELECT * FROM verliehen; Nun wollen Sie die Telefonnummer der Person ermitteln, damit Sie sich mit dieser in Verbindung setzen können. Versuchen Sie es einmal selbst in Worte zu fassen. Beispiel: »Suche die Telefonnummer von einer Person, der ich einen Film geliehen habe.« So setzen Sie dies in MySQL um: > SELECT telefon FROM kontakt, verliehen WHERE verliehen.name = kontakt.nname; Ein echter MySQL-Guru geht dabei sicherlich noch eleganter zu Werke. Aber das ist jetzt nicht das Ziel dieses Kapitels. Das Beispiel soll Ihnen zeigen, warum Sie gut beraten sind, eigene Client-Programme in C zu schreiben. ### 24.3.14 Datensatz löschen Hat Ihnen der Bekannte den Film wieder zurückgebracht, ist es an der Zeit, ihn aus der Tabelle verliehen zu löschen. Dies können Sie mit dem SQL-Befehl DELETE erledigen: > DELETE FROM verliehen WHERE titel = 'Der Patriot'; ### 24.3.15 Datensatz ändern Mit dem SQL-Kommando UPDATE können Sie die einzelnen oder auch mehrere Datensätze in einer Tabelle ändern. Zusätzlich wird der Befehl SET dazu verwendet. Wollen Sie beispielsweise die Altersbeschränkung für einen Film verändern, können Sie dabei so vorgehen: > UPDATE filmdaten SET fsk=12 WHERE fsk=6; Damit werden alle Daten fsk, bei denen der Wert 6 beträgt, in den Wert 12 umgeändert. ### 24.3.16 Zugriffsrechte in MySQL Auf die Zugriffsrechte von MySQL soll hier nur kurz eingegangen werden. Die Zugriffsrechte von MySQL werden ebenfalls in Tabellen verwaltet. Wechseln Sie in die Datenbank, und sehen Sie sich die Tabellen darin an: > USE mysql; SHOW TABLES; Sechs Tabellen werden aufgelistet. Die haben folgende Bedeutung: Tabelle | Bedeutung | | --- | --- | | | | | | | | | | | | | Anhand dieser Tabelle lassen sich folgende Zugriffslevel zur Vergabe von Benutzerrechten vergeben: * globale Rechte – Bezieht sich auf alle Datenbanken. * Datenbank – Bezieht sich auf eine bestimmte Datenbank. Benutzerrechte vergeben können Sie mit dem SQL-Kommando GRANT, und die Benutzerrechte entziehen Sie mit REVOKE. Da das Thema recht umfangreich ist, sei hierfür auf die MySQL-Dokumentation verwiesen. ### 24.3.17 Ãbersicht über einige SQL-Kommandos Damit Sie im weiteren Verlauf nicht immer wieder zu den einzelnen Abschnitten zurückblättern müssen, folgt hier ein kurzer Ãberblick über die SQL-Kommandos, die Sie bisher kennengelernt haben, und ihre jeweilige Bedeutung: SQL-Kommando | Bewirkt | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | # 24.4 Die MySQL-C-API ## 24.4 Die MySQL-C-API Die MySQL-C-API ist eine Bibliothek, die in C geschrieben wurde und die es Ihnen erlaubt, Client-Programme mit Zugriff auf die MySQL-Datenbank zu erstellen. Abgesehen von der MySQL-C-API gibt es noch MySQL-APIs zu Perl, PHP, C++, Python, Tcl und einen Eiffel-Wrapper, die aber alle – wie auch die C-API – die mysqlclient-Bibliothek verwenden. Eine Ausnahme stellt hierbei nur Java dar. Um mit Java auf den MySQL-Server zuzugreifen, wird der JDBC-Treiber benötigt. ### 24.4.1 Grundlagen zur Programmierung eines MySQL-Clients Bevor Sie beginnen, eigene Client-Programme zu schreiben, sollten Sie zunächst in Erfahrung bringen, wie Sie ein solches Programm erstellen können. Das Kompilieren und Linken eines Client-Programms ist gerade unter Windows recht umständlich. Umständlich daher, weil die Bibliothek libmysql.lib mit dem Visual-C++-Compiler erzeugt wurde. Für denjenigen, der diesen Compiler unter Windows verwendet, kann das egal sein. Aber viele Benutzer mit anderen Compilern werden recht schnell frustriert aufgeben, eigene MySQL-Client-Programme zu schreiben, wenn sich die Bibliothek nicht mit dem Compiler verträgt. Dabei darf neidisch auf die Linux-Anwender geschaut werden, da es auf diesem System überhaupt keine Probleme gibt, denn dort wird der Compiler gcc verwendet. Die Auswahl des Compilers und das Herumärgern mit der Bibliothek fallen also schon einmal weg. Damit Sie einen MySQL-Client programmieren können, benötigen Sie Folgendes: * die MySQL-Bibliothek (lib) * die MySQL-Headerdateien (include) Unter Windows ist bei einer Standardinstallation von MySQL in der Regel beides vorhanden. Die Bibliothek sollten Sie dabei im Verzeichnis c:\mysql\lib\opt (»c:« sei das Laufwerk) vorfinden und die Headerdateien im Verzeichnis c:\mysql\include. Bei Linux sollten Sie die Bibliothek im Verzeichnis /usr/lib oder /usr/lib/mysql oder auch /usr/local/lib/mysql finden. Die Headerdatei ist in der Regel unter /usr/include/mysql oder auch unter /usr/local/include/mysql abgelegt. Bei einer RPM-Installation unter Linux kann es auch sein, dass Sie zur Entwicklung eigener Clients noch ein extra RPM installieren müssen (Developer RPM). Wollen Sie jetzt den Client-Quellcode, den Sie erstellt haben, kompilieren und linken, müssen Sie angeben, wo sich die Headerdateien und die Bibliothek von MySQL befinden. Bei Windows müssen Sie auÃerdem die DLL libmysql.dll in ein Systemverzeichnis kopieren. Zumeist sollte dies das Verzeichnis c:\Windows\system32 sein. ### 24.4.2 Client-Programm mit dem gcc unter Linux und dem Cygwin–gcc-Compiler unter Windows Zuerst kompilieren Sie das geschriebene Client-Programm, in dem Sie mit dem Compiler-Flag -I (Include) angeben, an welcher Stelle sich die Headerdateien von MySQL befinden. Bei Linux mit gcc sieht das so aus: > gcc -c -I/usr/include/mysql myclient.c Bei Windows unter der Cygwin-Umgebung mit gcc sieht das so aus: > gcc -c -I"c:\mysql\include" myclient.c Jetzt verfügen Sie über eine Objektdatei in dem Verzeichnis, in dem Sie den Quellcode kompiliert haben. Als Nächstes müssen Sie diese Objektdatei zu einer ausführbaren Datei linken. Damit dies auch funktioniert, müssen Sie dem Linker mitteilen, wo sich die Client-Bibliothek von MySQL befindet. Dies erledigen Sie mit dem Compiler-Flag -L, mit dem der Pfad zur Bibliothek angegeben wird, und dem Flag -l, mit dem Sie die Bibliothek angeben, die hinzugelinkt werden soll. Die Eingabe für Linux lautet: > gcc -o myclient myclient.o -L/usr/lib/mysql -lmysqlclient Und mit Windows unter der Cygwin-Umgebung: > gcc -o myclient.exe myclient.o -L"c:\mysql\lib\opt" -llibmysql Bei Windows sollten Sie die dynamische Bibliothek libmySQL hinzulinken, die ein Wrapper zum Laden von libmySQL.dll ist. Es ist aber auch möglich, die statische Bibliothek mysqlclient.lib hinzuzulinken. Wenn alles bis hierher glatt verlaufen ist, können Sie den Client beim Namen aufrufen. ### 24.4.3 MySQL Client-Programme mit dem VC++ Compiler und dem Borland Freeware Compiler Bei beiden Compilern gehe ich davon aus, dass diese bereits auf Ihrem System installiert sind. Installationsanleitungen diverser Compiler finden Sie unter https://www.rheinwerk-verlag.de/2132/. # MS Visual C++ Erstellen Sie wie gewöhnlich ein leeres Win32-Konsolen-Fensterprojekt. Fügen Sie dem Projekt eine C++-Datei hinzu. In diese Datei können Sie jetzt wie gewohnt Ihren Quellcode eingeben. Binden Sie die Headerdateien "mysql.h" und "my_global.h" mit ein: > #include "my_global.h" #include "mysql.h" Bei den Projekteigenschaften (die Sie bei Visual C++ 2008 Express Edition beispielsweise über + erreichen) müssen Sie jetzt noch die Pfade zu den Headerdateien und der Bibliothek angeben, damit der Compiler die Headerdatei und der Linker die Bibliothek findet. Den Pfad zum include-Verzeichnis der MySQL-C-API können Sie über Projekt • projektname-Eigenschaften und im sich dann öffnenden Fenster über Konfigurationseigenschaften • C/C++ • Allgemein bei Zusätzliche Includeverzeichnisse auswählen (bei mir lautet das Verzeichnis beispielsweise "C:\Program Files\MySQL\MySQL Server 5.1\include"). Auch den Pfad zur Bibliothek libmysql.lib können Sie über Projekt • projektname-Eigenschaften bei Konfigurationseigenschaften • Linker • Befehlszeile im Textfeld Zusätzliche Optionen eingeben (bei mir lautet das Verzeichnis beispielsweise "C:\Program Files\MySQL\MySQL Server 5.1\lib\opt\libmysql.lib"). Abbildung 24.7 Projekteigenschaften wie den Pfad zur Bibliothek und Headerdateien von MySQL einstellen Jetzt können Sie das Programm linken und ausführen. Voraussetzung ist natürlich auch, dass Sie die DLL libmySQL.dll in ein Systemverzeichnis kopiert haben (beispielsweise system32). # Borland Freeware Compiler Im bin-Verzeichnis des Borland-Compilers befindet sich das Tool coff2omf, mit dem Sie die im Microsoft-Croff-Format vorliegende libmysql in ein für Borland übliches Format, omf, konvertieren können: > coff2omf c:\mysql\lib\opt\libmysql.lib c:\borland\bcc55\lib\ libmysql.lib Damit kopieren Sie auch gleich die im OMF-Format erzeugte Bibliothek libmysql in das Bibliothekenverzeichnis des Borland-Compilers. Das war es auch schon. Jetzt können Sie das Client-Programm kompilieren: > bcc32 -c -I"c:\mysql\include" myclient.c Nun befindet sich eine Objektdatei im entsprechenden Verzeichnis, die Sie mit den Dateien c0x32.obj, import32.lib sowie cw32.lib und der Bibliothek libmysql zusammenlinken. Die Objektdatei c0x32 und die beiden Bibliotheken import32 und cw32 sind notwendig für eine Konsolenanwendung. Hier sehen Sie die vollständige Linkeranweisung zu einer ausführbaren Datei: > ilink32 c0x32.obj myclient.obj , myclient.exe , , import32.lib cw32.lib libmysql.lib Bei dieser umständlichen Schreibweise empfiehlt es sich, eventuell eine Batchdatei zu erstellen. Nun können Sie den Client mit dem Namen starten. ### 24.4.4 Troubleshooting Die MySQL-C-API verwendet auch Funktionen aus der Headerdatei <math.h> (floor()). Bei manchen Linux-Distributionen müssen Sie <math.h> mit dem Compiler-Flag -lm hinzulinken: ``` gcc -o myclient myclient.o -L/usr/lib/mysql -lmysqlclient -lm ``` Bei Solaris müssen auÃerdem noch folgende zwei Bibliotheken hinzugelinkt werden: Erhalten Sie einen Undefined-reference-Fehler bei den Funktionen compress und uncompress, müssen Sie die Bibliothek zlib mit -lz hinzulinken: Erhalten Sie vom Compiler hingegen undefined reference-Fehler auf verschiedene Funktionen, dann verträgt sich die mysqlclient-Bibliothek nicht mit dem Compiler. Dann müssen Sie sich entweder einen Compiler besorgen, mit dem sich diese Bibliothek verträgt, oder Sie laden sich die Quellcode-Distribution herunter und übersetzen die Bibliothek für Ihren Compiler selbst. Wie Sie dabei vorgehen, können Sie dem MySQL-Manual entnehmen. ### 24.4.5 Das erste Client-Programm – Verbindung mit dem MySQL-Server herstellen Ihr erstes MySQL-Client-Programm wird das einfachste sein. Das Programm stellt ein Grundgerüst für die weiteren Client-Programme dar, die Sie noch schreiben werden. Bevor Sie nämlich umfangreiche Datenbankoperationen vornehmen, müssen Sie sich erst mit dem MySQL-Server verbinden. Zuerst müssen Sie für ein MySQL-Objekt Speicherplatz reservieren und es initialisieren. Ein MYSQL-Handle erstellen Sie wie folgt: > MYSQL *my; Die Struktur MYSQL repräsentiert ein Handle für eine Datenbankverbindung, das Sie für fast alle MySQL-Funktionen benötigen. Die Struktur MYSQL können Sie sich in der Headerdatei <mysql.h> gern genauer ansehen. Um für dieses Handle jetzt Speicherplatz zu reservieren und zu initialisieren, wird die Funktion mysql_init() verwendet. Die Syntax zu dieser Funktion lautet: > MYSQL *mysql_init(MYSQL *mysql); Wird diese Funktion mit einem NULL-Zeiger aufgerufen, wird zuerst Speicherplatz für ein MYSQL-Objekt alloziert und gleich darauf initialisiert. Zurück gibt diese Funktion dann ein neues MYSQL-Objekt. Rufen Sie diese Funktion hingegen mit einem MYSQL-Objekt auf, wird nur das Objekt initialisiert und die Adresse des Objekts zurückgegeben. In beiden Fällen gibt diese Funktion entweder ein initialisiertes MYSQL-Handle zurück oder im Fehlerfall den (C-typischen) NULL-Zeiger. > MYSQL *my; my = mysql_init(NULL); if(my == NULL) { fprintf(stderr, "Fehler beim Initialisieren \n"); exit (EXIT_FAILURE); } Die erfolgreiche Ausführung der Funktion mysql_init() ist Voraussetzung für die nächste Funktion mysql_real_connect(), mit der versucht wird, eine Verbindung mit dem MySQL-Server aufzubauen. Die Syntax dieser Funktion ist ein wenig lang, aber trotzdem recht klar: > MYSQL *mysql_real_connect( MYSQL *mysql, const char *host, const char *user, const char *passwort, const char *db, unsigned int port, const char *unix_socket, unsigned int client_flag ); Ohne erfolgreiche Ausführung dieser Funktion ist es nicht möglich, irgendeine weitere Funktion aus der C-API zu verwenden (mit Ausnahme von mysql_get_client_info()). In Tabelle 24.8 finden Sie die Bedeutungen der einzelnen Parameter der Funktion mysql_real_connect(). Parameter | Bedeutung | | --- | --- | | | | | | | | | | | | | | | | | | Die Funktion mysql_real_connect() gibt als Rückgabewert bei Erfolg das MYSQL-Handle des ersten Parameters zurück. Bei einem Fehler wird NULL zurückgeliefert. Somit sieht der vorzeitige Code folgendermaÃen aus: > MYSQL *my; my = mysql_init(NULL); if(my == NULL) { fprintf(stderr, "Initialisierung fehlgeschlagen\n"); exit (EXIT_FAILURE); } if( mysql_real_connect ( my, /* Zeiger auf MYSQL-Handler */ def_host_name, /* Host-Name */ def_user_name, /* User-Name */ def_passwort, /* Passwort für user_name */ def_db_name, /* Name der Datenbank */ 0, /* Port (default=0) */ NULL, /* Socket (default=NULL) */ 0 /* keine Flags */ ) == NULL) Da beim Aufruf der Funktion mysql_real_connect() fast ein gutes Dutzend Fehler auftreten kann, wäre es sehr aufschlussreich zu erfahren, was denn nicht funktioniert hat. Zum Glück müssen Sie hierfür keine spezielle Routine schreiben, die die einzelnen Fehler abfragt. Sie können die Funktionen mysql_errno() und mysql_error() verwenden. Hier sehen Sie die Syntax der Funktion mysql_errno(): > unsigned int mysql_errno(MYSQL *mysql); Schlägt die Verbindung mit dem Handler mysql fehl, gibt diese Funktion einen Fehlerstatuscode zurück. Wird kein Fehler festgestellt, gibt mysql_errno() 0 zurück. Ein Fehlerstatuscode allein nützt dem Anwender des Client-Programms allerdings recht wenig. Sie könnten jetzt die einzelnen symbolischen Konstanten der Headerdatei <errmsg.h> auswerten; etwa so: > unsigned int error; ... if( mysql_real_connect ( my, /* Zeiger auf MYSQL-Handler */ def_host_name, /* Host-Name */ def_user_name, /* User-Name */ def_passwort, /* Passwort für user_name */ def_db_name, /* Name der Datenbank */ 0, /* Port (default=0) */ NULL, /* Socket (default=NULL) */ 0 /* keine Flags */ ) == NULL) error = mysql_errno(my); if( error == CR_CONN_HOST_ERROR ) fprintf(stderr, "Keine Verbindung zu Host\n"); Die C-API für MySQL hat aber auch hierfür eine Funktion parat. Die Syntax lautet: > char *mysql_error(MYSQL *mysql); Diese Funktion gibt eine entsprechende Fehlermeldung auf dem Bildschirm aus, die von der zuletzt aufgerufenen API-Funktion provoziert wurde. Trat kein Fehler auf, gibt die Funktion einen leeren String (Index[0] == '\0') zurück. Somit können Sie, falls die Funktion mysql_real_connect() NULL zurückgibt, folgendermaÃen eine Fehlermeldung auf dem Bildschirm ausgeben (my sei das MYSQL-Handle): > fprintf (stderr, "Fehler mysql_real_connect(): %u (%s)\n", mysql_errno (my), mysql_error (my)); Hiermit wird im Fall eines Fehlers der Statuscode und ein String mit entsprechender Fehlermeldung ausgegeben. Jetzt haben Sie eine Verbindung mit dem MySQL-Server hergestellt und könnten damit arbeiten. Dazu folgt mehr im nächsten Abschnitt. Wenn eine Verbindung zum Server aufgebaut wurde, sollte diese auch irgendwann wieder freigegeben werden. Eine saubere Beendigung des Clients, also des MYSQL-Handles, erreichen Sie mit der Funktion mysql_close(): > void mysql_close(MYSQL *mysql); Dies sind die grundlegenden Aufgaben, um eine Verbindung mit dem MySQL-Server herzustellen und am Ende auch wieder zu beenden. Dazu sehen Sie jetzt alle Funktionen als ausführbares Programm: > /* mysql1.c */ #include <stdio.h> #include <stdlib.h> #if defined __WIN32__ || _MSC_VER #include "my_global.h" #include "mysql.h" #else #include <mysql.h> #endif int main (int argc, char *argv[]) { MYSQL *my; /* Handle initialisieren */ my = mysql_init(NULL); if(my == NULL) { fprintf(stderr, " Initialisierung fehlgeschlagen\n"); return EXIT_SUCCESS; } /* mit dem Server verbinden */ if( mysql_real_connect ( my, /* Zeiger auf MYSQL-Handler */ NULL, /* Host-Name */ NULL, /* User-Name */ NULL, /* Passwort für user_name */ NULL, /* Name der Datenbank */ 0, /* Port (default=0) */ NULL, /* Socket (default=NULL) */ 0 /* keine Flags */ ) == NULL) { fprintf (stderr, "Fehler mysql_real_connect():" "%u (%s)\n",mysql_errno (my), mysql_error (my)); } else printf("Erfolgreich mit dem MySQL-Server verbunden\n"); /* Hier befindet sich der Code für die Arbeit mit MySQL. */ /* Verbindung trennen */ mysql_close (my); return EXIT_SUCCESS; } ### 24.4.6 MySQL-Kommandozeilen-Optionen Im Listing zuvor wurde die Verbindung zum MySQL-Server über die Funktion mysql_real_connect() mit Default-Werten bzw. NULL-Zeigern aufgebaut. Dass dies in der Praxis häufig nicht so ist, dürfte klar sein. Dieses Thema ist im Prinzip nicht Teil dieses Buchs, doch einige Worte sollen hierzu trotzdem gesagt werden. Vielleicht erinnern Sie sich noch, wie der mysql-Client aufgerufen wurde: > mysql -u root -h localhost Die Bedeutung dieser einzelnen Flags und aller weiteren finden Sie in Tabelle 24.9. Parameter | Kurze Form | Lange Form | | --- | --- | --- | | | | | | | | | | | | | | | | Damit Ihr Client, den Sie programmieren, ebenso Flags auswerten kann wie der mysql-Client, müssen Sie entweder die Argumente aus der Kommandozeile selbst auswerten oder die einzelnen Argumente im Programm abfragen. Sollten Sie auf einem System arbeiten, das die Bibliothek getopt() beinhaltet, rate ich Ihnen, diese dafür zu verwenden. Wollen Sie wissen, wie die Default-Optionen für die aktuelle Verbindung mit MySQL lauten, können Sie die Funktion load_defaults() einsetzen. Die Syntax lautet: > void load_defaults(const char *conf_file, const char **groups, int *argc, char ***argv); Mit dieser Funktion laden Sie aus conf_file – unter Linux ist das die Datei my.cnf und unter Windows häufig auch my.ini – die Optionen der Gruppen groups. Zusätzlich werden noch die Kommandozeilenargumente zur Auswertung verwendet. Für die Variable groups können Sie einen oder mehrere Strings angeben. Dies sind die Zeilen, die in den eben genannten Konfigurations-Files zwischen eckigen Klammen stehen, beispielsweise unter Windows: > [WinMySQLadmin] user=Jonathan password=sql host=localhost ... Das letzte Element in der Gruppe muss ein NULL-Zeiger sein: > char *groups[] = { "client", "WinMySQLadmin", NULL }; Für den String conf_file wird in der Regel immer "my" verwendet. Bevor Sie jetzt die Funktion load_default() verwenden können, müssen Sie noch die Funktion my_init() aufrufen. Hier sehen Sie das Listing zu load_default(): > /* mysql2.c */ #include <stdio.h> #include <stdlib.h> #if defined __WIN32__ || _MSC_VER #include "my_global.h" #include "mysql.h" #else #include <mysql.h> #endif int main (int argc, char *argv[]) { int i; char *groups[] = { "client", "WinMySQLadmin", NULL }; my_init (); printf ("Ursprüngliche Argumente:\n"); for (i = 0; i < argc; i++) printf ("argv[%d] : %s\n", i, argv[i]); load_defaults ("my", (const char **)groups, &argc, &argv); printf ("Angepasste Argumente nach load_default():\n"); for (i = 0; i < argc; i++) printf ("argv[%d] : %s\n", i, argv[i]); return EXIT_SUCCESS; } Abbildung 24.8 Angepasste Argumente mit »load_default()« Wollen Sie die MySQL-Umgebungsvariablen MYSQL_TCP_PORT für die Portnummer und MSQL_UNIX_SOCKET für den Socket-Namen verwenden, können Sie dafür die Funktion getenv() aus der Headerdatei <stdlib.h> nutzen: > char *p; int port_num = 0; char *socket_name = NULL; if ((p = getenv ("MYSQL_TCP_PORT")) != NULL) port_num = atoi (p); if ((p = getenv ("MYSQL_UNIX_PORT")) != NULL) socket_name = p; ... if( mysql_real_connect ( my, /* Zeiger auf MYSQL-Handler */ NULL, /* Host-Name */ NULL, /* User-Name */ NULL, /* Passwort für user_name */ NULL, /* Name der Datenbank */ port_num, /* Port */ socket_name, /* Socket */ 0 /* keine Flags */ ) == NULL) ### 24.4.7 Anfrage an den Server Ich empfehle Ihnen jetzt eine nochmalige Wiederholung der SQL-Anweisungen, da Sie einige davon auf den nächsten Seiten mit der C-API wieder verwenden werden. Als Beispiel soll hier gezeigt werden, wie Sie auf eine bereits vorhandene Datenbank zugreifen können. Dabei dient die Datenbank dvd_archiv als Grundlage, die Sie im MySQL-Crashkurs erstellt haben. Falls Sie diese bereits gelöscht haben, erstellen Sie diese bitte nochmals. Hier sind die einzelnen Schritte dafür: > mysql> CREATE DATABASE dvd_archiv; mysql> USE dvd_archiv; mysql> CREATE TABLE filmdaten ( -> titel CHAR(255), hauptrolle CHAR(255), -> fsk TINYINT, gedreht YEAR); Zum Schluss dieses Kapitels werden Sie dazu ein etwas umfangreicheres Beispiel erstellen. Wie schon beim mysql-Client-Programm gibt es auch bei der C-API zwei Arten von Anfragen an den Server: * Das Client-Programm sendet eine Anfrage an den Server, wobei der Server nicht antwortet. * Das Client-Programm sendet eine Anfrage an den Server, und dieser gibt dem Client einen Rückgabewert. Wenn Sie wollen, können Sie sich dies wie bei den Funktionen vorstellen. Es gibt Funktionen mit einem Rückgabewert und Funktionen ohne einen Rückgabewert. Eine Anfrage an den Server können Sie mit der Funktion mysql_real_query() (bzw. auch mysql_query()) stellen. Jede Anfrage an den Server läuft folgendermaÃen ab: 1. | Sie erstellen eine SQL-Anfrage an den Server. | | --- | --- | 2. | Der Server erhält die Anfrage und überprüft diese auf syntaktische Fehler. | | --- | --- | 3. | Der Server führt die Anfrage aus und gibt das Resultat zurück. Ob ein Wert zurückgegeben wird, hängt von der Art der Anfrage ab. So gibt beispielsweise die Anfrage INSERT keinen Rückgabewert zurück, im Gegensatz zu einer Anfrage mit dem Kommando SELECT. | | --- | --- | Hier sehen Sie zuerst die Syntax der Funktion für das Stellen einer Anfrage: > int mysql_query(MYSQL *mysql, const char *anfrage); int mysql_real_query( MYSQL *mysql, const char *anfrage, unsigned long laenge ); Damit wird die SQL-Anweisung anfrage ausgeführt. Sie darf allerdings im Gegensatz zu der Anfrage, die Sie beim MySQL-Crashkurs kennengelernt haben, kein Semikolon oder \g am Ende haben. Bei dem String anfrage handelt es sich auÃerdem um einen nullterminierten String. Der Rückgabewert dieser Funktion lautet 0, wenn alles glatt verlief, ansonsten ist er ungleich 0. Wenn Sie mit der Funktion mysql_real_query() eine Anfrage an den Server stellen und Sie keine Antwort bekommen, könnte es an einem der folgenden Fehler liegen: * Der MySQL-Server ist gar nicht in Betrieb. Das klingt banal, kommt aber häufig vor. * Sie haben keine entsprechenden Zugriffsrechte, was unter Linux öfter der Fall ist. * Die Syntax der Anfrage ist falsch. * Die Anfrage ist ungültig. Beispielsweise wollen Sie den Inhalt einer Tabelle ausgeben, die gar nicht existiert. Jetzt folgt auf den nächsten Seiten das versprochene Programm, mit dem Sie auf die im Crashkurs erstellte Datenbank dvd_archiv zugreifen. Sofern Sie die Datenbank dvd_archiv bereits wieder gelöscht haben oder falls Sie ebenso wie der Autor zu den Personen gehören, die gerne kreuz und quer lesen, finden Sie hier nochmals die MySQL-Befehle (für den mysql-Client) um die entsprechende Datenbank mitsamt der Struktur anzulegen, die Sie für das folgende Listing benötigen: > CREATE DATABASE IF NOT EXISTS dvd_archiv; CREATE TABLE filmdaten ( titel CHAR(255), hauptrolle CHAR(255), fsk tinyint, gedreht YEAR ); Einen ersten Ãberblick, welche Funktionen auf den folgenden Seiten erstellt werden, können Sie den Angaben der Funktionsprototypen und der main()-Funktion des Programms entnehmen: ``` /* mysql3.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined __WIN32__ || _MSC_VER #include "my_global.h" #include "mysql.h" #else #include <mysql.h> #endif /* Wegen sehr vielen malloc()-Aufrufen im Listing * wurde hier zur Verkürzung des Listings ein Makro * geschrieben, das aber keine Schule machen soll!! */ #define malloc(size) \ malloc(size);\ if( (size) == NULL)\ {\ printf("Kein Speicher mehr ...\n");\ return;\ } /* Funktionsprototypen */ void check_error(void); void verbinden(void); void verbindung_schliessen(void); void db_waehlen(char *); void filmdaten_anfuegen(void); void filmdaten_loeschen(void); void filmdaten_aendern(void); void alle_daten_ausgeben(void); void schauspieler_suchen(char *); void print_line(MYSQL_RES *); MYSQL *mysql; /* Ab hier können Sie die einzelnen Funktionen der * kommenden Seiten einfügen. */ int main (int argc, char *argv[]) { int auswahl; char darsteller[255]; char *ptr; printf("Baue Verbindung zur Datenbank auf ...\n\n"); verbinden(); db_waehlen("dvd_archiv"); do { printf("\n-1- Filmdaten hinzufuegen\n"); printf("-2- Filmdaten loeschen\n"); printf("-3- Filmdaten aendern\n"); printf("-4- Alle Filmdaten ausgeben\n"); printf("-5- Film suchen\n"); printf("-6- Programm beenden\n\n"); printf("Ihre Auswahl : "); scanf("%d",&auswahl); getchar(); switch(auswahl) { case 1: filmdaten_anfuegen(); break; case 2: filmdaten_loeschen(); break; case 3: filmdaten_aendern(); break; case 4: alle_daten_ausgeben(); break; case 5: printf("Suchkriterium Schauspieler " "(Name eingeben): "); fgets(darsteller, 254, stdin); if((ptr=(char *)strchr(darsteller, '\n'))!= NULL) /* newline durch \0 ersetzen */ *ptr = '\0'; schauspieler_suchen(darsteller); break; case 6: printf("...beende Verbindung zur Datenbank\n"); break; default:printf("Falsche Eingabe\n\n"); } } while(auswahl != 6); verbindung_schliessen(); return EXIT_SUCCESS; } ``` Auf den ersten Blick sieht das Programm noch nicht wie ein MySQL-Client-Programm aus. Die API-Funktionen zum Verbinden mit dem Server, die Fehlerüberpüfung und das SchlieÃen einer Verbindung wurden aus der main()-Funktion entfernt und sind somit modular verfügbar. Hier sehen Sie die Funktionen verbinden(), check_error(), verbindung_schliessen() und db_waehlen(): > /* Bricht bei Fehler (mysql_error != 0) das Programm ab. */ void check_error(void) { if (mysql_errno(mysql) != 0) { fprintf(stderr, "Fehler: %s\n", mysql_error(mysql)); exit(EXIT_FAILURE); } } /* Baut eine Verbindung zum Datenbankserver auf. * Passen Sie ggf. Usernamen und Passwort und, sofern * andere Parameter benötigt werden, diese an Ihre * Bedürfnisse selbst an. */ void verbinden(void) { mysql=mysql_init(mysql); check_error(); mysql_real_connect(mysql, "localhost", "root", NULL, NULL, 0, NULL, 0); check_error(); } /* Serververbindung wieder schlieÃen und den Speicher für die * Struktur MYSQL wieder freigeben */ void verbindung_schliessen(void) { mysql_close(mysql); } /* Falls die Datenbank bei der Funktion verbinden() nicht * angegeben wurde oder Sie die Datenbank wechseln wollen, dann * verwenden Sie diese Funktion. */ void db_waehlen(char *db) { mysql_select_db(mysql, db); check_error(); } Die einzelnen Funktionen stellen bis auf die Funktion db_waehlen() nichts Neues mehr für Sie dar. In der Funktion db_waehlen() finden Sie die API-Funktion mysql_select_db(), die die folgende Syntax hat: > int mysql_select_db(MYSQL *mysql, const char *db); Mit dieser Funktion wechseln Sie in die Datenbank mit dem Namen db. Mit dem MYSQL-Handle mysql können Sie jetzt auf diese Datenbank mit weiteren Operationen zugreifen. Haben Sie keine Zugriffsrechte oder existiert diese Datenbank nicht, liefert sie einen Wert ungleich 0 zurück. Bei Erfolg hingegen ist der Rückgabewert 0. Diese Funktion entspricht also der SQL-Anweisung USE. Jetzt werden Sie eine einfache Anfrage an den Server stellen. Es sollen dabei mit der SQL-Anweisung INSERT neue Daten in die Datenbank eingefügt werden. Damit Sie jetzt nicht mehr so weit zurückblättern müssen, hier noch einmal das erforderliche SQL-Kommando: > INSERT INTO filmdaten (titel, hauptrolle, fsk, gedreht) VALUES (’<NAME>’, ’<NAME>’, 16, 2001); Die vollständige Funktion filmdaten_anfuegen(): > /* Daten mit mysql_real_query() in die Datenbank schreiben */ void filmdaten_anfuegen(void) { char titel[255], hauptrolle[255], temp[6]; unsigned int fsk, gedreht; int i, size=0; char *str[9], *query; char *ptr; printf("\n\nFilmtitel : "); fgets(titel, 254, stdin); if( (ptr = strchr(titel, '\n')) != NULL) *ptr = '\0'; /* newline durch \0 ersetzen */ printf("Hauptrolle : "); fgets(hauptrolle, 254, stdin); if( (ptr = strchr(hauptrolle, '\n')) != NULL) *ptr = '\0'; /* newline durch \0 ersetzen */ printf("FSK : "); fgets(temp, 4, stdin); if( (ptr = strchr(temp, '\n')) != NULL) *ptr = '\0'; /* newline durch \0 ersetzen */ sscanf(temp, "%u", &fsk); printf("Gedreht : "); fgets(temp, 5, stdin); if( (ptr = strchr(temp, '\n')) != NULL) *ptr = '\0'; /* newline durch \0 ersetzen */ sscanf(temp, "%u", &gedreht); /* jetzt wird der Anfragestring erstellt */ str[0]= "INSERT INTO filmdaten (titel, hauptrolle, fsk, " "gedreht) VALUES ('"; str[1] = malloc(strlen(titel)+1); strcpy(str[1], titel); str[2] = "','"; str[3] = malloc(strlen(hauptrolle)+1); strcpy(str[3], hauptrolle); str[4] = "',"; str[5] = malloc(3); sprintf(str[5], "%2u", fsk); str[6] = ","; str[7] = malloc(5); sprintf(str[7], "%4u", gedreht); str[8] = ")"; for (i=0; i < 9; i++) size+=strlen(str[i]); /* Speicherplatz für den Anfragestring reservieren */ query = malloc(size + 1); strcpy(query, str[0]); for(i = 1; i < 9; i++) strcat(query, str[i]); /* zum Testen für die Konsole */ /* printf("%s",query); */ /* jetzt die Anfrage an den Datenbankserver */ mysql_real_query(mysql, query, strlen(query)); check_error(); free(query); } Der GroÃteil dieser Funktion vollführt nichts anderes, als den Anfragestring für die Funktion mysql_real_query() dynamisch zu erstellen. Ich gehe hierbei davon aus, dass Sie mittlerweile gute Kenntnisse in C besitzen, sonst hätte es wohl kaum Sinn, sich mit dem Thema MySQL und C zu befassen. Wenn alles glatt verlief, befindet sich in der Datenbank dvd_archiv ein neuer Eintrag in der Tabelle filmdaten. Diese Funktion beachtet auch Einträge, bei denen Sie zum Beispiel keine Daten eingeben und einfach mit quittieren, damit dieses Feld leer bleibt. Als Nächstes soll die Funktion zum Löschen eines Datensatzes in der Tabelle filmdaten geschrieben werden: > void filmdaten_loeschen(void) { char del[255], temp[4]; char *item[]= {"titel", "hauptrolle", "fsk", "gedreht" }; char *ptr; char *str[5], *query='\0'; int auswahl, i, size=0; unsigned long affected; printf("Nach welchem Kriterium wollen Sie Daten loeschen\n"); printf("[1]=Titel [2]=Hauptrolle [3]=FSK " "[4]=Datum : [ ]\b\b"); fgets(temp, 3, stdin); if( (ptr = strchr(temp, '\n')) != NULL) *ptr = '\0'; /* newline durch \0 ersetzen */ sscanf(temp, "%d", &auswahl); str[0] = "DELETE FROM filmdaten WHERE "; if(auswahl > 0 && auswahl < 5) { str[1] = malloc(strlen(item[auswahl-1])+1); strcpy(str[1], item[auswahl-1]); } else { printf("Kein solches Kriterium vorhanden!!!\n\n"); return; } str[2] = " = '"; printf("Bitte angaben fuer \'%s\' machen: ", item[auswahl-1]); fgets(del, 254, stdin); if( (ptr = strchr(del, '\n')) != NULL) *ptr = '\0'; /* newline durch \0 ersetzen */ str[3] = malloc(strlen(del)+1); strcpy(str[3], del); str[4] = "'"; for (i=0; i < 5; i++) size+=strlen(str[i]); /* Speicherplatz für den Anfragestring reservieren */ query = malloc(size + 1); strcpy(query, str[0]); for(i = 1; i < 5; i++) strcat(query, str[i]); /* als Test für die Konsole */ /* printf("%s",query); */ /* jetzt die Anfrage an den Datenbankserver */ mysql_real_query(mysql, query, strlen(query)); check_error(); if((affected=(unsigned long)mysql_affected_rows(mysql))<= 0 ){ printf("Kein Datensatz von dieser Anfrage betroffen\n"); check_error(); } else printf("%ld %s von dieser Anfrage betroffen\n\n", affected, (affected == 1) ? "Datensatz war" : "Datensaetze waren" ); free(query); } Auch hier dient der Löwenanteil der Funktion dazu, den Anfragestring für die Funktion mysql_real_query() dynamisch zu erstellen. Neu in der Funktion filmdaten_loeschen ist die API-Funktion mysql_affected_rows(), die nach der Funktion mysql_real_query() aufgerufen wurde. Die Syntax dieser Funktion lautet: > my_ulonglong mysql_affected_rows(MYSQL *mysql); Diese Funktion gibt die Anzahl der Zeilen zurück, die von der letzten SQL-Anweisung wie DELETE, INSERT oder UPDATE betroffen war. Meistens wird diese Funktion unmittelbar nach einem Aufruf von mysql_real_query() verwendet. War kein Datensatz von der letzten Anfrage betroffen, liefert diese Funktion 0 zurück. Trat ein Fehler bei der Funktion auf, ist der Rückgabewert –1. Als Nächstes folgt die vollständige Funktion filmdaten_aendern(): > void filmdaten_aendern(void) { char change[255],replace[255], temp[4]; char *item[]= {"titel", "hauptrolle", "fsk", "gedreht" }; char *ptr; char *str[8], *query; int auswahl1, auswahl2, i, size=0; unsigned int integer; unsigned long affected; printf("Welche Daten wollen Sie aendern (Suchkriterium)\n"); printf("[1]=Titel [2]=Hauptrolle " "[3]=FSK [4]=Datum : [ ]\b\b"); fgets(temp, 3, stdin); if( (ptr = strchr(temp, '\n')) != NULL) *ptr = '\0'; /* newline durch \0 ersetzen */ sscanf(temp, "%1d", &auswahl1); printf("Welchen Inhalt suchen Sie fuer %s:", item[auswahl1-1]); fgets(change, 254, stdin); if( (ptr = strchr(change, '\n')) != NULL) *ptr = '\0'; /* newline durch \0 ersetzen */ printf("Welche Daten sollen ersetzt werden" " (Ersetzungskriterium)\n"); printf("[1]=Titel [2]=Hauptrolle " "[3]=FSK [4]=Datum : [ ]\b\b"); fgets(temp, 3, stdin); if( (ptr = strchr(temp, '\n')) != NULL) *ptr = '\0'; /* newline durch \0 ersetzen */ sscanf(temp, "%1d", &auswahl2); printf("Welchen Inhalt soll %s haben: ",item[auswahl2-1]); fgets(replace, 254, stdin); if( (ptr = strchr(replace, '\n')) != NULL) *ptr = '\0'; /* newline durch \0 ersetzen */ /* alle Daten vorhanden, um Querystr zu erzeugen */ str[0] = "UPDATE filmdaten SET "; if(auswahl2 > 0 && auswahl2 < 5) { str[1] = malloc(strlen(item[auswahl2-1])+1); strcpy(str[1], item[auswahl2-1]); } else { printf("Kein solches Kriterium vorhanden!!!\n\n"); return; } str[2] = "="; /* Integerwerte? */ if(auswahl2==3 || auswahl2==4) { sscanf(replace, "%u", &integer); str[3] = malloc(5); sprintf(str[3], "%4d", integer); } else { /* ... dann ist es ein str */ str[3] = malloc(strlen(replace)+3); strcpy(str[3], "'"); strcat(str[3], replace); strcat(str[3], "'"); } str[4] = " WHERE "; if(auswahl1 > 0 && auswahl1 < 5) { str[5] = malloc(strlen(item[auswahl1-1])+1); strcpy(str[5], item[auswahl1-1]); } else { printf("Kein solches Kriterium vorhanden!!!\n\n"); return; } str[6] = "="; /* Integerwerte? */ if(auswahl1==3 || auswahl1==4) { sscanf(change, "%u", &integer); str[7] = malloc(5); sprintf(str[7], "%4d", integer); } else { /* ... dann ist es ein str */ str[7] = malloc(strlen(change)+3); strcpy(str[7], "'"); strcat(str[7], change); strcat(str[7], "'"); } for (i=0; i < 8; i++) size+=strlen(str[i]); /* Speicherplatz für den Anfragestr reservieren */ query = malloc(size + 1); strcpy(query, str[0]); for(i = 1; i < 8; i++) strcat(query, str[i]); /* printf("%s",query); */ /* jetzt die Anfrage an den Datenbankserver */ mysql_real_query(mysql, query, strlen(query)); check_error(); if((affected=(unsigned long)mysql_affected_rows(mysql))<=0) { printf("Kein Datensatz von dieser Anfrage betroffen\n"); check_error(); } else printf("%ld %s von dieser Anfrage betroffen\n\n", affected, (affected == 1) ?"Datensatz war" : "Datensaetze waren"); free(query); } Der Ablauf der Funktion filmdaten_aendern() ähnelt dem der Funktion fimdaten_loeschen() zuvor, nur dass hier ein anderer Anfragestring (UPDATE) erstellt wird. Die Funktionen, mit denen Sie bisher eine Anfrage an den Server gestellt haben, haben noch keine Daten zurückgegeben. Aus dem MySQL-Crashkurs wissen Sie ja noch, dass Funktionen wie SELECT, EXPLAIN oder SHOW bewirken, dass etwas auf dem Bildschirm ausgegeben wird. Der Vorgang, Daten vom Server zu empfangen, wird ebenfalls mit der Funktion mysql_real_query() ausgelöst. Danach folgt ein Aufruf der API-Funktion mysql_store_result(), die alle angeforderten Daten vom Server in den Speicher des Client-Programms lädt. Hier sehen Sie die Syntax der Funktion: > MYSQL_RES *mysql_store_result(MYSQL *mysql); Alle angeforderten Daten befinden sich jetzt in der Struktur MYSQL_RES. Tritt beim Einlesen der Daten ein Fehler auf, wird NULL zurückgegeben. NULL wird allerdings auch bei SQL-Anweisungen wie INSERT, also Anweisungen ohne Rückgabewert, zurückgegeben. Ob also tatsächlich ein Fehler auftrat, müssen Sie mit mysql_errno() oder mysql_error() überprüfen. Nach dem Aufruf der Funktion mysql_store_results() befinden sich die Daten jetzt in der Struktur MYSQL_RES. Wollen Sie jetzt wissen, wie viele Zeilen sich in der Struktur MYSQL_RES befinden, können Sie folgende Funktion aufrufen: > my_ulonglong mysql_num_rows(MYSQL_RES *result); Die Funktion ist ähnlich wie mysql_affected_rows(). Auch hier empfiehlt sich aus Portabilitätsgründen ein unsigned long-Casting des Rückgabewerts. Diese Funktion ist natürlich optional und muss nicht unbedingt nach der Funktion mysql_store_result() aufgerufen werden. Dennoch erweist diese sich häufig als recht nützlich. Um die Daten aus der Struktur MYSQL_RES zu lesen, benötigen Sie eine Funktion, die das kann. Und das ist die Funktion mysql_fetch_row(): > MYSQL_ROW mysql_fetch_row(MYSQL_RES *result); Diese Funktion liest Zeile für Zeile aus der Struktur MYSQL_RES ein, bis ein NULL-Zeiger zurückgegeben wird; also ähnlich wie die Standardfunktion fgets(), nur nicht bis zum nächsten Newline, sondern bis zum nächsten Datensatz. NULL wird auch zurückgegeben, wenn ein Fehler aufgetreten ist. MYSQL_ROW präsentiert eine Zeile von Daten, die als array-gezählte Byte-Zeichenkette implementiert ist. Wollen Sie jetzt wissen, wie viele Spalten der aktuelle Datensatz in der Struktur MYSQL_RES hat, dann müssen Sie die Funktion mysql_num_fields() verwenden: > unsigned int mysql_num_fields(MYSQL_RES *results); Wenn Sie mit den Daten der Struktur MYSQL_RES fertig sind, dann sollten Sie den Speicher wieder freigeben, um Memory Leaks zu vermeiden. Die Syntax dazu lautet: > void mysql_free_result(MYSQL_RES *result); Zugegeben, das war jetzt ein ziemlicher Brocken, der Ihnen hier vor die FüÃe geschmissen wurde. Daher folgt nochmals eine kurze Zusammenfassung, wie Sie die Anfrage vom Server abholen und bearbeiten können: * Anfrage an den Server (mysql_real_query) * Daten der Anfrage abholen (mysql_store_result) * Anzahl der Zeilen ermitteln, die abgeholt wurden (mysql_num_rows) * Zeilenweises Einlesen der Daten (mysql_fetch_row) * Anzahl der Spalten der aktuellen Zeile ermitteln (mysql_num_fields) * Speicherplatz wieder freigeben (mysql_free_result) Hierzu folgt jetzt die Funktion schauspieler_suchen(), die alle diese Funktionen demonstriert. > void schauspieler_suchen(char *name) { unsigned long anzahl_reihen; unsigned int i; MYSQL_ROW row; MYSQL_RES *mysql_res; char *query, *string; char *select = "SELECT * FROM filmdaten WHERE hauptrolle='"; string = malloc(strlen(name)+2); strcpy(string,name); strcat(string, "'"); query = malloc(strlen(select)+strlen(string)+1); strcpy(query, select); strcat(query, string); /* jetzt die Anfrage an den Datenbankserver */ mysql_real_query(mysql, query, strlen(query)); check_error(); /* Daten der Anfrage abholen */ mysql_res = mysql_store_result(mysql); check_error(); /* Anzahl der gefundenen Datensätze ermitteln */ anzahl_reihen = (unsigned long) mysql_num_rows (mysql_res); printf ("Anzahl gefunden: %lu\n\n", anzahl_reihen); /* gefundenen Datensatz bzw. Datensätze ausgeben */ while ((row = mysql_fetch_row (mysql_res)) != NULL) { /* Einzelne Spalten der Zeile ausgeben */ for (i = 0; i < mysql_num_fields(mysql_res); i ++) printf ("%s ",row[i]); printf("\n"); } /* Speicherplatz wieder freigeben */ mysql_free_result(mysql_res); free(string); free(query); } In dieser Funktion wird in der Datenbank nach Filmen eines bestimmten Schauspielers gesucht, und diese werden dann ausgegeben. Zuvor wird wieder der Anfragestring erstellt. Um jetzt die Feldwerte eines einzelnen Feldes zu ermitteln, verwenden Sie die Funktion mysql_fetch_field(), die die folgende Syntax besitzt: > MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *results); Die Informationen des Feldes werden in der Struktur MYSQL_FIELD gespeichert. Tabelle 24.10 bietet einen kurzen Ãberblick darüber, welche Daten Sie aus dieser Struktur entnehmen können. Die folgenden zwei Funktionen alle_daten_ausgeben() und print_line() sollen jetzt noch die Funktion mysql_fetch_field() veranschaulichen: > void alle_daten_ausgeben(void) { unsigned int i, col_len; MYSQL_ROW row; MYSQL_RES *res; MYSQL_FIELD *field; /* jetzt die Anfrage an den Datenbankserver */ mysql_real_query(mysql, "SELECT * FROM filmdaten", strlen("SELECT * FROM filmdaten")); check_error(); /* Anfrage vom Server in die Struktur MYSQL_RES laden */ res = mysql_store_result(mysql); check_error(); /* offset = 0 bedeutet: auf den Anfang der Zeile setzen */ mysql_field_seek (res, 0); /* Damit bei der Ausgabe ein einheitliches Bild entsteht, * sollen die Daten für die maximale Länge einer Spalte * bei jeder einzelnen (MYSQL_FIELD)-Spalte verändert werden. */ for (i = 0; i < mysql_num_fields(res); i++) { field = mysql_fetch_field (res); /* Länge des Namens in der Spalte ermitteln */ col_len = strlen (field->name); /* Ist die Länge des Elements in der Spalte kleiner als die maximale Länge ... */ if (col_len < field->max_length) /* ... dann bekommt col_len den Wert der maximal erlaubten Länge der Spalte. */ col_len = field->max_length; /* Für den Fall, dass eine Spalte keine Daten beinhaltet ... */ if (col_len < 4 && !IS_NOT_NULL (field->flags)) /* ... bekommt col_len den Wert 4 für den String "NULL" ->keine Daten. */ col_len = 4; /* maximale Länge von Spalten-Info verändern */ field->max_length = col_len; } /* Namen der Tabelle ausgeben */ printf("Daten der Tabelle: [ %s ]\n", field->table); print_line(res); printf("|"); /* alles wieder auf den Anfang stellen */ mysql_field_seek (res, 0); /* jetzt den Tabellenkopf ausgeben (titel, hauptrolle, fsk, * gedreht) */ for (i = 0; i < mysql_num_fields (res); i++) { field = mysql_fetch_field (res); printf (" %-*s |", field->max_length, field->name); } printf("\n"); print_line(res); /* jetzt die Daten aus der Struktur MYSQL_RES zeilenweise * einlesen */ while ((row = mysql_fetch_row (res)) != NULL) { mysql_field_seek (res, 0); printf("|"); for (i = 0; i < mysql_num_fields (res); i++) { /* Spalte für Spalte abarbeiten */ field = mysql_fetch_field (res); /* keine Daten in dieser Spalte */ if (row[i] == NULL) printf (" %-*s |", field->max_length, "NULL"); /* Handelt es sich um ein numerisches Feld? */ else if (IS_NUM (field->type)) /* Dann wird der Inhalt rechtsbündig formatiert * ausgegeben. */ printf (" %*s |", field->max_length, row[i]); else /* Der Wert der Spalte ist ein String, also * linksbündige Ausgabe. */ printf (" %-*s |", field->max_length, row[i]); } printf("\n"); } print_line(res); mysql_free_result(res); } void print_line(MYSQL_RES *res) { MYSQL_FIELD *field; unsigned int i, j; mysql_field_seek (res, 0); /* erstes Zeichen der Linie */ printf("+"); for (i = 0; i < mysql_num_fields(res); i++) { field = mysql_fetch_field(res); /* max_length '-' Zeichen jeder Spalte ausgeben */ for (j = 0; j < field->max_length + 2; j++) printf("-"); /* am Ende der Spalte '+' ausgeben */ printf("+"); } printf("\n"); } Mit diesen beiden Funktionen werden alle Daten der Tabelle filmdaten sauber in Tabellenform auf dem Bildschirm ausgegeben. Zusätzlich wurde hier die Funktion mysql_field_seek() verwendet, womit der Feldcursor auf das angegebene Offset gesetzt wird. Da hier als Offset 0 angegeben wurde, wird immer bis zum Anfang einer Zeile gesucht. Die Funktion mysql_fetch_field(), die danach aufgerufen wird, ruft die Felddefinition der Spalte ab, die mit dem Offset MYSQL_FIELD_OFFSET verknüpft ist. Wollen Sie beispielsweise an eine Position des letzten mysql_fetch_field() zurückspringen, können Sie sich eine Position mit der Funktion mysql_field_tell() merken und den Rückgabewert dieser Funktion als Offset an die Funktion mysql_field_seek() übergeben. # 24.5 MySQL und C mit CGI ## 24.5 MySQL und C mit CGI Zum Abschluss soll wie versprochen ein Beispiel erstellt werden, bei dem Sie mithilfe eines CGI-Webformulars eine Datenbank mit E-Mail-Adressen füttern. Auf diese Weise erstellen Sie quasi eine grafische Oberfläche zum Bedienen einer Datenbank mithilfe des Webbrowsers. Erzeugen Sie eine neue Datenbank mit dem Namen mail_archiv. Geben Sie dazu im mysql-Client Folgendes ein: > CREATE DATABASE mail_archiv; Wechseln Sie mit USE in diese Datenbank, und erstellen Sie eine Tabelle mit folgendem SQL-Kommando: > CREATE TABLE daten (adresse CHAR(255), name CHAR(255)); ### 24.5.1 HTML-Eingabeformular Als Nächstes sollten Sie die HTML-Datei erstellen, mit der Sie die Daten eingeben können. Die Datei sieht wie folgt aus: > <html> <head> <title>Datenbank</title> </head> <body text="#000000" bgcolor="#FFFFFF" link="#FF0000" alink="#FF0000" vlink="#FF0000"> <h3>Datenbank (E-Mail-Adressen)</h3> <hr><br> <form action="http://localhost/cgi-bin/add_db.cgi" method=post> Neuen Datensatz hinzufügen: <pre>Name : <input value="IhrName" name="Name" size="20"> E-Mail : <input value="adr@mail" name="E-Mail" size="20"></pre> <input type=submit value="Hinzufügen"> </form> <hr><br> <form action=http://localhost/cgi-bin/search_db.cgi method=post> In der Datenbank suchen: <pre>Name : <input value="IhrName" name="Name" size="20"></pre> <input type=submit value="Suchen"> </form> <hr> </body> </htmlBei diesem HTML-Formular können zwei CGI-Anwendungen gestartet werden: zum einen das Einfügen neuer Daten in die Datenbank (add_db.cgi) und zum anderen das Suchen darin (search_db.cgi). Abbildung 24.9 HTML-Formular zur Eingabe oder Suche von Datensätzen ### 24.5.2 Die CGI-Anwendung »add_db.cgi« Zuerst wird die CGI-Anwendung zum Hinzufügen neuer Datensätze in die Datenbank geschrieben. Dabei finden Sie wieder altbekannte Funktionen aus den Abschnitten zu CGI und C. Ich habe mich entschlossen, das Listing hier vollständig wiederzugeben, da ich es auch nicht mag, ständig in einem Buch hin- und her zu blättern. > /* add_db.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined __WIN32__ || _MSC_VER #include "my_global.h" #include "mysql.h" #else #include <mysql.h> #endif #define MAX_PAARE 255 #define BUF 255 struct CGI_DATEN { char *variable; char *wert; struct CGI_DATEN *next; }; struct CGI_DATEN *ende = NULL; MYSQL *mysql; void print_html(void); char *getdata(void); char *Strdup(const char *); void hex2ascii(char *); char convert(char *); void loeschen(struct CGI_DATEN *); struct CGI_DATEN *erstellen(char *); void check_error(void); void verbinden(void); void verbindung_schliessen(void); /* Weiterleitung zu einer URL; * url ist die URL, an die Sie den User weiterleiten. */ void print_html(void) { printf("<html><head>\n"); printf("<title>Eintragsbestätigung</title>\n"); printf("</head><body>\n"); printf("Eintragung erfolgreich. Zurück gehts" " <a href=\"javascript:history.back()\">hier</a>"); printf("</body></html>\n"); } /* Die Funktion liest Daten mit der POST oder GET-Methode ein. * Rückgabewert: Stringpuffer mit den Daten * bei Fehler : NULL */ char *getdata(void) { unsigned long size; char *puffer = NULL; char *request = getenv("REQUEST_METHOD"); char *cont_len; char *cgi_string; /* zuerst die Request-Methode überprüfen */ if( NULL == request ) return NULL; else if( strcmp(request, "GET") == 0 ) { /* die Methode GET -> Query-String abholen */ cgi_string = getenv("QUERY_STRING"); if( NULL == cgi_string ) return NULL; else { puffer = Strdup(cgi_string); return puffer; /* Rückgabewert an den Aufrufer */ } } else if( strcmp(request, "POST") == 0 ) { /* die Methode POST -> Länge des Strings * ermitteln (CONTENT_LENGTH) */ cont_len = getenv("CONTENT_LENGTH"); if( NULL == cont_len) return NULL; else { /* String CONTENT_LENGTH in * unsigned long umwandeln */ size = (unsigned long) atoi(cont_len); if(size <= 0) return NULL; /* Keine Eingabe?! */ } /* Jetzt lesen wir die Daten von stdin ein. */ puffer = malloc(size+1); if( NULL == puffer ) return NULL; else { if( NULL == fgets(puffer, size+1, stdin) ) { free(puffer); return NULL; } else /* Rückgabewerte an den Aufrufer */ return puffer; } } /* Weder die GET-Methode noch die POST-Methode wurden verwendet. */ else return NULL; } /* Da die Funktion strdup() in der Headerdatei <string.h> keine * ANSI-C-Funktion ist, schreiben wir eine eigene. */ char *Strdup(const char *str) { char *p; if(NULL == str) return NULL; else { p = malloc(strlen(str)+1); if(NULL == p) return NULL; else strcpy(p, str); } return p; } /* Wandelt einzelne Hexzeichen (%xx) in ASCII-Zeichen * und kodierte Leerzeichen (+) in echte Leerzeichen um. */ void hex2ascii(char *str) { int x, y; for(x=0,y=0; str[y] != '\0'; ++x,++y) { str[x] = str[y]; /* Ein hexadezimales Zeichen ? */ if(str[x] == '%') { str[x] = convert(&str[y+1]); y += 2; } /* Ein Leerzeichen ? */ else if( str[x] == '+') str[x]=' '; } /* geparsten String sauber terminieren */ str[x] = '\0'; } /* Funktion konvertiert einen String von zwei hexadezimalen * Zeichen und gibt das einzelne dafür stehende Zeichen zurück. */ char convert(char *hex) { char ascii; /* erster Hexawert */ ascii = (hex[0] >= 'A' ? ((hex[0] & 0xdf) - 'A')+10 : (hex[0] - '0')); ascii <<= 4; /* Bitverschiebung schneller als ascii*=16 */ /* zweiter Hexawert */ ascii += (hex[1] >= 'A' ? ((hex[1] & 0xdf) - 'A')+10 : (hex[1] - '0')); return ascii; } /* Liste aus Variable/Wert-Paaren erstellen * Rückgabewert: Anfangsadresse der Liste * Bei Fehler: NULL */ struct CGI_DATEN *erstellen(char *str) { char* s; char* res; /* Irgendwo gibt es auch eine Grenze, hier sind MAX_PAARE erlaubt. */ char *paare[MAX_PAARE]; struct CGI_DATEN *ptr_daten = NULL; struct CGI_DATEN *ptr_anfang = NULL; int i=0, j=0; /* Zuerst werden die Variablen/Werte-Paare anhand des Zeichens * '&' getrennt, sofern es mehrere sind. */ s=str; res=strtok(s,"&"); while( res != NULL && i < MAX_PAARE) { /* Wert von res dynamisch in char **pair speichern */ paare[i] = (char *)malloc(strlen(res)+1); if(paare[i] == NULL) return NULL; paare[i] = res; res=strtok(NULL,"&"); i++; } /* Jetzt werden die Variablen von den Werten getrennt und * an die Struktur CGI_DATEN übergeben. */ while ( i > j ) { /* Das erste Element ? */ if(ptr_anfang == NULL) { ptr_anfang =malloc(sizeof (struct CGI_DATEN)); if( ptr_anfang == NULL ) return NULL; res = strtok( paare[j], "="); if(res == NULL) return NULL; ptr_anfang->variable = malloc(strlen(res)+1); if( ptr_anfang->variable == NULL ) return NULL; ptr_anfang->variable = res; res = strtok(NULL, "\0"); if(res == NULL) return NULL; ptr_anfang->wert = malloc(strlen(res)+1); if( ptr_anfang->wert == NULL ) return NULL; ptr_anfang->wert = res; /* printf("%s %s<br>", * ptr_anfang->variable, ptr_anfang->wert); */ ptr_anfang->next = malloc(sizeof (struct CGI_DATEN)); if(ptr_anfang->next == NULL) return NULL; ptr_daten = ptr_anfang->next; j++; } else { /* die restlichen Elemente */ res = strtok( paare[j], "="); if(res == NULL) return NULL; ptr_daten->variable = malloc(strlen(res)+1); if(ptr_daten->variable == NULL) return NULL; ptr_daten->variable = res; res = strtok(NULL, "\0"); if(res == NULL) return NULL; ptr_daten->wert = malloc(strlen(res)+1); if(ptr_daten->wert == NULL) return NULL; ptr_daten->wert = res; /* printf("%s %s<br>", * ptr_daten->variable, ptr_daten->wert); */ ptr_daten->next = malloc(sizeof (struct CGI_DATEN)); if( ptr_daten->next == NULL ) return NULL; ptr_daten = ptr_daten->next; j++; } } ende = ptr_daten; /* Anfangsadresse der Liste struct CGI_DATEN zurückgeben */ return ptr_anfang; } /* Bricht bei Fehler (mysql_error != 0) das Programm ab. */ void check_error(void) { if (mysql_errno(mysql) != 0) { fprintf(stderr, "Fehler: %s\n", mysql_error(mysql)); exit(EXIT_FAILURE); } } /* Baut eine Verbindung zum Datenbankserver auf. * Passen Sie ggf. Usernamen und Passwort und, sofern * andere Parameter benötigt werden, diese selbst an Ihre * Bedürfnisse an. */ void verbinden(void) { mysql= mysql_init(mysql); check_error(); mysql_real_connect(mysql, "localhost", "root", NULL, NULL, 0, NULL, 0); check_error(); } /* Serververbindung wieder schlieÃen und den Speicher für die * Struktur MYSQL wieder freigeben */ void verbindung_schliessen(void) { mysql_close(mysql); } /* Falls die Datenbank bei der Funktion verbinden() nicht angegeben * wurde oder Sie die Datenbank wechseln wollen, dann verwenden * Sie diese Funktion. */ void db_waehlen(char *db) { mysql_select_db(mysql, db); check_error(); } /* Daten mit mysql_real_query() in die Datenbank schreiben */ void daten_anfuegen(struct CGI_DATEN *daten) { char buf[BUF] = "INSERT INTO daten (name, adresse) VALUES ('"; strcat(buf, daten->wert); strcat(buf, "', '"); daten = daten->next; strcat(buf, daten->wert); strcat(buf, "');"); /* Jetzt die Anfrage an den Datenbankserver */ mysql_real_query(mysql, buf, strlen(buf)); check_error(); } int main(void) { char *str; struct CGI_DATEN *cgi; struct CGI_DATEN *free_cgi; /* für Fehlermeldungen */ printf("Content-Type: text/html\n\n"); /* Eingabe einlesen */ str = getdata(); if(str == NULL) { printf("Fehler beim Einlesen von der Formulareingabe"); return EXIT_FAILURE; } /* Hexzeichen in ASCII-Zeichen konvertieren und aus '+' * Leerzeichen machen */ hex2ascii(str); /* Liste der Formualar-Daten erstellen */ cgi = erstellen(str); free_cgi = cgi; if (cgi == NULL) { printf("Fehler beim Erstellen der " "Variablen/Werte-Liste!!\n"); return EXIT_FAILURE; } verbinden(); db_waehlen("mail_archiv"); daten_anfuegen(cgi); verbindung_schliessen(); print_html(); return EXIT_SUCCESS; } Ãbersetzen Sie den Quellcode wieder wie gewohnt, ändern Sie die Extension (*.cgi), und speichern Sie die ausführbare Datei im cgi-bin-Verzeichnis des (Apache-)Webservers. Unter Linux werden dafür teilweise root-Rechte benötigt. Ãndern Sie auÃerdem unter Linux die Zugriffsrechte für diese Datei (chmod go+rx add_db.cgi). Weiteres finden Sie in Kapitel 23, »CGI mit C«, das Sie bereits durchgenommen haben sollten, bevor Sie sich an dieses Programm wagen. ### 24.5.3 Die CGI-Anwendung »search_db.cgi« Als Nächstes folgt die CGI-Anwendung zur Suche in der Datenbank mail_archiv, die im GroÃen und Ganzen ebenfalls nichts mehr enthält, was nicht bereits besprochen wurde. > /* search_db.c */ #include <stdio.h> #include <stdlib.h> #if defined __WIN32__ || _MSC_VER #include "my_global.h" #include "mysql.h" #else #include <mysql.h> #endif #define MAX_PAARE 255 #define BUF 255 struct CGI_DATEN { char *variable; char *wert; struct CGI_DATEN *next; }; struct CGI_DATEN *ende = NULL; MYSQL *mysql; void print_html(void); char *getdata(void); char *Strdup(const char *); void hex2ascii(char *); char convert(char *); void loeschen(struct CGI_DATEN *); struct CGI_DATEN *erstellen(char *); void check_error(void); void verbinden(void); void verbindung_schliessen(void); /* Weiterleitung zu einer URL; * url ist die URL, an die Sie den User weiterleiten. */ void print_html(void) { printf("<html><head>\n"); printf("<title>Suchergebniss</title>\n"); printf("</head><body>\n"); printf("<br><br>Zurück gehts " "<a href=\"javascript:history.back()\">hier</a>"); printf("</body></html>\n"); } /* Die Funktion liest Daten mit der POST oder GET-Methode ein. * Rückgabewert: Stringpuffer mit den Daten * bei Fehler : NULL */ char *getdata(void) { unsigned long size; char *puffer = NULL; char *request = getenv("REQUEST_METHOD"); char *cont_len; char *cgi_string; /* zuerst die Request-Methode überprüfen */ if( NULL == request ) return NULL; else if( strcmp(request, "GET") == 0 ) { /* die Methode GET -> Query-String abholen */ cgi_string = getenv("QUERY_STRING"); if( NULL == cgi_string ) return NULL; else { puffer = Strdup(cgi_string); return puffer; /* Rückgabewert an den Aufrufer */ } } else if( strcmp(request, "POST") == 0 ) { /* Die Methode POST -> Länge des Strings * ermitteln (CONTENT_LENGTH) */ cont_len = getenv("CONTENT_LENGTH"); if( NULL == cont_len) return NULL; /* String CONTENT_LENGTH in unsigned long umwandeln */ else { size = (unsigned long) atoi(cont_len); if(size <= 0) return NULL; /* Keine Eingabe!?!? */ } /* jetzt lesen wir die Daten von stdin ein */ puffer = malloc(size+1); if( NULL == puffer ) return NULL; else { if( NULL == fgets(puffer, size+1, stdin) ) { free(puffer); return NULL; } else /* Rückgabewerte an den Aufrufer */ return puffer; } } /* Weder die GET-Methode noch die POST-Methode wurden verwendet. */ else return NULL; } /* Da die Funktion strdup() in der Headerdatei <string.h> keine * ANSI-C-Funktion ist, schreiben wir eine eigene. */ char *Strdup(const char *str) { char *p; if(NULL == str) return NULL; else { p = malloc(strlen(str)+1); if(NULL == p) return NULL; else strcpy(p, str); } return p; } /* Wandelt einzelne Hexzeichen (%xx) in ASCII-Zeichen und kodierte Leerzeichen (+) in echte Leerzeichen um. */ void hex2ascii(char *str) { int x, y; for(x=0,y=0; str[y] != '\0'; ++x,++y) { str[x] = str[y]; /* Ein hexadezimales Zeichen? */ if(str[x] == '%') { str[x] = convert(&str[y+1]); y += 2; } /* Ein Leerzeichen ? */ else if( str[x] == '+') str[x]=' '; } /* geparsten String sauber terminieren */ str[x] = '\0'; } /* Die Funktion konvertiert einen String von zwei hexadezimalen * Zeichen und gibt das einzelne dafür stehende Zeichen zurück. */ char convert(char *hex) { char ascii; /* erster Hexawert */ ascii = (hex[0] >= 'A' ? ((hex[0] & 0xdf) - 'A')+10 : (hex[0] - '0')); ascii <<= 4; /* Bitverschiebung schneller als ascii*=16 */ /* zweiter Hexawert */ ascii += (hex[1] >= 'A' ? ((hex[1] & 0xdf) - 'A')+10 : (hex[1] - '0')); return ascii; } /* Liste aus Variable/Wert-Paaren erstellen * Rückgabewert: Anfangsadresse der Liste * Bei Fehler: NULL */ struct CGI_DATEN *erstellen(char *str) { char* s; char* res; /* Irgendwo gibt es auch eine Grenze, hier sind MAX_PAARE erlaubt. */ char *paare[MAX_PAARE]; struct CGI_DATEN *ptr_daten = NULL; struct CGI_DATEN *ptr_anfang = NULL; int i=0, j=0; /* Zuerst werden die Variablen/Werte-Paare anhand des Zeichens * '&' getrennt, sofern es mehrere sind. */ s=str; res=strtok(s,"&"); while( res != NULL && i < MAX_PAARE) { /* Wert von res dynamisch in char **pair speichern */ paare[i] = malloc(strlen(res)+1); if(paare[i] == NULL) return NULL; paare[i] = res; res=strtok(NULL,"&"); i++; } /* Jetzt werden die Variablen von den Werten getrennt und * an die Struktur CGI_DATEN übergeben. */ while ( i > j ) { /* Das erste Element? */ if(ptr_anfang == NULL) { ptr_anfang = malloc (sizeof (struct CGI_DATEN)); if( ptr_anfang == NULL ) return NULL; res = strtok( paare[j], "="); if(res == NULL) return NULL; ptr_anfang->variable = malloc(strlen(res)+1); if( ptr_anfang->variable == NULL ) return NULL; ptr_anfang->variable = res; res = strtok(NULL, "\0"); if(res == NULL) return NULL; ptr_anfang->wert = malloc(strlen(res)+1); if( ptr_anfang->wert == NULL ) return NULL; ptr_anfang->wert = res; /* printf("%s %s<br>", * ptr_anfang->variable, ptr_anfang->wert); */ ptr_anfang->next = malloc(sizeof (struct CGI_DATEN)); if(ptr_anfang->next == NULL) return NULL; ptr_daten = ptr_anfang->next; j++; } else { /* die restlichen Elemente */ res = strtok( paare[j], "="); if(res == NULL) return NULL; ptr_daten->variable = malloc(strlen(res)+1); if(ptr_daten->variable == NULL) return NULL; ptr_daten->variable = res; res = strtok(NULL, "\0"); if(res == NULL) return NULL; ptr_daten->wert = malloc(strlen(res)+1); if(ptr_daten->wert == NULL) return NULL; ptr_daten->wert = res; /* printf("%s %s<br>", * ptr_daten->variable, ptr_daten->wert); */ ptr_daten->next = malloc(sizeof (struct CGI_DATEN)); if( ptr_daten->next == NULL ) return NULL; ptr_daten = ptr_daten->next; j++; } } ende = ptr_daten; /* Anfangsadresse der Liste struct CGI_DATEN zurückgeben */ return ptr_anfang; } /* Bricht bei Fehler (mysql_error != 0) das Programm ab. */ void check_error(void) { if (mysql_errno(mysql) != 0) { fprintf(stderr, "Fehler: %s\n", mysql_error(mysql)); exit(EXIT_FAILURE); } } /* Baut eine Verbindung zum Datenbankserver auf. * Passen Sie ggf. Usernamen und Passwort und, sofern * andere Parameter benötigt werden, diese selbst an * Ihre Bedürfnisse an. */ void verbinden(void) { mysql= mysql_init(mysql); check_error(); mysql_real_connect(mysql, "localhost", "root", NULL, NULL, 0, NULL, 0); check_error(); } /* Serververbindung wieder schlieÃen und den Speicher für die * Struktur MYSQL wieder freigeben */ void verbindung_schliessen(void) { mysql_close(mysql); } /* Falls die Datenbank bei der Funktion verbinden() nicht * angegeben wurde oder Sie die Datenbank wechseln wollen, * dann verwenden Sie diese Funktion. */ void db_waehlen(char *db) { mysql_select_db(mysql, db); check_error(); } /* Daten mit mysql_real_query() in die Datenbank schreiben */ void daten_suchen(struct CGI_DATEN *daten) { MYSQL_ROW row; MYSQL_RES *mysql_res; unsigned long anzahl_reihen; unsigned int i; char buf[BUF] = "SELECT adresse FROM daten WHERE name='"; strcat(buf, daten->wert); strcat(buf, "';"); mysql_real_query(mysql, buf, strlen(buf)); check_error(); /* Daten der Anfrage abholen */ mysql_res = mysql_store_result(mysql); check_error(); /* Anzahl der gefundenen Datensätze ermitteln */ anzahl_reihen = (unsigned long) mysql_num_rows (mysql_res); printf ("Anzahl gefunden: %lu\n\n<br><br>", anzahl_reihen); /* gefundenen Datensatz bzw. Datensätze ausgeben */ while ((row = mysql_fetch_row (mysql_res)) != NULL) { /* einzelne Spalten der Zeile ausgeben */ for (i = 0; i < mysql_num_fields(mysql_res); i ++) printf ("Adresse zu %s lautet %s<br> ", daten->wert,row[i]); printf("\n"); } /* Speicherplatz wieder freigeben */ mysql_free_result(mysql_res); } int main(void) { char *str; struct CGI_DATEN *cgi; struct CGI_DATEN *free_cgi; /* für Fehlermeldungen */ printf("Content-Type: text/html\n\n"); /* Eingabe einlesen */ str = getdata(); if(str == NULL) { printf("Fehler beim Einlesen von der Formulareingabe"); return EXIT_FAILURE; } /* Hexzeichen in ASCII-Zeichen konvertieren und aus '+' * Leerzeichen machen */ hex2ascii(str); /* Liste der Formualar-Daten erstellen */ cgi = erstellen(str); free_cgi = cgi; if (cgi == NULL) { printf("Fehler beim Erstellen der " "Variablen/Werte-Liste!!\n"); return EXIT_FAILURE; } verbinden(); db_waehlen("mail_archiv"); daten_suchen(cgi); verbindung_schliessen(); print_html(); return EXIT_FAILURE; } Natürlich gilt auch hier: Ãbersetzen Sie den Quellcode wie gewohnt, ändern Sie die Extension (*.cgi), und speichern Sie die ausführbare Datei im cgi-bin-Verzeichnis des (Apache-)Webservers. Unter Linux werden dafür teilweise root-Rechte benötigt. Ãndern Sie auÃerdem unter Linux die Zugriffsrechte für diese Datei (chmod go+rx search_db.cgi). Das war es. Wenn Sie jetzt wollen, können Sie die CGI-Anwendungen mit MySQL in der Praxis testen. Ãffnen Sie dazu mit Ihrem Webrowser das erstellte HTML-Formular. Jetzt können Sie munter Datensätze in die Datenbank einfügen oder in den Datensätzen suchen. Die Voraussetzung dafür, dass dies auch funktioniert, ist, dass der (Apache-)Webserver und der Datenbankserver MySQL gestartet wurden. Mit diesem Beispiel haben Sie jetzt die Grundlagen für komplexere Aufgaben mit der MySQL-Datenbank geschaffen. # 24.6 Funktionsübersicht ## 24.6 Funktionsübersicht Zum Abschluss dieses Kapitels fasst Tabelle 24.11 nochmals die wichtigsten Funktionen der MySQL-C-API für Referenzzwecke zusammen. # 24.7 Datentypenübersicht der C-API ## 24.7 Datentypenübersicht der C-API Auch zu den eigenen Datentypen von MySQL und der C-API folgt hier ein kurzer Ãberblick. Datentyp | Bedeutung | | --- | --- | | | | | | | | | | | | | # 25.2 Headerdateien zur Socketprogrammierung ## 25.2 Headerdateien zur Socketprogrammierung Zur Erstellung von Netzwerkanwendungen mit Sockets sind auf den Systemen verschiedene Headerdateien und unter MS-Windows auch eine bestimmte Bibliothek nötig. ### 25.2.1 Linux/UNIX Die Headerdateien für Linux/UNIX und auch für die BSD-Varianten lauten: > #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h### 25.2.2 Windows Unter MS-Windows sollte es ausreichen, die folgende Headerdatei zu inkludieren: > #include <winsock.hEventuell kann es auch nötig sein, die Headerdatei <windows.h> einzubinden – sofern Ihr Compiler eine seltsame Warn- bzw. Fehlermeldung ausgibt. Alternativ zu <winsock.h> können Sie hier auch die neuere <winsock2.h> inkludieren, was allerdings für die Beispiele im Buch nicht unbedingt nötig ist. # Bibliotheken Unter MS-Windows wird wie gesagt noch die Winsock- bzw. Winsock2-Bibliothek benötigt. Hierfür sind leider bei den verschiedensten Compilern unterschiedliche Bibliotheksnamen angegeben. Mir bekannte Namen unter Microsoft Visual C++ sind beispielsweise WSOCK32.LIB (für winsock) und WS2_32.LIB (für Winsock2). Bei einigen anderen Compilern heiÃen sie aber WINSOCK32.LIB und WINSOCK2_32.LIB. Bei der kostenlosen Entwicklungsumgebung Code::Blocks, die z. B. den MinGW-Compiler verwendet, lautet der Bibliotheksname LIBWSOCK32.a (Winsock) oder LIBWS2_32.a (Winsock2). Dabei müssen Sie bei Ihrem neuen Projekt lediglich eine der beiden Bibliotheken dem Linker mitteilen, indem Sie im lib-Verzeichnis des entsprechenden Compilers die entsprechende Bibliothek wählen. Wie dies mit den Entwicklungsumgebungen Visual C++ Express Edition 2008 und Code::Blocks genau funktioniert, können Sie in der Anleitung auf der Buch-CD nachlesen. # Die Windows-Programmierung und die (C-)Syntax Bevor es mit dem Thema weitergeht, will ich noch ein paar Worte zur Syntax der Windows-Programmierung sagen. Sofern Sie noch nichts damit zu tun gehabt haben, wird es wohl eine Weile dauern, bis Sie sich an die Windows-typische C-Schreibweise gewöhnt haben. Auf den ersten Blick erscheint einem alles ein wenig fremd. Beispielsweise wird anstelle von unsigned char der Name BYTE oder anstelle von unsigned long der Name DWORD für die Datentypen verwendet. Aber ein Blick in die Win32-Bibliothek zeigt, dass sich dies durch eine einfache Typdefinition ergibt: > typedef unsigned char BYTE; typedef unsigned long DWORD; Ebenso wird dies mit Strukturen und anderen Datentypen gemacht. AuÃerdem wird bei den Variablennamen von vielen Programmierern eine besondere Schreibweise, die sogenannte ungarische Notation, verwendet. Hierbei fängt jeder Variablenname mit einer Vorsilbe (Präfix) an, die etwas über den Variablentyp aussagt, gefolgt vom eigentlichen Namen, der mit einem GroÃbuchstaben beginnt. Ein Beispiel ist der Name szPauseName. Das Präfix sz steht hier für »string-zero terminated« d. h. »Zeichenkette mit dem Stringende-Zeichen«. Zwar verzichte ich in diesem Buch weitgehend auf die Verwendung einer solchen Syntax bzw. auf die Verwendung von Win32-Datentypen, aber sie sollte dennoch erwähnt werden, sofern Sie beispielsweise nach Quellcodes oder Dokumentationen zu diesem Thema Ausschau halten. # Winsock initialisieren Damit unter MS-Windows ein Prozess überhaupt Sockets verwenden kann, muss er vor jedem Aufruf einer Socket-Funktion initialisiert werden. Durch diese Initialisierung kann ein Prozess die WS2_32.DLL bzw. WINSOCK.DLL überhaupt erst verwenden. Sie initialisieren den Prozess durch den Systemaufruf WSAStartup(): > int WSAStartup ( WORD wVersionRequested, LPWSADATA lpWSAData ); Diese Funktion muss für jede weitere Socket-Funktion aufgerufen werden. Der erste Parameter ist vom Datentyp WORD (unsigned short) mit 2 Bytes Länge. Mit diesem Parameter geben Sie die Versionsnummer von Winsock an, die Sie verwenden wollen. Dabei legen Sie im Low-Order-Byte die Major-Nummer und im High-Order-Byte die Minor-Nummer (Revisionsnummer) fest. Damit Sie sich jetzt nicht mit Bitverschiebungen und den Byte-Orders auseinandersetzen müssen, verwenden Sie am besten gleich das Win32-Makro MAKEWORD(): > WORD MAKEWORD ( BYTE bLow, // low-order byte of short value BYTE bHigh // high-order byte of short value ); Und schon sind Sie ein Problem mehr los. Wollen Sie hierbei nun die Version 1.2 von Winsock verwenden, dann müssen Sie nur MAKEWORD(1, 2) verwenden. Für die Version 2.0 schreiben Sie einfach MAKEWORD(2 ,0). Mit dem zweiten Parameter von WSAStartup() geben Sie einen Zeiger auf die Struktur (LP)WSADATA (LP = Long Pointer) an. In dieser Struktur finden Sie Informationen zur Winsock-Version. Allerdings werden Sie diese Struktur im Buch nicht mehr benötigen. Wenn Sie mit der Anwendung fertig sind, sollten Sie zum Schluss mit der Funktion WSACleanup() die Verbindung mit WS2_32.DLL oder WINSOCK.DLL wieder beenden bzw. diese freigeben: > int WSACleanup (void); Damit werden diverse Aufräumarbeiten durchgeführt, und ein interner Referenzzähler, der auf WS2_32.DLL oder WINSOCK.DLL verweist, wird dekrementiert. # 25.3 Client/Server-Prinzip ## 25.3 Client/Server-Prinzip Beide Begriffe werden von der AuÃenwelt gerne missverstanden. Häufig stellt sich der Laie unter einem Server eine Hardware (einfach einen kompletten PC) vor. Bei dem Begriff »Client« ist dies recht ähnlich. Beides ist eigentlich falsch, denn sowohl der Server als auch der Client sind zwei Stückchen Software, die miteinander kommunizieren können. Diese Kommunikation muss dabei nicht zwangsläufig auf verschiedenen PCs stattfinden, auch wenn dies (in der Netzwerkprogrammierung) meistens der Fall ist. Es ist auch möglich, dass sich beides auf demselben Rechner befindet. Das Client/Server-Prinzip wird beispielsweise auch gern zur Kommunikation oder zum Austausch von Daten zwischen verschiedenen nicht verwandten Prozessen verwendet (Stichwort Interprozesskommunikation). Natürlich ist dies auch mit den Sockets (UNIX-Domain-Sockets) möglich – doch dies ist hier nicht das Thema. Der Server ist einfach eine Software, die einen bestimmten Dienst oder auch Service anbietet. Der oder meistens die Clients sind ebenfalls ein Stückchen Software, das diesen Dienst bzw. Service verwendet. Das einfachste Beispiel ist der Webserver (wie beispielsweise der Apache einer ist). Der Webserver bietet häufig viele Dienste wie FTP oder SSH an – aber der am meisten verwendete Dienst dürfte wohl das Anbieten von Webseiten (HTTP) sein. Und der Webbrowser ist dabei der Client, der diesen angebotenen Service vom Webserver verwendet. Damit können Sie die Webseiten auf Ihrem PC ansehen. Dabei ist es im Grunde egal, ob der Server auf einem Linux/UNIX-System ausgeführt wird (was gröÃtenteils der Fall ist) und der Client auf einem MS-Windows-System läuft (was bei Webbrowsern auch wieder gröÃtenteils der Fall ist). Wichtig ist, dass beide dieselbe Sprache sprechen (beispielsweise HTTP, Hypertext Transfer Protocol). Für das Client/Server-Prinzip in der Netzwerkprogrammierung ist es wichtig, dass eine Netzwerkverbindung zwischen mindestens zwei Endpunkten bestehen muss. Steht die Verbindung, kann die Kommunikation über das Netzwerk mit den verschiedenen Protokollen (TCP/IP oder UDP/IP) beginnen. ### 25.3.1 Loopback-Interface Da die meisten Leser das Client/Server-Beispiel auf dem lokalen Rechner testen werden, muss ich auch ein paar Worte zum Loopback-Interface sagen. Mit dem Loopback-Interface (127.0.0.1 oder auch localhost) können Sie die Netzwerkprotokolle auf dem lokalen Rechner zur Kommunikation verwenden, auch wenn kein Netzwerk vorhanden ist. Der Sinn des Loopback-Interface besteht einfach darin, dass manche Kommandos ihre Kommunikation auf dem Netzwerkprotokoll aufbauen. Somit würden ohne das Loopback-Interface die einen oder anderen Kommandos auf dem lokalen Rechner gar nicht funktionieren – wozu unter anderem auch Ihre Anwendungen zählen, sofern Sie diese lokal testen und verwenden wollen. # 25.4 Erstellen einer Client-Anwendung ## 25.4 Erstellen einer Client-Anwendung In diesem Abschnitt geht es darum, was für Funktionen grundlegend verwendet werden, um eine Client-Anwendung zu erstellen. ### 25.4.1 »socket()« – Erzeugen eines Kommunikationsendpunktes Der erste Schritt einer Kommunikationsverbindung – egal, ob dies auf dem Server oder auf dem Client geschieht – besteht immer erst einmal darin, einen Socket vom Betriebssystem anzufordern. Dabei ist noch egal, wer mit wem kommunizieren will. Das Erzeugen eines Sockets (Kommunikationsendpunkt) können Sie sich wie das Installieren einer Stromsteckdose vorstellen. Ãhnlich wie bei den Stromsteckdosen weltweit, wo es ja auch unterschiedliche Formen und Spannungen gibt, muss auch beim Anlegen eines Sockets angegeben werden, was hier alles »eingesteckt« werden kann. Hierzu sehen Sie zuerst die Syntax der Funktion socket() für Linux/UNIX: > #include <sys/types.h> #include <sys/socket.h> int socket(int domain, int type, int protocol); Und hier ist die Syntax für MS-Windows: > #include <winsock.h> SOCKET socket(int af, int type, int protocol); Auf beiden Systemen haben diese Funktionen eine fast identische Syntax – abgesehen vom Rückgabewert, der unter MS-Windows SOCKET lautet. Allerdings ist SOCKET letztendlich nichts anderes als eine Typdefinition von int, und somit könnten Sie in der Praxis hierfür auch int verwenden. Als Rückgabewert erhalten Sie bei beiden Versionen den Socket-Deskriptor. Bei einem Fehler gibt die Linux/UNIX-Version –1 zurück. Den Fehler können Sie mit dem Fehlercode von errno auswerten (beispielsweise mit perror() oder strerror()). Unter MS-Windows wird bei einem Fehler die Konstante SOCKET_ERROR (ebenfalls mit –1 definiert) zurückgegeben. Hierbei können Sie den Fehlercode mit der Funktion WSAGetLastError() ermitteln. Mit dem ersten Parameter domain bzw. af geben Sie die Adressfamilie (d. h. die Protokollfamilie) an, die Sie verwenden wollen. Eine komplette Liste aller auf Ihrem System unterstützten Protokolle finden Sie in der Headerdatei <sys/socket.h>. Tabelle 25.1 enthält einen Ãberblick zu den gängigeren und häufiger verwendeten Protokollen. Mit dem zweiten Parameter der Funktion socket() geben Sie den Socket-Typ an. Damit legen Sie die Ãbertragungsart der Daten fest. Für Sie sind hierbei erst einmal nur die symbolischen Konstanten SOCK_STREAM für TCP und SOCK_DGRAM für UDP interessant. Mit dem dritten Parameter können Sie ein Protokoll angeben, das Sie zur Ãbertragung verwenden wollen. Wenn Sie hierfür 0 eintragen, was meistens der Fall ist, wird das Standardprotokoll verwendet, das dem gewählten Socket-Typ (zweiter Parameter) entspricht. Im Fall von SOCK_STREAM wird TCP und bei SOCK_DGRAM wird UDP verwendet. Weitere mögliche Werte, ohne jetzt genauer darauf einzugehen, wären hierbei IPPROTO_TCP (TCP-Protokoll), IPPROTO_UDP (UDP-Protokoll), IPPROTO_ICMP (ICMP-Protokoll) und IPPROTO_RAW (wird bei Raw-Sockets verwendet). Wenn Sie allerdings beispielsweise für den Socket-Typ SOCK_STREAM angegeben haben und das TCP-Protokoll verwenden wollen, müssen Sie nicht extra noch beim dritten Parameter IPPROTO_TCP angeben. Mit der Angabe von 0 wird dieses Protokoll standardmäÃig verwendet. Somit sieht das Anfordern eines Sockets folgendermaÃen aus: > // Erzeuge das Socket - Verbindung über TCP/IP sock = socket( AF_INET, SOCK_STREAM, 0 ); if (sock < 0) { // Fehler beim Erzeugen des Sockets } ### 25.4.2 »connect()« – ein Client stellt eine Verbindung zum Server her Nachdem mit den Sockets die Kommunikationsendpunkte erzeugt wurden, kann der Client nun versuchen, eine Verbindung zum Server-Socket herzustellen. Dies wird mit der Funktion connect() versucht, die unter Linux/UNIX folgende Syntax hat: > #include <sys/types.h> #include <sys/socket.h> int connect ( int socket, const struct sockaddr *addr, int addrlen ); Unter MS-Windows lautet die Syntax so: > #include <winsock.h> int connect ( SOCKET s, const struct sockaddr FAR* addr, int addrlen ); Auch hier unterscheidet sich die Syntax nicht erheblich voneinander, und auch die Bedeutungen der einzelnen Parameter sind wieder dieselben. Bei einer erfolgreichen Ausführung geben beide Funktionen 0, ansonsten bei einem Fehler –1 (gleichwertig unter MS-Windows mit SOCKET_ERROR) zurück. Den Fehler können Sie auch hier wieder mit der Fehlervariablen errno (unter Linux/UNIX) oder mit der Funktion WSAGetLastError() (unter MS-Windows) ermitteln. Als erster Parameter wird der Socket-Deskriptor erwartet, über den Sie die Verbindung herstellen wollen. Dies ist der Rückgabewert, den Sie von der Funktion socket() erhalten haben. Um eine Verbindung zu einem anderen Rechner aufzubauen, werden logischerweise auch Informationen über die Adresse benötigt, mit der sich der Client verbinden will. Die Adressinformationen über den gewünschten Verbindungspartner tragen Sie im zweiten Parameter der Funktion connect() ein. Um sich mit dem Server zu verbinden, benötigen Sie Informationen über die Adressfamilie (Protokollfamilie), die Portnummer und logischerweise die IP-Adresse. Eingetragen werden diese Informationen mit dem zweiten Parameter der Struktur sockaddr, die folgendermaÃen definiert ist: > struct sockaddr { sa_family_t sa_family; // Adressfamilie AF_XXX char sa_data[14]; // Protokolladresse (IP-Nr. und Portnr.) }; Da diese Struktur allerdings recht umständlich auszufüllen ist, wurde für IP-Anwendungen eine spezielle Struktur eingeführt, mit der es möglich ist, die IP-Nummer und die Portnummer getrennt einzutragen: > struct sockaddr_in { sa_family sin_family; // Adressfamilie AF_XXX unsigned short int sin_port; // Portnummer struct in_addr sin_addr; // IP-Adresse unsigned char pad[8]; // Auffüllbytes für sockaddr }; Da beide Strukturen im Speicher gleichwertig sind, reicht es aus, eine einfache Typumwandlung bei connect() vorzunehmen. Mit dem letzten Parameter (addrlen) von connect() geben Sie die Länge in Bytes von sockaddr mit dem sizeof-Operator an. # Ausfüllen von »sockaddr_in« In der Strukturvariablen sin_family geben Sie die Adressfamilie (Protokollfamilie) an, mit der Sie kommunizieren wollen. Gewöhnlich gibt man hierfür dieselbe Familie an, wie schon beim ersten Parameter der Funktion socket(). In sin_port geben Sie die Portnummer an, über die Sie mit dem Server in Kontakt treten wollen. Wichtig ist hierbei, dass Sie den Wert in der Network Byte Order angeben. Es genügt also nicht, wenn Sie sich beispielsweise mit einem Webserver verbinden wollen, als Portnummer einfach 80 hinzuschreiben. Sie müssen hierbei auch auf die verschiedenen Architekturen Rücksicht nehmen, die es in heterogenen Netzwerken gibt. Denn auf den verschiedenen Architekturen gibt es unterschiedliche Anordnungen der Bytes zum Speichern von Zahlen. So wird bei der Anordnung gewöhnlich zwischen Big Endian und Little Endian unterschieden. Man spricht dabei gern vom »Zahlendreher«. Beim Big Endian-Format wird das höchstwertige Byte an der niedrigsten Adresse gespeichert, das zweithöchste an der nächsten Adresse und so weiter. Bei der Anordnung von Little Endian ist dies genau umgekehrt. Dabei wird das niedrigstwertige Byte an der niedrigsten Stelle gespeichert, das zweitniedrigste an der nächsten Stelle usw. Um jetzt aus einer lokal verwendeten Byte-Reihenfolge (Host Byte Order) eine Network-Byte-Order-Reihenfolge oder umgekehrt zu konvertieren, stehen Ihnen die folgenden vier Funktionen zur Verfügung: > #include <netinet/in.h> // Rückgabe : network-byte-order // Parameter: host-byte-order unsigned short int htons(unsigned short int hostshort); // Rückgabe : network-byte-order // Parameter: host-byte-order unsigned long int htonl(unsigned long int hostlong); // Rückgabe : host-byte-order // Parameter : network-byte-order unsigned short int ntohs(unsigned short int netshort); // Rückgabe : host-byte-order // Parameter : network-byte-order unsigned long int ntohl(unsigned long int netlong); Nicht jeder kennt allerdings die entsprechenden Portnummern zum entsprechenden Dienst. Hierbei kann die Funktion getservbyname() helfen. Dieser Funktion übergeben Sie den Namen eines Dienstes und das Transportprotokoll als Parameter. AnschlieÃend sucht getservbyname() in einer speziellen Datei nach einem Eintrag, der dazu passt, und gibt die Portnummer zurück. Hierfür gibt es eine spezielle Struktur in der Headerdatei <netdb.h> , mit der Sie an die Informationen zu den entsprechenden Diensten kommen: > struct servent { char *s_name; // offizieller Name vom Service char **s_aliases; // Alias-Liste int s_port; // Portnummer zum Servicenamen char *s_proto; // verwendetes Protokoll }; * s_name – offizieller Servicename * s_aliases – Ein Stringarray mit eventuellen Aliasnamen zum Service, falls vorhanden. Das letzte Element in der Liste ist NULL. * s_port – die Portnummer zum Servicenamen * s_proto – der Name des zu verwendenden Protokolls Die Syntax von getservbyname() lautet: > #include <netdb.h> struct servent *getservbyname ( const char *name, const char *proto ); Wenn Sie den Dienst name und das Protokoll proto angeben, liefert Ihnen diese Funktion bei Erfolg eine Adresse auf die Information in struct servent. Bei einem Fehler wird NULL zurückgegeben. Die IP-Adresse geben Sie in der Strukturvariablen sin_addr an. Allerdings wird auch hier die Network-Byte-Order-Reihenfolge erwartet. Hierbei ist uns allerdings die Funktion inet_addr() (oder die etwas sicherere Alternative inet_aton()) behilflich. Hierbei können Sie die IP-Adresse als String angeben und bekommen einen für sin_addr benötigten 32-Bit Wert in Network Byte Order zurück. Wenn der Client den Dienst eines Servers verwenden will, muss jenem natürlich dessen IP-Adresse bekannt sein. Meistens gibt ein Endanwender aber als Adresse den Rechnernamen anstatt der IP-Adresse an, da dieser einfacher zu merken ist. Damit also ein Client aus dem Rechnernamen (beispielsweise www.google.de) eine IP-Adresse (216.239.59.99) erhält, wird die Funktion gethostbyname() verwendet. > #include <netdb.h> struct hostent *gethostbyname(const char *rechnername); Um also aus einem Rechnernamen eine IP-Adresse und weitere Informationen zu ermitteln, steht ein sogenannter Nameserver zur Verfügung – dieser Rechner ist für die Umsetzung zwischen Rechnernamen und IP-Nummern zuständig. Selbst auf Ihrem Rechner finden Sie solche Einträge der lokalen IP-Nummern in der Datei /etc/hosts hinterlegt. Im Internet hingegen werden diese Daten in einer eigenen Datenbank gehalten. Um solche Informationen zu den einzelnen Rechnern zu erhalten, ist in der Headerdatei <netdb.h> folgende Struktur definiert: > struct hostent { char * h_name; char ** h_aliases; short h_addrtype; short h_length; char ** h_addr_list; }; * h_name – offizieller Name des Rechners. * h_aliases – ein Stringarray, in dem sich eventuell vorhandene Aliasnamen befinden. Das letzte Element ist immer NULL. * h_addrtyp – Hier steht der Adresstyp, was gewöhnlich AF_INET für IPv4 ist. * h_length – Hier findet sich die Länge der numerischen Adresse. * h_addr_list – Hierbei handelt es sich um ein Array von Zeigern auf die Adressen für den entsprechenden Rechner. Die Funktion gethostbyname() gibt bei Erfolg einen Zeiger auf struct hostent des gefundenen Rechners zurück, ansonsten bei einem Fehler NULL. Die letzte Strukturvariable pad in der Struktur sockaddr_in wird lediglich als Lückenfüller verwendet, um sockaddr_in auf die GröÃe von sockaddr aufzufüllen. Wenn Sie jetzt alle Strukturvariablen der Struktur sockaddr_in mit Werten belegt haben, können Sie die Funktion connect() aufrufen und bei stehender (erfolgreicher) Verbindung Daten austauschen (senden und empfangen). Hier folgt ein Codeausschnitt, der zeigt, wie ein »Auffüllen« der Struktur sockaddr_in und der anschlieÃende Aufruf der Funktion connect() vonstatten geht. Im Beispiel wird versucht, sich mit einem Webserver (Port 80; HTTP) zu verbinden, dessen IP-Adresse Sie als Argument in der Kommandozeile übergeben haben. > struct sockaddr_in server; unsigned long addr; ... // Alternative zu memset() -> bzero() memset( &server, 0, sizeof (server)); addr = inet_addr( argv[1] ); memcpy( (char *)&server.sin_addr, &addr, sizeof(addr)); server.sin_family = AF_INET; server.sin_port = htons(80); ... // Baue die Verbindung zum Server auf. if (connect(sock,(struct sockaddr*)&server, sizeof(server)) < 0){ // Fehler beim Verbindungsaufbau ... } ### 25.4.3 Senden und Empfangen von Daten Nachdem Sie sich erfolgreich mit dem Server verbunden haben, können Sie anfangen, Daten an den Server zu senden bzw. Daten zu empfangen. Hierzu gibt es jeweils für TCP und UDP ein Funktionspaar. Es war ja schon einmal die Rede davon, dass man mit Sockets ähnlich wie bei Dateien mit Filedeskriptoren arbeiten kann. Und in der Tat, unter Linux/UNIX kann der Austausch von Daten über Sockets auch mit den Systemcalls read() und write() stattfinden. Allerdings ist dies unter MS-Windows erst ab den Versionen NT/2000/XP mit den Funktionen ReadFile() und WriteFile() möglich. # »send()« und »recv()« – TCP Zum Senden von Daten von einem Socket an den Stream wird gewöhnlich die Funktion send() verwendet, die unter Linux/UNIX folgende Syntax besitzt: > #include <sys/types.h> #include <sys/socket.h> ssize_t send ( int socketfd, const void *data, size_t data_len, unsigned int flags ); Unter MS-Windows mit Winsock sieht die Syntax wieder ähnlich aus: > #include <winsock.h> int send ( SOCKET s, const char FAR* data, int data_len, int flags ); Wenn Sie diese Funktion mit write() vergleichen, können Sie Parallelen ziehen. Mit dem ersten Parameter geben Sie den Socket-Deskriptor an, über den Sie die Daten senden wollen. Im zweiten Parameter wird ein Zeiger auf den Speicherbereich erwartet, in dem sich die Daten befinden. Die GröÃe des Speicherbereichs geben Sie mit dem dritten Parameter an. Mit dem letzten Parameter können Sie das Verhalten von send() noch beeinflussen. Wird hierbei 0 angegeben, verhält sich send() wie die Systemfunktion write() zum Schreiben. Ansonsten wäre beispielsweise die symbolische Konstante MSG_OOP ein häufig verwendeter Wert, mit dem »Out-of-band«-Daten gesendet werden können. Weitere flags entnehmen Sie bitte wieder aus der entsprechenden Dokumentation (beispielsweise der Manual-Page) – da ich hierauf nicht näher eingehe. Im Falle eines Fehlers liefert send() –1 (was unter MS-Windows gleichwertig zur Konstante SOCKET_ERROR ist) zurück. Welcher Fehler auftrat, lässt sich wieder mit den üblichen betriebssystembedingten Routinen überprüfen (errno unter Linux/UNIX und WSAGetLastError() unter MS-Windows). Auch wenn kein Fehler auftritt, ist es dennoch sehr wichtig, den Rückgabewert zu überprüfen. Denn bei der Netzwerkprogrammierung sind auch gewisse Grenzen (Bandbreite) vorhanden – sprich, Sie können nicht unendlich viele Daten auf einmal versenden. Mit der Auswertung des Rückgabewerts können bzw. müssen Sie sich selbst darum kümmern, dass der eventuelle Rest, der nicht gesendet werden konnte, ebenfalls noch verschickt wird. Dies erledigen Sie, indem Sie data_len mit dem Rückgabewert von send() vergleichen. Durch diese Differenz (data_len – Rückgabewert) erhalten Sie die noch nicht gesendeten Daten. Um Daten von einem Stream-Socket zu empfangen (zu lesen), wird die Funktion recv() verwendet. Die Syntax unter Linux/UNIX lautet: > #include <sys/types.h> #include <sys/socket.h> ssize_t recv ( int socketfd, void *data , size_t data_len, unsigned int flags ); Und die Syntax unter MS-Windows ist: > #include <winsock.h> int recv (SOCKET s, char FAR* data, int data_len, int flags); Auch hier lassen sich mit Ausnahme des letzten Parameters wieder Parallelen zur Systemfunktion read() ziehen. Der erste Parameter ist wieder der Socket-Deskriptor der Verbindung, gefolgt von einem Zeiger auf einen Puffer, in den die Daten gelegt werden sollen. Die Länge des Puffers geben Sie mit dem dritten Parameter an, und mit den Flags können Sie das Verhalten von recv() beeinflussen. Eine Angabe von 0 bedeutet auch hier, dass sich recv() wie die Funktion read() verhält. Ansonsten wird auch hierbei gern die Konstante MSG_OOP (für »Out-of-band«-Daten, die gelesen werden können) und MSG_PEEK verwendet. Mit MSG_PEEK können Daten erneut gelesen werden. Zu weiteren möglichen flags sollten Sie bei Bedarf die entsprechende Dokumentation lesen (beispielsweise die Manual-Page). Im Falle eines Fehlers gilt dasselbe wie schon bei der Funktion send(). AuÃerdem kann die Funktion recv() auch 0 zurückgeben. Dies bedeutet dann, dass der Verbindungspartner seine Verbindung beendet hat. Ansonsten wird auch mit recv() die Anzahl der erfolgreich gelesenen Bytes zurückgeliefert. # »sendto()« und »recvfrom()« – UDP Für die Funktionen zum Senden und Empfangen von Datagrammen (UDP-Sockets) werden vorzugsweise sendto() und recvfrom() verwendet. Die Syntax unter Linux/UNIX lautet: > #include <sys/types.h> #include <sys/socket.h> ssize_t recvfrom( int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen ); ssize_t sendto( int s, const void *msg, size_t len, int flags, const struct sockaddr *to, socklen_t tolen ); Und es gibt eine entsprechende ähnliche Syntax unter MS-Windows: > #include <winsock.h> int sendto( SOCKET s, const char FAR * buf, int len, int flags, const struct sockaddr FAR * to, int tolen ); int recvfrom( SOCKET s, char FAR* buf, int len, int flags, struct sockaddr FAR* from, int FAR* fromlen ); Die Bedeutung der einzelnen Parameter sowie des Rückgabewerts entspricht exakt der von den TCP-Gegenstücken send() und recv(). Hinzugekommen hingegen sind am Ende zwei weitere Parameter. Mit dem fünften Parameter übergeben Sie einen Zeiger auf die Adresse des Zielrechners (bei sendto()) bzw. einen Zeiger auf die Adresse des Absenders (bei recvfrom()). Die Angaben entsprechen dabei dem Parameter sockaddr von der Funktion connect(). Mit dem letzten Parameter beider Funktionen geben Sie wieder die GröÃe der Struktur sockaddr an. Sollten Sie bei einer UDP-Verbindung die connect()-Funktion verwenden, können Sie auch die Funktionen send() und revc() verwenden. In diesem Fall werden die fehlenden Informationen zur Adresse automatisch ergänzt. ### 25.4.4 »close()« und »closesocket()« Sobald Sie mit der Datenübertragung fertig sind, sollten Sie den Socket-Deskriptor wieder freigeben bzw. schlieÃen. Unter Linux/UNIX können Sie hierbei, wie beim Lesen und/oder Schreiben einer Datei, ein simples close() verwenden: > #include <unistd.h> int close(int s); Unter MS-Windows hingegen wird hierbei die Funktion closesocket() verwendet, die letztendlich, abgesehen von ihrem anderen Namen, dieselbe Wirkung erzielt wie ein close() unter Linux/UNIX. > #include <winsock.h> int closesocket( SOCKET s); Beide Funktionen erwarten als Parameter den zu schlieÃenden Socket-Deskriptor und geben bei Erfolg 0, ansonsten bei einem Fehler –1 (gleichwertig zu SOCKET_ERROR unter MS-Windows) zurück. Auch hierbei können Sie den Fehler anhand von errno (Linux/UNIX) oder der Funktion WSAGetLastError() (MS-Windows) ermitteln. Ein Aufruf von close() bzw. closesocket() beendet auÃerdem eine TCP-Verbindung sofort. # 25.5 Erstellen einer Server-Anwendung ## 25.5 Erstellen einer Server-Anwendung Eine Server-Anwendung zu erstellen ist nicht viel schwieriger als das Programmieren der Client-Anwendung. Der Datenaustausch erfolgt genauso wie bei der Client-Anwendung via send()/recv() (TCP) bzw. sendto()/recvfrom() (UDP). Der Server muss allerdings keine Verbindung herstellen – dies ist die Aufgabe des Clients. Allerdings ist es die Aufgabe des Servers, Verbindungswünsche anzunehmen. Und um dies zu realisieren, müssen Sie den Server in einen Wartezustand versetzen. ### 25.5.1 »bind()« – Festlegen einer Adresse aus dem Namensraum Nachdem Sie auch auf der Serverseite mit der Funktion socket() eine »Steckdose« bereitgestellt haben, müssen Sie zunächst die Portnummer der Server-Anwendung festlegen. Sie wissen ja bereits von der Clientanwendung, dass mittels connect() auf eine bestimmte IP-Adresse und eine Portnummer des Servers zugegriffen wird. Unter welcher IP-Adresse und Portnummer der Server nun auf Anfragen der Clients wartet, müssen Sie mit der Funktion bind() festlegen. Somit weisen Sie praktisch einem Socket eine Adresse zu – schlieÃlich ist es durchaus gängig, dass eine Serveranwendung mehrere Sockets verwendet. Dass hierbei meistens die IP-Adresse die gleiche ist, dürfte klar sein, aber es ist durchaus möglich, die Datenübertragung über mehrere Ports zuzulassen. Die Funktion bind() wiederum teilt dem Betriebssystem mit, welchen Socket es mit einem bestimmten Port verknüpfen soll. Sobald dann ein Datenpaket eingeht, erkennt das Betriebssystem anhand der Portnummer, für welchen Socket das Paket ist. Die Syntax zur Funktion bind() lautet bei Linux/UNIX: > #include <sys/types.h> #include <sys/socket.h> int bind( int s, const struct sockaddr name, int namelen ); Bei MS-Windows lautet die Syntax ähnlich: > #include <winsock.h> int bind(SOCKET s, const struct sockaddr FAR* name, int namelen); Als ersten Parameter übergeben Sie wie immer den Socket-Deskriptor, den Sie mit socket() angelegt haben. Mit dem zweiten Parameter geben Sie einen Zeiger auf eine Adresse und Portnummer an. Damit teilen Sie dem System mit, welche Datenpakete für welches Socket gedacht sind. Die Struktur sockaddr bzw. (einfacher) sockaddr_in und deren Mitglieder wurde bereits ausführlich im Abschnitt zur Funktion connect() beschrieben. Allerdings sollte hier noch erwähnt werden, dass ein Rechner häufig über verschiedene Rechner (unter mehreren Adressen) und auch verschiedenste Netze (Internet, Intranet, lokales Netzwerk etc.) erreichbar ist bzw. sein muss. Damit ein Server über alle Netze und IP-Adressen eine Verbindung annimmt, setzt man die IP-Adresse auf INADDR_ANY (natürlich in Network Byte Order). Ansonsten geben Sie die IP-Adresse wie gewöhnlich mit der Funktion inet_addr() an. Es ist auÃerdem auch möglich, neben der IP-Adresse eine beliebige Portnummer zuzulassen. Hierfür müssen Sie lediglich 0 als Portnummer (in Network Byte Order) verwenden. Welchen Port Sie dann erhalten haben, können Sie mit der Funktion getsockname() im Nachhinein abfragen. Mehr zu dieser Funktion können Sie aus der entsprechenden Dokumentation entnehmen (beispielsweise der Manual-Page). Mit dem letzten Parameter geben Sie wiederum die Länge der Struktur (zweiter Parameter) in Bytes mit sizeof() an. bind() liefert im Falle eines Fehlers –1 (gleichwertig mit dem Fehlercode SOCKET_ERROR unter MS-Windows). Welcher Fehler aufgetreten ist, können Sie wiederum mit errno (Linux/UNIX) bzw. WSAGetLastError() (MS-Windows) in Erfahrung bringen. Hier sehen Sie einen kurzen Codeausschnitt, der zeigt, wie die Zuweisung einer Adresse auf der Serverseite in der Praxis realisiert wird: > struct sockaddr_in server; memset( &server, 0, sizeof (server)); // IPv4-Adresse server.sin_family = AF_INET; // Jede IP-Adresse ist gültig server.sin_addr.s_addr = htonl( INADDR_ANY ); // Portnummer 1234 server.sin_port = htons( 1234 ); if(bind( sock, (struct sockaddr*)&server, sizeof( server)) < 0) { //Fehler bei bind() } ### 25.5.2 »listen()« – Warteschlange für eingehende Verbindungen einrichten Im nächsten Schritt müssen Sie eine Warteschlange einrichten, die auf eingehende Verbindungswünsche eines Clients wartet – man spricht auch gerne vom »Horchen« auf Verbindungen, die am Socket eingehen. Eine solche Warteschlange wird mit der Funktion listen() eingerichtet. Dabei wird die Programmausführung des Servers so lange unterbrochen, bis ein Verbindungswunsch eintrifft. Mit listen() lassen sich durchaus mehrere Verbindungswünsche »gleichzeitig« einrichten. Die Syntax dieser Funktion sieht unter Linux/UNIX wie folgt aus: > #include <sys/types.h> #include <sys/socket.h> int listen( int s, int backlog ); Unter MS-Windows hingegen sieht die Syntax wie folgt aus: > #include <winsock.h> int listen( SOCKET s, int backlog ); Mit dem ersten Parameter geben Sie wie immer den Socket-Deskriptor an und mit dem zweiten Parameter die Länge der Warteschlange. Die Länge der Warteschlange ist die maximale Anzahl von Verbindungsanfragen, die in eine Warteschlange gestellt werden, wenn keine Verbindungen mehr angenommen werden können. Der Rückgabewert ist bei Erfolg 0 und auch hier bei einem Fehler –1 (gleichbedeutend unter MS-Windows mit SOCKET_ERROR). Den Fehlercode selbst können Sie wieder wie gehabt mit errno (Linux/UNIX) bzw. WSAGetLastError() (MS-Windows) auswerten. In der Praxis sieht die Verwendung von listen() wie folgt aus: > if( listen( sock, 5 ) == -1 ) { // Fehler bei listen() } ### 25.5.3 »accept()« und die Serverhauptschleife Sobald nun ein oder mehrere Clients Verbindung mit dem Server aufnehmen wollen, können Sie sich darauf verlassen, dass die Funktion accept() immer die nächste Verbindung aus der Warteschlange holt (die Sie mit listen() eingerichtet haben). Hier sehen Sie die Syntax dazu unter Linux/UNIX: > #include <sys/types.h> #include <sys/socket.h> int accept( int s, struct sockaddr *addr, socklen_t addrlen ); Die Syntax unter MS-Windows ist ähnlich: > #include <winsock.h> SOCKET accept( SOCKET s, struct sockaddr FAR* addr, int FAR* addrlen ); An der Syntax unter MS-Window lässt sich gleich erkennen, dass die Funktion accept() als Rückgabewert ein neues Socket zurückgibt. Hierbei handelt es sich um das gleiche Socket mit denselben Eigenschaften wie vom ersten Parameter s. Ãber dieses neue Socket wird anschlieÃend die Datenübertragung der Verbindung abgewickelt. Ein so akzeptiertes Socket kann allerdings nicht mehr für weitere Verbindungen verwendet werden. Das Orginalsocket s hingegen bleibt weiterhin für weitere Verbindungswünsche offen. Mit dem zweiten Parameter schreibt accept() Informationen (IP-Adresse und Port) über den Verbindungspartner in die Struktur sockaddr bzw. sockaddr_in. Dies ist logischerweise nötig, damit Sie wissen, mit wem Sie es zu tun haben. addrlen wiederum ist die GröÃe der Struktur sockaddr bzw. sockaddr_in – allerdings wird diesmal ein Zeiger auf die GröÃe der Adresse erwartet! Bei einem Fehler wird –1 (gleichbedeutend mit SOCKET_ERROR unter MS-Windows) zurückgegeben. Die genaue Ursache des Fehlers können Sie wieder mit errno (Linux/UNIX) bzw. WSAGetLastError() (MS-Windows) ermitteln. Bei erfolgreicher Ausführung von accept() wird, wie bereits beschrieben, ein neuer Socket-Deskriptor zurückgegeben. Ein wichtiger Teil der Serverprogrammierung ist auÃerdem die Serverhauptschleife. In dieser Schleife wird gewöhnlich die Funktion accept() aufgerufen, und darin findet auch gewöhnlich der Datentransfer zwischen Client und Server statt. Hier sehen Sie ein Beispiel für eine solche Serverhauptschleife: > struct sockaddr_in client; int sock, sock2; socklen_t len; ... for (;;) { len = sizeof( client ); sock2 = accept( sock, (struct sockaddr*)&client, &len); if (sock2 < 0) { //Fehler bei accept() } // Hier beginnt der Datenaustausch. } Abbildung 25.2 verdeutlicht alle Socket-Funktionen für eine TCP-Verbindung zwischen dem Server und dem Client anhand einer Grafik. Abbildung 25.2 Kompletter Vorgang einer TCP-Client/Server-Verbindung Für eine UDP-Verbindung zwischen Server und Client sieht der Vorgang hingegen so aus wie in Abbildung 25.3. Abbildung 25.3 Kompletter Vorgang einer UDP-Client/Server-Verbindung # 25.6 (Cross-Plattform-)TCP-Echo-Server ## 25.6 (Cross-Plattform-)TCP-Echo-Server In diesem Abschnitt schreiben wir als Beispiel einen einfachen portablen TCP-Echo-Server mit fast allen Funktionen, die eben beschrieben wurden. Befindet sich beispielsweise die Server-Software auf einem Rechner mit der IP-Adresse 196.12.32.6, so können Sie mit der Clientanwendung unter Angabe der entsprechenden IP-Adresse einen einfachen String via Kommandozeile senden. Der Server gibt diesen String mitsamt der Herkunft des Clients (IP-Adresse) und des Datums mit Uhrzeit auf die Standardausgabe aus. ### 25.6.1 Der Client Hier sehen Sie den Quellcode der Clientanwendung: > /* client.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #ifdef _WIN32 /* Headerfiles für Windows */ #include <winsock.h> #include <io.h> #else /* Headerfiles für UNIX/Linux */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <unistd.h> #endif #define PORT 1234 #define RCVBUFSIZE 8192 /* Funktion gibt aufgetretenen Fehler aus und * beendet die Anwendung. */ static void error_exit(char *errorMessage) { #ifdef _WIN32 fprintf(stderr,"%s: %d\n", errorMessage, WSAGetLastError()); #else fprintf(stderr, "%s: %s\n", errorMessage, strerror(errno)); #endif exit(EXIT_FAILURE); } int main( int argc, char *argv[]) { struct sockaddr_in server; struct hostent *host_info; unsigned long addr; #ifdef _WIN32 SOCKET sock; #else int sock; #endif char *echo_string; int echo_len; #ifdef _WIN32 /* Initialisiere TCP für Windows ("winsock"). */ WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD (1, 1); if (WSAStartup (wVersionRequested, &wsaData) != 0) error_exit( "Fehler beim Initialisieren von Winsock"); else printf("Winsock initialisiert\n"); #endif /* Sind die erforderlichen Kommandozeilenargumente vorhanden? */ if (argc < 3) error_exit("usage: client server-ip echo_word\n"); /* Erzeuge das Socket. */ sock = socket( AF_INET, SOCK_STREAM, 0 ); if (sock < 0) error_exit( "Fehler beim Anlegen eines Sockets"); /* Erzeuge die Socketadresse des Servers. * Sie besteht aus Typ, IP-Adresse und Portnummer. */ memset( &server, 0, sizeof (server)); if ((addr = inet_addr( argv[1])) != INADDR_NONE) { /* argv[1] ist eine numerische IP-Adresse. */ memcpy( (char *)&server.sin_addr, &addr, sizeof(addr)); } else { /* Für den Fall der Fälle: Wandle den * Servernamen bspw. "localhost" in eine IP-Adresse um. */ host_info = gethostbyname(argv[1]); if (NULL == host_info) error_exit("Unbekannter Server"); /* Server-IP-Adresse */ memcpy( (char *)&server.sin_addr, host_info->h_addr, host_info->h_length ); } /* IPv4-Verbindung */ server.sin_family = AF_INET; /* Portnummer */ server.sin_port = htons( PORT ); /* Baue die Verbindung zum Server auf. */ if(connect(sock,(struct sockaddr*)&server,sizeof(server)) <0) error_exit("Kann keine Verbindung zum " "Server herstellen"); /* Zweites Argument wird als "echo" beim Server verwendet. */ echo_string = argv[2]; /* Länge der Eingabe */ echo_len = strlen(echo_string); /* den String inkl. Nullterminator an den Server senden */ if (send(sock, echo_string, echo_len, 0) != echo_len) error_exit("send() hat eine andere Anzahl" " von Bytes versendet als erwartet !!!!"); /* SchlieÃe Verbindung und Socket. */ #ifdef _WIN32 closesocket(sock); /* Cleanup Winsock */ WSACleanup(); #else close(sock); #endif return EXIT_SUCCESS; } ### 25.6.2 Der Server Hier ist der Quellcode zur Server-Anwendung: > /* server.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <time.h> #ifdef _WIN32 /* Headerfiles für Windows */ #include <winsock.h> #include <io.h> #else /* Headerfiles für UNIX/Linux */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <unistd.h> #endif /* Portnummer */ #define PORT 1234 /* Puffer für eingehende Nachrichten */ #define RCVBUFSIZE 1024 #ifdef _WIN32 static void echo(SOCKET); #else static void echo( int ); #endif static void error_exit(char *errorMessage); /* Die Funktion gibt Daten vom Client auf stdout aus, * die dieser mit der Kommandozeile übergibt. */ #ifdef _WIN32 static void echo(SOCKET client_socket) #else static void echo(int client_socket) #endif { char echo_buffer[RCVBUFSIZE]; int recv_size; time_t zeit; if((recv_size = recv(client_socket, echo_buffer, RCVBUFSIZE,0)) < 0) error_exit("Fehler bei recv()"); echo_buffer[recv_size] = '\0'; time(&zeit); printf("Nachrichten vom Client : %s \t%s", echo_buffer, ctime(&zeit)); } /* Die Funktion gibt den aufgetretenen Fehler aus und * beendet die Anwendung. */ static void error_exit(char *error_message) { #ifdef _WIN32 fprintf(stderr,"%s: %d\n", error_message, WSAGetLastError()); #else fprintf(stderr, "%s: %s\n", error_message, strerror(errno)); #endif exit(EXIT_FAILURE); } int main( int argc, char *argv[]) { struct sockaddr_in server, client; #ifdef _WIN32 SOCKET sock, fd; #else int sock, fd; #endif unsigned int len; #ifdef _WIN32 /* Initialisiere TCP für Windows ("winsock"). */ WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD (1, 1); if (WSAStartup (wVersionRequested, &wsaData) != 0) error_exit( "Fehler beim Initialisieren von Winsock"); else printf("Winsock initialisiert\n"); #endif /* Erzeuge das Socket. */ sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock < 0) error_exit("Fehler beim Anlegen eines Sockets"); /* Erzeuge die Socketadresse des Servers. */ memset( &server, 0, sizeof (server)); /* IPv4-Verbindung */ server.sin_family = AF_INET; /* INADDR_ANY: jede IP-Adresse annehmen */ server.sin_addr.s_addr = htonl(INADDR_ANY); /* Portnummer */ server.sin_port = htons(PORT); /* Erzeuge die Bindung an die Serveradresse * (genauer: an einen bestimmten Port). */ if(bind(sock,(struct sockaddr*)&server, sizeof( server)) < 0) error_exit("Kann das Socket nicht \"binden\""); /* Teile dem Socket mit, dass Verbindungswünsche * von Clients entgegengenommen werden. */ if(listen(sock, 5) == -1 ) error_exit("Fehler bei listen"); printf("Server bereit - wartet auf Anfragen ...\n"); /* Bearbeite die Verbindungswünsche von Clients * in einer Endlosschleife. * Der Aufruf von accept() blockiert so lange, * bis ein Client Verbindung aufnimmt. */ for (;;) { len = sizeof(client); fd = accept(sock, (struct sockaddr*)&client, &len); if (fd < 0) error_exit("Fehler bei accept"); printf("Bearbeite den Client mit der Adresse: %s\n", inet_ntoa(client.sin_addr)); /* Daten vom Client auf dem Bildschirm ausgeben */ echo( fd ); /* SchlieÃe die Verbindung. */ #ifdef _WIN32 closesocket(fd); #else close(fd); #endif } return EXIT_SUCCESS; } Generell werden die meisten Leser dieses Beispiel am lokalen Rechner testen. Das heiÃt, sowohl die Server- als auch die Clientanwendung befindet sich dabei auf einem Rechner. Wie schon erwähnt wurde, ist dies dank des Loopback-Interfaces kein Problem. Die lokale IP-Adresse, die Sie auf Ihrem Rechner verwenden können, lautet hierbei 127.0.0.1 bzw. »localhost«. Wenn Sie allerdings die Möglichkeit haben, die Serveranwendung auf einem anderen System zu kompilieren und zu testen, so sollten Sie sich nicht scheuen, dies zu tun. Abbildung 25.4 zeigt das Programm bei der Ausführung. Abbildung 25.4 Ein Client schickt einen String an den Server. Abbildung 25.5 Der Server bearbeitet die Anfragen des bzw. der Clients. Natürlich stellt dieses Beispiel die primitivste Form der Netzwerkprogrammierung dar. Dennoch werden eigentlich alle wichtigen Funktionen der Netzwerkprogrammierung dazu verwendet. # 25.7 Cross-Plattform-Development ## 25.7 Cross-Plattform-Development Das kleine Beispiel des TCP-Echo-Servers zeigte Ihnen einen einfachen Weg, wie Sie mit einfachen #ifdef-Präprozessor-Direktiven eine Cross-Plattform-Anwendung schreiben können. Das Problem dabei (am Quellcode) war allerdings, dass alles für jede Plattform in eine Datei geschrieben wurde. Für das kleine Programm ist das zwar nicht die Rede wert, aber bei umfangreicheren und komplizierten Programmen ist es sinnvoller, einen abstrakten Layer (Abstraction Layer) zu schreiben. Nicht anders wird dies übrigens bei solchen Mammut-Projekten wie MySQL und dem Apache realisiert – auch hier finden Sie für alle gängigen Plattformen eine extra Version. ### 25.7.1 Abstraction Layer Hinter dem Begriff Abstraction Layer verbirgt sich nichts Kompliziertes. Der Abstraction Layer isoliert plattformspezifische Funktionen und Datentypen in separate Module für portablen Code. Die plattformspezifischen Module werden dann speziell für jede Plattform geschrieben. Des Weiteren erstellen Sie eine neue Headerdatei, in der sich eventuell die plattformspezifischen typedef und #define mitsamt den Funktionsprototypen der Module befinden. Bei der Anwendung selbst binden Sie nur noch diese Headerdatei ein. Auf den folgenden Seiten finden Sie nun die einzelnen Quellcodes für unseren abstrakten Layer – ich werde diesen einfach SOCKETPRX nennen. ### 25.7.2 Headerdatei für Linux/UNIX > /* socketprx.h für Linux/UNIX */ #ifndef SOCKETPRX_H_ #define SOCKETPRX_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <unistd.h> /* ein eigener primitver Datentyp für den Socket-Deskriptor */ #define socket_t int /* Funktionsprototypen */ void error_exit(char *error_message); int create_socket( int af, int type, int protocol ); void bind_socket(socket_t *sock, unsigned long adress, unsigned short port); void listen_socket( socket_t *sock ); void accept_socket( socket_t *new_socket, socket_t *socket ); void connect_socket(socket_t *sock, char *serv_addr, unsigned short port); void TCP_send( socket_t *sock, char *data, size_t size); void TCP_recv( socket_t *sock, char *data, size_t size); void UDP_send ( socket_t *sock, char *data, size_t size, char *addr, unsigned short port); void UDP_recv( socket_t *sock, char *data, size_t size); void close_socket( socket_t *sock ); void cleanup(void); #endif ### 25.7.3 Linux/UNIX-Quellcodedatei > /* socketlayer.c - für Linux/UNIX */ #include "socketprx.h" /* Die Funktion gibt aufgetretene Fehler aus und * beendet die Anwendung. */ void error_exit(char *error_message) { fprintf(stderr, "%s: %s\n", error_message, strerror(errno)); exit(EXIT_FAILURE); } int create_socket( int af, int type, int protocol ) { socket_t sock; const int y = 1; /* Erzeuge das Socket. */ sock = socket(af, type, protocol); if (sock < 0) error_exit("Fehler beim Anlegen eines Sockets"); /* Mehr dazu siehe Anmerkung am Ende des Listings ... */ setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)); return sock; } /* Erzeugt die Bindung an die Serveradresse, * (genauer gesagt an einen bestimmten Port). */ void bind_socket(socket_t *sock, unsigned long adress, unsigned short port) { struct sockaddr_in server; memset( &server, 0, sizeof (server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(adress); server.sin_port = htons(port); if (bind(*sock, (struct sockaddr*)&server,sizeof(server)) < 0) error_exit("Kann das Socket nicht \"binden\""); } /* Teile dem Socket mit, dass Verbindungswünsche * von Clients entgegengenommen werden. */ void listen_socket( socket_t *sock ) { if(listen(*sock, 5) == -1 ) error_exit("Fehler bei listen"); } /* Bearbeite die Verbindungswünsche von Clients. * Der Aufruf von accept() blockiert so lange, * bis ein Client Verbindung aufnimmt. */ void accept_socket( socket_t *socket, socket_t *new_socket ){ struct sockaddr_in client; unsigned int len; len = sizeof(client); *new_socket=accept(*socket,(struct sockaddr *)&client, &len); if (*new_socket == -1) error_exit("Fehler bei accept"); } /* Baut die Verbindung zum Server auf. */ void connect_socket(socket_t *sock, char *serv_addr, unsigned short port) { struct sockaddr_in server; struct hostent *host_info; unsigned long addr; memset( &server, 0, sizeof (server)); if ((addr = inet_addr( serv_addr )) != INADDR_NONE) { /* argv[1] ist eine numerische IP-Adresse */ memcpy( (char *)&server.sin_addr, &addr, sizeof(addr)); } else { /* Für den Fall der Fälle: Wandle den * Servernamen bspw. "localhost" in eine IP-Adresse um. */ host_info = gethostbyname( serv_addr ); if (NULL == host_info) error_exit("Unbekannter Server"); memcpy( (char *)&server.sin_addr, host_info->h_addr, host_info->h_length); } server.sin_family = AF_INET; server.sin_port = htons( port ); /* Baue die Verbindung zum Server auf. */ if (connect( *sock, (struct sockaddr *)&server, sizeof( server)) < 0) error_exit( "Kann keine Verbindung zum Server herstellen"); } /* Daten versenden via TCP */ void TCP_send( socket_t *sock, char *data, size_t size) { if(send( *sock, data, size, 0) == -1 ) error_exit("Fehler bei send()"); } /* Daten empfangen via TCP */ void TCP_recv( socket_t *sock, char *data, size_t size) { unsigned int len; len = recv (*sock, data, size, 0); if( len > 0 || len != -1 ) data[len] = '\0'; else error_exit("Fehler bei recv()"); } /* Daten senden via UDP */ void UDP_send ( socket_t *sock, char *data, size_t size, char *addr, unsigned short port){ struct sockaddr_in addr_sento; struct hostent *h; int rc; /* IP-Adresse des Servers überprüfen */ h = gethostbyname(addr); if (h == NULL) error_exit("Unbekannter Host?"); addr_sento.sin_family = h->h_addrtype; memcpy ( (char *) &addr_sento.sin_addr.s_addr, h->h_addr_list[0], h->h_length); addr_sento.sin_port = htons (port); rc = sendto(*sock, data, size, 0, (struct sockaddr *) &addr_sento, sizeof (addr_sento)); if (rc < 0) error_exit("Konnte Daten nicht senden - sendto()"); } /* Daten empfangen via UDP */ void UDP_recv( socket_t *sock, char *data, size_t size){ struct sockaddr_in addr_recvfrom; unsigned int len; int n; len = sizeof (addr_recvfrom); n = recvfrom ( *sock, data, size, 0, (struct sockaddr *) &addr_recvfrom, &len ); if (n < 0) { printf ("Keine Daten empfangen ...\n"); return; } } /* Socket schlieÃen */ void close_socket( socket_t *sock ){ close(*sock); } /* Unter Linux/UNIX ist nichts zu tun ... */ void cleanup(void){ printf("Aufraeumarbeiten erledigt ...\n"); return; } ### 25.7.4 Headerdatei für MS-Windows > /* socketprx.h für MS-Windows */ #ifndef SOCKETPRX_H_ #define SOCKETPRX_H_ #include <stdio.h> #include <stdlib.h> #include <winsock.h> #include <io.h> #define socket_t SOCKET void error_exit(char *error_message); int create_socket( int af, int type, int protocol ); void bind_socket(socket_t *sock, unsigned long adress, unsigned short port); void listen_socket( socket_t *sock ); void accept_socket( socket_t *new_socket, socket_t *socket ); void connect_socket(socket_t *sock, char *serv_addr, unsigned short port); void TCP_send( socket_t *sock, char *data, size_t size); void TCP_recv( socket_t *sock, char *data, size_t size); void UDP_send (socket_t *sock, char *data, size_t size); void UDP_recv( socket_t *sock, char *data, size_t size, char *addr, unsigned short port); void close_socket( socket_t *sock ); void cleanup(void); #endif ### 25.7.5 Windows-Quellcodedatei > /* socketlayer.c - für MS-Windows */ #include <stdio.h> #include <stdlib.h> #include <winsock.h> #include <io.h> #define socket_t SOCKET /* Die Funktion gibt aufgetretene Fehler aus und * beendet die Anwendung. */ void error_exit(char *error_message) { fprintf(stderr,"%s: %d\n", error_message, WSAGetLastError()); exit(EXIT_FAILURE); } /* Initialisiere TCP für Windows ("winsock"), * legt ein Socket an * und gibt das Socket als Rückgabewert zurück. */ int create_socket( int af, int type, int protocol ) { socket_t sock; WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD (1, 1); if (WSAStartup (wVersionRequested, &wsaData) != 0) error_exit( "Fehler beim Initialisieren von Winsock"); else printf("Winsock initialisiert\n"); /* Erzeuge das Socket. */ sock = socket(af, type, protocol); if (sock < 0) error_exit("Fehler beim Anlegen eines Sockets"); return sock; } /* Erzeugt die Bindung an die Serveradresse * (genauer gesagt an einen bestimmten Port). */ void bind_socket(socket_t *sock, unsigned long adress, unsigned short port) { struct sockaddr_in server; memset( &server, 0, sizeof (server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(adress); server.sin_port = htons(port); if (bind(*sock, (struct sockaddr*) &server, sizeof( server)) == SOCKET_ERROR) error_exit("Kann das Socket nicht \"binden\""); } /* Teile dem Socket mit, dass Verbindungswünsche * von Clients entgegengenommen werden. */ void listen_socket( socket_t *sock ) { if(listen(*sock, 5) == -1 ) error_exit("Fehler bei listen"); } /* Bearbeite die Verbindungswünsche von Clients. * Der Aufruf von accept() blockiert so lange, * bis ein Client Verbindung aufnimmt. */ void accept_socket( socket_t *socket, socket_t *new_socket ){ struct sockaddr_in client; unsigned int len; len = sizeof(client); *new_socket=accept(*socket, (struct sockaddr *)&client, &len); if (*new_socket == INVALID_SOCKET) error_exit("Fehler bei accept"); } /* Baut die Verbindung zum Server auf. */ void connect_socket( socket_t *sock, char *serv_addr, unsigned short port) { struct sockaddr_in server; struct hostent *host_info; unsigned long addr; memset( &server, 0, sizeof (server)); if ((addr = inet_addr( serv_addr )) != INADDR_NONE) { /* argv[1] ist eine numerische IP-Adresse. */ memcpy( (char *)&server.sin_addr, &addr, sizeof(addr)); } else { /* Für den Fall der Fälle: Wandle den * Servernamen bspw. "localhost" in eine IP-Adresse um. */ host_info = gethostbyname( serv_addr ); if (NULL == host_info) error_exit("Unbekannter Server"); memcpy( (char *)&server.sin_addr, host_info->h_addr, host_info->h_length); } server.sin_family = AF_INET; server.sin_port = htons( port ); /* Baue die Verbindung zum Server auf. */ if (connect( *sock, (struct sockaddr*)&server, sizeof( server)) < 0) error_exit( "Kann keine Verbindung zum Server herstellen"); } /* Daten versenden via TCP */ void TCP_send( socket_t *sock, char *data, size_t size ) { if( send (*sock, data, size, 0) == SOCKET_ERROR ) error_exit("Fehler bei send()"); } /* Daten empfangen via TCP */ void TCP_recv( socket_t *sock, char *data, size_t size) { int len; len = recv (*sock, data, size, 0); if( len > 0 || len != SOCKET_ERROR ) data[len] = '\0'; else error_exit("Fehler bei recv()"); } /* Daten senden via UDP */ void UDP_send ( socket_t *sock, char *data, size_t size, char *addr, unsigned short port){ struct sockaddr_in addr_sento; struct hostent *h; int rc; /* IP-Adresse vom Server überprüfen */ h = gethostbyname(addr); if (h == NULL) error_exit("Unbekannter Host?"); addr_sento.sin_family = h->h_addrtype; memcpy ( (char *) &addr_sento.sin_addr.s_addr, h->h_addr_list[0], h->h_length); addr_sento.sin_port = htons (port); rc = sendto(*sock, data, size, 0, (struct sockaddr *) &addr_sento, sizeof (addr_sento)); if (rc == SOCKET_ERROR) error_exit("Konnte Daten nicht senden - sendto()"); } /* Daten empfangen via UDP */ void UDP_recv( socket_t *sock, char *data, size_t size){ struct sockaddr_in addr_recvfrom; unsigned int len; int n; len = sizeof (addr_recvfrom); n = recvfrom ( *sock, data, size, 0, (struct sockaddr *) &addr_recvfrom, &len ); if (n == SOCKET_ERROR) error_exit("Fehler bei recvfrom()"); } /* Socket schlieÃen und Winsock freigeben */ void close_socket( socket_t *sock ){ closesocket(*sock); } void cleanup(void){ /* Cleanup Winsock */ WSACleanup(); printf("Aufraeuumarbeiten erledigt ...\n"); } ### 25.7.6 All together – die »main«-Funktionen Nachdem Ihnen nun zwei Versionen von SOCKETPRX zur Verfügung stehen, können Sie die Module jetzt auf dem System Ihrer Wahl übersetzen und ausführen. Der Vorteil ist, dass Sie nur noch eine Hauptfunktion benötigen – alle plattformspezifischen Eigenheiten verstecken sich ja nun hinter dem Layer. Und es gibt noch einen weiteren Vorteil: Bei einer guten Planung des Layers gestaltet sich die Erstellung der main()-Funktion erheblich leichter und kürzer – da Sie die Fehlerüberprüfungen nun auch dem Layer überlassen können. Besonders bezahlt macht sich ein solcher Layer, wenn Sie einzelne Routinen immer wieder benötigen. Somit können Sie eine tolle und simple Cross-Plattform-Bibliothek anbieten. Das Beispiel des TCP-Echo-Servers wurde hier erweitert. Daraus ist nun eine Art 1:1-Chat zwischen dem Server und Client geworden (wie Sie mehr als einen Client bearbeiten können, erfahren Sie noch). Der Server »lauscht« am Port 15000 und wartet, bis ein Client mit diesem in Verbindung tritt. Sobald ein Client eine Verbindung zum Server hergestellt hat, können Sie (der Server) dem Client eine Zeichenkette als Nachricht senden. AnschlieÃend wartet der Server auf eine Antwort vom Client. Sendet der Client dem Server die Textfolge »quit«, so bedeutet dies für den Server, dass der Client »aufgelegt« hat, und der Server wartet wieder (mittels accept()) auf eine Verbindungsanfrage eines Clients. Der Quellcode des Servers sieht so aus: > /* server.c */ #include <string.h> #include "socketprx.h" #define BUF 1024 int main (void) { socket_t sock1, sock2; int addrlen; char *buffer = (char*) malloc (BUF); sock1 = create_socket(AF_INET, SOCK_STREAM, 0); atexit(cleanup); bind_socket( &sock1, INADDR_ANY, 15000 ); listen_socket (&sock1); addrlen = sizeof (struct sockaddr_in); while (1) { accept_socket( &sock1, &sock2 ); do { printf ("Nachricht zum Versenden: "); fgets (buffer, BUF, stdin); TCP_send (&sock2, buffer, strlen (buffer)); TCP_recv (&sock2, buffer, BUF-1); printf ("Nachricht empfangen: %s\n", buffer); } while (strcmp (buffer, "quit\n") != 0); close_socket (&sock2); } close_socket (&sock1); return EXIT_SUCCESS; } Der Quellcode des Clients ist ähnlich simpel aufgebaut. Dieser versucht zunächst, eine Verbindung zum Server aufzubauen. Ist dies geglückt, wartet er auf eine Antwort vom Server. Schickt der Server dem Client eine Antwort, so wird diese auf die Standardausgabe ausgegeben. Jetzt ist der Client an der Reihe, dem Server eine Zeichenkette zu senden. Geben Sie hierfür »quit« an, beendet sich die Client-Anwendung und nimmt alle Aufräumarbeiten vor. Dass die Aufräumarbeiten (die Funktion cleanup()) durchgeführt werden, haben Sie mit der Standard-Funktion atexit() sichergestellt, die beim Beenden des Prozesses die Funktion cleanup() aufruft (was unter Linux/UNIX unbedeutend ist). Solch ein Cleanup wird generell gern in dieser Form verwendet. Dasselbe Cleanup wird übrigens auch beim Server eingerichtet und durchgeführt, sofern sich dieser beendet. Ansonsten findet ein reger Kommunikationsaustausch zwischen Server und Client statt. Hier sehen Sie den Quellcode für den Client: > /* client.c */ #include <string.h> #include "socketprx.h" #define BUF 1024 int main (int argc, char *argv[]) { socket_t sock; char *buffer = (char *)malloc (BUF); if( argc < 2 ){ printf("Usage: %s ServerAdresse\n", *argv); exit(EXIT_FAILURE); } sock = create_socket(AF_INET, SOCK_STREAM, 0); atexit(cleanup); connect_socket(&sock, argv[1], 15000); do { buffer[0] = '\0'; TCP_recv (&sock, buffer, BUF-1); printf ("Nachricht erhalten: %s\n", buffer); printf ("Nachricht zum Versenden: "); fgets (buffer, BUF, stdin); TCP_send (&sock, buffer, strlen (buffer)); } while (strcmp (buffer, "quit\n") != 0); close_socket (&sock); return EXIT_SUCCESS; } Abbildung 25.6 zeigt das Programm bei der Ausführung. Abbildung 25.6 Die Client-Anwendung unter MS-Windows bei der Ausführung Abbildung 25.7 Die Server-Anwendung unter MS-Windows bei der Ausführung Abbildung 25.8 Die Client-Anwendung unter Linux bei der Ausführung Abbildung 25.9 Die Server-Anwendung unter Linux bei der Ausführung ### 25.7.7 Ein UDP-Beispiel Bei unserem Layer wurden ja auch Funktionen zum Datenaustausch via UDP geschrieben. AuÃerdem wurde auch einiges zu UDP erwähnt, sodass ich Ihnen hier ein kleines Client/Server-Beispiel nicht vorenthalten will. Der Server wartet auf die Verbindung irgendeines Clients, der einen einfachen String als zweites Argument in der Kommandozeile versendet. Der Server gibt diese Zeichen mitsamt der lokalen Server-Uhrzeit auf die Standardausgabe aus und wartet anschlieÃend erneut wieder auf Daten am Port 1234 von irgendeinem Client. > /* udp_server.c */ #include <string.h> #include <time.h> #include "socketprx.h" #define LOCAL_SERVER_PORT 1234 #define BUF 255 int main (int argc, char *argv[]) { socket_t sock; char puffer[BUF]; time_t time1; char loctime[BUF]; char *ptr; /* Socket erzeugen */ sock = create_socket( AF_INET, SOCK_DGRAM, 0); atexit(cleanup); bind_socket(&sock, INADDR_ANY, LOCAL_SERVER_PORT); printf ("Warte auf Daten am Port (UDP) %u\n", LOCAL_SERVER_PORT); /* Server-Schleife */ while (1) { memset (puffer, 0, BUF); UDP_recv( &sock, puffer, BUF ); /* Zeitangaben präparieren */ time(&time1); strncpy(loctime, ctime(&time1), BUF); ptr = strchr(loctime, '\n' ); *ptr = '\0'; /* erhaltene Nachricht ausgeben */ printf ("%s: Daten erhalten: %s\n", loctime, puffer); } return EXIT_SUCCESS; } > /* udp_client.c */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "socketprx.h" #define BUF 1024 #define SERVER_PORT 1234 int main (int argc, char *argv[]) { socket_t sock; /* Kommandozeile auswerten */ if (argc < 3) { printf ("Usage: %s <server> <string>\n",argv[0]); exit (EXIT_FAILURE); } /* Socket erzeugen */ sock = create_socket( AF_INET, SOCK_DGRAM, 0); atexit(cleanup); bind_socket(&sock, INADDR_ANY, 0); UDP_send(&sock,argv[2],strlen(argv[2]),argv[1], SERVER_PORT); return EXIT_SUCCESS; } Abbildung 25.10 zeigt das Programm bei der Ausführung. Abbildung 25.10 Der UDP-Server im Einsatz unter Linux Abbildung 25.11 Die (UDP)Client-Anwendung unter Linux ### 25.7.8 Mehrere Clients gleichzeitig behandeln Einen gravierenden Nachteil allerdings hatten alle Server-Beispiele, die Sie bisher geschrieben haben. Alle Server sind nur für eine Client-Anfrage ausgelegt – sprich, die Server konnten nur einen Client gleichzeitig bearbeiten. Alle anderen Clients wurden in die Warteschlange gesteckt und mussten warten, bis der Server wieder für weitere Verbindungswünsche frei ist. Für Anwendungen wie Webserver, Chat-Programme, Spiele-Server etc. ist dieser Zustand unbrauchbar. Um diesen Zustand zu verbessern, gibt es mehrere Möglichkeiten, wobei sich hier die Varianten auf den verschiedenen Plattformen erheblich unterscheiden. Sinnvolle und mögliche Varianten wären: * die Verwendung von (Multi-)Threads – Dabei wird für jeden Client ein neuer Thread gestartet. Der »Nachteil« von Threads ist, dass es auf den verschiedenen Plattformen die verschiedensten Thread-Bibliotheken gibt und somit nur bedingt portabel sind. * die Verwendung von Prozessen – Hierbei wird für jeden Client ein neuer (Server–)Prozess gestartet – jeder Client bekommt hierbei praktisch seinen eigenen Server. Voraussetzung hierfür ist allerdings, dass Sie sich mit der Systemprogrammierung der entsprechenden Plattform auskennen. SchlieÃlich müssen die einzelnen Prozesse kontrolliert werden. Neben diesen Möglichkeiten gibt es selbstverständlich eine Reihe weiterer Verfahren, um mehrere Clients zu behandeln. Unter MS-Windows beispielsweise könnten Sie hierfür die WSA-Routinen WSAAsyncSelect() oder WSAEventSelect() verwenden. Bei Linux/UNIX hingegen würden sich hierfür auch asynchrone E/A-Routinen nach »POSIX«-Erweiterungen eignen. # »select()« – Eine portablere Alternative Neben den eben beschriebenen Möglichkeiten, die Sie verwenden können, um mehrere Clients zu bedienen, soll hier auf die Möglichkeit mit der Funktion select() etwas genauer eingegangen werden. Diese Funktion ist sowohl auf MS- als auch auf Linux/UNIX-Systemen vorhanden – und somit ein geeigneter Kandidat für eine portablere Lösung. Das Problem bei einem Server, wie Sie ihn bisher verwendet haben, ist, dass dieser immer nur auf einen Socket-Deskriptor gewartet hat und auch immer über einen Socket-Deskriptor Daten empfangen bzw. versendet hat. Wurde beim Server beispielsweise revc() aufgerufen, blockierte dieser Aufruf den Socket-Deskriptor so lange, bis der Client wirklich Daten an diesen gesendet hat. Natürlich kann man das Blockieren auch dadurch umgehen, dass man den Socket-Deskriptor als nicht-blockierend einrichtet (beispielsweise mit fcntl()). Allerdings sollten Sie bedenken, dass hierbei ständig überprüft wird, ob an einem Socket Daten vorliegen – das heiÃt, es wird in einer Schleife dauerhaft gepollt – was die CPU unnötig belastet. Mit der Funktion select() können Sie den Socket-Deskriptor so einrichten, dass nur dann CPU-Zeit benötigt wird, wenn auch wirklich Daten an einem Socket-Deskriptor vorliegen. Hier sehen Sie die Syntax zur Funktion select() unter Linux/UNIX: > // entsprechend nach POSIX 1003.1-2001 #include <sys/select.h> // entsprechend nach früheren Standards #include <sys/time.h> #include <sys/types.h> #include <unistd.h> int select( int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout ); Und hier ist die ähnliche Syntax unter MS-Windows: > int select( int n, fd_set FAR * readfds, fd_set FAR * writefds, fd_set FAR * exceptfds, const struct timeval FAR * timeout ); Mit dem ersten Parameter n geben Sie die GröÃe der folgenden Menge an. Hierfür wird gewöhnlich der Wert des höchsten (Socket-)Deskriptors plus eins angegeben. Sie sollten sich allerdings nicht darauf verlassen, dass hier automatisch eine aufsteigende und lückenlose Reihenfolge für die (Socket-)Deskriptoren vergeben wird. Welche Nummer der nächste (Socket-)Deskriptor verwendet, entscheidet immer noch das System. Daher empfiehlt es sich, jeden gesetzten (Socket-)Deskriptor mit dem zu vergleichen, der rein theoretisch der höchste ist. Die nächsten drei Parameter sind Zeiger auf die fd_sets, die zum Lesen, Schreiben oder auf Ausnahmen getestet werden. Sofern Sie einen der Parameter nicht verwenden wollen, können Sie hierfür NULL angeben. Drei getrennte Sets sind nötig, da man ja nicht alle (Socket-)Deskriptoren auf Lesen oder Schreiben testen möchte. Der am häufigsten verwendete Parameter (wie es auch im anschlieÃenden Beispiel der Fall ist) ist readfds. Mit diesem Parameter wird überprüft, ob auf den (Socket-)Deskriptoren Daten zum Lesen vorhanden sind. Das Gegenstück dazu ist der Parameter writefds. Hiermit können Sie die Beschreibbarkeit von (Socket–)Deskriptoren überprüfen – sprich, ob ein Deskriptor bereit ist, eine Ausgabe anzunehmen (diese Ãberprüfung wird beispielsweise gerne bei Pipes verwendet). Der dritte fd_set-Parameter, exceptfds, wird weitaus seltener verwendet. Mit ihm überprüfen Sie, ob bei einem (Socket-)Deskriptor irgendwelche besonderen Zustände (Ausnahmen) vorliegen. Dies wird beispielsweise bei Out-of-band-Daten (MSG_OOB) verwendet (siehe Manual-Page zu send() und/oder recv()). Nach dem Aufruf von select() wird diese Menge in Teilmengen der Filedeskriptoren verteilt, die die Bedingungen erfüllen. Mit dem letzten Parameter können Sie ein Timeout, eine Zeit im Format von Sekunden (tv_sec) und Mikrosekunden (tv_usec), einrichten. Diese Zeit wird dann abgewartet, bis eine bestimmte Bedingung eintritt. Sind Sie daran nicht interessiert, können Sie auch hier NULL angeben. Es gibt aber auch einen Nachteil, wenn sich select() vorzeitig verabschiedet (vor dem Ablauf der festgelegten Zeit). select() gibt keine Auskunft darüber, wie lange denn tatsächlich gewartet wurde. Dazu muss extra eine Funktion wie beispielsweise gettimeofday() aufgerufen werden. Die Funktion gibt die Anzahl der Filedeskriptoren zurück, die Ihre Bedingung erfüllt haben (einfach die Anzahl der (Socket-)Deskriptoren, die bereit sind). Wenn die Zeit abgelaufen ist (Timeout) wird 0 und bei einem Fehler des Funktionsaufrufs select()-1 zurückgegeben. Ein Problem bei select() ist, dass es mit Bitfeldern arbeitet – was somit abhängig vom Betriebssystem ist. Die BitfeldgröÃe bei BSD beispielsweise beträgt 256 und unter Linux 1024. Somit können auf BSD nur die ersten 256 und unter Linux 1024 Deskriptoren angesprochen werden. Unter MS-Windows kann dieser Wert sogar nur bis zu 64 Deskriptoren betragen. Wie viele Deskriptoren Sie nun tatsächlich pro Prozess verwenden können, ist mit der symbolischen Konstante FD_SETSIZE definiert. Natürlich macht es jetzt wenig Sinn, alle (Socket–) Deskriptoren zu überwachen. Zum Glück müssen Sie sich eigentlich recht wenig um diese Menge kümmern, da Ihnen der Datentyp fd_set die Arbeit zum Speichern der (Socket-)Deskriptoren abnimmt und einige Makros den Zugriff darauf erleichtern. Hier sehen Sie die Makros, um die Mengen zu bearbeiten: > FD_ZERO(fd_set *set); FD_SET(int element, fd_set *set); FD_CLR(int element, fd_set *set); FD_ISSET(int element, fd_set *set); Die Makros lassen sich recht schnell erklären. FD_ZERO() macht aus der Menge set eine leere Menge, FD_SET() fügt element der Menge set hinzu, und FD_CLR() entfernt element aus der Menge set. Mit FD_ISSET() können Sie überprüfen, ob element in der Menge set vorkommt (genauer gesagt: gesetzt ist). Das folgende Beispiel, ein einfacher TCP-Echo-Server, soll Ihnen die Funktion select() demonstrieren. Das Beispiel ist dem 1:1-Chat zwischen dem Server und dem Client recht ähnlich, den Sie in diesem Kapitel bereits geschrieben haben. Nur begnügen wir uns beim Server jetzt damit, dass dieser nur die Zeichenketten auf dem Bildschirm ausgibt und dem Client nicht antwortet. Allerdings gibt es den gravierenden Unterschied, dass der Server nun mehrere Clients »gleichzeitig« behandeln kann – genauer gesagt bis zu FD_SETSIZE Clients. Sobald auch hier ein Client die Zeichenfolge »quit« sendet, entfernt der Server den Client (genauer den (Socket-)Deskriptor) aus der Menge. Im Beispiel wurde aus Ãbersichtlichkeitsgründen darauf verzichtet, die select()-Abhandlung in unseren Layer SOCKETPRX zu implementieren. In der Praxis wäre dies allerdings sehr sinnvoll, da die Verwendung von select() doch zu einem der etwas komplizierteren Teile der Programmierung gehört. Dank des Layers SOCKETPRX kann ich select() erheblich leichter abhandeln als ohne. Hier folgt der gut dokumentierte Source-Code zum Server, der nun die Abfragen mehrerer Clients auf einmal abarbeiten kann: > /* multi_server.c */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "socketprx.h" #define BUF 1024 int main (void) { socket_t sock1, sock2, sock3; int i, ready, sock_max, max=-1; int client_sock[FD_SETSIZE]; fd_set gesamt_sock, lese_sock; char *buffer = (char*) malloc (BUF); sock_max = sock1 = create_socket(AF_INET, SOCK_STREAM, 0); atexit(cleanup); bind_socket( &sock1, INADDR_ANY, 15000 ); listen_socket (&sock1); for( i=0; i<FD_SETSIZE; i++) client_sock[i] = -1; FD_ZERO(&gesamt_sock); FD_SET(sock1, &gesamt_sock); for (;;) { /* immer aktualisieren */ lese_sock = gesamt_sock; /* Hier wird auf die Ankunft von Daten oder * neuer Verbindungen von Clients gewartet. */ ready = select( sock_max+1, &lese_sock, NULL, NULL, NULL ); /* Eine neue Client-Verbindung ...? */ if( FD_ISSET(sock1, &lese_sock)) { accept_socket( &sock1, &sock2 ); /* freien Platz für (Socket-)Deskriptor * in client_sock suchen und vergeben */ for( i=0; i< FD_SETSIZE; i++) if(client_sock[i] < 0) { client_sock[i] = sock2; break; } /* mehr als FD_SETSIZE Clients sind nicht möglich */ if( i == FD_SETSIZE ) error_exit("Server überlastet - zu viele Clients"); /* den neuen (Socket-)Deskriptor zur * (Gesamt)Menge hinzufügen */ FD_SET(sock2, &gesamt_sock); /* select() benötigt die höchste * (Socket-)Deskriptor-Nummer. */ if( sock2 > sock_max ) sock_max = sock2; /* höchster Index für client_sock * für die anschlieÃende Schleife benötigt */ if( i > max ) max = i; /* ... weitere (Lese-)Deskriptoren bereit? */ if( --ready <= 0 ) continue; //Nein ... } //if(FD_ISSET ... /* Ab hier werden alle Verbindungen von Clients auf * die Ankunft von neuen Daten überprüft. */ for(i=0; i<=max; i++) { if((sock3 = client_sock[i]) < 0) continue; /* (Socket-)Deskriptor gesetzt ... */ if(FD_ISSET(sock3, &lese_sock)){ /* ... dann die Daten lesen */ TCP_recv (&sock3, buffer, BUF-1); printf ("Nachricht empfangen: %s\n", buffer); /* Wenn quit erhalten wurde ... */ if (strcmp (buffer, "quit\n") == 0) { /* ... hat sich der Client beendet. */ close_socket (&sock3); //Socket schlieÃen FD_CLR(sock3, &gesamt_sock); //aus Menge löschen client_sock[i] = -1; //auf -1 setzen printf("Ein Client hat sich beendet\n"); } /* Sind noch lesbare Deskriptoren vorhanden ...? */ if( --ready <= 0 ) break; //Nein ... } } } // for(;;) return EXIT_SUCCESS; } Und jetzt folgt noch der Quellcode zur entsprechenden Client-Anwendung: > /* multi_client.c */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "socketprx.h" #define BUF 1024 int main (int argc, char *argv[]) { socket_t sock; char *buffer = (char *)malloc (BUF); if( argc < 2 ){ printf("Usage: %s ServerAdresse\n", *argv); exit(EXIT_FAILURE); } sock = create_socket(AF_INET, SOCK_STREAM, 0); atexit(cleanup); connect_socket(&sock, argv[1], 15000); do { buffer[0] = '\0'; printf ("Nachricht zum Versenden: "); fgets (buffer, BUF, stdin); TCP_send (&sock, buffer, strlen (buffer)); } while (strcmp (buffer, "quit\n") != 0); close_socket (&sock); return EXIT_SUCCESS; } Abbildung 25.12 zeigt das Programm bei der Ausführung. Abbildung 25.12 Der Server kann jetzt mehrere Anfragen (Clients) bearbeiten. Abbildung 25.13 Einer von zwei gerade aktiven Clients Abbildung 25.14 Der andere der beiden aktiven Clients zur selben Zeit # 25.8 Weitere Anmerkungen zur Netzwerkprogrammierung ## 25.8 Weitere Anmerkungen zur Netzwerkprogrammierung Mit diesem kleinen Kapitel haben Sie sich jetzt den Grundstein zur Netzwerkprogrammierung gelegt. Bedenken Sie aber, dass dieses Thema ein noch viel gröÃeres Spektrum umfasst, als ich hier beschrieben habe. Dazu könnte (will) man ein ganzes Buch schreiben (an mir soll‘s nicht liegen ;-)). Bevor Sie sich jetzt in das Abenteuer stürzen, eigene kleine Programme mit Netzwerkfunktionalität zu schreiben, möchte ich Sie hier noch in ein paar Abschnitten auf einige Dinge hinweisen, auf die Sie besonders achten sollten (bzw. mit denen Sie sich noch intensiver auseinandersetzen sollten) – insbesondere, wenn Ihre Anwendung nicht so funktioniert, wie Sie es gerne hätten. ### 25.8.1 Das Datenformat In den Beispielen, die Sie hier erstellt haben, wurden lediglich Zeichenketten verschickt. Meistens liegen die Daten aber nicht in einem solch bequemen Format vor. Wenn Sie beispielsweise Ganzzahlen oder Gleitpunktzahlen versenden wollen, verwenden Sie am besten sscanf() und snprintf(). Und was ist mit binären Strukturen (struct)? Auch hier empfiehlt es sich, die komplette Struktur in eine Zeichenkette zu konvertieren, bevor Sie diese versenden. Auf der anderen Seite müssen selbstverständlich ebenfalls bestimmte Vorkehrungen getroffen werden. Sicherlich, letztendlich entscheiden Sie, wie die Daten zwischen Client und Server hin- und hergeschickt werden. Allerdings sollten Sie bedenken, dass Sie nicht immer wissen, auf was für einen Rechner die Daten übertragen werden. Schicken Sie von einem Little-Endian-Rechner einen Integer an ein Big-Endian-System, sind Probleme vorprogrammiert. Oder was ist, wenn Sie von einem 64-Bit-Rechner einen Integer an einen 32-Bit-Rechner verschicken? Sie wissen also nie genau, welche GröÃe die Datentypen int, long und short auf der Gegenseite haben. Zwar gibt es (seit der Einführung des C99-Standards) die unabhängigen Typen wie beispielsweise int8_t, int16_t etc. und uint8_t etc. in der Headerdatei <stdint.h>, was aber recht wenig nützt, weil dieser Standard von einigen Compiler-Herstellern (insbesondere auf Windows-Systemen) unzureichend bis überhaupt nicht beachtet wird. Daher die Empfehlung: Senden Sie numerische Daten immer im Textformat an die Gegenseite. Natürlich setzt dies voraus, dass die Gegenseite denselben Zeichensatz verwendet. Wenn Sie einen String an einen Rechner schicken, auf dem sich nur japanische Schriftarten befinden, kommt nichts dabei raus. Ebenso müssen Sie unsere landestypischen Umlaute berücksichtigen, die meist auf einem Rechner, der beispielsweise in der USA steht, auch nicht richtig dargestellt werden können. Der Nachteil: Es wird Bandbreite verschwendet. Eine 64-Bit-Nummer beispielsweise kann nämlich über 20 Zeichen lang sein, während im Binärformat gerade mal 8 Zeichen dafür benötigt werden. Aber es ist Ihre Entscheidung! ### 25.8.2 Der Puffer Bisher mussten Sie sich nie so richtig um die Pufferung der Daten kümmern. Beispielsweise hat Ihnen bei Funktionen wie fgets() oder fputs() das System die Pufferung abgenommen. Sie mussten hierbei nur angeben, wie groà dieser Puffer sein sollte. In der Netzwerkprogrammierung müssen Sie sich nun selbst darum kümmern. Mit den Funktionen send()/sendto() und recv()/recvfrom() können bei den Sockets erst mal weniger Bytes ein- bzw. ausgegeben werden als angenommen. Das Problem ist, dass das System (der Kernel) für das Socket eine bestimmte PuffergröÃe vorgibt. Das bedeutet: Wenn der Puffer voll ist, liest recv()/recvfrom() bzw. schreibt send()/sendto() aus diesem bzw. in diesen Puffer – selbst dann, wenn noch nicht alle gewünschten Daten ausgelesen bzw. geschrieben wurden. Wenn Sie die Daten in Form eines char-Arrays mit einfachem Text übertragen, dürften Sie keine Probleme mit der Pufferung bekommen, sofern Sie einen String ordentlich mit \0 abschlieÃen. Sobald allerdings binäre Daten übertragen werden sollen, gibt es Probleme damit. Bei binären Daten können Sie sich nicht darauf verlassen, dass diese mit einem \0 abgeschlossen werden – weshalb Sie sich hierbei selbst um das letzte Zeichen kümmern müssen. Welche PuffergröÃe Sie verwenden, bleibt Ihnen überlassen und hängt vom Anwendungsfall ab. Allerdings macht ein byteweiser Puffer genauso wenig Sinn wie ein überdimensional groÃer Puffer. Es hat sich bewährt, eine PuffergröÃe von 512 oder 1024 KB zu verwenden. ### 25.8.3 Portabilität Sie haben in diesem Kapitel gesehen, wie man mit einem abstrakten Layer eine portable Anwendung (nicht nur) für die Netzwerkprogrammierung erstellen kann. Mit Linux/UNIX und MS-Windows haben Sie in den Beispielen eine recht groÃe Zielgruppe eingeschlossen. Bedenken Sie allerdings, dass es auch noch andere Systeme gibt. Gemeint sind beispielsweise Systeme wie QNX oder SGI IRIX. Zwar sind die Unterschiede der allgemeinen Socket-Programmierung nicht allzu gravierend, dennoch müssen Sie sich auch diesbezüglich gegebenenfalls schlau machen, welche Differenzen es dabei gibt. ### 25.8.4 Von IPv4 nach IPv6 Da IPv6 noch nicht eingeführt wurde (und eine Einführung noch nicht in Sicht ist), wurden seine Eigenheiten in den vorangegangenen Abschnitten nicht näher behandelt. Allerdings gibt es hierzu eigentlich auch gar nicht viel zu berichten. Daher folgt hier eine kurze Zusammenfassung für den Fall der Fälle, die zeigt, wie Sie Ihre Anwendungen von IPv4 nach IPv6 portieren könnten. # Konstanten Die IPv4-Konstanten AF_INET bzw. PF_INET wurden durch AF_INET6 bzw. PF_INET6 ersetzt. Hierbei muss eigentlich nur die Konstante um eine 6 erweitert werden. Es ist auch kein Fehler, wenn Sie auch bei einer IPv4-Software gleich die neuen Konstanten verwenden, da ein Programm, das auf IPv6 portiert wurde, auch weiterhin auf IPv4-Rechnern läuft (vorausgesetzt, der Rechner ist »dual-stacked«, was in Zukunft bei IPv6-fähigen Rechnern immer der Fall sein sollte). Was sich auch verändert hat, ist die Konstante INADDR_ANY, die beim Binden von Sockets an einen Port angeben wird. Sie bedeutet, dass Pakete von jedem Interface angenommen werden. Ein wenig ungewöhnlich ist, dass die neue Konstante kleingeschrieben wird – in6addr_any. Der Grund hierfür: Die alte Struktur in_addr bestand nur aus einem unsigned long int s_addr, und somit war die Konstante INADDR_ANY auch nur eine Zahl. Da die Adresse bei IPv6 128 Bit breit ist, ist dies nicht mehr möglich (da kein portabler Datentyp mit dieser Breite existiert), weshalb es sich nun um ein Array handelt: > struct in6_addr { union { uint8_t u6_addr8[16]; uint16_t u6_addr16[8]; uint32_t u6_addr32[4]; } in6_u; #define s6_addr in6_u.u6_addr8 #define s6_addr16 in6_u.u6_addr16 #define s6_addr32 in6_u.u6_addr32 }; # Strukturen Nachdem in_addr durch in6_addr ersetzt wurde (siehe oben), ist es auch nötig, die Struktur sockaddr_in anzupassen: > struct sockaddr_in6 { sa_family_t sin6_family /* Adress-Familie - AF_INET6 */ in_port_t sin6_port; /* Port Transportschicht # */ uint32_t sin6_flowinfo; /* IPv6 Datenfluss-Informationen */ struct in6_addr sin6_addr; /* IPv6 Adresse */ uint32_t sin6_scope_id; /* IPv6 Scope-Kennung */ }; Hier wurde nicht nur die Adressstruktur verändert, es wurden auch noch die zusätzlichen Strukturvariablen sin6_flowinfo und sin6_scope_id hinzugefügt. # Funktionen Der GroÃteil der Socket-API-Funktionen ist gleich geblieben. Verändert (hinzugefügt) wurden lediglich die meisten Adressauflösungs- und Konvertierungsfunktionen. So werden die Funktionen inet_aton() bzw. inet_ntoa() durch die Funktionen inet_pton() bzw. inet_ntop() ersetzt. Da diese neuen Funktionen jetzt nicht mehr auf Zahlen operieren, sondern auf den konkreten Adressstrukturen (z. B. in6_addr), unterstützen sie auch beliebige Adressfamilien. Noch wichtiger sind die neu hinzugekommenen Funktionen getaddrinfo() und getnameinfo(). Diese wurden als Ersatz für die Funktionen gethostbyname()/gethostbyaddr() und getipnodebyname()/getipnodebyaddr() eingeführt und haben den Vorteil, dass sie direkt sockaddr-Strukturen bearbeiten. Des Weiteren wurde noch die Funktion gethostbyname2() hinzugefügt, bei der es sich allerdings nur um eine reine GNU-Extension handelt! ### 25.8.5 RFC-Dokumente (Request for Comments) Sie wollen einen HTTP-, einen FTP- oder einen SMTP-Server bzw. einen Client erstellen, der damit kommuniziert, und wissen nicht, wo Sie anfangen sollen. Dies ist eine beliebte Frage in den Foren. Wie Sie bereits erfahren haben, findet die Kommunikation zwischen dem Server und Client über Protokolle statt (vergleichbar mit den verschiedenen Sprachen dieser Welt). Ein Webclient und ein Webserver beispielsweise unterhalten sich anders als ein Mailclient und ein Mailserver. All diese Standard-Protokolle werden in den RFCs (Requests for Comments) gesammelt. RFCs sind eine Reihe von technischen Dokumentationen zum Internet, die ihren Ursprung zu ARPANET-Zeiten 1969 hatten. Einen gewaltigen Fundus zur RFC-Sammlung finden Sie im Internet unter http://www.ietf.org/ (The Internet Engineering Task Force). ### 25.8.6 Sicherheit Das Wichtigste kommt zum Schluss. Mit der Netzwerkprogrammierung in C haben Sie auch das gefährlichste Kapitel in C kennengelernt. Die meisten Programme, die angegriffen werden, sind nicht Ihr Editor oder Ihre Entwicklungsumgebung, sondern die Programme, die mit dem Netz verbunden und somit meistens auch für alle erreichbar sind. Beispielsweise kann ein Buffer-Overflow bei einer Netzwerk-Anwendung sehr böse Folgen haben (ein beliebtes Lästerbeispiel ist der Internet Explorer alias »Internet Exploiter«). Des Weiteren sollten Sie beachten, dass die Daten, die Sie über ein Netzwerk versenden, jederzeit abgefangen werden können. Daher empfiehlt es sich, bei sicherheitsrelevanten Daten (beispielsweise Kundendaten) diese verschlüsselt zu versenden. Die Daten können zwar weiterhin abgefangen werden, aber bei einer guten Verschlüsselung sind diese Daten für den »Sniffer« nicht mehr lesbar – es sei denn, er kann die Verschlüsselung knacken. # 26.2 Programmiertechniken der Parallelisierung ## 26.2 Programmiertechniken der Parallelisierung Als Programmierer können Sie im Grunde mehrere Wege gehen, um Ihre Anwendung zu parallelisieren. ### 26.2.1 Automatische Parallelisierung Zunächst gäbe es die Möglichkeit, das Parallelisieren dem Compiler zu überlassen. Eine solche automatische Parallelisierung wird derzeit nur vom Intel-Compiler angeboten. Hierzu setzt man bei der Kompilierung die Option /Qparallel für Windows und /parallel für Linux. Bei der Ãbersetzung sucht der Compiler jetzt nach einfachen Schleifen (beispielsweise Grafikroutinen), die er in mehreren Threads parallel ausführen kann. Wer hier jetzt eine Compiler-Optimierung wie mit den Optionen -O1 etc. sieht, hat recht. Im Grunde ist diese Option des Compilers nichts anderes als das. Bei Tests ist es mir auÃerdem nicht gelungen, mehr als zwei parallele Threads zu erzeugen. ### 26.2.2 Halbautomatische Parallelisierung Neben der Möglichkeit, parallele Anwendungen mithilfe des Intel-Compilers automatisch zu erstellen, gibt es noch eine halbautomatische Möglichkeit (wenn man das so sagen darf). »Halbautomatisch« deswegen, weil hierbei der Code nicht verändert, sondern nur ergänzt werden muss. Hierzu verwendet man OpenMP, eine Programmierschnittstelle, die seit 1997 von verschiedenen Hardware- und Compiler-Herstellern zur Shared-Memory-Programmierung auf Multiprozessor-Rechnern verwendet wird. Ein Vorteil von OpenMP ist es, dass die Synchronisation der Threads implizit erfolgt. Allerdings schränkt dieser Vorteil den Grad der Parallelisierung erheblich ein. Des Weiteren lässt sich OpenMP nur für Shared-Memory-Systeme verwenden (wie dies beispielsweise bei den Dual-Core-CPUs der Fall ist). Für die Parallelisierung werden pragma-Direktiven verwendet, weshalb in dem Fall, dass ein Compiler OpenMP nicht unterstützt, keine Fehlermeldungen ausgegeben werden. OpenMP ist auf vielen gängigen Compilern vorhanden (MS Visual Studio etc.). Auch unter Linux wird der GCC unterstützt – dies allerdings erst ab der Version 4.2, was bedeutet, dass Sie den entsprechenden Snapshot (nach-)installieren müssen. Auch der Intel-Compiler (erhältlich für Linux und Windows) unterstützt OpenMP. OpenMP ist somit auch eine interessante und einfache Möglichkeit der (halbautomatischen) Parallelisierung, die sich allerdings wegen der Vereinfachungen recht schlecht skalieren lässt. Mehr Informationen dazu finden Sie auf der Webseite von OpenMP unter http://www.openmp.org/. ### 26.2.3 Echte Parallelisierung Dann gibt es noch den Weg der echten Thread-Programmierung. Allerdings ist die Multithread-Programmierung nicht unbedingt eine einfache Sache. Mehrere Threads bedeuten häufig auch mehr Aufwand bei der Programmerstellung. Gewöhnlich müssen Threads auch synchronisiert werden. SchlieÃlich stellt jeder Thread so etwas wie eine eigene Anwendung dar. Trotzdem reiÃt, wenn ein Thread beispielsweise abstürzt, dieser alle anderen Threads mit ins Verderben. Thread-Bibliotheken gibt es viele. Den Windows-Entwicklern werden da einige hausgemachte Lösungen für Win32, MFC oder das .NET-Framework mitgeliefert. Wer reine Windows-Anwendungen schreibt, der dürfte damit sehr zufrieden sein. Soll es aber plattformübergreifend sein, greift man gewöhnlich zur POSIX-Thread-Bibliothek. Diese Spezifikation beschreibt den POSIX-Standard 1003.1c oder kurz und einfach Pthreads. Auch in diesem Buch greifen wir auf die POSIX-Threads zurück, um hier die Erwartungen eines jeden Lesers unabhängig von der Systemangehörigkeit zu erfüllen. Ein Prozess ist das, was Sie bei den bisherigen Beispielen des Buches immer erstellt haben – also ein Programm bei seiner Ausführung. Diesem Programm steht zum Zeitpunkt seiner Ausführung die komplette Verwaltungseinheit des Betriebssystems zur Verfügung, als wäre es das einzige Programm, das ausgeführt wird. Zum Zeitpunkt der Ausführung erhält ein Prozess somit die volle Aufmerksamkeit der CPU. Eine solche alleinige Verfügbarkeit ist natürlich bei einem Multitasking-Betriebssystem zeitlich begrenzt. Ãblicherweise laufen auf einem Betriebssystem mehrere Prozesse »gleichzeitig« ab. Auch wenn Sie selbst noch kein Programm gestartet haben, laufen bereits viele Dienste im Hintergrund ab (unter Linux/Unix werden diese auch als Dämonprozesse bezeichnet). Egal welches Programm Sie nun ausführen, jede Anwendung bekommt eine gewisse Rechenzeit der CPU zur Verfügung gestellt, bevor die CPU die Rechenzeit einem anderen Prozess widmet (siehe Abbildung 26.1). Abbildung 26.1 Prozesse werden Task für Task abgearbeitet. Mit dieser Technik, dem Multitasking, hat es den Anschein, dass alle Prozesse quasi gleichzeitig ablaufen – was natürlich nicht möglich ist, da pro CPU immer nur ein Task ausgeführt werden kann. Im ersten Moment besteht vorerst gar kein Unterschied zwischen einem Prozess und einem Thread, denn letztendlich besteht ein Prozess mindestens aus einem Thread. Ferner endet ein Prozess, wenn sich alle Threads beenden. Somit ist der eine Prozess (dieser eine Prozess ist der erste Thread, auch »Main Thread« bzw. »Haupt-Thread« genannt) verantwortlich für die gleichzeitige Ausführung mehrerer Threads – da doch Threads auch nur innerhalb eines Prozesses ausgeführt werden. Der gravierende Unterschied zwischen den Threads und den Prozessen besteht darin, dass Threads unabhängige Befehlsfolgen innerhalb eines Prozesses sind. Man könnte auch sagen, Threads sind in einem Prozess gefangen oder verkapselt – im goldenen Käfig eingeschlossen (siehe Abbildung 26.2). Abbildung 26.2 Ein Prozess (Main-Thread) startet mehrere (Unter-)Threads. Prozesse werden gegenüber Threads immer als schwergewichtig dargestellt. Das kommt daher, dass bei der Erstellung eines Prozesses der komplette Namensraum dupliziert werden muss. Diesen Aufwand spart man bei der Verwendung von Threads, da diese in einem gemeinsamen Adressraum ablaufen. Somit stehen den einzelnen Threads dasselbe Codesegment, Datensegment, der Heap und alle anderen Zustandsdaten, die ein »gewöhnlicher« Prozess besitzt, zur Verfügung – was somit auch die Arbeit beim Austausch von Daten und bei der Kommunikation untereinander erheblich erleichtert. Weil aber kein Speicherschutzmechanismus unter den Threads vorhanden ist, bedeutet dies auch, dass ein Thread, wenn er abstürzt, alle anderen Threads mit abstürzen lässt. Einen Vergleich des Verwaltungsaufwandes zwischen den Threads und Prozessen finden Sie in den Abbildungen 26.3 und 26.4. Abbildung 26.3 Das beinhaltet jeder einzelne Prozess. Abbildung 26.4 Threads hingegen teilen sich (abgesehen vom Stacksegment und dem Befehlszähler) die Ressourcen. In Abbildung 26.4 lässt sich schön erkennen, dass sich Threads den Adressraum teilen. Allerdings macht gerade dies die Threads etwas aufwendiger zu programmieren, denn die Threads teilen sich hierbei die globalen Variablen, geöffneten Dateien (beispielsweise Filedeskriptor) – eben alle globalen Ressourcen auÃerhalb eines Threads –, weshalb hierbei gewisse Synchronisationsmechanismen nötig sind. Um POSIX-Threads verwenden zu können, müssen Sie die Pthread-Bibliothek erst einmal installieren. Unter Linux lässt sie sich bequem mit dem jeweiligen Paketmanager nachinstallieren. Auch für Windows lässt sich die Pthread-Bibliothek ohne groÃen Aufwand nachinstallieren. Erste Anlaufstelle sollte hierbei die Webseite http://sourceware.org/pthreads-win32/ sein. Damit ich hier nicht mehrere Seiten für die Anleitung zur Installation und Verwendung der Pthread-Bibliothek verschwende, finden Sie auf der Buch-CD eine Beschreibung, wie Sie Anwendungen mit der Pthread-Bibliothek erstellen können. Dabei wird neben Linux auch auf die Verwendung von Pthreads mit Entwicklungsumgebungen wie Code::Blocks und Visual C++ von Microsoft eingegangen. ### 26.4.1 Ein serielles Beispiel Um Ihnen die Threads zu demonstrieren, habe ich ein absolut einfaches Beispiel verwendet. Wir verwenden zwei int-Arrays mit 100.000 Elementen mit absteigendem Wert – was bedeutet, dass alle Elemente der beiden Arrays sortiert werden müssen. Hierbei geht es mir nur darum, zwei CPU-rechenintensive Aufgaben zu beschleunigen. Als Sortieralgorithmus habe ich den etwas langsameren Bubblesort verwendet. Folgendes Beispiel soll anschlieÃend parallel erstellt werden: > /* bubblesort.c */ #include <stdio.h> #include <stdlib.h> /* 100000 Elemente */ #define MAX 100000 /* ein Array von groÃen zu kleinen Werten */ int test_array1[MAX]; int test_array2[MAX]; /* in umgekehrter Reihenfolge erstellen */ void init_test_array(int *array) { int i, j; for(i = MAX,j=0; i >= 0; i--,j++) array[j] = i; } static void *bubble1(void* val) { int i, temp, elemente=MAX; while(elemente--) for(i = 1; i <= elemente; i++) if(test_array1[i-1] > test_array1[i]) { temp=test_array1[i]; test_array1[i]=test_array1[i-1]; test_array1[i-1]=temp; } } static void *bubble2(void* val) { int i, temp, elemente=MAX; while(elemente--) for(i = 1; i <= elemente; i++) if(test_array2[i-1] > test_array2[i]) { temp=test_array2[i]; test_array2[i]=test_array2[i-1]; test_array2[i-1]=temp; } } int main (void) { int i, j; init_test_array(test_array1); init_test_array(test_array2); bubble1(NULL); bubble2(NULL); /* Ausgabe in eine Textdatei */ freopen("myoutput.txt", "w+", stdout); for(i = 0; i < MAX; i++) printf("[%d-%d]", test_array1[i], test_array2[i]); return EXIT_SUCCESS; } Die sortierten Elemente finden Sie anschlieÃend in der Datei myoutput.txt, im selben Verzeichnis, in dem das Programm ausgeführt wird, wieder. Bei der Ausführung des Programms wird meine CPU (mit Dual-Core) ca. 50 % ausgelastet (siehe Abbildung 26.5). Neben der Anzeige der CPU-Auslastung wird auch noch der Verlauf beider CPUs bei der Auslastung angezeigt. Auch hieran kann man erkennen, dass nur eine CPU damit beschäftigt ist, das Array zu sortieren. Natürlich habe ich auch die einzelnen Prozesse überwacht, sodass mir nicht ein anderer Prozess mit einer rechenintensiven Anwendung dazwischenkommt. Abbildung 26.5 »bubblesort.c« bei der Ausführung ohne Threads Bei mehrfacher Ausführung des Programms lag die durchschnittliche Ausführzeit immer zwischen 25 und 28 Sekunden (was natürlich auch von der Rechenleistung abhängt). Das Ziel dieses Beispiels soll es nun sein, mithilfe der POSIX-Thread-Bibliothek, die Sortierung der beiden Arrays parallel auszuführen – sprich, jede CPU soll hier die Sortierung eines Arrays durchführen. Hierdurch versprechen wir uns eine erheblich schnellere Ausführzeit des Programms. ### 26.4.2 Das Grundgerüst für ein Programm mit mehreren Threads Bevor Sie das Programm zum Sortieren der Arrays parallel machen werden, sollen hier die grundlegenden Funktionen von Pthreads etwas näher beschrieben werden, die dazu nötig sind. # »pthread_create« – Einen neuen Thread erzeugen Einen neuen Thread können Sie mit der Funktion pthread_create() erzeugen: > #include <pthread.h.> int pthread_create( pthread_t *thread, const pthread_attr_t *attribute, void *(*funktion)(void *), void *argumente ); Jeder Thread hat eine eigene Identifikationsnummer vom Datentyp pthread_t, die in der Adresse des ersten Parameters von pthread_create() abgelegt wird. Attribute für den Thread können Sie mit dem zweiten Parameter vergeben. Wird hierfür NULL angegeben, werden die Standard-Attribute verwendet. Auf die Attribute eines Threads wird gesondert eingegangen. Mit dem dritten Parameter geben Sie die »Funktion« für den Thread selbst an – hierbei handelt es sich um den eigentlichen neuen Thread. Hierzu muss die Anfangsadresse der Funktion angegeben werden. Die Argumente für den Thread vom dritten Parameter können Sie mit dem vierten Parameter übergeben. Gewöhnlich wird dieses Argument verwendet, um Daten an den Thread zu übergeben. In der Praxis handelt es sich hierbei meistens um eine Strukturvariable. # Einen Thread beenden Um einen Thread zu beenden, gibt es im Grunde zwei Möglichkeiten: Entweder man verwendet funktionstypisch return oder die Funktion pthread_exit. In beiden Fällen muss der Rückgabewert vom Typ void* sein. Die Syntax zu pthread_exit() sieht so aus: > #include <pthread.h.> void pthread_exit( void * wert ); Mit den beiden Möglichkeiten wird nur der jeweilige Thread beendet. Den Rückgabewert können Sie anschlieÃend mit der Funktion pthread_join abfragen. Sollte allerdings irgendwo im Programm ein beliebiger Thread die Standard-Funktion exit() aufrufen, so bedeutet dies das Ende aller Threads einschlieÃlich des Haupt-Threads. Damit Sie sich nach der Beendigung eines Threads nicht noch um Reinigungsarbeiten wie das Freigeben der Ressourcen kümmern müssen, können Sie mit den Funktionen pthread_cleanup_push() und pthread_cleanup_pop() einen Exit-Handle einrichten. Ein solcher eingerichteter Handle wird dann immer ausgeführt, wenn ein Thread mit pthread_exit oder return beendet wurde. Im Grunde kann man diese Funktionen mit der Standardbibliotheksfunktion atexit() vergleichen. Anhand der Endung _push und _pop kann man schon erahnen, dass auch hier das Prinzip des Stacks verwendet wird. Hier die Syntax der beiden Funktionen: > #include <pthread.h.> void pthread_cleanup_push( void (*function)(void *), void *arg ); void pthread_cleanup_pop( int exec ); Mit pthread_cleanup_push() richten Sie den Exit-Handle ein. Als ersten Parameter geben Sie die Funktion an, die ausgeführt werden soll. Für die Argumente, die Sie der Funktion übergeben wollen, wird der zweite Parameter verwendet. Den zuletzt eingerichteten Exit-Handle können Sie wieder mit der Funktion pthread_cleanup_pop() vom Stack entfernen. Geben Sie allerdings einen Wert ungleich 0 als Parameter exec an, so wird diese Funktion zuvor noch ausgeführt, was bei einer Angabe von 0 nicht gemacht wird. # »pthread_join« – Warten auf das Thread-Ende Um aus dem Haupt-Thread auf das Ende und den Rückgabewert einzelner Threads zu warten, wird die Funktion pthread_join() verwendet: > #include <pthread.h.> int pthread_join( pthread_t thread, void **thread_return ); pthread_join() hält den aufrufenden Thread (meistens den Haupt-Thread), der einen Thread mit pthread_create erzeugt hat, so lange an, bis der Thread thread vom Typ pthread_t beendet wurde. Der Exit-Status (bzw. Rückgabewert) des Threads wird an die Adresse von thread_return geschrieben. Sind Sie nicht am Rückgabewert interessiert, können Sie hier auch NULL verwenden. Ein Thread, der sich beendet, wird eben so lange nicht »freigegeben« bzw. als beendeter Thread anerkannt, bis ein anderer Thread pthread_join aufruft. Daher sollte man für jeden erzeugten Thread einmal pthread_join aufrufen, es sei denn, man hat einen Thread mit pthread_detach »abgehängt«. # Ein paralleles Beispiel Mit diesen wenigen Funktionen ist es nun möglich, eine echte parallele Anwendung zu erstellen. Hierzu folgt das Beispiel zum Sortieren der Arrays mit Bubblesort – mit dem Unterschied zum Beispiel zuvor, dass jetzt jede CPU ein Array zum Sortieren bekommt. > /* thread1.c */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> /* 100000 Elemente */ #define MAX 100000 /* ein Array von groÃen zu kleinen Werten */ int test_array1[MAX]; int test_array2[MAX]; /* in umgekehrter Reihenfolge erstellen */ void init_test_array(int *array) { int i, j; for(i = MAX,j=0; i >= 0; i--,j++) array[j] = i; } // Thread 1 static void *bubble1(void* val) { static int i, temp, elemente=MAX; printf("Thread bubble1() wurde gestartet\n"); while(elemente--) for(i = 1; i <= elemente; i++) if(test_array1[i-1] > test_array1[i]) { temp=test_array1[i]; test_array1[i]=test_array1[i-1]; test_array1[i-1]=temp; } printf("Thread bubble1() wurde beendet\n"); // Der Rückgabewert interessiert uns nicht. return NULL; } // Thread 2 static void *bubble2(void* val) { static int i, temp, elemente=MAX; printf("Thread bubble2() wurde gestartet\n"); while(elemente--) for(i = 1; i <= elemente; i++) if(test_array2[i-1] > test_array2[i]) { temp=test_array2[i]; test_array2[i]=test_array2[i-1]; test_array2[i-1]=temp; } printf("Thread bubble2() wurde beendet\n"); // Der Rückgabewert interessiert uns nicht. return NULL; } int main (void) { pthread_t thread1, thread2; int i, rc; // Ausgabe in eine Textdatei freopen("myoutput.txt", "w+", stdout); printf("Haupt-Thread main() wurde gestartet\n"); // beide Arrays mit Werten initialisieren init_test_array(test_array1); init_test_array(test_array2); // Thread 1 erzeugen rc = pthread_create( &thread1, NULL, &bubble1, NULL ); if( rc != 0 ) { printf("Konnte Thread 1 nicht erzeugen\n"); return EXIT_FAILURE; } // Thread 2 erzeugen rc = pthread_create( &thread2, NULL, &bubble2, NULL ); if( rc != 0 ) { printf("Konnte Thread 2 nicht erzeugen\n"); return EXIT_FAILURE; } // Main-Thread wartet auf beide Threads. pthread_join( thread1, NULL ); pthread_join( thread2, NULL ); // das Ergebnis der Sortierung in die Datei // myoutput.txt schreiben for(i = 0; i < MAX; i++) { printf("[%d-%d]", test_array1[i], test_array2[i]); } printf("\nHaupt-Thread main() wurde beendet\n"); return EXIT_SUCCESS; } Die Ausführung des Programms an sich entspricht dem seriellen Beispiel. Die Arrays werden hier ebenfalls sortiert, und das Ergebnis wird in die Datei myoutput.txt geschrieben. Uns interessiert hierbei allerdings eher die Auslastung der CPUs und natürlich die Zeit, die diese Sortierung mit der parallelen Version benötigt. Ein Blick auf die Auslastung der CPU zeigt jetzt das gewünschte Ergebnis. Die beiden CPUs sind beide parallel zu 100 % ausgelastet und verrichten auch gleichzeitig ihre Arbeit. Abbildung 26.6 Bubblesort bei der parallelen Ausführung Auch die Ausführzeit hat sich gewaltig verändert. Anstatt der bisher 25–28 Sekunden verrichtet unser Programm jetzt seine Arbeit in 11–14 Sekunden. Wir haben damit die Ausführzeit quasi halbiert. ### 26.4.3 Zusammenfassung Anhand dieser kurzen Einführung zu den POSIX-Threads lässt sich schon erkennen, wie brisant und aktuell das Thema ist. Dennoch soll gesagt werden, dass Threads wirklich nur da eingesetzt werden sollten, wo sie unbedingt benötigt werden. Lassen Sie sich von diesem Kapitel nicht täuschen: Threads sind nicht immer so einfach zu implementieren. Häufig sind Synchronisationsmechanismen zu implementieren, wenn mehrere Threads die Daten teilen. Weià man hier nicht genau, was man tut, kann es passieren, dass die Threads Amok laufen oder dass es Datensalat gibt. Es gibt Probleme, die lassen sich sehr gut und einfach parallelisieren. Andere wiederum benötigen einfache Synchronisationsmechanismen, und wieder andere brauchen einen gewaltigen Verwaltungsaufwand, sodass sich ein Parallelisieren fast nicht lohnt. # 27.2 Memory Leaks (Speicherlecks) ## 27.2 Memory Leaks (Speicherlecks) Wie bei Buffer Overflows sind auch Memory Leaks in den meisten Fällen durch Programmierfehler zu erklären. Der erste Verdacht, es könnte sich bei Memory Leaks um Hardwareprobleme handeln, täuscht. Ein Memory Leak entsteht, wenn ein Programm dynamisch Speicher alloziert (malloc(), realloc(), ...) und diese Speicherressourcen nicht mehr an das System zurückgibt (mittels free()). Es steht nicht unendlich viel Speicher vom Heap dafür zur Verfügung. Programme wie das jetzt folgende erzeugen keine Probleme, wenn der Speicher nicht mehr an den Heap zurückgegeben wird: > /* mleak1.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char *p; p = malloc(sizeof("Hallo Welt\n")); if(NULL == p) { fprintf(stderr, "Abbruch: Speichermangel !!\n"); return EXIT_FAILURE; } strcpy(p, "Hallo Welt\n"); printf("%s",p); return EXIT_SUCCESS; } Hier bekommt der Heap seinen Speicher bei Beendigung des Programms sofort wieder zurück. Was ist aber mit Programmen, die dauerhaft im Einsatz sein müssen? Ein gutes Beispiel sind Telefongesellschaften, die jedes laufende, eingehende und ausgehende Gespräch nach dem FIFO-Prinzip auf dem Heap ablegen und ständig für diese Datensätze Speicher auf dem Heap allozieren bzw. für ältere Datensätze wieder freigeben müssen. Ein (stupides) Beispiel: > /* mleak2.c */ #include <stdio.h> #include <stdlib.h> int main(void) { char *p; while(p = malloc(64000)) { if(NULL == p) { fprintf(stderr, "Speicherplatzmangel!!\n"); return EXIT_FAILURE; } /* Tu was mit dem reservierten Speicher. */ } return EXIT_SUCCESS; } Dieses Programm wird wohl eine Weile ohne Probleme laufen. Aber je länger das Programm läuft, umso mehr Speicher benötigt es vom Heap. Dies wird sich auf Dauer schlecht auf die Performance des Systems auswirken. Denn der Heap ist ja nicht nur für ein Programm allein da. Die anderen Programme, die ebenfalls Ressourcen benötigen, werden immer langsamer. Am Ende bleibt einem nichts anderes mehr übrig, als das System neu zu starten (abhängig vom Betriebssystem und der Art der Anwendung). Meistens ist das Programm aber längst fertiggestellt, wenn ein Speicherleck gefunden wird. Dann kann guter Rat teuer werden, wenn Sie sich nicht auskennen. Eine primitive Möglichkeit, sofern Sie im Besitz des Quellcodes sind, ist es, sogenannte Wrapper-Makros für speicherallozierte und speicherfreigebende Funktionen zu schreiben, beispielsweise für die malloc()-Funktion: > #define malloc(size) \ malloc(size);\ printf("malloc in Zeile %ld der Datei %s (%ld Bytes) \n"\ ,__LINE__,__FILE__, size);\ count_malloc++; Bei Verwendung der malloc()-Funktion im Programm wird jetzt jeweils eine Ausgabe auf dem Bildschirm erzeugt, die anzeigt, in welcher Zeile und in welchem Programm die Funktion malloc() vorkommt und wie viel Speicher sie verwendet. AuÃerdem wird die Verwendung von malloc() mitgezählt. Dasselbe wird anschlieÃend auch mit der Funktion free() gemacht. Die Anzahl der gezählten malloc()- und free()-Aufrufe wird am Ende in eine Datei namens DEBUG_FILE geschrieben. > /* mem_check.h */ #ifndef MEM_CHECK_H #define MEM_CHECK_H #define DEBUG_FILE "Debug" static int count_malloc=0; static int count_free =0; FILE *f; #define malloc(size) \ malloc(size);\ printf("malloc in Zeile %d der Datei %s (%d Bytes) \n"\ ,__LINE__,__FILE__, size);\ count_malloc++; #define free(x)\ free(x); \ x=NULL;\ printf("free in Zeile %d der Datei %s\n", __LINE__,__FILE__);\ count_free++; #define return EXIT_SUCCESS; \ f=fopen(DEBUG_FILE, "w");\ fprintf(f, "Anzahl malloc : %d\n",count_malloc);\ fprintf(f, "Anzahl free : %d\n",count_free);\ fclose(f);\ printf("Datei : %s erstellt\n", DEBUG_FILE);\ return EXIT_SUCCESS; #endif Hier wurde eine Headerdatei namens mem_check.h erstellt, mit der alle Aufrufe von malloc() und free() auf dem Bildschirm ausgeben werden. Sie erfahren dadurch, in welcher Datei und welcher Zeile sich ein Aufruf dieser Funktion befindet. AuÃerdem wird auch die Anzahl der malloc()- und free()-Aufrufe mitgezählt. Sind mehr malloc()-Aufrufe als free()-Aufrufe vorhanden, wurde auf jeden Fall ein Speicherleck im Programm gefunden. Hier sehen Sie ein Listing zum Testen: > /* use_mem_check.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mem_check.h" int main(void) { char *p; p = malloc(sizeof("<NAME>\n")); if(NULL == p) { fprintf(stderr, "Speichermangel!!!\n"); return EXIT_FAILURE; } strcpy(p, "<NAME>\n"); printf("%s",p); malloc(1024); free(p); return EXIT_SUCCESS; } In der Praxis und bei gröÃeren Projekten ist diese Version, Memory Leaks aufzuspüren, nur bedingt geeignet. Mit dem Makro return 0 habe ich es mir allzu leicht gemacht. Dies setzt nämlich voraus, dass ein Programm auch damit beendet wird. Oft haben Sie es aber mit dauerhaft laufenden Programmen zu tun. Genauso sieht es mit der Zuordnung des allozierten und freigegebenen Speichers aus. Welches malloc() gehört zu welchem free()? Aber das Prinzip dürfte Ihnen klar geworden sein. Wenn Sie Fehler wie Memory Leaks finden wollen, haben Sie notfalls mit Wrapper-Makros eine gute Möglichkeit. Meistens werden Sie schon eher auf eines der mittlerweile vielen Tools oder auf eine der Bibliotheken zurückgreifen, die zur Erkennung von Memory Leaks programmiert wurden. ### 27.2.1 Bibliotheken und Tools zu Memory Leaks Es gibt mittlerweile eine unüberschaubare Menge von solchen Debugging-Tools. Daher folgt hier ein kleiner Ãberblick mit Angabe der Bezugsquellen. Meistens finden Sie dabei auf diesen Webseiten gleich die Dokumentation für die Anwendung. # ccmalloc Bezugsquelle: http://www.inf.ethz.ch/personal/biere/projects/ccmalloc/ ccmalloc wird mit dem C/C++-Programm verlinkt und gibt nach Beendigung des Programms einen Bericht über Memory Leaks aus. ccmalloc ist nicht geeignet, um festzustellen, ob versucht wurde, aus illegalen Speicherbereichen zu lesen. # dbmalloc Bezugsquelle: ftp://ftp.digital.com/pub/usenet/comp.sources.misc/volume32/dbmalloc/ dbmalloc ist in einer kommerziellen und einer kostenlosen Version erhältlich. Besondere Merkmale von dbmalloc sind: * Funktionsfluss, Datei und Zeileninformationen werden mit angegeben. * Gibt Adressen zurück (hilfreich zusammen mit Debuggern). * Grenzbereichsüberprüfung * Ausgabe auf die Standard-Fehlerausgabe * Findet Memory Leaks. Generell wird dbmalloc, wie die meisten anderen Memory-Leak-Tools zu einem Programm hinzugelinkt. Sie müssen also im Besitz des Quellcodes sein, um diesen neu zu übersetzen. Eine gute Anleitung in deutscher Sprache zu dieser Bibliothek finden Sie unter der URL http://www.c-handbuch.org/. # mpatrol Bezugsquelle: http://www.cbmamiga.demon.co.uk/mpatrol/ mpatrol ist ein leistungsfähiges Tool zum Auffinden von Memory Leaks, das sich leider auf die Performance des Programms negativ auswirkt. Folgende Funktionsmerkmale stehen Ihnen dabei zur Verfügung: * Ein Abbild des Stacks wird bei einem Fehler angezeigt. * Datei- und Zeilen-Informationen werden mit ausgegeben. * Es ist kompatibel zu dmalloc, dbmalloc, insure und purify. * Es ist nicht unbedingt erforderlich, neu zu übersetzen, um seine Programme mit mpatrol zu testen. * mpatrol findet alle denkbaren Fehler auf dem Heap. Fehler auf dem Stack werden nicht gefunden. Um ein Programm mit mpatrol zu testen, ist genau wie bei den meisten anderen Tools ein Ãberschreiben der speicheranfordernden und freigebenden Funktionsaufrufe notwendig. Bei mpatrol können Sie dies auf zwei Arten machen: Entweder Sie linken das Programm zu der statischen oder dynamischen Bibliothek oder Sie binden diese später durch einen Aufruf von > mpatrol --dynamc ./testprog -i file dynamisch mit in das Programm ein. Die letzte Möglichkeit funktioniert allerdings nur, wenn das Programm schon dynamisch zur Standard-C-Bibliothek übersetzt wurde, und selbst dann nur auf einigen wenigen Systemen, die diesen Befehl unterstützen. Für eine deutsche Dokumentation sei auch hier wieder auf die Webseite http://www.c-handbuch.org/ verwiesen. Es gibt auÃer diesen hier genannten Tools noch eine Reihe weiterer sehr guter Tools zum Auffinden von Memory Leaks. Einen guten Ãberblick können Sie sich auf der Seite http://www.cs.colorado.edu/~zorn/MallocDebug.html verschaffen. # 27.3 Tipps zu Sicherheitsproblemen ## 27.3 Tipps zu Sicherheitsproblemen Es gibt noch eine Menge weiterer Sicherheitsprobleme, die Sie auf den ersten Blick gar nicht als solche erkennen können. SchlieÃlich haben Sie keine Garantie, dass Ihr Programm vor allen Problemen geschützt ist, wenn Sie auf sichere Funktionen zurückgreifen. Zum Abschluss des Kapitels folgt hier noch ein kleiner Leitfaden zum Thema Sicherheit. Wenn Sie diese Punkte beherzigen, sollten sich Sicherheitsprobleme auf ein Minimum reduzieren lassen. * Vermeiden Sie Funktionen, die keine Längenprüfung der Ein- bzw. Ausgabe vornehmen (strcpy(), sprintf(), vsprintf(), scanf(), gets(),  ). * Verwenden Sie bei Funktionen, die eine formatierte Eingabe erwarten (etwa scanf()) eine GröÃenangabe (etwa %10s, %4d). * Ersetzen Sie gegebenenfalls unsichere Funktionen durch selbst geschriebene (z. B. gets() durch mygets()  ). * Ãberprüfen Sie die Eingabe von der Tastatur auf zulässige GröÃe. Verlassen Sie sich nicht darauf, dass der Anwender schon das Richtige eingeben wird. * Verwenden Sie die exec-Funktionen und system() nur mit konstanten Strings. Lassen Sie niemals den Anwender selbst einen String zusammenbasteln. * Vergessen Sie bei der Funktion strlen() nicht, dass diese Funktion alle Zeichen ohne das Terminierungszeichen zählt. Beim Reservieren von Speicher müssen Sie dies berücksichtigen. * Und der Klassiker: Die Anzahl der Elemente in einem Array und die Adressierung über den Index beginnt bei 0. # A.2 ASCII-Code-Tabelle ## A.2 ASCII-Code-Tabelle # A.3 Reservierte Schlüsselwörter in C ## A.3 Reservierte Schlüsselwörter in C (Schlüsselwörter in fetter Schrift wurden erst mit dem ANSI-C99-Standard eingeführt.) # A.4 Standard-Headerdateien der ANSI-C-Bibliothek ## A.4 Standard-Headerdateien der ANSI-C-Bibliothek (Headerdateien in fetter Schrift wurden erst mit dem ANSI-C99-Standard eingeführt.) # A.5 Weiterführende Links ## A.5 Weiterführende Links Da sich Webseiten und ihre Adressen recht häufig ändern, habe ich die weiterführenden Links zu den Kapiteln des Buchs auf https://www.rheinwerk-verlag.de/2132 ausgelagert. Somit ist sichergestellt, dass die Seiten immer erreichbar sind und ich für Sie regelmäÃig neue Links hinzufügen kann. # B.2 <complex.h> (C99) ## B.2 <complex.h> (C99) Um auch mit komplexen Zahlen rechnen zu können, wurden mit dem C99-Standard komplexe Gleitpunkttypen eingeführt und um mathematische Funktionen erweitert. Jede der hier aufgelisteten Funktionen gibt es in drei Versionen. Jede dieser Versionen arbeitet mit einem anderen Gleitpunkttyp (float, double, long double). Wenn Sie die float- bzw. long double-Version verwenden wollen, brauchen Sie beim Funktionsnamen nur ein f bzw. l anhängen. Funktion | Berechnet... | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Für geplante Erweiterungen der Headerdatei <complex.h> sind jetzt schon die Funktionsnamen cerf(), cerfc(), cexp2(), cexpm1(), clog10(), clog1p(), clog2(), clgamma() und ctgamma() mitsamt den entsprechenden Suffixen f und r reserviert. Ebenfalls in der Headerdatei <complex.h> sind folgende Makros definiert: # B.3 <ctype.h## B.3 <ctype.hIn der Headerdatei <ctype.h> finden Sie Funktionen oder Makros zur Klassifizierung und Umwandlung von einzelnen Zeichen. Als Argumente sind nur int-Werte im Bereich zwischen 0 und 255 erlaubt. # B.4 <errno.h## B.4 <errno.hIn der Headerdatei <errno.h> wird errno als Fehlervariable vom Typ int deklariert, die einige Funktionen der Standard-Bibliothek beim Auftreten eines Fehlers setzen. Der Standard schreibt auÃerdem nicht vor, dass errno eine globale Variable sein muss. errno kann auch ein Makro sein. Für jeden Wert, den errno annehmen kann, ist in der Headerdatei <errno.h> ein Makro mit dem groÃen Anfangsbuchstaben E definiert. Mindestens folgende drei Makros sind definiert: Häufig sind hierbei noch eine Menge weiterer Fehlercodes mit E definiert, die allerdings zum gröÃten Teil abhängig vom System und von der Implementierung sind (also keine Standard-Fehlercodes). # B.5 <fenv.h> (C99) ## B.5 <fenv.h> (C99) In der Headerdatei <fenv.h> finden Sie verschiedene Einstellungen für das Rechnen mit Gleitpunktzahlen, um mit Gleitpunkt-Exceptions und Zustandsflags zu arbeiten. AuÃerdem können Sie hierbei auch das Rundungsverhalten von Gleitpunkt-Arithmetiken einstellen. Um mit dem Programm auf diese Gleitpunkt-Umgebung zuzugreifen, empfiehlt es sich, dies dem Compiler mit dem Pragma STDC FENV_ACCESS mitzuteilen: > // Compiler-Optimierungen verhindern #pragma STDC FENV_ACCESS ON Für den Zugriff auf die komplette Gleitpunkt-Umgebung stehen folgende typedef-Typen zur Verfügung: Zugriff auf die komplette Gleitpunkt-Umgebung mit dem Typ fenv_t haben Sie mit folgenden Funktionen: Für den Zugriff auf die Gleitpunkt-Exception und Zustandsflags stehen Ihnen folgende Funktionen zur Verfügung: Zur genauen Identifizierung der Exeception- und Zustandsflags sind in der Headerdatei <fenv.h> folgende ganzzahlige Makros definiert: Ebenfalls in der Headerdatei <fenv.h> sind Funktionen definiert, um das Rundungsverhalten der Gleitpunkt-Arithmetik einzustellen: Folgende Makros sind hier in der Headerdatei <fenv.h> definiert, um den Rundungsmodus abzufragen bzw. zu setzen: # B.6 <float.h## B.6 <float.hIn der Headerdatei <float.h> werden Makros für die Genauigkeit, den Wertebereich und andere Eigenschaften der Datentypen float, double und long double definiert. Für die Genauigkeit und den Wertebereich von Gleitpunkttypen sind folgende Makros definiert: Des Weiteren gibt es noch folgende zwei Makros in der Headerdatei <float.h>, die mehr Informationen zur Ausführung von Gleitpunkt-Arithmetik liefern: # B.7 <inttypes.h> (C99) ## B.7 <inttypes.h> (C99) Der Header <inttypes.h> ist eine Ergänzung bzw. Erweiterung des Headers <stdint.h> (der natürlich auch inkludiert ist). <inttypes.h> definiert einige Makros (genauer Stringliterale), die als Konvertierungsspezifizierer für Funktionen der printf- und scanf-Familie verwendet werden können. Des Weiteren finden Sie in der Headerdatei den Struktur-Typ imaxdiv_t und weitere Funktionen. Der Struktur-Typ imaxdiv_t enthält zwei Argumente vom Typ intmax_t und wird von der Funktion imaxdiv() zurückgegeben: ``` #include <inttypes.h> imaxdiv_t imaxdiv(intmax_t numer, intmax_t denom); ``` Die Funktion imaxdiv() berechnet hierbei den Quotienten und den Rest einer Division von Ganzzahlen mit dem Typ intmax_t (definiert in <stdint.h>). Weitere Funktionen der Headerdatei <inttypes.h> sind: Die Makros der printf-Familie beginnen alle mit dem Präfix PRI, und die Makros der scanf-Familie beginnen mit dem Präfix SCN. Danach folgt der Konvertierungsspezifizierer d, i, o, x oder X mit dem Typnamen. Für jeden in <stdint.h> definierten Typ gibt es ein Makro. Bei der Ãbersicht der Makros müssen Sie lediglich noch den Buchstaben N des Makronamens durch die Bit-Breite des Typs austauschen (in der Regel 8, 16, 32 oder 64). Hier sehen Sie alle Makros für die Konvertierungsspezifizierer d, i, o, x oder X (bei scanf() gibt es den Konvertierungsspezifizierer X nicht): > // printf-Makros für signed integers PRIdN PRIdLEASTN PRIdFASTN PRIdMAX PRIdPTR PRIiN PRIiLEASTN PRIiFASTN PRIiMAX PRIiPTR // printf-Makros für unsigned integers PRIoN PRIoLEASTN PRIoFASTN PRIoMAX PRIoPTR PRIuN PRIuLEASTN PRIuFASTN PRIuMAX PRIuPTR PRIxN PRIxLEASTN PRIxFASTN PRIxMAX PRIxPTR PRIXN PRIXLEASTN PRIXFASTN PRIXMAX PRIXPTR // scanf-Makros für signed integers SCNdN SCNdLEASTN SCNdFASTN SCNdMAX SCNdPTR SCNiN SCNiLEASTN SCNiFASTN SCNiMAX SCNiPTR // scanf-Makros für unsigned integers SCNoN SCNoLEASTN SCNoFASTN SCNoMAX SCNoPTR SCNuN SCNuLEASTN SCNuFASTN SCNuMAX SCNuPTR SCNxN SCNxLEASTN SCNxFASTN SCNxMAX SCNxPTR # B.8 <iso646.h> (NA1) ## B.8 <iso646.h> (NA1) Die Headerdatei <iso646.h> wurde 1995 zum C90-Standard hinzugefügt. Sie enthält elf definierte Makros als alternative Schreibweise für Bit-Operatoren und logische Operatoren: Makro | Definiert als | | --- | --- | | | | | | | | | | | | | | | | | | | | | | | # B.9 <limits.h## B.9 <limits.hDie Wertebereiche für ganzzahlige Typen sind in der Headerdatei <limits.h> definiert: # B.10 <locale.h## B.10 <locale.hUm Anwendungen an die lokale Umgebung wie beispielsweise lokalspezifische Zeichen oder Währungsinformationen anzupassen, ist in der Headerdatei <locale.h> eine Struktur mit dem Typ struct lconv mit folgenden Mitgliedern deklariert: Um auf die Elemente der Struktur lconv zuzugreifen, sind in der Headerdatei folgende zwei Funktionen deklariert: Für das erste Argument von setlocale() sind folgende Makros definiert, mit denen Sie die Kategorie festlegen können: # B.11 <math.h## B.11 <math.hIn der Headerdatei <math.h> sind mathematische Funktionen für reelle Gleitpunktzahlen mit dazu passenden Makros und Typen deklariert. <math.h> wurde mit dem C99-Standard erweitert. In <math.h> finden Sie (seit dem C99-Standard) mit float_t und double_t zwei typedef-Typen, die das Gleitpunktformat darstellen, womit die arithmetischen Ausdrücke vom Typ float bzw. double intern berechnet werden. Von welchem Typ float_t und double_t sind, definiert der Wert des Makros FLT_EVAL_METHOD: FLT_EVAL_METHOD | float_t entspricht | double_t entspricht | | --- | --- | --- | | | | | | | | | | Der Vorteil der Verwendung von float_t und double_t gegenüber der herkömmlichen Verwendung der Typen float, double und long double ist, dass hier die Operanden nicht vor einer arithmetischen Operation konvertiert werden müssen, wie dies häufig der Fall ist. Folgende Makros sind (ab dem C99-Standard) in der Headerdatei <math.h> vorhanden, um die Gleitpunktwerte zu klassifizieren: Für die Ermittlung der entsprechenden Kategorie sind folgende Makros definiert: Intern werden alle diese Makros jedoch mithilfe des Makros fpclassify() ausgewertet, das Sie selbstverständlich auch manuell verwenden können: > if ( fpclassify(x) == FP_NAN ) { /*  */ } // ... gleichwert zu ... if( isnan(x) ) { /* ... */ } Auch zum Vergleich von reelen Zahlen sind folgende Makros in der Headerdatei <math.h> vorhanden: Weitere Makros in der Headerdatei <math.h> sind: Jetzt fehlen natürlich noch die Funktionen der Headerdatei <math.h>. Bei der Tabelle der Gleitpunktfunktionen werden hier nur die double-Versionen aufgelistet. Wenn Sie mit float oder long double arbeiten, müssen Sie zum Funktionsnamen lediglich den Buchstaben f oder l hinzufügen. Für die Funktion fma(x, y, z) können auÃerdem in der Headerdatei <math.h> seit dem C99-Standard die Makros FP_FAST_FMA, FP_FAST_FMAF, FP_FAST_FMAL definiert sein. Wenn diese definiert sind, dann bedeutet dies, dass die Ausführung der Funktion schneller ist als die Ausführung einer gewöhnlichen Multiplikation, gefolgt von einer Addition mit Operatoren (beispielsweise x*y+z). Dies ist dann der Fall, wenn die Funktion fma() spezielle Maschinenbefehle verwendet. FP_FAST_FMA ist die double-Version, FP_FAST_FMAF die float-Version und FP_FAST_FMAL die Version für long double. Auch für Funktion ilogb(x) gibt es mit FP_ILOGB0 und FP_ILOGBNAN zwei Makros. FP_ILOGB0 wird ausgegeben, wenn das Argument x den Wert 0 hat. FP_ILOGBNAN hingegen bedeutet, dass x keine gültige Gleitpunktzahl ist. FP_ILOGB0 kann entweder den Wert -INT_MAX oder INT_MIN haben und FP_LOGBNAN kann den Wert INT_MAX oder INT_MIN annehmen. Folgende Makros machen die Ãbersicht zur Headerdatei <math.h> jetzt komplett (C99): > // Konstante mit dem Wert 1 MATH_ERRNO // Konstante mit dem Wert 2 MATH_ERREXCEPT Diese Konstanten werden als Bit-Masken verwendet, um den Inhalt von math_errhandling. der externen Variablen oder eines Makros vom Typ int zu ermitteln. Ist beispielsweise der Ausdruck > if ( math_errhandlich & MATH_ERRNO ) { // Ein Fehler ist aufgetreten; errno auslesen } nicht null, dann können Sie daraus schlieÃen, dass bei einer Berechnung ein Fehler aufgetreten ist. Mit der Fehlervariablen errno können Sie jetzt ermitteln, ob es sich hierbei um einen Domain error (EDOM) oder Range error (ERANGE) handelt. Selbiges lässt sich mit den Exceptions der Gleitpunkt-Umgebung verwenden: > if ( math_errhandlich & MATH_ERREXCEPT ) { // Eine Exception ist aufgetreten. // Mögliche Exceptions finden Sie in <fenv.h>. } Wenn die Implementierung Exceptions der Gleitpunkt-Umgebung unterstützt, können Sie diese mithilfe der Makros FE_DIVBYZERO, FE_INEXACT, FE_INVALID, FE_OVERFLOW und FE_UNDERFLOW aus der Headerdatei <fenv.h> und der Funktion fetestexcept() auswerten. Mehr dazu habe ich bereits in Abschnitt 20.3.7, »Zugriff auf die Gleitpunktumgebung – <fenv.h>« geschrieben. # B.12 <setjmp.h## B.12 <setjmp.hGewöhnlich ist es ja nicht möglich, von einer aufgerufenen Funktion in die aufrufende Funktion zurückzukehren. Mit den Funktionen setjmp() und longjmp() hingegen ist ein solcher Rücksprung möglich. Der Programmzustand, der von setjmp() gesetzt und von longjmp() angesprungen wird, wird in einem Puffer vom Typ jmp_buf gespeichert. Bei jmp_buf handelt es sich um ein Array mit Informationen wie u. a. Register-Inhalte, Instruktions-Pointer oder Stackpointer. # B.13 <signal.h## B.13 <signal.hZur Behandlung von Signalen finden Sie in der Headerdatei <signal.h> folgende zwei Funktionen: Für das erste Argument von signal() bzw. raise() geben Sie die Signalnummer an, die behandelt bzw. gesendet werden soll. Hierfür sind im Standard mindestens folgende Makros vom Typ int definiert: Mit dem zweiten Argument der Funktion legen Sie entweder die Adresse des Signal-Handlers fest, oder Sie können eines der folgenden Makros verwenden: Des Weiteren ist in der Headerdatei <signal.h> ein Typ sig_atomic_t vorhanden, der Ihnen Zugriff auf atomare Operationen (beispielsweise als Hardware-Interrupt bei Signal-Handlern) ermöglicht. Der Wertebereich von sig_atomic_t ist in der Headerdatei <stdint.h> mit den Makros SIG_ATOMIC_MIN und SIG_ATOMIC_MAX definiert. # B.14 <stdarg.h## B.14 <stdarg.hIn der Headerdatei <stdarg.h> sind vier Makros und ein Typ für die Verwendung von optionalen Argumenten bei Funktionen definiert: # B.15 <stdbool.h> (C99) ## B.15 <stdbool.h> (C99) In der Headerdatei <stdbool.h> sind folgende Makros definiert: # B.16 <stddef.h## B.16 <stddef.hDie Headerdatei <stddef.h> beinhaltet folgende zwei Makros: Des Weiteren sind noch folgende drei Typen definiert: # B.17 <stdint.h> (C99) ## B.17 <stdint.h> (C99) In der Headerdatei <stdint.h> werden ganzzahlige Typen mit bestimmter Breite definiert. Mit »vorgegebener Breite« ist die Anzahl der Bits zur Darstellung des Werts gemeint, die dieser Typ verwenden darf. Spezielle Formatierungsspezifizierer für die printf- und scanf-Familie finden Sie in der Headerdatei <inttypes.h>. Hier die Typen im Ãberblick (Typen, die mit u (unsigned) beginnen, sind vorzeichenlos): Selbstverständlich finden Sie in der Headerdatei <stdint.h> auch die zum definierten Typ gehörenden Makros, die den minimalen und maximalen Wertebereich des Typs definieren. Auch hier müssen Sie N gegen die erlaubten Werte 8, 16, 32 oder 64 austauschen: Ebenfalls in der Headerdatei <stdint.h> werden Wertebereiche für Typen aus anderen Headern definiert: # B.18 <stdio.h## B.18 <stdio.hDie Headerdatei <stdio.h> deklariert eine Menge grundlegender Funktionen, Makros und Typen für die Ein-/Ausgabe. Zunächst ein Ãberblick über die Funktionen in <stdio.h>: Folgende Makros sind in der Headerdatei <stdio.h> meistens als positive Integer-Konstanten definiert: Folgende drei Typen sind in <stdio.h> definiert: Die folgenden drei Standard-Streams sind alle als Zeiger auf FILE im Header <stdio.h> definiert: Stream | Beschreibung | | --- | --- | | | | | | | # B.19 <stdlib.h## B.19 <stdlib.hDie Headerdatei <stdlib.h> ist so etwas wie ein Sammelsurium von Funktionen, weil sich hier viele Funktionen unterschiedlicher Bereiche finden. Es gibt folgende Funktionen in <stdlib.h>: Folgende Makros sind in <stdlib.h> definiert: Zu guter Letzt sind noch folgende fünf Typen in <stdlib.h> enthalten: Type | Beschreibung | | --- | --- | | | | | | | | | | | # B.20 <string.h## B.20 <string.hIn der Headerdatei <string.h> sind viele Stringfunktionen und Funktionen, die ein Array byteweise bearbeiten, vorhanden. Die Stringfunktionen beginnen hierbei mit dem Präfix str und die Bytefunktionen mit mem. Ebenfalls in der Headerdatei <string.h> ist der Typ size_t und das Makro NULL definiert, worauf jetzt schon des Ãfteren eingegangen wurde. Hierzu sehen Sie nun die Funktionen der Headerdatei: # B.21 <tgmath.h> (C99) ## B.21 <tgmath.h> (C99) Wollen Sie beispielsweise eine Funktion zum Ziehen der Quadratwurzel verwenden, so mussten Sie, abhängig vom Datentyp, zwischen sechs verschiedene Varianten mit sqrtf(), sqrt(), sqrtl(), csqrtf(), csqrt() und csqrtl() unterscheiden. Mit den typengenerischen Makros in <tgmath.h> brauchen Sie sich darüber keine Gedanken mehr zu machen. Hiermit brauchen Sie lediglich die Funktionen der double- bzw. double complex-Variante kennen, und ein Aufruf von sqrt() führt automatisch die entsprechende Erweiterung aus. Rufen Sie beispielsweise sqrt() mit einem float complex-Argument auf, wird automatisch die Erweiterung csqrtf() ausgeführt. # B.22 <time.hDate: 2001-01-01 Categories: Tags: ## B.22 <time.h<time.h> beinhaltet viele Standardfunktionen, Typen und Makros für die Behandlung von Datum und Uhrzeit. Hierzu zunächst ein Ãberblick über die Funktionen: Folgende Typen sind in <time.h> deklariert: In der Sturktur struct tm sind folgende Elemente deklariert: Element in struct tm | Beschreibung | | --- | --- | | | | | | | | | | | | | | | | | | | Folgende Makros sind in der Headerdatei <time.h> definiert: Makros | Beschreibung | | --- | --- | | | | | Jetzt noch eine Ãbersicht über die Formatspezifizierer der Funktion strftime(), um Werte von der Struktur struct tm in einen benutzerdefinierten String umzuwandeln. Folgende Umwandlungsvorgaben können Sie hier verwenden: Format | Wird ersetzt durch | Beispiel | | --- | --- | --- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | # B.23 <wchar.h> (NA1) ## B.23 <wchar.h> (NA1) Bisher haben Sie eine Menge Funktionen zu Verarbeitung von gewöhnlichen Strings gesehen. Wenn Sie auf der Suche nach entsprechenden Gegenstücken aus den Headerdateien <stdio.h>, <stdlib.h>, <string.h> oder <time.h> für Breitzeichen-Strings (vom Typ wchar_t) sind, werden Sie in dem Header <wchar.h> fündig. Zunächst die Ãbersicht über die Gegenstücke für breite Zeichen aus der Headerdatei <stdio.h>, die sich in <wchar.h> befinden: Natürlich finden Sie in <wchar.h> auch Funktionen für numerische Konvertierungen, wie aus der Headerdatei <stdlib.h>, nur eben für Breitzeichenstrings. Hier die entsprechenden Funktionen: Auch die Stringfunktionen für Breitzeichenstrings finden Sie in der Headerdatei <wchar.h>. Sie sind ihren Gegenstücken aus der Headerdatei <string.h> ebenbürtig: Für die Formatierung von Datum und Uhrzeit in einem Breitzeichenstring ist in <wchar.h> die Funktion wcsftime() deklariert: ``` size_t wcsftime( wchar_t * restrict s, size_t maxsize, const wchar_t * restrict format, const struct tm * restrict timeptr); ``` Die Verwendung der Funktion entspricht exakt der Verwendung der Funktion strftime() aus der Headerdatei <time.h>, nur eben mit Breitzeichenstrings. Des Weiteren finden Sie folgende Funktionen zur erweiterten Umwandlung von Breitzeichen in Multibytezeichen und umgekehrt: Folgende Typen sind in der Headerdatei <wchar.h> auÃerdem noch deklariert: Neben den Makros WCHAR_MIN, WCHAR_MAX (siehe <stdint.h>) und NULL definiert <wchar.h> auch das Makro WEOF. Diese Konstante ist vom Typ wint_t und stellt einen Wert dar, der nicht mit dem Wert eines Zeichens aus dem erweiterten Zeichensatz übereinstimmt. WEOF kann im Gegensatz zu EOF auch einen positiven Wert haben und wird von vielen Funktionen im Fall eines Fehlers oder beim Ende eines Lesevorgangs zurückgegeben.
sharpshootR
cran
R
Package ‘sharpshootR’ August 24, 2023 Type Package Encoding UTF-8 Title A Soil Survey Toolkit Description Miscellaneous soil data management, summary, visualization, and conversion utili- ties to support soil survey. Version 2.2 Date 2023-08-24 Maintainer <NAME> <<EMAIL>> LazyLoad yes LazyData true License GPL (>= 3) Repository CRAN URL https://github.com/ncss-tech/sharpshootR BugReports https://github.com/ncss-tech/sharpshootR/issues Suggests MASS, spdep, circlize, rvest, xml2, terra, raster, exactextractr, httr, jsonlite, igraph, dendextend, testthat, hydromad (>= 0.9.27), latticeExtra, farver, venn, gower, daymetr, elevatr, Evapotranspiration, zoo, SoilTaxonomy, sf, Hmisc Depends R (>= 3.5.0) Imports grDevices, graphics, methods, stats, utils, aqp, ape, soilDB, cluster, lattice, vegan, reshape2, scales, circular, RColorBrewer, plyr, digest, e1071, stringi, parallel, curl, grid Additional_repositories https://hydromad.github.io RoxygenNote 7.2.3 NeedsCompilation no Author <NAME> [cre, aut], <NAME> [aut], <NAME> [aut], <NAME> [aut], USDA-NRCS Soil Survey Staff [ctb] Date/Publication 2023-08-24 16:50:02 UTC R topics documented: sharpshootR-packag... 3 aggregateColorPlo... 4 amado... 6 aspect.plo... 6 CDEC.snow.course... 8 CDECquer... 9 CDECsnowQuer... 10 CDEC_StationInf... 11 colorMixtureVen... 12 component.adj.matri... 13 constantDensitySamplin... 14 dailyW... 15 dailyWB_SSURG... 16 diagnosticPropertyPlo... 17 diagnosticPropertyPlot... 19 dist.along.gra... 21 dueling.dendrogram... 22 ESS_by_Moran_... 23 estimateSoilMoistureStat... 23 FF... 25 FFDplo... 26 formatPLS... 27 generateLineHas... 28 geomorphBySoilSeries-SSURG... 29 HenryTimeLin... 30 HH... 31 huePositionPlo... 32 hydOrde... 33 isMineralSoilMateria... 34 iterateHydOrde... 35 joinAdjacenc... 37 LL2PLS... 37 moistureStateProportion... 38 moistureStateStat... 39 moistureStateThreshol... 39 monthlyW... 40 Moran_I_ByRaste... 42 multinominal2logica... 43 OSDexample... 44 PCP_plo... 44 percentileDem... 45 plotAvailWate... 46 plotGeomorphCrossSectio... 49 plotProfileDendrogra... 50 plotSoilRelationChordGrap... 51 plotSoilRelationGrap... 52 plotTransec... 55 plotW... 58 plotWB_line... 60 PLSS2L... 62 polygonAdjacenc... 63 prepareDailyClimateDat... 63 prepare_SSURGO_hydro_dat... 64 reconcileOSDGeomorp... 65 sample.by.pol... 66 sampleRasterStackByM... 67 samplingStabilit... 68 simpleW... 69 site_photos_km... 70 SoilTaxonomyDendrogra... 71 table5.... 74 vizAnnualClimat... 75 vizFlatsPositio... 76 vizGeomorphicComponen... 77 vizHillslopePositio... 78 vizMountainPositio... 79 vizSurfaceShap... 80 vizTerracePositio... 81 sharpshootR-package A collection of functions to support soil survey Description This package contains mish-mash of functionality and sample data related to the daily business of soil survey operations with the USDA-NRCS. Many of the functions are highly specialized and inherit default arguments from the names used by the various NCSS (National Cooperative Soil Survey) databases. A detailed description of this package with links to associated tutorials can be found at the project website. aggregateColorPlot Plot aggregate soil color data Description Generate a plot from summaries generated by aqp::aggregateColor(). Usage aggregateColorPlot( x, print.label = TRUE, label.font = 1, label.cex = 0.65, label.orientation = c("v", "h"), buffer.pct = 0.02, print.n.hz = FALSE, rect.border = "black", horizontal.borders = FALSE, horizontal.border.lwd = 2, x.axis = TRUE, y.axis = TRUE, ... ) Arguments x a list, results from aqp::aggregateColor() print.label logical, print Munsell color labels inside of rectangles, only if they fit label.font font specification for color labels label.cex font size for color labels label.orientation label orientation, v for vertical or h for horizontal buffer.pct extra space between labels and color rectangles print.n.hz optionally print the number of horizons below Munsell color labels rect.border color for rectangle border horizontal.borders optionally add horizontal borders between bands of color horizontal.border.lwd line width for horizontal borders x.axis logical, add a scale and label to x-axis? y.axis logical, add group labels to y-axis? ... additional arguments passed to plot Details Tutorial at http://ncss-tech.github.io/AQP/sharpshootR/aggregate-soil-color.html. Value nothing, function called for graphical output Author(s) <NAME> Examples if(require(aqp) & require(soilDB)) { data(loafercreek, package = 'soilDB') # generalize horizon names using REGEX rules n <- c('Oi', 'A', 'BA','Bt1','Bt2','Bt3','Cr','R') p <- c('O', '^A$|Ad|Ap|AB','BA$|Bw', 'Bt1$|^B$','^Bt$|^Bt2$','^Bt3|^Bt4|CBt$|BCt$|2Bt|2CB$|^C$','Cr','R') loafercreek$genhz <- generalize.hz(loafercreek$hzname, n, p) # remove non-matching generalized horizon names loafercreek$genhz[loafercreek$genhz == 'not-used'] <- NA loafercreek$genhz <- factor(loafercreek$genhz) # aggregate color data, this function is from the `aqp` package a <- aggregateColor(loafercreek, 'genhz') # plot op <- par(no.readonly = TRUE) par(mar=c(4,4,1,1)) # vertical labels, the default aggregateColorPlot(a, print.n.hz = TRUE) # horizontal labels aggregateColorPlot(a, print.n.hz = TRUE, label.orientation = 'h') par(op) } amador SSURGO Data Associated with the Amador Soil Series Description SSURGO Data Associated with the Amador Soil Series Usage data(amador) Format A subset of data taken from the "component" table of SSURGO mukey map unit key compname component name comppct_r component percentage Source USDA-NRCS SSURGO Database aspect.plot Plot Aspect Data Description Plot a graphical summary of multiple aspect measurements on a circular diagram. Usage aspect.plot( p, q = c(0.05, 0.5, 0.95), p.bins = 60, p.bw = 30, stack = TRUE, p.axis = seq(0, 350, by = 10), plot.title = NULL, line.col = "RoyalBlue", line.lwd = 1, line.lty = 2, arrow.col = line.col, arrow.lwd = 1, arrow.lty = 1, arrow.length = 0.15, ... ) Arguments p a vector of aspect angles in degrees, measured clock-wise from North q a vector of desired quantiles p.bins number of bins to use for circular histogram p.bw bandwidth used for circular density estimation stack logical, should the individual points be stacked into p.bins number of bins and plotted p.axis a sequence of integers (degrees) describing the circular axis plot.title an informative title line.col density line color line.lwd density line width line.lty density line line style arrow.col arrow color arrow.lwd arrow line width arrow.lty arrow line style arrow.length arrow head length ... further arguments passed to circular::plot.circular Details Spread and central tendency are depicted with a combination of circular histogram and kernel den- sity estimate. The circular mean, and relative confidence in that mean are depicted with an arrow: longer arrow lengths correspond to greater confidence in the mean. Value invisibly returns circular stats Note Manual adjustment of p.bw may be required in order to get an optimal circular density plot. This function requires the package circular, version 0.4-7 or later. Author(s) <NAME> Examples # simulate some data p.narrow <- runif(n=25, min=215, max=280) p.wide <- runif(n=25, min=0, max=270) # set figure margins to 0, 2-column plot op <- par(no.readonly = TRUE) par(mar = c(0,0,0,0), mfcol = c(1,2)) # plot, save circular stats x <- aspect.plot(p.narrow, p.bw=10, plot.title='Soil A', pch=21, col='black', bg='RoyalBlue') y <- aspect.plot(p.wide, p.bw=10, plot.title='Soil B', pch=21, col='black', bg='RoyalBlue') # reset output device options par(op) x CDEC.snow.courses CDEC Snow Course List Description The CDEC snow course list, updated September 2019 Usage data(CDEC.snow.courses) Format A data frame with 259 observations on the following 9 variables. course_number course number name connotative course label id course ID elev_feet course elevation in feet latitude latitude longitude longitude april.1.Avg.inches average inches of snow as of April 1st agency responsible agency watershed watershed label Source Data were scraped from http://cdec.water.ca.gov/misc/SnowCourses.html, 2019. Examples data(CDEC.snow.courses) head(CDEC.snow.courses) CDECquery Easy Access to the CDEC API Description A (relatively) simple interface to the CDEC website. Usage CDECquery(id, sensor, interval = "D", start, end) Arguments id station ID (e.g. ’spw’), single value or vector of station IDs, see details sensor the sensor ID, single value or vector of sensor numbers, see details interval character, ’D’ for daily, ’H’ for hourly, ’M’ for monthly, ’E’ for event: see Details. start starting date, in the format ’YYYY-MM-DD’ end ending date, in the format ’YYYY-MM-DD’ Details Sensors that report data on an interval other than monthly (’M’), daily (’D’), or hourly (’H’) can be queried with an event interval (’E’). Soil moisture and temperature sensors are an example of this type of reporting. See examples below. 1. Station IDs can be found here: http://cdec.water.ca.gov/staInfo.html 2a. Sensor IDs can be found using this URL: http://cdec.water.ca.gov/dynamicapp/staMeta? station_id=, followed by the station ID. 2b. Sensor details can be accessed using CDEC_StationInfo with the station ID. 3. Reservoir capacities can be found here: http://cdec.water.ca.gov/misc/resinfo.html 4. A new interactive map of CDEC stations can be found here: http://cdec.water.ca.gov Value A data.frame object with the following fields: datetime, year, month, value. Author(s) <NAME> References http://cdec.water.ca.gov/queryCSV.html See Also CDECsnowQuery CDEC_StationInfo CDECsnowQuery Get snow survey data (California only) from the CDEC website. Description Get snow survey data (California only) from the CDEC website. Usage CDECsnowQuery(course, start_yr, end_yr) Arguments course integer, course number (e.g. 129) start_yr integer, the starting year (e.g. 2010) end_yr integer, the ending year (e.g. 2013) Details This function downloads data from the CDEC website, therefore an internet connection is required. The SWE column contains adjusted SWE if available (Adjusted column), otherwise the reported SWE is used (Water column). See the tutorial for examples. Value a data.frame object, see examples Note Snow course locations, ID numbers, and other information can be found here: http://cdec. water.ca.gov/misc/SnowCourses.html Author(s) <NAME> References http://cdec.water.ca.gov/cgi-progs/snowQuery CDEC_StationInfo CDEC Sensor Details (by Station) Description Query CDEC Website for Sensor Details Usage CDEC_StationInfo(s) Arguments s character, a single CDEC station ID (e.g. ’HHM’) Details This function requires the rvest package. Value A list object containing site metadata, sensor metadata, and possibly comments about the site. Author(s) <NAME> See Also [CDECquery] colorMixtureVenn Create a Venn Diagram of Simulated Color Mixtures Description Create a Venn Diagram of Simulated Color Mixtures Usage colorMixtureVenn( chips, w = rep(1, times = length(chips))/length(chips), mixingMethod = "exact", ellipse = FALSE, labels = TRUE, names = FALSE, sncs = 0.85 ) Arguments chips character vector of standard Munsell color notation (e.g. "10YR 3/4") w vector of proportions, can sum to any number, must be same length as chips mixingMethod approach used to simulate a mixture: see aqp::mixMunsell() for details ellipse logical, use alternative ellipse-style (4 or 5 colors only) labels logical, print mixture labels names logical, print names outside of the "sets" sncs scaling factor for set names Value nothing returned, function is called to create graphical output Examples ## Not run: if(requireNamespace("venn") & requireNamespace("gower")) { chips <- c('10YR 8/1', '2.5YR 3/6', '10YR 2/2') names(chips) <- c("tan", "dark red", "dark brown") colorMixtureVenn(chips) colorMixtureVenn(chips, names = TRUE) colorMixtureVenn(chips, w = c(1, 1, 1), names = TRUE) colorMixtureVenn(chips, w = c(10, 5, 1), names = TRUE) } ## End(Not run) component.adj.matrix Create an adjacency matrix from a data.frame of component data Description Create an adjacency matrix from SSURGO component data Usage component.adj.matrix( d, mu = "mukey", co = "compname", wt = "comppct_r", method = c("community.matrix", "occurrence"), standardization = "max", metric = "jaccard", rm.orphans = TRUE, similarity = TRUE, return.comm.matrix = FALSE ) Arguments d data.frame, typically of SSURGO data mu name of the column containing the map unit ID (typically ’mukey’) co name of the column containing the component ID (typically ’compname’) wt name of the column containing the component weight percent (typically ’comp- pct_r’) method one of either: community.matrix, or occurrence; see details standardization community matrix standardization method, passed to vegan::decostand metric community matrix dissimilarity metric, passed to vegan::vegdist rm.orphans logical, should map units with a single component be omitted? (typically yes) similarity logical, return a similarity matrix? (if FALSE, a distance matrix is returned) return.comm.matrix logical, return pseudo-community matrix? (if TRUE no adjacency matrix is cre- ated) Value a similarity matrix / adjacency matrix suitable for use with igraph functions or anything else that can accommodate a similarity matrix. Author(s) <NAME> Examples if (requireNamespace("igraph")) { # load sample data set data(amador) # convert into adjacency matrix m <- component.adj.matrix(amador) # plot network diagram, with Amador soil highlighted plotSoilRelationGraph(m, s = 'amador') } constantDensitySampling Constant Density Sampling Description Perform sampling at a constant density over all polygons within a SpatialPolygonsDataFrame ob- ject. Usage constantDensitySampling(x, polygon.id='pID', parallel=FALSE, cores=NULL, n.pts.per.ac=1, min.samples=5, sampling.type='regular') Arguments x a SpatialPolygonsDataFrame object in a projected CRS with units of meters polygon.id name of attribute in x that contains a unique ID for each polygon parallel invoke parallel back-end cores number of CPU cores to use for parallel operation n.pts.per.ac requested sampling density in points per acre (results will be close) min.samples minimum requested number of samples per polygon sampling.type sampling type Value a SpatialPointsDataFrame object Note This function expects that x has coordinates associated with a projected CRS and units of meters. Author(s) <NAME> See Also sample.by.poly dailyWB Simple Daily Water Balance Description Simple interface to the hydromad "leaky bucket" soil moisture model, with accommodation for typical inputs from common soil data and climate sources. Critical points along the water retention curve are specified using volumetric water content (VWC): satiation (saturation), field capacity (typically 1/3 bar suction), and permanent wilting point (typically 15 bar suction). Usage dailyWB(x, daily.data, id, MS.style = "default", S_0 = 0.5, M = 0, etmult = 1) Arguments x data.frame, required columns include: • sat: VWC at satiation • fc: VWC at field capacity • pwp: VWC at permanent wilting point • thickness: soil material thickness in cm • a.ss: recession coefficients for subsurface flow from saturated zone, should be > 0 (range: 0-1) • "id" daily.data data.frame, required columns include: • date: Date class representation of dates • PPT: daily total, precipitation in mm • PET: daily total, potential ET in mm id character, name of column in x that is used to identify records MS.style moisture state classification style, see estimateSoilMoistureState S_0 fraction of water storage filled at time = 0 (range: 0-1) M fraction of area covered by deep-rooted vegetation etmult multiplier for PET Value a data.frame References <NAME>., <NAME>, <NAME>. (2003). Climate, soil and vegetation controls upon the vari- ability of water balance in temperate and semiarid landscapes: downward approach to water balance analysis. Water Resources Research 39(2), p 1035. <NAME>., <NAME>, <NAME> (2009). A top-down framework for watershed model evaluation and selection under uncertainty. Environmental Modelling and Software 24(8), pp. 901-916. dailyWB_SSURGO Perform daily water balance modeling using SSURGO and DAYMET Description Pending. Usage dailyWB_SSURGO( x, cokeys = NULL, start = 1988, end = 2018, modelDepth = 100, MS.style = "default", a.ss = 0.1, S_0 = 0.5, bufferRadiusMeters = 1 ) Arguments x sf object representing a single point cokeys vector of component keys to use start starting year (limited to DAYMET holdings) end ending year (limited to DAYMET holdings) modelDepth soil depth used for water balance, see details MS.style moisture state classification style, see estimateSoilMoistureState a.ss recession coefficients for subsurface flow from saturated zone, should be > 0 (range: 0-1) S_0 fraction of water storage filled at time = 0 (range: 0-1) bufferRadiusMeters spatial buffer (meters) applied to x for the look-up of SSURGO data Value data.frame of daily water balance results Author(s) <NAME> References <NAME>., <NAME>, <NAME>. (2003). Climate, soil and vegetation controls upon the vari- ability of water balance in temperate and semiarid landscapes: downward approach to water balance analysis. Water Resources Research 39(2), p 1035. diagnosticPropertyPlot Diagnostic Property Plot (base graphics) Description Generate a graphical description of the presence/absence of soil diagnostic properties. Usage diagnosticPropertyPlot( f, v, k, grid.label = "pedon_id", dend.label = "pedon_id", sort.vars = TRUE ) Arguments f SoilProfileCollection object v character vector of site-level attribute names of logical type k an integer, number of groups to highlight grid.label the name of a site-level attribute (usually unique) annotating the y-axis of the grid dend.label the name of a site-level attribute (usually unique) annotating dendrogram termi- nal leaves sort.vars sort variables according to natural clustering (TRUE), or use supplied ordering in v Details This function attempts to display several pieces of information within a single figure. First, soil profiles are sorted according to the presence/absence of diagnostic features named in v. Second, these diagnostic features are sorted according to their distribution among soil profiles. Third, a binary grid is established with row-ordering of profiles based on step 1 and column-ordering based on step 2. Blue cells represent the presence of a diagnostic feature. Soils with similar diagnostic features should ’clump’ together. See examples below. Value a list is silently returned by this function, containing: rd a data.frame containing IDs and grouping code profile.order a vector containing the order of soil profiles (row-order in figure), according to diagnostic property values var.order a vector containing the order of variables (column-order in figure), according to their distribution among profiles Author(s) <NAME> and <NAME> See Also multinominal2logical Examples if(require(aqp) & require(soilDB) & require(latticeExtra) ) { # sample data, an SPC data(gopheridge, package='soilDB') # get depth class sdc <- getSoilDepthClass(gopheridge, name = 'hzname') site(gopheridge) <- sdc # diagnostic properties to consider, no need to convert to factors v <- c('lithic.contact', 'paralithic.contact', 'argillic.horizon', 'cambic.horizon', 'ochric.epipedon', 'mollic.epipedon', 'very.shallow', 'shallow', 'mod.deep', 'deep', 'very.deep') # base graphics x <- diagnosticPropertyPlot(gopheridge, v, k=5) # lattice graphics x <- diagnosticPropertyPlot2(gopheridge, v, k=3) # check output str(x) } diagnosticPropertyPlot2 Diagnostic Property Plot (lattice) Description Generate a graphical description of the presence/absence of soil diagnostic properties. Usage diagnosticPropertyPlot2(f, v, k, grid.label = "pedon_id", sort.vars = TRUE) Arguments f SoilProfileCollection object v character vector of site-level attribute names of logical type k an integer, number of groups to highlight grid.label the name of a site-level attribute (usually unique) annotating the y-axis of the grid sort.vars sort variables according to natural clustering (TRUE), or use supplied ordering in v Details This function attempts to display several pieces of information within a single figure. First, soil profiles are sorted according to the presence/absence of diagnostic features named in v. Second, these diagnostic features are sorted according to their distribution among soil profiles. Third, a binary grid is established with row-ordering of profiles based on step 1 and column-ordering based on step 2. Blue cells represent the presence of a diagnostic feature. Soils with similar diagnostic features should ’clump’ together. See examples below. Value a list is silently returned by this function, containing: rd a data.frame containing IDs and grouping code profile.order a vector containing the order of soil profiles (row-order in figure), according to diagnostic property values var.order a vector containing the order of variables (column-order in figure), according to their distribution among profiles Author(s) <NAME> and <NAME> See Also multinominal2logical Examples if(require(aqp) & require(soilDB) & require(latticeExtra) ) { # sample data, an SPC data(gopheridge, package = 'soilDB') # get depth class sdc <- getSoilDepthClass(gopheridge, name = 'hzname') site(gopheridge) <- sdc # diagnostic properties to consider, no need to convert to factors v <- c('lithic.contact', 'paralithic.contact', 'argillic.horizon', 'cambic.horizon', 'ochric.epipedon', 'mollic.epipedon', 'very.shallow', 'shallow', 'mod.deep', 'deep', 'very.deep') # base graphics x <- diagnosticPropertyPlot(gopheridge, v, k=5) # lattice graphics x <- diagnosticPropertyPlot2(gopheridge, v, k=3) # check output str(x) } dist.along.grad Compute Euclidean distance along a gradient. Description This function computes Euclidean distance along points aligned to a given gradient (e.g. elevation). Usage dist.along.grad(coords, var, grad.order, grad.scaled.min, grad.scaled.max) Arguments coords a matrix of x and y coordinates in some projected coordinate system var a vector of the same length as coords, describing the gradient of interest grad.order vector of integers that define ordering of coordinates along gradient grad.scaled.min min value of rescaled gradient values grad.scaled.max max value of rescaled gradient values Details This function is primarily intended for use within plotTransect. Value A data.frame object: scaled.grad scaled gradient values scaled.distance cumulative distance, scaled to the interval of 0.5, nrow(coords) + 0.5 distance cumulative distance computed along gradient, e.g. transect distance variable sorted gradient values x x coordinates, ordered by gradient values y y coordinate, ordered by gradient values grad.order a vector index describing the sort order defined by gradient values Note This function is very much a work in progress, ideas welcome. Author(s) <NAME> See Also plotTransect dueling.dendrograms Dueling Dendrograms Description Graphically compare two related dendrograms Usage dueling.dendrograms( p.1, p.2, lab.1 = "D1", lab.2 = "D2", cex.nodelabels = 0.75, arrow.length = 0.05 ) Arguments p.1 left-hand phylo-class dendrogram p.2 right-hand phylo-class dendrogram lab.1 left-hand title lab.2 right-hand title cex.nodelabels character expansion size for node labels arrow.length arrow head size Details Connector arrows are used to link nodes from the left-hand dendrogram to the right-hand dendro- gram. Value nothing is returned, function is called to generate graphical output Author(s) <NAME> ESS_by_Moran_I Estimate Effective Sample Size Description Estimation of effective sample size (ESS). See Fortin & Dale 2005, p. 223, Equation 5.15 using global Moran’s I as ’rho’. Usage ESS_by_Moran_I(n, rho) Arguments n sample size rho Global Moran’s I Value numeric; estimated Effective Sample Size Author(s) <NAME> References Fortin, M.J. and Dale, M.R.T. (2005) Spatial Analysis: A Guide for Ecologists. Cambridge Univer- sity Press, Cambridge, 1-30. estimateSoilMoistureState A very simple estimation of soil moisture state based on volumetric water content Description This is a very simple classification of volumetric water content (VWC) into 5 "moisture states", based on an interpretation of water retention thresholds. Classification is performed using VWC at satiation, field capacity (typically 1/3 bar suction), permanent wilting point (typically 15 bar suc- tion), and water surplus in mm. The inputs to this function are closely aligned with the assumptions and output from hydromad::hydromad(sma = 'bucket', ...). Soil moisture classification rules are as follows: • VWC <= pwp: "very dry" • VWC > pwp AND <= (mid-point between fc and pwp): "dry" • VWC > (mid-point between fc and pwp) AND <= fc: "moist" • VWC > fc: "very moist" • VWC > fc AND U (surplus) > 4mm: "wet" Usage estimateSoilMoistureState( VWC, U, sat, fc, pwp, style = c("default", "newhall") ) Arguments VWC vector of volumetric water content (VWC), range is 0-1 U vector of surplus water (mm) sat satiation water content, range is 0-1 fc field capacity water content, range is 0-1 pwp permanent wilting point water content, range is 0-1 style VWC classification style Value vector of moisture states (ordered factor) Author(s) <NAME> Examples # "very moist" estimateSoilMoistureState(VWC = 0.3, U = 0, sat = 0.35, fc = 0.25, pwp = 0.15) estimateSoilMoistureState(VWC = 0.3, U = 2, sat = 0.35, fc = 0.25, pwp = 0.15) "wet" estimateSoilMoistureState(VWC = 0.3, U = 5, sat = 0.35, fc = 0.25, pwp = 0.15) # "very dry" estimateSoilMoistureState(VWC = 0.15, U = 0, sat = 0.35, fc = 0.25, pwp = 0.15) # "dry" estimateSoilMoistureState(VWC = 0.18, U = 0, sat = 0.35, fc = 0.25, pwp = 0.15) FFD Frost-Free Day Evaluation Description Evaluation frost-free days and related metrics from daily climate records. Usage FFD( d, returnDailyPr = TRUE, minDays = 165, frostTemp = 32, endSpringDOY = 182, startFallDOY = 213 ) Arguments d data.frame with columns ’datetime’ ’year’, and ’value’; ’value’ being daily minimum temperature, see details returnDailyPr optionally return list with daily summaries minDays min number of days of non-NA data in spring | fall, required for a reasonable estimate of FFD frostTemp critical temperature that defines "frost" (same units as d$value) endSpringDOY day of year that marks end of "spring" (typically Jan 1 – June 30) startFallDOY day of year that marks start of "fall" (typically Aug 1 – Dec 31) Details The default frostTemp=32 is suitable for use with minimum daily temperatures in degrees Fahren- heit. Use frostTemp = 0 for temperatures in degrees Celsius. FFD tutorial Value a data.frame when a returnDailyPr=FALSE, otherwise a list with the following elements: • summary: FFD summary statistics as a data.frame • fm: frost matrix • Pr.frost: Pr(frost|day): daily probability of frost Author(s) <NAME> Examples # 11 years of data from highland meadows data('HHM', package = 'sharpshootR') x.ffd <- FFD(HHM, returnDailyPr = FALSE, frostTemp = 32) str(x.ffd) FFDplot Plot output from FFD() Description Plot output from FFD() Usage FFDplot(s, sub.title = NULL) Arguments s output from FFD, with returnDailyPr = TRUE sub.title figure subtitle Value nothing, function is called to generate graphical output Examples # 11 years of data from highland meadows data('HHM', package = 'sharpshootR') x.ffd <- FFD(HHM, returnDailyPr = TRUE, frostTemp=32) FFDplot(x.ffd) formatPLSS formatPLSS Description Format PLSS information into a coded format that can be digested by PLSS web service. Usage formatPLSS(p, type = "SN") Arguments p data.frame with chunks of PLSS coordinates type an option to format protracted blocks ’PB’, unprotracted blocks ’UP’, or stan- dard section number ’SN’ (default). Details This function is typically accessed as a helper function to prepare data for use within PLSS2LL function. Value A vector of PLSS codes. Note This function expects that the Polygon object has coordinates associated with a projected CRS– e.g. units of meters. This function requires the following packages: stringi. Author(s) <NAME>, <NAME>, <NAME> See Also PLSS2LL Examples # create some data d <- data.frame( id = 1:3, qq = c('SW', 'SW', 'SE'), q = c('NE', 'NW', 'SE'), s = c(17, 32, 30), t = c('T36N', 'T35N', 'T35N'), r = c('R29W', 'R28W', 'R28W'), type = 'SN', m = 'MT20', stringsAsFactors = FALSE ) # add column names names(d) <- c('id', 'qq', 'q', 's', 't', 'r', 'type', 'm') # generate formatted PLSS codes formatPLSS(d, type='SN') generateLineHash Generate a unique ID for line segments Description Generate a unique ID for a line segment, based on the non-cryptographic murmur32 hash. Usage generateLineHash(x, precision = -1, algo = "murmur32") Arguments x an sf object, with 1 line segment per feature precision digits are rounded to this many places to the right (negative) or left (positive) of the decimal place algo hash function algorithm, passed to digest::digest() Details The input sf object must NOT contain multi-part features. The precision specified should be tai- lored to the coordinate system in use and the snapping tolerance used to create join decision line segments. A precision of 4 is reasonable for geographic coordinates (snapping tolerance of 0.0001 degrees or ~ 10 meters). A precision of -1 (snapping tolerance of 10 meters) is reasonable for pro- jected coordinate systems with units in meters. Value A vector of unique IDs created from the hash of line segment start and end vertex coordinates. Unique IDs are returned in the order of records of x and can therefore be saved into a new column of the associated attribute table. NA is returned for empty geometries. Note An error is issued if any non-unique IDs are generated. This could be caused by using coordinates that do not contain enough precision for unique hashing. Author(s) <NAME> Examples if(requireNamespace("sf")) { # 10 random line segments # shared end vertices .x <- runif(n = 11, min = 0, max = 100) .y <- runif(n = 11, min = 0, max = 100) m <- matrix(c(.x, .y), ncol = 2, byrow = TRUE) # init LINESTRING geometries a <- lapply(1:(nrow(m) - 1), function(i) { .idx <- c(i, i+1) geom <- sf::st_sfc(sf::st_linestring(m[.idx, ])) a <- sf::st_sf(geom) }) # flatten list -> 10 feature sf object a <- do.call('rbind', a) # line hashes a$id <- generateLineHash(a, precision = 0) # graphical check plot(a, lwd = 2, key.width = lcm(4), axes = TRUE, las = 1) # simulate empty geometry a$geom[2] <- sf::st_sfc(sf::st_linestring()) # NA returned for empty geometry generateLineHash(a, precision = 0) } geomorphBySoilSeries-SSURGO Geomorphic Position Probability via SDA Description Hillslope position probability estimates from the SDA query service (SSURGO) Usage hillslopeProbability(s, replaceNA=TRUE) surfaceShapeProbability(s, replaceNA=TRUE) geomPosHillProbability(s, replaceNA=TRUE) geomPosMountainProbability(s, replaceNA=TRUE) Arguments s a character vector of soil series names, automatically normalized to upper case replaceNA boolean: should missing classes be converted to probabilities of 0? Details These functions send a query to the SDA webservice. Further information on the SDA webservice and query examples can be found at http://sdmdataaccess.nrcs.usda.gov/QueryHelp.aspx Value A data.frame object with rows representing soil series, and columns representing probability esti- mates of that series occurring at specified geomorphic positions or associated with a surface shape. Note Probability values are computed from SSURGO data. Author(s) <NAME> HenryTimeLine Sensor Data Timeline from Henry Mount Soil and Water DB Description This function generates a simple chart of start/end dates for non-NA sensor data returned by soilDB::fetchHenry(). Data are organized according to sensor name + sensor depth. Usage HenryTimeLine(sensor_data, ...) Arguments sensor_data soiltemp, soilVWC, or related data returned by soilDB::fetchHenry() ... additional arguments to latticeExtra::segplot Value a lattice graphics object Author(s) <NAME> HHM Highland Meadows Description 11 years of climate data from the Highland Meadows weather station, as maintained by CA DWR. Usage data("HHM") Format A data frame with 3469 observations on the following 12 variables. station_id a character vector dur_code a character vector sensor_num a numeric vector sensor_type a character vector value a numeric vector flag a character vector units a character vector datetime a POSIXct year a numeric vector month a factor with levels January February March April May June July August September October November December water_year a numeric vector water_day a numeric vector huePositionPlot Hue Position Chart Description A simple visualization of the hue positions for a given Munsell value/chroma according to Soil Survey Technical Note 2. Usage huePositionPlot( value = 6, chroma = 6, chip.cex = 4.5, label.cex = 0.75, contour.dE00 = FALSE, origin = NULL, origin.cex = 0.75, grid.res = 2, ... ) Arguments value a single Munsell value chroma a single Munsell chroma chip.cex scaling for color chip rectangle label.cex scaling for color chip contour.dE00 logical, add dE00 contours from origin, imlpicitly TRUE when origin is not NULL origin point used for distance comparisons can be either single row matrix of CIELAB coordinates, a character vector specifying a Munsell color. By default (NULL) represents CIELAB coordinates (L,0,0), where L is a constant value determined by value and chroma. See examples. origin.cex scaling for origin point grid.res grid resolution for contours, units are CIELAB A/B coordinates. Caution, small values result in many pair-wise distances which could take a very long time. ... additional arguments to contour() Value nothing, function is called to generate graphical output Examples ## Not run: huePositionPlot(value = 4, chroma = 4) huePositionPlot(value = 6, chroma = 6) huePositionPlot(value = 8, chroma = 8) huePositionPlot(value = 6, chroma = 6, contour.dE00 = TRUE, grid.res = 2) # shift origin to arbitrary CIELAB coordinates or Munsell color huePositionPlot(origin = cbind(40, 5, 15), origin.cex = 0.5) huePositionPlot(origin = '5G 6/4', origin.cex = 0.5) huePositionPlot(origin = '10YR 3/4', origin.cex = 0.5) huePositionPlot(value = 3, chroma = 4, origin = '10YR 3/4', origin.cex = 0.5) ## End(Not run) hydOrder Hydrologic Ordering of a Geomorphic Proportion Matrix Description Hydrologic Ordering of a Geomorphic Proportion Matrix Usage hydOrder(x, g, clust = TRUE, j.amount = 0) Arguments x x data.frame, geomorphic proportion matrix, as created by soilDB::fetchOSD(..., extended=TRUE) g character, name of geomorphic summary table, one of: c('geomcomp', 'hillpos', 'flats', 'terrace', 'mtnpos', 'shape') clust logical, perform clustering of geomorphic proportion matrix j.amount amount of noise applied to rows having a duplicate proportion vector, passed to jitter() Value when clust = FALSE a vector of series names, in hydrologic ordering, otherwise a list with the following elements: • clust: rotated hclust object • hyd.order: vector of series names, in hydrologic ordering • clust.hyd.order: vector of series names, after clustering + rotation, approximate hydrologic ordering • match.rate: fraction of series matching target hydrologic ordering, after clustering + rotation • obj: objective function value (sum of squared rank differences), used by iterateHydOrder() Author(s) <NAME> Examples # example data, similar to results from soilDB::fetchOSD(..., extended = TRUE) data("OSDexamples") # no clustering of the geomorphic proportion matrix h <- hydOrder(OSDexamples$hillpos, g = 'hillpos', clust = FALSE) # compare with original order data.frame( original = OSDexamples$hillpos$series, ordered = h ) # cluster results h <- hydOrder(OSDexamples$hillpos, g = 'hillpos', clust = TRUE) str(h) isMineralSoilMaterial Mineral Soil Material Criteria from 12th Ed. of KST Description Evaluate mineral soil material criteria based on soil organic carbon, clay content, and length of saturation. Usage isMineralSoilMaterial(soc, clay, saturation = TRUE) Arguments soc soil organic carbon percent by mass clay clay content percent by mass saturation logical, cumulative saturation 30+ days Value data.frame of criteria test results iterateHydOrder Iteratively Attempt Hydrologic Ordering of Geomorphic Proportion Matrix Description Iteratively Attempt Hydrologic Ordering of Geomorphic Proportion Matrix Usage iterateHydOrder( x, g, target = 0.9, maxIter = 20, j.amount = 0.05, verbose = FALSE, trace = FALSE ) Arguments x data.frame geomorphic proportion matrix, as created by soilDB::fetchOSD(..., extended=TRUE) g name of geomorphic summary table, one of: c('geomcomp', 'hillpos', 'flats', 'terrace', 'mtnpos', 'shape') target numeric, target match rate maxIter integer, maximum number of perturbations of geomorphic probability matrix j.amount numeric, amount of noise applied to rows with too few unique values, passed to jitter() verbose logical, additional output printed via message trace logical, additional list of results for each iteration Details This function is used by the suite of geomorphic proportion visualization functions (viz*) to attempt rotation of a dendrogram according to "hydrologic ordering" rules. A perfect rotation is not always possible, and reported as a match rate in the returned score value Value A list with the following elements: • clust: rotated hclust object • hyd.order: vector of series names, in hydrologic ordering • clust.hyd.order: vector of series names, after clustering + rotation, approximate hydrologic ordering • match.rate: fraction of series matching target hydrologic ordering, after clustering + rotation • obj: objective function value (sum of squared rank differences), used by iterateHydOrder() • niter: number of iterations • trace: list of results by iteration, only when trace = TRUE Author(s) <NAME> Examples # example data, similar to results from soilDB::fetchOSD(..., extended = TRUE) data("OSDexamples") # single iteration of hydrologic ordering h1 <- hydOrder(OSDexamples$hillpos, g = 'hillpos', clust = TRUE) # perform several iterations, keep the best one h2 <- iterateHydOrder(OSDexamples$hillpos, 'hillpos', verbose = TRUE) # compare: only slightly better match rate achieved h1$match.rate h2$match.rate # return trace log for eval of objective function # increase max iterations h2 <- iterateHydOrder(OSDexamples$hillpos, 'hillpos', maxIter = 100, verbose = TRUE, trace = TRUE) # inspect objective function evolution tr <- h2$trace obj <- sapply(tr, '[[', 'obj') plot(obj, type = 'b') hist(obj) # in this case the clustering of hillpos proportions has only two possible configurations joinAdjacency Join Document Adjacency Description Convert a set of line segment "join decisions" into a weighted adjacency matrix describing which map unit symbols touch. Usage joinAdjacency(x, vars = c("l_musym", "r_musym")) Arguments x data.frame or similar object, each row represents a single shared edge (typi- cally sf LINESTRING feature) vars a vector of two characters naming columns containing "left", and "right" map unit symbols Value A weighted adjacency matrix is returned, suitable for plotting directly with plotSoilRelationGraph(). Author(s) <NAME> See Also plotSoilRelationGraph() LL2PLSS LL2PLSS Description Uses latitude and longitude coordinates to return the PLSS section geometry from the BLM PLSS web service. Usage LL2PLSS(x, y, returnlevel = c("I", "S")) Arguments x longitude coordinates (WGS84) y latitude coordinates (WGS84) returnlevel ’S’ for "Section" or ’I’ for "Intersection" (subsections) Details This function accepts geographic coordinates and returns the PLSS fabric geometry to the quarter- quarter section. returnlevel defaults to ’I’ which returns smallest intersected sectional aliquot ge- ometry, ’S’ will return the section geometry of the coordinates. See https://gis.blm.gov/arcgis/rest/services/Cadastral/BLM_N for details. Value sf object with geometry and PLSS definition. Note This function requires the following packages: httr, jsonlite, and sp. Author(s) <NAME>, <NAME>, <NAME> See Also PLSS2LL, formatPLSS moistureStateProportions Compute moisture state proportions Description Compute moisture state proportions Usage moistureStateProportions(x, id = "compname", step = c("month", "week", "doy")) Arguments x data.frame created by dailyWB() or dailyWB_SSURGO() id character, column name identifying sites, components, or soil series step time step, one of ’month’, ’week’, or ’doy’ Value data.frame moistureStateStats Statistics on Soil Moisture State Description Statistics on Soil Moisture State Usage moistureStateStats(x, id = "compname") Arguments x data.frame, created by moistureStateProportions() id name of ID column Value data.frame containing the most-likely moisture state and Shannon entropy. moistureStateThreshold Apply a threshold to soil moisture states Description Apply a threshold to soil moisture states Usage moistureStateThreshold( x, id = "compname", threshold = "moist", operator = c("<", ">", "==", "<=", ">=") ) Arguments x a data.frame created by dailyWB() or dailyWB_SSURGO() id character, column name identifying sites, soils, or soil series threshold moisture state threshold, see estimateSoilMoistureState operator one of "<", ">", "==", "<=", or ">=" Value data.frame Author(s) <NAME> monthlyWB Monthly Water Balances Description Perform a monthly water balance by "leaky bucket" model, inspired by code from bucket.sim of hydromad package, as defined in Bai et al., (2009) (model "SMA_S1"). The plant available water- holding storage (soil thickness * awc) is used as the "bucket capacity". All water in excess of this capacity is lumped into a single "surplus" term. Usage monthlyWB( AWC, PPT, PET, S_init = 1, starting_month = 1, rep = 1, keep_last = FALSE ) monthlyWB_summary(w) Arguments AWC available water-holding capacity (mm), typically thickness (mm) * awc (frac- tion) PPT time-series of monthly PPT (mm), calendar year ordering PET time-series of monthly PET (mm), calendar year ordering S_init initial fraction of AWC filled with water (values 0-1) starting_month starting month index, 1=January, 9=September rep number of cycles to run water balance keep_last keep only the last iteration of the water balance w used for for monthlyWB_summary(): a data.frame, such as result of monthlyWB(); Details See the monthly water balance tutorial for further examples and discussion. A number of important assumptions are made by this style of water balance modeling: • the concept of field capacity is built into the specified bucket size • the influence of aquitards or local terrain cannot be integrated into this model • interception is not used in this model Value a data.frame with the following elements: • PPT: monthly PPT (mm) • PET: monthly PET (mm) • U: monthly surplus (mm) • S: monthly soil moisture storage (mm) • ET: monthly AET (mm) • D: monthly deficit (mm) • month: month number • mo: month label monthlyWB_summary(): a data.frame containing: • cumulative (dry, moist, wet) days • consecutive (dry_con, moist_con, wet_con) days • total deficit (total_deficit) in mm • total surplus (total_surplus) in mm • total actual evapotranspiration (total_AET) in mm • annual actual evapotranspiration to potential evapotranspiration ratio (annual_AET_PET_ratio) References <NAME>, <NAME>. 1962. The use of calculated actual and potential evapotranspiration for estimat- ing potential plant growth. Hilgardia 32(10):443-469. <NAME>., <NAME> (2009). A top-down framework for watershed model evaluation and selection under uncertainty. Environmental Modelling and Software 24(8), pp. 901-916. <NAME>., <NAME>, <NAME>. (2003). Climate, soil and vegetation controls upon the vari- ability of water balance in temperate and semiarid landscapes: downward approach to water balance analysis. Water Resources Research 39(2), p 1035. Moran_I_ByRaster Compute Moran’s I for a raster sampled from a mapunit extent Description Compute Moran’s I using a subset of sample collected within the extent of a mapunit. This is likely an under-estimate of SA because we are including pixels both inside/outside MU delineations Usage Moran_I_ByRaster( r, mu.extent = NULL, n = NULL, k = NULL, do.correlogram = FALSE, cor.order = 5, crop.raster = TRUE ) Arguments r single SpatRaster mu.extent SpatVector representation of mapunit polygons bounding box (via terra::ext()) n number of regular samples (what is a reasonable value?) k number of neighbors used for weights matrix do.correlogram compute correlogram? cor.order order of correlogram crop.raster optionally disable cropping of the raster layer Details This function uses the spdep::moran.test() function Value If do.correlogram is TRUE a list with estimated Moran’s I ($I) and the correlogram ($correlogram), otherwise the estimated Moran’s I value. Author(s) <NAME> multinominal2logical Convert Multinominal to Logical Matrix Description Convert a single multinominal, site-level attribute from a SoilProfileCollection into a matrix of corresponding logical values. The result contains IDs from the SoilProfileCollection and can easily be joined to the original site-level data. Usage multinominal2logical(x, v) Arguments x a SoilProfileCollection object v the name of a site-level attribute that is a factor, or can be coerced to a factor, with more than 2 levels Value A data.frame with IDs in the first column, and as many columns of logical vectors as there were levels in v. See examples. Author(s) <NAME> See Also diagnosticPropertyPlot Examples if(require(soilDB) & require(aqp) & require(latticeExtra)) { # sample data, an SPC data(loafercreek, package='soilDB') # convert to logical matrix hp <- multinominal2logical(loafercreek, 'hillslopeprof') # join-in to site data site(loafercreek) <- hp # variable names v <- c('lithic.contact', 'paralithic.contact', 'argillic.horizon', 'toeslope', 'footslope', 'backslope', 'shoulder', 'summit') # visualize with some other diagnostic features x <- diagnosticPropertyPlot(loafercreek, v, k = 5, grid.label = 'bedrckkind', dend.label = 'pedon_id') } OSDexamples Example output from soilDB::fetchOSD() Description These example data are used to test various functions in this package when network access may be limited. Usage data(OSDexamples) Format An object of class list of length 17. PCP_plot Percentiles of Cumulative Precipitation Description Generate a plot representing percentiles of cumulative precipitation, given a historic record, and criteria for selecting a year of data for comparison. Usage PCP_plot( x, this.year, this.day = NULL, method = "exemplar", q.color = "RoyalBlue", c.color = "firebrick", ... ) Arguments x result from CDECquery for now, will need to generalize to other sources this.year a single water year, e.g. 2020 this.day optional integer representing days since start of selected water year method ’exemplar’ or ’daily’, currently ’exemplar’ is the only method available q.color color of percentiles cumulative precipitation c.color color of selected year ... additional arguments to plot Details This is very much a work in progress. Further examples at https://ncss-tech.github.io/AQP/ sharpshootR/CDEC.html, and https://ncss-tech.github.io/AQP/sharpshootR/cumulative-PPT. html. Value nothing, this function is called to create graphical output Author(s) <NAME> See Also waterDayYear percentileDemo Demonstration of Percentiles vs. Mean / SD Description This function can be used to graphically demonstrate the relationship between distribution shape, an idealized normal distribution (based on sample mean and sd) shape, and measures of central tendency / spread. Usage percentileDemo(x, labels.signif = 3, pctile.color = "RoyalBlue", mean.color = "Orange", range.color = "DarkRed", hist.breaks = 30, boxp = FALSE, ...) Arguments x vector of values to summarize labels.signif integer, number of significant digits to be used in figure annotation pctile.color color used to demonstrate range from 10th to 90th percentiles mean.color color used to specify mean +/- 2SD range.color color used to specify data range hist.breaks integer, number of suggested breaks to hist boxp logical, add a box and whisker plot? ... further arguments to plot Value A 1-row matrix of summary stats is invisibly returned. Note This function is mainly for educational purposes. Author(s) <NAME> References https://ncss-tech.github.io/soil-range-in-characteristics/why-percentiles.html Examples if (requireNamespace("Hmisc")) { x <- rnorm(100) percentileDemo(x) x <- rlnorm(100) percentileDemo(x) } plotAvailWater Visual Demonstration of Available Soil Water Description Generate a simplistic diagram of the various fractions of water held within soil pore-space. Largely inspired by Figure 2 from O’Geen (2013). Usage plotAvailWater( x, width = 0.25, cols = c(grey(0.5), "DarkGreen", "LightBlue", "RoyalBlue"), name.cex = 0.8, annotate = TRUE ) Arguments x a data.frame containing sample names and water retention data, see examples below width vertical width of each bar graph cols a vector of colors used to symbolize ’solid phase’, ’unavailable water’, ’available water’, and ’gravitational water’ name.cex character scaling of horizon names, printed on left-hand side of figure annotate logical, annotate AWC Value nothing, function is called to generate graphical output Author(s) <NAME> References <NAME>. (2013) Soil Water Dynamics. Nature Education Knowledge 4(5):9. Examples # demonstration s <- data.frame( name = c('<NAME>', '<NAME>', '<NAME>', '<NAME>'), pwp = c(0.05, 0.1, 0.18, 0.2), fc = c(0.1, 0.2, 0.38, 0.35), sat = c(0.25, 0.3, 0.45, 0.4)) s$solid <- with(s, 1-sat) par(mar=c(5, 6, 0.5, 0.5)) plotAvailWater(s, name.cex=1.25) if(requireNamespace("aqp")) { # demonstration using idealized AWC by soil texture data("ROSETTA.centroids", package = "aqp") # subset columns x <- ROSETTA.centroids[, c('texture', 'pwp', 'fc', 'sat', 'awc')] # adjust to expected names / additional data required by plotAvailWater names(x)[1] <- 'name' x$solid <- with(x, 1 - sat) # re-order based on approximate AWC x <- x[order(x$awc), ] op <- par(no.readonly = TRUE) par(mar=c(5, 6.5, 0.5, 0.5)) plotAvailWater(x, name.cex = 1) par(op) } # use some real data from SSURGO if(requireNamespace("curl") & curl::has_internet() & require(soilDB)) { q <- "SELECT hzdept_r as hztop, hzdepb_r as hzbottom, hzname as name, wsatiated_r/100.0 as sat, wthirdbar_r/100.0 as fc, wfifteenbar_r/100.0 as pwp, awc_r as awc FROM chorizon WHERE cokey IN (SELECT cokey from component where compname = 'dunstone') AND wsatiated_r IS NOT NULL ORDER BY cokey, hzdept_r ASC;" x <- SDA_query(q) x <- unique(x) x <- x[order(x$name), ] x$solid <- with(x, 1-sat) op <- par(no.readonly = TRUE) par(mar=c(5, 5, 0.5, 0.5)) plotAvailWater(x) par(op) } plotGeomorphCrossSection Present a SoilProfileCollection aligned to a geomorphic sum- mary as cross-section. Description Present a SoilProfileCollection aligned to a geomorphic summary as cross-section. Usage plotGeomorphCrossSection( x, type = c("line", "bar"), g = "hillpos", clust = TRUE, col = c("#377EB8", "#4DAF4A", "#984EA3", "#FF7F00", "#E41A1C"), ... ) Arguments x resulting list from soilDB::fetchOSD(..., extended = TRUE) type character, ’line’ for line plot or ’bar’ for barplot of geomorphic proportions g character, select a geomorphic summary. Currently ’hillpos’ (2D hillslope posi- tion) is the only supported choice. clust logical, use clustering order of geomorphic proportions (TRUE) or exact hydro- logic ordering (FALSE), see hydOrder() col character vector of colors ... additional arguments to iterateHydOrder() Details Additional arguments to aqp::plotSPC() can be provided using options(.aqp.plotSPC.args = list(...)). For example, adjustments to maximum depth and profile width can be set via: options(.aqp.plotSPC.args = list(max.depth = 150, width = 0.35). Default arguments can be reset with options(.aqp.plotSPC.args = NULL). When clust = TRUE, especially for SoilProfileCollections with a wide range in depth, it may be necessary to adjust the scaling.factor argument to aqp::plotSPC() via: options(.aqp.plotSPC.args = list(scaling.factor = 0.01)). Larger values will increase the height of profile sketches. Author(s) <NAME> plotProfileDendrogram Plot soil profiles below a dendrogram Description Plot soil profiles below a dendrogram Usage plotProfileDendrogram( x, clust, rotateToProfileID = FALSE, scaling.factor = 0.01, width = 0.1, y.offset = 0.1, dend.y.scale = max(clust$height * 2, na.rm = TRUE), dend.color = par("fg"), dend.width = 1, dend.type = c("phylogram", "cladogram"), debug = FALSE, ... ) Arguments x a SoilProfileCollection object clust a hierarchical clustering object generated by hclust, cluster::agnes, or cluster::diana rotateToProfileID logical, attempt rotation of dendrogram according to original profile IDs, re- quires dendExtend package scaling.factor vertical scaling of the profile heights (may have to tinker with this) width scaling of profile widths y.offset vertical offset for top of profiles dend.y.scale extent of y-axis (may have to tinker with this) dend.color dendrogram line color dend.width dendrogram line width dend.type dendrogram type, passed to plot.phylo(), either "phylogram" or "cladogram" debug logical,optionally print debugging data ... additional arguments to plotSPC Details This function places soil profile sketches below a dendrogram. Value a data.frame of IDs and linking structure Note You may have to tinker with some of the arguments to get optimal arrangement and scaling of soil profiles. Author(s) <NAME> plotSoilRelationChordGraph Visualize Soil Relationships via Chord Diagram Description Visualize Soil Relationships via Chord Diagram Usage plotSoilRelationChordGraph( m, s, mult = 2, base.color = "grey", highlight.colors = c("RoyalBlue", "DarkOrange", "DarkGreen"), add.legend = TRUE, ... ) Arguments m an adjacency matrix, no NA allowed s soil of interest, must exist in the column or row names of m mult multiplier used to re-scale data in m associated with s base.color color for all soils other than s and 1st and 2nd most commonly co-occurring soils highlight.colors vector of 3 colors: soil of interest, 1st most common, 2nd most common add.legend logical, add a legend ... additional arguments passed to circlize::chordDiagramFromMatrix Details This function is experimental. Documentation pending. See http://jokergoo.github.io/circlize/ for ideas. Value nothing, function is called to generate graphical output Author(s) <NAME> plotSoilRelationGraph Plot a component relation graph Description Plot a component relation graph based on an adjacency or similarity matrix. Usage plotSoilRelationGraph( m, s = "", plot.style = c("network", "dendrogram", "none"), graph.mode = "upper", spanning.tree = NULL, del.edges = NULL, vertex.scaling.method = "degree", vertex.scaling.factor = 2, edge.scaling.factor = 1, vertex.alpha = 0.65, edge.transparency = 1, edge.col = grey(0.5), edge.highlight.col = "royalblue", g.layout = igraph::layout_with_fr, vertex.label.color = "black", delete.singletons = FALSE, ... ) Arguments m adjacency matrix s central component; an empty character string is interpreted as no central com- ponent plot.style plot style (’network’, or ’dendrogram’), or ’none’ for no graphical output graph.mode interpretation of adjacency matrix: ’upper’ or ’directed’, see details spanning.tree plot the minimum or maximum spanning tree (’min’, ’max’), or, max span- ning tree plus edges with weight greater than the n-th quantile specified in spanning.tree. See details and examples. del.edges optionally delete edges with weights less than the specified quantile (0-1) vertex.scaling.method ’degree’ (default) or ’distance’, see details vertex.scaling.factor scaling factor applied to vertex size edge.scaling.factor optional scaling factor applied to edge width vertex.alpha optional transparency setting for vertices (0-1) edge.transparency optional transparency setting for edges (0-1) edge.col edge color, applied to all edges edge.highlight.col edge color applied to all edges connecting to component named in s g.layout an igraph layout function, defaults to igraph::layout_with_fr vertex.label.color vertex label color delete.singletons optionally delete vertices with no edges (degree == 0) ... further arguments passed to plotting function Details Vertex size is based on a normalized index of connectivity: • "degree" size = sqrt(igraph::degree(g) / max(igraph::degree(g))) * scaling.factor • "distance" size = sqrt(igraph::distance(V -> s) / max(igraph::distance(V -> s))) * scaling.factor, where distance(V->s) is the distance from all nodes to the named series, s. Edge width can be optionally scaled by edge weight by specifying an edge.scaling.factor value. The maximum spanning tree represents a sub-graph where the sum of edge weights are maximized. The minimum spanning tree represents a sub-graph where the sum of edge weights are minimized. The maximum spanning tree is likely a more useful simplification of the full graph, in which only the strongest relationships (e.g. most common co-occurrences) are preserved. The maximum spanning tree + edges with weights > n-th quantile is an experimental hybrid. The ’backbone’ of the graph is created by the maximum spanning tree, and augmented by ’strong’ auxiliary edges–defined by a value between 0 and 1. The graph.mode argument is passed to igraph::graph_from_adjacency_matrix() and deter- mines how vertex relationships are coded in the adjacency matrix m. Typically, the default value of ’upper’ (the upper triangle of m contains adjacency information) is the desired mode. If m contains directional information, set graph.mode to ’directed’. This has the side-effect of altering the default community detection algorithm from igraph::cluster_fast_greedy to igraph::cluster_walktrap. Value an igraph graph object is invisibly returned Note This function is a work in progress, ideas welcome. Author(s) <NAME> Examples if (requireNamespace("igraph")) { # load sample data set data(amador) # create weighted adjacency matrix (see ?component.adj.matrix for details) m <- component.adj.matrix(amador) # plot network diagram, with Amador soil highlighted plotSoilRelationGraph(m, s='amador') # dendrogram representation plotSoilRelationGraph(m, s='amador', plot.style='dendrogram') # compare methods m.o <- component.adj.matrix(amador, method='occurrence') op <- par(no.readonly = TRUE) par(mfcol=c(1,2)) plotSoilRelationGraph(m, s='amador', plot.style='dendrogram') title('community matrix') plotSoilRelationGraph(m.o, s='amador', plot.style='dendrogram') title('occurence') # investigate max spanning tree plotSoilRelationGraph(m, spanning.tree='max') # investigate max spanning tree + edges with weights > 75-th pctile plotSoilRelationGraph(m, spanning.tree=0.75) par(op) if(requireNamespace("curl") & curl::has_internet() & require(soilDB)) { # get similar data from soilweb, for the Pardee series s <- 'pardee' d <- siblings(s, component.data = TRUE) # normalize component names d$sib.data$compname <- tolower(d$sib.data$compname) # keep only major components d$sib.data <- subset(d$sib.data, subset=compkind == 'Series') # build adj. matrix and plot m <- component.adj.matrix(d$sib.data) plotSoilRelationGraph(m, s=s, plot.style='dendrogram') # alter plotting style, see ?plot.phylo plotSoilRelationGraph(m, s=s, plot.style='dendrogram', type='fan') plotSoilRelationGraph(m, s=s, plot.style='dendrogram', type='unrooted', use.edge.length=FALSE) } } plotTransect Arrange Profiles along a Transect Description Plot a collection of Soil Profiles linked to their position along some gradient (e.g. transect). Usage plotTransect( s, xy, grad.var.name, grad.var.order = order(site(s)[[grad.var.name]]), transect.col = "RoyalBlue", tick.number = 7, y.offset = 100, scaling.factor = 0.5, distance.axis.title = "Distance Along Transect (km)", grad.axis.title = NULL, dist.scaling.factor = 1000, spacing = c("regular", "relative"), fix.relative.pos = list(thresh = 0.6, maxIter = 5000), ... ) Arguments s SoilProfileCollection object xy sf object, defining point coordinates of soil profiles, must be in same order as s, must be a projected coordinate reference system (UTM, AEA, etc.) grad.var.name the name of a site-level attribute containing gradient values grad.var.order optional indexing vector used to override sorting along grad.var.name transect.col color used to plot gradient (transect) values tick.number number of desired ticks and labels on the gradient axis y.offset vertical offset used to position profile sketches scaling.factor scaling factor applied to profile sketches distance.axis.title a title for the along-transect distances grad.axis.title a title for the gradient axis dist.scaling.factor scaling factor (divisor) applied to linear distance units, default is conversion from m to km (1000) spacing profile sketch spacing style: "regular" (profiles aligned to an integer grid) or "relative" (relative distance along transect) fix.relative.pos adjust relative positions in the presence of overlap, FALSE to suppress, otherwise list of arguments to aqp::fixOverlap ... further arguments passed to aqp::plotSPC. Details Depending on the nature of your SoilProfileCollection and associated gradient values, it may be necessary to tinker with figure margins, y.offset and scaling.factor. Value An invisibly-returned data.frame object: • scaled.grad: scaled gradient values • scaled.distance: cumulative distance, scaled to the interval of 0.5, nrow(coords) + 0.5 • distance: cumulative distance computed along gradient, e.g. transect distance • variable: sorted gradient values • x: x coordinates, ordered by gradient values • y: y coordinate, ordered by gradient values • grad.order: a vector index describing the sort order defined by gradient values Note This function is very much a work in progress, ideas welcome! Author(s) <NAME> Examples if(require(aqp) & require(sf) & require(soilDB) ) { library(aqp) library(soilDB) library(sf) # sample data data("mineralKing", package = "soilDB") # device options are modified locally, reset when done op <- par(no.readonly = TRUE) # quick overview par(mar=c(1,1,2,1)) groupedProfilePlot(mineralKing, groups='taxonname', print.id=FALSE) # setup point locations s <- site(mineralKing) xy <- st_as_sf(s, coords = c('x_std', 'y_std')) st_crs(xy) <- 4326 # convert to suitable projected cRS # projected CRS, UTM z11 NAD83 (https://epsg.io/26911) xy <- st_transform(xy, 26911) # adjust margins par(mar = c(4.5, 4, 4, 1)) # standard transect plot, profile sketches arranged along integer sequence plotTransect(mineralKing, xy, grad.var.name = 'elev_field', grad.axis.title = 'Elevation (m)', label = 'pedon_id', name = 'hzname') # default behavior, attempt adjustments to prevent over-plot and preserve relative spacing # use set.seed() to fix outcome plotTransect(mineralKing, xy, grad.var.name = 'elev_field', grad.axis.title = 'Elevation (m)', label = 'pedon_id', name = 'hzname', width = 0.15, spacing = 'relative') # attempt relative positioning based on scaled distances, no corrections for overlap # profiles are clustered in space and therefore over-plot plotTransect(mineralKing, xy, grad.var.name = 'elev_field', grad.axis.title = 'Elevation (m)', label = 'pedon_id', name = 'hzname', width = 0.15, spacing = 'relative', fix.relative.pos = FALSE) # customize arguments to aqp::fixOverlap() plotTransect(mineralKing, xy, grad.var.name = 'elev_field', crs = crs.utm, grad.axis.title = 'Elevation (m)', label = 'pedon_id', name = 'hzname', width = 0.15, spacing = 'relative', fix.relative.pos = list(maxIter=6000, adj=0.2, thresh=0.7)) plotTransect(mineralKing, xy, grad.var.name = 'elev_field', crs = crs.utm, grad.axis.title = 'Elevation (m)', label = 'pedon_id', name = 'hzname', width = 0.2, spacing = 'relative', fix.relative.pos = list(maxIter = 6000, adj = 0.2, thresh = 0.6), name.style = 'center-center') par(op) } plotWB Visualize Monthly Water Balance Description This function offers one possible visualization for the results of monthlyWB(). Note that "surplus" water is stacked on top of "actual ET", and "deficit" water is stacked below "storage". Calculate actual values for "surplus" and "deficit" from the figure like this: • surplus value = surplus - AET • deficit value = deficit - storage Usage plotWB( WB, AWC = attr(WB, "AWC"), sw.col = "#377EB8", surplus.col = "#4DAF4A", et.col = "#E41A1C", deficit.col = "#FF7F00", pch = c(21, 21), pt.cex = 1, pt.col = par("bg"), pt.bg = par("fg"), lty = c(1, 2), lwd = 2, n.ticks = 8, grid.col = grey(0.65), month.cex = 1, legend.cex = 0.9, ylim ) Arguments WB output from monthlyWB() AWC available water-holding capacity (mm), typically the value used in monthlyWB() and stored as an attribute of WB sw.col color for soil water ("storage) surplus.col color for surplus water et.col color for ET deficit.col color for deficit pch plotting character for PPT and PET points pt.cex character expansion factor for PPT and PET points pt.col point symbol color for PPT and PET points pt.bg point symbol background color for PPT and PET points lty line type for PPT and PET lines (c(1, 2)) lwd line width for PPT and PET curves n.ticks approximate number of tick marks on positive and negative y-axis grid.col horizontal grid line color month.cex scaling factor for month labels (x-axis) legend.cex scaling factor for legend ylim optional vector of y-axis limits, c(-min, max), typically used when comparing drastically different water balances in the same figure. Default limits are usually best for a single water balance plot. Value nothing, function is called to generate graphical output Note You may have to adjust figure margins and size to get all of the elements to "look right". Author(s) <NAME> and <NAME> Examples if(requireNamespace('hydromad')) { ## A shallow / droughty soil near Sonora CA # 100mm (4") AWC AWC <- 100 PPT <- c(171, 151, 138, 71, 36, 7, 1, 2, 11, 48, 102, 145) PET <- c(15.17, 18.26, 30.57, 42.95, 75.37, 108.05, 139.74, 128.9, 93.99, 59.84, 26.95, 14.2) # water-year # three years x.wb <- monthlyWB(AWC, PPT, PET, S_init = 0, starting_month = 9, rep = 3) x.wb[x.wb$mo == 'Sep', ] # plot all three years plotWB(x.wb) # water-year / last iteration x.wb <- monthlyWB(AWC, PPT, PET, S_init = 0, starting_month = 9, rep = 3, keep_last = TRUE ) # plot plotWB(x.wb) ## Drummer series (Fine-silty, mixed, superactive, mesic Typic Endoaquolls), southern IL AWC <- 244 PPT <- c(36, 37, 54, 82, 98, 96, 92, 75, 69, 70, 65, 50) PET <- c(0, 0, 12, 46, 90, 130, 145, 128, 88, 46, 14, 0) # using calendar year x.wb <- monthlyWB(AWC, PPT, PET, S_init = 0, starting_month = 1, rep = 3, keep_last = TRUE ) plotWB(x.wb) } plotWB_lines Line / Area Visualization for Monthly Water Balance Description Pending. Usage plotWB_lines( WB, cols = c("#759CC9", "#EB6D6E", "#7FC47D"), line.col = "black", line.lty = c(1, 2, 3), interpolator = c("spline", "linear"), spline.method = c("natural", "periodic"), month.cex = 1, legend.cex = 0.9 ) Arguments WB output from monthlyWB() cols vector of three colors used for area under PPT, PET, and AET curves line.col single color used for PPT, PET, and AET lines line.lty vector of three line styles used for PPT, PET, AET curves interpolator spline or linear interpolation of monthly values, use of spline may lead to minor smoothing artifacts in shaded areas spline.method when interpolator = 'spline', argument passed to splinefun(..., method = spline.method) month.cex scaling factor for month labels legend.cex scaling factor for legend Value nothing, function is called to generate graphical output Author(s) <NAME> and <NAME> Examples if(requireNamespace('hydromad')) { ## A shallow / droughty soil near Sonora CA # 100mm (4") AWC AWC <- 100 PPT <- c(171, 151, 138, 71, 36, 7, 1, 2, 11, 48, 102, 145) PET <- c(15.17, 18.26, 30.57, 42.95, 75.37, 108.05, 139.74, 128.9, 93.99, 59.84, 26.95, 14.2) # calendar-year # three year warm-up x.wb <- monthlyWB(AWC, PPT, PET, S_init = 0, starting_month = 1, rep = 3, keep_last = TRUE) # plot plotWB_lines(x.wb) } PLSS2LL PLSS2LL Description Fetch latitude and longitude (centroid) coordinates for coded PLSS information from the BLM PLSS web service. Usage PLSS2LL(p, plssid = "plssid") Arguments p data.frame with chunks of PLSS definition plssid column name containing PLSS ID Value A data.frame of PLSS codes and coordinates. Note This function expects that the dataframe will have a ’plssid’ column generated by the formatPLSS function. Requires the following packages: httr, and jsonlite. Author(s) <NAME>, <NAME>, <NAME> See Also LL2PLSS, formatPLSS polygonAdjacency Summarize Spatial Adjacency of Polygon Fabric Description This function utilizes the spdep and igraph packages to evaluate several measures of spatial con- nectivity. Usage polygonAdjacency(x, v = "MUSYM", ...) Arguments x sf object containing simple polygon features, some of which should share edges v character, name of column in attribute table describing map unit labels ... additional arguments passed to spdep::poly2nb() Details Examples are presented in this tutorial. Value a list containing: • commonLines: an integer vector of feature IDs, describing polygons sharing edges and values of v (map unit labels) • adjMat: weighted adjacency matrix, suitable for visualization with plotSoilRelationGraph() Author(s) <NAME> prepareDailyClimateData Prepare daily climate data (DAYMET) for a single point Description This function returns daily climate data required for a simple water balance (and more), using three packages: • elevatr: elevation data at x • daymetr: DAYMET data at x for years start through end • Evapotranspiration: Makkink formulation for estimating reference crop evapotranspiration Usage prepareDailyClimateData(x, start, end, onlyWB = TRUE) Arguments x sf object representing a single point start start year (1998) end end year (2018) onlyWB logical, return just those date required by dailyWB Value a data.frame prepare_SSURGO_hydro_data Get and prepare basic soil hydraulic parameters from SSURGO via SDA Description Get and prepare basic soil hydraulic parameters from SSURGO via SDA Usage prepare_SSURGO_hydro_data(cokeys, max.depth) Arguments cokeys vector of component keys (cokey) in current SSURGO snapshot max.depth target depth of aggregation (cm), corrected later by real soil depth as reported by slab() Details Weighted mean soil hydraulic parameters are returned over the interval of 0-max.depth, calculated by aqp::slab(). Value a list containing: • SPC: SoilProfileCollection • agg: aggregate representation of hydraulic parameters, by cokey The following soil hydraulic properties are included: variable description cokey component key hzname horizon name hz_top horizon top depth (cm) hz_bottom horizon bottom depth (cm) thick horizon thickness (cm) sat VWC at saturation (cm/cm) fc VWC at field capacity or 1/3rd bar tension (cm/cm) pwp VWC at permanent wilting point or 15 bar tension (cm/cm) awc total sand content (<2mm fraction, mass %) sand total silt content (<2mm fraction, mass %) silt total clay content (<2mm fraction, mass %) clay total sand content (<2mm fraction, mass %) dbthirdbar bulk density at 1/3 bar tension (g/cm^3) ksat Ksat (um/second) soil_fraction volume fraction of soil (1 - coarse fragment volume fraction) Author(s) <NAME> reconcileOSDGeomorph Reconcile IDs between a SPC and associated geomorphic proportion table Description This function can assist with linked visualizations that include soil morphology data stored in a SoilProfileCollection and geomorphic proportions stored in a data.frame, as returned by soilDB::fetchOSD(). Usage reconcileOSDGeomorph( x, selection = c("hillpos", "geomcomp", "flats", "mtnpos", "terrace", "shape_across", "shape_down") ) Arguments x resulting list from soilDB::fetchOSD(..., extended = TRUE) selection character, name of geomorphic proportion table Value a list with subset SoilProfileCollection and data.frame of geomorphic proportions, selection is preserved as an attribute. Author(s) <NAME> sample.by.poly Sample a Polygon at Fixed Density Description Generate sampling points within a SpatialPolygon object, according to a specified sampling density. Usage sample.by.poly(p, n.pts.per.ac=1, min.samples=5, sampling.type='regular', p4s=NULL) Arguments p a Polygon object, with coordinates in a projected CRS with units of meters n.pts.per.ac requested sampling density in points per acre (results will be close) min.samples minimum requested number of samples per polygon sampling.type sampling type p4s a qualified proj4string that will be assigned to sampling points Details This function is typically accessed via some kind of helper function such as constantDensitySampling. Value A SpatialPoints object. Note This function expects that the Polygon object has coordinates associated with a projected CRS– e.g. units of meters. Invalid geometries may cause errors or yield incorrect sample sizes. Author(s) <NAME> See Also constantDensitySampling sampleRasterStackByMU Sample a Raster Stack Description Sample a raster stack by map unit polygons, at a constant density. Usage sampleRasterStackByMU( mu, mu.set, mu.col, raster.list, pts.per.acre, p = c(0, 0.05, 0.25, 0.5, 0.75, 0.95, 1), progress = TRUE, estimateEffectiveSampleSize = TRUE, polygon.id = "pID" ) Arguments mu a SpatialPolygonsDataFrame object in a projected coordinate reference sys- tem (CRS) mu.set character vector of map unit labels to be sampled mu.col column name in attribute table containing map unit labels raster.list a list containing raster names and paths, see details below pts.per.acre target sampling density in points per acre p percentiles for polygon area stats, e.g. c(0.05, 0.25, 0.5, 0.75, 0.95) progress logical, print a progress bar while sampling? estimateEffectiveSampleSize estimate an effective sample size via Moran’s I? polygon.id Column name containing unique polygon IDs; default: "pID"; calculated if missing Details This function is used by various NRCS reports that summarize or compare concepts defined by collections of polygons using raster data sampled from within each polygon, at a constant sampling density. Even though the function name includes "RasterStack", this function doesn’t actually op- erate on the "stack" object as defined in the raster package. The collection of raster data defined in raster.list do not have to share a common coordinate reference system, grid spacing, or extent. Point samples generated from mu are automatically converted to the CRS of each raster before ex- tracting values. The extent of each raster in raster.list must completely contain the extent of mu. Value A list containing: raster.samples a data.frame containing samples from all rasters in the stack area.stats a data.frame containing area statistics for all map units in the collection unsampled.ids an index to rows in the original SPDF associated with polygons not sampled raster.summary a data.frame containing information on sampled rasters Moran_I a data.frame containing estimates Moran’s I (index of spatial autocorrelation) Author(s) <NAME> See Also constantDensitySampling, sample.by.poly samplingStability Estimate Sampling Stability Description Stability is defined as the width of the 5th-95th percentile range, over n.reps replications of median estimates associated with sampling events. The resulting width is scaled by the population median and returned as a fraction. Usage samplingStability( mu, r, n.set = c(0.01, 0.1, 0.5, 1, 2), n.reps = 10, p.id = "pID" ) Arguments mu map unit polygons, must have polygon ID, must be in CRS with units of meters r SpatRaster n.set set of sampling density values to try n.reps number of replications p.id polygon ID column name Value data.frame with median stability values as percentage of population median, range: [0,1] Author(s) <NAME> simpleWB Simple interface to the hydromad "leaky bucket" soil moisture model Description Simple interface to the hydromad "leaky bucket" soil moisture model. Usage simpleWB( PPT, PET, D, thickness, sat, fc, pwp, S_0 = 0.5, a.ss = 0.05, M = 0, etmult = 1 ) Arguments PPT precipitation series (mm) PET potential ET series (mm) D dates thickness soil thickness (cm) sat volumetric water content at saturation (satiated water content) fc volumetric water content at field capacity (typically 1/3 bar suction) pwp volumetric water content at permanent wilting point (typically 15 bar suction) S_0 initial soil moisture as a fraction of total water storage (mm) a.ss recession coefficients for subsurface flow from saturated zone, should be > 0 M fraction of area covered by deep-rooted vegetation etmult multiplier for PET Details Adjustments for coarse fragments should be made by reducing thickness. Value a data.frame References <NAME>., <NAME>, <NAME>. (2003). Climate, soil and vegetation controls upon the vari- ability of water balance in temperate and semiarid landscapes: downward approach to water balance analysis. Water Resources Research 39(2), p 1035. <NAME>., <NAME> (2009). A top-down framework for watershed model evaluation and selection under uncertainty. Environmental Modelling and Software 24(8), pp. 901-916. site_photos_kml site_photos_kml Description Generates a KML file of site locations with associated site photos and a link to a pedon description report. Usage site_photos_kml(data, filename='photos.kml', make.image.grid=FALSE, file.source = c('local', 'relative') ) Arguments data a dataframe filename full file path and name with .kml extension make.image.grid logical, include linked site images, default is FALSE file.source ’local’ sources the image files to a specific system path, ’relative’ sources the image files to files folder that can be included and referenced within a .kmz file Details This function simplifies writing a kml file of site and/or sites with linked photos. Further documen- tation is provided in this tutorial. Value A KML file of of sites with embedded associated site photos. Author(s) <NAME>, <NAME> SoilTaxonomyDendrogram Soil Taxonomy Dendrogram Description Plot a dendrogram based on the first 4 levels of Soil Taxonomy, with soil profiles hanging below. A dissimilarity matrix is computed using Gower’s distance metric for nominal (KST.order = FALSE) or ordinal (KST.order = TRUE) scale variables, based on soil order, suborder, greatgroup, and sub- group taxa. Usage SoilTaxonomyDendrogram( spc, KST.order = TRUE, rotationOrder = NULL, level = c(soilorder = "soilorder", suborder = "suborder", greatgroup = "greatgroup", subgroup = "subgroup"), cluster.method = c("divisive", "agglomerative"), cluster.args = list(), name = "hzname", name.style = "center-center", id.style = "side", n.depth.ticks = 6, scaling.factor = 0.015, cex.names = 0.75, cex.id = 0.75, width = 0.25, y.offset = 0.5, shrink = FALSE, font.id = 2, cex.taxon.labels = 0.66, font.taxon.labels = 3, dend.color = par("fg"), dend.width = 1, dend.type = c("phylogram", "cladogram"), max.depth = ifelse(is.infinite(max(spc)), 200, max(spc)), ... ) Arguments spc a SoilProfileCollection object, typically returned by soilDB::fetchOSD KST.order logical, encode / cluster taxa via ordinal factors, based on ordering within Keys to Soil Taxonomy rotationOrder character vector of profile IDs with desired ordering of leaves in the dendrogram from left to right; exact ordering is not always possible level character. One or more site-level columns in spc. Default: "soilorder", "suborder", "greatgroup" and "subgroup" cluster.method Either "divisive" (cluster::diana(); default) or "agglomerative" (cluster::agnes()) cluster.args Optional: additional arguments for cluster::diana() or cluster::agnes() cluster methods name column name containing horizon names name.style passed to aqp::plotSPC id.style passed to aqp::plotSPC n.depth.ticks suggested number of ticks on the depth axis scaling.factor scaling factor used to convert depth units into plotting units cex.names character scaling for horizon names cex.id character scaling for profile IDs width width of profiles y.offset vertical offset between dendrogram and profiles shrink logical, should long horizon names be shrunk by 80% ? font.id integer, font style applied to profile id, default is 2 (bold) cex.taxon.labels numeric, character scaling for taxonomic information font.taxon.labels integer, font style applied to taxa labels, default is 3 (italic) dend.color dendrogram line color dend.width dendrogram line width dend.type dendrogram type, passed to plot.phylo(), either "phylogram" or "cladogram" max.depth depth at which profiles are truncated for plotting ... additional arguments to aqp::plotSPC Details This function looks for specific site-level attributes named: "soilorder", "suborder", "greatgroup", and "subgroup", or their NASIS physical column name analogues "taxorder", "taxsuborder", "taxgrtgroup", and "taxsubgrp". See https://github.com/ncss-tech/sharpshootR/blob/ master/misc/soilTaxonomyDendrogram-examples.R for some examples. The rotationOrder argument uses ape::rotateConstr() to reorder leaves within the hclust representation of the ST hierarchy. Perfect sorting is not always possible. Value An invisibly-returned list containing: • dist: pair-wise dissimilarity matrix • order: final ordering of hclust leaves Author(s) <NAME> Examples # built-in data, same as results from soilDB::fetchOSD() data("OSDexamples") # examples using first 8 profiles # KST-style ordering SoilTaxonomyDendrogram( OSDexamples$SPC[1:8, ], width = 0.3, name.style = 'center-center', KST.order = TRUE, axis.line.offset = -4, scaling.factor = 0.014 ) # classic ordering, based on nominal scale variables (un-ordered factors) SoilTaxonomyDendrogram( OSDexamples$SPC[1:8, ], width = 0.3, name.style = 'center-center', KST.order = FALSE, axis.line.offset = -4, scaling.factor = 0.014 ) # adjust taxon label font and font size SoilTaxonomyDendrogram( OSDexamples$SPC[1:15, ], width = 0.3, name.style = 'center-center', KST.order = FALSE, axis.line.offset = -4, scaling.factor = 0.014, font.taxon.labels = 2, cex.taxon.labels = 0.55 ) # cladogram vs. dendrogram # truncate profiles at 150cm SoilTaxonomyDendrogram( OSDexamples$SPC[1:16, ], width = 0.3, name.style = 'center-center', KST.order = TRUE, axis.line.offset = -4, scaling.factor = 0.02, font.taxon.labels = 1, cex.taxon.labels = 0.55, dend.type = 'cladogram', max.depth = 150 ) table5.2 Table 5.2 from Hole and Campbell, 1985. Description An adjacency matrix describing shared soil map boundary segments from the Soil Survey of Shawnee county, KS. This is table 5.2 from Hole and Campbell, 1985. Usage data(table5.2) Format An object of class matrix (inherits from array) with 18 rows and 18 columns. References <NAME>. and <NAME>. Soil Landscape Analysis. Rowman and Allanheld, 1985. Examples data("table5.2") if(requireNamespace("igraph")) { # note special incantation to get the "correct" graph structure g <- igraph::graph_from_adjacency_matrix(table5.2, mode = 'upper', diag = FALSE, weighted = TRUE) # visualize op <- par(no.readonly = TRUE) par(mar = c(0,0,0,0)) plot(g) plot(g, vertex.size = sqrt(igraph::degree(g) * 25), vertex.label.family = 'sans') # find communities cm <- igraph::cluster_walktrap(g) plot(cm, g, vertex.label.family = 'sans') par(op) } vizAnnualClimate Annual Climate Summaries for Soil Series Data Description Annual climate summaries for soil series, based on latticeExtra::segplot, based on 5th, 25th, 50th, 75th, and 95th percentiles. Input data should be from soilDB::fetchOSD. Usage vizAnnualClimate(climate.data, IQR.cex = 1, s = NULL, s.col = "firebrick", ...) Arguments climate.data Annual climate summaries, as returned from soilDB::fetchOSD(..., extended=TRUE) IQR.cex scaling factor for bar representing interquartile range s a soil series name, e.g. "LUCY", to highlight s.col color for highlighted soil series ... further arguments passed to latticeExtra::segplot Details This function was designed for use with soilDB::fetchOSD. It might be possible to use with other sources of data but your mileage may vary. See the Soil Series Query Functions tutorial for more information. Value A list with the following elements: • fig: lattice object (the figure) • clust: clustering object returned by cluster::diana Author(s) <NAME> See Also vizHillslopePosition vizFlatsPosition Visual Summary of Flat Landform Positions Description A unique display of landform position probability. Usage vizFlatsPosition( x, s = NULL, annotations = TRUE, annotation.cex = 0.75, cols = c("#2B83BA", "#ABDDA4", "#FFFFBF", "#FDAE61", "#D7191C"), ... ) Arguments x data.frame as created by soilDB::fetchOSD(..., extended=TRUE), see de- tails s an optional soil series name, highlighted in the figure annotations logical, add number of record and normalized Shannon entropy values annotation.cex annotation label scaling factor cols vector of colors ... additional arguments to [iterateHydOrder]: target = 0.9, maxIter = 20, j.amount = 0.05, verbo Details See the Soil Series Query Functions tutorial for more information. Value A list with the following elements: • fig: lattice object (the figure) • order: 1D ordering from cluster::diana • clust: hclust object • match.rate: fraction of series matching target hydrologic ordering, after clustering + rotation Author(s) <NAME> vizGeomorphicComponent Visual Summary of Hill Landform Positions Description A unique display of landform position probability. Usage vizGeomorphicComponent( x, s = NULL, annotations = TRUE, annotation.cex = 0.75, cols = c("#D53E4F", "#FC8D59", "#FEE08B", "#E6F598", "#99D594", "#3288BD"), ... ) Arguments x data.frame as created by soilDB::fetchOSD(..., extended=TRUE), see de- tails s an optional soil series name, highlighted in the figure annotations logical, add number of record and normalized Shannon entropy values annotation.cex annotation label scaling factor cols vector of colors ... additional arguments to [iterateHydOrder]: target = 0.9, maxIter = 20, j.amount = 0.05, verbo Details See the Soil Series Query Functions tutorial for more information. Value A list with the following elements: • fig: lattice object (the figure) • order: 1D ordering from cluster::diana • clust: hclust object • match.rate: fraction of series matching target hydrologic ordering, after clustering + rotation Author(s) <NAME> vizHillslopePosition Visual Summary of Hillslope Position Description A unique display of hillslope position probability. Usage vizHillslopePosition( x, s = NULL, annotations = TRUE, annotation.cex = 0.75, cols = c("#2B83BA", "#ABDDA4", "#FFFFBF", "#FDAE61", "#D7191C"), ... ) Arguments x data.frame as created by soilDB::fetchOSD(..., extended = TRUE) s an optional soil series name, highlighted in the figure annotations logical, add number of record and normalized Shannon entropy values annotation.cex annotation label scaling factor cols vector of colors ... additional arguments to [iterateHydOrder]: target = 0.9, maxIter = 20, j.amount = 0.05, verbo Details See the Soil Series Query Functions tutorial for more information. Value A list with the following elements: • fig: lattice object (the figure) • order: 1D ordering from cluster::diana • clust: hclust object • match.rate: fraction of series matching target hydrologic ordering, after clustering + rotation Author(s) <NAME> vizMountainPosition Visual Summary of Mountain Slope Positions Description A unique display of mountain slope position probability. Usage vizMountainPosition( x, s = NULL, annotations = TRUE, annotation.cex = 0.75, cols = c("#D53E4F", "#FC8D59", "#FEE08B", "#E6F598", "#99D594", "#3288BD"), ... ) Arguments x data.frame as created by soilDB::fetchOSD(..., extended=TRUE), see de- tails s an optional soil series name, highlighted in the figure annotations logical, add number of record and normalized Shannon entropy values annotation.cex annotation label scaling factor cols vector of colors ... additional arguments to [iterateHydOrder]: target = 0.9, maxIter = 20, j.amount = 0.05, verbo Details See the Soil Series Query Functions tutorial for more information. Value A list with the following elements: • fig: lattice object (the figure) • order: 1D ordering from cluster::diana • clust: hclust object • match.rate: fraction of series matching target hydrologic ordering, after clustering + rotation Author(s) <NAME> vizSurfaceShape Visual Summary of Surface Shape Description A unique display of surface shape (typically curvature) probability, suitable for across-slope or down-slope shape. Use the title argument to make this clear. Usage vizSurfaceShape( x, title = "Surface Shape", s = NULL, annotations = TRUE, annotation.cex = 0.75, cols = c("#2B83BA", "#FFFFBF", "#D7191C", "#808080", "darkgreen"), ... ) Arguments x data.frame as created by soilDB::fetchOSD(..., extended=TRUE), see de- tails title a reasonable title for the figure s an optional soil series name, highlighted in the figure annotations logical, add number of record and normalized Shannon entropy values annotation.cex annotation label scaling factor cols vector of colors ... additional arguments to [iterateHydOrder]: target = 0.9, maxIter = 20, j.amount = 0.05, verbo Details See the Soil Series Query Functions tutorial for more information. Value A list with the following elements: • fig: lattice object (the figure) • order: 1D ordering from cluster::diana • clust: hclust object • match.rate: fraction of series matching target hydrologic ordering, after clustering + rotation Author(s) <NAME> vizTerracePosition Visual Summary of Terraced Landform Positions Description A unique display of terraced landform position probability. Usage vizTerracePosition( x, s = NULL, annotations = TRUE, annotation.cex = 0.75, cols = c("#2B83BA", "#FDAE61"), ... ) Arguments x data.frame as created by soilDB::fetchOSD(..., extended=TRUE), see de- tails s an optional soil series name, highlighted in the figure annotations logical, add number of record and normalized Shannon entropy values annotation.cex annotation label scaling factor cols vector of colors ... additional arguments to [iterateHydOrder]: target = 0.9, maxIter = 20, j.amount = 0.05, verbo Details See the Soil Series Query Functions tutorial for more information. Value A list with the following elements: • fig: lattice object (the figure) • order: 1D ordering from cluster::diana • clust: hclust object • match.rate: fraction of series matching target hydrologic ordering, after clustering + rotation Author(s) <NAME>
ltxdoc
ctan
TeX
# The file ltxdoc.dtx for use with LaTeX 2\({}_{\cal E}\).+ Footnote †: This file has version number v2.1j, dated 2023/03/28. It contains the code for ltxdoc.cls <NAME> 2023/03/28 This file is maintained by the LaTeX Project team. Bug reports can be opened (category latex) at [https://latex-project.org/bugs.html](https://latex-project.org/bugs.html). ## 1 Documentation of the LaTeX sources This class file is designed for documenting the LaTeX source files. You may however find it generally useful as a class for typesetting the documentation of files produced in 'doc' format. Each documented file in the standard distribution comes with extension dtx. The appropriate class package or initex file will be extracted from the source by the docstrip system. Each dtx file may be directly processed with LaTeX 2\({}_{\cal E}\), for example latex2e docclass.dtx would produce the documentation of the Class and package interface. Each file that is used in producing the LaTeX 2\({}_{\cal E}\) format (ie not including the standard class and packages) will be printed together in one document if you LaTeX the file sources2e.tex. This has the advantage that one can produce a full index of macro usage across all the source files. If you need to customise the typesetting of any of these files, there are two options: * You can use docstrip with the module 'driver' to extract a small LaTeX file that you may edit to use whatever class or package options you require, before inputting the source file. * You can create a file ltxdoc.cfg. This configuration file will be read whenever the ltxdoc class is used, and so can be used to customise the typesetting of all the source files, without having to edit lots of small driver files. The second option is usually more convenient. Various possibilities are discussed in the next section. ## 3 Options ``` 1<=class> 2>DeclareOption{a5paper}{\@latexerr{Optionnotsupported}% 3{}} ``` Prevent loading of a config file. 4\newif{ifltxdoc@load@cfg@ ltxdoc@load@cfg@true 5\DeclareOption{nocfg}{\ltxdoc@load@cfg@false} Support rolling back doc to version 2: 6\let\ltxdoc@docVersion\@empty % use current version by default 7\DeclareOption{doc2}{% 8\def\ltxdoc@docVersion{=v2}% 9\DeclareRobustCommand\cs[1]{\texttt{\bslash #1}}% 10} 11\DeclareOption*\% 12\PassOptionsToClass {\CurrentOption}{article}} ``` ## 4 Option Processing ``` 13\ProcessOptions ``` ## 5 Local configuration Input a local configuration file, if it exists. ``` 14\ifltxdoc@load@cfg@ 15\InputIfFileExists{ltxdoc.cfg} 16{typeout{*****************************}% 17* Localconfigfileltxdoc.cfgused^->% 18*************} 19{} 20\else 21\ttypecout{*****************************}% 22* Localconfigfileignored^->% 23*************} 24\fi ``` ## 6 Loading article and doc ``` 25\LoadClass{article} ``` By default, loadthe current doc version (\ltxdoc@docVersion is empty). If option doc2 is given version 2 is loaded (\ltxdoc@doc@version contains =v2). 26\RequirePackage{doc}[ltxdoc@docVersion] Make | be a'short verb' character, but not in the document preamble, where an active character may interfere with packages that are loaded. 27\AtBeginDocument{\MakeShortVerb{\}} ``` As 'doc' documents tend to have a lot of monospaced material, Set up some tt substitutions to occur silently. 28\DeclareFontShape{OT1}{cmtt}{bx}{n}{<->ssub*cmtt/m/n}{ 29\DeclareFontFamily{OMS}{cmtt}{\%skewchar\{font48}%'60 30\DeclareFontShape{OMS}{cmtt}{m}{n}{<->ssub*cmsy/m}{}} 31\DeclareFontShape{OMS}{cmtt}{bx}{n}{<->ssub*cmsy/b/n}{} This substitution is in the standard fd file, but not silent. 32\DeclareFontShape{OT1}{cmss}{m}{it}{<->ssub*cmss/m/sl}{} 33\CodelineNumbered 34\DisableCrossrefs Increase the text width slightly so that with the standard fonts 72 columns of code may appear in a macrocode environment. 35\setlength{\textwidth}{355pt} Increase the marginpar width slightly, for long command names. And increase the left margin by a similar amount 36\addtolength\marginparwidth{30pt} 37\addtolength\oddsidemargin{20pt} 38\addtolength\evenisidemargin{20pt} 39\setcounter{StandardModuleDepth}{1} ## 7 Useful abbreviations \cmd{foo} Prints\foo verbatim. It may be used inside moving arguments. It can _not_ be use to record commands that are defined as "\outer" nor is it possible to use it on conditionals such as \iftrue or defined by \newif. \cs{foo} already available with the doc package also prints \foo, for those who prefer that syntax. (This second form can be used to record all types of command so the above restrictions do not apply. \cmd \cs %\DeclareRobustCommand\cs[1]... % defined later 41\df\cmd#1{cs{expandafter}cmd@to@cs}string#1} % can't use with new \cs 42\def\cmd#1{\text{text{}}char'\}expandafter\cmd@to@cs\string#1} 43\def\cmd@to@cs#1#2{char'number'#2}relax \marg\marg{text} prints {\(text{})},'mandatory argument'. 44\providecommandmarg[1]{% 45\ttfamily\char'}{\}meta{#1}{ttfamilychar'}}} \oarg\oarg{text} prints {\(text{})}, 'optional argument'. 46\providecommandoarg[1]{% 47\ttfamily[]{\meta#1}{ttfamily]}} \marg\marg{te,xt} prints (\(te,xt\)), 'picture mode argument'. 48\providecommandvarg[1]{% 49\ttfamily(}{\meta#1}{ttfamily)}} ## 8 Old Comments The LaTeX2\({}_{\mathfrak{C}}\) sources contain a lot of code inherited from LaTeX2.09. The comments in this code were not designed to be typeset, and do not contain the necessary LaTeX markup. The oldcomments environment typesets these comments, automatically sensing when any control sequence appears, and implicitly adding the \verb. This procedure does not produce particularly beautiful pages, but it } 98/endgroup 99\begingroup 100\sloppy% 101\objlines% 102\gdef\oc@percent#1~Mf% 103\ifvmode% 104\def\commentline{#1}% 105\ifx\commentline\oldc% 106\textit{End of historical \LaTeX},2.09 comments.} 107\end{oldcomments}% 108\else% 109\ifx\commentline\beginac% 110\begin{macrocode}% 111\else% 112\leavevmode% 113\#1~M% 114\fi\fi\% 115\else% 116\oc@ttf\char'\#1~M% 117\fi\% 118\endgroup% ## 9 DocInclude 119\@addtoreset{CodelineNo}{part} \DocIncludeMore or less exactly the same as \include, but uses \DocInput on a dtx file, not \input on a tex file. 120\def\partname{File} 121\newcommand*{\DocInclude}[1]{% 122\relax 123\clearpage 124\docincludeaux 125\IfFileExists{#1.fdd}% 126\def\currentfile{#1.fdd}% 127\def\currentfile{#1.dtx}% 128\ifnum\@auxout=\@partaux 129\@latexerr\string\include\spacecannot be nested}\@eha 130\else 131\set@curr@file{#1}% 132\edef\curr@file{\@strip@tex@ext\@curr@file}% 133\expandafter\@docinclude\expandafter\@curr@file} 134\fi\ 135\def\@docinclude#1 {\clearpage 136\iffilesvimmediate\write\@mainaux{\string}@input{#1.aux}}\%fi 137\@tempswarture\if@partsw \@tempswafalse\@edf\@tempb{#1}@for 138\@tempa:=\@partlist\do{ifx\@tempa\@tempb\@tempswarture\fi}\%fi 139\if@tempswa\let\@auxout\@partaux \if@filesw 140\immediate\openout\@partaux "#1.aux" 141\immediate\write\@partaux{\relax}\fi 142\@filehook@set@CurrentFile 279% or by providing your own config file 280 281endinput 282\(\langle\)/cfg\(\rangle\)
TaskQueue
cocoapods
Objective-C
taskqueue === TaskQueue Documentation --- Welcome to the documentation for TaskQueue, a powerful task management library for various platforms and languages. This guide will help you understand how to effectively manage and execute tasks using TaskQueue. ### Installation To install TaskQueue, follow these simple steps: 1. Download the latest version of the library from the official website or GitHub repository. 2. Include the TaskQueue library in your project. 3. Configure TaskQueue for your specific platform or language, as detailed in the platform-specific sections below. ### Platform-specific Configuration #### iOS Configuration ``` import TaskQueue // Add necessary iOS configuration code here ``` #### Android Configuration ``` import com.example.taskqueue.TaskQueue; // Add necessary Android configuration code here ``` ### Usage #### Basic Task Creation To create a basic task using TaskQueue, follow these steps: 1. Instantiate a new task using the provided TaskQueue APIs. 2. Specify the task’s parameters and behavior. 3. Add the task to the task queue for execution. ``` // Add basic task creation code here ``` #### Advanced Task Configuration If you require more advanced task configuration options, TaskQueue provides a range of features and APIs to cater to your needs. You can: * Set task priorities * Define dependencies between tasks * Specify task execution constraints * Handle task completion and results For detailed information on the various configuration options, please refer to the TaskQueue API documentation. ### TaskQueue SDKs and Integrations TaskQueue provides SDKs and integrations for various platforms and languages, enabling seamless integration into your existing projects. Below are the supported platforms: * iOS (Swift) * Android (Java/Kotlin) * Web (JavaScript) * Python * Node.js For detailed instructions on integrating and configuring TaskQueue for each platform, refer to the respective platform-specific sections in this documentation. ### Troubleshooting If you encounter any issues while using TaskQueue, please refer to our troubleshooting guide. It provides solutions to common problems and errors you might face during task execution. ### Conclusion With TaskQueue, you now have a powerful task management library at your disposal. Whether you are building iOS, Android, web, or backend applications, TaskQueue simplifies task execution and management, improving overall efficiency and productivity.
ISEtools
cran
R
Package ‘ISEtools’ October 19, 2022 Type Package Title Ion Selective Electrodes Analysis Methods Version 3.2.0 Date 2022-10-14 Author <NAME> [aut, cre], <NAME> [ctb], <NAME> [ctb], <NAME> [ctb] Maintainer <NAME> <<EMAIL>> Description Characterisation and calibration of single or multiple Ion Selective Electrodes (ISEs); activity estimation of experimental samples. Implements methods described in: <NAME>., <NAME>., <NAME>., <NAME>. and Mc- <NAME>. (2012) <doi:10.1002/elan.201100510>, <NAME>., <NAME>. and Mc- <NAME>. (2017) <doi:10.1109/ICSENS.2017.8233898>, <NAME>., <NAME>., <NAME>., and Mc- <NAME>. (2019) <doi:10.3390/s19204544>, and <NAME>., <NAME>., Granados- <NAME>., <NAME>., and <NAME>. (2020) <doi:10.1021/acssensors.9b02133>. Depends coda Imports graphics, stats, utils Suggests R2OpenBUGS, rjags, boot, R.rsp VignetteBuilder R.rsp SystemRequirements OpenBUGS (>=3.0) or JAGS (>=4.3.1) License GPL-2 NeedsCompilation no Repository CRAN Date/Publication 2022-10-19 09:17:57 UTC R topics documented: ISEtools-packag... 2 analyseIS... 3 carbonat... 6 describeIS... 7 LeadStdAd... 10 loadISEdat... 11 plot.analyseIS... 13 plot.ISEdat... 15 plot.ISEdescriptio... 16 print.analyseIS... 16 print.ISEdat... 17 print.ISEdescriptio... 18 summary.analyseIS... 18 summary.ISEdat... 19 summary.ISEdescriptio... 20 ISEtools-package Ion Selective Electrodes Analysis Methods Description Bayesian calibration for single or multiple ISEs using R and OpenBUGS (or JAGS). Estimation of analyte activities using single ISEs or ISE arrays. Details Package: ISEtools Type: Package Depends: R (>4.1.0) SystemRequirements: OpenBUGS (>3.0) or JAGS (>=4.3.1) The primary funtions are loadISEdata (which loads calibration and experimental data from tab- delimited text files), describeISE (uses Bayesian calibration to estimate ISE parameters from cali- bration data), and analyseISE (combines calibration data with experimental data in basic or standard addition format to estimate analyte concentrations). Author(s) <NAME> [aut, cre], <NAME> [ctb], <NAME> [ctb], <NAME> [ctb] Maintainer: <NAME> <<EMAIL>> References <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>. (2012). Bayesian Methods for Ion Selective Electrodes. Electroanalysis, 24, 316-324. <doi:10.1002/elan.201100510> <NAME>., <NAME>. and <NAME>. (2017). Characterising uncertainty in in- strumental limits of detection when sensor response is non-linear. 2017 IEEE SENSORS, Glasgow, United Kingdom, pp. 1-3. <doi:10.1109/ICSENS.2017.8233898> <NAME>., <NAME>., <NAME>., and <NAME>. (2019). Semi-automated data analysis for ion-selective electrodes and arrays using the R package ISEtools. Sensors 19(20), 4544. <doi:10.3390/s19204544> <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. (2020). Es- tablishing meaningful Limits of Detection for ion-selective electrodes and other nonlinear sensors ACS Sensors, 5, 250-257. <doi:10.1021/acssensors.9b02133> Examples data(LeadStdAdd) print(LeadStdAdd) summary(LeadStdAdd) plot(LeadStdAdd) example1 = describeISE(LeadStdAdd, Z =2, temperature=21) print(example1) summary(example1) plot(example1) example2 = analyseISE(LeadStdAdd, Z =2, temperature=21) print(example2) summary(example2) plot(example2, ylim = c(-7, -3), xlab = "ID (Sample)", ylab = expression(paste(log[10], " ", Pb^{paste("2","+",sep="")} ))) analyseISE Ion selective electrode characterisation and estimation of sample con- centrations Description Use Bayesian calibration to estimate parameters for y = a + b log(x + c) + error, where error follows a normal distribution with mean 0 and standard deviation sigma. The limit of detection (false positive/negative method or S/N=3 method) is also estimated. These values are then used to the estimate sample concentrations. Usage analyseISE(data, model.path=NA, model.name=NA, Z=NA, temperature = 21, burnin=25000, iters = 50000, chains=4, thin = 1, a.init= NA, b.init=NA, cstar.init=NA, logc.limits = c(-8.9, -1.9), sigma.upper = 5, diagnostic.print=FALSE, offset = 1, alpha = 0.05, beta = 0.05, SN = NA, program="OpenBUGS") Arguments data Calibration and experimental data (of class ’ISEdata’; see loadISEdata) model.path The directory where the BUGS model is located (defaults to ’models’ sub- directory under the location of ISEtools package, e.g. ’.../ISEtools/models’) model.name The name of the BUGS model (e.g. ’Single_ISE_model.txt’) (defaults are lo- cated in ISEtools package) Z Ionic valence (e.g. for lead, Z = 2) temperature temperature in degrees C burnin Initial number of Monte Carlo simulations to discard. iters Total number of iterations. chains Number of parallel MCMC chains thin Thinning rate, equal to 1/Proportion of simulations saved (e.g. thin = 10 records every tenth iteration). a.init Initial value for parameter a b.init Initial value for parameter b cstar.init Initial value for parameter cstar (c = cstar^10) logc.limits Upper and lower limits for log c initial values sigma.upper Upper limit for initial value of sigma diagnostic.print logical flag indicating whether a diagnostic printout is desired (default is F) offset The initial value for the slope is based on the last data point as sorted by concen- tration (i.e. the Nth point) and the (N - offset) data point. The default is offset = 1, corresponding to the last and second to last data points. alpha False positive rate used for detection threshold (not output) to calculate LOD(alpha, beta) only returned if SN = NA beta False negative rate used to calculate LOD(alpha, beta) only returned if SN = NA SN Desired signal-to-noise ratio for LOD(S/N) calculations (default is to calculate the S/N equivalent based on alpha, beta) program Choice of "OpenBUGS" (default and recommended for Windows or Linux) or "jags" (for macOS, see manual for warnings). Value analyseISE returns a list of class ’analyseISE’. Individual components include: SampleID Sample identification number log10x.exp Estimated concentration (log scale, mol/l) ahat Estimated value for a (from the median of the posterior distribution) bhat Estimated value for b (from the median of the posterior distribution) chat Estimated value for c (from the median of the posterior distribution) cstarhat Estimated value for cstar (from the median of the posterior distribution) sigmahat Estimated value for cstar (from the median of the posterior distribution) LOD.info List describing LOD method (alpha, beta or S/N) and corresponding values (al- pha, beta, SN) LOD.hat Estimated value for the limit of detection (from the median of the posterior dis- tribution) <parametername>.lcl Lower limit for the above parameters (e.g. ahat.lcl, bhat.lcl, ...) (from the 2.5th percentile of the posterior distribution) <parametername>.ucl Upper limit for the above parameters (from the 97.5th percentile of the posterior distribution) LOD.Q1 25th percentile estimated value of the limit of detection LOD.Q3 75th percentile estimated value of the limit of detection Author(s) <NAME>, <<EMAIL>> References <NAME>., <NAME>., <NAME>., <NAME>. and McGraw, C.M. (2012). Bayesian Methods for Ion Selective Electrodes. Electroanalysis, 24, 316-324. <doi:10.1002/elan.201100510> <NAME>., <NAME>. and <NAME>. (2017). Characterising uncertainty in in- strumental limits of detection when sensor response is non-linear. 2017 IEEE SENSORS, Glasgow, United Kingdom, pp. 1-3. <doi:10.1109/ICSENS.2017.8233898> <NAME>., <NAME>., <NAME>., and <NAME>. (2019). Semi-automated data analysis for ion-selective electrodes and arrays using the R package ISEtools. Sensors 19(20), 4544. <doi: 10.3390/s19204544> <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. (2020). Es- tablishing meaningful Limits of Detection for ion-selective electrodes and other nonlinear sensors ACS Sensors, 5, 250-257. <doi:10.1021/acssensors.9b02133> Examples # Fast-running example with only 100 MCMC iterations for testing: data(LeadStdAdd) example2test = analyseISE(LeadStdAdd, Z = 2, temperature = 21, burnin=100, iters=200, chains=1, a.init=c(176, 146, -112), b.init=c(29, 30, 31), cstar.init=c(0.26, 0.27, 0.22), program="jags") print(example2test) summary(example2test) plot(example2test, ylim = c(-7, -3), xlab = "ID (Sample)", ylab = expression(paste(log[10], " ", Pb^{paste("2","+",sep="")} ))) # Full example with 100,000 iterations (25,000 by 4 chains): data(LeadStdAdd) example2 = analyseISE(LeadStdAdd, Z = 2, temperature = 21) print(example2) summary(example2) plot(example2, ylim = c(-7, -3), xlab = "ID (Sample)", ylab = expression(paste(log[10], " ", Pb^{paste("2","+",sep="")} ))) carbonate ISE measurements of carbonate in seawater Description A data set containing emf responses for 8 ISEs measuring carbonate in seawater Usage data(carbonate) Format Load example carbonate data as an object of type ISEdata (see function loadISEdata) References <NAME>., <NAME>. and <NAME>. (2017). Characterising uncertainty in in- strumental limits of detection when sensor response is non-linear. 2017 IEEE SENSORS, Glasgow, United Kingdom, pp. 1-3. <doi:10.1109/ICSENS.2017.8233898> Examples data(carbonate) print(carbonate) plot(carbonate) describeISE Ion selective electrode characterisation Description Use Bayesian calibration to estimate parameters for y = a + b log(x + c) + error, where error follows a nomral distribution with mean 0 and standard deviation sigma. The limit of detection is also estimated. Usage describeISE(data, model.path=NA, model.name = NA, Z=NA, temperature = 21, burnin=25000, iters = 50000, chains=4, thin = 1, a.init= NA, b.init=NA, cstar.init=NA, logc.limits = c(-8.9, -1.9), sigma.upper = 5, diagnostic.print=FALSE, offset = 1, alpha = 0.05, beta = 0.05, SN = NA, keep.coda=TRUE, coda.n=1000, program="OpenBUGS") Arguments data Calibration data (of class ’ISEdata’; see loadISEdata) model.path The directory where the BUGS model is located (defaults to ’models’ sub- directory under the location of ISEtools package, e.g. ’.../ISEtools/models’) model.name The name of the BUGS model (e.g. ’Single_ISE_model.txt’) (defaults are lo- cated in ISEtools package) Z Ionic valence (e.g. for lead, Z = 2) temperature temperature in degrees C burnin Initial number of Monte Carlo simulations to discard. iters Total number of iterations. chains Number of parallel MCMC chains thin Thinning rate, equal to 1/Proportion of simulations saved (e.g. thin = 10 records every tenth iteration). a.init Initial value for parameter a b.init Initial value for parameter b cstar.init Initial value for parameter cstar (c = cstar^10) logc.limits Upper and lower limits for log c initial values sigma.upper Upper limit for initial value of sigma diagnostic.print logical flag indicating whether a diagnostic printout is desired (default is FALSE) offset The initial value for the slope is based on the last data point as sorted by concen- tration (i.e. the Nth point) and the (N - offset) data point. The default is offset = 1, corresponding to the last and second to last data points. alpha False positive rate used for detection threshold (not output) to calculate LOD(alpha, beta) only returned if SN = NA beta False negative rate used to calculate LOD(alpha, beta) only returned if SN = NA SN Desired signal-to-noise ratio for LOD(S/N) calculations (default is to calculate the S/N equivalent based on alpha, beta) keep.coda Logical flag indicating whether the MCMC simulations should be returned (keep.coda = TRUE) or not (keep.coda = FALSE) coda.n Indicates how many simulations to return (sampled with replacement). If coda.n >= the total, all are returned. program Choice of "OpenBUGS" (default and recommended for Windows or Linux) or "jags" (for macOS, see manual for warnings). Value describeISE returns a list of class ’ISEdescription’. Individual components are: ahat Estimated value for a (from the median of the posterior distribution) bhat Estimated value for b (from the median of the posterior distribution) chat Estimated value for c (from the median of the posterior distribution) cstarhat Estimated value for cstar (c to the 0.1 power) (from the median of the posterior distribution) sigmahat Estimated value for cstar (from the median of the posterior distribution) LOD.info List describing LOD method (alpha, beta or S/N) and corresponding values (al- pha, beta, SN) LOD.hat Estimated value for the limit of detection (from the median of the posterior dis- tribution) <parametername>.lcl Lower limit for the above parameters (e.g. ahat.lcl, bhat.lcl, ...) (from the 2.5th percentile of the posterior distribution) <parametername>.ucl Upper limit for the above parameters (from the 95.5th percentile of the posterior distribution) LOD.Q1 25th percentile estimated value of the limit of detection LOD.Q3 75th percentile estimated value of the limit of detection If keep.coda = TRUE, then these additional items are returned: ahat.coda Random sample (without replacement) of length coda.n from the Markov Chain Monte Carlo simulations for a bhat.coda Random sample (without replacement) of length coda.n from the Markov Chain Monte Carlo simulations for b chat.coda Random sample (without replacement) of length coda.n from the Markov Chain Monte Carlo simulations for c sigmahat.coda Random sample (without replacement) of length coda.n from the Markov Chain Monte Carlo simulations for sigma cstarhat.coda Random sample (without replacement) of length coda.n from the Markov Chain Monte Carlo simulations for cstar LOD.coda Random sample (without replacement) of length coda.n from the Markov Chain Monte Carlo simulations for LOD Author(s) <NAME>, <<EMAIL>> References <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>. (2012). Bayesian Methods for Ion Selective Electrodes. Electroanalysis, 24, 316-324. <NAME>., <NAME>. and <NAME>. (2017). Characterising uncertainty in in- strumental limits of detection when sensor response is non-linear. 2017 IEEE SENSORS, Glasgow, United Kingdom, pp. 1-3. <doi:10.1109/ICSENS.2017.8233898> <NAME>., <NAME>., <NAME>., and <NAME>. (2019). Semi-automated data analysis for ion-selective electrodes and arrays using the R package ISEtools. Sensors 19(20), 4544. <doi: 10.3390/s19204544> <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. (2020). Es- tablishing meaningful Limits of Detection for ion-selective electrodes and other nonlinear sensors ACS Sensors, 5, 250-257. <doi:10.1021/acssensors.9b02133> Examples # Fast-running example with only 100 MCMC iterations for testing: data(carbonate) example3test = describeISE(carbonate, Z = -2, SN = 3.6, burnin=100, iters=200, chains=1, a.init= c(-50,180,140,65,100,170,100,130), b.init=rep(-20,8), cstar.init=rep(0.2, 8), program="jags") print(example3test) summary(example3test) plot(example3test) # Full example with 100,000 iterations (25,000 by 4 chains): data(carbonate) example3 = describeISE(carbonate, Z = -2, SN = 3.6) print(example3) summary(example3) plot(example3) LeadStdAdd ISE measurements of lead in soil Description A data set containing emf responses for 3 ISEs measuring lead in soil at Silvermines, Ireland. Calibration data and experimental data for 17 samples (in standard addition format) are included. Usage data(LeadStdAdd) Format Load example lead data as an object of type ISEdata (see function loadISEdata) References <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>. (2012). Bayesian Methods for Ion Selective Electrodes. Electroanalysis, 24, 316-324. <doi:10.1002/elan.201100510> <NAME>., <NAME>., <NAME>., and <NAME>. (2019). Semi-automated data analysis for ion-selective electrodes and arrays using the R package ISEtools. Sensors 19(20), 4544. <doi: 10.3390/s19204544> <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. (2020). Es- tablishing meaningful Limits of Detection for ion-selective electrodes and other nonlinear sensors. ACS Sensors, 5, 250-257. <doi:10.1021/acssensors.9b02133> Examples data(LeadStdAdd) print(LeadStdAdd) summary(LeadStdAdd) plot(LeadStdAdd) ## Not run: # Additional usage of this dataset with describeISE and analyseISE: example1 = describeISE(LeadStdAdd, Z = 2, temperature = 21) print(example1) summary(example1) plot(example1) example2 = analyseISE(LeadStdAdd, Z = 2, temperature = 21) print(example2) summary(example2) plot(example2, ylim = c(-7, -3), xlab = "ID (Sample)", ylab = expression(paste(log[10], " ", Pb^{paste("2","+",sep="")} ))) ## End(Not run) loadISEdata Load ISE calibration and experimental data. Description Loads tab-delimited calibration and (if it exists) experimental sample data. Usage loadISEdata(filename.calibration, filename.experimental = NA) Arguments filename.calibration The name and location of the tab-delimited calibration file It should have the following structure: First line (header row): ISEID log10x emf Remaining lines (data): ISEID is an identifier for the ISE. The ISEID variables should be integers, with the lowest value equal to 1, and no gaps. That is, if there are four ISEs, they must be labeled 1, 2, 3, and 4. log10x is the log10 con- centration (mol/l) of the calibration samples. The emf readings (in mV) follow. filename.experimental The experimental file (if there is one, otherwise keep the default filename.experimental=NA) should have one of the following structures: basic model: The header row will include ISEID, SampleID, and emf. ISEID is defined the same way as in the calibration file. SampleID is an integer indicating which sample is being measured, and must follow the same numbering rules as ISEID. Finally, emf is the mV reading of the experimental samples for each ISE. or standard addition: When using the standard addition model, the experimental file will contain ISEID and SampleID as before. Two emf values are recorded: emf1 is the mV reading of the sample, and emf2 is the mV reading of the sample plus the addition. Additionally, V.s is the volume of the sample, V.add is the vol- ume of the addition, and conc.add is the concentration (mol/l) of the addition. The units of V.s and V.add do not matter as long as they are the same. Details Internally calls ’ISEdata.calibration’ if there is no experimental data. Value loadISEdata returns the following values in a list of class ISEdata: Calibration variables: N Total number of calibration measurements (e.g. for 5 calibration points mea- sured with 3 ISEs, N = 15) R Number of ISEs ISEID Identifier for the ISE log10x log concentration (mol/l) of calibration data emf emf (mV) for calibration data Experimental variables: M Number of experimental samples M.obs Total number of experimental measurements. E.g. for 4 samples each measured by 3 ISEs, M.obs = 12. Only returned if R > 1 ISEID.exp Identifier for the ISE for the experimental data (returned if R >1) x.exp Identifier for the experimental (returned if R > 1) Basic format only: emf.exp emf (mV) for experimental data Standard addition format only: delta.emf difference between emf1 and emf2 (mV) for experimental data V.s Sample volume (any units allowed but must be consistent) V.add Volume added to the sample conc.add Concentration added. Summary variables of calibration and experimental data: calibration.only Indicates whether there was only calibration data (TRUE) or calibration and experimental data (FALSE) stdadd Indicates whether standard addition was used. Returns NA (calibration data only), FALSE (basic experimental data), or TRUE (standard addition experi- mental data) data.calib The loaded calibration data frame data.exp The loaded experimental data frame Author(s) <NAME> <<EMAIL>> Examples ### # Loading the example tab-delimited text files for the lead data ### # 1. Find pathnames for the lead example txt files: path.calib = paste(path.package('ISEtools'), "/extdata", "/Lead_calibration.txt", sep="") path.basic = paste(path.package('ISEtools'), "/extdata", "/Lead_experimentalBasic.txt", sep="") path.sa = paste(path.package('ISEtools'), "/extdata", "/Lead_experimentalSA.txt", sep="") # Load the calibration data lead.example1 = loadISEdata(filename.calibration = path.calib) print(lead.example1) # ... and with experimental data, Basic format lead.example2 = loadISEdata(filename.calibration = path.calib, filename.experimental = path.basic) print(lead.example2) # ... and with experimental data, Standard Addition format lead.example3 = loadISEdata(filename.calibration = path.calib, filename.experimental = path.sa) print(lead.example3) plot.analyseISE Plot function for ion selective electrode characterisation and estima- tion of sample concentrations Description Plots sample concentration estimates derived from Bayesian calibration. E.g. analyseISE uses Bayesian calibration to estimate parameters for y = a + b log(x + c) + error, where error follows a normal distribution with mean 0 and standard deviation sigma. These valus are combined with experimental data to estimate sample concentrations. Usage ## S3 method for class 'analyseISE' plot(x, xlab = "Sample ID", ylab = expression(paste(log[10], " { ", italic(x), " }")), xlim = NA, ylim = c(-15, 0), x.ticks = NA, y.ticks = NA, x.ticks.label = TRUE, y.ticks.label = TRUE, y.las = 2, col = 1, x.shift = 0, xaxs = "r", yaxs = "r", add.box = TRUE, ...) Arguments x Calibration and experimental sample results (of class ’analyseISE’; see analy- seISE) xlab Label for the x-axis ylab Label for the y-axis xlim Limits for the x-axis. Automatically calculated if xlim = NA. ylim Limits for the y-axis. x.ticks Location of tickmarks for the x-axis. Automatically calculated if x.ticks = NA. y.ticks Location of tickmarks for the y-axis. Automatically calculated if y.ticks = NA. x.ticks.label Labels associated with x-axis tickmarks for the x-axis. Automatically calculated labels (TRUE), no labels (FALSE), or a column of text specifying custom labels (e.g. x.ticks.label = c("A", "B", "C") or similar, of the same length as x.ticks). y.ticks.label Labels associated with y-axis tickmarks for the y-axis. See x.ticks.label for details. y.las Indicates whether y-axis labels be perpendicular to the y-axis (2) or parallel to it (0). col Colour for the field of the plot. x.shift Shifts the plots to the left (- values) or right (+ values); useful for overlaying figures. xaxs The style of x-axis interval. See par for further details, but "r" adds 4 percent padding, "i" has no padding. yaxs The style of y-axis interval. See xaxs above. add.box Indicates whether a box should be drawn around the plot (TRUE) or not (FALSE). ... Other arguments to be passed through to plotting functions. Value No return value, creates plot. Author(s) <NAME>, <<EMAIL>> See Also analyseISE plot.ISEdata Basic plot of ion selective electrode calibration data Description Plots raw ISE calibration data; data should follow a hockey stick pattern coinciding with the equa- tion y = a + b log(x + c) + error, where error follows a normal distribution with mean 0 and standard deviation sigma. Usage ## S3 method for class 'ISEdata' plot(x, xlab = expression(paste(log[10], " { ", italic(x), " }")), ylab = "emf", pch = 20, ...) Arguments x ISE calibration data xlab Label for the x-axis ylab Label for the y-axis pch Plotting symbol for data ... Other arguments to be passed through to plotting functions. Value No return value, creates plot. Author(s) <NAME>, <<EMAIL>> See Also loadISEdata Examples data(LeadStdAdd) plot(LeadStdAdd) plot.ISEdescription Plot ISE parameter values Description Plots histograms of ISE parameter values a, b, c, sigma, and LOD (alpha, beta or S/N) for the equation y = a + b log(x + c) + error, where error follows a normal distribution with mean 0 and standard deviation sigma. Usage ## S3 method for class 'ISEdescription' plot(x, breaks = 20, ...) Arguments x ISE description (e.g. object of class ISEdescription) breaks Approximate number of bins for histograms, defaults to 20 ... Other arguments to be passed through to plotting (histogram) functions Value No return value, creates plot. Author(s) <NAME>, <<EMAIL>> See Also describeISE print.analyseISE Prints tables of ISE parameters and estimated sample concentrations. Description Prints tables of ISE parameters and estimated sample concentrations. Usage ## S3 method for class 'analyseISE' print(x, ...) Arguments x ISE analysis results (e.g. object of class analyseISE) ... Other objects passed through. Value No return value, prints results from analyseISE. Author(s) <NAME>, <<EMAIL>> See Also analyseISE print.ISEdata Prints ISE data Description Prints tables of calibration data and experimental data (if present). Usage ## S3 method for class 'ISEdata' print(x, ...) Arguments x ISE data (e.g. object of class ISEdata) ... Other objects passed through. Value No return value, prints ISE data. Author(s) <NAME>, <<EMAIL>> See Also loadISEdata Examples data(LeadStdAdd) print(LeadStdAdd) print.ISEdescription Prints tables of ISE parameters. Description Prints tables of ISE parameters for one or multiple ISEs. Usage ## S3 method for class 'ISEdescription' print(x, ...) Arguments x ISE analysis results (e.g. object of class analyseISE) ... Other objects passed through. Value No return value, prints results from describeISE. Author(s) <NAME>, <<EMAIL>> See Also describeISE summary.analyseISE Summary of estimates for ISE parameter values and experimental sample concentrations. Description summary.analyseISE takes an object of class analyseISE and produces summary tables. Usage ## S3 method for class 'analyseISE' summary(object, ...) Arguments object Data set of class ISEdata ... Other objects passed through. Value tables: Two tables (table1 and table2) are returned as a list. table1 A table of ISE parameter values (see summary.describeISE for details) table2 A table of estimated analyte concentrations for experimental samples Author(s) <NAME>, <<EMAIL>> See Also analyseISE summary.ISEdescription summary.ISEdata Summarises ISE data Description summary.ISE takes an object of class ISEdata (e.g. see loadISEdata) and produces metadata for it. Usage ## S3 method for class 'ISEdata' summary(object, ...) Arguments object Data set of class ISEdata ... Other objects passed through. Value metadata: Metadata for the ISEs, a list with N, R, calibration.only, M, and stdadd N Total number of calibration observations R Number of ISEs calibration.only Indicates calibration only data (T), or calibration and experimental data (F) M Number of experimental samples (NA if no experimental data were loaded) stdadd Indicates whether standard addition used for experimental samples (T) or the basic model was used (F), or no experimental data (NA) Author(s) <NAME>, <<EMAIL>> See Also loadISEdata Examples data(LeadStdAdd) summary(LeadStdAdd) summary.ISEdescription Summarise ISE parameters Description summary.ISEdescription takes an object of class ISEddescription and prints a table of parameter values for y = a + b log(x + c) + error, with the erros following a Normal distribution with mean 0 and standard deviation sigma. Also calculates LOD using the conditional analytic method (alpha, beta, or S/N). Usage ## S3 method for class 'ISEdescription' summary(object, ...) Arguments object object of class ISEdescription ... Other objects passed through. Value table1: A matrix with parameter values for each ISE Author(s) <NAME>, <<EMAIL>> See Also describeISE
ueberauth_slack
hex
Erlang
Ueberauth.Strategy.Slack === Implements an ÜeberauthSlack strategy for authentication with slack.com. When configuring the strategy in the Üeberauth providers, you can specify some defaults. * `uid_field` - The field to use as the UID field. This can be any populated field in the info struct. Default `:email` * `default_scope` - The scope to request by default from slack (permissions). Default "users:read" * `oauth2_module` - The OAuth2 module to use. Default Ueberauth.Strategy.Slack.OAuth ``` config :ueberauth, Ueberauth, providers: [ slack: { Ueberauth.Strategy.Slack, [uid_field: :nickname, default_scope: "users:read,users:write"] } ] ``` [Link to this section](#summary) Summary === [Functions](#functions) --- [auth(conn)](#auth/1) [default_options()](#default_options/0) [Link to this section](#functions) Functions === Überauth Slack === > Slack OAuth2 strategy for Überauth. [installation](#installation) Installation --- 1. Setup your application at [Slack API](https://api.slack.com). 2. Add `:ueberauth_slack` to your list of dependencies in `mix.exs`: ``` def deps do [{:ueberauth_slack, "~> 0.7"}] end ``` 3. Add the strategy to your applications: ``` def application do [applications: [:ueberauth_slack]] end ``` 4. Add Slack to your Überauth configuration: ``` config :ueberauth, Ueberauth, providers: [ slack: {Ueberauth.Strategy.Slack, []} ] ``` You can optionally restrict authentication by providing your team ID. [Find your Slack team ID here](https://api.slack.com/methods/auth.test/test). Note that this is NOT your team's Slack domain name! ``` config :ueberauth, Ueberauth, providers: [ slack: {Ueberauth.Strategy.Slack, [team: "0ABCDEF"]} ] ``` 5. Update your provider configuration: ``` config :ueberauth, Ueberauth.Strategy.Slack.OAuth, client_id: System.get_env("SLACK_CLIENT_ID"), client_secret: System.get_env("SLACK_CLIENT_SECRET") ``` 6. Include the Überauth plug in your controller: ``` defmodule MyApp.AuthController do use MyApp.Web, :controller plug Ueberauth ... end ``` 7. Create the request and callback routes if you haven't already: ``` scope "/auth", MyApp do pipe_through :browser get "/:provider", AuthController, :request get "/:provider/callback", AuthController, :callback end ``` 8. Your controller needs to implement callbacks to deal with [`Ueberauth.Auth`](https://hexdocs.pm/ueberauth/0.7.0/Ueberauth.Auth.html) and [`Ueberauth.Failure`](https://hexdocs.pm/ueberauth/0.7.0/Ueberauth.Failure.html) responses. For an example implementation see the [Überauth Example](https://github.com/ueberauth/ueberauth_example) application. [calling](#calling) Calling --- Depending on the configured url you can initiate the request through: ``` /auth/slack ``` Or with options: ``` /auth/slack?scope=users:read ``` By default the requested scope is "users:read". Scope can be configured either explicitly as a `scope` query value on the request path or in your configuration: ``` config :ueberauth, Ueberauth, providers: [ slack: {Ueberauth.Strategy.Slack, [default_scope: "users:read,users:write"]} ] ``` [license](#license) License --- Please see [LICENSE](https://github.com/ueberauth/ueberauth_slack/blob/master/LICENSE) for licensing details. [API Reference](api-reference.html) [Next Page → Contributing to Ueberauth Slack](contributing.html)
github.com/amalgam8/amalgam8
go
Go
README [¶](#section-readme) --- ### Amalgam8 - Microservice Routing Fabric [![GoReportCard Widget](https://goreportcard.com/badge/github.com/amalgam8/amalgam8)](https://goreportcard.com/report/github.com/amalgam8/amalgam8) [![Travis Widget](https://travis-ci.org/amalgam8/amalgam8.svg?branch=master)](https://travis-ci.org/amalgam8/amalgam8) #### TL;DR 1. A quick intro video to Amalgam8 [![Introduction to Amalgam8 Microservice Routing Fabric](http://img.youtube.com/vi/gvjhrxwX7S8/0.jpg)](http://www.youtube.com/watch?feature=player_embedded&v=gvjhrxwX7S8) 1. [Try the demo applications](https://amalgam8.io/docs/demo/) with a container runtime of your choice. 2. [Integrate the sidecar](https://www.amalgam8.io/docs/sidecar/) into your existing application to start using Amalgam8. --- #### Content and version-based routing - 101 In any realistic production deployment, there are typically multiple versions of microservices running at the same time, as you might be testing out a new version, troubleshooting an old version, or simply keeping the old version around just in case. *Content-based routing* allows you to route requests between microservices based on the content of the request, such as the URL, HTTP headers, etc. For example, ``` from microservice A, if request has "X-User-Id: QA", route to instance of (B:v2) else route to instance of (B:v1) ``` *Version-based routing* allows you to control how different versions of microservices can talk to each other. For example, ``` from microservice A:v2 route all requests to B:v2 from microservice A:v1 route 10% of requests to B:v2 and 90% to B:v1 ``` *A simple way to accomplish these functions is to control how microservices can talk to each other.* ### What is Amalgam8 ? Amalgam8 is a platform for building polyglot microservice applications that enables you to route requests between microservices in a *content-based* and *version-based* manner, independent of the underlying container orchestration layer ([Docker Swarm](https://www.docker.com/products/docker-swarm), [Kubernetes](https://kubernetes.io), [Marathon](https://mesosphere.github.io/marathon/)) or the cloud platform (Amazon AWS, IBM Bluemix, Google Cloud Platform, Microsoft Azure, etc.) Amalgam8 uses the sidecar model or the ambassador pattern for building microservices applications. The sidecar runs as in independent process and takes care of service registration, discovery and request routing to various microservices. The sidecar model simplifies development of polyglot applications. Through the Amalgam8 Control Plane, you can dynamically program the sidecars in each microservice and control how requests are routed between microservices. The control plane provides REST APIs that serve as the basis for building tools for various DevOps tasks such as A/B testing, internal releases and dark launches, canary rollouts, red/black deployments, resilience testing, etc. #### Amalgam8 - Components * The Amalgam8 Control Plane consists of two multi-tenant components: + [Service Registry](https://www.amalgam8.io/docs/control-plane-registry.html) + [Route Controller](https://www.amalgam8.io/docs/control-plane-controller.html)The registry and the controller store their state in a Redis backend. * In the data plane, the [Amalgam8 sidecar](https://amalgam8.io/docs/sidecar/) runs alongside each microservice instance. The sidecar is an [Envoy](https://lyft.github.io/envoy/) reverse proxy. In addition to proxying requests to other microservices, the sidecar is responsible for service registration, heartbeat, service discovery, load balancing, intelligent request routing, and fault injection. Microservices communicate with the sidecar via the loopback socket at http://localhost:6379 . For e.g., to make a REST API call over HTTP to serviceB, the application would use the following URL: http://localhost:6379/serviceB/apiEndpoint . The sidecar in-turn forwards the API call to an instance of service B. #### Documentation Detailed documentation on Amalgam8 can be found at <https://amalgam8.io/docs>. #### Demos To get started with Amalgam8, we suggest exploring some of the [demo applications](https://amalgam8.io/docs/demo). The walkthroughs demonstrate some of Amalgam8's key features. Detailed instructions are available for different container runtimes and cloud platforms. #### Getting Help If you have any questions or feedback, you can reach us via our public Slack channel (#amalgam8). To join this channel, please use the following self invite URL: <https://amalgam8-slack-invite.mybluemix.net--- ### Development Process To build from source, clone this repository, and follow the instructions in the [developer guide](https://github.com/amalgam8/amalgam8/blob/v1.1.0/devel). #### Travis CI Continuous builds are run on Travis CI. These builds use the `.travis.yml` configuration. #### Release Workflow This section includes instructions for working with releases, and is intended for the project's maintainers (requires write permissions) ##### Creating a release 1. Edit the `CHANGELOG.md` file, describing the changes included in this release. 2. Set a version for the release, by incrementing the current version according to the [semantic versioning](https://semver.org/) guidelines. For example, ``` export VERSION=v0.1.0 ``` 3. Create an [annotated tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging#Annotated-Tags) in your local copy of the repository: ``` git tag -a -m "Release $VERSION" $VERSION [commit id] ``` The `[commit id]` argument is optional. If not specified, HEAD is used. 4. Push the tag back to the Amalgam8 upstream repository on GitHub: ``` git push origin $VERSION ``` This command automatically creates a release object on GitHub, corresponding to the pushed tag. The release contains downloadable packages of the source code (both as `.zip` and `.tag.gz` archives). 1. Edit the [GitHub release object](https://github.com/amalgam8/amalgam8/releases), and add a title and description (according to `CHANGELOG.md`). ### License Copyright 2016 IBM Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### Contributing Contributions and feedback are welcome! Proposals and pull requests will be considered. Please see the [CONTRIBUTING.md](https://github.com/amalgam8/amalgam8/blob/v1.1.0/CONTRIBUTING.md) file for more information. None
npcure
cran
R
Package ‘npcure’ October 13, 2022 Version 0.1-5 Date 2020-02-28 Title Nonparametric Estimation in Mixture Cure Models Author <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] Maintainer <NAME> <<EMAIL>> Depends R (>= 3.5.0) Suggests KMsurv Description Performs nonparametric estimation in mixture cure models, and signifi- cance tests for the cure probability. For details, see López- Cheda et al. (2017a) <doi:10.1016/j.csda.2016.08.002> and López- Cheda et al. (2017b) <doi:10.1007/s11749-016-0515-1>. License GPL (>= 2) Imports permute, stats, utils, zoo NeedsCompilation yes Encoding UTF-8 Repository CRAN Date/Publication 2020-02-29 10:10:02 UTC R topics documented: npcure-packag... 2 bera... 3 beranc... 6 controlpar... 9 hpilo... 11 latenc... 12 latencyhboo... 16 print.npcur... 19 probcur... 20 probcurehboo... 23 summary.npcur... 26 testco... 28 testm... 30 npcure-package Nonparametric Estimation in Mixture Cure Models Description Performs nonparametric estimation in mixture cure models, and significance tests for the cure prob- ability. For details, see López-Cheda et al. (2017a) <doi:10.1016/j.csda.2016.08.002> and López- Cheda et al. (2017b) <doi:10.1007/s11749-016-0515-1>. Details Index of help topics: beran Compute Beran's Estimator of the Conditional Survival berancv Compute the Cross-Validation Bandwidth for Beran's Estimator of the Conditional Survival controlpars Control Values for the Bootstrap or Cross-validation hpilot Compute the Pilot Bandwidth for the Nonparametric Estimators of Cure Probability and Latency latency Compute Nonparametric Estimator of the Conditional Latency latencyhboot Compute the Bootstrap Bandwidth for the Nonparametric Estimator of the Latency npcure-package Nonparametric Estimation in Mixture Cure Models print.npcure Print Method for Objects of Class 'npcure' probcure Compute Nonparametric Estimator of the Conditional Probability of Cure probcurehboot Compute the Bootstrap Bandwidth for the Nonparametric Estimator of the Cure Probability summary.npcure Summary Method for Objects of Class 'npcure' testcov Covariate Significance Test of the Cure Probability testmz Test of Maller-Zhou Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] References <NAME>., <NAME>., <NAME>., <NAME>. (2017). Nonparametric incidence estimation and bootstrap bandwidth selection in mixture cure models. Computational Statistics & Data Analysis 105: 144–165. https://doi.org/10.1016/j.csda.2016.08.002. <NAME>., <NAME>., <NAME>. (2017). Nonparametric latency estimation for mixture cure models. Test, 26: 353–376. https://doi.org/10.1007/s11749-016-0515-1. beran Compute Beran’s Estimator of the Conditional Survival Description This function computes the Beran nonparametric estimator of the conditional survival function. Usage beran(x, t, d, dataset, x0, h, local = TRUE, testimate = NULL, conflevel = 0L, cvbootpars = if (conflevel == 0 && !missing(h)) NULL else controlpars()) Arguments x If dataset is missing, a numeric object giving the covariate values. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the covariate in the data frame. t If dataset is missing, a numeric object giving the observed times. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the observed times in the data frame. d If dataset is missing, an integer object giving the values of the uncensoring indicator. Censored observations must be coded as 0, uncensored ones as 1. If dataset is a data frame, it is interpreted as the name of the variable correspond- ing to the uncensoring indicator. dataset An optional data frame in which the variables named in x, t and d are inter- preted. If it is missing, x, t and d must be objects of the workspace. x0 A numeric vector of covariate values where the survival estimates will be com- puted. h A numeric vector of bandwidths. If it is missing the default is to use the cross- validation bandwidth computed by the berancv function. local A logical value, TRUE by default, specifying whether local or global bandwidths are used. testimate A numeric vector specifying the times at which the survival is estimated. By default it is NULL, and then the survival is estimated at the times given by t. conflevel A value controlling whether bootstrap confidence intervals (CI) of the survival are to be computed. With the default value, 0L, the CIs are not computed. If a numeric value between 0 and 1 is passed, it specifies the confidence level of the CIs. cvbootpars A list of parameters controlling the bootstrap when computing the CIs of the survival: B, the number of bootstrap resamples, and nnfrac, the fraction of the sample size that determines the order of the nearest neighbor used for choosing a pilot bandwidth. If h is missing the list of parameters is extended to be the same used for computing the cross-validation bandwidth (see the help of berancv for details). The default is the value returned by the controlpars function called without arguments. In case the CIs are not computed and h is not missing the default is NULL. Details This function computes the kernel type product-limit estimator of the conditional survival function S(t|x) = P (Y > t|X = x) under censoring, using the Nadaraya-Watson weights. The kernel used is the Epanechnikov. If the smoothing parameter h is not provided, then the cross-validation band- width selector in Geerdens et al. (2018) is used. The function is available only for one continuous covariate X. Value An object of S3 class ’npcure’. Formally, a list of components: type The constant string "survival". local The value of the local argument. h The value of the h argument, unless this is missing, in which case its value is that of the cross-validation bandwidth. x0 The value of the x0 argument. testim The numeric vector of time values where the survival function is estimated. S A list whose components are the estimates of the survival function for each one of the covariate values, i.e., those specified by the x0 argument. The survival estimates are given at the times determined by the testimate argument. Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] References Beran, R. (1981). Nonparametric regression with randomly censored survival data. Technical re- port, University of California, Berkeley. <NAME>., <NAME>., <NAME>. (2018). Conditional copula models for right-censored clus- tered event time data. Biostatistics, 19(2): 247-262. https://doi.org/10.1093/biostatistics/ kxx034. See Also controlpars, berancv Examples ## Some artificial data set.seed(123) n <- 50 x <- runif(n, -2, 2) ## Covariate values y <- rweibull(n, shape = .5*(x + 4)) ## True lifetimes c <- rexp(n) ## Censoring values p <- exp(2*x)/(1 + exp(2*x)) ## Probability of being susceptible u <- runif(n) t <- ifelse(u < p, pmin(y, c), c) ## Observed times d <- ifelse(u < p, ifelse(y < c, 1, 0), 0) ## Uncensoring indicator data <- data.frame(x = x, t = t, d = d) ## Survival estimates for covariate values 0, 0.5 using... ## ... (a) global bandwidths 0.3, 0.5, 1. ## By default, the estimates are computed at the observed times x0 <- c(0, .5) S1 <- beran(x, t, d, data, x0 = x0, h = c(.3, .5, 1), local = FALSE) ## Plot predicted survival curves for covariate value 0.5 plot(S1$testim, S1$S$h0.3$x0.5, type = "s", xlab = "Time", ylab = "Survival", ylim = c(0, 1)) lines(S1$testim, S1$S$h0.5$x0.5, type = "s", lty = 2) lines(S1$testim, S1$S$h1$x0.5, type = "s", lty = 3) ## The true survival curve is plotted for reference p0 <- exp(2*x0[2])/(1 + exp(2*x0[2])) lines(S1$testim, 1 - p0 + p0*pweibull(S1$testim, shape = .5*(x0[2] + 4), lower.tail = FALSE), col = 2) legend("topright", c("Estimate, h = 0.3", "Estimate, h = 0.5", "Estimate, h = 1", "True"), lty = c(1:3, 1), col = c(rep(1, 3), 2)) ## As before, but with estimates computed at fixed times 0.1, 0.2,...,1 S2 <- beran(x, t, d, data, x0 = x0, h = c(.3, .5, 1), local = FALSE, testimate = .1*(1:10)) ## ... (b) local bandwidths 0.3, 0.5. ## Note that the length of the covariate vector x0 and the bandwidth h ## must be the same. S3 <- beran(x, t, d, data, x0 = x0, h = c(.3, .5), local = TRUE) ## ... (c) the cross-validation (CV) bandwidth selector (the default ## when the bandwidth argument is not provided). ## The CV bandwidth is searched in a grid of 150 bandwidths (hl = 150) ## between 0.2 and 2 times the standardized interquartile range ## of the covariate values (hbound = c(.2, 2)). ## 95% confidence intervals are also given. S4 <- beran(x, t, d, data, x0 = x0, conflevel = .95, cvbootpars = controlpars(hl = 150, hbound = c(.2, 2))) ## Plot of predicted survival curve and confidence intervals for ## covariate value 0.5 plot(S4$testim, S4$S$x0.5, type = "s", xlab = "Time", ylab = "Survival", ylim = c(0, 1)) lines(S4$testim, S4$conf$x0.5$lower, type = "s", lty = 2) lines(S4$testim, S4$conf$x0.5$upper, type = "s", lty = 2) lines(S4$testim, 1 - p0 + p0 * pweibull(S4$testim, shape = .5*(x0[2] + 4), lower.tail = FALSE), col = 2) legend("topright", c("Estimate with CV bandwidth", "95% CI limits", "True"), lty = c(1, 2, 1), col = c(1, 1, 2)) ## Example with the dataset 'bmt' in the 'KMsurv' package ## to study the survival of patients aged 25 and 40. data("bmt", package = "KMsurv") x0 <- c(25, 40) S <- beran(z1, t2, d3, bmt, x0 = x0, conflevel = .95) ## Plot of predicted survival curves and confidence intervals plot(S$testim, S$S$x25, type = "s", xlab = "Time", ylab = "Survival", ylim = c(0, 1)) lines(S$testim, S$conf$x25$lower, type = "s", lty = 2) lines(S$testim, S$conf$x25$upper, type = "s", lty = 2) lines(S$testim, S$S$x40, type = "s", lty = 1, col = 2) lines(S$testim, S$conf$x40$lower, type = "s", lty = 2, col = 2) lines(S$testim, S$conf$x40$upper, type = "s", lty = 2, col = 2) legend("topright", c("Age 25: Estimate", "Age 25: 95% CI limits", "Age 40: Estimate", "Age 40: 95% CI limits"), lty = 1:2, col = c(1, 1, 2, 2)) berancv Compute the Cross-Validation Bandwidth for Beran’s Estimator of the Conditional Survival Description This function computes the cross-validation bandwidth for Beran’s estimator of the conditional survival function. Usage berancv(x, t, d, dataset, x0, cvpars = controlpars()) Arguments x If dataset is missing, a numeric object giving the covariate values. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the covariate in the data frame. t If dataset is missing, a numeric object giving the observed times. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the observed times in the data frame. d If dataset is missing, an integer object giving the values of the uncensoring indicator. Censored observations must be coded as 0, uncensored ones as 1. If dataset is a data frame, it is interpreted as the name of the variable correspond- ing to the uncensoring indicator in the data frame. dataset An optional data frame in which the variables named in x, t and indicator are interpreted. If it is missing, x, t and indicator must be objects of the workspace. x0 A numeric vector of covariate values where the local cross-validation bandwidth will be computed. cvpars A list of parameters controlling the process of bandwidth selection. The default is the value returned by the controlpars function called without arguments. See the help for controlpars for details. Details The cross-validation (CV) bandwidth is taken as the largest local minimizer of the leave-one-out cross-validated criterion in Geerdens et al. (2018). Let F (−i) (t|xi ), i = 1, . . . , n be the Beran estimator obtained using the data points (xj , tj , dj ), j = 1, . . . , i − 1, i + 1, . . . , n. For the CV criterion, the differences I(ti ≤ tj ) − F (−i) (tj |xi ) are computed only for the so-called ’useful pairs’ of observed times (ti , tj ). A pair (Ti , Tj ) is useful if the value of the indicator I(Ti ≤ Tj ) gives an unambiguous correct value for the indicator I(Yi ≤ Yj ) which contains the corresponding true (possibly unknown) event times, see Geerdens et al. (2018) for details. Gannoun et al. (2007) apply a similar criterion to perform bandwidth selection for the Beran estimator, but they consider only the pairs of true (uncensored) event times. Note that the inclusion of useful pairs of observed times would be especially advantageous if the censoring rate is high. Value An object of S3 class ’npcure’. Formally, a list of components: type The constant character string c("Cross-validation bandwidth", "survival"). x0 Grid of covariate values. h Selected local cross-validation bandwidths. hgrid Grid of bandwidths used (optional). Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] References <NAME>., <NAME>., <NAME>. (2007). Comparison of kernel estimators of conditional distribu- tion function and quantile regression under censoring. Statistical Modeling, 7: 329-344. https: //doi.org/10.1177/1471082X0700700404. <NAME>., <NAME>., <NAME>. (2018). Conditional copula models for right-censored clus- tered event time data. Biostatistics, 19(2): 247-262. https://doi.org/10.1093/biostatistics/ kxx034. See Also beran, controlpars, hpilot Examples ## Some artificial data set.seed(123) n <- 50 x <- runif(n, -2, 2) ## Covariate values y <- rweibull(n, shape = .5*(x + 4)) ## True lifetimes c <- rexp(n) ## Censoring values p <- exp(2*x)/(1 + exp(2*x)) ## Probability of being susceptible u <- runif(n) t <- ifelse(u < p, pmin(y, c), c) ## Observed times d <- ifelse(u < p, ifelse(y < c, 1, 0), 0) ## Uncensoring indicator data <- data.frame(x = x, t = t, d = d) ## Computation of cross-validation (CV) local bandwidth for Beran's ## estimator of survival for covariate values 0, 1, ... #### ... with the default control parameters (passed through 'cvpars') x0 <- c(0, 1) hcv <- berancv(x, t, d, data, x0 = x0) #### ... changing the default 'cvpars' by calling the 'controlpars()' #### function: #### (a) the CV local bandwidth is searched in a grid of 150 bandwidths #### ('hl = 150') between 0.2 and 4 times the standardized interquartile #### range of the covariate values of x ('hbound = c(.2, 4')) #### (b) all the grid bandwidths are saved ('hsave = TRUE') hcv <- berancv(x, t, d, data, x0 = x0, cvpars = controlpars(hbound = c(.2, 4), hl = 150, hsave = TRUE)) ## Survival estimates for covariate values 0, 1, with CV local bandwidth S1 <- beran(x, t, d, data, x0 = x0, h = hcv$h) ## Plot predicted survival curves for covariate values 0, 1 plot (S1$testim, S1$S$x0, type = "s", xlab = "Time", ylab = "Survival", ylim = c(0, 1)) lines(S1$testim, S1$S$x1, type = "s", lty = 2) ## The survival curves are displayed for reference p0 <- exp(2*x0)/(1 + exp(2*x0)) lines(S1$testim, 1 - p0[1] + p0[1]*pweibull(S1$testim, shape = .5*(x0[1] + 4), lower.tail = FALSE), col = 2) lines(S1$testim, 1 - p0[2] + p0[2]*pweibull(S1$testim, shape = .5*(x0[2] + 4), lower.tail = FALSE), lty = 2, col = 2) legend("topright", c("Estimate, x = 0", "True, x = 0", "Estimate, x = 1", "True, x = 1"), lty = c(1, 1, 2, 2), col = 1:2) ## Example with the dataset 'bmt' of the 'KMsurv' package to study the ## survival of patients aged 25 and 40. data("bmt", package = "KMsurv") x0 <- c(25, 40) hcv <- berancv(z1, t2, d3, bmt, x0 = x0, cvpars = controlpars(hbound = c(.2, 4), hl = 150, hsave = TRUE)) S <- beran(z1, t2, d3, bmt, x0 = x0, h = hcv$h, conflevel = .95) ## Plot of predicted survival curves and confidence intervals plot(S$testim, S$S$x25, type = "s", xlab = "Time", ylab = "Survival", ylim = c(0, 1)) lines(S$testim, S$conf$x25$lower, type = "s", lty = 2) lines(S$testim, S$conf$x25$upper, type = "s", lty = 2) lines(S$testim, S$S$x40, type = "s", lty = 1, col = 2) lines(S$testim, S$conf$x40$lower, type = "s", lty = 2, col = 2) lines(S$testim, S$conf$x40$upper, type = "s", lty = 2, col = 2) legend("topright", c("Age 25: Estimate", "Age 25: 95% CI limits", "Age 40: Estimate", "Age 40: 95% CI limits"), lty = 1:2, col = c(1, 1, 2, 2)) controlpars Control Values for the Bootstrap or Cross-validation Description This function returns a list of values for the control parameters of the functions of the package that use the bootstrap or cross-validation. Usage controlpars(B = 999L, hbound = c(0.1, 3), hl = 100L, hsave = FALSE, nnfrac = 0.25, fpilot = NULL, qt = 0.75, hsmooth = 1L, ...) Arguments B An integer giving the number of bootstrap resamples. hbound A numeric vector of length 2 specifying the minimum (default, 0.1) and maxi- mum (default, 3), respectively, of the initial grid of bandwidths as a multiple of the standardized interquartile range of the covariate values. hl A numeric value giving the length of the initial grid of bandwidths. The default is 100. hsave A logical value specifying if the grids of bandwidths must be saved as a com- ponent of the list returned by the berancv, latencyboot and probcurehboot functions. The default is FALSE. nnfrac A numeric value giving the fraction of the sample size that determines the order of the nearest neighbor used when choosing the pilot bandwidth. The default is 0.25. fpilot A function name or NULL. If NULL, the default, the hpilot function is used for computing a pilot bandwidth in case that one is needed. If not NULL, it must be the name of a user-defined function (given as a function name or as a character string). This function must necessarily have an argument x0, playing the same role than in hpilot, and must return a value of the same length than x0. If fpilot has more arguments, they are passed through the ... argument (see below). qt In bandwidth selection for the latency estimator (see latencyhboot), a numeric value specifiying the order of a quantile of the observed times. It determines the right boundary of the integration interval in the computation of the ISE (the left boundary is 0). The default is 0.75 (third quartile). hsmooth An integer. Its value controls whether the bandwidths selected by the latencyhboot and probcurehboot and berancv function should be smoothed, and, if so, the degree of smoothing. The smoothing consists in computing a centered mov- ing average of the unsmoothed vector of bandwidths returned by default by latencyhboot and probcurehboot. The value of hsmooth is the number of terms used to compute the average. The default is 1L, which means that no smoothing is done. ... Arguments of fpilot, if fpilot is not NULL. Details The output of controlpars is a list of control parameters required by the package functions which use the bootstrap or cross-validation. This is mainly the case of the berancv function, which com- putes a cross-validation bandwidth for Beran’s estimator of survival, and of the latencyhboot and probcurehboot functions, which compute the bootstrap bandwidth selectors of the estimators of the latency and the probability of cure, respectively. Since these functions are indirectly called by, respectively, the beran, latency and probcure functions when their h argument is missing, the output of controlpars is also the expected (and default) way of passing to them the parameters for bandwidth selection. Additionally, controlpars is used by beran, latency and probcure to set the number of boot- strap resamples and the value of nnfrac (see above) when confidence intervals are computed. The testcov function also uses it for setting the number of bootstrap resamples. Value A list whose components are the arguments of the function, their defaults being replaced with the values the function was called with. Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] See Also beran,berancv, hpilot, latency, latencyhboot, probcure, probcurehboot,testcov hpilot Compute the Pilot Bandwidth for the Nonparametric Estimators of Cure Probability and Latency Description This function computes local pilot bandwidths for the nonparametric estimators of the probability of cure and the latency function. Usage hpilot(x, x0, nnfrac = 0.25) Arguments x A numeric vector of observed covariate values. x0 A numeric vector specifying a grid of covariate values. nnfrac A numeric value giving the fraction of the sample size that determines the or- der of the nearest neighbor. This is taken as floor(length(x)*nnfrac). The default is 0.25. Details The function computes a data-driven local pilot bandwidth, required for the bootstrap bandwidth selector of the nonparametric estimators of the cure rate and latency functions. Simulations in López-Cheda et al. (2017) show that the choice of pilot bandwidth has small effect on the boot- strap bandwidth. This pilot bandwidth only depends on the sample size and the distribution of the covariate x (see López-Cheda, 2018): − g(x0) = 0.5(d+ k (x0) + dk (x0))(100/n) − where d+ k (x0) and dk (x0) are the distances from x0 to the k-th nearest neighbor on the right and the left, respectively, and k is a suitable integer depending on the sample size n. If there are not at − least k neighbors on the right or on the left, we use d+ k (x0) = dk (x0). The default value of k is −1/9 n/4. The order n satisfies the conditions in Theorem 1 of Li and Datta (2001) and coincides with the order obtained by Cao and González-Manteiga (1993) for the uncensored case. Value A numeric vector of local pilot bandwidths corresponding to each one of the values of the grid of covariate values given by x0. Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] References <NAME>., <NAME>. (1993). Bootstrap methods in regression smoothing. Journal of Nonparametric Statistics, 2: 379-388. https://doi.org/10.1080/10485259308832566. <NAME>., <NAME>. (2001). A bootstrap approach to nonparametric regression for right censored data. Annals of the Institute of Statistical Mathematics, 53(4): 708-729. https://doi.org/10.1023/A: 1014644700806. <NAME>. (2018). Nonparametric Inference in Mixture Cure Models. PhD dissertation, Universidade da Coruña. Spain. <NAME>., <NAME>., <NAME>., <NAME>. (2017). Nonparametric incidence estimation and bootstrap bandwidth selection in mixture cure models. Computational Statistics & Data Analysis, 105: 144–165. https://doi.org/10.1016/j.csda.2016.08.002. <NAME>., <NAME>., <NAME>. (2017). Nonparametric latency estimation for mixture cure models. TEST, 26: 353–376. https://doi.org/10.1007/s11749-016-0515-1. See Also controlpars, latencyhboot, probcurehboot Examples ## Some artificial data set.seed(123) n <- 50 x <- runif(n, -2, 2) ## Covariate values y <- rweibull(n, shape = .5*(x + 4)) ## True lifetimes c <- rexp(n) ## Censoring values p <- exp(2*x)/(1 + exp(2*x)) ## Probability of being susceptible u <- runif(n) t <- ifelse(u < p, pmin(y, c), c) ## Observed times d <- ifelse(u < p, ifelse(y < c, 1, 0), 0) ## Uncensoring indicator data <- data.frame(x = x, t = t, d = d) ## Computing pilot bandwidths for covariate values -1, -0.8, ..., 1 ## by taking the 5-th nearest neighbor hpilot(data$x, x0 = seq(-1, 1, by = .2), nnfrac = .05) latency Compute Nonparametric Estimator of the Conditional Latency Description This function computes the nonparametric estimator of the conditional latency function proposed by López-Cheda et al. (2017). Usage latency(x, t, d, dataset, x0, h, local = TRUE, testimate = NULL, conflevel = 0L, bootpars = if (conflevel == 0 && !missing(h)) NULL else controlpars()) Arguments x If dataset is missing, a numeric object giving the covariate values. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the covariate in the data frame. t If dataset is missing, a numeric object giving the observed times. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the observed times in the data frame. d If dataset is missing, an integer object giving the values of the uncensoring indicator. Censored observations must be coded as 0, uncensored ones as 1. Ifdataset is a data frame, it is interpreted as the name of the variable corre- sponding to the uncensoring indicator. dataset An optional data frame in which the variables named in x, t and d are inter- preted. If it is missing, x, t and d must be objects of the workspace. x0 A numeric vector of covariate values where the latency estimates will be com- puted. h A numeric vector of bandwidths. If it is missing the default is to use the local bootstrap bandwidth computed by the latencyhboot function. local A logical value, TRUE by default, specifying whether local or global bandwidths are used. testimate A numeric vector specifying the times at which the latency is estimated. By default it is NULL, and then the latency is estimated at the times given by t. conflevel A value controlling whether bootstrap confidence intervals (CI) of the latency are to be computed. With the default value, 0L, the CIs are not computed. If a numeric value between 0 and 1 is passed, it specifies the confidence level of the CIs. bootpars A list of parameters controlling the bootstrap when computing the CIs of the latency: B, the number of bootstrap resamples, and nnfrac, the fraction of the sample size that determines the order of the nearest neighbor used for choosing a pilot bandwidth. If h is missing the list of parameters is extended to be the same used for computing the bootstrap bandwidth (see the help of latencyhboot for details). The default is the value returned by the controlpars function called without arguments. In case the CIs are not computed and h is not missing the default is NULL. Details The function computes the nonparametric estimator of the conditional latency S0 (t|X = x0 ) = P (Y > t|Y < ∞, X = x0 ) proposed by López-Cheda et al. (2017). It is only available for a continuous covariate X. Value An object of S3 class ’npcure’. Formally, a list of components: type The constant string "latency". local The value of the local argument. h The value of the h argument, unless this is missing, in which case its value is that of the cross-validation bandwidth. x0 The value of the x0 argument. testim The numeric vector of time values where the latency function is estimated. S A list whose components are the estimates of the latency function for each one of the covariate values, i.e., those specified by the x0 argument. The latency estimates are given at the times determined by the testimate argument. conf A list of components lower and upper giving the lower and the upper limits of the confidence intervals, respectively. Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] References <NAME>., <NAME>., <NAME>. (2017). Nonparametric latency estimation for mixture cure models. Test, 26: 353–376. https://doi.org/10.1007/s11749-016-0515-1. See Also controlpars, latencyhboot Examples ## Some artificial data set.seed(123) n <- 50 x <- runif(n, -2, 2) ## Covariate values y <- rweibull(n, shape = .5*(x + 4)) ## True lifetimes c <- rexp(n) ## Censoring values p <- exp(2*x)/(1 + exp(2*x)) ## Probability of being susceptible u <- runif(n) t <- ifelse(u < p, pmin(y, c), c) ## Observed times d <- ifelse(u < p, ifelse(y < c, 1, 0), 0) ## Uncensoring indicator data <- data.frame(x = x, t = t, d = d) ## Latency estimates for covariate value 0.5... x0 <- .5 ## ... (a) with global bandwidths 0.5, 1, 2. ## By default, estimates are computed at the time values of 't' S1 <- latency(x, t, d, data, x0 = x0, h = c(.5, 1, 2), local = FALSE) plot(S1$testim, S1$S$h0.5$x0.5, type = "s", xlab = "Time", ylab = "Latency", ylim = c(0, 1)) lines(S1$testim, S1$S$h1$x0.5, type = "s", lty = 2) lines(S1$testim, S1$S$h2$x0.5, type = "s", lty = 3) ## The true latency curve is plotted as reference lines(S1$testim, pweibull(S1$testim, shape = .5*(x0 + 4), lower.tail = FALSE), col = 2) legend("topright", c(paste("Estimate, ", c("h = 0.5", "h = 1", "h = 2")), "True"), lty = c(1:3, 1), col = c(rep(1, 3), 2)) ## As before, but with estimates computed at times 0.1, 0.2,..., 1 S2 <- latency(x, t, d, data, x0 = x0, h = c(.5, 1, 2), local = FALSE, testimate = .1*(1:10)) ## ... (b) with local bandwidth 2. S3 <- latency(x, t, d, data, x0 = x0, h = 2, local = TRUE) #### Note that with only one covariate value the results with #### 'local = FALSE' and 'local = TRUE' coincide, but the output formats #### differ slightly. Compare with S3 <- latency(x, t, d, data, x0 = x0, h = 2, local = FALSE) ## ... (c) with local bootstrap bandwidth b <- latencyhboot(x, t, d, data, x0 = x0) S4 <- latency(x, t, d, data, x0 = x0, h = b$h) ## ... (d) when the bandwidth is not specified, the bootstrap bandwidth #### selector given by the 'latencyhboot' function is used by default. #### The computation of 95% confidence intervals based on 1999 bootstrap #### resamples is also illustrated S5 <- latency(x, t, d, data, x0 = x0, conflevel = .95, bootpars = controlpars(B = 1999)) plot(S5$testim, S5$S$x0, type = "s", xlab = "Time", ylab = "Latency", ylim = c(0, 1)) lines(S5$testim, S5$conf$x0$lower, type = "s", lty = 2) lines(S5$testim, S5$conf$x0$upper, type = "s", lty = 2) lines(S5$testim, pweibull(S5$testim, shape = .5*(x0 + 4), lower.tail = FALSE), col = 2) legend("topright", c("Estimate", "95% CI limits", "True"), lty = c(1, 2, 1), col = c(1, 1, 2)) ## Example with the dataset 'bmt' of the 'KMsurv' package ## to study the survival of the uncured patients aged 25 and 40 data("bmt", package = "KMsurv") x0 <- c(25, 40) S <- latency(z1, t2, d3, bmt, x0 = x0, conflevel = .95) ## Plot of predicted latency curves and confidence intervals plot(S$testim, S$S$x25, type = "s", xlab = "Time (days)", ylab = "Latency", ylim = c(0,1)) lines(S$testim, S$conf$x25$lower, type = "s", lty = 2) lines(S$testim, S$conf$x25$upper, type = "s", lty = 2) lines(S$testim, S$S$x40, type = "s", lty = 1, col = 2) lines(S$testim, S$conf$x40$lower, type = "s", lty = 2, col = 2) lines(S$testim, S$conf$x40$upper, type = "s", lty = 2, col = 2) legend("topright", c("Age 25: Estimate", "Age 25: 95% CI limits", "Age 40: Estimate","Age 40: 95% CI limits"), lty = 1:2, col = c(1, 1, 2, 2)) latencyhboot Compute the Bootstrap Bandwidth for the Nonparametric Estimator of the Latency Description This function computes the bootstrap bandwidth for the nonparametric estimator of the conditional latency function. Usage latencyhboot(x, t, d, dataset, x0, bootpars = controlpars()) Arguments x If dataset is missing, a numeric object giving the covariate values. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the covariate in the data frame. t If dataset is missing, a numeric object giving the observed times. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the observed times in the data frame. d If dataset is missing, an integer object giving the values of the uncensoring indicator. Censored observations must be coded as 0, uncensored ones as 1. If dataset is a data frame, it is interpreted as the name of the variable correspond- ing to the uncensoring indicator in the data frame. dataset An optional data frame in which the variables named in x, t and indicator are interpreted. If it is missing, x, t and indicator must be objects of the workspace. x0 A numeric vector of covariate values where the local bootstrap bandwidth will be computed. bootpars A list of parameters controlling the process of bandwidth selection. The default is the value returned by the controlpars function called without arguments. Details The function computes the bootstrap bandwidth selector for the nonparametric estimator of the con- ditional latency function at the covariate values given by x0. The bootstrap bandwidth is the mini- mizer of a bootstrap version of the Mean Integrated Squared Error (MISE) of the latency estimator, which is approximated by Monte Carlo by simulating a large number of bootstrap resamples, B. For each value of x0, the bootstrap MISE is the bootstrap expectation of the integrated difference be- tween the value of the latency estimator computed with the bootstrap sample in a grid of bandwidths and its value computed with the original sample and a pilot bandwidth. The bootstrap resamples are generated by using the simple weighted bootstrap resampling method, fixing the covariate. This method is equivalent to the simple weighted bootstrap of Li and Datta (2001). All the parameters typically involved in the bootstrap bandwidth selection process (number of bootstrap resamples, grid of bandwidths, pilot bandwidth, and right boundary of the integration interval for comput- ing the MISE) are typically set through the controlpars function, whose output is passed to the bootpars argument. Also, the bootstrap bandwidths can be smoothed, and, if so, the smoothed bandwidths are returned as a separate component of the output. See the help of controlpars for details. Value An object of S3 class ’npcure’. Formally, a list of components: type The constant character string c("Bootstrap bandwidth", "latency"). x0 Grid of covariate values. h Selected local bootstrap bandwidths. hsmooth Smoothed selected local bootstrap bandwidths (optional) hgrid Grid of bandwidths used (optional). Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] References <NAME>., <NAME>. (2001). A bootstrap approach to nonparametric regression for right censored data. Annals of the Institute of Statistical Mathematics, 53: 708–729. https://doi.org/10.1023/A: 1014644700806. <NAME>., <NAME>., <NAME>. (2017). Nonparametric latency estimation for mixture cure models. TEST, 26: 353–376. https://doi.org/10.1007/s11749-016-0515-1. See Also controlpars, latency Examples ## Some artificial data set.seed(123) n <- 50 x <- runif(n, -2, 2) ## Covariate values y <- rweibull(n, shape = .5*(x + 4)) ## True lifetimes c <- rexp(n) ## Censoring values p <- exp(2*x)/(1 + exp(2*x)) ## Probability of being susceptible u <- runif(n) t <- ifelse(u < p, pmin(y, c), c) ## Observed times d <- ifelse(u < p, ifelse(y < c, 1, 0), 0) ## Uncensoring indicator data <- data.frame(x = x, t = t, d = d) ## A vector of covariate values vecx0 <- seq(-1.5, 1.5, by = .1) ## Computation of bootstrap local bandwidths at the values of 'vecx0'... #### ... with the default control parameters hb1 <- latencyhboot(x, t, d, data, x0 = vecx0) #### ... changing the default 'bootpars' with 'controlpars()': #### (a) 'B = 1999' (1999 bootstrap resamples are generated), #### (b) 'hbound = c(.2, 4)' and 'hl = 50' (a grid of 50 bandwidths #### between 0.2 and 4 times the standardized interquartile range of #### the covariate values is built), and #### (c) 'hsave = TRUE' (the grid bandwidths are saved), and hb2 <- latencyhboot(x, t, d, data, x0 = vecx0, bootpars = controlpars(B = 1999, hbound = c(.2, 4), hl = 50, hsave = TRUE)) ## Estimates of the conditional latency at the covariate value x0 = 0 ## with the selected bootstrap bandwidths S1 <- latency(x, t, d, data, x0 = 0, h = hb1$h[hb1$x0 == 0]) S2 <- latency(x, t, d, data, x0 = 0, h = hb2$h[hb2$x0 == 0]) ## A plot comparing the estimates with bootstrap bandwidths obtained ## with default and non-default 'bootpars' plot(S1$testim, S1$S$x0, type = "s", xlab = "Time", ylab = "Latency", ylim = c(0, 1)) lines(S2$testim, S2$S$x0, type = "s", lty = 2) lines(S1$testim, pweibull(S1$testim, shape = .5*(0 + 4), lower.tail = FALSE), col = 2) legend("topright", c("Estimate with 'hb1'", "Estimate with 'hb2'", "True"), lty = c(1, 2, 1), col = c(1, 1, 2)) ## Example with the dataset 'bmt' of the 'KMsurv' package ## to study the survival of the uncured patients aged 25 and 40 data("bmt", package = "KMsurv") x0 <- c(25, 40) hb <- latencyhboot(z1, t2, d3, bmt, x0 = x0, bootpars = controlpars(B = 1999, hbound = c(.2, 4), hl = 150, hsave = TRUE)) S0 <- latency(z1, t2, d3, bmt, x0 = x0, hb$h, conflevel = .95) ## Plot of predicted latency curves and confidence bands plot(S0$testim, S0$S$x25, type = "s", xlab = "Time (days)", ylab = "Survival", ylim = c(0,1)) lines(S0$testim, S0$conf$x25$lower, type = "s", lty = 2) lines(S0$testim, S0$conf$x25$upper, type = "s", lty = 2) lines(S0$testim, S0$S$x40, type = "s", lty = 1, col = 2) lines(S0$testim, S0$conf$x40$lower, type = "s", lty = 2, col = 2) lines(S0$testim, S0$conf$x40$upper, type = "s", lty = 2, col = 2) legend("topright", c("Age 25: Estimate", "Age 25: 95% CI limits", "Age 40: Estimate", "Age 40: 95% CI limits"), lty = 1:2, col = c(1, 1, 2, 2)) print.npcure Print Method for Objects of Class ’npcure’ Description This function implements a print method for ’npcure’ objects. Usage ## S3 method for class 'npcure' print(x, how, head = FALSE, ...) Arguments x An object of class ’npcure’. how A character string with values "wide" or "long". If missing, the function itself chooses a convenient default. head A logical value that controls whether the function’s output must be abbreviated (TRUE) or not (FALSE, the default). ... Further optional arguments. Excepting for n, which controls how many lines are printed when head = TRUE, these are the arguments for the default method (i.e., print.default) of the print generic function. Value A formatted output. Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] See Also summary.npcure Examples ## Some artificial data set.seed(123) n <- 50 x <- runif(n, -2, 2) ## Covariate values y <- rweibull(n, shape = .5*(x + 4)) ## True lifetimes c <- rexp(n) ## Censoring values p <- exp(2*x)/(1 + exp(2*x)) ## Probability of being susceptible u <- runif(n) t <- ifelse(u < p, pmin(y, c), c) ## Observed times d <- ifelse(u < p, ifelse(y < c, 1, 0), 0) ## Uncensoring indicator data <- data.frame(x = x, t = t, d = d) ## Calling 'print()' with an object of class 'npcure' created by ## 'latency()' S1 <- latency(x, t, d, data, x0 = c(0, .5), h = c(1, 1.5)) ## In this case (latency estimation with local bandwidths and without ## confidence bands), the 'wide' format is used by default S1 print(S1, how = "wide") print(S1, how = "long") ## How to control the number of significant digits of the output, and ## how to abbreviate the output print(S1, digits = 5, head = TRUE, n = 4) ## Calling 'print()' with a 'npcure' object created by 'probcure()' q1 <- probcure(x, t, d, data, x0 = c(0, .5), h = c(.5, 1, 1.5), local = FALSE, conflevel = .95) ## Only the 'long' format is available when confidence bands are ## computed q1 print(q1, how = "long") print(q1, how = "wide") probcure Compute Nonparametric Estimator of the Conditional Probability of Cure Description This function computes the nonparametric estimator of the conditional probability of cure proposed by <NAME> Peng (2014). Usage probcure(x, t, d, dataset, x0, h, local = TRUE, conflevel = 0L, bootpars = if (conflevel == 0 && !missing(h)) NULL else controlpars()) Arguments x If dataset is missing, a numeric object giving the covariate values. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the covariate in the data frame. t If dataset is missing, a numeric object giving the observed times. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the observed times in the data frame. d If dataset is missing, an integer object giving the values of the uncensoring indicator. Censored observations must be coded as 0, uncensored ones as 1. If dataset is a data frame, it is interpreted as the name of the variable correspond- ing to the uncensoring indicator in the data frame. dataset An optional data frame in which the variables named in x, t and d are inter- preted. If it is missing, x, t and d must be objects of the workspace. x0 A numeric vector of covariate values where the estimates of cure probability will be computed. h A numeric vector of bandwidths. If it is missing the default is to use the local bootstrap bandwidth computed by the probcurehboot function. local A logical value, TRUE by default, specifying whether local or global bandwidths are used. conflevel A value controlling whether bootstrap confidence intervals (CI) of the cure prob- ability are to be computed. With the default value, 0L, the CIs are not computed. If a numeric value between 0 and 1 is passed, it specifies the confidence level of the CIs. bootpars A list of parameters controlling the bootstrap when computing either the CIs of the cure probability or the bootstrap bandwidth (if h is missing): B, the number of bootstrap resamples, and nnfrac, the fraction of the sample size that deter- mines the order of the nearest neighbor used for choosing a pilot bandwidth. The default is the value returned by the controlpars function called without arguments. If the CIs are not computed and h is not missing the default is NULL. Details The function computes the nonparametric estimator of the conditional cure probability q(X = x0 ) ≡ 1 − p(X = x0 ) = P (Y = ∞|X = x0 ) proposed by Xu and Peng (2014), and also studied by López-Cheda et al (2017). It is only available for a continuous covariate X. Value An object of S3 class ’npcure’. Formally, a list of components: estimate The constant string "cure". local The value of the local argument. h The value of the h argument, unless this is missing, in which case its value is that of the bootstrap bandwidth. x0 The value of the x0 argument. q A list with the estimates of the probability of cure. conf A list of components lower and upper giving the lower and the upper limits of the confidence intervals, respectively. Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] References <NAME>., <NAME>., <NAME>., <NAME>. (2017). Nonparametric incidence estimation and bootstrap bandwidth selection in mixture cure models. Computational Statistics & Data Analysis, 105: 144–165. https://doi.org/10.1016/j.csda.2016.08.002. <NAME>., <NAME>. (2014). Nonparametric cure rate estimation with covariates. The Canadian Journal of Statistics 42: 1-17. https://doi.org/10.1002/cjs.11197. See Also controlpars, probcurehboot Examples ## Some artificial data set.seed(123) n <- 50 x <- runif(n, -2, 2) ## Covariate values y <- rweibull(n, shape = 0.5 * (x + 4)) ## True lifetimes c <- rexp(n) ## Censoring values p <- exp(2*x)/(1 + exp(2*x)) ## Probability of being susceptible u <- runif(n) t <- ifelse(u < p, pmin(y, c), c) ## Observed times d <- ifelse(u < p, ifelse(y < c, 1, 0), 0) ## Uncensoring indicator data <- data.frame(x = x, t = t, d = d) ## Covariate values where cure probability is estimated x0 <- seq(-1.5, 1.5, by = 0.1) ## Nonparametric estimates of cure probability at 'x0'... ## ... (a) with global bandwidths 1, 1.5, 2 q1 <- probcure(x, t, d, data, x0 = x0, h = c(1, 1.5, 2), local = FALSE) #### Plot predicted cure probabilities at 'x0' for each bandwidth in 'h' #### (the true cure probability is displayed for reference) plot(q1$x0, q1$q$h1, type = "l", xlab = "Covariate", ylab = "Cure probability", ylim = c(0, 1)) lines(q1$x0, q1$q$h1.5, lty = 2) lines(q1$x0, q1$q$h2, lty = 3) lines(q1$x0, 1 - exp(2*q1$x0)/(1 + exp(2*q1$x0)), col = 2) legend("topright", c(paste("Estimate, ", c("h = 1", "h = 1.5", "h = 2")), "True"), lty = c(1, 2, 3, 1), col = c(1, 1, 1, 2)) ## ... (b) with local bandwidths (default) #### (the vectors passed to 'x0' and 'h' must have the same length) q2 <- probcure(x, t, d, data, x0 = x0, h = seq(1, 2.5, along = x0)) ## ... (c) with local bootstrap bandwidths (based on 1999 booostrap #### resamples). Besides, 95% confidence intervals are computed and #### smoothed (with a 15-th order moving average) set.seed(1) ## Not needed, just for reproducibility. hb <- probcurehboot(x, t, d, data, x0 = x0, bootpars = controlpars(B = 1999, hsmooth = 15)) q3 <- probcure(x, t, d, data, x0 = x0, h = hb$hsmooth, conflevel = .95, bootpars = controlpars(B = 1999)) ## ... (d) If the bandwidth is not specified, the local bootstrap #### bandwidth is used (same results as in (c)) set.seed(1) ## Not needed, just for reproducibility. q4 <- probcure(x, t, d, data, x0 = x0, conflevel = .95, bootpars = controlpars(B = 1999, hsmooth = 15)) #### Plot of the estimated cure probabilities evaluated at 'x0' #### (true cure rate displayed as reference) plot (q4$x0, q4$q, type = "l", ylim = c(0, 1), xlab = "Covariate X", ylab = "Cure probability") lines(q4$x0, q4$conf$lower, lty = 2) lines(q4$x0, q4$conf$upper, lty = 2) lines(q4$x0, 1-exp(2 * q4$x0)/(1 + exp(2 * q4$x0)), col = 2) legend("topright", c("Estimate", "95% CI limits", "True"), lty = c(1, 2, 1), col = c(1, 1, 2)) ## Example with the dataset 'bmt' in the 'KMsurv' package ## to study the probability of cure as a function of the age (z1). data("bmt", package = "KMsurv") x0 <- seq(quantile(bmt$z1, .05), quantile(bmt$z1, .95), length.out = 100) q.age <- probcure(z1, t2, d3, bmt, x0 = x0, conflevel = .95, bootpars = controlpars(B = 1999, hsmooth = 10)) ## Plot of estimated cure probability and confidence intervals par(mar = c(5, 4, 4, 5) + .1) plot(q.age$x0, q.age$q, type = "l", ylim = c(0, 1), xlab = "Patient age (years)", ylab = "Cure probability") lines(q.age$x0, q.age$conf$lower, lty = 2) lines(q.age$x0, q.age$conf$upper, lty = 2) ## The estimated density of age (z1) is added for reference par(new = TRUE) d.age <- density(bmt$z1) plot(d.age, xaxt = "n", yaxt = "n", xlab = "", ylab = "", col = 2, main = "", zero.line = FALSE) mtext("Density", side = 4, col = 2, line = 3) axis(4, ylim = c(0, max(d.age$y)), col = 2, col.axis = 2) legend("topright", c("Estimate", "95% CI limits", "Covariate density"), lty = c(1, 2, 1), col = c(1, 1, 2)) probcurehboot Compute the Bootstrap Bandwidth for the Nonparametric Estimator of the Cure Probability Description This function computes the bootstrap bandwidth for the nonparametric estimator of the conditional probability of cure. Usage probcurehboot(x, t, d, dataset, x0, bootpars = controlpars()) Arguments x If dataset is missing, a numeric object giving the covariate values. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the covariate in the data frame. t If dataset is missing, a numeric object giving the observed times. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the observed times in the data frame. d If dataset is missing, an integer object giving the values of the uncensoring indicator. Censored observations must be coded as 0, uncensored ones as 1. If dataset is a data frame, it is interpreted as the name of the variable correspond- ing to the uncensoring indicator in the data frame. dataset An optional data frame in which the variables named in x, t and indicator are interpreted. If it is missing, x, t and indicator must be objects of the workspace. x0 A numeric vector of covariate values where the local bootstrap bandwidth will be computed. bootpars A list of parameters controlling the process of bandwidth selection. The default is the value returned by the controlpars function called without arguments. Details The function computes the bootstrap bandwidth selector for the nonparametric estimator of the cure probability at the covariate values given by x0. The bootstrap bandwidth is the minimizer of a boot- strap version of the Mean Squared Error (MSE) of the cure rate estimator, which is approximated by Monte Carlo by simulating a large number, B, of bootstrap resamples. The bootstrap MSE is the bootstrap expectation of the difference between the value of the cure rate estimator computed with the bootstrap sample in a grid of bandwidths and its value computed with the original sample and a pilot bandwidth. The bootstrap resamples are generated by using the simple weighted boot- strap resampling method, fixing the covariate. This method is equivalent to the simple weighted bootstrap of Li and Datta (2001). All the parameters involved in the bootstrap bandwidth selection process (number of bootstrap resamples, grid of bandwidths, and pilot bandwidth) are typically set through the controlpars function, whose output is passed to the bootpars argument. See the help of controlpars for details. Given the local nature of bootstrap bandwidth selection, estimates obtained from sets of bootstrap bandwidths may sometimes look wiggly. To counter this behavior, the selected vector of bootstrap bandwidths can be smoothed by computing a moving average (its order being set by controlpars). Then, the smoothed bandwidths are contained in the hsmooth component of the returned value. Value An object of S3 class ’npcure’. Formally, a list of components: type The constant character string c("Bootstrap bandwidth", "cure"). x0 Grid of covariate values. h Selected local bootstrap bandwidths. hsmooth Smoothed selected local bootstrap bandwidths (optional) hgrid Grid of bandwidths used (optional). Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] References <NAME>., <NAME>. (2001). A bootstrap approach to nonparametric regression for right censored data. Annals of the Institute of Statistical Mathematics, 53: 708-729. https://doi.org/10.1023/A: 1014644700806. <NAME>., <NAME>., <NAME>., <NAME>. (2017). Nonparametric incidence estimation and bootstrap bandwidth selection in mixture cure models. Computational Statistics & Data Analysis, 105: 144–165. https://doi.org/10.1016/j.csda.2016.08.002. See Also controlpars, probcure Examples ## Some artificial data set.seed(123) n <- 50 x <- runif(n, -2, 2) ## Covariate values y <- rweibull(n, shape = .5*(x + 4)) ## True lifetimes c <- rexp(n) ## Censoring values p <- exp(2*x)/(1 + exp(2*x)) ## Probability of being susceptible u <- runif(n) t <- ifelse(u < p, pmin(y, c), c) ## Observed times d <- ifelse(u < p, ifelse(y < c, 1, 0), 0) ## Uncensoring indicator data <- data.frame(x = x, t = t, d = d) ## A vector of covariate values vecx0 <- seq(-1.5, 1.5, by = .1) ## Computation of bootstrap local bandwidth at the values of 'vecx0'... #### ... with the default control parameters set.seed(1) ## Not needed, just for reproducibility. hb1 <- probcurehboot(x, t, d, data, x0 = vecx0) #### ... changing the default 'bootpars' through 'controlpars()', with #### arguments: #### (a) 'B = 1999' (1999 bootstrap resamples are generated), #### (b) 'hbound = c(.2, 4)' and 'hl = 50' (a grid of 50 bandwidths #### between 0.2 and 4 times the standardized interquartilic range of #### the covariate values is built), #### (c) 'hsave = TRUE' (the grid bandwidths are saved), and #### (d) 'hsmooth = 7' (the bootstrap bandwidths are smoothed by a #### moving average of 7-th order) set.seed(1) ## Not needed, just for reproducibility. hb2 <- probcurehboot(x, t, d, data, x0 = vecx0, bootpars = controlpars(B = 1999, hbound = c(.2, 4), hl = 50, hsave = TRUE, hsmooth = 7)) ## Estimates of the conditional probability of cure at the covariate ## values of 'vecx0' with the selected bootstrap bandwidths q1 <- probcure(x, t, d, data, x0 = vecx0, h = hb1$h) q2 <- probcure(x, t, d, data, x0 = vecx0, h = hb2$h) q2sm <- probcure(x, t, d, data, x0 = vecx0, h = hb2$hsmooth) ## A plot comparing the estimates obtained with the bootstrap bandwidths plot(q1$x0, q1$q, type = "l", xlab = "Covariate", ylab = "Cure probability", ylim = c(0,1)) lines(q2$x0, q2$q, type = "l", lty = 2) lines(q2sm$x0, q2sm$q, type = "l", lty = 3) lines(q1$x0, 1 - exp(2*q1$x0)/(1 + exp(2*q1$x0)), col = 2) legend("topright", c("Estimate with 'hb1'", "Estimate with 'hb2'", "Estimate with 'hb2' smoothed", "True"), lty = c(1, 2, 3, 1), col = c(1, 1, 1, 2)) ## Example with the dataset 'bmt' of the 'KMsurv' package ## to study the probability of cure as a function of the age (z1). data("bmt", package = "KMsurv") x0 <- seq(quantile(bmt$z1, .05), quantile(bmt$z1, .95), length.out = 100) ## This might take a while hb <- probcurehboot(z1, t2, d3, bmt, x0 = x0, bootpars = controlpars(B = 1999, hbound = c(.2, 2), hl = 50, hsave = TRUE, hsmooth = 10)) q.age <- probcure(z1, t2, d3, bmt, x0 = x0, h = hb$h) q.age.smooth <- probcure(z1, t2, d3, bmt, x0 = x0, h = hb$hsmooth) ## Plot of estimated cure probability plot(q.age$x0, q.age$q, type = "l", ylim = c(0, 1), xlab = "Patient age (years)", ylab = "Cure probability") lines(q.age.smooth$x0, q.age.smooth$q, col = 2) legend("topright", c("Estimate with h bootstrap", "Estimate with smoothed h bootstrap"), lty = 1, col = 1:2) summary.npcure Summary Method for Objects of Class ’npcure’ Description This function prints a summary of a ’npcure’ object. Usage ## S3 method for class 'npcure' summary(object, ...) Arguments object An object of class ’npcure’. ... Further optional arguments for the default method (i.e., summary.default) of the summary generic function. Value A compact summary showing the components of the object. Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] See Also print.npcure Examples ## Some artificial data set.seed(123) n <- 50 x <- runif(n, -2, 2) ## Covariate values y <- rweibull(n, shape = .5*(x + 4)) ## True lifetimes c <- rexp(n) ## Censoring values p <- exp(2*x)/(1 + exp(2*x)) ## Probability of being susceptible u <- runif(n) t <- ifelse(u < p, pmin(y, c), c) ## Observed times d <- ifelse(u < p, ifelse(y < c, 1, 0), 0) ## Uncensoring indicator data <- data.frame(x = x, t = t, d = d) ## Calling 'summary()' with an object of class 'npcure' created by ## 'latency()' S1 <- latency(x, t, d, data, x0 = c(0, .5), h = c(1, 1.5)) summary(S1) ## If needed, the number of significant digits of the output can be set summary(S1, digits = 5) ## Calling 'summary()' with an object created by 'probcure()' q1 <- probcure(x, t, d, data, x0 = c(0, .5), h = c(.5, 1, 1.5), local = FALSE, conflevel = .95) summary(q1) testcov Covariate Significance Test of the Cure Probability Description This function carries out a significance test of covariate effect on the probability of cure. Usage testcov(x, t, d, dataset, bootpars = controlpars()) Arguments x If dataset is missing, an object giving the covariate values, whose type can be numeric, integer, factor or character. Ifdataset is a data frame, it is interpreted as the name of the variable corresponding to the covariate in the data frame. t If dataset is missing, a numeric object giving the observed times. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the observed times in the data frame. d If dataset is missing, an integer object giving the values of the uncensoring indicator. Censored observations must be coded as 0, uncensored ones as 1. If dataset is a data frame, it is interpreted as the name of the variable correspond- ing to the uncensoring indicator. dataset An optional data frame in which the variables named in x, t and d are inter- preted. If it is missing, x, t and d must be objects of the workspace. bootpars A list of parameters controlling the test. Currently, the only accepted component is B, the number of bootstrap resamples. The default is the value returned by the controlpars function called without arguments. Details The function computes a statistic, based on the method by Delgado and González-Manteiga (2004), to test whether a covariate X has an effect on the cure probability (H1 : cure probability = q(x)) or not (H0 : cure probability = q). Since the cure rate can be written as the regression function E(ν|X = x) = q(x), where ν is the cure indicator, the procedure is carried out as a significance test in nonparametric regression. The challenge of the test is that the cure indicator ν is only partially observed due to censoring: for the uncensored observations ν = 0, but it is unknown if a censored individual will be eventually cured or not (ν unknown). The approach consists in expressing the cure rate as a regression function with another response, not observable but estimable, say η. The estimated values of η depend on suitable estimates of the conditional distribution of the censoring variable and τ (x), an unknown time beyond which a subject could be considered as cured; see López-Cheda (2018). For the computation of the values of η, the censoring distribution is estimated unconditionally using the Kaplan-Meier product-limit estimator. The time τ is estimated by the largest uncensored time. The test statistic is a weighted mean of the difference between the observations of ηi and the values of the conditional mean of η under the null hypothesis: X Tn(x) = 1/n (ηi − η̄)I(xi ≤ x) . For a qualitative covariate there is no natural way to order the values xi . In principle, this makes impossible to compute the indicator function in the test statistic. The problem is solved by consid- ering all the possible combinations of the covariate values, and by computing the test statistic for each ’ordered’ combination. Tn(x) is taken as the largest value of these test statistics. The distribution of the test statistic under the null hypothesis is approximated by bootstrap, using independent naive resampling. Value An object of S3 class ’npcure’. Formally, a list of components: type The constant character string c("test", "Covariate"). x The name of the covariate. CM The result of the Cramer-von Mises test: a list with components statistic, the test statistic, and pvalue, the p-value. KS The result of the Kolmogorov-Smirnov test: a list with components statistic, the test statistic, and pvalue, the p-value. Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] References <NAME>., <NAME>. (2001). Significance testing in nonparametric regression based on the bootstrap. Annals of Statistics, 29: 1469-1507. <NAME>. (2018). Nonparametric Inference in Mixture Cure Models. PhD dissertation, Universidade da Coruña. Spain. See Also controlpars Examples ## Some artificial data set.seed(123) n <- 50 x <- runif(n, -2, 2) ## Covariate values y <- rweibull(n, shape = .5*(x + 4)) ## True lifetimes c <- rexp(n) ## Censoring values p <- exp(2*x)/(1 + exp(2*x)) ## Probability of being susceptible u <- runif(n) t <- ifelse(u < p, pmin(y, c), c) ## Observed times d <- ifelse(u < p, ifelse(y < c, 1, 0), 0) ## Uncensoring indicator data <- data.frame(x = x, t = t, d = d) ## Test of the significance of the covariate 'x' testcov(x, t, d, data) ## Test carried out with 1999 bootstrap resamples (the default is 999) testcov(x, t, d, data, bootpars = controlpars(B = 1999)) ## How to apply the test repeatedly when there is more than one ## covariate... ## ... 'y' is another continuous covariate of the data frame 'data' data$y <- runif(n, -1, 1) namecovar <- c("x", "y") ## ... testcov is called from a 'for' loop for (i in 1:length(namecovar)) { result <- testcov(data[, namecovar[i]], data$t, data$d) print(result) } ## In the previous example, testcov() was called without using the ## argument 'dataset'. To use it, the 'for' must be avoided testcov(x, t, d, data) testcov(y, t, d, data) ## Non-numeric covariates can also be tested... ## ... 'z' is a nominal covariate of the data frame 'data' data$z <- rep(factor(letters[1:5]), each = n/5) testcov(z, t, d, data) ## Example with the dataset 'bmt' in the 'KMsurv' package ## to study the effect on the probability of cure of... ## ... (a) a continuous covariate (z1 = age of the patient) data("bmt", package = "KMsurv") set.seed(1) ## Not needed, just for reproducibility. testcov(z1, t2, d3, bmt, bootpars = controlpars(B = 4999)) ## ... (b) a qualitative covariate (z3 = patient gender) set.seed(1) ## Not needed, just for reproducibility. testcov(z3, t2, d3, bmt, bootpars = controlpars(B = 4999)) testmz Test of Maller-Zhou Description This function carries out the nonparametric test of Maller and Zhou (1992). Usage testmz(t, d, dataset) Arguments t If dataset is missing, a numeric object giving the the observed times. If dataset is a data frame, it is interpreted as the name of the variable corresponding to the observed times in the data frame. d If dataset is missing, an integer object giving the values of the uncensoring indicator. Censored observations must be coded as 0, uncensored ones as 1. If dataset is a data frame, it is interpreted as the name of the variable correspond- ing to the uncensoring indicator. dataset An optional data frame in which the variables named in x, t and d are inter- preted. If it is missing, x, t and d must be objects of the workspace. Details The function implements Maller and Zhou’s (1992) method to test the null hypothesis H0 : τF0 > τG vs. H1 : τF0 ≤ τG , where τF0 and τG are the supports of, respectively, the distribution function of the survival time of the uncured and the distribution function of the censoring time. Value An object of S3 class ’npcure’. Formally, a list of components: type The constant character string c("test", "Maller-Zhou"). pvalue The p-value of the test. aux A list of components: statistic, the test statistic, n the sample size, delta, the difference between the largest observed time tn and the largest uncensored time t?n , and interval, a vector giving the range between max(0, t?n − delta) and t?n . Author(s) <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] References <NAME>., <NAME>. (1992). Estimating the proportion of immunes in a censored sample. Biometrika, 79: 731-739. https://doi.org/10.1093/biomet/79.4.731. See Also latency, probcure Examples ## Some artificial data set.seed(123) n <- 50 y <- qweibull(runif(n)*pweibull(2, shape = 2), shape = 2) ## True lifetimes c <- qexp(runif(n)*pexp(2.5)) ## Censoring values u <- runif(n) ## Probability of being susceptible is constantly equal to .5 t <- ifelse(u < .5, pmin(y, c), c) ## Observed times d <- ifelse(u < .5, ifelse(y < c, 1, 0), 0) ## Uncensoring indicator data <- data.frame(t = t, d = d) ## Maller-Zhou test testmz(t, d, data)
bbsBayes
cran
R
Package ‘bbsBayes’ February 27, 2023 Type Package Title Hierarchical Bayesian Analysis of North American BBS Data Version 2.5.3 Date 2023-02-18 Imports progress, jagsUI, ggrepel, geofacet, ggplot2, stringr, grDevices, dplyr, sf, tools, rappdirs, sbtools, mgcv Depends R (>= 3.5) SystemRequirements JAGS 4.3.0 (https://sourceforge.net/projects/mcmc-jags/) URL https://github.com/bbsBayes/bbsBayes NeedsCompilation no Description The North American Breeding Bird Survey (BBS) is a long-running program that seeks to monitor the status and trends of the breeding birds in North America. Since its start in 1966, the BBS has accumulated over 50 years of data for over 500 species of North American Birds. Given the temporal and spatial structure of the data, hierarchical Bayesian models are used to assess the status and trends of these 500+ species of birds. 'bbsBayes' allows you to perform hierarchical Bayesian analysis of BBS data. You can run a full model analysis for one or more species that you choose, or you can take more control and specify how the data should be stratified, prepared for 'JAGS', or modelled. The functions provided here allow you to replicate analyses performed by the United State Geological Survey (USGS, see Link and Sauer (2011) <doi:10.1525/auk.2010.09220>) and Canadian Wildlife Service (CWS, see Smith and Edwards (2020) <doi:10.1101/2020.03.26.010215>). License MIT + file LICENSE Encoding UTF-8 LazyData true RoxygenNote 7.1.1 Author <NAME> [aut, cre], <NAME> [aut] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2023-02-27 18:32:30 UTC R topics documented: bird_sampl... 2 fetch_bbs_dat... 3 generate_indice... 4 generate_ma... 7 generate_trend... 8 geofacet_plo... 11 get_composite_region... 13 get_final_value... 14 get_mcmc_lis... 16 get_prepared_dat... 17 get_strata_are... 18 load_bbs_dat... 19 load_ma... 20 load_sample_dat... 20 lpp... 21 model_to_fil... 22 plot_indice... 23 prepare_dat... 25 route_sampl... 28 run_mode... 29 r_ha... 31 species_sampl... 33 stratif... 33 bird_sample Sample point count data per species (Pacific Wren only) Description A sample dataset containing 10-stop counts of each bird species seen per route per year. NOTE: This only contains data for Pacific Wren, not the full data set. The full count set is obtained via the function fetch_bbs_data. The data is obtained from the United States Geological Survey and is subject to change as new data is added each year. See Details for citation. Usage bird_sample Format A data frame with 20 rows and 15 variables: statenum Numerical representation of state or province Route Numerican representation of the route the species was observed countrynum Numerical representation of the country RouteDataID Unique code for each year a route was run RPID Run Protocol ID Year Year the species was observed on the route AOU Numerical representation of the species, designated by American Ornithological Union Count10 Counts for stops 1-10 Count20 Counts for stops 11-20 Count30 Counts for stops 21-30 Count40 Counts for stops 31-40 Count50 Counts for stops 41-50 StopTotal Count for all stops SpeciesTotal Total count for the species on the route run BCR Bird Conservation Region the route was run in Details <NAME>., <NAME>., <NAME>, <NAME> and <NAME>. 2019. North American Breeding Bird Survey Dataset 1966 - 2018, version 2018.0. U.S. Geological Survey, Patuxent Wildlife Research Center. https://doi.org/10.5066/P9HE8XYJ. fetch_bbs_data Fetch Breeding Bird Survey dataset Description fetch_bbs_data uses File Transfer Protocol (FTP) to fetch Breeding Bird Survey data from the United States Geological Survey (USGS) FTP site. This is the raw data that is uploaded to the site before any analyses are performed. A package-specific directory is created on the user’s computer (see documentation of rappdirs::appdir for details of where this directory lives), and the BBS data is saved to that directory for use by other functions. Before downloading any data, the user must thoroughly read through the terms and conditions of the user of the data and type the word "yes" to agree. Usage fetch_bbs_data(level = "state", release = 2022, quiet = FALSE, force = FALSE) Arguments level A string, either "state" or "stop", specifying which counts to fetch. Defaults to "state", which provides counts beginning in 1966, aggregated in five bins, each of which contains cumulative counts from 10 of the 50 stops along a route. Specifying "stop" provides stop-level data beginning in 1997, which includes counts for each stop along routes individually. Note that stop-level data is not currently supported by the modeling utilities in bbsBayes. release Integer: what yearly release is desired? options are 2022 (default including data through 2021 field season) or 2020 (including data through 2019) quiet Logical: should progress bars be suppressed? Defaults to FALSE force Logical: if BBS data already exists on computer, should it be overwritten? De- faults to FALSE Value None generate_indices Generate regional annual indices of abundance continent and strata and optionally for countries, states/provinces, or BCRs from analyses run on the stratifications that support these composite regions Description generate_indices creates a data frame of the annual indices of relative abundance by year. This data frame can then be used to plot population trajectories for the species, and to estimate trends. Usage generate_indices( jags_mod = NULL, jags_data = NULL, quantiles = c(0.025, 0.05, 0.25, 0.75, 0.95, 0.975), regions = c("stratum", "continental"), alternate_n = "n", startyear = NULL, drop_exclude = FALSE, max_backcast = NULL, alt_region_names = NULL ) Arguments jags_mod JAGS list generated by run_model jags_data data object used in run_model quantiles vector of quantiles to be sampled from the posterior distribution Defaults to c(0.025,0.05,0.25,0.5,0.75,0.95,0.975) regions vector selecting regional compilation(s) to calculate. Default is "continental","stratum", options also include "national", "prov_state", "bcr", and "bcr_by_country" for the stratifications that include areas that align with those regions. alternate_n text string indicating the name of the alternative annual index parameter in a model, Default is "n", alternatives are "n2" which involves a different way of scaling the annual indices, "nsmooth" for the gam and gamye models which show only the smooth component of the trajectory, and "nslope" for the slope models which track only the linear slope component of the model startyear Optional first year for which to calculate the annual indices if a trajectory for only the more recent portion of the time series is desired. This is probably most relevant if max_backcast is set and so trajectories for different time-periods could include a different subset of strata (i.e., strata removed) drop_exclude logical indicating if the strata that exceed the max_backcast threshold should be excluded from the calculations, Default is FALSE (regions are flagged and listed but not dropped) max_backcast an optional integer indicating the maximum number of years to backcast the stratum-level estimates before the first year in which the species was observed on any route in that stratum. 5 is used in the CWS national estimates. If the observed data in a given stratum do not include at least one non-zero observation of the species between the first year of the BBS and startyear+max_backcast, the stratum is flagged within the relevant regional summary. Default value, NULL ignores any backcasting limit (i.e., generates annual indices for the entire time series, regardless of when the species was first observed) alt_region_names Optional dataframe indicating the strata to include in a custom spatial summary. Generate the basic dataframe structure with the extract_strata_areas func- tion, then modify with an additional column indicating the strata to include in a custom spatial summary Value List of 6 objects data_summary dataframe with the following columns Year Year of particular index Region Region name Region_alt Long name for region Region_type Type of region including continental, national,Province_State,BCR, bcr_by_country, or stratum Strata_included Strata included in the annual index calculations Strata_excluded Strata potentially excluded from the annual index calculations because they have no observations of the species in the first part of the time series, see arguments max_backcast and startyear Index Strata-weighted count index additional columns for each of the values in quantiles quantiles of the posterior distribution obs_mean Mean of the observed annual counts of birds across all routes and all years. An alternative estimate of the average relative abundance of the species in the region and year. Differences between this and the annual indices are a function of the model. For composite regions (i.e., anything other than stratum-level estimates) this average count is calculated as an area-weighted average across all strata included nrts Number of BBS routes that contributed data for this species, region, and year nrts_total Number of BBS routes that contributed data for this species and region for all years in the selected time-series, i.e., all years since startyear nnzero Number of BBS routes on which this species was observed (i.e., count is > 0) in this region and year backcast_flag approximate annual average proportion of the covered species range that is free of extrapolated population trajectories. e.g., 1.0 = data cover full time-series, 0.75 = data cover 75 percent of time-series. Only calculated if max_backcast != NULL samples array of all posterior draws area-weights data frame of the strata names and area weights used to calculate the continental estimates y_min first year used in the summary, scale 1:length of time-series y_max last year used in the summary, scale 1:length of time-series startyear first year used in the summary, scale 1966:2018 Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a JAGS model. jags_data <- prepare_jags_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2009, max_year = 2018) # Now run a JAGS model. jags_mod <- run_model(jags_data = jags_data, n_adapt = 0, n_burnin = 0, n_iter = 10, n_thin = 1) # Generate the continental and stratum indices indices <- generate_indices(jags_mod = jags_mod, jags_data = jags_data) # Generate only national indices indices_nat <- generate_indices(jags_mod = jags_mod, jags_data = jags_data, regions = c("national")) generate_map Generate a map of trends by strata. Description generate_map allows you to generate a colour-coded map of species trends for each strata. Given trends generated by generate_strata_trends, this function will shade in each stratum based on the percent change in that stratum. Usage generate_map( trend = NULL, select = FALSE, stratify_by = NULL, slope = FALSE, species = "", col_viridis = FALSE ) Arguments trend Dataframe of strata trends produced by generate_strata_trends or generate_regional_trends(... regions = "stratum") select logical flag to indicate if the stratum data need to be selected out of an trends ob- ject that includes continental, national, or other region-types. Default is FALSE stratify_by How were the data stratified? slope Logical, if TRUE, maps values of the alternative trend metric if slope = TRUE was used in generate_strata_trends, the slope of a log-linear regression through the annual indices. Default FALSE. species Text, optional species name to add plot title. if left blank "" no title is added col_viridis Logical flag to use "viridis" colour-blind friendly palette. Default is FALSE Value spplot object Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a JAGS model. jags_data <- prepare_jags_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2009, max_year = 2018) # Now run a JAGS model. jags_mod <- run_model(jags_data = jags_data, n_adapt = 0, n_burnin = 0, n_iter = 10, n_thin = 1) # Generate the continental and stratum indices indices <- generate_indices(jags_mod = jags_mod, jags_data = jags_data) # Now, generate the trends trends <- generate_trends(indices = indices) # Generate the map. Set select = TRUE because we are passing a # dataframe of trends of more than just the stratum regions map <- generate_map(trend = trends, stratify_by = "bbs_cws", select = TRUE, species = "Pacific Wren") generate_trends Generate regional trends continent and strata and optionally for coun- tries, states/provinces, or BCRs from analyses run on the stratifica- tions that support these composite regions Description generate_trends calculates the geometric mean annual changes in population size for composite regions. Usage generate_trends( indices = NULL, Min_year = NULL, Max_year = NULL, quantiles = c(0.025, 0.05, 0.25, 0.75, 0.95, 0.975), slope = FALSE, prob_decrease = NULL, prob_increase = NULL ) Arguments indices regional indices generated by generate_indices Min_year Minimum year to calculate trends from (e.g., 1970). Default is NULL, in which case the trend is calculated from the first year of the time-series of the supplied annual_indices file Max_year Maximum year to calculate trends to (e.g., 2018). Default is NULL, in which case the trend is calculated up to the last year of the time-series of the supplied annual_indices file quantiles vector of quantiles to be sampled from the posterior distribution Defaults to c(0.025,0.05,0.25,0.5,0.75,0.95,0.975) slope Logical, if TRUE, calculates an alternative trend metric, the slope of a log-linear regression through the annual indices. Default FALSE prob_decrease Optional vector of percent-change values to calculate the posterior probabilities that the population has decreased by at least this much (e.g., prob_decrease = c(50) would result in a calculation of the probability that the population has decreased by more than 50 percent over the period of the trend, i.e., less than half the population remains. Default is NULL, in which case no probability of decrease is calculated. prob_increase Optional vector of percent-change values to calculate the posterior probabilities that the population has increased by at least this much (e.g., prob_increase = c(100) would result in a calculation of the probability that the population has incrased by more than 100 percent, i.e., doubled, over the period of the trend. Default is NULL, in which case no probability of increase is calculated. Value Dataframe with one row for each region included in indices object, and columns including: Start_year first year of the trend End_year last year of the trend Region short name of the region Region_alt Long name for region Region_type Type of region including continental, national,Province_State,BCR, bcr_by_national, or stratum Strata_included Strata included in the trend and annual index calculations Strata_excluded Strata potentially excluded from the trend and annual index calculations because they have no observations of the species in the first part of the time series Trend Estimated mean annual percent change over the trend time-period (i.e., Start_year - End_year), according to an endpoint comparison of annual index in Start_year and the annual index in End_year Trend_Q_quantiles quantiles of the posterior distribution of Trend estimates, matching levels in- cluded in the quantiles argument Percent_Change Estimated total percent change over the trend time-period Percent_Change_Q_quantiles quantiles of the posterior distribution of Percent Change estimates, matching levels included in the quantiles argument Slope_Trend Estimated mean annual percent change over the trend time-period, according to the slope of a linear regression through the log-transformed annual indices Slope_Trend_Q_quantiles quantiles of the posterior distribution of Percent Change estimates, matching levels included in the quantiles argument prob_decrease_X_percent proportion of the posterior distribution of Percent_Change that is below the per- centage values supplied in prob_decrease prob_increase_X_percent proportion of the posterior distribution of Percent_Change that is above the per- centage values supplied in prob_increase Relative_Abundance Mean of the annual index values across all years. An estimate of the average relative abundance of the species in the region. Can be interepreted as the pre- dicted average count of the species in an average year on an average route by an average observer, for the years, routes, and observers in the existing data Observed_Relative_Abundance Mean of the observed annual counts of birds across all routes and all years. An alternative estimate of the average relative abundance of the species in the region. For composite regions (i.e., anything other than stratum-level estimates) this average count is calculated as an area-weighted average across all strata included Number_of_Strata The number of strata included in the region Width_of_X_percent_Credible_Interval Width (in percent/year) of the credible interval on the Trend calculation. Calcu- lated for the widest credible interval requested in quantiles argument. Default is 95 percent CI (i.e., Trend_Q0.975 - Trend_Q0.025) Width_of_X_percent_Credible_Interval_Slope Width (in percent/year) of the credible interval on the Trend calculation for the slope-based trend. Calculated for the widest credible interval requested in quantiles argument. Default is 95 percent CI (i.e., Slope_Trend_Q0.975 - Slope_Trend_Q0.025) Number_of_Routes The number of unique BBS routes included in the annual indices for this region and species, i.e., number of routes for this region and species for the years since generate_indices(startyear) Mean_Number_of_Routes The average number of BBS routes across years contributing data for this region and species backcast_flag approximate proportion of the included species range*years that are supported by data in a given region and year, e.g., 1.0 = data cover full time-series, 0.75 = data cover 75 percent of time-series. Only calculated if max_backcast != NULL Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a JAGS model. jags_data <- prepare_jags_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2009, max_year = 2018) # Now run a JAGS model. jags_mod <- run_model(jags_data = jags_data, n_adapt = 0, n_burnin = 0, n_iter = 10, n_thin = 1) # Generate the continental and stratum indices indices <- generate_indices(jags_mod = jags_mod, jags_data = jags_data) # Now, generate the trends trends <- generate_trends(indices = indices) geofacet_plot Generate a geofacet plot of population trajectories by province/state Description geofacet_plot allows you to generate a faceted plot of population trajectories for each strata by province/state. Given a model stratified by "state", "bbs_cws", or "bbs_usgs" and indices generated by generate_strata_indices or generate_regional_indices, this function will generate a faceted plot showing the population trajectories. All geofacet plots have one facet per state/province, so if strata-level indices from the "bbs_cws" or "bbs_usgs" are given, the function plots multiple trajectories (one for each of the relevant strata) within each facet. Usage geofacet_plot( indices_list = NULL, select = FALSE, stratify_by = NULL, ci_width = 0.95, multiple = FALSE, trends = NULL, slope = FALSE, add_observed_means = FALSE, species = "", col_viridis = FALSE ) Arguments indices_list Dataframe of strata or state/province indices produced by generate_strata_indices or generate_regional_indices select logical flag to indicate if the strata_level data need to be selected out of an in- dices_list object that includes stratum, national, or other region-types. Default is FALSE stratify_by How were the data stratified? ci_width quantile to define the width of the plotted credible interval. Defaults to 0.95, lower = 0.025 and upper = 0.975 multiple Logical, if TRUE, multiple strata-level trajectories are plotted within each prov/state facet trends Optional dataframe of matching strata or state/province trends produced by generate_strata_trends or generate_regional_trends. If included trajectories are coloured based on the same colour scale used in generate_map slope Optional Logical, if dataframe of trends is included, colours in the plot are based on slope trends, Default = FALSE add_observed_means Should the facet plots include points indicating the observed mean counts. De- faults to FALSE. Note: scale of observed means and annual indices may not match due to imbalanced sampling among strata species Species name to be added onto the plot col_viridis Logical flag to use "viridis" colour-blind friendly palette. Default is FALSE Value ggplot object Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a JAGS model. jags_data <- prepare_jags_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2009, max_year = 2018) # Now run a JAGS model. jags_mod <- run_model(jags_data = jags_data, n_adapt = 0, n_burnin = 0, n_iter = 10, n_thin = 1) # Generate the stratum indices indices <- generate_indices(jags_mod = jags_mod, jags_data = jags_data, regions = c("stratum")) # Now make the geofacet plot. gp <- geofacet_plot(indices_list = indices, stratify_by = "bbs_cws", species = "Pacific Wren", multiple = TRUE) # There is an unfortunate conflict between geofacet function in the geofacet package # and the S3 +.gg method in other ggplot-extension-packages like ggmcmc # The geofacet_plot function may fail with the following error message: # Error: Don't know how to add e2 to a plot # If this happens, you can fix the problem by following these steps # 1 - save your model output # 2 - restart your R-session # 3 - reload the bbsBayes package (do not re-load the other conflicting package, e.g., ggmcmc) get_composite_regions Get the area of each strata Description get_composite_regions allows you to obtain the dataframe defining the original composite re- gions for a given stratification type. Usage get_composite_regions(strata_type = NULL) Arguments strata_type Stratification type to return the areas of Value Data frame with at least the following variables: region Name of the stratum/region area_sq_km Area of the stratum/region in square kilometres Examples # Obtain the potential composite regions for each of the 5 stratification types # Most useful if the user wishes to create an set of custom composite regions # # USGS BBS st_comp_regions <- get_composite_regions(strata_type = "bbs_usgs") # create new column "Great_Plains" gpall <- rep("Outside",nrow(st_comp_regions)) gp <- which(st_comp_regions$bcr %in% c(11,17,18,19)) gpall[gp] <- "Inside" st_comp_regions$Great_Plains <- gpall # st_comp_regions can now be used as the dataframe input to the argument alt_region_names # in generate_regional_indices, # with "Great_Plains" as the value for the argument region # CWS BBS st_comp_regions <- get_composite_regions(strata_type = "bbs_cws") # BCR st_comp_regions <- get_composite_regions(strata_type = "bcr") # State/Province/Territory st_comp_regions <- get_composite_regions(strata_type = "state") # Degree block st_comp_regions <- get_composite_regions(strata_type = "latlong") get_final_values Get final values of JAGS model Description get_final_values returns the final values of all parameters of the model created by run_model as a list. This function would mostly be used in conjunction with run_model to provide initial values. Usage get_final_values(model = NULL) Arguments model Model object returned by run_model Value List of final values of monitored parameters. Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a JAGS model. jags_data <- prepare_jags_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2009, max_year = 2018) # Now run a JAGS model. For the sake of speed, we've adjusted # some arguments so that the JAGS model will not run any # adaptation steps (n_adapt = 0), no burnin steps (n_burnin = 0), # only 50 iterations per chain (n_iter = 50), and will not # thin the chain (n_thin = 1). This will produce several convergence # warnings, but we can ignore them for the sake of this toy example. jags_mod <- run_model(jags_data = jags_data, n_adapt = 0, n_burnin = 0, n_iter = 10, n_thin = 1) # Get the final values final_values <- get_final_values(model = jags_mod) # Then, we can use these final values as input for another model run jags_mod2 <- run_model(jags_data = jags_data, n_adapt = 0, n_burnin = 0, n_iter = 50, n_thin = 1, inits = final_values) get_mcmc_list Obtain MCMC list from jagsUI object Description get_mcmc_list will return both the mcmc.list object and the sims.list object from jagsUI. mcmc.list is a list of the MCMC samples generated by the rjags library, and sims.list is a vectorized version of mcmc.list produced by the jagsUI library. Usage get_mcmc_list(jags_mod = NULL) Arguments jags_mod JAGS object returned by run_model Value List containing: mcmc_list MCMC samples produced by rjags sims_list Vectorized posterior samples produced by jagsUI Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a JAGS model. jags_data <- prepare_jags_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2009, max_year = 2018) # Now run a JAGS model. For the sake of speed, we've adjusted # some arguments so that the JAGS model will not run any # adaptation steps (n_adapt = 0), no burnin steps (n_burnin = 0), # only 50 iterations per chain (n_iter = 50), and will not # thin the chain (n_thin = 1). This will produce several convergence # warnings, but we can ignore them for the sake of this toy example. jags_mod <- run_model(jags_data = jags_data, n_adapt = 0, n_burnin = 0, n_iter = 10, n_thin = 1) # Now, obtain the MCMC list mcmc_list <- get_mcmc_list(jags_mod = jags_mod) get_prepared_data Get the prepared species dataset used for JAGS Description get_prepared_data returns a data frame of the data that was used for JAGS. This is the subsetted data based on the selected species to model, with zero counts filled in and any other route/strata filter applied. Usage get_prepared_data(jags_data = NULL) Arguments jags_data List of JAGS input data produced by prepare_jags_data Value Data frame of 9 variables: count Number of species observed for this route run strat Numerical factors of the stratum obser Numerical factor of the observer year Numerical factor of the year firstyr 1 if this was the observer’s first year, 0 otherwise strat_name Name of the stratum route Route that this count was taken on rYear Year this count was conducted yearscale Scaled year Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a JAGS model. In this # toy example, we will set the minimum year as 2009 and # maximum year as 2018, effectively only setting up to # model 10 years of data. We will use the "first difference # model. jags_data <- prepare_jags_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2009, max_year = 2018) # Obtain the reassembled data frame for the data sent to JAGS prepped_data <- get_prepared_data(jags_data = jags_data) get_strata_area Get the area of each strata Description get_strata_area allows you to obtain the area of each strata for a given stratification type. Usage get_strata_area(strata_type = NULL) Arguments strata_type Stratification type to return the areas of Value Data frame with the following variables: region Name of the stratum/region area_sq_km Area of the stratum/region in square kilometres Examples # Obtain the strata area for each of the 5 stratification types # USGS BBS st_area <- get_strata_area(strata_type = "bbs_usgs") # CWS BBS st_area <- get_strata_area(strata_type = "bbs_cws") # BCR st_area <- get_strata_area(strata_type = "bcr") # State/Province/Territory st_area <- get_strata_area(strata_type = "state") # Degree block st_area <- get_strata_area(strata_type = "latlong") load_bbs_data Load Breeding Bird Survey dataset into R Session Description load_bbs_data loads the raw, unstratified BBS data into the current R session. The data must have been previously fetched using the fetch_bbs_data function. Note that this function is not necessary to run a Bayesian analysis of BBS data; calling stratify will return stratifed BBS data in a list of data frames. Usage load_bbs_data(level = "state") Arguments level A string, either "state" or "stop", specifying which counts to load. Defaults to "state", which provides counts beginning in 1966, aggregated in five bins, each of which contains cumulative counts from 10 of the 50 stops along a route. Specifying "stop" provides stop-level data beginning in 1997, which includes counts for each stop along routes individually. Note that stop-level data is not currently supported by the modeling utilities in bbsBayes. Value Large list (3 elements) consisting of: bird Data frame of sample bird point count data per route, per year route Data frame of sample yearly route data species Sample list of North American bird species load_map Load a map of of the geographic strata. Description load_map allows you to load a simple features object (sf package) that represents a map of the strata that can be easily plotted. Usage load_map(stratify_by = NULL) Arguments stratify_by How were the data stratified? Value sf polygon object Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_map <- load_map(stratify_by = "bbs_cws") # simple plot of the map plot(strat_map) load_sample_data Load Sample Breeding Bird Survey dataset into R Session Description load_sample_data returns the sample data provided by bbsBayes. The data is returned as a list of data frames, similar to what is returned by load_bbs_data Usage load_sample_data() Value Large list (3 elements) consisting of: bird Data frame of sample bird point count data per route, per year route Data frame of sample yearly route data species Sample list of North American bird species Examples sample_data <- load_sample_data() lppd Calculate log posterior predictive density Description lppd Calculate log posterior preditive density (LPPD) for the supplied model. Usage lppd(jags_data = NULL, jags_mod = NULL, pointwise = FALSE) Arguments jags_data Data prepared by prepare_jags_data, used for input to the JAGS model jags_mod JAGS list generated by run_model pointwise If set to TRUE, a data frame is returned that contains the pointwise LPPD for each count. Defaults to FALSE Details NOTE: in order to calculated LPPD, the model MUST track the parameter "lambda". In species that are data-rich, such as Wood Thrush, this produces extremely large JAGS objects, and takes up a considerable amount of memory when simulating with run_model Value Data frame of pointwise LPPD by count if pointwise is set to TRUE. Double precision numerical value of LPPD if pointwise is set to FALSE. Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a JAGS model. jags_data <- prepare_jags_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2014, max_year = 2018) # Now run a JAGS model. Make sure to track the lambda parameter here jags_mod <- run_model(jags_data = jags_data, n_adapt = 0, n_burnin = 0, n_iter = 5, n_thin = 1, parameters_to_save = c("n", "lambda")) # Output LPPD lppd(jags_data = jags_data, jags_mod = jags_mod) model_to_file Save model to text file Description model_to_file allows you to save any of the preloaded hierarchical Bayesian models to a text file. Usage model_to_file(model = NULL, filename = NULL, heavy_tailed = FALSE) Arguments model Model to be saved. Options are "slope", "firstdiff", "gam", "gamye" filename File name to create on disk. heavy_tailed Logical indicating whether the extra-Poisson error distribution should be mod- eled as a t-distribution, with heavier tails than the standard normal distribution. Default is currently FALSE, but recent results suggest users should strongly consider setting this to TRUE, even though it requires much longer convergence times Value None Examples # Save the Slope model to a file called "slope.txt" in temp directory model_to_file(model = "slope", filename = file.path(tempdir(), "slope.txt")) # Save the First Difference model to a file called "fd.txt" in temp directory model_to_file(model = "firstdiff", filename = file.path(tempdir(), "fd.txt")) # Save the GAM model to a file called "gam.txt" in temp directory model_to_file(model = "gam", filename = file.path(tempdir(), "gam.txt")) # Save the GAM year effects model to a file called "gamye.txt" in temp directory model_to_file(model = "gamye", filename = file.path(tempdir(), "gamye.txt")) plot_indices Generate plots of index trajectories by stratum Description Generates the indices plot for each stratum modelled. Usage plot_indices( indices_list = NULL, ci_width = 0.95, min_year = NULL, max_year = NULL, species = "", title_size = 20, axis_title_size = 18, axis_text_size = 16, line_width = 1, add_observed_means = FALSE, add_number_routes = FALSE ) Arguments indices_list List of indices of annual abundance and other results produced by generate_strata_indices ci_width quantile to define the width of the plotted credible interval. Defaults to 0.95, lower = 0.025 and upper = 0.975 min_year Minimum year to plot max_year Maximum year to plot species Species name to be added onto the plot title_size Specify font size of plot title. Defaults to 20 axis_title_size Specify font size of axis titles. Defaults to 18 axis_text_size Specify font size of axis text. Defaults to 16 line_width Specify the size of the trajectory line. Defaults to 1 add_observed_means Should the plot include points indicated the observed mean counts. Defaults to FALSE. Note: scale of observed means and annual indices may not match due to imbalanced sampling among routes add_number_routes Should the plot be superimposed over a dotplot showing the number of BBS routes included in each year. This is useful as a visual check on the relative data-density through time because in most cases the number of observations increases over time Value List of ggplot objects, each entry being a plot of a stratum indices Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a JAGS model. jags_data <- prepare_jags_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2009, max_year = 2018) # Now run a JAGS model. jags_mod <- run_model(jags_data = jags_data, n_adapt = 0, n_burnin = 0, n_iter = 10, n_thin = 1) # Generate only national, continental, and stratum indices indices <- generate_indices(jags_mod = jags_mod, jags_data = jags_data, regions = c("national", "continental", "stratum")) # Now, plot_indices() will generate a list of plots for all regions plot_list <- plot_indices(indices_list = indices, species = "Pacific Wren") #Suppose we wanted to access the continental plot. We could do so with cont_plot <- plot_list$continental # You can specify to only plot a subset of years using min_year and max_year # Plots indices from 2015 onward plot_list_2015_on <- plot_indices(indices_list = indices, min_year = 2015, species = "Pacific Wren") #Plot up indices up to the year 2017 plot_list_max_2017 <- plot_indices(indices_list = indices, max_year = 2017, species = "Pacific Wren") #Plot indices between 2011 and 2016 plot_list_2011_2015 <- plot_indices(indices_list = indices, min_year = 2011, max_year = 2016, species = "Pacific Wren") prepare_data Wrangle data to use for modelling input Description prepare_data subsets raw BBS data by selected species and and wrangles stratified data for use as input for models. Usage prepare_data( strat_data = NULL, species_to_run = NULL, model = NULL, heavy_tailed = FALSE, n_knots = NULL, min_year = NULL, max_year = NULL, min_n_routes = 3, min_max_route_years = 3, min_mean_route_years = 1, strata_rem = NULL, quiet = FALSE, sampler = "jags", basis = "original", ... ) Arguments strat_data Large list of stratified data returned by stratify() species_to_run Character string of the English name of the species to run model Character string of model to be used. Options are "slope", "firstdiff", "gam", "gamye. heavy_tailed Logical indicating whether the extra-Poisson error distribution should be mod- eled as a t-distribution, with heavier tails than the standard normal distribution. Default is currently FALSE, but recent results suggest users should strongly consider setting this to TRUE, even though it requires much longer convergence times n_knots Number of knots to be used in GAM function min_year Minimum year to keep in analysis max_year Maximum year to keep in analysis min_n_routes Minimum routes per strata where species has been observed. Defaults to 3 min_max_route_years Minimum number of years with non-zero observations of species on at least 1 route. Defaults to 3 min_mean_route_years Minimum average of years per route with the species observed. Defaults to 1. strata_rem Strata to remove from analysis. Defaults to NULL quiet Should progress bars be suppressed? sampler Which MCMC sampling software to use. Currently bbsBayes only supports "jags". basis Which version of the basis-function to use for the GAM smooth, the default is "original" the same basis used in Smith and Edwards 2020 and "mgcv" is an alternate that uses the "tp" basis from the packages mgcv (also used in brms, and rstanarm). If using the "mgcv" option, the user may want to consider adjusting the prior distributions for the parameters and their precision ... Additional arguments Value List of data to be used for modelling, including: model The model to be used heavy_tailed Logical indicating whether the extra-Poisson error distribution should be mod- eled as a t-distribution min_nu if heavy_tailed is TRUE, minimum value for truncated gamma on DF of t- distribution noise default is 0 and user must change manually after function is run ncounts The number of counts containing useful data for the species nstrata The number of strata used in the analysis ymin Minimum year used ymax Maximum year used nonzeroweight Proportion of routes in each strata with species obervation count Vector of counts for the species strat Vector of strata to be used in the analysis obser Vector of unique observer-route pairings year Vector of years for each count firstyr Vector of indicator variables as to whether an observer was a first year month vector of numeric month of observation day vector of numeric day of observation nobservers Total number of observer-route pairings fixedyear Median of all years (ymin:ymax), included only with slope and firstdiff models nknots Number of knots to use for smooting functions, included only with GAM X.basis Basis function for n smoothing functions, included only with GAM Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a model. In this # toy example, we will set the minimum year as 2009 and # maximum year as 2018, effectively only setting up to # model 10 years of data. We will use the "first difference # model. model_data <- prepare_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2009, max_year = 2018) # You can also specify the GAM model, with an optional number of # knots to use for the GAM basis. # By default, the number of knots will be equal to the floor # of the total unique years for the species / 4 model_data <- prepare_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "gam", n_knots = 9) route_sample Sample route data per year run (Pacific Wren only) Description A dataset containing data for each route run per year. NOTE: This only contains data for Pacific Wren, not the full data set. The full count set is obtained via the function fetch_bbs_data. The data is obtained from the United States Geological Survey and is subject to change as new data is added each year. See Details for citation. Usage route_sample Format A data frame with 20 rows and 32 variables: countrynum Numerical representation of the country statenum Numerical representation of state or province Route Numerican representation of the route the species was observed RouteName Name of the route, represented as a string Active Boolean 0 or 1 as to whether the route is currently active Latitude Latitude of the start of the route Longitude Longitude of the start of the route BCR What bird conservation region is the route in RouteTypeID Type of the route, only 1 is acceptable RouteTypeDetailID Route type detail ID RouteDataID Unique code for each year a route was run RPID Run Protocol ID Year Year the route was run Month Month the route was run Day Day the route was run ObsN Unique number for the observer on the route TotalSpp Total species observed on the route StartTemp Temperature at the start of the route EndTemp Temperature at the end of the route TempScale (C)elsius or (F)arenheit StartWind Wind type at the beginning of the route EndWind Wind type at the end of the route StartSky Sky conditions at the start of the route EndSky Sky conditions at the end of the route StartTime Time the route was started EndTime Time the route was ended Assistant Boolean 0 or 1 as to whether an assistant was used QualityCurrentID Quality current ID RunType Type of BBS route run. Only acceptable run type is 1 State String representation of state or province St_Abrev Abbreviated state or province Country Abbreviated country Details <NAME>., <NAME>., <NAME>, <NAME> and <NAME>. 2019. North American Breeding Bird Survey Dataset 1966 - 2018, version 2018.0. U.S. Geological Survey, Patuxent Wildlife Research Center. https://doi.org/10.5066/P9HE8XYJ. run_model Run JAGS model for prepared species data Description run-model runs a JAGS model as specified by the user for the species of interest Usage run_model( jags_data = NULL, model_file_path = NULL, inits = NULL, parameters_to_save = c("n"), track_n = TRUE, n_chains = 3, n_adapt = NULL, n_burnin = 20000, n_thin = 10, n_saved_steps = 2000, n_iter = 10000, parallel = FALSE, n_cores = NULL, quiet = FALSE, modules = NULL, ... ) Arguments jags_data List or environment containing the data to model, as output by prepare_jags_data model_file_path Path to custom model. Overrides the model variable set by prepare_jags_data inits Optional list of initialization values for JAGS model. If none are specified, the JAGS model will generate its own initial values. parameters_to_save Character vector of parameters to monitor in JAGS. Defaults to just monitoring "n" track_n By default, the parameter "n" will always be tracked, even if the user forgets to specify it. However, if the user is positive they do not want to track "n", this parameter can be be set to FALSE. NOTE: you will not be able to generate annual indices if "n" is not tracked. n_chains Optional number of chains to run. Defaults to 3. n_adapt Optional integer specifying the number of steps to adapt the JAGS model. The default is NULL, which will result in the function running groups of 100 adapta- tion iterations (to amax of 10,000) until JAGS reports adaptation is sufficient. If you set it manually, 1000 is the recommended minimum value. n_burnin Optional integer specifying the number of iterations to burn in the model. De- faults to 20000 per chain. n_thin Optional number of steps to thin or discard. n_saved_steps Optional number of steps to save per chain. Defaults to 2000. n_iter Optional number of iterations per chain. Defaults to 10000. parallel Should each chain be run parallel on separate cores? n_cores Number of cores to use if running in parallel. If NULL (default), and parallel = TRUE, the number of cores used will be the minimum of the n_chains specified and the number of cores on your computer quiet Should JAGS output be suppressed? modules Character vector of JAGS modules to load before analysis. By default no extra modules are loaded (other than ’basemod’ and ’bugs’). To force glm or other modules to load, use modules = "glm". Be warned, our experience suggests that including the glm module may cause problems with the BBS data. ... Additional arguments Value jagsUI object Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a JAGS model. jags_data <- prepare_jags_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2009, max_year = 2018) # Now run a JAGS model. For the sake of speed, we've adjusted # some arguments so that the JAGS model will not run any # adaptation steps (n_adapt = 0), no burnin steps (n_burnin = 0), # only 50 iterations per chain (n_iter = 50), and will not # thin the chain (n_thin = 1). This will produce several convergence # warnings, but we can ignore them for the sake of this toy example. jags_mod <- run_model(jags_data = jags_data, n_adapt = 0, n_burnin = 0, n_iter = 10, n_thin = 1, parameters_to_save = c("n", "strata")) r_hat Generate Gelman-Rubin’s R-Hat statistic Description r_hat returns a dataframe of Gelman-Rubin’s R-hat statistics for each parameter tracked in the model. Usage r_hat(jags_mod = NULL, parameter_list = NULL, threshold = NULL) Arguments jags_mod JAGS list generated by run_model parameter_list Optional list of parameters to subset threshold Return only r-hat values greater than OR equal to this threshold (floating point value) Details R-hat, also known as the potential scale reduction factor (PSRF) was described by Gelman & Rubin (1992) as a way of calculating convergence of parameters given 2 or more chains. See citation below for details. Gelman, Andrew; <NAME>. Inference from Iterative Simulation Using Multiple Sequences. Statist. Sci. 7 (1992), no. 4, 457–472. doi:10.1214/ss/1177011136. https://projecteuclid.org/euclid.ss/1177011136 Value Dataframe consisting of r-hat values per parameter. Examples # Toy example with Pacific Wren sample data # First, stratify the sample data strat_data <- stratify(by = "bbs_cws", sample_data = TRUE) # Prepare the stratified data for use in a JAGS model. jags_data <- prepare_jags_data(strat_data = strat_data, species_to_run = "Pacific Wren", model = "firstdiff", min_year = 2009, max_year = 2018) # Now run a JAGS model. jags_mod <- run_model(jags_data = jags_data, n_adapt = 0, n_burnin = 0, n_iter = 10, n_thin = 1, parameters_to_track = c("n","strata")) # Check convergence for all parameters convergence <- r_hat(jags_mod = jags_mod) # Check convergence for only subset of parameters convergence <- r_hat(jags_mod = jags_mod, parameter_list = "strata") # Only return R Hat values greater than or equal to specified value convergence <- r_hat(jags_mod = jags_mod, threshold = 1.1) species_sample Sample North American bird species list (Pacific Wren only) Description A dataset containing species list of North America. NOTE: This only contains data for Pacific Wren, not the full data set. The full count set is obtained via the function fetch_bbs_data. The data is obtained from the United States Geological Survey and is subject to change as new data is added each year. See Details for citation. Usage species_sample Format A data frame with 20 rows and 10 variables: seq Sequence - USGS use aou Numerical representation of the species, designated by American Ornithological Union english Species name in English order Taxonomic order family Taxonomic family genus Taxonomic genus species Taxonomic species sp.bbs Same as aou, no leading 0 Details <NAME>., <NAME>., <NAME>, <NAME> and <NAME>. 2019. North American Breeding Bird Survey Dataset 1966 - 2018, version 2018.0. U.S. Geological Survey, Patuxent Wildlife Research Center. https://doi.org/10.5066/P9HE8XYJ. stratify Stratify raw Breeding Bird Survey data Description Assigns each bird count data point and each route a strata based on its geographic location and the stratification as specified by the user. Usage stratify( by = NULL, sample_data = FALSE, bbs_data = NULL, lump_species_forms = TRUE, quiet = FALSE, stratify_by = NULL ) Arguments by String argument of stratification type. Options are "state", "bcr", "latlong", "bbs_cws", "bbs_usgs" sample_data Should just sample data (just Pacific Wren) be used? Defaults to FALSE. bbs_data Raw BBS data saved as a list of 3 data frames. Not necessary if you have already run fetch_bbs_data lump_species_forms Logical, default is TRUE, indicating that for species with multiple forms, the "unidentified" form is replaced by the sum of observations for all forms (in- cluding the original unidentified obs). The underlying BBS database includes separate data for each form, and these separate forms are retained with their original names. The original unidentified category for observations that were not specific to a particular form are replaced by the combined observations. If the user wishes to keep the unidentified form separate, this can be set to FALSE quiet Should progress bars be suppressed? stratify_by Deprecated in favour of ’by’ Value Large list (3 elements) consisting of: bird_strat Dataframe of stratified bird data route_strat Dataframe of stratified route data species_strat Dataframe of stratified species data by Argument used for stratification Examples # Toy examples using Pacific Wren sample data # Stratify by CWS USGS stratifications data_strat <- stratify(by = "bbs_usgs", sample_data = TRUE) # Stratify by Bird Conservation Regions only data_strat <- stratify(by = "bcr", sample_data = TRUE) # Stratify by CWS BBS stratifications data_strat <- stratify(by = "bbs_cws", sample_data = TRUE) # Stratify by State/Province/Territory only data_strat <- stratify(by = "state", sample_data = TRUE) # Stratify by blocks of 1 degree of latitude X 1 degree of longitude data_strat <- stratify(by = "latlong", sample_data = TRUE) # To stratify the entire dataset, simply set the sample_data = FALSE, # or drop that argument altogher. The function then requires fetch_bbs_data() # to have been run (takes about 10 minutes). Stratification of the entire dataset # may take up to 3 minutes.
netlink-packet-audit
rust
Rust
Struct netlink_packet_audit::AuditBuffer === ``` #[non_exhaustive]pub struct AuditBuffer<T> { /* private fields */ } ``` Implementations --- ### impl<T: AsRef<[u8]>> AuditBuffer<T#### pub fn new(buffer: T) -> AuditBuffer<T#### pub fn length(&self) -> usize #### pub fn new_checked(buffer: T) -> Result<AuditBuffer<T>, DecodeError### impl<'a, T: AsRef<[u8]> + ?Sized> AuditBuffer<&'a T#### pub fn inner(&self) -> &'a [u8] ### impl<'a, T: AsRef<[u8]> + AsMut<[u8]> + ?Sized> AuditBuffer<&'a mut T#### pub fn inner_mut(&mut self) -> &mut [u8] Trait Implementations --- ### impl<'a, T: AsRef<[u8]> + ?Sized> ParseableParametrized<AuditBuffer<&'a T>, u16> for AuditMessage #### fn parse_with_param( buf: &AuditBuffer<&'a T>, message_type: u16 ) -> Result<Self, DecodeErrorDeserialize the current type.Auto Trait Implementations --- ### impl<T> RefUnwindSafe for AuditBuffer<T>where T: RefUnwindSafe, ### impl<T> Send for AuditBuffer<T>where T: Send, ### impl<T> Sync for AuditBuffer<T>where T: Sync, ### impl<T> Unpin for AuditBuffer<T>where T: Unpin, ### impl<T> UnwindSafe for AuditBuffer<T>where T: UnwindSafe, Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"&'a [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct netlink_packet_audit::NetlinkAuditCodec === ``` #[non_exhaustive]pub struct NetlinkAuditCodec { /* private fields */ } ``` audit specific implementation of `NetlinkMessageCodec` due to the protocol violations in messages generated by kernal audit. Among the known bugs in kernel audit messages: * `nlmsg_len` sometimes contains the padding too (it shouldn’t) * `nlmsg_len` sometimes doesn’t contain the header (it really should) See also: * https://blog.des.no/2020/08/netlink-auditing-and-counting-bytes/ * https://github.com/torvalds/linux/blob/b5013d084e03e82ceeab4db8ae8ceeaebe76b0eb/kernel/audit.c#L2386 * https://github.com/mozilla/libaudit-go/issues/24 * https://github.com/linux-audit/audit-userspace/issues/78 Trait Implementations --- ### impl NetlinkMessageCodec for NetlinkAuditCodec #### fn decode<T>(src: &mut BytesMut) -> Result<Option<NetlinkMessage<T>>>where T: NetlinkDeserializable + Debug, Decode message of given type from datagram payload T: Debug + NetlinkSerializable, Encode message to (datagram) bufferAuto Trait Implementations --- ### impl RefUnwindSafe for NetlinkAuditCodec ### impl Send for NetlinkAuditCodec ### impl Sync for NetlinkAuditCodec ### impl Unpin for NetlinkAuditCodec ### impl UnwindSafe for NetlinkAuditCodec Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum netlink_packet_audit::AuditMessage === ``` #[non_exhaustive]pub enum AuditMessage { GetStatus(Option<StatusMessage>), SetStatus(StatusMessage), AddRule(RuleMessage), DelRule(RuleMessage), ListRules(Option<RuleMessage>), Event((u16, String)), Other((u16, String)), } ``` Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### GetStatus(Option<StatusMessage>) ### SetStatus(StatusMessage) ### AddRule(RuleMessage) ### DelRule(RuleMessage) ### ListRules(Option<RuleMessage>) ### Event((u16, String)) Event message (message types 1300 through 1399). This includes the following message types (this list is non-exhaustive, and not really kept up to date): `AUDIT_SYSCALL`, `AUDIT_PATH`, `AUDIT_IPC`, `AUDIT_SOCKETCALL`, `AUDIT_CONFIG_CHANGE`, `AUDIT_SOCKADDR`, `AUDIT_CWD`, `AUDIT_EXECVE`, `AUDIT_IPC_SET_PERM`, `AUDIT_MQ_OPEN`, `AUDIT_MQ_SENDRECV`, `AUDIT_MQ_NOTIFY`, `AUDIT_MQ_GETSETATTR`, `AUDIT_KERNEL_OTHER`, `AUDIT_FD_PAIR`, `AUDIT_OBJ_PID`, `AUDIT_TTY`, `AUDIT_EOE`, `AUDIT_BPRM_FCAPS`, `AUDIT_CAPSET`, `AUDIT_MMAP`, `AUDIT_NETFILTER_PKT`, `AUDIT_NETFILTER_CFG`, `AUDIT_SECCOMP`, `AUDIT_PROCTITLE`, `AUDIT_FEATURE_CHANGE`, `AUDIT_REPLACE`, `AUDIT_KERN_MODULE`, `AUDIT_FANOTIFY`. The first element of the tuple is the message type, and the second is the event data. ### Other((u16, String)) All the other events are parsed as such as they can be parsed also. Implementations --- ### impl AuditMessage #### pub fn is_event(&self) -> bool #### pub fn is_get_status(&self) -> bool #### pub fn is_set_status(&self) -> bool #### pub fn is_add_rule(&self) -> bool #### pub fn is_del_rule(&self) -> bool #### pub fn is_list_rules(&self) -> bool #### pub fn message_type(&self) -> u16 Trait Implementations --- ### impl Clone for AuditMessage #### fn clone(&self) -> AuditMessage Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn buffer_len(&self) -> usize Return the length of the serialized data.#### fn emit(&self, buffer: &mut [u8]) Serialize this types and write the serialized data into the given buffer. Converts to this type from the input type.### impl NetlinkDeserializable for AuditMessage #### type Error = DecodeError #### fn deserialize( header: &NetlinkHeader, payload: &[u8] ) -> Result<Self, Self::ErrorDeserialize the given buffer into `Self`.### impl NetlinkSerializable for AuditMessage #### fn message_type(&self) -> u16 #### fn buffer_len(&self) -> usize Return the length of the serialized data. Serialize this types and write the serialized data into the given buffer. `buffer`’s length is exactly `InnerMessage::buffer_len()`. It means that if `InnerMessage::buffer_len()` is buggy and does not return the appropriate length, bad things can happen: #### fn parse_with_param( buf: &AuditBuffer<&'a T>, message_type: u16 ) -> Result<Self, DecodeErrorDeserialize the current type.### impl PartialEq<AuditMessage> for AuditMessage #### fn eq(&self, other: &AuditMessage) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Eq for AuditMessage ### impl StructuralEq for AuditMessage ### impl StructuralPartialEq for AuditMessage Auto Trait Implementations --- ### impl RefUnwindSafe for AuditMessage ### impl Send for AuditMessage ### impl Sync for AuditMessage ### impl Unpin for AuditMessage ### impl UnwindSafe for AuditMessage Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.
serpy
readthedoc
Python
serpy 0.3.1 documentation [serpy](index.html#document-index) --- serpy: ridiculously fast object serialization[¶](#serpy-ridiculously-fast-object-serialization) === **serpy** is a super simple object serialization framework built for speed. **serpy** serializes complex datatypes (Django Models, custom classes, ...) to simple native types (dicts, lists, strings, ...). The native types can easily be converted to JSON or any other format needed. The goal of **serpy** is to be able to do this *simply*, *reliably*, and *quickly*. Since serializers are class based, they can be combined, extended and customized with very little code duplication. Compared to other popular Python serialization frameworks like [marshmallow](http://marshmallow.readthedocs.org) or [Django Rest Framework Serializers](http://www.django-rest-framework.org/api-guide/serializers/) **serpy** is at least an [order of magnitude](http://serpy.readthedocs.org/en/latest/performance.html) faster. Source[¶](#source) --- Source at: <https://github.com/clarkduvall/serpyIf you want a feature, send a pull request! Documentation[¶](#documentation) --- Full documentation at: <http://serpy.readthedocs.org/en/latest/Installation[¶](#installation) --- ``` $ pip install serpy ``` Examples[¶](#examples) --- ### Simple Example[¶](#simple-example) ``` import serpy class Foo(object): """The object to be serialized.""" y = 'hello' z = 9.5 def __init__(self, x): self.x = x class FooSerializer(serpy.Serializer): """The serializer schema definition.""" # Use a Field subclass like IntField if you need more validation. x = serpy.IntField() y = serpy.Field() z = serpy.Field() f = Foo(1) FooSerializer(f).data # {'x': 1, 'y': 'hello', 'z': 9.5} fs = [Foo(i) for i in range(100)] FooSerializer(fs, many=True).data # [{'x': 0, 'y': 'hello', 'z': 9.5}, {'x': 1, 'y': 'hello', 'z': 9.5}, ...] ``` ### Nested Example[¶](#nested-example) ``` import serpy class Nestee(object): """An object nested inside another object.""" n = 'hi' class Foo(object): x = 1 nested = Nestee() class NesteeSerializer(serpy.Serializer): n = serpy.Field() class FooSerializer(serpy.Serializer): x = serpy.Field() # Use another serializer as a field. nested = NesteeSerializer() f = Foo() FooSerializer(f).data # {'x': 1, 'nested': {'n': 'hi'}} ``` ### Complex Example[¶](#complex-example) ``` import serpy class Foo(object): y = 1 z = 2 super_long_thing = 10 def x(self): return 5 class FooSerializer(serpy.Serializer): w = serpy.Field(attr='super_long_thing') x = serpy.Field(call=True) plus = serpy.MethodField() def get_plus(self, obj): return obj.y + obj.z f = Foo() FooSerializer(f).data # {'w': 10, 'x': 5, 'plus': 3} ``` ### Inheritance Example[¶](#inheritance-example) ``` import serpy class Foo(object): a = 1 b = 2 class ASerializer(serpy.Serializer): a = serpy.Field() class ABSerializer(ASerializer): """ABSerializer inherits the 'a' field from ASerializer. This also works with multiple inheritance and mixins. """ b = serpy.Field() f = Foo() ASerializer(f).data # {'a': 1} ABSerializer(f).data # {'a': 1, 'b': 2} ``` License[¶](#license) --- serpy is free software distributed under the terms of the MIT license. See the [LICENSE](https://github.com/clarkduvall/serpy/blob/master/LICENSE) file. Contents: ### API Reference[¶](#api-reference) #### Serializer[¶](#serializer) *class* `serpy.``Serializer`(*instance=None*, *many=False*, *data=None*, *context=None*, ***kwargs*)[[source]](_modules/serpy/serializer.html#Serializer)[¶](#serpy.Serializer) [`Serializer`](#serpy.Serializer) is used as a base for custom serializers. The [`Serializer`](#serpy.Serializer) class is also a subclass of [`Field`](#serpy.Field), and can be used as a [`Field`](#serpy.Field) to create nested schemas. A serializer is defined by subclassing [`Serializer`](#serpy.Serializer) and adding each [`Field`](#serpy.Field) as a class variable: Example: ``` class FooSerializer(Serializer): foo = Field() bar = Field() foo = Foo(foo='hello', bar=5) FooSerializer(foo).data # {'foo': 'hello', 'bar': 5} ``` | Parameters: | * **instance** – The object or objects to serialize. * **many** (*bool*) – If `instance` is a collection of objects, set `many` to `True` to serialize to a list. * **context** – Currently unused parameter for compatability with Django REST Framework serializers. | `data`[¶](#serpy.Serializer.data) Get the serialized data from the [`Serializer`](#serpy.Serializer). The data will be cached for future accesses. `default_getter`[¶](#serpy.Serializer.default_getter) The default getter used if [`Field.as_getter()`](#serpy.Field.as_getter) returns None. alias of `attrgetter` *class* `serpy.``DictSerializer`(*instance=None*, *many=False*, *data=None*, *context=None*, ***kwargs*)[[source]](_modules/serpy/serializer.html#DictSerializer)[¶](#serpy.DictSerializer) [`DictSerializer`](#serpy.DictSerializer) serializes python `dicts` instead of objects. Instead of the serializer’s fields fetching data using `operator.attrgetter`, [`DictSerializer`](#serpy.DictSerializer) uses `operator.itemgetter`. Example: ``` class FooSerializer(DictSerializer): foo = IntField() bar = FloatField() foo = {'foo': '5', 'bar': '2.2'} FooSerializer(foo).data # {'foo': 5, 'bar': 2.2} ``` `default_getter`[¶](#serpy.DictSerializer.default_getter) alias of `itemgetter` #### Fields[¶](#fields) If none of these fields fit your needs, **serpy** makes it simple to create custom fields. See the [Custom Fields](custom-fields.html) documentation. *class* `serpy.``Field`(*attr=None*, *call=False*, *label=None*, *required=True*)[[source]](_modules/serpy/fields.html#Field)[¶](#serpy.Field) [`Field`](#serpy.Field) is used to define what attributes will be serialized. A [`Field`](#serpy.Field) maps a property or function on an object to a value in the serialized result. Subclass this to make custom fields. For most simple cases, overriding [`Field.to_value()`](#serpy.Field.to_value) should give enough flexibility. If more control is needed, override [`Field.as_getter()`](#serpy.Field.as_getter). | Parameters: | * **attr** (*str*) – The attribute to get on the object, using the same format as `operator.attrgetter`. If this is not supplied, the name this field was assigned to on the serializer will be used. * **call** (*bool*) – Whether the value should be called after it is retrieved from the object. Useful if an object has a method to be serialized. * **label** (*str*) – A label to use as the name of the serialized field instead of using the attribute name of the field. * **required** (*bool*) – Whether the field is required. If set to `False`, [`Field.to_value()`](#serpy.Field.to_value) will not be called if the value is `None`. | `as_getter`(*serializer_field_name*, *serializer_cls*)[[source]](_modules/serpy/fields.html#Field.as_getter)[¶](#serpy.Field.as_getter) Returns a function that fetches an attribute from an object. Return `None` to use the default getter for the serializer defined in [`Serializer.default_getter`](#serpy.Serializer.default_getter). When a [`Serializer`](#serpy.Serializer) is defined, each [`Field`](#serpy.Field) will be converted into a getter function using this method. During serialization, each getter will be called with the object being serialized, and the return value will be passed through [`Field.to_value()`](#serpy.Field.to_value). If a [`Field`](#serpy.Field) has `getter_takes_serializer = True`, then the getter returned from this method will be called with the [`Serializer`](#serpy.Serializer) instance as the first argument, and the object being serialized as the second. | Parameters: | * **serializer_field_name** (*str*) – The name this field was assigned to on the serializer. * **serializer_cls** – The [`Serializer`](#serpy.Serializer) this field is a part of. | `getter_takes_serializer` *= False*[¶](#serpy.Field.getter_takes_serializer) Set to `True` if the value function returned from [`Field.as_getter()`](#serpy.Field.as_getter) requires the serializer to be passed in as the first argument. Otherwise, the object will be the only parameter. `to_value`(*value*)[[source]](_modules/serpy/fields.html#Field.to_value)[¶](#serpy.Field.to_value) Transform the serialized value. Override this method to clean and validate values serialized by this field. For example to implement an `int` field: ``` def to_value(self, value): return int(value) ``` | Parameters: | **value** – The value fetched from the object being serialized. | *class* `serpy.``StrField`(*attr=None*, *call=False*, *label=None*, *required=True*)[[source]](_modules/serpy/fields.html#StrField)[¶](#serpy.StrField) A [`Field`](#serpy.Field) that converts the value to a string. `to_value`[¶](#serpy.StrField.to_value) alias of `unicode` *class* `serpy.``IntField`(*attr=None*, *call=False*, *label=None*, *required=True*)[[source]](_modules/serpy/fields.html#IntField)[¶](#serpy.IntField) A [`Field`](#serpy.Field) that converts the value to an integer. `to_value`[¶](#serpy.IntField.to_value) alias of `int` *class* `serpy.``FloatField`(*attr=None*, *call=False*, *label=None*, *required=True*)[[source]](_modules/serpy/fields.html#FloatField)[¶](#serpy.FloatField) A [`Field`](#serpy.Field) that converts the value to a float. `to_value`[¶](#serpy.FloatField.to_value) alias of `float` *class* `serpy.``BoolField`(*attr=None*, *call=False*, *label=None*, *required=True*)[[source]](_modules/serpy/fields.html#BoolField)[¶](#serpy.BoolField) A [`Field`](#serpy.Field) that converts the value to a boolean. `to_value`[¶](#serpy.BoolField.to_value) alias of `bool` *class* `serpy.``MethodField`(*method=None*, ***kwargs*)[[source]](_modules/serpy/fields.html#MethodField)[¶](#serpy.MethodField) A [`Field`](#serpy.Field) that calls a method on the [`Serializer`](#serpy.Serializer). This is useful if a [`Field`](#serpy.Field) needs to serialize a value that may come from multiple attributes on an object. For example: ``` class FooSerializer(Serializer): plus = MethodField() minus = MethodField('do_minus') def get_plus(self, foo_obj): return foo_obj.bar + foo_obj.baz def do_minus(self, foo_obj): return foo_obj.bar - foo_obj.baz foo = Foo(bar=5, baz=10) FooSerializer(foo).data # {'plus': 15, 'minus': -5} ``` | Parameters: | **method** (*str*) – The method on the serializer to call. Defaults to `'get_<field name>'`. | ### Custom Fields[¶](#custom-fields) The most common way to create a custom field with **serpy** is to override [`serpy.Field.to_value()`](index.html#serpy.Field.to_value). This method is called on the value retrieved from the object being serialized. For example, to create a field that adds 5 to every value it serializes, do: ``` class Add5Field(serpy.Field): def to_value(self, value): return value + 5 ``` Then to use it: ``` class Obj(object): pass class ObjSerializer(serpy.Serializer): foo = Add5Field() f = Obj() f.foo = 9 ObjSerializer(f).data # {'foo': 14} ``` Another use for custom fields is data validation. For example, to validate that every serialized value has a `'.'` in it: ``` class ValidateDotField(serpy.Field): def to_value(self, value): if '.' not in value: raise ValidationError('no dot!') return value ``` For more control over the behavior of the field, override [`serpy.Field.as_getter()`](index.html#serpy.Field.as_getter). When the [`serpy.Serializer`](index.html#serpy.Serializer) class is created, each field will be compiled to a getter, that will be called to get its associated attribute from the object. For an example of this, see the [`serpy.MethodField()`](index.html#serpy.MethodField) implementation. ### Performance Benchmarks[¶](#performance-benchmarks) **serpy** was compared against two other popular serializer frameworks: > * [marshmallow](http://marshmallow.readthedocs.org) > * [Django Rest Framework Serializers](http://www.django-rest-framework.org/api-guide/serializers/) These graphs show the results. The benchmark scripts are found in the [benchmarks](https://github.com/clarkduvall/serpy/tree/master/benchmarks) directory in the **serpy** [GitHub repository](https://github.com/clarkduvall/serpy). Run these benchmarks yourself with: ``` $ git clone https://github.com/clarkduvall/serpy.git && cd serpy $ tox -e benchmarks ``` #### Results[¶](#results) These benchmarks were run on a Lenovo T530 with a 2-core 2.5 GHz i5 processor and 8G of memory. ##### Simple Benchmark[¶](#simple-benchmark) This benchmark serializes simple objects that have a single field. ##### Complex Benchmark[¶](#complex-benchmark) This benchmark serializes nested objects with multiple fields of different types. ##### Data[¶](#data) bm_simple.py time taken (in seconds)[¶](#id1) | # objects | Django Rest Framework | marshmallow | serpy | | --- | --- | --- | --- | | 10000 | 0.2414798737 | 0.1281440258 | 0.006773948669 | | 20000 | 0.4704430103 | 0.2609949112 | 0.01343297958 | | 30000 | 0.7049410343 | 0.3850591183 | 0.02005600929 | | 40000 | 0.9448800087 | 0.5248949528 | 0.02748799324 | | 50000 | 1.196242809 | 0.6589410305 | 0.03510689735 | | 60000 | 1.513856888 | 0.8019201756 | 0.04155898094 | | 70000 | 1.695443153 | 0.9703800678 | 0.05080986023 | | 80000 | 1.943806887 | 1.04428792 | 0.06843280792 | | 90000 | 2.189687967 | 1.16334486 | 0.07787084579 | | 100000 | 2.445794821 | 1.302541018 | 0.0864470005 | bm_simple.py objects per second[¶](#id2) | # objects | Django Rest Framework | marshmallow | serpy | | --- | --- | --- | --- | | 10000 | 41411.31867 | 78037.19243 | 1476243.841 | | 20000 | 42513.11968 | 76629.84657 | 1488872.954 | | 30000 | 42556.7509 | 77910.11452 | 1495811.034 | | 40000 | 42333.41761 | 76205.72419 | 1455180.8 | | 50000 | 41797.53442 | 75879.32408 | 1424221.557 | | 60000 | 39633.86532 | 74820.41459 | 1443731.262 | | 70000 | 41287.14069 | 72136.68368 | 1377685.349 | | 80000 | 41156.35177 | 76607.22533 | 1169029.92 | | 90000 | 41101.74662 | 77363.1303 | 1155759.888 | | 100000 | 40886.50411 | 76773.01417 | 1156778.135 | bm_complex.py time taken (in seconds)[¶](#id3) | # objects | Django Rest Framework | marshmallow | serpy | | --- | --- | --- | --- | | 100 | 0.06559991837 | 0.07014703751 | 0.003219127655 | | 200 | 0.1476380825 | 0.1144611835 | 0.006608009338 | | 300 | 0.171423912 | 0.169506073 | 0.009553909302 | | 400 | 0.2272388935 | 0.2767920494 | 0.01268196106 | | 500 | 0.3147311211 | 0.2825651169 | 0.0157828331 | | 600 | 0.3746049404 | 0.3694860935 | 0.01907610893 | | 700 | 0.3846490383 | 0.3978009224 | 0.02250695229 | | 800 | 0.4846799374 | 0.4635269642 | 0.02613210678 | | 900 | 0.5376219749 | 0.5094399452 | 0.02945303917 | | 1000 | 0.5961399078 | 0.5659701824 | 0.03282499313 | bm_complex.py objects per second[¶](#id4) | # objects | Django Rest Framework | marshmallow | serpy | | --- | --- | --- | --- | | 100 | 1524.392141 | 1425.576953 | 31064.3164 | | 200 | 1354.664031 | 1747.317246 | 30266.30105 | | 300 | 1750.047566 | 1769.848093 | 31400.75863 | | 400 | 1760.262048 | 1445.128214 | 31540.86329 | | 500 | 1588.65764 | 1769.50363 | 31679.99033 | | 600 | 1601.687365 | 1623.877084 | 31452.95522 | | 700 | 1819.840765 | 1759.67415 | 31101.50104 | | 800 | 1650.573788 | 1725.897438 | 30613.68173 | | 900 | 1674.038715 | 1766.645919 | 30557.11823 | | 1000 | 1677.458574 | 1766.877534 | 30464.59129 | Indices and tables[¶](#indices-and-tables) --- * [Index](genindex.html) * [Module Index](py-modindex.html) * [Search Page](search.html)
sshkit
hex
Erlang
SSHKit === [![Build Status](https://travis-ci.org/bitcrowd/sshkit.ex.svg?branch=master)](https://travis-ci.org/bitcrowd/sshkit.ex) [![Inline docs](https://inch-ci.org/github/bitcrowd/sshkit.ex.svg?branch=master)](https://inch-ci.org/github/bitcrowd/sshkit.ex) SSHKit is an Elixir toolkit for performing tasks on one or more servers, built on top of Erlang’s SSH application. [Documentation for SSHKit is available online](https://hexdocs.pm/sshkit). Usage --- SSHKit is designed to enable server task automation in a structured and repeatable way, e.g. in the context of deployment tools: ``` hosts = ["1.eg.io", {"2.eg.io", port: 2222}] context = SSHKit.context(hosts) |> SSHKit.path("/var/www/phx") |> SSHKit.user("deploy") |> SSHKit.group("deploy") |> SSHKit.umask("022") |> SSHKit.env(%{"NODE_ENV" => "production"}) [:ok, :ok] = SSHKit.upload(context, ".", recursive: true) [{:ok, _, 0}, {:ok, _, 0}] = SSHKit.run(context, "yarn install") ``` The [`SSHKit`](https://hexdocs.pm/sshkit/SSHKit.html) module documentation has more guidance and examples for the DSL. If you need more control, take a look at the [`SSHKit.SSH`](https://hexdocs.pm/sshkit/SSHKit.SSH.html) and [`SSHKit.SCP`](https://hexdocs.pm/sshkit/SSHKit.SCP.html) modules. Installation --- Just add `sshkit` to your list of dependencies in `mix.exs`: ``` def deps do [{:sshkit, "~> 0.1"}] end ``` SSHKit should be automatically started unless the `:applications` key is set inside `def application` in your `mix.exs`. In such cases, you need to [remove the `:applications` key in favor of `:extra_applications`](https://elixir-lang.org/blog/2017/01/05/elixir-v1-4-0-released/#application-inference). Modules --- SSHKit consists of three core modules: ``` +---+ | SSHKit | +---+ | | SSHKit.SCP | | +---+ | SSHKit.SSH | +---+ ``` 1. [**`SSHKit.SSH`**](https://hexdocs.pm/sshkit/SSHKit.SSH.html) provides convenience functions for working with SSH connections and for executing commands on remote hosts. 2. [**`SSHKit.SCP`**](https://hexdocs.pm/sshkit/SSHKit.SCP.html) provides convenience functions for transferring files or entire directory trees to or from a remote host via SCP. It is built on top of [`SSHKit.SSH`](SSHKit.SSH.html). 3. [**`SSHKit`**](https://hexdocs.pm/sshkit/SSHKit.html) provides the main API for automating tasks on remote hosts in a structured way. It uses both `SSH` and `SCP` to implement its functionality. Additional modules, e.g. for custom client key handling, are available as separate packages: * [**`ssh_client_key_api`**](https://hex.pm/packages/ssh_client_key_api): An Elixir implementation for the Erlang `ssh_client_key_api` behavior, to make it easier to specify SSH keys and `known_hosts` files independently of any particular user's home directory. Testing --- As usual, to run all tests, use: ``` mix test ``` Apart from unit tests, we also have [functional tests](https://en.wikipedia.org/wiki/Functional_testing). These check SSHKit functionality against real SSH server implementations running inside Docker containers. Therefore, you need to have [Docker](https://www.docker.com/) installed. All functional tests are tagged as such. Hence, if you wish to skip them: ``` mix test --exclude functional ``` Hint: We've found functional tests to run significantly faster with [Docker Machine](https://docs.docker.com/machine/) compared to [Docker for Mac](https://docs.docker.com/docker-for-mac/) on OS X. Releasing --- * Make sure tests pass: [`mix test`](https://hexdocs.pm/mix/Mix.Tasks.Test.html). * Increase version number in `mix.exs`, keeping [semantic versioning](https://semver.org/) in mind. * Update [CHANGLOG.md](./CHANGELOG.md): + Create a new section for the current version. + Reset the `master` section to the empty template. * Commit your changes: `git commit -m "Release 0.1.0"`. * Tag the commit with the version number: `git tag -a v0.1.0`. + Annotate the tag with the respective section from [CHANGLOG.md](./CHANGELOG.md) *(in a git-compatible format)*. * Push your commit: `git push`. * Push the tag: `git push origin v0.1.0` * Publish the new release to hex.pm: [`mix hex.publish`](https://hexdocs.pm/hex/Mix.Tasks.Hex.Publish.html). + You can find the hex.pm credentials in the bitcrowd password store. Contributing --- We welcome everyone to contribute to SSHKit and help us tackle existing issues! Use the [issue tracker](https://github.com/bitcrowd/sshkit.ex/issues) for bug reports or feature requests. Open a [pull request](https://github.com/bitcrowd/sshkit.ex/pulls) when you are ready to contribute. If you are planning to contribute documentation, please check [the best practices for writing documentation](https://hexdocs.pm/elixir/writing-documentation.html). Thanks --- SSHKit is inspired by [SSHKit for Ruby](https://github.com/capistrano/sshkit) which is part of the fantastic [Capistrano](https://github.com/capistrano) project. It deliberately departs from its role model with regard to its API given the very different nature of the two programming languages. If you are looking for an Elixir deployment tool similar to Capistrano, take a look at [Bootleg](https://github.com/labzero/bootleg) which is based on top of SSHKit. License --- SSHKit source code is released under the MIT License. Check the [LICENSE](./LICENSE) file for more information. SSHKit === A toolkit for performing tasks on one or more servers. ``` hosts = ["1.eg.io", {"2.eg.io", port: 2222}] context = SSHKit.context(hosts) |> SSHKit.path("/var/www/phx") |> SSHKit.user("deploy") |> SSHKit.group("deploy") |> SSHKit.umask("022") |> SSHKit.env(%{"NODE_ENV" => "production"}) [:ok, :ok] = SSHKit.upload(context, ".", recursive: true) [{:ok, _, 0}, {:ok, _, 0}] = SSHKit.run(context, "yarn install", mode: :parallel) ``` [Link to this section](#summary) Summary === [Functions](#functions) --- [context(hosts, defaults \\ [])](#context/2) Takes one or more (remote) hosts and creates an execution context in which remote commands can be run. Accepts any form of host specification also accepted by [`host/1`](#host/1) and [`host/2`](#host/2), i.e. binaries, maps and 2-tuples. [download(context, source, options \\ [])](#download/3) Download a file or files from the given context. [env(context, map)](#env/2) Defines new environment variables or overrides existing ones for a given context. [group(context, name)](#group/2) Specifies the group commands are executed with. [host(arg1)](#host/1) Produces an [`SSHKit.Host`](SSHKit.Host.html) struct holding the information needed to connect to a (remote) host. [host(host, options \\ [])](#host/2) Produces an [`SSHKit.Host`](SSHKit.Host.html) struct holding the information needed to connect to a (remote) host. [path(context, path)](#path/2) Changes the working directory commands are executed in for the given context. [run(context, command)](#run/2) Executes a command in the given context. [umask(context, mask)](#umask/2) Changes the file creation mode mask affecting default file and directory permissions. [upload(context, source, options \\ [])](#upload/3) Upload a file or files to the given context. [user(context, name)](#user/2) Specifies the user under whose name commands are executed. That user might be different than the user with which ssh connects to the remote host. [Link to this section](#functions) Functions === SSHKit.Context === A context encapsulates the environment for the execution of a task. That is: * hosts to run the task on, see [`SSHKit.context/2`](SSHKit.html#context/2) * working directory to start in, see [`SSHKit.path/2`](SSHKit.html#path/2) * user to run as, see [`SSHKit.user/2`](SSHKit.html#user/2) * group, see [`SSHKit.group/2`](SSHKit.html#group/2) * file creation mode mask, see [`SSHKit.umask/2`](SSHKit.html#umask/2) * environment variables, see [`SSHKit.env/2`](SSHKit.html#env/2) A context can then be used to run commands, upload or download files: See [`SSHKit.run/2`](SSHKit.html#run/2), [`SSHKit.upload/3`](SSHKit.html#upload/3) and [`SSHKit.download/3`](SSHKit.html#download/3). [Link to this section](#summary) Summary === [Functions](#functions) --- [build(context, command)](#build/2) Compiles an executable command string for running the given `command` in the provided `context`. [Link to this section](#functions) Functions === SSHKit.Host === Provides the data structure holding the information about how to connect to a host. Examples --- ``` %SSHKit.Host{name: "3.eg.io", options: [port: 2223]} |> SSHKit.context() |> SSHKit.run("touch base") ``` SSHKit.SCP === Provides convenience functions for transferring files or directory trees to or from a remote host via SCP. Built on top of [`SSHKit.SSH`](SSHKit.SSH.html). Common options --- These options are available for both uploads and downloads: * `:verbose` - let the remote scp process be verbose, default `false` * `:recursive` - set to `true` for copying directories, default `false` * `:preserve` - preserve timestamps, default `false` * `:timeout` - timeout in milliseconds, default `:infinity` Examples --- ``` {:ok, conn} = SSHKit.SSH.connect("eg.io", user: "me") :ok = SSHKit.SCP.upload(conn, ".", "/home/code/phx", recursive: true) :ok = SSHKit.SSH.close(conn) ``` [Link to this section](#summary) Summary === [Functions](#functions) --- [download(connection, source, target, options \\ [])](#download/4) Downloads a file or directory from a remote host. [upload(connection, source, target, options \\ [])](#upload/4) Uploads a local file or directory to a remote host. [Link to this section](#functions) Functions === SSHKit.SSH behaviour === Provides convenience functions for working with SSH connections and executing commands on remote hosts. Examples --- ``` {:ok, conn} = SSHKit.SSH.connect("eg.io", user: "me") {:ok, output, status} = SSHKit.SSH.run(conn, "uptime") :ok = SSHKit.SSH.close(conn) Enum.each(output, fn {:stdout, data} -> IO.write(data) {:stderr, data} -> IO.write([IO.ANSI.red, data, IO.ANSI.reset]) end) IO.puts("$?: #{status}") ``` [Link to this section](#summary) Summary === [Functions](#functions) --- [close(connection)](#close/1) [connect(host, options_or_function \\ [])](#connect/2) [connect(host, options, function)](#connect/3) Similar to [`connect/2`](#connect/2) but expects a function as its last argument. [run(connection, command, options \\ [])](#run/3) [Callbacks](#callbacks) --- [close(arg1)](#c:close/1) Closes an SSH connection. [connect(binary, arg2)](#c:connect/2) Establishes a connection to an SSH server. [run(arg1, binary, keyword)](#c:run/3) Executes a command on the remote and aggregates incoming messages. [Link to this section](#functions) Functions === [Link to this section](#callbacks) Callbacks === SSHKit.SSH.Channel === Defines a [`SSHKit.SSH.Channel`](#content) struct representing a connection channel. A channel struct has the following fields: * `connection` - the underlying [`SSHKit.SSH.Connection`](SSHKit.SSH.Connection.html) * `type` - the type of the channel, i.e. `:session` * `id` - the unique channel id [Link to this section](#summary) Summary === [Functions](#functions) --- [adjust(channel, size)](#adjust/2) Adjusts the flow control window. [close(channel)](#close/1) Closes an SSH channel. [eof(channel)](#eof/1) Sends an EOF message on an open SSH channel. [exec(channel, command, timeout \\ :infinity)](#exec/3) Executes a command on the remote host. [flush(channel, timeout \\ 0)](#flush/2) Flushes any pending messages for the given channel. [loop(channel, timeout \\ :infinity, acc, fun)](#loop/4) Loops over channel messages until the channel is closed, or looping is stopped explicitly. [open(connection, options \\ [])](#open/2) Opens a channel on an SSH connection. [ptty(channel, options \\ [], timeout \\ :infinity)](#ptty/3) Allocates PTTY. [recv(channel, timeout \\ :infinity)](#recv/2) Receive the next message on an open SSH channel. [send(channel, type \\ 0, data, timeout \\ :infinity)](#send/4) Sends data across an open SSH channel. [subsystem(channel, subsystem, options \\ [])](#subsystem/3) Activates a subsystem on a channel. [Link to this section](#functions) Functions === SSHKit.SSH.Connection === Defines a [`SSHKit.SSH.Connection`](#content) struct representing a host connection. A connection struct has the following fields: * `host` - the name or IP of the remote host * `port` - the port to connect to * `options` - additional connection options * `ref` - the underlying `:ssh` connection ref [Link to this section](#summary) Summary === [Types](#types) --- [t()](#t:t/0) [Functions](#functions) --- [close(conn)](#close/1) Closes an SSH connection. [open(host, options \\ [])](#open/2) Opens a connection to an SSH server. [reopen(connection, options \\ [])](#reopen/2) Opens a new connection, based on the parameters of an existing one. [Link to this section](#types) Types === [Link to this section](#functions) Functions ===
CNVRG
cran
R
Package ‘CNVRG’ October 12, 2022 Title Dirichlet Multinomial Modeling of Relative Abundance Data Version 1.0.0 Maintainer <NAME> <<EMAIL>> Description Implements Dirichlet multinomial modeling of relative abundance data using functionality pro- vided by the 'Stan' software. The purpose of this package is to provide a user friendly way to in- terface with 'Stan' that is suitable for those new to modeling. For more regarding the model- ing mathematics and computational techniques we use see our publication in Molecular Ecol- ogy Resources titled 'Dirichlet multinomial modeling outperforms alternatives for analy- sis of ecological count data' (Harrison et al. 2020 <doi:10.1111/1755-0998.13128>). License GPL-3 Encoding UTF-8 LazyData true RoxygenNote 7.1.1 Biarch true Depends R (>= 3.4.0) Imports methods, Rcpp (>= 0.12.0), rstan (>= 2.18.1), vegan, rstantools (>= 2.1.1), tibble LinkingTo BH (>= 1.66.0), Rcpp (>= 0.12.0), RcppEigen (>= 0.3.3.3.0), RcppParallel (>= 5.0.1), rstan (>= 2.18.1), StanHeaders (>= 2.18.0) SystemRequirements GNU make Repository CRAN NeedsCompilation yes Author <NAME> [aut, cre] (<https://orcid.org/0000-0003-2524-0273>), <NAME> [aut] (<https://orcid.org/0000-0002-7294-5607>), <NAME> [aut] (<https://orcid.org/0000-0002-8923-1803>), C. <NAME> [aut] (<https://orcid.org/0000-0003-4222-8858>) Date/Publication 2021-09-04 04:40:06 UTC R topics documented: CNVRG-packag... 2 cnvrg_HM... 2 cnvrg_V... 4 diff_abun... 5 diversity_cal... 6 extract_pi_quantile... 8 extract_point_estimat... 9 fung... 10 indexe... 11 isd_transfor... 11 CNVRG-package The ’CNVRG’ package. Description This package implements Dirichlet multinomial modeling of relative abundance data using func- tionality provided by the ’Stan’ software. The purpose of this package is to provide a user friendly way to interface with ’Stan’ that is suitable for those new modelling. References Stan Development Team (2018). RStan: the R interface to Stan. R package version 2.18.2. cnvrg_HMC Perform Hamiltonian Monte Carlo sampling Description This function uses a compiled Dirichlet multinomial model and performs Hamiltonian Monte Carlo sampling of posteriors using ’Stan’. After sampling it is important to check convergence. Use the summary function and shinystan to do this. If you use this function then credit ’Stan’ and ’RStan’ along with this package. Usage cnvrg_HMC( countData, starts, ends, algorithm = "NUTS", chains = 2, burn = 500, samples = 1000, thinning_rate = 2, cores = 1, params_to_save = c("pi", "p") ) Arguments countData A matrix or data frame of counts.The first field should be sample names and the subsequent fields should be integer data. Data should be arranged so that the first n rows correspond to one treatment group and the next n rows correspond with the next treatment group, and so on. The row indices for the first and last sample in these groups are fed into this function via ’starts’ and ’ends’. starts A vector defining the indices that correspond to the first sample in each treatment group. The indexer function can help with this. ends A vector defining the indices that correspond to the last sample in each treatment group. The indexer function can help with this. algorithm The algorithm to use when sampling. Either ’NUTS’ or ’HMC’ or ’Fixed_param’. If unsure, then be like a squirrel. This is "No U turn sampling". The abbreviation is from ’Stan’. chains The number of chains to run. burn The warm up or ’burn in’ time. samples How many samples from the posterior to save. thinning_rate Thinning rate to use during sampling. cores The number of cores to use. params_to_save The parameters from which to save samples. Can be ’p’, ’pi’, ’theta’. Details It can be helpful to use the indexer function to automatically identify the indices needed for the ’starts’ and ’ends’ parameters. See the vignette for an example. Warning: data must be input in the correct organized format or this function will not provide accu- rate results. See vignette if you are unsure how to organize data. Warning: depending upon size of data to be analyzed this function can take a very long time to run. Value A fitted ’Stan’ object that includes the samples from the parameters designated. Examples #simulate an OTU table com_demo <-matrix(0, nrow = 10, ncol = 10) com_demo[1:5,] <- c(rep(3,5), rep(7,5)) #Alternates 3 and 7 com_demo[6:10,] <- c(rep(7,5), rep(3,5)) #Reverses alternation fornames <- NA for(i in 1:length(com_demo[1,])){ fornames[i] <- paste("otu_", i, sep = "") } sample_vec <- NA for(i in 1:length(com_demo[,1])){ sample_vec[i] <- paste("sample", i, sep = "_") } com_demo <- data.frame(sample_vec, com_demo) names(com_demo) <- c("sample", fornames) #These are toy data, many more samples, multiple chains, and a longer burn #are likely advisable for real data. fitstan_HMC <- cnvrg_HMC(com_demo,starts = c(1,6), ends=c(5,10), chains = 1, burn = 100, samples = 150, thinning_rate = 2) cnvrg_VI Perform variational inference sampling Description This function uses a compiled Dirichlet multinomial model and performs variational inference esti- mation of posteriors using ’Stan’. Evaluating the performance of variational inference is currently under development per our understanding. Please roll over to the ’Stan’ website and see if new diagnostics are available. If you use this function then credit ’Stan’ and ’RStan’ along with this package. Usage cnvrg_VI( countData, starts, ends, algorithm = "meanfield", output_samples = 500, params_to_save = c("pi", "p") ) Arguments countData A matrix or data frame of counts.The first field should be sample names and the subsequent fields should be integer data. Data should be arranged so that the first n rows correspond to one treatment group and the next n rows correspond with the next treatment group, and so on. The row indices for the first and last sample in these groups are fed into this function via ’starts’ and ’ends’. starts A vector defining the indices that correspond to the first sample in each treatment group. The indexer function can help with this. ends A vector defining the indices that correspond to the last sample in each treatment group. The indexer function can help with this. algorithm The algorithm to use when performing variational inference. Either ’meanfield’ or ’fullrank’. The former is the default. output_samples The number of samples from the approximated posterior to save. params_to_save The parameters from which to save samples. Can be ’p’, ’pi’, ’theta’. Details It can be helpful to use the indexer function to automatically identify the indices needed for the ’starts’ and ’ends’ parameters. See the vignette for an example. Warning: data must be input in the correct organized format or this function will not provide accu- rate results. See vignette if you are unsure how to organize data. Warning: depending upon size of data to be analyzed this function can take a very long time to run. Value A fitted ’Stan’ object that includes the samples from the parameters designated. Examples #simulate an OTU table diff_abund Calculate features with different abundances between treatment groups Description This function determines which features within the matrix that was modeled differ in relative abun- dance among treatment groups. Pass in a model object, with samples for pi parameters. This function only works for pi parameters. Usage diff_abund(model_out, countData, prob_threshold = 0.05) Arguments model_out Output of CNVRG modeling functions, including cnvrg_HMC and cnvrg_VI countData Dataframe of count data that was modeled. Should be exactly the same as those data modeled! The first field should be sample name and integer count data should be in all other fields. This is passed in so that the names of fields can be used to make the output of differential relative abundance testing more readable. prob_threshold Probability threshold, below which it is considered that features had a high prob- ability of differing between groups. Default is 0.05. Details The output of this function gives the proportion of samples that were greater than zero after sub- tracting the two relevant posterior distributions. Therefore, values that are very large or very small denote a high certainty that the distributions subtracted differ. If this concept is not clear, then read Harrison et al. 2020 ’Dirichlet multinomial modeling outperforms alternatives for analysis of microbiome and other ecological count data’ in Molecular Ecology Resources. For a simple explanation, see this video: https://use.vg/OSVhFJ The posterior probability distribution of differences is also output. These samples can be useful for plotting or other downstream analyses. Finally, a list of data frames describing the features that differed among treatment comparisons is output, with the probability of differences and the magnitude of those differences (the effect size) included. Value A dataframe with the first field denoting the treatment comparison (e.g., treatment 1 vs. 2) and subsequent fields stating the proportion of samples from the posterior that were greater than zero (called "certainty of diffs"). Note that each treatment group is compared to all other groups, which leads to some redundancy in output. A list, called ppd_diffs, holding samples from the posterior probability distribution of the differences is also output. Finally, a list of dataframes describing results for only those features with a high probability of differing is output (this list is named: features_that_differed). Examples #simulate an OTU table com_demo <-matrix(0, nrow = 10, ncol = 10) com_demo[1:5,] <- c(rep(3,5), rep(7,5)) #Alternates 3 and 7 com_demo[6:10,] <- c(rep(7,5), rep(3,5)) #Reverses alternation fornames <- NA for(i in 1:length(com_demo[1,])){ fornames[i] <- paste("otu_", i, sep = "") } sample_vec <- NA for(i in 1:length(com_demo[,1])){ sample_vec[i] <- paste("sample", i, sep = "_") } com_demo <- data.frame(sample_vec, com_demo) names(com_demo) <- c("sample", fornames) out <- cnvrg_VI(com_demo,starts = c(1,6), ends=c(5,10)) diff_abund_test <- diff_abund(model_out = out, countData = com_demo) diversity_calc Calculate diversity entropies for each replicate Description Calculate Shannon’s or Simpson’s indices for each replicate while propagating uncertainty in rela- tive abundance estimates through calculations. Usage diversity_calc( model_out, countData, params = "pi", entropy_measure = "shannon", equivalents = T ) Arguments model_out Output of CNVRG modeling functions, including cnvrg_HMC and cnvrg_VI or isd_transform countData Dataframe of count data that was modeled. Should be exactly the same as those data modeled! The first field should be sample name and integer count data should be in all other fields. This is passed in so that the names of fields can be used to make the output of differential relative abundance testing more readable. params Parameter for which to calculate diversity, can be ’p’ or ’pi’ or both (e.g., c("pi","p")) entropy_measure Diversity entropy to use, can be one of ’shannon’ or ’simpson’ equivalents Convert entropies into number equivalents. Defaults to true. See Jost (2006), "Entropy and diversity" Details Takes as input either a fitted Stan object from the cnvrg_HMC or cnvrg_VI functions, or the output of isd_transform. As always, doublecheck the results to ensure the function has output reasonable values. Note that because there are no zero values and all proportion estimates are non zero there is a lot of information within the modeled data. Because diversity entropies are measures of information content, this means there will be a much higher entropy estimate for modeled data than the raw count data. However, patterns of variation in diversity should be similar among treatment groups for modeled and raw data. Value A list that has samples from posterior distributions of entropy metrics Examples #simulate an OTU table com_demo <-matrix(0, nrow = 10, ncol = 10) com_demo[1:5,] <- c(rep(3,5), rep(7,5)) #Alternates 3 and 7 com_demo[6:10,] <- c(rep(7,5), rep(3,5)) #Reverses alternation fornames <- NA for(i in 1:length(com_demo[1,])){ fornames[i] <- paste("otu_", i, sep = "") } sample_vec <- NA for(i in 1:length(com_demo[,1])){ sample_vec[i] <- paste("sample", i, sep = "_") } com_demo <- data.frame(sample_vec, com_demo) names(com_demo) <- c("sample", fornames) out <- cnvrg_VI(com_demo,starts = c(1,6), ends=c(5,10)) diversity_calc(model_out = out,params = c("pi","p"), countData = com_demo, entropy_measure = 'shannon') extract_pi_quantiles Extract quantiles of pi parameters Description Provides quantiles of pi parameters for each feature and treatment group. Usage extract_pi_quantiles(model_out, probs = c(0.05, 0.5, 0.95)) Arguments model_out Output of CNVRG modeling functions, including cnvrg_HMC and cnvrg_VI probs A vector of quantiles Value A list specifying quantiles for each feature in each treatment group. Examples #simulate an OTU table com_demo <-matrix(0, nrow = 10, ncol = 10) com_demo[1:5,] <- c(rep(3,5), rep(7,5)) #Alternates 3 and 7 com_demo[6:10,] <- c(rep(7,5), rep(3,5)) #Reverses alternation fornames <- NA for(i in 1:length(com_demo[1,])){ fornames[i] <- paste("otu_", i, sep = "") } sample_vec <- NA for(i in 1:length(com_demo[,1])){ sample_vec[i] <- paste("sample", i, sep = "_") } com_demo <- data.frame(sample_vec, com_demo) names(com_demo) <- c("sample", fornames) out <- cnvrg_VI(com_demo,starts = c(1,6), ends=c(5,10)) extract_pi_quantiles(model_out = out, probs = c(0.05,0.5,0.95)) extract_point_estimate Extract point estimates of multinomial and Dirichlet parameters Description Provides the mean value of posterior probability distributions for parameters. Usage extract_point_estimate(model_out, countData, params = c("pi", "p")) Arguments model_out Output of CNVRG modeling functions, including cnvrg_HMC and cnvrg_VI countData The count data modeled. params Parameters to be extracted, either pi (Dirichlet) or p (multinomial). Value A list of of point estimates for model parameters. If both multinomial and Dirichlet parameters are requested then they will be named elements of a list. Examples #simulate an OTU table com_demo <-matrix(0, nrow = 10, ncol = 10) com_demo[1:5,] <- c(rep(3,5), rep(7,5)) #Alternates 3 and 7 com_demo[6:10,] <- c(rep(7,5), rep(3,5)) #Reverses alternation fornames <- NA for(i in 1:length(com_demo[1,])){ fornames[i] <- paste("otu_", i, sep = "") } sample_vec <- NA for(i in 1:length(com_demo[,1])){ sample_vec[i] <- paste("sample", i, sep = "_") } com_demo <- data.frame(sample_vec, com_demo) names(com_demo) <- c("sample", fornames) out <- cnvrg_VI(com_demo,starts = c(1,6), ends=c(5,10)) extract_point_estimate(model_out = out, countData = com_demo) fungi Fungal endophytes of Astragalus lentiginosus grown near Reno, NV Description Fungal endophytes of Astragalus lentiginosus grown near Reno, NV Usage fungi Format A data frame with columns: treatment A categorical variable describing if a plant was treated with a slurry of endophyte in- oculum and whether it was positive or negative for Alternaria fulva. Otu10 Contains count data. Otu100 Contains count data. Otu11 Contains count data. Otu12 Contains count data. Otu4 Contains count data. Otu40 Contains count data. Otu42 Contains count data. Otu54 Contains count data. Otu58 Contains count data. Otu6 Contains count data. Otu62 Contains count data. Otu7 Contains count data. Otu70 Contains count data. Otu71 Contains count data. Otu72 Contains count data. Otu74 Contains count data. Otu76 Contains count data. Otu77 Contains count data. Otu79 Contains count data. Otu86 Contains count data. Otu9 Contains count data. Otu92 Contains count data. Otu94 Contains count data. Otu96 Contains count data. Otu97 Contains count data. Otu99 Contains count data. Source <NAME>, https://www.biorxiv.org/content/10.1101/608729v1.full Examples ## Not run: fungi ## End(Not run) indexer Determine indices for treatment groups Description This function determines the indices for the first and last replicates within a vector describing treat- ment group. Usage indexer(x) Arguments x Vector input. Value A list with two named elements that contain start and end indices. Examples indexer(c(rep("treatment1",5), rep("treatment2",5))) isd_transform Transform data into estimates of absolute abundances using an ISD Description If an internal standard (ISD) has been added to samples such that the counts for that standard are representative of the same absolute abundance, then the ISD can be used to transform relative abundance data such that they are proportional to absolute abundances (Harrison et al. 2020). This function performs this division while preserving uncertainty in relative abundance estimates of both the ISD and the other features present. Usage isd_transform(model_out, isd_index, countData, format = "stan") Arguments model_out Output of CNVRG modeling functions, including cnvrg_HMC and cnvrg_VI isd_index The index for the field with information for the internal standard. countData The count data modeled. format The output format. Can be either ’or ’samples’ or ’ml’. "samples" outputs sam- ples from the posterior probability distribution, the last option ("ml") outputs the mean of posterior samples for each parameter. Details An index for the ISD must be provided. This should be the field index that corresponds with the ISD. Remember that the index should mirror what has been modeled. Also, note that this function subtracts one from this index because the modeled data have a non integer sample field. If the wrong index is passed in, the output of this function will be incorrect, but there will not be a fatal error or warning. A simple check that the correct index has been passed to the function is to examine the output and make sure that the field that should correspond with the ISD is one (signifying that the ISD was divided by itself). Output format can either as means of the samples for each pi parameter or the transformed samples from the posterior distribution for that parameter. Harrison et al. 2020. ’The quest for absolute abundance: the use of internal standards for DNA based community ecology’ Molecular Ecology Resources. Value A dataframe, or list, specifying either point estimates for each feature in each treatment group (if output format is ’ml’) or samples from the posterior (if output format is ’samples’). Examples #simulate an OTU table com_demo <-matrix(0, nrow = 10, ncol = 10) com_demo[1:5,] <- c(rep(3,5), rep(7,5)) #Alternates 3 and 7 com_demo[6:10,] <- c(rep(7,5), rep(3,5)) #Reverses alternation fornames <- NA for(i in 1:length(com_demo[1,])){ fornames[i] <- paste("otu_", i, sep = "") } sample_vec <- NA for(i in 1:length(com_demo[,1])){ sample_vec[i] <- paste("sample", i, sep = "_") } com_demo <- data.frame(sample_vec, com_demo) names(com_demo) <- c("sample", fornames) #Model the data out <- cnvrg_VI(com_demo,starts = c(1,6), ends=c(5,10)) #Transform the data transformed_data <- isd_transform(model_out = out, countData = com_demo, isd_index = 3, format = "ml")
sonnerie
rust
Rust
Module sonnerie::formatted === Read or write formatted data to a text stream. Enums --- * PrintRecordFormatPrint the record format (`uUfF`) right after the timestamp * PrintTimestampSpecify how to print the timestamp Functions --- * add_from_streamRead keys from a text stream and insert it into a transaction * add_from_stream_with_fmtReads from text, each record reports its own format. * print_recordWrite a formatted record to a stream Module sonnerie::row_format === Decode an encoded row format. Traits --- * RowFormatDecodes a row by its format. Created with `parse_row_format`. Functions --- * parse_row_formatconvert a text-based row format description to an object * row_format_size Struct sonnerie::CreateTx === ``` pub struct CreateTx { /* private fields */ } ``` Create a transaction file in the specified db directory. Add new records with `CreateTx::add_record`. They must be in sorted order. After adding records, call `CreateTx::commit` which ensures the transaction is on disk. Not calling commit will rollback the transaction. Implementations --- ### impl CreateTx #### pub fn new(dir: &Path) -> Result<CreateTxOpen a transaction file inside this specific directory. The transaction is named “tx.XXX.tmp” where XXX is an increasing value basedo on timestamp. On commit, the file is renamed to not have the “.tmp” suffix. #### pub fn add_record( &mut self, key: &str, timestamp: NaiveDateTime, values: impl RecordBuilder ) -> Result<(), WriteFailureAdd a record with the given key, timestamp, and values. The values can be encoded with the function `crate::record()` The format string is automatically inferred by the Rust-types of the values. ``` transaction.add_record( "key name", "2010-01-01T00:00:01".parse().unwrap(), sonnerie::record("Column 1").add("Column 2").add(3i32) ).unwrap(); ``` Because &[&dyn ToRecord] also implements the `crate::RecordBuilder` trait, you can also use an array to specify the types, but then less work happens at compile-time and the performance isn’t as good: ``` transaction.add_record( "key name", "2010-01-01T00:00:01".parse().unwrap(), &[&"Column 1" as &dyn sonnerie::ToRecord, &"Column 2", &3i32] ).unwrap(); ``` Each successive call to this function must have greater or equal values for key and timestamp. #### pub fn add_record_raw( &mut self, key: &str, format: &str, data: &[u8] ) -> Result<(), WriteFailureAdd a record with the given key, format, and payload. The data must match the format (otherwise you can corrupt the database). The data also encodes the timestamp. Each successive call to this function must have greater or equal values for key and timestamp. Encode the data with `crate::row_format::RowFormat`. This function is made available for tools that need more versaility in how they process databases. It’s generally preferable to use `CreateTx::add_record()` #### pub fn delete( &mut self, first_key: &str, last_key: &str, after_time: u64, before_time: u64, filter: &str ) -> Result<(), WriteFailureDelete a range of records You can use an empty string to indicate “unbounded” and `u64::MIN` and `u64::MAX` for the timestamps, similarly. This function must be called as the one and only action in a transaction and then committed. #### pub fn commit_to(self, final_name: &Path) -> Result<()Commit the transaction, but give it a specific name. This function is necessary for compacting, normally you would just call the basic `CreateTx::commit`. #### pub fn commit(self) -> Result<()Commit the transaction. On successful completion, the data is on disk (fsync is called) and the filename is renamed to lose its “.tmp” suffix. Auto Trait Implementations --- ### impl !RefUnwindSafe for CreateTx ### impl Send for CreateTx ### impl Sync for CreateTx ### impl Unpin for CreateTx ### impl !UnwindSafe for CreateTx Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pointable for T #### const ALIGN: usize = mem::align_of::<T>() The alignment of pointer.#### type Init = T The type for initializers.#### unsafe fn init(init: <T as Pointable>::Init) -> usize Initializes a with the given initializer. Dereferences the given pointer. Mutably dereferences the given pointer. Drops the object pointed to by the given pointer. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V Struct sonnerie::DatabaseReader === ``` pub struct DatabaseReader { /* private fields */ } ``` Read a database in key-timestamp sorted format. Open a database with `new` and then `get`, `get_filter` or `get_range` to select which keys to read. Implementations --- ### impl DatabaseReader #### pub fn new(dir: &Path) -> Result<DatabaseReaderOpen a database at the given path. All of the committed transactions are opened. Any transactions that appear after `new` is called are not opened (create a new `DatabaseReader`). #### pub fn without_main_db(dir: &Path) -> Result<DatabaseReaderOpen a database at the given path, but not the `main` file. This is only useful for doing a minor compaction. #### pub fn transaction_paths(&self) -> Vec<PathBufGet the filenames of each transaction. This is useful for compacting, because after compaction is complete, you would delete all of the transaction files. This function also returns the path for `main`, which is overwritten. Don’t delete that. This function doesn’t return the transactions that contain deletions. #### pub fn delete_txes_paths(&self) -> impl Iterator<Item = &PathGet the filenames of the transactions that have a delete marker in them. #### pub fn get<'rdr>(&'rdr self, key: &'rdr str) -> DatabaseRecordReader<'rdrGet a reader for only a single key Returns an object that will read all of the records for only one key. #### pub fn get_range<'d>( &'d self, range: impl RangeBounds<&'d str> + 'd + Clone ) -> DatabaseRecordReader<'dGet a reader for a lexicographic range of keys Use inclusive or exclusive range syntax to select a range. Example: `rdr.get_range("chimpan-ay" ..= "chimpan-zee")` Range queries are always efficient and readahead may occur. #### pub fn get_range_keys<'d>( &'d self, range: impl RangeBounds<&'d str> + 'd + Clone ) -> DatabaseKeyReader<'dGet a key reader for a lexicographic range of keys **`feature=by-key`** Each iterator represents a given key, you may iterate over each of those to get each record for that key. Use inclusive or exclusive range syntax to select a range. Example: `rdr.get_range("chimpan-ay" ..= "chimpan-zee")` Range queries are always efficient and readahead may occur. #### pub fn get_filter<'d>( &'d self, wildcard: &'d Wildcard ) -> DatabaseRecordReader<'dGet a reader that filters on SQL’s “LIKE”-like syntax. A wildcard filter that has a fixed prefix, such as `"chimp%"` is always efficient. #### pub fn get_filter_keys<'d>( &'d self, wildcard: &'d Wildcard ) -> DatabaseKeyReader<'dGet a key reader that filters on SQL’s “LIKE”-like syntax. **`feature=by-key`** Each iterator represents a given key, you may iterate over each of those to get each record for that key. A wildcard filter that has a fixed prefix, such as `"chimp%"` is always efficient. Auto Trait Implementations --- ### impl RefUnwindSafe for DatabaseReader ### impl Send for DatabaseReader ### impl Sync for DatabaseReader ### impl Unpin for DatabaseReader ### impl UnwindSafe for DatabaseReader Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pointable for T #### const ALIGN: usize = mem::align_of::<T>() The alignment of pointer.#### type Init = T The type for initializers.#### unsafe fn init(init: <T as Pointable>::Init) -> usize Initializes a with the given initializer. Dereferences the given pointer. Mutably dereferences the given pointer. Drops the object pointed to by the given pointer. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V Struct sonnerie::Reader === ``` pub struct Reader { /* private fields */ } ``` Read and filter keys from a single transaction file Implementations --- ### impl Reader #### pub fn new(r: File) -> Result<Either<Reader, DeleteMarker>Open a single transaction file If instead you want to read from an entire database, use `DatabaseReader` which provides a similar API. #### pub fn get<'rdr, 'k>(&'rdr self, key: &'k str) -> StringKeyRangeReader<'rdr, 'kGet a reader for only a single key Returns an object that will read all of the records for only one key. #### pub fn get_range<'rdr, 'k>( &'rdr self, range: impl RangeBounds<&'k str> + 'k + Clone ) -> StringKeyRangeReader<'rdr, 'kGet a reader for a lexicographic range of keys Use inclusive or exclusive range syntax to select a range. Example: `rdr.get_range("chimpan-ay" ..= "chimpan-zee")` Range queries are always efficient and readahead may occur. #### pub fn get_filter<'rdr, 'k>( &'rdr self, wildcard: &'k Wildcard ) -> StringKeyRangeReader<'rdr, 'kGet a reader that filters on SQL’s “LIKE”-like syntax. A wildcard filter that has a fixed prefix, such as `"chimp%"` is always efficient. #### pub fn print_info<W: Write>(&self, w: &mut W) -> Result<()Print diagnostic information about this transaction file. This function is for debugging only. Auto Trait Implementations --- ### impl RefUnwindSafe for Reader ### impl Send for Reader ### impl Sync for Reader ### impl Unpin for Reader ### impl UnwindSafe for Reader Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pointable for T #### const ALIGN: usize = mem::align_of::<T>() The alignment of pointer.#### type Init = T The type for initializers.#### unsafe fn init(init: <T as Pointable>::Init) -> usize Initializes a with the given initializer. Dereferences the given pointer. Mutably dereferences the given pointer. Drops the object pointed to by the given pointer. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V {"StringKeyRangeReader<'rdr, 'k>":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.StringKeyRangeReader.html\" title=\"struct sonnerie::StringKeyRangeReader\">StringKeyRangeReader</a>&lt;'rdr, 'k&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'rdr, 'k&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"struct.StringKeyRangeReader.html\" title=\"struct sonnerie::StringKeyRangeReader\">StringKeyRangeReader</a>&lt;'rdr, 'k&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"struct\" href=\"struct.Record.html\" title=\"struct sonnerie::Record\">Record</a>;</span>"} Struct sonnerie::Record === ``` pub struct Record { /* private fields */ } ``` Stores a single timestamp for a single key of data Internally copy-on-write so cheap to copy Implementations --- ### impl Record #### pub fn key(&self) -> &str The key of this record. #### pub fn format(&self) -> &str The format of this record (as the single-character codes) #### pub fn time(&self) -> NaiveDateTime A decoded timestamp for this record #### pub fn timestamp_nanos(&self) -> u64 The raw timestamp for this record as nanoseconds #### pub fn get_checked<'a, T: FromRecord<'a>>(&'a self, col: usize) -> Result<TRead a single column returning possible errors Errors can include an invalid data stream or incompatible types. Any column can be read as long as its type can losslessly be interpreted as the requested type. For example, if the column stores a ‘u’ (32-bit unsigned), then it can be read into a `u32` or a `u64`. However, it’s a failure to read the column as a `u32` if the column stores a `U`, even if the stored value itself can be represented in a `u32`. #### pub fn get<'a, T: FromRecord<'a>>(&'a self, column: usize) -> T Read a column, turning errors into panics Same as `Record::get``(n).unwrap()` #### pub fn value<'a, T: FromRecord<'a>>(&'a self) -> T The value for the first column same as `Record::get``(0)` #### pub fn raw(&self) -> &[u8] The encoded payload of this data. The timestamp and as 8 bytes in nanoseconds, and then each column in turn Trait Implementations --- ### impl Debug for Record #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for Record ### impl Send for Record ### impl Sync for Record ### impl Unpin for Record ### impl UnwindSafe for Record Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pointable for T #### const ALIGN: usize = mem::align_of::<T>() The alignment of pointer.#### type Init = T The type for initializers.#### unsafe fn init(init: <T as Pointable>::Init) -> usize Initializes a with the given initializer. Dereferences the given pointer. Mutably dereferences the given pointer. Drops the object pointed to by the given pointer. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct sonnerie::RecordBuilderEnd === ``` pub struct RecordBuilderEnd; ``` Placeholder type to mark the end of a record, when writing Rust’s generics are used to build a chain of types, `record()` returns a `BuildingRecord<FirstColumnType,RecordBuilderEnd>` where `FirstColumnType` implements `RecordBuilder` trait for the first column value. When you use [`BuildingRecord::add()`] to add an additional column, the type `BuildingRecord<BuildingRecord<SecondColumnType, FirstColumnType>,RecordBuilderEnd>` will be built. Trait Implementations --- ### impl RecordBuilder for RecordBuilderEnd Auto Trait Implementations --- ### impl RefUnwindSafe for RecordBuilderEnd ### impl Send for RecordBuilderEnd ### impl Sync for RecordBuilderEnd ### impl Unpin for RecordBuilderEnd ### impl UnwindSafe for RecordBuilderEnd Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pointable for T #### const ALIGN: usize = mem::align_of::<T>() The alignment of pointer.#### type Init = T The type for initializers.#### unsafe fn init(init: <T as Pointable>::Init) -> usize Initializes a with the given initializer. Dereferences the given pointer. Mutably dereferences the given pointer. Drops the object pointed to by the given pointer. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V Struct sonnerie::Wildcard === ``` pub struct Wildcard { /* private fields */ } ``` matches % as a wildcard operator Implementations --- ### impl Wildcard #### pub fn new(w: &str) -> Wildcard Parse a wildcard filter. All strings are valid, so never fails. #### pub fn prefix(&self) -> &str Returns the shortest possible fixed prefix. If no “%” is in the filter, then the entire string is returned, Otherwise everything up to the “%” is returned, which may be an empty string. #### pub fn is_exact(&self) -> bool returns true if this search can only match a single key. This only happens when there is no “%” in the filter. #### pub fn as_regex(&self) -> Option<RegexReturns the regex that matches my wildcard. Returns None if the prefix is all that’s needed, even if it’s still a wildcard. “prefix%suffix” returns `Some` but `prefix%` returns `None`. Auto Trait Implementations --- ### impl RefUnwindSafe for Wildcard ### impl Send for Wildcard ### impl Sync for Wildcard ### impl Unpin for Wildcard ### impl UnwindSafe for Wildcard Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pointable for T #### const ALIGN: usize = mem::align_of::<T>() The alignment of pointer.#### type Init = T The type for initializers.#### unsafe fn init(init: <T as Pointable>::Init) -> usize Initializes a with the given initializer. Dereferences the given pointer. Mutably dereferences the given pointer. Drops the object pointed to by the given pointer. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V Trait sonnerie::FromRecord === ``` pub trait FromRecord<'a>: Sized { // Required method fn get(fmt_char: u8, bytes: &'a [u8]) -> Result<Self>; } ``` Implements conversions from `Record` columns to Rust types Required Methods --- #### fn get(fmt_char: u8, bytes: &'a [u8]) -> Result<SelfImplementations on Foreign Types --- ### impl<'a> FromRecord<'a> for u32 #### fn get(fmt_char: u8, bytes: &[u8]) -> Result<Self### impl<'a> FromRecord<'a> for i32 #### fn get(fmt_char: u8, bytes: &'a [u8]) -> Result<Self### impl<'a> FromRecord<'a> for String #### fn get(fmt_char: u8, bytes: &'a [u8]) -> Result<Self### impl<'a> FromRecord<'a> for u64 #### fn get(fmt_char: u8, bytes: &'a [u8]) -> Result<Self### impl<'a> FromRecord<'a> for i64 #### fn get(fmt_char: u8, bytes: &'a [u8]) -> Result<Self### impl<'a> FromRecord<'a> for f32 #### fn get(fmt_char: u8, bytes: &'a [u8]) -> Result<Self### impl<'a> FromRecord<'a> for f64 #### fn get(fmt_char: u8, bytes: &'a [u8]) -> Result<Self### impl<'a> FromRecord<'a> for &'a str #### fn get(fmt_char: u8, bytes: &'a [u8]) -> Result<SelfImplementors --- Trait sonnerie::RecordBuilder === ``` pub trait RecordBuilder { } ``` Converts multiple-column data to the internal encoding Create this type with `crate::record()` Implementations on Foreign Types --- ### impl RecordBuilder for [&dyn ToRecord] ### impl<const N: usize> RecordBuilder for &[&dyn ToRecord; N] ### impl RecordBuilder for &[&dyn ToRecord] Implementors --- ### impl RecordBuilder for RecordBuilderEnd Trait sonnerie::ToRecord === ``` pub trait ToRecord { // Required methods fn store(&self, buf: &mut Vec<u8>); fn format_char(&self) -> u8; fn size(&self) -> usize; fn variable_size(&self) -> bool; } ``` Implements conversions from Rust types to Sonnerie records Required Methods --- #### fn store(&self, buf: &mut Vec<u8>) #### fn format_char(&self) -> u8 #### fn size(&self) -> usize #### fn variable_size(&self) -> bool Implementations on Foreign Types --- ### impl ToRecord for &str #### fn store(&self, buf: &mut Vec<u8>) #### fn format_char(&self) -> u8 #### fn size(&self) -> usize #### fn variable_size(&self) -> bool ### impl ToRecord for f64 #### fn store(&self, buf: &mut Vec<u8>) #### fn format_char(&self) -> u8 #### fn size(&self) -> usize #### fn variable_size(&self) -> bool ### impl ToRecord for i64 #### fn store(&self, buf: &mut Vec<u8>) #### fn format_char(&self) -> u8 #### fn size(&self) -> usize #### fn variable_size(&self) -> bool ### impl ToRecord for i32 #### fn store(&self, buf: &mut Vec<u8>) #### fn format_char(&self) -> u8 #### fn size(&self) -> usize #### fn variable_size(&self) -> bool ### impl ToRecord for f32 #### fn store(&self, buf: &mut Vec<u8>) #### fn format_char(&self) -> u8 #### fn size(&self) -> usize #### fn variable_size(&self) -> bool ### impl ToRecord for u64 #### fn store(&self, buf: &mut Vec<u8>) #### fn format_char(&self) -> u8 #### fn size(&self) -> usize #### fn variable_size(&self) -> bool ### impl ToRecord for u32 #### fn store(&self, buf: &mut Vec<u8>) #### fn format_char(&self) -> u8 #### fn size(&self) -> usize #### fn variable_size(&self) -> bool Implementors --- Function sonnerie::record === ``` pub fn record<Rec: ToRecord>( value: Rec ) -> BuildingRecord<Rec, RecordBuilderEnd> ``` A high-level function to build records from Rust types `record()` encodes the given value into a column, you can call `add()` on returned object as many times as you want by chaining, to create multicolumn records. The Rust type of each column is used to determine the stored format string. For example, a `u32` will be stored with the format string `u`. ``` transaction.add_record( "key name", "2010-01-01T00:00:01".parse().unwrap(), sonnerie::record("Column 1").add("Column 2").add(3i32) ).unwrap(); ``` This function performs most of its work at compile-time. Type Definition sonnerie::Timestamp === ``` pub type Timestamp = u64; ``` Nanoseconds since the unix epoch
cargo_arrayfire.jsonl
personal_doc
Unknown
# About ArrayFire Date: 2023-09-25 Categories: Tags: ArrayFire is a high performance software library for parallel computing with an easy-to-use API. Its array based function set makes parallel programming more accessible. Install ArrayFire using either a binary installer for Windows, OSX, or Linux or download it from source: The array object is beautifully simple. Array-based notation effectively expresses computational algorithms in readable math-resembling notation. Expertise in parallel programming is not required to use ArrayFire. A few lines of ArrayFire code accomplishes what can take 100s of complicated lines in CUDA, oneAPI, or OpenCL kernels. ArrayFire contains hundreds of functions across various domains including: Each function is hand-tuned by ArrayFire developers with all possible low-level optimizations. ArrayFire operates on common data shapes and sizes, including vectors, matrices, volumes, and It supports common data types, including single and double precision floating point values, complex numbers, booleans, and 32-bit signed and unsigned integers. ArrayFire can be used as a stand-alone application or integrated with existing CUDA, oneAPI, or OpenCL code. With support for x86, ARM, CUDA, oneAPI, and OpenCL devices, ArrayFire supports for a comprehensive list of devices. Each ArrayFire installation comes with: ArrayFire supports batched operations on N-dimensional arrays. Batch operations in ArrayFire are run in parallel ensuring an optimal usage of CUDA, oneAPI, or OpenCL devices. Best performance with ArrayFire is achieved using vectorization techniques. ArrayFire can also execute loop iterations in parallel with the gfor function. ArrayFire performs run-time analysis of code to increase arithmetic intensity and memory throughput, while avoiding unnecessary temporary allocations. It has an awesome internal JIT compiler to make important optimizations. Read more about how ArrayFire JIT. can improve the performance in your application. Here is an example of ArrayFire code that performs a Monte Carlo estimation of PI. If you redistribute ArrayFire, please follow the terms established in the license. If you wish to cite ArrayFire in an academic publication, please use the following reference: Formatted: > Yalamanchili, P., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME> <NAME>. (2015). ArrayFire - A high performance software library for parallel computing with an easy-to-use API. Atlanta: AccelerEyes. Retrieved from https://github.com/arrayfire/arrayfire BibTeX: > @misc{Yalamanchili2015, abstract = {ArrayFire is a high performance software library for parallel computing with an easy-to-use API. Its array based function set makes parallel programming simple. ArrayFire's multiple backends (CUDA, OpenCL and native CPU) make it platform independent and highly portable. A few lines of code in ArrayFire can replace dozens of lines of parallel computing code, saving you valuable time and lowering development costs.}, address = {Atlanta}, author = {<NAME> <NAME> <NAME> and <NAME> and Entschev, Peter and Kloppenborg, Brian and <NAME> and <NAME>}, publisher = {AccelerEyes}, title = {{ArrayFire - A high performance software library for parallel computing with an easy-to-use API}}, url = {https://github.com/arrayfire/arrayfire}, year = {2015} } ArrayFire development is funded by AccelerEyes LLC (dba ArrayFire) and several third parties, please see the list of acknowledgements.
RcmdrPlugin
cran
R
Package ‘RcmdrPlugin.SCDA’ October 12, 2022 Type Package Title Rcmdr Plugin for Designing and Analyzing Single-Case Experiments Version 1.2.0 Date 2019-07-01 Author <NAME> and <NAME> Maintainer <NAME> <<EMAIL>> Depends SCVA, SCRT, SCMA Imports Rcmdr, tcltk Description Provides a GUI for the SCVA, SCRT and SCMA packages as de- scribed in Bulte and Onghena (2013) <doi:10.22237/jmasm/1383280020>. The package is writ- ten as an Rcmdr plugin. License GPL (>= 2) Repository CRAN NeedsCompilation no Date/Publication 2019-07-24 22:50:02 UTC R topics documented: RcmdrSCDAPlugin-packag... 1 RcmdrSCDAPlugin-package Install the SCDA Rcmdr Plug-In Description This package provides an Rcmdr "plug-in" for the SCVA, SCRT and SCMA packages. Details 1 Package: RcmdrSCDAPlugin Type: Package Version: 1.2.0 Date: 2019-07-01 License: GPL version 2 or newer Author(s) <NAME> and <NAME> Maintainer: <NAME> <<EMAIL>> See Also Rcmdr. Examples scores <- c(10,9,8,10,7,2,5,3,4,5) # Example data labels <- c("A","A","A","A","A","B","B","B","B","B") d <- data.frame(labels, scores) graph(design="AB", data=d) pvalue.systematic(design="AB", data=d, limit=1, statistic="A-B")
gopkg.in/go-toast/toast.v1
go
Go
README [¶](#section-readme) --- ### Toast A go package for Windows 10 toast notifications. As seen in [jacobmarshall/pokevision-cli](https://github.com/jacobmarshall/pokevision-cli). #### CLI As well as using go-toast within your Go projects, you can also utilise the CLI - for any of your projects. Download [64bit](https://go-toast-downloads.s3.amazonaws.com/v1/toast64.exe) or [32bit](https://go-toast-downloads.s3.amazonaws.com/v1/toast32.exe) ``` C:\Users\Example\Downloads\toast64.exe \ --app-id "Example App" \ --title "Hello World" \ --message "Lorem ipsum dolor sit amet, consectetur adipiscing elit." \ --icon "C:\Users\Example\Pictures\icon.png" \ --audio "default" --loop \ --duration "long" \ --activation-arg "https://google.com" \ --action "Open maps" --action-arg "bingmaps:?q=sushi" \ --action "Open browser" --action-arg "http://..." ``` ![CLI](https://github.com/go-toast/toast/raw/0a84660828b2/screenshot-cli.png) #### Example ``` package main import ( "log" "gopkg.in/toast.v1" ) func main() { notification := toast.Notification{ AppID: "Example App", Title: "My notification", Message: "Some message about how important something is...", Icon: "go.png", // This file must exist (remove this line if it doesn't) Actions: []toast.Action{ {"protocol", "I'm a button", ""}, {"protocol", "Me too!", ""}, }, } err := notification.Push() if err != nil { log.Fatalln(err) } } ``` #### Screenshots ![Toast](https://github.com/go-toast/toast/raw/0a84660828b2/screenshot-toast.png) ![Action centre](https://github.com/go-toast/toast/raw/0a84660828b2/screenshot-action-centre.png) Documentation [¶](#section-documentation) --- ### Index [¶](#pkg-index) * [Constants](#pkg-constants) * [Variables](#pkg-variables) * [func Audio(name string) (toastAudio, error)](#Audio) * [func Duration(name string) (toastDuration, error)](#Duration) * [type Action](#Action) * [type Notification](#Notification) * + [func (n *Notification) Push() error](#Notification.Push) ### Constants [¶](#pkg-constants) ``` const ( Default toastAudio = "ms-winsoundevent:Notification.Default" IM = "ms-winsoundevent:Notification.IM" Mail = "ms-winsoundevent:Notification.Mail" Reminder = "ms-winsoundevent:Notification.Reminder" SMS = "ms-winsoundevent:Notification.SMS" LoopingAlarm = "ms-winsoundevent:Notification.Looping.Alarm" LoopingAlarm2 = "ms-winsoundevent:Notification.Looping.Alarm2" LoopingAlarm3 = "ms-winsoundevent:Notification.Looping.Alarm3" LoopingAlarm4 = "ms-winsoundevent:Notification.Looping.Alarm4" LoopingAlarm5 = "ms-winsoundevent:Notification.Looping.Alarm5" LoopingAlarm6 = "ms-winsoundevent:Notification.Looping.Alarm6" LoopingAlarm7 = "ms-winsoundevent:Notification.Looping.Alarm7" LoopingAlarm8 = "ms-winsoundevent:Notification.Looping.Alarm8" LoopingAlarm9 = "ms-winsoundevent:Notification.Looping.Alarm9" LoopingAlarm10 = "ms-winsoundevent:Notification.Looping.Alarm10" LoopingCall = "ms-winsoundevent:Notification.Looping.Call" LoopingCall2 = "ms-winsoundevent:Notification.Looping.Call2" LoopingCall3 = "ms-winsoundevent:Notification.Looping.Call3" LoopingCall4 = "ms-winsoundevent:Notification.Looping.Call4" LoopingCall5 = "ms-winsoundevent:Notification.Looping.Call5" LoopingCall6 = "ms-winsoundevent:Notification.Looping.Call6" LoopingCall7 = "ms-winsoundevent:Notification.Looping.Call7" LoopingCall8 = "ms-winsoundevent:Notification.Looping.Call8" LoopingCall9 = "ms-winsoundevent:Notification.Looping.Call9" LoopingCall10 = "ms-winsoundevent:Notification.Looping.Call10" Silent = "silent" ) ``` ``` const ( Short toastDuration = "short" Long = "long" ) ``` ### Variables [¶](#pkg-variables) ``` var ( ErrorInvalidAudio [error](/builtin#error) = [errors](/errors).[New](/errors#New)("toast: invalid audio") ErrorInvalidDuration = [errors](/errors).[New](/errors#New)("toast: invalid duration") ) ``` ### Functions [¶](#pkg-functions) #### func [Audio](https://github.com/go-toast/toast/blob/0a84660828b2/toast.go#L262) [¶](#Audio) ``` func Audio(name [string](/builtin#string)) (toastAudio, [error](/builtin#error)) ``` Returns a toastAudio given a user-provided input (useful for cli apps). If the "name" doesn't match, then the default toastAudio is returned, along with ErrorInvalidAudio. The following names are valid; * default * im * mail * reminder * sms * loopingalarm * loopimgalarm[2-10] * loopingcall * loopingcall[2-10] * silent Handle the error appropriately according to how your app should work. #### func [Duration](https://github.com/go-toast/toast/blob/0a84660828b2/toast.go#L332) [¶](#Duration) ``` func Duration(name [string](/builtin#string)) (toastDuration, [error](/builtin#error)) ``` Returns a toastDuration given a user-provided input (useful for cli apps). The default duration is short. If the "name" doesn't match, then the default toastDuration is returned, along with ErrorInvalidDuration. Most of the time "short" is the most appropriate for a toast notification, and Microsoft recommend not using "long", but it can be useful for important dialogs or looping sound toasts. The following names are valid; * short * long Handle the error appropriately according to how your app should work. ### Types [¶](#pkg-types) #### type [Action](https://github.com/go-toast/toast/blob/0a84660828b2/toast.go#L190) [¶](#Action) ``` type Action struct { Type [string](/builtin#string) Label [string](/builtin#string) Arguments [string](/builtin#string) } ``` Action Defines an actionable button. See <https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-adaptive-interactive-toasts> for more info. Only protocol type action buttons are actually useful, as there's no way of receiving feedback from the user's choice. Examples of protocol type action buttons include: "bingmaps:?q=sushi" to open up Windows 10's maps app with a pre-populated search field set to "sushi". ``` toast.Action{"protocol", "Open Maps", "bingmaps:?q=sushi"} ``` #### type [Notification](https://github.com/go-toast/toast/blob/0a84660828b2/toast.go#L146) [¶](#Notification) ``` type Notification struct { // The name of your app. This value shows up in Windows 10's Action Centre, so make it // something readable for your users. It can contain spaces, however special characters // (eg. é) are not supported. AppID [string](/builtin#string) // The main title/heading for the toast notification. Title [string](/builtin#string) // The single/multi line message to display for the toast notification. Message [string](/builtin#string) // An optional path to an image on the OS to display to the left of the title & message. Icon [string](/builtin#string) // The type of notification level action (like toast.Action) ActivationType [string](/builtin#string) // The activation/action arguments (invoked when the user clicks the notification) ActivationArguments [string](/builtin#string) // Optional action buttons to display below the notification title & message. Actions [][Action](#Action) // The audio to play when displaying the toast Audio toastAudio // Whether to loop the audio (default false) Loop [bool](/builtin#bool) // How long the toast should show up for (short/long) Duration toastDuration } ``` Notification The toast notification data. The following fields are strongly recommended; * AppID * Title If no toastAudio is provided, then the toast notification will be silent. You can set the toast to have a default audio by setting "Audio" to "toast.Default", or if your go app takes user-provided input for audio, call the "toast.Audio(name)" func. The AppID is shown beneath the toast message (in certain cases), and above the notification within the Action Center - and is used to group your notifications together. It is recommended that you provide a "pretty" name for your app, and not something like "com.example.MyApp". If no Title is provided, but a Message is, the message will display as the toast notification's title - which is a slightly different font style (heavier). The Icon should be an absolute path to the icon (as the toast is invoked from a temporary path on the user's system, not the working directory). If you would like the toast to call an external process/open a webpage, then you can set ActivationArguments to the uri you would like to trigger when the toast is clicked. For example: "<https://google.com>" would open the Google homepage when the user clicks the toast notification. By default, clicking the toast just hides/dismisses it. The following would show a notification to the user letting them know they received an email, and opens gmail.com when they click the notification. It also makes the Windows 10 "mail" sound effect. ``` toast := toast.Notification{ AppID: "Google Mail", Title: email.Subject, Message: email.Preview, Icon: "C:/Program Files/Google Mail/icons/logo.png", ActivationArguments: "https://gmail.com", Audio: toast.Mail, } err := toast.Push() ``` #### func (*Notification) [Push](https://github.com/go-toast/toast/blob/0a84660828b2/toast.go#L236) [¶](#Notification.Push) ``` func (n *[Notification](#Notification)) Push() [error](/builtin#error) ``` Builds the Windows PowerShell script & invokes it, causing the toast to display. Note: Running the PowerShell script is by far the slowest process here, and can take a few seconds in some cases. ``` notification := toast.Notification{ AppID: "Example App", Title: "My notification", Message: "Some message about how important something is...", Icon: "go.png", Actions: []toast.Action{ {"protocol", "I'm a button", ""}, {"protocol", "Me too!", ""}, }, } err := notification.Push() if err != nil { log.Fatalln(err) } ```
pyperformance
readthedoc
TOML
Python Performance Benchmark Suite 1.0.6 documentation The Python Performance Benchmark Suite[¶](#the-python-performance-benchmark-suite) === The `pyperformance` project is intended to be an authoritative source of benchmarks for all Python implementations. The focus is on real-world benchmarks, rather than synthetic benchmarks, using whole applications when possible. * [pyperformance documentation](http://pyperformance.readthedocs.io/) * [pyperformance GitHub project](https://github.com/python/pyperformance) (source code, issues) * [Download pyperformance on PyPI](https://pypi.python.org/pypi/pyperformance) pyperformance is distributed under the MIT license. Documenation: Usage[¶](#usage) --- ### Installation[¶](#installation) Command to install pyperformance: ``` python3 -m pip install pyperformance ``` The command installs a new `pyperformance` program. If needed, `pyperf` and `six` dependencies are installed automatically. pyperformance works on Python 3.6 and newer, but it may work on Python 3.4 and 3.5. At runtime, Python development files (header files) may be needed to install some dependencies like `dulwich_log` or `psutil`, to build their C extension. Commands on Fedora to install dependencies: * Python 3: `sudo dnf install python3-devel` * PyPy: `sudo dnf install pypy-devel` #### Windows notes[¶](#windows-notes) On Windows, to allow pyperformance to build dependencies from source like `greenlet`, `dulwich` or `psutil`, if you want to use a `python.exe` built from source, you should not use the `python.exe` directly. Instead, you must run the little-known command `PC\layout` to create a filesystem layout that resembles an installed Python: ``` .\python.bat -m PC.layout --preset-default --copy installed -v ``` (Use the `--help` flag for more info about `PC\layout`.) Now you can use the “installed” Python executable: ``` installed\python.exe -m pip install pyperformance installed\python.exe -m pyperformance run ... ``` Using an *actually* installed Python executable (e.g. via `py`) works fine too. ### Run benchmarks[¶](#run-benchmarks) Commands to compare Python 3.6 and Python 3.7 performance: ``` pyperformance run --python=python3.6 -o py36.json pyperformance run --python=python3.7 -o py38.json pyperformance compare py36.json py38.json ``` Note: `python3 -m pyperformance ...` syntax works as well (ex: `python3 -m pyperformance run -o py38.json`), but requires to install pyperformance on each tested Python version. JSON files are produced by the pyperf module and so can be analyzed using pyperf commands: ``` python3 -m pyperf show py36.json python3 -m pyperf check py36.json python3 -m pyperf metadata py36.json python3 -m pyperf stats py36.json python3 -m pyperf hist py36.json python3 -m pyperf dump py36.json (...) ``` It’s also possible to use pyperf to compare results of two JSON files: ``` python3 -m pyperf compare_to py36.json py38.json --table ``` #### Basic commands[¶](#basic-commands) pyperformance actions: ``` run Run benchmarks on the running python show Display a benchmark file compare Compare two benchmark files list List benchmarks of the running Python list_groups List benchmark groups of the running Python venv Actions on the virtual environment ``` #### Common options[¶](#common-options) Options available to all commands: ``` -h, --help show this help message and exit ``` #### run[¶](#run) Run benchmarks on the running python. Usage: ``` pyperformance run [-h] [-r] [-f] [--debug-single-value] [-v] [-m] [--affinity CPU_LIST] [-o FILENAME] [--append FILENAME] [--manifest MANIFEST] [-b BM_LIST] [--inherit-environ VAR_LIST] [-p PYTHON] ``` options: ``` -h, --help show this help message and exit -r, --rigorous Spend longer running tests to get more accurate results -f, --fast Get rough answers quickly --debug-single-value Debug: fastest mode, only compute a single value -v, --verbose Print more output -m, --track-memory Track memory usage. This only works on Linux. --affinity CPU_LIST Specify CPU affinity for benchmark runs. This way, benchmarks can be forced to run on a given CPU to minimize run to run variation. -o FILENAME, --output FILENAME Run the benchmarks on only one interpreter and write benchmark into FILENAME. Provide only baseline_python, not changed_python. --append FILENAME Add runs to an existing file, or create it if it doesn't exist --manifest MANIFEST benchmark manifest file to use -b BM_LIST, --benchmarks BM_LIST Comma-separated list of benchmarks to run. Can contain both positive and negative arguments: --benchmarks=run_this,also_this,-not_this. If there are no positive arguments, we'll run all benchmarks except the negative arguments. Otherwise we run only the positive arguments. --inherit-environ VAR_LIST Comma-separated list of environment variable names that are inherited from the parent environment when running benchmarking subprocesses. -p PYTHON, --python PYTHON Python executable (default: use running Python) ``` #### show[¶](#show) Display a benchmark file. Usage: ``` show FILENAME ``` positional arguments: ``` FILENAME ``` #### compare[¶](#compare) Compare two benchmark files. Usage: ``` pyperformance compare [-h] [-v] [-O STYLE] [--csv CSV_FILE] [--inherit-environ VAR_LIST] [-p PYTHON] baseline_file.json changed_file.json ``` positional arguments: ``` baseline_file.json changed_file.json ``` options: ``` -v, --verbose Print more output -O STYLE, --output_style STYLE What style the benchmark output should take. Valid options are 'normal' and 'table'. Default is normal. --csv CSV_FILE Name of a file the results will be written to, as a three-column CSV file containing minimum runtimes for each benchmark. --inherit-environ VAR_LIST Comma-separated list of environment variable names that are inherited from the parent environment when running benchmarking subprocesses. -p PYTHON, --python PYTHON Python executable (default: use running Python) ``` #### list[¶](#list) List benchmarks of the running Python. Usage: ``` pyperformance list [-h] [--manifest MANIFEST] [-b BM_LIST] [--inherit-environ VAR_LIST] [-p PYTHON] ``` options: ``` --manifest MANIFEST benchmark manifest file to use -b BM_LIST, --benchmarks BM_LIST Comma-separated list of benchmarks to run. Can contain both positive and negative arguments: --benchmarks=run_this,also_this,-not_this. If there are no positive arguments, we'll run all benchmarks except the negative arguments. Otherwise we run only the positive arguments. --inherit-environ VAR_LIST Comma-separated list of environment variable names that are inherited from the parent environment when running benchmarking subprocesses. -p PYTHON, --python PYTHON Python executable (default: use running Python) ``` Use `python3 -m pyperformance list -b all` to list all benchmarks. #### list_groups[¶](#list-groups) List benchmark groups of the running Python. Usage: ``` pyperformance list_groups [-h] [--manifest MANIFEST] [--inherit-environ VAR_LIST] [-p PYTHON] ``` options: ``` --manifest MANIFEST benchmark manifest file to use --inherit-environ VAR_LIST Comma-separated list of environment variable names that are inherited from the parent environment when running benchmarking subprocesses. -p PYTHON, --python PYTHON Python executable (default: use running Python) ``` #### venv[¶](#venv) Actions on the virtual environment. Actions: ``` show Display the path to the virtual environment and its status (created or not) create Create the virtual environment recreate Force the recreation of the the virtual environment remove Remove the virtual environment ``` Common options: ``` --venv VENV Path to the virtual environment --inherit-environ VAR_LIST Comma-separated list of environment variable names that are inherited from the parent environment when running benchmarking subprocesses. -p PYTHON, --python PYTHON Python executable (default: use running Python) ``` ##### venv show[¶](#venv-show) Display the path to the virtual environment and its status (created or not). Usage: ``` pyperformance venv show [-h] [--venv VENV] [--inherit-environ VAR_LIST] [-p PYTHON] ``` ##### venv create[¶](#venv-create) Create the virtual environment. Usage: ``` pyperformance venv create [-h] [--venv VENV] [--manifest MANIFEST] [-b BM_LIST] [--inherit-environ VAR_LIST] [-p PYTHON] ``` options: ``` --manifest MANIFEST benchmark manifest file to use -b BM_LIST, --benchmarks BM_LIST Comma-separated list of benchmarks to run. Can contain both positive and negative arguments: --benchmarks=run_this,also_this,-not_this. If there are no positive arguments, we'll run all benchmarks except the negative arguments. Otherwise we run only the positive arguments. ``` ##### venv recreate[¶](#venv-recreate) Force the recreation of the the virtual environment. Usage: ``` pyperformance venv recreate [-h] [--venv VENV] [--manifest MANIFEST] [-b BM_LIST] [--inherit-environ VAR_LIST] [-p PYTHON] ``` options: ``` --manifest MANIFEST benchmark manifest file to use -b BM_LIST, --benchmarks BM_LIST Comma-separated list of benchmarks to run. Can contain both positive and negative arguments: --benchmarks=run_this,also_this,-not_this. If there are no positive arguments, we'll run all benchmarks except the negative arguments. Otherwise we run only the positive arguments. ``` ##### venv remove[¶](#venv-remove) Remove the virtual environment. Usage: ``` pyperformance venv remove [-h] [--venv VENV] [--inherit-environ VAR_LIST] [-p PYTHON] ``` ### Compile Python to run benchmarks[¶](#compile-python-to-run-benchmarks) pyperformance actions: ``` compile Compile and install CPython and run benchmarks on installed Python compile_all Compile and install CPython and run benchmarks on installed Python on all branches and revisions of CONFIG_FILE upload Upload JSON results to a Codespeed website ``` All these commands require a configuration file. Simple configuration usable for `compile` (but not for `compile_all` nor `upload`), `doc/benchmark.conf`: ``` [config] json_dir = ~/prog/python/bench_json [scm] repo_dir = ~/prog/python/master update = True [compile] bench_dir = ~/prog/python/bench_tmpdir [run_benchmark] system_tune = True affinity = 2,3 ``` Configuration file sample with comments, `doc/benchmark.conf.sample`: ``` [config] # Directory where JSON files are written. # - uploaded files are moved to json_dir/uploaded/ # - results of patched Python are written into json_dir/patch/ json_dir = ~/json # If True, compile CPython is debug mode (LTO and PGO disabled), # run benchmarks with --debug-single-sample, and disable upload. # # Use this option used to quickly test a configuration. debug = False [scm] # Directory of CPython source code (Git repository) repo_dir = ~/cpython # Update the Git repository (git fetch)? update = True # Name of the Git remote, used to create revision of # the Git branch. For example, use revision 'remotes/origin/3.6' # for the branch '3.6'. git_remote = remotes/origin [compile] # Create files into bench_dir: # - bench_dir/bench-xxx.log # - bench_dir/prefix/: where Python is installed # - bench_dir/venv/: Virtual environment used by pyperformance bench_dir = ~/bench_tmpdir # Link Time Optimization (LTO)? lto = True # Profiled Guided Optimization (PGO)? pgo = True # The space-separated list of libraries that are package-only, # i.e., locally installed but not on header and library paths. # For each such library, determine the install path and add an # appropriate subpath to CFLAGS and LDFLAGS declarations passed # to configure. As an exception, the prefix for openssl, if that # library is present here, is passed via the --with-openssl # option. Currently, this only works with Homebrew on macOS. # If running on macOS with Homebrew, you probably want to use: # pkg_only = openssl readline sqlite3 xz zlib # The version of zlib shipping with macOS probably works as well, # as long as Apple's SDK headers are installed. pkg_only = # Install Python? If false, run Python from the build directory # # WARNING: Running Python from the build directory introduces subtle changes # compared to running an installed Python. Moreover, creating a virtual # environment using a Python run from the build directory fails in many cases, # especially on Python older than 3.4. Only disable installation if you # really understand what you are doing! install = True [run_benchmark] # Run "sudo python3 -m pyperf system tune" before running benchmarks? system_tune = True # --manifest option for 'pyperformance run' manifest = # --benchmarks option for 'pyperformance run' benchmarks = # --affinity option for 'pyperf system tune' and 'pyperformance run' affinity = # Upload generated JSON file? # # Upload is disabled on patched Python, in debug mode or if install is # disabled. upload = False # Specify '-j' parameter in 'make' command jobs = 8 # Configuration to upload results to a Codespeed website [upload] url = environment = executable = project = [compile_all] # List of CPython Git branches branches = default 3.6 3.5 2.7 # List of revisions to benchmark by compile_all [compile_all_revisions] # list of 'sha1=' (default branch: 'master') or 'sha1=branch' # used by the "pyperformance compile_all" command # e.g.: 11159d2c9d6616497ef4cc62953a5c3cc8454afb = ``` #### compile[¶](#compile) Compile Python, install Python and run benchmarks on the installed Python. Usage: ``` pyperformance compile [-h] [--patch PATCH] [-U] [-T] [--inherit-environ VAR_LIST] [-p PYTHON] config_file revision [branch] ``` positional arguments: ``` config_file Configuration filename revision Python benchmarked revision branch Git branch ``` options: ``` --patch PATCH Patch file -U, --no-update Don't update the Git repository -T, --no-tune Don't run 'pyperf system tune' to tune the system for benchmarks --inherit-environ VAR_LIST Comma-separated list of environment variable names that are inherited from the parent environment when running benchmarking subprocesses. -p PYTHON, --python PYTHON Python executable (default: use running Python) ``` Notes: * PGO is broken on Ubuntu 14.04 LTS with GCC 4.8.4-2ubuntu1~14.04: `Modules/socketmodule.c:7743:1: internal compiler error: in edge_badness, at ipa-inline.c:895` #### compile_all[¶](#compile-all) Compile all branches and revisions of CONFIG_FILE. Usage: ``` pyperformance compile_all [-h] [--inherit-environ VAR_LIST] [-p PYTHON] config_file ``` positional arguments: ``` config_file Configuration filename ``` options: ``` --inherit-environ VAR_LIST Comma-separated list of environment variable names that are inherited from the parent environment when running benchmarking subprocesses. -p PYTHON, --python PYTHON Python executable (default: use running Python) ``` #### upload[¶](#upload) Upload results from a JSON file to a Codespeed website. Usage: ``` pyperformance upload [-h] [--inherit-environ VAR_LIST] [-p PYTHON] config_file json_file ``` positional arguments: ``` config_file Configuration filename json_file JSON filename ``` options: ``` --inherit-environ VAR_LIST Comma-separated list of environment variable names that are inherited from the parent environment when running benchmarking subprocesses. -p PYTHON, --python PYTHON Python executable (default: use running Python) ``` ### How to get stable benchmarks[¶](#how-to-get-stable-benchmarks) * Run `python3 -m pyperf system tune` command * Compile Python using LTO (Link Time Optimization) and PGO (profile guided optimizations): use the [pyperformance compile](#cmd-compile) command with uses LTO and PGO by default * See advices of the pyperf documentation: [How to get reproductible benchmark results](http://pyperf.readthedocs.io/en/latest/run_benchmark.html#how-to-get-reproductible-benchmark-results). ### pyperformance virtual environment[¶](#pyperformance-virtual-environment) To run benchmarks, pyperformance first creates a virtual environment. It installs requirements with fixed versions to get a reproductible environment. The system Python has unknown module installed with unknown versions, and can have `.pth` files run at Python startup which can modify Python behaviour or at least slow down Python startup. ### What is the goal of pyperformance[¶](#what-is-the-goal-of-pyperformance) A benchmark is always written for a specific purpose. Depending how the benchmark is written and how the benchmark is run, the result can be different and so have a different meaning. The pyperformance benchmark suite has multiple goals: * Help to detect performance regression in a Python implementation * Validate that an optimization change makes Python faster and don’t performance regressions, or only minor regressions * Compare two implementations of Python, for example CPython and PyPy * Showcase of Python performance which ideally would be representative of performances of applications running on production #### Don’t disable GC nor ASLR[¶](#don-t-disable-gc-nor-aslr) The pyperf module and pyperformance benchmarks are designed to produce reproductible results, but not at the price of running benchmarks in a special mode which would not be used to run applications in production. For these reasons, the Python garbage collector, Python randomized hash function and system ASLR (Address Space Layout Randomization) are **not disabled**. Benchmarks don’t call `gc.collect()` neither since CPython implements it with [stop-the-world](https://en.wikipedia.org/wiki/Tracing_garbage_collection#Stop-the-world_vs._incremental_vs._concurrent) and so applications don’t call it to not kill performances. #### Include outliers and spikes[¶](#include-outliers-and-spikes) Moreover, while the pyperf documentation explains how to reduce the random noise of the system and other applications, some benchmarks use the system and so can get different timing depending on the system workload, depending on I/O performances, etc. Outliers and temporary spikes in results are **not automatically removed**: values are summarized by computing the average (arithmetic mean) and standard deviation which “contains” these spikes, instead of using median and the median absolute deviation for example which to ignore outliers. It is deliberate choice since applications running in production are impacted by such temporary slowdown caused by various things like a garbage collection or a JIT compilation. #### Warmups and steady state[¶](#warmups-and-steady-state) A borderline issue are the benchmarks “warmups”. The first values of each worker process are always slower: 10% slower in the best case, it can be 1000% slower or more on PyPy. Right now (2017-04-14), pyperformance ignore first values considered as warmup until a benchmark reachs its “steady state”. The “steady state” can include temporary spikes every 5 values (ex: caused by the garbage collector), and it can still imply further JIT compiler optimizations but with a “low” impact on the average pyperformance. To be clear “warmup” and “steady state” are a work-in-progress and a very complex topic, especially on PyPy and its JIT compiler. ### Notes[¶](#notes) Tool for comparing the performance of two Python implementations. pyperformance will run Student’s two-tailed T test on the benchmark results at the 95% confidence level to indicate whether the observed difference is statistically significant. Omitting the `-b` option will result in the default group of benchmarks being run Omitting `-b` is the same as specifying -b default. To run every benchmark pyperformance knows about, use `-b all`. To see a full list of all available benchmarks, use –help. Negative benchmarks specifications are also supported: -b -2to3 will run every benchmark in the default group except for 2to3 (this is the same as -b default,-2to3). -b all,-django will run all benchmarks except the Django templates benchmark. Negative groups (e.g., -b -default) are not supported. Positive benchmarks are parsed before the negative benchmarks are subtracted. If `--track_memory` is passed, pyperformance will continuously sample the benchmark’s memory usage. This currently only works on Linux 2.6.16 and higher or Windows with PyWin32. Because `--track_memory` introduces performance jitter while collecting memory measurements, only memory usage is reported in the final report. Benchmarks[¶](#benchmarks) --- Also see [Custom Benchmarks](index.html#document-custom_benchmarks) regarding how to create your own benchmarks or use someone else’s. ### Available Groups[¶](#available-groups) Like individual benchmarks (see “Available benchmarks” below), benchmarks group are allowed after the -b option. Use `python3 -m pyperformance list_groups` to list groups and their benchmarks. Available benchmark groups: * `all`: Group including all benchmarks * `apps`: “High-level” applicative benchmarks (2to3, Chameleon, Tornado HTTP) * `default`: Group of benchmarks run by default by the `run` command * `math`: Float and integers * `regex`: Collection of regular expression benchmarks * `serialize`: Benchmarks on `pickle` and `json` modules * `startup`: Collection of microbenchmarks focused on Python interpreter start-up time. * `template`: Templating libraries Use the `python3 -m pyperformance list_groups` command to list groups and their benchmarks. ### Available Benchmarks[¶](#available-benchmarks) In pyperformance 0.5.5, the following microbenchmarks have been removed because they are too short, not representative of real applications and are too unstable. * `call_method_slots` * `call_method_unknown` * `call_method` * `call_simple` * `pybench` #### 2to3[¶](#to3) Run the 2to3 tool on the `pyperformance/benchmarks/data/2to3/` directory: copy of the `django/core/*.py` files of Django 1.1.4, 9 files. Run the `python -m lib2to3 -f all <files>` command where `python` is `sys.executable`. So the test does not only mesure the performance of Python itself, but also the performance of the `lib2to3` module which can change depending on the Python version. Note Files are called `.py.txt` instead of `.py` to not run PEP 8 checks on them, and more generally to not modify them. #### async_tree[¶](#async-tree) Async workload benchmark, which calls `asyncio.gather()` on a tree (6 levels deep, 6 branches per level) with the leaf nodes simulating some [potentially] async work (depending on the benchmark variant). Available variants: * `async_tree`: no actual async work at any leaf node. * `async_tree_io`: all leaf nodes simulate async IO workload (async sleep 50ms). * `async_tree_memoization`: all leaf nodes simulate async IO workload with 90% of the data memoized. * `async_tree_cpu_io_mixed`: half of the leaf nodes simulate CPU-bound workload (`math.factorial(500)`) and the other half simulate the same workload as the `async_tree_memoization` variant. These benchmarks also have an “eager” flavor that uses asyncio eager task factory, if available. #### chameleon[¶](#chameleon) Render a template using the `chameleon` module to create an HTML table of 500 lignes and 10 columns. See the `chameleon.PageTemplate` class. #### chaos[¶](#chaos) Create chaosgame-like fractals. Command lines options: ``` --thickness THICKNESS Thickness (default: 0.25) --width WIDTH Image width (default: 256) --height HEIGHT Image height (default: 256) --iterations ITERATIONS Number of iterations (default: 5000) --filename FILENAME.PPM Output filename of the PPM picture --rng-seed RNG_SEED Random number generator seed (default: 1234) ``` When `--filename` option is used, the timing includes the time to create the PPM file. Copyright (C) 2005 <NAME> Image generated by bm_chaos (took 3 sec on CPython 3.5) with the command: ``` python3 pyperformance/benchmarks/bm_chaos.py --worker -l1 -w0 -n1 --filename chaos.ppm --width=512 --height=512 --iterations 50000 ``` #### crypto_pyaes[¶](#crypto-pyaes) benchmark a pure-Python implementation of the AES block-cipher in CTR mode using the `pyaes` module. The benchmark is slower on CPython 3 compared to CPython 2.7, because CPython 3 has no more “small int” type (`int`). The CPython 3 `int` type now always has an arbitrary size, as CPython 2.7 `long` type. See [pyaes](https://github.com/ricmoo/pyaes): A pure-Python implementation of the AES block cipher algorithm and the common modes of operation (CBC, CFB, CTR, ECB and OFB). #### deepcopy[¶](#deepcopy) Benchmark the Python copy.deepcopy method. The deepcopy method is performed on a nested dictionary and a dataclass. #### deltablue[¶](#deltablue) DeltaBlue benchmark Ported for the PyPy project. Contributed by <NAME> This implementation of the DeltaBlue benchmark was directly ported from the [V8’s source code](https://github.com/v8/v8/blob/master/benchmarks/deltablue.js), which was in turn derived from the Smalltalk implementation by <NAME> and <NAME>. The original Javascript implementation was licensed under the GPL. It’s been updated in places to be more idiomatic to Python (for loops over collections, a couple magic methods, `OrderedCollection` being a list & things altering those collections changed to the builtin methods) but largely retains the layout & logic from the original. (Ugh.) #### django_template[¶](#django-template) Use the Django template system to build a 150x150-cell HTML table. Use `Context` and `Template` classes of the `django.template` module. #### dulwich_log[¶](#dulwich-log) Iterate on commits of the asyncio Git repository using the Dulwich module. Use `pyperformance/benchmarks/data/asyncio.git/` repository. Pseudo-code of the benchmark: ``` repo = dulwich.repo.Repo(repo_path) head = repo.head() for entry in repo.get_walker(head): pass ``` See the [Dulwich project](https://www.dulwich.io/). #### docutils[¶](#docutils) Use [Docutils](https://docutils.sourceforge.io/) to convert Docutils’ documentation to HTML. Representative of building a medium-sized documentation set. #### fannkuch[¶](#fannkuch) The Computer Language Benchmarks Game: <http://benchmarksgame.alioth.debian.org/Contributed by <NAME>, modified by Tupteq. #### float[¶](#float) Artificial, floating point-heavy benchmark originally used by Factor. Create 100,000 point objects which compute `math.cos()`, `math.sin()` and `math.sqrt()` Changed in version 0.5.5: Use `__slots__` on the Point class to focus the benchmark on float rather than testing performance of class attributes. #### genshi[¶](#genshi) Render a template using Genshi (`genshi.template` module): * `genshi_text`: Render a HTML template using the `NewTextTemplate` class * `genshi_xml`: Render an XML template using the `MarkupTemplate` class See the [Genshi project](http://pythonhosted.org/Genshi/). #### go[¶](#go) Artificial intelligence playing the Go board game. Use [Zobrist hashing](https://en.wikipedia.org/wiki/Zobrist_hashing). #### hexiom[¶](#hexiom) Solver of Hexiom board game (level 25 by default). Command line option: ``` --level {2,10,20,25,30,36} Hexiom board level (default: 25) ``` #### hg_startup[¶](#hg-startup) Get Mercurial’s help screen. Measure the performance of the `python path/to/hg help` command using `pyperf.Runner.bench_command()`, where `python` is `sys.executable` and `path/to/hg` is the Mercurial program installed in a virtual environmnent. The `bench_command()` redirects stdout and stderr into `/dev/null`. See the [Mercurial project](https://www.mercurial-scm.org/). #### html5lib[¶](#html5lib) Parse the `pyperformance/benchmarks/data/w3_tr_html5.html` HTML file (132 KB) using `html5lib`. The file is the HTML 5 specification, but truncated to parse the file in less than 1 second (around 250 ms). On CPython, after 3 warmups, the benchmarks enters a cycle of 5 values: every 5th value is 10% slower. Plot of 1 run of 50 values (the warmup is not rendered): See the [html5lib project](https://html5lib.readthedocs.io/). #### json_dumps, json_loads[¶](#json-dumps-json-loads) Benchmark `dumps()` and `loads()` functions of the `json` module. `bm_json_dumps.py` command line option: ``` --cases CASES Comma separated list of cases. Available cases: EMPTY, SIMPLE, NESTED, HUGE. By default, run all cases. ``` #### logging[¶](#logging) Benchmarks on the `logging` module: * `logging_format`: Benchmark `logger.warn(fmt, str)` * `logging_simple`: Benchmark `logger.warn(msg)` * `logging_silent`: Benchmark `logger.debug(msg)` when the log is ignored Script command line option: ``` format silent simple ``` See the [logging module](https://docs.python.org/dev/library/logging.html). #### mako[¶](#mako) Use the Mako template system to build a 150x150-cell HTML table. Includes: * two template inherences * HTML escaping, XML escaping, URL escaping, whitespace trimming * function defitions and calls * forloops See the [Mako project](http://docs.makotemplates.org/). #### mdp[¶](#mdp) Battle with damages and topological sorting of nodes in a graph. See [Topological sorting](https://en.wikipedia.org/wiki/Topological_sorting). #### meteor_contest[¶](#meteor-contest) Solver for Meteor Puzzle board. Meteor Puzzle board: <http://benchmarksgame.alioth.debian.org/u32/meteor-description.html#meteorThe Computer Language Benchmarks Game: <http://benchmarksgame.alioth.debian.org/Contributed by <NAME>, 2008-08-21. #### nbody[¶](#nbody) N-body benchmark from the Computer Language Benchmarks Game. Microbenchmark on floating point operations. This is intended to support Unladen Swallow’s perf.py. Accordingly, it has been modified from the Shootout version: * Accept standard Unladen Swallow benchmark options. * Run report_energy()/advance() in a loop. * Reimplement itertools.combinations() to work with older Python versions. Pulled from: <http://benchmarksgame.alioth.debian.org/u64q/program.php?test=nbody&lang=python3&id=1Contributed by <NAME>. Modified by Tupteq, <NAME>, and <NAME>. #### python_startup, python_startup_nosite[¶](#python-startup-python-startup-nosite) * `python_startup`: Measure the Python startup time, run `python -c pass` where `python` is `sys.executable` * `python_startup_nosite`: Measure the Python startup time without importing the `site` module, run `python -S -c pass` where `python` is `sys.executable` Run the benchmark with `pyperf.Runner.bench_command()`. #### nqueens[¶](#nqueens) Simple, brute-force N-Queens solver. See [Eight queens puzzle](https://en.wikipedia.org/wiki/Eight_queens_puzzle). #### pathlib[¶](#pathlib) Test the performance of operations of the `pathlib` module of the standard library. This benchmark stresses the creation of small objects, globbing, and system calls. See the [documentation of the pathlib module](https://docs.python.org/dev/library/pathlib.html). #### pickle[¶](#pickle) pickle benchmarks (serialize): * `pickle`: use the cPickle module to pickle a variety of datasets. * `pickle_dict`: microbenchmark; use the cPickle module to pickle a lot of dicts. * `pickle_list`: microbenchmark; use the cPickle module to pickle a lot of lists. * `pickle_pure_python`: use the pure-Python pickle module to pickle a variety of datasets. unpickle benchmarks (deserialize): * `unpickle`: use the cPickle module to unnpickle a variety of datasets. * `unpickle_list` * `unpickle_pure_python`: use the pure-Python pickle module to unpickle a variety of datasets. #### pidigits[¶](#pidigits) Calculating 2,000 digits of π. This benchmark stresses big integer arithmetic. Command line option: ``` --digits DIGITS Number of computed pi digits (default: 2000) ``` Adapted from code on: <http://benchmarksgame.alioth.debian.org/#### pyflate[¶](#pyflate) Benchmark of a pure-Python bzip2 decompressor: decompress the `pyperformance/benchmarks/data/interpreter.tar.bz2` file in memory. Copyright 2006–2007-01-21 <NAME>: <http://www.paul.sladen.org/projects/compression/You may use and distribute this code under any DFSG-compatible license (eg. BSD, GNU GPLv2). Stand-alone pure-Python DEFLATE (gzip) and bzip2 decoder/decompressor. This is probably most useful for research purposes/index building; there is certainly some room for improvement in the Huffman bit-matcher. With the as-written implementation, there was a known bug in BWT decoding to do with repeated strings. This has been worked around; see ‘bwt_reverse()’. Correct output is produced in all test cases but ideally the problem would be found… #### raytrace[¶](#raytrace) Simple raytracer. Command line options: ``` --width WIDTH Image width (default: 100) --height HEIGHT Image height (default: 100) --filename FILENAME.PPM Output filename of the PPM picture ``` This file contains definitions for a simple raytracer. Copyright Callum and <NAME>, 2008. This file may be freely redistributed under the MIT license, <http://www.opensource.org/licenses/mit-license.phpFrom <http://www.lshift.net/blog/2008/10/29/toy-raytracer-in-pythonImage generated by the command (took 68.4 sec on CPython 3.5): ``` python3 pyperformance/benchmarks/bm_raytrace.py --worker --filename=raytrace.ppm -l1 -w0 -n1 -v --width=800 --height=600 ``` #### regex_compile[¶](#regex-compile) Stress the performance of Python’s regex compiler, rather than the regex execution speed. Benchmark how quickly Python’s regex implementation can compile regexes. We bring in all the regexes used by the other regex benchmarks, capture them by stubbing out the re module, then compile those regexes repeatedly. We muck with the re module’s caching to force it to recompile every regex we give it. #### regex_dna[¶](#regex-dna) regex DNA benchmark using “fasta” to generate the test case. The Computer Language Benchmarks Game <http://benchmarksgame.alioth.debian.org/regex-dna Python 3 #5 program: contributed by <NAME> 2to3 modified by <NAME> fasta Python 3 #3 program: modified by <NAME> modified again by <NAME> modified by <NAME> Modified by <NAME> #### regex_effbot[¶](#regex-effbot) Some of the original benchmarks used to tune mainline Python’s current regex engine. #### regex_v8[¶](#regex-v8) Python port of V8’s regex benchmark. Automatically generated on 2009-01-30. This benchmark is generated by loading 50 of the most popular pages on the web and logging all regexp operations performed. Each operation is given a weight that is calculated from an estimate of the popularity of the pages where it occurs and the number of times it is executed while loading each page. Finally the literal letters in the data are encoded using ROT13 in a way that does not affect how the regexps match their input. Ported to Python for Unladen Swallow. The original JS version can be found at <https://github.com/v8/v8/blob/master/benchmarks/regexp.js>, r1243. #### richards[¶](#richards) The classic Python Richards benchmark. Based on a Java version. Based on original version written in BCPL by Dr <NAME> in 1981 at Cambridge University Computer Laboratory, England and a C++ version derived from a Smalltalk version written by <NAME>. Java version: Copyright (C) 1995 Sun Microsystems, Inc. Translation from C++, <NAME> Outer loop added by <NAME> #### scimark[¶](#scimark) * `scimark_sor`: [Successive over-relaxation (SOR)](https://en.wikipedia.org/wiki/Successive_over-relaxation) benchmark * `scimark_sparse_mat_mult`: [sparse matrix](https://en.wikipedia.org/wiki/Sparse_matrix) [multiplication](https://en.wikipedia.org/wiki/Matrix_multiplication_algorithm) benchmark * `scimark_monte_carlo`: benchmark on the [Monte Carlo algorithm](https://en.wikipedia.org/wiki/Monte_Carlo_algorithm) to compute the area of a disc * `scimark_lu`: [LU decomposition](https://en.wikipedia.org/wiki/LU_decomposition) benchmark * `scimark_fft`: [Fast Fourier transform (FFT)](https://en.wikipedia.org/wiki/Fast_Fourier_transform) benchmark #### spectral_norm[¶](#spectral-norm) MathWorld: “Hundred-Dollar, Hundred-Digit Challenge Problems”, Challenge #3. <http://mathworld.wolfram.com/Hundred-DollarHundred-DigitChallengeProblems.htmlThe Computer Language Benchmarks Game <http://benchmarksgame.alioth.debian.org/u64q/spectralnorm-description.html#spectralnormContributed by <NAME>. Fixed by <NAME>. Sped up by <NAME>. Dirtily sped up by <NAME>. Concurrency by <NAME>. #### sqlalchemy_declarative, sqlalchemy_imperative[¶](#sqlalchemy-declarative-sqlalchemy-imperative) * `sqlalchemy_declarative`: SQLAlchemy Declarative benchmark using SQLite * `sqlalchemy_imperative`: SQLAlchemy Imperative benchmark using SQLite See the [SQLAlchemy project](https://www.sqlalchemy.org/). #### sqlite_synth[¶](#sqlite-synth) Benchmark Python aggregate for SQLite. The goal of the benchmark (written for PyPy) is to test CFFI performance and going back and forth between SQLite and Python a lot. Therefore the queries themselves are really simple. See the [SQLite project](https://www.sqlite.org/) and the [Python sqlite3 module (stdlib)](https://docs.python.org/dev/library/sqlite3.html). #### sympy[¶](#sympy) Benchmark on the `sympy` module: * `sympy_expand`: Benchmark `sympy.expand()` * `sympy_integrate`: Benchmark `sympy.integrate()` * `sympy_str`: Benchmark `str(sympy.expand())` * `sympy_sum`: Benchmark `sympy.summation()` On CPython, some `sympy_sum` values are 5%-10% slower: ``` $ python3 -m pyperf dump sympy_sum.json Run 1: 1 warmup, 50 values, 1 loop - warmup 1: 404 ms (+63%) - value 1: 244 ms - value 2: 245 ms - value 3: 258 ms <--- - value 4: 245 ms - value 5: 245 ms - value 6: 279 ms (+12%) <--- - value 7: 246 ms - value 8: 244 ms - value 9: 245 ms - value 10: 255 ms <--- - value 11: 245 ms - value 12: 245 ms - value 13: 256 ms <--- - value 14: 248 ms - value 15: 245 ms - value 16: 245 ms ... ``` Plot of 1 run of 50 values (the warmup is not rendered): See the [sympy project](http://www.sympy.org/). #### telco[¶](#telco) Telco Benchmark for measuring the performance of decimal calculations: * <http://speleotrove.com/decimal/telco.html> * <http://speleotrove.com/decimal/telcoSpec.html> * A call type indicator, `c`, is set from the bottom (least significant) bit of the duration (hence `c` is 0 or 1). * A rate, `r`, is determined from the call type. Those calls with `c=0` have a low `r`: `0.0013`; the remainder (‘distance calls’) have a ‘premium’ `r`: `0.00894`. (The rates are, very roughly, in Euros or dollarates per second.) * A price, `p`, for the call is then calculated (`p=r*n`). This is rounded to exactly 2 fractional digits using round-half-even (Banker’s round to nearest). * A basic tax, `b`, is calculated: `b=p*0.0675` (6.75%). This is truncated to exactly 2 fractional digits (round-down), and the total basic tax variable is then incremented (`sumB=sumB+b`). * For distance calls: a distance tax, `d`, is calculated: `d=p*0.0341` (3.41%). This is truncated to exactly 2 fractional digits (round-down), and then the total distance tax variable is incremented (`sumD=sumD+d`). * The total price, `t`, is calculated (`t=p+b`, and, if a distance call, `t=t+d`). * The total prices variable is incremented (`sumT=sumT+t`). * The total price, `t`, is converted to a string, `s`. The Python benchmark is implemented with the `decimal` module. See the [Python decimal module (stdlib)](https://docs.python.org/dev/library/decimal.html). #### tornado_http[¶](#tornado-http) Benchmark HTTP server of the `tornado` module See the [Tornado project](http://www.tornadoweb.org/). #### unpack_sequence[¶](#unpack-sequence) Microbenchmark for unpacking lists and tuples. Pseudo-code: ``` a, b, c, d, e, f, g, h, i, j = to_unpack ``` where `to_unpack` is `tuple(range(10))` or `list(range(10))`. #### xml_etree[¶](#xml-etree) Benchmark the `ElementTree` API of the `xml.etree` module: * `xml_etree_generate`: Create an XML document * `xml_etree_iterparse`: Benchmark `etree.iterparse()` * `xml_etree_parse`: Benchmark `etree.parse()` * `xml_etree_process`: Process an XML document See the [Python xml.etree.ElementTree module (stdlib)](https://docs.python.org/dev/library/xml.etree.elementtree.html). Custom Benchmarks[¶](#custom-benchmarks) --- pyperformance includes its own set of benchmarks (see [Benchmarks](index.html#document-benchmarks)). However, it also supports using custom benchmarks. ### Using Custom Benchmarks[¶](#using-custom-benchmarks) To use custom benchmarks, you will need to use the `--manifest` CLI option and provide the path to the manifest file describing those benchmarks. ### The pyperformance File Formats[¶](#the-pyperformance-file-formats) `pyperformance` uses two file formats to identify benchmarks: * manifest - a set of benchmarks * metadata - a single benchmark For each benchmark, there are two required files and several optional ones. Those files are expected to be in a specific directory structure (unless customized in the metadata). The structure (see below) is such that it’s easy to maintain a benchmark (or set of benchmarks) on GitHub and distribute it on PyPI. It also simplifies publishing a Python project’s benchmarks. The alternative is pointing people at a repo. Benchmarks can inherit metadata from other metadata files. This is useful for keeping common metadata for a set of benchmarks (e.g. “version”) in one file. Likewise, benchmarks for a Python project can inherit metadata from the project’s pyproject.toml. Sometimes a benchmark will have one or more variants that run using the same script. Variants like this are supported by `pyperformance` without requiring much extra effort. #### Benchmark Directory Structure[¶](#benchmark-directory-structure) Normally a benchmark is structured like this: ``` bm_NAME/ data/ # if needed requirements.txt # lock file, if any pyproject.toml run_benchmark.py ``` (Note the “bm_” prefix on the directory name.) “pyproject.toml” holds the metadata. “run_benchmark.py” holds the actual benchmark code. Both are necessary. `pyperformance` treats the metadata file as the fundamental source of information about a benchmark. A manifest for a set of benchmarks is effectively a mapping of names to metadata files. So a metadata file is essential. It can be located anywhere on disk. However, if it isn’t located in the structure described above then the metadata must identify where to find the other files. Other than that, only a benchmark script (e.g. “run_benchmark.py” above) is required. All other files are optional. When a benchmark has variants, each has its own metadata file next to the normal “pyproject.toml”, named “bm_NAME.toml”. (Note the “bm_” prefix.) The format of variant metadata files is exactly the same. `pyperformance` treats them the same, except that the sibling “pyproject.toml” is inherited by default. #### Manifest Files[¶](#manifest-files) A manifest file identifies a set of benchmarks, as well as (optionally) how they should be grouped. `pyperformance` uses the manifest to determine which benchmarks are available to run (and thus which to run by default). A manifest normally looks like this: ``` [benchmarks] name metafile bench1 somedir/bm_bench1/pyproject.toml bench2 somedir/pyproject.toml bench3 ../anotherdir ``` The “benchmarks” section is a table with rows of tab-separated-values. The “name” value is how `pyperformance` will identify the benchmark. The “metafile” value is where `pyperformance` will look for the benchmark’s metadata. If a metafile is a directory then it looks for “pyproject.toml” in that directory. ##### Benchmark Groups[¶](#benchmark-groups) The other sections in the manifest file relate to grouping: ``` [benchmarks] name metafile bench1 somedir/bm_bench1 bench2 somedir/bm_bench2 bench3 anotherdir/mybench.toml [groups] tag1 tag2 [group default] bench2 bench3 [group tricky] bench2 ``` The “groups” section specifies available groups that may be identified by benchmark tags (see about tags in the metadata section below). Any other group sections in the manifest are automatically added to the list of available groups. If no “default” group is specified then one is automatically added with all benchmarks from the “benchmarks” section in it. If there is no “groups” section and no individual group sections (other than “default”) then the set of all tags of the known benchmarks is treated as “groups”. A group named “all” as also automatically added which has all known benchmarks in it. Benchmarks can be excluded from a group by using a `-` (minus) prefix. Any benchmark alraedy in the list (at that point) that matches will be dropped from the list. If the first entry in the section is an exclusion then all known benchmarks are first added to the list before the exclusion is applied. For example: ``` [benchmarks] name metafile bench1 somedir/bm_bench1 bench2 somedir/bm_bench2 bench3 anotherdir/mybench.toml [group default] -bench1 ``` This means by default only “bench2” and “bench3” are run. ##### Merging Manifests[¶](#merging-manifests) To combine manifests, use the `[includes]` section in the manifest: ``` [includes] project1/benchmarks/MANIFEST project2/benchmarks/MANIFEST <default> ``` Note that `<default>` is the same as including the manifest file for the default pyperformance benchmarks. ##### A Local Benchmark Suite[¶](#a-local-benchmark-suite) Often a project will have more than one benchmark that it will treat as a suite. `pyperformance` handles this without any extra work. In the dirctory holding the manifest file put all the benchmarks. Then put `<local>` in the “metafile” column, like this: ``` [benchmarks] name metafile bench1 <local> bench2 <local> bench3 <local> bench4 <local> bench5 <local> ``` It will look for `DIR/bm_NAME/pyproject.toml`. If there are also variants, identify the main benchmark in the “metafile” value, like this: ``` [benchmarks] name metafile bench1 <local> bench2 <local> bench3 <local> variant1 <local:bench3> variant2 <local:bench3> ``` `pyperformance` will look for `DIR/bm_BASE/bm_NAME.toml`, where “BASE” is the part after “local:”. ##### A Project’s Benchmark Suite[¶](#a-project-s-benchmark-suite) A Python project can identify its benchmark suite by putting the path to the manifest file in the project’s top-level pyproject.toml. Additional manifests can be identified as well: ``` [tool.pyperformance] manifest = "..." manifests = ["...", "..."] ``` (Reminder: that is the pyproject.toml, not the manifest file.) #### Benchmark Metadata Files[¶](#benchmark-metadata-files) A benchmark’s metadata file (usually pyproject.toml) follows the format specified in [PEP 621](https://www.python.org/dev/peps/pep-0621) and [PEP 518](https://www.python.org/dev/peps/pep-0518). So there are two supported sections in the file: “project” and “tool.pyperformance”. A typical metadata file will look something like this: ``` [project] version = "0.9.1" dependencies = ["pyperf"] dynamic = ["name"] [tool.pyperformance] name = "my_benchmark" ``` A highly detailed one might look like this: ``` [project] name = "pyperformance_bm_json_dumps" version = "0.9.1" description = "A benchmark for json.dumps()" requires-python = ">=3.8" dependencies = ["pyperf"] urls = {repository = "https://github.com/python/pyperformance"} dynamic = ["version"] [tool.pyperformance] name = "json_dumps" tags = "serialize" runscript = "bench.py" datadir = ".data-files/extras" extra_opts = ["--special"] ``` ##### Inheritance[¶](#inheritance) For one benchmark to inherit from another (or from common metadata), the “inherits” field is available: ``` [project] dependencies = ["pyperf"] dynamic = ["name", "version"] [tool.pyperformance] name = "my_benchmark" inherits = "../common.toml" ``` All values in either section of the inherited metadata are treated as defaults, on top of which the current metadata is applied. In the above example, for instance, a value for “version” in common.toml would be used here. If the “inherits” value is a directory (even for “..”) then “base.toml” in that directory will be inherited. For variants, the base pyproject.toml is the default value for “inherits”. ##### Inferred Values[¶](#inferred-values) In some situations, omitted values will be inferred from other available data (even for required fields). * `project.name` <= `tool.pyperformance.name` * `project.*` <= inherited metadata (except for “name” and “dynamic”) * `tool.pyperformance.name` <= metadata filename * `tool.pyperformance.*` <= inherited metadata (except for “name” and “inherits”) When the name is inferred from the filename for a regularly structured benchmark, the “bm_” prefix is removed from the benchmark’s directory. If it is a variant that prefix is removed from the metadata filename, as well as the .toml suffix. ##### The `[project]` Section[¶](#the-project-section) | field | type | R | T | B | D | | --- | --- | --- | --- | --- | --- | | project.name | str | X | X | | | | project.version | ver | X | | X | X | | project.dependencies | [str] | | | X | | | project.dynamic | [str] | | | | | “R”: required “T”: inferred from the tool section “B”: inferred from the inherited metadata “D”: for default benchmarks, inferred from pyperformance “dynamic” is required by PEP 621 for when a field will be filled in dynamically by the tool. This is especially important for required fields. All other PEP 621 fields are optional (e.g. `requires-python = ">=3.8"`, `{repository = "https://github.com/..."}`). ##### The `[tool.pyperformance]` Section[¶](#the-tool-pyperformance-section) | field | type | R | B | F | | --- | --- | --- | --- | --- | | tool.name | str | X | | X | | tool.tags | [str] | | X | | | tool.extra_opts | [str] | | X | | | tool.inherits | file | | | | | tool.runscript | file | | X | | | tool.datadir | file | | X | | “R”: required “B”: inferred from the inherited metadata “F”: inferred from filename * tags: optional list of names to group benchmarks * extra_opts: optional list of args to pass to `tool.runscript` * runscript: the benchmark script to use instead of run_benchmark.py. CPython results, 2017[¶](#cpython-results-2017) --- This page lists benchmarks which became faster in CPython. ### Optimizations[¶](#optimizations) #### 2016-12-14: speedup method calls[¶](#speedup-method-calls) Optimization: [Speedup method calls 1.2x](https://bugs.python.org/issue26110), [commit f2392133](https://github.com/python/cpython/commit/f2392133eba777f05947a8996c507690b95379c3). | Benchmark | 2016-12-01 (27580c1fb5e8) | 2017-01-01 (67e1aa0b58be) | | --- | --- | --- | | call_method | 14.1 ms | 11.2 ms: 1.26x faster (-21%) | | call_method_slots | 13.9 ms | 11.1 ms: 1.25x faster (-20%) | | call_method_unknown | 16.0 ms | 14.3 ms: 1.12x faster (-11%) | #### 2016-04-22: pymalloc allocator[¶](#pymalloc-allocator) Optimization: [PyMem_Malloc() now uses the fast pymalloc allocator](http://bugs.python.org/issue26249), [commit f5c4b990](https://github.com/python/cpython/commit/f5c4b99034fae12ac2b9498dd12b5b3f352b90c8). Changes of at least 5%: | Benchmark | 2016-04-21 (5439fc4901db) | 2016-04-22 (f5c4b99034fa) | | --- | --- | --- | | unpickle_list | 10.4 us | 7.64 us: 1.36x faster (-27%) | | json_dumps | 28.0 ms | 25.2 ms: 1.11x faster (-10%) | | unpickle_pure_python | 741 us | 678 us: 1.09x faster (-9%) | | unpickle | 33.9 us | 31.3 us: 1.08x faster (-8%) | | meteor_contest | 197 ms | 183 ms: 1.08x faster (-7%) | | mako | 36.9 ms | 34.3 ms: 1.07x faster (-7%) | | pathlib | 41.0 ms | 38.4 ms: 1.07x faster (-6%) | | call_method_slots | 14.8 ms | 13.9 ms: 1.07x faster (-6%) | | telco | 19.5 ms | 18.3 ms: 1.07x faster (-6%) | | scimark_lu | 413 ms | 388 ms: 1.07x faster (-6%) | | nqueens | 221 ms | 207 ms: 1.07x faster (-6%) | | fannkuch | 937 ms | 882 ms: 1.06x faster (-6%) | | regex_compile | 319 ms | 301 ms: 1.06x faster (-6%) | | raytrace | 1.16 sec | 1.09 sec: 1.06x faster (-5%) | | pickle_pure_python | 1.11 ms | 1.05 ms: 1.05x faster (-5%) | | genshi_text | 70.1 ms | 66.6 ms: 1.05x faster (-5%) | #### 2015-12-07: Optimize ElementTree.iterparse(), xml_etree_iterparse[¶](#optimize-elementtree-iterparse-xml-etree-iterparse) Optimization: [Issue #25638: Optimized ElementTree.iterparse(); it is now 2x faster](http://bugs.python.org/issue25638), [commit 9ec5e25f2](https://github.com/python/cpython/commit/9ec5e25f26a490510bb5da5c26a276cd30a263a0). | Benchmark | 2015-12-01 (df144092a340) | 2016-01-01 (71db90356390) | | --- | --- | --- | | xml_etree_iterparse | 423 ms | 206 ms: 2.05x faster (-51%) | #### 2015-09-19: PGO uses test suite, pidigits[¶](#pgo-uses-test-suite-pidigits) Optimization: [Issue #24915: Add Clang support to PGO builds and use the test suite for profile data](http://bugs.python.org/issue24915), [commit 7188a3ef](https://github.com/python/cpython/commit/7188a3efe07b9effdb760f3a96783f250214f0be). Changes of at least 5%: | Benchmark | 2015-09-18 (4b363e270108) | 2015-09-18_22-13 (7188a3efe07b) | | --- | --- | --- | | pickle | 33.7 us | 26.4 us: 1.28x faster (-22%) | | pidigits | 332 ms | 286 ms: 1.16x faster (-14%) | | pickle_list | 9.90 us | 8.84 us: 1.12x faster (-11%) | | unpickle | 37.2 us | 33.3 us: 1.12x faster (-11%) | | unpickle_list | 11.1 us | 9.95 us: 1.11x faster (-10%) | | regex_dna | 330 ms | 297 ms: 1.11x faster (-10%) | | regex_effbot | 6.43 ms | 5.80 ms: 1.11x faster (-10%) | | pickle_dict | 69.3 us | 64.1 us: 1.08x faster (-8%) | | mako | 39.1 ms | 36.2 ms: 1.08x faster (-7%) | | call_simple | 12.2 ms | 11.6 ms: 1.05x faster (-5%) | | genshi_xml | 175 ms | 166 ms: 1.05x faster (-5%) | Changes of at least 5%, sadly two benchmarks also became slower: | Benchmark | 2015-09-18_14-32-master-4b363e270108 | 2015-09-18_22-13-master-7188a3efe07b | | --- | --- | --- | | unpickle_pure_python | 776 us | 821 us: 1.06x slower (+6%) | | regex_v8 | 49.5 ms | 52.6 ms: 1.06x slower (+6%) | #### 2015-05-30: C implementation of collections.OrderedDict, html5lib[¶](#c-implementation-of-collections-ordereddict-html5lib) Optimization: [Issue #16991: Add a C implementation of collections.OrderedDict](http://bugs.python.org/issue16991), [commit 96c6af9b](https://github.com/python/cpython/commit/96c6af9b207c188c52ac53ce87bb7f2dea3f328b). | Benchmark | 2015-05-02 (3b4d30a27bd6) | 2015-06-01 (41874c570cf3) | | --- | --- | --- | | html5lib | 285 ms | 233 ms: 1.23x faster (-19%) | #### 2015-05-23: C implementation of functools.lru_cache(), sympy[¶](#c-implementation-of-functools-lru-cache-sympy) Optimization: [Issue #14373: Added C implementation of functools.lru_cache()](http://bugs.python.org/issue14373), [commit 1c858c35](https://github.com/python/cpython/commit/1c858c352b8c11419f79f586334c49378726dba8). Changes of at least 5%: | Benchmark | 2015-05-23_19-15-master-c70908558d8e | 2015-05-23_19-42-master-1c858c352b8c | | --- | --- | --- | | sympy_expand | 1.45 sec | 1.14 sec: 1.27x faster (-21%) | | sympy_sum | 308 ms | 247 ms: 1.25x faster (-20%) | | sympy_str | 621 ms | 500 ms: 1.24x faster (-19%) | | sympy_integrate | 54.2 ms | 45.7 ms: 1.19x faster (-16%) | | scimark_lu | 497 ms | 471 ms: 1.06x faster (-5%) | `pickle_dict` is seen as 1.06x slower, but since pickle doesn’t use functools.lru_cache(), the change is ignored in the table. ### Slowdown[¶](#slowdown) #### 2016-09-11: regex_compile[¶](#regex-compile) Slowdown: [convert re flags to (much friendlier) IntFlag constants (issue #28082)](http://bugs.python.org/issue28082), [commit f93395bc](https://github.com/python/cpython/commit/f93395bc5125c99539597bf134ca8bcf9707655b). | Benchmark | 2016-04-01 (6b6abd4cf10e) | 2016-07-01 (355048970b2a) | 2016-10-01 (78a111c7d867) | | --- | --- | --- | --- | | regex_compile | 339 ms | 309 ms: 1.10x faster (-9%) | 383 ms: 1.13x slower (+13%) | ### Timeline[¶](#timeline) #### April, 2016 -> May, 2016[¶](#april-2016-may-2016) 2016-04-01 .. 2016-05-01: | Benchmark | 2016-04-01 (dcfebb32e277) | 2016-05-01 (f1e2671fdf88) | | --- | --- | --- | | nqueens | 255 ms | 207 ms: 1.23x faster (-19%) | | raytrace | 1.31 sec | 1.09 sec: 1.19x faster (-16%) | | float | 290 ms | 243 ms: 1.19x faster (-16%) | | chaos | 273 ms | 235 ms: 1.16x faster (-14%) | | hexiom | 21.0 ms | 18.6 ms: 1.13x faster (-11%) | | deltablue | 16.4 ms | 14.6 ms: 1.12x faster (-11%) | | go | 557 ms | 502 ms: 1.11x faster (-10%) | | nbody | 254 ms | 232 ms: 1.10x faster (-9%) | #### call_method[¶](#call-method) Timeline 2016-04-01 .. 2017-01-01: | Benchmark | 2016-04-01 (6b6abd4cf10e) | 2016-07-01 (355048970b2a) | 2016-10-01 (78a111c7d867) | 2017-01-01 (67e1aa0b58be) | | --- | --- | --- | --- | --- | | call_method | 15.8 ms | 14.9 ms: 1.06x faster (-6%) | 14.1 ms: 1.13x faster (-11%) | 11.2 ms: 1.42x faster (-29%) | | call_method_slots | 15.7 ms | 15.2 ms: 1.03x faster (-3%) | 14.0 ms: 1.13x faster (-11%) | 11.1 ms: 1.42x faster (-29%) | | call_method_unknown | 17.7 ms | 15.9 ms: 1.11x faster (-10%) | 15.6 ms: 1.13x faster (-11%) | 14.3 ms: 1.23x faster (-19%) | #### crypto_pyaes[¶](#crypto-pyaes) | Benchmark | 2016-04-01 (master) | 2016-05-01 (master) | | --- | --- | --- | | crypto_pyaes | 226 ms | 205 ms: 1.10x faster (-9%) | 2016-03-01 .. 2016-06-01: | Benchmark | 2016-03-01 (13d09afff127) | 2016-06-01 (d80ab7d94578) | | --- | --- | --- | | crypto_pyaes | 231 ms | 199 ms: 1.16x faster (-14%) | #### json_loads[¶](#json-loads) Progress on 21 months, 2015-01-01 .. 2016-10-01: | Benchmark | 2015-01-01 (52074ac866eb) | 2016-10-01 (78a111c7d867) | | --- | --- | --- | | json_loads | 64.0 us | 56.6 us: 1.13x faster (-11%) | #### logging_silent[¶](#logging-silent) | Benchmark | 2016-01-01 (899b72cee21c) | 2016-07-01 (355048970b2a) | | --- | --- | --- | | logging_silent | 718 ns | 606 ns: 1.18x faster (-16%) | #### pickle[¶](#pickle) pickle, 2016-08-02 .. 2016-09-08: | Benchmark | 2016-08-02 (133138a284be) | 2016-09-08 (10427f44852b) | | --- | --- | --- | | pickle | 25.5 us | 21.4 us: 1.19x faster (-16%) | pickle dict/list: | Benchmark | 2016-04-01 (6b6abd4cf10e) | 2016-10-01 (78a111c7d867) | | --- | --- | --- | | pickle_dict | 64.5 us | 57.7 us: 1.12x faster (-11%) | | pickle_list | 9.06 us | 7.79 us: 1.16x faster (-14%) | unpickle: | Benchmark | 2015-07-01 (d7982beca93c) | 2015-10-01 (30b7138fe12b) | | --- | --- | --- | | unpickle | 36.9 us | 32.8 us: 1.13x faster (-11%) | #### python_startup[¶](#python-startup) 2015-04-01 .. 2015-10-01: | Benchmark | 2015-04-01 (4fd929b43121) | 2015-10-01 (30b7138fe12b) | | --- | --- | --- | | python_startup | 16.4 ms | 17.2 ms: 1.05x slower (+5%) | | python_startup_no_site | 8.65 ms | 8.90 ms: 1.03x slower (+3%) | 2016-04-01 .. 2017-01-01: | Benchmark | 2016-04-01 (6b6abd4cf10e) | 2017-01-01 (67e1aa0b58be) | | --- | --- | --- | | python_startup | 17.3 ms | 14.5 ms: 1.20x faster (-16%) | | python_startup_no_site | 8.89 ms | 8.39 ms: 1.06x faster (-6%) | #### regex_compile[¶](#id1) | Benchmark | 2016-04-01 (6b6abd4cf10e) | 2016-07-01 (355048970b2a) | 2016-10-01 (78a111c7d867) | | --- | --- | --- | --- | | regex_compile | 339 ms | 309 ms: 1.10x faster (-9%) | 383 ms: 1.13x slower (+13%) | #### telco[¶](#telco) | Benchmark | 2016-01-01 (899b72cee21c) | 2016-04-01 (6b6abd4cf10e) | 2016-07-01 (355048970b2a) | 2016-10-01 (78a111c7d867) | 2017-03-31 (cdcac039fb44) | | --- | --- | --- | --- | --- | --- | | telco | 19.6 ms | 19.2 ms: 1.02x faster (-2%) | 18.3 ms: 1.08x faster (-7%) | 15.1 ms: 1.30x faster (-23%) | 13.9 ms: 1.41x faster (-29%) | #### scimark[¶](#scimark) 2016-10-01 .. 2017-03-31: | Benchmark | 2016-10-01 (78a111c7d867) | 2017-01-01 (67e1aa0b58be) | 2017-03-31 (cdcac039fb44) | | --- | --- | --- | --- | | scimark_lu | 423 ms | 378 ms: 1.12x faster (-11%) | 318 ms: 1.33x faster (-25%) | | scimark_sor | 426 ms | 403 ms: 1.06x faster (-5%) | 375 ms: 1.14x faster (-12%) | #### sqlalchemy_declarative[¶](#sqlalchemy-declarative) | Benchmark | 2014-10-01 (5a789f7eaf81) | 2015-10-01 (30b7138fe12b) | | --- | --- | --- | | sqlalchemy_declarative | 345 ms | 301 ms: 1.15x faster (-13%) | #### sympy[¶](#sympy) 2016-04-01 .. 2016-10-01: | Benchmark | 2016-04-01 (6b6abd4cf10e) | 2016-07-01 (355048970b2a) | 2016-10-01 (78a111c7d867) | | --- | --- | --- | --- | | sympy_expand | 1.10 sec | 1.01 sec: 1.09x faster (-8%) | 942 ms: 1.17x faster (-14%) | | sympy_integrate | 46.6 ms | 42.9 ms: 1.09x faster (-8%) | 41.2 ms: 1.13x faster (-11%) | | sympy_sum | 247 ms | 233 ms: 1.06x faster (-6%) | 199 ms: 1.24x faster (-19%) | | sympy_str | 483 ms | 454 ms: 1.07x faster (-6%) | 427 ms: 1.13x faster (-12%) | #### xml_etree_generate[¶](#xml-etree-generate) | Benchmark | 2015-04-01 (4fd929b43121) | 2015-07-01 (d7982beca93c) | 2015-10-01 (30b7138fe12b) | 2016-01-01 (899b72cee21c) | 2016-07-01 (355048970b2a) | | --- | --- | --- | --- | --- | --- | | xml_etree_generate | 282 ms | 267 ms: 1.06x faster (-5%) | 256 ms: 1.10x faster (-9%) | 237 ms: 1.19x faster (-16%) | 212 ms: 1.33x faster (-25%) | Changelog[¶](#changelog) --- ### Version 1.0.9 (2023-06-14)[¶](#version-1-0-9-2023-06-14) * Vendor lib2to3 for Python 3.13+ * Add TaskGroups variants to async_tree benchmarks ### Version 1.0.8 (2023-06-02)[¶](#version-1-0-8-2023-06-02) * Move the main requirements.txt file to pyperformance/requirements so that dependabot can only run on that one file * Update dependencies of benchmarks not to specify setuptools * On older versions of Python, skip benchmarks that use features introduced in newer Python versions * Support `--inherit-environ` when reusing a venv * Use tomllib/tomli over toml * Update MANIFEST.in to include cert files for asyncio_tcp_ssl benchmark * Fix undefined variable issue when raising VenvPipInstallFailedError * Add mypy config; run mypy in CI * Fix typo of str.partition from _pyproject_toml.py * Add version of Richards benchmark that uses super() * Add a benchmark for runtime-checkable protocols * Extend async tree benchmarks to cover eager task execution ### Version 1.0.7 (2023-04-22)[¶](#version-1-0-7-2023-04-22) * Upgrade pyperf from 2.5.0 to 2.6.0 * Clean unused imports and other small code details * Migrage to the pyproject.toml based project * Fix the django_template benchmark due to lack of distutils * Add benchmark for toml * Add benchmark for comprehensions * Add benchmark for asyncio_tcp_ssl * Add benchmark for asyncio_tcp * Add benchmark for Dask scheduler * Add the gc benchmarks to the MANIFEST file ### Version 1.0.6 (2022-11-20)[¶](#version-1-0-6-2022-11-20) * Upgrade pyperf from 2.4.1 to 2.5.0 * Add a benchmark to measure gc traversal * Add jobs field in compile section to specify make -j param * Add benchmark for Docutils * Add async_generators benchmark * Add benchmark for IPC * Fix Manifest Group * Fix installing dev build of pyperformance inside compile/compile_all * Always upload, even when some benchmarks fail * Add sqlglot benchmarks * Support reporting geometric mean by tags * Allow for specifying local wheels and sdists as dependencies * Add a benchmark based on python -m pprint * Add mdp back into the default group * Add coroutines benchmark * Reduce noise in generators benchmark * Add benchmark for deepcopy * Add coverage benchmark * Add generators benchmark * Add benchmark for async tree workloads * Support relative paths to manifest files * Add support for multiple benchmark groups in a manifest * Fix –inherit-environ issue * Use working Genshi 0.7.7 ### Version 1.0.4 (2022-01-25)[¶](#version-1-0-4-2022-01-25) * Re-release support for user-defined benchmark after fixing problem with virtual environments. ### Version 1.0.3 (2021-12-20)[¶](#version-1-0-3-2021-12-20) * Support user-defined benchmark suites. ### Version 1.0.2 (2021-05-11)[¶](#version-1-0-2-2021-05-11) * Disable the henshi benchmark temporarily since is no longer compatible with Python 3.11. * Reenable html5lib benchmark: html5lib 1.1 has been released. * Update requirements. * Replace Travis CI with GitHub Actions. * The development branch `master` was renamed to `main`. See <https://sfconservancy.org/news/2020/jun/23/gitbranchname/> for the rationale. ### Version 1.0.1 (2020-03-26)[¶](#version-1-0-1-2020-03-26) * Drop usage of the six module since Python 2 is no longer supported. Remove Python 2 specific code. * Update dependencies: + django: 3.0 => 3.0.4 + dulwich: 0.19.14 => 0.19.15 + mako: 1.1.0 = > 1.1.2 + mercurial: 5.1.1 => 5.3.1 + psutil: 5.6.7 => 5.7.0 + pyperf: 1.7.0 => 2.0.0 + sqlalchemy: 1.3.12 => 1.3.15 + sympy: 1.5 => 1.5.1 + tornado: 6.0.3 => 6.0.4 * Remove six, html5lib and mercurial requirements. * pip-tools (pip-compile) is now used to update dependencies ### Version 1.0.0 (2019-12-17)[¶](#version-1-0-0-2019-12-17) * Enable pyflate benchmarks on Python 3. * Remove `spambayes` benchmark: it is not compatible with Python 3. * Remove `2n3`:benchmark group. * Drop Python 2.7 support: old Django and Tornado versions are not compatible with incoming Python 3.9. * Disable html5lib benchmark temporarily, since it’s no longer compatible with Python 3.9. * Update requirements: + Django: 1.11.22 => 3.0 + Mako: 1.0.14 => 1.1.0 + SQLAlchemy: 1.3.6 => 1.3.12 + certifi: 2019.6.16 => 2019.11.28 + docutils: 0.15.1 => 0.15.2 + dulwich: 0.19.11 => 0.19.14 + mercurial: 5.0.2 => 5.1.1 + psutil: 5.6. => 5.6.7 + pyperf: 1.6.1 => 1.7.0 + six: 1.12. => 1.13.0 + sympy: 1.4 => 1.5 ### Version 0.9.1 (2019-07-29)[¶](#version-0-9-1-2019-07-29) * Enable hg_startup on Python 3 * Fix compatibility with Python 3.8 beta 2 * Update requirements: + certifi: 2019.3.9 => 2019.6.16 + Chameleon: 3.6.1 => 3.6.2 + Django: 1.11.20 => 1.11.22 + docutils: 0.14 => 0.15.1.post1 + Mako: 1.0.10 => 1.0.14 + mercurial: 5.0 => 5.0.2 + pathlib2: 2.3.3 => 2.3.4 + psutil: 5.6.2 => 5.6.3 + SQLAlchemy: 1.3.4 => 1.3.6 ### Version 0.9.0 (2019-05-29)[¶](#version-0-9-0-2019-05-29) * Project renamed from “performance” to “pyperformance” * Upgrade pyperf from version 1.6.0 to 1.6.1. The project has been renamed from “perf” to “pyperf”. Update imports. * Issue #54: Update Genshi to 0.7.3. It is now compatible with Python 3.8. * Update requirements: + Mako: 1.0.9= > 1.0.10 + SQLAlchemy: 1.3.3 => 1.3.4 ### Version 0.8.0 (2019-05-10)[¶](#version-0-8-0-2019-05-10) * compile command: Add “pkg_only” option to benchmark.conf. Add support for native libraries that are installed but not on path. Patch by <NAME>. * Update Travis configuration: use trusty image, use pip cache. Patch by <NAME>. * Upgrade tornado to 5.1.1. Patch by <NAME>. * Fix compile command on Mac OS: no program extension. Patch by <NAME>. * Update requirements: + Chameleon: 3.4 => 3.6.1 + Django: 1.11.16 => 1.11.20 + Genshi: 0.7.1 => 0.7.2 + Mako: 1.0.7 => 1.0.9 + MarkupSafe: 1.0 => 1.1.1 + SQLAlchemy: 1.2.12 => 1.3.3 + certifi: 2018.10.15 => 2019.3.9 + dulwich: 0.19.6 => 0.19.11 + mercurial: 4.7.2 => 5.0 + mpmath: 1.0.0 => 1.1.0 + pathlib2: 2.3.2 => 2.3.3 + perf: 1.5.1 => 1.6.0 + psutil: 5.4.7 => 5.6.2 + six: 1.11.0 => 1.12.0 + sympy: 1.3 => 1.4 + tornado: 4.5.3 => 5.1.1 ### Version 0.7.0 (2018-10-16)[¶](#version-0-7-0-2018-10-16) * python_startup: Add `--exit` option. * Update requirements: + certifi: 2017.11.5 => 2018.10.15 + Chameleon: 3.2 => 3.4 + Django: 1.11.9 => 1.11.16 + dulwich: 0.18.6 => 0.19.6 + Genshi: 0.7 => 0.7.1 + mercurial: 4.4.2 => 4.7.2 + pathlib2: 2.3.0 => 2.3.2 + psutil: 5.4.3 => 5.4.7 + SQLAlchemy: 1.2.0 => 1.2.12 + sympy: 1.1.1 => 1.3 * Fix issue #40 for pip 10 and newer: Remove indirect dependencies. Indirect dependencies were used to install cffi, but Mercurial 4.0 doesn’t depend on cffi anymore. ### Version 0.6.1 (2018-01-11)[¶](#version-0-6-1-2018-01-11) * Fix inherit-environ: propagate to recursive invocations of `performance` in `compile` and `compile_all` commands. * Fix the `--track-memory` option thanks to the update to perf 1.5. * Update requirements + certifi: 2017.4.17 => 2017.11.5 + Chameleon: 3.1 => 3.2 + Django: 1.11.3 => 1.11.9 + docutils: 0.13.1 => 0.14 + dulwich: 0.17.3 => 0.18.6 + html5lib: 0.999999999 => 1.0.1 + Mako: 1.0.6 => 1.0.7 + mercurial: 4.2.2 => 4.4.2 + mpmath: 0.19 => 1.0.0 + perf: 1.4 => 1.5.1 (fix `--track-memory` option) + psutil: 5.2.2 => 5.4.3 + pyaes: 1.6.0 => 1.6.1 + six: 1.10.0 => 1.11.0 + SQLAlchemy: 1.1.11 => 1.2.0 + sympy: 1.0 => 1.1.1 + tornado: 4.5.1 => 4.5.3 ### Version 0.6.0 (2017-07-06)[¶](#version-0-6-0-2017-07-06) * Change `warn` to `warning` in bm_logging.py. In Python 3, Logger.warn() calls warnings.warn() to log a deprecation warning, so is slower than Logger.warning(). * Add again the `logging_silent` microbenchmark suite. * compile command: update the Git repository before getting the revision * Update requirements + perf: 1.3 => 1.4 (fix parse_cpu_list(): strip also NUL characters) + Django: 1.11.1 => 1.11.3 + mercurial: 4.2 => 4.2.2 + pathlib2: 2.2.1 => 2.3.0 + SQLAlchemy: 1.1.10 => 1.1.11 ### Version 0.5.5 (2017-05-29)[¶](#version-0-5-5-2017-05-29) * On the 2.x branch on CPython, `compile` now pass `--enable-unicode=ucs4` to the `configure` script on all platforms, except on Windows which uses UTF-16 because of its 16-bit wchar_t. * The `float` benchmark now uses `__slots__` on the `Point` class. * Remove the following microbenchmarks. They have been moved to the [pymicrobench](https://github.com/vstinner/pymicrobench) project because they are too short, not representative of real applications and are too unstable. + `pybench` microbenchmark suite + `call_simple` + `call_method` + `call_method_unknown` + `call_method_slots` + `logging_silent`: values are faster than 1 ns on PyPy with 2^27 loops! (and around 0.7 us on CPython) * Update requirements + Django: 1.11 => 1.11.1 + SQLAlchemy: 1.1.9 => 1.1.10 + certifi: 2017.1.23 => 2017.4.17 + perf: 1.2 => 1.3 + mercurial: 4.1.2 => 4.2 + tornado: 4.4.3 => 4.5.1 ### Version 0.5.4 (2017-04-10)[¶](#version-0-5-4-2017-04-10) * Create a new documentation at: <http://pyperformance.readthedocs.io/> * Add “CPython results, 2017” to the doc: significant performance changes, significant optimizations, timeline, etc. * The `show` command doesn’t need to create a virtual env anymore. * Add new commands: + `pyperformance compile`: compile, install and benchmark + `pyperformance compile_all`: benchmark multiple branches and revisions of Python + `pyperformance upload`: upload a JSON file to a Codespeed * setup.py: add dependencies to `perf` and `six` modules. * bm_xml_etree now uses “_pure_python” in benchmark names if the accelerator is explicitly disabled. * Upgrade requirements: + Django: 1.10.6 -> 1.11 + SQLAlchemy: 1.1.6 -> 1.1.9 + mercurial: 4.1.1 -> 4.1.2 + perf: 1.1 => 1.2 + psutil: 5.2.1 -> 5.2.2 + tornado: 4.4.2 -> 4.4.3 + webencodings: 0.5 -> 0.5.1 * perf 1.2 now calibrates the number of warmups on PyPy. * On Python 3.5a0: force pip 7.1.2 and setuptools 18.5: <https://sourceforge.net/p/pyparsing/bugs/100/### Version 0.5.3 (2017-03-27)[¶](#version-0-5-3-2017-03-27) * Upgrade Dulwich to 0.17.3 to support PyPy older than 5.6: see <https://github.com/jelmer/dulwich/issues/509> * Fix ResourceWarning warnings: close explicitly files and sockets. * scripts: replace Mercurial commands with Git commands. * Upgrade requirements: + dulwich: 0.17.1 => 0.17.3 + perf: 1.0 => 1.1 + psutil: 5.2.0 => 5.2.1 ### Version 0.5.2 (2017-03-17)[¶](#version-0-5-2-2017-03-17) * Upgrade requirements: + certifi: 2016.9.26 => 2017.1.23 + Chameleon: 3.0 => 3.1 + Django: 1.10.5 => 1.10.6 + MarkupSafe: 0.23 => 1.0 + dulwich: 0.16.3 => 0.17.1 + mercurial: 4.0.2 => 4.1.1 + pathlib2: 2.2.0 => 2.2.1 + perf: 0.9.3 => 1.0 + psutil: 5.0.1 => 5.2.0 + SQLAlchemy: 1.1.4 => 1.1.6 ### Version 0.5.1 (2017-01-16)[¶](#version-0-5-1-2017-01-16) * Fix Windows support (upgrade perf from 0.9.0 to 0.9.3) * Upgrade requirements: + Chameleon: 2.25 => 3.0 + Django: 1.10.3 => 1.10.5 + docutils: 0.12 => 0.13.1 + dulwich: 0.15.0 => 0.16.3 + mercurial: 4.0.0 => 4.0.2 + perf: 0.9.0 => 0.9.3 + psutil: 5.0.0 => 5.0.1 ### Version 0.5.0 (2016-11-16)[¶](#version-0-5-0-2016-11-16) * Add `mdp` benchmark: battle with damages and topological sorting of nodes in a graph * The `default` benchmark group now include all benchmarks but `pybench` * If a benchmark fails, log an error, continue to execute following benchmarks, but exit with error code 1. * Remove deprecated benchmarks: `threading_threaded_count` and `threading_iterative_count`. It wasn’t possible to run them anyway. * `dulwich` requirement is now optional since its installation fails on Windows. * Upgrade requirements: + Mako: 1.0.5 => 1.0.6 + Mercurial: 3.9.2 => 4.0.0 + SQLAlchemy: 1.1.3 => 1.1.4 + backports-abc: 0.4 => 0.5 ### Version 0.4.0 (2016-11-07)[¶](#version-0-4-0-2016-11-07) * Add `sqlalchemy_imperative` benchmark: it wasn’t registered properly * The `list` command now only lists the benchmark that the `run` command will run. The `list` command gets a new `-b/--benchmarks` option. * Rewrite the code creating the virtual environment to test correctly pip. Download and run `get-pip.py` if pip installation failed. * Upgrade requirements: + perf: 0.8.2 => 0.9.0 + Django: 1.10.2 => 1.10.3 + Mako: 1.0.4 => 1.0.5 + psutil: 4.3.1 => 5.0.0 + SQLAlchemy: 1.1.2 => 1.1.3 * Remove `virtualenv` dependency ### Version 0.3.2 (2016-10-19)[¶](#version-0-3-2-2016-10-19) * Fix setup.py: include also `performance/benchmarks/data/asyncio.git/` ### Version 0.3.1 (2016-10-19)[¶](#version-0-3-1-2016-10-19) * Add `regex_dna` benchmark * The `run` command now fails with an error if no benchmark was run. * genshi, logging, scimark, sympy and xml_etree scripts now run all sub-benchmarks by default * Rewrite pybench using perf: remove the old legacy code to calibrate and run benchmarks, reuse perf.Runner API. * Change heuristic to create the virtual environment, tried commands: + `python -m venv` + `python -m virtualenv` + `virtualenv -p python` * The creation of the virtual environment now ensures that pip works to detect “python3 -m venv” which doesn’t install pip. * Upgrade perf dependency from 0.7.12 to 0.8.2: update all benchmarks to the new perf 0.8 API (which introduces incompatible changes) * Update SQLAlchemy from 1.1.1 to 1.1.2 ### Version 0.3.0 (2016-10-11)[¶](#version-0-3-0-2016-10-11) New benchmarks: * Add `crypto_pyaes`: Benchmark a pure-Python implementation of the AES block-cipher in CTR mode using the pyaes module (version 1.6.0). Add `pyaes` dependency. * Add `sympy`: Benchmark on SymPy. Add `scipy` dependency. * Add `scimark` benchmark * Add `deltablue`: DeltaBlue benchmark * Add `dulwich_log`: Iterate on commits of the asyncio Git repository using the Dulwich module. Add `dulwich` (and `mpmath`) dependencies. * Add `pyflate`: Pyflate benchmark, tar/bzip2 decompressor in pure Python * Add `sqlite_synth` benchmark: Benchmark Python aggregate for SQLite * Add `genshi` benchmark: Render template to XML or plain text using the Genshi module. Add `Genshi` dependency. * Add `sqlalchemy_declarative` and `sqlalchemy_imperative` benchmarks: SQLAlchemy Declarative and Imperative benchmarks using SQLite. Add `SQLAlchemy` dependency. Enhancements: * `compare` command now fails if the performance versions are different * `nbody`: add `--reference` and `--iterations` command line options. * `chaos`: add `--width`, `--height`, `--thickness`, `--filename` and `--rng-seed` command line options * `django_template`: add `--table-size` command line option * `json_dumps`: add `--cases` command line option * `pidigits`: add `--digits` command line option * `raytrace`: add `--width`, `--height` and `--filename` command line options * Port `html5lib` benchmark to Python 3 * Enable `pickle_pure_python` and `unpickle_pure_python` on Python 3 (code was already compatible with Python 3) * Creating the virtual environment doesn’t inherit environment variables (especially `PYTHONPATH`) by default anymore: `--inherit-environ` command line option must now be used explicitly. Bugfixes: * `chaos` benchmark now also reset the `random` module at each sample to get more reproductible benchmark results * Logging benchmarks now truncate the in-memory stream before each benchmark run Rename benchmarks: * Rename benchmarks to get a consistent name between the command line and benchmark name in the JSON file. * Rename pickle benchmarks: > + `slowpickle` becomes `pickle_pure_python` > + `slowunpickle` becomes `unpickle_pure_python` > + `fastpickle` becomes `pickle` > + `fastunpickle` becomes `unpickle` > * Rename ElementTree benchmarks: replace `etree_` prefix with > `xml_etree_`. > * Rename `hexiom2` to `hexiom_level25` and explicitly pass `--level=25` > parameter > * Rename `json_load` to `json_loads` > * Rename `json_dump_v2` to `json_dumps` (and remove the deprecated > `json_dump` benchmark) > * Rename `normal_startup` to `python_startup`, and `startup_nosite` > to `python_startup_no_site` > * Rename `threaded_count` to `threading_threaded_count`, > rename `iterative_count` to `threading_iterative_count` > * Rename logging benchmarks: > + `silent_logging` to `logging_silent` > + `simple_logging` to `logging_simple` > + `formatted_logging` to `logging_format` Minor changes: * Update dependencies * Remove broken `--args` command line option. ### Version 0.2.2 (2016-09-19)[¶](#version-0-2-2-2016-09-19) * Add a new `show` command to display a benchmark file * Issue #11: Display Python version in compare. Display also the performance version. * CPython issue #26383; csv output: don’t truncate digits for timings shorter than 1 us * compare: Use sample unit of benchmarks, format values in the table output using the unit * compare: Fix the table output if benchmarks only contain a single sample * Remove unused -C/–control_label and -E/–experiment_label options * Update perf dependency to 0.7.11 to get Benchmark.get_unit() and BenchmarkSuite.get_metadata() ### Version 0.2.1 (2016-09-10)[¶](#version-0-2-1-2016-09-10) * Add `--csv` option to the `compare` command * Fix `compare -O table` output format * Freeze indirect dependencies in requirements.txt * `run`: add `--track-memory` option to track the memory peak usage * Update perf dependency to 0.7.8 to support memory tracking and the new `--inherit-environ` command line option * If `virtualenv` command fail, try another command to create the virtual environment: catch `virtualenv` error * The first command to upgrade pip to version `>= 6.0` now uses the `pip` binary rather than `python -m pip` to support pip 1.0 which doesn’t support `python -m pip` CLI. * Update Django (1.10.1), Mercurial (3.9.1) and psutil (4.3.1) * Rename `--inherit_env` command line option to `--inherit-environ` and fix it ### Version 0.2 (2016-09-01)[¶](#version-0-2-2016-09-01) * Update Django dependency to 1.10 * Update Chameleon dependency to 2.24 * Add the `--venv` command line option * Convert Python startup, Mercurial startup and 2to3 benchmarks to perf scripts (bm_startup.py, bm_hg_startup.py and bm_2to3.py) * Pass the `--affinity` option to perf scripts rather than using the `taskset` command * Put more installer and optional requirements into `performance/requirements.txt` * Cached `.pyc` files are no more removed before running a benchmark. Use `venv recreate` command to update a virtual environment if required. * The broken `--track_memory` option has been removed. It will be added back when it will be fixed. * Add performance version to metadata * Upgrade perf dependency to 0.7.5 to get `Benchmark.update_metadata()` ### Version 0.1.2 (2016-08-27)[¶](#version-0-1-2-2016-08-27) * Windows is now supported * Add a new `venv` command to show, create, recrete or remove the virtual environment. * Fix pybench benchmark (update to perf 0.7.4 API) * performance now tries to install the `psutil` module on CPython for better system metrics in metadata and CPU pinning on Python 2. * The creation of the virtual environment now also tries `virtualenv` and `venv` Python modules, not only the virtualenv command. * The development version of performance now installs performance with “pip install -e <path_to_performance>” * The GitHub project was renamed from `python/benchmarks` to `python/performance`. ### Version 0.1.1 (2016-08-24)[¶](#version-0-1-1-2016-08-24) * Fix the creation of the virtual environment * Rename pybenchmarks script to pyperformance * Add -p/–python command line option * Add __main__ module to be able to run: python3 -m performance ### Version 0.1 (2016-08-24)[¶](#version-0-1-2016-08-24) * First release after the conversion to the perf module and move to GitHub * Removed benchmarks + django_v2, django_v3 + rietveld + spitfire (and psyco): Spitfire is not available on PyPI + pystone + gcbench + tuple_gc_hell ### History[¶](#history) Projected moved to <https://github.com/python/performance> in August 2016. Files reorganized, benchmarks patched to use the perf module to run benchmark in multiple processes. Project started in December 2008 by <NAME> and <NAME> for the Unladen Swallow project. The project was hosted at <https://hg.python.org/benchmarks> until Feb 2016 Other Python Benchmarks: * CPython: [speed.python.org](https://speed.python.org/) uses pyperf, pyperformance and [Codespeed](https://github.com/tobami/codespeed/) (Django web application) * PyPy: [speed.pypy.org](http://speed.pypy.org/) uses [PyPy benchmarks](https://bitbucket.org/pypy/benchmarks) * Pyston: [pyston-perf](https://github.com/dropbox/pyston-perf) and [speed.pyston.org](http://speed.pyston.org/) * [Numba benchmarks](http://numba.pydata.org/numba-benchmark/) * Cython: [Cython Demos/benchmarks](https://github.com/cython/cython/tree/master/Demos/benchmarks) * pythran: [numpy-benchmarks](https://github.com/serge-sans-paille/numpy-benchmarks) See also the [Python speed mailing list](https://mail.python.org/mailman/listinfo/speed) and the [Python pyperf module](http://pyperf.readthedocs.io/) (used by pyperformance). pyperformance is not tuned for PyPy yet: use the [PyPy benchmarks project](https://foss.heptapod.net/pypy/benchmarks) instead to measure PyPy performances. Image generated by bm_raytrace (pure Python raytrace): [Python Performance Benchmark Suite](index.html#document-index) === ### Navigation * [Usage](index.html#document-usage) * [Benchmarks](index.html#document-benchmarks) * [Custom Benchmarks](index.html#document-custom_benchmarks) * [CPython results, 2017](index.html#document-cpython_results_2017) * [Changelog](index.html#document-changelog) ### Related Topics * [Documentation overview](index.html#document-index) ### Quick search
safer-ffi
rust
Rust
Crate safer_ffi === ![safer-ffi-banner](https://github.com/getditto/safer_ffi/blob/banner/guide/assets/safer_ffi.jpg?raw=true) ![CI](https://github.com/getditto/safer_ffi/workflows/CI/badge.svg?branch=master) ![guide](https://img.shields.io/badge/guide-mdbook-blue) ![docs-rs](https://docs.rs/safer-ffi/badge.svg) ![crates-io](https://img.shields.io/crates/v/safer-ffi.svg) ![repository](https://img.shields.io/badge/repository-GitHub-brightgreen.svg) What is `safer_ffi`? --- `safer_ffi` is a framework that helps you write foreign function interfaces (FFI) without polluting your Rust code with `unsafe { ... }` code blocks while making functions far easier to read and maintain. > **📚 Read The User Guide 📚** ### Prerequisites Minimum Supported Rust Version: `1.66.1` Quickstart --- Click to hide ##### Small self-contained demo You may try working with the `examples/point` example embedded in the repo: ``` git clone https://github.com/getditto/safer_ffi && cd safer_ffi (cd examples/point && make) ``` Otherwise, to start using `::safer_ffi`, follow the following steps: #### Crate layout ##### Step 1: `Cargo.toml` Edit your `Cargo.toml` like so: ``` [package] name = "crate_name" version = "0.1.0" edition = "2021" [lib] crate-type = [ "staticlib", # Ensure it gets compiled as a (static) C library # "cdylib", # If you want a shared/dynamic C library (advanced) "lib", # For `generate-headers` and other downstream rust dependents # such as integration `tests/`, doctests, and `examples/` ] [dependencies] # Use `cargo add` or `cargo search` to find the latest values of x.y.z. # For instance: # cargo add safer-ffi safer-ffi.version = "x.y.z" safer-ffi.features = [] # you may add some later on. [features] # If you want to generate the headers, use a feature-gate # to opt into doing so: headers = ["safer-ffi/headers"] ``` * Where `"x.y.z"` ought to be replaced by the last released version, which you can find by running `cargo search safer-ffi`. * See the dedicated chapter on `Cargo.toml` for more info. ##### Step 2: `src/lib.rs` Then, to export a Rust function to FFI, add the `#[derive_ReprC]` and `#[ffi_export]` attributes like so: ``` use ::safer_ffi::prelude::*; /// A `struct` usable from both Rust and C #[derive_ReprC] #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct Point { x: f64, y: f64, } /* Export a Rust function to the C world. */ /// Returns the middle point of `[a, b]`. #[ffi_export] fn mid_point(a: &Point, b: &Point) -> Point { Point { x: (a.x + b.x) / 2., y: (a.y + b.y) / 2., } } /// Pretty-prints a point using Rust's formatting logic. #[ffi_export] fn print_point(point: &Point) { println!("{:?}", point); } // The following function is only necessary for the header generation. #[cfg(feature = "headers")] // c.f. the `Cargo.toml` section pub fn generate_headers() -> ::std::io::Result<()> { ::safer_ffi::headers::builder() .to_file("rust_points.h")? .generate() } ``` * See the dedicated chapter on `src/lib.rs` for more info. ##### Step 3: `src/bin/generate-headers.rs` ``` fn main() -> ::std::io::Result<()> { ::crate_name::generate_headers() } ``` #### Compilation & header generation ``` # Compile the C library (in `target/{debug,release}/libcrate_name.ext`) cargo build # --release # Generate the C header cargo run --features headers --bin generate-headers ``` * See the dedicated chapter on header generation for more info. Generated C header (`rust_points.h`) ``` /*! \file */ /******************************************* * * * File auto-generated by `::safer_ffi`. * * * * Do not manually edit this file. * * * *******************************************/ #ifndef __RUST_CRATE_NAME__ #define __RUST_CRATE_NAME__ #ifdef __cplusplus extern "C" { #endif #include <stddef.h> #include <stdint.h/** \brief * A `struct` usable from both Rust and C */ typedef struct Point { /** <No documentation available> */ double x; /** <No documentation available> */ double y; } Point_t; /** \brief * Returns the middle point of `[a, b]`. */ Point_t mid_point ( Point_t const * a, Point_t const * b); /** \brief * Pretty-prints a point using Rust's formatting logic. */ void print_point ( Point_t const * point); #ifdef __cplusplus } /* extern \"C\" */ #endif #endif /* __RUST_CRATE_NAME__ */ ``` --- ### Testing it from C Here is a basic example to showcase FFI calling into our exported Rust functions: #### `main.c` ``` #include <stdlib.h#include "rust_points.h" int main (int argc, char const * const argv[]) { Point_t a = { .x = 84, .y = 45 }; Point_t b = { .x = 0, .y = 39 }; Point_t m = mid_point(&a, &b); print_point(&m); return EXIT_SUCCESS; } ``` #### Compilation command ``` cc -o main{,.c} -L target/debug -l crate_name -l{pthread,dl,m} # Now feel free to run the compiled binary ./main ``` * Note regarding the extra `-l…` flags. Those vary based on the version of the Rust standard library being used, and the system being used to compile it. In order to reliably know which ones to use, `rustc` itself ought to be queried for it. Simple command: ``` rustc --crate-type=staticlib --print=native-static-libs -</dev/null ``` this yields, *to the stderr*, output along the lines of: ``` note: Link against the following native artifacts when linking against this static library. The order and any duplication can be significant on some platforms. note: native-static-libs: -lSystem -lresolv -lc -lm -liconv ``` Using something like `sed -nE 's/^note: native-static-libs: (.*)/\1/p'` is thus a convenient way to extract these flags: ``` rustc --crate-type=staticlib --print=native-static-libs -</dev/null \ 2>&1 | sed -nE 's/^note: native-static-libs: (.*)/\1/p' ``` Ideally, you would not query for this information *in a vacuum* (*e.g.*, `/dev/null` file being used as input Rust code just above), and rather, would apply it for your actual code being compiled: ``` cargo rustc -q -- --print=native-static-libs \ 2>&1 | sed -nE 's/^note: native-static-libs: (.*)/\1/p' ``` And if you really wanted to polish things further, you could use the JSON-formatted compiler output (this, for instance, avoids having to redirect `stderr`). But then you’d have to use a JSON parser, such as `jq`: ``` RUST_STDLIB_DEPS=$(set -eo pipefail && \ cargo rustc \ --message-format=json \ -- --print=native-static-libs \ | jq -r ' select (.reason == "compiler-message") | .message.message ' | sed -nE 's/^native-static-libs: (.*)/\1/p' \ ) ``` and then use: ``` cc -o main{,.c} -L target/debug -l crate_name ${RUST_STDLIB_DEPS} ``` which does output: ``` Point { x: 42.0, y: 42.0 } ``` 🚀🚀 ### Development #### Tests safer-ffi includes three different tests suites that can be run. ``` # In the project root: cargo test # FFI tests make -C ffi_tests # JavaScript tests make -C js_tests # Running the JS tests also gives you instructions for running browser tests. # Run this command in the `js_tests` directory, open a browser and navigate to # http://localhost:13337/ wasm-pack build --target web && python3 -m http.server 13337 ``` Re-exports --- * `pub use dyn_traits::futures;` * `pub use tuple::*;` Modules --- * boxed`alloc``#[repr(C)]` `Box`ed types. * char_p`char *`-compatible strings (slim pointers), for easier use from within C. They thus do not support inner nulls, nor string appending. * closureClosures with a `#[repr(C)]` layout (inlined vtable), up to 9 function arguments. * dyn_traits`dyn-traits`See the dedicated section of the guide. * headers`headers`C headers generation. * layoutTrait abstractions describing the semantics of “being `#[repr(C)]`” * libcOn certain platforms, `::libc` has no definitions for pervasive types such as `size_t`. * prelude * ptrWrappers around `NonNull` to better express the semantics of such pointer. * sliceLogic common to all fat pointers. * string`Rust` string types with a defined `#[repr(C)]` layout, albeit not `char *` compatible (*fat* pointers). * tupleTuple types with a guaranteed `#[repr(C)]` layout. * vec`alloc` Macros --- * CTypeSafely implement `CType` for a `#[repr(C)]` struct **when all its fields are `CType`**. * NULL * ReprCTransitioning helper macro: still uses the old `ReprC!` syntax, but just to forward to the new `#[derive_ReprC2($(js)?)]` one. * cCreates a compile-time checked `char_p::Ref``<'static>` out of a string literal. * c_vec`alloc` * ffi_export_future_helpers`dyn-traits` Structs --- * String`alloc`Same as `String`, but with guaranteed `#[repr(C)]` layout * Vec`alloc`Same as `Vec<T>`, but with guaranteed `#[repr(C)]` layout * c_charA `ReprC` *standalone* type with the same layout and ABI as `::libc::c_char`. * c_intA `ReprC` *standalone* type with the same layout and ABI as `::libc::c_int`. Attribute Macros --- * cfg_headersIdentity macro when `feature = "headers"` is enabled, otherwise this macro outputs nothing. * derive_ReprCSafely implement `ReprC` for a `#[repr(C)]` struct **when all its fields are `ReprC`**. * ffi_exportExport a function to be callable by C. Crate safer_ffi === ![safer-ffi-banner](https://github.com/getditto/safer_ffi/blob/banner/guide/assets/safer_ffi.jpg?raw=true) ![CI](https://github.com/getditto/safer_ffi/workflows/CI/badge.svg?branch=master) ![guide](https://img.shields.io/badge/guide-mdbook-blue) ![docs-rs](https://docs.rs/safer-ffi/badge.svg) ![crates-io](https://img.shields.io/crates/v/safer-ffi.svg) ![repository](https://img.shields.io/badge/repository-GitHub-brightgreen.svg) What is `safer_ffi`? --- `safer_ffi` is a framework that helps you write foreign function interfaces (FFI) without polluting your Rust code with `unsafe { ... }` code blocks while making functions far easier to read and maintain. > **📚 Read The User Guide 📚** ### Prerequisites Minimum Supported Rust Version: `1.66.1` Quickstart --- Click to hide ##### Small self-contained demo You may try working with the `examples/point` example embedded in the repo: ``` git clone https://github.com/getditto/safer_ffi && cd safer_ffi (cd examples/point && make) ``` Otherwise, to start using `::safer_ffi`, follow the following steps: #### Crate layout ##### Step 1: `Cargo.toml` Edit your `Cargo.toml` like so: ``` [package] name = "crate_name" version = "0.1.0" edition = "2021" [lib] crate-type = [ "staticlib", # Ensure it gets compiled as a (static) C library # "cdylib", # If you want a shared/dynamic C library (advanced) "lib", # For `generate-headers` and other downstream rust dependents # such as integration `tests/`, doctests, and `examples/` ] [dependencies] # Use `cargo add` or `cargo search` to find the latest values of x.y.z. # For instance: # cargo add safer-ffi safer-ffi.version = "x.y.z" safer-ffi.features = [] # you may add some later on. [features] # If you want to generate the headers, use a feature-gate # to opt into doing so: headers = ["safer-ffi/headers"] ``` * Where `"x.y.z"` ought to be replaced by the last released version, which you can find by running `cargo search safer-ffi`. * See the dedicated chapter on `Cargo.toml` for more info. ##### Step 2: `src/lib.rs` Then, to export a Rust function to FFI, add the `#[derive_ReprC]` and `#[ffi_export]` attributes like so: ``` use ::safer_ffi::prelude::*; /// A `struct` usable from both Rust and C #[derive_ReprC] #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct Point { x: f64, y: f64, } /* Export a Rust function to the C world. */ /// Returns the middle point of `[a, b]`. #[ffi_export] fn mid_point(a: &Point, b: &Point) -> Point { Point { x: (a.x + b.x) / 2., y: (a.y + b.y) / 2., } } /// Pretty-prints a point using Rust's formatting logic. #[ffi_export] fn print_point(point: &Point) { println!("{:?}", point); } // The following function is only necessary for the header generation. #[cfg(feature = "headers")] // c.f. the `Cargo.toml` section pub fn generate_headers() -> ::std::io::Result<()> { ::safer_ffi::headers::builder() .to_file("rust_points.h")? .generate() } ``` * See the dedicated chapter on `src/lib.rs` for more info. ##### Step 3: `src/bin/generate-headers.rs` ``` fn main() -> ::std::io::Result<()> { ::crate_name::generate_headers() } ``` #### Compilation & header generation ``` # Compile the C library (in `target/{debug,release}/libcrate_name.ext`) cargo build # --release # Generate the C header cargo run --features headers --bin generate-headers ``` * See the dedicated chapter on header generation for more info. Generated C header (`rust_points.h`) ``` /*! \file */ /******************************************* * * * File auto-generated by `::safer_ffi`. * * * * Do not manually edit this file. * * * *******************************************/ #ifndef __RUST_CRATE_NAME__ #define __RUST_CRATE_NAME__ #ifdef __cplusplus extern "C" { #endif #include <stddef.h> #include <stdint.h/** \brief * A `struct` usable from both Rust and C */ typedef struct Point { /** <No documentation available> */ double x; /** <No documentation available> */ double y; } Point_t; /** \brief * Returns the middle point of `[a, b]`. */ Point_t mid_point ( Point_t const * a, Point_t const * b); /** \brief * Pretty-prints a point using Rust's formatting logic. */ void print_point ( Point_t const * point); #ifdef __cplusplus } /* extern \"C\" */ #endif #endif /* __RUST_CRATE_NAME__ */ ``` --- ### Testing it from C Here is a basic example to showcase FFI calling into our exported Rust functions: #### `main.c` ``` #include <stdlib.h#include "rust_points.h" int main (int argc, char const * const argv[]) { Point_t a = { .x = 84, .y = 45 }; Point_t b = { .x = 0, .y = 39 }; Point_t m = mid_point(&a, &b); print_point(&m); return EXIT_SUCCESS; } ``` #### Compilation command ``` cc -o main{,.c} -L target/debug -l crate_name -l{pthread,dl,m} # Now feel free to run the compiled binary ./main ``` * Note regarding the extra `-l…` flags. Those vary based on the version of the Rust standard library being used, and the system being used to compile it. In order to reliably know which ones to use, `rustc` itself ought to be queried for it. Simple command: ``` rustc --crate-type=staticlib --print=native-static-libs -</dev/null ``` this yields, *to the stderr*, output along the lines of: ``` note: Link against the following native artifacts when linking against this static library. The order and any duplication can be significant on some platforms. note: native-static-libs: -lSystem -lresolv -lc -lm -liconv ``` Using something like `sed -nE 's/^note: native-static-libs: (.*)/\1/p'` is thus a convenient way to extract these flags: ``` rustc --crate-type=staticlib --print=native-static-libs -</dev/null \ 2>&1 | sed -nE 's/^note: native-static-libs: (.*)/\1/p' ``` Ideally, you would not query for this information *in a vacuum* (*e.g.*, `/dev/null` file being used as input Rust code just above), and rather, would apply it for your actual code being compiled: ``` cargo rustc -q -- --print=native-static-libs \ 2>&1 | sed -nE 's/^note: native-static-libs: (.*)/\1/p' ``` And if you really wanted to polish things further, you could use the JSON-formatted compiler output (this, for instance, avoids having to redirect `stderr`). But then you’d have to use a JSON parser, such as `jq`: ``` RUST_STDLIB_DEPS=$(set -eo pipefail && \ cargo rustc \ --message-format=json \ -- --print=native-static-libs \ | jq -r ' select (.reason == "compiler-message") | .message.message ' | sed -nE 's/^native-static-libs: (.*)/\1/p' \ ) ``` and then use: ``` cc -o main{,.c} -L target/debug -l crate_name ${RUST_STDLIB_DEPS} ``` which does output: ``` Point { x: 42.0, y: 42.0 } ``` 🚀🚀 ### Development #### Tests safer-ffi includes three different tests suites that can be run. ``` # In the project root: cargo test # FFI tests make -C ffi_tests # JavaScript tests make -C js_tests # Running the JS tests also gives you instructions for running browser tests. # Run this command in the `js_tests` directory, open a browser and navigate to # http://localhost:13337/ wasm-pack build --target web && python3 -m http.server 13337 ``` Re-exports --- * `pub use dyn_traits::futures;` * `pub use tuple::*;` Modules --- * boxed`alloc``#[repr(C)]` `Box`ed types. * char_p`char *`-compatible strings (slim pointers), for easier use from within C. They thus do not support inner nulls, nor string appending. * closureClosures with a `#[repr(C)]` layout (inlined vtable), up to 9 function arguments. * dyn_traits`dyn-traits`See the dedicated section of the guide. * headers`headers`C headers generation. * layoutTrait abstractions describing the semantics of “being `#[repr(C)]`” * libcOn certain platforms, `::libc` has no definitions for pervasive types such as `size_t`. * prelude * ptrWrappers around `NonNull` to better express the semantics of such pointer. * sliceLogic common to all fat pointers. * string`Rust` string types with a defined `#[repr(C)]` layout, albeit not `char *` compatible (*fat* pointers). * tupleTuple types with a guaranteed `#[repr(C)]` layout. * vec`alloc` Macros --- * CTypeSafely implement `CType` for a `#[repr(C)]` struct **when all its fields are `CType`**. * NULL * ReprCTransitioning helper macro: still uses the old `ReprC!` syntax, but just to forward to the new `#[derive_ReprC2($(js)?)]` one. * cCreates a compile-time checked `char_p::Ref``<'static>` out of a string literal. * c_vec`alloc` * ffi_export_future_helpers`dyn-traits` Structs --- * String`alloc`Same as `String`, but with guaranteed `#[repr(C)]` layout * Vec`alloc`Same as `Vec<T>`, but with guaranteed `#[repr(C)]` layout * c_charA `ReprC` *standalone* type with the same layout and ABI as `::libc::c_char`. * c_intA `ReprC` *standalone* type with the same layout and ABI as `::libc::c_int`. Attribute Macros --- * cfg_headersIdentity macro when `feature = "headers"` is enabled, otherwise this macro outputs nothing. * derive_ReprCSafely implement `ReprC` for a `#[repr(C)]` struct **when all its fields are `ReprC`**. * ffi_exportExport a function to be callable by C. Module safer_ffi::dyn_traits::futures === Available on **crate feature `dyn-traits`** only.See the dedicated secion of the guide. Macros --- * ffi_export_future_helpers Structs --- * FfiFutureExecutorVTableC Layout * FfiFutureExecutorVTable_Layout * FfiFutureVTableC Layout * FfiFutureVTable_Layout * PollFuture_Layout Enums --- * PollFutureAn FFI-safe `Poll<()>`. Traits --- * FfiFutureModels a `Future` resolving to `()`. * FfiFutureExecutorModels an `async` runtime’s *handle*. Module safer_ffi::tuple === Tuple types with a guaranteed `#[repr(C)]` layout. Simplified for lighter documentation, but the actual `struct` definitions and impls range from `Tuple1` up to `Tuple6`. Structs --- * Tuple1Simplified for lighter documentation, but the actual impls range from `Tuple1` up to `Tuple6`. * Tuple1_LayoutSimplified for lighter documentation, but the actual impls range from `Tuple1` up to `Tuple6`. * Tuple2Simplified for lighter documentation, but the actual impls range from `Tuple1` up to `Tuple6`. * Tuple2_LayoutSimplified for lighter documentation, but the actual impls range from `Tuple1` up to `Tuple6`. * Tuple3C Layout * Tuple3_Layout * Tuple4C Layout * Tuple4_Layout * Tuple5C Layout * Tuple5_Layout * Tuple6C Layout * Tuple6_Layout Module safer_ffi::boxed === Available on **crate feature `alloc`** only.`#[repr(C)]` `Box`ed types. Re-exports --- * `pub use crate::slice::slice_boxed;` * `pub use crate::string::str_boxed;` Structs --- * Box_Same as `Box<T>`, (*e.g.*, same `#[repr(C)]` layout), but with **no non-aliasing guarantee**. Traits --- * FitForCArc * FitForCBox Type Aliases --- * Box Module safer_ffi::char_p === `char *`-compatible strings (slim pointers), for easier use from within C. They thus do not support inner nulls, nor string appending. Structs --- * InvalidNulTerminator * char_p_boxedA `#[repr(c)]` null-terminated UTF-8 encoded string, for compatibility with both the `char *` C API and Rust `str`. * char_p_rawSame as `char_p_ref`, but without any lifetime attached whatsoever. * char_p_refA `#[repr(c)]` null-terminated UTF-8 encoded string, for compatibility with both the C `char *` API and Rust’s `str`. Functions --- * new`alloc`Constructs a new `char_p::Box` off a stringy input. Module safer_ffi::closure === Closures with a `#[repr(C)]` layout (inlined vtable), up to 9 function arguments. Simplified for lighter documentation, but the actual `struct` definitions and impls range up to `...DynFn...9`. ### Examples #### FFI-safe `Box<dyn FnMut()>` * ``` use ::safer_ffi::prelude::*; let mut captured = String::from("…"); let ffi_safe: repr_c::Box<dyn Send + FnMut()> = Box::new(move || { captured.push('!'); println!("{}", captured); }) .into() ; fn assert_ffi_safe (_: &impl ReprC) {} assert_ffi_safe(&ffi_safe); ``` #### FFI-safe `Arc<dyn Fn()>` * ``` use ::{ safer_ffi::{ prelude::*, }, std::{ sync::Arc, }, }; let captured = String::from("…"); let ffi_safe: repr_c::Arc<dyn Send + Sync + Fn()> = Arc::new(move || { println!("{}", captured); }) .into() ; fn assert_ffi_safe (_: &impl ReprC) {} assert_ffi_safe(&ffi_safe); ``` Re-exports --- * `pub use self::arc::ArcDynFn0;` * `pub use self::arc::ArcDynFn1;` * `pub use self::boxed::BoxDynFnMut0;` * `pub use self::boxed::BoxDynFnMut1;` * `pub use self::arc::ArcDynFn2;` * `pub use self::arc::ArcDynFn3;` * `pub use self::arc::ArcDynFn4;` * `pub use self::arc::ArcDynFn5;` * `pub use self::arc::ArcDynFn6;` * `pub use self::arc::ArcDynFn7;` * `pub use self::arc::ArcDynFn8;` * `pub use self::arc::ArcDynFn9;` * `pub use self::boxed::BoxDynFnMut2;` * `pub use self::boxed::BoxDynFnMut3;` * `pub use self::boxed::BoxDynFnMut4;` * `pub use self::boxed::BoxDynFnMut5;` * `pub use self::boxed::BoxDynFnMut6;` * `pub use self::boxed::BoxDynFnMut7;` * `pub use self::boxed::BoxDynFnMut8;` * `pub use self::boxed::BoxDynFnMut9;` * `pub use borrowed::RefDynFnMut0;` * `pub use borrowed::RefDynFnMut1;` * `pub use borrowed::RefDynFnMut2;` * `pub use borrowed::RefDynFnMut3;` * `pub use borrowed::RefDynFnMut4;` * `pub use borrowed::RefDynFnMut5;` * `pub use borrowed::RefDynFnMut6;` * `pub use borrowed::RefDynFnMut7;` * `pub use borrowed::RefDynFnMut8;` * `pub use borrowed::RefDynFnMut9;` Modules --- * arc`alloc``Arc<dyn 'static + Send + Sync + Fn(...) -> _>` but with a `#[repr(C)]` layout (inlined virtual method table). * borrowed`&'lt mut (dyn 'lt + Send + FnMut(...) -> _>` but with a `#[repr(C)]` layout (env ptr + function ptr). * boxed`alloc``Box<dyn 'static + Send + FnMut(...) -> _>` but with a `#[repr(C)]` layout (inlined virtual method table). Module safer_ffi::dyn_traits === Available on **crate feature `dyn-traits`** only.See the dedicated section of the guide. Re-exports --- * `pub use dyn_drop::*;` Modules --- * dyn_drop * futuresSee the dedicated secion of the guide. Structs --- * ErasedRefC Layout * ErasedTy * VirtualPtrC Layout Traits --- * DynClone * ReprCTrait * VirtualPtrFrom Module safer_ffi::headers === Available on **crate feature `headers`** only.C headers generation. This module is only enabled when the `"headers"` feature of `::safer_ffi` is enabled, which is expected to be done through a cargo feature within the (downstream) crate defining the `#[ffi_export]`ed functions. ``` [dependencies] safer-ffi = { version = "...", features = ["proc_macros"] } [features] generate-headers = ["safer-ffi/headers"] ``` Then, to generate the bindings, just define a `#[safer_ffi::cfg_headers]`-gated `#[test]` function, which can then call the `builder` to do the work: ``` use ::std::{io, fs}; use ::safer_ffi::prelude::*; /// Concatenate two strings. /// /// The returned value must be freed with `rust_free` #[ffi_export] fn rust_concat (fst: char_p::Ref<'_>, snd: char_p::Ref<'_>) -> char_p::Box { let s: String = format!("{}{}\0", fst, snd); s .try_into() // Try to convert to a boxed `char *` pointer .unwrap() // Only fails if there is an inner nul byte. } /// Frees a pointer obtained by calling `rust_concat`. #[ffi_export] fn rust_free (it: char_p::Box) { drop(it); } #[::safer_ffi::cfg_headers] #[test] fn generate_c_header () -> io::Result<()> { ::safer_ffi::headers::builder() .with_guard("__ASGARD__") .to_file("filename.h")? .generate() } ``` so that ``` cargo test --features generate-headers -- \ --exact generate_c_header \ --nocapture ``` generates a `"filename.h"` file (⚠️ overwriting it if it exists ⚠️) with the following contents: ``` /*! \file */ /*******************************************  * *  * File auto-generated by `::safer_ffi`. *  * *  * Do not manually edit this file. *  * *  *******************************************/ #ifndef __ASGARD__ #define __ASGARD__ /** \brief  * Concatenate two strings.  *  * The returned value must be freed with `rust_free_string`  */ char * rust_concat ( char const * fst, char const * snd); /** \brief  * Frees a pointer obtained by calling `rust_concat`.  */ void rust_free_string ( char * it); #endif /* __ASGARD__ */ ``` Modules --- * languages Structs --- * Builder * HashSetDefinerSimplest implementation of a `Definer`: a `HashSet<String>, &'_ mut dyn Write` pair. Enums --- * LanguageLanguage of the generated headers. * NamingConventionAllow user to specify Traits --- * DefinerHelper for the generation of C headers. Functions --- * builder Module safer_ffi::layout === Trait abstractions describing the semantics of “being `#[repr(C)]`” Modules --- * OpaqueKindType-level `enum` Macros --- * CTypeSafely implement `CType` for a `#[repr(C)]` struct **when all its fields are `CType`**. * ReprCTransitioning helper macro: still uses the old `ReprC!` syntax, but just to forward to the new `#[derive_ReprC2($(js)?)]` one. * from_CType_impl_ReprCFor clarity; this macro may be stabilized if downstream users find it useful * Structs --- * Opaque Traits --- * CTypeSafety (non-exhaustive list at the moment): * ConcreteReprCAlias for `ReprC where Self::CLayout::OPAQUE_KIND = OpaqueKind::Concrete` * LegacyCTypeOne of the two core traits of this crate (with `ReprC`). * ReprCThe meat of the crate. *The* trait. This trait describes that **a type has a defined / fixed `#[repr(C)]` layout**. Functions --- * from_raw⚠ * from_raw_unchecked⚠ * into_raw⚠ Type Aliases --- * CLayoutOf Attribute Macros --- * derive_ReprC Module safer_ffi::libc === On certain platforms, `::libc` has no definitions for pervasive types such as `size_t`. We polyfill them here, and reëxport them for downstream users to use at leisure (*e.g.*, so that they don’t have to do that themselves too!). ``` pub use :: libc :: { #[doc = r" Note: you should probably be using [`crate::c_char`] instead."] c_char else u8, #[doc = r" Note: you should probably be using [`crate::c_int`] instead."] c_int else :: core :: ffi :: c_int, #[doc = r""] size_t else usize, #[doc = r""] uintptr_t else usize, } ; ``` Type Aliases --- * c_charA *`type` alias* to `::libc::c_char`. * c_intA *`type` alias* to `::libc::c_int`. * size_tA *`type` alias* to `::libc::size_t`. * uintptr_tA *`type` alias* to `::libc::uintptr_t`. Module safer_ffi::ptr === Wrappers around `NonNull` to better express the semantics of such pointer. Useful when manually defining custom low-level `ReprC` types. Re-exports --- * `pub use ::core::ptr::*;` Structs --- * NonNullMut * NonNullOwned * NonNullRef Module safer_ffi::slice === Logic common to all fat pointers. Re-exports --- * `pub use self::slice_ref as Ref;` * `pub use self::slice_mut as Mut;` * `pub use slice_boxed as Box;` Structs --- * slice_boxed`Box``<[T]>` (fat pointer to a slice), but with a guaranteed `#[repr(C)]` layout. * slice_boxed_Layout`Box``<[T]>` (fat pointer to a slice), but with a guaranteed `#[repr(C)]` layout. * slice_mut`&'lt mut [T]` but with a guaranteed `#[repr(C)]` layout. * slice_mut_Layout`&'lt mut [T]` but with a guaranteed `#[repr(C)]` layout. * slice_rawLike `slice_ref` and `slice_mut`, but with any lifetime attached whatsoever. * slice_raw_LayoutLike `slice_ref` and `slice_mut`, but with any lifetime attached whatsoever. * slice_ref`&'lt [T]` but with a guaranteed `#[repr(C)]` layout. * slice_ref_Layout`&'lt [T]` but with a guaranteed `#[repr(C)]` layout. Module safer_ffi::string === `Rust` string types with a defined `#[repr(C)]` layout, albeit not `char *` compatible (*fat* pointers). Structs --- * StringSame as `String`, but with guaranteed `#[repr(C)]` layout * str_boxedSame as `Box``<str>`, but with a guaranteed `#[repr(C)]` layout. * str_ref`&'lt str`, but with a guaranteed `#[repr(C)]` layout. Macro safer_ffi::CType === ``` macro_rules! CType { ( $( @doc_meta( $($doc_meta:tt)* ) )? #[repr(C $(, js $(@$js:tt)?)? $(,)?)] $(#[$($meta:tt)*])* $pub:vis struct $StructName:ident $( [ $($lt:lifetime ,)* $($($generics:ident),+ $(,)?)? ] $(where { $($bounds:tt)* })? )? { $( $(#[$($field_meta:tt)*])* $field_pub:vis $field_name:ident : $field_ty:ty ),+ $(,)? } ) => { ... }; ( @js_enum $Enum_Layout:ident { $( $Variant:ident = $Discriminant:expr ),* $(,)? } ) => { ... }; } ``` Safely implement `CType` for a `#[repr(C)]` struct **when all its fields are `CType`**. Note: you rarely need to call this macro directly. Instead, look for the [`ReprC!`] macro to safely implement `ReprC`. Trait safer_ffi::layout::LegacyCType === ``` pub unsafe trait LegacyCType: Sized + Copy + CType { type OPAQUE_KIND: T; // Required methods fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result; fn c_define_self(definer: &mut dyn Definer) -> Result<()>; fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result; fn csharp_define_self(definer: &mut dyn Definer) -> Result<()>; // Provided methods fn c_short_name() -> ImplDisplay<Self> { ... } fn c_var(var_name: &str) -> ImplDisplay<'_, Self> { ... } fn legacy_csharp_marshaler() -> Option<String> { ... } fn csharp_ty() -> String { ... } fn csharp_var(var_name: &str) -> String { ... } } ``` One of the two core traits of this crate (with `ReprC`). `CType` is an `unsafe` trait that binds a Rust type to a C typedef. To optimise compile-times, the C typedef part is gated behind the `headers` cargo feature, so when that feature is not enabled, the trait may “look” like a marker trait, but it isn’t. That’s why **manually implementing this trait is strongly discouraged**, although not forbidden: * If you trully want a manual implementation of `CType` (*e.g.*, for an “opaque type” pattern, *i.e.*, a forward declaration), then, to implement the trait so that it works no matter the status of the `safer_ffi/headers` feature, one must define the methods as if feature was present, but with a `#[::safer_ffi::cfg_headers]` gate slapped on *each* method. Safety --- The Rust type in an `extern "C"` function must have the same layout and ABI as the defined C type, and all the bit-patterns representing any instance of such C type must be valid and safe bit-patterns for the Rust type. For the most common types, there are only two reasons to correctly be a `CType`: * being a primitive type, such as an integer type or a (slim) pointer. + This crates provides as many of these implementations as possible. * and recursively, a non-zero-sized `#[repr(C)]` struct of `CType` fields. + the `CType!` macro can be used to wrap a `#[repr(C)]` struct definition to *safely* and automagically implement the trait when it is sound to do so. Note that types such as Rust’s `bool` are ruled out by this definition, since it has the ABI of a `u8 <-> uint8_t`, and yet there are many bit-patterns for the `uint8_t` type that do not make *valid* `bool`s. For such types, see the `ReprC` trait. Required Associated Types --- #### type OPAQUE_KIND: T Required Methods --- #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result A short-name description of the type, mainly used to fill “placeholders” such as when monomorphising generics structs or arrays. This provides the implementation used by [`CType::c_short_name`]`()`. There are no bad implementations of this method, except, of course, for the obligation to provide a valid identifier chunk, *i.e.*, the output must only contain alphanumeric digits and underscores. For instance, given `T : CType` and `const N: usize > 0`, the type `[T; N]` (inline fixed-size array of `N` consecutive elements of type `T`) will be typedef-named as: ``` write!(fmt, "{}_{}_array", <T as CType>::c_short_name(), N) ``` Generally, typedefs with a trailing `_t` will see that `_t` trimmed when used as a `short_name`. ###### Implementation by `CType!`: A non generic struct such as: ``` CType! { #[repr(C)] struct Foo { /* fields */ } } ``` will have `Foo` as its `short_name`. A generic struct such as: ``` CType! { #[repr(C)] struct Foo[T] where { T : CType } { /* fields */ } } ``` will have `Foo_xxx` as its `short_name`, with `xxx` being `T`’s `short_name`. #### fn c_define_self(definer: &mut dyn Definer) -> Result<()Necessary one-time code for [`CType::c_var`]`()` to make sense. Some types, such as `char`, are part of the language, and can be used directly by [`CType::c_var`]`()`. In that case, there is nothing else to *define*, and all is fine. * That is the default implementation of this method: doing nothing. But most often than not, a `typedef` or an `#include` is required. In that case, here is the place to put it, with the help of the provided `Definer`. ##### Idempotent Given some `definer: &mut dyn Definer`, **the `c_define_self(definer)` call must be idempotent *w.r.t.* code generated**. In other words, two or more such calls must not generate any extra code *w.r.t* the first call. This is easy to achieve thanks to `definer`: ``` // This ensures the idempotency requirements are met. definer.define_once( // some unique `&str`, ideally the C name being defined: "my_super_type_t", // Actual code generation logic, writing to `definer.out()` &mut |definer| { // If the typdef recursively needs other types being defined, // ensure it is the case by explicitly calling // `c_define_self(definer)` on those types. OtherType::c_define_self(definer)?; write!(definer.out(), "typedef ... my_super_type_t;", ...) }, )? ``` ##### Safety Given that the defined types may be used by [`CType::c_var_fmt`]`()`, the same safety disclaimers apply. ###### Examples ###### `i32` The corresponding type for `i32` in C is `int32_t`, but such type definition is not part of the language, it is brought by a library instead: `<stdint.h>` (or `<inttypes.h>` since it includes it). ``` unsafe impl CType for i32 { #[::safer_ffi::cfg_headers] fn c_define_self (definer: &'_ mut dyn Definer) -> io::Result<()> { definer.define_once("<stdint.h>", &mut |definer| { write!(definer.out(), "\n#include <stdint.h>\n") }) } // ... } ``` ###### `#[repr(C)] struct Foo { x: i32 }` ``` #[repr(C)] struct Foo { x: i32, } unsafe impl CType for i32 { #[::safer_ffi::cfg_headers] fn c_define_self (definer: &'_ mut dyn Definer) -> io::Result<()> { definer.define_once("Foo_t", &mut |definer| { // ensure int32_t makes sense <i32 as CType>::c_define_self(definer)?; write!(definer.out(), "typedef struct {{ {}; }} Foo_t;", <i32 as CType>::c_var("x"), ) }) } // ... } ``` #### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result The core method of the trait: it provides the implementation to be used by [`CType::c_var`], by bringing a `Formatter` in scope. This provides the implementation used by [`CType::c_var`]`()`. The implementations are thus much like any classic `Display` impl, except that: * it must output valid C code representing the type corresponding to the Rust type. * a `var_name` may be supplied, in which case the type must use that as its “variable name” (C being how it is, the var name may need to be inserted in the middle of the types, such as with arrays and function pointers). ##### Safety Here is where the meat of the safety happens: associating a Rust type to a non-corresponding C definition will cause Undefined Behavior when a function using such type in its ABI is called. ###### Examples ###### `i32` ``` unsafe impl CType for i32 { #[::safer_ffi::cfg_headers] fn c_var_fmt ( fmt: &'_ mut fmt::Formatter<'_>, var_name: &'_ str, ) -> fmt::Result { write!(fmt, "int32_t {}", var_name) } // ... } ``` ###### `Option<extern "C" fn (i32) -> u32>` ``` unsafe impl CType for Option<extern "C" fn (i32) -> u32> { #[::safer_ffi::cfg_headers] fn c_var_fmt ( fmt: &'_ mut fmt::Formatter<'_>, var_name: &'_ str, ) -> fmt::Result { write!(fmt, "uint32_t (*{})(int32_t)", var_name) } // ... } ``` ###### `[i32; 42]` ``` unsafe impl CType for [i32; 42] { #[::safer_ffi::cfg_headers] fn c_var_fmt ( fmt: &'_ mut fmt::Formatter<'_>, var_name: &'_ str, ) -> fmt::Result { let typedef_name = format_args!("{}_t", Self::c_short_name()); write!(fmt, "{} {}", typedef_name, var_name) } // Since `c_var_fmt()` requires a one-time typedef, overriding // `c_define_self()` is necessary: #[::safer_ffi::cfg_headers] fn c_define_self (definer: &'_ mut dyn Definer) -> fmt::Result { let typedef_name = &format!("{}_t", Self::c_short_name()); definer.define_once(typedef_name, &mut |definer| { // ensure the array element type is defined i32::c_define_self(definer)?; write!(definer.out(), "typedef struct {{ {0}; }} {1};\n", i32::c_var("arr[42]"), // `int32_t arr[42]` typedef_name, ) }) } // etc. } ``` #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()Extra typedef code (*e.g.* `[LayoutKind.Sequential] struct ...`) Provided Methods --- #### fn c_short_name() -> ImplDisplay<SelfConvenience function for *callers* / users of types implementing `CType`. The `Display` logic is auto-derived from the implementation of [`CType::c_short_name_fmt`]`()`. #### fn c_var(var_name: &str) -> ImplDisplay<'_, SelfConvenience function for *callers* / users of types implementing `CType`. The `Display` logic is auto-derived from the implementation of [`CType::c_var_fmt`]`()`. #### fn legacy_csharp_marshaler() -> Option<StringOptional marshaler attached to the type (*e.g.*, `[MarshalAs(UnmanagedType.FunctionPtr)]`) #### fn csharp_ty() -> String Type name (*e.g.*, `int`, `string`, `IntPtr`) #### fn csharp_var(var_name: &str) -> String Convenience function for formatting `{ty} {var}` in CSharp. Implementations on Foreign Types --- ### impl<Item: CType> LegacyCType for [Item; 7] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 14] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 1000] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 2] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 60] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Ret: CType, A9: CType, A8: CType, A7: CType, A6: CType, A5: CType, A4: CType, A3: CType, A2: CType, A1: CType> LegacyCType for Option<unsafe extern "C" fn(_: A9, _: A8, _: A7, _: A6, _: A5, _: A4, _: A3, _: A2, _: A1) -> RetSimplified for lighter documentation, but the actual impls include **up to 9 function parameters**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### fn legacy_csharp_marshaler() -> Option<String#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 3] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl LegacyCType for u16 #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 11] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 600] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 20] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 1] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 30] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Ret: CType, A2: CType, A1: CType> LegacyCType for Option<unsafe extern "C" fn(_: A2, _: A1) -> RetSimplified for lighter documentation, but the actual impls include **up to 9 function parameters**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### fn legacy_csharp_marshaler() -> Option<String#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 9] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Ret: CType, A1: CType> LegacyCType for Option<unsafe extern "C" fn(_: A1) -> RetSimplified for lighter documentation, but the actual impls include **up to 9 function parameters**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### fn legacy_csharp_marshaler() -> Option<String#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 15] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl LegacyCType for u64 #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 250] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 48] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl LegacyCType for isize #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 29] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 70] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Ret: CType, A8: CType, A7: CType, A6: CType, A5: CType, A4: CType, A3: CType, A2: CType, A1: CType> LegacyCType for Option<unsafe extern "C" fn(_: A8, _: A7, _: A6, _: A5, _: A4, _: A3, _: A2, _: A1) -> RetSimplified for lighter documentation, but the actual impls include **up to 9 function parameters**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### fn legacy_csharp_marshaler() -> Option<String#### type OPAQUE_KIND = Concrete ### impl<Ret: CType, A5: CType, A4: CType, A3: CType, A2: CType, A1: CType> LegacyCType for Option<unsafe extern "C" fn(_: A5, _: A4, _: A3, _: A2, _: A1) -> RetSimplified for lighter documentation, but the actual impls include **up to 9 function parameters**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### fn legacy_csharp_marshaler() -> Option<String#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 96] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Ret: CType> LegacyCType for Option<unsafe extern "C" fn() -> RetSimplified for lighter documentation, but the actual impls include **up to 9 function parameters**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### fn legacy_csharp_marshaler() -> Option<String#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 512] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Ret: CType, A4: CType, A3: CType, A2: CType, A1: CType> LegacyCType for Option<unsafe extern "C" fn(_: A4, _: A3, _: A2, _: A1) -> RetSimplified for lighter documentation, but the actual impls include **up to 9 function parameters**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### fn legacy_csharp_marshaler() -> Option<String#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 18] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<T: CType> LegacyCType for *mut T #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl LegacyCType for f32 #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn c_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl LegacyCType for i16 #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 125] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 28] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl LegacyCType for u32 #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 200] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl LegacyCType for i64 #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 75] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Ret: CType, A7: CType, A6: CType, A5: CType, A4: CType, A3: CType, A2: CType, A1: CType> LegacyCType for Option<unsafe extern "C" fn(_: A7, _: A6, _: A5, _: A4, _: A3, _: A2, _: A1) -> RetSimplified for lighter documentation, but the actual impls include **up to 9 function parameters**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### fn legacy_csharp_marshaler() -> Option<String#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 8] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 6] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 40] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 90] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 256] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 128] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 21] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 26] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 12] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 16] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 64] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 24] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 22] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 750] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 25] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 300] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 23] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 31] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 19] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<T: CType> LegacyCType for *const T #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl LegacyCType for i8 #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 10] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 27] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl LegacyCType for f64 #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn c_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl<Ret: CType, A6: CType, A5: CType, A4: CType, A3: CType, A2: CType, A1: CType> LegacyCType for Option<unsafe extern "C" fn(_: A6, _: A5, _: A4, _: A3, _: A2, _: A1) -> RetSimplified for lighter documentation, but the actual impls include **up to 9 function parameters**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### fn legacy_csharp_marshaler() -> Option<String#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 100] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 192] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 400] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 5] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 1024] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Ret: CType, A3: CType, A2: CType, A1: CType> LegacyCType for Option<unsafe extern "C" fn(_: A3, _: A2, _: A1) -> RetSimplified for lighter documentation, but the actual impls include **up to 9 function parameters**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### fn legacy_csharp_marshaler() -> Option<String#### type OPAQUE_KIND = Concrete ### impl LegacyCType for i32 #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl LegacyCType for u8 #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 800] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 500] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 17] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 13] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 32] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 80] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl LegacyCType for usize #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(_: &mut dyn Definer) -> Result<()#### fn csharp_ty() -> String #### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 700] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 50] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 4] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete ### impl<Item: CType> LegacyCType for [Item; 900] Simplified for lighter documentation, but the actual impls range **from `1` up to `32`, plus a bunch of significant lengths up to `1024`**. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result #### fn c_define_self(definer: &mut dyn Definer) -> Result<()#### fn c_var_fmt(fmt: &mut Formatter<'_>, var_name: &str) -> Result #### fn csharp_define_self(definer: &mut dyn Definer) -> Result<()#### type OPAQUE_KIND = Concrete Implementors --- ### impl LegacyCType for c_char #### type OPAQUE_KIND = Concrete ### impl LegacyCType for c_int #### type OPAQUE_KIND = Concrete Macro safer_ffi::ReprC === ``` macro_rules! ReprC { ( $( @[doc = $doc:expr] )? $( #[doc = $doc2:expr] )* #[repr( $C_or_transparent:ident $(, $($(@$if_js:tt)? js $(,)? )? )? )] $( #[$attr:meta] )* $pub:vis struct $StructName:ident $([$($generics:tt)*])? $( where { $($wc:tt)* } )? $({ $($body:tt)* })? $(( $($body2:tt)* );)? ) => { ... }; } ``` Transitioning helper macro: still uses the old `ReprC!` syntax, but just to forward to the new `#[derive_ReprC2($(js)?)]` one. Macro safer_ffi::c === ``` c!() { /* proc-macro */ } ``` Creates a compile-time checked `char_p::Ref``<'static>` out of a string literal. Example --- ``` use ::safer_ffi::prelude::*; #[ffi_export] fn concat (s1: char_p::Ref<'_>, s2: char_p::Ref<'_>) -> char_p::Box { format!("{}{}", s1.to_str(), s2.to_str()) .try_into() .unwrap() // No inner nulls in our format string } fn main () { assert_eq!( concat(c!("Hello, "), c!("World!")).as_ref(), c!("Hello, World!"), ); } ``` If the string literal contains an inner null byte, then the macro will detect it at compile time and thus cause a compile-time error (allowing to skip the then unnecessary runtime check!): ``` let _ = ::safer_ffi::c!("Hell\0, World!"); // <- Compile error ``` Struct safer_ffi::char_p::char_p_ref === ``` #[repr(transparent)]pub struct char_p_ref<'lt>(/* private fields */); ``` A `#[repr(c)]` null-terminated UTF-8 encoded string, for compatibility with both the C `char *` API and Rust’s `str`. This is a **borrowed** version, *i.e.*, with the semantics of `&'lt CStr` / `&'lt str`, but for it being a *slim* pointer. C Layout --- * `ptr :: NonNullRef < c_char >` Implementations --- ### impl char_p_ref<'static#### pub const EMPTY: Self = _ ### impl<'lt> char_p_ref<'lt#### pub const unsafe fn from_ptr_unchecked(ptr: NonNull<u8>) -> Self ### impl<'lt> char_p_ref<'lt#### pub fn bytes(self: char_p_ref<'lt>) -> impl Iterator<Item = NonZeroU8> + 'lt #### pub fn to_nonzero_bytes(self: char_p_ref<'lt>) -> &'lt [NonZeroU8] #### pub fn to_bytes(self: char_p_ref<'lt>) -> &'lt [u8] #### pub fn to_bytes_with_null(self: char_p_ref<'lt>) -> &'lt [u8] #### pub fn to_str(self: char_p_ref<'lt>) -> &'lt str #### pub fn to_str_with_null(self: char_p_ref<'lt>) -> &'lt str #### pub fn to_string(&self) -> String Available on **crate feature `alloc`** only.Poor-man’s specialization of `ToString::to_string()` #### pub fn to_owned(self: char_p_ref<'lt>) -> char_p_boxed Available on **crate feature `alloc`** only.Trait Implementations --- ### impl<'lt> Clone for char_p_ref<'lt#### fn clone(&self) -> char_p_ref<'ltReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. Formats the value using the given formatter. Panics if the `CStr` is not valid UTF-8. #### fn from(s: &'lt CStr) -> char_p_ref<'ltConverts to this type from the input type.### impl<'lt> From<char_p_ref<'lt>> for char_p_raw #### fn from(it: char_p_ref<'lt>) -> char_p_raw Converts to this type from the input type.### impl<'lt> PartialEq<char_p_ref<'lt>> for char_p_ref<'lt#### fn eq(&self, other: &Self) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<'lt> ReprC for char_p_ref<'lt>where NonNullRef<c_char>: ReprC, #### type CLayout = <NonNullRef<c_char> as ReprC>::CLayout The `CType` having the same layout as `Self`.#### fn is_valid(it: &Self::CLayout) -> bool Sanity checks that can be performed on an instance of the `CType` layout. for<'lt> &'lt [u8]: Send, ### impl Sync for char_p_ref<'_>where for<'lt> &'lt [u8]: Sync, Auto Trait Implementations --- ### impl<'lt> RefUnwindSafe for char_p_ref<'lt### impl<'lt> Unpin for char_p_ref<'lt### impl<'lt> UnwindSafe for char_p_ref<'ltBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: Copy, #### fn as_out<'out>(&'out mut self) -> Out<'out, T### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn compat(self) -> Compat<TApplies the `Compat` adapter by value. <T as ReprC>::CLayout: CType<OPAQUE_KIND = Concrete>, T: ReprC + ?Sized, #### type ConcreteCLayout = <T as ReprC>::CLayout ### impl<T> FitForCBox for T #### type CBoxWrapped = Box_<TAvailable on **crate feature `alloc`** only.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ManuallyDropMut for T #### type Ret = ManuallyDrop<T#### fn manually_drop_mut<'__>(&'__ mut self) -> &'__ mut ManuallyDrop<T### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> UpcastAny for Twhere T: 'static, #### fn upcast_any(&self) -> &(dyn Any + 'static) Available on **crate feature `headers`** only.{"&'lt [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","Compat<&T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","Compat<&mut T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","Compat<T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>"} Struct safer_ffi::String === ``` pub struct String(/* private fields */); ``` Available on **crate feature `alloc`** only.Same as `String`, but with guaranteed `#[repr(C)]` layout C Layout --- * `Vec < u8 >` Implementations --- ### impl String #### pub const EMPTY: Self = _ #### pub fn with_rust_mut<R>( self: &mut String, f: impl FnOnce(&mut String) -> R ) -> R Methods from Deref<Target = str> --- 1.0.0 · source#### pub fn len(&self) -> usize Returns the length of `self`. This length is in bytes, not `char`s or graphemes. In other words, it might not be what a human considers the length of the string. ##### Examples ``` let len = "foo".len(); assert_eq!(3, len); assert_eq!("ƒoo".len(), 4); // fancy f! assert_eq!("ƒoo".chars().count(), 3); ``` 1.0.0 · source#### pub fn is_empty(&self) -> bool Returns `true` if `self` has a length of zero bytes. ##### Examples ``` let s = ""; assert!(s.is_empty()); let s = "not empty"; assert!(!s.is_empty()); ``` 1.9.0 · source#### pub fn is_char_boundary(&self, index: usize) -> bool Checks that `index`-th byte is the first byte in a UTF-8 code point sequence or the end of the string. The start and end of the string (when `index == self.len()`) are considered to be boundaries. Returns `false` if `index` is greater than `self.len()`. ##### Examples ``` let s = "Löwe 老虎 Léopard"; assert!(s.is_char_boundary(0)); // start of `老` assert!(s.is_char_boundary(6)); assert!(s.is_char_boundary(s.len())); // second byte of `ö` assert!(!s.is_char_boundary(2)); // third byte of `老` assert!(!s.is_char_boundary(8)); ``` #### pub fn floor_char_boundary(&self, index: usize) -> usize 🔬This is a nightly-only experimental API. (`round_char_boundary`)Finds the closest `x` not exceeding `index` where `is_char_boundary(x)` is `true`. This method can help you truncate a string so that it’s still valid UTF-8, but doesn’t exceed a given number of bytes. Note that this is done purely at the character level and can still visually split graphemes, even though the underlying characters aren’t split. For example, the emoji 🧑‍🔬 (scientist) could be split so that the string only includes 🧑 (person) instead. ##### Examples ``` #![feature(round_char_boundary)] let s = "❤️🧡💛💚💙💜"; assert_eq!(s.len(), 26); assert!(!s.is_char_boundary(13)); let closest = s.floor_char_boundary(13); assert_eq!(closest, 10); assert_eq!(&s[..closest], "❤️🧡"); ``` #### pub fn ceil_char_boundary(&self, index: usize) -> usize 🔬This is a nightly-only experimental API. (`round_char_boundary`)Finds the closest `x` not below `index` where `is_char_boundary(x)` is `true`. If `index` is greater than the length of the string, this returns the length of the string. This method is the natural complement to `floor_char_boundary`. See that method for more details. ##### Examples ``` #![feature(round_char_boundary)] let s = "❤️🧡💛💚💙💜"; assert_eq!(s.len(), 26); assert!(!s.is_char_boundary(13)); let closest = s.ceil_char_boundary(13); assert_eq!(closest, 14); assert_eq!(&s[..closest], "❤️🧡💛"); ``` 1.0.0 · source#### pub fn as_bytes(&self) -> &[u8] Converts a string slice to a byte slice. To convert the byte slice back into a string slice, use the `from_utf8` function. ##### Examples ``` let bytes = "bors".as_bytes(); assert_eq!(b"bors", bytes); ``` 1.0.0 · source#### pub fn as_ptr(&self) -> *constu8 Converts a string slice to a raw pointer. As string slices are a slice of bytes, the raw pointer points to a `u8`. This pointer will be pointing to the first byte of the string slice. The caller must ensure that the returned pointer is never written to. If you need to mutate the contents of the string slice, use `as_mut_ptr`. ##### Examples ``` let s = "Hello"; let ptr = s.as_ptr(); ``` 1.20.0 · source#### pub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>where I: SliceIndex<str>, Returns a subslice of `str`. This is the non-panicking alternative to indexing the `str`. Returns `None` whenever equivalent indexing operation would panic. ##### Examples ``` let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` 1.20.0 · source#### pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Outputwhere I: SliceIndex<str>, Returns an unchecked subslice of `str`. This is the unchecked alternative to indexing the `str`. ##### Safety Callers of this function are responsible that these preconditions are satisfied: * The starting index must not exceed the ending index; * Indexes must be within bounds of the original slice; * Indexes must lie on UTF-8 sequence boundaries. Failing that, the returned string slice may reference invalid memory or violate the invariants communicated by the `str` type. ##### Examples ``` let v = "🗻∈🌏"; unsafe { assert_eq!("🗻", v.get_unchecked(0..4)); assert_eq!("∈", v.get_unchecked(4..7)); assert_eq!("🌏", v.get_unchecked(7..11)); } ``` 1.0.0 · source#### pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str 👎Deprecated since 1.29.0: use `get_unchecked(begin..end)` insteadCreates a string slice from another string slice, bypassing safety checks. This is generally not recommended, use with caution! For a safe alternative see `str` and `Index`. This new slice goes from `begin` to `end`, including `begin` but excluding `end`. To get a mutable string slice instead, see the `slice_mut_unchecked` method. ##### Safety Callers of this function are responsible that three preconditions are satisfied: * `begin` must not exceed `end`. * `begin` and `end` must be byte positions within the string slice. * `begin` and `end` must lie on UTF-8 sequence boundaries. ##### Examples ``` let s = "Löwe 老虎 Léopard"; unsafe { assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21)); } let s = "Hello, world!"; unsafe { assert_eq!("world", s.slice_unchecked(7, 12)); } ``` 1.4.0 · source#### pub fn split_at(&self, mid: usize) -> (&str, &str) Divide one string slice into two at an index. The argument, `mid`, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point. The two slices returned go from the start of the string slice to `mid`, and from `mid` to the end of the string slice. To get mutable string slices instead, see the `split_at_mut` method. ##### Panics Panics if `mid` is not on a UTF-8 code point boundary, or if it is past the end of the last code point of the string slice. ##### Examples ``` let s = "<NAME>"; let (first, last) = s.split_at(3); assert_eq!("Per", first); assert_eq!(" Martin-Löf", last); ``` 1.0.0 · source#### pub fn chars(&self) -> Chars<'_Returns an iterator over the `char`s of a string slice. As a string slice consists of valid UTF-8, we can iterate through a string slice by `char`. This method returns such an iterator. It’s important to remember that `char` represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want. This functionality is not provided by Rust’s standard library, check crates.io instead. ##### Examples Basic usage: ``` let word = "goodbye"; let count = word.chars().count(); assert_eq!(7, count); let mut chars = word.chars(); assert_eq!(Some('g'), chars.next()); assert_eq!(Some('o'), chars.next()); assert_eq!(Some('o'), chars.next()); assert_eq!(Some('d'), chars.next()); assert_eq!(Some('b'), chars.next()); assert_eq!(Some('y'), chars.next()); assert_eq!(Some('e'), chars.next()); assert_eq!(None, chars.next()); ``` Remember, `char`s might not match your intuition about characters: ``` let y = "y̆"; let mut chars = y.chars(); assert_eq!(Some('y'), chars.next()); // not 'y̆' assert_eq!(Some('\u{0306}'), chars.next()); assert_eq!(None, chars.next()); ``` 1.0.0 · source#### pub fn char_indices(&self) -> CharIndices<'_Returns an iterator over the `char`s of a string slice, and their positions. As a string slice consists of valid UTF-8, we can iterate through a string slice by `char`. This method returns an iterator of both these `char`s, as well as their byte positions. The iterator yields tuples. The position is first, the `char` is second. ##### Examples Basic usage: ``` let word = "goodbye"; let count = word.char_indices().count(); assert_eq!(7, count); let mut char_indices = word.char_indices(); assert_eq!(Some((0, 'g')), char_indices.next()); assert_eq!(Some((1, 'o')), char_indices.next()); assert_eq!(Some((2, 'o')), char_indices.next()); assert_eq!(Some((3, 'd')), char_indices.next()); assert_eq!(Some((4, 'b')), char_indices.next()); assert_eq!(Some((5, 'y')), char_indices.next()); assert_eq!(Some((6, 'e')), char_indices.next()); assert_eq!(None, char_indices.next()); ``` Remember, `char`s might not match your intuition about characters: ``` let yes = "y̆es"; let mut char_indices = yes.char_indices(); assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆') assert_eq!(Some((1, '\u{0306}')), char_indices.next()); // note the 3 here - the last character took up two bytes assert_eq!(Some((3, 'e')), char_indices.next()); assert_eq!(Some((4, 's')), char_indices.next()); assert_eq!(None, char_indices.next()); ``` 1.0.0 · source#### pub fn bytes(&self) -> Bytes<'_An iterator over the bytes of a string slice. As a string slice consists of a sequence of bytes, we can iterate through a string slice by byte. This method returns such an iterator. ##### Examples ``` let mut bytes = "bors".bytes(); assert_eq!(Some(b'b'), bytes.next()); assert_eq!(Some(b'o'), bytes.next()); assert_eq!(Some(b'r'), bytes.next()); assert_eq!(Some(b's'), bytes.next()); assert_eq!(None, bytes.next()); ``` 1.1.0 · source#### pub fn split_whitespace(&self) -> SplitWhitespace<'_Splits a string slice by whitespace. The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of whitespace. ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`. If you only want to split on ASCII whitespace instead, use `split_ascii_whitespace`. ##### Examples Basic usage: ``` let mut iter = "A few words".split_whitespace(); assert_eq!(Some("A"), iter.next()); assert_eq!(Some("few"), iter.next()); assert_eq!(Some("words"), iter.next()); assert_eq!(None, iter.next()); ``` All kinds of whitespace are considered: ``` let mut iter = " <NAME>\ta\u{2009}little \n\t lamb".split_whitespace(); assert_eq!(Some("Mary"), iter.next()); assert_eq!(Some("had"), iter.next()); assert_eq!(Some("a"), iter.next()); assert_eq!(Some("little"), iter.next()); assert_eq!(Some("lamb"), iter.next()); assert_eq!(None, iter.next()); ``` If the string is empty or all whitespace, the iterator yields no string slices: ``` assert_eq!("".split_whitespace().next(), None); assert_eq!(" ".split_whitespace().next(), None); ``` 1.34.0 · source#### pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_Splits a string slice by ASCII whitespace. The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of ASCII whitespace. To split by Unicode `Whitespace` instead, use `split_whitespace`. ##### Examples Basic usage: ``` let mut iter = "A few words".split_ascii_whitespace(); assert_eq!(Some("A"), iter.next()); assert_eq!(Some("few"), iter.next()); assert_eq!(Some("words"), iter.next()); assert_eq!(None, iter.next()); ``` All kinds of ASCII whitespace are considered: ``` let mut iter = " <NAME>\ta little \n\t lamb".split_ascii_whitespace(); assert_eq!(Some("Mary"), iter.next()); assert_eq!(Some("had"), iter.next()); assert_eq!(Some("a"), iter.next()); assert_eq!(Some("little"), iter.next()); assert_eq!(Some("lamb"), iter.next()); assert_eq!(None, iter.next()); ``` If the string is empty or all ASCII whitespace, the iterator yields no string slices: ``` assert_eq!("".split_ascii_whitespace().next(), None); assert_eq!(" ".split_ascii_whitespace().next(), None); ``` 1.0.0 · source#### pub fn lines(&self) -> Lines<'_An iterator over the lines of a string, as string slices. Lines are split at line endings that are either newlines (`\n`) or sequences of a carriage return followed by a line feed (`\r\n`). Line terminators are not included in the lines returned by the iterator. Note that any carriage return (`\r`) not immediately followed by a line feed (`\n`) does not split a line. These carriage returns are thereby included in the produced lines. The final line ending is optional. A string that ends with a final line ending will return the same lines as an otherwise identical string without a final line ending. ##### Examples Basic usage: ``` let text = "foo\r\nbar\n\nbaz\r"; let mut lines = text.lines(); assert_eq!(Some("foo"), lines.next()); assert_eq!(Some("bar"), lines.next()); assert_eq!(Some(""), lines.next()); // Trailing carriage return is included in the last line assert_eq!(Some("baz\r"), lines.next()); assert_eq!(None, lines.next()); ``` The final line does not require any ending: ``` let text = "foo\nbar\n\r\nbaz"; let mut lines = text.lines(); assert_eq!(Some("foo"), lines.next()); assert_eq!(Some("bar"), lines.next()); assert_eq!(Some(""), lines.next()); assert_eq!(Some("baz"), lines.next()); assert_eq!(None, lines.next()); ``` 1.0.0 · source#### pub fn lines_any(&self) -> LinesAny<'_👎Deprecated since 1.4.0: use lines() instead nowAn iterator over the lines of a string. 1.8.0 · source#### pub fn encode_utf16(&self) -> EncodeUtf16<'_Returns an iterator of `u16` over the string encoded as UTF-16. ##### Examples ``` let text = "Zażółć gęślą jaźń"; let utf8_len = text.len(); let utf16_len = text.encode_utf16().count(); assert!(utf16_len <= utf8_len); ``` 1.0.0 · source#### pub fn contains<'a, P>(&'a self, pat: P) -> boolwhere P: Pattern<'a>, Returns `true` if the given pattern matches a sub-slice of this string slice. Returns `false` if it does not. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Examples ``` let bananas = "bananas"; assert!(bananas.contains("nana")); assert!(!bananas.contains("apples")); ``` 1.0.0 · source#### pub fn starts_with<'a, P>(&'a self, pat: P) -> boolwhere P: Pattern<'a>, Returns `true` if the given pattern matches a prefix of this string slice. Returns `false` if it does not. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Examples ``` let bananas = "bananas"; assert!(bananas.starts_with("bana")); assert!(!bananas.starts_with("nana")); ``` 1.0.0 · source#### pub fn ends_with<'a, P>(&'a self, pat: P) -> boolwhere P: Pattern<'a>, <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, Returns `true` if the given pattern matches a suffix of this string slice. Returns `false` if it does not. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Examples ``` let bananas = "bananas"; assert!(bananas.ends_with("anas")); assert!(!bananas.ends_with("nana")); ``` 1.0.0 · source#### pub fn find<'a, P>(&'a self, pat: P) -> Option<usize>where P: Pattern<'a>, Returns the byte index of the first character of this string slice that matches the pattern. Returns `None` if the pattern doesn’t match. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Examples Simple patterns: ``` let s = "Löwe 老虎 <NAME>"; assert_eq!(s.find('L'), Some(0)); assert_eq!(s.find('é'), Some(14)); assert_eq!(s.find("pard"), Some(17)); ``` More complex patterns using point-free style and closures: ``` let s = "Löwe 老虎 Léopard"; assert_eq!(s.find(char::is_whitespace), Some(5)); assert_eq!(s.find(char::is_lowercase), Some(1)); assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1)); assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4)); ``` Not finding the pattern: ``` let s = "Löwe 老虎 Léopard"; let x: &[_] = &['1', '2']; assert_eq!(s.find(x), None); ``` 1.0.0 · source#### pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>where P: Pattern<'a>, <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, Returns the byte index for the first character of the last match of the pattern in this string slice. Returns `None` if the pattern doesn’t match. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Examples Simple patterns: ``` let s = "Löwe 老虎 <NAME>"; assert_eq!(s.rfind('L'), Some(13)); assert_eq!(s.rfind('é'), Some(14)); assert_eq!(s.rfind("pard"), Some(24)); ``` More complex patterns with closures: ``` let s = "Löwe 老虎 Léopard"; assert_eq!(s.rfind(char::is_whitespace), Some(12)); assert_eq!(s.rfind(char::is_lowercase), Some(20)); ``` Not finding the pattern: ``` let s = "Löwe 老虎 Léopard"; let x: &[_] = &['1', '2']; assert_eq!(s.rfind(x), None); ``` 1.0.0 · source#### pub fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> where P: Pattern<'a>, An iterator over substrings of this string slice, separated by characters matched by a pattern. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Iterator behavior The returned iterator will be a `DoubleEndedIterator` if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., `char`, but not for `&str`. If the pattern allows a reverse search but its results might differ from a forward search, the `rsplit` method can be used. ##### Examples Simple patterns: ``` let v: Vec<&str> = "Mary had a little lamb".split(' ').collect(); assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]); let v: Vec<&str> = "".split('X').collect(); assert_eq!(v, [""]); let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect(); assert_eq!(v, ["lion", "", "tiger", "leopard"]); let v: Vec<&str> = "lion::tiger::leopard".split("::").collect(); assert_eq!(v, ["lion", "tiger", "leopard"]); let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect(); assert_eq!(v, ["abc", "def", "ghi"]); let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect(); assert_eq!(v, ["lion", "tiger", "leopard"]); ``` If the pattern is a slice of chars, split on each occurrence of any of the characters: ``` let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect(); assert_eq!(v, ["2020", "11", "03", "23", "59"]); ``` A more complex pattern, using a closure: ``` let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect(); assert_eq!(v, ["abc", "def", "ghi"]); ``` If a string contains multiple contiguous separators, you will end up with empty strings in the output: ``` let x = "||||a||b|c".to_string(); let d: Vec<_> = x.split('|').collect(); assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]); ``` Contiguous separators are separated by the empty string. ``` let x = "(///)".to_string(); let d: Vec<_> = x.split('/').collect(); assert_eq!(d, &["(", "", "", ")"]); ``` Separators at the start or end of a string are neighbored by empty strings. ``` let d: Vec<_> = "010".split("0").collect(); assert_eq!(d, &["", "1", ""]); ``` When the empty string is used as a separator, it separates every character in the string, along with the beginning and end of the string. ``` let f: Vec<_> = "rust".split("").collect(); assert_eq!(f, &["", "r", "u", "s", "t", ""]); ``` Contiguous separators can lead to possibly surprising behavior when whitespace is used as the separator. This code is correct: ``` let x = " a b c".to_string(); let d: Vec<_> = x.split(' ').collect(); assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]); ``` It does *not* give you: ``` assert_eq!(d, &["a", "b", "c"]); ``` Use `split_whitespace` for this behavior. 1.51.0 · source#### pub fn split_inclusive<'a, P>(&'a self, pat: P) -> SplitInclusive<'a, P> where P: Pattern<'a>, An iterator over substrings of this string slice, separated by characters matched by a pattern. Differs from the iterator produced by `split` in that `split_inclusive` leaves the matched part as the terminator of the substring. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Examples ``` let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb." .split_inclusive('\n').collect(); assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]); ``` If the last element of the string is matched, that element will be considered the terminator of the preceding substring. That substring will be the last item returned by the iterator. ``` let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n" .split_inclusive('\n').collect(); assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]); ``` 1.0.0 · source#### pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P> where P: Pattern<'a>, <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, An iterator over substrings of the given string slice, separated by characters matched by a pattern and yielded in reverse order. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Iterator behavior The returned iterator requires that the pattern supports a reverse search, and it will be a `DoubleEndedIterator` if a forward/reverse search yields the same elements. For iterating from the front, the `split` method can be used. ##### Examples Simple patterns: ``` let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect(); assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]); let v: Vec<&str> = "".rsplit('X').collect(); assert_eq!(v, [""]); let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect(); assert_eq!(v, ["leopard", "tiger", "", "lion"]); let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect(); assert_eq!(v, ["leopard", "tiger", "lion"]); ``` A more complex pattern, using a closure: ``` let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect(); assert_eq!(v, ["ghi", "def", "abc"]); ``` 1.0.0 · source#### pub fn split_terminator<'a, P>(&'a self, pat: P) -> SplitTerminator<'a, P> where P: Pattern<'a>, An iterator over substrings of the given string slice, separated by characters matched by a pattern. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. Equivalent to `split`, except that the trailing substring is skipped if empty. This method can be used for string data that is *terminated*, rather than *separated* by a pattern. ##### Iterator behavior The returned iterator will be a `DoubleEndedIterator` if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., `char`, but not for `&str`. If the pattern allows a reverse search but its results might differ from a forward search, the `rsplit_terminator` method can be used. ##### Examples ``` let v: Vec<&str> = "A.B.".split_terminator('.').collect(); assert_eq!(v, ["A", "B"]); let v: Vec<&str> = "A..B..".split_terminator(".").collect(); assert_eq!(v, ["A", "", "B", ""]); let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect(); assert_eq!(v, ["A", "B", "C", "D"]); ``` 1.0.0 · source#### pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P> where P: Pattern<'a>, <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, An iterator over substrings of `self`, separated by characters matched by a pattern and yielded in reverse order. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. Equivalent to `split`, except that the trailing substring is skipped if empty. This method can be used for string data that is *terminated*, rather than *separated* by a pattern. ##### Iterator behavior The returned iterator requires that the pattern supports a reverse search, and it will be double ended if a forward/reverse search yields the same elements. For iterating from the front, the `split_terminator` method can be used. ##### Examples ``` let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect(); assert_eq!(v, ["B", "A"]); let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect(); assert_eq!(v, ["", "B", "", "A"]); let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect(); assert_eq!(v, ["D", "C", "B", "A"]); ``` 1.0.0 · source#### pub fn splitn<'a, P>(&'a self, n: usize, pat: P) -> SplitN<'a, P> where P: Pattern<'a>, An iterator over substrings of the given string slice, separated by a pattern, restricted to returning at most `n` items. If `n` substrings are returned, the last substring (the `n`th substring) will contain the remainder of the string. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Iterator behavior The returned iterator will not be double ended, because it is not efficient to support. If the pattern allows a reverse search, the `rsplitn` method can be used. ##### Examples Simple patterns: ``` let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect(); assert_eq!(v, ["Mary", "had", "a little lambda"]); let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect(); assert_eq!(v, ["lion", "", "tigerXleopard"]); let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect(); assert_eq!(v, ["abcXdef"]); let v: Vec<&str> = "".splitn(1, 'X').collect(); assert_eq!(v, [""]); ``` A more complex pattern, using a closure: ``` let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect(); assert_eq!(v, ["abc", "defXghi"]); ``` 1.0.0 · source#### pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P> where P: Pattern<'a>, <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, An iterator over substrings of this string slice, separated by a pattern, starting from the end of the string, restricted to returning at most `n` items. If `n` substrings are returned, the last substring (the `n`th substring) will contain the remainder of the string. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Iterator behavior The returned iterator will not be double ended, because it is not efficient to support. For splitting from the front, the `splitn` method can be used. ##### Examples Simple patterns: ``` let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect(); assert_eq!(v, ["lamb", "little", "Mary had a"]); let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect(); assert_eq!(v, ["leopard", "tiger", "lionX"]); let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect(); assert_eq!(v, ["leopard", "lion::tiger"]); ``` A more complex pattern, using a closure: ``` let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect(); assert_eq!(v, ["ghi", "abc1def"]); ``` 1.52.0 · source#### pub fn split_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where P: Pattern<'a>, Splits the string on the first occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter. ##### Examples ``` assert_eq!("cfg".split_once('='), None); assert_eq!("cfg=".split_once('='), Some(("cfg", ""))); assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo"))); assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar"))); ``` 1.52.0 · source#### pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where P: Pattern<'a>, <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, Splits the string on the last occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter. ##### Examples ``` assert_eq!("cfg".rsplit_once('='), None); assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo"))); assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar"))); ``` 1.2.0 · source#### pub fn matches<'a, P>(&'a self, pat: P) -> Matches<'a, P> where P: Pattern<'a>, An iterator over the disjoint matches of a pattern within the given string slice. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Iterator behavior The returned iterator will be a `DoubleEndedIterator` if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., `char`, but not for `&str`. If the pattern allows a reverse search but its results might differ from a forward search, the `rmatches` method can be used. ##### Examples ``` let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect(); assert_eq!(v, ["abc", "abc", "abc"]); let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect(); assert_eq!(v, ["1", "2", "3"]); ``` 1.2.0 · source#### pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P> where P: Pattern<'a>, <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, An iterator over the disjoint matches of a pattern within this string slice, yielded in reverse order. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Iterator behavior The returned iterator requires that the pattern supports a reverse search, and it will be a `DoubleEndedIterator` if a forward/reverse search yields the same elements. For iterating from the front, the `matches` method can be used. ##### Examples ``` let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect(); assert_eq!(v, ["abc", "abc", "abc"]); let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect(); assert_eq!(v, ["3", "2", "1"]); ``` 1.5.0 · source#### pub fn match_indices<'a, P>(&'a self, pat: P) -> MatchIndices<'a, P> where P: Pattern<'a>, An iterator over the disjoint matches of a pattern within this string slice as well as the index that the match starts at. For matches of `pat` within `self` that overlap, only the indices corresponding to the first match are returned. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Iterator behavior The returned iterator will be a `DoubleEndedIterator` if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., `char`, but not for `&str`. If the pattern allows a reverse search but its results might differ from a forward search, the `rmatch_indices` method can be used. ##### Examples ``` let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` 1.5.0 · source#### pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P> where P: Pattern<'a>, <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, An iterator over the disjoint matches of a pattern within `self`, yielded in reverse order along with the index of the match. For matches of `pat` within `self` that overlap, only the indices corresponding to the last match are returned. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Iterator behavior The returned iterator requires that the pattern supports a reverse search, and it will be a `DoubleEndedIterator` if a forward/reverse search yields the same elements. For iterating from the front, the `match_indices` method can be used. ##### Examples ``` let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect(); assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]); let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect(); assert_eq!(v, [(4, "abc"), (1, "abc")]); let v: Vec<_> = "ababa".rmatch_indices("aba").collect(); assert_eq!(v, [(2, "aba")]); // only the last `aba` ``` 1.0.0 · source#### pub fn trim(&self) -> &str Returns a string slice with leading and trailing whitespace removed. ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`, which includes newlines. ##### Examples ``` let s = "\n Hello\tworld\t\n"; assert_eq!("Hello\tworld", s.trim()); ``` 1.30.0 · source#### pub fn trim_start(&self) -> &str Returns a string slice with leading whitespace removed. ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`, which includes newlines. ##### Text directionality A string is a sequence of bytes. `start` in this context means the first position of that byte string; for a left-to-right language like English or Russian, this will be left side, and for right-to-left languages like Arabic or Hebrew, this will be the right side. ##### Examples Basic usage: ``` let s = "\n Hello\tworld\t\n"; assert_eq!("Hello\tworld\t\n", s.trim_start()); ``` Directionality: ``` let s = " English "; assert!(Some('E') == s.trim_start().chars().next()); let s = " עברית "; assert!(Some('ע') == s.trim_start().chars().next()); ``` 1.30.0 · source#### pub fn trim_end(&self) -> &str Returns a string slice with trailing whitespace removed. ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`, which includes newlines. ##### Text directionality A string is a sequence of bytes. `end` in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side. ##### Examples Basic usage: ``` let s = "\n Hello\tworld\t\n"; assert_eq!("\n Hello\tworld", s.trim_end()); ``` Directionality: ``` let s = " English "; assert!(Some('h') == s.trim_end().chars().rev().next()); let s = " עברית "; assert!(Some('ת') == s.trim_end().chars().rev().next()); ``` 1.0.0 · source#### pub fn trim_left(&self) -> &str 👎Deprecated since 1.33.0: superseded by `trim_start`Returns a string slice with leading whitespace removed. ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`. ##### Text directionality A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *right* side, not the left. ##### Examples Basic usage: ``` let s = " Hello\tworld\t"; assert_eq!("Hello\tworld\t", s.trim_left()); ``` Directionality: ``` let s = " English"; assert!(Some('E') == s.trim_left().chars().next()); let s = " עברית"; assert!(Some('ע') == s.trim_left().chars().next()); ``` 1.0.0 · source#### pub fn trim_right(&self) -> &str 👎Deprecated since 1.33.0: superseded by `trim_end`Returns a string slice with trailing whitespace removed. ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`. ##### Text directionality A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *left* side, not the right. ##### Examples Basic usage: ``` let s = " Hello\tworld\t"; assert_eq!(" Hello\tworld", s.trim_right()); ``` Directionality: ``` let s = "English "; assert!(Some('h') == s.trim_right().chars().rev().next()); let s = "עברית "; assert!(Some('ת') == s.trim_right().chars().rev().next()); ``` 1.0.0 · source#### pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a strwhere P: Pattern<'a>, <P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>, Returns a string slice with all prefixes and suffixes that match a pattern repeatedly removed. The pattern can be a `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Examples Simple patterns: ``` assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar"); assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_matches(x), "foo1bar"); ``` A more complex pattern, using a closure: ``` assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar"); ``` 1.30.0 · source#### pub fn trim_start_matches<'a, P>(&'a self, pat: P) -> &'a strwhere P: Pattern<'a>, Returns a string slice with all prefixes that match a pattern repeatedly removed. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Text directionality A string is a sequence of bytes. `start` in this context means the first position of that byte string; for a left-to-right language like English or Russian, this will be left side, and for right-to-left languages like Arabic or Hebrew, this will be the right side. ##### Examples ``` assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); ``` 1.45.0 · source#### pub fn strip_prefix<'a, P>(&'a self, prefix: P) -> Option<&'a str>where P: Pattern<'a>, Returns a string slice with the prefix removed. If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once. If the string does not start with `prefix`, returns `None`. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Examples ``` assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar")); assert_eq!("foo:bar".strip_prefix("bar"), None); assert_eq!("foofoo".strip_prefix("foo"), Some("foo")); ``` 1.45.0 · source#### pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>where P: Pattern<'a>, <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, Returns a string slice with the suffix removed. If the string ends with the pattern `suffix`, returns the substring before the suffix, wrapped in `Some`. Unlike `trim_end_matches`, this method removes the suffix exactly once. If the string does not end with `suffix`, returns `None`. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Examples ``` assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar")); assert_eq!("bar:foo".strip_suffix("bar"), None); assert_eq!("foofoo".strip_suffix("foo"), Some("foo")); ``` 1.30.0 · source#### pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a strwhere P: Pattern<'a>, <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, Returns a string slice with all suffixes that match a pattern repeatedly removed. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Text directionality A string is a sequence of bytes. `end` in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side. ##### Examples Simple patterns: ``` assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar"); assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar"); ``` A more complex pattern, using a closure: ``` assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo"); ``` 1.0.0 · source#### pub fn trim_left_matches<'a, P>(&'a self, pat: P) -> &'a strwhere P: Pattern<'a>, 👎Deprecated since 1.33.0: superseded by `trim_start_matches`Returns a string slice with all prefixes that match a pattern repeatedly removed. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Text directionality A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *right* side, not the left. ##### Examples ``` assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12"); ``` 1.0.0 · source#### pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a strwhere P: Pattern<'a>, <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, 👎Deprecated since 1.33.0: superseded by `trim_end_matches`Returns a string slice with all suffixes that match a pattern repeatedly removed. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ##### Text directionality A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *left* side, not the right. ##### Examples Simple patterns: ``` assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar"); assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar"); ``` A more complex pattern, using a closure: ``` assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo"); ``` 1.0.0 · source#### pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>where F: FromStr, Parses this string slice into another type. Because `parse` is so general, it can cause problems with type inference. As such, `parse` is one of the few times you’ll see the syntax affectionately known as the ‘turbofish’: `::<>`. This helps the inference algorithm understand specifically which type you’re trying to parse into. `parse` can parse into any type that implements the `FromStr` trait. ##### Errors Will return `Err` if it’s not possible to parse this string slice into the desired type. ##### Examples Basic usage ``` let four: u32 = "4".parse().unwrap(); assert_eq!(4, four); ``` Using the ‘turbofish’ instead of annotating `four`: ``` let four = "4".parse::<u32>(); assert_eq!(Ok(4), four); ``` Failing to parse: ``` let nope = "j".parse::<u32>(); assert!(nope.is_err()); ``` 1.23.0 · source#### pub fn is_ascii(&self) -> bool Checks if all characters in this string are within the ASCII range. ##### Examples ``` let ascii = "hello!\n"; let non_ascii = "Grüße, Jürgen ❤"; assert!(ascii.is_ascii()); assert!(!non_ascii.is_ascii()); ``` #### pub fn as_ascii(&self) -> Option<&[AsciiChar]🔬This is a nightly-only experimental API. (`ascii_char`)If this string slice `is_ascii`, returns it as a slice of ASCII characters, otherwise returns `None`. 1.23.0 · source#### pub fn eq_ignore_ascii_case(&self, other: &str) -> bool Checks that two strings are an ASCII case-insensitive match. Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`, but without allocating and copying temporaries. ##### Examples ``` assert!("Ferris".eq_ignore_ascii_case("FERRIS")); assert!("Ferrös".eq_ignore_ascii_case("FERRöS")); assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS")); ``` 1.34.0 · source#### pub fn escape_debug(&self) -> EscapeDebug<'_Return an iterator that escapes each char in `self` with `char::escape_debug`. Note: only extended grapheme codepoints that begin the string will be escaped. ##### Examples As an iterator: ``` for c in "❤\n!".escape_debug() { print!("{c}"); } println!(); ``` Using `println!` directly: ``` println!("{}", "❤\n!".escape_debug()); ``` Both are equivalent to: ``` println!("❤\\n!"); ``` Using `to_string`: ``` assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!"); ``` 1.34.0 · source#### pub fn escape_default(&self) -> EscapeDefault<'_Return an iterator that escapes each char in `self` with `char::escape_default`. ##### Examples As an iterator: ``` for c in "❤\n!".escape_default() { print!("{c}"); } println!(); ``` Using `println!` directly: ``` println!("{}", "❤\n!".escape_default()); ``` Both are equivalent to: ``` println!("\\u{{2764}}\\n!"); ``` Using `to_string`: ``` assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!"); ``` 1.34.0 · source#### pub fn escape_unicode(&self) -> EscapeUnicode<'_Return an iterator that escapes each char in `self` with `char::escape_unicode`. ##### Examples As an iterator: ``` for c in "❤\n!".escape_unicode() { print!("{c}"); } println!(); ``` Using `println!` directly: ``` println!("{}", "❤\n!".escape_unicode()); ``` Both are equivalent to: ``` println!("\\u{{2764}}\\u{{a}}\\u{{21}}"); ``` Using `to_string`: ``` assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}"); ``` 1.0.0 · source#### pub fn replace<'a, P>(&'a self, from: P, to: &str) -> Stringwhere P: Pattern<'a>, Replaces all matches of a pattern with another string. `replace` creates a new `String`, and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice. ##### Examples Basic usage: ``` let s = "this is old"; assert_eq!("this is new", s.replace("old", "new")); assert_eq!("than an old", s.replace("is", "an")); ``` When the pattern doesn’t match, it returns this string slice as `String`: ``` let s = "this is old"; assert_eq!(s, s.replace("cookie monster", "little lamb")); ``` 1.16.0 · source#### pub fn replacen<'a, P>(&'a self, pat: P, to: &str, count: usize) -> Stringwhere P: Pattern<'a>, Replaces first N matches of a pattern with another string. `replacen` creates a new `String`, and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice at most `count` times. ##### Examples Basic usage: ``` let s = "foo foo 123 foo"; assert_eq!("new new 123 foo", s.replacen("foo", "new", 2)); assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3)); assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1)); ``` When the pattern doesn’t match, it returns this string slice as `String`: ``` let s = "this is old"; assert_eq!(s, s.replacen("cookie monster", "little lamb", 10)); ``` 1.2.0 · source#### pub fn to_lowercase(&self) -> String Returns the lowercase equivalent of this string slice, as a new `String`. ‘Lowercase’ is defined according to the terms of the Unicode Derived Core Property `Lowercase`. Since some characters can expand into multiple characters when changing the case, this function returns a `String` instead of modifying the parameter in-place. ##### Examples Basic usage: ``` let s = "HELLO"; assert_eq!("hello", s.to_lowercase()); ``` A tricky example, with sigma: ``` let sigma = "Σ"; assert_eq!("σ", sigma.to_lowercase()); // but at the end of a word, it's ς, not σ: let odysseus = "ὈΔΥΣΣΕΎΣ"; assert_eq!("ὀδυσσεύς", odysseus.to_lowercase()); ``` Languages without case are not changed: ``` let new_year = "农历新年"; assert_eq!(new_year, new_year.to_lowercase()); ``` 1.2.0 · source#### pub fn to_uppercase(&self) -> String Returns the uppercase equivalent of this string slice, as a new `String`. ‘Uppercase’ is defined according to the terms of the Unicode Derived Core Property `Uppercase`. Since some characters can expand into multiple characters when changing the case, this function returns a `String` instead of modifying the parameter in-place. ##### Examples Basic usage: ``` let s = "hello"; assert_eq!("HELLO", s.to_uppercase()); ``` Scripts without case are not changed: ``` let new_year = "农历新年"; assert_eq!(new_year, new_year.to_uppercase()); ``` One character can become multiple: ``` let s = "tschüß"; assert_eq!("TSCHÜSS", s.to_uppercase()); ``` 1.16.0 · source#### pub fn repeat(&self, n: usize) -> String Creates a new `String` by repeating a string `n` times. ##### Panics This function will panic if the capacity would overflow. ##### Examples Basic usage: ``` assert_eq!("abc".repeat(4), String::from("abcabcabcabc")); ``` A panic upon overflow: ``` // this will panic at runtime let huge = "0123456789abcdef".repeat(usize::MAX); ``` 1.23.0 · source#### pub fn to_ascii_uppercase(&self) -> String Returns a copy of this string where each character is mapped to its ASCII upper case equivalent. ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged. To uppercase the value in-place, use `make_ascii_uppercase`. To uppercase ASCII characters in addition to non-ASCII characters, use `to_uppercase`. ##### Examples ``` let s = "Grüße, Jürgen ❤"; assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase()); ``` 1.23.0 · source#### pub fn to_ascii_lowercase(&self) -> String Returns a copy of this string where each character is mapped to its ASCII lower case equivalent. ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged. To lowercase the value in-place, use `make_ascii_lowercase`. To lowercase ASCII characters in addition to non-ASCII characters, use `to_lowercase`. ##### Examples ``` let s = "Grüße, Jürgen ❤"; assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase()); ``` Trait Implementations --- ### impl Clone for String #### fn clone(&self) -> Self Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. ``` use ::safer_ffi::prelude::*; let s: repr_c::String = "".into(); assert_eq!(format!("{s:?}"), "\"\""); ``` #### fn fmt(&self, fmt: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### type Target = str The resulting type after dereferencing.#### fn deref(&self) -> &Self::Target Dereferences the value.### impl Display for String ``` use ::safer_ffi::prelude::*; let s: repr_c::String = "".into(); assert_eq!(format!("{s}"), ""); ``` #### fn fmt(&self, fmt: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn from(s: &str) -> String Converts to this type from the input type.### impl From<String> for String Convert a `safer_ffi::String` to a `std::string::String`. #### fn from(value: String) -> String Converts to this type from the input type.### impl From<String> for String Convert a `std::string::String` to a `safer_ffi::String`. #### fn from(s: String) -> String Converts to this type from the input type.### impl ReprC for Stringwhere Vec<u8>: ReprC, #### type CLayout = <Vec<u8> as ReprC>::CLayout The `CType` having the same layout as `Self`.#### fn is_valid(it: &Self::CLayout) -> bool Sanity checks that can be performed on an instance of the `CType` layout. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for String ### impl Send for String ### impl Sync for String ### impl Unpin for String ### impl UnwindSafe for String Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn compat(self) -> Compat<TApplies the `Compat` adapter by value. #### type CBoxWrapped = Box_<TAvailable on **crate feature `alloc`** only.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ManuallyDropMut for T #### type Ret = ManuallyDrop<T#### fn manually_drop_mut<'__>(&'__ mut self) -> &'__ mut ManuallyDrop<T### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> UpcastAny for Twhere T: 'static, #### fn upcast_any(&self) -> &(dyn Any + 'static) Available on **crate feature `headers`** only.{"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","Bytes<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.Bytes.html\" title=\"struct core::str::iter::Bytes\">Bytes</a>&lt;'_&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.Bytes.html\" title=\"struct core::str::iter::Bytes\">Bytes</a>&lt;'_&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>;</span>","CharIndices<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.CharIndices.html\" title=\"struct core::str::iter::CharIndices\">CharIndices</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.CharIndices.html\" title=\"struct core::str::iter::CharIndices\">CharIndices</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>, <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.char.html\">char</a>);</span>","Chars<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.Chars.html\" title=\"struct core::str::iter::Chars\">Chars</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.Chars.html\" title=\"struct core::str::iter::Chars\">Chars</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.char.html\">char</a>;</span>","Compat<&T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","Compat<&mut T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","Compat<T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","EncodeUtf16<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.EncodeUtf16.html\" title=\"struct core::str::iter::EncodeUtf16\">EncodeUtf16</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.EncodeUtf16.html\" title=\"struct core::str::iter::EncodeUtf16\">EncodeUtf16</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u16.html\">u16</a>;</span>","EscapeDebug<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.EscapeDebug.html\" title=\"struct core::str::iter::EscapeDebug\">EscapeDebug</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.EscapeDebug.html\" title=\"struct core::str::iter::EscapeDebug\">EscapeDebug</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.char.html\">char</a>;</span>","EscapeDefault<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.EscapeDefault.html\" title=\"struct core::str::iter::EscapeDefault\">EscapeDefault</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.EscapeDefault.html\" title=\"struct core::str::iter::EscapeDefault\">EscapeDefault</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.char.html\">char</a>;</span>","EscapeUnicode<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.EscapeUnicode.html\" title=\"struct core::str::iter::EscapeUnicode\">EscapeUnicode</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.EscapeUnicode.html\" title=\"struct core::str::iter::EscapeUnicode\">EscapeUnicode</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.char.html\">char</a>;</span>","Lines<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.Lines.html\" title=\"struct core::str::iter::Lines\">Lines</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.Lines.html\" title=\"struct core::str::iter::Lines\">Lines</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","LinesAny<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.LinesAny.html\" title=\"struct core::str::iter::LinesAny\">LinesAny</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.LinesAny.html\" title=\"struct core::str::iter::LinesAny\">LinesAny</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","MatchIndices<'a, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.MatchIndices.html\" title=\"struct core::str::iter::MatchIndices\">MatchIndices</a>&lt;'a, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.MatchIndices.html\" title=\"struct core::str::iter::MatchIndices\">MatchIndices</a>&lt;'a, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>, &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>);</span>","Matches<'a, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.Matches.html\" title=\"struct core::str::iter::Matches\">Matches</a>&lt;'a, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.Matches.html\" title=\"struct core::str::iter::Matches\">Matches</a>&lt;'a, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","RMatchIndices<'a, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.RMatchIndices.html\" title=\"struct core::str::iter::RMatchIndices\">RMatchIndices</a>&lt;'a, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.RMatchIndices.html\" title=\"struct core::str::iter::RMatchIndices\">RMatchIndices</a>&lt;'a, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;,\n &lt;P as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html#associatedtype.Searcher\" title=\"type core::str::pattern::Pattern::Searcher\">Searcher</a>: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.ReverseSearcher.html\" title=\"trait core::str::pattern::ReverseSearcher\">ReverseSearcher</a>&lt;'a&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>, &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>);</span>","RMatches<'a, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.RMatches.html\" title=\"struct core::str::iter::RMatches\">RMatches</a>&lt;'a, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.RMatches.html\" title=\"struct core::str::iter::RMatches\">RMatches</a>&lt;'a, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;,\n &lt;P as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html#associatedtype.Searcher\" title=\"type core::str::pattern::Pattern::Searcher\">Searcher</a>: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.ReverseSearcher.html\" title=\"trait core::str::pattern::ReverseSearcher\">ReverseSearcher</a>&lt;'a&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","RSplit<'a, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.RSplit.html\" title=\"struct core::str::iter::RSplit\">RSplit</a>&lt;'a, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.RSplit.html\" title=\"struct core::str::iter::RSplit\">RSplit</a>&lt;'a, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;,\n &lt;P as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html#associatedtype.Searcher\" title=\"type core::str::pattern::Pattern::Searcher\">Searcher</a>: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.ReverseSearcher.html\" title=\"trait core::str::pattern::ReverseSearcher\">ReverseSearcher</a>&lt;'a&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","RSplitN<'a, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.RSplitN.html\" title=\"struct core::str::iter::RSplitN\">RSplitN</a>&lt;'a, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.RSplitN.html\" title=\"struct core::str::iter::RSplitN\">RSplitN</a>&lt;'a, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;,\n &lt;P as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html#associatedtype.Searcher\" title=\"type core::str::pattern::Pattern::Searcher\">Searcher</a>: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.ReverseSearcher.html\" title=\"trait core::str::pattern::ReverseSearcher\">ReverseSearcher</a>&lt;'a&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","RSplitTerminator<'a, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.RSplitTerminator.html\" title=\"struct core::str::iter::RSplitTerminator\">RSplitTerminator</a>&lt;'a, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.RSplitTerminator.html\" title=\"struct core::str::iter::RSplitTerminator\">RSplitTerminator</a>&lt;'a, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;,\n &lt;P as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html#associatedtype.Searcher\" title=\"type core::str::pattern::Pattern::Searcher\">Searcher</a>: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.ReverseSearcher.html\" title=\"trait core::str::pattern::ReverseSearcher\">ReverseSearcher</a>&lt;'a&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","Split<'a, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.Split.html\" title=\"struct core::str::iter::Split\">Split</a>&lt;'a, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.Split.html\" title=\"struct core::str::iter::Split\">Split</a>&lt;'a, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","SplitAsciiWhitespace<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.SplitAsciiWhitespace.html\" title=\"struct core::str::iter::SplitAsciiWhitespace\">SplitAsciiWhitespace</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.SplitAsciiWhitespace.html\" title=\"struct core::str::iter::SplitAsciiWhitespace\">SplitAsciiWhitespace</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","SplitInclusive<'a, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.SplitInclusive.html\" title=\"struct core::str::iter::SplitInclusive\">SplitInclusive</a>&lt;'a, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.SplitInclusive.html\" title=\"struct core::str::iter::SplitInclusive\">SplitInclusive</a>&lt;'a, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","SplitN<'a, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.SplitN.html\" title=\"struct core::str::iter::SplitN\">SplitN</a>&lt;'a, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.SplitN.html\" title=\"struct core::str::iter::SplitN\">SplitN</a>&lt;'a, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","SplitTerminator<'a, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.SplitTerminator.html\" title=\"struct core::str::iter::SplitTerminator\">SplitTerminator</a>&lt;'a, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.SplitTerminator.html\" title=\"struct core::str::iter::SplitTerminator\">SplitTerminator</a>&lt;'a, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/str/pattern/trait.Pattern.html\" title=\"trait core::str::pattern::Pattern\">Pattern</a>&lt;'a&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>","SplitWhitespace<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.SplitWhitespace.html\" title=\"struct core::str::iter::SplitWhitespace\">SplitWhitespace</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/str/iter/struct.SplitWhitespace.html\" title=\"struct core::str::iter::SplitWhitespace\">SplitWhitespace</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.str.html\">str</a>;</span>"} Struct safer_ffi::Vec === ``` pub struct Vec<T> { /* private fields */ } ``` Available on **crate feature `alloc`** only.Same as `Vec<T>`, but with guaranteed `#[repr(C)]` layout C Layout --- * `Vec_Layout` Implementations --- ### impl<T> Vec<T#### pub fn as_ref(&self) -> slice_ref<'_, T#### pub fn as_mut(&mut self) -> slice_mut<'_, T### impl<T> Vec<T#### pub const EMPTY: Self = _ #### pub fn with_rust_mut<R>( self: &mut Vec<T>, f: impl FnOnce(&mut Vec<T>) -> R ) -> R Methods from Deref<Target = [T]> --- 1.0.0 · source#### pub fn len(&self) -> usize Returns the number of elements in the slice. ##### Examples ``` let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` 1.0.0 · source#### pub fn is_empty(&self) -> bool Returns `true` if the slice has a length of 0. ##### Examples ``` let a = [1, 2, 3]; assert!(!a.is_empty()); ``` 1.0.0 · source#### pub fn first(&self) -> Option<&TReturns the first element of the slice, or `None` if it is empty. ##### Examples ``` let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` 1.0.0 · source#### pub fn first_mut(&mut self) -> Option<&mut TReturns a mutable pointer to the first element of the slice, or `None` if it is empty. ##### Examples ``` let x = &mut [0, 1, 2]; if let Some(first) = x.first_mut() { *first = 5; } assert_eq!(x, &[5, 1, 2]); ``` 1.5.0 · source#### pub fn split_first(&self) -> Option<(&T, &[T])Returns the first and all the rest of the elements of the slice, or `None` if it is empty. ##### Examples ``` let x = &[0, 1, 2]; if let Some((first, elements)) = x.split_first() { assert_eq!(first, &0); assert_eq!(elements, &[1, 2]); } ``` 1.5.0 · source#### pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])Returns the first and all the rest of the elements of the slice, or `None` if it is empty. ##### Examples ``` let x = &mut [0, 1, 2]; if let Some((first, elements)) = x.split_first_mut() { *first = 3; elements[0] = 4; elements[1] = 5; } assert_eq!(x, &[3, 4, 5]); ``` 1.5.0 · source#### pub fn split_last(&self) -> Option<(&T, &[T])Returns the last and all the rest of the elements of the slice, or `None` if it is empty. ##### Examples ``` let x = &[0, 1, 2]; if let Some((last, elements)) = x.split_last() { assert_eq!(last, &2); assert_eq!(elements, &[0, 1]); } ``` 1.5.0 · source#### pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])Returns the last and all the rest of the elements of the slice, or `None` if it is empty. ##### Examples ``` let x = &mut [0, 1, 2]; if let Some((last, elements)) = x.split_last_mut() { *last = 3; elements[0] = 4; elements[1] = 5; } assert_eq!(x, &[4, 5, 3]); ``` 1.0.0 · source#### pub fn last(&self) -> Option<&TReturns the last element of the slice, or `None` if it is empty. ##### Examples ``` let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` 1.0.0 · source#### pub fn last_mut(&mut self) -> Option<&mut TReturns a mutable pointer to the last item in the slice. ##### Examples ``` let x = &mut [0, 1, 2]; if let Some(last) = x.last_mut() { *last = 10; } assert_eq!(x, &[0, 1, 10]); ``` #### pub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]🔬This is a nightly-only experimental API. (`slice_first_last_chunk`)Returns the first `N` elements of the slice, or `None` if it has fewer than `N` elements. ##### Examples ``` #![feature(slice_first_last_chunk)] let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` #### pub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]🔬This is a nightly-only experimental API. (`slice_first_last_chunk`)Returns a mutable reference to the first `N` elements of the slice, or `None` if it has fewer than `N` elements. ##### Examples ``` #![feature(slice_first_last_chunk)] let x = &mut [0, 1, 2]; if let Some(first) = x.first_chunk_mut::<2>() { first[0] = 5; first[1] = 4; } assert_eq!(x, &[5, 4, 2]); ``` #### pub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])🔬This is a nightly-only experimental API. (`slice_first_last_chunk`)Returns the first `N` elements of the slice and the remainder, or `None` if it has fewer than `N` elements. ##### Examples ``` #![feature(slice_first_last_chunk)] let x = &[0, 1, 2]; if let Some((first, elements)) = x.split_first_chunk::<2>() { assert_eq!(first, &[0, 1]); assert_eq!(elements, &[2]); } ``` #### pub fn split_first_chunk_mut<const N: usize>( &mut self ) -> Option<(&mut [T; N], &mut [T])🔬This is a nightly-only experimental API. (`slice_first_last_chunk`)Returns a mutable reference to the first `N` elements of the slice and the remainder, or `None` if it has fewer than `N` elements. ##### Examples ``` #![feature(slice_first_last_chunk)] let x = &mut [0, 1, 2]; if let Some((first, elements)) = x.split_first_chunk_mut::<2>() { first[0] = 3; first[1] = 4; elements[0] = 5; } assert_eq!(x, &[3, 4, 5]); ``` #### pub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])🔬This is a nightly-only experimental API. (`slice_first_last_chunk`)Returns the last `N` elements of the slice and the remainder, or `None` if it has fewer than `N` elements. ##### Examples ``` #![feature(slice_first_last_chunk)] let x = &[0, 1, 2]; if let Some((last, elements)) = x.split_last_chunk::<2>() { assert_eq!(last, &[1, 2]); assert_eq!(elements, &[0]); } ``` #### pub fn split_last_chunk_mut<const N: usize>( &mut self ) -> Option<(&mut [T; N], &mut [T])🔬This is a nightly-only experimental API. (`slice_first_last_chunk`)Returns the last and all the rest of the elements of the slice, or `None` if it is empty. ##### Examples ``` #![feature(slice_first_last_chunk)] let x = &mut [0, 1, 2]; if let Some((last, elements)) = x.split_last_chunk_mut::<2>() { last[0] = 3; last[1] = 4; elements[0] = 5; } assert_eq!(x, &[5, 3, 4]); ``` #### pub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]🔬This is a nightly-only experimental API. (`slice_first_last_chunk`)Returns the last element of the slice, or `None` if it is empty. ##### Examples ``` #![feature(slice_first_last_chunk)] let u = [10, 40, 30]; assert_eq!(Some(&[40, 30]), u.last_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.last_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.last_chunk::<0>()); ``` #### pub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]🔬This is a nightly-only experimental API. (`slice_first_last_chunk`)Returns a mutable pointer to the last item in the slice. ##### Examples ``` #![feature(slice_first_last_chunk)] let x = &mut [0, 1, 2]; if let Some(last) = x.last_chunk_mut::<2>() { last[0] = 10; last[1] = 20; } assert_eq!(x, &[0, 10, 20]); ``` 1.0.0 · source#### pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>where I: SliceIndex<[T]>, Returns a reference to an element or subslice depending on the type of index. * If given a position, returns a reference to the element at that position or `None` if out of bounds. * If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ##### Examples ``` let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` 1.0.0 · source#### pub fn get_mut<I>( &mut self, index: I ) -> Option<&mut <I as SliceIndex<[T]>>::Output>where I: SliceIndex<[T]>, Returns a mutable reference to an element or subslice depending on the type of index (see `get`) or `None` if the index is out of bounds. ##### Examples ``` let x = &mut [0, 1, 2]; if let Some(elem) = x.get_mut(1) { *elem = 42; } assert_eq!(x, &[0, 42, 2]); ``` 1.0.0 · source#### pub unsafe fn get_unchecked<I>( &self, index: I ) -> &<I as SliceIndex<[T]>>::Outputwhere I: SliceIndex<[T]>, Returns a reference to an element or subslice, without doing bounds checking. For a safe alternative see `get`. ##### Safety Calling this method with an out-of-bounds index is *undefined behavior* even if the resulting reference is not used. ##### Examples ``` let x = &[1, 2, 4]; unsafe { assert_eq!(x.get_unchecked(1), &2); } ``` 1.0.0 · source#### pub unsafe fn get_unchecked_mut<I>( &mut self, index: I ) -> &mut <I as SliceIndex<[T]>>::Outputwhere I: SliceIndex<[T]>, Returns a mutable reference to an element or subslice, without doing bounds checking. For a safe alternative see `get_mut`. ##### Safety Calling this method with an out-of-bounds index is *undefined behavior* even if the resulting reference is not used. ##### Examples ``` let x = &mut [1, 2, 4]; unsafe { let elem = x.get_unchecked_mut(1); *elem = 13; } assert_eq!(x, &[1, 13, 4]); ``` 1.0.0 · source#### pub fn as_ptr(&self) -> *const T Returns a raw pointer to the slice’s buffer. The caller must ensure that the slice outlives the pointer this function returns, or else it will end up pointing to garbage. The caller must also ensure that the memory the pointer (non-transitively) points to is never written to (except inside an `UnsafeCell`) using this pointer or any pointer derived from it. If you need to mutate the contents of the slice, use `as_mut_ptr`. Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid. ##### Examples ``` let x = &[1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(x.get_unchecked(i), &*x_ptr.add(i)); } } ``` 1.0.0 · source#### pub fn as_mut_ptr(&mut self) -> *mut T Returns an unsafe mutable pointer to the slice’s buffer. The caller must ensure that the slice outlives the pointer this function returns, or else it will end up pointing to garbage. Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid. ##### Examples ``` let x = &mut [1, 2, 4]; let x_ptr = x.as_mut_ptr(); unsafe { for i in 0..x.len() { *x_ptr.add(i) += 2; } } assert_eq!(x, &[3, 4, 6]); ``` 1.48.0 · source#### pub fn as_ptr_range(&self) -> Range<*const TReturns the two raw pointers spanning the slice. The returned range is half-open, which means that the end pointer points *one past* the last element of the slice. This way, an empty slice is represented by two equal pointers, and the difference between the two pointers represents the size of the slice. See `as_ptr` for warnings on using these pointers. The end pointer requires extra caution, as it does not point to a valid element in the slice. This function is useful for interacting with foreign interfaces which use two pointers to refer to a range of elements in memory, as is common in C++. It can also be useful to check if a pointer to an element refers to an element of this slice: ``` let a = [1, 2, 3]; let x = &a[1] as *const _; let y = &5 as *const _; assert!(a.as_ptr_range().contains(&x)); assert!(!a.as_ptr_range().contains(&y)); ``` 1.48.0 · source#### pub fn as_mut_ptr_range(&mut self) -> Range<*mut TReturns the two unsafe mutable pointers spanning the slice. The returned range is half-open, which means that the end pointer points *one past* the last element of the slice. This way, an empty slice is represented by two equal pointers, and the difference between the two pointers represents the size of the slice. See `as_mut_ptr` for warnings on using these pointers. The end pointer requires extra caution, as it does not point to a valid element in the slice. This function is useful for interacting with foreign interfaces which use two pointers to refer to a range of elements in memory, as is common in C++. 1.0.0 · source#### pub fn swap(&mut self, a: usize, b: usize) Swaps two elements in the slice. If `a` equals to `b`, it’s guaranteed that elements won’t change value. ##### Arguments * a - The index of the first element * b - The index of the second element ##### Panics Panics if `a` or `b` are out of bounds. ##### Examples ``` let mut v = ["a", "b", "c", "d", "e"]; v.swap(2, 4); assert!(v == ["a", "b", "e", "d", "c"]); ``` #### pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize) 🔬This is a nightly-only experimental API. (`slice_swap_unchecked`)Swaps two elements in the slice, without doing bounds checking. For a safe alternative see `swap`. ##### Arguments * a - The index of the first element * b - The index of the second element ##### Safety Calling this method with an out-of-bounds index is *undefined behavior*. The caller has to ensure that `a < self.len()` and `b < self.len()`. ##### Examples ``` #![feature(slice_swap_unchecked)] let mut v = ["a", "b", "c", "d"]; // SAFETY: we know that 1 and 3 are both indices of the slice unsafe { v.swap_unchecked(1, 3) }; assert!(v == ["a", "d", "c", "b"]); ``` 1.0.0 · source#### pub fn reverse(&mut self) Reverses the order of elements in the slice, in place. ##### Examples ``` let mut v = [1, 2, 3]; v.reverse(); assert!(v == [3, 2, 1]); ``` 1.0.0 · source#### pub fn iter(&self) -> Iter<'_, TReturns an iterator over the slice. The iterator yields all items from start to end. ##### Examples ``` let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` 1.0.0 · source#### pub fn iter_mut(&mut self) -> IterMut<'_, TReturns an iterator that allows modifying each value. The iterator yields all items from start to end. ##### Examples ``` let x = &mut [1, 2, 4]; for elem in x.iter_mut() { *elem += 2; } assert_eq!(x, &[3, 4, 6]); ``` 1.0.0 · source#### pub fn windows(&self, size: usize) -> Windows<'_, TReturns an iterator over all contiguous windows of length `size`. The windows overlap. If the slice is shorter than `size`, the iterator returns no values. ##### Panics Panics if `size` is 0. ##### Examples ``` let slice = ['r', 'u', 's', 't']; let mut iter = slice.windows(2); assert_eq!(iter.next().unwrap(), &['r', 'u']); assert_eq!(iter.next().unwrap(), &['u', 's']); assert_eq!(iter.next().unwrap(), &['s', 't']); assert!(iter.next().is_none()); ``` If the slice is shorter than `size`: ``` let slice = ['f', 'o', 'o']; let mut iter = slice.windows(4); assert!(iter.next().is_none()); ``` There’s no `windows_mut`, as that existing would let safe code violate the “only one `&mut` at a time to the same thing” rule. However, you can sometimes use `Cell::as_slice_of_cells` in conjunction with `windows` to accomplish something similar: ``` use std::cell::Cell; let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5']; let slice = &mut array[..]; let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells(); for w in slice_of_cells.windows(3) { Cell::swap(&w[0], &w[2]); } assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']); ``` 1.0.0 · source#### pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, TReturns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice. The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`. See `chunks_exact` for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and `rchunks` for the same iterator but starting at the end of the slice. ##### Panics Panics if `chunk_size` is 0. ##### Examples ``` let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.chunks(2); assert_eq!(iter.next().unwrap(), &['l', 'o']); assert_eq!(iter.next().unwrap(), &['r', 'e']); assert_eq!(iter.next().unwrap(), &['m']); assert!(iter.next().is_none()); ``` 1.0.0 · source#### pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, TReturns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice. The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`. See `chunks_exact_mut` for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and `rchunks_mut` for the same iterator but starting at the end of the slice. ##### Panics Panics if `chunk_size` is 0. ##### Examples ``` let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.chunks_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[1, 1, 2, 2, 3]); ``` 1.31.0 · source#### pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, TReturns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice. The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `remainder` function of the iterator. Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of `chunks`. See `chunks` for a variant of this iterator that also returns the remainder as a smaller chunk, and `rchunks_exact` for the same iterator but starting at the end of the slice. ##### Panics Panics if `chunk_size` is 0. ##### Examples ``` let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.chunks_exact(2); assert_eq!(iter.next().unwrap(), &['l', 'o']); assert_eq!(iter.next().unwrap(), &['r', 'e']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['m']); ``` 1.31.0 · source#### pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, TReturns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice. The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `into_remainder` function of the iterator. Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of `chunks_mut`. See `chunks_mut` for a variant of this iterator that also returns the remainder as a smaller chunk, and `rchunks_exact_mut` for the same iterator but starting at the end of the slice. ##### Panics Panics if `chunk_size` is 0. ##### Examples ``` let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.chunks_exact_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[1, 1, 2, 2, 0]); ``` #### pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]] 🔬This is a nightly-only experimental API. (`slice_as_chunks`)Splits the slice into a slice of `N`-element arrays, assuming that there’s no remainder. ##### Safety This may only be called when * The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`). * `N != 0`. ##### Examples ``` #![feature(slice_as_chunks)] let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!']; let chunks: &[[char; 1]] = // SAFETY: 1-element chunks never have remainder unsafe { slice.as_chunks_unchecked() }; assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]); let chunks: &[[char; 3]] = // SAFETY: The slice length (6) is a multiple of 3 unsafe { slice.as_chunks_unchecked() }; assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]); // These would be unsound: // let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5 // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed ``` #### pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) 🔬This is a nightly-only experimental API. (`slice_as_chunks`)Splits the slice into a slice of `N`-element arrays, starting at the beginning of the slice, and a remainder slice with length strictly less than `N`. ##### Panics Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized. ##### Examples ``` #![feature(slice_as_chunks)] let slice = ['l', 'o', 'r', 'e', 'm']; let (chunks, remainder) = slice.as_chunks(); assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]); assert_eq!(remainder, &['m']); ``` If you expect the slice to be an exact multiple, you can combine `let`-`else` with an empty slice pattern: ``` #![feature(slice_as_chunks)] let slice = ['R', 'u', 's', 't']; let (chunks, []) = slice.as_chunks::<2>() else { panic!("slice didn't have even length") }; assert_eq!(chunks, &[['R', 'u'], ['s', 't']]); ``` #### pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]]) 🔬This is a nightly-only experimental API. (`slice_as_chunks`)Splits the slice into a slice of `N`-element arrays, starting at the end of the slice, and a remainder slice with length strictly less than `N`. ##### Panics Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized. ##### Examples ``` #![feature(slice_as_chunks)] let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks(); assert_eq!(remainder, &['l']); assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); ``` #### pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N🔬This is a nightly-only experimental API. (`array_chunks`)Returns an iterator over `N` elements of the slice at a time, starting at the beginning of the slice. The chunks are array references and do not overlap. If `N` does not divide the length of the slice, then the last up to `N-1` elements will be omitted and can be retrieved from the `remainder` function of the iterator. This method is the const generic equivalent of `chunks_exact`. ##### Panics Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized. ##### Examples ``` #![feature(array_chunks)] let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.array_chunks(); assert_eq!(iter.next().unwrap(), &['l', 'o']); assert_eq!(iter.next().unwrap(), &['r', 'e']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['m']); ``` #### pub unsafe fn as_chunks_unchecked_mut<const N: usize>( &mut self ) -> &mut [[T; N]] 🔬This is a nightly-only experimental API. (`slice_as_chunks`)Splits the slice into a slice of `N`-element arrays, assuming that there’s no remainder. ##### Safety This may only be called when * The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`). * `N != 0`. ##### Examples ``` #![feature(slice_as_chunks)] let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!']; let chunks: &mut [[char; 1]] = // SAFETY: 1-element chunks never have remainder unsafe { slice.as_chunks_unchecked_mut() }; chunks[0] = ['L']; assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]); let chunks: &mut [[char; 3]] = // SAFETY: The slice length (6) is a multiple of 3 unsafe { slice.as_chunks_unchecked_mut() }; chunks[1] = ['a', 'x', '?']; assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']); // These would be unsound: // let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5 // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed ``` #### pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) 🔬This is a nightly-only experimental API. (`slice_as_chunks`)Splits the slice into a slice of `N`-element arrays, starting at the beginning of the slice, and a remainder slice with length strictly less than `N`. ##### Panics Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized. ##### Examples ``` #![feature(slice_as_chunks)] let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; let (chunks, remainder) = v.as_chunks_mut(); remainder[0] = 9; for chunk in chunks { *chunk = [count; 2]; count += 1; } assert_eq!(v, &[1, 1, 2, 2, 9]); ``` #### pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]]) 🔬This is a nightly-only experimental API. (`slice_as_chunks`)Splits the slice into a slice of `N`-element arrays, starting at the end of the slice, and a remainder slice with length strictly less than `N`. ##### Panics Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized. ##### Examples ``` #![feature(slice_as_chunks)] let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; let (remainder, chunks) = v.as_rchunks_mut(); remainder[0] = 9; for chunk in chunks { *chunk = [count; 2]; count += 1; } assert_eq!(v, &[9, 1, 1, 2, 2]); ``` #### pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N🔬This is a nightly-only experimental API. (`array_chunks`)Returns an iterator over `N` elements of the slice at a time, starting at the beginning of the slice. The chunks are mutable array references and do not overlap. If `N` does not divide the length of the slice, then the last up to `N-1` elements will be omitted and can be retrieved from the `into_remainder` function of the iterator. This method is the const generic equivalent of `chunks_exact_mut`. ##### Panics Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized. ##### Examples ``` #![feature(array_chunks)] let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.array_chunks_mut() { *chunk = [count; 2]; count += 1; } assert_eq!(v, &[1, 1, 2, 2, 0]); ``` #### pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N🔬This is a nightly-only experimental API. (`array_windows`)Returns an iterator over overlapping windows of `N` elements of a slice, starting at the beginning of the slice. This is the const generic equivalent of `windows`. If `N` is greater than the size of the slice, it will return no windows. ##### Panics Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized. ##### Examples ``` #![feature(array_windows)] let slice = [0, 1, 2, 3]; let mut iter = slice.array_windows(); assert_eq!(iter.next().unwrap(), &[0, 1]); assert_eq!(iter.next().unwrap(), &[1, 2]); assert_eq!(iter.next().unwrap(), &[2, 3]); assert!(iter.next().is_none()); ``` 1.31.0 · source#### pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, TReturns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`. See `rchunks_exact` for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and `chunks` for the same iterator but starting at the beginning of the slice. ##### Panics Panics if `chunk_size` is 0. ##### Examples ``` let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` 1.31.0 · source#### pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, TReturns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`. See `rchunks_exact_mut` for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and `chunks_mut` for the same iterator but starting at the beginning of the slice. ##### Panics Panics if `chunk_size` is 0. ##### Examples ``` let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[3, 2, 2, 1, 1]); ``` 1.31.0 · source#### pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, TReturns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `remainder` function of the iterator. Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of `rchunks`. See `rchunks` for a variant of this iterator that also returns the remainder as a smaller chunk, and `chunks_exact` for the same iterator but starting at the beginning of the slice. ##### Panics Panics if `chunk_size` is 0. ##### Examples ``` let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` 1.31.0 · source#### pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, TReturns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `into_remainder` function of the iterator. Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of `chunks_mut`. See `rchunks_mut` for a variant of this iterator that also returns the remainder as a smaller chunk, and `chunks_exact_mut` for the same iterator but starting at the beginning of the slice. ##### Panics Panics if `chunk_size` is 0. ##### Examples ``` let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_exact_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[0, 2, 2, 1, 1]); ``` #### pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F> where F: FnMut(&T, &T) -> bool, 🔬This is a nightly-only experimental API. (`slice_group_by`)Returns an iterator over the slice producing non-overlapping runs of elements using the predicate to separate them. The predicate is called on two elements following themselves, it means the predicate is called on `slice[0]` and `slice[1]` then on `slice[1]` and `slice[2]` and so on. ##### Examples ``` #![feature(slice_group_by)] let slice = &[1, 1, 1, 3, 3, 2, 2, 2]; let mut iter = slice.group_by(|a, b| a == b); assert_eq!(iter.next(), Some(&[1, 1, 1][..])); assert_eq!(iter.next(), Some(&[3, 3][..])); assert_eq!(iter.next(), Some(&[2, 2, 2][..])); assert_eq!(iter.next(), None); ``` This method can be used to extract the sorted subslices: ``` #![feature(slice_group_by)] let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4]; let mut iter = slice.group_by(|a, b| a <= b); assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..])); assert_eq!(iter.next(), Some(&[2, 3][..])); assert_eq!(iter.next(), Some(&[2, 3, 4][..])); assert_eq!(iter.next(), None); ``` #### pub fn group_by_mut<F>(&mut self, pred: F) -> GroupByMut<'_, T, F> where F: FnMut(&T, &T) -> bool, 🔬This is a nightly-only experimental API. (`slice_group_by`)Returns an iterator over the slice producing non-overlapping mutable runs of elements using the predicate to separate them. The predicate is called on two elements following themselves, it means the predicate is called on `slice[0]` and `slice[1]` then on `slice[1]` and `slice[2]` and so on. ##### Examples ``` #![feature(slice_group_by)] let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2]; let mut iter = slice.group_by_mut(|a, b| a == b); assert_eq!(iter.next(), Some(&mut [1, 1, 1][..])); assert_eq!(iter.next(), Some(&mut [3, 3][..])); assert_eq!(iter.next(), Some(&mut [2, 2, 2][..])); assert_eq!(iter.next(), None); ``` This method can be used to extract the sorted subslices: ``` #![feature(slice_group_by)] let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4]; let mut iter = slice.group_by_mut(|a, b| a <= b); assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..])); assert_eq!(iter.next(), Some(&mut [2, 3][..])); assert_eq!(iter.next(), Some(&mut [2, 3, 4][..])); assert_eq!(iter.next(), None); ``` 1.0.0 · source#### pub fn split_at(&self, mid: usize) -> (&[T], &[T]) Divides one slice into two at an index. The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself). ##### Panics Panics if `mid > len`. ##### Examples ``` let v = [1, 2, 3, 4, 5, 6]; { let (left, right) = v.split_at(0); assert_eq!(left, []); assert_eq!(right, [1, 2, 3, 4, 5, 6]); } { let (left, right) = v.split_at(2); assert_eq!(left, [1, 2]); assert_eq!(right, [3, 4, 5, 6]); } { let (left, right) = v.split_at(6); assert_eq!(left, [1, 2, 3, 4, 5, 6]); assert_eq!(right, []); } ``` 1.0.0 · source#### pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) Divides one mutable slice into two at an index. The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself). ##### Panics Panics if `mid > len`. ##### Examples ``` let mut v = [1, 0, 3, 0, 5, 6]; let (left, right) = v.split_at_mut(2); assert_eq!(left, [1, 0]); assert_eq!(right, [3, 0, 5, 6]); left[1] = 2; right[1] = 4; assert_eq!(v, [1, 2, 3, 4, 5, 6]); ``` #### pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) 🔬This is a nightly-only experimental API. (`slice_split_at_unchecked`)Divides one slice into two at an index, without doing bounds checking. The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself). For a safe alternative see `split_at`. ##### Safety Calling this method with an out-of-bounds index is *undefined behavior* even if the resulting reference is not used. The caller has to ensure that `0 <= mid <= self.len()`. ##### Examples ``` #![feature(slice_split_at_unchecked)] let v = [1, 2, 3, 4, 5, 6]; unsafe { let (left, right) = v.split_at_unchecked(0); assert_eq!(left, []); assert_eq!(right, [1, 2, 3, 4, 5, 6]); } unsafe { let (left, right) = v.split_at_unchecked(2); assert_eq!(left, [1, 2]); assert_eq!(right, [3, 4, 5, 6]); } unsafe { let (left, right) = v.split_at_unchecked(6); assert_eq!(left, [1, 2, 3, 4, 5, 6]); assert_eq!(right, []); } ``` #### pub unsafe fn split_at_mut_unchecked( &mut self, mid: usize ) -> (&mut [T], &mut [T]) 🔬This is a nightly-only experimental API. (`slice_split_at_unchecked`)Divides one mutable slice into two at an index, without doing bounds checking. The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself). For a safe alternative see `split_at_mut`. ##### Safety Calling this method with an out-of-bounds index is *undefined behavior* even if the resulting reference is not used. The caller has to ensure that `0 <= mid <= self.len()`. ##### Examples ``` #![feature(slice_split_at_unchecked)] let mut v = [1, 0, 3, 0, 5, 6]; // scoped to restrict the lifetime of the borrows unsafe { let (left, right) = v.split_at_mut_unchecked(2); assert_eq!(left, [1, 0]); assert_eq!(right, [3, 0, 5, 6]); left[1] = 2; right[1] = 4; } assert_eq!(v, [1, 2, 3, 4, 5, 6]); ``` #### pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T]) 🔬This is a nightly-only experimental API. (`split_array`)Divides one slice into an array and a remainder slice at an index. The array will contain all indices from `[0, N)` (excluding the index `N` itself) and the slice will contain all indices from `[N, len)` (excluding the index `len` itself). ##### Panics Panics if `N > len`. ##### Examples ``` #![feature(split_array)] let v = &[1, 2, 3, 4, 5, 6][..]; { let (left, right) = v.split_array_ref::<0>(); assert_eq!(left, &[]); assert_eq!(right, [1, 2, 3, 4, 5, 6]); } { let (left, right) = v.split_array_ref::<2>(); assert_eq!(left, &[1, 2]); assert_eq!(right, [3, 4, 5, 6]); } { let (left, right) = v.split_array_ref::<6>(); assert_eq!(left, &[1, 2, 3, 4, 5, 6]); assert_eq!(right, []); } ``` #### pub fn split_array_mut<const N: usize>(&mut self) -> (&mut [T; N], &mut [T]) 🔬This is a nightly-only experimental API. (`split_array`)Divides one mutable slice into an array and a remainder slice at an index. The array will contain all indices from `[0, N)` (excluding the index `N` itself) and the slice will contain all indices from `[N, len)` (excluding the index `len` itself). ##### Panics Panics if `N > len`. ##### Examples ``` #![feature(split_array)] let mut v = &mut [1, 0, 3, 0, 5, 6][..]; let (left, right) = v.split_array_mut::<2>(); assert_eq!(left, &mut [1, 0]); assert_eq!(right, [3, 0, 5, 6]); left[1] = 2; right[1] = 4; assert_eq!(v, [1, 2, 3, 4, 5, 6]); ``` #### pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N]) 🔬This is a nightly-only experimental API. (`split_array`)Divides one slice into an array and a remainder slice at an index from the end. The slice will contain all indices from `[0, len - N)` (excluding the index `len - N` itself) and the array will contain all indices from `[len - N, len)` (excluding the index `len` itself). ##### Panics Panics if `N > len`. ##### Examples ``` #![feature(split_array)] let v = &[1, 2, 3, 4, 5, 6][..]; { let (left, right) = v.rsplit_array_ref::<0>(); assert_eq!(left, [1, 2, 3, 4, 5, 6]); assert_eq!(right, &[]); } { let (left, right) = v.rsplit_array_ref::<2>(); assert_eq!(left, [1, 2, 3, 4]); assert_eq!(right, &[5, 6]); } { let (left, right) = v.rsplit_array_ref::<6>(); assert_eq!(left, []); assert_eq!(right, &[1, 2, 3, 4, 5, 6]); } ``` #### pub fn rsplit_array_mut<const N: usize>(&mut self) -> (&mut [T], &mut [T; N]) 🔬This is a nightly-only experimental API. (`split_array`)Divides one mutable slice into an array and a remainder slice at an index from the end. The slice will contain all indices from `[0, len - N)` (excluding the index `N` itself) and the array will contain all indices from `[len - N, len)` (excluding the index `len` itself). ##### Panics Panics if `N > len`. ##### Examples ``` #![feature(split_array)] let mut v = &mut [1, 0, 3, 0, 5, 6][..]; let (left, right) = v.rsplit_array_mut::<4>(); assert_eq!(left, [1, 0]); assert_eq!(right, &mut [3, 0, 5, 6]); left[1] = 2; right[1] = 4; assert_eq!(v, [1, 2, 3, 4, 5, 6]); ``` 1.0.0 · source#### pub fn split<F>(&self, pred: F) -> Split<'_, T, F> where F: FnMut(&T) -> bool, Returns an iterator over subslices separated by elements that match `pred`. The matched element is not contained in the subslices. ##### Examples ``` let slice = [10, 40, 33, 20]; let mut iter = slice.split(|num| num % 3 == 0); assert_eq!(iter.next().unwrap(), &[10, 40]); assert_eq!(iter.next().unwrap(), &[20]); assert!(iter.next().is_none()); ``` If the first element is matched, an empty slice will be the first item returned by the iterator. Similarly, if the last element in the slice is matched, an empty slice will be the last item returned by the iterator: ``` let slice = [10, 40, 33]; let mut iter = slice.split(|num| num % 3 == 0); assert_eq!(iter.next().unwrap(), &[10, 40]); assert_eq!(iter.next().unwrap(), &[]); assert!(iter.next().is_none()); ``` If two matched elements are directly adjacent, an empty slice will be present between them: ``` let slice = [10, 6, 33, 20]; let mut iter = slice.split(|num| num % 3 == 0); assert_eq!(iter.next().unwrap(), &[10]); assert_eq!(iter.next().unwrap(), &[]); assert_eq!(iter.next().unwrap(), &[20]); assert!(iter.next().is_none()); ``` 1.0.0 · source#### pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F> where F: FnMut(&T) -> bool, Returns an iterator over mutable subslices separated by elements that match `pred`. The matched element is not contained in the subslices. ##### Examples ``` let mut v = [10, 40, 30, 20, 60, 50]; for group in v.split_mut(|num| *num % 3 == 0) { group[0] = 1; } assert_eq!(v, [1, 40, 30, 1, 60, 1]); ``` 1.51.0 · source#### pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F> where F: FnMut(&T) -> bool, Returns an iterator over subslices separated by elements that match `pred`. The matched element is contained in the end of the previous subslice as a terminator. ##### Examples ``` let slice = [10, 40, 33, 20]; let mut iter = slice.split_inclusive(|num| num % 3 == 0); assert_eq!(iter.next().unwrap(), &[10, 40, 33]); assert_eq!(iter.next().unwrap(), &[20]); assert!(iter.next().is_none()); ``` If the last element of the slice is matched, that element will be considered the terminator of the preceding slice. That slice will be the last item returned by the iterator. ``` let slice = [3, 10, 40, 33]; let mut iter = slice.split_inclusive(|num| num % 3 == 0); assert_eq!(iter.next().unwrap(), &[3]); assert_eq!(iter.next().unwrap(), &[10, 40, 33]); assert!(iter.next().is_none()); ``` 1.51.0 · source#### pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F> where F: FnMut(&T) -> bool, Returns an iterator over mutable subslices separated by elements that match `pred`. The matched element is contained in the previous subslice as a terminator. ##### Examples ``` let mut v = [10, 40, 30, 20, 60, 50]; for group in v.split_inclusive_mut(|num| *num % 3 == 0) { let terminator_idx = group.len()-1; group[terminator_idx] = 1; } assert_eq!(v, [10, 40, 1, 20, 1, 1]); ``` 1.27.0 · source#### pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F> where F: FnMut(&T) -> bool, Returns an iterator over subslices separated by elements that match `pred`, starting at the end of the slice and working backwards. The matched element is not contained in the subslices. ##### Examples ``` let slice = [11, 22, 33, 0, 44, 55]; let mut iter = slice.rsplit(|num| *num == 0); assert_eq!(iter.next().unwrap(), &[44, 55]); assert_eq!(iter.next().unwrap(), &[11, 22, 33]); assert_eq!(iter.next(), None); ``` As with `split()`, if the first or last element is matched, an empty slice will be the first (or last) item returned by the iterator. ``` let v = &[0, 1, 1, 2, 3, 5, 8]; let mut it = v.rsplit(|n| *n % 2 == 0); assert_eq!(it.next().unwrap(), &[]); assert_eq!(it.next().unwrap(), &[3, 5]); assert_eq!(it.next().unwrap(), &[1, 1]); assert_eq!(it.next().unwrap(), &[]); assert_eq!(it.next(), None); ``` 1.27.0 · source#### pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F> where F: FnMut(&T) -> bool, Returns an iterator over mutable subslices separated by elements that match `pred`, starting at the end of the slice and working backwards. The matched element is not contained in the subslices. ##### Examples ``` let mut v = [100, 400, 300, 200, 600, 500]; let mut count = 0; for group in v.rsplit_mut(|num| *num % 3 == 0) { count += 1; group[0] = count; } assert_eq!(v, [3, 400, 300, 2, 600, 1]); ``` 1.0.0 · source#### pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F> where F: FnMut(&T) -> bool, Returns an iterator over subslices separated by elements that match `pred`, limited to returning at most `n` items. The matched element is not contained in the subslices. The last element returned, if any, will contain the remainder of the slice. ##### Examples Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`, `[20, 60, 50]`): ``` let v = [10, 40, 30, 20, 60, 50]; for group in v.splitn(2, |num| *num % 3 == 0) { println!("{group:?}"); } ``` 1.0.0 · source#### pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F> where F: FnMut(&T) -> bool, Returns an iterator over mutable subslices separated by elements that match `pred`, limited to returning at most `n` items. The matched element is not contained in the subslices. The last element returned, if any, will contain the remainder of the slice. ##### Examples ``` let mut v = [10, 40, 30, 20, 60, 50]; for group in v.splitn_mut(2, |num| *num % 3 == 0) { group[0] = 1; } assert_eq!(v, [1, 40, 30, 1, 60, 50]); ``` 1.0.0 · source#### pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F> where F: FnMut(&T) -> bool, Returns an iterator over subslices separated by elements that match `pred` limited to returning at most `n` items. This starts at the end of the slice and works backwards. The matched element is not contained in the subslices. The last element returned, if any, will contain the remainder of the slice. ##### Examples Print the slice split once, starting from the end, by numbers divisible by 3 (i.e., `[50]`, `[10, 40, 30, 20]`): ``` let v = [10, 40, 30, 20, 60, 50]; for group in v.rsplitn(2, |num| *num % 3 == 0) { println!("{group:?}"); } ``` 1.0.0 · source#### pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F> where F: FnMut(&T) -> bool, Returns an iterator over subslices separated by elements that match `pred` limited to returning at most `n` items. This starts at the end of the slice and works backwards. The matched element is not contained in the subslices. The last element returned, if any, will contain the remainder of the slice. ##### Examples ``` let mut s = [10, 40, 30, 20, 60, 50]; for group in s.rsplitn_mut(2, |num| *num % 3 == 0) { group[0] = 1; } assert_eq!(s, [1, 40, 30, 20, 60, 1]); ``` 1.0.0 · source#### pub fn contains(&self, x: &T) -> boolwhere T: PartialEq<T>, Returns `true` if the slice contains an element with the given value. This operation is *O*(*n*). Note that if you have a sorted slice, `binary_search` may be faster. ##### Examples ``` let v = [10, 40, 30]; assert!(v.contains(&30)); assert!(!v.contains(&50)); ``` If you do not have a `&T`, but some other value that you can compare with one (for example, `String` implements `PartialEq<str>`), you can use `iter().any`: ``` let v = [String::from("hello"), String::from("world")]; // slice of `String` assert!(v.iter().any(|e| e == "hello")); // search with `&str` assert!(!v.iter().any(|e| e == "hi")); ``` 1.0.0 · source#### pub fn starts_with(&self, needle: &[T]) -> boolwhere T: PartialEq<T>, Returns `true` if `needle` is a prefix of the slice. ##### Examples ``` let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` Always returns `true` if `needle` is an empty slice: ``` let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` 1.0.0 · source#### pub fn ends_with(&self, needle: &[T]) -> boolwhere T: PartialEq<T>, Returns `true` if `needle` is a suffix of the slice. ##### Examples ``` let v = [10, 40, 30]; assert!(v.ends_with(&[30])); assert!(v.ends_with(&[40, 30])); assert!(!v.ends_with(&[50])); assert!(!v.ends_with(&[50, 30])); ``` Always returns `true` if `needle` is an empty slice: ``` let v = &[10, 40, 30]; assert!(v.ends_with(&[])); let v: &[u8] = &[]; assert!(v.ends_with(&[])); ``` 1.51.0 · source#### pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>where P: SlicePattern<Item = T> + ?Sized, T: PartialEq<T>, Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If the slice does not start with `prefix`, returns `None`. ##### Examples ``` let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` 1.51.0 · source#### pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>where P: SlicePattern<Item = T> + ?Sized, T: PartialEq<T>, Returns a subslice with the suffix removed. If the slice ends with `suffix`, returns the subslice before the suffix, wrapped in `Some`. If `suffix` is empty, simply returns the original slice. If the slice does not end with `suffix`, returns `None`. ##### Examples ``` let v = &[10, 40, 30]; assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..])); assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..])); assert_eq!(v.strip_suffix(&[50]), None); assert_eq!(v.strip_suffix(&[50, 30]), None); ``` 1.0.0 · source#### pub fn binary_search(&self, x: &T) -> Result<usize, usize>where T: Ord, Binary searches this slice for a given element. If the slice is not sorted, the returned result is unspecified and meaningless. If the value is found then `Result::Ok` is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. The index is chosen deterministically, but is subject to change in future versions of Rust. If the value is not found then `Result::Err` is returned, containing the index where a matching element could be inserted while maintaining sorted order. See also `binary_search_by`, `binary_search_by_key`, and `partition_point`. ##### Examples Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`. ``` let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` If you want to find that whole *range* of matching items, rather than an arbitrary matching one, that can be done using `partition_point`: ``` let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let low = s.partition_point(|x| x < &1); assert_eq!(low, 1); let high = s.partition_point(|x| x <= &1); assert_eq!(high, 5); let r = s.binary_search(&1); assert!((low..high).contains(&r.unwrap())); assert!(s[..low].iter().all(|&x| x < 1)); assert!(s[low..high].iter().all(|&x| x == 1)); assert!(s[high..].iter().all(|&x| x > 1)); // For something not found, the "range" of equal items is empty assert_eq!(s.partition_point(|x| x < &11), 9); assert_eq!(s.partition_point(|x| x <= &11), 9); assert_eq!(s.binary_search(&11), Err(9)); ``` If you want to insert an item to a sorted vector, while maintaining sort order, consider using `partition_point`: ``` let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let num = 42; let idx = s.partition_point(|&x| x < num); // The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);` s.insert(idx, num); assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); ``` 1.0.0 · source#### pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>where F: FnMut(&'a T) -> Ordering, Binary searches this slice with a comparator function. The comparator function should return an order code that indicates whether its argument is `Less`, `Equal` or `Greater` the desired target. If the slice is not sorted or if the comparator function does not implement an order consistent with the sort order of the underlying slice, the returned result is unspecified and meaningless. If the value is found then `Result::Ok` is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. The index is chosen deterministically, but is subject to change in future versions of Rust. If the value is not found then `Result::Err` is returned, containing the index where a matching element could be inserted while maintaining sorted order. See also `binary_search`, `binary_search_by_key`, and `partition_point`. ##### Examples Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`. ``` let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let seek = 13; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9)); let seek = 4; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7)); let seek = 100; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13)); let seek = 1; let r = s.binary_search_by(|probe| probe.cmp(&seek)); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` 1.10.0 · source#### pub fn binary_search_by_key<'a, B, F>( &'a self, b: &B, f: F ) -> Result<usize, usize>where F: FnMut(&'a T) -> B, B: Ord, Binary searches this slice with a key extraction function. Assumes that the slice is sorted by the key, for instance with `sort_by_key` using the same key extraction function. If the slice is not sorted by the key, the returned result is unspecified and meaningless. If the value is found then `Result::Ok` is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. The index is chosen deterministically, but is subject to change in future versions of Rust. If the value is not found then `Result::Err` is returned, containing the index where a matching element could be inserted while maintaining sorted order. See also `binary_search`, `binary_search_by`, and `partition_point`. ##### Examples Looks up a series of four elements in a slice of pairs sorted by their second elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`. ``` let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13), (1, 21), (2, 34), (4, 55)]; assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9)); assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7)); assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13)); let r = s.binary_search_by_key(&1, |&(a, b)| b); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` 1.20.0 · source#### pub fn sort_unstable(&mut self)where T: Ord, Sorts the slice, but might not preserve the order of equal elements. This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and *O*(*n* * log(*n*)) worst-case. ##### Current implementation The current algorithm is based on pattern-defeating quicksort by <NAME>, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior. It is typically faster than stable sorting, except in a few special cases, e.g., when the slice consists of several concatenated sorted sequences. ##### Examples ``` let mut v = [-5, 4, 1, -3, 2]; v.sort_unstable(); assert!(v == [-5, -3, 1, 2, 4]); ``` 1.20.0 · source#### pub fn sort_unstable_by<F>(&mut self, compare: F)where F: FnMut(&T, &T) -> Ordering, Sorts the slice with a comparator function, but might not preserve the order of equal elements. This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and *O*(*n* * log(*n*)) worst-case. The comparator function must define a total ordering for the elements in the slice. If the ordering is not total, the order of the elements is unspecified. An order is a total order if it is (for all `a`, `b` and `c`): * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`. For example, while `f64` doesn’t implement `Ord` because `NaN != NaN`, we can use `partial_cmp` as our sort function when we know the slice doesn’t contain a `NaN`. ``` let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0]; floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()); assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]); ``` ##### Current implementation The current algorithm is based on pattern-defeating quicksort by <NAME>, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior. It is typically faster than stable sorting, except in a few special cases, e.g., when the slice consists of several concatenated sorted sequences. ##### Examples ``` let mut v = [5, 4, 1, 3, 2]; v.sort_unstable_by(|a, b| a.cmp(b)); assert!(v == [1, 2, 3, 4, 5]); // reverse sorting v.sort_unstable_by(|a, b| b.cmp(a)); assert!(v == [5, 4, 3, 2, 1]); ``` 1.20.0 · source#### pub fn sort_unstable_by_key<K, F>(&mut self, f: F)where F: FnMut(&T) -> K, K: Ord, Sorts the slice with a key extraction function, but might not preserve the order of equal elements. This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and *O*(*m* * *n* * log(*n*)) worst-case, where the key function is *O*(*m*). ##### Current implementation The current algorithm is based on pattern-defeating quicksort by <NAME>, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior. Due to its key calling strategy, `sort_unstable_by_key` is likely to be slower than `sort_by_cached_key` in cases where the key function is expensive. ##### Examples ``` let mut v = [-5i32, 4, 1, -3, 2]; v.sort_unstable_by_key(|k| k.abs()); assert!(v == [1, 2, -3, 4, -5]); ``` 1.49.0 · source#### pub fn select_nth_unstable( &mut self, index: usize ) -> (&mut [T], &mut T, &mut [T])where T: Ord, Reorder the slice such that the element at `index` is at its final sorted position. This reordering has the additional property that any value at position `i < index` will be less than or equal to any value at a position `j > index`. Additionally, this reordering is unstable (i.e. any number of equal elements may end up at position `index`), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This function is also known as “kth element” in other libraries. It returns a triplet of the following from the reordered slice: the subslice prior to `index`, the element at `index`, and the subslice after `index`; accordingly, the values in those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to the value of the element at `index`. ##### Current implementation The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also the basis for `sort_unstable`. The fallback algorithm is Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime for all inputs. ##### Panics Panics when `index >= len()`, meaning it always panics on empty slices. ##### Examples ``` let mut v = [-5i32, 4, 1, -3, 2]; // Find the median v.select_nth_unstable(2); // We are only guaranteed the slice will be one of the following, based on the way we sort // about the specified index. assert!(v == [-3, -5, 1, 2, 4] || v == [-5, -3, 1, 2, 4] || v == [-3, -5, 1, 4, 2] || v == [-5, -3, 1, 4, 2]); ``` 1.49.0 · source#### pub fn select_nth_unstable_by<F>( &mut self, index: usize, compare: F ) -> (&mut [T], &mut T, &mut [T])where F: FnMut(&T, &T) -> Ordering, Reorder the slice with a comparator function such that the element at `index` is at its final sorted position. This reordering has the additional property that any value at position `i < index` will be less than or equal to any value at a position `j > index` using the comparator function. Additionally, this reordering is unstable (i.e. any number of equal elements may end up at position `index`), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This function is also known as “kth element” in other libraries. It returns a triplet of the following from the slice reordered according to the provided comparator function: the subslice prior to `index`, the element at `index`, and the subslice after `index`; accordingly, the values in those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to the value of the element at `index`. ##### Current implementation The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also the basis for `sort_unstable`. The fallback algorithm is Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime for all inputs. ##### Panics Panics when `index >= len()`, meaning it always panics on empty slices. ##### Examples ``` let mut v = [-5i32, 4, 1, -3, 2]; // Find the median as if the slice were sorted in descending order. v.select_nth_unstable_by(2, |a, b| b.cmp(a)); // We are only guaranteed the slice will be one of the following, based on the way we sort // about the specified index. assert!(v == [2, 4, 1, -5, -3] || v == [2, 4, 1, -3, -5] || v == [4, 2, 1, -5, -3] || v == [4, 2, 1, -3, -5]); ``` 1.49.0 · source#### pub fn select_nth_unstable_by_key<K, F>( &mut self, index: usize, f: F ) -> (&mut [T], &mut T, &mut [T])where F: FnMut(&T) -> K, K: Ord, Reorder the slice with a key extraction function such that the element at `index` is at its final sorted position. This reordering has the additional property that any value at position `i < index` will be less than or equal to any value at a position `j > index` using the key extraction function. Additionally, this reordering is unstable (i.e. any number of equal elements may end up at position `index`), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This function is also known as “kth element” in other libraries. It returns a triplet of the following from the slice reordered according to the provided key extraction function: the subslice prior to `index`, the element at `index`, and the subslice after `index`; accordingly, the values in those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to the value of the element at `index`. ##### Current implementation The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also the basis for `sort_unstable`. The fallback algorithm is Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime for all inputs. ##### Panics Panics when `index >= len()`, meaning it always panics on empty slices. ##### Examples ``` let mut v = [-5i32, 4, 1, -3, 2]; // Return the median as if the array were sorted according to absolute value. v.select_nth_unstable_by_key(2, |a| a.abs()); // We are only guaranteed the slice will be one of the following, based on the way we sort // about the specified index. assert!(v == [1, 2, -3, 4, -5] || v == [1, 2, -3, -5, 4] || v == [2, 1, -3, 4, -5] || v == [2, 1, -3, -5, 4]); ``` #### pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])where T: PartialEq<T>, 🔬This is a nightly-only experimental API. (`slice_partition_dedup`)Moves all consecutive repeated elements to the end of the slice according to the `PartialEq` trait implementation. Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order. If the slice is sorted, the first returned slice contains no duplicates. ##### Examples ``` #![feature(slice_partition_dedup)] let mut slice = [1, 2, 2, 3, 3, 2, 1, 1]; let (dedup, duplicates) = slice.partition_dedup(); assert_eq!(dedup, [1, 2, 3, 2, 1]); assert_eq!(duplicates, [2, 3, 1]); ``` #### pub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])where F: FnMut(&mut T, &mut T) -> bool, 🔬This is a nightly-only experimental API. (`slice_partition_dedup`)Moves all but the first of consecutive elements to the end of the slice satisfying a given equality relation. Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order. The `same_bucket` function is passed references to two elements from the slice and must determine if the elements compare equal. The elements are passed in opposite order from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved at the end of the slice. If the slice is sorted, the first returned slice contains no duplicates. ##### Examples ``` #![feature(slice_partition_dedup)] let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"]; let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b)); assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]); assert_eq!(duplicates, ["bar", "Foo", "BAZ"]); ``` #### pub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])where F: FnMut(&mut T) -> K, K: PartialEq<K>, 🔬This is a nightly-only experimental API. (`slice_partition_dedup`)Moves all but the first of consecutive elements to the end of the slice that resolve to the same key. Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order. If the slice is sorted, the first returned slice contains no duplicates. ##### Examples ``` #![feature(slice_partition_dedup)] let mut slice = [10, 20, 21, 30, 30, 20, 11, 13]; let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10); assert_eq!(dedup, [10, 20, 30, 20, 11]); assert_eq!(duplicates, [21, 30, 13]); ``` 1.26.0 · source#### pub fn rotate_left(&mut self, mid: usize) Rotates the slice in-place such that the first `mid` elements of the slice move to the end while the last `self.len() - mid` elements move to the front. After calling `rotate_left`, the element previously at index `mid` will become the first element in the slice. ##### Panics This function will panic if `mid` is greater than the length of the slice. Note that `mid == self.len()` does *not* panic and is a no-op rotation. ##### Complexity Takes linear (in `self.len()`) time. ##### Examples ``` let mut a = ['a', 'b', 'c', 'd', 'e', 'f']; a.rotate_left(2); assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']); ``` Rotating a subslice: ``` let mut a = ['a', 'b', 'c', 'd', 'e', 'f']; a[1..5].rotate_left(1); assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']); ``` 1.26.0 · source#### pub fn rotate_right(&mut self, k: usize) Rotates the slice in-place such that the first `self.len() - k` elements of the slice move to the end while the last `k` elements move to the front. After calling `rotate_right`, the element previously at index `self.len() - k` will become the first element in the slice. ##### Panics This function will panic if `k` is greater than the length of the slice. Note that `k == self.len()` does *not* panic and is a no-op rotation. ##### Complexity Takes linear (in `self.len()`) time. ##### Examples ``` let mut a = ['a', 'b', 'c', 'd', 'e', 'f']; a.rotate_right(2); assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']); ``` Rotate a subslice: ``` let mut a = ['a', 'b', 'c', 'd', 'e', 'f']; a[1..5].rotate_right(1); assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']); ``` 1.50.0 · source#### pub fn fill(&mut self, value: T)where T: Clone, Fills `self` with elements by cloning `value`. ##### Examples ``` let mut buf = vec![0; 10]; buf.fill(1); assert_eq!(buf, vec![1; 10]); ``` 1.51.0 · source#### pub fn fill_with<F>(&mut self, f: F)where F: FnMut() -> T, Fills `self` with elements returned by calling a closure repeatedly. This method uses a closure to create new values. If you’d rather `Clone` a given value, use `fill`. If you want to use the `Default` trait to generate values, you can pass `Default::default` as the argument. ##### Examples ``` let mut buf = vec![1; 10]; buf.fill_with(Default::default); assert_eq!(buf, vec![0; 10]); ``` 1.7.0 · source#### pub fn clone_from_slice(&mut self, src: &[T])where T: Clone, Copies the elements from `src` into `self`. The length of `src` must be the same as `self`. ##### Panics This function will panic if the two slices have different lengths. ##### Examples Cloning two elements from a slice into another: ``` let src = [1, 2, 3, 4]; let mut dst = [0, 0]; // Because the slices have to be the same length, // we slice the source slice from four elements // to two. It will panic if we don't do this. dst.clone_from_slice(&src[2..]); assert_eq!(src, [1, 2, 3, 4]); assert_eq!(dst, [3, 4]); ``` Rust enforces that there can only be one mutable reference with no immutable references to a particular piece of data in a particular scope. Because of this, attempting to use `clone_from_slice` on a single slice will result in a compile failure: ``` let mut slice = [1, 2, 3, 4, 5]; slice[..2].clone_from_slice(&slice[3..]); // compile fail! ``` To work around this, we can use `split_at_mut` to create two distinct sub-slices from a slice: ``` let mut slice = [1, 2, 3, 4, 5]; { let (left, right) = slice.split_at_mut(2); left.clone_from_slice(&right[1..]); } assert_eq!(slice, [4, 5, 3, 4, 5]); ``` 1.9.0 · source#### pub fn copy_from_slice(&mut self, src: &[T])where T: Copy, Copies all elements from `src` into `self`, using a memcpy. The length of `src` must be the same as `self`. If `T` does not implement `Copy`, use `clone_from_slice`. ##### Panics This function will panic if the two slices have different lengths. ##### Examples Copying two elements from a slice into another: ``` let src = [1, 2, 3, 4]; let mut dst = [0, 0]; // Because the slices have to be the same length, // we slice the source slice from four elements // to two. It will panic if we don't do this. dst.copy_from_slice(&src[2..]); assert_eq!(src, [1, 2, 3, 4]); assert_eq!(dst, [3, 4]); ``` Rust enforces that there can only be one mutable reference with no immutable references to a particular piece of data in a particular scope. Because of this, attempting to use `copy_from_slice` on a single slice will result in a compile failure: ``` let mut slice = [1, 2, 3, 4, 5]; slice[..2].copy_from_slice(&slice[3..]); // compile fail! ``` To work around this, we can use `split_at_mut` to create two distinct sub-slices from a slice: ``` let mut slice = [1, 2, 3, 4, 5]; { let (left, right) = slice.split_at_mut(2); left.copy_from_slice(&right[1..]); } assert_eq!(slice, [4, 5, 3, 4, 5]); ``` 1.37.0 · source#### pub fn copy_within<R>(&mut self, src: R, dest: usize)where R: RangeBounds<usize>, T: Copy, Copies elements from one part of the slice to another part of itself, using a memmove. `src` is the range within `self` to copy from. `dest` is the starting index of the range within `self` to copy to, which will have the same length as `src`. The two ranges may overlap. The ends of the two ranges must be less than or equal to `self.len()`. ##### Panics This function will panic if either range exceeds the end of the slice, or if the end of `src` is before the start. ##### Examples Copying four bytes within a slice: ``` let mut bytes = *b"Hello, World!"; bytes.copy_within(1..5, 8); assert_eq!(&bytes, b"Hello, Wello!"); ``` 1.27.0 · source#### pub fn swap_with_slice(&mut self, other: &mut [T]) Swaps all elements in `self` with those in `other`. The length of `other` must be the same as `self`. ##### Panics This function will panic if the two slices have different lengths. ##### Example Swapping two elements across slices: ``` let mut slice1 = [0, 0]; let mut slice2 = [1, 2, 3, 4]; slice1.swap_with_slice(&mut slice2[2..]); assert_eq!(slice1, [3, 4]); assert_eq!(slice2, [1, 2, 0, 0]); ``` Rust enforces that there can only be one mutable reference to a particular piece of data in a particular scope. Because of this, attempting to use `swap_with_slice` on a single slice will result in a compile failure: ``` let mut slice = [1, 2, 3, 4, 5]; slice[..2].swap_with_slice(&mut slice[3..]); // compile fail! ``` To work around this, we can use `split_at_mut` to create two distinct mutable sub-slices from a slice: ``` let mut slice = [1, 2, 3, 4, 5]; { let (left, right) = slice.split_at_mut(2); left.swap_with_slice(&mut right[1..]); } assert_eq!(slice, [4, 5, 3, 1, 2]); ``` 1.30.0 · source#### pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) Transmute the slice to a slice of another type, ensuring alignment of the types is maintained. This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. How exactly the slice is split up is not specified; the middle part may be smaller than necessary. However, if this fails to return a maximal middle part, that is because code is running in a context where performance does not matter, such as a sanitizer attempting to find alignment bugs. Regular code running in a default (debug or release) execution *will* return a maximal middle part. This method has no purpose when either input element `T` or output element `U` are zero-sized and will return the original slice without splitting anything. ##### Safety This method is essentially a `transmute` with respect to the elements in the returned middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here. ##### Examples Basic usage: ``` unsafe { let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7]; let (prefix, shorts, suffix) = bytes.align_to::<u16>(); // less_efficient_algorithm_for_bytes(prefix); // more_efficient_algorithm_for_aligned_shorts(shorts); // less_efficient_algorithm_for_bytes(suffix); } ``` 1.30.0 · source#### pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) Transmute the mutable slice to a mutable slice of another type, ensuring alignment of the types is maintained. This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. How exactly the slice is split up is not specified; the middle part may be smaller than necessary. However, if this fails to return a maximal middle part, that is because code is running in a context where performance does not matter, such as a sanitizer attempting to find alignment bugs. Regular code running in a default (debug or release) execution *will* return a maximal middle part. This method has no purpose when either input element `T` or output element `U` are zero-sized and will return the original slice without splitting anything. ##### Safety This method is essentially a `transmute` with respect to the elements in the returned middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here. ##### Examples Basic usage: ``` unsafe { let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7]; let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>(); // less_efficient_algorithm_for_bytes(prefix); // more_efficient_algorithm_for_aligned_shorts(shorts); // less_efficient_algorithm_for_bytes(suffix); } ``` #### pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])where Simd<T, LANES>: AsRef<[T; LANES]>, T: SimdElement, LaneCount<LANES>: SupportedLaneCount, 🔬This is a nightly-only experimental API. (`portable_simd`)Split a slice into a prefix, a middle of aligned SIMD types, and a suffix. This is a safe wrapper around `slice::align_to`, so has the same weak postconditions as that method. You’re only assured that `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`. Notably, all of the following are possible: * `prefix.len() >= LANES`. * `middle.is_empty()` despite `self.len() >= 3 * LANES`. * `suffix.len() >= LANES`. That said, this is a safe method, so if you’re only writing safe code, then this can at most cause incorrect logic, not unsoundness. ##### Panics This will panic if the size of the SIMD type is different from `LANES` times that of the scalar. At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps that from ever happening, as only power-of-two numbers of lanes are supported. It’s possible that, in the future, those restrictions might be lifted in a way that would make it possible to see panics from this method for something like `LANES == 3`. ##### Examples ``` #![feature(portable_simd)] use core::simd::SimdFloat; let short = &[1, 2, 3]; let (prefix, middle, suffix) = short.as_simd::<4>(); assert_eq!(middle, []); // Not enough elements for anything in the middle // They might be split in any possible way between prefix and suffix let it = prefix.iter().chain(suffix).copied(); assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]); fn basic_simd_sum(x: &[f32]) -> f32 { use std::ops::Add; use std::simd::f32x4; let (prefix, middle, suffix) = x.as_simd(); let sums = f32x4::from_array([ prefix.iter().copied().sum(), 0.0, 0.0, suffix.iter().copied().sum(), ]); let sums = middle.iter().copied().fold(sums, f32x4::add); sums.reduce_sum() } let numbers: Vec<f32> = (1..101).map(|x| x as _).collect(); assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0); ``` #### pub fn as_simd_mut<const LANES: usize>( &mut self ) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])where Simd<T, LANES>: AsMut<[T; LANES]>, T: SimdElement, LaneCount<LANES>: SupportedLaneCount, 🔬This is a nightly-only experimental API. (`portable_simd`)Split a mutable slice into a mutable prefix, a middle of aligned SIMD types, and a mutable suffix. This is a safe wrapper around `slice::align_to_mut`, so has the same weak postconditions as that method. You’re only assured that `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`. Notably, all of the following are possible: * `prefix.len() >= LANES`. * `middle.is_empty()` despite `self.len() >= 3 * LANES`. * `suffix.len() >= LANES`. That said, this is a safe method, so if you’re only writing safe code, then this can at most cause incorrect logic, not unsoundness. This is the mutable version of `slice::as_simd`; see that for examples. ##### Panics This will panic if the size of the SIMD type is different from `LANES` times that of the scalar. At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps that from ever happening, as only power-of-two numbers of lanes are supported. It’s possible that, in the future, those restrictions might be lifted in a way that would make it possible to see panics from this method for something like `LANES == 3`. #### pub fn is_sorted(&self) -> boolwhere T: PartialOrd<T>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this slice are sorted. That is, for each element `a` and its following element `b`, `a <= b` must hold. If the slice yields exactly zero or one element, `true` is returned. Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition implies that this function returns `false` if any two consecutive items are not comparable. ##### Examples ``` #![feature(is_sorted)] let empty: [i32; 0] = []; assert!([1, 2, 2, 9].is_sorted()); assert!(![1, 3, 2, 4].is_sorted()); assert!([0].is_sorted()); assert!(empty.is_sorted()); assert!(![0.0, 1.0, f32::NAN].is_sorted()); ``` #### pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> boolwhere F: FnMut(&'a T, &'a T) -> Option<Ordering>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this slice are sorted using the given comparator function. Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare` function to determine the ordering of two elements. Apart from that, it’s equivalent to `is_sorted`; see its documentation for more information. #### pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> boolwhere F: FnMut(&'a T) -> K, K: PartialOrd<K>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this slice are sorted using the given key extraction function. Instead of comparing the slice’s elements directly, this function compares the keys of the elements, as determined by `f`. Apart from that, it’s equivalent to `is_sorted`; see its documentation for more information. ##### Examples ``` #![feature(is_sorted)] assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len())); assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs())); ``` 1.52.0 · source#### pub fn partition_point<P>(&self, pred: P) -> usizewhere P: FnMut(&T) -> bool, Returns the index of the partition point according to the given predicate (the index of the first element of the second partition). The slice is assumed to be partitioned according to the given predicate. This means that all elements for which the predicate returns true are at the start of the slice and all elements for which the predicate returns false are at the end. For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0` (all odd numbers are at the start, all even at the end). If this slice is not partitioned, the returned result is unspecified and meaningless, as this method performs a kind of binary search. See also `binary_search`, `binary_search_by`, and `binary_search_by_key`. ##### Examples ``` let v = [1, 2, 3, 3, 5, 6, 7]; let i = v.partition_point(|&x| x < 5); assert_eq!(i, 4); assert!(v[..i].iter().all(|&x| x < 5)); assert!(v[i..].iter().all(|&x| !(x < 5))); ``` If all elements of the slice match the predicate, including if the slice is empty, then the length of the slice will be returned: ``` let a = [2, 4, 8]; assert_eq!(a.partition_point(|x| x < &100), a.len()); let a: [i32; 0] = []; assert_eq!(a.partition_point(|x| x < &100), 0); ``` If you want to insert an item to a sorted vector, while maintaining sort order: ``` let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let num = 42; let idx = s.partition_point(|&x| x < num); s.insert(idx, num); assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); ``` #### pub fn take<R, 'a>(self: &mut &'a [T], range: R) -> Option<&'a [T]>where R: OneSidedRange<usize>, 🔬This is a nightly-only experimental API. (`slice_take`)Removes the subslice corresponding to the given range and returns a reference to it. Returns `None` and does not modify the slice if the given range is out of bounds. Note that this method only accepts one-sided ranges such as `2..` or `..6`, but not `2..6`. ##### Examples Taking the first three elements of a slice: ``` #![feature(slice_take)] let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut first_three = slice.take(..3).unwrap(); assert_eq!(slice, &['d']); assert_eq!(first_three, &['a', 'b', 'c']); ``` Taking the last two elements of a slice: ``` #![feature(slice_take)] let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut tail = slice.take(2..).unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(tail, &['c', 'd']); ``` Getting `None` when `range` is out of bounds: ``` #![feature(slice_take)] let mut slice: &[_] = &['a', 'b', 'c', 'd']; assert_eq!(None, slice.take(5..)); assert_eq!(None, slice.take(..5)); assert_eq!(None, slice.take(..=4)); let expected: &[char] = &['a', 'b', 'c', 'd']; assert_eq!(Some(expected), slice.take(..4)); ``` #### pub fn take_mut<R, 'a>(self: &mut &'a mut [T], range: R) -> Option<&'a mut [T]>where R: OneSidedRange<usize>, 🔬This is a nightly-only experimental API. (`slice_take`)Removes the subslice corresponding to the given range and returns a mutable reference to it. Returns `None` and does not modify the slice if the given range is out of bounds. Note that this method only accepts one-sided ranges such as `2..` or `..6`, but not `2..6`. ##### Examples Taking the first three elements of a slice: ``` #![feature(slice_take)] let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd']; let mut first_three = slice.take_mut(..3).unwrap(); assert_eq!(slice, &mut ['d']); assert_eq!(first_three, &mut ['a', 'b', 'c']); ``` Taking the last two elements of a slice: ``` #![feature(slice_take)] let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd']; let mut tail = slice.take_mut(2..).unwrap(); assert_eq!(slice, &mut ['a', 'b']); assert_eq!(tail, &mut ['c', 'd']); ``` Getting `None` when `range` is out of bounds: ``` #![feature(slice_take)] let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd']; assert_eq!(None, slice.take_mut(5..)); assert_eq!(None, slice.take_mut(..5)); assert_eq!(None, slice.take_mut(..=4)); let expected: &mut [_] = &mut ['a', 'b', 'c', 'd']; assert_eq!(Some(expected), slice.take_mut(..4)); ``` #### pub fn take_first<'a>(self: &mut &'a [T]) -> Option<&'a T🔬This is a nightly-only experimental API. (`slice_take`)Removes the first element of the slice and returns a reference to it. Returns `None` if the slice is empty. ##### Examples ``` #![feature(slice_take)] let mut slice: &[_] = &['a', 'b', 'c']; let first = slice.take_first().unwrap(); assert_eq!(slice, &['b', 'c']); assert_eq!(first, &'a'); ``` #### pub fn take_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T🔬This is a nightly-only experimental API. (`slice_take`)Removes the first element of the slice and returns a mutable reference to it. Returns `None` if the slice is empty. ##### Examples ``` #![feature(slice_take)] let mut slice: &mut [_] = &mut ['a', 'b', 'c']; let first = slice.take_first_mut().unwrap(); *first = 'd'; assert_eq!(slice, &['b', 'c']); assert_eq!(first, &'d'); ``` #### pub fn take_last<'a>(self: &mut &'a [T]) -> Option<&'a T🔬This is a nightly-only experimental API. (`slice_take`)Removes the last element of the slice and returns a reference to it. Returns `None` if the slice is empty. ##### Examples ``` #![feature(slice_take)] let mut slice: &[_] = &['a', 'b', 'c']; let last = slice.take_last().unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(last, &'c'); ``` #### pub fn take_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T🔬This is a nightly-only experimental API. (`slice_take`)Removes the last element of the slice and returns a mutable reference to it. Returns `None` if the slice is empty. ##### Examples ``` #![feature(slice_take)] let mut slice: &mut [_] = &mut ['a', 'b', 'c']; let last = slice.take_last_mut().unwrap(); *last = 'd'; assert_eq!(slice, &['a', 'b']); assert_eq!(last, &'d'); ``` #### pub unsafe fn get_many_unchecked_mut<const N: usize>( &mut self, indices: [usize; N] ) -> [&mut T; N] 🔬This is a nightly-only experimental API. (`get_many_mut`)Returns mutable references to many indices at once, without doing any checks. For a safe alternative see `get_many_mut`. ##### Safety Calling this method with overlapping or out-of-bounds indices is *undefined behavior* even if the resulting references are not used. ##### Examples ``` #![feature(get_many_mut)] let x = &mut [1, 2, 4]; unsafe { let [a, b] = x.get_many_unchecked_mut([0, 2]); *a *= 10; *b *= 100; } assert_eq!(x, &[10, 2, 400]); ``` #### pub fn get_many_mut<const N: usize>( &mut self, indices: [usize; N] ) -> Result<[&mut T; N], GetManyMutError<N>🔬This is a nightly-only experimental API. (`get_many_mut`)Returns mutable references to many indices at once. Returns an error if any index is out-of-bounds, or if the same index was passed more than once. ##### Examples ``` #![feature(get_many_mut)] let v = &mut [1, 2, 3]; if let Ok([a, b]) = v.get_many_mut([0, 2]) { *a = 413; *b = 612; } assert_eq!(v, &[413, 2, 612]); ``` #### pub fn flatten(&self) -> &[T] 🔬This is a nightly-only experimental API. (`slice_flatten`)Takes a `&[[T; N]]`, and flattens it to a `&[T]`. ##### Panics This panics if the length of the resulting slice would overflow a `usize`. This is only possible when flattening a slice of arrays of zero-sized types, and thus tends to be irrelevant in practice. If `size_of::<T>() > 0`, this will never panic. ##### Examples ``` #![feature(slice_flatten)] assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]); assert_eq!( [[1, 2, 3], [4, 5, 6]].flatten(), [[1, 2], [3, 4], [5, 6]].flatten(), ); let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []]; assert!(slice_of_empty_arrays.flatten().is_empty()); let empty_slice_of_arrays: &[[u32; 10]] = &[]; assert!(empty_slice_of_arrays.flatten().is_empty()); ``` #### pub fn flatten_mut(&mut self) -> &mut [T] 🔬This is a nightly-only experimental API. (`slice_flatten`)Takes a `&mut [[T; N]]`, and flattens it to a `&mut [T]`. ##### Panics This panics if the length of the resulting slice would overflow a `usize`. This is only possible when flattening a slice of arrays of zero-sized types, and thus tends to be irrelevant in practice. If `size_of::<T>() > 0`, this will never panic. ##### Examples ``` #![feature(slice_flatten)] fn add_5_to_all(slice: &mut [i32]) { for i in slice { *i += 5; } } let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; add_5_to_all(array.flatten_mut()); assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]); ``` #### pub fn sort_floats(&mut self) 🔬This is a nightly-only experimental API. (`sort_floats`)Sorts the slice of floats. This sort is in-place (i.e. does not allocate), *O*(*n* * log(*n*)) worst-case, and uses the ordering defined by `f64::total_cmp`. ##### Current implementation This uses the same sorting algorithm as `sort_unstable_by`. ##### Examples ``` #![feature(sort_floats)] let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0]; v.sort_floats(); let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN]; assert_eq!(&v[..8], &sorted[..8]); assert!(v[8].is_nan()); ``` 1.23.0 · source#### pub fn is_ascii(&self) -> bool Checks if all bytes in this slice are within the ASCII range. #### pub fn as_ascii(&self) -> Option<&[AsciiChar]🔬This is a nightly-only experimental API. (`ascii_char`)If this slice `is_ascii`, returns it as a slice of ASCII characters, otherwise returns `None`. #### pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar] 🔬This is a nightly-only experimental API. (`ascii_char`)Converts this slice of bytes into a slice of ASCII characters, without checking whether they’re valid. ##### Safety Every byte in the slice must be in `0..=127`, or else this is UB. 1.23.0 · source#### pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool Checks that two slices are an ASCII case-insensitive match. Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`, but without allocating and copying temporaries. 1.23.0 · source#### pub fn make_ascii_uppercase(&mut self) Converts this slice to its ASCII upper case equivalent in-place. ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged. To return a new uppercased value without modifying the existing one, use `to_ascii_uppercase`. 1.23.0 · source#### pub fn make_ascii_lowercase(&mut self) Converts this slice to its ASCII lower case equivalent in-place. ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged. To return a new lowercased value without modifying the existing one, use `to_ascii_lowercase`. 1.60.0 · source#### pub fn escape_ascii(&self) -> EscapeAscii<'_Returns an iterator that produces an escaped version of this slice, treating it as an ASCII string. ##### Examples ``` let s = b"0\t\r\n'\"\\\x9d"; let escaped = s.escape_ascii().to_string(); assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d"); ``` #### pub fn trim_ascii_start(&self) -> &[u8] 🔬This is a nightly-only experimental API. (`byte_slice_trim_ascii`)Returns a byte slice with leading ASCII whitespace bytes removed. ‘Whitespace’ refers to the definition used by `u8::is_ascii_whitespace`. ##### Examples ``` #![feature(byte_slice_trim_ascii)] assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n"); assert_eq!(b" ".trim_ascii_start(), b""); assert_eq!(b"".trim_ascii_start(), b""); ``` #### pub fn trim_ascii_end(&self) -> &[u8] 🔬This is a nightly-only experimental API. (`byte_slice_trim_ascii`)Returns a byte slice with trailing ASCII whitespace bytes removed. ‘Whitespace’ refers to the definition used by `u8::is_ascii_whitespace`. ##### Examples ``` #![feature(byte_slice_trim_ascii)] assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world"); assert_eq!(b" ".trim_ascii_end(), b""); assert_eq!(b"".trim_ascii_end(), b""); ``` #### pub fn trim_ascii(&self) -> &[u8] 🔬This is a nightly-only experimental API. (`byte_slice_trim_ascii`)Returns a byte slice with leading and trailing ASCII whitespace bytes removed. ‘Whitespace’ refers to the definition used by `u8::is_ascii_whitespace`. ##### Examples ``` #![feature(byte_slice_trim_ascii)] assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world"); assert_eq!(b" ".trim_ascii(), b""); assert_eq!(b"".trim_ascii(), b""); ``` #### pub fn sort_floats(&mut self) 🔬This is a nightly-only experimental API. (`sort_floats`)Sorts the slice of floats. This sort is in-place (i.e. does not allocate), *O*(*n* * log(*n*)) worst-case, and uses the ordering defined by `f32::total_cmp`. ##### Current implementation This uses the same sorting algorithm as `sort_unstable_by`. ##### Examples ``` #![feature(sort_floats)] let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0]; v.sort_floats(); let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN]; assert_eq!(&v[..8], &sorted[..8]); assert!(v[8].is_nan()); ``` #### pub fn as_str(&self) -> &str 🔬This is a nightly-only experimental API. (`ascii_char`)Views this slice of ASCII characters as a UTF-8 `str`. #### pub fn as_bytes(&self) -> &[u8] 🔬This is a nightly-only experimental API. (`ascii_char`)Views this slice of ASCII characters as a slice of `u8` bytes. 1.0.0 · source#### pub fn sort(&mut self)where T: Ord, Sorts the slice. This sort is stable (i.e., does not reorder equal elements) and *O*(*n* * log(*n*)) worst-case. When applicable, unstable sorting is preferred because it is generally faster than stable sorting and it doesn’t allocate auxiliary memory. See `sort_unstable`. ##### Current implementation The current algorithm is an adaptive, iterative merge sort inspired by timsort. It is designed to be very fast in cases where the slice is nearly sorted, or consists of two or more sorted sequences concatenated one after another. Also, it allocates temporary storage half the size of `self`, but for short slices a non-allocating insertion sort is used instead. ##### Examples ``` let mut v = [-5, 4, 1, -3, 2]; v.sort(); assert!(v == [-5, -3, 1, 2, 4]); ``` 1.0.0 · source#### pub fn sort_by<F>(&mut self, compare: F)where F: FnMut(&T, &T) -> Ordering, Sorts the slice with a comparator function. This sort is stable (i.e., does not reorder equal elements) and *O*(*n* * log(*n*)) worst-case. The comparator function must define a total ordering for the elements in the slice. If the ordering is not total, the order of the elements is unspecified. An order is a total order if it is (for all `a`, `b` and `c`): * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`. For example, while `f64` doesn’t implement `Ord` because `NaN != NaN`, we can use `partial_cmp` as our sort function when we know the slice doesn’t contain a `NaN`. ``` let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0]; floats.sort_by(|a, b| a.partial_cmp(b).unwrap()); assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]); ``` When applicable, unstable sorting is preferred because it is generally faster than stable sorting and it doesn’t allocate auxiliary memory. See `sort_unstable_by`. ##### Current implementation The current algorithm is an adaptive, iterative merge sort inspired by timsort. It is designed to be very fast in cases where the slice is nearly sorted, or consists of two or more sorted sequences concatenated one after another. Also, it allocates temporary storage half the size of `self`, but for short slices a non-allocating insertion sort is used instead. ##### Examples ``` let mut v = [5, 4, 1, 3, 2]; v.sort_by(|a, b| a.cmp(b)); assert!(v == [1, 2, 3, 4, 5]); // reverse sorting v.sort_by(|a, b| b.cmp(a)); assert!(v == [5, 4, 3, 2, 1]); ``` 1.7.0 · source#### pub fn sort_by_key<K, F>(&mut self, f: F)where F: FnMut(&T) -> K, K: Ord, Sorts the slice with a key extraction function. This sort is stable (i.e., does not reorder equal elements) and *O*(*m* * *n* * log(*n*)) worst-case, where the key function is *O*(*m*). For expensive key functions (e.g. functions that are not simple property accesses or basic operations), `sort_by_cached_key` is likely to be significantly faster, as it does not recompute element keys. When applicable, unstable sorting is preferred because it is generally faster than stable sorting and it doesn’t allocate auxiliary memory. See `sort_unstable_by_key`. ##### Current implementation The current algorithm is an adaptive, iterative merge sort inspired by timsort. It is designed to be very fast in cases where the slice is nearly sorted, or consists of two or more sorted sequences concatenated one after another. Also, it allocates temporary storage half the size of `self`, but for short slices a non-allocating insertion sort is used instead. ##### Examples ``` let mut v = [-5i32, 4, 1, -3, 2]; v.sort_by_key(|k| k.abs()); assert!(v == [1, 2, -3, 4, -5]); ``` 1.34.0 · source#### pub fn sort_by_cached_key<K, F>(&mut self, f: F)where F: FnMut(&T) -> K, K: Ord, Sorts the slice with a key extraction function. During sorting, the key function is called at most once per element, by using temporary storage to remember the results of key evaluation. The order of calls to the key function is unspecified and may change in future versions of the standard library. This sort is stable (i.e., does not reorder equal elements) and *O*(*m* * *n* + *n* * log(*n*)) worst-case, where the key function is *O*(*m*). For simple key functions (e.g., functions that are property accesses or basic operations), `sort_by_key` is likely to be faster. ##### Current implementation The current algorithm is based on pattern-defeating quicksort by <NAME>, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior. In the worst case, the algorithm allocates temporary storage in a `Vec<(K, usize)>` the length of the slice. ##### Examples ``` let mut v = [-5i32, 4, 32, -3, 2]; v.sort_by_cached_key(|k| k.to_string()); assert!(v == [-3, -5, 2, 32, 4]); ``` 1.0.0 · source#### pub fn to_vec(&self) -> Vec<T, Global>where T: Clone, Copies `self` into a new `Vec`. ##### Examples ``` let s = [10, 40, 30]; let x = s.to_vec(); // Here, `s` and `x` can be modified independently. ``` #### pub fn to_vec_in<A>(&self, alloc: A) -> Vec<T, A>where A: Allocator, T: Clone, 🔬This is a nightly-only experimental API. (`allocator_api`)Copies `self` into a new `Vec` with an allocator. ##### Examples ``` #![feature(allocator_api)] use std::alloc::System; let s = [10, 40, 30]; let x = s.to_vec_in(System); // Here, `s` and `x` can be modified independently. ``` 1.40.0 · source#### pub fn repeat(&self, n: usize) -> Vec<T, Global>where T: Copy, Creates a vector by copying a slice `n` times. ##### Panics This function will panic if the capacity would overflow. ##### Examples Basic usage: ``` assert_eq!([1, 2].repeat(3), vec![1, 2, 1, 2, 1, 2]); ``` A panic upon overflow: ``` // this will panic at runtime b"0123456789abcdef".repeat(usize::MAX); ``` 1.0.0 · source#### pub fn concat<Item>(&self) -> <[T] as Concat<Item>>::Output where [T]: Concat<Item>, Item: ?Sized, Flattens a slice of `T` into a single value `Self::Output`. ##### Examples ``` assert_eq!(["hello", "world"].concat(), "helloworld"); assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]); ``` 1.3.0 · source#### pub fn join<Separator>( &self, sep: Separator ) -> <[T] as Join<Separator>>::Output where [T]: Join<Separator>, Flattens a slice of `T` into a single value `Self::Output`, placing a given separator between each. ##### Examples ``` assert_eq!(["hello", "world"].join(" "), "hello world"); assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]); assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]); ``` 1.0.0 · source#### pub fn connect<Separator>( &self, sep: Separator ) -> <[T] as Join<Separator>>::Output where [T]: Join<Separator>, 👎Deprecated since 1.3.0: renamed to joinFlattens a slice of `T` into a single value `Self::Output`, placing a given separator between each. ##### Examples ``` assert_eq!(["hello", "world"].connect(" "), "hello world"); assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]); ``` 1.23.0 · source#### pub fn to_ascii_uppercase(&self) -> Vec<u8, GlobalReturns a vector containing a copy of this slice where each byte is mapped to its ASCII upper case equivalent. ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged. To uppercase the value in-place, use `make_ascii_uppercase`. 1.23.0 · source#### pub fn to_ascii_lowercase(&self) -> Vec<u8, GlobalReturns a vector containing a copy of this slice where each byte is mapped to its ASCII lower case equivalent. ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged. To lowercase the value in-place, use `make_ascii_lowercase`. Trait Implementations --- ### impl<T: Clone + ReprC> Clone for Vec<T#### fn clone(&self) -> Self Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. The resulting type after dereferencing.#### fn deref(self: &Vec<T>) -> &[T] Dereferences the value.### impl<T> DerefMut for Vec<T#### fn deref_mut(self: &mut Vec<T>) -> &mut [T] Mutably dereferences the value.### impl<T> Drop for Vec<T#### fn drop(self: &mut Vec<T>) Executes the destructor for this type. #### fn from(value: Vec<T>) -> Vec<TConverts to this type from the input type.### impl<T> From<Vec<T, Global>> for Vec<TConvert a `std::vec::Vec` to a `safer_ffi::Vec`. #### fn from(vec: Vec<T>) -> Vec<TConverts to this type from the input type.### impl<T> ReprC for Vec<T>where T: ReprC, NonNullOwned<T>: ConcreteReprC, usize: ConcreteReprC, #### type CLayout = Vec_Layout<TThe `CType` having the same layout as `Self`.#### fn is_valid(_it: &Self::CLayout) -> bool Sanity checks that can be performed on an instance of the `CType` layout. Vec<T>: Send, ### impl<T> Sync for Vec<T>where Vec<T>: Sync, Auto Trait Implementations --- ### impl<T> RefUnwindSafe for Vec<T>where T: RefUnwindSafe, ### impl<T> Unpin for Vec<T>where T: Unpin, ### impl<T> UnwindSafe for Vec<T>where T: UnwindSafe + RefUnwindSafe, Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn compat(self) -> Compat<TApplies the `Compat` adapter by value. #### type CBoxWrapped = Box_<TAvailable on **crate feature `alloc`** only.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ManuallyDropMut for T #### type Ret = ManuallyDrop<T#### fn manually_drop_mut<'__>(&'__ mut self) -> &'__ mut ManuallyDrop<T### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> UpcastAny for Twhere T: 'static, #### fn upcast_any(&self) -> &(dyn Any + 'static) Available on **crate feature `headers`** only.{"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","<[T] as Concat<Item>>::Output":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","<[T] as Join<Separator>>::Output":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","ArrayChunks<'_, T, N>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ArrayChunks.html\" title=\"struct core::slice::iter::ArrayChunks\">ArrayChunks</a>&lt;'a, T, N&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, const N: <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ArrayChunks.html\" title=\"struct core::slice::iter::ArrayChunks\">ArrayChunks</a>&lt;'a, T, N&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.array.html\">[T; N]</a>;</span>","ArrayChunksMut<'_, T, N>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ArrayChunksMut.html\" title=\"struct core::slice::iter::ArrayChunksMut\">ArrayChunksMut</a>&lt;'a, T, N&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, const N: <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ArrayChunksMut.html\" title=\"struct core::slice::iter::ArrayChunksMut\">ArrayChunksMut</a>&lt;'a, T, N&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a mut <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.array.html\">[T; N]</a>;</span>","ArrayWindows<'_, T, N>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ArrayWindows.html\" title=\"struct core::slice::iter::ArrayWindows\">ArrayWindows</a>&lt;'a, T, N&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, const N: <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ArrayWindows.html\" title=\"struct core::slice::iter::ArrayWindows\">ArrayWindows</a>&lt;'a, T, N&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.array.html\">[T; N]</a>;</span>","Chunks<'_, T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.Chunks.html\" title=\"struct core::slice::iter::Chunks\">Chunks</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.Chunks.html\" title=\"struct core::slice::iter::Chunks\">Chunks</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","ChunksExact<'_, T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ChunksExact.html\" title=\"struct core::slice::iter::ChunksExact\">ChunksExact</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ChunksExact.html\" title=\"struct core::slice::iter::ChunksExact\">ChunksExact</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","ChunksExactMut<'_, T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ChunksExactMut.html\" title=\"struct core::slice::iter::ChunksExactMut\">ChunksExactMut</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ChunksExactMut.html\" title=\"struct core::slice::iter::ChunksExactMut\">ChunksExactMut</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a mut <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","ChunksMut<'_, T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ChunksMut.html\" title=\"struct core::slice::iter::ChunksMut\">ChunksMut</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.ChunksMut.html\" title=\"struct core::slice::iter::ChunksMut\">ChunksMut</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a mut <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","Compat<&T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","Compat<&mut T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","Compat<T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","EscapeAscii<'_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/ascii/struct.EscapeAscii.html\" title=\"struct core::slice::ascii::EscapeAscii\">EscapeAscii</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/ascii/struct.EscapeAscii.html\" title=\"struct core::slice::ascii::EscapeAscii\">EscapeAscii</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>;</span>","GroupBy<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.GroupBy.html\" title=\"struct core::slice::iter::GroupBy\">GroupBy</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.GroupBy.html\" title=\"struct core::slice::iter::GroupBy\">GroupBy</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n T: 'a,\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>, <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","GroupByMut<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.GroupByMut.html\" title=\"struct core::slice::iter::GroupByMut\">GroupByMut</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.GroupByMut.html\" title=\"struct core::slice::iter::GroupByMut\">GroupByMut</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n T: 'a,\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>, <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a mut <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","Iter<'_, T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.Iter.html\" title=\"struct core::slice::iter::Iter\">Iter</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.Iter.html\" title=\"struct core::slice::iter::Iter\">Iter</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a T</a>;</span>","IterMut<'_, T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.IterMut.html\" title=\"struct core::slice::iter::IterMut\">IterMut</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.IterMut.html\" title=\"struct core::slice::iter::IterMut\">IterMut</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a mut T</a>;</span>","RChunks<'_, T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RChunks.html\" title=\"struct core::slice::iter::RChunks\">RChunks</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RChunks.html\" title=\"struct core::slice::iter::RChunks\">RChunks</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","RChunksExact<'_, T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RChunksExact.html\" title=\"struct core::slice::iter::RChunksExact\">RChunksExact</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RChunksExact.html\" title=\"struct core::slice::iter::RChunksExact\">RChunksExact</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","RChunksExactMut<'_, T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RChunksExactMut.html\" title=\"struct core::slice::iter::RChunksExactMut\">RChunksExactMut</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RChunksExactMut.html\" title=\"struct core::slice::iter::RChunksExactMut\">RChunksExactMut</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a mut <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","RChunksMut<'_, T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RChunksMut.html\" title=\"struct core::slice::iter::RChunksMut\">RChunksMut</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RChunksMut.html\" title=\"struct core::slice::iter::RChunksMut\">RChunksMut</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a mut <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","RSplit<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RSplit.html\" title=\"struct core::slice::iter::RSplit\">RSplit</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RSplit.html\" title=\"struct core::slice::iter::RSplit\">RSplit</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","RSplitMut<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RSplitMut.html\" title=\"struct core::slice::iter::RSplitMut\">RSplitMut</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RSplitMut.html\" title=\"struct core::slice::iter::RSplitMut\">RSplitMut</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a mut <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","RSplitN<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RSplitN.html\" title=\"struct core::slice::iter::RSplitN\">RSplitN</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RSplitN.html\" title=\"struct core::slice::iter::RSplitN\">RSplitN</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","RSplitNMut<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RSplitNMut.html\" title=\"struct core::slice::iter::RSplitNMut\">RSplitNMut</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.RSplitNMut.html\" title=\"struct core::slice::iter::RSplitNMut\">RSplitNMut</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a mut <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","Range<*const T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/ops/range/struct.Range.html\" title=\"struct core::ops::range::Range\">Range</a>&lt;A&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/ops/range/struct.Range.html\" title=\"struct core::ops::range::Range\">Range</a>&lt;A&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/range/trait.Step.html\" title=\"trait core::iter::range::Step\">Step</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = A;</span>","Range<*mut T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/ops/range/struct.Range.html\" title=\"struct core::ops::range::Range\">Range</a>&lt;A&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/ops/range/struct.Range.html\" title=\"struct core::ops::range::Range\">Range</a>&lt;A&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/range/trait.Step.html\" title=\"trait core::iter::range::Step\">Step</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = A;</span>","Split<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.Split.html\" title=\"struct core::slice::iter::Split\">Split</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.Split.html\" title=\"struct core::slice::iter::Split\">Split</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","SplitInclusive<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.SplitInclusive.html\" title=\"struct core::slice::iter::SplitInclusive\">SplitInclusive</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.SplitInclusive.html\" title=\"struct core::slice::iter::SplitInclusive\">SplitInclusive</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","SplitInclusiveMut<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.SplitInclusiveMut.html\" title=\"struct core::slice::iter::SplitInclusiveMut\">SplitInclusiveMut</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.SplitInclusiveMut.html\" title=\"struct core::slice::iter::SplitInclusiveMut\">SplitInclusiveMut</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a mut <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","SplitMut<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.SplitMut.html\" title=\"struct core::slice::iter::SplitMut\">SplitMut</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.SplitMut.html\" title=\"struct core::slice::iter::SplitMut\">SplitMut</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a mut <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","SplitN<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.SplitN.html\" title=\"struct core::slice::iter::SplitN\">SplitN</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.SplitN.html\" title=\"struct core::slice::iter::SplitN\">SplitN</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","SplitNMut<'_, T, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.SplitNMut.html\" title=\"struct core::slice::iter::SplitNMut\">SplitNMut</a>&lt;'a, T, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T, P&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.SplitNMut.html\" title=\"struct core::slice::iter::SplitNMut\">SplitNMut</a>&lt;'a, T, P&gt;<span class=\"where fmt-newline\">where\n P: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/ops/function/trait.FnMut.html\" title=\"trait core::ops::function::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;T</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a mut <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>","Vec<u8, Global>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html\" title=\"struct alloc::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html\" title=\"struct alloc::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/alloc/trait.Allocator.html\" title=\"trait core::alloc::Allocator\">Allocator</a>,</span></span>","Windows<'_, T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.Windows.html\" title=\"struct core::slice::iter::Windows\">Windows</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/slice/iter/struct.Windows.html\" title=\"struct core::slice::iter::Windows\">Windows</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &amp;'a <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.slice.html\">[T]</a>;</span>"} Struct safer_ffi::c_char === ``` pub struct c_char(pub u8); ``` A `ReprC` *standalone* type with the same layout and ABI as `::libc::c_char`. By *standalone*, the idea is that this is defined as a (`transparent`) *newtype* `struct`, rather than as a *`type` alias*, which is error-prone and yields less-portable headers (since the header generation will resolve the type alias and emit, for instance, `int8_t`, ⚠️). By using this type, you guarantee that the C `char` type be used in the headers. Tuple Fields --- `0: u8`Trait Implementations --- ### impl Clone for c_char #### fn clone(&self) -> c_char Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> c_char Returns the “default value” for a type. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result A short-name description of the type, mainly used to fill “placeholders” such as when monomorphising generics structs or arrays. The core method of the trait: it provides the implementation to be used by [`CType::c_var`], by bringing a `Formatter` in scope. Type name (*e.g.*, `int`, `string`, `IntPtr`)#### type OPAQUE_KIND = Concrete #### fn c_short_name() -> ImplDisplay<SelfConvenience function for *callers* / users of types implementing `CType`. `CType`. `[MarshalAs(UnmanagedType.FunctionPtr)]`)#### fn csharp_var(var_name: &str) -> String Convenience function for formatting `{ty} {var}` in CSharp.### impl Ord for c_char #### fn cmp(&self, other: &c_char) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &c_char) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<c_char> for c_char #### fn partial_cmp(&self, other: &c_char) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### type CLayout = c_char The `CType` having the same layout as `Self`.#### fn is_valid(_: &Self::CLayout) -> bool Sanity checks that can be performed on an instance of the `CType` layout. ### impl Eq for c_char ### impl StructuralEq for c_char ### impl StructuralPartialEq for c_char Auto Trait Implementations --- ### impl RefUnwindSafe for c_char ### impl Send for c_char ### impl Sync for c_char ### impl Unpin for c_char ### impl UnwindSafe for c_char Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: Copy, #### fn as_out<'out>(&'out mut self) -> Out<'out, T### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: LegacyCType, #### type OPAQUE_KIND = <T as LegacyCType>::OPAQUE_KIND #### fn short_name() -> String #### fn define_self__impl( _: &(dyn HeaderLanguage + 'static), _: &mut dyn Definer ) -> Result<(), Error#### fn define_self( language: &(dyn HeaderLanguage + 'static), definer: &mut dyn Definer ) -> Result<(), Error#### fn name(language: &(dyn HeaderLanguage + 'static)) -> String #### fn name_wrapping_var( language: &(dyn HeaderLanguage + 'static), var_name: &str ) -> String #### fn csharp_marshaler() -> Option<StringOptional marshaler attached to the type (*e.g.*, `[MarshalAs(UnmanagedType.FunctionPtr)]`)#### fn zeroed() -> Self ### impl<T> CompatExt for T #### fn compat(self) -> Compat<TApplies the `Compat` adapter by value. <T as ReprC>::CLayout: CType<OPAQUE_KIND = Concrete>, T: ReprC + ?Sized, #### type ConcreteCLayout = <T as ReprC>::CLayout ### impl<T> FitForCBox for T #### type CBoxWrapped = Box_<TAvailable on **crate feature `alloc`** only.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ManuallyDropMut for T #### type Ret = ManuallyDrop<T#### fn manually_drop_mut<'__>(&'__ mut self) -> &'__ mut ManuallyDrop<T### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> UpcastAny for Twhere T: 'static, #### fn upcast_any(&self) -> &(dyn Any + 'static) Available on **crate feature `headers`** only.{"Compat<&T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","Compat<&mut T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","Compat<T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>"} Type Alias safer_ffi::libc::c_char === ``` pub type c_char = c_char; ``` A *`type` alias* to `::libc::c_char`. Note: you should probably be using `crate::c_char` instead. Trait Implementations --- 1.0.0 · source### impl Add<&i8> for i8 #### type Output = <i8 as Add<i8>>::Output The resulting type after applying the `+` operator.#### fn add(self, other: &i8) -> <i8 as Add<i8>>::Output Performs the `+` operation. Read more1.0.0 · source### impl Add<i8> for i8 #### type Output = i8 The resulting type after applying the `+` operator.#### fn add(self, other: i8) -> i8 Performs the `+` operation. Read more1.22.0 · source### impl AddAssign<&i8> for i8 #### fn add_assign(&mut self, other: &i8) Performs the `+=` operation. Read more1.8.0 · source### impl AddAssign<i8> for i8 #### fn add_assign(&mut self, other: i8) Performs the `+=` operation. Read more1.0.0 · source### impl Binary for i8 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl BitAnd<&i8> for i8 #### type Output = <i8 as BitAnd<i8>>::Output The resulting type after applying the `&` operator.#### fn bitand(self, other: &i8) -> <i8 as BitAnd<i8>>::Output Performs the `&` operation. Read more1.0.0 · source### impl BitAnd<i8> for i8 #### type Output = i8 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: i8) -> i8 Performs the `&` operation. Read more1.22.0 · source### impl BitAndAssign<&i8> for i8 #### fn bitand_assign(&mut self, other: &i8) Performs the `&=` operation. Read more1.8.0 · source### impl BitAndAssign<i8> for i8 #### fn bitand_assign(&mut self, other: i8) Performs the `&=` operation. Read more1.0.0 · source### impl BitOr<&i8> for i8 #### type Output = <i8 as BitOr<i8>>::Output The resulting type after applying the `|` operator.#### fn bitor(self, other: &i8) -> <i8 as BitOr<i8>>::Output Performs the `|` operation. Read more1.45.0 · source### impl BitOr<NonZeroI8> for i8 #### type Output = NonZeroI8 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: NonZeroI8) -> <i8 as BitOr<NonZeroI8>>::Output Performs the `|` operation. Read more1.0.0 · source### impl BitOr<i8> for i8 #### type Output = i8 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: i8) -> i8 Performs the `|` operation. Read more1.22.0 · source### impl BitOrAssign<&i8> for i8 #### fn bitor_assign(&mut self, other: &i8) Performs the `|=` operation. Read more1.8.0 · source### impl BitOrAssign<i8> for i8 #### fn bitor_assign(&mut self, other: i8) Performs the `|=` operation. Read more1.0.0 · source### impl BitXor<&i8> for i8 #### type Output = <i8 as BitXor<i8>>::Output The resulting type after applying the `^` operator.#### fn bitxor(self, other: &i8) -> <i8 as BitXor<i8>>::Output Performs the `^` operation. Read more1.0.0 · source### impl BitXor<i8> for i8 #### type Output = i8 The resulting type after applying the `^` operator.#### fn bitxor(self, other: i8) -> i8 Performs the `^` operation. Read more1.22.0 · source### impl BitXorAssign<&i8> for i8 #### fn bitxor_assign(&mut self, other: &i8) Performs the `^=` operation. Read more1.8.0 · source### impl BitXorAssign<i8> for i8 #### fn bitxor_assign(&mut self, other: i8) Performs the `^=` operation. Read more1.0.0 · source### impl Clone for i8 #### fn clone(&self) -> i8 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more1.0.0 · source### impl Debug for i8 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. Read more1.0.0 · source### impl Default for i8 #### fn default() -> i8 Returns the default value of `0` 1.0.0 · source### impl Display for i8 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. Read more1.0.0 · source### impl Div<&i8> for i8 #### type Output = <i8 as Div<i8>>::Output The resulting type after applying the `/` operator.#### fn div(self, other: &i8) -> <i8 as Div<i8>>::Output Performs the `/` operation. Read more1.0.0 · source### impl Div<i8> for i8 This operation rounds towards zero, truncating any fractional part of the exact result. #### Panics This operation will panic if `other == 0` or the division results in overflow. #### type Output = i8 The resulting type after applying the `/` operator.#### fn div(self, other: i8) -> i8 Performs the `/` operation. Read more1.22.0 · source### impl DivAssign<&i8> for i8 #### fn div_assign(&mut self, other: &i8) Performs the `/=` operation. Read more1.8.0 · source### impl DivAssign<i8> for i8 #### fn div_assign(&mut self, other: i8) Performs the `/=` operation. Read more1.31.0 · source### impl From<NonZeroI8> for i8 #### fn from(nonzero: NonZeroI8) -> i8 Converts a `NonZeroI8` into an `i8` 1.28.0 · source### impl From<bool> for i8 #### fn from(small: bool) -> i8 Converts a `bool` to a `i8`. The resulting value is `0` for `false` and `1` for `true` values. ##### Examples ``` assert_eq!(i8::from(true), 1); assert_eq!(i8::from(false), 0); ``` 1.0.0 · source### impl Hash for i8 #### fn hash<H>(&self, state: &mut H)where H: Hasher, Feeds this value into the given `Hasher`. H: Hasher, Feeds a slice of this type into the given `Hasher`. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result A short-name description of the type, mainly used to fill “placeholders” such as when monomorphising generics structs or arrays. The core method of the trait: it provides the implementation to be used by [`CType::c_var`], by bringing a `Formatter` in scope. Type name (*e.g.*, `int`, `string`, `IntPtr`)#### type OPAQUE_KIND = Concrete #### fn c_short_name() -> ImplDisplay<SelfConvenience function for *callers* / users of types implementing `CType`. `CType`. `[MarshalAs(UnmanagedType.FunctionPtr)]`)#### fn csharp_var(var_name: &str) -> String Convenience function for formatting `{ty} {var}` in CSharp.1.42.0 · source### impl LowerExp for i8 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl LowerHex for i8 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl Mul<&i8> for i8 #### type Output = <i8 as Mul<i8>>::Output The resulting type after applying the `*` operator.#### fn mul(self, other: &i8) -> <i8 as Mul<i8>>::Output Performs the `*` operation. Read more1.0.0 · source### impl Mul<i8> for i8 #### type Output = i8 The resulting type after applying the `*` operator.#### fn mul(self, other: i8) -> i8 Performs the `*` operation. Read more1.22.0 · source### impl MulAssign<&i8> for i8 #### fn mul_assign(&mut self, other: &i8) Performs the `*=` operation. Read more1.8.0 · source### impl MulAssign<i8> for i8 #### fn mul_assign(&mut self, other: i8) Performs the `*=` operation. Read more1.0.0 · source### impl Neg for i8 #### type Output = i8 The resulting type after applying the `-` operator.#### fn neg(self) -> i8 Performs the unary `-` operation. Read more1.0.0 · source### impl Not for i8 #### type Output = i8 The resulting type after applying the `!` operator.#### fn not(self) -> i8 Performs the unary `!` operation. Read more1.0.0 · source### impl Octal for i8 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl Ord for i8 #### fn cmp(&self, other: &i8) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. Read more1.0.0 · source### impl PartialEq<i8> for i8 #### fn eq(&self, other: &i8) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.#### fn ne(&self, other: &i8) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.1.0.0 · source### impl PartialOrd<i8> for i8 #### fn partial_cmp(&self, other: &i8) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. This method tests less than (for `self` and `other`) and is used by the `<` operator. This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.12.0 · source### impl<'a> Product<&'a i8> for i8 #### fn product<I>(iter: I) -> i8where I: Iterator<Item = &'a i8>, Method which takes an iterator and generates `Self` from the elements by multiplying the items.1.12.0 · source### impl Product<i8> for i8 #### fn product<I>(iter: I) -> i8where I: Iterator<Item = i8>, Method which takes an iterator and generates `Self` from the elements by multiplying the items.1.0.0 · source### impl Rem<&i8> for i8 #### type Output = <i8 as Rem<i8>>::Output The resulting type after applying the `%` operator.#### fn rem(self, other: &i8) -> <i8 as Rem<i8>>::Output Performs the `%` operation. Read more1.0.0 · source### impl Rem<i8> for i8 This operation satisfies `n % d == n - (n / d) * d`. The result has the same sign as the left operand. #### Panics This operation will panic if `other == 0` or if `self / other` results in overflow. #### type Output = i8 The resulting type after applying the `%` operator.#### fn rem(self, other: i8) -> i8 Performs the `%` operation. Read more1.22.0 · source### impl RemAssign<&i8> for i8 #### fn rem_assign(&mut self, other: &i8) Performs the `%=` operation. Read more1.8.0 · source### impl RemAssign<i8> for i8 #### fn rem_assign(&mut self, other: i8) Performs the `%=` operation. #### type CLayout = i8 The `CType` having the same layout as `Self`.#### fn is_valid(_: &Self::CLayout) -> bool Sanity checks that can be performed on an instance of the `CType` layout. Read more1.0.0 · source### impl Shl<&i128> for i8 #### type Output = <i8 as Shl<i128>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i128) -> <i8 as Shl<i128>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i16> for i8 #### type Output = <i8 as Shl<i16>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i16) -> <i8 as Shl<i16>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i32> for i8 #### type Output = <i8 as Shl<i32>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i32) -> <i8 as Shl<i32>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i64> for i8 #### type Output = <i8 as Shl<i64>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i64) -> <i8 as Shl<i64>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i8> for i8 #### type Output = <i8 as Shl<i8>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i8) -> <i8 as Shl<i8>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&isize> for i8 #### type Output = <i8 as Shl<isize>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &isize) -> <i8 as Shl<isize>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u128> for i8 #### type Output = <i8 as Shl<u128>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u128) -> <i8 as Shl<u128>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u16> for i8 #### type Output = <i8 as Shl<u16>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u16) -> <i8 as Shl<u16>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u32> for i8 #### type Output = <i8 as Shl<u32>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u32) -> <i8 as Shl<u32>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u64> for i8 #### type Output = <i8 as Shl<u64>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u64) -> <i8 as Shl<u64>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u8> for i8 #### type Output = <i8 as Shl<u8>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u8) -> <i8 as Shl<u8>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&usize> for i8 #### type Output = <i8 as Shl<usize>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &usize) -> <i8 as Shl<usize>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i128> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: i128) -> i8 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i16> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: i16) -> i8 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i32> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: i32) -> i8 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i64> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: i64) -> i8 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i8> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: i8) -> i8 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<isize> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: isize) -> i8 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u128> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: u128) -> i8 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u16> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: u16) -> i8 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u32> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: u32) -> i8 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u64> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: u64) -> i8 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u8> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: u8) -> i8 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<usize> for i8 #### type Output = i8 The resulting type after applying the `<<` operator.#### fn shl(self, other: usize) -> i8 Performs the `<<` operation. Read more1.22.0 · source### impl ShlAssign<&i128> for i8 #### fn shl_assign(&mut self, other: &i128) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i16> for i8 #### fn shl_assign(&mut self, other: &i16) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i32> for i8 #### fn shl_assign(&mut self, other: &i32) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i64> for i8 #### fn shl_assign(&mut self, other: &i64) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i8> for i8 #### fn shl_assign(&mut self, other: &i8) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&isize> for i8 #### fn shl_assign(&mut self, other: &isize) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u128> for i8 #### fn shl_assign(&mut self, other: &u128) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u16> for i8 #### fn shl_assign(&mut self, other: &u16) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u32> for i8 #### fn shl_assign(&mut self, other: &u32) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u64> for i8 #### fn shl_assign(&mut self, other: &u64) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u8> for i8 #### fn shl_assign(&mut self, other: &u8) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&usize> for i8 #### fn shl_assign(&mut self, other: &usize) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i128> for i8 #### fn shl_assign(&mut self, other: i128) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i16> for i8 #### fn shl_assign(&mut self, other: i16) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i32> for i8 #### fn shl_assign(&mut self, other: i32) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i64> for i8 #### fn shl_assign(&mut self, other: i64) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i8> for i8 #### fn shl_assign(&mut self, other: i8) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<isize> for i8 #### fn shl_assign(&mut self, other: isize) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u128> for i8 #### fn shl_assign(&mut self, other: u128) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u16> for i8 #### fn shl_assign(&mut self, other: u16) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u32> for i8 #### fn shl_assign(&mut self, other: u32) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u64> for i8 #### fn shl_assign(&mut self, other: u64) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u8> for i8 #### fn shl_assign(&mut self, other: u8) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<usize> for i8 #### fn shl_assign(&mut self, other: usize) Performs the `<<=` operation. Read more1.0.0 · source### impl Shr<&i128> for i8 #### type Output = <i8 as Shr<i128>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i128) -> <i8 as Shr<i128>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i16> for i8 #### type Output = <i8 as Shr<i16>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i16) -> <i8 as Shr<i16>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i32> for i8 #### type Output = <i8 as Shr<i32>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i32) -> <i8 as Shr<i32>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i64> for i8 #### type Output = <i8 as Shr<i64>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i64) -> <i8 as Shr<i64>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i8> for i8 #### type Output = <i8 as Shr<i8>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i8) -> <i8 as Shr<i8>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&isize> for i8 #### type Output = <i8 as Shr<isize>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &isize) -> <i8 as Shr<isize>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u128> for i8 #### type Output = <i8 as Shr<u128>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u128) -> <i8 as Shr<u128>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u16> for i8 #### type Output = <i8 as Shr<u16>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u16) -> <i8 as Shr<u16>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u32> for i8 #### type Output = <i8 as Shr<u32>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u32) -> <i8 as Shr<u32>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u64> for i8 #### type Output = <i8 as Shr<u64>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u64) -> <i8 as Shr<u64>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u8> for i8 #### type Output = <i8 as Shr<u8>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u8) -> <i8 as Shr<u8>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&usize> for i8 #### type Output = <i8 as Shr<usize>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &usize) -> <i8 as Shr<usize>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i128> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: i128) -> i8 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i16> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: i16) -> i8 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i32> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: i32) -> i8 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i64> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: i64) -> i8 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i8> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: i8) -> i8 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<isize> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: isize) -> i8 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u128> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: u128) -> i8 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u16> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: u16) -> i8 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u32> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: u32) -> i8 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u64> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: u64) -> i8 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u8> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: u8) -> i8 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<usize> for i8 #### type Output = i8 The resulting type after applying the `>>` operator.#### fn shr(self, other: usize) -> i8 Performs the `>>` operation. Read more1.22.0 · source### impl ShrAssign<&i128> for i8 #### fn shr_assign(&mut self, other: &i128) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i16> for i8 #### fn shr_assign(&mut self, other: &i16) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i32> for i8 #### fn shr_assign(&mut self, other: &i32) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i64> for i8 #### fn shr_assign(&mut self, other: &i64) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i8> for i8 #### fn shr_assign(&mut self, other: &i8) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&isize> for i8 #### fn shr_assign(&mut self, other: &isize) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u128> for i8 #### fn shr_assign(&mut self, other: &u128) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u16> for i8 #### fn shr_assign(&mut self, other: &u16) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u32> for i8 #### fn shr_assign(&mut self, other: &u32) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u64> for i8 #### fn shr_assign(&mut self, other: &u64) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u8> for i8 #### fn shr_assign(&mut self, other: &u8) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&usize> for i8 #### fn shr_assign(&mut self, other: &usize) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i128> for i8 #### fn shr_assign(&mut self, other: i128) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i16> for i8 #### fn shr_assign(&mut self, other: i16) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i32> for i8 #### fn shr_assign(&mut self, other: i32) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i64> for i8 #### fn shr_assign(&mut self, other: i64) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i8> for i8 #### fn shr_assign(&mut self, other: i8) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<isize> for i8 #### fn shr_assign(&mut self, other: isize) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u128> for i8 #### fn shr_assign(&mut self, other: u128) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u16> for i8 #### fn shr_assign(&mut self, other: u16) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u32> for i8 #### fn shr_assign(&mut self, other: u32) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u64> for i8 #### fn shr_assign(&mut self, other: u64) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u8> for i8 #### fn shr_assign(&mut self, other: u8) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<usize> for i8 #### fn shr_assign(&mut self, other: usize) Performs the `>>=` operation. #### type Mask = i8 🔬This is a nightly-only experimental API. (`portable_simd`)The mask element type corresponding to this element type.### impl Step for i8 #### unsafe fn forward_unchecked(start: i8, n: usize) -> i8 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *successor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *predecessor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *successor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *predecessor* of `self` `count` times. of `self` `count` times. of `self` `count` times. Read more1.0.0 · source### impl Sub<&i8> for i8 #### type Output = <i8 as Sub<i8>>::Output The resulting type after applying the `-` operator.#### fn sub(self, other: &i8) -> <i8 as Sub<i8>>::Output Performs the `-` operation. Read more1.0.0 · source### impl Sub<i8> for i8 #### type Output = i8 The resulting type after applying the `-` operator.#### fn sub(self, other: i8) -> i8 Performs the `-` operation. Read more1.22.0 · source### impl SubAssign<&i8> for i8 #### fn sub_assign(&mut self, other: &i8) Performs the `-=` operation. Read more1.8.0 · source### impl SubAssign<i8> for i8 #### fn sub_assign(&mut self, other: i8) Performs the `-=` operation. Read more1.12.0 · source### impl<'a> Sum<&'a i8> for i8 #### fn sum<I>(iter: I) -> i8where I: Iterator<Item = &'a i8>, Method which takes an iterator and generates `Self` from the elements by “summing up” the items.1.12.0 · source### impl Sum<i8> for i8 #### fn sum<I>(iter: I) -> i8where I: Iterator<Item = i8>, Method which takes an iterator and generates `Self` from the elements by “summing up” the items.1.34.0 · source### impl TryFrom<i128> for i8 #### fn try_from(u: i128) -> Result<i8, <i8 as TryFrom<i128>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<i16> for i8 #### fn try_from(u: i16) -> Result<i8, <i8 as TryFrom<i16>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<i32> for i8 #### fn try_from(u: i32) -> Result<i8, <i8 as TryFrom<i32>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<i64> for i8 #### fn try_from(u: i64) -> Result<i8, <i8 as TryFrom<i64>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<isize> for i8 #### fn try_from(u: isize) -> Result<i8, <i8 as TryFrom<isize>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u128> for i8 #### fn try_from(u: u128) -> Result<i8, <i8 as TryFrom<u128>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u16> for i8 #### fn try_from(u: u16) -> Result<i8, <i8 as TryFrom<u16>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u32> for i8 #### fn try_from(u: u32) -> Result<i8, <i8 as TryFrom<u32>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u64> for i8 #### fn try_from(u: u64) -> Result<i8, <i8 as TryFrom<u64>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u8> for i8 #### fn try_from(u: u8) -> Result<i8, <i8 as TryFrom<u8>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<usize> for i8 #### fn try_from(u: usize) -> Result<i8, <i8 as TryFrom<usize>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.42.0 · source### impl UpperExp for i8 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl UpperHex for i8 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl ConstParamTy for i8 1.0.0 · source### impl Copy for i8 1.0.0 · source### impl Eq for i8 ### impl MaskElement for i8 ### impl SimdCast for i8 ### impl StructuralEq for i8 ### impl StructuralPartialEq for i8 ### impl TrustedStep for i8 Struct safer_ffi::c_int === ``` pub struct c_int(pub c_int); ``` A `ReprC` *standalone* type with the same layout and ABI as `::libc::c_int`. By *standalone*, the idea is that this is defined as a (`transparent`) *newtype* `struct`, rather than as a *`type` alias*, which is error-prone and yields less-portable headers (since the header generation will resolve the type alias and emit, for instance, `int32_t`, ⚠️). By using this type, you guarantee that the C `int` type be used in the headers. Tuple Fields --- `0: c_int`Trait Implementations --- ### impl Clone for c_int #### fn clone(&self) -> c_int Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(self: &c_int, fmt: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result A short-name description of the type, mainly used to fill “placeholders” such as when monomorphising generics structs or arrays. The core method of the trait: it provides the implementation to be used by [`CType::c_var`], by bringing a `Formatter` in scope. Type name (*e.g.*, `int`, `string`, `IntPtr`)#### fn legacy_csharp_marshaler() -> Option<StringOptional marshaler attached to the type (*e.g.*, `[MarshalAs(UnmanagedType.FunctionPtr)]`)#### type OPAQUE_KIND = Concrete #### fn c_short_name() -> ImplDisplay<SelfConvenience function for *callers* / users of types implementing `CType`. `CType`. Convenience function for formatting `{ty} {var}` in CSharp.### impl PartialEq<c_int> for c_int #### fn eq(&self, other: &c_int) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for c_int ### impl Eq for c_int ### impl StructuralEq for c_int ### impl StructuralPartialEq for c_int Auto Trait Implementations --- ### impl RefUnwindSafe for c_int ### impl Send for c_int ### impl Sync for c_int ### impl Unpin for c_int ### impl UnwindSafe for c_int Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: Copy, #### fn as_out<'out>(&'out mut self) -> Out<'out, T### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: LegacyCType, #### type OPAQUE_KIND = <T as LegacyCType>::OPAQUE_KIND #### fn short_name() -> String #### fn define_self__impl( _: &(dyn HeaderLanguage + 'static), _: &mut dyn Definer ) -> Result<(), Error#### fn define_self( language: &(dyn HeaderLanguage + 'static), definer: &mut dyn Definer ) -> Result<(), Error#### fn name(language: &(dyn HeaderLanguage + 'static)) -> String #### fn name_wrapping_var( language: &(dyn HeaderLanguage + 'static), var_name: &str ) -> String #### fn csharp_marshaler() -> Option<StringOptional marshaler attached to the type (*e.g.*, `[MarshalAs(UnmanagedType.FunctionPtr)]`)#### fn zeroed() -> Self ### impl<T> CompatExt for T #### fn compat(self) -> Compat<TApplies the `Compat` adapter by value. #### type CBoxWrapped = Box_<TAvailable on **crate feature `alloc`** only.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ManuallyDropMut for T #### type Ret = ManuallyDrop<T#### fn manually_drop_mut<'__>(&'__ mut self) -> &'__ mut ManuallyDrop<T### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> UpcastAny for Twhere T: 'static, #### fn upcast_any(&self) -> &(dyn Any + 'static) Available on **crate feature `headers`** only.{"Compat<&T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","Compat<&mut T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>","Compat<T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"https://docs.rs/async-compat/0.2.1/x86_64-unknown-linux-gnu/async_compat/struct.Compat.html\" title=\"struct async_compat::Compat\">Compat</a>&lt;T&gt;<span class=\"where fmt-newline\">where\n T: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = &lt;T as <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a>&gt;::<a class=\"associatedtype\" href=\"https://doc.rust-lang.org/nightly/core/future/future/trait.Future.html#associatedtype.Output\" title=\"type core::future::future::Future::Output\">Output</a>;</span>"} Type Alias safer_ffi::libc::c_int === ``` pub type c_int = c_int; ``` A *`type` alias* to `::libc::c_int`. Note: you should probably be using `crate::c_int` instead. Trait Implementations --- 1.0.0 · source### impl Add<&i32> for i32 #### type Output = <i32 as Add<i32>>::Output The resulting type after applying the `+` operator.#### fn add(self, other: &i32) -> <i32 as Add<i32>>::Output Performs the `+` operation. Read more1.0.0 · source### impl Add<i32> for i32 #### type Output = i32 The resulting type after applying the `+` operator.#### fn add(self, other: i32) -> i32 Performs the `+` operation. Read more1.22.0 · source### impl AddAssign<&i32> for i32 #### fn add_assign(&mut self, other: &i32) Performs the `+=` operation. Read more1.8.0 · source### impl AddAssign<i32> for i32 #### fn add_assign(&mut self, other: i32) Performs the `+=` operation. Read more1.48.0 · source### impl AsRawFd for i32 #### fn as_raw_fd(&self) -> i32 Extracts the raw file descriptor. Read more1.0.0 · source### impl Binary for i32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl BitAnd<&i32> for i32 #### type Output = <i32 as BitAnd<i32>>::Output The resulting type after applying the `&` operator.#### fn bitand(self, other: &i32) -> <i32 as BitAnd<i32>>::Output Performs the `&` operation. Read more1.0.0 · source### impl BitAnd<i32> for i32 #### type Output = i32 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: i32) -> i32 Performs the `&` operation. Read more1.22.0 · source### impl BitAndAssign<&i32> for i32 #### fn bitand_assign(&mut self, other: &i32) Performs the `&=` operation. Read more1.8.0 · source### impl BitAndAssign<i32> for i32 #### fn bitand_assign(&mut self, other: i32) Performs the `&=` operation. Read more1.0.0 · source### impl BitOr<&i32> for i32 #### type Output = <i32 as BitOr<i32>>::Output The resulting type after applying the `|` operator.#### fn bitor(self, other: &i32) -> <i32 as BitOr<i32>>::Output Performs the `|` operation. Read more1.45.0 · source### impl BitOr<NonZeroI32> for i32 #### type Output = NonZeroI32 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: NonZeroI32) -> <i32 as BitOr<NonZeroI32>>::Output Performs the `|` operation. Read more1.0.0 · source### impl BitOr<i32> for i32 #### type Output = i32 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: i32) -> i32 Performs the `|` operation. Read more1.22.0 · source### impl BitOrAssign<&i32> for i32 #### fn bitor_assign(&mut self, other: &i32) Performs the `|=` operation. Read more1.8.0 · source### impl BitOrAssign<i32> for i32 #### fn bitor_assign(&mut self, other: i32) Performs the `|=` operation. Read more1.0.0 · source### impl BitXor<&i32> for i32 #### type Output = <i32 as BitXor<i32>>::Output The resulting type after applying the `^` operator.#### fn bitxor(self, other: &i32) -> <i32 as BitXor<i32>>::Output Performs the `^` operation. Read more1.0.0 · source### impl BitXor<i32> for i32 #### type Output = i32 The resulting type after applying the `^` operator.#### fn bitxor(self, other: i32) -> i32 Performs the `^` operation. Read more1.22.0 · source### impl BitXorAssign<&i32> for i32 #### fn bitxor_assign(&mut self, other: &i32) Performs the `^=` operation. Read more1.8.0 · source### impl BitXorAssign<i32> for i32 #### fn bitxor_assign(&mut self, other: i32) Performs the `^=` operation. Read more1.0.0 · source### impl Clone for i32 #### fn clone(&self) -> i32 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more1.0.0 · source### impl Debug for i32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. Read more1.0.0 · source### impl Default for i32 #### fn default() -> i32 Returns the default value of `0` 1.0.0 · source### impl Display for i32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. Read more1.0.0 · source### impl Div<&i32> for i32 #### type Output = <i32 as Div<i32>>::Output The resulting type after applying the `/` operator.#### fn div(self, other: &i32) -> <i32 as Div<i32>>::Output Performs the `/` operation. Read more1.0.0 · source### impl Div<i32> for i32 This operation rounds towards zero, truncating any fractional part of the exact result. #### Panics This operation will panic if `other == 0` or the division results in overflow. #### type Output = i32 The resulting type after applying the `/` operator.#### fn div(self, other: i32) -> i32 Performs the `/` operation. Read more1.22.0 · source### impl DivAssign<&i32> for i32 #### fn div_assign(&mut self, other: &i32) Performs the `/=` operation. Read more1.8.0 · source### impl DivAssign<i32> for i32 #### fn div_assign(&mut self, other: i32) Performs the `/=` operation. Read more1.31.0 · source### impl From<NonZeroI32> for i32 #### fn from(nonzero: NonZeroI32) -> i32 Converts a `NonZeroI32` into an `i32` 1.28.0 · source### impl From<bool> for i32 #### fn from(small: bool) -> i32 Converts a `bool` to a `i32`. The resulting value is `0` for `false` and `1` for `true` values. ##### Examples ``` assert_eq!(i32::from(true), 1); assert_eq!(i32::from(false), 0); ``` 1.5.0 · source### impl From<i16> for i32 #### fn from(small: i16) -> i32 Converts `i16` to `i32` losslessly. 1.5.0 · source### impl From<i8> for i32 #### fn from(small: i8) -> i32 Converts `i8` to `i32` losslessly. 1.5.0 · source### impl From<u16> for i32 #### fn from(small: u16) -> i32 Converts `u16` to `i32` losslessly. 1.5.0 · source### impl From<u8> for i32 #### fn from(small: u8) -> i32 Converts `u8` to `i32` losslessly. 1.48.0 · source### impl FromRawFd for i32 #### unsafe fn from_raw_fd(fd: i32) -> i32 Constructs a new instance of `Self` from the given raw file descriptor. Read more1.0.0 · source### impl Hash for i32 #### fn hash<H>(&self, state: &mut H)where H: Hasher, Feeds this value into the given `Hasher`. H: Hasher, Feeds a slice of this type into the given `Hasher`. Read more1.48.0 · source### impl IntoRawFd for i32 #### fn into_raw_fd(self) -> i32 Consumes this object, returning the raw underlying file descriptor. #### fn c_short_name_fmt(fmt: &mut Formatter<'_>) -> Result A short-name description of the type, mainly used to fill “placeholders” such as when monomorphising generics structs or arrays. The core method of the trait: it provides the implementation to be used by [`CType::c_var`], by bringing a `Formatter` in scope. Type name (*e.g.*, `int`, `string`, `IntPtr`)#### type OPAQUE_KIND = Concrete #### fn c_short_name() -> ImplDisplay<SelfConvenience function for *callers* / users of types implementing `CType`. `CType`. `[MarshalAs(UnmanagedType.FunctionPtr)]`)#### fn csharp_var(var_name: &str) -> String Convenience function for formatting `{ty} {var}` in CSharp.1.42.0 · source### impl LowerExp for i32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl LowerHex for i32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl Mul<&i32> for i32 #### type Output = <i32 as Mul<i32>>::Output The resulting type after applying the `*` operator.#### fn mul(self, other: &i32) -> <i32 as Mul<i32>>::Output Performs the `*` operation. Read more1.0.0 · source### impl Mul<i32> for i32 #### type Output = i32 The resulting type after applying the `*` operator.#### fn mul(self, other: i32) -> i32 Performs the `*` operation. Read more1.22.0 · source### impl MulAssign<&i32> for i32 #### fn mul_assign(&mut self, other: &i32) Performs the `*=` operation. Read more1.8.0 · source### impl MulAssign<i32> for i32 #### fn mul_assign(&mut self, other: i32) Performs the `*=` operation. Read more1.0.0 · source### impl Neg for i32 #### type Output = i32 The resulting type after applying the `-` operator.#### fn neg(self) -> i32 Performs the unary `-` operation. Read more1.0.0 · source### impl Not for i32 #### type Output = i32 The resulting type after applying the `!` operator.#### fn not(self) -> i32 Performs the unary `!` operation. Read more1.0.0 · source### impl Octal for i32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl Ord for i32 #### fn cmp(&self, other: &i32) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. Read more1.0.0 · source### impl PartialEq<i32> for i32 #### fn eq(&self, other: &i32) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.#### fn ne(&self, other: &i32) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.1.0.0 · source### impl PartialOrd<i32> for i32 #### fn partial_cmp(&self, other: &i32) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. This method tests less than (for `self` and `other`) and is used by the `<` operator. This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.12.0 · source### impl<'a> Product<&'a i32> for i32 #### fn product<I>(iter: I) -> i32where I: Iterator<Item = &'a i32>, Method which takes an iterator and generates `Self` from the elements by multiplying the items.1.12.0 · source### impl Product<i32> for i32 #### fn product<I>(iter: I) -> i32where I: Iterator<Item = i32>, Method which takes an iterator and generates `Self` from the elements by multiplying the items.1.0.0 · source### impl Rem<&i32> for i32 #### type Output = <i32 as Rem<i32>>::Output The resulting type after applying the `%` operator.#### fn rem(self, other: &i32) -> <i32 as Rem<i32>>::Output Performs the `%` operation. Read more1.0.0 · source### impl Rem<i32> for i32 This operation satisfies `n % d == n - (n / d) * d`. The result has the same sign as the left operand. #### Panics This operation will panic if `other == 0` or if `self / other` results in overflow. #### type Output = i32 The resulting type after applying the `%` operator.#### fn rem(self, other: i32) -> i32 Performs the `%` operation. Read more1.22.0 · source### impl RemAssign<&i32> for i32 #### fn rem_assign(&mut self, other: &i32) Performs the `%=` operation. Read more1.8.0 · source### impl RemAssign<i32> for i32 #### fn rem_assign(&mut self, other: i32) Performs the `%=` operation. #### type CLayout = i32 The `CType` having the same layout as `Self`.#### fn is_valid(_: &Self::CLayout) -> bool Sanity checks that can be performed on an instance of the `CType` layout. Read more1.0.0 · source### impl Shl<&i128> for i32 #### type Output = <i32 as Shl<i128>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i128) -> <i32 as Shl<i128>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i16> for i32 #### type Output = <i32 as Shl<i16>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i16) -> <i32 as Shl<i16>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i32> for i32 #### type Output = <i32 as Shl<i32>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i32) -> <i32 as Shl<i32>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i64> for i32 #### type Output = <i32 as Shl<i64>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i64) -> <i32 as Shl<i64>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i8> for i32 #### type Output = <i32 as Shl<i8>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i8) -> <i32 as Shl<i8>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&isize> for i32 #### type Output = <i32 as Shl<isize>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &isize) -> <i32 as Shl<isize>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u128> for i32 #### type Output = <i32 as Shl<u128>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u128) -> <i32 as Shl<u128>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u16> for i32 #### type Output = <i32 as Shl<u16>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u16) -> <i32 as Shl<u16>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u32> for i32 #### type Output = <i32 as Shl<u32>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u32) -> <i32 as Shl<u32>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u64> for i32 #### type Output = <i32 as Shl<u64>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u64) -> <i32 as Shl<u64>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u8> for i32 #### type Output = <i32 as Shl<u8>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u8) -> <i32 as Shl<u8>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&usize> for i32 #### type Output = <i32 as Shl<usize>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &usize) -> <i32 as Shl<usize>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i128> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: i128) -> i32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i16> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: i16) -> i32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i32> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: i32) -> i32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i64> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: i64) -> i32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i8> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: i8) -> i32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<isize> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: isize) -> i32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u128> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: u128) -> i32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u16> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: u16) -> i32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u32> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: u32) -> i32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u64> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: u64) -> i32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u8> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: u8) -> i32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<usize> for i32 #### type Output = i32 The resulting type after applying the `<<` operator.#### fn shl(self, other: usize) -> i32 Performs the `<<` operation. Read more1.22.0 · source### impl ShlAssign<&i128> for i32 #### fn shl_assign(&mut self, other: &i128) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i16> for i32 #### fn shl_assign(&mut self, other: &i16) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i32> for i32 #### fn shl_assign(&mut self, other: &i32) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i64> for i32 #### fn shl_assign(&mut self, other: &i64) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i8> for i32 #### fn shl_assign(&mut self, other: &i8) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&isize> for i32 #### fn shl_assign(&mut self, other: &isize) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u128> for i32 #### fn shl_assign(&mut self, other: &u128) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u16> for i32 #### fn shl_assign(&mut self, other: &u16) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u32> for i32 #### fn shl_assign(&mut self, other: &u32) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u64> for i32 #### fn shl_assign(&mut self, other: &u64) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u8> for i32 #### fn shl_assign(&mut self, other: &u8) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&usize> for i32 #### fn shl_assign(&mut self, other: &usize) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i128> for i32 #### fn shl_assign(&mut self, other: i128) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i16> for i32 #### fn shl_assign(&mut self, other: i16) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i32> for i32 #### fn shl_assign(&mut self, other: i32) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i64> for i32 #### fn shl_assign(&mut self, other: i64) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i8> for i32 #### fn shl_assign(&mut self, other: i8) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<isize> for i32 #### fn shl_assign(&mut self, other: isize) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u128> for i32 #### fn shl_assign(&mut self, other: u128) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u16> for i32 #### fn shl_assign(&mut self, other: u16) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u32> for i32 #### fn shl_assign(&mut self, other: u32) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u64> for i32 #### fn shl_assign(&mut self, other: u64) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u8> for i32 #### fn shl_assign(&mut self, other: u8) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<usize> for i32 #### fn shl_assign(&mut self, other: usize) Performs the `<<=` operation. Read more1.0.0 · source### impl Shr<&i128> for i32 #### type Output = <i32 as Shr<i128>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i128) -> <i32 as Shr<i128>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i16> for i32 #### type Output = <i32 as Shr<i16>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i16) -> <i32 as Shr<i16>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i32> for i32 #### type Output = <i32 as Shr<i32>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i32) -> <i32 as Shr<i32>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i64> for i32 #### type Output = <i32 as Shr<i64>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i64) -> <i32 as Shr<i64>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i8> for i32 #### type Output = <i32 as Shr<i8>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i8) -> <i32 as Shr<i8>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&isize> for i32 #### type Output = <i32 as Shr<isize>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &isize) -> <i32 as Shr<isize>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u128> for i32 #### type Output = <i32 as Shr<u128>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u128) -> <i32 as Shr<u128>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u16> for i32 #### type Output = <i32 as Shr<u16>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u16) -> <i32 as Shr<u16>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u32> for i32 #### type Output = <i32 as Shr<u32>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u32) -> <i32 as Shr<u32>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u64> for i32 #### type Output = <i32 as Shr<u64>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u64) -> <i32 as Shr<u64>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u8> for i32 #### type Output = <i32 as Shr<u8>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u8) -> <i32 as Shr<u8>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&usize> for i32 #### type Output = <i32 as Shr<usize>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &usize) -> <i32 as Shr<usize>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i128> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: i128) -> i32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i16> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: i16) -> i32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i32> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: i32) -> i32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i64> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: i64) -> i32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i8> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: i8) -> i32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<isize> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: isize) -> i32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u128> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: u128) -> i32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u16> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: u16) -> i32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u32> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: u32) -> i32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u64> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: u64) -> i32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u8> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: u8) -> i32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<usize> for i32 #### type Output = i32 The resulting type after applying the `>>` operator.#### fn shr(self, other: usize) -> i32 Performs the `>>` operation. Read more1.22.0 · source### impl ShrAssign<&i128> for i32 #### fn shr_assign(&mut self, other: &i128) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i16> for i32 #### fn shr_assign(&mut self, other: &i16) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i32> for i32 #### fn shr_assign(&mut self, other: &i32) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i64> for i32 #### fn shr_assign(&mut self, other: &i64) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i8> for i32 #### fn shr_assign(&mut self, other: &i8) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&isize> for i32 #### fn shr_assign(&mut self, other: &isize) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u128> for i32 #### fn shr_assign(&mut self, other: &u128) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u16> for i32 #### fn shr_assign(&mut self, other: &u16) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u32> for i32 #### fn shr_assign(&mut self, other: &u32) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u64> for i32 #### fn shr_assign(&mut self, other: &u64) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u8> for i32 #### fn shr_assign(&mut self, other: &u8) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&usize> for i32 #### fn shr_assign(&mut self, other: &usize) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i128> for i32 #### fn shr_assign(&mut self, other: i128) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i16> for i32 #### fn shr_assign(&mut self, other: i16) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i32> for i32 #### fn shr_assign(&mut self, other: i32) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i64> for i32 #### fn shr_assign(&mut self, other: i64) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i8> for i32 #### fn shr_assign(&mut self, other: i8) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<isize> for i32 #### fn shr_assign(&mut self, other: isize) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u128> for i32 #### fn shr_assign(&mut self, other: u128) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u16> for i32 #### fn shr_assign(&mut self, other: u16) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u32> for i32 #### fn shr_assign(&mut self, other: u32) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u64> for i32 #### fn shr_assign(&mut self, other: u64) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u8> for i32 #### fn shr_assign(&mut self, other: u8) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<usize> for i32 #### fn shr_assign(&mut self, other: usize) Performs the `>>=` operation. #### type Mask = i32 🔬This is a nightly-only experimental API. (`portable_simd`)The mask element type corresponding to this element type.### impl Step for i32 #### unsafe fn forward_unchecked(start: i32, n: usize) -> i32 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *successor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *predecessor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *successor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *predecessor* of `self` `count` times. of `self` `count` times. of `self` `count` times. Read more1.0.0 · source### impl Sub<&i32> for i32 #### type Output = <i32 as Sub<i32>>::Output The resulting type after applying the `-` operator.#### fn sub(self, other: &i32) -> <i32 as Sub<i32>>::Output Performs the `-` operation. Read more1.0.0 · source### impl Sub<i32> for i32 #### type Output = i32 The resulting type after applying the `-` operator.#### fn sub(self, other: i32) -> i32 Performs the `-` operation. Read more1.22.0 · source### impl SubAssign<&i32> for i32 #### fn sub_assign(&mut self, other: &i32) Performs the `-=` operation. Read more1.8.0 · source### impl SubAssign<i32> for i32 #### fn sub_assign(&mut self, other: i32) Performs the `-=` operation. Read more1.12.0 · source### impl<'a> Sum<&'a i32> for i32 #### fn sum<I>(iter: I) -> i32where I: Iterator<Item = &'a i32>, Method which takes an iterator and generates `Self` from the elements by “summing up” the items.1.12.0 · source### impl Sum<i32> for i32 #### fn sum<I>(iter: I) -> i32where I: Iterator<Item = i32>, Method which takes an iterator and generates `Self` from the elements by “summing up” the items.1.34.0 · source### impl TryFrom<i128> for i32 #### fn try_from(u: i128) -> Result<i32, <i32 as TryFrom<i128>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<i64> for i32 #### fn try_from(u: i64) -> Result<i32, <i32 as TryFrom<i64>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<isize> for i32 #### fn try_from(u: isize) -> Result<i32, <i32 as TryFrom<isize>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u128> for i32 #### fn try_from(u: u128) -> Result<i32, <i32 as TryFrom<u128>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u32> for i32 #### fn try_from(u: u32) -> Result<i32, <i32 as TryFrom<u32>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u64> for i32 #### fn try_from(u: u64) -> Result<i32, <i32 as TryFrom<u64>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<usize> for i32 #### fn try_from(u: usize) -> Result<i32, <i32 as TryFrom<usize>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.42.0 · source### impl UpperExp for i32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl UpperHex for i32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl ConstParamTy for i32 1.0.0 · source### impl Copy for i32 1.0.0 · source### impl Eq for i32 ### impl MaskElement for i32 ### impl SimdCast for i32 ### impl StructuralEq for i32 ### impl StructuralPartialEq for i32 ### impl TrustedStep for i32 Attribute Macro safer_ffi::cfg_headers === ``` #[cfg_headers] ``` Identity macro when `feature = "headers"` is enabled, otherwise this macro outputs nothing. Attribute Macro safer_ffi::derive_ReprC === ``` #[derive_ReprC] ``` Safely implement `ReprC` for a `#[repr(C)]` struct **when all its fields are `ReprC`**. Examples --- #### Simple `struct` ``` use ::safer_ffi::prelude::*; #[derive_ReprC] #[repr(C)] struct Instant { seconds: u64, nanos: u32, } ``` * corresponding to the following C definition: ``` typedef struct { uint64_t seconds; uint32_t nanos; } Instant_t; ``` #### Field-less `enum` ``` use ::safer_ffi::prelude::*; #[derive_ReprC] #[repr(u8)] enum Status { Ok = 0, Busy, NotInTheMood, OnStrike, OhNo, } ``` * corresponding to the following C definition: ``` typedef uint8_t Status_t; enum { STATUS_OK = 0, STATUS_BUSY, STATUS_NOT_IN_THE_MOOD, STATUS_ON_STRIKE, STATUS_OH_NO, } ``` #### Generic `struct` In that case, it is required that the struct’s generic types carry a `: ReprC` bound each: ``` use ::safer_ffi::prelude::*; #[derive_ReprC] #[repr(C)] struct Point<Coordinate : ReprC> { x: Coordinate, y: Coordinate, } ``` Each monomorphization leads to its own C definition: * **`Point<i32>`** ``` typedef struct { int32_t x; int32_t y; } Point_int32_t; ``` * **`Point<f64>`** ``` typedef struct { double x; double y; } Point_double_t; ``` Macro safer_ffi::layout::ReprC === ``` macro_rules! ReprC { ( $( @[doc = $doc:expr] )? $( #[doc = $doc2:expr] )* #[repr( $C_or_transparent:ident $(, $($(@$if_js:tt)? js $(,)? )? )? )] $( #[$attr:meta] )* $pub:vis struct $StructName:ident $([$($generics:tt)*])? $( where { $($wc:tt)* } )? $({ $($body:tt)* })? $(( $($body2:tt)* );)? ) => { ... }; } ``` Transitioning helper macro: still uses the old `ReprC!` syntax, but just to forward to the new `#[derive_ReprC2($(js)?)]` one. Attribute Macro safer_ffi::ffi_export === ``` #[ffi_export] ``` Export a function to be callable by C. Example --- ``` use ::safer_ffi::prelude::ffi_export; #[ffi_export] /// Add two integers together. fn add (x: i32, y: i32) -> i32 { x + y } ``` * ensures that the generated headers will include the following definition: ``` #include <stdint.h/* \brief * Add two integers together. */ int32_t add (int32_t x, int32_t y); ``` * exports an `add` symbol pointing to the C-ABI compatible `int32_t (*)(int32_t x, int32_t y)` function. (The crate type needs to be `cdylib` or `staticlib` for this to work, and, of course, the C compiler invocation needs to include `-L path/to/the/compiled/library -l name_of_your_crate`) + when in doubt, use `staticlib`. `ReprC` --- You can use any Rust types in the singature of an `#[ffi_export]`- function, provided each of the types involved in the signature is `ReprC`. Otherwise the layout of the involved types in the C world is **undefined**, which `#[ffi_export]` will detect, leading to a compilation error. To have custom structs implement `ReprC`, it suffices to annotate the `struct` definitions with the `#[derive_ReprC]` (on top of the obviously required `#[repr(C)]`).
github.com/flant/shell-operator
go
Go
README [¶](#section-readme) --- ![shell-operator logo](https://github.com/flant/shell-operator/raw/v1.3.2/docs/src/image/shell-operator-small-logo.png) [![docker pull flant/shell-operator](https://img.shields.io/docker/pulls/flant/shell-operator.svg?logo=docker)](https://hub.docker.com/r/flant/shell-operator) [![GH Discussions](https://img.shields.io/badge/GitHub-discussions-brightgreen)](https://github.com/flant/shell-operator/discussions) **Shell-operator** is a tool for running event-driven scripts in a Kubernetes cluster. This operator is not an operator for a *particular software product* such as `prometheus-operator` or `kafka-operator`. Shell-operator provides an integration layer between Kubernetes cluster events and shell scripts by treating scripts as hooks triggered by events. Think of it as an `operator-sdk` but for scripts. Shell-operator is used as a base for more advanced [addon-operator](https://github.com/flant/addon-operator) that supports Helm charts and value storages. Shell-operator provides: * **Ease of management of a Kubernetes cluster**: use the tools that Ops are familiar with. It can be bash, python, kubectl, etc. * **Kubernetes object events**: hook can be triggered by `add`, `update` or `delete` events. **[Learn more](https://github.com/flant/shell-operator/blob/v1.3.2/docs/src/HOOKS.md) about hooks.** * **Object selector and properties filter**: shell-operator can monitor a particular set of objects and detect changes in their properties. * **Simple configuration**: hook binding definition is a JSON or YAML document on script's stdout. * **Validating webhook machinery**: hook can handle validating for Kubernetes resources. * **Conversion webhook machinery**: hook can handle version conversion for Kubernetes resources. ### Documentation Please see the [docs](https://flant.github.io/shell-operator/) for more in-depth information and supported features. ### Examples and notable users More examples of how you can use shell-operator are available in the [examples](https://github.com/flant/shell-operator/blob/v1.3.2/examples) directory. Prominent shell-operator use cases include: * [Deckhouse](https://deckhouse.io/) Kubernetes platform where both projects, shell-operator and addon-operator, are used as the core technology to configure & extend K8s features; * KubeSphere Kubernetes platform's [installer](https://github.com/kubesphere/ks-installer); * [Kafka DevOps solution](https://github.com/confluentinc/streaming-ops) from Confluent. Please find out & share more examples in [Show & tell discussions](https://github.com/flant/shell-operator/discussions/categories/show-and-tell). ### Articles & talks Shell-operator has been presented during KubeCon + CloudNativeCon Europe 2020 Virtual (Aug'20). Here is the talk called "Go? Bash! Meet the shell-operator": * [YouTube video](https://www.youtube.com/watch?v=we0s4ETUBLc); * [text summary](https://medium.com/flant-com/meet-the-shell-operator-kubecon-36c14ba2f8fe); * [slides](https://speakerdeck.com/flant/go-bash-meet-the-shell-operator). Official publications on shell-operator: * "[shell-operator v1.0.0: the long-awaited release of our tool to create Kubernetes operators](https://blog.deckhouse.io/shell-operator-v1-0-0-the-long-awaited-release-of-our-tool-to-create-kubernetes-operators-b20fc0bbca9f?source=friends_link&sk=4d5f991eef62ad22222c5a725712ccdd)" (Apr'21); * "[shell-operator & addon-operator news: hooks as admission webhooks, Helm 3, OpenAPI, Go hooks, and more!](https://blog.deckhouse.io/shell-operator-addon-operator-news-hooks-as-admission-webhooks-helm-3-openapi-go-hooks-and-369df9b4af08?source=friends_link&sk=142aec38bdcdbca73868eb4cc0b85483)" (Feb'21); * "[Kubernetes operators made easy with shell-operator: project status & news](https://blog.deckhouse.io/shell-operator-for-kubernetes-update-2f1f9f9ebfb1)" (Jul'20); * "[Announcing shell-operator to simplify creating of Kubernetes operators](https://blog.deckhouse.io/kubernetes-shell-operator-76c596b42f23)" (May'19). Other languages: * Chinese: "[介绍一个不太小的工具:Shell Operator](https://blog.fleeto.us/post/shell-operator/)"; "[使用shell-operator实现Operator](https://cloud.tencent.com/developer/article/1701733)"; * Dutch: "[Een operator om te automatiseren – Hoe pak je dat aan?](https://www.hcs-company.com/blog/operator-automatiseren-namespace-openshift)"; * Russian: "[shell-operator v1.0.0: долгожданный релиз нашего проекта для Kubernetes-операторов](https://habr.com/ru/company/flant/blog/551456/)"; "[Представляем shell-operator: создавать операторы для Kubernetes стало ещё проще](https://habr.com/ru/company/flant/blog/447442/)". ### Community Please feel free to reach developers/maintainers and users via [GitHub Discussions](https://github.com/flant/shell-operator/discussions) for any questions regarding shell-operator. You're also welcome to follow [@flant\_com](https://twitter.com/flant_com) to stay informed about all our Open Source initiatives. ### License Apache License 2.0, see [LICENSE](https://github.com/flant/shell-operator/blob/v1.3.2/LICENSE). None
tokio-uring
rust
Rust
Crate tokio_uring === Tokio-uring provides a safe io-uring interface for the Tokio runtime. The library requires Linux kernel 5.10 or later. Getting started --- Using `tokio-uring` requires starting a [`tokio-uring`] runtime. This runtime internally manages the main Tokio runtime and a `io-uring` driver. ``` use tokio_uring::fs::File; fn main() -> Result<(), Box<dyn std::error::Error>> { tokio_uring::start(async { // Open a file let file = File::open("hello.txt").await?; let buf = vec![0; 4096]; // Read some data, the buffer is passed by ownership and // submitted to the kernel. When the operation completes, // we get the buffer back. let (res, buf) = file.read_at(buf, 0).await; let n = res?; // Display the contents println!("{:?}", &buf[..n]); Ok(()) }) } ``` Under the hood, `tokio_uring::start` starts a [`current-thread`] Runtime. For concurrency, spawn multiple threads, each with a `tokio-uring` runtime. The `tokio-uring` resource types are optimized for single-threaded usage and most are `!Sync`. Submit-based operations --- Unlike Tokio proper, `io-uring` is based on submission based operations. Ownership of resources are passed to the kernel, which then performs the operation. When the operation completes, ownership is passed back to the caller. Because of this difference, the `tokio-uring` APIs diverge. For example, in the above example, reading from a `File` requires passing ownership of the buffer. Closing resources --- With `io-uring`, closing a resource (e.g. a file) is an asynchronous operation. Because Rust does not support asynchronous drop yet, resource types provide an explicit `close()` function. If the `close()` function is not called, the resource will still be closed on drop, but the operation will happen in the background. There is no guarantee as to **when** the implicit close-on-drop operation happens, so it is recommended to explicitly call `close()`. Modules --- * bufUtilities for working with buffers. * fsFilesystem manipulation operations. * netTCP/UDP bindings for `tokio-uring`. Structs --- * BuilderBuilder API to allow starting the runtime and creating the io_uring driver with non-default parameters. * RuntimeThe Runtime executor Functions --- * builderReturn a Builder to allow setting parameters before calling the start method. Returns a Builder with our default values, all of which can be replaced with the methods below. * no_opThe simplest possible operation. Just posts a completion event, nothing else. * spawnSpawns a new asynchronous task, returning a `JoinHandle` for it. * startStart an `io_uring` enabled Tokio runtime. * uring_builderCreate and return an io_uring::Builder that can then be modified through its implementation methods. Type Definitions --- * BufResultA specialized `Result` type for `io-uring` operations with buffers. Crate tokio_uring === Tokio-uring provides a safe io-uring interface for the Tokio runtime. The library requires Linux kernel 5.10 or later. Getting started --- Using `tokio-uring` requires starting a [`tokio-uring`] runtime. This runtime internally manages the main Tokio runtime and a `io-uring` driver. ``` use tokio_uring::fs::File; fn main() -> Result<(), Box<dyn std::error::Error>> { tokio_uring::start(async { // Open a file let file = File::open("hello.txt").await?; let buf = vec![0; 4096]; // Read some data, the buffer is passed by ownership and // submitted to the kernel. When the operation completes, // we get the buffer back. let (res, buf) = file.read_at(buf, 0).await; let n = res?; // Display the contents println!("{:?}", &buf[..n]); Ok(()) }) } ``` Under the hood, `tokio_uring::start` starts a [`current-thread`] Runtime. For concurrency, spawn multiple threads, each with a `tokio-uring` runtime. The `tokio-uring` resource types are optimized for single-threaded usage and most are `!Sync`. Submit-based operations --- Unlike Tokio proper, `io-uring` is based on submission based operations. Ownership of resources are passed to the kernel, which then performs the operation. When the operation completes, ownership is passed back to the caller. Because of this difference, the `tokio-uring` APIs diverge. For example, in the above example, reading from a `File` requires passing ownership of the buffer. Closing resources --- With `io-uring`, closing a resource (e.g. a file) is an asynchronous operation. Because Rust does not support asynchronous drop yet, resource types provide an explicit `close()` function. If the `close()` function is not called, the resource will still be closed on drop, but the operation will happen in the background. There is no guarantee as to **when** the implicit close-on-drop operation happens, so it is recommended to explicitly call `close()`. Modules --- * bufUtilities for working with buffers. * fsFilesystem manipulation operations. * netTCP/UDP bindings for `tokio-uring`. Structs --- * BuilderBuilder API to allow starting the runtime and creating the io_uring driver with non-default parameters. * RuntimeThe Runtime executor Functions --- * builderReturn a Builder to allow setting parameters before calling the start method. Returns a Builder with our default values, all of which can be replaced with the methods below. * no_opThe simplest possible operation. Just posts a completion event, nothing else. * spawnSpawns a new asynchronous task, returning a `JoinHandle` for it. * startStart an `io_uring` enabled Tokio runtime. * uring_builderCreate and return an io_uring::Builder that can then be modified through its implementation methods. Type Definitions --- * BufResultA specialized `Result` type for `io-uring` operations with buffers. Module tokio_uring::buf === Utilities for working with buffers. `io-uring` APIs require passing ownership of buffers to the runtime. The crate defines `IoBuf` and `IoBufMut` traits which are implemented by buffer types that respect the `io-uring` contract. Structs --- * SliceAn owned view into a contiguous sequence of bytes. Traits --- * IoBufAn `io-uring` compatible buffer. * IoBufMutA mutable`io-uring` compatible buffer. Module tokio_uring::fs === Filesystem manipulation operations. Structs --- * FileA reference to an open file on the filesystem. * OpenOptionsOptions and flags which can be used to configure how a file is opened. Functions --- * remove_dirRemoves an empty directory. * remove_fileRemoves a File * renameRenames a file or directory to a new name, replacing the original file if `to` already exists. Module tokio_uring::net === TCP/UDP bindings for `tokio-uring`. This module contains the TCP/UDP networking types, similar to the standard library, which can be used to implement networking protocols. Organization --- * `TcpListener` and `TcpStream` provide functionality for communication over TCP * `UdpSocket` provides functionality for communication over UDP Structs --- * TcpListenerA TCP socket server, listening for connections. * TcpStreamA TCP stream between a local and a remote socket. * UdpSocketA UDP socket. * UnixListenerA Unix socket server, listening for connections. * UnixStreamA Unix stream between two local sockets on a Unix OS. Struct tokio_uring::Builder === ``` pub struct Builder { /* private fields */ } ``` Builder API to allow starting the runtime and creating the io_uring driver with non-default parameters. Implementations --- ### impl Builder #### pub fn entries(&mut self, e: u32) -> &mut Self Set number of submission queue entries in uring. The kernel will ensure it uses a power of two and will round this up if necessary. The kernel requires the number of completion queue entries to be larger than the submission queue entries so generally will double the sq entries count. The caller can specify even a larger cq entries count by using the uring_builder as shown in the start example below. #### pub fn uring_builder(&mut self, b: &Builder) -> &mut Self Replace the default io_uring Builder. This allows the caller to craft the io_uring Builder using the io_uring crate’s Builder API. Refer to the Builder start method for an example. Refer to the io_uring::builder documentation for all the supported methods. #### pub fn start<F: Future>(&self, future: F) -> F::Output Start an `io_uring` enabled Tokio runtime. ##### Examples Creating a uring driver with only 64 submission queue entries but many more completion queue entries. ``` use tokio::net::TcpListener; fn main() -> Result<(), Box<dyn std::error::Error>> { tokio_uring::builder() .entries(64) .uring_builder(tokio_uring::uring_builder() .setup_cqsize(1024) ) .start(async { let listener = TcpListener::bind("127.0.0.1:8080").await?; loop { let (socket, _) = listener.accept().await?; // process socket } } ) } ``` Auto Trait Implementations --- ### impl RefUnwindSafe for Builder ### impl Send for Builder ### impl Sync for Builder ### impl Unpin for Builder ### impl UnwindSafe for Builder Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct tokio_uring::Runtime === ``` pub struct Runtime { /* private fields */ } ``` The Runtime executor Implementations --- ### impl Runtime #### pub fn new(b: &Builder) -> Result<RuntimeCreate a new tokio_uring runtime on the current thread #### pub fn block_on<F>(&self, future: F) -> F::Outputwhere F: Future, Runs a future to completion on the current runtime Trait Implementations --- ### impl Drop for Runtime #### fn drop(&mut self) Executes the destructor for this type. Read moreAuto Trait Implementations --- ### impl !RefUnwindSafe for Runtime ### impl !Send for Runtime ### impl !Sync for Runtime ### impl Unpin for Runtime ### impl !UnwindSafe for Runtime Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Function tokio_uring::builder === ``` pub fn builder() -> Builder ``` Return a Builder to allow setting parameters before calling the start method. Returns a Builder with our default values, all of which can be replaced with the methods below. Refer to Builder::start for an example. Function tokio_uring::no_op === ``` pub async fn no_op() -> Result<()> ``` The simplest possible operation. Just posts a completion event, nothing else. This has a place in benchmarking and sanity checking uring. Examples --- ``` fn main() -> Result<(), Box<dyn std::error::Error>> { tokio_uring::start(async { // Place a NoOp on the ring, and await completion event tokio_uring::no_op().await?; Ok(()) }) } ``` Function tokio_uring::spawn === ``` pub fn spawn<T: Future + 'static>(task: T) -> JoinHandle<T::Output> ``` Spawns a new asynchronous task, returning a `JoinHandle` for it. Spawning a task enables the task to execute concurrently to other tasks. There is no guarantee that a spawned task will execute to completion. When a runtime is shutdown, all outstanding tasks are dropped, regardless of the lifecycle of that task. This function must be called from the context of a `tokio-uring` runtime. Examples --- In this example, a server is started and `spawn` is used to start a new task that processes each received connection. ``` tokio_uring::start(async { let handle = tokio_uring::spawn(async { println!("hello from a background task"); }); // Let the task complete handle.await.unwrap(); }); ``` Function tokio_uring::start === ``` pub fn start<F: Future>(future: F) -> F::Output ``` Start an `io_uring` enabled Tokio runtime. All `tokio-uring` resource types must be used from within the context of a runtime. The `start` method initializes the runtime and runs it for the duration of `future`. The `tokio-uring` runtime is compatible with all Tokio, so it is possible to run Tokio based libraries (e.g. hyper) from within the tokio-uring runtime. A `tokio-uring` runtime consists of a Tokio `current_thread` runtime and an `io-uring` driver. All tasks spawned on the `tokio-uring` runtime are executed on the current thread. To add concurrency, spawn multiple threads, each with a `tokio-uring` runtime. Examples --- Basic usage ``` use tokio_uring::fs::File; fn main() -> Result<(), Box<dyn std::error::Error>> { tokio_uring::start(async { // Open a file let file = File::open("hello.txt").await?; let buf = vec![0; 4096]; // Read some data, the buffer is passed by ownership and // submitted to the kernel. When the operation completes, // we get the buffer back. let (res, buf) = file.read_at(buf, 0).await; let n = res?; // Display the contents println!("{:?}", &buf[..n]); Ok(()) }) } ``` Using Tokio types from the `tokio-uring` runtime ``` use tokio::net::TcpListener; fn main() -> Result<(), Box<dyn std::error::Error>> { tokio_uring::start(async { let listener = TcpListener::bind("127.0.0.1:8080").await?; loop { let (socket, _) = listener.accept().await?; // process socket } }) } ``` Function tokio_uring::uring_builder === ``` pub fn uring_builder() -> Builder ``` Create and return an io_uring::Builder that can then be modified through its implementation methods. This function is provided to avoid requiring the user of this crate from having to use the io_uring crate as well. Refer to Builder::start example for its intended usage. Type Definition tokio_uring::BufResult === ``` pub type BufResult<T, B> = (Result<T>, B); ``` A specialized `Result` type for `io-uring` operations with buffers. This type is used as a return value for asynchronous `io-uring` methods that require passing ownership of a buffer to the runtime. When the operation completes, the buffer is returned whether or not the operation completed successfully. Examples --- ``` use tokio_uring::fs::File; fn main() -> Result<(), Box<dyn std::error::Error>> { tokio_uring::start(async { // Open a file let file = File::open("hello.txt").await?; let buf = vec![0; 4096]; // Read some data, the buffer is passed by ownership and // submitted to the kernel. When the operation completes, // we get the buffer back. let (res, buf) = file.read_at(buf, 0).await; let n = res?; // Display the contents println!("{:?}", &buf[..n]); Ok(()) }) } ```
roslibpy
readthedoc
Python
roslibpy 1.5.0 documentation [roslibpy](#) === Python ROS Bridge library ### Navigation * [roslibpy: ROS Bridge library](index.html#document-readme) * [Examples](index.html#document-examples) * [API Reference](index.html#document-reference/index) * [Contributor’s Guide](index.html#document-contributing) * [Authors](index.html#document-authors) * [Changelog](index.html#document-changelog) ### Quick search roslibpy: ROS Bridge library[¶](#roslibpy-ros-bridge-library) === **Python ROS Bridge library** allows to use Python and IronPython to interact with [ROS](http://www.ros.org), the open-source robotic middleware. It uses WebSockets to connect to [rosbridge 2.0](http://wiki.ros.org/rosbridge_suite) and provides publishing, subscribing, service calls, actionlib, TF, and other essential ROS functionality. Unlike the [rospy](http://wiki.ros.org/rospy) library, this does not require a local ROS environment, allowing usage from platforms other than Linux. The API of **roslibpy** is modeled to closely match that of [roslibjs](http://wiki.ros.org/roslibjs). Contents[¶](#contents) === roslibpy: ROS Bridge library[¶](#roslibpy-ros-bridge-library) --- **Python ROS Bridge library** allows to use Python and IronPython to interact with [ROS](http://www.ros.org), the open-source robotic middleware. It uses WebSockets to connect to [rosbridge 2.0](http://wiki.ros.org/rosbridge_suite) and provides publishing, subscribing, service calls, actionlib, TF, and other essential ROS functionality. Unlike the [rospy](http://wiki.ros.org/rospy) library, this does not require a local ROS environment, allowing usage from platforms other than Linux. The API of **roslibpy** is modeled to closely match that of [roslibjs](http://wiki.ros.org/roslibjs). ### Main features[¶](#main-features) * Topic publishing and subscribing. * Service calls (client). * Service advertisement (server). * ROS parameter management (get/set/delete). * ROS API services for getting ROS meta-information. * Actionlib support for interfacing with preemptable tasks. * TF Client via the `tf2_web_republisher`. **Roslibpy** runs on Python 3.x and IronPython 2.7. ### Installation[¶](#installation) To install **roslibpy**, simply use `pip`: ``` pip install roslibpy ``` For IronPython, the `pip` command is slightly different: ``` ipy -X:Frames -m pip install --user roslibpy ``` Remember that you will need a working ROS setup including the **rosbridge server** and **TF2 web republisher** accessible within your network. ### Documentation[¶](#documentation) The full documentation, including examples and API reference is available on [readthedocs](https://roslibpy.readthedocs.io/). ### Contributing[¶](#contributing) Make sure you setup your local development environment correctly: * Clone the [roslibpy](https://github.com/gramaziokohler/roslibpy) repository. * Create a virtual environment. * Install development dependencies: ``` pip install -r requirements-dev.txt ``` **You’re ready to start coding!** During development, use [pyinvoke](http://docs.pyinvoke.org/) tasks on the command prompt to ease recurring operations: * `invoke clean`: Clean all generated artifacts. * `invoke check`: Run various code and documentation style checks. * `invoke docs`: Generate documentation. * `invoke test`: Run all tests and checks in one swift command. * `invoke`: Show available tasks. For more details, check the *Contributor’s Guide* available as part of [the documentation](https://roslibpy.readthedocs.io/). The default branch was recently renamed to main. If you’ve already cloned this repository, you’ll need to update your local repository structure with the following lines: ``` git branch -m master main git fetch origin git branch -u origin/main main ``` ### Releasing this project[¶](#releasing-this-project) Ready to release a new version **roslibpy**? Here’s how to do it: * We use [semver](http://semver.org/), i.e. we bump versions as follows: + `patch`: bugfixes. + `minor`: backwards-compatible features added. + `major`: backwards-incompatible changes. * Update the `CHANGELOG.rst` with all novelty! * Ready? Release everything in one command: ``` invoke release [patch|minor|major] ``` * Profit! ### Credits[¶](#credits) This library is based on [roslibjs](http://wiki.ros.org/roslibjs) and to a large extent, it is a line-by-line port to Python, changing only where a more idiomatic form makes sense, so a huge part of the credit goes to the [roslibjs authors](https://github.com/RobotWebTools/roslibjs/blob/develop/AUTHORS.md). Examples[¶](#examples) --- Getting started with **roslibpy** is simple. The following examples will help you on the first steps using it to connect to a ROS environment. Before you start, make sure you have ROS and rosbridge running (see [ROS Setup](index.html#ros-setup)). These examples assume ROS is running on the same computer where you run the examples. If that is not the case, change the `host` argument from `'localhost'` to the *IP Address* of your ROS instance. ### First connection[¶](#first-connection) We start importing `roslibpy` as follows: ``` >>> import roslibpy ``` And we initialize the connection with: ``` >>> ros = roslibpy.Ros(host='localhost', port=9090) >>> ros.run() ``` Easy, right? Let’s check the status: ``` >>> ros.is_connected True ``` **Yay! Our first connection to ROS!** ### Putting it all together[¶](#putting-it-all-together) Let’s build a full example into a python file. Create a file named `ros-hello-world.py` and paste the following content: ``` import roslibpy client = roslibpy.Ros(host='localhost', port=9090) client.run() print('Is ROS connected?', client.is_connected) client.terminate() ``` Now run it from the command prompt typing: ``` $ python ros-hello-world.py ``` The program will run, print once we are connected and terminate the connection. #### Controlling the event loop[¶](#controlling-the-event-loop) In the previous examples, we started the ROS connection with a call to `run()`, which starts the event loop in the background. In some cases, we want to handle the main event loop more explicitely in the foreground. [`roslibpy.Ros`](index.html#roslibpy.Ros) provides the method `run_forever()` for this purpose. If we use this method to start the event loop, we need to setup all connection handlers beforehand. We will use the [`roslibpy.Ros.on_ready()`](index.html#roslibpy.Ros.on_ready) method to do this. We will pass a function to it, that will be invoked when the connection is ready. The following snippet shows the same connection example above but using `run_forever()` and `on_ready`: ``` from __future__ import print_function import roslibpy client = roslibpy.Ros(host='localhost', port=9090) client.on_ready(lambda: print('Is ROS connected?', client.is_connected)) client.run_forever() ``` Note The difference between `run()` and `run_forever()` is that the former starts the event processing in a separate thread, while the latter blocks the calling thread. ### Disconnecting[¶](#disconnecting) Once your task is done, you should disconnect cleanly from `rosbridge`. There are two related methods available for this: > * [`roslibpy.Ros.close()`](index.html#roslibpy.Ros.close): Disconnect the websocket connection. Once the connection is closed, > it is still possible to reconnect by calling [`roslibpy.Ros.connect()`](index.html#roslibpy.Ros.connect): again. > * [`roslibpy.Ros.terminate()`](index.html#roslibpy.Ros.terminate): Terminate the main event loop. If the connection is still open, > it will first close it. Note Terminating the event loop is an irreversible action when using the `twisted/authbahn` loop because `twisted` reactors cannot be restarted. This operation should be reserved to be executed at the very end of your program. ### Reconnecting[¶](#reconnecting) If `rosbridge` is not responsive when the connection is started or if an established connection drops uncleanly, `roslibpy` will try to reconnect automatically, and reconnect subscriber and publisher topics as well. Reconnect will be retried with an exponential back-off. ### Hello World: Topics[¶](#hello-world-topics) The `Hello world` of ROS is to start two nodes that communicate using topic subscription/publishing. The nodes (a talker and a listener) are extremely simple but they exemplify a distributed system with communication between two processes over the ROS infrastructure. #### Writing the talker node[¶](#writing-the-talker-node) The following example starts a ROS node and begins to publish messages in loop (to terminate, press `ctrl+c`): ``` import time import roslibpy client = roslibpy.Ros(host='localhost', port=9090) client.run() talker = roslibpy.Topic(client, '/chatter', 'std_msgs/String') while client.is_connected: talker.publish(roslibpy.Message({'data': 'Hello World!'})) print('Sending message...') time.sleep(1) talker.unadvertise() client.terminate() ``` * [`ros-hello-world-talker.py`](_downloads/8cc3ddde8586d956025ee76f2c2b9798/ros-hello-world-talker.py) #### Writing the listener node[¶](#writing-the-listener-node) Now let’s move on to the listener side: ``` from __future__ import print_function import roslibpy client = roslibpy.Ros(host='localhost', port=9090) client.run() listener = roslibpy.Topic(client, '/chatter', 'std_msgs/String') listener.subscribe(lambda message: print('Heard talking: ' + message['data'])) try: while True: pass except KeyboardInterrupt: client.terminate() ``` * [`ros-hello-world-listener.py`](_downloads/0b206915a8fe3c2c1e417c8f684b2542/ros-hello-world-listener.py) #### Running the example[¶](#running-the-example) Open a command prompt and start the talker: ``` python ros-hello-world-talker.py ``` Now open a second command prompt and start the listener: ``` python ros-hello-world-listener.py ``` Note It is not relevant where the files are located. They can be in different folders or even in different computers as long as the ROS instance is the same. ### Using services[¶](#using-services) Another way for nodes to communicate between each other is through ROS Services. Services require the definition of request and response types so the following example shows how to use an existing service called `get_loggers`: ``` import roslibpy client = roslibpy.Ros(host='localhost', port=9090) client.run() service = roslibpy.Service(client, '/rosout/get_loggers', 'roscpp/GetLoggers') request = roslibpy.ServiceRequest() print('Calling service...') result = service.call(request) print('Service response: {}'.format(result['loggers'])) client.terminate() ``` * [`ros-service-call-logger.py`](_downloads/c97abd36a414cd4d296209cb08c935aa/ros-service-call-logger.py) ### Creating services[¶](#creating-services) It is also possible to create new services, as long as the service type definition is present in your ROS environment. The following example shows how to create a simple service that uses one of the standard service types defined in ROS (`std_srvs/SetBool`): ``` import roslibpy def handler(request, response): print('Setting speed to {}'.format(request['data'])) response['success'] = True return True client = roslibpy.Ros(host='localhost', port=9090) service = roslibpy.Service(client, '/set_ludicrous_speed', 'std_srvs/SetBool') service.advertise(handler) print('Service advertised.') client.run_forever() client.terminate() ``` * [`ros-service.py`](_downloads/457f25e6582e4eafd88097cc078066a5/ros-service.py) Download it and run it from the command prompt typing: ``` $ python ros-service.py ``` The service will be active while the program is running (to terminate, press `ctrl+c`). Leave this service running and download and run the following service calling code example to verify the service is working: * [`ros-service-call-set-bool.py`](_downloads/39491ca47c39b2b82801c3056d63cffb/ros-service-call-set-bool.py) Download it and run it from the command prompt typing: ``` $ python ros-service-call-set-bool.py ``` Note Now that you have a grasp of the basics of `roslibpy`, check out more details in the [API Reference](index.html#ros-api-reference). ### Actions[¶](#actions) Besides Topics and Services, ROS provides **Actions**, which are intended for long-running tasks, such as navigation, because they are non-blocking and allow the cancellation (preempting) of an action while it is executing. `roslibpy` supports both consuming actions (i.e. action clients) and also providing actions, through the [`roslibpy.actionlib.SimpleActionServer`](index.html#roslibpy.actionlib.SimpleActionServer). The following examples use the **Fibonacci** action, which is defined in the [actionlib_tutorials](http://wiki.ros.org/actionlib_tutorials). #### Action servers[¶](#action-servers) Let’s start with the definition of the fibonacci server: ``` import roslibpy import roslibpy.actionlib client = roslibpy.Ros(host='localhost', port=9090) server = roslibpy.actionlib.SimpleActionServer(client, '/fibonacci', 'actionlib_tutorials/FibonacciAction') def execute(goal): print('Received new fibonacci goal: {}'.format(goal['order'])) seq = [0, 1] for i in range(1, goal['order']): if server.is_preempt_requested(): server.set_preempted() return seq.append(seq[i] + seq[i - 1]) server.send_feedback({'sequence': seq}) server.set_succeeded({'sequence': seq}) server.start(execute) client.run_forever() ``` * [`ros-action-server.py`](_downloads/e096e29280ca74e3fc088014458ec3ba/ros-action-server.py) Download it and run it from the command prompt typing: ``` $ python ros-action-server.py ``` The action server will be active while the program is running (to terminate, press `ctrl+c`). Leave this window running if you want to test it with the next example. #### Action clients[¶](#action-clients) Now let’s see how to write an action client for our newly created server. The following program shows a simple action client: ``` from __future__ import print_function import roslibpy import roslibpy.actionlib client = roslibpy.Ros(host='localhost', port=9090) client.run() action_client = roslibpy.actionlib.ActionClient(client, '/fibonacci', 'actionlib_tutorials/FibonacciAction') goal = roslibpy.actionlib.Goal(action_client, roslibpy.Message({'order': 8})) goal.on('feedback', lambda f: print(f['sequence'])) goal.send() result = goal.wait(10) action_client.dispose() print('Result: {}'.format(result['sequence'])) ``` * [`ros-action-client.py`](_downloads/a6fb7d209eb2f349be4ee1abf6f47bc1/ros-action-client.py) Download it and run it from the command prompt typing: ``` $ python ros-action-client.py ``` You will immediately see all the intermediate calculations of our action server, followed by a line indicating the resulting fibonacci sequence. This example is very simplified and uses the [`roslibpy.actionlib.Goal.wait()`](index.html#roslibpy.actionlib.Goal.wait) function to make the code easier to read as an example. A more robust way to handle results is to hook up to the `result` event with a callback. ### Querying ROS API[¶](#querying-ros-api) ROS provides an API to inspect topics, services, nodes and much more. This API can be used programmatically from Python code, and also be invoked from the command line. #### Usage from the command-line[¶](#usage-from-the-command-line) The command line mimics closely that of ROS itself. The following commands are available: ``` $ roslibpy topic list $ roslibpy topic type /rosout $ roslibpy topic find std_msgs/Int32 $ roslibpy msg info rosgraph_msgs/Log $ roslibpy service list $ roslibpy service type /rosout/get_loggers $ roslibpy service find roscpp/GetLoggers $ roslibpy srv info roscpp/GetLoggers $ roslibpy param list $ roslibpy param set /foo "[\"1\", 1, 1.0]" $ roslibpy param get /foo $ roslibpy param delete /foo ``` #### Usage from Python code[¶](#usage-from-python-code) And conversely, the following methods allow to query the ROS API from Python code. ##### Topics[¶](#topics) * [`roslibpy.Ros.get_topics()`](index.html#roslibpy.Ros.get_topics) * [`roslibpy.Ros.get_topic_type()`](index.html#roslibpy.Ros.get_topic_type) * [`roslibpy.Ros.get_topics_for_type()`](index.html#roslibpy.Ros.get_topics_for_type) * [`roslibpy.Ros.get_message_details()`](index.html#roslibpy.Ros.get_message_details) ##### Services[¶](#services) * [`roslibpy.Ros.get_services()`](index.html#roslibpy.Ros.get_services) * [`roslibpy.Ros.get_service_type()`](index.html#roslibpy.Ros.get_service_type) * [`roslibpy.Ros.get_services_for_type()`](index.html#roslibpy.Ros.get_services_for_type) * [`roslibpy.Ros.get_service_request_details()`](index.html#roslibpy.Ros.get_service_request_details) * [`roslibpy.Ros.get_service_response_details()`](index.html#roslibpy.Ros.get_service_response_details) ##### Params[¶](#params) * [`roslibpy.Ros.get_params()`](index.html#roslibpy.Ros.get_params) * [`roslibpy.Ros.get_param()`](index.html#roslibpy.Ros.get_param) * [`roslibpy.Ros.set_param()`](index.html#roslibpy.Ros.set_param) * [`roslibpy.Ros.delete_param()`](index.html#roslibpy.Ros.delete_param) ##### Time[¶](#time) * [`roslibpy.Ros.get_time()`](index.html#roslibpy.Ros.get_time) ### Advanced examples[¶](#advanced-examples) The following list is a compilation of more elaborate examples of the usage of `roslibpy`. We encourage everyone to submit suggestions for new examples, either send a pull request or request it via the issue tracker. #### Enable debug logging[¶](#enable-debug-logging) This example shows how to enable debugging output using Python `logging` infrastructure. ``` import logging import roslibpy # Configure logging to high verbosity (DEBUG) fmt = '%(asctime)s %(levelname)8s: %(message)s' logging.basicConfig(format=fmt, level=logging.DEBUG) log = logging.getLogger(__name__) client = roslibpy.Ros(host='127.0.0.1', port=9090) client.on_ready(lambda: log.info('On ready has been triggered')) client.run_forever() ``` #### Check roundtrip message latency[¶](#check-roundtrip-message-latency) This example shows how to check roundtrip message latency on your system. ``` import logging import time import roslibpy # Configure logging fmt = '%(asctime)s %(levelname)8s: %(message)s' logging.basicConfig(format=fmt, level=logging.INFO) log = logging.getLogger(__name__) client = roslibpy.Ros(host='127.0.0.1', port=9090) def receive_message(msg): age = int(time.time() * 1000) - msg['data'] log.info('Age of message: %6dms', age) publisher = roslibpy.Topic(client, '/check_latency', 'std_msgs/UInt64') publisher.advertise() subscriber = roslibpy.Topic(client, '/check_latency', 'std_msgs/UInt64') subscriber.subscribe(receive_message) def publish_message(): publisher.publish(dict(data=int(time.time() * 1000))) client.call_later(.5, publish_message) client.on_ready(publish_message) client.run_forever() ``` The output on the console should look similar to the following: ``` $ python 02_check_latency.py 2020-04-09 07:45:49,909 INFO: Connection to ROS ready. 2020-04-09 07:45:50,431 INFO: Age of message: 2ms 2020-04-09 07:45:50,932 INFO: Age of message: 2ms 2020-04-09 07:45:51,431 INFO: Age of message: 1ms 2020-04-09 07:45:51,932 INFO: Age of message: 2ms 2020-04-09 07:45:52,434 INFO: Age of message: 3ms 2020-04-09 07:45:52,934 INFO: Age of message: 2ms 2020-04-09 07:45:53,435 INFO: Age of message: 3ms 2020-04-09 07:45:53,934 INFO: Age of message: 1ms 2020-04-09 07:45:54,436 INFO: Age of message: 2ms ``` #### Throttle messages for a slow consumer[¶](#throttle-messages-for-a-slow-consumer) This example shows how to throttle messages that are published are a rate faster than what a slow consumer (subscribed) can process. In this example, only the newest messages are preserved, messages that cannot be consumed on time are dropped. ``` import time import logging from roslibpy import Header from roslibpy import Ros from roslibpy import Time from roslibpy import Topic from roslibpy.core import LOGGER # Configure logging fmt = '%(asctime)s %(levelname)8s: %(message)s' logging.basicConfig(format=fmt, level=logging.INFO) log = logging.getLogger(__name__) client = Ros(host='127.0.0.1', port=9090) def receive_message(msg): header = Header(msg['seq'], msg['stamp'], msg['frame_id']) age = time.time() - header['stamp'].to_sec() fmt = 'Age of message (sequence #%d): %6.3f seconds' log.info(fmt, msg['seq'], age) # Simulate a very slow consumer time.sleep(.5) publisher = Topic(client, '/slow_consumer', 'std_msgs/Header') publisher.advertise() # Queue length needs to be used in combination with throttle rate (in ms) # This value must be tuned to the expected duration of the slow consumer # and ideally bigger than the max of it, # otherwise message will be older than expected (up to a limit) subscriber = Topic(client, '/slow_consumer', 'std_msgs/Header', queue_length=1, throttle_rate=600) subscriber.subscribe(receive_message) seq = 0 def publish_message(): global seq seq += 1 header = Header(frame_id='', seq=seq, stamp=Time.now()) publisher.publish(header) client.call_later(.001, publish_message) client.on_ready(publish_message) client.run_forever() ``` In the console, you should see gaps in the sequence of messages, because the publisher is producing messages every 0.001 seconds, but we configure a queue of length 1, with a throttling of 600ms to give time to our slow consumer. Without this throttling, the consumer would process increasingly old messages. #### Publish images[¶](#publish-images) This example shows how to publish images using the built-in `sensor_msgs/CompressedImage` message type. ``` import base64 import logging import time import roslibpy # Configure logging fmt = '%(asctime)s %(levelname)8s: %(message)s' logging.basicConfig(format=fmt, level=logging.INFO) log = logging.getLogger(__name__) client = roslibpy.Ros(host='127.0.0.1', port=9090) publisher = roslibpy.Topic(client, '/camera/image/compressed', 'sensor_msgs/CompressedImage') publisher.advertise() def publish_image(): with open('robots.jpg', 'rb') as image_file: image_bytes = image_file.read() encoded = base64.b64encode(image_bytes).decode('ascii') publisher.publish(dict(format='jpeg', data=encoded)) client.on_ready(publish_image) client.run_forever() ``` #### Subscribe to images[¶](#subscribe-to-images) This example shows how to subscribe to a topic of images using the built-in `sensor_msgs/CompressedImage` message type. ``` import base64 import logging import time import roslibpy # Configure logging fmt = '%(asctime)s %(levelname)8s: %(message)s' logging.basicConfig(format=fmt, level=logging.INFO) log = logging.getLogger(__name__) client = roslibpy.Ros(host='127.0.0.1', port=9090) def receive_image(msg): log.info('Received image seq=%d', msg['header']['seq']) base64_bytes = msg['data'].encode('ascii') image_bytes = base64.b64decode(base64_bytes) with open('received-image-{}.{}'.format(msg['header']['seq'], msg['format']) , 'wb') as image_file: image_file.write(image_bytes) subscriber = roslibpy.Topic(client, '/camera/image/compressed', 'sensor_msgs/CompressedImage') subscriber.subscribe(receive_image) client.run_forever() ``` API Reference[¶](#api-reference) --- This library relies on the [ROS bridge suite](http://wiki.ros.org/rosbridge_suite) by Robot Web Tools to interact with ROS via WebSockets. The [ROS bridge protocol](https://github.com/RobotWebTools/rosbridge_suite/blob/master/ROSBRIDGE_PROTOCOL.md) uses JSON as message transport to allow access to ROS functionality such as publishing, subscribing, service calls, actionlib, TF, etc. ### ROS Setup[¶](#ros-setup-1) In order to use this library, your ROS environment needs to be setup to run `rosbridge`. First install the **rosbridge suite** with the following commands: ``` sudo apt-get install -y ros-kinetic-rosbridge-server sudo apt-get install -y ros-kinetic-tf2-web-republisher ``` And before starting a connection, make sure you launch all services: ``` roslaunch rosbridge_server rosbridge_websocket.launch rosrun tf2_web_republisher tf2_web_republisher ``` ### Connecting to ROS[¶](#connecting-to-ros) The connection to ROS is managed by the [`Ros`](#roslibpy.Ros) class. Besides connection and disposal, it handles automatic reconnections when needed. Other classes that need an active connection with ROS receive this instance as an argument to their constructors. *class* `roslibpy.``Ros`(*host*, *port=None*, *is_secure=False*)[[source]](_modules/roslibpy/ros.html#Ros)[¶](#roslibpy.Ros) Connection manager to ROS server. Parameters: * **host** (`str`) – Name or IP address of the ROS bridge host, e.g. `127.0.0.1`. * **port** (`int`) – ROS bridge port, e.g. `9090`. * **is_secure** (`bool`) – `True` to use a secure web sockets connection, otherwise `False`. `blocking_call_from_thread`(*callback*, *timeout*)[[source]](_modules/roslibpy/ros.html#Ros.blocking_call_from_thread)[¶](#roslibpy.Ros.blocking_call_from_thread) Call the given function from a thread, and wait for the result synchronously for as long as the timeout will allow. Parameters: * **callback** – Callable function to be invoked from the thread. * **timeout** (`int`) – Number of seconds to wait for the response before raising an exception. Returns: The results from the callback, or a timeout exception. `call_async_service`(*message*, *callback*, *errback*)[[source]](_modules/roslibpy/ros.html#Ros.call_async_service)[¶](#roslibpy.Ros.call_async_service) Send a service request to ROS once the connection is established. If a connection to ROS is already available, the request is sent immediately. Parameters: * **message** ([`Message`](#roslibpy.Message)) – ROS Bridge Message containing the request. * **callback** – Callback invoked on successful execution. * **errback** – Callback invoked on error. `call_in_thread`(*callback*)[[source]](_modules/roslibpy/ros.html#Ros.call_in_thread)[¶](#roslibpy.Ros.call_in_thread) Call the given function in a thread. The threading implementation is deferred to the factory. Parameters: **callback** (`callable`) – Callable function to be invoked. `call_later`(*delay*, *callback*)[[source]](_modules/roslibpy/ros.html#Ros.call_later)[¶](#roslibpy.Ros.call_later) Call the given function after a certain period of time has passed. Parameters: * **delay** (`int`) – Number of seconds to wait before invoking the callback. * **callback** (`callable`) – Callable function to be invoked when ROS connection is ready. `call_sync_service`(*message*, *timeout*)[[source]](_modules/roslibpy/ros.html#Ros.call_sync_service)[¶](#roslibpy.Ros.call_sync_service) Send a blocking service request to ROS once the connection is established, waiting for the result to be return. If a connection to ROS is already available, the request is sent immediately. Parameters: * **message** ([`Message`](#roslibpy.Message)) – ROS Bridge Message containing the request. * **timeout** (`int`) – Number of seconds to wait for the response before raising an exception. Returns: Either returns the service request results or raises a timeout exception. `close`(*timeout=10*)[[source]](_modules/roslibpy/ros.html#Ros.close)[¶](#roslibpy.Ros.close) Disconnect from ROS. `connect`()[[source]](_modules/roslibpy/ros.html#Ros.connect)[¶](#roslibpy.Ros.connect) Connect to ROS. `delete_param`(*name*, *callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.delete_param)[¶](#roslibpy.Ros.delete_param) Delete parameter from the ROS Parameter Server. Note To make this a blocking call, pass `None` to the `callback` parameter . `emit`(*event_name*, **args*)[[source]](_modules/roslibpy/ros.html#Ros.emit)[¶](#roslibpy.Ros.emit) Trigger a named event. `get_action_servers`(*callback*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_action_servers)[¶](#roslibpy.Ros.get_action_servers) Retrieve list of action servers in ROS. `get_message_details`(*message_type*, *callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_message_details)[¶](#roslibpy.Ros.get_message_details) Retrieve details of a message type in ROS. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: Message type details if blocking, otherwise `None`. `get_node_details`(*node*, *callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_node_details)[¶](#roslibpy.Ros.get_node_details) Retrieve list subscribed topics, publishing topics and services of a specific node name. Note To make this a blocking call, pass `None` to the `callback` parameter . `get_nodes`(*callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_nodes)[¶](#roslibpy.Ros.get_nodes) Retrieve list of active node names in ROS. Note To make this a blocking call, pass `None` to the `callback` parameter . `get_param`(*name*, *callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_param)[¶](#roslibpy.Ros.get_param) Get the value of a parameter from the ROS Parameter Server. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: Parameter value if blocking, otherwise `None`. `get_params`(*callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_params)[¶](#roslibpy.Ros.get_params) Retrieve list of param names from the ROS Parameter Server. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: *list* – List of parameters if blocking, otherwise `None`. `get_service_request_callback`(*message*)[[source]](_modules/roslibpy/ros.html#Ros.get_service_request_callback)[¶](#roslibpy.Ros.get_service_request_callback) Get the callback which, when called, sends the service request. Parameters: **message** ([`Message`](#roslibpy.Message)) – ROS Bridge Message containing the request. Returns: A callable which makes the service request. `get_service_request_details`(*type*, *callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_service_request_details)[¶](#roslibpy.Ros.get_service_request_details) Retrieve details of a ROS Service Request. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: Service Request details if blocking, otherwise `None`. `get_service_response_details`(*type*, *callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_service_response_details)[¶](#roslibpy.Ros.get_service_response_details) Retrieve details of a ROS Service Response. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: Service Response details if blocking, otherwise `None`. `get_service_type`(*service_name*, *callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_service_type)[¶](#roslibpy.Ros.get_service_type) Retrieve the type of a service in ROS. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: *str* – Service type if blocking, otherwise `None`. `get_services`(*callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_services)[¶](#roslibpy.Ros.get_services) Retrieve list of active service names in ROS. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: *list* – List of services if blocking, otherwise `None`. `get_services_for_type`(*service_type*, *callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_services_for_type)[¶](#roslibpy.Ros.get_services_for_type) Retrieve list of services in ROS matching the specified type. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: *list* – List of services matching the specified type if blocking, otherwise `None`. `get_time`(*callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_time)[¶](#roslibpy.Ros.get_time) Retrieve the current ROS time. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: [`Time`](#roslibpy.Time) – An instance of ROS Time. `get_topic_type`(*topic*, *callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_topic_type)[¶](#roslibpy.Ros.get_topic_type) Retrieve the type of a topic in ROS. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: *str* – Topic type if blocking, otherwise `None`. `get_topics`(*callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_topics)[¶](#roslibpy.Ros.get_topics) Retrieve list of topics in ROS. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: *list* – List of topics if blocking, otherwise `None`. `get_topics_for_type`(*topic_type*, *callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.get_topics_for_type)[¶](#roslibpy.Ros.get_topics_for_type) Retrieve list of topics in ROS matching the specified type. Note To make this a blocking call, pass `None` to the `callback` parameter . Returns: *list* – List of topics matching the specified type if blocking, otherwise `None`. *property* `id_counter`[¶](#roslibpy.Ros.id_counter) Generate an auto-incremental ID starting from 1. Returns: *int* – An auto-incremented ID. *property* `is_connected`[¶](#roslibpy.Ros.is_connected) Indicate if the ROS connection is open or not. Returns: *bool* – True if connected to ROS, False otherwise. `off`(*event_name*, *callback=None*)[[source]](_modules/roslibpy/ros.html#Ros.off)[¶](#roslibpy.Ros.off) Remove a callback from an arbitrary named event. Parameters: * **event_name** (`str`) – Name of the event from which to unsubscribe. * **callback** – Callable function. If `None`, all callbacks of the event will be removed. `on`(*event_name*, *callback*)[[source]](_modules/roslibpy/ros.html#Ros.on)[¶](#roslibpy.Ros.on) Add a callback to an arbitrary named event. Parameters: * **event_name** (`str`) – Name of the event to which to subscribe. * **callback** – Callable function to be executed when the event is triggered. `on_ready`(*callback*, *run_in_thread=True*)[[source]](_modules/roslibpy/ros.html#Ros.on_ready)[¶](#roslibpy.Ros.on_ready) Add a callback to be executed when the connection is established. If a connection to ROS is already available, the callback is executed immediately. Parameters: * **callback** – Callable function to be invoked when ROS connection is ready. * **run_in_thread** (`bool`) – True to run the callback in a separate thread, False otherwise. `run`(*timeout=10*)[[source]](_modules/roslibpy/ros.html#Ros.run)[¶](#roslibpy.Ros.run) Kick-starts a non-blocking event loop. Parameters: **timeout** – Timeout to wait until connection is ready. `run_forever`()[[source]](_modules/roslibpy/ros.html#Ros.run_forever)[¶](#roslibpy.Ros.run_forever) Kick-starts a blocking loop to wait for events. Depending on the implementations, and the client applications, running this might be required or not. `send_on_ready`(*message*)[[source]](_modules/roslibpy/ros.html#Ros.send_on_ready)[¶](#roslibpy.Ros.send_on_ready) Send message to ROS once the connection is established. If a connection to ROS is already available, the message is sent immediately. Parameters: **message** ([`Message`](#roslibpy.Message)) – ROS Bridge Message to send. `set_param`(*name*, *value*, *callback=None*, *errback=None*)[[source]](_modules/roslibpy/ros.html#Ros.set_param)[¶](#roslibpy.Ros.set_param) Set the value of a parameter from the ROS Parameter Server. Note To make this a blocking call, pass `None` to the `callback` parameter . `terminate`()[[source]](_modules/roslibpy/ros.html#Ros.terminate)[¶](#roslibpy.Ros.terminate) Signals the termination of the main event loop. `roslibpy.``set_rosapi_timeout`(*timeout*)[[source]](_modules/roslibpy/ros.html#set_rosapi_timeout)[¶](#roslibpy.set_rosapi_timeout) Set the default number of seconds to wait for a response before raising an exception. Parameters: **timeout** (`int`) – Duration in seconds. ### Main ROS concepts[¶](#main-ros-concepts) #### Topics[¶](#topics) ROS is a communication infrastructure. In ROS, different **nodes** communicate with each other through messages. **ROS messages** are represented by the [`Message`](#roslibpy.Message) class and are passed around via [`Topics`](#roslibpy.Topic) using a **publish/subscribe** model. *class* `roslibpy.``Message`(*values=None*)[[source]](_modules/roslibpy/core.html#Message)[¶](#roslibpy.Message) Message objects used for publishing and subscribing to/from topics. A message is fundamentally a dictionary and behaves as one. *class* `roslibpy.``Header`(*seq=None*, *stamp=None*, *frame_id=None*)[[source]](_modules/roslibpy/core.html#Header)[¶](#roslibpy.Header) Represents a message header of the ROS type std_msgs/Header. *class* `roslibpy.``Topic`(*ros*, *name*, *message_type*, *compression=None*, *latch=False*, *throttle_rate=0*, *queue_size=100*, *queue_length=0*, *reconnect_on_close=True*)[[source]](_modules/roslibpy/core.html#Topic)[¶](#roslibpy.Topic) Publish and/or subscribe to a topic in ROS. Parameters: * **ros** ([`Ros`](#roslibpy.Ros)) – Instance of the ROS connection. * **name** (`str`) – Topic name, e.g. `/cmd_vel`. * **message_type** (`str`) – Message type, e.g. `std_msgs/String`. * **compression** (`str`) – Type of compression to use, e.g. png. Defaults to None. * **throttle_rate** (`int`) – Rate (in ms between messages) at which to throttle the topics. * **queue_size** (`int`) – Queue size created at bridge side for re-publishing webtopics. * **latch** (`bool`) – True to latch the topic when publishing, False otherwise. * **queue_length** (`int`) – Queue length at bridge side used when subscribing. * **reconnect_on_close** (`bool`) – Reconnect topic (both publisher & subscriber) on reconnection. `advertise`()[[source]](_modules/roslibpy/core.html#Topic.advertise)[¶](#roslibpy.Topic.advertise) Register as a publisher for the topic. *property* `is_advertised`[¶](#roslibpy.Topic.is_advertised) Indicate if the topic is currently advertised or not. Returns: *bool* – True if advertised as publisher of this topic, False otherwise. *property* `is_subscribed`[¶](#roslibpy.Topic.is_subscribed) Indicate if the topic is currently subscribed or not. Returns: *bool* – True if subscribed to this topic, False otherwise. `publish`(*message*)[[source]](_modules/roslibpy/core.html#Topic.publish)[¶](#roslibpy.Topic.publish) Publish a message to the topic. Parameters: **message** ([`Message`](#roslibpy.Message)) – ROS Bridge Message to publish. `subscribe`(*callback*)[[source]](_modules/roslibpy/core.html#Topic.subscribe)[¶](#roslibpy.Topic.subscribe) Register a subscription to the topic. Every time a message is published for the given topic, the callback will be called with the message object. Parameters: **callback** – Function to be called when messages of this topic are published. `unadvertise`()[[source]](_modules/roslibpy/core.html#Topic.unadvertise)[¶](#roslibpy.Topic.unadvertise) Unregister as a publisher for the topic. `unsubscribe`()[[source]](_modules/roslibpy/core.html#Topic.unsubscribe)[¶](#roslibpy.Topic.unsubscribe) Unregister from a subscribed the topic. #### Services[¶](#services) Besides the publish/subscribe model used with topics, ROS offers a request/response model via [`Services`](#roslibpy.Service). *class* `roslibpy.``Service`(*ros*, *name*, *service_type*, *reconnect_on_close=True*)[[source]](_modules/roslibpy/core.html#Service)[¶](#roslibpy.Service) Client/server of ROS services. This class can be used both to consume other ROS services as a client, or to provide ROS services as a server. Parameters: * **ros** ([`Ros`](#roslibpy.Ros)) – Instance of the ROS connection. * **name** (`str`) – Service name, e.g. `/add_two_ints`. * **service_type** (`str`) – Service type, e.g. `rospy_tutorials/AddTwoInts`. `advertise`(*callback*)[[source]](_modules/roslibpy/core.html#Service.advertise)[¶](#roslibpy.Service.advertise) Start advertising the service. This turns the instance from a client into a server. The callback will be invoked with every request that is made to the service. If the service is already advertised, this call does nothing. Parameters: **callback** – Callback invoked on every service call. It should accept two parameters: service_request and service_response. It should return True if executed correctly, otherwise False. `call`(*request*, *callback=None*, *errback=None*, *timeout=None*)[[source]](_modules/roslibpy/core.html#Service.call)[¶](#roslibpy.Service.call) Start a service call. Note The service can be used either as blocking or non-blocking. If the `callback` parameter is `None`, then the call will block until receiving a response. Otherwise, the service response will be returned in the callback. Parameters: * **request** ([`ServiceRequest`](#roslibpy.ServiceRequest)) – Service request. * **callback** – Callback invoked on successful execution. * **errback** – Callback invoked on error. * **timeout** – Timeout for the operation, in seconds. Only used if blocking. Returns: *object* – Service response if used as a blocking call, otherwise `None`. *property* `is_advertised`[¶](#roslibpy.Service.is_advertised) Service servers are registered as advertised on ROS. This class can be used to be a service client or a server. Returns: *bool* – True if this is a server, False otherwise. `unadvertise`()[[source]](_modules/roslibpy/core.html#Service.unadvertise)[¶](#roslibpy.Service.unadvertise) Unregister as a service server. *class* `roslibpy.``ServiceRequest`(*values=None*)[[source]](_modules/roslibpy/core.html#ServiceRequest)[¶](#roslibpy.ServiceRequest) Request for a service call. *class* `roslibpy.``ServiceResponse`(*values=None*)[[source]](_modules/roslibpy/core.html#ServiceResponse)[¶](#roslibpy.ServiceResponse) Response returned from a service call. #### Parameter server[¶](#parameter-server) ROS provides a parameter server to share data among different nodes. This service can be accessed via the [`Param`](#roslibpy.Param) class. *class* `roslibpy.``Param`(*ros*, *name*)[[source]](_modules/roslibpy/core.html#Param)[¶](#roslibpy.Param) A ROS parameter. Parameters: * **ros** ([`Ros`](#roslibpy.Ros)) – Instance of the ROS connection. * **name** (`str`) – Parameter name, e.g. `max_vel_x`. `delete`(*callback=None*, *errback=None*, *timeout=None*)[[source]](_modules/roslibpy/core.html#Param.delete)[¶](#roslibpy.Param.delete) Delete the parameter. Note This method can be used either as blocking or non-blocking. If the `callback` parameter is `None`, the call will block until completion. Parameters: * **callback** – Callable function to be invoked when the operation is completed. * **errback** – Callback invoked on error. * **timeout** – Timeout for the operation, in seconds. Only used if blocking. `get`(*callback=None*, *errback=None*, *timeout=None*)[[source]](_modules/roslibpy/core.html#Param.get)[¶](#roslibpy.Param.get) Fetch the current value of the parameter. Note This method can be used either as blocking or non-blocking. If the `callback` parameter is `None`, the call will block and return the parameter value. Otherwise, the parameter value will be passed on to the callback. Parameters: * **callback** – Callable function to be invoked when the operation is completed. * **errback** – Callback invoked on error. * **timeout** – Timeout for the operation, in seconds. Only used if blocking. Returns: *object* – Parameter value if used as a blocking call, otherwise `None`. `set`(*value*, *callback=None*, *errback=None*, *timeout=None*)[[source]](_modules/roslibpy/core.html#Param.set)[¶](#roslibpy.Param.set) Set a new value to the parameter. Note This method can be used either as blocking or non-blocking. If the `callback` parameter is `None`, the call will block until completion. Parameters: * **callback** – Callable function to be invoked when the operation is completed. * **errback** – Callback invoked on error. * **timeout** – Timeout for the operation, in seconds. Only used if blocking. #### Time[¶](#time) To represent time, there is the concept of ROS time primitive type, which consists of two integers: seconds since epoch and nanoseconds since seconds. *class* `roslibpy.``Time`(*secs*, *nsecs*)[[source]](_modules/roslibpy/core.html#Time)[¶](#roslibpy.Time) Represents ROS time with two integers: seconds since epoch and nanoseconds since seconds. *static* `from_sec`(*float_secs*)[[source]](_modules/roslibpy/core.html#Time.from_sec)[¶](#roslibpy.Time.from_sec) Create new Time instance from a float seconds representation (e.g. `time.time()`). `is_zero`()[[source]](_modules/roslibpy/core.html#Time.is_zero)[¶](#roslibpy.Time.is_zero) Return `True` if zero (secs and nsecs) otherwise `False`. *static* `now`()[[source]](_modules/roslibpy/core.html#Time.now)[¶](#roslibpy.Time.now) Create new Time instance from the current system time (not ROS time). *property* `nsecs`[¶](#roslibpy.Time.nsecs) Nanoseconds since seconds. *property* `secs`[¶](#roslibpy.Time.secs) Seconds since epoch. `to_nsec`()[[source]](_modules/roslibpy/core.html#Time.to_nsec)[¶](#roslibpy.Time.to_nsec) Return time as nanoseconds from epoch. `to_sec`()[[source]](_modules/roslibpy/core.html#Time.to_sec)[¶](#roslibpy.Time.to_sec) Return time as float seconds representation (same as `time.time()`). ### Actionlib[¶](#actionlib) Another way to interact with ROS is through the **actionlib** stack. Actions in ROS allow to execute preemptable tasks, i.e. tasks that can be interrupted by the client. Actions are used via the [`ActionClient`](#roslibpy.actionlib.ActionClient) to which [`Goals`](#roslibpy.actionlib.Goal) can be added. Each goal emits events that can be listened to in order to react to the updates from the action server. There are four events emmitted: **status**, **result**, **feedback**, and **timeout**. *class* `roslibpy.actionlib.``Goal`(*action_client*, *goal_message*)[[source]](_modules/roslibpy/actionlib.html#Goal)[¶](#roslibpy.actionlib.Goal) Goal for an action server. After an event has been added to an action client, it will emit different events to indicate its progress: * `status`: fires to notify clients on the current state of the goal. * `feedback`: fires to send clients periodic auxiliary information of the goal. * `result`: fires to send clients the result upon completion of the goal. * `timeout`: fires when the goal did not complete in the specified timeout window. Parameters: * **action_client** ([`ActionClient`](#roslibpy.actionlib.ActionClient)) – Instance of the action client associated with the goal. * **goal_message** ([`Message`](#roslibpy.Message)) – Goal for the action server. `cancel`()[[source]](_modules/roslibpy/actionlib.html#Goal.cancel)[¶](#roslibpy.actionlib.Goal.cancel) Cancel the current goal. *property* `is_finished`[¶](#roslibpy.actionlib.Goal.is_finished) Indicate if the goal is finished or not. Returns: *bool* – True if finished, False otherwise. `send`(*result_callback=None*, *timeout=None*)[[source]](_modules/roslibpy/actionlib.html#Goal.send)[¶](#roslibpy.actionlib.Goal.send) Send goal to the action server. Parameters: * **timeout** (`int`) – Timeout for the goal’s result expressed in seconds. * **callback** (`callable`) – Function to be called when a result is received. * **It is a shorthand for hooking on the ``result`` event.** `wait`(*timeout=None*)[[source]](_modules/roslibpy/actionlib.html#Goal.wait)[¶](#roslibpy.actionlib.Goal.wait) Block until the result is available. If `timeout` is `None`, it will wait indefinitely. Parameters: **timeout** (`int`) – Timeout to wait for the result expressed in seconds. Returns: Result of the goal. *class* `roslibpy.actionlib.``ActionClient`(*ros*, *server_name*, *action_name*, *timeout=None*, *omit_feedback=False*, *omit_status=False*, *omit_result=False*)[[source]](_modules/roslibpy/actionlib.html#ActionClient)[¶](#roslibpy.actionlib.ActionClient) Client to use ROS actions. Parameters: * **ros** ([`Ros`](#roslibpy.Ros)) – Instance of the ROS connection. * **server_name** (`str`) – Action server name, e.g. `/fibonacci`. * **action_name** (`str`) – Action message name, e.g. `actionlib_tutorials/FibonacciAction`. * **timeout** (`int`) – **Deprecated.** Connection timeout, expressed in seconds. `add_goal`(*goal*)[[source]](_modules/roslibpy/actionlib.html#ActionClient.add_goal)[¶](#roslibpy.actionlib.ActionClient.add_goal) Add a goal to this action client. Parameters: **goal** ([`Goal`](#roslibpy.actionlib.Goal)) – Goal to add. `cancel`()[[source]](_modules/roslibpy/actionlib.html#ActionClient.cancel)[¶](#roslibpy.actionlib.ActionClient.cancel) Cancel all goals associated with this action client. `dispose`()[[source]](_modules/roslibpy/actionlib.html#ActionClient.dispose)[¶](#roslibpy.actionlib.ActionClient.dispose) Unsubscribe and unadvertise all topics associated with this action client. *class* `roslibpy.actionlib.``SimpleActionServer`(*ros*, *server_name*, *action_name*)[[source]](_modules/roslibpy/actionlib.html#SimpleActionServer)[¶](#roslibpy.actionlib.SimpleActionServer) Implementation of the simple action server. The server emits the following events: * `goal`: fires when a new goal has been received by the server. * `cancel`: fires when the client has requested the cancellation of the action. Parameters: * **ros** ([`Ros`](#roslibpy.Ros)) – Instance of the ROS connection. * **server_name** (`str`) – Action server name, e.g. `/fibonacci`. * **action_name** (`str`) – Action message name, e.g. `actionlib_tutorials/FibonacciAction`. `is_preempt_requested`()[[source]](_modules/roslibpy/actionlib.html#SimpleActionServer.is_preempt_requested)[¶](#roslibpy.actionlib.SimpleActionServer.is_preempt_requested) Indicate whether the client has requested preemption of the current goal. `send_feedback`(*feedback*)[[source]](_modules/roslibpy/actionlib.html#SimpleActionServer.send_feedback)[¶](#roslibpy.actionlib.SimpleActionServer.send_feedback) Send feedback. Parameters: **feedback** (`dict`) – Dictionary of key/values of the feedback message. `set_preempted`()[[source]](_modules/roslibpy/actionlib.html#SimpleActionServer.set_preempted)[¶](#roslibpy.actionlib.SimpleActionServer.set_preempted) Set the current action to preempted (cancelled). `set_succeeded`(*result*)[[source]](_modules/roslibpy/actionlib.html#SimpleActionServer.set_succeeded)[¶](#roslibpy.actionlib.SimpleActionServer.set_succeeded) Set the current action state to succeeded. Parameters: **result** (`dict`) – Dictionary of key/values to set as the result of the action. `start`(*action_callback*)[[source]](_modules/roslibpy/actionlib.html#SimpleActionServer.start)[¶](#roslibpy.actionlib.SimpleActionServer.start) Start the action server. Parameters: * **action_callback** – Callable function to be invoked when a new goal is received. * **It takes one paramter containing the goal message.** *class* `roslibpy.actionlib.``GoalStatus`[[source]](_modules/roslibpy/actionlib.html#GoalStatus)[¶](#roslibpy.actionlib.GoalStatus) Valid goal statuses. ### TF[¶](#tf) ROS provides a very powerful transform library called [TF2](http://wiki.ros.org/tf2), which lets the user keep track of multiple coordinate frames over time. The **roslibpy** library offers access to it through the [tf2_web_republisher](http://wiki.ros.org/tf2_web_republisher) via the [`TFClient`](#roslibpy.tf.TFClient) class. *class* `roslibpy.tf.``TFClient`(*ros*, *fixed_frame='/base_link'*, *angular_threshold=2.0*, *translation_threshold=0.01*, *rate=10.0*, *update_delay=50*, *topic_timeout=2000.0*, *server_name='/tf2_web_republisher'*, *repub_service_name='/republish_tfs'*)[[source]](_modules/roslibpy/tf.html#TFClient)[¶](#roslibpy.tf.TFClient) A TF Client that listens to TFs from tf2_web_republisher. Parameters: * **ros** ([`Ros`](#roslibpy.Ros)) – Instance of the ROS connection. * **fixed_frame** (`str`) – Fixed frame, e.g. `/base_link`. * **angular_threshold** (`float`) – Angular threshold for the TF republisher. * **translation_threshold** (`float`) – Translation threshold for the TF republisher. * **rate** (`float`) – Rate for the TF republisher. * **update_delay** (`int`) – Time expressed in milliseconds to wait after a new subscription before update TFs. * **topic_timeout** (`int`) – Timeout parameter for the TF republisher expressed in milliseconds. * **repub_service_name** (`str`) – Name of the republish tfs service, e.g. `/republish_tfs`. `dispose`()[[source]](_modules/roslibpy/tf.html#TFClient.dispose)[¶](#roslibpy.tf.TFClient.dispose) Unsubscribe and unadvertise all topics associated with this instance. `subscribe`(*frame_id*, *callback*)[[source]](_modules/roslibpy/tf.html#TFClient.subscribe)[¶](#roslibpy.tf.TFClient.subscribe) Subscribe to the given TF frame. Parameters: * **frame_id** (`str`) – TF frame identifier to subscribe to. * **callback** (`callable`) – A callable functions receiving one parameter with transform data. `unsubscribe`(*frame_id*, *callback*)[[source]](_modules/roslibpy/tf.html#TFClient.unsubscribe)[¶](#roslibpy.tf.TFClient.unsubscribe) Unsubscribe from the given TF frame. Parameters: * **frame_id** (`str`) – TF frame identifier to unsubscribe from. * **callback** (`callable`) – The callback function to remove. `update_goal`()[[source]](_modules/roslibpy/tf.html#TFClient.update_goal)[¶](#roslibpy.tf.TFClient.update_goal) Send a new service request to the tf2_web_republisher based on the current list of TFs. Contributor’s Guide[¶](#contributor-s-guide) --- Contributions are always welcome and greatly appreciated! ### Code contributions[¶](#code-contributions) We love pull requests from everyone! Here’s a quick guide to improve the code: 1. Fork [the repository](https://github.com/gramaziokohler/roslibpy) and clone the fork. 2. Create a virtual environment using your tool of choice (e.g. `virtualenv`, `conda`, etc). 3. Install development dependencies: ``` pip install -r requirements-dev.txt ``` 4. Run the docker container: ``` docker run -d -p 9090:9090 --name roslibpy_integration_tests gramaziokohler/integration-tests-bridge /bin/bash -c "roslaunch /integration-tests.launch" ``` 5. Make sure all tests pass: ``` invoke test ``` 6. Start making your changes to the **main** branch (or branch off of it). 7. Make sure all tests still pass: ``` invoke test ``` 8. Stop your docker container: ``` docker stop roslibpy_integration_tests ``` 9. Add yourself to `AUTHORS.rst`. 10. Commit your changes and push your branch to GitHub. 11. Create a [pull request](https://help.github.com/articles/about-pull-requests/) through the GitHub website. During development, use [pyinvoke](http://docs.pyinvoke.org/) tasks on the command prompt to ease recurring operations: * `invoke clean`: Clean all generated artifacts. * `invoke check`: Run various code and documentation style checks. * `invoke docs`: Generate documentation. * `invoke test`: Run all tests and checks in one swift command. * `invoke`: Show available tasks. ### Documentation improvements[¶](#documentation-improvements) We could always use more documentation, whether as part of the introduction/examples/usage documentation or API documentation in docstrings. Documentation is written in [reStructuredText](http://docutils.sourceforge.net/rst.html) and use [Sphinx](http://sphinx-doc.org/index.html) to generate the HTML output. Once you made the documentation changes locally, run the documentation generation: ``` invoke docs ``` ### Bug reports[¶](#bug-reports) When [reporting a bug](https://github.com/gramaziokohler/roslibpy/issues) please include: > * Operating system name and version. > * ROS version. > * Any details about your local setup that might be helpful in troubleshooting. > * Detailed steps to reproduce the bug. ### Feature requests and feedback[¶](#feature-requests-and-feedback) The best way to send feedback is to file an issue on [Github](https://github.com/gramaziokohler/roslibpy/issues). If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. Authors[¶](#authors) --- * <NAME> Research [@gramaziokohler](https://github.com/gramaziokohler) * <NAME> <[<EMAIL>](mailto:casas%40arch.ethz.ch)> [@gonzalocasas](https://github.com/gonzalocasas) * <NAME> [@ipa-mdl](https://github.com/ipa-mdl) * <NAME> [@beverlylytle](https://github.com/beverlylytle) * <NAME> [@jeandeaual](https://github.com/jeandeaual) * <NAME> [@obi-t4](https://github.com/obi-t4) * <NAME> [@MisterOwlPT](https://github.com/MisterOwlPT) * <NAME> [@DomenicP](https://github.com/DomenicP) Changelog[¶](#changelog) --- All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ### 1.5.0[¶](#section-1) **Added** * Added a wait event to close on IronPython to ensure the close request is sent before returning. **Changed** **Fixed** * Fixed reconnection behavior on IronPython which would trigger reconnects even after a manual disconnect. **Deprecated** **Removed** ### 1.4.2[¶](#section-2) **Added** **Changed** * Added `tls` to the twisted requirement (#111). **Fixed** **Deprecated** **Removed** ### 1.4.1[¶](#section-3) **Added** **Changed** **Fixed** * Fixed bug with action client/server and now they work as expected. * Fixed Python 2.7 incompatibilities introduced in 1.4.0. **Deprecated** **Removed** ### 1.4.0[¶](#section-4) **Added** **Changed** * Switched to `black` for python code formatting. * Fix incompatible settings between `black` and `flake8`. * Updated Github Actions workflows to remove python 3.6 builds. * Replaced occurrences of `raise Exception` with more specific `Exception` subclasses. **Fixed** **Deprecated** **Removed** ### 1.3.0[¶](#section-5) **Added** * Added function to set the default timeout value. * Added ROS host and port parameters to the command-line interface. **Fixed** * Fixed #87 where a goal could be marked as terminal on result alone rather than both result and status. * Ensure input of `Time` is always two integers. ### 1.2.1[¶](#section-6) **Added** **Changed** **Fixed** * Fixed blocking issues on the Twisted/Autobahn-based implementation of websockets. **Deprecated** **Removed** ### 1.2.0[¶](#section-7) **Changed** * Changed behavior: Advertising services automatically reconnect when websockets is reconnected. * References to ROS master change to ROS. **Added** * Added `Header` and `Time` data types. * Added ROS API method to retrieve current ROS time: `ros.get_time`. ### 1.1.0[¶](#section-8) **Added** * Added `set_initial_delay`, `set_max_delay` and `set_max_retries` to `RosBridgeClientFactory` to control reconnection parameters. * Added `closing` event to `Ros` class that gets triggered right before closing the connection. ### 1.0.0[¶](#section-9) **Changed** * Changed behavior: Topics automatically reconnect when websockets is reconnected. **Added** * Added blocking behavior to more ROS API methods: `ros.get_nodes` and `ros.get_node_details`. * Added reconnection support to IronPython implementation of websockets. * Added automatic topic reconnection support for both subscribers and publishers. **Fixed** * Fixed reconnection issues on the Twisted/Autobahn-based implementation of websockets. ### 0.7.1[¶](#section-10) **Fixed** * Fixed blocking service calls for Mac OS. ### 0.7.0[¶](#section-11) **Changed** * The non-blocking event loop runner `run()` now defaults to 10 seconds timeout before raising an exception. **Added** * Added blocking behavior to ROS API methods, e.g. `ros.get_topics`. * Added command-line mode to ROS API, e.g. `roslibpy topic list`. * Added blocking behavior to the `Param` class. * Added parameter manipulation methods to `Ros` class: `get_param`, `set_param`, `delete_param`. ### 0.6.0[¶](#section-12) **Changed** * For consistency, `timeout` parameter of `Goal.send()` is now expressed in **seconds**, instead of milliseconds. **Deprecated** * The `timeout` parameter of `ActionClient()` is ignored in favor of blocking until the connection is established. **Fixed** * Raise exceptions when timeouts expire on ROS connection or service calls. **Added** * Support for calling a function in a thread from the Ros client. * Added implementation of a Simple Action Server. ### 0.5.0[¶](#section-13) **Changed** * The non-blocking event loop runner now waits for the connection to be established in order to minimize the need for `on_ready` handlers. **Added** * Support blocking and non-blocking service calls. **Fixed** * Fixed an internal unsubscribing issue. ### 0.4.1[¶](#section-14) **Fixed** * Resolve reconnection issues. ### 0.4.0[¶](#section-15) **Added** * Add a non-blocking event loop runner. ### 0.3.0[¶](#section-16) **Changed** * Unsubscribing from a listener no longer requires the original callback to be passed. ### 0.2.1[¶](#section-17) **Fixed** * Fix JSON serialization error on TF Client (on Python 3.x). ### 0.2.0[¶](#section-18) **Added** * Add support for IronPython 2.7. **Changed** * Handler `on_ready` now defaults to run the callback in thread. **Deprecated** * Rename `run_event_loop` to the more fitting `run_forever`. ### 0.1.1[¶](#section-19) **Fixed** * Minimal documentation fixes. ### 0.1.0[¶](#section-20) **Added** * Initial version. Indices and tables[¶](#indices-and-tables) --- * [Index](genindex.html) * [Module Index](py-modindex.html) * [Search Page](search.html)
web3-brc
npm
JavaScript
Ethereum JavaScript API === This is the Ethereum compatible [JavaScript API](https://github.com/ethereum/wiki/wiki/JavaScript-API) which implements the [Generic JSON RPC](https://github.com/ethereum/wiki/wiki/JSON-RPC) spec. It's available on npm as a node module, for Bower and component as embeddable scripts, and as a meteor.js package. You need to run a local Ethereum node to use this library. [Documentation](https://github.com/ethereum/wiki/wiki/JavaScript-API) Table of Contents --- * [Installation](#installation) + [Node.js](#nodejs) + [Yarn](#yarn) + [Meteor.js](#meteorjs) + [As a Browser module](#as-a-browser-module) * [Usage](#usage) + [Migration from 0.13.0 to 0.14.0](#migration-from-0130-to-0140) * [Contribute!](#contribute) + [Requirements](#requirements) + [Building (gulp)](#building-gulp) + [Testing (mocha)](#testing-mocha) + [Community](#community) + [Other implementations](#other-implementations) * [License](#license) Installation --- ### Node.js ``` npm install web3 ``` ### Yarn ``` yarn add web3 ``` ### Meteor.js ``` meteor add ethereum:web3 ``` ### As a Browser module CDN ``` <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.36/dist/web3.min.js" integrity="sha256-nWBTbvx<KEY> crossorigin="anonymous"></script> ``` Bower ``` bower install web3 ``` Component ``` component install ethereum/web3.js ``` * Include `web3.min.js` in your html file. (not required for the meteor package) Usage --- Use the `web3` object directly from the global namespace: ``` console.log(web3); // {eth: .., shh: ...} // It's here! ``` Set a provider (`HttpProvider`): ``` if (typeof web3 !== 'undefined') {  web3 = new Web3(web3.currentProvider);} else {  // Set the provider you want from Web3.providers  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));} ``` Set a provider (`HttpProvider` using [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication)): ``` web3.setProvider(new web3.providers.HttpProvider('http://' + BasicAuthUsername + ':' + BasicAuthPassword + '@localhost:8545')); ``` There you go, now you can use it: ``` var coinbase = web3.eth.coinbase;var balance = web3.eth.getBalance(coinbase); ``` You can find more examples in the [`example`](https://github.com/ethereum/web3.js/tree/master/example) directory. ### Migration from 0.13.0 to 0.14.0 web3.js version 0.14.0 supports [multiple instances of the web3](https://github.com/ethereum/web3.js/issues/297) object. To migrate to this version, please follow the guide: ``` -var web3 = require('web3');+var Web3 = require('web3');+var web3 = new Web3(); ``` Contribute! --- ### Requirements * Node.js * npm ``` # On Linux: sudo apt-get updatesudo apt-get install nodejssudo apt-get install npmsudo apt-get install nodejs-legacy ``` ### Building (gulp) ``` npm run-script build ``` ### Testing (mocha) ``` npm test ``` ### Community * [Gitter](https://gitter.im/ethereum/web3.js?source=orgpage) * [Forum](https://forum.ethereum.org/categories/ethereum-js) ### Other implementations * Python [Web3.py](https://github.com/ethereum/web3.py) * Haskell [hs-web3](https://github.com/airalab/hs-web3) * Java [web3j](https://github.com/web3j/web3j) * Scala [web3j-scala](https://github.com/mslinn/web3j-scala) * Purescript [purescript-web3](https://github.com/f-o-a-m/purescript-web3) * PHP [web3.php](https://github.com/sc0Vu/web3.php) * PHP [ethereum-php](https://github.com/digitaldonkey/ethereum-php) * Rust [rust-web3](https://github.com/tomusdrw/rust-web3) * Swift [web3swift](https://github.com/BANKEX/web3swift) License --- [LGPL-3.0+](https://github.com/ethereum/web3.js/blob/HEAD/LICENSE.md) © 2015 Contributors Readme --- ### Keywords * ethereum * javascript * API
aiokafka
readthedoc
Python
aiokafka 0.8.0 documentation Welcome to aiokafka’s documentation![¶](#welcome-to-aiokafka-s-documentation) === **aiokafka** is a client for the Apache Kafka distributed stream processing system using [asyncio](http://docs.python.org/3.7/library/asyncio.html). It is based on the [kafka-python](https://github.com/dpkp/kafka-python) library and reuses its internals for protocol parsing, errors, etc. The client is designed to function much like the official Java client, with a sprinkling of Pythonic interfaces. **aiokafka** can be used with 0.9+ Kafka brokers and supports fully coordinated consumer groups – i.e., dynamic partition assignment to multiple consumers in the same group. Getting started[¶](#getting-started) --- ### AIOKafkaConsumer[¶](#aiokafkaconsumer) [`AIOKafkaConsumer`](index.html#aiokafka.AIOKafkaConsumer) is a high-level message consumer, intended to operate as similarly as possible to the official Java client. Here’s a consumer example: ``` from aiokafka import AIOKafkaConsumer import asyncio async def consume(): consumer = AIOKafkaConsumer( 'my_topic', 'my_other_topic', bootstrap_servers='localhost:9092', group_id="my-group") # Get cluster layout and join group `my-group` await consumer.start() try: # Consume messages async for msg in consumer: print("consumed: ", msg.topic, msg.partition, msg.offset, msg.key, msg.value, msg.timestamp) finally: # Will leave consumer group; perform autocommit if enabled. await consumer.stop() asyncio.run(consume()) ``` Read more in [Consumer client](index.html#consumer-usage) section. ### AIOKafkaProducer[¶](#aiokafkaproducer) [`AIOKafkaProducer`](index.html#aiokafka.AIOKafkaProducer) is a high-level, asynchronous message producer. Here’s a producer example: ``` from aiokafka import AIOKafkaProducer import asyncio async def send_one(): producer = AIOKafkaProducer( bootstrap_servers='localhost:9092') # Get cluster layout and initial topic/partition leadership information await producer.start() try: # Produce message await producer.send_and_wait("my_topic", b"Super message") finally: # Wait for all pending messages to be delivered or expire. await producer.stop() asyncio.run(send_one()) ``` Read more in [Producer client](index.html#producer-usage) section. Installation[¶](#installation) --- ``` pip install aiokafka ``` Note **aiokafka** requires the [kafka-python](https://github.com/dpkp/kafka-python) library. ### Optional LZ4 install[¶](#optional-lz4-install) To enable LZ4 compression/decompression, install **aiokafka** with `lz4` extra option: > pip install ‘aiokafka[lz4]’ Note, that on **Windows** you will need Visual Studio build tools, available for download from <http://landinghub.visualstudio.com/visual-cpp-build-tools### Optional Snappy install[¶](#optional-snappy-install) 1. Download and build Snappy from <http://google.github.io/snappy/Ubuntu: ``` apt-get install libsnappy-dev ``` OSX: ``` brew install snappy ``` From Source: ``` wget https://github.com/google/snappy/tarball/master tar xzvf google-snappy-X.X.X-X-XXXXXXXX.tar.gz cd google-snappy-X.X.X-X-XXXXXXXX ./configure make sudo make install ``` 1. Install **aiokafka** with `snappy` extra option ``` pip install 'aiokafka[snappy]' ``` ### Optional zstd indtall[¶](#optional-zstd-indtall) To enable Zstandard compression/decompression, install **aiokafka** with `zstd` extra option: ``` pip install 'aiokafka[zstd]' ``` ### Optional GSSAPI install[¶](#optional-gssapi-install) To enable SASL authentication with GSSAPI, install **aiokafka** with `gssapi` extra option: ``` pip install 'aiokafka[gssapi]' ``` Source code[¶](#source-code) --- The project is hosted on [GitHub](https://github.com/aio-libs/aiokafka) Please feel free to file an issue on [bug tracker](https://github.com/aio-libs/aiokafka/issues) if you have found a bug or have some suggestion for library improvement. The library uses [Travis](https://travis-ci.com/aio-libs/aiokafka) for Continious Integration. Authors and License[¶](#authors-and-license) --- The **aiokafka** package is Apache 2 licensed and freely available. Feel free to improve this package and send a pull request to [GitHub](https://github.com/aio-libs/aiokafka). Contents: ### Producer client[¶](#producer-client) [`AIOKafkaProducer`](index.html#aiokafka.AIOKafkaProducer) is a client that publishes records to the Kafka cluster. Most simple usage would be: ``` producer = aiokafka.AIOKafkaProducer(bootstrap_servers="localhost:9092") await producer.start() try: await producer.send_and_wait("my_topic", b"Super message") finally: await producer.stop() ``` Under the hood, [`AIOKafkaProducer`](index.html#aiokafka.AIOKafkaProducer) does quite some work on message delivery including batching, retries, etc. All of it can be configured, so let’s go through some components for a better understanding of the configuration options. #### Message buffering[¶](#message-buffering) While the user would expect the example above to send `"Super message"` directly to the broker, it’s actually not sent right away, but rather added to a **buffer space**. A background task will then get batches of messages and send them to appropriate nodes in the cluster. This batching scheme allows *more throughput and more efficient compression*. To see it more clearly lets avoid the [`send_and_wait()`](index.html#aiokafka.AIOKafkaProducer.send_and_wait) shortcut: ``` # Will add the message to 1st partition's batch. If this method times out, # we can say for sure that message will never be sent. fut = await producer.send("my_topic", b"Super message", partition=1) # Message will either be delivered or an unrecoverable error will occur. # Cancelling this future will not cancel the send. msg = await fut ``` Batches themselves are created **per partition** with a maximum size of max_batch_size. Messages in a batch are strictly in append order and only 1 batch per partition is sent at a time (**aiokafka** does not support `max.inflight.requests.per.connection` option present in Java client). This makes a strict guarantee on message order in a partition. By default, a new batch is sent immediately after the previous one (even if it’s not full). If you want to reduce the number of requests you can set linger_ms to something other than 0. This will add an additional delay before sending next batch if it’s not yet full. **aiokafka** does not (yet!) support some options, supported by Java’s client: * `buffer.memory` to limit how much buffer space is used by Producer to schedule requests in *all partitions*. * `max.block.ms` to limit the amount of time [`send()`](index.html#aiokafka.AIOKafkaProducer.send) coroutine will wait for buffer append when the memory limit is reached. For now use: ``` await asyncio.wait_for(producer.send(...), timeout=timeout) ``` If your use case requires direct batching control, see [Direct batch control](#direct-batch-control). #### Retries and Message acknowledgement[¶](#retries-and-message-acknowledgement) **aiokafka** will retry most errors automatically, but only until request_timeout_ms. If a request is expired, the last error will be raised to the application. Retrying messages on application level after an error will potentially lead to duplicates, so it’s up to the user to decide. For example, if [`RequestTimedOutError`](index.html#aiokafka.errors.RequestTimedOutError) is raised, Producer can’t be sure if the Broker wrote the request or not. The acks option controls when the produce request is considered acknowledged. The most durable setting is `acks="all"`. Broker will wait for all available replicas to write the request before replying to Producer. Broker will consult it’s `min.insync.replicas` setting to know the minimal amount of replicas to write. If there’s not enough in sync replicas either [`NotEnoughReplicasError`](index.html#aiokafka.errors.NotEnoughReplicasError) or [`NotEnoughReplicasAfterAppendError`](index.html#aiokafka.errors.NotEnoughReplicasAfterAppendError) will be raised. It’s up to the user what to do in those cases, as the errors are not retriable. The default is `ack=1` setting. It will not wait for replica writes, only for Leader to write the request. The least safe is `ack=0` when there will be no acknowledgement from Broker, meaning client will never retry, as it will never see any errors. #### Idempotent produce[¶](#idempotent-produce) As of Kafka 0.11 the Brokers support idempotent producing, that will prevent the Producer from creating duplicates on retries. *aiokafka* supports this mode by passing the parameter `enable_idempotence=True` to [`AIOKafkaProducer`](index.html#aiokafka.AIOKafkaProducer): ``` producer = aiokafka.AIOKafkaProducer( bootstrap_servers='localhost:9092', enable_idempotence=True) await producer.start() try: await producer.send_and_wait("my_topic", b"Super message") finally: await producer.stop() ``` This option will change a bit the logic on message delivery: > * The above mentioned `ack="all"` will be forced. If any other value is > explicitly passed with `enable_idempotence=True` a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) will > be raised. > * I contrast to general mode, will not raise [`RequestTimedOutError`](index.html#aiokafka.errors.RequestTimedOutError) > errors and will not expire batch delivery after `request_timeout_ms` > passed. New in version 0.5.0. #### Transactional producer[¶](#transactional-producer) As of Kafka 0.11 the Brokers support transactional message producer, meaning that messages sent to one or more topics will only be visible on consumers after the transaction is committed. To use the transactional producer and the attendant APIs, you must set the `transactional_id` configuration property: ``` producer = aiokafka.AIOKafkaProducer( bootstrap_servers='localhost:9092', transactional_id="transactional_test") await producer.start() try: async with producer.transaction(): res = await producer.send_and_wait( "test-topic", b"Super transactional message") finally: await producer.stop() ``` If the transactional_id is set, idempotence is automatically enabled along with the producer configs which idempotence depends on. Further, topics which are included in transactions should be configured for durability. In particular, the `replication.factor` should be at least `3`, and the `min.insync.replicas` for these topics should be set to `2`. Finally, in order for transactional guarantees to be realized from end-to-end, the consumers must be configured to read only committed messages as well. See [Reading Transactional Messages](index.html#transactional-consume). The purpose of the transactional_id is to enable transaction recovery across multiple sessions of a single producer instance. It would typically be derived from the shard identifier in a partitioned, stateful, application. As such, it should be unique to each producer instance running within a partitioned application. Using the same transactional_id will cause the previous instance to raise an exception [`ProducerFenced`](index.html#aiokafka.errors.ProducerFenced) that is not retriable and will force it to exit. Besides, the [`transaction()`](index.html#aiokafka.AIOKafkaProducer.transaction) shortcut producer also supports a set of API’s similar to ones in Java Client. See the [`AIOKafkaProducer`](index.html#aiokafka.AIOKafkaProducer) API docs. Besides being able to commit several topics atomically, as offsets are also stored in a separate system topic it’s possible to commit a consumer offset as part of the same transaction: ``` async with producer.transaction(): commit_offsets = { TopicPartition("some-topic", 0): 100 } await producer.send_offsets_to_transaction( commit_offsets, "some-consumer-group") ``` See a more full example in [Transactional Consume-Process-Produce](index.html#transaction-example). New in version 0.5.0. #### Returned `RecordMetadata` object[¶](#returned-recordmetadata-object) After a message is sent, the user receives a [`RecordMetadata`](index.html#aiokafka.structs.RecordMetadata) object. Note In a very rare case, when Idempotent or Transactional producer is used and there was a long wait between batch initial send and a retry, producer may return `offset == -1` and `timestamp == -1` as Broker already expired the metadata for this produce sequence and only knows that it’s a duplicate due to a larger sequence present #### Direct batch control[¶](#direct-batch-control) Users who need precise control over batch flow may use the lower-level [`create_batch()`](index.html#aiokafka.AIOKafkaProducer.create_batch) and [`send_batch()`](index.html#aiokafka.AIOKafkaProducer.send_batch) interfaces: ``` # Create the batch without queueing for delivery. batch = producer.create_batch() # Populate the batch. The append() method will return metadata for the # added message or None if batch is full. for i in range(2): metadata = batch.append(value=b"msg %d" % i, key=None, timestamp=None) assert metadata is not None # Optionally close the batch to further submission. If left open, the batch # may be appended to by producer.send(). batch.close() # Add the batch to the first partition's submission queue. If this method # times out, we can say for sure that batch will never be sent. fut = await producer.send_batch(batch, "my_topic", partition=1) # Batch will either be delivered or an unrecoverable error will occur. # Cancelling this future will not cancel the send. record = await fut ``` While any number of batches may be created, only a single batch per partition is sent at a time. Additional calls to [`send_batch()`](index.html#aiokafka.AIOKafkaProducer.send_batch) against the same partition will wait for the inflight batch to be delivered before sending. Upon delivery, the `record`’s [`offset`](index.html#aiokafka.structs.RecordMetadata.offset) will match the batch’s first message. ### Consumer client[¶](#consumer-client) [`AIOKafkaConsumer`](index.html#aiokafka.AIOKafkaConsumer) is a client that consumes records from a Kafka cluster. Most simple usage would be: ``` consumer = aiokafka.AIOKafkaConsumer( "my_topic", bootstrap_servers='localhost:9092' ) await consumer.start() try: async for msg in consumer: print( "{}:{:d}:{:d}: key={} value={} timestamp_ms={}".format( msg.topic, msg.partition, msg.offset, msg.key, msg.value, msg.timestamp) ) finally: await consumer.stop() ``` Note [`msg.value`](index.html#aiokafka.structs.ConsumerRecord.value) and [`msg.key`](index.html#aiokafka.structs.ConsumerRecord.key) are raw bytes, use [`AIOKafkaConsumer`](index.html#aiokafka.AIOKafkaConsumer)’s key_deserializer and value_deserializer configuration if you need to decode them. Note [`AIOKafkaConsumer`](index.html#aiokafka.AIOKafkaConsumer) maintains TCP connections as well as a few background tasks to fetch data and coordinate assignments. Failure to call [`AIOKafkaConsumer.stop()`](index.html#aiokafka.AIOKafkaConsumer.stop) after consumer use *will leave background tasks running*. [`AIOKafkaConsumer`](index.html#aiokafka.AIOKafkaConsumer) transparently handles the failure of Kafka brokers and transparently adapts as topic partitions it fetches migrate within the cluster. It also interacts with the broker to allow groups of consumers to load balance consumption using [Consumer Groups](#consumer-groups). #### Offsets and Consumer Position[¶](#offsets-and-consumer-position) Kafka maintains a numerical [`offset`](index.html#aiokafka.structs.ConsumerRecord.offset) for each record in a partition. This [`offset`](index.html#aiokafka.structs.ConsumerRecord.offset) acts as a *unique identifier* of a record within that partition and also denotes the *position* of the consumer in the partition. For example: ``` msg = await consumer.getone() print(msg.offset) # Unique msg autoincrement ID in this topic-partition. tp = aiokafka.TopicPartition(msg.topic, msg.partition) position = await consumer.position(tp) # Position is the next fetched offset assert position == msg.offset + 1 committed = await consumer.committed(tp) print(committed) ``` Note To use the [`commit()`](index.html#aiokafka.AIOKafkaConsumer.commit) and [`committed()`](index.html#aiokafka.AIOKafkaConsumer.committed) APIs you need to set `group_id` to something other than `None`. See [consumer-groups](#consumer-groups) below. Here if the consumer is at *position* `5`, it has consumed records with *offsets* `0` through `4` and will next receive the record with *offset* `5`. There are actually two *notions of position*: * The *position* gives the offset of the next record that should be given out. It will be *one larger* than the highest offset the consumer has seen in that partition. It automatically increases every time the consumer yields messages in either [`getmany()`](index.html#aiokafka.AIOKafkaConsumer.getmany) or [`getone()`](index.html#aiokafka.AIOKafkaConsumer.getone) calls. * The *committed position* is the last offset that has been stored securely. Should the process restart, this is the offset that the consumer will start from. The consumer can either *automatically commit offsets periodically*, or it can choose to control this committed position *manually* by calling [`await consumer.commit()`](index.html#aiokafka.AIOKafkaConsumer.commit). This distinction gives the consumer control over when a record is considered consumed. It is discussed in further detail below. ##### Manual vs automatic committing[¶](#manual-vs-automatic-committing) For most simple use cases auto committing is probably the best choice: ``` consumer = AIOKafkaConsumer( "my_topic", bootstrap_servers='localhost:9092', group_id="my_group", # Consumer must be in a group to commit enable_auto_commit=True, # Is True by default anyway auto_commit_interval_ms=1000, # Autocommit every second auto_offset_reset="earliest", # If committed offset not found, start # from beginning ) await consumer.start() async for msg in consumer: # Will periodically commit returned messages. # process message pass ``` This example can have *“At least once”* [delivery semantics](https://kafka.apache.org/documentation/#semantics), but only if we process messages **one at a time**. If you want *“At least once”* semantics for batch operations you should use *manual commit*: ``` consumer = AIOKafkaConsumer( "my_topic", bootstrap_servers='localhost:9092', group_id="my_group", # Consumer must be in a group to commit enable_auto_commit=False, # Will disable autocommit auto_offset_reset="earliest", # If committed offset not found, start # from beginning ) await consumer.start() batch = [] async for msg in consumer: batch.append(msg) if len(batch) == 100: await process_msg_batch(batch) await consumer.commit() batch = [] ``` Warning When using **manual commit** it is recommended to provide a [`ConsumerRebalanceListener`](index.html#aiokafka.abc.ConsumerRebalanceListener) which will process pending messages in the batch and commit before allowing rejoin. If your group will rebalance during processing commit will fail with [`CommitFailedError`](index.html#aiokafka.errors.CommitFailedError), as partitions may have been processed by other consumer already. This example will hold on to messages until we have enough to process in bulk. The algorithm can be enhanced by taking advantage of: * [`await consumer.getmany()`](index.html#aiokafka.AIOKafkaConsumer.getmany) to avoid multiple calls to get a batch of messages. * [`await consumer.highwater(partition)`](index.html#aiokafka.AIOKafkaConsumer.highwater) to understand if we have more unconsumed messages or this one is the last one in the partition. If you want to have more control over which partition and message is committed, you can specify offset manually: ``` while True: result = await consumer.getmany(timeout_ms=10 * 1000) for tp, messages in result.items(): if messages: await process_msg_batch(messages) # Commit progress only for this partition await consumer.commit({tp: messages[-1].offset + 1}) ``` Note The committed offset should always be the offset of the next message that your application will read. Thus, when calling [`await consumer.commit(offset)`](index.html#aiokafka.AIOKafkaConsumer.commit) you should add one to the offset of the last message processed. Here we process a batch of messages per partition and commit not all consumed *offsets*, but only for the partition, we processed. ##### Controlling The Consumer’s Position[¶](#controlling-the-consumer-s-position) In most use cases the consumer will simply consume records from beginning to end, periodically committing its position (either automatically or manually). If you only want your consumer to process newest messages, you can ask it to start from `latest` offset: ``` consumer = AIOKafkaConsumer( "my_topic", bootstrap_servers='localhost:9092', auto_offset_reset="latest", ) await consumer.start() async for msg in consumer: # process message pass ``` Note If you have a valid **committed position** consumer will use that. `auto_offset_reset` will only be used when the position is invalid. Kafka also allows the consumer to manually control its position, moving forward or backwards in a partition at will using [`AIOKafkaConsumer.seek()`](index.html#aiokafka.AIOKafkaConsumer.seek). For example, you can re-consume records: ``` msg = await consumer.getone() tp = TopicPartition(msg.topic, msg.partition) consumer.seek(tp, msg.offset) msg2 = await consumer.getone() assert msg2 == msg ``` Also you can combine it with `offset_for_times` API to query to specific offsets based on timestamp. There are several use cases where manually controlling the consumer’s position can be useful. *One case* is for **time-sensitive record processing** it may make sense for a consumer that falls far enough behind to not attempt to catch up processing all records, but rather just skip to the most recent records. Or you can use `offsets_for_times` API to get the offsets after certain timestamp. *Another use case* is for a **system that maintains local state**. In such a system the consumer will want to initialize its position on startup to whatever is contained in the local store. Likewise, if the local state is destroyed (say because the disk is lost) the state may be recreated on a new machine by re-consuming all the data and recreating the state (assuming that Kafka is retaining sufficient history). See also related configuration params and API docs: * auto_offset_reset config option to set behaviour in case the position is either undefined or incorrect. * [`seek()`](index.html#aiokafka.AIOKafkaConsumer.seek), [`seek_to_beginning()`](index.html#aiokafka.AIOKafkaConsumer.seek_to_beginning), [`seek_to_end()`](index.html#aiokafka.AIOKafkaConsumer.seek_to_end) API’s to force position change on partition(‘s). * [`offsets_for_times()`](index.html#aiokafka.AIOKafkaConsumer.offsets_for_times), [`beginning_offsets()`](index.html#aiokafka.AIOKafkaConsumer.beginning_offsets), [`end_offsets()`](index.html#aiokafka.AIOKafkaConsumer.end_offsets) API’s to query offsets for partitions even if they are not assigned to this consumer. ##### Storing Offsets Outside Kafka[¶](#storing-offsets-outside-kafka) Storing *offsets* in Kafka is optional, you can store offsets in another place and use [`seek()`](index.html#aiokafka.AIOKafkaConsumer.seek) API to start from saved position. The primary use case for this is allowing the application to store both the offset and the results of the consumption in the same system in a way that both the results and offsets are stored atomically. For example, if we save aggregated by key counts in Redis: ``` import json from collections import Counter redis = await aioredis.create_redis(("localhost", 6379)) REDIS_HASH_KEY = "aggregated_count:my_topic:0" tp = TopicPartition("my_topic", 0) consumer = AIOKafkaConsumer( bootstrap_servers='localhost:9092', enable_auto_commit=False, ) await consumer.start() consumer.assign([tp]) # Load initial state of aggregation and last processed offset offset = -1 counts = Counter() initial_counts = await redis.hgetall(REDIS_HASH_KEY, encoding="utf-8") for key, state in initial_counts.items(): state = json.loads(state) offset = max([offset, state['offset']]) counts[key] = state['count'] # Same as with manual commit, you need to fetch next message, so +1 consumer.seek(tp, offset + 1) async for msg in consumer: key = msg.key.decode("utf-8") counts[key] += 1 value = json.dumps({ "count": counts[key], "offset": msg.offset }) await redis.hset(REDIS_HASH_KEY, key, value) ``` So to save results outside of Kafka you need to: * Configure: `enable.auto.commit=false` * Use the offset provided with each [`ConsumerRecord`](index.html#aiokafka.structs.ConsumerRecord) to save your position * On restart or rebalance restore the position of the consumer using [`seek()`](index.html#aiokafka.AIOKafkaConsumer.seek) This is not always possible, but when it is it will make the consumption fully atomic and give *exactly once* semantics that are stronger than the default *at-least once* semantics you get with Kafka’s offset commit functionality. This type of usage is simplest when the partition assignment is also done manually (like we did above). If the partition assignment is done automatically special care is needed to handle the case where partition assignments change. See [Local state and storing offsets outside of Kafka](index.html#local-state-consumer-example) example for more details. #### Consumer Groups and Topic Subscriptions[¶](#consumer-groups-and-topic-subscriptions) Kafka uses the concept of **Consumer Groups** to allow a pool of processes to divide the work of consuming and processing records. These processes can either be running on the same machine or they can be distributed over many machines to provide scalability and fault tolerance for processing. All [`AIOKafkaConsumer`](index.html#aiokafka.AIOKafkaConsumer) instances sharing the same `group_id` will be part of the same **Consumer Group**: ``` # Process 1 consumer = AIOKafkaConsumer( "my_topic", bootstrap_servers='localhost:9092', group_id="MyGreatConsumerGroup" # This will enable Consumer Groups ) await consumer.start() async for msg in consumer: print("Process %s consumed msg from partition %s" % ( os.getpid(), msg.partition)) # Process 2 consumer2 = AIOKafkaConsumer( "my_topic", bootstrap_servers='localhost:9092', group_id="MyGreatConsumerGroup" # This will enable Consumer Groups ) await consumer2.start() async for msg in consumer2: print("Process %s consumed msg from partition %s" % ( os.getpid(), msg.partition)) ``` Each consumer in a group can dynamically set the list of topics it wants to subscribe to through [`subscribe()`](index.html#aiokafka.AIOKafkaConsumer.subscribe) call. Kafka will deliver each message in the subscribed topics to only one of the processes in each consumer group. This is achieved by balancing the *partitions* between all members in the consumer group so that **each partition is assigned to exactly one consumer** in the group. So if there is a topic with *four* partitions and a consumer group with *two* processes, each process would consume from *two* partitions. Membership in a consumer group is maintained dynamically: if a process fails, the partitions assigned to it *will be reassigned to other consumers* in the same group. Similarly, if a new consumer joins the group, partitions will be *moved from existing consumers to the new one*. This is known as **rebalancing the group**. Note Conceptually you can think of a **Consumer Group** as being a *single logical subscriber* that happens to be made up of multiple processes. In addition, when group reassignment happens automatically, consumers can be notified through a [`ConsumerRebalanceListener`](index.html#aiokafka.abc.ConsumerRebalanceListener), which allows them to finish necessary application-level logic such as state cleanup, manual offset commits, etc. See [`subscribe()`](index.html#aiokafka.AIOKafkaConsumer.subscribe) docs for more details. Warning Be careful with [`ConsumerRebalanceListener`](index.html#aiokafka.abc.ConsumerRebalanceListener) to avoid deadlocks. The Consumer will await the defined handlers and will block subsequent calls to [`getmany()`](index.html#aiokafka.AIOKafkaConsumer.getmany) and [`getone()`](index.html#aiokafka.AIOKafkaConsumer.getone). For example this code will deadlock: ``` lock = asyncio.Lock() consumer = AIOKafkaConsumer(...) class MyRebalancer(aiokafka.ConsumerRebalanceListener): async def on_partitions_revoked(self, revoked): async with lock: pass async def on_partitions_assigned(self, assigned): pass async def main(): consumer.subscribe("topic", listener=MyRebalancer()) while True: async with lock: msgs = await consumer.getmany(timeout_ms=1000) # process messages ``` You need to put [`consumer.getmany(timeout_ms=1000)`](index.html#aiokafka.AIOKafkaConsumer.getmany) call outside of the lock. For more information on how **Consumer Groups** are organized see [Official Kafka Docs](https://kafka.apache.org/documentation/#intro_consumers). ##### Topic subscription by pattern[¶](#topic-subscription-by-pattern) [`AIOKafkaConsumer`](index.html#aiokafka.AIOKafkaConsumer) performs periodic metadata refreshes in the background and will notice when new partitions are added to one of the subscribed topics or when a new topic matching a *subscribed regex* is created. For example: ``` consumer = AIOKafkaConsumer( bootstrap_servers='localhost:9092', metadata_max_age_ms=30000, # This controls the polling interval ) await consumer.start() consumer.subscribe(pattern="^MyGreatTopic-.*$") async for msg in consumer: # Will detect metadata changes print("Consumed msg %s %s %s" % (msg.topic, msg.partition, msg.value)) ``` Here, the consumer will automatically detect new topics like `MyGreatTopic-1` or `MyGreatTopic-2` and start consuming them. If you use [Consumer Groups](consumer-groups) the group’s *Leader* will trigger a **group rebalance** when it notices metadata changes. It’s because only the *Leader* has full knowledge of which topics are assigned to the group. ##### Manual partition assignment[¶](#manual-partition-assignment) It is also possible for the consumer to manually assign specific partitions using [`assign([tp1, tp2])`](index.html#aiokafka.AIOKafkaConsumer.assign). In this case, dynamic partition assignment and consumer group coordination will be disabled. For example: ``` consumer = AIOKafkaConsumer( bootstrap_servers='localhost:9092' ) tp1 = TopicPartition("my_topic", 1) tp2 = TopicPartition("my_topic", 2) consumer.assign([tp1, tp2]) async for msg in consumer: print("Consumed msg %s %s %s", msg.topic, msg.partition, msg.value) ``` `group_id` can still be used for committing position, but be careful to avoid **collisions** with multiple instances sharing the same group. It is not possible to mix manual partition assignment [`assign()`](index.html#aiokafka.AIOKafkaConsumer.assign) and topic subscription [`subscribe()`](index.html#aiokafka.AIOKafkaConsumer.subscribe). An attempt to do so will result in an [`IllegalStateError`](index.html#aiokafka.errors.IllegalStateError). ##### Consumption Flow Control[¶](#consumption-flow-control) By default Consumer will fetch from all partitions, effectively giving these partitions the same priority. However in some cases, you would want for some partitions to have higher priority (say they have more lag and you want to catch up). For example: ``` consumer = AIOKafkaConsumer("my_topic", ...) partitions = [] # Fetch all partitions on first request while True: msgs = await consumer.getmany(*partitions) # process messages await process_messages(msgs) # Prioritize partitions, that lag behind. partitions = [] for partition in consumer.assignment(): highwater = consumer.highwater(partition) position = await consumer.position(partition) position_lag = highwater - position timestamp = consumer.last_poll_timestamp(partition) time_lag = time.time() * 1000 - timestamp if position_lag > POSITION_THRESHOLD or time_lag > TIME_THRESHOLD: partitions.append(partition) ``` Note This interface differs from [`pause()`](index.html#aiokafka.AIOKafkaConsumer.pause) / [`resume()`](index.html#aiokafka.AIOKafkaConsumer.resume) interface of [kafka-python](https://github.com/dpkp/kafka-python) and Java clients. Here we will consume all partitions if they do not lag behind, but if some go above a certain *threshold*, we will consume them to catch up. This can very well be used in a case where some consumer died and this consumer took over its partitions, that are now lagging behind. Some things to note about it: * There may be a slight **pause in consumption** if you change the partitions you are fetching. This can happen when Consumer requests a fetch for partitions that have no data available. Consider setting a relatively low `fetch_max_wait_ms` to avoid this. * The `async for` interface can not be used with explicit partition filtering, just use [`getone()`](index.html#aiokafka.AIOKafkaConsumer.getone) instead. ##### Reading Transactional Messages[¶](#reading-transactional-messages) Transactions were introduced in Kafka 0.11.0 wherein applications can write to multiple topics and partitions atomically. In order for this to work, consumers reading from these partitions should be configured to only read committed data. This can be achieved by by setting the `isolation_level=read_committed` in the consumer’s configuration: ``` consumer = aiokafka.AIOKafkaConsumer( "my_topic", bootstrap_servers='localhost:9092', isolation_level="read_committed" ) await consumer.start() async for msg in consumer: # Only read committed tranasctions pass ``` In read_committed mode, the consumer will read only those transactional messages which have been successfully committed. It will continue to read non-transactional messages as before. There is no client-side buffering in read_committed mode. Instead, the end offset of a partition for a read_committed consumer would be the offset of the first message in the partition belonging to an open transaction. This offset is known as the **Last Stable Offset** (LSO). A read_committed consumer will only read up to the LSO and filter out any transactional messages which have been aborted. The LSO also affects the behavior of [`seek_to_end()`](index.html#aiokafka.AIOKafkaConsumer.seek_to_end) and [`end_offsets()`](index.html#aiokafka.AIOKafkaConsumer.end_offsets) for read_committed consumers, details of which are in each method’s documentation. Finally, [`last_stable_offset()`](index.html#aiokafka.AIOKafkaConsumer.last_stable_offset) API was added similarly to [`highwater()`](index.html#aiokafka.AIOKafkaConsumer.highwater) API to query the lSO on a currently assigned transaction: ``` async for msg in consumer: # Only read committed tranasctions tp = TopicPartition(msg.topic, msg.partition) lso = consumer.last_stable_offset(tp) lag = lso - msg.offset print(f"Consumer is behind by {lag} messages") end_offsets = await consumer.end_offsets([tp]) assert end_offsets[tp] == lso await consumer.seek_to_end(tp) position = await consumer.position(tp) ``` Partitions with transactional messages will include commit or abort markers which indicate the result of a transaction. There markers are not returned to applications, yet have an offset in the log. As a result, applications reading from topics with transactional messages will see gaps in the consumed offsets. These missing messages would be the transaction markers, and they are filtered out for consumers in both isolation levels. Additionally, applications using read_committed consumers may also see gaps due to aborted transactions, since those messages would not be returned by the consumer and yet would have valid offsets. #### Detecting Consumer Failures[¶](#detecting-consumer-failures) People who worked with [kafka-python](https://github.com/dpkp/kafka-python) or Java Client probably know that the [`poll()`](https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.poll) API is designed to ensure liveness of a [Consumer Groups](consumer-groups). In other words, Consumer will only be considered alive if it consumes messages. It’s not the same for **aiokafka**, for more details read [Difference between aiokafka and kafka-python](index.html#kafka-python-difference). **aiokafka** will join the group on [`start()`](index.html#aiokafka.AIOKafkaConsumer.start) and will send heartbeats in the background, keeping the group alive, same as Java Client. But in the case of a rebalance it will also done in the background. Offset commits in autocommit mode is done strictly by time in the background (in Java client autocommit will not be done if you don’t call [`poll()`](https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.poll) another time). ### Difference between aiokafka and kafka-python[¶](#difference-between-aiokafka-and-kafka-python) #### Why do we need another library?[¶](#why-do-we-need-another-library) [kafka-python](https://github.com/dpkp/kafka-python) is a great project, which tries to fully mimic the interface of the [Java Client API](https://kafka.apache.org/documentation/#api). It is more *feature* oriented, rather than *speed*, but still gives quite good throughput. It’s actively developed and is fast to react to changes in the Java client. While [kafka-python](https://github.com/dpkp/kafka-python) has a lot of great features it is made to be used in a **Threaded** environment. Even more, it mimics Java’s client, making it **Java’s threaded** environment, which does not have that much of *asynchronous* ways of doing things. It’s not **bad** as Java’s Threads are very powerful with the ability to use multiple cores. The API itself just can’t be adopted to be used in an asynchronous way (even though the library does asynchronous IO using *selectors*). It has too much blocking behavior including *blocking* socket usage, threading synchronization, etc. Examples would be: * *bootstrap*, which blocks in the constructor itself * blocking iterator for consumption * sending produce requests block if buffer is full All those can’t be changed to use [`Future`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future) API seamlessly. So to get a normal, non-blocking interface based on [`Future`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future)’s and coroutines a new library needed to be written. #### API differences and rationale[¶](#api-differences-and-rationale) **aiokafka** has some differences in API design. While the **Producer** is mostly the same, **Consumer** has some significant differences, that we want to talk about. ##### Consumer has no `poll()` method[¶](#consumer-has-no-poll-method) In [kafka-python](https://github.com/dpkp/kafka-python), [`kafka.KafkaConsumer.poll()`](https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.poll) is a blocking call that performs not only message fetching, but also: > * Socket polling using epoll, kqueue or other available API of your OS. > * Ensures liveliness of a Consumer Group > * Does autocommit This will never be a case where you own the IO loop, at least not with socket polling. To avoid misunderstandings as to why do those methods behave in a different way [`AIOKafkaConsumer`](index.html#aiokafka.AIOKafkaConsumer) exposes this interface under the name [`getmany()`](index.html#aiokafka.AIOKafkaConsumer.getmany) with some other differences described below. ##### Rebalances are happening in the background[¶](#rebalances-are-happening-in-the-background) In original Kafka Java Client before 0.10.1 heartbeats were only sent if `poll()` was called. This lead to a lot of issues (reasons for [KIP-41](https://cwiki.apache.org/confluence/display/KAFKA/KIP-41%3A+KafkaConsumer+Max+Records) and [KIP-62](https://cwiki.apache.org/confluence/display/KAFKA/KIP-62%3A+Allow+consumer+to+send+heartbeats+from+a+background+thread) proposals) and workarounds using [`pause()`](https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.pause) and [`poll(0)`](https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.poll) for heartbeats. After Java client and kafka-python also changed the behaviour to a background Thread sending, that mitigated most issues. **aiokafka** delegates heartbeating to a background *Task* and will send heartbeats to Coordinator as long as the *event loop* is running. This behaviour is very similar to Java client, with the exception of no heartbeats on long CPU bound methods. But **aiokafka** also performs group rebalancing in the same background Task. This means, that the processing time between [`getmany()`](index.html#aiokafka.AIOKafkaConsumer.getmany) calls actually does not affect rebalancing. `KIP-62` proposed to provide `max.poll.interval.ms` as the configuration for both *rebalance timeout* and *consumer processing timeout*. In **aiokafka** it does not make much sense, as those 2 are not related, so we added both configurations (`rebalance_timeout_ms` and `max_poll_interval_ms`). It is quite critical to provide [`ConsumerRebalanceListener`](index.html#aiokafka.abc.ConsumerRebalanceListener) if you need to control rebalance start and end moments. In that case set the `rebalance_timeout_ms` to the maximum time your application can spend waiting in the callback. If your callback waits for the last [`getmany()`](index.html#aiokafka.AIOKafkaConsumer.getmany) result to be processed, it is safe to set this value to `max_poll_interval_ms`, same as in Java client. ##### Prefetching is more sophisticated[¶](#prefetching-is-more-sophisticated) In the [Kafka Java Client](JavaClientAPI) and [kafka-python](https://github.com/dpkp/kafka-python), the prefetching is very simple, as it only performs prefetches: * in [`poll()`](https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.poll) call if we don’t have enough data stored to satisfy another [`poll()`](https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.poll) * in the *iterator* interface if we have processed *nearly* all data. A very simplified version would be: ``` def poll(): max_records = self.config['max_poll_records'] records = consumer.fethed_records(max_records) if not consumer.has_enough_records(max_records) consumer.send_fetches() # prefetch another batch return records ``` This works great for throughput as the algorithm is simple and we pipeline IO task with record processing. But it does not perform as great in case of **semantic partitioning**, where you may have per-partition processing. In this case latency will be bound to the time of processing of data in all topics. Which is why **aiokafka** tries to do prefetches **per partition**. For example, if we processed all data pending for a partition in *iterator* interface, **aiokafka** will *try* to prefetch new data right away. The same interface could be built on top of [kafka-python](https://github.com/dpkp/kafka-python)’s [`pause()`](https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.pause) API, but would require [a lot of code](https://gist.github.com/tvoinarovskyi/05a5d083a0f96cae3e9b4c2af580be74). Note Using [`getmany()`](index.html#aiokafka.AIOKafkaConsumer.getmany) without specifying partitions will result in the same prefetch behaviour as using [`poll()`](https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.poll). ### API Documentation[¶](#api-documentation) #### Producer class[¶](#producer-class) *class* aiokafka.AIOKafkaProducer(***, *loop=None*, *bootstrap_servers='localhost'*, *client_id=None*, *metadata_max_age_ms=300000*, *request_timeout_ms=40000*, *api_version='auto'*, *acks=<object object>*, *key_serializer=None*, *value_serializer=None*, *compression_type=None*, *max_batch_size=16384*, *partitioner=<kafka.partitioner.default.DefaultPartitioner object>*, *max_request_size=1048576*, *linger_ms=0*, *send_backoff_ms=100*, *retry_backoff_ms=100*, *security_protocol='PLAINTEXT'*, *ssl_context=None*, *connections_max_idle_ms=540000*, *enable_idempotence=False*, *transactional_id=None*, *transaction_timeout_ms=60000*, *sasl_mechanism='PLAIN'*, *sasl_plain_password=None*, *sasl_plain_username=None*, *sasl_kerberos_service_name='kafka'*, *sasl_kerberos_domain_name=None*, *sasl_oauth_token_provider=None*)[[source]](_modules/aiokafka/producer/producer.html#AIOKafkaProducer)[¶](#aiokafka.AIOKafkaProducer) A Kafka client that publishes records to the Kafka cluster. The producer consists of a pool of buffer space that holds records that haven’t yet been transmitted to the server as well as a background task that is responsible for turning these records into requests and transmitting them to the cluster. The [`send()`](#aiokafka.AIOKafkaProducer.send) method is asynchronous. When called it adds the record to a buffer of pending record sends and immediately returns. This allows the producer to batch together individual records for efficiency. The acks config controls the criteria under which requests are considered complete. The `all` setting will result in waiting for all replicas to respond, the slowest but most durable setting. The key_serializer and value_serializer instruct how to turn the key and value objects the user provides into [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes). Parameters * **bootstrap_servers** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)*,* [*list*](https://docs.python.org/3/library/stdtypes.html#list)*(*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*)*) – a `host[:port]` string or list of `host[:port]` strings that the producer should contact to bootstrap initial cluster metadata. This does not have to be the full node list. It just needs to have at least one broker that will respond to a Metadata API Request. Default port is 9092. If no servers are specified, will default to `localhost:9092`. * **client_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – a name for this client. This string is passed in each request to servers and can be used to identify specific server-side log entries that correspond to this client. Default: `aiokafka-producer-#` (appended with a unique number per instance) * **key_serializer** (*Callable*) – used to convert user-supplied keys to bytes If not [`None`](https://docs.python.org/3/library/constants.html#None), called as `f(key),` should return [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes). Default: [`None`](https://docs.python.org/3/library/constants.html#None). * **value_serializer** (*Callable*) – used to convert user-supplied message values to [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes). If not [`None`](https://docs.python.org/3/library/constants.html#None), called as `f(value)`, should return [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes). Default: [`None`](https://docs.python.org/3/library/constants.html#None). * **acks** (*Any*) – one of `0`, `1`, `all`. The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are common: + `0`: Producer will not wait for any acknowledgment from the server at all. The message will immediately be added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retries configuration will not take effect (as the client won’t generally know of any failures). The offset given back for each record will always be set to -1. + `1`: The broker leader will write the record to its local log but will respond without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost. + `all`: The broker leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. If unset, defaults to `acks=1`. If enable_idempotence is [`True`](https://docs.python.org/3/library/constants.html#True) defaults to `acks=all` * **compression_type** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – The compression type for all data generated by the producer. Valid values are `gzip`, `snappy`, `lz4`, `zstd` or [`None`](https://docs.python.org/3/library/constants.html#None). Compression is of full batches of data, so the efficacy of batching will also impact the compression ratio (more batching means better compression). Default: [`None`](https://docs.python.org/3/library/constants.html#None). * **max_batch_size** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Maximum size of buffered data per partition. After this amount [`send()`](#aiokafka.AIOKafkaProducer.send) coroutine will block until batch is drained. Default: 16384 * **linger_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delay; that is, if first request is processed faster, than linger_ms, producer will wait `linger_ms - process_time`. Default: 0 (i.e. no delay). * **partitioner** (*Callable*) – Callable used to determine which partition each message is assigned to. Called (after key serialization): `partitioner(key_bytes, all_partitions, available_partitions)`. The default partitioner implementation hashes each non-None key using the same murmur2 algorithm as the Java client so that messages with the same key are assigned to the same partition. When a key is [`None`](https://docs.python.org/3/library/constants.html#None), the message is delivered to a random partition (filtered to partitions with available leaders only, if possible). * **max_request_size** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The maximum size of a request. This is also effectively a cap on the maximum record size. Note that the server has its own cap on record size which may be different from this. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. Default: 1048576. * **metadata_max_age_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The period of time in milliseconds after which we force a refresh of metadata even if we haven’t seen any partition leadership changes to proactively discover any new brokers or partitions. Default: 300000 * **request_timeout_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Produce request timeout in milliseconds. As it’s sent as part of [`ProduceRequest`](#kafka.protocol.produce.ProduceRequest) (it’s a blocking call), maximum waiting time can be up to `2 * request_timeout_ms`. Default: 40000. * **retry_backoff_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Milliseconds to backoff when retrying on errors. Default: 100. * **api_version** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – specify which kafka API version to use. If set to `auto`, will attempt to infer the broker version by probing various APIs. Default: `auto` * **security_protocol** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – Protocol used to communicate with brokers. Valid values are: `PLAINTEXT`, `SSL`. Default: `PLAINTEXT`. Default: `PLAINTEXT`. * **ssl_context** ([*ssl.SSLContext*](https://docs.python.org/3/library/ssl.html#ssl.SSLContext)) – pre-configured [`SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext) for wrapping socket connections. Directly passed into asyncio’s [`create_connection()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.create_connection). For more information see [SSL Authentication](#ssl-auth). Default: [`None`](https://docs.python.org/3/library/constants.html#None) * **connections_max_idle_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Close idle connections after the number of milliseconds specified by this config. Specifying [`None`](https://docs.python.org/3/library/constants.html#None) will disable idle checks. Default: 540000 (9 minutes). * **enable_idempotence** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) – When set to [`True`](https://docs.python.org/3/library/constants.html#True), the producer will ensure that exactly one copy of each message is written in the stream. If [`False`](https://docs.python.org/3/library/constants.html#False), producer retries due to broker failures, etc., may write duplicates of the retried message in the stream. Note that enabling idempotence acks to set to `all`. If it is not explicitly set by the user it will be chosen. If incompatible values are set, a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) will be thrown. New in version 0.5.0. * **sasl_mechanism** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – Authentication mechanism when security_protocol is configured for `SASL_PLAINTEXT` or `SASL_SSL`. Valid values are: `PLAIN`, `GSSAPI`, `SCRAM-SHA-256`, `SCRAM-SHA-512`, `OAUTHBEARER`. Default: `PLAIN` * **sasl_plain_username** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – username for SASL `PLAIN` authentication. Default: [`None`](https://docs.python.org/3/library/constants.html#None) * **sasl_plain_password** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – password for SASL `PLAIN` authentication. Default: [`None`](https://docs.python.org/3/library/constants.html#None) * **sasl_oauth_token_provider** ([`AbstractTokenProvider`](#aiokafka.abc.AbstractTokenProvider)) – OAuthBearer token provider instance. (See [`kafka.oauth.abstract`](#module-kafka.oauth.abstract)). Default: [`None`](https://docs.python.org/3/library/constants.html#None) Note Many configuration parameters are taken from the Java client: <https://kafka.apache.org/documentation.html#producerconfigscreate_batch()[[source]](_modules/aiokafka/producer/producer.html#AIOKafkaProducer.create_batch)[¶](#aiokafka.AIOKafkaProducer.create_batch) Create and return an empty [`BatchBuilder`](#aiokafka.producer.message_accumulator.BatchBuilder). The batch is not queued for send until submission to [`send_batch()`](#aiokafka.AIOKafkaProducer.send_batch). Returns empty batch to be filled and submitted by the caller. Return type [BatchBuilder](index.html#aiokafka.producer.message_accumulator.BatchBuilder) *async* flush()[[source]](_modules/aiokafka/producer/producer.html#AIOKafkaProducer.flush)[¶](#aiokafka.AIOKafkaProducer.flush) Wait until all batches are Delivered and futures resolved *async* partitions_for(*topic*)[[source]](_modules/aiokafka/producer/producer.html#AIOKafkaProducer.partitions_for)[¶](#aiokafka.AIOKafkaProducer.partitions_for) Returns set of all known partitions for the topic. *async* send(*topic*, *value=None*, *key=None*, *partition=None*, *timestamp_ms=None*, *headers=None*)[[source]](_modules/aiokafka/producer/producer.html#AIOKafkaProducer.send)[¶](#aiokafka.AIOKafkaProducer.send) Publish a message to a topic. Parameters * **topic** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – topic where the message will be published * **value** (*Optional*) – message value. Must be type [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes), or be serializable to [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes) via configured value_serializer. If value is [`None`](https://docs.python.org/3/library/constants.html#None), key is required and message acts as a `delete`. See [Kafka compaction documentation](https://kafka.apache.org/documentation.html#compaction) for more details. (compaction requires kafka >= 0.8.1) * **partition** ([*int*](https://docs.python.org/3/library/functions.html#int)*,* *Optional*) – optionally specify a partition. If not set, the partition will be selected using the configured partitioner. * **key** (*Optional*) – a key to associate with the message. Can be used to determine which partition to send the message to. If partition is [`None`](https://docs.python.org/3/library/constants.html#None) (and producer’s partitioner config is left as default), then messages with the same key will be delivered to the same partition (but if key is [`None`](https://docs.python.org/3/library/constants.html#None), partition is chosen randomly). Must be type [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes), or be serializable to bytes via configured key_serializer. * **timestamp_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)*,* *Optional*) – epoch milliseconds (from Jan 1 1970 UTC) to use as the message timestamp. Defaults to current time. * **headers** (*Optional*) – Kafka headers to be included in the message using the format `[("key", b"value")]`. Iterable of tuples where key is a normal string and value is a byte string. Returns object that will be set when message is processed Return type [asyncio.Future](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future) Raises [**KafkaTimeoutError**](index.html#aiokafka.errors.KafkaTimeoutError) – if we can’t schedule this record (pending buffer is full) in up to request_timeout_ms milliseconds. Note The returned future will wait based on request_timeout_ms setting. Cancelling the returned future **will not** stop event from being sent, but cancelling the [`send()`](#aiokafka.AIOKafkaProducer.send) coroutine itself **will**. *async* send_and_wait(*topic*, *value=None*, *key=None*, *partition=None*, *timestamp_ms=None*, *headers=None*)[[source]](_modules/aiokafka/producer/producer.html#AIOKafkaProducer.send_and_wait)[¶](#aiokafka.AIOKafkaProducer.send_and_wait) Publish a message to a topic and wait the result *async* send_batch(*batch*, *topic*, ***, *partition*)[[source]](_modules/aiokafka/producer/producer.html#AIOKafkaProducer.send_batch)[¶](#aiokafka.AIOKafkaProducer.send_batch) Submit a BatchBuilder for publication. Parameters * **batch** ([*BatchBuilder*](index.html#aiokafka.producer.message_accumulator.BatchBuilder)) – batch object to be published. * **topic** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – topic where the batch will be published. * **partition** ([*int*](https://docs.python.org/3/library/functions.html#int)) – partition where this batch will be published. Returns object that will be set when the batch isdelivered. Return type [asyncio.Future](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future) *async* start()[[source]](_modules/aiokafka/producer/producer.html#AIOKafkaProducer.start)[¶](#aiokafka.AIOKafkaProducer.start) Connect to Kafka cluster and check server version *async* stop()[[source]](_modules/aiokafka/producer/producer.html#AIOKafkaProducer.stop)[¶](#aiokafka.AIOKafkaProducer.stop) Flush all pending data and close all connections to kafka cluster transaction()[[source]](_modules/aiokafka/producer/producer.html#AIOKafkaProducer.transaction)[¶](#aiokafka.AIOKafkaProducer.transaction) Start a transaction context #### Consumer class[¶](#consumer-class) *class* aiokafka.AIOKafkaConsumer(**topics*, *loop=None*, *bootstrap_servers='localhost'*, *client_id='aiokafka-0.8.0'*, *group_id=None*, *key_deserializer=None*, *value_deserializer=None*, *fetch_max_wait_ms=500*, *fetch_max_bytes=52428800*, *fetch_min_bytes=1*, *max_partition_fetch_bytes=1048576*, *request_timeout_ms=40000*, *retry_backoff_ms=100*, *auto_offset_reset='latest'*, *enable_auto_commit=True*, *auto_commit_interval_ms=5000*, *check_crcs=True*, *metadata_max_age_ms=300000*, *partition_assignment_strategy=(<class 'kafka.coordinator.assignors.roundrobin.RoundRobinPartitionAssignor'>*, *)*, *max_poll_interval_ms=300000*, *rebalance_timeout_ms=None*, *session_timeout_ms=10000*, *heartbeat_interval_ms=3000*, *consumer_timeout_ms=200*, *max_poll_records=None*, *ssl_context=None*, *security_protocol='PLAINTEXT'*, *api_version='auto'*, *exclude_internal_topics=True*, *connections_max_idle_ms=540000*, *isolation_level='read_uncommitted'*, *sasl_mechanism='PLAIN'*, *sasl_plain_password=None*, *sasl_plain_username=None*, *sasl_kerberos_service_name='kafka'*, *sasl_kerberos_domain_name=None*, *sasl_oauth_token_provider=None*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer)[¶](#aiokafka.AIOKafkaConsumer) A client that consumes records from a Kafka cluster. The consumer will transparently handle the failure of servers in the Kafka cluster, and adapt as topic-partitions are created or migrate between brokers. It also interacts with the assigned Kafka Group Coordinator node to allow multiple consumers to load balance consumption of topics (feature of Kafka >= 0.9.0.0). Parameters * ***topics** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)*(*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*)*) – optional list of topics to subscribe to. If not set, call [`subscribe()`](#aiokafka.AIOKafkaConsumer.subscribe) or [`assign()`](#aiokafka.AIOKafkaConsumer.assign) before consuming records. Passing topics directly is same as calling [`subscribe()`](#aiokafka.AIOKafkaConsumer.subscribe) API. * **bootstrap_servers** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)*,* [*list*](https://docs.python.org/3/library/stdtypes.html#list)*(*[*str*](https://docs.python.org/3/library/stdtypes.html#str)*)*) – a `host[:port]` string (or list of `host[:port]` strings) that the consumer should contact to bootstrap initial cluster metadata. This does not have to be the full node list. It just needs to have at least one broker that will respond to a Metadata API Request. Default port is 9092. If no servers are specified, will default to `localhost:9092`. * **client_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – a name for this client. This string is passed in each request to servers and can be used to identify specific server-side log entries that correspond to this client. Also submitted to [`GroupCoordinator`](#aiokafka.consumer.group_coordinator.GroupCoordinator) for logging with respect to consumer group administration. Default: `aiokafka-{version}` * **group_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str) *or* [*None*](https://docs.python.org/3/library/constants.html#None)) – name of the consumer group to join for dynamic partition assignment (if enabled), and to use for fetching and committing offsets. If None, auto-partition assignment (via group coordinator) and offset commits are disabled. Default: None * **key_deserializer** (*Callable*) – Any callable that takes a raw message key and returns a deserialized key. * **value_deserializer** (*Callable**,* *Optional*) – Any callable that takes a raw message value and returns a deserialized value. * **fetch_min_bytes** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Minimum amount of data the server should return for a fetch request, otherwise wait up to fetch_max_wait_ms for more data to accumulate. Default: 1. * **fetch_max_bytes** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The maximum amount of data the server should return for a fetch request. This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than this value, the message will still be returned to ensure that the consumer can make progress. NOTE: consumer performs fetches to multiple brokers in parallel so memory usage will depend on the number of brokers containing partitions for the topic. Supported Kafka version >= 0.10.1.0. Default: 52428800 (50 Mb). * **fetch_max_wait_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The maximum amount of time in milliseconds the server will block before answering the fetch request if there isn’t sufficient data to immediately satisfy the requirement given by fetch_min_bytes. Default: 500. * **max_partition_fetch_bytes** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The maximum amount of data per-partition the server will return. The maximum total memory used for a request `= #partitions * max_partition_fetch_bytes`. This size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message on a certain partition. Default: 1048576. * **max_poll_records** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The maximum number of records returned in a single call to [`getmany()`](#aiokafka.AIOKafkaConsumer.getmany). Defaults `None`, no limit. * **request_timeout_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Client request timeout in milliseconds. Default: 40000. * **retry_backoff_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Milliseconds to backoff when retrying on errors. Default: 100. * **auto_offset_reset** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – A policy for resetting offsets on [`OffsetOutOfRangeError`](#aiokafka.errors.OffsetOutOfRangeError) errors: `earliest` will move to the oldest available message, `latest` will move to the most recent, and `none` will raise an exception so you can handle this case. Default: `latest`. * **enable_auto_commit** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) – If true the consumer’s offset will be periodically committed in the background. Default: True. * **auto_commit_interval_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – milliseconds between automatic offset commits, if enable_auto_commit is True. Default: 5000. * **check_crcs** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) – Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. Default: True * **metadata_max_age_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The period of time in milliseconds after which we force a refresh of metadata even if we haven’t seen any partition leadership changes to proactively discover any new brokers or partitions. Default: 300000 * **partition_assignment_strategy** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)) – List of objects to use to distribute partition ownership amongst consumer instances when group management is used. This preference is implicit in the order of the strategies in the list. When assignment strategy changes: to support a change to the assignment strategy, new versions must enable support both for the old assignment strategy and the new one. The coordinator will choose the old assignment strategy until all members have been updated. Then it will choose the new strategy. Default: [[`RoundRobinPartitionAssignor`](#kafka.coordinator.assignors.roundrobin.RoundRobinPartitionAssignor)] * **max_poll_interval_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Maximum allowed time between calls to consume messages (e.g., [`getmany()`](#aiokafka.AIOKafkaConsumer.getmany)). If this interval is exceeded the consumer is considered failed and the group will rebalance in order to reassign the partitions to another consumer group member. If API methods block waiting for messages, that time does not count against this timeout. See [KIP-62](https://cwiki.apache.org/confluence/display/KAFKA/KIP-62%3A+Allow+consumer+to+send+heartbeats+from+a+background+thread) for more information. Default 300000 * **rebalance_timeout_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The maximum time server will wait for this consumer to rejoin the group in a case of rebalance. In Java client this behaviour is bound to max.poll.interval.ms configuration, but as `aiokafka` will rejoin the group in the background, we decouple this setting to allow finer tuning by users that use [`ConsumerRebalanceListener`](#aiokafka.abc.ConsumerRebalanceListener) to delay rebalacing. Defaults to `session_timeout_ms` * **session_timeout_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Client group session and failure detection timeout. The consumer sends periodic heartbeats (heartbeat.interval.ms) to indicate its liveness to the broker. If no hearts are received by the broker for a group member within the session timeout, the broker will remove the consumer from the group and trigger a rebalance. The allowed range is configured with the **broker** configuration properties group.min.session.timeout.ms and group.max.session.timeout.ms. Default: 10000 * **heartbeat_interval_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The expected time in milliseconds between heartbeats to the consumer coordinator when using Kafka’s group management feature. Heartbeats are used to ensure that the consumer’s session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than session_timeout_ms, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. Default: 3000 * **consumer_timeout_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – maximum wait timeout for background fetching routine. Mostly defines how fast the system will see rebalance and request new data for new partitions. Default: 200 * **api_version** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – specify which kafka API version to use. [`AIOKafkaConsumer`](#aiokafka.AIOKafkaConsumer) supports Kafka API versions >=0.9 only. If set to `auto`, will attempt to infer the broker version by probing various APIs. Default: `auto` * **security_protocol** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – Protocol used to communicate with brokers. Valid values are: `PLAINTEXT`, `SSL`. Default: `PLAINTEXT`. * **ssl_context** ([*ssl.SSLContext*](https://docs.python.org/3/library/ssl.html#ssl.SSLContext)) – pre-configured [`SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext) for wrapping socket connections. Directly passed into asyncio’s [`create_connection()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.create_connection). For more information see [SSL Authentication](#ssl-auth). Default: None. * **exclude_internal_topics** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) – Whether records from internal topics (such as offsets) should be exposed to the consumer. If set to True the only way to receive records from an internal topic is subscribing to it. Requires 0.10+ Default: True * **connections_max_idle_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Close idle connections after the number of milliseconds specified by this config. Specifying None will disable idle checks. Default: 540000 (9 minutes). * **isolation_level** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – Controls how to read messages written transactionally. If set to `read_committed`, [`getmany()`](#aiokafka.AIOKafkaConsumer.getmany) will only return transactional messages which have been committed. If set to `read_uncommitted` (the default), [`getmany()`](#aiokafka.AIOKafkaConsumer.getmany) will return all messages, even transactional messages which have been aborted. Non-transactional messages will be returned unconditionally in either mode. Messages will always be returned in offset order. Hence, in read_committed mode, [`getmany()`](#aiokafka.AIOKafkaConsumer.getmany) will only return messages up to the last stable offset (LSO), which is the one less than the offset of the first open transaction. In particular any messages appearing after messages belonging to ongoing transactions will be withheld until the relevant transaction has been completed. As a result, read_committed consumers will not be able to read up to the high watermark when there are in flight transactions. Further, when in read_committed the seek_to_end method will return the LSO. See method docs below. Default: `read_uncommitted` * **sasl_mechanism** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – Authentication mechanism when security_protocol is configured for `SASL_PLAINTEXT` or `SASL_SSL`. Valid values are: `PLAIN`, `GSSAPI`, `SCRAM-SHA-256`, `SCRAM-SHA-512`, `OAUTHBEARER`. Default: `PLAIN` * **sasl_plain_username** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – username for SASL `PLAIN` authentication. Default: None * **sasl_plain_password** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – password for SASL `PLAIN` authentication. Default: None * **sasl_oauth_token_provider** ([*AbstractTokenProvider*](index.html#aiokafka.abc.AbstractTokenProvider)) – OAuthBearer token provider instance. (See [`kafka.oauth.abstract`](#module-kafka.oauth.abstract)). Default: None Note Many configuration parameters are taken from Java Client: <https://kafka.apache.org/documentation.html#newconsumerconfigsassign(*partitions*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.assign)[¶](#aiokafka.AIOKafkaConsumer.assign) Manually assign a list of [`TopicPartition`](#kafka.structs.TopicPartition) to this consumer. This interface does not support incremental assignment and will replace the previous assignment (if there was one). Parameters **partitions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)*(*[*TopicPartition*](index.html#kafka.structs.TopicPartition)*)*) – assignment for this instance. Raises [**IllegalStateError**](index.html#aiokafka.errors.IllegalStateError) – if consumer has already called [`subscribe()`](#aiokafka.AIOKafkaConsumer.subscribe) Warning It is not possible to use both manual partition assignment with [`assign()`](#aiokafka.AIOKafkaConsumer.assign) and group assignment with [`subscribe()`](#aiokafka.AIOKafkaConsumer.subscribe). Note Manual topic assignment through this method does not use the consumer’s group management functionality. As such, there will be **no rebalance operation triggered** when group membership or cluster and topic metadata change. assignment()[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.assignment)[¶](#aiokafka.AIOKafkaConsumer.assignment) Get the set of partitions currently assigned to this consumer. If partitions were directly assigned using [`assign()`](#aiokafka.AIOKafkaConsumer.assign), then this will simply return the same partitions that were previously assigned. If topics were subscribed using [`subscribe()`](#aiokafka.AIOKafkaConsumer.subscribe), then this will give the set of topic partitions currently assigned to the consumer (which may be empty if the assignment hasn’t happened yet or if the partitions are in the process of being reassigned). Returns the set of partitions currently assigned to this consumer Return type [set](https://docs.python.org/3/library/stdtypes.html#set)([TopicPartition](index.html#kafka.structs.TopicPartition)) *async* beginning_offsets(*partitions*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.beginning_offsets)[¶](#aiokafka.AIOKafkaConsumer.beginning_offsets) Get the first offset for the given partitions. This method does not change the current consumer position of the partitions. Note This method may block indefinitely if the partition does not exist. Parameters **partitions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)*[*[*TopicPartition*](index.html#kafka.structs.TopicPartition)*]*) – List of [`TopicPartition`](#kafka.structs.TopicPartition) instances to fetch offsets for. Returns mapping of partition to earliest available offset. Return type [dict](https://docs.python.org/3/library/stdtypes.html#dict) [[TopicPartition](index.html#kafka.structs.TopicPartition), [int](https://docs.python.org/3/library/functions.html#int)] Raises * [**UnsupportedVersionError**](index.html#aiokafka.errors.UnsupportedVersionError) – If the broker does not support looking up the offsets by timestamp. * [**KafkaTimeoutError**](index.html#aiokafka.errors.KafkaTimeoutError) – If fetch failed in request_timeout_ms. New in version 0.3.0. *async* commit(*offsets=None*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.commit)[¶](#aiokafka.AIOKafkaConsumer.commit) Commit offsets to Kafka. This commits offsets only to Kafka. The offsets committed using this API will be used on the first fetch after every rebalance and also on startup. As such, if you need to store offsets in anything other than Kafka, this API should not be used. Currently only supports kafka-topic offset storage (not Zookeeper) When explicitly passing offsets use either offset of next record, or tuple of offset and metadata: ``` tp = TopicPartition(msg.topic, msg.partition) metadata = "Some utf-8 metadata" # Either await consumer.commit({tp: msg.offset + 1}) # Or position directly await consumer.commit({tp: (msg.offset + 1, metadata)}) ``` Note If you want *fire and forget* commit, like [`commit_async()`](https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.commit_async) in [kafka-python](https://github.com/dpkp/kafka-python), just run it in a task. Something like: ``` fut = loop.create_task(consumer.commit()) fut.add_done_callback(on_commit_done) ``` Parameters **offsets** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*,* *Optional*) – A mapping from [`TopicPartition`](#kafka.structs.TopicPartition) to `(offset, metadata)` to commit with the configured `group_id`. Defaults to current consumed offsets for all subscribed partitions. Raises * [**CommitFailedError**](index.html#aiokafka.errors.CommitFailedError) – If membership already changed on broker. * [**IllegalOperation**](index.html#aiokafka.errors.IllegalOperation) – If used with `group_id == None`. * [**IllegalStateError**](index.html#aiokafka.errors.IllegalStateError) – If partitions not assigned. * [**KafkaError**](index.html#aiokafka.errors.KafkaError) – If commit failed on broker side. This could be due to invalid offset, too long metadata, authorization failure, etc. * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError) – If offsets is of wrong format. Changed in version 0.4.0: Changed [`AssertionError`](https://docs.python.org/3/library/exceptions.html#AssertionError) to [`IllegalStateError`](#aiokafka.errors.IllegalStateError) in case of unassigned partition. Changed in version 0.4.0: Will now raise [`CommitFailedError`](#aiokafka.errors.CommitFailedError) in case membership changed, as (possibly) this partition is handled by another consumer. *async* committed(*partition*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.committed)[¶](#aiokafka.AIOKafkaConsumer.committed) Get the last committed offset for the given partition. (whether the commit happened by this process or another). This offset will be used as the position for the consumer in the event of a failure. This call will block to do a remote call to get the latest offset, as those are not cached by consumer (Transactional Producer can change them without Consumer knowledge as of Kafka 0.11.0) Parameters **partition** ([*TopicPartition*](index.html#kafka.structs.TopicPartition)) – the partition to check Returns The last committed offset, or None if there was no prior commit. Raises [**IllegalOperation**](index.html#aiokafka.errors.IllegalOperation) – If used with `group_id == None` *async* end_offsets(*partitions*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.end_offsets)[¶](#aiokafka.AIOKafkaConsumer.end_offsets) Get the last offset for the given partitions. The last offset of a partition is the offset of the upcoming message, i.e. the offset of the last available message + 1. This method does not change the current consumer position of the partitions. Note This method may block indefinitely if the partition does not exist. Parameters **partitions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)*[*[*TopicPartition*](index.html#kafka.structs.TopicPartition)*]*) – List of [`TopicPartition`](#kafka.structs.TopicPartition) instances to fetch offsets for. Returns mapping of partition to last available offset + 1. Return type [dict](https://docs.python.org/3/library/stdtypes.html#dict) [[TopicPartition](index.html#kafka.structs.TopicPartition), [int](https://docs.python.org/3/library/functions.html#int)] Raises * [**UnsupportedVersionError**](index.html#aiokafka.errors.UnsupportedVersionError) – If the broker does not support looking up the offsets by timestamp. * [**KafkaTimeoutError**](index.html#aiokafka.errors.KafkaTimeoutError) – If fetch failed in `request_timeout_ms` New in version 0.3.0. *async* getmany(**partitions*, *timeout_ms=0*, *max_records=None*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.getmany)[¶](#aiokafka.AIOKafkaConsumer.getmany) Get messages from assigned topics / partitions. Prefetched messages are returned in batches by topic-partition. If messages is not available in the prefetched buffer this method waits timeout_ms milliseconds. Parameters * **partitions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)*[*[*TopicPartition*](index.html#kafka.structs.TopicPartition)*]*) – The partitions that need fetching message. If no one partition specified then all subscribed partitions will be used * **timeout_ms** ([*int*](https://docs.python.org/3/library/functions.html#int)*,* *Optional*) – milliseconds spent waiting if data is not available in the buffer. If 0, returns immediately with any records that are available currently in the buffer, else returns empty. Must not be negative. Default: 0 Returns topic to list of records since the last fetch for the subscribed list of topics and partitions Return type [dict](https://docs.python.org/3/library/stdtypes.html#dict)([TopicPartition](index.html#kafka.structs.TopicPartition), [list](https://docs.python.org/3/library/stdtypes.html#list)[[ConsumerRecord](index.html#aiokafka.structs.ConsumerRecord)]) Example usage: ``` data = await consumer.getmany() for tp, messages in data.items(): topic = tp.topic partition = tp.partition for message in messages: # Process message print(message.offset, message.key, message.value) ``` *async* getone(**partitions*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.getone)[¶](#aiokafka.AIOKafkaConsumer.getone) Get one message from Kafka. If no new messages prefetched, this method will wait for it. Parameters **partitions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)*(*[*TopicPartition*](index.html#kafka.structs.TopicPartition)*)*) – Optional list of partitions to return from. If no partitions specified then returned message will be from any partition, which consumer is subscribed to. Returns the message Return type [ConsumerRecord](index.html#aiokafka.structs.ConsumerRecord) Will return instance of ``` collections.namedtuple( "ConsumerRecord", ["topic", "partition", "offset", "key", "value"]) ``` Example usage: ``` while True: message = await consumer.getone() topic = message.topic partition = message.partition # Process message print(message.offset, message.key, message.value) ``` highwater(*partition*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.highwater)[¶](#aiokafka.AIOKafkaConsumer.highwater) Last known highwater offset for a partition. A highwater offset is the offset that will be assigned to the next message that is produced. It may be useful for calculating lag, by comparing with the reported position. Note that both position and highwater refer to the *next* offset – i.e., highwater offset is one greater than the newest available message. Highwater offsets are returned as part of `FetchResponse`, so will not be available if messages for this partition were not requested yet. Parameters **partition** ([*TopicPartition*](index.html#kafka.structs.TopicPartition)) – partition to check Returns offset if available Return type [int](https://docs.python.org/3/library/functions.html#int) or [None](https://docs.python.org/3/library/constants.html#None) last_poll_timestamp(*partition*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.last_poll_timestamp)[¶](#aiokafka.AIOKafkaConsumer.last_poll_timestamp) Returns the timestamp of the last poll of this partition (in ms). It is the last time [`highwater()`](#aiokafka.AIOKafkaConsumer.highwater) and [`last_stable_offset()`](#aiokafka.AIOKafkaConsumer.last_stable_offset) were updated. However it does not mean that new messages were received. As with [`highwater()`](#aiokafka.AIOKafkaConsumer.highwater) will not be available until some messages are consumed. Parameters **partition** ([*TopicPartition*](index.html#kafka.structs.TopicPartition)) – partition to check Returns timestamp if available Return type [int](https://docs.python.org/3/library/functions.html#int) or [None](https://docs.python.org/3/library/constants.html#None) last_stable_offset(*partition*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.last_stable_offset)[¶](#aiokafka.AIOKafkaConsumer.last_stable_offset) Returns the Last Stable Offset of a topic. It will be the last offset up to which point all transactions were completed. Only available in with isolation_level read_committed, in read_uncommitted will always return -1. Will return None for older Brokers. As with [`highwater()`](#aiokafka.AIOKafkaConsumer.highwater) will not be available until some messages are consumed. Parameters **partition** ([*TopicPartition*](index.html#kafka.structs.TopicPartition)) – partition to check Returns offset if available Return type [int](https://docs.python.org/3/library/functions.html#int) or [None](https://docs.python.org/3/library/constants.html#None) *async* offsets_for_times(*timestamps*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.offsets_for_times)[¶](#aiokafka.AIOKafkaConsumer.offsets_for_times) Look up the offsets for the given partitions by timestamp. The returned offset for each partition is the earliest offset whose timestamp is greater than or equal to the given timestamp in the corresponding partition. The consumer does not have to be assigned the partitions. If the message format version in a partition is before 0.10.0, i.e. the messages do not have timestamps, `None` will be returned for that partition. Note This method may block indefinitely if the partition does not exist. Parameters **timestamps** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*(*[*TopicPartition*](index.html#kafka.structs.TopicPartition)*,* [*int*](https://docs.python.org/3/library/functions.html#int)*)*) – mapping from partition to the timestamp to look up. Unit should be milliseconds since beginning of the epoch (midnight Jan 1, 1970 (UTC)) Returns mapping from partition to the timestamp and offset of the first message with timestamp greater than or equal to the target timestamp. Return type [dict](https://docs.python.org/3/library/stdtypes.html#dict)([TopicPartition](index.html#kafka.structs.TopicPartition), [OffsetAndTimestamp](index.html#aiokafka.structs.OffsetAndTimestamp)) Raises * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError) – If the target timestamp is negative * [**UnsupportedVersionError**](index.html#aiokafka.errors.UnsupportedVersionError) – If the broker does not support looking up the offsets by timestamp. * [**KafkaTimeoutError**](index.html#aiokafka.errors.KafkaTimeoutError) – If fetch failed in request_timeout_ms New in version 0.3.0. partitions_for_topic(*topic*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.partitions_for_topic)[¶](#aiokafka.AIOKafkaConsumer.partitions_for_topic) Get metadata about the partitions for a given topic. This method will return None if Consumer does not already have metadata for this topic. Parameters **topic** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – topic to check Returns partition ids Return type [set](https://docs.python.org/3/library/stdtypes.html#set) pause(**partitions*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.pause)[¶](#aiokafka.AIOKafkaConsumer.pause) Suspend fetching from the requested partitions. Future calls to [`getmany()`](#aiokafka.AIOKafkaConsumer.getmany) will not return any records from these partitions until they have been resumed using [`resume()`](#aiokafka.AIOKafkaConsumer.resume). Note: This method does not affect partition subscription. In particular, it does not cause a group rebalance when automatic assignment is used. Parameters ***partitions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)*[*[*TopicPartition*](index.html#kafka.structs.TopicPartition)*]*) – Partitions to pause. paused()[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.paused)[¶](#aiokafka.AIOKafkaConsumer.paused) Get the partitions that were previously paused using [`pause()`](#aiokafka.AIOKafkaConsumer.pause). Returns partitions Return type [set](https://docs.python.org/3/library/stdtypes.html#set)[[TopicPartition](index.html#kafka.structs.TopicPartition)] *async* position(*partition*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.position)[¶](#aiokafka.AIOKafkaConsumer.position) Get the offset of the *next record* that will be fetched (if a record with that offset exists on broker). Parameters **partition** ([*TopicPartition*](index.html#kafka.structs.TopicPartition)) – partition to check Returns offset Return type [int](https://docs.python.org/3/library/functions.html#int) Raises [**IllegalStateError**](index.html#aiokafka.errors.IllegalStateError) – partition is not assigned Changed in version 0.4.0: Changed [`AssertionError`](https://docs.python.org/3/library/exceptions.html#AssertionError) to [`IllegalStateError`](#aiokafka.errors.IllegalStateError) in case of unassigned partition resume(**partitions*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.resume)[¶](#aiokafka.AIOKafkaConsumer.resume) Resume fetching from the specified (paused) partitions. Parameters ***partitions** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)*[*[*TopicPartition*](index.html#kafka.structs.TopicPartition)*]*) – Partitions to resume. seek(*partition*, *offset*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.seek)[¶](#aiokafka.AIOKafkaConsumer.seek) Manually specify the fetch offset for a [`TopicPartition`](#kafka.structs.TopicPartition). Overrides the fetch offsets that the consumer will use on the next [`getmany()`](#aiokafka.AIOKafkaConsumer.getmany)/[`getone()`](#aiokafka.AIOKafkaConsumer.getone) call. If this API is invoked for the same partition more than once, the latest offset will be used on the next fetch. Note You may lose data if this API is arbitrarily used in the middle of consumption to reset the fetch offsets. Use it either on rebalance listeners or after all pending messages are processed. Parameters * **partition** ([*TopicPartition*](index.html#kafka.structs.TopicPartition)) – partition for seek operation * **offset** ([*int*](https://docs.python.org/3/library/functions.html#int)) – message offset in partition Raises * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError) – if offset is not a positive integer * [**IllegalStateError**](index.html#aiokafka.errors.IllegalStateError) – partition is not currently assigned Changed in version 0.4.0: Changed [`AssertionError`](https://docs.python.org/3/library/exceptions.html#AssertionError) to [`IllegalStateError`](#aiokafka.errors.IllegalStateError) and [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) in respective cases. *async* seek_to_beginning(**partitions*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.seek_to_beginning)[¶](#aiokafka.AIOKafkaConsumer.seek_to_beginning) Seek to the oldest available offset for partitions. Parameters ***partitions** – Optionally provide specific [`TopicPartition`](#kafka.structs.TopicPartition), otherwise default to all assigned partitions. Raises * [**IllegalStateError**](index.html#aiokafka.errors.IllegalStateError) – If any partition is not currently assigned * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError) – If partitions are not instances of [`TopicPartition`](#kafka.structs.TopicPartition) New in version 0.3.0. *async* seek_to_committed(**partitions*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.seek_to_committed)[¶](#aiokafka.AIOKafkaConsumer.seek_to_committed) Seek to the committed offset for partitions. Parameters ***partitions** – Optionally provide specific [`TopicPartition`](#kafka.structs.TopicPartition), otherwise default to all assigned partitions. Returns mapping of the currently committed offsets. Return type [dict](https://docs.python.org/3/library/stdtypes.html#dict)([TopicPartition](index.html#kafka.structs.TopicPartition), [int](https://docs.python.org/3/library/functions.html#int)) Raises * [**IllegalStateError**](index.html#aiokafka.errors.IllegalStateError) – If any partition is not currently assigned * [**IllegalOperation**](index.html#aiokafka.errors.IllegalOperation) – If used with `group_id == None` Changed in version 0.3.0: Changed [`AssertionError`](https://docs.python.org/3/library/exceptions.html#AssertionError) to [`IllegalStateError`](#aiokafka.errors.IllegalStateError) in case of unassigned partition *async* seek_to_end(**partitions*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.seek_to_end)[¶](#aiokafka.AIOKafkaConsumer.seek_to_end) Seek to the most recent available offset for partitions. Parameters ***partitions** – Optionally provide specific [`TopicPartition`](#kafka.structs.TopicPartition), otherwise default to all assigned partitions. Raises * [**IllegalStateError**](index.html#aiokafka.errors.IllegalStateError) – If any partition is not currently assigned * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError) – If partitions are not instances of [`TopicPartition`](#kafka.structs.TopicPartition) New in version 0.3.0. *async* start()[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.start)[¶](#aiokafka.AIOKafkaConsumer.start) Connect to Kafka cluster. This will: * Load metadata for all cluster nodes and partition allocation * Wait for possible topic autocreation * Join group if `group_id` provided *async* stop()[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.stop)[¶](#aiokafka.AIOKafkaConsumer.stop) Close the consumer, while waiting for finalizers: * Commit last consumed message if autocommit enabled * Leave group if used Consumer Groups subscribe(*topics=()*, *pattern=None*, *listener=None*)[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.subscribe)[¶](#aiokafka.AIOKafkaConsumer.subscribe) Subscribe to a list of topics, or a topic regex pattern. Partitions will be dynamically assigned via a group coordinator. Topic subscriptions are not incremental: this list will replace the current assignment (if there is one). This method is incompatible with [`assign()`](#aiokafka.AIOKafkaConsumer.assign). Parameters * **topics** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)) – List of topics for subscription. * **pattern** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – Pattern to match available topics. You must provide either topics or pattern, but not both. * **listener** ([*ConsumerRebalanceListener*](index.html#aiokafka.abc.ConsumerRebalanceListener)) – Optionally include listener callback, which will be called before and after each rebalance operation. As part of group management, the consumer will keep track of the list of consumers that belong to a particular group and will trigger a rebalance operation if one of the following events trigger: + Number of partitions change for any of the subscribed topics + Topic is created or deleted + An existing member of the consumer group dies + A new member is added to the consumer group When any of these events are triggered, the provided listener will be invoked first to indicate that the consumer’s assignment has been revoked, and then again when the new assignment has been received. Note that this listener will immediately override any listener set in a previous call to subscribe. It is guaranteed, however, that the partitions revoked/assigned through this interface are from topics subscribed in this call. Raises * [**IllegalStateError**](index.html#aiokafka.errors.IllegalStateError) – if called after previously calling [`assign()`](#aiokafka.AIOKafkaConsumer.assign) * [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError) – if neither topics or pattern is provided or both are provided * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError) – if listener is not a [`ConsumerRebalanceListener`](#aiokafka.abc.ConsumerRebalanceListener) subscription()[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.subscription)[¶](#aiokafka.AIOKafkaConsumer.subscription) Get the current topics subscription. Returns a set of topics Return type [frozenset](https://docs.python.org/3/library/stdtypes.html#frozenset)([str](https://docs.python.org/3/library/stdtypes.html#str)) *async* topics()[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.topics)[¶](#aiokafka.AIOKafkaConsumer.topics) Get all topics the user is authorized to view. Returns topics Return type [set](https://docs.python.org/3/library/stdtypes.html#set) unsubscribe()[[source]](_modules/aiokafka/consumer/consumer.html#AIOKafkaConsumer.unsubscribe)[¶](#aiokafka.AIOKafkaConsumer.unsubscribe) Unsubscribe from all topics and clear all assigned partitions. #### Helpers[¶](#helpers) aiokafka.helpers.create_ssl_context(***, *cafile=None*, *capath=None*, *cadata=None*, *certfile=None*, *keyfile=None*, *password=None*, *crlfile=None*)[[source]](_modules/aiokafka/helpers.html#create_ssl_context)[¶](#aiokafka.helpers.create_ssl_context) Simple helper, that creates an [`SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext) based on params similar to those in [kafka-python](https://github.com/dpkp/kafka-python), but with some restrictions like: * check_hostname is not optional, and will be set to [`True`](https://docs.python.org/3/library/constants.html#True) * crlfile option is missing. It is fairly hard to test it. Parameters * **cafile** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – Certificate Authority file path containing certificates used to sign broker certificates. If CA not specified (by either cafile, capath, cadata) default system CA will be used if found by OpenSSL. For more information see [`load_verify_locations()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_verify_locations). Default: [`None`](https://docs.python.org/3/library/constants.html#None) * **capath** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – Same as cafile, but points to a directory containing several CA certificates. For more information see [`load_verify_locations()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_verify_locations). Default: [`None`](https://docs.python.org/3/library/constants.html#None) * **cadata** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)*,* [*bytes*](https://docs.python.org/3/library/stdtypes.html#bytes)) – Same as cafile, but instead contains already read data in either ASCII or bytes format. Can be used to specify DER-encoded certificates, rather than PEM ones. For more information see [`load_verify_locations()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_verify_locations). Default: [`None`](https://docs.python.org/3/library/constants.html#None) * **certfile** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – optional filename of file in PEM format containing the client certificate, as well as any CA certificates needed to establish the certificate’s authenticity. For more information see [`load_cert_chain()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_cert_chain). Default: [`None`](https://docs.python.org/3/library/constants.html#None). * **keyfile** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – optional filename containing the client private key. For more information see [`load_cert_chain()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_cert_chain). Default: [`None`](https://docs.python.org/3/library/constants.html#None). * **password** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – optional password to be used when loading the certificate chain. For more information see [`load_cert_chain()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_cert_chain). Default: [`None`](https://docs.python.org/3/library/constants.html#None). #### Abstracts[¶](#abstracts) *class* aiokafka.abc.AbstractTokenProvider(***config*)[[source]](_modules/aiokafka/abc.html#AbstractTokenProvider)[¶](#aiokafka.abc.AbstractTokenProvider) A Token Provider must be used for the [SASL OAuthBearer](https://docs.confluent.io/platform/current/kafka/authentication_sasl/authentication_sasl_oauth.html) protocol. The implementation should ensure token reuse so that multiple calls at connect time do not create multiple tokens. The implementation should also periodically refresh the token in order to guarantee that each call returns an unexpired token. A timeout error should be returned after a short period of inactivity so that the broker can log debugging info and retry. Token Providers MUST implement the [`token()`](#aiokafka.abc.AbstractTokenProvider.token) method *abstract async* token()[[source]](_modules/aiokafka/abc.html#AbstractTokenProvider.token)[¶](#aiokafka.abc.AbstractTokenProvider.token) An async callback returning a [`str`](https://docs.python.org/3/library/stdtypes.html#str) ID/Access Token to be sent to the Kafka client. In case where a synchoronous callback is needed, implementations like following can be used: ``` from aiokafka.abc import AbstractTokenProvider class CustomTokenProvider(AbstractTokenProvider): async def token(self): return asyncio.get_running_loop().run_in_executor( None, self._token) def _token(self): # The actual synchoronous token callback. ``` extensions()[[source]](_modules/aiokafka/abc.html#AbstractTokenProvider.extensions)[¶](#aiokafka.abc.AbstractTokenProvider.extensions) This is an OPTIONAL method that may be implemented. Returns a map of key-value pairs that can be sent with the SASL/OAUTHBEARER initial client request. If not implemented, the values are ignored This feature is only available in Kafka >= 2.1.0. *class* aiokafka.abc.ConsumerRebalanceListener[[source]](_modules/aiokafka/abc.html#ConsumerRebalanceListener)[¶](#aiokafka.abc.ConsumerRebalanceListener) A callback interface that the user can implement to trigger custom actions when the set of partitions assigned to the consumer changes. This is applicable when the consumer is having Kafka auto-manage group membership. If the consumer’s directly assign partitions, those partitions will never be reassigned and this callback is not applicable. When Kafka is managing the group membership, a partition re-assignment will be triggered any time the members of the group changes or the subscription of the members changes. This can occur when processes die, new process instances are added or old instances come back to life after failure. Rebalances can also be triggered by changes affecting the subscribed topics (e.g. when then number of partitions is administratively adjusted). There are many uses for this functionality. One common use is saving offsets in a custom store. By saving offsets in the [`on_partitions_revoked()`](#aiokafka.abc.ConsumerRebalanceListener.on_partitions_revoked), call we can ensure that any time partition assignment changes the offset gets saved. Another use is flushing out any kind of cache of intermediate results the consumer may be keeping. For example, consider a case where the consumer is subscribed to a topic containing user page views, and the goal is to count the number of page views per users for each five minute window. Let’s say the topic is partitioned by the user id so that all events for a particular user will go to a single consumer instance. The consumer can keep in memory a running tally of actions per user and only flush these out to a remote data store when its cache gets too big. However if a partition is reassigned it may want to automatically trigger a flush of this cache, before the new owner takes over consumption. This callback will execute during the rebalance process, and Consumer will wait for callbacks to finish before proceeding with group join. It is guaranteed that all consumer processes will invoke [`on_partitions_revoked()`](#aiokafka.abc.ConsumerRebalanceListener.on_partitions_revoked) prior to any process invoking [`on_partitions_assigned()`](#aiokafka.abc.ConsumerRebalanceListener.on_partitions_assigned). So if offsets or other state is saved in the [`on_partitions_revoked()`](#aiokafka.abc.ConsumerRebalanceListener.on_partitions_revoked) call, it should be saved by the time the process taking over that partition has their [`on_partitions_assigned()`](#aiokafka.abc.ConsumerRebalanceListener.on_partitions_assigned) callback called to load the state. *abstract* on_partitions_revoked(*revoked*)[[source]](_modules/aiokafka/abc.html#ConsumerRebalanceListener.on_partitions_revoked)[¶](#aiokafka.abc.ConsumerRebalanceListener.on_partitions_revoked) A coroutine or function the user can implement to provide cleanup or custom state save on the start of a rebalance operation. This method will be called *before* a rebalance operation starts and *after* the consumer stops fetching data. If you are using manual commit you have to commit all consumed offsets here, to avoid duplicate message delivery after rebalance is finished. Note This method is only called before rebalances. It is not called prior to [`AIOKafkaConsumer.stop()`](#aiokafka.AIOKafkaConsumer.stop) Parameters **revoked** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)*(*[*TopicPartition*](index.html#kafka.structs.TopicPartition)*)*) – the partitions that were assigned to the consumer on the last rebalance *abstract* on_partitions_assigned(*assigned*)[[source]](_modules/aiokafka/abc.html#ConsumerRebalanceListener.on_partitions_assigned)[¶](#aiokafka.abc.ConsumerRebalanceListener.on_partitions_assigned) A coroutine or function the user can implement to provide load of custom consumer state or cache warmup on completion of a successful partition re-assignment. This method will be called *after* partition re-assignment completes and *before* the consumer starts fetching data again. It is guaranteed that all the processes in a consumer group will execute their [`on_partitions_revoked()`](#aiokafka.abc.ConsumerRebalanceListener.on_partitions_revoked) callback before any instance executes its [`on_partitions_assigned()`](#aiokafka.abc.ConsumerRebalanceListener.on_partitions_assigned) callback. Parameters **assigned** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)*(*[*TopicPartition*](index.html#kafka.structs.TopicPartition)*)*) – the partitions assigned to the consumer (may include partitions that were previously assigned) #### SSL Authentication[¶](#ssl-authentication) Security is not an easy thing, at least when you want to do it right. Before diving in on how to setup aiokafka to work with SSL, make sure there is a need for SSL Authentication and go through the [official documentation](http://kafka.apache.org/documentation.html#security_ssl) for SSL support in Kafka itself. aiokafka provides only `ssl_context` as a parameter for Consumer and Producer classes. This is done intentionally, as it is recommended that you read through the [Python ssl documentation](https://docs.python.org/3/library/ssl.html#security-considerations) to have some understanding on the topic. Although if you know what you are doing, there is a simple helper function [`aiokafka.helpers.create_ssl_context()`](#aiokafka.helpers.create_ssl_context), that will create an [`ssl.SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext) based on similar params to [kafka-python](https://github.com/dpkp/kafka-python). A few notes on Kafka’s SSL store types. Java uses **JKS** store type, that contains normal certificates, same as ones OpenSSL (and Python, as it’s based on OpenSSL) uses, but encodes them into a single, encrypted file, protected by another password. Just look the internet on how to extract CARoot, Certificate and Key from JKS store. See also the [Using SSL with aiokafka](index.html#ssl-example) example. #### SASL Authentication[¶](#sasl-authentication) As of version 0.5.1 aiokafka supports SASL authentication using both `PLAIN` and `GSSAPI` SASL methods. Be sure to install [gssapi](https://pypi.org/project/gssapi/) python module to use `GSSAPI`. Please consult the [official documentation](http://kafka.apache.org/documentation.html#security_sasl) for setup instructions on Broker side. Client configuration is pretty much the same as Java’s, consult the `sasl_*` options in Consumer and Producer API Reference for more details. #### Error handling[¶](#error-handling) Both consumer and producer can raise exceptions that inherit from the [`aiokafka.errors.KafkaError`](#aiokafka.errors.KafkaError) class. Exception handling example: ``` from aiokafka.errors import KafkaError, KafkaTimeoutError # ... try: send_future = await producer.send('foobar', b'test data') response = await send_future # wait until message is produced except KafkaTimeoutError: print("produce timeout... maybe we want to resend data again?") except KafkaError as err: print("some kafka error on produce: {}".format(err)) ``` ##### Consumer errors[¶](#consumer-errors) Consumer’s `async for` and [`getone()`](#aiokafka.AIOKafkaConsumer.getone)/[`getmany()`](#aiokafka.AIOKafkaConsumer.getmany) interfaces will handle those differently. Possible consumer errors include: * [`TopicAuthorizationFailedError`](#aiokafka.errors.TopicAuthorizationFailedError) - topic requires authorization. Always raised * [`OffsetOutOfRangeError`](#aiokafka.errors.OffsetOutOfRangeError) - if you don’t specify auto_offset_reset policy and started cosumption from not valid offset. Always raised * [`RecordTooLargeError`](#aiokafka.errors.RecordTooLargeError) - broker has a *MessageSet* larger than max_partition_fetch_bytes. **async for** - log error, **get*** will raise it. * [`InvalidMessageError`](#aiokafka.errors.InvalidMessageError) - CRC check on MessageSet failed due to connection failure or bug. Always raised. Changed in version `0.5.0`, before we ignored this error in `async for`. #### Other references[¶](#other-references) *class* aiokafka.producer.message_accumulator.BatchBuilder(*magic*, *batch_size*, *compression_type*, ***, *is_transactional*)[[source]](_modules/aiokafka/producer/message_accumulator.html#BatchBuilder)[¶](#aiokafka.producer.message_accumulator.BatchBuilder) *class* aiokafka.consumer.group_coordinator.GroupCoordinator(*client*, *subscription*, ***, *group_id='aiokafka-default-group'*, *session_timeout_ms=10000*, *heartbeat_interval_ms=3000*, *retry_backoff_ms=100*, *enable_auto_commit=True*, *auto_commit_interval_ms=5000*, *assignors=(<class 'kafka.coordinator.assignors.roundrobin.RoundRobinPartitionAssignor'>*, *)*, *exclude_internal_topics=True*, *max_poll_interval_ms=300000*, *rebalance_timeout_ms=30000*)[[source]](_modules/aiokafka/consumer/group_coordinator.html#GroupCoordinator)[¶](#aiokafka.consumer.group_coordinator.GroupCoordinator) GroupCoordinator implements group management for single group member by interacting with a designated Kafka broker (the coordinator). Group semantics are provided by extending this class. From a high level, Kafka’s group management protocol consists of the following sequence of actions: 1. Group Registration: Group members register with the coordinator providing their own metadata (such as the set of topics they are interested in). 2. Group/Leader Selection: The coordinator (one of Kafka nodes) select the members of the group and chooses one member (one of client’s) as the leader. 3. State Assignment: The leader receives metadata for all members and assigns partitions to them. 4. Group Stabilization: Each member receives the state assigned by the leader and begins processing. Between each phase coordinator awaits all clients to respond. If some do not respond in time - it will revoke their membership NOTE: Try to maintain same log messages and behaviour as Java and > kafka-python clients: <https://github.com/apache/kafka/blob/0.10.1.1/clients/src/main/java/> org/apache/kafka/clients/consumer/internals/AbstractCoordinator.java <https://github.com/apache/kafka/blob/0.10.1.1/clients/src/main/java/> org/apache/kafka/clients/consumer/internals/ConsumerCoordinator.java *class* kafka.coordinator.assignors.roundrobin.RoundRobinPartitionAssignor[[source]](_modules/kafka/coordinator/assignors/roundrobin.html#RoundRobinPartitionAssignor)[¶](#kafka.coordinator.assignors.roundrobin.RoundRobinPartitionAssignor) The roundrobin assignor lays out all the available partitions and all the available consumers. It then proceeds to do a roundrobin assignment from partition to consumer. If the subscriptions of all consumer instances are identical, then the partitions will be uniformly distributed. (i.e., the partition ownership counts will be within a delta of exactly one across all consumers.) For example, suppose there are two consumers C0 and C1, two topics t0 and t1, and each topic has 3 partitions, resulting in partitions t0p0, t0p1, t0p2, t1p0, t1p1, and t1p2. The assignment will be:C0: [t0p0, t0p2, t1p1] C1: [t0p1, t1p0, t1p2] When subscriptions differ across consumer instances, the assignment process still considers each consumer instance in round robin fashion but skips over an instance if it is not subscribed to the topic. Unlike the case when subscriptions are identical, this can result in imbalanced assignments. For example, suppose we have three consumers C0, C1, C2, and three topics t0, t1, t2, with unbalanced partitions t0p0, t1p0, t1p1, t2p0, t2p1, t2p2, where C0 is subscribed to t0; C1 is subscribed to t0, t1; and C2 is subscribed to t0, t1, t2. The assignment will be:C0: [t0p0] C1: [t1p0] C2: [t1p1, t2p0, t2p1, t2p2] ##### Errors[¶](#module-aiokafka.errors) *exception* aiokafka.errors.ConcurrentTransactions[[source]](_modules/aiokafka/errors.html#ConcurrentTransactions)[¶](#aiokafka.errors.ConcurrentTransactions) *exception* aiokafka.errors.ConsumerStoppedError[[source]](_modules/aiokafka/errors.html#ConsumerStoppedError)[¶](#aiokafka.errors.ConsumerStoppedError) Raised on get* methods of Consumer if it’s cancelled, even pending ones. *exception* aiokafka.errors.CoordinatorLoadInProgressError[[source]](_modules/aiokafka/errors.html#CoordinatorLoadInProgressError)[¶](#aiokafka.errors.CoordinatorLoadInProgressError) *exception* aiokafka.errors.CoordinatorNotAvailableError[[source]](_modules/aiokafka/errors.html#CoordinatorNotAvailableError)[¶](#aiokafka.errors.CoordinatorNotAvailableError) *exception* aiokafka.errors.DelegationTokenAuthDisabled[[source]](_modules/aiokafka/errors.html#DelegationTokenAuthDisabled)[¶](#aiokafka.errors.DelegationTokenAuthDisabled) *exception* aiokafka.errors.DelegationTokenAuthorizationFailed[[source]](_modules/aiokafka/errors.html#DelegationTokenAuthorizationFailed)[¶](#aiokafka.errors.DelegationTokenAuthorizationFailed) *exception* aiokafka.errors.DelegationTokenExpired[[source]](_modules/aiokafka/errors.html#DelegationTokenExpired)[¶](#aiokafka.errors.DelegationTokenExpired) *exception* aiokafka.errors.DelegationTokenNotFound[[source]](_modules/aiokafka/errors.html#DelegationTokenNotFound)[¶](#aiokafka.errors.DelegationTokenNotFound) *exception* aiokafka.errors.DelegationTokenOwnerMismatch[[source]](_modules/aiokafka/errors.html#DelegationTokenOwnerMismatch)[¶](#aiokafka.errors.DelegationTokenOwnerMismatch) *exception* aiokafka.errors.DelegationTokenRequestNotAllowed[[source]](_modules/aiokafka/errors.html#DelegationTokenRequestNotAllowed)[¶](#aiokafka.errors.DelegationTokenRequestNotAllowed) *exception* aiokafka.errors.DuplicateSequenceNumber[[source]](_modules/aiokafka/errors.html#DuplicateSequenceNumber)[¶](#aiokafka.errors.DuplicateSequenceNumber) *exception* aiokafka.errors.FetchSessionIdNotFound[[source]](_modules/aiokafka/errors.html#FetchSessionIdNotFound)[¶](#aiokafka.errors.FetchSessionIdNotFound) aiokafka.errors.GroupCoordinatorNotAvailableError[¶](#aiokafka.errors.GroupCoordinatorNotAvailableError) alias of [`aiokafka.errors.CoordinatorNotAvailableError`](#aiokafka.errors.CoordinatorNotAvailableError) *exception* aiokafka.errors.GroupIdNotFound[[source]](_modules/aiokafka/errors.html#GroupIdNotFound)[¶](#aiokafka.errors.GroupIdNotFound) aiokafka.errors.GroupLoadInProgressError[¶](#aiokafka.errors.GroupLoadInProgressError) alias of [`aiokafka.errors.CoordinatorLoadInProgressError`](#aiokafka.errors.CoordinatorLoadInProgressError) *exception* aiokafka.errors.IllegalOperation[[source]](_modules/aiokafka/errors.html#IllegalOperation)[¶](#aiokafka.errors.IllegalOperation) Raised if you try to execute an operation, that is not available with current configuration. For example trying to commit if no group_id was given. *exception* aiokafka.errors.InvalidFetchSessionEpoch[[source]](_modules/aiokafka/errors.html#InvalidFetchSessionEpoch)[¶](#aiokafka.errors.InvalidFetchSessionEpoch) *exception* aiokafka.errors.InvalidPrincipalType[[source]](_modules/aiokafka/errors.html#InvalidPrincipalType)[¶](#aiokafka.errors.InvalidPrincipalType) *exception* aiokafka.errors.InvalidProducerEpoch[[source]](_modules/aiokafka/errors.html#InvalidProducerEpoch)[¶](#aiokafka.errors.InvalidProducerEpoch) *exception* aiokafka.errors.InvalidProducerIdMapping[[source]](_modules/aiokafka/errors.html#InvalidProducerIdMapping)[¶](#aiokafka.errors.InvalidProducerIdMapping) *exception* aiokafka.errors.InvalidTransactionTimeout[[source]](_modules/aiokafka/errors.html#InvalidTransactionTimeout)[¶](#aiokafka.errors.InvalidTransactionTimeout) *exception* aiokafka.errors.InvalidTxnState[[source]](_modules/aiokafka/errors.html#InvalidTxnState)[¶](#aiokafka.errors.InvalidTxnState) *exception* aiokafka.errors.KafkaStorageError[[source]](_modules/aiokafka/errors.html#KafkaStorageError)[¶](#aiokafka.errors.KafkaStorageError) *exception* aiokafka.errors.ListenerNotFound[[source]](_modules/aiokafka/errors.html#ListenerNotFound)[¶](#aiokafka.errors.ListenerNotFound) *exception* aiokafka.errors.LogDirNotFound[[source]](_modules/aiokafka/errors.html#LogDirNotFound)[¶](#aiokafka.errors.LogDirNotFound) *exception* aiokafka.errors.NoOffsetForPartitionError[[source]](_modules/aiokafka/errors.html#NoOffsetForPartitionError)[¶](#aiokafka.errors.NoOffsetForPartitionError) *exception* aiokafka.errors.NonEmptyGroup[[source]](_modules/aiokafka/errors.html#NonEmptyGroup)[¶](#aiokafka.errors.NonEmptyGroup) *exception* aiokafka.errors.NotCoordinatorError[[source]](_modules/aiokafka/errors.html#NotCoordinatorError)[¶](#aiokafka.errors.NotCoordinatorError) aiokafka.errors.NotCoordinatorForGroupError[¶](#aiokafka.errors.NotCoordinatorForGroupError) alias of [`aiokafka.errors.NotCoordinatorError`](#aiokafka.errors.NotCoordinatorError) *exception* aiokafka.errors.OperationNotAttempted[[source]](_modules/aiokafka/errors.html#OperationNotAttempted)[¶](#aiokafka.errors.OperationNotAttempted) *exception* aiokafka.errors.OutOfOrderSequenceNumber[[source]](_modules/aiokafka/errors.html#OutOfOrderSequenceNumber)[¶](#aiokafka.errors.OutOfOrderSequenceNumber) *exception* aiokafka.errors.ProducerClosed[[source]](_modules/aiokafka/errors.html#ProducerClosed)[¶](#aiokafka.errors.ProducerClosed) *exception* aiokafka.errors.ProducerFenced(*msg='There is a newer producer using the same transactional_id ortransaction timeout occurred (check that processing time is below transaction_timeout_ms)'*)[[source]](_modules/aiokafka/errors.html#ProducerFenced)[¶](#aiokafka.errors.ProducerFenced) Another producer with the same transactional ID went online. NOTE: As it seems this will be raised by Broker if transaction timeout occurred also. *exception* aiokafka.errors.ReassignmentInProgress[[source]](_modules/aiokafka/errors.html#ReassignmentInProgress)[¶](#aiokafka.errors.ReassignmentInProgress) *exception* aiokafka.errors.RecordTooLargeError[[source]](_modules/aiokafka/errors.html#RecordTooLargeError)[¶](#aiokafka.errors.RecordTooLargeError) *exception* aiokafka.errors.SaslAuthenticationFailed[[source]](_modules/aiokafka/errors.html#SaslAuthenticationFailed)[¶](#aiokafka.errors.SaslAuthenticationFailed) *exception* aiokafka.errors.SecurityDisabled[[source]](_modules/aiokafka/errors.html#SecurityDisabled)[¶](#aiokafka.errors.SecurityDisabled) *exception* aiokafka.errors.TransactionCoordinatorFenced[[source]](_modules/aiokafka/errors.html#TransactionCoordinatorFenced)[¶](#aiokafka.errors.TransactionCoordinatorFenced) *exception* aiokafka.errors.TransactionalIdAuthorizationFailed[[source]](_modules/aiokafka/errors.html#TransactionalIdAuthorizationFailed)[¶](#aiokafka.errors.TransactionalIdAuthorizationFailed) *exception* aiokafka.errors.UnknownProducerId[[source]](_modules/aiokafka/errors.html#UnknownProducerId)[¶](#aiokafka.errors.UnknownProducerId) *class* aiokafka.errors.KafkaTimeoutError[[source]](_modules/kafka/errors.html#KafkaTimeoutError)[¶](#aiokafka.errors.KafkaTimeoutError) *class* aiokafka.errors.RequestTimedOutError[[source]](_modules/kafka/errors.html#RequestTimedOutError)[¶](#aiokafka.errors.RequestTimedOutError) *class* aiokafka.errors.NotEnoughReplicasError[[source]](_modules/kafka/errors.html#NotEnoughReplicasError)[¶](#aiokafka.errors.NotEnoughReplicasError) *class* aiokafka.errors.NotEnoughReplicasAfterAppendError[[source]](_modules/kafka/errors.html#NotEnoughReplicasAfterAppendError)[¶](#aiokafka.errors.NotEnoughReplicasAfterAppendError) *class* aiokafka.errors.KafkaError[[source]](_modules/kafka/errors.html#KafkaError)[¶](#aiokafka.errors.KafkaError) *class* aiokafka.errors.UnsupportedVersionError[[source]](_modules/kafka/errors.html#UnsupportedVersionError)[¶](#aiokafka.errors.UnsupportedVersionError) *class* aiokafka.errors.TopicAuthorizationFailedError[[source]](_modules/kafka/errors.html#TopicAuthorizationFailedError)[¶](#aiokafka.errors.TopicAuthorizationFailedError) *class* aiokafka.errors.OffsetOutOfRangeError[[source]](_modules/kafka/errors.html#OffsetOutOfRangeError)[¶](#aiokafka.errors.OffsetOutOfRangeError) *class* aiokafka.errors.CorruptRecordException[[source]](_modules/kafka/errors.html#CorruptRecordException)[¶](#aiokafka.errors.CorruptRecordException) *class* kafka.errors.CorruptRecordException[[source]](_modules/kafka/errors.html#CorruptRecordException)[¶](#kafka.errors.CorruptRecordException) aiokafka.errors.InvalidMessageError[¶](#aiokafka.errors.InvalidMessageError) alias of [`kafka.errors.CorruptRecordException`](#kafka.errors.CorruptRecordException) *class* aiokafka.errors.IllegalStateError[[source]](_modules/kafka/errors.html#IllegalStateError)[¶](#aiokafka.errors.IllegalStateError) *class* aiokafka.errors.CommitFailedError(**args*, ***kwargs*)[[source]](_modules/kafka/errors.html#CommitFailedError)[¶](#aiokafka.errors.CommitFailedError) ##### Structs[¶](#module-aiokafka.structs) *class* kafka.structs.TopicPartition(*topic*, *partition*)[¶](#kafka.structs.TopicPartition) A Kafka broker metadata used by admin tools. Keyword Arguments * **nodeID** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The Kafka broker id. * **host** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – The Kafka broker hostname. * **port** ([*int*](https://docs.python.org/3/library/functions.html#int)) – The Kafka broker port. * **rack** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – The rack of the broker, which is used to in rack aware partition assignment for fault tolerance. * **Examples** – RACK1, us-east-1d. Default: None *property* partition[¶](#kafka.structs.TopicPartition.partition) Alias for field number 1 *property* topic[¶](#kafka.structs.TopicPartition.topic) Alias for field number 0 *class* aiokafka.structs.RecordMetadata(*topic: [str](https://docs.python.org/3/library/stdtypes.html#str)*, *partition: [int](https://docs.python.org/3/library/functions.html#int)*, *topic_partition: [kafka.structs.TopicPartition](index.html#kafka.structs.TopicPartition)*, *offset: [int](https://docs.python.org/3/library/functions.html#int)*, *timestamp: Optional[[int](https://docs.python.org/3/library/functions.html#int)]*, *timestamp_type: [int](https://docs.python.org/3/library/functions.html#int)*, *log_start_offset: Optional[[int](https://docs.python.org/3/library/functions.html#int)]*)[[source]](_modules/aiokafka/structs.html#RecordMetadata)[¶](#aiokafka.structs.RecordMetadata) Returned when a [`AIOKafkaProducer`](#aiokafka.AIOKafkaProducer) sends a message *property* log_start_offset[¶](#aiokafka.structs.RecordMetadata.log_start_offset) *property* offset[¶](#aiokafka.structs.RecordMetadata.offset) The unique offset of the message in this partition. See [Offsets and Consumer Position](index.html#offset-and-position) for more details on offsets. *property* partition[¶](#aiokafka.structs.RecordMetadata.partition) The partition number *property* timestamp[¶](#aiokafka.structs.RecordMetadata.timestamp) Timestamp in millis, None for older Brokers *property* timestamp_type[¶](#aiokafka.structs.RecordMetadata.timestamp_type) The timestamp type of this record. If the broker respected the timestamp passed to [`AIOKafkaProducer.send()`](#aiokafka.AIOKafkaProducer.send), `0` will be returned (`CreateTime`). If the broker set it’s own timestamp, `1` will be returned (`LogAppendTime`). *property* topic[¶](#aiokafka.structs.RecordMetadata.topic) The topic name *property* topic_partition[¶](#aiokafka.structs.RecordMetadata.topic_partition) *class* aiokafka.structs.ConsumerRecord(**args*, ***kwds*)[[source]](_modules/aiokafka/structs.html#ConsumerRecord)[¶](#aiokafka.structs.ConsumerRecord) checksum*: [int](https://docs.python.org/3/library/functions.html#int)*[¶](#aiokafka.structs.ConsumerRecord.checksum) Deprecated headers*: Sequence[Tuple[[str](https://docs.python.org/3/library/stdtypes.html#str), [bytes](https://docs.python.org/3/library/stdtypes.html#bytes)]]*[¶](#aiokafka.structs.ConsumerRecord.headers) The headers key*: Optional[[aiokafka.structs.KT](index.html#aiokafka.structs.KT)]*[¶](#aiokafka.structs.ConsumerRecord.key) The key (or None if no key is specified) offset*: [int](https://docs.python.org/3/library/functions.html#int)*[¶](#aiokafka.structs.ConsumerRecord.offset) The position of this record in the corresponding Kafka partition. partition*: [int](https://docs.python.org/3/library/functions.html#int)*[¶](#aiokafka.structs.ConsumerRecord.partition) The partition from which this record is received serialized_key_size*: [int](https://docs.python.org/3/library/functions.html#int)*[¶](#aiokafka.structs.ConsumerRecord.serialized_key_size) The size of the serialized, uncompressed key in bytes. serialized_value_size*: [int](https://docs.python.org/3/library/functions.html#int)*[¶](#aiokafka.structs.ConsumerRecord.serialized_value_size) The size of the serialized, uncompressed value in bytes. timestamp*: [int](https://docs.python.org/3/library/functions.html#int)*[¶](#aiokafka.structs.ConsumerRecord.timestamp) The timestamp of this record timestamp_type*: [int](https://docs.python.org/3/library/functions.html#int)*[¶](#aiokafka.structs.ConsumerRecord.timestamp_type) The timestamp type of this record topic*: [str](https://docs.python.org/3/library/stdtypes.html#str)*[¶](#aiokafka.structs.ConsumerRecord.topic) The topic this record is received from value*: Optional[[aiokafka.structs.VT](index.html#aiokafka.structs.VT)]*[¶](#aiokafka.structs.ConsumerRecord.value) The value *class* aiokafka.structs.OffsetAndTimestamp(*offset*, *timestamp*)[[source]](_modules/aiokafka/structs.html#OffsetAndTimestamp)[¶](#aiokafka.structs.OffsetAndTimestamp) *property* offset[¶](#aiokafka.structs.OffsetAndTimestamp.offset) Alias for field number 0 *property* timestamp[¶](#aiokafka.structs.OffsetAndTimestamp.timestamp) Alias for field number 1 *class* aiokafka.structs.KT[¶](#aiokafka.structs.KT) The type of a key. *class* aiokafka.structs.VT[¶](#aiokafka.structs.VT) The type of a value. ##### Protocols[¶](#protocols) kafka.protocol.produce.ProduceRequest[¶](#kafka.protocol.produce.ProduceRequest) alias of [<class ‘kafka.protocol.produce.ProduceRequest_v0’>, <class ‘kafka.protocol.produce.ProduceRequest_v1’>, <class ‘kafka.protocol.produce.ProduceRequest_v2’>, <class ‘kafka.protocol.produce.ProduceRequest_v3’>, <class ‘kafka.protocol.produce.ProduceRequest_v4’>, <class ‘kafka.protocol.produce.ProduceRequest_v5’>, <class ‘kafka.protocol.produce.ProduceRequest_v6’>, <class ‘kafka.protocol.produce.ProduceRequest_v7’>, <class ‘kafka.protocol.produce.ProduceRequest_v8’>] ### Examples[¶](#examples) #### Serialization and compression[¶](#serialization-and-compression) Kafka supports several compression types: `gzip`, `snappy` and `lz4`. You only need to specify the compression in Kafka Producer, Consumer will decompress automatically. Note:Messages are compressed in batches, so you will have more efficiency on larger batches. You can consider setting linger_ms to batch more data before sending. By default [`value`](index.html#aiokafka.structs.ConsumerRecord.value) and [`key`](index.html#aiokafka.structs.ConsumerRecord.key) attributes of returned [`ConsumerRecord`](index.html#aiokafka.structs.ConsumerRecord) instances are [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes). You can use custom serializer/deserializer hooks to operate on objects instead of [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes) in those attributes. Producer ``` import json import asyncio from aiokafka import AIOKafkaProducer def serializer(value): return json.dumps(value).encode() async def produce(): producer = AIOKafkaProducer( bootstrap_servers='localhost:9092', value_serializer=serializer, compression_type="gzip") await producer.start() data = {"a": 123.4, "b": "some string"} await producer.send('foobar', data) data = [1,2,3,4] await producer.send('foobar', data) await producer.stop() asyncio.run(produce()) ``` Consumer ``` import json import asyncio from kafka.common import KafkaError from aiokafka import AIOKafkaConsumer def deserializer(serialized): return json.loads(serialized) async def consume(): # consumer will decompress messages automatically # in accordance to compression type specified in producer consumer = AIOKafkaConsumer( 'foobar', bootstrap_servers='localhost:9092', value_deserializer=deserializer, auto_offset_reset='earliest') await consumer.start() data = await consumer.getmany(timeout_ms=10000) for tp, messages in data.items(): for message in messages: print(type(message.value), message.value) await consumer.stop() asyncio.run(consume()) ``` Output: ``` >>> python3 producer.py >>> python3 consumer.py <class 'dict'> {'a': 123.4, 'b': 'some string'} <class 'list'> [1,2,3,4] ``` #### Manual commit[¶](#manual-commit) When processing more sensitive data `enable_auto_commit=False` mode of Consumer can lead to data loss in cases of critical failure. To avoid it we can commit offsets manually after they were processed. Note, that this is a tradeoff from *at most once* to *at least once* delivery, to achieve *exactly once* you will need to save offsets in the destination database and validate those yourself. More on message delivery: <https://kafka.apache.org/documentation.html#semanticsNote After Kafka Broker version 0.11 and after aiokafka==0.5.0 it is possible to use Transactional Producer to achieve *exactly once* delivery semantics. See [Transactional producer](index.html#transactional-producer) section. Consumer: ``` import json import asyncio from kafka.common import KafkaError from aiokafka import AIOKafkaConsumer async def consume(): consumer = AIOKafkaConsumer( 'foobar', bootstrap_servers='localhost:9092', auto_offset_reset='earliest', group_id="some-consumer-group", enable_auto_commit=False) await consumer.start() # we want to consume 10 messages from "foobar" topic # and commit after that for _ in range(10): msg = await consumer.getone() await consumer.commit() await consumer.stop() asyncio.run(consume()) ``` #### Group consumer[¶](#group-consumer) As of Kafka 9.0 Consumers can consume on the same topic simultaneously. This is achieved by coordinating consumers by one of Kafka broker nodes (coordinator). This node will perform synchronization of partition assignment (thou the partitions will be assigned by python code) and consumers will always return messages for the assigned partitions. Note:Though Consumer will never return messages from not assigned partitions, if you are in `autocommit=False` mode, you should re-check assignment before processing next message returned by [`getmany()`](index.html#aiokafka.AIOKafkaConsumer.getmany) call. Producer: ``` import sys import asyncio from aiokafka import AIOKafkaProducer async def produce(value, partition): producer = AIOKafkaProducer(bootstrap_servers='localhost:9092') await producer.start() await producer.send('some-topic', value, partition=partition) await producer.stop() if len(sys.argv) != 3: print("usage: producer.py <partition> <message>") sys.exit(1) value = sys.argv[2].encode() partition = int(sys.argv[1]) asyncio.run(produce(value, partition)) ``` Consumer: ``` import sys import asyncio from aiokafka import AIOKafkaConsumer async def consume(): consumer = AIOKafkaConsumer( 'some-topic', group_id=group_id, bootstrap_servers='localhost:9092', auto_offset_reset='earliest') await consumer.start() for _ in range(msg_cnt): msg = await consumer.getone() print(f"Message from partition [{msg.partition}]: {msg.value}") await consumer.stop() if len(sys.argv) < 3: print("usage: consumer.py <group_id> <wait messages count>") sys.exit(1) group_id = sys.argv[1] msg_cnt = int(sys.argv[2]) asyncio.run(consume(group_id, msg_cnt)) ``` Run example scripts: * Creating topic `some-topic` with 2 partitions using standard Kafka utility: ``` bin/kafka-topics.sh --create \ --zookeeper localhost:2181 \ --replication-factor 1 \ --partitions 2 \ --topic some-topic ``` * terminal#1: ``` python3 consumer.py TEST_GROUP 2 ``` * terminal#2: ``` python3 consumer.py TEST_GROUP 2 ``` * terminal#3: ``` python3 consumer.py OTHER_GROUP 4 ``` * terminal#4: ``` python3 producer.py 0 'message #1' python3 producer.py 0 'message #2' python3 producer.py 1 'message #3' python3 producer.py 1 'message #4' ``` Output: * terminal#1: ``` Message from partition [0]: b'message #1' Message from partition [0]: b'message #2' ``` * terminal#2: ``` Message from partition [1]: b'message #3' Message from partition [1]: b'message #4' ``` * terminal#3: ``` Message from partition [1]: b'message #3' Message from partition [1]: b'message #4' Message from partition [0]: b'message #1' Message from partition [0]: b'message #2' ``` #### Custom partitioner[¶](#custom-partitioner) If you consider using partitions as a logical entity, rather then purely for load-balancing, you may need to have more control over routing messages to partitions. By default hashing algorithms are used. Producer ``` import asyncio import random from aiokafka import AIOKafkaProducer def my_partitioner(key, all_partitions, available_partitions): if key == b'first': return all_partitions[0] elif key == b'last': return all_partitions[-1] return random.choice(all_partitions) async def produce_one(producer, key, value): future = await producer.send('foobar', value, key=key) resp = await future print("'%s' produced in partition: %i"%(value.decode(), resp.partition)) async def produce_task(): producer = AIOKafkaProducer( bootstrap_servers='localhost:9092', partitioner=my_partitioner) await producer.start() await produce_one(producer, b'last', b'1') await produce_one(producer, b'some', b'2') await produce_one(producer, b'first', b'3') await producer.stop() asyncio.run(produce_task()) ``` Output (topic `foobar` has 10 partitions): ``` >>> python3 producer.py '1' produced in partition: 9 '2' produced in partition: 6 '3' produced in partition: 0 ``` #### Using SSL with aiokafka[¶](#using-ssl-with-aiokafka) An example of SSL usage with **aiokafka**. Please read [SSL Authentication](index.html#ssl-auth) for more information. ``` import asyncio from aiokafka import AIOKafkaProducer, AIOKafkaConsumer from aiokafka.helpers import create_ssl_context from kafka.common import TopicPartition context = create_ssl_context( cafile="./ca-cert", # CA used to sign certificate. # `CARoot` of JKS store container certfile="./cert-signed", # Signed certificate keyfile="./cert-key", # Private Key file of `certfile` certificate password="123123" ) async def produce_and_consume(): # Produce producer = AIOKafkaProducer( bootstrap_servers='localhost:9093', security_protocol="SSL", ssl_context=context) await producer.start() try: msg = await producer.send_and_wait( 'my_topic', b"Super Message", partition=0) finally: await producer.stop() consumer = AIOKafkaConsumer( "my_topic", bootstrap_servers='localhost:9093', security_protocol="SSL", ssl_context=context) await consumer.start() try: consumer.seek(TopicPartition('my_topic', 0), msg.offset) fetch_msg = await consumer.getone() finally: await consumer.stop() print("Success", msg, fetch_msg) if __name__ == "__main__": asyncio.run(produce_and_consume()) ``` Output: ``` >>> python3 ssl_consume_produce.py Success RecordMetadata(topic='my_topic', partition=0, topic_partition=TopicPartition(topic='my_topic', partition=0), offset=32) ConsumerRecord(topic='my_topic', partition=0, offset=32, timestamp=1479393347381, timestamp_type=0, key=None, value=b'Super Message', checksum=469650252, serialized_key_size=-1, serialized_value_size=13) ``` #### Local state and storing offsets outside of Kafka[¶](#local-state-and-storing-offsets-outside-of-kafka) While the default for Kafka applications is storing commit points in Kafka’s internal storage, you can disable that and use [`seek()`](index.html#aiokafka.AIOKafkaConsumer.seek) to move to stored points. This makes sense if you want to store offsets in the same system as results of computations (filesystem in example below). But that said, you will still probably want to use the coordinated consumer groups feature. This example shows extensive usage of [`ConsumerRebalanceListener`](index.html#aiokafka.abc.ConsumerRebalanceListener) to control what’s done before and after rebalance’s. Local State consumer: ``` import asyncio from aiokafka import AIOKafkaConsumer, ConsumerRebalanceListener from aiokafka.errors import OffsetOutOfRangeError import json import pathlib from collections import Counter FILE_NAME_TMPL = "/tmp/my-partition-state-{tp.topic}-{tp.partition}.json" class RebalanceListener(ConsumerRebalanceListener): def __init__(self, consumer, local_state): self.consumer = consumer self.local_state = local_state async def on_partitions_revoked(self, revoked): print("Revoked", revoked) self.local_state.dump_local_state() async def on_partitions_assigned(self, assigned): print("Assigned", assigned) self.local_state.load_local_state(assigned) for tp in assigned: last_offset = self.local_state.get_last_offset(tp) if last_offset < 0: await self.consumer.seek_to_beginning(tp) else: self.consumer.seek(tp, last_offset + 1) class LocalState: def __init__(self): self._counts = {} self._offsets = {} def dump_local_state(self): for tp in self._counts: fpath = pathlib.Path(FILE_NAME_TMPL.format(tp=tp)) with fpath.open("w+") as f: json.dump({ "last_offset": self._offsets[tp], "counts": dict(self._counts[tp]) }, f) def load_local_state(self, partitions): self._counts.clear() self._offsets.clear() for tp in partitions: fpath = pathlib.Path(FILE_NAME_TMPL.format(tp=tp)) state = { "last_offset": -1, # Non existing, will reset "counts": {} } if fpath.exists(): with fpath.open("r+") as f: try: state = json.load(f) except json.JSONDecodeError: pass self._counts[tp] = Counter(state['counts']) self._offsets[tp] = state['last_offset'] def add_counts(self, tp, counts, last_offset): self._counts[tp] += counts self._offsets[tp] = last_offset def get_last_offset(self, tp): return self._offsets[tp] def discard_state(self, tps): for tp in tps: self._offsets[tp] = -1 self._counts[tp] = Counter() async def save_state_every_second(local_state): while True: try: await asyncio.sleep(1) except asyncio.CancelledError: break local_state.dump_local_state() async def consume(): consumer = AIOKafkaConsumer( bootstrap_servers='localhost:9092', group_id="my_group", # Consumer must be in a group to commit enable_auto_commit=False, # Will disable autocommit auto_offset_reset="none", key_deserializer=lambda key: key.decode("utf-8") if key else "", ) await consumer.start() local_state = LocalState() listener = RebalanceListener(consumer, local_state) consumer.subscribe(topics=["test"], listener=listener) save_task = asyncio.create_task(save_state_every_second(local_state)) try: while True: try: msg_set = await consumer.getmany(timeout_ms=1000) except OffsetOutOfRangeError as err: # This means that saved file is outdated and should be # discarded tps = err.args[0].keys() local_state.discard_state(tps) await consumer.seek_to_beginning(*tps) continue for tp, msgs in msg_set.items(): counts = Counter() for msg in msgs: print("Process", tp, msg.key) counts[msg.key] += 1 local_state.add_counts(tp, counts, msg.offset) finally: await consumer.stop() save_task.cancel() await save_task if __name__ == "__main__": asyncio.run(consume()) ``` There are several points of interest in this example: > * We implement `RebalanceListener` to dump all counts and offsets before > rebalances. After rebalances we load them from the same files. It’s a kind > of cache to avoid re-reading all messages. > * We control offset reset policy manually by setting > `auto_offset_reset="none"`. We need it to catch [`OffsetOutOfRangeError`](index.html#aiokafka.errors.OffsetOutOfRangeError) > so we can clear cache if files were old and such offsets don’t exist > anymore in Kafka. > * As we count `keys` here, those will always be partitioned to the same > partition on produce. We will not have duplicate counts in different files. Output for 1st consumer: ``` >>> python examples/local_state_consumer.py Revoked set() Assigned {TopicPartition(topic='test', partition=0), TopicPartition(topic='test', partition=1), TopicPartition(topic='test', partition=2)} Heartbeat failed for group my_group because it is rebalancing Revoked {TopicPartition(topic='test', partition=0), TopicPartition(topic='test', partition=1), TopicPartition(topic='test', partition=2)} Assigned {TopicPartition(topic='test', partition=0), TopicPartition(topic='test', partition=2)} Process TopicPartition(topic='test', partition=2) 123 Process TopicPartition(topic='test', partition=2) 9999 Process TopicPartition(topic='test', partition=2) 1111 Process TopicPartition(topic='test', partition=0) 4444 Process TopicPartition(topic='test', partition=0) 123123 Process TopicPartition(topic='test', partition=0) 5555 Process TopicPartition(topic='test', partition=2) 88891823 Process TopicPartition(topic='test', partition=2) 2 ``` Output for 2nd consumer: ``` >>> python examples/local_state_consumer.py Revoked set() Assigned {TopicPartition(topic='test', partition=1)} Process TopicPartition(topic='test', partition=1) 321 Process TopicPartition(topic='test', partition=1) 777 ``` Those create such files as a result: ``` >>> cat /tmp/my-partition-state-test-0.json && echo {"last_offset": 4, "counts": {"123123": 1, "4444": 1, "321": 2, "5555": 1}} ``` #### Batch producer[¶](#batch-producer) If your application needs precise control over batch creation and submission and you’re willing to forego the niceties of automatic serialization and partition selection, you may use the simple [`create_batch()`](index.html#aiokafka.AIOKafkaProducer.create_batch) and [`send_batch()`](index.html#aiokafka.AIOKafkaProducer.send_batch) interface. Producer ``` import asyncio import random from aiokafka.producer import AIOKafkaProducer async def send_many(num): topic = "my_topic" producer = AIOKafkaProducer() await producer.start() batch = producer.create_batch() i = 0 while i < num: msg = ("Test message %d" % i).encode("utf-8") metadata = batch.append(key=None, value=msg, timestamp=None) if metadata is None: partitions = await producer.partitions_for(topic) partition = random.choice(tuple(partitions)) await producer.send_batch(batch, topic, partition=partition) print("%d messages sent to partition %d" % (batch.record_count(), partition)) batch = producer.create_batch() continue i += 1 partitions = await producer.partitions_for(topic) partition = random.choice(tuple(partitions)) await producer.send_batch(batch, topic, partition=partition) print("%d messages sent to partition %d" % (batch.record_count(), partition)) await producer.stop() asyncio.run(send_many(1000)) ``` Output (topic `my_topic` has 3 partitions): ``` >>> python3 batch_produce.py 329 messages sent to partition 2 327 messages sent to partition 0 327 messages sent to partition 0 17 messages sent to partition 1 ``` #### Transactional Consume-Process-Produce[¶](#transactional-consume-process-produce) If you have a pattern where you want to consume from one topic, process data and produce to a different one, you would really like to do it with using Transactional Producer. In the example below we read from `IN_TOPIC`, process data and produce the resut to `OUT_TOPIC` in a transactional manner. ``` import asyncio from collections import defaultdict, Counter from aiokafka import TopicPartition, AIOKafkaConsumer, AIOKafkaProducer IN_TOPIC = "in_topic" GROUP_ID = "processing-group" OUT_TOPIC = "out_topic" TRANSACTIONAL_ID = "my-txn-id" BOOTSTRAP_SERVERS = "localhost:9092" POLL_TIMEOUT = 60_000 def process_batch(msgs): # Group by key do simple count sampling by a minute window buckets_by_key = defaultdict(Counter) for msg in msgs: timestamp = (msg.timestamp // 60_000) * 60 buckets_by_key[msg.key][timestamp] += 1 res = [] for key, counts in buckets_by_key.items(): for timestamp, count in counts.items(): value = str(count).encode() res.append((key, value, timestamp)) return res async def transactional_process(): consumer = AIOKafkaConsumer( IN_TOPIC, bootstrap_servers=BOOTSTRAP_SERVERS, enable_auto_commit=False, group_id=GROUP_ID, isolation_level="read_committed" # <-- This will filter aborted txn's ) await consumer.start() producer = AIOKafkaProducer( bootstrap_servers=BOOTSTRAP_SERVERS, transactional_id=TRANSACTIONAL_ID ) await producer.start() try: while True: msg_batch = await consumer.getmany(timeout_ms=POLL_TIMEOUT) async with producer.transaction(): commit_offsets = {} in_msgs = [] for tp, msgs in msg_batch.items(): in_msgs.extend(msgs) commit_offsets[tp] = msgs[-1].offset + 1 out_msgs = process_batch(in_msgs) for key, value, timestamp in out_msgs: await producer.send( OUT_TOPIC, value=value, key=key, timestamp_ms=int(timestamp * 1000) ) # We commit through the producer because we want the commit # to only succeed if the whole transaction is done # successfully. await producer.send_offsets_to_transaction( commit_offsets, GROUP_ID) finally: await consumer.stop() await producer.stop() if __name__ == "__main__": asyncio.run(transactional_process()) ``` Indices and tables[¶](#indices-and-tables) === * [Index](genindex.html) * [Module Index](py-modindex.html) * [Search Page](search.html) [aiokafka](#) === Apache Kafka client for asyncio ### Navigation * [Producer client](index.html#document-producer) * [Consumer client](index.html#document-consumer) * [Difference between aiokafka and kafka-python](index.html#document-kafka-python_difference) * [API Documentation](index.html#document-api) * [Examples](index.html#document-examples) ### Quick search
mrfse
cran
R
Package ‘mrfse’ November 16, 2022 Title Markov Random Field Structure Estimator Version 0.4.1 Date 2022-11-10 Description Three algorithms for estimating a Markov random field structure.Two of them are an ex- act version and a simulated annealing version of a penalized maximum conditional likeli- hood method similar to the Bayesian Information Criterion. These algorithm are de- scribed in Frondana (2016) <doi:10.11606/T.45.2018.tde-02022018- 151123>.The third one is a greedy algorithm, de- scribed in Bresler (2015) <doi:10.1145/2746539.2746631). License GPL (>= 3) NeedsCompilation yes LinkingTo Rcpp Imports Rcpp Depends gtools, Rfast Author <NAME> [aut, cre], <NAME> [rev, ths] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2022-11-16 14:40:15 UTC R topics documented: mrfse.c... 2 mrfse.ci.co... 3 mrfse.ci.nco... 4 mrfse.create.sample... 5 mrfse.exac... 6 mrfse.exact.co... 7 mrfse.exact.nco... 8 mrfse.s... 9 mrfse.sa.co... 10 mrfse.sa.nco... 11 mrfse.sampl... 12 mrfse.ci Bresler’s non-binary Markov random field structure estimator Description A greedy algorithm to estimate Markovian neighborhoods. Usage mrfse.ci(a_size, sample, tau, max_degree=ncol(sample)-1) Arguments a_size Size of the alphabet. sample A integer-valued matrix. Each value must belong range 0 and a_size - 1. Ma- trix has dimension n x V, where n is number of samples and V is number of nodes. tau A hyperparameter. See references. max_degree The maximum length of a candidate Markovian neighborhood. Must be non- negative and less than ncol(sample). Value A list filled with estimated Markov neighborhood for each graph vertex Author(s) <NAME> References <NAME>. 2015. Efficiently Learning Ising Models on Arbitrary Graphs. In Proceedings of the forty-seventh annual ACM symposium on Theory of Computing (STOC ’15). Association for Com- puting Machinery, New York, NY, USA, 771–782. DOI:https://doi.org/10.1145/2746539.2746631 Examples library(mrfse) a_size = c(0, 1) s = matrix(sample(a_size, size=1000, replace=TRUE), ncol=5) mrfse.ci(length(a_size), s, 0.2) mrfse.ci.con Conservative approach for Bresler’s non-binary estimator Description A greedy algorithm to estimate Markovian neighborhoods. Usage mrfse.ci.con(a_size, sample, tau, max_degree=ncol(sample)-1) Arguments a_size Size of the alphabet. sample A integer-valued matrix. Each value must belong range 0 and a_size - 1. Ma- trix has dimension n x V, where n is number of samples and V is number of nodes. tau A hyperparameter. See references. max_degree The maximum length of a candidate Markovian neighborhood. Must be non- negative and less than ncol(sample). Value A adjacency matrix of the estimated Markov random field graph. Author(s) <NAME> References <NAME>. 2015. Efficiently Learning Ising Models on Arbitrary Graphs. In Proceedings of the forty-seventh annual ACM symposium on Theory of Computing (STOC ’15). Association for Com- puting Machinery, New York, NY, USA, 771–782. DOI:https://doi.org/10.1145/2746539.2746631 Examples library(mrfse) a_size = c(0, 1) s = matrix(sample(a_size, size=1000, replace=TRUE), ncol=5) mrfse.ci.con(length(a_size), s, 0.2) mrfse.ci.ncon Non-conservative approach for Bresler’s non-binary estimator Description A greedy algorithm to estimate Markovian neighborhoods. Usage mrfse.ci.ncon(a_size, sample, tau, max_degree=ncol(sample)-1) Arguments a_size Size of the alphabet. sample A integer-valued matrix. Each value must belong range 0 and a_size - 1. Ma- trix has dimension n x V, where n is number of samples and V is number of nodes. tau A hyperparameter. See references. max_degree The maximum length of a candidate Markovian neighborhood. Must be non- negative and less than ncol(sample). Value A adjacency matrix of the estimated Markov random field graph. Author(s) <NAME> References <NAME>. 2015. Efficiently Learning Ising Models on Arbitrary Graphs. In Proceedings of the forty-seventh annual ACM symposium on Theory of Computing (STOC ’15). Association for Com- puting Machinery, New York, NY, USA, 771–782. DOI:https://doi.org/10.1145/2746539.2746631 Examples library(mrfse) a_size = c(0, 1) s = matrix(sample(a_size, size=1000, replace=TRUE), ncol=5) mrfse.ci.ncon(length(a_size), s, 0.2) mrfse.create.sampler Create a sampler for Markov random field. Description Create a sampler for Markov random field from a DAG Usage mrfse.create.sampler(dag_adj, A) Arguments dag_adj An direct acyclic graph adjacency matrix A Size of alphabet Value A list filled with the following components: neigh: A list of neighborhood. For each i, neigh[[i]] is a markovian neighborhood of vertex i probs: A list of probabilities. For each i, probs[[i]] is matrix of probabilities of vertex i given your markovian neighborhood. Those probabilites will be used to generate a sample. moral_adj: moral graph of adj_dag topol_sort: topological sort of adj_dag num_nodes: number of nodes de adj_dag A: alphabet size Author(s) <NAME> Examples library(mrfse) adj = matrix(c(0, 1, 0, 0, 0, 0, 0, 1, 0), byrow=TRUE, ncol=3) mrfse.create.sampler(adj, 3) mrfse.exact A Markov random field structure estimator Description A penalized likelihood BIC-based to estimate Markovian neighborhoods. Usage mrfse.exact(a_size, sample, c, max_neigh= ncol(sample) - 1) Arguments a_size Size of the alphabet. sample A integer-valued matrix. Each value must belong range 0 and a_size - 1. Ma- trix has dimension n x V, where n is number of samples and V is number of nodes. c The penalization constant. Must be positive. max_neigh The maximum length of a candidate Markovian neighborhood. Must be non- negative and less than ncol(sample). Value A list filled with estimated Markov neighborhood for each graph vertex Author(s) <NAME> References FRONDANA, <NAME>. Model selection for discrete Markov random fields on graphs. São Paulo : Instituto de Matemática e Estatística, University of São Paulo, 2016. Doctoral Thesis in Es- tatística. <doi:10.11606/T.45.2018.tde-02022018-151123> http://www.teses.usp.br/teses/ disponiveis/45/45133/tde-02022018-151123/publico/tese_Iara_Frondana.pdf Examples library(mrfse) a_size = c(0, 1) s = matrix(sample(a_size, size=1000, replace=TRUE), ncol=5) mrfse.exact(length(a_size), s, 1.0) mrfse.exact.con Conservative approach for Frondana’s mrfse Description Conservative construction of the estimated Markov random field graph. Usage mrfse.exact.con(a_size, sample, c, max_neigh = ncol(sample) - 1) Arguments a_size Size of the alphabet. sample A integer-valued matrix. Each value must belong range 0 and a_size - 1. Ma- trix has dimension n x V, where n is number of samples and V is number of nodes. c The penalization constant. Must be positive. max_neigh The maximum length of a candidate Markovian neighborhood. Must be non- negative and less than ncol(sample). Value A adjacency matrix of the estimated Markov random field graph. Author(s) <NAME> References FRONDANA, <NAME>. Model selection for discrete Markov random fields on graphs. São Paulo : Instituto de Matemática e Estatística, University of São Paulo, 2016. Doctoral Thesis in Es- tatística. <doi:10.11606/T.45.2018.tde-02022018-151123> http://www.teses.usp.br/teses/ disponiveis/45/45133/tde-02022018-151123/publico/tese_Iara_Frondana.pdf Examples library(mrfse) a = c(0, 1) s = matrix(sample(a, size=1000, replace=TRUE), ncol=5) mrfse.exact.con(length(a), s, 1.0) mrfse.exact.ncon Non-conservative approach for Frondana’s mrfse Description Conservative construction of the estimated Markov random field graph. Usage mrfse.exact.ncon(a_size, sample, c, max_neigh = ncol(sample) - 1) Arguments a_size Size of the alphabet. sample A integer-valued matrix. Each value must belong range 0 and a_size - 1. Ma- trix has dimension n x V, where n is number of samples and V is number of nodes. c The penalization constant. Must be positive. max_neigh The maximum length of a candidate Markovian neighborhood. Must be non- negative and less than ncol(sample). Value A adjacency matrix of the estimated Markov random field graph. Author(s) <NAME> References FRONDANA, <NAME>. Model selection for discrete Markov random fields on graphs. São Paulo : Instituto de Matemática e Estatística, University of São Paulo, 2016. Doctoral Thesis in Es- tatística. <doi:10.11606/T.45.2018.tde-02022018-151123> http://www.teses.usp.br/teses/ disponiveis/45/45133/tde-02022018-151123/publico/tese_Iara_Frondana.pdf Examples library(mrfse) a = c(0, 1) s = matrix(sample(a, size=1000, replace=TRUE), ncol=5) mrfse.exact.ncon(length(a), s, 1.0) mrfse.sa A Markov random field structure estimator using simulated annealing approach Description A penalized likelihood BIC-based to estimate Markovian neighborhoods. Usage mrfse.sa(a_size, sample, c, t0, iterations=1000, max_neigh=ncol(sample)-1) Arguments a_size Size of the alphabet. sample A integer-valued matrix. Each value must belong range 0 and a_size - 1. Ma- trix has dimension n x V, where n is number of samples and V is number of nodes. c The penalization constant. Must be positive. t0 Inital temperature iterations Number of simulated annealing iterations max_neigh The maximum length of a candidate Markovian neighborhood. Must be non- negative and less than ncol(sample). Value A list filled with estimated Markov neighborhood for each graph vertex Author(s) <NAME> References FRONDANA, <NAME>. Model selection for discrete Markov random fields on graphs. São Paulo : Instituto de Matemática e Estatística, University of São Paulo, 2016. Doctoral Thesis in Es- tatística. <doi:10.11606/T.45.2018.tde-02022018-151123> http://www.teses.usp.br/teses/ disponiveis/45/45133/tde-02022018-151123/publico/tese_Iara_Frondana.pdf Examples library(mrfse) a_size = c(0, 1) s = matrix(sample(a_size, size=1000, replace=TRUE), ncol=5) mrfse.sa(length(a_size), s, 1.0, 500, 1000) mrfse.sa.con Cnservative approach for Frondana’s mrfse using simulated annealing Description A penalized likelihood BIC-based to estimate Markovian neighborhoods. Usage mrfse.sa.con(a_size, sample, c, t0, iterations=1000, max_neigh=ncol(sample)-1) Arguments a_size Size of the alphabet. sample A integer-valued matrix. Each value must belong range 0 and a_size - 1. Ma- trix has dimension n x V, where n is number of samples and V is number of nodes. c The penalization constant. Must be positive. t0 Inital temperature iterations Number of simulated annealing iterations max_neigh The maximum length of a candidate Markovian neighborhood. Must be non- negative and less than ncol(sample). Value A adjacency matrix of the estimated Markov random field graph. Author(s) <NAME> References FRONDANA, <NAME>. Model selection for discrete Markov random fields on graphs. São Paulo : Instituto de Matemática e Estatística, University of São Paulo, 2016. Doctoral Thesis in Es- tatística. <doi:10.11606/T.45.2018.tde-02022018-151123> http://www.teses.usp.br/teses/ disponiveis/45/45133/tde-02022018-151123/publico/tese_Iara_Frondana.pdf Examples library(mrfse) a_size = c(0, 1) s = matrix(sample(a_size, size=1000, replace=TRUE), ncol=5) mrfse.sa.con(length(a_size), s, 1.0, 500, 1000) mrfse.sa.ncon Non-conservative approach for Frondana’s mrfse using simulated an- nealing Description A penalized likelihood BIC-based to estimate Markovian neighborhoods. Usage mrfse.sa.ncon(a_size, sample, c, t0, iterations=1000, max_neigh=ncol(sample)-1) Arguments a_size Size of the alphabet. sample A integer-valued matrix. Each value must belong range 0 and a_size - 1. Ma- trix has dimension n x V, where n is number of samples and V is number of nodes. c The penalization constant. Must be positive. t0 Inital temperature iterations Number of simulated annealing iterations max_neigh The maximum length of a candidate Markovian neighborhood. Must be non- negative and less than ncol(sample). Value A adjacency matrix of the estimated Markov random field graph. Author(s) <NAME> References FRONDANA, <NAME>. Model selection for discrete Markov random fields on graphs. São Paulo : Instituto de Matemática e Estatística, University of São Paulo, 2016. Doctoral Thesis in Es- tatística. <doi:10.11606/T.45.2018.tde-02022018-151123> http://www.teses.usp.br/teses/ disponiveis/45/45133/tde-02022018-151123/publico/tese_Iara_Frondana.pdf Examples library(mrfse) a_size = c(0, 1) s = matrix(sample(a_size, size=1000, replace=TRUE), ncol=5) mrfse.sa.ncon(length(a_size), s, 1.0, 500, 1000) mrfse.sample Generate a independent sample of a Markov random field Description Generate a independent sample of a Markov random field according to the probilities of the sampler. Usage mrfse.sample(sampler, n) Arguments sampler A sampler created by mrfse.create.sampler function n Size of sample Value A matrix whose number of columns is the number of nodes. Each line is a single independent sample of Markov random field given by the probabilites of sampler. Author(s) <NAME> Examples library(mrfse) adj = matrix(c(0, 1, 0, 0, 0, 0, 0, 1, 0), byrow=TRUE, ncol=3) sampler = mrfse.create.sampler(adj, 3) mrfse.sample(sampler, 3000)
Numero
cran
R
Package ‘Numero’ January 9, 2023 Type Package Title Statistical Framework to Define Subgroups in Complex Datasets Version 1.9.5 Date 2023-01-09 Author <NAME> [aut], <NAME> [aut], <NAME> [aut], <NAME> [aut, cre] Maintainer <NAME> <<EMAIL>> Description High-dimensional datasets that do not exhibit a clear intrinsic clustered struc- ture pose a challenge to conventional clustering algorithms. For this reason, we developed an un- supervised framework that helps scientists to better subgroup their datasets based on vi- sual cues, please see <NAME>, <NAME>, <NAME>, Makinen V-P (2019) Numero: a statisti- cal framework to define multivariable subgroups in complex population-based datasets, Int J Epi- demiology, 48:369-37, <doi:10.1093/ije/dyy113>. The framework includes the necessary func- tions to construct a self-organizing map of the data, to evaluate the statistical signifi- cance of the observed data patterns, and to visualize the results. License GPL (>= 2) Imports Rcpp (>= 1.0.0) LinkingTo Rcpp VignetteBuilder knitr, rmarkdown Suggests knitr, rmarkdown NeedsCompilation yes Repository CRAN SystemRequirements C++11 Encoding UTF-8 Date/Publication 2023-01-09 08:10:12 UTC R topics documented: nroAggregat... 2 nroColoriz... 3 nroDestratif... 5 nroKmean... 6 nroKohone... 7 nroLabe... 8 nroMatc... 10 nroPermut... 11 nroPlo... 12 nroPostproces... 15 nroPreproces... 16 nroSummar... 17 nroTrai... 19 numero.clea... 20 numero.creat... 22 numero.evaluat... 23 numero.plo... 24 numero.prepar... 26 numero.qualit... 27 numero.subgrou... 28 numero.summar... 29 nroAggregate Regional averages on a self-organizing map Description Estimate district averages based on assigned map locations for each data point. Usage nroAggregate(topology, districts, data = NULL) Arguments topology A data frame with K rows and six columns, see details. districts An integer vector of M best-matching districts. data A vector of M elements or an M x N matrix of data values. Details Topology can be either the output from nroKohonen() or a data frame in the same format as the element topology within the the output from nroKohonen(). The input argument districts is expected to be the output from nroMatch(). Value If the input argument data is empty, the histogram of the data points on the map is returned (a vector of K elements). If data are available, a matrix of K rows and N columns that contains the average district values after smoothing is returned. The output includes the attribute ’histogram’ that contains data point counts over each data column. Column names and the attribute ’binary’ are copied from the input. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Prepare training data. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- scale.default(dataset[,trvars]) # K-means clustering. km <- nroKmeans(data = trdata) # Self-organizing map. sm <- nroKohonen(seeds = km) sm <- nroTrain(map = sm, data = trdata) # Assign data points into districts. matches <- nroMatch(centroids = sm, data = trdata) # District averages for one variable. chol <- nroAggregate(topology = sm, districts = matches, data = dataset$CHOL) print(chol) # District averages for all variables. planes <- nroAggregate(topology = sm, districts = matches, data = dataset) print(head(planes)) nroColorize Assign colors based on value Description Assign colors to map districts based on the respective district values. Usage nroColorize(values, ranges = NULL, amplitudes = 1, palette = "rhodo") Arguments values A vector of K values or a K x N data frame, where K is the number of map districts and N is the number of variables. ranges A data frame with N rows and 2 columns, see details. amplitudes Single value or a vector of N elements or a data frame of N rows that contains the column AMPLITUDE. palette One of pre-defined colormap names (see details). Details The argument ranges sets the minimum and maximum district values irrespective of the contents of values. It can be used as a fixed reference across different colorings to ensure that the same value produces the same color across function calls. The argument amplitudes controls the proportion of the color range that is available for the district value range. For proportions below 1, the minimum district value is assigned to a color that is between the first and middle element in the color palette, and the maximum is assigned to a color that is between the middle and the last element. If amplitude is greater than 1, extreme low and high values are clipped to the first and last color in the palette, respectively. Available color palettes include "grey", "fire", "jungle", "miami", "rhodo" or "tan". Any other word will revert to a rainbow colormap. Value A matrix of hexadecimal color codes as strings. The output also includes the attribute ’contrast’ that indicates which colors have a good contrast with black as opposed to white, the attribute ’ranges’ that contains a copy of the dynamic ranges across districts, and the attribute ’palette’ that indicates the color scheme. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Prepare training data. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- scale.default(dataset[,trvars]) # K-means clustering. km <- nroKmeans(data = trdata) # Self-organizing map. sm <- nroKohonen(seeds = km) sm <- nroTrain(map = sm, data = trdata) # Assign data points into districts. matches <- nroMatch(centroids = sm, data = trdata) # District averages for all variables. planes <- nroAggregate(topology = sm, districts = matches, data = dataset) # District colors for cholesterol. chol <- nroColorize(values = planes[,"CHOL"]) print(head(chol)) # District colors for all variables. colrs <- nroColorize(values = planes) print(head(colrs)) nroDestratify Mitigate data stratification Description Removes differences in value distribution within subsets of data points. Usage nroDestratify(data, labels) Arguments data A matrix or a data frame with M rows. labels A vector of M subset labels. Details Only non-binary numerical columns are processed, the rest will be excluded from the results. The de-stratification algorithm is based on ranked data: the distribution of each subset will be mapped to the pooled distribution over all subsets by matching subset-specific ranking with ranking of all values. Value A matrix of de-stratified values. The output also includes the attribute ’incomplete’ that lists those columns where (some of) the values were set to missing due to processing failures. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Remove sex differences for creatinine. creat <- nroDestratify(dataset$CREAT, dataset$MALE) # Compare creatinine distributions. men <- which(dataset$MALE == 1) women <- which(dataset$MALE == 0) print(summary(dataset[men,"CREAT"])) print(summary(dataset[women,"CREAT"])) print(summary(creat[men])) print(summary(creat[women])) # Remove sex differences (produces warnings for binary traits). ds <- nroDestratify(dataset, dataset$MALE) # Compare HDL2C distributions. print(summary(dataset[men,"HDL2C"])) print(summary(dataset[women,"HDL2C"])) print(summary(ds[men,"HDL2C"])) print(summary(ds[women,"HDL2C"])) nroKmeans K-means clustering Description K-means clustering for multi-dimensional data. Usage nroKmeans(data, k = 3, subsample = NULL, balance = 0, message = NULL) Arguments data A data frame or a matrix. k Number of centroids. subsample Number of randomly selected rows used during a single training cycle. balance Penalty parameter for size difference between clusters. message If positive, progress information is printed at the specified interval in seconds. Details The K centroids are determined by Lloyd’s algorithm with Euclidean distances or by using 1 - Pearson correlation as the distance measure. If subsample is less than the number of data rows, a random subset of the specified size is used for each training cycle. By default, subsample is set automatically depending on the size of the dataset. If balance = 0.0, the algorithm is applied with no balancing, if balance = 1.0 all the clusters will be forced to be of equal size. Intermediate values are permitted. Note that if subsampling is applied, balancing may become less accurate. Value A list with named elements: centroids is a matrix of the main results, layout contains the best- matching centroid labels and model residuals for each usable data point and history is the chrono- logical record of training errors. The subsampling parameter that was used during training is stored in the element subsample. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Prepare training data. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- scale.default(dataset[,trvars]) # Unbalanced K-means clustering. km0 <- nroKmeans(data = trdata, k = 5, balance = 0.0) print(table(km0$layout$BMC)) print(km0$centroids) # Balanced K-means clustering. km1 <- nroKmeans(data = trdata, k = 5, balance = 1.0) print(table(km1$layout$BMC)) print(km1$centroids) nroKohonen Self-organizing map Description Interpolates the initial district profiles of a self-organizing map based on pre-determined seed pro- files. Usage nroKohonen(seeds, radius = 3, smoothness = 1.0) Arguments seeds A matrix or a data frame of K rows and N columns. radius Map radius. smoothness Rigidity of the map to adapt to regional differences. Value A list of named elements: centroids contains the N-dimensional district profiles, and topology is an H x 6 matrix that contains the 2D spatial layout for the map districts: the first two columns (X, Y) indicate the positions of districts in Cartesian coordinates, the other four columns (RADIUS1, RADIUS2, ANGLE1, ANGLE2) define the perimeter of the district areas for visualisation on a circular map. Additional parameters are stored as attributes in topology. The function is named after <NAME>, the inventor of the self-organizing map. See Also Please see nroKmeans() to create the seeds. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Prepare training data. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- scale.default(dataset[,trvars]) # K-means clustering. km <- nroKmeans(data = trdata) # Self-organizing map. sm <- nroKohonen(seeds = km) print(head(sm$centroids)) print(head(sm$topology)) nroLabel Label pruning Description Optimize the look and selection of labels on map districts. Usage nroLabel(topology, values, gap = 2.3) Arguments topology A data frame with K rows and six columns, see details. values A vector of K values or a K x N data frame, where K is the number of map districts and N is the number of variables. gap Minimum distance between map districts with non-empty labels. Details The function assigns visible labels for districts based on the absolute deviations from the average district value. The most extreme districts are picked first, and then the remaining districts are prioritized based on their value and distance to the other districts already labeled. Columns that are listed in the attribute "binary" in values are given percentage labels. Topology can be either the output from nroKohonen() or a data frame in the same format as the element topology within the aforementioned output list. Value A matrix with K rows and N columns that contains selected labels for the map districts for each of the columns in values. The output has the attribute ’visible’ that contains binary flags to guide visibility. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Prepare training data. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- scale.default(dataset[,trvars]) # K-means clustering. km <- nroKmeans(data = trdata) # Self-organizing map. sm <- nroKohonen(seeds = km) sm <- nroTrain(map = sm, data = trdata) # Assign data points into districts. matches <- nroMatch(centroids = sm, data = trdata) # District averages for all variables. planes <- nroAggregate(topology = sm, districts = matches, data = dataset) # District labels for cholesterol. chol <- nroLabel(topology = sm, values = planes[,"CHOL"]) print(head(attr(chol, "visible"))) print(head(chol)) # District labels for all variables. colrs <- nroLabel(topology = sm, values = planes) print(head(attr(colrs, "visible"))) print(head(colrs)) nroMatch Best-matching districts Description Compare multi-dimensional data points against the district profiles of a self-organizing map (SOM). Usage nroMatch(centroids, data) Arguments centroids Either a matrix, a data frame or a list that contains the element centroids. data A data matrix with identical column names to the centroid matrix. Details The input argument centroids can be a matrix or a data frame that contains multivariable data profiles organized row-wise. It can also be the output list object from nroKmeans() or nroTrain(). Value A vector of integers with elements corresponding to the rows in data. Each element contains the index of the best matching row from centroids. The vector also has the attribute ’quality’ that contains three columns: RESIDUAL is the distance between a point and a centroid in data space (shorter is better), RESIDUAL.z is a scale-independent version of RESIDUAL if the mean residual and standard deviation are available from training his- tory, and COVERAGE shows the proportion of data elements that were available for matching. The names of the columns that were used for matching are stored in the attribute variables. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Prepare training data. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- scale.default(dataset[,trvars]) # K-means clustering. km <- nroKmeans(data = trdata, k = 10) # Assign data points into districts. matches <- nroMatch(centroids = km, data = trdata) print(head(attr(matches,"quality"))) print(table(matches)) nroPermute Permutation analysis of map layout Description Estimate the dynamic range and statistical significance for regional patterns on a self-organizing maps using permutations. Usage nroPermute(map, districts, data, n = 1000, message = NULL, zbase = NULL, seed = 0.0) Arguments map A list object in the format from nroTrain(). districts An integer vector of M best matching districts. data A numeric vector of M values or an M x N matrix (or data frame), where M is the number of data points and N is the number of variables. n Maximum number of permutations per variable. message If positive, progress information is printed at the specified interval in seconds. zbase Reference Z-score for determining color amplitudes. seed Seed value for random number generator. Details The input argument map must contain the map topology and the centroid profiles as returned by the functions nroKmeans(), nroKohonen(), or nroTrain(). The input argument districts must contain integers between 1 and K, where K is the number map units. Any other values will be ignored. Training variables and data points are detected by the column names of map$centroids, the at- tribute "variables" in districts and the names of elements in districts. Value A data frame with eight columns: P.z is a parametric estimate for statistical significance, P.freq is the frequency-based estimate for statistical signicance, and Z is the estimated z-score of how far the observed map plane is from the average randomly generated layout. N.data indicates how many data values were used and N.cycles tells the number of completed permutations. AMPLITUDE is a dynamic range modifier for colors that can be used in nroColorize(). The output also contains the attribute ’zbase’ that indicates the normalization factor for the color amplitudes. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Set row names. rownames(dataset) <- paste("r", 1:nrow(dataset), sep="") # Prepare training data. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- scale.default(dataset[,trvars]) # K-means clustering. km <- nroKmeans(data = trdata) # Self-organizing map. sm <- nroKohonen(seeds = km) sm <- nroTrain(map = sm, data = trdata) # Assign data points into districts. matches <- nroMatch(centroids = sm, data = trdata) # Estimate statistics for cholesterol chol <- nroPermute(map = sm, districts = matches, data = dataset$CHOL) print(chol[,c("TRAINING", "Z", "P.z", "P.freq")]) # Estimate statistics. stats <- nroPermute(map = sm, districts = matches, data = dataset) print(stats[,c("TRAINING", "Z", "P.z", "P.freq")]) nroPlot Plot a self-organizing map Description Create a graphical interface for selecting subgroups from multiple map colorings simultaneously. Usage nroPlot(topology, colors, labels = NULL, subplot = NULL, interactive = FALSE, clear = NULL) nroPlot.save(file, topology, colors, labels = NULL, subplot = NULL, font = 1.0) Arguments topology A data frame with K rows and six or more columns that contain the district positions of a self-organizing map and optional region assignments. colors A character vector with K elements or a K x N matrix of hexadecimal color codes as strings. labels A character vector with K elements or a K x N matrix of district labels. subplot A two-element vector that sets out the number of rows and columns for a grid layout of multiple colorings. clear If TRUE, all graphics devices are cleared when the plot is refreshed. interactive If TRUE, an interactive version of the plot is launched. file If non-empty, the figure is saved as an SVG or HTML file instead of plotting on graphics device. font Multiplier to adjust font size for SVG and HTML output. Details The input topology must follow the format from nroKohonen(), but may also contain the columns REGION, and REGION.label that specify the names for subsets of districts and the single character labels to be shown on top of those districts. The input can also be the list object as returned by nroKohonen(). The color input can include the attribute ’contrast’ that contains a binary vector or a matrix of equal size. If an element is set, it means a dark label or highlight will have better contrast with the background. The label input can include the attribute ’visible’ that contains a binary vector or a matrix of equal size. If an element is set, it means a label is visible, otherwise it will not be shown on the map. Some non-alphanumeric characters are not supported and will be automatically converted to "_". Too long labels or column names will be truncated. The default value for clear is TRUE to prevent multiple plot windows from accumulating within the RStudio. If you are running R from the terminal or using detached devices, setting clear to FALSE will retain the current window when refreshing. If the file name ends with ".html", an interactive HTML document is produced, otherwise an SVG document is created. We recommend opening the HTML file with a web browser to select regions on large maps (i.e. when the R plot window becomes too slow to use). The HTML page allows you to assign subgroups and to save the results as tab-delimited text. Value The main function returns a data frame with K rows that contains the topology and subgrouping information. The .save subroutine returns the number of bytes written in the output file. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Detect binary columns. dataset <- nroPreprocess(dataset, method = "") # Prepare training data. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- scale.default(dataset[,trvars]) # K-means clustering. km <- nroKmeans(data = trdata) # Self-organizing map. sm <- nroKohonen(seeds = km) sm <- nroTrain(map = sm, data = trdata) # Assign data points into districts. matches <- nroMatch(centroids = sm, data = trdata) # Select a subset of variables and detect binary data. vars <- c("AGE", "MALE", "uALB", "CHOL", "DIAB_KIDNEY", "DECEASED") selected <- nroPreprocess(dataset[,vars], method = "") # Calculate district averages for seleted variables. vars <- c("AGE", "MALE", "uALB", "CHOL", "DIAB_KIDNEY", "DECEASED") planes <- nroAggregate(topology = sm, districts = matches, data = selected) # Estimate statistics. stats <- nroPermute(map = sm, districts = matches, data = selected) # Set visuals. colrs <- nroColorize(values = planes, amplitudes = stats) labls <- nroLabel(topology = sm, values = planes) # Add subgrouping information. topo <- sm$topology topo$REGION <- "" topo$REGION[1:8] <- "Center" topo$REGION[9:21] <- "Perimeter" # Add subgroup labels. topo$REGION.label <- "" topo$REGION.label[1:8] <- "C" topo$REGION.label[9:21] <- "P" # Add subgroup colors. topo$REGION.color <- "" topo$REGION.color[1:8] <- "#00f00060" topo$REGION.color[9:21] <- "#f000f060" # Plot colorings on screen. nroPlot(topology = topo, colors = colrs, labels = labls) # Save colorings in file. #fn <- "colorings.html" #n <- nroPlot.save(file = fn, topology = topo, # colors = colrs, labels = labls) #cat(n, " bytes saved in '", fn, "'\n", sep="") nroPostprocess Standardization using existing parameters Description Process a new dataset using a standardization procedure that was created for another dataset Usage nroPostprocess(data, mapping, reverse = FALSE, trim = FALSE) Arguments data A matrix or a data frame with column names. mapping A list object or a matrix or a data frame. reverse If true, standardized data will be reverted back to original scale. trim If true, unusable rows and columns are removed. Details The input argument can be a data frame with the attribute ’mapping’ as returned from nroPreprocess() or a list object with the elements input and output that each contain a data frame or a matrix of equal size. The function projects the input data to the values in mapping$input to determine the positions of the input values with respect to the rows in the model. These positions are then used to interpolate corresponding output values in mapping$output. The mapping elements must have consistent row and column names. Value A matrix or data frame of processed values. Author(s) <NAME> Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Show original data characteristics. print(summary(dataset)) # Preprocess a subset of data. ds.pre <- nroPreprocess(dataset[1:100,]) print(summary(ds.pre)) # Repeat preprocessing for the whole dataset (approximation). ds.post <- nroPostprocess(dataset, ds.pre) print(summary(ds.post)) nroPreprocess Data cleaning and standardization Description Convert to numerical values, remove unusable rows and columns, and standardize scale of each variable. Usage nroPreprocess(data, method = "standard", clip = 5.0, resolution = 100, trim = FALSE) Arguments data A matrix or a data frame. method Method for standardizing scale and location, see details below. clip Range for clipping extreme values in multiples of standard deviations. resolution Maximum number of sampling points to capture distribution shape. trim if TRUE, empty rows and columns are removed. Details Standardization methods include empty string for no action, "standard" for centering by mean and division by standard deviation, "uniform" for normalized ranks between -1 and 1, "tapered" for a version of the rank-based method that puts more samples around zero and "normal" for quantile- based mapping to standard normal distribution. The standard method also checks if the distribution is skewed and applies logarithm if it makes the distribution closer to the normal curve. Clipping is not applied if the method is rank-based or if the threshold is set to NULL. Value A matrix of numerical values. A value mapping model is stored in the attribute ’mapping’. The names of binary columns are stored in the attribute ’binary’. Author(s) <NAME> Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Show original data characteristics. print(summary(dataset)) # Detect binary columns. ds <- nroPreprocess(dataset, method = "") print(attr(ds,"binary")) # Centering and scaling cholesterol. ds <- nroPreprocess(dataset$CHOL) print(summary(ds)) # Centering and scaling. ds <- nroPreprocess(dataset) print(summary(ds)) # Tapered ranks. ds <- nroPreprocess(dataset, method = "tapered") print(summary(ds)) # Standard normal ranks. ds <- nroPreprocess(dataset, method = "normal") print(summary(ds)) nroSummary Estimate subgroup statistics Description Combine data points that reside in districts that belong to a larger region into a subgroup; compare descriptive statistics between subgroups. Usage nroSummary(data, districts, regions = NULL, categlim = 8, capacity = 10) Arguments data A vector of named M elements or an M x N matrix of data values with row names. districts An integer vector of M named elements that indicate the best match out of K districts for each row name in the data matrix, please see nroMatch for an exam- ple. regions An vector of K elements or a data frame of K rows that defines if a district belongs to a larger region (i.e. a subgroup), see details. categlim The threshold for the number of unique values before a variable is considered continuous. capacity Maximum number of subgroups to compare. Details If defined, the region vector should have K elements where K is the total number of map districts. The region input can also be a data frame of K rows where the column REGION will be used for assigning district to regions, and REGION.label will be used as the character label as seen on the map, see the output from nroPlot() for an example. Districts and data points are connected by comparing element names in districts and names or row names of data. Districts and regions are connected by comparing element values in districts and names or row names of regions. If the region vector is empty, each district is automatically assigned to its own region. Safeguards are in place to prevent crashes from empty categories; this reduces statistical power slightly when numbers are small. Value A data frame of summary statistics that contains a row for every combination of subgroups and variables. The chi-squared test is used for comparisons with respect to categorical variables, and rank-regulated t-test and ANOVA are applied to continuous variables. Region labels for each row are stored in the attribute ’labels’ and a list that contains the subsets of rows in each region is stored in the attribute ’subgroups’. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Prepare training data. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- scale.default(dataset[,trvars]) # K-means clustering. km <- nroKmeans(data = trdata) # Self-organizing map. sm <- nroKohonen(seeds = km) sm <- nroTrain(map = sm, data = trdata) # Assign data points into districts. matches <- nroMatch(centroids = sm, data = trdata) # Calculate district averages for urinary albumin. plane <- nroAggregate(topology = sm, districts = matches, data = dataset$uALB) plane <- as.vector(plane) # Assign subgroups based on urinary albumin. regns <- rep("HighAlb", length.out=length(plane)) regns[which(plane < quantile(plane, 0.67))] <- "MiddleAlb" regns[which(plane < quantile(plane, 0.33))] <- "LowAlb" # Add label info and make a data frame. regns <- data.frame(REGION=regns, REGION.label="", stringsAsFactors=FALSE) regns[which(regns$REGION == "HighAlb"),"REGION.label"] <- "H" regns[which(regns$REGION == "MiddleAlb"),"REGION.label"] <- "M" regns[which(regns$REGION == "LowAlb"),"REGION.label"] <- "L" # Calculate summary statistics. st <- nroSummary(data = dataset, districts = matches, regions = regns) print(st[,c("VARIABLE","SUBGROUP","MEAN","P.chisq","P.t","P.anova")]) nroTrain Train self-organizing map Description Iterative algorithm to adapt a self-organizing map (SOM) to a set of multivariable data. Usage nroTrain(map, data, subsample = NULL, balance = 0, message = NULL) Arguments map A list object as returned by nroKohonen(). data A matrix or a data frame. subsample Number of rows used during a single training cycle. balance Penalty parameter for variation in the numbers of resident samples across disc- tricts, see nroKmeans(). message If positive, progress information is printed at the specified interval in seconds. Details The map is fitted according to columns that are found both in the SOM centroids and the input data. If subsample is less than the number of data rows, a random subset of the specified size is used for each training cycle. By default, subsample is set automatically depending on the size of the dataset. Value A copy of the list object map, where the element centroids is updated according to the data pat- terns. The quantization errors during training are stored in the element history. The subsampling parameter that was used during training is stored in the element subsample. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Prepare training data. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- scale.default(dataset[,trvars]) # K-means clustering. km <- nroKmeans(data = trdata) # Train with full data. sm <- nroKohonen(seeds = km) sm <- nroTrain(map = sm, data = trdata, subsample = nrow(trdata)) print(sm$history) # Train with subsampling. sm <- nroKohonen(seeds = km) sm <- nroTrain(map = sm, data = trdata, subsample = 200) print(sm$history) numero.clean Clean datasets Description Sets row names and removes unusable columns and rows. Usage numero.clean(..., identity = NULL, na.freq = 0.9, num.only = TRUE, select = "") Arguments ... Matrices or a data frames. identity Name(s) of the column(s) that contain identification information. na.freq The proportion of how many missing values are allowed in each column and in each row. num.only If true, only numeric columns are included. select Indicate if only identities present in all datasets or in exactly one of the datasets are included. Details If multiple identity columns are provided, composite identity keys are constructed by concatenating elements from each column with "_" added as a separator. The frequency of missing values (against /codena.freq) is tested first by column then by row. Selection can take three values: "" for no selection, "union" for all identities expanded to every dataset, "shared" for only those data points present in all usable datasets or "distinct" for excluding any points that can be found in more than one dataset. Note that the union may result in rows with no usable values. Value A data frame if only one input dataset, or a list of data frames if multiple datasets. Author(s) <NAME> Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Create new versions for testing. dsA <- dataset[1:250, c("INDEX","AGE","MALE","uALB")] dsB <- dataset[151:300, c("INDEX","AGE","MALE","uALB","CHOL")] dsC <- dataset[201:500, c("INDEX","AGE","MALE","DIAB_RETINO")] # Select all rows. results <- numero.clean(a = dsA, b = dsB, c = dsC, identity = "INDEX") cat("\n\nNo selection:\n") print(nrow(results$a)) print(nrow(results$b)) print(nrow(results$c)) # Select all rows and expanded for all identities. results <- numero.clean(a = dsA, b = dsB, c = dsC, identity = "INDEX", select = "union") cat("\n\nUnion:\n") print(nrow(results$a)) print(nrow(results$b)) print(nrow(results$c)) # Select only rows that are shared between all datasets. results <- numero.clean(a = dsA, b = dsB, c = dsC, identity = "INDEX", select = "intersection") cat("\n\nIntersection:\n") print(nrow(results$a)) print(nrow(results$b)) print(nrow(results$c)) # Select only rows with a unique INDEX ('dsB' has none). results <- numero.clean(a = dsA, b = dsB, c = dsC, identity = "INDEX", select = "exclusion") cat("\n\nExclusion:\n") print(nrow(results$a)) print(nrow(results$b)) print(nrow(results$c)) # Add extra identification information. dsA$GROUP <- "A" dsB$GROUP <- "B" dsC$GROUP <- "C" # Select rows with a unique identifier. results <- numero.clean(a = dsA, b = dsB, c = dsC, identity = c("GROUP","INDEX"), select = "exclusion") cat("\n\nMulti-identities:\n") print(nrow(results$a)) print(nrow(results$b)) print(nrow(results$c)) numero.create Create a self-organizing map Description Set up a self-organizing map and train it with data Usage numero.create(data, radius = NULL, smoothness = NULL, subsample = NULL) Arguments data A matrix or a data frame. radius Map radius. smoothness Rigidity of the map to adapt to regional differences. subsample Number of data points used during a single training cycle. Details The parameter subsample sets the number of data points that are randomly picked for each training cycle; if the number is substantially less than the size of the dataset, the function will finish quicker. Value A list with named elements: data contains the training data, kmeans is the output from nroKmeans() during the initialiation of the SOM, map is the finished self-organising map from nroTrain() and layout contains the output from nroMatch() for the training data points. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Set identities and manage missing data. dataset <- numero.clean(dataset, identity = "INDEX") # Prepare training set. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- numero.prepare(data = dataset, variables = trvars) # Create a self-organizing map. modl <- numero.create(data = trdata) numero.evaluate Self-organizing map statistics Description Evaluate regional variation of data values on a self-organizing map Usage numero.evaluate(model, data, ranked = TRUE, n = 1000) Arguments model A list object that contains a self-organizing map and a data layout. data A matrix or a data frame. ranked If true, a rank transform is applied to avoid problems from skewed distributions or outliers. n Maximum number of permutations per data column. Details The input argument model can be the output from numero.create() or from numero.quality(). Value A list with named elements: som contains the self-organizing map, layout contains the district as- signments for data points, planes contains smoothed district averages from nroAggregate(), the element ranges contains the reference ranges to be used in nroColorize(), the element statistics contains the output from nroPermute(), the element palette is the name of the colormap and the element data contains the data points that were used for calculating the statistics. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Set identities and manage missing data. dataset <- numero.clean(dataset, identity = "INDEX") # Prepare training variables. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- numero.prepare(data = dataset, variables = trvars) # Create a self-organizing map. sm <- numero.create(data = trdata) qc <- numero.quality(model = sm) # Evaluate map statistics. results <- numero.evaluate(model = qc, data = dataset) print(results$statistics[,c("TRAINING", "Z", "P.z", "P.freq")]) numero.plot Plot results from SOM analysis Description Plot map colorings and save them as vector graphics Usage numero.plot(results, variables = NULL, topology = NULL, folder = NULL, prefix = "figure", reference = NULL, subplot = NULL, gain = 1, detach = FALSE, capacity = 500, font = NULL) Arguments results A list object that contains the self-organizing map and its statistical colorings. variables A string vector that contains names of variables to show. topology The topology of a SOM with subgroup labels. folder Folder path for saving figures. prefix Prefix for each figure file (if saving enabled). reference Reference color ranges and scales. gain Modifier for overall color intensity. subplot A two-element vector that sets out the number of rows and columns for subplots per figure. detach Use detached windows for figures. capacity Maximum number of subplots to show on screen. font Multiplier to adjust font size for SVG and HTML output, see nroPlot.save(). Details The input results must contain the output from codenumero.evaluate() or similar. The input argument topology can be the topology of a SOM or with additional columns as in the output from numero.subgroup(). The input argument reference follows the output format from numero.evaluate(). Possible values for detach include "X11", "aqua", TRUE or FALSE. Using multiple figures may result in different behaviour in terminal vs. RStudio instances. The default behaviour is to create detached windows for each figure when the X11 display server is available (e.g. in Linux). To use detached windows in Mac, use the value "aqua". Setting detach = TRUE will use a more general approach, however, some systems may behave unpredictably. To create multiple figures that remain docked within the RStudio work window, set detach = FALSE. If a destination folder is provided, all plots are saved in files without plotting them on screen. Value The number of figures that were created. Author(s) <NAME> Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Set identities and manage missing data. dataset <- numero.clean(dataset, identity = "INDEX") # Prepare training variables. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- numero.prepare(data = dataset, variables = trvars, batch = "MALE", confounders = c("AGE", "T1D_DURAT")) # Create a self-organizing map. sm <- numero.create(data = trdata) qc <- numero.quality(model = sm) # Evaluate map statistics for all variables. stats <- numero.evaluate(model = qc, data = dataset) # Plot map colorings. numero.plot(results = stats) numero.prepare Prepare datasets for analysis Description Prepare training data by mitigating confounding factors and standardizing values. Usage numero.prepare(data, variables = NULL, confounders = NULL, batch = NULL, method = "standard", clip = 5.0, pipeline = NULL, undo = FALSE) Arguments data A matrix or a data frame. variables A character vector of column names, see details. confounders Names of columns that contain confounder data. batch The name of the column that contains batch labels. method Method to standardize values, see nroPreprocess(). clip Range for clipping extreme values in multiples of standard deviations. pipeline Processing parameters from a previous use of the function. undo If true, standardization is reversed after adjusting for batches and confounders. Details We recommend first applying numero.clean() to the full dataset, then selecting a subset for train- ing using the input argument variables. This preserves any attributes that may be used in Numero functions. If a previous pipeline is available, it overrides all processing parameters irrespective of other input arguments. Due to safeguards against numerical instability, the standardized values may deviate slightly from the expected range (<0.1 percent error is typical). Clipping of extreme values is applied only during the first round of standardization before adjust- ments for confounders. Therefore, the final output may contain values that exceed the threshold. Value A matrix with the attributes ’pipeline’ that contains the processing parameters and ’subsets’ that contains row names divided into batches if batch correction was applied. Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Set identities and manage missing data. dataset <- numero.clean(dataset, identity = "INDEX") # Prepare training variables using default standardization. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- numero.prepare(data = dataset, variables = trvars) print(summary(trdata)) # Prepare training values adjusted for age and sex and # standardized by rank-based method. trdata <- numero.prepare(data = dataset, variables = trvars, batch = "MALE", confounders = "AGE", method = "tapered") print(summary(trdata)) numero.quality Self-organizing map statistics Description Assign new data points to map districts and calculate quality measures Usage numero.quality(model, data = NULL) Arguments model A list object that contains a self-organizing map (and a data layout). data A matrix or a data frame. Details The input argument model must be in the the output format as returned by numero.create(). Value A list with named elements: som contains the self-organizing map; layout contains the district assignments for data points; planes contains smoothed district averages of quality measures, see nroAggregate() and nroMatch(); the element ranges contains the reference ranges to be used in nroColorize(); the element palette is the name of the colormap to be used for colorings; and statistics contains the output from nroPermute(). Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Set identities and manage missing data. dataset <- numero.clean(dataset, identity = "INDEX") # Prepare training variables. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- numero.prepare(data = dataset, variables = trvars) # Create a self-organizing map. modl <- numero.create(data = trdata) # Analyze map quality. qc <- numero.quality(model = modl) numero.subgroup Interactive subgroup assignment Description Plot self-organizing map colorings and let the user choose multi-district regions as subgroups Usage numero.subgroup(results, variables, topology = NULL, reference = NULL, gain = 1, detach = FALSE, capacity = 9, automatic = FALSE) Arguments results A list object that contains the self-organizing map and its statistical colorings. variables A string vector that contains names of variables to show on screen. topology A SOM topology or the output from a previous subgrouping session. reference Reference color ranges and scales. gain Modifier for overall color intensity. detach Use a detached window. capacity Maximum number of subplots to show on screen. automatic If greater than zero, automatic segmentation of the map is triggered, the value sets the number of subgroups. Details The input results must contain the output from numero.evaluate() or similar. The input argument topology can be the structure of a SOM or with additional columns as in the output from nroPlot(). The input argument reference follows the output format from numero.evaluate(). Setting detach to FALSE will also clear all devices whenever the figure is refreshed. This may be in- convenient when using R from the terminal, for example; please see the help page of numero.plot() for using a detached window device instead. If any districts are left unmarked, they are automatically collected into a subgroup of their own. If automatic is set, user input is skipped. Value A data frame similar to the format returned by nroPlot(). Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Set identities and manage missing data. dataset <- numero.clean(dataset, identity = "INDEX") # Prepare training variables. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- numero.prepare(data = dataset, variables = trvars) # Create a self-organizing map. sm <- numero.create(data = trdata) qc <- numero.quality(model = sm) # Evaluate map statistics for all variables. stats <- numero.evaluate(model = qc, data = dataset) # Define subgroups, uncomment to launch interactive window. #elem <- numero.subgroup(results = stats, variables = trvars) numero.summary Summarize subgroup statistics Description Estimates subgroup statistics after self-organizing map analysis Usage numero.summary(results, topology, data = NULL, capacity = 10) Arguments results A list object that contains the self-organizing map and its statistical colorings. topology A SOM topology with additional labels that indicate selected regions. data A matrix or a data frame. capacity Maximum number of subgroups to compare. Details The input results must contain the output from numero.evaluate() or similar. The input argument topology must be a definition of a SOM with additional columns as in the output from numero.subgroup(). The function first looks for row names in data that are also included in results. The rows are then divided into subgroups according to the district assignments in results and the region labels in topology. Value A data frame of summary statistics, see nroSummary() for details. The data frame also contains additional information on which variables were used for the training of the SOM. The attribute ’layout’ is added to the output. It indicates the location on the map and the subgroup name and label for each data row that were included in the analysis. Author(s) <NAME> Examples # Import data. fname <- system.file("extdata", "finndiane.txt", package = "Numero") dataset <- read.delim(file = fname) # Set identities and manage missing data. dataset <- numero.clean(dataset, identity = "INDEX") # Prepare training variables. trvars <- c("CHOL", "HDL2C", "TG", "CREAT", "uALB") trdata <- numero.prepare(data = dataset, variables = trvars) # Create a self-organizing map. sm <- numero.create(data = trdata) qc <- numero.quality(model = sm) # Evaluate map statistics for all variables. stats <- numero.evaluate(model = qc, data = dataset) # Define subgroups. x <- stats$planes[,"uALB"] tops <- which(x >= quantile(x, 0.75, na.rm=TRUE)) bottoms <- which(x <= quantile(x, 0.25, na.rm=TRUE)) elem <- data.frame(stats$map$topology, stringsAsFactors = FALSE) elem$REGION <- "MiddleAlb" elem$REGION[tops] <- "HighAlb" elem$REGION[bottoms] <- "LowAlb" elem$REGION.label <- "M" elem$REGION.label[tops] <- "H" elem$REGION.label[bottoms] <- "L" # Compare subgroups. cmp <- numero.summary(results = stats, topology = elem, data = dataset)
github.com/mattes/fugu
go
Go
README [¶](#section-readme) --- ![](https://github.com/mattes/fugu/raw/v1.1.1/fugu.png) ### What is fugu? * fugu is a convenience wrapper around docker commands * fugu loads config from a fugu.yml file and merges these arguments with command line flags. **Example** ``` # fugu.yml (maybe stored next to Dockerfile) image: ubuntu name: my-ubuntu publish: - 8080:80 ``` ``` $ fugu run --detach # runs ... docker run --detach --name=my-ubuntu --publish=8080:80 ubuntu ``` Fugu commands include: `build`, `run`, `exec`, `destroy`, `push`, `pull`, `images`. **[All commands and their usage](https://github.com/mattes/fugu/raw/v1/fugu/usage.txt)** and [example fugu.yml files](https://github.com/mattes/fugu/tree/v1/examples). ### Installation ``` # Mac OS X curl -L https://github.com/mattes/fugu/releases/download/v1.1.1/fugu.v1.1.1.darwin.x86_64.tar.gz | tar xvz mv fugu.v1.1.1.darwin.x86_64 /usr/local/bin/fugu chmod +x /usr/local/bin/fugu # Linux curl -L https://github.com/mattes/fugu/releases/download/v1.1.1/fugu.v1.1.1.linux.x86_64.tar.gz | tar xvz mv fugu.v1.1.1.linux.x86_64 /usr/local/bin/fugu chmod +x /usr/local/bin/fugu ``` #### How is this different from docker-compose/ fig? While [docker-compose](https://docs.docker.com/compose) (originated from `fig`) focuses on the definition and orchestration of complex application environments, fugu focuses on one single docker container/ docker image. #### Changelog Find the changelog and breaking changes here: <https://github.com/mattes/fugu/releases--- [![Build Status](https://travis-ci.org/mattes/fugu.svg?branch=v1)](https://travis-ci.org/mattes/fugu) Fugu is built on top of [go-collect](https://github.com/mattes/go-collect). ##### Credits Thanks to [<NAME>](https://dribbble.com/golifter) for his nice fugu fish logo. Documentation [¶](#section-documentation) --- ### Index [¶](#pkg-index) * [Variables](#pkg-variables) * [func DockerExec(cmd string, printCmd bool)](#DockerExec) * [type RegistryDockerImage](#RegistryDockerImage) * + [func ListImages(registry, user, password string) ([]RegistryDockerImage, error)](#ListImages) * [type RegistryDockerImages](#RegistryDockerImages) * + [func (a RegistryDockerImages) Len() int](#RegistryDockerImages.Len) + [func (a RegistryDockerImages) Less(i, j int) bool](#RegistryDockerImages.Less) + [func (a RegistryDockerImages) Swap(i, j int)](#RegistryDockerImages.Swap) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) ``` var ( ErrTooManyArgs = [errors](/errors).[New](/errors#New)("too many arguments given") ErrMissingImage = [errors](/errors).[New](/errors#New)("image option is missing") ErrMissingName = [errors](/errors).[New](/errors#New)("name option is missing") ErrUnknownLabel = [errors](/errors).[New](/errors#New)("unknown label") ErrTagGitBranch = [errors](/errors).[New](/errors#New)("tag-git-branch failed") ErrMissingFlag = [errors](/errors).[New](/errors#New)("missing required flag") ErrNoCredentials = [errors](/errors).[New](/errors#New)("missing required credentials") ) ``` ``` var Commands = [make](/builtin#make)(map[[string](/builtin#string)]func(c *collect.Collector, p *[data](/github.com/mattes/go-collect/data).[Data](/github.com/mattes/go-collect/data#Data), args [][string](/builtin#string)) (err [error](/builtin#error))) ``` Commands have more freedom and usually print to stdout/stderr directly ``` var DockerCommands = [make](/builtin#make)(map[[string](/builtin#string)]func(c *collect.Collector, p *[data](/github.com/mattes/go-collect/data).[Data](/github.com/mattes/go-collect/data#Data), args [][string](/builtin#string)) (str [string](/builtin#string), err [error](/builtin#error))) ``` DockerCommands return string that is always run ``` var DockerFlags = [make](/builtin#make)(map[[string](/builtin#string)]*[flags](/github.com/mattes/go-collect/flags).[Flags](/github.com/mattes/go-collect/flags#Flags)) ``` ``` var FuguFlags = [make](/builtin#make)(map[[string](/builtin#string)]*[flags](/github.com/mattes/go-collect/flags).[Flags](/github.com/mattes/go-collect/flags#Flags)) ``` ### Functions [¶](#pkg-functions) #### func [DockerExec](https://github.com/mattes/fugu/blob/v1.1.1/helper.go#L20) [¶](#DockerExec) ``` func DockerExec(cmd [string](/builtin#string), printCmd [bool](/builtin#bool)) ``` DockerExec runs a docker command ### Types [¶](#pkg-types) #### type [RegistryDockerImage](https://github.com/mattes/fugu/blob/v1.1.1/helper.go#L80) [¶](#RegistryDockerImage) ``` type RegistryDockerImage struct { Name [string](/builtin#string) Tags [][string](/builtin#string) } ``` #### func [ListImages](https://github.com/mattes/fugu/blob/v1.1.1/helper.go#L91) [¶](#ListImages) ``` func ListImages(registry, user, password [string](/builtin#string)) ([][RegistryDockerImage](#RegistryDockerImage), [error](/builtin#error)) ``` #### type [RegistryDockerImages](https://github.com/mattes/fugu/blob/v1.1.1/helper.go#L85) [¶](#RegistryDockerImages) ``` type RegistryDockerImages [][RegistryDockerImage](#RegistryDockerImage) ``` #### func (RegistryDockerImages) [Len](https://github.com/mattes/fugu/blob/v1.1.1/helper.go#L87) [¶](#RegistryDockerImages.Len) ``` func (a [RegistryDockerImages](#RegistryDockerImages)) Len() [int](/builtin#int) ``` #### func (RegistryDockerImages) [Less](https://github.com/mattes/fugu/blob/v1.1.1/helper.go#L89) [¶](#RegistryDockerImages.Less) ``` func (a [RegistryDockerImages](#RegistryDockerImages)) Less(i, j [int](/builtin#int)) [bool](/builtin#bool) ``` #### func (RegistryDockerImages) [Swap](https://github.com/mattes/fugu/blob/v1.1.1/helper.go#L88) [¶](#RegistryDockerImages.Swap) ``` func (a [RegistryDockerImages](#RegistryDockerImages)) Swap(i, j [int](/builtin#int)) ```
modernperlbooks_com_books_modern_perl_2016
free_programming_book
SQL
Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. A Perl expert can solve a problem in a few lines of well-tested code. Now you can unlock these powers for yourself. Modern Perl is the Perl tutorial that teaches you how Perl really works. It's the only book that explains Perl thoroughly, from its philosophical roots to the pragmatic decisions that help you solve real problems—and keep them solved. You'll understand how the language fits together and discover the secrets used by the global Perl community. This beloved guide is now completely updated for Perl 5.22. * Perldoc * Expressivity * Context * Implicit Ideas * Names * Variables * Values * Control Flow * Scalars * Arrays * Hashes * Coercion * Packages * References * Nested Data Structures * Operator Characteristics * Operator Types * Declaring Functions * Invoking Functions * Function Parameters * Functions and Namespaces * Reporting Errors * Advanced Functions * Pitfalls and Misfeatures * Scope * Anonymous Functions * Closures * State versus Closures * State versus Pseudo-State * Attributes * AUTOLOAD * Literals * The qr// Operator and Regex Combinations * Quantifiers * Greediness * Regex Anchors * Metacharacters * Character Classes * Capturing * Grouping and Alternation * Other Escape Sequences * Assertions * Regex Modifiers * Smart Matching * Moose * Blessed References * Reflection * Advanced OO Perl * Writing Maintainable Perl * Writing Idiomatic Perl * Writing Effective Perl * Exceptions * Pragmas * Testing * Handling Warnings * Files * Modules * Distributions * The UNIVERSAL Package * Code Generation * Overloading * Taint * Idioms * Global Variables * Barewords * Indirect Objects * Prototypes * Method-Function Equivalence * Automatic Dereferencing * Tie Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. <NAME> released the first version of Perl in 1987. The language grew from its niche as a tool for system administrators who needed something more powerful than shell scripting and easier to use than C programming into a general-purpose programming language. Perl has a solid history of pragmatism and, in recent years, a disciplined approach to enhancement and backwards compatibility. Over Perl's long history—Perl 5 has been continually refined over the past twenty years—our understanding of what makes great Perl programs has changed. While you can write productive programs which never take advantage of all the language has to offer, the global Perl community has invented, borrowed, enhanced, and polished ideas and made them available to anyone willing to learn them. Modern Perl is a mindset. It's an approach to writing great software with the Perl programming language. It's how effective Perl programmers write powerful, maintainable, scalable, concise, and excellent code. It takes advantage of Perl's extensive library of free software (the CPAN) and language features designed to multiply your productivity. You'll benefit most from this book if you have some experience with Perl or another programming language already. If you're comfortable writing and executing programs (and happy to consult the documentation when it's mentioned), you'll get the most from this book. ## Running Modern Perl The `Modern::Perl` module from the CPAN (The CPAN) allows Perl to warn you of typos and other potential problems. It also enables new features introduced in modern Perl releases. Unless otherwise mentioned, all of the code snippets in this book assume you've started with this basic program skeleton: use Modern::Perl '2015'; use autodie; ``` If you don't have `Modern::Perl` installed, you could write instead: use 5.016; # implies "use strict;" use warnings; use autodie; ``` Some examples use testing functions such as `ok()` , `like()` , and `is()` (Testing). The skeleton for these examples is: use Modern::Perl; use Test::More; # example code here At the time of writing, the current stable major Perl release is Perl 5.22. If you're using an older version of Perl, you may not be able to run all of the examples in this book unmodified. The examples in this book work best with Perl 5.16.0 or newer, though we recommend at least Perl 5.20. While the term "Modern Perl" has traditionally referred to any version of Perl from 5.10.1, the language has improved dramatically over the past several years. Though Perl comes pre-installed on many operating systems, you may need to install a more modern version. Windows users, download Strawberry Perl from http://www.strawberryperl.com/ or ActivePerl from https://platform.activestate.com/featured-projects. Users of other operating systems with Perl already installed (and a C compiler and the other development tools), start by installing the CPAN module `App::perlbrew` http://search.cpan.org/perldoc?App::perlbrew. `perlbrew` manages multiple Perl installations, so that you can switch between versions for testing and deployment. You can also install CPAN modules in your home directory without affecting the system installation. If you've ever had to beg a system administrator for permission to install software, you'll appreciate this. ## Credits This book would not have been possible without questions, comments, suggestions, advice, wisdom, and encouragement from many, many people. In particular, the author thanks this edition's tech reviewers <NAME>, <NAME>, and <NAME> as well as <NAME>, editor of this edition. Contributors to this and previous editions include: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Felipe, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Michael Hicks, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, ww from PerlMonks, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, harleypig, hbm, and sunnavy. Any remaining errors are the fault of the stubborn author. Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. Perl gets things done—it's flexible, forgiving, and malleable. Capable programmers use it every day for everything from one-liners and one-off automations to multi-year, multi-programmer projects. Perl is pragmatic. You're in charge. You decide how to solve your problems and Perl will mold itself to do what you mean, with little frustration and no ceremony. Perl will grow with you. In the next hour, you'll learn enough to write real, useful programs—and you'll understand how the language works and why it works as it does. Modern Perl takes advantage of this knowledge and the combined experience of the global Perl community to help you write working, maintainable code. First, you need to know how to learn more. ## Perldoc Perl respects your time; Perl culture values documentation. The language ships with thousands of pages of core documentation. The `perldoc` utility is part of every complete Perl installation. Your OS may provide this as an additional package; install `perl-doc` on Debian or Ubuntu GNU/Linux, for example. `perldoc` can display the core docs as well as the documentation of every Perl module you have installed—whether a core module or one installed from the Comprehensive Perl Archive Network (CPAN). Use `perldoc` to read the documentation for a module or part of the core documentation: ``` $ perldoc List::Util $ perldoc perltoc $ perldoc Moose::Manual ``` The first example displays the documentation of the `List::Util` module; these docs are in the module itself. The second example is the table of contents of the core docs. This file is purely documentation. The third example requires you to install the `Moose` (Moose) CPAN distribution; it displays the pure-documentation manual. `perldoc` hides these all of these details for you; there's no distinction between reading the documentation for a core library such as `Data::Dumper` or one installed from the CPAN. Perl culture values documentation so much that even external libraries follow the good example of the core language documentation. The standard documentation template includes a description of the module, sample uses, and a detailed explanation of the module and its interface. While the amount of documentation varies by author, the form of the documentation is remarkably consistent. How to Read the Documentation Perl has lots of documentation. Where do you start? `perldoc perltoc` displays the table of contents of the core documentation, and `perldoc perlfaq` is the table of contents for Frequently Asked Questions about Perl. `perldoc perlop` and `perldoc perlsyn` document Perl's symbolic operators and syntactic constructs. `perldoc perldiag` explains the meanings of Perl's warning messages. `perldoc perlvar` lists all of Perl's symbolic variables. You don't have to memorize anything in these docs. Skim them for a great overview of the language and come back to them when you have questions. The `perldoc` utility can do much, much more (see `perldoc perldoc` ). Use the `-q` option with a keyword to search the Perl FAQ. For example, `perldoc -q sort` returns three questions: How do I sort an array by (anything)?, How do I sort a hash (optionally by value instead of key)?, and How can I always keep my hash sorted?. The `-f` option shows the documentation for a builtin Perl function, such as `perldoc -f sort` . If you don't know the name of the function you want, browse the list of available builtins in `perldoc perlfunc` . The `-v` option looks up a builtin variable. For example, `perldoc -v $PID` explains `$PID` , which is the variable containing the current program's process id. Depending on your shell, you may have to quote the variable appropriately. The `-l` option shows the path to the file containing the documentation. (A module may have a separate .pod file in addition to its .pm file.) The `-m` option displays the entire contents of the module, code and all, without any special formatting. Perl uses a documentation format called POD, short for Plain Old Documentation. `perldoc perlpod` describes how POD works. Other POD tools include `podchecker` , which validates the structure of POD documents, and the `Pod::Webserver` CPAN module, which displays local POD as HTML through a minimal web server. ## Expressivity Before <NAME> created Perl, he studied linguistics. Unlike other programming languages designed around a mathematical notion, Perl's design emulates how people communicate with people. This gives you the freedom to write programs depending on your current needs. You may write simple, straightforward code or combine many small pieces into larger programs. You may select from multiple design paradigms, and you may eschew or embrace advanced features. Learning Perl is like learning any spoken language. You'll learn a few words, then string together sentences, and then enjoy simple conversations. Mastery comes from practice of both reading and writing code. You don't have to understand every detail of Perl to be productive, but the principles in this chapter are essential to your growth as a programmer. Other languages may claim that there should be only one best way to solve any problem. Perl allows you to decide what's most readable, most useful, most appealing, or most fun. Perl hackers call this TIMTOWTDI, pronounced "<NAME>", or "There's more than one way to do it!" This expressivity allows master craftworkers to create amazing programs but also allows the unwary to make messes. You'll develop your own sense of good taste with experience. Express yourself, but be mindful of readability and maintainability, especially for those who come after you. Perl novices often find certain syntactic constructs opaque. These idioms (Idioms) offer great (if subtle) power to experienced programmers, but it's okay to avoid them until you're comfortable with them. As another design goal, Perl tries to avoid surprising experienced (Perl) programmers. For example, adding two variables ( ``` $first_num + $second_num ``` ) is obviously a numeric operation (Numeric Operators). You've expressed your intent to treat the values of those variables as numbers by using a numeric operator. Perl happily does so. No matter the contents of `$first_num` and `$second_num` , Perl will coerce them to numeric values (Numeric Coercion). Perl adepts often call this principle DWIM, or do what I mean. You could just as well call this the principle of least astonishment. Given a cursory understanding of Perl (especially context; Context), it should be possible to understand the intent of an unfamiliar Perl expression. You will develop this skill as you learn Perl. Perl's expressivity allows novices to write useful programs without having to understand the entire language. This is by design! Experienced developers often call the results baby Perl as a term of endearment. Everyone begins as a novice. Through practice and learning from more experienced programmers, you will understand and adopt more powerful idioms and techniques. It's okay for you to write simple code that you understand. Keep practicing and you'll become a native speaker. A novice Perl hacker might triple a list of numbers with: for (my $i = 0; $i < scalar @numbers; $i++) { $tripled[$i] = $numbers[$i] * 3; } ``` ... and a Perl adept might write: for my $num (@numbers) { push @tripled, $num * 3; } ``` ... while an experienced Perl hacker could write: ``` my @tripled = map { $_ * 3 } @numbers; ``` Every program gets the same result. Each uses Perl in a different way. As you get more comfortable with Perl, you can let the language do more for you. With experience, you can focus on what you want to do rather than how to do it. Perl doesn't care if you write baby or expert code. Design and refine your programs for clarity, expressivity, reuse, and maintainability, in part or in whole. Take advantage of this flexibility and pragmatism: it's far better to accomplish your task effectively now than to write a conceptually pure and beautiful program next year. ## Context In spoken languages, the meaning of a word or phrase depends on how you use it; the local context of other grammatical constructs helps clarify the intent. For example, the inappropriate pluralization of "Please give me one hamburgers!" sounds wrong (the pluralization of the noun differs from the amount), just as the incorrect gender of "la gato" (the article is feminine, but the noun is masculine) makes native speakers chuckle. Some words do double duty; one sheep is a sheep just as two sheep are also sheep and you program a program. Perl uses context to express how to treat a piece of data. This governs the amount of data as well as the kind of data. For example, several Perl operations produce different behaviors when you expect zero, one, or many results. A specific construct in Perl may do something different if you write "Do this, but I don't care about any results" compared to "Do this and give me multiple results." Other operations allow you to specify whether you expect to work with numeric, textual, or true or false data. You must keep context in mind when you read Perl code. Every expression is part of a larger context. You may find yourself slapping your forehead after a long debugging session when you discover that your assumptions about context were incorrect. If instead you're aware of context, your code will be more correct—and cleaner, flexible, and more concise. ### Void, Scalar, and List Context Amount context governs how many items you expect an operation to produce. Think of subject-verb number agreement in English. Even without knowing the formal description of this principle, you probably understand the error in the sentence "Perl are a fun language." (In terms of amount context, you could say that the verb "are" expects a plural noun or noun phrase.) In Perl, the number of items you request influences how many you receive. Suppose the function (Declaring Functions) called `find_chores()` sorts your household todo list in order of priority. The number of chores you expect to read from your list influences what the function produces. If you expect nothing, you're just pretending to be busy. If you expect one task, you have something to do for the next fifteen minutes. If you have a burst of energy on a free weekend, you could get all of your chores. Why does context matter? A context-aware function can examine its calling context and decide how much work it must do. When you call a function and never use its return value, you've used void context: `find_chores();` Assigning the function's return value to a single item (Scalars) enforces scalar context: ``` my $single_result = find_chores(); ``` Assigning the results of calling the function to an array (Arrays) or a list, or using it in a list, evaluates the function in list context: ``` my @all_results = find_chores(); my ($single_element, @rest) = find_chores(); # list of results passed to a function process_list_of_results( find_chores() ); ``` The parentheses in the second line of the previous example group the two variable declarations (Lexical Scope) into a single unit so that assignment assigns to both of the variables. A single-item list is still a list, though. You could also correctly write: ``` my ($single_element) = find_chores(); ``` .... in which case the parentheses tell Perl parser that you intend list context for the single variable `$single_element` . This is subtle, but now that you know about it, the difference of amount context between these two statements should be obvious: ``` my $scalar_context = find_chores(); my ($list_context) = find_chores(); ``` Lists propagate list context to the expressions they contain. This often confuses novices until they understand it. Both of these calls to `find_chores()` occur in list context: ``` process_list_of_results( find_chores() ); my %results = ( cheap_operation => $cheap_results, expensive_operation => find_chores(), # OOPS! ); ``` Yes, initializing a hash (Hashes) with a list of values imposes list context on `find_chores` . Use the `scalar` operator to impose scalar context: ``` my %results = ( cheap_operation => $cheap_results, expensive_operation => scalar find_chores(), ); ``` Again, context can help you determine how much work a function should do. In void context, `find_chores()` may legitimately do nothing. In scalar context, it can find only the most important task. In list context, it must sort and return the entire list. ### Numeric, String, and Boolean Context Perl's other context—value context—influences how Perl interprets a piece of data. Perl can figure out if you have a number or a string and convert data between the two types. In exchange for not having to declare explicitly what type of data a variable contains or a function produces, Perl's value contexts provide hints about how to treat that data. Perl will coerce values to specific proper types (Coercion) depending on the operators you use. For example, the `eq` operator tests that two values contain equivalent string values: ``` say "Catastrophic crypto fail!" if $alice eq $bob; ``` You may have had a baffling experience where you know that the strings are different, but they still compare the same: ``` my $alice = 'alice'; say "Catastrophic crypto fail!" if $alice == 'Bob'; ``` The `eq` operator treats its operands as strings by enforcing string context on them, but the `==` operator imposes numeric context. In numeric context, both strings evaluate to `0` (Numeric Coercion). Be sure to use the proper operator for your desired value context. Boolean context occurs when you use a value in a conditional statement. In the previous examples, `if` evaluated the results of the `eq` and `==` operators in boolean context. In rare circumstances, you may not be able to use the appropriate operator to enforce value context. To force a numeric context, add zero to a variable. To force a string context, concatenate a variable with the empty string. To force a boolean context, double up the negation operator: ``` my $numeric_x = 0 + $x; # forces numeric context my $stringy_x = '' . $x; # forces string context my $boolean_x = !!$x; # forces boolean context ``` Value contexts are easier to identify than amount contexts. Once you know which operators provide which contexts (Operator Types), you'll rarely make mistakes. ## Implicit Ideas Perl code can seem dense at first, but it's full of linguistic shortcuts. These allow experienced programmers to glance at code and understand its important implications. Context is one shortcut. Another is default variables—the programming equivalent of pronouns. ### The Default Scalar Variable The default scalar variable (or topic variable), `$_` , is most notable in its absence: many of Perl's builtin operations work on the contents of `$_` in the absence of an explicit variable. You can still type `$_` if it makes your code clearer to you, but it's often unnecessary. Many of Perl's scalar operators (including `chr` , `ord` , `lc` , `length` , `reverse` , and `uc` ) work on the default scalar variable if you do not provide an alternative. For example, the `chomp` builtin removes any trailing newline sequence (technically the contents of `$/` ; see `perldoc -f chomp` ) from its operand: ``` my $uncle = "Bob\n"; chomp $uncle; say "'$uncle'"; ``` `$_` behaves the same way in Perl as the pronoun it does in English. Without an explicit variable, `chomp` removes the trailing newline sequence from `$_` . When you write " `chomp;` ", Perl will always chomp it. These two lines of code are equivalent: ``` chomp $_; chomp; ``` `say` and `$_` in the absence of other arguments: ``` print; # prints $_ to the current filehandle say; # prints $_ and a newline to the current filehandle ``` Perl's regular expression facilities (Regular Expressions and Matching) default to `$_` to match, substitute, and transliterate: ``` $_ = 'My name is Paquito'; say if /My name is/; s/Paquito/Paquita/; tr/A-Z/a-z/; say; ``` Perl's looping directives (Looping Directives) default to using `$_` as the iteration variable, whether `for` iterating over a list: ``` say "#$_" for 1 .. 10; for (1 .. 10) { say "#$_"; } ``` ... or `while` waiting for an expression to evaluate to false: ``` while (<STDIN>) { chomp; say scalar reverse; } ``` ... or `map` transforming a list: ``` my @squares = map { $_ * $_ } 1 .. 10; say for @squares; # note the postfix for ``` ... or `grep` filtering a list: ``` say 'Brunch is possible!' if grep { /pancake mix/ } @pantry; ``` Just as English gets confusing when you have too many pronouns and antecedents, so does Perl when you mix explicit and implicit uses of `$_` . In general, there's only one `$_` . If you use it in multiple places, one operator's `$_` may override another's. For example, if one function uses `$_` and you call it from another function which uses `$_` , the callee may clobber the caller's value: ``` while (<STDIN>) { chomp; # BAD EXAMPLE my $munged = calculate_value( $_ ); say "Original: $_"; say "Munged : $munged"; } ``` If `calculate_value()` or any other function changed `$_` , that change would persist through that iteration of the loop. Using a named lexical is safer and may be clearer: ``` while (my $line = <STDIN>) { ... } ``` Use `$_` as you would the word "it" in formal writing: sparingly, in small and well-defined scopes. The `...` Operator The triple-dot ( `...` ) operator is a placeholder for code you intend to fill in later. Perl will parse it as a complete statement, but will throw an exception that you're trying to run unimplemented code if you try to run it. See `perldoc perlop` for more details. ### The Default Array Variables Perl also provides two implicit array variables. Perl passes arguments to functions (Declaring Functions) in an array named `@_` . Array operations (Arrays) inside functions use this array by default. These two snippets of code are equivalent: ``` sub foo { my $arg = shift; ... } sub foo_explicit_args { my $arg = shift @_; ... } ``` Just as `$_` corresponds to the pronoun it, `@_` corresponds to the pronouns they and them. Unlike `$_` , each function has a separate copy of `@_` . The builtins `shift` and `pop` operate on `@_` , if provided no explicit operands. Outside of all functions, the default array variable `@ARGV` contains the command-line arguments provided to the program. Perl's array operations (including `shift` and `pop` ) operate on `@ARGV` implicitly outside of functions. You cannot use `@_` when you mean `@ARGV` . `readline` Perl's `<$fh>` operator is the same as the `readline` builtin. `readline $fh` does the same thing as `<$fh>` . A bare `readline` behaves just like `<>` . For historic reasons, `<>` is still more common, but consider using `readline` as a more readable alternative. (What's more readable, `glob '*.html'` to `<*.html>` ? The same idea applies.) `ARGV` has one special case. If you read from the null filehandle `<>` , Perl will treat every element in `@ARGV` as the name of a file to open for reading. (If `@ARGV` is empty, Perl will read from standard input; see Input and Output.) This implicit `@ARGV` behavior is useful for writing short programs, such as a command-line filter which reverses its input: ``` while (<>) { chomp; say scalar reverse; } ``` The Double Open Operator Perl 5.22 made this expression a little safer with the `<<>>` operator. If a filename provided contains a special punctuation symbol like `|filename` or `filename|` , Perl would do something special with it. The double-diamond operator avoids this behavior. Why `scalar` ? `say` imposes list context on its operands. `reverse` passes its context on to its operands, treating them as a list in list context and a concatenated string in scalar context. If the behavior of `reverse` sounds confusing, your instincts are correct. Perl arguably should have separated "reverse a string" from "reverse a list". If you run it with a list of files: ``` $ perl reverse_lines.pl encrypted/*.txt ``` ... the result will be one long stream of output. Without any arguments, you can provide your own standard input by piping in from another program or typing directly. That's a lot of flexibility in a small program—and you're only getting started. Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. Perl's greatest accomplishment is the huge amount of reusable libraries it has available. Larry Wall explicitly encouraged the Perl community to create and maintain their own extensions to solve every problem imaginable without fragmenting the language into incompatible pidgins. It worked. That technical accomplishment was almost as important as the growth of a community around Perl. People write libraries. People build on the work of other people. People make a community worth joining and preserving and expanding. The Perl community welcomes willing participants at all levels, from novices to the developers of Perl itself. Take advantage of the knowledge and experience and code of countless other programmers, and you'll become a better programmer. ## The CPAN Perl is a pragmatic language. If you have a problem, chances are the global Perl community has already written—and shared—code to solve it. Modern Perl programming relies on the CPAN (http://www.cpan.org/). The Comprehensive Perl Archive Network is an uploading and mirroring system for redistributable, reusable Perl code. It's one of the largest libraries of code in the world. You can find everything from database access to profiling tools to protocols for almost every network device ever created to sound and graphics libraries and wrappers for shared libraries on your system. Modern Perl without the CPAN is just another language. Modern Perl with the CPAN is a powerful toolkit for solving problems. CPAN hosts distributions, or collections of reusable Perl code. A single distribution can contain one or more modules: self-contained libraries of Perl code. Each distribution occupies its own CPAN namespace and provides unique metadata. The CPAN is Big, Really Big The CPAN adds hundreds of registered contributors and thousands of indexed modules in hundreds of distributions every month. Those numbers do not take into account updates. In May 2015, search.cpan.org reported 12207 uploaders, 150552 modules, and 31873 distributions (representing growth rates of 10.8%, 16.7%, and 9.6% since the previous edition of this book, respectively). The CPAN itself is merely a mirroring service. Authors upload distributions to a central service (PAUSE) which replicates them to mirror sites from which CPAN clients download them. All of this relies on common behavior; community standards have evolved to identify the attributes and characteristics of well-formed CPAN distributions. These include: * the behavior of automated CPAN installers * metadata to describe what each distribution provides and expects * machine-readable documentation and licensing Additional CPAN services provide comprehensive automated testing and reporting across platforms and Perl versions. Every CPAN distribution has its own ticket queue on http://rt.cpan.org/ for reporting bugs and working with authors. CPAN sites also link to previous distribution versions, module ratings, documentation annotations, and more. All of this is available from both http://search.cpan.org/ and http://metacpan.org/. Modern Perl installations include a client to connect to, search, download, build, test, and install CPAN distributions; this is CPAN.pm. With a recent version (as of this writing, 2.10 is the latest stable release), module installation is reasonably easy. Start the client with: `$ cpan` To install a distribution within the client: ``` $ cpan cpan[1]> install Modern::Perl ``` ... or to install directly from the command line: `$ cpan Modern::Perl` <NAME>'s tutorial on configuring CPAN.pm http://learnperl.scratchcomputing.com/tutorials/configuration/ includes a great troubleshooting section. ### CPAN Management Tools If your operating system provides its own Perl installation, it may be out of date or depend on specific versions of CPAN distributions. Serious Perl developers often construct virtual walls between the system Perl and their development Perl installations. Several projects help to make this possible. The `App::cpanminus` CPAN client is fast and simple and needs no configuration. Install it with `cpan App::cpanminus` , or: ``` $ curl -LO http://xrl.us/cpanm $ less cpanm # review the code before running $ chmod +x cpanm $ ./cpanm ``` `App::perlbrew` is a system to manage and to switch between your own installations of multiple versions and configurations of Perl. Installation is as easy as: ``` $ curl -LO http://xrl.us/perlbrew $ less perlbrew # review the code before running $ chmod +x perlbrew $ ./perlbrew install $ perldoc App::perlbrew ``` The `local::lib` CPAN distribution allows you to install and to manage multiple Perl installations. This is an effective way to maintain CPAN distributions for individual users or applications without affecting the system as a whole. See https://metacpan.org/pod/local::lib and https://metacpan.org/pod/App::local::lib::helper for more details. All three projects tend to assume a Unix-like environment. Windows users, see the Padre all-in-one download (http://padre.perlide.org/download.html). ## Community Sites Perl's homepage at http://www.perl.org/ links to documentation, source code, tutorials, mailing lists, and several important community projects, such as the Perl.org Online library (https://www.perl.org/books/library.html). If you're new to Perl, the Perl beginners mailing list is a friendly place to ask novice questions and get accurate and helpful answers. See http://learn.perl.org/faq/beginners.html. The home of Perl development is http://dev.perl.org/, which links to relevant resources for Perl's core development. The CPAN's (The CPAN) central location is http://www.cpan.org/, though experienced users spend more time on http://search.cpan.org/ and https://metacpan.org/. Get used to browsing here for freely available libraries. Several community sites offer news and commentary. http://blogs.perl.org/ is a free blog platform open to any Perl community member. Other sites aggregate the musings of Perl hackers, including http://perlsphere.net/, http://PerlTricks.com/, and http://ironman.enlightenedperl.org/. The latter is part of an initiative from the Enlightened Perl Organization (http://enlightenedperl.org/) to increase the amount and improve the quality of Perl publishing on the web. Perl Weekly (http://perlweekly.com/) offers a weekly take on news from the Perl world. @perlbuzz (https://twitter.com/perlbuzz) regularly tweets new Perl links. ## Development Sites Best Practical Solutions (http://bestpractical.com/) maintains an installation of RT, its popular request-tracking system, for Perl development. Perl's queue is http://rt.perl.org/. Every CPAN distribution has its own queue on http://rt.cpan.org/. The Perl 5 Porters (or p5p) mailing list is the focal point of the development of Perl. See http://lists.cpan.org/showlist.cgi?name=perl5-porters. The Perl Foundation (http://www.perlfoundation.org/) exists to support the development and promotion of Perl and its community. Many Perl hackers use Github http://github.com/ to host their projects, including the sources of this book http://github.com/chromatic/modern_perl_book/. See especially Gitpan http://github.com/gitpan/, which hosts Git repositories chronicling the complete history of every distribution on the CPAN. A Local Git Mirror GitPAN receives infrequent updates. As an alternative to hacking CPAN distributions from GitPAN, consider using Yanick Champoux's wonderful `Git::CPAN::Patch` module to create local Git repositories from CPAN distributions. ## Events The Perl community holds countless conferences, workshops, seminars, and meetings. In particular, the community-run YAPC—Yet Another Perl Conference—is a successful, local, low-cost conference model held on multiple continents. See http://yapc.org/. Hundreds of local Perl Mongers groups get together frequently for technical talks and social interaction. See http://www.pm.org/. ## IRC When Perl mongers can't meet in person, many collaborate and chat online through the textual chat system known as IRC. The main server for Perl community is `irc://irc.perl.org/` . Be aware that the channel #perl is a general purpose channel for discussing whatever its participants want to discuss. Direct questions to #perl-help instead. Many of the most popular and useful Perl projects have their own IRC channels, such as #moose and #catalyst; you can find mention of these channels in project documentation. Date: 2020-12-10 Categories: Tags: Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. The Perl language is a combination of several individual pieces. Although spoken languages use nuance and tone of voice and intuition to communicate across gaps in knowledge and understanding, computers and source code require precision. You can write effective Perl code without knowing every detail of every language feature, but you must understand how they work together to write Perl code well. ## Names Names (or identifiers) are everywhere in Perl programs: you choose them for variables, functions, packages, classes, and even filehandles. Valid Perl names all begin with a letter or an underscore and may optionally include any combination of letters, numbers, and underscores. When the `utf8` pragma (Unicode and Strings) is in effect, you may use any UTF-8 word characters in identifiers. These are valid Perl identifiers: ``` my $name; my @_private_names; my %Names_to_Addresses; sub anAwkwardName3; # with use utf8; enabled package Ingy::Döt::Net; ``` These are invalid Perl identifiers: ``` my $invalid name; # space is invalid my @3; # cannot start with number my %~flags; # symbols invalid in name package a-lisp-style-name; ``` Names exist primarily for your benefit as a programmer. These rules apply only to literal names which appear in your source code, such as `sub fetch_pie` or `my $waffleiron` . Only Perl's parser enforces the rules about identifier names. You may also refer to entities with names generated at runtime or provided as input to a program. These symbolic lookups provide flexibility at the expense of safety. Invoking functions or methods indirectly or looking up symbols in a namespace lets you bypass Perl's parser. Symbolic lookups can produce confusing code. As <NAME> recommends http://perl.plover.com/varvarname.html, prefer a hash (Hashes) or nested data structure (Nested Data Structures) over variables named, for example, `$recipe1` , `$recipe2` , and so on. ### Variable Names and Sigils Variable names always have a leading sigil (a symbol) which indicates the type of the variable's value. Scalar variables (Scalars) use the dollar sign ( `$` ). Array variables (Arrays) use the at sign ( `@` ). Hash variables (Hashes) use the percent sign ( `%` ): ``` my $scalar; my @array; my %hash; ``` Sigils separate variables into different namespaces. It's possible—though confusing—to declare multiple variables of the same name with different types: ``` my ($bad_name, @bad_name, %bad_name); ``` Perl won't get confused, though humans will. The sigil of a variable changes depending on its use; this change is called variant sigils. As context determines how many items you expect from an operation or what type of data you expect to get, so the sigil governs how you manipulate the data of a variable. For example, use the scalar sigil ( `$` ) to access a single element of an array or a hash: ``` my $hash_element = $hash{ $key }; my $array_element = $array[ $index ] $hash{ $key } = 'value'; $array[ $index ] = 'item'; ``` The parallel with amount context is important. Using a scalar element of an aggregate as an lvalue (the target of an assignment; on the left side of the `=` character) imposes scalar context (Context) on the rvalue (the value assigned; on the right side of the `=` character). Similarly, accessing multiple elements of a hash or an array—an operation known as slicing—uses the at symbol ( `@` ) and imposes list context—even if the list itself has zero or one elements: ``` my @hash_elements = @hash{ @keys }; my @array_elements = @array[ @indexes ]; my %hash; @hash{ @keys } = @values; ``` Given Perl's variant sigils, the most reliable way to determine the type of a variable—scalar, array, or hash—is to observe the operations performed on it. Arrays support indexed access through square brackets. Hashes support keyed access through curly brackets. Scalars have neither. ### Namespaces Perl allows you to collect similar functions and variables into their own unique named spaces—namespaces (Packages). A namespace is a collection of symbols grouped under a globally unique name. Perl allows multi-level namespaces, with names joined by double colons ( `::` ). refers to a logical collection of related variables and functions, such as `scoop()` and `pour_hot_fudge()` . Within a namespace, you may use the short name of its members. Outside of the namespace, you must refer to a member by its fully-qualified name. Within , `add_sprinkles()` refers to the same function as does ``` DessertShop::IceCream::add_sprinkles() ``` outside of the namespace. Standard identifier rules apply to package names. By convention, the Perl core reserves lowercase package names for core pragmas (Pragmas), such as `strict` and `warnings` . User-defined packages all start with uppercase letters. This is a policy enforced primarily by community guidelines. All namespaces in Perl are globally visible. When Perl looks up a symbol in ``` DessertShop::IceCream::Freezer ``` , it looks in the `main::` symbol table for a symbol representing the `DessertShop::` namespace, in that namespace for the `IceCream::` namespace, and so on. Yet `Freezer::` is visible from outside of the `IceCream::` namespace. The nesting of the former within the latter is only a storage mechanism; it implies nothing about relationships between parent and child or sibling packages. Only you as a programmer can make logical relationships between entities obvious—by choosing good names and organizing them well. ## Variables A variable in Perl is a storage location for a value (Values). While a trivial program may manipulate values directly, most programs work with variables. Think of this like algebra: you manipulate symbols to describe formulas. It's easier to explain the Pythagorean theorem in terms of the variables `a` , `b` , and `c` than by intuiting its principle by producing a long list of valid values. ### Variable Scopes Your ability to access a variable within your program depends on the variable's scope (Scope). Most variables in modern Perl programs have a lexical scope (Lexical Scope) governed by the syntax of the program as written. Most lexical scopes are either the contents of blocks delimited by curly braces ( `{` and `}` ) or entire files. Files themselves provide their own lexical scopes, such that a `package` declaration on its own does not create a new scope: ``` package Store::Toy; my $discount = 0.10; package Store::Music; # $discount still visible say "Our current discount is $discount!"; ``` You may also provide a block to the `package` declaration. Because this introduces a new block, it also provides a new lexical scope: ``` package Store::Toy { my $discount = 0.10; } package Store::Music { # $discount not visible } package Store::BoardGame; # $discount still not visible ``` ### Variable Sigils The sigil of the variable in a declaration determines the type of the variable: scalar, array, or hash. The sigil used when accessing a variable varies depending on what you do to the variable. For example, you declare an array as `@values` . Access the first element—a single value—of the array with `$values[0]` . Access a list of values from the array with `@values[ @indices ]` . The sigil you use determines amount context in an lvalue situation: ``` # imposes lvalue context on some_function() @values[ @indexes ] = some_function(); ``` ... or gets coerced in an rvalue situation: ``` # list evaluated to final element in scalar context my $element = @values[ @indices ]; ``` ### Anonymous Variables Perl variables do not require names. Names exist to help you, the programmer, keep track of an `$apple` , `@barrels` , or `%cookie_recipes` . Variables created without literal names in your source code are anonymous. The only way to access anonymous variables is by reference (References). ### Variables, Types, and Coercion This relationship between variable types, sigils, and context is essential to your understanding of Perl. A Perl variable represents both a value (a dollar cost, available pizza toppings, the names and numbers of guitar stores) and the container which stores that value. Perl's type system deals with value types and container types. While a variable's container type—scalar, array, or hash—cannot change, Perl is flexible about a variable's value type. You may store a string in a variable in one line, append to that variable a number on the next, and reassign a reference to a function (Function References) on the third, though this is a great way to confuse yourself. Performing an operation on a variable which imposes a specific value type may cause coercion (Coercion) of the variable's existing value type. For example, the documented way to determine the number of entries in an array is to evaluate that array in scalar context (Context). Because a scalar variable can only ever contain a scalar, assigning an array (the rvalue) to a scalar (the lvalue) imposes scalar context on the operation, and an array evaluated in scalar context produces the number of elements in the array: `my $count = @items;` ## Values New programmers spend a lot of time thinking about what their programs must do. Mature programmers spend their time designing a model for the data their programs must understand. Variables allow you to manipulate data in the abstract. The values held in variables make programs concrete and useful. These values are your aunt's name and address, the distance between your office and a golf course on the moon, or the sum of the masses of all of the cookies you've eaten in the past year. Within your program, the rules regarding the format of that data are often strict. Effective programs need effective (simple, fast, efficient, easy) ways to represent their data. ### Strings A string is a piece of textual or binary data with no particular formatting or contents. It could be your name, an image read from disk, or the source code of the program itself. A string has meaning in the program only when you give it meaning. A literal string appears in your program surrounded by a pair of quoting characters. The most common string delimiters are single and double quotes: ``` my $name = '<NAME>, <NAME>'; my $address = "Room 539, Bilskirnir, Valhalla"; ``` Characters in a single-quoted string are exactly and only ever what they appear to be, with two exceptions. To include a single quote inside a single-quoted string, you must escape it with a leading backslash: ``` my $reminder = 'Don\'t forget to escape ' . 'the single quote!'; ``` To include a backslash at the end of a string, escape it with another leading backslash. Otherwise Perl will think you're trying to escape the closing delimiter: ``` my $exception = 'This string ends with a ' . 'backslash, not a quote: \\'; ``` Any other backslash will be part of the string as it appears, unless you have two adjacent backslashes, in which case Perl will believe that you intended to escape the second: is 'Modern \ Perl', 'Modern \\ Perl', 'single quotes backslash escaping'; Testing Examples This example uses `Test::More` to prove the assertion that Perl considers these two lines equivalent. See Testing for details on how that works. A double-quoted string gives you more options, such as encoding otherwise invisible whitespace characters in the string: ``` my $tab = "\t"; my $newline = "\n"; my $carriage = "\r"; my $formfeed = "\f"; my $backspace = "\b"; ``` You may have inferred from this that you can represent the same logical string in multiple ways. You can include a tab within a string by typing the `\t` escape sequence or by hitting the Tab key on your keyboard. Both strings look and behave the same to Perl, even though the representation of the string may differ in the source code. A string declaration may cross (and include) newlines, so these two declarations are equivalent: ``` my $escaped = "two\nlines"; my $literal = "two lines"; is $escaped, $literal, 'equivalent \n and newline'; ``` ... but the escape sequences are easier for humans to read. Perl strings have variable—not fixed—lengths. Perl will change their sizes for you as you modify and manipulate them. Use the concatenation operator `.` to combine multiple strings together: ``` my $kitten = 'Choco' . ' ' . 'Spidermonkey'; ``` ... though concatenating three literal strings like this is ultimate the same to Perl as writing a single string. When you interpolate the value of a scalar variable or the values of an array within a double-quoted string, the current contents of the variable become part of the string as if you'd concatenated them: ``` my $factoid = "$name lives at $address!"; # equivalent to my $factoid = $name . ' lives at ' . $address . '!'; ``` Include a literal double-quote inside a double-quoted string by escaping it with a leading backslash: ``` my $quote = "\"Ouch,\", he cried. \"That hurt!\""; ``` Repeated backslashing sometimes becomes unwieldy. A quoting operator allows you to choose an alternate string delimiter. The `q` operator indicates single quoting (no interpolation), while the ``` my $quote = qq{"Ouch", he said. "That hurt!"}; my $reminder = q^Don't escape the single quote!^; my $complaint = q{It's too early to be awake.}; ``` Use the heredoc syntax to assign multiple lines to a string: ``` my $blurb =<<'END_BLURB'; He looked up. "Change is the constant on which they all can agree. We instead, born out of time, remain perfect and perfectly self-aware. We only suffer change as we pursue it. It is against our nature. We rebel against that change. Shall we consider them greater for it?" END_BLURB ``` This syntax has three parts. The double angle-brackets introduce the heredoc. The quotes determine whether the heredoc follows single- or double-quoted behavior; double-quoted behavior is the default. `END_BLURB` is an arbitrary identifier, chosen by the programmer, used as the ending delimiter. Regardless of the indentation of the heredoc declaration itself, the ending delimiter must start at the beginning of the line: ``` sub some_function { my $ingredients =<<'END_INGREDIENTS'; Two eggs One cup flour Two ounces butter One-quarter teaspoon salt One cup milk One drop vanilla Season to taste END_INGREDIENTS } ``` Using a string in a non-string context will induce coercion (Coercion). ### Unicode and Strings Unicode is a system used to represent the characters of the world's written languages. Most English text uses a character set of only 127 characters (which requires seven bits of storage and fits nicely into eight-bit bytes), but it's naïve to believe that you won't someday need an umlaut. Perl strings can represent either of two separate but related data types: * Sequences of Unicode characters Each character has a codepoint, a unique number which identifies it in the Unicode character set. * Sequences of octets Binary data in a sequence of octets—8 bit numbers, each of which can represent a number between 0 and 255. Words Matter Why octet and not byte? An octet is unambiguously eight bits. A byte can be fewer or more bits, depending on esoteric hardware. Assuming that one character fits in one byte will cause you no end of Unicode grief. Separate the idea of memory storage from character representation. Forget that you ever heard of bytes. Unicode strings and binary strings look superficially similar. Each has a `length()` . Each supports standard string operations such as concatenation, splicing, and regular expression processing (Regular Expressions and Matching). Any string which is not purely binary data is textual data, and thus should be a sequence of Unicode characters. However, because of how your operating system represents data on disk or from users or over the network—as sequences of octets—Perl can't know if the data you read is an image file or a text document or anything else. By default, Perl treats all incoming data as sequences of octets. It's up to you to give that data meaning. # Character Encodings A Unicode string is a sequence of octets which represents a sequence of characters. A Unicode encoding maps octet sequences to characters. Some encodings, such as UTF-8, can encode all of the characters in the Unicode character set. Other encodings represent only a subset of Unicode characters. For example, ASCII encodes plain English text (no accented characters allowed), while Latin-1 can represent text in most languages which use the Latin alphabet (umlauts, grave and circumflex accents, et cetera). An Evolving Standard Perl 5.16 supports the Unicode 6.1 standard, 5.18 the 6.2 standard, 5.20 the 6.3 standard, and 5.22 the 7.0 standard. See http://unicode.org/versions/. To avoid most Unicode problems, always decode to and from the appropriate encoding at the inputs and outputs of your program. Read that sentence again. Memorize it. You'll be glad of it later. # Unicode in Your Filehandles When you tell Perl that a specific filehandle (Files) should interpret data via specific Unicode encoding, Perl will use an IO layer to convert between octets and characters. The mode operand of the `open` builtin allows you to request an IO layer by name. For example, the `:utf8` layer decodes UTF-8 data: ``` open my $fh, '<:utf8', $textfile; my $unicode_string = <$fh>; ``` Use `binmode` to apply an IO layer to an existing filehandle: ``` binmode $fh, ':utf8'; my $unicode_string = <$fh>; binmode STDOUT, ':utf8'; say $unicode_string; ``` If you want to write Unicode to files, you must specify the desired encoding. Otherwise, Perl will warn you when you print Unicode characters that don't look like octets; this is what `Wide character in %s` means. Enable UTF-8 Everywhere Use the `utf8::all` module to add the UTF-8 IO layer to all filehandles throughout your program. The module also enables all sorts of other Unicode features. It's very handy, but it's a blunt instrument and no substitute for understanding what your program needs to do. # Unicode in Your Data The core module `Encode` 's `decode()` function converts a sequence of octets to Perl's internal Unicode representation. The corresponding `encode()` function converts from Perl's internal encoding to the desired encoding: ``` my $from_utf8 = decode('utf8', $data); my $to_latin1 = encode('iso-8859-1', $string); ``` To handle Unicode properly, you must always decode incoming data via a known encoding and encode outgoing data to a known encoding. Again, you must know what kind of data you expect to consume and to produce. Being specific will help you avoid all kinds of trouble. # Unicode in Your Programs The easiest way to use Unicode characters in your source code us with the `utf8` pragma (Pragmas), which tells the Perl parser to decode the rest of the file as UTF-8 characters. This allows you to use Unicode characters in strings and identifiers: ``` use utf8; sub £_to_¥ { ... } my $yen = £_to_¥('1000£'); ``` To write this code, your text editor must understand UTF-8 and you must save the file with the appropriate encoding. Again, any two programs which communicate with Unicode data must agree on the encoding of that data. Within double-quoted strings, you may also use a Unicode escape sequence to represent character encodings. The syntax `\x{}` represents a single character; place the hex form of the character's Unicode number http://unicode.org/charts/ within the curly brackets: ``` my $escaped_thorn = "\x{00FE}"; ``` Some Unicode characters have names, which make them easier for other programmers to read. Use the `charnames` pragma to enable named characters via the `\N{}` escape syntax: ``` use charnames ':full'; use Test::More tests => 1; my $escaped_thorn = "\x{00FE}"; my $named_thorn = "\N{LATIN SMALL LETTER THORN}"; is $escaped_thorn, $named_thorn, 'Thorn equivalence check'; ``` You may use the `\x{}` and `\N{}` forms within regular expressions as well as anywhere else you may legitimately use a string or a character. # Implicit Conversion Most Unicode problems in Perl arise from the fact that a string could be either a sequence of octets or a sequence of characters. Perl allows you to combine these types through the use of implicit conversions. When these conversions are wrong, they're rarely obviously wrong but they're also often spectacularly wrong in ways that are difficult to debug. When Perl concatenates a sequence of octets with a sequence of Unicode characters, it implicitly decodes the octet sequence using the Latin-1 encoding. The resulting string will contain Unicode characters. When you print Unicode characters, Perl will encode the string using UTF-8, because Latin-1 cannot represent the entire set of Unicode characters—because Latin-1 is a subset of UTF-8. The asymmetry between encodings and octets can lead to Unicode strings encoded as UTF-8 for output and decoded as Latin-1 from input. Worse yet, when the text contains only English characters with no accents, the bug stays hidden, because both encodings use the same representation for every character. You don't have to understand all of this right now; just know that this behavior happens and that it's not what you want. ``` my $hello = "Hello, "; my $greeting = $hello . $name; ``` If `$name` contains Alice, you will never notice any problem: because the Latin-1 representation is the same as the UTF-8 representation. If `$name` contains José, `$name` can contain several possible values: * `$name` contains four Unicode characters. * `$name` contains four Latin-1 octets representing four Unicode characters. * `$name` contains five UTF-8 octets representing four Unicode characters. The string literal has several possible scenarios: * It is an ASCII string literal and contains octets: ``` my $hello = "Hello, "; ``` * It is a Latin-1 string literal with no explicit encoding and contains octets: ``` my $hello = "¡Hola, "; ``` * It is a non-ASCII string literal (the `utf8` or `encoding` pragma is in effect) and contains Unicode characters: ``` my $hello = "Kuirabá, "; ``` If both `$hello` and `$name` are Unicode strings, the concatenation will produce another Unicode string. If both strings are octet sequences, Perl will concatenate them into a new octet sequence. If both values are octets of the same encoding—both Latin-1, for example, the concatenation will work correctly. If the octets do not share an encoding—for example, a concatenation appending UTF-8 data to Latin-1 data—then the resulting sequence of octets makes sense in neither encoding. This could happen if the user entered a name as UTF-8 data and the greeting were a Latin-1 string literal, but the program decoded neither. If only one of the values is a Unicode string, Perl will decode the other as Latin-1 data. If this is not the correct encoding, the resulting Unicode characters will be wrong. For example, if the user input were UTF-8 data and the string literal were a Unicode string, the name would be incorrectly decoded into five Unicode characters to form José (sic) instead of José because the UTF-8 data means something else when decoded as Latin-1 data. Again, you don't have to follow all of the details here if you remember this: always decode on input and encode on output. See `perldoc perluniintro` for a far more detailed explanation of Unicode, encodings, and how to manage incoming and outgoing data in a Unicode world. For far more detail about managing Unicode effectively throughout your programs, see Tom Christiansen's answer to "Why does Modern Perl avoid UTF-8 by default?" http://stackoverflow.com/questions/6162484/why-does-modern-perl-avoid-utf-8-by-default/6163129#6163129 and his "Perl Unicode Cookbook" series http://www.perl.com/pub/2012/04/perlunicook-standard-preamble.html. ### Numbers Perl supports numbers as both integers and floating-point values. You may represent them with scientific notation as well as in binary, octal, and hexadecimal forms: ``` my $integer = 42; my $float = 0.007; my $sci_float = 1.02e14; my $binary = 0b101010; my $octal = 052; my $hex = 0x20; # only in Perl 5.22 my $hex_float = 0x1.0p-3; ``` The numeric prefixes `0b` , `0` , and `0x` specify binary, octal, and hex notation respectively. Be aware that a leading zero on an integer always indicates octal mode. When 1.99 + 1.99 is 4 Even though you can write floating-point values explicitly with perfect accuracy, Perl—like most programming languages—represents them internally in a binary format. This representation is sometimes imprecise in specific ways; consult `perldoc perlnumber` for more details. Perl 5.22 allows you to use a hexadecimal representation of floating point values, so as to keep maximum precision. See "Scalar value constructors" in `perldoc perldata` for more information. You may not use commas to separate thousands in numeric literals, as the parser will interpret them as the comma operator. Instead, use underscores. These three examples are equivalent, though the second might be the most readable: ``` my $billion = 1000000000; my $billion = 1_000_000_000; my $billion = 10_0_00_00_0_0_0; ``` Because of coercion (Coercion), Perl programmers rarely have to worry about converting incoming data to numbers. Perl will treat anything which looks like a number as a number when evaluated in a numeric context. In the rare circumstances where you need to know if something looks like a number without evaluating it in a numeric context, use the `looks_like_number` function from the core module `Scalar::Util` . This function returns a true value if Perl will consider the given argument numeric. The `Regexp::Common` module from the CPAN provides several well-tested regular expressions to identify more specific types of numeric values such as whole numbers, integers, and floating-point values. Numeric Size Limits What's the maximum size of a value you can represent in Perl? It depends; you're probably using a 64-bit build, so the largest integer is `(2**31) - 1` and the smallest is `-(2**31)` —though see `perldoc perlnumber` for more thorough details. Use `Math::BigInt` and `Math::BigFloat` to handle with larger or smaller or more precise numbers. ### Undef Perl's `undef` value represents an unassigned, undefined, and unknown value. Declared but undefined scalar variables contain `undef` : ``` my $name = undef; # unnecessary assignment my $rank; # also contains undef ``` `undef` evaluates to false in boolean a context. Evaluating `undef` in a string context—such as interpolating it into a string: ``` my $undefined; my $defined = $undefined . '... and so forth'; ``` ... produces an `uninitialized value` warning: ``` Use of uninitialized value $undefined in concatenation (.) or string... ``` The `defined` builtin returns a true value if its operand evaluates to a defined value (anything other than `undef` ): ``` my $status = 'suffering from a cold'; say defined $status; # 1, which is a true value say defined undef; # empty string; a false value ``` ### The Empty List When used on the right-hand side of an assignment, the `()` construct represents an empty list. In scalar context, this evaluates to `undef` . In list context, it is an empty list. When used on the left-hand side of an assignment, the `()` construct imposes list context. Hence this idiom (Idioms) to count the number of elements returned from an expression in list context without using a temporary variable: ``` my $count = () = get_clown_hats(); ``` Because of the right associativity (Associativity) of the assignment operator, Perl first evaluates the second assignment by calling `get_clown_hats()` in list context. This produces a list. Assignment to the empty list throws away all of the values of the list, but that assignment takes place in scalar context, which evaluates to the number of items on the right hand side of the assignment. As a result, `$count` contains the number of elements in the list returned from `get_clown_hats()` . This idiom often confuses new programmers, but with practice, you'll understand how Perl's fundamental design features fit together. ### Lists A list is a comma-separated group of one or more expressions. Lists may occur verbatim in source code as values: ``` my @first_fibs = (1, 1, 2, 3, 5, 8, 13, 21); ``` ... as targets of assignments: ``` my ($package, $filename, $line) = caller(); ``` ... or as lists of expressions: ``` say name(), ' => ', age(); ``` Parentheses do not create lists. The comma operator creates lists. The parentheses in these examples merely group expressions to change their precedence (Precedence). As an example of lists without parens, use the range operator to create lists of literals in a compact form: ``` my @chars = 'a' .. 'z'; my @count = 13 .. 27; ``` Use the `qw()` operator to split a literal string on whitespace to produce a list of strings. As this is a quoting operator, you may choose any delimiters you like: ``` my @stooges = qw! <NAME> Shemp <NAME> !; ``` No Comment Please Perl will emit a warning if a `qw()` contains a comma or the comment character ( `#` ), because not only are such characters rare in a `qw()` , their presence is often a mistake. Lists can (and often do) occur as the results of expressions, but these lists do not appear literally in source code. Lists and arrays are not interchangeable in Perl. Lists are values. Arrays are containers. You may store a list in an array and you may coerce an array to a list, but they are separate entities. For example, indexing into a list always occurs in list context. Indexing into an array can occur in scalar context (for a single element) or list context (for a slice): ``` # don't worry about the details right now sub context { my $context = wantarray(); say defined $context ? $context ? 'list' : 'scalar' : 'void'; return 0; } my @list_slice = (1, 2, 3)[context()]; my @array_slice = @list_slice[context()]; my $array_index = $array_slice[context()]; say context(); # list context context(); # void context ``` ## Control Flow Perl's basic control flow is straightforward. Program execution starts at the beginning (the first line of the file executed) and continues to the end: ``` say 'At start'; say 'In middle'; say 'At end'; ``` Perl's control flow directives change the order of what happens next in the program. ### Branching Directives The `if` directive performs the associated action only when its conditional expression evaluates to a true value: ``` say 'Hello, Bob!' if $name eq 'Bob'; ``` This postfix form is useful for simple expressions. Its block form groups multiple expressions into a unit which evaluates to a single boolean value: ``` if ($name eq 'Bob') { say 'Hello, Bob!'; found_bob(); } ``` The conditional expression may consist of multiple subexpressions which will be coerced to a boolean value: ``` if ($name eq 'Bob' && not greeted_bob()) { say 'Hello, Bob!'; found_bob(); } ``` The block form requires parentheses around its condition, but the postfix form does not. In the postfix form, adding parentheses can clarify the intent of the code at the expense of visual cleanliness: ``` greet_bob() if ($name eq 'Bob' && not greeted_bob()); ``` The `unless` directive is the negated form of `if` . Perl will perform the action when the conditional expression evaluates to a false value: ``` say "You're not Bob!" unless $name eq 'Bob'; ``` Like `if` , `unless` also has a block form, though many programmers avoid it due to its potential for confusion: ``` unless (is_leap_year() and is_full_moon()) { frolic(); gambol(); } ``` `unless` works very well for postfix conditionals, especially parameter validation in functions (Postfix Parameter Validation): ``` sub frolic { # do nothing without parameters return unless @_; for my $chant (@_) { ... } } ``` The block forms of `if` and `unless` both support the `else` directive, which provides a block to execute when the conditional expression does not evaluate to the appropriate value: `else` blocks allow you to rewrite `if` and `unless` conditionals in terms of each other: However, the implied double negative of using `unless` with an `else` block can be confusing. This example may be the only place you ever see it. Just as Perl provides both `if` and `unless` to allow you to phrase your conditionals in the most readable way, Perl has both positive and negative conditional operators: ... though the double negative implied by the presence of the `else` block may be difficult to read. Use one or more `elsif` directives to check multiple and mutually exclusive conditions: ``` if ($name eq 'Robert') { say 'Hi, Bob!'; greet_user(); } elsif ($name eq 'James') { say 'Hi, Jim!'; greet_user(); } elsif ($name eq 'Armando') { say 'Hi, Mando!'; greet_user(); } else { say "You're not my uncle."; shun_user(); } ``` An `unless` chain may also use an `elsif` block, but good luck deciphering that. Perl supports neither `elseunless` nor `else if` . Larry prefers `elsif` for aesthetic reasons, as well the prior art of the Ada programming language: ``` if ($name eq 'Rick') { say 'Hi, cousin!'; } # warning; syntax error else if ($name eq 'Kristen') { say 'Hi, cousin-in-law!'; } ``` ### The Ternary Conditional Operator The ternary conditional operator evaluates a conditional expression and evaluates to one of two alternatives: ``` my $time_suffix = after_noon($time) ? 'afternoon' : 'morning'; # equivalent to my $time_suffix; if (after_noon(time)) { $time_suffix = 'afternoon'; } else { $time_suffix = 'morning'; } ``` The conditional expression precedes the question mark character ( `?` ). The colon character ( `:` ) separates the alternatives. The alternatives are expressions of arbitrary complexity—including other ternary conditional expressions, though consider clarity over concision. # Short Circuiting Perl exhibits short-circuiting behavior when it encounters complex conditional expressions. When Perl can determine that a complex expression would succeed or fail as a whole without evaluating every subexpression, it will not evaluate subsequent subexpressions. This is most obvious with an example: The return value of `ok()` (Testing) is the boolean value produced by the first argument, so the example prints: ``` ok 1 - subexpression one ok 2 - subexpression two Both true! ``` When the first subexpression—the first call to `ok` —evaluates to a true value, Perl must evaluate the second subexpression. If the first subexpression had evaluated to a false value, there would be no need to check subsequent subexpressions, as the entire expression could not succeed: ``` not ok 1 - subexpression one ``` Even though the second subexpression would obviously succeed, Perl never evaluates it. The same short-circuiting behavior is evident for logical-or operations: ``` say 'Either true!' if ok 1, 'subexpression one' || ok 1, 'subexpression two'; ``` ``` ok 1 - subexpression one Either true! ``` Given the success of the first subexpression, Perl can avoid evaluating the second subexpression. If the first subexpression were false, the result of evaluating the second subexpression would dictate the result of evaluating the entire expression. Besides allowing you to avoid potentially expensive computations, short circuiting can help you to avoid errors and warnings, as in the case where using an undefined value might raise a warning: ``` my $bbq; if (defined $bbq and $bbq eq 'brisket') { ... } ``` ### Context for Conditional Directives The conditional directives— `if` , `unless` , and the ternary conditional operator—all evaluate an expression in boolean context (Context). As comparison operators such as `eq` , `==` , `ne` , and `!=` all produce boolean results when evaluated, Perl coerces the results of other expressions—including variables and values—into boolean forms. Perl has neither a single true value nor a single false value. Any number which evaluates to 0 is false. This includes `0` , `0.0` , `0e0` , `0x0` , and so on. The empty string ( `''` ) and `'0'` evaluate to a false value, but the strings `'0.0'` , `'0e0'` , and so on do not. The idiom `'0 but true'` evaluates to 0 in numeric context—but true in boolean context due to its string contents. Both the empty list and `undef` evaluate to a false value. Empty arrays and hashes return the number 0 in scalar context, so they evaluate to a false value in boolean context. An array which contains a single element—even `undef` —evaluates to true in boolean context. A hash which contains any elements—even a key and a value of `undef` —evaluates to a true value in boolean context. Greater Control Over Context The `Want` module from the CPAN allows you to detect boolean context within your own functions. The core `overloading` pragma (Overloading) allows you to specify what your own data types produce when evaluated in various contexts. ### Looping Directives Perl provides several directives for looping and iteration. The foreach-style loop evaluates an expression which produces a list and executes a statement or block until it has exhausted that list: ``` # square the first ten positive integers foreach (1 .. 10) { say "$_ * $_ = ", $_ * $_; } ``` This example uses the range operator to produce a list of integers from one to ten inclusive. The `foreach` directive loops over them, setting the topic variable `$_` (The Default Scalar Variable) to each in turn. Perl executes the block for each integer and, as a result, prints the squares of the integers. `foreach` versus `for` Many Perl programmers refer to iteration as `foreach` loops, but Perl treats the names `foreach` and `for` interchangeably. The parenthesized expression determines the type and behavior of the loop; the keyword does not. Like `if` and `unless` , this loop has a postfix form: ``` say "$_ * $_ = ", $_ * $_ for 1 .. 10; ``` A `for` loop may use a named variable instead of the topic: When a `for` loop uses an iterator variable, the variable is scoped to the block within the loop. Perl will set this lexical to the value of each item in the iteration. Perl will not modify the topic variable ( `$_` ). If you have declared a lexical `$i` in an outer scope, its value will persist outside the loop: ``` my $i = 'cow'; This localization occurs even if you do not redeclare the iteration variable as a lexical, but keep the habit of declaring iteration values as lexicals: ``` my $i = 'horse'; ### Iteration and Aliasing The `for` loop aliases the iterator variable to the values in the iteration such that any modifications to the value of the iterator modifies the value in place: $_ **= 2 for @nums; is $nums[0], 1, '1 * 1 is 1'; is $nums[1], 4, '2 * 2 is 4'; is $nums[9], 100, '10 * 10 is 100'; ``` This aliasing also works with the block style `for` loop: ``` for my $num (@nums) { $num **= 2; } ``` ... as well as iteration with the topic variable: ``` for (@nums) { $_ **= 2; } ``` You cannot use aliasing to modify constant values, however. Perl will produce an exception about modification of read-only values. ``` $_++ and say for qw( Huex Dewex Louid ); ``` You may occasionally see the use of `for` with a single scalar variable: ``` for ($user_input) { s/\A\s+//; # trim leading whitespace s/\s+\z//; # trim trailing whitespace $_ = quotemeta; # escape non-word characters } ``` This idiom (Idioms) uses the iteration operator for its side effect of aliasing `$_` , though it's clearer to operate on the named variable itself. ### Iteration and Scoping The topic variable's iterator scoping has a subtle gotcha. Consider a function `topic_mangler()` which modifies `$_` on purpose. If code iterating over a list called `topic_mangler()` without protecting `$_` , you'd have to spend some time debugging the effects: ``` for (@values) { topic_mangler(); } sub topic_mangler { s/foo/bar/; } ``` The substitution in `topic_mangler()` will modify elements of `@values` in place. If you must use `$_` rather than a named variable, use the topic aliasing behavior of `for` : ``` sub topic_mangler { # was $_ = shift; for (shift) { s/foo/bar/; s/baz/quux/; return $_; } } ``` Alternately, use a named iteration variable in the `for` loop. That's almost always the right advice. ### The C-Style For Loop The C-style for loop requires you to manage the conditions of iteration: You must explicitly assign to an iteration variable in the looping construct, as this loop performs neither aliasing nor assignment to the topic variable. While any variable declared in the loop construct is scoped to the lexical block of the loop, Perl will not limit the lexical scope of a variable declared outside of the loop construct: ``` my $i = 'pig'; isnt $i, 'pig', '$i overwritten with a number'; ``` The looping construct may have three subexpressions. The first subexpression—the initialization section—executes only once, before the loop body executes. Perl evaluates the second subexpression—the conditional comparison—before each iteration of the loop body. When this evaluates to a true value, iteration proceeds. When it evaluates to a false value, iteration stops. The final subexpression executes after each iteration of the loop body. ``` for ( # loop initialization subexpression say 'Initializing', my $i = 0; # conditional comparison subexpression say "Iteration: $i" and $i < 10; # iteration ending subexpression say 'Incrementing ' . $i++ ) { say "$i * $i = ", $i * $i; } ``` Note the lack of a semicolon after the final subexpression as well as the use of the comma operator and low-precedence `and` ; this syntax is surprisingly finicky. When possible, prefer the `foreach` -style loop to the `for` loop. All three subexpressions are optional. One infinite `for` loop is: `for (;;) { ... }` ### While and Until A while loop continues until the loop conditional expression evaluates to a false value. An idiomatic infinite loop is: `while (1) { ... }` Unlike the iteration `foreach` -style loop, the `while` loop's condition has no side effects. If `@values` has one or more elements, this code is also an infinite loop, because every iteration will evaluate `@values` in scalar context to a non-zero value and iteration will continue: ``` while (@values) { say $values[0]; } ``` To prevent such an infinite `while` loop, use a destructive update of the `@values` array by modifying the array within each iteration: ``` while (@values) { my $value = shift @values; say $value; } ``` Modifying `@values` inside of the `while` condition check also works, but it has some subtleties related to the truthiness of each value. ``` while (my $value = shift @values) { say $value; } ``` This loop will exit as soon as the assignment expression used as the conditional expression evaluates to a false value. If that's what you intend, add a comment to the code. The until loop reverses the sense of the test of the `while` loop. Iteration continues while the loop conditional expression evaluates to a false value: ``` until ($finished_running) { ... } ``` The canonical use of the `while` loop is to iterate over input from a filehandle: ``` while (<$fh>) { # remove newlines chomp; ... } ``` Perl interprets this `while` loop as if you had written: ``` while (defined($_ = <$fh>)) { # remove newlines chomp; ... } ``` Without the implicit `defined` , any line read from the filehandle which evaluated to a false value in a scalar context—a blank line or a line which contained only the character `0` —would end the loop. The `readline` ( `<>` ) operator returns an undefined value only when it has reached the end of the file. Both `while` and `until` have postfix forms, such as the infinite loop `1 while 1;` . Any single expression is suitable for a postfix `while` or `until` , including the classic "Hello, world!" example from 8-bit computers of the early 1980s: ``` print "Hello, world! " while 1; ``` Infinite loops are more useful than they seem, especially for event loops in GUI programs, program interpreters, or network servers: ``` $server->dispatch_results until $should_shutdown; ``` Use a `do` block to group several expressions into a single unit: ``` do { say 'What is your name?'; my $name = <>; chomp $name; say "Hello, $name!" if $name; } until (eof); ``` A `do` block parses as a single expression which may contain several expressions. Unlike the `while` loop's block form, the `do` block with a postfix `while` or `until` will execute its body at least once. This construct is less common than the other loop forms, but very powerful. ### Loops within Loops You may nest loops within other loops: ``` for my $suit (@suits) { for my $values (@card_values) { ... } } ``` Note the value of declaring iteration variables! The potential for confusion with the topic variable and its scope is too great otherwise. Novices commonly exhaust filehandles accidentally while nesting `foreach` and `while` loops: ``` use autodie 'open'; open my $fh, '<', $some_file; for my $prefix (@prefixes) { # DO NOT USE; buggy code while (<$fh>) { say $prefix, $_; } } ``` Opening the filehandle outside of the `for` loop leaves the file position unchanged between each iteration of the `for` loop. On its second iteration, the `while` loop will have nothing to read (the `readline` will return a false value). You can solve this problem in many ways; re-open the file inside the `for` loop (wasteful but simple), slurp the entire file into memory (works best with small files), or `seek` the filehandle back to the beginning of the file for each iteration: ``` for my $prefix (@prefixes) { while (<$fh>) { say $prefix, $_; } seek $fh, 0, 0; } ``` ### Loop Control Sometimes you must break out of a loop before you have exhausted the iteration conditions. Perl's standard control mechanisms—exceptions and `return` —work, but you may also use loop control statements. The next statement restarts the loop at its next iteration. Use it when you've done everything you need to in the current iteration. To loop over lines in a file and skip everything that starts with the comment character `#` : Multiple Exits versus Nested Ifs Compare the use of `next` with the alternative: wrapping the rest of the body of the block in an `if` . Now consider what happens if you have multiple conditions which could cause you to skip a line. Loop control modifiers with postfix conditionals can make your code much more readable. The last statement ends the loop immediately. To finish processing a file once you've seen the ending token, write: The redo statement restarts the current iteration without evaluating the conditional again. This can be useful in those few cases where you want to modify the line you've read in place, then start processing over from the beginning without clobbering it with another line. To implement a silly file parser that joins lines which end with a backslash: ``` while (my $line = <$fh>) { chomp $line; # match backslash at the end of a line if ($line =~ s{\\$}{}) { $line .= <$fh>; redo; } Nested loops can be confusing, especially with loop control statements. If you cannot extract inner loops into named functions, use loop labels to clarify your intent: ``` LINE: while (<$fh>) { chomp; PREFIX: for my $prefix (@prefixes) { next LINE unless $prefix; say "$prefix: $_"; # next PREFIX is implicit here } } ``` ### Continue The `continue` construct behaves like the third subexpression of a `for` loop; Perl executes any continue block before subsequent iterations of a loop, whether due to normal loop repetition or premature re-iteration from `next` . You may use it with a `while` , `until` , `when` , or `for` loop. Examples of `continue` are rare, but it's useful any time you want to guarantee that something occurs with every iteration of the loop, regardless of how that iteration ends: ``` while ($i < 10 ) { next unless $i % 2; say $i; } continue { say 'Continuing...'; $i++; } ``` Be aware that a `continue` block does not execute when control flow leaves a loop due to `last` or `redo` . ### Switch Statements Perl 5.10 introduced a new construct named `given` as a Perlish `switch` statement. It didn't quite work out; `given` is still experimental, if less buggy in newer releases. Avoid it unless you know exactly what you're doing. If you need a switch statement, use `for` to alias the topic variable ( `$_` ) and `when` to match it against simple expressions with smart match (Smart Matching) semantics. To write the Rock, Paper, Scissors game: ``` my @options = ( \&rock, \&paper, \&scissors ); my $confused = "I don't understand your move."; do { say "Rock, Paper, Scissors! Pick one: "; chomp( my $user = <STDIN> ); my $computer_match = $options[ rand @options ]; $computer_match->( lc( $user ) ); } until (eof); sub rock { print "I chose rock. "; sub paper { print "I chose paper. "; sub scissors { print "I chose scissors. "; Perl executes the `default` rule when none of the other conditions match. Adding Spock and Lizard is left as an exercise for the reader. ### Tailcalls A tailcall occurs when the last expression within a function is a call to another function. The outer function's return value becomes the inner function's return value: ``` sub log_and_greet_person { my $name = shift; log( "Greeting $name" ); return greet_person( $name ); } ``` is more efficient than returning to and then from is a tailcall optimization. Heavily recursive code (Recursion)—especially mutually recursive code—can consume a lot of memory. Tailcalls reduce the memory needed for internal bookkeeping of control flow and can make expensive algorithms cheaper. Unfortunately, Perl does not automatically perform this optimization, so you have to do it yourself when it's necessary. The builtin `goto` operator has a form which calls a function as if the current function were never called, essentially erasing the bookkeeping for the new function call. The ugly syntax confuses people who've heard "Never use `goto` ", but it works: ``` sub log_and_greet_person { my ($name) = @_; log( "Greeting $name" ); goto &greet_person; } ``` This example has two important characteristics. First, `goto &function_name` or ``` goto &$function_reference ``` requires the use of the function sigil ( `&` ) so that the parser knows to perform a tailcall instead of jumping to a label. Second, this form of function call passes the contents of `@_` implicitly to the called function. You may modify `@_` to change the passed arguments if you desire. This technique is most useful when you want to hijack control flow to get out of the way of other functions inspecting `caller` (such as when you're implementing special logging or some sort of debugging feature), or when using an algorithm which requires a lot of recursion. Remember it if you need it, but feel free not to use it. ## Scalars Perl's fundamental data type is the scalar: a single, discrete value. That value may be a string, an integer, a floating point value, a filehandle, or a reference—but it is always a single value. Scalars may be lexical, package, or global (Global Variables) variables. You may only declare lexical or package variables. The names of scalar variables must conform to standard variable naming guidelines (Names). Scalar variables always use the leading dollar-sign ( `$` ) sigil (Variable Sigils). Variant Sigils and Context Scalar values and scalar context have a deep connection; assigning to a scalar imposes scalar context. Using the scalar sigil with an aggregate variable accesses a single element of the hash or array in scalar context. ### Scalars and Types A scalar variable can contain any type of scalar value without special conversions, coercions, or casts. The type of value stored in a scalar variable, once assigned, can change arbitrarily: ``` my $value; $value = 123.456; $value = 77; $value = "I am Chuck's big toe."; $value = Store::IceCream->new; ``` Even though this code is legal, changing the type of data stored in a scalar is confusing. This flexibility of type often leads to value coercion (Coercion). For example, you may treat the contents of a scalar as a string, even if you didn't explicitly assign it a string: ``` my $zip_code = 97123; my $city_state_zip = 'Hillsboro, Oregon' . ' ' . $zip_code; ``` You may also use mathematical operations on strings: ``` my $call_sign = 'KBMIU'; # update sign in place and return new value my $next_sign = ++$call_sign; # return old value, then update sign my $curr_sign = $call_sign++; # but does not work as: my $new_sign = $call_sign + 1; ``` One-Way Increment Magic This magical string increment behavior has no corresponding magical decrement behavior. You can't restore the previous string value by writing `$call_sign--` . This string increment operation turns `a` into `b` and `z` into `aa` , respecting character set and case. While `ZZ9` becomes `AAA0` , `ZZ09` becomes `ZZ10` —numbers wrap around while there are more significant places to increment, as on a vehicle odometer. Evaluating a reference (References) in string context produces a string. Evaluating a reference in numeric context produces a number. Neither operation modifies the reference in place, but you cannot recreate the reference from either result: ``` my $authors = [qw( <NAME> )]; my $stringy_ref = '' . $authors; my $numeric_ref = 0 + $authors; ``` `$authors` is still useful as a reference, but `$stringy_ref` is a string with no connection to the reference and `$numeric_ref` is a number with no connection to the reference. To allow coercion without data loss, Perl scalars can contain both numeric and string components. The internal data structure which represents a scalar in Perl has a numeric slot and a string slot. Accessing a string in a numeric context produces a scalar with both string and numeric values. Scalars do not contain a separate slot for boolean values. In boolean context, the empty strings ( `''` ) and `'0'` evaluate to false values. All other strings evaluate to true values. In boolean context, numbers which evaluate to zero ( `0` , `0.0` , and `0e0` ) evaluate to false values. All other numbers evaluate to true values. What is Truth? Be careful that the strings `'0.0'` and `'0e0'` evaluate to true values. This is one place where Perl makes a distinction between what looks like a number and what really is a number. `undef` is always a false value. ## Arrays Perl's array data type is a language-supported aggregate which can store zero or more scalars. You can access individual members of the array by integer indexes, and you can add or remove elements at will. Arrays grow or shrink as you manipulate them. The `@` sigil denotes an array. To declare an array: `my @items;` ### Array Elements Use the scalar sigil to access an individual element of an array. `$cats[0]` refers unambiguously to the `@cats` array, because postfix (Fixity) square brackets ( `[]` ) always mean indexed access to an array. The first element of an array is at the zeroth index: ``` # @cats contains a list of Cat objects my $first_cat = $cats[0]; ``` The last index of an array depends on the number of elements in the array. An array in scalar context (due to scalar assignment, string concatenation, addition, or boolean context) evaluates to the number of elements in the array: ``` # scalar assignment my $num_cats = @cats; # string concatenation say 'I have ' . @cats . ' cats!'; # addition my $num_animals = @cats + @dogs + @fish; # boolean context say 'Yep, a cat owner!' if @cats; ``` To get the index of the final element of an array, subtract one from the number of elements of the array (because array indexes start at 0) or use the unwieldy `$#cats` syntax: ``` my $first_index = 0; my $last_index = @cats - 1; # or # my $last_index = $#cats; say "My first cat has an index of $first_index, " . "and my last cat has an index of $last_index." ``` Most of the time you care more about the relative position of an array element. Use a negative array index to refer to elements from the end. The last element of an array is available at the index `-1` . The second to last element of the array is available at index `-2` , and so on: ``` my $last_cat = $cats[-1]; my $second_to_last_cat = $cats[-2]; ``` `$#` has another use: resize an array in place by assigning to `$#array` . Remember that Perl arrays are mutable. They expand or contract as necessary. When you shrink an array, Perl will discard values which do not fit in the resized array. When you expand an array, Perl will fill the expanded positions with `undef` . ### Array Assignment Assign to individual positions in an array directly by index: ``` my @cats; $cats[3] = 'Jack'; $cats[2] = 'Tuxedo'; $cats[0] = 'Daisy'; $cats[1] = 'Petunia'; $cats[4] = 'Brad'; $cats[5] = 'Choco'; ``` If you assign to an index beyond the array's current bounds, Perl will extend the array for you. As you might expect, all intermediary positions with then contain `undef` . After the first assignment, the array will contain `undef` at positions 0, 1, and 2 and `Jack` at position 3. As an assignment shortcut, initialize an array from a list: ``` my @cats = ( 'Daisy', 'Petunia', 'Tuxedo', ... ); ``` ... but remember that these parentheses do not create a list. Without parentheses, this would assign `Daisy` as the first and only element of the array, due to operator precedence (Precedence). `Petunia` , `Tuxedo` , and all of the other cats would be evaluated in void context and Perl would complain. (So would all the other cats, especially Petunia.) You may assign any expression which produces a list to an array: ``` my @cats = get_cat_list(); my @timeinfo = localtime(); my @nums = 1 .. 10; ``` Assigning to a scalar element of an array imposes scalar context, while assigning to the array as a whole imposes list context. To clear an array, assign an empty list: ``` my @dates = ( 1969, 2001, 2010, 2051, 1787 ); ... @dates = (); ``` This is one of the only cases where parentheses do indicate a list; without something to mark a list, Perl and readers of the code would get confused. Arrays Start Empty `my @items = ();` is a longer and noisier version of `my @items` . Freshly-declared arrays start out empty. Not "full of `undef` " empty. Really empty. ### Array Operations Sometimes an array is more convenient as an ordered, mutable collection of items than as a mapping of indices to values. Perl provides several operations to manipulate array elements. The `push` and `pop` operators add and remove elements from the tail of an array, respectively: ``` my @meals; # what is there to eat? push @meals, qw( hamburgers pizza lasagna turnip ); # ... but your nephew hates vegetables pop @meals; ``` You may `push` a list of values onto an array, but you may only `pop` one at a time. `push` returns the new number of elements in the array. `pop` returns the removed element. Because `push` operates on a list, you can easily append the elements of one multiple arrays with: ``` push @meals, @breakfast, @lunch, @dinner; ``` Similarly, `unshift` and `shift` add elements to and remove an element from the start of an array, respectively: ``` # expand our culinary horizons unshift @meals, qw( tofu spanakopita taquitos ); # rethink that whole soy idea shift @meals; ``` `unshift` prepends a list of elements to the start of the array and returns the new number of elements in the array. `shift` removes and returns the first element of the array. Almost no one uses these return values. The `splice` operator removes and replaces elements from an array given an offset, a length of a list slice, and replacement elements. Both replacing and removing are optional; you may omit either. The `perlfunc` description of `splice` demonstrates its equivalences with `push` , `pop` , `shift` , and `unshift` . One effective use is removal of two elements from an array: ``` my ($winner, $runnerup) = splice @finalists, 0, 2; # or my $winner = shift @finalists; my $runnerup = shift @finalists; ``` The `each` operator allows you to iterate over an array by index and value: ``` while (my ($position, $title) = each @bookshelf) { say "#$position: $title"; } ``` ### Array Slices An array slice allows you to access elements of an array in list context. Unlike scalar access of an array element, this indexing operation takes a list of zero or more indices and uses the array sigil ( `@` ): ``` my @youngest_cats = @cats[-1, -2]; my @oldest_cats = @cats[0 .. 2]; my @selected_cats = @cats[ @indexes ]; ``` Array slices are useful for assignment: ``` @users[ @replace_indices ] = @replace_users; ``` The only syntactic difference between an array slice of one element and the scalar access of an array element is the leading sigil. The semantic difference is greater: an array slice always imposes list context. An array slice evaluated in scalar context will produce a warning: ``` Scalar value @cats[1] better written as $cats[1]... ``` An array slice imposes list context on the expression used as its index: ``` # function called in list context my @hungry_cats = @cats[ get_cat_indices() ]; ``` A slice can contain zero or more elements—including one: ``` # single-element array slice; list context @cats[-1] = get_more_cats(); # single-element array access; scalar context $cats[-1] = get_more_cats(); ``` ### Arrays and Context In list context, arrays flatten into lists. If you pass multiple arrays to a normal function, they will flatten into a single list: ``` my @cats = qw( <NAME> <NAME> ); my @dogs = qw( <NAME> ); take_pets_to_vet( @cats, @dogs ); sub take_pets_to_vet { # BUGGY: do not use! my (@cats, @dogs) = @_; ... } ``` Within the function, `@_` will contain nine elements, not two, because list assignment to arrays is greedy. An array will consume as many elements from the list as possible. After the assignment, `@cats` will contain every argument passed to the function. `@dogs` will be empty, and woe to anyone who treats Rodney as a cat. This flattening behavior sometimes confuses people who attempt to create nested arrays: ``` # creates a single array, not an array of arrays my @numbers = (1 .. 10, (11 .. 20, (21 .. 30))); ``` ... but this code is effectively the same as either: ``` # parentheses do not create lists my @numbers = ( 1 .. 10, 11 .. 20, 21 .. 30 ); # creates a single array, not an array of arrays my @numbers = 1 .. 30; ``` ... because, again, parentheses merely group expressions. They do not create lists. To avoid this flattening behavior, use array references (Array References). ### Array Interpolation Arrays interpolate in strings as lists of the stringification of each item separated by the current value of the magic global `$"` . The default value of this variable is a single space. Its English.pm mnemonic is `$LIST_SEPARATOR` . Thus: ``` my @alphabet = 'a' .. 'z'; say "[@alphabet]"; [a b c d e f g h i j k l m n o p q r s t u v w x y z] ``` Per <NAME>, localize `$"` with a delimiter to improve your debugging: ``` # what's in this array again? local $" = ')('; say "(@sweet_treats)"; (pie)(cake)(doughnuts)(cookies)(cinnamon roll) ``` ## Hashes A hash is an aggregate data structure which associates string keys with scalar values. Just as the name of a variable corresponds to something which holds a value, so a hash key refers to something which contains a value. Think of a hash like a contact list: use the names of your friends to look up their birthdays. Other languages call hashes tables, associative arrays, dictionaries, and maps. Hashes have two important properties: they store one scalar per unique key and they provide no specific ordering of keys. Keep that latter property in mind. Though it has always been true in Perl, it's very, very true in modern Perl. ### Declaring Hashes Hashes use the `%` sigil. Declare a lexical hash with: ``` my %favorite_flavors; ``` A hash starts out empty. You could write ``` my %favorite_flavors = (); ``` , but that's redundant. Hashes use the scalar sigil `$` when accessing individual elements and curly braces `{ }` for keyed access: ``` my %favorite_flavors; $favorite_flavors{Gabi} = 'Dark chocolate raspberry'; $favorite_flavors{Annette} = 'French vanilla'; ``` Assign a list of keys and values to a hash in a single expression: ``` my %favorite_flavors = ( 'Gabi', 'Dark chocolate raspberry', 'Annette', 'French vanilla', ); ``` Hashes store pairs of keys and values. Perl will warn you if you assign an odd number of elements to a hash. Idiomatic Perl often uses the fat comma operator ( `=>` ) to associate values with keys, as it makes the pairing more visible: ``` my %favorite_flavors = ( Gabi => 'Dark chocolate raspberry', Annette => 'French vanilla', ); ``` The fat comma operator acts like the regular comma and also automatically quotes the previous bareword (Barewords). The `strict` pragma will not warn about such a bareword—and if you have a function with the same name as a hash key, the fat comma will not call the function: ``` sub name { 'Leonardo' } my %address = ( name => '1123 Fib Place' ); ``` The key of this hash will be `name` and not `Leonardo` . To call the function, make the function call explicit: ``` my %address = ( name() => '1123 Fib Place' ); ``` You may occasionally see `undef %hash` , but that's a little ugly. Assign an empty list to empty a hash: ``` %favorite_flavors = (); ``` ### Hash Indexing To access an individual hash value, use the keyed access syntax: ``` my $address = $addresses{$name}; ``` In this example, `$name` contains a string which is also a key of the hash. As with accessing an individual element of an array, the hash's sigil has changed from `%` to `$` to indicate keyed access to a scalar value. You may also use string literals as hash keys. Perl quotes barewords automatically according to the same rules as fat commas: ``` # auto-quoted my $address = $addresses{Victor}; # needs quoting; not a valid bareword my $address = $addresses{'Sue-Linn'}; # function call needs disambiguation my $address = $addresses{get_name()}; ``` Don't Quote Me Novices often always quote string literal hash keys, but experienced developers elide the quotes whenever possible. If you code this way, you can use the rare presence of quotes to indicate that you're doing something special on purpose. Even Perl builtins get the autoquoting treatment: sub get_address_from_name { return $addresses{+shift}; } ``` The unary plus (Unary Coercions) turns what would be a bareword ( `shift` ) subject to autoquoting rules into an expression. As this implies, you can use an arbitrary expression—not only a function call—as the key of a hash: ``` # don't actually do this though my $address = $addresses{reverse 'odranoeL'}; # interpolation is fine my $address = $addresses{"$first_name $last_name"}; # so are method calls my $address = $addresses{ $user->name }; ``` Hash keys can only be strings. Anything that evaluates to a string is an acceptable hash key. Perl will go so far as to coerce (Coercion) an expression into a string. For example, if you use an object as a hash key, you'll get the stringified version of that object instead of the object itself: ``` for my $isbn (@isbns) { my $book = Book->fetch_by_isbn( $isbn ); # unlikely to do what you want $books{$book} = $book->price; } ``` That stringified hash will look something like `Book=HASH(0x222d148)` . `Book` refers to the class name. `HASH` identifies the object as a blessed reference. `0x22d148` is a number used to identify the object (more precisely: it's the location of the data structure representing the hash in memory, so it's neither quite random nor unique). ### Hash Key Existence The `exists` operator returns a boolean value to indicate whether a hash contains the given key: say "Have Leonardo's address" if exists $addresses{Leonardo}; say "Have Warnie's address" if exists $addresses{Warnie}; ``` Using `exists` instead of accessing the hash key directly avoids two problems. First, it does not check the boolean nature of the hash value; a hash key may exist with a value even if that value evaluates to a boolean false (including `undef` ): ``` my %false_key_value = ( 0 => '' ); ok %false_key_value, 'hash containing false key & value should evaluate to a true value'; ``` Second, `exists` avoids autovivification (Autovivification) within nested data structures (Nested Data Structures). If a hash key exists, its value may be `undef` . Check that with `defined` : ``` $addresses{Leibniz} = undef; say "Gottfried lives at $addresses{Leibniz}" if exists $addresses{Leibniz} && defined $addresses{Leibniz}; ``` ### Accessing Hash Keys and Values Hashes are aggregate variables, but their pairwise nature is unique. Perl allows you to iterate over a hash's keys, its values, or pairs of its keys and values. The `keys` operator produces a list of hash keys: ``` for my $addressee (keys %addresses) { say "Found an address for $addressee!"; } ``` The `values` operator produces a list of hash values: ``` for my $address (values %addresses) { say "Someone lives at $address"; } ``` The `each` operator produces a list of two-element key/value lists: ``` while (my ($addressee, $address) = each %addresses) { say "$addressee lives at $address"; } ``` Unlike arrays, hash elements have no obvious ordering. The ordering depends on the internal implementation of the hash, the particular version of Perl you are using, the size of the hash, and a random factor. Even so, the order of hash items is consistent between `keys` , `values` , and `each` . Modifying the hash may change the order, but you can rely on that order if the hash remains the same. However, even if two hashes have the same keys and values, you cannot rely on the iteration order between those hashes being the same. They may have been constructed differently or have had elements removed. Since Perl 5.18, even if you build two hashes in the same way, you cannot depend on the same iteration order between them. Read the previous paragraph again. You'll be glad you did. Each hash has only a single iterator for the `each` operator. You cannot reliably iterate over a hash with `each` more than once; if you begin a new iteration while another is in progress, the former will end prematurely and the latter will begin partway through the iteration. Beware not to call any function which may itself try to iterate over the hash with `each` . This is rarely a problem, but it's not fun to debug. Reset a hash's iterator with `keys` or `values` in void context: ``` # reset hash iterator keys %addresses; while (my ($addressee, $address) = each %addresses) { ... } ``` ### Hash Slices A hash slice is a list of keys or values of a hash indexed in a single operation. To initialize multiple elements of a hash at once: ``` my %cats; @cats{qw( <NAME> Grumpy )} = (1) x 4; ``` This is equivalent to the initialization: ``` my %cats = map { $_ => 1 } qw( <NAME> Grumpy ); ``` Note however that the hash slice assignment can also add to the existing contents of the hash. Hash slices also allow you to retrieve multiple values from a hash in a single operation. As with array slices, the sigil of the hash changes to `@` to indicate list context. The use of the curly braces indicates keyed access and makes the fact that you're working with a hash unambiguous: ``` my @buyer_addresses = @addresses{ @buyers }; ``` Hash slices make it easy to merge two hashes: ``` my %addresses = ( ... ); my %canada_addresses = ( ... ); @addresses{ keys %canada_addresses } = values %canada_addresses; ``` This is equivalent to looping over the contents of `%canada_addresses` manually, but is much shorter. Note that this relies on the iteration order of the hash remaining consistent between `keys` and `values` . Perl guarantees this, but only because these operations occur on the same hash with no modifications to that hash between the `keys` and `values` operations. What if the same key occurs in both hashes? The hash slice approach always overwrites existing key/value pairs in `%addresses` . If you want other behavior, looping is more appropriate. ### The Empty Hash An empty hash contains no keys or values. It evaluates to a false value in a boolean context. A hash which contains at least one key/value pair evaluates to a true value in boolean context even if all of the keys or all of the values or both would themselves evaluate to boolean false values. my %empty; ok ! %empty, 'empty hash should evaluate false'; In scalar context, a hash evaluates to a string which represents the ratio of full buckets in the hash—internal details about the hash implementation that you can safely ignore. In a boolean scalar context, this ratio evaluates to a false value, so remember that instead of the ratio details. In list context, a hash evaluates to a list of key/value pairs similar to the list produced by the `each` operator. However, you cannot iterate over this list the same way you can iterate over the list produced by `each` . This loop will never terminate: ``` # infinite loop for non-empty hashes while (my ($key, $value) = %hash) { ... } ``` You can loop over the list of keys and values with a `for` loop, but the iterator variable will get a key on one iteration and its value on the next, because Perl will flatten the hash into a single list of interleaved keys and values. ### Hash Idioms Because each key exists only once in a hash, assigning the same key to a hash multiple times stores only the most recent value associated with that key. This behavior has advantages! For example, to find unique elements of a list: ``` my %uniq; undef @uniq{ @items }; my @uniques = keys %uniq; ``` Using `undef` with a hash slice sets the values of the hash to `undef` . This idiom is the cheapest way to perform set operations with a hash. Hashes are useful for counting elements, such as IP addresses in a log file: ``` my %ip_addresses; while (my $line = <$logfile>) { chomp $line; my ($ip, $resource) = analyze_line( $line ); $ip_addresses{$ip}++; ... } ``` The initial value of a hash value is `undef` . The postincrement operator ( `++` ) treats that as zero. This in-place modification of the value increments an existing value for that key. If no value exists for that key, Perl creates a value ( `undef` ) and immediately increments it to one, as the numification of `undef` produces the value 0. This strategy provides a useful caching mechanism to store the result of an expensive operation with little overhead: ``` { my %user_cache; sub fetch_user { my $id = shift; $user_cache{$id} //= create_user($id); return $user_cache{$id}; } } ``` This orcish maneuver (or-cache) returns the value from the hash, if it exists. Otherwise, it calculates, caches, and returns the value. The defined-or assignment operator ( `//=` ) evaluates its left operand. If that operand is not defined, the operator assigns to the lvalue the value of its right operand. In other words, if there's no value in the hash for the given key, this function will call `create_user()` with the key and update the hash. You may see older code which uses the boolean-or assignment operator ( `||=` ) for this purpose. Remember though that some valid values evaluate as false in a boolean context. The defined-or operator usually makes more sense, as it tests for definedness instead of truthiness. If your function takes several arguments, use a slurpy hash (Slurping) to gather key/value pairs into a single hash as named function arguments: ``` sub make_sundae { my %parameters = @_; ... } make_sundae( flavor => 'Lemon Burst', topping => 'cookie bits' ); ``` This approach allows you to set default values: ``` sub make_sundae { my %parameters = @_; $parameters{flavor} //= 'Vanilla'; $parameters{topping} //= 'fudge'; $parameters{sprinkles} //= 100; ... } ``` ... or include them in the hash initialization, as latter assignments take precedence over earlier assignments: ``` sub make_sundae { my %parameters = ( flavor => 'Vanilla', topping => 'fudge', sprinkles => 100, @_, ); ... } ``` ### Locking Hashes As hash keys are barewords, they offer little typo protection compared to the function and variable name protection offered by the `strict` pragma. The little-used core module `Hash::Util` can make hashes safer. To prevent someone from accidentally adding a hash key you did not intend (whether as a typo or from untrusted user input), use the `lock_keys()` function to restrict the hash to its current set of keys. Any attempt to add a new key to the hash will raise an exception. Similarly you can lock or unlock the existing value for a given key in the hash ( `lock_value()` and `unlock_value()` ) and make or unmake the entire hash read-only with `lock_hash()` and `unlock_hash()` . This is lax security; anyone can use the appropriate unlocking functions to work around the locking. Yet it does protect against typos and other unintended accidents. ## Coercion Throughout the lifetime of a Perl variable, it may contain values of different types—strings, integers, rational numbers, and more. Instead of attaching type information to variables, Perl relies on the context provided by operators (Numeric, String, and Boolean Context) to determine how to handle values. By design, Perl attempts to do what you mean—you may hear this referred to as DWIM for do what I mean or dwimmery.>—though you must be specific about your intentions. If you treat a value as a string, Perl will do its best to coerce that value into a string. ### Boolean Coercion Boolean coercion occurs when you test the truthiness of a value, such as in an `if` or `while` condition. Numeric 0, `undef` , the empty string, and the string `'0'` all evaluate as false values. All other values—including strings which may be numerically equal to zero (such as `'0.0'` , `'0e'` , and `'0 but true'` )—evaluate as true values. When a scalar has both string and numeric components (Dualvars), Perl prefers to check the string component for boolean truth. `'0 but true'` evaluates to zero numerically, but it is not an empty string, so it evaluates to a true value in boolean context. ### String Coercion String coercion occurs when using string operators such as comparisons ( `eq` and `cmp` ), concatenation, `split` , `substr` , and regular expressions, as well as when using a value or an expression as a hash key. The undefined value stringifies to an empty string but produces a "use of uninitialized value" warning. Numbers stringify to strings containing their values; the value `10` stringifies to the string `10` . You can even `split` a number into individual digits with: ``` my @digits = split '', 1234567890; ``` ### Numeric Coercion Numeric coercion occurs when using numeric comparison operators (such as `==` and `<=>` ), when performing mathematic operations, and when using a value or expression as an array or list index. The undefined value numifies to zero and produces a "Use of uninitialized value" warning. Strings which do not begin with numeric portions numify to zero and produce an "Argument isn't numeric" warning. Strings which begin with characters allowed in numeric literals numify to those values and produce no warnings, such that `10 leptons leaping` numifies to `10` and ``` 6.022e23 moles marauding ``` numifies to `6.022e23` . The core module `Scalar::Util` contains a `looks_like_number()` function which uses the same rules as the Perl parser to extract a number from a string. Mathematicians Rejoice The strings `Inf` and `Infinity` represent the infinite value and behave as numbers. The string `NaN` represents the concept "not a number". Numifying them produces no "Argument isn't numeric" warning. Beware that Perl's ideas of infinity and not a number may not match your platform's ideas; these notions aren't always portable across operating systems. Perl is consistent even if the rest of the universe isn't. ### Reference Coercion Using a dereferencing operation on a non-reference turns that value into a reference. This process of autovivification (Autovivification) is handy when manipulating nested data structures (Nested Data Structures): ``` my %users; $users{Brad}{id} = 228; $users{Jack}{id} = 229; ``` Although the hash never contained values for `Brad` and `Jack` , Perl helpfully created hash references for them, then assigned each a key/value pair keyed on `id` . ### Cached Coercions Perl's internal representation of values stores both string and numeric values. Stringifying a numeric value does not replace the numeric value. Instead, it adds a stringified value to the internal representation, which then contains both components. Similarly, numifying a string value populates the numeric component while leaving the string component untouched. Certain Perl operations prefer to use one component of a value over another—boolean checks prefer strings, for example. If a value has a cached representation in a form you do not expect, relying on an implicit conversion may produce surprising results. You almost never need to be explicit about what you expect. Your author can recall doing so twice in two decades. Even so, knowing that this caching occurs may someday help you diagnose an odd situation. ### Dualvars The multi-component nature of Perl values is available to users in the form of dualvars. The core module `Scalar::Util` provides a function `dualvar()` which allows you to bypass Perl coercion and manipulate the string and numeric components of a value separately: ``` use Scalar::Util 'dualvar'; my $false_name = dualvar 0, 'Sparkles & Blue'; say 'Boolean true!' if !! $false_name; say 'Numeric false!' unless 0 + $false_name; say 'String true!' if '' . $false_name; ``` ## Packages A Perl namespace associates and encapsulates various named entities. It's like your family name or a brand name. Unlike a real-world name, a namespace implies no direct relationship between entities. Such relationships may exist, but they are not required to. A package in Perl is a collection of code in a single namespace. The distinction is subtle: the package represents the source code and the namespace represents the internal data structure Perl uses to collect and group that code. The `package` builtin declares a package and a namespace: our @boxes; sub add_box { ... } ``` All global variables and functions declared or referred to after the package declaration refer to symbols within the `MyCode` namespace. You can refer to the `@boxes` variable from the `main` namespace only by its fully qualified name of `@MyCode::boxes` . A fully qualified name includes a complete package name, so that you can call the `add_box()` function by `MyCode::add_box()` . The scope of a package continues until the next `package` declaration or the end of the file, whichever comes first. You may also provide a block with `package` to delineate the scope of the declaration: ``` package Pinball::Wizard { our $VERSION = 1969; } ``` The default package is the `main` package. Without a package declaration, the current package is `main` . This rule applies to one-liners, standalone programs, and even .pm files. Besides a name, a package has a version and three implicit methods, `import()` (Importing), `unimport()` , and `VERSION()` . `VERSION()` returns the package's version. This is a series of numbers contained in a package global named `$VERSION` . By rough convention, versions are a series of dot-separated integers such as `1.23` or `1.1.10` . Perl includes a stricter syntax for version numbers, as documented in ``` perldoc version::Internals ``` . These version numbers must have a leading `v` character and at least three integer components separated by periods: ``` package MyCode v1.2.1; ``` Combined with the block form of a `package` declaration, you can write: ``` package Pinball::Wizard v1969.3.7 { ... } ``` You're more likely to see the older version of this code, written as: our $VERSION = 1.21; ``` Every package inherits a `VERSION()` method from the `UNIVERSAL` base class. This method returns the value of `$VERSION` : ``` my $version = Some::Plugin->VERSION; ``` If you provide a version number as an argument, this method will throw an exception unless the version of the module is equal to or greater than the argument: ``` # require at least 2.1 Some::Plugin->VERSION( 2.1 ); die "Your plugin $version is too old" unless $version > 2; ``` You may override `VERSION()` , though there are few reasons to do so. ### Packages and Namespaces Every `package` declaration creates a new namespace, if necessary. After Perl parses that declaration, it will store all subsequent package global symbols (global variables and functions) in that namespace. Perl has open namespaces. You can add functions or variables to a namespace at any point, either with a new package declaration: ``` package Pack { sub first_sub { ... } } Pack::first_sub(); package Pack { sub second_sub { ... } } Pack::second_sub(); ``` ... or by declaring functions with fully qualified names: ``` # implicit package main; You can add to a package at any point during compilation or runtime, regardless of the current file, though building up a package from multiple declarations in multiple files can make code difficult to spelunk. Namespaces can have as many levels as your organizational scheme requires, though namespaces are not hierarchical. The only relationship between separate packages is semantic, not technical. Many projects and businesses create their own top-level namespaces. This reduces the possibility of global conflicts and helps to organize code on disk. For example: * `StrangeMonkey` is the project name * `StrangeMonkey::UI` organizes user interface code * ``` StrangeMonkey::Persistence ``` organizes data management code * `StrangeMonkey::Test` organizes testing code for the project ... and so on. This is a convention, but it's a useful one. ## References Perl usually does what you expect, even if what you expect is subtle. Consider what happens when you pass values to functions: ``` sub reverse_greeting { my $name = reverse shift; return "Hello, $name!"; } my $name = 'Chuck'; say reverse_greeting( $name ); say $name; ``` Outside of the function, `$name` contains `Chuck` , even though the value passed into the function gets reversed into `kcuhC` . You probably expected that. The value of `$name` outside the function is separate from the `$name` inside the function. Modifying one has no effect on the other. Consider the alternative. If you had to make copies of every value before anything could possibly change them out from under you, you'd have to write lots of extra defensive code. Sometimes it's useful to modify values in place. If you want to pass a hash full of data to a function to modify it, creating and returning a new hash for each change could be tedious and inefficient, at least without some amazing compiler magic. Perl provides a mechanism by which to refer to a value without making a copy. Any changes made to that reference will update the value in place, such that all references to that value will refer to the modified value. A reference is a first-class scalar data type which refers to another first-class data type. ### Scalar References The reference operator is the backslash ( `\` ). In scalar context, it creates a single reference which refers to another value. In list context, it creates a list of references. To take a reference to `$name` : ``` my $name = 'Larry'; my $name_ref = \$name; ``` You must dereference a reference to evaluate the value to which it refers. Dereferencing requires you to add an extra sigil for each level of dereferencing: ``` sub reverse_in_place { my $name_ref = shift; $$name_ref = reverse $$name_ref; } my $name = 'Blabby'; reverse_in_place( \$name ); say $name; ``` The double scalar sigil ( `$$` ) dereferences a scalar reference. Parameters in `@_` behave as aliases to caller variables (Iteration and Aliasing), so you can modify them in place: my $name = 'allizocohC'; reverse_value_in_place( $name ); say $name; ``` You usually don't want to modify values this way—callers rarely expect it, for example. Assigning parameters to lexicals within your functions makes copies of the values in `@_` and avoids this aliasing behavior. Saving Memory with References Modifying a value in place or returning a reference to a scalar can save memory. Because Perl copies values on assignment, you could end up with multiple copies of a large string. Passing around references means that Perl will only copy the references—a far cheaper operation. Before you modify your code to pass only references, however, measure to see if this will make a difference. Complex references may require a curly-brace block to disambiguate portions of the expression. You may always use this syntax, though sometimes it clarifies and other times it obscures: ``` sub reverse_in_place { my $name_ref = shift; ${ $name_ref } = reverse ${ $name_ref }; } ``` If you forget to dereference a scalar reference, Perl will likely coerce the reference into a string value of the form `SCALAR(0x93339e8)` or a numeric value such as `0x93339e8` . This value indicates the type of reference (in this case, `SCALAR` ) and the location in memory of the reference (because that's an unambiguous design choice, not because you can do anything with the memory location itself). References Aren't Pointers Perl does not offer native access to memory locations. The address of the reference is a value used as an identifier. Unlike pointers in a language such as C, you cannot modify the address of a reference or treat it as an address into memory. These addresses are mostly unique because Perl may reuse storage locations as it reclaims unused memory. ### Array References Array references are useful in several circumstances: * To pass and return arrays from functions without list flattening * To create multi-dimensional data structures * To avoid unnecessary array copying * To hold anonymous data structures Use the reference operator to create a reference to a declared array: ``` my @cards = qw( K Q J 10 9 8 7 6 5 4 3 2 A ); my $cards_ref = \@cards; ``` Any modifications made through `$cards_ref` will modify `@cards` and vice versa. You may access the entire array as a whole with the `@` sigil, whether to flatten the array into a list (list context) or count its elements (scalar context): ``` my $card_count = @$cards_ref; my @card_copy = @$cards_ref; ``` Access individual elements with the dereferencing arrow ( `->` ): ``` my $first_card = $cards_ref->[0]; my $last_card = $cards_ref->[-1]; ``` The arrow is necessary to distinguish between a scalar named `$cards_ref` and an array named `@cards_ref` . Note the use of the scalar sigil (Variable Sigils) to access a single element. Doubling Sigils An alternate syntax prepends another scalar sigil to the array reference. It's shorter but uglier to write ``` my $first_card = $$cards_ref[0]; ``` . Use the curly-brace dereferencing syntax to slice (Array Slices) an array reference: ``` my @high_cards = @{ $cards_ref }[0 .. 2, -1]; ``` You may omit the curly braces, but their grouping often improves readability. To create an anonymous array, surround a list-producing expression with square brackets: ``` my $suits_ref = [qw( Monkeys Robots Dinos Cheese )]; ``` This array reference behaves the same as named array references, except that the anonymous array brackets always create a new reference. Taking a reference to a named array in its scope always refers to the same array. For example: push @meals, 'ice cream sundae'; ``` ... both `$sunday_ref` and `$monday_ref` now contain a dessert, while: push @meals, 'berry pie'; ``` ... neither `$sunday_ref` nor `$monday_ref` contains a dessert. Within the square braces used to create the anonymous array, list context flattens the `@meals` array into a list unconnected to `@meals` . ### Hash References Use the reference operator on a named hash to create a hash reference: ``` my %colors = ( blue => 'azul', gold => 'dorado', red => 'rojo', yellow => 'amarillo', purple => 'morado', ); my $colors_ref = \%colors; ``` Access the keys or values of the hash by prepending the reference with the hash sigil `%` : ``` my @english_colors = keys %$colors_ref; my @spanish_colors = values %$colors_ref; ``` Access individual values of the hash (to store, delete, check the existence of, or retrieve) by using the dereferencing arrow or double scalar sigils: ``` sub translate_to_spanish { my $color = shift; return $colors_ref->{$color}; # or return $$colors_ref{$color}; } ``` Use the array sigil ( `@` ) and disambiguation braces to slice a hash reference: ``` my @colors = qw( red blue green ); my @colores = @{ $colors_ref }{@colors}; ``` Create anonymous hashes in place with curly braces: ``` my $food_ref = { 'birthday cake' => 'la torta de cumpleaños', candy => 'dulces', cupcake => 'bizcochito', 'ice cream' => 'helado', }; ``` As with anonymous arrays, anonymous hashes create a new anonymous hash on every execution. Watch Those Braces! The common novice error of assigning an anonymous hash to a standard hash produces a warning about an odd number of elements in the hash. Use parentheses for a named hash and curly brackets for an anonymous hash. ### Function References Perl supports first-class functions; a function is a data type just as is an array or hash. In other words, Perl supports function references. This enables many advanced features (Closures). Create a function reference by using the reference operator and the function sigil ( `&` ) on the name of a function: ``` sub bake_cake { say 'Baking a wonderful cake!' }; my $cake_ref = \&bake_cake; ``` Without the function sigil ( `&` ), you will take a reference to the function's return value or values. Create anonymous functions with the bare `sub` keyword: ``` my $pie_ref = sub { say 'Making a delicious pie!' }; ``` The use of the `sub` builtin without a name compiles the function but does not register it with the current namespace. The only way to access this function is via the reference returned from `sub` . Invoke the function reference with the dereferencing arrow: ``` $cake_ref->(); $pie_ref->(); ``` Perl 4 Function Calls An alternate invocation syntax for function references uses the function sigil ( `&` ) instead of the dereferencing arrow. Avoid this `&$cupcake_ref` syntax; it has subtle implications for parsing and argument passing. Think of the empty parentheses as denoting an invocation dereferencing operation in the same way that square brackets indicate an indexed (array) lookup and curly brackets a keyed (hash) lookup. Pass arguments to the function within the parentheses: ``` $bake_something_ref->( 'cupcakes' ); ``` You may also use function references as methods with objects (Moose). This is useful when you've already looked up the method (Reflection): ``` my $clean = $robot_maid->can( 'cleanup' ); $robot_maid->$clean( $kitchen ); ``` ### Filehandle References The lexical filehandle form of `open` and `opendir` operate on filehandle references. Internally, these filehandles are objects of the class `IO::File` . You can call methods on them directly: ``` use autodie 'open'; open my $out_fh, '>', 'output_file.txt'; $out_fh->say( 'Have some text!' ); ``` Old code might `use IO::Handle;` . Older code may take references to typeglobs: ``` local *FH; open FH, "> $file" or die "Can't write '$file': $!"; my $fh = *FH; ``` This idiom predates the lexical filehandles introduced by Perl 5.6 in March 2000. You may still use the reference operator on typeglobs to take references to package-global filehandles such as `STDIN` , `STDOUT` , `STDERR` , or `DATA` —but these are all global names anyhow. As lexical filehandles respect explicit scoping, they allow you to manage the lifespan of filehandles as a feature of Perl's memory management. ### Reference Counts Perl uses a memory management technique known as reference counting. Every Perl value has a counter attached to it, internally. Perl increases this counter every time something takes a reference to the value, whether implicitly or explicitly. Perl decreases that counter every time a reference goes away. When the counter reaches zero, Perl can safely recycle that value. Consider the filehandle opened in this inner scope: ``` say 'file not open'; { open my $fh, '>', 'inner_scope.txt'; $fh->say( 'file open here' ); } say 'file closed here'; ``` Within the inner block in the example, there's one `$fh` . (Multiple lines in the source code mention it, but there's only one variable, the one named `$fh` .) `$fh` is only in scope in the block. Its value never leaves the block. When execution reaches the end of the block, Perl recycles the variable `$fh` and decreases the reference count of the filehandle referred to by `$fh` . The filehandle's reference count reaches zero, so Perl destroys the filehandle to reclaim memory. As part of the process, it calls `close()` on the filehandle implicitly. You don't have to understand the details of how all of this works. You only need to understand that your actions in taking references and passing them around affect how Perl manages memory (see Circular References). ### References and Functions When you use references as arguments to functions, document your intent carefully. Modifying the values of a reference from within a function may surprise the calling code, which never expected anything else to modify its data. To modify the contents of a reference without affecting the reference itself, copy its values to a new variable: ``` my @new_array = @{ $array_ref }; my %new_hash = %{ $hash_ref }; ``` This is only necessary in a few cases, but explicit cloning helps avoid nasty surprises for the calling code. If you use nested data structures or other complex references, consider the use of the core module `Storable` and its `dclone` (deep cloning) function. ### Postfix Dereferencing Perl 5.20 introduced and Perl 5.24 stabilized a feature called postfix dereferencing. Instead of using prefix or circumfix dereferencing notation, you can dereference a complex expression with a syntax that reads from left to right. For example, if you have an array reference, you can dereference the array with an array splat notation ( `@*` ): ``` my $recipients = [qw( Mother Father Partner Nephew Niece Neighbor )]; for my $recipient ($recipients->@*) { say "Need to find a gift for $recipient"; } ``` This simple example has little benefit in concision, but it's more useful with complex structures: ``` my %recipients = ( mandatory => [qw( Partner Nephew Niece )], optional => [qw( Mother Father )], mmmmmmaybe => [qw( Neighbor )], ); for my $recipient ($recipients{optional}->@*) { say "Probably should find a gift for $recipient"; } ``` ... or with references returned from function or method calls: ``` say "Have $200 to spend on " . join ', ', get_recipients_for_budget({ usd => 200 })->@*; ``` This operation imposes scalar context on the function or method. Hashes use a similar notation, with the `%*` hash sigil and splat: ``` my $holiday_starts = { Hannukah => '2020-12-10', Christmas => '2020-12-25', Kwanzaa => '2020-12-26', }; Again, you can dereference the return value of a function or method call in the same fashion: This postfix dereferencing syntax allows both array and hash slices: ``` my @pto_holidays = $holiday_starts->@{qw( Hannukah Kwanzaa )}; my @first_recipients = $recipients->@[0 .. 3]; ``` Scalars use the notation `->$*` : ``` my $not_a_constant = \"variable"; say $not_a_constant->$*; ``` This also works with functions or methods as you expect, but it provides no slice form. You may find it consistent to use only prefix, circumfix, or postfix dereferencing in a section of code. For more information, consult the "Postfix Dereference Syntax" section of `perldoc perlref` . ## Nested Data Structures Perl's aggregate data types—arrays and hashes—store scalars indexed by integer or string keys. Note the word scalar. If you try to store an array in an array, Perl's automatic list flattening will make everything into a single array: ``` my @counts = qw( eenie miney moe ); my @ducks = qw( huey dewey louie ); my @game = qw( duck duck grayduck ); my @famous_triplets = ( @counts, @ducks, @game ); ``` Perl's solution to this is references (References), which are special scalars that can refer to other variables (scalars, arrays, and hashes). You Nested data structures in Perl, such as an array of arrays or a hash of hashes, are possible through the use of references. Unfortunately, the reference syntax can be a little bit ugly. Use the reference operator, `\` , to produce a reference to a named variable: ``` my @famous_triplets = ( \@counts, \@ducks, \@game ); ``` ... or the anonymous reference declaration syntax to avoid the use of named variables: ``` my @famous_triplets = ( [qw( eenie miney moe )], [qw( huey dewey louie )], [qw( duck duck goose )], ); my %meals = ( breakfast => { entree => 'eggs', side => 'hash browns' }, lunch => { entree => 'panini', side => 'apple' }, dinner => { entree => 'steak', side => 'avocado salad' }, ); ``` Commas are Free Perl allows an optional trailing comma after the last element of a list. This makes it easy to add more elements in the future. Use Perl's reference syntax to access elements in nested data structures. The sigil denotes the amount of data to retrieve. The dereferencing arrow indicates that the value of one portion of the data structure is a reference: ``` my $last_nephew = $famous_triplets[1]->[2]; my $meal_side = $meals{breakfast}->{side}; ``` The only way to access elements in a nested data structure is through references, so the arrow in the previous examples is superfluous. You may omit it for clarity, except for invoking function references: ``` my $nephew = $famous_triplets[1][2]; my $meal = $meals{breakfast}{side}; $actions{generous}{buy_food}->( $nephew, $meal ); ``` Use disambiguation blocks to access components of nested data structures as if they were first-class arrays or hashes: ``` my $nephew_count = @{ $famous_triplets[1] }; my $dinner_courses = keys %{ $meals{dinner} }; ``` ... or to slice a nested data structure: ``` my ($entree, $side) = @{ $meals{breakfast} }{ qw( entree side ) }; ``` Whitespace helps, but does not entirely eliminate the noise of this construct. Sometimes a temporary variable provides more clarity: ``` my $meal_ref = $meals{breakfast}; my ($entree, $side) = @$meal_ref{qw( entree side )}; ``` ... or use `for` 's implicit aliasing to avoid the use of an intermediate reference (though note the lack of `my` ): ``` ($entree, $side) = @{ $_ }{qw( entree side )} for $meals{breakfast}; ``` `perldoc perldsc` , the data structures cookbook, gives copious examples of how to use Perl's various data structures. ### Autovivification When you attempt to write to a component of a nested data structure, Perl will create the path through the data structure to the destination as necessary: ``` my @aoaoaoa; $aoaoaoa[0][0][0][0] = 'nested deeply'; ``` After the second line of code, this array of arrays of arrays of arrays contains an array reference in an array reference in an array reference in an array reference. Each array reference contains one element. Similarly, when you ask Perl to treat an undefined value as if it were a hash reference, Perl will turn that undefined value into a hash reference: ``` my %hohoh; $hohoh{Robot}{Santa} = 'mostly harmful'; ``` This behavior is autovivification. While it reduces the initialization code of nested data structures, it cannot distinguish between the honest intent to create missing elements in nested data structures or a typo. You may wonder at the contradiction between taking advantage of autovivification while enabling `strict` ures. Is it more convenient to catch errors which change the behavior of your program at the expense of disabling error checks for a few well-encapsulated symbolic references? Is it more convenient to allow data structures to grow or safer to require a fixed size and an allowed set of keys? The answers depend on your project. During early development, allow yourself the freedom to experiment. While testing and deploying, consider an increase of strictness to prevent unwanted side effects. The `autovivification` pragma (Pragmas) from the CPAN lets you disable autovivification in a lexical scope for specific types of operations. Combined with the `strict` pragma, you can enable these behaviors where and as necessary. You can verify your expectations before dereferencing each level of a complex data structure, but the resulting code is often lengthy and tedious. It's better to avoid deeply nested data structures by revising your data model to provide better encapsulation. ### Debugging Nested Data Structures The complexity of Perl's dereferencing syntax combined with the potential for confusion with multiple levels of references can make debugging nested data structures difficult. The core module `Data::Dumper` converts values of arbitrary complexity into strings of Perl code, which helps visualize what you have: ``` use Data::Dumper; my $complex_structure = { numbers => [ 1 .. 3 ]; letters => [ 'a' .. 'c' ], objects => { breakfast => $continental, lunch => $late_tea, dinner => $banquet, }, }; print Dumper( $my_complex_structure ); ``` ... which might produce something like: ``` $VAR1 = { 'numbers' => [ 1, 2, 3 ], 'letters' => [ 'a', 'b', 'c' ], 'meals' => { 'dinner' => bless({...}, 'Dinner'), 'lunch' => bless({...}, 'Lunch'), 'breakfast' => bless({...}, 'Breakfast'), }, }; ``` Use this when you need to figure out what a data structure contains, what you should access, and what you accessed instead. As the elided example alludes, `Data::Dumper` can dump objects as well as function references (if you set ``` $Data::Dumper::Deparse ``` to a true value). While `Data::Dumper` is a core module and prints Perl code, its output is verbose. Some developers prefer the use of the `YAML::XS` or `JSON` modules for debugging. They do not produce Perl code, but their outputs can be much clearer to read and to understand. ### Circular References Perl's memory management system of reference counting (Reference Counts) has one drawback. Two references which point to each other, whether directly or indirectly, form a circular reference that Perl cannot destroy on its own. Consider a biological model, where each entity has two parents and zero or more children: Both `$alice` and `$robin` contain an array reference which contains `$cianne` . Because `$cianne` is a hash reference which contains `$alice` and `$robin` , Perl will never decrease the reference count of any of these three people to zero. It doesn't recognize that these circular references exist, and it can't manage the lifespan of these entities. Either break the reference count manually yourself (by clearing the children of `$alice` and `$robin` or the parents of `$cianne` ), or use weak references. A weak reference does not increase the reference count of its referent. Use the core module `Scalar::Util` 's `weaken()` function to weaken a reference: ``` use Scalar::Util 'weaken'; weaken( $cianne->{mother} ); weaken( $cianne->{father} ); ``` `$cianne` will retain usable references to `$alice` and `$robin` , but those weak references do not count toward the number of remaining references to the parents. If the reference count of `$alice` reaches zero, Perl's garbage collector will reclaim her record, even though `$cianne` has a weak reference to `$alice` . When `$alice` gets reclaimed, `$cianne` 's reference to `$alice` will be set to `undef` . Most data structures do not need weak references, but when they're necessary, they're invaluable. ### Alternatives to Nested Data Structures While Perl is content to process data structures nested as deeply as you can imagine, the human cost of understanding these data structures and their relationships—to say nothing of the complex syntax—is high. Beyond two or three levels of nesting, consider whether modeling various components of your system with classes and objects (Moose) will allow for clearer code. Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. Some people call Perl an "operator-oriented language". A Perl operator is a series of one or more symbols used as part of the syntax of a language. Each operator operates on zero or more operands. Think of an operator as a special sort of function the parser understands and its operands as arguments. You've seen how Perl manages context through its operators. To understand Perl fully, you must understand how operators interact with their operands. ## Operator Characteristics Every operator possesses several important characteristics which govern its behavior: the number of operands on which it operates, its relationship to other operators, the contexts it enforces, and the syntax it provides. `perldoc perlop` and `perldoc perlsyn` provide voluminous information about Perl's operators, but the docs assume you're already familiar with a few essential computer science concepts. Fortunately, you'll recognize these ideas from written language and elementary mathematics, even if you've never heard their complicated names before. ### Precedence The precedence of an operator governs when Perl should evaluate it in an expression. Perl evaluates the operator with the highest precedence first, then the next highest, all the way to the lowest precedence. Remember basic math? Multiply and divide before you add and subtract. That's precedence. Because the precedence of multiplication is higher than the precedence of addition, in Perl `7 + 7 * 10` evaluates to `77` , not `140` . Use grouping parentheses to force the evaluation of some operators before others. In `(7 + 7) * 10` , grouping the addition into a single unit forces its evaluation before the multiplication—though Perl wants to perform the multiplication first, it has to evaluate the grouped subexpression into a single value as the multiplication operator's left operand. The result is `140` . `perldoc perlop` contains a table of precedence. Skim it a few times, but don't bother memorizing it (almost no one does). Spend your time simplifying your code where you can. Then add parentheses where they clarify. In cases where two operators have the same precedence, other factors such as associativity (Associativity) and fixity (Fixity) break the tie. ### Associativity The associativity of an operator governs whether it evaluates from left to right or right to left. Addition is left associative, such that `2 + 3 + 4` evaluates `2 + 3` first, then adds `4` to the result, not that order of evaluation matters. Exponentiation is right associative, such that `2 ** 3 ** 4` evaluates `3 ** 4` first, then raises `2` to the 81st power. Use parentheses if you write code like this. If you memorize only the precedence and associativity of the common mathematical operators, you'll be fine. Simplify your code and you won't have to memorize other associativities. If you can't simplify your code (or if you're maintaining code and trying to understand it), use the core `B::Deparse` module to see exactly how Perl handles operator precedence and associativity. Run `perl -MO=Deparse,-p` on a snippet of code The `-p` flag adds extra grouping parentheses which often clarify evaluation order. Beware that Perl's optimizer will simplify mathematical operations using constant values. If you really need to deparse a complex expression, use named variables instead of constant values, as in `$x ** $y ** $z` . ### Arity The arity of an operator is the number of operands on which it operates. A nullary operator operates on zero operands. A unary operator operates on one operand. A binary operator operates on two operands. A trinary operator operates on three operands. A listary operator operates on a list of zero or more operands. Arithmetic operators are binary operators and are usually left associative. This has implications for tie-breaking evaluation order of operands with the same precedence. For example, `2 + 3 - 4` evaluates `2 + 3` first. Addition and subtraction have the same precedence, but they're left associative and binary, so the proper evaluation order applies the leftmost operator ( `+` ) to the leftmost two operands ( `2` and `3` ) with the leftmost operator ( `+` ), then applies the rightmost operator ( `-` ) to the result of the first operation and the rightmost operand ( `4` ). ### Fixity Perl novices often find confusion between the interaction of listary operators—especially function calls—and nested expressions. Where parentheses usually help, beware of the parsing complexity of: ``` # probably buggy code say ( 1 + 2 + 3 ) * 4; ``` ... which prints the value `6` and (probably) evaluates as a whole to `4` (the return value of `say` multiplied by `4` ). Perl's parser happily interprets the parentheses as postcircumfix operators denoting the arguments to `say` , not circumfix parentheses grouping an expression to change precedence. An operator's fixity is its position relative to its operands: * Infix operators appear between their operands. Most mathematical operators are infix operators, such as the multiplication operator in `$length * $width` . * Prefix operators precede their operands. Postfix operators follow their operands. These operators tend to be unary, such as mathematic negation ( `-$x` ), boolean negation ( `!$y` ), and postfix increment ( `$z++` ). * Circumfix operators surround their operands, as with the anonymous hash constructor ( `{ ... }` ) and quoting operators ( `qq[ ... ]` ). * Postcircumfix operators follow certain operands and surround others, as seen in hash and array element access ( `$hash{$x}` and `$array[$y]` ). ## Operator Types Perl's operators provide value contexts (Numeric, String, and Boolean Context) to their operands. To choose the appropriate operator, you must know the values of the operands you provide as well as the value you expect to receive. ### Numeric Operators Numeric operators impose numeric contexts on their operands. These operators are the standard arithmetic operators of addition ( `+` ), subtraction ( `-` ), multiplication ( `*` ), division ( `/` ), exponentiation ( `**` ), and modulo ( `%` ), their in-place variants ( `+=` , `-=` , `*=` , `/=` , `**=` , and `%=` ), and both postfix and prefix auto-decrement ( `--` ). The auto-increment operator has special string behavior (Special Operators). Several comparison operators impose numeric contexts upon their operands. These are numeric equality ( `==` ), numeric inequality ( `!=` ), greater than ( `>` ), less than ( `<` ), greater than or equal to ( `>=` ), less than or equal to ( `<=` ), and the sort comparison operator ( `<=>` ). ### String Operators String operators impose string contexts on their operands. These operators are positive and negative regular expression binding ( `=~` and `!~` , respectively), and concatenation ( `.` ). Several comparison operators impose string contexts upon their operands. These are string equality ( `eq` ), string inequality ( `ne` ), greater than ( `gt` ), less than ( `lt` ), greater than or equal to ( `ge` ), less than or equal to ( `le` ), and the string sort comparison operator ( `cmp` ). ### Logical Operators Logical operators impose a boolean context on their operands. These operators are `&&` , `and` , `||` , and `or` . These infix operators all exhibit short-circuiting behavior (Short Circuiting). The word forms have lower precedence than the punctuation forms. The defined-or operator, `//` , tests the definedness of its operand. Unlike `||` which tests the truth of its operand, `//` evaluates to a true value even if its operand evaluates to a numeric zero or the empty string. This is especially useful for setting default parameter values: ``` sub name_pet { my $name = shift // 'Fluffy'; ... } ``` The ternary conditional operator ( `?:` ) takes three operands. It evaluates the first in boolean context and evaluates to the second if the first is true and the third otherwise: ``` my $truthiness = $value ? 'true' : 'false'; ``` The prefix `!` and `not` operators return the logical opposites of the boolean values of their operands. `not` is a lower precedence version of `!` . The `xor` operator is an infix operator which evaluates to the exclusive-or of its operands. ### Bitwise Operators Bitwise operators treat their operands numerically at the bit level. These uncommon operators are left shift ( `<<` ), right shift ( `>>` ), bitwise and ( `&` ), bitwise or ( `|` ), and bitwise xor ( `^` ), as well as their in-place variants ( `<<=` , `>>=` , `&=` , `|=` , and `^=` ). ### Special Operators The auto-increment operator has special behavior. When used on a value with a numeric component (Cached Coercions), the operator increments that numeric component. If the value is obviously a string (if it has no numeric component), the operator increments the value's string component such that `a` becomes `b` , `zz` becomes `aaa` , and `a9` becomes `b0` . ``` my $num = 1; my $str = 'a'; $num++; $str++; is $num, 2, 'numeric autoincrement'; is $str, 'b', 'string autoincrement'; no warnings 'numeric'; $num += $str; $str++; is $num, 2, 'numeric addition with $str'; is $str, 1, '... gives $str a numeric part'; ``` The repetition operator ( `x` ) is an infix operator with complex behavior. When evaluated in list context with a list as its first operand, it evaluates to that list repeated the number of times specified by its second operand. When evaluated in list context with a scalar as its first operand, it produces a string consisting of the string value of its first operand concatenated to itself the number of times specified by its second operand. In scalar context, the operator repeats and concatenates a string: ``` my @scheherazade = ('nights') x 1001; my $calendar = 'nights' x 1001; my $cal_length = length $calendar; is @scheherazade, 1001, 'list repeated'; is $cal_length, 1001 * length 'nights', 'word repeated'; my @schenolist = 'nights' x 1001; my $calscalar = ('nights') x 1001; is @schenolist, 1, 'no lvalue list'; is length $calscalar, 1001 * length 'nights', 'word still repeated'; ``` The infix range operator ( `..` ) produces a list of items in list context: ``` my @cards = ( 2 .. 10, 'J', 'Q', 'K', 'A' ); ``` It can only produce simple, incrementing ranges of integers or strings. In boolean context, the range operator performs a flip-flop operation. This operator produces a false value until its left operand is true. That value stays true until the right operand is true, after which the value is false again until the left operand is true again. Imagine parsing the text of a formal letter with: ``` while (/Hello, $user/ .. /Sincerely,/) { say "> $_"; } ``` The comma operator ( `,` ) is an infix operator. In scalar context it evaluates its left operand then returns the value produced by evaluating its right operand. In list context, it evaluates both operands in left-to-right order. The fat comma operator ( `=>` ) also quotes any bareword used as its left operand (Hashes). The triple-dot or whatever operator stands in for a single statement. It is nullary and has neither precedence nor associativity. It parses, but when executed it throws an exception with the string `Unimplemented` . This makes a great placeholder in example code you don't expect anyone to execute: ``` sub some_example { # implement this yourself ... } ``` Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. A function (or subroutine) in Perl is a discrete, encapsulated unit of behavior. A program is a collection of little black boxes where the interaction of these functions governs the control flow of the program. A function may have a name. It may consume incoming information. It may produce outgoing information. Functions are a prime mechanism for organizing code into similar groups, identifying individual pieces by name, and providing reusable units of behavior. ## Declaring Functions Use the `sub` builtin to declare a function: Now you can invoke `greet_me()` from anywhere within your program. Just as you may declare a lexical variable but leave its value undefined, you may declare a function without defining it. A forward declaration tells Perl to record that a named function exists. You may define it later: `sub greet_sun;` ## Invoking Functions Use postfix (Fixity) parentheses to invoke a named function. Any arguments to the function may go within the parentheses: ``` greet_me( 'Jack', 'Tuxie', 'Brad' ); greet_me( 'Snowy' ); greet_me(); ``` While these parentheses are not strictly necessary for these examples—even with `strict` enabled—they provide clarity to human readers as well as Perl's parser. When in doubt, use them. Function arguments can be arbitrary expressions—including variables and function calls: ``` greet_me( $name ); greet_me( @authors ); greet_me( %editors ); greet_me( get_readers() ); ``` ... though Perl's default parameter handling sometimes surprises novices. ## Function Parameters A function receives its parameters in a single array, `@_` (The Default Array Variables). When you invoke a function, Perl flattens all provided arguments into a single list. The function must either unpack its parameters into variables or operate on `@_` directly: ``` sub greet_one { my ($name) = @_; say "Hello, $name!"; } sub greet_all { say "Hello, $_!" for @_; } ``` `@_` behaves as a normal array. Most Perl functions `shift` off parameters or use list assignment, but you may also access individual elements by index: ``` sub greet_one_shift { my $name = shift; say "Hello, $name!"; } sub greet_two_list_assignment { my ($hero, $sidekick) = @_; say "Well if it isn't $hero and $sidekick. Welcome!"; } sub greet_one_indexed { my $name = $_[0]; say "Hello, $name!"; # or, less clear say "Hello, $_[0]!"; } ``` You may also `unshift` , `push` , `pop` , `splice` , and use slices of `@_` . Remember that the array builtins use `@_` as the default operand within functions, so that `my $name = shift;` works. Take advantage of this idiom. To access a single scalar parameter from `@_` , use `shift` , an index of `@_` , or lvalue list context parentheses. Otherwise, Perl will happily evaluate `@_` in scalar context for you and assign the number of parameters passed: ``` sub bad_greet_one { my $name = @_; # buggy say "Hello, $name; you look numeric today!" } ``` List assignment of multiple parameters is often clearer than multiple lines of `shift` . Compare: ``` my $left_value = shift; my $operation = shift; my $right_value = shift; ``` ... to: ``` my ($left_value, $operation, $right_value) = @_; ``` The latter is simpler to read. As a side benefit, it has better runtime performance, though you're unlikely to notice. Occasionally you may see code which extracts parameters from `@_` and passes the rest to another function: ``` sub delegated_method { my $self = shift; say 'Calling delegated_method()' $self->delegate->delegated_method( @_ ); } ``` Use `shift` when your function needs only a single parameter. Use list assignment when accessing multiple parameters. ### Real Function Signatures Perl 5.20 added built-in function signatures as an experimental feature. "Experimental" means that they may change or even go away in future releases of Perl, so you need to enable them to signal that you accept the possibility of rewriting code. ``` use experimental 'signatures'; ``` With that disclaimer in place, you can now write: ``` sub greet_one($name) { say "Hello, $name!"; } ``` ... which is equivalent to writing: ``` sub greet_one { die "Too many arguments for subroutine" if @_ < 1; die "Too few arguments for subroutine" if @_ > 1; my $name = shift; say "Hello, $name!"; } ``` You can make `$name` an optional variable by assigning it a default value: ``` sub greet_one($name = 'Bruce') { say "Hello, $name!"; } ``` ... in which case writing `greet_one( 'Bruce' )` and `greet_one()` will both ignore Batman's crime-fighting identity. You may use aggregate arguments at the end of a signature: ``` sub greet_all($leader, @everyone) { say "Hello, $leader!"; say "Hi also, $_." for @everyone; } sub make_nested_hash($name, %pairs) { return { $name => \%pairs }; } ``` ... or indicate that a function expects no arguments: ``` sub no_gifts_please() { say 'I have too much stuff already.' } ``` ... which means that you'll get the ``` Too many arguments for subroutine ``` exception by calling that function with arguments. These experimental signatures have more features than discussed here. As you get beyond basic positional parameters, the possibility of incompatible changes in future versions of Perl increases, however. See `perldoc perlsub` 's "Signatures" section for more details, especially in newer versions of Perl. Signatures aren't your only options. Several CPAN distributions extend Perl's parameter handling with additional syntax and options. `Method::Signatures` works as far back as Perl 5.8. `Kavorka` works with Perl 5.14 and newer. Should You Use Signatures? Despite the experimental nature of function signatures—or the additional dependencies of the CPAN modules—all of these options can make your code a little shorter and a little clearer both to read and to write. By all means experiment with these options to find out what works best for you and your team. Even sticking with simple positional parameters can improve your work. ### Flattening List flattening into `@_` happens on the caller side of a function call. Passing a hash as an argument produces a list of key/value pairs: show_pets( %pet_names_and_types ); sub show_pets { my %pets = @_; while (my ($name, $type) = each %pets) { say "$name is a $type"; } } ``` When Perl flattens `%pet_names_and_types` into a list, the order of the key/value pairs from the hash will vary, but the list will always contain a key immediately followed by its value. Hash assignment inside `show_pets()` works the same way as the explicit assignment to `%pet_names_and_types` . This flattening is often useful, but beware of mixing scalars with flattened aggregates in parameter lists. To write a `show_pets_of_type()` function, where one parameter is the type of pet to display, pass that type as the first parameter (or use `pop` to remove it from the end of `@_` , if you like to confuse people): ``` sub show_pets_by_type { my ($type, %pets) = @_; while (my ($name, $species) = each %pets) { next unless $species eq $type; say "$name is a $species"; } } show_pets_by_type( 'dog', %pet_names_and_types ); show_pets_by_type( 'cat', %pet_names_and_types ); show_pets_by_type( 'moose', %pet_names_and_types ); ``` With experimental function signatures, you could write: ``` sub show_pets_by_type($type, %pets) { ... } ``` ### Slurping List assignment with an aggregate is always greedy, so assigning to `%pets` slurps all of the remaining values from `@_` . If the `$type` parameter came at the end of `@_` , Perl would warn about assigning an odd number of elements to the hash. You could work around that: ``` sub show_pets_by_type { my $type = pop; my %pets = @_; ... at the expense of clarity. The same principle applies when assigning to an array as a parameter. Use references (References) to avoid unwanted aggregate flattening. ### Aliasing `@_` contains a subtlety; it aliases function arguments. In other words, if you access `@_` directly, you can modify the arguments passed to the function: my $name = 'Orange'; modify_name( $name ); say $name; # prints egnarO ``` Modify an element of `@_` directly and you will modify the original argument. Be cautious and unpack `@_` rigorously—or document the modification carefully. ## Functions and Namespaces Every function has a containing namespace (Packages). Functions in an undeclared namespace—functions not declared within the scope of an explicit `package` statement—exist in the `main` namespace. You may also declare a function within another namespace by prefixing its name: ``` sub Extensions::Math::add { ... } ``` This will create the namespace as necessary and then declare the function within it. Remember that Perl packages are open for modification at any point—even while your program is running. Perl will issue a warning if you declare multiple functions with the same name in a single namespace. Refer to other functions within the same namespace with their short names. Use a fully-qualified name to invoke a function in another namespace: Extensions::Math::add( $scalar, $vector ); ``` Remember, functions are visible outside of their own namespaces through their fully-qualified names. Alternately, you may import names from other namespaces. Lexical Functions Perl 5.18 added an experimental feature to declare functions lexically. They're visible only within lexical scopes after declaration. See the "Lexical Subroutines" section of `perldoc perlsub` for more details. ### Importing When loading a module with the `use` builtin (Modules), Perl automatically calls a method named `import()` . Modules can provide their own `import()` method which makes some or all defined symbols available to the calling package. Any arguments after the name of the module in the `use` statement get passed to the module's `import()` method. Thus: `use strict;` ... loads the strict.pm module and calls `strict->import()` with no arguments, while: ``` use strict 'refs'; use strict qw( subs vars ); ``` ... loads the strict.pm module, calls ``` strict->import( 'refs' ) ``` , then calls ``` strict->import( 'subs', vars' ) ``` . `use` has special behavior with regard to `import()` , but you may call `import()` directly. The `use` example is equivalent to: ``` BEGIN { require strict; strict->import( 'refs' ); strict->import( qw( subs vars ) ); } ``` The `use` builtin adds an implicit `BEGIN` block around these statements so that the `import()` call happens immediately after the parser has compiled the entire `use` statement. This ensures that the parser knows about any symbols imported by `strict` before it compiles the rest of the program. Otherwise, any functions imported from other modules but not declared in the current file would look like barewords, and would violate `strict` , for example. Of course, `strict` is a pragma (Pragmas), so it has other effects. ## Reporting Errors Use the `caller` builtin to inspect a function's calling context. When passed no arguments, `caller` returns a list containing the name of the calling package, the name of the file containing the call, and the line number of the file on which the call occurred: main(); sub main { show_call_information(); } sub show_call_information { my ($package, $file, $line) = caller(); say "Called from $package in $file:$line"; } ``` The full call chain is available for inspection. Pass a single integer argument n to `caller()` to inspect the caller of the caller of the caller n times back. Within ``` show_call_information() ``` , `caller(0)` returns information about the call from `main()` . `caller(1)` returns information about the call from the start of the program. This optional argument also tells `caller` to provide additional return values, including the name of the function and the context of the call: ``` sub show_call_information { my ($package, $file, $line, $func) = caller(0); say "Called $func from $package in $file:$line"; } ``` The standard `Carp` module uses `caller` to enhance error and warning messages. When used in place of `die` in library code, `croak()` throws an exception from the point of view of its caller. `carp()` reports a warning from the file and line number of its caller (Producing Warnings). Use `caller` (or `Carp` ) when validating parameters or preconditions of a function to indicate that whatever called the function did so erroneously. ### Validating Arguments While Perl does its best to do what you mean, it offers few native ways to test the validity of arguments provided to a function. Evaluate `@_` in scalar context to check that the number of parameters passed to a function is correct: ``` sub add_numbers { croak 'Expected two numbers, received: ' . @_ unless @_ == 2; This validation reports any parameter count error from the point of view of its caller, thanks to the use of `croak` . Type checking is more difficult, because of Perl's operator-oriented type conversions (Context). If you want additional safety of function parameters, see CPAN modules such as `Params::Validate` . ## Advanced Functions Functions are the foundation of many advanced Perl features. ### Context Awareness Perl's builtins know whether you've invoked them in void, scalar, or list context. So too can your functions. The `wantarray` builtin returns `undef` to signify void context, a false value to signify scalar context, and a true value to signify list context. Yes, it's misnamed; see `perldoc -f wantarray` for proof. ``` sub context_sensitive { my $context = wantarray(); return qw( List context ) if $context; say 'Void context' unless defined $context; return 'Scalar context' unless $context; } context_sensitive(); say my $scalar = context_sensitive(); say context_sensitive(); ``` This can be useful for functions which might produce expensive return values to avoid doing so in void context. Some idiomatic functions return a list in list context and the first element of the list or an array reference in scalar context. However, there exists no single best recommendation for the use of `wantarray` . Sometimes it's clearer to write separate and unambiguous functions, such as `get_all_toppings()` and `get_next_topping()` . Putting it in Context Robin Houston's `Want` and Damian Conway's `Contextual::Return` distributions from the CPAN offer many possibilities for writing powerful context-aware interfaces. ### Recursion Suppose you want to find an element in a sorted array. You could iterate through every element of the array individually, looking for the target, but on average, you'll have to examine half of the elements of the array. Another approach is to halve the array, pick the element at the midpoint, compare, then repeat with either the lower or upper half. Divide and conquer. When you run out of elements to inspect or find the element, stop. An automated test for this technique could be: my @elements = ( 1, 5, 6, 19, 48, 77, 997, 1025, 7777, 8192, 9999 ); ok elem_exists( 1, @elements ), 'found first element in array'; ok elem_exists( 9999, @elements ), 'found last element in array'; ok ! elem_exists( 998, @elements ), 'did not find element not in array'; ok ! elem_exists( -1, @elements ), 'did not find element not in array'; ok ! elem_exists( 10000, @elements ), 'did not find element not in array'; ok elem_exists( 77, @elements ), 'found midpoint element'; ok elem_exists( 48, @elements ), 'found end of lower half element'; ok elem_exists( 997, @elements ), 'found start of upper half element'; Recursion is a deceptively simple concept. Every call to a function in Perl creates a new call frame, an data structure internal to Perl itself which represents the fact that you've called a function. This call frame includes the lexical environment of the function's current invocation—the values of all lexical variables within the function as invoked. Because the storage of the values of the lexical variables is separate from the function itself, you can have multiple calls to a function active at the same time. A function can even call itself, or recur. To make the previous test pass, write the recursive function `elem_exists()` : # break recursion with no elements to search return unless @array; # bias down with odd number of elements my $midpoint = int( (@array / 2) - 0.5 ); my $miditem = $array[ $midpoint ]; # return true if found return 1 if $item == $miditem; # return false with only one element return if @array == 1; Keep in mind that the arguments to the function will be different for every call, otherwise the function would always behave the same way (it would continue recursing until the program crashes). That's why the termination condition is so important. Every recursive program can be written without recursion, but this divide-and-conquer approach is an effective way to manage many similar types of problems. For more information about recursion, iteration, and advanced function use in Perl the free book Higher Order Perl http://hop.perl.plover.com/ is an excellent reference. ### Lexicals Every invocation of a function creates its own instance of a lexical scope represented internally by a call frame. Even though the declaration of `elem_exists()` creates a single scope for the lexicals `$item` , `@array` , `$midpoint` , and `$miditem` , every call to `elem_exists()` —even recursively—stores the values of those lexicals separately. Not only can `elem_exists()` call itself, but the lexical variables of each invocation are safe and separate: ``` use Carp 'cluck'; cluck "[$item] (@array)"; ... } ``` ### Tail Calls One drawback of recursion is that it's easy to write a function which calls itself infinitely. `elem_exists()` function has several `return` statements for this reason. Perl offers a helpful ``` Deep recursion on subroutine ``` warning when it suspects runaway recursion. The limit of 100 recursive calls is arbitrary, but often useful. Disable this warning with ``` no warnings 'recursion' ``` . Because each call to a function requires a new call frame and lexical storage space, highly-recursive code can use more memory than iterative code. Tail call elimination can help. A tail call is a call to a function which directly returns that function's results. These recursive calls to `elem_exists()` : ... are candidates for tail call elimination. This optimization would avoid returning to the current call and then returning to the parent call. Instead, it returns to the parent call directly. Perl does not eliminate tail calls automatically, but you can get the same effect by using a special form of the `goto` builtin. Unlike the form which often produces spaghetti code, the `goto` function form replaces the current function call with a call to another function. You may use a function by name or by reference. Manipulate `@_` to modify the arguments passed to the replacement function: ``` # split the array down and recurse if ($item < $miditem) { @_ = ($item, @array[0 .. $midpoint]); goto &elem_exists; } # split the array up and recurse else { @_ = ($item, @array[$midpoint + 1 .. $#array] ); goto &elem_exists; } ``` Sometimes optimizations are ugly, but if the alternative is highly recursive code which runs out of memory, embrace the ugly and rejoice in the practical. ## Pitfalls and Misfeatures Perl still supports old-style invocations of functions, carried over from ancient versions of Perl. Previous versions of Perl required you to invoke functions with a leading ampersand ( `&` ) character: ``` # outdated style; avoid my $result = &calculate_result( 52 ); # very outdated; truly avoid my $result = do &calculate_result( 42 ); ``` While the vestigial syntax is visual clutter, the leading ampersand form has other surprising behaviors. First, it disables any prototype checking. Second, it implicitly passes the contents of `@_` unmodified, unless you've explicitly passed arguments yourself. That unfortunate behavior can be confusing invisible action at a distance. A final pitfall comes from leaving the parentheses off of function calls. The Perl parser uses several heuristics to resolve ambiguous barewords and the number of parameters passed to a function. Heuristics can be wrong: ``` # warning; contains a subtle bug ok elem_exists 1, @elements, 'found first element'; ``` The call to `elem_exists()` will gobble up the test description intended as the second argument to `ok()` . Because `elem_exists()` uses a slurpy second parameter, this may go unnoticed until Perl produces warnings about comparing a non-number (the test description, which it cannot convert into a number) with the element in the array. While extraneous parentheses can hamper readability, thoughtful use of parentheses can clarify code to readers and to Perl itself. ## Scope Everything with a name in Perl (a variable, a function, a filehandle, a class) has a scope. This scope governs the lifespan and visibility of these entities. Scoping helps to enforce encapsulation—keeping related concepts together and preventing their details from leaking. ### Lexical Scope Lexical scope is the scope apparent to the readers of a program. Any block delimited by curly braces creates a new scope: a bare block, the block of a loop construct, the block of a `sub` declaration, an `eval` block, a `package` block, or any other non-quoting block. The Perl compiler resolves this scope during compilation. Lexical scope describes the visibility of variables declared with `my` —lexical variables. A lexical variable declared in one scope is visible in that scope and any scopes nested within it, but is invisible to sibling or outer scopes: ``` # outer lexical scope { package Robot::Butler # inner lexical scope my $battery_level; sub tidy_room { # further inner lexical scope my $timer; do { # innermost lexical scope my $dustpan; ... } while (@_); # sibling inner lexical scope for (@_) { # separate innermost scope my $polish_cloth; ... } } } ``` ... `$battery_level` is visible in all four scopes. `$timer` is visible in the method, the `do` block, and the `for` loop. `$dustpan` is visible only in the `do` block and `$polish_cloth` within the `for` loop. Declaring a lexical in an inner scope with the same name as a lexical in an outer scope hides, or shadows, the outer lexical within the inner scope. For example: ``` my $name = 'Jacob'; { my $name = 'Edward'; say $name; } say $name; ``` The silly lexical shadowing example program prints `Edward` and then `Jacob` (don't worry; they're family members, not vampires) because the lexical in the nested scope hides the lexical in the outer scope. Shadowing a lexical is a feature of encapsulation. Declaring multiple variables with the same name and type in the same lexical scope produces a warning message. In real code with larger scopes, this shadowing behavior is often desirable—it's easier to understand code when a lexical is in scope only for a couple of dozen lines. Lexical shadowing can happen by accident, though. Limit the scope of variables and the nesting of scopes to lessen your risk. Some lexical declarations have subtleties, such as a lexical variable used as the iterator variable of a `for` loop. Its declaration occurs outside of the block, but its scope is that within the loop block: ``` my $cat = 'Brad'; for my $cat (qw( <NAME> <NAME> )) { say "Inner cat is $cat"; } say "Outer cat is $cat"; ``` Functions—named and anonymous—provide lexical scoping to their bodies. This enables closures (Closures). ### Our Scope Within a scope you may declare an alias to a package variable with the `our` builtin. Like `my` , `our` enforces lexical scoping of the alias. The fully-qualified name is available everywhere, but the lexical alias is visible only within its scope. `our` is most useful with package global variables such as `$VERSION` and `$AUTOLOAD` . You get a little bit of typo detection (declaring a package global with `our` satisfies the `strict` pragma's `vars` rule), but you still have to deal with a global variable. ### Dynamic Scope Dynamic scope resembles lexical scope in its visibility rules, but instead of looking outward in compile-time scopes, lookup traverses backwards through all of the function calls you've made to reach the current code. Dynamic scope applies only to global and package global variables (as lexicals aren't visible outside their scopes). While a package global variable may be visible within all scopes, its value may change depending on `local` ization and assignment: ``` our $scope; sub inner { say $scope; } sub main { say $scope; local $scope = 'main() scope'; middle(); } sub middle { say $scope; inner(); } $scope = 'outer scope'; main(); say $scope; ``` The program begins by declaring an `our` variable, `$scope` , as well as three functions. It ends by assigning to `$scope` and calling `main()` . Within `main()` , the program prints `$scope` 's current value, `outer scope` , then `local` izes the variable. This changes the visibility of the symbol within the current lexical scope as well as in any functions called from the current lexical scope; that as well as condition is what dynamic scoping does. Thus, `$scope` contains `main() scope` within the body of both `middle()` and `inner()` . After `main()` returns, when control flow reaches the end of its block, Perl restores the original value of the `local` ized `$scope` . The final `say` prints `outer scope` once again. Perl also uses different storage mechanisms for package variables and lexical variables. Every scope which contains lexical variables uses a data structure called a lexical pad or lexpad to store the values for its enclosed lexical variables. Every time control flow enters one of these scopes, Perl creates another lexpad to contain the values of the lexical variables for that particular call. This makes functions work correctly, especially recursive functions (Recursion). Each package has a single symbol table which holds package variables and well as named functions. Importing (Importing) works by inspecting and manipulating this symbol table. So does `local` . This is why you may only `local` ize global and package global variables—never lexical variables. `local` is most often useful with magic variables. For example, `$/` , the input record separator, governs how much data a `readline` operation will read from a filehandle. `$!` , the system error variable, contains error details for the most recent system call. `$@` , the Perl `eval` error variable, contains any error from the most recent `eval` operation. `$|` , the autoflush variable, governs whether Perl will flush the currently `select` ed filehandle after every write operation. `local` izing these in the narrowest possible scope limits the effect of your changes. This can prevent strange behavior in other parts of your code. ### State Scope Perl's `state` keyword allows you to declare a lexical which has a one-time initialization as well as value persistence: say counter(); say counter(); say counter(); ``` On the first call to `counter` , Perl initializes `$count` . On subsequent calls, `$count` retains its previous value. This program prints `1` , `2` , and `3` . Change `state` to `my` and the program will print `1` , `1` , and `1` . You may use an expression to set a `state` variable's initial value: say counter(2); say counter(4); say counter(6); ``` Even though a simple reading of the code may suggest that the output should be `2` , `4` , and `6` , the output is actually `2` , `3` , and `4` . The first call to the sub `counter` sets the `$count` variable. Subsequent calls will not change its value. `state` can be useful for establishing a default value or preparing a cache, but be sure to understand its initialization behavior if you use it: ``` sub counter { state $count = shift; say 'Second arg is: ', shift; return $count++; } The counter for this program prints `2` , `3` , and `4` as expected, but the values of the intended second arguments to the `counter()` calls are `two` , `4` , and `6` —because the `shift` of the first argument only happens in the first call to `counter()` . Either change the API to prevent this mistake, or guard against it with: ``` sub counter { my ($initial_value, $text) = @_; state $count = $initial_value; say "Second arg is: $text"; return $count++; } ## Anonymous Functions An anonymous function is a function without a name. It behaves exactly like a named function—you can invoke it, pass it arguments, return values from it, and take references to it. Yet you can only access an anonymous function by reference (Function References), not by name. A Perl idiom known as a dispatch table uses hashes to associate input with behavior: ``` my %dispatch = ( plus => \&add_two_numbers, minus => \&subtract_two_numbers, times => \&multiply_two_numbers, ); sub add_two_numbers { $_[0] + $_[1] } sub subtract_two_numbers { $_[0] - $_[1] } sub multiply_two_numbers { $_[0] * $_[1] } sub dispatch { my ($left, $op, $right) = @_; return unless exists $dispatch{ $op }; return $dispatch{ $op }->( $left, $right ); } ``` The `dispatch()` function takes arguments of the form `(2, 'times', 2)` , evaluates the operation, and returns the result. A trivial calculator application could use `dispatch` to figure out which calculation to perform based on user input. ### Declaring Anonymous Functions The `sub` builtin used without a name creates and returns an anonymous function. Use this function reference where you'd use a reference to a named function, such as to declare the dispatch table's functions in place: ``` my %dispatch = ( plus => sub { $_[0] + $_[1] }, minus => sub { $_[0] - $_[1] }, times => sub { $_[0] * $_[1] }, dividedby => sub { $_[0] / $_[1] }, raisedto => sub { $_[0] ** $_[1] }, ); ``` Defensive Dispatch Only those functions within this dispatch table are available for users to call. If your dispatch function used a user-provided string as the literal name of functions, a malicious user could call any function anywhere by passing a fully-qualified name such as ``` 'Internal::Functions::malicious_function' ``` . You may also see anonymous functions passed as function arguments: ``` sub invoke_anon_function { my $func = shift; return $func->( @_ ); } sub named_func { say 'I am a named function!'; } invoke_anon_function( \&named_func ); invoke_anon_function( sub { say 'Who am I?' } ); ``` ### Anonymous Function Names Use introspection to determine whether a function is named or anonymous, whether through `caller()` or the CPAN module `Sub::Identify` 's `sub_name()` function: ``` package ShowCaller; sub show_caller { my ($package, $file, $line, $sub) = caller(1); say "Called from $sub in $package:$file:$line"; } sub main { my $anon_sub = sub { show_caller() }; show_caller(); $anon_sub->(); } main(); ``` The result may be surprising: ``` Called from ShowCaller::main in ShowCaller:anoncaller.pl:20 Called from ShowCaller::__ANON__ in ShowCaller:anoncaller.pl:17 ``` The `__ANON__` in the second line of output demonstrates that the anonymous function has no name that Perl can identify. The CPAN module `Sub::Name` 's `subname()` function allows you to attach names to anonymous functions: ``` use Sub::Name; use Sub::Identify 'sub_name'; my $anon = sub {}; say sub_name( $anon ); my $named = subname( 'pseudo-anonymous', $anon ); say sub_name( $named ); say sub_name( $anon ); say sub_name( sub {} ); ``` This program produces: ``` __ANON__ pseudo-anonymous pseudo-anonymous __ANON__ ``` Be aware that both references refer to the same underlying anonymous function. Using `subname()` on one reference will change that underlying function; all other references to that function will see the new name. ### Implicit Anonymous Functions Perl allows you to declare anonymous functions as function arguments without using the `sub` keyword. Though this feature exists nominally to enable programmers to write their own syntax such as that for `map` and `eval` (Prototypes), you can use it for other things, such as to write delayed functions that don't look like functions. Consider the CPAN module `Test::Fatal` , which takes an anonymous function as the first argument to its `exception()` function: ``` use Test::More; use Test::Fatal; my $croaker = exception { die 'I croak!' }; my $liver = exception { 1 + 1 }; like $croaker, qr/I croak/, 'die() should croak'; is $liver, undef, 'addition should live'; You might rewrite this more verbosely as: ``` my $croaker = exception( sub { die 'I croak!' } ); my $liver = exception( sub { 1 + 1 } ); ``` ... or to pass named functions by reference: ``` sub croaker { die 'I croak!' } sub liver { 1 + 1 } my $croaker = exception \&croaker; my $liver = exception \&liver; like $croaker, qr/I croak/, 'die() should die'; is $liver, undef, 'addition should live'; ``` ... but you may not pass them as scalar references: ``` my $croak_ref = \&croaker; my $live_ref = \&liver; # BUGGY: does not work my $croaker = exception $croak_ref; my $liver = exception $live_ref; ``` ... because the prototype changes the way the Perl parser interprets this code. It cannot determine with 100% clarity what `$croaker` and `$liver` will contain, and so will throw an exception. ``` Type of arg 1 to Test::Fatal::exception must be block or sub {} (not private variable) ``` A function which takes an anonymous function as the first of multiple arguments cannot have a trailing comma after the function block: ``` use Test::More; use Test::Fatal 'dies_ok'; dies_ok { die 'This is my boomstick!' } 'No movie references here'; ``` This is an occasionally confusing wart on otherwise helpful syntax, courtesy of a quirk of the Perl parser. The syntactic clarity available by promoting bare blocks to anonymous functions can be helpful, but use it sparingly and document the API with care. ## Closures The computer science term higher order functions refers to functions which manipulate other functions. Every time control flow enters a function, that function gets a new environment representing that invocation's lexical scope (Scope). That applies equally well to anonymous functions (Anonymous Functions). The implication is powerful, and closures show off this power. ### Creating Closures A closure is a function that uses lexical variables from an outer scope. You've probably already created and used closures without realizing it: ``` use Modern::Perl '2015'; my $filename = shift @ARGV; sub get_filename { return $filename } ``` If this code seems straightforward to you, good! Of course the `get_filename()` function can see the `$filename` lexical. That's how scope works! Suppose you want to iterate over a list of items without managing the iterator yourself. You can create a function which returns a function that, when invoked, will return the next item in the iteration: ``` sub make_iterator { my @items = @_; my $count = 0; return sub { return if $count == @items; return $items[ $count++ ]; } } my $cousins = make_iterator(qw( <NAME> <NAME> <NAME> Alex )); say $cousins->() for 1 .. 6; ``` Even though `make_iterator()` has returned, the anonymous function stored in `$cousins` has closed over the values of these variables as they existed within the invocation of `make_iterator()` —and their values persist (Reference Counts). Because invoking `make_iterator()` creates a separate lexical environment, the anonymous sub it creates and returns closes over a unique lexical environment for each invocation: ``` my $aunts = make_iterator(qw( <NAME> Sylvia <NAME> )); say $cousins->(); say $aunts->(); ``` Because `make_iterator()` does not return these lexicals by value or by reference, only the closure can access them. They're encapsulated as effectively as any other lexical is, although any code which shares a lexical environment can access these values. This idiom provides better encapsulation of what would otherwise be a file or package global variable: ``` { my $private_variable; sub set_private { $private_variable = shift } sub get_private { $private_variable } } ``` Named functions have package global scope, thus you cannot nest named functions. Any lexical variables shared between nested functions will go unshared when the outer function destroys its first lexical environment. Perl will warn you when this happens. Invasion of Privacy The CPAN module `PadWalker` lets you violate lexical encapsulation, but anyone who uses it gets to fix any bugs that result. ### Uses of Closures Iterating over a fixed-sized list with a closure is interesting, but closures can do much more, such as iterating over a list which is too expensive to calculate or too large to maintain in memory all at once. Consider a function to create the Fibonacci series as you need its elements (probably so you can check the output of your Haskell homework). Instead of recalculating the series recursively, use a cache and lazily create the elements you need: ``` sub gen_fib { my @fibs = (0, 1); if ($item >= @fibs) { for my $calc (@fibs .. $item) { $fibs[$calc] = $fibs[$calc - 2] + $fibs[$calc - 1]; } } return $fibs[$item]; } } # calculate 42nd Fibonacci number my $fib = gen_fib(); say $fib->( 42 ); ``` Every call to the function returned by `gen_fib()` takes one argument, the nth element of the Fibonacci series. The function generates and caches all preceding values in the series as necessary, and returns the requested element. Here's where closures and first class functions get interesting. This code does two things; there's a pattern specific to caching intertwined with the numeric series. What happens if you extract the cache-specific code (initialize a cache, execute custom code to populate cache elements, and return the calculated or cached value) to a function ? ``` sub gen_caching_closure { my ($calc_element, @cache) = @_; $calc_element->($item, \@cache) unless $item < @cache; return $cache[$item]; }; } sub gen_fib { my @fibs = (0, 1, 1); return gen_caching_closure( sub { my ($item, $fibs) = @_; for my $calc ((@$fibs - 1) .. $item) { $fibs->[$calc] = $fibs->[$calc - 2] + $fibs->[$calc - 1]; } }, @fibs ); } ``` The program behaves as it did before, but now function references and closures separate the cache initialization behavior from the calculation of the next number in the Fibonacci series. Customizing the behavior of code—in this case, —by passing in a function allows tremendous flexibility and can clean up your code. Fold, Apply, and Filter The builtins `map` , `grep` , and `sort` are themselves higher-order functions. ### Closures and Partial Application Closures can also remove unwanted genericity. Consider the case of a function which takes several parameters: ``` sub make_sundae { my %args = @_; my $ice_cream = get_ice_cream( $args{ice_cream} ); my $banana = get_banana( $args{banana} ); my $syrup = get_syrup( $args{syrup} ); ... } ``` Myriad customization possibilities might work very well in a full-sized ice cream store, but for an ice cream cart where you only serve French vanilla ice cream on Cavendish bananas, every call to `make_sundae()` passes arguments that never change. Partial application allows you to bind some of the arguments to a function now so that you can provide the others later. Wrap the function you intend to call in a closure and pass the bound arguments. For your ice cream cart: ``` my $make_cart_sundae = sub { return make_sundae( @_, ice_cream => 'French Vanilla', banana => 'Cavendish', ); }; ``` Now whenever you process an order, invoke the function reference in `$make_cart_sundae` and pass only the interesting arguments. You'll never forget the invariants or pass them incorrectly. You can even use `Sub::Install` from the CPAN to import `$make_cart_sundae` function into another namespace. This is only the start of what you can do with higher order functions. <NAME>'s Higher Order Perl is the canonical reference on first-class functions and closures in Perl. Read it online at http://hop.perl.plover.com/. ## State versus Closures Closures (Closures) use lexical scope (Scope) to control access to lexical variables—even with named functions: ``` { my $safety = 0; sub enable_safety { $safety = 1 } sub disable_safety { $safety = 0 } sub do_something_awesome { return if $safety; ... } } ``` All three functions encapsulate that shared state without exposing the lexical variable outside of their shared scope. This idiom works well for cases where multiple functions access that lexical, but it's clunky when only one function does. Suppose every hundredth ice cream parlor customer gets free sprinkles: ``` my $cust_count = 0; sub serve_customer { $cust_count++; my $order = shift; add_sprinkles($order) if $cust_count % 100 == 0; ... } ``` This approach works, but creating a new outer lexical scope for a single function is a little bit noisy. The `state` builtin allows you to declare a lexically scoped variable with a value that persists between invocations: ``` sub serve_customer { state $cust_count = 0; $cust_count++; my $order = shift; add_sprinkles($order) if ($cust_count % 100 == 0); `state` also works within anonymous functions: ``` sub make_counter { return sub { state $count = 0; return $count++; } } ``` ... though there are few obvious benefits to this approach. ## State versus Pseudo-State In old versions of Perl, a named function could close over its previous lexical scope by abusing a quirk of implementation. Using a postfix conditional which evaluates to false with a `my` declaration avoided reinitializing a lexical variable to `undef` or its initialized value. Now any use of a postfix conditional expression modifying a lexical variable declaration produces a deprecation warning. It's too easy to write inadvertently buggy code with this technique; use `state` instead where available, or a true closure otherwise. Rewrite this idiom when you encounter it: ``` sub inadvertent_state { # my $counter = 1 if 0; # DEPRECATED; don't use state $counter = 1; # prefer You may only initialize a state variable with a scalar value. If you need to keep track of an aggregate, use a hash or array reference (References). ## Attributes Named entities in Perl—variables and functions—can have additional metadata attached in the form of attributes. These attributes are arbitrary names and values used with certain types of metaprogramming (Code Generation). Attribute declaration syntax is awkward, and using attributes effectively is more art than science. Most programs never use them, but when used well they offer clarity and maintenance benefits. A simple attribute is a colon-preceded identifier attached to a declaration: ``` my $fortress :hidden; sub erupt_volcano :ScienceProject { ... } ``` When Perl parses these declarations, it invokes attribute handlers named `hidden` and `ScienceProject` , if they exist for the appropriate types (scalars and functions, respectively). These handlers can do anything. If the appropriate handlers do not exist, Perl will throw a compile-time exception. Attributes may include a list of parameters. Perl treats these parameters as lists of constant strings. The `Test::Class` module from the CPAN uses such parametric arguments to good effect: ``` sub setup_tests :Test(setup) { ... } sub test_monkey_creation :Test(10) { ... } sub shutdown_tests :Test(teardown) { ... } ``` The `Test` attribute identifies methods which include test assertions and optionally identifies the number of assertions the method intends to run. While introspection (Reflection) of these classes could discover the appropriate test methods, given well-designed solid heuristics, the `:Test` attribute is unambiguous. `Test::Class` provides attribute handlers which keep track of these methods. When the class has finished parsing, `Test::Class` can loop through the list of test methods and run them. The `setup` and `teardown` parameters allow test classes to define their own support methods without worrying about conflicts with other such methods in other classes. This separates the idea of what this class must do from how other classes do their work. Otherwise a test class might have only one method named `setup` and one named `teardown` and would have to do everything there, then call the parent methods, and so on. ### Drawbacks of Attributes Attributes have their drawbacks. The canonical pragma for working with attributes (the `attributes` pragma) has listed its interface as experimental for many years, and for good reason. <NAME>'s core module `Attribute::Handlers` is much easier to use, and <NAME>'s `Attribute::Lexical` is a newer approach. Prefer either to `attributes` whenever possible. The worst feature of attributes is that they make it easy to warp the syntax of Perl in unpredictable ways. You may not be able to predict what code with attributes will do. Good documentation helps, but if an innocent-looking declaration on a lexical variable stores a reference to that variable somewhere, your expectations of its lifespan may be wrong. Likewise, a handler may wrap a function in another function and replace it in the symbol table without your knowledge—consider a `:memoize` attribute which automatically invokes the core `Memoize` module. Attributes can help you to solve difficult problems or to make an API much easier to use. When used properly, they're powerful—but most programs never need them. ## AUTOLOAD Perl does not require you to declare every function before you call it. Perl will happily attempt to call a function even if it doesn't exist. Consider the program: ``` use Modern::Perl; bake_pie( filling => 'apple' ); ``` When you run it, Perl will throw an exception due to the call to the undefined function `bake_pie()` . Now add a function called `AUTOLOAD()` : `sub AUTOLOAD {}` When you run the program now, nothing obvious will happen. Perl will call a function named `AUTOLOAD()` in a package—if it exists—whenever normal dispatch fails. Change the `AUTOLOAD()` to emit a message to demonstrate that it gets called: ``` sub AUTOLOAD { say 'In AUTOLOAD()!' } ``` The `AUTOLOAD()` function receives the arguments passed to the undefined function in `@_` and the fully-qualified name of the undefined function in the package global `$AUTOLOAD` (here, `main::bake_pie` ): ``` sub AUTOLOAD { our $AUTOLOAD; # pretty-print the arguments local $" = ', '; say "In AUTOLOAD(@_) for $AUTOLOAD!" } ``` Extract the method name with a regular expression (Regular Expressions and Matching): ``` sub AUTOLOAD { my ($name) = our $AUTOLOAD =~ /::(\w+)$/; # pretty-print the arguments local $" = ', '; say "In AUTOLOAD(@_) for $name!" } ``` Whatever `AUTOLOAD()` returns, the original call receives: ``` say secret_tangent( -1 ); sub AUTOLOAD { return 'mu' } ``` So far, these examples have merely intercepted calls to undefined functions. You have other options. ### Redispatching Methods in AUTOLOAD() A common pattern in OO programming (Moose) is to delegate or proxy certain methods from one object to another. A logging proxy can help with debugging: ``` package Proxy::Log; # constructor blesses reference to a scalar sub AUTOLOAD { my ($name) = our $AUTOLOAD =~ /::(\w+)$/; Log::method_call( $name, @_ ); my $self = shift; return $$self->$name( @_ ); } ``` This `AUTOLOAD()` extracts the name of the undefined method. Then it dereferences the proxied object from a blessed scalar reference, logs the method call, then invokes that method on the proxied object with the provided parameters. ### Generating Code in AUTOLOAD() This double dispatch is easy to write but inefficient. Every method call on the proxy must fail normal dispatch to end up in `AUTOLOAD()` . Pay that penalty only once by installing new methods into the proxy class as the program needs them: no strict 'refs'; *{ $AUTOLOAD } = $method; return $method->( @_ ); } ``` The body of the previous `AUTOLOAD()` has become a closure (Closures) bound over the name of the undefined method. Installing that closure in the appropriate symbol table allows all subsequent dispatch to that method to find the created closure (and avoid `AUTOLOAD()` ). This code finally invokes the method directly and returns the result. Though this approach is cleaner and almost always more transparent than handling the behavior directly in `AUTOLOAD()` , the code called by `AUTOLOAD()` may see `AUTOLOAD()` in its `caller()` list. While it may violate encapsulation to care that this occurs, leaking the details of how an object provides a method may also violate encapsulation. Some code uses a tailcall (Tailcalls) to replace the current invocation of `AUTOLOAD()` with a call to the destination method: no strict 'refs'; *{ $AUTOLOAD } = $method; goto &$method; } ``` This has the same effect as invoking `$method` directly, except that `AUTOLOAD()` will no longer appear in the list of calls available from `caller()` , so it looks like normal method dispatch occurred. ### Drawbacks of AUTOLOAD `AUTOLOAD()` can be useful, though it is difficult to use properly. The naïve approach to generating methods at runtime means that the `can()` method will not report the right information about the capabilities of objects and classes. The easiest solution is to predeclare all functions you plan to `AUTOLOAD()` with the `subs` pragma: ``` use subs qw( red green blue ochre teal ); ``` Now You See Them Forward declarations are useful only in the two rare cases of attributes (Attributes) and autoloading (AUTOLOAD). That technique documents your intent well, but requires you to maintain a static list of functions or methods. Overriding `can()` (The UNIVERSAL Package) sometimes works better: ``` sub can { my ($self, $method) = @_; # use results of parent can() my $meth_ref = $self->SUPER::can( $method ); return $meth_ref if $meth_ref; # add some filter here return unless $self->should_generate( $method ); $meth_ref = sub { ... }; no strict 'refs'; return *{ $method } = $meth_ref; } sub AUTOLOAD { my ($self) = @_; my ($name) = our $AUTOLOAD =~ /::(\w+)$/; return unless my $meth_ref = $self->can( $name ); goto &$meth_ref; } ``` `AUTOLOAD()` is a big hammer; it can catch functions and methods you had no intention of autoloading, such as `DESTROY()` , the destructor of objects. If you write a `DESTROY()` method with no implementation, Perl will happily dispatch to it instead of `AUTOLOAD()` : ``` # skip AUTOLOAD() sub DESTROY {} ``` A Very Special Method The special methods `import()` , `unimport()` , and `VERSION()` never go through `AUTOLOAD()` . If you mix functions and methods in a single namespace which inherits from another package which provides its own `AUTOLOAD()` , you may see the strange error: ``` Use of inherited AUTOLOAD for non-method slam_door() is deprecated ``` If this happens to you, simplify your code; you've called a function which does not exist in a package which inherits from a class which contains its own `AUTOLOAD()` . The problem compounds in several ways: mixing functions and methods in a single namespace is often a design flaw, inheritance and `AUTOLOAD()` get complex very quickly, and reasoning about code when you don't know what methods objects provide is difficult. `AUTOLOAD()` is useful for quick and dirty programming, but robust code avoids it. Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. Perl's sometimes called the Practical Extraction and Reporting Language. You've seen how control flow, operators, and data structures make Perl practical and you can imagine how to create reports. What's the Extraction part mean? Perl's good at text processing, in part due to regular expressions. A regular expression (also regex or regexp) is a pattern which describes characteristics of a piece of text—to extract an address, replace a misspelling, even to scrape stock prices off of a website to help you figure out what to do with your investment account. Perl's regular expression engine applies these patterns to match or to replace portions of text. While mastering regular expressions is a daunting pursuit, a little knowledge will give you great power. You'll build up your knowledge over time, with practice, as you add more and more features to your toolkit. While this chapter gives an overview of the most important regex features, it's not exhaustive. Perl's documentation includes a tutorial ( `perldoc perlretut` ), a reference guide ( `perldoc perlreref` ), and full documentation ( `perldoc perlre` ). If you're interested in the theory, <NAME>'s book Mastering Regular Expressions explains the computer science and the mechanics of how regular expressions work. ## Literals A regex can be as simple as a substring pattern: ``` my $name = 'Chatfield'; say 'Found a hat!' if $name =~ /hat/; ``` The match operator ( `m//` , abbreviated `//` ) identifies a regular expression—in this example, `hat` . This pattern is not a word. Instead it means "the `h` character, followed by the `a` character, followed by the `t` character." Each character in the pattern is an indivisible element (an atom). An atom either matches or it doesn't. The regex binding operator ( `=~` ) is an infix operator (Fixity) which applies the regex of its second operand to a string provided as its first operand. When evaluated in scalar context, a match evaluates to a boolean value representing the success or failure of the match. The negated form of the binding operator ( `!~` ) evaluates to a true value unless the match succeeds. Remember `index` ! The `index` builtin can also search for a literal substring within a string. Using a regex engine for that is like flying an autonomous combat drone to the corner store to buy cheese—but Perl lets you write code however you find it clear. The substitution operator, `s///` , is in one sense a circumfix operator (Fixity) with two operands. Its first operand (the part between the first and second delimiters) is a regular expression. The second operand (the part between the second and third delimiters) is a substring used to replace the matched portion of the string operand used with the regex binding operator. For example, to cure pesky summer allergies: ``` my $status = 'I feel ill.'; $status =~ s/ill/well/; say $status; ``` ## The qr// Operator and Regex Combinations The `qr//` operator creates first-class regexes you can store in variables. Use these regexes as operands to the match and substitution operators: ``` my $hat = qr/hat/; say 'Found a hat!' if $name =~ /$hat/; ``` ... or combine multiple regex objects into complex patterns: ``` my $hat = qr/hat/; my $field = qr/field/; say 'Found a hat in a field!' if $name =~ /$hat$field/; like $name, qr/$hat$field/, 'Found a hat in a field!'; ``` Like `is` , with More `like` `Test::More` 's `like` function tests that the first argument matches the regex provided as the second argument. ## Quantifiers Matching literal expressions is good, but regex quantifiers make regexes more powerful. These metacharacters govern how often a regex component may appear in a matching string. The simplest quantifier is the zero or one quantifier, or `?` : ``` my $cat_or_ct = qr/ca?t/; like 'cat', $cat_or_ct, "'cat' matches /ca?t/"; like 'ct', $cat_or_ct, "'ct' matches /ca?t/"; ``` Any atom in a regular expression followed by the `?` character means "match zero or one instance(s) of this atom." This regular expression matches if zero or one `a` characters immediately follow a `c` character and immediately precede a `t` character. This regex matches both the literal substrings `cat` and `ct` . The one or more quantifier, or `+` , matches at least one instance of its atom: ``` my $some_a = qr/ca+t/; like 'cat', $some_a, "'cat' matches /ca+t/"; like 'caat', $some_a, "'caat' matches/"; like 'caaat', $some_a, "'caaat' matches"; like 'caaaat', $some_a, "'caaaat' matches"; unlike 'ct', $some_a, "'ct' does not match"; ``` There is no theoretical limit to the maximum number of quantified atoms which can match. The zero or more quantifier, `*` , matches zero or more instances of the quantified atom: ``` my $any_a = qr/ca*t/; like 'cat', $any_a, "'cat' matches /ca*t/"; like 'caat', $any_a, "'caat' matches"; like 'caaat', $any_a, "'caaat' matches"; like 'caaaat', $any_a, "'caaaat' matches"; like 'ct', $any_a, "'ct' matches"; ``` As silly as this seems, it allows you to specify optional components of a regex. Use it sparingly, though: it's a blunt and expensive tool. Most regular expressions benefit from using the `?` and `+` quantifiers far more than `*` . Be precise about your intent to clarify your code. Numeric quantifiers express the number of times an atom may match. `{n}` means that a match must occur exactly n times. ``` # equivalent to qr/cat/; my $only_one_a = qr/ca{1}t/; like 'cat', $only_one_a, "'cat' matches /ca{1}t/"; ``` `{n,}` matches an atom at least n times: ``` # equivalent to qr/ca+t/; my $some_a = qr/ca{1,}t/; like 'cat', $some_a, "'cat' matches /ca{1,}t/"; like 'caat', $some_a, "'caat' matches"; like 'caaat', $some_a, "'caaat' matches"; like 'caaaat', $some_a, "'caaaat' matches"; ``` `{n,m}` means that a match must occur at least n times and cannot occur more than m times: ``` my $few_a = qr/ca{1,3}t/; like 'cat', $few_a, "'cat' matches /ca{1,3}t/"; like 'caat', $few_a, "'caat' matches"; like 'caaat', $few_a, "'caaat' matches"; unlike 'caaaat', $few_a, "'caaaat' doesn't match"; ``` You may express the symbolic quantifiers in terms of the numeric quantifiers, but the symbolic quantifiers are shorter and more common. ## Greediness The `+` and `*` quantifiers are greedy: they try to match as much of the input string as possible. This can be particularly pernicious. Consider a naïve use of the "zero or more non-newline characters" pattern of `.*` : ``` # a poor regex my $hot_meal = qr/hot.*meal/; say 'Found a hot meal!' if 'I have a hot meal' =~ $hot_meal; say 'Found a hot meal!' if 'one-shot, piecemeal work!' =~ $hot_meal; ``` Greedy quantifiers start by matching everything at first. If that match does not succeed, the regex engine will back off one character at a time until it finds a match. The `?` quantifier modifier turns a greedy-quantifier non-greedy: ``` my $minimal_greedy = qr/hot.*?meal/; ``` When given a non-greedy quantifier, the regular expression engine will prefer the shortest possible potential match. If that match fails, the engine will increase the number of characters identified by the `.*?` token combination one character at a time. Because `*` matches zero or more times, the minimal potential match for this token combination is zero characters: ``` say 'Found a hot meal' if 'ilikeahotmeal' =~ /$minimal_greedy/; ``` Use `+?` to match one or more items non-greedily: ``` my $minimal_greedy_plus = qr/hot.+?meal/; unlike 'ilikeahotmeal', $minimal_greedy_plus; like 'i like a hot meal', $minimal_greedy_plus; ``` The `?` quantifier modifier applies to the `?` (zero or one matches) quantifier as well as the range quantifiers. It causes the regex to match as little of the input as possible. Regexes are powerful, but they're not always the best way to solve a problem. This is doubly true for the greedy patterns `.+` and `.*` . A crossword puzzle fan who needs to fill in four boxes of 7 Down ("Rich soil") will find too many invalid candidates with the pattern: ``` my $seven_down = qr/l$letters_only*m/; ``` If you run this against all of the words in a dictionary, it'll match `Alabama` , `Belgium` , and `Bethlehem` long before it reaches `loam` , the real answer. Not only are those words too long, but the matched portions occur everywhere in the word, not just at the start. ## Regex Anchors It's important to know how the regex engine handles greedy matches—but it's equally as important to know what kind of matches you want. Regex anchors force the regex engine to start or end a match at a fixed position. The start of string anchor ( `\A` ) dictates that any match must start at the beginning of the string: ``` # also matches "lammed", "lawmaker", and "layman" my $seven_down = qr/\Al${letters_only}{2}m/; ``` The end of line string anchor ( `\z` ) requires that a match end at the end of the string. ``` # also matches "loom", but an obvious improvement my $seven_down = qr/\Al${letters_only}{2}m\z/; ``` You will often see the `^` and `$` assertions used to match the start and end of strings. `^` does match the start of the string, but in certain circumstances it can match the invisible point just after a newline within the string. Similarly, `$` does match the end of the string (just before a newline, if it exists), but it can match the invisible point just before a newline in the middle of the string. `\A` and `\z` are more specific and, thus, more useful. The word boundary anchor ( `\b` ) matches only at the boundary between a word character ( `\w` ) and a non-word character ( `\W` ). That boundary isn't a character in and of itself; it has no width. It's invisible. Use an anchored regex to find `loam` while prohibiting `Belgium` : ``` my $seven_down = qr/\bl${letters_only}{2}m\b/; ``` This anchor has one flaw which may or may not trip you; it doesn't understand punctuation such as the apostrophe. Fortunately, Perl 5.22 added the Unicode word boundary metacharacter `\b{wb}` , which does understand contractions: ``` say "Panic" if "Don't Panic" =~ /Don\b/; say "No Panic" unless "Don't Panic" =~ /Don\b{wb}/; ``` ## Metacharacters Perl interprets several characters in regular expressions as metacharacters, characters represent something other than their literal interpretation. You've seen a few metacharacters already ( `\b` , `.` , and `?` , for example). Metacharacters give regex wielders power far beyond mere substring matches. The regex engine treats all metacharacters as atoms. See ``` perldoc perlrebackslash ``` for far more detail about metacharacters. The `.` metacharacter means "match any character except a newline". Many novices forget that nuance. A simple regex search—ignoring the obvious improvement of using anchors—for 7 Down might be `/l..m/` . Of course, there's always more than one way to get the right answer: ``` for my $word (@words) { next unless length( $word ) == 4; next unless $word =~ /l..m/; say "Possibility: $word"; } ``` If the potential matches in `@words` are more than the simplest English words, you will get false positives. `.` also matches punctuation characters, whitespace, and numbers. Be specific! The `\w` metacharacter represents all Unicode alphanumeric characters (Unicode and Strings) and the underscore: ``` next unless $word =~ /l\w\wm/; ``` The `\d` metacharacter matches Unicode digits: ``` next unless $number =~ /\d{3}-\d{3}-\d{4}/; say "I have your number: $number"; ``` ... though in this case, the `Regexp::English` module has a much better phone number regex already written for you. Use the `\s` metacharacter to match whitespace. Whitespace means a literal space, a tab character, a carriage return, a form-feed, or a newline: ``` my $two_three_letter_words = qr/\w{3}\s\w{3}/; ``` Negated Metacharacters These metacharacters have negated forms. Use `\W` to match any character except a word character. Use `\D` to match a non-digit character. Use `\S` to match anything but whitespace. Use `\B` to match anywhere except a word boundary and `\B{wb}` to match anywhere except a Unicode word boundary. ## Character Classes When none of those metacharacters is specific enough, group multiple characters into a character class by enclosing them in square brackets. A character class allows you to treat a group of alternatives as a single atom. ``` my $ascii_vowels = qr/[aeiou]/; my $maybe_cat = qr/c${ascii_vowels}t/; ``` Interpolation Happens Without those curly braces, Perl's parser would interpret the variable name as `$ascii_vowelst` , which either causes a compile-time error about an unknown variable or interpolates the contents of an existing `$ascii_vowelst` into the regex. The hyphen character ( `-` ) allows you to include a contiguous range of characters in a class, such as this `$ascii_letters_only` regex: ``` my $ascii_letters_only = qr/[a-zA-Z]/; ``` To include the hyphen as a member of the class, place it at the start or end of the class: ``` my $interesting_punctuation = qr/[-!?]/; ``` ... or escape it: ``` my $line_characters = qr/[|=\-_]/; ``` Use the caret ( `^` ) as the first element of the character class to mean "anything except these characters": ``` my $not_an_ascii_vowel = qr/[^aeiou]/; ``` Use a caret anywhere but the first position to make it a member of the character class. To include a hyphen in a negated character class, place it after the caret or at the end of the class—or escape it. ## Capturing Regular expressions allow you to group and capture portions of the match for later use. To extract an American telephone number of the form `(202) 456-1111` from a string: ``` my $area_code = qr/\(\d{3}\)/; my $local_number = qr/\d{3}-?\d{4}/; my $phone_number = qr/$area_code\s?$local_number/; ``` Note the escaped parentheses within `$area_code` . Parentheses are special in Perl regular expressions. They group atoms into larger units and capture portions of matching strings. To match literal parentheses, escape them with backslashes as seen in `$area_code` . ### Named Captures Named captures allow you to capture portions of matches from applying a regular expression and access them later. For example, when extracting a phone number from contact information: ``` if ($contact_info =~ /(?<phone>$phone_number)/) { say "Found a number $+{phone}"; } ``` Named capture syntax has the form: ``` (?<capture name> ... ) ``` Parentheses enclose the capture. The `?< name >` construct immediately follows the opening parenthesis and provides a name for this particular capture. The remainder of the capture is a regular expression. When a match against the enclosing pattern succeeds, Perl updates the magic variable `%+` . In this hash, the key is the name of the capture and the value is the portion of the string which matched the capture. ### Numbered Captures Perl also supports numbered captures: ``` if ($contact_info =~ /($phone_number)/) { say "Found a number $1"; } ``` This form of capture provides no identifying name and does nothing to `%+` . Instead, Perl stores the captured substring in a series of magic variables. The first matching capture goes into `$1` , the second into `$2` , and so on. Capture counts start at the opening parenthesis of the capture. Thus the first left parenthesis begins the capture into `$1` , the second into `$2` , and so on. While the syntax for named captures is longer than for numbered captures, it provides additional clarity. Counting left parentheses is tedious, and combining regexes which each contain numbered captures is difficult. Named captures improve regex maintainability—though name collisions are possible, they're relatively infrequent. Minimize the risk by using named captures only in top-level regexes, rather than in smaller regexes composed into larger. In list context, a regex match returns a list of captured substrings: ``` if (my ($number) = $contact_info =~ /($phone_number)/) { say "Found a number $number"; } ``` Numbered captures are also useful in simple substitutions, where named captures may be more verbose: ``` my $order = 'Vegan brownies!'; $order =~ s/Vegan (\w+)/Vegetarian $1/; # or $order =~ s/Vegan (?<food>\w+)/Vegetarian $+{food}/; ``` ## Grouping and Alternation Previous examples have all applied quantifiers to simple atoms. You may apply them to any regex element: ``` my $pork = qr/pork/; my $beans = qr/beans/; like 'pork and beans', qr/\A$pork?.*?$beans/, 'maybe pork, definitely beans'; ``` If you expand the regex manually, the results may surprise you: ``` my $pork_and_beans = qr/\Apork?.*beans/; like 'pork and beans', qr/$pork_and_beans/, 'maybe pork, definitely beans'; like 'por and beans', qr/$pork_and_beans/, 'wait... no phylloquinone here!'; ``` Sometimes specificity helps pattern accuracy: ``` my $pork = qr/pork/; my $and = qr/and/; my $beans = qr/beans/; like 'pork and beans', qr/\A$pork? $and? $beans/, 'maybe pork, maybe and, definitely beans'; ``` Some regexes need to match either one thing or another. The alternation metacharacter ( `|` ) indicates that either possibility may match. ``` my $rice = qr/rice/; my $beans = qr/beans/; like 'rice', qr/$rice|$beans/, 'Found rice'; like 'beans', qr/$rice|$beans/, 'Found beans'; ``` While it's easy to interpret `rice|beans` as meaning `ric` , followed by either `e` or `b` , followed by `eans` , alternations always include the entire fragment to the nearest regex delimiter, whether the start or end of the pattern, an enclosing parenthesis, another alternation character, or a square bracket. Alternation has a lower precedence (Precedence) than even atoms: ``` like 'rice', qr/rice|beans/, 'Found rice'; like 'beans', qr/rice|beans/, 'Found beans'; unlike 'ricb', qr/rice|beans/, 'Found hybrid'; ``` To reduce confusion, use named fragments in variables ( `$rice|$beans` ) or group alternation candidates in non-capturing groups: ``` my $starches = qr/(?:pasta|potatoes|rice)/; ``` The `(?:)` sequence groups a series of atoms without making a capture. Non-Captured For Your Protection A stringified regular expression includes an enclosing non-capturing group; `qr/rice|beans/` stringifies as `(?^u:rice|beans)` . ## Other Escape Sequences To match a literal instance of a metacharacter, escape it with a backslash ( `\` ). You've seen this before, where `\(` refers to a single left parenthesis and `\]` refers to a single right square bracket. `\.` refers to a literal period character instead of the "match anything but an explicit newline character" atom. Remember to escape the alternation metacharacter ( `|` ) as well as the end of line metacharacter ( `$` ) and the quantifiers ( `+` , `?` , `*` ) if you want to match their symbols literally. The metacharacter disabling characters ( `\Q` and `\E` ) disable metacharacter interpretation within their boundaries. This is especially useful when you don't control the source of match text: ``` my ($text, $literal_text) = @_; return $text =~ /\Q$literal_text\E/; ``` The `$literal_text` argument can contain anything—the string `** ALERT **` , for example. Within the fragment bounded by `\Q` and `\E` , Perl will interpret the regex as `** ALERT **` and attempt to match literal asterisk characters instead of treating the asterisks as greedy quantifiers. Regex Security Be cautious when processing regular expressions from untrusted user input. A malicious regex master can craft a regular expression which may take years to match input strings, creating a denial-of-service attack against your program. ## Assertions Regex anchors such as `\A` , `\b` , `\B` , and `\Z` are regex assertions. These assertions do not match individual characters within the string. Instead they match specific conditions of the string. For example, no matter what the string contains, the regex `qr/\A/` will always match. Zero-width assertions match a pattern. Most importantly, they do not consume the portion of the pattern that they match. For example, to find a cat on its own, you might use a word boundary assertion: ``` my $just_a_cat = qr/cat\b/; # or my $just_a_cat = qr/cat\b{wb}/; ``` ... but to find a non-disastrous feline, you could use a zero-width negative look-ahead assertion: ``` my $safe_feline = qr/cat(?!astrophe)/; ``` The construct `(?!...)` matches the phrase `cat` only if the phrase `astrophe` does not immediately follow. The zero-width positive look-ahead assertion: ``` my $disastrous_feline = qr/cat(?=astrophe)/; ``` ... matches the phrase `cat` only if the phrase `astrophe` immediately follows. While a normal regular expression can accomplish the same thing, consider a regex to find all non-catastrophic words in the dictionary which start with `cat` : ``` my $disastrous_feline = qr/cat(?!astrophe)/; while (<$words>) { chomp; next unless /\A(?<cat>$disastrous_feline.*)\Z/; say "Found a non-catastrophe '$+{cat}'"; } ``` The zero-width assertion consumes none of the source string, which leaves the anchored fragment `.*\Z` to match. Otherwise, the capture would only capture the `cat` portion of the source string. To assert that your feline never occurs at the start of a line, use a zero-width negative look-behind assertion. These assertions must have fixed sizes, and thus you may not use quantifiers: ``` my $middle_cat = qr/(?<!\A)cat/; ``` The construct `(?<!...)` contains the fixed-width pattern. You could also express that the `cat` must always occur immediately after a space character with a zero-width positive look-behind assertion: ``` my $space_cat = qr/(?<=\s)cat/; ``` The construct `(?<=...)` contains the fixed-width pattern. This approach can be useful when combining a global regex match with the `\G` modifier. Perl also includes the keep assertion `\K` . This zero-width positive look-behind assertion can have a variable length: ``` my $spacey_cat = qr/\s+\Kcat/; like 'my cat has been to space', $spacey_cat; like 'my cat has been to doublespace', $spacey_cat; ``` `\K` is surprisingly useful for certain substitutions which remove the end of a pattern. It lets you match a pattern but remove only a portion of it: ``` my $exclamation = 'This is a catastrophe!'; $exclamation =~ s/cat\K\w+!/./; like $exclamation, qr/\bcat\./, "That wasn't so bad!"; ``` Everything until the `\K` assertion matches, but only the portion of the match after the assertion will be substituted away. ## Regex Modifiers Several modifiers change the behavior of the regular expression operators. These modifiers appear at the end of the match, substitution, and `qr//` operators. For example, to enable case-insensitive matching: ``` my $pet = 'ELLie'; like $pet, qr/Ellie/, 'Nice puppy!'; like $pet, qr/Ellie/i, 'shift key br0ken'; ``` The first `like()` will fail because the strings contain different letters. The second `like()` will pass, because the `/i` modifier causes the regex to ignore case distinctions. `L` and `l` are effectively equivalent in the second regex due to the modifier. You may also embed regex modifiers within a pattern: ``` my $find_a_cat = qr/(?<feline>(?i)cat)/; ``` The `(?i)` syntax enables case-insensitive matching only for its enclosing group—in this case, the named capture. You may use multiple modifiers with this form. Disable specific modifiers by preceding them with the minus character ( `-` ): ``` my $find_a_rational = qr/(?<number>(?-i)Rat)/; ``` The multiline operator, `/m` , allows the `^` and `$` anchors to match at any newline embedded within the string. The `/s` modifier treats the source string as a single line such that the `.` metacharacter matches the newline character. Damian Conway suggests the mnemonic that `/m` modifies the behavior of multiple regex metacharacters, while `/s` modifies the behavior of a single regex metacharacter. The `/r` modifier causes a substitution operation to return the result of the substitution, leaving the original string unchanged. If the substitution succeeds, the result is a modified copy of the original. If the substitution fails (because the pattern does not match), the result is an unmodified copy of the original: ``` my $status = 'I am hungry for pie.'; my $newstatus = $status =~ s/pie/cake/r; my $statuscopy = $status =~ s/liver and onions/bratwurst/r; is $status, 'I am hungry for pie.', 'original string should be unmodified'; like $newstatus, qr/cake/, 'cake wanted'; unlike $statuscopy, qr/bratwurst/, 'wurst not want not'; ``` The `/x` modifier allows you to embed additional whitespace and comments within patterns. With this modifier in effect, the regex engine ignores whitespace and comments, so your code can be more readable: ``` my $attr_re = qr{ \A # start of line (?: [;\n\s]* # spaces and semicolons (?:/*.*?*/)? # C comments )* ATTR \s+ ( U?INTVAL | FLOATVAL | STRING\s+* ) }x; ``` This regex isn't simple, but comments and whitespace improve its readability. Even if you compose regexes together from compiled fragments, the `/x` modifier can still improve your code. The `/g` modifier matches a regex globally throughout a string. This makes sense when used with a substitution: ``` # appease the Mitchell estate my $contents = slurp( $file ); $contents =~ s/Scarlett O'Hara/Mauve Midway/g; ``` When used with a match—not a substitution—the `\G` metacharacter allows you to process a string within a loop one chunk at a time. `\G` matches at the position where the most recent match ended. To process a poorly-encoded file full of American telephone numbers in logical chunks, you might write: ``` while ($contents =~ /\G(\w{3})(\w{3})(\w{4})/g) { push @numbers, "($1) $2-$3"; } ``` Be aware that the `\G` anchor will begin at the last point in the string where the previous iteration of the match occurred. If the previous match ended with a greedy match such as `.*` , the next match will have less available string to match. Lookahead assertions can also help. The `/e` modifier allows you to write arbitrary code on the right side of a substitution operation. If the match succeeds, the regex engine will use the return value of that code as the substitution value. The earlier global substitution example could be simpler with code like: ``` # appease the Mitchell estate $sequel =~ s{Scarlett( O'Hara)?} { 'Mauve' . defined $1 ? ' Midway' : '' }ge; ``` Each additional occurrence of the `/e` modifier will cause another evaluation of the result of the expression, though only Perl golfers use anything beyond `/ee` . ## Smart Matching The smart match operator, `~~` , compares two operands and returns a true value if they match. The type of comparison depends on the type of both operands. `given` (Switch Statements) performs an implicit smart match. This feature is experimental. The details of the current design are complex and unwieldy, and no proposal for simplifying things has gained enough popular support to warrant the feature's overhaul. The more complex your operands, the more likely you are to receive confusing results. Avoid comparing objects and stick to simple operations between two scalars or one scalar and one aggregate for the best results. The smart match operator is an infix operator: say 'They match (somehow)' if $l_operand ~~ $r_operand; ``` The type of comparison generally depends first on the type of the right operand and then on the left operand. For example, if the right operand is a scalar with a numeric component, the comparison will use numeric equality. If the right operand is a regex, the comparison will use a grep or a pattern match. If the right operand is an array, the comparison will perform a grep or a recursive smart match. If the right operand is a hash, the comparison will check the existence of one or more keys. A large and intimidating chart in `perldoc perlsyn` gives far more details about all the comparisons smart match can perform. These examples are deliberately simple, because smart match can be confusing: my ($x, $y) = (10, 20); say 'Not equal numerically' unless $x ~~ $y; my $z = '10 little endians'; say 'Equal numeric-ishally' if $x ~~ $z; my $needle = qr/needle/; say 'Pattern match' if 'needle' ~~ $needle; say 'Grep through array' if @haystack ~~ $needle; say 'Grep through hash keys' if %hayhash ~~ $needle; say 'Grep through array' if $needle ~~ @haystack; say 'Array elements exist as hash keys' if %hayhash ~~ @haystack; say 'Smart match elements' if @straw ~~ @haystack; say 'Grep through hash keys' if $needle ~~ %hayhash; say 'Array elements exist as hash keys' if @haystack ~~ %hayhash; say 'Hash keys identical' if %hayhash ~~ %haymap; ``` Smart match works even if one operand is a reference to the given data type: ``` say 'Hash keys identical' if %hayhash ~~ \%hayhash; ``` It's difficult to recommend the use of smart match except in the simplest circumstances, but it can be useful when you have a literal string or number to match against a variable. Date: 2008-04-01 Categories: Tags: Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. Every large program has several levels of design. At the bottom, you have specific details about the problem you're solving. At the top levels, you have to organize the code so it makes sense. Our only hope to manage this complexity is to exploit abstraction (treating similar things similarly) and encapsulation (grouping related details together). Functions alone are insufficient for large problems. Several techniques group functions into units of related behaviors; you've already seen higher-order functions. Another popular technique is object orientation (OO), or object oriented programming (OOP), where programs work with objects—discrete, unique entities with their own identities. ## Moose Perl's default object system is minimal but flexible. Its syntax is a little clunky, and it exposes how an object system works. You can build great things on top of it, but it doesn't give you what many other languages do by default. Moose is a complete object system for Perl. It's a complete distribution available from the CPAN—not a part of the core language, but worth installing and using regardless. Moose offers both a simpler way to use an object system as well as advanced features of languages such as Smalltalk and Common Lisp. Moose objects work with plain vanilla Perl. Within your programs, you can mix and match objects written with Perl's default object system and Moose. Moose Documentation See `Moose::Manual` on the CPAN for comprehensive Moose documentation. ### Classes A Moose object is a concrete instance of a class, which is a template describing data and behavior specific to the object. A class generally belongs to a package (Packages), which provides its name: This `Cat` class appears to do nothing, but that's all Moose needs to make a class. Create objects (or instances) of the `Cat` class with the syntax: ``` my $brad = Cat->new; my $jack = Cat->new; ``` In the same way that this arrow operator dereferences a reference, it calls a method on `Cat` . ### Methods A method is a function associated with a class. In the same way that a function belongs to a namespace, a method belongs to a class. When you call a method, you do so with an invocant. When you call `new()` on `Cat` , the name of the class, `Cat` , is `new()` 's invocant. Think of this as sending a message to a class: "do whatever `new()` does." In this case, calling the `new()` method—sending the `new` message—returns a new object of the `Cat` class. When you call a method on an object, that object is the invocant: ``` my $choco = Cat->new; $choco->sleep_on_keyboard; ``` A method's first argument is its invocant ( `$self` , by convention). Suppose a `Cat` can `meow()` : sub meow { my $self = shift; say 'Meow!'; } } ``` Now any `Cat` instance can wake you for its early morning feeding: ``` # the cat always meows three times at 6 am my $fuzzy_alarm = Cat->new; $fuzzy_alarm->meow for 1 .. 3; ``` Every object can have its own distinct data. Methods which read or write the data of their invocants are instance methods; they depend on the presence of an appropriate invocant to work correctly. Methods (such as `meow()` ) which do not access instance data are class methods. You may invoke class methods on classes and class and instance methods on instances, but you cannot invoke instance methods on classes. Class methods are effectively namespaced global functions. Without access to instance data, they have few advantages over namespaced functions. Most OO code uses instance methods to read and write instance data. Constructors, which create instances, are class methods. When you declare a Moose class, Moose provides a default constructor named `new()` . ### Attributes Every Perl object is unique. Objects can contain private data associated with each unique object—often called attributes, instance data, or object state. Define an attribute by declaring it as part of the class: has 'name', is => 'ro', isa => 'Str'; } ``` Moose exports the `has()` function for you to use to declare an attribute. In English, this code reads " `Cat` objects have a `name` attribute. It's read-only, and is a string." The first argument, `'name'` , is the attribute's name. The `is => 'ro'` pair of arguments declares that this attribute is `r` ead `o` nly, so you cannot modify the attribute's value after you've set it. Finally, the `isa => 'Str'` pair declares that the value of this attribute can only be a `Str` ing. From this code Moose creates an accessor method named `name()` and allows you to pass a `name` parameter to `Cat` 's constructor: ``` for my $name (qw( <NAME> )) { my $cat = Cat->new( name => $name ); say "Created a cat for ", $cat->name; } ``` Moose's documentation uses parentheses to separate attribute names and characteristics: ``` has 'name' => ( is => 'ro', isa => 'Str' ); ``` This is equivalent to: ``` has( 'name', 'is', 'ro', 'isa', 'Str' ); ``` Moose's approach works nicely for complex declarations: ``` has 'name' => ( is => 'ro', isa => 'Str', # advanced Moose options; perldoc Moose init_arg => undef, lazy_build => 1, ); ``` ... while this book prefers a low-punctuation approach for simple declarations. Choose the style which offers you the most clarity. When an attribute declaration has a type, Moose will attempt to validate all values assigned to that attribute. Sometimes this strictness is invaluable. While Moose will complain if you try to set `name` to a value which isn't a string, attributes do not require types. In that case, anything goes: has 'name', is => 'ro', isa => 'Str'; has 'age', is => 'ro'; } my $invalid = Cat->new( name => 'bizarre', age => 'purple' ); ``` If you mark an attribute as readable and writable (with `is => rw` ), Moose will create a mutator method which can change that attribute's value: has 'name', is => 'ro', isa => 'Str'; has 'age', is => 'ro', isa => 'Int'; has 'diet', is => 'rw'; } my $fat = Cat->new( name => 'Fatty', age => 8, diet => 'Sea Treats' ); say $fat->name, ' eats ', $fat->diet; $fat->diet( 'Low Sodium Kitty Lo Mein' ); say $fat->name, ' now eats ', $fat->diet; ``` An `ro` accessor used as a mutator will throw the exception ``` Cannot assign a value to a read-only accessor at ... ``` . Using `ro` or `rw` is a matter of design, convenience, and purity. Moose enforces no single philosophy here. Some people suggest making all instance data `ro` such that you must pass instance data into the constructor (Immutability). In the `Cat` example, `age()` might still be an accessor, but the constructor could take the year of the cat's birth and calculate the age itself based on the current year. This approach consolidates validation code and ensures that all objects have valid data after creation. This illustrates a subtle but important principle of object orientation. An object contains related data and can perform behaviors with and on that data. A class describes that data and those behaviors. You can have multiple independent objects with separate instance data and treat all of those objects the same way; they will behave differently depending on their instance data. ### Encapsulation Moose allows you to declare which attributes class instances possess (a cat has a name) as well as the attributes of those attributes (you can name a cat once and thereafter its name cannot change). Moose itself decides how to store those attributes—you access them through accessors. This is encapsulation: hiding the internal details of an object from external users of that object. Consider the aforementioned idea to change how `Cat` s manage their ages by passing in the year of the cat's birth and calculating the age as needed: While the syntax for creating `Cat` objects has changed, the syntax for using `Cat` objects has not. Outside of `Cat` , `age()` behaves as it always has. How it works is a detail hidden inside the `Cat` class. Compatibility and APIs Retain the old syntax for creating `Cat` objects by customizing the generated `Cat` constructor to allow passing an `age` parameter. Calculate `birth_year` from that. See . This change offers another advantage; a default attribute value will let users construct a new `Cat` object without providing a birth year: The `default` keyword on an attribute uses a function reference (or a literal string or number) which returns the default value for that attribute when constructing a new object. If the code creating an object passes no constructor value for that attribute, the object gets the default value: ``` my $kitten = Cat->new( name => 'Hugo' ); ``` ... and that kitten will have an age of `0` until next year. # Polymorphism The real power of object orientation goes beyond classes and encapsulation. A well-designed OO program can manage many types of data. When well-designed classes encapsulate specific details of objects into the appropriate places, something curious happens: the code often becomes less specific. Moving the details of what the program knows about individual `Cat` s (the attributes) and what the program knows that `Cat` s can do (the methods) into the `Cat` class means that code that deals with `Cat` instances can happily ignore how `Cat` does what it does. Consider a function which displays details of an object: ``` sub show_vital_stats { my $object = shift; say 'My name is ', $object->name; say 'I am ', $object->age; say 'I eat ', $object->diet; } ``` This function obviously works if you pass it a `Cat` object. It will also do the right thing for any object with the appropriate three accessors, no matter how that object provides those accessors and no matter what kind of object it is: `Cat` , `Caterpillar` , or `Catbird` , or even if the class uses Moose at all. `show_vital_stats()` cares that an invocant is valid only in that it supports three methods, `name()` , `age()` , and `diet()` which take no arguments and each return something which can concatenate in a string context. Your code may have a hundred different classes with no obvious relationship between them, but they will all work with this function if they support the behavior it expects. This property is polymorphism: you can substitute an object of one class for an object of another class if they provide the same external interface. Duck Typing Some languages and environments require you to imply or declare a formal relationship between two classes before allowing a program to substitute instances for each other. Perl makes no such requirement. You may treat any two instances with methods of the same name as equivalent. Some people call this duck typing, arguing that any object which can `quack()` is sufficiently duck-like that you can treat it as a duck. Without object polymorphism, enumerating a zoo's worth of animals would be tedious. Similarly, you may already start to see how calculating the age of an ocelot or octopus should be the same as calculating the age of a `Cat` . Hold that thought. Of course, the mere existence of a method called `name()` or `age()` does not by itself imply the behavior of that object. A `Dog` object may have an `age()` which is an accessor such that you can discover `$rodney` is 13 but `$lucky` is 8. A `Cheese` object may have an `age()` method that lets you control how long to stow `$cheddar` to sharpen it. `age()` may be an accessor in one class but not in another: ``` # how old is the cat? my $years = $zeppie->age; # store the cheese in the warehouse for six months $cheese->age; ``` Sometimes it's useful to know what an object does and what that means. ### Roles A role is a named collection of behavior and state. (Many of the ideas come from Smalltalk traits http://scg.unibe.ch/research/traits.) While a class organizes behaviors and state into a template for objects, a role organizes a named collection of behaviors and state. You can instantiate a class, but not a role. A role is something a class does. Given an `Animal` which has an age and a `Cheese` which can age, one difference may be that `Animal` does the `LivingBeing` role, while the `Cheese` does the `Storable` role: ``` package LivingBeing { use Moose::Role; requires qw( name age diet ); } ``` The `requires` keyword provided by `Moose::Role` allows you to list methods that this role requires of its composing classes. Anything which does this role must supply the `name()` , `age()` , and `diet()` methods. The `Cat` class must declare that it performs the role: with 'LivingBeing'; sub age { ... } } ``` The `with` line causes Moose to compose the `LivingBeing` role into the `Cat` class. Composition ensures all of the attributes and methods of the role are part of the class. `LivingBeing` requires any composing class to provide methods named `name()` , `age()` , and `diet()` . `Cat` satisfies these constraints. If `LivingBeing` were composed into a class which did not provide those methods, Moose would throw an exception. Order Matters! The `with` keyword used to apply roles to a class must occur after attribute declaration so that composition can identify any generated accessor methods. This is a side-effect of the implementation of Moose and not an intrinsic feature of roles. Now all `Cat` instances will return a true value when queried if they provide the `LivingBeing` role. `Cheese` objects should not: ``` say 'Alive!' if $fluffy->DOES( 'LivingBeing' ); say 'Moldy!' if $cheese->DOES( 'LivingBeing' ); ``` This design technique separates the capabilities of classes and objects from the implementation of those classes and objects. As implied earlier, the birth year calculation behavior of the `Cat` class could itself be a role: ``` package CalculateAge::From::BirthYear { use Moose::Role; Extracting this role from `Cat` makes the useful behavior available to other classes. Now `Cat` can compose both roles: with 'LivingBeing', 'CalculateAge::From::BirthYear'; } ``` The `age()` method of satisfies the requirement of the `LivingBeing` role. Extracting the role has only changed the details of how `Cat` calculates an age. It's still a `LivingBeing` . `Cat` can choose to implement its own age or get it from somewhere else. All that matters is that it provides an `age()` which satisfies the `LivingBeing` constraint. While polymorphism means that you can treat multiple objects with the same behavior in the same way, allomorphism means that an object may implement the same behavior in multiple ways. Pervasive allomorphism can reduce the size of your classes and increase the amount of code shared between them. It also allows you to name specific and discrete collections of behaviors—very useful for testing for capabilities instead of implementations. # Roles and DOES() When you compose a role into a class, the class and its instances will return a true value when you call `DOES()` on them: ``` say 'This Cat is alive!' if $kitten->DOES( 'LivingBeing' ); ``` ### Inheritance Perl's object system supports inheritance, which establishes a parent and child relationship between two classes such that a child specializes its parent. The child class behaves the same way as its parent—it has the same number and types of attributes and can use the same methods. It may have additional data and behavior, but you may substitute any instance of a child where code expects its parent. In one sense, a subclass provides the role implied by the existence of its parent class. Roles versus Inheritance Should you use roles or inheritance? Roles provide composition-time safety, better type checking, better factoring of code, and finer-grained control over names and behaviors, but inheritance is more familiar to experienced developers of other languages. Use inheritance when one class truly extends another. Use a role when a class needs additional behavior, especially when that behavior has a meaningful name. Roles compare favorably to other design techniques such as mixins, multiple inheritance, and monkeypatching http://www.modernperlbooks.com/mt/2009/04/the-why-of-perl-roles.html. Consider a `LightSource` class which provides two public attributes ( `enabled` and `candle_power` ) and two methods ( `light` and `extinguish` ): ``` package LightSource { use Moose; has 'candle_power', is => 'ro', isa => 'Int', default => 1; has 'enabled', is => 'ro', isa => 'Bool', default => 0, writer => '_set_enabled'; sub light { my $self = shift; $self->_set_enabled( 1 ); } sub extinguish { my $self = shift; $self->_set_enabled( 0 ); } } ``` Note that `enabled` 's `writer` option creates a private accessor usable within the class to set the value. # Inheritance and Attributes A subclass of `LightSource` could define an industrial-strength super candle with a hundred times the luminance: ``` package SuperCandle { use Moose; has '+candle_power', default => 100; } ``` `extends` takes a list of class names to use as parents of the current class. If that were the only line in this class, `SuperCandle` objects would behave in the same ways as `LightSource` objects. A `SuperCandle` instance would have both the `candle_power` and `enabled` attributes as well as the `light()` and `extinguish()` methods. The `+` at the start of an attribute name (such as `candle_power` ) indicates that the current class does something special with that attribute. Here the super candle overrides the default value of the light source, so any new `SuperCandle` created has a light value of 100 regular candles. When you invoke `light()` or `extinguish()` on a `SuperCandle` object, Perl will look in the `SuperCandle` class for the method. If there's no method by that name in the child class, Perl will look at the parent class, then grandparent, and so on. In this case, those methods are in the `LightSource` class. Attribute inheritance works similarly (see `perldoc Class::MOP` ). # Method Dispatch Order Perl's dispatch strategy controls how Perl selects the appropriate method to run for a method call. As you may have gathered from roles and polymorphism, much of OO's power comes from method dispatch. Method dispatch order (or method resolution order or MRO) is obvious for single-parent classes. Look in the object's class, then its parent, and so on until you find the method—or run out of parents. Classes which inherit from multiple parents (multiple inheritance), such as a `Hovercraft` which extends both `Boat` and `Car` , require trickier dispatch. Reasoning about multiple inheritance is complex, so avoid multiple inheritance when possible. Perl uses a depth-first method resolution strategy. It searches the class of the first named parent and all of that parent's parents recursively before searching the classes of the current class's immediate parents. The `mro` pragma (Pragmas) provides alternate strategies, including the C3 MRO strategy which searches a given class's immediate parents before searching any of their parents. See `perldoc mro` for more details. # Inheritance and Methods As with attributes, subclasses may override methods. Imagine a light that you cannot extinguish: ``` package Glowstick { use Moose; sub extinguish {} } ``` Calling `extinguish()` on a glowstick does nothing, even though `LightSource` 's method does something. Method dispatch will find the subclass's method. You may not have meant to do this. When you do, use Moose's `override` to express your intention clearly. Within an overridden method, Moose's `super()` allows you to call the overridden method: ``` package LightSource::Cranky { use Carp 'carp'; use Moose; override light => sub { my $self = shift; carp "Can't light a lit LightSource!" if $self->enabled; super(); }; override extinguish => sub { my $self = shift; carp "Can't extinguish unlit LightSource!" unless $self->enabled; super(); }; } ``` This subclass adds a warning when trying to light or extinguish a light source that already has the current state. The `super()` function dispatches to the nearest parent's implementation of the current method, per the normal Perl method resolution order. (See for more dispatch options.) # Inheritance and isa() Perl's `isa()` method returns true if its invocant is or extends a named class. That invocant may be the name of a class or an instance of an object: ``` say 'Looks like a LightSource' if $sconce->isa( 'LightSource' ); say 'Hominidae do not glow' unless $chimpy->isa( 'LightSource' ); ``` ### Moose and Perl OO Moose provides many features beyond Perl's default OO system. While you can build everything you get with Moose yourself (Blessed References), or cobble it together with a series of CPAN distributions, Moose is worth using. It is a coherent whole, with documentation, a mature and attentive development community, and a history of successful use in important projects. Moose provides constructors, destructors, accessors, and encapsulation. You must do the work of declaring what you want, and you get safe and useful code in return. Moose objects can extend and work with objects from the vanilla Perl system. While Moose is not a part of the Perl core, its popularity ensures that it's available on many OS distributions, including Strawberry Perl and ActivePerl. Even though Moose is a CPAN module and not a core library, its cleanliness and simplicity make it essential to modern Perl programming. Moose also allows metaprogramming—manipulating your objects through Moose itself. If you've ever wondered which methods are available on a class or an object or which attributes an object supports, this information is available: ``` my $metaclass = Monkey::Pants->meta; say 'Monkey::Pants instances have the attributes:'; say $_->name for $metaclass->get_all_attributes; say 'Monkey::Pants instances support the methods:'; say $_->fully_qualified_name for $metaclass->get_all_methods; ``` You can even see which classes extend a given class: ``` my $metaclass = Monkey->meta; say 'Monkey is the superclass of:'; say $_ for $metaclass->subclasses; ``` See ``` perldoc Class::MOP::Class ``` for more information about metaclass operations and `perldoc Class::MOP` for Moose metaprogramming information. Moose and its meta-object protocol (or MOP) offers the possibility of a better syntax for declaring and working with classes and objects in Perl. This is valid code: ``` use MooseX::Declare; The `MooseX::Declare` CPAN distribution adds the `class` , `role` , and `method` keywords to reduce the amount of boilerplate necessary to write good object oriented code in Perl. Note specifically the declarative nature of this example, as well as the lack of `my $self = shift;` in `age()` . Another good option is `Moops` , which allows you to write: ``` use Moops; The Svelte Alces Moose isn't a small library, but it's powerful. The most popular alternative is `Moo` , a slimmer library that's almost completely compatible with Moose. Many projects migrate some or all code to Moo where speed or memory use is an issue. Start with Moose, then see if Moo makes sense for you. ## Blessed References Perl's core object system is deliberately minimal. It has only three rules: * A class is a package. * A method is a function. * A (blessed) reference is an object. You can build anything else out of those three rules. This minimalism can be impractical for larger projects—in particular, the possibilities for greater abstraction through metaprogramming (Code Generation) are awkward and limited. Moose (Moose) is a better choice for modern programs larger than a couple of hundred lines, although plenty of legacy code uses Perl's default OO. You've seen the first two rules already. The `bless` builtin associates the name of a class with a reference. That reference is now a valid invocant. Perl will perform method dispatch on it. A constructor is a method which creates and blesses a reference. By convention, constructors are named `new()` . Constructors are also almost always class methods. `bless` takes two operands, a reference and a class name, and evaluates to the reference. The reference may be any valid reference, empty or not. The class does not have to exist yet. You may even use `bless` outside of a constructor or a class, but you violate encapsulation to expose the details of object construction outside of a constructor. A constructor can be as simple as: ``` sub new { my $class = shift; bless {}, $class; } ``` By design, this constructor receives the class name as the method's invocant. You may also hard-code the name of a class at the expense of flexibility. A parametric constructor—one which relies on the invocant to determine the class name—allows reuse through inheritance, delegation, or exporting. The type of reference used is relevant only to how the object stores its own instance data. It has no other effect on the resulting object. Hash references are most common, but you can bless any type of reference: ``` my $array_obj = bless [], $class; my $scalar_obj = bless \$scalar, $class; my $func_obj = bless \&some_func, $class; ``` Moose classes define object attributes declaratively, but Perl's default OO is lax. A class representing basketball players which stores jersey number and position might use a constructor like: ``` package Player { sub new { my ($class, %attrs) = @_; bless \%attrs, $class; } } ``` ... and create players with: ``` my $joel = Player->new( number => 10, position => 'center' ); my $damian = Player->new( number => 0, position => 'guard' ); ``` The class's methods can access object attributes as hash elements directly: ``` sub format { my $self = shift; return '#' . $self->{number} . ' plays ' . $self->{position}; } ``` ... but so can any other code, so any change to the object's internal representation may break other code. Accessor methods are safer: ``` sub number { return shift->{number} } sub position { return shift->{position} } ``` ... and now you're starting to write yourself what Moose gives you for free. Better yet, Moose encourages people to use accessors instead of direct attribute access by generating the accessors itself. You won't see them in your code. Goodbye, temptation. ### Method Lookup and Inheritance Given a blessed reference, a method call of the form: ``` my $number = $joel->number; ``` ... looks up the name of the class associated with the blessed reference `$joel` —in this case, `Player` . Next, Perl looks for a function named `number()` in `Player` . (Remember that Perl makes no distinction between functions in a namespace and methods.) If no such function exists and if `Player` extends a parent class, Perl looks in the parent class (and so on and so on) until it finds a `number()` . If Perl finds `number()` , it calls that method with `$joel` as an invocant. You've seen this before with Moose; it works the same way here. Keeping Namespaces Clean The `namespace::autoclean` CPAN module can help avoid unintentional collisions between imported functions and methods. Moose provides `extends` to track inheritance relationships, but Perl uses a package global variable named `@ISA` . The method dispatcher looks in each class's `@ISA` to find the names of its parent classes. If `InjuredPlayer` extends `Player` , you might write: ``` package InjuredPlayer { @InjuredPlayer::ISA = 'Player'; } ``` The `parent` pragma (Pragmas) is cleaner: ``` package InjuredPlayer { use parent 'Player'; } ``` Moose has its own metamodel which stores extended inheritance information. This allows Moose to provide additional metaprogramming opportunities. You may inherit from multiple parent classes: ``` package InjuredPlayer; { use parent qw( Player Hospital::Patient ); } ``` ... though the caveats about multiple inheritance and method dispatch complexity apply. Consider instead roles (Roles) or Moose method modifiers. ### AUTOLOAD If there is no applicable method in the invocant's class or any of its superclasses, Perl will next look for an `AUTOLOAD()` function (AUTOLOAD) in every applicable class according to the selected method resolution order. Perl will invoke any `AUTOLOAD()` it finds. In the case of multiple inheritance, `AUTOLOAD()` can be very difficult to understand. ### Method Overriding and SUPER As with Moose, you may override methods in basic Perl OO. Unlike Moose, Perl provides no mechanism for indicating your intent to override a parent's method. Worse yet, any function you predeclare, declare, or import into the child class may silently override a method in the parent class. Even if you forget to use Moose's `override` system, at least it exists. Basic Perl OO offers no such protection. To override a parent method in a child class, declare a method of the same name. Within an overridden method, call the parent method with the `SUPER::` dispatch hint: ``` sub overridden { my $self = shift; warn 'Called overridden() in child!'; return $self->SUPER::overridden( @_ ); } ``` The `SUPER::` prefix to the method name tells the method dispatcher to dispatch to an overridden method of the appropriate name. You can provide your own arguments to the overridden method, but most code reuses `@_` . Be careful to `shift` off the invocant if you do. The Brokenness of `SUPER::` `SUPER::` has a confusing misfeature: it dispatches to the parent of the package into which the overridden method was compiled. If you've imported this method from another package, Perl will happily dispatch to the wrong parent. The desire for backwards compatibility has kept this misfeature in place. The `SUPER` module from the CPAN offers a workaround. Moose's `super()` does not suffer the same problem. ### Strategies for Coping with Blessed References Blessed references may seem simultaneously minimal and confusing. Moose is much easier to use, so use it whenever possible. If you do find yourself maintaining code which uses blessed references, or if you can't convince your team to use Moose in full yet, you can work around some of the problems of blessed references with a few rules of thumb: * Do not mix functions and methods in the same class. * Use a single .pm file for each class, unless the class is a small, self-contained helper used from a single place. * Follow Perl standards, such as naming constructors `new()` and using `$self` as the invocant name. * Use accessor methods pervasively, even within methods in your class. A module such as `Class::Accessor` helps to avoid repetitive boilerplate. * Avoid `AUTOLOAD()` where possible. If you must use it, use function forward declarations (Declaring Functions) to avoid ambiguity. * Expect that someone, somewhere will eventually need to subclass (or delegate to or reimplement the interface of) your classes. Make it easier for them by not assuming details of the internals of your code, by using the two-argument form of `bless` , and by breaking your classes into the smallest responsible units of code. * Use helper modules such as `Role::Tiny` to allow better use and reuse. ## Reflection Reflection (or introspection) is the process of asking a program about itself as it runs. By treating code as data you can manage code in the same way that you manage data. That sounds like a truism, but it's an important insight into modern programming. It's also a principle behind code generation (Code Generation). Moose's `Class::MOP` (Class::MOP) simplifies many reflection tasks for object systems. Several other Perl idioms help you inspect and manipulate running programs. ### Checking that a Module Has Loaded If you know the name of a module, you can check that Perl believes it has loaded that module by looking in the `%INC` hash. When Perl loads code with `use` or `require` , it stores an entry in `%INC` where the key is the file path of the module to load and the value is the full path on disk to that module. In other words, loading `Modern::Perl` effectively does: ``` $INC{'Modern/Perl.pm'} = '.../lib/site_perl/5.22.1/Modern/Perl.pm'; ``` The details of the path will vary depending on your installation. To test that Perl has successfully loaded a module, convert the name of the module into the canonical file form and test for that key's existence within `%INC` : ``` sub module_loaded { (my $modname = shift) =~ s!::!/!g; return exists $INC{ $modname . '.pm' }; } ``` As with `@INC` , any code anywhere may manipulate `%INC` . Some modules (such as `Test::MockObject` or `Test::MockModule` ) manipulate `%INC` for good reasons. Depending on your paranoia level, you may check the path and the expected contents of the package yourself. The `Class::Load` CPAN module's `is_class_loaded()` function does all of this for you without making you manipulate `%INC` . ### Checking that a Package Exists To check that a package exists somewhere in your program—if some code somewhere has executed a `package` directive with a given name—check that the package inherits from `UNIVERSAL` . Anything which extends `UNIVERSAL` must somehow provide the `can()` method (whether by inheriting it from `UNIVERSAL` or overriding it). If no such package exists, Perl will throw an exception about an invalid invocant, so wrap this call in an `eval` block: ``` say "$pkg exists" if eval { $pkg->can( 'can' ) }; ``` An alternate approach is to grovel through Perl's symbol tables. You're on your own here. ### Checking that a Class Exists Because Perl makes no strong distinction between packages and classes, the best you can do without Moose is to check that a package of the expected class name exists. You can check that the package `can()` provide `new()` , but there is no guarantee that any `new()` found is either a method or a constructor. ### Checking a Module Version Number Modules do not have to provide version numbers, but every package inherits the `VERSION()` method from the universal parent class `UNIVERSAL` (The UNIVERSAL Package): ``` my $version = $module->VERSION; ``` `VERSION()` returns the given module's version number, if defined. Otherwise it returns `undef` . If the module does not exist, the method will likewise return `undef` . ### Checking that a Function Exists To check whether a function exists in a package, call `can()` as a class method on the package name: ``` say "$func() exists" if $pkg->can( $func ); ``` Perl will throw an exception unless `$pkg` is a valid invocant; wrap the method call in an `eval` block if you have any doubts about its validity. Beware that a function implemented in terms of `AUTOLOAD()` (AUTOLOAD) may report the wrong answer if the function's package has not predeclared the function or overridden `can()` correctly. This is a bug in the other package. Use this technique to determine if a module's `import()` has imported a function into the current namespace: ``` say "$func() imported!" if __PACKAGE__->can( $func ); ``` As with checking for the existence of a package, you can root around in symbol tables yourself, if you have the patience for it. ### Checking that a Method Exists There is no foolproof way for reflection to distinguish between a function or a method. ### Rooting Around in Symbol Tables A symbol table is a special type of hash where the keys are the names of package global symbols and the values are typeglobs. A typeglob is an internal data structure which can contain a scalar, an array, a hash, a filehandle, and a function—any or all at once. Access a symbol table as a hash by appending double-colons to the name of the package. For example, the symbol table for the `MonkeyGrinder` package is available as `%MonkeyGrinder::` . You can test the existence of specific symbol names within a symbol table with the `exists` operator (or manipulate the symbol table to add or remove symbols, if you like). Yet be aware that certain changes to the Perl core have modified the details of what typeglobs store and when and why. See the "Symbol Tables" section in `perldoc perlmod` for more details, then consider the other techniques explained earlier instead. If you really need to manipulate symbol tables and typeglobs, use the `Package::Stash` CPAN module. ## Advanced OO Perl Creating and using objects in Perl with Moose (Moose) is easy. Designing good programs is not. It's as easy to overdesign a program as it is to underdesign it. Only practical experience can help you understand the most important design techniques, but several principles can guide you. ### Favor Composition Over Inheritance Novice OO designs often overuse inheritance to reuse code and to exploit polymorphism. The result is a deep class hierarchy with responsibilities scattered all over the place. Maintaining this code is difficult—who knows where to add or edit behavior? What happens when code in one place conflicts with code declared elsewhere? Inheritance is only one of many tools for OO programmers. It's not always the right tool. It's often the wrong tool. A `Car` may extend `Vehicle::Wheeled` (an is-a relationship), but `Car` may better contain several `Wheel` objects as instance attributes (a has-a relationship). Decomposing complex classes into smaller, focused entities improves encapsulation and reduces the possibility that any one class or role does too much. Smaller, simpler, and better encapsulated entities are easier to understand, test, and maintain. ### Single Responsibility Principle When you design your object system, consider the responsibilities of each entity. For example, an `Employee` object may represent specific information about a person's name, contact information, and other personal data, while a `Job` object may represent business responsibilities. Separating these entities in terms of their responsibilities allows the `Employee` class to consider only the problem of managing information specific to who the person is and the `Job` class to represent what the person does. (Two `Employee` s may have a `Job` -sharing arrangement, for example, or one `Employee` may have the CFO and the COO `Job` s.) When each class has a single responsibility, you reduce coupling between classes and improve the encapsulation of class-specific data and behavior. ### Don't Repeat Yourself Complexity and duplication complicate development and maintenance. The DRY principle (Don't Repeat Yourself) is a reminder to seek out and to eliminate duplication within the system. Duplication exists in data as well as in code. Instead of repeating configuration information, user data, and other important artifacts of your system, create a single, canonical representation of that information from which you can generate the other artifacts. This principle helps you to find the optimal representation of your system and its data and reduces the possibility that duplicate information will get out of sync. ### Liskov Substitution Principle The Liskov substitution principle suggests that you should be able to substitute a specialization of a class or a role for the original without violating the original's API. In other words, an object should be as or more general with regard to what it expects and at least as specific about what it produces as the object it replaces. Imagine two classes, `Dessert` and its child class `PecanPie` . If the classes follow the Liskov substitution principle, you can replace every use of `Dessert` objects with `PecanPie` objects in the test suite, and everything should pass. See Reg Braithwaite's "IS-STRICTLY-EQUIVALENT-TO-A" http://weblog.raganwald.com/2008/04/is-strictly-equivalent-to.html. for more details. ### Subtypes and Coercions Moose allows you to declare and use types and extend them through subtypes to form ever more specialized descriptions of what your data represents and how it behaves. These type annotations help verify that the function and method parameters are correct—or can be coerced into the proper data types. For example, you may wish to allow people to provide dates to a `Ledger` entry as strings while representing them as `DateTime` instances internally. You can do this by creating a Date type and adding a coercion from string types. See ``` Moose::Util::TypeConstraints ``` and `MooseX::Types` for more information. ### Immutability With a well-designed object, you tell it what to do, not how to do it. If you find yourself accessing object instance data (even through accessor methods) outside of the object itself, you may have too much access to an object's internals. OO novices often treat objects as if they were bundles of records which use methods to get and set internal values. This simple technique leads to the unfortunate temptation to spread the object's responsibilities throughout the entire system. You can prevent inappropriate access by making your objects immutable. Provide the necessary data to their constructors, then disallow any modifications of this information from outside the class. Expose no methods to mutate instance data—make all of your public accessors read-only and use internal attribute writers sparingly. Once you've constructed such an object, you know it's always in a valid state. You can never modify its data to put it in an invalid state. This takes tremendous discipline, but the resulting systems are robust, testable, and maintainable. Some designs go as far as to prohibit the modification of instance data within the class itself. Date: 2014-01-01 Categories: Tags: Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. To program well, we must find the balance between getting the job done now and doing the job right. We must balance time, resources, and quality. Programs have bugs. Programs need maintenance and expansion. Programs have multiple programmers. A beautiful program that never delivers value is worthless, but an awful program that cannot be maintained is a risk waiting to happen. Skilled programmers understand their constraints and write the right code. To write Perl well, you must understand the language. You must also cultivate a sense of good taste for the language and the design of programs. The only way to do so is to practice—not just writing code, but maintaining and reading good code. This path has no shortcuts, but it does have guideposts. ## Writing Maintainable Perl Maintainability is the nebulous measurement of how easy it is to understand and modify a program. Write some code. Come back to it in six months (or six days). How long does it take you to find and fix a bug or add a feature? That's maintainability. Maintainability doesn't measure whether you have to look up the syntax for a builtin or a library function. It doesn't measure how someone who has never programmed before will or won't read your code. Assume you're talking to a competent programmer who understands the problem you're trying to solve. How much work does she have to put in to understand your code? What problems will she face in doing so? To write maintainable software, you need experience solving real problems, an understanding of the idioms and techniques and style of your programming language, and good taste. You can develop all of these by concentrating on a few principles. * Remove duplication. Bugs lurk in sections of repeated and similar code—when you fix a bug in one piece of code, did you fix it in others? When you updated one section, did you update the others? Well-designed systems have little duplication. They use functions, modules, objects, and roles to extract duplicate code into distinct components which accurately model the domain of the problem. The best designs sometimes allow you to add features by removing code. * Name entities well. Your code tells a story. Every name you choose for a variable, function, module, class, and role allows you to clarify or obfuscate your intent. Choose your names carefully. If you're having trouble choosing good names, you may need to rethink your design or study your problem in more detail. * Avoid unnecessary cleverness. Concise code is good, when it reveals the intention of the code. Clever code hides your intent behind flashy tricks. Perl allows you to write the right code at the right time. Choose the most obvious solution when possible. Experience and good taste will guide you. Some problems require clever solutions. When this happens, encapsulate this code behind a simple interface and document your cleverness. * Embrace simplicity. If everything else is equal, a simpler program is easier to maintain than a complex program. Simplicity means knowing what's most important and doing just that. Sometimes you need powerful, robust code. Sometimes you need a one-liner. Simplicity means building only what you need. This is no excuse to avoid error checking or modularity or validation or security. Simple code can use advanced features. Simple code can use CPAN modules, and many of them. Simple code may require work to understand. Yet simple code solves problems effectively, without unnecessary work. ## Writing Idiomatic Perl Perl borrows liberally from other languages. Perl lets you write the code you want to write. C programmers often write C-style Perl, just as Java programmers write Java-style Perl and Lisp programmers write Lispy Perl. Effective Perl programmers write Perlish Perl by embracing the language's idioms. * Understand community wisdom. Perl programmers often debate techniques and idioms fiercely. Perl programmers also often share their work, and not just on the CPAN. Pay attention; there's not always one and only one best way to do things. The interesting discussions happen about the tradeoffs between various ideals and styles. * Follow community norms. Perl is a community of toolsmiths who solve broad problems, including static code analysis ( `Perl::Critic` ), reformatting ( `Perl::Tidy` ), and private distribution systems ( `CPAN::Mini` , `Carton` , `Pinto` ). Take advantage of the CPAN infrastructure; follow the CPAN model of writing, documenting, packaging, testing, and distributing your code. * Read code. Join a mailing list such as Perl Beginners (http://learn.perl.org/faq/beginners.html) and otherwise immerse yourself in the community http://www.perl.org/community.html. Read code and try to answer questions—even if you never post your answers, writing code to solve one problem every work day will teach you an enormous amount very quickly. CPAN developers, <NAME>, and mailing list participants have hard-won experience solving problems in myriad ways. Talk to them. Read their code. Ask questions. Learn from them and let them guide—and learn from—you. ## Writing Effective Perl Writing maintainable code means designing maintainable code. Good design comes from good habits. * Write testable code. Writing an effective test suite (Testing) exercises the same design skills as writing effective code. Code is code. Good tests also give you the confidence to modify a program while keeping it running correctly. * Modularize. Enforce encapsulation and abstraction boundaries. Find the right interfaces between components. Name things well and put them where they belong. Modularity forces you to think about similarities and differences and points of communication where your design fits together. Find the pieces that don't fit well. Revise your design until they do fit. * Follow sensible coding standards. Effective guidelines discuss error handling, security, encapsulation, API design, project layout, and other facets of maintainable code. Excellent guidelines help developers communicate with each other with code. If you look at a new project and nothing surprises you, that's great! Your job is to solve problems with code. Let your code—and the infrastructure around it—speak clearly. * Exploit the CPAN. Perl programmers solve problems, then share those solutions. The CPAN is a force multiplier; search it first for a solution or partial solution to your problem. Invest time in research to find full or partial solutions you can reuse. It will pay off. If you find a bug, report it. Patch it, if possible. Submit a failing test case. Fix a typo. Ask for a feature. Say "Thank you!" Then, when you're ready, When you're ready—when you create something new or fix something old in a reusable way—share your code. ## Exceptions Good programmers anticipate the unexpected. Files that should exist won't. A huge disk that should never fill up will. The network that never goes down stops responding. The unbreakable database crashes and eats a table. The unexpected happens. Perl handles exceptional conditions through exceptions: a dynamically-scoped control flow mechanism designed to raise and handle errors. Robust software must handle them. If you can recover, great! If you can't, log the relevant information and retry. ### Throwing Exceptions Suppose you want to write a log file. If you can't open the file, something has gone wrong. Use `die` to throw an exception (or see The autodie Pragma): ``` sub open_log_file { my $name = shift; open my $fh, '>>', $name or die "Can't open log to '$name': $!"; return $fh; } ``` `die()` sets the global variable `$@` to its operand and immediately exits the current function without returning anything. This is known as throwing an exception. A thrown exception will continue up the call stack (Controlled Execution) until something catches it. If nothing catches the exception, the program will exit with an error. Exception handling uses the same dynamic scope (Dynamic Scope) as `local` symbols. ### Catching Exceptions Sometimes allowing an exception to end the program is useful. A program run from a timed process might throw an exception when the error logs are full, causing an SMS to go out to administrators. Other exceptions might not be fatal—your program might be able to recover from one. Another might give you a chance to save the user's work and exit cleanly. Use the block form of the `eval` operator to catch an exception: If the file open succeeds, `$fh` will contain the filehandle. If it fails, `$fh` will remain undefined and program flow will continue. The block argument to `eval` introduces a new scope, both lexical and dynamic. If `open_log_file()` called other functions and something eventually threw an exception, this `eval` could catch it. An exception handler is a blunt tool. It will catch all exceptions thrown in its dynamic scope. To check which exception you've caught (or if you've caught an exception at all), check the value of `$@` . Be sure to `local` ize `$@` before you attempt to catch an exception, as `$@` is a global variable: # caught exception if (my $exception = $@) { ... } ``` Copy `$@` to a lexical variable immediately to avoid the possibility of subsequent code clobbering the global variable `$@` . You never know what else has used an `eval` block elsewhere and reset `$@` . `$@` usually contains a string describing the exception. Inspect its contents to see whether you can handle the exception: ``` if (my $exception = $@) { die $exception unless $exception =~ /^Can't open logging/; $fh = log_to_syslog(); } ``` Rethrow an exception by calling `die()` again. Pass the existing exception or a new one as necessary. Applying regular expressions to string exceptions can be fragile, because error messages may change over time. This includes the core exceptions that Perl itself throws. Instead of throwing an exception as a string, you may use a reference—even a blessed reference—with `die` . This allows you to provide much more information in your exception: line numbers, files, and other debugging information. Retrieving information from a data structure is much easier than parsing data out of a string. Catch these exceptions as you would any other exception. The CPAN distribution `Exception::Class` makes creating and using exception objects easy: ``` package Zoo::Exceptions { use Exception::Class 'Zoo::AnimalEscaped', 'Zoo::HandlerEscaped'; } sub cage_open { my $self = shift; Zoo::AnimalEscaped->throw unless $self->contains_animal; ... } sub breakroom_open { my $self = shift; Zoo::HandlerEscaped->throw unless $self->contains_handler; ... } ``` Another fine option is `Throwable::Error` . ### Exception Caveats Though throwing exceptions is simple, catching them is less so. Using `$@` correctly requires you to navigate several subtle risks: * Un `local` ized uses in the same or a nested dynamic scope may modify `$@` * `$@` may contain an object which returns a false value in boolean context * A signal handler (especially the `DIE` signal handler) may change `$@` * The destruction of an object during scope exit may call `eval` and change `$@` Modern Perl has fixed some of these issues. Though they rarely occur, they're difficult to diagnose. The `Try::Tiny` CPAN distribution improves the safety of exception handling and the syntax: ``` use Try::Tiny; my $fh = try { open_log_file( 'monkeytown.log' ) } catch { log_exception( $_ ) }; ``` `try` replaces `eval` . The optional `catch` block executes only when `try` catches an exception. `catch` receives the caught exception as the topic variable `$_` . ### Built-in Exceptions Perl itself throws several exceptional conditions. `perldoc perldiag` lists several "trappable fatal errors". Some are syntax errors that Perl produces during failed compilations, but you can catch the others during runtime. The most interesting are: * Using a disallowed key in a locked hash (Locking Hashes) * Blessing a non-reference (Blessed References) * Calling a method on an invalid invocant (Moose) * Failing to find a method of the given name on the invocant * Using a tainted value in an unsafe fashion (Taint) * Modifying a read-only value * Performing an invalid operation on a reference (References) You can also catch exceptions produced by `autodie` (The autodie Pragma) and any lexical warnings promoted to exceptions (Registering Your Own Warnings). ## Pragmas Most Perl modules provide new functions or define classes (Moose). Others, such as `strict` or `warnings` , influence the behavior of the language itself. This second type of module is a pragma. By convention, pragma names are written in lower-case to differentiate them from other modules. ### Pragmas and Scope Pragmas work by exporting specific behavior or information into the lexical scopes of their callers. You've seen how declaring a lexical variable makes a symbol name available within a scope. Using a pragma makes its behavior effective within a scope as well: ``` { # $lexical not visible; strict not in effect { use strict; my $lexical = 'available here'; # $lexical is visible; strict is in effect } # $lexical again invisible; strict not in effect } ``` Just as lexical declarations affect inner scopes, pragmas maintain their effects within inner scopes: ``` # file scope use strict; { # inner scope, but strict still in effect my $inner = 'another lexical'; } ``` ### Using Pragmas `use` a pragma as you would any other module. Pragmas may take arguments, such as a minimum version number to use or a list of arguments to change their behaviors: ``` # require variable declarations, prohibit barewords use strict qw( subs vars ); # rely on the semantics of the 2014 book use Modern::Perl '2014'; ``` Sometimes you need to disable all or part of those effects within a further nested lexical scope. The `no` builtin performs an unimport (Importing), which reverses some or all effects of a well-behaved pragma. For example, to disable the protection of `strict` when you need to do something symbolic: ``` use Modern::Perl; # or use strict; { no strict 'refs'; # manipulate the symbol table here } ``` ### Useful Pragmas Perl includes several useful core pragmas. * the `strict` pragma enables compiler checking of symbolic references, bareword use, and variable declaration. * the `warnings` pragma enables optional warnings for deprecated, unintended, and awkward behaviors. * the `utf8` pragma tells Perl's parser to understand the source code of the current file with the UTF-8 encoding. * the `autodie` pragma enables automatic error checking of system calls and builtins. * the `constant` pragma allows you to create compile-time constant values (though see the CPAN's `Const::Fast` for an alternative). * the `vars` pragma allows you to declare package global variables, such as `$VERSION` or `@ISA` (Blessed References). * the `feature` pragma allows you to enable and disable newer features of Perl individually. Where `use 5.18;` enables all of the Perl 5.18 features and the `strict` pragma, `use feature ':5.18';` does the same. This pragma is more useful to disable individual features in a lexical scope. * the `experimental` pragma enables or disables experimental features such as signatures (Real Function Signatures) or postfix dereferencing. * the `less` pragma demonstrates how to write a pragma. As you might suspect from `less` , you can write your own lexical pragmas in pure Perl. `perldoc perlpragma` explains how to do so, while the explanation of `$^H` in `perldoc perlvar` explains how the feature works. The CPAN has begun to gather non-core pragmas: * `autovivification` disables autovivification (Autovivification) * `indirect` prevents the use of indirect invocation (Indirect Objects) * `autobox` enables object-like behavior for Perl's core types (scalars, references, arrays, and hashes). * `perl5i` combines and enables many experimental language extensions into a coherent whole. These tools are not widely used yet, but they have their champions. `autovivification` and `indirect` can help you write more correct code. `autobox` and `perl5i` are experiments with what Perl might one day become; they're worth playing with in small projects. Date: 2009-03-01 Categories: Tags: Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. You can learn a lot of syntax from a book by writing small programs to solve the example problems. Writing good code to solve real problems takes more discipline and understanding. You must learn to manage code. How do you know that it works? How do you organize it? What makes it robust in the face of errors? What makes code clean? Clear? Maintainable? Modern Perl helps you answer all those questions. ## Testing You've already tested your code. If you've ever run it, noticed something wasn't quite right, made a change, and then ran it again, you've tested your code. Testing is the process of verifying that your software behaves as intended. Effective testing automates that process. Rather than relying on humans to perform repeated manual checks perfectly, let the computer do it. Perl's tools help you write the right tests. ### Test::More The fundamental unit of testing is a test assertion. Every test assertion is a simple question with a yes or no answer: does this code behave as I intended? Any condition you can test in your program can (eventually) become one or more assertions. A complex program may have thousands of individual conditions. That's fine. That's testable. Isolating specific behaviors into individual assertions helps you debug errors of coding and errors of understanding, and it makes your code and tests easier to maintain. Perl testing begins with the core module `Test::More` and its `ok()` function. `ok()` takes two parameters, a boolean value and a string which describes the test's purpose: The function `done_testing()` tells `Test::More` that the program has executed all of the assertions you expected to run. If the program exited unexpectedly (from an uncaught exception, a call to `exit` , or whatever), the test framework will notify you that something went wrong. Without a mechanism like `done_testing()` , how would you know? While this example code is too simple to fail, code that's too simple to fail fails far more often than you want. `Test::More` allows an optional test plan to count the number of individual assertions you plan to run: ``` use Test::More tests => 4; The `tests` argument to `Test::More` sets the test plan for the program. This is a safety net. If fewer than four tests ran, something went wrong. If more than four tests ran, something went wrong. `done_testing()` is easier, but sometimes an exact count can be useful (when you want to control the number of assertions in a loop, for example). ### Running Tests This example test file is a complete Perl program which produces the output: ``` ok 1 - the number one should be true not ok 2 - ... and zero should not # Failed test '... and zero should not' # at truth_values.t line 4. not ok 3 - the empty string should be false # Failed test 'the empty string should be false' # at truth_values.t line 5. ok 4 - ... and a non-empty string should not 1..4 # Looks like you failed 2 tests of 4. ``` This output uses a test output format called TAP, the Test Anything Protocol http://testanything.org/. Failed TAP tests produce diagnostic messages for debugging purposes. This is easy enough to read, but it's only four assertions. A real program may have thousands of assertions. In most cases, you want to know either that everything passed or the specifics of any failures. The core module The program `prove` —built on the core module `TAP::Harness` —runs tests, interprets TAP, and displays only the most pertinent information: ``` $ prove truth_values.t truth_values.t .. 1/? # Failed test '... and zero should not' # at truth_values.t line 4. # Failed test 'the empty string should be false' # at truth_values.t line 5. # Looks like you failed 2 tests of 4. truth_values.t .. Dubious, test returned 2 (wstat 512, 0x200) Failed 2/4 subtests Test Summary Report ------------------- truth_values.t (Wstat: 512 Tests: 4 Failed: 2) Failed tests: 2-3 ``` That's a lot of output to display what is already obvious: the second and third tests fail because zero and the empty string evaluate to false. Fortunately, it's easy to fix those failing tests (Boolean Coercion): ``` ok ! 0, '... and zero should not'; ok ! '', 'the empty string should be false'; ``` With those two changes, `prove` now displays: ``` $ prove truth_values.t truth_values.t .. ok All tests successful. ``` See `perldoc prove` for other test options, such as running tests in parallel ( `-j` ), automatically adding the relative directory lib/ to Perl's include path ( `-l` ), recursively running all test files found under t/ ( `-r t` ), and running slow tests first ( `--state=slow,save` ). The Bash shell alias `proveall` combines many of these options: ``` alias proveall='prove -j9 --state=slow,save -lr t' ``` ### Better Comparisons Even though the heart of all automated testing is the boolean condition "is this true or false?", reducing everything to that boolean condition is tedious and produces awkward diagnostics. `Test::More` provides several other convenient assertion functions. The `is()` function compares two values using Perl's `eq` operator. If the values are equal, the test passes: ``` is 4, 2 + 2, 'addition should work'; is 'pancake', 100, 'pancakes are numeric'; ``` The first test passes and the second fails with a diagnostic message: ``` t/is_tests.t .. 1/2 # Failed test 'pancakes are numeric' # at t/is_tests.t line 8. # got: 'pancake' # expected: '100' # Looks like you failed 1 test of 2. ``` Where `ok()` only provides the line number of the failing test, `is()` displays the expected and received values. `is()` applies implicit scalar context to its values (Prototypes). This means, for example, that you can check the number of elements in an array without explicitly evaluating the array in scalar context, and it's why you can omit the parentheses: ``` my @cousins = qw( <NAME> <NAME> <NAME> ); is @cousins, 6, 'I should have only six cousins'; ``` ... though some people prefer to write `scalar @cousins` for the sake of clarity. `Test::More` 's corresponding `isnt()` function compares two values using the `ne` operator and passes if they are not equal. It also provides scalar context to its operands. Both `is()` and `isnt()` apply string comparisons with the `eq` and `ne` operators. This almost always does the right thing, but for strict numeric comparisons or complex values such as objects with overloading (Overloading) or dual vars (Dualvars), use the `cmp_ok()` function. This function takes the first value to compare, a comparison operator, and the second value to compare: ``` cmp_ok 100, '<=', $cur_balance, 'I should have at least $100'; cmp_ok $monkey, '==', $ape, 'Simian numifications should agree'; ``` If you're concerned about string equality with numeric comparisons—a reasonable concern—then use `cmp_ok()` instead of `is()` . Classes and objects provide their own interesting ways to interact with tests. Test that a class or object extends another class (Inheritance) with `isa_ok()` : ``` my $chimpzilla = RobotMonkey->new; isa_ok $chimpzilla, 'Robot'; isa_ok $chimpzilla, 'Monkey'; ``` `isa_ok()` provides its own diagnostic message on failure. `can_ok()` verifies that a class or object can perform the requested method (or methods): ``` can_ok $chimpzilla, 'eat_banana'; can_ok $chimpzilla, 'transform', 'destroy_tokyo'; ``` The `is_deeply()` function compares two references to ensure that their contents are equal: ``` use Clone; my $numbers = [ 4, 8, 15, 16, 23, 42 ]; my $clonenums = Clone::clone( $numbers ); is_deeply $numbers, $clonenums, 'clone() should produce identical items'; ``` If the comparison fails, `Test::More` will do its best to provide a reasonable diagnostic indicating the position of the first inequality between the structures. See the CPAN modules `Test::Differences` and `Test::Deep` for more configurable tests. `Test::More` has several other more specialized test functions. ### Organizing Tests CPAN distributions should include a t/ directory containing one or more test files named with the .t suffix. When you build a distribution, the testing step runs all of the t/*.t files, summarizes their output, and succeeds or fails based on the results of the test suite as a whole. Two organization strategies are popular: * Each .t file should correspond to a .pm file * Each .t file should correspond to a logical feature A hybrid approach is the most flexible; one test can verify that all of your modules compile, while other tests demonstrate that each module behaves as intended. As your project grows, the second approach is easier to manage. Keep your test files small and focused and they'll be easier to maintain. Separate test files can also speed up development. If you're adding the ability to breathe fire to your `RobotMonkey` , you may want only to run the t/robot_monkey/breathe_fire.t test file. When you have the feature working to your satisfaction, run the entire test suite to verify that local changes have no unintended global effects. ### Other Testing Modules `Test::More` relies on a testing backend known as `Test::Builder` which manages the test plan and coordinates the test output into TAP. This design allows multiple test modules to share the same `Test::Builder` backend. Consequently, the CPAN has hundreds of test modules available—and they can all work together in the same program. * `Test::Fatal` helps test that your code throws (and does not throw) exceptions appropriately. You may also encounter `Test::Exception` . * `Test::MockObject` and `Test::MockModule` allow you to test difficult interfaces by mocking (emulating behavior to produce controlled results). * `Test::WWW::Mechanize` helps test web applications, while `Plack::Test` , `Plack::Test::Agent` , and the subclass ``` Test::WWW::Mechanize::PSGI ``` can do so without using an external live web server. * `Test::Database` provides functions to test the use and abuse of databases. `DBICx::TestDatabase` helps test schemas built with `DBIx::Class` . * `Test::Class` offers an alternate mechanism for organizing test suites. It allows you to create classes in which specific methods group tests. You can inherit from test classes just as your code classes inherit from each other. This is an excellent way to reduce duplication in test suites. See Curtis Poe's excellent `Test::Class` series http://www.modernperlbooks.com/mt/2009/03/organizing-test-suites-with-testclass.html. The newer `Test::Routine` distribution offers similar possibilities through the use of Moose (Moose). * `Test::Differences` tests strings and data structures for equality and displays any differences in its diagnostics. `Test::LongString` adds similar assertions. * `Test::Deep` tests the equivalence of nested data structures (Nested Data Structures). * `Devel::Cover` analyzes the execution of your test suite to report on the amount of your code your tests actually exercises. In general, the more coverage the better—although 100% coverage is not always possible, 95% is far better than 80%. * `Test::Most` gathers several useful test modules into one parent module. It saves time and effort. See the Perl QA project http://qa.perl.org/ for more information about testing in Perl. ## Handling Warnings While there's more than one way to write a working Perl program, some of those ways can be confusing, unclear, and even incorrect. Perl's warnings system can help you avoid these situations. ### Producing Warnings Use the `warn` builtin to emit a warning: ``` warn 'Something went wrong!'; ``` `warn` prints a list of values to the STDERR filehandle (Input and Output). Perl will append the filename and line number of the `warn` call unless the last element of the list ends in a newline. The core `Carp` module extends Perl's warning mechanisms. Its `carp()` function reports a warning from the perspective of the calling code. Given a function like: ``` use Carp 'carp'; sub only_two_arguments { my ($lop, $rop) = @_; carp( 'Too many arguments provided' ) if @_ > 2; ... } ``` ... the arity (Arity) warning will include the filename and line number of the calling code, not `only_two_arguments()` . `Carp` 's `cluck()` is similar, but it produces a backtrace of all function calls which led to the current function. `Carp` 's verbose mode adds backtraces to all warnings produced by `carp()` and `croak()` (Reporting Errors) throughout the entire program: ``` $ perl -MCarp=verbose my_prog.pl ``` Use `Carp` when writing modules (Modules) instead of `warn` or `die` . Injecting Carp Sometimes you'll have to debug code written without the use of `carp()` or `cluck()` . In that case, use the `Carp::Always` module to add backtraces to all `warn` or `die` calls: ``` perl -MCarp::Always some_program.pl ``` . ### Enabling and Disabling Warnings The venerable `-w` command-line flag enables warnings throughout the program, even in external modules written and maintained by other people. It's all or nothing—though it can help you if you have the time and energy to eliminate warnings and potential warnings throughout the entire codebase. This was the only way to enable warnings in Perl programs for many years. The modern approach is to use the `warnings` pragma (or an equivalent such as `use Modern::Perl;` ). This enables warnings in lexical scopes. If you've used `warnings` in a scope, you're indicating that the code should not normally produce warnings. Global Warnings Flags The `-W` flag enables warnings throughout the program unilaterally, regardless of any use of `warnings` . The `-X` flag disables warnings throughout the program unilaterally. Neither is common. All of `-w` , `-W` , and `-X` affect the value of the global variable `$^W` . Code written before the `warnings` pragma came about in spring 2000 may `local` ize `$^W` to suppress certain warnings within a given scope. ### Disabling Warning Categories Use `no warnings;` with an argument list to disable selective warnings within a scope. Omitting the argument list disables all warnings within that scope. `perldoc perllexwarn` lists all of the warnings categories your version of Perl understands. Most of them represent truly interesting conditions, but some may be actively unhelpful in your specific circumstances. For example, the `recursion` warning will occur if Perl detects that a function has called itself more than a hundred times. If you are confident in your ability to write recursion-ending conditions, you may disable this warning within the scope of the recursion—though tail calls may be better (Tail Calls). If you're generating code (Code Generation) or locally redefining symbols, you may wish to disable the `redefine` warnings. Some experienced Perl hackers disable the `uninitialized` value warnings in string-processing code which concatenates values from many sources. If you're careful about initializing your variables, you may never need to disable this warning, but sometimes the warning gets in the way of writing concise code in your local style. ### Making Warnings Fatal If your project considers warnings as onerous as errors, you can make them fatal. To promote all warnings into exceptions within a lexical scope: ``` use warnings FATAL => 'all'; ``` You may also make specific categories of warnings fatal, such as the use of deprecated constructs: ``` use warnings FATAL => 'deprecated'; ``` With proper discipline, this can produce very robust code—but be cautious. Many warnings come from conditions that Perl can detect only when your code is running. If your test suite fails to identify all of the warnings you might encounter, fatalizing these warnings may cause your program to crash. Newer versions of Perl often add new warnings. Upgrading to a new version without careful testing might cause new exceptional conditions. More than that, any custom warnings you or the libraries you use will also be fatal (Registering Your Own Warnings). If you enable fatal warnings, do so only in code that you control and never in library code you expect other people to use. ### Catching Warnings If you're willing to work for it, you can catch warnings as you would exceptions. The `%SIG` variable (see `perldoc perlvar` ) contains handlers for out-of-band signals raised by Perl or your operating system. Assign a function reference to `$SIG{__WARN__}` to catch a warning: ``` { my $warning; local $SIG{__WARN__} = sub { $warning .= shift }; # do something risky ... say "Caught warning:\n$warning" if $warning; } ``` Within the warning handler, the first argument is the warning's message. Admittedly, this technique is less useful than disabling warnings lexically—but it can come to good use in test modules such as `Test::Warnings` from the CPAN, where the actual text of the warning is important. `%SIG` is a global variable, so `local` ize it in the smallest possible scope. ### Registering Your Own Warnings The `warnings::register` pragma allows you to create your own warnings which users can enable and disable lexically. From a module, `use` the pragma: use warnings::register; ``` This will create a new warnings category named after the package `Scary::Monkey` . Enable these warnings with ``` use warnings 'Scary::Monkey' ``` and disable them with ``` no warnings 'Scary::Monkey' ``` . Use `warnings::enabled()` to test if the caller's lexical scope has enabled a warning category. Use `warnings::warnif()` to produce a warning only if warnings are in effect. For example, to produce a warning in the `deprecated` category: use warnings::register; sub import { warnings::warnif( 'deprecated', 'empty imports from ' . __PACKAGE__ . ' are now deprecated' ) unless @_; } ``` See `perldoc perllexwarn` for more details. ## Files Most programs interact with the real world mostly by reading, writing, and otherwise manipulating files. Perl began as a tool for system administrators and is still a language well suited for text processing. ### Input and Output A filehandle represents the current state of one specific channel of input or output. Every Perl program starts with three standard filehandles, `STDIN` (the input to the program), `STDOUT` (the output from the program), and `STDERR` (the error output from the program). By default, everything you `say` goes to `STDOUT` , while errors and warnings go to `STDERR` . This separation of output allows you to redirect useful output and errors to two different places—an output file and error logs, for example. Use the `open` builtin to initialize a filehandle. To open a file for reading: ``` open my $fh, '<', 'filename' or die "Cannot read '$filename': $!\n"; ``` The first operand is a lexical which will contain the filehandle. The second operand is the file mode, which determines the type of file operation (reading, writing, appending, et cetera). The final operand is the name of the file on which to operate. If the `open` fails, the `die` clause will throw an exception, with the reason for failure in the `$!` magic variable. You may open files for writing, appending, reading and writing, and more. Some of the most important file modes are: * `<` , which opens a file for reading. * `>` , which open for writing, clobbering existing contents if the file exists and creating a new file otherwise. * `>>` , which opens a file for writing, appending to any existing contents and creating a new file otherwise. * `+<` , which opens a file for both reading and writing. * `-|` , which opens a pipe to an external process for reading. * `|-` , which opens a pipe to an external process for writing. You may also create filehandles which read from or write to plain Perl scalars, using any existing file mode: ``` open my $read_fh, '<', \$fake_input; open my $write_fh, '>', \$captured_output; do_something_awesome( $read_fh, $write_fh ); ``` `perldoc perlopentut` explains in detail more exotic uses of `open` , including its ability to launch and control other processes, as well as the use of `sysopen` for finer-grained control over input and output. `perldoc perlfaq5` includes working code for many common IO tasks. Remember `autodie` ? Assume the examples in this section have `use autodie;` enabled so as to elide explicit error handling. If you choose not to use `autodie` , check the return values of all system calls to handle errors appropriately. # Unicode, IO Layers, and File Modes In addition to the file mode, you may add an IO encoding layer which allows Perl to encode to or decode from a Unicode encoding. For example, to read a file written in the UTF-8 encoding: ``` open my $in_fh, '<:encoding(UTF-8)', $infile; ``` ... or to write to a file using the UTF-8 encoding: ``` open my $out_fh, '>:encoding(UTF-8)', $outfile; ``` # Two-argument `open` Older code often uses the two-argument form of `open()` , which jams the file mode with the name of the file to open: ``` open my $fh, "> $file" or die "Cannot write to '$file': $!\n"; ``` Perl must extract the file mode from the filename. That's a risk; anytime Perl has to guess at what you mean, it may guess incorrectly. Worse, if `$file` came from untrusted user input, you have a potential security problem, as any unexpected characters could change how your program behaves. The three-argument `open()` is a safer replacement for this code. The Many Names of `DATA` The special package global `DATA` filehandle represents the current file of source code. When Perl finishes compiling a file, it leaves `DATA` open and pointing to the end of the compilation unit if the file has a `__DATA__` or `__END__` section. Any text which occurs after that token is available for reading from `DATA` . The entire file is available if you use `seek` to rewind the filehandle. This is useful for short, self-contained programs. See `perldoc perldata` for more details. # Reading from Files Given a filehandle opened for input, read from it with the `readline` builtin, also written as `<>` . A common idiom reads a line at a time in a `while()` loop: while (<$fh>) { chomp; say "Read a line '$_'"; } ``` In scalar context, `readline` reads a single line of the file and returns it, or `undef` if it's reached the end of file (test that condition with the `eof` builtin). Each iteration in this example returns the next line or `undef` . This `while` idiom explicitly checks the definedness of the variable used for iteration, so only the end of file condition will end the loop. This idiom is equivalent to: while (defined($_ = <$fh>)) { chomp; say "Read a line '$_'"; last if eof $fh; } ``` Why use `while` and not `for` ? `for` imposes list context on its operands. When in list context, `readline` will read the entire file before processing any of it. `while` performs iteration and reads a line at a time. When memory use is a concern, use `while` . Every line read from `readline` includes the character or characters which mark the end of a line. In most cases, this is a platform-specific sequence consisting of a newline ( `\n` ), a carriage return ( `\r` ), or a combination of the two ( `\r\n` ). Use `chomp` to remove it. The cleanest way to read a file line-by-line in Perl is: ``` open my $fh, '<', $filename; while (my $line = <$fh>) { chomp $line; ... } ``` Perl assumes that files contain text by default. If you're reading binary data—a media file or a compressed file, for example—use `binmode` before performing any IO. This will force Perl to treat the file data as pure data, without modifying it in any way, such as translating `\n` into the platform-specific newline sequence. While Unix-like platforms may not always need `binmode` , portable programs play it safe (Unicode and Strings). # Writing to Files Given a filehandle open for output, `say` to write to the file: ``` open my $out_fh, '>', 'output_file.txt'; print $out_fh "Here's a line of text\n"; say $out_fh "... and here's another"; ``` Note the lack of comma between the filehandle and the next operand. Filehandle Disambiguation Damian Conway's Perl Best Practices recommends enclosing the filehandle in curly braces as a habit. This is necessary to disambiguate parsing of a filehandle contained in anything other than a plain scalar—a filehandle in an array or hash or returned from an object method—and it won't hurt anything in the simpler cases. Both `say` take a list of operands. Perl uses the magic global `$,` as the separator between list values. Perl uses any value of `$\` as the final argument to `\n` as an implicit final argument to `say` ). Remember that `$\` is `undef` by default. These two examples produce the same result: ``` my @princes = qw( <NAME> ... ); local $\ = "\n\n"; # prints a list of princes, followed by two newlines print @princes; local $\ = ''; print join( $,, @princes ) . "\n\n"; ``` # Closing Files When you've finished working with a file, `close` its filehandle explicitly or allow it to go out of scope. Perl will close it for you. The benefit of calling `close` explicitly is that you can check for—and recover from—specific errors, such as running out of space on a storage device or a broken network connection. As usual, `autodie` handles these checks for you: ``` use autodie qw( open close ); open my $fh, '>', $file; close $fh; ``` # Special File Handling Variables For every line read, Perl increments the value of the variable `$.` , which serves as a line counter. `readline` uses the current contents of `$/` as the line-ending sequence. The value of this variable defaults to the most appropriate line-ending character sequence for text files on your current platform. The word line is a misnomer, however. `$/` can contain any sequence of characters (but not a regular expression). This is useful for highly-structured data in which you want to read a record at a time. Given a file with records separated by two blank lines, set `$/` to `\n\n` to read a record at a time. Use `chomp` on a record read from the file to remove the double-newline sequence. Perl buffers its output by default, performing IO only when the amount of pending output exceeds a threshold. This allows Perl to batch up expensive IO operations instead of always writing very small amounts of data. Yet sometimes you want to send data as soon as you have it without waiting for that buffering—especially if you're writing a command-line filter connected to other programs or a line-oriented network service. The `$|` variable controls buffering on the currently active output filehandle. When set to a non-zero value, Perl will flush the output after each write to the filehandle. When set to a zero value, Perl will use its default buffering strategy. Automatic Flushing Files default to a fully-buffered strategy. `STDOUT` when connected to an active terminal—but not another program—uses a line-buffered strategy, where Perl flushes `STDOUT` every time it encounters a newline in the output. Instead of cluttering your code with a global variable, use the `autoflush()` method to change the buffering behavior of a lexical filehandle: ``` open my $fh, '>', 'pecan.log'; $fh->autoflush( 1 ); ``` You can call any method provided by `IO::File` on a filehandle. For example, the `input_line_number()` and ``` input_record_separator() ``` methods do the job of `$.` and `$/` on individual filehandles. See the documentation for `IO::File` , `IO::Handle` , and `IO::Seekable` . ### Directories and Paths Working with directories is similar to working with files, except that you cannot write to directories. Open a directory handle with the `opendir` builtin: ``` opendir my $dirh, '/home/monkeytamer/tasks/'; ``` The `readdir` builtin reads from a directory. As with `readline` , you may iterate over the contents of directories one entry at a time or you may assign everything to an array in one swoop: ``` # iteration while (my $file = readdir $dirh) { ... } # flatten into a list, assign to array my @files = readdir $otherdirh; ``` In a `while` loop, `readdir` sets `$_` : ``` opendir my $dirh, 'tasks/circus/'; while (readdir $dirh) { next if /^\./; say "Found a task $_!"; } ``` The curious regular expression in this example skips so-called hidden files on Unix and Unix-like systems, where a leading dot prevents them from appearing in directory listings by default. It also skips the two special files `.` and `..` , which represent the current directory and the parent directory respectively. The names returned from `readdir` are relative to the directory itself. (Remember that an absolute path is a path fully qualified to its filesystem.) If the tasks/ directory contains three files named eat, drink, and be_monkey, `readdir` will return `eat` , `drink` , and `be_monkey` instead of tasks/eat, tasks/drink, and task/be_monkey. Close a directory handle with the `closedir` builtin or by letting it go out of scope. # Manipulating Paths Perl offers a Unixy view of your filesystem and will interpret Unix-style paths appropriately for your operating system and filesystem. If you're using Microsoft Windows, you can use the path C:/My Documents/Robots/Bender/ just as easily as you can use the path C:\My Documents\Robots\Caprica Six\. Even though Perl uses Unix file semantics consistently, cross-platform file manipulation is much easier with a module. The core `File::Spec` module family lets you manipulate file paths safely and portably. It's a little clunky, but it's well documented. The `Path::Class` distribution on the CPAN has a nicer interface. Use the `dir()` function to create an object representing a directory and the `file()` function to create an object representing a file: ``` use Path::Class; my $meals = dir( 'tasks', 'cooking' ); my $file = file( 'tasks', 'health', 'robots.txt' ); ``` You can get file objects from directories and vice versa: ``` my $lunch = $meals->file( 'veggie_calzone' ); my $robots_dir = $robot_list->dir; ``` You can even open filehandles to directories and files: ``` my $dir_fh = $dir->open; my $robots_fh = $robot_list->open( 'r' ) or die "Open failed: $!"; ``` Both `Path::Class::Dir` and `Path::Class::File` offer further useful behaviors—though beware that if you use a `Path::Class` object of some kind with an operator or function which expects a string containing a file path, you need to stringify the object yourself. This is a persistent but minor annoyance. (If you find it burdensome, try `Path::Tiny` as an alternative.) ``` my $contents = read_from_filename( "$lunch" ); ``` ### File Manipulation Besides reading and writing files, you can also manipulate them as you would directly from a command line or a file manager. The file test operators, collectively called the `-X` operators, examine file and directory attributes. To test that a file exists: ``` say 'Present!' if -e $filename; ``` The `-e` operator has a single operand, either the name of a file or handle to a file or directory. If the file or directory exists, the expression will evaluate to a true value. `perldoc -f -X` lists all other file tests. `-f` returns a true value if its operand is a plain file. `-d` returns a true value if its operand is a directory. `-r` returns a true value if the file permissions of its operand permit reading by the current user. `-s` returns a true value if its operand is a non-empty file. Look up the documentation for any of these operators with `perldoc -f -r` , for example. The `rename` builtin can rename a file or move it between directories. It takes two operands, the old path of the file and the new path: ``` rename 'death_star.txt', 'carbon_sink.txt'; # or if you're stylish: rename 'death_star.txt' => 'carbon_sink.txt'; ``` There's no core builtin to copy a file, but the core `File::Copy` module provides both `copy()` and `move()` functions. Use the `unlink` builtin to remove one or more files. (The `delete` builtin deletes an element from a hash, not a file from the filesystem.) These functions and builtins all return true values on success and set `$!` on error. `Path::Class` also provides convenience methods to remove files completely and portably as well as to check certain file attributes. Perl tracks its current working directory. By default, this is the active directory from where you launched the program. The core `Cwd` module's `cwd()` function returns the name of the current working directory. The builtin `chdir` attempts to change the current working directory. Working from the correct directory is essential to working with files with relative paths. The CPAN module `File::chdir` makes manipulating the current working directory easier. If you're a fan of the command line and use `pushd` and `popd` , see also `File::pushd` . ## Modules You've seen functions, classes, and data structure used to organize code. Perl's next mechanism for organization and extension is the module. A module is a package contained in its own file and loadable with `use` or `require` . A module must be valid Perl code. It must end with an expression which evaluates to a true value so that the Perl parser knows it has loaded and compiled the module successfully. There are no other requirements—only strong conventions. When you load a module, Perl splits the package name on double-colons ( `::` ) and turns the components of the package name into a file path. This means that `use StrangeMonkey;` causes Perl to search for a file named StrangeMonkey.pm in every directory in `@INC` in order, until it finds one or exhausts the list. Similarly, ``` use StrangeMonkey::Persistence; ``` causes Perl to search for a file named `Persistence.pm` in every directory named StrangeMonkey/ present in every directory in `@INC` , and so on. ``` use StrangeMonkey::UI::Mobile; ``` causes Perl to search for a relative file path of StrangeMonkey/UI/Mobile.pm in every directory in `@INC` . The resulting file may or may not contain a package declaration matching its filename—there is no such technical requirement—but you'll cause confusion without that match. `perldoc` Tricks ``` perldoc -l Module::Name ``` will print the full path to the relevant .pm file, if that file contains documentation in POD form. ``` perldoc -lm Module::Name ``` will print the full path to the .pm file. ``` perldoc -m Module::Name ``` will display the contents of the .pm file. ### Organizing Code with Modules Perl does not require you to use modules, packages, or namespaces. You may put all of your code in a single .pl file, or in multiple .pl files you `require` as necessary. You have the flexibility to manage your code in the most appropriate way, given your development style, the formality and risk and reward of the project, your experience, and your comfort with deploying code. Even so, a project with more than a couple of hundred lines of code benefits from module organization: * Modules help to enforce a logical separation between distinct entities in the system. * Modules provide an API boundary, whether procedural or OO. * Modules suggest a natural organization of source code. * The Perl ecosystem has many tools devoted to creating, maintaining, organizing, and deploying modules and distributions. * Modules provide a mechanism of code reuse. Even if you do not use an object-oriented approach, modeling every distinct entity or responsibility in your system with its own module keeps related code together and separate code separate. ### Using and Importing When you load a module with `use` , Perl loads it from disk, then calls its `import()` method with any arguments you provided. That `import()` method takes a list of names and exports functions and other symbols into the calling namespace. This is merely convention; a module may decline to provide an `import()` , or its `import()` may perform other behaviors. Pragmas (Pragmas) such as `strict` use arguments to change the behavior of the calling lexical scope instead of exporting symbols: ``` use strict; # ... calls strict->import() use File::Spec::Functions 'tmpdir'; # ... calls File::Spec::Functions->import( 'tmpdir' ) use feature qw( say unicode_strings ); # ... calls feature->import( qw( say unicode_strings ) ) ``` The `no` builtin calls a module's `unimport()` method, if it exists, passing any arguments. This is most common with pragmas which introduce or modify behavior through `import()` : ``` use strict; # no symbolic references or barewords # variable declaration required { no strict 'refs'; # symbolic references allowed # strict 'subs' and 'vars' still in effect } ``` Both `use` and `no` take effect during compilation, such that: ``` use Module::Name qw( list of arguments ); ``` ``` BEGIN { require 'Module/Name.pm'; Module::Name->import( qw( list of arguments ) ); } ``` Similarly: ``` no Module::Name qw( list of arguments ); ``` ``` BEGIN { require 'Module/Name.pm'; Module::Name->unimport(qw( list of arguments )); } ``` ... including the `require` of the module. Missing Methods Never Missed If `import()` or `unimport()` does not exist in the module, Perl will produce no error. These methods are truly optional. You may call `import()` and `unimport()` directly, though outside of a `BEGIN` block it makes little sense to do so; after compilation has completed, the effects of `import()` or `unimport()` may have little effect (given that these methods tend to modify the compilation process by importing symbols or toggling features). Portable programs are careful about case even if they don't have to be. Both `use` and `require` are case-sensitive. While Perl knows the difference between `strict` and `Strict` , your combination of operating system and file system may not. If you were to write `use Strict;` , Perl would not find strict.pm on a case-sensitive filesystem. With a case-insensitive filesystem, Perl would happily load Strict.pm, but nothing would happen when it tried to call `Strict->import()` . (strict.pm declares a package named `strict` . `Strict` does not exist and thus has no `import()` method, which is not an error.) ### Exporting A module can make package global symbols available to other packages through a process known as exporting—often by calling `import()` implicitly or directly. The core module `Exporter` is the standard way to export symbols from a module. `Exporter` relies on the presence of package global variables such as `@EXPORT_OK` and `@EXPORT` , which list symbols to export when requested. Consider a ``` StrangeMonkey::Utilities ``` module which provides several standalone functions: ``` package StrangeMonkey::Utilities; use Exporter 'import'; our @EXPORT_OK = qw( round translate screech ); ... ``` Any other code now can use this module and, optionally, import any or all of the three exported functions. You may also export variables: ``` push @EXPORT_OK, qw( $spider $saki $squirrel ); ``` Export symbols by default by listing them in `@EXPORT` instead of `@EXPORT_OK` : ``` our @EXPORT = qw( monkey_dance monkey_sleep ); ``` ... so that any ``` use StrangeMonkey::Utilities; ``` will import both functions. Be aware that specifying symbols to import will not import default symbols; you only get what you request. To load a module without importing any symbols, use an explicit empty list: ``` # make the module available, but import() nothing use StrangeMonkey::Utilities (); ``` Regardless of any import lists, you can always call functions in another package with their fully-qualified names: ``` StrangeMonkey::Utilities::screech(); ``` Simplified Exporting The CPAN module `Sub::Exporter` provides a nicer interface to export functions without using package globals. It also offers more powerful options. However, `Exporter` can export variables, while `Sub::Exporter` only exports functions. The CPAN module `Moose::Exporter` offers a powerful mechanism to work with Moose-based systems, but the learning curve is not shallow. ## Distributions A distribution is a collection of metadata and modules (Modules) into a single redistributable, testable, and installable unit. The easiest way to configure, build, package, test, and install Perl code is to follow the CPAN's conventions. These conventions govern how to package a distribution, how to resolve its dependencies, where to install the code and documentation, how to verify that it works, how to display documentation, and how to manage a repository. These guidelines have arisen from the rough consensus of thousands of contributors working on tens of thousands of projects. A distribution built to CPAN standards can be tested on several versions of Perl on several different hardware platforms within a few hours of its uploading, with errors reported automatically to authors—all without human intervention. When people talk about CPAN being Perl's secret weapon, this is what they mean. You may choose never to release any of your code as public CPAN distributions, but you can use CPAN tools and conventions to manage even private code. The Perl community has built amazing infrastructure. Take advantage of it. ### Attributes of a Distribution Besides modules, a distribution includes several files and directories: * Build.PL or Makefile.PL, a driver program used to configure, build, test, bundle, and install the distribution. * MANIFEST, a list of all files contained in the distribution. This helps tools verify that a bundle is complete. * META.yml and/or META.json, a file containing metadata about the distribution and its dependencies. * README, a description of the distribution, its intent, and its copyright and licensing information. * lib/, the directory containing Perl modules. * t/, a directory containing test files. * Changes, a human-readable log of every significant change to the distribution. A well-formed distribution must contain a unique name and single version number (often taken from its primary module). Any distribution you download from the public CPAN should conform to these standards. The public CPANTS service http://cpants.perl.org/ evaluates each uploaded distribution against packaging guidelines and conventions and recommends improvements. Following the CPANTS guidelines doesn't mean the code works, but it does mean that CPAN packaging and installation tools should understand the distribution. ### CPAN Tools for Managing Distributions The Perl core includes several tools to manage distributions: * `CPAN.pm` is the official CPAN client. While by default this client installs distributions from the public CPAN, you can also use your own repository instead of or in addition to the public repository. * `ExtUtils::MakeMaker` is a complex but well-used system of modules used to package, build, test, and install Perl distributions. It works with Makefile.PL files. * `Test::More` (Testing) is the basic and most widely used testing module used to write automated tests for Perl software. * `TAP::Harness` and `prove` (Running Tests) run tests and interpret and report their results. In addition, several non-core CPAN modules make your life easier as a developer: * `App::cpanminus` is a configuration-free CPAN client. It handles the most common cases, uses little memory, and works quickly. * `App::perlbrew` helps you to manage multiple installations of Perl. Install new versions of Perl for testing or production, or to isolate applications and their dependencies. * `CPAN::Mini` and the `cpanmini` command allow you to create your own (private) mirror of the public CPAN. You can inject your own distributions into this repository and manage which versions of the public modules are available in your organization. * `Dist::Zilla` automates away common distribution tasks. While it uses either `Module::Build` or `ExtUtils::MakeMaker` , it can replace your use of them directly. See http://dzil.org/ for an interactive tutorial. * `Test::Reporter` allows you to report the results of running the automated test suites of distributions you install, giving their authors more data on any failures. * Carton and Pinto are two newer projects which help manage and install code's dependencies. Neither is in widespread use yet, but they're both under active development. * `Module::Build` is an alternative to `ExtUtils::MakeMaker` , written in pure Perl. While it has advantages, it's not as widely used or maintained. ### Designing Distributions The process of designing a distribution could fill a book (such as <NAME>'s Writing Perl Modules for CPAN), but a few design principles will help you. Start with a utility such as `Module::Starter` or `Dist::Zilla` . The initial cost of learning the configuration and rules may seem like a steep investment, but the benefit of having everything set up the right way (and in the case of `Dist::Zilla` , never going out of date) relieves you of tedious busywork. A distribution should follow several non-code guidelines: * Each distribution performs a single, well-defined purpose. That purpose may even include gathering several related distributions into a single installable bundle. Decompose your software into individual distributions to manage their dependencies appropriately and to respect their encapsulation. * Each distribution contains a single version number. Version numbers must always increase. The semantic version policy http://semver.org/ is sane and compatible with Perl's approach. * Each distribution provides a well-defined API. A comprehensive automated test suite can verify that you maintain this API across versions. If you use a local CPAN mirror to install your own distributions, you can re-use the CPAN infrastructure for testing distributions and their dependencies. You get easy access to integration testing across reusable components. * Distribution tests are useful and repeatable. The CPAN infrastructure supports automated test reporting. Use it! * Interfaces are simple and effective. Avoid the use of global symbols and default exports; allow people to use only what they need. Do not pollute their namespaces. ## The UNIVERSAL Package Perl's builtin `UNIVERSAL` package is the ancestor of all other packages—it's the ultimate parent class in the object-oriented sense (Moose). `UNIVERSAL` provides a few methods for its children to use, inherit, or override. ### The VERSION() Method The `VERSION()` method returns the value of the `$VERSION` variable of the invoking package or class. If you provide a version number as an optional parameter, the method will throw an exception if the queried `$VERSION` is not equal to or greater than the parameter. Given a `HowlerMonkey` module of version `1.23` , its `VERSION()` method behaves as: ``` my $hm = HowlerMonkey->new; say HowlerMonkey->VERSION; # prints 1.23 say $hm->VERSION; # prints 1.23 say $hm->VERSION( 0.0 ); # prints 1.23 say $hm->VERSION( 1.23 ); # prints 1.23 say $hm->VERSION( 2.0 ); # exception! ``` There's little reason to override `VERSION()` . ### The DOES() Method The `DOES()` method supports the use of roles (Roles) in programs. Pass it an invocant and the name of a role, and the method will return true if the appropriate class somehow does that role through inheritance, delegation, composition, role application, or any other mechanism. The default implementation of `DOES()` falls back to `isa()` , because inheritance is one mechanism by which a class may do a role. Given a `Cappuchin` , its `DOES()` method behaves as: ``` say Cappuchin->DOES( 'Monkey' ); # prints 1 say $cappy->DOES( 'Monkey' ); # prints 1 say Cappuchin->DOES( 'Invertebrate' ); # prints 0 ``` Override `DOES()` if you manually consume a role or otherwise somehow provide allomorphic equivalence. ### The can() Method The `can()` method takes a string containing the name of a method or function. It returns a function reference, if it exists. Otherwise, it returns a false value. You may call this on a class, an object, or the name of a package. Given a class named `SpiderMonkey` with a method named `screech` , get a reference to the method with: ``` if (my $meth = SpiderMonkey->can( 'screech' )) {...} ``` This technique leads to the pattern of checking for a method's existence before dispatching to it: ``` if (my $meth = $sm->can( 'screech' ) { # method; not a function $sm->$meth(); } ``` Use `can()` to test if a package implements a specific function or method: ``` use Class::Load; die "Couldn't load $module!" unless load_class( $module ); if (my $register = $module->can( 'register' )) { # function; not a method $register->(); } ``` `Module::Pluggable` The CPAN module `Class::Load` simplifies the work of loading classes by name. `Module::Pluggable` makes it easier to build and manage plugin systems. Get to know both distributions. ### The isa() Method The `isa()` method takes a string containing the name of a class or the name of a core type ( `SCALAR` , `ARRAY` , `HASH` , `Regexp` , `IO` , and `CODE` ). Call it as a class method or an instance method on an object. `isa()` returns a true value if its invocant is or derives from the named class, or if the invocant is a blessed reference to the given type. Given an object `$pepper` (a hash reference blessed into the `Monkey` class, which inherits from the `Mammal` class), its `isa()` method behaves as: ``` say $pepper->isa( 'Monkey' ); # prints 1 say $pepper->isa( 'Mammal' ); # prints 1 say $pepper->isa( 'HASH' ); # prints 1 say Monkey->isa( 'Mammal' ); # prints 1 say $pepper->isa( 'Dolphin' ); # prints 0 say $pepper->isa( 'ARRAY' ); # prints 0 say Monkey->isa( 'HASH' ); # prints 0 ``` Any class may override `isa()` . This can be useful when working with mock objects ( `Test::MockObject` and `Test::MockModule` , for example) or with code that does not use roles (Roles). Be aware that any class which does override `isa()` generally has a good reason for doing so. Does a Class Exist? While both `UNIVERSAL::isa()` and `UNIVERSAL::can()` are methods (Method-Function Equivalence), you may safely use the latter as a function solely to determine whether a class exists in Perl. If ``` UNIVERSAL::can( $classname, 'can' ) ``` returns a true value, someone somewhere has defined a class of the name `$classname` . That class may not be usable, but it does exist. ### Extending UNIVERSAL It's tempting to store other methods in `UNIVERSAL` to make them available to all other classes and objects in Perl. Avoid this temptation; this global behavior can have subtle side effects, especially in code you didn't write and don't maintain. With that said, occasional abuse of `UNIVERSAL` for debugging purposes and to fix improper default behavior may be excusable. For example, <NAME>'s `UNIVERSAL::ref` distribution makes the nearly-useless `ref()` operator usable. The `UNIVERSAL::can` and `UNIVERSAL::isa` distributions can help you debug anti-polymorphism bugs (Method-Function Equivalence). `Perl::Critic` can detect those and other problems. Outside of very carefully controlled code and very specific, very pragmatic situations, there's no reason to put code in `UNIVERSAL` directly, especially given the other design alternatives. ## Code Generation Novice programmers write more code than they need to write. They start with long lists of procedural code, then discover functions, then parameters, then objects, and—perhaps—higher-order functions and closures. As you improve your skills, you'll write less code to solve the same problems. You'll use better abstractions. You'll write more general code. You can reuse code—and when you can add features by deleting code, you'll achieve something great. Writing programs to write programs for you—metaprogramming or code generation—allows you to build reusable abstractions. While you can make a huge mess, you can also build amazing things. Metaprogramming techniques make Moose possible, for example (Moose). The `AUTOLOAD` technique (AUTOLOAD) for missing functions and methods demonstrates this technique in a specific form: Perl's function and method dispatch system allows you to control what happens when normal lookup fails. ### eval The simplest code generation technique is to build a string containing a snippet of valid Perl and compile it with the string `eval` operator. Unlike the exception-catching block `eval` operator, string `eval` compiles the contents of the string within the current scope, including the current package and lexical bindings. A common use for this technique is providing a fallback if you can't (or don't want to) load an optional dependency: ``` eval { require Monkey::Tracer } or eval 'sub Monkey::Tracer::log {}'; ``` If `Monkey::Tracer` is not available, this code defines a `log()` function which will do nothing. This simple example is deceptive; getting `eval` right takes effort. You must handle quoting issues to include variables within your `eval` d code. Add more complexity to interpolate some variables but not others: ``` sub generate_accessors { my ($methname, $attrname) = @_; eval <<"END_ACCESSOR"; sub get_$methname { my \$self = shift; return \$self->{$attrname}; } sub set_$methname { my (\$self, \$value) = \@_; \$self->{$attrname} = \$value; } END_ACCESSOR } ``` Woe to those who forget a backslash! Good luck convincing your syntax highlighter what's happening! Worse yet, each invocation of string `eval` builds a new data structure representing the entire code, and compiling code isn't free. Yet even with its limitations, this technique is simple and useful. ### Parametric Closures While building accessors and mutators with `eval` is straightforward, closures (Closures) allow you to add parameters to generated code at compilation time without requiring additional evaluation: ``` sub generate_accessors { my $attrname = shift; my $getter = sub { my $self = shift; return $self->{$attrname}; }; my $setter = sub { my ($self, $value) = @_; $self->{$attrname} = $value; }; return $getter, $setter; } ``` This code avoids unpleasant quoting issues and compiles each closure only once. It limits the memory used by sharing the compiled code between all closure instances. All that differs is the binding to the `$attrname` lexical. In a long-running process or a class with a lot of accessors, this technique can be very useful. Installing into symbol tables is reasonably easy, if ugly: ``` my ($get, $set) = generate_accessors( 'pie' ); no strict 'refs'; *{ 'get_pie' } = $get; *{ 'set_pie' } = $set; ``` Think of the asterisk as a typeglob sigil, where a typeglob is Perl jargon for "symbol table". Dereferencing a string like this refers to a symbol in the current symbol table, which is the section of the current namespace which contains globally-accessible symbols such as package globals, functions, and methods. Assigning a reference to a symbol table entry installs or replaces that entry. To promote an anonymous function to a method, store that function's reference in the symbol table. Assigning to a symbol table symbol with a string, not a literal variable name, is a symbolic reference. You must disable `strict` reference checking for the operation. Many programs have a subtle bug in similar code, as they assign and generate in a single line: ``` no strict 'refs'; *{ $methname } = sub { # subtle bug: strict refs disabled here too }; ``` This example disables strictures for the outer block as well as the body of the function itself. Only the assignment violates strict reference checking, so disable strictures for that operation alone: ``` { my $sub = sub { ... }; no strict 'refs'; *{ $methname } = $sub; } ``` If the name of the method is a string literal in your source code, rather than the contents of a variable, you can assign to the relevant symbol directly: ``` { no warnings 'once'; (*get_pie, *set_pie) = generate_accessors( 'pie' ); } ``` Assigning directly to the glob does not violate strictures, but mentioning each glob only once does produce a "used only once" warning you can disable with the `warnings` pragma. ### Compile-time Manipulation Unlike code written explicitly as code, code generated through string `eval` gets compiled while your program is running. Where you might expect a normal function to be available throughout the lifetime of your program, a generated function might not be available when you expect it. Force Perl to run code—to generate other code—during compilation by wrapping it in a `BEGIN` block. When the Perl parser encounters a block labeled `BEGIN` , it parses and compiles the entire block, then runs it (unless it has syntax errors). When the block finishes running, parsing will continue as if there had been no interruption. The difference between writing: ``` sub get_age { ... } sub set_age { ... } sub get_name { ... } sub set_name { ... } sub get_weight { ... } sub set_weight { ... } ``` ... and: BEGIN { for my $accessor (qw( age name weight )) { my ($get, $set) = make_accessors( $accessor ); no strict 'refs'; *{ 'get_' . $accessor } = $get; *{ 'set_' . $accessor } = $set; } } ``` ... is primarily one of maintainability. You could argue for and against either form. Within a module, any code outside of functions executes when you `use` the module, because of the implicit `BEGIN` Perl adds around the `require` and `import` (Importing). Any code outside of a function but inside the module will execute before the `import()` call occurs. If you `require` the module, there is no implicit `BEGIN` block. After parsing finishes, Perl will run code outside of the functions. Beware of the interaction between lexical declaration (the association of a name with a scope) and lexical assignment. The former happens during compilation, while the latter occurs at the point of execution. This code has a subtle bug: ``` use UNIVERSAL::require; # buggy; do not use my $wanted_package = 'Monkey::Jetpack'; BEGIN { $wanted_package->require; $wanted_package->import; } ``` ... because the `BEGIN` block will execute before the assignment of the string value to `$wanted_package` occurs. The result will be an exception from attempting to invoke the `require()` method on an undefined value. The `UNIVERSAL::require` CPAN distribution adds a `require()` method to `UNIVERSAL` . ### Class::MOP Unlike installing function references to populate namespaces and to create methods, there's no simple way to create classes dynamically in Perl. Moose comes to the rescue, with its bundled `Class::MOP` library. It provides a meta object protocol—a mechanism for creating and manipulating an object system by manipulating objects. Rather than writing your own fragile string `eval` code or trying to poke into symbol tables manually, you can manipulate the entities and abstractions of your program with objects and methods. To create a class: ``` use Class::MOP; my $class = Class::MOP::Class->create( 'Monkey::Wrench' ); ``` Add attributes and methods to this class when you create it: ``` my $class = Class::MOP::Class->create( 'Monkey::Wrench' => ( attributes => [ Class::MOP::Attribute->new( '$material' ), Class::MOP::Attribute->new( '$color' ), ], methods => { tighten => sub { ... }, loosen => sub { ... }, }, ), ); ``` ... or to the metaclass (the object which represents that class) once created: ``` $class->add_attribute( experience => Class::MOP::Attribute->new( '$xp' ) ); $class->add_method( bash_zombie => sub { ... } ); ``` A MOP gives you more than the ability to create new entities as the program runs. You get to look inside existing (MOP-aware) code. For example, to determine the characteristics of the class, use the `Class::MOP::Class` methods: ``` my @attrs = $class->get_all_attributes; my @meths = $class->get_all_methods; ``` Similarly ``` Class::MOP::Attribute ``` and `Class::MOP::Method` allow you to create and manipulate and introspect attributes and methods. ## Overloading Perl is not a pervasively object oriented language. Its core data types (scalars, arrays, and hashes) are not objects with methods, but you can control the behavior of your own classes and objects, especially when they undergo coercion or contextual evaluation. This is overloading. Overloading is subtle but powerful. Consider how an object behaves in boolean context. In boolean context, an object will evaluate to a true value, unless you overload boolification. Why would you do this? Suppose you're using the Null Object pattern http://www.c2.com/cgi/wiki?NullObject to make your own objects appear false in boolean context. You can overload an object's behavior for almost every operation or coercion: stringification, numification, boolification, iteration, invocation, array access, hash access, arithmetic operations, comparison operations, smart match, bitwise operations, and even assignment. Stringification, numification, and boolification are the most important and most common. ### Overloading Common Operations The `overload` pragma associates functions with overloadable operations. Pass the pragma argument pairs, where the key is the name of a type of overload and the value is a function reference. A `Null` class which overloads boolean evaluation so that it always evaluates to a false value might resemble: ``` package Null { use overload 'bool' => sub { 0 }; It's easy to add a stringification: ``` package Null { use overload 'bool' => sub { 0 }, '""' => sub { '(null)' }; } ``` Overriding numification is more complex, because arithmetic operators tend to be binary ops (Arity). Given two operands both with overloaded methods for addition, which overloading should take precedence? The answer needs to be consistent, easy to explain, and understandable by people who haven't read the source code of the implementation. `perldoc overload` attempts to explain this in the sections labeled Calling Conventions for Binary Operations and MAGIC AUTOGENERATION, but the easiest solution is to overload numification (keyed by `'0+'` ) and tell `overload` to use the provided overloads as fallbacks: ``` package Null { use overload 'bool' => sub { 0 }, '""' => sub { '(null)' }, '0+' => sub { 0 }, fallback => 1; } ``` Setting `fallback` to a true value gives Perl the option to use any other defined overloads to perform an operation. If that's not possible, Perl will act as if there were no overloads in effect. This is often what you want. Without `fallback` , Perl will only use the specific overloadings you have provided. If someone tries to perform an operation you have not overloaded, Perl will throw an exception. ### Overload and Inheritance Subclasses inherit overloadings from their ancestors. They may override this behavior in one of two ways. If the parent class defines overloadings in terms of function references, a child class must do the same to override its parent's behavior. The alternative is to define overloadings in terms of method name. This allows child classes to customize their behavior by overriding those methods: ``` package Null { use overload 'bool' => 'get_bool', '""' => 'get_string', '0+' => 'get_num', fallback => 1; sub get_bool { 0 } } ``` Any child class can do something different for boolification by overriding `get_bool()` : ``` package Null::ButTrue { use parent 'Null'; sub get_bool { 1 } } ``` ### Uses of Overloading Overloading may seem like a tempting tool to use to produce symbolic shortcuts for new operations. The `IO::All` CPAN distribution pushes this idea to its limit to produce a simple and elegant API. Yet for every brilliant API refined through the appropriate use of overloading, a dozen more messes congeal. Sometimes the best code eschews cleverness in favor of simplicity. Overriding addition, multiplication, and even concatenation on a `Matrix` class makes sense because the existing notation for those operations is pervasive. A new problem domain without that established notation is a poor candidate for overloading, as is a problem domain where you have to squint to make Perl's existing operators match a different notation. Damian Conway's Perl Best Practices suggests one other use for overloading: to prevent the accidental abuse of objects. For example, overloading numification to `croak()` for objects which have no reasonable single numeric representation can help you find and fix real bugs. ## Taint Some Perl features can help you write secure programs. These tools are no substitute for careful thought and planning, but they reward caution and understanding and can help you avoid subtle mistakes. Taint mode (or taint) is a sticky piece of metadata attached to all data which comes from outside of your program. Any data derived from tainted data is also tainted. You may use tainted data within your program, but if you use it to affect the outside world—if you use it insecurely—Perl will throw a fatal exception. ### Using Taint Mode `perldoc perlsec` explains taint mode in copious detail. Launch your program with the `-T` command-line argument to enable taint mode. If you use this argument on the `#!` line of a program, you must run the program directly. If you run it as ``` perl mytaintedappl.pl ``` and neglect the `-T` flag, Perl will exit with an exception—by the time Perl encounters the flag on the `#!` line, it's missed its opportunity to taint the environment data in `%ENV` , for example. ### Sources of Taint Taint can come from two places: file input and the program's operating environment. The former is anything you read from a file or collect from users in the case of web or network programming. The latter includes any command-line arguments, environment variables, and data from system calls. Even operations such as reading from a directory handle produce tainted data. The `tainted()` function from the core module `Scalar::Util` returns true if its argument is tainted: ``` die 'Oh no! Tainted data!' if Scalar::Util::tainted( $sketchy_data ); ``` ### Removing Taint from Data To remove taint, you must extract known-good portions of the data with a regular expression capture. That captured data will be untainted. For example, if your user input consists of a US telephone number, you can untaint it with: ``` die 'Number still tainted!' unless $number =~ /(\(/d{3}\) \d{3}-\d{4})/; my $safe_number = $1; ``` The more specific your pattern is about what you allow, the more secure your program can be. The opposite approach of denying specific items or forms runs the risk of overlooking something harmful. Far better to disallow something that's safe but unexpected than that to allow something harmful which appears safe. Even so, nothing prevents you from writing a capture for the entire contents of a variable—but in that case, why use taint? ### Removing Taint from the Environment The superglobal `%ENV` represents the environment variables of the system where you're running your program. This data is tainted because forces outside of the program's control can manipulate values there. Any environment variable which modifies how Perl or the shell finds files and directories is an attack vector. A taint-sensitive program should delete several keys from `%ENV` and set `$ENV{PATH}` to a specific and well-secured path: ``` delete @ENV{ qw( IFS CDPATH ENV BASH_ENV ) }; $ENV{PATH} = '/path/to/app/binaries/'; ``` If you do not set `$ENV{PATH}` appropriately, you will receive messages about its insecurity. If this environment variable contained the current working directory, or if it contained relative directories, or if the directories could be modified by anyone else on the system, a clever attacker could perpetrate mischief. For similar reasons, `@INC` does not contain the current working directory under taint mode. Perl will also ignore the `PERL5LIB` and `PERLLIB` environment variables. Use the `lib` pragma or the `-I` flag to `perl` to add library directories to the program. ### Taint Gotchas Taint mode is all or nothing. It's either on or off. This sometimes leads people to use permissive patterns to untaint data and, thus, gives the illusion of security. In that case, taint is busywork which provides no real security. Review your untainting rules carefully. Unfortunately, not all modules handle tainted data appropriately. This is a bug which CPAN authors should take more seriously. If you have to make legacy code taint-safe, consider the use of the `-t` flag, which enables taint mode but reduces taint violations from exceptions to warnings. This is not a substitute for full taint mode, but it allows you to secure existing programs without the all or nothing approach of `-T` . Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. "Simple" means different things to different programmers. Effective programmers understand how Perl's features interact and combine. Their fluent code takes advantage of language patterns and idioms. The result of this Perlish thinking is concise, powerful, and useful code—and it's simple when you understand it. ## Idioms Every language has common patterns of expression, or idioms. The earth revolves, but we speak of the sun rising or setting. We brag about clever hacks but cringe at nasty hacks and code smells. Perl has idioms; they're both language features and design techniques. They're mannerisms and mechanisms that give your code a Perlish accent. You don't have to use them to get your job done, but they play to Perl's strengths. ### The Object as `$self` Perl's object system (Moose) treats the invocant of a method as a mundane parameter. Regardless of whether you invoke a class or an instance method, the first element of `@_` is always the invocant. By convention, most Perl code uses `$class` as the name of the class method invocant and `$self` for the name of the object invocant. This convention is strong enough that useful extensions such as `Moops` assume you will use `$self` as the name of object invocants. ### Named Parameters Perl loves lists. Lists are a fundamental element of Perl. List flattening and binding lets you chain together multiple expressions to manipulate data in every way possible. While Perl's argument passing simplicity (everything flattens into `@_` ) is occasionally too simple, assigning from `@_` in list context allows you to unpack named parameters as pairs. The fat comma (Declaring Hashes) operator turns an ordinary list into an obvious list of pairs of arguments: ``` make_ice_cream_sundae( whipped_cream => 1, sprinkles => 1, banana => 0, ice_cream => 'mint chocolate chip', ); ``` You can unpack these parameters into a hash and treat that hash as if it were a single argument: ``` sub make_ice_cream_sundae { my %args = @_; my $dessert = get_ice_cream( $args{ice_cream} ); ... } ``` Hash or Hash Ref? Perl Best Practices suggests passing hash references instead. This allows Perl to perform caller-side validation of the hash reference. If you pass the wrong number of arguments, you'll get an error where you call the function. This technique works well with `import()` (Importing) or other methods; process as many parameters as you like before slurping the remainder into a hash: ``` sub import { my ($class, %args) = @_; my $calling_package = caller(); ... } ``` ### The Schwartzian Transform The Schwartzian transform is an elegant demonstration of the pervasive list handling idiom borrowed from Lisp. Suppose you have a Perl hash which associates the names of your co-workers with their phone extensions: ``` my %extensions = ( '000' => 'Damian', '002' => 'Wesley', '042' => 'Robin', '088' => 'Nic', ); ``` Hash Key Quoting Rules Fat comma hash key quoting only works on things that look like barewords. With the leading zero, these keys look like octal numbers. Everyone makes this mistake at least once. To sort this list by name alphabetically, you must sort the hash by its values, not its keys. Getting the values sorted correctly is easy: ``` my @sorted_names = sort values %extensions; ``` ... but you need an extra step to preserve the association of names and extensions, hence the Schwartzian transform. First, convert the hash into a list of data structures which will be easier to sort—in this case, two-element anonymous arrays: ``` my @pairs = map { [ $_, $extensions{$_} ] } keys %extensions; ``` `sort` takes this list of anonymous arrays and compares their second elements (the names) as strings: ``` my @sorted_pairs = sort { $a->[1] cmp $b->[1] } @pairs; ``` The block provided to `sort` receives arguments in two package-scoped (Scope) variables: `$a` and `$b` . (See `perldoc -f sort` for an extensive discussion of the implications of this scoping.) The `sort` block takes its arguments two at a time. The first becomes the contents of `$a` and the second the contents of `$b` . If `$a` should sort ahead of `$b` in the results, the block must return -1. If both values sort to the same position, the block must return 0. Finally, if `$a` should sort after `$b` in the results, the block should return 1. Any other return values are errors. Know Your Data Reversing the hash in place would work if no one had the same name. This particular data set presents no such problem, but code defensively. The `cmp` operator performs string comparisons and the `<=>` performs numeric comparisons. Given `@sorted_pairs` , a second `map` operation converts the data structure to a more usable form: ``` my @formatted_exts = map { "$_->[1], ext. $_->[0]" } @sorted_pairs; ``` ... and now you can print the whole thing: ``` say for @formatted_exts; ``` The Schwartzian transformation chains all of these expressions together to elide those temporary variables: ``` say for map { " $_->[1], ext. $_->[0]" } sort { $a->[1] cmp $b->[1] } map { [ $_ => $extensions{$_} ] } keys %extensions; ``` Read the expression from right to left, in evaluation order. For each key in the extensions hash, make a two-item anonymous array containing the key and the value. Sort that list of anonymous arrays by their second elements, the hash values. Format a string of output from those sorted arrays. The Schwartzian transform pipeline of `map` - `sort` - `map` transforms a data structure into another form easier for sorting and then transforms it back into the first from—or another form. While this sorting example is simple, consider the case of calculating a cryptographic hash for a large file. The Schwartzian transform is especially useful because it effectively caches any expensive calculations by performing them once in the first-executed `map` . ### Easy File Slurping `local` is essential to managing Perl's magic global variables. You must understand scope (Scope) to use `local` effectively—but if you do, you can use tight and lightweight scopes in interesting ways. For example, to slurp files into a scalar in a single expression: # or my $file; { local $/; $file = <$fh> }; ``` `$/` is the input record separator. `local` izing it sets its value to `undef` , pending assignment. As the value of the separator is undefined, Perl happily reads the entire contents of the filehandle in one swoop. Because a `do` block evaluates to the value of the last expression evaluated within the block, this evaluates to the data read from the filehandle: the contents of the file. At the end of the expression, `$/` has reverted to its previous state and `$file` contains the contents of the file. The second example avoids a second copy of the string containing the file's contents; it's not as pretty, but it uses the least amount of memory. `File::Slurper` This useful example is admittedly maddening for people who don't understand both `local` and scoping. The `File::Slurper` module from the CPAN is a worthy (and often faster) alternative. ### Handling Main Many programs commonly set up several file-scoped lexical variables before handing off processing to other functions. It's tempting to use these variables directly, rather than passing values to and returning values from functions, especially as programs grow. Unfortunately, these programs may come to rely on subtleties of what happens when during Perl's compilation process—a variable you thought would be initialized to a specific value may not get initialized until much later. Remember that Perl requires no special syntax for creating closures (Closures)—you can close over a lexical variable inadvertently. To avoid this, wrap the main code of your program in a single function, `main()` . Encapsulate your variables to their proper scopes. Then add a single line to the beginning of your program, after you've used all of the modules and pragmas you need: ``` #!/usr/bin/perl use Modern::Perl; exit main( @ARGV ); sub main { ... # successful exit return 0; } sub other_functions { ... } ``` Calling `main()` before anything else in the program forces you to be explicit about initialization and compilation order. Calling `exit` with `main()` 's return value prevents any other bare code from running. ### Controlled Execution The effective difference between a program and a module is in its intended use. Users invoke programs directly, while programs load modules after execution has already begun. Yet both modules and programs are merely Perl code. Making a module executable is easy. So is making a program behave as a module (useful for testing parts of an existing program without formally making a module). All you need to do is to discover how Perl began to execute a piece of code. `caller` 's single optional argument governs the number of call frames (Recursion) to look back through. `caller(0)` reports information about the current call frame. To allow a module to run correctly as a program or a module, put all executable code in functions, add a `main()` function, and write a single line at the start of the module: ``` main() unless caller(0); ``` If there's no caller for the module, someone invoked it directly as a program (with ``` perl path/to/Module.pm ``` instead of `use Module;` ). Improved Caller Inspection The eighth element of the list returned from `caller` in list context is a true value if the call frame represents `use` or `require` and `undef` otherwise. While that's more accurate, few people use it. ### Postfix Parameter Validation The CPAN has several modules which help verify the parameters of your functions; `Params::Validate` and ``` MooseX::Params::Validate ``` are two good options. Simple validation is easy even without those modules. Suppose your function takes exactly two arguments. You could write: ``` use Carp 'croak'; sub groom_monkeys { if (@_ != 2) { croak 'Can only groom two monkeys!'; } ... } ``` ... but from a linguistic perspective, the consequences are more important than the check and deserve to be at the start of the expression: ``` croak 'Can only groom two monkeys!' unless @_ == 2; ``` This early return technique—especially with postfix conditionals—can simplify the rest of the code. Each such assertion is effectively a single row in a truth table. Alternately, function signatures (Real Function Signatures) of some kind will handle this case for you. ### Regex En Passant Many Perl idioms rely on the fact that expressions evaluate to values: ``` say my $ext_num = my $extension = 42; ``` That clunky code demonstrates how to use the value of one expression in another expression. This isn't a new idea; you've likely used the return value of a function in a list or as an argument to another function before. You may not have realized its implications. Suppose you want to extract a first name from a first name plus surname combination with a precompiled regular expression in `$first_name_rx` : ``` my ($first_name) = $name =~ /($first_name_rx)/; ``` In list context, a successful regex match returns a list of all captures (Capturing, and Perl assigns the first one to `$first_name` . To remove all non-word characters to create a useful user name for a system account, you could write: ``` (my $normalized_name = $name) =~ tr/A-Za-z//dc; ``` Non-Destructive Substitutions Newer code can use the non-destructive substitution modifier `/r` : ``` my $normalized_name = $name =~ tr/A-Za-z//dcr; ``` . First, assign the value of `$name` to `$normalized_name` . The parentheses change precedence so that assignment happens first. The assignment expression evaluates to the variable `$normalized_name` . That variable becomes the first operand to the transliteration operator. This technique works on other in-place modification operators: ``` my $age = 14; (my $next_age = $age)++; say "I am $age, but next year I will be $next_age"; ``` ### Unary Coercions Perl's type system almost always does the right thing when you choose the correct operators. Use the string concatenation operator and Perl will treat both operands as strings. Use the addition operator and Perl will treat both operands as numeric. Occasionally you have to give Perl a hint about what you mean with a unary coercion to force a specific evaluation of a value. Add zero to treat a value as numeric: ``` my $numeric_value = 0 + $value; ``` Double negate a value to treat it as a boolean: ``` my $boolean_value = !! $value; ``` Concatenate a value with the empty string to treat it as a string: ``` my $string_value = '' . $value; ``` The need for these coercions is vanishingly rare, but it happens. While it may look like it would be safe to remove a "useless" `+ 0` from an expression, doing so may well break the code. ## Global Variables Perl provides several super global variables. They're not scoped to a package or file. They're really, truly global. Unfortunately, any direct or indirect modifications of these variables may change the behavior of other parts of the program. Experienced Perl hackers have memorized some of them. Few people have memorized all of them—they're terse. Only a handful are regularly useful. `perldoc perlvar` contains the exhaustive list of these variables. ### Managing Super Globals As Perl evolves, it moves more global behavior into lexical behavior, so that you can avoid many of these globals. When you must use them, use `local` in the smallest possible scope to constrain any modifications. You are still susceptible to any changes made to these variables from code you call, but you reduce the likelihood of surprising code outside of your scope. As the easy file slurping idiom (Easy File Slurping) demonstrates, `local` is often the right approach: The effect of `local` izing `$/` lasts only through the end of the block. There is a low chance that any Perl code will run as a result of reading lines from the filehandle and change the value of `$/` within the `do` block. Not all cases of using super globals are this easy to guard, but this often works. Other times you need to read the value of a super global and hope that no other code has modified it. Catching exceptions with an `eval` block is susceptible to at least one race condition where `DESTROY()` methods invoked on lexicals that have gone out of scope may reset `$@` : eval { ... }; if (my $exception = $@) { ... } ``` Copy `$@` immediately after catching an exception to preserve its contents. See also `Try::Tiny` instead (Exception Caveats). ### English Names The core `English` module provides verbose names for punctuation-heavy super globals. Import them into a namespace with: ``` use English '-no_match_vars'; # unnecessary in 5.20 and 5.22 ``` This allows you to use the verbose names documented in `perldoc perlvar` within the scope of this pragma. Three regex-related super globals ( `$&` , `$`` , and `$'` ) used to impose a global performance penalty for all regular expressions within a program. This has been fixed in Perl 5.20. If you forget the `-no_match_vars` import, your program will suffer the penalty even if you don't explicitly read from those variables. Modern Perl programs can use the `@-` variable instead of them. ### Useful Super Globals Most programs can get by with using only a couple of the super globals. You're most likely to encounter only a few of these variables. `$/` (or ``` $INPUT_RECORD_SEPARATOR ``` from the `English` pragma) is a string of zero or more characters which denotes the end of a record when reading input a record at a time. By default, this is your platform-specific newline character sequence. If you undefine this value, Perl will attempt to read the entire file into memory. If you set this value to a reference to an integer, Perl will try to read that many bytes per record (so beware of Unicode concerns). If you set this value to an empty string ( `''` ), Perl will read in a paragraph at a time, where a paragraph is a chunk of text followed by an arbitrary number of newlines. `$.` ( `$INPUT_LINE_NUMBER` ) contains the number of records read from the most recently-accessed filehandle. You can read from this variable, but writing to it has no effect. Localizing this variable will localize the filehandle to which it refers. Yes, that's confusing. `$|` ( `$OUTPUT_AUTOFLUSH` ) governs whether Perl will flush everything written to the currently selected filehandle immediately or only when Perl's buffer is full. Unbuffered output is useful when writing to a pipe or socket or terminal which should not block waiting for input. This variable will coerce any values assigned to it to boolean values. `@ARGV` contains the command-line arguments passed to the program. `$!` ( `$ERRNO` ) is a dualvar (Dualvars) which contains the result of the most recent system call. In numeric context, this corresponds to C's `errno` value, where anything other than zero indicates an error. In string context, this evaluates to the appropriate system error string. Localize this variable before making a system call (implicitly or explicitly) to avoid overwriting the `errno` value for other code elsewhere. Perl's internals make system calls sometimes, so the value of this variable can change out from under you. Copy it immediately after causing a system call for accurate results. `$"` ( `$LIST_SEPARATOR` ) contains the string used to separate array and list elements interpolated into a string. `%+` contains named captures from successful regular expression matches (Named Captures). `$@` ( `$EVAL_ERROR` ) contains the value thrown from the most recent exception (Catching Exceptions). `$0` ( `$PROGRAM_NAME` ) contains the name of the program currently executing. You may modify this value on some Unix-like platforms to change the name of the program as it appears to other programs on the system, such as `ps` or `top` . `$$` ( `$PID` ) contains the process id of the currently running instance of the program as the operating system understands it. This will vary between `fork()` ed programs and may vary between threads in the same program. `@INC` holds a list of filesystem paths in which Perl will look for files to load with `use` or `require` . See `perldoc -f require` for other items this array can contain. `%SIG` maps OS and low-level Perl signals to function references used to handle those signals. Trap the standard Ctrl-C interrupt by catching the `INT` signal, for example. See `perldoc perlipc` for more information about signals and signal handling. ### Alternatives to Super Globals IO and exceptions are the worst perpetrators of action at a distance. Use `Try::Tiny` (Exception Caveats) to insulate you from the tricky semantics of proper exception handling. `local` ize and copy the value of `$!` to avoid strange behaviors when Perl makes implicit system calls. Use `IO::File` and its methods on lexical filehandles (Special File Handling Variables) to limit unwanted global changes to IO behavior. Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. Perl is a malleable language. You can write programs in whichever creative, maintainable, obfuscated, or bizarre fashion you prefer. Good programmers write code that they want to maintain, but Perl won't decide for you what you consider maintainable. Perl isn't perfect. Some features are difficult to use correctly. Others seem great but don't work all that well. Some have strange edge cases. Knowing what to avoid in Perl—and when to avoid it—will help you write robust code that survives the twin tests of time and real users. ## Barewords Perl's parser understands Perl's builtins and operators. It uses sigils to identify variables and other punctuation to recognize function and method calls. Yet sometimes the parser has to guess what you mean, especially when you use a bareword—an identifier without a sigil or other syntactically significant punctuation. ### Good Uses of Barewords Though the `strict` pragma (Pragmas) rightly forbids ambiguous barewords, some barewords are acceptable. # Bareword hash keys Hash keys in Perl are usually not ambiguous because the parser can identify them as string keys; `pinball` in `$games{pinball}` is obviously a string. Occasionally this interpretation is not what you want, especially when you intend to evaluate a builtin or a function to produce the hash key. To make these cases clear, pass arguments to the function, use parentheses, or prepend a unary plus to force the evaluation of the builtin: ``` # the literal 'shift' is the key my $value = $items{shift}; # the value produced by shift is the key my $value = $items{shift @_} # the function returns the key my $value = $items{myshift( @_ )} # unary plus indicates the builtin shift my $value = $items{+shift}; ``` # Bareword package names Package names are also barewords. If your naming conventions rule that package names have initial capitals and functions do not, you'll rarely encounter naming collisions. Even still, Perl must determine how to parse `Package->method` . Does it mean "call a function named `Package()` and call `method()` on its return value?" or "Call a method named `method()` in the `Package` namespace?" The answer depends on the code Perl has already compiled when it encounters that method call. Force the parser to treat `Package` as a package name by appending the package separator ( `::` ) or make it a literal string: ``` # probably a class method Package->method; # definitely a class method Package::->method; # a slightly less ugly class method 'Package'->method; # package separator my $q = Plack::Request::->new; # unambiguously a string literal my $q = 'Plack::Request'->new; ``` Almost no real code does this, but it's unambiguous, so be able to read it. # Bareword named code blocks The special named code blocks `AUTOLOAD` , `BEGIN` , `CHECK` , `DESTROY` , `END` , `INIT` , and `UNITCHECK` are barewords which declare functions without the `sub` builtin. You've seen this before (Code Generation): ``` package Monkey::Butler; BEGIN { initialize_simians( __PACKAGE__ ) } While you can declare `AUTOLOAD()` without using `sub` , few people do. # Bareword constants Constants declared with the `constant` pragma are usable as barewords: ``` # don't use this for real authentication use constant NAME => 'Bucky'; use constant PASSWORD => '|38fish!head74|'; return unless $name eq NAME && $pass eq PASSWORD; ``` These constants do not interpolate in double-quoted strings. Constants are a special case of prototyped functions (Prototypes). When you predeclare a function with a prototype, the parser will treat all subsequent uses of that bareword specially—and will warn about ambiguous parsing errors. All other drawbacks of prototypes still apply. ### Ill-Advised Uses of Barewords No matter how cautiously you code, barewords still produce ambiguous code. You can avoid the worst abuses, but you will encounter several types of barewords in legacy code. # Bareword hash values Some old code may not take pains to quote the values of hash pairs: ``` # poor style; do not use my %parents = ( mother => Annette, father => Floyd, ); ``` When neither the `Floyd()` nor `Annette()` functions exist, Perl will interpret these barewords as strings. `strict 'subs'` will produce an error in this situation. # Bareword function calls Code written without `strict 'subs'` may use bareword function names. Adding parentheses will make the code pass strictures. Use `perl -MO=Deparse,-p` (see `perldoc B::Deparse` ) to discover how Perl parses them, then parenthesize accordingly. # Bareword filehandles Prior to lexical filehandles (Filehandle References), all file and directory handles used barewords. You can almost always safely rewrite this code to use lexical filehandles. Perl's parser recognizes the special exceptions of `STDIN` , `STDOUT` , and `STDERR` . # Bareword sort functions The second operand of the `sort` builtin can be the name of a function to use for sorting. While this is rarely ambiguous to the parser, it can confuse human readers. The alternative of providing a function reference in a scalar is little better: ``` # bareword style my @sorted = sort compare_lengths @unsorted; # function reference in scalar my $comparison = \&compare_lengths; my @sorted = sort $comparison @unsorted; ``` The second option avoids the use of a bareword, but the result is longer. Unfortunately, Perl's parser does not understand the single-line version due to the special parsing of `sort` ; you cannot use an arbitrary expression (such as taking a reference to a named function) where a block or a scalar might otherwise go. ``` # does not work my @sorted = sort \&compare_lengths @unsorted; ``` In both cases, the way `sort` invokes the function and provides arguments can be confusing (see `perldoc -f sort` for the details). Where possible, consider using the block form of `sort` instead. If you must use either function form, add a comment about what you're doing and why. ## Indirect Objects Perl is not a pure object-oriented language. It has no operator `new` ; a constructor is anything which returns an object. By convention, constructors are class methods named `new()` , but you can name these methods anything you want, or even use functions. Several old Perl OO tutorials promote the use of C++ and Java-style constructor calls: ``` my $q = new Alces; # DO NOT USE ``` ... instead of the obvious method call: `my $q = Alces->new;` These examples produce equivalent behavior, except when they don't. ### Bareword Indirect Invocations In the indirect object form (more precisely, the dative case) of the first example, the method precedes the invocant. This is fine in spoken languages where verbs and nouns are more obvious, but it introduces parsing ambiguities in Perl. Because the method's name is a bareword (Barewords), the parser uses several heuristics to figure out the proper interpretation of this code. While these heuristics are well-tested and almost always correct, their failure modes are confusing. Things get worse when you pass arguments to a constructor: ``` my $obj = new Class( arg => $value ); # DO NOT USE ``` In this example, the name of the class looks like a function call. Perl can and does often get this right, but its heuristics depend on which package names the parser has seen, which barewords it has already resolved, how it resolved those barewords, and the names of functions already declared in the current package. For an exhaustive list of these conditions, you have to read the source code of Perl's parser—not something the average Perl programmer wants to do (see `intuit_method` in toke.c, if you're really curious—but feel free to forget this suggestion ever existed). Imagine running afoul of a prototyped function (Prototypes) with a name which just happens to conflict somehow with the name of a class or a method called indirectly, such as a poorly-named `JSON()` method in the same file where the `JSON` module is used, to pick an example that actually happened. This is rare, but it's very unpleasant to debug. Avoid indirect invocations instead. ### Indirect Notation Scalar Limitations Another danger of the indirect syntax is that the parser expects a single scalar expression as the object. Printing to a filehandle stored in an aggregate variable seems obvious, but it is not: ``` # DOES NOT WORK say $config->{output} 'Fun diagnostic message!'; ``` Perl will attempt to call `say` on the `$config` object. `close` , and `say` —all builtins which operate on filehandles—operate in an indirect fashion. This was fine when filehandles were package globals, but lexical filehandles (Filehandle References) make the indirect object syntax problems obvious. To solve this, disambiguate the subexpression which produces the intended invocant: ``` say {$config->{output}} 'Fun diagnostic message!'; ``` ### Alternatives to Indirect Notation Direct invocation notation does not suffer this ambiguity problem. To construct an object, call the constructor method on the class name directly: ``` my $q = Plack::Request->new; my $obj = Class->new( arg => $value ); ``` This syntax still has a bareword problem in that if you have a function named `Request` in the `Plack` namespace, Perl will interpret the bareword class name as a call to the function, as: ``` sub Plack::Request; # you wrote Plack::Request->new, but Perl saw my $q = Plack::Request()->new; ``` Disambiguate this syntax as usual (Bareword package names). For the limited case of filehandle operations, the dative use is so prevalent that you can use the indirect invocation approach if you surround your intended invocant with curly brackets. You can use methods on lexical filehandles, though almost no one ever does this for `say` . The CPAN module ``` Perl::Critic::Policy::Dynamic::NoIndirect ``` (a plugin for `Perl::Critic` ) can analyze your code to find indirect invocations. The CPAN module `indirect` can identify and prohibit their use in running programs: ``` # warn on indirect use no indirect; # throw exceptions on their use no indirect ':fatal'; ``` ## Prototypes A prototype is a piece of metadata attached to a function or variable. A function prototype changes how Perl's parser understands it. Prototypes allow you to define your own functions which behave like builtins. Consider the builtin `push` , which takes an array and a list. While Perl would normally flatten the array and list into a single list passed to `push` , Perl knows to treat the array as a container and does not flatten its values. In effect, this is like passing a reference to an array and a list of values to `push` —because Perl's parser understands this is what `push` needs to do. Function prototypes attach to function declarations: ``` sub foo (&@); sub bar ($$) { ... } my $baz = sub (&&) { ... }; ``` Any prototype attached to a forward declaration must match the prototype attached to the function declaration. Perl will give a warning if this is not true. Strangely you may omit the prototype from a forward declaration and include it for the full declaration—but the only reason to do so is to win a trivia contest. The builtin `prototype` takes the name of a function and returns a string representing its prototype. To see the prototype of a builtin, prepend `CORE::` to its name for `prototype` 's operand: ``` $ perl -E "say prototype 'CORE::push';" \@@ $ perl -E "say prototype 'CORE::keys';" \% $ perl -E "say prototype 'CORE::open';" *;$@ ``` `prototype` will return `undef` for those builtins whose functions you cannot emulate: ``` say prototype 'CORE::system' // 'undef' # undef; cannot emulate builtin system say prototype 'CORE::prototype' // 'undef' # undef; builtin prototype has no prototype ``` Remember `push` ? ``` $ perl -E "say prototype 'CORE::push';" \@@ ``` The `@` character represents a list. The backslash forces the use of a reference to the corresponding argument. This prototype means that `push` takes a reference to an array and a list of values. You might write `mypush` as: ``` sub mypush (\@@) { my ($array, @rest) = @_; push @$array, @rest; } ``` Other prototype characters include `$` to force a scalar argument, `%` to mark a hash (most often used as a reference), and `&` to identify a code block. See `perldoc perlsub` for more information. ### The Problem with Prototypes Prototypes change how Perl parses your code and how Perl coerces arguments passed to your functions. While these prototypes may superficially resemble function signatures (Real Function Signatures) in other languages, they are very different. They do not document the number or types of arguments functions expect, nor do they map arguments to named parameters. Prototype coercions work in subtle ways, such as enforcing scalar context on incoming arguments: ``` sub numeric_equality($$) { my ($left, $right) = @_; return $left == $right; } say 'They're equal, whatever that means!' if numeric_equality @nums, 10; ``` ... but only work on simple expressions: ``` sub mypush(\@@); # compilation error: prototype mismatch # (expects array, gets scalar assignment) mypush( my $elems = [], 1 .. 20 ); ``` To debug this, users of `mypush` must know both that a prototype exists, and the limitations of the array prototype. That's a lot of cognitive burden to put on a user—and if you think this error message is inscrutable, wait until you see the complicated prototype errors. ### Good Uses of Prototypes Prototypes do have a few good uses that outweigh their problems. For example, you can use a prototyped function to override one of Perl's builtins. First check that you can override the builtin by examining its prototype in a small test program. Then use the `subs` pragma to tell Perl that you plan to override a builtin. Finally declare your override with the correct prototype: ``` use subs 'push'; sub push (\@@) { ... } ``` Beware that the `subs` pragma is in effect for the remainder of the file, regardless of any lexical scoping. You may also usefully use prototypes to define compile-time constants. When Perl encounters a function declared with an empty prototype (as opposed to no prototype) and this function evaluates to a single constant expression, the optimizer will turn all calls to that function into constants instead of function calls: ``` sub PI () { 4 * atan2(1, 1) } ``` All subsequent code will use the calculated value of pi in place of the bareword `PI` or a call to `PI()` , with respect to scoping and visibility. The core pragma `constant` handles these details for you. The `Const::Fast` module from the CPAN creates constant scalars which you can interpolate into strings. A reasonable use of prototypes is to extend Perl's syntax to operate on anonymous functions as blocks. The CPAN module `Test::Exception` uses this to good effect to provide a nice API with delayed computation. Its `throws_ok()` function takes three arguments: a block of code to run, a regular expression to match against the string of the exception, and an optional description of the test: throws_ok { my $unobject; $unobject->yoink } qr/Can't call method "yoink" on an undefined/, 'Method on undefined invocant should fail'; The exported `throws_ok()` function has a prototype of `&$;$` . Its first argument is a block, which becomes an anonymous function. The second argument is a scalar. The third argument is optional. Careful readers may have spotted the absence of a comma after the block. This is a quirk of Perl's parser, which expects whitespace after a prototyped block, not the comma operator. This is a drawback of the prototype syntax. If that bothers you, use `throws_ok()` without taking advantage of the prototype: throws_ok( sub { my $unobject; $unobject->yoink() }, qr/Can't call method "yoink" on an undefined/, 'Method on undefined invocant should fail' ); `Test::Fatal` allows similar testing and uses a simpler approach to avoid this ambiguity. <NAME> suggests a final good use of prototypes, to define a custom named function to use with `sort` : ``` sub length_sort ($$) { my ($left, $right) = @_; return length($left) <=> length($right); } my @sorted = sort length_sort @unsorted; ``` The prototype of `$$` forces Perl to pass the sort pairs in `@_` . `sort` 's documentation suggests that this is slightly slower than using the package globals `$a` and `$b` , but using lexical variables often makes up for any speed penalty. ## Method-Function Equivalence Perl's object system is deliberately minimal (Blessed References). A class is a package, and Perl does not distinguish between a function and a method stored in a package. The same builtin, `sub` , declares both. Perl will happily dispatch to a function called as a method. Likewise, you can invoke a method as if it were a function—fully-qualified, exported, or as a reference—if you pass in your own invocant manually. Invoking the wrong thing in the wrong way causes problems. ### Caller-side Consider a class with several methods: ``` package Order { use List::Util 'sum'; sub calculate_price { my $self = shift; return sum( 0, $self->get_items ); } Given an `Order` object `$o` , the following invocations of this method may seem equivalent: ``` my $price = $o->calculate_price; # broken; do not use my $price = Order::calculate_price( $o ); ``` Though in this simple case, they produce the same output, the latter violates object encapsulation by bypassing method lookup. Perl has one circumstance where this behavior may seem necessary. If you force method resolution without dispatch, how do you invoke the resulting method reference? ``` my $meth_ref = $o->can( 'apply_discount' ); ``` There are two possibilities. The first is to discard the return value of the `can()` method: ``` $o->apply_discount if $o->can( 'apply_discount' ); ``` The second is to use the reference itself with method invocation syntax: ``` if (my $meth_ref = $o->can( 'apply_discount' )) { $o->$meth_ref(); } ``` When `$meth_ref` contains a function reference, Perl will invoke that reference with `$o` as the invocant. This works even under strictures, as it does when invoking a method with a scalar containing its name: ``` my $name = 'apply_discount'; $o->$name(); ``` There is one small drawback in invoking a method by reference; if the structure of the program changes between storing the reference and invoking the reference, the reference may no longer refer to the most appropriate method. If the `Order` class has changed such that ``` Order::apply_discount ``` is no longer the right method to call, the reference in `$meth_ref` will not have updated. That's an unlikely circumstance, but limit the scope of a method reference when you use this invocation form just in case. ### Callee-side The `CGI` module has these two-faced functions. Every one of them must apply several heuristics to determine whether the first argument is an invocant. This causes problems. It's difficult to predict exactly which invocants are potentially valid for a given method, especially when you may have to deal with subclasses. Creating an API that users cannot easily misuse is more difficult too, as is your documentation burden. What happens when one part of the project uses the procedural interface and another uses the object interface? If you must provide a separate procedural and OO interface to a library, create two separate APIs. ## Automatic Dereferencing Perl can automatically dereference certain references on your behalf. Given an array reference in `$arrayref` , you can write: ``` push $arrayref, qw( list of values ); ``` Given an expression which returns an array reference, you can do the same: ``` push $houses{$location}[$closets], \@new_shoes; ``` The Autoderef Experiment After Perl 5.18, you must enable this feature with ``` use experimental 'autoderef'; ``` . That should be a sign to tread carefully here. The same goes for the array operators `pop` , `shift` , `unshift` , `splice` , `keys` , `values` , and `each` and the hash operators `keys` , `values` , and `each` . If the reference provided is not of the proper type—if it does not dereference properly—Perl will throw an exception. While this may seem more dangerous than explicitly dereferencing references directly, it is in fact the same behavior: ``` my $ref = sub { ... }; # will throw an exception push $ref, qw( list of values ); # will also throw an exception push @$ref, qw( list of values ); ``` Unfortunately, this automatic dereferencing has two problems. First, it only works on plain variables. If you have a `bless` ed array or hash, a `tie` d hash, or an object with array or hash overloading, Perl will throw a runtime exception instead of dereferencing the reference. Second, remember that `each` , `keys` , and `values` can operate on both arrays and hashes. You can't look at: ``` my @items = each $ref; ``` ... and tell whether `@items` contains a list of key/value pairs or index/value pairs, because you don't know whether you should expect `$ref` to refer to a hash or an array. Yes, choosing good variable names will help, but this code is intrinsically confusing. Neither of these drawbacks make this syntax unusable in general, but its rough edges and potential for confusing readers make it less useful than it could be. ## Tie Where overloading (Overloading) allows you to customize the behavior of classes and objects for specific types of coercion, a mechanism called tying allows you to customize the behavior of primitive variables (scalars, arrays, hashes, and filehandles). Any operation you might perform on a tied variable translates to a specific method call on an object. For example, the `tie` builtin allows core `Tie::File` module to treat files as if they were arrays of records, letting you `push` and `pop` and `shift` as you see fit. ( `tie` was intended to use file-backed stores for hashes and arrays, so that Perl could use data too large to fit in available memory. RAM was more expensive 20 years ago.) The class to which you `tie` a variable must conform to a defined interface for a specific data type. Read `perldoc perltie` for an overview, then see the core modules `Tie::StdScalar` , `Tie::StdArray` , and `Tie::StdHash` for specific details. Start by inheriting from one of those classes, then override any specific methods you need to modify. When Class and Package Names Collide If `tie` weren't confusing enough, `Tie::Scalar` , `Tie::Array` , and `Tie::Hash` define the necessary interfaces to tie scalars, arrays, and hashes, but `Tie::StdScalar` , `Tie::StdArray` , and `Tie::StdHash` provide the default implementations. ### Tying Variables To tie a variable: ``` use Tie::File; tie my @file, 'Tie::File', @args; ``` The first operand is the variable to tie. The second is the name of the class into which to tie it. `@args` is an optional list of arguments required for the tying function. In the case of `Tie::File` , `@args` should contain a valid filename. Tying functions resemble constructors: `TIESCALAR` , `TIEARRAY()` , `TIEHASH()` , or `TIEHANDLE()` for scalars, arrays, hashes, and filehandles respectively. Each function returns a new object which represents the tied variable. Both `tie` and `tied` return this object, though most people use `tied` in a boolean context. ### Implementing Tied Variables To implement the class of a tied variable, inherit from a core module such as `Tie::StdScalar` , Then override the specific methods for the operations you want to change. In the case of a tied scalar, these are likely `FETCH` and `STORE` , possibly `TIESCALAR()` , and probably not `DESTROY()` . Here's a class which logs all reads from and writes to a scalar: ``` package Tie::Scalar::Logged { use Tie::Scalar; use parent -norequire => 'Tie::StdScalar'; sub STORE { my ($self, $value) = @_; Logger->log("Storing <$value> (was [$$self])", 1); $$self = $value; } sub FETCH { my $self = shift; Logger->log("Retrieving <$$self>", 1); return $$self; } } ``` Assume that the `Logger` class method `log()` takes a string and the number of frames up the call stack of which to report the location. Within the `STORE()` and `FETCH()` methods, `$self` works as a blessed scalar. Assigning to that scalar reference changes the value of the scalar. Reading from it returns its value. Similarly, the methods of `Tie::StdArray` and `Tie::StdHash` act on blessed array and hash references, respectively. Again, `perldoc perltie` explains the methods tied variables support, such as reading or writing multiple values at once. Isn't `tie` Fun? The `-norequire` option prevents the `parent` pragma from attempting to load a file for `Tie::StdScalar` , as that module is part of the file Tie/Scalar.pm. That's right, there's no .pm file for `Tie::StdScalar` . Isn't this fun? ### When to use Tied Variables Tied variables seem like fun opportunities for cleverness, but they can produce confusing interfaces. Unless you have a very good reason for making objects behave as if they were builtin data types, avoid creating your own ties without good reason. `tie` d variables are also much slower than builtin data types. With that said, tied variables can help you debug tricky code (use the logged scalar to help you understand where a value changes) or to make certain impossible things possible (access large files without running out of memory). Tied variables are less useful as the primary interfaces to objects; it's often too difficult and constraining to try to fit your whole interface to that supported by `tie()` . A final word of warning is a sad indictment of lazy programming: a lot of code goes out of its way to prevent use of tied variables, often by accident. This is unfortunate, but library code is sometimes fast and lazy with what it expects, and you can't always fix it. Visit Modern Perl to download your own copy of this book or buy Modern Perl at Amazon. Perl isn't perfect, but it is malleable—because no single configuration is ideal for every programmer and every purpose. Some useful behaviors are available as core libraries. More are available from the CPAN. Effective Perl programmers take full advantage of the options available to them. ## Useful Core Modules Perl's language design process has always tried to combine practicality with expandability, but it was as impossible to predict the future in 1994 as it is in 2015. Perl 5 expanded the language and made the CPAN possible, but it also retained backwards compatibility with most Perl 1 code written as far back as 1987. The best Perl code of 2015 is very different from the best Perl code of 1994 or the best Perl code of 1987, and part of that is due to its core library. ### The strict Pragma The `strict` pragma (Pragmas) allows you to forbid (or re-enable) various powerful language constructs which offer potential for accidental abuse. `strict` forbids symbolic references, requires variable declarations (Lexical Scope), and prohibits the use of undeclared barewords (Barewords). While symbolic references are occasionally necessary (Using and Importing), the use of a variable as a variable name offers the possibility of subtle errors of action at a distance—or, worse, the possibility of poorly-validated user input manipulating private data for malicious purposes. Requiring variable declarations helps to detect typos in variable names and encourages proper scoping of lexical variables. It's easier to see the intended scope of a lexical variable if all variables have `my` or `our` declarations in the appropriate scope. `strict` takes effect in lexical scopes. See `perldoc strict` for more details. ### The warnings Pragma The `warnings` pragma (Handling Warnings) controls the reporting of various warning classes, such as attempting to stringify the `undef` value or using the wrong type of operator on values. It also warns about the use of deprecated features. The most useful warnings explain that Perl had trouble understanding what you meant and had to guess at the proper interpretation. Even though Perl often guesses correctly, disambiguation on your part will ensure that your programs run correctly. The `warnings` pragma takes effect in lexical scopes. See `perldoc perllexwarn` and `perldoc warnings` for more details. Asking for More Help If you use both `warnings` with `diagnostics` , you'll get expanded diagnostic messages for each warning present in your programs, straight out of `perldoc perldiag` . It's a great help when learning Perl, but be sure to disable `diagnostics` before deploying your program, lest you fill up your logs or expose debugging information to users. ### The autodie Pragma Perl leaves error handling (or error ignoring) up to you. If you forget to check the return value of every `open()` call, for example, you could try to read from a closed filehandle—or worse, lose data as you try to write to one. The `autodie` pragma changes this for you. If you write: ``` use autodie; open my $fh, '>', $file; ``` ... an unsuccessful `open()` call will throw an exception. Given that the most appropriate approach to a failed system call is throwing an exception, this pragma can remove a lot of boilerplate code and allow you the peace of mind of knowing that you haven't forgotten to check a return value. One caveat of `autodie` is that it can be a sledgehammer when you need a finishing hammer; if you only need a couple of system calls checked for you, you can limit its imports accordingly. See `perldoc autodie` for more information. ### Perl Version Numbers If you encounter a piece of Perl code without knowing when it was written or who wrote it, can you tell which version of Perl it requires? If you have a lot of experience with Perl both before and after the release of Perl 5.10, you might remember which version added `say` and when `autodie` entered the core. Otherwise, you might have to guess, trawl through `perldelta` files, or use `CPAN::MinimumVersion` from the CPAN. There's no requirement for you to add the minimum required Perl version number to all new code you write, but it can clarify your intentions. For example, if you've tested your code with Perl 5.18 and use only features present in Perl 5.18, write: `use 5.018;` ... and you'll document your intent. You'll also make it easier for tools to identify the particular features of Perl you may or may not use in this code. If someone comes along later and proves that the code works just fine on Perl 5.14, you can change the version number—and you'll do so based on practical evidence. ## What's Next? Although Perl includes an extensive core library, it's not comprehensive. Many of the best modules are available outside of the core, from the CPAN (The CPAN). The `Task::Kensho` meta-distribution includes several other distributions which represent the best the CPAN has to offer. When you need to solve a problem, look there first. The CPAN has plenty of other gems, though. For example, if you want to: * Access a database via SQL, use the `DBI` module * Embed a lightweight, single-file database, use the `DBD::SQLite` module * Manage your database schemas, use `Sqitch` * Represent database entities as objects, use `DBIx::Class` * Perform basic web programming, use `Plack` * Use a powerful web framework, use `Mojolicious` , `Dancer` , or `Catalyst` * Process structured data files, use `Text::CSV_XS` (or `Text::CSV` ) * Manage module installations for applications, use `Carton` * Manipulate numeric data, use `PDL` * Manipulate images, use `Imager` * Access shared libraries, use `FFI::Platypus` * Extract data from XML files, use `XML::Rabbit` * Keep your code tidy, use `Perl::Tidy` * Watch for problems beyond strictures and warnings, use `Perl::Critic` ... and the list goes on. Skim the CPAN recent uploads page http://search.cpan.org/recent frequently to see what's new and what's updated. ### Thinking in Perl As is true of any creative endeavor, learning Perl never stops. While "Modern Perl" describes how the best Perl programmers approach their craft, their techniques and tools always evolve. What's great in 2015 and 2016 might not have been imagined even five years ago—and the greatness of 2020 and beyond might be mere inklings in the mind of an enterprising Perl hacker right now. Now you have the chance to shape that future. It's up to you to continue discovering how to make Perl work for you and how to make Perl better, whether learning from the global Perl community, perusing the documentation of the core and CPAN modules, and by careful practice, discovering what works for you and what helps you write the right code. Perl's not perfect (though it improves, year after year, release after release). It can be as clean or as messy as you need it to be, depending on the problems you have to solve. It's up to you to use it well. As a wise person once said, "May you do good things with Perl."
robeth
cran
R
Package ‘robeth’ August 22, 2023 Type Package Title R Functions for Robust Statistics Version 2.7-8 Date 2023-08-21 Depends R (>= 3.2.0) Author <NAME> <<EMAIL>> Maintainer <NAME> <<EMAIL>> Description Locations problems, M-estimates of coefficients and scale in linear regression, Weights for bounded influence regression, Covariance matrix of the coefficient estimates, Asymptotic relative efficiency of regression M-estimates, Robust testing in linear models, High breakdown point regression, M-estimates of covariance matrices, M-estimates for discrete generalized linear models. License GPL (>= 2) LazyLoad yes NeedsCompilation yes Repository CRAN Date/Publication 2023-08-22 08:00:05 UTC R topics documented: robeth-packag... 5 .dFvGe... 28 .dFvPu... 29 add... 29 airef... 30 airef... 31 binpr... 32 cer... 33 cerf... 33 cfrco... 34 Ch... 34 ch... 35 chis... 35 cia2b... 36 cibea... 37 ciclo... 37 cifac... 38 cimed... 39 ciroc... 39 comva... 40 cquan... 40 cyfal... 41 cygal... 42 cynal... 43 Dbino... 44 dfcom... 44 dfrpa... 46 dfval... 46 dot... 47 dotp... 47 dpois... 48 exc... 49 exch... 49 fcu... 50 Fn.Exp.... 51 fstor... 51 gaus... 52 gauss... 52 gfedc... 53 ginta... 54 glmde... 55 gyast... 56 gycst... 57 gymai... 57 gytst... 59 h1... 60 h12... 60 hylms... 61 hylts... 62 hyses... 63 hysest... 64 ingam... 65 kfasc... 65 kfedc... 66 kfedc... 67 kffac... 67 kiasc... 68 kiedc... 69 kiedc... 69 ktask... 70 ktask... 71 lgam... 72 libet... 72 libet... 73 libet... 73 licll... 74 lieps... 74 lieps... 75 liind... 75 liind... 76 liind... 77 lilar... 77 litts... 78 lmd... 78 lrfct... 79 lyhal... 80 lyhdl... 81 lymnw... 81 lytau... 82 lywal... 83 mch... 84 mchl... 85 messagen... 85 mf... 86 mff... 86 mfrag... 87 mf... 88 mfy... 88 mha... 89 min... 90 minv... 90 mirts... 91 ml... 92 mly... 92 ms... 93 msf... 94 msf1... 94 msf... 95 ms... 95 mss... 96 mtt... 97 mtt1... 97 mtt... 98 mtt2... 98 mtt... 99 mtt3... 100 mt... 100 mty... 101 myhbh... 102 mymvl... 102 nlg... 103 nrm... 104 nrm2... 104 perm... 105 perm... 105 poiss... 106 prec... 107 prec... 107 probs... 108 Ps... 108 ps... 109 Ps... 109 ps... 110 QD2coef.... 110 QD2funC.... 111 Qn.Exp.... 112 quan... 112 Rando... 113 Regtau.... 114 RegtauW.... 114 Rh... 115 rh... 116 ribet... 116 ribet... 117 ribet... 117 ricll... 118 rilar... 119 rimtr... 119 rimtr... 120 rmv... 121 rube... 121 rybif... 122 ryhal... 123 rynal... 124 rysal... 125 rysig... 126 rywal... 127 sca... 128 scal... 129 srt... 130 srt... 130 swa... 131 swap... 132 tauar... 133 tfrn2... 134 tftau... 134 tisrt... 135 to.characte... 136 to.doubl... 136 to.intege... 137 to.singl... 137 tquan... 138 ttask... 138 tteig... 139 Uc... 140 uc... 140 ug... 141 Upc... 141 upc... 142 userf... 142 userf... 143 vc... 143 vpc... 144 Wc... 144 wc... 145 wfsha... 145 wimed... 146 Wpc... 147 wpc... 147 Ww... 148 ww... 148 wyfal... 149 wyfco... 150 wygal... 151 wynal... 152 xer... 153 xer... 153 xs... 154 xsy... 154 zeml... 155 robeth-package Interface for the FORTRAN programs developed at the ETH-Zuerich and then at IUMSP-Lausanne Description This package allows the computation of a broad class of procedures based on M-estimation and high breakdown point estimation, including robust regresion, robust testing of linear hypotheses and robust covariances. The reference book quoted below is required for the theoritical background of the statistical and numerical methods Details Package: robeth Type: Package #Version: 2.7-7 #Date: 2023-06-19 License: GPL version 2 or later Author(s) <NAME> <<EMAIL>> Maintainer: <NAME> <<EMAIL>> References Marazzi A., (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. Examples library(robeth) # # ------------- Examples of Chapter 1: Location problems ------------------------------ # y <- c(6.0,7.0,5.0,10.5,8.5,3.5,6.1,4.0,4.6,4.5,5.9,6.5) n <- 12 dfvals() #----------------------------------------------------------------------- # M-estimate (tm) of location and confidence interval (tl,tu) # dfrpar(as.matrix(y),"huber") libeth() s <- lilars(y); t0 <- s$theta; s0 <- s$sigma s <- lyhalg(y=y,theta=t0,sigmai=s0) tm <- s$theta; vartm <- s$var s <- quant(0.975) tl <- tm-s$x*sqrt(vartm) tu <- tm+s$x*sqrt(vartm) #----------------------------------------------------------------------- # Hodges and Lehmann estimate (th) and confidence interval (zl,zu) # m <- n*(n+1)/2 # n even k1 <- m/2; k2 <- k1+1 z1 <- lyhdle(y=y,k=k1); z2 <- lyhdle(y=y,k=k2) th <- (z1$hdle+z2$hdle)/2. ku <- liindh(0.95,n); kl <- liindh(0.05,n) zu <- lyhdle(y=y,k=ku$k); zl <- lyhdle(y=y,k=kl$k) #....................................................................... { cat(" tm, tl, tu : ",round(c(tm,tl,tu),3),"\n") cat(" th, zl, zu : ",round(c(th,zl$hdle,zu$hdle),3),"\n") } # tm, tl, tu : 5.809 4.748 6.87 # th, zl, zu : 5.85 5 7 #======================================================================= # # Two sample problem # y <- c(17.9,13.3,10.6,7.6,5.7,5.6,5.4,3.3,3.1,0.9) n <- 10 x <- c(7.7,5.0,1.7,0.0,-3.0,-3.1,-10.5) m <- 7 #----------------------------------------------------------------------- # Estimate (dm) and confidence interval [dl,du] based on Mann-Whitney # k1 <- m*n/2; k2 <- k1+1 s1 <- lymnwt(x=x,y=y,k=k1); s2 <- lymnwt(x=x,y=y,k=k2) dm <- (s1$tmnwt+s2$tmnwt)/2.0 sl <- liindw(0.05,m,n); kl <- sl$k s <- lymnwt(x=x,y=y,k=kl); dl <- s$tmnwt s <- lymnwt(x=x,y=y,k=m*n-kl+1); du <- s$tmnwt #----------------------------------------------------------------------- # Tau-test . P-value (P) # z <- c(x,y) dfrpar(as.matrix(z),"huber") libeth() s <- lytau2(z=z,m=m,n=n) P <- s$p # # estimate (tm) and confidence interval (tl,tu) # tm <- s$deltal c22<- s$cov[3] s <- quant(0.975) tl <- tm-s$x*sqrt(c22) tu <- tm+s$x*sqrt(c22) #....................................................................... { cat("dm, dl, du:",round(c(dm,dl,du),3),"\n") cat("P, tm, tl, tu:",round(c(P,tm,tl,tu),3),"\n") } # dm, dl, du: 6.35 2.9 12.9 # P, tm, tl, tu: 0.014 6.918 1.562 12.273 # # Examples of Chapter 2: M-estimates of coefficients and scale in linear regression # # Read data; declare the vector wgt; load defaults # z <- c(-1, -2, 0, 35, 1, 0, -3, 20, -1, -2, 0, 30, 1, 0, -3, 39, -1, -2, 0, 24, 1, 0, -3, 16, -1, -2, 0, 37, 1, 0, -3, 27, -1, -2, 0, 28, 1, 0, -3, -12, -1, -2, 0, 73, 1, 0, -3, 2, -1, -2, 0, 31, 1, 0, -3, 31, -1, -2, 0, 21, 1, 0, -1, 26, -1, -2, 0, -5, 1, 0, -1, 60, -1, 0, 0, 62, 1, 0, -1, 48, -1, 0, 0, 67, 1, 0, -1, -8, -1, 0, 0, 95, 1, 0, -1, 46, -1, 0, 0, 62, 1, 0, -1, 77, -1, 0, 0, 54, 1, 0, 1, 57, -1, 0, 0, 56, 1, 0, 1, 89, -1, 0, 0, 48, 1, 0, 1, 103, -1, 0, 0, 70, 1, 0, 1, 129, -1, 0, 0, 94, 1, 0, 1, 139, -1, 0, 0, 42, 1, 0, 1, 128, -1, 2, 0, 116, 1, 0, 1, 89, -1, 2, 0, 105, 1, 0, 1, 86, -1, 2, 0, 91, 1, 0, 3, 140, -1, 2, 0, 94, 1, 0, 3, 133, -1, 2, 0, 130, 1, 0, 3, 142, -1, 2, 0, 79, 1, 0, 3, 118, -1, 2, 0, 120, 1, 0, 3, 137, -1, 2, 0, 124, 1, 0, 3, 84, -1, 2, 0, -8, 1, 0, 3, 101) xx <- matrix(z,ncol=4, byrow=TRUE) dimnames(xx) <- list(NULL,c("z2","xS","xT","y")) z2 <- xx[,"z2"]; xS <- xx[,"xS"]; xT <- xx[,"xT"] x <- cbind(1, z2, xS+xT, xS-xT, xS^2+xT^2, xS^2-xT^2, xT^3) y <- xx[,"y"] wgt <- vector("numeric",length(y)) n <- 56; np <- 7 dfvals() # Set parameters for Huber estimate dfrpar(x, "huber") # Compute the constants beta, bet0, epsi2 and epsip ribeth(wgt) ribet0(wgt) s <- liepsh() epsi2 <- s$epsi2; epsip <- s$epsip # # Least squares solution (theta0,sigma0) # z <- riclls(x, y) theta0<- z$theta; sigma0 <- z$sigma # Preliminary estimate of the covariance matrix of the coefficients cv <- kiascv(z$xt, fu=epsi2/epsip^2, fb=0.) cov <- cv$cov #----------------------------------------------------------------------- # Solution (theta1,sigma1) by means of RYHALG. # zr <- ryhalg(x,y,theta0,wgt,cov,sigmai=sigma0,ic=0) theta1<- zr$theta[1:np]; sigma1 <- zr$sigmaf; nit1 <- zr$nit #----------------------------------------------------------------------- # Solution (theta2,sigma2) by means of RYWALG (recompute cov) # cv <- ktaskv(x, f=epsi2/epsip^2) zr <- rywalg(x, y, theta0, wgt, cv$cov, sigmai=sigma0) theta2 <- zr$theta[1:np]; sigma2 <- zr$sigmaf; nit2 <- zr$nit #----------------------------------------------------------------------- # Solution (theta3,sigma3) by means of RYSALG with ISIGMA=2. # zr <- rysalg(x,y, theta0, wgt, cv$cov, sigma0, isigma=2) theta3 <- zr$theta[1:np]; sigma3 <- zr$sigmaf; nit3 <- zr$nit #----------------------------------------------------------------------- # Solution (theta4,sigma4) by means of RYNALG with ICNV=2 and ISIGMA=0. # # Invert cov covm1 <- cv$cov zc <- mchl(covm1,np) zc <- minv(zc$a, np) zc <- mtt1(zc$r,np) covm1 <- zc$b zr <- rynalg(x,y, theta0, wgt, covm1, sigmai=sigma3, iopt=1, isigma=0, icnv=2) theta4 <- zr$theta[1:np]; sigma4 <- zr$sigmaf; nit4 <- zr$nit #....................................................................... { cat("theta0 : ",round(theta0[1:np],3),"\n") cat("sigma0 : ",round(sigma0,3),"\n") cat("theta1 : ",round(theta1,3),"\n") cat("sigma1, nit1 : ",round(sigma1,3),nit1,"\n") cat("theta2 : ",round(theta2,3),"\n") cat("sigma2, nit2 : ",round(sigma2,3),nit2,"\n") cat("theta3 : ",round(theta3,3),"\n") cat("sigma3, nit3 : ",round(sigma3,3),nit3,"\n") cat("theta4 : ",round(theta4,3),"\n") cat("sigma4, nit4 : ",round(sigma4,3),nit4,"\n") } # theta0 : 68.634 3.634 24.081 -8.053 -0.446 -0.179 -1.634 # sigma0 : 26.635 # theta1 : 70.006 5.006 24.742 -6.246 -0.079 0.434 -1.487 # sigma1, nit1 : 23.564 7 # theta2 : 70.006 5.006 24.742 -6.245 -0.079 0.434 -1.487 # sigma2, nit2 : 23.563 7 # theta3 : 69.993 5.002 24.766 -6.214 -0.055 0.44 -1.48 # sigma3, nit3 : 22.249 3 # theta4 : 69.993 5.002 24.766 -6.214 -0.055 0.44 -1.48 # sigma4, nit4 : 22.249 3 # # ---- Examples of Chapter 3: Weights for bounded influence regression ------ # #======================================================================= rbmost <- function(x,y,cc,usext=userfd) { n <- nrow(x); np <- ncol(x); dfcomn(xk=np) .dFvPut(1,"itw") z <- wimedv(x) z <- wyfalg(x, z$a, y, exu=usext); nitw <- z$nit wgt <- 1/z$dist; wgt[wgt>1.e6] <- 1.e6 z <- comval() bto <- z$bt0; ipso <- z$ipsi; co <- z$c z <- ribet0(wgt, itype=2, isqw=0) xt <- x*wgt; yt <- y * wgt z <- rilars(xt, yt) theta0 <- z$theta; sigma0 <- z$sigma rs <- z$rs/wgt; r1 <- rs/sigma0 dfcomn(ipsi=1,c=cc) z <- liepsh(cc) den <- z$epsip g <- Psp(r1)/den # (see Psi in Chpt. 14) dfcomn(ipsi=ipso, c=co, bet0=bto) list(theta=theta0, sigma=sigma0, rs=rs, g=g, nitw=nitw) } #----------------------------------------------------------------------- # Mallows-standard estimate (with wyfalg and rywalg) # Mal.Std <- function(x, y, b2=-1, cc=-1, isigma=2) { n <- length(y); np <- ncol(x) dfrpar(x, "Mal-Std", b2, cc); .dFv <- .dFvGet() if (isigma==1) {dfcomn(d=.dFv$ccc); .dFvPut(1,"isg")} # Weights z <- wimedv(x) z <- wyfalg(x, z$a, y); nitw <- z$nit wgt <- Www(z$dist) # See Www in Chpt. 14 # Initial cov. matrix of coefficient estimates z <- kiedch(wgt) cov <- ktaskw(x, z$d, z$e, f=1/n) # Initial theta and sigma z <- rbmost(x,y,1.5,userfd) theta0 <- z$theta; sigma0 <- z$sigma; nitw0 <- z$nitw # Final theta and sigma if (isigma==1) ribeth(wgt) else ribet0(wgt) z <- rywalg(x, y,theta0,wgt,cov$cov, sigmai=sigma0) theta1 <- z$theta[1:np]; sigma1 <- z$sigmaf; nit1 <- z$nit # Covariance matrix of coefficient estimates z <- kfedcc(wgt, z$rs, sigma=sigma1) cov <- ktaskw(x, z$d, z$e, f=(sigma1^2)/n) sd1 <- NULL; for (i in 1:np) { j <- i*(i+1)/2 sd1 <- c(sd1,cov$cov[j]) } sd1 <- sqrt(sd1) #....................................................................... { cat("rbmost: theta0 : ",round(theta0[1:np],3),"\n") cat("rbmost: sigma0, nitw : ",round(sigma0,3),nitw0,"\n") cat("Mallows-Std: theta1 : ",round(theta1,3),"\n") cat("Mallows-Std: sd1 : ",round(sd1,3),"\n") cat("Mallows-Std: sigma1, nitw, nit1 : ",round(sigma1,3),nitw,nit1,"\n") } #....................................................................... list(theta0=theta0[1:np], sigma0=sigma0, nitw=nitw, theta1=theta1, sigma1=sigma1, nit1=nit1, sd1=sd1)} #----------------------------------------------------------------------- # Krasker-Welsch estimate (with wynalg and rynalg) # Kra.Wel <- function(x, y, ckw=-1, isigma=2) { n <- length(y); np <- ncol(x) dfrpar(x, "Kra-Wel", ckw); .dFv <- .dFvGet() if (isigma==1) {dfcomn(d=.dFv$ccc); .dFvPut(1,"isg")} # Weights z <- wimedv(x) z <- wynalg(x, z$a); nitw <- z$nit wgt <- Www(z$dist) # See Www in Chpt. 14 # Initial cov. matrix of coefficient estimates z <- kiedch(wgt) cov <- ktaskw(x, z$d, z$e, f=1/n) # Initial theta and sigma z <- rbmost(x, y, cc=1.5) theta0 <- z$theta; sigma0 <- z$sigma; nitw0 <- z$nitw # Final theta and sigma if (isigma==1) ribeth(wgt) else ribet0(wgt) z <- rynalg(x, y,theta0,wgt,cov$cov, sigmai=sigma0) theta2 <- z$theta[1:np]; sigma2 <- z$sigma; nit2 <- z$nit # # Covariance matrix of coefficient estimates # z <- kfedcc(wgt, z$rs, sigma=sigma2) cov <- ktaskw(x, z$d, z$e, f=(sigma2^2)/n) sd2 <- NULL; for (i in 1:np) { j <- i*(i+1)/2 sd2 <- c(sd2,cov$cov[j]) } sd2 <- sqrt(sd2) #....................................................................... { cat("rbmost: theta0 : ",round(theta0[1:np],3),"\n") cat("rbmost: sigma0, nitw : ",round(sigma0,3),nitw0,"\n") cat("Krasker-Welsch: theta2 : ",round(theta2,3),"\n") cat("Krasker-Welsch: sd2 : ",round(sd2,3),"\n") cat("Krasker-Welsch: sigma2, nitw, nit2 : ",round(sigma2,3),nitw,nit2,"\n") } #....................................................................... list(theta0=theta0[1:np], sigma0=sigma0, nitw=nitw, theta2=theta2, sigma2=sigma2, nit2=nit2, sd2=sd2)} #----------------------------------------------------------------------- # Read data; load defaults # z <- c( 8.2, 4, 23.005, 1, 7.6, 5, 23.873, 1, 4.6, 0, 26.417, 1, 4.3, 1, 24.868, 1, 5.9, 2, 29.895, 1, 5.0, 3, 24.200, 1, 6.5, 4, 23.215, 1, 8.3, 5, 21.862, 1, 10.1, 0, 22.274, 1, 13.2, 1, 23.830, 1, 12.6, 2, 25.144, 1, 10.4, 3, 22.430, 1, 10.8, 4, 21.785, 1, 13.1, 5, 22.380, 1, 13.3, 0, 23.927, 1, 10.4, 1, 33.443, 1, 10.5, 2, 24.859, 1, 7.7, 3, 22.686, 1, 10.0, 0, 21.789, 1, 12.0, 1, 22.041, 1, 12.1, 4, 21.033, 1, 13.6, 5, 21.005, 1, 15.0, 0, 25.865, 1, 13.5, 1, 26.290, 1, 11.5, 2, 22.932, 1, 12.0, 3, 21.313, 1, 13.0, 4, 20.769, 1, 14.1, 5, 21.393, 1) x <- matrix(z, ncol=4, byrow=TRUE) y <- c( 7.6, 7.7, 4.3, 5.9, 5.0, 6.5, 8.3, 8.2, 13.2, 12.6, 10.4, 10.8, 13.1, 12.3, 10.4, 10.5, 7.7, 9.5, 12.0, 12.6, 13.6, 14.1, 13.5, 11.5, 12.0, 13.0, 14.1, 15.1) dfvals() dfcomn(xk=4) cat("Results\n") z1 <- Mal.Std(x, y) z2 <- Kra.Wel(x, y) # # ---- Examples of Chapter 4: Covariance matrix of the coefficient estimates ------ # # # Read x[1:4] and then set x[,4] <- 1 # z <- c(80, 27, 89, 1, 80, 27, 88, 1, 75, 25, 90, 1, 62, 24, 87, 1, 62, 22, 87, 1, 62, 23, 87, 1, 62, 24, 93, 1, 62, 24, 93, 1, 58, 23, 87, 1, 58, 18, 80, 1, 58, 18, 89, 1, 58, 17, 88, 1, 58, 18, 82, 1, 58, 19, 93, 1, 50, 18, 89, 1, 50, 18, 86, 1, 50, 19, 72, 1, 50, 19, 79, 1, 50, 20, 80, 1, 56, 20, 82, 1, 70, 20, 91, 1) x <- matrix(z, ncol=4, byrow=TRUE) n <- 21; np <- 4; ncov <- np*(np+1)/2 dfvals() # Cov. matrix of Huber-type estimates dfrpar(x, "huber") s <- liepsh() epsi2 <- s$epsi2; epsip <- s$epsip z <- rimtrf(x) xt <- z$x; sg <- z$sg; ip <- z$ip zc <- kiascv(xt, fu=epsi2/epsip^2, fb=0.) covi <- zc$cov # Can be used in ryhalg with ic=0 zc <- kfascv(xt, covi, f=1, sg=sg, ip=ip) covf <- zc$cov #....................................................................... str <- rep(" ", ncov); str[cumsum(1:np)] <- "\n" { cat("covf:\n") cat(round(covf,6),sep=str) } # # ---- Examples of Chapter 5: Asymptotic relative efficiency ------ # #----------------------------------------------------------------------- # Huber # dfcomn(ipsi=1,c=1.345,d=1.345) .dFvPut(1,"ite") z <- airef0(mu=3, ialfa=1, sigmx=1) #....................................................................... { cat(" airef0 : Huber\n reff, alfa, beta, nit: ") cat(round(c(z$reff,z$alfa,z$beta,z$nit),3),sep=c(", ",", ",", ","\n")) } #----------------------------------------------------------------------- # Schweppe: Krasker-Welsch # dfcomn(ipsi=1,c=3.76,iucv=3,ckw=3.76,iwww=1) .dFvPut(3,"ite") z <- airef0(mu=3, ialfa=1, sigmx=1) #....................................................................... { cat(" airef0 : Krasker-Welsch\n reff, alfa, beta, nit: ") cat(round(c(z$reff,z$alfa,z$beta,z$nit),3),sep=c(", ",", ",", ","\n")) } #----------------------------------------------------------------------- # Mallows-Standard # dfcomn(ipsi=1,c=1.5,iucv=1,a2=0,b2=6.16,iww=3) .dFvPut(2,"ite") z <- airef0(mu=3, ialfa=1, sigmx=1) #....................................................................... { cat(" airef0 : Mallows-Std \n reff, alfa, beta, nit: ") cat(round(c(z$reff,z$alfa,z$beta,z$nit),3),sep=c(", ",", ",", ","\n")) } #======================================================================= z <- c(1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1) tt <- matrix(z,ncol=3,byrow=TRUE) n <- nrow(tt); mu <- 2 nu <- ncol(tt) #----------------------------------------------------------------------- # Huber # dfrpar(tt,"Huber") z <- airefq(tt, mu=mu, sigmx=1) #....................................................................... { cat(" airefq : Huber\n reff, beta, nit: ") cat(round(c(z$reff,z$beta,z$nit),3),sep=c(", ",", ",", ","\n")) } #----------------------------------------------------------------------- # Krasker-Welsch # dfrpar(tt,"kra-wel",upar=3.755) z <- airefq(tt, mu=mu, sigmx=1,init=1) #....................................................................... { cat(" airefq : Krasker-Welsch\n reff, beta, nit: ") cat(round(c(z$reff,z$beta,z$nit),3),sep=c(", ",", ",", ","\n")) } #----------------------------------------------------------------------- # Mallows Standard # dfrpar(tt,"Mal-Std",1.1*(mu+nu),1.569) z <- airefq(tt, mu=mu, sigmx=1,init=1) #....................................................................... { cat(" airefq : Mallows-Std\n reff, beta, nit: ") cat(round(c(z$reff,z$beta,z$nit),3),sep=c(", ",", ",", ","\n")) } # # ---- Examples of Chapter 6: Robust testing in linear models ------ # #======================================================================= tautest <- function(x,y,np,nq) { # Full model. np variables in x[,1:np] n <- nrow(x) z <- riclls(x[,1:np], y) theta0 <- z$theta; sigma0 <- z$sigma; .dFv <- .dFvGet() z <- liepsh(.dFv$ccc) # ccc is globally defined by dfrpar epsi2 <- z$epsi2; epsip <- z$epsip zc <- ktaskv(x[,1:np],f=epsi2/(epsip^2)) covi <- zc$cov ribeth(y) zf <- rywalg(x[,1:np],y,theta0,y,covi,sigmai=sigma0) thetaf <- zf$theta; sigma <- zf$sigmaf; rf <- zf$rs f <- kffacv(rf,np=np,sigma=sigma) zc <- ktaskv(x[,1:np],f=f$fh*(sigma^2)/n) cov <- zc$cov # Sub-model: nq variables in x[,1:nq], nq < np covi <- cov[1:(nq*(nq+1)/2)] zs <- rywalg(x[,1:nq], y, thetaf, y, covi, sigmai=sigma,isigma=0) thetas <- zs$theta; rs <- zs$rs # Compute Tau-test statistic and P-value ztau <- tftaut(rf,rs,y,rho,np,nq,sigma) ftau <- ztau$ftau z <- chisq(1,np-nq,ftau*epsip/epsi2) P <- 1-z$p #....................................................................... { cat(" F_tau, P, sigma: ") cat(round(c(ftau,P,sigma),3),sep=c(", ",", ","\n")) cat(" theta (small model): ",round(thetas[1:nq],3),"\n\n") } #....................................................................... list(thetas=thetas[1:nq], sigma=sigma, rs=rs,ftau=ftau, P=P)} #------------------------------------------------------------------------ dshift <- function(x, theta, sigma, rs, nq) { # Shift estimate d and confidence interval ncov <- nq*(nq+1)/2 f <- kffacv(rs,np=nq,sigma=sigma) zc <- ktaskv(x[,1:nq],f=f$fh) cov <- zc$cov k11 <- 4.*cov[ncov-nq] k12 <- 2.*cov[ncov-1] k22 <- cov[ncov] za <- quant(0.05/2) d <- 2*theta[nq-1]/theta[nq] q <- za$x*sigma/theta[nq] g <- k22*(q^2) a <- d-g*k12/k22 b <- abs(q)*sqrt(k11-2*d*k12+d*d*k22-g*(k11-k12*k12/k22)) dL <- (a-b)/(1-g) dU <- (a+b)/(1-g) #....................................................................... cat(" d, dL, dU: ",round(c(d,dL,dU),3),sep=c("",", ",", ","\n")) #....................................................................... list(d=d, dL=dL, dU=dU) } #------------------------------------------------------------------------ potcy <- function(m,ml,mu,h,k,d,cs,ct) { fact <- ((h*k) %% 2) + 1 r <- exp(log(d)*(fact*m+h-k)/2 - log(ct/cs)) rl <- exp(log(d)*(fact*ml+h-k)/2 - log(ct/cs)) ru <- exp(log(d)*(fact*mu+h-k)/2 - log(ct/cs)) list(R=r, Rl=rl, Ru=ru)} #------------------------------------------------------------------------ rbmost <- function(x,y,cc,usext=userfd) { n <- nrow(x); np <- ncol(x); dfcomn(xk=np) .dFvPut(1,"itw") z <- wimedv(x) z <- wyfalg(x, z$a, y, exu=usext); nitw <- z$nit wgt <- 1/z$dist; wgt[wgt>1.e6] <- 1.e6 z <- comval() bto <- z$bt0; ipso <- z$ipsi; co <- z$c z <- ribet0(wgt, itype=2, isqw=0) xt <- x*wgt; yt <- y * wgt z <- rilars(xt, yt) theta0 <- z$theta; sigma0 <- z$sigma rs <- z$rs/wgt; r1 <- rs/sigma0 dfcomn(ipsi=1,c=cc) z <- liepsh(cc) den <- z$epsip g <- Psp(r1)/den # (see Psp in Chpt. 14) dfcomn(ipsi=ipso, c=co, bet0=bto) list(theta=theta0, sigma=sigma0, rs=rs, g=g, nitw=nitw) } #======================================================================= dfvals() z <- c(-1, -2, 0, 35, 1, 0, -3, 20, -1, -2, 0, 30, 1, 0, -3, 39, -1, -2, 0, 24, 1, 0, -3, 16, -1, -2, 0, 37, 1, 0, -3, 27, -1, -2, 0, 28, 1, 0, -3, -12, -1, -2, 0, 73, 1, 0, -3, 2, -1, -2, 0, 31, 1, 0, -3, 31, -1, -2, 0, 21, 1, 0, -1, 26, -1, -2, 0, -5, 1, 0, -1, 60, -1, 0, 0, 62, 1, 0, -1, 48, -1, 0, 0, 67, 1, 0, -1, -8, -1, 0, 0, 95, 1, 0, -1, 46, -1, 0, 0, 62, 1, 0, -1, 77, -1, 0, 0, 54, 1, 0, 1, 57, -1, 0, 0, 56, 1, 0, 1, 89, -1, 0, 0, 48, 1, 0, 1, 103, -1, 0, 0, 70, 1, 0, 1, 129, -1, 0, 0, 94, 1, 0, 1, 139, -1, 0, 0, 42, 1, 0, 1, 128, -1, 2, 0, 116, 1, 0, 1, 89, -1, 2, 0, 105, 1, 0, 1, 86, -1, 2, 0, 91, 1, 0, 3, 140, -1, 2, 0, 94, 1, 0, 3, 133, -1, 2, 0, 130, 1, 0, 3, 142, -1, 2, 0, 79, 1, 0, 3, 118, -1, 2, 0, 120, 1, 0, 3, 137, -1, 2, 0, 124, 1, 0, 3, 84, -1, 2, 0, -8, 1, 0, 3, 101) xx <- matrix(z,ncol=4, byrow=TRUE) dimnames(xx) <- list(NULL,c("z2","xS","xT","y")) z2 <- xx[,"z2"]; xS <- xx[,"xS"]; xT <- xx[,"xT"] x <- cbind(1, z2, xS+xT, xS-xT, xS^2+xT^2, xS^2-xT^2, xT^3) y <- xx[,"y"] z <- dfrpar(x, "huber",psipar=1.345) # # Tau-test and shift estimate # { cat("Results (linearity test)\n") np <- 7; nq <- 4 # Test linearity z <- tautest(x,y,np,nq) cat("Results (parallelism test)\n") np <- 4; nq <- 3 # Test parallelism z <- tautest(x,y,np,nq) z <- dshift(x, z$thetas, z$sigma, z$rs, nq) } #------------------------------------------------------------------------ # Input data; set defaults # z <- c(35.3, 20, 10.98, 29.7, 20, 11.13, 30.8, 23, 12.51, 58.8, 20, 8.40, 61.4, 21, 9.27, 71.3, 22, 8.73, 74.4, 11, 6.36, 76.7, 23, 8.50, 70.7, 21, 7.82, 57.5, 20, 9.14, 46.4, 20, 8.24, 28.9, 21, 12.19, 28.1, 21, 11.88, 39.1, 19, 9.57, 46.8, 23, 10.94, 48.5, 20, 9.58, 59.3, 22, 10.09, 70.0, 22, 8.11, 70.0, 11, 6.83, 74.5, 23, 8.88, 72.1, 20, 7.68, 58.1, 21, 8.47, 44.6, 20, 8.86, 33.4, 20, 10.36, 28.6, 22, 11.08) x <- matrix(z, ncol=3, byrow=TRUE) y <- x[,3]; x[,2:3] <- x[,1:2]; x[,1] <- 1 n <- length(y); np <- ncol(x); nq <- np - 1 # # Optimal tau-test based on Schweppe-type estimates # z <- tauare(itype=3,mu=1,cpsi=2.665,bb=0,sigmax=1) dfrpar(x, "Sch-Tau",upar=2.67); .dFvPut(1,"isg"); .dFv <- .dFvGet(); dfcomn(d=.dFv$ccc) # Full model: initial estimates of theta, sigma and weights dfcomn(xk=np) # Needed for userfd zr <- rbmost(x,y,cc=1.5) theta0 <- zr$theta; sigma0 <- zr$sigma; nitw0 <- zr$nitw # # Initial and final values of weights # z <- wimedv(x) z <- wyfalg(x, z$a, zr$g, nvarq=nq, igwt=1) wgt <- 1/z$dist ; wgt[wgt>1.e6] <- 1.e6 # Full model: covariance matrix of coefficients and inverse z <- kiedch(wgt) zc <- ktaskw(x, z$d, z$e, f=1/n, iainv=1) cov <- zc$cov; ainv <- zc$ainv # Full model: Final estimate of theta and sigma ribeth(wgt) zf <- rywalg(x, y,theta0,wgt,cov, sigmai=sigma0) thetaf <- zf$theta[1:np]; sigma <- zf$sigmaf; nitf <- zf$nit # Small model: Final estimate of theta and sigma covi <- cov[1:(nq*(nq+1)/2)] xt <- x[,1:nq,drop=FALSE] zs <- rywalg(xt, y, theta0, wgt, covi, sigmai=sigma, isigma=0) thetas <- zs$theta[1:nq]; nits <- zs$nit # Compute Tau-test statistic ft <- tftaut(zf$rs,zs$rs,wgt,rho,np,nq,sigma) ftau <- ft$ftau # P-value z <- ttaskt(cov, ainv, np, nq, fact=n) z <- tteign(z$covtau,nq) xlmbda <- z$xlmbda[1:(np-nq)] mult <- rep(1, length=np) delta <- rep(0, length=np) z <- ruben(xlmbda, delta, mult,ftau, xmode=-1, maxit=100, eps=0.0001) P <- 1-z$cumdf #....................................................................... { cat(" Optimal Tau-test : Schweppe-type estimates\n") cat(" theta0: ",round(theta0[1:np],3),"\n sigma0, nitw: ") cat(round(c(sigma0,nitw0),3),sep=c(", ","\n")) cat(" thetaf: ",round(thetaf,3),"\n sigma, nit: ") cat(round(c(sigma,nitf),3),sep=c(", ","\n")) cat(" thetas: ",round(thetas,3),"\n sigma, nit: ") cat(round(c(sigma,nits),3),sep=c(", ","\n")) cat(" F_tau =",round(ftau,3),", P =",P,"\n") } #======================================================================= rn2mal <- function(x,y,b2,c,nq) { n <- length(y); np <- ncol(x) # # Rn2-test on Mallows estimators # ============================== dfrpar(x, "mal-std", b2, c) .dFvPut(1,"isg"); .dFv <- .dFvGet(); dfcomn(d=.dFv$ccc) # # Initial and final values of weights # z <- wimedv(x) z <- wyfalg(x, z$a, wgt) wgt <- Www(z$dist); nitw <- z$nit # # Initial theta and sigma (using weighted LAR) # ribet0(wgt, isqw=0) xt <- x*wgt yt <- y * wgt z <- rilars(xt, yt) theta0 <- z$theta; sigma0 <- z$sigma # # Initial value of COV # z <- kiedch(wgt) zc <- ktaskw(x, z$d, z$e, f=1/n) covi <- zc$cov # # Solution by means of RYWALG. # z <- ribeth(wgt) beta <- z$bta zw <- rywalg(x, y, theta0, wgt, covi, sigmai=sigma0) theta1 <- zw$theta[1:np]; sigma1 <- zw$sigmaf; nit1 <- zw$nit # # Unscaled covariance matrix of coefficients # zc <- kfedcb(wgt, zw$rs, sigma=sigma1) z <- ktaskw(x, zc$d, zc$e, f=1/n) cov1 <- z$cov # # Rn2-test statistic and significance # z <- tfrn2t(cov1,theta1,n,nq) rn2m <- z$rn2t/(n*sigma1^2) z <- chisq(1,np-nq,rn2m) p1 <- 1.-z$p list(theta1=theta1, sigma1=sigma1, wgt=wgt, nitw=nitw, nit1=nit1, rn2m=rn2m, p1=p1)} #------------------------------------------------------------------------ # # Read data # z <- c(35.3, 20, 10.98, 29.7, 20, 11.13, 30.8, 23, 12.51, 58.8, 20, 8.40, 61.4, 21, 9.27, 71.3, 22, 8.73, 74.4, 11, 6.36, 76.7, 23, 8.50, 70.7, 21, 7.82, 57.5, 20, 9.14, 46.4, 20, 8.24, 28.9, 21, 12.19, 28.1, 21, 11.88, 39.1, 19, 9.57, 46.8, 23, 10.94, 48.5, 20, 9.58, 59.3, 22, 10.09, 70.0, 22, 8.11, 70.0, 11, 6.83, 74.5, 23, 8.88, 72.1, 20, 7.68, 58.1, 21, 8.47, 44.6, 20, 8.86, 33.4, 20, 10.36, 28.6, 22, 11.08) x <- matrix(z, ncol=3, byrow=TRUE) y <- x[,3]; x[,2:3] <- x[,1:2]; x[,1] <- 1 n <- length(y); np <- ncol(x); nq <- np - 1 wgt <- vector("numeric",length(y)) z <- rn2mal(x, y, 4, 1.5, nq) #....................................................................... { cat("Rn2-test on Mallows estimators\n") cat(" theta1: ",round(z$theta1,3),"\n sigma1, nitw, nit1: ") cat(round(c(z$sigma1,z$nitw,z$nit1),3),sep=c(", ",", ","\n")) cat(" Rn2 =",round(z$rn2m,3),", P =",z$p1,"\n") } # # ---- Examples of Chapter 7: Breakdown point regression ------ # # # Read data; load defaults # z <- c(80, 27, 89, 42, 80, 27, 88, 37, 75, 25, 90, 37, 62, 24, 87, 28, 62, 22, 87, 18, 62, 23, 87, 18, 62, 24, 93, 19, 62, 24, 93, 20, 58, 23, 87, 15, 58, 18, 80, 14, 58, 18, 89, 14, 58, 17, 88, 13, 58, 18, 82, 11, 58, 19, 93, 12, 50, 18, 89, 8, 50, 18, 86, 7, 50, 19, 72, 8, 50, 19, 79, 8, 50, 20, 80, 9, 56, 20, 82, 15, 70, 20, 91, 15) x <- matrix(z, ncol=4, byrow=TRUE) y <- x[,4]; x[,4] <- 1 n <- length(y); np <- ncol(x) nq <- np+1 dfvals() # # Least median of squares # zr <- hylmse(x,y, nq, ik=1, iopt=3, intch=1) theta1 <- zr$theta; xmin1 <- zr$xmin zr <- hylmse(x,y, nq, ik=2, iopt=3, intch=1) theta2 <- zr$theta; xmin2 <- zr$xmin zr <- hylmse(x,y, nq, ik=1, iopt=1, intch=1) theta3 <- zr$theta; xmin3 <- zr$xmin # # Least trimmed squares # zr <- hyltse(x,y, nq, ik=1, iopt=3, intch=1) theta4 <- zr$theta; xmin4 <- zr$smin zr <- hyltse(x,y, nq, ik=2, iopt=3, intch=1) theta5 <- zr$theta; xmin5 <- zr$smin zr <- hyltse(x,y, nq, ik=1, iopt=1, intch=1) theta6 <- zr$theta; xmin6 <- zr$smin # # S-estimate # z <- dfrpar(x,'S') z <- ribetu(y) zr <- hysest(x,y, nq, iopt=3, intch=1) theta7 <- zr$theta[1:np]; xmin7 <- zr$smin zr <- hysest(x,y, nq, iopt=1, intch=1) theta8 <- zr$theta[1:np]; xmin8 <- zr$smin #....................................................................... { cat("Results\n theta1 = (") cat(round(theta1,3),sep=", ") cat("), xmin1 ="); cat(round(xmin1,3)) cat("\n theta2 = ("); cat(round(theta2,3),sep=", ") cat("), xmin2 ="); cat(round(xmin2,3)) cat("\n theta3 = ("); cat(round(theta3,3),sep=", ") cat("), xmin3 ="); cat(round(xmin3,3)) cat("\n theta4 = ("); cat(round(theta4,3),sep=", ") cat("), xmin4 ="); cat(round(xmin4,3)) cat("\n theta5 = ("); cat(round(theta5,3),sep=", ") cat("), xmin5 ="); cat(round(xmin5,3)) cat("\n theta6 = ("); cat(round(theta6,3),sep=", ") cat("), xmin6 ="); cat(round(xmin6,3)) cat("\n theta7 = ("); cat(round(theta7,3),sep=", ") cat("), xmin7 ="); cat(round(xmin7,3)) cat("\n theta8 = ("); cat(round(theta8,3),sep=", ") cat("), xmin8 ="); cat(round(xmin8,3),"\n") } # # ---- Examples of Chapter 8: M-estimates of covariance matrices ------ # # # Read data; set defaults # z <- c(4.37, 5.23, 4.38, 5.02, 4.56, 5.74, 4.42, 4.66, 4.26, 4.93, 4.29, 4.66, 4.56, 5.74, 4.38, 4.90, 4.30, 5.19, 4.22, 4.39, 4.46, 5.46, 3.48, 6.05, 3.84, 4.65, 4.38, 4.42, 4.57, 5.27, 4.56, 5.10, 4.26, 5.57, 4.45, 5.22, 4.37, 5.12, 3.49, 6.29, 3.49, 5.73, 4.23, 4.34, 4.43, 5.45, 4.62, 5.62, 4.48, 5.42, 4.53, 5.10, 4.01, 4.05, 4.45, 5.22, 4.29, 4.26, 4.53, 5.18, 4.42, 4.58, 4.43, 5.57, 4.23, 3.94, 4.38, 4.62, 4.42, 4.18, 4.45, 5.06, 4.23, 4.18, 4.50, 5.34, 3.49, 5.89, 4.45, 5.34, 4.29, 4.38, 4.55, 5.54, 4.29, 4.22, 4.45, 4.98, 4.42, 4.42, 4.42, 4.50, 4.49, 4.85) cx <- matrix(z, ncol=2, byrow=TRUE) n <- nrow(cx); np <- ncol(cx) dst0 <- vector("numeric",n) #----------------------------------------------------------------------- # Classical covariance # t0 <- apply(cx, 2, mean) xmb <- sweep(cx, 2, t0) cv0 <- crossprod(xmb)/n # Mahalanobis distances cvm1 <- solve(cv0) for (i in 1:n) { z <- xmb[i,,drop=FALSE]; dst0[i] <- sqrt(z %*% cvm1 %*% t(z))} #======================================================================= # M-estimate of covariance # zc <- cicloc() za <- cia2b2(nvar=np) a2 <- za$a2; b2 <- za$b2 zd <- cibeat(a2, b2, np) cw <- zc$c; dv <- zd$d dfcomn(iucv=1, a2=a2, b2=b2, bt=dv, cw=cw) # zf <- cifact(a2,b2,np); fc <- zf$fc z <- cimedv(cx) ai <- z$a; ti <- z$t; fc <- 1 #----------------------------------------------------------------------- # With prescription F0 zd <- cyfalg(cx,ai,ti) zc <- cfrcov(zd$a,np,fc) cv1 <- zc$cov; t1 <- zd$t; dst1 <- zd$dist; nt1 <- zd$nit #----------------------------------------------------------------------- # With prescription NH zd <- cynalg(cx,ai,ti) zc <- cfrcov(zd$a,np,fc) cv2 <- zc$cov; t2 <- zd$t; dst2 <- zd$dist; nt2 <- zd$nit #----------------------------------------------------------------------- # With prescription CG zd <- cygalg(cx,ai,ti) zc <- cfrcov(zd$a,np,fc) cv3 <- zc$cov; t3 <- zd$t; dst3 <- zd$dist; nt3 <- zd$nit #....................................................................... { cat("Results\n\n cv0[1,1],cv0[2,1],cv0[2,2] = (") cat(round(as.vector(cv0)[-2],3),sep=", ") cat(")\n t0 = ("); cat(round(t0,3),sep=", ") cat(")\n dist0 :\n ") cat(round(dst0,3),sep=c(rep(", ",9),",\n ")) cat("\n cv1[1,1],cv1[2,1],cv1[2,2] = (") cat(round(cv1,3),sep=", ") cat(")\n t1 = ("); cat(round(t1,3),sep=", ") cat("), nit1 =",nt1); cat("\n dist1 :\n ") cat(round(dst1,3),sep=c(rep(", ",9),",\n ")) cat("\n cv2[1,1],cv2[2,1],cv2[2,2] = (") cat(round(cv2,3),sep=", ") cat(")\n t2 = ("); cat(round(t2,3),sep=", ") cat("), nit2 =",nt2); cat("\n dist2 :\n ") cat(round(dst2,3),sep=c(rep(", ",9),",\n ")) cat("\n cv3[1,1],cv3[2,1],cv3[2,2] = (") cat(round(cv3,3),sep=", ") cat(")\n t3 = ("); cat(round(t3,3),sep=", ") cat("), nit3 =",nt3); cat("\n dist3 :\n ") cat(round(dst3,3),sep=c(rep(", ",9),",\n ")) } # # ----------- Examples of Chapter 9: Mixed procedures -------------- # bindec <- function(np,ind,cpc,cpr) { n <- length(ind) ccar <- matrix("-",ncol=np, nrow=n) for (i in 1:n) { j <- 0 num <- abs(ind[i]) while (num != 0 & j < np) { j <- j+1 if (num %% 2 == 1) ccar[i,j] <- "X" num <- num %/% 2}} data.frame(Cp=round(cpc,3),Cp.r=round(cpr,3),ipr=ind,i=ccar) } #----------------------------------------------------------------------- # Read data # z <- c(-1, -2, 0, 35, 1, 0, -3, 20, -1, -2, 0, 30, 1, 0, -3, 39, -1, -2, 0, 24, 1, 0, -3, 16, -1, -2, 0, 37, 1, 0, -3, 27, -1, -2, 0, 28, 1, 0, -3, -12, -1, -2, 0, 73, 1, 0, -3, 2, -1, -2, 0, 31, 1, 0, -3, 31, -1, -2, 0, 21, 1, 0, -1, 26, -1, -2, 0, -5, 1, 0, -1, 60, -1, 0, 0, 62, 1, 0, -1, 48, -1, 0, 0, 67, 1, 0, -1, -8, -1, 0, 0, 95, 1, 0, -1, 46, -1, 0, 0, 62, 1, 0, -1, 77, -1, 0, 0, 54, 1, 0, 1, 57, -1, 0, 0, 56, 1, 0, 1, 89, -1, 0, 0, 48, 1, 0, 1, 103, -1, 0, 0, 70, 1, 0, 1, 129, -1, 0, 0, 94, 1, 0, 1, 139, -1, 0, 0, 42, 1, 0, 1, 128, -1, 2, 0, 116, 1, 0, 1, 89, -1, 2, 0, 105, 1, 0, 1, 86, -1, 2, 0, 91, 1, 0, 3, 140, -1, 2, 0, 94, 1, 0, 3, 133, -1, 2, 0, 130, 1, 0, 3, 142, -1, 2, 0, 79, 1, 0, 3, 118, -1, 2, 0, 120, 1, 0, 3, 137, -1, 2, 0, 124, 1, 0, 3, 84, -1, 2, 0, -8, 1, 0, 3, 101) xx <- matrix(z,ncol=4, byrow=TRUE) dimnames(xx) <- list(NULL,c("z2","xS","xT","y")) z2 <- xx[,"z2"]; xS <- xx[,"xS"]; xT <- xx[,"xT"] x <- cbind(1, z2, xS+xT, xS-xT, xS^2+xT^2, xS^2-xT^2, xT^3) y <- xx[,"y"] wgt <- vector("numeric",length(y)) n <- 56; np <- 7 dfvals() # Compute classical sigma and the t-statistics dfrpar(x,"ols",-1,-1); .dFv <- .dFvGet() z <- mirtsr(x,y,.dFv$ite) sigmc <- z$sigma; tstac <- z$t # Compute robust sigma and the t-statistics dfrpar(x,"huber",-1,-1); .dFv <- .dFvGet() z <- mirtsr(x,y,.dFv$ite) sigmr <- z$sigma; tstar <- z$t # # All possible regressions including the constant and linear terms # vp <- rep(-0.5, length=np) vp[1] <- 3; vp[3] <- 2; vp[4] <- 1 za <- mfragr(x, y, vp, nc=18, .dFv$ite, sigmac=sigmc, sigmar=sigmr) # # Priorites by means of t-directed search # zt <- mfragr(x, y, tstar, nc=7, .dFv$ite, sigmac=sigmc, sigmar=sigmr) #....................................................................... { cat(" Estimates of sigma\n ") cat(" sigmc =",round(sigmc,3),", sigmr =",round(sigmr,3),"\n") cat(" Regressions on subset of variables:\n") cat(" C{p} C{p,@} ipr 1 2 3 4 5 6 7\n") cat(t(bindec(np,za$ipr,za$cpc,za$cpr)),sep=c(rep(" ",9),"\n")) cat("\n t-directed search\n") cat(" tstar[1:7]=(", round(tstar,3),sep=c("",rep(", ",6))) cat(")\n C_p C{p,@} ipr 1 2 3 4 5 6 7\n") cat(t(bindec(np,zt$ipr,zt$cpc,zt$cpr)),sep=c(rep(" ",9),"\n")) } #======================================================================= # # Read data; set defaults # z <- c(4.37, 5.23, 4.48, 5.42, 4.38, 5.02, 4.53, 5.10, 4.56, 5.74, 4.01, 4.05, 4.42, 4.66, 4.45, 5.22, 4.26, 4.93, 4.29, 4.26, 4.29, 4.66, 4.53, 5.18, 4.56, 5.74, 4.42, 4.58, 4.38, 4.90, 4.43, 5.57, 4.30, 5.19, 4.23, 3.94, 4.22, 4.39, 4.38, 4.62, 4.46, 5.46, 4.42, 4.18, 3.48, 6.05, 4.45, 5.06, 3.84, 4.65, 4.23, 4.18, 4.38, 4.42, 4.50, 5.34, 4.57, 5.27, 3.49, 5.89, 4.56, 5.10, 4.45, 5.34, 4.26, 5.57, 4.29, 4.38, 4.45, 5.22, 4.55, 5.54, 4.37, 5.12, 4.29, 4.22, 3.49, 6.29, 4.45, 4.98, 3.49, 5.73, 4.42, 4.42, 4.23, 4.34, 4.42, 4.50, 4.43, 5.45, 4.49, 4.85, 4.62, 5.62) cx <- matrix(z, ncol=2, byrow=TRUE) n <- nrow(cx); np <- ncol(cx) y <- vector("numeric",length=n) # # Minimum Volume Ellipsoid covariances # dfvals(); .dFv <- .dFvGet() z <- mymvlm(cx,y,ilms=0,iopt=3,iseed=5321) dst <- z$d; cv <- z$cov; xvol <- z$xvol #....................................................................... { cat("Minimum Volume Ellipsoid covariances\n cv = (") cat(round(cv,3),sep=c(", ",", ")) cat("), Objective function value =",round(xvol,3),"\ndistances:\n") cat(round(dst,3),sep=c(rep(", ",9),",\n")) } #======================================================================= # # Read data; load defaults # z <- c(80, 27, 89, 42, 80, 27, 88, 37, 75, 25, 90, 37, 62, 24, 87, 28, 62, 22, 87, 18, 62, 23, 87, 18, 62, 24, 93, 19, 62, 24, 93, 20, 58, 23, 87, 15, 58, 18, 80, 14, 58, 18, 89, 14, 58, 17, 88, 13, 58, 18, 82, 11, 58, 19, 93, 12, 50, 18, 89, 8, 50, 18, 86, 7, 50, 19, 72, 8, 50, 19, 79, 8, 50, 20, 80, 9, 56, 20, 82, 15, 70, 20, 91, 15) x <- matrix(z, ncol=4, byrow=TRUE) y <- x[,4]; x[,4] <- 1 n <- length(y); np <- ncol(x) nq <- np+1 dfvals() # # High breakdown point & high efficiency regression # dfrpar(x,"S",-1,-1) z <- myhbhe(x, y, iseed=5431) #....................................................................... { cat("High breakdown point & high efficiency regression\n") cat(" theta0 = ("); cat(round(z$theta0,3),sep=", ") cat("), sigma0 =",round(z$sigm0,3)) cat("\n theta1 = ("); cat(round(z$theta1,3),sep=", ") cat("), sigma1 = ",round(z$sigm1,3),", tbias =",sep="") cat(round(z$tbias,3),"\n") } # # -------- Examples of Chapter 10: M-estimates for discrete GLM --------- # glmb <- function(x,y,n,np,upar) { # # BI estimates of theta, A, ci and wa: Bernouilli responses, b=upar # # Initial theta, A (A0) and c (c0) # ni <- rep.int(1,n) z <- gintac(x,y,ni,icase=1,b=upar,c=1.5) theta0 <- z$theta[1:np]; A0 <- z$a; c0 <- z$ci # Initial distances |Ax_i| and cut off points a_i (wa) wa <- upar/z$dist vtheta <- x %*% theta0 z <- gfedca(vtheta, c0, wa, ni, icase=1) zc <- ktaskw(x, z$d, z$e, f=1/n) # See Chpt. 4 covi <- zc$cov # Final theta, A, c (ci) and a (wa) z <- gymain(x, y, ni, covi, A0, theta0, b = upar) theta <- z$theta; A <- z$a; ci <- z$ci; wa <- z$wa; nit <- z$nit # Final cov. matrix and std. dev's of coeff. estimates z <- gfedca(z$vtheta, ci, wa, ni, icase=1) sdev <- NULL zc <- ktaskw(x, z$d, z$e, f=1/n) for (i in 1:np) {ii <- i*(i+1)/2; sdev <- c(sdev,zc$cov[ii])} sdev <- sqrt(sdev) list(theta=theta, A=A, ci=ci, wa=wa, nit=nit, sdev=sdev)} #----------------------------------------------------------------------- # Read data; load defaults # z <- c(3.70, 0.825, 1, 3.50, 1.090, 1, 1.25, 2.500, 1, 0.75, 1.500, 1, 0.80, 3.200, 1, 0.70, 3.500, 1, 0.60, 0.750, 0, 1.10, 1.700, 0, 0.90, 0.750, 0, 0.90, 0.450, 0, 0.80, 0.570, 0, 0.55, 2.750, 0, 0.60, 3.000, 0, 1.40, 2.330, 1, 0.75, 3.750, 1, 2.30, 1.640, 1, 3.20, 1.600, 1, 0.85, 1.415, 1, 1.70, 1.060, 0, 1.80, 1.800, 1, 0.40, 2.000, 0, 0.95, 1.360, 0, 1.35, 1.350, 0, 1.50, 1.360, 0, 1.60, 1.780, 1, 0.60, 1.500, 0, 1.80, 1.500, 1, 0.95, 1.900, 0, 1.90, 0.950, 1, 1.60, 0.400, 0, 2.70, 0.750, 1, 2.35, 0.300, 0, 1.10, 1.830, 0, 1.10, 2.200, 1, 1.20, 2.000, 1, 0.80, 3.330, 1, 0.95, 1.900, 0, 0.75, 1.900, 0, 1.30, 1.625, 1) x <- matrix(z, ncol=3, byrow=TRUE) y <- x[,3]; x[,3] <- log(x[,2]); x[,2] <- log(x[,1]) ; x[,1] <- 1 n <- length(y); np <- ncol(x) dfvals() upar <- 3.2*sqrt(np) z1 <- glmb(x,y,n,np,upar) upar <- 3.7*sqrt(np) z2 <- glmb(x,y,n,np,upar) z <- glmb(x,y,n,np,300) # Classical estimates #....................................................................... { cat("\n Robust estimates : upar=5.5426, nit =",z1$nit,"\n") cat(" {theta[i] (sdev[i]), i=1:3}\n ") for (i in 1:3) cat(round(z1$theta[i],3)," (",round(z1$sdev[i],3),") ",sep="") cat("\n\n Robust estimates : upar=6.4086, nit =",z2$nit,"\n") cat(" {theta[i] (sdev[i]), i=1:3}\n ") for (i in 1:3) cat(round(z2$theta[i],3)," (",round(z2$sdev[i],3),") ",sep="") cat("\n\n Classical estimates : upar=300, nit =",z$nit,"\n") cat(" {theta[i] (sdev[i]), i=1:3}\n ") for (i in 1:3) cat(round(z$theta[i],3)," (",round(z$sdev[i],3),") ",sep="") cat("\n") } #----------------------------------------------------------------------- .dFvGet Provide the current values of the scalar parameters used by the Ro- beth subroutines Description See <NAME>. (1993), p.404 Usage .dFvGet() Value A list with the current values of the scalar parameters uaed in robeth. See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.404 .dFvPut Set the current values of the scalar parameters used by the Robeth subroutines Description See <NAME>. (1993), p.404 Usage .dFvPut(vals, nams) Arguments vals The vector of parameter values nams The vector of parameter names to be modified Value No value returned. The named parameters are internaly modified. References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.404 addc Adds a column vector to a transformed design matrix and updates its QR-decomposition Description See <NAME>. (1993), p.355 Usage addc(x, n = nrow(x), l, j, ip) Arguments x See reference n See reference l See reference j See reference ip See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.355 airef0 Asymptotic relative efficiency of a general M-estimate for a model with mu quantitative covariates with or without a constant term Description See <NAME>. (1993), p.167 Usage airef0(expsi = psi, exu = ucv, exw = www, itype = .dFvGet()$ite, mu, ialfa = .dFvGet()$ial, sigmx = 1, upper = .dFvGet()$upr, til = .dFvGet()$tli, maxit = .dFvGet()$mxe, tol = .dFvGet()$tlo) Arguments expsi See reference exu See reference exw See reference itype See reference mu See reference ialfa See reference sigmx See reference upper See reference til See reference maxit See reference tol See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.167 airefq Asymptotic relative efficiency of a general M-estimate for a model with mu quantitative and nu qualitative covariates Description See <NAME>. (1993), p.170 Usage airefq(t, expsi = psi, exu = ucv, exw = www, itype = .dFvGet()$ite, mu, sigmx = 1, upper = .dFvGet()$upr, til = .dFvGet()$tli, tau = .dFvGet()$tua, nobs = nrow(t), maxit = .dFvGet()$mxe, tol = .dFvGet()$tlo, init = .dFvGet()$ini, nitmon = .dFvGet()$ntm) Arguments t See reference expsi See reference exu See reference exw See reference itype See reference mu See reference sigmx See reference upper See reference til See reference tau See reference nobs See reference maxit See reference tol See reference init See reference nitmon See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.170 binprd Binomial probability distribution Description See Marazzi A. (1993), p.367 Usage binprd(k, n, p) Arguments k See reference n See reference p See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.367 cerf Complemented error function (single precision) Description See <NAME>. (1993), p.380 Usage cerf(x) Arguments x See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.380 cerfd Complemented error function (double precision) Description See Marazzi A. (1993), p.380 Usage cerfd(x) Arguments x See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.380 cfrcov Computation of fC.fC.inv(AT A) for a given matrix A and scale factor fC Description See Marazzi A. (1993), p.242 Usage cfrcov(a, nvar, fc, tau = .dFvGet()$tua) Arguments a See reference nvar See reference fc See reference tau See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.242 Chi Chi weight function for location and regression Description See Marazzi A. (1993), p.322 Usage Chi(svals) Arguments svals A vector of input values Value The values of the chi function for each element of svals References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.32 chi Chi weight function for location and regression Description See Marazzi A. (1993), p.322 Usage chi(s) Arguments s A scalar input value Value The value of the chi function for s References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.322 chisq Cumulative Chi-square distribution function Description See Marazzi A. (1993), p.373 Usage chisq(kode = 1, ifn, x) Arguments kode See reference ifn See reference x See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.373 cia2b2 Determination of the parameters a2 and b2 of the Huber weight func- tion from the proportion eps of contamination Description See Marazzi A. (1993), p.244 Usage cia2b2(eps = .dFvGet()$esp, nvar, tol = .dFvGet()$tlo, maxit = .dFvGet()$mxt) Arguments eps See reference nvar See reference tol See reference maxit See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.244 cibeat Determination of the parameter d of the Huber weight function Description See Marazzi A. (1993), p.247 Usage cibeat(a2 = .dFvGet()$aa2, b2 = .dFvGet()$bb2, nvar) Arguments a2 See reference b2 See reference nvar See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.247 cicloc Determination of the parameter c of the Huber weight function from the proportion eps of contamination Description See <NAME>. (1993), p.243 Usage cicloc(eps = .dFvGet()$esp, tol = .dFvGet()$tlo) Arguments eps See reference tol See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.243 cifact Determination of the correction factor for the M-estimate based on Huber weight function Description See <NAME>. (1993), p.246 Usage cifact(a2 = .dFvGet()$aa2, b2 = .dFvGet()$bb2, nvar, tol = .dFvGet()$tlo, maxit = .dFvGet()$mxt) Arguments a2 See reference b2 See reference nvar See reference tol See reference maxit See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.246 cimedv Initial values for the iterative algorithms implemented in CYFALG, CYNALG, and CYGALG Description See <NAME>. (1993), p.230 Usage cimedv(x, nobs = nrow(x), nfirst = nobs, iloc = .dFvGet()$ilc, t) Arguments x See reference nobs See reference nfirst See reference iloc See reference t See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.230 cirock Initial values for the Rocke estimates of covariance Description See <NAME>. (1993), p.223 Usage cirock(nvar, em = .dFvGet()$em, cr = .dFvGet()$cr, iopt = 1) Arguments nvar See the description of nvar as indicated above em See the description of em as indicated above cr See the description of cr as indicated above iopt See the description of iopt as indicated above Author(s) <NAME> (1981) References https://www.ubc.ca/search/?q=rocke#gsc.tab=0&gsc.q=rocke&gsc.page=1 - <NAME>. (1993), Algorithm, Routines, and S functions for Robust Statistics, Wadsworth & Brooks/cole, Pacific Grove, California, p.223 comval Gives the current values ofthe parameters of the ROBETH subroutine common blocks Description See <NAME>. (1993), p.405 Usage comval() Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.405 cquant Inverse of the cumulative Chi2-distribution function Description See <NAME>. (1993), p.374 Usage cquant(p, ifn, tol = 5e-06, maxit = 50) Arguments p See reference ifn See reference tol See reference maxit See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.374 cyfalg Fixed-point algorithm for the computation of an M-estimate of multi- variate location and scatter Description See <NAME>. (1993), p.232 Usage cyfalg(x, a, t, exu = ucv, exv = vcv, exw = wcv, nobs = nrow(x), tau = .dFvGet()$tua, maxit = .dFvGet()$mxf, nitmon = .dFvGet()$ntm, iloc = .dFvGet()$ilc, icnv = .dFvGet()$icv, tol = .dFvGet()$tlo) Arguments x See reference a See reference t See reference exu See reference exv See reference exw See reference nobs See reference tau See reference maxit See reference nitmon See reference iloc See reference icnv See reference tol See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.232 cygalg Conjugate gradient algorithm for the computation of an M-estimate of multivariate location and scatter Description See <NAME>. (1993), p.238 Usage cygalg(x, a, t, exu = ucv, exup = upcv, exv = vcv, exw = wcv, exwp = wpcv, nobs = nrow(x), maxit = .dFvGet()$mxg, nitmon = .dFvGet()$ntm, iloc = .dFvGet()$ilc, icnv = .dFvGet()$icv, tol = .dFvGet()$tlo, xfud = .dFvGet()$xfd) Arguments x See reference a See reference t See reference exu See reference exup See reference exv See reference exw See reference exwp See reference nobs See reference maxit See reference nitmon See reference iloc See reference icnv See reference tol See reference xfud See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.238 cynalg Newton-type algorithm for the computation of an M-estimate of mul- tivariate location and scatter Description See <NAME>. (1993), p.235 Usage cynalg(x, a, t, exu = ucv, exup = upcv, exv = vcv, exvp = vpcv, exw = wcv, exwp = wpcv, nobs = nrow(x), maxit = .dFvGet()$mxn, nitmon = .dFvGet()$ntm, iloc = .dFvGet()$ilc, icnv = .dFvGet()$icv, tol = .dFvGet()$tlo, xfud = .dFvGet()$xfd) Arguments x See reference a See reference t See reference exu See reference exup See reference exv See reference exvp See reference exw See reference exwp See reference nobs See reference maxit See reference nitmon See reference iloc See reference icnv See reference tol See reference xfud See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.235 Dbinom Diagonal matrix D for the binomial case in discrete GLM Description See <NAME>. (1993), p.310 Usage Dbinom(y, ci, vtheta, wa, ni, f0, oi = 0, kap = 1e-06) Arguments y See reference ci See reference vtheta See reference wa See reference ni See reference f0 See reference oi See reference kap See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.310 dfcomn Assigns values to the ROBETH parameters included in common blocks Description See <NAME>. (1993), p.405 Usage dfcomn(ipsi = -9, c = -1.345, h1 = -1.7, h2 = -3.4, h3 = -8.5, xk = -1.548, d = -1.345, beta = -0.5, bet0 = -1, iucv = -1, a2 = 0, b2 = -3, chk = -9, ckw = -2, bb = -1, bt = -1, cw = -1, em = -1.345, cr = -2, vk = -1, np = -2, nu = -1, v7 = -1, iwww = -1) Arguments ipsi Option parameter for the choice of ψ. Set -4 <= ipsi <= 4 c Parameter c of the Huber function h1 Parameter h1 of the Hampel function h2 Parameter h2 of the Hampel function h3 Parameter h3 of the Hampel function xk Parameter k of the rescaled Tukey biweight d See reference beta Parameter β to makeσ estimate asymptotically unbiased bet0 Parameter β0 to makeσ estimate asymptotically unbiased iucv Option parameter for the choice of u(s), u’(s), v(s), v’(s), w(s) or w’(s) a2 Parameter a^2 of Huber’s mimimax u-function b2 Parameter b^2 of Huber’s mimimax u-function chk Parameter c of the Hampel-Krasker u-function ckw Parameter c of the Krasker-Welsch u-function bb Parameter b of the Mallows-unstandard u-function bt Option parameter for w(s) or w’(s) cw Option parameter for w(s) or w’(s) em Parameter em for unstandard u-function cr Parameter cr for unstandard u-function vk Parameter vk for unstandard u-function np Parameter np for unstandard u-function nu Parameter nu for unstandard u-function v7 Parameter v for unstandard u-function iwww Option parameter for the choice of ω̄. Set 0 <= iwww <= 3 Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.405 dfrpar Sets default parameters for regression estimates Description See <NAME>. (1993), p.398 and p.406 Usage dfrpar(x, etype, upar = -1, psipar = -1) Arguments x See reference etype See reference upar See reference psipar See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.398 and p.406 dfvals Provide default values for most scalar parameters used by the Robeth subroutines Description See <NAME>. (1993), p.404 Usage dfvals() Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.404 dotp Forms the scalar (dot) product of two vectors Description See <NAME>. (1993), p.350 Usage dotp(x, y, n = nrow(x), incx = 1, incy = 1) Arguments x See reference y See reference n See reference incx See reference incy See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.350 dotpd Forms the scalar (dot) product of two vectors (double precision) Description See <NAME>. (1993), p.350 Usage dotpd(x, y, n = nrow(x), incx = 1, incy = 1) Arguments x See reference y See reference n See reference incx See reference incy See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.350 dpoiss Diagonal matrix D for the Poisson case in discrete GLM Description See <NAME>. (1993), p.312 Usage dpoiss(y, ci, vtheta, wa, f0, oi = 0, kap = 1e-06) Arguments y See reference ci See reference vtheta See reference wa See reference f0 See reference oi See reference kap See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.31 exch Exchanges two columns of a symmetric matrix Description See Marazzi A. (1993), p.364 Usage exch(s, n, h, k) Arguments s See reference n See reference h See reference k See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.364 exchd Exchanges two columns of a symmetric matrix (double precision) Description See Marazzi A. (1993), p.364 Usage exchd(s, n, h, k) Arguments s See reference n See reference h See reference k See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.364 fcum Cumulative F-distribution function Description See Marazzi A. (1993), p.379 Usage fcum(n1, n2, x) Arguments n1 See reference n2 See reference x See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.37 Fn.Exp.f Parametric estimate of survival cdf Description Parametric estimate of survival cdf Usage Fn.Exp.f(z, y , delta, mu, sigma, lambda, zero=1e-4) Arguments z See reference y See reference delta See reference mu See reference sigma See reference lambda See reference zero See reference Value See reference References Marazzi A. (2010) Robust estimation of the extended log-gamma (not yet published) fstord Determination of the j-th order statistic Description See Marazzi A. (1993), p.389 Usage fstord(y, j) Arguments y See reference j See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.389 gauss Cumulative Gaussian distribution function Description See Marazzi A. (1993), p.371 Usage gauss(kode = 1, x) Arguments kode See reference x See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.371 gaussd Cumulative Gaussian distribution function (double precision) Description See Marazzi A. (1993), p.371 Usage gaussd(kode = 1, x) Arguments kode See reference x See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.371 gfedca Diagonal matrices D_G and E_G Description See Marazzi A. (1993), p.309 Usage gfedca(vtheta, ci, wa, ni, oi = 0, icase = .dFvGet()$ics) Arguments vtheta See reference ci See reference wa See reference ni See reference oi See reference icase See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.309 gintac Initial values of theta, A and c_i,...,c_n Description See <NAME>. (1993), p.292 Usage gintac(x, y, ni, oi = 0, icase = .dFvGet()$ics, maxtt = .dFvGet()$mxt, maxta = .dFvGet()$mxf, tolt = .dFvGet()$tlo, tola = .dFvGet()$tlo, b = 1.1 * sqrt(np), c = 1.345) Arguments x See reference y See reference ni See reference oi See reference icase See reference maxtt See reference maxta See reference tolt See reference tola See reference b See reference c See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.292 glmdev The total deviance of the fitted generalizrd linear model Description Computes the sum of the vector deviance and other intermediate results Usage glmdev(y, ni, ci, wa, vtheta, offset = 0, icase = .dFvGet()$ics) Arguments y The vector of observations ni The number of trial at xi in the binomial case (ics=2). Otherwise ni=1 for each xi. ci The constants ci wa The vector of ai=b/|Axi| vtheta The vector of xi^T offset Optional offset added to the linear predictor. icase Set ics=1 for Bernoulli case, ics=2 for Binomial case and ics=3 for Poisson case Value A list with the following components: dev 2*sum_i abs(Li-Ti) thetas The estimates of theta_i li The values of Li sc The alues of Ti References <NAME>., <NAME>., <NAME>. (1989). Conditionally unbiased bounded-influence estimation in general regression models, with application to generalized linear models. Journal of the American Statistical Association, 84, 460-466. <NAME>. (1993). Algorithms, Routines, and S-functions for robust Statistics. Chapman and Hall, New York. <NAME>. (1997). Object oriented S-plus functions for robust discrete generalized linear models available in the doc folder of this package. gyastp Fixed-point algorithm for the A-step Description See <NAME>. (1993), p.301 Usage gyastp(x, y, ni, vtheta, ci, a, oi = 0, b = 1.1 * sqrt(nvar), iugl = .dFvGet()$iug, icase = .dFvGet()$ics, tau = .dFvGet()$tua, maxit = .dFvGet()$mxf, nitmon = .dFvGet()$ntm, icnv = .dFvGet()$icv, tol = .dFvGet()$tlo) Arguments x See reference y See reference ni See reference vtheta See reference ci See reference a See reference oi See reference b See reference iugl See reference icase See reference tau See reference maxit See reference nitmon See reference icnv See reference tol See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.301 gycstp Newton-type algorithm for the c-step Description See <NAME>. (1993), p.299 Usage gycstp(icase = .dFvGet()$ics, ialg = .dFvGet()$ilg, ni, a, e, tol = .dFvGet()$tlo, maxit = .dFvGet()$mxt, t) Arguments icase See reference ialg See reference ni See reference a See reference e See reference tol See reference maxit See reference t See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.299 gymain Main algorithm Description See <NAME>. (1993), p.304 Usage gymain(x, y, ni, cov, a, theta, oi = 0, b = 1.1 * sqrt(np), gam = .dFvGet()$gma, tau = .dFvGet()$tua, icase = .dFvGet()$ics, iugl = .dFvGet()$iug, iopt = .dFvGet()$ipo, ialg = .dFvGet()$ilg, icnvt = .dFvGet()$icn, icnva = .dFvGet()$icv, maxit = .dFvGet()$mxx, maxtt = .dFvGet()$mxt, maxta = .dFvGet()$mxf, maxtc = .dFvGet()$mxt, nitmnt = .dFvGet()$ntm, nitmna = .dFvGet()$ntm, tol = .dFvGet()$tlo, tolt = .dFvGet()$tlo * 10, tola = .dFvGet()$tlo * 10, tolc = .dFvGet()$tlo * 10) Arguments x See reference y See reference ni See reference cov See reference a See reference theta See reference oi See reference b See reference gam See reference tau See reference icase See reference iugl See reference iopt See reference ialg See reference icnvt See reference icnva See reference maxit See reference maxtt See reference maxta See reference maxtc See reference nitmnt See reference nitmna See reference tol See reference tolt See reference tola See reference tolc See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.304 gytstp Newton-type algorithm for the theta-step Description See <NAME>. (1993), p.295 Usage gytstp(x, y, ci, theta, wa, cov, ni, oi = 0, gam = .dFvGet()$gma, tol = .dFvGet()$tlo, tau = .dFvGet()$tua, iopt = .dFvGet()$ipo, icase = .dFvGet()$ics, icnv = .dFvGet()$icn, maxit = .dFvGet()$mxt, nitmon = .dFvGet()$ntm) Arguments x See reference y See reference ci See reference theta See reference wa See reference cov See reference ni See reference oi See reference gam See reference tol See reference tau See reference iopt See reference icase See reference icnv See reference maxit See reference nitmon See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.295 h12 Constructs and/or applies a single elementary Householder transfor- mation Description See Marazzi A. (1993), p.359 Usage h12(mode, lpivot, l1, u, up, c, ice, icv, ncv) Arguments mode See reference lpivot See reference l1 See reference u See reference up See reference c See reference ice See reference icv See reference ncv See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.359 h12d Constructs and/or applies a single elementary Householder transfor- mation (double precision) Description See <NAME>. (1993), p.359 Usage h12d(mode, lpivot, l1, u, up, c, ice, icv, ncv) Arguments mode See reference lpivot See reference l1 See reference u See reference up See reference c See reference ice See reference icv See reference ncv See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.35 hylmse Resampling algorithm for the computation of the LMS estimate Description See <NAME>. (1993), p.208 Usage hylmse(x, y, nq = np, ik = .dFvGet()$ik1, iopt = .dFvGet()$ipt, intch = .dFvGet()$ich, nrep, tol = .dFvGet()$tlo, tau = .dFvGet()$tua, iseed = .dFvGet()$isd) Arguments x See reference y See reference nq See reference ik See reference iopt See reference intch See reference nrep See reference tol See reference tau See reference iseed See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.208 hyltse Resampling algorithm for the computation of the LTS estimate Description See <NAME>. (1993), p.212 Usage hyltse(x, y, nq = np, ik = .dFvGet()$ik1, iopt = .dFvGet()$ipt, intch = .dFvGet()$ich, nrep, tol = .dFvGet()$tlo, tau = .dFvGet()$tua, iseed = .dFvGet()$isd, smin) Arguments x See reference y See reference nq See reference ik See reference iopt See reference intch See reference nrep See reference tol See reference tau See reference iseed See reference smin See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.212 hysest Resampling algorithm for the computation of S-estimates Description See <NAME>. (1993), p.216 Usage hysest(x, y, nq = np, iopt = .dFvGet()$ipt, intch = .dFvGet()$ich, nrep, tols = .dFvGet()$tls, tolr = .dFvGet()$tlr, tau = .dFvGet()$tua, gam = .dFvGet()$gma, maxit = .dFvGet()$mxt, maxs1 = .dFvGet()$msx, maxs2 = .dFvGet()$mxs, expsi = psi, expsp = psp, exchi = chi, iseed = .dFvGet()$isd) Arguments x See reference y See reference nq See reference iopt See reference intch See reference nrep See reference tols See reference tolr See reference tau See reference gam See reference maxit See reference maxs1 See reference maxs2 See reference expsi See reference expsp See reference exchi See reference iseed See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.216 hysestw Resampling algorithm for the computation of weighted S-estimates Description See <NAME>. (1993), p.216 Usage hysestw(x, y, wgt, nq = np, iopt = .dFvGet()$ipt, intch = .dFvGet()$ich, nrep, tols = .dFvGet()$tls, tolr = .dFvGet()$tlr, tau = .dFvGet()$tua, gam = .dFvGet()$gma, maxit = .dFvGet()$mxt, maxs1 = .dFvGet()$msx, maxs2 = .dFvGet()$mxs, expsi = psi, expsp = psp, exchi = chi, iseed = .dFvGet()$isd) Arguments x See reference y See reference wgt See reference nq See reference iopt See reference intch See reference nrep See reference tols See reference tolr See reference tau See reference gam See reference maxit See reference maxs1 See reference maxs2 See reference expsi See reference expsp See reference exchi See reference iseed See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.216 ingama Incomplete Gamma-integral function Description See Marazzi A. (1993), p.381 Usage ingama(x, p) Arguments x See reference p See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.381 kfascv Backtransformation of the covariance matrix of the coefficient esti- mates Description See Marazzi A. (1993), p.152 Usage kfascv(xt, cov, k = np, mdx = nrow(xt), f = .dFvGet()$fff, sg, ip) Arguments xt See reference cov See reference k See reference mdx See reference f See reference sg See reference ip See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.152 kfedcb Diagonal hat matrices D_M, E_M, D_S, and E_S Description See Marazzi A. (1993), p.159 Usage kfedcb(wgt, rs, expsi = psi, expsp = psp, sigma, itype = .dFvGet()$ite) Arguments wgt See reference rs See reference expsi See reference expsp See reference sigma See reference itype See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.15 kfedcc Diagonal ’check’ matrices D_M, E_M, D_S, and E_S Description See Marazzi A. (1993), p.160 Usage kfedcc(wgt, rs, expsi = psi, expsp = psp, sigma, itype = .dFvGet()$ite) Arguments wgt See reference rs See reference expsi See reference expsp See reference sigma See reference itype See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.160 kffacv Correction factor f_H for the covariance matrix of a Huber-type esti- mate Description See <NAME>. (1993), p.154 Usage kffacv(rs, expsi = psi, expsp = psp, np, sigma) Arguments rs See reference expsi See reference expsp See reference np See reference sigma See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.154 kiascv Covariance matrix of the coefficient estimates of the form f.inv(XT X) in the transformed coordinate system Description See Marazzi A. (1993), p.150 Usage kiascv(xt, k = np, mdx = nrow(xt), fu = .dFvGet()$fu1, fb = .dFvGet()$fb1) Arguments xt See reference k See reference mdx See reference fu See reference fb See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.150 kiedch Diagonal matrices D_M, E_M, D_S, E_S when psi is the Huber func- tion Description See Marazzi A. (1993), p.156 Usage kiedch(wgt, c = .dFvGet()$ccc, itype = .dFvGet()$ite) Arguments wgt See reference c See reference itype See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.156 kiedcu Diagonal matrices D_M, E_M, D_S, E_S when psi is a user-supplied function Description See Marazzi A. (1993), p.157 Usage kiedcu(wgt, expsi = psi, itype = .dFvGet()$ite, upper = .dFvGet()$upr, til = .dFvGet()$tli) Arguments wgt See reference expsi See reference itype See reference upper See reference til See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.157 ktaskv Covariance matrix of the coefficient estimates of the form f.inv(XT X) Description See Marazzi A. (1993), p.147 Usage ktaskv(x, n = nrow(x), tau = .dFvGet()$tua, f = .dFvGet()$fff) Arguments x See reference n See reference tau See reference f See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.147 ktaskw Covariance matrix of the coefficient estimates of the form f.inv(S1) S2 inv(S1) Description See Marazzi A. (1993), p.148 Usage ktaskw(x, d, e, tau = .dFvGet()$tua, ia = .dFvGet()$ia1, f = .dFvGet()$fff, f1 = .dFvGet()$ff1, iainv = .dFvGet()$ia2, a) Arguments x See reference d See reference e See reference tau See reference ia See reference f See reference f1 See reference iainv See reference a See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.148 lgama Logarithm at the Gamma-function at the point x Description See Marazzi A. (1993), p.383 Usage lgama(x) Arguments x See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.383 libet0 Computation of Beta0 = Phi_inv(0.75) Description See Marazzi A. (1993), p.46 Usage libet0() Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.46 libeth Computation of Int Chi(s) dPhi(s) when Chi=Psi.Psi/2 and Psi is the Huber function Description See Marazzi A. (1993), p.44 Usage libeth(d = .dFvGet()$ddd) Arguments d See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.44 libetu Computation of Int Chi(s) dPhi(s) when Chi is a user-supplied func- tion Description See Marazzi A. (1993), p.45 Usage libetu(exchi = chi, upper = .dFvGet()$upr, til = .dFvGet()$tli) Arguments exchi See reference upper See reference til See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.45 liclls Classical estimates of mean and standard deviation Description See Marazzi A. (1993), p.27 Usage liclls(y) Arguments y Vector of observations Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.27 liepsh Computation of Int Psi(s).Psi(s) dPhi(s) and Int Psi’(s) dPhi(s) when Psi is the Huber function Description See Marazzi A. (1993), p.47 Usage liepsh(c = .dFvGet()$ccc) Arguments c See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.47 liepsu Computation of Int Psi(s).Psi(s) dPhi(s) and Int Psi’(s) dPhi(s) when Psi is a user-supplied external function Description See Marazzi A. (1993), p.48 Usage liepsu(expsi = psi, upper = .dFvGet()$upr, til = .dFvGet()$tli) Arguments expsi See reference upper See reference til See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.48 liindh Inverts the approximate null distribution of the one-sample Wilcoxon test statistic Description See Marazzi A. (1993), p.36 Usage liindh(alpha = .dFvGet()$alf, n) Arguments alpha See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.36 liinds Inverts the approximate null distribution of the sign test statistic Description See Marazzi A. (1993), p.35 Usage liinds(alpha = .dFvGet()$alf, n) Arguments alpha See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.35 liindw Inverts the approximate null distribution of the Mann-Whitney test statistic Description See Marazzi A. (1993), p.43 Usage liindw(alpha = .dFvGet()$alf, m, n) Arguments alpha See reference m See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.43 lilars Median an median absolute deviation Description See Marazzi A. (1993), p.28 Usage lilars(y, isort = .dFvGet()$isr) Arguments y See reference isort See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.28 littst t-test for the shift parameter Description See Marazzi A. (1993), p.37 Usage littst(x, y, alpha = .dFvGet()$alf) Arguments x See reference y See reference alpha See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.37 lmdd Median and median absolute deviation Description See <NAME>. (1993), p.388 Usage lmdd(x, isort = 1) Arguments x See reference isort See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.388 lrfctd Computation of Li, li and lip Description See <NAME>. (1993), p.282-286 and p.297-298 Usage lrfctd(icase, y, ci, vtheta, offset, wa, ni, i0, i1, i2) Arguments icase Integer: 1 for Bernouilli, 2 for binomial and 3 for Poisson. y The y vector. ci The c_i vector. vtheta The x by theta vector. offset The offset vector. wa The a_i vector. ni The integer n_i vector. i0 Integer: 1 to compute Li otherwise 0. i1 Integer: 1 to compute li otherwise 0. i2 Integer: 1 to compute lip otherwise 0. Value List with the following components : f0 NULL if i0=0 else Li. i1 NULL if i1=0 else li , derivative of Li. i2 NULL if i2=0 else lip, derivative of li. sf0 NULL if i0=0 else sum of the Li components. References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.282-286 and p.297-298 lyhalg M-estimate of location with simultaneous estimation of scale Description See <NAME>. (1993), p.30 Usage lyhalg(y, expsi = psi, expsp = psp, exchi = chi, theta, sigmai, tol = .dFvGet()$tlo, gam = .dFvGet()$gma, isigma = .dFvGet()$isg, maxit = .dFvGet()$mxt, maxis = .dFvGet()$mxs) Arguments y See reference expsi See reference expsp See reference exchi See reference theta See reference sigmai See reference tol See reference gam See reference isigma See reference maxit See reference maxis See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.30 lyhdle Hodges-Lehman estimate and confidence intervals for the center of symmetry based on the one-sample Wilcoxon test Description See <NAME>. (1993), p.33 Usage lyhdle(y, isort = .dFvGet()$isr, k, tol = .dFvGet()$tlo, maxit = .dFvGet()$mxt) Arguments y See reference isort See reference k See reference tol See reference maxit See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.33 lymnwt Nonparametric estimate and confidence intervals for the shift param- eter based on the Mann-Whitney test statistic Description See <NAME>. (1993), p.41 Usage lymnwt(x, y, isort = .dFvGet()$isr, k, tol = .dFvGet()$tlo, maxit = .dFvGet()$mxt) Arguments x See reference y See reference isort See reference k See reference tol See reference maxit See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.41 lytau2 tau-test for the shift parameter Description See <NAME>. (1993), p.38 Usage lytau2(z, expsi = psi, expsp = psp, exchi = chi, exrho = rho, m, n, tol = .dFvGet()$tlo, gam = .dFvGet()$gma, isigma = .dFvGet()$isg, maxit = .dFvGet()$mxt, nitmon = .dFvGet()$ntm) Arguments z See reference expsi See reference expsp See reference exchi See reference exrho See reference m See reference n See reference tol See reference gam See reference isigma See reference maxit See reference nitmon See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.38 lywalg W-algorithm for M-estimate of location Description Robust location estimate with simultaneous estimation of the scale parameter Usage lywalg(y, lambda, psp0 = psp(0), expsi = psi, exchi = chi, exrho = rho, sigmai, tol = .dFvGet()$tlo, gam = .dFvGet()$gma, isigma = .dFvGet()$isg, maxit = .dFvGet()$mxt, maxis = .dFvGet()$mxs, nitmon = .dFvGet()$ntm) Arguments y Vector containing the observations lambda Initial solution of the location parameter psp0 Value of psp(0) (first derivative of the psi function) expsi User supplied psi function exchi User supplied chi function exrho User supplied rho function sigmai Initial estimate of the scale parameter tol Relative precision for the convergence criterion gam Relaxation factor. Set 0 < gam < 2. isigma If isigma<0, the value of sigma is not changed during the first iteration. If isigma=0, bypasss iteration on sigma (sigmaf=sigmai). If |isigma|>0, sigma is updated using the robeth function rysigm. maxit Maximum number of cycles maxis Maximum number of iterations for the scale step nitmon If nitmon>0 and the iteration counter is a multiple of nitmon, the current value of sigma, theta and delta are printed. If no iteration monitoring is required, set nitmon equal to 0. Details The .dFv variables for the default values must be created by a call to the dfvals() function of the robeth package. To see if this variable is available in your R session, type ls(all.names=TRUE). The parameters for psi, chi and rho functions must also be set by a preliminary call to the dfcomn function of the robeth package. Value lambda Final value of the location estimate nit Reached number of cycles sigmaf Final estimate of sigma rs The residual vector References <NAME>. (1993), Algorithm, Routines, and S functions for Robust Statistics, Wadsworth & Brooks/cole, Pacific Grove, California. p.30 and p.83 . mchl Cholesky decomposition of a symmetric matrix Description See Marazzi A. (1993), p.353 Usage mchl(a, n) Arguments a See reference n See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.353 mchld Cholesky decomposition of a symmetric matrix (double precision) Description See Marazzi A. (1993), p.353 Usage mchld(a, n) Arguments a See reference n See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.353 messagena Print a message when a required argument is missing Description Function only needed for the interface Usage messagena(x) Arguments x A character string Value None (invisible NULL). mff Multiplies a full matrix by a full matrix Description See Marazzi A. (1993), p.339 Usage mff(a, b, m = nrow(a)) Arguments a See reference b See reference m See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.339 mffd Multiplies a full matrix by a full matrix (double precision) Description See <NAME>. (1993), p.339 Usage mffd(a, b, m = nrow(a)) Arguments a See reference b See reference m See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.339 mfragr Generation and comparison of all regressions on subsets of covariates Description See <NAME>. (1993), p.258 Usage mfragr(x, y, vp, nc, itype = .dFvGet()$ith, c = .dFvGet()$ccc, tol = .dFvGet()$tlo, gam = .dFvGet()$gma, maxit = .dFvGet()$mxt, sigmac, sigmar) Arguments x See reference y See reference vp See reference nc See reference itype See reference c See reference tol See reference gam See reference maxit See reference sigmac See reference sigmar See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.258 mfy Multiplies a full matrix by a vector Description See <NAME>. (1993), p.342 Usage mfy(a, y, m = nrow(a), iye = 1, ize = 1) Arguments a See reference y See reference m See reference iye See reference ize See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.342 mfyd Multiplies a full matrix by a vector (double precision) Description See <NAME>. (1993), p.342 Usage mfyd(a, y, m = nrow(a), iye = 1, ize = 1) Arguments a See reference y See reference m See reference iye See reference ize See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.342 mhat Computes the diagonal elements of the hat matrix Description See Marazzi A. (1993), p.354 Usage mhat(x, n = nrow(x), k = np, sh) Arguments x See reference n See reference k See reference sh See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.354 minv Inverts a triangular matrix Description See <NAME>. (1993), p.348 Usage minv(r, n, tau = .dFvGet()$tua) Arguments r See reference n See reference tau See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.348 minvd Inverts a triangular matrix (double precision) Description See Marazzi A. (1993), p.348 Usage minvd(r, n, tau = .dFvGet()$tua) Arguments r See reference n See reference tau See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.348 mirtsr Computation of (robust) t-statistics for t-directed search Description See Marazzi A. (1993), p.262 Usage mirtsr(x, y, itype = .dFvGet()$ite, c = .dFvGet()$ccc, d = .dFvGet()$ddd, tol = .dFvGet()$tlo, gam = .dFvGet()$gma, maxit = .dFvGet()$mxt, maxis = .dFvGet()$mxs, tau = .dFvGet()$tua) Arguments x See reference y See reference itype See reference c See reference d See reference tol See reference gam See reference maxit See reference maxis See reference tau See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.262 mly Multiplies a lower-triangular matrix by a vector Description See Marazzi A. (1993), p.346 Usage mly(a, y, n, iye = 1) Arguments a See reference y See reference n See reference iye See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.346 mlyd Multiplies a lower-triangular matrix by a vector (double precision) Description See Marazzi A. (1993), p.346 Usage mlyd(a, y, n, iye = 1) Arguments a See reference y See reference n See reference iye See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.346 msf Multiplies a symmetric matrix by a full matrix Description See Marazzi A. (1993), p.340 Usage msf(a, b, n) Arguments a See reference b See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.340 msf1 Multiplies a symmetric matrix by a full matrix when the result is a symmetric matrix Description See Marazzi A. (1993), p.341 Usage msf1(a, b) Arguments a See reference b See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.341 msf1d Multiplies a symmetric matrix by a full matrix when the result is a symmetric matrix Description See Marazzi A. (1993), p.341 Usage msf1d(a, b) Arguments a See reference b See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.341 msfd Multiplies a symmetric matrix by a full matrix (double precision) Description See Marazzi A. (1993), p.340 Usage msfd(a, b, n) Arguments a See reference b See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California.v mss Multiplies a symmetric matrix by a symmetric matrix Description See Marazzi A. (1993), p.338 Usage mss(a, b, n) Arguments a See reference b See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.338 mssd Multiplies a symmetric matrix by a symmetric matrix (double preci- sion) Description See Marazzi A. (1993), p.342 Usage mssd(a, b, n) Arguments a See reference b See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.342 mtt1 Multiplies an upper-triangular matrix by its transpose Description See Marazzi A. (1993), p.343 Usage mtt1(a, n) Arguments a See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.343 mtt1d Multiplies an upper-triangular matrix by its transpose (double preci- sion) Description See Marazzi A. (1993), p.343 Usage mtt1d(a, n) Arguments a See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.343 mtt2 Multiplies a lower-triangular matrix by its transpose Description See Marazzi A. (1993), p.344 Usage mtt2(a, n) Arguments a See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.344 mtt2d Multiplies a lower-triangular matrix by its transpose (double preci- sion) Description See Marazzi A. (1993), p.344 Usage mtt2d(a, n) Arguments a See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.344 mtt3 Multiplies a triangular matrix by a triangular matrix Description See Marazzi A. (1993), p.345 Usage mtt3(a, b, n) Arguments a See reference b See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.345 mtt3d Multiplies a triangular matrix by a triangular matrix (double preci- sion) Description See Marazzi A. (1993), p.345 Usage mtt3d(a, b, n) Arguments a See reference b See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.345 mty Multiplies an upper-triangular matrix by a vector Description See Marazzi A. (1993), p.347 Usage mty(a, y, n, iye = 1) Arguments a See reference y See reference n See reference iye See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.347 mtyd Multiplies an upper-triangular matrix by a vector Description See Marazzi A. (1993), p.347 Usage mtyd(a, y, n, iye = 1) Arguments a See reference y See reference n See reference iye See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.347 myhbhe High breakdown point and high efficiency regression with test for bias Description See Marazzi A. (1993), p.270 Usage myhbhe(x, y, iseed = .dFvGet()$isd) Arguments x See reference y See reference iseed See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.270 mymvlm Simultaneous computation of the MVE and LMS estimates Description See Marazzi A. (1993), p.265 Usage mymvlm(x, y, ilms = .dFvGet()$ilm, iopt = .dFvGet()$ipt, intch = .dFvGet()$ich, nrep, tolv = .dFvGet()$tlv, tolm = .dFvGet()$tlm, tau = .dFvGet()$tua, iseed = .dFvGet()$isd) Arguments x See reference y See reference ilms See reference iopt See reference intch See reference nrep See reference tolv See reference tolm See reference tau See reference iseed See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.265 nlgm Logarithm of the Gamma-function at the point n/2 Description See Marazzi A. (1993), p.382 Usage nlgm(n) Arguments n See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.382 nrm2 Forms the Euclidean norm of a vector Description See Marazzi A. (1993), p.351 Usage nrm2(x, n = nrow(x), incx = 1) Arguments x See reference n See reference incx See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.351 nrm2d Forms the Euclidean norm of a vector (double precision) Description See Marazzi A. (1993), p.351 Usage nrm2d(x, n = nrow(x), incx = 1) Arguments x See reference n See reference incx See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.351 permc Permutes the columns of a matrix by means of transpositions Description See Marazzi A. (1993), p.365 Usage permc(x, it, n = nrow(x), iopt = 1) Arguments x See reference it See reference n See reference iopt See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.365 permv Permutes the elements of a vector Description See Marazzi A. (1993), p.366 Usage permv(y, it, iopt = 1) Arguments y See reference it See reference iopt See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.366 poissn Poisson distribution Description See Marazzi A. (1993), p.368 Usage poissn(lambda, k) Arguments lambda See reference k See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.368 precd Algorithmic determination of the smallest double precision positive number x Description See Marazzi A. (1993), p.385 Usage precd() Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.385 precs Algorithmic determination of the smallest double precision positive number x Description See Marazzi A. (1993), p.385 Usage precs() Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.385 probst Cumulative t-distribution function Description See Marazzi A. (1993), p.377 Usage probst(x, ifn) Arguments x See reference ifn See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.377 Psi psi weight function for location and regression Description See Marazzi A. (1993), p.319 Usage Psi(svals) Arguments svals A vector of input values Value The values of the psi weight function for each element of svals References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.319 psi psi weight function for location and regression Description See Marazzi A. (1993), p.319 Usage psi(s) Arguments s A scalar input value Value The value of the psi weight function for s References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.319 Psp psi’ weight function for location and regression Description See Marazzi A. (1993), p.320 Usage Psp(svals) Arguments svals A vector of input values Value The values of the psi’ weight function for each element of svals References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.320 psp psi’ weight function for location and regression Description See Marazzi A. (1993), p.320 Usage psp(s) Arguments s A scalar input value Value The value of the psi’ weight function for s References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.320 QD2coef.f Auxiliary function to find mu and sigma parameter for extended loggamma distribution Description QD2coef.f computes for a given lambda, the mu and sigma parameters Usage QD2coef.f(lambda, yc, delta, muI, sigmaI, zero=1e-4) Arguments lambda See reference yc See reference delta See reference muI See reference sigmaI See reference zero See reference Value See reference References <NAME>. (2010) Robust estimation of the extended log-gamma (not yet published) QD2funC.f Auxiliary function to find lambda parameter for extended loggamma distribution Description QD2funC.f computes a sum of squared residuals for a given lambda Usage QD2funC.f(lambda, yc, delta, muI, sigmaI, zero=1e-4) Arguments lambda See reference yc See reference delta See reference muI See reference sigmaI See reference zero See reference Value See reference References <NAME>. (2010) Robust estimation of the extended log-gamma (not yet published) Qn.Exp.f Auxiliary function to compute quantiles of survival cdf Description Qn.Exp.f computes quantiles of survival cdf Usage Qn.Exp.f(p, yc, delta, mu, sigma, lambda, zero=1e-4) Arguments p See reference yc See reference delta See reference mu See reference sigma See reference lambda See reference zero See reference Value See reference References <NAME>. (2010) Robust estimation of the extended log-gamma (not yet published) quant Inverse of the standard Gaussian cumulative distribution function Description See <NAME>. (1993), p.372 Usage quant(p) Arguments p See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.372 Random Uniform random number generator Description See <NAME>. (1993), p.386 Usage Random(iseed = .dFvGet()$isd) Arguments iseed See reference Details See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California.p.386 Regtau.f Auxiliary function for the computation of QQopt Description QQopt is a resampling algorithm for the determination of the parameters of a Loggamma model Usage Regtau.f(x, y, b1, c1, b2, c2, N, tol = 1e-6, seed = 567) Arguments x See reference y See reference b1 See reference c1 See reference b2 See reference c2 See reference N See reference tol See reference seed See reference Value See reference References <NAME>. (2009) Robust estimation of the generalized log-gamma (not yet published) RegtauW.f Auxiliary function for the computation of QQopt Description QQopt is a resampling algorithm for the determination of the parameters of a Loggamma model Usage RegtauW.f(x, y, w, b1, c1, b2, c2, N, tol = 1e-6, seed = 567) Arguments x See reference y See reference w See reference b1 See reference c1 See reference b2 See reference c2 See reference N See reference tol See reference seed See reference Value See reference References <NAME>. (2009) Robust estimation of the generalized log-gamma (not yet published) Rho Rho weight function for location and regression Description See <NAME>. (1993), p.320 Usage Rho(svals) Arguments svals A vector of input values Value The values of the rho function for each element of svals References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.320 rho rho weight function for location and regression Description See <NAME>. (1993), p.320 Usage rho(s) Arguments s A scalar input value Value The value of the rho function for s References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.320 ribet0 Computation of the constant Beta0 Description See <NAME>. (1993), p.100 Usage ribet0(wgt, itype = .dFvGet()$ite, isqw = .dFvGet()$isq, tol = .dFvGet()$tlo) Arguments wgt See reference itype See reference isqw See reference tol See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.10 ribeth Computation of the constant Beta when Chi=Psi.Psi/2 and Psi is the Huber function Description See <NAME>. (1993), p.97 Usage ribeth(wgt, d = .dFvGet()$ddd, itype = .dFvGet()$ite) Arguments wgt See reference d See reference itype See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.97 ribetu Computation of the constant Beta when Chi is a user-supplied func- tion Description See Marazzi A. (1993), p.98 Usage ribetu(wgt, exchi = chi, itype = .dFvGet()$ite, upper = .dFvGet()$upr, til = .dFvGet()$tli) Arguments wgt See reference exchi See reference itype See reference upper See reference til See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.98 riclls Solution of the least squares problem Description See Marazzi A. (1993), p.67 Usage riclls(xt, y, k = np, ix = .dFvGet()$ix1, iy = .dFvGet()$iy1, sf, sg, sh, ip) Arguments xt See reference y See reference k See reference ix See reference iy See reference sf See reference sg See reference sh See reference ip See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.67 rilars Solution of the least absolute residual problem Description See <NAME>. (1993), p.71 Usage rilars(x, y, tol = .dFvGet()$tlu) Arguments x See reference y See reference tol See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.71 rimtrd Double precision version of RIMTRF Description See Marazzi A. (1993), p.64 Usage rimtrd(x, n = nrow(x), intch = .dFvGet()$ith, tau = .dFvGet()$tua) Arguments x See reference n See reference intch See reference tau See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.64 See Also rimtrf rimtrf Upper triangularization (QR-decomposition) of the design matrix and determination of its pseudorank Description See <NAME>. (1993), p.64 Usage rimtrf(x, n = nrow(x), intch = .dFvGet()$ith, tau = .dFvGet()$tua) Arguments x See reference n See reference intch See reference tau See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.64 rmvc Removes a column from a transformed design matrix and updates its QR-decomposition Description See <NAME>. (1993), p.357 Usage rmvc(x, n = nrow(x), l, j, ip) Arguments x See reference n See reference l See reference j See reference ip See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.357 ruben Cumulative distribution and density function of a linear combination of chi-2 random variables Description See Marazzi A. (1993), p.375 Usage ruben(xlmbda, delta, mult, x, xmode = 1, maxit = 50, eps = 1e-04) Arguments xlmbda See reference delta See reference mult See reference x See reference xmode See reference maxit See reference eps See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.375 rybifr Bounded influence regression Description See <NAME>. (1993), p.410 Usage rybifr(x, y, np, nthet = np + 1, itype = 2, icoll = 0, isigma = 1, ch = 1.345, ck = 1.05 * sqrt(nthet), bm = 1.05 * sqrt(nthet), tol = 0.001, tau = 1e-06, maxitt = 50, maxitw = 80) Arguments x See reference y See reference np See reference nthet See reference itype See reference icoll See reference isigma See reference ch See reference ck See reference bm See reference tol See reference tau See reference maxitt See reference maxitw See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.410 ryhalg H-algorithm for M-estimates Description See <NAME>. (1993), p.98 Usage ryhalg(x, y, theta, wgt, cov, expsi = psi, exchi = chi, exrho = rho, sigmai, k = np, tol = .dFvGet()$tlo, gam = .dFvGet()$gma, tau = .dFvGet()$tua, itype = .dFvGet()$ite, ix = .dFvGet()$ix1, iy = .dFvGet()$iy1, ic = .dFvGet()$ic1, isigma = .dFvGet()$isg, icnv = .dFvGet()$icn, maxit = .dFvGet()$mxt, maxis = .dFvGet()$mxs, nitmon = .dFvGet()$ntm, sf, sg, sh, ip) Arguments x See reference y See reference theta See reference wgt See reference cov See reference expsi See reference exchi See reference exrho See reference sigmai See reference k See reference tol See reference gam See reference tau See reference itype See reference ix See reference iy See reference ic See reference isigma See reference icnv See reference maxit See reference maxis See reference nitmon See reference sf See reference sg See reference sh See reference ip See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.98 rynalg Newton algorithm with adaptive steps for M-estimates Description See <NAME>. (1993), p.73 Usage rynalg(x, y, theta, wgt, cov, expsi = psi, expsp = psp, exchi = chi, exrho = rho, sigmai, gam = .dFvGet()$gma, tol = .dFvGet()$tlo, tau = .dFvGet()$tua, itype = .dFvGet()$ite, iopt = .dFvGet()$iop, isigma = .dFvGet()$isg, icnv = .dFvGet()$icn, maxit = .dFvGet()$mxt, maxis = .dFvGet()$mxs, nitmon = .dFvGet()$ntm) Arguments x See reference y See reference theta See reference wgt See reference cov See reference expsi See reference expsp See reference exchi See reference exrho See reference sigmai See reference gam See reference tol See reference tau See reference itype See reference iopt See reference isigma See reference icnv See reference maxit See reference maxis See reference nitmon See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.73 rysalg S-algorithm for M-estimates Description See <NAME>. (1993), p.87 Usage rysalg(x, y, theta, wgt, cov, sigmai, tol = .dFvGet()$tlo, tau = .dFvGet()$tua, itype = .dFvGet()$ite, isigma = .dFvGet()$isg, icnv = .dFvGet()$icn, maxit = .dFvGet()$mxt, maxis = .dFvGet()$mxs, nitmon = .dFvGet()$ntm) Arguments x See reference y See reference theta See reference wgt See reference cov See reference sigmai See reference tol See reference tau See reference itype See reference isigma See reference icnv See reference maxit See reference maxis See reference nitmon See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.87 rysigm Iterative algorithm for the computation of an M-estimate of the scale parameter when the residuals are given Description See <NAME>. (1993), p.94 Usage rysigm(rs, wgt, exchi = chi, sigmai, np, tol = .dFvGet()$tlo, itype = .dFvGet()$ite, isigma = .dFvGet()$isg, maxis = .dFvGet()$mxt) Arguments rs See reference wgt See reference exchi See reference sigmai See reference np See reference tol See reference itype See reference isigma See reference maxis See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.94 rywalg W-algorithm for M-estimates Description See <NAME>. (1993), p.87 Usage rywalg(x, y, theta, wgt, cov, psp0 = psp(0), expsi = psi, exchi = chi, exrho = rho, sigmai, tol = .dFvGet()$tlo, gam = .dFvGet()$gma, tau = .dFvGet()$tua, itype = .dFvGet()$ite, isigma = .dFvGet()$isg, icnv = .dFvGet()$icn, maxit = .dFvGet()$mxt, maxis = .dFvGet()$mxs, nitmon = .dFvGet()$ntm) Arguments x See reference y See reference theta See reference wgt See reference cov See reference psp0 See reference expsi See reference exchi See reference exrho See reference sigmai See reference tol See reference gam See reference tau See reference itype See reference isigma See reference icnv See reference maxit See reference maxis See reference nitmon See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.87 scal Scales a vector by a constant Description See Marazzi A. (1993), p.349 Usage scal(x, sa, n = nrow(x), incx = 1) Arguments x See reference sa See reference n See reference incx See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.349 scald Scales a double precision vector by a constant Description See <NAME>. (1993), p.349 Usage scald(x, sa, n = nrow(x), incx = 1) Arguments x See reference sa See reference n See reference incx See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.349 See Also scal srt1 Sorts the components of a vector in ascending order Description See <NAME>. (1993), p.361 Usage srt1(a, k1 = 1, k2 = n) Arguments a See reference k1 See reference k2 See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.361 See Also srt2 srt2 Sorts the components of a vector in ascending order and permutes the components of another vector accordingly Description See Marazzi A. (1993), p.362 Usage srt2(a, b, k1 = 1, k2 = n) Arguments a See reference b See reference k1 See reference k2 See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.362 See Also srt1 swap Interchanges two vectors Description See <NAME>. (1993), p.363 Usage swap(x, y, n = nrow(x), incx = 1, incy = 1) Arguments x See reference y See reference n See reference incx See reference incy See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.363 See Also swapd swapd Interchanges two vectors (double precision) Description See <NAME>. (1993), p.363 Usage swapd(x, y, n = nrow(x), incx = 1, incy = 1) Arguments x See reference y See reference n See reference incx See reference incy See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.363 See Also swap tauare Asymptotic relative efficiency of the tau-test Description See <NAME>. (1993), p.190 Usage tauare(itype = .dFvGet()$ite, mu, maxit = .dFvGet()$mxe, cpsi, bb, sigmax = 1, upper = .dFvGet()$upr, til = .dFvGet()$tli, tol = .dFvGet()$tlo) Arguments itype See reference mu See reference maxit See reference cpsi See reference bb See reference sigmax See reference upper See reference til See reference tol See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.190 tfrn2t Computes the Rn2-test statistic for a linear hypothesis in canonical form Description See Marazzi A. (1993), p.187 Usage tfrn2t(cov, theta, n, nq, tau = .dFvGet()$tua) Arguments cov See reference theta See reference n See reference nq See reference tau See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.187 tftaut Computes the tau-test statistic for a linear hypothesis in canonical form Description See Marazzi A. (1993), p.182 Usage tftaut(rs1, rs2, wgt, exrho = rho, np, nq, sigma, itype = .dFvGet()$ite) Arguments rs1 See reference rs2 See reference wgt See reference exrho See reference np See reference nq See reference sigma See reference itype See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.182 tisrtc Permutes the columns of the design matrix: Predictors in omega are placed in the first q positions Description See Marazzi A. (1993), p.188 Usage tisrtc(x, iv, n = nrow(x)) Arguments x See reference iv See reference n See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.188 to.character Convert local variable to Fortran character Description Function only needed for the interface Usage to.character(x) Arguments x An R object Value x converted to character to.double Convert local variable to Fortran double precision Description Function only needed for the interface Usage to.double(x) Arguments x An R numeric object Value x converted to double precision to.integer Convert local variable to Fortran integer Description Function only needed for the interface Usage to.integer(x) Arguments x An R numeric object Value x converted to integer to.single Convert local variable to Fortran single precision Description Function only needed for the interface Usage to.single(x) Arguments x An R numeric object Value x converted to single precision tquant Inverse of the cumulative t-distribution function Description See <NAME>. (1993), p.378 Usage tquant(p, ifn) Arguments p See reference ifn See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.378 ttaskt Computes the matrix Ktau Description See <NAME>. (1993), p.184 Usage ttaskt(cov, ainv, np, nq, mdc = np - nq, fact = .dFvGet()$ffc) Arguments cov See reference ainv See reference np See reference nq See reference mdc See reference fact See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.184 tteign Computes the eigenvalues of the matrix Ktau Description See Marazzi A. (1993), p.186 Usage tteign(covtau, nq, mdc = np - nq) Arguments covtau See reference nq See reference mdc See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.186 Ucv u weight function for covariances Description See Marazzi A. (1993), p.323 Usage Ucv(svals) Arguments svals A vector of input values Value The values of the u function for each element of svals References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.323 ucv u weight function for covariances Description See Marazzi A. (1993), p.323 Usage ucv(s) Arguments s A scalar input value Value The value of the u function for s References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.323 ugl ub weight function for M-estimates in GLM Description See Marazzi A. (1993), p.331 Usage ugl(upar, npar = 4, s) Arguments upar See reference npar See reference s See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.331 Upcv u’ weight function for covariances Description See Marazzi A. (1993), p.325 Usage Upcv(svals) Arguments svals A vector of input values Value The values of the u function for each element of svals References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.325 upcv u’ weight function for covariances Description See Marazzi A. (1993), p.325 Usage upcv(s) Arguments s A scalar input value Value The value of the u’ function for s References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.325 userfd Dummy u user function (double precision) Description See Marazzi A. (1993), p.139 Usage userfd(s) Arguments s A scalar input value Value The double precision value of the u function for s References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.139 userfs Dummy u user function Description See Marazzi A. (1993), p.139 Usage userfs(s) Arguments s A scalar input value Value The single precision value of the u function for s References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.139 vcv v weight function for covariances Description See Marazzi A. (1993) p.327 Usage vcv(s) Arguments s A scalar input value Value The value of the v function for s References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.327 vpcv v’ weight function for covariances Description See Marazzi A. (1993), p.327 Usage vpcv(s) Arguments s A scalar input value Value The value of the v’ function for s References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.327 Wcv w weight function for covariances Description See Marazzi A. (1993), p.328 Usage Wcv(svals) Arguments svals A vector of input values Value The values of the w function for each element of svals References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.328 wcv v weight function for covariances Description See Marazzi A. (1993), p.328 Usage wcv(s) Arguments s A scalar input value Value The value of the w function for s References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.328 wfshat Schweppe original weight proposal Description See Marazzi A. (1993), p.137 Usage wfshat(xt, n = nrow(xt), sh) Arguments xt See reference n See reference sh See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.137 wimedv Initial value of the matrix A Description See Marazzi A. (1993), p.119 Usage wimedv(x, nobs = nrow(x), itypw = .dFvGet()$itw, init = .dFvGet()$ini, nfirst = nobs) Arguments x See reference nobs See reference itypw See reference init See reference nfirst See reference Value See reference References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.119 Wpcv w’ weight function for covariances Description See Marazzi A. (1993), p.329 Usage Wpcv(svals) Arguments svals A vector of input values Value The values of the w’ function for each element of svals References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.329 wpcv w’ weight function for covariances Description See Marazzi A. (1993), p.329 Usage wpcv(s) Arguments s A scalar input value Value The value of the w’ function for s References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.329 Www w weight function for covariances Description See Marazzi A. (1993), p.330 Usage Www(svals) Arguments svals A vector of input values Value The values of the w weight function for each element of svals References Marazzi A. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.330 www w weight function Description See Mar<NAME>. (1993), p.330 Usage www(s) Arguments s A scalar input value Value The value of the w weight function for s References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.330 wyfalg Fixed-point algorithm for the computation of the matrix A Description See <NAME>. (1993), p.121 Usage wyfalg(x, a, gwt, exu = ucv, nobs = nrow(x), nvarq = 0, tau = .dFvGet()$tua, maxit = .dFvGet()$mxf, nitmon = .dFvGet()$ntm, icnv = .dFvGet()$icv, itypw = .dFvGet()$itw, igwt = 0, tol = .dFvGet()$tlo) Arguments x See reference a See reference gwt See reference exu See reference nobs See reference nvarq See reference tau See reference maxit See reference nitmon See reference icnv See reference itypw See reference igwt See reference tol See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.121 wyfcol Modified fixed-point algorithm for collinear data in the standardized case Description See <NAME>. (1993), p.87 Usage wyfcol(x, exu = ucv, nobs = nrow(x), iwgt = .dFvGet()$iwg, apar = .dFvGet()$apr, tau = .dFvGet()$tua, tol = .dFvGet()$tlo, maxit = .dFvGet()$mxf, nitmon = .dFvGet()$ntm, icnv = .dFvGet()$icv) Arguments x See reference exu See reference nobs See reference iwgt See reference apar See reference tau See reference tol See reference maxit See reference nitmon See reference icnv See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.8 wygalg Conjugate gradient algorithm for the computation of the lower- triangular matrix A in the standardized case Description See <NAME>. (1993), p.127 Usage wygalg(x, a, exu = ucv, exup = upcv, nobs = nrow(x), maxit = .dFvGet()$mxg, nitmon = .dFvGet()$ntm, icnv = .dFvGet()$icv, tol = .dFvGet()$tlo, xfud = .dFvGet()$xfd) Arguments x See reference a See reference exu See reference exup See reference nobs See reference maxit See reference nitmon See reference icnv See reference tol See reference xfud See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.127 wynalg Newton-Huber algorithm for the computation of the lower-triangular matrix A in the standardized case Description See <NAME>. (1993), p.87 Usage wynalg(x, a, exu = ucv, exup = upcv, nobs = nrow(x), maxit = .dFvGet()$mxn, nitmon = .dFvGet()$ntm, icnv = .dFvGet()$icv, tol = .dFvGet()$tlo, xfud = .dFvGet()$xfd) Arguments x See reference a See reference exu See reference exup See reference nobs See reference maxit See reference nitmon See reference icnv See reference tol See reference xfud See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.87 xerf Gaussian density function Description See Marazzi A. (1993), p.369 Usage xerf(kode = 2, x) Arguments kode See reference x See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.369 xerp Density of the norm of a standard Gaussian vector with p components Description See Marazzi A. (1993), p.370 Usage xerp(ip, xlcnst = -1, s) Arguments ip See reference xlcnst See reference s See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.370 xsy Evaluates a quadratic form Description See Marazzi A. (1993), p.352 Usage xsy(x, y, s) Arguments x See reference y See reference s See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.352 xsyd Evaluates a quadratic form (double precision) Description See <NAME>. (1993) p.352 Usage xsyd(x, y, s) Arguments x See reference y See reference s See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.352 See Also xsy zemll Zeng method for censored data Description See Reference Usage zemll(b, x, yo, do) Arguments b See reference x See reference yo See reference do See reference Value See reference References <NAME>. (1993) Algorithm, Routines, and S functions for Robust Statistics. Wadsworth & Brooks/cole, Pacific Grove, California. p.216
stripe-rails
ruby
Ruby
Stripe::Rails: A Rails Engine for use with [stripe.com](https://stripe.com) === [![Gem Version](https://badge.fury.io/rb/stripe-rails.svg)](https://badge.fury.io/rb/stripe-rails) [![Build Status](https://travis-ci.org/tansengming/stripe-rails.svg?branch=master)](https://travis-ci.org/tansengming/stripe-rails) [![Code Climate](https://codeclimate.com/github/tansengming/stripe-rails/badges/gpa.svg)](https://codeclimate.com/github/tansengming/stripe-rails) [![Test Coverage](https://codeclimate.com/github/tansengming/stripe-rails/badges/coverage.svg)](https://codeclimate.com/github/tansengming/stripe-rails/coverage) [![Tidelift](https://tidelift.com/badges/github/tansengming/stripe-rails)](#) This gem can help your rails application integrate with Stripe in the following ways * manage stripe configurations in a single place. * makes stripe.js available from the asset pipeline. * manage product, prices, plans and coupons from within your app. * painlessly receive and validate webhooks from stripe. [📫 Sign up for the Newsletter](http://tinyletter.com/stripe-rails) to receive occasional updates. [Professionally supported stripe-rails is coming soon](https://tidelift.com/subscription/pkg/rubygems-stripe-rails?utm_source=rubygems-stripe-rails&utm_medium=referral&utm_campaign=readme) --- [Installation](#installation) * [Setup your API keys](#setup-your-api-keys) * [Manually set your API version (optional)](#manually-set-your-api-version-optional) [Setup your payment configuration](#setup-your-payment-configuration) * [Configuring your plans and coupons](#configuring-your-plans-and-coupons) [Stripe Elements](#stripe-elements) [Webhooks](#webhooks) * [Signed Webhooks](#signed-webhooks) + [Testing Signed Webhooks Locally](#testing-signed-webhooks-locally) * [Disabling auto mount](#disabling-auto-mount) * [Responding to webhooks](#responding-to-webhooks) * [Critical and non-critical hooks](#critical-and-non-critical-hooks) * [Filtering Callbacks](#filtering-callbacks) * [Catchall Callback](#catchall-callback) [Unit testing](#unit-testing) [Thanks](#thanks) [Code of Conduct](#code-of-conduct) Installation --- Add this line to your application's Gemfile: ``` gem 'stripe-rails' ``` If you are going to be using [stripe.js](https://stripe.com/docs/stripe.js) to securely collect credit card information on the client, then you will need to add the stripe javascript tags into your template. stripe-rails provides a helper to make this easy: ``` <%= stripe_javascript_tag %> ``` or, you can render it as a partial: ``` <%= render :partial => 'stripe/js' %> ``` In both cases, stripe-rails will choose a version of stripe.js appropriate for your development environment and automatically configure it to use your publishable API key. By default it uses `stripe-debug.js` for your `development` environment and `stripe.js` for everything else, but you can manually configure it per environment. ``` config.stripe.debug_js = true # use stripe-debug.js config.stripe.debug_js = false # use stripe.js ``` By default the helper renders the `v3` version of `stripe.js`. You can provide an alternate version to the helper to generate the appropriate tag: ``` <%= stripe_javascript_tag(:v2) %> ``` ### Setup your API keys. You will need to configure your application to authenticate with stripe.com using [your api key](https://stripe.com/docs/stripe.js). There are two methods to do this, you can either set the environment variable `STRIPE_SECRET_KEY`: ``` export STRIPE_SECRET_KEY=<KEY> ``` or if you are on heroku: ``` heroku config:add STRIPE_SECRET_KEY=sk_test_xxyyzz ``` You can also set this value from inside ruby configuration code: ``` config.stripe.secret_key = "<KEY>" ``` In either case, it is recommended that you *not* check in this value into source control. You can verify that your api is set up and functioning properly by running the following command: ``` rake stripe:verify ``` If you are going to be using stripe.js, then you will also need to set the value of your publishable key. A nice way to do it is to set your test publishable for all environments: ``` # config/application.rb # ... config.stripe.publishable_key = '<KEY>' ``` And then override it to use your live key in production only ``` # config/environments/production.rb # ... config.stripe.publishable_key = '<KEY>' ``` This key will be publicly visible on the internet, so it is ok to put in your source. If you prefer to environment variables, you can also set `STRIPE_PUBLISHABLE_KEY`: ``` export STRIPE_PUBLISHABLE_KEY=<KEY> ``` If no API key is provided, `stripe-rails` will show a warning: "No stripe.com API key was configured ...". You can silence this warning by setting the `ignore_missing_secret_key` option to `true`: ``` # config/environments/production.rb # ... config.stripe.ignore_missing_secret_key = true ``` ### Manually set your API version (optional) If you need to test a new API version in development, you can override the version number manually. ``` # config/environments/development.rb # ... config.stripe.api_version = '2015-10-16' ``` Setup your payment configuration --- If you're using subscriptions, then you'll need to set up your application's payment plans and discounts. `Stripe::Rails` lets you automate the management of these definitions from within the application itself. To get started: ``` rails generate stripe:install ``` this will generate the configuration files containing your plan and coupon definitions: ``` create config/stripe/products.rb create config/stripe/plans.rb create config/stripe/prices.rb create config/stripe/coupons.rb ``` ### Configuring your plans and coupons Use the plan builder to define as many plans as you want in `config/stripe/plans.rb` ``` [Stripe](/gems/stripe-rails/Stripe "Stripe (module)").plan :silver do |plan| plan.name = 'ACME Silver' plan.amount = 699 # $6.99 plan.interval = 'month' end [Stripe](/gems/stripe-rails/Stripe "Stripe (module)").plan :gold do |plan| plan.name = 'ACME Gold' plan.amount = 999 # $9.99 plan.interval = 'month' end [Stripe](/gems/stripe-rails/Stripe "Stripe (module)").plan :bronze do |plan| # Use an existing product id to prevent a new plan from # getting created plan.product_id = 'prod_XXXXXXXXXXXXXX' plan.amount = 999 # $9.99 plan.interval = 'month' # Use graduated pricing tiers # ref: https://stripe.com/docs/api/plans/object#plan_object-tiers plan.tiers = [ { unit_amount: 1500, up_to: 10 }, { unit_amount: 1000, up_to: 'inf' } ] plan.tiers_mode = 'graduated' # set the usage type to 'metered' plan.usage_type = 'metered' end ``` This will define constants for these plans in the Stripe::Plans module so that you can refer to them by reference as opposed to an id string. ``` [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Plans](/gems/stripe-rails/Stripe/Plans "Stripe::Plans (module)")::SILVER # => 'silver: ACME Silver' [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Plans](/gems/stripe-rails/Stripe/Plans "Stripe::Plans (module)")::GOLD # => 'gold: ACME Gold' ``` If you have to support an existing plan with a Stripe plan id that can not be used as a Ruby constant, provide the plan id as a symbol when defining the plan, but provide the name for the constant to define with `constant_name`: ``` [Stripe](/gems/stripe-rails/Stripe "Stripe (module)").plan "Silver-Plan".to_sym do |plan| plan.constant_name = 'SILVER_PLAN' # <--- plan.name = 'ACME Silver' plan.amount = 699 plan.interval = 'month' end [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Plans](/gems/stripe-rails/Stripe/Plans "Stripe::Plans (module)")::SILVER_PLAN # => will be defined # Will map to plan :id => "Silver-Plan" on Stripe ``` **Note** - If you're planning on running `rake stripe:prepare` to create your subscription plans, Stripe will restrict plan ids to match this regexp (`/\A[a-zA-Z0-9_\-]+\z/`) when created via API but still allows creation of plan ids that don't follow this restriction when manually created on stripe.com. Coupons are created in much the same way: ``` [Stripe](/gems/stripe-rails/Stripe "Stripe (module)").coupon :super_elite_free_vip do |coupon| coupon.duration = 'forever' coupon.percent_off = 100 coupon.max_redemptions = 5 end ``` As are Products: ``` [Stripe](/gems/stripe-rails/Stripe "Stripe (module)").product :primo do |product| product.name = 'PRIMO as a service' product.type = 'service' product.statement_descriptor = 'PRIMO' end ``` And Prices: ``` [Stripe](/gems/stripe-rails/Stripe "Stripe (module)").price :bronze do |price| # Use an existing product id to prevent a new product from # getting created price.product_id = [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Products](/gems/stripe-rails/Stripe/Products "Stripe::Products (module)")::PRIMO.id price.billing_scheme = 'tiered' price.recurring = { interval: 'month', usage_type: 'metered' } # Use graduated pricing tiers # ref: https://stripe.com/docs/api/prices/object#price_object-tiers price.tiers = [ { unit_amount: 1500, up_to: 10 }, { unit_amount: 1000, up_to: 'inf' } ] price.tiers_mode = 'graduated' end ``` To upload your plans, products, prices and coupons onto stripe.com, run: ``` rake stripe:prepare ``` This will create any plans, products, prices and coupons that do not currently exist, and treat as a NOOP any objects that already exist, so you can run this command safely as many times as you wish. Now you can use any of these objects in your application. NOTE: You must destroy plans and prices manually from your stripe dashboard. Stripe Elements --- Stripe::Rails allows you to easily include [Stripe Elements](https://stripe.com/payments/elements) in your application. > Stripe Elements are rich, pre-built UI components that help you create your own pixel-perfect checkout flows across desktop and mobile. Simply include the `stripe_elements_tag` anywhere below the `stripe_javascript_tag` and pass it the path to the controller action which will handle the Stripe token once the form is submitted: ``` <%= stripe_javascript_tag %> <%= stripe_elements_tag submit_path: billing_path %> ``` ### Configuration options Stripe::Rails comes bundled with default CSS and Javascript for Stripe elements, making it easy to drop in to your app. You can also specify your own assets paths: ``` <%= stripe_elements_tag submit_path: billing_path, css_path: 'your/asset/path', js_path: 'your/asset/path' %> ``` If you decide to use your own CSS and Javascript for Stripe Elements, please refer to the [Stripe elements docs](https://stripe.com/docs/stripe-js/elements/quickstart). To change the form text you can add the following keys to your locale files ``` # config/locales/en.yml en: stripe_rails: elements: label_text: Your label text submit_button_text: Your button text ``` Webhooks --- Stripe::Rails automatically sets up your application to receive webhooks from stripe.com whenever a payment event is generated. To enable this, you will need to configure your [stripe webhooks](https://manage.stripe.com/#account/webhooks) to point back to your application. By default, the webhook controller is mounted at '/stripe/events' so you would want to enter in `http://myproductionapp.com/stripe/events` as your url for live mode, and `http://mystagingapp.com/stripe/events` for your test mode. If you want to mount the stripe engine somewhere else, you can do so by setting the `stripe.endpoint` parameter. E.g. ``` config.stripe.endpoint = '/payment/stripe-integration' ``` Your new webhook URL would then be `http://myproductionapp/payment/stripe-integration/events` ### Signed Webhooks Validation of your webhook's signature uses your webhook endpoint signing secret. Before you can verify signatures, you need to retrieve your endpoint’s secret from your Stripe Dashboard. Select an endpoint for which you want to obtain the secret, then select the Click to reveal button. ``` # config/application.rb # ... config.stripe.signing_secrets = ['whsec_XXXYYYZZZ'] ``` Each secret is unique to the endpoint to which it corresponds. If you use multiple endpoint, you must obtain a secret for each one. After this setup, Stripe starts to sign each webhook it sends to the endpoint. Because of this, we recommend setting this variable with environment variables: ``` export STRIPE_SIGNING_SECRET=whsec_XXXYYYZZZ export STRIPE_CONNECT_SIGNING_SECRET=whsec_AAABBBCCC ``` ``` config.stripe.signing_secrets = [ENV.fetch('STRIPE_SIGNING_SECRET'), ENV.fetch('STRIPE_CONNECT_SIGNING_SECRET')] ``` The first secret that successfully matches for each incoming webhook will be used to verify the incoming events. #### Testing Signed Webhooks Locally In order to test signed webhooks, you'll need to trigger test webhooks from your Stripe dashboard, and configure your local environment to receive remote network requests. To do so, we recommend using [ngrok](https://ngrok.com/) to configure a secure tunnel to `localhost`. Once configured and running, `ngrok` will give you a unique URL which can be used to set up a webhook endpoint. Webhook endpoints are configured in your Dashboard's [Webhook settings](https://dashboard.stripe.com/account/webhooks) section. Make sure you are in **Test** mode and click `Add endpoint`, and provide your `ngrok` URL along with the `stripe.endpoint` suffix. An example webhook URL would then be `https://bf2a5d21.ngrok.io/stripe/events`. Once your endpoint is configured, you can reveal the **Signing secret**. This will need to be set as documented above: ``` # config/application.rb # ... config.stripe.signing_secrets = ['<KEY>'] ``` And you'll need to restart your rails server with: ``` rails restart ``` Now you're ready to click **Send test webhook**, and trigger whichever events you'd like to test from Stripe itself. ### Disabling auto mount Sometimes, you don't want the stripe engine to be auto-mounted so that you control *exactly* what priority it will take in your routing table. This is especially important if you have a catch-all route which should appear after all other routes. In order to disable auto-mounting of the Stripe engine: ``` # in application.rb config.stripe.auto_mount = false ``` Then, you will have to manually mount the engine in your main application. ``` # in your application's routes.rb: mount [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Engine](/gems/stripe-rails/Stripe/Engine "Stripe::Engine (class)") => "/stripe" ``` ### Responding to webhooks Once you have your webhook URL configured you can respond to a stripe webhook *anywhere* in your application just by including the Stripe::Callbacks module into your class and declaring a callback with one of the callback methods. For example, to update a customer's payment status: ``` class User < ActiveRecord::Base include [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Callbacks](/gems/stripe-rails/Stripe/Callbacks "Stripe::Callbacks (module)") after_customer_updated! do |customer, event| user = User.find_by_stripe_customer_id(customer.id) if customer.delinquent user.is_account_current = false user.save! end end end ``` or to send an email with one of your customer's monthly invoices ``` class InvoiceMailer < ActionMailer::Base include [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Callbacks](/gems/stripe-rails/Stripe/Callbacks "Stripe::Callbacks (module)") after_invoice_created! do |invoice, event| user = User.find_by_stripe_customer(invoice.customer) new_invoice(user, invoice).deliver end def new_invoice(user, invoice) @user = user @invoice = invoice mail :to => user.email, :subject => '[Acme.com] Your new invoice' end end ``` **Note:** `Stripe::Callbacks` won't get included until the including class has been loaded. This is usually not an issue in the production environment as eager loading is enabled by default (`config.eager_load = true`). You may run into an issue in your development environment where eager loading is disabled by default. If you don't wish to enable eager loading in development, you can configure the classes to be eager loaded like so ``` # in your application's config/environments/development.rb config.stripe.eager_load = 'account', 'module/some_class', 'etc' ``` This will ensure that callbacks will get loaded in those configured classes if eager loading is disabled. The naming convention for the callback events is after__callback_name! where `callback_name` is name of the stripe event with all `.` characters substituted with underscores. So, for example, the stripe event `customer.discount.created` can be hooked by `after_customer_discount_created!` and so on... Each web hook is passed an instance of the stripe object to which the event corresponds ([`Stripe::Customer`](https://stripe.com/docs/api?lang=ruby#customers), [`Stripe::Invoice`](https://stripe.com/docs/api?lang=ruby#invoices), [`Stripe::Charge`](https://stripe.com/docs/api?lang=ruby#charges), etc...) as well as the [`Stripe::Event`](https://stripe.com/docs/api?lang=ruby#events) which contains metadata about the event being raised. By default, the event is re-fetched securely from stripe.com to prevent damage to your system by a malicious system spoofing real stripe events. ### Critical and non-critical hooks So far, the examples have all used critical hooks, but in fact, each callback method comes in two flavors: "critical", specified with a trailing `!` character, and "non-critical", which has no "bang" character at all. What distinguishes one from the other is that *if an exception is raised in a critical callback, it will cause the entire webhook to fail*. This will indicate to stripe.com that you did not receive the webhook at all, and that it should retry it again later until it receives a successful response. On the other hand, there are some tasks that are more tangential to the payment work flow and aren't such a big deal if they get dropped on the floor. For example, A non-critical hook can be used to do things like have a bot notify your company's chatroom that something a credit card was successfully charged: ``` class AcmeBot include [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Callbacks](/gems/stripe-rails/Stripe/Callbacks "Stripe::Callbacks (module)") after_charge_succeeded do |charge| announce "Attention all Dudes and Dudettes. Ya'll are so PAID!!!" end end ``` Chances are that if you experience a momentary failure in connectivity to your chatroom, you don't want the whole payment notification to fail. ### Filtering Callbacks Certain stripe events represent updates to existing data. You may want to only fire the event when certain attributes of that data are updated. You can pass an `:only` option to your callback to filter to specify which attribute updates you're interested in. For example, to warn users whenever their credit card has changed: ``` class StripeMailer include [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Callbacks](/gems/stripe-rails/Stripe/Callbacks "Stripe::Callbacks (module)") after_customer_updated! :only => :active_card do |customer, evt| your_credit_card_on_file_was_updated_are_you_sure_this_was_you(customer).deliver end end ``` Filters can be specified as an array as well: ``` module Accounting include [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Callbacks](/gems/stripe-rails/Stripe/Callbacks "Stripe::Callbacks (module)") after_invoice_updated! :only => [:amount, :subtotal] do # update our records end end ``` Alternatively, you can just pass a proc to filter the event manually. It will receive an instance of [`Stripe::Event`](https://stripe.com/docs/api?lang=ruby#events) as its parameter: ``` module StagingOnly include Stripe::Callbacks after_charge_succeeded! :only => proc {|charge, evt| unless evt.livemode} do |charge| puts "FAKE DATA, PLEASE IGNORE!" end end ``` ### Catchall Callback The special 'stripe.event' callback will be invoked for every single event received from stripe.com. This can be useful for things like logging and analytics: ``` class StripeFirehose include [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Callbacks](/gems/stripe-rails/Stripe/Callbacks "Stripe::Callbacks (module)") after_stripe_event do |target, event| # do something useful end end ``` See the [complete listing of all stripe events](https://stripe.com/docs/api?lang=ruby#event_types), and the [webhook tutorial](https://stripe.com/docs/webhooks) for more great information on this subject. Unit testing --- If you want to test your callbacks, you can use the `Stripe::Rails::Testing` module to send mocked Stripe events. ``` require 'stripe/rails/testing' test "my callback handles new subscription" do [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Rails](/gems/stripe-rails/Stripe/Rails "Stripe::Rails (module)")::[Testing](/gems/stripe-rails/Stripe/Rails/Testing "Stripe::Rails::Testing (module)").[send_event](/gems/stripe-rails/Stripe/Rails/Testing#send_event-class_method "Stripe::Rails::Testing.send_event (method)") "customer.subscription.created" # Assertions end ``` You can also overwrite some event properties: ([More info](https://github.com/rebelidealist/stripe-ruby-mock#customizing-webhooks)) ``` require 'stripe/rails/testing' test "my callback handles new subscription" do [Stripe](/gems/stripe-rails/Stripe "Stripe (module)")::[Rails](/gems/stripe-rails/Stripe/Rails "Stripe::Rails (module)")::[Testing](/gems/stripe-rails/Stripe/Rails/Testing "Stripe::Rails::Testing (module)").[send_event](/gems/stripe-rails/Stripe/Rails/Testing#send_event-class_method "Stripe::Rails::Testing.send_event (method)") "customer.subscription.created", { :email => "[[email protected]](/cdn-cgi/l/email-protection)", :account_balance => 40 } # Assertions end ``` The default fixtures come from [the `stripe-ruby-mock` gem](https://github.com/rebelidealist/stripe-ruby-mock/tree/master/lib/stripe_mock/webhook_fixtures). Thanks --- [![Frontside](http://frontside.io/images/logo.svg)](http://frontside.io) `Stripe::Rails` was originally developed with love and fondness by your friends at [Frontside](http://frontside.io). They are available for your custom software development needs, including integration with stripe.com. [![Evercondo](https://dl.dropboxusercontent.com/s/m3ma9356uelep53/evercondo.png)](https://www.evercondo.com) `Stripe::Rails` has also been supported by the fine folks at [Evercondo](https://www.evercondo.com), the next generation condo management software. Code of Conduct --- Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms, which can be found in the `CODE_OF_CONDUCT.md` file in this repository.
holopy
readthedoc
Python
HoloPy 3.5.0 documentation [HoloPy](index.html#document-index) --- Holography and Light Scattering in Python[¶](#holography-and-light-scattering-in-python) === | Release: | 3.5.0 | `HoloPy` is a python based tool for working with digital holograms and light scattering. HoloPy can be used to analyze holograms in two complementary ways: * Backward propagation of light from a digital hologram to [reconstruct](index.html#recon-tutorial) 3D volumes. + This approach requires no prior knowledge about the scatterer * Forward propagation of light from a [scattering calculation](index.html#calc-tutorial) of a predetermined scatterer. + Comparison to a measured hologram with [Bayesian inference](index.html#fit-tutorial) allows precise measurement of scatterer properties and position. HoloPy provides a powerful and user-friendly python interface to fast scattering and optical propagation theories implemented in Fortran and C code. It also provides a set of flexible objects that make it easy to describe and analyze data from complex experiments or simulations. HoloPy started as a project in the [Manoharan Lab at Harvard University](http://manoharan.seas.harvard.edu/holopy). If you use HoloPy, you may wish to cite one or more of the sources listed in [References and credits](index.html#credits). We also encourage you to sign up for our [User Mailing List](https://groups.google.com/d/forum/holopy-users) or join us on [GitHub](https://github.com/manoharan-lab/holopy) to keep up to date on releases, answer questions, and benefit from other users’ questions. HoloPy Release Notes[¶](#holopy-release-notes) --- ### Holopy 3.5[¶](#holopy-3-5) #### Announcements[¶](#announcements) If you encounter errors loading prevoiusly saved HoloPy objects, try loading them with HoloPy 3.4 and saving a new version. See deprecation notes below. #### New Features[¶](#new-features) * New [`AberratedMieLens`](index.html#holopy.scattering.theory.mielens.AberratedMieLens) allows for calculating holograms of spheres as imaged through a lens with spherical aberrations. #### Improvements[¶](#improvements) * Calling a numpy ufunc on a Prior object with name kwarg gives the resulting TransformedPrior object that name, e.g. clip_x = np.min(x, name=’clipped’). * Cleaned up model parameter names created from TransformedPrior objects. * CmaStrategy now scales first step size based on initial population, not prior. * Inference models work with scattering theories that require parameters. See more in the user guide [The HoloPy Scatterer](index.html#scatterers-user). * Interpolation in background images is now robust to adjacent dead pixels. * Restored ability to call scattering functions on parameterized scatterers. #### Documentation[¶](#documentation) * Updated inference tutorial #### Bugfixes[¶](#bugfixes) * NmpfitStrategy now correctly accounts for non-uniform priors when optimizing. * Functional fitting interface no longer lets alpha go to zero. * Now able to save Model objects whose scatterer attribute contains xarrays. #### Compatibility Notes[¶](#compatibility-notes) * HoloPy now assumes dictionaries are ordered, so it requires python>=3.7. #### Developer Notes[¶](#developer-notes) * The [`ScatteringTheory`](index.html#holopy.scattering.theory.scatteringtheory.ScatteringTheory) now performs scattering calculations only, as its single responsibility. This should make it easier to implement new scattering theories. Code that was previously in [`ScatteringTheory`](index.html#holopy.scattering.theory.scatteringtheory.ScatteringTheory) that calculated deterimed at which points the scattering matrices or scattered fields needed to be calculated is now in holopy.scattering.imageformation. * The parameter parsing previously done by the Model class has now been broken out to a new hp.core.mapping module so it can be accessed by non-Model objects. * prior.py has been moved from to hp.core module from hp.inference but is still accessible in the hp.inference namespace. #### Deprecations[¶](#deprecations) * PerfectLensModel is now deprecated; lens models are now directly fittable with either AlphaModel or ExactModel. To do so, pass in a `holopy.prior.Prior` object as the lens_angle. * Inference-related deprecations started in 3.4 are now complete. This means that some old holopy inference objects are no longer loadable. If you still need to access these objects, holopy version 3.4 will let you load old inference objects and save them in the new format that is compatible with this (and future) versions of holopy. ### Holopy 3.4[¶](#holopy-3-4) #### New Features[¶](#id1) * New [`Lens`](index.html#holopy.scattering.theory.lens.Lens) scattering theory to model the effect of an objective lens can be applied to any other scattering theory. * New [`TransformedPrior`](index.html#holopy.core.prior.TransformedPrior) that applies a function to one or multiple component [`Prior`](index.html#holopy.core.prior.Prior) objects and maintains ties in a [`Model`](index.html#holopy.inference.model.Model). #### Improvements[¶](#id2) * DDA scattering theories no longer default to printing intermediate C output. * It is now possible to save all slices of a reconstruction stack as images. * Rearrangement of some Scatterer properties and methods so they are now accessible by a broader group of classes. * PerfectLensModel now accepts hologram scaling factor alpha as a parameter for inference. * It is now possible to pass an inference strategy to the high-level fit() and sample() functions, either by name or as a Strategy object. * High level inference functions fit() and sample() are now accessible in the root HoloPy namespace as hp.fit() and hp.sample(). * Scatterer.parameters() now matches the arguments to create the scatterer instead of deconstructing composite objects. * New prior.renamed() method to create an identical prior with a new name. * New way to easily construct scatterers from model parameters with `model.scatterer_from_parameters()`. * New `model.initial_guess` attribute which can be used to evaluate initial guess by psasing into `model.scatterer_from_parameters()` or `model.forward()` methods. * Model parameters now use the names of their prior objects if present. * Standardized parameter naming across composite objects (eg. list, dict). * Any model parameters can now be tied, not just specific combinations within Scatterers objects. * Expanded math operations of [`Prior`](index.html#holopy.core.prior.Prior) objects, including numpy ufuncs. * Math operations on `Prior` objects now use [`TransformedPrior`](index.html#holopy.core.prior.TransformedPrior) to maintain ties when used in a [`Model`](index.html#holopy.inference.model.Model). #### Documentation[¶](#id3) * New user guide on [The HoloPy Scatterer](index.html#scatterers-user). * New user guide on [The HoloPy Scattering Theories](index.html#theories-user). * More discussion of scattering theories in tutorial. #### Deprecations[¶](#id4) * The model.fit() and model.sample() methods have been deprecated in favour of the high-level hp.fit() and hp.sample functions(). * Adjustments to saving of Model objects (and Results objects containing them). Backwards compatibility is supported for now, but be sure to save new copies! * Scatterer.guess no longer exists. Instead, you must define a model and use: `model.scatterer_from_parameters(model.initial_guess)`. * Scatterer.from_parameters() is no longer guaranteed to return a definite object. * Composite scatterers no longer keep track of tied parameters. * Scattering interface functions such as calc_holo() now require a definite scatterer without priors. #### Bugfixes[¶](#id5) * Fortran output no longer occasionaly leaks through the output supression context manager used by multiple scattering theories. * Restored ability to visualize slices through a scatterer object * Now possible to fit only some elements of a list, eg. Scatterer center * Models can now include xarray parameters and still support saving/loading. * The [`MieLens`](index.html#holopy.scattering.theory.mielens.MieLens) scattering theory now works for both large and small spheres. * The `Lens` theory works for arbitrary linear polarization of the incoming light. This bug was not present on any releases, only on the development branch. #### Compatibility Notes[¶](#id6) * Holopy’s hard dependencies are further streamlined, and there is improved handling of missing optional dependencies. #### Developer Notes[¶](#id7) * Documentation now automatically runs sphinx apidoc when building docs. * New Scatterer attribute `_parameters` provides a view into the scatterer and supports editing. * [`ComplexPrior`](index.html#holopy.core.prior.ComplexPrior) now inherits from [`TransformedPrior`](index.html#holopy.core.prior.TransformedPrior), but Model maps don’t keep track of this, e.g. in model.scatterer. ### Holopy 3.3[¶](#holopy-3-3) #### New Features[¶](#id8) * Inference in holopy has been overhauled; take a look at the updated docs to check it out! Briefly, the inference and fitting modules have been combined into a unified, object-oriented interface, with several convenience functions available to the user both for the inference strategies and the inference results. One noticeable change with this is that the least-squares based fitting algorithms such as Nmpfit now work correctly with priors, including with non-uniform priors. There is also a new, user-friendly functionality for inference in holopy. Moreover, the inference pipelines can work with arbitrary user-defined functions instead of just holograms. * There is a new scattering theory, holopy.scattering.theory.MieLens, which describes the effect of the objective lens on recorded holograms of spherical particles. This new theory is especially useful if you want to analyze particles below the microscope focus. * There are two new inference strategies: a global optimizer CMA-ES strategy, under holopy.inference.cmaes.CmaStrategy, and a least-squares strategy which uses scipy.optimize.leastsq instead of the Nmpfit code. #### Deprecations[¶](#id9) * The keyword argument normals is deprecated in detector_points, detector_grid, and related functions, as the old implementation was incorrect. This deprecation is effective immediately; calling code with the normals keyword will raise a ValueError. * The old fitting interface, in holopy.fitting, is in the process of being deprecated (see “New Features” above). Calling the old fitting interface will raise a UserWarning but will otherwise work until the next holopy release. #### Bugfixes[¶](#id10) In addition to many minor bugfixes, the following user-facing bugs have been fixed: * load_average now works with a cropped reference image and uses less memory on large image stacks. * Issues with loss of fidelity on saving and loading objects have been fixed. * A bug where hp.propagate failed when gradient_filter=True has been fixed. * Tied parameters in inference calculations works correctly on edge cases. * Inference should work with more generic scatterers. * The Fortran code should be easier to build and install on Windows machines. This is partially done via a post-install script that checks that files are written to the correct location (which corrects some compiler differences between Windows and Linux). We still recommend installing Holopy with conda. #### Improvements[¶](#id11) * User-facing docstrings have been improved throughout holopy. * schwimmbad now handles parallel computations with Python’s multiprocessing or mpi. * More types of objects can be visualized with hp.show. * DDA default behaviour now has use_indicators=True since it is faster and better tested * The scaling of initial distributions both for Markov-Chain Monte Carlo and for CMA inference strategies can now be specified. #### Compatibility Notes[¶](#id12) * We are curently phasing out support for pre-3.6 Python versions (due to ordered vs unordered dicts). #### Developer Notes[¶](#id13) * Test coverage has dramatically increased in holopy. * Tests no longer output extraneous information on running. * The ScatteringTheory class has been refactored to allow for faster, more flexible extension. #### Miscellaneous Changes[¶](#miscellaneous-changes) * Some previously required dependencies are now optional. Tutorials[¶](#tutorials) --- Skip to the [Loading Data](index.html#load-tutorial) tutorial if you already have HoloPy installed and want to get started quickly. ### Getting Started[¶](#getting-started) #### Installation[¶](#installation) As of version 3.0, HoloPy supports only Python 3. We recommend using the [anaconda](https://www.continuum.io/anaconda-overview) distribution of Python, which makes it easy to install the required dependencies. HoloPy is available on [conda-forge](https://conda-forge.github.io/), so you can install it with: ``` conda install -c conda-forge holopy ``` in a shell, terminal, or command prompt. Once you have HoloPy installed, open an IPython console or Jupyter Notebook and run: ``` import holopy ``` If this line works, skip to [Using HoloPy](#usage) before diving into the tutorials. You can also build HoloPy from source by following the instructions for [Installing HoloPy for Developers](index.html#dev-install). ##### Dependencies[¶](#dependencies) HoloPy’s hard dependencies can be found in [requirements.txt](https://github.com/manoharan-lab/holopy/blob/master/requirements.txt). Optional dependencies for certain calculations include: * [a-dda](http://code.google.com/p/a-dda/) (Discrete Dipole calculations of arbitrary scatterers) * [mayavi2](http://docs.enthought.com/mayavi/mayavi/) (if you want to do 3D plotting [experimental]) #### Using HoloPy[¶](#using-holopy) You will probably be most comfortable using HoloPy in Jupyter (resembles Mathematica) or Spyder (resembles Matlab) interfaces. HoloPy is designed to be used with an interactive backend. In the console, try running: ``` from holopy import check_display check_display() ``` You should see an image, and you should be able to change the square to a circle or diamond by using the left/right arrow keys. If you can, then you’re all set! Check out our [Loading Data](index.html#load-tutorial) tutorial to start using HoloPy. If you don’t see an image, or if the arrow keys don’t do anything, you can try setting your backend with *one* of the following: ``` %matplotlib tk %matplotlib qt %matplotlib gtk %matplotlib gtk3 ``` Note that these commands will only work in an IPython console or Jupyter Notebook. If the one that you tried gave an `ImportError`, you should restart your kernel and try another. Note that there can only be one matplotlib backend per ipython kernel, so you have the best chance of success if you restart your kernel and immediately enter the `%matplotlib` command before doing anything else. Sometimes a backend will be chosen for you (that cannot be changed later) as soon as you plot something, for example by running `test_disp()` or [`show()`](index.html#holopy.core.io.vis.show). Trying to set to one of the above backends that is not installed will result in an error, but will also prevent you from setting a different backend until you restart your kernel. An additional option in Spyder is to change the backend through the menu: Tools > Preferences > IPython console > Graphics. It will not take effect until you restart your kernel, but it will then remember your backend for future sessions, which can be convenient. Additional options for inline interactive polts in jupyter are: ``` %matplotlib nbagg %matplotlib widget ``` ### Loading Data[¶](#loading-data) HoloPy can work with any image data, but our tutorials will focus on holograms. #### Loading and viewing a hologram[¶](#loading-and-viewing-a-hologram) We include a couple of example holograms with HoloPy. Lets start by loading and viewing one of them ``` import holopy as hp from holopy.core.io import get_example_data_path imagepath = get_example_data_path('image01.jpg') raw_holo = hp.load_image(imagepath, spacing = 0.0851) hp.show(raw_holo) ``` ([Source code](../pyplots/show_example_holo.py)) The first few lines just specify where to look for an image. The most important line actually loads the image so that you can work with it: ``` raw_holo = hp.load_image(imagepath, spacing = 0.0851) ``` HoloPy can import any image format that can be handled by [Pillow](http://pillow.readthedocs.io/en/3.3.x/handbook/image-file-formats.html). The spacing argument tells holopy about the scale of your image. Here, we had previously measured that each pixel is a square with side length 0.0851 micrometers. In general, you should specify `spacing` as the distance between adjacent pixel centres. You can load an image without a spacing value if you just want to look at it, but holopy calculations will give incorrect results. The final line displays the loaded image on your screen with the built-in HoloPy [`show()`](index.html#holopy.core.io.vis.show) function. If you don’t see anything, you may need to set your matplotlib backend. Refer to [Using HoloPy](index.html#usage) for instructions. #### Correcting Noisy Images[¶](#correcting-noisy-images) The raw hologram has some non-uniform illumination and an artifact in the upper-right corner. These can be removed if you take a background image with the same optical setup but without the object of interest. Dividing the raw hologram by the background using [`bg_correct()`](index.html#holopy.core.process.img_proc.bg_correct) improves the image a lot. ``` from holopy.core.process import bg_correct bgpath = get_example_data_path('bg01.jpg') bg = hp.load_image(bgpath, spacing = 0.0851) holo = bg_correct(raw_holo, bg) hp.show(holo) ``` ([Source code](../pyplots/show_bg_holo.py)) Often, it is beneficial to record multiple background images. In this case, we want an average image to pass into [`bg_correct()`](index.html#holopy.core.process.img_proc.bg_correct) as our background. ``` bgpath = get_example_data_path(['bg01.jpg', 'bg02.jpg', 'bg03.jpg']) bg = hp.core.io.load_average(bgpath, refimg = raw_holo) holo = bg_correct(raw_holo, bg) hp.show(holo) ``` Here, we have used [`load_average()`](index.html#holopy.core.io.io.load_average) to construct an average of the three background images specified in `bgpath`. The `refimg` argument allows us to specify a reference image that is used to provide spacing and other metadata to the new averaged image. If you are worried about stray light in your optical train, you should also capture a dark-field image of your sample, recorded with no laser illumination. A dark-field image is specified as an optional third argument to [`bg_correct()`](index.html#holopy.core.process.img_proc.bg_correct). ``` dfpath = get_example_data_path('df01.jpg') df = hp.load_image(dfpath, spacing = 0.0851) holo = bg_correct(raw_holo, bg, df) hp.show(holo) ``` Holopy includes some other convenient tools for manipulating image data. See the [HoloPy Tools](index.html#tools) page for details. #### Telling HoloPy about your Experimental Setup[¶](#telling-holopy-about-your-experimental-setup) Recorded holograms are a product of the specific experimental setup that produced them. The image only makes sense when considered with the experimental conditions in mind. When you load an image, you have the option to specify some of this information in the form of *metadata* that is associated with the image. In fact, we already saw an example of this when we specified image spacing earlier. The sample in our image was immersed in water (refractive index 1.33). Illumination was by a red laser with wavelength 660 nm and polarization in the x-direction. We can tell HoloPy all of this information when loading the image: ``` raw_holo = hp.load_image(imagepath, spacing=0.0851, medium_index=1.33, illum_wavelen=0.660, illum_polarization=(1,0)) ``` You can then view these metadata values as attributes of `raw_holo`, as in `raw_holo.medium_index`. However, you must use a special function [`update_metadata()`](index.html#holopy.core.metadata.update_metadata) to edit them. If we forgot to specify metadata when loading the image, we can use [`update_metadata()`](index.html#holopy.core.metadata.update_metadata) to add it later: ``` holo = hp.core.update_metadata(holo, medium_index=1.33, illum_wavelen=0.660, illum_polarization=(1,0)) ``` Note Spacing and wavelength must be given in the same units - micrometers in the example above. Holopy has no built-in length scale and requires only that you be consistent. For example, we could have specified both parameters in terms of nanometers or meters instead. HoloPy images are stored as [xarray DataArray](http://xarray.pydata.org/en/stable/data-structures.html) objects. xarray is a powerful tool that makes it easy to keep track of metadata and extra image dimensions, distinguishing between a time slice and a volume slice, for example. While you do not need any knowledge of xarray to use HoloPy, some familiarity will make certain tasks easier. This is especially true if you want to directly manipulate data before or after applying HoloPy’s built-in functions. #### Saving and Reloading Holograms[¶](#saving-and-reloading-holograms) Once you have background-divided a hologram and associated it with metadata, you might want to save it so that you can skip those steps next time you are working with the same image: ``` hp.save('outfilename', holo) ``` saves your processed image to a compact HDF5 file. In fact, you can use [`save()`](index.html#holopy.core.io.io.save) on any holopy object. To reload your same hologram with metadata you would write: ``` holo = hp.load('outfilename') ``` If you would like to save your hologram to an image format for easy visualization, use: ``` hp.save_image('outfilename', holo) ``` Additional options of [`save_image()`](index.html#holopy.core.io.io.save_image) allow you to control how image intensity is scaled. Although HoloPy stores metadata when writing to .tif image files, you should save holograms in HDF5 format using [`save()`](index.html#holopy.core.io.io.save) to avoid rounding. ### Reconstructing Data (Numerical Propagation)[¶](#reconstructing-data-numerical-propagation) A hologram contains information about the electric field amplitude and phase at the detector plane. Shining light back through a hologram allows reconstruction of the electric field at points upstream of the detector plane. HoloPy performs this function mathematically by numerically propagating a hologram (or electric field) to another position in space. This allows you to reconstruct 3D sample volumes from 2D images. The light source is assumed to be collimated here, but HoloPy is also capable of [Reconstructing Point Source Holograms](index.html#ps-recon-tutorial). #### Example Reconstruction[¶](#example-reconstruction) ``` import numpy as np import holopy as hp from holopy.core.io import get_example_data_path, load_average from holopy.core.process import bg_correct imagepath = get_example_data_path('image01.jpg') raw_holo = hp.load_image(imagepath, spacing = 0.0851, medium_index = 1.33, illum_wavelen = 0.66, ) bgpath = get_example_data_path(['bg01.jpg','bg02.jpg','bg03.jpg']) bg = load_average(bgpath, refimg = raw_holo) holo = bg_correct(raw_holo, bg) zstack = np.linspace(0, 20, 11) rec_vol = hp.propagate(holo, zstack) hp.show(rec_vol) ``` ([Source code](../pyplots/basic_recon.py)) We’ll examine each section of code in turn. The first block: ``` import numpy as np import holopy as hp from holopy.core.io import get_example_data_path, load_average from holopy.core.process import bg_correct ``` loads the relevant modules from HoloPy and NumPy. The second block: ``` imagepath = get_example_data_path('image01.jpg') raw_holo = hp.load_image(imagepath, spacing = 0.0851, medium_index = 1.33, illum_wavelen = 0.66) bgpath = get_example_data_path(['bg01.jpg','bg02.jpg','bg03.jpg']) bg = load_average(bgpath, refimg = raw_holo) holo = bg_correct(raw_holo, bg) ``` reads in a hologram and divides it by a corresponding background image. If this is unfamiliar to you, please review the [Loading Data](index.html#load-tutorial) tutorial. Next, we use numpy’s linspace to define a set of distances between the image plane and the reconstruction plane at 2-micron intervals to propagate our image to. You can also propagate to a single distance or to a set of distances obtained in some other fashion. The actual propagation is accomplished with [`propagate()`](index.html#holopy.propagation.convolution_propagation.propagate): ``` zstack = np.linspace(0, 20, 11) rec_vol = hp.propagate(holo, zstack) ``` Here, HoloPy has projected the hologram image through space to each of the distances contained in `zstack` by using the metadata that we specified when loading the image. If we forgot to load optical metadata with the image, we can explicitly indicate the parameters for propagation to obtain an identical object: ``` rec_vol = hp.propagate(holo, zstack, illum_wavelen = 0.660, medium_index = 1.33) ``` #### Visualizing Reconstructions[¶](#visualizing-reconstructions) You can display the reconstruction with [`show()`](index.html#holopy.core.io.vis.show): ``` hp.show(rec_vol) ``` Pressing the left and right arrow keys steps through volumes slices - propagation to different z-planes. If the left and right arrow keys don’t do anything, you might need to set your matplotlib backend. Refer to [Using HoloPy](index.html#usage) for instructions. Reconstructions are actually comprised of complex numbers. [`show()`](index.html#holopy.core.io.vis.show) defaults to showing you the amplitude of the image. You can get different, and sometimes better, contrast by viewing the phase angle or imaginary part of the reconstruction: ``` hp.show(rec_vol.imag) hp.show(np.angle(rec_vol)) ``` These phase sensitive visualizations will change contrast as you step through because you hit different places in the phase period. Such a reconstruction will work better if you use steps that are an integer number of wavelengths in medium: ``` med_wavelen = holo.illum_wavelen / holo.medium_index rec_vol = hp.propagate(holo, zstack*med_wavelen) hp.show(rec_vol.imag) ``` #### Cascaded Free Space Propagation[¶](#cascaded-free-space-propagation) HoloPy calculates reconstructions by performing a convolution of the hologram with the reference wave over the distance to be propagated. By default, HoloPy calculates a single transfer function to perform the convolution over the specified distance. However, a better reconstruction can sometimes be obtained by iteratively propagating the hologram over short distances. This cascaded free space propagation is particularly useful when the reconstructions have fine features or when propagating over large distances. For further details, refer to [Kreis 2002](http://dx.doi.org/10.1117/1.1489678). To implement cascaded free space propagation in HoloPy, pass a `cfsp` argument into [`propagate()`](index.html#holopy.propagation.convolution_propagation.propagate) indicating how many times the hologram should be iteratively propagated. For example, to propagate in three steps over each distance, we write: ``` rec_vol = hp.propagate(holo, zstack, cfsp = 3) ``` ### Reconstructing Point Source Holograms[¶](#reconstructing-point-source-holograms) Holograms are typically reconstructed optically by shining light back through them. This corresponds mathematically to propagating the field stored in the hologram to some different plane. The propagation performed here assumes that the hologram was recorded using a point source (diverging spherical wave) as the light source. This is also known as lens-free holography. Note that this is different than propagation calculations where a collimated light source (plane wave) is used. For recontructions using a plane wave see [Reconstructing Data (Numerical Propagation)](index.html#recon-tutorial). This point-source propagation calculation is an implementation of the algorithm that appears in [Jericho and Kreuzer 2010](http://link.springer.com/chapter/10.1007%2F978-3-642-15813-1_1). Curently, only square input images and propagation through media with a refractive index of 1 are supported. #### Example Reconstruction[¶](#example-reconstruction) ``` import holopy as hp import numpy as np from holopy.core.io import get_example_data_path from holopy.propagation import ps_propagate from scipy.ndimage.measurements import center_of_mass imagepath = get_example_data_path('ps_image01.jpg') bgpath = get_example_data_path('ps_bg01.jpg') L = 0.0407 # distance from light source to screen/camera cam_spacing = 12e-6 # linear size of camera pixels mag = 9.0 # magnification npix_out = 1020 # linear size of output image (pixels) zstack = np.arange(1.08e-3, 1.18e-3, 0.01e-3) # distances from camera to reconstruct holo = hp.load_image(imagepath, spacing=cam_spacing, illum_wavelen=406e-9, medium_index=1) # load hologram bg = hp.load_image(bgpath, spacing=cam_spacing) # load background image holo = hp.core.process.bg_correct(holo, bg+1, bg) # subtract background (not divide) beam_c = center_of_mass(bg.values.squeeze()) # get beam center out_schema = hp.core.detector_grid(shape=npix_out, spacing=cam_spacing/mag) # set output shape recons = ps_propagate(holo, zstack, L, beam_c, out_schema) # do propagation hp.show(abs(recons[:,350:550,450:650])) # display result ``` ([Source code](../pyplots/basic_ps_recon.py)) We’ll examine each section of code in turn. The first block: ``` import holopy as hp import numpy as np from holopy.core.io import get_example_data_path from holopy.propagation import ps_propagate from scipy.ndimage.measurements import center_of_mass ``` loads the relevant modules. The second block: ``` imagepath = get_example_data_path('ps_image01.jpg') bgpath = get_example_data_path('ps_bg01.jpg') L = 0.0407 # distance from light source to screen/camera cam_spacing = 12e-6 # linear size of camera pixels mag = 9.0 # magnification npix_out = 1020 # linear size of output image (pixels) zstack = np.arange(1.08e-3, 1.18e-3, 0.01e-3) # distances from camera to reconstruct ``` defines all parameters used for the reconstruction. Numpy’s linspace was used to define a set of distances at 10-micron intervals to propagate our image to. You can also propagate to a single distance or to a set of distances obtained in some other fashion. The third block: ``` holo = hp.load_image(imagepath, spacing=cam_spacing, illum_wavelen=406e-9, medium_index=1) # load hologram bg = hp.load_image(bgpath, spacing=cam_spacing) # load background image holo = hp.core.process.bg_correct(holo, bg+1, bg) # subtract background (not divide) beam_c = center_of_mass(bg.values.squeeze()) # get beam center out_schema = hp.core.detector_grid(shape=npix_out, spacing=cam_spacing/mag) # set output shape ``` reads in a hologram and subtracts the corresponding background image. If this is unfamiliar to you, please review the [Loading Data](index.html#load-tutorial) tutorial. The third block also finds the center of the reference beam and sets the size and pixel spacing of the output images. Finally, the actual propagation is accomplished with [`ps_propagate()`](index.html#holopy.propagation.point_source_propagate.ps_propagate) and a cropped region of the result is displayed. See the [Reconstructing Data (Numerical Propagation)](index.html#recon-tutorial) page for details on visualizing the reconstruction results. ``` recons = ps_propagate(holo, zstack, L, beam_c, out_schema) # do propagation hp.show(abs(recons[:,350:550,450:650])) # display result ``` #### Magnification and Output Image Size[¶](#magnification-and-output-image-size) Unlike the case where a collimated beam is used as the illumination and the pixel spacing in the reconstruction is the same as in the original hologram, for lens-free reconstructions the pixel spacing in the reconstruction can be chosen arbitrarily. In order to magnify the reconstruction the spacing in the reconstruction plane should be smaller than spacing in the original hologram. In the code above, the magnification of the reconstruction can be set using the variable `mag`, or when calling [`ps_propagate()`](index.html#holopy.propagation.point_source_propagate.ps_propagate) directly the desired pixel spacing in the reconstruction is specified through the spacing of `out_schema`. Note that the output spacing will not be the spacing of `out_schema` exactly, but should be within a few percent of it. We recommend calling [`get_spacing()`](index.html#holopy.core.metadata.get_spacing) on `recons` to get the actual spacing used. Note that the total physical size of the plane that is reconstructed remains the same when different output pixel spacings are used. This means that reconstructions with large output spacings will only have a small number of pixels, and reconstructions with small output spacings will have a large number of pixels. If the linear size (in pixels) of the total reconstruction plane is smaller than `npix_out`, the entire reconstruction plane will be returned. However, if the linear size of total reconstruction plane is larger than `npix_out`, only the center region of the reconstruction plane with linear size `npix_out` is returned. In the current version of the code, the amount of memory needed to perform a reconstruction scales with `mag`2. Presumably this limitation can be overcome by implementing the steps described in the *Convolution* section of the *Appendix* of [Jericho and Kreuzer 2010](http://link.springer.com/chapter/10.1007%2F978-3-642-15813-1_1). ### Scattering Calculations[¶](#scattering-calculations) Optical physicists and astronomers have worked out how to compute the scattering of light from many kinds of objects. HoloPy provides an easy interface for computing scattered fields, intensities, scattering matrices, cross-sections, and holograms generated by microscopic objects. (Computing scattering from macroscopic objects is computationally difficult and is not well-supported in HoloPy.) #### A Simple Example[¶](#a-simple-example) Let’s start by calculating an in-line hologram generated by a plane wave scattering from a microsphere. ``` import holopy as hp from holopy.scattering import calc_holo, Sphere sphere = Sphere(n=1.59, r=0.5, center=(4, 4, 5)) medium_index = 1.33 illum_wavelen = 0.660 illum_polarization = (1, 0) detector = hp.detector_grid(shape=100, spacing=0.1) holo = calc_holo(detector, sphere, medium_index, illum_wavelen, illum_polarization, theory='auto') hp.show(holo) ``` ([Source code](../pyplots/calc_sphere.py)) (You may need to call `matplotlib.pyplot.show()` if you can’t see the hologram after running this code.) To calculate a hologram, HoloPy needs to know two things: the *scatterer* that is scattering the light and the *experimental setup* under which the hologram is recorded. With those two, HoloPy chooses an appropriate *scattering theory* that calculates the hologram from the scatterer and the experimental setup; advanced users may want to choose the theory themselves. We’ll examine each section of code in turn. The first few lines : ``` import holopy as hp from holopy.scattering import calc_holo, Sphere ``` load the relevant modules from HoloPy that we’ll need for doing our calculation. The next line describes the *scatterer* we would like to model: ``` sphere = Sphere(n=1.59, r=0.5, center=(4, 4, 5)) ``` Scatterers are described in HoloPy by a [`Scatterer`](index.html#holopy.scattering.scatterer.scatterer.Scatterer) object. Here, we use a [`Sphere`](index.html#holopy.scattering.scatterer.sphere.Sphere) as the scatterer object. A [`Scatterer`](index.html#holopy.scattering.scatterer.scatterer.Scatterer) object contains information about the geometry (position, size, shape) and optical properties (refractive index) of the object that is scattering light. We’ve defined a spherical scatterer with radius 0.5 microns and index of refraction 1.59. This refractive index is approximately that of polystyrene. Next, we need to describe the *experimental setup*, including how we are illuminating our sphere, and how that light will be detected: ``` medium_index = 1.33 illum_wavelen = 0.66 illum_polarization = (1, 0) detector = hp.detector_grid(shape=100, spacing=0.1) ``` We are going to be using red light (wavelength = 660 nm in vacuum) polarized in the x-direction to illuminate a sphere immersed in water (refractive index = 1.33). Refer to [Units](index.html#units) and [Coordinate System](index.html#coordinate-system) if you’re confused about how the wavelength and polarization are specified. The scattered light will be collected at a detector, which is frequently a digital camera mounted onto a microscope. We defined our detector as a 100 x 100 pixel array, with each square pixel of side length .1 microns. The `shape` argument tells HoloPy how many pixels are in the detector and affects computation time. The `spacing` argument tells HoloPy how far apart each pixel is. Both parameters affect the absolute size of the detector. Finally, we need to specify the *scattering theory* which knows how to calculate the hologram from the experimental setup and the scatterer. By setting `theory='auto'`, we let HoloPy automatically select a theory. If no theory is specified, HoloPy will automatically select a theory as well. After getting everything ready, the actual scattering calculation is straightforward: ``` holo = calc_holo(detector, sphere, medium_index, illum_wavelen, illum_polarization, theory='auto') hp.show(holo) ``` Congratulations! You just calculated the in-line hologram generated at the detector plane by interference between the scattered field and the reference wave. For an in-line hologram, the reference wave is simply the part of the field that is not scattered or absorbed by the particle. You might have noticed that our scattering calculation requires much of the same metadata we specified when loading an image. If we have an experimental image from the system we would like to model, we can use that as an argument in [`calc_holo()`](index.html#holopy.scattering.interface.calc_holo) instead of our `detector` object created from [`detector_grid()`](index.html#holopy.core.metadata.detector_grid). HoloPy will calculate a hologram image with pixels at the same positions as the experimental image, and so we don’t need to worry about making a [`detector_grid()`](index.html#holopy.core.metadata.detector_grid) with the correct `shape` and `spacing` arguments. ``` from holopy.core.io import get_example_data_path imagepath = get_example_data_path('image0002.h5') exp_img = hp.load(imagepath) holo = calc_holo(exp_img, sphere) ``` Note that we didn’t need to explicitly specify illumination information when calling [`calc_holo()`](index.html#holopy.scattering.interface.calc_holo), since our image contained saved metadata and HoloPy used its values. Passing an image to a scattering function is particularly useful when comparing simulated data to experimental results, since we can easily recreate our experimental conditions exactly. So far all of the images we have calculated are holograms, or the interference pattern that results from the superposition of a scattered wave with a reference wave. Holopy can also be used to examine scattered fields on their own. Simply replace [`calc_holo()`](index.html#holopy.scattering.interface.calc_holo) with [`calc_field()`](index.html#holopy.scattering.interface.calc_field) to look at scattered electric fields (complex) or [`calc_intensity()`](index.html#holopy.scattering.interface.calc_intensity) to look at field amplitudes, which is the typical measurement in a light scattering experiment. #### More Complex Scatterers[¶](#more-complex-scatterers) Let’s proceed to a few examples with different [`Scatterer`](index.html#holopy.scattering.scatterer.scatterer.Scatterer) objects. You can find a more thorough desccription of all their functionalities in the user guide on [The HoloPy Scatterer](index.html#scatterers-user). ##### Coated Spheres[¶](#coated-spheres) HoloPy can also calculate holograms from coated (or multilayered) spheres. Constructing a coated sphere differs only in specifying a list of refractive indices and outer radii corresponding to the layers (starting from the core and working outwards). ``` coated_sphere = Sphere(center=(2.5, 5, 5), n=(1.59, 1.42), r=(0.3, 0.6)) holo = calc_holo(exp_img, coated_sphere) hp.show(holo) ``` If you prefer thinking in terms of the thickness of subsequent layers, instead of their distance from the center, you can use [`LayeredSphere`](index.html#holopy.scattering.scatterer.sphere.LayeredSphere) to achieve the same result: ``` from holopy.scattering import LayeredSphere coated_sphere = LayeredSphere(center=(2.5, 5, 5), n=(1.59, 1.42), t=(0.3, 0.3)) ``` ##### Collection of Spheres[¶](#collection-of-spheres) If we want to calculate a hologram from a collection of spheres, we must first define the spheres individually, and then combine them into a [`Spheres`](index.html#holopy.scattering.scatterer.spherecluster.Spheres) object: ``` from holopy.scattering import Spheres s1 = Sphere(center=(5, 5, 5), n = 1.59, r = .5) s2 = Sphere(center=(4, 4, 5), n = 1.59, r = .5) collection = Spheres([s1, s2]) holo = calc_holo(exp_img, collection) hp.show(holo) ``` Adding more spheres to the cluster is as simple as defining more sphere objects and passing a longer list of spheres to the [`Spheres`](index.html#holopy.scattering.scatterer.spherecluster.Spheres) constructor. ##### Non-spherical Objects[¶](#non-spherical-objects) To define a non-spherical scatterer, use [`Spheroid`](index.html#holopy.scattering.scatterer.spheroid.Spheroid) or [`Cylinder`](index.html#holopy.scattering.scatterer.cylinder.Cylinder) objects. These axisymmetric scatterers are defined by two dimensions, and can describe scatterers that are elongated or squashed along one direction. By default, these objects are aligned with the z-axis, but they can be rotated into any orientation by passing a set of Euler angles to the `rotation` argument when defining the scatterer. See [Rotations of Scatterers](index.html#rotations) for information on how these angles are defined. As an example, here is a hologram produced by a cylinder aligned with the vertical axis (`x-axis` according to the HoloPy [Coordinate System](index.html#coordinate-system)). Note that the hologram image is elongated in the horizontal direction since the sides of the cylinder scatter light more than the ends. ``` import numpy as np from holopy.scattering import Cylinder c = Cylinder(center=(5, 5, 7), n = 1.59, d=0.75, h=2, rotation=(0,np.pi/2, 0)) holo = calc_holo(exp_img, c) hp.show(holo) ``` #### More Complex Experimental Setups[¶](#more-complex-experimental-setups) While the examples above will be sufficient for most purposes, there are a few additional options that are useful in certain scenarios. ##### Multi-channel Holograms[¶](#multi-channel-holograms) Sometimes a hologram may include data from multiple illumination sources, such as two separate wavelengths of incident light. In this case, the extra arguments can be passed in as a dictionary object, with keys corresponding to dimension names in the image. You can also use a multi-channel experimental image in place of calling [`detector_grid()`](index.html#holopy.core.metadata.detector_grid). ``` illum_dim = {'illumination':['red', 'green']} n_dict = {'red':1.58,'green':1.60} wl_dict = {'red':0.690,'green':0.520} det_c = hp.detector_grid(shape=200, spacing=0.1, extra_dims = illum_dim) s_c = Sphere(r=0.6, n=n_dict, center=[6,6,6]) holo = calc_holo(det_c, s_c, illum_wavelen=wl_dict, illum_polarization=(0,1), medium_index=1.33) ``` ##### Scattering Theories in HoloPy[¶](#scattering-theories-in-holopy) HoloPy contains a number of scattering theories to model the scattering from different kinds of scatterers. You can specifiy a scattering theory by setting the `theory` keyword to a [`ScatteringTheory`](index.html#holopy.scattering.theory.scatteringtheory.ScatteringTheory) object, rather than setting the theory to `'auto'`. For instance, to force HoloPy to calculate the hologram of a sphere using Mie theory (the theory which exactly describes scattering from a spherical particle), we set the `theory` keyword to an instance of the [`Mie`](index.html#holopy.scattering.theory.mie.Mie) class: ``` from holopy.scattering.theory import Mie theory = Mie() holo = calc_holo(detector, sphere, medium_index, illum_wavelen, illum_polarization, theory=theory) ``` HoloPy has multiple scattering theories which work for different types of scatterers and which describe particle scattering and interactions with the optical train in varying degrees of complexity. HoloPy has scattering theories that describe scattering from individual spheres, layered spheres, clusters of spheres, spheroids, cylinders, and arbitrary objects. Some of these scattering theories can take parameters to modify how the theory performs the calculation (by, *e.g.*, making certain approximations or specifying properties of the optical train). For a more thorough description of these scattering theories and how HoloPy chooses default scattering theories, see the user guide, [The HoloPy Scattering Theories](index.html#theories-user). ##### Detector Types in HoloPy[¶](#detector-types-in-holopy) The [`detector_grid()`](index.html#holopy.core.metadata.detector_grid) function we saw earlier creates holograms that display nicely and are easily compared to experimental images. However, they can be computationally expensive, as they require calculations of the electric field at many points. If you only need to calculate values at a few points, or if your points of interest are not arranged in a 2D grid, you can use [`detector_points()`](index.html#holopy.core.metadata.detector_points), which accepts either a dictionary of coordinates or indvidual coordinate dimensions: ``` x = [0, 1, 0, 1, 2] y = [0, 0, 1, 1, 1] z = -1 coord_dict = {'x': x, 'y': y, 'z': z} detector = hp.detector_points(x = x, y = y, z = z) detector = hp.detector_points(coord_dict) ``` The coordinates for [`detector_points()`](index.html#holopy.core.metadata.detector_points) can be specified in terms of either Cartesian or spherical coordinates. If spherical coordinates are used, the `center` value of your scatterer is ignored and the coordinates are interpreted as being relative to the scatterer. #### Static light scattering calculations[¶](#static-light-scattering-calculations) ##### Scattering Matrices[¶](#scattering-matrices) In a static light scattering measurement you record the scattered intensity at a number of locations. A common experimental setup contains multiple detectors at a constant radial distance from a sample (or a single detector on a goniometer arm that can swing to multiple angles.) In this kind of experiment you are usually assuming that the detector is far enough away from the particles that the far-field approximation is valid, and you are usually not interested in the exact distance of the detector from the particles. So, it’s most convenient to work with amplitude scattering matrices that are angle-dependent. (See [[Bohren1983]](index.html#bohren1983) for further mathematical description.) ``` import numpy as np from holopy.scattering import calc_scat_matrix detector = hp.detector_points(theta = np.linspace(0, np.pi, 100), phi = 0) distant_sphere = Sphere(r=0.5, n=1.59) matr = calc_scat_matrix(detector, distant_sphere, medium_index, illum_wavelen) ``` Here we omit specifying the location (center) of the scatterer. This is only valid when you’re calculating a far-field quantity. Similarly, note that our detector, defined from a [`detector_points()`](index.html#holopy.core.metadata.detector_points) function, includes information about direction but not distance. It is typical to look at scattering matrices on a semilog plot. You can make one as follows: ``` import matplotlib.pyplot as plt plt.figure() plt.semilogy(np.linspace(0, np.pi, 100), abs(matr[:,0,0])**2) plt.semilogy(np.linspace(0, np.pi, 100), abs(matr[:,1,1])**2) plt.show() ``` ([Source code](../pyplots/calc_scat_matr.py)) You are usually interested in the intensities of the scattered fields, which are proportional to the modulus squared of the amplitude scattering matrix. The diagonal elements give the intensities for the incident light and the scattered light both polarized parallel and perpendicular to the scattering plane, respectively. ##### Scattering Cross-Sections[¶](#scattering-cross-sections) The scattering cross section provides a measure of how much light from an incident beam is scattered by a particular scatterer. Similar to calculating scattering matrices, we can omit the position of the scatterer for calculation of cross sections. Since cross sections integrates over all angles, we can also omit the `detector` argument entirely: ``` from holopy.scattering import calc_cross_sections x_sec = calc_cross_sections(distant_sphere, medium_index, illum_wavelen, illum_polarization) ``` x_sec returns an array containing four elements. The first element is the scattering cross section, specified in terms of the same units as wavelength and particle size. The second and third elements are the absorption and extinction cross sections, respectively. The final element is the average value of the cosine of the scattering angle. ### Scattering from Arbitrary Structures with DDA[¶](#scattering-from-arbitrary-structures-with-dda) The discrete dipole approximation (DDA) lets us calculate scattering from any arbitrary object by representing it as a closely packed array of point dipoles. In HoloPy you can make use of the DDA by specifying a general [`Scatterer`](index.html#holopy.scattering.scatterer.scatterer.Scatterer) with an indicator function (or set of functions for a composite scatterer containing multiple media). HoloPy uses [ADDA](http://code.google.com/p/a-dda/) to do the actual DDA calculations, so you will need to install ADDA and be able to run: ``` adda ``` at a terminal for HoloPy DDA calculations to succeed. To install ADDA, first download or clone the [code](https://github.com/adda-team/adda) from GitHub. In a terminal window, go to the directory ’adda/src’ and compile using one of three options: ``` make seq ``` or: ``` make ``` or: ``` make OpenCL ``` `make seq` will not take advantage of any parallel processing of the cores on your computer. `make` uses mpi for parallel processing. `make OpenCL` uses OpenCL for parallel processing. If the make does not work due to missing packages, you will have to download the specified packages and install them. Next, you must modify your path in your .bashrc or /bash_profile (for mac). Add the line: ``` export PATH=$PATH:userpath/adda/src/seq ``` or: ``` export PATH=$PATH:userpath/adda/src/mpi ``` or: ``` export PATH=$PATH:userpath/adda/src/OpenCL ``` where you should use the path that matches the make you chose above. A lot of the code associated with DDA is fairly new so be careful; there are probably bugs. If you find any, please [report](https://github.com/manoharan-lab/holopy/issues) them. #### Defining the geometry of the scatterer[¶](#defining-the-geometry-of-the-scatterer) To calculate the scattering pattern for an arbitrary object, you first need an indicator function which outputs ‘True’ if a test coordinate lies within your scatterer, and ‘False’ if it doesn’t. The indicator function is an argument of the constructor of your scatterer. For example, if you wanted to define a dumbbell consisting of the union of two overlapping spheres you could do so like this: ``` import holopy as hp from holopy.scattering import Scatterer, Sphere, calc_holo import numpy as np s1 = Sphere(r = .5, center = (0, -.4, 0)) s2 = Sphere(r = .5, center = (0, .4, 0)) detector = hp.detector_grid(100, .1) dumbbell = Scatterer(lambda point: np.logical_or(s1.contains(point), s2.contains(point)), 1.59, (5, 5, 5)) holo = calc_holo(detector, dumbbell, medium_index=1.33, illum_wavelen=.66, illum_polarization=(1, 0)) ``` Here we take advantage of the fact that Spheres can tell us if a point lies inside them. We use `s1` and `s2` as purely geometrical constructs, so we do not give them indices of refraction, instead specifying n when defining `dumbbell`. HoloPy contains convenient wrappers for many built-in ADDA constructions. The dumbbell defined explicitly above could also have been defined with the HoloPy [`Bisphere`](index.html#holopy.scattering.scatterer.bisphere.Bisphere) class instead. Similar classes exist to define an [`Ellipsoid`](index.html#holopy.scattering.scatterer.ellipsoid.Ellipsoid), [`Cylinder`](index.html#holopy.scattering.scatterer.cylinder.Cylinder), or [`Capsule`](index.html#holopy.scattering.scatterer.capsule.Capsule). #### Mutiple Materials: A Janus Sphere[¶](#mutiple-materials-a-janus-sphere) You can also provide a set of indicators and indices to define a scatterer containing multiple materials. As an example, lets look at a [janus sphere](http://en.wikipedia.org/wiki/Janus_particles) consisting of a plastic sphere with a high index coating on the top half: ``` from holopy.scattering.scatterer import Indicators import numpy as np s1 = Sphere(r = .5, center = (0, 0, 0)) s2 = Sphere(r = .51, center = (0, 0, 0)) def cap(point): return(np.logical_and(np.logical_and(point[...,2] > 0, s2.contains(point)), np.logical_not(s1.contains(point)))) indicators = Indicators([s1.contains, cap], [[-.51, .51], [-.51, .51], [-.51, .51]]) janus = Scatterer(indicators, (1.34, 2.0), (5, 5, 5)) holo = calc_holo(detector, janus, medium_index=1.33, illum_wavelen=.66, illum_polarization=(1, 0)) ``` We had to manually set up the bounds of the indicator functions here because the automatic bounds determination routine gets confused by the cap that does not contain the origin. We also provide a `JanusSphere` scatterer which is very similar to the scatterer defined above, but can also take a rotation angle to specify other orientations: ``` from holopy.scattering import JanusSphere janus = JanusSphere(n = [1.34, 2.0], r = [.5, .51], rotation = (-np.pi/2, 0), center = (5, 5, 5)) ``` ### Fitting Models to Data[¶](#fitting-models-to-data) As we have seen, we can use HoloPy to perform [Scattering Calculations](index.html#calc-tutorial) from many types of objects. Here, the goal is to compare these calculated holograms to a recorded experimental hologram, and adjust the parameters of the simulated scatterer to get a good fit for the real hologram. #### A Simple Least Squares Fit[¶](#a-simple-least-squares-fit) We start by loading and processing data using many of the functions outlined in the tutorial on [Loading Data](index.html#load-tutorial). ``` import holopy as hp import numpy as np from holopy.core.io import get_example_data_path, load_average from holopy.core.process import bg_correct, subimage, normalize from holopy.scattering import Sphere, Spheres, calc_holo from holopy.inference import prior, ExactModel, CmaStrategy, EmceeStrategy # load an image imagepath = get_example_data_path('image01.jpg') raw_holo = hp.load_image(imagepath, spacing = 0.0851, medium_index = 1.33, illum_wavelen = 0.66, illum_polarization = (1,0)) bgpath = get_example_data_path(['bg01.jpg','bg02.jpg','bg03.jpg']) bg = load_average(bgpath, refimg = raw_holo) data_holo = bg_correct(raw_holo, bg) # process the image data_holo = subimage(data_holo, [250,250], 200) data_holo = normalize(data_holo) ``` Next we define a scatterer that we wish to model as our initial guess. We can calculate the hologram that it would produce if it were placed in our experimental setup, as in the previous tutorial on [Scattering Calculations](index.html#calc-tutorial). Fitting works best if your initial guess is close to the correct result. You can find guesses for x and y coordinates with [`center_find()`](index.html#holopy.core.process.centerfinder.center_find), and a guess for z with [`propagate()`](index.html#holopy.propagation.convolution_propagation.propagate). ``` guess_sphere = Sphere(n=1.58, r=0.5, center=[24,22,15]) initial_guess = calc_holo(data_holo, guess_sphere) hp.show(data_holo) hp.show(initial_guess) ``` Finally, we can adjust the parameters of the sphere in order to get a good fit to the data. Here we adjust the center coordinates (x, y, z) of the sphere and its radius, but hold its refractive index fixed. By default [`fit()`](index.html#holopy.inference.interface.fit) will adjust all parameters, so we can omit the argument if that is what we want. ``` parameters_to_fit = ['x', 'y', 'z', 'r'] fit_result = hp.fit(data_holo, guess_sphere, parameters=parameters_to_fit) ``` The [`fit()`](index.html#holopy.inference.interface.fit) function automatically runs [`calc_holo()`](index.html#holopy.scattering.interface.calc_holo) on many different sets of parameter values to find the combination that gives the best match to the experimental `data_holo`. We get back a [`FitResult`](index.html#holopy.inference.result.FitResult) object that knows how to summarize the results of the fitting calculation in various ways, and can be saved to a file with `hp.save`()` : ``` best_fit_values = fit_result.parameters initial_guess_values = fit_result.guess_parameters best_fit_sphere = fit_result.scatterer best_fit_hologram = fit_result.hologram best_fit_lnprob = fit_result.max_lnprob hp.save('results_file.h5', fit_result) ``` If we look at `best_fit_values` or `best_fit_sphere`, we see that our initial guess of the sphere’s position of (24, 22, 15) was corrected to (24.16, 21.84, 16.35). Note that we have achieved sub-pixel position resolution! #### Customizing the model[¶](#customizing-the-model) Sometimes you might want a bit more control over how the parameters are varied. You can customize the parameters with a [`Model`](index.html#holopy.inference.model.Model) object that describes parameters as [`Prior`](index.html#holopy.core.prior.Prior) objects instead of simply passing in your best guess scatterer and the names of the parameters you wish to vary. For example, we can set bounds on the coordinate parameters and use a Gaussian prior for the radius - here, with a mean of 0.5 and standard deviation of 0.05 micrometers. ``` x = prior.Uniform(lower_bound=15, upper_bound=30, guess=24) y = prior.Uniform(15, 30, 22) z = prior.Uniform(10, 20) par_sphere = Sphere(n=1.58, r=prior.Gaussian(0.5, 0.05), center=[x, y, z]) model = ExactModel(scatterer=par_sphere, calc_func=calc_holo) fit_result = hp.fit(data_holo, model) ``` Here we have used an [`ExactModel`](index.html#holopy.inference.model.ExactModel) which takes a function `calc_func` to apply on the [`Scatterer`](index.html#holopy.scattering.scatterer.scatterer.Scatterer) (we have used [`calc_holo()`](index.html#holopy.scattering.interface.calc_holo) here). The [`ExactModel`](index.html#holopy.inference.model.ExactModel) isn’t actually the default when we call [`fit()`](index.html#holopy.inference.interface.fit) directly. Instead, HoloPy uses an [`AlphaModel`](index.html#holopy.inference.model.AlphaModel), which includes an additional fitting parameter to control the hologram contrast intensity - the same as calling [`calc_holo()`](index.html#holopy.scattering.interface.calc_holo) with a scaling argument. You can fit for the extra parameters in these models by defining them as [`Prior`](index.html#holopy.core.prior.Prior) objects. Likewise, if the scattering theory you are using requires fittable parameters (such as the lens_angle for the [`MieLens`](index.html#holopy.scattering.theory.mielens.MieLens) theory or the spherical_aberration for the [`AberratedMieLens`](index.html#holopy.scattering.theory.mielens.AberratedMieLens) theory), you can fit for these by defining them as [`Prior`](index.html#holopy.core.prior.Prior) objects as well. The model in our example has read in some metadata from `data_holo` (illumination wavelength & polarization, medium refractive index, and image noise level). If we want to override those values, or if we loaded an image without specifying metadata, we can pass them directly into the [`Model`](index.html#holopy.inference.model.Model) object by using keywords when defining it. ##### Advanced Parameter Specification[¶](#advanced-parameter-specification) You can use the [`Model`](index.html#holopy.inference.model.Model) framework to more finely control parameters, such as specifying a complex refractive index : ``` n = prior.ComplexPrior(real=prior.Gaussian(1.58, 0.02), imag=1e-4) ``` When this refractive index is used to define a [`Sphere`](index.html#holopy.scattering.scatterer.sphere.Sphere), [`fit()`](index.html#holopy.inference.interface.fit) will fit to the real part of index of refraction while holding the imaginary part fixed. You could fit it as well by specifying a [`Prior`](index.html#holopy.core.prior.Prior) for `imag`. You may desire to fit holograms with *tied parameters*, in which several physical quantities that could be varied independently are constrained to have the same (but non-constant) value. A common example involves fitting a model to a multi-particle hologram in which all of the particles are constrained to have the same refractive index, but the index is determined by the fitter. This may be done by defining a parameter and using it in multiple places. Other tools for handling tied parameters are described in the user guide on [The HoloPy Scatterer](index.html#scatterers-user). ``` n1 = prior.Gaussian(1.58, 0.02) sphere_cluster = Spheres([ Sphere(n = n1, r = 0.5, center = [10., 10., 20.]), Sphere(n = n1, r = 0.5, center = [9., 11., 21.])]) ``` #### Transforming Priors[¶](#transforming-priors) Sometimes you might want to apply mathematical operations to transform one prior into another, for example in the following use cases: * You want two parameters to vary together with values that are related but unequal, such as the length and radius of a cylinder with known aspect ratio, or the z-coordinates of two vertically stacked particles. * You want a parameter that is distrbuted according to some other distribution, such as a cylinder axis evenly distributed in spherical coordinates or a sphere with uniformly distributed volume (not radius). * You want to reparamaterize a problem to reduce covariances between fitting parameters, such as finding the separation distance between two closely interacting particles or to find the positions of particles confined to a plane with a slight tilt as compared to the x-y plane. If you have an explicit transformation function you can use it to define a [`TransformedPrior`](index.html#holopy.core.prior.TransformedPrior) object, for example to define a polar angle with the appropriate distribution we might do: ``` def uniform2polar(u): # we want polar angle \theta distributed according to sin(\theta) # Use inverse transform sampling, correct for \theta in [0, pi] symmetric_polar = np.arcsin(u) return symmetric_polar + np.pi/2 director = prior.Uniform(-1, 1, name='director') polar_angle = prior.TransformedPrior(uniform2polar, director, name='polar') ``` You can use [`TransformedPrior`](index.html#holopy.core.prior.TransformedPrior) objects when defining a [`Scatterer`](index.html#holopy.scattering.scatterer.scatterer.Scatterer) just like regular priors. They share some attributes with basic priors as well, such as the [`TransformedPrior.sample()`](index.html#holopy.core.prior.TransformedPrior.sample) method, but you cannot directly calculate probabilities or log-probabilities of a [`TransformedPrior`](index.html#holopy.core.prior.TransformedPrior) taking on a particular value. Besides explicitly defining them, you can also create [`TransformedPrior`](index.html#holopy.core.prior.TransformedPrior) objects by using numpy ufuncs and built-in operators on priors: ``` sphere_area = prior.Uniform(1, 2, name='base_area') diameter = np.sqrt(sphere_area / np.pi) radius = diameter / 2 shell = radius + 0.1 ``` All of our derived objects are [`TransformedPrior`](index.html#holopy.core.prior.TransformedPrior) objects, even though we didn’t explicitly define them that way. If we use more than one of `sphere_area`, `diameter`, `radius`, or `shell` in a fitting or inference calculation, they will all be derived from a single parameter (`sphere_area` in this case) even though they take on different values. Note that we could have expressed `shell` in one line if we didn’t care about the intermediate values: ``` shell = np.sqrt(prior.Uniform(1, 2, name='base_area')) / 2 + 0.1 shell.name = 'shell' ``` It’s always a good idea to assign your priors names when working with [`TransformedPrior`](index.html#holopy.core.prior.TransformedPrior) objects to keep track of their relationships. Parameter names will be generated if none are provided but they might not be very informative. To help with naming, you can even assign names to [`TransformedPrior`](index.html#holopy.core.prior.TransformedPrior) objects when using numpy ufuncs! ``` diameter = np.sqrt(sphere_area / np.pi, name='diameter') ``` #### Bayesian Parameter Estimation[¶](#bayesian-parameter-estimation) Often, we aren’t just interested in the best-fit (MAP) parameter values, but in the full range of parameter values that provide a reasonable fit to an observed hologram. This is best expressed as a Bayesian posterior distribution, which we can sample with a Markov Chain Monte Carlo (MCMC) algorithm. The approach and formalism used by HoloPy are described in more detail in [[Dimiduk2016]](index.html#dimiduk2016). For more information on Bayesian inference in general, see [[Gregory2010]](index.html#gregory2010). A sampling calculation uses the same model and data as the fitting calculation in the preceding section, but we replace the function [`fit()`](index.html#holopy.inference.interface.fit) with [`sample()`](index.html#holopy.inference.interface.sample) instead. Note that this calculation without further modifications might take an unreasonably long time! There are some tips on how to speed up the calculation further down on this page. The [`sample()`](index.html#holopy.inference.interface.sample) calculation returns a [`SamplingResult`](index.html#holopy.inference.result.SamplingResult) object, which is similar to the [`FitResult`](index.html#holopy.inference.result.FitResult) returned by [`fit()`](index.html#holopy.inference.interface.fit), but with some additional features. We can access the sampled parameter values and calculated log-probabilities with `SamplingResult.samples` and `SamplingResult.lnprobs`, respectively. Usually, the MCMC samples will take some steps to converge or “burn-in” to a stationary distribution from your initial guess. This is most easily seen in the values of `SamplingResult.lnprobs`, which will rise at first and then fluctuate around a stationary value after having burned in. You can remove the early samples with the built-in method [`SamplingResult.burn_in()`](index.html#holopy.inference.result.SamplingResult.burn_in), which returns a new [`SamplingResult`](index.html#holopy.inference.result.SamplingResult) with only the burned-in samples. #### Customizing the algorithm[¶](#customizing-the-algorithm) The [`fit()`](index.html#holopy.inference.interface.fit) and [`sample()`](index.html#holopy.inference.interface.sample) functions follow algorithms that determine which sets of parameter values to simulate and compare to the experimental data. You can specify a different algorithm by passing a *strategy* keyword into either function. Options for [`fit()`](index.html#holopy.inference.interface.fit) currently include the default Levenberg-Marquardt (`strategy="nmpfit"`), as well as cma-es (`strategy="cma"`) and scipy least squares (`strategy="scipy lsq"`). Options for [`sample()`](index.html#holopy.inference.interface.sample) include the default without tempering (`strategy="emcee"`), tempering by changing the number of pixels evaluated (`strategy="subset tempering"`), or parallel tempered MCMC (`strategy="parallel tempering"`) [not currently implemented]. You can see the available strategies in your version of HoloPy by calling `hp.inference.available_fit_strategies` or `hp.inference.available_sampling_strategies`. Each of these algorithms runs with a set of default values, but these may need to be adjusted for your particular situation. For example, you may want to set a random seed, control parallel computations, customize an initial guess, or specify hyperparameters of the algorithm. To use non-default settings, you must define a *Strategy* object for the algorithm you would like to use. You can save the strategy to a file for use in future calculations or modify it during an interactive session. ``` cma_fit_strategy = CmaStrategy(popsize=15, parallel=None) cma_fit_strategy.seed = 1234 hp.save('cma_strategy_file.h5', cma_fit_strategy) strategy_result = fit(data_holo, model, cma_fit_strategy) ``` In the example above, we have adjusted the `popsize` hyperparameter of the cma-es algorithm, prevented the calculation from running as a parallel computation, and set a random seed for reproducibility. The calculation returns a [`FitResult`](index.html#holopy.inference.result.FitResult) object, just like a direct call to [`fit()`](index.html#holopy.inference.interface.fit). Similarly, we can customize a MCMC computation to sample a posterior by calling [`sample()`](index.html#holopy.inference.interface.sample) with a [`EmceeStrategy`](index.html#holopy.inference.emcee.EmceeStrategy) object. Here we perform a MCMC calculation that uses only 500 pixels from the image and runs 50 walkers each for 2000 samples. We set the initial walker distribution to be one tenth of the prior width. In general, the burn-in time for a MCMC calculation will be reduced if you provide an initial guess position and width that is as close as possible to the eventual posterior distribution. You can use [`Model.generate_guess()`](index.html#holopy.inference.model.Model.generate_guess) to generate an initial sampling to pass in as an initial guess to your [`EmceeStrategy`](index.html#holopy.inference.emcee.EmceeStrategy) object. ``` nwalkers = 50 initial_guess = model.generate_guess(nwalkers, scaling=0.1) emcee_strategy = EmceeStrategy(npixels=500, nwalkers=nwalkers, nsamples=2000, walker_initial_pos=initial_guess) hp.save('emcee_strategy_file.h5', emcee_strategy) emcee_result = hp.sample(data_holo, model, emcee_strategy) ``` ##### Random Subset Fitting[¶](#random-subset-fitting) In the most recent example, we evaluated the holograms at the locations of only 500 pixels in the experimental image. This is because a hologram usually contains far more information than is needed to estimate your parameters of interest. You can often get a significantly faster fit with little or no loss in accuracy by fitting to only a random fraction of the pixels in a hologram. You will want to do some testing to make sure that you still get acceptable answers with your data, but our investigations have shown that you can frequently use random fractions of 0.1 or 0.01 with little effect on your results and gain a speedup of 10x or greater. ### Developer’s Guide[¶](#developer-s-guide) #### Installing HoloPy for Developers[¶](#installing-holopy-for-developers) If you are going to hack on holopy, you probably only want to compile the scattering extensions. **For Mac and Linux:** Download or clone the latest version of HoloPy from Git Hub at <https://github.com/manoharan-lab/holopy>. Let’s say you downloaded or cloned HoloPy to `/home/me/holopy`. Then open a terminal, `cd` to `/home/me/holopy` and run: ``` python setup.py develop ``` This puts the extensions inside the source tree, so that you can work directly from `/home/me/holopy` and have the changes reflected in the version of HoloPy that you import into python. **Note for Mac users:** gfortran may put its library in a place python can’t find it. If you get errors including something like `can't find /usr/local/libgfortran.3.dynlib` you can symlink them in from your install. You can do this by running: ``` sudo ln -s /usr/local/gfortran/lib/libgfortran.3.dynlib /usr/local/lib sudo ln -s /usr/local/gfortran/lib/libquadmath.3.dynlib /usr/local/lib ``` **For Windows:** Installation on Windows is still a work in progress, but we have been able to get HoloPy working on Windows 10 with an AMD64 architecture (64-bit) processor. 1. Install [Anaconda](https://www.continuum.io/downloads) with Python 3.6 and make sure it is working. 2. Install the C compiler. It’s included in [Visual Studio 2015 Community](https://www.visualstudio.com/downloads/). Make sure it is working with a C helloworld. 3. From now on, make sure any command prompt window invokes the right environment conditions for compiling with VC. To do this, make sure `C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat` is added to the system path variable. This batch detects your architecture, then runs another batch that sets the path include the directory with the correct version of the VC compiler. 4. Install cython and made sure it works. 5. Install [Intel’s Fortran compiler](https://software.intel.com/en-us/fortran-compilers/try-buy). A good place to start is the trial version of Parallel Studio XE. Make sure it is working with a Fortran helloworld. 6. Install [mingw32-make](https://sourceforge.net/projects/mingw/files/MinGW/Extension/make/), which does not come with Anaconda by default. 7. Download or clone the master branch of HoloPy from <https://github.com/manoharan-lab/holopy>. 8. Open the command prompt included in Intel’s Parallel Studio. Run `holopy/setup.py`. It is necessay to use Intel’s Parallel Studio command prompt to avoid compiling errors. 9. Install the following dependencies that don’t come with Anaconda: ``` conda install xarray dask netCDF4 bottleneck conda install -c astropy emcee=2.2.1 ``` 10. Open an iPython console where holopy is installed and try `import holopy`. If the above procedure doesn’t work, or you find something else that does, please [let us know](https://github.com/manoharan-lab/holopy/issues) so that we can improve these instructions. #### How HoloPy Stores Data[¶](#how-holopy-stores-data) Images in HoloPy are stored in the format of xarray [DataArrays](http://xarray.pydata.org/en/stable/data-structures.html#dataarray). Spatial information is tracked in the DataArray’s `dims` and `coords` fields according to the HoloPy [Coordinate System](index.html#coordinate-system). Additional dimensions are sometimes specified to account for different z-slices, times, or field components, for example. Optical parameters like refractive index and illumination wavelength are stored in the DataArray’s `attrs` field. The [`detector_grid()`](index.html#holopy.core.metadata.detector_grid) function simply creates a 2D image composed entirely of zeros. In contrast, the [`detector_points()`](index.html#holopy.core.metadata.detector_points) function creates a DataArray with a single dimension named ‘point’. Spatial coordinates (in either Cartesian or spherical form) track this dimension, so that each data value in the array has its own set of coordinates unrelated to its neighbours. This type of one-dimensional organization is sometimes used for 2D images as well. Inference and fitting methods typically use only a subset of points in an image (see random_subset), and so it makes sense for them to keep track of lists of location coordinates instead of a grid. Furthermore, HoloPy’s scattering functions accept coordinates in the form of a 3xN array of coordinates. In both of these cases, the 2D image is flattened into a 1D DataArray like that created by [`detector_points()`](index.html#holopy.core.metadata.detector_points). In this case the single dimension is ‘flat’ instead of ‘point’. HoloPy treats arrays with these two named dimensions identically, except that the ‘flat’ dimension can be unstacked to restore a 2D image or 3D volume. HoloPy’s use of DataArrays sometimes assigns smaller DataArrays in `attrs`, which can lead to problems when saving data to a file. When saving a DataArray to file, HoloPy converts any DataArrays in `attrs` to numpy arrays, and keeps track of their dimension names separately. HoloPy’s [`save_image()`](index.html#holopy.core.io.io.save_image) writes a yaml dump of `attrs` (along with spacing information) to the `imagedescription` field of .tif file metadata. infer_tutorial returns a lot of information, which is stored in the form of a [`SamplingResult`](index.html#holopy.inference.result.SamplingResult) object. This object stores the model and [`EmceeStrategy`](index.html#holopy.inference.emcee.EmceeStrategy) that were used in the inference calculation as attributes. An additional attribute named `dataset` is an [xarray Dataset](http://xarray.pydata.org/en/stable/data-structures.html#dataset) that contains both the data used in the inference calculation, as well as the raw output. The parameter values at each step of the sampling chain and the calculated log-probabilities at each step are stored here under the `samples` and `lnprobs` namespaces. #### Adding a new scattering theory[¶](#adding-a-new-scattering-theory) Adding a new scattering theory is relatively straightforward. You just need to define a new scattering theory class and implement one or two methods to compute the raw scattering values: ``` class YourTheory(ScatteringTheory): def can_handle(self, scatterer): # Your code here def raw_fields(self, positions, scatterer, medium_wavevec, medium_index, illum_polarization): # Your code here def raw_scat_matrs(self, scatterer, pos, medium_wavevec, medium_index): # Your code here def raw_cross_sections(self, scatterer, medium_wavevec, medium_index, illum_polarization): # Your code here ``` You can get away with just defining one of either `raw_scat_matrs` or `raw_fields` if you just want holograms, fields, or intensities. If you want scattering matrices you will need to implement `raw_scat_matrs`, and if you want cross sections, you will need to implement `raw_cross_sections`. We separate out `raw_fields` from `raw_scat_matrs` to allow for faster fields calculation for specific cases, such as the Mie, MieLens, and Multisphere theories (and you might want to do so for your theory as well); the base [`ScatteringTheory`](index.html#holopy.scattering.theory.scatteringtheory.ScatteringTheory) class calculates the fields from the scattering matrices by default. You can look at the Mie theory in HoloPy for an example of calling Fortran functions to compute scattering (C functions will look similar from the python side) or DDA for an an example of calling out to an external command line tool by generating files and reading output files. If you want to fit parameters in your scattering theory, you also need to define a class attribute parameter_names that contains the fittable attributes of the scattering theory. Once you do this, fitting should work natively with your new scattering theory: you should be able to specify the parameters as a `prior.Prior` object and holopy’s inference `Model` will auto-detect them as fittable parameters. For an example of this, see the [`Lens`](index.html#holopy.scattering.theory.lens.Lens), [`MieLens`](index.html#holopy.scattering.theory.mielens.MieLens), or [`AberratedMieLens`](index.html#holopy.scattering.theory.mielens.AberratedMieLens) classes. #### Adding a new inference model[¶](#adding-a-new-inference-model) To perform inference, you need a noise model. You can make a new noise model by inheriting from `NoiseModel`. This class has all the machinery to compute likelihoods of observing data given some set of parameters and assuming Gaussian noise. To implement a new model, you just need to implement one function: `forward`. This function receives a dictionary of parameter values and a data shape schema (defined by [`detector_grid()`](index.html#holopy.core.metadata.detector_grid), for example) and needs to return simulated data of shape specified. See the `_forward` function in `AlphaModel` for an example of how to do this. If you want to use some other noise model, you may need to override _lnlike and define the probablity given your uncertainty. You can reference _lnlike in `NoiseModel`. #### Running Tests[¶](#running-tests) HoloPy comes with a suite of tests that ensure everything has been built correctly and that it’s able to perform all of the calculations it is designed to do. To run these tests, navigate to the root of the package (e.g. `/home/me/holopy`) and run: ``` python run_nose.py ``` User Guide[¶](#user-guide) --- Skip to the [Loading Data](index.html#load-tutorial) tutorial if you already have HoloPy installed and want to get started quickly. ### The HoloPy Scatterer[¶](#the-holopy-scatterer) The HoloPy [`Scatterer`](index.html#holopy.scattering.scatterer.scatterer.Scatterer) class defines objects that are described by numerical quantities (e.g. dimension, location, refractive index) and have known light-scattering behaviour described by a [`ScatteringTheory`](index.html#holopy.scattering.theory.scatteringtheory.ScatteringTheory). Scatterers are generally used in two scenarios: * All numerical properties (e.g. dimension, location, refractive index) are fixed to simulate a specific light scattering experiment. * Some numerical properties are defined as [`Prior`](index.html#holopy.core.prior.Prior) objects, representing unknown values to be determined in an inference calculation. You can find examples of these use cases in the [Scattering Calculations](index.html#calc-tutorial) and [Fitting Models to Data](index.html#fit-tutorial) tutorials. Scatterer objects in HoloPy are inherited from two base classes: * [CenteredScatterer](#individual-scatterer) describes a single object, with an optional location specified * [Scatterers](#composite-scatterer) describes a collection of individual scatterers #### Scatterer Attributes[¶](#scatterer-attributes) All HoloPy Scatterer classes have the following properties/methods: General manipulation * [`x`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.x), [`y`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.y), [`z`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.z) Components of scatterer center * [`translated()`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.translated) New scatterer with location coordinates shifted by a vector Inference calculations * [`parameters`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.parameters) Dictionary of all values needed to describe the scatterer. Values described as [`Prior`](index.html#holopy.core.prior.Prior) objects will appear that way here as well. * [`from_parameters()`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.from_parameters) New scatterer built from a dictionary of parameters Discretization * [`indicators`](index.html#holopy.scattering.scatterer.scatterer.Indicators) Function(s) to describe region(s) of space occupied by scatterer domain(s) * [`index_at()`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.index_at) Scatterer’s refractive index at given coordinates * [`in_domain()`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.in_domain) Which domain of the scatterer the given coordinates are in * [`contains()`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.contains) Check whether a particular point is in any domains of the scatterer * [`num_domains`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.num_domains) Number of domains of the scatterer * [`bounds`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.bounds) Extents of the scatterer in each dimension * [`voxelate()`](index.html#holopy.scattering.scatterer.scatterer.Scatterer.voxelate) 3D voxel grid representation of the scatterer containing its refractive index at each point #### Individual Scatterers[¶](#individual-scatterers) [`CenteredScatterer`](index.html#holopy.scattering.scatterer.scatterer.CenteredScatterer) objects are not instantiated directly, but instead in one of the subclasses: * [`Sphere`](index.html#holopy.scattering.scatterer.sphere.Sphere) Can contain multiple concentric layers defined by their outer radius * [`LayeredSphere`](index.html#holopy.scattering.scatterer.sphere.LayeredSphere) Defines multiple concentric layers by their layer thickness * [`Cylinder`](index.html#holopy.scattering.scatterer.cylinder.Cylinder) * [`Ellipsoid`](index.html#holopy.scattering.scatterer.ellipsoid.Ellipsoid) * [`Spheroid`](index.html#holopy.scattering.scatterer.spheroid.Spheroid) * [`Bisphere`](index.html#holopy.scattering.scatterer.bisphere.Bisphere) Union of two spheres * [`Capsule`](index.html#holopy.scattering.scatterer.capsule.Capsule) Cylinder with semi-spherical caps on either end * [`JanusSphere_Uniform`](index.html#holopy.scattering.scatterer.janus.JanusSphere_Uniform) Sphere with a semi-spherical outer layer of constant thickness * [`JanusSphere_Tapered`](index.html#holopy.scattering.scatterer.janus.JanusSphere_Tapered) Sphere with a semi-spherical outer layer that has a crescent profile * [`CsgScatterer`](index.html#holopy.scattering.scatterer.csg.CsgScatterer) Allows for construction of an arbitrary scatterer by constructive solid geometry #### Composite Scatterers[¶](#composite-scatterers) [`Scatterers`](index.html#holopy.scattering.scatterer.composite.Scatterers) objects contain multiple individual scatterers,and support the following features in addition to those shared with [`CenteredScatterer`](index.html#holopy.scattering.scatterer.scatterer.CenteredScatterer): Component scatterer handling * Support for selecting component scatterers with square brackets and python slicing syntax * [`add()`](index.html#holopy.scattering.scatterer.composite.Scatterers.add) Adds a new scatterer to the composite in-place * [`rotated()`](index.html#holopy.scattering.scatterer.composite.Scatterers.rotated) New scatterer rotated about its center according to [HoloPy rotation conventions](index.html#rotations) There are two specific composite scatterer classes for working with collections of spheres that have additional functionality: [`Spheres`](index.html#holopy.scattering.scatterer.spherecluster.Spheres) A collection of spherical scatterers, with the following properties: * [`overlaps`](index.html#holopy.scattering.scatterer.spherecluster.Spheres.overlaps) List of pairs of component spheres that overlap * `largest_overlap` Maximum overlap distance between component spheres [`RigidCluster`](index.html#holopy.scattering.scatterer.spherecluster.RigidCluster) A collection of spherical scatterers in fixed relative positions. The entire cluster can be translated and/or rotated. [`RigidCluster.scatterers`](index.html#holopy.scattering.scatterer.spherecluster.RigidCluster.scatterers) and [`RigidCluster.from_parameters()`](index.html#holopy.scattering.scatterer.spherecluster.RigidCluster.from_parameters) both return [`Spheres`](index.html#holopy.scattering.scatterer.spherecluster.Spheres) type objects. ### The HoloPy Scattering Theories[¶](#the-holopy-scattering-theories) The HoloPy [`ScatteringTheory`](index.html#holopy.scattering.theory.scatteringtheory.ScatteringTheory) classes know how to calculate scattered fields from detector and scatterer information. Each scattering theory is only able to work with certain specific scatterers. There are two broad classes of scattering theories in HoloPy: [lens-free](#lens-free) theories which treat the recorded fields as the magnified image of the fields at the focal plane, and [lens-based](#with-lens) theories which use a more detailed description of the effects of the objective lens. The lens-free theories usually do not need any additional parameters specified, whereas the lens theories need the lens’s acceptance angle, which can be specified as either a fixed number or a [`Prior`](index.html#holopy.core.prior.Prior) object, representing an unknown value to be determined in an inference calculation. All scattering theories in HoloPy inherit from the [`ScatteringTheory`](index.html#holopy.scattering.theory.scatteringtheory.ScatteringTheory) class. Not sure how to choose a scattering theory? See the [Which Scattering Theory should I use?](#how-to-choose-theory) section. #### ScatteringTheory Methods[¶](#scatteringtheory-methods) HoloPy Scattering theories calculate the scattered fields through one of the following methods. > * `_raw_fields()` > Calculates the scattering fields. > * `_raw_scat_matrs()` > Calculates the scattering matrices. > * `_raw_cross_sections()` > Calculates the cross sections. > * `_can_handle()` > Checks if the theory is compatible with a given scatterer. If a theory is asked for the raw fields, but does not have a `_raw_fields` method, the scattering theory attempts to calculate them via the scattering matrices, as called by `_raw_scat_matrs`. More than one of these methods may be implemented for performance reasons. Be advised that the [`ScatteringTheory`](index.html#holopy.scattering.theory.scatteringtheory.ScatteringTheory) class is under active development, and these method names may change. #### Lens-Free Scattering Theories[¶](#lens-free-scattering-theories) * [`DDA`](index.html#holopy.scattering.theory.dda.DDA) + Can handle every [`Scatterer`](index.html#holopy.scattering.scatterer.scatterer.Scatterer) object in HoloPy + Computes scattered fields using the discrete dipole approximation, as implemented by ADDA. + Requires the ADDA package to be installed separately, as detailed in the [DDA section](index.html#dda-tutorial) + Functions in two different ways, as controlled by the `use_indicators` flag. If the `use_indicators` flag is `True`, the scatterer is voxelated within HoloPy before passing to ADDA. If the flag is `False`, ADDA’s built-in scatterer geometries are used for things like spheres, cylinders, ellipsoids, etc. * [`Mie`](index.html#holopy.scattering.theory.mie.Mie) + Can handle [`Sphere`](index.html#holopy.scattering.scatterer.sphere.Sphere) objects, [`LayeredSphere`](index.html#holopy.scattering.scatterer.sphere.LayeredSphere) objects, or [`Spheres`](index.html#holopy.scattering.scatterer.spherecluster.Spheres) through superposition. + Computes scattered fields using Mie theory. * [`Multisphere`](index.html#holopy.scattering.theory.multisphere.Multisphere) + Can handle [`Spheres`](index.html#holopy.scattering.scatterer.spherecluster.Spheres) objects. + Cannot handle [`Spheres`](index.html#holopy.scattering.scatterer.spherecluster.Spheres) objects composed of layered spheres. + Computes scattered fields through a T-matrix-based solution of scattering, accounting for multiple scattering between spheres to find a (numerically) exact solution. * [`Tmatrix`](index.html#holopy.scattering.theory.tmatrix.Tmatrix) + Can handle [`Sphere`](index.html#holopy.scattering.scatterer.sphere.Sphere), [`Cylinder`](index.html#holopy.scattering.scatterer.cylinder.Cylinder), or [`Spheroid`](index.html#holopy.scattering.scatterer.spheroid.Spheroid) objects. + Computes scattered fields by calculating the T-matrix for axisymmetric scatterers, to find a (numerically) exact solution. + Occasionally has problems due to Fortran compilations. #### Lens-Based Scattering Theories[¶](#lens-based-scattering-theories) * [`Lens`](index.html#holopy.scattering.theory.lens.Lens) + Create by including one of the [Lens-Free](#lens-free) theories. + Can handle whatever the additional included theory can handle. + Considerably slower than the normal scattering theory. + Performance can be improved if the [numexpr](https://pypi.org/project/numexpr/) package is installed. * [`MieLens`](index.html#holopy.scattering.theory.mielens.MieLens) + Can handle [`Sphere`](index.html#holopy.scattering.scatterer.sphere.Sphere) objects, or [`Spheres`](index.html#holopy.scattering.scatterer.spherecluster.Spheres) through superposition. + Computes scattered fields using Mie theory, but incorporates diffractive effects of a perfect objective lens. + Used for performance; `MieLens(lens_angle)` is much faster than calling `Lens(lens_angle, Mie())` and slightly faster than `Mie()`. * [`AberratedMieLens`](index.html#holopy.scattering.theory.mielens.AberratedMieLens) + Can handle [`Sphere`](index.html#holopy.scattering.scatterer.sphere.Sphere) objects, or [`Spheres`](index.html#holopy.scattering.scatterer.spherecluster.Spheres) through superposition. + Computes scattered fields using Mie theory, but incorporates both diffractive effects of an objective lens and arbitrary-order spherical aberration. + [`AberratedMieLens`](index.html#holopy.scattering.theory.mielens.AberratedMieLens) and [`MieLens`](index.html#holopy.scattering.theory.mielens.MieLens) have the same computational cost, although [`AberratedMieLens`](index.html#holopy.scattering.theory.mielens.AberratedMieLens) requires more parameters for fitting. #### Which Scattering Theory should I use?[¶](#which-scattering-theory-should-i-use) HoloPy chooses a default scattering theory based off the scatterer type, currently determined by the function [`determine_default_theory_for()`](index.html#holopy.scattering.interface.determine_default_theory_for). If you’re not satisfied with HoloPy’s default scattering theory selection, you should choose the scattering theory based off of (1) the scatterer that you are modeling, and (2) whether you want to describe the effect of the lens on the recorded hologram in detail. ##### An Individual Sphere[¶](#an-individual-sphere) For single spheres, the default is to calculate scattering using Mie theory, implemented in the class [`Mie`](index.html#holopy.scattering.theory.mie.Mie). Mie theory is the exact solution to Maxwell’s equations for the scattered field from a spherical particle, originally derived by <NAME> and (independently) by <NAME> in the early 1900s. ##### Multiple Spheres[¶](#multiple-spheres) A scatterer composed of multiple spheres can exhibit multiple scattering and coupling of the near-fields of neighbouring particles. Mie theory doesn’t include these effects, so [`Spheres`](index.html#holopy.scattering.scatterer.spherecluster.Spheres) objects are by default calculated using the [`Multisphere`](index.html#holopy.scattering.theory.multisphere.Multisphere) theory, which accounts for multiple scattering by using the SCSMFO package from [<NAME>](http://www.eng.auburn.edu/~dmckwski/). This calculation uses T-matrix methods to give the exact solution to Maxwell’s equation for the scattering from an arbitrary arrangement of non-overlapping spheres. Sometimes you might want to calculate scattering from multiple spheres using Mie theory if you are worried about computation time or if your spheres are widely separated (such that optical coupling between the spheres is negligible) You can specify Mie theory manually when calling the [`calc_holo()`](index.html#holopy.scattering.interface.calc_holo) function, as the following code snippet shows: ``` import holopy as hp from holopy.core.io import get_example_data_path from holopy.scattering import ( Sphere, Spheres, Mie, calc_holo) s1 = Sphere(center=(5, 5, 5), n = 1.59, r = .5) s2 = Sphere(center=(4, 4, 5), n = 1.59, r = .5) collection = Spheres([s1, s2]) imagepath = get_example_data_path('image0002.h5') exp_img = hp.load(imagepath) holo = calc_holo(exp_img, collection, theory=Mie) ``` Note that the multisphere theory does not work with collections of multi-layered spheres; in this case HoloPy defaults to using Mie theory with superposition. ##### Non-spherical particles[¶](#non-spherical-particles) HoloPy also includes scattering theories that can calculate scattering from non-spherical particles. For cylindrical or spheroidal particles, by default HoloPy calculates scattering from cylindrical or spheroidal particles by using the [`Tmatrix`](index.html#holopy.scattering.theory.tmatrix.Tmatrix) theory, which uses the T-matrix code from [<NAME>ishchenko](https://www.giss.nasa.gov/staff/mmishchenko/t_matrix.html). ``` from holopy.scattering.theory import Tmatrix from holopy.scattering.scatterer import Spheroid spheroid = Spheroid(n=1.59, r=(1., 2.), center=(4, 4, 5)) theory = Tmatrix() holo = calc_holo(exp_img, spheroid, theory=theory) ``` Holopy can also access a discrete dipole approximation (DDA) theory to model arbitrary non-spherical objects. See the [Scattering from Arbitrary Structures with DDA](index.html#dda-tutorial) tutorial for more details. ##### Including the effect of the lens[¶](#including-the-effect-of-the-lens) Most of the scattering theories in HoloPy treat the fields on the detector as a (magnified) image of the fields at the focal plane. While these theories usually provide a good description of holograms of particles far above the focus, when the particle is near near the focus subtle optical effects can cause deviations between the recorded hologram and theories which do not specifically describe the effects of the lens. To deal with this, HoloPy currently offers two scattering theories which describe the effects of a perfect lens on the recorded hologram. Both of these scattering theories need information about the lens to make predictions, specifically the acceptance angle of the lens. The acceptance angle \(\beta\) is related to the numerical aperture or NA of the lens by \(\beta = \arcsin(NA / n_f)\), where \(n_f\) is the refractive of the immersion fluid. For more details on the effect of the lens on the recorded hologram, see our papers [here](https://www.osapublishing.org/oe/abstract.cfm?uri=oe-28-2-1061) and [here](url). The [`Lens`](index.html#holopy.scattering.theory.lens.Lens) theory allows HoloPy to include the effects of a perfect objective lens with any scattering theory. The Lens theory works by wrapping a normal scattering theory. For instance, to calculate the image of a sphere in an objective lens with an acceptance angle of 1.0, do ``` from holopy.scattering.theory import Lens, Mie lens_angle = 1.0 theory = Lens(lens_angle, Mie()) ``` This theory can then be passed to [`calc_holo()`](index.html#holopy.scattering.interface.calc_holo) just like any other scattering theory. However, calculations with the [`Lens`](index.html#holopy.scattering.theory.lens.Lens) theory are very slow, orders of magnitude slower than calculations without the lens. To get around the slow speed of the [`Lens`](index.html#holopy.scattering.theory.lens.Lens) theory, HoloPy offers an additional theory, [`MieLens`](index.html#holopy.scattering.theory.mielens.MieLens), specifically for spherical particles imaged with a perfect lens. For spherical particles, some analytical simplifications are possible which greatly speed up the description of the objective lens – in fact, the [`MieLens`](index.html#holopy.scattering.theory.mielens.MieLens) theory’s implementation is slightly faster than [`Mie`](index.html#holopy.scattering.theory.mie.Mie) theory’s. The following code creates a [`MieLens`](index.html#holopy.scattering.theory.mielens.MieLens) theory, which can be passed to [`calc_holo()`](index.html#holopy.scattering.interface.calc_holo) just like any other scattering theory: ``` from holopy.scattering.theory import MieLens lens_angle = 1.0 theory = MieLens(lens_angle) ``` In addition, holopy supports the calculation of holograms of spherical particles when the imaging objective lens has spherical aberrations of arbitrary order. Currently only spherical aberrations are supported, and only for the image of spherical scatterers. The following code creates a [`AberratedMieLens`](index.html#holopy.scattering.theory.mielens.AberratedMieLens) theory with aberrations up to 8th order in the phase. This theory can be passed to [`calc_holo()`](index.html#holopy.scattering.interface.calc_holo) just like any other scattering theory: ``` from holopy.scattering.theory import AberratedMieLens aberration_coefficients = [1.0, 2.0, 3.0] lens_angle = 1.0 theory = AberratedMieLens( spherical_aberration=aberration_coefficients, lens_angle=lens_angle) ``` ##### My Scattering theory isn’t here?!?![¶](#my-scattering-theory-isn-t-here) Add your own scattering theory to HoloPy! See [Adding a new scattering theory](index.html#scat-theory) for details. If you think your new scattering theory may be useful for other users, please consider submitting a [pull request](https://github.com/manoharan-lab/holopy/pulls). ### HoloPy Tools[¶](#holopy-tools) Holopy contains a number of tools to help you with common tasks when analyzing holograms. This page provides a summary of the tools available, while full descriptions can be found in the relevant code reference. #### General Image Processing Tools[¶](#general-image-processing-tools) The tools described here are frequently used when analyzing holgrams. They are available from the `holopy.core.process` namespace. The [`normalize()`](index.html#holopy.core.process.img_proc.normalize) function divides an image by its average, returning an image with a mean pixel value of 1. Note that this is the same normalization convention used by HoloPy when calculating holograms with [`calc_holo()`](index.html#holopy.scattering.interface.calc_holo). Cropping an image introduces difficulties in keeping track of the relative coordinates of features within an image and maintaining metadata. By using the [`subimage()`](index.html#holopy.core.process.img_proc.subimage) function, the image origin is maintained in the cropped image, so coordinate locations of features (such as a scatterer) remain unchanged. Since holograms of particles usually take the form of concentric rings, the location of a scatterer can usually be found by locating the apparent center(s) of the image. Use [`center_find()`](index.html#holopy.core.process.centerfinder.center_find) to locate one or more centers in an image. You can remove isolated dead pixels with zero intensity (e.g. for a background division) by using [`zero_filter()`](index.html#holopy.core.process.img_proc.zero_filter). This function replaces the dead pixel with the average of its neighbours, and fails if adjacent pixels have zero intensity. The [`add_noise()`](index.html#holopy.core.process.img_proc.add_noise) function allows you to add Gaussian-correlated random noise to a calculated image so that it more closely resembles experimental data. To find gradient values at all points in an image, use [`image_gradient()`](index.html#holopy.core.process.centerfinder.image_gradient). To simply remove a planar intensity gradient from an image, use [`detrend()`](index.html#holopy.core.process.img_proc.detrend). Note that this gives a mean pixel value of zero. Frequency space analysis provides a powerful tool for working with images. Use [`fft()`](index.html#holopy.core.process.fourier.fft) and [`ifft()`](index.html#holopy.core.process.fourier.ifft) to perform fourier transforms and inverse fourier transforms, respectively. These make use of `numpy.fft` functions, but are wrapped to correctly interpret HoloPy objects. HoloPy also includes a Hough transform ([`hough()`](index.html#holopy.core.process.centerfinder.hough)) to help identify lines and other features in your images. #### Math Tools[¶](#math-tools) HoloPy contains implementations of a few mathematical functions related to scattering calculations. These functions are available from the `holopy.core.math` namespace. To find the distance between two points, use [`cartesian_distance()`](index.html#holopy.core.math.cartesian_distance). To rotate a set of points by arbitrary angles about the three coordinate axes, use [`rotate_points()`](index.html#holopy.core.math.rotate_points). You can also calculate a rotation matrix with [`rotation_matrix()`](index.html#holopy.core.math.rotation_matrix) to save and use later. To convert spherical coordinates into Cartesian coordinates, use [`to_cartesian()`](index.html#holopy.core.math.to_cartesian). To convert Cartesian coordinates into spherical coordinates, use `to_spherical()`. When comparing data to a model, the chi-squared and r-squared values provide measures of goodness-of-fit. You can access these through [`chisq()`](index.html#holopy.core.math.chisq) and [`rsq()`](index.html#holopy.core.math.rsq). ### HoloPy Concepts[¶](#holopy-concepts) #### Units[¶](#units) HoloPy does **not** enforce any particular set of units. As long as you are consistent, you can use any set of units, for example pixels, meters, or microns. So if you specify the wavelength of your red imaging laser as 658 then all other units (*x*, *y*, *z* position coordinates, particle radii, etc.) must also be specified in nanometers. #### Coordinate System[¶](#coordinate-system) For image data (data points arrayed in a regular grid in a single plane), HoloPy defaults to placing the origin, (0,0), at the top left corner as shown below. The x-axis runs vertically down, the y-axis runs horizontally to the right, and the z-axis points out of the screen, toward you. This corresponds to the way that images are treated by most computer software. In sample space, we choose the z axis so that distances to objects from the camera/focal plane are positive (have positive z coordinates). The price we pay for this choice is that the propagation direction of the illumination light is then negative. In the image above, light travels from a source located in front of the screen, through a scatterer, and onto a detector behind the screen. More complex detector geometries will define their own origin, or ask you to define one. #### Rotations of Scatterers[¶](#rotations-of-scatterers) Certain scattering calculations in HoloPy require specifying the orientation of a scatterer (such as a Janus sphere) relative to the HoloPy coordinate system. We do this in the most general way possible by specifying three Euler angles and a reference orientation. Rotating a scatterer initially in the reference orientation through the three Euler angles \(\alpha\), \(\beta\), and \(\gamma\) (in the active transformation picture) yields the desired orientation. The reference orientation is specified by the definition of the scatterer. The Euler rotations are performed in the following way: 1. Rotate the scatterer an angle \(\alpha\) about the HoloPy \(z\) axis. 2. Rotate the scatterer an angle \(\beta\) about the HoloPy \(y\) axis. 3. Rotate the scatterer an angle \(\gamma\) about the HoloPy \(z\) axis. The sense of rotation is as follows: each angle is a rotation in the *clockwise* direction about the specified axis, viewed along the positive direction of the axis from the origin. This is the usual sense of how rotations are typically defined in math: holopy package[¶](#module-holopy) --- HoloPy is a set of tools for working with digital holograms and light scattering. It contains tools for working loading data and associating it with expermiental metadata, reconstructing holograms, calculating light scattering, fitting scattering models to data, and visualizing images and calculations. ### Subpackages[¶](#subpackages) #### holopy.core package[¶](#module-holopy.core) Loading, saving, and basic processing of data. ##### Subpackages[¶](#subpackages) ###### holopy.core.io package[¶](#module-holopy.core.io) ####### Submodules[¶](#module-holopy.core.io.io) Common entry point for holopy io. Dispatches to the correct load/save functions. *class* `Accumulator`[¶](#holopy.core.io.io.Accumulator) Bases: [`object`](https://docs.python.org/3/library/functions.html#object) Calculates average and coefficient of variance for numerical data in one pass using Welford’s algorithim. `cv`()[¶](#holopy.core.io.io.Accumulator.cv) The coefficient of variation `mean`()[¶](#holopy.core.io.io.Accumulator.mean) `push`(*x*)[¶](#holopy.core.io.io.Accumulator.push) `default_extension`(*inf*, *defext='.h5'*)[¶](#holopy.core.io.io.default_extension) `get_example_data`(*name*)[¶](#holopy.core.io.io.get_example_data) `get_example_data_path`(*name*)[¶](#holopy.core.io.io.get_example_data_path) `load`(*inf*, *lazy=False*)[¶](#holopy.core.io.io.load) Load data or results | Parameters: | **inf** (*string*) – String specifying an hdf5 file containing holopy data | | Returns: | **obj** – The array object contained in the file | | Return type: | xarray.DataArray | `load_average`(*filepath*, *refimg=None*, *spacing=None*, *medium_index=None*, *illum_wavelen=None*, *illum_polarization=None*, *noise_sd=None*, *channel=None*, *image_glob='*.tif'*)[¶](#holopy.core.io.io.load_average) Average a set of images (usually as a background) | Parameters: | * **filepath** (*string* *or* [*list*](https://docs.python.org/3/library/stdtypes.html#list)*(**string**)*) – Directory or list of filenames or filepaths. If filename is a directory, it will average all images matching image_glob. * **refimg** (*xarray.DataArray*) – reference image to provide spacing and metadata for the new image. * **spacing** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Spacing between pixels in the images. Used preferentially over refimg value if both are provided. * **medium_index** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Refractive index of the medium in the images. Used preferentially over refimg value if both are provided. * **illum_wavelen** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Wavelength of illumination in the images. Used preferentially over refimg value if both are provided. * **illum_polarization** (*list-like*) – Polarization of illumination in the images. Used preferentially over refimg value if both are provided. * **image_glob** (*string*) – Glob used to select images (if images is a directory) | | Returns: | **averaged_image** – Image which is an average of images noise_sd attribute contains average pixel stdev normalized by total image intensity | | Return type: | xarray.DataArray | `load_image`(*inf*, *spacing=None*, *medium_index=None*, *illum_wavelen=None*, *illum_polarization=None*, *noise_sd=None*, *channel=None*, *name=None*)[¶](#holopy.core.io.io.load_image) Load data or results | Parameters: | * **inf** (*string*) – File to load. * **spacing** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* *(*[*float*](https://docs.python.org/3/library/functions.html#float)*,* [*float*](https://docs.python.org/3/library/functions.html#float)*)* *(**optional**)*) – pixel size of images in each dimension - assumes square pixels if single value. set equal to 1 if not passed in and issues warning. * **medium_index** ([*float*](https://docs.python.org/3/library/functions.html#float) *(**optional**)*) – refractive index of the medium * **illum_wavelen** ([*float*](https://docs.python.org/3/library/functions.html#float) *(**optional**)*) – wavelength (in vacuum) of illuminating light * **illum_polarization** (*(*[*float*](https://docs.python.org/3/library/functions.html#float)*,* [*float*](https://docs.python.org/3/library/functions.html#float)*)* *(**optional**)*) – (x, y) polarization vector of the illuminating light * **noise_sd** ([*float*](https://docs.python.org/3/library/functions.html#float) *(**optional**)*) – noise level in the image, normalized to image intensity * **channel** ([*int*](https://docs.python.org/3/library/functions.html#int) *or* *tuple of ints* *(**optional**)*) – number(s) of channel to load for a color image (in general 0=red, 1=green, 2=blue) name : str (optional) name to assign the xr.DataArray object resulting from load_image | | Returns: | **obj** | | Return type: | xarray.DataArray representation of the image with associated metadata | `pack_attrs`(*a*, *do_spacing=False*)[¶](#holopy.core.io.io.pack_attrs) `save`(*outf*, *obj*)[¶](#holopy.core.io.io.save) Save a holopy object Will save objects as yaml text containing all information about the object unless outf is a filename with an image extension, in which case it will save an image, truncating metadata. | Parameters: | * **outf** (*basestring* *or* *file*) – Location to save the object * **obj** ([`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject)) – The object to save | `save_image`(*filename*, *im*, *scaling='auto'*, *depth=8*)[¶](#holopy.core.io.io.save_image) Save an ndarray or image as a tiff. | Parameters: | * **filename** (*basestring*) – filename in which to save image. If im is an image the function should default to the image’s name field if no filename is specified * **im** (ndarray or `holopy.image.Image`) – image to save. * **scaling** (*'auto'**,* [*None*](https://docs.python.org/3/library/constants.html#None)*, or* *(**Int**,* *Int**)*) – How the image should be scaled for saving. Ignored for float output. It defaults to auto, use the full range of the output format. Other options are None, meaning no scaling, or a pair of integers specifying the values which should be set to the maximum and minimum values of the image format. * **depth** (*8**,* *16* *or* *'float'*) – What type of image to save. Options other than 8bit may not be supported for many image types. You probably don’t want to save 8bit images without some kind of scaling. | `save_images`(*filenames*, *ims*, *scaling='auto'*, *depth=8*)[¶](#holopy.core.io.io.save_images) Saves a volume as separate images (think of reconstruction volumes). | Parameters: | * **filenames** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)) – List of filenames. There have to be the same number of filenames as of images to save. Each image will be saved in the corresponding file with the same index. * **ims** (ndarray or `holopy.image.Image`) – Images to save, with separate z-coordinates from which they each will be selected. * **scaling** (*'auto'**,* [*None*](https://docs.python.org/3/library/constants.html#None)*, or* *(**Int**,* *Int**)*) – How the images should be scaled for saving. Ignored for float output. It defaults to auto, use the full range of the output format. Other options are None, meaning no scaling, or a pair of integers specifying the values which should be set to the maximum and minimum values of the image format. * **depth** (*8**,* *16* *or* *'float'*) – What type of image to save. Options other than 8bit may not be supported for many image types. You probably don’t want to save 8bit images without some kind of scaling. | `unpack_attrs`(*a*)[¶](#holopy.core.io.io.unpack_attrs) Reading and writing of yaml files. yaml files are structured text files designed to be easy for humans to read and write but also easy for computers to read. HoloPy uses them to store information about experimental conditions and to describe analysis procedures. `class_loader`(*loader*, *node*)[¶](#holopy.core.io.serialize.class_loader) `class_representer`(*dumper*, *data*)[¶](#holopy.core.io.serialize.class_representer) `complex_constructor`(*loader*, *node*)[¶](#holopy.core.io.serialize.complex_constructor) `complex_representer`(*dumper*, *data*)[¶](#holopy.core.io.serialize.complex_representer) `ignore_aliases`(*data*)[¶](#holopy.core.io.serialize.ignore_aliases) `instancemethod_constructor`(*loader*, *node*)[¶](#holopy.core.io.serialize.instancemethod_constructor) `instancemethod_representer`(*dumper*, *data*)[¶](#holopy.core.io.serialize.instancemethod_representer) `load`(*inf*)[¶](#holopy.core.io.serialize.load) `ndarray_representer`(*dumper*, *data*)[¶](#holopy.core.io.serialize.ndarray_representer) `numpy_float_representer`(*dumper*, *data*)[¶](#holopy.core.io.serialize.numpy_float_representer) `numpy_int_representer`(*dumper*, *data*)[¶](#holopy.core.io.serialize.numpy_int_representer) `numpy_ufunc_constructor`(*loader*, *node*)[¶](#holopy.core.io.serialize.numpy_ufunc_constructor) `numpy_ufunc_representer`(*dumper*, *data*)[¶](#holopy.core.io.serialize.numpy_ufunc_representer) `save`(*outf*, *obj*)[¶](#holopy.core.io.serialize.save) `tuple_representer`(*dumper*, *data*)[¶](#holopy.core.io.serialize.tuple_representer) Prepare HoloPy objects for display on screen or write to file. *class* `Show2D`(*im*)[¶](#holopy.core.io.vis.Show2D) Bases: [`object`](https://docs.python.org/3/library/functions.html#object) `click`(*event*)[¶](#holopy.core.io.vis.Show2D.click) `draw`()[¶](#holopy.core.io.vis.Show2D.draw) `format_coord`(*x*, *y*)[¶](#holopy.core.io.vis.Show2D.format_coord) `save`(*filename*)[¶](#holopy.core.io.vis.Show2D.save) Saves the currently displayed Plot into a file. | Parameters: | **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – Name for the file to save to. | `save_all`(*filenames*)[¶](#holopy.core.io.vis.Show2D.save_all) Saves the complete stack of images into separate files. | Parameters: | **filenames** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)) – Names of the files to save as a list. Has to have the same length as the number of images that are contained in this object. | *exception* `VisualizationNotImplemented`(*o*)[¶](#holopy.core.io.vis.VisualizationNotImplemented) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) `check_display`()[¶](#holopy.core.io.vis.check_display) Diagnostic test to check matplotlib backend. You should see a white square inside a black square, with a colorbar. Pressing the left or right arrow keys should cycle through z. You should see: > Z = 0 : A white axes-aligned square > Z = 1 : A white circle > Z = 2 : A white diamond (square at 45 degrees) `display_image`(*im*, *scaling='auto'*, *vert_axis='x'*, *horiz_axis='y'*, *depth_axis='z'*, *colour_axis='illumination'*)[¶](#holopy.core.io.vis.display_image) `save_plot`(*filenames*, *data*, *scaling='auto'*, *vert_axis='x'*, *horiz_axis='y'*, *depth_axis='z'*, *colour_axis='illumination'*)[¶](#holopy.core.io.vis.save_plot) Saves a hologram or reconstruction to (a) file(s). | Parameters: | * **filenames** (*list / str*) – Name(s) of the file(s). If there is only one image contained (e.g. hologram), the name will be used as a file name. If o contains more plottable images (e.g. reconstruction volume), it should be a list of filenames with the same length as objects. * **data** (*xarray.DataArray* *or* *ndarray*) – Object to save. * **scaling** (*(*[*float*](https://docs.python.org/3/library/functions.html#float)*,* [*float*](https://docs.python.org/3/library/functions.html#float)*)**,* *optional*) – (min, max) value to display in image, default is full range of o. * **vert_axis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)*,* *optional*) – axis to display vertically, default x. * **horiz_axis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)*,* *optional*) – axis to display horizontally, default y. * **depth_axis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)*,* *optional*) – axis to scroll with arrow keys, default ‘z’. * **colour_axis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)*,* *optional*) – axis to display as RGB channels in colour image, default illumination. | Notes Loads plotting library the first time it is required (so that we don’t have to import all of matplotlib or mayavi just to load holopy) `show`(*o*, *scaling='auto'*, *vert_axis='x'*, *horiz_axis='y'*, *depth_axis='z'*, *colour_axis='illumination'*)[¶](#holopy.core.io.vis.show) Visualize a hologram or reconstruction | Parameters: | * **o** (*xarray.DataArray* *or* *ndarray*) – Object to visualize * **scaling** (*(*[*float*](https://docs.python.org/3/library/functions.html#float)*,* [*float*](https://docs.python.org/3/library/functions.html#float)*)**,* *optional*) – (min, max) value to display in image, default is full range of o. * **vert_axis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)*,* *optional*) – axis to display vertically, default x. * **horiz_axis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)*,* *optional*) – axis to display horizontally, default y. * **depth_axis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)*,* *optional*) – axis to scroll with arrow keys, default ‘z’. * **colour_axis** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)*,* *optional*) – axis to display as RGB channels in colour image, default illumination. | Notes Loads plotting library the first time it is required (so that we don’t have to import all of matplotlib or mayavi just to load holopy) `show_scatterer_slices`(*scatterer*, *spacing*)[¶](#holopy.core.io.vis.show_scatterer_slices) Show slices of a scatterer voxelation scatterer : .Scatterer scatterer to visualize spacing : float or (float, float, float) voxel spacing for the visualization `show_sphere_cluster`(*s*, *color*)[¶](#holopy.core.io.vis.show_sphere_cluster) This function to show a 3D rendering of a Spheres obj hasn’t worked since HoloPy 3.0, due to Mayavi compatibility issues. We keep the code because we hope to re-implement this functionality eventually. ###### holopy.core.process package[¶](#module-holopy.core.process) Routines for image processing. Useful for pre-processing raw holograms prior to extracting final data or post-processing reconstructions. ####### Submodules[¶](#module-holopy.core.process.centerfinder) The centerfinder module is a group of functions for locating the centers of holographic ring patterns. The module can find the center of a single-sphere holographic pattern, a dimer holographic pattern, or the centers of multiple (well-separated: clearly separate ring patterns with separate centers) single spheres or dimers. The intended use is for determining an initial parameter guess for hologram fitting. We thank the Grier Group at NYU for suggesting the use of the Hough transform. For their independent implementation of a Hough-based holographic feature detection algorithm, see: <http://physics.nyu.edu/grierlab/software/circletransform.pro> For a case study and further reading, see: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> & <NAME>, Flow visualization and flow cytometry with holographic video microscopy, Optics Express 17, 13071-13079 (2009). `center_find`(*image*, *centers=1*, *threshold=0.5*, *blursize=3.0*)[¶](#holopy.core.process.centerfinder.center_find) Finds the coordinates of the center of a holographic pattern. The coordinates returned are in pixels (row number, column number). Intended for finding the center of single particle or dimer holograms which basically show concentric circles. The optional threshold parameter (between 0 and 1) gives a bound on what magnitude of gradients to include in the calculation. For example, threshold=.75 means ignore any gradients that are less than 75% of the maximum gradient in the image. The optional blursize parameter sets the size of a Gaussian filter that is applied to the image. This step improves accuracy when small features in the image have large gradients (e.g. dust particles on the camera). Without blurring, these features may be incorrectly identified as the hologram center. For best results, blursize should be set to the radius of features to be ignored, but smaller than the distance between hologram fringes. To skip blurring, set blursize to 0. | Parameters: | * **image** (*ndarray*) – image to find the center(s) in * **centers** ([*int*](https://docs.python.org/3/library/functions.html#int)) – number of centers to find * **threshold** ([*float*](https://docs.python.org/3/library/functions.html#float) *(**optional**)*) – fraction of the maximum gradient below which all other gradients will be ignored (range 0-.99) * **blursize** ([*float*](https://docs.python.org/3/library/functions.html#float) *(**optional**)*) – radius (in pixels) of the Gaussian filter that is applied prior to Hough transform | | Returns: | **res** – row(s) and column(s) of center(s) | | Return type: | ndarray | Notes When threshold is close to 1, the code will run quickly but may lack accuracy. When threshold is set to 0, the gradient at all pixels will contribute to finding the centers and the code will take a little bit longer. `hough`(*col_deriv*, *row_deriv*, *centers=1*, *threshold=0.25*)[¶](#holopy.core.process.centerfinder.hough) Following the approach of a Hough transform, finds the pixel which the most gradients point towards or away from. Uses only gradients with magnitudes greater than threshold*maximum gradient. Once the pixel is found, uses a brightness-weighted average around that pixel to refine the center location to return. After the first center is found, the sourrounding area is blocked out and another brightest pixel is searched for if more centers are required. | Parameters: | * **col_deriv** (*numpy.ndarray*) – y-component of image intensity gradient * **row_deriv** (*numpy.ndarray*) – x-component of image intensity gradient * **centers** ([*int*](https://docs.python.org/3/library/functions.html#int)) – number of centers to find * **threshold** ([*float*](https://docs.python.org/3/library/functions.html#float) *(**optional**)*) – fraction of the maximum gradient below which all other gradients will be ignored (range 0-.99) | | Returns: | **res** – row and column of center or centers | | Return type: | ndarray | `image_gradient`(*image*)[¶](#holopy.core.process.centerfinder.image_gradient) Uses the Sobel operator as a numerical approximation of a derivative to find the x and y components of the image’s intensity gradient at each pixel. | Parameters: | **image** (*ndarray*) – image to find the gradient of | | Returns: | * **gradx** (*ndarray*) – x-components of intensity gradient * **grady** (*ndarray*) – y-components of intensity gradient | Handles Fourier transforms of HoloPy images by using numpy’s fft package. Tries to correctly interpret dimensions from xarray. `fft`(*data*, *shift=True*)[¶](#holopy.core.process.fourier.fft) More convenient Fast Fourier Transform An easier to use fft function, it will pick the correct fft to do based on the shape of the array, and do the fftshift for you. This is intended for working with images, and thus for dimensions greater than 2 does slicewise transforms of each “image” in a multidimensional stack | Parameters: | * **data** (*ndarray* *or* *xarray*) – The array to transform * **shift** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) – Whether to preform an fftshift on the array to give low frequences near the center as you probably expect. Default is to do the fftshift. | | Returns: | **fta** – The fourier transform of a | | Return type: | ndarray | `ft_coord`(*c*)[¶](#holopy.core.process.fourier.ft_coord) `ft_coords`(*cs*)[¶](#holopy.core.process.fourier.ft_coords) `get_spacing`(*c*)[¶](#holopy.core.process.fourier.get_spacing) `ifft`(*data*, *shift=True*)[¶](#holopy.core.process.fourier.ifft) More convenient Inverse Fast Fourier Transform An easier to use ifft function, it will pick the correct ifft to do based on the shape of the array, and do the fftshift for you. This is intended for working with images, and thus for dimensions greater than 2 does slicewise transforms of each “image” in a multidimensional stack | Parameters: | * **data** (*ndarray* *or* *xarray*) – The array to transform * **shift** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) – Whether to preform an fftshift on the array to give low frequences near the center as you probably expect. Default is to do the fftshift. | | Returns: | The inverse fourier transform of data | | Return type: | ndarray | `ift_coord`(*c*)[¶](#holopy.core.process.fourier.ift_coord) `ift_coords`(*cs*)[¶](#holopy.core.process.fourier.ift_coords) `transform_metadata`(*a*, *inverse*)[¶](#holopy.core.process.fourier.transform_metadata) Image enhancement through background subtraction, contrast adjustment, or detrending `add_noise`(*image*, *noise_mean=0.1*, *smoothing=0.01*, *poisson_lambda=1000*)[¶](#holopy.core.process.img_proc.add_noise) Add simulated noise to images. Intended for use with exact calculated images to make them look more like noisy ‘real’ measurements. Real image noise usually has correlation, so we smooth the raw random variable. The noise_mean can be controlled independently of the poisson_lambda that controls the shape of the distribution. In general, you can stick with our default of a large poisson_lambda (ie for imaging conditions not near the shot noise limit). Defaults are set to give noise vaguely similar to what we tend to see in our holographic imaging. | Parameters: | * **image** (*xarray.DataArray*) – The image to add noise to. * **smoothing** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Fraction of the image size to smooth by. Should in general be << 1 * **poisson_lambda** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Used to compute the shape of the noise distribution. You can generally leave this at its default value unless you are simulating shot noise limited imaging. | | Returns: | **noisy_image** – A copy of the input image with noise added. | | Return type: | xarray.DataArray | `bg_correct`(*raw*, *bg*, *df=None*)[¶](#holopy.core.process.img_proc.bg_correct) Correct for noisy images by dividing by a background. The calculation used is (raw-df)/(bg-df). | Parameters: | * **raw** (*xarray.DataArray*) – Image to be background divided. * **bg** (*xarray.DataArray*) – background image recorded with the same optical setup. * **df** (*xarray.DataArray*) – dark field image recorded without illumination. | | Returns: | **corrected_image** – A copy of the background divided input image with None values of noise_sd updated to match bg. | | Return type: | xarray.DataArray | `detrend`(*image*)[¶](#holopy.core.process.img_proc.detrend) Remove linear trends from an image. Performs a 2 axis linear detrend using scipy.signal.detrend | Parameters: | **image** (*xarray.DataArray*) – Image to process | | Returns: | **image** – Image with linear trends removed | | Return type: | xarray.DataArray | `normalize`(*image*)[¶](#holopy.core.process.img_proc.normalize) Normalize an image by dividing by the pixel average. This gives the image a mean value of 1. | Parameters: | **image** (*xarray.DataArray*) – The array to normalize | | Returns: | **normalized_image** – The normalized image | | Return type: | xarray.DataArray | `simulate_noise`(*shape*, *mean=0.1*, *smoothing=0.01*, *poisson_lambda=1000*)[¶](#holopy.core.process.img_proc.simulate_noise) Create an array of correlated noise. The noise_mean can be controlled independently of the poisson_lambda that controls the shape of the distribution. In general, you can stick with our default of a large poisson_lambda (ie for imaging conditions not near the shot noise limit). Defaults are set to give noise vaguely similar to what we tend to see in our holographic imaging. | Parameters: | * **shape** ([*int*](https://docs.python.org/3/library/functions.html#int) *or* *array_like of ints*) – shape of noise array * **smoothing** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Fraction of the image size to smooth by. Should in general be << 1 * **poisson_lambda** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Used to compute the shape of the noise distribution. You can generally leave this at its default value unless you are simulating shot noise limited imaging. | | Returns: | **noisy_image** – A copy of the input image with noise added. | | Return type: | ndarray | `subimage`(*arr*, *center*, *shape*)[¶](#holopy.core.process.img_proc.subimage) Pick out a region of an image or other array | Parameters: | * **arr** (*xarray.DataArray*) – The array to subimage * **center** (*tuple of ints* *or* *floats*) – The desired center of the region, should have the same number of elements as the arr has dimensions. Floats will be rounded * **shape** ([*int*](https://docs.python.org/3/library/functions.html#int) *or* *(*[*int*](https://docs.python.org/3/library/functions.html#int)*,* [*int*](https://docs.python.org/3/library/functions.html#int)*)*) – Desired shape of the region in x & y dimensions. If a single int is given it is applied along both axes. Shape values must be even. | | Returns: | **sub** – Subset of shape shape centered at center. DataArray coords will be set such that the upper left corner of the output has coordinates relative to the input. | | Return type: | xarray.DataArray | `zero_filter`(*image*)[¶](#holopy.core.process.img_proc.zero_filter) Search for and interpolate pixels equal to 0. This is to avoid NaN’s when a hologram is divided by a BG with 0’s. Interpolation fails if any of the four corner pixels are 0. | Parameters: | **image** (*xarray.DataArray*) – Image to process | | Returns: | **image** – Image where pixels = 0 are instead given values equal to average of neighbors. dtype is the same as the input image | | Return type: | xarray.DataArray | ##### Submodules[¶](#module-holopy.core.errors) Error classes used in holopy *exception* `BadImage`[¶](#holopy.core.errors.BadImage) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `CoordSysError`[¶](#holopy.core.errors.CoordSysError) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `DependencyMissing`(*dependency*, *message=''*)[¶](#holopy.core.errors.DependencyMissing) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `DeprecationError`[¶](#holopy.core.errors.DeprecationError) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `LoadError`(*filename*, *message*)[¶](#holopy.core.errors.LoadError) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `NoMetadata`[¶](#holopy.core.errors.NoMetadata) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `PerformanceWarning`[¶](#holopy.core.errors.PerformanceWarning) Bases: [`UserWarning`](https://docs.python.org/3/library/exceptions.html#UserWarning) `raise_fitting_api_error`(*correct*, *obselete*)[¶](#holopy.core.errors.raise_fitting_api_error) Root class for all of holopy. This class provides serialization to and from yaml text file for all holopy objects. yaml files are structured text files designed to be easy for humans to read and write but also easy for computers to read. HoloPy uses them to store information about experimental conditions and to describe analysis procedures. *class* `HoloPyObject`[¶](#holopy.core.holopy_object.HoloPyObject) Bases: [`holopy.core.holopy_object.Serializable`](#holopy.core.holopy_object.Serializable) Ancestor class for all HoloPy classes. HoloPy object’s purpose is to provide the machinery for saving to and loading from HoloPy yaml files *classmethod* `from_yaml`(*loader*, *node*)[¶](#holopy.core.holopy_object.HoloPyObject.from_yaml) Convert a representation node to a Python object. *classmethod* `to_yaml`(*dumper*, *data*)[¶](#holopy.core.holopy_object.HoloPyObject.to_yaml) Convert a Python object to a representation node. *class* `Serializable`[¶](#holopy.core.holopy_object.Serializable) Bases: `yaml.YAMLObject` Base class for any object that wants a nice clean yaml output *classmethod* `to_yaml`(*dumper*, *data*)[¶](#holopy.core.holopy_object.Serializable.to_yaml) Convert a Python object to a representation node. *class* `SerializableMetaclass`(*name*, *bases*, *kwds*)[¶](#holopy.core.holopy_object.SerializableMetaclass) Bases: `yaml.YAMLObjectMetaclass` *class* `Mapper`[¶](#holopy.core.mapping.Mapper) Bases: [`holopy.core.holopy_object.HoloPyObject`](#holopy.core.holopy_object.HoloPyObject) Creates “maps” from objects containing priors that retain their hierarchical structure (including ties) but are easily serializable. The main entry point is through convert_to_map, which returns a map of the object and also updates the Mapper parameter and parameter_names attributes so they can be extracted for later use. `add_parameter`(*parameter*, *name*)[¶](#holopy.core.mapping.Mapper.add_parameter) `check_for_ties`(*parameter*)[¶](#holopy.core.mapping.Mapper.check_for_ties) `convert_to_map`(*parameter*, *name=''*)[¶](#holopy.core.mapping.Mapper.convert_to_map) `get_parameter_index`(*parameter*, *name*)[¶](#holopy.core.mapping.Mapper.get_parameter_index) `iterate_mapping`(*prefix*, *pairs*)[¶](#holopy.core.mapping.Mapper.iterate_mapping) `map_dictionary`(*parameter*, *name*)[¶](#holopy.core.mapping.Mapper.map_dictionary) `map_transformed_prior`(*parameter*, *name*)[¶](#holopy.core.mapping.Mapper.map_transformed_prior) `map_xarray`(*parameter*, *name*)[¶](#holopy.core.mapping.Mapper.map_xarray) `edit_map_indices`(*map_entry*, *indices*)[¶](#holopy.core.mapping.edit_map_indices) Adjusts a map to account for ties between parameters | Parameters: | * **map_entry** – map or subset of map created by model methods * **indices** (*listlike*) – indices of parameters to be tied | `make_xarray`(*dim_name*, *keys*, *values*)[¶](#holopy.core.mapping.make_xarray) Packs values into xarray with new dim and coords (keys) `read_map`(*map_entry*, *parameter_values*)[¶](#holopy.core.mapping.read_map) Reads a map to create an object | Parameters: | * **map_entry** – map or subset of map created by model methods * **parameter_values** (*listlike*) – values to replace map placeholders in final object | `transformed_prior`(*transformation*, *base_priors*)[¶](#holopy.core.mapping.transformed_prior) `cartesian_distance`(*p1, p2=[0, 0, 0]*)[¶](#holopy.core.math.cartesian_distance) Return the Cartesian distance between points p1 and p2. | Parameters: | **p2** (*p1**,*) – Coordinates of point 1 and point 2 in N-dimensions | | Returns: | **dist** – Cartesian distance between points p1 and p2 | | Return type: | float64 | `chisq`(*fit*, *data*)[¶](#holopy.core.math.chisq) Calculate per-point value of chi-squared comparing a best-fit model and data. | Parameters: | * **fit** (*array_like*) – Values of best-fit model to be compared to data * **data** (*array_like*) – Data values to be compared to model | | Returns: | **chisq** – Chi-squared per point | | Return type: | [float](https://docs.python.org/3/library/functions.html#float) | Notes chi-squared is defined as \[\chi^2 = \frac{1}{N}\sum_{\textrm{points}} (\textrm{fit} - \textrm{data})^2\] where \(N\) is the number of data points. `find_transformation_function`(*initial_coordinates*, *desired_coordinates*)[¶](#holopy.core.math.find_transformation_function) `keep_in_same_coordinates`(*coords*)[¶](#holopy.core.math.keep_in_same_coordinates) `rotate_points`(*points*, *theta*, *phi*, *psi*)[¶](#holopy.core.math.rotate_points) Rotate an array of points about Euler angles in a z, y, z convention. | Parameters: | * **points** (*array-like* *(**n**,**3**)*) – Set of points to be rotated * **phi****,** **psi** (*theta**,*) – Euler rotation angles in z, y, z convention. These are *not* the same as angles in spherical coordinates. | | Returns: | **rotated_points** – Points rotated by Euler angles | | Return type: | array(n,3) | `rotation_matrix`(*alpha*, *beta*, *gamma*, *radians=True*)[¶](#holopy.core.math.rotation_matrix) Return a 3D rotation matrix | Parameters: | * **beta****,** **gamma** (*alpha**,*) – Euler rotation angles in z, y, z convention * **radians** (*boolean*) – Default True; treats input angles in radians | | Returns: | **rot** – Rotation matrix. To rotate a column vector x, use np.dot(rot, x.) | | Return type: | array(3,3) | Notes The Euler angles rotate a vector (in the active picture) by alpha clockwise about the fixed lab z axis, beta clockwise about the lab y axis, and by gamma about the lab z axis. Clockwise is defined as viewed from the origin, looking in the positive direction along an axis. This breaks compatability with previous conventions, which were adopted for compatability with the passive picture used by SCSMFO. `rsq`(*fit*, *data*)[¶](#holopy.core.math.rsq) Calculate correlation coeffiction R-squared comparing a best-fit model and data. | Parameters: | * **fit** (*array_like*) – Values of best-fit model to be compared to data * **data** (*array_like*) – Data values to be compared to model | | Returns: | **rsq** – Correlation coefficient R-squared. | | Return type: | [float](https://docs.python.org/3/library/functions.html#float) | Notes R-squared is defined as \[R^2 = 1 - \frac{\sum_{\textrm{points}} (\textrm{data} - \textrm{fit})^2}{\sum_{\textrm{points}} (\textrm{data} - \bar{\textrm{data}})^2}\] where \(\bar{\textrm{data}}\) is the mean value of the data. If the model perfectly describes the data, \(R^2 = 1\). `to_cartesian`(*r*, *theta*, *phi*)[¶](#holopy.core.math.to_cartesian) `transform_cartesian_to_cylindrical`(*x_y_z*)[¶](#holopy.core.math.transform_cartesian_to_cylindrical) `transform_cartesian_to_spherical`(*x_y_z*)[¶](#holopy.core.math.transform_cartesian_to_spherical) `transform_cylindrical_to_cartesian`(*rho_phi_z*)[¶](#holopy.core.math.transform_cylindrical_to_cartesian) `transform_cylindrical_to_spherical`(*rho_phi_z*)[¶](#holopy.core.math.transform_cylindrical_to_spherical) `transform_spherical_to_cartesian`(*r_theta_phi*)[¶](#holopy.core.math.transform_spherical_to_cartesian) `transform_spherical_to_cylindrical`(*r_theta_phi*)[¶](#holopy.core.math.transform_spherical_to_cylindrical) Classes for defining metadata about experimental or calculated results. `clean_concat`(*arrays*, *dim*)[¶](#holopy.core.metadata.clean_concat) Concatenate a list of xr.DataArray objects along a specified dimension, keeping the metadata of the first array. | Parameters: | * **arrays** (list of `xr.xarray`) – * **dim** (*valid dimension* *(**string**)*) – | | Returns: | | | Return type: | xarray | `copy_metadata`(*old*, *data*, *do_coords=True*)[¶](#holopy.core.metadata.copy_metadata) Create a new xarray with data from one input and metadata from another. | Parameters: | * **old** (xr.DataArray) – The xarray to copy the metadata from. * **data** (xr.DataArray) – The xarray to copy the data from. * **do_coords** ([*bool*](https://docs.python.org/3/library/functions.html#bool)*,* *optional*) – Whether or not to copy the coordinates. Default is True * **Returns** – * **xr.DataArray** – | `data_grid`(*arr*, *spacing=None*, *medium_index=None*, *illum_wavelen=None*, *illum_polarization=None*, *noise_sd=None*, *name=None*, *extra_dims=None*, *z=0*)[¶](#holopy.core.metadata.data_grid) Create a set of detector points along with other experimental metadata. | Returns: | | | Return type: | DataArray object | Notes Use the higher-level detector_grid() and detector_points() functions. This should be viewed as a factory method. `detector_grid`(*shape*, *spacing*, *name=None*, *extra_dims=None*)[¶](#holopy.core.metadata.detector_grid) Create a rectangular grid of pixels to represent a detector on which scattering calculations are to be performed. | Parameters: | * **shape** ([*int*](https://docs.python.org/3/library/functions.html#int) *or* *list-like* *(**2**)*) – If int, detector is a square grid of shape x shape points. If array_like, detector has *shape*[0] rows and *shape*[1] columns. * **spacing** ([*int*](https://docs.python.org/3/library/functions.html#int) *or* *list-like* *(**2**)*) – If int, distance between square detector pixels. If array_like, *spacing*[0] between adjacent rows and *spacing*[1] between adjacent columns. * **name** (*string**,* *optional*) – * **extra_dims** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*,* *optional*) – extra dimension(s) to add to the empty detector grid as {dimname: [coords]}. | | Returns: | **grid** – DataArray of zeros with coordinates calculated according to *shape* and *spacing* | | Return type: | DataArray object | Notes Typically used to define a set of points to represent the pixels of a digital camera in scattering calculations. `detector_points`(*coords={}*, *x=None*, *y=None*, *z=None*, *r=None*, *theta=None*, *phi=None*, *name=None*)[¶](#holopy.core.metadata.detector_points) Returns a one-dimensional set of detector coordinates at which scattering calculations are to be done. | Parameters: | * **coords** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*,* *optional*) – Dictionary of detector coordinates. Default: empty dictionary. Typical usage should not pass this argument, giving other parameters (Cartesian x, y, and z or polar r, theta, and phi coordinates) instead. * **y** (*x**,*) – Cartesian x and y coordinates of detectors. * **z** ([*int*](https://docs.python.org/3/library/functions.html#int) *or* *array_like**,* *optional*) – Cartesian z coordinates of detectors. If not specified, assume z = 0. * **r** ([*int*](https://docs.python.org/3/library/functions.html#int) *or* *array_like**,* *optional*) – Spherical polar radial coordinates of detectors. If not specified, assume r = infinity (far-field). * **theta** ([*int*](https://docs.python.org/3/library/functions.html#int) *or* *array_like**,* *optional*) – Spherical polar coordinates (polar angle from z axis) of detectors. * **phi** ([*int*](https://docs.python.org/3/library/functions.html#int) *or* *array_like**,* *optional*) – Spherical polar azimuthal coodinates of detectors. * **name** (*string*) – | | Returns: | **grid** – DataArray of zeros with calculated coordinates. | | Return type: | DataArray object | Notes Specify either the Cartesian or the polar coordinates of your detector. This may be helpful for modeling static light scattering calculations. Use detector_grid() to specify coordinates of a grid of pixels (e.g., a digital camera.) `dict_to_array`(*schema*, *inval*)[¶](#holopy.core.metadata.dict_to_array) `flat`(*a*)[¶](#holopy.core.metadata.flat) `from_flat`(*a*)[¶](#holopy.core.metadata.from_flat) `get_extents`(*detector_grid*)[¶](#holopy.core.metadata.get_extents) Find the x, y, z extent of a ``detector_grid``, as a dict. `get_spacing`(*detector_grid*)[¶](#holopy.core.metadata.get_spacing) Find the (x, y) spacing for a ``detector_grid``. `get_values`(*a*)[¶](#holopy.core.metadata.get_values) `make_coords`(*shape*, *spacing*, *z=0*)[¶](#holopy.core.metadata.make_coords) `make_subset_data`(*data*, *pixels=None*, *return_selection=False*, *seed=None*)[¶](#holopy.core.metadata.make_subset_data) Sub-sample a data for faster inference. | Parameters: | * **data** (xr.DataArray) – The data to subsample * **pixels** ([*int*](https://docs.python.org/3/library/functions.html#int)*,* *optional*) – The number of pixels to subsample. Defaults to the entire image. * **return_selection** ([*bool*](https://docs.python.org/3/library/functions.html#bool)*,* *optional*) – Whether to return the pixel indices which were sampled. Default is False * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int) *or* [*None*](https://docs.python.org/3/library/constants.html#None)*,* *optional*) – If not None, the seed to seed the random number generator with. | | Returns: | * **subset** (xr.DataArray) * **[selection** (*np.ndarray, dtype int]*) | `to_vector`(*c*)[¶](#holopy.core.metadata.to_vector) `update_metadata`(*a*, *medium_index=None*, *illum_wavelen=None*, *illum_polarization=None*, *noise_sd=None*)[¶](#holopy.core.metadata.update_metadata) Returns a copy of an image with updated metadata in its ‘attrs’ field. | Parameters: | * **a** (*xarray.DataArray*) – image to update. * **medium_index** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Updated refractive index of the medium in the image. * **illum_wavelen** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Updated wavelength of illumination in the image. * **illum_polarization** (*list-like*) – Updated polarization of illumination in the image. * **noise_sd** ([*float*](https://docs.python.org/3/library/functions.html#float)) – standard deviation of Gaussian noise in the image. | | Returns: | **b** – copy of input image with updated metadata. | | Return type: | xarray.DataArray | *class* `BoundedGaussian`(*mu*, *sd*, *lower_bound=-inf*, *upper_bound=inf*, *name=None*)[¶](#holopy.core.prior.BoundedGaussian) Bases: [`holopy.core.prior.Gaussian`](#holopy.core.prior.Gaussian) `lnprob`(*p*)[¶](#holopy.core.prior.BoundedGaussian.lnprob) Note that this does not return the actual log-probability, but a value proportional to it. `prob`(*p*)[¶](#holopy.core.prior.BoundedGaussian.prob) Note that this does not return the actual probability, but a value proportional to it. `sample`(*size=None*)[¶](#holopy.core.prior.BoundedGaussian.sample) *class* `ComplexPrior`(*real*, *imag*, *name=None*)[¶](#holopy.core.prior.ComplexPrior) Bases: [`holopy.core.prior.TransformedPrior`](#holopy.core.prior.TransformedPrior) A complex free parameter ComplexPrior has a real and imaginary part which can (potentially) vary separately. | Parameters: | * **imag** (*real**,*) – The real and imaginary parts of this parameter. Assign floats to fix that portion or parameters to allow it to vary. The parameters must be purely real. You should omit names for the parameters; ComplexPrior will name them * **name** (*string*) – Short descriptive name of the ComplexPrior. Do not provide this if using a ParameterizedScatterer, a name will be assigned based its position within the scatterer. | `imag`[¶](#holopy.core.prior.ComplexPrior.imag) `lnprob`(*p*)[¶](#holopy.core.prior.ComplexPrior.lnprob) `map_keys`[¶](#holopy.core.prior.ComplexPrior.map_keys) `prob`(*p*)[¶](#holopy.core.prior.ComplexPrior.prob) `real`[¶](#holopy.core.prior.ComplexPrior.real) *class* `Gaussian`(*mu*, *sd*, *name=None*)[¶](#holopy.core.prior.Gaussian) Bases: [`holopy.core.prior.Prior`](#holopy.core.prior.Prior) `guess`[¶](#holopy.core.prior.Gaussian.guess) `lnprob`(*p*)[¶](#holopy.core.prior.Gaussian.lnprob) `prob`(*p*)[¶](#holopy.core.prior.Gaussian.prob) `sample`(*size=None*)[¶](#holopy.core.prior.Gaussian.sample) `variance`[¶](#holopy.core.prior.Gaussian.variance) *class* `Prior`[¶](#holopy.core.prior.Prior) Bases: [`holopy.core.holopy_object.HoloPyObject`](#holopy.core.holopy_object.HoloPyObject) Base class for Bayesian priors in holopy. Prior subclasses should define at least the following methods: > * guess > * sample > * prob > * lnprob `renamed`(*name*)[¶](#holopy.core.prior.Prior.renamed) `scale`(*physical*)[¶](#holopy.core.prior.Prior.scale) `unscale`(*scaled*)[¶](#holopy.core.prior.Prior.unscale) *class* `TransformedPrior`(*transformation*, *base_prior*, *name=None*)[¶](#holopy.core.prior.TransformedPrior) Bases: [`holopy.core.prior.Prior`](#holopy.core.prior.Prior) `guess`[¶](#holopy.core.prior.TransformedPrior.guess) `lnprob`(*p*)[¶](#holopy.core.prior.TransformedPrior.lnprob) `map_keys`[¶](#holopy.core.prior.TransformedPrior.map_keys) `prob`(*p*)[¶](#holopy.core.prior.TransformedPrior.prob) `sample`(*size=None*)[¶](#holopy.core.prior.TransformedPrior.sample) *class* `Uniform`(*lower_bound*, *upper_bound*, *guess=None*, *name=None*)[¶](#holopy.core.prior.Uniform) Bases: [`holopy.core.prior.Prior`](#holopy.core.prior.Prior) `interval`[¶](#holopy.core.prior.Uniform.interval) `lnprob`(*p*)[¶](#holopy.core.prior.Uniform.lnprob) `prob`(*p*)[¶](#holopy.core.prior.Uniform.prob) `sample`(*size=None*)[¶](#holopy.core.prior.Uniform.sample) `generate_guess`(*parameters*, *nguess=1*, *scaling=1*, *seed=None*)[¶](#holopy.core.prior.generate_guess) `make_center_priors`(*im*, *z_range_extents=5*, *xy_uncertainty_pixels=1*, *z_range_units=None*)[¶](#holopy.core.prior.make_center_priors) Make sensible default priors for the center of a sphere in a hologram | Parameters: | * **im** (*xarray*) – The image you wish to make priors for * **z_range_extents** ([*float*](https://docs.python.org/3/library/functions.html#float) *(**optional**)*) – What range to extend a uniform prior for z over, measured in multiples of the total extent of the image. The default is 5 times the extent of the image, a large range, but since tempering is quite good at refining this, it is safer to just choose a large range to be sure to include the correct value. * **xy_uncertainty_pixels** ([*float*](https://docs.python.org/3/library/functions.html#float) *(**optional**)*) – The number of pixels of uncertainty to assume for the centerfinder. The default is 1 pixel, and this is probably correct for most images. * **z_range_units** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Specify the range of the z prior in your data units. If provided, z_range_extents is ignored. | `updated`(*prior*, *v*, *extra_uncertainty=0*)[¶](#holopy.core.prior.updated) Update a prior from a posterior | Parameters: | * **v** ([*UncertainValue*](index.html#holopy.inference.result.UncertainValue)) – The new value, usually from an mcmc result * **extra_uncertainty** ([*float*](https://docs.python.org/3/library/functions.html#float)) – provide a floor for uncertainty (sd) of the new parameter | Misc utility functions to make coding more convenient *class* `LnpostWrapper`(*model*, *data*, *new_pixels=None*, *minus=False*)[¶](#holopy.core.utils.LnpostWrapper) Bases: [`holopy.core.holopy_object.HoloPyObject`](#holopy.core.holopy_object.HoloPyObject) We want to be able to define a specific model.lnposterior calculation that only takes parameter values as an argument for passing into optimizers. However, individual functions can’t be pickled to distribute hologram calculations with python multiprocessing. This class solves both issues. `evaluate`(*par_vals*)[¶](#holopy.core.utils.LnpostWrapper.evaluate) *class* `NonePool`[¶](#holopy.core.utils.NonePool) Bases: [`object`](https://docs.python.org/3/library/functions.html#object) `close`()[¶](#holopy.core.utils.NonePool.close) `map`(*function*, *arguments*)[¶](#holopy.core.utils.NonePool.map) *class* `SuppressOutput`(*suppress_output=True*)[¶](#holopy.core.utils.SuppressOutput) Bases: [`object`](https://docs.python.org/3/library/functions.html#object) `choose_pool`(*parallel*)[¶](#holopy.core.utils.choose_pool) This is a remake of schwimmbad.choose_pool with a single argument. `dict_without`(*d*, *keys*)[¶](#holopy.core.utils.dict_without) Exclude a list of keys from a dictionary. Silently ignores any key in keys that is not in the dict (this is intended to be used to make sure a dict does not contain specific keys) :param d: The dictionary to operate on :type d: dict :param keys: The keys to exclude :type keys: list(string) :param returns: A copy of dict without any of the specified keys :type returns: d2 `ensure_array`(*x*)[¶](#holopy.core.utils.ensure_array) if x is None, returns None. Otherwise, gives x in a form so that each of: len(x), x[0], x+2 will not fail. `ensure_listlike`(*x*)[¶](#holopy.core.utils.ensure_listlike) `ensure_scalar`(*x*)[¶](#holopy.core.utils.ensure_scalar) `mkdir_p`(*path*)[¶](#holopy.core.utils.mkdir_p) Equivalent to mkdir -p at the shell, this function makes a directory and its parents as needed, silently doing nothing if it exists. `repeat_sing_dims`(*indict*, *keys='all'*)[¶](#holopy.core.utils.repeat_sing_dims) `updated`(*d*, *update={}*, *filter_none=True*, ***kwargs*)[¶](#holopy.core.utils.updated) Return a dictionary updated with keys from update Analgous to sorted, this is an equivalent of d.update as a non-modifying free function | Parameters: | * **d** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) – The dict to update * **update** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) – The dict to take updates from | #### holopy.inference package[¶](#module-holopy.inference) ##### Submodules[¶](#module-holopy.inference.cmaes) Stochastic fitting of models to data *class* `CmaStrategy`(*npixels=None*, *popsize=None*, *resample_pixels=True*, *parent_fraction=0.25*, *weight_function=None*, *walker_initial_pos=None*, *tols={}*, *seed=None*, *parallel='auto'*)[¶](#holopy.inference.cmaes.CmaStrategy) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) Inference strategy defining a Covariance Matrix Adaptation Evolutionary Strategy using cma package | Parameters: | * **npixels** ([*int*](https://docs.python.org/3/library/functions.html#int)*,* *optional*) – Number of pixels in the image to fit. default fits all. * **resample_pixels** (*Boolean**,* *optional*) – If true (default), new pixels are chosen for each call of posterior. Otherwise, a single pixel subset is used throughout calculation. * **parent_fraction** ([*float*](https://docs.python.org/3/library/functions.html#float)*,* *optional*) – Fraction of each generation to use to construct the next generation. Takes symbol mu in cma literature * **weight_function** (*function**,* *optional*) – takes arguments (i, popsize), i in range(popsize); returns weight of i * **tols** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*,* *optional*) – tolerance values to overwrite the cma defaults * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int)*,* *optional*) – random seed to use * **parallel** (*optional*) – number of threads to use or pool object or one of {None, ‘all’, ‘mpi’}. Default tries ‘mpi’ then ‘all’. | `fit`(*model*, *data*)[¶](#holopy.inference.cmaes.CmaStrategy.fit) `run_cma`(*obj_func*, *parameters*, *initial_population*, *weight_function*, *tols={}*, *seed=None*, *parallel='auto'*)[¶](#holopy.inference.cmaes.run_cma) instantiate and run a CMAEvolutionStrategy object | Parameters: | * **obj_func** (*Function*) – function to be minimized (not maximized like posterior) * **parameters** (*list of Prior objects*) – parameters to fit * **initial_population** (*array*) – starting population with shape = (popsize, len(parameters)) * **weight_function** (*function*) – takes arguments (i, popsize), i in range(popsize); returns weight of i * **tols** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)*,* *optional*) – tolerance values to overwrite the cma defaults * **seed** ([*int*](https://docs.python.org/3/library/functions.html#int)*,* *optional*) – random seed to use * **parallel** (*optional*) – number of threads to use or pool object or one of {None, ‘all’, ‘mpi’}. Default tries ‘mpi’ then ‘all’. | Sample posterior probabilities given model and data *class* `EmceeStrategy`(*nwalkers=100*, *nsamples=None*, *npixels=None*, *walker_initial_pos=None*, *parallel='auto'*, *seed=None*)[¶](#holopy.inference.emcee.EmceeStrategy) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) `sample`(*model*, *data*)[¶](#holopy.inference.emcee.EmceeStrategy.sample) *class* `TemperedStrategy`(*next_initial_dist=<function sample_one_sigma_gaussian>*, *nwalkers=100*, *nsamples=1000*, *min_pixels=None*, *npixels=1000*, *walker_initial_pos=None*, *parallel='auto'*, *stages=3*, *stage_len=30*, *seed=None*)[¶](#holopy.inference.emcee.TemperedStrategy) Bases: [`holopy.inference.emcee.EmceeStrategy`](#holopy.inference.emcee.EmceeStrategy) `add_stage_strategy`(*nsamples*, *npixels*)[¶](#holopy.inference.emcee.TemperedStrategy.add_stage_strategy) `sample`(*model*, *data*)[¶](#holopy.inference.emcee.TemperedStrategy.sample) `emcee_lnprobs_DataArray`(*sampler*)[¶](#holopy.inference.emcee.emcee_lnprobs_DataArray) `emcee_samples_DataArray`(*sampler*, *parameter_names*)[¶](#holopy.inference.emcee.emcee_samples_DataArray) `sample_emcee`(*model*, *data*, *nwalkers*, *nsamples*, *walker_initial_pos*, *parallel='auto'*, *seed=None*)[¶](#holopy.inference.emcee.sample_emcee) `sample_one_sigma_gaussian`(*result*)[¶](#holopy.inference.emcee.sample_one_sigma_gaussian) `fit`(*data*, *model*, *parameters=None*, *strategy=None*)[¶](#holopy.inference.interface.fit) `make_default_model`(*base_scatterer*, *fitting_parameters=None*)[¶](#holopy.inference.interface.make_default_model) `make_uniform`(*guesses*, *key*)[¶](#holopy.inference.interface.make_uniform) `parameterize_scatterer`(*base_scatterer*, *fitting_parameters*)[¶](#holopy.inference.interface.parameterize_scatterer) `replace_center`(*parameters*, *key*)[¶](#holopy.inference.interface.replace_center) `sample`(*data*, *model*, *strategy=None*)[¶](#holopy.inference.interface.sample) `validate_strategy`(*strategy*, *operation*)[¶](#holopy.inference.interface.validate_strategy) *class* `AlphaModel`(*scatterer*, *alpha=1*, *noise_sd=None*, *medium_index=None*, *illum_wavelen=None*, *illum_polarization=None*, *theory='auto'*, *constraints=[]*)[¶](#holopy.inference.model.AlphaModel) Bases: [`holopy.inference.model.Model`](#holopy.inference.model.Model) Model of hologram image formation with scaling parameter alpha. `alpha`[¶](#holopy.inference.model.AlphaModel.alpha) *class* `ExactModel`(*scatterer*, *calc_func=<function calc_holo>*, *noise_sd=None*, *medium_index=None*, *illum_wavelen=None*, *illum_polarization=None*, *theory='auto'*, *constraints=[]*)[¶](#holopy.inference.model.ExactModel) Bases: [`holopy.inference.model.Model`](#holopy.inference.model.Model) Model of arbitrary scattering function given by calc_func. *class* `LimitOverlaps`(*fraction=0.1*)[¶](#holopy.inference.model.LimitOverlaps) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) Constraint prohibiting overlaps beyond a certain tolerance. fraction is the largest overlap allowed, in terms of sphere diameter. `check`(*s*)[¶](#holopy.inference.model.LimitOverlaps.check) *class* `Model`(*scatterer*, *noise_sd=None*, *medium_index=None*, *illum_wavelen=None*, *illum_polarization=None*, *theory='auto'*, *constraints=[]*)[¶](#holopy.inference.model.Model) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) Model probabilites of observing data Compute probabilities that observed data could be explained by a set of scatterer and observation parameters. `add_tie`(*parameters_to_tie*, *new_name=None*)[¶](#holopy.inference.model.Model.add_tie) Defines new ties between model parameters | Parameters: | * **parameters_to_tie** (*listlike*) – names of parameters to tie, as given by keys in model.parameters * **new_name** (*string**,* *optional*) – the name for the new tied parameter | `ensure_parameters_are_listlike`(*pars*)[¶](#holopy.inference.model.Model.ensure_parameters_are_listlike) `fit`(*data*, *strategy=None*)[¶](#holopy.inference.model.Model.fit) `forward`(*pars*, *detector*)[¶](#holopy.inference.model.Model.forward) *classmethod* `from_yaml`(*loader*, *node*)[¶](#holopy.inference.model.Model.from_yaml) Convert a representation node to a Python object. `generate_guess`(*n=1*, *scaling=1*, *seed=None*)[¶](#holopy.inference.model.Model.generate_guess) `illum_polarization`[¶](#holopy.inference.model.Model.illum_polarization) `illum_wavelen`[¶](#holopy.inference.model.Model.illum_wavelen) `initial_guess`[¶](#holopy.inference.model.Model.initial_guess) dictionary of initial guess values for each parameter `initial_guess_scatterer`[¶](#holopy.inference.model.Model.initial_guess_scatterer) `lnlike`(*pars*, *data*)[¶](#holopy.inference.model.Model.lnlike) Compute the log-likelihood for pars given data | Parameters: | * **pars** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict) *or* [*list*](https://docs.python.org/3/library/stdtypes.html#list)) – list - values for each parameter in the order of self._parameters dict - keys should match self.parameters * **data** (*xarray*) – The data to compute likelihood against | | Returns: | **lnlike** | | Return type: | [float](https://docs.python.org/3/library/functions.html#float) | `lnposterior`(*pars*, *data*, *pixels=None*)[¶](#holopy.inference.model.Model.lnposterior) Compute the log-posterior probability of pars given data | Parameters: | * **pars** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict) *or* [*list*](https://docs.python.org/3/library/stdtypes.html#list)) – list - values for each parameter in the order of self._parameters dict - keys should match self.parameters * **data** (*xarray*) – The data to compute posterior against * **pixels** ([*int*](https://docs.python.org/3/library/functions.html#int)*(**optional**)*) – Specify to use a random subset of all pixels in data | | Returns: | **lnposterior** | | Return type: | [float](https://docs.python.org/3/library/functions.html#float) | `lnprior`(*pars*)[¶](#holopy.inference.model.Model.lnprior) Compute the log-prior probability of pars | Parameters: | **pars** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict) *or* [*list*](https://docs.python.org/3/library/stdtypes.html#list)) – list - values for each parameter in the order of self._parameters dict - keys should match self.parameters | | Returns: | **lnprior** | | Return type: | [float](https://docs.python.org/3/library/functions.html#float) | `medium_index`[¶](#holopy.inference.model.Model.medium_index) `noise_sd`[¶](#holopy.inference.model.Model.noise_sd) `parameters`[¶](#holopy.inference.model.Model.parameters) dictionary of the model’s parameters `sample`(*data*, *strategy=None*)[¶](#holopy.inference.model.Model.sample) `scatterer`[¶](#holopy.inference.model.Model.scatterer) `scatterer_from_parameters`(*pars*)[¶](#holopy.inference.model.Model.scatterer_from_parameters) Creates a scatterer by setting values for model parameters | Parameters: | **pars** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict) *or* [*list*](https://docs.python.org/3/library/stdtypes.html#list)) – list - values for each parameter in the order of self._parameters dict - keys should match self.parameters | | Returns: | | | Return type: | scatterer | `theory_from_parameters`(*pars*)[¶](#holopy.inference.model.Model.theory_from_parameters) Interfaces to minimizers. Classes here provide a common interface to a variety of third party minimizers. *class* `NmpfitStrategy`(*npixels=None*, *quiet=True*, *ftol=1e-10*, *xtol=1e-10*, *gtol=1e-10*, *damp=0*, *maxiter=100*, *seed=None*)[¶](#holopy.inference.nmpfit.NmpfitStrategy) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) Levenberg-Marquardt minimizer, from Numpy/Python translation of <NAME>’s mpfit.pro. | Parameters: | * **npixels** ([*None*](https://docs.python.org/3/library/constants.html#None)) – Fit only a randomly selected fraction of the data points in data * **quiet** (*Boolean*) – If False, print output on minimizer convergence. Default is True * **ftol** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Convergence criterion for minimizer: converges if actual and predicted relative reductions in chi squared <= ftol * **xtol** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Convergence criterion for minimizer: converges if relative error between two Levenberg-Marquardt iterations is <= xtol * **gtol** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Convergence criterion for minimizer: converges if absolute value of cosine of angle between vector of cost function evaluated at current solution for minimized parameters and any column of the Jacobian is <= gtol * **damp** ([*float*](https://docs.python.org/3/library/functions.html#float)) – If nonzero, residuals larger than damp will be replaced by tanh. See nmpfit documentation. * **maxiter** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Maximum number of Levenberg-Marquardt iterations to be performed. | Notes See nmpfit documentation for further details. Not all functionalities of nmpfit are implemented here: in particular, we do not allow analytical derivatives of the residual function, which is impractical and/or impossible to calculate for holograms. If you want to weight the residuals, you need to supply a custom residual function. `calc_residuals`(*par_vals*)[¶](#holopy.inference.nmpfit.NmpfitStrategy.calc_residuals) `cleanup_from_fit`()[¶](#holopy.inference.nmpfit.NmpfitStrategy.cleanup_from_fit) `fit`(*model*, *data*)[¶](#holopy.inference.nmpfit.NmpfitStrategy.fit) fit a model to some data | Parameters: | * **model** ([`Model`](#holopy.inference.model.Model) object) – A model describing the scattering system which leads to your data and the parameters to vary to fit it to the data * **data** (*xarray.DataArray*) – The data to fit | | Returns: | **result** – an object containing the best fit parameters and information about the fit | | Return type: | `FitResult` | `get_errors_from_minimizer`(*fitted_pars*)[¶](#holopy.inference.nmpfit.NmpfitStrategy.get_errors_from_minimizer) `initialize_fit`(*model*, *data*)[¶](#holopy.inference.nmpfit.NmpfitStrategy.initialize_fit) `minimize`(*parameters*, *obj_func*)[¶](#holopy.inference.nmpfit.NmpfitStrategy.minimize) `unscale_pars_from_minimizer`(*values*)[¶](#holopy.inference.nmpfit.NmpfitStrategy.unscale_pars_from_minimizer) Results of sampling *class* `FitResult`(*data*, *model*, *strategy*, *time*, *kwargs={}*)[¶](#holopy.inference.result.FitResult) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) `add_attr`(*kwargs*)[¶](#holopy.inference.result.FitResult.add_attr) `best_fit`()[¶](#holopy.inference.result.FitResult.best_fit) `forward`(*pars*)[¶](#holopy.inference.result.FitResult.forward) `guess_hologram`[¶](#holopy.inference.result.FitResult.guess_hologram) `guess_parameters`[¶](#holopy.inference.result.FitResult.guess_parameters) `guess_scatterer`[¶](#holopy.inference.result.FitResult.guess_scatterer) `hologram`[¶](#holopy.inference.result.FitResult.hologram) `max_lnprob`[¶](#holopy.inference.result.FitResult.max_lnprob) `parameters`[¶](#holopy.inference.result.FitResult.parameters) `scatterer`[¶](#holopy.inference.result.FitResult.scatterer) *class* `SamplingResult`(*data*, *model*, *strategy*, *time*, *kwargs={}*)[¶](#holopy.inference.result.SamplingResult) Bases: [`holopy.inference.result.FitResult`](#holopy.inference.result.FitResult) `burn_in`(*sample_number*)[¶](#holopy.inference.result.SamplingResult.burn_in) *class* `TemperedSamplingResult`(*end_result*, *stage_results*, *strategy*, *time*)[¶](#holopy.inference.result.TemperedSamplingResult) Bases: [`holopy.inference.result.SamplingResult`](#holopy.inference.result.SamplingResult) *class* `UncertainValue`(*guess*, *plus*, *minus=None*, *name=None*)[¶](#holopy.inference.result.UncertainValue) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) Represent an uncertain value | Parameters: | * **value** ([*float*](https://docs.python.org/3/library/functions.html#float)) – The value * **plus** ([*float*](https://docs.python.org/3/library/functions.html#float)) – The plus n_sigma uncertainty (or the uncertainty if it is symmetric) * **minus** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* [*None*](https://docs.python.org/3/library/constants.html#None)) – The minus n_sigma uncertainty, or None if the uncertainty is symmetric * **n_sigma** ([*int*](https://docs.python.org/3/library/functions.html#int) *(or* [*float*](https://docs.python.org/3/library/functions.html#float)*)*) – The number of sigma the uncertainties represent | *class* `LeastSquaresScipyStrategy`(*ftol=1e-10*, *xtol=1e-10*, *gtol=1e-10*, *max_nfev=None*, *npixels=None*)[¶](#holopy.inference.scipyfit.LeastSquaresScipyStrategy) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) `fit`(*model*, *data*)[¶](#holopy.inference.scipyfit.LeastSquaresScipyStrategy.fit) fit a model to some data | Parameters: | * **model** ([`Model`](#holopy.inference.model.Model) object) – A model describing the scattering system which leads to your data and the parameters to vary to fit it to the data * **data** (*xarray.DataArray*) – The data to fit | | Returns: | **result** – Contains the best fit parameters and information about the fit | | Return type: | `FitResult` | `minimize`(*parameters*, *residuals_function*)[¶](#holopy.inference.scipyfit.LeastSquaresScipyStrategy.minimize) `unscale_pars_from_minimizer`(*parameters*, *values*)[¶](#holopy.inference.scipyfit.LeastSquaresScipyStrategy.unscale_pars_from_minimizer) #### holopy.propagation package[¶](#module-holopy.propagation) ##### Submodules[¶](#module-holopy.propagation.convolution_propagation) Code to propagate objects/waves using scattering models. `propagate`(*data*, *d*, *medium_index=None*, *illum_wavelen=None*, *cfsp=0*, *gradient_filter=False*)[¶](#holopy.propagation.convolution_propagation.propagate) Propagates a hologram along the optical axis | Parameters: | * **data** (*xarray.DataArray*) – Hologram to propagate * **d** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* *list of floats*) – Distance to propagate or desired schema. A list tells to propagate to several distances and return the volume * **cfsp** (*integer* *(**optional**)*) – Cascaded free-space propagation factor. If this is an integer > 0, the transfer function G will be calculated at d/csf and the value returned will be G**csf. This helps avoid artifacts related to the limited window of the transfer function * **gradient_filter** ([*float*](https://docs.python.org/3/library/functions.html#float)) – For each distance, compute a second propagation a distance gradient_filter away and subtract. This enhances contrast of rapidly varying features. You may wish to use the number that is a multiple of the medium wavelength (illum_wavelen / medium_index) | | Returns: | **data** – The hologram progagated to a distance d from its current location. | | Return type: | xarray.DataArray | Notes holopy is agnostic to units, and the propagation result will be correct as long as the distance and wavelength are in the same units. `trans_func`(*schema*, *d*, *med_wavelen*, *cfsp=0*, *gradient_filter=0*)[¶](#holopy.propagation.convolution_propagation.trans_func) Calculates the optical transfer function to use in reconstruction This routine uses the analytical form of the transfer function found in in Kreis [[1]](#id3). It can optionally do cascaded free-space propagation for greater accuracy [[2]](#id4), although the code will run slightly more slowly. | Parameters: | * **schema** (*xarray.DataArray*) – Hologram to obtain the maximum dimensions of the transfer function * **d** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* *list of floats*) – Reconstruction distance. If list or array, this function will return an array of transfer functions, one for each distance * **med_wavelen** ([*float*](https://docs.python.org/3/library/functions.html#float)) – The wavelength in the medium you are propagating through * **cfsp** (*integer* *(**optional**)*) – Cascaded free-space propagation factor. If this is an integer > 0, the transfer function G will be calculated at d/csf and the value returned will be G**csf * **gradient_filter** ([*float*](https://docs.python.org/3/library/functions.html#float) *(**optional**)*) – Subtract a second transfer function a distance gradient_filter from each z | | Returns: | **trans_func** – The calculated transfer function. This will be at most as large as shape, but may be smaller if the frequencies outside that are zero | | Return type: | xarray.DataArray | References | [[1]](#id1) | Kreis, Handbook of Holographic Interferometry (Wiley, 2005), equation 3.79 (page 116) | | [[2]](#id2) | Kreis, Optical Engineering 41(8):1829, section 5 | `interpolate2D`(*data*, *i*, *j*, *fill=None*)[¶](#holopy.propagation.point_source_propagate.interpolate2D) Interpolates values from a 2D array (data) given non-integer indecies i and j. If [i,j] is outside of the shape of data, fill is returned. If fill=None, the value of the closest edge pixel to (i,j) is used. `ps_propagate`(*data*, *d*, *L*, *beam_c*, *out_schema=None*)[¶](#holopy.propagation.point_source_propagate.ps_propagate) Propagates light back through a hologram that was taken using a diverging reference beam. | Parameters: | * **is a holopy Xarray. It is the hologram to reconstruct. Must be** (*data*) – * **The pixel spacing must also be square.** (*square.*) – * **= distance from pinhole to reconstructed image****,** **in meters** **(****this is** (*d*) – * **in Jericho and Kreuzer****)** **Can be a scalar** **or** **a 1D list** **or** **array.** (*z*) – * **= distance from screen to pinhole****,** **in meters** (*L*) – * **=** **[****x****,****y****]** **coodinates of beam center****,** **in pixels** (*beam_c*) – * **= size of output image and pixel spacing****,** **default is the schema** (*out_schema*) – * **data.** (*of*) – | | Returns: | | | Return type: | an image(volume) corresponding to the reconstruction at plane(s) d. | Notes Only propagation through media with refractive index 1 is supported. This is a wrapper function for ps_propagate_plane() This function can handle a single reconstruction plane or a volume. Based on the algorithm described in <NAME> and <NAME>, “Point Source Digital In-Line Holographic Microscopy,” Chapter 1 of Coherent Light Microscopy, Springer, 2010. <http://link.springer.com/chapter/10.1007%2F978-3-642-15813-1_1`ps_propagate_plane`(*data*, *d*, *L*, *beam_c*, *out_schema=None*, *old_Ip=False*)[¶](#holopy.propagation.point_source_propagate.ps_propagate_plane) Propagates light back through a hologram that was taken using a diverging reference beam. | Parameters: | * **is a holopy Xarray. It is the hologram to reconstruct. Must be square.** (*data*) – * **pixel spacing must also be square.** (*The*) – * **= distance from pinhole to reconstructed image****,** **in meters** **(****this is z in** (*d*) – * **and Kreuzer****)** **Must be a scalar.** (*Jericho*) – * **= distance from screen to pinhole****,** **in meters** (*L*) – * **=** **[****x****,****y****]** **coodinates of beam center****,** **in pixels** (*beam_c*) – * **= size of output image and pixel spacing****,** **default is the schema** (*out_schema*) – * **data.** (*of*) – * **Ip == True****,** **returns Ip to be used on calculations in the stack** (*if*) – * **Ip == False compute reconstructed image as normal** (*if*) – * **Ip is an image****,** **use this to speed up calculations** (*if*) – | | Returns: | | | Return type: | returns an image(volume) corresponding to the reconstruction at plane(s) d. | Notes Propataion can be to one plane only. Only propagation through media with refractive index 1 is supported. Based on the algorithm described in <NAME> and <NAME>, “Point Source Digital In-Line Holographic Microscopy,” Chapter 1 of Coherent Light Microscopy, Springer, 2010. <http://link.springer.com/chapter/10.1007%2F978-3-642-15813-1_1#### holopy.scattering package[¶](#module-holopy.scattering) Scattering calculations The scattering package provides objects and methods to define scatterer geometries, and theories to compute scattering from specified geometries. Scattering depends on holopy.core, and certain scattering theories may require external scattering codes. The HoloPy scattering module is used to: 1. Describe geometry as a [`scatterer`](index.html#module-holopy.scattering.scatterer) object 2. Define the result you want as a xarray.DataArray xarray.DataArray 3. Calculate scattering quantities with an [`theory`](index.html#module-holopy.scattering.theory) appropriate for your [`scatterer`](index.html#module-holopy.scattering.scatterer) ##### Subpackages[¶](#subpackages) ###### holopy.scattering.scatterer package[¶](#module-holopy.scattering.scatterer) Modules for defining different types of scatterers, including scattering primitives such as Spheres, and more complex objects such as Clusters. ####### Submodules[¶](#module-holopy.scattering.scatterer.bisphere) Defines cylinder scatterers. *class* `Bisphere`(*n=None*, *h=None*, *d=None*, *center=None*, *rotation=(0*, *0*, *0)*)[¶](#holopy.scattering.scatterer.bisphere.Bisphere) Bases: [`holopy.scattering.scatterer.scatterer.CenteredScatterer`](#holopy.scattering.scatterer.scatterer.CenteredScatterer) Scattering object representing bisphere scatterers | Parameters: | * **n** ([*complex*](https://docs.python.org/3/library/functions.html#complex)) – Index of refraction * **h** (*distance between centers*) – * **d** (*diameter*) – * **center** (*3-tuple**,* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *or* *numpy array*) – specifies coordinates of center of the scatterer * **rotation** (*3-tuple**,* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *or* *numpy.array*) – specifies the Euler angles (alpha, beta, gamma) in radians defined in a-dda manual section 8.1 | Defines capsule scatterers. *class* `Capsule`(*n=None*, *h=None*, *d=None*, *center=None*, *rotation=(0*, *0*, *0)*)[¶](#holopy.scattering.scatterer.capsule.Capsule) Bases: [`holopy.scattering.scatterer.scatterer.CenteredScatterer`](#holopy.scattering.scatterer.scatterer.CenteredScatterer) > A cylinder with semi-spherical caps. > A particle with no rotation has its long axis pointing along +z, > specify other orientations by euler angle rotations from that reference. | Parameters: | * **n** ([*complex*](https://docs.python.org/3/library/functions.html#complex)) – Index of refraction * **h** (*height of cylinder*) – * **d** (*diameter*) – * **center** (*3-tuple**,* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *or* *numpy array*) – specifies coordinates of center of the scatterer * **rotation** (*3-tuple**,* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *or* *numpy.array*) – specifies the Euler angles (alpha, beta, gamma) in radians | `indicators`[¶](#holopy.scattering.scatterer.capsule.Capsule.indicators) Defines Scatterers, a scatterer that consists of other scatterers, including scattering primitives (e.g. Sphere) or other Scatterers scatterers (e.g. two trimers). *class* `Scatterers`(*scatterers=None*)[¶](#holopy.scattering.scatterer.composite.Scatterers) Bases: [`holopy.scattering.scatterer.scatterer.Scatterer`](#holopy.scattering.scatterer.scatterer.Scatterer) Contains optical and geometrical properties of a a composite scatterer. A Scatterers can consist of multiple scattering primitives (e.g. Sphere) or other Scatterers scatterers. `scatterers`[¶](#holopy.scattering.scatterer.composite.Scatterers.scatterers) List of scatterers that make up this object | Type: | [list](https://docs.python.org/3/library/stdtypes.html#list) | `parameters [property]` Dictionary of composite’s parameters `add`(*scatterer*)[¶](#holopy.scattering.scatterer.composite.Scatterers.add) Adds a new scatterer to the composite. `from_parameters`()[¶](#holopy.scattering.scatterer.composite.Scatterers.from_parameters) `translated`()[¶](#holopy.scattering.scatterer.composite.Scatterers.translated) `rotated`()[¶](#holopy.scattering.scatterer.composite.Scatterers.rotated) Notes Stores information about components in a tree. This is the most generic container for a collection of scatterers. `add`(*scatterer*) `from_parameters`(*new_parameters*) Makes a new object similar to self with values as given in parameters. This returns a physical object, so any priors are replaced with their guesses if not included in passed-in parameters. | Parameters: | * **parameters** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) – dictionary of parameters to use in the new object. Keys should match those of self.parameters. * **overwrite** ([*bool*](https://docs.python.org/3/library/functions.html#bool) *(**optional**)*) – if True, constant values are replaced by those in parameters | `get_component_list`()[¶](#holopy.scattering.scatterer.composite.Scatterers.get_component_list) `in_domain`(*points*)[¶](#holopy.scattering.scatterer.composite.Scatterers.in_domain) Tell which domain of a scatterer points are in | Parameters: | **points** (*np.ndarray* *(**Nx3**)*) – Point or list of points to evaluate | | Returns: | **domain** – The domain of each point. Domain 0 means not in the particle | | Return type: | np.ndarray (N) | `index_at`(*point*)[¶](#holopy.scattering.scatterer.composite.Scatterers.index_at) `rotated`(*ang1*, *ang2=None*, *ang3=None*) `translated`(*coord1*, *coord2=None*, *coord3=None*) Make a copy of this scatterer translated to a new location | Parameters: | **y****,** **z** (*x**,*) – Value of the translation along each axis | | Returns: | **translated** – A copy of this scatterer translated to a new location | | Return type: | [Scatterer](index.html#holopy.scattering.scatterer.scatterer.Scatterer) | Do Constructive Solid Geometry (CSG) with scatterers. Currently only useful with the DDA th *class* `CsgScatterer`(*s1*, *s2*)[¶](#holopy.scattering.scatterer.csg.CsgScatterer) Bases: [`holopy.scattering.scatterer.scatterer.Scatterer`](#holopy.scattering.scatterer.scatterer.Scatterer) `bounds`[¶](#holopy.scattering.scatterer.csg.CsgScatterer.bounds) `rotated`(*alpha*, *beta*, *gamma*)[¶](#holopy.scattering.scatterer.csg.CsgScatterer.rotated) *class* `Difference`(*s1*, *s2*)[¶](#holopy.scattering.scatterer.csg.Difference) Bases: [`holopy.scattering.scatterer.csg.CsgScatterer`](#holopy.scattering.scatterer.csg.CsgScatterer) `bounds`[¶](#holopy.scattering.scatterer.csg.Difference.bounds) `in_domain`(*points*)[¶](#holopy.scattering.scatterer.csg.Difference.in_domain) Tell which domain of a scatterer points are in | Parameters: | **points** (*np.ndarray* *(**Nx3**)*) – Point or list of points to evaluate | | Returns: | **domain** – The domain of each point. Domain 0 means not in the particle | | Return type: | np.ndarray (N) | *class* `Intersection`(*s1*, *s2*)[¶](#holopy.scattering.scatterer.csg.Intersection) Bases: [`holopy.scattering.scatterer.csg.CsgScatterer`](#holopy.scattering.scatterer.csg.CsgScatterer) `in_domain`(*points*)[¶](#holopy.scattering.scatterer.csg.Intersection.in_domain) Tell which domain of a scatterer points are in | Parameters: | **points** (*np.ndarray* *(**Nx3**)*) – Point or list of points to evaluate | | Returns: | **domain** – The domain of each point. Domain 0 means not in the particle | | Return type: | np.ndarray (N) | *class* `Union`(*s1*, *s2*)[¶](#holopy.scattering.scatterer.csg.Union) Bases: [`holopy.scattering.scatterer.csg.CsgScatterer`](#holopy.scattering.scatterer.csg.CsgScatterer) `in_domain`(*points*)[¶](#holopy.scattering.scatterer.csg.Union.in_domain) Tell which domain of a scatterer points are in | Parameters: | **points** (*np.ndarray* *(**Nx3**)*) – Point or list of points to evaluate | | Returns: | **domain** – The domain of each point. Domain 0 means not in the particle | | Return type: | np.ndarray (N) | Defines cylinder scatterers. *class* `Cylinder`(*n=None*, *h=None*, *d=None*, *center=None*, *rotation=(0*, *0*, *0)*)[¶](#holopy.scattering.scatterer.cylinder.Cylinder) Bases: [`holopy.scattering.scatterer.scatterer.CenteredScatterer`](#holopy.scattering.scatterer.scatterer.CenteredScatterer) Scattering object representing cylinder scatterers | Parameters: | * **n** ([*complex*](https://docs.python.org/3/library/functions.html#complex)) – Index of refraction * **h** (*height of cylinder*) – * **d** (*diameter*) – * **center** (*3-tuple**,* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *or* *numpy array*) – specifies coordinates of center of the scatterer * **rotation** (*3-tuple**,* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *or* *numpy.array*) – specifies the Euler angles (alpha, beta, gamma) in radians defined in a-dda manual section 8.1 | Defines ellipsoidal scatterers. *class* `Ellipsoid`(*n=None*, *r=None*, *center=None*, *rotation=(0*, *0*, *0)*)[¶](#holopy.scattering.scatterer.ellipsoid.Ellipsoid) Bases: [`holopy.scattering.scatterer.scatterer.CenteredScatterer`](#holopy.scattering.scatterer.scatterer.CenteredScatterer) Scattering object representing ellipsoidal scatterers | Parameters: | * **n** ([*complex*](https://docs.python.org/3/library/functions.html#complex)) – Index of refraction * **r** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* *(*[*float*](https://docs.python.org/3/library/functions.html#float)*,* [*float*](https://docs.python.org/3/library/functions.html#float)*,* [*float*](https://docs.python.org/3/library/functions.html#float)*)*) – x, y, z semi-axes of the ellipsoid * **center** (*3-tuple**,* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *or* *numpy array*) – specifies coordinates of center of the scatterer * **rotation** (*3-tuple**,* [*list*](https://docs.python.org/3/library/stdtypes.html#list) *or* *numpy.array*) – specifies the Euler angles (alpha, beta, gamma) in radians defined in a-dda manual section 8.1 | `indicators`[¶](#holopy.scattering.scatterer.ellipsoid.Ellipsoid.indicators) Ellipsoid indicators does not currently apply rotations | Type: | NOTE | Defines two types of Janus (two faced) Spheres as scattering primitives. *class* `JanusSphere_Tapered`(*n=None*, *r=None*, *rotation=(0*, *0)*, *center=None*)[¶](#holopy.scattering.scatterer.janus.JanusSphere_Tapered) Bases: [`holopy.scattering.scatterer.scatterer.CenteredScatterer`](#holopy.scattering.scatterer.scatterer.CenteredScatterer) `indicators`[¶](#holopy.scattering.scatterer.janus.JanusSphere_Tapered.indicators) *class* `JanusSphere_Uniform`(*n=None*, *r=None*, *rotation=(0*, *0*, *0)*, *center=None*)[¶](#holopy.scattering.scatterer.janus.JanusSphere_Uniform) Bases: [`holopy.scattering.scatterer.scatterer.CenteredScatterer`](#holopy.scattering.scatterer.scatterer.CenteredScatterer) `indicators`[¶](#holopy.scattering.scatterer.janus.JanusSphere_Uniform.indicators) The abstract base class for all scattering objects *class* `CenteredScatterer`(*center=None*)[¶](#holopy.scattering.scatterer.scatterer.CenteredScatterer) Bases: [`holopy.scattering.scatterer.scatterer.Scatterer`](#holopy.scattering.scatterer.scatterer.Scatterer) *class* `Indicators`(*functions*, *bound=None*)[¶](#holopy.scattering.scatterer.scatterer.Indicators) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) Class holding functions describing a scatterer One or more functions (one per domain) that take Nx3 arrays of points and return a boolean array of membership in each domain. More than one indicator is allowed to return true for a given point, in that case the point is considered a member of the first domain with a true value. *class* `Scatterer`(*indicators*, *n*, *center*)[¶](#holopy.scattering.scatterer.scatterer.Scatterer) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) Base class for scatterers `bounds`[¶](#holopy.scattering.scatterer.scatterer.Scatterer.bounds) `contains`(*points*)[¶](#holopy.scattering.scatterer.scatterer.Scatterer.contains) `from_parameters`(*parameters*)[¶](#holopy.scattering.scatterer.scatterer.Scatterer.from_parameters) Create a Scatterer from a dictionary of parameters | Parameters: | **parameters** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) – Parameters for a scatterer. This should be of the form returned by Scatterer.parameters. | | Returns: | **scatterer** – A scatterer with the given parameter values | | Return type: | Scatterer class | `in_domain`(*points*)[¶](#holopy.scattering.scatterer.scatterer.Scatterer.in_domain) Tell which domain of a scatterer points are in | Parameters: | **points** (*np.ndarray* *(**Nx3**)*) – Point or list of points to evaluate | | Returns: | **domain** – The domain of each point. Domain 0 means not in the particle | | Return type: | np.ndarray (N) | `index_at`(*points*, *background=0*)[¶](#holopy.scattering.scatterer.scatterer.Scatterer.index_at) `num_domains`[¶](#holopy.scattering.scatterer.scatterer.Scatterer.num_domains) `parameters`[¶](#holopy.scattering.scatterer.scatterer.Scatterer.parameters) Get a dictionary of this scatterer’s parameters | Parameters: | **None** – | | Returns: | **parameters** – A dictionary of this scatterer’s parameters. This dict can be passed to Scatterer.from_parameters to make a copy of this scatterer | | Return type: | [dict](https://docs.python.org/3/library/stdtypes.html#dict) | `translated`(*coord1*, *coord2=None*, *coord3=None*)[¶](#holopy.scattering.scatterer.scatterer.Scatterer.translated) Make a copy of this scatterer translated to a new location | Parameters: | **y****,** **z** (*x**,*) – Value of the translation along each axis | | Returns: | **translated** – A copy of this scatterer translated to a new location | | Return type: | [Scatterer](index.html#holopy.scattering.scatterer.scatterer.Scatterer) | `voxelate`(*spacing*, *medium_index=0*)[¶](#holopy.scattering.scatterer.scatterer.Scatterer.voxelate) Represent a scatterer by discretizing into voxels | Parameters: | * **spacing** ([*float*](https://docs.python.org/3/library/functions.html#float)) – The spacing between voxels in the returned voxelation * **medium_index** ([*float*](https://docs.python.org/3/library/functions.html#float)) – The background index of refraction to fill in at regions where the scatterer is not present | | Returns: | **voxelation** – An array with refractive index at every pixel | | Return type: | np.ndarray | `voxelate_domains`(*spacing*)[¶](#holopy.scattering.scatterer.scatterer.Scatterer.voxelate_domains) `x`[¶](#holopy.scattering.scatterer.scatterer.Scatterer.x) `y`[¶](#holopy.scattering.scatterer.scatterer.Scatterer.y) `z`[¶](#holopy.scattering.scatterer.scatterer.Scatterer.z) `bound_union`(*d1*, *d2*)[¶](#holopy.scattering.scatterer.scatterer.bound_union) `find_bounds`(*indicator*)[¶](#holopy.scattering.scatterer.scatterer.find_bounds) Finds the bounds needed to contain an indicator function Notes Will probably determine incorrect bounds for functions which are not convex Defines Sphere, a scattering primitive *class* `LayeredSphere`(*n=None*, *t=None*, *center=None*)[¶](#holopy.scattering.scatterer.sphere.LayeredSphere) Bases: [`holopy.scattering.scatterer.sphere.Sphere`](#holopy.scattering.scatterer.sphere.Sphere) Alternative description of a sphere where you specify layer thicknesses instead of radii `n`[¶](#holopy.scattering.scatterer.sphere.LayeredSphere.n) Index of each each layer | Type: | list of complex | `t`[¶](#holopy.scattering.scatterer.sphere.LayeredSphere.t) Thickness of each layer | Type: | list of float | `center`[¶](#holopy.scattering.scatterer.sphere.LayeredSphere.center) specifies coordinates of center of sphere | Type: | length 3 listlike | `r`[¶](#holopy.scattering.scatterer.sphere.LayeredSphere.r) *class* `Sphere`(*n=None*, *r=0.5*, *center=None*)[¶](#holopy.scattering.scatterer.sphere.Sphere) Bases: [`holopy.scattering.scatterer.scatterer.CenteredScatterer`](#holopy.scattering.scatterer.scatterer.CenteredScatterer) Contains optical and geometrical properties of a sphere, a scattering primitive. This can be a multiple layered sphere by making r and n lists. `n`[¶](#holopy.scattering.scatterer.sphere.Sphere.n) index of refraction of each layer of the sphere | Type: | [complex](https://docs.python.org/3/library/functions.html#complex) or list of complex | `r`[¶](#holopy.scattering.scatterer.sphere.Sphere.r) radius of the sphere or outer radius of each sphere. | Type: | [float](https://docs.python.org/3/library/functions.html#float) or list of float | `center`[¶](#holopy.scattering.scatterer.sphere.Sphere.center) specifies coordinates of center of sphere | Type: | length 3 listlike | `indicators`[¶](#holopy.scattering.scatterer.sphere.Sphere.indicators) `num_domains`[¶](#holopy.scattering.scatterer.sphere.Sphere.num_domains) `rotated`(*alpha*, *beta*, *gamma*)[¶](#holopy.scattering.scatterer.sphere.Sphere.rotated) Defines Spheres, a Scatterers scatterer consisting of Spheres *class* `RigidCluster`(*spheres*, *translation=(0*, *0*, *0)*, *rotation=(0*, *0*, *0)*)[¶](#holopy.scattering.scatterer.spherecluster.RigidCluster) Bases: [`holopy.scattering.scatterer.spherecluster.Spheres`](#holopy.scattering.scatterer.spherecluster.Spheres) `from_parameters`(*parameters*)[¶](#holopy.scattering.scatterer.spherecluster.RigidCluster.from_parameters) Makes a new object similar to self with values as given in parameters. This returns a physical object, so any priors are replaced with their guesses if not included in passed-in parameters. | Parameters: | * **parameters** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) – dictionary of parameters to use in the new object. Keys should match those of self.parameters. * **overwrite** ([*bool*](https://docs.python.org/3/library/functions.html#bool) *(**optional**)*) – if True, constant values are replaced by those in parameters | `scatterers`[¶](#holopy.scattering.scatterer.spherecluster.RigidCluster.scatterers) *class* `Spheres`(*scatterers*, *warn=True*)[¶](#holopy.scattering.scatterer.spherecluster.Spheres) Bases: [`holopy.scattering.scatterer.composite.Scatterers`](#holopy.scattering.scatterer.composite.Scatterers) Contains optical and geometrical properties of a cluster of spheres. `spheres`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.spheres) Spheres which will make up the cluster | Type: | list of Spheres | `warn`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.warn) if True, overlapping spheres raise warnings. | Type: | [bool](https://docs.python.org/3/library/functions.html#bool) | Notes `add`(*scatterer*)[¶](#holopy.scattering.scatterer.spherecluster.Spheres.add) `center`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.center) `centers`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.centers) `largest_overlap`()[¶](#holopy.scattering.scatterer.spherecluster.Spheres.largest_overlap) `n`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.n) `n_imag`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.n_imag) `n_real`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.n_real) `overlaps`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.overlaps) `r`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.r) `x`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.x) `y`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.y) `z`[¶](#holopy.scattering.scatterer.spherecluster.Spheres.z) Defines spheroidal scatterers. *class* `Spheroid`(*n=None*, *r=None*, *rotation=(0*, *0*, *0)*, *center=None*)[¶](#holopy.scattering.scatterer.spheroid.Spheroid) Bases: [`holopy.scattering.scatterer.scatterer.CenteredScatterer`](#holopy.scattering.scatterer.scatterer.CenteredScatterer) Scattering object representing spheroidal scatterers `n`[¶](#holopy.scattering.scatterer.spheroid.Spheroid.n) Index of refraction | Type: | [complex](https://docs.python.org/3/library/functions.html#complex) | `r`[¶](#holopy.scattering.scatterer.spheroid.Spheroid.r) length of xy and z semi-axes of the spheroid | Type: | ([float](https://docs.python.org/3/library/functions.html#float), [float](https://docs.python.org/3/library/functions.html#float)) | `rotation`[¶](#holopy.scattering.scatterer.spheroid.Spheroid.rotation) specifies the Euler angles (alpha, beta, gamma) in radians | Type: | 3-tuple, [list](https://docs.python.org/3/library/stdtypes.html#list) or numpy array | `center`[¶](#holopy.scattering.scatterer.spheroid.Spheroid.center) specifies coordinates of center of the scatterer | Type: | 3-tuple, [list](https://docs.python.org/3/library/stdtypes.html#list) or numpy array | `indicators`[¶](#holopy.scattering.scatterer.spheroid.Spheroid.indicators) ###### holopy.scattering.theory package[¶](#module-holopy.scattering.theory) Theories to compute scattering from objects. All theories have a common interface defined by [`holopy.scattering.theory.scatteringtheory.ScatteringTheory`](#holopy.scattering.theory.scatteringtheory.ScatteringTheory). ####### Subpackages[¶](#subpackages) ######## holopy.scattering.theory.mie_f package[¶](#module-holopy.scattering.theory.mie_f) Fortran extension module for calculating cluster holograms using tmatrix scattering theory. ######### Submodules[¶](#module-holopy.scattering.theory.mie_f.mie_specfuncs) Compute special functions needed for the computation of scattering coefficients in the Lorenz-Mie scattering solution and related problems such as layered spheres. These functions are not to be used for calculations at each field point. Rather, they should be used once for the calculation of scattering coefficients, which then get passed to faster Fortran code for field calculations. Papers referenced herein: <NAME>, <NAME>, and <NAME>, “Internal absorption cross sections in a stratified sphere,” Applied Optics 29, 1551-1559, (1990). Yang, “Improved recursive algorithm for light scattering by a multilayered sphere,” Applied Optics 42, 1710-1720, (1993). `Qratio`(*z1*, *z2*, *nstop*, *dns1=None*, *dns2=None*, *eps1=0.001*, *eps2=1e-16*)[¶](#holopy.scattering.theory.mie_f.mie_specfuncs.Qratio) Calculate ratio of Riccati-Bessel functions defined in [[Yang2003]](index.html#yang2003) eq. 23 by up recursion. Notes Logarithmic derivatives calculated automatically if not specified. Lentz continued fraction algorithm used to start downward recursion for logarithmic derivatives. `R_psi`(*z1*, *z2*, *nmax*, *eps1=0.001*, *eps2=1e-16*)[¶](#holopy.scattering.theory.mie_f.mie_specfuncs.R_psi) Calculate ratio of Riccati-Bessel function psi: psi(z1)/psi(z2). Notes See [[Mackowski1990]](index.html#mackowski1990) eqns. 65-66. Uses Lentz continued fraction algorithm for logarithmic derivatives. `log_der_1`(*z*, *nmx*, *nstop*)[¶](#holopy.scattering.theory.mie_f.mie_specfuncs.log_der_1) Computes logarithmic derivative of Riccati-Bessel function psi_n(z) by downward recursion as in BHMIE. | Parameters: | * **z** (*complex argument*) – * **nmx** (*order from which downward recursion begins.*) – * **nstop** (*integer**,* *maximum order*) – | Notes psi_n(z) is related to the spherical Bessel function j_n(z). Consider implementing Lentz’s continued fraction method. `log_der_13`(*z*, *nstop*, *eps1=0.001*, *eps2=1e-16*)[¶](#holopy.scattering.theory.mie_f.mie_specfuncs.log_der_13) Calculate logarithmic derivatives of Riccati-Bessel functions psi and xi for complex arguments. Riccati-Bessel conventions follow Bohren & Huffman. See Mackowski et al., Applied Optics 29, 1555 (1990). | Parameters: | * **z** (*complex number*) – * **nstop** (*maximum order of computation*) – * **eps1** (*underflow criterion for Lentz continued fraction for Dn1*) – * **eps2** (*convergence criterion for Lentz continued fraction for Dn1*) – | `riccati_psi_xi`(*x*, *nstop*)[¶](#holopy.scattering.theory.mie_f.mie_specfuncs.riccati_psi_xi) Calculate Riccati-Bessel functions psi and xi for real argument. | Parameters: | * **x** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Argument * **nstop** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Maximum order to calculate to | | Returns: | psi and xi | | Return type: | ndarray(2, nstop) | Notes Uses upwards recursion. MieScatLib.py Library of code to do Mie scattering calculations. `asymmetry_parameter`(*al*, *bl*)[¶](#holopy.scattering.theory.mie_f.miescatlib.asymmetry_parameter) Calculate asymmetry parameter of scattered field. | Parameters: | **bn** (*an**,*) – coefficient arrays from Mie solution | | Returns: | | | Return type: | [float](https://docs.python.org/3/library/functions.html#float) | Notes See discussion on Bohren & Huffman p. 120. The output of this function omits the prefactor of 4/(x^2 Q_sca). `cross_sections`(*al*, *bl*)[¶](#holopy.scattering.theory.mie_f.miescatlib.cross_sections) Calculates scattering and extinction cross sections given arrays of Mie scattering coefficients an and bn. | Parameters: | **bn** (*an**,*) – coefficient arrays from Mie solution | | Returns: | Scattering, extinction, and radar backscattering cross sections | | Return type: | ndarray(3) | Notes See Bohren & Huffman eqns. 4.61 and 4.62. The output omits a scaling prefactor of 2 * pi / k^2. `internal_coeffs`(*m*, *x*, *n_max*, *eps1=0.001*, *eps2=1e-16*)[¶](#holopy.scattering.theory.mie_f.miescatlib.internal_coeffs) Calculate internal Mie coefficients c_n and d_n given relative index, size parameter, and maximum order of expansion. | Parameters: | **docstring for scatcoeffs** (*See*) – | | Returns: | Internal coefficients c_n and d_n | | Return type: | ndarray(2,n) [complex](https://docs.python.org/3/library/functions.html#complex) | Notes Follow Bohren & Huffman’s convention. Note that <NAME> and Kerker have different conventions (labeling of c_n and d_n and factors of m) for their internal coefficients. `nstop`(*x*)[¶](#holopy.scattering.theory.mie_f.miescatlib.nstop) Calculate maximum expansion order of Lorenz-Mie solution. | Parameters: | **x** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Particle size parameter | | Returns: | **nstop** | | Return type: | [int](https://docs.python.org/3/library/functions.html#int) | Notes Criterion taken from [[Wiscombe1980]](index.html#wiscombe1980). `scatcoeffs`(*m*, *x*, *nstop*, *eps1=0.001*, *eps2=1e-16*)[¶](#holopy.scattering.theory.mie_f.miescatlib.scatcoeffs) Calculate expansion coefficients for scattered field in Lorenz-Mie solution. | Parameters: | * **m** ([*complex*](https://docs.python.org/3/library/functions.html#complex)) – Sphere relative refractive index (n_sphere / n_medium) * **x** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Sphere size parameter (k_med * a) * **nstop** ([*int*](https://docs.python.org/3/library/functions.html#int)) – Maximum order of scattered field expansion * **eps1** ([*float*](https://docs.python.org/3/library/functions.html#float)*,* *optional*) – In Lentz continued fraction algorithm for logarithmic derivative D_n(z), value of continued fraction numerator or denominator triggering ill-conditioning workaround. * **eps2** ([*float*](https://docs.python.org/3/library/functions.html#float)*,* *optional*) – Convergence criterion for Lentz continued fraction algorithm | | Returns: | Scattering coefficients a_n and b_n | | Return type: | array(2, nstop), [complex](https://docs.python.org/3/library/functions.html#complex) | Notes Uses formula for scattering coefficients based on logarithmic derivative D_n(z) of spherical Bessel function psi_n(z). See [[Bohren1983]](index.html#bohren1983) eq. 4.88. Following BHMIE, calculates D_n for complex argument using downward recursion, and Riccati-Bessel functions psi and xi for real argument using upward recursion. Initializes downward recursion for D_n using Lentz continued fraction algorithm [[Lentz1976]](index.html#lentz1976). multilayer_sphere_lib.py Author: <NAME> ([<EMAIL>](mailto:fung%40physics.harvard.edu)) Functions to calculate the scattering from a spherically symmetric particle with an arbitrary number of layers with different refractive indices. Key reference for multilayer algorithm: Yang, “Improved recursive algorithm for light scattering by a multilayered sphere,” Applied Optics 42, 1710-1720, (1993). `scatcoeffs_multi`(*marray*, *xarray*, *eps1=0.001*, *eps2=1e-16*)[¶](#holopy.scattering.theory.mie_f.multilayer_sphere_lib.scatcoeffs_multi) Calculate scattered field expansion coefficients (in the Mie formalism) for a particle with an arbitrary number of spherically symmetric layers. | Parameters: | * **marray** (*array_like**,* *complex128*) – array of layer indices, innermost first * **xarray** (*array_like**,* *real*) – array of layer size parameters (k * outer radius), innermost first * **eps1** ([*float*](https://docs.python.org/3/library/functions.html#float)*,* *optional*) – underflow criterion for Lentz continued fraction for Dn1 * **eps2** ([*float*](https://docs.python.org/3/library/functions.html#float)*,* *optional*) – convergence criterion for Lentz continued fraction for Dn1 | | Returns: | **scat_coeffs** – Scattering coefficients | | Return type: | ndarray ([complex](https://docs.python.org/3/library/functions.html#complex)) | Extensions for T-Matrix scattering calculations (in fortran77 and fortran90); numpy.distutils should automatically use f2py to compile these, and f2py should detect your fortran compiler. The code works with gcc, but has not been tested with other compilers. Note that f2py by default compiles with optimization flags. Ignore compiler warnings of unused variables, unused dummy arguments, and variables being used uninitialized from compiling scsmfo_min. The former is relics of how scsmfo was written which I am not touching. The latter is likely due to some GOTO statements that could cause a variable to be referenced before it’s initialized. Under normal usage I wouldn’t worry about it. `configuration`(*parent_package=''*, *top_path=None*)[¶](#holopy.scattering.theory.mie_f.setup.configuration) ######## holopy.scattering.theory.tmatrix_f package[¶](#module-holopy.scattering.theory.tmatrix_f) ######### Submodules[¶](#module-holopy.scattering.theory.tmatrix_f.setup) `configuration`(*parent_package=''*, *top_path=None*)[¶](#holopy.scattering.theory.tmatrix_f.setup.configuration) ####### Submodules[¶](#module-holopy.scattering.theory.dda) Compute holograms using the discrete dipole approximation (DDA). Currently uses ADDA (<https://github.com/adda-team/adda>) to do DDA calculations. .. moduleauthor:: <NAME> <[<EMAIL>](mailto:tdimiduk%40physics.harvard.edu)*class* `DDA`(*n_cpu=1*, *use_gpu=False*, *gpu_id=None*, *max_dpl_size=None*, *use_indicators=True*, *keep_raw_calculations=False*, *addacmd=[]*, *suppress_C_output=True*)[¶](#holopy.scattering.theory.dda.DDA) Bases: [`holopy.scattering.theory.scatteringtheory.ScatteringTheory`](#holopy.scattering.theory.scatteringtheory.ScatteringTheory) Computes scattering using the the Discrete Dipole Approximation (DDA). It can (in principle) calculate scattering from any arbitrary scatterer. The DDA uses a numerical method that represents arbitrary scatterers as an array of point dipoles and then self-consistently solves Maxwell’s equations to determine the scattered field. In practice, this model can be extremely computationally intensive, particularly if the size of the scatterer is larger than the wavelength of light. This model requires an external scattering code: [a-dda](http://code.google.com/p/a-dda/) `n_cpu`[¶](#holopy.scattering.theory.dda.DDA.n_cpu) Number of threads to use for the DDA calculation | Type: | [int](https://docs.python.org/3/library/functions.html#int) (optional) | `max_dpl_size`[¶](#holopy.scattering.theory.dda.DDA.max_dpl_size) Force a maximum dipole size. This is useful for forcing extra dipoles if necessary to resolve features in an object. This may make dda calculations take much longer. | Type: | [float](https://docs.python.org/3/library/functions.html#float) (optional) | `use_indicators`[¶](#holopy.scattering.theory.dda.DDA.use_indicators) If true, a scatterer’s indicators method will be used instead of its built-in adda definition | Type: | [bool](https://docs.python.org/3/library/functions.html#bool) | `keep_raw_calculations`[¶](#holopy.scattering.theory.dda.DDA.keep_raw_calculations) If true, do not delete the temporary file we run ADDA in, instead print its path so you can inspect its raw results | Type: | [bool](https://docs.python.org/3/library/functions.html#bool) | Notes Does not handle near fields. This introduces ~5% error at 10 microns. This can in principle handle any scatterer, but in practice it will need excessive memory or computation time for particularly large scatterers. *classmethod* `can_handle`(*scatterer*)[¶](#holopy.scattering.theory.dda.DDA.can_handle) Given a scatterer, returns a bool `raw_scat_matrs`(*scatterer*, *pos*, *medium_wavevec*, *medium_index*)[¶](#holopy.scattering.theory.dda.DDA.raw_scat_matrs) Given a (3, N) array pos etc, returns an (N, 2, 2) array `required_spacing`(*bounds*, *medium_wavelen*, *medium_index*, *n*)[¶](#holopy.scattering.theory.dda.DDA.required_spacing) *class* `Lens`(*lens_angle*, *theory*, *quad_npts_theta=100*, *quad_npts_phi=100*, *use_numexpr=True*)[¶](#holopy.scattering.theory.lens.Lens) Bases: [`holopy.scattering.theory.scatteringtheory.ScatteringTheory`](#holopy.scattering.theory.scatteringtheory.ScatteringTheory) Wraps a ScatteringTheory and overrides the raw_fields to include the effect of an objective lens. `can_handle`(*scatterer*)[¶](#holopy.scattering.theory.lens.Lens.can_handle) Given a scatterer, returns a bool `desired_coordinate_system` *= 'cylindrical'*[¶](#holopy.scattering.theory.lens.Lens.desired_coordinate_system) `numexpr_integrand_prefactor1` *= 'exp(1j * krho_p * sintheta * cos(phi_relative))'*[¶](#holopy.scattering.theory.lens.Lens.numexpr_integrand_prefactor1) `numexpr_integrand_prefactor2` *= 'exp(1j * kz_p * (1 - costheta))'*[¶](#holopy.scattering.theory.lens.Lens.numexpr_integrand_prefactor2) `numexpr_integrand_prefactor3` *= 'sqrt(costheta) * sintheta * phi_wts * theta_wts'*[¶](#holopy.scattering.theory.lens.Lens.numexpr_integrand_prefactor3) `numexpr_integrandl` *= 'prefactor * (cosphi * (cosphi * S2 + sinphi * S3) + sinphi * (cosphi * S4 + sinphi * S1))'*[¶](#holopy.scattering.theory.lens.Lens.numexpr_integrandl) `numexpr_integrandr` *= 'prefactor * (sinphi * (cosphi * S2 + sinphi * S3) - cosphi * (cosphi * S4 + sinphi * S1))'*[¶](#holopy.scattering.theory.lens.Lens.numexpr_integrandr) `parameter_names` *= ('lens_angle',)*[¶](#holopy.scattering.theory.lens.Lens.parameter_names) `raw_fields`(*positions*, *scatterer*, *medium_wavevec*, *medium_index*, *illum_polarization*)[¶](#holopy.scattering.theory.lens.Lens.raw_fields) Given a (3, N) array pos, etc, returns a (3, N) array `gauss_legendre_pts_wts`(*a*, *b*, *npts=100*)[¶](#holopy.scattering.theory.lens.gauss_legendre_pts_wts) Quadrature points for integration on interval [a, b] `pts_wts_for_phi_integrals`(*npts*)[¶](#holopy.scattering.theory.lens.pts_wts_for_phi_integrals) Quadrature points for integration on the periodic interval [0, pi] Since this interval is periodic, we use equally-spaced points with equal weights. Calculates holograms of spheres using Fortran implementation of Mie theory. Uses superposition to calculate scattering from multiple spheres. Uses full radial dependence of spherical Hankel functions for scattered field. *class* `Mie`(*compute_escat_radial=True*, *full_radial_dependence=True*, *eps1=0.01*, *eps2=1e-16*)[¶](#holopy.scattering.theory.mie.Mie) Bases: [`holopy.scattering.theory.scatteringtheory.ScatteringTheory`](#holopy.scattering.theory.scatteringtheory.ScatteringTheory) Compute scattering using the Lorenz-Mie solution. This theory calculates exact scattering for single spheres and approximate results for groups of spheres. It does not account for multiple scattering, hence the approximation in the case of multiple spheres. Neglecting multiple scattering is a good approximation if the particles are sufficiently separated. This model can also calculate the exact scattered field from a spherically symmetric particle with an arbitrary number of layers with differing refractive indices, using Yang’s recursive algorithm ([[Yang2003]](index.html#yang2003)). By default, calculates radial component of scattered electric fields, which is nonradiative. Currently, in calculating the Lorenz-Mie scattering coefficients, the maximum size parameter x = ka is limited to 1000. `can_handle`(*scatterer*)[¶](#holopy.scattering.theory.mie.Mie.can_handle) Given a scatterer, returns a bool `raw_cross_sections`(*scatterer*, *medium_wavevec*, *medium_index*, *illum_polarization*)[¶](#holopy.scattering.theory.mie.Mie.raw_cross_sections) Calculate scattering, absorption, and extinction cross sections, and asymmetry parameter for spherically symmetric scatterers. | Parameters: | **scatterer** (`scatterpy.scatterer` object) – spherically symmetric scatterer to compute for (Calculation would need to be implemented in a radically different way, via numerical quadrature, for sphere clusters) | | Returns: | **cross_sections** – Dimensional scattering, absorption, and extinction cross sections, and <cos heta> | | Return type: | array (4) | Notes The radiation pressure cross section C_pr is given by C_pr = C_ext - <cos heta> C_sca. The radiation pressure force on a sphere is F = (n_med I_0 C_pr) / c where I_0 is the incident intensity. See van de Hulst, p. 14. `raw_fields`(*positions*, *scatterer*, *medium_wavevec*, *medium_index*, *illum_polarization*)[¶](#holopy.scattering.theory.mie.Mie.raw_fields) Given a (3, N) array pos, etc, returns a (3, N) array `raw_scat_matrs`(*scatterer*, *pos*, *medium_wavevec*, *medium_index*)[¶](#holopy.scattering.theory.mie.Mie.raw_scat_matrs) Returns far-field amplitude scattering matrices (with theta and phi dependence only) – assume spherical wave asymptotic r dependence *class* `AberratedMieLens`(*spherical_aberration=0.0*, *lens_angle=1.0*, *calculator_accuracy_kwargs={}*)[¶](#holopy.scattering.theory.mielens.AberratedMieLens) Bases: [`holopy.scattering.theory.mielens.MieLens`](#holopy.scattering.theory.mielens.MieLens) `parameter_names` *= ('lens_angle', 'spherical_aberration')*[¶](#holopy.scattering.theory.mielens.AberratedMieLens.parameter_names) *class* `MieLens`(*lens_angle=1.0*, *calculator_accuracy_kwargs={}*)[¶](#holopy.scattering.theory.mielens.MieLens) Bases: [`holopy.scattering.theory.scatteringtheory.ScatteringTheory`](#holopy.scattering.theory.scatteringtheory.ScatteringTheory) Exact scattering from a sphere imaged through a perfect lens. Calculates holograms of spheres using an analytical solution of the Mie scattered field imaged by a perfect lens (see [[Leahy2020]](index.html#leahy2020)). Can use superposition to calculate scattering from multiple spheres. See also `mielensfunctions.MieLensCalculator` `can_handle`(*scatterer*)[¶](#holopy.scattering.theory.mielens.MieLens.can_handle) Given a scatterer, returns a bool `desired_coordinate_system` *= 'cylindrical'*[¶](#holopy.scattering.theory.mielens.MieLens.desired_coordinate_system) `parameter_names` *= ('lens_angle',)*[¶](#holopy.scattering.theory.mielens.MieLens.parameter_names) `raw_fields`(*positions*, *scatterer*, *medium_wavevec*, *medium_index*, *illum_polarization*)[¶](#holopy.scattering.theory.mielens.MieLens.raw_fields) | Parameters: | * **positions** (*(**3**,* *N**)* *numpy.ndarray*) – The (k * rho, phi, z) coordinates, relative to the sphere, of the points to calculate the fields. Note that the radial coordinate is rescaled by the wavevector. * **scatterer** (`scatterer.Sphere` object) – * **medium_wavevec** ([*float*](https://docs.python.org/3/library/functions.html#float)) – * **medium_index** ([*float*](https://docs.python.org/3/library/functions.html#float)) – * **illum_polarization** (*2-element tuple*) – The (x, y) field polarizations. | *class* `AberratedMieLensCalculator`(*spherical_aberration=None*, ***kwargs*)[¶](#holopy.scattering.theory.mielensfunctions.AberratedMieLensCalculator) Bases: [`holopy.scattering.theory.mielensfunctions.MieLensCalculator`](#holopy.scattering.theory.mielensfunctions.MieLensCalculator) `must_be_specified` *= ['particle_kz', 'index_ratio', 'size_parameter', 'lens_angle', 'spherical_aberration']*[¶](#holopy.scattering.theory.mielensfunctions.AberratedMieLensCalculator.must_be_specified) *class* `AlBlFunctions`[¶](#holopy.scattering.theory.mielensfunctions.AlBlFunctions) Bases: [`object`](https://docs.python.org/3/library/functions.html#object) > Group of functions for calculating the Mie scattering coefficients, > used for expressing the scattered field in terms of vector spherical > harmonics. > The coefficients a_l, b_l are defined as > ..math: > ``` > a_l = > ``` rac{psi_l(x) psi_l’(nx) - n psi_l(nx) psi_l’(x)} > {xi_l(x) psi_l’(nx) - n psi_l(nx) xi_l’(x)}, b_l = rac{psi_l(nx) psi_l’(x) - n psi_l(x) psi_l’(nx)} > {psi_l(nx) xi_l’(x) - n xi_l(x) psi_l’(nx)}, where \(\psi_l\) and \(\xi_l\) are the Riccati-Bessel functions of the first and third kinds, respectively. The definitions used here follow those of van de Hulst [[1]_](#id13), which differ from those used in Bohren and Huffman [[2]_](#id14). | [1] | <NAME>, “Light Scattering by Small Particles”, Dover (1981), pg 123. | | [2] | <NAME> and <NAME>, “Absorption and Scattering of Light by Small Particles”, Wiley (2004), pg 101. | *static* `calculate_al_bl`(*index_ratio*, *size_parameter*, *l*)[¶](#holopy.scattering.theory.mielensfunctions.AlBlFunctions.calculate_al_bl) Returns a_l and b_l; see class docstring. | Parameters: | * **index_ratio** ([*float*](https://docs.python.org/3/library/functions.html#float)) – relative index of refraction * **size_paramter** ([*float*](https://docs.python.org/3/library/functions.html#float)) – Size parameter * **l** ([*int*](https://docs.python.org/3/library/functions.html#int)*,* *array-like*) – Order of scattering coefficient | | Returns: | **a_l, b_l** | | Return type: | numpy.ndarray | *static* `riccati_psin`(*n*, *z*, *derivative=False*)[¶](#holopy.scattering.theory.mielensfunctions.AlBlFunctions.riccati_psin) Riccati-Bessel function of the first kind or its derivative. \[\psi_n(z) = z\,j_n(z),\] where \(j_n(z)\) is the spherical Bessel function of the first kind. Parameters n : int, array_like Order of the Bessel function (n >= 0). z : complex or float, array_like Argument of the Bessel function. derivative : bool, optional If True, the value of the derivative (rather than the function itself) is returned. | Returns: | **psin** | | Return type: | ndarray | *static* `riccati_xin`(*order*, *z*, *derivative=False*)[¶](#holopy.scattering.theory.mielensfunctions.AlBlFunctions.riccati_xin) Riccati-Bessel function of the third kind or its derivative. \[\xi_n(z) = z\,h^{(1)}_n(z),\] where \(h^{(1)}_n(z)\) is the first spherical Hankel function. | Parameters: | * **n** ([*int*](https://docs.python.org/3/library/functions.html#int)*,* *array_like*) – Order of the Bessel function (n >= 0). * **z** ([*complex*](https://docs.python.org/3/library/functions.html#complex) *or* [*float*](https://docs.python.org/3/library/functions.html#float)*,* *array_like*) – Argument of the Bessel function. * **derivative** ([*bool*](https://docs.python.org/3/library/functions.html#bool)*,* *optional*) – If True, the value of the derivative (rather than the function itself) is returned. | | Returns: | **xin** | | Return type: | ndarray | *class* `MieLensCalculator`(*particle_kz=None*, *index_ratio=None*, *size_parameter=None*, *lens_angle=None*, *quad_npts=100*, *interpolate_integrals='check'*, *interpolator_window_size=30.0*, *interpolator_degree=32*)[¶](#holopy.scattering.theory.mielensfunctions.MieLensCalculator) Bases: [`object`](https://docs.python.org/3/library/functions.html#object) `calculate_incident_field`()[¶](#holopy.scattering.theory.mielensfunctions.MieLensCalculator.calculate_incident_field) This is here so (i) Any corrections in the theory to the scattered field > have an easy place to enter, and 2. Other modules can consistently use the same scattered field as this module. `calculate_scattered_field`(*krho*, *phi*)[¶](#holopy.scattering.theory.mielensfunctions.MieLensCalculator.calculate_scattered_field) Calculates the field from a Mie scatterer imaged through a high-NA lens and excited with an electric field of unit strength directed along the optical axis. > \[\] ec{E}_{sc} = A left[ I_{12} sin(2phi) hat{y} + -I_{10} hat{x} + I_{12} cos(2phi) hat{x} + -I_{20} hat{x} + -I_{22} cos(2phi) hat{x} + -I_{22} sin(2phi) hat{y} ight] > krho, phi : numpy.ndarray > The position of the particle relative to the focal point of the > lens, in (i) cylindrical coordinates and (ii) dimensionless > wavevectur units. Must all be the same shape. > field_xcomp, field_ycomp : numpy.ndarray > The (x, y) components of the electric field at the detector, where > the initial field is polarized in the x-direction. Same shape as > krho, phi > This will have problems for large rho, z, because of the quadrature > points. Empirically this problem happens for rho >~ 4 * quad_npts. > Could be adaptive if needed…. `calculate_total_field`(*krho*, *phi*)[¶](#holopy.scattering.theory.mielensfunctions.MieLensCalculator.calculate_total_field) The total (incident + scattered) field at the detector `calculate_total_intensity`(*krho*, *phi*)[¶](#holopy.scattering.theory.mielensfunctions.MieLensCalculator.calculate_total_intensity) `must_be_specified` *= ['particle_kz', 'index_ratio', 'size_parameter', 'lens_angle']*[¶](#holopy.scattering.theory.mielensfunctions.MieLensCalculator.must_be_specified) *class* `MieScatteringMatrix`(*parallel_or_perpendicular='perpendicular'*, *index_ratio=None*, *size_parameter=None*, *max_l=None*)[¶](#holopy.scattering.theory.mielensfunctions.MieScatteringMatrix) Bases: [`object`](https://docs.python.org/3/library/functions.html#object) *class* `PiecewiseChebyshevApproximant`(*function*, *degree*, *window_breakpoints*, **args*)[¶](#holopy.scattering.theory.mielensfunctions.PiecewiseChebyshevApproximant) Bases: [`object`](https://docs.python.org/3/library/functions.html#object) `calculate_al_bl`(*index_ratio*, *size_parameter*, *l*)[¶](#holopy.scattering.theory.mielensfunctions.calculate_al_bl) `calculate_pil_taul`(*theta*, *max_order*)[¶](#holopy.scattering.theory.mielensfunctions.calculate_pil_taul) > The 1st through Nth order angle dependent functions for Mie scattering, > evaluated at theta. The functions :math`pi( heta)` and :math` au( heta) > are defined as: > ..math: > ``` > \pi_n( heta) = > ``` rac{1}{sin heta} P_n^1(cos heta) > au_n( heta) = rac{mathrm{d}}{mathrm{d} heta} P_n^1(cos heta) > where \(P_n^m\) is the associated Legendre function. The functions are > computed by upward recurrence using the relations > ..math: > ``` > \pi_n = > ``` rac{2n-1}{n-1}cos heta , pi_{n-1} - rac{n}{n-1}pi_{n-2} > > > au_n = n , cos heta , pi_n - (n+1)pi_{n-1} > beginning with \(pi_0 = 0\) and \(pi_1 = 1\) > theta : array_like > angles (in radians) at which to evaluate the angular functions > max_order : int > 0 > Order at which to halt iteration. Must be > 0 > pi, tau : ndarray > 2D arrays with shape (len(theta), max_order) containing the > values of the angular functions evaluated at theta up to order > max_order `gauss_legendre_pts_wts`(*a*, *b*, *npts=100*)[¶](#holopy.scattering.theory.mielensfunctions.gauss_legendre_pts_wts) Quadrature points for integration on interval [a, b] `j2`(*x*)[¶](#holopy.scattering.theory.mielensfunctions.j2) A fast J_2(x) defined in terms of other special functions `spherical_h1n`(*n*, *z*, *derivative=False*)[¶](#holopy.scattering.theory.mielensfunctions.spherical_h1n) Spherical Hankel function H_n(z) or its derivative `spherical_h2n`(*n*, *z*, *derivative=False*)[¶](#holopy.scattering.theory.mielensfunctions.spherical_h2n) Spherical Hankel function H_n(z) or its derivative Defines Multisphere theory class, which calculates scattering for multiple spheres using the (exact) superposition method implemented in modified version of Daniel Mackowski’s SCSMFO1B.FOR. Uses full radial dependence of spherical Hankel functions for the scattered field. *class* `Multisphere`(*niter=200*, *eps=1e-06*, *meth=1*, *qeps1=1e-05*, *qeps2=1e-08*, *compute_escat_radial=False*, *suppress_fortran_output=True*)[¶](#holopy.scattering.theory.multisphere.Multisphere) Bases: [`holopy.scattering.theory.scatteringtheory.ScatteringTheory`](#holopy.scattering.theory.scatteringtheory.ScatteringTheory) Exact scattering from a cluster of spheres. Calculate the scattered field of a collection of spheres through a numerical method that accounts for multiple scattering and near-field effects (see [[Fung2011]](index.html#fung2011), [[Mackowski1996]](index.html#mackowski1996)). This approach is much more accurate than Mie superposition, but it is also more computationally intensive. The Multisphere code can handle any number of spheres; see notes below for details. `niter`[¶](#holopy.scattering.theory.multisphere.Multisphere.niter) maximum number of iterations to use in solving the interaction equations | Type: | integer (optional) | `meth`[¶](#holopy.scattering.theory.multisphere.Multisphere.meth) method to use to solve interaction equations. Set to 0 for biconjugate gradient; 1 for order-of-scattering | Type: | integer (optional) | `eps`[¶](#holopy.scattering.theory.multisphere.Multisphere.eps) relative error tolerance in solution for interaction equations | Type: | [float](https://docs.python.org/3/library/functions.html#float) (optional) | `qeps1`[¶](#holopy.scattering.theory.multisphere.Multisphere.qeps1) error tolerance used to determine at what order the single-sphere spherical harmonic expansion should be truncated | Type: | [float](https://docs.python.org/3/library/functions.html#float) (optional) | `qeps2`[¶](#holopy.scattering.theory.multisphere.Multisphere.qeps2) error tolerance used to determine at what order the cluster spherical harmonic expansion should be truncated | Type: | [float](https://docs.python.org/3/library/functions.html#float) (optional) | Notes According to Mackowski’s manual for SCSMFO1B.FOR [[1]_](#id15) and later papers [[2]_](#id16), the biconjugate gradient is generally the most efficient method for solving the interaction equations, especially for dense arrays of identical spheres. Order-of-scattering may converge better for non-identical spheres. Multisphere does not check for overlaps becaue overlapping spheres can be useful for getting fits to converge. The results to be sensible for small overlaps even though mathemtically speaking they are not xstrictly valid. Currently, Multisphere does not calculate the radial component of scattered electric fields. This is a good approximation for large kr, since the radial component falls off as 1/kr^2. scfodim.for contains three parameters, all integers: * nod: Maximum number of spheres * nod: Maximum order of individual sphere expansions. Will depend on size of largest sphere in cluster. * notd: Maximum order of cluster-centered expansion. Will depend on overall size of cluster. Changing these values will require recompiling Fortran extensions. The maximum size parameter of each individual sphere in a cluster is currently limited to 1000, indepdently of the above scfodim.for parameters. References | [1] | <NAME>, SCSMFO.FOR: Calculation of the Scattering Properties for a Cluster of Spheres, <ftp://ftp.eng.auburn.edu/pub/dmckwski/scatcodes/scsmfo.ps> | | [2] | <NAME>, <NAME>, A multiple sphere T-matrix Fortran code for use on parallel computer clusters, Journal of Quantitative Spectroscopy and Radiative Transfer, In Press, Corrected Proof, Available online 11 March 2011, ISSN 0022-4073, DOI: 10.1016/j.jqsrt.2011.02.019. | `can_handle`(*scatterer*)[¶](#holopy.scattering.theory.multisphere.Multisphere.can_handle) Given a scatterer, returns a bool `raw_cross_sections`(*scatterer*, *medium_wavevec*, *medium_index*, *illum_polarization*)[¶](#holopy.scattering.theory.multisphere.Multisphere.raw_cross_sections) Calculate scattering, absorption, and extinction cross sections, and asymmetry parameter for sphere clusters with polarized incident light. The extinction cross section is calculated from the optical theorem. The scattering cross section is calculated by numerical quadrature of the scattered field, and the absorption cross section is calculated from the difference of the extinction cross section and the scattering cross section. | Parameters: | **scatterer** (`scatterpy.scatterer` object) – sphere cluster to compute for | | Returns: | **cross_sections** – Dimensional scattering, absorption, and extinction cross sections, and <cos heta> | | Return type: | array (4) | `raw_fields`(*positions*, *scatterer*, *medium_wavevec*, *medium_index*, *illum_polarization*)[¶](#holopy.scattering.theory.multisphere.Multisphere.raw_fields) Given a (3, N) array pos, etc, returns a (3, N) array `raw_scat_matrs`(*scatterer*, *pos*, *medium_wavevec*, *medium_index*)[¶](#holopy.scattering.theory.multisphere.Multisphere.raw_scat_matrs) Calculate far-field amplitude scattering matrices at multiple positions `normalize_polarization`(*illum_polarization*)[¶](#holopy.scattering.theory.multisphere.normalize_polarization) *class* `ScatteringTheory`[¶](#holopy.scattering.theory.scatteringtheory.ScatteringTheory) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) Defines common interface for all scattering theories. Subclasses must implement: * can_handle * raw_fields or raw_scat_matrs or both. * (optionally) raw_cross_sections, Notes Subclasses should implement the following methods to create a scatteringtheory that works for the following user-facing methods: * calc_holo: raw_fields or raw_scat_matrs * calc_intensity: raw_fields or raw_scat_matrs * calc_field: raw_fields or raw_scat_matrs * calc_scat_matrix: raw_scat_matrs * calc_cross_sections: raw_cross_sections By default, ScatteringTheories computer raw_fields from the raw_scat_matrs; over-ride the raw_fields method to compute the fields in a different way. `can_handle`(*scatterer*)[¶](#holopy.scattering.theory.scatteringtheory.ScatteringTheory.can_handle) Given a scatterer, returns a bool `desired_coordinate_system` *= 'spherical'*[¶](#holopy.scattering.theory.scatteringtheory.ScatteringTheory.desired_coordinate_system) `from_parameters`(*parameters*)[¶](#holopy.scattering.theory.scatteringtheory.ScatteringTheory.from_parameters) Creates a ScatteringTheory like the current one, but with different parameters. Used for fitting | Parameters: | **dict** – keys should be valid self.parameter_names fields, values should be the corresponding kwargs | | Returns: | | | Return type: | ScatteringTheory instance, of the same class as self | `parameter_names` *= ()*[¶](#holopy.scattering.theory.scatteringtheory.ScatteringTheory.parameter_names) `parameters`[¶](#holopy.scattering.theory.scatteringtheory.ScatteringTheory.parameters) `raw_cross_sections`(*scatterer*, *medium_wavevec*, *medium_index*, *illum_polarization*)[¶](#holopy.scattering.theory.scatteringtheory.ScatteringTheory.raw_cross_sections) Returns cross-sections, as an array [cscat, cabs, cext, asym] `raw_fields`(*pos*, *scatterer*, *medium_wavevec*, *medium_index*, *illum_polarization*)[¶](#holopy.scattering.theory.scatteringtheory.ScatteringTheory.raw_fields) Given a (3, N) array pos, etc, returns a (3, N) array `raw_scat_matrs`(*scatterer*, *pos*, *medium_wavevec*, *medium_index*)[¶](#holopy.scattering.theory.scatteringtheory.ScatteringTheory.raw_scat_matrs) Given a (3, N) array pos etc, returns an (N, 2, 2) array Compute holograms using Mishchenko’s T-matrix method for axisymmetric scatterers. Currently uses *class* `Tmatrix`[¶](#holopy.scattering.theory.tmatrix.Tmatrix) Bases: [`holopy.scattering.theory.scatteringtheory.ScatteringTheory`](#holopy.scattering.theory.scatteringtheory.ScatteringTheory) Computes scattering using the axisymmetric T-matrix solution by Mishchenko with extended precision. It can calculate scattering from axisymmetric scatterers such as cylinders and spheroids. Calculations for particles that are very large or have high aspect ratios may not converge. Notes Does not handle near fields. This introduces ~5% error at 10 microns. `can_handle`(*scatterer*)[¶](#holopy.scattering.theory.tmatrix.Tmatrix.can_handle) Given a scatterer, returns a bool `raw_fields`(*pos*, *scatterer*, *medium_wavevec*, *medium_index*, *illum_polarization*)[¶](#holopy.scattering.theory.tmatrix.Tmatrix.raw_fields) Given a (3, N) array pos, etc, returns a (3, N) array `raw_scat_matrs`(*scatterer*, *pos*, *medium_wavevec*, *medium_index*)[¶](#holopy.scattering.theory.tmatrix.Tmatrix.raw_scat_matrs) Given a (3, N) array pos etc, returns an (N, 2, 2) array ##### Submodules[¶](#module-holopy.scattering.errors) Exceptions used in scatterpy module. These are separated out from the other exceptions in other parts of HoloPy to keep things modular. *exception* `AutoTheoryFailed`(*scatterer*)[¶](#holopy.scattering.errors.AutoTheoryFailed) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `InvalidScatterer`(*scatterer*, *message*)[¶](#holopy.scattering.errors.InvalidScatterer) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `MissingParameter`(*parameter_name*)[¶](#holopy.scattering.errors.MissingParameter) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `MultisphereFailure`[¶](#holopy.scattering.errors.MultisphereFailure) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `OverlapWarning`(*scatterer*, *overlaps*)[¶](#holopy.scattering.errors.OverlapWarning) Bases: [`UserWarning`](https://docs.python.org/3/library/exceptions.html#UserWarning) *exception* `ParameterSpecificationError`[¶](#holopy.scattering.errors.ParameterSpecificationError) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `TheoryNotCompatibleError`(*theory*, *scatterer*, *reason=None*)[¶](#holopy.scattering.errors.TheoryNotCompatibleError) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *exception* `TmatrixFailure`(*logfilestr*)[¶](#holopy.scattering.errors.TmatrixFailure) Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) *class* `ImageFormation`(*scattering_theory*)[¶](#holopy.scattering.imageformation.ImageFormation) Bases: [`holopy.core.holopy_object.HoloPyObject`](index.html#holopy.core.holopy_object.HoloPyObject) Calculates fields, holograms, intensities, etc. `calculate_cross_sections`(*scatterer*, *medium_wavevec*, *medium_index*, *illum_polarization*)[¶](#holopy.scattering.imageformation.ImageFormation.calculate_cross_sections) `calculate_scattered_field`(*scatterer*, *schema*)[¶](#holopy.scattering.imageformation.ImageFormation.calculate_scattered_field) | Parameters: | **scatterer** ([`scatterer`](index.html#module-holopy.scattering.scatterer) object) – (possibly composite) scatterer for which to compute scattering | | Returns: | **e_field** – scattered electric field | | Return type: | `VectorGrid` | `calculate_scattering_matrix`(*scatterer*, *schema*)[¶](#holopy.scattering.imageformation.ImageFormation.calculate_scattering_matrix) Compute scattering matrices for scatterer | Parameters: | **scatterer** ([`holopy.scattering.scatterer`](index.html#module-holopy.scattering.scatterer) object) – (possibly composite) scatterer for which to compute scattering | | Returns: | **scat_matr** – Scattering matrices at specified positions | | Return type: | `Marray` | `get_wavevec_from`(*schema*)[¶](#holopy.scattering.imageformation.get_wavevec_from) `select_scatterer_by_illumination`(*scatterer*, *illum*)[¶](#holopy.scattering.imageformation.select_scatterer_by_illumination) Base class for scattering theories. Implements python-based calc_intensity and calc_holo, based on subclass’s calc_field `calc_cross_sections`(*scatterer*, *medium_index=None*, *illum_wavelen=None*, *illum_polarization=None*, *theory='auto'*)[¶](#holopy.scattering.interface.calc_cross_sections) Calculate scattering, absorption, and extinction cross sections, and asymmetry parameter <cos heta>. | Parameters: | * **scatterer** (`scatterer` object) – (possibly composite) scatterer for which to compute scattering * **medium_index** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* [*complex*](https://docs.python.org/3/library/functions.html#complex)) – Refractive index of the medium in which the scatter is imbedded * **illum_wavelen** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* *ndarray**(*[*float*](https://docs.python.org/3/library/functions.html#float)*)*) – Wavelength of illumination light. If illum_wavelen is an array result will add a dimension and have all wavelengths * **theory** (`theory` object (optional)) – Scattering theory object to use for the calculation. This is optional if there is a clear choice of theory for your scatterer. If there is not a clear choice, calc_cross_sections will error out and ask you to specify a theory | | Returns: | **cross_sections** – Dimensional scattering, absorption, and extinction cross sections, and <cos theta> | | Return type: | array (4) | `calc_field`(*detector*, *scatterer*, *medium_index=None*, *illum_wavelen=None*, *illum_polarization=None*, *theory='auto'*)[¶](#holopy.scattering.interface.calc_field) Calculate the scattered fields from a scatterer illuminated by a reference wave. | Parameters: | * **detector** (*xarray object*) – The detector points and calculation metadata used to calculate the scattered fields. * **scatterer** (`scatterer` object) – (possibly composite) scatterer for which to compute scattering * **medium_index** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* [*complex*](https://docs.python.org/3/library/functions.html#complex)) – Refractive index of the medium in which the scatter is imbedded * **illum_wavelen** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* *ndarray**(*[*float*](https://docs.python.org/3/library/functions.html#float)*)*) – Wavelength of illumination light. If illum_wavelen is an array result will add a dimension and have all wavelengths * **theory** (`theory` object (optional)) – Scattering theory object to use for the calculation. This is optional if there is a clear choice of theory for your scatterer. If there is not a clear choice, calc_field will error out and ask you to specify a theory | | Returns: | **e_field** – Calculated hologram from the given distribution of spheres | | Return type: | `Vector` object | `calc_holo`(*detector*, *scatterer*, *medium_index=None*, *illum_wavelen=None*, *illum_polarization=None*, *theory='auto'*, *scaling=1.0*)[¶](#holopy.scattering.interface.calc_holo) Calculate hologram formed by interference between scattered fields and a reference wave | Parameters: | * **detector** (*xarray object*) – The detector points and calculation metadata used to calculate the hologram. * **scatterer** (`scatterer` object) – (possibly composite) scatterer for which to compute scattering * **medium_index** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* [*complex*](https://docs.python.org/3/library/functions.html#complex)) – Refractive index of the medium in which the scatter is imbedded * **illum_wavelen** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* *ndarray**(*[*float*](https://docs.python.org/3/library/functions.html#float)*)*) – Wavelength of illumination light. If illum_wavelen is an array result will add a dimension and have all wavelengths * **theory** (`theory` object (optional)) – Scattering theory object to use for the calculation. This is optional if there is a clear choice of theory for your scatterer. If there is not a clear choice, calc_holo will error out and ask you to specify a theory * **scaling** (*scaling value* *(**alpha**)* *for amplitude of reference wave*) – | | Returns: | **holo** – Calculated hologram from the given distribution of spheres | | Return type: | xarray.DataArray | `calc_intensity`(*detector*, *scatterer*, *medium_index=None*, *illum_wavelen=None*, *illum_polarization=None*, *theory='auto'*)[¶](#holopy.scattering.interface.calc_intensity) Calculate intensity from the scattered field at a set of locations | Parameters: | * **detector** (*xarray object*) – The detector points and calculation metadata used to calculate the intensity. * **scatterer** (`scatterer` object) – (possibly composite) scatterer for which to compute scattering * **medium_index** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* [*complex*](https://docs.python.org/3/library/functions.html#complex)) – Refractive index of the medium in which the scatter is imbedded * **illum_wavelen** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* *ndarray**(*[*float*](https://docs.python.org/3/library/functions.html#float)*)*) – Wavelength of illumination light. If illum_wavelen is an array result will add a dimension and have all wavelengths * **theory** (`theory` object (optional)) – Scattering theory object to use for the calculation. This is optional if there is a clear choice of theory for your scatterer. If there is not a clear choice, calc_intensity will error out and ask you to specify a theory | | Returns: | **inten** – scattered intensity | | Return type: | xarray.DataArray | `calc_scat_matrix`(*detector*, *scatterer*, *medium_index=None*, *illum_wavelen=None*, *theory='auto'*)[¶](#holopy.scattering.interface.calc_scat_matrix) Compute farfield scattering matrices for scatterer | Parameters: | * **detector** (*xarray object*) – The detector points and calculation metadata used to calculate the scattering matrices. * **scatterer** ([`holopy.scattering.scatterer`](index.html#module-holopy.scattering.scatterer) object) – (possibly composite) scatterer for which to compute scattering * **medium_index** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* [*complex*](https://docs.python.org/3/library/functions.html#complex)) – Refractive index of the medium in which the scatter is imbedded * **illum_wavelen** ([*float*](https://docs.python.org/3/library/functions.html#float) *or* *ndarray**(*[*float*](https://docs.python.org/3/library/functions.html#float)*)*) – Wavelength of illumination light. If illum_wavelen is an array result will add a dimension and have all wavelengths * **theory** (`theory` object (optional)) – Scattering theory object to use for the calculation. This is optional if there is a clear choice of theory for your scatterer. If there is not a clear choice, calc_scat_matrix will error out and ask you to specify a theory | | Returns: | **scat_matr** – Scattering matrices at specified positions | | Return type: | `Marray` | `determine_default_theory_for`(*scatterer*)[¶](#holopy.scattering.interface.determine_default_theory_for) `finalize`(*detector*, *result*)[¶](#holopy.scattering.interface.finalize) `interpret_theory`(*scatterer*, *theory='auto'*)[¶](#holopy.scattering.interface.interpret_theory) `prep_schema`(*detector*, *medium_index*, *illum_wavelen*, *illum_polarization*)[¶](#holopy.scattering.interface.prep_schema) `scattered_field_to_hologram`(*scat*, *ref*)[¶](#holopy.scattering.interface.scattered_field_to_hologram) Calculate a hologram from an E-field | Parameters: | * **scat** (`VectorGrid`) – The scattered (object) field * **ref** (*xarray**[**vector**]**]*) – The reference field | `validate_scatterer`(*scatterer*)[¶](#holopy.scattering.interface.validate_scatterer) References and credits[¶](#references-and-credits) --- The following references describe applications of HoloPy and technical advances. If you use HoloPy, we ask that you cite the articles that are relevant to your application. | [Dimiduk2016] | Dimiduk, <NAME>., and <NAME>. “Bayesian Approach to Analyzing Holograms of Colloidal Particles.” Optics Express 24, no. 21 (October 17, 2016): 24045–60. doi:10.1364/OE.24.024045. | | [Wang2016] | Wang, Anna, <NAME>, and <NAME>. “Tracking E. Coli Runs and Tumbles with Scattering Solutions and Digital Holographic Microscopy.” Optics Express 24, no. 21 (October 17, 2016): 23719–25. doi:10.1364/OE.24.023719. | | [Dimiduk2014] | Dimiduk, <NAME>., <NAME>, <NAME>, and <NAME>. “Random-Subset Fitting of Digital Holograms for Fast Three-Dimensional Particle Tracking.” Applied Optics 53, no. 27 (September 20, 2014): G177–83. doi:10.1364/AO.53.00G177. | | [Wang2014] | Wang, Anna, <NAME>. Dimiduk, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. “Using the Discrete Dipole Approximation and Holographic Microscopy to Measure Rotational Dynamics of Non-Spherical Colloidal Particles.” Journal of Quantitative Spectroscopy and Radiative Transfer 146 (October 2014): 499–509. doi:10.1016/j.jqsrt.2013.12.019. | | [Fung2013] | Fung, Jerome, and <NAME>. “Holographic Measurements of Anisotropic Three-Dimensional Diffusion of Colloidal Clusters.” Physical Review E 88, no. 2 (August 30, 2013): 020302. doi:10.1103/PhysRevE.88.020302. | | [Fung2012] | <NAME>, <NAME>, <NAME>, and <NAME>. “Imaging Multiple Colloidal Particles by Fitting Electromagnetic Scattering Solutions to Digital Holograms.” Journal of Quantitative Spectroscopy and Radiative Transfer 113, no. 18 (December 2012): 2482–89. doi:10.1016/j.jqsrt.2012.06.007. | | [Kaz2012] | Kaz, <NAME>., <NAME>, <NAME>, <NAME>, and <NAME>. “Physical Ageing of the Contact Line on Colloidal Particles at Liquid Interfaces.” Nature Materials 11, no. 2 (February 2012): 138–42. doi:10.1038/nmat3190. | | [Perry2012] | Perry, <NAME>., <NAME>, <NAME>, <NAME>, and <NAME>. “Real-Space Studies of the Structure and Dynamics of Self-Assembled Colloidal Clusters.” Faraday Discussions 159, no. 1 (June 7, 2012): 211–34. doi:10.1039/C2FD20061A. | | [Fung2011] | <NAME>, K. <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. “Measuring Translational, Rotational, and Vibrational Dynamics in Colloids with Digital Holographic Microscopy.” Optics Express 19, no. 9 (April 25, 2011): 8051–65. doi:10.1364/OE.19.008051. | | [Leahy2020] | <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. “Large depth-of-field tracking of colloidal spheres in holographic microscopy by modeling the objective lens.” Optics Express 28, no. 2 (2020): 1061-1075. doi:10.1364/OE.382159 | Ovryn and Izen and Lee and coworkers were the first to develop methods to fit scattering models to digital holograms: | [Ovryn2000] | Ovryn, Ben, and <NAME>. “Imaging of Transparent Spheres through a Planar Interface Using a High-Numerical-Aperture Optical Microscope.” Journal of the Optical Society of America A 17, no. 7 (July 1, 2000): 1202–13. doi:10.1364/JOSAA.17.001202. | | [Lee2007] | Lee, Sang-Hyuk, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. “Characterizing and Tracking Single Colloidal Particles with Video Holographic Microscopy.” Optics Express 15, no. 26 (December 24, 2007): 18275–82. doi:10.1364/OE.15.018275. | The following papers describe different methods for calculating scattering and various algorithms that HoloPy uses in its calculations: | [Yurkin2011] | <NAME>., and <NAME>. “The Discrete-Dipole-Approximation Code ADDA: Capabilities and Known Limitations.” Journal of Quantitative Spectroscopy and Radiative Transfer 112, no. 13 (September 2011): 2234–47. doi:10.1016/j.jqsrt.2011.01.031. | | [Mackowski1990] | <NAME>., <NAME>., and <NAME>. “Internal absorption cross sections in a stratified sphere.” Applied Optics 29, no. 10 (1990). do:10.1364/AO.29.001551. | | [Mackowski1996] | Mackowski, <NAME>., and <NAME>. “Calculation of the T Matrix and the Scattering Matrix for Ensembles of Spheres.” Journal of the Optical Society of America A 13, no. 11 (November 1, 1996): 2266. doi:10.1364/JOSAA.13.002266. | | [Wiscombe1996] | <NAME>. “Mie Scattering Calculations: Advances in Technique and Fast, Vector-Speed Computer Codes,” 1979. doi:10.5065/D6ZP4414. | | [Wiscombe1980] | <NAME>. “Improved Mie scattering algorithms.” Applied Optics 19, no. 9 (May 1, 1980): 1505. doi:10.1364/AO.19.001505. | | [Yang2003] | <NAME>. “Improved Recursive Algorithm for Light Scattering by a Multilayered Sphere.” Applied Optics 42, no. 9 (March 20, 2003): 1710–20. doi:10.1364/AO.42.001710. | | [Lentz1976] | <NAME>. “Generating Bessel Functions in Mie Scattering Calculations Using Continued Fractions.” Applied Optics 15, no. 3 (March 1, 1976): 668–71. doi:10.1364/AO.15.000668. | For scattering calculations and formalism, we draw heavily on the treatise of Bohren & Huffman. We generally follow their conventions except where noted. | [Bohren1983] | <NAME> and <NAME>, *Absorption and Scattering of Light by Small Particles*, Wiley (1983). | For an introduction to Bayesian analysis of experimental data, we recommend | [Gregory2010] | <NAME>, *Bayesian Logical Data Analysis for the Physical Sciences*, Cambridge University Press (2010) | The package includes code from several sources. We thank <NAME> for allowing us to include his T-Matrix code, which computes scattering from clusters of spheres: [SCSMFO1B](ftp://ftp.eng.auburn.edu/pub/dmckwski/scatcodes/index.html). We also make use of a modified version of the Python version of [mpfit](http://www.physics.wisc.edu/~craigm/idl/fitting.html), originally developed by <NAME>. The modified version we use is drawn from the [stsci_python](http://www.stsci.edu/resources/software_hardware/pyraf/stsci_python) package. We thank <NAME> for permitting us to use his routine [SBESJY.FOR](http://www.fresco.org.uk/programs/barnett/index.htm), which computes spherical Bessel functions. HoloPy is based upon work supported by the National Science Foundation under grant numbers CBET-0747625, DMR-0820484, DMR-1306410, and DMR-1420570.
diffee
cran
R
Package ‘diffee’ October 13, 2022 Version 1.1.0 Date 2018-07-03 Title Fast and Scalable Learning of Sparse Changes in High-Dimensional Gaussian Graphical Model Structure Author <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] Maintainer <NAME> <<EMAIL>> Depends R (>= 3.0.0), igraph, pcaPP Description This is an R implementation of Fast and Scalable Learning of Sparse Changes in High- Dimensional Gaussian Graphical Model Structure (DIFFEE). The DIFFEE algo- rithm can be used to fast estimate the differential network between two related datasets. For in- stance, it can identify differential gene network from datasets of case and control. By perform- ing data-driven network inference from two high-dimensional data sets, this tool can help users ef- fectively translate two aggregated data blocks into knowledge of the changes among entities be- tween two Gaussian Graphical Model. Please run demo(diffeeDemo) to learn the basic func- tions provided by this package. For further details, please read the original pa- per: <NAME>, <NAME>, <NAME> (2018) <arXiv:1710.11223>. License GPL-2 URL https://github.com/QData/DIFFEE BugReports https://github.com/QData/DIFFEE RoxygenNote 6.0.1 NeedsCompilation no Repository CRAN Date/Publication 2018-07-03 19:50:03 UTC R topics documented: diffee-packag... 2 cance... 3 diffe... 4 exampleDat... 5 exampleData50... 6 exampleDataGrap... 6 nip_37_dat... 7 plot.diffe... 7 returngrap... 9 diffee-package estimating DIFFerential networks via an Elementary Estimator under a high-dimensional situation Description This is an R implementation of Fast and Scalable Learning of Sparse Changes in High-Dimensional Gaussian Graphical Model Structure (DIFFEE). The DIFFEE algorithm can be used to fast estimate the differetial network between two related datasets. For instance, it can identify differential gene network from datasets of case and control. By performing data-driven network inference from two high-dimensional data sets, this tool can help users effectively translate two aggregated data blocks into knowledge of the changes among entities between two Gaussian Graphical Model. Please run demo(diffeeDemo) to learn the basic functions provided by this package. For further details, please read the original paper: <NAME>, <NAME>, <NAME> (2018) <arXiv:1710.11223>. Details Package: diffee Type: Package Version: 1.0.0 Date: 2018-03-05 License: GPL (>= 2) We focus on the problem of estimating the change in the dependency structures of two p-dimensional Gaussian Graphical models (GGMs). Previous studies for sparse change estimation in GGMs in- volve expensive and difficult non-smooth optimization. We propose a novel method, DIFFEE for estimating DIFFerential networks via an Elementary Estimator under a high-dimensional situation. DIFFEE is solved through a faster and closed form solution that enables it to work in large-scale settings. We conduct a rigorous statistical analysis showing that surprisingly DIFFEE achieves the same asymptotic convergence rates as the state-of-the-art estimators that are much more difficult to compute. Our experimental results on multiple synthetic datasets and one real-world data about brain connectivity show strong performance improvements over baselines, as well as significant computational benefits. Author(s) <NAME>, <NAME> Maintainer: <NAME> - bw4mw at virginia dot edu References <NAME>, <NAME>, <NAME> (2018). Fast and Scalable Learning of Sparse Changes in High-Dimensional Gaussian Graphical Model Structure. <arXiv:1710.11223> Examples ## Not run: data(exampleData) result = diffee(exampleData[[1]], exampleData[[2]], 0.45) plot.diffee(result) ## End(Not run) cancer Microarray data set for breast cancer Description et al’s paper. It concerns one hundred thirty-three patients with stage I–III breast cancer. Patients were treated with chemotherapy prior to surgery. Patient response to the treatment can be classified as either a pathologic complete response (pCR) or residual disease (not-pCR). Hess et al developed and tested a reliable multigene predictor for treatment response on this data set, composed by a set of 26 genes having a high predictive value. Usage data(cancer) Format a list of two objects: dataframe with 133 observations of 26 features and factors indicating whether each sample (out of 133) is of type "not" or type "pcr" Details The dataset splits into 2 parts (pCR and not pCR), on which network inference algorithms should be applied independently or in the multitask framework: only individuals from the same classes should be consider as independent and identically distributed. References <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> (2006). Pharmacogenomic predictor of sensitivity to preoperative chemotherapy with Paclitaxel and Fluorouracil, Doxorubicin, and Cy- clophosphamide in breast cancer, Journal of Clinical Oncology, vol. 24(26), pp. 4236–4244. diffee Fast and Scalable Learning of Sparse Changes in High-Dimensional Gaussian Graphical Model Structure Description Estimate DIFFerential networks via an Elementary Estimator under a high-dimensional situation. Please run demo(diffee) to learn the basic functions provided by this package. For further details, please read the original paper: Beil<NAME>, <NAME>, <NAME> (2018) <arXiv:1710.11223>. Usage diffee(C, D, lambda = 0.05, covType = "cov", thre = "soft") Arguments C A input matrix for the ’control’ group. It can be data matrix or covariance ma- trix. If C is a symmetric matrix, the matrices are assumed to be covariance matrix. More details at <https://github.com/QData/DIFFEE> D A input matrix for the ’disease’ group. It can be data matrix or covariance ma- trix. If D is a symmetric matrix, the matrices are assumed to be covariance matrix. More details at <https://github.com/QData/DIFFEE> lambda A positive number. The hyperparameter controls the sparsity level of the matri- ces. The λn in the following section: Details. covType A parameter to decide which Graphical model we choose to estimate from the input data. If covType = "cov", it means that we estimate multiple sparse Gaussian Graph- ical models. This option assumes that we calculate (when input X represents data directly) or use (when X elements are symmetric representing covariance matrices) the sample covariance matrices as input to the simule algorithm. If covType = "kendall", it means that we estimate multiple nonparanormal Graph- ical models. This option assumes that we calculate (when input X represents data directly) or use (when X elements are symmetric representing correlation matrices) the kendall’s tau correlation matrices as input to the simule algorithm. thre A parameter to decide which threshold function to use for Tv . If thre = "soft", it means that we choose soft-threshold function as Tv . If thre = "hard", it means that we choose hard-threshold function as Tv . Details The DIFFEE algorithm is a fast and scalable Learning algorithm of Sparse Changes in High- Dimensional Gaussian Graphical Model Structure. It solves the following equation: ∆ Subject to : ([Tv (Σ̂d )]−1 − [Tv (Σ̂c )]−1 )||∞ ≤ λn Please also see the equation (2.11) in our paper. The λn is the hyperparameter controlling the sparsity level of the matrix and it is the lambda in our function. For further details, please see our paper: <NAME>, <NAME>, <NAME> (2018) <arXiv:1710.11223>. Value diffNet A matrix of the estimated sparse changes between two Gaussian Graphical Mod- els Author(s) <NAME> References <NAME>, <NAME>, <NAME> (2018). Fast and Scalable Learning of Sparse Changes in High-Dimensional Gaussian Graphical Model Structure. <arXiv:1710.11223> Examples ## Not run: data(exampleData) result = diffee(exampleData[[1]], exampleData[[2]], 0.45) plot.diffee(result) ## End(Not run) exampleData A simulated toy dataset that includes 2 data matrices (from 2 related tasks). Description A simulated toy dataset that includes 2 data matrices (from 2 related tasks). Each data matrix is about 100 features observed in 200 samples. The two data matrices are about exactly the same set of 100 features. This multi-task dataset is generated from two related random graphs. Please run demo(diffee) to learn the basic functions provided by this package. For further details, please read the original paper: <http://link.springer.com/article/10.1007/s10994-017-5635-7>. Usage data(exampleData) Format The format is: List of 2 matrices $ : num [1:200, 1:100] -0.0982 -0.2417 -1.704 0.4 ... ..- attr(*, "dimnames")=List of 2 .. ..$ : NULL .. ..$ : NULL $ : num [1:200, 1:100] -0.161 0.41 0.17 0. ... ..- attr(*, "dimnames")=List of 2 .. ..$ : NULL .. ..$ : NULL exampleData500 A simulated toy dataset that includes 2 data matrices (from 2 related tasks). Description A simulated toy dataset that includes 2 data matrices (from 2 related tasks). Each data matrix is about 500 features observed in 1000 samples. The two data matrices are about exactly the same set of 500 features. This multi-task dataset is generated from two related random graphs. Please run demo(diffee) to learn the basic functions provided by this package. For further details, please read the original paper: <http://link.springer.com/article/10.1007/s10994-017-5635-7>. Usage data(exampleData500) Format A list of 2 matrices of size [1:500, 1:500] and [1:500, 1:500] exampleDataGraph A simulated toy dataset that includes 3 igraph objects Description (first one being the shared graph and second and third being task specific 1 and 2 graphs) The graphs are generated from two related random graphs and the underlaying high dimensional gaussian dis- tribution generates the exampleData dataset. exampleDataGraph serves as a groundtruth to compare in demo(synthetic). Usage data(exampleDataGraph) Format A list of 3 igraph objects nip_37_data NIPS word count dataset Description This NIPS Conference Papers 1987-2015 Data set is avaiable at UCI Machine Learning Repository. The original dataset is in the form of a 11463 x 5812 matrix of word counts (11463 words and 5812 conference papers) Due to the size of the original dataset, it is preprocessed and reduced to a list of two matrices (2900 x 37 and 2911 x 37) The dataset consists of two tasks (early (up to 2006) and recent (after 2006) NIPS conference papers) with 37 words Usage data(nip_37_data) Format a list of two nonnegative integer matrices (1:2900, 1:37) and (1:2911,1:37) Columns are named with year_paperid and rows are names with word name References ’Poisson Random Fields for Dynamic Feature Models’. <NAME>., <NAME>., <NAME>., <NAME>. W. (2016) plot.diffee Plot diffee result specified by user input Description This function can plot and return multiple sparse graphs distinguished by edge colors from the result generated by diffee Usage ## S3 method for class 'diffee' plot(x, graphlabel = NULL, type = "task", index = NULL, graphlayout = NULL, ...) Arguments x output generated from diffee function (diffee class) graphlabel vertex names for the graph, there are three options: (1) NA (no label) (2) NULL (default numeric label according to the feature order) (3) a vector of labels (a vector of labels cooresponding to x) deault value is NULL type type of graph, there are four options: (1) "task" (graph for each task (including shared part) specified further by subID (task number)) (2) "neighbour" (zoom into nodes in the graph specified further by index (node id)) index determines which node(s) to zoom into when parameter type is "neighbour" could either be an integer or vector of integers representing node ids (zoom into one node or multiple nodes) graphlayout layout for the graph (two column matrix specifying x,y coordinates of each node in graph) if not provided, igraph will use the default layout_nicely() function to present the graph ... extra parameters passed to plot.igraph Details when only the diffee is provided, the function will plot all graphs with default numeric labels User can specify multiple subID and multiple index to zoom in multiple nodes on multiple graphs Each graph will include a descriptive title. Value a plot of graph / subgraph from diffee result specified by user input Author(s) <NAME>, <NAME> (Author), <NAME> (maintainer) Examples ## Not run: data(exampleData) result = diffee(exampleData[[1]], exampleData[[2]], 0.45) plot.diffee(result) ## End(Not run) returngraph return igraph object from diffee result specified by user input Description This function can return an igraph object from diffee result for user to work with directly Usage returngraph(x, type = "task", index = NULL) Arguments x output generated from diffee function (diffee class) type type of graph, there are four options: (1) "task" (graph for each task (including shared part) specified further by subID (task number)) (2) "neighbour" (zoom into nodes in the graph specified further by parameter "index" (node id) index determines which node(s) to zoom into when parameter type is "neighbour" could either be an integer or vector of integers representing node ids (zoom into one node or multiple nodes) Details the function aims to provide users the flexibility to explore and visualize the graph own their own generated from diffee Value an igraph object of graph / subgraph from diffee result specified by user input Author(s) <NAME>, <NAME> (Author), <NAME> (maintainer) Examples ## Not run: data(exampleData) result = diffee(exampleData[[1]], exampleData[[2]], 0.45) graph = returngraph(result) ## End(Not run)
github.com/kubesphere/kubekey
go
Go
README [¶](#section-readme) --- ### KubeKey [![CI](https://github.com/kubesphere/kubekey/workflows/CI/badge.svg?branch=master&event=push)](https://github.com/kubesphere/kubekey/actions?query=event%3Apush+branch%3Amaster+workflow%3ACI+) > English | [中文](https://github.com/kubesphere/kubekey/blob/v1.2.2/README_zh-CN.md) Since v3.0.0, [KubeSphere](https://kubesphere.io) changes the ansible-based installer to the new installer called KubeKey that is developed in Go language. With KubeKey, you can install Kubernetes and KubeSphere separately or as a whole easily, efficiently and flexibly. There are three scenarios to use KubeKey. * Install Kubernetes only * Install Kubernetes and KubeSphere together in one command * Install Kubernetes first, then deploy KubeSphere on it using [ks-installer](https://github.com/kubesphere/ks-installer) > **Important:** If you have existing clusters, please refer to [ks-installer (Install KubeSphere on existing Kubernetes cluster)](https://github.com/kubesphere/ks-installer). #### Motivation * Ansible-based installer has a bunch of software dependency such as Python. KubeKey is developed in Go language to get rid of the problem in a variety of environment so that increasing the success rate of installation. * KubeKey uses Kubeadm to install K8s cluster on nodes in parallel as much as possible in order to reduce installation complexity and improve efficiency. It will greatly save installation time compared to the older installer. * KubeKey supports for scaling cluster from allinone to multi-node cluster, even an HA cluster. * KubeKey aims to install cluster as an object, i.e., CaaO. #### Supported Environment ##### Linux Distributions * **Ubuntu** *16.04, 18.04, 20.04* * **Debian** *Buster, Stretch* * **CentOS/RHEL** *7* * **SUSE Linux Enterprise Server** *15* > Recommended Linux Kernel Version: `4.15 or later` > You can run the `uname -srm` command to check the Linux Kernel Version. ##### Kubernetes Versions * **v1.17**:   *v1.17.9* * **v1.18**:   *v1.18.6* * **v1.19**:   *v1.19.8* * **v1.20**:   *v1.20.6* * **v1.21**:   *v1.21.5* (default) * **v1.22**:   *v1.22.1* > Looking for more supported versions [Click here](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/kubernetes-versions.md) #### Requirements and Recommendations * Minimum resource requirements (For Minimal Installation of KubeSphere only): + 2 vCPUs + 4 GB RAM + 20 GB Storage > /var/lib/docker is mainly used to store the container data, and will gradually increase in size during use and operation. In the case of a production environment, it is recommended that /var/lib/docker mounts a drive separately. * OS requirements: + `SSH` can access to all nodes. + Time synchronization for all nodes. + `sudo`/`curl`/`openssl` should be used in all nodes. + `docker` can be installed by yourself or by KubeKey. + `Red Hat` includes `SELinux` in its `Linux release`. It is recommended to close SELinux or [switch the mode of SELinux](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/turn-off-SELinux.md) to `Permissive` > * It's recommended that Your OS is clean (without any other software installed), otherwise there may be conflicts. > * A container image mirror (accelerator) is recommended to be prepared if you have trouble downloading images from dockerhub.io. [Configure registry-mirrors for the Docker daemon](https://docs.docker.com/registry/recipes/mirror/#configure-the-docker-daemon). > * KubeKey will install [OpenEBS](https://openebs.io/) to provision LocalPV for development and testing environment by default, this is convenient for new users. For production, please use NFS / Ceph / GlusterFS or commercial products as persistent storage, and install the [relevant client](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/storage-client.md) in all nodes. > * If you encounter `Permission denied` when copying, it is recommended to check [SELinux and turn off it](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/turn-off-SELinux.md) first * Dependency requirements: KubeKey can install Kubernetes and KubeSphere together. The dependency that needs to be installed may be different based on the Kubernetes version to be installed. You can refer to the list below to see if you need to install relevant dependencies on your node in advance. | | Kubernetes Version ≥ 1.18 | Kubernetes Version < 1.18 | | --- | --- | --- | | `socat` | Required | Optional but recommended | | `conntrack` | Required | Optional but recommended | | `ebtables` | Optional but recommended | Optional but recommended | | `ipset` | Optional but recommended | Optional but recommended | * Networking and DNS requirements: + Make sure the DNS address in `/etc/resolv.conf` is available. Otherwise, it may cause some issues of DNS in cluster. + If your network configuration uses Firewall or Security Group,you must ensure infrastructure components can communicate with each other through specific ports. It's recommended that you turn off the firewall or follow the link configuriation: [NetworkAccess](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/network-access.md). #### Usage ##### Get the Installer Executable File * Binary downloads of the KubeKey can be found on the [Releases page](https://github.com/kubesphere/kubekey/releases). Unpack the binary and you are good to go! * Build Binary from Source Code ``` git clone https://github.com/kubesphere/kubekey.git cd kubekey ./build.sh ``` > Note: > * Docker needs to be installed before building. > * If you have problem to access `https://proxy.golang.org/`, excute `build.sh -p` instead. ##### Create a Cluster ###### Quick Start Quick Start is for `all-in-one` installation which is a good start to get familiar with KubeSphere. > Note: Since Kubernetes temporarily does not support uppercase NodeName, contains uppercase letters in the hostname will lead to subsequent installation error Command > If you have problem to access `https://storage.googleapis.com`, execute first `export KKZONE=cn`. ``` ./kk create cluster [--with-kubernetes version] [--with-kubesphere version] ``` Examples * Create a pure Kubernetes cluster with default version. ``` ./kk create cluster ``` * Create a Kubernetes cluster with a specified version ([supported versions](#readme-KubernetesVersions)). ``` ./kk create cluster --with-kubernetes v1.19.8 ``` * Create a Kubernetes cluster with KubeSphere installed (e.g. `--with-kubesphere v3.1.0`) ``` ./kk create cluster --with-kubesphere [version] ``` ###### Advanced You have more control to customize parameters or create a multi-node cluster using the advanced installation. Specifically, create a cluster by specifying a configuration file. > If you have problem to access `https://storage.googleapis.com`, execute first `export KKZONE=cn`. 1. First, create an example configuration file ``` ./kk create config [--with-kubernetes version] [--with-kubesphere version] [(-f | --file) path] ``` **examples:** * create an example config file with default configurations. You also can specify the file that could be a different filename, or in different folder. ``` ./kk create config [-f ~/myfolder/abc.yaml] ``` * with KubeSphere ``` ./kk create config --with-kubesphere ``` 2. Modify the file config-sample.yaml according to your environment > Note: Since Kubernetes temporarily does not support uppercase NodeName, contains uppercase letters in workerNode`s name will lead to subsequent installation error > A persistent storage is required in the cluster, when kubesphere will be installed. The local volume is used default. If you want to use other persistent storage, please refer to [addons](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/addons.md). 1. Create a cluster using the configuration file ``` ./kk create cluster -f config-sample.yaml ``` ##### Enable Multi-cluster Management By default, KubeKey will only install a **solo** cluster without Kubernetes federation. If you want to set up a multi-cluster control plane to centrally manage multiple clusters using KubeSphere, you need to set the `ClusterRole` in [config-example.yaml](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/config-example.md). For multi-cluster user guide, please refer to [How to Enable the Multi-cluster Feature](https://github.com/kubesphere/community/tree/master/sig-multicluster/how-to-setup-multicluster-on-kubesphere). ##### Enable Pluggable Components KubeSphere has decoupled some core feature components since v2.1.0. These components are designed to be pluggable which means you can enable them either before or after installation. By default, KubeSphere will be started with a minimal installation if you do not enable them. You can enable any of them according to your demands. It is highly recommended that you install these pluggable components to discover the full-stack features and capabilities provided by KubeSphere. Please ensure your machines have sufficient CPU and memory before enabling them. See [Enable Pluggable Components](https://github.com/kubesphere/ks-installer#enable-pluggable-components) for the details. ##### Add Nodes Add new node's information to the cluster config file, then apply the changes. ``` ./kk add nodes -f config-sample.yaml ``` ##### Delete Nodes You can delete the node by the following command,the nodeName that needs to be removed. ``` ./kk delete node <nodeName> -f config-sample.yaml ``` ##### Delete Cluster You can delete the cluster by the following command: * If you started with the quick start (all-in-one): ``` ./kk delete cluster ``` * If you started with the advanced (created with a configuration file): ``` ./kk delete cluster [-f config-sample.yaml] ``` ##### Upgrade Cluster ###### Allinone Upgrading cluster with a specified version. ``` ./kk upgrade [--with-kubernetes version] [--with-kubesphere version] ``` * Support upgrading Kubernetes only. * Support upgrading KubeSphere only. * Support upgrading Kubernetes and KubeSphere. ###### Multi-nodes Upgrading cluster with a specified configuration file. ``` ./kk upgrade [--with-kubernetes version] [--with-kubesphere version] [(-f | --file) path] ``` * If `--with-kubernetes` or `--with-kubesphere` is specified, the configuration file will be also updated. * Use `-f` to specify the configuration file which was generated for cluster creation. > Note: Upgrading multi-nodes cluster need a specified configuration file. If the cluster was installed without kubekey or the configuration file for installation was not found, the configuration file needs to be created by yourself or following command. Getting cluster info and generating kubekey's configuration file (optional). ``` ./kk create config [--from-cluster] [(-f | --file) path] [--kubeconfig path] ``` * `--from-cluster` means fetching cluster's information from an existing cluster. * `-f` refers to the path where the configuration file is generated. * `--kubeconfig` refers to the path where the kubeconfig. * After generating the configuration file, some parameters need to be filled in, such as the ssh information of the nodes. #### Documents * [Configuration example](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/config-example.md) * [Addons](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/addons.md) * [Network access](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/network-access.md) * [Storage clients](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/storage-client.md) * [kubectl auto-completion](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/kubectl-autocompletion.md) * [kubekey auto-completion](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/kubekey-autocompletion.md) * [Roadmap](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/roadmap.md) * [Check-Renew-Certificate](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/check-renew-certificate.md) * [Developer-Guide](https://github.com/kubesphere/kubekey/blob/v1.2.2/docs/developer-guide.md) #### Contributors ✨ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | [**pixiake**](https://github.com/pixiake)[💻](https://github.com/kubesphere/kubekey/commits?author=pixiake "Code") [📖](https://github.com/kubesphere/kubekey/commits?author=pixiake "Documentation") | [**Forest**](https://github.com/Forest-L)[💻](https://github.com/kubesphere/kubekey/commits?author=Forest-L "Code") [📖](https://github.com/kubesphere/kubekey/commits?author=Forest-L "Documentation") | [**rayzhou2017**](https://kubesphere.io/)[💻](https://github.com/kubesphere/kubekey/commits?author=rayzhou2017 "Code") [📖](https://github.com/kubesphere/kubekey/commits?author=rayzhou2017 "Documentation") | [**shaowenchen**](https://www.chenshaowen.com/)[💻](https://github.com/kubesphere/kubekey/commits?author=shaowenchen "Code") [📖](https://github.com/kubesphere/kubekey/commits?author=shaowenchen "Documentation") | [**Zhao Xiaojie**](http://surenpi.com/)[💻](https://github.com/kubesphere/kubekey/commits?author=LinuxSuRen "Code") [📖](https://github.com/kubesphere/kubekey/commits?author=LinuxSuRen "Documentation") | [**<NAME>**](https://github.com/zackzhangkai)[💻](https://github.com/kubesphere/kubekey/commits?author=zackzhangkai "Code") | [**<NAME>**](https://akhilerm.com/)[💻](https://github.com/kubesphere/kubekey/commits?author=akhilerm "Code") | | [**pengfei**](https://github.com/FeynmanZhou)[📖](https://github.com/kubesphere/kubekey/commits?author=FeynmanZhou "Documentation") | [**min zhang**](https://github.com/min-zh)[💻](https://github.com/kubesphere/kubekey/commits?author=min-zh "Code") [📖](https://github.com/kubesphere/kubekey/commits?author=min-zh "Documentation") | [**zgldh**](https://github.com/zgldh)[💻](https://github.com/kubesphere/kubekey/commits?author=zgldh "Code") | [**xrjk**](https://github.com/xrjk)[💻](https://github.com/kubesphere/kubekey/commits?author=xrjk "Code") | [**yonghongshi**](https://github.com/stoneshi-yunify)[💻](https://github.com/kubesphere/kubekey/commits?author=stoneshi-yunify "Code") | [**Honglei**](https://github.com/shenhonglei)[📖](https://github.com/kubesphere/kubekey/commits?author=shenhonglei "Documentation") | [**liucy1983**](https://github.com/liucy1983)[💻](https://github.com/kubesphere/kubekey/commits?author=liucy1983 "Code") | | [**Lien**](https://github.com/lilien1010)[📖](https://github.com/kubesphere/kubekey/commits?author=lilien1010 "Documentation") | [**<NAME>**](https://github.com/klj890)[📖](https://github.com/kubesphere/kubekey/commits?author=klj890 "Documentation") | [**<NAME>**](https://github.com/hlwanghl)[💻](https://github.com/kubesphere/kubekey/commits?author=hlwanghl "Code") | [**dawn**](https://fafucoder.github.io/)[💻](https://github.com/kubesphere/kubekey/commits?author=fafucoder "Code") | [**<NAME>**](https://github.com/duanjiong)[💻](https://github.com/kubesphere/kubekey/commits?author=duanjiong "Code") | [**calvinyv**](https://github.com/calvinyv)[📖](https://github.com/kubesphere/kubekey/commits?author=calvinyv "Documentation") | [**<NAME>**](https://github.com/benjaminhuo)[📖](https://github.com/kubesphere/kubekey/commits?author=benjaminhuo "Documentation") | | [**Sherlock113**](https://github.com/Sherlock113)[📖](https://github.com/kubesphere/kubekey/commits?author=Sherlock113 "Documentation") | [**fu_changjie**](https://github.com/Fuchange)[📖](https://github.com/kubesphere/kubekey/commits?author=Fuchange "Documentation") | [**yuswift**](https://github.com/yuswift)[💻](https://github.com/kubesphere/kubekey/commits?author=yuswift "Code") | [**ruiyaoOps**](https://github.com/ruiyaoOps)[📖](https://github.com/kubesphere/kubekey/commits?author=ruiyaoOps "Documentation") | [**LXM**](http://www.luxingmin.com)[📖](https://github.com/kubesphere/kubekey/commits?author=lxm "Documentation") | [**sbhnet**](https://github.com/sbhnet)[💻](https://github.com/kubesphere/kubekey/commits?author=sbhnet "Code") | [**misteruly**](https://github.com/misteruly)[💻](https://github.com/kubesphere/kubekey/commits?author=misteruly "Code") | | [**<NAME>**](https://johnniang.me)[📖](https://github.com/kubesphere/kubekey/commits?author=JohnNiang "Documentation") | [**<NAME>**](https://alimy.me)[💻](https://github.com/kubesphere/kubekey/commits?author=alimy "Code") | [**独孤昊天**](https://github.com/duguhaotian)[💻](https://github.com/kubesphere/kubekey/commits?author=duguhaotian "Code") | [**<NAME>**](https://github.com/lshmouse)[💻](https://github.com/kubesphere/kubekey/commits?author=lshmouse "Code") | [**<NAME>**](https://github.com/24sama)[💻](https://github.com/kubesphere/kubekey/commits?author=24sama "Code") | [**Roland**](https://github.com/RolandMa1986)[💻](https://github.com/kubesphere/kubekey/commits?author=RolandMa1986 "Code") | [**<NAME>**](https://ops.m114.org)[📖](https://github.com/kubesphere/kubekey/commits?author=vinsonzou "Documentation") | | [**tag_gee_y**](https://github.com/tagGeeY)[💻](https://github.com/kubesphere/kubekey/commits?author=tagGeeY "Code") | [**codebee**](https://github.com/liulangwa)[💻](https://github.com/kubesphere/kubekey/commits?author=liulangwa "Code") | [**<NAME>**](https://github.com/TheApeMachine)[🤔](#ideas-TheApeMachine) | [**Naidile P N**](https://github.com/Naidile-P-N)[💻](https://github.com/kubesphere/kubekey/commits?author=Naidile-P-N "Code") | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! Documentation [¶](#section-documentation) --- ![The Go Gopher](/static/shared/gopher/airplane-1200x945.svg) There is no documentation for this package.
github.com/odpf/stencil/clients/go
go
Go
README [¶](#section-readme) --- ### Stencil go client [![Go Reference](https://pkg.go.dev/badge/github.com/odpf/stencil/clients/go.svg)](https://pkg.go.dev/github.com/odpf/stencil/clients/go) Stencil go client package provides a store to lookup protobuf descriptors and options to keep the protobuf descriptors upto date. It has following features * Deserialize protobuf messages directly by specifying protobuf message name * Serialize data by specifying protobuf message name * Ability to refresh protobuf descriptors in specified intervals * Support to download descriptors from multiple urls #### Requirements * go 1.16 #### Installation Use `go get` ``` go get github.com/odpf/stencil/clients/go ``` Then import the stencil package into your own code as mentioned below ``` import stencil "github.com/odpf/stencil/clients/go" ``` #### Usage ##### Creating a client ``` import stencil "github.com/odpf/stencil/clients/go" url := "http://localhost:8000/v1beta1/namespaces/{test-namespace}/schemas/{schema-name}" client, err := stencil.NewClient([]string{url}, stencil.Options{}) ``` ##### Get Descriptor ``` import stencil "github.com/odpf/stencil/clients/go" url := "http://localhost:8000/v1beta1/namespaces/{test-namespace}/schemas/{schema-name}" client, err := stencil.NewClient([]string{url}, stencil.Options{}) if err != nil { return } desc, err := client.GetDescriptor("google.protobuf.DescriptorProto") ``` ##### Parse protobuf message. ``` import stencil "github.com/odpf/stencil/clients/go" url := "http://localhost:8000/v1beta1/namespaces/{test-namespace}/schemas/{schema-name}" client, err := stencil.NewClient([]string{url}, stencil.Options{}) if err != nil { return } data := []byte("") parsedMsg, err := client.Parse("google.protobuf.DescriptorProto", data) ``` ##### Serialize data. ``` import stencil "github.com/odpf/stencil/clients/go" url := "http://url/to/proto/descriptorset/file" client, err := stencil.NewClient([]string{url}, stencil.Options{}) if err != nil { return } data := map[string]interface{}{} serializedMsg, err := client.Serialize("google.protobuf.DescriptorProto", data) ``` ##### Enable auto refresh of schemas ``` import stencil "github.com/odpf/stencil/clients/go" url := "http://localhost:8000/v1beta1/namespaces/{test-namespace}/schemas/{schema-name}" // Configured to refresh schema every 12 hours client, err := stencil.NewClient([]string{url}, stencil.Options{AutoRefresh: true, RefreshInterval: time.Hours * 12}) if err != nil { return } desc, err := client.GetDescriptor("google.protobuf.DescriptorProto") ``` ##### Using VersionBasedRefresh strategy ``` import stencil "github.com/odpf/stencil/clients/go" url := "http://localhost:8000/v1beta1/namespaces/{test-namespace}/schemas/{schema-name}" // Configured to refresh schema every 12 hours client, err := stencil.NewClient([]string{url}, stencil.Options{AutoRefresh: true, RefreshInterval: time.Hours * 12, RefreshStrategy: stencil.VersionBasedRefresh}) if err != nil { return } desc, err := client.GetDescriptor("google.protobuf.DescriptorProto") ``` Refer to [go documentation](https://pkg.go.dev/github.com/odpf/stencil/clients/go) for all available methods and options. Documentation [¶](#section-documentation) --- ### Overview [¶](#pkg-overview) Package stencil helps to download and refresh protobuf descriptors from remote server and provides helper functions to get protobuf schema descriptors and can parse the messages dynamically. ### Index [¶](#pkg-index) * [Variables](#pkg-variables) * [type Client](#Client) * + [func NewClient(urls []string, options Options) (Client, error)](#NewClient) * [type HTTPOptions](#HTTPOptions) * [type Logger](#Logger) * [type Options](#Options) * [type RefreshStrategy](#RefreshStrategy) * [type Resolver](#Resolver) * + [func NewResolver(data []byte) (*Resolver, error)](#NewResolver) * + [func (r *Resolver) Get(className string) (protoreflect.MessageType, bool)](#Resolver.Get) + [func (r *Resolver) GetTypeResolver() *protoregistry.Types](#Resolver.GetTypeResolver) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) ``` var ( //ErrNotFound default sentinel error if proto not found ErrNotFound = [errors](/github.com/pkg/errors).[New](/github.com/pkg/errors#New)("not found") //ErrInvalidDescriptor is for when descriptor does not match the message ErrInvalidDescriptor = [errors](/github.com/pkg/errors).[New](/github.com/pkg/errors#New)("invalid descriptor") ) ``` ### Functions [¶](#pkg-functions) This section is empty. ### Types [¶](#pkg-types) #### type [Client](https://github.com/odpf/stencil/blob/254183aaf205/clients/go/client.go#L26) [¶](#Client) ``` type Client interface { // Parse parses protobuf message from wire format to protoreflect.ProtoMessage given fully qualified name of proto message. // Returns ErrNotFound error if given class name is not found Parse([string](/builtin#string), [][byte](/builtin#byte)) ([protoreflect](/google.golang.org/protobuf/reflect/protoreflect).[ProtoMessage](/google.golang.org/protobuf/reflect/protoreflect#ProtoMessage), [error](/builtin#error)) // Serialize serializes data to bytes given fully qualified name of proto message. // Returns ErrNotFound error if given class name is not found Serialize([string](/builtin#string), interface{}) ([][byte](/builtin#byte), [error](/builtin#error)) // GetDescriptor returns protoreflect.MessageDescriptor given fully qualified proto java class name GetDescriptor([string](/builtin#string)) ([protoreflect](/google.golang.org/protobuf/reflect/protoreflect).[MessageDescriptor](/google.golang.org/protobuf/reflect/protoreflect#MessageDescriptor), [error](/builtin#error)) // Close stops background refresh if configured. Close() // Refresh loads new values from specified url. If the schema is already fetched, the previous value // will continue to be used by Parse methods while the new value is loading. // If schemas not loaded, then this function will block until the value is loaded. Refresh() } ``` Client provides utility functions to parse protobuf messages at runtime. protobuf messages can be identified by specifying fully qualified generated proto java class name. #### func [NewClient](https://github.com/odpf/stencil/blob/254183aaf205/clients/go/client.go#L79) [¶](#NewClient) ``` func NewClient(urls [][string](/builtin#string), options [Options](#Options)) ([Client](#Client), [error](/builtin#error)) ``` NewClient creates stencil client. Downloads proto descriptor file from given url and stores the definitions. It will throw error if download fails or downloaded file is not fully contained descriptor file #### type [HTTPOptions](https://github.com/odpf/stencil/blob/254183aaf205/clients/go/client.go#L44) [¶](#HTTPOptions) ``` type HTTPOptions struct { // Timeout specifies a time limit for requests made by this client. Default to 10s. // `0` duration not allowed. Client will set to default value (i.e. 10s). Timeout [time](/time).[Duration](/time#Duration) // Headers provide extra headers to be added in requests made by this client Headers map[[string](/builtin#string)][string](/builtin#string) } ``` HTTPOptions options for http client #### type [Logger](https://github.com/odpf/stencil/blob/254183aaf205/clients/go/logger.go#L4) [¶](#Logger) ``` type Logger interface { Info([string](/builtin#string)) Error([string](/builtin#string)) } ``` Logger interface used to get logging from stencil internals. #### type [Options](https://github.com/odpf/stencil/blob/254183aaf205/clients/go/client.go#L53) [¶](#Options) ``` type Options struct { // AutoRefresh boolean to enable or disable autorefresh. Default to false AutoRefresh [bool](/builtin#bool) // RefreshInterval refresh interval to fetch descriptor file from server. Default to 12h. // `0` duration not allowed. Client will set to default value (i.e. 12h). RefreshInterval [time](/time).[Duration](/time#Duration) // HTTPOptions options for http client [HTTPOptions](#HTTPOptions) // RefreshStrategy refresh strategy to use while fetching schema. // Default strategy set to `stencil.LongPollingRefresh` strategy [RefreshStrategy](#RefreshStrategy) // Logger is the interface used to get logging from stencil internals. [Logger](#Logger) } ``` Options options for stencil client #### type [RefreshStrategy](https://github.com/odpf/stencil/blob/254183aaf205/clients/go/refresh_strategy.go#L11) [¶](#RefreshStrategy) ``` type RefreshStrategy [int](/builtin#int) ``` RefreshStrategy clients can configure which refresh strategy to use to download latest schema. Default is LongPollingRefresh strategy ``` const ( // LongPollingRefresh this refresh strategy tries to update schema on every specified interval. // It doesn't check for schema changes explicitly. LongPollingRefresh [RefreshStrategy](#RefreshStrategy) = [iota](/builtin#iota) // VersionBasedRefresh this refresh strategy utilizes versions API provided by Stencil Server. // If new version is available then only schema cache would be updated. VersionBasedRefresh ) ``` #### type [Resolver](https://github.com/odpf/stencil/blob/254183aaf205/clients/go/resolver.go#L12) [¶](#Resolver) ``` type Resolver struct { // contains filtered or unexported fields } ``` Resolver protobuf type resolver #### func [NewResolver](https://github.com/odpf/stencil/blob/254183aaf205/clients/go/resolver.go#L73) [¶](#NewResolver) ``` func NewResolver(data [][byte](/builtin#byte)) (*[Resolver](#Resolver), [error](/builtin#error)) ``` NewResolver parses protobuf fileDescriptorSet schema returns type Resolver #### func (*Resolver) [Get](https://github.com/odpf/stencil/blob/254183aaf205/clients/go/resolver.go#L20) [¶](#Resolver.Get) ``` func (r *[Resolver](#Resolver)) Get(className [string](/builtin#string)) ([protoreflect](/google.golang.org/protobuf/reflect/protoreflect).[MessageType](/google.golang.org/protobuf/reflect/protoreflect#MessageType), [bool](/builtin#bool)) ``` Get returns protobuf messageType for given proto message fullname. If java package file option is added, then message classname would be javapackage + message name. If java package file option is not defined then className would be proto message fullName. #### func (*Resolver) [GetTypeResolver](https://github.com/odpf/stencil/blob/254183aaf205/clients/go/resolver.go#L33) [¶](#Resolver.GetTypeResolver) ``` func (r *[Resolver](#Resolver)) GetTypeResolver() *[protoregistry](/google.golang.org/protobuf/reflect/protoregistry).[Types](/google.golang.org/protobuf/reflect/protoregistry#Types) ``` GetTypeResolver returns type resolver
bgw
cran
R
Package ‘bgw’ July 13, 2023 Type Package Title Bunch-Gay-Welsch Statistical Estimation Version 0.1.2 Maintainer <NAME> <<EMAIL>> Description Performs statistical estimation and inference-related computations by accessing and executing modified versions of 'Fortran' subroutines originally published in the Association for Computing Machinery (ACM) journal Transactions on Mathematical Software (TOMS) by Bunch, Gay and Welsch (1993) <doi:10.1145/151271.151279>. The acronym 'BGW' (from the authors' last names) will be used when making reference to technical content (e.g., algorithm, methodology) that originally appeared in ACM TOMS. A key feature of BGW is that it exploits the special structure of statistical estimation problems within a trust-region-based optimization approach to produce an estimation algorithm that is much more effective than the usual practice of using optimization methods and codes originally developed for general optimization. The 'bgw' package bundles 'R' wrapper (and related) functions with modified 'Fortran' source code so that it can be compiled and linked in the 'R' environment for fast execution. This version implements a function ('bgw_mle.R') that performs maximum likelihood estimation (MLE) for a user-provided model object that computes probabilities (a.k.a. probability densities). The motivation for producing this initial version is to provide fast, efficient, and reliable MLE for discrete choice models that can be called from the 'Apollo' choice modelling 'R' package: see <http://www.apollochoicemodelling.com>. However, estimation can also be performed in a stand-alone fashion without using 'Apollo' (as shown in simple examples). After this initial version is available on CRAN, an updated version of 'Apollo' (0.2.9) will be made available that automatically loads 'bgw'. Additional development can then occur, including more detailed examples in 'bgw' that refer to 'Apollo.' Note also that BGW capabilities are not limited to MLE, and future extension to other estimators (e.g., nonlinear least squares, generalized method of moments, etc.) is possible. The 'Fortran' code included in 'bgw' was modified by one of the original BGW authors (Bunch) under his rights as confirmed by direct consultation with the ACM Intellectual Property and Rights Manager. See <https://authors.acm.org/author-resources/author-rights>. The main requirement is clear citation of the original publication (see above). License GPL-3 Encoding UTF-8 NeedsCompilation yes Depends R (>= 4.0.0) Suggests knitr, rmarkdown, testthat (>= 3.0.0), VignetteBuilder knitr RoxygenNote 7.2.3 Author <NAME> [aut, cre] (<https://orcid.org/0000-0001-8728-7072>), <NAME> [ctb], <NAME> [ctb], <NAME> [ctb], <NAME> [ctb] Config/testthat/edition 3 Repository CRAN Date/Publication 2023-07-13 14:30:02 UTC R topics documented: bgw_checkSettin... 2 bgw_drgl... 3 bgw_itsu... 4 bgw_ml... 5 bgw_mle_setu... 8 bgw_writeIteration... 9 bgw_checkSetting bgw_checkSetting Description Checks to see if user-provided value for a bgw_setting is valid. Usage bgw_checkSetting( settingValue, bgw_setting_type, bgw_validDiscrete, bgw_contLB, bgw_contUB ) Arguments settingValue Setting value (submitted by user). bgw_setting_type Type of setting being checked. Possible values are "discrete" and "continuous". bgw_validDiscrete List. Contains valid values for a discrete setting. bgw_contLB Numerical value. The lower bound for a valid continuous setting. bgw_contUB Numerical value. The upper bound for a valid continuous setting. Value Logical. Indicates if the setting is okay or not. bgw_drglg bgw_drglg Description An r wrapper to call drglg_c, which in turn is a wrapper to call the Fortran subroutine drglg. drglg is the BGW iteration driver for performing statistical parameter estimation Usage bgw_drglg( d, dr, iv, liv, lv, n, nd, nn, p, ps, r, rd, v, x, rhoi, rhor, i_itsum ) Arguments d Scaling vector dr Derivative of the choice probability model wrt x iv BGW internal vector of integer values liv Length of iv. lv Length of v. n Dimension of vector (r) of generalized residuals for the model nd Leading dimension dr. Must be at least ps. nn Leading dimension of r, rd p Dimension of x (as well as d, g) = number of parameters being estimated ps Number of non-nuisance parameters (= p in this implementation) r Vector of generalized residuals for the model rd Vector of storage space for regression diagonostics (not currently used) v BGW internal vector of numeric values x Parameter vector for which the objective function is being minimized rhoi Vector of integers for use by user (not currently used) rhor Vector of numeric values for use by user (not currently used) i_itsum Variable for passing itsum instruction back to bgw_mle Value out List of return values. bgw_itsum bgw_itsum Description Prints iteration summary, info on initial and final x. Usage bgw_itsum(d, g, iv, v, x, p, betaIsNamed, betaNames = NULL, i_itsum) Arguments d Scaling vector g Gradient of objective function (negative-log-likelihood) wrt x iv BGW internal vector of integer values v BGW internal vector of numeric values x Parameter vector for which the objective function is being minimized p Dimension of x betaIsNamed Logical. betaNames Character vector. If available, has beta parameter names. i_itsum Code from caller to select specific options Value iv There are iv values changed inside bgw_itsum. The iv vector is the integer workspace for Fortran BGW. bgw_mle bgw_mle Description Performs maximum likelihood estimation (MLE) for the user-provided model defined in bgw_calcR. Usage bgw_mle(calcR, betaStart, calcJ = NULL, bgw_settings = NULL) Arguments calcR Function that computes an n-vector (R) of model residuals for a p-vector of (numeric) parameters beta (the first argument). In this case the residuals are likelihoods (probabilities). (The beta vector can be named or unnamed.) betaStart Vector of initial starting values for beta. Can be either a named or unnamed vector. calcJ Function that computes the matrix of partial derivatives of R wrt beta (a.k.a. the Jacobian). If NULL, finite-difference derivatives are used. In matrix form, dim=c(p,n). However, it could be stored as a vector in column-major order. bgw_settings List. Contains control parameters for BGW estimation code. All parameters have default values, so user input is entirely optional. • printLevel: Integer (0-3). Controls the level of detail for iteration in- formation written to the console during estimation. 0 = silent, 1 = print starting values and final solution only, 2 = short line summary, 3 = long line summary (see documentation). Default = 3. • silent: Logical. Suppresses all output. Default = FALSE. (Currently re- dundant with printLevel = 0.) • printNonDefaultSettings: Logical. Echos any user-provided bgw_settings. Default = TRUE. • printStartingValues: Logical. Default = TRUE. Print starting values for beta. • printFinalResults: Logical. Default = TRUE. Print final status of es- timation (convergence/error message), summary statistics (negative log- likelihood, iterations, function evals, etc.), beta, gradient, and (if available) estimated standard errors and t-ratios. (See vcHessianMethod for variance- covariance specification.) • maxIterations: Numeric. Maximum number of iterations for the estima- tion. BGW default is 150. • maxFunctionEvals: Numeric. Maximum number of objective function evaluations. BGW default is 200. • modelName: Character. Used to create names for requested output files. Default is "bgw_mle_model." • outputDirectory: Character. Name of sub-directory (~/outputDirectory) to write output files. Default is NULL (current directory). • writeItSummary: Logical. If TRUE, iteration information is echoed in the output file "modelName_itSummary.csv". Default is FALSE. [Not cur- rently implemented.] • writeIter: Logical. If TRUE, parameters and log-likelihood for each iter- ation are written to "modelName_iterations.csv". Default is FALSE. • vcHessianMethod: Character. Method for computing the Hessian approxi- mation used for the variance-covariance matrix (VC = H^(-1)). Options are: "none","bhhh","finiteDifferences", or "fdFunction" ("finiteDifferences" au- tomatically uses gradient differences if a gradient is available, otherwise it uses objective function differences. "fdFunction" allows the user to use objective function differences even if a gradient is available). Default is "bhhh." • scalingMethod: Character. Method used to compute a scaling vector (scaleVec_i, i=1,..,p). Define a matrix D = diag(scaleVec_1,..., scaleVec_p). When using scaling, values in scaleVec should be chosen so that the el- ements of D*beta are roughly comparable in size. The re-scaled beta is used when computing trial steps using trust regions, and when computing stopping criteria. Options are: "adaptive," "none," and "userScaling": the default is "adaptive." For a description of the "adaptive" method, which up- dates scaleVec at each iteration using information from the model Jacobian, see Bunch, Gay, and Welsch (1993). For "none," scaleVec is set to a p- vector of ones for the entire search. The "userScaling" option indicates that the user is supplying their own (fixed) scaleVec in bgw_settings[["userScaleVector"]] (see next item). Both items must be properly set or an error occurs. • userScaleVector: Numeric, with dimension p = number of free param- eters. Can be either a named or unnamed vector. This is a user-provided scaling vector that is used ONLY in conjunction with the non-default option "userScaling" for bgw_settings[["scalingMethod"]] (see previous item). Details This function has been written to provide an R-based interface to Fortran estimation software pub- lished in Bunch, Gay and Welsch (1993), "Algorithm 717-Subroutines for Maximum Likelihood and Quasi-Likelihood Estimation of Parameters in Nonlinear Regression Models," ACM Transac- tions on Mathematical Software, 19 (1), March 1993, 109-130. The letters BGW will be used in various ways to denote the source of the estimation functionality. A primary motivation was to develop a more efficient maximum likelihood estimation function for use in the Apollo choice modelling package: see http://www.apollochoicemodelling.com/. However, we have adopted a design whereby the BGW package is wholly independent of Apollo, and can be used in a stand-alone fashion. Note also that the BGW Fortran subroutines are written to support general statistical estimation for an arbitrary objective/criterion function. So, although this version of the package is specifically written for MLE, the package may see future updates that expand the number of estimation options (for, e.g., nonlinear least squares, generalized method of moments, etc.). Remark: Following the convention in the numerical optimization literature, BGW minimizes the objective function. That is, bgw_mle minimizes the negative-log-likelihood for the model calcR. Value model object of class ’bgw_mle’. Output of a bgw maximum likelihood estimation procedure. A list with the following attributes: • betaStart: Vector of initial starting values. • bgw_settings: List. The same as the input argument. • hasAnalyticGrad: Logical. Indicates in an analytical gradient calculation was used. If the user has not provided a calcJ function (see input parameter), it is set to FALSE. • numParams: Numeric. Number of model parameters used in calcR. • numResids: Numeric. Number of independent observations (model residuals) in data set = dimension of calcR output. • code: Numeric. Numeric return code from BGW. • message: Character. Message statement characterizing termination of MLE search. • betaStop: Vector. Value of parameter vector at conclusion of MLE search. See message to determine if beta is a valid estimate. • finalLL: Numeric. Value of log-likelihood at betaStop. • iterations: Numeric. Number of iterations used in MLE search. In BGW, this is the same as the number of gradient evaluations. • functionEvals: Numeric. Number of function evaluations used in MLE search. (This ex- cludes function evaluations used by any finite-difference calculations for the gradient and/or the vcHessian. • gradient: Vector. The gradient evaluated at betaStop. • scaleVec: Vector. The scaling vector at the conclusion of the MLE search. Note: In the current version, this will be a p-vector of 1’s (used throughout the search). In future versions, additional scaling options may be implemented. • estimate: Vector. MLE parameter vector obtained by BGW. The same as betaStop if a valid convergence condition is achieved. Null otherwise. • maximum: Numeric. Final log-likelihood value for a (successful) MLE search. • hessianMethodAttempted: String. Requested method for computing vcHessian (from bgw_settings). • hessianMethodUsed: String. Method actually used for computing vcHessian (if vcHessian was requested, and if the computation was successful. If not, a message indicating ’no request’ or ’singular vcHessian’ is provided.) • vcHessianConditionNumber: Numeric. Estimated upper bound on reciprocal of Euclidean condition number of vcHessian (if available). Set to -1 if unavailable. • varcovBGW: Matrix. p-by-p matrix containing estimate of the variance-covariance matrix (if requested and available). • vcVec: Vector. Lower triangle of variance-covariance matrix stored in vector form (row-major order, if requested and available). • seBGW: Vector. Estimated standard errors for parameter estimates (if requested and available). • tstatBGW: Vector. Estimated t-statistics (versus 0, if requested and available). bgw_mle_setup bgw_mle_setup Description Sets up R-level storage for bgw_mle. This function replaces multiple Fortran subroutines from the BGW Fortran code due at least in part to the prohibition against using Fortran write statements in R packages. The current design produces two vectors (iv_r and v_r) that mirror the main vectors required by the Fortran code. For the moment, the idea is to create named vectors to facilitate coding in bgw_mle. It may be that these could be deleted (or overwritten by an as.numeric() conversion) prior to the main Fortran calls. Usage bgw_mle_setup(p, n, hasAnalyticModelDeriv, control = NULL) Arguments p Number of parameters (components of x) being estimated. (Determined in bgw_mle from size of ’start’ vector. n Number of model residuals (in vector r). (Determined in bgw_mle by the size of the output vector from CalcR.) hasAnalyticModelDeriv Logical. TRUE if CalcRJ has been provided. FALSE means that bgw_mle must employ finite-difference gradients (which has implications for storage alloca- tion). control List of bgw_mle control parameters (optional). If not provided, BGW default parameters will be used. If provided, default parameters will be overwritten by those corresponding parameters provided by the caller (but these must also be checked). Value iv and v vectors used by BGW Fortran. bgw_writeIterations Writes the vector [beta,ll] to a file called modelname_iterations.csv # Was created using apollo_writeTheta as a starting point... Because this is an internal function, the inputs will be assumed to be clean. Description Writes the vector [beta,ll] to a file called modelname_iterations.csv # Was created using apollo_writeTheta as a starting point... Because this is an internal function, the inputs will be assumed to be clean. Usage bgw_writeIterations(beta, ll, outputFile) Arguments beta vector of parameters to be written (for now, no fixed betas). ll scalar representing the log-likelihood of the whole model. outputFile Character. Name of the output file. Value Nothing.
luigi
readthedoc
Python
Luigi 2.8.13 documentation [Luigi](index.html#document-index) --- Luigi is a Python (2.7, 3.6, 3.7 tested) package that helps you build complex pipelines of batch jobs. It handles dependency resolution, workflow management, visualization, handling failures, command line integration, and much more. Getting Started[¶](#getting-started) === Run `pip install luigi` to install the latest stable version from [PyPI](https://pypi.python.org/pypi/luigi). [Documentation for the latest release](https://luigi.readthedocs.io/en/stable/) is hosted on readthedocs. Run `pip install luigi[toml]` to install Luigi with [TOML-based configs](https://luigi.readthedocs.io/en/stable/configuration.html) support. For the bleeding edge code, `pip install git+https://github.com/spotify/luigi.git`. [Bleeding edge documentation](https://luigi.readthedocs.io/en/latest/) is also available. Background[¶](#background) === The purpose of Luigi is to address all the plumbing typically associated with long-running batch processes. You want to chain many tasks, automate them, and failures *will* happen. These tasks can be anything, but are typically long running things like [Hadoop](http://hadoop.apache.org/) jobs, dumping data to/from databases, running machine learning algorithms, or anything else. There are other software packages that focus on lower level aspects of data processing, like [Hive](http://hive.apache.org/), [Pig](http://pig.apache.org/), or [Cascading](http://www.cascading.org/). Luigi is not a framework to replace these. Instead it helps you stitch many tasks together, where each task can be a [Hive query](https://luigi.readthedocs.io/en/latest/api/luigi.contrib.hive.html), a [Hadoop job in Java](https://luigi.readthedocs.io/en/latest/api/luigi.contrib.hadoop_jar.html), a [Spark job in Scala or Python](https://luigi.readthedocs.io/en/latest/api/luigi.contrib.spark.html), a Python snippet, [dumping a table](https://luigi.readthedocs.io/en/latest/api/luigi.contrib.sqla.html) from a database, or anything else. It’s easy to build up long-running pipelines that comprise thousands of tasks and take days or weeks to complete. Luigi takes care of a lot of the workflow management so that you can focus on the tasks themselves and their dependencies. You can build pretty much any task you want, but Luigi also comes with a *toolbox* of several common task templates that you use. It includes support for running [Python mapreduce jobs](https://luigi.readthedocs.io/en/latest/api/luigi.contrib.hadoop.html) in Hadoop, as well as [Hive](https://luigi.readthedocs.io/en/latest/api/luigi.contrib.hive.html), and [Pig](https://luigi.readthedocs.io/en/latest/api/luigi.contrib.pig.html), jobs. It also comes with [file system abstractions for HDFS](https://luigi.readthedocs.io/en/latest/api/luigi.contrib.hdfs.html), and local files that ensures all file system operations are atomic. This is important because it means your data pipeline will not crash in a state containing partial data. Visualiser page[¶](#visualiser-page) === The Luigi server comes with a web interface too, so you can search and filter among all your tasks. Dependency graph example[¶](#dependency-graph-example) === Just to give you an idea of what Luigi does, this is a screen shot from something we are running in production. Using Luigi’s visualiser, we get a nice visual overview of the dependency graph of the workflow. Each node represents a task which has to be run. Green tasks are already completed whereas yellow tasks are yet to be run. Most of these tasks are Hadoop jobs, but there are also some things that run locally and build up data files. Philosophy[¶](#philosophy) === Conceptually, Luigi is similar to [GNU Make](http://www.gnu.org/software/make/) where you have certain tasks and these tasks in turn may have dependencies on other tasks. There are also some similarities to [Oozie](http://oozie.apache.org/) and [Azkaban](http://data.linkedin.com/opensource/azkaban). One major difference is that Luigi is not just built specifically for Hadoop, and it’s easy to extend it with other kinds of tasks. Everything in Luigi is in Python. Instead of XML configuration or similar external data files, the dependency graph is specified *within Python*. This makes it easy to build up complex dependency graphs of tasks, where the dependencies can involve date algebra or recursive references to other versions of the same task. However, the workflow can trigger things not in Python, such as running [Pig scripts](https://luigi.readthedocs.io/en/latest/api/luigi.contrib.pig.html) or [scp’ing files](https://luigi.readthedocs.io/en/latest/api/luigi.contrib.ssh.html). Who uses Luigi?[¶](#who-uses-luigi) === We use Luigi internally at [Spotify](https://www.spotify.com) to run thousands of tasks every day, organized in complex dependency graphs. Most of these tasks are Hadoop jobs. Luigi provides an infrastructure that powers all kinds of stuff including recommendations, toplists, A/B test analysis, external reports, internal dashboards, etc. Since Luigi is open source and without any registration walls, the exact number of Luigi users is unknown. But based on the number of unique contributors, we expect hundreds of enterprises to use it. Some users have written blog posts or held presentations about Luigi: * [Spotify](https://www.spotify.com) [(presentation, 2014)](http://www.slideshare.net/erikbern/luigi-presentation-nyc-data-science) * [Foursquare](https://foursquare.com/) [(presentation, 2013)](http://www.slideshare.net/OpenAnayticsMeetup/luigi-presentation-17-23199897) * [Mortar Data (Datadog)](https://www.datadoghq.com/) [(documentation / tutorial)](http://help.mortardata.com/technologies/luigi) * [Stripe](https://stripe.com/) [(presentation, 2014)](http://www.slideshare.net/PyData/python-as-part-of-a-production-machine-learning-stack-by-michael-manapat-pydata-sv-2014) * [Asana](https://asana.com/) [(blog, 2014)](https://eng.asana.com/2014/11/stable-accessible-data-infrastructure-startup/) * [Buffer](https://buffer.com/) [(blog, 2014)](https://overflow.bufferapp.com/2014/10/31/buffers-new-data-architecture/) * [SeatGeek](https://seatgeek.com/) [(blog, 2015)](http://chairnerd.seatgeek.com/building-out-the-seatgeek-data-pipeline/) * [Treasure Data](https://www.treasuredata.com/) [(blog, 2015)](http://blog.treasuredata.com/blog/2015/02/25/managing-the-data-pipeline-with-git-luigi/) * [Growth Intelligence](http://growthintel.com/) [(presentation, 2015)](http://www.slideshare.net/growthintel/a-beginners-guide-to-building-data-pipelines-with-luigi) * [AdRoll](https://www.adroll.com/) [(blog, 2015)](http://tech.adroll.com/blog/data/2015/09/22/data-pipelines-docker.html) * 17zuoye [(presentation, 2015)](https://speakerdeck.com/mvj3/luiti-an-offline-task-management-framework) * [Custobar](https://www.custobar.com/) [(presentation, 2016)](http://www.slideshare.net/teemukurppa/managing-data-workflows-with-luigi) * [Blendle](https://launch.blendle.com/) [(presentation)](http://www.anneschuth.nl/wp-content/uploads/sea-anneschuth-streamingblendle.pdf#page=126) * [TrustYou](http://www.trustyou.com/) [(presentation, 2015)](https://speakerdeck.com/mfcabrera/pydata-berlin-2015-processing-hotel-reviews-with-python) * [Groupon](https://www.groupon.com/) / [OrderUp](https://orderup.com) [(alternative implementation)](https://github.com/groupon/luigi-warehouse) * [Red Hat - Marketing Operations](https://www.redhat.com) [(blog, 2017)](https://github.com/rh-marketingops/rh-mo-scc-luigi) * [GetNinjas](https://www.getninjas.com.br/) [(blog, 2017)](https://labs.getninjas.com.br/using-luigi-to-create-and-monitor-pipelines-of-batch-jobs-eb8b3cd2a574) * [voyages-sncf.com](https://www.voyages-sncf.com/) [(presentation, 2017)](https://github.com/voyages-sncf-technologies/meetup-afpy-nantes-luigi) * [Open Targets](https://www.opentargets.org/) [(blog, 2017)](https://blog.opentargets.org/using-containers-with-luigi) * [Leipzig University Library](https://ub.uni-leipzig.de) [(presentation, 2016)](https://de.slideshare.net/MartinCzygan/build-your-own-discovery-index-of-scholary-eresources) / [(project)](https://finc.info/de/datenquellen) * [Synetiq](https://synetiq.net/) [(presentation, 2017)](https://www.youtube.com/watch?v=M4xUQXogSfo) * [Glossier](https://www.glossier.com/) [(blog, 2018)](https://medium.com/glossier/how-to-build-a-data-warehouse-what-weve-learned-so-far-at-glossier-6ff1e1783e31) * [Data Revenue](https://www.datarevenue.com/) [(blog, 2018)](https://www.datarevenue.com/en/blog/how-to-scale-your-machine-learning-pipeline) * [Uppsala University](http://pharmb.io) [(tutorial)](http://uppnex.se/twiki/do/view/Courses/EinfraMPS2015/Luigi.html) / [(presentation, 2015)](https://www.youtube.com/watch?v=f26PqSXZdWM) / [(slides, 2015)](https://www.slideshare.net/SamuelLampa/building-workflows-with-spotifys-luigi) / [(poster, 2015)](https://pharmb.io/poster/2015-sciluigi/) / [(paper, 2016)](https://doi.org/10.1186/s13321-016-0179-6) / [(project)](https://github.com/pharmbio/sciluigi) * [GIPHY](https://giphy.com/) [(blog, 2019)](https://engineering.giphy.com/luigi-the-10x-plumber-containerizing-scaling-luigi-in-kubernetes/) * [xtream](https://xtreamers.io/) [(blog, 2019)](https://towardsdatascience.com/lessons-from-a-real-machine-learning-project-part-1-from-jupyter-to-luigi-bdfd0b050ca5) * [CIAN](https://cian.ru/) [(presentation, 2019)](https://www.highload.ru/moscow/2019/abstracts/6030) Some more companies are using Luigi but haven’t had a chance yet to write about it: * [Schibsted](http://www.schibsted.com/) * [enbrite.ly](http://enbrite.ly/) * [Dow Jones / The Wall Street Journal](http://wsj.com) * [Hotels.com](https://hotels.com) * [Newsela](https://newsela.com) * [Squarespace](https://www.squarespace.com/) * [OAO](https://adops.com/) * [Grovo](https://grovo.com/) * [Weebly](https://www.weebly.com/) * [Deloitte](https://www.Deloitte.co.uk/) * [Stacktome](https://stacktome.com/) * [LINX+Neemu+Chaordic](https://www.chaordic.com.br/) * [Foxberry](https://www.foxberry.com/) * [Okko](https://okko.tv/) * [ISVWorld](http://isvworld.com/) * [Big Data](https://bigdata.com.br/) * [Movio](https://movio.co.nz/) * [Bonnier News](https://www.bonniernews.se/) * [Starsky Robotics](https://www.starsky.io/) * [BaseTIS](https://www.basetis.com/) * [Hopper](https://www.hopper.com/) * [VOYAGE GROUP/Zucks](https://zucks.co.jp/en/) * [Textpert](https://www.textpert.ai/) * [Whizar](https://www.whizar.com/) * [xtream](https://www.xtreamers.io/) * [Skyscanner](https://www.skyscanner.net/) * [Jodel](https://www.jodel.com/) * [Mekar](https://mekar.id/en/) * [M3](https://corporate.m3.com/en/) We’re more than happy to have your company added here. Just send a PR on GitHub. External links[¶](#external-links) === * [Mailing List](https://groups.google.com/d/forum/luigi-user/) for discussions and asking questions. (Google Groups) * [Releases](https://pypi.python.org/pypi/luigi) (PyPI) * [Source code](https://github.com/spotify/luigi) (GitHub) * [Hubot Integration](https://github.com/houzz/hubot-luigi) plugin for Slack, Hipchat, etc (GitHub) Authors[¶](#authors) === Luigi was built at [Spotify](https://www.spotify.com), mainly by [<NAME>](https://github.com/erikbern) and [<NAME>](https://github.com/freider). [Many other people](https://github.com/spotify/luigi/graphs/contributors) have contributed since open sourcing in late 2012. [<NAME>](https://github.com/tarrasch) is currently the chief maintainer of Luigi. Table of Contents[¶](#table-of-contents) === Example – Top Artists[¶](#example-top-artists) --- This is a very simplified case of something we do at Spotify a lot. All user actions are logged to Google Cloud Storage (previously HDFS) where we run a bunch of processing jobs to transform the data. The processing code itself is implemented in a scalable data processing framework, such as Scio, Scalding, or Spark, but the jobs are orchestrated with Luigi. At some point we might end up with a smaller data set that we can bulk ingest into Cassandra, Postgres, or other storage suitable for serving or exploration. For the purpose of this exercise, we want to aggregate all streams, find the top 10 artists and then put the results into Postgres. This example is also available in [examples/top_artists.py](https://github.com/spotify/luigi/blob/master/examples/top_artists.py). ### Step 1 - Aggregate Artist Streams[¶](#step-1-aggregate-artist-streams) ``` class AggregateArtists(luigi.Task): date_interval = luigi.DateIntervalParameter() def output(self): return luigi.LocalTarget("data/artist_streams_%s.tsv" % self.date_interval) def requires(self): return [Streams(date) for date in self.date_interval] def run(self): artist_count = defaultdict(int) for input in self.input(): with input.open('r') as in_file: for line in in_file: timestamp, artist, track = line.strip().split() artist_count[artist] += 1 with self.output().open('w') as out_file: for artist, count in artist_count.iteritems(): print >> out_file, artist, count ``` Note that this is just a portion of the file `examples/top_artists.py`. In particular, `Streams` is defined as a [`Task`](index.html#luigi.task.Task), acting as a dependency for `AggregateArtists`. In addition, `luigi.run()` is called if the script is executed directly, allowing it to be run from the command line. There are several pieces of this snippet that deserve more explanation. * Any [`Task`](index.html#luigi.task.Task) may be customized by instantiating one or more [`Parameter`](index.html#luigi.parameter.Parameter) objects on the class level. * The [`output()`](index.html#luigi.task.Task.output) method tells Luigi where the result of running the task will end up. The path can be some function of the parameters. * The [`requires()`](index.html#luigi.task.Task.requires) tasks specifies other tasks that we need to perform this task. In this case it’s an external dump named *Streams* which takes the date as the argument. * For plain Tasks, the [`run()`](index.html#luigi.task.Task.run) method implements the task. This could be anything, including calling subprocesses, performing long running number crunching, etc. For some subclasses of [`Task`](index.html#luigi.task.Task) you don’t have to implement the `run` method. For instance, for the [`JobTask`](index.html#luigi.contrib.hadoop.JobTask) subclass you implement a *mapper* and *reducer* instead. * [`LocalTarget`](index.html#luigi.LocalTarget) is a built in class that makes it easy to read/write from/to the local filesystem. It also makes all file operations atomic, which is nice in case your script crashes for any reason. ### Running this Locally[¶](#running-this-locally) Try running this using eg. ``` $ cd examples $ luigi --module top_artists AggregateArtists --local-scheduler --date-interval 2012-06 ``` Note that *top_artists* needs to be in your PYTHONPATH, or else this can produce an error (*ImportError: No module named top_artists*). Add the current working directory to the command PYTHONPATH with: ``` $ PYTHONPATH='.' luigi --module top_artists AggregateArtists --local-scheduler --date-interval 2012-06 ``` You can also try to view the manual using `--help` which will give you an overview of the options. Running the command again will do nothing because the output file is already created. In that sense, any task in Luigi is *idempotent* because running it many times gives the same outcome as running it once. Note that unlike Makefile, the output will not be recreated when any of the input files is modified. You need to delete the output file manually. The `--local-scheduler` flag tells Luigi not to connect to a scheduler server. This is not recommended for other purpose than just testing things. ### Step 1b - Aggregate artists with Spark[¶](#step-1b-aggregate-artists-with-spark) While Luigi can process data inline, it is normally used to orchestrate external programs that perform the actual processing. In this example, we will demonstrate how top artists instead can be read from HDFS and calculated with Spark, orchestrated by Luigi. ``` class AggregateArtistsSpark(luigi.contrib.spark.SparkSubmitTask): date_interval = luigi.DateIntervalParameter() app = 'top_artists_spark.py' master = 'local[*]' def output(self): return luigi.contrib.hdfs.HdfsTarget("data/artist_streams_%s.tsv" % self.date_interval) def requires(self): return [StreamsHdfs(date) for date in self.date_interval] def app_options(self): # :func:`~luigi.task.Task.input` returns the targets produced by the tasks in # `~luigi.task.Task.requires`. return [','.join([p.path for p in self.input()]), self.output().path] ``` `luigi.contrib.hadoop.SparkSubmitTask` doesn’t require you to implement a [`run()`](index.html#luigi.task.Task.run) method. Instead, you specify the command line parameters to send to `spark-submit`, as well as any other configuration specific to Spark. Python code for the Spark job is found below. ``` import operator import sys from pyspark.sql import SparkSession def main(argv): input_paths = argv[1].split(',') output_path = argv[2] spark = SparkSession.builder.getOrCreate() streams = spark.read.option('sep', '\t').csv(input_paths[0]) for stream_path in input_paths[1:]: streams.union(spark.read.option('sep', '\t').csv(stream_path)) # The second field is the artist counts = streams \ .map(lambda row: (row[1], 1)) \ .reduceByKey(operator.add) counts.write.option('sep', '\t').csv(output_path) if __name__ == '__main__': sys.exit(main(sys.argv)) ``` In a typical deployment scenario, the Luigi orchestration definition above as well as the Pyspark processing code would be packaged into a deployment package, such as a container image. The processing code does not have to be implemented in Python, any program can be packaged in the image and run from Luigi. ### Step 2 – Find the Top Artists[¶](#step-2-find-the-top-artists) At this point, we’ve counted the number of streams for each artists, for the full time period. We are left with a large file that contains mappings of artist -> count data, and we want to find the top 10 artists. Since we only have a few hundred thousand artists, and calculating artists is nontrivial to parallelize, we choose to do this not as a Hadoop job, but just as a plain old for-loop in Python. ``` class Top10Artists(luigi.Task): date_interval = luigi.DateIntervalParameter() use_hadoop = luigi.BoolParameter() def requires(self): if self.use_hadoop: return AggregateArtistsSpark(self.date_interval) else: return AggregateArtists(self.date_interval) def output(self): return luigi.LocalTarget("data/top_artists_%s.tsv" % self.date_interval) def run(self): top_10 = nlargest(10, self._input_iterator()) with self.output().open('w') as out_file: for streams, artist in top_10: print >> out_file, self.date_interval.date_a, self.date_interval.date_b, artist, streams def _input_iterator(self): with self.input().open('r') as in_file: for line in in_file: artist, streams = line.strip().split() yield int(streams), int(artist) ``` The most interesting thing here is that this task (*Top10Artists*) defines a dependency on the previous task (*AggregateArtists*). This means that if the output of *AggregateArtists* does not exist, the task will run before *Top10Artists*. ``` $ luigi --module examples.top_artists Top10Artists --local-scheduler --date-interval 2012-07 ``` This will run both tasks. ### Step 3 - Insert into Postgres[¶](#step-3-insert-into-postgres) This mainly serves as an example of a specific subclass *Task* that doesn’t require any code to be written. It’s also an example of how you can define task templates that you can reuse for a lot of different tasks. ``` class ArtistToplistToDatabase(luigi.contrib.postgres.CopyToTable): date_interval = luigi.DateIntervalParameter() use_hadoop = luigi.BoolParameter() host = "localhost" database = "toplists" user = "luigi" password = "abc123" # ;) table = "top10" columns = [("date_from", "DATE"), ("date_to", "DATE"), ("artist", "TEXT"), ("streams", "INT")] def requires(self): return Top10Artists(self.date_interval, self.use_hadoop) ``` Just like previously, this defines a recursive dependency on the previous task. If you try to build the task, that will also trigger building all its upstream dependencies. ### Using the Central Planner[¶](#using-the-central-planner) The `--local-scheduler` flag tells Luigi not to connect to a central scheduler. This is recommended in order to get started and or for development purposes. At the point where you start putting things in production we strongly recommend running the central scheduler server. In addition to providing locking so that the same task is not run by multiple processes at the same time, this server also provides a pretty nice visualization of your current work flow. If you drop the `--local-scheduler` flag, your script will try to connect to the central planner, by default at localhost port 8082. If you run ``` $ luigid ``` in the background and then run your task without the `--local-scheduler` flag, then your script will now schedule through a centralized server. You need [Tornado](http://www.tornadoweb.org/) for this to work. Launching <http://localhost:8082> should show something like this: Web server screenshot Looking at the dependency graph for any of the tasks yields something like this: Aggregate artists screenshot In production, you’ll want to run the centralized scheduler. See: [Using the Central Scheduler](index.html#document-central_scheduler) for more information. Building workflows[¶](#building-workflows) --- There are two fundamental building blocks of Luigi - the [`Task`](index.html#luigi.task.Task) class and the [`Target`](index.html#luigi.target.Target) class. Both are abstract classes and expect a few methods to be implemented. In addition to those two concepts, the [`Parameter`](index.html#luigi.parameter.Parameter) class is an important concept that governs how a Task is run. ### Target[¶](#target) The [`Target`](index.html#luigi.target.Target) class corresponds to a file on a disk, a file on HDFS or some kind of a checkpoint, like an entry in a database. Actually, the only method that Targets have to implement is the *exists* method which returns True if and only if the Target exists. In practice, implementing Target subclasses is rarely needed. Luigi comes with a toolbox of several useful Targets. In particular, `LocalTarget` and [`HdfsTarget`](index.html#luigi.contrib.hdfs.target.HdfsTarget), but there is also support for other file systems: [`luigi.contrib.s3.S3Target`](index.html#luigi.contrib.s3.S3Target), [`luigi.contrib.ssh.RemoteTarget`](index.html#luigi.contrib.ssh.RemoteTarget), [`luigi.contrib.ftp.RemoteTarget`](index.html#luigi.contrib.ftp.RemoteTarget), [`luigi.contrib.mysqldb.MySqlTarget`](index.html#luigi.contrib.mysqldb.MySqlTarget), [`luigi.contrib.redshift.RedshiftTarget`](index.html#luigi.contrib.redshift.RedshiftTarget), and several more. Most of these targets, are file system-like. For instance, `LocalTarget` and [`HdfsTarget`](index.html#luigi.contrib.hdfs.target.HdfsTarget) map to a file on the local drive or a file in HDFS. In addition these also wrap the underlying operations to make them atomic. They both implement the `open()` method which returns a stream object that could be read (`mode='r'`) from or written to (`mode='w'`). Luigi comes with Gzip support by providing `format=format.Gzip`. Adding support for other formats is pretty simple. ### Task[¶](#task) The [`Task`](index.html#luigi.task.Task) class is a bit more conceptually interesting because this is where computation is done. There are a few methods that can be implemented to alter its behavior, most notably [`run()`](index.html#luigi.task.Task.run), [`output()`](index.html#luigi.task.Task.output) and [`requires()`](index.html#luigi.task.Task.requires). Tasks consume Targets that were created by some other task. They usually also output targets: You can define dependencies between *Tasks* using the [`requires()`](index.html#luigi.task.Task.requires) method. See [Tasks](index.html#document-tasks) for more info. Each task defines its outputs using the [`output()`](index.html#luigi.task.Task.output) method. Additionally, there is a helper method [`input()`](index.html#luigi.task.Task.input) that returns the corresponding Target classes for each Task dependency. ### Parameter[¶](#parameter) The Task class corresponds to some type of job that is run, but in general you want to allow some form of parameterization of it. For instance, if your Task class runs a Hadoop job to create a report every night, you probably want to make the date a parameter of the class. See [Parameters](index.html#document-parameters) for more info. ### Dependencies[¶](#dependencies) Using tasks, targets, and parameters, Luigi lets you express arbitrary dependencies in *code*, rather than using some kind of awkward config DSL. This is really useful because in the real world, dependencies are often very messy. For instance, some examples of the dependencies you might encounter: (These diagrams are from a [Luigi presentation in late 2014 at NYC Data Science meetup](http://www.slideshare.net/erikbern/luigi-presentation-nyc-data-science)) Tasks[¶](#tasks) --- Tasks are where the execution takes place. Tasks depend on each other and output targets. An outline of how a task can look like: ### Task.requires[¶](#task-requires) The [`requires()`](index.html#luigi.task.Task.requires) method is used to specify dependencies on other Task object, which might even be of the same class. For instance, an example implementation could be ``` def requires(self): return OtherTask(self.date), DailyReport(self.date - datetime.timedelta(1)) ``` In this case, the DailyReport task depends on two inputs created earlier, one of which is the same class. requires can return other Tasks in any way wrapped up within dicts/lists/tuples/etc. ### Requiring another Task[¶](#requiring-another-task) Note that [`requires()`](index.html#luigi.task.Task.requires) can *not* return a [`Target`](index.html#luigi.target.Target) object. If you have a simple Target object that is created externally you can wrap it in a Task class like this: ``` class LogFiles(luigi.ExternalTask): def output(self): return luigi.contrib.hdfs.HdfsTarget('/log') ``` This also makes it easier to add parameters: ``` class LogFiles(luigi.ExternalTask): date = luigi.DateParameter() def output(self): return luigi.contrib.hdfs.HdfsTarget(self.date.strftime('/log/%Y-%m-%d')) ``` ### Task.output[¶](#task-output) The [`output()`](index.html#luigi.task.Task.output) method returns one or more [`Target`](index.html#luigi.target.Target) objects. Similarly to requires, you can return them wrapped up in any way that’s convenient for you. However we recommend that any [`Task`](index.html#luigi.task.Task) only return one single [`Target`](index.html#luigi.target.Target) in output. If multiple outputs are returned, atomicity will be lost unless the [`Task`](index.html#luigi.task.Task) itself can ensure that each [`Target`](index.html#luigi.target.Target) is atomically created. (If atomicity is not of concern, then it is safe to return multiple [`Target`](index.html#luigi.target.Target) objects.) ``` class DailyReport(luigi.Task): date = luigi.DateParameter() def output(self): return luigi.contrib.hdfs.HdfsTarget(self.date.strftime('/reports/%Y-%m-%d')) # ... ``` ### Task.run[¶](#task-run) The [`run()`](index.html#luigi.task.Task.run) method now contains the actual code that is run. When you are using [Task.requires](#task-requires) and [Task.run](#task-run) Luigi breaks down everything into two stages. First it figures out all dependencies between tasks, then it runs everything. The [`input()`](index.html#luigi.task.Task.input) method is an internal helper method that just replaces all Task objects in requires with their corresponding output. An example: ``` class GenerateWords(luigi.Task): def output(self): return luigi.LocalTarget('words.txt') def run(self): # write a dummy list of words to output file words = [ 'apple', 'banana', 'grapefruit' ] with self.output().open('w') as f: for word in words: f.write('{word}\n'.format(word=word)) class CountLetters(luigi.Task): def requires(self): return GenerateWords() def output(self): return luigi.LocalTarget('letter_counts.txt') def run(self): # read in file as list with self.input().open('r') as infile: words = infile.read().splitlines() # write each word to output file with its corresponding letter count with self.output().open('w') as outfile: for word in words: outfile.write( '{word} | {letter_count}\n'.format( word=word, letter_count=len(word) ) ) ``` It’s useful to note that if you’re writing to a binary file, Luigi automatically strips the `'b'` flag due to how atomic writes/reads work. In order to write a binary file, such as a pickle file, you should instead use `format=Nop` when calling LocalTarget. Following the above example: ``` class GenerateWords(luigi.Task): def output(self): return luigi.LocalTarget('words.pckl', format=Nop) def run(self): import pickle # write a dummy list of words to output file words = [ 'apple', 'banana', 'grapefruit' ] with self.output().open('w') as f: pickle.dump(words, f) ``` ### Task.input[¶](#task-input) As seen in the example above, [`input()`](index.html#luigi.task.Task.input) is a wrapper around [Task.requires](#task-requires) that returns the corresponding Target objects instead of Task objects. Anything returned by [Task.requires](#task-requires) will be transformed, including lists, nested dicts, etc. This can be useful if you have many dependencies: ``` class TaskWithManyInputs(luigi.Task): def requires(self): return {'a': TaskA(), 'b': [TaskB(i) for i in xrange(100)]} def run(self): f = self.input()['a'].open('r') g = [y.open('r') for y in self.input()['b']] ``` ### Dynamic dependencies[¶](#dynamic-dependencies) Sometimes you might not know exactly what other tasks to depend on until runtime. In that case, Luigi provides a mechanism to specify dynamic dependencies. If you yield another [`Task`](index.html#luigi.task.Task) in the [Task.run](#task-run) method, the current task will be suspended and the other task will be run. You can also yield a list of tasks. ``` class MyTask(luigi.Task): def run(self): other_target = yield OtherTask() # dynamic dependencies resolve into targets f = other_target.open('r') ``` This mechanism is an alternative to [Task.requires](#task-requires) in case you are not able to build up the full dependency graph before running the task. It does come with some constraints: the [Task.run](#task-run) method will resume from scratch each time a new task is yielded. In other words, you should make sure your [Task.run](#task-run) method is idempotent. (This is good practice for all Tasks in Luigi, but especially so for tasks with dynamic dependencies). For an example of a workflow using dynamic dependencies, see [examples/dynamic_requirements.py](https://github.com/spotify/luigi/blob/master/examples/dynamic_requirements.py). ### Task status tracking[¶](#task-status-tracking) For long-running or remote tasks it is convenient to see extended status information not only on the command line or in your logs but also in the GUI of the central scheduler. Luigi implements dynamic status messages, progress bar and tracking urls which may point to an external monitoring system. You can set this information using callbacks within [Task.run](#task-run): ``` class MyTask(luigi.Task): def run(self): # set a tracking url self.set_tracking_url("http://...") # set status messages during the workload for i in range(100): # do some hard work here if i % 10 == 0: self.set_status_message("Progress: %d / 100" % i) # displays a progress bar in the scheduler UI self.set_progress_percentage(i) ``` ### Events and callbacks[¶](#events-and-callbacks) Luigi has a built-in event system that allows you to register callbacks to events and trigger them from your own tasks. You can both hook into some pre-defined events and create your own. Each event handle is tied to a Task class and will be triggered only from that class or a subclass of it. This allows you to effortlessly subscribe to events only from a specific class (e.g. for hadoop jobs). ``` @luigi.Task.event_handler(luigi.Event.SUCCESS) def celebrate_success(task): """Will be called directly after a successful execution of `run` on any Task subclass (i.e. all luigi Tasks) """ ... @luigi.contrib.hadoop.JobTask.event_handler(luigi.Event.FAILURE) def mourn_failure(task, exception): """Will be called directly after a failed execution of `run` on any JobTask subclass """ ... luigi.run() ``` ### But I just want to run a Hadoop job?[¶](#but-i-just-want-to-run-a-hadoop-job) The Hadoop code is integrated in the rest of the Luigi code because we really believe almost all Hadoop jobs benefit from being part of some sort of workflow. However, in theory, nothing stops you from using the [`JobTask`](index.html#luigi.contrib.hadoop.JobTask) class (and also [`HdfsTarget`](index.html#luigi.contrib.hdfs.target.HdfsTarget)) without using the rest of Luigi. You can simply run it manually using ``` MyJobTask('abc', 123).run() ``` You can use the hdfs.target.HdfsTarget class anywhere by just instantiating it: ``` t = luigi.contrib.hdfs.target.HdfsTarget('/tmp/test.gz', format=format.Gzip) f = t.open('w') # ... f.close() # needed ``` ### Task priority[¶](#task-priority) The scheduler decides which task to run next from the set of all tasks that have all their dependencies met. By default, this choice is pretty arbitrary, which is fine for most workflows and situations. If you want to have some control on the order of execution of available tasks, you can set the `priority` property of a task, for example as follows: ``` # A static priority value as a class constant: class MyTask(luigi.Task): priority = 100 # ... # A dynamic priority value with a "@property" decorated method: class OtherTask(luigi.Task): @property def priority(self): if self.date > some_threshold: return 80 else: return 40 # ... ``` Tasks with a higher priority value will be picked before tasks with a lower priority value. There is no predefined range of priorities, you can choose whatever (int or float) values you want to use. The default value is 0. Warning: task execution order in Luigi is influenced by both dependencies and priorities, but in Luigi dependencies come first. For example: if there is a task A with priority 1000 but still with unmet dependencies and a task B with priority 1 without any pending dependencies, task B will be picked first. ### Namespaces, families and ids[¶](#namespaces-families-and-ids) In order to avoid name clashes and to be able to have an identifier for tasks, Luigi introduces the concepts *task_namespace*, *task_family* and *task_id*. The namespace and family operate on class level meanwhile the task id only exists on instance level. The concepts are best illustrated using code. ``` import luigi class MyTask(luigi.Task): my_param = luigi.Parameter() task_namespace = 'my_namespace' my_task = MyTask(my_param='hello') print(my_task) # --> my_namespace.MyTask(my_param=hello) print(my_task.get_task_namespace()) # --> my_namespace print(my_task.get_task_family()) # --> my_namespace.MyTask print(my_task.task_id) # --> my_namespace.MyTask_hello_890907e7ce print(MyTask.get_task_namespace()) # --> my_namespace print(MyTask.get_task_family()) # --> my_namespace.MyTask print(MyTask.task_id) # --> Error! ``` The full documentation for this machinery exists in the [`task`](index.html#module-luigi.task) module. ### Instance caching[¶](#instance-caching) In addition to the stuff mentioned above, Luigi also does some metaclass logic so that if e.g. `DailyReport(datetime.date(2012, 5, 10))` is instantiated twice in the code, it will in fact result in the same object. See [Instance caching](index.html#parameter-instance-caching) for more info Parameters[¶](#parameters) --- Parameters is the Luigi equivalent of creating a constructor for each Task. Luigi requires you to declare these parameters by instantiating [`Parameter`](index.html#luigi.parameter.Parameter) objects on the class scope: ``` class DailyReport(luigi.contrib.hadoop.JobTask): date = luigi.DateParameter(default=datetime.date.today()) # ... ``` By doing this, Luigi can take care of all the boilerplate code that would normally be needed in the constructor. Internally, the DailyReport object can now be constructed by running `DailyReport(datetime.date(2012, 5, 10))` or just `DailyReport()`. Luigi also creates a command line parser that automatically handles the conversion from strings to Python types. This way you can invoke the job on the command line eg. by passing `--date 2012-05-10`. The parameters are all set to their values on the Task object instance, i.e. ``` d = DailyReport(datetime.date(2012, 5, 10)) print(d.date) ``` will return the same date that the object was constructed with. Same goes if you invoke Luigi on the command line. ### Instance caching[¶](#instance-caching) Tasks are uniquely identified by their class name and values of their parameters. In fact, within the same worker, two tasks of the same class with parameters of the same values are not just equal, but the same instance: ``` >>> import luigi >>> import datetime >>> class DateTask(luigi.Task): ... date = luigi.DateParameter() ... >>> a = datetime.date(2014, 1, 21) >>> b = datetime.date(2014, 1, 21) >>> a is b False >>> c = DateTask(date=a) >>> d = DateTask(date=b) >>> c DateTask(date=2014-01-21) >>> d DateTask(date=2014-01-21) >>> c is d True ``` ### Insignificant parameters[¶](#insignificant-parameters) If a parameter is created with `significant=False`, it is ignored as far as the Task signature is concerned. Tasks created with only insignificant parameters differing have the same signature but are not the same instance: ``` >>> class DateTask2(DateTask): ... other = luigi.Parameter(significant=False) ... >>> c = DateTask2(date=a, other="foo") >>> d = DateTask2(date=b, other="bar") >>> c DateTask2(date=2014-01-21) >>> d DateTask2(date=2014-01-21) >>> c.other 'foo' >>> d.other 'bar' >>> c is d False >>> hash(c) == hash(d) True ``` ### Parameter visibility[¶](#parameter-visibility) Using [`ParameterVisibility`](index.html#luigi.parameter.ParameterVisibility) you can configure parameter visibility. By default, all parameters are public, but you can also set them hidden or private. ``` >>> import luigi >>> from luigi.parameter import ParameterVisibility >>> luigi.Parameter(visibility=ParameterVisibility.PRIVATE) ``` `ParameterVisibility.PUBLIC` (default) - visible everywhere `ParameterVisibility.HIDDEN` - ignored in WEB-view, but saved into database if save db_history is true `ParameterVisibility.PRIVATE` - visible only inside task. ### Parameter types[¶](#parameter-types) In the examples above, the *type* of the parameter is determined by using different subclasses of [`Parameter`](index.html#luigi.parameter.Parameter). There are a few of them, like [`DateParameter`](index.html#luigi.parameter.DateParameter), [`DateIntervalParameter`](index.html#luigi.parameter.DateIntervalParameter), [`IntParameter`](index.html#luigi.parameter.IntParameter), [`FloatParameter`](index.html#luigi.parameter.FloatParameter), etc. Python is not a statically typed language and you don’t have to specify the types of any of your parameters. You can simply use the base class [`Parameter`](index.html#luigi.parameter.Parameter) if you don’t care. The reason you would use a subclass like [`DateParameter`](index.html#luigi.parameter.DateParameter) is that Luigi needs to know its type for the command line interaction. That’s how it knows how to convert a string provided on the command line to the corresponding type (i.e. datetime.date instead of a string). ### Setting parameter value for other classes[¶](#setting-parameter-value-for-other-classes) All parameters are also exposed on a class level on the command line interface. For instance, say you have classes TaskA and TaskB: ``` class TaskA(luigi.Task): x = luigi.Parameter() class TaskB(luigi.Task): y = luigi.Parameter() ``` You can run `TaskB` on the command line: `luigi TaskB --y 42`. But you can also set the class value of `TaskA` by running `luigi TaskB --y 42 --TaskA-x 43`. This sets the value of `TaskA.x` to 43 on a *class* level. It is still possible to override it inside Python if you instantiate `TaskA(x=44)`. All parameters can also be set from the configuration file. For instance, you can put this in the config: ``` [TaskA] x: 45 ``` Just as in the previous case, this will set the value of `TaskA.x` to 45 on the *class* level. And likewise, it is still possible to override it inside Python if you instantiate `TaskA(x=44)`. ### Parameter resolution order[¶](#parameter-resolution-order) Parameters are resolved in the following order of decreasing priority: 1. Any value passed to the constructor, or task level value set on the command line (applies on an instance level) 2. Any value set on the command line (applies on a class level) 3. Any configuration option (applies on a class level) 4. Any default value provided to the parameter (applies on a class level) See the [`Parameter`](index.html#luigi.parameter.Parameter) class for more information. Running Luigi[¶](#running-luigi) --- ### Running from the Command Line[¶](#running-from-the-command-line) The preferred way to run Luigi tasks is through the `luigi` command line tool that will be installed with the pip package. ``` # my_module.py, available in your sys.path import luigi class MyTask(luigi.Task): x = luigi.IntParameter() y = luigi.IntParameter(default=45) def run(self): print(self.x + self.y) ``` Should be run like this ``` $ luigi --module my_module MyTask --x 123 --y 456 --local-scheduler ``` Or alternatively like this: ``` $ python -m luigi --module my_module MyTask --x 100 --local-scheduler ``` Note that if a parameter name contains ‘_’, it should be replaced by ‘-‘. For example, if MyTask had a parameter called ‘my_parameter’: ``` $ luigi --module my_module MyTask --my-parameter 100 --local-scheduler ``` Note Please make sure to always place task parameters behind the task family! ### Running from Python code[¶](#running-from-python-code) Another way to start tasks from Python code is using `luigi.build(tasks, worker_scheduler_factory=None, **env_params)` from `luigi.interface` module. This way of running luigi tasks is useful if you want to get some dynamic parameters from another source, such as database, or provide additional logic before you start tasks. One notable difference is that `build` defaults to not using the identical process lock. If you want to change this behaviour, just pass `no_lock=False`. ``` class MyTask1(luigi.Task): x = luigi.IntParameter() y = luigi.IntParameter(default=0) def run(self): print(self.x + self.y) class MyTask2(luigi.Task): x = luigi.IntParameter() y = luigi.IntParameter(default=1) z = luigi.IntParameter(default=2) def run(self): print(self.x * self.y * self.z) if __name__ == '__main__': luigi.build([MyTask1(x=10), MyTask2(x=15, z=3)]) ``` Also, it is possible to pass additional parameters to `build` such as host, port, workers and local_scheduler: ``` if __name__ == '__main__': luigi.build([MyTask1(x=1)], workers=5, local_scheduler=True) ``` To achieve some special requirements you can pass to `build` your `worker_scheduler_factory` which will return your worker and/or scheduler implementations: ``` class MyWorker(Worker): # some custom logic class MyFactory(object): def create_local_scheduler(self): return scheduler.Scheduler(prune_on_get_work=True, record_task_history=False) def create_remote_scheduler(self, url): return rpc.RemoteScheduler(url) def create_worker(self, scheduler, worker_processes, assistant=False): # return your worker instance return MyWorker( scheduler=scheduler, worker_processes=worker_processes, assistant=assistant) if __name__ == '__main__': luigi.build([MyTask1(x=1)], worker_scheduler_factory=MyFactory()) ``` In some cases (like task queue) it may be useful. ### Response of luigi.build()/luigi.run()[¶](#response-of-luigi-build-luigi-run) * **Default response** By default *luigi.build()/luigi.run()* returns True if there were no scheduling errors. This is the same as the attribute `LuigiRunResult.scheduling_succeeded`. * **Detailed response** This is a response of type [`LuigiRunResult`](index.html#luigi.execution_summary.LuigiRunResult). This is obtained by passing a keyword argument `detailed_summary=True` to *build/run*. This response contains detailed information about the jobs. ``` if __name__ == '__main__': luigi_run_result = luigi.build(..., detailed_summary=True) print(luigi_run_result.summary_text) ``` ### Luigi on Windows[¶](#luigi-on-windows) Most Luigi functionality works on Windows. Exceptions: * Specifying multiple worker processes using the `workers` argument for `luigi.build`, or using the `--workers` command line argument. (Similarly, specifying `--worker-force-multiprocessing`). For most programs, this will result in failure (a common sight is `BrokenPipeError`). The reason is that worker processes are assumed to be forked from the main process. Forking is [not possible](https://docs.python.org/dev/library/multiprocessing.html#contexts-and-start-methods) on Windows. * Running the Luigi central scheduling server as a daemon (i.e. with `--background`). Again, a Unix-only concept. Using the Central Scheduler[¶](#using-the-central-scheduler) --- While the `--local-scheduler` flag is useful for development purposes, it’s not recommended for production usage. The centralized scheduler serves two purposes: * Make sure two instances of the same task are not running simultaneously * Provide visualization of everything that’s going on. Note that the central scheduler does not execute anything for you or help you with job parallelization. For running tasks periodically, the easiest thing to do is to trigger a Python script from cron or from a continuously running process. There is no central process that automatically triggers jobs. This model may seem limited, but we believe that it makes things far more intuitive and easy to understand. ### The luigid server[¶](#the-luigid-server) To run the server as a daemon run: ``` $ luigid --background --pidfile <PATH_TO_PIDFILE> --logdir <PATH_TO_LOGDIR> --state-path <PATH_TO_STATEFILE> ``` Note that this requires `python-daemon`. By default, the server starts on AF_INET and AF_INET6 port `8082` (which can be changed with the `--port` flag) and listens on all IPs. (To use an AF_UNIX socket use the `--unix-socket` flag) For a full list of configuration options and defaults, see the [scheduler configuration section](index.html#scheduler-config). Note that `luigid` uses the same configuration files as the Luigi client (i.e. `luigi.cfg` or `/etc/luigi/client.cfg` by default). ### Enabling Task History[¶](#enabling-task-history) Task History is an experimental feature in which additional information about tasks that have been executed are recorded in a relational database for historical analysis. This information is exposed via the Central Scheduler at `/history`. To enable the task history, specify `record_task_history = True` in the `[scheduler]` section of `luigi.cfg` and specify `db_connection` under `[task_history]`. The `db_connection` string is used to configure the [SQLAlchemy engine](http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html). When starting up, `luigid` will create all the necessary tables using [create_all](http://docs.sqlalchemy.org/en/rel_0_9/core/metadata.html#sqlalchemy.schema.MetaData.create_all). Example configuration ``` [scheduler] record_task_history = True state_path = /usr/local/var/luigi-state.pickle [task_history] db_connection = sqlite:////usr/local/var/luigi-task-hist.db ``` The task history has the following pages: * `/history` a reverse-cronological listing of runs from the past 24 hours. Example screenshot: > * `/history/by_id/:id` detailed information about a run, including: parameter values, the host on which it ran, and timing information. Example screenshot: > * `/history/by_name/:name` a listing of all runs of a task with the given task name. Example screenshot: > * `/history/by_params/:name?data=params` a listing of all runs of a given task restricted to runs with param values matching the given data. The data is a json blob describing the parameters, e.g. `{"foo": "bar"}` looks for a task with `foo=bar`. Execution Model[¶](#execution-model) --- Luigi has a quite simple model for execution and triggering. ### Workers and task execution[¶](#workers-and-task-execution) The most important aspect is that *no execution is transferred*. When you run a Luigi workflow, the worker schedules all tasks, and also executes the tasks within the process. The benefit of this scheme is that it’s super easy to debug since all execution takes place in the process. It also makes deployment a non-event. During development, you typically run the Luigi workflow from the command line, whereas when you deploy it, you can trigger it using crontab or any other scheduler. The downside is that Luigi doesn’t give you scalability for free. In practice this is not a problem until you start running thousands of tasks. Isn’t the point of Luigi to automate and schedule these workflows? To some extent. Luigi helps you *encode the dependencies* of tasks and build up chains. Furthermore, Luigi’s scheduler makes sure that there’s a centralized view of the dependency graph and that the same job will not be executed by multiple workers simultaneously. ### Scheduler[¶](#scheduler) A client only starts the `run()` method of a task when the single-threaded central scheduler has permitted it. Since the number of tasks is usually very small (in comparison with the petabytes of data one task is processing), we can afford the convenience of a simple centralised server. The gif is from [this presentation](https://tarrasch.github.io/luigid-basics-jun-2015/), which is about the client and server interaction. ### Triggering tasks[¶](#triggering-tasks) Luigi does not include its own triggering, so you have to rely on an external scheduler such as crontab to actually trigger the workflows. In practice, it’s not a big hurdle because Luigi avoids all the mess typically caused by it. Scheduling a complex workflow is fairly trivial using eg. crontab. In the future, Luigi might implement its own triggering. The dependency on crontab (or any external triggering mechanism) is a bit awkward and it would be nice to avoid. #### Trigger example[¶](#trigger-example) For instance, if you have an external data dump that arrives every day and that your workflow depends on it, you write a workflow that depends on this data dump. Crontab can then trigger this workflow *every minute* to check if the data has arrived. If it has, it will run the full dependency graph. ``` # my_tasks.py class DataDump(luigi.ExternalTask): date = luigi.DateParameter() def output(self): return luigi.contrib.hdfs.HdfsTarget(self.date.strftime('/var/log/dump/%Y-%m-%d.txt')) class AggregationTask(luigi.Task): date = luigi.DateParameter() window = luigi.IntParameter() def requires(self): return [DataDump(self.date - datetime.timedelta(i)) for i in xrange(self.window)] def run(self): run_some_cool_stuff(self.input()) def output(self): return luigi.contrib.hdfs.HdfsTarget('/aggregated-%s-%d' % (self.date, self.window)) class RunAll(luigi.Task): ''' Dummy task that triggers execution of a other tasks''' def requires(self): for window in [3, 7, 14]: for d in xrange(10): # guarantee that aggregations were run for the past 10 days yield AggregationTask(datetime.date.today() - datetime.timedelta(d), window) ``` In your cronline you would then have something like ``` 30 0 * * * my-user luigi RunAll --module my_tasks ``` You can trigger this as much as you want from crontab, and even across multiple machines, because the central scheduler will make sure at most one of each `AggregationTask` task is run simultaneously. Note that this might actually mean multiple tasks can be run because there are instances with different parameters, and this can give you some form of parallelization (eg. `AggregationTask(2013-01-09)` might run in parallel with `AggregationTask(2013-01-08)`). Of course, some Task types (eg. `HadoopJobTask`) can transfer execution to other places, but this is up to each Task to define. Luigi Patterns[¶](#luigi-patterns) --- ### Code Reuse[¶](#code-reuse) One nice thing about Luigi is that it’s super easy to depend on tasks defined in other repos. It’s also trivial to have “forks” in the execution path, where the output of one task may become the input of many other tasks. Currently, no semantics for “intermediate” output is supported, meaning that all output will be persisted indefinitely. The upside of that is that if you try to run X -> Y, and Y crashes, you can resume with the previously built X. The downside is that you will have a lot of intermediate results on your file system. A useful pattern is to put these files in a special directory and have some kind of periodical garbage collection clean it up. ### Triggering Many Tasks[¶](#triggering-many-tasks) A convenient pattern is to have a dummy Task at the end of several dependency chains, so you can trigger a multitude of pipelines by specifying just one task in command line, similarly to how e.g. [make](http://www.gnu.org/software/make/) works. ``` class AllReports(luigi.WrapperTask): date = luigi.DateParameter(default=datetime.date.today()) def requires(self): yield SomeReport(self.date) yield SomeOtherReport(self.date) yield CropReport(self.date) yield TPSReport(self.date) yield FooBarBazReport(self.date) ``` This simple task will not do anything itself, but will invoke a bunch of other tasks. Per each invocation, Luigi will perform as many of the pending jobs as possible (those which have all their dependencies present). You’ll need to use [`WrapperTask`](index.html#luigi.task.WrapperTask) for this instead of the usual Task class, because this job will not produce any output of its own, and as such needs a way to indicate when it’s complete. This class is used for tasks that only wrap other tasks and that by definition are done if all their requirements exist. ### Triggering recurring tasks[¶](#triggering-recurring-tasks) A common requirement is to have a daily report (or something else) produced every night. Sometimes for various reasons tasks will keep crashing or lacking their required dependencies for more than a day though, which would lead to a missing deliverable for some date. Oops. To ensure that the above AllReports task is eventually completed for every day (value of date parameter), one could e.g. add a loop in requires method to yield dependencies on the past few days preceding self.date. Then, so long as Luigi keeps being invoked, the backlog of jobs would catch up nicely after fixing intermittent problems. Luigi actually comes with a reusable tool for achieving this, called [`RangeDailyBase`](index.html#luigi.tools.range.RangeDailyBase) (resp. [`RangeHourlyBase`](index.html#luigi.tools.range.RangeHourlyBase)). Simply putting ``` luigi --module all_reports RangeDailyBase --of AllReports --start 2015-01-01 ``` in your crontab will easily keep gaps from occurring from 2015-01-01 onwards. NB - it will not always loop over everything from 2015-01-01 till current time though, but rather a maximum of 3 months ago by default - see [`RangeDailyBase`](index.html#luigi.tools.range.RangeDailyBase) documentation for this and more knobs for tweaking behavior. See also Monitoring below. ### Efficiently triggering recurring tasks[¶](#efficiently-triggering-recurring-tasks) RangeDailyBase, described above, is named like that because a more efficient subclass exists, [`RangeDaily`](index.html#luigi.tools.range.RangeDaily) (resp. [`RangeHourly`](index.html#luigi.tools.range.RangeHourly)), tailored for hundreds of task classes scheduled concurrently with contiguousness requirements spanning years (which would incur redundant completeness checks and scheduler overload using the naive looping approach.) Usage: ``` luigi --module all_reports RangeDaily --of AllReports --start 2015-01-01 ``` It has the same knobs as RangeDailyBase, with some added requirements. Namely the task must implement an efficient bulk_complete method, or must be writing output to file system Target with date parameter value consistently represented in the file path. ### Backfilling tasks[¶](#backfilling-tasks) Also a common use case, sometimes you have tweaked existing recurring task code and you want to schedule recomputation of it over an interval of dates for that or another reason. Most conveniently it is achieved with the above described range tools, just with both start (inclusive) and stop (exclusive) parameters specified: ``` luigi --module all_reports RangeDaily --of AllReportsV2 --start 2014-10-31 --stop 2014-12-25 ``` ### Propagating parameters with Range[¶](#propagating-parameters-with-range) Some tasks you want to recur may include additional parameters which need to be configured. The Range classes provide a parameter which accepts a [`DictParameter`](index.html#luigi.parameter.DictParameter) and passes any parameters onwards for this purpose. ``` luigi RangeDaily --of MyTask --start 2014-10-31 --of-params '{"my_string_param": "123", "my_int_param": 123}' ``` Alternatively, you can specify parameters at the task family level (as described [here](index.html#parameter-class-level-parameters)), however these will not appear in the task name for the upstream Range task which can have implications in how the scheduler and visualizer handle task instances. ``` luigi RangeDaily --of MyTask --start 2014-10-31 --MyTask-my-param 123 ``` ### Batching multiple parameter values into a single run[¶](#batching-multiple-parameter-values-into-a-single-run) Sometimes it’ll be faster to run multiple jobs together as a single batch rather than running them each individually. When this is the case, you can mark some parameters with a batch_method in their constructor to tell the worker how to combine multiple values. One common way to do this is by simply running the maximum value. This is good for tasks that overwrite older data when a newer one runs. You accomplish this by setting the batch_method to max, like so: ``` class A(luigi.Task): date = luigi.DateParameter(batch_method=max) ``` What’s exciting about this is that if you send multiple As to the scheduler, it can combine them and return one. So if `A(date=2016-07-28)`, `A(date=2016-07-29)` and `A(date=2016-07-30)` are all ready to run, you will start running `A(date=2016-07-30)`. While this is running, the scheduler will show `A(date=2016-07-28)`, `A(date=2016-07-29)` as batch running while `A(date=2016-07-30)` is running. When `A(date=2016-07-30)` is done running and becomes FAILED or DONE, the other two tasks will be updated to the same status. If you want to limit how big a batch can get, simply set max_batch_size. So if you have ``` class A(luigi.Task): date = luigi.DateParameter(batch_method=max) max_batch_size = 10 ``` then the scheduler will batch at most 10 jobs together. You probably do not want to do this with the max batch method, but it can be helpful if you use other methods. You can use any method that takes a list of parameter values and returns a single parameter value. If you have two max batch parameters, you’ll get the max values for both of them. If you have parameters that don’t have a batch method, they’ll be aggregated separately. So if you have a class like ``` class A(luigi.Task): p1 = luigi.IntParameter(batch_method=max) p2 = luigi.IntParameter(batch_method=max) p3 = luigi.IntParameter() ``` and you create tasks `A(p1=1, p2=2, p3=0)`, `A(p1=2, p2=3, p3=0)`, `A(p1=3, p2=4, p3=1)`, you’ll get them batched as `A(p1=2, p2=3, p3=0)` and `A(p1=3, p2=4, p3=1)`. Note that batched tasks do not take up [[resources]](index.html#resources-config), only the task that ends up running will use resources. The scheduler only checks that there are sufficient resources for each task individually before batching them all together. ### Tasks that regularly overwrite the same data source[¶](#tasks-that-regularly-overwrite-the-same-data-source) If you are overwriting of the same data source with every run, you’ll need to ensure that two batches can’t run at the same time. You can do this pretty easily by setting batch_method to max and setting a unique resource: ``` class A(luigi.Task): date = luigi.DateParameter(batch_method=max) resources = {'overwrite_resource': 1} ``` Now if you have multiple tasks such as `A(date=2016-06-01)`, `A(date=2016-06-02)`, `A(date=2016-06-03)`, the scheduler will just tell you to run the highest available one and mark the lower ones as batch_running. Using a unique resource will prevent multiple tasks from writing to the same location at the same time if a new one becomes available while others are running. ### Avoiding concurrent writes to a single file[¶](#avoiding-concurrent-writes-to-a-single-file) Updating a single file from several tasks is almost always a bad idea, and you need to be very confident that no other good solution exists before doing this. If, however, you have no other option, then you will probably at least need to ensure that no two tasks try to write to the file _simultaneously_. By turning ‘resources’ into a Python property, it can return a value dependent on the task parameters or other dynamic attributes: ``` class A(luigi.Task): ... @property def resources(self): return { self.important_file_name: 1 } ``` Since, by default, resources have a usage limit of 1, no two instances of Task A will now run if they have the same important_file_name property. ### Decreasing resources of running tasks[¶](#decreasing-resources-of-running-tasks) At scheduling time, the luigi scheduler needs to be aware of the maximum resource consumption a task might have once it runs. For some tasks, however, it can be beneficial to decrease the amount of consumed resources between two steps within their run method (e.g. after some heavy computation). In this case, a different task waiting for that particular resource can already be scheduled. ``` class A(luigi.Task): # set maximum resources a priori resources = {"some_resource": 3} def run(self): # do something ... # decrease consumption of "some_resource" by one self.decrease_running_resources({"some_resource": 1}) # continue with reduced resources ... ``` ### Monitoring task pipelines[¶](#monitoring-task-pipelines) Luigi comes with some existing ways in [`luigi.notifications`](index.html#module-luigi.notifications) to receive notifications whenever tasks crash. Email is the most common way. The above mentioned range tools for recurring tasks not only implement reliable scheduling for you, but also emit events which you can use to set up delay monitoring. That way you can implement alerts for when jobs are stuck for prolonged periods lacking input data or otherwise requiring attention. ### Atomic Writes Problem[¶](#atomic-writes-problem) A very common mistake done by luigi plumbers is to write data partially to the final destination, that is, not atomically. The problem arises because completion checks in luigi are exactly as naive as running [`luigi.target.Target.exists()`](index.html#luigi.target.Target.exists). And in many cases it just means to check if a folder exist on disk. During the time we have partially written data, a task depending on that output would think its input is complete. This can have devestating effects, as in [the thanksgiving bug](http://tarrasch.github.io/luigi-budapest-bi-oct-2015/#/21). The concept can be illustrated by imagining that we deal with data stored on local disk and by running commands: ``` # This the BAD way $ mkdir /outputs/final_output $ big-slow-calculation > /outputs/final_output/foo.data ``` As stated earlier, the problem is that only partial data exists for a duration, yet we consider the data to be [`complete()`](index.html#luigi.task.Task.complete) because the output folder already exists. Here is a robust version of this: ``` # This is the good way $ mkdir /outputs/final_output-tmp-123456 $ big-slow-calculation > /outputs/final_output-tmp-123456/foo.data $ mv --no-target-directory --no-clobber /outputs/final_output{-tmp-123456,} $ [[ -d /outputs/final_output-tmp-123456 ]] && rm -r /outputs/final_output-tmp-123456 ``` Indeed, the good way is not as trivial. It involves coming up with a unique directory name and a pretty complex `mv` line, the reason `mv` need all those is because we don’t want `mv` to move a directory into a potentially existing directory. A directory could already exist in exceptional cases, for example when central locking fails and the same task would somehow run twice at the same time. Lastly, in the exceptional case where the file was never moved, one might want to remove the temporary directory that never got used. Note that this was an example where the storage was on local disk. But for every storage (hard disk file, hdfs file, database table, etc.) this procedure will look different. But do every luigi user need to implement that complexity? Nope, thankfully luigi developers are aware of these and luigi comes with many built-in solutions. In the case of you’re dealing with a file system ([`FileSystemTarget`](index.html#luigi.target.FileSystemTarget)), you should consider using [`temporary_path()`](index.html#luigi.target.FileSystemTarget.temporary_path). For other targets, you should ensure that the way you’re writing your final output directory is atomic. ### Sending messages to tasks[¶](#sending-messages-to-tasks) The central scheduler is able to send messages to particular tasks. When a running task accepts messages, it can access a [multiprocessing.Queue](https://docs.python.org/3/library/multiprocessing.html#pipes-and-queues) object storing incoming messages. You can implement custom behavior to react and respond to messages: ``` class Example(luigi.Task): # common task setup ... # configure the task to accept all incoming messages accepts_messages = True def run(self): # this example runs some loop and listens for the # "terminate" message, and responds to all other messages for _ in some_loop(): # check incomming messages if not self.scheduler_messages.empty(): msg = self.scheduler_messages.get() if msg.content == "terminate": break else: msg.respond("unknown message") # finalize ... ``` Messages can be sent right from the scheduler UI which also displays responses (if any). Note that this feature is only available when the scheduler is configured to send messages (see the [[scheduler]](index.html#scheduler-config) config), and the task is configured to accept them. Configuration[¶](#configuration) --- All configuration can be done by adding configuration files. Supported config parsers: * `cfg` (default), based on Python’s standard [ConfigParser](https://docs.python.org/3/library/configparser.html). Values may refer to environment variables using `${ENVVAR}` syntax. * `toml` You can choose right parser via `LUIGI_CONFIG_PARSER` environment variable. For example, `LUIGI_CONFIG_PARSER=toml`. Default (cfg) parser are looked for in: * `/etc/luigi/client.cfg` (deprecated) * `/etc/luigi/luigi.cfg` * `client.cfg` (deprecated) * `luigi.cfg` * `LUIGI_CONFIG_PATH` environment variable [TOML](https://github.com/toml-lang/toml) parser are looked for in: * `/etc/luigi/luigi.toml` * `luigi.toml` * `LUIGI_CONFIG_PATH` environment variable Both config lists increase in priority (from low to high). The order only matters in case of key conflicts (see docs for [ConfigParser.read](https://docs.python.org/3.6/library/configparser.html#configparser.ConfigParser.read)). These files are meant for both the client and `luigid`. If you decide to specify your own configuration you should make sure that both the client and `luigid` load it properly. The config file is broken into sections, each controlling a different part of the config. Example cfg config: ``` [hadoop] version=cdh4 streaming_jar=/usr/lib/hadoop-xyz/hadoop-streaming-xyz-123.jar [core] scheduler_host=luigi-host.mycompany.foo ``` Example toml config: ``` [hadoop] version = "cdh4" streaming_jar = "/usr/lib/hadoop-xyz/hadoop-streaming-xyz-123.jar" [core] scheduler_host = "luigi-host.mycompany.foo" ``` Also see [examples/config.toml](https://github.com/spotify/luigi/blob/master/examples/config.toml) for more complex example. ### Parameters from config Ingestion[¶](#parameters-from-config-ingestion) All parameters can be overridden from configuration files. For instance if you have a Task definition: ``` class DailyReport(luigi.contrib.hadoop.JobTask): date = luigi.DateParameter(default=datetime.date.today()) # ... ``` Then you can override the default value for `DailyReport().date` by providing it in the configuration: ``` [DailyReport] date=2012-01-01 ``` #### Configuration classes[¶](#configuration-classes) Using the [Parameters from config Ingestion](#paramconfigingestion) method, we derive the conventional way to do global configuration. Imagine this configuration. ``` [mysection] option=hello intoption=123 ``` We can create a [`Config`](index.html#luigi.Config) class: ``` import luigi # Config classes should be camel cased class mysection(luigi.Config): option = luigi.Parameter(default='world') intoption = luigi.IntParameter(default=555) mysection().option mysection().intoption ``` ### Configurable options[¶](#configurable-options) Luigi comes with a lot of configurable options. Below, we describe each section and the parameters available within it. ### [core][¶](#core) These parameters control core Luigi behavior, such as error e-mails and interactions between the worker and scheduler. autoload_range New in version 2.8.11. If false, prevents range tasks from autoloading. They can still be loaded using `--module luigi.tools.range`. Defaults to true. Setting this to true explicitly disables the deprecation warning. default_scheduler_host Hostname of the machine running the scheduler. Defaults to localhost. default_scheduler_port Port of the remote scheduler api process. Defaults to 8082. default_scheduler_url Full path to remote scheduler. Defaults to `http://localhost:8082/`. For TLS support use the URL scheme: `https`, example: `https://luigi.example.com:443/` (Note: you will have to terminate TLS using an HTTP proxy) You can also use this to connect to a local Unix socket using the non-standard URI scheme: `http+unix` example: `http+unix://%2Fvar%2Frun%2Fluigid%2Fluigid.sock/` hdfs_tmp_dir Base directory in which to store temporary files on hdfs. Defaults to tempfile.gettempdir() history_filename If set, specifies a filename for Luigi to write stuff (currently just job id) to in mapreduce job’s output directory. Useful in a configuration where no history is stored in the output directory by Hadoop. log_level The default log level to use when no logging_conf_file is set. Must be a valid name of a [Python log level](https://docs.python.org/2/library/logging.html#logging-levels). Default is `DEBUG`. logging_conf_file Location of the logging configuration file. max_shown_tasks New in version 1.0.20. The maximum number of tasks returned in a task_list api call. This will restrict the number of tasks shown in task lists in the visualiser. Small values can alleviate frozen browsers when there are too many done tasks. This defaults to 100000 (one hundred thousand). max_graph_nodes New in version 2.0.0. The maximum number of nodes returned by a dep_graph or inverse_dep_graph api call. Small values can greatly speed up graph display in the visualiser by limiting the number of nodes shown. Some of the nodes that are not sent to the visualiser will still show up as dependencies of nodes that were sent. These nodes are given TRUNCATED status. no_configure_logging If true, logging is not configured. Defaults to false. parallel_scheduling If true, the scheduler will compute complete functions of tasks in parallel using multiprocessing. This can significantly speed up scheduling, but requires that all tasks can be pickled. Defaults to false. parallel_scheduling_processes The number of processes to use for parallel scheduling. If not specified the default number of processes will be the total number of CPUs available. rpc_connect_timeout Number of seconds to wait before timing out when making an API call. Defaults to 10.0 rpc_retry_attempts The maximum number of retries to connect the central scheduler before giving up. Defaults to 3 rpc_retry_wait Number of seconds to wait before the next attempt will be started to connect to the central scheduler between two retry attempts. Defaults to 30 ### [cors][¶](#cors) New in version 2.8.0. These parameters control `/api/<method>` `CORS` behaviour (see: [W3C Cross-Origin Resource Sharing](http://www.w3.org/TR/cors/)). enabled Enables CORS support. Defaults to false. allowed_origins A list of allowed origins. Used only if `allow_any_origin` is false. Configure in JSON array format, e.g. [“foo”, “bar”]. Defaults to empty. allow_any_origin Accepts requests from any origin. Defaults to false. allow_null_origin Allows the request to set `null` value of the `Origin` header. Defaults to false. max_age Content of `Access-Control-Max-Age`. Defaults to 86400 (24 hours). allowed_methods Content of `Access-Control-Allow-Methods`. Defaults to `GET, OPTIONS`. allowed_headers Content of `Access-Control-Allow-Headers`. Defaults to `Accept, Content-Type, Origin`. exposed_headers Content of `Access-Control-Expose-Headers`. Defaults to empty string (will NOT be sent as a response header). allow_credentials Indicates that the actual request can include user credentials. Defaults to false. ### [worker][¶](#worker) These parameters control Luigi worker behavior. count_uniques If true, workers will only count unique pending jobs when deciding whether to stay alive. So if a worker can’t get a job to run and other workers are waiting on all of its pending jobs, the worker will die. `worker_keep_alive` must be `true` for this to have any effect. Defaults to false. keep_alive If true, workers will stay alive when they run out of jobs to run, as long as they have some pending job waiting to be run. Defaults to false. ping_interval Number of seconds to wait between pinging scheduler to let it know that the worker is still alive. Defaults to 1.0. task_limit New in version 1.0.25. Maximum number of tasks to schedule per invocation. Upon exceeding it, the worker will issue a warning and proceed with the workflow obtained thus far. Prevents incidents due to spamming of the scheduler, usually accidental. Default: no limit. timeout New in version 1.0.20. Number of seconds after which to kill a task which has been running for too long. This provides a default value for all tasks, which can be overridden by setting the `worker_timeout` property in any task. Default value is 0, meaning no timeout. wait_interval Number of seconds for the worker to wait before asking the scheduler for another job after the scheduler has said that it does not have any available jobs. wait_jitter Size of jitter to add to the worker wait interval such that the multiple workers do not ask the scheduler for another job at the same time. Default: 5.0 max_keep_alive_idle_duration New in version 2.8.4. Maximum duration to keep worker alive while in idle state. Default: 0 (Indefinitely) max_reschedules The maximum number of times that a job can be automatically rescheduled by a worker before it will stop trying. Workers will reschedule a job if it is found to not be done when attempting to run a dependent job. This defaults to 1. retry_external_tasks If true, incomplete external tasks (i.e. tasks where the `run()` method is NotImplemented) will be retested for completion while Luigi is running. This means that if external dependencies are satisfied after a workflow has started, any tasks dependent on that resource will be eligible for running. Note: Every time the task remains incomplete, it will count as FAILED, so normal retry logic applies (see: `retry_count` and `retry_delay`). This setting works best with `worker_keep_alive: true`. If false, external tasks will only be evaluated when Luigi is first invoked. In this case, Luigi will not check whether external dependencies are satisfied while a workflow is in progress, so dependent tasks will remain PENDING until the workflow is reinvoked. Defaults to false for backwards compatibility. no_install_shutdown_handler By default, workers will stop requesting new work and finish running pending tasks after receiving a `SIGUSR1` signal. This provides a hook for gracefully shutting down workers that are in the process of running (potentially expensive) tasks. If set to true, Luigi will NOT install this shutdown hook on workers. Note this hook does not work on Windows operating systems, or when jobs are launched outside the main execution thread. Defaults to false. send_failure_email Controls whether the worker will send e-mails on task and scheduling failures. If set to false, workers will only send e-mails on framework errors during scheduling and all other e-mail must be handled by the scheduler. Defaults to true. check_unfulfilled_deps If true, the worker checks for completeness of dependencies before running a task. In case unfulfilled dependencies are detected, an exception is raised and the task will not run. This mechanism is useful to detect situations where tasks do not create their outputs properly, or when targets were removed after the dependency tree was built. It is recommended to disable this feature only when the completeness checks are known to be bottlenecks, e.g. when the `exists()` calls of the dependencies’ outputs are resource-intensive. Defaults to true. force_multiprocessing By default, luigi uses multiprocessing when *more than one* worker process is requested. When set to true, multiprocessing is used independent of the the number of workers. Defaults to false. ### [elasticsearch][¶](#elasticsearch) These parameters control use of elasticsearch marker_index Defaults to “update_log”. marker_doc_type Defaults to “entry”. ### [email][¶](#email) General parameters force_send If true, e-mails are sent in all run configurations (even if stdout is connected to a tty device). Defaults to False. format Type of e-mail to send. Valid values are “plain”, “html” and “none”. When set to html, tracebacks are wrapped in <pre> tags to get fixed- width font. When set to none, no e-mails will be sent. Default value is plain. method Valid values are “smtp”, “sendgrid”, “ses” and “sns”. SES and SNS are services of Amazon web services. SendGrid is an email delivery service. The default value is “smtp”. In order to send messages through Amazon SNS or SES set up your AWS config files or run Luigi on an EC2 instance with proper instance profile. In order to use sendgrid, fill in your sendgrid API key in the [[sendgrid]](#sendgrid) section. In order to use smtp, fill in the appropriate fields in the [[smtp]](#smtp) section. prefix Optional prefix to add to the subject line of all e-mails. For example, setting this to “[LUIGI]” would change the subject line of an e-mail from “Luigi: Framework error” to “[LUIGI] Luigi: Framework error” receiver Recipient of all error e-mails. If this is not set, no error e-mails are sent when Luigi crashes unless the crashed job has owners set. If Luigi is run from the command line, no e-mails will be sent unless output is redirected to a file. Set it to SNS Topic ARN if you want to receive notifications through Amazon SNS. Make sure to set method to sns in this case too. sender User name in from field of error e-mails. Default value: luigi-client@<server_name### [batch_notifier][¶](#batch-notifier) Parameters controlling the contents of batch notifications sent from the scheduler email_interval Number of minutes between e-mail sends. Making this larger results in fewer, bigger e-mails. Defaults to 60. batch_mode Controls how tasks are grouped together in the e-mail. Suppose we have the following sequence of failures: 1. TaskA(a=1, b=1) 2. TaskA(a=1, b=1) 3. TaskA(a=2, b=1) 4. TaskA(a=1, b=2) 5. TaskB(a=1, b=1) For any setting of batch_mode, the batch e-mail will record 5 failures and mention them in the subject. The difference is in how they will be displayed in the body. Here are example bodies with error_messages set to 0. “all” only groups together failures for the exact same task: * TaskA(a=1, b=1) (2 failures) * TaskA(a=1, b=2) (1 failure) * TaskA(a=2, b=1) (1 failure) * TaskB(a=1, b=1) (1 failure) “family” groups together failures for tasks of the same family: * TaskA (4 failures) * TaskB (1 failure) “unbatched_params” groups together tasks that look the same after removing batched parameters. So if TaskA has a batch_method set for parameter a, we get the following: * TaskA(b=1) (3 failures) * TaskA(b=2) (1 failure) * TaskB(a=1, b=2) (1 failure) Defaults to “unbatched_params”, which is identical to “all” if you are not using batched parameters. error_lines Number of lines to include from each error message in the batch e-mail. This can be used to keep e-mails shorter while preserving the more useful information usually found near the bottom of stack traces. This can be set to 0 to include all lines. If you don’t wish to see error messages, instead set `error_messages` to 0. Defaults to 20. error_messages Number of messages to preserve for each task group. As most tasks that fail repeatedly do so for similar reasons each time, it’s not usually necessary to keep every message. This controls how many messages are kept for each task or task group. The most recent error messages are kept. Set to 0 to not include error messages in the e-mails. Defaults to 1. group_by_error_messages Quite often, a system or cluster failure will cause many disparate task types to fail for the same reason. This can cause a lot of noise in the batch e-mails. This cuts down on the noise by listing items with identical error messages together. Error messages are compared after limiting by `error_lines`. Defaults to true. ### [hadoop][¶](#hadoop) Parameters controlling basic hadoop tasks command Name of command for running hadoop from the command line. Defaults to “hadoop” python_executable Name of command for running python from the command line. Defaults to “python” scheduler Type of scheduler to use when scheduling hadoop jobs. Can be “fair” or “capacity”. Defaults to “fair”. streaming_jar Path to your streaming jar. Must be specified to run streaming jobs. version Version of hadoop used in your cluster. Can be “cdh3”, “chd4”, or “apache1”. Defaults to “cdh4”. ### [hdfs][¶](#hdfs) Parameters controlling the use of snakebite to speed up hdfs queries. client Client to use for most hadoop commands. Options are “snakebite”, “snakebite_with_hadoopcli_fallback”, “webhdfs” and “hadoopcli”. Snakebite is much faster, so use of it is encouraged. webhdfs is fast and works with Python 3 as well, but has not been used that much in the wild. Both snakebite and webhdfs requires you to install it separately on the machine. Defaults to “hadoopcli”. client_version Optionally specifies hadoop client version for snakebite. effective_user Optionally specifies the effective user for snakebite. namenode_host The hostname of the namenode. Needed for snakebite if snakebite_autoconfig is not set. namenode_port The port used by snakebite on the namenode. Needed for snakebite if snakebite_autoconfig is not set. snakebite_autoconfig If true, attempts to automatically detect the host and port of the namenode for snakebite queries. Defaults to false. tmp_dir Path to where Luigi will put temporary files on hdfs ### [hive][¶](#hive) Parameters controlling hive tasks command Name of the command used to run hive on the command line. Defaults to “hive”. hiverc_location Optional path to hive rc file. metastore_host Hostname for metastore. metastore_port Port for hive to connect to metastore host. release If set to “apache”, uses a hive client that better handles apache hive output. All other values use the standard client Defaults to “cdh4”. ### [kubernetes][¶](#kubernetes) Parameters controlling Kubernetes Job Tasks auth_method Authorization method to access the cluster. Options are “[kubeconfig](http://kubernetes.io/docs/user-guide/service-accounts)” or “[service-account](http://kubernetes.io/docs/user-guide/kubeconfig-file)” kubeconfig_path Path to kubeconfig file, for cluster authentication. It defaults to `~/.kube/config`, which is the default location when using [minikube](http://kubernetes.io/docs/getting-started-guides/minikube). When auth_method is “service-account” this property is ignored. max_retrials Maximum number of retrials in case of job failure. ### [mysql][¶](#mysql) Parameters controlling use of MySQL targets marker_table Table in which to store status of table updates. This table will be created if it doesn’t already exist. Defaults to “table_updates”. ### [postgres][¶](#postgres) Parameters controlling the use of Postgres targets local_tmp_dir Directory in which to temporarily store data before writing to postgres. Uses system default if not specified. marker_table Table in which to store status of table updates. This table will be created if it doesn’t already exist. Defaults to “table_updates”. ### [redshift][¶](#redshift) Parameters controlling the use of Redshift targets marker_table Table in which to store status of table updates. This table will be created if it doesn’t already exist. Defaults to “table_updates”. ### [resources][¶](#resources) This section can contain arbitrary keys. Each of these specifies the amount of a global resource that the scheduler can allow workers to use. The scheduler will prevent running jobs with resources specified from exceeding the counts in this section. Unspecified resources are assumed to have limit 1. Example resources section for a configuration with 2 hive resources and 1 mysql resource: ``` [resources] hive=2 mysql=1 ``` Note that it was not necessary to specify the 1 for mysql here, but it is good practice to do so when you have a fixed set of resources. ### [retcode][¶](#retcode) Configure return codes for the Luigi binary. In the case of multiple return codes that could apply, for example a failing task and missing data, the *numerically greatest* return code is returned. We recommend that you copy this set of exit codes to your `luigi.cfg` file: ``` [retcode] # The following return codes are the recommended exit codes for Luigi # They are in increasing level of severity (for most applications) already_running=10 missing_data=20 not_run=25 task_failed=30 scheduling_error=35 unhandled_exception=40 ``` already_running This can happen in two different cases. Either the local lock file was taken at the time the invocation starts up. Or, the central scheduler have reported that some tasks could not have been run, because other workers are already running the tasks. missing_data For when an [`ExternalTask`](index.html#luigi.task.ExternalTask) is not complete, and this caused the worker to give up. As an alternative to fiddling with this, see the [worker] keep_alive option. not_run For when a task is not granted run permission by the scheduler. Typically because of lack of resources, because the task has been already run by another worker or because the attempted task is in DISABLED state. Connectivity issues with the central scheduler might also cause this. This does not include the cases for which a run is not allowed due to missing dependencies (missing_data) or due to the fact that another worker is currently running the task (already_running). task_failed For signaling that there were last known to have failed. Typically because some exception have been raised. scheduling_error For when a task’s `complete()` or `requires()` method fails with an exception, or when the limit number of tasks is reached. unhandled_exception For internal Luigi errors. Defaults to 4, since this type of error probably will not recover over time. If you customize return codes, prefer to set them in range 128 to 255 to avoid conflicts. Return codes in range 0 to 127 are reserved for possible future use by Luigi contributors. ### [scalding][¶](#scalding) Parameters controlling running of scalding jobs scala_home Home directory for scala on your machine. Defaults to either SCALA_HOME or /usr/share/scala if SCALA_HOME is unset. scalding_home Home directory for scalding on your machine. Defaults to either SCALDING_HOME or /usr/share/scalding if SCALDING_HOME is unset. scalding_provided Provided directory for scalding on your machine. Defaults to either SCALDING_HOME/provided or /usr/share/scalding/provided scalding_libjars Libjars directory for scalding on your machine. Defaults to either SCALDING_HOME/libjars or /usr/share/scalding/libjars ### [scheduler][¶](#scheduler) Parameters controlling scheduler behavior batch_emails Whether to send batch e-mails for failures and disables rather than sending immediate disable e-mails and just relying on workers to send immediate batch e-mails. Defaults to false. disable_hard_timeout Hard time limit after which tasks will be disabled by the server if they fail again, in seconds. It will disable the task if it fails **again** after this amount of time. E.g. if this was set to 600 (i.e. 10 minutes), and the task first failed at 10:00am, the task would be disabled if it failed again any time after 10:10am. Note: This setting does not consider the values of the `retry_count` or `disable_window_seconds` settings. retry_count Number of times a task can fail within `disable_window_seconds` before the scheduler will automatically disable it. If not set, the scheduler will not automatically disable jobs. disable_persist_seconds Number of seconds for which an automatic scheduler disable lasts. Defaults to 86400 (1 day). disable_window_seconds Number of seconds during which `retry_count` failures must occur in order for an automatic disable by the scheduler. The scheduler forgets about disables that have occurred longer ago than this amount of time. Defaults to 3600 (1 hour). record_task_history If true, stores task history in a database. Defaults to false. remove_delay Number of seconds to wait before removing a task that has no stakeholders. Defaults to 600 (10 minutes). retry_delay Number of seconds to wait after a task failure to mark it pending again. Defaults to 900 (15 minutes). state_path Path in which to store the Luigi scheduler’s state. When the scheduler is shut down, its state is stored in this path. The scheduler must be shut down cleanly for this to work, usually with a kill command. If the kill command includes the -9 flag, the scheduler will not be able to save its state. When the scheduler is started, it will load the state from this path if it exists. This will restore all scheduled jobs and other state from when the scheduler last shut down. Sometimes this path must be deleted when restarting the scheduler after upgrading Luigi, as old state files can become incompatible with the new scheduler. When this happens, all workers should be restarted after the scheduler both to become compatible with the updated code and to reschedule the jobs that the scheduler has now forgotten about. This defaults to /var/lib/luigi-server/state.pickle worker_disconnect_delay Number of seconds to wait after a worker has stopped pinging the scheduler before removing it and marking all of its running tasks as failed. Defaults to 60. pause_enabled If false, disables pause/unpause operations and hides the pause toggle from the visualiser. send_messages When true, the scheduler is allowed to send messages to running tasks and the central scheduler provides a simple prompt per task to send messages. Defaults to true. metrics_collector Optional setting allowing Luigi to use a contribution to collect metrics about the pipeline to a third-party. By default this uses the default metric collector that acts as a shell and does nothing. The currently available options are “datadog” and “prometheus”. ### [sendgrid][¶](#sendgrid) These parameters control sending error e-mails through SendGrid. apikey API key of the SendGrid account. ### [smtp][¶](#smtp) These parameters control the smtp server setup. host Hostname for sending mail through smtp. Defaults to localhost. local_hostname If specified, overrides the FQDN of localhost in the HELO/EHLO command. no_tls If true, connects to smtp without TLS. Defaults to false. password Password to log in to your smtp server. Must be specified for username to have an effect. port Port number for smtp on smtp_host. Defaults to 0. ssl If true, connects to smtp through SSL. Defaults to false. timeout Sets the number of seconds after which smtp attempts should time out. Defaults to 10. username Username to log in to your smtp server, if necessary. ### [spark][¶](#spark) Parameters controlling the default execution of [`SparkSubmitTask`](index.html#luigi.contrib.spark.SparkSubmitTask) and [`PySparkTask`](index.html#luigi.contrib.spark.PySparkTask): Deprecated since version 1.1.1: `SparkJob`, `Spark1xJob` and `PySpark1xJob` are deprecated. Please use [`SparkSubmitTask`](index.html#luigi.contrib.spark.SparkSubmitTask) or [`PySparkTask`](index.html#luigi.contrib.spark.PySparkTask). spark_submit Command to run in order to submit spark jobs. Default: `"spark-submit"` master Master url to use for `spark_submit`. Example: local[*], spark://masterhost:7077. Default: Spark default (Prior to 1.1.1: yarn-client) deploy_mode Whether to launch the driver programs locally (“client”) or on one of the worker machines inside the cluster (“cluster”). Default: Spark default jars Comma-separated list of local jars to include on the driver and executor classpaths. Default: Spark default packages Comma-separated list of packages to link to on the driver and executors py_files Comma-separated list of .zip, .egg, or .py files to place on the `PYTHONPATH` for Python apps. Default: Spark default files Comma-separated list of files to be placed in the working directory of each executor. Default: Spark default conf: Arbitrary Spark configuration property in the form Prop=Value|Prop2=Value2. Default: Spark default properties_file Path to a file from which to load extra properties. Default: Spark default driver_memory Memory for driver (e.g. 1000M, 2G). Default: Spark default driver_java_options Extra Java options to pass to the driver. Default: Spark default driver_library_path Extra library path entries to pass to the driver. Default: Spark default driver_class_path Extra class path entries to pass to the driver. Default: Spark default executor_memory Memory per executor (e.g. 1000M, 2G). Default: Spark default *Configuration for Spark submit jobs on Spark standalone with cluster deploy mode only:* driver_cores Cores for driver. Default: Spark default supervise If given, restarts the driver on failure. Default: Spark default *Configuration for Spark submit jobs on Spark standalone and Mesos only:* total_executor_cores Total cores for all executors. Default: Spark default *Configuration for Spark submit jobs on YARN only:* executor_cores Number of cores per executor. Default: Spark default queue The YARN queue to submit to. Default: Spark default num_executors Number of executors to launch. Default: Spark default archives Comma separated list of archives to be extracted into the working directory of each executor. Default: Spark default hadoop_conf_dir Location of the hadoop conf dir. Sets HADOOP_CONF_DIR environment variable when running spark. Example: /etc/hadoop/conf *Extra configuration for PySparkTask jobs:* py_packages Comma-separated list of local packages (in your python path) to be distributed to the cluster. *Parameters controlling the execution of SparkJob jobs (deprecated):* ### [task_history][¶](#task-history) Parameters controlling storage of task history in a database db_connection Connection string for connecting to the task history db using sqlalchemy. ### [execution_summary][¶](#execution-summary) Parameters controlling execution summary of a worker summary_length Maximum number of tasks to show in an execution summary. If the value is 0, then all tasks will be displayed. Default value is 5. ### [webhdfs][¶](#webhdfs) port The port to use for webhdfs. The normal namenode port is probably on a different port from this one. user Perform file system operations as the specified user instead of $USER. Since this parameter is not honored by any of the other hdfs clients, you should think twice before setting this parameter. client_type The type of client to use. Default is the “insecure” client that requires no authentication. The other option is the “kerberos” client that uses kerberos authentication. ### [datadog][¶](#datadog) api_key The api key found in the account settings of Datadog under the API sections. app_key The application key found in the account settings of Datadog under the API sections. default_tags Optional settings that adds the tag to all the metrics and events sent to Datadog. Default value is “application:luigi”. environment Allows you to tweak multiple environment to differentiate between production, staging or development metrics within Datadog. Default value is “development”. statsd_host The host that has the statsd instance to allow Datadog to send statsd metric. Default value is “localhost”. statsd_port The port on the host that allows connection to the statsd host. Defaults value is 8125. metric_namespace Optional prefix to add to the beginning of every metric sent to Datadog. Default value is “luigi”. ### Per Task Retry-Policy[¶](#per-task-retry-policy) Luigi also supports defining `retry_policy` per task. ``` class GenerateWordsFromHdfs(luigi.Task): retry_count = 2 ... class GenerateWordsFromRDBM(luigi.Task): retry_count = 5 ... class CountLetters(luigi.Task): def requires(self): return [GenerateWordsFromHdfs()] def run(): yield GenerateWordsFromRDBM() ... ``` If none of retry-policy fields is defined per task, the field value will be **default** value which is defined in luigi config file. To make luigi sticks to the given retry-policy, be sure you run luigi worker with `keep_alive` config. Please check `keep_alive` config in [[worker]](#worker-config) section. ### Retry-Policy Fields[¶](#retry-policy-fields) The fields below are in retry-policy and they can be defined per task. * `retry_count` * `disable_hard_timeout` * `disable_window_seconds` Configure logging[¶](#configure-logging) --- ### Config options:[¶](#config-options) Some config options for config [core] section log_level The default log level to use when no logging_conf_file is set. Must be a valid name of a [Python log level](https://docs.python.org/3/library/logging.html#logging-levels). Default is `DEBUG`. logging_conf_file Location of the logging configuration file. no_configure_logging If true, logging is not configured. Defaults to false. ### Config section[¶](#config-section) If you’re use TOML for configuration file, you can configure logging via `logging` section in this file. See [example](https://github.com/spotify/luigi/blob/master/examples/config.toml) for more details. ### Luigid CLI options:[¶](#luigid-cli-options) `--background` Run daemon in background mode. Disable logging setup and set up log level to INFO for root logger. `--logdir` set logging with INFO level and output in `$logdir/luigi-server.log` file ### Worker CLI options:[¶](#worker-cli-options) `--logging-conf-file` Configuration file for logging. `--log-level` Default log level. Available values: NOTSET, DEBUG, INFO, WARNING, ERROR, CRITICAL. Default DEBUG. See [Python documentation](https://docs.python.org/3/library/logging.html#logging-levels) For information about levels difference. ### Configuration options resolution order:[¶](#configuration-options-resolution-order) 1. no_configure_logging option 2. `--background` 3. `--logdir` 4. `--logging-conf-file` 5. logging_conf_file option 6. `logging` section 7. `--log-level` 8. log_level option Design and limitations[¶](#design-and-limitations) --- Luigi is the successor to a couple of attempts that we weren’t fully happy with. We learned a lot from our mistakes and some design decisions include: * Straightforward command-line integration. * As little boilerplate as possible. * Focus on job scheduling and dependency resolution, not a particular platform. In particular, this means no limitation to Hadoop. Though Hadoop/HDFS support is built-in and is easy to use, this is just one of many types of things you can run. * A file system abstraction where code doesn’t have to care about where files are located. * Atomic file system operations through this abstraction. If a task crashes it won’t lead to a broken state. * The dependencies are decentralized. No big config file in XML. Each task just specifies which inputs it needs and cross-module dependencies are trivial. * A web server that renders the dependency graph and does locking, etc for free. * Trivial to extend with new file systems, file formats, and job types. You can easily write jobs that inserts a Tokyo Cabinet into Cassandra. Adding support for new systems is generally not very hard. (Feel free to send us a patch when you’re done!) * Date algebra included. * Lots of unit tests of the most basic stuff. It wouldn’t be fair not to mention some limitations with the current design: * Its focus is on batch processing so it’s probably less useful for near real-time pipelines or continuously running processes. * The assumption is that each task is a sizable chunk of work. While you can probably schedule a few thousand jobs, it’s not meant to scale beyond tens of thousands. * Luigi does not support distribution of execution. When you have workers running thousands of jobs daily, this starts to matter, because the worker nodes get overloaded. There are some ways to mitigate this (trigger from many nodes, use resources), but none of them are ideal. * Luigi does not come with built-in triggering, and you still need to rely on something like crontab to trigger workflows periodically. Also, it should be mentioned that Luigi is named after the world’s second most famous plumber. API Reference[¶](#api-reference) === | [`luigi`](index.html#module-luigi) | Package containing core luigi functionality. | | [`luigi.contrib`](index.html#module-luigi.contrib) | Package containing optional and-on functionality. | | [`luigi.tools`](index.html#module-luigi.tools) | Sort of a standard library for doing stuff with Tasks at a somewhat abstract level. | | [`luigi.local_target`](index.html#module-luigi.local_target) | `LocalTarget` provides a concrete implementation of a [`Target`](index.html#luigi.target.Target) class that uses files on the local file system | Indices and tables[¶](#indices-and-tables) --- * [Index](genindex.html) * [Module Index](py-modindex.html) * [Search Page](search.html)
rglwidget
cran
R
Package ‘rglwidget’ October 14, 2022 Type Package Title 'rgl' in 'htmlwidgets' Framework Version 0.2.1 Author <NAME> Maintainer <NAME> <<EMAIL>> Description The contents of this package have been merged into rgl, so it is no longer needed. Imports rgl (>= 0.96.0) License GPL-2 LazyData TRUE NeedsCompilation no Repository CRAN Date/Publication 2016-08-26 13:22:08 R topics documented: rglwidget-packag... 1 rglwidget-package ’rgl’ in ’htmlwidgets’ Framework Description The contents of this package have been merged into rgl, so it is no longer needed. Details The DESCRIPTION file: Package: rglwidget Type: Package Title: ’rgl’ in ’htmlwidgets’ Framework Version: 0.2.1 Author: <NAME> Maintainer: <NAME> <<EMAIL>> Description: The contents of this package have been merged into rgl, so it is no longer needed. Imports: rgl (>= 0.96.0) License: GPL-2 LazyData: TRUE Index of help topics: rglwidget-package 'rgl' in 'htmlwidgets' Framework The rglwidget package has been merged into the rgl package, and should no longer be used. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>>
github.com/pion/turn
go
Go
README [¶](#section-readme) --- [Pion TURN](https://pion.ly) Pion TURN === #### An extendable TURN server written in Go [![Pion TURN](https://img.shields.io/badge/pion-turn-gray.svg?longCache=true&colorB=brightgreen)](https://pion.ly) [![Slack Widget](https://img.shields.io/badge/join-us%20on%20slack-gray.svg?longCache=true&logo=slack&colorB=brightgreen)](http://gophers.slack.com/messages/pion) [![Waffle board](https://img.shields.io/badge/pm-waffle-gray.svg?longCache=true&colorB=brightgreen)](https://waffle.io/pion/webrtc) [![Build Status](https://travis-ci.org/pion/turn.svg?branch=master)](https://travis-ci.org/pion/turn) [![GoDoc](https://godoc.org/github.com/pion/turn?status.svg)](https://godoc.org/github.com/pion/turn) [![Coverage Status](https://codecov.io/gh/pion/turn/branch/master/graph/badge.svg)](https://codecov.io/gh/pion/turn) [![Go Report Card](https://goreportcard.com/badge/github.com/pion/turn)](https://goreportcard.com/report/github.com/pion/turn) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/d53ec6c70576476cb16c140c2964afde)](https://www.codacy.com/app/Sean-Der/turn) [![](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) A TURN server written in Go that is designed to be scalable, extendable and embeddable out of the box. For simple use cases it only requires downloading 1 static binary, and setting 3 options. See [DESIGN.md](https://github.com/pion/turn/blob/v1.4.0/DESIGN.md) for the the features it offers, and future goals. ### Quick Start If you want just a simple TURN server with a few static usernames `simple-turn` will perfectly suit your purposes. If you have custom requirements such as a database proceed to extending. `simple-turn` is a single static binary, and all config is driven by environment variables. On a fresh Linux AWS instance these are all the steps you would need. ``` $ wget -q https://github.com/pion/turn/releases/download/1.0.3/simple-turn-linux-amd64 $ chmod +x simple-turn-linux-amd64 $ export USERS='user=password foo=bar' $ export REALM=my-server.com $ export UDP_PORT=3478 $ ./simple-turn-linux-amd64 ``` To explain what every step does * Download simple-turn for Linux x64, see [release](https://github.com/pion/turn/releases) for other platforms * Make it executable * Configure auth, in the form of `USERNAME=PASSWORD USERNAME=PASSWORD` with no limits * Set your realm, this is the public URL or name of your server * Set the port you listen on, 3478 is the default port for TURN That is it! Then to use your new TURN server your WebRTC config would look like ``` { iceServers: [{ urls: "turn:YOUR_SERVER" username: "user", credential: "password" }] ``` --- If you are using Windows you would set these values in Powershell by doing. Also make sure your firewall is configured properly. ``` > $env:USERS = "user=password foo=bar" > $env:REALM = "my-server.com" > $env:UDP_PORT = 3478 ``` ### Extending See [simple-turn](https://github.com/pion/turn/raw/master/cmd/simple-turn/main.go) pion-turn can be configured by implementing [these callbacks](https://github.com/pion/turn/raw/master/turn.go#L11) and by passing [these arguments](https://github.com/pion/turn/raw/master/turn.go#L11) All that `simple-turn` does is take environment variables, and then uses the same API. ### Developing For developing a Dockerfile is available with features like hot-reloads, and is meant to be volume mounted. Make sure you also have github.com/pion/pkg in your path, or you can exclude the second volume mount. This is only meant for development, see [demo-conference](https://github.com/pion/demo-conference) to see TURN usage as a user. ``` docker build -t turn . docker run -v $(pwd):/usr/local/src/github.com/pion/turn -v $(pwd)/../pkg:/usr/local/src/github.com/pion/pkg turn ``` Currently only Linux is supported until Docker supports full (host <-> container) networking on Windows/OSX ### RFCs #### Implemented * [RFC 5389: Session Traversal Utilities for NAT (STUN)](https://tools.ietf.org/html/rfc5389) * [RFC 5766: Traversal Using Relays around NAT (TURN)](https://tools.ietf.org/html/rfc5766) #### Planned * [RFC 6062: Traversal Using Relays around NAT (TURN) Extensions for TCP Allocations](https://tools.ietf.org/html/rfc6062) * [RFC 6156: Traversal Using Relays around NAT (TURN) Extension for IPv6](https://tools.ietf.org/html/rfc6156) ### Community Pion has an active community on the [Golang Slack](https://invite.slack.golangbridge.org/). Sign up and join the **#pion** channel for discussions and support. You can also use [Pion mailing list](https://groups.google.com/forum/#!forum/pion). We are always looking to support **your projects**. Please reach out if you have something to build! ### Contributing Check out the [CONTRIBUTING.md](https://github.com/pion/turn/blob/v1.4.0/CONTRIBUTING.md) to join the group of amazing people making this project possible: * [<NAME>](https://github.com/backkem) - *Documentation* * [<NAME>](https://github.com/iwittkau) - *STUN client* * [<NAME>](https://github.com/kc5nra) - *Original Author* * [<NAME>](https://github.com/paralax) - *Documentation* * [<NAME>](https://github.com/misi) - *Documentation* * [<NAME>](https://github.com/santrym) - *Mascot* * [<NAME>](https://github.com/Sean-Der) - *Original Author* * [winds2016](https://github.com/winds2016) - *Windows platform testing* * [songjiayang](https://github.com/songjiayang) - *SongJiaYang* * [<NAME>](https://github.com/enobufs) - *vnet* * [namreg](https://github.com/namreg) - *Igor German* * [<NAME>](https://github.com/ernado) - *protocol* * [<NAME>](https://github.com/epes) * [<NAME>](https://github.com/lrezek) * [<NAME>](https://github.com/hugoArregui) * [<NAME>](https://github.com/AeroNotix) ### License MIT License - see [LICENSE.md](https://github.com/pion/turn/blob/v1.4.0/LICENSE.md) for full text Documentation [¶](#section-documentation) --- ### Index [¶](#pkg-index) * [type AuthHandler](#AuthHandler) * [type Client](#Client) * + [func NewClient(config *ClientConfig) (*Client, error)](#NewClient) * + [func (c *Client) Allocate() (net.PacketConn, error)](#Client.Allocate) + [func (c *Client) Close()](#Client.Close) + [func (c *Client) HandleInbound(data []byte, from net.Addr) (bool, error)](#Client.HandleInbound) + [func (c *Client) Listen() error](#Client.Listen) + [func (c *Client) OnDeallocated(relayedAddr net.Addr)](#Client.OnDeallocated) + [func (c *Client) PerformTransaction(msg *stun.Message, to net.Addr, dontWait bool) (client.TransactionResult, error)](#Client.PerformTransaction) + [func (c *Client) Realm() stun.Realm](#Client.Realm) + [func (c *Client) STUNServerAddr() net.Addr](#Client.STUNServerAddr) + [func (c *Client) SendBindingRequest() (net.Addr, error)](#Client.SendBindingRequest) + [func (c *Client) SendBindingRequestTo(to net.Addr) (net.Addr, error)](#Client.SendBindingRequestTo) + [func (c *Client) TURNServerAddr() net.Addr](#Client.TURNServerAddr) + [func (c *Client) Username() stun.Username](#Client.Username) + [func (c *Client) WriteTo(data []byte, to net.Addr) (int, error)](#Client.WriteTo) * [type ClientConfig](#ClientConfig) * [type STUNConn](#STUNConn) * + [func NewSTUNConn(nextConn net.Conn) *STUNConn](#NewSTUNConn) * + [func (s *STUNConn) Close() error](#STUNConn.Close) + [func (s *STUNConn) LocalAddr() net.Addr](#STUNConn.LocalAddr) + [func (s *STUNConn) ReadFrom(p []byte) (n int, addr net.Addr, err error)](#STUNConn.ReadFrom) + [func (s *STUNConn) SetDeadline(t time.Time) error](#STUNConn.SetDeadline) + [func (s *STUNConn) SetReadDeadline(t time.Time) error](#STUNConn.SetReadDeadline) + [func (s *STUNConn) SetWriteDeadline(t time.Time) error](#STUNConn.SetWriteDeadline) + [func (s *STUNConn) WriteTo(p []byte, addr net.Addr) (n int, err error)](#STUNConn.WriteTo) * [type Sender](#Sender) * [type Server](#Server) * + [func NewServer(config *ServerConfig) *Server](#NewServer) * + [func (s *Server) AddExternalIPAddr(mapping string) error](#Server.AddExternalIPAddr) + [func (s *Server) AddListeningIPAddr(addrStr string) error](#Server.AddListeningIPAddr) + [func (s *Server) AddRelayIPAddr(addrStr string) error](#Server.AddRelayIPAddr) + [func (s *Server) Close() error](#Server.Close) + [func (s *Server) Start() error](#Server.Start) * [type ServerConfig](#ServerConfig) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) This section is empty. ### Functions [¶](#pkg-functions) This section is empty. ### Types [¶](#pkg-types) #### type [AuthHandler](https://github.com/pion/turn/blob/v1.4.0/server.go#L28) [¶](#AuthHandler) added in v1.2.0 ``` type AuthHandler func(username [string](/builtin#string), srcAddr [net](/net).[Addr](/net#Addr)) (password [string](/builtin#string), ok [bool](/builtin#bool)) ``` AuthHandler is a callback used to handle incoming auth requests, allowing users to customize Pion TURN with custom behavior #### type [Client](https://github.com/pion/turn/blob/v1.4.0/client.go#L50) [¶](#Client) ``` type Client struct { // contains filtered or unexported fields } ``` Client is a STUN server client #### func [NewClient](https://github.com/pion/turn/blob/v1.4.0/client.go#L72) [¶](#NewClient) added in v1.2.0 ``` func NewClient(config *[ClientConfig](#ClientConfig)) (*[Client](#Client), [error](/builtin#error)) ``` NewClient returns a new Client instance. listeningAddress is the address and port to listen on, default "0.0.0.0:0" #### func (*Client) [Allocate](https://github.com/pion/turn/blob/v1.4.0/client.go#L230) [¶](#Client.Allocate) added in v1.3.0 ``` func (c *[Client](#Client)) Allocate() ([net](/net).[PacketConn](/net#PacketConn), [error](/builtin#error)) ``` Allocate sends a TURN allocation request to the given transport address #### func (*Client) [Close](https://github.com/pion/turn/blob/v1.4.0/client.go#L187) [¶](#Client.Close) added in v1.3.0 ``` func (c *[Client](#Client)) Close() ``` Close closes this client #### func (*Client) [HandleInbound](https://github.com/pion/turn/blob/v1.4.0/client.go#L378) [¶](#Client.HandleInbound) added in v1.3.0 ``` func (c *[Client](#Client)) HandleInbound(data [][byte](/builtin#byte), from [net](/net).[Addr](/net#Addr)) ([bool](/builtin#bool), [error](/builtin#error)) ``` HandleInbound handles data received. This method handles incoming packet demultiplex it by the source address and the types of the message. This return a booleen (handled or not) and if there was an error. Caller should check if the packet was handled by this client or not. If not handled, it is assumed that the packet is application data. If an error is returned, the caller should discard the packet regardless. #### func (*Client) [Listen](https://github.com/pion/turn/blob/v1.4.0/client.go#L159) [¶](#Client.Listen) added in v1.3.0 ``` func (c *[Client](#Client)) Listen() [error](/builtin#error) ``` Listen will have this client start listening on the conn provided via the config. This is optional. If not used, you will need to call HandleInbound method to supply incoming data, instead. #### func (*Client) [OnDeallocated](https://github.com/pion/turn/blob/v1.4.0/client.go#L367) [¶](#Client.OnDeallocated) added in v1.3.0 ``` func (c *[Client](#Client)) OnDeallocated(relayedAddr [net](/net).[Addr](/net#Addr)) ``` OnDeallocated is called when deallocation of relay address has been complete. (Called by UDPConn) #### func (*Client) [PerformTransaction](https://github.com/pion/turn/blob/v1.4.0/client.go#L330) [¶](#Client.PerformTransaction) added in v1.3.0 ``` func (c *[Client](#Client)) PerformTransaction(msg *[stun](/github.com/pion/stun).[Message](/github.com/pion/stun#Message), to [net](/net).[Addr](/net#Addr), dontWait [bool](/builtin#bool)) ([client](/github.com/pion/turn@v1.4.0/internal/client).[TransactionResult](/github.com/pion/turn@v1.4.0/internal/client#TransactionResult), [error](/builtin#error)) ``` PerformTransaction performs STUN transaction #### func (*Client) [Realm](https://github.com/pion/turn/blob/v1.4.0/client.go#L147) [¶](#Client.Realm) added in v1.3.0 ``` func (c *[Client](#Client)) Realm() [stun](/github.com/pion/stun).[Realm](/github.com/pion/stun#Realm) ``` Realm return realm #### func (*Client) [STUNServerAddr](https://github.com/pion/turn/blob/v1.4.0/client.go#L137) [¶](#Client.STUNServerAddr) added in v1.3.0 ``` func (c *[Client](#Client)) STUNServerAddr() [net](/net).[Addr](/net#Addr) ``` STUNServerAddr return the STUN server address #### func (*Client) [SendBindingRequest](https://github.com/pion/turn/blob/v1.4.0/client.go#L222) [¶](#Client.SendBindingRequest) added in v1.3.0 ``` func (c *[Client](#Client)) SendBindingRequest() ([net](/net).[Addr](/net#Addr), [error](/builtin#error)) ``` SendBindingRequest sends a new STUN request to the STUN server #### func (*Client) [SendBindingRequestTo](https://github.com/pion/turn/blob/v1.4.0/client.go#L194) [¶](#Client.SendBindingRequestTo) added in v1.3.0 ``` func (c *[Client](#Client)) SendBindingRequestTo(to [net](/net).[Addr](/net#Addr)) ([net](/net).[Addr](/net#Addr), [error](/builtin#error)) ``` SendBindingRequestTo sends a new STUN request to the given transport address #### func (*Client) [TURNServerAddr](https://github.com/pion/turn/blob/v1.4.0/client.go#L132) [¶](#Client.TURNServerAddr) added in v1.3.0 ``` func (c *[Client](#Client)) TURNServerAddr() [net](/net).[Addr](/net#Addr) ``` TURNServerAddr return the TURN server address #### func (*Client) [Username](https://github.com/pion/turn/blob/v1.4.0/client.go#L142) [¶](#Client.Username) added in v1.3.0 ``` func (c *[Client](#Client)) Username() [stun](/github.com/pion/stun).[Username](/github.com/pion/stun#Username) ``` Username returns username #### func (*Client) [WriteTo](https://github.com/pion/turn/blob/v1.4.0/client.go#L152) [¶](#Client.WriteTo) added in v1.3.0 ``` func (c *[Client](#Client)) WriteTo(data [][byte](/builtin#byte), to [net](/net).[Addr](/net#Addr)) ([int](/builtin#int), [error](/builtin#error)) ``` WriteTo sends data to the specified destination using the base socket. #### type [ClientConfig](https://github.com/pion/turn/blob/v1.4.0/client.go#L36) [¶](#ClientConfig) added in v1.2.0 ``` type ClientConfig struct { STUNServerAddr [string](/builtin#string) // STUN server address (e.g. "stun.abc.com:3478") TURNServerAddr [string](/builtin#string) // TURN server addrees (e.g. "turn.abc.com:3478") Username [string](/builtin#string) Password [string](/builtin#string) Realm [string](/builtin#string) Software [string](/builtin#string) RTO [time](/time).[Duration](/time#Duration) Conn [net](/net).[PacketConn](/net#PacketConn) // Listening socket (net.PacketConn) LoggerFactory [logging](/github.com/pion/logging).[LoggerFactory](/github.com/pion/logging#LoggerFactory) Net *[vnet](/github.com/pion/transport/vnet).[Net](/github.com/pion/transport/vnet#Net) } ``` ClientConfig is a bag of config parameters for Client. #### type [STUNConn](https://github.com/pion/turn/blob/v1.4.0/stun_conn.go#L19) [¶](#STUNConn) added in v1.4.0 ``` type STUNConn struct { // contains filtered or unexported fields } ``` STUNConn wraps a net.Conn and implements net.PacketConn by being STUN aware and packetizing the stream #### func [NewSTUNConn](https://github.com/pion/turn/blob/v1.4.0/stun_conn.go#L118) [¶](#NewSTUNConn) added in v1.4.0 ``` func NewSTUNConn(nextConn [net](/net).[Conn](/net#Conn)) *[STUNConn](#STUNConn) ``` NewSTUNConn creates a STUNConn #### func (*STUNConn) [Close](https://github.com/pion/turn/blob/v1.4.0/stun_conn.go#L93) [¶](#STUNConn.Close) added in v1.4.0 ``` func (s *[STUNConn](#STUNConn)) Close() [error](/builtin#error) ``` Close implements Close from net.PacketConn #### func (*STUNConn) [LocalAddr](https://github.com/pion/turn/blob/v1.4.0/stun_conn.go#L98) [¶](#STUNConn.LocalAddr) added in v1.4.0 ``` func (s *[STUNConn](#STUNConn)) LocalAddr() [net](/net).[Addr](/net#Addr) ``` LocalAddr implements LocalAddr from net.PacketConn #### func (*STUNConn) [ReadFrom](https://github.com/pion/turn/blob/v1.4.0/stun_conn.go#L65) [¶](#STUNConn.ReadFrom) added in v1.4.0 ``` func (s *[STUNConn](#STUNConn)) ReadFrom(p [][byte](/builtin#byte)) (n [int](/builtin#int), addr [net](/net).[Addr](/net#Addr), err [error](/builtin#error)) ``` ReadFrom implements ReadFrom from net.PacketConn #### func (*STUNConn) [SetDeadline](https://github.com/pion/turn/blob/v1.4.0/stun_conn.go#L103) [¶](#STUNConn.SetDeadline) added in v1.4.0 ``` func (s *[STUNConn](#STUNConn)) SetDeadline(t [time](/time).[Time](/time#Time)) [error](/builtin#error) ``` SetDeadline implements SetDeadline from net.PacketConn #### func (*STUNConn) [SetReadDeadline](https://github.com/pion/turn/blob/v1.4.0/stun_conn.go#L108) [¶](#STUNConn.SetReadDeadline) added in v1.4.0 ``` func (s *[STUNConn](#STUNConn)) SetReadDeadline(t [time](/time).[Time](/time#Time)) [error](/builtin#error) ``` SetReadDeadline implements SetReadDeadline from net.PacketConn #### func (*STUNConn) [SetWriteDeadline](https://github.com/pion/turn/blob/v1.4.0/stun_conn.go#L113) [¶](#STUNConn.SetWriteDeadline) added in v1.4.0 ``` func (s *[STUNConn](#STUNConn)) SetWriteDeadline(t [time](/time).[Time](/time#Time)) [error](/builtin#error) ``` SetWriteDeadline implements SetWriteDeadline from net.PacketConn #### func (*STUNConn) [WriteTo](https://github.com/pion/turn/blob/v1.4.0/stun_conn.go#L88) [¶](#STUNConn.WriteTo) added in v1.4.0 ``` func (s *[STUNConn](#STUNConn)) WriteTo(p [][byte](/builtin#byte), addr [net](/net).[Addr](/net#Addr)) (n [int](/builtin#int), err [error](/builtin#error)) ``` WriteTo implements WriteTo from net.PacketConn #### type [Sender](https://github.com/pion/turn/blob/v1.4.0/sender.go#L10) [¶](#Sender) added in v1.3.0 ``` type Sender func(conn [net](/net).[PacketConn](/net#PacketConn), addr [net](/net).[Addr](/net#Addr), attrs ...[stun](/github.com/pion/stun).[Setter](/github.com/pion/stun#Setter)) [error](/builtin#error) ``` Sender is responsible for building a message and sending it to the given addr. #### type [Server](https://github.com/pion/turn/blob/v1.4.0/server.go#L56) [¶](#Server) ``` type Server struct { // contains filtered or unexported fields } ``` Server is an instance of the Pion TURN server #### func [NewServer](https://github.com/pion/turn/blob/v1.4.0/server.go#L75) [¶](#NewServer) added in v1.2.0 ``` func NewServer(config *[ServerConfig](#ServerConfig)) *[Server](#Server) ``` NewServer creates the Pion TURN server #### func (*Server) [AddExternalIPAddr](https://github.com/pion/turn/blob/v1.4.0/server.go#L166) [¶](#Server.AddExternalIPAddr) added in v1.3.5 ``` func (s *[Server](#Server)) AddExternalIPAddr(mapping [string](/builtin#string)) [error](/builtin#error) ``` AddExternalIPAddr adds a mapping to an external IP address. This is useful when the TURN server is behind a 1-to-1 NAT, or a D-NAT (which is typical when hosting on AWS EC2). The argument should be a dotted-decimal representation of external IP address. If there is more than on IP address, the argument should be a cancatenation of external IP and local IP delimited by a '/'. Ex 1: "185.199.108.153" Ex 2: "185.199.108.153/10.0.1.2" By default, no address mapping is used. This method must be called before calling Start(). #### func (*Server) [AddListeningIPAddr](https://github.com/pion/turn/blob/v1.4.0/server.go#L121) [¶](#Server.AddListeningIPAddr) added in v1.2.0 ``` func (s *[Server](#Server)) AddListeningIPAddr(addrStr [string](/builtin#string)) [error](/builtin#error) ``` AddListeningIPAddr adds a listening IP address. If not specified, it will automatically assigns the listening IP addresses from the system. This method must be called before calling Start(). #### func (*Server) [AddRelayIPAddr](https://github.com/pion/turn/blob/v1.4.0/server.go#L139) [¶](#Server.AddRelayIPAddr) added in v1.2.1 ``` func (s *[Server](#Server)) AddRelayIPAddr(addrStr [string](/builtin#string)) [error](/builtin#error) ``` AddRelayIPAddr adds a listening IP address. Note: current implementation can have only one relay IP address. If not specified, it will automatically assigns the relay IP addresses from the system. This method must be called before calling Start(). #### func (*Server) [Close](https://github.com/pion/turn/blob/v1.4.0/server.go#L328) [¶](#Server.Close) added in v1.2.0 ``` func (s *[Server](#Server)) Close() [error](/builtin#error) ``` Close closes the connection. #### func (*Server) [Start](https://github.com/pion/turn/blob/v1.4.0/server.go#L276) [¶](#Server.Start) added in v1.2.0 ``` func (s *[Server](#Server)) Start() [error](/builtin#error) ``` Start starts the server. #### type [ServerConfig](https://github.com/pion/turn/blob/v1.4.0/server.go#L31) [¶](#ServerConfig) added in v1.2.0 ``` type ServerConfig struct { // Realm sets the realm for this server Realm [string](/builtin#string) // AuthHandler is the handler called on each incoming auth requests. AuthHandler [AuthHandler](#AuthHandler) // ChannelBindTimeout sets the lifetime of channel binding. Defaults to 10 minutes. ChannelBindTimeout [time](/time).[Duration](/time#Duration) // ListeningPort sets the listening port number. Defaults to 3478. ListeningPort [int](/builtin#int) // LoggerFactory must be set for logging from this server. LoggerFactory [logging](/github.com/pion/logging).[LoggerFactory](/github.com/pion/logging#LoggerFactory) // Net is used by pion developers. Do not use in your application. Net *[vnet](/github.com/pion/transport/vnet).[Net](/github.com/pion/transport/vnet#Net) // Software is the STUN SOFTWARE attribute. Useful for debugging purpose. Software [string](/builtin#string) // Sender is a custom implementation of the request Sender. Sender [Sender](#Sender) } ``` ServerConfig is a bag of config parameters for Server.
@blockly/eslint-config
npm
JavaScript
@blockly/eslint-config === > ESLint [shareable config](http://eslint.org/docs/developer-guide/shareable-configs.html) used by [Blockly plugins](https://github.com/google/blockly-samples/tree/master/plugins) Installation --- ``` npm install --save-dev eslint @blockly/eslint-config ``` About --- This configuration is specific to Blockly and blockly-samples style rules. In general, we follow the Google [JavaScript](https://google.github.io/styleguide/jsguide.html) and [TypeScript](https://google.github.io/styleguide/tsguide.html) style guides, but not entirely, due to the existence of code that predates Google's current recommendations. This configuration also does not match the core Blockly repo's configuration in an effort to make sure new sample code follows the more modern guidelines. The top-level `rules` section contains rules that apply to all js and ts files. The `overrides` section contains an override for TypeScript files that has TS-specific rules. In some cases, rules in the top-level section are disabled in favor of their TS-specific counterparts. In general, TS files must adhere to both sets of rules. ### JsDoc and TsDoc flavors JS files are set to "closure" flavor of JsDoc using the `eslint-plugin-jsdoc` [package](https://www.npmjs.com/package/eslint-plugin-jsdoc). This preset enforces that Google's Closure-style JsDoc rules are used rather than the non-Google JsDoc rules. One notable departure from the Closure style is that we use `@returns` rather than `@return`. TS files are set to the "typescript" flavor in the `eslint-plugin-jsdoc` settings. This should correspond to TsDoc style, but this plugin provides a superior experience to that of the `eslint-plugin-tsdoc` [package](https://www.npmjs.com/package/eslint-plugin-tsdoc), which does not provide configurable rules. License --- Apache 2.0 Readme --- ### Keywords * blockly * eslint * eslintplugin * dev
weon
readthedoc
Unknown
Date: 2000-01-01 Categories: Tags: This document contains the main instructions in order to use the Fly T-WEoN (Fly Tool for Weighted Epigenetic Networks) Cytoscape app. * Open the Fly T-WEoN app Within Cytoscape, go to Apps >> Fly T-WEoN - Fly Tool for Weighted Epigenomic Network. This will display the user interface as shown in the figure. 2. Interface The Fly T-WEoN interface is an input screen where the user complete required and optional data. In the backend, Fly T-WEoN executes Perl scripts, therefore parsing correctly the data to arguments and call orderly the scripts to filter out unlikely ocurring gene regulations from a reference gene regulatory network. There is a known issue occurring in MacOS. Users has reported that the Network Definition selector is not shown. However, the selector is still there; you only need to click on in this blank space and the menu will be displayed to select a network definition. * Required data In order to use Fly T-WEoN, you need to provide at least three required data as listed as follow: * Network Definition: This field corresponds to the reference GRN to which apply filters to generate the weighted GRN. We provide three references networks, which were constructed within a different cut-off of 1500, 2000, and 5000 nucleotides: if a Transcription Factor Binding Site or other regulatory element is contained in the cut-off upstream the Transcription Start Site of Drosophila melanogaster genes, then the GRN defines a connection between gene and regulator. * Expression File: Fly T-WEoN employs RNA-seq data to filter out absent transcription factors and miRNAs from the Reference GRN. The RNA-seq data must be provided formatted in a two-columns file separated by tabulations. The first column is the gene name while the second is the expression of the corresponding gene. Expression could be reported as read counts, reads per kilobase million (RPKM) or fragments per kilobase million (FPKM). Data must be a single experiment or the average value of the experimental replication. * Result folder: A folder where results will be placed. * Optional data If you have data from DNase (or ATAC-seq), Histone modifications and/or methylation experiments, you can use it to complement RNA-seq data and get a more specific Gene Regulation Network. So, for the `DNase file` and `Methylation file` fields, you need to provide four-columns files separated by tabulations. Each column correspond, in order, to the chromosome, the initial coordinate, the ending coordinate, and the score for the mapped feature. Both files has an associated `Score` field used as a threshold value to dismiss lower score values from the original data. Default is zero, which means that all mapped features in the DNase and Methylation files will be used in the filtering process. Respect to the ``` Histone Mark Path Files ``` button, once you click it a new window will appear as shown in the next image, so in this new window you can select files for the corresponding post-translational modification of histone tails. Each data must be a three-columns files separated by tabulations, where each column correspond to the chromosome, the initial coordinate, and the ending coordinate of the mapped feature. * Execute filtering and visualization of results After all data is selected, please click on `Run Fly T-WEoN` . The weighted GRN will be loaded in Cytoscape with the `Create View` button to display the time and/or tissue specific GRN. Note It is important to remark that the filtering process could take a long time depending on your machine hardware and the number of files and information on them provided to Fly T-WEoN. Please be patient. * Details of the Output Files A set of files are created after executing Fly T-WEoN, which are located in the folder selected as output. These files are described as follow: * output_filter_PTMs.txt: A file describing information about chromosome, id of the coding gene for the transcription factor (TF), starting coordinate of the transcription factor binding site (TFBS), ending coordinate of the TFBS, name of the post-translational modification (PTM) of histone tails (histone marks), starting coordinate of the PTM, ending coordinate of the PTM, open or closed chromatin state (represented as + or -) and place where the PTM was found (on the promotor region, P, or on the gene, G) * output_connect.txt: A file describing information about PTMs. In the first column is the connection in the Gene Regulatory Network (GRN) and the second has info about PTM and the number of times that PTM was found and affecting the connection. * output_connection_analysis.txt: A file describing all PTMs affecting the binding of a TF. * output_regulator_express.tsv: A file describing connections from expressed regulators to genes. * output_regulator_no_express.tsv: A file describing connections from non-expressed regulators to genes. * output_mirna_express.tsv: A file describing connections from expressed miRNAs to genes. * output_mirna_no_express.tsv: A file describing connections from non-expressed miRNAs to genes. * out_TFBS_network.tsv: A copy of the reference GRN used as input. * specific_GRN.tsv: A file that merge output_regulator_express.tsv and output_mirna_express.tsv results. * scored_GRN.tsv: Same as specific_GRN.tsv, except for this file include information about the calculated score of the connection. This score is based on a set of filters (based on Expression, DNase, histone marks, and Methylation) indicating the evidence for the regulatory interaction. Importantly to note is that the scale for the evidence score go from one to five (only if all four types of experiments were provided by the user). If you close Cytoscape and need to visualize again the weighted GRN, please import the specific_GRN.tsv or scored_GRN.tsv into Cytoscape. Feel free to contact directly throught the Github repository or to Dr. <NAME>’s e-mail.
BioProbability
cran
R
Package ‘BioProbability’ October 12, 2022 Type Package Title Probability in Biostatistics Version 1.0 Author <NAME>, <NAME> Maintainer <NAME> <<EMAIL>> Description Several tools for analyzing diagnostic tests and 2x2 contingency tables are pro- vided. In particular, positive and negative predictive values for a diagnostic tests can be calcu- lated from prevalence, sensitivity and specificity values. For contingency tables, rela- tive risk and odds ratio measures are estimated. Furthermore, confidence intervals are provided. License GPL-2 NeedsCompilation no Repository CRAN Date/Publication 2020-01-24 18:10:07 UTC R topics documented: input... 1 input... 2 odd... 2 odds.rati... 3 predictive.valu... 4 relative.ris... 5 sensitivity.specificit... 6 input1 Auxiliary function Description Auxiliary function. input2 Auxiliary function Description Auxiliary function. odds Odds of a success Description This function calculates the odds of a success from its probability. For more details, see Agresti (2018, ISBN: 978-1-119-40528-3). Usage odds(p,name="Prevalence") Arguments p a numeric value indicating the probability of the success. It is possible to con- sider a numeric vector of different probabilities values. name a character value indicating the name of the success. Possible values for this argument are name="Prevalence" or name="Incidence". Value A matrix of two columns. The first column contains the vector of probabilities p. The second column contains the corresponding odds values. References Agresti, A. (2018). An introduction to categorical data analysis. John Wiley & Sons. ISBN: 978-1- 119-40528-3. Examples odds(0.09, name="Prevalence") odds.ratio Odds ratio calculation Description This function calculates the odds ratio from a contingency table. Furthermore, a confidence interval for the odds ratio is provided. Details on the confidence interval can be found in Agresti (2018, ISBN: 978-1-119-40528-3). Usage odds.ratio(A, show.matrix = FALSE, conf.int = FALSE, level = 0.05) Arguments A a 2x2 matrix object where A[1,1] contains the number of people with the dis- ease who have been exposed to some condition; A[1,2], the number of people without the disease who have not been exposed this condition; A[2,1], the num- ber of people with the disease who have been exposed to the condition; A[2,2], the number of people without the disease who have not been exposed to some condition. show.matrix a logical value indicating whether the matrix A must be shown. conf.int a logical value indicating whether a confidence interval for the relative risk must be calculated. level level of significance for the confidence interval. Value If conf.int=TRUE, a list of length equal to two. The first element of the list Odds Ratio corresponds to the estimation of the odds ratio; the second one Confidence Interval of level contains the corresponding confidence interval. If conf.int=FALSE, a numeric value corresponding to the estimation of the odds ratio. References Agresti, A. (2018). An introduction to categorical data analysis. John Wiley & Sons. ISBN: 978-1- 119-40528-3. Examples A<-matrix(c(744,231,421,659),nrow=2) odds.ratio(A,show.matrix=TRUE,conf.int=TRUE) predictive.value Positive and negative predictive values for a diagnostic test. Description This function calculates the positive and negative predictive values for a diagnostic test from the prevalence, the sensitivity and the specificity values using the Bayes’ theorem. For more details, see Agresti (2018, ISBN: 978-1-119-40528-3). Usage predictive.value(p, Spe, Sen, plot.it = FALSE) Arguments p a numeric value indicating the prevalence of the disease. It is possible to con- sider a numeric vector of different values for the prevalence. Spe a numeric value corresponding to the specificity of the diagnostic test. Sen a numeric value corresponding to the sensitivity of the diagnostic test. plot.it a logical value indicating whether the scatterplots for the prevalence values and the corresponding predictive values for the diagnostic test must be plotted. Value A matrix of three columns. The first column contains the vector of prevalences p. The second and third columns contain the corresponding positive and negative predictive values, respectively. If plot.it=TRUE, the scatterplots for the prevalence values and the predictive values is are plotted. References <NAME>. (2018). An introduction to categorical data analysis. <NAME> & Sons. ISBN: 978-1- 119-40528-3. Examples p<-seq(0.001,0.1,length=10) predictive.value(p,Spe=0.95,Sen=0.97,plot.it=TRUE) relative.risk Relative risk calculation Description This function calculates the relative risk from a contingency table. Furthermore, a confidence in- terval for the relative risk is provided. Details on the confidence interval can be found in Agresti (2018, ISBN: 978-1-119-40528-3). Usage relative.risk(A, show.matrix = FALSE, conf.int = FALSE, level = 0.05) Arguments A a 2x2 matrix object where A[1,1] contains the number of people with the dis- ease who have been exposed to some condition; A[1,2], the number of people without the disease who have not been exposed this condition; A[2,1], the num- ber of people with the disease who have been exposed to the condition; A[2,2], the number of people without the disease who have not been exposed to some condition. show.matrix a logical value indicating whether the matrix A must be shown. conf.int a logical value indicating whether a confidence interval for the relative risk must be calculated. level level of significance for the confidence interval. Value If conf.int=TRUE, a list of length equal to two. The first element of the list Relative Risk cor- responds to the estimation of the relative risk; the second one Confidence Interval of level contains the corresponding confidence interval. If conf.int=FALSE, a numeric value corresponding to the estimation of the relative risk. References <NAME>. (2018). An introduction to categorical data analysis. <NAME> & Sons. ISBN: 978-1- 119-40528-3. Examples A<-matrix(c(744,231,421,659),nrow=2) relative.risk(A,show.matrix=TRUE,conf.int=TRUE) relative.risk(A,show.matrix=TRUE,conf.int=TRUE,level=0.1) sensitivity.specificity Sensitivity and specificity for a diagnostic test. Description This function calculates the sensitivity and specificity for a diagnostic test. Definition of these two concepts can be found in Agresti (2018, ISBN: 978-1-119-40528-3). Usage sensitivity.specificity(A, show.matrix = FALSE) Arguments A a 2x2 matrix object where A[1,1] contains the number of people with the disease and with a positive test result; A[1,2], the number of people without the disease with a positive test result; A[2,1], the number of people with the disease with a negative test result; A[2,2], the number of people without the disease and with a negative test result. show.matrix a logical value indicating whether the matrix A must be shown. Value A vector object of two components: The first one cointains the sensitivity and the second compo- nent, the specificity. References <NAME>. (2018). An introduction to categorical data analysis. <NAME> & Sons. ISBN: 978-1- 119-40528-3. Examples A<-matrix(c(744,231,421,659),nrow=2) sensitivity.specificity(A,show.matrix=TRUE)
thermal-print
rust
Rust
Crate thermal_print === Support for the CSN-A2 thermal printer via `embedded_hal`. This crate also supports bitmap printing via `tinybmp`. Usage --- Create a new `Printer` on a serial port on your platform and write text via the implemented `core::fmt::Write` trait. You can use the `write!` and `writeln!` macros to accomplish this. See the `Printer` struct documentation for advanced capabilities, such as printing barcodes and bitmaps. Structs --- PrintModeConfigures print options such as the font used, white-on-black, upside-down or bold printing, as well as double-width, double-height and strikethrough modes via individual `bool` flags. PrintModeBuilderBuilder for `PrintMode`. PrintSettingsDefines the printer’s heat settings. PrintSettingsBuilderBuilder for `PrintSettings`. PrinterA representation of the thermal printer. Implements the `core::fmt::Write` trait for printing normal text. Enums --- BarCodeSpecialCharacterThese are special characters described in the printer documentation. BarCodeSystemDefines the barcode system to be used. BarcodeWidthSee the table below for barcode width options depending on the barcode type. The default is `Width3`. CharacterSetDetermines the used international character set. Default: `USA`. CodeTableDetermines the used code page. Default: `CP437`. FontSpecifies the used internal printer font. User-defined fonts are currently not supported by this driver. JustificationDetermines whether text is aligned left, center, or right. PrintModeBuilderErrorError type for PrintModeBuilder PrintSettingsBuilderErrorError type for PrintSettingsBuilder RasterBitImageModeDefines the raster bit-image mode. UnderlineSets no, normal, or thick underlining. Constants --- PIXEL_COLOR_CUTOFFDetermines a cutoff value each pixel in a `RawBmp` is compared against. Pixels below this value get printed as a dot, pixels above not. Crate thermal_print === Support for the CSN-A2 thermal printer via `embedded_hal`. This crate also supports bitmap printing via `tinybmp`. Usage --- Create a new `Printer` on a serial port on your platform and write text via the implemented `core::fmt::Write` trait. You can use the `write!` and `writeln!` macros to accomplish this. See the `Printer` struct documentation for advanced capabilities, such as printing barcodes and bitmaps. Structs --- PrintModeConfigures print options such as the font used, white-on-black, upside-down or bold printing, as well as double-width, double-height and strikethrough modes via individual `bool` flags. PrintModeBuilderBuilder for `PrintMode`. PrintSettingsDefines the printer’s heat settings. PrintSettingsBuilderBuilder for `PrintSettings`. PrinterA representation of the thermal printer. Implements the `core::fmt::Write` trait for printing normal text. Enums --- BarCodeSpecialCharacterThese are special characters described in the printer documentation. BarCodeSystemDefines the barcode system to be used. BarcodeWidthSee the table below for barcode width options depending on the barcode type. The default is `Width3`. CharacterSetDetermines the used international character set. Default: `USA`. CodeTableDetermines the used code page. Default: `CP437`. FontSpecifies the used internal printer font. User-defined fonts are currently not supported by this driver. JustificationDetermines whether text is aligned left, center, or right. PrintModeBuilderErrorError type for PrintModeBuilder PrintSettingsBuilderErrorError type for PrintSettingsBuilder RasterBitImageModeDefines the raster bit-image mode. UnderlineSets no, normal, or thick underlining. Constants --- PIXEL_COLOR_CUTOFFDetermines a cutoff value each pixel in a `RawBmp` is compared against. Pixels below this value get printed as a dot, pixels above not. Struct thermal_print::Printer === ``` pub struct Printer<Port: Write<u8>, Delay: DelayUs<u32>> { pub serial: Port, pub delay: Delay, /* private fields */ } ``` A representation of the thermal printer. Implements the `core::fmt::Write` trait for printing normal text. Fields --- `serial: Port``delay: Delay`Implementations --- source### impl<Port: Write<u8>, Delay: DelayUs<u32>> Printer<Port, Delaysource#### pub fn new(serial: Port, delay: Delay) -> Printer<Port, DelayCreate a new `Printer` with default settings. You must specify the serial port to be used, as well as a delay implementation of your HAL to allow the driver to block while the printer is outputting text. source#### pub fn reset(&mut self) Send the initialization sequence and configure tab stops. source#### pub fn wake(&mut self) Wake the device from sleep. Also block for 75ms, as according to the datasheet the printer needs at least 50ms in order to be ready to receive commands. source#### pub fn init(&mut self) Block for 500ms to allow the printer to boot, then wake it up, disable sleep, and call reset. source#### pub fn set_print_mode(&mut self, print_mode: PrintMode) Select print mode(s), such as inverse printing or double-height mode. source#### pub fn set_print_settings(&mut self, print_settings: PrintSettings) Configure print settings. See `PrintSettings` for more information. source#### pub fn set_justification(&mut self, justification: Justification) source#### pub fn set_underline(&mut self, mode: Underline) source#### pub fn set_character_set(&mut self, character_set: CharacterSet) source#### pub fn set_code_table(&mut self, code_table: CodeTable) source#### pub fn print_bitmap(&mut self, bmp: RawBmp<'_>, mode: RasterBitImageMode) Print a bitmap image. This command is not affected by print modes, but justification is respected. Since only monochrome images can be printed, the raw color value of each pixel is matched against `PIXEL_COLOR_CUTOFF`. If a pixel color is below this value, it produces a dot in the output (reasoning that darker pixels should be printed, while lighter ones should not be), otherwise not. ##### Example ``` printer.init(); printer.print_bitmap( RawBmp::from_slice( include_bytes!("../resources/ferris.bmp") ).unwrap(), RasterBitImageMode::Normal ); ``` source#### pub fn print_barcode(&mut self, system: BarCodeSystem, text: &str) Print a barcode with the specified `BarCodeSystem`. Note that each system requires a specific range of characters. source#### pub fn set_barcode_height(&mut self, height: u8) Set the barcode height to the specified number of dots. source#### pub fn set_barcode_left_space(&mut self, space: u8) Set the space to the left of the barcode to the specified number of dots. source#### pub fn set_barcode_width(&mut self, width: BarcodeWidth) Set the barcode width to the specified value. See `BarcodeWidth` for more information. source#### pub fn set_rotation_mode(&mut self, rotate: bool) Enable or disable the 90° clockwise rotation mode. source#### pub fn feed(&mut self) Feed the paper by exactly one line. source#### pub fn feed_n(&mut self, lines: u8) Feed the paper by the specified number of lines. Trait Implementations --- source### impl<Port: Write<u8>, Delay: DelayUs<u32>> Write for Printer<Port, Delaysource#### fn write_str(&mut self, s: &str) -> Result<(), ErrorWrites a string slice into this writer, returning whether the write succeeded. Read more source#### fn write_char(&mut self, c: char) -> Result<(), ErrorWrites a `char` into this writer, returning whether the write succeeded. Read more source#### fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), ErrorGlue for usage of the `write!` macro with implementors of this trait. Read more Auto Trait Implementations --- ### impl<Port, Delay> RefUnwindSafe for Printer<Port, Delay> where    Delay: RefUnwindSafe,    Port: RefUnwindSafe, ### impl<Port, Delay> Send for Printer<Port, Delay> where    Delay: Send,    Port: Send, ### impl<Port, Delay> Sync for Printer<Port, Delay> where    Delay: Sync,    Port: Sync, ### impl<Port, Delay> Unpin for Printer<Port, Delay> where    Delay: Unpin,    Port: Unpin, ### impl<Port, Delay> UnwindSafe for Printer<Port, Delay> where    Delay: UnwindSafe,    Port: UnwindSafe, Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Struct thermal_print::PrintMode === ``` pub struct PrintMode { pub font: Font, pub inverse: bool, pub upside_down: bool, pub emph: bool, pub double_height: bool, pub double_width: bool, pub delete_line: bool, } ``` Configures print options such as the font used, white-on-black, upside-down or bold printing, as well as double-width, double-height and strikethrough modes via individual `bool` flags. Prefer to use `PrintModeBuilder` to construct. Fields --- `font: Font`the `Font` to be used `inverse: bool`enables white-on-black printing `upside_down: bool`enables upside-down printing `emph: bool`enables bold printing `double_height: bool`enables double-height printing mode `double_width: bool`enables double-width printing mode `delete_line: bool`enables strikethrough mode Trait Implementations --- source### impl Clone for PrintMode source#### fn clone(&self) -> PrintMode Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Default for PrintMode source#### fn default() -> PrintMode Returns the “default value” for a type. Read more source### impl Into<u8> for PrintMode source#### fn into(self) -> u8 Converts this type into the (usually inferred) input type. source### impl Copy for PrintMode Auto Trait Implementations --- ### impl RefUnwindSafe for PrintMode ### impl Send for PrintMode ### impl Sync for PrintMode ### impl Unpin for PrintMode ### impl UnwindSafe for PrintMode Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Struct thermal_print::PrintModeBuilder === ``` pub struct PrintModeBuilder { /* private fields */ } ``` Builder for `PrintMode`. Implementations --- source### impl PrintModeBuilder source#### pub fn font<VALUE: Into<Font>>(&mut self, value: VALUE) -> &mutSelf the `Font` to be used source#### pub fn inverse<VALUE: Into<bool>>(&mut self, value: VALUE) -> &mutSelf enables white-on-black printing source#### pub fn upside_down<VALUE: Into<bool>>(&mut self, value: VALUE) -> &mutSelf enables upside-down printing source#### pub fn emph<VALUE: Into<bool>>(&mut self, value: VALUE) -> &mutSelf enables bold printing source#### pub fn double_height<VALUE: Into<bool>>(&mut self, value: VALUE) -> &mutSelf enables double-height printing mode source#### pub fn double_width<VALUE: Into<bool>>(&mut self, value: VALUE) -> &mutSelf enables double-width printing mode source#### pub fn delete_line<VALUE: Into<bool>>(&mut self, value: VALUE) -> &mutSelf enables strikethrough mode source#### pub fn build(&self) -> Result<PrintMode, PrintModeBuilderErrorBuilds a new `PrintMode`. ##### Errors If a required field has not been initialized. Trait Implementations --- source### impl Clone for PrintModeBuilder source#### fn clone(&self) -> PrintModeBuilder Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Default for PrintModeBuilder source#### fn default() -> Self Returns the “default value” for a type. Read more Auto Trait Implementations --- ### impl RefUnwindSafe for PrintModeBuilder ### impl Send for PrintModeBuilder ### impl Sync for PrintModeBuilder ### impl Unpin for PrintModeBuilder ### impl UnwindSafe for PrintModeBuilder Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Struct thermal_print::PrintSettings === ``` pub struct PrintSettings { /* private fields */ } ``` Defines the printer’s heat settings. Prefer to use `PrintSettingsBuilder` to construct. Trait Implementations --- source### impl Clone for PrintSettings source#### fn clone(&self) -> PrintSettings Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Default for PrintSettings source#### fn default() -> Self Returns the “default value” for a type. Read more source### impl Into<[u8; 3]> for PrintSettings source#### fn into(self) -> [u8; 3] Converts this type into the (usually inferred) input type. source### impl Copy for PrintSettings Auto Trait Implementations --- ### impl RefUnwindSafe for PrintSettings ### impl Send for PrintSettings ### impl Sync for PrintSettings ### impl Unpin for PrintSettings ### impl UnwindSafe for PrintSettings Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Struct thermal_print::PrintSettingsBuilder === ``` pub struct PrintSettingsBuilder { /* private fields */ } ``` Builder for `PrintSettings`. Implementations --- source### impl PrintSettingsBuilder source#### pub fn dots<VALUE: Into<u8>>(&mut self, value: VALUE) -> &mutSelf The maximum number of print head elements that will fire simultaneously. More dots require a higher peak current, but speed up the printing process. Unit: 8 dots. Default: 11 (96 dots) source#### pub fn time<VALUE: Into<u8>>(&mut self, value: VALUE) -> &mutSelf The duration that the heat elements are fired. A longer heating time results in a darker print, but a slower printing speed. Unit: 10 microseconds. Default: 1.2 milliseconds. source#### pub fn interval<VALUE: Into<u8>>(&mut self, value: VALUE) -> &mutSelf The recovery time between firing of the heating dots. A longer recovery interval results in clearer prints, but a slower printing speed and possibly static friction between the paper and the print roll. Unit: 10 microseconds. Default: 200 microseconds. source#### pub fn build(&self) -> Result<PrintSettings, PrintSettingsBuilderErrorBuilds a new `PrintSettings`. ##### Errors If a required field has not been initialized. Trait Implementations --- source### impl Clone for PrintSettingsBuilder source#### fn clone(&self) -> PrintSettingsBuilder Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Default for PrintSettingsBuilder source#### fn default() -> Self Returns the “default value” for a type. Read more Auto Trait Implementations --- ### impl RefUnwindSafe for PrintSettingsBuilder ### impl Send for PrintSettingsBuilder ### impl Sync for PrintSettingsBuilder ### impl Unpin for PrintSettingsBuilder ### impl UnwindSafe for PrintSettingsBuilder Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Enum thermal_print::BarCodeSpecialCharacter === ``` #[repr(u8)] pub enum BarCodeSpecialCharacter { Shift, CodeA, CodeB, CodeC, Fnc1, Fnc2, Fnc3, Fnc4, CurlyOpen, } ``` These are special characters described in the printer documentation. TODO: Find out what exactly this is useful for. Variants --- ### `Shift` ### `CodeA` ### `CodeB` ### `CodeC` ### `Fnc1` ### `Fnc2` ### `Fnc3` ### `Fnc4` ### `CurlyOpen` “{” Trait Implementations --- source### impl From<BarCodeSpecialCharacter> for u8 source#### fn from(enum_value: BarCodeSpecialCharacter) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for BarCodeSpecialCharacter ### impl Send for BarCodeSpecialCharacter ### impl Sync for BarCodeSpecialCharacter ### impl Unpin for BarCodeSpecialCharacter ### impl UnwindSafe for BarCodeSpecialCharacter Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Enum thermal_print::BarCodeSystem === ``` #[repr(u8)] pub enum BarCodeSystem { UpcA, UpcE, Ean13, Ean8, Code39, Itf, Codabar, Code93, Code128, } ``` Defines the barcode system to be used. Some systems are considered binary-level, and some are multi-level systems, which is important for setting the barcode width. See `BarcodeWidth` for more information. Variants --- ### `UpcA` ### `UpcE` ### `Ean13` ### `Ean8` ### `Code39` ### `Itf` ### `Codabar` ### `Code93` ### `Code128` Trait Implementations --- source### impl Default for BarCodeSystem source#### fn default() -> Self Returns the “default value” for a type. Read more source### impl From<BarCodeSystem> for u8 source#### fn from(enum_value: BarCodeSystem) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for BarCodeSystem ### impl Send for BarCodeSystem ### impl Sync for BarCodeSystem ### impl Unpin for BarCodeSystem ### impl UnwindSafe for BarCodeSystem Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Enum thermal_print::BarcodeWidth === ``` #[repr(u8)] pub enum BarcodeWidth { Width2, Width3, Width4, Width5, Width6, } ``` See the table below for barcode width options depending on the barcode type. The default is `Width3`. | Width | Module Width (mm) for multi-level barcode | Thin Element (mm) for binary-level | Thick Element (mm) for binary-level | | --- | --- | --- | --- | | `Width2` | 0.250 | 0.250 | 0.625 | | `Width3` | 0.375 | 0.375 | 1.000 | | `Width4` | 0.560 | 0.560 | 1.250 | | `Width5` | 0.625 | 0.625 | 1.625 | | `Width6` | 0.750 | 0.750 | 2.000 | `UpcA`, `UpcE`, `Ean8`, `Ean13` `Code93` and `Code128` are considered multi-level barcodes. `Code39`, `Itf` and `Codabar` are binary-level codes. Variants --- ### `Width2` ### `Width3` ### `Width4` ### `Width5` ### `Width6` Trait Implementations --- source### impl From<BarcodeWidth> for u8 source#### fn from(enum_value: BarcodeWidth) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for BarcodeWidth ### impl Send for BarcodeWidth ### impl Sync for BarcodeWidth ### impl Unpin for BarcodeWidth ### impl UnwindSafe for BarcodeWidth Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Enum thermal_print::CharacterSet === ``` #[repr(u8)] pub enum CharacterSet { USA, France, Germany, UK, DenmarkI, Sweden, Italy, SpainI, Japan, Norway, DenmarkII, SpainII, LatinAmerica, Korea, SloveniaCroatia, China, } ``` Determines the used international character set. Default: `USA`. Variants --- ### `USA` ### `France` ### `Germany` ### `UK` ### `DenmarkI` ### `Sweden` ### `Italy` ### `SpainI` ### `Japan` ### `Norway` ### `DenmarkII` ### `SpainII` ### `LatinAmerica` ### `Korea` ### `SloveniaCroatia` ### `China` Trait Implementations --- source### impl Default for CharacterSet source#### fn default() -> Self Returns the “default value” for a type. Read more source### impl From<CharacterSet> for u8 source#### fn from(enum_value: CharacterSet) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for CharacterSet ### impl Send for CharacterSet ### impl Sync for CharacterSet ### impl Unpin for CharacterSet ### impl UnwindSafe for CharacterSet Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Enum thermal_print::CodeTable === ``` #[repr(u8)] pub enum CodeTable { CP437, Katakana, CP850, CP860, CP863, CP865, WCP1251, CP866, MIK, CP755, Iran, CP862, WCP1252, WCP1253, CP852, CP858, IranII, Latvian, CP864, Iso8859_1, CP737, WCP1257, Thai, CP720, CP855, CP857, WCP1250, CP775, WCP1254, WCP1255, WCP1256, WCP1258, Iso8859_2, Iso8859_3, Iso8859_4, Iso8859_5, Iso8859_6, Iso8859_7, Iso8859_8, Iso8859_9, Iso8859_15, Thai2, CP856, CP874, } ``` Determines the used code page. Default: `CP437`. Variants --- ### `CP437` ### `Katakana` ### `CP850` ### `CP860` ### `CP863` ### `CP865` ### `WCP1251` ### `CP866` ### `MIK` ### `CP755` ### `Iran` ### `CP862` ### `WCP1252` ### `WCP1253` ### `CP852` ### `CP858` ### `IranII` ### `Latvian` ### `CP864` ### `Iso8859_1` ### `CP737` ### `WCP1257` ### `Thai` ### `CP720` ### `CP855` ### `CP857` ### `WCP1250` ### `CP775` ### `WCP1254` ### `WCP1255` ### `WCP1256` ### `WCP1258` ### `Iso8859_2` ### `Iso8859_3` ### `Iso8859_4` ### `Iso8859_5` ### `Iso8859_6` ### `Iso8859_7` ### `Iso8859_8` ### `Iso8859_9` ### `Iso8859_15` ### `Thai2` ### `CP856` ### `CP874` Trait Implementations --- source### impl Default for CodeTable source#### fn default() -> Self Returns the “default value” for a type. Read more source### impl From<CodeTable> for u8 source#### fn from(enum_value: CodeTable) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for CodeTable ### impl Send for CodeTable ### impl Sync for CodeTable ### impl Unpin for CodeTable ### impl UnwindSafe for CodeTable Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Enum thermal_print::Font === ``` pub enum Font { FontA, FontB, } ``` Specifies the used internal printer font. User-defined fonts are currently not supported by this driver. Variants --- ### `FontA` ### `FontB` Trait Implementations --- source### impl Clone for Font source#### fn clone(&self) -> Font Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Default for Font source#### fn default() -> Self Returns the “default value” for a type. Read more source### impl Copy for Font Auto Trait Implementations --- ### impl RefUnwindSafe for Font ### impl Send for Font ### impl Sync for Font ### impl Unpin for Font ### impl UnwindSafe for Font Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Enum thermal_print::Justification === ``` pub enum Justification { Left, Center, Right, } ``` Determines whether text is aligned left, center, or right. Variants --- ### `Left` ### `Center` ### `Right` Trait Implementations --- source### impl Default for Justification source#### fn default() -> Self Returns the “default value” for a type. Read more Auto Trait Implementations --- ### impl RefUnwindSafe for Justification ### impl Send for Justification ### impl Sync for Justification ### impl Unpin for Justification ### impl UnwindSafe for Justification Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Enum thermal_print::PrintModeBuilderError === ``` #[non_exhaustive] pub enum PrintModeBuilderError { UninitializedField(&'static str), ValidationError(String), } ``` Error type for PrintModeBuilder Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### `UninitializedField(&'static str)` Uninitialized field ### `ValidationError(String)` Custom validation error Trait Implementations --- source### impl Debug for PrintModeBuilderError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for PrintModeBuilderError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl From<String> for PrintModeBuilderError source#### fn from(s: String) -> Self Converts to this type from the input type. source### impl From<UninitializedFieldError> for PrintModeBuilderError source#### fn from(s: UninitializedFieldError) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for PrintModeBuilderError ### impl Send for PrintModeBuilderError ### impl Sync for PrintModeBuilderError ### impl Unpin for PrintModeBuilderError ### impl UnwindSafe for PrintModeBuilderError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Enum thermal_print::PrintSettingsBuilderError === ``` #[non_exhaustive] pub enum PrintSettingsBuilderError { UninitializedField(&'static str), ValidationError(String), } ``` Error type for PrintSettingsBuilder Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### `UninitializedField(&'static str)` Uninitialized field ### `ValidationError(String)` Custom validation error Trait Implementations --- source### impl Debug for PrintSettingsBuilderError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for PrintSettingsBuilderError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl From<String> for PrintSettingsBuilderError source#### fn from(s: String) -> Self Converts to this type from the input type. source### impl From<UninitializedFieldError> for PrintSettingsBuilderError source#### fn from(s: UninitializedFieldError) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for PrintSettingsBuilderError ### impl Send for PrintSettingsBuilderError ### impl Sync for PrintSettingsBuilderError ### impl Unpin for PrintSettingsBuilderError ### impl UnwindSafe for PrintSettingsBuilderError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Enum thermal_print::RasterBitImageMode === ``` #[repr(u8)] pub enum RasterBitImageMode { Normal, DoubleWidth, DoubleHeight, Quadruple, } ``` Defines the raster bit-image mode. | Mode | Vertical Density | Horizontal Density | | --- | --- | --- | | `Normal` | 203.2dpi | 203.2dpi | | `DoubleWidth` | 203.2dpi | 101.6dpi | | `DoubleHeight` | 101.6dpi | 203.2dpi | | `Quadruple` | 101.6dpi | 101.6dpi | Variants --- ### `Normal` ### `DoubleWidth` ### `DoubleHeight` ### `Quadruple` Trait Implementations --- source### impl Default for RasterBitImageMode source#### fn default() -> Self Returns the “default value” for a type. Read more source### impl From<RasterBitImageMode> for u8 source#### fn from(enum_value: RasterBitImageMode) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for RasterBitImageMode ### impl Send for RasterBitImageMode ### impl Sync for RasterBitImageMode ### impl Unpin for RasterBitImageMode ### impl UnwindSafe for RasterBitImageMode Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Enum thermal_print::Underline === ``` pub enum Underline { None, Normal, Double, } ``` Sets no, normal, or thick underlining. Variants --- ### `None` ### `Normal` ### `Double` Trait Implementations --- source### impl Default for Underline source#### fn default() -> Self Returns the “default value” for a type. Read more Auto Trait Implementations --- ### impl RefUnwindSafe for Underline ### impl Send for Underline ### impl Sync for Underline ### impl Unpin for Underline ### impl UnwindSafe for Underline Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Az for T source#### fn az<Dst>(self) -> Dst where    T: Cast<Dst>, Casts the value. source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<Src, Dst> CastFrom<Src> for Dst where    Src: Cast<Dst>, source#### fn cast_from(src: Src) -> Dst Casts the value. source### impl<T> CheckedAs for T source#### fn checked_as<Dst>(self) -> Option<Dst> where    T: CheckedCast<Dst>, Casts the value. source### impl<Src, Dst> CheckedCastFrom<Src> for Dst where    Src: CheckedCast<Dst>, source#### fn checked_cast_from(src: Src) -> Option<DstCasts the value. ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. Read more #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. Read more #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more #### fn fmt_list(self) -> FmtList<Self> where    &'aSelf: for<'a> IntoIterator, Formats each item in a sequence. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> OverflowingAs for T source#### fn overflowing_as<Dst>(self) -> (Dst, bool) where    T: OverflowingCast<Dst>, Casts the value. source### impl<Src, Dst> OverflowingCastFrom<Src> for Dst where    Src: OverflowingCast<Dst>, source#### fn overflowing_cast_from(src: Src) -> (Dst, bool) OverflowingCasts the value. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more source### impl<T> SaturatingAs for T source#### fn saturating_as<Dst>(self) -> Dst where    T: SaturatingCast<Dst>, Casts the value. source### impl<Src, Dst> SaturatingCastFrom<Src> for Dst where    Src: SaturatingCast<Dst>, source#### fn saturating_cast_from(src: Src) -> Dst Casts the value. ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> UnwrappedAs for T source#### fn unwrapped_as<Dst>(self) -> Dst where    T: UnwrappedCast<Dst>, Casts the value. source### impl<Src, Dst> UnwrappedCastFrom<Src> for Dst where    Src: UnwrappedCast<Dst>, source#### fn unwrapped_cast_from(src: Src) -> Dst UnwrappedCasts the value. source### impl<T> WrappingAs for T source#### fn wrapping_as<Dst>(self) -> Dst where    T: WrappingCast<Dst>, Casts the value. source### impl<Src, Dst> WrappingCastFrom<Src> for Dst where    Src: WrappingCast<Dst>, source#### fn wrapping_cast_from(src: Src) -> Dst WrappingCasts the value. Constant thermal_print::PIXEL_COLOR_CUTOFF === ``` pub const PIXEL_COLOR_CUTOFF: u32 = 0x0000FFFF; ``` Determines a cutoff value each pixel in a `RawBmp` is compared against. Pixels below this value get printed as a dot, pixels above not.
exrm
hex
Erlang
Getting Started === How to get up and running with releases --- This project’s goal is to make releases with Elixir projects a breeze. It is composed of a mix task, and build files required to successfully take your Elixir project and perform a release build, and a [simplified configuration mechanism](https://github.com/bitwalker/conform) which integrates with your current configuration and makes it easy for your operations group to configure the release once deployed. All you have to do to get started is the following: Start by adding exrm as a dependency to your project: ``` defp deps do [{:exrm, "~> 0.18.1"}] end ``` ### Usage You can build a release with the `release` task: ``` $ mix release ``` This task constructs the complete release for you. The output is sent to `rel/<project>`. To see what flags you can pass to this task, use `mix help release`. You can start a console connected to the release build of your application with: ``` $ rel/<project>/bin/<project> console ``` ### Testing a release during development Rather than having to build a release, deploy, then test, you can actually test your release during development by using `mix release --dev`. This symlinks your application’s code into the release, allowing you to make code changes, then recompile and restart your release to see the changes. Being able to rapidly test and tweak your release like this goes a long way to making the release process less tedious! ### Cleanup You can clean up release artifacts produced by exrm with: ``` $ mix release.clean ``` This will clean up any temporary artifacts related to the current version, and allow you to effectively start a release build from scratch. By passing the `--implode` flag, you can further extend the clean up to *all* release related artifacts, effectively resetting yourself to a pre-exrm state. This should be done carefully, as anything related to releases will be removed! You can pass the `--no-confirm` flag in addition to `--implode` if you want to bypass exrm’s warning about removing all artifacts (this is primarily for automated tasks, but might come in useful during testing scenarios) ### **IMPORTANT** It is currently not supported to perform hot upgrades/downgrades from the `rel` directory. This is because the upgrade/downgrade process deletes files from the release when it is installed, which will cause issues when you are attempting to build a release of the next version of your app. It is important that you do actual deployments of your app outside of the build directory! exrm v1.0.8 Mix.Tasks.Release === Build a release for the current mix application. Examples --- ``` # Build a release using defaults mix release # Pass args to erlexec when running the release mix release --erl="-env TZ UTC" # Enable dev mode. Make changes, compile using MIX_ENV=prod # and execute your release again to pick up the changes mix release --dev # Set the verbosity level mix release --verbosity=[silent|quiet|normal|verbose] # Do not ask for confirmation to skip missing applications warning mix release --no-confirm-missing ``` You may pass any number of arguments as needed. Make sure you pass arguments using `--key=value`, not `--key value`, as the args may be interpreted incorrectly otherwise. Summary === [Functions](#functions) --- [relx_config_path()](#relx_config_path/0) [run(args)](#run/1) Callback implementation for `c:Mix.Task.run/1` Functions === relx_config_path() run(args) Callback implementation for `c:Mix.Task.run/1`. exrm v1.0.8 Mix.Tasks.Release.Clean === Clean up any release-related files. Examples --- ``` # Cleans the release for the current version of the project mix release.clean # Remove all files generated by exrm, including releases mix release.clean --implode # Implode, but do not confirm (DANGEROUS) mix release.clean --implode --no-confirm ``` Summary === [Functions](#functions) --- [do_cleanup(atom)](#do_cleanup/1) [do_run(args)](#do_run/1) [run(args)](#run/1) Callback implementation for `c:Mix.Task.run/1` Functions === do_cleanup(atom) do_run(args) run(args) Callback implementation for `c:Mix.Task.run/1`. exrm v1.0.8 Mix.Tasks.Release.Plugins === View information about active release plugins Examples --- ``` # View all active plugins mix release.plugins # View detailed info about a plugin, if available mix release.plugins <plugin_name> ``` Summary === [Functions](#functions) --- [run(args)](#run/1) Callback implementation for `c:Mix.Task.run/1` Functions === run(args) Callback implementation for `c:Mix.Task.run/1`. exrm v1.0.8 ReleaseManager.Appups === Module for auto-generating appups between releases. Summary === [Functions](#functions) --- [make(application, v1, v2, v1_path, v2_path)](#make/5) Generate a .appup for the given application, start version, and upgrade version Functions === make(application, v1, v2, v1_path, v2_path) Generate a .appup for the given application, start version, and upgrade version. ``` ## Parameter information application: the application name as an atom v1: the start version, such as "0.0.1" v2: the upgrade version, such as "0.0.2" v1_path: the path to the v1 artifacts (rel/<app>/lib/<app>-0.0.1) v2_path: the path to the v2 artifacts (_build/prod/lib/<app>) ``` exrm v1.0.8 ReleaseManager.Config === Configuration for the release task. Contains the following values: ``` name: The name of your application version: The version of your application dev?: Is this release being built in dev mode env: The mix environment the app should be build for erl: The binary containing all options to pass to erl upgrade?: Is this release an upgrade? verbosity: The verbosity level, one of [silent|quiet|normal|verbose] package: Path to the generated release package. ``` exrm v1.0.8 ReleaseManager.Deps === This module provides functions for retrieving dependency information. Summary === [Functions](#functions) --- [get_explicit_applications()](#get_explicit_applications/0) Returns a list of explict applications found in mix.exs :applications/:included_applications [get_implicit_applications(extras \\ [])](#get_implicit_applications/1) Returns a graph (represented as a nested keyword list) of implicitly included applications for the current project [get_included_applications()](#get_included_applications/0) Gets all applications and what applications they include [get_included_applications(deps)](#get_included_applications/1) [get_missing_applications(options \\ [])](#get_missing_applications/1) Discovers missing applications which could prevent a release from running properly. Returns a tree to be formatted for output. The tree is a nested kwlist [get_missing_applications(deps, options)](#get_missing_applications/2) [print_missing_applications(options \\ [])](#print_missing_applications/1) Produces a list of lines to be printed, which display each missing application, the depedency graph representing where it comes from, and a short message describing where it should be added Functions === get_explicit_applications() Returns a list of explict applications found in mix.exs :applications/:included_applications get_implicit_applications(extras \\ []) Returns a graph (represented as a nested keyword list) of implicitly included applications for the current project. get_included_applications() Gets all applications and what applications they include. get_included_applications(deps) get_missing_applications(options \\ []) Discovers missing applications which could prevent a release from running properly. Returns a tree to be formatted for output. The tree is a nested kwlist. get_missing_applications(deps, options) print_missing_applications(options \\ []) Produces a list of lines to be printed, which display each missing application, the depedency graph representing where it comes from, and a short message describing where it should be added: Example --- ``` exrm -> conform -> neotoma => neotoma is missing from conform exrm -> relx -> providers -> getopt => getopt is missing from providers exrm -> relx -> getopt => getopt is missing from relx exrm -> relx -> erlware_commons => erlware_commons is missing from relx exrm -> relx -> bbmustache => bbmustache is missing from relx ``` exrm v1.0.8 ReleaseManager.Plugin behaviour === This module provide a simple way to add additional steps to the release task. You can define your own plugins using the sample definition below. Note that the module namespace must be nested under `ReleaseManager.Plugin.*`. ``` defmodule ReleaseManager.Plugin.Hello do use ReleaseManager.Plugin def before_release(%Config{} = config) do info "This is executed just prior to compiling the release" end def after_release(%Config{} = config) do info "This is executed just after compiling the release" end def after_package(%Config{} = config) do info "This is executed just after packaging the release" end def after_cleanup(_args) do info "This is executed just after running cleanup" end end ``` A couple things are imported or aliased for you. Those things are: * The ReleaseManager.Config struct is aliased for you to just Config * `debug/1`, `info/1`, `warn/1`, `notice/1`, and `error/1` are imported for you. These should be used to do any output for the user. `before_release/1` and `after_release/1` are required callbacks, and will each be passed a `Config` struct, containing the configuration for the release task. You can choose to return the config struct modified or unmodified, or not at all. In the former case, any modifications you made will be passed on to the remaining plugins and the final release task. The required callback `after_cleanup/1` is passed the command line arguments. The return value is not used. All plugins are executed just prior, and just after compiling the release, as the name of the callbacks reflect. The `before_release/1` callback is called after some internal tasks, such as generating the sys.config and others. Summary === [Functions](#functions) --- [load_all()](#load_all/0) Loads all plugins in all code paths [Callbacks](#callbacks) --- [after_cleanup(list)](#c:after_cleanup/1) [after_package(arg0)](#c:after_package/1) [after_release(arg0)](#c:after_release/1) [before_release(arg0)](#c:before_release/1) A plugin needs to implement `before_release/1`, and `after_release/1` both of which receive a %ReleaseManager.Config struct, as well as `after_cleanup/1`, which receives the arguments given for the command as a list of strings Functions === load_all() #### Specs ``` load_all :: [] | [atom] ``` Loads all plugins in all code paths. Callbacks === after_cleanup(list) #### Specs ``` after_cleanup([[String.t](http://elixir-lang.org/docs/stable/elixir/String.html#t:t/0)]) :: any ``` after_package(arg0) #### Specs ``` after_package([ReleaseManager.Config.t](ReleaseManager.Config.html#t:t/0)) :: any ``` after_release(arg0) #### Specs ``` after_release([ReleaseManager.Config.t](ReleaseManager.Config.html#t:t/0)) :: any ``` before_release(arg0) #### Specs ``` before_release([ReleaseManager.Config.t](ReleaseManager.Config.html#t:t/0)) :: any ``` A plugin needs to implement `before_release/1`, and `after_release/1` both of which receive a %ReleaseManager.Config struct, as well as `after_cleanup/1`, which receives the arguments given for the command as a list of strings. exrm v1.0.8 ReleaseManager.Plugin.Appups === Generates a .appup for each dependency in your project Summary === [Functions](#functions) --- [after_cleanup()](#after_cleanup/1) Callback implementation for [`ReleaseManager.Plugin.after_cleanup/1`](ReleaseManager.Plugin.html#c:after_cleanup/1) [after_package()](#after_package/1) Callback implementation for [`ReleaseManager.Plugin.after_package/1`](ReleaseManager.Plugin.html#c:after_package/1) [after_release()](#after_release/1) Callback implementation for [`ReleaseManager.Plugin.after_release/1`](ReleaseManager.Plugin.html#c:after_release/1) [before_release(config)](#before_release/1) Callback implementation for [`ReleaseManager.Plugin.before_release/1`](ReleaseManager.Plugin.html#c:before_release/1) [do_appup(config, list)](#do_appup/2) Functions === after_cleanup() Callback implementation for [`ReleaseManager.Plugin.after_cleanup/1`](ReleaseManager.Plugin.html#c:after_cleanup/1). after_package() Callback implementation for [`ReleaseManager.Plugin.after_package/1`](ReleaseManager.Plugin.html#c:after_package/1). after_release() Callback implementation for [`ReleaseManager.Plugin.after_release/1`](ReleaseManager.Plugin.html#c:after_release/1). before_release(config) Callback implementation for [`ReleaseManager.Plugin.before_release/1`](ReleaseManager.Plugin.html#c:before_release/1). do_appup(config, list) exrm v1.0.8 ReleaseManager.Plugin.Consolidation === Summary === [Functions](#functions) --- [after_cleanup()](#after_cleanup/1) Callback implementation for [`ReleaseManager.Plugin.after_cleanup/1`](ReleaseManager.Plugin.html#c:after_cleanup/1) [after_package()](#after_package/1) Callback implementation for [`ReleaseManager.Plugin.after_package/1`](ReleaseManager.Plugin.html#c:after_package/1) [after_release()](#after_release/1) Callback implementation for [`ReleaseManager.Plugin.after_release/1`](ReleaseManager.Plugin.html#c:after_release/1) [before_release(config)](#before_release/1) Callback implementation for [`ReleaseManager.Plugin.before_release/1`](ReleaseManager.Plugin.html#c:before_release/1) Functions === after_cleanup() Callback implementation for [`ReleaseManager.Plugin.after_cleanup/1`](ReleaseManager.Plugin.html#c:after_cleanup/1). after_package() Callback implementation for [`ReleaseManager.Plugin.after_package/1`](ReleaseManager.Plugin.html#c:after_package/1). after_release() Callback implementation for [`ReleaseManager.Plugin.after_release/1`](ReleaseManager.Plugin.html#c:after_release/1). before_release(config) Callback implementation for [`ReleaseManager.Plugin.before_release/1`](ReleaseManager.Plugin.html#c:before_release/1). exrm v1.0.8 ReleaseManager.Utils === This module provides helper functions for the `mix release` and `mix release.clean` tasks. Summary === [Functions](#functions) --- [abort!()](#abort!/0) Exits with exit status 1 [chmod(target, mode)](#chmod/2) Change user permissions for a target file or directory [get_elixir_lib_paths()](#get_elixir_lib_paths/0) Get the local paths of the current Elixir libraries [get_last_release(project)](#get_last_release/1) Get the most recent release prior to the current one [get_releases(project)](#get_releases/1) Get a list of tuples representing the previous releases [load_config(env, project_config \\ Mix.Project.config())](#load_config/2) Load the current project’s configuration [merge(old, new)](#merge/2) Merges two sets of Elixir/Erlang terms, where the terms come in the form of lists of tuples. For example, such as is found in the relx.config file [mix(command, env)](#mix/2) Call the _elixir mix binary with the given arguments [mix(command, env, atom)](#mix/3) [priv_path()](#priv_path/0) Get the priv path of the exrm dependency [read_terms(path)](#read_terms/1) Reads a file as Erlang terms [rel_dest_path()](#rel_dest_path/0) Get the rel path of the current project [rel_dest_path(files)](#rel_dest_path/1) Get the path to a file located in the rel directory of the current project. You can pass either a file name, or a list of directories to a file, like [rel_file_dest_path()](#rel_file_dest_path/0) Get the rel/.files path of the current project [rel_file_dest_path(files)](#rel_file_dest_path/1) Get the path to a file located in the rel/.files directory of the current project. You can pass either a file name, or a list of directories to a file, like [rel_file_source_path()](#rel_file_source_path/0) Get the priv/rel/files path of the exrm dependency [rel_file_source_path(file)](#rel_file_source_path/1) Get the path to a file located in priv/rel/files of the exrm dependency [rel_source_path()](#rel_source_path/0) Get the priv/rel path of the exrm dependency [rel_source_path(file)](#rel_source_path/1) Get the path to a file located in priv/rel of the exrm dependency [relx(name, version, verbosity, upgrade?, dev_mode?)](#relx/5) Execute `relx` [sort_versions(versions)](#sort_versions/1) Sort a list of versions, latest one first. Tries to use semver version compare, but can fall back to regular string compare [string_to_terms(str)](#string_to_terms/1) Convert a string to Erlang terms [with_env(env, fun)](#with_env/2) Perform some actions within the context of a specific mix environment [write_term(path, term)](#write_term/2) Writes an Elixir/Erlang term to the provided path [write_terms(path, terms)](#write_terms/2) Writes a collection of Elixir/Erlang terms to the provided path Functions === abort!() Exits with exit status 1 chmod(target, mode) Change user permissions for a target file or directory get_elixir_lib_paths() Get the local paths of the current Elixir libraries get_last_release(project) Get the most recent release prior to the current one get_releases(project) Get a list of tuples representing the previous releases: Examples --- ``` get_releases #=> [{"test", "0.0.1"}, {"test", "0.0.2"}] ``` load_config(env, project_config \\ Mix.Project.config()) Load the current project’s configuration merge(old, new) Merges two sets of Elixir/Erlang terms, where the terms come in the form of lists of tuples. For example, such as is found in the relx.config file mix(command, env) Call the _elixir mix binary with the given arguments mix(command, env, atom) priv_path() Get the priv path of the exrm dependency read_terms(path) Reads a file as Erlang terms rel_dest_path() Get the rel path of the current project. rel_dest_path(files) Get the path to a file located in the rel directory of the current project. You can pass either a file name, or a list of directories to a file, like: ``` iex> ReleaseManager.Utils.rel_dest_path "relx.config" "path/to/project/rel/relx.config" iex> ReleaseManager.Utils.rel_dest_path ["<project>", "lib", "<project>.appup"] "path/to/project/rel/<project>/lib/<project>.appup" ``` rel_file_dest_path() Get the rel/.files path of the current project. rel_file_dest_path(files) Get the path to a file located in the rel/.files directory of the current project. You can pass either a file name, or a list of directories to a file, like: ``` iex> ReleaseManager.Utils.rel_file_dest_path "sys.config" "path/to/project/rel/.files/sys.config" iex> ReleaseManager.Utils.rel_dest_path ["some", "path", "file.txt"] "path/to/project/rel/.files/some/path/file.txt" ``` rel_file_source_path() Get the priv/rel/files path of the exrm dependency rel_file_source_path(file) Get the path to a file located in priv/rel/files of the exrm dependency rel_source_path() Get the priv/rel path of the exrm dependency rel_source_path(file) Get the path to a file located in priv/rel of the exrm dependency relx(name, version, verbosity, upgrade?, dev_mode?) Execute `relx` sort_versions(versions) Sort a list of versions, latest one first. Tries to use semver version compare, but can fall back to regular string compare. string_to_terms(str) Convert a string to Erlang terms with_env(env, fun) Perform some actions within the context of a specific mix environment write_term(path, term) Writes an Elixir/Erlang term to the provided path write_terms(path, terms) Writes a collection of Elixir/Erlang terms to the provided path exrm v1.0.8 ReleaseManager.Utils.Logger === Summary === [Functions](#functions) --- [configure(verbosity)](#configure/1) [debug(message)](#debug/1) Print an informational message without color [error(message)](#error/1) Print an error message in red [info(message)](#info/1) Print an informational message in green [notice(message)](#notice/1) Print a notice in yellow [warn(message)](#warn/1) Print a warning message in yellow Functions === configure(verbosity) debug(message) Print an informational message without color error(message) Print an error message in red info(message) Print an informational message in green notice(message) Print a notice in yellow warn(message) Print a warning message in yellow
thumbnex
hex
Erlang
Thumbnex === [![Build Status](https://github.com/talklittle/thumbnex/actions/workflows/ci.yml/badge.svg)](https://github.com/talklittle/thumbnex/actions?query=workflow%3ACI) [![Module Version](https://img.shields.io/hexpm/v/thumbnex.svg)](https://hex.pm/packages/thumbnex) Elixir library to generate thumbnails from images and videos. Documentation: <https://hexdocs.pm/thumbnex/ Installation --- Add `:thumbnex` to your list of dependencies in `mix.exs`: ``` def deps do [ {:thumbnex, "~> 0.4.0"} ] end ``` Prerequisites --- * [ImageMagick](https://imagemagick.org) * [FFmpeg](https://ffmpeg.org) Release notes --- See the [changelog](changelog.html) for changes between versions. Examples --- Create a regular thumbnail: ``` Thumbnex.create_thumbnail( "/path/to/input.mp4", "/path/to/output.jpg", max_width: 200, max_height: 200 ) ``` Create a lightweight animated GIF preview: ``` Thumbnex.animated_gif_thumbnail( "/path/to/input.mp4", "/path/to/output.gif", frame_count: 4, fps: 1 ) ``` Copyright and License --- Copyright (c) 2016 <NAME> Thumbnex source code is licensed under the [MIT License](license.html). [MIT License](license.html) Thumbnex === Create thumbnails from images and videos. [Link to this section](#summary) Summary === [Functions](#functions) --- [animated_gif_thumbnail(input_path, output_path, opts \\ [])](#animated_gif_thumbnail/3) Create an animated GIF preview. [create_thumbnail(input_path, output_path, opts \\ [])](#create_thumbnail/3) Create a thumbnail image. [Link to this section](#functions) Functions === Thumbnex.Animations === [Link to this section](#summary) Summary === [Functions](#functions) --- [duration(input_path)](#duration/1) [Link to this section](#functions) Functions === Thumbnex.ExtractFrame === [Link to this section](#summary) Summary === [Functions](#functions) --- [multiple_frames(file_path, frame_count, fps, opts \\ [])](#multiple_frames/4) Extract multiple frames from the input file. Specify the number of frames, and the frames per second, to output. [single_frame(file_path, time_offset_seconds, opts \\ [])](#single_frame/3) Extract a single frame from the input file. [Link to this section](#functions) Functions === Thumbnex.Gifs === [Link to this section](#summary) Summary === [Functions](#functions) --- [duration(gif_path)](#duration/1) Return the GIF duration in seconds. [optimize_mogrify_image(image)](#optimize_mogrify_image/1) [Link to this section](#functions) Functions === API Reference === Modules --- [Thumbnex](Thumbnex.html) Create thumbnails from images and videos. [Thumbnex.Animations](Thumbnex.Animations.html) [Thumbnex.ExtractFrame](Thumbnex.ExtractFrame.html) [Thumbnex.Gifs](Thumbnex.Gifs.html) [Changelog](changelog.html)
nuget_Candid_GuideStarAPI.jsonl
personal_doc
JSON
# New Essentials API V3 launched! You can now get nonprofit information even faster. Learn more about the updates. # NEW — Check nonprofit compliance with California AB488 regulation using additional Charity Check API endpoint. More info HERE ## Use the world's most trusted and comprehensive philanthropy data for your app and websites Request free trial Explore API docs # Available APIs ## Taxonomy GraphQL API Use the power of Candid's Philanthropy Classification System (PCS) taxonomy. ## Nonprofit Eligibility API Verify a nonprofit's eligibility to receive donations through Apple Pay. ## Demographics API Enable insightful, impactful, and equitable giving decisions with a dynamic snapshot of Demographics data. ## Essentials API Boost your nonprofit search and access key nonprofit information. ## Premier API Enhance your apps, records, or experience with the power of the GuideStar Nonprofit Profile including robust nonprofit financials, people, DEI, and IRS compliance validation. ## Charity Check API Save time and ensure the nonprofits you support are IRS compliant. ## Grants API Leverage advanced search and filters to analyze the most comprehensive and accurate data on grants, funders, recipients, and funding activity. ## News API Access the only API on the market delivering real-time social sector news, curated from over 65,000 sources. # Available Solutions ## For grantmaking Solve pressing challenges presented with grantmaking by powering your solution with a Candid API. ## For donations Enable nonprofit eligibility screening to power donations through mobile payment providers. Welcome to Candid's developer portal! We are so glad you are here. What you will find is that Candid has a wide array of APIs for you to get the information you need to do good. Candid's APIs are versatile and complement the information you can find in some of our other products like GuideStar.org, Foundation Directory, and Foundation Maps. Candid's APIs are also used in some of our special topic pages, like our COVID-19 philanthropic response page and Racial Equity page, so you can stay up to date, in real time, on what matters most. Whether you are building a platform supporting the social sector, integrating data to streamline the grantmaking lifecycle, or curating trending topics in the philanthropic community, Candid's APIs can help. To learn more about how you can get started, continue reading and exploring our developer portal! If you have any feedback, please share with us here: Feedback ## How the API docs are organized ## Documentation section This includes specific details on our API platform, covering broad topics such as getting API access, authentication & account management, status and error codes, rate limits and thresholds, security, and more. ## Endpoint definitions section Individual API endpoint definitions are arranged by category. Each API definition contains detailed information on API requests, responses, statuses, and more. Nonprofit APIs Taxonomy API Funding APIs News & Research API If you are onboarding any of Candid's APIs, many of our APIs have a field that returns the GuideStar profile URL. You can use this to create a link for users to access and view the basic GuideStar profile. However, users will encounter a registration or sign in page if they click the URL from your website, preventing them from viewing the GuideStar Profile without logging in. To remove this registration, API support can whitelist your website that allows this login to be bypassed, so your users have a seamless experience clicking from your site into the GuideStar profile. If you need your website whitelisted, please send the following information to API support: * The production website URL that will refer to the GuideStar Profile * All other website URLs that are used in your testing environments API support will whitelist your website and will let you know when you can test to ensure it was appropriately set up. User guides for grantmaking solutions Adopt Candid Seals of Transparency as an eligibility requirement Prepopulate your grant application Demographic data for grantmaking Validate organizations using charity check Updated 4 months ago Did this page help you?YesNo A Candid profile is a simple way to showcase an organization’s work. Organizations can earn Candid Seals of Transparency and tell their full story on their profile by adding specific information about their programs such as measures of progress, operations–including diversity, equity and inclusion (DEI) information—and financials. Organizations can provide varying levels of details about themselves, corresponding to four different seal levels: Bronze, Silver, Gold, and Platinum. Seals are accompanied by a year denoting when they were obtained. Organizations are required to update their information on a roughly yearly basis to keep their seals from expiring. The Candid profile can be a powerful way to increase an organization’s fundraising success and visibility. Information provided via Candid profiles is sent to all major U.S.-based donor-advised funds and 200+ charitable sites, including AmazonSmile and Facebook. It can also simplify the grant application process, reducing the burden faced by organizations applying for funding and providing you with a streamlined way of obtaining the information you need to make funding decisions (see Prepopulate your grant application for more information). By recommending or requiring a Seal of Transparency in your grant guidelines, you are also helping increase and enrich sector-wide information about nonprofits–who they are, what they do, and why it matters. ## For Funders Funders who would like to incorporate a Candid Seal of Transparency requirement in their grant management workflows can use Candid's Premier API. The Premier API provides you a real-time view of a Candid profile, which allows you to access all the data an organization has provided directly to Candid, including Seal level. In order to build the eligibility requirements and verify that an applicant or grantee has a Seal of Transparency, we recommend integrating a process or workflow where you can: * Ask the organization for their EIN, or use the EIN already associated with their record in your system * Upon a submit or a refresh button on the record, call the Premier API to get their Candid Profile Level * Save their Candid profile level by using the field returned in the Premier API and record the timestamp * Verify the response to see if they meet eligibility or not The will return one of the below statuses describing the organization's profile level: * a status indicating if their Seal of Transparency level is active by returning the level (bronze, silver, gold, platinum) and the year obtained (2020, 2021, etc.) * a status indicating if their seal of transparency has expired * a status indicating if their profile is basic (which means an organization claimed their profile, but did not provide enough information to earn a seal) * a status indicating if their profile is unclaimed ``` "gs_profile_update_level": "Platinum 2021" ``` ``` "gs_profile_update_level": "Expired" ``` ``` "gs_profile_update_level": "Basic" ``` ``` "gs_profile_update_level": "None" ``` If the organization does not meet your eligibility requirements, we recommend you share the following with the applicant or grantee: We require funding applicants to claim their Candid profile by submitting the necessary information to achieve a {your eligibility requirement here} Seal of Transparency. It’s free and you can start here. If an organization successfully claims and updates their profile, the Premier API will reflect the new profile level status the next day. In addition to the profile level, you can incorporate all the data submitted through our profile update program into your applications. Please check out the Premier API for a full view of the data you can incorporate from the Candid profile. ## For Grant Management Systems To incorporate the Seal of Transparency as an eligibility requirement for the funders you serve, you can use the field from the Premier API to pull in the profile level verification in eligibility questionnaires and grant applications. In addition to the recommendations above, we recommend the following features when funders build eligibility questionnaires and grant applications that require a Candid Seal of Transparency: * Allow the funder to select which profile level meets their eligibility requirements * Share the status of the organization's profile level to the individual completing the questionnaire or application * Guide organizations to their Candid profile if they do not pass the eligibility requirement * Share with the funder if the organization meets their eligibility requirement in the grant application * Update the grant record reflecting the organization's profile level with a date and timestamp ## Candid 2022 Profile Standard PDF Fields we collect through our profile that are available in Candid's Premier API As a field, we are amid a timely and important conversation about reducing grantee burden in the grant application process. Calls for common applications and efforts like #FixTheForm show that foundations often ask similar questions when they assess potential grantees. Candid’s GuideStar profile aligns with these information needs, and our API provides a solution to automatically prepopulate grant applications. Candid provides information and data that is commonly used to understand a nonprofit holistically, from financials to program areas to results. Our database includes data on more than 1.8 million active nonprofits, and our APIs support the transfer of this data into other systems in real-time. This data can be used to prepopulate grant applications so that you can: * Ask fewer questions on your grant application and reports * Align your questions to be consistent with funding peers * Adopt best practices in normalizing data on organizations By using Candid's APIs in the grant application process, you're not only getting better information for your own organization, you are also reducing the burden on nonprofits, who won't need to submit the same information for each grant they apply for. The more funders make use of this existing information, the larger the benefits to nonprofits, enabling networks of scale. ## Solutions for funders and grant management software Applicant experience * Allow the applicant to enter their EIN, or use the EIN associated with their login (if applicable) * Display the grant application plugin button that triggers a call to our Premier API v3. Automatically prepopulate the form with the appropriate fields. * Allow the applicant to review and update the information, if needed. Funder experience * Allow the funder to design the grant application and select the desired fields. * Use the table below to determine which fields to make available to allow funders the option to simplify the grant application experience. ## Fields commonly used in grant applications Below, you’ll find the organizational data you can use in your grant applications. This data is available in Premier API. ## Organization and contact information These fields are used to retrieve basic information about the nonprofit and who to contact for fundraising. Premier API Field | Example | Description | | --- | --- | --- | | 13-1837418 | Employee identification number | | Candid | Organization name | | Platinum 2021 | GuideStar Seal of Transparency level | | 32 Old Slip | Organization address street name | | 24th Floor | Organization address suite or apartment number | | New York | Organization address city | | NY | Organization address state | | 10005 | Organization address zip code | | New York | Organization address county | | Candid | Legal organization name | | candid.org | Organization website URL | | 1956 | Year that an organization was founded | | <NAME> | Name of primary fundraising contact | | Senior Director of Development | Title of primary fundraising contact | | <EMAIL> | Email address of primary fundraising contact | | 212 620-4230 | Phone number of primary fundraising contact | ## Mission, subject areas and populations served These fields generally describe what the organization supports, listed using Candid's Taxonomy, NTEE, and SDG codes. Premier API Field | Example | Description | | --- | --- | --- | | Candid gets you the information you need to do good. | Organization mission statement | b'Premier API Field\n Example\n Description\n \n \n \n mission\n \n Candid gets you the information you need to do good.\n Organization mission statement\n \n \n pcs_codes > pcs_facet\n Population with Gender/Age\n PCS facet name\n \n \n pcs_codes > pcs_description\n Adults\n PCS code description\n \n \n \n ntee_code\n \n T50 - Philanthropy, Voluntarism, and Grantmaking\n National Taxonomy of Exempt Entities (NTEE) Code\n \n \n sdg > id\n 17\n UN sustainable development goal number\n \n \n sdg > description\n Partnerships for the Goals\n UN sustainable development goal description' ## Programs and impact measurements These fields are used to understand an organization's programs and the impact an organization has on its population served. These fields are available in an array when multiple programs and impact measurements are reported by the nonprofit to Candid. Premier API Field | Example | Description | | --- | --- | --- | b'Premier API Field\n Example\n Description\n \n \n Program > name\n Knowledge Tools\n Program name\n \n \n Program > description\n Through data, research, and our collective experience, Candid provides our users with the knowledge they need to make strategic decisions and develop practical solutions to achieve their missions...\n Program description\n \n \n Program > target_population\n General/Unspecified\n First target population that the program is targeting\n \n \n Program > target_population2\n Second target population that the program is targeting\n \n \n Program > budget\n 3002061\n Program budget in dollars\n \n \n Program > areas_served\n United States\n Name of the geographic area served by the program\n \n \n PlatinumMetrics > metric\n Number of organizations you can find on GuideStar\n Metric name\n \n \n PlatinumMetrics > years\n 2018, 66602.0; 2017, 48075\n The years this metric was captured and the values for a given year\n \n \n PlatinumMetrics > type_of_metric\n Output - describing our activities and reach\n How this metric is being measured\n \n \n PlatinumMetrics > direction_of_success\n Increasing\n How to determine if this metric is showing a successful trend' ## Subsection and tax-exempt status These fields can be used to understand tax-exempt status. Premier API Field | Example | Description | | --- | --- | --- | | 03 | Subsection Codes are the codes shown under section 501(c) of the Internal Revenue Code of 1986, which define the category under which an organization may be exempt | | 501(c)(3) Public Charity | Description of organization subsection code | | 3 | Single digit code designating the type of organization. If there is no group exemption, will be one of (Central, Intermediate, or Independent); if there is a group exemption, will be one of (Central, Intermediate, Independent, or Subordinate).This code is used if the organization is an independent organization or an independent auxiliary (i.e. not affiliated with a National, Regional, or Geographic grouping of organizations) | | This code is used if the organization is an independent organization or an independent auxiliary (i.e., not affiliated with a a National, Regional, or Geographic grouping of organizations). | Description of what the affiliation code means | | 1 | Signifies whether contributions made to an organization are deductible | | Contributions are deductible, as provided by law | Deductibility code description | b'Premier API Field\n Example\n Description\n \n \n \n subsection_code\n \n 03\n Subsection Codes are the codes shown under section 501(c) of the Internal Revenue Code of 1986, which define the category under which an organization may be exempt\n \n \n \n subsection_description\n \n 501(c)(3) Public Charity\n Description of organization subsection code\n \n \n \n affiliation_code\n \n 3\n Single digit code designating the type of organization. If there is no group exemption, will be one of (Central, Intermediate, or Independent); if there is a group exemption, will be one of (Central, Intermediate, Independent, or Subordinate).This code is used if the organization is an independent organization or an independent auxiliary (i.e. not affiliated with a National, Regional, or Geographic grouping of organizations)\n \n \n \n affiliation_description\n \n This code is used if the organization is an independent organization or an independent auxiliary (i.e., not affiliated with a a National, Regional, or Geographic grouping of organizations).\n Description of what the affiliation code means\n \n \n \n deductibility_code\n \n 1\n Signifies whether contributions made to an organization are deductible\n \n \n \n deductibility_description\n \n Contributions are deductible, as provided by law\n Deductibility code description\n \n \n parent_organizations > EIN\n 53-0196617\n Array of EINs of parent organizations\n \n \n parent_organizations > organization_name\n UNITED STATES CONFERENCE OF CATHOLIC BISHOPS\n Array of names of parent organizations\n \n \n parent_organizations > group_exemption\n 0928\n Four-digit internal number assigned to parent organizations holding group exemption letters.\n \n \n \n letter_of_determination_doc_name\n \n Candid IRS Letter of Determination\n Document name of the letter of determination\n \n \n \n letter_of_determination_url\n \n https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185350&approved=True\n URL to the letter of determination' ## Financials These fields are used to understand the general financial health of an organization. There are many more financial fields present in the Premier API including Part VIII, IX, X of the Form 990 and a financial trends analysis. There is also a PDF view of the financial trends available at Premier Financial Trends Analysis PDF API. Premier API Field | Example | Description | | --- | --- | --- | | 2019 | The most recent fiscal year of all financials on file | | F990 | The IRS 990 form type used in this financial data | | IRS Form 990 | Source of current financial information | | 45546348 | Total monetary amount of assets, in USD | | 29706800 | Total revenue, in USD | | 25781921 | Total expenses, in USD | b'Premier API Field\n Example\n Description\n \n \n \n fiscal_year\n \n 2019\n The most recent fiscal year of all financials on file\n \n \n \n form_type\n \n F990\n The IRS 990 form type used in this financial data\n \n \n \n data_source\n \n IRS Form 990\n Source of current financial information\n \n \n \n assets_total\n \n 45546348\n Total monetary amount of assets, in USD\n \n \n \n total_revenue\n \n 29706800\n Total revenue, in USD\n \n \n \n expenses_total\n \n 25781921\n Total expenses, in USD\n \n \n financial_statements > fiscal_year_end\n 2019\n The fiscal year end of the financial statement\n \n \n financial_statements > document_url\n https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185348&approved=True\n The URL of the financial statement' ## Board of directors These fields can be used to pull in the board of directors. Premier API Field | Example | Description | | --- | --- | --- | | <NAME> | | Walmart | b"Premier API Field\n Example\n Description\n \n \n \n board_chair_name\n \n <NAME>\n \n \n \n board_chair_affiliation\n \n Walmart\n \n \n board_of_directors > name\n <NAME>\n Array of board of directors' names\n \n \n board_of_directors > title\n Array of board of directors' titles\n \n \n board_of_directors > Company\n HIP-Hispanics in Philanthropy\n Array of board of directors' companies" ## Demographics and equity strategies We include the answers to the following demographic questions for each participating organization: We include the answers for these staff and volunteer groups working at the organization: * CEO/Leader * Co-CEO/ Co-Leader * Board Members * Senior Staff * Staff Organization equity strategies are available within the demographics section of Premier API and provide an understanding of the equity strategies in place at an organization. See the Demographic data for grantmaking user guide for more information. In the past few years, there has been a heightened interest in nonprofit demographic data – to gain visibility on matters of equity, uplift the work of BIPOC-led organizations, and increase investment in groups that reflect the communities they serve. The result? Nonprofits are asked to collect, organize, and provide demographic data over and over again in different formats, creating a time-consuming burden. Demographics via Candid is part of our shared commitment to relieve this burden by having nonprofits share their demographic data one time (Data1x), in a standard format, where it can be freely accessed and referenced by other potential funders. As more funders accept demographic data from Candid, nonprofits will save time on “paperwork” and focus more fully on what’s important: their missions. This creates efficiencies, helping your members do better by their grantees and giving funders access to in-depth information that they can incorporate into their evaluation and grants process. Integrate Candid’s Demographics API into your grantmaking process to access the most recent organizational demographics data on your grantees. If you already use Candid’s Premier API in your grantmaking process, you can utilize the demographics data found there. This guide offers direction on how to leverage demographic data to further your equitable funding journey. Power your grantmaking processes with the comprehensive demographic data returned in the Demographics API. * Reduce burden on grantees by automatically appending demographic data to grant applications. * Make informed grant decisions based on data directly in your grants management system (GMS). * Create data-driven reports on the composition of your grantmaking portfolio. * Keep your records up to date with the latest information refreshed on demand or automatically on a cadence that works best for your organization. Learn more about the demographic data Candid collects in our Organizational demographic data user guide. ## Using demographic data ### Sample grant application workflow * Nonprofit completes grant application and provides employer identification number (EIN). * Funder calls Candid’s Demographics API to populate nonprofit organizational demographic data. * Funder checks `demographics_status` field to see whether the organization has provided demographics data. See more information about demographics status messages here. * If no demographic data is found, funder directs nonprofit to claim their Candid profile and provide demographic data. * When nonprofit provides or updates demographic data, funder calls Candid’s Demographics API again to retrieve data updated in real-time. * Funder checks * Demographic data can then be stored and visualized. ### Sample organization-level data visualization Candid profiles provide an example of how demographic data can be displayed for one organization. Data for the leader is broken out and aggregated data is available for each category and staff level. Overall staffing totals are listed in parentheses behind the staffing category, and on hover, users can see the specific proportion that a particular demographic category represents. ### Sample aggregated data visualization The Demographics via Candid dashboard is a publicly available data visualization built in Tableau that allows users to see demographic data aggregated across nonprofits. Below is an example of how Race & Ethnicity data is displayed in aggregate for a cohort of organizations on this dashboard ## Calculating percentage totals If you are interested in representing demographics as the percentage of each group who identified with a particular subcategory, you can use the below fields, available in the `staff_level_totals` object, as denominators for percentages: * total_board_members: number of individuals on the board * total_staff: number of individuals who work at the organization, including senior staff, leader, and co-leader * total_senior_staff: number of senior staff (C-suite or management with budgetary oversight) who work at the organization, including the leader and co-leader ## Resources for nonprofits * Additional guidance for nonprofits on the benefits of sharing demographic data and how to get started is available in the Candid Learning knowledge base. * Candid’s help guide on how to collect and share demographic data provides best practices and a sample survey for nonprofits. * Candid’s FAQs provide guidance on how a nonprofit can claim their Candid profile and complete the demographics section of the profile. For more information on organizational demographic data, review this user guide: The Charity Check API serves as a validation tool to understand the status and eligibility of a nonprofit organization. The API allows you to integrate this validation tool into your grantmaking workflow to: * Ensure charities are compliant within key databases including IRS Publication 78, IRS Business Master File, Internal Revenue Bulletin, Automatic Revocation of Exemption, and OFAC Specially Designated National list. * Gather additional details to support decision-making, such as organization type, deductibility limitations, religious organization status, revocations, and more. * Download a date and timestamped charity check PDF document to archive for due diligence via Charity Check PDF API. * Confirm organizations' nonprofit status with California state authorities, including the Attorney General’s Registry of Charitable Trusts and Franchise Tax Board. For more information, see these user guides: Date: 2022-10-03 Categories: Tags: ## Prerequisite: Set up Apple Pay Apple Pay is an easy, secure, and private way of accepting donations for your nonprofit organization. To set up Apple Pay for donations, please review the user guide linked at https://developer.apple.com/apple-pay/nonprofits/. ## Nonprofit eligibility to receive donations with Apple Pay Apple Pay requires that nonprofits pass an eligibility screening to ensure they stay in compliance with Apple Pay's eligibility criteria. At minimum, an eligible nonprofit needs to: * be a registered 501(c)3 organization * earn a Bronze Seal of Transparency from Candid, every year There are additional eligibility criteria proprietary to Apple Pay that may make an organization ineligible. Candid provides this screening on behalf of Apple Pay so that donation platforms only provide Apple Pay to eligible organizations. ## What is the Nonprofit Eligibility API? Candid provides an API that is updated in real-time, and returns an organization's eligibility status to receive donations through Apple Pay. You can find organizations by passing in the EIN in the query parameters, up to 25 at a time. ``` https://api.candid.org/eligible/v1/apple?ein=13-1837418 ``` When sent, the API returns the following fields that can be used to verify an organization's eligibility. ``` { "organization_name": "Candid", "ein": "13-1837418", "eligibility_status": true, "eligibility_status_message": "Your organization is eligible.", "eligibility_checked_date": "2022-10-03T14:56:50.3281388Z", "profile_level": "Platinum", "profile_year": "2022", "profile_link": "https://www.guidestar.org/profile/13-1837418", "seal_last_modified": "2022-01-18T13:44:48.0000000Z", "website_url": "candid.org", "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" } } ``` Review our Nonprofit Eligibility API specification to try it out. ## How to check an organization's eligibility to receive donations through Apple Pay Initial seedUpon implementation, you can use the Nonprofit Eligibility API to seed your database for an organization's eligibility to receive donations through Apple Pay. Configuring Apple Pay for donations When an organization wants to turn on donations through Apple Pay, look up the organization by `ein` and display their ``` eligibility_status_message ``` on the webpage, which states if the organization is eligible to receive donations. If the organization is ineligible, a reason for ineligibility is given, in addition to the next course of action. There are 6 messages a nonprofit can encounter. b'eligibility_status_message examples\n Description\n \n \n "Your organization is eligible."\n This message displays when a nonprofit is eligible for donations through Apple Pay.\n \n \n "Your organization is ineligible. Claim your Candid profile and earn your Bronze seal by visiting https://www.guidestar.org/UpdateNonprofitProfile to be eligible."\n This message displays when a nonprofit is not eligible because they are not a Bronze seal holder.\n \n \n "Your organization is ineligible to receive donations through Apple Pay. However, you can still boost your fundraising efforts. Claim and update your nonprofit profile https://www.guidestar.org/UpdateNonprofitProfile. Candid&#8217;s profiles powers 200+ charitable sites such as AmazonSmile."\n This message displays when a nonprofit is not eligible because they are not a 501(c)3 organization.\n \n \n &#8220;Your organization is ineligible. Please reach out to <EMAIL> for further clarification."\n This message displays when a nonprofit is ineligible due to other reasons.\n \n \n "Your organization is ineligible. Simply earn your Bronze seal to become eligible. Get started https://www.guidestar.org/UpdateNonprofitProfile."\n This message displays when an organization is not eligible because they have not provided enough information to earn a Seal of Transparency.\n \n \n "Your organization is ineligible because your Seal of Transparency is more than a year old. Log in to update your profile and earn the latest Seal https://www.guidestar.org/Account/Login."\n This message displays when a nonprofit is not eligible because their Seal of Transparency is more than a year old.' After a nonprofit claims their Candid profile and earns a Bronze Seal, the Nonprofit Eligibility API will immediately be updated and reflect their new eligibility status. Encountering a 404 If the organization is not found in the API (404), the organization is not eligible to accept donations with Apple. Whitelisting your website to bypass GuideStar registration If you are redirecting users to the 'profile_link' field, please ensure you have followed the steps in this user guide, Whitelisting your website to bypass GuideStar registration, to ensure your users do not encounter a sign in screen when viewing their profile Displaying the Apple Pay buttonIt is required for the platform to perform daily verification for each organization to keep the Apple Pay button visible on the organization's website and content. The check can be completed upon the first page view of the day and cached for the remainder of the day. * If the organization's `eligibility_status` returns as `true` , no further action is needed by the donation platform. * If the organization's `eligibility_status` returns as `false` , the Apple Pay button needs to be hidden from the webpage. It is suggested to follow up with the organization when this happens. * If the organization is not found in the API, they should not have an Apple Pay button configured. Organization's eligibility status changes for other reasons than specifiedIf the organization is a 501(c)3 and has Bronze Seal or higher within the last year, but is still ineligible, please reach out to mailto:<EMAIL> for further clarification. ## FAQ's - Frequently Asked Questions How do I access nonprofits who are eligible to receive donations through Apple Pay? Candid provides the Nonprofit Eligibility API that returns eligible and ineligible nonprofits for donations through Apple Pay. Please contact us for access. * What do donation platforms need to do to enable Apple Pay for donations? * A donation platform needs to set up Apple Pay by following the steps in this user guide: https://developer.apple.com/apple-pay/nonprofits/ * In addition, Apple Pay requires that nonprofits pass an eligibility screening to ensure they organization is in compliance with Apple Pay's eligibility criteria. Please follow the eligibility steps in this user guide: https://developer.candid.org/docs/apple-pay-for-donations * How frequently is the API updated with new nonprofits eligible for donations through Apple Pay? * The Nonprofit Eligibility API is updated in real-time, based on data updates, like a nonprofit earning their bronze seal. Updates made to a nonprofit profile will reflect in the API within a few seconds. * What does each status message mean in the API? * `eligibility_status` = `true` * The organization is eligible to receive donations via Apple Pay. * Note: `subsection_code` = ‘501(c)3 is also required. * `eligibility_status` = `false` * The organization is not eligible to receive donations via Apple Pay. * Donation button needs to be hidden from the webpage * Note: Since `subsection_code` = `501(c)3...` is also required, all other `subsection_code` statuses are ineligible and `eligibility_status` = false * Recommended actions when an organization is not eligible for Apple Pay * Display the `profile_link` field to redirect the nonprofit to Candid’s website to earn their Bronze Seal of Transparency if `seal_level` = 'unclaimed', 'expired', or 'basic' or issued over a year ago. Upon completion of the process the organization will update to `eligibility_status` = `true` * If the organization is a 501(c)3 and has Bronze Seal or higher within the last year, but is still ineligible, please reach out to mailto:<EMAIL> for further clarification. * If the organization is not a 501(c)3, let the nonprofit know they are ineligible because their subsection code does not meet Apple's criteria. * Display the * How frequently do I need to check for eligibility of organizations? Daily. It is required for the donation platform to perform daily checks for each organization to keep the Apple Pay button present on the organization's website and content. The check can be completed upon the first page view of the day where the Apple Pay button is displayed and cached until the next day. * Who do I reach out to if a nonprofit on my platform has a question about accepting donations with Apple Pay? * Please reach out to mailto:<EMAIL> with the organization name and EIN to obtain further clarification. Updated 9 months ago Contact us to get information on Candid's APIs ImagineCRM, a registered Salesforce Partner, built a custom integration on the Salesforce Lightning Platform to sync Candid's data to Salesforce using Candid's APIs. This interface to Candid's data is easily accessible to clients and compatible with Essentials API, Premier API, Charity Check API, and Charity Check PDF API. Clients are able to streamline workflows, auto-populate nonprofit applications, and update key indicators for current grantees. Through this tool, our clients access Candid's data that provides the information they need to make strategic decisions. ## Connector Demonstration ## Background While collaborating with Candid and executives from lmagineCRM, a registered Salesforce Partner, we recognized a market need for an integration with Candid's APIs that would automate the accessibility of a broad range of key performance data for nonprofit organizations during the lifecycle of a grant. Using Salesforce's Lightning Platform, ImagineCRM built the Connector to resolve pain points for foundation administrators, project managers, and API end-users at all levels. ## About ImagineCRM In Their Own WordsThe ImagineCRM team is built with diverse certified Salesforce professionals and business perspectives that allow us to collaborate well with our clients. As a Salesforce Registered Consulting Partner, our experience gives us an understanding of what organizations are seeking to improve because we've been in that role, which allows us to do a better job of creating your new path using Salesforce. Updated almost 2 years ago Visit ImagineCRM to inquire for more information Essentials API is Candid's nonprofit search engine, where you can find the most common set of data about nonprofits to quickly find organizations most relevant to your users, and use those results to get more data from our other APIs. The Essentials API returns search results in JSON format. * Search by organization name or EIN to help users find nonprofits. * Research nonprofits most relevant to your users based on keyword search terms, location, financials & more. * Surface organizations with recently updated data to keep your records up to date. * Identify organizations who have submitted demographic data to Candid. * Create advanced search capabilities for your users to search by cause area, within a location and radius, and between a range of revenue, assets and expenses. * Allow users to filter results based on Pub78 Verification, audits performed, and form types filed with the IRS. * Display results with nonprofit branding including mission, website, logo, and contact information to help users easily recognize their favorite nonprofits. The following endpoints are the most recent versions included with Essentials API: Organization Search Endpoints * Essentials API v3 (Most Recent Version) - Search Candid’s most common set of data about nonprofits to quickly find organizations most relevant to your users, and use those results to get more data from our other APIs. API returns search result in JSON format. Easily Build Your Essentials v3 Search Query Lookup Value Helper Endpoints * Essentials Lookup API - Provides a list of all the tables used as a filter_name with the Essentials Lookup endpoints. The tables and their contents can be used to generate dropdowns and filters in your system when using the Essentials API. * Essentials Lookup Filter Name API - Provides a list of all the human-readable search values within a specific filter_name table that can be used in search queries with the Essentials endpoints. Each array contains a table key, name value, and search value. The resulting search_value(s) can be passed as search values in the Essentials API. * Essentials Lookup Key Value API - Lookup details on a specific filter using the known `filter_name` and `key_or_value` . The resulting `search_value` can be passed as a search value in the Essentials API. ## Essentials endpoint-specific user guides * Essentials API search examples Make the most of Essentials API organization search with these examples that utilize the request body. Updated 11 months ago Take all the guess-work out of building your search query by using the built-in query generator on the Essentials v3 API docs page ``` { "code": 200, "message": "Request was processed successfully!", "took": 18, "time": "2023-08-29 18:31:18Z", "results_count": 1, "page_count": 1, "errors": [], "hits": [ { "organization": { "organization_id": "6908410", "ein": "13-2875808", "organization_name": "Human Rights Watch, Inc.", "also_known_as": "HRW", "group_exemption": "0000", "mission": "Human Rights Watch defends the rights of people worldwide. We scrupulously investigate abuses, expose the facts widely, and pressure those with power to respect rights and secure justice. Human Rights Watch is an independent, international organization that works as part of a vibrant movement to uphold human dignity and advance the cause of human rights for all.", "website_url": "www.hrw.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7933415&approved=True", "profile_level": "Platinum", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/13-2875808", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(212) 290-4700", "contact_title": "Executive Director", "number_of_employees": "378", "ruling_year": 1976 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "350 5th Ave Fl 34", "address_line_2": "", "city": "New York City", "state": "NY", "zip": "10118", "msa": "NY - New York, NY-NJ", "congressional_district": "District 12, NY", "county": "New York, NY", "latitude": 40.7484, "longitude": -73.9846 }, "taxonomies": { "subject_codes": [ { "subject_code": "SR000000", "subject_code_description": "Human rights" } ], "population_served_codes": [ { "population_served_code": "PG060000", "population_served_description": "Victims and oppressed people" }, { "population_served_code": "PG040000", "population_served_description": "Incarcerated people" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010100", "population_served_description": "Immigrants" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PC040000", "population_served_description": "Women and girls" }, { "population_served_code": "PC030000", "population_served_description": "Intersex people" }, { "population_served_code": "PC010000", "population_served_description": "LGBTQ people" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" }, { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "Q70", "ntee_code_description": "International Human Rights" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 93499541.0, "total_expenses": 92236869.0, "total_assets": 224270259.0 }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-07-07T16:47:53.0000000", "profile_last_modified": "2022-07-07T16:47:53.0000000", "dei_last_modified": "2022-07-07T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } } ] } ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 181, "time": "2023-08-29 18:31:44Z", "results_count": 7204, "page_count": 289, "errors": [], "hits": [ { "organization": { "organization_id": "8315557", "ein": "91-1224834", "organization_name": "University District Food Bank", "also_known_as": "University District Food Bank (UDFB)", "group_exemption": "0000", "mission": "Building a hunger-free Northeast Seattle by providing our neighbors with reliable access to healthy food and life-changing resources", "website_url": "http://www.udistrictfoodbank.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=4413589&approved=True", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/91-1224834", "profile_logo": "", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(206) 523-7060 x709", "contact_title": "Executive Director", "number_of_employees": "22", "ruling_year": 1984 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "5017 Roosevelt Way NE", "address_line_2": "", "city": "Seattle", "state": "WA", "zip": "98105", "msa": "WA - Seattle-Everett", "congressional_district": "District 7, WA", "county": "King, WA", "latitude": 47.6651, "longitude": -122.3174 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030100", "population_served_description": "Homeless people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 5398095.0, "total_expenses": 5164245.0, "total_assets": 6627239.0 }, "bmf_gross_receipts": 6556161.0, "bmf_assets": 6627239.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2020-09-18T19:00:03.0000000", "profile_last_modified": "2019-09-17T14:48:46.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-06-23T11:00:41.0000000" } }, { "organization": { "organization_id": "7366705", "ein": "33-0072922", "organization_name": "Feeding America Riverside | San Bernardino Counties", "also_known_as": "FARSB and Feeding America Riverside|San Bernardino", "group_exemption": "0000", "mission": "Our mission is to alleviate hunger in the Inland Empire.", "website_url": "www.feedingamericaie.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9253953&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/33-0072922", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(951) 359-4757 x109", "contact_title": "CEO", "number_of_employees": "44", "ruling_year": 1985 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2950 Jefferson St Ste A", "address_line_2": "", "city": "Riverside", "state": "CA", "zip": "92504", "msa": "CA - Riverside-<NAME>", "congressional_district": "District 41, CA", "county": "Riverside, CA", "latitude": 33.9249, "longitude": -117.4068 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE060000", "population_served_description": "Indigenous peoples" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 51690761.0, "total_expenses": 50907739.0, "total_assets": 12504802.0 }, "bmf_gross_receipts": 51690761.0, "bmf_assets": 12504802.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-07-12T18:24:58.0000000", "profile_last_modified": "2023-07-12T18:24:57.0000000", "dei_last_modified": "2023-07-03T08:51:58.0000000", "financials_last_modified": "2023-05-18T19:00:46.0000000", "last_modified": "2023-07-12T18:24:57.0000000" } }, { "organization": { "organization_id": "7068444", "ein": "22-2986809", "organization_name": "Good Shepherd Food Bank", "also_known_as": "Good Shepherd Food Bank of Maine", "group_exemption": "0000", "mission": "The mission of Good Shepherd Food Bank is to eliminate hunger in Maine by sourcing and distributing nutritious food to people in need, building strong community partnerships, and mobilizing the public in the fight to end hunger", "website_url": "http://www.gsfb.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9158944&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/22-2986809", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(207) 782-3554", "contact_title": "President", "number_of_employees": "120", "ruling_year": 1989 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 1807", "address_line_2": "", "city": "Auburn", "state": "ME", "zip": "04211", "msa": "ME - Lewiston-Auburn", "congressional_district": "District 2, ME", "county": "Androscoggin, ME", "latitude": 44.0926, "longitude": -70.2394 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" } ], "ntee_codes": [ { "ntee_code": "K30", "ntee_code_description": "Food Service, Free Food Distribution Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 81382745.0, "total_expenses": 76370570.0, "total_assets": 53999694.0 }, "bmf_gross_receipts": 115118481.0, "bmf_assets": 53999694.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-06-16T08:41:02.0000000", "profile_last_modified": "2023-06-16T09:46:35.0000000", "dei_last_modified": "2021-07-27T09:43:41.0000000", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-06-16T09:46:35.0000000" } }, { "organization": { "organization_id": "7883890", "ein": "58-1376648", "organization_name": "Atlanta Community Food Bank, Inc.", "also_known_as": "ACFB", "group_exemption": "0000", "mission": "The Atlanta Community Food Bank works to end hunger across metro Atlanta and north Georgia with the food, people, and big ideas needed to make sure all members of our community have access to enough nourishment to live a healthy and productive life.We all need nutritious food to live the lives we imagine. Yet far too many people in our own community experience hunger every day, including children, seniors, and working families.Through more than 600 nonprofit partners, we help more than 700,000 people get healthy food every year. Our goal is that, by 2025, all hungry people in our service area will have access to the nutritious meals they need when they need them. It takes the power of our whole community to make that possible. Join us at ACFB.org.", "website_url": "www.acfb.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9383117&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/58-1376648", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(678) 553-5960", "contact_title": "CDO", "number_of_employees": "201", "ruling_year": 1980 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3400 N Desert Dr", "address_line_2": "", "city": "Atlanta", "state": "GA", "zip": "30344", "msa": "GA - Atlanta", "congressional_district": "District 5, GA", "county": "Fulton, GA", "latitude": 33.6779, "longitude": -84.454 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 194337596.0, "total_expenses": 277955814.0, "total_assets": 52336237.0 }, "bmf_gross_receipts": 194388146.0, "bmf_assets": 52336237.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-02-23T15:46:04.0000000", "profile_last_modified": "2023-08-22T17:06:34.0000000", "dei_last_modified": "2023-02-23T00:00:00.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-08-22T17:06:34.0000000" } }, { "organization": { "organization_id": "9180485", "ein": "32-0362611", "organization_name": "Second Harvest Food Bank of Orange County, Inc.", "also_known_as": "", "group_exemption": "0000", "mission": "Our MissionIn collaboration with our partners, we provide dignified, equitable and consistent access to nutritious food, creating a foundation for community health.Our VisionAn Orange County with food and nutritional security for all.", "website_url": "FeedOC.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8663610&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/32-0362611", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "CEO", "number_of_employees": "100", "ruling_year": 2012 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "8014 Marine Way", "address_line_2": "", "city": "Irvine", "state": "CA", "zip": "92618", "msa": "CA - Orange County", "congressional_district": "District 45, CA", "county": "Orange, CA", "latitude": 33.6758, "longitude": -117.7406 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 91574545.0, "total_expenses": 89920549.0, "total_assets": 33252765.0 }, "bmf_gross_receipts": 91955323.0, "bmf_assets": 33252765.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-02-08T12:16:46.0000000", "profile_last_modified": "2023-02-08T12:19:28.0000000", "dei_last_modified": "2023-01-13T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7274634", "ein": "25-1420599", "organization_name": "Greater Pittsburgh Community Food Bank", "also_known_as": "", "group_exemption": "0000", "mission": "Mission: To leverage the power of community to achieve lasting solutions to hunger and its root causes. Vision: Communities where everyone has access to the food and resources they need to thrive.We are a proud partner of Feeding America.", "website_url": "www.pittsburghfoodbank.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8817175&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/25-1420599", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(412) 460-3663 x290", "contact_title": "", "number_of_employees": "229", "ruling_year": 1982 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1 N Linden St", "address_line_2": "", "city": "Duquesne", "state": "PA", "zip": "15110", "msa": "PA - Pittsburgh", "congressional_district": "District 18, PA", "county": "Allegheny, PA", "latitude": 40.3696, "longitude": -79.8515 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P60", "ntee_code_description": "Emergency Assistance (Food, Clothing, Cash)" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 70996227.0, "total_expenses": 71767027.0, "total_assets": 56117517.0 }, "bmf_gross_receipts": 72389218.0, "bmf_assets": 56117517.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-03-14T13:21:54.0000000", "profile_last_modified": "2023-03-14T14:52:37.0000000", "dei_last_modified": "2023-03-14T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "6915492", "ein": "13-3179546", "organization_name": "Food Bank For New York City", "also_known_as": "", "group_exemption": "0000", "mission": "The mission of Food Bank For New York City is to end hunger by organizing food, information and support for community survival, and dignity. Food Bank For New York City has been working to end food poverty in our five boroughs for 35 years. As the city’s largest hunger-relief organization, we employ a multifaceted approach centered on helping low-income New Yorkers overcome their circumstances and achieve greater independence.", "website_url": "https://www.foodbanknyc.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9399284&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-3179546", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(212) 566-7855 x8370", "contact_title": "Director, Administration & Board Engagement", "number_of_employees": "265", "ruling_year": 1983 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "39 Broadway Fl 10", "address_line_2": "", "city": "New York City", "state": "NY", "zip": "10006", "msa": "NY - New York, NY-NJ", "congressional_district": "District 10, NY", "county": "New York, NY", "latitude": 40.7086, "longitude": -74.0135 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 187094963.0, "total_expenses": 188033917.0, "total_assets": 62094729.0 }, "bmf_gross_receipts": 223635795.0, "bmf_assets": 62094729.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-08-25T10:41:12.0000000", "profile_last_modified": "2023-08-25T10:41:12.0000000", "dei_last_modified": "2023-08-24T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-08-25T10:41:12.0000000" } }, { "organization": { "organization_id": "7753229", "ein": "52-1135690", "organization_name": "Maryland Food Bank, Inc.", "also_known_as": "MFB", "group_exemption": "0000", "mission": "Feeding people, strengthening communities, and ending hunger for more Marylanders.", "website_url": "https://www.mdfoodbank.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8744437&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/52-1135690", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(410) 737-8282 x220", "contact_title": "", "number_of_employees": "255", "ruling_year": 1979 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2200 Halethorpe Farms Rd", "address_line_2": "", "city": "Halethorpe", "state": "MD", "zip": "21227", "msa": "MD - Baltimore", "congressional_district": "District 3, MD", "county": "Baltimore, MD", "latitude": 39.2275, "longitude": -76.6854 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 77965271.0, "total_expenses": 83722626.0, "total_assets": 64631559.0 }, "bmf_gross_receipts": 78116082.0, "bmf_assets": 64631559.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-02-24T14:21:16.0000000", "profile_last_modified": "2023-02-24T14:28:58.0000000", "dei_last_modified": "2022-09-29T00:00:00.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-06-13T13:54:00.0000000" } }, { "organization": { "organization_id": "7610581", "ein": "41-2120170", "organization_name": "Midwest Food Bank NFP", "also_known_as": "Midwest Food Bank", "group_exemption": "0000", "mission": "As a faith-based organization, it is the mission of Midwest Food Bank to share the love of Christ by alleviating hunger and malnutrition locally and throughout the world and providing disaster relief; all without discrimination. Our vision is to provide industry-leading food relief to those in need while feeding them spiritually.", "website_url": "https://midwestfoodbank.org/home", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9055250&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/41-2120170", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "Mrs. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Chief Financial Officer", "number_of_employees": "69", "ruling_year": 2004 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2031 Warehouse Rd", "address_line_2": "", "city": "Normal", "state": "IL", "zip": "61761", "msa": "IL - Bloomington-Normal", "congressional_district": "District 18, IL", "county": "Mclean, IL", "latitude": 40.5463, "longitude": -88.9892 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SJ060000", "subject_code_description": "Disasters and emergency management" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" } ], "population_served_codes": [ { "population_served_code": "PG060300", "population_served_description": "Victims of conflict and war" }, { "population_served_code": "PG060200", "population_served_description": "Victims of disaster" }, { "population_served_code": "PG060000", "population_served_description": "Victims and oppressed people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE060300", "population_served_description": "American Indians" }, { "population_served_code": "PE060000", "population_served_description": "Indigenous peoples" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 434933396.0, "total_expenses": 431262937.0, "total_assets": 75721541.0 }, "bmf_gross_receipts": 435391600.0, "bmf_assets": 75721541.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-23T15:09:50.0000000", "profile_last_modified": "2023-05-25T14:26:48.0000000", "dei_last_modified": "2023-01-31T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7428800", "ein": "35-1483868", "organization_name": "Gleaners Food Bank of Indiana, Inc.", "also_known_as": "Gleaners", "group_exemption": "0000", "mission": "To be a leader in the fight against hunger.", "website_url": "http://www.gleaners.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9377472&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/35-1483868", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(317) 829-1765", "contact_title": "Chief Communications and Advocacy Officer", "number_of_employees": "125", "ruling_year": 1980 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3737 Waldemere Ave", "address_line_2": "", "city": "Indianapolis", "state": "IN", "zip": "46241", "msa": "IN - Indianapolis", "congressional_district": "District 7, IN", "county": "Marion, IN", "latitude": 39.7082, "longitude": -86.2618 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 186505461.0, "total_expenses": 177254309.0, "total_assets": 57600145.0 }, "bmf_gross_receipts": 195566385.0, "bmf_assets": 57600145.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-07-06T11:01:35.0000000", "profile_last_modified": "2023-08-22T12:13:23.0000000", "dei_last_modified": "2023-07-06T10:24:46.0000000", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-08-22T12:13:23.0000000" } }, { "organization": { "organization_id": "8075102", "ein": "72-0956468", "organization_name": "Second Harvest Food Bank of Greater New Orleans and Acadiana", "also_known_as": "Second Harvest Food Bank", "group_exemption": "0000", "mission": "Second Harvest Food Bank leads the fight against hunger and builds food security in South Louisiana by providing food access, advocacy, education, and disaster response. One in seven people in South Louisiana is at risk of hunger. Second Harvest provides 40 million meals annually to 300,000 people in need across 23 parishes. Every $1 donation provides 3 meals to a hungry family. When you donate to Second Harvest, you help create a brighter future for our entire community.", "website_url": "www.no-hunger.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9395975&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/72-0956468", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(504) 729-2830", "contact_title": "Director of Marketing and Communications", "number_of_employees": "153", "ruling_year": 1984 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "700 Edwards Ave", "address_line_2": "", "city": "New Orleans", "state": "LA", "zip": "70123", "msa": "LA - New Orleans", "congressional_district": "District 1, LA", "county": "Jefferson, LA", "latitude": 29.9524, "longitude": -90.2081 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 115175910.0, "total_expenses": 98681339.0, "total_assets": 91041656.0 }, "bmf_gross_receipts": 119838980.0, "bmf_assets": 91041656.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-07-13T15:55:44.0000000", "profile_last_modified": "2023-08-24T15:23:15.0000000", "dei_last_modified": "2022-03-10T11:06:42.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-08-24T15:23:15.0000000" } }, { "organization": { "organization_id": "7723331", "ein": "51-0192519", "organization_name": "Community Food Bank Inc., dba Community Food Bank of Southern Arizona", "also_known_as": "Community Food Bank of Southern Arizona", "group_exemption": "0000", "mission": "We change lives in the communities we serve by feeding the hungry today and building a healthy, hunger-free tomorrow.The Community Food Bank of Southern Arizona serves residents in the following counties:Pima, Cochise, Santa Cruz, Graham, Greenlee.", "website_url": "www.communityfoodbank.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8868843&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/51-0192519", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(520) 882-3308", "contact_title": "Chief Executive Officer", "number_of_employees": "190", "ruling_year": 1976 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3003 S Country Club Rd", "address_line_2": "", "city": "Tucson", "state": "AZ", "zip": "85713", "msa": "AZ - Tucson", "congressional_district": "", "county": "Pima, AZ", "latitude": 32.1892, "longitude": -110.9265 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SM020000", "subject_code_description": "Food security" }, { "subject_code": "SM010000", "subject_code_description": "Agriculture" }, { "subject_code": "SM000000", "subject_code_description": "Agriculture, fishing and forestry" }, { "subject_code": "SK000000", "subject_code_description": "Public affairs" } ], "population_served_codes": [ { "population_served_code": "PJ080000", "population_served_description": "Farmers" }, { "population_served_code": "PJ020000", "population_served_description": "Unemployed people" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 127317393.0, "total_expenses": 124467078.0, "total_assets": 56197038.0 }, "bmf_gross_receipts": 141008806.0, "bmf_assets": 56197038.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-03-28T14:39:18.0000000", "profile_last_modified": "2023-03-28T14:57:19.0000000", "dei_last_modified": "2023-03-28T00:00:00.0000000", "financials_last_modified": "2023-05-18T18:49:03.0000000", "last_modified": "2023-05-18T18:49:03.0000000" } }, { "organization": { "organization_id": "7753667", "ein": "52-1202644", "organization_name": "Blue Ridge Area Food Bank, Inc.", "also_known_as": "", "group_exemption": "0000", "mission": "Our MISSION is to provide nourishing food to our neighbors in need through vibrant community partnerships and passionate public support.", "website_url": "http://www.brafb.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8541306&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/52-1202644", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(540)", "contact_title": "(540) 248-3663", "number_of_employees": "76", "ruling_year": 1981 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 937", "address_line_2": "96 Laurel Hill Road,", "city": "Verona", "state": "VA", "zip": "24482", "msa": "", "congressional_district": "District 6, VA", "county": "Augusta, VA", "latitude": 38.2036, "longitude": -79.0037 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PJ020000", "population_served_description": "Unemployed people" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K30", "ntee_code_description": "Food Service, Free Food Distribution Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 59706112.0, "total_expenses": 58772589.0, "total_assets": 30715187.0 }, "bmf_gross_receipts": 67315638.0, "bmf_assets": 30715187.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-01-20T09:38:14.0000000", "profile_last_modified": "2023-01-20T09:38:14.0000000", "dei_last_modified": "2021-03-24T14:22:36.0000000", "financials_last_modified": "2023-05-18T18:49:03.0000000", "last_modified": "2023-06-13T13:54:00.0000000" } }, { "organization": { "organization_id": "8233955", "ein": "77-0320851", "organization_name": "Central California Food Bank", "also_known_as": "Central California Food Bank", "group_exemption": "0000", "mission": "Central California Food Bank (formerly Community Food Bank) is the region’s largest nonprofit organization focused solely on ending hunger. Our mission is to fight hunger by gathering and distributing food, engaging in partnerships that advance self-sufficiency, and providing community leadership on issues related to hunger. Through these efforts, we envision a hunger-free Central California.Through our comprehensive hunger-relief programs and services, Central California Food Bank provides food to more than 280,000 people each month, including nearly 100,000 children throughout Fresno, Madera, Tulare, Kings, and Kern Counties.", "website_url": "www.ccfoodbank.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8915654&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/77-0320851", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "co-CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(559) 237-3663 x1131", "contact_title": "Grant Writer", "number_of_employees": "57", "ruling_year": 1997 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "4010 E Amendola Dr", "address_line_2": "", "city": "Fresno", "state": "CA", "zip": "93725", "msa": "CA - Fresno", "congressional_district": "District 16, CA", "county": "Fresno, CA", "latitude": 36.6915, "longitude": -119.7424 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SE130602", "subject_code_description": "Nutrition" }, { "subject_code": "SE130600", "subject_code_description": "Physical fitness" }, { "subject_code": "SE130000", "subject_code_description": "Public health" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 95910819.0, "total_expenses": 93176666.0, "total_assets": 46778902.0 }, "bmf_gross_receipts": 101987814.0, "bmf_assets": 46778902.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-04-11T18:03:08.0000000", "profile_last_modified": "2023-04-11T18:03:08.0000000", "dei_last_modified": "2021-06-10T15:31:30.0000000", "financials_last_modified": "2023-08-24T13:00:37.0000000", "last_modified": "2023-08-24T13:00:37.0000000" } }, { "organization": { "organization_id": "8399461", "ein": "94-2418054", "organization_name": "FOOD BANK CONTRA COSTA AND SOLANO", "also_known_as": "FBCCS", "group_exemption": "0000", "mission": "Leading the fight to end hunger, in partnership with our community and in service of our neighbors in need.", "website_url": "http://www.foodbankccs.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8918025&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/94-2418054", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(925)", "contact_title": "President and CEO", "number_of_employees": "140", "ruling_year": 1977 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "4010 Nelson Ave", "address_line_2": "", "city": "Concord", "state": "CA", "zip": "94520", "msa": "CA - Oakland", "congressional_district": "District 11, CA", "county": "Contra Costa, CA", "latitude": 38.0062, "longitude": -122.0478 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010100", "population_served_description": "Infants and toddlers" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K30", "ntee_code_description": "Food Service, Free Food Distribution Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 115008160.0, "total_expenses": 114568791.0, "total_assets": 40927503.0 }, "bmf_gross_receipts": 115035747.0, "bmf_assets": 40927503.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-04-12T13:23:28.0000000", "profile_last_modified": "2023-04-12T13:23:28.0000000", "dei_last_modified": "2022-03-10T16:09:21.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-05-18T17:01:04.0000000" } }, { "organization": { "organization_id": "6868205", "ein": "06-1063025", "organization_name": "Connecticut Foodshare", "also_known_as": ".", "group_exemption": "0000", "mission": "Connecticut Foodshare's mission is to deliver a more informed and equitable response to hunger by mobilizing community partners, volunteers, and supporters throughout Connecticut.", "website_url": "http://www.ctfoodshare.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9158934&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/06-1063025", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(860) 856-4334", "contact_title": "Institutional Giving Manager", "number_of_employees": "129", "ruling_year": 1982 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2 Research Pkwy", "address_line_2": "", "city": "Wallingford", "state": "CT", "zip": "06492", "msa": "CT - New Haven-Meriden", "congressional_district": "District 3, CT", "county": "New Haven, CT", "latitude": 41.4589, "longitude": -72.8195 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PJ020000", "population_served_description": "Unemployed people" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 98816890.0, "total_expenses": 98283077.0, "total_assets": 64587641.0 }, "bmf_gross_receipts": 98877956.0, "bmf_assets": 64587641.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-03-09T13:49:41.0000000", "profile_last_modified": "2023-06-16T09:44:03.0000000", "dei_last_modified": "2022-11-29T00:00:00.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-06-16T09:44:03.0000000" } }, { "organization": { "organization_id": "7883990", "ein": "58-1457912", "organization_name": "Second Harvest Food Bank of Northwest North Carolina, Inc.", "also_known_as": "", "group_exemption": "0000", "mission": "With our community and partners, we will increase food security and create pathways that build a stronger Northwest North Carolina.", "website_url": "www.secondharvestnwnc.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9061834&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/58-1457912", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Dorector", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(336) 784-5770 x237", "contact_title": "Senior Manager, Development Operations", "number_of_employees": "157", "ruling_year": 1982 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3330 Shorefair Dr", "address_line_2": "", "city": "<NAME>", "state": "NC", "zip": "27105", "msa": "NC - Greensboro-Winston-Salem-High Point", "congressional_district": "District 5, NC", "county": "Forsyth, NC", "latitude": 36.1485, "longitude": -80.237 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 84978237.0, "total_expenses": 72953989.0, "total_assets": 40643437.0 }, "bmf_gross_receipts": 86652056.0, "bmf_assets": 40643437.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-28T14:52:09.0000000", "profile_last_modified": "2023-05-28T14:52:09.0000000", "dei_last_modified": "2021-07-07T18:28:29.0000000", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-05-28T14:52:09.0000000" } }, { "organization": { "organization_id": "7463303", "ein": "36-2971864", "organization_name": "Greater Chicago Food Depository", "also_known_as": "Food Depository", "group_exemption": "0000", "mission": "The Greater Chicago Food Depository, Chicago’s food bank, believes a healthy community starts with food. We are at the center of a network of more than 800 partner organizations and programs – food pantries, soup kitchens, shelters, mobile distributions and other partners – working to bring food, dignity and hope to our neighbors across Chicago and Cook County. The Food Depository addresses the root causes of hunger with job training, advocacy and other innovative solutions. We are a proud member of Feeding America – the national network of food banks. By working to help those most in need go from hungry to hopeful, we truly become a Greater Chicago.", "website_url": "http://www.chicagosfoodbank.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9034293&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/36-2971864", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(773) 247-3663", "contact_title": "", "number_of_employees": "359", "ruling_year": 1978 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "4100 W Ann Lurie Pl", "address_line_2": "", "city": "Chicago", "state": "IL", "zip": "60632", "msa": "IL - Chicago", "congressional_district": "District 4, IL", "county": "Cook, IL", "latitude": 41.808, "longitude": -87.7079 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030400", "population_served_description": "Working poor" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 180413430.0, "total_expenses": 181434874.0, "total_assets": 197112141.0 }, "bmf_gross_receipts": 219531696.0, "bmf_assets": 197112141.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-18T16:28:29.0000000", "profile_last_modified": "2023-05-18T16:28:29.0000000", "dei_last_modified": "2022-09-28T00:00:00.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-06-13T13:54:00.0000000" } }, { "organization": { "organization_id": "7470043", "ein": "36-3203648", "organization_name": "Northern Illinois Food Bank", "also_known_as": "", "group_exemption": "0000", "mission": "Northern Illinois Food Bank's mission is to provide nutritious food and resources for our neighbors, with dignity, equity and convenience, through partnerships and innovation.", "website_url": "www.solvehungertoday.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7650091&approved=True", "profile_level": "Platinum", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/36-3203648", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2022-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(630) 443-6910 x124", "contact_title": "Director of Corporate and Foundation Giving", "number_of_employees": "226", "ruling_year": 1982 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "273 Dearborn Ct", "address_line_2": "", "city": "Geneva", "state": "IL", "zip": "60134", "msa": "IL - Chicago", "congressional_district": "District 14, IL", "county": "Kane, IL", "latitude": 41.8805, "longitude": -88.3335 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SM020000", "subject_code_description": "Food security" }, { "subject_code": "SM000000", "subject_code_description": "Agriculture, fishing and forestry" } ], "population_served_codes": [ { "population_served_code": "PH020000", "population_served_description": "People with diseases and illnesses" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K30", "ntee_code_description": "Food Service, Free Food Distribution Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 150994521.0, "total_expenses": 146601264.0, "total_assets": 70648201.0 }, "bmf_gross_receipts": 177381847.0, "bmf_assets": 70648201.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2022-03-16T12:59:06.0000000", "profile_last_modified": "2022-03-16T12:59:06.0000000", "dei_last_modified": "2022-02-16T09:38:27.0000000", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-05-18T15:24:48.0000000" } }, { "organization": { "organization_id": "7525985", "ein": "38-2515765", "organization_name": "FOODBANK COUNCIL OF MICHIGAN INC", "also_known_as": "FBCM", "group_exemption": "0000", "mission": "The Food Bank Council of Michigan's mission is to create a food secure state through advocacy, resource management, and collaboration among stakeholders and Michigan's unified food bank network.", "website_url": "www.fbcmich.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8561226&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/38-2515765", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "Dr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(517) 664-9903", "contact_title": "Executive Director", "number_of_employees": "11", "ruling_year": 1984 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "330 Marshall St Ste 102", "address_line_2": "", "city": "Lansing", "state": "MI", "zip": "48912", "msa": "MI - Lansing-East Lansing", "congressional_district": "District 8, MI", "county": "Ingham, MI", "latitude": 42.737, "longitude": -84.526 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SM010000", "subject_code_description": "Agriculture" }, { "subject_code": "SM000000", "subject_code_description": "Agriculture, fishing and forestry" }, { "subject_code": "SK000000", "subject_code_description": "Public affairs" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 165817709.0, "total_expenses": 165749389.0, "total_assets": 6936316.0 }, "bmf_gross_receipts": 165817709.0, "bmf_assets": 6936316.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-01-22T23:02:46.0000000", "profile_last_modified": "2023-01-22T23:36:11.0000000", "dei_last_modified": "2023-01-22T00:00:00.0000000", "financials_last_modified": "2023-04-01T07:08:43.0000000", "last_modified": "2023-04-01T07:08:43.0000000" } }, { "organization": { "organization_id": "8040780", "ein": "65-0342192", "organization_name": "Farm Share, Inc.", "also_known_as": "Farm Share", "group_exemption": "0000", "mission": "No Person Goes Hungry & No Food Goes to Waste!", "website_url": "https://www.farmshare.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9146182&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/65-0342192", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(786) 604-6540", "contact_title": "", "number_of_employees": "100", "ruling_year": 1993 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "14125 SW 320th St", "address_line_2": "", "city": "Homestead", "state": "FL", "zip": "33033", "msa": "FL - Miami", "congressional_district": "District 26, FL", "county": "Miami-dade, FL", "latitude": 25.4702, "longitude": -80.4204 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030500", "subject_code_description": "Free goods distribution" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SM020000", "subject_code_description": "Food security" }, { "subject_code": "SM000000", "subject_code_description": "Agriculture, fishing and forestry" }, { "subject_code": "SJ060000", "subject_code_description": "Disasters and emergency management" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" } ], "population_served_codes": [ { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG060000", "population_served_description": "Victims and oppressed people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" } ], "ntee_codes": [ { "ntee_code": "K99", "ntee_code_description": "Other Food, Agriculture, and Nutrition N.E.C." } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 189909560.0, "total_expenses": 189361369.0, "total_assets": 21939880.0 }, "bmf_gross_receipts": 189909560.0, "bmf_assets": 21939880.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-06-12T09:18:09.0000000", "profile_last_modified": "2023-06-13T14:07:15.0000000", "dei_last_modified": "2022-01-27T16:26:32.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-06-13T14:07:15.0000000" } }, { "organization": { "organization_id": "8552538", "ein": "26-0457477", "organization_name": "Feeding San Diego", "also_known_as": "FSD", "group_exemption": "0000", "mission": "Feeding San Diego is a non-profit organization on a mission to end hunger through food rescue. Established in 2007, we are the leading hunger-relief and food rescue organization in San Diego County and the only Feeding America affiliate in the region. Our organization provides 35 million meals every year to children, families, seniors, college students, military families, and veterans in partnership with a network of nearly 400 local charities, schools, faith communities, meal sites, and food pantries. Last year, more than 70 percent of the food provided to the community was rescued from local and national food donors. By diverting high-quality food from the landfill and reducing greenhouse gas emissions, Feeding San Diego protects people and the planet.", "website_url": "feedingsandiego.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8829355&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/26-0457477", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(858) 452-3663", "contact_title": "", "number_of_employees": "100", "ruling_year": 2007 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "9477 Waples St Ste 100", "address_line_2": "", "city": "San Diego", "state": "CA", "zip": "92121", "msa": "CA - San Diego", "congressional_district": "District 52, CA", "county": "San Diego, CA", "latitude": 32.9025, "longitude": -117.1834 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SJ060000", "subject_code_description": "Disasters and emergency management" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" } ], "population_served_codes": [ { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ060000", "population_served_description": "Military personnel" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 80337291.0, "total_expenses": 83839100.0, "total_assets": 16976547.0 }, "bmf_gross_receipts": 80348901.0, "bmf_assets": 16976547.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-16T14:47:32.0000000", "profile_last_modified": "2023-03-16T16:31:30.0000000", "dei_last_modified": "2023-03-16T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "8153945", "ein": "75-1785357", "organization_name": "North Texas Food Bank", "also_known_as": "NTFB", "group_exemption": "0000", "mission": "To close the hunger gap in North Texas by providing access to nutritious food.", "website_url": "www.ntfb.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8420432&approved=True", "profile_level": "Platinum", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/75-1785357", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2022-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(214) 270-2059", "contact_title": "Senior Director of Marketing and Communications", "number_of_employees": "284", "ruling_year": 1981 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3677 Mapleshade Ln", "address_line_2": "", "city": "Plano", "state": "TX", "zip": "75075", "msa": "TX - Dallas-Fort Worth", "congressional_district": "District 1, TX", "county": "Collin, TX", "latitude": 33.0033, "longitude": -96.762 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SE130602", "subject_code_description": "Nutrition" }, { "subject_code": "SE130600", "subject_code_description": "Physical fitness" }, { "subject_code": "SE130000", "subject_code_description": "Public health" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PJ020000", "population_served_description": "Unemployed people" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 213425483.0, "total_expenses": 206102038.0, "total_assets": 148508537.0 }, "bmf_gross_receipts": 315261741.0, "bmf_assets": 148508537.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2022-12-14T12:37:22.0000000", "profile_last_modified": "2022-12-14T12:37:22.0000000", "dei_last_modified": "2022-12-13T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7985589", "ein": "62-1049447", "organization_name": "Second Harvest Food Bank of Middle Tennessee", "also_known_as": "", "group_exemption": "0000", "mission": "We provide food to people facing hunger and work to advance hunger solutions.", "website_url": "www.secondharvestmidtn.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9382239&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/62-1049447", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President/CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(615) 329-3491", "contact_title": "President/CEO", "number_of_employees": "138", "ruling_year": 1979 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "331 Great Circle Rd", "address_line_2": "", "city": "Nashville", "state": "TN", "zip": "37228", "msa": "TN - Nashville", "congressional_district": "District 5, TN", "county": "Davidson, TN", "latitude": 36.1982, "longitude": -86.7946 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 133978627.0, "total_expenses": 127289471.0, "total_assets": 63545616.0 }, "bmf_gross_receipts": 138295787.0, "bmf_assets": 63545616.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-03-28T17:23:20.0000000", "profile_last_modified": "2023-08-22T16:14:58.0000000", "dei_last_modified": "2023-03-28T00:00:00.0000000", "financials_last_modified": "2023-05-18T19:00:46.0000000", "last_modified": "2023-08-22T16:14:58.0000000" } }, { "organization": { "organization_id": "8265555", "ein": "85-0278525", "organization_name": "Roadrunner Food Bank, Inc.", "also_known_as": "Roadrunner Food Bank of New Mexico", "group_exemption": "0000", "mission": "Roadrunner Food Bank of New Mexico is the largest non-profit dedicated to addressing food insecurity in New Mexico. As a food distribution hub, we provide food to hundreds of affiliated member partners around the state including food pantries, soup kitchens, shelters, and four smaller regional food banks. We also distribute food through specialized programs helping children, families, and seniors at schools, low-income seniors housing sites, senior centers, and with and through health care partnerships. Every week hundreds of thousands of hungry children, seniors and families are reached through this statewide hunger-relief network. We are working together with our partners, volunteers and contributors to end food insecurity and hunger in New Mexico.", "website_url": "www.rrfb.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8790393&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-0278525", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(505) 349-5333", "contact_title": "Chief Development Officer", "number_of_employees": "168", "ruling_year": 1980 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "5840 Office Blvd NE", "address_line_2": "", "city": "Albuquerque", "state": "NM", "zip": "87109", "msa": "NM - Albuquerque", "congressional_district": "", "county": "Bernalillo, NM", "latitude": 35.1457, "longitude": -106.601 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG040200", "population_served_description": "Ex-offenders" }, { "population_served_code": "PG040000", "population_served_description": "Incarcerated people" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K31", "ntee_code_description": "Food Banks, Food Pantries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 120843441.0, "total_expenses": 106819172.0, "total_assets": 51163005.0 }, "bmf_gross_receipts": 120843441.0, "bmf_assets": 51163005.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-03-07T15:48:02.0000000", "profile_last_modified": "2023-03-07T16:24:16.0000000", "dei_last_modified": "2023-03-07T00:00:00.0000000", "financials_last_modified": "2023-05-18T18:49:03.0000000", "last_modified": "2023-05-18T18:49:03.0000000" } } ] } ``` ## Search using keywords and filtering for city, state, and search terms ``` { "code": 200, "message": "Request was processed successfully!", "took": 40, "time": "2023-08-29 18:32:34Z", "results_count": 7, "page_count": 1, "errors": [], "hits": [ { "organization": { "organization_id": "8030190", "ein": "65-0988321", "organization_name": "Bonefish & Tarpon Trust", "also_known_as": "BTT", "group_exemption": "0000", "mission": "To conserve bonefish, tarpon, and permit--the species, their habitats and the fisheries they comprise through science-based conservation, education, and advocacy.", "website_url": "www.bonefishtarpontrust.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8718297&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/65-0988321", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(786) 618-9479", "contact_title": "President & CEO", "number_of_employees": "13", "ruling_year": 2001 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2937 SW 27th Ave Ste 203", "address_line_2": "", "city": "Miami", "state": "FL", "zip": "33133", "msa": "FL - Miami", "congressional_district": "District 27, FL", "county": "Miami-dade, FL", "latitude": 25.7368, "longitude": -80.2377 }, "taxonomies": { "subject_codes": [ { "subject_code": "SC060200", "subject_code_description": "Nature education" }, { "subject_code": "SC060000", "subject_code_description": "Environmental education" }, { "subject_code": "SC040102", "subject_code_description": "Aquatic wildlife protection" }, { "subject_code": "SC040100", "subject_code_description": "Wildlife biodiversity" }, { "subject_code": "SC040000", "subject_code_description": "Biodiversity" }, { "subject_code": "SC030406", "subject_code_description": "Wetlands" }, { "subject_code": "SC030403", "subject_code_description": "Oceans and coastal waters" }, { "subject_code": "SC030400", "subject_code_description": "Water resources" }, { "subject_code": "SC030000", "subject_code_description": "Natural resources" }, { "subject_code": "SC000000", "subject_code_description": "Environment" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "D33", "ntee_code_description": "Fisheries" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 3763572.0, "total_expenses": 3438243.0, "total_assets": 2159678.0 }, "bmf_gross_receipts": 4105184.0, "bmf_assets": 2159678.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-21T16:21:24.0000000", "profile_last_modified": "2023-02-21T16:24:32.0000000", "dei_last_modified": "2023-02-21T00:00:00.0000000", "financials_last_modified": "2023-04-21T07:03:12.0000000", "last_modified": "2023-04-21T07:03:12.0000000" } }, { "organization": { "organization_id": "8962613", "ein": "27-3185735", "organization_name": "Cleo Institute Inc", "also_known_as": "", "group_exemption": "0000", "mission": "TO EDUCATE & EMPOWER COMMUNITIES TO DEMAND CLIMATE ACTION, ENSURING A SAFE, JUST & HEALTHY ENVIRONMENT FOR ALL.", "website_url": "http://www.cleoinstitute.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=6706464&approved=True", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/27-3185735", "profile_logo": "", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(305) 573-5251", "contact_title": "Director of Programs", "number_of_employees": "17", "ruling_year": 2010 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2103 Coral Way Fl 2", "address_line_2": "", "city": "Miami", "state": "FL", "zip": "33145", "msa": "FL - Miami", "congressional_district": "District 27, FL", "county": "Miami-Dade, FL", "latitude": 25.7507, "longitude": -80.2281 }, "taxonomies": { "subject_codes": [ { "subject_code": "SC060000", "subject_code_description": "Environmental education" }, { "subject_code": "SJ060200", "subject_code_description": "Disaster preparedness" }, { "subject_code": "SJ060000", "subject_code_description": "Disasters and emergency management" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" }, { "subject_code": "SC000000", "subject_code_description": "Environment" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PC040000", "population_served_description": "Women and girls" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "C60", "ntee_code_description": "Environmental Education and Outdoor Survival Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 1445897.0, "total_expenses": 1261591.0, "total_assets": 1163052.0 }, "bmf_gross_receipts": 1445897.0, "bmf_assets": 1163052.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-08T19:00:00.0000000", "profile_last_modified": "2022-02-22T15:06:20.0000000", "dei_last_modified": "2019-11-26T11:10:57.0000000", "financials_last_modified": "2023-05-10T19:00:13.0000000", "last_modified": "2023-05-10T19:00:13.0000000" } }, { "organization": { "organization_id": "7041168", "ein": "20-5196010", "organization_name": "<NAME>, Inc.", "also_known_as": "Green Schools Challenge", "group_exemption": "0000", "mission": "Dream in Green’s mission is to empower individuals, especially youth, to lead in the response to climate change and other environmental challenges facing South Florida..We assist diverse organizations, including schools, households, local governments and businesses to reduce their environmental footprint. Through establishing partnerships in our community, we develop, implement and oversee educational programs and workshops that promote environmentally sustainable behaviors among all age groups, with a particular emphasis on K-12 students.", "website_url": "www.dreamingreen.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9315985&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/20-5196010", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(786) 574-4909", "contact_title": "Executive Director", "number_of_employees": "2", "ruling_year": 2006 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2103 Coral Way Center For Social Change 2nd Floor", "address_line_2": "", "city": "Miami", "state": "FL", "zip": "33145", "msa": "FL - Miami", "congressional_district": "District 27, FL", "county": "Miami-Dade, FL", "latitude": 25.7537, "longitude": -80.2336 }, "taxonomies": { "subject_codes": [ { "subject_code": "SC060000", "subject_code_description": "Environmental education" }, { "subject_code": "SC030600", "subject_code_description": "Energy resources" }, { "subject_code": "SC030000", "subject_code_description": "Natural resources" }, { "subject_code": "SC000000", "subject_code_description": "Environment" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B90", "ntee_code_description": "Educational Services and Schools - Other" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 233201.0, "total_expenses": 241212.0, "total_assets": 261426.0 }, "bmf_gross_receipts": 233201.0, "bmf_assets": 261426.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-08-02T11:02:35.0000000", "profile_last_modified": "2023-08-02T11:02:35.0000000", "dei_last_modified": "2020-06-19T16:55:50.0000000", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-08-02T11:02:35.0000000" } }, { "organization": { "organization_id": "8041374", "ein": "65-0350357", "organization_name": "The Miami Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "The Miami Foundation builds the philanthropic, civic, and leadership backbone for Greater Miami. Since 1967, the Foundation has invested $485 million to strengthen our community with partnerships and contributions from more than 1000 fundholders and 35,000 donors. The Miami Foundation, which currently manages over $350 million in assets, mobilizes donors, nonprofits, leaders, and locals to set a bold vision for our community's future and to invest in a stronger, more equitable, more resilient Greater Miami.", "website_url": "http://www.miamifoundation.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7139131&approved=True", "profile_level": "Bronze", "profile_year": 2021, "profile_link": "https://www.guidestar.org/profile/65-0350357", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2021-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "President and CEO", "number_of_employees": "35", "ruling_year": 1992 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "40 NW 3rd St Ste 305", "address_line_2": "", "city": "Miami", "state": "FL", "zip": "33128", "msa": "FL - Miami", "congressional_district": "District 24, FL", "county": "Miami-dade, FL", "latitude": 25.777, "longitude": -80.1944 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SA060000", "subject_code_description": "Performing arts" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" } ], "ntee_codes": [ { "ntee_code": "T31", "ntee_code_description": "Community Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 147324669.0, "total_expenses": 70287015.0, "total_assets": 460864709.0 }, "bmf_gross_receipts": 316768507.0, "bmf_assets": 460864709.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2021-09-28T09:46:03.0000000", "profile_last_modified": "2022-02-22T13:48:31.0000000", "dei_last_modified": "2021-01-20T11:59:17.0000000", "financials_last_modified": "2023-05-11T17:31:11.0000000", "last_modified": "2023-05-11T17:31:11.0000000" } }, { "organization": { "organization_id": "10066890", "ein": "86-3071998", "organization_name": "La Coupe Joseph Farm Project Inc", "also_known_as": "", "group_exemption": "0000", "mission": "La Coupe Joseph Farm Project Inc is devoted to deliver effective educational, ecological, and wellness resources that promote sustainable living within South Florida.", "website_url": "", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9346427&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/86-3071998", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO and Fund development Officer (a. i.)", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Chief Executive Officer", "number_of_employees": "", "ruling_year": 2022 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "20451 NW 2nd Ave Ste 103", "address_line_2": "", "city": "Miami", "state": "FL", "zip": "33169", "msa": "FL - Miami", "congressional_district": "District 24, FL", "county": "Miami-dade, FL", "latitude": 25.9635, "longitude": -80.2059 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS070106", "subject_code_description": "Transitional living" }, { "subject_code": "SS070100", "subject_code_description": "Supportive housing" }, { "subject_code": "SS070000", "subject_code_description": "Shelter and residential care" }, { "subject_code": "SS040800", "subject_code_description": "Single parent support" }, { "subject_code": "SS040700", "subject_code_description": "Parent education" }, { "subject_code": "SS040400", "subject_code_description": "Family counseling" }, { "subject_code": "SS040000", "subject_code_description": "Family services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN060600", "subject_code_description": "Entrepreneurship" }, { "subject_code": "SN060100", "subject_code_description": "Business promotion" }, { "subject_code": "SN060000", "subject_code_description": "Business and industry" }, { "subject_code": "SN030101", "subject_code_description": "Gardening" }, { "subject_code": "SN030100", "subject_code_description": "Community beautification" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SM020200", "subject_code_description": "Sustainable agriculture" }, { "subject_code": "SM020100", "subject_code_description": "Community food systems" }, { "subject_code": "SM020000", "subject_code_description": "Food security" }, { "subject_code": "SM000000", "subject_code_description": "Agriculture, fishing and forestry" }, { "subject_code": "SB070200", "subject_code_description": "Continuing education" }, { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ080000", "population_served_description": "Farmers" }, { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ030000", "population_served_description": "Self-employed people" }, { "population_served_code": "PJ020000", "population_served_description": "Unemployed people" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG060200", "population_served_description": "Victims of disaster" }, { "population_served_code": "PG060000", "population_served_description": "Victims and oppressed people" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010400", "population_served_description": "Refugees and displaced people" }, { "population_served_code": "PG010200", "population_served_description": "Migrant workers" }, { "population_served_code": "PG010100", "population_served_description": "Immigrants" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE070000", "population_served_description": "Multiracial people" }, { "population_served_code": "PE050300", "population_served_description": "People of Caribbean descent" }, { "population_served_code": "PE050000", "population_served_description": "People of Latin American descent" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020200", "population_served_description": "Older adults" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "K99", "ntee_code_description": "Other Food, Agriculture, and Nutrition N.E.C." } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "EZ", "fiscal_year": 2022, "total_revenue": 0.0, "total_expenses": 0.0, "total_assets": 0.0 }, "bmf_gross_receipts": 0.0, "bmf_assets": 789.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-08-10T23:09:47.0000000", "profile_last_modified": "2023-08-11T19:57:15.0000000", "dei_last_modified": "2023-08-10T00:00:00.0000000", "financials_last_modified": "2023-05-18T18:49:23.0000000", "last_modified": "2023-08-11T19:57:15.0000000" } }, { "organization": { "organization_id": "9997334", "ein": "86-2827046", "organization_name": "Resilience Youth Network", "also_known_as": "", "group_exemption": "0000", "mission": "", "website_url": "resilienceyouthnetwork.org", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/86-2827046", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2021 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "441 NE 52nd St", "address_line_2": "", "city": "Miami", "state": "FL", "zip": "33137", "msa": "FL - Miami", "congressional_district": "District 24, FL", "county": "Miami-dade, FL", "latitude": 25.8237, "longitude": -80.186 }, "taxonomies": { "subject_codes": [ { "subject_code": "SJ000000", "subject_code_description": "Public safety" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "M01", "ntee_code_description": "Alliance/Advocacy Organizations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-09-09T13:27:18.0000000" } }, { "organization": { "organization_id": "9469959", "ein": "47-3369805", "organization_name": "Resilience Action Fund Inc", "also_known_as": "RESILIENCE ACTION FUND", "group_exemption": "0000", "mission": "Empowerconsumerswithknowledgeandtoolstowithstandnaturalhazardswithlong-lastingandresilienthomesandcommunities,includingpublications,documentaries,buildingresilienceindex,homebuyers'guide,publicoutreachandothereducationaltools.", "website_url": "www.buildingresilient.com", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/47-3369805", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2015 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "441 NE 52nd St", "address_line_2": "", "city": "Miami", "state": "FL", "zip": "33137", "msa": "FL - Miami", "congressional_district": "District 24, FL", "county": "Miami-dade, FL", "latitude": 25.8237, "longitude": -80.186 }, "taxonomies": { "subject_codes": [ { "subject_code": "SJ000000", "subject_code_description": "Public safety" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "M01", "ntee_code_description": "Alliance/Advocacy Organizations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "EZ", "fiscal_year": 2022, "total_revenue": 97776.0, "total_expenses": 59012.0, "total_assets": 400530.0 }, "bmf_gross_receipts": 97809.0, "bmf_assets": 400530.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "2023-05-18T17:01:47.0000000", "last_modified": "2023-05-18T17:01:47.0000000" } } ] } ``` ## Filter search results by Candid's taxonomy Filter results by using Candid's taxonomy, up to 25 codes at a time. ``` { "filters": { "organization": { "subject_codes":["SB090200"], /*college preparation*/ "population_served_codes":["PA020100"] /*young adults*/ } } } ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 39, "time": "2023-08-29 18:33:07Z", "results_count": 118, "page_count": 5, "errors": [], "hits": [ { "organization": { "organization_id": "7606737", "ein": "41-1968798", "organization_name": "College Possible", "also_known_as": "", "group_exemption": "0000", "mission": "College Possible is making college admission and success possible for students from low-income backgrounds through an intensive curriculum of coaching and support.", "website_url": "www.CollegePossible.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8640923&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/41-1968798", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(651) 288-9455", "contact_title": "CEO", "number_of_employees": "813", "ruling_year": 2000 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "755 Prior Ave N Ste 210", "address_line_2": "", "city": "St Paul", "state": "MN", "zip": "55104", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "District 4, MN", "county": "Ramsey, MN", "latitude": 44.9656, "longitude": -93.1823 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 31201183.0, "total_expenses": 27834304.0, "total_assets": 23283310.0 }, "bmf_gross_receipts": 31323954.0, "bmf_assets": 23283310.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-02-03T14:31:21.0000000", "profile_last_modified": "2023-02-03T14:31:21.0000000", "dei_last_modified": "2023-01-27T00:00:00.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-05-18T17:01:04.0000000" } }, { "organization": { "organization_id": "6926751", "ein": "13-3840394", "organization_name": "The Posse Foundation", "also_known_as": "Posse", "group_exemption": "0000", "mission": "The Posse Foundation benefits both students and college campuses and is rooted in the belief that a small, diverse group of talented students – a \"posse\" – carefully selected and trained, serves as a catalyst for individual and community development. As the United States becomes an increasingly multicultural society, Posse believes that the leaders of the 21st century should reflect the country's rich demographic mix. The key to a promising future for our nation rests on the ability of strong leaders from diverse backgrounds to develop consensus solutions to complex social problems. Posse's primary aim is to cultivate these leaders of tomorrow.", "website_url": "http://www.possefoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7812846&approved=True", "profile_level": "Platinum", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/13-3840394", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2022-seal.svg", "leader_name": "<NAME>", "leader_title": "President and Founder", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(212) 405-1691", "contact_title": "Chief Development Officer", "number_of_employees": "240", "ruling_year": 1996 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "14 Wall St Ste 8a60", "address_line_2": "", "city": "New York City", "state": "NY", "zip": "10005", "msa": "NY - New York, NY-NJ", "congressional_district": "District 10, NY", "county": "New York, NY", "latitude": 40.7074, "longitude": -74.011 }, "taxonomies": { "subject_codes": [ { "subject_code": "SK020000", "subject_code_description": "Leadership development" }, { "subject_code": "SK000000", "subject_code_description": "Public affairs" }, { "subject_code": "SB090500", "subject_code_description": "Student retention" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B82", "ntee_code_description": "Scholarships, Student Financial Aid, Awards" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 33725316.0, "total_expenses": 23252059.0, "total_assets": 137527136.0 }, "bmf_gross_receipts": 48302842.0, "bmf_assets": 137527136.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-04-08T16:54:52.0000000", "profile_last_modified": "2022-05-20T12:33:35.0000000", "dei_last_modified": "2022-04-12T12:28:13.0000000", "financials_last_modified": "2023-05-18T18:49:03.0000000", "last_modified": "2023-05-18T18:49:03.0000000" } }, { "organization": { "organization_id": "9250464", "ein": "46-1314848", "organization_name": "uAspire", "also_known_as": "Previously known as ACCESS", "group_exemption": "0000", "mission": "uAspire is a nonprofit organization ensuring that all young people have the financial information and resources necessary to find an affordable path to and through college. Our singular focus is on college affordability and removing financial barriers so that every student has an equitable opportunity to graduate from college and succeed in life.Through student advising, counselor training, and policy and systems change, we work to remove the financial barriers to higher education. Collectively, our three models impacted over 690,000 students nationwide in 2018-19. Headquartered in Boston, we have a team of 65 full-time staff in California, Massachusetts, and New York.", "website_url": "http://www.uaspire.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8762212&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/46-1314848", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Senior Director, Marketing and Communications", "number_of_employees": "87", "ruling_year": 2013 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "31 Milk St Ste 900", "address_line_2": "", "city": "Boston", "state": "MA", "zip": "02109", "msa": "MA - Boston", "congressional_district": "District 8, MA", "county": "Suffolk, MA", "latitude": 42.3568, "longitude": -71.058 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B82", "ntee_code_description": "Scholarships, Student Financial Aid, Awards" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 11001635.0, "total_expenses": 7683195.0, "total_assets": 9973087.0 }, "bmf_gross_receipts": 13454450.0, "bmf_assets": 9973087.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-28T16:45:16.0000000", "profile_last_modified": "2023-02-28T16:45:16.0000000", "dei_last_modified": "2021-03-25T10:17:31.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "9907570", "ein": "85-0902650", "organization_name": "TECH FORWARD INC", "also_known_as": "HBCU FORCE", "group_exemption": "0000", "mission": "Tech Forward is a nonprofit organization that exposes marginalized communities tocloud and SAAS (software-as-a-service) based technologies and career paths to helpparticipants be more marketable, and obtain higher-paying jobs and career opportunities.", "website_url": "http://www.hbcuforce.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8934059&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-0902650", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Founder and Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Founder and Executive Director", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "5829 Campbellton Rd SW # 104-168", "address_line_2": "", "city": "Atlanta", "state": "GA", "zip": "30331", "msa": "GA - Atlanta", "congressional_district": "District 5, GA", "county": "Fulton, GA", "latitude": 33.6992, "longitude": -84.578 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS080000", "subject_code_description": "Job services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SB090800", "subject_code_description": "E-learning" }, { "subject_code": "SB090300", "subject_code_description": "Computer literacy" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB031000", "subject_code_description": "STEM education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050200", "population_served_description": "Teachers" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PE050300", "population_served_description": "People of Caribbean descent" }, { "population_served_code": "PE050000", "population_served_description": "People of Latin American descent" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P20", "ntee_code_description": "Human Service Organizations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-04-17T17:54:45.0000000", "profile_last_modified": "2023-04-17T17:54:45.0000000", "dei_last_modified": "2021-02-07T19:08:50.0000000", "financials_last_modified": "", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "9968776", "ein": "85-2923799", "organization_name": "Xceleader", "also_known_as": "", "group_exemption": "0000", "mission": "Increase and strengthen Black leadership by providing tools that inspire action and fuel ambition.", "website_url": "https://www.xceleader.com", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9019922&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-2923799", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Co-Founder", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1414 N Shepherd Dr Apt 404", "address_line_2": "", "city": "Houston", "state": "TX", "zip": "77008", "msa": "TX - Houston", "congressional_district": "District 2, TX", "county": "Harris, TX", "latitude": 29.7963, "longitude": -95.41 }, "taxonomies": { "subject_codes": [ { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SN020302", "subject_code_description": "Job training" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SK020000", "subject_code_description": "Leadership development" }, { "subject_code": "SK000000", "subject_code_description": "Public affairs" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020200", "population_served_description": "Older adults" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "R99", "ntee_code_description": "Civil Rights, Social Action, and Advocacy N.E.C." } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-02T14:03:41.0000000", "profile_last_modified": "2023-05-15T15:47:48.0000000", "dei_last_modified": "2022-11-29T11:54:57.0000000", "financials_last_modified": "", "last_modified": "2023-05-15T15:47:48.0000000" } }, { "organization": { "organization_id": "9962085", "ein": "85-2539829", "organization_name": "<NAME>", "also_known_as": "<NAME>", "group_exemption": "0000", "mission": "Our mission is to provide a way for adolescents and young adults to achieve economic mobility by equipping them with life-based skills and resources to overcome their adversities.", "website_url": "https://gene-xcellence.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8933280&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-2539829", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Founder, CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2021 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "106 W Georgia Rd", "address_line_2": "", "city": "Simpsonville", "state": "SC", "zip": "29681", "msa": "SC - Greenville-Spartanburg-Anderson", "congressional_district": "District 4, SC", "county": "Greenville, SC", "latitude": 34.7396, "longitude": -82.2583 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050600", "subject_code_description": "Economics for youth" }, { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS050303", "subject_code_description": "Youth peer mentoring" }, { "subject_code": "SS050301", "subject_code_description": "Adult and child mentoring" }, { "subject_code": "SS050300", "subject_code_description": "Youth mentoring" }, { "subject_code": "SS050100", "subject_code_description": "Youth services" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090100", "subject_code_description": "Out-of-school learning" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O50", "ntee_code_description": "Youth Development Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-04-17T15:16:08.0000000", "profile_last_modified": "2023-04-17T15:46:23.0000000", "dei_last_modified": "2022-08-29T18:36:26.0000000", "financials_last_modified": "", "last_modified": "2023-04-17T15:46:23.0000000" } }, { "organization": { "organization_id": "9925672", "ein": "84-3478958", "organization_name": "Holistic Evolution Inc", "also_known_as": "", "group_exemption": "0000", "mission": "Our Mission is to encourage the evolution of males of color 16-24 through supporting mentoring, health equity and other prevention efforts in Northwest Indiana; providing resources to remove unforeseen barriers to the evolution of males of color.", "website_url": "https://www.holisticevolution.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8983987&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/84-3478958", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(219) 293-7553", "contact_title": "CEO", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "234 Marcliffe Dr Apt 7", "address_line_2": "", "city": "Valparaiso", "state": "IN", "zip": "46385", "msa": "IN - Gary-Hammond-East Chicago", "congressional_district": "District 1, IN", "county": "Porter, IN", "latitude": 41.4445, "longitude": -87.1127 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS060602", "subject_code_description": "Aging out of foster care" }, { "subject_code": "SS060600", "subject_code_description": "Transition planning" }, { "subject_code": "SS060000", "subject_code_description": "Personal services" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SR050000", "subject_code_description": "Diversity and intergroup relations" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030200", "subject_code_description": "Community organizing" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SJ020000", "subject_code_description": "Abuse prevention" }, { "subject_code": "SJ010100", "subject_code_description": "Impaired driving" }, { "subject_code": "SJ010000", "subject_code_description": "Crime prevention" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" }, { "subject_code": "SE130600", "subject_code_description": "Physical fitness" }, { "subject_code": "SE130500", "subject_code_description": "Sexually transmitted disease control" }, { "subject_code": "SE130000", "subject_code_description": "Public health" }, { "subject_code": "SE120700", "subject_code_description": "Mental health counseling" }, { "subject_code": "SE120200", "subject_code_description": "Community mental health care" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE020000", "subject_code_description": "Health care access" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SB091200", "subject_code_description": "Tutoring" }, { "subject_code": "SB090500", "subject_code_description": "Student retention" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090100", "subject_code_description": "Out-of-school learning" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB020000", "subject_code_description": "Educational management" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG040200", "population_served_description": "Ex-offenders" }, { "population_served_code": "PG040000", "population_served_description": "Incarcerated people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE070000", "population_served_description": "Multiracial people" }, { "population_served_code": "PE060000", "population_served_description": "Indigenous peoples" }, { "population_served_code": "PE050000", "population_served_description": "People of Latin American descent" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE020000", "population_served_description": "People of Asian descent" }, { "population_served_code": "PE010000", "population_served_description": "People of Middle Eastern descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PD040400", "population_served_description": "Transitioning children" }, { "population_served_code": "PD040000", "population_served_description": "Non-adult children" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O50", "ntee_code_description": "Youth Development Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-05-03T15:47:54.0000000", "profile_last_modified": "2023-05-03T15:47:54.0000000", "dei_last_modified": "2023-05-03T14:29:01.0000000", "financials_last_modified": "", "last_modified": "2023-05-03T15:47:54.0000000" } }, { "organization": { "organization_id": "9916903", "ein": "85-1487665", "organization_name": "Charity Achievement Networking and Education Foundation", "also_known_as": "CANE Foundation", "group_exemption": "0000", "mission": "The purpose of CANE is to positively influence the well-being, aspirations, connectedness, and education of youth in the Pearland-Manvel-Fresno, Texas area; with special emphasis on underappreciated and underserved African-American youth. Embedded in this purpose is the uplifting, promotion, support, admiration, and appreciation of often overlooked achievers and difference-makers in the community.", "website_url": "www.thecanefoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8686721&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-1487665", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Treasurer", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3422 Business Center Dr Ste 106 # 49", "address_line_2": "", "city": "Pearland", "state": "TX", "zip": "77584", "msa": "TX - Brazoria", "congressional_district": "District 22, TX", "county": "Brazoria, TX", "latitude": 29.5517, "longitude": -95.3703 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB090500", "subject_code_description": "Student retention" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB031000", "subject_code_description": "STEM education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE070000", "population_served_description": "Multiracial people" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "S80", "ntee_code_description": "Community Service Clubs (Kiwanis, Lions, Jaycees, etc.)" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-13T19:50:48.0000000", "profile_last_modified": "2023-02-13T19:50:48.0000000", "dei_last_modified": "2020-12-16T17:57:08.0000000", "financials_last_modified": "", "last_modified": "2023-03-14T12:27:00.0000000" } }, { "organization": { "organization_id": "9125335", "ein": "80-0177104", "organization_name": "Collective Souls Incorporated", "also_known_as": "", "group_exemption": "0000", "mission": "Mission is to educate, mentor, and nurture today's youth to help them reach their highest potential in becoming successful in life.", "website_url": "www.collectivesoulsinc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/80-0177104", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(314) 479-7747", "contact_title": "CEO", "number_of_employees": "", "ruling_year": 2011 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "7829 Bloom Dr", "address_line_2": "", "city": "St Louis", "state": "MO", "zip": "63133", "msa": "MO - St. Louis, MO-IL", "congressional_district": "District 1, MO", "county": "Saint Louis, MO", "latitude": 38.6742, "longitude": -91.3388 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS050800", "subject_code_description": "Community service for youth" }, { "subject_code": "SS050300", "subject_code_description": "Youth mentoring" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB091200", "subject_code_description": "Tutoring" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA010500", "subject_code_description": "Arts education" }, { "subject_code": "SA010000", "subject_code_description": "Arts services" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O50", "ntee_code_description": "Youth Development Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-08T21:18:08.0000000", "profile_last_modified": "2023-01-08T21:18:08.0000000", "dei_last_modified": "2023-01-08T20:10:43.0000000", "financials_last_modified": "", "last_modified": "2023-04-10T15:32:00.0000000" } }, { "organization": { "organization_id": "7663448", "ein": "43-1815310", "organization_name": "Kanakuk Ministries", "also_known_as": "Kanakuk Kamps, Kanakuk KampOut, Link Year, Link Academy, and AfterDark", "group_exemption": "0000", "mission": "Equipping Next Generation Christian Leaders is more than our mission, it is our heartbeat. Since 1926, Kanakuk has welcomed over 500,000 Kampers and 50,000 summer staff from across the country and around the world, equipping them with leadership skills and Biblical truths to impact their schools and communities as examples of Jesus Christ.", "website_url": "https://kanakuk.com/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8329795&approved=True", "profile_level": "Gold", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/43-1815310", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Chairman", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(417) 266-3334", "contact_title": "Chief Business Officer", "number_of_employees": "2221", "ruling_year": 2015 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1353 Lake Shore Dr", "address_line_2": "", "city": "Branson", "state": "MO", "zip": "65616", "msa": "", "congressional_district": "District 7, MO", "county": "Taney, MO", "latitude": 36.6495, "longitude": -93.2457 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050900", "subject_code_description": "Religion for youth" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SQ020000", "subject_code_description": "Sports" }, { "subject_code": "SQ010100", "subject_code_description": "Camps" }, { "subject_code": "SQ010000", "subject_code_description": "Community recreation" }, { "subject_code": "SQ000000", "subject_code_description": "Sports and recreation" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PF010000", "population_served_description": "Christians" }, { "population_served_code": "PF000000", "population_served_description": "Religious groups" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O55", "ntee_code_description": "Religious Leadership, Youth Development" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 37973061.0, "total_expenses": 35386498.0, "total_assets": 49435943.0 }, "bmf_gross_receipts": 39512496.0, "bmf_assets": 49435943.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-14T19:02:02.0000000", "profile_last_modified": "2022-11-14T19:08:22.0000000", "dei_last_modified": "2022-11-14T00:00:00.0000000", "financials_last_modified": "2023-08-24T13:00:37.0000000", "last_modified": "2023-08-24T13:00:37.0000000" } }, { "organization": { "organization_id": "9742285", "ein": "82-4458239", "organization_name": "MENTEE", "also_known_as": "MENTEE Global", "group_exemption": "0000", "mission": "MENTEE is a non-profit organization aligned with global SDGs that provides access to a global network of mentor specialists who share their skills and support to help create better, healthier lives for marginalized populations living around the world. Using our virtual platform, mentees are given the power of access to choose any specialist they need to help accelerate their success. The program provides trauma and mentorship training for our global mentors as well as additional professional skills training for our mentees. We are partnered with 5 NGOs and institutions globally and are supporting 7 different countries on 4 different continents.", "website_url": "www.menteeglobal.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8605490&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/82-4458239", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Founder & CEO", "contact_name": "Mrs. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(708) 647-1542", "contact_title": "Founder & CEO", "number_of_employees": "", "ruling_year": 2018 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1320 Dartford Ct", "address_line_2": "", "city": "Naperville", "state": "IL", "zip": "60540", "msa": "IL - Chicago", "congressional_district": "District 6, IL", "county": "Dupage, IL", "latitude": 41.7575, "longitude": -88.115 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SR040000", "subject_code_description": "Antidiscrimination" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SN020302", "subject_code_description": "Job training" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020200", "population_served_description": "Older adults" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O50", "ntee_code_description": "Youth Development Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-28T16:54:06.0000000", "profile_last_modified": "2023-01-28T16:54:06.0000000", "dei_last_modified": "2020-11-20T19:08:28.0000000", "financials_last_modified": "", "last_modified": "2023-01-28T16:54:06.0000000" } }, { "organization": { "organization_id": "9899191", "ein": "85-1160030", "organization_name": "Sabinal Alumni", "also_known_as": "", "group_exemption": "0000", "mission": "To support Sabinal Independent School District through scholarships that enable graduates to pursue a postsecondary education.", "website_url": "www.sabinalalumni.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9245695&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-1160030", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "President", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "555 E 5th St Apt 3007", "address_line_2": "", "city": "Austin", "state": "TX", "zip": "78701", "msa": "TX - Austin-San Marcos", "congressional_district": "District 21, TX", "county": "Travis, TX", "latitude": 30.2657, "longitude": -97.738 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080100", "subject_code_description": "Alumni relations" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050100", "subject_code_description": "Community college education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B84", "ntee_code_description": "Alumni Associations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-07-10T19:21:01.0000000", "profile_last_modified": "2023-07-10T19:21:01.0000000", "dei_last_modified": "2023-07-10T16:56:50.0000000", "financials_last_modified": "", "last_modified": "2023-07-10T19:21:01.0000000" } }, { "organization": { "organization_id": "9945110", "ein": "85-3756579", "organization_name": "<NAME>", "also_known_as": "", "group_exemption": "0000", "mission": "To bridge the gap of educational inequity in LA County by supporting the students who need it most. Not only is there an increasingly widening gap in educational opportunities and outcomes in LA County, there is also a significant gap in scholarship funding available for high potential students who don’t score well using traditional metrics like GPA and standardized test scores. AFF aims to close this gap by supporting those who may not have the highest GPA or SAT scores, but display strong morals, grit and determination in the face of adversity. Lastly, we aim to honor Alexx’s memory by giving back to the communities that he called home.", "website_url": "afloresfoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8819500&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-3756579", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(626) 890- x367", "contact_title": "Executive Director", "number_of_employees": "", "ruling_year": 2021 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "5830 Benner St", "address_line_2": "", "city": "Los Angeles", "state": "CA", "zip": "90042", "msa": "CA - Los Angeles-Long Beach", "congressional_district": "District 34, CA", "county": "Los Angeles, CA", "latitude": 34.1074, "longitude": -118.1899 }, "taxonomies": { "subject_codes": [ { "subject_code": "SC040300", "subject_code_description": "Forest preservation" }, { "subject_code": "SC040000", "subject_code_description": "Biodiversity" }, { "subject_code": "SC000000", "subject_code_description": "Environment" }, { "subject_code": "SB090500", "subject_code_description": "Student retention" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050100", "subject_code_description": "Community college education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "C36", "ntee_code_description": "Forest Conservation" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-14T20:51:41.0000000", "profile_last_modified": "2023-03-14T20:51:41.0000000", "dei_last_modified": "2023-03-14T00:00:00.0000000", "financials_last_modified": "", "last_modified": "2023-04-10T15:32:00.0000000" } }, { "organization": { "organization_id": "9957537", "ein": "86-1715885", "organization_name": "Tepic Foundation Inc", "also_known_as": "", "group_exemption": "0000", "mission": "We make career education accessible to ALL to impact lives and communities.", "website_url": "https://www.tepicfoundation.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8607126&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/86-1715885", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Founder & President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(706) 383- x9618", "contact_title": "Founder & President, CEO", "number_of_employees": "", "ruling_year": 2021 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1323 W Walnut Ave Ste 2 # 208", "address_line_2": "", "city": "Dalton", "state": "GA", "zip": "30720", "msa": "", "congressional_district": "District 14, GA", "county": "Whitfield, GA", "latitude": 34.7594, "longitude": -84.9913 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050300", "subject_code_description": "Youth mentoring" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS040700", "subject_code_description": "Parent education" }, { "subject_code": "SS040000", "subject_code_description": "Family services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB070200", "subject_code_description": "Continuing education" }, { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD020200", "population_served_description": "Adolescent parents" }, { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P20", "ntee_code_description": "Human Service Organizations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-29T12:31:31.0000000", "profile_last_modified": "2023-01-29T12:31:31.0000000", "dei_last_modified": "2023-01-29T00:00:00.0000000", "financials_last_modified": "", "last_modified": "2023-03-14T12:27:00.0000000" } }, { "organization": { "organization_id": "10095317", "ein": "88-2074295", "organization_name": "Positive Integration Inc", "also_known_as": "", "group_exemption": "0000", "mission": "Positive Integration's mission is to bridge the divide between our young people, ages 16 to 24, in the community and the growing skills gaping in our workforce. Positive Integration specializes in training and employment opportunities for youth and young adults. We envision a community where young people are more broadly valued, hired by employers, receiving support, and participating in positive & meaningful life activities.", "website_url": "www.positiveintegration.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9329917&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/88-2074295", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Executive Director", "number_of_employees": "", "ruling_year": 2022 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "4720 W Donges Ln", "address_line_2": "", "city": "Milwaukee", "state": "WI", "zip": "53223", "msa": "WI - Milwaukee", "congressional_district": "District 4, WI", "county": "Milwaukee, WI", "latitude": 43.1913, "longitude": -87.9694 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050800", "subject_code_description": "Community service for youth" }, { "subject_code": "SS050600", "subject_code_description": "Economics for youth" }, { "subject_code": "SS050301", "subject_code_description": "Adult and child mentoring" }, { "subject_code": "SS050300", "subject_code_description": "Youth mentoring" }, { "subject_code": "SS050100", "subject_code_description": "Youth services" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN020304", "subject_code_description": "Job creation and workforce development" }, { "subject_code": "SN020302", "subject_code_description": "Job training" }, { "subject_code": "SN020301", "subject_code_description": "Job counseling" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ020000", "population_served_description": "Unemployed people" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PE050000", "population_served_description": "People of Latin American descent" }, { "population_served_code": "PE040000", "population_served_description": "People of European descent" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "J22", "ntee_code_description": "Employment Training" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-08-03T15:58:27.0000000", "profile_last_modified": "2023-08-07T15:20:38.0000000", "dei_last_modified": "2023-08-02T16:13:40.0000000", "financials_last_modified": "", "last_modified": "2023-08-07T15:20:38.0000000" } }, { "organization": { "organization_id": "9832922", "ein": "84-3142901", "organization_name": "TLT - Tomorrows Leaders Today Inc", "also_known_as": "", "group_exemption": "0000", "mission": "TLT- Tomorrows Leaders Today, Inc. is a 501(c)(3) nonprofit organization dedicated to helping develop youth leaders through education, collaboration and mentorships with community & business leaders for the collective benefit of the students and their communities.", "website_url": "www.TLTLeaders.Org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9370639&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/84-3142901", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President/Executive Director and Founder", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(214) 226-5971", "contact_title": "Founder, President, Executive Director", "number_of_employees": "", "ruling_year": 2019 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 5058", "address_line_2": "", "city": "Frisco", "state": "TX", "zip": "75035", "msa": "TX - Dallas-Fort Worth", "congressional_district": "District 1, TX", "county": "Collin, TX", "latitude": 33.152, "longitude": -96.7752 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050800", "subject_code_description": "Community service for youth" }, { "subject_code": "SS050700", "subject_code_description": "Civics for youth" }, { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS050300", "subject_code_description": "Youth mentoring" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB090400", "subject_code_description": "Cooperative education" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ060000", "population_served_description": "Military personnel" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ020000", "population_served_description": "Unemployed people" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020200", "population_served_description": "Older adults" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O50", "ntee_code_description": "Youth Development Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-09T16:48:30.0000000", "profile_last_modified": "2023-08-18T22:26:53.0000000", "dei_last_modified": "2023-08-18T00:00:00.0000000", "financials_last_modified": "", "last_modified": "2023-08-18T22:26:53.0000000" } }, { "organization": { "organization_id": "9930923", "ein": "85-3048142", "organization_name": "Create and Collaborate", "also_known_as": "Create + Collaborate", "group_exemption": "0000", "mission": "WE CREATE ENDLESS OPPORTUNITIES FOR UNDERSERVED YOUNG ADULTS THROUGH COLLABORATIVE PARTNERSHIPS BY PROVIDING THEM WITH THE RESOURCES THEY NEED TO DREAM AND SUCCEED.", "website_url": "www.createandco.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8616688&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-3048142", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Founder, CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Founder, CEO", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "501 W Rosedale St Apt 149", "address_line_2": "", "city": "Fort Worth", "state": "TX", "zip": "76104", "msa": "TX - Fort Worth", "congressional_district": "", "county": "Tarrant, TX", "latitude": 32.7332, "longitude": -97.3299 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SQ022200", "subject_code_description": "Sports training" }, { "subject_code": "SQ020000", "subject_code_description": "Sports" }, { "subject_code": "SQ000000", "subject_code_description": "Sports and recreation" }, { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG060100", "population_served_description": "Victims of crime and abuse" }, { "population_served_code": "PG060000", "population_served_description": "Victims and oppressed people" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O99", "ntee_code_description": "Other Youth Development N.E.C." } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 71173.0, "bmf_assets": 52229.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-31T02:00:17.0000000", "profile_last_modified": "2023-01-31T02:01:50.0000000", "dei_last_modified": "2023-01-31T00:00:00.0000000", "financials_last_modified": "", "last_modified": "2023-07-10T17:03:00.0000000" } }, { "organization": { "organization_id": "7414365", "ein": "34-6516654", "organization_name": "United Way of Greater Cleveland", "also_known_as": "United Way", "group_exemption": "5378", "mission": "United Way of Greater Cleveland mobilizes people and resources by creating solutions that improve lives and our community.", "website_url": "http://www.unitedwaycleveland.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9067411&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/34-6516654", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(216) 436-2208", "contact_title": "Proposal Manager/Grant Writer", "number_of_employees": "146", "ruling_year": 1960 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": true, "subordinate": false, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "1331 Euclid Ave", "address_line_2": "", "city": "Cleveland", "state": "OH", "zip": "44115", "msa": "OH - Cleveland", "congressional_district": "District 11, OH", "county": "Cuyahoga, OH", "latitude": 41.5009, "longitude": -81.6823 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SS070400", "subject_code_description": "Homeless shelters" }, { "subject_code": "SS070100", "subject_code_description": "Supportive housing" }, { "subject_code": "SS070000", "subject_code_description": "Shelter and residential care" }, { "subject_code": "SS050300", "subject_code_description": "Youth mentoring" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS040000", "subject_code_description": "Family services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN050800", "subject_code_description": "Financial counseling" }, { "subject_code": "SN050000", "subject_code_description": "Financial services" }, { "subject_code": "SN020302", "subject_code_description": "Job training" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SM020000", "subject_code_description": "Food security" }, { "subject_code": "SM000000", "subject_code_description": "Agriculture, fishing and forestry" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" }, { "subject_code": "SE130000", "subject_code_description": "Public health" }, { "subject_code": "SE120504", "subject_code_description": "Substance abuse treatment" }, { "subject_code": "SE120500", "subject_code_description": "Addiction services" }, { "subject_code": "SE120200", "subject_code_description": "Community mental health care" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE050100", "subject_code_description": "Health care clinics" }, { "subject_code": "SE050000", "subject_code_description": "Out-patient medical care" }, { "subject_code": "SE040200", "subject_code_description": "Community health care" }, { "subject_code": "SE040000", "subject_code_description": "In-patient medical care" }, { "subject_code": "SE030700", "subject_code_description": "Patient-centered care" }, { "subject_code": "SE030000", "subject_code_description": "Health care administration and financing" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SB100000", "subject_code_description": "Early childhood education" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090100", "subject_code_description": "Out-of-school learning" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH030000", "population_served_description": "Substance abusers" }, { "population_served_code": "PH020300", "population_served_description": "Terminally ill people" }, { "population_served_code": "PH020100", "population_served_description": "People with HIV/AIDS" }, { "population_served_code": "PH020000", "population_served_description": "People with diseases and illnesses" }, { "population_served_code": "PH010400", "population_served_description": "People with psychosocial disabilities" }, { "population_served_code": "PH010100", "population_served_description": "People with physical disabilities" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG060100", "population_served_description": "Victims of crime and abuse" }, { "population_served_code": "PG060000", "population_served_description": "Victims and oppressed people" }, { "population_served_code": "PG040000", "population_served_description": "Incarcerated people" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030100", "population_served_description": "Homeless people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD050000", "population_served_description": "Caregivers" }, { "population_served_code": "PD020400", "population_served_description": "Single parents" }, { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PC050200", "population_served_description": "Men" }, { "population_served_code": "PC050100", "population_served_description": "Boys" }, { "population_served_code": "PC050000", "population_served_description": "Men and boys" }, { "population_served_code": "PC040200", "population_served_description": "Women" }, { "population_served_code": "PC040100", "population_served_description": "Girls" }, { "population_served_code": "PC040000", "population_served_description": "Women and girls" }, { "population_served_code": "PC010000", "population_served_description": "LGBTQ people" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" }, { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010100", "population_served_description": "Infants and toddlers" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T70", "ntee_code_description": "Fund Raising Organizations That Cross Categories includes Community Funds/Trusts and Federated Giving Programs) e.g. United Way" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 18584237.0, "total_expenses": 18261123.0, "total_assets": 37317556.0 }, "bmf_gross_receipts": 18648897.0, "bmf_assets": 37317556.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-26T10:02:58.0000000", "profile_last_modified": "2023-05-31T07:43:15.0000000", "dei_last_modified": "2023-05-26T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-07-10T17:03:00.0000000" } }, { "organization": { "organization_id": "7278818", "ein": "25-0753320", "organization_name": "George Junior Republic in Pennsylvania", "also_known_as": "", "group_exemption": "0000", "mission": "George Junior Republic is dedicated to changing the lives of at-risk youth through a broad continuum of programs that engage the entire person and support the mental, physical, and emotional needs while teaching responsibility, citizenship, and skills that will help them grow into productive members of society.", "website_url": "www.gjr.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8852714&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/25-0753320", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(724) 458-9330 x2115", "contact_title": "Development Director", "number_of_employees": "558", "ruling_year": 1961 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "233 George Junior Rd", "address_line_2": "", "city": "Grove City", "state": "PA", "zip": "16127", "msa": "PA - Sharon", "congressional_district": "District 16, PA", "county": "Mercer, PA", "latitude": 41.1641, "longitude": -80.0861 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS070100", "subject_code_description": "Supportive housing" }, { "subject_code": "SS070000", "subject_code_description": "Shelter and residential care" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN060800", "subject_code_description": "Trade" }, { "subject_code": "SN060000", "subject_code_description": "Business and industry" }, { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN020302", "subject_code_description": "Job training" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SE120500", "subject_code_description": "Addiction services" }, { "subject_code": "SE120300", "subject_code_description": "Residential mental health care" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA050400", "subject_code_description": "Design" }, { "subject_code": "SA050300", "subject_code_description": "Ceramic arts" }, { "subject_code": "SA050200", "subject_code_description": "Art conservation" }, { "subject_code": "SA050000", "subject_code_description": "Visual arts" }, { "subject_code": "SA010500", "subject_code_description": "Arts education" }, { "subject_code": "SA010000", "subject_code_description": "Arts services" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PH030000", "population_served_description": "Substance abusers" }, { "population_served_code": "PH010700", "population_served_description": "People with other disabilities" }, { "population_served_code": "PH010500", "population_served_description": "People with intellectual disabilities" }, { "population_served_code": "PH010400", "population_served_description": "People with psychosocial disabilities" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG060100", "population_served_description": "Victims of crime and abuse" }, { "population_served_code": "PG060000", "population_served_description": "Victims and oppressed people" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG040000", "population_served_description": "Incarcerated people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD040400", "population_served_description": "Transitioning children" }, { "population_served_code": "PD040300", "population_served_description": "Foster and adoptive children" }, { "population_served_code": "PD040100", "population_served_description": "Orphans" }, { "population_served_code": "PD040000", "population_served_description": "Non-adult children" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PC050201", "population_served_description": "Young men" }, { "population_served_code": "PC050200", "population_served_description": "Men" }, { "population_served_code": "PC050100", "population_served_description": "Boys" }, { "population_served_code": "PC050000", "population_served_description": "Men and boys" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "F33", "ntee_code_description": "Group Home, Residential Treatment Facility - Mental Health Related" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 18297642.0, "total_expenses": 29248804.0, "total_assets": 4947842.0 }, "bmf_gross_receipts": 18297642.0, "bmf_assets": 4947842.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-03-09T10:33:00.0000000", "profile_last_modified": "2023-03-23T11:46:52.0000000", "dei_last_modified": "2023-03-23T00:00:00.0000000", "financials_last_modified": "2023-05-18T18:49:03.0000000", "last_modified": "2023-05-18T18:49:03.0000000" } }, { "organization": { "organization_id": "8351295", "ein": "91-2082980", "organization_name": "Jeffersonville Clark County NAACP Youth Council", "also_known_as": "Jeffersonville Youth & College Division", "group_exemption": "1531", "mission": "The mission of the NAACP Youth & College Division shall be to inform youth of the problems affecting African Americans and other racial and ethnic minorities; to advance the economic, education, social and political status of African Americans and other racial and ethnic minorities and their harmonious cooperation with other peoples; to stimulate an appreciation of the African Diaspora and other people of color’s contribution to civilization; and to develop an intelligent, effective youth leadership.", "website_url": "", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8133627&approved=True", "profile_level": "Silver", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/91-2082980", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Youth Advisor", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(812) 391-6174", "contact_title": "Advisor", "number_of_employees": "", "ruling_year": 1961 }, "properties": { "bmf_status": true, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "PO Box 1464", "address_line_2": "", "city": "Jeffersonville", "state": "IN", "zip": "47131", "msa": "IN - Louisville, KY-IN", "congressional_district": "District 9, IN", "county": "Clark, IN", "latitude": 38.3005, "longitude": -85.7416 }, "taxonomies": { "subject_codes": [ { "subject_code": "SR050000", "subject_code_description": "Diversity and intergroup relations" }, { "subject_code": "SR040200", "subject_code_description": "Ethnic and racial minority rights" }, { "subject_code": "SR040000", "subject_code_description": "Antidiscrimination" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SB091200", "subject_code_description": "Tutoring" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "R22", "ntee_code_description": "Minority Rights" } ], "subsection_code": { "subsection_code": "04", "subsection_code_description": "501(c)(4) Civic Leagues and Social Welfare Organizations" }, "foundation_code": { "foundation_code": "00", "foundation_code_description": "All organizations except 501(c)(3)" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-09-18T13:37:20.0000000", "profile_last_modified": "2022-09-18T13:37:20.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-15T12:27:00.0000000" } }, { "organization": { "organization_id": "9940672", "ein": "85-1067852", "organization_name": "Discover Your Pace Inc", "also_known_as": "Discover Your Pace | DYP", "group_exemption": "0000", "mission": "To uplift systemically oppressed intersectional communities by providing equitable access to innovative advisory programs that foster economic sustainability (Manage), self-efficacy (Advance), social intelligence (Balance), & charitable service (Impact).", "website_url": "www.discoveryourpace.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8099867&approved=True", "profile_level": "Gold", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/85-1067852", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2022-seal.svg", "leader_name": "<NAME> | Howard University (BBA) | Gates Millennium Scholar", "leader_title": "Managing Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Managing Director", "number_of_employees": "", "ruling_year": 2021 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": true, "revoked": true, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "20 Martin Ter", "address_line_2": "", "city": "Randolph", "state": "MA", "zip": "02368", "msa": "MA - Boston", "congressional_district": "District 7, MA", "county": "Norfolk, MA", "latitude": 42.1553, "longitude": -71.0469 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS060400", "subject_code_description": "Self-advocacy" }, { "subject_code": "SS060000", "subject_code_description": "Personal services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SR040000", "subject_code_description": "Antidiscrimination" }, { "subject_code": "SR020800", "subject_code_description": "Economic justice" }, { "subject_code": "SR020000", "subject_code_description": "Social rights" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SQ010000", "subject_code_description": "Community recreation" }, { "subject_code": "SQ000000", "subject_code_description": "Sports and recreation" }, { "subject_code": "SN050800", "subject_code_description": "Financial counseling" }, { "subject_code": "SN050000", "subject_code_description": "Financial services" }, { "subject_code": "SN020301", "subject_code_description": "Job counseling" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SK020000", "subject_code_description": "Leadership development" }, { "subject_code": "SK000000", "subject_code_description": "Public affairs" }, { "subject_code": "SD040000", "subject_code_description": "Nonprofits" }, { "subject_code": "SD030000", "subject_code_description": "Voluntarism" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090100", "subject_code_description": "Out-of-school learning" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB070200", "subject_code_description": "Continuing education" }, { "subject_code": "SB070101", "subject_code_description": "Adult literacy" }, { "subject_code": "SB070100", "subject_code_description": "Basic and remedial instruction" }, { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ120000", "population_served_description": "Activists" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ030000", "population_served_description": "Self-employed people" }, { "population_served_code": "PJ020000", "population_served_description": "Unemployed people" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PC050000", "population_served_description": "Men and boys" }, { "population_served_code": "PC040000", "population_served_description": "Women and girls" }, { "population_served_code": "PC010000", "population_served_description": "LGBTQ people" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P20", "ntee_code_description": "Human Service Organizations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-09-04T02:51:35.0000000", "profile_last_modified": "2022-09-04T03:34:19.0000000", "dei_last_modified": "2022-09-04T02:49:58.0000000", "financials_last_modified": "", "last_modified": "2022-09-09T13:27:18.0000000" } }, { "organization": { "organization_id": "9317638", "ein": "46-5061687", "organization_name": "Scholarship America Inc", "also_known_as": "Tioga Area Dollars for Scholars", "group_exemption": "1546", "mission": "Since its charter on March 31, 1992, Tioga Area Dollars for Scholars has been successful in awarding over $400,000 in scholarships towards the postsecondary education of Tioga High School graduates and alumni. The chapter is a nonprofit, community based organization that raises funds to provide scholarships for eligible community applicants. The goal is to involve the community in supporting local fund raising events for the purpose of raising needed funds.", "website_url": "https://tioga.dollarsforscholars.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2021, "profile_link": "https://www.guidestar.org/profile/46-5061687", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2021-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(701) 664-3368", "contact_title": "Clinic Manager/Foundation Director", "number_of_employees": "", "ruling_year": 1962 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "PO Box 925", "address_line_2": "", "city": "Tioga", "state": "ND", "zip": "58852", "msa": "", "congressional_district": "", "county": "Williams, ND", "latitude": 48.3728, "longitude": -102.9369 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN050103", "subject_code_description": "Community development finance" }, { "subject_code": "SN050100", "subject_code_description": "Development finance" }, { "subject_code": "SN050000", "subject_code_description": "Financial services" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SH050103", "subject_code_description": "Financial applications" }, { "subject_code": "SH050100", "subject_code_description": "Software applications" }, { "subject_code": "SH050000", "subject_code_description": "Information communications technology" }, { "subject_code": "SH000000", "subject_code_description": "Information and communications" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B82", "ntee_code_description": "Scholarships, Student Financial Aid, Awards" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2021-11-24T15:24:34.0000000", "profile_last_modified": "2021-11-24T15:24:34.0000000", "dei_last_modified": "2021-11-24T14:23:47.0000000", "financials_last_modified": "", "last_modified": "2022-09-09T13:27:18.0000000" } }, { "organization": { "organization_id": "7645026", "ein": "43-0669085", "organization_name": "Big Brothers Sisters of Eastern Missouri", "also_known_as": "Big Brothers Big Sisters of Eastern Missouri", "group_exemption": "0000", "mission": "Big Brothers Big Sisters of Eastern Missouri (BBBSEMO) partners with young people in their pursuit of meaningful, stable, and independent lives. Our overarching goal is to empower young people to succeed in school, graduate from high school (or achieve high school equivalency), and advance on post-secondary paths (Enroll in college/trade school, Enlist in the military, or obtain Employment). We envision young people will \"own their futures\" AND become independent, happy adults who obtain living-wage jobs by age 26.", "website_url": "www.bbbsemo.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8816465&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/43-0669085", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(314) 633-0032", "contact_title": "Senior Manager of Grants", "number_of_employees": "73", "ruling_year": 1942 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "501 N Grand Blvd Ste 100", "address_line_2": "", "city": "St Louis", "state": "MO", "zip": "63103", "msa": "MO - St. Louis, MO-IL", "congressional_district": "District 1, MO", "county": "Saint Louis City, MO", "latitude": 38.6381, "longitude": -90.2322 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050100", "subject_code_description": "Youth services" }, { "subject_code": "SS050300", "subject_code_description": "Youth mentoring" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PC050100", "population_served_description": "Boys" }, { "population_served_code": "PC050000", "population_served_description": "Men and boys" }, { "population_served_code": "PC040100", "population_served_description": "Girls" }, { "population_served_code": "PC040000", "population_served_description": "Women and girls" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P30", "ntee_code_description": "Children's and Youth Services" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 5973794.0, "total_expenses": 5451047.0, "total_assets": 21272231.0 }, "bmf_gross_receipts": 11544164.0, "bmf_assets": 26064688.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-14T13:49:32.0000000", "profile_last_modified": "2023-03-14T13:49:32.0000000", "dei_last_modified": "2023-03-14T12:10:11.0000000", "financials_last_modified": "2023-04-21T07:03:01.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "6916379", "ein": "13-3389060", "organization_name": "Bruce J. Heim Foundation", "also_known_as": "The Heim Foundation", "group_exemption": "0000", "mission": "The Bruce J. Heim Foundation was established in 1986 to provide financial assistance to causes which will help people, especially young individuals or small groups, who have demonstrated potential for excellence in an area of interest. The Foundation hopes that such assistance will allow the recipients to improve, develop and concentrate on their talents, thus providing additional impetus for future success. It also hopes to nurture a spirit of gratitude and reciprocity in the recipients that will stimulate them to support, and become involved in, similar philanthropic causes.", "website_url": "brucejheimfoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8797049&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-3389060", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "Mrs. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(504) 321-0040", "contact_title": "Executive Director", "number_of_employees": "", "ruling_year": 1988 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3525 N Causeway Blvd Ste 605", "address_line_2": "", "city": "Metairie", "state": "LA", "zip": "70002", "msa": "LA - New Orleans", "congressional_district": "District 1, LA", "county": "Jefferson, LA", "latitude": 30.0134, "longitude": -90.1546 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB100000", "subject_code_description": "Early childhood education" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB070200", "subject_code_description": "Continuing education" }, { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA070000", "subject_code_description": "Museums" }, { "subject_code": "SA060700", "subject_code_description": "Performing arts education" }, { "subject_code": "SA060300", "subject_code_description": "Music" }, { "subject_code": "SA060100", "subject_code_description": "Dance" }, { "subject_code": "SA060000", "subject_code_description": "Performing arts" }, { "subject_code": "SA010500", "subject_code_description": "Arts education" }, { "subject_code": "SA010000", "subject_code_description": "Arts services" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2022, "total_revenue": 369228.0, "total_expenses": 225070.0, "total_assets": 3596419.0 }, "bmf_gross_receipts": 1004849.0, "bmf_assets": 2517659.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-08T19:57:44.0000000", "profile_last_modified": "2023-03-08T19:57:44.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T09:02:02.0000000", "last_modified": "2023-06-23T09:02:02.0000000" } }, { "organization": { "organization_id": "8204919", "ein": "76-0680130", "organization_name": "Harris and Eliza Kempner Fund", "also_known_as": "", "group_exemption": "0000", "mission": "The mission of the Harris and Eliza Kempner Fund is to invest in the long-term success, sustainability, and well-being of Galveston and its residents.", "website_url": "http://www.kempnerfund.org/", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/76-0680130", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2001 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2228 Mechanic St Ste 220", "address_line_2": "", "city": "Galveston", "state": "TX", "zip": "77550", "msa": "TX - Galveston-Texas City", "congressional_district": "District 14, TX", "county": "Galveston, TX", "latitude": 29.3065, "longitude": -94.7933 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS090300", "subject_code_description": "Immigrant services" }, { "subject_code": "SS090000", "subject_code_description": "Special population support" }, { "subject_code": "SS070400", "subject_code_description": "Homeless shelters" }, { "subject_code": "SS070000", "subject_code_description": "Shelter and residential care" }, { "subject_code": "SS050800", "subject_code_description": "Community service for youth" }, { "subject_code": "SS050700", "subject_code_description": "Civics for youth" }, { "subject_code": "SS050303", "subject_code_description": "Youth peer mentoring" }, { "subject_code": "SS050301", "subject_code_description": "Adult and child mentoring" }, { "subject_code": "SS050300", "subject_code_description": "Youth mentoring" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS040700", "subject_code_description": "Parent education" }, { "subject_code": "SS040400", "subject_code_description": "Family counseling" }, { "subject_code": "SS040000", "subject_code_description": "Family services" }, { "subject_code": "SS030602", "subject_code_description": "Food delivery" }, { "subject_code": "SS030601", "subject_code_description": "Food banks" }, { "subject_code": "SS030600", "subject_code_description": "Food aid" }, { "subject_code": "SS030000", "subject_code_description": "Basic and emergency aid" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030100", "subject_code_description": "Community beautification" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN010000", "subject_code_description": "Sustainable development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SE120700", "subject_code_description": "Mental health counseling" }, { "subject_code": "SE120600", "subject_code_description": "Crisis intervention" }, { "subject_code": "SE120504", "subject_code_description": "Substance abuse treatment" }, { "subject_code": "SE120503", "subject_code_description": "Substance abuse prevention" }, { "subject_code": "SE120500", "subject_code_description": "Addiction services" }, { "subject_code": "SE120200", "subject_code_description": "Community mental health care" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE020000", "subject_code_description": "Health care access" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SD040000", "subject_code_description": "Nonprofits" }, { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SC060300", "subject_code_description": "Outdoor education" }, { "subject_code": "SC060200", "subject_code_description": "Nature education" }, { "subject_code": "SC060000", "subject_code_description": "Environmental education" }, { "subject_code": "SC030406", "subject_code_description": "Wetlands" }, { "subject_code": "SC030405", "subject_code_description": "Water conservation" }, { "subject_code": "SC030403", "subject_code_description": "Oceans and coastal waters" }, { "subject_code": "SC030400", "subject_code_description": "Water resources" }, { "subject_code": "SC030000", "subject_code_description": "Natural resources" }, { "subject_code": "SC020000", "subject_code_description": "Climate change" }, { "subject_code": "SC000000", "subject_code_description": "Environment" }, { "subject_code": "SB100000", "subject_code_description": "Early childhood education" }, { "subject_code": "SB090300", "subject_code_description": "Computer literacy" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA090300", "subject_code_description": "Historic preservation" }, { "subject_code": "SA090000", "subject_code_description": "Historical activities" }, { "subject_code": "SA010500", "subject_code_description": "Arts education" }, { "subject_code": "SA010200", "subject_code_description": "Artists' services" }, { "subject_code": "SA010000", "subject_code_description": "Arts services" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PG060000", "population_served_description": "Victims and oppressed people" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020200", "population_served_description": "Older adults" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T90", "ntee_code_description": "Named Trusts/Foundations N.E.C." } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 5826538.0, "total_expenses": 3198667.0, "total_assets": 66684854.0 }, "bmf_gross_receipts": 5826538.0, "bmf_assets": 49221567.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-12T17:20:29.0000000", "profile_last_modified": "2023-01-12T17:20:29.0000000", "dei_last_modified": "2023-01-12T16:12:21.0000000", "financials_last_modified": "2023-05-18T17:02:28.0000000", "last_modified": "2023-06-13T13:54:00.0000000" } } ] } ``` In the example above, `AND` operator logic is applied when two filters are used together. This example will return organizations who match college preparation `AND` young adults ``` { "filters": { "organization": { "subject_codes": ["SB090200,SB030400"] /*college preparation or secondary education*/ } } } ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 134, "time": "2023-08-29 18:33:40Z", "results_count": 9478, "page_count": 380, "errors": [], "hits": [ { "organization": { "organization_id": "6907953", "ein": "13-1740010", "organization_name": "New York Institute for Special Education", "also_known_as": "", "group_exemption": "0000", "mission": "The mission of The New York Institute for Special Education is to provide quality educational programs and support to the students and families in a safe, caring environment, to awaken and inspire student curiosity, lifelong learning, and fulfillment.", "website_url": "www.nyise.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9289744&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-1740010", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME> ", "leader_title": "Executive Director ", "contact_name": "Dr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(718) 519-7000", "contact_title": "Executive Director", "number_of_employees": "302", "ruling_year": 1942 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "999 Pelham Pkwy N", "address_line_2": "", "city": "Bronx", "state": "NY", "zip": "10469", "msa": "NY - New York, NY-NJ", "congressional_district": "District 14, NY", "county": "Bronx, NY", "latitude": 40.8581, "longitude": -73.8566 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB100000", "subject_code_description": "Early childhood education" }, { "subject_code": "SB030800", "subject_code_description": "Special needs education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030300", "subject_code_description": "Middle school education" }, { "subject_code": "SB030200", "subject_code_description": "Elementary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH010400", "population_served_description": "People with psychosocial disabilities" }, { "population_served_code": "PH010200", "population_served_description": "People with vision impairments" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PA010100", "population_served_description": "Infants and toddlers" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B28", "ntee_code_description": "Specialized Education Institutions/Schools for Visually or Hearing Impaired, Learning Disabled" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 45507452.0, "total_expenses": 29569914.0, "total_assets": 182971152.0 }, "bmf_gross_receipts": 75164891.0, "bmf_assets": 182971152.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-07-24T17:31:30.0000000", "profile_last_modified": "2023-07-24T17:31:30.0000000", "dei_last_modified": "2022-01-27T18:16:35.0000000", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-07-24T17:31:30.0000000" } }, { "organization": { "organization_id": "6864040", "ein": "06-0646786", "organization_name": "MISS PORTERS SCHOOL INC", "also_known_as": "", "group_exemption": "0000", "mission": "Miss Porter's School educates young women to become informed, bold, resourceful, and ethical global citizens. We expect our graduates to shape a changing world.", "website_url": "www.porters.org", "logo_url": "", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/06-0646786", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(860) 409-3620", "contact_title": "Chief Advancement Officer", "number_of_employees": "232", "ruling_year": 1943 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "60 Main St", "address_line_2": "", "city": "Farmington", "state": "CT", "zip": "06032", "msa": "CT - Hartford", "congressional_district": "District 5, CT", "county": "Hartford, CT", "latitude": 41.7224, "longitude": -72.8289 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PC040104", "population_served_description": "Adolescent girls" }, { "population_served_code": "PC040100", "population_served_description": "Girls" }, { "population_served_code": "PC040000", "population_served_description": "Women and girls" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 43634865.0, "total_expenses": 32812324.0, "total_assets": 215294054.0 }, "bmf_gross_receipts": 94556970.0, "bmf_assets": 215294054.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-05-23T08:56:41.0000000", "profile_last_modified": "2023-05-23T08:56:41.0000000", "dei_last_modified": "2023-05-23T00:00:00.0000000", "financials_last_modified": "2023-05-18T19:00:46.0000000", "last_modified": "2023-05-23T08:56:41.0000000" } }, { "organization": { "organization_id": "9644672", "ein": "36-4802935", "organization_name": "Project Lead the Way, Inc", "also_known_as": "PLTW", "group_exemption": "0000", "mission": "PROJECT LEAD THE WAY (PLTW) EMPOWERS STUDENTS TO THRIVE IN AN EVOLVING WORLD.", "website_url": "www.pltw.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9406183&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/36-4802935", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "Communications Team", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Communications", "number_of_employees": "274", "ruling_year": 2017 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "5939 Castle Creek Parkway North Dr", "address_line_2": "", "city": "Indianapolis", "state": "IN", "zip": "46250", "msa": "IN - Indianapolis", "congressional_district": "District 5, IN", "county": "Marion, IN", "latitude": 39.9157, "longitude": -86.0703 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB090300", "subject_code_description": "Computer literacy" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB031000", "subject_code_description": "STEM education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030300", "subject_code_description": "Middle school education" }, { "subject_code": "SB030200", "subject_code_description": "Elementary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B90", "ntee_code_description": "Educational Services and Schools - Other" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 65462690.0, "total_expenses": 57653861.0, "total_assets": 104347608.0 }, "bmf_gross_receipts": 116375267.0, "bmf_assets": 104347608.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-08-28T09:08:34.0000000", "profile_last_modified": "2023-08-28T09:08:34.0000000", "dei_last_modified": "2023-08-28T00:00:00.0000000", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-08-28T09:08:34.0000000" } }, { "organization": { "organization_id": "6906750", "ein": "13-1935349", "organization_name": "International College-Beirut Lebanon", "also_known_as": "International College", "group_exemption": "0000", "mission": "The Mission of IC is to empower learners to take initiative, think critically, and serve as role models in a global society. The curriculum aims for excellence at all levels and embraces the education of the whole person. Graduates of IC will have developed self-confidence, problem-solving, and decision-making abilities as well as self-discipline, social and environmental responsibility, and an awareness of and respect for the connected nature of our global community.", "website_url": "https://www.ic.edu.lb/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8850707&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-1935349", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(212) 529-3005 x3005", "contact_title": "Development Associate", "number_of_employees": "26", "ruling_year": 1934 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "305 E 47th St Fl 10", "address_line_2": "", "city": "New York City", "state": "NY", "zip": "10017", "msa": "NY - New York, NY-NJ", "congressional_district": "District 12, NY", "county": "New York, NY", "latitude": 40.753, "longitude": -73.9698 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB100000", "subject_code_description": "Early childhood education" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B20", "ntee_code_description": "Elementary, Secondary Ed" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 57077984.0, "total_expenses": 47545222.0, "total_assets": 181935809.0 }, "bmf_gross_receipts": 60946636.0, "bmf_assets": 181935809.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-22T17:12:44.0000000", "profile_last_modified": "2023-03-22T17:12:44.0000000", "dei_last_modified": "2020-04-01T14:49:52.0000000", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "8266381", "ein": "85-0325494", "organization_name": "Santa Fe Institute", "also_known_as": "SFI", "group_exemption": "0000", "mission": "The Santa Fe Institute is the world headquarters for complexity science, operated as an independent, not-for-profit research and education center located in Santa Fe, New Mexico.Our researchers endeavor to understand and unify the underlying, shared patterns in complex physical, biological, social, cultural, technological, and even possible astrobiological worlds. Our global research network of scholars spans borders, departments, and disciplines, unifying curious minds steeped in rigorous logical, mathematical, and computational reasoning. As we reveal the unseen mechanisms and processes that shape these evolving worlds, we seek to use this understanding to promote the well-being of humankind and of life on earth.", "website_url": "http://www.santafe.edu", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8843801&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-0325494", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and <NAME> Professor of Complex Systems", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(505) 946-3678", "contact_title": "", "number_of_employees": "89", "ruling_year": 1984 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1399 Hyde Park Rd", "address_line_2": "", "city": "Santa Fe", "state": "NM", "zip": "87501", "msa": "NM - Santa Fe", "congressional_district": "District 1, NM", "county": "Santa Fe, NM", "latitude": 35.6917, "longitude": -105.9393 }, "taxonomies": { "subject_codes": [ { "subject_code": "SG090000", "subject_code_description": "Interdisciplinary studies" }, { "subject_code": "SG000000", "subject_code_description": "Social sciences" }, { "subject_code": "SF000000", "subject_code_description": "Science" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "U05", "ntee_code_description": "Research Institutes and/or Public Policy Analysis" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 57773982.0, "total_expenses": 12028658.0, "total_assets": 95101684.0 }, "bmf_gross_receipts": 60995428.0, "bmf_assets": 95101684.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-03-20T15:57:17.0000000", "profile_last_modified": "2023-03-21T13:16:48.0000000", "dei_last_modified": "2023-03-20T00:00:00.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-05-18T17:01:04.0000000" } }, { "organization": { "organization_id": "8227800", "ein": "81-0622701", "organization_name": "Five Keys Schools and Programs", "also_known_as": "Five Keys", "group_exemption": "0000", "mission": "Through the use of social justice and restorative justice principles, Five Keys seeks to empower members of underserved communities and create meaningful opportunities to improve lives across the \"Five Keys\" of Education, Employment, Recovery, Family, and Community.Five Keys' vision is that all people have access to the resources they need to lead positive, productive, and self-determined lives. We commit ourselves to advancing belonging, inclusion, diversity, justice, and equity. Five Keys is a multi-faceted nonprofit organization that serves about 14,000 people annually in 20 counties throughout California. Programs are available at more than 80 neighborhood sites, 17 county jails, and 8 state prisons.", "website_url": "www.fivekeys.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9129910&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/81-0622701", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(415) 734-3310", "contact_title": "President & CEO", "number_of_employees": "1465", "ruling_year": 2004 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "70 Oak Grove St", "address_line_2": "", "city": "San Francisco", "state": "CA", "zip": "94107", "msa": "CA - San Francisco-Oakland", "congressional_district": "District 12, CA", "county": "San Francisco, CA", "latitude": 37.7771, "longitude": -122.4016 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS090200", "subject_code_description": "Homeless services" }, { "subject_code": "SS090000", "subject_code_description": "Special population support" }, { "subject_code": "SS070400", "subject_code_description": "Homeless shelters" }, { "subject_code": "SS070102", "subject_code_description": "Housing for the homeless" }, { "subject_code": "SS070100", "subject_code_description": "Supportive housing" }, { "subject_code": "SS070000", "subject_code_description": "Shelter and residential care" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SM010103", "subject_code_description": "Agricultural education" }, { "subject_code": "SM010100", "subject_code_description": "Farm viability" }, { "subject_code": "SM010000", "subject_code_description": "Agriculture" }, { "subject_code": "SM000000", "subject_code_description": "Agriculture, fishing and forestry" }, { "subject_code": "SJ050500", "subject_code_description": "Offender re-entry" }, { "subject_code": "SJ050400", "subject_code_description": "Services for offenders" }, { "subject_code": "SJ050300", "subject_code_description": "Rehabilitation of offenders" }, { "subject_code": "SJ050000", "subject_code_description": "Corrections and penology" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" }, { "subject_code": "SE120504", "subject_code_description": "Substance abuse treatment" }, { "subject_code": "SE120500", "subject_code_description": "Addiction services" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB040100", "subject_code_description": "Vocational secondary education" }, { "subject_code": "SB040000", "subject_code_description": "Vocational education" }, { "subject_code": "SB030600", "subject_code_description": "Charter school education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ050200", "population_served_description": "Teachers" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ020000", "population_served_description": "Unemployed people" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH030000", "population_served_description": "Substance abusers" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG060100", "population_served_description": "Victims of crime and abuse" }, { "population_served_code": "PG060000", "population_served_description": "Victims and oppressed people" }, { "population_served_code": "PG050200", "population_served_description": "Dropouts" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG040000", "population_served_description": "Incarcerated people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" } ], "ntee_codes": [ { "ntee_code": "B29", "ntee_code_description": "Charter Schools" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 97031582.0, "total_expenses": 89809955.0, "total_assets": 50545317.0 }, "bmf_gross_receipts": 97031582.0, "bmf_assets": 50545317.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-06-09T13:14:33.0000000", "profile_last_modified": "2023-06-09T13:14:33.0000000", "dei_last_modified": "2023-06-06T16:08:30.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-06-09T13:14:33.0000000" } }, { "organization": { "organization_id": "6822120", "ein": "04-2103564", "organization_name": "Governor Dummer Academy", "also_known_as": "d/b/a The Governors Academy", "group_exemption": "0000", "mission": "The Governor's Academy, founded in 1763 on New England coastal farmland, combines centuries of tradition with a dedication to educational innovation. Students flourish in a diverse community distinguished by enduring relationships with teachers and defined by a commitment to learning and a thoughtful balance of academics, athletics, arts and service to others. Academy graduates are life-long learners who embrace their civic duty and global responsibility.", "website_url": "www.thegovernorsacademy.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9118906&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/04-2103564", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Head of School", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(978) 499-3123", "contact_title": "Director of Finance", "number_of_employees": "295", "ruling_year": 1935 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1 Elm St", "address_line_2": "", "city": "Byfield", "state": "MA", "zip": "01922", "msa": "MA - Boston", "congressional_district": "District 6, MA", "county": "Essex, MA", "latitude": 42.7482, "longitude": -70.8984 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SC000000", "subject_code_description": "Environment" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 45263829.0, "total_expenses": 34659499.0, "total_assets": 163271740.0 }, "bmf_gross_receipts": 54256542.0, "bmf_assets": 163271740.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-06-08T12:11:26.0000000", "profile_last_modified": "2023-06-08T12:11:26.0000000", "dei_last_modified": "2023-06-08T11:42:12.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7855035", "ein": "56-0532314", "organization_name": "<NAME>", "also_known_as": "", "group_exemption": "0000", "mission": "Saint Mary's School in Raleigh, North Carolina, is an independent, college-preparatory, girls boarding and day high school dedicated to academic excellence and personal achievement for grades 9-12.", "website_url": "www.sms.edu", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9218467&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/56-0532314", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Head of School", "contact_name": "Mrs. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(919) 424-4007", "contact_title": "Senior Project Manager for Institutional Advancement", "number_of_employees": "198", "ruling_year": 1938 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "900 Hillsborough St", "address_line_2": "", "city": "Raleigh", "state": "NC", "zip": "27603", "msa": "NC - Raleigh-Durham-Chapel Hill", "congressional_district": "District 4, NC", "county": "Wake, NC", "latitude": 35.7815, "longitude": -78.6529 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PC040104", "population_served_description": "Adolescent girls" }, { "population_served_code": "PC040100", "population_served_description": "Girls" }, { "population_served_code": "PC040000", "population_served_description": "Women and girls" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 36030346.0, "total_expenses": 18824083.0, "total_assets": 84583083.0 }, "bmf_gross_receipts": 55394049.0, "bmf_assets": 84583083.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-26T14:57:54.0000000", "profile_last_modified": "2023-06-30T09:16:47.0000000", "dei_last_modified": "2023-01-26T13:11:36.0000000", "financials_last_modified": "2023-07-20T17:00:37.0000000", "last_modified": "2023-07-20T17:00:37.0000000" } }, { "organization": { "organization_id": "8357554", "ein": "91-2170962", "organization_name": "The Ceres Foundation Inc 43J-74D54", "also_known_as": "", "group_exemption": "0000", "mission": "The Ceres Foundation works to strengthen communities and improve the life outcomes of disadvantaged youth and their families. We do this through dynamic partnerships and long-term, capacity building investments in innovative nonprofits.", "website_url": "www.ceresgiving.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7918775&approved=True", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/91-2170962", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2002 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 578", "address_line_2": "", "city": "Groton", "state": "MA", "zip": "01450", "msa": "MA - Lowell, MA-NH", "congressional_district": "District 3, MA", "county": "Middlesex, MA", "latitude": 42.6091, "longitude": -71.552 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SB090500", "subject_code_description": "Student retention" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090100", "subject_code_description": "Out-of-school learning" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB050300", "subject_code_description": "University education" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050100", "subject_code_description": "Community college education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB040000", "subject_code_description": "Vocational education" }, { "subject_code": "SB031000", "subject_code_description": "STEM education" }, { "subject_code": "SB030300", "subject_code_description": "Middle school education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" } ], "ntee_codes": [ { "ntee_code": "T20", "ntee_code_description": "Private Grantmaking Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 84238191.0, "total_expenses": 2631045.0, "total_assets": 122977549.0 }, "bmf_gross_receipts": 176651303.0, "bmf_assets": 114461876.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-07-01T09:07:48.0000000", "profile_last_modified": "2022-07-01T09:09:14.0000000", "dei_last_modified": "2022-07-01T09:07:29.0000000", "financials_last_modified": "2023-05-18T15:30:05.0000000", "last_modified": "2023-05-18T15:30:05.0000000" } }, { "organization": { "organization_id": "7522621", "ein": "38-1359513", "organization_name": "The Edison Institute, Inc. dba The Henry Ford", "also_known_as": "The Henry Ford", "group_exemption": "0000", "mission": "The Edison Institute does business as \"The Henry Ford.\"  Its mission is to provide unique educational experiences based on authentic objects, stories and lives from America's traditions of ingenuity, resourcefulness, and innovation. Its purpose is to inspire people to learn from these traditions to help shape a better future.", "website_url": "http://www.thehenryford.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8579218&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/38-1359513", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(313) 982-6113", "contact_title": "Special Assistant the President and Senior Director, External Relations", "number_of_employees": "1244", "ruling_year": 1945 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "20900 Oakwood Blvd", "address_line_2": "", "city": "Dearborn", "state": "MI", "zip": "48124", "msa": "MI - Detroit", "congressional_district": "District 12, MI", "county": "Wayne, MI", "latitude": 42.3001, "longitude": -83.233 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030600", "subject_code_description": "Charter school education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA070800", "subject_code_description": "Science museums" }, { "subject_code": "SA070400", "subject_code_description": "History museums" }, { "subject_code": "SA070000", "subject_code_description": "Museums" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "A54", "ntee_code_description": "History Museums" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 88893387.0, "total_expenses": 63176100.0, "total_assets": 598342638.0 }, "bmf_gross_receipts": 138692689.0, "bmf_assets": 598342638.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-01-24T15:56:39.0000000", "profile_last_modified": "2023-01-24T15:56:39.0000000", "dei_last_modified": "2023-01-20T00:00:00.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-05-18T18:57:25.0000000" } }, { "organization": { "organization_id": "7490987", "ein": "36-4241970", "organization_name": "Noble Network of Charter Schools", "also_known_as": "Noble Network of Charter Schools", "group_exemption": "0000", "mission": "Noble will ensure that all students have equitable and positive school experiences that equip them to complete college and lead choice-filled lives.", "website_url": "http://nobleschools.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8729499&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/36-4241970", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(312) 521-5287", "contact_title": "", "number_of_employees": "2101", "ruling_year": 1999 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1 N State St Fl 15", "address_line_2": "", "city": "Chicago", "state": "IL", "zip": "60602", "msa": "IL - Chicago", "congressional_district": "District 7, IL", "county": "Cook, IL", "latitude": 41.8826, "longitude": -87.6279 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB080100", "subject_code_description": "Alumni relations" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 227971902.0, "total_expenses": 228530056.0, "total_assets": 237808950.0 }, "bmf_gross_receipts": 245139665.0, "bmf_assets": 237808950.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-02-23T13:37:32.0000000", "profile_last_modified": "2023-02-23T13:37:32.0000000", "dei_last_modified": "2022-04-22T15:58:03.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-05-18T17:01:04.0000000" } }, { "organization": { "organization_id": "7042600", "ein": "20-5010766", "organization_name": "KIPP Public Schools Northern California", "also_known_as": "KIPP Public Schools Northern California", "group_exemption": "0000", "mission": "Together with families and communities, KIPP Public Schools Northern California creates joyful, academically excellent schools that prepare students with the skills and confidence to pursue the paths they choose - college, career and beyond - so they can lead fulfilling lives and create a more just world. =", "website_url": "https://kippnorcal.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9014087&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/20-5010766", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(510) 917-8940", "contact_title": "Associate Director of Institutional Giving", "number_of_employees": "1185", "ruling_year": 2006 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1000 Broadway Ste 460", "address_line_2": "", "city": "Oakland", "state": "CA", "zip": "94607", "msa": "CA - Oakland", "congressional_district": "District 13, CA", "county": "Alameda, CA", "latitude": 37.8065, "longitude": -122.2848 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB100000", "subject_code_description": "Early childhood education" }, { "subject_code": "SB091100", "subject_code_description": "Reading promotion" }, { "subject_code": "SB091000", "subject_code_description": "Parent-teacher involvement" }, { "subject_code": "SB090500", "subject_code_description": "Student retention" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB020000", "subject_code_description": "Educational management" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 135604924.0, "total_expenses": 110609216.0, "total_assets": 198161708.0 }, "bmf_gross_receipts": 135604924.0, "bmf_assets": 198161708.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-12T14:35:08.0000000", "profile_last_modified": "2023-05-12T15:06:39.0000000", "dei_last_modified": "2023-05-12T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7102257", "ein": "23-1352647", "organization_name": "The Hill School", "also_known_as": "", "group_exemption": "0000", "mission": "The Hill School prepares students from across the United States and around the world for excellence in school, college, careers, and life. The Hill School combines a challenging liberal arts curriculum with clear moral direction and leadership training in a structured residential community. Dedicated to the development of the minds, bodies, and souls of all Hill students, the School professes not only to describe the world in which they live but also to prescribe the best ways to live. The Hill School is committed to inculcating fundamental traditions while developing the practical skills and core knowledge on which further learning must be based, then to leading students to a global perspective on the world and their places in it.", "website_url": "www.thehill.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9094364&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/23-1352647", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Headmaster", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Assistant Treasurer", "number_of_employees": "358", "ruling_year": 1938 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "860 Beech St", "address_line_2": "", "city": "Pottstown", "state": "PA", "zip": "19464", "msa": "PA - Philadelphia, PA-NJ", "congressional_district": "District 4, PA", "county": "Montgomery, PA", "latitude": 40.2472, "longitude": -75.6309 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PC050104", "population_served_description": "Adolescent boys" }, { "population_served_code": "PC050100", "population_served_description": "Boys" }, { "population_served_code": "PC050000", "population_served_description": "Men and boys" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 62962335.0, "total_expenses": 51587225.0, "total_assets": 320010649.0 }, "bmf_gross_receipts": 83044355.0, "bmf_assets": 320010649.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-06-07T15:19:43.0000000", "profile_last_modified": "2023-06-07T15:19:43.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-06-23T11:00:41.0000000" } }, { "organization": { "organization_id": "7198469", "ein": "23-7243247", "organization_name": "BLAKE SCHOOL", "also_known_as": "The Blake School", "group_exemption": "0000", "mission": "The Blake School provides students with an excellent, academically challenging education in a diverse and supportive community committed to a common set of values. Students are expected to participate in an integrated program of academic, artistic and athletic activities in preparation for college, lifelong learning, community service and lives as responsible world citizens.", "website_url": "www.blakeschool.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/23-7243247", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Head of School", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(952) 988-3459", "contact_title": "Director of Finance", "number_of_employees": "671", "ruling_year": 1973 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "110 Blake Rd S", "address_line_2": "", "city": "Hopkins", "state": "MN", "zip": "55343", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "District 5, MN", "county": "Hennepin, MN", "latitude": 44.9241, "longitude": -93.3858 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B20", "ntee_code_description": "Elementary, Secondary Ed" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 58825092.0, "total_expenses": 57649865.0, "total_assets": 202228265.0 }, "bmf_gross_receipts": 97749450.0, "bmf_assets": 202228265.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-06T09:26:18.0000000", "profile_last_modified": "2023-02-06T09:28:34.0000000", "dei_last_modified": "2021-05-05T15:21:45.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "6926840", "ein": "13-3850158", "organization_name": "TNTP, Inc.", "also_known_as": "TNTP", "group_exemption": "0000", "mission": "Since 1997, TNTP has worked side-by-side with teachers, school leaders, and school system leaders across the United States to ensure students have access to great teaching, rigorous academic content, and supportive environments that help them succeed. We offer innovative ideas and practical solutions at every level of the education system to improve students’ daily experiences—especially for those who have historically been denied access to educational opportunity. We envision a just and equitable education system that supports the full identity and potential of every young person, and our mission is to achieve justice in education by providing every K-12 student with equitable opportunities that lead to pathways for economic and social mobility.", "website_url": "http://tntp.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9289564&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-3850158", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "Dr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(718) 233-2800", "contact_title": "Chief Executive Officer", "number_of_employees": "1045", "ruling_year": 1995 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "500 Fashion Ave Fl 8", "address_line_2": "", "city": "New York City", "state": "NY", "zip": "10018", "msa": "NY - New York, NY-NJ", "congressional_district": "District 10, NY", "county": "New York, NY", "latitude": 40.7529, "longitude": -73.9892 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB060500", "subject_code_description": "Teacher education" }, { "subject_code": "SB060000", "subject_code_description": "Graduate and professional education" }, { "subject_code": "SB031000", "subject_code_description": "STEM education" }, { "subject_code": "SB030800", "subject_code_description": "Special needs education" }, { "subject_code": "SB030500", "subject_code_description": "Bilingual education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030300", "subject_code_description": "Middle school education" }, { "subject_code": "SB030200", "subject_code_description": "Elementary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB020000", "subject_code_description": "Educational management" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050200", "population_served_description": "Teachers" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B02", "ntee_code_description": "Management & Technical Assistance" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 144637728.0, "total_expenses": 127020746.0, "total_assets": 74584093.0 }, "bmf_gross_receipts": 144637728.0, "bmf_assets": 74584093.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-07-24T16:55:56.0000000", "profile_last_modified": "2023-07-24T16:55:56.0000000", "dei_last_modified": "2023-07-24T00:00:00.0000000", "financials_last_modified": "2023-05-18T18:49:03.0000000", "last_modified": "2023-07-24T16:55:56.0000000" } }, { "organization": { "organization_id": "6878185", "ein": "06-1576405", "organization_name": "EL Education, Inc.", "also_known_as": "EL Education", "group_exemption": "0000", "mission": "EL Education is a national nonprofit that partners with educators to transform K-12 schools and districts into hubs of equitable opportunity. Our mission is to create classrooms where teachers can fulfill their highest aspirations, and students achieve more than they think possible, becoming active contributors to building a better world.", "website_url": "www.eleducation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9336240&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/06-1576405", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(212) 239-4455", "contact_title": "Managing Director of Development", "number_of_employees": "157", "ruling_year": 2000 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "247 W 35th St Fl 8", "address_line_2": "", "city": "New York City", "state": "NY", "zip": "10001", "msa": "NY - New York, NY-NJ", "congressional_district": "District 10, NY", "county": "New York, NY", "latitude": 40.7522, "longitude": -73.9915 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB091100", "subject_code_description": "Reading promotion" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB060500", "subject_code_description": "Teacher education" }, { "subject_code": "SB060000", "subject_code_description": "Graduate and professional education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B20", "ntee_code_description": "Elementary, Secondary Ed" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 41458493.0, "total_expenses": 33337644.0, "total_assets": 36539179.0 }, "bmf_gross_receipts": 41526166.0, "bmf_assets": 36539179.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-03T07:20:55.0000000", "profile_last_modified": "2023-08-09T12:15:53.0000000", "dei_last_modified": "2023-08-09T00:00:00.0000000", "financials_last_modified": "2023-08-24T13:00:37.0000000", "last_modified": "2023-08-24T13:00:37.0000000" } }, { "organization": { "organization_id": "7633601", "ein": "42-1495980", "organization_name": "Community Foundation of Greater Muscatine", "also_known_as": "Community Foundation of Greater Muscatine", "group_exemption": "0000", "mission": "The Community Foundation of Greater Muscatine actively works to improve the quality of life in Muscatine County through philanthropy.", "website_url": "https://www.muscatinecommunityfoundation.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9211796&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/42-1495980", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(563) 571-5430", "contact_title": "Executive Director", "number_of_employees": "14", "ruling_year": 2000 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "215 W Mississippi Dr", "address_line_2": "", "city": "Muscatine", "state": "IA", "zip": "52761", "msa": "", "congressional_district": "District 2, IA", "county": "Muscatine, IA", "latitude": 41.4335, "longitude": -91.0547 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T31", "ntee_code_description": "Community Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 10914284.0, "total_expenses": 3458420.0, "total_assets": 66591017.0 }, "bmf_gross_receipts": 30278107.0, "bmf_assets": 66591017.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-06-28T15:51:28.0000000", "profile_last_modified": "2023-06-28T15:51:28.0000000", "dei_last_modified": "2020-06-24T14:40:16.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-06-28T15:51:28.0000000" } }, { "organization": { "organization_id": "8549908", "ein": "20-5470086", "organization_name": "Colorado Early Colleges", "also_known_as": "Colorado Early Colleges", "group_exemption": "0000", "mission": "All students, regardless of background or skill level, will have the opportunity to pursue a growth mindset that will allow them to achieve mastery and to demonstrate that they can succeed in school, in college, and in their chosen career.No exceptions. No excuses.", "website_url": "www.coloradoearlycolleges.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8788585&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/20-5470086", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Administrator", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(970) 377-0044", "contact_title": "Director of Philanthropy and Strategic Partnerships", "number_of_employees": "577", "ruling_year": 2007 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "4424 Innovation Dr", "address_line_2": "", "city": "Fort Collins", "state": "CO", "zip": "80525", "msa": "CO - Fort Collins-Loveland", "congressional_district": "District 2, CO", "county": "Larimer, CO", "latitude": 40.5251, "longitude": -105.0461 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050600", "subject_code_description": "Economics for youth" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN020301", "subject_code_description": "Job counseling" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB030600", "subject_code_description": "Charter school education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B29", "ntee_code_description": "Charter Schools" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 50408994.0, "total_expenses": 45602287.0, "total_assets": 30394080.0 }, "bmf_gross_receipts": 50408994.0, "bmf_assets": 30394080.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-07T12:46:23.0000000", "profile_last_modified": "2023-03-07T12:46:23.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-06-23T11:00:41.0000000" } }, { "organization": { "organization_id": "8423163", "ein": "94-3311088", "organization_name": "Aspire Public Schools", "also_known_as": "Aspire Public Schools Foundation", "group_exemption": "0000", "mission": "Aspire’s Mission:Provide a rigorous, joyful academic experience that cultivates our scholars’ skills, talents, and gifts, such that they may pursue and persist in college or any post-secondary pathway that is authentic to their identities;Promote inclusivity and disrupt systems that have historically oppressed marginalized communities, including Black, Latino/a/x, Indigenous, and People of Color; andNurture our scholars’ pride in their abilities, identities, and communities.", "website_url": "http://www.aspirepublicschools.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8706357&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/94-3311088", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(510) 434-5500", "contact_title": "Director of Development", "number_of_employees": "2609", "ruling_year": 1999 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1001 22nd Ave Ste 100", "address_line_2": "", "city": "Oakland", "state": "CA", "zip": "94606", "msa": "CA - Oakland", "congressional_district": "District 13, CA", "county": "Alameda, CA", "latitude": 37.7973, "longitude": -122.2423 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030600", "subject_code_description": "Charter school education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE050000", "population_served_description": "People of Latin American descent" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B20", "ntee_code_description": "Elementary, Secondary Ed" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 233476749.0, "total_expenses": 211117883.0, "total_assets": 207841845.0 }, "bmf_gross_receipts": 238208597.0, "bmf_assets": 207841845.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-02-17T13:17:44.0000000", "profile_last_modified": "2023-02-17T13:17:44.0000000", "dei_last_modified": "2021-05-07T11:39:43.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-05-18T17:01:04.0000000" } }, { "organization": { "organization_id": "6798845", "ein": "02-0223338", "organization_name": "Pinkerton Academy", "also_known_as": "", "group_exemption": "0000", "mission": "Mission: Rooted in a community of courtesy, respect, and responsibility, Pinkerton Academy seeks to provide a safe and welcoming environment which prepares all students for success in a changing world.", "website_url": "www.pinkertonacademy.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7569563&approved=True", "profile_level": "Silver", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/02-0223338", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Headmaster", "contact_name": "Mrs <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(603) 437-5200 x1102", "contact_title": "Director of Communications", "number_of_employees": "651", "ruling_year": 1941 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "19 N Main St", "address_line_2": "", "city": "Derry", "state": "NH", "zip": "03038", "msa": "NH - Lawrence-Haverhill, MA-NH", "congressional_district": "District 1, NH", "county": "Rockingham, NH", "latitude": 42.8944, "longitude": -71.3136 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 57395711.0, "total_expenses": 51568558.0, "total_assets": 86428214.0 }, "bmf_gross_receipts": 74314060.0, "bmf_assets": 86428214.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-02-22T13:45:35.0000000", "profile_last_modified": "2022-02-22T13:45:35.0000000", "dei_last_modified": "", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-05-18T15:24:48.0000000" } }, { "organization": { "organization_id": "7835130", "ein": "55-0806673", "organization_name": "Bright Star Schools", "also_known_as": "Bright Star Schools", "group_exemption": "0000", "mission": "Our mission is to provide holistic, inclusive support for all students to achieve academic excellence and grow their unique talents so that they find joy and fulfillment in higher education, career, and life.", "website_url": "www.brightstarschools.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8391340&approved=True", "profile_level": "Silver", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/55-0806673", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(703) 795-9664", "contact_title": "Development Manager", "number_of_employees": "590", "ruling_year": 2004 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "5101 Santa Monica Blvd Ste 8", "address_line_2": "Pmb 93,", "city": "Los Angeles", "state": "CA", "zip": "90029", "msa": "CA - Los Angeles-Long Beach", "congressional_district": "District 28, CA", "county": "Los Angeles, CA", "latitude": 34.0908, "longitude": -118.3005 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030600", "subject_code_description": "Charter school education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B20", "ntee_code_description": "Elementary, Secondary Ed" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 70636057.0, "total_expenses": 61975077.0, "total_assets": 111091804.0 }, "bmf_gross_receipts": 70636057.0, "bmf_assets": 111091804.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-12-02T13:27:14.0000000", "profile_last_modified": "2022-12-02T13:28:42.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "6882375", "ein": "11-1630821", "organization_name": "Polytechnic Preparatory Country Day School", "also_known_as": "Poly Prep", "group_exemption": "0000", "mission": "College preparatory day school that continues to honor the mission of the school's founders, providingan outstanding academic program and a strong, supportive community for the city's brightest and most promising young men and women.", "website_url": "www.polyprep.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/11-1630821", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Head of School", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(718) 836-9800", "contact_title": "Headmaster", "number_of_employees": "687", "ruling_year": 1946 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "9216 7th Ave", "address_line_2": "", "city": "Brooklyn", "state": "NY", "zip": "11228", "msa": "NY - New York, NY-NJ", "congressional_district": "District 11, NY", "county": "Kings, NY", "latitude": 40.6143, "longitude": -74.0229 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B20", "ntee_code_description": "Elementary, Secondary Ed" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 76376518.0, "total_expenses": 67714731.0, "total_assets": 174200532.0 }, "bmf_gross_receipts": 88361288.0, "bmf_assets": 174200532.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T08:06:05.0000000", "profile_last_modified": "2022-11-03T08:06:05.0000000", "dei_last_modified": "2022-11-03T08:06:07.0000000", "financials_last_modified": "2023-05-18T18:49:03.0000000", "last_modified": "2023-05-18T18:49:03.0000000" } }, { "organization": { "organization_id": "6822725", "ein": "04-2105855", "organization_name": "WORCESTER ACADEMY", "also_known_as": "", "group_exemption": "0000", "mission": "Founded in 1834, Worcester Academy is a day boarding school for grades 6-12 and post-graduates. The Academy mission is to instill in students the desire to learn throughout life, to engage passionately with the world around them, and to be honorable persons of strong and resourceful character. Worcester Academy's Core Values—Honor, Respect, Community, Personal Growth, and Challenge—are essential to its mission and are a testimony to its beliefs and commitments. The Academy motto is \"Achieve the Honorable.\"", "website_url": "www.worcesteracademy.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/04-2105855", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Head of School", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(508) 754-5302 x135", "contact_title": "", "number_of_employees": "265", "ruling_year": 1935 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "81 Providence St", "address_line_2": "", "city": "Worcester", "state": "MA", "zip": "01604", "msa": "MA - Worcester", "congressional_district": "District 2, MA", "county": "Worcester, MA", "latitude": 42.2534, "longitude": -71.7927 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030300", "subject_code_description": "Middle school education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B20", "ntee_code_description": "Elementary, Secondary Ed" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 71283222.0, "total_expenses": 32353683.0, "total_assets": 144370971.0 }, "bmf_gross_receipts": 79735971.0, "bmf_assets": 144370971.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-05-03T09:22:53.0000000", "profile_last_modified": "2022-05-03T09:22:53.0000000", "dei_last_modified": "2022-05-02T11:57:46.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "8581836", "ein": "92-0184898", "organization_name": "Palisades Charter High School", "also_known_as": "", "group_exemption": "0000", "mission": "PALISADES CHARTER HIGH SCHOOL WILL EMPOWER OUR DIVERSE STUDENT POPULATION TO MAKE POSITIVE CONTRIBUTIONS TO THE GLOBAL COMMUNITY BY DEDICATING OUR RESOURCES TO ENSURE EDUCATIONAL EXCELLENCE, CIVIC RESPONSIBILTY, AND PERSONAL GROWTH.", "website_url": "www.palihigh.org", "logo_url": "", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/92-0184898", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director/Principal", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(310) 230-7272", "contact_title": "Director of Development", "number_of_employees": "371", "ruling_year": 2007 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "15777 Bowdoin St", "address_line_2": "", "city": "Pacific Palisades", "state": "CA", "zip": "90272", "msa": "CA - Los Angeles-Long Beach", "congressional_district": "", "county": "Los Angeles, CA", "latitude": 34.0469, "longitude": -118.5318 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030600", "subject_code_description": "Charter school education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PE070000", "population_served_description": "Multiracial people" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 41146615.0, "total_expenses": 39736198.0, "total_assets": 27090937.0 }, "bmf_gross_receipts": 41576797.0, "bmf_assets": 27090937.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-06-26T17:44:44.0000000", "profile_last_modified": "2023-06-26T17:44:44.0000000", "dei_last_modified": "2022-06-01T14:13:06.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-26T17:44:44.0000000" } }, { "organization": { "organization_id": "7376479", "ein": "33-0542733", "organization_name": "The High Desert Partnership In Academic Excellence Foundation, Inc.", "also_known_as": "Lewis Center for Educational Research", "group_exemption": "0000", "mission": "The mission of the Lewis Center for Educational Research is to ensure our schools and programs prepare students for success in a global society through data driven, innovative, and research proven practices in a safe and inclusive culture.", "website_url": "www.lewiscenter.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9084715&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/33-0542733", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President/CEO", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(760) 946-5414 x201", "contact_title": "Executive Assistant", "number_of_employees": "356", "ruling_year": 1993 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "Lewis Center For Educational Research 17500 Mana Rd", "address_line_2": "", "city": "Apple Valley", "state": "CA", "zip": "92307", "msa": "CA - Riverside-San Bernardino-Ontario", "congressional_district": "District 8, CA", "county": "San Bernardino, CA", "latitude": 34.5362, "longitude": -117.1963 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030600", "subject_code_description": "Charter school education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030200", "subject_code_description": "Elementary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB020000", "subject_code_description": "Educational management" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B24", "ntee_code_description": "Primary/Elementary Schools" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 41620811.0, "total_expenses": 32024885.0, "total_assets": 138617610.0 }, "bmf_gross_receipts": 41637556.0, "bmf_assets": 138617610.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-06-06T11:31:26.0000000", "profile_last_modified": "2023-06-06T11:31:26.0000000", "dei_last_modified": "2023-02-27T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } } ] } ``` In the example above, `OR` operator logic is applied within the same filter. This example will return organizations who match college preparation `OR` secondary education ``` { "filters": { "organization": { "subject_codes":["SB090200,SB030400"], /*college preparation or secondary education*/ "population_served_codes":["PA020100"] /*young adults*/ } } } ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 40, "time": "2023-08-29 18:34:06Z", "results_count": 234, "page_count": 10, "errors": [], "hits": [ { "organization": { "organization_id": "7042600", "ein": "20-5010766", "organization_name": "KIPP Public Schools Northern California", "also_known_as": "KIPP Public Schools Northern California", "group_exemption": "0000", "mission": "Together with families and communities, KIPP Public Schools Northern California creates joyful, academically excellent schools that prepare students with the skills and confidence to pursue the paths they choose - college, career and beyond - so they can lead fulfilling lives and create a more just world. =", "website_url": "https://kippnorcal.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9014087&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/20-5010766", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(510) 917-8940", "contact_title": "Associate Director of Institutional Giving", "number_of_employees": "1185", "ruling_year": 2006 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1000 Broadway Ste 460", "address_line_2": "", "city": "Oakland", "state": "CA", "zip": "94607", "msa": "CA - Oakland", "congressional_district": "District 13, CA", "county": "Alameda, CA", "latitude": 37.8065, "longitude": -122.2848 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB100000", "subject_code_description": "Early childhood education" }, { "subject_code": "SB091100", "subject_code_description": "Reading promotion" }, { "subject_code": "SB091000", "subject_code_description": "Parent-teacher involvement" }, { "subject_code": "SB090500", "subject_code_description": "Student retention" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB020000", "subject_code_description": "Educational management" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 135604924.0, "total_expenses": 110609216.0, "total_assets": 198161708.0 }, "bmf_gross_receipts": 135604924.0, "bmf_assets": 198161708.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-12T14:35:08.0000000", "profile_last_modified": "2023-05-12T15:06:39.0000000", "dei_last_modified": "2023-05-12T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "6822725", "ein": "04-2105855", "organization_name": "WORCESTER ACADEMY", "also_known_as": "", "group_exemption": "0000", "mission": "Founded in 1834, Worcester Academy is a day boarding school for grades 6-12 and post-graduates. The Academy mission is to instill in students the desire to learn throughout life, to engage passionately with the world around them, and to be honorable persons of strong and resourceful character. Worcester Academy's Core Values—Honor, Respect, Community, Personal Growth, and Challenge—are essential to its mission and are a testimony to its beliefs and commitments. The Academy motto is \"Achieve the Honorable.\"", "website_url": "www.worcesteracademy.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/04-2105855", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Head of School", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(508) 754-5302 x135", "contact_title": "", "number_of_employees": "265", "ruling_year": 1935 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "81 Providence St", "address_line_2": "", "city": "Worcester", "state": "MA", "zip": "01604", "msa": "MA - Worcester", "congressional_district": "District 2, MA", "county": "Worcester, MA", "latitude": 42.2534, "longitude": -71.7927 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030300", "subject_code_description": "Middle school education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B20", "ntee_code_description": "Elementary, Secondary Ed" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 71283222.0, "total_expenses": 32353683.0, "total_assets": 144370971.0 }, "bmf_gross_receipts": 79735971.0, "bmf_assets": 144370971.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-05-03T09:22:53.0000000", "profile_last_modified": "2022-05-03T09:22:53.0000000", "dei_last_modified": "2022-05-02T11:57:46.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "8415696", "ein": "94-3187806", "organization_name": "Eastside College Preparatory School, Inc.", "also_known_as": "Eastside College Preparatory School", "group_exemption": "0000", "mission": "At Eastside College Preparatory School we are committed to opening new doors for students historically underrepresented in higher education. Our challenging and engaging curriculum enables students to discover their intellectual strengths, sharpen their academic skills, and embrace new opportunities in a culture of learning that supports the potential of every student to enter and succeed in a four-year college and beyond. Eastside students who are the first in their families to go to college create a ripple effect, changing their own lives, the lives of their families, and the life of their community.", "website_url": "www.eastside.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8293379&approved=True", "profile_level": "Platinum", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/94-3187806", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Principal", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(650) 688-0850 x144", "contact_title": "Director of Development", "number_of_employees": "86", "ruling_year": 1999 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1041 Myrtle St", "address_line_2": "", "city": "East Palo Alto", "state": "CA", "zip": "94303", "msa": "CA - San Francisco-Oakland", "congressional_district": "District 14, CA", "county": "San Mateo, CA", "latitude": 37.4633, "longitude": -122.1329 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 19756515.0, "total_expenses": 11412948.0, "total_assets": 181036317.0 }, "bmf_gross_receipts": 70903095.0, "bmf_assets": 181036317.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T18:24:11.0000000", "profile_last_modified": "2022-11-03T18:24:11.0000000", "dei_last_modified": "2022-11-03T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7410174", "ein": "34-1580038", "organization_name": "National Inventors Hall of Fame, Inc.", "also_known_as": "", "group_exemption": "0000", "mission": "The mission of NIHF is to be a catalyst for change through recognizing inventors and invention, promoting creativity, and advancing the spirit of innovation and entrepreneurship.", "website_url": "www.invent.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8740282&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/34-1580038", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "249", "ruling_year": 1988 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3701 Highland Park NW", "address_line_2": "", "city": "North Canton", "state": "OH", "zip": "44720", "msa": "OH - Canton-Massillon", "congressional_district": "District 16, OH", "county": "Stark, OH", "latitude": 40.9173, "longitude": -81.4132 }, "taxonomies": { "subject_codes": [ { "subject_code": "SA070800", "subject_code_description": "Science museums" }, { "subject_code": "SA070000", "subject_code_description": "Museums" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" }, { "subject_code": "SB070200", "subject_code_description": "Continuing education" }, { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB031000", "subject_code_description": "STEM education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030300", "subject_code_description": "Middle school education" }, { "subject_code": "SB030200", "subject_code_description": "Elementary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "A57", "ntee_code_description": "Science & Technology Museum" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 39073824.0, "total_expenses": 29398870.0, "total_assets": 44107247.0 }, "bmf_gross_receipts": 46582594.0, "bmf_assets": 52514312.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-02-24T06:31:30.0000000", "profile_last_modified": "2023-02-24T06:31:30.0000000", "dei_last_modified": "2022-08-26T00:00:00.0000000", "financials_last_modified": "2023-05-10T20:45:21.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "7606737", "ein": "41-1968798", "organization_name": "College Possible", "also_known_as": "", "group_exemption": "0000", "mission": "College Possible is making college admission and success possible for students from low-income backgrounds through an intensive curriculum of coaching and support.", "website_url": "www.CollegePossible.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8640923&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/41-1968798", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(651) 288-9455", "contact_title": "CEO", "number_of_employees": "813", "ruling_year": 2000 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "755 Prior Ave N Ste 210", "address_line_2": "", "city": "St Paul", "state": "MN", "zip": "55104", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "District 4, MN", "county": "Ramsey, MN", "latitude": 44.9656, "longitude": -93.1823 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 31201183.0, "total_expenses": 27834304.0, "total_assets": 23283310.0 }, "bmf_gross_receipts": 31323954.0, "bmf_assets": 23283310.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-02-03T14:31:21.0000000", "profile_last_modified": "2023-02-03T14:31:21.0000000", "dei_last_modified": "2023-01-27T00:00:00.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-05-18T17:01:04.0000000" } }, { "organization": { "organization_id": "8268022", "ein": "85-0297355", "organization_name": "ARMAND HAMMER UNITED WORLD COLLEGE OF THE AMERICAN WEST", "also_known_as": "UWC-USA", "group_exemption": "0000", "mission": "UWC makes education a force to unite people, nations, and cultures for peace and a sustainable future.The school has 234 students from 76 different countries.", "website_url": "http://www.uwc-usa.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8292382&approved=True", "profile_level": "Gold", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/85-0297355", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2022-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(505) 454-4214", "contact_title": "Chief Advancement Officer", "number_of_employees": "170", "ruling_year": 1982 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 248", "address_line_2": "", "city": "Montezuma", "state": "NM", "zip": "87731", "msa": "", "congressional_district": "District 1, NM", "county": "San Miguel, NM", "latitude": 35.6734, "longitude": -105.3441 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 44401758.0, "total_expenses": 29045555.0, "total_assets": 400858910.0 }, "bmf_gross_receipts": 44401758.0, "bmf_assets": 400858910.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T15:58:21.0000000", "profile_last_modified": "2022-11-03T15:58:21.0000000", "dei_last_modified": "2022-11-03T00:00:00.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "6926751", "ein": "13-3840394", "organization_name": "The Posse Foundation", "also_known_as": "Posse", "group_exemption": "0000", "mission": "The Posse Foundation benefits both students and college campuses and is rooted in the belief that a small, diverse group of talented students – a \"posse\" – carefully selected and trained, serves as a catalyst for individual and community development. As the United States becomes an increasingly multicultural society, Posse believes that the leaders of the 21st century should reflect the country's rich demographic mix. The key to a promising future for our nation rests on the ability of strong leaders from diverse backgrounds to develop consensus solutions to complex social problems. Posse's primary aim is to cultivate these leaders of tomorrow.", "website_url": "http://www.possefoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7812846&approved=True", "profile_level": "Platinum", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/13-3840394", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2022-seal.svg", "leader_name": "<NAME>", "leader_title": "President and Founder", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(212) 405-1691", "contact_title": "Chief Development Officer", "number_of_employees": "240", "ruling_year": 1996 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "14 Wall St Ste 8a60", "address_line_2": "", "city": "New York City", "state": "NY", "zip": "10005", "msa": "NY - New York, NY-NJ", "congressional_district": "District 10, NY", "county": "New York, NY", "latitude": 40.7074, "longitude": -74.011 }, "taxonomies": { "subject_codes": [ { "subject_code": "SK020000", "subject_code_description": "Leadership development" }, { "subject_code": "SK000000", "subject_code_description": "Public affairs" }, { "subject_code": "SB090500", "subject_code_description": "Student retention" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B82", "ntee_code_description": "Scholarships, Student Financial Aid, Awards" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 33725316.0, "total_expenses": 23252059.0, "total_assets": 137527136.0 }, "bmf_gross_receipts": 48302842.0, "bmf_assets": 137527136.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-04-08T16:54:52.0000000", "profile_last_modified": "2022-05-20T12:33:35.0000000", "dei_last_modified": "2022-04-12T12:28:13.0000000", "financials_last_modified": "2023-05-18T18:49:03.0000000", "last_modified": "2023-05-18T18:49:03.0000000" } }, { "organization": { "organization_id": "9250464", "ein": "46-1314848", "organization_name": "uAspire", "also_known_as": "Previously known as ACCESS", "group_exemption": "0000", "mission": "uAspire is a nonprofit organization ensuring that all young people have the financial information and resources necessary to find an affordable path to and through college. Our singular focus is on college affordability and removing financial barriers so that every student has an equitable opportunity to graduate from college and succeed in life.Through student advising, counselor training, and policy and systems change, we work to remove the financial barriers to higher education. Collectively, our three models impacted over 690,000 students nationwide in 2018-19. Headquartered in Boston, we have a team of 65 full-time staff in California, Massachusetts, and New York.", "website_url": "http://www.uaspire.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8762212&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/46-1314848", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Senior Director, Marketing and Communications", "number_of_employees": "87", "ruling_year": 2013 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "31 Milk St Ste 900", "address_line_2": "", "city": "Boston", "state": "MA", "zip": "02109", "msa": "MA - Boston", "congressional_district": "District 8, MA", "county": "Suffolk, MA", "latitude": 42.3568, "longitude": -71.058 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B82", "ntee_code_description": "Scholarships, Student Financial Aid, Awards" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 11001635.0, "total_expenses": 7683195.0, "total_assets": 9973087.0 }, "bmf_gross_receipts": 13454450.0, "bmf_assets": 9973087.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-28T16:45:16.0000000", "profile_last_modified": "2023-02-28T16:45:16.0000000", "dei_last_modified": "2021-03-25T10:17:31.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7346572", "ein": "31-1672272", "organization_name": "Dohn Community High School", "also_known_as": "Dohn Community High School", "group_exemption": "0000", "mission": "Dohn Community High School is a multi-campus, nonprofit school serving high school-age and adult students. We deliver continuous progress to a full spectrum of learning needs. We promote community engagement, social development, and career fulfillment following graduation.Dohn soars on achieving educational success with the highest graduation rates of all Ohio charter high schools.\"We Make Dreams Come True\" is our vision statement.", "website_url": "www.dohnschool.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8862318&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/31-1672272", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(513) 908-5724", "contact_title": "Development Director", "number_of_employees": "205", "ruling_year": 2000 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "608 E McMillan St", "address_line_2": "", "city": "Cincinnati", "state": "OH", "zip": "45206", "msa": "OH - Cincinnati, OH-KY-IN", "congressional_district": "", "county": "Hamilton, OH", "latitude": 39.1264, "longitude": -84.4975 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030800", "subject_code_description": "Special needs education" }, { "subject_code": "SB030600", "subject_code_description": "Charter school education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 16370625.0, "total_expenses": 15256211.0, "total_assets": 3470956.0 }, "bmf_gross_receipts": 16370625.0, "bmf_assets": 3470956.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-03-27T10:06:13.0000000", "profile_last_modified": "2023-03-27T10:06:13.0000000", "dei_last_modified": "2022-06-17T00:00:00.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-07-10T17:03:00.0000000" } }, { "organization": { "organization_id": "7663448", "ein": "43-1815310", "organization_name": "Kanakuk Ministries", "also_known_as": "Kanakuk Kamps, Kanakuk KampOut, Link Year, Link Academy, and AfterDark", "group_exemption": "0000", "mission": "Equipping Next Generation Christian Leaders is more than our mission, it is our heartbeat. Since 1926, Kanakuk has welcomed over 500,000 Kampers and 50,000 summer staff from across the country and around the world, equipping them with leadership skills and Biblical truths to impact their schools and communities as examples of Jesus Christ.", "website_url": "https://kanakuk.com/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8329795&approved=True", "profile_level": "Gold", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/43-1815310", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Chairman", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(417) 266-3334", "contact_title": "Chief Business Officer", "number_of_employees": "2221", "ruling_year": 2015 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1353 Lake Shore Dr", "address_line_2": "", "city": "Branson", "state": "MO", "zip": "65616", "msa": "", "congressional_district": "District 7, MO", "county": "Taney, MO", "latitude": 36.6495, "longitude": -93.2457 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050900", "subject_code_description": "Religion for youth" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SQ020000", "subject_code_description": "Sports" }, { "subject_code": "SQ010100", "subject_code_description": "Camps" }, { "subject_code": "SQ010000", "subject_code_description": "Community recreation" }, { "subject_code": "SQ000000", "subject_code_description": "Sports and recreation" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PF010000", "population_served_description": "Christians" }, { "population_served_code": "PF000000", "population_served_description": "Religious groups" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O55", "ntee_code_description": "Religious Leadership, Youth Development" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 37973061.0, "total_expenses": 35386498.0, "total_assets": 49435943.0 }, "bmf_gross_receipts": 39512496.0, "bmf_assets": 49435943.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-14T19:02:02.0000000", "profile_last_modified": "2022-11-14T19:08:22.0000000", "dei_last_modified": "2022-11-14T00:00:00.0000000", "financials_last_modified": "2023-08-24T13:00:37.0000000", "last_modified": "2023-08-24T13:00:37.0000000" } }, { "organization": { "organization_id": "9907570", "ein": "85-0902650", "organization_name": "TECH FORWARD INC", "also_known_as": "HBCU FORCE", "group_exemption": "0000", "mission": "Tech Forward is a nonprofit organization that exposes marginalized communities tocloud and SAAS (software-as-a-service) based technologies and career paths to helpparticipants be more marketable, and obtain higher-paying jobs and career opportunities.", "website_url": "http://www.hbcuforce.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8934059&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-0902650", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Founder and Executive Director", "contact_name": "Mrs <NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Founder and Executive Director", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "5829 Campbellton Rd SW # 104-168", "address_line_2": "", "city": "Atlanta", "state": "GA", "zip": "30331", "msa": "GA - Atlanta", "congressional_district": "District 5, GA", "county": "Fulton, GA", "latitude": 33.6992, "longitude": -84.578 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS080000", "subject_code_description": "Job services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SB090800", "subject_code_description": "E-learning" }, { "subject_code": "SB090300", "subject_code_description": "Computer literacy" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB031000", "subject_code_description": "STEM education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050200", "population_served_description": "Teachers" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PE050300", "population_served_description": "People of Caribbean descent" }, { "population_served_code": "PE050000", "population_served_description": "People of Latin American descent" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P20", "ntee_code_description": "Human Service Organizations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-04-17T17:54:45.0000000", "profile_last_modified": "2023-04-17T17:54:45.0000000", "dei_last_modified": "2021-02-07T19:08:50.0000000", "financials_last_modified": "", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "10143492", "ein": "92-2404245", "organization_name": "Resound Future Bilingual Educators Network", "also_known_as": "", "group_exemption": "0000", "mission": "Creating pathways for future bilingual educators to impact the next generation", "website_url": "http://www.resounded.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9222530&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/92-2404245", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2023 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1047 Forbes Rd", "address_line_2": "", "city": "Fort Mill", "state": "SC", "zip": "29707", "msa": "SC - Charlotte-Gastonia-Rock Hill, NC-SC", "congressional_district": "District 5, SC", "county": "Lancaster, SC", "latitude": 35.062, "longitude": -80.8984 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB060500", "subject_code_description": "Teacher education" }, { "subject_code": "SB060000", "subject_code_description": "Graduate and professional education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB031100", "subject_code_description": "Multicultural education" }, { "subject_code": "SB030500", "subject_code_description": "Bilingual education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA080300", "subject_code_description": "Languages" }, { "subject_code": "SA080000", "subject_code_description": "Humanities" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PJ050200", "population_served_description": "Teachers" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B01", "ntee_code_description": "Alliance/Advocacy Organizations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-07-02T21:56:34.0000000", "profile_last_modified": "2023-07-02T21:56:34.0000000", "dei_last_modified": "2023-07-02T21:51:03.0000000", "financials_last_modified": "", "last_modified": "2023-07-02T21:56:34.0000000" } }, { "organization": { "organization_id": "9968776", "ein": "85-2923799", "organization_name": "Xceleader", "also_known_as": "", "group_exemption": "0000", "mission": "Increase and strengthen Black leadership by providing tools that inspire action and fuel ambition.", "website_url": "https://www.xceleader.com", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9019922&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-2923799", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Co-Founder", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1414 N Shepherd Dr Apt 404", "address_line_2": "", "city": "Houston", "state": "TX", "zip": "77008", "msa": "TX - Houston", "congressional_district": "District 2, TX", "county": "Harris, TX", "latitude": 29.7963, "longitude": -95.41 }, "taxonomies": { "subject_codes": [ { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SN020302", "subject_code_description": "Job training" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SK020000", "subject_code_description": "Leadership development" }, { "subject_code": "SK000000", "subject_code_description": "Public affairs" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020200", "population_served_description": "Older adults" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "R99", "ntee_code_description": "Civil Rights, Social Action, and Advocacy N.E.C." } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-02T14:03:41.0000000", "profile_last_modified": "2023-05-15T15:47:48.0000000", "dei_last_modified": "2022-11-29T11:54:57.0000000", "financials_last_modified": "", "last_modified": "2023-05-15T15:47:48.0000000" } }, { "organization": { "organization_id": "9962085", "ein": "85-2539829", "organization_name": "Gene Xcellence", "also_known_as": "Gene Xcellence", "group_exemption": "0000", "mission": "Our mission is to provide a way for adolescents and young adults to achieve economic mobility by equipping them with life-based skills and resources to overcome their adversities.", "website_url": "https://gene-xcellence.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8933280&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-2539829", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Founder, CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2021 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "106 W Georgia Rd", "address_line_2": "", "city": "Simpsonville", "state": "SC", "zip": "29681", "msa": "SC - Greenville-Spartanburg-Anderson", "congressional_district": "District 4, SC", "county": "Greenville, SC", "latitude": 34.7396, "longitude": -82.2583 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050600", "subject_code_description": "Economics for youth" }, { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS050303", "subject_code_description": "Youth peer mentoring" }, { "subject_code": "SS050301", "subject_code_description": "Adult and child mentoring" }, { "subject_code": "SS050300", "subject_code_description": "Youth mentoring" }, { "subject_code": "SS050100", "subject_code_description": "Youth services" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090100", "subject_code_description": "Out-of-school learning" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O50", "ntee_code_description": "Youth Development Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-04-17T15:16:08.0000000", "profile_last_modified": "2023-04-17T15:46:23.0000000", "dei_last_modified": "2022-08-29T18:36:26.0000000", "financials_last_modified": "", "last_modified": "2023-04-17T15:46:23.0000000" } }, { "organization": { "organization_id": "9925672", "ein": "84-3478958", "organization_name": "Holistic Evolution Inc", "also_known_as": "", "group_exemption": "0000", "mission": "Our Mission is to encourage the evolution of males of color 16-24 through supporting mentoring, health equity and other prevention efforts in Northwest Indiana; providing resources to remove unforeseen barriers to the evolution of males of color.", "website_url": "https://www.holisticevolution.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8983987&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/84-3478958", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(219) 293-7553", "contact_title": "CEO", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "234 Marcliffe Dr Apt 7", "address_line_2": "", "city": "Valparaiso", "state": "IN", "zip": "46385", "msa": "IN - Gary-Hammond-East Chicago", "congressional_district": "District 1, IN", "county": "Porter, IN", "latitude": 41.4445, "longitude": -87.1127 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS060602", "subject_code_description": "Aging out of foster care" }, { "subject_code": "SS060600", "subject_code_description": "Transition planning" }, { "subject_code": "SS060000", "subject_code_description": "Personal services" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SR050000", "subject_code_description": "Diversity and intergroup relations" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030200", "subject_code_description": "Community organizing" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SJ020000", "subject_code_description": "Abuse prevention" }, { "subject_code": "SJ010100", "subject_code_description": "Impaired driving" }, { "subject_code": "SJ010000", "subject_code_description": "Crime prevention" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" }, { "subject_code": "SE130600", "subject_code_description": "Physical fitness" }, { "subject_code": "SE130500", "subject_code_description": "Sexually transmitted disease control" }, { "subject_code": "SE130000", "subject_code_description": "Public health" }, { "subject_code": "SE120700", "subject_code_description": "Mental health counseling" }, { "subject_code": "SE120200", "subject_code_description": "Community mental health care" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE020000", "subject_code_description": "Health care access" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SB091200", "subject_code_description": "Tutoring" }, { "subject_code": "SB090500", "subject_code_description": "Student retention" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090100", "subject_code_description": "Out-of-school learning" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB020000", "subject_code_description": "Educational management" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG040200", "population_served_description": "Ex-offenders" }, { "population_served_code": "PG040000", "population_served_description": "Incarcerated people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE070000", "population_served_description": "Multiracial people" }, { "population_served_code": "PE060000", "population_served_description": "Indigenous peoples" }, { "population_served_code": "PE050000", "population_served_description": "People of Latin American descent" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE020000", "population_served_description": "People of Asian descent" }, { "population_served_code": "PE010000", "population_served_description": "People of Middle Eastern descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PD040400", "population_served_description": "Transitioning children" }, { "population_served_code": "PD040000", "population_served_description": "Non-adult children" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O50", "ntee_code_description": "Youth Development Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-05-03T15:47:54.0000000", "profile_last_modified": "2023-05-03T15:47:54.0000000", "dei_last_modified": "2023-05-03T14:29:01.0000000", "financials_last_modified": "", "last_modified": "2023-05-03T15:47:54.0000000" } }, { "organization": { "organization_id": "9969095", "ein": "85-3339422", "organization_name": "Institute for Youth in Policy", "also_known_as": "YIP Institute", "group_exemption": "0000", "mission": "The Institute for Youth in Policy is a youth-run, nonpartisan Institute utilizing discourse to redefine the way youth interacts with policy. Within the Institute, young leaders cultivate curriculum, content, and policy which spurs fundamental innovation through discussional richness and diversity of thought.We are students helping other students succeed and we believe constructive discourse is the key to forging lasting impact, as the movement we are leading continues to grow. Our large membership keeps us on track to ensure the most efficient, innovative, and effective approach.", "website_url": "https://yipinstitute.com", "logo_url": "", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-3339422", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Executive Director", "number_of_employees": "", "ruling_year": 2021 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1700 Van Ness Ave # 1143", "address_line_2": "", "city": "San Francisco", "state": "CA", "zip": "94109", "msa": "CA - San Francisco-Oakland", "congressional_district": "District 12, CA", "county": "San Francisco, CA", "latitude": 37.7913, "longitude": -122.4224 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN060300", "subject_code_description": "Corporate social responsibility" }, { "subject_code": "SN060000", "subject_code_description": "Business and industry" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SK040000", "subject_code_description": "Democracy" }, { "subject_code": "SK010000", "subject_code_description": "Public policy" }, { "subject_code": "SK000000", "subject_code_description": "Public affairs" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050200", "population_served_description": "Teachers" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "S05", "ntee_code_description": "Research Institutes and/or Public Policy Analysis" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-12T16:56:27.0000000", "profile_last_modified": "2023-03-12T16:56:27.0000000", "dei_last_modified": "2022-10-06T00:00:00.0000000", "financials_last_modified": "", "last_modified": "2023-05-09T11:30:00.0000000" } }, { "organization": { "organization_id": "9916903", "ein": "85-1487665", "organization_name": "Charity Achievement Networking and Education Foundation", "also_known_as": "CANE Foundation", "group_exemption": "0000", "mission": "The purpose of CANE is to positively influence the well-being, aspirations, connectedness, and education of youth in the Pearland-Manvel-Fresno, Texas area; with special emphasis on underappreciated and underserved African-American youth. Embedded in this purpose is the uplifting, promotion, support, admiration, and appreciation of often overlooked achievers and difference-makers in the community.", "website_url": "www.thecanefoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8686721&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-1487665", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Treasurer", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3422 Business Center Dr Ste 106 # 49", "address_line_2": "", "city": "Pearland", "state": "TX", "zip": "77584", "msa": "TX - Brazoria", "congressional_district": "District 22, TX", "county": "Brazoria, TX", "latitude": 29.5517, "longitude": -95.3703 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB090500", "subject_code_description": "Student retention" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB031000", "subject_code_description": "STEM education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE070000", "population_served_description": "Multiracial people" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "S80", "ntee_code_description": "Community Service Clubs (Kiwanis, Lions, Jaycees, etc.)" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-13T19:50:48.0000000", "profile_last_modified": "2023-02-13T19:50:48.0000000", "dei_last_modified": "2020-12-16T17:57:08.0000000", "financials_last_modified": "", "last_modified": "2023-03-14T12:27:00.0000000" } }, { "organization": { "organization_id": "9125335", "ein": "80-0177104", "organization_name": "Collective Souls Incorporated", "also_known_as": "", "group_exemption": "0000", "mission": "Mission is to educate, mentor, and nurture today's youth to help them reach their highest potential in becoming successful in life.", "website_url": "www.collectivesoulsinc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/80-0177104", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(314) 479-7747", "contact_title": "CEO", "number_of_employees": "", "ruling_year": 2011 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "7829 Bloom Dr", "address_line_2": "", "city": "St Louis", "state": "MO", "zip": "63133", "msa": "MO - St. Louis, MO-IL", "congressional_district": "District 1, MO", "county": "Saint Louis, MO", "latitude": 38.6742, "longitude": -91.3388 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS050800", "subject_code_description": "Community service for youth" }, { "subject_code": "SS050300", "subject_code_description": "Youth mentoring" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB091200", "subject_code_description": "Tutoring" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA010500", "subject_code_description": "Arts education" }, { "subject_code": "SA010000", "subject_code_description": "Arts services" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O50", "ntee_code_description": "Youth Development Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-08T21:18:08.0000000", "profile_last_modified": "2023-01-08T21:18:08.0000000", "dei_last_modified": "2023-01-08T20:10:43.0000000", "financials_last_modified": "", "last_modified": "2023-04-10T15:32:00.0000000" } }, { "organization": { "organization_id": "9369752", "ein": "95-2419408", "organization_name": "<NAME>", "also_known_as": "", "group_exemption": "0928", "mission": "As a college preparatory diocesan Catholic high school, Rosary Academy empowers the mind, body, and spirit of each young woman in a transformative educational experience. Guided by the Blessed Mother, Rosary Academy embraces and challenges its students with an innovative instructional curriculum to achieve academic success and ignite the call to serve the dear neighbor without distinction.", "website_url": "https://www.rosaryacademy.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8460330&approved=True", "profile_level": "Silver", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/95-2419408", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Head of School", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(714) 879-6302 x215", "contact_title": "Director of Business Operations", "number_of_employees": "", "ruling_year": 1965 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "1340 N Acacia Ave", "address_line_2": "", "city": "Fullerton", "state": "CA", "zip": "92831", "msa": "CA - Orange County", "congressional_district": "District 39, CA", "county": "Orange, CA", "latitude": 33.8867, "longitude": -117.8985 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030200", "subject_code_description": "Catholicism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" }, { "subject_code": "SG000000", "subject_code_description": "Social sciences" }, { "subject_code": "SB031000", "subject_code_description": "STEM education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-03T20:34:28.0000000", "profile_last_modified": "2023-01-03T20:34:27.0000000", "dei_last_modified": "2021-10-11T15:35:49.0000000", "financials_last_modified": "", "last_modified": "2023-01-03T20:34:27.0000000" } }, { "organization": { "organization_id": "10033984", "ein": "87-3741262", "organization_name": "Banging Pots Foundation, Inc.", "also_known_as": "", "group_exemption": "0000", "mission": "The Banging Pots Foundation is about that mindset, the belief in new horizons, shifting the paradigm, and following through the journey of our desires, until a thought becomes the thing we wished to create.We know, though, that on this path, it’s difficult to go it alone. The Banging Pots Foundation is about the belief, that no matter the blizzard, there will always be somebody, ‘banging pots’ to lead you home. We do that by paying the way forward for kids and teens whose parents cannot afford to send them to school. Every single donation helps us send our kids to school.", "website_url": "https://www.summerraininternational.com/banging-pots", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9412925&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/87-3741262", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2022 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "5434 Deerbrooke Creek Cir Apt 3", "address_line_2": "", "city": "Tampa", "state": "FL", "zip": "33624", "msa": "FL - Tampa-St. Petersburg-Clearwater", "congressional_district": "District 14, FL", "county": "Hillsborough, FL", "latitude": 28.0619, "longitude": -82.5379 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030900", "subject_code_description": "Child educational development" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030300", "subject_code_description": "Middle school education" }, { "subject_code": "SB030200", "subject_code_description": "Elementary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T50", "ntee_code_description": "Philanthropy / Charity / Voluntarism Promotion (General)" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-06-15T21:50:42.0000000", "profile_last_modified": "2023-08-28T22:42:33.0000000", "dei_last_modified": "2023-02-05T00:00:00.0000000", "financials_last_modified": "", "last_modified": "2023-08-28T22:42:33.0000000" } }, { "organization": { "organization_id": "9433049", "ein": "47-3725518", "organization_name": "Poor 2 Glee Foundation", "also_known_as": "P2G FOUND / P2G Foundation", "group_exemption": "0000", "mission": "Poverty ends when we work together to grow our education and finances. For those of us in the SF Bay Area who make less than, $100k are living below the poverty line. In leading the Poor 2 Glee (P2G) Foundation into helping to end poverty by educating youth and adults on basic financial and business education. I and my team know how to help you invest and grow your income.", "website_url": "p2gfoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8780458&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/47-3725518", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO/President/ Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(408) 829-1392", "contact_title": "CEO/President/ Executive Director", "number_of_employees": "", "ruling_year": 2015 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1775 McLaughlin Ave", "address_line_2": "", "city": "San Jose", "state": "CA", "zip": "95122", "msa": "CA - San Jose", "congressional_district": "District 19, CA", "county": "Santa Clara, CA", "latitude": 37.3249, "longitude": -121.846 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN060000", "subject_code_description": "Business and industry" }, { "subject_code": "SN020301", "subject_code_description": "Job counseling" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B25", "ntee_code_description": "Secondary/High School" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-04T22:40:56.0000000", "profile_last_modified": "2023-03-04T22:40:56.0000000", "dei_last_modified": "2023-03-05T00:00:00.0000000", "financials_last_modified": "", "last_modified": "2023-03-14T12:27:00.0000000" } }, { "organization": { "organization_id": "9742285", "ein": "82-4458239", "organization_name": "MENTEE", "also_known_as": "MENTEE Global", "group_exemption": "0000", "mission": "MENTEE is a non-profit organization aligned with global SDGs that provides access to a global network of mentor specialists who share their skills and support to help create better, healthier lives for marginalized populations living around the world. Using our virtual platform, mentees are given the power of access to choose any specialist they need to help accelerate their success. The program provides trauma and mentorship training for our global mentors as well as additional professional skills training for our mentees. We are partnered with 5 NGOs and institutions globally and are supporting 7 different countries on 4 different continents.", "website_url": "www.menteeglobal.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8605490&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/82-4458239", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Founder & CEO", "contact_name": "Mrs. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(708) 647-1542", "contact_title": "Founder & CEO", "number_of_employees": "", "ruling_year": 2018 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1320 Dartford Ct", "address_line_2": "", "city": "Naperville", "state": "IL", "zip": "60540", "msa": "IL - Chicago", "congressional_district": "District 6, IL", "county": "Dupage, IL", "latitude": 41.7575, "longitude": -88.115 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SR040000", "subject_code_description": "Antidiscrimination" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SN020302", "subject_code_description": "Job training" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020200", "population_served_description": "Older adults" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O50", "ntee_code_description": "Youth Development Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-28T16:54:06.0000000", "profile_last_modified": "2023-01-28T16:54:06.0000000", "dei_last_modified": "2020-11-20T19:08:28.0000000", "financials_last_modified": "", "last_modified": "2023-01-28T16:54:06.0000000" } }, { "organization": { "organization_id": "9899191", "ein": "85-1160030", "organization_name": "Sabinal Alumni", "also_known_as": "", "group_exemption": "0000", "mission": "To support Sabinal Independent School District through scholarships that enable graduates to pursue a postsecondary education.", "website_url": "www.sabinalalumni.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9245695&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-1160030", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "President", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "555 E 5th St Apt 3007", "address_line_2": "", "city": "Austin", "state": "TX", "zip": "78701", "msa": "TX - Austin-<NAME>", "congressional_district": "District 21, TX", "county": "Travis, TX", "latitude": 30.2657, "longitude": -97.738 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080100", "subject_code_description": "Alumni relations" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050100", "subject_code_description": "Community college education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B84", "ntee_code_description": "Alumni Associations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-07-10T19:21:01.0000000", "profile_last_modified": "2023-07-10T19:21:01.0000000", "dei_last_modified": "2023-07-10T16:56:50.0000000", "financials_last_modified": "", "last_modified": "2023-07-10T19:21:01.0000000" } }, { "organization": { "organization_id": "10016787", "ein": "87-1266060", "organization_name": "Adopt A Destiny Inc", "also_known_as": "", "group_exemption": "0000", "mission": "At Adopt A Destiny, our mission is to empower the black and brown population with a primary focus on low-income high school and college students in New York and a secondary focus on black and brown migrants. We address their financial and social challenges and provide students with opportunities for higher education, and migrants access to social resources. We are dedicated to creating a supportive environment that fosters academic excellence, personal growth, and social mobility.", "website_url": "https://adoptadestiny.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9181383&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/87-1266060", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2022 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "11623 196th St", "address_line_2": "", "city": "St Albans", "state": "NY", "zip": "11412", "msa": "NY - New York, NY-NJ", "congressional_district": "District 5, NY", "county": "Queens, NY", "latitude": 40.6986, "longitude": -73.7596 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SR050000", "subject_code_description": "Diversity and intergroup relations" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB040000", "subject_code_description": "Vocational education" }, { "subject_code": "SB030400", "subject_code_description": "Secondary education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA040000", "subject_code_description": "Cultural awareness" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PJ100000", "population_served_description": "Artists and performers" }, { "population_served_code": "PJ050300", "population_served_description": "Researchers" }, { "population_served_code": "PJ050200", "population_served_description": "Teachers" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ030000", "population_served_description": "Self-employed people" }, { "population_served_code": "PJ020000", "population_served_description": "Unemployed people" }, { "population_served_code": "PJ010000", "population_served_description": "Domestic workers" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010600", "population_served_description": "Internally displaced people" }, { "population_served_code": "PG010500", "population_served_description": "Asylum seekers" }, { "population_served_code": "PG010400", "population_served_description": "Refugees and displaced people" }, { "population_served_code": "PG010300", "population_served_description": "Cross-border families" }, { "population_served_code": "PG010100", "population_served_description": "Immigrants" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE050300", "population_served_description": "People of Caribbean descent" }, { "population_served_code": "PE050200", "population_served_description": "People of South American descent" }, { "population_served_code": "PE050100", "population_served_description": "People of Central American descent" }, { "population_served_code": "PE050000", "population_served_description": "People of Latin American descent" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PD020400", "population_served_description": "Single parents" }, { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B82", "ntee_code_description": "Scholarships, Student Financial Aid, Awards" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-06-21T23:18:20.0000000", "profile_last_modified": "2023-06-21T23:18:20.0000000", "dei_last_modified": "2023-06-21T00:00:00.0000000", "financials_last_modified": "", "last_modified": "2023-06-21T23:18:20.0000000" } }, { "organization": { "organization_id": "9945110", "ein": "85-3756579", "organization_name": "<NAME>", "also_known_as": "", "group_exemption": "0000", "mission": "To bridge the gap of educational inequity in LA County by supporting the students who need it most. Not only is there an increasingly widening gap in educational opportunities and outcomes in LA County, there is also a significant gap in scholarship funding available for high potential students who don’t score well using traditional metrics like GPA and standardized test scores. AFF aims to close this gap by supporting those who may not have the highest GPA or SAT scores, but display strong morals, grit and determination in the face of adversity. Lastly, we aim to honor Alexx’s memory by giving back to the communities that he called home.", "website_url": "afloresfoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8819500&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/85-3756579", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(626) 890- x367", "contact_title": "Executive Director", "number_of_employees": "", "ruling_year": 2021 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "5830 Benner St", "address_line_2": "", "city": "Los Angeles", "state": "CA", "zip": "90042", "msa": "CA - Los Angeles-Long Beach", "congressional_district": "District 34, CA", "county": "Los Angeles, CA", "latitude": 34.1074, "longitude": -118.1899 }, "taxonomies": { "subject_codes": [ { "subject_code": "SC040300", "subject_code_description": "Forest preservation" }, { "subject_code": "SC040000", "subject_code_description": "Biodiversity" }, { "subject_code": "SC000000", "subject_code_description": "Environment" }, { "subject_code": "SB090500", "subject_code_description": "Student retention" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050100", "subject_code_description": "Community college education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "C36", "ntee_code_description": "Forest Conservation" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-14T20:51:41.0000000", "profile_last_modified": "2023-03-14T20:51:41.0000000", "dei_last_modified": "2023-03-14T00:00:00.0000000", "financials_last_modified": "", "last_modified": "2023-04-10T15:32:00.0000000" } } ] } ``` This example will return organizations who match the following logic: (college preparation `OR` secondary education) `AND` young adults ## Filter by organizations who submitted demographic data to Candid Find organizations who have submitted demographic data to Candid ``` { "filters": { "organization": { "properties": { "dei_submitted": true } } } } ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 609, "time": "2023-08-29 18:34:44Z", "results_count": 51796, "page_count": 2072, "errors": [], "hits": [ { "organization": { "organization_id": "8872439", "ein": "26-4486735", "organization_name": "Sixteen Thirty Fund", "also_known_as": "", "group_exemption": "0000", "mission": "SIXTEEN THIRTY FUND OPERATES EXCLUSIVELY FOR THE PURPOSE OF PROMOTING SOCIAL WELFARE, INCLUDING, BUT NOT LIMITED TO, PROVIDING PUBLIC EDUCATION ON AND CONDUCTING ADVOCACY REGARDING KEY POLICIES.", "website_url": "https://www.sixteenthirtyfund.org/", "logo_url": "", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/26-4486735", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "5", "ruling_year": 2009 }, "properties": { "bmf_status": true, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1828 L St NW Ste 300b", "address_line_2": "", "city": "Washington", "state": "DC", "zip": "20036", "msa": "DC - Washington, DC-MD-VA", "congressional_district": "", "county": "District of Columbia, DC", "latitude": 38.9037, "longitude": -77.0422 }, "taxonomies": { "subject_codes": [ { "subject_code": "SC060000", "subject_code_description": "Environmental education" }, { "subject_code": "SC000000", "subject_code_description": "Environment" } ], "population_served_codes": [ { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" } ], "ntee_codes": [ { "ntee_code": "C60", "ntee_code_description": "Environmental Education and Outdoor Survival Programs" } ], "subsection_code": { "subsection_code": "04", "subsection_code_description": "501(c)(4) Civic Leagues and Social Welfare Organizations" }, "foundation_code": { "foundation_code": "00", "foundation_code_description": "All organizations except 501(c)(3)" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 190651953.0, "total_expenses": 173564342.0, "total_assets": 97684457.0 }, "bmf_gross_receipts": 190701430.0, "bmf_assets": 97684457.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-27T14:07:46.0000000", "profile_last_modified": "2023-03-27T14:07:46.0000000", "dei_last_modified": "2023-03-27T00:00:00.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-05-18T17:01:04.0000000" } }, { "organization": { "organization_id": "6815439", "ein": "03-0373895", "organization_name": "<NAME>. and Marion L. Miller Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "The James F. and Marion L. Miller Foundation, an independent private foundation, was established in 2002 to enhance the quality of life of Oregonians through the support of classroom education and the performing, visual, and literary arts.", "website_url": "http://www.millerfound.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9266976&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/03-0373895", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2003 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1905 SE 10th Ave", "address_line_2": "", "city": "Portland", "state": "OR", "zip": "97214", "msa": "OR - Portland, OR-WA", "congressional_district": "District 3, OR", "county": "Multnomah, OR", "latitude": 45.5093, "longitude": -122.6557 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PJ100000", "population_served_description": "Artists and performers" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T22", "ntee_code_description": "Private Independent Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 30090803.0, "total_expenses": 14949129.0, "total_assets": 241189830.0 }, "bmf_gross_receipts": 62977995.0, "bmf_assets": 164280841.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-07-17T17:01:28.0000000", "profile_last_modified": "2023-07-17T17:01:28.0000000", "dei_last_modified": "2022-01-19T14:17:44.0000000", "financials_last_modified": "2023-05-10T06:17:24.0000000", "last_modified": "2023-07-17T17:01:28.0000000" } }, { "organization": { "organization_id": "6858442", "ein": "04-6579815", "organization_name": "Barr Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "To invest in human, natural, and creative potential, serving as thoughtful stewards and catalysts.Based in Boston, Barr focuses regionally, and selectively engages nationally, working in partnership with nonprofits, foundations, the public sector, and civic and business leaders to elevate the arts and creative expression, to advance solutions for climate change, and to connect all students to success in high school and beyond. With assets of $1.8 billion, Barr is among the largest private foundations in New England and has contributed more than $911 million to charitable causes since 1999.", "website_url": "https://www.barrfoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8991122&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/04-6579815", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & Trustee", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(617) 854-3447", "contact_title": "Communications Associate", "number_of_employees": "", "ruling_year": 1988 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2 Atlantic Ave", "address_line_2": "", "city": "Boston", "state": "MA", "zip": "02110", "msa": "MA - Boston", "congressional_district": "District 8, MA", "county": "Suffolk, MA", "latitude": 42.3633, "longitude": -71.051 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SC030500", "subject_code_description": "Land resources" }, { "subject_code": "SC030000", "subject_code_description": "Natural resources" }, { "subject_code": "SC020000", "subject_code_description": "Climate change" }, { "subject_code": "SC000000", "subject_code_description": "Environment" }, { "subject_code": "SB090100", "subject_code_description": "Out-of-school learning" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA060000", "subject_code_description": "Performing arts" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T22", "ntee_code_description": "Private Independent Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 449148867.0, "total_expenses": 157493185.0, "total_assets": 3482999636.0 }, "bmf_gross_receipts": 563683901.0, "bmf_assets": 1838977066.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-01T09:29:05.0000000", "profile_last_modified": "2023-05-05T11:24:23.0000000", "dei_last_modified": "2023-05-05T00:00:00.0000000", "financials_last_modified": "2023-05-18T15:30:05.0000000", "last_modified": "2023-05-18T15:30:05.0000000" } }, { "organization": { "organization_id": "6920224", "ein": "13-3647019", "organization_name": "<NAME>", "also_known_as": "", "group_exemption": "0000", "mission": "Heron's mission is to help people and communities help themselves.", "website_url": "www.heron.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8922817&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-3647019", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Managing Vice President", "number_of_employees": "", "ruling_year": 1992 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 9438", "address_line_2": "", "city": "New Haven", "state": "CT", "zip": "06534", "msa": "CT - New Haven-Meriden", "congressional_district": "District 3, CT", "county": "New Haven, CT", "latitude": 41.3464, "longitude": -72.9434 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T20", "ntee_code_description": "Private Grantmaking Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 28288660.0, "total_expenses": 15613585.0, "total_assets": 412823233.0 }, "bmf_gross_receipts": 82911698.0, "bmf_assets": 412823233.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-04-13T12:23:22.0000000", "profile_last_modified": "2023-04-13T12:23:22.0000000", "dei_last_modified": "2021-12-13T10:57:59.0000000", "financials_last_modified": "2023-05-18T17:02:28.0000000", "last_modified": "2023-05-18T17:02:28.0000000" } }, { "organization": { "organization_id": "6943140", "ein": "13-6108163", "organization_name": "SURDNA FOUNDATION INC", "also_known_as": "", "group_exemption": "0000", "mission": "The Surdna Foundation seeks to foster sustainable communities in the United States — communities guided by principles of social justice and distinguished by healthy environments, inclusive economies, and thriving cultures.For over five generations, the Foundation has been governed largely by descendants of <NAME> and has developed a tradition of innovative service for those in need of help or opportunity.", "website_url": "surdna.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-6108163", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(212) 557-0010", "contact_title": "Learning & Impact Officer", "number_of_employees": "", "ruling_year": 1938 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "200 Madison Ave Fl 25", "address_line_2": "", "city": "New York City", "state": "NY", "zip": "10016", "msa": "NY - New York, NY-NJ", "congressional_district": "District 12, NY", "county": "New York, NY", "latitude": 40.7484, "longitude": -73.9825 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PC040000", "population_served_description": "Women and girls" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" } ], "ntee_codes": [ { "ntee_code": "T20", "ntee_code_description": "Private Grantmaking Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2022, "total_revenue": 50900057.0, "total_expenses": 51216331.0, "total_assets": 1222374293.0 }, "bmf_gross_receipts": 221365496.0, "bmf_assets": 1222374293.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-07T11:22:18.0000000", "profile_last_modified": "2023-05-05T14:04:07.0000000", "dei_last_modified": "2023-05-05T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:02:02.0000000", "last_modified": "2023-06-23T09:02:02.0000000" } }, { "organization": { "organization_id": "7808396", "ein": "54-1511748", "organization_name": "AKAL INSTITUTE", "also_known_as": "", "group_exemption": "0000", "mission": "The mission of AKAL is to develop integrated wellness center(s) that can be deployed across the U.S. and are designed and operated in a manner that provides a cost-effective, success-driven approach to addiction recovery transitional living to restore individuals to self-sufficiency.\\nTo achieve transitional living, it is necessary to have facilities that provide inpatient services and outpatient services including therapy, job training, employment, and sober living. Within these facilities and programs come special requirements for men and women.\\n\\nHarness the power of technology and the dedication of skilled, knowledgeable professionals to serve and care for our clients and their families, enabling them to achieve their potential and live fuller, more rewarding lives.", "website_url": "http://akalinstitute.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8778610&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/54-1511748", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Founder, Chairman and CEO", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Chief Administrative Officer", "number_of_employees": "", "ruling_year": 1991 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 200", "address_line_2": "", "city": "Rancho Santa Fe", "state": "CA", "zip": "92067", "msa": "CA - San Diego", "congressional_district": "District 49, CA", "county": "San Diego, CA", "latitude": 33.0164, "longitude": -117.1968 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE120500", "subject_code_description": "Addiction services" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH030000", "population_served_description": "Substance abusers" }, { "population_served_code": "PH000000", "population_served_description": "Health" } ], "ntee_codes": [ { "ntee_code": "F20", "ntee_code_description": "Alcohol, Drug and Substance Abuse, Dependency Prevention and Treatment" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Operating Foundation" }, "foundation_code": { "foundation_code": "03", "foundation_code_description": "Private Operating foundation (other)" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": -14891940.0, "total_expenses": 12936754.0, "total_assets": 13061672.0 }, "bmf_gross_receipts": 194555437.0, "bmf_assets": 13061239.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-03T18:44:16.0000000", "profile_last_modified": "2023-03-03T18:44:16.0000000", "dei_last_modified": "2021-04-02T13:37:28.0000000", "financials_last_modified": "2023-05-18T17:02:28.0000000", "last_modified": "2023-05-18T17:02:28.0000000" } }, { "organization": { "organization_id": "7855011", "ein": "56-0529965", "organization_name": "The Duke Endowment", "also_known_as": "Duke Endowment", "group_exemption": "0000", "mission": "We work through select North Carolina and South Carolina organizations to: Ensure children grow up in families safe from maltreatment Improve the health of Carolinians Advance high-value education for students Preserve the pivotal role United Methodist churches play in rural communities", "website_url": "http://www.dukeendowment.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9188197&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/56-0529965", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(704) 969-2100", "contact_title": "Director, Communications", "number_of_employees": "", "ruling_year": 1938 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "800 E Morehead St", "address_line_2": "", "city": "Charlotte", "state": "NC", "zip": "28202", "msa": "NC - Charlotte-Gastonia-Rock Hill, NC-SC", "congressional_district": "District 12, NC", "county": "Mecklenburg, NC", "latitude": 35.215, "longitude": -80.8457 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SP000000", "subject_code_description": "Religion" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SK000000", "subject_code_description": "Public affairs" }, { "subject_code": "SH000000", "subject_code_description": "Information and communications" }, { "subject_code": "SG000000", "subject_code_description": "Social sciences" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SB100000", "subject_code_description": "Early childhood education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH040000", "population_served_description": "Pregnant people" }, { "population_served_code": "PH030000", "population_served_description": "Substance abusers" }, { "population_served_code": "PH020000", "population_served_description": "People with diseases and illnesses" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PD050000", "population_served_description": "Caregivers" }, { "population_served_code": "PD040000", "population_served_description": "Non-adult children" }, { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T20", "ntee_code_description": "Private Grantmaking Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 832404504.0, "total_expenses": 220201927.0, "total_assets": 5889117596.0 }, "bmf_gross_receipts": 3355239034.0, "bmf_assets": 3374460396.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-06-22T17:13:09.0000000", "profile_last_modified": "2023-06-22T17:17:51.0000000", "dei_last_modified": "2023-06-22T00:00:00.0000000", "financials_last_modified": "2023-05-18T15:30:05.0000000", "last_modified": "2023-06-22T17:17:51.0000000" } }, { "organization": { "organization_id": "7101381", "ein": "22-2842846", "organization_name": "Community Connections for Children, Inc", "also_known_as": "", "group_exemption": "0000", "mission": "Community Connections for Children, Inc. ensures that all families have access to affordable, high quality child care choices that lead to success in school and life.", "website_url": "http://cccforpa.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9058306&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/22-2842846", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "76", "ruling_year": 1988 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "29 N Duke St", "address_line_2": "", "city": "York", "state": "PA", "zip": "17401", "msa": "PA - York", "congressional_district": "District 10, PA", "county": "York, PA", "latitude": 39.964, "longitude": -76.7263 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS040302", "subject_code_description": "Child care" }, { "subject_code": "SS040300", "subject_code_description": "Child welfare" }, { "subject_code": "SS040000", "subject_code_description": "Family services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN020302", "subject_code_description": "Job training" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB100000", "subject_code_description": "Early childhood education" }, { "subject_code": "SB091000", "subject_code_description": "Parent-teacher involvement" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010100", "population_served_description": "Infants and toddlers" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P33", "ntee_code_description": "Child Day Care" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 144029187.0, "total_expenses": 142865650.0, "total_assets": 29069252.0 }, "bmf_gross_receipts": 115294715.0, "bmf_assets": 14301001.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-26T07:42:48.0000000", "profile_last_modified": "2023-05-26T07:51:50.0000000", "dei_last_modified": "2023-05-26T07:48:20.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-05-26T07:51:50.0000000" } }, { "organization": { "organization_id": "7467623", "ein": "36-3525653", "organization_name": "Bcbsm Foundation Inc", "also_known_as": "", "group_exemption": "0000", "mission": "We build strong community partnerships to advance racial and health equity.", "website_url": "https://www.bluecrossmnfoundation.org/", "logo_url": "", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/36-3525653", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(651) 662-7250", "contact_title": "Foundation President", "number_of_employees": "", "ruling_year": 1988 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 64560", "address_line_2": "R472,", "city": "St Paul", "state": "MN", "zip": "55164", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "District 2, MN", "county": "Ramsey, MN", "latitude": 44.9148, "longitude": -93.0477 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SS040000", "subject_code_description": "Family services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SR040200", "subject_code_description": "Ethnic and racial minority rights" }, { "subject_code": "SR040000", "subject_code_description": "Antidiscrimination" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SJ060000", "subject_code_description": "Disasters and emergency management" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" }, { "subject_code": "SE130000", "subject_code_description": "Public health" }, { "subject_code": "SE020000", "subject_code_description": "Health care access" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SB030900", "subject_code_description": "Child educational development" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE060300", "population_served_description": "American Indians" }, { "population_served_code": "PE060000", "population_served_description": "Indigenous peoples" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T20", "ntee_code_description": "Private Grantmaking Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 6512413.0, "total_expenses": 6741939.0, "total_assets": 78373762.0 }, "bmf_gross_receipts": 61364232.0, "bmf_assets": 78373762.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-23T13:32:28.0000000", "profile_last_modified": "2023-02-23T13:32:28.0000000", "dei_last_modified": "2021-07-30T07:27:09.0000000", "financials_last_modified": "2023-05-10T10:13:57.0000000", "last_modified": "2023-05-10T10:13:57.0000000" } }, { "organization": { "organization_id": "7103106", "ein": "23-1503488", "organization_name": "William Penn Foundation", "also_known_as": "WPF", "group_exemption": "0000", "mission": "Our mission is to help improve education for low-income children, ensure a sustainable environment, foster creative communities that enhance civic life and advance philanthropy in the Greater Philadelphia region.", "website_url": "http://www.williampennfoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8742591&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/23-1503488", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(215) 988-1830", "contact_title": "Director, Grants Management", "number_of_employees": "", "ruling_year": 1947 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2 Logan Sq Fl 100", "address_line_2": "", "city": "Philadelphia", "state": "PA", "zip": "19103", "msa": "PA - Philadelphia, PA-NJ", "congressional_district": "District 1, PA", "county": "Philadelphia, PA", "latitude": 39.9515, "longitude": -75.1745 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T20", "ntee_code_description": "Private Grantmaking Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 378565953.0, "total_expenses": 157448356.0, "total_assets": 3919486888.0 }, "bmf_gross_receipts": 1929998597.0, "bmf_assets": 3919486888.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-24T11:56:38.0000000", "profile_last_modified": "2023-02-24T11:56:38.0000000", "dei_last_modified": "2022-06-07T00:00:00.0000000", "financials_last_modified": "2023-05-18T15:30:05.0000000", "last_modified": "2023-05-18T15:30:05.0000000" } }, { "organization": { "organization_id": "8951454", "ein": "27-2559468", "organization_name": "AAA Scholarship Foundation Inc", "also_known_as": "AAA Scholarships", "group_exemption": "0000", "mission": "AAA Scholarship Foundation's mission is to provide economic and other assistance to economically-disadvantaged families to enable them to select the best schools for their children.", "website_url": "www.aaascholarships.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8577360&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/27-2559468", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(888) 707-2465 x710", "contact_title": "President", "number_of_employees": "18", "ruling_year": 2010 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 15719", "address_line_2": "", "city": "Tampa", "state": "FL", "zip": "33684", "msa": "FL - Tampa-St. Petersburg-Clearwater", "congressional_district": "District 14, FL", "county": "Hillsborough, FL", "latitude": 27.9967, "longitude": -82.4837 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B82", "ntee_code_description": "Scholarships, Student Financial Aid, Awards" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 128005629.0, "total_expenses": 89721926.0, "total_assets": 113422809.0 }, "bmf_gross_receipts": 128797873.0, "bmf_assets": 113422809.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-24T14:09:35.0000000", "profile_last_modified": "2023-01-24T14:09:35.0000000", "dei_last_modified": "2022-03-01T14:10:06.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-05-18T17:01:04.0000000" } }, { "organization": { "organization_id": "7534720", "ein": "38-2876435", "organization_name": "Ruth Mott Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "The foundation's mission is to advocate, stimulate, and support community vitality. Its commitment is to base the foundation in its home community of Flint, Michigan", "website_url": "http://www.ruthmottfoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9276613&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/38-2876435", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Grants Manager", "number_of_employees": "", "ruling_year": 1989 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "111 E Court St Ste 3c", "address_line_2": "", "city": "Flint", "state": "MI", "zip": "48502", "msa": "MI - Flint", "congressional_district": "District 5, MI", "county": "Genesee, MI", "latitude": 43.0126, "longitude": -83.6877 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B82", "ntee_code_description": "Scholarships, Student Financial Aid, Awards" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 30117543.0, "total_expenses": 11816600.0, "total_assets": 288091185.0 }, "bmf_gross_receipts": 85651741.0, "bmf_assets": 290091185.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-07-19T15:21:52.0000000", "profile_last_modified": "2023-07-19T16:08:10.0000000", "dei_last_modified": "2023-07-19T00:00:00.0000000", "financials_last_modified": "2023-05-18T17:02:28.0000000", "last_modified": "2023-07-19T16:08:10.0000000" } }, { "organization": { "organization_id": "7345025", "ein": "31-1496872", "organization_name": "The Harvest Foundation", "also_known_as": "Harvest Foundation", "group_exemption": "0000", "mission": "The Harvest Foundation researches and responsibly invests in programs and initiatives to address local challenges in health, education, and community vitality.", "website_url": "www.theharvestfoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9032244&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/31-1496872", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(276) 632-3329 x118", "contact_title": "Director of Communications", "number_of_employees": "", "ruling_year": 1997 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 5183", "address_line_2": "", "city": "Martinsville", "state": "VA", "zip": "24115", "msa": "", "congressional_district": "District 9, VA", "county": "Martinsville City, VA", "latitude": 36.6879, "longitude": -79.8679 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "S30", "ntee_code_description": "Economic Development" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 26551741.0, "total_expenses": 30399653.0, "total_assets": 283210343.0 }, "bmf_gross_receipts": 92826721.0, "bmf_assets": 283210343.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-05-18T10:59:57.0000000", "profile_last_modified": "2023-05-18T10:59:57.0000000", "dei_last_modified": "2023-05-18T00:00:00.0000000", "financials_last_modified": "2023-05-18T15:30:05.0000000", "last_modified": "2023-05-18T15:30:05.0000000" } }, { "organization": { "organization_id": "7590246", "ein": "41-0719221", "organization_name": "NORTHWEST AREA FOUNDATION", "also_known_as": "NWAF", "group_exemption": "0000", "mission": "The mission of the Northwest Area Foundation is to support efforts by the people, organizations and communities of our eight-state region to reduce poverty and achieve sustainable prosperity. We support organizations that work to reimagine and restructure unjust systems so communities can thrive on their own terms. They lead with courage, wisdom and vision, advancing long-overdue change in deep connection with the land they inhabit and the communities they serve - Native Americans, communities of color, immigrants, refugees and people in rural areas. These organizations are on a journey of building social, racial and economic justice. Our region includes Idaho, Iowa, Minnesota, Montana, North Dakota, Oregon, South Dakota, Washington and the 76 Native Nations of our region.", "website_url": "www.nwaf.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9023557&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/41-0719221", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(651) 225-7704", "contact_title": "Communications Director", "number_of_employees": "", "ruling_year": 1947 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "60 Plato Blvd E Ste 400", "address_line_2": "", "city": "St Paul", "state": "MN", "zip": "55107", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "District 4, MN", "county": "Ramsey, MN", "latitude": 44.9274, "longitude": -93.0856 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SR040200", "subject_code_description": "Ethnic and racial minority rights" }, { "subject_code": "SR040100", "subject_code_description": "Immigrants' rights" }, { "subject_code": "SR040000", "subject_code_description": "Antidiscrimination" }, { "subject_code": "SR020800", "subject_code_description": "Economic justice" }, { "subject_code": "SR020700", "subject_code_description": "Cultural rights" }, { "subject_code": "SR020000", "subject_code_description": "Social rights" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SN050103", "subject_code_description": "Community development finance" }, { "subject_code": "SN050100", "subject_code_description": "Development finance" }, { "subject_code": "SN050000", "subject_code_description": "Financial services" }, { "subject_code": "SN020200", "subject_code_description": "Rural development" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN010000", "subject_code_description": "Sustainable development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE060300", "population_served_description": "American Indians" }, { "population_served_code": "PE060000", "population_served_description": "Indigenous peoples" }, { "population_served_code": "PE050000", "population_served_description": "People of Latin American descent" }, { "population_served_code": "PE030000", "population_served_description": "People of African descent" }, { "population_served_code": "PE020000", "population_served_description": "People of Asian descent" }, { "population_served_code": "PE010000", "population_served_description": "People of Middle Eastern descent" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" } ], "ntee_codes": [ { "ntee_code": "T22", "ntee_code_description": "Private Independent Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 54713221.0, "total_expenses": 34395996.0, "total_assets": 565953353.0 }, "bmf_gross_receipts": 152404747.0, "bmf_assets": 565953353.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-05-16T13:06:55.0000000", "profile_last_modified": "2023-05-16T13:06:55.0000000", "dei_last_modified": "2023-04-13T00:00:00.0000000", "financials_last_modified": "2023-05-18T17:02:28.0000000", "last_modified": "2023-05-18T17:02:28.0000000" } }, { "organization": { "organization_id": "7535520", "ein": "38-2923581", "organization_name": "Pulte Family Charitable Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "Our MissionGuided by the belief in the inherent dignity of all persons, the Pulte Family Charitable Foundation works to meet the basic human needs of the most marginalized members of the human family, including socioeconomically disadvantaged youth; the aged; persons with physical, emotional and mental disabilities; and those with the fewest material resources. In addition to the above, the Foundation seeks to serve religious communities and correlative organizations of Judeo-Christian beliefs. To this end, the Foundation strives to enact through its grantees the Seven Corporal Works of Mercy: feed the hungry, give drink to the thirsty; clothe the naked; care for captives; shelter the homeless; visit the sick, and assist the mourning.", "website_url": "www.pultefamilyfoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8584377&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/38-2923581", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1990 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "220 S Dixie Hwy", "address_line_2": "", "city": "Boca Raton", "state": "FL", "zip": "33432", "msa": "FL - West Palm Beach-Boca Raton", "congressional_district": "District 22, FL", "county": "Palm Beach, FL", "latitude": 26.3477, "longitude": -80.0882 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH020000", "population_served_description": "People with diseases and illnesses" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG060000", "population_served_description": "Victims and oppressed people" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T20", "ntee_code_description": "Private Grantmaking Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 153978853.0, "total_expenses": 11302200.0, "total_assets": 474068562.0 }, "bmf_gross_receipts": 223275678.0, "bmf_assets": 379447659.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-25T09:39:58.0000000", "profile_last_modified": "2023-01-25T10:55:00.0000000", "dei_last_modified": "2022-05-05T15:24:06.0000000", "financials_last_modified": "2023-05-18T15:30:05.0000000", "last_modified": "2023-05-18T15:30:05.0000000" } }, { "organization": { "organization_id": "9466755", "ein": "36-4812310", "organization_name": "The Libra Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "We are committed to supporting organizations led by those most impacted by systemic oppression – largely low-income communities of color. The Libra Foundation’s guiding principle is that those who are closest to the issues understand those issues the best. They are not only the most equipped to build solutions, they are the most effective at implementing those solutions. We focus on frontline organizations led by people of color transforming the criminal justice system and advancing environmental and climate justice and gender justice.", "website_url": "thelibrafoundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8755634&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/36-4812310", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Director of Operations", "number_of_employees": "", "ruling_year": 2015 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1 Letterman Dr Ste C4-420", "address_line_2": "", "city": "San Francisco", "state": "CA", "zip": "94129", "msa": "CA - San Francisco-Oakland", "congressional_district": "District 12, CA", "county": "San Francisco, CA", "latitude": 37.7992, "longitude": -122.4526 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SR020000", "subject_code_description": "Social rights" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SN030200", "subject_code_description": "Community organizing" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" } ], "population_served_codes": [ { "population_served_code": "PG040000", "population_served_description": "Incarcerated people" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE070000", "population_served_description": "Multiracial people" }, { "population_served_code": "PE060000", "population_served_description": "Indigenous peoples" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PC040000", "population_served_description": "Women and girls" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" } ], "ntee_codes": [ { "ntee_code": "T20", "ntee_code_description": "Private Grantmaking Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 81132072.0, "total_expenses": 35884261.0, "total_assets": 556131508.0 }, "bmf_gross_receipts": 206204295.0, "bmf_assets": 556131508.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-27T16:25:03.0000000", "profile_last_modified": "2023-02-27T16:30:37.0000000", "dei_last_modified": "2021-11-02T16:50:27.0000000", "financials_last_modified": "2023-05-18T15:30:05.0000000", "last_modified": "2023-05-18T15:30:05.0000000" } }, { "organization": { "organization_id": "7594037", "ein": "41-0907857", "organization_name": "Lifeworks Services Inc.", "also_known_as": "Lifeworks", "group_exemption": "0000", "mission": "Our mission is to partner with people with disabilities to drive change by increasing opportunity and access in the community.", "website_url": "lifeworks.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8713129&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/41-0907857", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(651) 332-6822", "contact_title": "Vice President of Advancement", "number_of_employees": "1958", "ruling_year": 1974 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "6636 Cedar Ave S Ste 250", "address_line_2": "", "city": "Minneapolis", "state": "MN", "zip": "55423", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "District 5, MN", "county": "Hennepin, MN", "latitude": 44.8826, "longitude": -93.2479 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS090100", "subject_code_description": "Developmental disability services" }, { "subject_code": "SS090000", "subject_code_description": "Special population support" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SR040300", "subject_code_description": "Disabled persons' rights" }, { "subject_code": "SR040000", "subject_code_description": "Antidiscrimination" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" } ], "population_served_codes": [ { "population_served_code": "PH010500", "population_served_description": "People with intellectual disabilities" }, { "population_served_code": "PH010400", "population_served_description": "People with psychosocial disabilities" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD050000", "population_served_description": "Caregivers" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" } ], "ntee_codes": [ { "ntee_code": "P82", "ntee_code_description": "Developmentally Disabled Services/Centers" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 90055832.0, "total_expenses": 89120362.0, "total_assets": 41350989.0 }, "bmf_gross_receipts": 90149863.0, "bmf_assets": 41350989.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-06T11:25:40.0000000", "profile_last_modified": "2023-02-20T16:03:22.0000000", "dei_last_modified": "2023-02-14T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7785213", "ein": "52-2136842", "organization_name": "The Keith Campbell Foundation for the Environment Inc", "also_known_as": "", "group_exemption": "0000", "mission": "A family foundation that believes in strategic infusions of funding, we dedicate nearly 100% of our grant dollars to the environment. As citizens of the planet, we are compelled to participate in the protection of natural resources\\r\\nin the communities where we live.", "website_url": "http://www.campbellfoundation.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9367816&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/52-2136842", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "Ms <NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Assistant to the President", "number_of_employees": "", "ruling_year": 2000 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "410 Severn Ave", "address_line_2": "", "city": "Annapolis", "state": "MD", "zip": "21403", "msa": "MD - Baltimore", "congressional_district": "District 3, MD", "county": "Anne Arundel, MD", "latitude": 38.9716, "longitude": -76.4826 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T22", "ntee_code_description": "Private Independent Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 72039329.0, "total_expenses": 13589586.0, "total_assets": 309938612.0 }, "bmf_gross_receipts": 284609390.0, "bmf_assets": 309938612.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-27T16:48:44.0000000", "profile_last_modified": "2023-08-18T12:27:19.0000000", "dei_last_modified": "2023-08-14T00:00:00.0000000", "financials_last_modified": "2023-05-18T17:02:28.0000000", "last_modified": "2023-08-18T12:27:19.0000000" } }, { "organization": { "organization_id": "6908016", "ein": "13-1760106", "organization_name": "Rockefeller Brothers Fund, Inc.", "also_known_as": "RBF", "group_exemption": "0000", "mission": "The Rockefeller Brothers Fund advances social change that contributes to a more just, sustainable, and peaceful world.", "website_url": "www.rbf.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9358347&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-1760106", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(212) 812-4200", "contact_title": "Grants Manager, Systems and Data Analysis", "number_of_employees": "", "ruling_year": 1997 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "475 Riverside Dr Rm 900", "address_line_2": "", "city": "New York City", "state": "NY", "zip": "10115", "msa": "NY - New York, NY-NJ", "congressional_district": "District 10, NY", "county": "New York, NY", "latitude": 40.8108, "longitude": -73.9644 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T20", "ntee_code_description": "Private Grantmaking Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2021, "total_revenue": 94665303.0, "total_expenses": 90363116.0, "total_assets": 1654004790.0 }, "bmf_gross_receipts": 838386923.0, "bmf_assets": 1654004790.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-08-16T12:02:13.0000000", "profile_last_modified": "2023-08-16T12:02:13.0000000", "dei_last_modified": "2023-07-26T00:00:00.0000000", "financials_last_modified": "2023-05-18T15:30:05.0000000", "last_modified": "2023-08-16T12:02:13.0000000" } }, { "organization": { "organization_id": "8449057", "ein": "95-3169713", "organization_name": "Arnold and Mabel Beckman Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "The Arnold and Mabel Beckman Foundation makes grants to program-related, non-profit research institutions to promote research in chemistry and the life sciences, broadly interpreted, and particularly to foster the invention of methods, instruments, and materials that will open up new avenues of research in science.", "website_url": "www.beckman-foundation.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9159934&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/95-3169713", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(949) 531-0400", "contact_title": "Office Manager", "number_of_employees": "", "ruling_year": 2021 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "100 Academy", "address_line_2": "", "city": "Irvine", "state": "CA", "zip": "92617", "msa": "CA - Orange County", "congressional_district": "District 45, CA", "county": "Orange, CA", "latitude": 33.6488, "longitude": -117.8532 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SF040600", "subject_code_description": "Molecular biology" }, { "subject_code": "SF040100", "subject_code_description": "Biochemistry" }, { "subject_code": "SF040000", "subject_code_description": "Biology" }, { "subject_code": "SF030200", "subject_code_description": "Chemical engineering" }, { "subject_code": "SF030000", "subject_code_description": "Engineering" }, { "subject_code": "SF020400", "subject_code_description": "Nanotechnology" }, { "subject_code": "SF020200", "subject_code_description": "Biotechnology" }, { "subject_code": "SF020000", "subject_code_description": "Technology" }, { "subject_code": "SF010500", "subject_code_description": "Marine science" }, { "subject_code": "SF010300", "subject_code_description": "Physics" }, { "subject_code": "SF010200", "subject_code_description": "Chemistry" }, { "subject_code": "SF010000", "subject_code_description": "Physical and earth sciences" }, { "subject_code": "SF000000", "subject_code_description": "Science" }, { "subject_code": "SE151500", "subject_code_description": "Cancers" }, { "subject_code": "SE150000", "subject_code_description": "Diseases and conditions" }, { "subject_code": "SE140100", "subject_code_description": "Biomedicine" }, { "subject_code": "SE140000", "subject_code_description": "Medical specialties" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PJ050300", "population_served_description": "Researchers" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" } ], "ntee_codes": [ { "ntee_code": "T20", "ntee_code_description": "Private Grantmaking Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Private Non-Operating Foundation" }, "foundation_code": { "foundation_code": "04", "foundation_code_description": "Private nonoperating foundation" } }, "financials": { "most_recent_year": { "form_type": "PF", "fiscal_year": 2022, "total_revenue": 35282385.0, "total_expenses": 35704110.0, "total_assets": 639441907.0 }, "bmf_gross_receipts": 210210767.0, "bmf_assets": 639441907.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-28T12:31:21.0000000", "profile_last_modified": "2023-06-16T13:02:31.0000000", "dei_last_modified": "2022-04-14T11:54:54.0000000", "financials_last_modified": "2023-05-18T15:30:05.0000000", "last_modified": "2023-06-16T13:02:31.0000000" } }, { "organization": { "organization_id": "8415738", "ein": "94-3189424", "organization_name": "San Francisco General Hospital Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "The San Francisco General Hospital Foundation supports and funds excellence in patient care and innovation at Zuckerberg San Francisco General Hospital and Trauma Center (ZSFG) because we believe in equity, access, and quality health care for all.", "website_url": "https://SFGHF.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9292870&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/94-3189424", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(628) 206-5943", "contact_title": "Chief Executive Officer", "number_of_employees": "23", "ruling_year": 1994 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 410836", "address_line_2": "", "city": "San Francisco", "state": "CA", "zip": "94141", "msa": "CA - San Francisco-Oakland", "congressional_district": "District 12, CA", "county": "San Francisco, CA", "latitude": 37.7286, "longitude": -122.4311 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE130000", "subject_code_description": "Public health" }, { "subject_code": "SE040400", "subject_code_description": "Hospital care" }, { "subject_code": "SE040200", "subject_code_description": "Community health care" }, { "subject_code": "SE040000", "subject_code_description": "In-patient medical care" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "E22", "ntee_code_description": "Hospital (General)" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 18861066.0, "total_expenses": 11235838.0, "total_assets": 120086821.0 }, "bmf_gross_receipts": 346449397.0, "bmf_assets": 120086821.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-07-25T16:03:06.0000000", "profile_last_modified": "2023-07-25T16:05:26.0000000", "dei_last_modified": "2023-06-14T00:00:00.0000000", "financials_last_modified": "2023-05-09T12:06:06.0000000", "last_modified": "2023-07-25T16:05:26.0000000" } }, { "organization": { "organization_id": "9476826", "ein": "47-3681860", "organization_name": "Hopewell Fund", "also_known_as": "", "group_exemption": "0000", "mission": "THE HOPEWELL FUND IS A 501(C)(3) NONPROFIT THAT USES FISCAL SPONSORSHIP AND CHARITABLE GRANT-MAKING TO SUPPORT DOMESTIC AND INTERNATIONAL INITIATIVES AIMED AT ADVANCING PUBLIC GOOD AND ACHIEVING EQUITY FOR ALL PEOPLE.", "website_url": "https://www.hopewellfund.org/about-the-fund/", "logo_url": "", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/47-3681860", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "135", "ruling_year": 2015 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1828 L St NW", "address_line_2": "", "city": "Washington", "state": "DC", "zip": "20036", "msa": "DC - Washington, DC-MD-VA", "congressional_district": "", "county": "District of Columbia, DC", "latitude": 38.9037, "longitude": -77.0422 }, "taxonomies": { "subject_codes": [ { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" } ], "ntee_codes": [ { "ntee_code": "T12", "ntee_code_description": "Fund Raising and/or Fund Distribution" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 123385939.0, "total_expenses": 122053314.0, "total_assets": 159581623.0 }, "bmf_gross_receipts": 168691480.0, "bmf_assets": 159581623.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-24T15:26:07.0000000", "profile_last_modified": "2023-03-24T15:26:07.0000000", "dei_last_modified": "2023-03-24T00:00:00.0000000", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-05-18T15:24:48.0000000" } }, { "organization": { "organization_id": "7469372", "ein": "36-3584029", "organization_name": "UPPER MIDWEST ORGAN PROCUREMENT ORGANIZATION INC", "also_known_as": "LifeSource", "group_exemption": "0000", "mission": "LifeSource saves lives and offers hope and healing through excellence in organ, eye and tissue donation. We serve the people of Minnesota, North Dakota and South Dakota and portions of western Wisconsin.", "website_url": "www.life-source.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8536232&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/36-3584029", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>, RN MS", "leader_title": "Chief Executive Officer", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(612) 800-6100", "contact_title": "Chief Administrative Officer", "number_of_employees": "204", "ruling_year": 1989 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "2225 W River Rd", "address_line_2": "", "city": "Minneapolis", "state": "MN", "zip": "55411", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "District 5, MN", "county": "Hennepin, MN", "latitude": 45.0016, "longitude": -93.2767 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE110400", "subject_code_description": "Organ and tissue banks" }, { "subject_code": "SE110000", "subject_code_description": "Medical support services" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "E65", "ntee_code_description": "Organ and Tissue Bank" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 73448702.0, "total_expenses": 68428588.0, "total_assets": 70090155.0 }, "bmf_gross_receipts": 78587674.0, "bmf_assets": 70090155.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-19T18:29:32.0000000", "profile_last_modified": "2023-01-19T18:29:32.0000000", "dei_last_modified": "2022-12-29T13:41:22.0000000", "financials_last_modified": "2023-05-10T21:00:09.0000000", "last_modified": "2023-05-10T21:00:09.0000000" } }, { "organization": { "organization_id": "7594419", "ein": "41-1601449", "organization_name": "Feed My Starving Children", "also_known_as": "FMSC", "group_exemption": "0000", "mission": "A Christian organization with headquarters in Minnesota along with sites and events around the country, FMSCs mission is to eliminate child malnutrition worldwide while providing meaningful service opportunities for volunteers in the United States.", "website_url": "http://www.fmsc.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8565806&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/41-1601449", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(763) 267-6311", "contact_title": "Digital Marketing & Analytics Manager", "number_of_employees": "390", "ruling_year": 1989 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "401 93rd Ave NW", "address_line_2": "", "city": "Minneapolis", "state": "MN", "zip": "55433", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "", "county": "Anoka, MN", "latitude": 45.1961, "longitude": -94.8184 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SJ060400", "subject_code_description": "Disaster relief" }, { "subject_code": "SJ060000", "subject_code_description": "Disasters and emergency management" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P20", "ntee_code_description": "Human Service Organizations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 62648844.0, "total_expenses": 56099737.0, "total_assets": 39897595.0 }, "bmf_gross_receipts": 65619187.0, "bmf_assets": 38450008.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-23T12:59:12.0000000", "profile_last_modified": "2023-01-23T12:59:11.0000000", "dei_last_modified": "2023-01-23T00:00:00.0000000", "financials_last_modified": "2023-05-11T03:00:11.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "6904867", "ein": "13-0434195", "organization_name": "American Society for Technion - Israel Institute of Technology, Inc.", "also_known_as": "ATS", "group_exemption": "0000", "mission": "The American Technion Society supports the growth and success of the Technion – Israel Institute of Technology, a global innovation powerhouse. Our investments in the Technion’s research, education, and innovation efforts advance critical breakthroughs that benefit the State of Israel and the global good.With headquarters in New York City and offices around the United States, we are donors, alumni, and stakeholders who believe that when the Technion is strong, Israel is strong — and our world is a better place. We fund scholarships, research, labs, and facilities that have helped produce world-changing contributions and supported Technion for decades.", "website_url": "http://ats.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8867376&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-0434195", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "Mrs. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(212)", "contact_title": "Director of Marketing", "number_of_employees": "80", "ruling_year": 1956 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "55 E 59th St", "address_line_2": "", "city": "New York City", "state": "NY", "zip": "10022", "msa": "NY - New York, NY-NJ", "congressional_district": "District 12, NY", "county": "New York, NY", "latitude": 40.7633, "longitude": -73.9708 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP070000", "subject_code_description": "Judaism" }, { "subject_code": "SP000000", "subject_code_description": "Religion" }, { "subject_code": "SF030000", "subject_code_description": "Engineering" }, { "subject_code": "SF000000", "subject_code_description": "Science" }, { "subject_code": "SB060000", "subject_code_description": "Graduate and professional education" }, { "subject_code": "SB050300", "subject_code_description": "University education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B43", "ntee_code_description": "University or Technological" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 98767366.0, "total_expenses": 81453814.0, "total_assets": 629417045.0 }, "bmf_gross_receipts": 166775797.0, "bmf_assets": 629417045.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-27T08:24:39.0000000", "profile_last_modified": "2023-03-28T11:25:22.0000000", "dei_last_modified": "2021-05-14T14:35:39.0000000", "financials_last_modified": "2023-05-10T07:00:16.0000000", "last_modified": "2023-05-10T07:00:16.0000000" } } ] } ``` ## Search for organizations by the last time their data was updated Search for new data as it happens. Below is an example search for any updates that occurred between November 1st and December 1st of 2022. ``` { "filters": { "last_updated": { "start_date": "2022-11-01T01:01:01:01", "end_date": "2022-12-01T01:01:01:01", "date_type": "last_modified" } } } ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 121, "time": "2023-08-29 18:35:16Z", "results_count": 34663, "page_count": 1387, "errors": [], "hits": [ { "organization": { "organization_id": "9518643", "ein": "47-5339264", "organization_name": "SOCIETY OF FRIENDS OF FORT OSAGE", "also_known_as": "", "group_exemption": "0000", "mission": "\"The Society of Friends of Fort Osage was formed as a non profit corporation to support Fort Osage National Historic Landmark. Our mission is to raise awareness through financial support; striving to preserve, protect, and interpret the physical, structural, and cultural heritage of Fort Osage.”", "website_url": "fortosagenhs.com", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7882028&approved=True", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/47-5339264", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "President", "number_of_employees": "", "ruling_year": 2016 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3828 Blue Ridge Blvd", "address_line_2": "", "city": "Independence", "state": "MO", "zip": "64052", "msa": "MO - Kansas City, MO-KS", "congressional_district": "District 5, MO", "county": "Jackson, MO", "latitude": 39.0536, "longitude": -94.4494 }, "taxonomies": { "subject_codes": [ { "subject_code": "SA090000", "subject_code_description": "Historical activities" }, { "subject_code": "SA070400", "subject_code_description": "History museums" }, { "subject_code": "SA070000", "subject_code_description": "Museums" }, { "subject_code": "SA020000", "subject_code_description": "Folk arts" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PD050000", "population_served_description": "Caregivers" }, { "population_served_code": "PD040000", "population_served_description": "Non-adult children" }, { "population_served_code": "PD030000", "population_served_description": "Widows and widowers" }, { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "A54", "ntee_code_description": "History Museums" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-06-17T12:45:28.0000000", "profile_last_modified": "2022-06-17T12:45:28.0000000", "dei_last_modified": "2022-06-17T11:21:32.0000000", "financials_last_modified": "", "last_modified": "2022-11-15T12:27:00.0000000" } }, { "organization": { "organization_id": "8003263", "ein": "62-6283662", "organization_name": "Mark Collie Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "Our mission is to raise awareness and funds for Type One Diabetes by supporting educational programs and advancement of research. We are dedicated to finding a cure.", "website_url": "", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8375911&approved=True", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/62-6283662", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Director of Operations", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(615) 517-1413", "contact_title": "Director of Operations", "number_of_employees": "", "ruling_year": 2020 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "201 Ruth Way", "address_line_2": "", "city": "Spring Hill", "state": "TN", "zip": "37174", "msa": "", "congressional_district": "District 4, TN", "county": "Maury, TN", "latitude": 35.742, "longitude": -86.905 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "E99", "ntee_code_description": "Health - General and Rehabilitative N.E.C." } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-29T10:12:40.0000000", "profile_last_modified": "2022-11-29T10:12:40.0000000", "dei_last_modified": "2022-11-29T09:08:26.0000000", "financials_last_modified": "", "last_modified": "2022-11-29T10:12:40.0000000" } }, { "organization": { "organization_id": "9855939", "ein": "84-3468961", "organization_name": "Lifeology AZ Inc", "also_known_as": "", "group_exemption": "0000", "mission": "Lifeology AZ's mission is to end youth homelessness by learning, growing and creating intentional communities where young people can live and thrive", "website_url": "http://www.lifeologyaz.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8299151&approved=True", "profile_level": "Silver", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/84-3468961", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2022-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>@life<EMAIL>", "contact_phone": "(602) 321-9393", "contact_title": "", "number_of_employees": "", "ruling_year": 2019 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3718 North 62nd Avenue", "address_line_2": "", "city": "Phoenix", "state": "AZ", "zip": "85043", "msa": "AZ - Phoenix-Mesa", "congressional_district": "District 7, AZ", "county": "Maricopa, AZ", "latitude": 33.4264, "longitude": -112.2036 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" } ], "population_served_codes": [ { "population_served_code": "PG030100", "population_served_description": "Homeless people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O50", "ntee_code_description": "Youth Development Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-05T11:57:14.0000000", "profile_last_modified": "2022-11-05T12:02:26.0000000", "dei_last_modified": "2022-11-05T08:39:47.0000000", "financials_last_modified": "", "last_modified": "2022-11-05T12:02:26.0000000" } }, { "organization": { "organization_id": "7197359", "ein": "23-7281878", "organization_name": "Price-Anderson Post 341, Veterans of Foreign Wars of the U.S.", "also_known_as": "VFW Price Anderson Post 341", "group_exemption": "1831", "mission": "Our mission is to 'honor the dead by helping the living' through veterans' service, community service, national security and a strong national defense.", "website_url": "www.vfw341.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7249251&approved=True", "profile_level": "Bronze", "profile_year": 2021, "profile_link": "https://www.guidestar.org/profile/23-7281878", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2021-seal.svg", "leader_name": "<NAME>", "leader_title": "Commander", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(202) 388-0900", "contact_title": "Commander", "number_of_employees": "", "ruling_year": 1967 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "1601 Kenilworth Ave NE", "address_line_2": "", "city": "Washington", "state": "DC", "zip": "20019", "msa": "DC - Washington, DC-MD-VA", "congressional_district": "", "county": "District of Columbia, DC", "latitude": 38.8914, "longitude": -76.936 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS090000", "subject_code_description": "Special population support" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ090000", "population_served_description": "Emergency responders" }, { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ060000", "population_served_description": "Military personnel" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" } ], "ntee_codes": [ { "ntee_code": "W30", "ntee_code_description": "Military/Veterans' Organizations" } ], "subsection_code": { "subsection_code": "19", "subsection_code_description": "501(c)(19) Post or Organizations of War Veterans" }, "foundation_code": { "foundation_code": "00", "foundation_code_description": "All organizations except 501(c)(3)" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2021-10-28T08:21:57.0000000", "profile_last_modified": "2021-11-08T13:59:52.0000000", "dei_last_modified": "2021-10-28T08:19:52.0000000", "financials_last_modified": "", "last_modified": "2022-11-15T12:27:00.0000000" } }, { "organization": { "organization_id": "10099763", "ein": "04-2192690", "organization_name": "First Community United Methodist Church of Medford", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/04-2192690", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1905 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "55 Otis St", "address_line_2": "", "city": "Medford", "state": "MA", "zip": "02155", "msa": "MA - Boston", "congressional_district": "District 5, MA", "county": "Middlesex, MA", "latitude": 42.4191, "longitude": -71.0964 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:07.0000000", "profile_last_modified": "2022-11-03T04:02:07.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:07.0000000" } }, { "organization": { "organization_id": "10099764", "ein": "04-3306707", "organization_name": "Wesley United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/04-3306707", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "98 N Maple St", "address_line_2": "", "city": "Hadley", "state": "MA", "zip": "01035", "msa": "MA - Springfield", "congressional_district": "District 2, MA", "county": "Hampshire, MA", "latitude": 42.3739, "longitude": -72.549 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:08.0000000", "profile_last_modified": "2022-11-03T04:02:08.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:08.0000000" } }, { "organization": { "organization_id": "10099762", "ein": "03-0459553", "organization_name": "<NAME>ley United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/03-0459553", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>.", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "3817 Philadelphia Rd", "address_line_2": "", "city": "Abingdon", "state": "MD", "zip": "21009", "msa": "MD - Baltimore", "congressional_district": "District 2, MD", "county": "Harford, MD", "latitude": 39.4675, "longitude": -76.2732 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:06.0000000", "profile_last_modified": "2022-11-03T04:02:06.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:06.0000000" } }, { "organization": { "organization_id": "10099765", "ein": "14-1558076", "organization_name": "Pawling Avenue United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/14-1558076", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "520 Pawling Ave", "address_line_2": "", "city": "Troy", "state": "NY", "zip": "12180", "msa": "NY - Albany-Schenectady-Troy", "congressional_district": "District 20, NY", "county": "Rensselaer, NY", "latitude": 42.7059, "longitude": -73.6607 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:09.0000000", "profile_last_modified": "2022-11-03T04:02:09.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:09.0000000" } }, { "organization": { "organization_id": "9265219", "ein": "46-2616110", "organization_name": "Tech4Ghana USA Inc", "also_known_as": "", "group_exemption": "0000", "mission": "Tech4Ghana USA supports the campus of Tech4Ghana in Wli, Ghana. Tech4Ghana promotes the welfare of the local community by providing computer resources and English language books for education of school-age girls and boys. In addition, Tech4Ghana provides a source of clean water and food to the community.", "website_url": "http://www.tech4ghana.com", "logo_url": "", "profile_level": "Bronze", "profile_year": 2021, "profile_link": "https://www.guidestar.org/profile/46-2616110", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2021-seal.svg", "leader_name": "<NAME>", "leader_title": "Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Director", "number_of_employees": "", "ruling_year": 2013 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "180 Dekalb Ave Apt 5", "address_line_2": "", "city": "Brooklyn", "state": "NY", "zip": "11205", "msa": "NY - New York, NY-NJ", "congressional_district": "District 8, NY", "county": "Kings, NY", "latitude": 40.6896, "longitude": -73.9729 }, "taxonomies": { "subject_codes": [ { "subject_code": "ST040000", "subject_code_description": "International development" }, { "subject_code": "ST000000", "subject_code_description": "International relations" }, { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB090300", "subject_code_description": "Computer literacy" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB030900", "subject_code_description": "Child educational development" }, { "subject_code": "SB030500", "subject_code_description": "Bilingual education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD010100", "population_served_description": "Families of origin" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "Q30", "ntee_code_description": "International Development, Relief Services" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2021-10-15T14:37:19.0000000", "profile_last_modified": "2021-10-15T14:37:19.0000000", "dei_last_modified": "2021-10-14T12:11:43.0000000", "financials_last_modified": "", "last_modified": "2022-11-15T12:27:00.0000000" } }, { "organization": { "organization_id": "10099801", "ein": "46-1201316", "organization_name": "Christ Fellowship United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/46-1201316", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "10915 Shaenfield Rd", "address_line_2": "", "city": "San Antonio", "state": "TX", "zip": "78254", "msa": "TX - San Antonio", "congressional_district": "District 20, TX", "county": "Bexar, TX", "latitude": 29.5199, "longitude": -98.707 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:50.0000000", "profile_last_modified": "2022-11-03T04:02:50.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:50.0000000" } }, { "organization": { "organization_id": "9329598", "ein": "46-3918415", "organization_name": "Liveliving International Foundation", "also_known_as": "TRANSFORMATIONAL LIVING", "group_exemption": "0000", "mission": "Our mission is to equip people of faith to experience the abundant life of the Kingdom of God in body, mind, and spirit.We will deliver online courses with group coaching that demonstrate how to achieve health and wellbeing by integrating:*scientific knowledge about the body, mind and spirit,*lifestyle modification tools, and*Christian mindfulness.", "website_url": "https://liveliving.org/", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/46-3918415", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2014 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "4651 Woodstock Rd PMB 227", "address_line_2": "", "city": "Roswell", "state": "GA", "zip": "30075", "msa": "GA - Atlanta", "congressional_district": "District 6, GA", "county": "Cobb, GA", "latitude": 34.0622, "longitude": -84.4209 }, "taxonomies": { "subject_codes": [ { "subject_code": "SH040300", "subject_code_description": "Publishing" }, { "subject_code": "SH040000", "subject_code_description": "Communication media" }, { "subject_code": "SH000000", "subject_code_description": "Information and communications" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" }, { "subject_code": "SE151104", "subject_code_description": "Stress" }, { "subject_code": "SE151100", "subject_code_description": "Mental and behavioral disorders" }, { "subject_code": "SE150000", "subject_code_description": "Diseases and conditions" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PF010000", "population_served_description": "Christians" }, { "population_served_code": "PF000000", "population_served_description": "Religious groups" } ], "ntee_codes": [ { "ntee_code": "X83", "ntee_code_description": "Religious Printing, Publishing" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-02T11:18:20.0000000", "profile_last_modified": "2022-11-02T11:18:20.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-02T11:18:20.0000000" } }, { "organization": { "organization_id": "10099795", "ein": "42-1340411", "organization_name": "<NAME> United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/42-1340411", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "12321 Hickman Rd", "address_line_2": "", "city": "Urbandale", "state": "IA", "zip": "50323", "msa": "IA - Des Moines", "congressional_district": "", "county": "Polk, IA", "latitude": 41.6149, "longitude": -93.787 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:43.0000000", "profile_last_modified": "2022-11-03T04:02:43.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:43.0000000" } }, { "organization": { "organization_id": "10099797", "ein": "42-6005715", "organization_name": "First United Methodist Church of Red Oak", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/42-6005715", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "600 E Hammond St", "address_line_2": "", "city": "Red Oak", "state": "IA", "zip": "51566", "msa": "", "congressional_district": "", "county": "Montgomery, IA", "latitude": 41.0105, "longitude": -95.2255 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:45.0000000", "profile_last_modified": "2022-11-03T04:02:45.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:45.0000000" } }, { "organization": { "organization_id": "10099800", "ein": "43-0729624", "organization_name": "Trinity United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/43-0729624", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1928 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "300 S Main St", "address_line_2": "", "city": "Brookfield", "state": "MO", "zip": "64628", "msa": "", "congressional_district": "District 6, MO", "county": "Linn, MO", "latitude": 39.782, "longitude": -93.0725 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:48.0000000", "profile_last_modified": "2022-11-03T04:02:48.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:48.0000000" } }, { "organization": { "organization_id": "9416872", "ein": "47-1130849", "organization_name": "Will Grant Vision Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "We work to preserve a basic human right to health and wellness by engaging individuals who suffer from preventable vision loss due to limitations in information and access to adequate vision care services.By changing what people see, we aspire to change what they can do.We work towards 2020.", "website_url": "https://willgrantvision.com/", "logo_url": "", "profile_level": "Bronze", "profile_year": 2021, "profile_link": "https://www.guidestar.org/profile/47-1130849", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2021-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2015 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "315 W 5th St Apt 404", "address_line_2": "", "city": "Los Angeles", "state": "CA", "zip": "90013", "msa": "CA - Los Angeles-Long Beach", "congressional_district": "District 34, CA", "county": "Los Angeles, CA", "latitude": 34.0481, "longitude": -118.2508 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "E99", "ntee_code_description": "Health - General and Rehabilitative N.E.C." } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2021-09-21T16:13:22.0000000", "profile_last_modified": "2021-09-21T16:13:22.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-15T12:27:00.0000000" } }, { "organization": { "organization_id": "10099796", "ein": "42-1558939", "organization_name": "<NAME>'s United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/42-1558939", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "25187 Signboard Rd", "address_line_2": "", "city": "Ruther Glen", "state": "VA", "zip": "22546", "msa": "", "congressional_district": "", "county": "Caroline, VA", "latitude": 37.9172, "longitude": -77.3936 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:44.0000000", "profile_last_modified": "2022-11-03T04:02:44.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:44.0000000" } }, { "organization": { "organization_id": "10099799", "ein": "43-0687401", "organization_name": "Palmyra United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/43-0687401", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "120 W Olive St", "address_line_2": "", "city": "Palmyra", "state": "MO", "zip": "63461", "msa": "", "congressional_district": "District 6, MO", "county": "Marion, MO", "latitude": 39.7979, "longitude": -91.5233 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:47.0000000", "profile_last_modified": "2022-11-03T04:02:47.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:47.0000000" } }, { "organization": { "organization_id": "10099867", "ein": "43-1310937", "organization_name": "The Table United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/43-1310937", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2022 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "3609 SW State Route 7", "address_line_2": "", "city": "Blue Springs", "state": "MO", "zip": "64014", "msa": "MO - Kansas City, MO-KS", "congressional_district": "District 5, MO", "county": "Jackson, MO", "latitude": 39.0146, "longitude": -94.2605 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:49.0000000", "profile_last_modified": "2022-11-03T04:02:49.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:49.0000000" } }, { "organization": { "organization_id": "9207038", "ein": "45-3868994", "organization_name": "CHIME IN MUSIC WITH A MISSION INC", "also_known_as": "We Sing! Children's Choir of Connecticut", "group_exemption": "0000", "mission": "Our invitation's in our name: <NAME>!Arising from our origins as a family of handbell choirs, our mission is to engage people in the joy and sense of community that music fosters through participation and performance. So our handbell concerts are interactive and include a time for our audience and supporters to chime in through interactive Q&A sessions, audience participation with voices and instruments, and the after-concert petting zoo to sample all the instruments. Our home base is Bethlehem, CT, but we share our handbell music at a diversity of settings and venues, near and far, throughout the year. From Main Stage at the Bethlehem Fair to the New Haven International Festival of Arts & Ideas to Carnegie Hall to local nursing homes, from collaborative concerts with choral and orchestral groups to hosting local choirs and community musicians for an annual Ring & Sing Community Music Day, we are passionate about making and sharing our music to build community.", "website_url": "www.chimeinmusic.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7564381&approved=True", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/45-3868994", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "Director of Music", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(860) 631-3246", "contact_title": "Director of Music", "number_of_employees": "", "ruling_year": 2012 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 21", "address_line_2": "", "city": "Bethlehem", "state": "CT", "zip": "06751", "msa": "CT - Waterbury", "congressional_district": "District 5, CT", "county": "Litchfield, CT", "latitude": 41.6414, "longitude": -73.2126 }, "taxonomies": { "subject_codes": [ { "subject_code": "SA060300", "subject_code_description": "Music" }, { "subject_code": "SA060000", "subject_code_description": "Performing arts" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "A68", "ntee_code_description": "Music" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-02-20T10:32:31.0000000", "profile_last_modified": "2022-02-20T10:34:59.0000000", "dei_last_modified": "2022-02-20T10:31:54.0000000", "financials_last_modified": "", "last_modified": "2022-11-15T12:27:00.0000000" } }, { "organization": { "organization_id": "10099804", "ein": "54-0592600", "organization_name": "Grace United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/54-0592600", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "18484 Wilson Ave", "address_line_2": "", "city": "Parksley", "state": "VA", "zip": "23421", "msa": "", "congressional_district": "District 2, VA", "county": "Accomack, VA", "latitude": 37.7802, "longitude": -75.6325 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:53.0000000", "profile_last_modified": "2022-11-03T04:02:53.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:53.0000000" } }, { "organization": { "organization_id": "10099805", "ein": "54-1641387", "organization_name": "Oakland United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/54-1641387", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "121 Piccadilly Ct", "address_line_2": "", "city": "Goode", "state": "VA", "zip": "24556", "msa": "VA - Lynchburg", "congressional_district": "District 6, VA", "county": "Bedford, VA", "latitude": 37.3215, "longitude": -79.3849 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:54.0000000", "profile_last_modified": "2022-11-03T04:02:54.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:54.0000000" } }, { "organization": { "organization_id": "10099802", "ein": "48-0543753", "organization_name": "First United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/48-0543753", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "600 SW Topeka Blvd", "address_line_2": "", "city": "Topeka", "state": "KS", "zip": "66603", "msa": "KS - Topeka", "congressional_district": "District 2, KS", "county": "Shawnee, KS", "latitude": 39.0532, "longitude": -95.679 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:51.0000000", "profile_last_modified": "2022-11-03T04:02:51.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:51.0000000" } }, { "organization": { "organization_id": "7741879", "ein": "51-0528695", "organization_name": "Northeast Pyr Rescue", "also_known_as": "", "group_exemption": "0000", "mission": "NEPR's RoleNEPR helps families place dogs when they can no longer keep them. In addition, we work with shelters and veterinarians when Pyrs are lost, abandoned, neglected or surrendered.Interested families must complete an application and the application is reviewed by the geographically closest NEPR volunteer. The volunteer will contact the applicant by phone to discuss the application and establish a time for a home visit. Home visits are required.Rescue and Re-homing –We provide rescue care for Great Pyrenees dogs that are lost, abandoned, neglected or surrendered and place them in loving permanent homes. In many instances the dogs have lived with attentive and loving families but due to difficult circumstances, such as divorce or owner death, the Pyr needs to find a new home.", "website_url": "http://nepyresq.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/51-0528695", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2006 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 704", "address_line_2": "", "city": "Lee", "state": "MA", "zip": "01238", "msa": "MA - Pittsfield", "congressional_district": "District 1, MA", "county": "Berkshire, MA", "latitude": 42.302, "longitude": -73.2455 }, "taxonomies": { "subject_codes": [ { "subject_code": "SC050103", "subject_code_description": "Animal rescue and rehabilitation" }, { "subject_code": "SC050100", "subject_code_description": "Animal welfare" }, { "subject_code": "SC050000", "subject_code_description": "Domesticated animals" }, { "subject_code": "SC000000", "subject_code_description": "Environment" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "D20", "ntee_code_description": "Animal Protection and Welfare (includes Humane Societies and SPCAs)" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-05T23:00:34.0000000", "profile_last_modified": "2022-11-05T23:00:34.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-05T23:00:34.0000000" } }, { "organization": { "organization_id": "10099803", "ein": "51-1665359", "organization_name": "Limona Village Chapel United Methodist Church", "also_known_as": "", "group_exemption": "2573", "mission": "The mission of the church is to make disciples of Jesus Christ for the transformation of the world.", "website_url": "www.umc.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/51-1665359", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "408 Limona Rd", "address_line_2": "", "city": "Brandon", "state": "FL", "zip": "33510", "msa": "FL - Tampa-St. Petersburg-Clearwater", "congressional_district": "District 15, FL", "county": "Hillsborough, FL", "latitude": 27.9437, "longitude": -82.3042 }, "taxonomies": { "subject_codes": [ { "subject_code": "SP030104", "subject_code_description": "Methodism" }, { "subject_code": "SP030100", "subject_code_description": "Protestantism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": null, "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-11-03T04:02:52.0000000", "profile_last_modified": "2022-11-03T04:02:52.0000000", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-11-03T04:02:52.0000000" } }, { "organization": { "organization_id": "9124837", "ein": "51-0678318", "organization_name": "Veterans of Foreign Wars of the United States Auxiliary Department", "also_known_as": "VFW Post 1087 Auxiliary", "group_exemption": "5790", "mission": "To foster camaraderie among United States veterans of overseas conflicts. To serve our veterans, the military and our communities. To advocate on behalf of all veterans.", "website_url": "", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7557083&approved=True", "profile_level": "Bronze", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/51-0678318", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2022-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 2010 }, "properties": { "bmf_status": true, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "305 52nd St S", "address_line_2": "", "city": "Great Falls", "state": "MT", "zip": "59405", "msa": "MT - Great Falls", "congressional_district": "", "county": "Cascade, MT", "latitude": 47.5015, "longitude": -111.2208 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS090000", "subject_code_description": "Special population support" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ060000", "population_served_description": "Military personnel" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" } ], "ntee_codes": [ { "ntee_code": "W30", "ntee_code_description": "Military/Veterans' Organizations" } ], "subsection_code": { "subsection_code": "19", "subsection_code_description": "501(c)(19) Post or Organizations of War Veterans" }, "foundation_code": { "foundation_code": "00", "foundation_code_description": "All organizations except 501(c)(3)" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2022-02-17T14:26:28.0000000", "profile_last_modified": "2022-02-17T14:26:28.0000000", "dei_last_modified": "2022-02-17T12:24:23.0000000", "financials_last_modified": "", "last_modified": "2022-11-15T12:27:00.0000000" } } ] } ``` Pass through the appropriate date type to use in the example above for different results. Date Type | Approx. number of updates per month | Type of updates included | | --- | --- | --- | | 6,800 | Changes in Seal of Transparency level | | 7,000 | Updates to information on the Candid profile | | 2,000 | Changes to demographic data on the Candid profile | | 29,000 | New financial document received | | 36,000 | All updates listed above | ``` { "code": 200, "message": "Request was processed successfully!", "took": 3293, "time": "2023-08-29 18:35:59Z", "results_count": 1356209, "page_count": 54249, "errors": [], "hits": [ { "organization": { "organization_id": "7690060", "ein": "47-0376531", "organization_name": "Clarkson Regional Health Services Inc", "also_known_as": "", "group_exemption": "0000", "mission": "PROVIDING EDUCATIONAL AND TRAINING PROGRAMS.CORPORATION WHOSE PURPOSE IS TO ESTABLISH AND MAINTAIN, DIRECTLY OR INDIRECTLY, INSTITUTIONS TO PROVIDE FOR THE ECONOMICAL AND EFFICIENT DELIVERY OF HEALTHCARE AND RELATED SERVICES, INCLUDING PROVIDING EDUCATIONAL AND TRAINING PROGRAMS.", "website_url": "www.clarksonregionl.com", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8858064&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/47-0376531", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "COO and General Counsel", "number_of_employees": "11", "ruling_year": 1937 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "9300 Underwood Ave Ste 110", "address_line_2": "", "city": "Omaha", "state": "NE", "zip": "68114", "msa": "NE - Omaha, NE-IA", "congressional_district": "District 2, NE", "county": "Douglas, NE", "latitude": 41.2652, "longitude": -96.0597 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE040200", "subject_code_description": "Community health care" }, { "subject_code": "SE040000", "subject_code_description": "In-patient medical care" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "E21", "ntee_code_description": "Community Health Systems" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 34472396.0, "total_expenses": 15893021.0, "total_assets": 891078928.0 }, "bmf_gross_receipts": 443571958.0, "bmf_assets": 891078928.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-24T14:08:51.0000000", "profile_last_modified": "2023-03-24T14:09:55.0000000", "dei_last_modified": "2023-03-24T13:05:39.0000000", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-06-23T11:00:41.0000000" } }, { "organization": { "organization_id": "9300272", "ein": "46-0942102", "organization_name": "The Blackbaud Giving Fund", "also_known_as": "", "group_exemption": "0000", "mission": "The Blackbaud Giving Fund unleashes generosity by connecting people to causes they care about around the world. We leverage our donor advised fund to help people easily distribute grants.", "website_url": "https://www.blackbaudgivingfund.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8718577&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/46-0942102", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(843) 654-2079", "contact_title": "Executive Director", "number_of_employees": "1", "ruling_year": 2014 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "65 Fairchild St", "address_line_2": "", "city": "Daniel Island", "state": "SC", "zip": "29492", "msa": "SC - Charleston-North Charleston", "congressional_district": "District 1, SC", "county": "Berkeley, SC", "latitude": 32.8917, "longitude": -79.9053 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PF000000", "population_served_description": "Religious groups" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" } ], "ntee_codes": [ { "ntee_code": "T12", "ntee_code_description": "Fund Raising and/or Fund Distribution" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 653475747.0, "total_expenses": 635429927.0, "total_assets": 82255396.0 }, "bmf_gross_receipts": 653475747.0, "bmf_assets": 82255396.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-21T16:48:24.0000000", "profile_last_modified": "2023-02-21T16:48:24.0000000", "dei_last_modified": "2022-01-20T09:24:56.0000000", "financials_last_modified": "2023-04-21T07:03:04.0000000", "last_modified": "2023-04-21T07:03:04.0000000" } }, { "organization": { "organization_id": "7171676", "ein": "23-7166534", "organization_name": "Texas A&M University-Kingsville Foundation, Inc", "also_known_as": "", "group_exemption": "0000", "mission": "To build private support for the mission and vision of Texas A&M University Kingsville, and to be a vital partner with Texas A&M University-Kingsville by developing donor relationships and linking resources in the pursuit of the University's goals of excellence.", "website_url": "https://www.javelinagiving.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9362636&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/23-7166534", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Foundation CEO", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(361) 593-3918", "contact_title": "Foundation CEO", "number_of_employees": "9", "ruling_year": 1972 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 2202", "address_line_2": "", "city": "Kingsville", "state": "TX", "zip": "78363", "msa": "", "congressional_district": "District 34, TX", "county": "Kleberg, TX", "latitude": 27.5122, "longitude": -97.8626 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB050300", "subject_code_description": "University education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B11", "ntee_code_description": "Single Organization Support" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "13", "foundation_code_description": "Organization which operates for benefit of college or university and is owned or operated by a governmental unit." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 50309350.0, "total_expenses": 5700031.0, "total_assets": 124964662.0 }, "bmf_gross_receipts": 132284619.0, "bmf_assets": 124964662.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-04-27T11:03:28.0000000", "profile_last_modified": "2023-08-17T11:10:09.0000000", "dei_last_modified": "2022-05-26T00:00:00.0000000", "financials_last_modified": "2023-05-18T18:49:03.0000000", "last_modified": "2023-08-17T11:10:09.0000000" } }, { "organization": { "organization_id": "8619203", "ein": "26-2291955", "organization_name": "Veteran Tickets Foundation", "also_known_as": "Vet Tix", "group_exemption": "0000", "mission": "Veteran Tickets Foundation - ( Vet Tix - 1st Tix ) provides tickets to events which reduce stress, strengthen family bonds, build life-long memories and encourage service members, veterans and first responders to stay engaged with local communities and American life.( Vet Tix - 1st Tix ) provides tickets to all branches of currently-serving Military, Veterans, including immediate family of troops KIA and first responders.( Vet Tix - 1st Tix ) secures tickets to sporting events, concerts, performing arts, educational and family activities across the nation. VetTixers and 1stTixers sign up online. We verify their service. VetTixers and 1stTixers request tickets to events that interest them, then pay a small delivery fee to receive themwww.VetTix.orgwww.1stTix.org", "website_url": "www.vettix.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8998927&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/26-2291955", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(602)", "contact_title": "Chief Executive Officer", "number_of_employees": "27", "ruling_year": 2010 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "1255 W Rio Salado Pkwy Ste 209", "address_line_2": "", "city": "Tempe", "state": "AZ", "zip": "85281", "msa": "AZ - Phoenix-Mesa", "congressional_district": "District 9, AZ", "county": "Maricopa, AZ", "latitude": 33.4308, "longitude": -111.9573 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS090000", "subject_code_description": "Special population support" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PJ090000", "population_served_description": "Emergency responders" }, { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ060000", "population_served_description": "Military personnel" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" } ], "ntee_codes": [ { "ntee_code": "W30", "ntee_code_description": "Military/Veterans' Organizations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 171576223.0, "total_expenses": 168227690.0, "total_assets": 6785734.0 }, "bmf_gross_receipts": 171576223.0, "bmf_assets": 6785734.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-28T11:57:54.0000000", "profile_last_modified": "2023-05-09T11:39:27.0000000", "dei_last_modified": "2021-04-13T15:32:51.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7327118", "ein": "31-1118357", "organization_name": "North Central Health Services Inc", "also_known_as": "", "group_exemption": "0000", "mission": "THE ORGANIZATION IS COMMITTED TO ADVANCING AND PROVIDING HEALTH CARE FOR THE BENEFIT OF THE CITIZENS OF ITS EIGHT COUNTY SERVICE AREA. CONTINUE ON SCHEDULE O:THROUGH THE SUPPORT OF TECHNOLOGICAL AND SCIENTIFIC ADVANCEMENT, EDUCATION, QUALITY OF LIFE, AND HUMANITARIAN COMMUNITY SERVICES, NCHS WILL STRIVE TO PROMOTE A HEALTHY COMMUNITY FOR ALL AREA RESIDENTS.", "website_url": "http://WWW.NCHSI.COM", "logo_url": "", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/31-1118357", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "4", "ruling_year": 1985 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2900 N River Rd", "address_line_2": "", "city": "West Lafayette", "state": "IN", "zip": "47906", "msa": "IN - Lafayette", "congressional_district": "District 4, IN", "county": "Tippecanoe, IN", "latitude": 40.4593, "longitude": -86.8925 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE040200", "subject_code_description": "Community health care" }, { "subject_code": "SE040000", "subject_code_description": "In-patient medical care" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "E21", "ntee_code_description": "Community Health Systems" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "12", "foundation_code_description": "Hospital or medical research organization" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 65454732.0, "total_expenses": 14494198.0, "total_assets": 519937079.0 }, "bmf_gross_receipts": 824677582.0, "bmf_assets": 519937079.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-07-13T09:42:17.0000000", "profile_last_modified": "2023-07-13T09:45:39.0000000", "dei_last_modified": "", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-07-13T09:45:39.0000000" } }, { "organization": { "organization_id": "7384109", "ein": "33-0841281", "organization_name": "PANCREATIC CANCER ACTION NETWORK INC", "also_known_as": "Pancreatic Cancer Action Network", "group_exemption": "0000", "mission": "Our mission is to take bold action to improve the lives of everyone impacted by pancreatic cancer by advancing scientific research, building community, sharing knowledge and advocating for patients.PanCAN's vision is to create a world in which all patients with pancreatic cancer will thrive.", "website_url": "www.pancan.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8725803&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/33-0841281", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>, JD, MBA", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(310) 725-0025", "contact_title": "", "number_of_employees": "191", "ruling_year": 1999 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1500 Rosecrans Ave Ste 200", "address_line_2": "", "city": "Manhattan Beach", "state": "CA", "zip": "90266", "msa": "CA - Los Angeles-Long Beach", "congressional_district": "", "county": "Los Angeles, CA", "latitude": 33.9019, "longitude": -118.3869 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE151503", "subject_code_description": "Pancreatic cancer" }, { "subject_code": "SE151500", "subject_code_description": "Cancers" }, { "subject_code": "SE150000", "subject_code_description": "Diseases and conditions" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "E01", "ntee_code_description": "Alliance/Advocacy Organizations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 52930843.0, "total_expenses": 52685332.0, "total_assets": 68159698.0 }, "bmf_gross_receipts": 65937316.0, "bmf_assets": 68159698.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-23T09:28:28.0000000", "profile_last_modified": "2023-02-23T09:28:28.0000000", "dei_last_modified": "2022-04-18T10:15:43.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-05-18T18:57:25.0000000" } }, { "organization": { "organization_id": "7408070", "ein": "34-1964742", "organization_name": "Christian Healthcare Ministries Inc.", "also_known_as": "", "group_exemption": "0000", "mission": "The mission of Christian Healthcare Ministries is to glorify God, show Christian love, and experience God's presence as Christians share each other's medical bills.", "website_url": "www.chministries.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9222993&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/34-1964742", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(800) 791-6225", "contact_title": "Chief Financial Officer", "number_of_employees": "379", "ruling_year": 2003 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "127 Hazelwood Ave", "address_line_2": "", "city": "Barberton", "state": "OH", "zip": "44203", "msa": "OH - Akron", "congressional_district": "District 13, OH", "county": "Summit, OH", "latitude": 41.0336, "longitude": -81.5842 }, "taxonomies": { "subject_codes": [ { "subject_code": "SZ000000", "subject_code_description": "Unknown or not classified" }, { "subject_code": "SE030300", "subject_code_description": "Health care financing" }, { "subject_code": "SE030000", "subject_code_description": "Health care administration and financing" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PJ030000", "population_served_description": "Self-employed people" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PF010000", "population_served_description": "Christians" }, { "population_served_code": "PF000000", "population_served_description": "Religious groups" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "Z99", "ntee_code_description": "Unknown" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 752912401.0, "total_expenses": 723408757.0, "total_assets": 164612180.0 }, "bmf_gross_receipts": 754413355.0, "bmf_assets": 164612180.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-07-03T09:38:20.0000000", "profile_last_modified": "2023-07-03T09:40:46.0000000", "dei_last_modified": "2020-07-16T12:54:01.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-07-03T09:40:46.0000000" } }, { "organization": { "organization_id": "7799367", "ein": "52-6001143", "organization_name": "Enoch Pratt Free Library of Baltimore City", "also_known_as": "the Pratt", "group_exemption": "0000", "mission": "Our mission is to empower, enrich, and enhance the quality of life for all through equitable access to information, services, and opportunity. For all, rich and poor, without distinction of race or color (Enoch Pratt, 1882)", "website_url": "www.prattlibrary.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8878776&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/52-6001143", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & Chief Executive Officer", "contact_name": "Mrs. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(410) 396-5314", "contact_title": "Director of Institutional Advancement", "number_of_employees": "54", "ruling_year": 1976 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "400 Cathedral St", "address_line_2": "", "city": "Baltimore", "state": "MD", "zip": "21201", "msa": "MD - Baltimore", "congressional_district": "District 7, MD", "county": "Baltimore City, MD", "latitude": 39.2941, "longitude": -76.6169 }, "taxonomies": { "subject_codes": [ { "subject_code": "SH020400", "subject_code_description": "Public libraries" }, { "subject_code": "SH020000", "subject_code_description": "Libraries" }, { "subject_code": "SH000000", "subject_code_description": "Information and communications" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010100", "population_served_description": "Infants and toddlers" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B70", "ntee_code_description": "Libraries, Library Science" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 51102300.0, "total_expenses": 59176700.0, "total_assets": 214992500.0 }, "bmf_gross_receipts": 68317300.0, "bmf_assets": 214992500.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-28T11:32:20.0000000", "profile_last_modified": "2023-03-30T15:12:30.0000000", "dei_last_modified": "2023-03-13T00:00:00.0000000", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-06-23T11:00:41.0000000" } }, { "organization": { "organization_id": "8240267", "ein": "83-0400149", "organization_name": "Catholic Community Foundation", "also_known_as": "", "group_exemption": "0928", "mission": "The Catholic Community Foundation develops, acquires and distributes funds that provide support to parish, educational, religious, charitable and other organizations. We are the preeminent facilitator of Grant Making based on Catholic values, in Silicon Valley. We accomplish this through Endowments, Family funds, Donor Advised Funds and effective legacy planning. We work with institutions to ensure long-term financial strength through building endowments, and effective planned giving activities. Through our grantmaking, we impact the breadth and effectiveness of many organizations and programs. We are a strong partner in growing and supporting ministry. Motivated by our Gospel call, we seek to inspire, facilitate and celebrate philanthropy based on Catholic values.", "website_url": "http://www.catholiccf.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8855418&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/83-0400149", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(408) 995-5219", "contact_title": "Chief Executive Officer", "number_of_employees": "7", "ruling_year": 1946 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "777 N 1st St Ste 490", "address_line_2": "", "city": "San Jose", "state": "CA", "zip": "95112", "msa": "CA - San Jose", "congressional_district": "District 19, CA", "county": "Santa Clara, CA", "latitude": 37.3506, "longitude": -121.9013 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SP030200", "subject_code_description": "Catholicism" }, { "subject_code": "SP030000", "subject_code_description": "Christianity" }, { "subject_code": "SP000000", "subject_code_description": "Religion" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PF010200", "population_served_description": "Catholics" }, { "population_served_code": "PF010000", "population_served_description": "Christians" }, { "population_served_code": "PF000000", "population_served_description": "Religious groups" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" } ], "ntee_codes": [ { "ntee_code": "T70", "ntee_code_description": "Fund Raising Organizations That Cross Categories includes Community Funds/Trusts and Federated Giving Programs) e.g. United Way" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 21591960.0, "total_expenses": 5907790.0, "total_assets": 151557808.0 }, "bmf_gross_receipts": 66670142.0, "bmf_assets": 151557808.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-03-23T16:54:55.0000000", "profile_last_modified": "2023-03-23T16:54:55.0000000", "dei_last_modified": "2021-06-22T10:44:48.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-05-18T18:57:25.0000000" } }, { "organization": { "organization_id": "9842859", "ein": "83-4186070", "organization_name": "PGA TOUR First Tee Foundation Inc", "also_known_as": "First Tee", "group_exemption": "0000", "mission": "First Tee's Mission is to impact the lives of young people by providing educational programs that build character and instill life-enhancing values through the game of golf.", "website_url": "https://www.firsttee.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9051888&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/83-4186070", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Director, Marketing Services", "number_of_employees": "56", "ruling_year": 2019 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "13000 Sawgrass Village Cir Ste 4", "address_line_2": "", "city": "Ponte Vedra Beach", "state": "FL", "zip": "32082", "msa": "FL - Jacksonville", "congressional_district": "District 4, FL", "county": "Saint Johns, FL", "latitude": 30.2066, "longitude": -81.3831 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SQ020700", "subject_code_description": "Golf" }, { "subject_code": "SQ020000", "subject_code_description": "Sports" }, { "subject_code": "SQ000000", "subject_code_description": "Sports and recreation" } ], "population_served_codes": [ { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010300", "population_served_description": "Preteens" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "O50", "ntee_code_description": "Youth Development Programs" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 69880814.0, "total_expenses": 31347492.0, "total_assets": 130809259.0 }, "bmf_gross_receipts": 73499538.0, "bmf_assets": 130809259.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-05-24T16:31:44.0000000", "profile_last_modified": "2023-05-24T16:31:44.0000000", "dei_last_modified": "2021-04-06T16:32:24.0000000", "financials_last_modified": "2023-05-18T19:00:46.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "8842634", "ein": "26-3408048", "organization_name": "CAR DONATION FOUNDATION", "also_known_as": "Wheels for Wishes", "group_exemption": "0000", "mission": "Car Donation Foundation d/b/a Wheels For Wishes believes that every child, no matter his or her health, deserves a chance to have a happy and fulfilling childhood. By donating your vehicle, we are able to raise funds to support Make-A-Wish chapters in locations throughout the country, helping grant wishes to children with life-threatening medical conditions. A wish is an opportunity for a child to focus on something other than their medical routines, and be a kid again.", "website_url": "www.wheelsforwishes.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9377790&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/26-3408048", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Executive Director", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Executive Director", "number_of_employees": "1", "ruling_year": 2009 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "5775 Wayzata Blvd Ste 700", "address_line_2": "", "city": "Minneapolis", "state": "MN", "zip": "55416", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "District 5, MN", "county": "Hennepin, MN", "latitude": 44.9502, "longitude": -93.3393 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T19", "ntee_code_description": "Nonmonetary Support N.E.C." } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 65728159.0, "total_expenses": 63461586.0, "total_assets": 12821701.0 }, "bmf_gross_receipts": 149507118.0, "bmf_assets": 12821701.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-08-22T12:20:51.0000000", "profile_last_modified": "2023-08-22T12:20:51.0000000", "dei_last_modified": "2021-05-07T19:03:51.0000000", "financials_last_modified": "2023-05-10T17:00:18.0000000", "last_modified": "2023-08-22T12:20:51.0000000" } }, { "organization": { "organization_id": "7101381", "ein": "22-2842846", "organization_name": "Community Connections for Children, Inc", "also_known_as": "", "group_exemption": "0000", "mission": "Community Connections for Children, Inc. ensures that all families have access to affordable, high quality child care choices that lead to success in school and life.", "website_url": "http://cccforpa.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9058306&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/22-2842846", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "76", "ruling_year": 1988 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "29 N Duke St", "address_line_2": "", "city": "York", "state": "PA", "zip": "17401", "msa": "PA - York", "congressional_district": "District 10, PA", "county": "York, PA", "latitude": 39.964, "longitude": -76.7263 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS040302", "subject_code_description": "Child care" }, { "subject_code": "SS040300", "subject_code_description": "Child welfare" }, { "subject_code": "SS040000", "subject_code_description": "Family services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN030400", "subject_code_description": "Community service" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN020302", "subject_code_description": "Job training" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SB100000", "subject_code_description": "Early childhood education" }, { "subject_code": "SB091000", "subject_code_description": "Parent-teacher involvement" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010100", "population_served_description": "Infants and toddlers" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P33", "ntee_code_description": "Child Day Care" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 144029187.0, "total_expenses": 142865650.0, "total_assets": 29069252.0 }, "bmf_gross_receipts": 115294715.0, "bmf_assets": 14301001.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-26T07:42:48.0000000", "profile_last_modified": "2023-05-26T07:51:50.0000000", "dei_last_modified": "2023-05-26T07:48:20.0000000", "financials_last_modified": "2023-05-18T18:57:25.0000000", "last_modified": "2023-05-26T07:51:50.0000000" } }, { "organization": { "organization_id": "8045160", "ein": "68-0161455", "organization_name": "North Valley Community Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "At North Valley Community Foundation we exist to help you change the world. Through partnership, financial services, training and education we are the North Valley's Hub for philanthropy, helping individuals, families, businesses and non-profits to maximize their impact on the local and global community.", "website_url": "www.nvcf.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8523520&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/68-0161455", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "Mrs. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(530) 891-1150", "contact_title": "President & CEO", "number_of_employees": "46", "ruling_year": 1994 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "The Foundation Building 1811 Concord Ave. Ste. 220", "address_line_2": "", "city": "Chico", "state": "CA", "zip": "95928", "msa": "CA - Chico-Paradise", "congressional_district": "District 1, CA", "county": "Butte, CA", "latitude": 39.7294, "longitude": -121.8102 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN050000", "subject_code_description": "Financial services" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SD040000", "subject_code_description": "Nonprofits" }, { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T31", "ntee_code_description": "Community Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 16028341.0, "total_expenses": 17694994.0, "total_assets": 60759000.0 }, "bmf_gross_receipts": 62842457.0, "bmf_assets": 60759000.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-19T15:19:23.0000000", "profile_last_modified": "2023-01-19T15:19:23.0000000", "dei_last_modified": "2021-08-27T10:55:30.0000000", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-05-18T15:24:48.0000000" } }, { "organization": { "organization_id": "7491653", "ein": "36-4272272", "organization_name": "All Chicago Making Homelessness History", "also_known_as": "", "group_exemption": "0000", "mission": "All Chicago’s mission is to unite our community and resources to provide solutions that ensure and sustain the stability of home.", "website_url": "https://allchicago.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9312184&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/36-4272272", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and Chief Executive Officer", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Development and Communications Associate", "number_of_employees": "92", "ruling_year": 1999 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "651 W Washington Blvd Ste 504", "address_line_2": "", "city": "Chicago", "state": "IL", "zip": "60661", "msa": "IL - Chicago", "congressional_district": "District 7, IL", "county": "Cook, IL", "latitude": 41.8835, "longitude": -87.6433 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS070300", "subject_code_description": "Housing services" }, { "subject_code": "SS090200", "subject_code_description": "Homeless services" }, { "subject_code": "SS090000", "subject_code_description": "Special population support" }, { "subject_code": "SS070400", "subject_code_description": "Homeless shelters" }, { "subject_code": "SS070000", "subject_code_description": "Shelter and residential care" }, { "subject_code": "SS000000", "subject_code_description": "Human services" } ], "population_served_codes": [ { "population_served_code": "PG030100", "population_served_description": "Homeless people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" } ], "ntee_codes": [ { "ntee_code": "L80", "ntee_code_description": "Other Housing Support Services" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 72080478.0, "total_expenses": 62452225.0, "total_assets": 31255730.0 }, "bmf_gross_receipts": 78218269.0, "bmf_assets": 31255730.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-07-27T15:08:23.0000000", "profile_last_modified": "2023-08-01T11:46:13.0000000", "dei_last_modified": "2023-07-18T00:00:00.0000000", "financials_last_modified": "2023-05-10T23:00:25.0000000", "last_modified": "2023-08-01T11:46:13.0000000" } }, { "organization": { "organization_id": "8432791", "ein": "94-2978977", "organization_name": "Institute on Aging", "also_known_as": "IOA", "group_exemption": "0000", "mission": "The mission of The Institute on Aging is to enhance the quality of life for adults as they age by enabling them to maintain their health, well-being, independence and participation in the community. We fulfill this mission for a diverse community by developing and providing innovative programs in health, social service, creative arts, spiritual support, education and research.", "website_url": "www.IOAging.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8972151&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/94-2978977", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(415) 379-2657", "contact_title": "Database Manager", "number_of_employees": "780", "ruling_year": 1986 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "3575 Geary Blvd", "address_line_2": "", "city": "San Francisco", "state": "CA", "zip": "94118", "msa": "CA - San Francisco-Oakland", "congressional_district": "District 12, CA", "county": "San Francisco, CA", "latitude": 37.7812, "longitude": -122.4577 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS090500", "subject_code_description": "Senior services" }, { "subject_code": "SS090000", "subject_code_description": "Special population support" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SE140700", "subject_code_description": "Geriatrics" }, { "subject_code": "SE140000", "subject_code_description": "Medical specialties" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE060100", "subject_code_description": "Home health care" }, { "subject_code": "SE060000", "subject_code_description": "Nursing care" }, { "subject_code": "SE040200", "subject_code_description": "Community health care" }, { "subject_code": "SE040000", "subject_code_description": "In-patient medical care" }, { "subject_code": "SE020000", "subject_code_description": "Health care access" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P81", "ntee_code_description": "Senior Centers/Services" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 68010483.0, "total_expenses": 66958167.0, "total_assets": 55163678.0 }, "bmf_gross_receipts": 68120060.0, "bmf_assets": 55163678.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-04-25T19:05:25.0000000", "profile_last_modified": "2023-04-28T18:11:17.0000000", "dei_last_modified": "2023-04-25T00:00:00.0000000", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-06-23T11:00:41.0000000" } }, { "organization": { "organization_id": "8951454", "ein": "27-2559468", "organization_name": "AAA Scholarship Foundation Inc", "also_known_as": "AAA Scholarships", "group_exemption": "0000", "mission": "AAA Scholarship Foundation's mission is to provide economic and other assistance to economically-disadvantaged families to enable them to select the best schools for their children.", "website_url": "www.aaascholarships.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8577360&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/27-2559468", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(888) 707-2465 x710", "contact_title": "President", "number_of_employees": "18", "ruling_year": 2010 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 15719", "address_line_2": "", "city": "Tampa", "state": "FL", "zip": "33684", "msa": "FL - Tampa-St. Petersburg-Clearwater", "congressional_district": "District 14, FL", "county": "Hillsborough, FL", "latitude": 27.9967, "longitude": -82.4837 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B82", "ntee_code_description": "Scholarships, Student Financial Aid, Awards" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 128005629.0, "total_expenses": 89721926.0, "total_assets": 113422809.0 }, "bmf_gross_receipts": 128797873.0, "bmf_assets": 113422809.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-24T14:09:35.0000000", "profile_last_modified": "2023-01-24T14:09:35.0000000", "dei_last_modified": "2022-03-01T14:10:06.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-05-18T17:01:04.0000000" } }, { "organization": { "organization_id": "9128858", "ein": "27-4357830", "organization_name": "NEMA FOUNDATION INC dba ProvisionBridge", "also_known_as": "ProvisionBridge", "group_exemption": "0000", "mission": "ProvisionBridge exists to provide an easy, tax-efficient way for individuals, families and organizations to give charitably to organizations that provide care for those in need Difficult times, rising medical costs, natural disasters, and other problems have left more and more families in need of financial assistance and more families and organizations wanting to help Recognizing these needs led a team of dedicated leaders in the nonprofit community to start ProvisionBridge In 2011", "website_url": "www.provisionbridge.org", "logo_url": "", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/27-4357830", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "4", "ruling_year": 2011 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1859 Northgate Blvd", "address_line_2": "", "city": "Sarasota", "state": "FL", "zip": "34234", "msa": "FL - Sarasota-Bradenton", "congressional_district": "District 16, FL", "county": "Sarasota, FL", "latitude": 27.3721, "longitude": -82.5338 }, "taxonomies": { "subject_codes": [ { "subject_code": "SZ000000", "subject_code_description": "Unknown or not classified" }, { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "T30", "ntee_code_description": "Public Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 61480995.0, "total_expenses": 44480279.0, "total_assets": 40863488.0 }, "bmf_gross_receipts": 66205427.0, "bmf_assets": 40863488.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-02T11:34:03.0000000", "profile_last_modified": "2023-02-02T11:39:05.0000000", "dei_last_modified": "2023-02-02T11:32:48.0000000", "financials_last_modified": "2023-05-18T19:00:46.0000000", "last_modified": "2023-05-18T19:00:46.0000000" } }, { "organization": { "organization_id": "7100529", "ein": "23-1445669", "organization_name": "Defender Association of Philadelphia", "also_known_as": "", "group_exemption": "0000", "mission": "The Defender Association of Philadelphia provides high-quality, client-centered legal representation, connection to social services, and reentry support to adults and juveniles in Philadelphia, engaging in advocacy and community collaboration to improve the lives of vulnerable populations, protect the Constitution, and ensure a fair and equitable justice system.", "website_url": "https://phillydefenders.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9228221&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/23-1445669", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "<NAME>", "number_of_employees": "701", "ruling_year": 1937 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1441 Sansom St", "address_line_2": "", "city": "Philadelphia", "state": "PA", "zip": "19102", "msa": "PA - Philadelphia, PA-NJ", "congressional_district": "District 1, PA", "county": "Philadelphia, PA", "latitude": 39.9502, "longitude": -75.1648 }, "taxonomies": { "subject_codes": [ { "subject_code": "SR050000", "subject_code_description": "Diversity and intergroup relations" }, { "subject_code": "SR040000", "subject_code_description": "Antidiscrimination" }, { "subject_code": "SR030000", "subject_code_description": "Justice rights" }, { "subject_code": "SR010400", "subject_code_description": "Freedom from slavery" }, { "subject_code": "SR010300", "subject_code_description": "Freedom from violence and torture" }, { "subject_code": "SR010000", "subject_code_description": "Individual liberties" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SJ050000", "subject_code_description": "Corrections and penology" }, { "subject_code": "SJ040700", "subject_code_description": "Public interest law" }, { "subject_code": "SJ040600", "subject_code_description": "Legal aid" }, { "subject_code": "SJ040200", "subject_code_description": "Guardianship" }, { "subject_code": "SJ040100", "subject_code_description": "Child advocacy" }, { "subject_code": "SJ040000", "subject_code_description": "Legal services" }, { "subject_code": "SJ030000", "subject_code_description": "Courts" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" }, { "subject_code": "SB060400", "subject_code_description": "Social work education" }, { "subject_code": "SB060200", "subject_code_description": "Law education" }, { "subject_code": "SB060000", "subject_code_description": "Graduate and professional education" }, { "subject_code": "SB010000", "subject_code_description": "Equal opportunity in education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PH030000", "population_served_description": "Substance abusers" }, { "population_served_code": "PH010400", "population_served_description": "People with psychosocial disabilities" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG040000", "population_served_description": "Incarcerated people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "I80", "ntee_code_description": "Legal Services" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 76191393.0, "total_expenses": 73816848.0, "total_assets": 32492853.0 }, "bmf_gross_receipts": 76191393.0, "bmf_assets": 32492853.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-07-05T11:52:23.0000000", "profile_last_modified": "2023-07-05T11:52:23.0000000", "dei_last_modified": "2023-05-17T15:27:43.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "7594037", "ein": "41-0907857", "organization_name": "Lifeworks Services Inc.", "also_known_as": "Lifeworks", "group_exemption": "0000", "mission": "Our mission is to partner with people with disabilities to drive change by increasing opportunity and access in the community.", "website_url": "lifeworks.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8713129&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/41-0907857", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(651) 332-6822", "contact_title": "Vice President of Advancement", "number_of_employees": "1958", "ruling_year": 1974 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "6636 Cedar Ave S Ste 250", "address_line_2": "", "city": "Minneapolis", "state": "MN", "zip": "55423", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "District 5, MN", "county": "Hennepin, MN", "latitude": 44.8826, "longitude": -93.2479 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS090100", "subject_code_description": "Developmental disability services" }, { "subject_code": "SS090000", "subject_code_description": "Special population support" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SR040300", "subject_code_description": "Disabled persons' rights" }, { "subject_code": "SR040000", "subject_code_description": "Antidiscrimination" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" } ], "population_served_codes": [ { "population_served_code": "PH010500", "population_served_description": "People with intellectual disabilities" }, { "population_served_code": "PH010400", "population_served_description": "People with psychosocial disabilities" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD050000", "population_served_description": "Caregivers" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" } ], "ntee_codes": [ { "ntee_code": "P82", "ntee_code_description": "Developmentally Disabled Services/Centers" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 90055832.0, "total_expenses": 89120362.0, "total_assets": 41350989.0 }, "bmf_gross_receipts": 90149863.0, "bmf_assets": 41350989.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-06T11:25:40.0000000", "profile_last_modified": "2023-02-20T16:03:22.0000000", "dei_last_modified": "2023-02-14T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7469372", "ein": "36-3584029", "organization_name": "UPPER MIDWEST ORGAN PROCUREMENT ORGANIZATION INC", "also_known_as": "LifeSource", "group_exemption": "0000", "mission": "LifeSource saves lives and offers hope and healing through excellence in organ, eye and tissue donation. We serve the people of Minnesota, North Dakota and South Dakota and portions of western Wisconsin.", "website_url": "www.life-source.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8536232&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/36-3584029", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>, RN MS", "leader_title": "Chief Executive Officer", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(612) 800-6100", "contact_title": "Chief Administrative Officer", "number_of_employees": "204", "ruling_year": 1989 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "2225 W River Rd", "address_line_2": "", "city": "Minneapolis", "state": "MN", "zip": "55411", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "District 5, MN", "county": "Hennepin, MN", "latitude": 45.0016, "longitude": -93.2767 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE110400", "subject_code_description": "Organ and tissue banks" }, { "subject_code": "SE110000", "subject_code_description": "Medical support services" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "E65", "ntee_code_description": "Organ and Tissue Bank" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 73448702.0, "total_expenses": 68428588.0, "total_assets": 70090155.0 }, "bmf_gross_receipts": 78587674.0, "bmf_assets": 70090155.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-19T18:29:32.0000000", "profile_last_modified": "2023-01-19T18:29:32.0000000", "dei_last_modified": "2022-12-29T13:41:22.0000000", "financials_last_modified": "2023-05-10T21:00:09.0000000", "last_modified": "2023-05-10T21:00:09.0000000" } }, { "organization": { "organization_id": "7930473", "ein": "59-0942383", "organization_name": "ST ANDREWS SCHOOL OF BOCA RATON INC", "also_known_as": "Saint Andrew's School", "group_exemption": "0000", "mission": "We provide educational excellence in an inclusive community, fostering lifelong learning and nurturing each individual in mind, body, and spirit in the Episcopal tradition.", "website_url": "www.saintandrews.net", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8693576&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/59-0942383", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Head of School", "contact_name": "Dr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(561) 210-2064", "contact_title": "Director of Marketing and Communications", "number_of_employees": "489", "ruling_year": 1963 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3900 Jog Rd", "address_line_2": "", "city": "Boca Raton", "state": "FL", "zip": "33434", "msa": "FL - West Palm Beach-Boca Raton", "congressional_district": "District 22, FL", "county": "Palm Beach, FL", "latitude": 26.3844, "longitude": -80.1692 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B20", "ntee_code_description": "Elementary, Secondary Ed" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 73505985.0, "total_expenses": 51156965.0, "total_assets": 114146495.0 }, "bmf_gross_receipts": 78087340.0, "bmf_assets": 114146495.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-02-15T08:40:20.0000000", "profile_last_modified": "2023-02-15T08:42:33.0000000", "dei_last_modified": "2021-05-14T14:55:08.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "7594419", "ein": "41-1601449", "organization_name": "Feed My Starving Children", "also_known_as": "FMSC", "group_exemption": "0000", "mission": "A Christian organization with headquarters in Minnesota along with sites and events around the country, FMSCs mission is to eliminate child malnutrition worldwide while providing meaningful service opportunities for volunteers in the United States.", "website_url": "http://www.fmsc.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8565806&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/41-1601449", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(763) 267-6311", "contact_title": "Digital Marketing & Analytics Manager", "number_of_employees": "390", "ruling_year": 1989 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "401 93rd Ave NW", "address_line_2": "", "city": "Minneapolis", "state": "MN", "zip": "55433", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "", "county": "Anoka, MN", "latitude": 45.1961, "longitude": -94.8184 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SJ060400", "subject_code_description": "Disaster relief" }, { "subject_code": "SJ060000", "subject_code_description": "Disasters and emergency management" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P20", "ntee_code_description": "Human Service Organizations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 62648844.0, "total_expenses": 56099737.0, "total_assets": 39897595.0 }, "bmf_gross_receipts": 65619187.0, "bmf_assets": 38450008.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-23T12:59:12.0000000", "profile_last_modified": "2023-01-23T12:59:11.0000000", "dei_last_modified": "2023-01-23T00:00:00.0000000", "financials_last_modified": "2023-05-11T03:00:11.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "6840867", "ein": "04-3460220", "organization_name": "The Progeria Research Foundation, Inc.", "also_known_as": "Progeria Research Foundation, PRF", "group_exemption": "0000", "mission": "The Progeria Research Foundation's (PRF) mission is to find treatments and the cure for Progeria and its aging-related disorders, including heart disease. Progeria is a fatal, 'rapid aging' disease that afflicts children, who die of heart disease at an average age of 14 years. PRF was founded in 1999 in response to the complete lack of resources and research on Progeria, and is the only organization in the world solely dedicated to discovering treatments and the cure for this devastating condition.", "website_url": "www.progeriaresearch.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9167571&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/04-3460220", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and Executive Director", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(978) 535-2594", "contact_title": "President and Executive Director", "number_of_employees": "14", "ruling_year": 1999 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 3453", "address_line_2": "", "city": "Peabody", "state": "MA", "zip": "01961", "msa": "MA - Boston", "congressional_district": "District 6, MA", "county": "Essex, MA", "latitude": 42.5336, "longitude": -70.9651 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE151400", "subject_code_description": "Genetic conditions and birth defects" }, { "subject_code": "SE150700", "subject_code_description": "Heart and circulatory system diseases" }, { "subject_code": "SE150000", "subject_code_description": "Diseases and conditions" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "H80", "ntee_code_description": "Specifically Named Diseases Research" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 49219762.0, "total_expenses": 3160686.0, "total_assets": 53690802.0 }, "bmf_gross_receipts": 94050831.0, "bmf_assets": 53690802.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-06-20T11:04:18.0000000", "profile_last_modified": "2023-06-20T11:04:18.0000000", "dei_last_modified": "2022-01-19T14:58:53.0000000", "financials_last_modified": "2023-05-18T18:49:03.0000000", "last_modified": "2023-06-20T11:04:18.0000000" } }, { "organization": { "organization_id": "7074683", "ein": "22-2743917", "organization_name": "COMMUNITY FOUNDATION FOR GREATER BUFFALO INC", "also_known_as": "", "group_exemption": "0000", "mission": "Mission: Connecting people, ideas and resources to improve lives in Western New York.Our vision is a vibrant and equitable region where every individual thrives.", "website_url": "www.cfgb.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8473285&approved=True", "profile_level": "Silver", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/22-2743917", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2022-seal.svg", "leader_name": "<NAME>", "leader_title": "President/CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(716) 852-2857", "contact_title": "VP Finance", "number_of_employees": "49", "ruling_year": 1987 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "Larkin At Exchange 726 Exchange St. Suite 525", "address_line_2": "", "city": "Buffalo", "state": "NY", "zip": "14210", "msa": "NY - Buffalo-Niagara Falls", "congressional_district": "District 26, NY", "county": "Erie, NY", "latitude": 42.8649, "longitude": -78.8304 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" } ], "ntee_codes": [ { "ntee_code": "T31", "ntee_code_description": "Community Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 143802626.0, "total_expenses": 47739302.0, "total_assets": 874380305.0 }, "bmf_gross_receipts": 187926250.0, "bmf_assets": 874380305.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-01-06T15:38:21.0000000", "profile_last_modified": "2023-01-06T15:38:21.0000000", "dei_last_modified": "2023-01-06T15:34:04.0000000", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-05-18T15:24:48.0000000" } }, { "organization": { "organization_id": "8438248", "ein": "95-1644589", "organization_name": "<NAME> Library and Art Gallery", "also_known_as": "Huntington Library, Art Museum, and Botanical Gardens", "group_exemption": "0000", "mission": "Founded in 1919 by <NAME>, the Library, Art Museum, and Botanical Gardens promote and advance learning, the arts and sciences, and the public welfare. The institution seeks to improve, enhance, and preserve its collections through its devotion to research, education, and beauty serving both the general public and a growing network of scholars.", "website_url": "www.huntington.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8916112&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/95-1644589", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(626) 405-2293", "contact_title": "VP Advancement", "number_of_employees": "578", "ruling_year": 1938 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1151 Oxford Rd", "address_line_2": "", "city": "San Marino", "state": "CA", "zip": "91108", "msa": "CA - Los Angeles-Long Beach", "congressional_district": "District 27, CA", "county": "Los Angeles, CA", "latitude": 34.1268, "longitude": -118.1092 }, "taxonomies": { "subject_codes": [ { "subject_code": "SH020200", "subject_code_description": "Archives and special collections" }, { "subject_code": "SH020000", "subject_code_description": "Libraries" }, { "subject_code": "SH000000", "subject_code_description": "Information and communications" }, { "subject_code": "SC040201", "subject_code_description": "Botanical gardens" }, { "subject_code": "SC040200", "subject_code_description": "Plant biodiversity" }, { "subject_code": "SC040000", "subject_code_description": "Biodiversity" }, { "subject_code": "SC000000", "subject_code_description": "Environment" }, { "subject_code": "SA070100", "subject_code_description": "Art museums" }, { "subject_code": "SA070000", "subject_code_description": "Museums" }, { "subject_code": "SA010500", "subject_code_description": "Arts education" }, { "subject_code": "SA010000", "subject_code_description": "Arts services" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "A11", "ntee_code_description": "Single Organization Support" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 128861733.0, "total_expenses": 100849878.0, "total_assets": 862313980.0 }, "bmf_gross_receipts": 422919661.0, "bmf_assets": 862313980.0, "required_to_file_990t": true, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2023-04-12T00:29:03.0000000", "profile_last_modified": "2023-04-12T00:29:03.0000000", "dei_last_modified": "2021-07-09T09:12:31.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } } ] } ``` ``` { "filters": { "financials": { "most_recent_year": { "form_types": { "f990": true }, "total_revenue": { "min": 50000 }, "total_expenses": { "min": 30000 }, "total_assets": { "min": 4000000 } }, "required_to_file_990t": true, "a_133_audit_performed": true } } } ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 101, "time": "2023-08-29 18:36:24Z", "results_count": 2991, "page_count": 120, "errors": [], "hits": [ { "organization": { "organization_id": "6906822", "ein": "13-1967321", "organization_name": "<NAME>", "also_known_as": "Mercy", "group_exemption": "0000", "mission": "Mercy College is committed to providing motivated students the opportunity to transform their lives through higher education by offering liberal arts and professional programs in personalized and high quality learning environments, thus preparing students to embark on rewarding careers, to continue learning throughout their lives and to act ethically and responsibly in a changing world.", "website_url": "www.mercy.edu", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8456670&approved=True", "profile_level": "Silver", "profile_year": 2022, "profile_link": "https://www.guidestar.org/profile/13-1967321", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2022-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(914) 674-7562", "contact_title": "Executive Director of Institutional Research", "number_of_employees": "2413", "ruling_year": 1971 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "555 Broadway Mercy College", "address_line_2": "", "city": "Dobbs Ferry", "state": "NY", "zip": "10522", "msa": "NY - New York, NY-NJ", "congressional_district": "District 17, NY", "county": "Westchester, NY", "latitude": 41.013, "longitude": -73.8634 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB060000", "subject_code_description": "Graduate and professional education" }, { "subject_code": "SB050300", "subject_code_description": "University education" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050100", "population_served_description": "Students" }, { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" } ], "ntee_codes": [ { "ntee_code": "B40", "ntee_code_description": "Higher Education Institutions" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 239467272.0, "total_expenses": 209020071.0, "total_assets": 626665016.0 }, "bmf_gross_receipts": 398510967.0, "bmf_assets": 626665016.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-01-03T10:10:16.0000000", "profile_last_modified": "2023-01-03T10:10:16.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-06-23T11:00:41.0000000" } }, { "organization": { "organization_id": "7051751", "ein": "21-0634988", "organization_name": "Institute for Advanced Study", "also_known_as": "<NAME> & <NAME>", "group_exemption": "0000", "mission": "The Institute exists to encourage and support fundamental scholarship—the original, often speculative, thinking that produces advances in knowledge that change the way we understand the world. Work at the Institute takes place in four Schools: Historical Studies, Mathematics, Natural Sciences and Social Science. It provides for the mentoring of younger scholars by a permanent Faculty, and it offers all who work there the freedom to undertake research that will make significant contributions in any of the broad range of fields in the sciences and humanities studied at the Institute. The Institute, founded in 1930, is a private, independent academic institution located in Princeton, New Jersey.", "website_url": "http://www.ias.edu", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8814088&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/21-0634988", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Director of Editorial and Content Strategy", "number_of_employees": "509", "ruling_year": 1931 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "Einstein Dr", "address_line_2": "", "city": "Princeton", "state": "NJ", "zip": "08540", "msa": "NJ - Trenton", "congressional_district": "District 12, NJ", "county": "Mercer, NJ", "latitude": 40.3615, "longitude": -74.653 }, "taxonomies": { "subject_codes": [ { "subject_code": "SG090000", "subject_code_description": "Interdisciplinary studies" }, { "subject_code": "SG000000", "subject_code_description": "Social sciences" }, { "subject_code": "SB060000", "subject_code_description": "Graduate and professional education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B40", "ntee_code_description": "Higher Education Institutions" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 127450651.0, "total_expenses": 70114395.0, "total_assets": 1292353306.0 }, "bmf_gross_receipts": 464505959.0, "bmf_assets": 1292353306.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-03-14T09:28:28.0000000", "profile_last_modified": "2023-03-14T09:31:22.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7100782", "ein": "23-1526668", "organization_name": "CABRINI UNIVERSITY", "also_known_as": "", "group_exemption": "0928", "mission": "Education of the HeartCabrini University is a Catholic institution of higher education dedicated to academic excellence, leadership development, and a commitment to social justice. Cabrini welcomes learners of all faiths, cultures, and backgrounds and prepares them to become engaged citizens of the world.", "website_url": "www.cabrini.edu", "logo_url": "", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/23-1526668", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Interim President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(610) 902-8250", "contact_title": "Director, Advancement Services", "number_of_employees": "991", "ruling_year": 1946 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "610 King of Prussia Rd", "address_line_2": "", "city": "Wayne", "state": "PA", "zip": "19087", "msa": "PA - Philadelphia, PA-NJ", "congressional_district": "District 5, PA", "county": "Delaware, PA", "latitude": 40.0545, "longitude": -75.3666 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB060000", "subject_code_description": "Graduate and professional education" }, { "subject_code": "SB050300", "subject_code_description": "University education" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B43", "ntee_code_description": "University or Technological" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 68449867.0, "total_expenses": 75801948.0, "total_assets": 118667361.0 }, "bmf_gross_receipts": 73934977.0, "bmf_assets": 118667361.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-01-19T17:35:57.0000000", "profile_last_modified": "2023-01-19T17:35:57.0000000", "dei_last_modified": "2023-01-19T17:35:26.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7749339", "ein": "52-0705392", "organization_name": "Stevenson University Inc.", "also_known_as": "", "group_exemption": "0000", "mission": "The University is an innovative, coeducational, independent institution offering undergraduate and graduate students a career-focused education marked by individualized attention, civility, and respect for difference. The University blends the liberal arts with career exploration and planning, complementing a traditional education with applied learning beyond the classroom. The University meets students where they are and supports and challenges them to become reflective and accomplished individuals committed to a lifetime of learning and contribution. Students graduate with the competence and confidence needed to address creatively the opportunities and problems facing their communities, the nation, and the world.", "website_url": "www.stevenson.edu", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8602721&approved=True", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/52-0705392", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(443) 334-2347", "contact_title": "Assistant Controller", "number_of_employees": "1450", "ruling_year": 1996 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1525 Greenspring Valley Rd", "address_line_2": "", "city": "Stevenson", "state": "MD", "zip": "21153", "msa": "MD - Baltimore", "congressional_district": "District 3, MD", "county": "Baltimore, MD", "latitude": 39.4236, "longitude": -76.6997 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB060000", "subject_code_description": "Graduate and professional education" }, { "subject_code": "SB050300", "subject_code_description": "University education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B40", "ntee_code_description": "Higher Education Institutions" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 161866162.0, "total_expenses": 150618294.0, "total_assets": 339125128.0 }, "bmf_gross_receipts": 184307303.0, "bmf_assets": 339125128.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-01-27T15:50:11.0000000", "profile_last_modified": "2023-01-27T15:50:11.0000000", "dei_last_modified": "", "financials_last_modified": "2023-05-18T15:24:48.0000000", "last_modified": "2023-05-18T15:24:48.0000000" } }, { "organization": { "organization_id": "8088726", "ein": "73-0580274", "organization_name": "Oklahoma Medical Research Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "OMRF was founded with the mission of helping Oklahomans and people everywhere live longer, healthier lives. That mission has remained our organization's compass, guiding our scientists not only to perform groundbreaking scientific research but to research that helps mankind in the battle against human disease. Our goal, quite simply, is to make discoveries that make a difference.", "website_url": "www.omrf.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9046477&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/73-0580274", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "624", "ruling_year": 1999 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "825 NE 13th St", "address_line_2": "", "city": "Oklahoma City", "state": "OK", "zip": "73104", "msa": "OK - Oklahoma City", "congressional_district": "District 5, OK", "county": "Oklahoma, OK", "latitude": 35.4749, "longitude": -97.5049 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE150000", "subject_code_description": "Diseases and conditions" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "H80", "ntee_code_description": "Specifically Named Diseases Research" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 107744875.0, "total_expenses": 96940173.0, "total_assets": 463812009.0 }, "bmf_gross_receipts": 171272531.0, "bmf_assets": 463812009.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-23T12:20:55.0000000", "profile_last_modified": "2023-05-23T12:20:55.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7941374", "ein": "59-3001853", "organization_name": "Community Foundation of Tampa Bay Inc", "also_known_as": "", "group_exemption": "0000", "mission": "Our Mission: Building a vibrant, prosperous community through transformative vision, leadership, and philanthropy.", "website_url": "www.cftampabay.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8800563&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/59-3001853", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(813) 609-4858", "contact_title": "", "number_of_employees": "29", "ruling_year": 1990 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "4300 W Cypress St Ste 700", "address_line_2": "", "city": "Tampa", "state": "FL", "zip": "33607", "msa": "FL - Tampa-St. Petersburg-Clearwater", "congressional_district": "District 14, FL", "county": "Hillsborough, FL", "latitude": 27.9522, "longitude": -82.5159 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T31", "ntee_code_description": "Community Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 263193049.0, "total_expenses": 75575458.0, "total_assets": 499126043.0 }, "bmf_gross_receipts": 281848450.0, "bmf_assets": 499126043.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-03-09T15:26:23.0000000", "profile_last_modified": "2023-03-09T15:42:43.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "7746528", "ein": "52-0591421", "organization_name": "St. John's College - Annapolis", "also_known_as": "", "group_exemption": "0000", "mission": "St. John's College is unique in American higher education. All classes are conducted as seminars. No textbooks are used; instead, students, along with their tutors (professors) work through the original texts in philosophy, literature, history, mathematics, science, economics, theology, and political science. St. John's College is a community dedicated to liberal education. Such education seeks to free men and women from the tyrannies of unexamined opinions and inherited prejudices. It also endeavors to enable them to make intelligent, free choices concerning the ends and means of both public and private life. At St. John's, freedom is pursued mainly through thoughtful conversation about great books of the Western tradition.", "website_url": "https://www.sjc.edu/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9244382&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/52-0591421", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Vice President of Finance & Operations/CFO", "number_of_employees": "968", "ruling_year": 1942 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "60 College Ave", "address_line_2": "", "city": "Annapolis", "state": "MD", "zip": "21401", "msa": "MD - Baltimore", "congressional_district": "District 3, MD", "county": "<NAME>, MD", "latitude": 38.9831, "longitude": -76.5314 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB050300", "subject_code_description": "University education" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B43", "ntee_code_description": "University or Technological" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 100932482.0, "total_expenses": 74490426.0, "total_assets": 377084479.0 }, "bmf_gross_receipts": 103641369.0, "bmf_assets": 377084479.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-07-10T14:51:56.0000000", "profile_last_modified": "2023-07-10T15:46:53.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-07-10T15:46:53.0000000" } }, { "organization": { "organization_id": "7798848", "ein": "54-0505977", "organization_name": "Washington and Lee University", "also_known_as": "", "group_exemption": "0000", "mission": "Washington and Lee University provides a liberal arts education that develops students' capacity to think freely, critically and humanely, and to conduct themselves with honor, integrity and civility. Graduates will be prepared for lifelong learning, personal achievement, responsible leadership, service to others, and engaged citizenship in a global and diverse society.", "website_url": "https://www.wlu.edu", "logo_url": "", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/54-0505977", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(540) 458-8459", "contact_title": "Executive Director of Communications and Public Affairs", "number_of_employees": "2603", "ruling_year": 1923 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "204 W Washington St", "address_line_2": "", "city": "Lexington", "state": "VA", "zip": "24450", "msa": "", "congressional_district": "District 6, VA", "county": "Lexington City, VA", "latitude": 37.7869, "longitude": -79.4446 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB060000", "subject_code_description": "Graduate and professional education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B42", "ntee_code_description": "Undergraduate College (4-year)" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 248819904.0, "total_expenses": 254894072.0, "total_assets": 2488364359.0 }, "bmf_gross_receipts": 460149428.0, "bmf_assets": 2488364359.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-07-10T14:02:49.0000000", "profile_last_modified": "2023-07-11T15:17:24.0000000", "dei_last_modified": "2023-03-07T12:16:56.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-07-11T15:17:24.0000000" } }, { "organization": { "organization_id": "7797977", "ein": "54-0505888", "organization_name": "Colonial Williamsburg Foundation", "also_known_as": "", "group_exemption": "0000", "mission": "Colonial Williamsburg's educational mission \"so that the future may learn from the past\" is advanced through educational programming, preservation, and research. As the largest living museum in the country, Colonial Williamsburg upholds our mission through immersive, authentic 18th-century experiences and programming to inspire people as they learn about this historic capital, the events that occurred here, and the diverse people who helped shape America.", "website_url": "www.colonialwilliamsburg.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8532995&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/54-0505888", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(757) 565-8428", "contact_title": "Executive Director, Development Services", "number_of_employees": "1155", "ruling_year": 1938 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 1776", "address_line_2": "", "city": "Williamsburg", "state": "VA", "zip": "23187", "msa": "VA - Norfolk-Virginia Beach-Newport News, VA-NC", "congressional_district": "District 2, VA", "county": "Williamsburg City, VA", "latitude": 37.2728, "longitude": -76.7188 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA090300", "subject_code_description": "Historic preservation" }, { "subject_code": "SA090000", "subject_code_description": "Historical activities" }, { "subject_code": "SA070400", "subject_code_description": "History museums" }, { "subject_code": "SA070000", "subject_code_description": "Museums" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "A54", "ntee_code_description": "History Museums" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 164089192.0, "total_expenses": 111219023.0, "total_assets": 1685638784.0 }, "bmf_gross_receipts": 751423134.0, "bmf_assets": 1685638784.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-01-19T16:58:58.0000000", "profile_last_modified": "2023-01-19T16:58:58.0000000", "dei_last_modified": "2022-01-25T08:36:16.0000000", "financials_last_modified": "2023-05-18T19:00:46.0000000", "last_modified": "2023-05-18T19:00:46.0000000" } }, { "organization": { "organization_id": "7797989", "ein": "54-0505940", "organization_name": "RANDOLPH-MACON COLLEGE", "also_known_as": "", "group_exemption": "0000", "mission": "Randolph-Macon is an undergraduate, coeducational college of the liberal arts. The purpose of a Randolph-Macon education is to develop the mind and the character of its students. They are challenged to communicate effectively, to think analytically and critically, to experience and appreciate the creative process, to develop qualities of leadership, and to synthesize what they know with who they are. At Randolph-Macon College the liberal arts constitute a comprehensive educational opportunity.", "website_url": "www.rmc.edu", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9102256&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/54-0505940", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "Mr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(804) 752-7241", "contact_title": "Vice President of Administration and Finance", "number_of_employees": "1165", "ruling_year": 1923 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 5005", "address_line_2": "", "city": "Ashland", "state": "VA", "zip": "23005", "msa": "VA - Richmond-Petersburg", "congressional_district": "", "county": "Hanover, VA", "latitude": 37.7533, "longitude": -77.4769 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" } ], "ntee_codes": [ { "ntee_code": "B42", "ntee_code_description": "Undergraduate College (4-year)" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 106388149.0, "total_expenses": 96600817.0, "total_assets": 398057628.0 }, "bmf_gross_receipts": 107093593.0, "bmf_assets": 398057628.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-06-07T16:18:32.0000000", "profile_last_modified": "2023-06-07T16:18:32.0000000", "dei_last_modified": "2021-02-03T14:51:04.0000000", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-06-23T11:00:41.0000000" } }, { "organization": { "organization_id": "7929242", "ein": "59-0637903", "organization_name": "Ringling College Of Art And Design", "also_known_as": "", "group_exemption": "0000", "mission": "Through art and design, we educate the creative critical thinkers who will transform the future.", "website_url": "www.ringling.edu", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9324575&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/59-0637903", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "Dr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(941) 359-7601", "contact_title": "President", "number_of_employees": "1122", "ruling_year": 1938 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2700 N Tamiami Trl", "address_line_2": "", "city": "Sarasota", "state": "FL", "zip": "34234", "msa": "FL - Sarasota-Bradenton", "congressional_district": "District 16, FL", "county": "Sarasota, FL", "latitude": 27.3599, "longitude": -82.5491 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050600", "subject_code_description": "Economics for youth" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA050000", "subject_code_description": "Visual arts" }, { "subject_code": "SA010500", "subject_code_description": "Arts education" }, { "subject_code": "SA010000", "subject_code_description": "Arts services" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "B42", "ntee_code_description": "Undergraduate College (4-year)" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 119229866.0, "total_expenses": 107972065.0, "total_assets": 401598018.0 }, "bmf_gross_receipts": 187935519.0, "bmf_assets": 401598018.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-08-04T13:41:58.0000000", "profile_last_modified": "2023-08-04T13:41:58.0000000", "dei_last_modified": "2023-04-11T00:00:00.0000000", "financials_last_modified": "2023-05-18T17:01:04.0000000", "last_modified": "2023-08-04T13:41:58.0000000" } }, { "organization": { "organization_id": "7357373", "ein": "31-4379435", "organization_name": "CAPITAL UNIVERSITY", "also_known_as": "CU", "group_exemption": "0000", "mission": "Transforming lives through higher education:  By drawing upon the Lutheran principle of free inquiry, Capital University: provides for personal growth by encouraging,enabling, and celebrating learning;prepares individuals to be knowledgeable, independent, critical thinkers - educated for lives of leadership and service in an increasingly diverse society;inspires individuals to be morally reflective, spiritually alive, and civically engaged.", "website_url": "www.capital.edu", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8995469&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/31-4379435", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(614)", "contact_title": "Donation Coord.", "number_of_employees": "1750", "ruling_year": 1971 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1 College and Main", "address_line_2": "", "city": "Columbus", "state": "OH", "zip": "43209", "msa": "OH - Columbus", "congressional_district": "District 1, OH", "county": "Franklin, OH", "latitude": 39.9561, "longitude": -82.9995 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB060000", "subject_code_description": "Graduate and professional education" }, { "subject_code": "SB050300", "subject_code_description": "University education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ050000", "population_served_description": "Academics" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" } ], "ntee_codes": [ { "ntee_code": "B40", "ntee_code_description": "Higher Education Institutions" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 132427868.0, "total_expenses": 132090936.0, "total_assets": 276697863.0 }, "bmf_gross_receipts": 341381526.0, "bmf_assets": 276697863.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-08T07:59:15.0000000", "profile_last_modified": "2023-05-08T07:59:15.0000000", "dei_last_modified": "2021-11-03T07:51:36.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "8435132", "ein": "94-2971761", "organization_name": "Seneca Family of Agencies", "also_known_as": "Kinship Center - Canyon Acres", "group_exemption": "0000", "mission": "Seneca Family of Agencies helps children and families through the most difficult times of their lives.", "website_url": "www.senecafoa.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8641235&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/94-2971761", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Grant Writer", "number_of_employees": "1807", "ruling_year": 1985 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "8945 Golf Links Rd", "address_line_2": "", "city": "Oakland", "state": "CA", "zip": "94605", "msa": "CA - Oakland", "congressional_district": "District 13, CA", "county": "Alameda, CA", "latitude": 37.7594, "longitude": -122.1557 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS050100", "subject_code_description": "Youth services" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS040000", "subject_code_description": "Family services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SB040000", "subject_code_description": "Vocational education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PH010400", "population_served_description": "People with psychosocial disabilities" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG050000", "population_served_description": "At-risk youth" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P30", "ntee_code_description": "Children's and Youth Services" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 150101219.0, "total_expenses": 147726804.0, "total_assets": 124878544.0 }, "bmf_gross_receipts": 151310943.0, "bmf_assets": 124878544.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-02-03T14:40:47.0000000", "profile_last_modified": "2023-02-03T14:58:36.0000000", "dei_last_modified": "2023-02-03T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "6920337", "ein": "13-3508093", "organization_name": "IONA UNIVERSITY", "also_known_as": "IONA UNIVERSITY", "group_exemption": "0928", "mission": "IONA UNIVERSITY IS A DIVERSE COMMUNITY OF LEARNERS AND SCHOLARS DEDICATED TO ACADEMIC EXCELLENCE IN THE TRADITION OF THE CHRISTIAN BROTHERS AND AMERICAN CATHOLIC HIGHER EDUCATION. WE COMMIT OURSELVES TO EDUCATION WITHIN THE RICH HERITAGE OF THESE LEGACIES, ESPECIALLY INTELLECTUAL INQUIRY AND THE VALUES OF JUSTICE, PEACE, AND SERVICE", "website_url": "WWW.IONA.EDU", "logo_url": "", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-3508093", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(914) 633-2512", "contact_title": "Vice President of Strategic Initiatives and Board Secretary", "number_of_employees": "1625", "ruling_year": 1946 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "715 North Ave McSpedon Hall", "address_line_2": "", "city": "New Rochelle", "state": "NY", "zip": "10801", "msa": "NY - New York, NY-NJ", "congressional_district": "District 16, NY", "county": "Westchester, NY", "latitude": 40.9176, "longitude": -73.7863 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB050300", "subject_code_description": "University education" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B43", "ntee_code_description": "University or Technological" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "10", "foundation_code_description": "Church" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 177877196.0, "total_expenses": 176036683.0, "total_assets": 443220124.0 }, "bmf_gross_receipts": 197484109.0, "bmf_assets": 443220124.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-02-08T15:37:51.0000000", "profile_last_modified": "2023-02-09T11:00:23.0000000", "dei_last_modified": "2023-02-09T00:00:00.0000000", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-07-10T17:03:00.0000000" } }, { "organization": { "organization_id": "6822559", "ein": "04-2104764", "organization_name": "The Home For Little Wanderers", "also_known_as": "The Home", "group_exemption": "0000", "mission": "The Home's mission is to help vulnerable children and their families build permanent, positive change", "website_url": "http://www.thehome.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9257397&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/04-2104764", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Vice President of Marketing & Communications", "number_of_employees": "1211", "ruling_year": 1999 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "10 Guest St", "address_line_2": "", "city": "Brighton", "state": "MA", "zip": "02135", "msa": "MA - Boston", "congressional_district": "District 7, MA", "county": "Suffolk, MA", "latitude": 42.3574, "longitude": -71.1483 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS070000", "subject_code_description": "Shelter and residential care" }, { "subject_code": "SS050400", "subject_code_description": "Youth organizing" }, { "subject_code": "SS050100", "subject_code_description": "Youth services" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS040300", "subject_code_description": "Child welfare" }, { "subject_code": "SS040000", "subject_code_description": "Family services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SE120700", "subject_code_description": "Mental health counseling" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "P30", "ntee_code_description": "Children's and Youth Services" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 66911196.0, "total_expenses": 75708388.0, "total_assets": 129613681.0 }, "bmf_gross_receipts": 86564628.0, "bmf_assets": 129613681.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-07-13T15:15:01.0000000", "profile_last_modified": "2023-07-13T15:15:01.0000000", "dei_last_modified": "2022-09-16T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "7990466", "ein": "62-1471789", "organization_name": "The Community Foundation of Middle Tennessee", "also_known_as": "", "group_exemption": "0000", "mission": "Dedicated to connecting generosity with need. Helping people help others through tailored charitable giving.", "website_url": "www.cfmt.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9251066&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/62-1471789", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "55", "ruling_year": 1992 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "3833 Cleghorn Ave Ste 400", "address_line_2": "", "city": "Nashville", "state": "TN", "zip": "37215", "msa": "TN - Nashville", "congressional_district": "District 5, TN", "county": "Davidson, TN", "latitude": 36.1087, "longitude": -86.8186 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SS090500", "subject_code_description": "Senior services" }, { "subject_code": "SS090000", "subject_code_description": "Special population support" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN040000", "subject_code_description": "Housing development" }, { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SE150000", "subject_code_description": "Diseases and conditions" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SC050100", "subject_code_description": "Animal welfare" }, { "subject_code": "SC050000", "subject_code_description": "Domesticated animals" }, { "subject_code": "SC030000", "subject_code_description": "Natural resources" }, { "subject_code": "SC000000", "subject_code_description": "Environment" }, { "subject_code": "SB000000", "subject_code_description": "Education" }, { "subject_code": "SA090300", "subject_code_description": "Historic preservation" }, { "subject_code": "SA090000", "subject_code_description": "Historical activities" }, { "subject_code": "SA080000", "subject_code_description": "Humanities" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T31", "ntee_code_description": "Community Foundations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 137846384.0, "total_expenses": 77840837.0, "total_assets": 622114153.0 }, "bmf_gross_receipts": 258734097.0, "bmf_assets": 622114153.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-07-12T10:34:52.0000000", "profile_last_modified": "2023-07-12T10:34:52.0000000", "dei_last_modified": "", "financials_last_modified": "2023-05-18T19:00:46.0000000", "last_modified": "2023-07-12T10:34:52.0000000" } }, { "organization": { "organization_id": "7798826", "ein": "54-0505906", "organization_name": "Hampden-Sydney College", "also_known_as": "", "group_exemption": "0000", "mission": "The tenth oldest college in America, with a student body of approximately 1,040 undergraduate men, Hampden-Sydney College is committed to the belief that a liberal education provides the best foundation not only for a professional career, but for the great intellectual and moral challenges of life. Hampden-Sydney's curriculum is directed toward the cultivation of a literate, articulate, and critical mind through the study of the sciences, the humanities, and the social sciences.", "website_url": "http://www.hsc.edu", "logo_url": "", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/54-0505906", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(434) 223-7258", "contact_title": "Vice President for College Advancement", "number_of_employees": "757", "ruling_year": 1957 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "PO Box 637", "address_line_2": "", "city": "Hampden Sydney", "state": "VA", "zip": "23943", "msa": "", "congressional_district": "District 5, VA", "county": "Prince Edward, VA", "latitude": 37.2423, "longitude": -78.459 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B40", "ntee_code_description": "Higher Education Institutions" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 80706273.0, "total_expenses": 80819006.0, "total_assets": 448932160.0 }, "bmf_gross_receipts": 100084103.0, "bmf_assets": 448932160.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-06-05T16:44:05.0000000", "profile_last_modified": "2023-06-05T16:44:05.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-06-23T09:00:47.0000000" } }, { "organization": { "organization_id": "6936520", "ein": "13-5633307", "organization_name": "HIAS INC", "also_known_as": "Hebrew Immigrant Aid Society", "group_exemption": "0000", "mission": "Drawing on our Jewish values and history, HIAS provides vital services to refugees and asylum seekers around the world and advocates for their fundamental rights so they can rebuild their lives.", "website_url": "https://www.hias.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9037590&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-5633307", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President and CEO", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(212) 613-1355", "contact_title": "Associate Director, DevOps", "number_of_employees": "198", "ruling_year": 1954 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "1300 Spring St Ste 500", "address_line_2": "", "city": "Silver Spring", "state": "MD", "zip": "20910", "msa": "MD - Washington, DC-MD-VA", "congressional_district": "District 8, MD", "county": "Montgomery, MD", "latitude": 38.9994, "longitude": -77.032 }, "taxonomies": { "subject_codes": [ { "subject_code": "SS090300", "subject_code_description": "Immigrant services" }, { "subject_code": "SS090000", "subject_code_description": "Special population support" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SR040100", "subject_code_description": "Immigrants' rights" }, { "subject_code": "SR040000", "subject_code_description": "Antidiscrimination" }, { "subject_code": "SR010800", "subject_code_description": "Right to free movement and asylum" }, { "subject_code": "SR010000", "subject_code_description": "Individual liberties" }, { "subject_code": "SR000000", "subject_code_description": "Human rights" } ], "population_served_codes": [ { "population_served_code": "PG010100", "population_served_description": "Immigrants" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" } ], "ntee_codes": [ { "ntee_code": "P84", "ntee_code_description": "Ethnic/Immigrant Services" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 118743935.0, "total_expenses": 86362405.0, "total_assets": 115613843.0 }, "bmf_gross_receipts": 143276371.0, "bmf_assets": 115613843.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-19T15:32:16.0000000", "profile_last_modified": "2023-05-19T15:32:16.0000000", "dei_last_modified": "2023-05-19T00:00:00.0000000", "financials_last_modified": "2023-05-18T21:00:55.0000000", "last_modified": "2023-05-19T15:32:16.0000000" } }, { "organization": { "organization_id": "8251014", "ein": "84-0399006", "organization_name": "The Aspen Institute", "also_known_as": "", "group_exemption": "0000", "mission": "The Aspen Institute is a global nonprofit organization committed to realizing a free, just, and equitable society. Founded in 1949, the Institute drives change through dialogue, leadership, and action to help solve the most important challenges facing the United States and the world.\\n\\nWe bring together thoughtful people with diverse backgrounds and points of view. We cultivate and support values-based, purpose-driven leaders in many communities. We turn ideas into action and impact for individuals and society.", "website_url": "https://www.aspeninstitute.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8952758&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/84-0399006", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(202) 736-3849", "contact_title": "Chief of Staff", "number_of_employees": "720", "ruling_year": 1951 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "2300 N St NW Ste 700", "address_line_2": "", "city": "Washington", "state": "DC", "zip": "20037", "msa": "DC - Washington, DC-MD-VA", "congressional_district": "", "county": "District of Columbia, DC", "latitude": 38.9072, "longitude": -77.0501 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SK010000", "subject_code_description": "Public policy" }, { "subject_code": "SK000000", "subject_code_description": "Public affairs" }, { "subject_code": "SG000000", "subject_code_description": "Social sciences" } ], "population_served_codes": [ { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "V20", "ntee_code_description": "Social Science Research Institutes, Services" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 171246686.0, "total_expenses": 143773765.0, "total_assets": 465514933.0 }, "bmf_gross_receipts": 479307525.0, "bmf_assets": 465514933.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-04-24T08:26:54.0000000", "profile_last_modified": "2023-04-24T08:26:54.0000000", "dei_last_modified": "2021-04-16T15:40:24.0000000", "financials_last_modified": "2023-05-11T17:55:58.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "8145480", "ein": "75-0991727", "organization_name": "Fort Worth Zoological Association, Inc.", "also_known_as": "Fort Worth Zoo", "group_exemption": "0000", "mission": "The mission of the Fort Worth Zoo is to strengthen the bond between humans and the environment by promoting responsible stewardship of wildlife and ensuring diverse, high-quality educational and entertaining family experiences through effective and efficient management of its resources. The foundation of this mission statement is based on three cornerstone principles: Conservation: A commitment to affect positive change through the facilitation of conservation and sound scientific research. Education: A commitment to provide factual information to nurture an appreciation of and respect for wildlife and the environment. Entertainment: A commitment to excellence and to always exceed our guest's expectations", "website_url": "www.fortworthzoo.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9287230&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/75-0991727", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(817) 759-7555", "contact_title": "", "number_of_employees": "751", "ruling_year": 1952 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "1989 Colonial Pkwy", "address_line_2": "", "city": "Fort Worth", "state": "TX", "zip": "76110", "msa": "TX - Fort Worth", "congressional_district": "District 12, TX", "county": "Tarrant, TX", "latitude": 32.7227, "longitude": -97.3601 }, "taxonomies": { "subject_codes": [ { "subject_code": "SC040107", "subject_code_description": "Zoos" }, { "subject_code": "SC040100", "subject_code_description": "Wildlife biodiversity" }, { "subject_code": "SC040000", "subject_code_description": "Biodiversity" }, { "subject_code": "SC000000", "subject_code_description": "Environment" } ], "population_served_codes": [ { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "D50", "ntee_code_description": "Zoo, Zoological Society" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 52699554.0, "total_expenses": 65564329.0, "total_assets": 96773959.0 }, "bmf_gross_receipts": 55949795.0, "bmf_assets": 96773959.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-07-24T11:39:46.0000000", "profile_last_modified": "2023-07-24T11:48:06.0000000", "dei_last_modified": "2023-07-24T00:00:00.0000000", "financials_last_modified": "2023-05-11T17:31:11.0000000", "last_modified": "2023-07-24T11:48:06.0000000" } }, { "organization": { "organization_id": "9233935", "ein": "90-0884353", "organization_name": "Shed NYC Inc", "also_known_as": "The Shed", "group_exemption": "0000", "mission": "The Shed is a new cultural institution of and for the 21st century. We produce and welcome innovative art and ideas, across all forms of creativity, to build a shared understanding of our rapidly changing world and a more equitable society.As an independent nonprofit that values invention, equity, and generosity, we are committed to advancing art forms, addressing the urgent issues of our time, and making our work impactful, sustainable, and relevant to the local community, the cultural sector, New York City, and beyond.", "website_url": "theshed.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8512700&approved=True", "profile_level": "Silver", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/90-0884353", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-SILVER2023-seal.svg", "leader_name": "<NAME>", "leader_title": "PRESIDENT AND COO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "Associate Director of Development Operations", "number_of_employees": "719", "ruling_year": 2013 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "The Bloomberg Building 545 W 30 St", "address_line_2": "", "city": "New York City", "state": "NY", "zip": "10001", "msa": "NY - New York, NY-NJ", "congressional_district": "District 10, NY", "county": "New York, NY", "latitude": 40.7496, "longitude": -73.9962 }, "taxonomies": { "subject_codes": [ { "subject_code": "SA060000", "subject_code_description": "Performing arts" }, { "subject_code": "SA010000", "subject_code_description": "Arts services" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" } ], "population_served_codes": [ { "population_served_code": "PJ100000", "population_served_description": "Artists and performers" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "A61", "ntee_code_description": "Performing Arts Centers" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 48390004.0, "total_expenses": 38489710.0, "total_assets": 605118283.0 }, "bmf_gross_receipts": 55109661.0, "bmf_assets": 605118283.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-01-18T19:03:54.0000000", "profile_last_modified": "2023-01-18T19:15:06.0000000", "dei_last_modified": "2023-01-18T19:03:09.0000000", "financials_last_modified": "2023-04-01T07:08:23.0000000", "last_modified": "2023-04-01T07:08:23.0000000" } }, { "organization": { "organization_id": "8389636", "ein": "94-0382780", "organization_name": "Chinese Hospital", "also_known_as": "Chinese Hospital", "group_exemption": "0000", "mission": "Chinese Hospital, a community-owned, not-for-profit organization, exists primarily to deliver quality health care in a cost effective way, responsive to the community's ethnic and cultural uniqueness, providing access to health care and acceptability to all socioeconomic levels. Chinese Hospital is governed by a voluntary Board of Trustees, broadly representative of the community, and strives to assume a leadership role in all health matters. Chinese Hospital's mission emphasizes these important points:*Community ownership and responsiveness*Community leadership*Cultural uniqueness*Concern for a broad spectrum of health needs, including but not limited to hospital care.", "website_url": "http://www.chinesehospital-sf.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9057582&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/94-0382780", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "Dr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(415) 677-2470", "contact_title": "Chief Executive Officer", "number_of_employees": "566", "ruling_year": 1935 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "845 Jackson St", "address_line_2": "", "city": "San Francisco", "state": "CA", "zip": "94133", "msa": "CA - San Francisco-Oakland", "congressional_district": "District 12, CA", "county": "San Francisco, CA", "latitude": 37.7957, "longitude": -122.409 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE040400", "subject_code_description": "Hospital care" }, { "subject_code": "SE040000", "subject_code_description": "In-patient medical care" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "E22", "ntee_code_description": "Hospital (General)" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "12", "foundation_code_description": "Hospital or medical research organization" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 125188263.0, "total_expenses": 135350258.0, "total_assets": 303436312.0 }, "bmf_gross_receipts": 125337093.0, "bmf_assets": 303436312.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-25T18:55:25.0000000", "profile_last_modified": "2023-05-25T18:55:25.0000000", "dei_last_modified": "2023-05-25T00:00:00.0000000", "financials_last_modified": "2023-05-18T19:00:46.0000000", "last_modified": "2023-05-25T18:55:25.0000000" } }, { "organization": { "organization_id": "8444846", "ein": "95-2796316", "organization_name": "NEIGHBORHOOD HEALTHCARE", "also_known_as": "95-2796316", "group_exemption": "0000", "mission": "Our mission is to improve the health and happiness of the communities we serve by providing quality care toall, regardless of situation or circumstance.", "website_url": "http://www.nhcare.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9375875&approved=True", "profile_level": "Platinum", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/95-2796316", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "leader_name": "<NAME>", "leader_title": "Chief Executive Officer", "contact_name": "Dr. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(760) 520-8300", "contact_title": "CEO", "number_of_employees": "1012", "ruling_year": 1973 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": false } }, "geography": { "address_line_1": "425 N Date St Ste 203", "address_line_2": "", "city": "Escondido", "state": "CA", "zip": "92025", "msa": "CA - San Diego", "congressional_district": "District 50, CA", "county": "San Diego, CA", "latitude": 33.1289, "longitude": -117.0714 }, "taxonomies": { "subject_codes": [ { "subject_code": "SE120200", "subject_code_description": "Community mental health care" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE040200", "subject_code_description": "Community health care" }, { "subject_code": "SE040000", "subject_code_description": "In-patient medical care" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PH020000", "population_served_description": "People with diseases and illnesses" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PE000000", "population_served_description": "Ethnic and racial groups" } ], "ntee_codes": [ { "ntee_code": "E99", "ntee_code_description": "Health - General and Rehabilitative N.E.C." } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 149081726.0, "total_expenses": 120846295.0, "total_assets": 143902623.0 }, "bmf_gross_receipts": 149186005.0, "bmf_assets": 143902623.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-06-02T14:50:01.0000000", "profile_last_modified": "2023-08-21T20:20:39.0000000", "dei_last_modified": "2023-08-14T00:00:00.0000000", "financials_last_modified": "2023-05-18T21:00:55.0000000", "last_modified": "2023-08-21T20:20:39.0000000" } }, { "organization": { "organization_id": "7279686", "ein": "24-0804602", "organization_name": "KING'S COLLEGE", "also_known_as": "", "group_exemption": "0000", "mission": "King's College is a Catholic institution of higher education animated and guided by the Congregation of Holy Cross. King's pursues excellence in teaching, learning, and scholarship through a rigorous core curriculum, major programs across the liberal arts and sciences, nationally accredited professional programs at the undergraduate and graduate levels, and personal attention to student formation in a nurturing community. Since its founding in 1946, King's has been dedicated to the Holy Cross ideal of transforming minds and hearts with zeal in communities of hope. The College's commitment to students is expressed both in the curriculum and in co-curricular programs encouraging service, fostering reflection, and cultivating leadership skills.", "website_url": "www.kings.edu", "logo_url": "", "profile_level": "Bronze", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/24-0804602", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-BRONZE2023-seal.svg", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "1089", "ruling_year": 1977 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": false, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": false, "independent": true, "headquarters": true } }, "geography": { "address_line_1": "133 N River St", "address_line_2": "", "city": "Wilkes Barre", "state": "PA", "zip": "18711", "msa": "PA - Scranton-Wilkes-Barre-Hazleton", "congressional_district": "District 8, PA", "county": "Luzerne, PA", "latitude": 41.2773, "longitude": -77.2258 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB050300", "subject_code_description": "University education" }, { "subject_code": "SB050200", "subject_code_description": "Undergraduate education" }, { "subject_code": "SB050000", "subject_code_description": "Higher education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B43", "ntee_code_description": "University or Technological" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "11", "foundation_code_description": "School" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 93732066.0, "total_expenses": 103468593.0, "total_assets": 268680451.0 }, "bmf_gross_receipts": 108041300.0, "bmf_assets": 268680451.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-03-07T14:38:02.0000000", "profile_last_modified": "2023-03-07T14:41:01.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-06-23T11:00:41.0000000" } }, { "organization": { "organization_id": "6938869", "ein": "13-5602319", "organization_name": "Catholic Medical Mission Board, Inc.", "also_known_as": "CMMB", "group_exemption": "0928", "mission": "Inspired by the example of Jesus, CMMB works in partnership globally to deliver locally sustainable, quality health solutions to women, children, and their communities.Our vision is a world in which every human life is valued, and health and human dignity are shared by all.", "website_url": "https://cmmb.org/", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9267927&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/13-5602319", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "(212) 242-7757", "contact_title": "Operations and Donor Experience", "number_of_employees": "55", "ruling_year": 1946 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "3301 11th St", "address_line_2": "", "city": "Astoria", "state": "NY", "zip": "11106", "msa": "NY - New York, NY-NJ", "congressional_district": "District 12, NY", "county": "Queens, NY", "latitude": 40.7629, "longitude": -73.931 }, "taxonomies": { "subject_codes": [ { "subject_code": "ST040000", "subject_code_description": "International development" }, { "subject_code": "ST000000", "subject_code_description": "International relations" }, { "subject_code": "SJ060000", "subject_code_description": "Disasters and emergency management" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" }, { "subject_code": "SE130000", "subject_code_description": "Public health" }, { "subject_code": "SE040200", "subject_code_description": "Community health care" }, { "subject_code": "SE040000", "subject_code_description": "In-patient medical care" }, { "subject_code": "SE000000", "subject_code_description": "Health" } ], "population_served_codes": [ { "population_served_code": "PH020000", "population_served_description": "People with diseases and illnesses" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" } ], "ntee_codes": [ { "ntee_code": "Q30", "ntee_code_description": "International Development, Relief Services" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 411400438.0, "total_expenses": 351930119.0, "total_assets": 138995355.0 }, "bmf_gross_receipts": 411883466.0, "bmf_assets": 138995355.0, "required_to_file_990t": true, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-07-18T09:30:00.0000000", "profile_last_modified": "2023-07-18T09:30:00.0000000", "dei_last_modified": "2022-12-10T00:00:00.0000000", "financials_last_modified": "2023-05-10T07:00:16.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } } ] } ``` ## Filter search results by group exemption and relationship type Filter search results by group exemption and relationship type to return all child organizations within a group exemption. ``` { "filters": { "organization": { "properties": { "relationship_type": { "subordinate": true } }, "group_exemption": [ "0123" ] } } } ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 35, "time": "2023-08-29 18:39:21Z", "results_count": 101, "page_count": 5, "errors": [], "hits": [ { "organization": { "organization_id": "6855358", "ein": "04-6112839", "organization_name": "Alpha Omega International Dental Fraternity", "also_known_as": "BOSTON CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/04-6112839", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1953 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "5 Harwich Ln", "address_line_2": "", "city": "Andover", "state": "MA", "zip": "01810", "msa": "MA - Lawrence-Haverhill, MA-NH", "congressional_district": "District 6, MA", "county": "Essex, MA", "latitude": 42.6312, "longitude": -71.1176 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-12-13T14:59:00.0000000" } }, { "organization": { "organization_id": "7163383", "ein": "23-7138107", "organization_name": "Alpha Omega International Dental Fraternity", "also_known_as": "SEATTLE CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/23-7138107", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "8405 SE 53rd Pl", "address_line_2": "", "city": "Mercer Island", "state": "WA", "zip": "98040", "msa": "WA - Seattle-Everett", "congressional_district": "District 9, WA", "county": "King, WA", "latitude": 47.5541, "longitude": -122.2249 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2023-03-14T12:27:00.0000000" } }, { "organization": { "organization_id": "8873419", "ein": "27-0259668", "organization_name": "Alpha Omega International Dental Fraternity", "also_known_as": "INDIANAPOLIS CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/27-0259668", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "8267 Twin Pointe Cir", "address_line_2": "", "city": "Indianapolis", "state": "IN", "zip": "46236", "msa": "IN - Indianapolis", "congressional_district": "District 5, IN", "county": "Marion, IN", "latitude": 39.9067, "longitude": -85.9671 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-12-13T14:59:00.0000000" } }, { "organization": { "organization_id": "7416586", "ein": "34-6575895", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "CLEVELAND CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/34-6575895", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "4649 Colinas Dr", "address_line_2": "", "city": "Medina", "state": "OH", "zip": "44256", "msa": "OH - Cleveland", "congressional_district": "District 7, OH", "county": "Medina, OH", "latitude": 41.1163, "longitude": -81.8546 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-10-14T11:14:00.0000000" } }, { "organization": { "organization_id": "8889147", "ein": "61-1276503", "organization_name": "Alpha Omega International Dental Fraternity", "also_known_as": "LOUISVILLE CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/61-1276503", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1940 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "6402 Westwind Way Ste 4", "address_line_2": "", "city": "Crestwood", "state": "KY", "zip": "40014", "msa": "KY - Louisville, KY-IN", "congressional_district": "District 4, KY", "county": "Oldham, KY", "latitude": 38.3385, "longitude": -85.4758 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-09-09T13:27:18.0000000" } }, { "organization": { "organization_id": "8179715", "ein": "75-2506326", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "DALLAS CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "http://ao.org", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/75-2506326", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "7522 Campbell Rd", "address_line_2": "", "city": "Dallas", "state": "TX", "zip": "75248", "msa": "TX - Dallas-Fort Worth", "congressional_district": "District 32, TX", "county": "Dallas, TX", "latitude": 32.9782, "longitude": -96.7717 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-09-09T13:27:18.0000000" } }, { "organization": { "organization_id": "7166682", "ein": "23-7148401", "organization_name": "Alpha Omega International Dental Fraternity", "also_known_as": "COLUMBUS CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/23-7148401", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "215 S Drexel Ave", "address_line_2": "", "city": "Columbus", "state": "OH", "zip": "43209", "msa": "OH - Columbus", "congressional_district": "District 1, OH", "county": "Franklin, OH", "latitude": 39.9645, "longitude": -82.9375 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2022-09-09T13:27:18.0000000" } }, { "organization": { "organization_id": "7570996", "ein": "38-6091506", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "<NAME>", "group_exemption": "0123", "mission": "ALPHA OMEGA IS THE WORLDWIDE DENTAL ORGANIZATION THAT PROMOTES PROFESSIONAL EXCELLENCE THROUGH FAMILY, FRATERNAL AND JUDAIC VALUES.", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/38-6091506", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "PO Box 251304", "address_line_2": "", "city": "West Bloomfield", "state": "MI", "zip": "48325", "msa": "MI - Detroit", "congressional_district": "District 9, MI", "county": "Oakland, MI", "latitude": 42.6395, "longitude": -84.4233 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080100", "subject_code_description": "Alumni relations" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B84", "ntee_code_description": "Alumni Associations" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "EZ", "fiscal_year": 2022, "total_revenue": 31097.0, "total_expenses": 0.0, "total_assets": 21602.0 }, "bmf_gross_receipts": 31222.0, "bmf_assets": 21602.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "2023-05-18T15:27:11.0000000", "last_modified": "2023-07-10T17:03:00.0000000" } }, { "organization": { "organization_id": "7359897", "ein": "31-6063382", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "CINCINNATI CHAPTER", "group_exemption": "0123", "mission": "FRATERNITY FOR PROFESSIONAL DENTITS", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/31-6063382", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "4464 Carver Woods Dr", "address_line_2": "", "city": "Blue Ash", "state": "OH", "zip": "45242", "msa": "OH - Cincinnati, OH-KY-IN", "congressional_district": "District 2, OH", "county": "Hamilton, OH", "latitude": 39.2447, "longitude": -84.3857 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "EZ", "fiscal_year": 2021, "total_revenue": 700.0, "total_expenses": 190.0, "total_assets": 17780.0 }, "bmf_gross_receipts": 1600.0, "bmf_assets": 14089.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "2023-05-12T15:16:29.0000000", "last_modified": "2023-08-15T15:54:00.0000000" } }, { "organization": { "organization_id": "8488633", "ein": "95-6141202", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "LOS ANGELES CHAPTER", "group_exemption": "0123", "mission": "TO PROVIDE LECTURES, SEMINARS AND STUDY GROUPS BY LOCAL CHAPTERS FOR CONTINUING EDUCATION OF DENTISTS.", "website_url": "http://WWW.AOSOCAL.ORG", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/95-6141202", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "0", "ruling_year": 1966 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "2901 Wilshire Blvd Ste 405", "address_line_2": "", "city": "Santa Monica", "state": "CA", "zip": "90403", "msa": "CA - Los Angeles-Long Beach", "congressional_district": "", "county": "Los Angeles, CA", "latitude": 34.0391, "longitude": -118.4737 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 33248.0, "total_expenses": 22173.0, "total_assets": 242635.0 }, "bmf_gross_receipts": 33248.0, "bmf_assets": 242635.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "2023-05-11T17:55:58.0000000", "last_modified": "2023-05-11T17:55:58.0000000" } }, { "organization": { "organization_id": "7787958", "ein": "52-6056062", "organization_name": "Alpha Omega International Dental Fraternity", "also_known_as": "WASHINGTON DC CHAPTER", "group_exemption": "0123", "mission": "THE EXCHANGE OF KNOWLEDGE RELATING TO THE DENTAL PROFESSION AND THE FOSTERING OF FRATERNITY AMONG THE MEMBERS OF THE DENTAL PROFESSION.", "website_url": "http://ALPHAOMEGAWASHINGTONDC.ORG", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/52-6056062", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": null }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "5802 Hubbard Dr", "address_line_2": "", "city": "Rockville", "state": "MD", "zip": "20852", "msa": "MD - Washington, DC-MD-VA", "congressional_district": "District 8, MD", "county": "Montgomery, MD", "latitude": 39.055, "longitude": -77.1192 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "EZ", "fiscal_year": 2022, "total_revenue": 51474.0, "total_expenses": 60843.0, "total_assets": 41147.0 }, "bmf_gross_receipts": 62327.0, "bmf_assets": 41147.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "2023-05-18T17:01:47.0000000", "last_modified": "2023-05-18T17:01:47.0000000" } }, { "organization": { "organization_id": "6903461", "ein": "11-6037697", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "QUEENS-N<NAME>", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/11-6037697", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1940 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "100 Merrick Rd 106 E", "address_line_2": "", "city": "Rockville Centre", "state": "NY", "zip": "11570", "msa": "NY - Nassau-Suffolk", "congressional_district": "District 4, NY", "county": "Nassau, NY", "latitude": 40.6654, "longitude": -73.6366 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-15T19:26:47.0000000" } }, { "organization": { "organization_id": "6907684", "ein": "13-2684381", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "IOTA NEW YORK UNIVERSITY", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/13-2684381", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1971 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "384 Highland Ave", "address_line_2": "", "city": "Cliffside Park", "state": "NJ", "zip": "07010", "msa": "NJ - Bergen-Passaic", "congressional_district": "District 9, NJ", "county": "Bergen, NJ", "latitude": 40.8163, "longitude": -73.9866 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-15T19:28:13.0000000" } }, { "organization": { "organization_id": "6946428", "ein": "13-6207763", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "STATEN ISLAND CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/13-6207763", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "1011 Richmond Rd", "address_line_2": "", "city": "Staten Island", "state": "NY", "zip": "10304", "msa": "NY - New York, NY-NJ", "congressional_district": "District 11, NY", "county": "Richmond, NY", "latitude": 40.602, "longitude": -74.0928 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-15T19:38:21.0000000" } }, { "organization": { "organization_id": "7618958", "ein": "41-1397325", "organization_name": "Alpha Omega International Dental Fraternity, Inc.", "also_known_as": "MINNESOTA CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/41-1397325", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "2905 Dean Pkwy", "address_line_2": "", "city": "Minneapolis", "state": "MN", "zip": "55416", "msa": "MN - Minneapolis-St. Paul, MN-WI", "congressional_district": "District 5, MN", "county": "Hennepin, MN", "latitude": 44.9502, "longitude": -93.3393 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-16T06:13:52.0000000" } }, { "organization": { "organization_id": "7670890", "ein": "43-6048918", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "SAINT LOUIS CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/43-6048918", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1940 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "1100 Horse Run Ct", "address_line_2": "", "city": "Chesterfield", "state": "MO", "zip": "63005", "msa": "MO - St. Louis, MO-IL", "congressional_district": "District 2, MO", "county": "Saint Louis, MO", "latitude": 38.6484, "longitude": -90.6368 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-16T07:28:41.0000000" } }, { "organization": { "organization_id": "7794107", "ein": "52-6068044", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "BALTIMORE CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/52-6068044", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "12089 Long Lake Dr", "address_line_2": "", "city": "Owings Mills", "state": "MD", "zip": "21117", "msa": "MD - Baltimore", "congressional_district": "District 2, MD", "county": "Baltimore, MD", "latitude": 39.4574, "longitude": -76.7908 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-16T14:11:03.0000000" } }, { "organization": { "organization_id": "7819807", "ein": "54-6065155", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "NORFOLK CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/54-6065155", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "355 Crawford St Ste 612", "address_line_2": "", "city": "Portsmouth", "state": "VA", "zip": "23704", "msa": "VA - Norfolk-Virginia Beach-Newport News, VA-NC", "congressional_district": "District 1, VA", "county": "Portsmouth City, VA", "latitude": 36.8374, "longitude": -76.2979 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-16T14:52:45.0000000" } }, { "organization": { "organization_id": "7734589", "ein": "51-0241068", "organization_name": "Alpha Omega International Dental Fraternity, Inc.", "also_known_as": "<NAME>", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/51-0241068", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "8811 Frankway Dr <NAME>", "address_line_2": "", "city": "Houston", "state": "TX", "zip": "77096", "msa": "TX - Houston", "congressional_district": "District 7, TX", "county": "Harris, TX", "latitude": 29.6878, "longitude": -95.4546 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-16T12:59:32.0000000" } }, { "organization": { "organization_id": "7755231", "ein": "51-0178872", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "AUGUSTA CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/51-0178872", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "1519 Laney Walker Blvd", "address_line_2": "", "city": "Augusta", "state": "GA", "zip": "30904", "msa": "GA - Augusta-Aiken, GA-SC", "congressional_district": "District 12, GA", "county": "Richmond, GA", "latitude": 33.4708, "longitude": -81.9932 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-16T12:45:21.0000000" } }, { "organization": { "organization_id": "8262634", "ein": "84-6045610", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "<NAME>", "group_exemption": "0123", "mission": "", "website_url": "denver.ao.org", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/84-6045610", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "9592 E Maplewood Cir", "address_line_2": "", "city": "Englewood", "state": "CO", "zip": "80111", "msa": "CO - Denver-Boulder", "congressional_district": "District 6, CO", "county": "Arapahoe, CO", "latitude": 39.6034, "longitude": -104.8773 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 8888.0, "bmf_assets": 12918.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-17T11:40:16.0000000" } }, { "organization": { "organization_id": "8281499", "ein": "86-0839262", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "GREATER PHOENIX CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/86-0839262", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "29243 N 69th Way", "address_line_2": "", "city": "Scottsdale", "state": "AZ", "zip": "85266", "msa": "AZ - Phoenix-Mesa", "congressional_district": "District 6, AZ", "county": "Maricopa, AZ", "latitude": 33.751, "longitude": -111.9301 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-17T13:29:19.0000000" } }, { "organization": { "organization_id": "8284581", "ein": "86-0973217", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "ALBUQUERQUE", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/86-0973217", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "4620 Jefferson Ln NE", "address_line_2": "", "city": "Albuquerque", "state": "NM", "zip": "87109", "msa": "NM - Albuquerque", "congressional_district": "", "county": "Bernalillo, NM", "latitude": 35.1342, "longitude": -106.5933 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-17T13:35:15.0000000" } }, { "organization": { "organization_id": "8344329", "ein": "91-2009856", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "ORLANDO CHAPTER", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/91-2009856", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "926 N Maitland Ave", "address_line_2": "", "city": "Maitland", "state": "FL", "zip": "32751", "msa": "FL - Orlando", "congressional_district": "District 7, FL", "county": "Orange, FL", "latitude": 28.6349, "longitude": -81.3657 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-17T17:05:24.0000000" } }, { "organization": { "organization_id": "8346554", "ein": "91-2010006", "organization_name": "Alpha Omega International Dental Fraternity Inc", "also_known_as": "SIGMA BETA STONY BROOK UNIVERSITY", "group_exemption": "0123", "mission": "", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/91-2010006", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1966 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "140 Grerla Hollow Rd", "address_line_2": "", "city": "E Setauket", "state": "NY", "zip": "11733", "msa": "NY - Nassau-Suffolk", "congressional_district": "District 1, NY", "county": "Suffolk, NY", "latitude": 40.931, "longitude": -73.1015 }, "taxonomies": { "subject_codes": [ { "subject_code": "SB080200", "subject_code_description": "Sororities and fraternities" }, { "subject_code": "SB080000", "subject_code_description": "Student services" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "B83", "ntee_code_description": "Student Sororities, Fraternities" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes." } }, "financials": { "most_recent_year": { "form_type": "", "fiscal_year": null, "total_revenue": null, "total_expenses": null, "total_assets": null }, "bmf_gross_receipts": 0.0, "bmf_assets": 0.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "", "last_modified": "2021-10-17T17:05:25.0000000" } } ] } ``` Updated about 2 months ago ## Search using keywords and filtering for city, state, ## Filter search results by NTEE major and minor codes Filter results by using NTEE major and minor code filters. NTEE major codes are high-level, while NTEE minor codes are more discrete. ``` { "filters": { "organization": { "ntee_major_codes": [ "T" ] } } } ``` ``` { "filters": { "organization": { "ntee_minor_codes": [ "T50" ] } } } ``` ``` { "filters": { "organization": { "form_types": { "f990": true, "f990pf": false, "required_to_file_990t": true }, "audits": { "a_133_audit_performed": true } }, "financials": { "total_revenue": { "min": 5000000 }, "total_expenses": { "min": 3000000 }, "total_assets": { "max": 300000000 } } } } ``` Updated 11 months ago Generate comprehensive nonprofit profiles that include program results, financial breakdowns, operations, and more to gives users the details they need to make informed decisions. * Brand nonprofit profile pages that highlight the mission, address, contact information and social media channels for users to get in touch. * Display programs, results, and feedback goals for users to see how the nonprofit is achieving their mission. * Access years of detailed nonprofit financial data and enjoy out of the box analytics with our Financial Trends Analysis Report. * Allow users to download reporting including Form 990s, Annual Reports, Audited Financials, and Letters of Determination. The following endpoints are the most recent versions included with Premier API: Premier (GuideStar Profile) Endpoint * Premier API v3 (Most Recent Version) Use an EIN in the path parameter to get the nonprofit profile financials, people, DEI, and IRS compliance validation. Premier PDF Endpoints Premier Financial Trends Analysis PDF API v1 Use an EIN in the path parameter to get a PDF of the nonprofit profile financial trends analysis. * Premier GuideStar Pro Report PDF API v1 Use an EIN in the path parameter to get a PDF report of the nonprofit profile financials, people, and IRS compliance validation. ## Premier endpoint-specific user guides * Premier API v3 Use our most comprehensive API to power your application with robust financials, organizational information and effortless nonprofit compliance validation. * Organization demographic data How to use the organizational demographic data available in the Premier v3 API. ## Premier PDFs endpoint-specific user guides * Premier Financial Trends Analysis PDF API Use an EIN in the path parameter to get a PDF of the nonprofit profile financial trends analysis. * Premier GuideStar Pro Report PDF API Use an EIN in the path parameter to get a PDF report of the nonprofit profile financials, people, and IRS compliance validation. Updated almost 2 years ago Date: 1998-07-31 Categories: Tags: Use our most comprehensive API to power your application with robust financials, organizational information and effortless nonprofit compliance validation. Premier v3 is the most recent version. Users of Premier v2 or v1 are encouraged to adopt Premier v3. Premier API only accepts GET requests. ``` https://api.candid.org/premier/v3/13-1837418 ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 279, "errors": [], "data": { "summary": { "organization_id": 6908122, "organization_name": "Candid", "ein": "13-1837418", "bridge_id": null, "address_line_1": "32 Old Slip", "address_line_2": "24th Floor", "city": "New York", "state": "NY", "zip": "10005", "county": "New York", "latitude": "40.705966", "longitude": "-74.008849", "fax": "(212)807-3677", "govt_registered_name": "Candid", "also_known_as": "The Foundation Center, Foundation Center, GuideStar, GuideStar USA", "fiscal_year_end": "Dec 31", "fiscal_year_start": "Jan 1", "affiliation_code": "3", "affiliation_description": "Independent - This code is used if the organization is an indepenedent organization or an independent auxiliary (i.e., not affiliated with a a National, Regional, or Geographic grouping of organizations).", "contact_name": "<NAME>", "contact_title": "Director of Communications", "contact_email": "<EMAIL>", "contact_phone": "212-620-4230", "contact_fax": "212-807-3677", "gs_profile_update_level": "Platinum 2021", "gs_profile_update_level_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2021-seal.svg", "deductibility_code": "1", "deductibility_description": "Contributions are deductible, as provided by law", "donation_to_ein": "13-1837418", "donation_to_name": "Candid", "areas_served_narrative": null, "ruling_year": "1957", "gs_public_report": "https://www.guidestar.org/profile/13-1837418", "gs_pro_pdf": "https://apidata.guidestar.org/premier/v1/propdf/13-1837418", "gs_financial_trends_analysis_pdf": "https://apidata.guidestar.org/premier/v1/ftapdf/13-1837418", "impact_statement": null, "subsection_code": "03", "subsection_description": "501(c)(3) Public Charity", "keywords": "philanthropy, data, transparency, capacity building, research, education, foundations, foundation, charitable giving, data driven decisions, nonprofits, transparency, nonprofit sector, organizational effectiveness, organizational efficiency, nonprofit information hub, Forms 990, GuideStar, Foundation Center", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185344&approved=True", "mission": "Candid gets you the information you need to do good.", "is_national_hq": false, "ntee_code": "T50 - Philanthropy, Voluntarism, and Grantmaking", "sdg": { "id": 17, "description": "Partnerships for the Goals" }, "website_url": "candid.org", "year_founded": "1956", "year_incorporated": "", "is_non_bmf_org": false, "first_on_bmf_date": "1998-07-31T04:00:00Z", "last_on_bmf_date": "2021-10-11T04:00:00Z", "profile_data_change_dates": { "primary_address_last_modified": "2020-11-12T14:28:48", "payment_address_last_modified": "2021-05-24T15:41:46", "primary_contact_email_last_modified": "2020-11-12T14:28:48", "fundraising_contact_email_last_modified": "2020-11-12T14:28:48", "org_website_last_modified": "2020-11-12T14:28:48" }, "addresses": [ { "address_line_1": "32 Old Slip", "address_line_2": "24th Floor", "city": "New York", "state": "NY", "postal_code": "10005", "country": "USA", "address_type": "Main Address" }, { "address_line_1": "32 Old Slip", "address_line_2": "24th Floor", "city": "New York", "state": "NY", "postal_code": "10005", "country": "USA", "address_type": "Physical Address" }, { "address_line_1": "P.O. Box 22799", "address_line_2": "", "city": "New York", "state": "NY", "postal_code": "10087-2799", "country": "USA", "address_type": "Payment/Donation Address" } ], "affiliations": null, "awards": null, "formerly_known_as": [ { "former_name": "", "year": "" } ], "forms_1023_1024": null, "letters_of_determination": [ { "letter_of_determination_doc_name": "Candid IRS Letter of Determination", "letter_of_determination_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185350&approved=True" } ], "letters_of_dissolution": null, "ntee_codes": [ { "ntee_code": "T50", "primary_code": "T", "primary_description": "Philanthropy, Voluntarism, and Grantmaking", "sub_code": "50", "sub_description": "Philanthropy / Charity / Voluntarism Promotion (General)" } ], "naics_code": { "naics_code": "813219", "naics_description": "Other Grantmaking and Giving Services " }, "sic_codes": [ { "sic_code": "8399", "sic_description": "Social Services, NEC" } ], "platinum_evaluation_documents": [ { "document_name": "", "document_year": "", "document_url": "", "document_type": "" } ], "other_documents": [ { "document_name": "Candid's 2030 Vision", "document_year": "2020", "otherdocument_contents": "/ViewEdoc.aspx?edocId=7185360&approved=true", "document_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185360&approved=True" } ], "photos": [ { "picture_url": "", "caption": "" } ], "social_media_urls": [ "https://www.facebook.com/CandidDotOrg/", "https://twitter.com/CandidDotOrg", "https://www.linkedin.com/company/candiddotorg/", "https://www.youtube.com/user/candiddotorg", "https://www.instagram.com/candiddotorg/" ], "telephone_numbers": [ { "telephone_number": "(212)620-4230", "telephone_type": "Preferred" } ], "videos": [ { "video_caption": "", "video_url": "" } ], "org_collect_feedback": true, "org_feedback_example": "", "org_quiz_interest": false, "org_learn_more": false, "feedback_responses": [ { "question_text": "How is your organization collecting feedback from the people you serve?", "response_text": "We regularly collect feedback through: Electronic surveys (by email, tablet, etc.), Focus groups or interviews (by phone or in person), Community meetings/Town halls, Constituent (client or resident, etc.) advisory committees, other: Online Chat" }, { "question_text": "How is your organization using feedback from the people you serve?", "response_text": "We use feedback to: To identify and remedy poor client service experiences, To identify bright spots and enhance positive service experiences, To make fundamental changes to our programs and/or operations, To inform the development of new programs/projects, To identify where we are less inclusive or equitable across demographic groups, To strengthen relationships with the people we serve" }, { "question_text": "With whom is the organization sharing feedback?", "response_text": "We share feedback with: Our staff, Our board" }, { "question_text": "What challenges does the organization face when collecting feedback?", "response_text": "It is difficult to: It is difficult to get the people we serve to respond to requests for feedback" } ], "pcs_codes": [ { "pcs_facet": "Population", "pcs_code": "PA000000", "pcs_description": "Age groups", "pcs_parent_code": null, "pcs_parent_description": null }, { "pcs_facet": "Subject", "pcs_code": "SB000000", "pcs_description": "Education", "pcs_parent_code": null, "pcs_parent_description": null }, { "pcs_facet": "Subject", "pcs_code": "SD000000", "pcs_description": "Philanthropy", "pcs_parent_code": null, "pcs_parent_description": null } ], "profile_sdg_codes": [ { "id": 17, "description": "Partnerships for the Goals" }, { "id": 1, "description": "No Poverty" }, { "id": 2, "description": "Zero Hunger" }, { "id": 3, "description": "Good Health and Well-being" }, { "id": 4, "description": "Quality Education" }, { "id": 5, "description": "Gender Equality" }, { "id": 10, "description": "Reduced Inequalities" }, { "id": 9, "description": "Industry, Innovation and Infrastructure" }, { "id": 8, "description": "Decent Work and Economic Growth" }, { "id": 7, "description": "Affordable and Clean Energy" }, { "id": 6, "description": "Clean Water and Sanitation" }, { "id": 11, "description": "Sustainable Cities and Communities" }, { "id": 13, "description": "Climate Action" }, { "id": 15, "description": "Life on Land" }, { "id": 14, "description": "Life Below Water" }, { "id": 16, "description": "Peace, Justice and Strong Institutions" }, { "id": 12, "description": "Responsible Consumption and Production" } ] }, "programs": { "programs": [ { "name": "Knowledge Tools", "description": "Through data, research, and our collective experience, Candid provides users with the knowledge they need to make strategic decisions and develop practical solutions to achieve their missions. \n\nOur GuideStar database makes it easier to understand nonprofits and what they do. We support ongoing learning and research by sharing the sector’s collective knowledge on IssueLab while also producing our own research. Through Glasspockets we provide the data, resources, examples, and action steps foundations need to understand the value of transparency and be more open in their own communications. We work closely with organizations around the globe to assist them in collecting and organizing their region’s philanthropy data by sharing what we have learned about data acquisition and data architecture. Our CF Insights program is the leader in data collection and research for the community foundation field in the U.S. with a reputation for benchmarking and analysis of trends.", "target_population": "General/Unspecified", "target_population2": "", "budget": "", "areas_served": [ "Global" ] }, { "name": "Data Tools", "description": "Candid ensures that nonprofit information is available whenever and wherever it is needed. Through our GuideStar database we share information on 2.8 million current and historic tax exempt organizations. Nonprofits use the tool to showcase their work, find partners for collaboration, and connect with other leaders in the field; donors use it to find nonprofits that champion the causes they care about. Our data feeds into tools used by community foundations, grants management vendors, grantmaking organizations, and philanthropic websites and applications such as Volunteer Match, AmazonSmile, and Facebook. \n\nFoundation Directory Online (FDO) provides subscribers with access to timely, comprehensive information on U.S. grantmakers and their grants, plus a growing number of foundations located outside of the U.S. FDO contains data on 19 million grants and 166,000 grantmakers, and is freely accessible to organizations and community stakeholders at our 400+ FIN partners. \n\nFoundation Maps contains records on more than 16.8 million grants, with innovative ways to visualize funding data, and the flexibility and precision to tailor research. This tool helps funders and nonprofits access the data they need to make strategic decisions and strengthen their impact.", "target_population": "General/Unspecified", "target_population2": "", "budget": "", "areas_served": [ "Global" ] }, { "name": "Grantseeker Tools", "description": "Each year, hundreds of thousands of people use Candid’s searchable database, Foundation Directory Online (FDO), to find supporters and partners to advance their work. FDO, the world’s most robust source of foundation and grants data, is available for free use at our 400+ Funding Information Network (FIN) partners. Located at libraries, community foundations, and colleges, our FIN assures public access to our resources across the U.S. and several other countries. By making our subscription services accessible at no cost through our network and providing capacity building services online, we ensure that 99 percent of the people that use our services do so for free. We also provide free introductory trainings in-person and online to help nonprofit professionals learn the skills they need (such as proposal writing, prospect research, etc.) to find funding, enabling them to sustain their programs in the communities they serve.", "target_population": "General/Unspecified", "target_population2": "", "budget": "", "areas_served": [ "Global" ] }, { "name": "Training", "description": "Candid operates research, education, and training programs designed to advance knowledge about philanthropy at every level, and provided under-resourced nonprofit organizations with the tools they need to better fulfill their missions. \n\nThrough Candid Learning, we provide tools and resources to help nonprofits become more viable grant applicants and build sustainable organizations. We offer trainings and special events in-person and online to build capacity in three core competencies: fundraising, organizational sustainability, and leadership and management. These resources help equip nonprofits to better serve their constituents and tackle critical social issues. \n\nGrantCraft combines the collective wisdom of funders worldwide with Candid’s expertise to help funders increase the impact of their funds. GrantCraft delivers the knowledge funders need to be strategic and effective in their work, addressing questions they face across various strategies and issue areas.\n\nWe also train nonprofits in-person and online to help them complete their GuideStar nonprofit profiles and showcase their work. Organizations are empowered to tell their stories and explain their impact through programmatic metrics.", "target_population": "General/Unspecified", "target_population2": "", "budget": "", "areas_served": [ "Global" ] } ], "platinum_metrics": [ { "metric": "Number of organizations you can find on GuideStar", "years": [ { "year": 2018, "value": 2761541.0 }, { "year": 2017, "value": 2675783.0 }, { "year": 2016, "value": 2585936.0 }, { "year": 2015, "value": 2489543.0 }, { "year": 2019, "value": 2869792.0 }, { "year": 2020, "value": 2768870.0 } ], "target_population_served": [], "type_of_metric": "Output - describing our activities and reach", "direction_of_success": "Increasing" }, { "metric": "Number of organizations who share enough information to earn a Seal of Transparency on GuideStar", "years": [ { "year": 2018, "value": 66602.0 }, { "year": 2017, "value": 48075.0 }, { "year": 2016, "value": 36534.0 }, { "year": 2015, "value": 32340.0 }, { "year": 2019, "value": 77129.0 }, { "year": 2020, "value": 74452.0 } ], "target_population_served": [], "type_of_metric": "Output - describing our activities and reach", "direction_of_success": "Increasing" }, { "metric": "Number of unique website visitors on GuideStar", "years": [ { "year": 2018, "value": 10507936.0 }, { "year": 2017, "value": 8836577.0 }, { "year": 2016, "value": 6864166.0 }, { "year": 2015, "value": 7146463.0 }, { "year": 2019, "value": 12900000.0 }, { "year": 2020, "value": 12314055.0 } ], "target_population_served": [], "type_of_metric": "Input - describing resources we use", "direction_of_success": "Increasing" }, { "metric": "Number of unique website visitors on all Foundation Center Web Properties, including Candid Learning, GrantCraft, Philanthropy News Digest, and Glasspockets", "years": [ { "year": 2018, "value": 6168572.0 }, { "year": 2017, "value": 5929660.0 }, { "year": 2016, "value": 6017225.0 }, { "year": 2015, "value": 5943208.0 }, { "year": 2019, "value": 7065815.0 }, { "year": 2020, "value": 7387190.0 } ], "target_population_served": [], "type_of_metric": "Input - describing resources we use", "direction_of_success": "Increasing" }, { "metric": "Number of Grants Coded", "years": [ { "year": 2018, "value": 3849017.0 }, { "year": 2017, "value": 3647847.0 }, { "year": 2016, "value": 3000000.0 }, { "year": 2015, "value": 300000.0 }, { "year": 2019, "value": 3900000.0 } ], "target_population_served": [], "type_of_metric": "Output - describing our activities and reach", "direction_of_success": "Increasing" }, { "metric": "Number of Funding Information Network Partners", "years": [ { "year": 2018, "value": 437.0 }, { "year": 2017, "value": 428.0 }, { "year": 2016, "value": 477.0 }, { "year": 2015, "value": 464.0 }, { "year": 2019, "value": 408.0 }, { "year": 2020, "value": 400.0 } ], "target_population_served": [], "type_of_metric": "Input - describing resources we use", "direction_of_success": "Increasing" }, { "metric": "Number of research reports and white papers available on IssueLab.org", "years": [ { "year": 2018, "value": 27297.0 }, { "year": 2017, "value": 23480.0 }, { "year": 2016, "value": 21220.0 }, { "year": 2015, "value": 18887.0 }, { "year": 2019, "value": 29317.0 }, { "year": 2020, "value": 29988.0 } ], "target_population_served": [], "type_of_metric": "Output - describing our activities and reach", "direction_of_success": "Increasing" }, { "metric": "Number of websites and organizations (outside of our organization) that share our resources and information", "years": [ { "year": 2018, "value": 240.0 }, { "year": 2017, "value": 204.0 }, { "year": 2016, "value": 190.0 }, { "year": 2015, "value": 154.0 }, { "year": 2019, "value": 246.0 }, { "year": 2020, "value": 250.0 } ], "target_population_served": [], "type_of_metric": "Output - describing our activities and reach", "direction_of_success": "Increasing" } ], "charting_impact_answers": [ { "question": "How would you summarize the problem or need your organization is working to address?", "answer": "Now more than ever, open access to timely, nonpartisan data and intelligence is critical to the ability to solve increasingly complex social issues. Our field needs a data-driven institution with the scale to support and advance the work of social sector stakeholders as we traverse a period of closing political space, technological upheaval, and global opportunity." }, { "question": "What is your organization aiming to accomplish", "answer": "Candid provides trusted information, data-driven tools, research, analysis, best practices, and trainings to help the social sector increase its ability to affect change and transform lives. We represent the world’s largest repositories of trusted historical and present-day information on nonprofits, foundations, and the capital flows that bind them. We aim to create the future of data, information, and knowledge for the social sector. We will also work to enhance the services we offer to the millions of people who rely on us to help them make the world a better place." }, { "question": "What are your strategies for making this happen?", "answer": "Candid will develop a new generation of products and services that are technologically sophisticated and designed to champion the causes, organizations, and knowledge that power civil society worldwide. We will leverage our shared stores of talent, data, indicators, research, news, and capacity-building resources to improve philanthropic systems and practices in the U.S. and around the world, and will enable knowledge sharing with the potential to transform how civil society and the social sector learns and improves.\n\nAs we integrate operations, we will continue the core work of both Foundation Center and GuideStar while using our combined expertise to amplify our impact. We will continue to learn from one another and those we serve to determine how to improve our offerings and provide tools that will help nonprofits, foundations, giving platforms, and other social sector stakeholders achieve their missions." }, { "question": "What are your organization's capabilities for doing this?", "answer": "With more than 80 years of collective experience supporting the social sector, Candid has the combined staff expertise, organizational capacity, and leadership to provide new resources and services for those in the social sector and beyond. \n\nWe are fortunate to have a staff of 200+ dedicated professionals skilled in building tools and delivering services to nonprofits, foundations, professionals, and individuals; stable financials and a plan for continued sustainability; an engaged board of directors from a wide variety of disciplines; and a large group of committed funders. Our staff leadership has a long track record of expanding our service to the field, often by capitalizing on new technologies. By developing the skills and knowledge base of our staff, we ensure that we can continue to innovate, and effectively identify and meet needs in the sector as they arise. \n\nCandid’s combined history of serving nonprofits, grantmakers, researchers, and do-gooders of all kinds provides us with unique insights into the the evolving needs of the social sector. These insights help us shape our offerings and ensure that we keep our finger on the pulse of what our users need to help them do good. We have long held that increasing transparency in our sector would increase its effectiveness, and that democratizing access to data, knowledge, and resources would level the playing field for those working to improve their communities and champion their causes. The combination of a trusted history of providing non-partisan data and knowledge and the ability to create cutting edge technology to propel the social sector forward gives us a unique vantage point from which to serve those who are working to build a better world." }, { "question": "How will your organization know if you are making progress?", "answer": "Candid works to ensure that our programs and services align with our overarching mission and goals. Each year, we create an organizational work plan, set our tactical organizational performance objectives by prioritizing key projects, and evaluate our progress against the implementation plan. GuideStar and Foundation Center’s 2019 key indicators can be found in the Programs and Results section of our profile.\n\nIn addition, we seek to constantly engage in the processes of listening to our social sector audience, and use what we learn to respond with innovative ideas, prototypes, and products and services. Our audience includes nonprofits, grantmakers, training and webinar participants, and customers, as well as our own staff. We continually apply the knowledge that we gain throughout the year to increase our relevance and value to our service recipients. While we use analytics to track users of our online resources, and monitor attendees at our classes and programs, we increasingly connect with our users through surveys and testimonials to learn how our work is benefiting them." }, { "question": "What have you accomplished so far and what's next?", "answer": "Candid was formed in 2019 with the integration of Foundation Center and GuideStar. The guiding work and missions of Foundation Center and GuideStar were complementary, and we collaborated over the years on data processing efficiencies, data standards for the social sector, and the development of a registry of unique identification numbers for nonprofits globally. We have helped each other maintain data standards and protect the integrity of the data that we collect. For example, one of our most recent collaborations included building the Basic Registry of Identified Global Entities (BRIDGE). BRIDGE numbers help the social sector discover what other data exists, integrate data systems, and ensure that nonprofits and service organizations are discoverable. Both organizations have made great strides in advancing the social sector, and we look forward to the exciting year that lies ahead." } ] }, "financials": { "most_recent_year_financials": { "period_begin": "2018-01-01T05:00:00Z", "period_end": "2018-12-31T05:00:00Z", "fiscal_year": 2018, "form_type": "F990", "data_source": "IRS Form 990", "assets_total": 45546348.0, "total_liabilities": 14772793.0, "revenue_contributions": 13834354.0, "revenue_govt_grants": 0.0, "revenue_program_services": 15511812.0, "revenue_investments": 298384.0, "revenue_special_events": 0.0, "revenue_sales": 0.0, "revenue_other": 62250.0, "total_revenue": 29706800.0, "expense_administration": 6654944.0, "expense_program_services": 18093787.0, "expense_fundraising": 1033190.0, "expense_accounting": 189708.0, "expense_advertising_promotion": 250313.0, "expense_info_technology": 1056301.0, "expense_insurance": 142522.0, "expense_interest": 57281.0, "expense_investment_management": 72143.0, "expense_legal": 468697.0, "expense_pension_plan": 1063097.0, "expense_professional_fundraising": null, "unrestricted_net_assets": 17241046.0, "net_fixed_assets_LBE": 15475765.0, "notes_payable_mortgages": 0.0, "months_of_cash": "8.6", "expense_professional_fees": null, "expense_publications": null, "expense_operating_admin": null, "expense_gifts_grants_paid": null, "total_expense_disbursements": null, "expenses_total": 25781921.0, "net_gain_loss": 3924879.0, "expense_salaries_employee_benefits": null, "cash_and_equivalent_assets": 162144.0, "investments_us_government": null, "investments_stock": null, "investments_bonds": null, "investments_other": null, "land_buildings_equipment": null, "other_assets": null }, "f990_financials": [ { "period_begin": "2018-01-01T05:00:00Z", "period_end": "2018-12-31T05:00:00Z", "membership_dues": 0.0, "revenue_contributions": 13834354.0, "revenue_govt_grants": 0.0, "revenue_program_services": 15511812.0, "revenue_investments": 298384.0, "revenue_special_events": 0.0, "revenue_sales": 0.0, "revenue_other": 62250.0, "revenue_total": 29706800.0, "affiliate_net_payments": null, "expense_program_services": 18093787.0, "expense_administration": 6654944.0, "expense_fundraising": 1033190.0, "expenses_total": 25781921.0, "net_gain_loss": 3924879.0, "expense_accounting": 189708.0, "expense_advertising_promotion": 250313.0, "expense_info_technology": 1056301.0, "expense_insurance": 142522.0, "expense_interest": 57281.0, "expense_investment_management": 72143.0, "expense_legal": 468697.0, "expense_pension_plan": 1063097.0, "expense_publications": 250313.0, "expense_profesional_fundraising": null, "assets_total": 45546348.0, "unrestricted_net_assets": 17241046.0, "net_fixed_assets_LBE": null, "net_assets_end_of_year": 30773555.0, "other_expense": 0.0, "notes_payable_mortgages": 0.0, "liabilities_total": 14772793.0, "months_of_cash": "8.6", "part_8_revenue": { "federated_campaigns": 0.0, "membership_dues": 0.0, "fundraising_events": 0.0, "related_orgs": 0.0, "government_grants": 0.0, "contributions_other": 13834354.0, "contributions_noncash": 0.0, "contributions_all": 13834354.0, "service_revenue": 15511812.0, "income_investment": 257743.0, "income_bonds": 0.0, "royalties": 0.0, "rents_real": 144698.0, "rents_personal": null, "rent_expenses_real": 134840.0, "rent_expenses_personal": null, "rent_income_real": 9858.0, "rent_income_personal": null, "net_rental": 9858.0, "gross_securities": 501739.0, "gross_other": null, "cost_securities": 470956.0, "cost_other": null, "gain_securities": 30783.0, "gain_other": null, "net_sales": 30783.0, "contributions": null, "gross_special": 0.0, "direct_expenses": null, "net_special": 0.0, "gaming_income": null, "gaming_expenses": null, "gaming_net": 0.0, "gross_sales": null, "cost_goods": null, "gross_profit": 0.0, "revenue_other": 62250.0, "revenue_total": 29706800.0, "service_description_a": "PRODUCT REVENUE", "service_code_a": 611710.0, "service_description_b": "FUNDING INFO. NETWORK", "service_amount_a": 12705091.0, "service_code_b": 611710.0, "service_amount_b": 800980.0, "service_description_c": "EDUCATIONAL PRGM REV.", "service_code_c": 611710.0, "service_amount_c": 478032.0, "service_description_d": "FOUNDATION BENCHMARKER", "service_code_d": 611710.0, "service_amount_d": 466806.0, "service_description_e": "FOUNDATION WEB BUILDER", "service_code_e": 611710.0, "service_amount_e": 104574.0, "service_description_f": null, "service_code_f": null, "service_amount_f": null }, "part_9_expenses": { "grants_orgs_us": null, "grants_individuals_us": null, "grants_orgs_non_us": null, "benefits_total": null, "compensation_current": 1137169.0, "compensation_disqualified": 0.0, "wages_total": 12197687.0, "pension_total": 1063097.0, "employee_benefits_total": 1994504.0, "payroll_tax_total": 526246.0, "fees_management": 0.0, "fees_legal": 468697.0, "accounting_fees_total": 189708.0, "fees_lobbying": null, "fundraising_total": null, "fees_investments": 72143.0, "fees_other": 733805.0, "ads_promo": 250313.0, "office": 681418.0, "information_technology": 1056301.0, "expense_royalties": 146.0, "occupancy_total": 2049215.0, "travel_total": 424943.0, "entertain_officials": null, "meetings_total": 117576.0, "interest_total": 57281.0, "payments": null, "depreciation_total": 2129713.0, "insurance": 142522.0, "expense_a_total": 169017.0, "expense_b_total": 73531.0, "expense_c_total": 48135.0, "expense_d_total": 27833.0, "expense_e_total": null, "expenses_total": 25781921.0, "total_program_services": 18093787.0, "total_management": 6654944.0, "total_fundraising": 1033190.0, "expense_joint_total": null, "joint_services": null, "joint_general": null, "joint_fundraising": null, "all_other_expenses": 170921.0, "expense_a_description": "SALES TAX EXPENSE", "expense_b_description": "REPAIRS AND MAINTENANCE", "expense_c_description": "RECRUITMENT COSTS", "expense_d_description": "UBIT EXPENSE" }, "part_10_balance_sheet": { "cash_boy": 155612.0, "cash_eoy": 162144.0, "savings_boy": 13505683.0, "savings_eoy": 16867058.0, "pledges_grants_boy": 2302243.0, "pledges_grants_eoy": 4508299.0, "accounts_receivable_boy": 551722.0, "accounts_receivable_eoy": 491761.0, "qualified_receivable_boy": 0.0, "qualified_receivable_eoy": 0.0, "disqualified_receivable_boy": 0.0, "disqualified_receivable_eoy": 0.0, "loans_receivable_boy": null, "loans_receivable_eoy": null, "inventory_boy": 3026.0, "inventory_eoy": 3026.0, "prepaid_boy": 348723.0, "prepaid_eoy": 639890.0, "lbe_base": 23062951.0, "less_depreciation": 15475765.0, "lbe_boy": 9716899.0, "lbe_eoy": 7587186.0, "public_securities_boy": 0.0, "public_securities_eoy": 0.0, "other_securities_boy": 16071297.0, "other_securities_eoy": 15286984.0, "investment_programs_boy": 0.0, "investment_programs_eoy": 0.0, "intangible_assets_boy": 0.0, "intangible_assets_eoy": 0.0, "other_assets_boy": 0.0, "other_assets_eoy": 0.0, "assets_total_boy": 42655205.0, "assets_total_eoy": 45546348.0, "accounts_payable_boy": 932186.0, "accounts_payable_eoy": 989090.0, "grants_payable_boy": 0.0, "grants_payable_eoy": 0.0, "deferred_revenue_boy": 6698220.0, "deferred_revenue_eoy": 7564055.0, "tax_exempt_bonds_boy": 0.0, "tax_exempt_bonds_eoy": 0.0, "escrow_liability_boy": 0.0, "escrow_liability_eoy": 0.0, "payable_officiers_boy": 0.0, "payable_officiers_eoy": 0.0, "secured_notes_payable_boy": 0.0, "secured_notes_payable_eoy": 0.0, "unsecured_notes_payable_boy": 1268260.0, "unsecured_notes_payable_eoy": 551749.0, "liability_other_boy": 6142102.0, "liability_other_eoy": 5667899.0, "liability_total_boy": 15040768.0, "liability_total_eoy": 14772793.0, "unrestricted_boy": 18742786.0, "unrestricted_eoy": 17241046.0, "temporarily_restricted_boy": 7157651.0, "temporarily_restricted_eoy": 11818509.0, "permanently_restricted_boy": 1714000.0, "permanently_restricted_eoy": 1714000.0, "restricted_boy": 0.0, "restricted_eoy": 0.0, "capital_boy": null, "capital_eoy": null, "paid_in_boy": null, "paid_in_eoy": null, "retained_boy": null, "retained_eoy": null, "net_total_boy": 27614437.0, "net_total_eoy": 30773555.0, "balances_boy": 42655205.0, "balances_eoy": 45546348.0 } }, { "period_begin": "2017-01-01T05:00:00Z", "period_end": "2017-12-31T05:00:00Z", "membership_dues": 0.0, "revenue_contributions": 8611116.0, "revenue_govt_grants": 0.0, "revenue_program_services": 14470873.0, "revenue_investments": 1285246.0, "revenue_special_events": 0.0, "revenue_sales": 0.0, "revenue_other": 89916.0, "revenue_total": 24457151.0, "affiliate_net_payments": null, "expense_program_services": 18553043.0, "expense_administration": 5129145.0, "expense_fundraising": 1033700.0, "expenses_total": 24715888.0, "net_gain_loss": -258737.0, "expense_accounting": 107095.0, "expense_advertising_promotion": 216667.0, "expense_info_technology": 1185542.0, "expense_insurance": 131193.0, "expense_interest": 13727.0, "expense_investment_management": 178784.0, "expense_legal": 109226.0, "expense_pension_plan": 961113.0, "expense_publications": 216667.0, "expense_profesional_fundraising": null, "assets_total": 42655205.0, "unrestricted_net_assets": 18742786.0, "net_fixed_assets_LBE": null, "net_assets_end_of_year": 27614437.0, "other_expense": 0.0, "notes_payable_mortgages": 0.0, "liabilities_total": 15040768.0, "months_of_cash": "7.3", "part_8_revenue": { "federated_campaigns": 0.0, "membership_dues": 0.0, "fundraising_events": 0.0, "related_orgs": 0.0, "government_grants": 0.0, "contributions_other": 8611116.0, "contributions_noncash": 0.0, "contributions_all": 8611116.0, "service_revenue": 14470873.0, "income_investment": 385684.0, "income_bonds": 0.0, "royalties": 0.0, "rents_real": 132187.0, "rents_personal": null, "rent_expenses_real": 0.0, "rent_expenses_personal": null, "rent_income_real": 132187.0, "rent_income_personal": null, "net_rental": 132187.0, "gross_securities": 3126848.0, "gross_other": null, "cost_securities": 2359473.0, "cost_other": null, "gain_securities": 767375.0, "gain_other": null, "net_sales": 767375.0, "contributions": null, "gross_special": 0.0, "direct_expenses": null, "net_special": 0.0, "gaming_income": null, "gaming_expenses": null, "gaming_net": 0.0, "gross_sales": null, "cost_goods": null, "gross_profit": 0.0, "revenue_other": 89916.0, "revenue_total": 24457151.0, "service_description_a": "PRODUCT REVENUE", "service_code_a": 611710.0, "service_description_b": "FUNDING INFO. NETWORK", "service_amount_a": 11627587.0, "service_code_b": 611710.0, "service_amount_b": 800693.0, "service_description_c": "EDUCATIONAL PRGM REV.", "service_code_c": 611710.0, "service_amount_c": 491000.0, "service_description_d": "FOUNDATION BENCHMARKER", "service_code_d": 611710.0, "service_amount_d": 397200.0, "service_description_e": "FOUNDATION WEB BUILDER", "service_code_e": 611710.0, "service_amount_e": 81007.0, "service_description_f": null, "service_code_f": null, "service_amount_f": null }, "part_9_expenses": { "grants_orgs_us": null, "grants_individuals_us": null, "grants_orgs_non_us": null, "benefits_total": null, "compensation_current": 1267176.0, "compensation_disqualified": 0.0, "wages_total": 10185251.0, "pension_total": 961113.0, "employee_benefits_total": 1446948.0, "payroll_tax_total": 838159.0, "fees_management": 0.0, "fees_legal": 109226.0, "accounting_fees_total": 107095.0, "fees_lobbying": null, "fundraising_total": null, "fees_investments": 178784.0, "fees_other": 1066319.0, "ads_promo": 216667.0, "office": 619739.0, "information_technology": 1185542.0, "expense_royalties": 588.0, "occupancy_total": 2218153.0, "travel_total": 498295.0, "entertain_officials": null, "meetings_total": 93886.0, "interest_total": 13727.0, "payments": null, "depreciation_total": 2353765.0, "insurance": 131193.0, "expense_a_total": 800139.0, "expense_b_total": 114397.0, "expense_c_total": 90738.0, "expense_d_total": 55273.0, "expense_e_total": null, "expenses_total": 24715888.0, "total_program_services": 18553043.0, "total_management": 5129145.0, "total_fundraising": 1033700.0, "expense_joint_total": null, "joint_services": null, "joint_general": null, "joint_fundraising": null, "all_other_expenses": 163715.0, "expense_a_description": "OTHER FEES", "expense_b_description": "MISCELLANEOUS", "expense_c_description": "SALES TAX EXPENSE", "expense_d_description": "SEMINAR INSTRUCTION FEE" }, "part_10_balance_sheet": { "cash_boy": 159360.0, "cash_eoy": 155612.0, "savings_boy": 10795902.0, "savings_eoy": 13505683.0, "pledges_grants_boy": 2824836.0, "pledges_grants_eoy": 2302243.0, "accounts_receivable_boy": 783566.0, "accounts_receivable_eoy": 551722.0, "qualified_receivable_boy": 0.0, "qualified_receivable_eoy": 0.0, "disqualified_receivable_boy": 0.0, "disqualified_receivable_eoy": 0.0, "loans_receivable_boy": null, "loans_receivable_eoy": null, "inventory_boy": 63782.0, "inventory_eoy": 3026.0, "prepaid_boy": 520298.0, "prepaid_eoy": 348723.0, "lbe_base": 23062951.0, "less_depreciation": 13346052.0, "lbe_boy": 11515309.0, "lbe_eoy": 9716899.0, "public_securities_boy": 0.0, "public_securities_eoy": 0.0, "other_securities_boy": 14334873.0, "other_securities_eoy": 16071297.0, "investment_programs_boy": 0.0, "investment_programs_eoy": 0.0, "intangible_assets_boy": 0.0, "intangible_assets_eoy": 0.0, "other_assets_boy": 0.0, "other_assets_eoy": 0.0, "assets_total_boy": 40997926.0, "assets_total_eoy": 42655205.0, "accounts_payable_boy": 845233.0, "accounts_payable_eoy": 932186.0, "grants_payable_boy": 0.0, "grants_payable_eoy": 0.0, "deferred_revenue_boy": 5896680.0, "deferred_revenue_eoy": 6698220.0, "tax_exempt_bonds_boy": 0.0, "tax_exempt_bonds_eoy": 0.0, "escrow_liability_boy": 0.0, "escrow_liability_eoy": 0.0, "payable_officiers_boy": 0.0, "payable_officiers_eoy": 0.0, "secured_notes_payable_boy": 0.0, "secured_notes_payable_eoy": 0.0, "unsecured_notes_payable_boy": 1546377.0, "unsecured_notes_payable_eoy": 1268260.0, "liability_other_boy": 6277868.0, "liability_other_eoy": 6142102.0, "liability_total_boy": 14566158.0, "liability_total_eoy": 15040768.0, "unrestricted_boy": 18369348.0, "unrestricted_eoy": 18742786.0, "temporarily_restricted_boy": 6348420.0, "temporarily_restricted_eoy": 7157651.0, "permanently_restricted_boy": 1714000.0, "permanently_restricted_eoy": 1714000.0, "restricted_boy": 0.0, "restricted_eoy": 0.0, "capital_boy": null, "capital_eoy": null, "paid_in_boy": null, "paid_in_eoy": null, "retained_boy": null, "retained_eoy": null, "net_total_boy": 26431768.0, "net_total_eoy": 27614437.0, "balances_boy": 40997926.0, "balances_eoy": 42655205.0 } }, { "period_begin": "2016-01-01T05:00:00Z", "period_end": "2016-12-31T05:00:00Z", "membership_dues": 0.0, "revenue_contributions": 8687596.0, "revenue_govt_grants": 0.0, "revenue_program_services": 14309956.0, "revenue_investments": 1038198.0, "revenue_special_events": 0.0, "revenue_sales": 0.0, "revenue_other": 76030.0, "revenue_total": 24111780.0, "affiliate_net_payments": null, "expense_program_services": 19622829.0, "expense_administration": 6512350.0, "expense_fundraising": 1065424.0, "expenses_total": 27200603.0, "net_gain_loss": -3088823.0, "expense_accounting": 135750.0, "expense_advertising_promotion": 72643.0, "expense_info_technology": 1349550.0, "expense_insurance": 136759.0, "expense_interest": 35750.0, "expense_investment_management": 184496.0, "expense_legal": 143562.0, "expense_pension_plan": 915603.0, "expense_publications": 72643.0, "expense_profesional_fundraising": null, "assets_total": 40997926.0, "unrestricted_net_assets": 18369348.0, "net_fixed_assets_LBE": null, "net_assets_end_of_year": 26431768.0, "other_expense": 0.0, "notes_payable_mortgages": 0.0, "liabilities_total": 14566158.0, "months_of_cash": "5.3", "part_8_revenue": { "federated_campaigns": 0.0, "membership_dues": 0.0, "fundraising_events": 0.0, "related_orgs": 0.0, "government_grants": 0.0, "contributions_other": 8687596.0, "contributions_noncash": 0.0, "contributions_all": 8687596.0, "service_revenue": 14309956.0, "income_investment": 384989.0, "income_bonds": 0.0, "royalties": 0.0, "rents_real": null, "rents_personal": null, "rent_expenses_real": null, "rent_expenses_personal": null, "rent_income_real": null, "rent_income_personal": null, "net_rental": 0.0, "gross_securities": 1814187.0, "gross_other": null, "cost_securities": 1160978.0, "cost_other": null, "gain_securities": 653209.0, "gain_other": null, "net_sales": 653209.0, "contributions": null, "gross_special": 0.0, "direct_expenses": null, "net_special": 0.0, "gaming_income": null, "gaming_expenses": null, "gaming_net": 0.0, "gross_sales": null, "cost_goods": null, "gross_profit": 0.0, "revenue_other": 76030.0, "revenue_total": 24111780.0, "service_description_a": "PRODUCT REVENUE", "service_code_a": 611710.0, "service_description_b": "FUNDING INFO. NETWORK", "service_amount_a": 11193704.0, "service_code_b": 611710.0, "service_amount_b": 584891.0, "service_description_c": "EDUCATIONAL PRGM REV.", "service_code_c": 611710.0, "service_amount_c": 477279.0, "service_description_d": "DATABASE SEARCH REV.", "service_code_d": 611710.0, "service_amount_d": 101522.0, "service_description_e": "ASSOCIATES PGRM MEMBER", "service_code_e": 611710.0, "service_amount_e": 29678.0, "service_description_f": null, "service_code_f": null, "service_amount_f": null }, "part_9_expenses": { "grants_orgs_us": null, "grants_individuals_us": null, "grants_orgs_non_us": null, "benefits_total": null, "compensation_current": 1797520.0, "compensation_disqualified": 0.0, "wages_total": 11501211.0, "pension_total": 915603.0, "employee_benefits_total": 1494035.0, "payroll_tax_total": 936310.0, "fees_management": 0.0, "fees_legal": 143562.0, "accounting_fees_total": 135750.0, "fees_lobbying": null, "fundraising_total": null, "fees_investments": 184496.0, "fees_other": 1205473.0, "ads_promo": 72643.0, "office": 728452.0, "information_technology": 1349550.0, "expense_royalties": 2102.0, "occupancy_total": 2134523.0, "travel_total": 553070.0, "entertain_officials": null, "meetings_total": 89725.0, "interest_total": 35750.0, "payments": null, "depreciation_total": 2385507.0, "insurance": 136759.0, "expense_a_total": 125580.0, "expense_b_total": 44387.0, "expense_c_total": 37408.0, "expense_d_total": 15764.0, "expense_e_total": null, "expenses_total": 27200603.0, "total_program_services": 19622829.0, "total_management": 6512350.0, "total_fundraising": 1065424.0, "expense_joint_total": null, "joint_services": null, "joint_general": null, "joint_fundraising": null, "all_other_expenses": 1175423.0, "expense_a_description": "PRINTING & DUPLICATING", "expense_b_description": "LIBRARY ACQUISITION", "expense_c_description": "SEMINAR INSTRUCTION FEE", "expense_d_description": "PUBLICATION DIST." }, "part_10_balance_sheet": { "cash_boy": 148070.0, "cash_eoy": 159360.0, "savings_boy": 11790891.0, "savings_eoy": 10795902.0, "pledges_grants_boy": 3441807.0, "pledges_grants_eoy": 2824836.0, "accounts_receivable_boy": 930328.0, "accounts_receivable_eoy": 783566.0, "qualified_receivable_boy": 0.0, "qualified_receivable_eoy": 0.0, "disqualified_receivable_boy": 0.0, "disqualified_receivable_eoy": 0.0, "loans_receivable_boy": null, "loans_receivable_eoy": null, "inventory_boy": 66864.0, "inventory_eoy": 63782.0, "prepaid_boy": 456453.0, "prepaid_eoy": 520298.0, "lbe_base": 22555320.0, "less_depreciation": 11040011.0, "lbe_boy": 13168590.0, "lbe_eoy": 11515309.0, "public_securities_boy": 0.0, "public_securities_eoy": 0.0, "other_securities_boy": 15157087.0, "other_securities_eoy": 14334873.0, "investment_programs_boy": 0.0, "investment_programs_eoy": 0.0, "intangible_assets_boy": 0.0, "intangible_assets_eoy": 0.0, "other_assets_boy": 0.0, "other_assets_eoy": 0.0, "assets_total_boy": 45160090.0, "assets_total_eoy": 40997926.0, "accounts_payable_boy": 1266006.0, "accounts_payable_eoy": 845233.0, "grants_payable_boy": 0.0, "grants_payable_eoy": 0.0, "deferred_revenue_boy": 5519089.0, "deferred_revenue_eoy": 5896680.0, "tax_exempt_bonds_boy": 0.0, "tax_exempt_bonds_eoy": 0.0, "escrow_liability_boy": 0.0, "escrow_liability_eoy": 0.0, "payable_officiers_boy": 0.0, "payable_officiers_eoy": 0.0, "secured_notes_payable_boy": 0.0, "secured_notes_payable_eoy": 0.0, "unsecured_notes_payable_boy": 2500000.0, "unsecured_notes_payable_eoy": 1546377.0, "liability_other_boy": 6657119.0, "liability_other_eoy": 6277868.0, "liability_total_boy": 15942214.0, "liability_total_eoy": 14566158.0, "unrestricted_boy": 20113577.0, "unrestricted_eoy": 18369348.0, "temporarily_restricted_boy": 7390299.0, "temporarily_restricted_eoy": 6348420.0, "permanently_restricted_boy": 1714000.0, "permanently_restricted_eoy": 1714000.0, "restricted_boy": 0.0, "restricted_eoy": 0.0, "capital_boy": null, "capital_eoy": null, "paid_in_boy": null, "paid_in_eoy": null, "retained_boy": null, "retained_eoy": null, "net_total_boy": 29217876.0, "net_total_eoy": 26431768.0, "balances_boy": 45160090.0, "balances_eoy": 40997926.0 } }, { "period_begin": "2015-01-01T05:00:00Z", "period_end": "2015-12-31T05:00:00Z", "membership_dues": 0.0, "revenue_contributions": 10017916.0, "revenue_govt_grants": 0.0, "revenue_program_services": 14551976.0, "revenue_investments": 762322.0, "revenue_special_events": 0.0, "revenue_sales": 0.0, "revenue_other": 60960.0, "revenue_total": 25393174.0, "affiliate_net_payments": 0.0, "expense_program_services": 20234651.0, "expense_administration": 6325047.0, "expense_fundraising": 919311.0, "expenses_total": 27479009.0, "net_gain_loss": -2085835.0, "expense_accounting": 137165.0, "expense_advertising_promotion": 18781.0, "expense_info_technology": 1453056.0, "expense_insurance": 161703.0, "expense_interest": 0.0, "expense_investment_management": 268408.0, "expense_legal": 98883.0, "expense_pension_plan": 1072490.0, "expense_publications": 18781.0, "expense_profesional_fundraising": 0.0, "assets_total": 45160090.0, "unrestricted_net_assets": 20113577.0, "net_fixed_assets_LBE": null, "net_assets_end_of_year": 29217876.0, "other_expense": 0.0, "notes_payable_mortgages": 0.0, "liabilities_total": 15942214.0, "months_of_cash": "5.5", "part_8_revenue": { "federated_campaigns": 0.0, "membership_dues": 0.0, "fundraising_events": 0.0, "related_orgs": 0.0, "government_grants": 0.0, "contributions_other": 10017916.0, "contributions_noncash": 200000.0, "contributions_all": 10017916.0, "service_revenue": 14551976.0, "income_investment": 503062.0, "income_bonds": 0.0, "royalties": 0.0, "rents_real": null, "rents_personal": null, "rent_expenses_real": null, "rent_expenses_personal": null, "rent_income_real": 0.0, "rent_income_personal": 0.0, "net_rental": 0.0, "gross_securities": 536509.0, "gross_other": null, "cost_securities": 277249.0, "cost_other": null, "gain_securities": 259260.0, "gain_other": null, "net_sales": 259260.0, "contributions": null, "gross_special": 0.0, "direct_expenses": null, "net_special": 0.0, "gaming_income": null, "gaming_expenses": null, "gaming_net": 0.0, "gross_sales": null, "cost_goods": null, "gross_profit": 0.0, "revenue_other": 60960.0, "revenue_total": 25393174.0, "service_description_a": "PRODUCT REVENUE", "service_code_a": 611710.0, "service_description_b": "EDUCATIONAL PROGRAM REVENUE", "service_amount_a": 11486940.0, "service_code_b": 611710.0, "service_amount_b": 767336.0, "service_description_c": "ASSOCIATES PROGRAM MEMBERSHIP FEES", "service_code_c": 611710.0, "service_amount_c": 73473.0, "service_description_d": "DATABASE SEARCH REVENUE", "service_code_d": 611710.0, "service_amount_d": 118611.0, "service_description_e": "FUNDING INFO NETWORK MEMBERSHIP FEES", "service_code_e": 611710.0, "service_amount_e": 529487.0, "service_description_f": null, "service_code_f": null, "service_amount_f": 1576129.0 }, "part_9_expenses": { "grants_orgs_us": 0.0, "grants_individuals_us": 0.0, "grants_orgs_non_us": 0.0, "benefits_total": 0.0, "compensation_current": 1270680.0, "compensation_disqualified": 0.0, "wages_total": 11091404.0, "pension_total": 1072490.0, "employee_benefits_total": 1546475.0, "payroll_tax_total": 965951.0, "fees_management": 0.0, "fees_legal": 98883.0, "accounting_fees_total": 137165.0, "fees_lobbying": 0.0, "fundraising_total": 0.0, "fees_investments": 268408.0, "fees_other": 1585804.0, "ads_promo": 18781.0, "office": 716413.0, "information_technology": 1453056.0, "expense_royalties": 4302.0, "occupancy_total": 3631394.0, "travel_total": 555988.0, "entertain_officials": 0.0, "meetings_total": 213619.0, "interest_total": 0.0, "payments": 0.0, "depreciation_total": 1382596.0, "insurance": 161703.0, "expense_a_total": 209594.0, "expense_b_total": 102345.0, "expense_c_total": 52292.0, "expense_d_total": 20883.0, "expense_e_total": null, "expenses_total": 27479009.0, "total_program_services": 20234651.0, "total_management": 6325047.0, "total_fundraising": 919311.0, "expense_joint_total": null, "joint_services": null, "joint_general": null, "joint_fundraising": null, "all_other_expenses": 918783.0, "expense_a_description": "PRINTING AND DUPLICATING", "expense_b_description": "SEMINAR INSTRUCTION", "expense_c_description": "LIBRARY ACQUISITION", "expense_d_description": "PUBLICATION DISTRIBUTION" }, "part_10_balance_sheet": { "cash_boy": 147217.0, "cash_eoy": 148070.0, "savings_boy": 13032172.0, "savings_eoy": 11790891.0, "pledges_grants_boy": 7377015.0, "pledges_grants_eoy": 3441807.0, "accounts_receivable_boy": 557403.0, "accounts_receivable_eoy": 930328.0, "qualified_receivable_boy": 0.0, "qualified_receivable_eoy": 0.0, "disqualified_receivable_boy": 0.0, "disqualified_receivable_eoy": 0.0, "loans_receivable_boy": 0.0, "loans_receivable_eoy": 0.0, "inventory_boy": 87679.0, "inventory_eoy": 66864.0, "prepaid_boy": 556571.0, "prepaid_eoy": 456453.0, "lbe_base": 21854447.0, "less_depreciation": 8685857.0, "lbe_boy": 3530916.0, "lbe_eoy": 13168590.0, "public_securities_boy": 0.0, "public_securities_eoy": 0.0, "other_securities_boy": 15836545.0, "other_securities_eoy": 15157087.0, "investment_programs_boy": 0.0, "investment_programs_eoy": 0.0, "intangible_assets_boy": 0.0, "intangible_assets_eoy": 0.0, "other_assets_boy": 0.0, "other_assets_eoy": 0.0, "assets_total_boy": 41125518.0, "assets_total_eoy": 45160090.0, "accounts_payable_boy": 1403755.0, "accounts_payable_eoy": 1266006.0, "grants_payable_boy": 0.0, "grants_payable_eoy": 0.0, "deferred_revenue_boy": 5430117.0, "deferred_revenue_eoy": 5519089.0, "tax_exempt_bonds_boy": 0.0, "tax_exempt_bonds_eoy": 0.0, "escrow_liability_boy": 0.0, "escrow_liability_eoy": 0.0, "payable_officiers_boy": 0.0, "payable_officiers_eoy": 0.0, "secured_notes_payable_boy": 0.0, "secured_notes_payable_eoy": 0.0, "unsecured_notes_payable_boy": 0.0, "unsecured_notes_payable_eoy": 2500000.0, "liability_other_boy": 2132234.0, "liability_other_eoy": 6657119.0, "liability_total_boy": 8966106.0, "liability_total_eoy": 15942214.0, "unrestricted_boy": 17094780.0, "unrestricted_eoy": 20113577.0, "temporarily_restricted_boy": 13350632.0, "temporarily_restricted_eoy": 7390299.0, "permanently_restricted_boy": 1714000.0, "permanently_restricted_eoy": 1714000.0, "restricted_boy": 0.0, "restricted_eoy": 0.0, "capital_boy": null, "capital_eoy": null, "paid_in_boy": null, "paid_in_eoy": null, "retained_boy": null, "retained_eoy": null, "net_total_boy": 32159412.0, "net_total_eoy": 29217876.0, "balances_boy": 41125518.0, "balances_eoy": 45160090.0 } }, { "period_begin": "2014-01-01T05:00:00Z", "period_end": "2014-12-31T05:00:00Z", "membership_dues": 0.0, "revenue_contributions": 9061221.0, "revenue_govt_grants": 0.0, "revenue_program_services": 13669697.0, "revenue_investments": 723466.0, "revenue_special_events": 0.0, "revenue_sales": 0.0, "revenue_other": 74950.0, "revenue_total": 23529334.0, "affiliate_net_payments": 0.0, "expense_program_services": 19568101.0, "expense_administration": 4711774.0, "expense_fundraising": 858077.0, "expenses_total": 25137952.0, "net_gain_loss": -1608618.0, "expense_accounting": 121530.0, "expense_advertising_promotion": 72178.0, "expense_info_technology": 1130938.0, "expense_insurance": 142591.0, "expense_interest": 0.0, "expense_investment_management": 264528.0, "expense_legal": 77904.0, "expense_pension_plan": 1024318.0, "expense_publications": 72178.0, "expense_profesional_fundraising": 0.0, "assets_total": 41125518.0, "unrestricted_net_assets": 17094780.0, "net_fixed_assets_LBE": null, "net_assets_end_of_year": 32159412.0, "other_expense": 0.0, "notes_payable_mortgages": 0.0, "liabilities_total": 8966106.0, "months_of_cash": "6.5", "part_8_revenue": { "federated_campaigns": 0.0, "membership_dues": 0.0, "fundraising_events": 0.0, "related_orgs": 0.0, "government_grants": 0.0, "contributions_other": 9061221.0, "contributions_noncash": 0.0, "contributions_all": 9061221.0, "service_revenue": 13669697.0, "income_investment": 490597.0, "income_bonds": 0.0, "royalties": 0.0, "rents_real": null, "rents_personal": null, "rent_expenses_real": null, "rent_expenses_personal": null, "rent_income_real": 0.0, "rent_income_personal": 0.0, "net_rental": 0.0, "gross_securities": 529329.0, "gross_other": null, "cost_securities": 296460.0, "cost_other": null, "gain_securities": 232869.0, "gain_other": null, "net_sales": 232869.0, "contributions": null, "gross_special": 0.0, "direct_expenses": null, "net_special": 0.0, "gaming_income": null, "gaming_expenses": null, "gaming_net": 0.0, "gross_sales": null, "cost_goods": null, "gross_profit": 0.0, "revenue_other": 74950.0, "revenue_total": 23529334.0, "service_description_a": "PRODUCT REVENUE", "service_code_a": 611710.0, "service_description_b": "EDUCATIONAL PROGRAM REVENUE", "service_amount_a": 11338221.0, "service_code_b": 611710.0, "service_amount_b": 705861.0, "service_description_c": "ASSOCIATES PROGRAM MEMBERSHIP FEES", "service_code_c": 611710.0, "service_amount_c": 70127.0, "service_description_d": "DATABASE SEARCH REVENUE", "service_code_d": 611710.0, "service_amount_d": 136457.0, "service_description_e": "FUNDING INFO NETWORK MEMBERSHIP FEES", "service_code_e": 611710.0, "service_amount_e": 484511.0, "service_description_f": "All other program service revenue", "service_code_f": null, "service_amount_f": 934520.0 }, "part_9_expenses": { "grants_orgs_us": 0.0, "grants_individuals_us": 0.0, "grants_orgs_non_us": 0.0, "benefits_total": 0.0, "compensation_current": 1077068.0, "compensation_disqualified": 0.0, "wages_total": 10770099.0, "pension_total": 1024318.0, "employee_benefits_total": 1323468.0, "payroll_tax_total": 928814.0, "fees_management": 0.0, "fees_legal": 77904.0, "accounting_fees_total": 121530.0, "fees_lobbying": 0.0, "fundraising_total": 0.0, "fees_investments": 264528.0, "fees_other": 2038361.0, "ads_promo": 72178.0, "office": 699387.0, "information_technology": 1130938.0, "expense_royalties": 2491.0, "occupancy_total": 2717388.0, "travel_total": 683592.0, "entertain_officials": 0.0, "meetings_total": 171129.0, "interest_total": 0.0, "payments": 0.0, "depreciation_total": 750781.0, "insurance": 142591.0, "expense_a_total": 289048.0, "expense_b_total": 131231.0, "expense_c_total": 64658.0, "expense_d_total": 22248.0, "expense_e_total": null, "expenses_total": 25137952.0, "total_program_services": 19568101.0, "total_management": 4711774.0, "total_fundraising": 858077.0, "expense_joint_total": null, "joint_services": null, "joint_general": null, "joint_fundraising": null, "all_other_expenses": 634202.0, "expense_a_description": "PRINTING AND DUPLICATING", "expense_b_description": "SEMINAR INSTRUCTION", "expense_c_description": "LIBRARY ACQUISITION", "expense_d_description": "PUBLICATION DISTRIBUTION" }, "part_10_balance_sheet": { "cash_boy": 126397.0, "cash_eoy": 147217.0, "savings_boy": 12309556.0, "savings_eoy": 13032172.0, "pledges_grants_boy": 12148677.0, "pledges_grants_eoy": 7377015.0, "accounts_receivable_boy": 739681.0, "accounts_receivable_eoy": 557403.0, "qualified_receivable_boy": 0.0, "qualified_receivable_eoy": 0.0, "disqualified_receivable_boy": 0.0, "disqualified_receivable_eoy": 0.0, "loans_receivable_boy": 0.0, "loans_receivable_eoy": 0.0, "inventory_boy": 89289.0, "inventory_eoy": 87679.0, "prepaid_boy": 315978.0, "prepaid_eoy": 556571.0, "lbe_base": 14823707.0, "less_depreciation": 11292791.0, "lbe_boy": 1214452.0, "lbe_eoy": 3530916.0, "public_securities_boy": 0.0, "public_securities_eoy": 0.0, "other_securities_boy": 14513831.0, "other_securities_eoy": 15836545.0, "investment_programs_boy": 0.0, "investment_programs_eoy": 0.0, "intangible_assets_boy": 0.0, "intangible_assets_eoy": 0.0, "other_assets_boy": 0.0, "other_assets_eoy": 0.0, "assets_total_boy": 41457861.0, "assets_total_eoy": 41125518.0, "accounts_payable_boy": 1437025.0, "accounts_payable_eoy": 1403755.0, "grants_payable_boy": 0.0, "grants_payable_eoy": 0.0, "deferred_revenue_boy": 4955572.0, "deferred_revenue_eoy": 5430117.0, "tax_exempt_bonds_boy": 0.0, "tax_exempt_bonds_eoy": 0.0, "escrow_liability_boy": 0.0, "escrow_liability_eoy": 0.0, "payable_officiers_boy": 0.0, "payable_officiers_eoy": 0.0, "secured_notes_payable_boy": 0.0, "secured_notes_payable_eoy": 0.0, "unsecured_notes_payable_boy": 0.0, "unsecured_notes_payable_eoy": 0.0, "liability_other_boy": 1665816.0, "liability_other_eoy": 2132234.0, "liability_total_boy": 8058413.0, "liability_total_eoy": 8966106.0, "unrestricted_boy": 14463153.0, "unrestricted_eoy": 17094780.0, "temporarily_restricted_boy": 17222295.0, "temporarily_restricted_eoy": 13350632.0, "permanently_restricted_boy": 1714000.0, "permanently_restricted_eoy": 1714000.0, "restricted_boy": 0.0, "restricted_eoy": 0.0, "capital_boy": null, "capital_eoy": null, "paid_in_boy": null, "paid_in_eoy": null, "retained_boy": null, "retained_eoy": null, "net_total_boy": 33399448.0, "net_total_eoy": 32159412.0, "balances_boy": 41457861.0, "balances_eoy": 41125518.0 } } ], "pf990_financials": null, "f990ez_financials": null, "financial_trends_analysis": [ { "fiscal_year": "2018", "business_model_indicators": { "profitability": { "Unrestricted_surplus_(deficit)_before_depreciation": 627973, "surplus_as_percent_of_expenses_before_depreciation": "2.7%", "Unrestricted_surplus_(deficit)_after_depreciation": -1501740, "surplus_as_percent_of_expenses_after_depreciation": "-5.8%" }, "revenue_composition": { "total_revenue_unrestricted_and_restricted": 29706800, "total_revenue_percent_change_over_prior_year": "21.5%", "total_revenue_prior": 24457151.0, "program_svcs_revenue": "52.2%", "membership_dues": "0.0%", "investment_income": "0.9%", "government_grants": "0.0%", "other_grants_contributions": "46.6%", "other_revenue": "0.3%" }, "expense_composition": { "total_expenses_before_depreciation": 23652208, "total_expenses_percent_change_over_prior_year": "5.8%", "personnel": "71.5%", "professional_fees": "6.2%", "occupancy": "8.7%", "interest_expense": "0.2%", "pass_through": "0.0%", "all_other_expenses": "13.4%" }, "full_cost_components": { "total_expenses_after_depreciation": 25781921, "one_month_of_savings": 1971017, "debt_principal_payment": 716511, "fixed_asset_additions": 0, "total_full_costs_estimated": 28469449 } }, "capital_structure_indicators": { "liquidity": { "months_of_cash": 8.6, "months_of_cash_and_investments": 16.4, "months_of_estimated_liquid_unrestricted_net_assets": 4.9 }, "balance_sheet_composition": { "cash": 17029202, "investments": 15286984, "receivables": 5000060, "gross_land_buildings_and_equipment_lbe": 23062951, "accumulated_depreciation_as_percent_of_lbe": "67.1%", "liabilities_as_percent_of_net_assets": "32.4%", "unrestricted_net_assets": 17241046, "temporarily_restricted_net_assets": 11818509, "permanently_restricted_net_assets": 1714000, "restricted_net_assets": 13532509, "total_net_assets": 30773555 } }, "key_data_checks": { "data_check_errors": false } }, { "fiscal_year": "2017", "business_model_indicators": { "profitability": { "Unrestricted_surplus_(deficit)_before_depreciation": 2727203, "surplus_as_percent_of_expenses_before_depreciation": "12.2%", "Unrestricted_surplus_(deficit)_after_depreciation": 373438, "surplus_as_percent_of_expenses_after_depreciation": "1.5%" }, "revenue_composition": { "total_revenue_unrestricted_and_restricted": 24457151, "total_revenue_percent_change_over_prior_year": "1.4%", "total_revenue_prior": 24111780.0, "program_svcs_revenue": "59.2%", "membership_dues": "0.0%", "investment_income": "1.6%", "government_grants": "0.0%", "other_grants_contributions": "35.2%", "other_revenue": "4.0%" }, "expense_composition": { "total_expenses_before_depreciation": 22362123, "total_expenses_percent_change_over_prior_year": "-9.9%", "personnel": "65.7%", "professional_fees": "6.5%", "occupancy": "9.9%", "interest_expense": "0.1%", "pass_through": "0.0%", "all_other_expenses": "17.8%" }, "full_cost_components": { "total_expenses_after_depreciation": 24715888, "one_month_of_savings": 1863510, "debt_principal_payment": 278117, "fixed_asset_additions": 0, "total_full_costs_estimated": 26857515 } }, "capital_structure_indicators": { "liquidity": { "months_of_cash": 7.3, "months_of_cash_and_investments": 16.0, "months_of_estimated_liquid_unrestricted_net_assets": 4.8 }, "balance_sheet_composition": { "cash": 13661295, "investments": 16071297, "receivables": 2853965, "gross_land_buildings_and_equipment_lbe": 23062951, "accumulated_depreciation_as_percent_of_lbe": "57.9%", "liabilities_as_percent_of_net_assets": "35.3%", "unrestricted_net_assets": 18742786, "temporarily_restricted_net_assets": 7157651, "permanently_restricted_net_assets": 1714000, "restricted_net_assets": 8871651, "total_net_assets": 27614437 } }, "key_data_checks": { "data_check_errors": false } }, { "fiscal_year": "2016", "business_model_indicators": { "profitability": { "Unrestricted_surplus_(deficit)_before_depreciation": 641278, "surplus_as_percent_of_expenses_before_depreciation": "2.6%", "Unrestricted_surplus_(deficit)_after_depreciation": -1744229, "surplus_as_percent_of_expenses_after_depreciation": "-6.4%" }, "revenue_composition": { "total_revenue_unrestricted_and_restricted": 24111780, "total_revenue_percent_change_over_prior_year": "-5.0%", "total_revenue_prior": 25393174.0, "program_svcs_revenue": "59.3%", "membership_dues": "0.0%", "investment_income": "1.6%", "government_grants": "0.0%", "other_grants_contributions": "36.0%", "other_revenue": "3.0%" }, "expense_composition": { "total_expenses_before_depreciation": 24815096, "total_expenses_percent_change_over_prior_year": "-4.9%", "personnel": "67.1%", "professional_fees": "6.7%", "occupancy": "8.6%", "interest_expense": "0.1%", "pass_through": "0.0%", "all_other_expenses": "17.5%" }, "full_cost_components": { "total_expenses_after_depreciation": 27200603, "one_month_of_savings": 2067924, "debt_principal_payment": 953623, "fixed_asset_additions": 0, "total_full_costs_estimated": 30222150 } }, "capital_structure_indicators": { "liquidity": { "months_of_cash": 5.3, "months_of_cash_and_investments": 12.2, "months_of_estimated_liquid_unrestricted_net_assets": 3.3 }, "balance_sheet_composition": { "cash": 10955262, "investments": 14334873, "receivables": 3608402, "gross_land_buildings_and_equipment_lbe": 22555320, "accumulated_depreciation_as_percent_of_lbe": "48.9%", "liabilities_as_percent_of_net_assets": "35.5%", "unrestricted_net_assets": 18369348, "temporarily_restricted_net_assets": 6348420, "permanently_restricted_net_assets": 1714000, "restricted_net_assets": 8062420, "total_net_assets": 26431768 } }, "key_data_checks": { "data_check_errors": false } }, { "fiscal_year": "2015", "business_model_indicators": { "profitability": { "Unrestricted_surplus_(deficit)_before_depreciation": 4401393, "surplus_as_percent_of_expenses_before_depreciation": "16.9%", "Unrestricted_surplus_(deficit)_after_depreciation": 3018797, "surplus_as_percent_of_expenses_after_depreciation": "11.0%" }, "revenue_composition": { "total_revenue_unrestricted_and_restricted": 25393174, "total_revenue_percent_change_over_prior_year": "7.9%", "total_revenue_prior": 23529334.0, "program_svcs_revenue": "57.3%", "membership_dues": "0.0%", "investment_income": "2.0%", "government_grants": "0.0%", "other_grants_contributions": "39.5%", "other_revenue": "1.3%" }, "expense_composition": { "total_expenses_before_depreciation": 26096413, "total_expenses_percent_change_over_prior_year": "7.0%", "personnel": "61.1%", "professional_fees": "8.0%", "occupancy": "13.9%", "interest_expense": "0.0%", "pass_through": "0.0%", "all_other_expenses": "17.0%" }, "full_cost_components": { "total_expenses_after_depreciation": 27479009, "one_month_of_savings": 2174701, "debt_principal_payment": 0, "fixed_asset_additions": 11020270, "total_full_costs_estimated": 40673980 } }, "capital_structure_indicators": { "liquidity": { "months_of_cash": 5.5, "months_of_cash_and_investments": 12.5, "months_of_estimated_liquid_unrestricted_net_assets": 3.2 }, "balance_sheet_composition": { "cash": 11938961, "investments": 15157087, "receivables": 4372135, "gross_land_buildings_and_equipment_lbe": 21854447, "accumulated_depreciation_as_percent_of_lbe": "39.7%", "liabilities_as_percent_of_net_assets": "35.3%", "unrestricted_net_assets": 20113577, "temporarily_restricted_net_assets": 7390299, "permanently_restricted_net_assets": 1714000, "restricted_net_assets": 9104299, "total_net_assets": 29217876 } }, "key_data_checks": { "data_check_errors": false } }, { "fiscal_year": "2014", "business_model_indicators": { "profitability": { "Unrestricted_surplus_(deficit)_before_depreciation": 3382408, "surplus_as_percent_of_expenses_before_depreciation": "13.9%", "Unrestricted_surplus_(deficit)_after_depreciation": 2631627, "surplus_as_percent_of_expenses_after_depreciation": "10.5%" }, "revenue_composition": { "total_revenue_unrestricted_and_restricted": 23529334, "total_revenue_percent_change_over_prior_year": "0.0%", "total_revenue_prior": 0.0, "program_svcs_revenue": "58.1%", "membership_dues": "0.0%", "investment_income": "2.1%", "government_grants": "0.0%", "other_grants_contributions": "38.5%", "other_revenue": "1.3%" }, "expense_composition": { "total_expenses_before_depreciation": 24387171, "total_expenses_percent_change_over_prior_year": "0.0%", "personnel": "62.0%", "professional_fees": "10.3%", "occupancy": "11.1%", "interest_expense": "0.0%", "pass_through": "0.0%", "all_other_expenses": "16.6%" }, "full_cost_components": { "total_expenses_after_depreciation": 25137952, "one_month_of_savings": 2032264, "debt_principal_payment": 0, "fixed_asset_additions": 3067245, "total_full_costs_estimated": 30237461 } }, "capital_structure_indicators": { "liquidity": { "months_of_cash": 6.5, "months_of_cash_and_investments": 14.3, "months_of_estimated_liquid_unrestricted_net_assets": 6.7 }, "balance_sheet_composition": { "cash": 13179389, "investments": 15836545, "receivables": 7934418, "gross_land_buildings_and_equipment_lbe": 14823707, "accumulated_depreciation_as_percent_of_lbe": "76.2%", "liabilities_as_percent_of_net_assets": "21.8%", "unrestricted_net_assets": 17094780, "temporarily_restricted_net_assets": 13350632, "permanently_restricted_net_assets": 1714000, "restricted_net_assets": 15064632, "total_net_assets": 32159412 } }, "key_data_checks": { "data_check_errors": false } } ], "financial_documents": [ { "form990_name": "2019 Candid 990", "form990_year": "2019", "form990_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185358&approved=True", "form990_source": "(provided by organization)" }, { "form990_name": "2018 Foundation Center 990", "form990_year": "2018", "form990_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185359&approved=True", "form990_source": "(provided by organization)" }, { "form990_name": "2018 Form 990T", "form990_year": "2018", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2018/131/837/2018-131837418-11192e3f-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2018 Form 990", "form990_year": "2018", "form990_url": "https://pdf.guidestar.org/PDF_Images/2018/131/837/2018-131837418-1116ff41-9.pdf", "form990_source": "US IRS" }, { "form990_name": "6908122-Form990-2017-1547655735858.pdf", "form990_year": "2017", "form990_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185357&approved=True", "form990_source": "(provided by organization)" }, { "form990_name": "2017 Form 990T", "form990_year": "2017", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2017/131/837/2017-131837418-0f6643ce-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2017 Form 990", "form990_year": "2017", "form990_url": "https://pdf.guidestar.org/PDF_Images/2017/131/837/2017-131837418-0f891a54-9.pdf", "form990_source": "US IRS" }, { "form990_name": "Foundation Center 990", "form990_year": "2016", "form990_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185356&approved=True", "form990_source": "(provided by organization)" }, { "form990_name": "2016 Form 990T", "form990_year": "2016", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2016/131/837/2016-131837418-0dc25b10-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2016 Form 990", "form990_year": "2016", "form990_url": "https://pdf.guidestar.org/PDF_Images/2016/131/837/2016-131837418-0e09db17-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2015 Form 990T", "form990_year": "2015", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2015/131/837/2015-131837418-0d323c11-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2015 Form 990", "form990_year": "2015", "form990_url": "https://pdf.guidestar.org/PDF_Images/2015/131/837/2015-131837418-0d8befc7-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2014 Form 990T", "form990_year": "2014", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2014/131/837/2014-131837418-0b690c81-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2014 Form 990", "form990_year": "2014", "form990_url": "https://pdf.guidestar.org/PDF_Images/2014/131/837/2014-131837418-0bafe6c3-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2013 Form 990T", "form990_year": "2013", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2013/131/837/2013-131837418-0a563571-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2013 Form 990", "form990_year": "2013", "form990_url": "https://pdf.guidestar.org/PDF_Images/2013/131/837/2013-131837418-0aa74c3b-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2012 Form 990T", "form990_year": "2012", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2012/131/837/2012-131837418-09d4d063-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2012 Form 990", "form990_year": "2012", "form990_url": "https://pdf.guidestar.org/PDF_Images/2012/131/837/2012-131837418-09dafffc-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2011 Form 990T", "form990_year": "2011", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2011/131/837/2011-131837418-0841214f-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2011 Form 990", "form990_year": "2011", "form990_url": "https://pdf.guidestar.org/PDF_Images/2011/131/837/2011-131837418-088dbff4-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2010 Form 990T", "form990_year": "2010", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2010/131/837/2010-131837418-07321ce1-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2010 Form 990", "form990_year": "2010", "form990_url": "https://pdf.guidestar.org/PDF_Images/2010/131/837/2010-131837418-07888983-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2009 Form 990T", "form990_year": "2009", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2009/131/837/2009-131837418-05f13f3f-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2009 Form 990T", "form990_year": "2009", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2009/131/837/2009-131837418-07e4a287-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2009 Form 990T", "form990_year": "2009", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2009/131/837/2009-131837418-07e4a286-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2009 Form 990", "form990_year": "2009", "form990_url": "https://pdf.guidestar.org/PDF_Images/2009/131/837/2009-131837418-066a76d7-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2008 Form 990T", "form990_year": "2008", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2008/131/837/2008-131837418-050177f6-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2008 Form 990T", "form990_year": "2008", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2008/131/837/2008-131837418-07e4a27d-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2008 Form 990T", "form990_year": "2008", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2008/131/837/2008-131837418-07e4a27b-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2008 Form 990", "form990_year": "2008", "form990_url": "https://pdf.guidestar.org/PDF_Images/2008/131/837/2008-131837418-050c3410-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2007 Form 990T", "form990_year": "2007", "form990_url": "https://pdf.guidestar.org/PDF_Images/F990T/2007/131/837/2007-131837418-07c5633a-T.pdf", "form990_source": "US IRS" }, { "form990_name": "2007 Form 990", "form990_year": "2007", "form990_url": "https://pdf.guidestar.org/PDF_Images/2007/131/837/2007-131837418-04a9c2ed-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2006 Form 990", "form990_year": "2006", "form990_url": "https://pdf.guidestar.org/PDF_Images/2006/131/837/2006-131837418-03cdfa1a-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2005 Form 990", "form990_year": "2005", "form990_url": "https://pdf.guidestar.org/PDF_Images/2005/131/837/2005-131837418-02baa308-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2004 Form 990", "form990_year": "2004", "form990_url": "https://pdf.guidestar.org/PDF_Images/2004/131/837/2004-131837418-01f61537-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2003 Form 990", "form990_year": "2003", "form990_url": "https://pdf.guidestar.org/PDF_Images/2003/131/837/2003-131837418-1-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2002 Form 990", "form990_year": "2002", "form990_url": "https://pdf.guidestar.org/PDF_Images/2002/131/837/2002-131837418-1-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2001 Form 990", "form990_year": "2001", "form990_url": "https://pdf.guidestar.org/PDF_Images/2001/131/837/2001-131837418-1-9.pdf", "form990_source": "US IRS" }, { "form990_name": "2000 Form 990", "form990_year": "2000", "form990_url": "https://pdf.guidestar.org/PDF_Images/2000/131/837/2000-131837418-1-9.pdf", "form990_source": "US IRS" }, { "form990_name": "1999 Form 990", "form990_year": "1999", "form990_url": "https://pdf.guidestar.org/PDF_Images/1999/131/837/1999-131837418-1-9.pdf", "form990_source": "US IRS" }, { "form990_name": "1998 Form 990", "form990_year": "1998", "form990_url": "https://pdf.guidestar.org/PDF_Images/1998/131/837/1998-131837418-1-9.pdf", "form990_source": "US IRS" } ], "forms_990T": [ { "form990t_name": "", "form990t_url": "" } ], "funding_needs": null, "funding_sources": [ { "funding_source": "", "funding_amount": "" }, { "funding_source": "", "funding_amount": "" }, { "funding_source": "", "funding_amount": "" } ], "financial_statements": [ { "fiscal_year_begin": "", "fiscal_year_end": "2016", "auditing_company": "PKF O’CONNOR DAVIES, LLP", "doc_name": "", "document_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185345&approved=True" }, { "fiscal_year_begin": "", "fiscal_year_end": "2017", "auditing_company": "PKF O'CONNOR DAVIES, LLP", "doc_name": "2017 Final Audit Report.pdf", "document_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185346&approved=True" }, { "fiscal_year_begin": "", "fiscal_year_end": "2018", "auditing_company": "PKF O’CONNOR DAVIES, LLP", "doc_name": "2018 Final Audit Report", "document_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185347&approved=True" }, { "fiscal_year_begin": "", "fiscal_year_end": "2019", "auditing_company": "PKF O’CONNOR DAVIES, LLP", "doc_name": "2019 Final Audit Report", "document_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185348&approved=True" } ], "annual_reports": [ { "doc_name": "2020 Annual Report", "contents": "/ViewEdoc.aspx?edocId=7185355&approved=true", "year": "2020", "url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185355&approved=True" }, { "doc_name": "2019 Annual Report", "contents": "/ViewEdoc.aspx?edocId=7185354&approved=true", "year": "2019", "url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185354&approved=True" }, { "doc_name": "6908122-AnnualReport-2018-1548786093937.pdf", "contents": "/ViewEdoc.aspx?edocId=7185353&approved=true", "year": "2018", "url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185353&approved=True" }, { "doc_name": "6908122-AnnualReport-2017.pdf", "contents": "/ViewEdoc.aspx?edocId=7185352&approved=true", "year": "2017", "url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185352&approved=True" }, { "doc_name": "2016 Annual Report", "contents": "/ViewEdoc.aspx?edocId=7185351&approved=true", "year": "2016", "url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=7185351&approved=True" } ], "accounting_ratios": [ { "year": 2018, "months_of_cash": "8.64", "liquidity": "1.19", "fringe_rate": "0.27", "net_gain_loss": "3924879.00" }, { "year": 2017, "months_of_cash": "7.33", "liquidity": "0.94", "fringe_rate": "0.28", "net_gain_loss": "-258737.00" }, { "year": 2016, "months_of_cash": "5.30", "liquidity": "0.81", "fringe_rate": "0.25", "net_gain_loss": "-3088823.00" }, { "year": 2015, "months_of_cash": "5.49", "liquidity": "0.81", "fringe_rate": "0.29", "net_gain_loss": "-2085835.00" }, { "year": 2014, "months_of_cash": "6.49", "liquidity": "1.53", "fringe_rate": "0.28", "net_gain_loss": "-1608618.00" }, { "year": 2013, "months_of_cash": "6.08", "liquidity": "1.64", "fringe_rate": "0.27", "net_gain_loss": "5235752.00" }, { "year": 2012, "months_of_cash": "6.36", "liquidity": "2.73", "fringe_rate": "0.27", "net_gain_loss": "5911784.00" } ] }, "operations": { "leader_name": "Mr. <NAME>", "leader_profile": "<NAME> leads Candid as its President. Mr. Smith joined Candid (formerly Foundation Center) as President in October 2008.\n\nPreviously, he was president of the Oak Foundation in Geneva, Switzerland. Prior to that, he developed and led Ford Foundation's Peace and Social Justice Program. During his 10-year tenure as vice president, he distributed hundreds of millions of dollars to organizations working on human rights, international cooperation, governance, and civil society in the U.S. and around the world.\n\nMr. Smith has devoted his entire career to the philanthropic and nonprofit sectors. He serves on the board of directors of the Tinker Foundation and the advisory board of the United Nations Trust Fund for Human Security. He holds an M.A. in economics from the New School for Social Research in New York and a B.A. in anthropology and ethnomusicology from the University of Michigan.", "co_leader_name": " ", "co_leader_profile": "", "no_of_employees": 178, "no_of_volunteers": 15, "organization_email": null, "organization_details_year": 2018, "officers_directors_key_employees": [ { "name": "<NAME>", "title": "PRESIDENT", "type": [ "Officer", "Individual Trustee" ], "compensation": 629603.0, "related_compensation": 0.0, "other_compensation": 60914.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TREASURER/VP FINANCIAL STRATEGY", "type": [ "Officer" ], "compensation": 236569.0, "related_compensation": 0.0, "other_compensation": 16604.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "SEC. & VP-SOCIAL SECTOR OUTREACH", "type": [ "Officer" ], "compensation": 174264.0, "related_compensation": 0.0, "other_compensation": 20215.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "CHAIR", "type": [ "Officer", "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "VICE CHAIR", "type": [ "Officer", "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE (THRU 04/2018)", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE (THRU 08/2018)", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE (THRU 08/2018)", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "TRUSTEE (THRU 04/2018)", "type": [ "Individual Trustee" ], "compensation": 0.0, "related_compensation": 0.0, "other_compensation": 0.0, "hours": "", "benefits": null } ], "highest_paid_employees": [ { "name": "<NAME>", "title": "VP- DATA AND TECHNOLOGY", "type": [ "Highest Paid Employee" ], "compensation": 240038.0, "related_compensation": 0.0, "other_compensation": 44100.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "VP- KNOWLEDGE SERVICES", "type": [ "Highest Paid Employee" ], "compensation": 229375.0, "related_compensation": 0.0, "other_compensation": 66703.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "DIRECTOR OF SUBSCRIPTION PRODUCTS", "type": [ "Highest Paid Employee" ], "compensation": 212841.0, "related_compensation": 0.0, "other_compensation": 45853.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "VP- SENIOR ADVISOR", "type": [ "Highest Paid Employee" ], "compensation": 205628.0, "related_compensation": 0.0, "other_compensation": 27245.0, "hours": "", "benefits": null }, { "name": "<NAME>", "title": "DIRECTOR OF TECHNOLOGY INTEGRATION", "type": [ "Highest Paid Employee" ], "compensation": 195141.0, "related_compensation": 0.0, "other_compensation": 27430.0, "hours": "", "benefits": null } ], "employees_greater_than_100K": 8, "board_chair_name": "<NAME>", "board_chair_affiliation": "Walmart", "board_chair_term_start": null, "board_chair_term_end": null, "board_co_chair_name": " ", "board_co_chair_affiliation": "", "board_co_chair_term_start": null, "board_co_chair_term_end": null, "board_of_directors": [ { "name": "<NAME>", "title": null, "company": "HIP-Hispanics in Philanthropy" }, { "name": "<NAME>", "title": null, "company": "Rockefeller Philanthropy Advisors, Inc." }, { "name": "<NAME>", "title": null, "company": "J.D. Power" }, { "name": "<NAME>", "title": null, "company": "Charles Stewart Mott Foundation" }, { "name": "<NAME>", "title": null, "company": "The Burton D. Morgan Foundation" }, { "name": "<NAME>", "title": null, "company": "The Rockefeller Foundation" }, { "name": "<NAME>", "title": null, "company": "Massmart (Walmart Africa)" }, { "name": "<NAME>", "title": null, "company": "OGCI" }, { "name": "<NAME>", "title": null, "company": "New Media Insight" }, { "name": "<NAME>", "title": null, "company": "Center for High Impact Philanthropy, University of Pennsylvania" }, { "name": "<NAME>", "title": null, "company": "Bridges Fund Management" }, { "name": "<NAME>", "title": null, "company": "Candid (President)" }, { "name": "<NAME>", "title": null, "company": "Arab Foundations Forum" }, { "name": "<NAME>", "title": null, "company": "Asociación Española de Fundaciones (AEF; Spanish Association of Foundations)" }, { "name": "<NAME>", "title": null, "company": "BrightHive" }, { "name": "<NAME>", "title": null, "company": "The Duke Endowment" }, { "name": "<NAME>", "title": null, "company": "Bill & Melinda Gates Foundation" }, { "name": "<NAME>", "title": null, "company": "African Philanthropy Forum" }, { "name": "<NAME>", "title": null, "company": "Uniti Networks" }, { "name": "<NAME>", "title": null, "company": "MacArthur Foundation" }, { "name": "<NAME>", "title": null, "company": "Michigan Nonprofit Association" } ], "board_leadership_practices": [ { "question": "Does the board conduct a formal orientation for new board members and require all board members to sign a written agreement regarding their roles, responsibilities, and expectations? ", "answer": "Yes" }, { "question": "Has the board conducted a formal, written assessment of the chief executive within the past year?", "answer": "Yes" }, { "question": "Have the board and senior staff reviewed the conflict-of-interest policy and completed and signed disclosure statements within the past year?", "answer": "Yes" }, { "question": "Does the board ensure an inclusive board member recruitment process that results in diversity of thought and leadership?", "answer": "Yes" }, { "question": "Does the board conducted a formal, written self-assessment of its performance within the past three years?", "answer": "Yes" } ], "organization_demographics": null, "demographics": { "staff_level_totals": { "total_board_members": "20", "total_staff": "223", "total_senior_staff": "8" }, "equity_strategies": { "data_compensation": true, "data_disparities": null, "data_root_cause": null, "data_programming_goals": null, "data_feedback": true, "data_demographics": null, "data_strategic_plan": false, "policy_standards": null, "policy_promotion": null, "policy_evaluation": true, "policy_community": null, "policy_leadership": true, "policy_satisfaction": null, "policy_equity": null, "equity_strategy_last_modified": "07/16/2020" }, "categories": [ { "category": "Race & Ethnicity", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Asian American/Pacific Islanders/Asian", "board_members": 2, "staff": 20, "senior_staff": 2, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Black/African American/African", "board_members": 4, "staff": 20, "senior_staff": 1, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Hispanic/Latino/Latina/Latinx", "board_members": 1, "staff": 15, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Native American/American Indian/Indigenous", "board_members": 0, "staff": 1, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "White/Caucasian/European", "board_members": 11, "staff": 110, "senior_staff": 3, "reported_by_ceo": true, "reported_by_coceo": null }, { "subcategory": "Multi-Racial/Multi-Ethnic (2+ races/ethnicities)", "board_members": 2, "staff": 6, "senior_staff": 1, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Decline to state", "board_members": null, "staff": 5, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Unknown", "board_members": null, "staff": 42, "senior_staff": 1, "reported_by_ceo": false, "reported_by_coceo": null } ] }, { "category": "Race & Ethnicity Other", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Other", "board_members": null, "staff": null, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null }, { "subcategory": "Other", "board_members": null, "staff": null, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null }, { "subcategory": "Middle Eastern", "board_members": null, "staff": 2, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null }, { "subcategory": "Race: Black; Ethnicity: Latinx", "board_members": null, "staff": 1, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null }, { "subcategory": "South Asian", "board_members": null, "staff": 1, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null } ] }, { "category": "Gender Identity", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Female", "board_members": 9, "staff": 110, "senior_staff": 4, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Male", "board_members": 10, "staff": 65, "senior_staff": 4, "reported_by_ceo": true, "reported_by_coceo": null }, { "subcategory": "Non-binary", "board_members": null, "staff": 5, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Decline to state", "board_members": 1, "staff": 3, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Unknown", "board_members": null, "staff": 40, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null } ] }, { "category": "Gender Identity 2", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Transgender", "board_members": null, "staff": 2, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Not transgender (cisgender)", "board_members": 2, "staff": 153, "senior_staff": 1, "reported_by_ceo": true, "reported_by_coceo": null }, { "subcategory": "Decline to state", "board_members": null, "staff": 11, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Unknown", "board_members": 18, "staff": 57, "senior_staff": 7, "reported_by_ceo": false, "reported_by_coceo": null } ] }, { "category": "Sexual Orientation", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Gay, Lesbian, Bisexual, or other sexual orientations in the LGBTQIA+ community", "board_members": null, "staff": 30, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Heterosexual or Straight", "board_members": 20, "staff": 143, "senior_staff": 7, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Decline to state", "board_members": null, "staff": 7, "senior_staff": null, "reported_by_ceo": true, "reported_by_coceo": null }, { "subcategory": "Unknown", "board_members": null, "staff": 43, "senior_staff": 1, "reported_by_ceo": false, "reported_by_coceo": null } ] }, { "category": "Disability Status", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Person with a disability", "board_members": null, "staff": 14, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Person without a disability", "board_members": 20, "staff": 158, "senior_staff": 7, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Decline to state", "board_members": null, "staff": 3, "senior_staff": null, "reported_by_ceo": true, "reported_by_coceo": null }, { "subcategory": "Unknown", "board_members": null, "staff": 48, "senior_staff": 1, "reported_by_ceo": null, "reported_by_coceo": null } ] } ] }, "contractors": [ { "name": "<NAME>", "address": "1133 AVENUE OF THE AMERICAS NEW YORK NY 10036 USA", "compensation": "344045.0", "service_type": "LEGAL" }, { "name": "<NAME>", "address": "2300 CLARENDON BLVD SUITE 925 ARLINGTON VA 22201 USA", "compensation": "338572.0", "service_type": "IT CONSULTING" }, { "name": "<NAME>", "address": "180 VARICK STREET ROOM 822 NEW YORK NY 10014 USA", "compensation": "150000.0", "service_type": "BRAND CONSULTING" } ], "blog_url": "https://blog.candid.org/", "fundraising_contact_name": null, "fundraising_contact_title": "", "fundraising_contact_email": "", "fundraising_contact_phone": null, "preparer_firm_name": "PKF O'CONNOR DAVIES LLP", "preparer_firm_address": "500 MAMARONECK AVENUE HARRISON NY 105281633", "preparer_firm_ein": "27-1728945", "preparer_firm_phone": "914-381-8900", "senior_staff": [], "other_staff": [ { "name": "<NAME>", "title": "Executive Vice President", "type": "Senior Staff" }, { "name": "<NAME>", "title": "Vice President of Talent", "type": "Senior Staff" }, { "name": "<NAME>", "title": "Vice President of Products", "type": "Senior Staff" }, { "name": "<NAME>", "title": "Vice President of Planning", "type": "Senior Staff" }, { "name": "<NAME>", "title": "Vice President of Technology", "type": "Senior Staff" }, { "name": "<NAME>", "title": "Senior Advisor", "type": "Senior Staff" }, { "name": "<NAME>", "title": "Vice President of Networks", "type": "Senior Staff" } ], "accreditations": [ { "accreditation": "", "year": "" } ] }, "charitycheck": { "organization_id": "6908122", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "13-1837418", "organization_name": "Candid", "organization_name_aka": "The Foundation Center, Foundation Center, GuideStar, GuideStar USA", "address_line1": "32 Old Slip", "address_line2": "24th Floor", "city": "New York", "state": "NY", "state_name": "New York", "zip": "10005", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Candid", "pub78_ein": "13-1837418", "pub78_verified": "True", "pub78_city": "New York", "pub78_state": "NY", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/8/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "CANDID", "bmf_ein": "13-1837418", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "06", "ruling_year": "1957", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/5/2021 4:39:03 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] } } } ``` Gain quick insights into an organization's financial health with side-by-side financial data from the past five years available in an easy-to-read and intuitive PDF format. The financial data used to generate financial trends analysis is sourced from the IRS Form 990s. You can access the financial trends analysis data within the output of Premier API in the ``` financial_trends_analysis ``` array. Insert an EIN in the path parameter to retrieve a PDF of the nonprofit profile financial trends analysis. Premier Financial Trends Analysis PDF API only accepts GET requests. ``` https://api.candid.org/premier/v1/ftapdf/16-1541024 ``` ## Example Financial Trends Analysis PDF ## Financial Trends Analysis Glossary and Formulas Business model: The expression of how an organization makes and spends money in service of its mission. * Profitability: An indicator of an organization's business model performance by showing whether it realized a surplus or experienced a deficit in a given year. Surpluses are essential to nonprofit financial health. * Unrestricted surplus (deficit) after depreciation: A measure of profitability. In this report, this metric is calculated from the balance sheet due to the use of IRS Form 990 data. It is important for organizations to aim for surpluses that exceed their expenses including depreciation. Depreciation is a non-cash expense, which, for property owners, can be sizable. Unrestricted surplus (deficit) may not always reflect the amount available for operations if non-operating items, such as capital campaign contributions released from restriction and gains/losses on investments, are present. Calculation: Balance Sheet, Line 27B (Unrestricted net assets, end of year) - Line 27A (Unrestricted net assets, beginning of year) * Unrestricted surplus (deficit) before depreciation: Same as above but calculated before annual depreciation expense. It may be helpful to look at profitability without the effects of depreciation, a non-cash expense that serves as a proxy for future replacement needs on fixed assets. Calculation: Balance Sheet, Line 27B (Unrestricted net assets, end of year) - Line 27A (Unrestricted net assets, beginning of year) + Statement of Functional Expenses, Line 22A (Depreciation) * Total revenue (restricted and unrestricted): The sum of all income sources received within a given year. The Form 990 does not distinguish between unrestricted and restricted revenues; therefore it is possible that a portion of revenues reported here are restricted for future use and unavailable for use in the year received. Statement of Revenue, Line 12A (Total revenue) * Program services revenue: Funds received by an organization in exchange for providing the services for which it received tax-exemption (e.g., tuition, fees, or admissions). Government revenue is considered program service revenue if the government, rather than the public, is the primary beneficiary of the services. Most government contracts should be booked under government grants since the beneficiary is the general public. However, it is not uncommon for nonprofits to book contracts as program services revenue. Medicare and Medicaid payments should be considered program services revenue since the insurance coverage is with the individual who contracts with the nonprofit organization for service. May also include earned revenue from sales of inventory for hospitals, colleges and universities only and revenue from certain unrelated trade and business activities. Statement of Revenue, Line 2g * Membership dues: The portion of a charge for organizational membership that is not given in exchange for any goods or services. For example, a theater provides a donor with two tickets worth $50 for a $75 membership. Only $25 would be recognized in this line item. Statement of Revenue, Line 1b * Investment income: Interest and dividend income from equity, debt, and bond securities. Excludes realized and unrealized gains and losses on investments. Calculation: Statement of Revenue, Line 3A (Investment income) + Line 4A (Income from investment of tax-exempt bond proceeds) * Government grants: Government revenue, whether from local, state, federal or foreign government units, is considered a contributed grant if the primary beneficiary of services provided is the public, rather than the government unit itself. For the purposes of this report, due to the use of IRS Form 990 data, most government contracts should be booked under government grants since the beneficiary is the general public. However, it is not uncommon for nonprofits to book contracts as program services revenue. Statement of Revenue, Line 1e * All other grants and contributions: For the purposes of this report, includes: support from federated campaigns (such as United Way), foundations, individuals, corporations, fundraising events (net of expenses) and other related organizations. May include restricted funds received for future years, and therefore not accurately represent revenue available for use in the given year. May also include funds not intended for operations, e.g., capital campaign dollars for a facility project or an endowment. Calculation: Statement of Revenue, Sum of Lines 1a (Federated campaigns), 1c (Fundraising events), 1d (Related organizations), 1f (All other contributions), 8c (Net income from fundraising events) * Other revenue: For the purposes of this report, this category includes rental income, royalties, gaming, gains/losses on sales of assets and investments, sales of inventory items, and miscellaneous revenue. Calculation: Statement of Revenue, Sum of Lines 5A (Royalties), 6d (Net gain or loss, Gross Rents), 7d (Net gain or loss, sales of other assets), 9c (Net income or (loss) from gaming), 10c (Net income or (loss) from sales of inventory), 11e (Total miscellaneous revenue) * Total expenses before depreciation: The annual costs of running operations and programming, excluding depreciation. Depreciation is an accounting estimate of the general wear and tear of land, buildings, equipment or other fixed assets over a defined useful life. Though it is a non-cash expense, it can help nonprofits plan for the maintenance and replacement of depreciated fixed assets. Calculation: Statement of Functional Expenses, Line 25A (Total functional expenses) - Line 22A (Depreciation) * Personnel: Personnel expenses include salaries, payroll taxes and benefits. This category generally excludes costs associated with contract personnel, but depends on how the nonprofit filled out the Form 990. Calculation: Statement of Functional Expenses, Sum of Lines 5A (Compensation of current), 6A (Compensation not included), 7A (Other salaries and wages), 8A (Pension plan contributions), 9A (Other employee benefits), 10A (Payroll taxes) * Professional fees: All contract professionals, such as teachers, artists, musicians, lawyers, accountants, architects, who do not have their taxes withheld by the organization nor do they receive benefits. Calculation: Statement of Functional Expenses, Sum of Lines 11a (Management), 11b (Legal), 11c (Accounting), 11d (Lobbying), 11e (Professional fundraising), 11f (Investment mgmt.), 11g (Other) * Occupancy: All costs relating to the rent, utilities, insurance and maintenance of square footage occupied. Does not include periodic capital improvements to property (leased or owned), which would be capitalized on the balance sheet as assets. Statement of Functional Expenses, Line 16A * Interest: The interest portion of loan payments, which are reflected in an organization's income statement or budget - does not include payments of loan principal which are captured on the balance sheet. Statement of Functional Expenses, Line 20A * Pass-through: Funds either spent on behalf of, or passed through to, a secondary recipient. Statement of Functional Expenses, Lines 1A-4A * All other expenses: For the purposes of this report, this expense category includes all expense line items not reflected in Personnel, Professional fees, Occupancy, Interest, and Pass-through expense categories. Calculation: Statement of Functional Expenses, Sum of Lines 12A (Advertising), 13A (Office expenses), 14A (Information technology), 15A (Royalties), 17A (Travel), 18A (Payments of travel or entertainment), 19A (Conferences, conventions), 21A (Payments to affiliates), 23A (Insurance), 24a, b, c, d, e, f (Other expenses) * Full Costs: Comprised of total expenses in addition to resource needs reflected on an organization's balance sheet and necessary for longer-term financial health. Relevant amounts and components of full cost vary by individual organization and can include: total expenses - including unfunded expenses, working capital, reserves, debt principal repayments, fixed asset additions, and change capital. See Full Report for a detailed estimated analysis. * Capital structure: The nature (restricted vs. unrestricted, fixed vs. liquid), composition (relative proportion across categories), and magnitude (amounts) of the assets, liabilities, and net assets comprising the balance sheet. A well-balanced capital structure enables organizations to take risks, innovate, and pursue new opportunities when it is appropriate and sufficiently sized to cover the organization's full cost needs. * Liquidity: Refers to the amount of cash and cash-like resources an organization has available to manage its working capital needs and to respond to risks or opportunities. * Months of cash: Measures how long an organization can operate at average monthly expense levels solely using existing cash. Some cash may be restricted by donors for future years or purposes and therefore limited in availability. A portion of temporarily restricted cash, however, may be available in the following fiscal year to deliver programs. Only a conversation with management can clarify what is available and when. Months of cash is calculated as end of year cash balance divided by monthly expenses (excluding depreciation). Calculation: [Balance Sheet, Line 1B (Cash) + Line 2B (Savings)] / [(Statement of Functional Expenses, Line 25A (Total functional expenses) - Line 22A (Depreciation)) / 12 (months)] * Months of estimated liquid unrestricted net assets: A measure of financial flexibility and risk tolerance, liquid unrestricted net assets (LUNA) represents the portion of unrestricted net assets exclusive of any ownership of fixed assets. LUNA includes a combination of cash, investments, receivables, and prepaid expenses less all liabilities not related to fixed assets. As one measure of liquidity, it represents flexible funds available to support operations. Months of estimated LUNA is calculated as LUNA divided by monthly expenses (excluding depreciation). This number is estimated due to assumptions made about the nature of debt reported in the Form 990. Calculation: [Balance Sheet, Line 27B (Unrestricted net assets) - Line 10c (Land, buildings, and equipment) - Line 23B (Secured mortgages) - Line 20B (Tax-exempt bond)] / [(Statement of Functional Expenses, Line 25A (Total functional expenses) - Line 22A (Depreciation)) / 12 (months)] Note: When net equity in land, buildings, and equipment is negative, it is excluded from the calculation of months of unrestricted liquid net assets. Updated almost 2 years ago Explore the endpoint documentation. Access nonprofit profile financials, people, and IRS compliance validation in an easy-to-read and intuitive PDF format. Insert an EIN in the path parameter to retrieve a Pro Report PDF of the organization. Premier Pro Report PDF only accepts GET requests. ``` https://api.candid.org/premier/v1/propdf/20-0049703 ``` ## Example Pro Report PDF Use Candid to validate organizations to ensure donations are 100% compliant with the IRS. * Ensure charities are compliant within key databases including IRS Publication 78, IRS Business Master File, Internal Revenue Bulletin, Automatic Revocation of Exemption, and OFAC Specially Designated Nationals List. * Gather additional details to support decision making, such as organization type, deductibility limitations, religious organization status, revocations, and more. * Download a timestamped Charity Check PDF document to archive for due diligence. * Verify multiple organizations simultaneously to serve solutions at scale. * Confirm organizations' nonprofit status with California state authorities, including the Attorney General’s Registry of Charitable Trusts and Franchise Tax Board. Each Charity Check API is a distinct endpoint that requires a unique API key. Please contact your Candid Account Manager if you need an API key. Charity Check API Validate organizations to ensure donations are 100% compliant with the IRS. * Charity Check PDF API Generate a PDF report to validate nonprofit status and eligibility with a 100% IRS compliant charity check. * Charity Check Bulk API Validate nonprofit status and eligibility of up to 25 organizations at a time with a 100% IRS compliant charity check. * State-level Charity Check - California Check whether charitable organizations may or may not operate in California with Attorney General Registry and Franchise Tax Board data. Grantmaking: Charity status confirmation and audit trailUtilize the Charity Check API to check the status and compliance of a single nonprofit organization at a time with detailed data. Utilize the Charity Check PDF API to download and save a PDF copy of the charity check report, which includes a timestamp, to build an audit trail for grantmaking. PDF Charity Check ReportUtilize the Charity Check PDF API to download and save a stand-alone Charity Check report on a single organization at a time. Batch and automate Charity Check jobsUtilize the Charity Check Bulk API to batch and automate large charity check jobs of up to 25 organizations at a time. ## Charity check overview user guides Interpret Charity Check Data Explore a detailed explanation of the Charity Check fields and potential outputs. * Charity Check Example Responses See example responses to interpret organization statuses. * FAQs - Charity Check Read some of our frequently asked questions regarding Charity Check. ## Charity Check endpoint-specific user guides Charity Check API Use Candid to validate organizations to ensure donations are 100% compliant with the IRS. * Charity Check PDF API Download a formatted Charity Check PDF and save it for your records. * Charity Check Bulk API Validate up to 25 organizations at a time with bulk capacity. * State-level Charity Check - California Confirm organizations' nonprofit status in California. Updated 4 days ago Charity Check API contains over 40 fields to help validate an organization's charitable status. * Support grant giving decision making with access to the validation data you need including organization type, deductibility limitations, religious organization status, revocations, and more * Seamlessly check compliance across multiple IRS-required databases Charity Check API only accepts GET requests. ``` https://api.candid.org/charitycheck/v1/13-1837418 ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 7, "errors": [], "data": { "organization_id": "6908122", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "13-1837418", "organization_name": "Candid", "organization_name_aka": "The Foundation Center, Foundation Center, GuideStar, GuideStar USA", "address_line1": "32 Old Slip", "address_line2": "24th Floor", "city": "New York", "state": "NY", "state_name": "New York", "zip": "10005", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Candid", "pub78_ein": "13-1837418", "pub78_verified": "True", "pub78_city": "New York", "pub78_state": "NY", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "CANDID", "bmf_ein": "13-1837418", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "06", "ruling_year": "1957", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:42:10 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] } } ``` In addition to the validation data returned with the Charity Check API, subscribers can also access a Charity Check PDF report using the Charity Check API PDF endpoint, which requires a separate API key. Please contact your Candid Account Manager if you need an API key to this specific endpoint.. * For more details on Charity Check fields, see the guide Interpret Charity Check data fields. Charity Check PDF API only accepts GET requests. ``` https://api.candid.org/charitycheckpdf/v1/pdf/13-1837418 ``` Click or tap on the graphic to enlarge it. ## Example Charity Check PDF ## Anatomy of a Charity Check PDF Report If you need to validate many organizations at once, use the Charity Check Bulk API to validate up to 25 organizations in a single API call. For each organization, the data returned is similar to that of a single Charity Check API call. By retrieving data on up to 25 organizations at once, we can reduce the number of API calls needed at scale to keep your records and accounts up to date. * For more details on Charity Check fields, see the guide Understanding Charity Check API responses. Charity Check Bulk API is a POST call with the list of organization EINs passed as a JSON list within the body. ## Example POST request and JSON body The Charity Check Bulk API only accepts a POST request. The organizations' EINs are passed as a JSON list within the request body. ``` https://api.candid.org/charitycheckbulk/v1 ``` ``` { "eins": [ "13-1837418", "53-0242652", "53-0206027", "81-1488711", "91-0996800", "13-2875808", "91-1039776", "91-1261928", "22-1905062", "94-3087060", "94-1156258", "23-2888152", "31-6402269", "20-3668110", "39-0866228", "56-1326126", "62-1049447", "58-1716970", "13-3179546", "20-0049703", "52-1388917", "13-3327220", "59-2654440", "59-2332120", "13-3300271" ] } ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 224, "errors": [], "data": { "organizations": [ { "organization_id": "6908122", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "13-1837418", "organization_name": "Candid", "organization_name_aka": "The Foundation Center, Foundation Center, GuideStar, GuideStar USA", "address_line1": "32 Old Slip", "address_line2": "24th Floor", "city": "New York", "state": "NY", "state_name": "New York", "zip": "10005", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Candid", "pub78_ein": "13-1837418", "pub78_verified": "True", "pub78_city": "New York", "pub78_state": "NY", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "CANDID", "bmf_ein": "13-1837418", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "06", "ruling_year": "1957", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7794876", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "53-0242652", "organization_name": "Nature Conservancy, Inc.", "organization_name_aka": "The Nature Conservancy", "address_line1": "4245 N Fairfax Dr", "address_line2": "Ste 100", "city": "Arlington", "state": "VA", "state_name": "Virginia", "zip": "22203", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Nature Conservancy", "pub78_ein": "53-0242652", "pub78_verified": "True", "pub78_city": "Arlington", "pub78_state": "VA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "Generally, a central organization holding a group exemption letter, whose subordinate units covered by the group exemption are also eligible to receive tax-deductible contributions, even though they are not separately listed (deductibility limitation dependent on various factors).", "deductibility_limitation": "Depends on various factors", "deductibility_status_description": "GROUP" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "NATURE CONSERVANCY", "bmf_ein": "53-0242652", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "03", "ruling_year": "1954", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "1251", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7794317", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "53-0206027", "organization_name": "Smithsonian Institution", "organization_name_aka": "Smithsonian", "address_line1": "P. O. Box 37012", "address_line2": "Mrc 035", "city": "Washington", "state": "DC", "state_name": "District of Columbia", "zip": "20013", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Smithsonian Institute", "pub78_ein": "53-0206027", "pub78_verified": "True", "pub78_city": "Washington", "pub78_state": "DC", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "SMITHSONIAN INSTITUTE", "bmf_ein": "53-0206027", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "01", "ruling_year": "1924", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "9575799", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "81-1488711", "organization_name": "O<NAME> G<NAME>", "organization_name_aka": "", "address_line1": "PO Box 1564", "address_line2": "", "city": "Oak Harbor", "state": "WA", "state_name": "Washington", "zip": "98277", "filing_req_code": "020", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Oak Harbor Garry Oak Society", "pub78_ein": "81-1488711", "pub78_verified": "True", "pub78_city": "Oak Harbor", "pub78_state": "WA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "OAK HARBOR GARRY OAK SOCIETY", "bmf_ein": "81-1488711", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "12", "ruling_year": "2016", "adv_ruling_month": "", "adv_ruling_year": "", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "8314080", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "91-0996800", "organization_name": "<NAME>", "organization_name_aka": "", "address_line1": "600 Se Barrington Dr", "address_line2": "", "city": "Oak Harbor", "state": "WA", "state_name": "Washington", "zip": "98277", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "<NAME>", "pub78_ein": "91-0996800", "pub78_verified": "True", "pub78_city": "Oak Harbor", "pub78_state": "WA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "ISLAND THRIFT", "bmf_ein": "91-0996800", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "12", "ruling_year": "1977", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "6908410", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "13-2875808", "organization_name": "Human Rights Watch, Inc.", "organization_name_aka": "HRW", "address_line1": "350 Fifth Avenue", "address_line2": "34th Floor", "city": "New York", "state": "NY", "state_name": "New York", "zip": "10118", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Human Rights Watch Inc.", "pub78_ein": "13-2875808", "pub78_verified": "True", "pub78_city": "New York", "pub78_state": "NY", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "<NAME>", "bmf_ein": "13-2875808", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "11", "ruling_year": "1976", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "8312347", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "91-1039776", "organization_name": "Assistance League of Bellingham WA", "organization_name_aka": "Title", "address_line1": "P.O. Box 2998", "address_line2": "", "city": "Bellingham", "state": "WA", "state_name": "Washington", "zip": "98227", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Assistance League of Bellingham Washington", "pub78_ein": "91-1039776", "pub78_verified": "True", "pub78_city": "Bellingham", "pub78_state": "WA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "ASSISTANCE LEAGUE OF BELLINGHAM WASHINGTON", "bmf_ein": "91-1039776", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "11", "ruling_year": "1978", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "8316175", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "91-1261928", "organization_name": "<NAME>", "organization_name_aka": "WCLT", "address_line1": "765 Wonn Road", "address_line2": "C-201", "city": "Greenbank", "state": "WA", "state_name": "Washington", "zip": "98253", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Whidbey-Camano Land Trust", "pub78_ein": "91-1261928", "pub78_verified": "True", "pub78_city": "Greenbank", "pub78_state": "WA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "WHIDBEY-CAMANO LAND TRUST", "bmf_ein": "91-1261928", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "03", "ruling_year": "1985", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7053782", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "22-1905062", "organization_name": "MARINE CORPS SCHOLARSHIP FOUNDATION INC", "organization_name_aka": "", "address_line1": "909 N Washington St Ste 400", "address_line2": "", "city": "Alexandria", "state": "VA", "state_name": "Virginia", "zip": "22314", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Marine Corps Scholarship Foundation Inc.", "pub78_ein": "22-1905062", "pub78_verified": "True", "pub78_city": "Alexandria", "pub78_state": "VA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "<NAME>PS SCHOLARSHIP FOUNDATION INC", "bmf_ein": "22-1905062", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "04", "ruling_year": "1995", "adv_ruling_month": "", "adv_ruling_year": "", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "8410255", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "94-3087060", "organization_name": "Abode Services", "organization_name_aka": "", "address_line1": "40849 Fremont Blvd", "address_line2": "", "city": "Fremont", "state": "CA", "state_name": "California", "zip": "94538", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Abode Services", "pub78_ein": "94-3087060", "pub78_verified": "True", "pub78_city": "Fremont", "pub78_state": "CA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "ABODE SERVICES", "bmf_ein": "94-3087060", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "11", "ruling_year": "1989", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "8388885", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "94-1156258", "organization_name": "California Academy of Sciences", "organization_name_aka": "", "address_line1": "55 Music Concourse Drive", "address_line2": "Golden Gate Park", "city": "San Francisco", "state": "CA", "state_name": "California", "zip": "94118", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "California Academy of Sciences", "pub78_ein": "94-1156258", "pub78_verified": "True", "pub78_city": "San Francisco", "pub78_state": "CA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "CALIFORNIA ACADEMY OF SCIENCES", "bmf_ein": "94-1156258", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "04", "ruling_year": "1926", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7136262", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "23-2888152", "organization_name": "<NAME>", "organization_name_aka": "", "address_line1": "P.O. Box 9509", "address_line2": "", "city": "Warwick", "state": "RI", "state_name": "Rhode Island", "zip": "02889", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Vanguard Charitable Endowment Program", "pub78_ein": "23-2888152", "pub78_verified": "True", "pub78_city": "Malvern", "pub78_state": "PA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "VANGUARD CHARITABLE ENDOWMENT PROGRAM", "bmf_ein": "23-2888152", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "12", "ruling_year": "1997", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7361255", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "31-6402269", "organization_name": "The Ohio University Foundation", "organization_name_aka": "", "address_line1": "PO Box 869", "address_line2": "", "city": "Athens", "state": "OH", "state_name": "Ohio", "zip": "45701", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Ohio University Foundation", "pub78_ein": "31-6402269", "pub78_verified": "True", "pub78_city": "Athens", "pub78_state": "OH", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "OHIO UNIVERSITY FOUNDATION", "bmf_ein": "31-6402269", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "03", "ruling_year": "1955", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7024911", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "20-3668110", "organization_name": "ONE ACRE FUND", "organization_name_aka": "", "address_line1": "1954 First St. #183", "address_line2": "", "city": "Highland Park", "state": "IL", "state_name": "Illinois", "zip": "60035", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "One Acre Fund", "pub78_ein": "20-3668110", "pub78_verified": "True", "pub78_city": "Brooklyn", "pub78_state": "NY", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "ONE ACRE FUND", "bmf_ein": "20-3668110", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "01", "ruling_year": "2006", "adv_ruling_month": "12", "adv_ruling_year": "2009", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7559689", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "39-0866228", "organization_name": "AMERICAN BOARD OF INTERNAL MEDICINE", "organization_name_aka": "", "address_line1": "510 Walnut Street", "address_line2": "Suite 1700", "city": "Philadelphia", "state": "PA", "state_name": "Pennsylvania", "zip": "19106", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "American Board of Internal Medicine", "pub78_ein": "39-0866228", "pub78_verified": "True", "pub78_city": "Philadelphia", "pub78_state": "PA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "AMERICAN BOARD OF INTERNAL MEDICINE", "bmf_ein": "39-0866228", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes.", "ruling_month": "12", "ruling_year": "1946", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(2) organization", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7870663", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "56-1326126", "organization_name": "Monarch", "organization_name_aka": "", "address_line1": "350 Pee Dee Avenue", "address_line2": "Suite 101", "city": "Albemarle", "state": "NC", "state_name": "North Carolina", "zip": "28001", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Monarch", "pub78_ein": "56-1326126", "pub78_verified": "True", "pub78_city": "Albemarle", "pub78_state": "NC", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "MONARCH", "bmf_ein": "56-1326126", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes.", "ruling_month": "06", "ruling_year": "1982", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(2) organization", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7985589", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "62-1049447", "organization_name": "Second Harvest Food Bank of Middle Tennessee", "organization_name_aka": "", "address_line1": "331 Great Circle Road", "address_line2": "", "city": "Nashville", "state": "TN", "state_name": "Tennessee", "zip": "37228", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Second Harvest Food Bank of Middle Tennessee Inc.", "pub78_ein": "62-1049447", "pub78_verified": "True", "pub78_city": "Nashville", "pub78_state": "TN", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "SECOND HARVEST FOOD BANK OF MIDDLE TENNESSEE INC", "bmf_ein": "62-1049447", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "05", "ruling_year": "1979", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7890582", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "58-1716970", "organization_name": "Youth Villages Inc", "organization_name_aka": "", "address_line1": "3320 Brother Boulevard", "address_line2": "", "city": "Memphis", "state": "TN", "state_name": "Tennessee", "zip": "38133", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Youth Villages Inc.", "pub78_ein": "58-1716970", "pub78_verified": "True", "pub78_city": "Bartlett", "pub78_state": "TN", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "YOUTH VILLAGES INC", "bmf_ein": "58-1716970", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes.", "ruling_month": "06", "ruling_year": "1987", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(2) organization", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "6915492", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "13-3179546", "organization_name": "Food Bank For New York City", "organization_name_aka": "", "address_line1": "39 Broadway, 10th Floor", "address_line2": "", "city": "New York", "state": "NY", "state_name": "New York", "zip": "10006", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Food Bank for New York City", "pub78_ein": "13-3179546", "pub78_verified": "True", "pub78_city": "New York", "pub78_state": "NY", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "FOOD BANK FOR NEW YORK CITY", "bmf_ein": "13-3179546", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "11", "ruling_year": "1983", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "6971754", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "20-0049703", "organization_name": "Wikimedia Foundation, Inc.", "organization_name_aka": "", "address_line1": "PO Box 98204", "address_line2": "", "city": "Washington", "state": "DC", "state_name": "District of Columbia", "zip": "20090", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Wikimedia Foundation Org", "pub78_ein": "20-0049703", "pub78_verified": "True", "pub78_city": "San Francisco", "pub78_state": "CA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "WIKIMEDIA FOUNDATION ORG", "bmf_ein": "20-0049703", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "03", "ruling_year": "2005", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7756945", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "52-1388917", "organization_name": "The Conservation Fund", "organization_name_aka": "", "address_line1": "1655 N. Fort Myer Drive", "address_line2": "Ste 1300", "city": "Arlington", "state": "VA", "state_name": "Virginia", "zip": "22209", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "The Conservation Fund A Nonprofit Corporation", "pub78_ein": "52-1388917", "pub78_verified": "True", "pub78_city": "Arlington", "pub78_state": "VA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "THE CONSERVATION FUND A NONPROFIT CORPORATION", "bmf_ein": "52-1388917", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "07", "ruling_year": "1985", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "6917780", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "13-3327220", "organization_name": "Action Against Hunger USA", "organization_name_aka": "", "address_line1": "One Whitehall Street", "address_line2": "2nd Floor", "city": "New York", "state": "NY", "state_name": "New York", "zip": "10004", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Action Against Hunger USA", "pub78_ein": "13-3327220", "pub78_verified": "True", "pub78_city": "New York", "pub78_state": "NY", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "ACTION AGAINST HUNGER USA", "bmf_ein": "13-3327220", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "12", "ruling_year": "1985", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "8006749", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "59-2654440", "organization_name": "Give Kids The World, Inc.", "organization_name_aka": "", "address_line1": "210 S Bass Rd", "address_line2": "", "city": "Kissimmee", "state": "FL", "state_name": "Florida", "zip": "34746", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Give Kids the World Inc.", "pub78_ein": "59-2654440", "pub78_verified": "True", "pub78_city": "Kissimmee", "pub78_state": "FL", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "GIVE KIDS THE WORLD INC", "bmf_ein": "59-2654440", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "16", "foundation_code_description": "Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes.", "ruling_month": "10", "ruling_year": "1986", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(2) organization", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "7980839", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "59-2332120", "organization_name": "H<NAME> Food Bank of Southwest Florida, Inc.", "organization_name_aka": "", "address_line1": "3760 Fowler Street", "address_line2": "", "city": "Fort Myers", "state": "FL", "state_name": "Florida", "zip": "33901", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Harry Chapin Food Bank of Southwest Florida Inc.", "pub78_ein": "59-2332120", "pub78_verified": "True", "pub78_city": "Fort Myers", "pub78_state": "FL", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "HARRY CHAPIN FOOD BANK OF SOUTHWEST FLORIDA INC", "bmf_ein": "59-2332120", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "08", "ruling_year": "1984", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] }, { "organization_id": "6917391", "organization_info_last_modified": "11/2/2021 2:25:06 PM", "ein": "13-3300271", "organization_name": "Delivering Good, Inc.", "organization_name_aka": "", "address_line1": "266 West 37th Street", "address_line2": "22nd Floor", "city": "New York", "state": "NY", "state_name": "New York", "zip": "10018", "filing_req_code": "010", "charity_check_last_modified": "10/29/2021 4:41:38 PM", "pub78_church_message": null, "pub78_organization_name": "Delivering Good Inc.", "pub78_ein": "13-3300271", "pub78_verified": "True", "pub78_city": "New York", "pub78_state": "NY", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A public charity (50% deductibility limitation).", "deductibility_limitation": "50%", "deductibility_status_description": "PC" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "11/1/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "DELIVERING GOOD INC", "bmf_ein": "13-3300271", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "09", "ruling_year": "1986", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "11/3/2021 10:49:29 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] } ] } } ``` Charity Check API contains over 40 fields to help validate an organization's charitable status. In this guide, we will provide a potential list of values for select advanced fields, so you can build out your validation, exception handling, and business rules appropriately. For a complete Charity Check API specification, including all fields and basic descriptions, see the APIs Docs for Charity Check API. More information about California data fields in Charity Check can be found in the State-level Charity Check user guide. ## Filing Required Code This indicates the primary return(s) the organization is required to file. Filing Required Code | Filing Required Code Description* | | --- | --- | 000 | This organization is not required to file an annual return with the IRS. | 001 | This organization is required to file an IRS Form 990-PF. | 010 | This organization is required to file an IRS Form 990 or 990-EZ. | 011 | This organization is required to file an IRS Form 990-PF. | 020 | This organization is required to file an IRS Form 990-N. | 021 | This organization is required to file an IRS Form 990-N. | 030 | This organization is required to file a group return with the IRS. | 031 | This organization is required to file an IRS Form 990-PF group return. | 040 | This organization is required to file an IRS Form 990-BL, return for Black Lung Trusts. | 060 | This organization is not required to file an annual return with the IRS because it is a church. | 061 | This organization is not required to file an annual return with the IRS because it is a church. | 070 | This organization is not required to file an annual return with the IRS because it is a government 501 c (1). | 130 | This organization is not required to file an annual return with the IRS because it is a religious organization. | 140 | This organization is not required to file an annual return with the IRS because it is an arm of a state or local government. | 141 | This organization is not required to file an annual return with the IRS because it is an arm of a state or local government. | *Note: Filing Required Code Descriptions are provided for interpretation purposes and are not included in the API field output. ## Pub78 Church Message A message indicating that although the organization is not on the Pub78, their filing requirement code shows that they are a religious organization and are therefore not required to appear on the Pub78 to establish their status. Null * "This organization is a church or religious organization. Churches and religious organizations qualify for exemption from federal income tax under IRC Section 501(c)(3) and are generally eligible to receive tax-deductible contributions." ## Pub78 Indicator Indicator for understanding an organization’s Publication 78 data. Subordinate organizations in group exemptions inherit the Pub78 status of the parent organization. Pub78 Indicator | Pub78 Indicator Description* | | --- | --- | 0 | Organization data provided from Pub 78 quarterly update. | 2 | Organization is subordinate with inherited data from central organization. | *Note: Pub78 Indicator Descriptions are provided for interpretation purposes and are not included in the API field output. ## Organization Types Section Overview The following table describes the possible values of the ``` deductibility_status_description ``` , `organization_type` , and ``` deductibility_limitation ``` fields, all found within the `organization_types` array. Deductibility Status Description | Organization Type | Deductibility Limitation | | --- | --- | --- | EO | An organization described in section 170(c) of the Internal Revenue Code other than a public charity or a private foundation (deductibility limitation dependent on various factors). | Depends on various factors | FED | An organization to which contributions are deductible if made for the use of a federal governmental unit (50% deductibility limitation). | 50% | FORGN | A foreign-addressed organization. These are generally organizations formed in the United States that conduct activities in foreign countries. Certain foreign organizations that receive charitable contributions deductible pursuant to treaty are also included, as are organizations created in U.S. possessions (deductibility limitation dependent on various factors). | Depends on various factors | GROUP | Generally, a central organization holding a group exemption letter, whose subordinate units covered by the group exemption are also eligible to receive tax-deductible contributions, even though they are not separately listed (deductibility limitation dependent on various factors). | Depends on various factors | LODGE | A domestic fraternal society, operating under the lodge system, but only if the contribution is to be used exclusively for charitable purposes (30% deductibility limitation). | 30% | PC | A public charity (50% deductibility limitation). | 50% | PF | A private foundation (30% deductibility limitation, generally). | 30% (generally) | POF | A private operating foundation (50% deductibility limitation). | 50% | SO | A type 1, type 2 or functionally integrated type 3 supporting organization (50% deductibility limitation). | 50% | SONFI | A non-functionally integrated type 3 supporting organization (50% deductibility limitation). | 50% | SOUNK | A supporting organization, unspecified type (50% deductibility limitation). | 50% | UNKWN | A charitable organization whose public charity status has not been determined (deductibility limitation dependent on various factors). | Depends on various factors | ## BMF Church Message A message indicating that although the organization is not on the IRS BMF, their filing requirement code shows that they are a church or religious organization and are therefore not required to appear on the IRS BMF to establish their status. * Null * "Churches that meet the requirements of IRC Section 501(c)(3) are automatically considered tax exempt and are not required to apply for and obtain recognition of tax-exempt status from the IRS." ## BMF Subsection Section Overview The following table describes the two fields that relate to the BMF subsection of an organization. Note that not all BMF subsections have descriptions available from the IRS. For more information, please visit IRS subsection codes. * BMF Subsection * BMF Subsection Description BMF Subsection | BMF Subsection Description | | --- | --- | 00 | 01 | 501(c)(1) Government Instrumentality | 02 | 501(c)(2) Title Holding Corporation | 03 | 501(c)(3) Private Nonoperating Foundation | 03 | 501(c)(3) Private Nonoperating Foundation (This organization has notified the IRS of its intention to convert to a public charity, and the IRS has ruled that grantors and contributors may consider it a public charity for the purpose of making contributions to the organization.) | 03 | 501(c)(3) Private Operating Foundation | 03 | 501(c)(3) Private Operating Foundation (This organization has notified the IRS of its intention to convert to a public charity, and the IRS has ruled that grantors and contributors may consider it a public charity for the purpose of making contributions to the organization.) | 03 | 501(c)(3) Public Charity | 04 | 501(c)(4) Civic Leagues and Social Welfare Organizations | 05 | 501(c)(5) Labor, Agricultural and Horticultural Organizations | 06 | 501(c)(6) Business Leagues, etc. | 07 | 501(c)(7) Social and Recreation Clubs | 08 | 501(c)(8) Fraternal Beneficiary Societies | 09 | 501(c)(9) Employees Associations | 10 | 501(c)(10) Domestic Fraternal Societies | 11 | 501(c)(11) Teachers' Retirement Fund Associations | 12 | 501(c)(12) Local Benevolent Life Insurance Associations, Mutual Irrigation and Telephone Companies, and Like Co | 13 | 501(c)(13) Cemetery Companies | 14 | 501(c)(14) Credit Unions and Other Mutual Financial Organizations | 15 | 501(c)(15) Mutual Insurance Company other than Life or Marine | 16 | 501(c)(16) Corporations Financing Crop Operations | 17 | 501(c)(17) Supplemental Unemployment Compensations Trust or Plan | 18 | 501(c)(18) Employee Funded Pension Trust formed prior to June 1959 | 19 | 501(c)(19) Post or Organizations of War Veterans | 20 | 501(c)(20) Group Legal Services Plan Organization | 21 | 501(c)(21) Black Lung Benefit Trusts | 23 | 501(c)(23) Veterans Association formed prior to 1880 | 25 | 501(c)(25) Title Holding Corporations for Multiple Organizations (Pensions, etc.) | 26 | 501(c)(26) State Sponsored High Risk Health Insurance Organization | 27 | 501(c)(27) State Sponsored Workers Compensation Reinsurances | 29 | 501(c)(29) ACA 1322 Qualified Nonprofit Health Insurance Issuers | 40 | 501(d) Apostolic and Religious Organizations | 50 | 501(e) Cooperative Hospital Service Organizations | 71 | 501(n) Charitable Risk Pools | 81 | 82 | 91 | 4947(a)(1) Non-exempt charitable trust (Public Charity) | 92 | 4947(a)(1) Non-Exempt Charitable Trusts - Private Foundations | ## Subsection Description Subsection code description as it relates to the subsection code that appears in the Business Master File. This code identifies the type of tax-exempt organization. This is often used to determine if contributions to the organization are tax-deductible. Subsection description | | --- | 501(c)(1) Government Instrumentality | 501(c)(2) Title Holding Corporation | 501(c)(3) Private Nonoperating Foundation | 501(c)(3) Private Nonoperating Foundation (This organization has notified the IRS of its intention to convert to a public charity, and the IRS has ruled that grantors and contributors may consider it a public charity for the purpose of making contributions to the organization.) | 501(c)(3) Private Operating Foundation | 501(c)(3) Private Operating Foundation (This organization has notified the IRS of its intention to convert to a public charity, and the IRS has ruled that grantors and contributors may consider it a public charity for the purpose of making contributions to the organization.) | 501(c)(3) Public Charity | 501(c)(4) Civic Leagues and Social Welfare Organizations | 501(c)(5) Labor, Agricultural and Horticultural Organizations | 501(c)(6) Business Leagues, etc. | 501(c)(7) Social and Recreation Clubs | 501(c)(8) Fraternal Beneficiary Societies | 501(c)(9) Employees Associations | 501(c)(10) Domestic Fraternal Societies | 501(c)(11) Teachers' Retirement Fund Associations | 501(c)(12) Local Benevolent Life Insurance Associations, Mutual Irrigation and Telephone Companies, and Like Co | 501(c)(13) Cemetery Companies | 501(c)(14) Credit Unions and Other Mutual Financial Organizations | 501(c)(15) Mutual Insurance Company other than Life or Marine | 501(c)(16) Corporations Financing Crop Operations | 501(c)(17) Supplemental Unemployment Compensations Trust or Plan | 501(c)(18) Employee Funded Pension Trust formed prior to June 1959 | 501(c)(19) Post or Organizations of War Veterans | 501(c)(20) Group Legal Services Plan Organization | 501(c)(21) Black Lung Benefit Trusts | 501(c)(23) Veterans Association formed prior to 1880 | 501(c)(25) Title Holding Corporations for Multiple Organizations (Pensions, etc.) | 501(c)(26) State Sponsored High Risk Health Insurance Organization | 501(c)(27) State Sponsored Workers Compensation Reinsurances | 501(c)(29) ACA 1322 Qualified Nonprofit Health Insurance Issuers | 501(d) Apostolic and Religious Organizations | 501(e) Cooperative Hospital Service Organizations | 501(n) Charitable Risk Pools | 4947(a)(1) Non-exempt charitable trust (Public Charity) | 4947(a)(1) Non-Exempt Charitable Trusts - Private Foundations | ## Foundation Code Foundation Code | Foundation Code Description | | --- | --- | 00 | All organizations except 501(c)(3) | 02 | Private operating foundation exempt from paying excise taxes or investment income | 03 | Private Operating foundation (other) | 04 | Private nonoperating foundation | 09 | Suspense | 10 | Church | 11 | School | 12 | Hospital or medical research organization | 13 | Organization which operates for benefit of college or university and is owned or operated by a governmental unit. | 14 | Governmental unit | 15 | Organization which receives a substantial part of its support from a governmental unit or the general public | 16 | Organization that normally receives no more than one-third of its support from gross investment income and unrelated business income and at the same time more than one-third of its support from contributions, fees, and gross receipts related to exempt purposes. | 17 | Organizations operated solely for the benefit of and in conjunction with organizations described in 10 through 16 above. | 18 | Organization organized and operated to test for public safety. | 21 | 509(a)(3) Type I | 22 | 509(a)(3) Type II | 23 | 509(a)(3) Type III Functionally Integrated | 24 | 509(a)(3) Type III Not Functionally Integrated | ## Foundation Type Code Section Overview Foundation Type Code | Foundation Type Code Description | | --- | --- | EOF | Exempt operating foundation (section 4940(d)) | NC | Non-charity (not 501(c)(3)) | Not Available | Code cannot be determined due to insufficient data. | PC | Public charity described in section 509(a)(1) or (2) | PF | Private non-operating foundation (section 509(a)) | POF | Private operating foundation (section 4942(j)(3)) other than an EOF | SO I | Type I supporting organization (sections 509(a)(3) and 509(a)(3)(B)(i)) other than an SO-DP | SO II | Type II supporting organization (sections 509(a)(3) and 509(a)(3)(B)(ii)) other than an SO-DP | SO III FI | Functionally integrated type III supporting organization (sections 509(a)(3), 509(a)(3)(B)(iii), and 4943(f) (5)(B)) other than an SO-DP | SO III NFI | Non-functionally integrated type III supporting organization (sections 509(a)(3), 509(a)(3)(B)(iii), and 4943(f) (5)(B)) | TPS | Testing for public safety organization (section 509(a)(4)) | ## Exempt Status Code The EO Status Code defines the type of exemption held by the organization. Exempt Status Code | Exempt Status Code Description* | | --- | --- | 01 | Unconditional Exemption | 02 | Conditional Exemption | 12 | Trust described in section 4947(a)(2) of the IR Code | 25 | Organization terminating its private foundation status under section 507(b)(1)(B) of the Code | ## OFAC Status Indicates whether this organization has been listed by OFAC on the Specially Designated National (SDN) List, also known as the “Terrorist Watch List.” * This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list. * This organization's tax exemption has been suspended under Internal Revenue Code Section 501(p). Contributions to this organization during its 501(p) suspension are not deductible. This organization has been designated by the U.S. Treasury Department's Office of Foreign Assets Control as supporting or engaging in terrorist activity. All financial transactions with this organization by residents of the United States, or within the borders of the United States, are prohibited. Learn more at https://www.treasury.gov/resource-center/sanctions/Pages/default.aspx ## Revocation Code Indicates the automatic revocation code provided by the IRS in the Automatic Revocation of Exemption File. Most tax-exempt organizations other than churches and certain church-related organizations are required to file an annual information return or notice with the IRS. Organizations that do not file for three consecutive years automatically lose their tax-exempt status. An automatic revocation is effective on the original filing due date of the third annual return or notice. Revocation Code | Revocation Code Description* | | --- | --- | Indicates no revocation code for the organization. | F | Failure to File | R | Reinstated | ## Foundation 509A Status Non-private foundation status. Only applies to 501(c)(3) public charities | | --- | Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(i) | Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(ii) | Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(iii) | Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(iv) | Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(v) | Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi) | Section 509(a)(2) organization | Section 509(a)(3) organization | Section 509(a)(3) Type I organization | Section 509(a)(3) Type II organization | Section 509(a)(3) Type III Functionally Integrated organization | Section 509(a)(3) Type III Not Functionally Integrated organization | Section 509(a)(4) organization | Preview response examples to see different charity check scenarios. For additional information on the data returned, see the detailed guide Interpret Charity Check Data Fields. Notable fields The fields that are key to validating each scenario are indicated with a comment /see here/ ## Example organization that would pass a Charity Check screening ``` { "code": 200, "message": "Request was processed successfully!", "took": 16, "errors": [], "data": { "organization_id": "7794876", "organization_info_last_modified": "5/14/2020 3:44:01 PM", "ein": "53-0242652", "organization_name": "Nature Conservancy, Inc.", "organization_name_aka": "The Nature Conservancy", "address_line1": "4245 N Fairfax Dr", "address_line2": "Ste 100", "city": "Arlington", "state": "VA", "state_name": "Virginia", "zip": "22203", "filing_req_code": "010", "charity_check_last_modified": "5/14/2020 3:42:08 PM", "pub78_church_message": null, "pub78_organization_name": "Nature Conservancy", "pub78_ein": "53-0242652", "pub78_verified": "True", "pub78_city": "Arlington", "pub78_state": "VA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "Generally, a central organization holding a group exemption letter, whose subordinate units covered by the group exemption are also eligible to receive tax-deductible contributions, even though they are not separately listed (deductibility limitation dependent on various factors).", "deductibility_limitation": "Depends on various factors", "deductibility_status_description": "GROUP" } ], "most_recent_pub78": "5/11/2020 4:00:00 AM", "most_recent_irb": "5/18/2020 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "NATURE CONSERVANCY", "bmf_ein": "53-0242652", "bmf_status": "True", "most_recent_bmf": "5/11/2020 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "03", "ruling_year": "1954", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "1251", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "5/21/2020 5:56:41 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] } } ``` ## Example organization that was automatically revoked ``` { code": 200, "message": "Request was processed successfully!", "took": 10, "errors": [], "data": { "organization_id": "6802268", "organization_info_last_modified": "5/14/2020 3:44:01 PM", "ein": "00-0267075", "organization_name": "International Association of Lions Clubs", "organization_name_aka": "BRUNSWICK GATEWAY ", "address_line1": "3324 Kelwin Ave", "address_line2": "", "city": "Brunswick", "state": "GA", "state_name": "Georgia", "zip": "31520", "filing_req_code": "020", "charity_check_last_modified": "5/14/2020 3:42:08 PM", "pub78_church_message": null, "pub78_organization_name": "", "pub78_ein": "", "pub78_verified": "False", "pub78_city": "", "pub78_state": "", "pub78_indicator": "", "organization_types": null, "most_recent_pub78": "", "most_recent_irb": "5/26/2020 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "", "bmf_ein": "", "bmf_status": "False", "most_recent_bmf": "5/11/2020 4:00:00 AM", "bmf_subsection": "", "subsection_description": "", "foundation_code": "", "foundation_code_description": "", "ruling_month": "", "ruling_year": "", "adv_ruling_month": "", "adv_ruling_year": "", "group_exemption": "", "exempt_status_code": "", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", /*see here*/ "revocation_code": "F", /*see here*/ "revocation_date": "11/15/2010 5:00:00 AM", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "5/27/2020 9:27:22 PM", "foundation_type_code": "Not Available", "foundation_type_description": "Code cannot be determined due to insufficient data.", "parent_organizations": [] } } ``` ## Example organization that was automatically revoked, then reinstated ``` { "code": 200, "message": "Request was processed successfully!", "took": 13, "errors": [], "data": { "organization_id": "9261139", "organization_info_last_modified": "10/11/2021 4:03:16 PM", "ein": "01-0280026", "organization_name": "Maple Grove Cemetery Corporation", "organization_name_aka": "", "address_line1": "136 Rebel Hill Rd", "address_line2": "", "city": "Islesboro", "state": "ME", "state_name": "Maine", "zip": "04848", "filing_req_code": "020", "charity_check_last_modified": "10/11/2021 4:01:07 PM", "pub78_church_message": null, "pub78_organization_name": "Maple Grove Cemetery Corporation", "pub78_ein": "01-0280026", "pub78_verified": "True", "pub78_city": "Islesboo", "pub78_state": "ME", "pub78_indicator": "0", "organization_types": [ { "organization_type": "An organization described in section 170(c) of the Internal Revenue Code other than a public charity or a private foundation (deductibility limitation dependent on various factors).", "deductibility_limitation": "Depends on various factors", "deductibility_status_description": "EO" } ], "most_recent_pub78": "10/11/2021 4:00:00 AM", "most_recent_irb": "10/25/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "MAPLE GROVE CEMETERY CORPORATION", "bmf_ein": "01-0280026", "bmf_status": "True", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "13", "subsection_description": "501(c)(13) Cemetery Companies", "foundation_code": "00", "foundation_code_description": "All organizations except 501(c)(3)", "ruling_month": "08", "ruling_year": "2013", "adv_ruling_month": "00", "adv_ruling_year": "0000", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", /*see here*/"revocation_code": "R", /*see here*/"revocation_date": "5/15/2010 4:00:00 AM", /*see here*/"reinstatement_date": "8/1/2013 4:00:00 AM", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "Only applies to 501(c)(3) public charities", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "10/28/2021 10:36:37 PM", "foundation_type_code": "NC", "foundation_type_description": "Non-charity (not 501(c)(3))", "parent_organizations": [] } } ``` ## Example organization that was listed on the IRS Internal Revenue Bulletin ``` { "code": 200, "message": "Request was processed successfully!", "took": 61, "errors": [], "data": { "organization_id": "8368373", "organization_info_last_modified": "10/11/2021 4:03:16 PM", "ein": "92-0115914", "organization_name": "Fairbanks Outboard Association Inc", "organization_name_aka": "", "address_line1": "PO Box 81594", "address_line2": "", "city": "Fairbanks", "state": "AK", "state_name": "Alaska", "zip": "99708", "filing_req_code": "020", "charity_check_last_modified": "10/11/2021 4:01:07 PM", "pub78_church_message": null, "pub78_organization_name": "", "pub78_ein": "", "pub78_verified": "False", "pub78_city": "", "pub78_state": "", "pub78_indicator": "", "organization_types": null, "most_recent_pub78": "", "most_recent_irb": "10/25/2021 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "", "bmf_ein": "", "bmf_status": "False", "most_recent_bmf": "10/11/2021 4:00:00 AM", "bmf_subsection": "", "subsection_description": "", "foundation_code": "", "foundation_code_description": "", "ruling_month": "", "ruling_year": "", "adv_ruling_month": "", "adv_ruling_year": "", "group_exemption": "", "exempt_status_code": "", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "F", "revocation_date": "5/15/2010 4:00:00 AM", "reinstatement_date": "10/1/2014 4:00:00 AM", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "", /*see here*/"irb_organization_id": "41560", /*see here*/"bulletin_number": "2020-05", /*see here*/"bulletin_url": "https://www.irs.gov/pub/irs-irbs/irb20-05.pdf", /*see here*/"effective_date": "1/27/2020 5:00:00 AM", /*see here*/"irb_last_modified": "1/24/2020 7:28:21 PM", "report_date": "10/29/2021 3:23:42 PM", "foundation_type_code": "Not Available", "foundation_type_description": "Code cannot be determined due to insufficient data.", "parent_organizations": [] } } ``` ## Example organization that is on the OFAC list ``` { "code": 200, "message": "Request was processed successfully!", "took": 11, "errors": [], "data": { "organization_id": "7479013", "organization_info_last_modified": "5/14/2020 3:44:01 PM", "ein": "36-3823186", "organization_name": "Benevolence International Foundation", "organization_name_aka": "", "address_line1": "9838 S Roberts Rd Ste 1w", "address_line2": "", "city": "Palos Hills", "state": "IL", "state_name": "Illinois", "zip": "60465", "filing_req_code": "010", "charity_check_last_modified": "5/22/2020 12:04:54 PM", "pub78_church_message": null, "pub78_organization_name": "", "pub78_ein": "", "pub78_verified": "False", "pub78_city": "", "pub78_state": "", "pub78_indicator": "", "organization_types": null, "most_recent_pub78": "", "most_recent_irb": "5/26/2020 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "", "bmf_ein": "", "bmf_status": "False", "most_recent_bmf": "5/11/2020 4:00:00 AM", "bmf_subsection": "", "subsection_description": "", "foundation_code": "", "foundation_code_description": "", "ruling_month": "", "ruling_year": "", "adv_ruling_month": "", "adv_ruling_year": "", "group_exemption": "", "exempt_status_code": "", /*see here*/"ofac_status": "This organization's tax exemption has been suspended under Internal Revenue Code Section 501(p). Contributions to this organization during its 501(p) suspension are not deductible.\r\n\r\nThis organization has been designated by the U.S. Treasury Department's Office of Foreign Assets Control as supporting or engaging in terrorist activity. All financial transactions with this organization by residents of the United States, or within the borders of the United States, are prohibited. <a href=\"https://www.treasury.gov/resource-center/sanctions/Pages/default.aspx\" title=\"Learn more\" target=\"_blank\">Learn more</a>", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "5/27/2020 9:22:44 PM", "foundation_type_code": "Not Available", "foundation_type_description": "Code cannot be determined due to insufficient data.", "parent_organizations": [] } } ``` ## Example organization that is a religious organization ``` { "code": 200, "message": "Request was processed successfully!", "took": 9, "errors": [], "data": { "organization_id": "6802280", "organization_info_last_modified": "5/14/2020 3:44:01 PM", "ein": "00-0846590", "organization_name": "Evangelical Christian Fellowship I<NAME> Evangelica Inc", "organization_name_aka": "", "address_line1": "190 Cherry St", "address_line2": "", "city": "Fall River", "state": "MA", "state_name": "Massachusetts", "zip": "02720", "filing_req_code": "060", "charity_check_last_modified": "5/14/2020 3:42:08 PM", /*see here*/"pub78_church_message": "This organization is a church or religious organization. Churches and religious organizations qualify for exemption from federal income tax under IRC Section 501(c)(3) and are generally eligible to receive tax-deductible contributions.", "pub78_organization_name": "", "pub78_ein": "", "pub78_verified": "False", "pub78_city": "", "pub78_state": "", "pub78_indicator": "", "organization_types": null, "most_recent_pub78": "", "most_recent_irb": "5/26/2020 12:00:00 AM", /*see here*/"bmf_church_message": "This organization is a church or religious organization. Churches and religious organizations qualify for exemption from federal income tax under IRC Section 501(c)(3) and are generally eligible to receive tax-deductible contributions.", "bmf_organization_name": "", "bmf_ein": "", "bmf_status": "False", "most_recent_bmf": "5/11/2020 4:00:00 AM", "bmf_subsection": "", "subsection_description": "", "foundation_code": "", "foundation_code_description": "", "ruling_month": "", "ruling_year": "", "adv_ruling_month": "", "adv_ruling_year": "", "group_exemption": "", "exempt_status_code": "", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", "irs_bmf_pub78_conflict": "False", "foundation_509a_status": "", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "5/27/2020 9:25:55 PM", "foundation_type_code": "Not Available", "foundation_type_description": "Code cannot be determined due to insufficient data.", "parent_organizations": [] } } ``` ## Example organization with an IRS BMF/Pub 78 conflict ``` { "code": 200, "message": "Request was processed successfully!", "took": 9, "errors": [], "data": { "organization_id": "9406662", "organization_info_last_modified": "5/27/2020 6:50:28 PM", "ein": "46-4556468", "organization_name": "PLUSONEPLUSONEPLUSONE", "organization_name_aka": "PLUS1", "address_line1": "1459 18th Street Box 348", "address_line2": "", "city": "San Francisco", "state": "CA", "state_name": "California", "zip": "94107", "filing_req_code": "010", "charity_check_last_modified": "5/22/2020 12:04:54 PM", "pub78_church_message": null, "pub78_organization_name": "Plusoneplusoneplusone", "pub78_ein": "46-4556468", "pub78_verified": "True", "pub78_city": "San Francisco", "pub78_state": "CA", "pub78_indicator": "0", "organization_types": [ { "organization_type": "A private foundation (30% deductibility limitation, generally).", "deductibility_limitation": "30% (generally)", "deductibility_status_description": "PF" } ], "most_recent_pub78": "5/11/2020 4:00:00 AM", "most_recent_irb": "5/26/2020 12:00:00 AM", "bmf_church_message": null, "bmf_organization_name": "PLUSONEPLUSONEPLUSONE", "bmf_ein": "46-4556468", "bmf_status": "True", "most_recent_bmf": "5/11/2020 4:00:00 AM", "bmf_subsection": "03", "subsection_description": "501(c)(3) Public Charity", "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public", "ruling_month": "07", "ruling_year": "2014", "adv_ruling_month": "", "adv_ruling_year": "", "group_exemption": "0000", "exempt_status_code": "01", "ofac_status": "This organization was not included in the Office of Foreign Assets Control Specially Designated Nationals(SDN) list.", "revocation_code": "", "revocation_date": "", "reinstatement_date": "", /*see here*/"irs_bmf_pub78_conflict": "True", "foundation_509a_status": "Section 509(a)(1) organization as referred to in Section 170(b)(1)(A)(vi)", "irb_organization_id": "", "bulletin_number": "", "bulletin_url": "", "effective_date": "", "irb_last_modified": "", "report_date": "5/27/2020 9:24:34 PM", "foundation_type_code": "PC", "foundation_type_description": "Public charity described in section 509(a)(1) or (2)", "parent_organizations": [] } } ``` Q: Can I use a third party such as Candid to obtain BMF data concerning a potential grantee’s public charity classification? * A. Yes! IRS Revenue Procedure 2011-33 allows grantors to rely on third-party resources, such as Charity Check, to obtain required Business Master File (BMF) data concerning a potential grantee's public charity classification under section 509 (a) (1), (2) or (3). Q: Can I deduct a contribution? * A. View this mini video course produced by IRS Exempt Organizations on contribution deductibility. See Also: PDF text transcript of the mini course. Q: How do I access the PDF Charity Check Report? * A. You can download a PDF version of the Charity Check report by making a call to the Charity Check PDF API. Q: Can I rely on Tax Exempt Organization Search to find an organization’s foundation classification or whether contributions to an organization are deductible? * A. Contributors and grantors may rely on either the Tax Exempt Organization Search or the Exempt Organizations Business Master File Extract (EO BMF). Both are updated monthly, although not necessarily on the same day. To assist with searches, the IRS publishes the date the information was posted. Q: Is there a field in the Charity Check API that identifies the last time an IRS Revocation List was processed? I’m aware of the revocation_date and reinstatement_date fields, but those would only be populated for NPOs that were revoked or reinstated at least once. Is there a method that would allow me to make a single call to retrieve this information? * A. Unfortunately, there is not an explicit field for the last date a revocations file was processed. We will keep that in mind for future API releases. Q. How frequently does the Charity Check API pull and update a revocation list from the IRS? * A. We ping the IRS website every 20 minutes and download the big three files (BMF, Pub78, Revocations) when we detect changes. Occasionally, the IRS will update the files in the middle of the month, but not change the date on the website. The most likely file to be updated mid-month is the Revocations file. When it does, we process it and push it out to products in less than 24 hours. Q: Does the weekly IRB impact NPO status in terms of tax status? We are trying to determine what information is being updated to an NPO from this bulletin. * A. The Internal Revenue Bulletin (IRB) is the authoritative instrument for announcing official rulings and procedures of the IRS and for publishing Treasury Decisions, Executive Orders, Tax Conventions, legislation, court decisions, and other items of general interest. Q: Which field represents an NPO’s headquarters? * A. In the GuideStar Premier API you can use the field “is_national_hq”, in the data/summary section, to determine if the NPO is considered a headquarters. Note that the Premier API uses a separate license from a standalone charity check license. Q: Is there a field that indicates an organization is not US-based? * A. Yes, you can reference the Deductibility Status Description field and filter by code: FORGN to flag these organizations, and cross-reference the organization address. Organizations with this status description are classified by the IRS as “A foreign-addressed organization. These are generally organizations formed in the United States that conduct activities in foreign countries. Certain foreign organizations that receive charitable contributions deductible pursuant to treaty are also included, as are organizations created in U.S. possessions (deductibility limitation dependent on various factors).” Q: I know that organizations that have just achieved their tax-exempt status can send their letter of determination to GuideStar in advance of being listed on the IRS BMF/Pub78 to be included on the GuideStar website. Is this data available via your Charity Check API as well? * A. No, this advanced status data is not currently available via the API, it is tentatively planned to be included in the next version of the Charity Check API. Q: Does every record list a most recent IRB date regardless of if the organization is listed on the IRB? * A. Yes, a most recent IRB date is listed on every record. Q: Is it correct to assume that Bulletin Number, Bulletin URL, and Bulletin Effective Date would only be populated if an organization is listed on a bulletin? Q: What happens if an organization is listed in January and then again in March? Do you only show the most recent bulletin number/URL and associated date? * A. Yes, the most recent IRB will be listed. Q: Being listed in the IRB doesn’t necessarily mean an organization was revoked–for example, it might mean it’s under investigation– so do you list all entries so we can look at what exactly was said about the organization in question? * A. Yes, the link to the IRB is provided for that reason. Q: What happens if the organization’s status was revoked and then is reinstated? Do you wipe these fields out, or do they stay on the record? * A. Yes, they remain on the record for research purposes. Q: Is the IRB Last Modified field the date that you updated the IRB related fields? * A. Yes, it will be populated for the organizations that appear on the IRB. Q: Is the purposes of the IRB related fields collectively to enable a grant maker to flag an organization for further research/due diligence – not to screen them out – correct? Q: The Charity Check occasionally (though rarely) doesn't reflect the same data--for example, an organization’s name--that is shown on GuideStar website. Why is that? * A. The guidestar.org website relies on the GuideStar database and the Charity Check API relies on the IRS BMF, IRS Publication 78, as well as the GuideStar database. There may be differences with the data due to its ever-changing nature, which is why we provide fields directly from all three sources for comparison. Q: Can you share more about your data sources and processes? A. Candid processes paper and electronic annual filings daily. The volume for these varies from a low of 12,000 to a high of 130,000 in a given month based on the time of year and what the IRS releases. In addition to annual filings, we monitor and pull in updates from multiple IRS backbone data sources listed below as well as the OFAC SDN list: • Exempt Organizations Business Master File Extract (EO BMF) • Tax Exempt Organization Search (formally known as Pub78) • Automatic Revocation List • IRS Internal Revenue Bulletin (IRB) • OFAC Specially Designated National (SDN) List * While there is an official published cadence for each of these, we have found anomalies in the IRS’s posting schedule, so we proactively scrape the IRS website every 20 minutes and download the big three files (BMF, Pub78, Revocations) to determine if any file has changed. If that process detects a change, we process the file and update our database accordingly. * Regarding anomalies, while there is an official schedule the IRS publishes, occasionally they will update the files off-cycle (for example, mid-month) without changing the date on the website. The most likely file to be updated mid-month is the Revocations file. When this happens, we process the change and push it out to products in fewer than 24 hours. * We cannot independently validate the information in these files, so we do not maintain ‘quality’ metrics along those lines. We do, however, test the BMF and Pub78 files before loading them to ensure that the volume of changes to any individual field are within a statistical range based on historic patterns. If any changes fall outside of those ranges, we put the load on hold, research the issue, and engage the IRS if we find what we believe is an error on their part. * We also take steps to enhance the data we receive in several ways. Examples of this include the use of address correction software, the application of NTEE codes from the NCCS, geo coding (lat/long), and the addition of CBSA/MSA, PCS, and SDG codes. Q: Does the Charity Check API contain data from state nonprofit registries? * A. Yes, the California endpoint provides data from the California Attorney General’s Registry of Charitable Trusts and Franchise Tax Board. More information about the Charity Check California endpoint can be found in the California endpoint guide. The California endpoint of the Charity Check API provides data about a nonprofit's status with the California Attorney General's Registry of Charitable Trusts and the California Franchise Tax Board. This data can be used to check the standing of a nonprofit organization in California and confirm that they are eligible to receive donations. This endpoint uses EIN as a path parameter to return data for an organization. ``` https://api.candid.org/charitycheck/v1/CA/13-1837418 ``` ## Interpreting data fields ### Attorney General (AG) The `attorney_general` object contains information regarding an organization's standing with the California Attorney General's Registry of Charitable Trusts. The ``` ag_may_operate_or_solicit_in_ca ``` field provides information about whether the organization may or may not operate or solicit in California. The `ag_registry_status` field provides additional data about the organization's Charity Registration status. Below is a table of potential values for these fields. More information on the definition of these registry statuses can be found here. May_Operate_or_Solicit_in_CA | Registry_Status | | --- | --- | No | Delinquent - Late Fees Due | No | Delinquent | No | Mutual Benefit | No | Not Registered - Cease and Desist Order | No | Revoked | No | Subject to Cease and Desist Order | No | Suspended | Not Operating/Dissolved | Closed - Registration Not Required | Not Operating/Dissolved | Dissolution Pending | Not Operating/Dissolved | Dissolution Waiver Issued | Not Operating/Dissolved | Dissolved | Not Operating/Dissolved | Exempt - Dissolution Pending | Not Operating/Dissolved | Exempt - Dissolution Waiver Issued | Not Operating/Dissolved | Exempt - Dissolved | Not Operating/Dissolved | Exempt - Withdrawn | Not Operating/Dissolved | Never Registered - Diss. Waiver Issued | Not Operating/Dissolved | Never Registered - Dissolution Pending | Not Operating/Dissolved | Never Registered - Dissolved | Not Operating/Dissolved | Never Registered - Withdrawn | Not Operating/Dissolved | Trust Closed | Not Operating/Dissolved | Withdrawn | Undetermined | Enforcement Action Pending | Undetermined | Not Registered | Yes | Current - Awaiting Reporting | Yes | Current - In Process | Yes | Current - Probationary Registration | Yes | Current - Reporting Incomplete | Yes | Current | Yes | Exempt - Facility Financing | Yes | Exempt - Form 990-PF Required | Yes | Exempt - Religious | Yes | Exempt | Yes | Registered - Corporate Trustee | ### Franchise Tax Board (FTB) The `franchise_tax_board` object contains information regarding an organization's standing with the California Franchise Tax Board. The ``` ftb_revocation_status ``` field is a Boolean value indicting whether an organization's tax-exempt status has been revoked by Franchise Tax Board. If ``` "ftb_revocation_status": true ``` , the ``` ftb_revocation_status_date ``` field will list the date the organization's tax-exempt status was revoked. Below are sample responses that provide example of organizations with various different statuses in California. Key fields to validate each scenario are marked "/see here/". ``` { "code": 200, "message": "Request was processed successfully!", "took": 355, "errors": [], "data": { "ein": "20-0307526", "california_entity_id": "2560233", "organization_name": "<NAME>", "city": "SANTA MONICA", "state": "CA", "attorney_general": { /*see here*/"ag_may_operate_or_solicit_in_ca": "No", "ag_registry_status": "Revoked", "ag_state_charity_reg_num": "123602", "ag_issue_date": "12/31/2005 12:00:00 AM", "ag_last_renewal_date": "5/6/2009 12:00:00 AM", "ag_status_set_date": "2/3/2022 12:00:00 AM", "ag_as_of_date": "6/21/2023 12:00:00 AM", "ag_source_data_conflict": false, "ag_source_data_conflict_date": "", "most_recent_ag": "6/21/2023 12:00:00 AM" }, "franchise_tax_board": { /*see here*/"ftb_revocation_status": true, "ftb_revocation_status_date": "6/1/2011 12:00:00 AM", "most_recent_ftb": "6/13/2023 12:00:00 AM", "ftb_source_data_conflict": false, "ftb_source_data_conflict_date": "" } } } ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 717, "errors": [], "data": { "ein": "33-0841281", "california_entity_id": "2133191", "organization_name": "PANCREATIC CANCER ACTION NETWORK INC.", "city": "MANHATTAN BEACH", "state": "CA", "attorney_general": { /*see here*/"ag_may_operate_or_solicit_in_ca": "Yes", "ag_registry_status": "Current", "ag_state_charity_reg_num": "114088", "ag_issue_date": "6/30/2006 12:00:00 AM", "ag_last_renewal_date": "1/3/2023 12:00:00 AM", "ag_status_set_date": "1/3/2023 12:00:00 AM", "ag_as_of_date": "6/21/2023 12:00:00 AM", "ag_source_data_conflict": false, "ag_source_data_conflict_date": "", "most_recent_ag": "6/21/2023 12:00:00 AM" }, "franchise_tax_board": { /*see here*/"ftb_revocation_status": false, "ftb_revocation_status_date": "", "most_recent_ftb": "", "ftb_source_data_conflict": false, "ftb_source_data_conflict_date": "" } } } ``` ### Example organization not registered in California Organizations that are not operating or fundraising in California are not required to register in California. If the organization has no status in California, a 404 error will be returned, indicating that no California data is present. ``` { "code": 404, "message": "Request was processed successfully but we could not find the resource, 85-2814738", "took": 13, "errors": [] } ``` ### Example organization not located in California, but prohibited from operating/soliciting in California Organizations that are not located in California can be prohibited from operating and soliciting in California. ``` { "code": 200, "message": "Request was processed successfully!", "took": 191, "errors": [], "data": { "ein": "91-1303277", "california_entity_id": "1968784", "organization_name": "THE <NAME>YAN ASSOCIATION", "city": "RENTON", "state": "WA", "attorney_general": { /*see here*/"ag_may_operate_or_solicit_in_ca": "No", "ag_registry_status": "Revoked", "ag_state_charity_reg_num": "132205", "ag_issue_date": "12/31/2005 12:00:00 AM", "ag_last_renewal_date": "6/22/2010 12:00:00 AM", "ag_status_set_date": "2/3/2022 12:00:00 AM", "ag_as_of_date": "6/21/2023 12:00:00 AM", "ag_source_data_conflict": false, "ag_source_data_conflict_date": "", "most_recent_ag": "6/21/2023 12:00:00 AM" }, "franchise_tax_board": { "ftb_revocation_status": false, "ftb_revocation_status_date": "", "most_recent_ftb": "", "ftb_source_data_conflict": false, "ftb_source_data_conflict_date": "" } } } ``` ## Source data conflicts Occasionally a nonprofit notifies Candid that their status with the AG or FTB has been updated since the last file posting. If the organization is able to provide documentation of their updated status, that will be noted in the ``` ag_source_data_conflict ``` ``` ftb_source_data_conflict ``` field, respectively. The date the conflict was identified is recorded in the ``` ag_source_data_conflict_date ``` ``` ftb_source_data_conflict_date ``` field, and the applicable status fields will be updated to the correct values. Updated 4 days ago Add demographic data to nonprofit records, and keep this data up to date with the latest information refreshed on demand or automatically. * Streamline your application processes and participate in sector-wide efficiencies to reduce grantee burden while gaining access to incredibly detailed, insightful, and actionable data. * Automatically append demographic data as new grant applications are submitted. * Make fully informed grant decisions on the completeness of data directly in your systems. * Create powerful, data-driven reports and analysis on the impact of your grantmaking and the composition of your grantmaking portfolio. * Demographics API Use an EIN in the path parameter to get nonprofit demographic information. ## User guides * Organizational demographic data An overview of organizational demographic data and how to use it. * Demographic data for grantmaking Guidance for grantmakers on implementing demographic data. ## Getting access Request a free trial today. Date: 2023-04-05 Categories: Tags: To better understand the demographic identities of those working in the nonprofit sector and reduce the reporting burden on nonprofits, Candid collects and shares demographic data about staff and board members from a growing number of U.S. nonprofits and foundations. This data is accessible in the Premier API and Demographics API. ## Data collection Nonprofits are eligible to submit demographic data about their staff and board via their Candid profile. This overview describes how nonprofits can get started in sharing their demographic data. See here for Candid’s official guidance for nonprofits on how to collect demographic data from their staff and here for guidance on how to share this data with Candid through an organization’s profile. Organizations are encouraged to update their demographic data on an annual basis, and demographic data represents organizations’ most recent demographic data. Candid invites organizations to share information about each of the following demographic categories: Data for the above categories is collected at the following staffing levels: * Leader/ Co-Leader * Board Members * Senior Staff * Staff Nonprofits are asked to report individual level data for leaders and co-leaders (e.g., CEO’s race, gender, etc.), and aggregate demographic information for other staffing levels (e.g., 4 Black board members, 5 white board members, 2 Asian board members). Organizations can share information for some or all of these categories and staffing levels. ## Demographics status messages Whether or not an organization has shared demographic information will be flagged in the demographics_status and demographics_status_nonprofit fields. See the table below for possible values and intended end users for these messages. Field | End User | Message if demographics data is submitted | Message if demographics data is not submitted | | --- | --- | --- | --- | | Foundation or Individual Donor | This organization has provided Candid demographics data on MM/dd/yyyy. | This organization has not provided Candid demographics data. Please encourage the nonprofit to complete their Candid profile by visiting https://www.guidestar.org/UpdateNonprofitProfile. | | Nonprofit | Your organization has provided Candid demographics data on MM/dd/yyyy. | Your organization has not provided Candid demographics data. Please complete your Candid profile by visiting https://www.guidestar.org/UpdateNonprofitProfile. | Status messages when the organization has submitted demographic data will include the date the information was shared, which is also available in the `date_last_modified` field. ## Data structure * `staff_level_totals` : object containing the total number of individuals within each personnel group at the organization * `total_board_members` : number of individuals on the board * `total_staff` : number of individuals who work at the organization, including senior staff, leader, and co-leader * `total_senior_staff` : number of senior staff (C-suite or management with budgetary oversight) who work at the organization, including the leader and co-leader * `categories` : array containing demographic information objects * `category` : represents the type of demographic information contained within the object. See below for possible values. * ``` board_members_not_collected ``` , `staff_not_collected` , ``` senior_staff_not_collected ``` : boolean (true/false) fields under category represent that the organization did not provide information for this category for the specified group * `subcategories` : array containing detailed objects related to the category. * `Subcategory` : represents the answers to the question's category for the groups working at the organization. See below for possible values. * `board_members` , `staff` , `senior_staff` : represent the total number of individuals in each group at the organization who identify within the subcategory * `reported_by_ceo` and `reported_by_coceo` : boolean (true/false) fields which indicate if the organization’s leader and co-leader identify within the subcategory. If not applicable, this field is null. Below is a sample response from the Demographics API: ``` { "code": 200, "message": "Request was processed successfully!", "took": 116, "errors": [], "data": { "summary": { "organization_name": "Candid", "ein": "13-1837418", "city": "New York City", "state": "NY", "demographics_status": "This organization has provided Candid Demographics Data on 05/04/2023", "demographics_status_nonprofit": "Your organization has provided Candid Demographics Data on 05/04/2023", "date_last_modified": "05/04/2023" }, "demographics": { "staff_level_totals": { "total_board_members": "17", "total_staff": "195", "total_senior_staff": "8" }, "categories": [ { "category": "Race & Ethnicity", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Asian/Asian American", "board_members": 1, "staff": 26, "senior_staff": 4, "reported_by_ceo": true, "reported_by_coceo": null }, { "subcategory": "Black/African American", "board_members": 4, "staff": 17, "senior_staff": 1, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Hispanic/Latino/Latina/Latinx", "board_members": 0, "staff": 13, "senior_staff": 1, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Native American/American Indian/Alaska Native/Indigenous", "board_members": 0, "staff": 0, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "White/Caucasian/European", "board_members": 8, "staff": 90, "senior_staff": 1, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Multi-Racial/Multi-Ethnic (2+ races/ethnicities)", "board_members": 1, "staff": 7, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Decline to state", "board_members": null, "staff": 11, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Unknown", "board_members": 2, "staff": 31, "senior_staff": 1, "reported_by_ceo": null, "reported_by_coceo": null }, { "subcategory": "Middle Eastern/Northern African", "board_members": 0, "staff": null, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null }, { "subcategory": "Native Hawaiian/Pacific Islander", "board_members": 0, "staff": null, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null } ] }, { "category": "Race & Ethnicity Other", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Other", "board_members": 1, "staff": null, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null } ] }, { "category": "Gender Identity", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Female", "board_members": 8, "staff": 94, "senior_staff": 3, "reported_by_ceo": true, "reported_by_coceo": null }, { "subcategory": "Male", "board_members": 7, "staff": 57, "senior_staff": 5, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Non-binary", "board_members": null, "staff": 6, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Decline to state", "board_members": null, "staff": 9, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Unknown", "board_members": 2, "staff": 29, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null } ] }, { "category": "Gender Identity 2", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Transgender", "board_members": 0, "staff": 2, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Not transgender (cisgender)", "board_members": 14, "staff": 144, "senior_staff": 8, "reported_by_ceo": true, "reported_by_coceo": null }, { "subcategory": "Decline to state", "board_members": 1, "staff": 15, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Unknown", "board_members": 2, "staff": 34, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null } ] }, { "category": "Sexual Orientation", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Gay, lesbian, bisexual, or other sexual orientations in the LGBTQIA+ community", "board_members": null, "staff": 23, "senior_staff": 2, "reported_by_ceo": true, "reported_by_coceo": null }, { "subcategory": "Heterosexual or straight", "board_members": 14, "staff": 129, "senior_staff": 6, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Decline to state", "board_members": 1, "staff": 14, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Unknown", "board_members": 2, "staff": 29, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null } ] }, { "category": "Disability Status", "board_members_not_collected": false, "staff_not_collected": false, "senior_staff_not_collected": false, "subcategories": [ { "subcategory": "Person with a disability", "board_members": null, "staff": 21, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Person without a disability", "board_members": 15, "staff": 129, "senior_staff": 8, "reported_by_ceo": true, "reported_by_coceo": null }, { "subcategory": "Decline to state", "board_members": null, "staff": 12, "senior_staff": null, "reported_by_ceo": false, "reported_by_coceo": null }, { "subcategory": "Unknown", "board_members": 2, "staff": 33, "senior_staff": null, "reported_by_ceo": null, "reported_by_coceo": null } ] } ] } } } ``` ## Demographic categories and subcategories Listed below are possible response values for the category and subcategory fields: Category | Subcategories | Notes | | --- | --- | --- | Race & Ethnicity | - Asian/Asian American | Race & Ethnicity Other | Write-in answers | Each subcategory represents a write-in answer to "Prefer to identify with another race." | Gender Identity | - Female | Gender Identity 2 | - Transgender | Sexual orientation | - Heterosexual or straight | Disability Status | - Person with a disability | For more information on how to use organizational demographic data for grantmaking, review this user guide: * Build dynamic filtering capabilities to help users find causes that matter most to them. * Harness Candid's up to date taxonomy to enable users to explore the nonprofit sector. * Use GraphQL to get exactly the data you need in one API call. * Combine with other Candid APIs to create a robust nonprofit data system. ## GraphQL Candid's Taxonomy API is built using GraphQL. GraphQL APIs work differently than REST APIs by allowing you to select the data returned by each query. For more information about working with GraphQL, please see the Overview of GraphQL guide. ## PCS Taxonomy The Philanthropy Classification System (PCS) is Candid's taxonomy, describing the activities of the philanthropic sector. Candid's PCS is based on the National Taxonomy of Exempt Entities (NTEE) and has been expanded over the last three decades to include the emerging work we have evidenced while capturing and indexing the work of the sector on a global scale. PCS classifies philanthropy activities under five facets: Subject, Population, Organization Type, Transaction Type, and Support Strategy. ### PCS Subject Codes Subject codes describe the core activities and services of an organization, often referred to as cause area. Examples include elementary education or clean water supply. ### PCS Population Codes Population codes describe the population served or impacted by a nonprofit's work. Examples include girls or people with disabilities. More information about the PCS can be found at taxonomy.candid.org. ## API Reference * Candid Taxonomy API Utilize Candid's Philanthropy Classification System taxonomy. * For donation platforms: * Create front-end menus to help users identify nonprofits working in cause areas of interest * For funders: * Leverage taxonomy codes when generating grant opportunities * For nonprofits: * Define work using taxonomy codes to help find funders and donations ## Using Taxonomy API with other Candid APIs Taxonomy API can be combined with Candid's Essentials, Grants, and News APIs to create a robust nonprofit data system. Taxonomy API can be used to build an interactive front end experience for end users, allowing them to select the taxonomy code that best encapsulates what they are looking for. On the back end, the selected code can be passed into the Essentials, Grants, or News APIs to identify relevant organizations, grants, or news articles. ## Translating NTEE codes to PCS codes The nteeMinor query returns an object called pcsCrosswalk. This provides the PCS code values and names that correspond with the searched NTEE code (where an equivalent value is available). This can be used to easily update systems that utilize the NTEE taxonomy to take advantage of the freshness and specificity of the PCS taxonomy. ## Other taxonomies Taxonomy API also includes access to the following IRS taxonomies: * NTEE Major * NTEE Minor * Filing Type * Subsection Code * Foundation Type * MSA Code Candid’s Taxonomy API is built using GraphQL. GraphQL is a powerful query language for APIs, and has several notable benefits: * Returns exactly the data as you’re interested in. * Reduces the number of requests to get to the data you need. * Predictable results - provides data in the same structure as it is requested. GraphQL resources For more resources, visit GraphQL’s Introduction to GraphQL. ### Operations GraphQL supports several operation types (queries, mutations, and subscriptions). Candid's Taxonomy API makes use of queries only. ### Queries Queries are used to fetch data. Users can specify which fields will be returned by a query, and the resulting data will be returned in the same structure as the query. ### Arguments Arguments can be passed into fields and used to filter or transform the resulting data. For example, the following example is a query ( `termsByFacet` ) that will return PCS terms, using an argument ( `facet: SUBJECT` ) to limit results to the Subject facet only. The fields `code` and `name` will be returned for each result. ``` query { termsByFacet (facet: SUBJECT) { data { code name } } } ``` ### Multiple Queries More than one query can be included in a single call to the API. ### Aliases Aliases can be used to rename a field in the result. This is especially helpful when multiple queries are being used, since argument values are not returned in the results. For example, the following queries will return all PCS terms in the Subject facet ( ``` termsByFacet(facet: SUBJECT) ``` ), as well as all PCS terms in the Population facet ( ``` termsByFacet(facet: POPULATION) ``` ). To differentiate the results of each query, the aliases `subjectTerms` and `populationTerms` have been used. ``` query { subjectTerms: termsByFacet(facet: SUBJECT) { data { code name } } populationTerms: termsByFacet(facet: POPULATION) { data { code name } } } ``` ### Fragments When the same set of fields is repeated multiple times in a query, it can be helpful to utilize fragments, which are reusable collections of fields. The below example replaces the fields `code` and `name` , which are repeated in the example above, with the fragment `codeFields` , which can then be referenced in queries. ``` query { subjectTerms: termsByFacet(facet: SUBJECT) { data { ...codeFields } } populationTerms: termsByFacet(facet: POPULATION) { data { ...codeFields } } } fragment codeFields on Term { code name } ``` Updated 7 months ago Find sample Taxonomy API searches: Calling Taxonomy GraphQL API The Taxonomy GraphQL API can be called using a POST call to the URL ``` https://api.candid.org/taxonomy/graphql/ ``` . Requests must be authenticated via HTTP Header by passing the subscription key within Subscription-Key. The search query can be created by using the built-in query generator on the Taxonomy API docs page. ## Search by PCS term name Return PCS codes that exactly match the searched name (e.g. "children and youth") within a given facet (e.g. population). This search includes the parent of the code, as well as up to three possible levels of child codes. ``` query { termsByName(pcsNames:[{facet: POPULATION, name: "children and youth"}]) { meta { code message resultsCount took } data { ...term parents{ ...term } children{ ...term children{ ...term children{ ...term } } } } } } ``` { "data": { "termsByName": { "meta": { "code": 200, "message": "Success", "resultsCount": 1, "took": 643 }, "data": [ { "code": "PA010000", "name": "Children and youth", "description": "Young people from birth to 18 years of age.", "facet": "POPULATION", "depth": 1, "hasChildren": true, "parents": [ { "code": "PA000000", "name": "Age groups", "description": "People categorized by age. The age ranges provided are the ones considered by Foundation Center to be fairly common and sensible ranges associated with each term, but other organizations associate quite different ranges with some of the terms.", "facet": "POPULATION", "depth": 0, "hasChildren": true } ], "children": [ { "code": "PA010400", "name": "Adolescents", "description": "Young people from 13 to 18 years of age.", "facet": "POPULATION", "depth": 2, "hasChildren": false, "children": [] }, { "code": "PA010200", "name": "Children", "description": "Young people from 3 to 9 years of age.", "facet": "POPULATION", "depth": 2, "hasChildren": false, "children": [] }, { "code": "PA010100", "name": "<NAME>", "description": "Young people from birth to 2 years of age.", "facet": "POPULATION", "depth": 2, "hasChildren": false, "children": [] }, { "code": "PA010300", "name": "Preteens", "description": "Young people from 10 to 12 years of age.", "facet": "POPULATION", "depth": 2, "hasChildren": false, "children": [] } ] } ] } } } ``` ## Search by PCS code Return PCS codes based on the alphanumeric code (e.g. "SE000000") within a given facet (e.g. subject). This search includes the parent of the code, as well as up to three possible levels of child codes. ``` query { termsByCode (pcsCodes:[{code:"SE000000", facet: SUBJECT}]) { meta { code message resultsCount took } data { ...term parents{ ...term } children{ ...term children{ ...term children{ ...term } } } } } } ``` { "data": { "termsByCode": { "meta": { "code": 200, "message": "Success", "resultsCount": 1, "took": 859 }, "data": [ { "code": "SE000000", "name": "Health", "description": "Promotion and protection of the physical and mental well-being of people through medical care and treatment; assessment and amelioration of social, environmental, and biomedical factors affecting that well-being; research into various diseases and in various disciplines; and education and prevention activities that increase people's own efforts at protecting public health.", "facet": "SUBJECT", "depth": 0, "hasChildren": true, "parents": [], "children": [ { "code": "SE150000", "name": "Diseases and conditions", "description": "Service, education and research related to a particular disease, condition or disability, or group of diseases, conditions or disabilities. Also included are support agencies and programs active in the prevention or treatment of diseases and disorders.", "facet": "SUBJECT", "depth": 1, "hasChildren": true, "children": [ { "code": "SE150200", "name": "Brain and nervous system disorders", "description": "Programs of service, education and research on prevention or treatment of diseases or conditions, including brain injuries, that affect the brain. For organizations representing neurologists or others in the neurosciences, use Neurology.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE150202", "name": "ALS", "description": "Amyotrophic lateral sclerosis (ALS), often referred to as Lou Gehrig's disease, is a progressive neurodegenerative disease that affects nerve cells in the brain and the spinal cord. Motor neurons reach from the brain to the spinal cord and from the spinal cord to the muscles throughout the body.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150201", "name": "Alzheimer's Disease and other forms of dementia", "description": "Programs of service, education and research on prevention or treatment of Alzheimer's disease or other forms of dementia.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150203", "name": "Autism", "description": "Programs of service, education and research on prevention or treatment of autism, a developmental disability, usually evident by age three, which affects a child's ability to communicate, understand language, play and relate to others.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150204", "name": "Cerebral palsy", "description": "Programs of service, education and research on prevention or treatment of cerebral palsy, a central nervous system impairment that is characterized by an inability to fully control motor function.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150205", "name": "Epilepsy", "description": "Programs of service, education and research on prevention or treatment of epilepsy, a recurrent paroxysmal disorder of cerebral function that is characterized by sudden brief interruptions in or complete loss of consciousness, motor activity and/or sensory phenomena.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150209", "name": "Meningitis", "description": "Programs of service, education and research on prevention and treatment of Meningitis, a potentially fatal inflammation of the protective membranes covering the brain and spinal cord.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150206", "name": "Multiple sclerosis", "description": "Programs of service, education and research on prevention or treatment of multiple sclerosis and other related conditions affecting the central nervous system.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150208", "name": "Parkinson's disease", "description": "Programs of service, education and research on prevention or treatment of Parkinson's Disease, a chronic progressive nervous disease chiefly of later life that is marked by tremor and weakness of resting muscles.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150207", "name": "Spinal cord injuries and diseases", "description": "Programs of service, education and research on prevention or treatment of diseases or disorders affecting the spinal cord and its associated nerves.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE151500", "name": "Cancers", "description": "Programs of service, education and research on prevention or treatment of cancer. Use this term to indicate a wide variety of forms of cancer, or forms of cancer other than leukemia. The associated medical specialty is medical oncology, a subspecialty of internal medicine.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE151501", "name": "Breast cancer", "description": "Prevention or treatment of cancer of the breast.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151506", "name": "Colorectal cancer", "description": "A digestive system cancer that starts in the colon or the rectum. Colon cancer and rectal cancer have many features in common. Symptoms may include blood in the stool, changes in bowel movements, weight loss, and chronic fatigue. Most colorectal cancers develop due to aging and/or lifestyle factors, with a much smaller number of cases due to inherited genetic disorders. Diagnosis may be obtained through colonoscopy or sigmoidoscopy. Use For: Colon cancer; Rectal cancer; Bowel cancer; Intestinal cancer. For Anal cancer, use Cancer.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151502", "name": "Leukemia", "description": "Programs of service, education and research on prevention or treatment of leukemia, a form of cancer that affects the white blood cells.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151505", "name": "Lung cancer", "description": "Lung cancer is a malignant lung tumor characterized by uncontrolled cell growth in tissues of the lung. Left untreated, the growth will spread beyond the lung by process of metastasis into nearby tissue or other parts of the body. Use For: Pulmonary carcinoma; Carcinoma of the lung; Lung carcinoma; Small-cell lung carcinoma; Non-small-cell lung carcinoma; Lung carcinoid tumors; Bronchogenic carcinoma.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151503", "name": "Pancreatic cancer", "description": "Prevention or treatment of cancer of the pancreas.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151504", "name": "Prostate cancer", "description": "Prevention or treatment of cancer of the prostate (specific to males).", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE150300", "name": "Digestive system diseases", "description": "Programs of service, education and research on prevention or treatment of diseases and conditions such as abdominal pain, ulcers, diarrhea, cancer or jaundice that affect the digestive system including the stomach, bowels, liver, gallbladder and related organs. The related medical specialty is gastroenterology, a subspecialty of internal medicine.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE150301", "name": "Celiac disease", "description": "Prevention or treatment of Celiac disease, an autoimmune disorder of the small intestine in genetically predisposed people, which is caused by a reaction to gliadin (a gluten protein found in wheat and grains).", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150302", "name": "Crohn's disease and colitis", "description": "Prevention or treatment of Crohn's disease, a type of chronic inflammatory bowel disease that may affect any part of the gastrointestinal tract from mouth to anus. Crohn's disease also cause complications such as anemia, skin rashes, arthritis and fatigue. Treatments include modifying lifestyle, medications and surgery. Colitis is an inflammation of the colon that can be chronic or acute.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150303", "name": "Irritable bowel syndrome", "description": "Prevention or treatment of Irritable Bowel Syndrome (IBS), a functional gastrointestinal (GI) disorder. IBS is a symptom based diagnosis characterized by chronic abdominal pain, discomfort, bloating and changes of bowel habits. Treatments to relieve symptoms include dietary adjustments, medication and psychological interventions.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150304", "name": "Liver diseases", "description": "Programs of service, education and research on prevention or treatment of diseases or conditions that affect the liver.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE150400", "name": "Ear, nose and throat diseases", "description": "Programs of service, education and research on prevention or treatment of diseases or conditions that affect the head and neck including the ears, the respiratory and upper alimentary systems, the face, the jaws and related structures. The related medical specialty is otolaryngology.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE150600", "name": "Endocrine, nutritional and metabolic diseases", "description": "Prevention or treatment of disorders of the endocrine system, metabolic disorders (such as diabetes) and nutritional disorders.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE150601", "name": "Diabetes", "description": "Programs of service, education and research on prevention or treatment of diabetes, a disorder in which the pancreas produces too little insulin, with the result that the body is unable to adequately metabolize sugar.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150602", "name": "Malnutrition", "description": "Prevention or treatment of conditions caused by a lack of essential nutrition due to disease, or dietary deprivation or over-abundance. Malnutrition is of special importance in pregnant women, children and the elderly.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE150500", "name": "Eye diseases", "description": "Programs of service, education and research on prevention or treatment of blindness and diseases or other conditions that affect the eyes. The associated medical specialty is ophthalmology. For social service organizations whose purpose is to promote the independence of blind/vision impaired people, use Special population support, and Population Group, People with vision impairments. See also Vision care.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE151400", "name": "Genetic conditions and birth defects", "description": "Programs of service, education and research on prevention or treatment of any of a number of illnesses or conditions that are hereditary and passed from parent to offspring. Use this term to indicate a wide variety of genetic disorders or on genetic disorders not broken out at a lower level.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE151401", "name": "Cystic fibrosis", "description": "Programs of service, education and research on prevention or treatment of cystic fibrosis, a hereditary disease that affects the pancreas, respiratory system, and sweat glands.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151402", "name": "Down syndrome", "description": "Programs of service, education and research on prevention or treatment of Down Syndrome, a hereditary condition that results in mental retardation.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151403", "name": "Hemophilia", "description": "Programs of service, education and research on prevention or treatment of hemophilia, a hereditary blood disease that is characterized by greatly prolonged coagulation time.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE150700", "name": "Heart and circulatory system diseases", "description": "Programs of service, education and research on prevention or treatment of diseases or conditions, including stroke, that affect the heart, lungs and blood vessels. The related medical specialty is cardiovascular medicine, a subspecialty of internal medicine.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE150800", "name": "Immune system diseases", "description": "Prevention or treatment of diseases of the immune system that cause abnormally low or high activity of the immune system.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE150801", "name": "HIV/AIDS", "description": "Programs of service, education and research on prevention or treatment of AIDS, a disease that impairs the functioning of the body's immune system, leaving affected individuals vulnerable to illnesses that would not otherwise occur. See Also: People with HIV/AIDS (Population Group).", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE151000", "name": "Infectious and parasitic diseases", "description": "Programs of service, education and research on prevention or treatment of diseases and disorders that are vector- or food-borne or transmitted from person to person; or that are caused by organisms like protozoa, worms, lice, fleas, ticks or other parasites that live within, upon or at the expense of the affected individual. See also Communicable disease control.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE151001", "name": "Cholera", "description": "Prevention or treatment of Cholera, an infection of the small intestine caused by bacterium Vibrio cholerae that is primarily transmitted via contaminated drinking water. Prevention of Cholera epidemics can include the administration of oral vaccines to create herd immunity within a population.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151004", "name": "Ebola", "description": "Prevention, research and treatment of an infectious and generally fatal disease marked by fever and severe internal bleeding, spread through contact with infected body fluids by a filovirus (Ebola virus). Typically occurs in West Africa, and tropical regions of Sub-Saharan Africa.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151002", "name": "Malaria", "description": "Prevention or treatment of Malaria, a mosquito-borne infectious disease that is prevalent in the tropical and subtropical regions. Malaria is caused by parasitic protozoans that travel through the blood to the liver, where they reproduce and can cause symptoms such as headaches and fever, sometimes leading to coma and death.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151003", "name": "Tuberculosis", "description": "Prevention and treatment of Tuberculosis (TB), a common and often lethal infectious disease that typically attacks the lungs (but can also be extra-pulmonary). Tuberculosis is caused by various strains of mycobacteria and is treated using antibiotics.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE150900", "name": "Kidney diseases", "description": "Programs of service, education and research on prevention or treatment of diseases or conditions that affect the kidneys. The related medical specialty is nephrology, a subspecialty of internal medicine.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE151100", "name": "Mental and behavioral disorders", "description": "Preventive, diagnostic and treatment activities that focus on a particular mental health disorder. Use this term for programs that focus on disorders not broken out at a lower level or which deal with a multiplicity of disorders. Includes: Attention deficit/hyperactivity disorder (though this may be considered a neurological impairment and belong with a disability listing); Avoidant disorder of childhood/adolescence; Conduct disorders; Conversion disorder; Depersonalization disorder; Elective mutism; Identity disorder; Intermittent explosive disorder; Kleptomania; Multiple personalities; Obsessive-compulsive disorders; Oppositional disorder; Overanxious disorder; Panic disorders; Paranoid disorders; Personality disorders (there are many); Phobias; Psychogenic amnesia; Psychogenic fugue; Psychogenic pain disorder; Pyromania; Separation anxiety disorder; Sexual disorders (exhibitionism, fetishism, pedophilia, sexual/psychosexual dysfunction, sexual masochism, sexual sadism, voyeurism and zoophilia); and Somatization disorder.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE151101", "name": "Alcoholism", "description": "Programs of service, education and research on prevention or treatment of alcoholism, a chronic, progressively disabling and potentially fatal disease that is characterized by increased tolerance, physical dependence and pathological organ changes which are a result of alcohol consumption. Use this for Fetal alcohol syndrome; see also Substance abuse prevention and treatment.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151102", "name": "Depression", "description": "Preventive, diagnostic and treatment activities that focus on individuals who have mental health disorders involving depression including bipolar disorder (manic-depression), cyclothymic disorder, major depression, postpartum depression, and seasonal affective disorder syndrome (SADS).", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151103", "name": "Learning disorders", "description": "Activities of voluntary health organizations, support agencies and programs to prevent or treat learning disabilities, disorders of one or more of the basic psychological processes which are involved in understanding or using spoken or written language. These disorders may manifest themselves in an impaired ability to listen, think, read, write, spell or perform mathematical calculations.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151104", "name": "Stress", "description": "Preventive, diagnostic and treatment activities that focus on individuals who have stress-related disorders such as post-traumatic stress syndrome.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE150100", "name": "Musculoskeletal diseases", "description": "Programs of service, education and research on prevention or treatment of diseases or conditions that affect the nerves, muscles or bones. Use this term for projects that focus on a wide variety of nerve, muscle and bone diseases or those not broken out at a lower level. The related medical specialty is orthopedic surgery. For organizations representing orthopedic surgeons, use Orthopedics.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE150101", "name": "Arthritis", "description": "Programs of service, education and research on prevention or treatment of arthritis (including osteoarthritis and rheumatoid arthritis), an inflammatory condition affecting the joints. The related medical specialty is rheumatology, a subspecialty of internal medicine, though rheumatology is broader and covers more conditions than arthritis.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE150102", "name": "Muscular dystrophy", "description": "Programs of service, education and research on prevention or treatment of muscular dystrophy, a familial disease that is characterized by absence of muscular development, first affecting the lower extremities. See also Genetic conditions and birth defects.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE151200", "name": "Respiratory system diseases", "description": "Programs of service, education and research on prevention or treatment of diseases or conditions that affect the lungs. The related medical specialty is pulmonary disease specialists.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE151201", "name": "Asthma", "description": "Programs of service, education and research on prevention or treatment of asthma, a disorder of the bronchial system that is characterized by labored breathing and wheezing.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151202", "name": "Chronic obstructive pulmonary disease", "description": "Prevention or treatment of a lung disease that is defined by persistently inadequate airflow, which is due to the breakdown of lung tissue and dysfunction of the small airways.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE151203", "name": "Pneumoconiosis", "description": "Prevention or treatment of Pneumoconiosis, a restrictive lung disease that is an occupational disease caused by the inhalation of dust in the workplace. Pneumoconiosis leads to chronic shortness of breath. Pneumoconiosis can be given various names according to the type of dust that workers have inhaled. It is most common in miners and other workers exposed to particulates in the air due to their occupation.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE151300", "name": "Skin conditions", "description": "Programs of service, education and research on prevention or treatment of diseases or conditions that affect the skin. The related medical specialty is dermatology.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] } ] }, { "code": "SE020000", "name": "Health care access", "description": "The ready availability of affordable, quality health and medical care, especially for those in remote areas (rural areas, Indian/Native American reservations, underserved urban areas and other locations without adequate health care services), those with language barriers (culturally sensitive health care) and those who cannot afford to pay for adequate care. Use For: Health care parity; Right to health care; Patient access; Health care expansion; Culturally-sensitive health care.", "facet": "SUBJECT", "depth": 1, "hasChildren": false, "children": [] }, { "code": "SE030000", "name": "Health care administration and financing", "description": "The administration and management of health and medical care through insurance, other financing activities, technical assistance, services to patients and their families, and the study and practice of ethical behavior in medical care and research.", "facet": "SUBJECT", "depth": 1, "hasChildren": true, "children": [ { "code": "SE030100", "name": "Bioethics", "description": "Programs that promote the study or teaching of ethical issues involved in the practice of medicine or research including right-to-die issues, end-of-life decision-making, access to lifesaving procedures for people who are terminally ill, transplant ethics, implications of recent developments in genetic testing and genetic manipulation in humans, cloning and utilization of animals for research purposes. For efforts to influence public opinion or public policy on medical issues related to the civil liberties of individuals, it may be more appropriate to use Individual liberties; Right to die; Reproductive rights; Right to life; or Patients' rights.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE030200", "name": "Electronic health records", "description": "Health records in a digital format and/or a digital information system for storing, sharing and retrieving digital health records. Includes system creation and maintenance, as well as issues related to personal privacy and system security. Electronic health records can be used for research purposes as source of anonymous data.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE030300", "name": "Health care financing", "description": "Activities that address the financing of health care other than health insurance or managed care, and efforts to contain the cost of health care.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE030400", "name": "Health care management", "description": "The leadership, management and administration of public and private health care systems, hospitals, hospital networks, and clinics. This includes the physical functioning and administration of institutions and networks, as well issues related to shaping public policy and best practices within institutions and networks.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE030500", "name": "Health insurance", "description": "Policies and programs which indemnify or reimburse policy holders for all or a portion of the cost of hospital or medical care or for lost income arising from an illness or injury. Includes dental insurance, hazardous occupations benefits, indemnity health plans, Medicare insurance supplements, long-term care insurance, and private disability insurance.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE030600", "name": "Managed care", "description": "A health care system or approach in which patients agree to visit only certain doctors and hospitals, and in which the cost of treatment is monitored and influenced by a managing company, i.e. a healthcare plan or system that seeks to control medical costs by contracting with a network of providers, requiring preauthorization for visits to specialists, and other strategies. Use For: HMOs (Health Maintenance Organizations), PPOs (Preferred Provider Organizations), ACOs (Accountable Care Organizations), MCOs (Managed Care Organizations), MSAs (Medical Savings Accounts), PSOs (Point of Service Organizations), PFFS (Private Fee for Service), and other forms of networked health care.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE031000", "name": "Medical counseling", "description": "Therapeutic counseling in support of patients undergoing treatment for diseases and patients experiencing illness, eases distress and provides spiritual and emotional support in coping with side effects, including insomnia, fatigue and pain, while helping patient to understand personal reactions to treatment.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE030800", "name": "Patient social services", "description": "Programs that provide social and recreational activities for people who are recovering from surgery or a serious illness to help them gain confidence and readjust to living and/or working in the community. Also included are programs that provide supportive services for children who are ill and for their families which enable family members to remain with a child who is hospitalized or which attempt to make a gravely or terminally ill child's final days, weeks and months more pleasant. Includes Make-a-Wish groups and patient/family housing programs such as Ronald McDonald House.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE030700", "name": "Patient-centered care", "description": "Health care services that assist patients and their families to navigate the health care system and allow them to take charge of their care and how it is to be administered. Included are assistance to develop written goals and objectives that relate to a recommended therapeutic regimen, medical procedures and self-care. Also included are medical social work services for patients and families during hospitalization and discharge which offer consultation and coordination of available services for the patient's continuing care at home or in a short- or long-term care facility.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE030900", "name": "Patients' rights", "description": "Work for passage and enforcement of laws and other social measures that protect and promote the rights and interests of patients of the health and medical care system.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] } ] }, { "code": "SE010000", "name": "Health care quality", "description": "Health care quality is receiving the best possible care for an illness or condition including the avoidance of errors/mistakes, patient safety, respectful treatment by health care professionals and clear answers to questions about treatment. Use For: HCQ, Health care improvement. See Also: Patient-Centered care", "facet": "SUBJECT", "depth": 1, "hasChildren": false, "children": [] }, { "code": "SE100000", "name": "Holistic medicine", "description": "A medical specialty and health care strategy that works to integrate the physical, mental, emotional, social and spiritual aspects of health, and focuses on education and responsibility for personal efforts to achieve balance and well-being. The term Alternative medicine is often used by the general public and some healthcare practitioners to refer to medical techniques which are not known or accepted by the majority of conventional or allopathic medical practitioners. Such techniques include non-invasive, non-pharmaceutical techniques such as Medical herbalism, Acupuncture, Homeopathy, Reiki, and many others. Alternative medicine can also refer to any experimental drug or non-drug technique that is not currently accepted by conventional medical practitioners. Most practitioners prefer the term Complementary medicine, which implies that these modalities should not be an alternative to, but rather an enhancement of conventional medicine. Other examples of alternative health care include: Acupressure; Biofeedback; Chiropractic; Herbal medicine; Iridology; Osteopathy; Reflexology; Spiritual healing (e.g., Christian Science practitioners); and Vitamin therapy.", "facet": "SUBJECT", "depth": 1, "hasChildren": false, "children": [] }, { "code": "SE040000", "name": "In-patient medical care", "description": "The prevention and treatment of mental and physical disorders and disease by medical professionals and the facilities and organizations that provide access to prevention and treatment of these diseases and disorders.", "facet": "SUBJECT", "depth": 1, "hasChildren": true, "children": [ { "code": "SE040100", "name": "Burn care", "description": "Special facilities or services for people who have received second- and third-degree burns to exterior services of the body or to the respiratory tract that were caused by fire or excessive heat, flash explosions, hot steam or water, chemicals, electricity or radioactive substances or heat. Burn centers utilize a variety of equipment, including sterilized rooms which have specially purified air to prevent infection, special beds and mattresses, heat shields rather than blankets and hyperbaric oxygen chambers which use concentrated oxygen to speed healing and prevent infection.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE040200", "name": "Community health care", "description": "The provision of health care services through a variety of programs and facilities in the same community or region, often by management corporations and other entities that own and manage at least one, but typically multiple, hospitals or medical facilities.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE040300", "name": "Convalescent care", "description": "Nursing and personal care provided over an extended period of time (usually more than thirty days) for people who require a level of care less than that provided in an acute facility, and/or for chronically or disabled individuals. Includes intermediate care facilities, skilled nursing facilities and subacute care nursing facilities. Includes care for patients recovering from illness or medical procedures who have been discharged from hospital but need additional assistance or supervision before returning home. For residential nursing care for the elderly, use Nursing homes.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE040400", "name": "Hospital care", "description": "Health care services and facilities that are licensed to operate twenty-four hours per day and offer diagnostic and treatment services as well as emergency and critical care services for people who have any of a variety of illnesses or injuries which require immediate, short-term intervention.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE040404", "name": "Children's hospital care", "description": "Care provided in hospitals that provide treatment specifically for children and that specialize in the prevention and treatment of childhood diseases and disorders.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE040401", "name": "Emergency care", "description": "Care provided in hospital emergency rooms, hospitals equipped for trauma care (those with trained trauma surgeons and anesthesiologists who are available on call twenty-four hours per day) and designated trauma centers which are equipped with licensed helicopter pads and trained trauma surgeons and anesthesiologists who are available in-house twenty-four hours per day. They deal with urgent, life threatening accidents and illness, both physical and mental. They are the first point of entry for medical emergencies and provide acute care, as well as performing triage and directing non-emergency medical patients to the appropriate medical department of the hospital.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE040402", "name": "Intensive care", "description": "Programs that make available lifesaving techniques and equipment to seriously ill patients who are gathered in special units or distinct parts of health care facilities and are under continuous observation by trained medical staff. Included are general intensive care units and specialized units such as cardiac intensive care and neonatal intensive care.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE040403", "name": "Specialty hospital care", "description": "Health care services or facilities like orthopedic hospitals or cancer treatment that provide diagnostic and treatment services on an inpatient basis for people who have specified medical conditions.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] } ] }, { "code": "SE140000", "name": "Medical specialties", "description": "Projects that include or represent physicians who have special training and expertise in one clinical area of practice which focuses on a specific age group (e.g., geriatrics, pediatrics), an organ system of the body (e.g., internal medicine, obstetrics/gynecology) or complex scientific techniques developed to diagnose or treat certain types of disorders (e.g., nuclear medicine, radiology). Use this term for projects that represent a wide variety of medical disciplines or those that are not broken out at a lower level. These may include: Aerospace medicine; Family practice (care for entire family unit); Nuclear medicine (therapeutic utilization of nuclear materials); Occupational medicine (occupational disease and injury); and Rheumatology (joints, muscles, bones and tendons).", "facet": "SUBJECT", "depth": 1, "hasChildren": true, "children": [ { "code": "SE140100", "name": "Biomedicine", "description": "A medical specialty that deal with the intersection of human medicine with fundamental biosciences and biotechnologies such as biochemistry, chemistry, biology, histology, genetics, embryology, anatomy, physiology, pathology, biomedical engineering, molecular medicine, zoology, botanics and microbiology. Work in this area can be used to improve the treatment and care options available to physicians.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE140200", "name": "Cardiology", "description": "A medical specialty that deals with the heart and its diseases.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE140300", "name": "Dermatology", "description": "A medical specialty that deals with the skin and its diseases,", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE140400", "name": "Diagnostic imaging", "description": "A medical specialty that deals with the therapeutic utilization of radiant energy and its modifiers in the study and management of disease. Practitioners use x-rays, MRIs, CAT scans, PET scans, and other methods of analysis and imaging of substances in vitro and in vivo for diagnosis and the administration of substances for the treatment of disease, especially malignant tumors.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE140500", "name": "Gastroenterology", "description": "A medical specialty that deals with the digestive system and its disorders. It is a subspecialty of internal medicine and includes the subspecialty of hepatology that deals specifically with the liver, pancreas and biliary tree.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE140600", "name": "Genetics", "description": "A discipline of biology that deals with the science of genes and heredity, Medical Genetics seeks to understand how genetic variation is related to health and disease, including the use of genetic markers as a diagnostic tool for the prevention and treatment of disease. Genome mapping is the creation of a genetic map that assigns DNA fragments to chromosomes, as well as identifying genetic elements that are responsible for or association with a specific disease.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE140700", "name": "Geriatrics", "description": "A medical specialty which provides preventive, diagnostic and treatment services for elderly individuals who have diseases or conditions that are associated with the aging process, and engages in the study of this process. Special assistance may include recognizing altered presentations of illnesses, dealing with multisystem organ involvement, handling special drug interactions, utilizing resources such as nursing homes and community social services, and assisting with ethical issues in the care of people who are elderly.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE140800", "name": "Hematology", "description": "A medical specialty that deals with the blood and blood-forming organs.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE140900", "name": "Immunology", "description": "A medical specialty that provides comprehensive preventive, diagnostic and treatment services for individuals who have diseases and conditions that arise as a result of malfunctioning immune systems. Immunology is a subspecialty of internal medicine.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE141000", "name": "Internal medicine", "description": "A medical specialty which provides comprehensive care for common and complex multisystem illnesses which affect the internal organs in ambulatory care as well as hospital settings. The American Board of Internal Medicine lists these subspecialties: cardiology, endocrinology, gastroenterology, hematology, infectious disease, medical oncology, nephrology, pulmonology, rheumatology, adolescent medicine, clinical cardiac electrophysiology, critical care medicine, geriatric medicine, interventional cardiology, hospital medicine, sleep medicine, sports medicine, transplant hepatology (also allergy and immunology). The American College of Osteopathic Internists also includes nuclear medicine as a subspecialty.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE141100", "name": "Neurology", "description": "A medical specialty which provides comprehensive medical management including preventive, diagnostic and treatment services for individuals who have diseases or injuries that affect the central, peripheral or autonomic nervous systems including the brain, cranial nerves, spinal cord, spinal nerves and other related structures. See also Brain and nervous system disorders.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE141200", "name": "Obstetrics and gynecology", "description": "Medical specialties that deal with childbirth and the diseases and routine physical care of the reproductive system of women.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE141300", "name": "Oncology", "description": "A medical specialty focused on the study, diagnosis and treatment of cancerous tumors. Oncology is a subspecialty of internal medicine", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE141400", "name": "Ophthalmology", "description": "A medical specialty that deals with the anatomy, physiology and diseases of the eye.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE141500", "name": "Orthopedics", "description": "A medical specialty dealing with the preservation, investigation and restoration of the form and function of the extremities, spine and associated structures by medical, surgical and physical means. Conditions treated by these orthopedic surgeons include congenital deformities, trauma, infections, tumors and metabolic disturbances of the musculoskeletal system including those that affect the spine, hands, feet, knees, hips, shoulders and elbows. Orthopedic surgery is a subspecialty of surgery.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE141600", "name": "Pathology", "description": "A medical specialty which studies changes in the structure and function of tissue and organs as a result of illness. Pathologists examine tissue removed during surgical procedures for evidence of disease and conduct postmortem examinations of cadavers to determine the cause of death.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE141700", "name": "Pediatrics", "description": "A medical specialty dealing with the biological, social and environmental factors that have an influence on a developing child and expertise in diagnosing and treating acute and chronic diseases that are common to individuals in this age range. Includes the following subspecialties: Adolescent medicine; Neonatal/perinatal medicine; Pediatric allergy; Pediatric cardiology; Pediatric endocrinology; Pediatric gastroenterology; Pediatric hematology/oncology; Pediatric immunological disorders; Pediatric infectious disease; Pediatric nephrology; Pediatric pulmonary disease; and Pediatric neurology.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE141800", "name": "Pharmacology", "description": "A medical specialty that deals with the science of drugs.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE141900", "name": "Psychiatry", "description": "A medical specialty associated with the study, diagnosis, treatment and prevention of mental disorders and physical abnormalities and injuries to the brain. This includes various affective, behavioral, cognitive and perceptual abnormalities. Psychiatry employs both pharmaceutical and behavioral and talk therapies to treat patients. Psychiatry overlaps with neurology/neuroscience, psychology, cognitive science and biochemistry.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE142000", "name": "Stem cell therapy", "description": "Projects in an intervention strategy using undifferentiated cells with the potential to develop specialized cells to treat disease or injury. Includes embryonic, fetal, adult and other types of stem cell treatments and therapeutics.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE142100", "name": "Surgery", "description": "A medical specialty which diagnoses conditions which require surgical intervention and provide preoperative, operative and postoperative care for surgical patients. The general surgeon has expertise in problems relating to the head, neck, breast, abdomen, extremities and the gastrointestinal, vascular and endocrine systems. Subspecialties include: Cardiothoracic surgery; Pediatric cardiothoracic surgery; Colon/rectal surgery; Neurosurgery; Orthopedic surgery (see Orthopedics); Pediatric orthopedics; Pediatric surgery; Plastic/reconstructive surgery; Trauma surgery; Urology and subspecialties: Gynecologic urology; and Pediatric urology; and Vascular surgery.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE142102", "name": "Organ transplantation", "description": "The use of surgery to transplant organs obtained from a living or deceased donor to a patient to restore normal or near-normal physical function.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE142101", "name": "Reconstructive surgery", "description": "The use of surgery to restore form or function of the body. Reconstructive surgery can be performed by surgeons in a wide variety of medical specialties and subspecialties, including general surgery, plastic surgery, otolaryngology, gynecology, pediatrics and podiatry.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE142200", "name": "Urology", "description": "A medical specialty that deals with the male and female urinary tract and the male reproductive organs.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] } ] }, { "code": "SE110000", "name": "Medical support services", "description": "Design and provision of equipment, services or other forms of support which are supplemental to the treatment or rehabilitation of people who have illnesses, injuries or disabilities; or which are instrumental in the prevention of illnesses, injuries or disabilities prior to their occurrence. Use this term for organizations that provide a wide range of health supportive services or which offer services not broken out at a lower level. Included are organizations that provide medical equipment/supplies (e.g., incontinence supplies, medical dressing, apnea monitors, blood pressure monitors, heart monitors, ostomy supplies, respiratory aids, sickroom equipment and therapy beds).", "facet": "SUBJECT", "depth": 1, "hasChildren": true, "children": [ { "code": "SE110100", "name": "Blood banks", "description": "Acquisition, processing, typing, transport and storage of whole blood and blood products including red blood cells, white blood cells, platelets and plasma constituents for use by people who need transfusions; and pre-transfusion compatibility tests to ensure that blood transfusions, when necessary, are as safe as possible.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE110200", "name": "Emergency medical services", "description": "Activities outside of intensive care units and hospital emergency rooms that provide emergency care for people who have acute, life-threatening injuries or severe illnesses. And rapid transportation to health care facilities for accident victims and acutely ill or injured individuals who need immediate medical intervention both on the scene and en route. Included are EMTs (emergency medical technicians); mobile trauma units; paramedic services, ambulances, air ambulances and mercy flights by volunteer pilots who transport human organs and tissues for transplants; plasma or whole blood; mothers' milk; anatomical specimens for medical research; medical personnel, equipment and supplies; and, in instances of medical and financial need, individual patients who require services from health care facilities that they would be unable to access without assistance.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE110300", "name": "Home medical equipment", "description": "The provision of new or used medical equipment for long or short-term use by a patient at home.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE110400", "name": "Organ and tissue banks", "description": "Services and facilities that accept donated hearts, kidneys, livers, skin and other organs and tissue for use in transplant operations. Included are ear banks and eye banks.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE110500", "name": "Pharmacies", "description": "The practice of preparing, preserving, compounding and dispensing drugs in accordance with prescriptions prepared by licensed physicians. Also included are suppliers of medication such as insulin that has been prescribed as a part of an individual's treatment for an illness or injury when the individual is unable to purchase the medication for him- or herself.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE110600", "name": "Prosthetics", "description": "Artificial devices that replace a missing body part that has been lost through trauma, disease or a congenital condition. Modern prosthetics can range from a simple non-mechanical cosmetic replacement of a lost body part to a permanently attached artificial body part or a neural prosthetic, which is a fully functional robotic body part that is controlled via biosensors.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] } ] }, { "code": "SE120000", "name": "Mental health care", "description": "Preventive, diagnostic and treatment services in a variety of community and hospital-based settings to help people to achieve, maintain and enhance a state of emotional well-being, personal empowerment and the skills to cope with everyday demands without excessive stress; to prevent or deal with the consequences of addiction; and to address emergencies or crises having to do with mental trauma or severe mental distress. Treatment may include emotional support, introspection and problem-solving assistance utilizing a variety of modalities and approaches, and medication, as needed, for individuals who range from the severely chronically mentally ill to those who are experiencing difficult life transitions or who are having problems in coping with daily living. Use this term for types of mental health care not specifically broken out at lower levels or for multiple types of care within the same program or facility. See also Art and music therapy. Examples include: Different types of therapies (dance, hypnotherapy, music, orthomolecular, play, poetry, recreation); Psychiatric occupational therapy; Psychiatric rehabilitation; Programs that feature a particular counseling approach (gestalt, Jungian); Supportive services for institutionalized individuals, e.g., pet visitation programs; Psychiatric day treatment; Mental health drop-in centers; Home-based psychiatric care; Community mental health education; Early intervention programs; Mental health evaluation; Psychiatric case management; Psychiatric central intake/assessment; Psychopharmacology/medication monitoring; and Therapist referrals. Also included are efforts to promote social conditions that enhance the potential in the community for good mental health and to improve methods and facilities for treating mental illness.", "facet": "SUBJECT", "depth": 1, "hasChildren": true, "children": [ { "code": "SE120500", "name": "Addiction services", "description": "Preventive, diagnostic and inpatient, outpatient and residential treatment services as well as transitional support for people who have a physical and/or psychological dependency on one or a combination of addictive substances including alcohol and/or drugs; or whose use of these substances has impaired their physical or mental health or their personal, social or occupational functioning. And counseling, medical treatment, and other supportive services for individuals who have a psychological dependency involving a particular pattern of behavior, e.g., eating, gambling, spending money, sexual compulsions and workaholic behavior. Use this term for providers of both substance abuse prevention and treatment services or those that offer other specified substance abuse services; and for addictive disorders not broken out at a lower level or for combinations of types of addictive disorders. Included may be: Primary recovery homes; Relapse prevention programs; Sober living centers; Supportive recovery homes. Very often used with Population Group, Substance abusers.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE120501", "name": "Eating disorders", "description": "Multidisciplinary programs, often offered on an inpatient basis with post-discharge outpatient therapy, that provide comprehensive diagnostic and treatment services for individuals who have anorexia nervosa, bulimarexia, bulimia or a related eating disorder. Treatment is individualized and involves a combination of techniques including individual psychotherapy, mutual support groups, medication, nutritional counseling, behavior modification and group or family therapy.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE120502", "name": "Smoking", "description": "Programs that utilize one or a variety of techniques including aversion therapy, hypnosis, acupuncture, acupressure, and individual and/or group therapy or mutual support groups to help people who wish to control their dependence on nicotine and give up cigarettes, cigars, pipe tobacco, chewing tobacco, snuff or other substances containing nicotine. Also included are smoking education/prevention programs that provide a variety of services including presentations in schools and agencies and to family groups regarding the dangers of smoking or utilizing other substances containing nicotine in an effort to prevent people from starting.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE120503", "name": "Substance abuse prevention", "description": "Any of a variety of services including individual, group and/or family counseling; knowledge and skill-enhancing activities; and structured groups which focus on family dynamics, problem-solving, self-esteem and other similar issues, for people of all ages who are at risk for substance abuse. Substance abuse education programs usually also offer presentations in schools and agencies and to family groups regarding the dangers of drug and/or alcohol abuse.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE120504", "name": "Substance abuse treatment", "description": "Any of a variety of treatment services for individuals who have a physical and/or psychological dependency on one or a combination of addictive substances including alcohol and/or drugs. Included may be: Central intake/assessment services; Detoxification services (inpatient, outpatient); Drug testing; Inpatient drug/alcohol abuse treatment; Antabuse programs; Drug/alcohol abuse counseling; Drug/alcohol abuse drop-in services; Drug/alcohol day treatment; Perinatal drug treatment; Residential drug/alcohol treatment; Drug/alcohol abuse crisis intervention; Substance abuse hotlines; and Substance abuse intervention programs.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE120200", "name": "Community mental health care", "description": "Community-based outpatient mental health care, often operated on contract with the city or county, that offer individual, group, conjoint and family counseling, therapy groups, medication and other mental health services for community residents, especially those who are indigent, who have acute or chronic mental or emotional disturbances or who may be experiencing difficulty resolving personal or interpersonal conflicts or making personal adjustments to stressful life situations such as separation, divorce, widowhood, loss of a child, poor health, unemployment, family violence, delinquency or substance abuse. For family service agencies that provide counseling, see also Family counseling.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE120600", "name": "Crisis intervention", "description": "Immediate assistance for people who are in acute emotional distress; who are a danger to themselves or to others; or who are hysterical, frightened or otherwise unable to cope with a problem that requires immediate action. The objective of crisis intervention is to defuse the critical nature of the situation, ensure the person's safety, and return the individual to a state of equilibrium in which he or she is capable of identifying and seeking solutions to the problem. Use this term for crisis intervention services or hotlines not broken out at a lower level or for organizations that offer multiple types of crisis intervention/hotline services. Included may be the following: Crisis houses; In-person crisis intervention; Involuntary psychiatric intervention; Psychiatric emergency rooms; and Mental health hotlines. For child abuse hotlines, use Child abuse. For battering hotlines, use Domestic violence. For substance abuse hotlines, use Substance abuse treatment. For suicide prevention hotlines, use Suicide crisis intervention.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE120602", "name": "Sexual assault victim services", "description": "Programs that provide telephone crisis intervention services or crisis, short-term and/or ongoing in-person counseling for people who are coping with the emotional trauma that is the result of sexual assault by an individual other than a spouse or other family member, and/or for their significant others. Hotline services may include steps to ensure the individual's safety; short-term emotional support; information regarding the person's rights and alternatives; and referrals and/or accompaniment to resources for medical, legal and emotional needs, advocacy and other related services. Counseling services may focus on adult or child sexual assault survivors and may be available through a variety of modalities including individual, conjoint, family and group therapy sessions for the survivor and/or significant others. Also included are other services related to sexual assault: support groups; counseling services for sexual assault survivors (individual and group); medical treatment for sexual assault; and rape evidence collection kits.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE120601", "name": "Suicide crisis intervention", "description": "Telephone crisis intervention services and/or counseling for individuals who are having suicidal feelings or for their significant others with the objective of exploring alternatives to self-harm or self-destruction. Suicide prevention workers establish and maintain contact with the individual while identifying and clarifying the focal problem, evaluate the suicidal potential, assess the individual's strengths and resources, and mobilize available resources including paramedic or police intervention and emergency psychiatric care as needed.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE120700", "name": "Mental health counseling", "description": "Treatment services which may include emotional support, problem-solving assistance, information and guidance through a variety of counseling modalities for individuals who are having difficulty in coping with a traumatic experience or a personal relationship or in making the adjustments that are required by their particular stage in life. Therapeutic sessions may be structured according to a variety of counseling modalities which may include individual, group, family or conjoint counseling, helpline counseling, peer counseling or therapeutic self-help materials Use this term for counseling that focuses on specific problems not broken out at a lower level or for counseling that focuses on multiple specific problems. Included may be individual or group counseling in the following areas: Adolescent/youth counseling; Anger management; Child guidance; Cult membership counseling; Gender identity counseling; Geriatric counseling; Health problems counseling; Holocaust counseling; Post-abortion counseling; Psychiatric disorder counseling; Sexual offender counseling; Sexual orientation counseling; Sexuality counseling; Terminal illness counseling; and Veteran reintegration counseling. For family service agencies that provide counseling, see Family counseling.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE120702", "name": "Bereavement counseling", "description": "Providing emotional support, problem-solving assistance, information and guidance for people who have recently lost a loved one. Included are counseling programs for widows and widowers, children who have lost a parent, parents who have lost a child and people who are in other similar situations. Includes mutual support groups that deal with bereavement.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE120701", "name": "Support groups", "description": "Support groups are a group of people with common experiences or concerns who provide each other with encouragement, comfort, and advice. Support groups are often patient-initiated and peer-led; and may take place outside of a formal \"counseling\" session led by a mental health professional. Support groups include a wide range of people and topics from alcohol/drug-related issues (Alcoholics Anonymous, Al-Anon, Narcotics Anonymous, etc.), to LGBT issues (Gay/same sex parenting, children of LGBT parents), to weight issues (Weight Watchers, Overeaters Anonymous, etc.), to survivors of abuse, to a range of relationship issues, etc. Use For: 12-step group; Encounter group; Support system; Self-help group.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE120100", "name": "Psychiatric care", "description": "Programs, often hospital-based, that provide diagnostic and treatment services for individuals who have acute or chronic mental or emotional disturbances, who require hospitalization on a voluntary or involuntary basis for maximum benefit, and who might be a threat to themselves, to their families or to others if left in the community or placed in a less restrictive treatment setting. The objective of inpatient mental health programs is to stabilize and return the individual to the community for ongoing treatment as quickly as possible, and to facilitate the transition by preparing the individual's family to cope with the limitations imposed by the illness and by arranging for other supportive services as required. Included are psychiatric hospitals and state hospitals for people who are mentally disordered.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE120300", "name": "Residential mental health care", "description": "Therapeutic living environments in community-based facilities for individuals (adults or children) who have emotional and/or behavioral problems and who require a structured, supervised treatment program which may include individual, group, family and other treatment modalities as appropriate. Services are geared to the specific needs of individual residents and their eventual return to the community when their personal and social adjustment and development permit. For group homes and residential facilities primarily providing custodial care for older adults, people with disabilities, or others, see also Residential and custodial care. For group homes for offenders, delinquent youth and others having contact with the criminal justice system, see also Prison alternatives.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE120400", "name": "Transitional mental health services", "description": "Transitional residential treatment programs that continue the treatment and rehabilitation process begun in a crisis residential program. They also serve others who are referred directly from the hospital or other community resources. The purpose of transitional residential programs is to provide an opportunity for rehabilitation and socialization which prepares clients for independent living in the community.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] } ] }, { "code": "SE060000", "name": "Nursing care", "description": "Providers of nursing care on an inpatient or home-care basis for people who need continuous care but are not in an acute phase of their illness. Use this code for organizations that provide nursing services that are not broken out at a more specific level, e.g., Candy Stripers or Chronic Care.", "facet": "SUBJECT", "depth": 1, "hasChildren": true, "children": [ { "code": "SE060100", "name": "Home health care", "description": "Visiting nurse associations and other similar services that provide skilled nursing care and related health services for recently discharged hospital patients, and elderly or disabled individuals who may otherwise require care in an institution.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE060200", "name": "Hospice care", "description": "Providers of a full range of palliative and supportive services for terminally ill people who are in the final stages of their illnesses and for their families. Services may include medical care, pain and symptom management, home nurse visitation, case management, counseling, and bereavement services for the patient and members of the family. Hospice care may also be provided in the individual's own home.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE060300", "name": "Palliative care", "description": "Medical care or treatment that concentrates on reducing the severity of disease symptoms, rather than striving to halt, delay, or reverse progression of the disease itself or provide a cure. The goal is to prevent and relieve suffering and to improve quality of life for people facing serious, complex illness. Non-hospice palliative care is not dependent on prognosis and is offered in conjunction with curative and all other appropriate forms of medical treatment. It should not be confused with hospice care which delivers palliative care to those at the end of life.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] } ] }, { "code": "SE050000", "name": "Out-patient medical care", "description": "Care provided in health centers, clinics, and other facilities that provide walk-in, walk-out diagnostic and treatment services of a specialized nature for people whose care does not require confinement or a hospital stay. Includes special care, such as: Antivenin supplies; Artificial organs; Chemotherapy/radiation therapy; Clinical trials; Coma management; Diagnostic services including Diagnostic radiology/imaging (majors being CAT scans, chest x-rays, GI series, MRI, ultrasound); Blood tests; Bone density tests (for osteoporosis); Heart catheterization monitoring; and Pediatric evaluation. Dialysis centers; Hyperbaric chambers; Outpatient surgery; Pacemakers; Pain management; Second opinions; Sex change operations; Tattoo removal; and Weight management (other than eating disorders).", "facet": "SUBJECT", "depth": 1, "hasChildren": true, "children": [ { "code": "SE050200", "name": "Dental care", "description": "Care of the teeth and associated structures in the oral cavity Including the prevention, diagnosis and treatment of diseases of the teeth and gums. Included may be: Dental hygiene services; Dental prosthodontics including dentures; Dental restoration; Emergency dental care; Mobile dental care; Oral/maxillofacial surgery; Orthodontics; Pediatric dentistry; and Periodontics.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE050500", "name": "E-health", "description": "The use of telecommunication technologies and the Internet to provide healthcare services at a distance. It is commonly used to provide both emergency and non-emergency mental and physical healthcare to remote communities that have little or no direct access to healthcare services.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE050100", "name": "Health care clinics", "description": "Outpatient facilities, known also as free clinics and community health centers, that have been established by the community and which provide basic medical care including physical examinations, immunizations, family planning, nutrition assistance and diagnosis and treatment of common ailments. Services are often provided on an ability-to-pay basis when they target low-income and indigent residents of the community. Include mobile health clinics.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE050300", "name": "Hearing care", "description": "Support and assistance for people who were born with or have developed hearing disorders due to accident, prolonged exposure to loud noise, illness or aging. This can include testing hearing to diagnose problems, providing hearing aids to improve hearing, and programs to increase awareness of environmental dangers to hearing.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE050800", "name": "Preventive care", "description": "Measures taken for disease prevention, with attention to environmental issues, genetic predisposition, lifestyle choices, and other factors, and relying on anticipatory actions categorized as primary, secondary and tertiary prevention. May include check-ups to screen for diseases, to identify risk factors for disease, to enhance awareness of and promote health and wellness, and to update immunizations and boosters.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE050600", "name": "School-based health care", "description": "Health care provided on primary and secondary school campuses, generally a combination of primary and mental health care, substance abuse counseling, case management, dental health, nutrition programs, and health education and promotion, staffed by interdisciplinary health care providers including nurse practitioners, physician assistants, social workers, substance abuse counselors and mental health professionals. The emphasis is usually on prevention and early intervention; providing reproductive health care may be provided, but sometimes with certain restrictions or permissions required.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE050700", "name": "Urgent care", "description": "Urgent care is most often provided on a walk-in basis 7 days a week, with flexible access outside normal business hours, focused on the delivery of ambulatory care in a dedicated medical facility outside of a traditional emergency room with a licensed physician operating as medical director. This type of care is most often used to treat injuries or illnesses requiring immediate care, but not serious enough to require an ER visit, and distinguished from similar ambulatory healthcare centers such as emergency departments and convenient care clinics by scope of conditions treated, cost of treatment, daily hours that care is provided, and the available facilities on-site, including diagnostic equipment.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE050400", "name": "Vision care", "description": "Assistance to people whose vision is defective by measuring the visual refractive power of their eyes and prescribing eyeglasses or contact lenses which give them normal vision or correct their vision to the greatest extent possible. Also included are programs that offer visual acuity and/or color tests for the purpose of identifying individuals who are color-blind or have an impaired ability to see, and vision screening programs.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] } ] }, { "code": "SE130000", "name": "Public health", "description": "Programs whose primary purpose is to inform the public of existing or potential health and safety hazards and measures for furthering the early detection, treatment or rehabilitation of people who have an illness, injury or disability; or which provide anticipatory information or guidance to help people deal with or understand specific medical procedures, being hospitalized or other necessary interfaces with the health care system. Also included are public health programs that improve the health of the community through comprehensive efforts to prevent, control, and eradicate communicable disease; eliminate environmental health hazards; and recognize, prevent and control occupational health hazards and illnesses. Use this term for organizations that provide a wide range of public health or health education services or which offer public health or health education services not broken out at a lower level. Included are the following: Disease/disability information (usually printed materials); Health fairs; Health screening programs for older adults, school children and other targeted groups (blood pressure, hearing, etc.); Hygiene programs; Immunization programs (including travel shots); Medically oriented books and playthings; and Wellness programs (for the community and the workplace). See also first aid training, and poison control.", "facet": "SUBJECT", "depth": 1, "hasChildren": true, "children": [ { "code": "SE130100", "name": "Communicable disease control", "description": "Protection of public health through comprehensive efforts to prevent, control and eradicate vaccine-preventable diseases, vector and food-borne diseases, diseases that are transmitted from person to person, and diseases that are spread by direct or indirect contact. Activities include routine surveillance of communicable disease activity, assessment of the community immunization level through school records and immunization studies, investigation of epidemic outbreaks and appropriate measures such as isolation to prevent disease transmission. Most common health efforts are those which seek to prevent and control food poisoning, rabies and tuberculosis; and vaccine and immunization efforts. See also Sexually transmitted disease (STD) control.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE130200", "name": "Environmental health", "description": "Addressing aspects of the natural or built environment - physical, chemical, and biological factors external to a person - affecting human health and disease-prevention. See also Clean water supply, Hygiene, and Sanitation.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE130300", "name": "Epidemiology", "description": "Investigation of the causes, characteristics and impact of the occurrence in a community or region of a group of illnesses of a similar nature whose numbers are clearly in excess of normal expectation and are derived from a common source.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE130400", "name": "Occupational health", "description": "Enforcement of the laws which establish job safety and health standards in the workplace in order to eliminate or minimize the incidence of employment-related personal illness, injury or death of workers. Included are work hazards citation appeals, work hazards consultation and work hazards enforcement.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE130600", "name": "Physical fitness", "description": "The development and preservation of physical abilities and physical condition necessary for good or improved health. See Also: Sports training.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE130601", "name": "Exercise", "description": "Exercise is an activity requiring physical effort, carried out especially to sustain or improve health and fitness. It is usually planned, structured, and repetitive for the purpose of increasing strength, agility, coordination, balance, flexibility, cardiovascular capacity, and other physical traits; along with restorative periods of rest. It includes indoor-related activity such as a gym workout or exercise at another facility or use of exercise equipment in your own home. It also includes outdoor-related physical activity such as walking, running, cycling, sports activities (baseball, softball, basketball, football, etc.), and other activities. See Also: Sports training. Use For: Aerobic exercise; Aerobics; Physical activity; Physical education; Gym memberships; Personal trainers; Workouts.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE130602", "name": "Nutrition", "description": "Efforts to provide information concerning the basic principles of healthful eating, food handling, food preparation and shopping skills. Included is information about the basic food groups, vitamin and mineral requirements, and the relationship of nutrition to the preservation of good health and the prevention of illness. Also included are provision of nutrition assessment and prescription services.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE130603", "name": "Obesity", "description": "The condition of being overweight to an extent that physical health is adversely affected and the likelihood of developing certain chronic conditions is increased (specific definitions and criteria vary). Included are activities to prevent obesity (especially in children), to address and reduce obesity and its effects in individuals, and to educate people about the risks associated with obesity and how to avoid the condition. Use For: Weight loss.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE130500", "name": "Sexually transmitted disease control", "description": "Screening, diagnostic and treatment services for individuals who have contracted gonorrhea, syphilis, genital herpes or other diseases that are spread by sexual contact; or that control the occurrence of sexually transmitted diseases by monitoring the incidence of the disease in the general population, investigating individual outbreaks, and identifying and screening recent contacts of people who are infected to stop the spread of the disease.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE130700", "name": "Water access, sanitation and hygiene", "description": "The provision of adequate water, sanitation and hygiene services. Examples include promoting the use of toilets and/or latrines, proper waste disposal (human, household and commercial waste), control of rodents and other disease carriers, promoting hand washing, providing potable, healthy or safe water, especially in developing areas of the world, waste water treatment and management, construction of sewer systems, upgrading and/or fixing existing water or sanitation facilities, and other WASH-related issues.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE130701", "name": "Clean water supply", "description": "Efforts to promote health by providing households and communities access to clean and safe water for consumption and productive uses in pursuit of a livelihood; includes filtration systems, point-of-use treatment, pumping systems, well-digging, aqueducts, safe storage, rain-collection systems, and chemical treatments. For large scale water supply systems or infrastructure, see Water utilities. See also Water pollution, and Water resources.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE130703", "name": "Hygiene", "description": "Encouragement of individual, household, and community practices associated with cleanliness for the purpose of preserving health; including hand-washing, respiratory hygiene, food hygiene, medical hygiene, etc. This is one element of WASH (Water, Sanitation, and Hygiene) programs and will often be used in a 'clean water' context.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE130702", "name": "Sanitation", "description": "Health promotion through the prevention of human contact with waste materials; includes disposal services for human waste and wastewater, and latrine, sewer, and septic systems or projects. For large scale sewage or water treatment systems or infrastructure, see Sewage utilities.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] } ] }, { "code": "SE080000", "name": "Rehabilitation", "description": "Combinations of treatment and education services which are designed to restore maximum functioning, a sense of well-being, and a personally satisfying level of independence for individuals who have temporary or permanent disabilities. Included are organizations that provide primary health care and rehabilitative therapy for individuals suffering from physical or mental impairments due to injury, genetic defect, or disease. Services may include physical and occupational therapy services and inpatient and outpatient facilities that provide multidisciplinary restorative services. Use this term for organizations that provide a wide range of rehabilitative services or which offer services not broken out at a lower level. Included may be: Amputee rehabilitation; Cardiac rehabilitation; Hand rehabilitation; Occupational therapy; Pulmonary rehabilitation; and Stroke/head injury rehabilitation. Use this term for Easter Seal Society.", "facet": "SUBJECT", "depth": 1, "hasChildren": true, "children": [ { "code": "SE080100", "name": "Animal therapy", "description": "Interaction with companion and service animals, including domesticated pets, farm animals and dolphins, as a form of therapy and treatment, in nursing homes, prisons, mental health facilities and other institutional, as well as private contexts. The goal is to improve a patient's physical, social, emotional and cognitive functioning. Use For: therapeutic riding, hippotherapy, pet partner, pet therapy. See Also: Human-animal interactions", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE080200", "name": "Art and music therapy", "description": "Services to enable individuals who have mental, emotional or social problems to achieve self-expression and emotional release by communicating their emotions and conflict graphically through painting, drawing, sculpting and other art forms. Art therapy is used both as a diagnostic tool and a treatment technique.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE080300", "name": "Physical therapy", "description": "Utilization of the therapeutic properties of exercise, heat, cold, electricity, ultraviolet, water and massage to improve circulation, strengthen muscles, reduce pain and restore mobility to people who have been disabled by stroke, arthritis, back or spinal cord injuries or other debilitating conditions. Includes cryotherapy, electrical stimulation, hydrotherapy and massage.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE080400", "name": "Play therapy", "description": "A form of counseling or psychotherapy usually used with children under the age of eleven. Play therapy uses play as a medium of expression and means to communicate feelings and experiences that a child is unable to express verbally due to age or trauma. Play therapy is used to diagnose, prevent and resolve psychological challenges.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE080500", "name": "Speech and hearing rehabilitation", "description": "Comprehensive diagnostic and treatment services for individuals who have speech and/or language problems; neurological disorders or diseases; or disorders of the middle, inner or outer ear, larynx, tongue, mouth, or other structures whose coordination and appropriate functioning are necessary for speech and/or hearing. Included may be: Audiological evaluations; Auditory training; Cued speech instruction; Finger spelling instruction; Oral communication instruction; Sign language instruction; Speech reading instruction; Total communication instruction; Verbal-tonal instruction; Visual English instruction; Language therapy; Speech and language evaluations; and Speech therapy.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] } ] }, { "code": "SE070000", "name": "Reproductive health care", "description": "Providers of medical, educational and counseling services which relate to the conception, delivery and care of offspring. Use this term for providers of a wide range of reproductive health services or which offer reproductive health services not broken out at a lower level. For prevention of adolescent pregnancy, use Pregnancy prevention (youth). For maternity homes for unwed mothers, or advice and guidance programs that focus on adolescent parents, see Adolescent parenting.", "facet": "SUBJECT", "depth": 1, "hasChildren": true, "children": [ { "code": "SE070200", "name": "Abortion", "description": "Provision of pregnancy termination services for women who have decided not to follow through with their pregnancies.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE070300", "name": "Childbirth", "description": "Specialist providers of comprehensive preventive, diagnostic and treatment services for women during pregnancy, childbirth and the period immediately following childbirth. Includes services for women who are ready to give birth, alternative birthing centers, care provided by doulas and midwives, hospital delivery rooms, and programs that support methods of child delivery which emphasizes a gentle and peaceful environment.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE070100", "name": "Family planning", "description": "Providers of assistance to people who want to control the size of their families and the spacing of their children, usually through some form of birth control. Planned Parenthood is an example of this type of activity. Included may be contraceptive devices and oral steroid pills and natural family planning methods which rely on awareness of the woman's fertility cycle in order to avoid pregnancy.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] }, { "code": "SE070400", "name": "Maternal and perinatal health", "description": "Health care for expectant, nursing, and new mothers from the time of verified pregnancy through birth and the first few years of the child's life to ensure their own physical well-being and the healthy development and birth of their child. Includes programs dealing with postpartum conditions, as depression; early infant care education; and breast feeding assistance.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE070402", "name": "Infant care", "description": "Providers of health screening and immunization services for infants and toddlers to ensure their physical well-being and healthy development.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE070401", "name": "Prenatal care", "description": "Health care for expectant mothers from the time of verified pregnancy through birth and shortly afterward to ensure their own physical well-being and the healthy development and birth of their child. Included are programs that offer classes or other educational experiences which prepare prospective mothers and their birth partners emotionally and physically for the labor and birth process; Birth orientation programs; Cesarean birthing classes; Early pregnancy classes; Programs for at-risk/low-income mothers to prevent maternal and infant mortality; Prepared childbirth (including Lamaze, Bradley and other techniques); Sibling preparation programs; and Vaginal birth after cesarean classes.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE070600", "name": "Sexual education", "description": "Programs that provide information and instruction concerning the physiological and emotional aspects of human sexuality including anatomy, human reproduction, birth control and sexually transmitted diseases including AIDS.", "facet": "SUBJECT", "depth": 2, "hasChildren": true, "children": [ { "code": "SE070602", "name": "Abstinence-only sex education", "description": "Abstinence-only programs (also called abstinence-only-until-marriage programs) promote abstinence from sexual behavior for children and youth as a pathway to healthy development. It generally excludes discussions concerned with birth control, safer sex, and sexual orientation.", "facet": "SUBJECT", "depth": 3, "hasChildren": false }, { "code": "SE070601", "name": "Comprehensive sex education", "description": "Programs that provide age-appropriate, medically accurate information and instruction concerning the physiological and emotional aspects of human sexuality including anatomy, human reproduction, birth control and sexually transmitted diseases including AIDS. Comprehensive sex education covers the wide array of topics that affect sexuality and sexual health, including information and communication skills building to promote health and well-being in a way that is developmentally appropriate.", "facet": "SUBJECT", "depth": 3, "hasChildren": false } ] }, { "code": "SE070500", "name": "Youth pregnancy prevention", "description": "A variety of informational and supportive services which promote healthy teen attitudes and behaviors regarding sexuality with the objective of heightening their awareness of the consequences of sexual activity and helping teens to avoid an unwanted pregnancy. Topics may include peer pressure, parent/teen communications, male/female relationships, values clarification, self-esteem, human reproduction, birth control and sexually transmitted diseases including AIDS. Also included are programs that increase the awareness on the part of the general community about the problem of adolescent pregnancy. See also Sexual education with which this term is often associated. Population Groups associated with subject are usually Adolescents, Male, and Female unless another specific population group is mentioned. For supportive services for pregnant teens or teen parents, use Adolescent parenting.", "facet": "SUBJECT", "depth": 2, "hasChildren": false, "children": [] } ] }, { "code": "SE090000", "name": "Traditional medicine and healing", "description": "A system of healthcare that has ancient roots, cultural bonds, trained healers, and a theoretical construct. Traditional medicine and healing uses knowledge, skills, and practices based on the theories, beliefs, and experiences indigenous to different cultures.; traditional systems include Ayurveda medicine, ethnomedicine, shamanism and traditional Chinese and other Eastern medicines. Use For: Folk medicine; Eastern medicine; Indigenous medicine; Shamanism. See Also: Holistic medicine.", "facet": "SUBJECT", "depth": 1, "hasChildren": false, "children": [] } ] } ] } } } ``` ## Search by PCS match Return PCS codes relevant to the search term (e.g. "agriculture") across all facets. This search returns exact matches, approximate matches and relevant matches based on name, descriptions, and codes. ``` query { termsByMatch(match: {searchTerm: "agriculture", limit: 5}) { meta { code message resultsCount took } data { ...term } } } ``` { "data": { "termsByMatch": { "meta": { "code": 200, "message": "Success", "resultsCount": 4, "took": 3171 }, "data": [ { "code": "SM000000", "name": "Agriculture, fishing and forestry", "description": "The development and improvement of biological, renewable food and material resources and the systems that produce them - natural, commercial, and industrial. Included are: agricultural activities that improve management of food production and the health of the land and water on which farms and ranches depend; forestry and forest management activities that support the health and productivity of those resources and regions; fishing and fish farming activities that support the health and productivity of that food resource; and efforts to ensure the security, amount, and appropriateness of the food resources available to communities and other groups.", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SM010000", "name": "Agriculture", "description": "Activities that focus on development or improvement of food resources or food procurement.", "facet": "SUBJECT", "depth": 1, "hasChildren": true }, { "code": "SS050500", "name": "Agriculture for youth", "description": "Projects that emphasize the total development of young people through work on the animal, engineering, family/consumer health, resource, plant or social science project of their choice in consultation with their parents and supervising adult volunteers, as 4-H Club, Future Farmers, and Future Homemakers. Members also participate in camping activities, leadership conferences, awards programs and community service activities. For organizing, promoting or otherwise supporting county or other fairs, use Festivals.", "facet": "SUBJECT", "depth": 1, "hasChildren": false }, { "code": "SM020200", "name": "Sustainable agriculture", "description": "Programs that are responsible for working with landowners and operators or other land users and developers to ensure that land utilization practices protect the nation's farmlands and other open spaces, many of which are being converted to urban uses, from unnecessary erosion and sedimentation or other destruction. Services may include: Development of soil and land capability studies and maps to ascertain appropriate uses for specific tracts of land; Development of conservation plans for specific areas which include measures for protecting and preserving waterways and vegetation, which provide for flood protection and which show the location of conservation devices such as dikes, water diversions, terraces, dams, reservoirs, water conduits, grassed waterways and plantings of grass, trees and shrubs to protect agricultural land; and Consultation and technical assistance for individuals, particularly farmers, who want to ensure that their lands are adequately protected.", "facet": "SUBJECT", "depth": 1, "hasChildren": true } ] } } } ``` ## Search by PCS facet Return all PCS codes within a given facet (e.g. subject). ``` query { termsByFacet(facet: SUBJECT) { meta { code message resultsCount took } data { ...term } } } ``` { "data": { "termsByFacet": { "meta": { "code": 200, "message": "Success", "resultsCount": 18, "took": 11444 }, "data": [ { "code": "SM000000", "name": "Agriculture, fishing and forestry", "description": "The development and improvement of biological, renewable food and material resources and the systems that produce them - natural, commercial, and industrial. Included are: agricultural activities that improve management of food production and the health of the land and water on which farms and ranches depend; forestry and forest management activities that support the health and productivity of those resources and regions; fishing and fish farming activities that support the health and productivity of that food resource; and efforts to ensure the security, amount, and appropriateness of the food resources available to communities and other groups.", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SA000000", "name": "Arts and culture", "description": "Enjoyment or understanding of the visual, performing, or folk arts or the humanities (history, art history, modern and classical languages, philosophy, ethics); and organizations that promote the appreciation or understanding of historical events, including historical societies and genealogical or heredity-based organizations (e.g., Sons of the Revolution, Daughters of the Confederacy, etc.). Includes museums and halls of fame; historic preservation programs; groups of or services to artists, performers, entertainers, writers, or humanities scholars; programs which promote artistic expression of or within ethnic groups and cultures; and art and performing art schools, centers, and studios. Does not include libraries and reading programs (see Education); botanical gardens,or zoos (see Environment).", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SN000000", "name": "Community and economic development", "description": "Work to strengthen the health and prosperity of communities and increase the capacity of various community organizations to improve the quality of life for all, including community and neighborhood development and improvement services; urban, rural, and sustainable economic development programs; business and financial services and services to improve or develop commercial and industrial enterprises within communities; services to enhance, improve, and protect the workforce and promote employment; efforts to develop and rehabilitate community housing, and organize tenants and homeowners; and community service programs.", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SB000000", "name": "Education", "description": "All formally constituted educational institutions (except art and performing art schools) and projects or activities that administer or support those institutions; libraries; organizations whose primary purpose is to provide opportunities for supplementing and continuing education outside the framework of formal education institutions (including English-as-a-second-language programs and literacy and reading programs for children and adults); and organizations that provide educationally related services to students and schools, e.g., educational testing services, scholarship programs, drop-out prevention and programs designed to increase parent participation in the schools.", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SC000000", "name": "Environment", "description": "Preservation and protection of the natural environment: including pollution control and abatement programs; conservation and responsible development of natural resources; biodiversity preservation and wildlife conservation; protection of animals, including domestic pets and animals providing special services; control or elimination of hazardous and toxic substances; solid waste management programs; and environmental education. Does not include programs that focus on the protection or preservation of farmlands or soil and water conservation for agricultural, food production purposes or livestock issues (see Agriculture, Fishing, and Forestry); or programs that focus on recreational parks (see Sports and Recreation).", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SE000000", "name": "Health", "description": "Promotion and protection of the physical and mental well-being of people through medical care and treatment; assessment and amelioration of social, environmental, and biomedical factors affecting that well-being; research into various diseases and in various disciplines; and education and prevention activities that increase people's own efforts at protecting public health.", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SR000000", "name": "Human rights", "description": "The protection and promotion of the human rights and civil liberties of individuals and communities. This includes protecting equal rights for and fighting discrimination against some categories of people; improving relations between racial, ethnic, and cultural groups; and promoting voting rights. Does not include organizations that focus on or provide legal services (see Legal services); or groups using advocacy as a method to achieve goals in a particular subject area such as food, housing and education. In these cases, select the most appropriate term in the subject area, and a Strategy of Equal access. For animal rights work, see Research on animals and Humane education (in Environment).", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SS000000", "name": "Human services", "description": "Promotion and provision of a broad range of social or human services to individuals or families; family services, including shelters and aftercare programs for victims of domestic violence; direct social services to children and adolescents (e.g., adoption and foster care services, child day care, etc.); personal social services, travelers aid, etc.; residential, custodial care facilities and services for individuals unable to live independently due to developmental disabilities, age or physical infirmity; and programs that promote general independent functioning and living of individuals (e.g., retarded citizens associations, guide dog services for people with disabilities, etc.); job assistance programs that help those with significant barriers to employment, including special employment assistance for people who have disabilities or other disadvantages); housing rehabilitation, home improvement, shelters, and other non-recreational temporary housing facilities, and services to assist individuals and families in locating, acquiring, or sustaining clean, safe and adequate housing on a rental or ownership basis; programs that work to build character and develop leadership and social skills among children and youth, including scouting organizations; adult matching programs; business, agricultural, religious and other youth leadership programs; and youth community service clubs; food services for the poor and hungry, including dining facilities, food banks, and food delivery services.", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SH000000", "name": "Information and communications", "description": "The gathering, storage, organization, manipulation, dissemination, and display of data, information, communication, and narrative. Included are programs that develop or make use of information technology to increase the amount and complexity of data that can be managed; policies that work to insure broad availability of information; programs that gather and broadcast news and information about current events; libraries that store and make available information in a variety of formats; media organizations and programs that broadcast information across a variety of platforms; telecommunications services; and information science and computer applications.", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "ST000000", "name": "International relations", "description": "Promoting international understanding and friendly relations among nations, preserving international peace, and protecting national security interests. Also included are efforts to provide development and relief services to other countries or regions, international trade activities and globalization, and programs of international exchange.", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SD000000", "name": "Philanthropy", "description": "Organizations or programs that focus on promoting the practice of giving and volunteering or which represent and serve a wide range of philanthropy and charitable institutions; private grantmaking foundations and charitable trusts; federated giving programs that provide funding and other types of assistance to community services (e.g., United Way, Jewish Federation); programs that promote individual giving through pooling of funds or trusts for maximal financial and program administration performance (e.g., public foundations and community foundations); and programs that provide management and administrative support to philanthropic and nonprofit organizations and projects. Does not include fund-raising, distribution services, or volunteer bureaus and volunteer action centers operating in a specific major group area (see Support Strategy and Organization Type terms).", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SK000000", "name": "Public affairs", "description": "Organizations or programs that focus on promoting the effective functioning of government, public administration and public officials; programs that conduct or promote research in multidisciplinary public policy (e.g., Joint Center for Political Studies); programs that support or provide services required for the effective functioning of society (e.g., public works projects, public utilities, public finance, legal and judicial systems, elections, etc.).; programs that promote patriotism, encourage civic participation, and support national security; and organizations that protect the public against the distribution of unsafe goods and products, including product testing and reporting services. Does not include social services organizations that focus on the provision of human services (use terms in Human services); strict political science research (use Political science); or public policy research tied specifically to a major group area (use field-specific coding where possible).", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SJ000000", "name": "Public safety", "description": "Protection and relief of the public from crime, violence, disaster, accident, and other potential causes of harm. Included are crime, abuse, and violence prevention services; police and other law enforcement agencies; detention and rehabilitation services for offenders and ex-offenders; judicial and administration of justice activities; legal assistance to individuals and organizations, including groups whose primary purpose is to conduct public interest litigation; activities to prevent, predict or control the effects of disasters; educate and prepare individuals to cope with the effects of disasters; provide broad-based disaster relief services to victims; provide relief to victims of accidents caused by human frailty or error (e.g., poisoning, choking, electrical shock, falls); first aid training and services; and many kinds of safety education and promotion. Does not include agencies that provide aftercare services to the victims of crime or abuse and neglect (see Victim aid, Domestic violence, Sexual assault victim services, and other terms).", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SP000000", "name": "Religion", "description": "Worship, religious training or study, governance, or administration of organized religions, or the promotion of religious activities. Does not include other services operated under the auspices of specific religious groups such as educational institutions, hospitals, social service agencies, etc. For separately organized graduate schools of theology, use Theology and Graduate and professional education.", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SF000000", "name": "Science", "description": "Efforts to promote or conduct research and study in the physical and life sciences, mathematics, engineering and technology. Does not include medical research; or research institutes and services operating in a single major group area. For these organizations and programs, use the most appropriate subject code, and a research code from either the Organization Type or Support Strategy facets", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SG000000", "name": "Social sciences", "description": "The study of, teaching of, or research in one or more of, the social sciences, including economics, psychology, political science and demographics. Also includes interdisciplinary research programs such as black studies and urban studies.", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SQ000000", "name": "Sports and recreation", "description": "Services meeting the recreational needs of individuals and communities, including camps and camping programs; physical fitness and other recreational facilities such as parks, playgrounds, etc.; sports training and competition services; and other sports, recreational and social clubs. Does not include programs primarily involved in character building and leadership development for youth such as scouting, even though they may also provide recreational programs (see Youth development); or neighborhood centers, senior centers and other community centers primarily engaged in the provision of social services (see Human Services).", "facet": "SUBJECT", "depth": 0, "hasChildren": true }, { "code": "SZ000000", "name": "Unknown or not classified", "description": "", "facet": "SUBJECT", "depth": 0, "hasChildren": false } ] } } } ``` ## Search by NTEE code Return NTEE minor codes that are relevant to the search term (e.g. "animal"). This search returns relevant matches based on name, descriptions, and codes. This search can also return the equivalent PCS codes and names, as well as if this code is an exact match to the NTEE code. ``` query { nteeMinor (query: "animal") { data { key value type pcsCrosswalk { code name exact_match } } } } ``` ``` { "data": { "nteeMinor": { "data": [ { "key": "D61", "value": "Animal Training, Behavior", "type": "ntee_minor", "pcsCrosswalk": { "code": "SC050200", "name": "Animal training", "exact_match": true } }, { "key": "D99", "value": "Animal Related Activities N.E.C.", "type": "ntee_minor", "pcsCrosswalk": { "code": "SC050000", "name": "Domesticated animals", "exact_match": false } }, { "key": "D20", "value": "Animal Protection and Welfare (includes Humane Societies and SPCAs)", "type": "ntee_minor", "pcsCrosswalk": { "code": "SC050100", "name": "Animal welfare", "exact_match": true } } ] } } } ``` ## IRS taxonomies Return IRS taxonomy codes: NTEE Major, NTEE Minor (see above), filing type, subsection code, foundation type code, MSA code. The search below includes queries for all of these code types. ``` query { nteeMajor(query:"art") { data { ...code } } filingType(query: "church") { data { ...code } } subsection(query: "public charity") { data { ...code } } foundationType(query: "foundation") { data { ...code } } msa(query: "dallas") { data { ...code } } } fragment code on MiscCode { key value } ``` ``` { "data": { "nteeMajor": { "data": [ { "key": "A00", "value": "Arts, Culture, and Humanities" } ] }, "nteeMinor": { "data": [ { "key": "K31", "value": "Food Banks, Food Pantries" } ] }, "filingType": { "data": [ { "key": "061", "value": "This organization is not required to file an annual return with the IRS because it is a church." }, { "key": "060", "value": "This organization is not required to file an annual return with the IRS because it is a church." } ] }, "subsection": { "data": [ { "key": "91", "value": "4947(a)(1) Non-Exempt Charitable Trusts (Public Charity)" }, { "key": "03", "value": "501(c)(3) Public Charity" } ] }, "foundationType": { "data": [ { "key": "02", "value": "Private operating foundation exempt from paying excise taxes or investment income" }, { "key": "03", "value": "Private Operating foundation (other)" }, { "key": "04", "value": "Private nonoperating foundation" } ] }, "msa": { "data": [ { "key": "1920", "value": "Dallas-Fort Worth, TX" } ] } } } ``` Grants API allows you to search and filter the most comprehensive and accurate data on grants, funders, recipients, and funding transaction activity. * Gain versatile insight into grantmakers, recipients, and funding activities. * Analyze funding trends, uncover new insights, and explore collaboration opportunities. * Bring global funding landscapes to life using summary statistics with flexible criteria. * Search on PCS, Keyword, Funder, Recipient, location, and more. * Explore many contemporary funding topics such as Covid-19 relief and racial equity. * /transactions Understand granular grant detail including funder, recipient, and grant transaction information. * /funders Find out which funders are supporting specific causes and gain insights such as aggregated funder giving totals, including the funder, dollar amount granted, and grant counts. * /recipients Discover nonprofit funding activities based on subject area, population served, geo location and more. Gain insights such as aggregation of recipient data, including the recipient, location, total dollar amount received, and grant counts. * /summary Generate aggregate grant funding and organization totals. This includes dollar value of grants, funder counts, recipient counts, and grant counts. * Add on to existing nonprofit records to provide a wider funding context and enhance the content used for grant-making decisions. * For nonprofits and GMS grant-seeking tools: * Use for greater context into grant prospecting to see who else your target grantmaker has funded to predict the likelihood of their future funding. * For CRM systems: * Build live landscapes, dashboards, and widgets to provide deep insights on where grantmaking dollars originate, who they are going to, and why it matters. Data returned in the Grants API is compiled from multiple sources, including direct reporting of grants by foundations, IRS information returns (Forms 990 and 990-PF), foundation websites, and other public sources. Candid monitors more than 35 diverse information sources to verify the grant details in our databases. For more information, view the grants data fact sheet which provides answers to frequently asked questions about Candid’s grants data, as well as special notes for researchers interested in using our data. The following table contains search examples from the Grants API to demonstrate ways to use the API. Please refer to Grants API reference for the complete search capabilities and results in the Grants API. Search Example | Query | | --- | --- | I want to see how many grants were awarded to Candid in 2018 and the total amount awarded. | /grants/recipients | I want to see what grants were awarded to Candid in 2018 to gain insight into: | /grants/transactions | I want to see the largest funders who have awarded funds to address climate change in 2018, to organizations in California, for grants between $10,000 and $25,000. | /grants/funders | I want to see a summary of giving for those that are addressing climate change, in 2018, for recipients located in California. | /grants/summary | I want to see a summary of giving for those that are supporting climate change, in 2018, for recipients located in California who have earned a Seal of Transparency on their GuideStar Profile. | /grants/summary | I want to see the most recent grants that have been added or updated in Candid’s database. | /grants/transactions | Q. What does the query parameter “query” search on? * A. The 'query' parameter searches on the following fields: Funder name, funder city, recipient name, recipient city, recipient country if not USA, recipient county if USA, subject code text, grant description, program area, grant type, title, funder mission statement, program name and program description. Q. What does the query parameter “subject” and “population” search on? * A. The subject and population (PCS) searches on only the grant level subject and population codes. If there are no grant subject or population codes, it will search on recipient subject and population. Q. How frequently do we publish new grants to the API? * A. We publish new grants to the API every business day (Monday to Friday). Q. What is Candid’s Philanthropy Classification System (PCS)? * A. Please visit https://taxonomy.candid.org/ for more information. To learn how to use it in our APIs, see our Candid's Taxonomy guide. Q. What are the sources of Candid’s grants data and what data is collected? Q. How recent is the data? Q. How complete is the data? Q. How are grants coded? Access the only API on the market delivering real-time, actionable news on nonprofits, philanthropy, and the social sector, curated by Candid from over 65,000 sources. * Enhance your records, applications, and leads with real-time news. * Save time by automatically monitoring news, staff changes, and advisories. * Engage your users with topic and theme-based news feeds using advanced article metadata. * Enjoy powerful search filters including keywords, organizations, Candid’s PCS Taxonomy, sources, locations, and more. * Candid News API Search for philanthropy and social sector news. * Streamline due-diligence activities by easily accessing news and advisories * Add on to existing nonprofit records or submitted applications to provide relevant news, advisories, and staff changes to understand the impact nonprofits have on their communities. * Monitor news for organizations, cause areas, locations, and populations that matter most to your programs. * For nonprofits and GMS grant-seeking tools: * Add into grant prospecting for greater context to see real-time updates from grantmakers including news on grants and RFPs. * For business intelligence and Client Relationship Management (CRM) systems: * Build landscapes, dashboards, and widgets using news content to provide greater context around the organizations, subjects, and populations that matter. * For developers creating news feeds, websites, or apps: * Create compelling and deeply customizable news feeds and experiences. Articles returned in the news API are curated from multiple sources, including The Global Database of Events, Language, and Tone (GDELT), web scraping, newsletters from foundations and nonprofits, and the social media feeds of more than 100,000 nonprofits. New articles may become available as frequently as every 15 minutes. News is selected for relevance using natural language processing. Using machine learning, relevant articles are then coded to the Philanthropy Classification System and examined for mentions of grants, RFPs, staffing changes, and advisory content. Organizations, people, and geographies mentioned in each article are recognized; detected organizations are also matched to known nonprofits and foundations. Candid has tracked over 65,000 unique news sources to date. Search TermsYou can search for news content using free text search terms. Passing search terms in double quotes, such as "Tree planting", will perform an exact search term match. Article Publication Date RangeTo search for articles using the article publication date range, use the `start_date` and `end_date` parameters. These date ranges are the most commonly used date parameters in the API. * `start _date` The oldest article publication date to search from, in the format YYYY-MM-DD. Default is one month from today's date. The maximum date range size is one year. The earliest possible start_date is 2018-09-24. * `end_date` The most recent article publication date to search to in the format YYYY-MM-DD. Default is today's date. The maximum date range size is one year. Article Database Added Date RangeKeeping your systems up to date with real time news is important to many of our developers and clients. So that you can stay in sync with the Candid News database, which is updated as frequently as every 15 minutes, we offer the ability to search by the date and time an article was inserted into the database. To do so, you can call the API by passing an `added_start_date` and `added_end_date` parameters, with an `added_end_date` 15 minutes later than `added_start_date` . If you call the API every 15 minutes, you’ll pick up all new articles across all possible number of API result pages. If you do not require real-time news, you can expand the range to daily, weekly, or a time range that best fits your processes. * `added_state_date` Used to search by the earliest date an article was added to Candid News database, in the format yyyy-MM-dd'T'HH:mm:ss.SSSXXX. Default is one month from today's date. The maximum date window size is one year. The earliest date to search from is 2018-09-24. * `added_end_date` Used to search by most recent date and time article was added to the Candid News database, in the format yyyy-MM-dd'T'HH:mm:ss.SSSXXX. Default is today's date. The maximum date window size is one year. EINs and Organization NamesThere are two ways to search for news content on specific organizations. * Using the EINs for the organizations you are interested in. EINs can be formatted with or without a dash. This is a direct way to search for organizations, as Candid performs a process to identify distinct organizations within content and match content to an organization's EIN. This process applies to articles published starting in late 2020, so use the organization name to search for content published prior to late 2020. To search for content related to organizations before late 2020 instead use the organization name. You can pass up to 25 EINs at a time, which will be joined using OR. * Using the names of the organizations you are interested in. This is a broader way of searching for organizations. You can pass up to 25 organization names at a time that will be joined using OR. Locations with GeoName IDThe locations search in the Candid News API uses GeoNames, which is a user-editable geographical database available through various web services under a Creative Commons attribution license. A GeoName ID is required to search locations using the Candid News API. Please refer to Candid's geo search for more information. Subjects and Populations with Candid's Philanthropy Classification System (PCS)A valuable way to search for news is to use Candid's Philanthropy Classification System (PCS), which is Candid's taxonomy describing subjects and populations in the social sector. To deploy the PCS in your system, you will need to use the codes associated to each term for relevant searches in the Candid News API. Please refer to Candid's taxonomy for more information. PeopleSearch using the names of people mentioned in news content. You can pass up to 25 people names at a time, which will be joined using OR. Sources Include & Sources ExcludeSearch by including or excluding specific news sources in URL format. By default, leaving these parameters blank will search across all news sources. You can pass up to 25 sources at a time that will be joined using OR. Ask your sales representative for a seed file of our top 5,000 news sources. Staff Change MentionedSearch for news content containing mentions of staff changes, which are topics such as promotions, retirements, and new hires. True = Only return articles containing mentions of staff changes. False = Do not return articles containing mentions of staff changes. Null = Return articles regardless of staff changes mentioned. RFP MentionedSearch for news content containing mentions of RFPs. True = Only return articles containing mentions of RFPs. False = Do not return articles containing mentions of RFPs. Null = Return articles regardless of RFPs mentioned. Grant MentionedSearch for news content containing mentions of grants. True = Only return articles containing mentions of grants. False = Do not return articles containing mentions of grants. Null = Return articles regardless of grants mentioned. Advisory ContentAdvisory content is flagged for organizations or people in the social sector that may or may not require due diligence. True = Only return articles flagged as advisory content. False = Do not return articles flagged as advisory content. Null = Return articles regardless of advisory content. AND/OR Filter OperatorToggle the and/or union type for searches for the following parameters Subjects, Populations, Locations, People, and Organizations. Default is AND. Please note that inter-array parameter values are not affected by the filter operator. Updated almost 2 years ago Date: 2021-08-01 Categories: Tags: The following user profiles and example searches show the versatility of the News API. ## Example Searches I am a grantmaker and would like to enhance my CRM and GMS records on Candid with the latest news and updates over the past year. ``` api.candid.org/news/v1/search?start_date=2021-01-01&amp;eins=13-1837418 api.candid.org/news/v1/search?start_date=2021-01-01&amp;organizations=Candid ``` I am a grantmaker reviewing a grant application from the Make-a-Wish Foundation, and I want to see advisories related to that organization for the past two years. ``` api.candid.org/news/v1/search?start_date=2019-07-14&amp;end_date=2020-01-25&amp;organizations=Make a wish foundation&amp;advisory_content=TRUE ``` I am a busy Program Officer and I would like to automatically monitor the organizations in my sphere of influence, daily, while being able to set up special alerts for staff changes and advisory content. ``` api.candid.org/news/v1/search?start_date=2020-07-12&amp;end_date=2021-07-13&amp;organizations=Los Angeles Regional Food Bank&amp;organizations=Benton Community Foundation&amp;organizations=Black Womens Blueprint&amp;filter_operator=OR ``` I am a developer and want to create customizable news feeds for users on the subjects, populations, and geographic areas that matter most to them individually. ``` api.candid.org/news/v1/search?start_date=2021-01-01&amp;locations=4982236&amp;subjects=SA070600&amp;populations=PE050000&amp;filter_operator=OR ``` I am a developer and want to provide my users with real-time news by keeping my database in sync with the Candid News database by calling the API every 15 minutes, using the `added_date_start` and `added_date_end` fields. ``` api.candid.org/news/v1/search?added_start_date=2021-08-01T17:30:18.1169712&amp;added_end_date=2021-08-01T17:45:18.1169712 ``` ## Prerequisites Access to Candid's APIs are required in order to use Guidestar's SDK. If you do not have access, please review our Getting access guide. The following APIs are available in GuideStar's SDK: ## Installation The GuideStar SDK is available on NuGet. To install using the Package Manager: ``` PM> Install-Package Candid.GuideStarAPI ``` Or, if using .NET Core: ``` dotnet add package Candid.GuideStarAPI ``` ## SDK Setup At the most simple level, calling an API requires initializing the system with an API key, then calling the correct method from the resource you are interested in. Many Candid APIs use an EIN (Employer Identification Number) as a key for documents. To use PremierThe following code shows how to retrieve the Premier JSON document of an EIN. Note that the return value--here, the “premier” variable--will be formatted as a string. ``` GuideStarClient.SubscriptionKeys.Add(Domain.PremierV3, PREMIER_KEY); var premier = PremierResource.GetOrganization(EIN); ``` All request methods have an asynchronous and synchronous version. ``` GuideStarClient.SubscriptionKeys.Add(Domain.PremierV3, PREMIER_KEY); var premier = await PremierResource.GetOrganizationAsync(EIN); ``` All responses are defined in our API documentation, found at Premier API. To use Charity CheckSimilarly, the following code will return the Charity Check JSON document of an EIN as a string. ``` GuideStarClient.SubscriptionKeys.Add(Domain.CharityCheckV1, CHARITYCHECK_KEY); var charitycheck = CharityCheckResource.GetOrganization(EIN); ``` All responses are defined in our API documentation, found at Charity Check API. To use EssentialsThe Essentials resource takes a search payload as input instead of an EIN. For all relative search filters allowed in the payload, refer to the code example below and to the API documentation found at Essentials API. ``` string searchterms = ""; int from = 1; int size = 25; string sortby = "organization_name"; string[] state = { "ny" }; string zip = ""; int radius = 50; string[] msa = { "" }; string[] city = { "" }; string[] county = { "" }; string[] profilelevel = { "Platinum", "Bronze" }; string[] nteemajor = { "" }; string[] nteeminor = { "" }; string[] subsection = { "" }; string[] foundation = { "" }; bool bmfstatus = true; bool pub78verified = true; int minemployees = 0; int maxemployees = 1000000000; int minrevenue = 0; int maxrevenue = 1000000000; int minexpenses = 0; int maxexpesnes = 1000000000; int minassets = 0; int maxassets = 100000000; string ESSENTIALS_KEY = "Your key here"; var payload = SearchPayloadBuilder.Create() .WithSearchTerms(searchterms) //search terms is a string used as a keyword search .From(from) //from is an integer to specify which record to start at for pagination .Size(size) //size is an integer to specify how many records to return .Sort(SortBuilder => { SortBuilder.SortBy(sortby); //sortby is a string to specify how to sort the records SortBuilder.SortByAscending(); //sortbyascending is used to sort the records alphabectically. The sort is set to true when this is present in the form. //SortBuilder.SortByDescending(); //sortbydescending is used to sort the records reverse alphabectically. The sort is set to true when this is present in the form. } ) .Filters(filterBuilder => { filterBuilder.Geography(geographyBuilder => { geographyBuilder.HavingState(state); //state is a string array to filter on multiple states //geographyBuilder.HavingZipCode(zip); //zip is a string to filter on 1 zip code geographyBuilder.WithinZipRadius(radius); //radius is an integer to include up to 50 miles from the zip geographyBuilder.HavingMSA(msa); //msa is an string array to filter on multiple msa codes geographyBuilder.HavingCity(city); //city is a string array to filter on multiple cities geographyBuilder.HavingCounty(county); //county is a string array to filter on multiple counties } ); filterBuilder.Organization(OrganizationBuilder => { OrganizationBuilder.HavingProfileLevel(profilelevel); //profilelevel is a string array to filter on the seal of transparency level OrganizationBuilder.HavingNTEEMajorCode(nteemajor); //nteemajor is a string array to filter on major ntee codes OrganizationBuilder.HavingNTEEMinorCode(nteeminor); //nteeminor is a string array to filter on minor ntee codes OrganizationBuilder.HavingSubsectionCode(subsection); //subsection is a string array to filer on subsection codes OrganizationBuilder.HavingFoundationCode(foundation); //foundation is a string array to filer on foundation codes OrganizationBuilder.IsOnBMF(bmfstatus); //bmfstatus is a boolean to filter on bmf status OrganizationBuilder.IsPub78Verified(pub78verified); //pub78verified is a boolean to filter on verification on pub 78 OrganizationBuilder.AffiliationType(AffiliationTypeBuilder => { //AffiliationTypeBuilder.OnlyParents(); //only parents is used to filter parent organizations. The search is set to true when this is present in the form. //AffiliationTypeBuilder.OnlySubordinate(); //only subordinate is used to filter subordinate organizations. The search is set to true when this is present in the form. //AffiliationTypeBuilder.OnlyIndependent(); //only independent is used to filter independent organizations. The search is set to true when this is present in the form. //AffiliationTypeBuilder.OnlyHeadquarters(); //only headquarters is used to filter headquarter organizations. The search is set to true when this is present in the form. } ); OrganizationBuilder.SpecificExclusions(SpecificExclusionBuilder => { SpecificExclusionBuilder.ExcludeRevokedOrganizations(); //exclude revoked organizations is used to filter out any revoked organizations. The search is set to true when this is present in the form. SpecificExclusionBuilder.ExcludeDefunctOrMergedOrganizations(); //exclude defunct or merged organizations is used to filter out any defunct or merged organizations. the search is set to true when this is present in the form. } ); OrganizationBuilder.NumberOfEmployees(MinMaxBuilder => { MinMaxBuilder.HavingMaximum(maxemployees); //maxemployees is an integer to include organizations with the number of employees less than the specified amount MinMaxBuilder.HavingMinimum(minemployees); //minemployees is an integer to include organizations with the number of employees more than the specified amount } ); OrganizationBuilder.FormTypes(FormTypeBuilder => { FormTypeBuilder.OnlyF990(); //only f990 is used to filter organizations who filed a form 990. The search is set to true when this is present in the form. //FormTypeBuilder.OnlyF990PF(); //only f990pf is used to filter organizations who filed a form 990-pf. The search is set to true when this is present in the form. //FormTypeBuilder.Only990tRequired(); //only f990t required is used to filter organizations who are required to filed a form 990-t. The search is set to true when this is present in the form. } ); OrganizationBuilder.Audits(AuditBuilder => { AuditBuilder.HavingA133Audit(); // having a133 audit is used to filter organizations who have completed an a133 audit. The search is set to true when this is present in the form. } ); } ); filterBuilder.Financials(finBuilder => { finBuilder.Form990Assets(assets => { assets.HavingMaximum(maxassets); //maxassets is an integer to include organizations with assets less than the specified amount assets.HavingMinimum(minassets); //minassets is an integer to include organizations with assets more than the specified amount } ); finBuilder.Form990Expenses(expenses => { expenses.HavingMaximum(maxexpesnes); //maxexpenses is an integer to include organizations with expenses less than the specified amount expenses.HavingMinimum(minexpenses); //minexpenses is an integer to include organizations with expenses more than the specified amount } ); finBuilder.Form990Revenue(revenue => { revenue.HavingMaximum(maxrevenue); //maxrevenue is an integer to include organizations with revenue less than the specified amount revenue.HavingMinimum(minrevenue); //minrevenue is an integer to include organizations with revenue more than the specified amount } ); } ); } ) .Build(); GuideStarClient.SubscriptionKeys.Add(Domain.EssentialsV2, ESSENTIALS_KEY); var essentials = EssentialsResource.GetOrganization(payload); ``` The return is a JSON collection of organization info that matches the payload parameters. All Essentials responses are defined at Essentials API There is a demonstration website in ASP.NET Core MVC to show example usage of the SDK. ## GitHub Repo Find the example project on our GitHub. ## Managing API Keys API keys are stored and retrieved using the Microsoft Secrets Manager tool. View a sample secrets.json file below. ``` { "Keys:CharityCheckKey": "KEY", "Keys:CharityCheckPDFKey": "KEY", "Keys:EssentialsKey": "KEY", "Keys:PremierKey": "KEY" } ``` # 8.30.2023 - Grants API bug fix # 8.29.2023 - Essentials v3 has more data and search capabilities # 8.21.23 - GeoSearch and GeoChildren queries added to Taxonomy GraphQL API Two new queries are now available in the Taxonomy API: `GeoSearch` and `GeoChildren` . These queries return codes from the GeoNames taxonomy that can be used to identify geographic information. # 7.19.23 - NTEE to PCS crosswalk available in Taxonomy GraphQL API # 7.17.23 - Additional Demographics status message available in Demographics and Premier APIs # 5.24.2023 - Demographics status now available in Premier API v3; Essentials API bug fixes # 5.19.2023 - Essentials v3 bug fix # 5.15.2023 - Demographics API released # 3.27.2023 - Taxonomy GraphQL API released This data supports recent California regulations requiring charity fundraising platforms to ensure that nonprofits are in good standing in California in order to distribute donations to them. A sample of the California endpoint is below, and additional details can be found in the user guide. Request access to try it out, and visit the California Endpoint user guide to learn more. We released a fix so that when funder_key is entered as the input for the funder_id parameter, it returns the appropriate 200 response. * New fields available in the response, below: Field Name | Example | Description | | --- | --- | --- | group_exemption | 0000 | A group exemption number is a four-digit number assigned by the IRS to the central/parent organization of a group with a group exemption letter | leader_name | <NAME> | Name of the leader | leader_title | Chief Executive Officer | Title of the leader | congressional_district | District 10, NY | Congressional district of the organization's address | * Existing fields with better data coverage, below: Field Name | Example | Description | | --- | --- | --- | subsection_code | 03 | IRS subsection code of the organization | subsection_code_description | 501(c)(3) Public Charity | Description of IRS subsection code | foundation_code | 15 | Foundation code that describes the organization | foundation_code_description | Organization which receives a substantial part of its support from a governmental unit or the general public | Description of foundation code | form_type | EZ | Tax form filing type | fiscal_year | 2021 | Fiscal year of the most recent tax filing | total_revenue | 49660.0 | Most recent year total revenue | total_expenses | 28863.0 | Most recent year total expenses | total_assets | 172969.0 | Most recent year total assets | * New filter to find all subordinate organizations with a group exemption code: ``` { "filters": { "organization": { "group_exemption": [5378] } } } ``` ``` { "code": 200, "message": "Request was processed successfully!", "took": 15, "time": "2023-08-29 13:46:48Z", "results_count": 4, "page_count": 1, "errors": [], "hits": [ { "organization": { "organization_id": "7414365", "ein": "34-6516654", "organization_name": "United Way of Greater Cleveland", "also_known_as": "United Way", "group_exemption": "5378", "mission": "United Way of Greater Cleveland mobilizes people and resources by creating solutions that improve lives and our community.", "website_url": "http://www.unitedwaycleveland.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=9067411&approved=True", "profile_level": "Gold", "profile_year": 2023, "profile_link": "https://www.guidestar.org/profile/34-6516654", "profile_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-GOLD2023-seal.svg", "leader_name": "<NAME>", "leader_title": "President & CEO", "contact_name": "Ms. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(216) 436-2208", "contact_title": "Proposal Manager/Grant Writer", "number_of_employees": "146", "ruling_year": 1960 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": true, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": true, "subordinate": false, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "1331 Euclid Ave", "address_line_2": "", "city": "Cleveland", "state": "OH", "zip": "44115", "msa": "OH - Cleveland", "congressional_district": "District 11, OH", "county": "Cuyahoga, OH", "latitude": 41.5009, "longitude": -81.6823 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" }, { "subject_code": "SS070400", "subject_code_description": "Homeless shelters" }, { "subject_code": "SS070100", "subject_code_description": "Supportive housing" }, { "subject_code": "SS070000", "subject_code_description": "Shelter and residential care" }, { "subject_code": "SS050300", "subject_code_description": "Youth mentoring" }, { "subject_code": "SS050000", "subject_code_description": "Youth development" }, { "subject_code": "SS040000", "subject_code_description": "Family services" }, { "subject_code": "SS000000", "subject_code_description": "Human services" }, { "subject_code": "SN050800", "subject_code_description": "Financial counseling" }, { "subject_code": "SN050000", "subject_code_description": "Financial services" }, { "subject_code": "SN020302", "subject_code_description": "Job training" }, { "subject_code": "SN020300", "subject_code_description": "Employment" }, { "subject_code": "SN020000", "subject_code_description": "Economic development" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SM020000", "subject_code_description": "Food security" }, { "subject_code": "SM000000", "subject_code_description": "Agriculture, fishing and forestry" }, { "subject_code": "SJ000000", "subject_code_description": "Public safety" }, { "subject_code": "SE130000", "subject_code_description": "Public health" }, { "subject_code": "SE120504", "subject_code_description": "Substance abuse treatment" }, { "subject_code": "SE120500", "subject_code_description": "Addiction services" }, { "subject_code": "SE120200", "subject_code_description": "Community mental health care" }, { "subject_code": "SE120000", "subject_code_description": "Mental health care" }, { "subject_code": "SE050100", "subject_code_description": "Health care clinics" }, { "subject_code": "SE050000", "subject_code_description": "Out-patient medical care" }, { "subject_code": "SE040200", "subject_code_description": "Community health care" }, { "subject_code": "SE040000", "subject_code_description": "In-patient medical care" }, { "subject_code": "SE030700", "subject_code_description": "Patient-centered care" }, { "subject_code": "SE030000", "subject_code_description": "Health care administration and financing" }, { "subject_code": "SE000000", "subject_code_description": "Health" }, { "subject_code": "SB100000", "subject_code_description": "Early childhood education" }, { "subject_code": "SB090200", "subject_code_description": "College preparation" }, { "subject_code": "SB090100", "subject_code_description": "Out-of-school learning" }, { "subject_code": "SB090000", "subject_code_description": "Education services" }, { "subject_code": "SB070000", "subject_code_description": "Adult education" }, { "subject_code": "SB030000", "subject_code_description": "Elementary and secondary education" }, { "subject_code": "SB000000", "subject_code_description": "Education" } ], "population_served_codes": [ { "population_served_code": "PJ070000", "population_served_description": "Veterans" }, { "population_served_code": "PJ000000", "population_served_description": "Work status and occupations" }, { "population_served_code": "PH030000", "population_served_description": "Substance abusers" }, { "population_served_code": "PH020300", "population_served_description": "Terminally ill people" }, { "population_served_code": "PH020100", "population_served_description": "People with HIV/AIDS" }, { "population_served_code": "PH020000", "population_served_description": "People with diseases and illnesses" }, { "population_served_code": "PH010400", "population_served_description": "People with psychosocial disabilities" }, { "population_served_code": "PH010100", "population_served_description": "People with physical disabilities" }, { "population_served_code": "PH010000", "population_served_description": "People with disabilities" }, { "population_served_code": "PH000000", "population_served_description": "Health" }, { "population_served_code": "PG060100", "population_served_description": "Victims of crime and abuse" }, { "population_served_code": "PG060000", "population_served_description": "Victims and oppressed people" }, { "population_served_code": "PG040000", "population_served_description": "Incarcerated people" }, { "population_served_code": "PG030200", "population_served_description": "Low-income people" }, { "population_served_code": "PG030100", "population_served_description": "Homeless people" }, { "population_served_code": "PG030000", "population_served_description": "Economically disadvantaged people" }, { "population_served_code": "PG010000", "population_served_description": "Immigrants and migrants" }, { "population_served_code": "PG000000", "population_served_description": "Social and economic status" }, { "population_served_code": "PD050000", "population_served_description": "Caregivers" }, { "population_served_code": "PD020400", "population_served_description": "Single parents" }, { "population_served_code": "PD020000", "population_served_description": "Parents" }, { "population_served_code": "PD010000", "population_served_description": "Families" }, { "population_served_code": "PD000000", "population_served_description": "Family relationships" }, { "population_served_code": "PC050200", "population_served_description": "Men" }, { "population_served_code": "PC050100", "population_served_description": "Boys" }, { "population_served_code": "PC050000", "population_served_description": "Men and boys" }, { "population_served_code": "PC040200", "population_served_description": "Women" }, { "population_served_code": "PC040100", "population_served_description": "Girls" }, { "population_served_code": "PC040000", "population_served_description": "Women and girls" }, { "population_served_code": "PC010000", "population_served_description": "LGBTQ people" }, { "population_served_code": "PC000000", "population_served_description": "Sexual identity" }, { "population_served_code": "PA020300", "population_served_description": "Seniors" }, { "population_served_code": "PA020100", "population_served_description": "Young adults" }, { "population_served_code": "PA020000", "population_served_description": "Adults" }, { "population_served_code": "PA010400", "population_served_description": "Adolescents" }, { "population_served_code": "PA010200", "population_served_description": "Children" }, { "population_served_code": "PA010100", "population_served_description": "Infants and toddlers" }, { "population_served_code": "PA010000", "population_served_description": "Children and youth" }, { "population_served_code": "PA000000", "population_served_description": "Age groups" } ], "ntee_codes": [ { "ntee_code": "T70", "ntee_code_description": "Fund Raising Organizations That Cross Categories includes Community Funds/Trusts and Federated Giving Programs) e.g. United Way" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 18584237.0, "total_expenses": 18261123.0, "total_assets": 37317556.0 }, "bmf_gross_receipts": 18648897.0, "bmf_assets": 37317556.0, "required_to_file_990t": false, "a_133_audit_performed": true }, "dates": { "seal_last_modified": "2023-05-26T10:02:58.0000000", "profile_last_modified": "2023-05-31T07:43:15.0000000", "dei_last_modified": "2023-05-26T00:00:00.0000000", "financials_last_modified": "2023-06-23T09:00:47.0000000", "last_modified": "2023-07-10T17:03:00.0000000" } }, { "organization": { "organization_id": "9871605", "ein": "84-2305005", "organization_name": "United Way of Greater Cleveland Fund", "also_known_as": "UNITED WAY OF GREATER CLEVELAND PHI", "group_exemption": "5378", "mission": "TO SUPPORT THE PROGRAMS AND OPERATIONS OF UNITED WAY OF GREATER CLEVELAND, A RELATED 501(C)(3) ORGANIZATION.", "website_url": "", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/84-2305005", "profile_logo": "", "leader_name": "", "leader_title": "", "contact_name": "", "contact_email": "", "contact_phone": "", "contact_title": "", "number_of_employees": "", "ruling_year": 1960 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "1331 Euclid Ave", "address_line_2": "", "city": "Cleveland", "state": "OH", "zip": "44115", "msa": "OH - Cleveland", "congressional_district": "District 11, OH", "county": "Cuyahoga, OH", "latitude": 41.5009, "longitude": -81.6823 }, "taxonomies": { "subject_codes": [ { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "T70", "ntee_code_description": "Fund Raising Organizations That Cross Categories includes Community Funds/Trusts and Federated Giving Programs) e.g. United Way" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "EZ", "fiscal_year": 2022, "total_revenue": 0.0, "total_expenses": 0.0, "total_assets": 0.0 }, "bmf_gross_receipts": 0.0, "bmf_assets": 1.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "", "profile_last_modified": "", "dei_last_modified": "", "financials_last_modified": "2023-06-23T09:01:21.0000000", "last_modified": "2023-06-23T09:01:21.0000000" } }, { "organization": { "organization_id": "7052957", "ein": "20-5575556", "organization_name": "UNITED WAY OF GEAUGA COUNTY (dba)", "also_known_as": "United Way Services of Geauga County", "group_exemption": "5378", "mission": "United Way Servcies of Geauqa County unites people and resources to improve lives.", "website_url": "www.uwsgc.org", "logo_url": "", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/20-5575556", "profile_logo": "", "leader_name": "<NAME>", "leader_title": "", "contact_name": "<NAME>", "contact_email": "<EMAIL>", "contact_phone": "", "contact_title": "", "number_of_employees": "0", "ruling_year": 1960 }, "properties": { "bmf_status": true, "pub78_verified": true, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": false, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "209 Center St Unit H", "address_line_2": "", "city": "Chardon", "state": "OH", "zip": "44024", "msa": "OH - Cleveland", "congressional_district": "District 14, OH", "county": "Geauga, OH", "latitude": 41.5834, "longitude": -81.2091 }, "taxonomies": { "subject_codes": [ { "subject_code": "SN030000", "subject_code_description": "Community improvement" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SA080000", "subject_code_description": "Humanities" }, { "subject_code": "SA000000", "subject_code_description": "Arts and culture" }, { "subject_code": "SD020000", "subject_code_description": "Foundations" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "T70", "ntee_code_description": "Fund Raising Organizations That Cross Categories includes Community Funds/Trusts and Federated Giving Programs) e.g. United Way" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2022, "total_revenue": 1113190.0, "total_expenses": 899989.0, "total_assets": 1438558.0 }, "bmf_gross_receipts": 1113190.0, "bmf_assets": 1438558.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2016-07-08T19:00:10.0000000", "profile_last_modified": "2014-07-08T13:07:05.0000000", "dei_last_modified": "", "financials_last_modified": "2023-06-23T11:00:41.0000000", "last_modified": "2023-06-23T11:00:41.0000000" } }, { "organization": { "organization_id": "7164668", "ein": "23-7110762", "organization_name": "United Way of Medina", "also_known_as": "United Way of Medina County", "group_exemption": "5378", "mission": "Since 1929, the United Way of Medina County has maintained a tradition of helping those in need, assessing the needs of the community, raising funds and distributing financial support to local program partners. Since 2014 our Community Impact focus has been early childhood development to prepare children to learn when they start school; summer reinforcement to prevent slide in children requiring extra academic support; youth engagement to help students learn coping skills and reduce the behaviors leading to suicide and drug use; and the distribution of weekend food support for low income students who receive free or reduced lunch.", "website_url": "http://www.unitedwaymedina.org", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=5318821&approved=True", "profile_level": "None", "profile_year": null, "profile_link": "https://www.guidestar.org/profile/23-7110762", "profile_logo": "", "leader_name": "<NAME>", "leader_title": "Interim Director", "contact_name": "Mrs. <NAME>", "contact_email": "<EMAIL>", "contact_phone": "(330) 636-0062", "contact_title": "Finance Coordinator", "number_of_employees": "0", "ruling_year": 1960 }, "properties": { "bmf_status": false, "pub78_verified": false, "allow_online_giving": true, "dei_submitted": false, "revoked": false, "defunct_or_merged": true, "relationship_type": { "parent": false, "subordinate": true, "independent": false, "headquarters": false } }, "geography": { "address_line_1": "728 E Smith Rd", "address_line_2": "", "city": "Medina", "state": "OH", "zip": "44256", "msa": "OH - Cleveland", "congressional_district": "District 16, OH", "county": "Medina, OH", "latitude": 41.1353, "longitude": -81.8491 }, "taxonomies": { "subject_codes": [ { "subject_code": "SA000000", "subject_code_description": "Arts and culture" }, { "subject_code": "SN000000", "subject_code_description": "Community and economic development" }, { "subject_code": "SD040000", "subject_code_description": "Nonprofits" }, { "subject_code": "SD000000", "subject_code_description": "Philanthropy" } ], "population_served_codes": [], "ntee_codes": [ { "ntee_code": "A12", "ntee_code_description": "Fund Raising and/or Fund Distribution" } ], "subsection_code": { "subsection_code": "03", "subsection_code_description": "501(c)(3) Public Charity" }, "foundation_code": { "foundation_code": "15", "foundation_code_description": "Organization which receives a substantial part of its support from a governmental unit or the general public" } }, "financials": { "most_recent_year": { "form_type": "990", "fiscal_year": 2021, "total_revenue": 0.0, "total_expenses": 0.0, "total_assets": 0.0 }, "bmf_gross_receipts": 633353.0, "bmf_assets": 804785.0, "required_to_file_990t": false, "a_133_audit_performed": false }, "dates": { "seal_last_modified": "2021-10-07T19:00:02.0000000", "profile_last_modified": "2019-10-07T09:46:57.0000000", "dei_last_modified": "2019-10-07T09:39:31.0000000", "financials_last_modified": "2022-06-27T21:00:21.0000000", "last_modified": "2022-06-27T21:00:21.0000000" } } ] } ``` added Two new queries are now available in the Taxonomy API: `GeoSearch` and `GeoChildren` . These queries return codes from the GeoNames taxonomy that can be used to identify geographic information. GeoName IDs can be used as search parameters to filter the Grants and News APIs by geographic areas. See below for examples of these queries and results. More information can be found in the Taxonomy API docs and user guides. ### GeoSearch The GeoSearch query uses a keyword input to return relevant results from the GeoNames taxonomy, and can be filtered by geographic level. ``` { geoSearch (searchTerms: "ohio", geoLevel:ADM1) { data { id name displayName geoLevel countryCode } } } ``` ``` { "data": { "geoSearch": { "data": [ { "id": 5165418, "name": "Ohio", "displayName": "Ohio (United States)", "geoLevel": "ADM1", "countryCode": "US" } ] } } } ``` ### GeoChildren The GeoChildren query returns the child terms for a given GeoNames code. ``` { geoChildren (parentId: 5165418, parentLevel: ADM1, childLevel: ADM2) { data { id geoLevel name displayName } } } ``` ``` { "data": { "geoChildren": { "data": [ { "id": 4505006, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Adams County (Ohio, United States)" }, { "id": 5145576, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Allen County (Ohio, United States)" }, { "id": 5146062, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Ashland County (Ohio, United States)" }, { "id": 5146092, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Ashtabula County (Ohio, United States)" }, { "id": 4505546, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Athens County (Ohio, United States)" }, { "id": 5146199, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Auglaize County (Ohio, United States)" }, { "id": 5147012, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Belmont County (Ohio, United States)" }, { "id": 4507215, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Brown County (Ohio, United States)" }, { "id": 4507568, "geoLevel": "ADM2", "name": "Butler County", "displayName": "Butler County (Ohio, United States)" }, { "id": 5149311, "geoLevel": "ADM2", "name": "Carroll County", "displayName": "Carroll County (Ohio, United States)" }, { "id": 5149757, "geoLevel": "ADM2", "name": "Champaign County", "displayName": "Champaign County (Ohio, United States)" }, { "id": 4508810, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Clark County (Ohio, United States)" }, { "id": 4508924, "geoLevel": "ADM2", "name": "Clermont County", "displayName": "Clermont County (Ohio, United States)" }, { "id": 4508988, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Clinton County (Ohio, United States)" }, { "id": 5150853, "geoLevel": "ADM2", "name": "Columbiana County", "displayName": "Columbiana County (Ohio, United States)" }, { "id": 5151190, "geoLevel": "ADM2", "name": "Coshocton County", "displayName": "Coshocton County (Ohio, United States)" }, { "id": 5151374, "geoLevel": "ADM2", "name": "Crawford County", "displayName": "Crawford County (Ohio, United States)" }, { "id": 5151606, "geoLevel": "ADM2", "name": "Cuyahoga County", "displayName": "Cuyahoga County (Ohio, United States)" }, { "id": 5151705, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Darke County (Ohio, United States)" }, { "id": 5151865, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Defiance County (Ohio, United States)" }, { "id": 5151896, "geoLevel": "ADM2", "name": "Delaware County", "displayName": "Delaware County (Ohio, United States)" }, { "id": 5153362, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Erie County (Ohio, United States)" }, { "id": 4511295, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Fairfield County (Ohio, United States)" }, { "id": 4511521, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Fayette County (Ohio, United States)" }, { "id": 4512214, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Franklin County (Ohio, United States)" }, { "id": 5155347, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Fulton County (Ohio, United States)" }, { "id": 4512438, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Gallia County (Ohio, United States)" }, { "id": 5155556, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Geauga County (Ohio, United States)" }, { "id": 4513280, "geoLevel": "ADM2", "name": "Greene County", "displayName": "Greene County (Ohio, United States)" }, { "id": 5156615, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Guernsey County (Ohio, United States)" }, { "id": 4513583, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Hamilton County (Ohio, United States)" }, { "id": 5156770, "geoLevel": "ADM2", "name": "Hancock County", "displayName": "Hancock County (Ohio, United States)" }, { "id": 5156844, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Hardin County (Ohio, United States)" }, { "id": 5156975, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Harrison County (Ohio, United States)" }, { "id": 5157338, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Henry County (Ohio, United States)" }, { "id": 4514204, "geoLevel": "ADM2", "name": "Highland County", "displayName": "Highland County (Ohio, United States)" }, { "id": 4514358, "geoLevel": "ADM2", "name": "Hocking County", "displayName": "Hocking County (Ohio, United States)" }, { "id": 5157783, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Holmes County (Ohio, United States)" }, { "id": 5158275, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Huron County (Ohio, United States)" }, { "id": 4515328, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Jackson County (Ohio, United States)" }, { "id": 5159079, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Jefferson County (Ohio, United States)" }, { "id": 5159891, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Knox County (Ohio, United States)" }, { "id": 5160090, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Lake County (Ohio, United States)" }, { "id": 4516351, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Lawrence County (Ohio, United States)" }, { "id": 5160740, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Licking County (Ohio, United States)" }, { "id": 5161156, "geoLevel": "ADM2", "name": "Logan County", "displayName": "Logan County (Ohio, United States)" }, { "id": 5161272, "geoLevel": "ADM2", "name": "Lorain County", "displayName": "Lorain County (Ohio, United States)" }, { "id": 5161413, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Lucas County (Ohio, United States)" }, { "id": 4517365, "geoLevel": "ADM2", "name": "Madison County", "displayName": "Madison County (Ohio, United States)" }, { "id": 5161640, "geoLevel": "ADM2", "name": "Mahoning County", "displayName": "Mahoning County (Ohio, United States)" }, { "id": 5161911, "geoLevel": "ADM2", "name": "Marion County", "displayName": "Marion County (Ohio, United States)" }, { "id": 5162517, "geoLevel": "ADM2", "name": "Medina County", "displayName": "Medina County (Ohio, United States)" }, { "id": 4518038, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Meigs County (Ohio, United States)" }, { "id": 5162679, "geoLevel": "ADM2", "name": "Mercer County", "displayName": "Mercer County (Ohio, United States)" }, { "id": 5162774, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Miami County (Ohio, United States)" }, { "id": 4518563, "geoLevel": "ADM2", "name": "Monroe County", "displayName": "Monroe County (Ohio, United States)" }, { "id": 4518598, "geoLevel": "ADM2", "name": "Montgomery County", "displayName": "Montgomery County (Ohio, United States)" }, { "id": 4518677, "geoLevel": "ADM2", "name": "Morgan County", "displayName": "Morgan County (Ohio, United States)" }, { "id": 5163509, "geoLevel": "ADM2", "name": "Morrow County", "displayName": "Morrow County (Ohio, United States)" }, { "id": 4519300, "geoLevel": "ADM2", "name": "Muskingum County", "displayName": "Muskingum County (Ohio, United States)" }, { "id": 4519808, "geoLevel": "ADM2", "name": "Noble County", "displayName": "Noble County (Ohio, United States)" }, { "id": 5165803, "geoLevel": "ADM2", "name": "Ottawa County", "displayName": "Ottawa County (Ohio, United States)" }, { "id": 5166256, "geoLevel": "ADM2", "name": "Paulding County", "displayName": "Paulding County (Ohio, United States)" }, { "id": 4521093, "geoLevel": "ADM2", "name": "Perry County", "displayName": "Perry County (Ohio, United States)" }, { "id": 4521196, "geoLevel": "ADM2", "name": "Pickaway County", "displayName": "Pickaway County (Ohio, United States)" }, { "id": 4521245, "geoLevel": "ADM2", "name": "Pike County", "displayName": "Pike County (Ohio, United States)" }, { "id": 5167284, "geoLevel": "ADM2", "name": "Portage County", "displayName": "Portage County (Ohio, United States)" }, { "id": 4521907, "geoLevel": "ADM2", "name": "Preble County", "displayName": "Preble County (Ohio, United States)" }, { "id": 5167574, "geoLevel": "ADM2", "name": "Putnam County", "displayName": "Putnam County (Ohio, United States)" }, { "id": 5168041, "geoLevel": "ADM2", "name": "Richland County", "displayName": "Richland County (Ohio, United States)" }, { "id": 4522889, "geoLevel": "ADM2", "name": "Ross County", "displayName": "Ross County (Ohio, United States)" }, { "id": 5170698, "geoLevel": "ADM2", "name": "Sandusky County", "displayName": "Sandusky County (Ohio, United States)" }, { "id": 4524221, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Scioto County (Ohio, United States)" }, { "id": 5171643, "geoLevel": "ADM2", "name": "Seneca County", "displayName": "Seneca County (Ohio, United States)" }, { "id": 5171871, "geoLevel": "ADM2", "name": "Shelby County", "displayName": "Shelby County (Ohio, United States)" }, { "id": 5172936, "geoLevel": "ADM2", "name": "Stark County", "displayName": "Stark County (Ohio, United States)" }, { "id": 5173386, "geoLevel": "ADM2", "name": "Summit County", "displayName": "Summit County (Ohio, United States)" }, { "id": 5174418, "geoLevel": "ADM2", "name": "Trumbull County", "displayName": "Trumbull County (Ohio, United States)" }, { "id": 5174499, "geoLevel": "ADM2", "name": "Tuscarawas County", "displayName": "Tuscarawas County (Ohio, United States)" }, { "id": 5174669, "geoLevel": "ADM2", "name": "Union County", "displayName": "Union County (Ohio, United States)" }, { "id": 5175012, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "<NAME> County (Ohio, United States)" }, { "id": 4527250, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Vinton County (Ohio, United States)" }, { "id": 4527624, "geoLevel": "ADM2", "name": "Warren County", "displayName": "Warren County (Ohio, United States)" }, { "id": 4527654, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Washington County (Ohio, United States)" }, { "id": 5175898, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Wayne County (Ohio, United States)" }, { "id": 5176872, "geoLevel": "ADM2", "name": "<NAME>", "displayName": "Williams County (Ohio, United States)" }, { "id": 5177229, "geoLevel": "ADM2", "name": "Wood County", "displayName": "Wood County (Ohio, United States)" }, { "id": 5177434, "geoLevel": "ADM2", "name": "Wyandot County", "displayName": "Wyandot County (Ohio, United States)" } ] } } } ``` Within the nteeMinor query in the Taxonomy API, a new object called pcsCrosswalk is now available. This returns the PCS code and name that corresponds with the searched NTEE code, where an equivalent is available. See an example of the new return below. ``` { "data": { "nteeMinor": { "data": [ { "key": "A51", "value": "Art Museums", "type": "ntee_minor", /*NEW*/ "pcsCrosswalk": { "code": "SA070100", "name": "Art museums", "exact_match": true } } ] } } } ``` Request access to try it out, and visit the Taxonomy API user guides to learn more. ``` demographics_status_nonprofit ``` has also been added to the Demographics and Premier APIs to provide guidance for nonprofits directly. If a nonprofit has not shared demographic information with Candid, the field will display "Your organization has not provided Candid demographics data. Please complete your Candid profile by visiting https://www.guidestar.org/UpdateNonprofitProfile." Learn more about demographic data and status messages in the Organizational demographic data guide. We have added a Demographics status message to the response of the Premier API v3. This field will describe whether an organization has shared information about their organizational demographics with Candid. The `demographics_status` field will be available in the "summary" section of the Premier API, and will have two possible responses: * "This organization has provided Candid Demographics data" * "This organization has not provided Candid Demographics data" If the organization has provided demographics data, it can be accessed in the "demographics" section of the Premier API. If the organization has not provided demographics data, the "demographics" section will be null. More information about organizational demographics data can be found in our user guide. ## Example of Demographics status field ``` "summary": { "organization_id": 6908122, "organization_name": "Candid", "ein": "13-1837418", "bridge_id": "", "address_line_1": "32 Old Slip", "address_line_2": "24th Floor", "city": "New York", "state": "NY", "zip": "10005", "county": "New York", "latitude": "40.706104", "longitude": "-74.008893", "fax": "(212)807-3677", "govt_registered_name": "Candid", "also_known_as": "The Foundation Center, Foundation Center, GuideStar, GuideStar USA", "fiscal_year_end": "Dec 31", "fiscal_year_start": "Jan 1", "affiliation_code": "3", "affiliation_description": "Independent - This code is used if the organization is an indepenedent organization or an independent auxiliary (i.e., not affiliated with a a National, Regional, or Geographic grouping of organizations).", "contact_name": "<NAME>", "contact_title": "Senior Director of Communications and Brand Awareness", "contact_email": "<EMAIL>", "contact_phone": "212-620-4230", "contact_fax": "212-807-3677", "gs_profile_update_level": "Platinum 2023", "gs_profile_update_level_logo": "https://www.guidestar.org/App_Themes/MainSite2/images/ProfilePageSvgs/profile-PLATINUM2023-seal.svg", "deductibility_code": "1", "deductibility_description": "Contributions are deductible, as provided by law", "donation_to_ein": "13-1837418", "donation_to_name": "Candid", "areas_served_narrative": "", "ruling_year": "", "gs_public_report": "https://www.guidestar.org/profile/13-1837418", "gs_pro_pdf": "https://apidata.guidestar.org/premier/v1/propdf/13-1837418", "gs_financial_trends_analysis_pdf": "https://apidata.guidestar.org/premier/v1/ftapdf/13-1837418", "impact_statement": "", "subsection_code": "03", "subsection_description": "501(c)(3) Public Charity", "keywords": "philanthropy, data, transparency, capacity building, research, education, foundations, foundation, charitable giving, data driven decisions, nonprofits, transparency, nonprofit sector, organizational effectiveness, organizational efficiency, nonprofit information hub, Forms 990, GuideStar, Foundation Center", "logo_url": "https://www.guidestar.org/ViewEdoc.aspx?eDocId=8987049&approved=True", "mission": "Candid gets you the information you need to do good.", "is_national_hq": false, /*NEW*/"demographics_status": "This organization has provided Candid Demographic Data" } ``` # Essentials API bug fixes We released 2 bugs fixes identified in our Essentials API: * Adjusted invalid last updated date and 500 Error message * Fixed issues with min/max ruling year and number of employees filters Please reach out to <EMAIL> with any questions. We released a fixed so that ruling year filters return the appropriate 200 response. * Reduce the burden on nonprofits to repeatedly provide demographic data * Streamline your grant application process by accessing pre-populated demographic data * Analyze the impact of your grantmaking and the composition of your grantmaking portfolio Build dynamic filtering capabilities to help users find causes that matter most to them. * Harness Candid's up to date taxonomy to enable users to explore the nonprofit sector. * Use GraphQL to get exactly the data you need in one API call * Combine with other Candid APIs to create a robust nonprofit data system. Candid at a glance Candid. . See the world. Make it better. Contact us Candid gets you the information you need to do good. Find us in your community Find Candid locations by entering zip code, city, state, or country Graph i QL Prettify Merge Copy History xxxxxxxxxx 1 { 2 3 } Query Variables Request Headers xxxxxxxxxx 1 xxxxxxxxxx 1 { 2 3 } xxxxxxxxxx Documentation Explorer ✕ ⚲ No Schema Available Explorer ✕ No Schema Available Candid. . Candid is a 501(c)(3) nonprofit organization, EIN 13-1837418 . Donations are tax-deductible. ©2023 Candid. All rights reserved. Terms of service . Foundation Center GuideStar Foundation Center and GuideStar are Candid. To receive support from our API Team, please open a support ticket by emailing: We will be in touch with you shortly. ## Share Your Feedback We would love to hear your thoughts, suggestions and more. Please share on our API Feedback Page. -1 +1 100 1234 8ball a ab abc abcd accept aerial-tramway airplane alarm-clock alien ambulance anchor angel anger angry anguished ant apple aquarius aries arrow-backward # Where can I find the status of the API? over 2 years ago by <NAME> You can contact Candid's API support team by either: * Using the bottom right-hand pop-up called API Support to submit your questions to * Email us directly at <EMAIL> Date: 2022-11-10 Categories: Tags: ## The best nonprofit search engine just got better. Users can make searches more relevant and real-time with access to new filters. * Power your nonprofit search for donors to find organizations they are most interested in using Candid's Philanthropy Classification System * Search for organizations with recently updated data to keep your records up to date. Never miss an update again. * Find organizations who have submitted demographic, equity and inclusion data to Candid to discover who to give to * Find and sort search results by location for users to discover organizations closest to them View the /essentials/v3 API docs to learn more. ## Expanded list of features include: Search features * Filter on Candid’s Philanthropy Classification System using subject and populations served facet * Filter for organizations who have submitted demographic, equity and inclusion data to Candid * Search for real-time updates using start and end dates when: * Organizations earn their seal * Organizations update their Candid profile * Organizations submit demographic data * Candid processes 990 financials posted from IRS sources * Search and sort organization results by the ruling year an organization became a registered nonprofit * Search and sort organization results by zip code distance to the user Data response * A restructured response makes it easier to display taxonomy descriptions and financials * Ruling year, profile year, profile link, and seal of transparency logo are provided in the response * DEI submitted flag is returned in the response * All modification dates are returned in the response I am a grant maker who wants to find organizations that updated their Candid profile over the last 7 days so that I know which organization records I need to update ``` { "filters": { "last_updated": { "start_date": "2022-11-10T00:00:00", "end_date": "2022-11-17T23:59:59", "date_type": "profile_last_modified" } } } ``` I am a grants manager who wants to see organizations who submitted demographic data to Candid last month so that I can update my records appropriately ``` { "filters": { "organization": { "properties": { "dei_submitted": true } }, "last_updated": { "start_date": "2022-10-01T00:00:00", "end_date": "2022-10-31T23:59:59", "date_type": "dei_last_modified" } } } ``` I am a donor who wants to find organizations serving specific subjects and populations that received their nonprofit ruling in the last 3 years so that I can discover new organizations to give to in the areas I care about ``` { "sort": { "sort_by": "ruling_year", "sort_order": "desc" }, "filters": { "organization": { "subject_codes": [ "SN04" ], "population_served_codes": [ "PG0302" ], "ruling_year": { "min": 2019, "max": 2022 } } } } ``` I am a grants manager who wants to automatically monitor grantee organizations when new data is available so that I can be alerted about/ automatically update all changes on grantees daily ``` { "filters": { "last_updated": { "start_date": "2022-11-01T00:00:00", "end_date": "2022-11-01T23:59:59", "date_type": "last_modified" } }, "search_terms": "22-2842846 83-2688014 27-1734337 81-3465689 25-1404779 01-0814204 02-0274509 02-0501917 13-3156445 43-1741457 " } ``` I am a donor who wants to find nonprofits closest to me who support my subject area of interest ``` { "sort": { "sort_by": "distance", "sort_order": "desc" }, "filters": { "geography": { "zip": 10005, "radius": 50 }, "organization": { "subject_codes": [ "SN04" ] } } } ``` I am a financial analyst who wants to find all financial updates for 990 EZ filers, last month, so that I can make sure my system of record is up to date ``` { "filters": { "financials": { "most_recent_year": { "form_types": { "f990ez": true } } }, "last_updated": { "date_type": "financials_last_modified", "start_date": "2022-10-01", "end_date": "2022-10-31" } } } ``` To display, pull, or process the organization's data changes, the Premier API should be called to get those details. Current Essentials API customers can upgrade to v3 at any time. Try it out for free and contact us to get a quote providerstringrequiredProvider's name to ensure respective eligibility criteria is applied.einarray of stringsrequiredA comma separated array of strings of up to 25 einsein*ADD string 200OK 400Bad Request 401Unauthorized 403Forbidden 404No Results Found 406Not Acceptable 429Too Many Requests 500Internal Server ErrorUpdated 6 months ago Did this page help you?YesNo Date: 2021-09-01 Categories: Tags: search_termsstringTerm(s) to search in Candid’s news sources.start_datedateThe oldest article publication date to search from in the format yyyy-MM-dd. Default is one month before today's date, and the earliest possible value is 2018-09-24. The start_date and end_date can be at most one year apart.end_datedateThe most recent article publication date to search to in the format yyyy-MM-dd. Default is today's date. The start_date and end_date can be at most one year apart.added_start_datedate-timeA filter, along with added_end_date, based on the date an article was added to the Candid News database, in the format yyyy-MM-ddTHH:mm:ss.fffffffZ. Default is one month before today's date. The added_start_date and added_end_date fields can be at most one year apart. The earliest added_start_date to search from is 2018-09-24added_end_datedate-timeA filter, along with added_start_date, based on the date an article was added to the Candid News database in the format yyyy-MM-ddTHH:mm:ss.fffffffZ. Default is today's date. The added_start_date and added_end_date fields can be at most one year apart.einsarray of stringsA list of up to 25 organization EINs each of which formatted with or without a dash. Multiple values should be joined using OR.einsADD stringorganizationsarray of stringsA list of up to 25 organization names. Multiple values should be joined using OR.organizationsADD stringlocationsarray of integersA list of up to 25 geoName IDs for locations. Multiple values should be joined using OR. Contact Candid for a JSON file of all Candid-supported GeoName IDs.locationsADD integersubjectsarray of stringsA list of up to 25 Candid Philanthropy Classification System (PCS) Subject Facet codes (eg. ST000000, SR040000, SA010200, etc). Top-level PCS codes will include searches for all related child codes. Multiple values should be joined using OR.subjectsADD stringpopulationsarray of stringsA list of up to 25 Candid Philanthropy Classification System (PCS) Population Facet codes (eg. PC000000, PG010000, PE050000, etc). Top-level PCS codes will include searches for all related child codes. Multiple values should be joined using OR.populationsADD stringpeoplearray of stringsA list of up to 25 names of people by which to filter news articles. Multiple values should be joined using OR.peopleADD stringsources_includearray of stringsA list of up to 25 names of news source to include. Accepts up to 25, multiple values should be joined using OR.sources_includeADD stringsources_excludearray of stringsA list of up to 25 names of news sources to exclude. Accepts up to 25, multiple values should be joined using OR.sources_excludeADD stringstaff_change_mentionedbooleanIndicates whether to return articles containing mentions of staff changes. If true, only articles that mention staff changes will be returned. If false, only articles that do not mention staff changes will be returned. If null, articles will be returned regardless of staff changes mentioned.truefalserfp_mentionedbooleanIndicates whether to return articles containing mentions of rfp. If true, only articles containing mentions of RFPs will be returned. If false, only articles not containing mentions of RFPs will be returned. If null, articles will be returned regardless of RFPs mentioned.truefalsegrant_mentionedbooleanIndicates whether to return articles containing mentions of grants. If true, only articles containing mentions of grants will be returned. If false, only articles not containing mentions of grants will be returned. If null, articles will be returned regardless of grants mentioned.truefalsefilter_operatorstringDetermines the union type for searches for the following parameters Subjects, Populations, Locations, People, and Organizations. Default is AND. Note that inter-array parameter values are not affected by the filter operator.ANDORadvisory_contentbooleanAdvisory content is flagged for organizations or people in the social sector that may or may not require due diligence. True = Only return articles flagged as advisory content. False = Do not return articles flagged as advisory content. Null = Return articles regardless of advisory content.truefalsesort_orderstringThe direction to sort the results by publication date, either "asc" (ascending) or "desc" (descending). Default is desc.descascpageintegerSelect the page number for search results. If page is not specified, it defaults to 1. The maximum page value is the total number of results divided by 25. 200OK 400Bad Request 401Unauthorized 403Forbidden 404No Results Found 406Not Acceptable 429Too Many Requests 500Internal Server ErrorUpdated 3 months ago Did this page help you?YesNo
async_cache
rust
Rust
Crate async_cache === AsyncCache is a cache system that automatically updates and deletes entries using async fetchers. Usage --- To use AsyncCache, you need to implement the `Fetcher` trait for the type you want to cache. Then you can use the `Options` struct to configure the cache and create an instance of `AsyncCache`. ``` use async_cache::{AsyncCache, Fetcher, Options}; use faststr::FastStr; use std::time::Duration; #[derive(Clone)] struct MyValue(u32); #[derive(Clone)] struct MyFetcher; #[async_trait::async_trait] impl Fetcher<MyValue> for MyFetcher { type Error = anyhow::Error; //// The implementation of fetch function should return the value associated with a key, or an error if it fails. async fn fetch(&self, key: FastStr) -> Result<MyValue, Self::Error> { // Your implementation here Ok(MyValue(100)) } } let mut cache = Options::new(Duration::from_secs(10), MyFetcher).with_expire(Some(Duration::from_secs(10))) .build(); // Now you can use the cache to get and set values let key = FastStr::from("key"); let val = cache.get_or_set(key.clone(), MyValue(50)); assert_eq!(val, MyValue(50)); let other_val = cache.get(key).await.unwrap(); assert_eq!(other_val, MyValue(50)); ``` Design --- AsyncCache uses async-singleflight to reduce redundant load on underlying fetcher, requests from different future tasks with the same key will only trigger a single fetcher call. It also provides a few channels to notify the client of the cache when the cache is updated or there was an error with a fetch. `AsyncCache` is thread-safe and can be cloned and shared across tasks. Example --- ``` use async_cache::{AsyncCache, Options}; use faststr::FastStr; use std::time::Duration; #[tokio::main] async fn main() { let interval = Duration::from_millis(100); let options = Options::new(interval, GitHubFetcher::new()) .with_expire(Some(Duration::from_secs(30))); let cache = options.build(); let key = FastStr::from("your key"); match cache.get(key).await { Some(v) => println!("value: {}", v), None => println!("first fetch failed"), } tokio::time::delay_for(Duration::from_secs(5)).await; match cache.get(key).await { Some(v) => println!("value: {}", v), None => println!("fetch data failed"), } } ``` Structs --- * AsyncCache * Options Traits --- * Fetcher Crate async_cache === AsyncCache is a cache system that automatically updates and deletes entries using async fetchers. Usage --- To use AsyncCache, you need to implement the `Fetcher` trait for the type you want to cache. Then you can use the `Options` struct to configure the cache and create an instance of `AsyncCache`. ``` use async_cache::{AsyncCache, Fetcher, Options}; use faststr::FastStr; use std::time::Duration; #[derive(Clone)] struct MyValue(u32); #[derive(Clone)] struct MyFetcher; #[async_trait::async_trait] impl Fetcher<MyValue> for MyFetcher { type Error = anyhow::Error; //// The implementation of fetch function should return the value associated with a key, or an error if it fails. async fn fetch(&self, key: FastStr) -> Result<MyValue, Self::Error> { // Your implementation here Ok(MyValue(100)) } } let mut cache = Options::new(Duration::from_secs(10), MyFetcher).with_expire(Some(Duration::from_secs(10))) .build(); // Now you can use the cache to get and set values let key = FastStr::from("key"); let val = cache.get_or_set(key.clone(), MyValue(50)); assert_eq!(val, MyValue(50)); let other_val = cache.get(key).await.unwrap(); assert_eq!(other_val, MyValue(50)); ``` Design --- AsyncCache uses async-singleflight to reduce redundant load on underlying fetcher, requests from different future tasks with the same key will only trigger a single fetcher call. It also provides a few channels to notify the client of the cache when the cache is updated or there was an error with a fetch. `AsyncCache` is thread-safe and can be cloned and shared across tasks. Example --- ``` use async_cache::{AsyncCache, Options}; use faststr::FastStr; use std::time::Duration; #[tokio::main] async fn main() { let interval = Duration::from_millis(100); let options = Options::new(interval, GitHubFetcher::new()) .with_expire(Some(Duration::from_secs(30))); let cache = options.build(); let key = FastStr::from("your key"); match cache.get(key).await { Some(v) => println!("value: {}", v), None => println!("first fetch failed"), } tokio::time::delay_for(Duration::from_secs(5)).await; match cache.get(key).await { Some(v) => println!("value: {}", v), None => println!("fetch data failed"), } } ``` Structs --- * AsyncCache * Options Traits --- * Fetcher Struct async_cache::AsyncCache === ``` pub struct AsyncCache<T, F>where T: Send + Sync + Clone + 'static, F: Fetcher<T> + Sync + Send + Clone + 'static,{ /* private fields */ } ``` Implementations --- ### impl<T, F> AsyncCache<T, F>where T: Send + Sync + Clone + 'static, F: Fetcher<T> + Sync + Send + Clone + 'static, #### pub fn set_default(&self, key: FastStr, value: T) SetDefault sets the default value of given key if it is new to the cache. It is useful for cache warming up. #### pub async fn get(&self, key: FastStr) -> Option<TReturns None if first fetch result is err #### pub fn get_or_set(&self, key: FastStr, value: T) -> T #### pub async fn delete(&self, should_delete: impl Fn(&str) -> bool) Trait Implementations --- ### impl<T, F> Clone for AsyncCache<T, F>where T: Send + Sync + Clone + 'static + Clone, F: Fetcher<T> + Sync + Send + Clone + 'static + Clone, #### fn clone(&self) -> AsyncCache<T, FReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read moreAuto Trait Implementations --- ### impl<T, F> !RefUnwindSafe for AsyncCache<T, F### impl<T, F> Send for AsyncCache<T, F### impl<T, F> Sync for AsyncCache<T, F### impl<T, F> Unpin for AsyncCache<T, F### impl<T, F> !UnwindSafe for AsyncCache<T, FBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct async_cache::Options === ``` pub struct Options<T, F>where T: Send + Sync + Clone + 'static, F: Fetcher<T> + Sync + Send + Clone + 'static,{ /* private fields */ } ``` Implementations --- ### impl<T, F> Options<T, F>where T: Send + Sync + Clone + 'static, F: Fetcher<T> + Sync + Send + Clone + 'static, #### pub fn new(refresh_interval: Duration, fetcher: F) -> Self #### pub fn with_expire(self, expire_interval: Option<Duration>) -> Self #### pub fn with_error_tx(self, tx: Sender<(FastStr, Error)>) -> Self #### pub fn with_change_tx(self, tx: Sender<(FastStr, T, T)>) -> Self #### pub fn with_delete_tx(self, tx: Sender<(FastStr, T)>) -> Self #### pub fn build(self) -> AsyncCache<T, FAuto Trait Implementations --- ### impl<T, F> !RefUnwindSafe for Options<T, F### impl<T, F> Send for Options<T, F### impl<T, F> Sync for Options<T, F### impl<T, F> Unpin for Options<T, F>where F: Unpin, T: Unpin, ### impl<T, F> !UnwindSafe for Options<T, FBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.
networktools
cran
R
Package ‘networktools’ August 23, 2023 Title Tools for Identifying Important Nodes in Networks Version 1.5.1 Date 2023-8-22 Description Includes assorted tools for network analysis. Bridge centrality; gold- bricker; MDS, PCA, & eigenmodel network plotting. Depends R (>= 3.0.0) License GPL-3 Encoding UTF-8 LazyData true Imports qgraph,igraph,reshape2,ggplot2,gridExtra,stats,graphics,utils,cocor,RColorBrewer,R.utils,eigenmodel,psych,smacof,word RoxygenNote 7.2.3 Suggests dplyr, testthat URL https://CRAN.R-project.org/package=networktools BugReports https://github.com/paytonjjones/networktools/issues NeedsCompilation no Author <NAME> [aut, cre] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2023-08-22 22:10:02 UTC R topics documented: assumptionChec... 2 bridg... 3 coerce_to_adjacenc... 5 depressio... 6 EIGENne... 6 expectedIn... 7 goldbricke... 8 MDSne... 10 net_reduc... 11 PCAne... 12 plot.bridg... 13 plot.expectedIn... 14 PROCRUSTESne... 15 socia... 16 assumptionCheck Assumption Checking Function Description Checks some basic assumptions about the suitability of network analysis on your data Usage assumptionCheck( data, type = c("network", "impact"), percent = 20, split = c("median", "mean", "forceEqual", "cutEqual", "quartiles"), plot = FALSE, binary.data = FALSE, na.rm = TRUE ) Arguments data dataframe or matrix of observational data (rows: observations, columns: nodes) type which assumptions to check? "network" tests the suitability for network analysis in general. "impact" tests the suitability for analyzing impact percent percent difference from grand mean that is acceptable when comparing vari- ances. split if type="impact", specifies the type of split to utilize plot logical. Should histograms each variable be plotted? binary.data logical. Defaults to FALSE na.rm logical. Should missing values be removed? Details Network analysis rests on several assumptions. Among these: - Variance of each node is (roughly) equal - Distributions are (roughly) normal Comparing networks in impact rests on additional assumptions including: - Overall variances are (roughly) equal in each half This function checks these assumptions and notifies any violations. This function is not intended as a substitute for careful data visualization and independent assumption checks. See citations in the references section for further details. References <NAME>., <NAME>, <NAME>., & <NAME>, <NAME>. (2016). Differences in Connection Strength between Mental Symptoms Might Be Explained by Differences in Variance: Reanalysis of Network Data Did Not Confirm Staging. PLOS ONE, 11(11), e0155205. Retrieved from https://doi.org/10.1371/journal.pone.0155205 bridge Bridge Centrality Description Calculates bridge centrality metrics (bridge strength, bridge betweenness, bridge closeness, and bridge expected influence) given a network and a prespecified set of communities. Usage bridge( network, communities = NULL, useCommunities = "all", directed = NULL, nodes = NULL, normalize = FALSE ) Arguments network a network of class "igraph", "qgraph", or an adjacency matrix representing a network communities an object of class "communities" (igraph) OR a character vector of community assignments for each node (e.g., c("Comm1", "Comm1", "Comm2", "Comm2)). The ordering of this vector should correspond to the vector from argument "nodes". Can also be in list format (e.g., list("Comm1"=c(1:10), "Comm2"=c(11:20))) useCommunities character vector specifying which communities should be included. Default set to "all" directed logical. Directedness is automatically detected if set to "NULL" (the default). Symmetric adjacency matrices will be undirected, asymmetric matrices will be directed nodes a vector containing the names of the nodes. If set to "NULL", this vector will be automatically detected in the order extracted normalize logical. Bridge centralities are divided by their highest possible value (assuming max edge strength=1) in order to normalize by different community sizes Details To plot the results, first save as an object, and then use plot() (see ?plot.bridge) Centrality metrics (strength, betweenness, etc.) illuminate how nodes are interconnected among the entire network. However, sometimes we are interested in the connectivity between specific communities in a larger network. Nodes that are important in communication between communities can be conceptualized as bridge nodes. Bridge centrality statistics aim to identify bridge nodes. Bridge centralities can be calculated across all communities, or between a specific subset of communities (as identified by the useCommunities argument) The bridge() function currently returns 5 centrality metrics: 1) bridge strength, 2) bridge between- ness, 3) bridge closeness, 4) bridge expected influence (1-step), and 5) bridge expected influence (2-step) See ?plot.bridge for plotting details. Bridge strength is defined as the sum of the absolute value of all edges that exist between a node A and all nodes that are not in the same community as node A. In a directed network, bridge strength can be separated into bridge in-degree and bridge out-degree. Bridge betweenness is defined as the number of times a node B lies on the shortest path between nodes A and C, where nodes A and C come from different communities. Bridge closeness is defined as the inverse of the average length of the path from a node A to all nodes that are not in the same community as node A. Bridge expected influence (1-step) is defined as the sum of the value (+ or -) of all edges that exist between a node A and all nodes that are not in the same community as node A. In a directed network, expected influence only considers edges extending from the given node (e.g., out-degree) Bridge expected influence (2-step) is similar to 1-step, but also considers the indirect effect that a node A may have on other communities through other nodes (e.g, an indirect effect on node C as in A -> B -> C). Indirect effects are weighted by the first edge weight (e.g., A -> B), and then added to the 1-step expected influence. Indirect effects back on node A’s own community (A -> B -> A) are not counted. If negative edges exist, bridge expected influence should be used. Bridge closeness and bridge betweenness are only defined for positive edge weights, thus negative edges, if present, are deleted in the calculation of these metrics. Bridge strength uses the absolute value of edge weights. Value bridge returns a list of class bridge which contains: $'Bridge Strength' $'Bridge Betweenness' $'Bridge Closeness' $'Bridge Expected Influence (1-step)' $'Bridge Expected Influence (2-step)' Each of these contains a vector of named centrality values $'communities' is also returned, which returns the communities in vector format. If communities were supplied as a list or igraph object, it is advised that one check the accuracy of this vector. Examples graph1 <- qgraph::qgraph(cor(depression)) b <- bridge(graph1, communities=c('1','1','2','2','2','2','1','2','1')) b coerce_to_adjacency Coerce to adjacency matrix Description Takes an object of type "qgraph", "igraph", or an adjacency matrix (or data.frame) and outputs an adjacency matrix Usage coerce_to_adjacency(input, directed = NULL) Arguments input a network of class "igraph", "qgraph", or an adjacency matrix representing a network directed logical. is the network directed? If set to NULL, auto-detection is used depression Simulated Depression Profiles Description This simulated dataset contains severity ratings for 9 symptoms of major depressive disorder in 1000 individuals. Symptom ratings are assumed to be self-reported on a 100 point sliding scale. Usage depression Format a dataframe. Columns represent symptoms and rows represent individuals Examples head(depression) EIGENnet EIGENnet Description Convenience function for converting a qgraph object to an eigenmodel layout Usage EIGENnet( qgraph_net, EIGENadj = NULL, S = 1000, burn = 200, seed = 1, repulse = F, repulsion = 1, eigenmodelArgs = list(), ... ) Arguments qgraph_net an object of type qgraph EIGENadj to use a base matrix for the eigenmodel other than the adjacency matrix stored in qgraph_net, provide it in this argument S number of samples from the Markov chain burn number of initial scans of the Markov chain to be dropped seed a random seed repulse logical. Add a small repulsion force with wordcloud package to avoid node overlap? repulsion scalar for the repulsion force (if repulse=T). Larger values add more repulsion eigenmodelArgs additional arguments in list format passed to eigenmodel::eigenmodel_mcmc ... additional arguments passed to qgraph Details An eigenmodel can be interpreted based on coordinate placement of each node. A node in the top right corner scored high on both the first and second latent components References <NAME>., <NAME>., & <NAME>. (2018). Visualizing psychological networks: A tutorial in R. Frontiers in Psychology, 9, 1742. https://doi.org/10.3389/fpsyg.2018.01742 expectedInf Expected Influence Description Calculates the one-step and two-step expected influence of each node. Usage expectedInf(network, step = c("both", 1, 2), directed = FALSE) Arguments network an object of type qgraph, igraph, or an adjacency matrix representing a net- work. Adjacency matrices should be complete (e.g., not only upper or lower half) step compute 1-step expected influence, 2-step expected influence, or both directed logical. Specifies if edges are directed, defaults to FALSE Details When a network contains both positive and negative edges, traditional centrality measures such as strength centrality may not accurately predict node influence on the network. Robinaugh, Millner, & McNally (2016) showed that in these cases, expected influence is a more appropriate measure. One-step expected influence is defined as the sum of all edges extending from a given node (where the sign of each edge is maintained). Two-step expected influence, as the name implies, measures connectivity up to two edges away from the node. It is defined as the sum of the (weighted) expected influences of each node connected to the initial node plus the one-step expected influence of the initial node. Weights are determined by the edge strength between the initial node and each "second step" node. See citations in the references section for further details. References <NAME>., <NAME>., & <NAME>. (2016). Identifying highly influential nodes in the complicated grief network. Journal of abnormal psychology, 125, 747. Examples out1 <- expectedInf(cor(depression[,1:5])) out1$step1 out1$step2 plot(out1) plot(out1, order="value", zscore=TRUE) igraph_obj <- igraph::graph_from_adjacency_matrix(cor(depression)) out_igraph <- expectedInf(igraph_obj) qgraph_obj <- qgraph::qgraph(cor(depression), DoNotPlot=TRUE) out_qgraph <- expectedInf(qgraph_obj) goldbricker Goldbricker - Identifying redundant nodes in networks using com- pared correlations Description This function compares correlations in a psychometric network in order to identify nodes which most likely measure the same underlying construct (i.e., are colinear) Usage goldbricker( data, p = 0.05, method = "hittner2003", threshold = 0.25, corMin = 0.5, progressbar = TRUE ) Arguments data a data frame consisting of n rows (participants) and j columns (variables) p a p-value threshold for determining if correlation pairs are "significantly differ- ent" method method for comparing correlations. See ?cocor.dep.groups.overlap for a full list threshold variable pairs which have less than the threshold proportion of significantly dif- ferent correlations will be considered "bad pairs" corMin the minimum zero-order correlation between two items to be considered "bad pairs". Items that are uncorrelated are unlikely to represent the same underlying construct progressbar logical. prints a progress bar in the console Details In a given psychometric network, two nodes may be redundantly measuring the same underlying construct. If this is the case, the correlations between those two variables and all other variables should be highly similar. That is, they should correlate to the same degree with other variables. The cocor package uses a p-value threshold to determine whether a pair of correlations to a third variable are significantly different from each other. Goldbricker wraps the cocor package to com- pare every possible combination of correlations in a psychometric network. It calculates the pro- portion of correlations which are significantly different for each different pair of nodes. Using the threshold argument, one can set the proportion of correlations which is deemed "too low". All pairs of nodes which fall below this threshold are returned as defined "bad pairs". Pairs can then be combined using the net_reduce function Note: to quickly change the threshold, one may simply enter an object of class "goldbricker" in the data argument, and change the threshold. The p-value cannot be modified in the same fashion, as re-computation is necessary. Value goldbricker returns a list of class goldbricker which contains: $proportion_matrix - a j x j matrix of proportions. Each proportion signifies the amount of significantly different correlations between the given node pair (j x j) $suggested_reductions - a vector of "bad pairs" (names) and their proportions (values) $p - p value from input $threshold - threshold from input Examples gb_depression <- goldbricker(depression, threshold=0.5) reduced_depression <- net_reduce(data=depression, badpairs=gb_depression) ## Set a new threshold quickly gb_depression_60 <- goldbricker(data=gb_depression, threshold=0.6) MDSnet MDSnet Description Convenience function for converting a qgraph object to a layout determined by multidimensional scaling Usage MDSnet( qgraph_net, type = c("ordinal", "interval", "ratio", "mspline"), MDSadj = NULL, stressTxt = F, repulse = F, repulsion = 1, mdsArgs = list(), ... ) Arguments qgraph_net an object of type qgraph type transformation function for MDS, defaults to "ordinal" MDSadj to use a proximities matrix other than the adjacency matrix stored in qgraph_net, provide it in this argument stressTxt logical. Print the stress value in the lower left corner of the plot? repulse logical. Add a small repulsion force with wordcloud package to avoid node overlap? repulsion scalar for the repulsion force. Larger values add more repulsion mdsArgs additional arguments in list format passed to smacof::mds ... additional arguments passed to qgraph Details A network plotted with multidimensional scaling can be interpreted based on the distances between nodes. Nodes close together represent closely associated nodes, whereas nodes that are far apart represent unassociated or negatively associated nodes. References <NAME>., <NAME>., & <NAME>. (2018). Visualizing psychological networks: A tutorial in R. Frontiers in Psychology, 9, 1742. https://doi.org/10.3389/fpsyg.2018.01742 net_reduce net_reduce Description This function takes predefined pairs of colinear variables in a dataset and a) combines them via PCA or b) picks the "better" variable and eliminates the other variable Usage net_reduce(data, badpairs, method = c("PCA", "best_goldbricker")) Arguments data a data frame consisting of n rows (participants) and j columns (variables) badpairs pairs of variables to be combined. Input may consist of: -an object of class "goldbricker" (all bad pairs are combined) -a vector of item names, each con- secutive pair will be considered a bad pair -a matrix with 2 columns where each bad pair takes up 1 row method method for combining variables. PCA takes the first principal component of the two variables and defines it as a new variable. best_goldbricker requires that the input of "badpairs" be an object of class "goldbricker" it selects the more unique variable, and eliminates the other variable in the pair. Details In a given psychometric network, two nodes may be redundantly measuring the same underlying construct. If this is the case, both variables should not appear in the same network, or network prop- erties will be inaccurate. These variable pairs can be reduced by combining them, or by eliminating one of them. net_reduce automates this process when given a list of "bad pairs" If the same variable appears in multiple "bad pairs" (e.g., "x" and "y" is a bad pair, and so is "x" and "z"), only the first of these pairs which appears in the badpairs argument will be reduced by the function. Value goldbricker returns a dataframe of n rows (participants) and j - x columns, where j is the number of variables in the original dataframe, and x is the number of bad pairs to reduce. Examples gb_depression <- goldbricker(depression, threshold=0.5) reduced_depression_PCA <- net_reduce(data=depression, badpairs=gb_depression) reduced_depression_best <- net_reduce(data=depression, badpairs=gb_depression, method="best_goldbricker") PCAnet PCAnet Description Convenience function for converting a qgraph object to a layout determined by principal compo- nents analysis Usage PCAnet( qgraph_net, cormat, varTxt = F, repulse = F, repulsion = 1, principalArgs = list(), ... ) Arguments qgraph_net an object of type qgraph cormat the correlation matrix of the relevant data. If this argument is missing, the func- tion will assume that the adjacency matrix from qgraph_net is a correlation matrix varTxt logical. Print the variance accounted for by the PCA in the lower left corner of the plot repulse logical. Add a small repulsion force with wordcloud package to avoid node overlap? repulsion scalar for the repulsion force (if repulse=T). Larger values add more repulsion principalArgs additional arguments in list format passed to psych::principal ... additional arguments passed to qgraph Details A network plotted with PCA can be interpreted based on coordinate placement of each node. A node in the top right corner scored high on both the first and second principal components References <NAME>., <NAME>., & <NAME>. (2018). Visualizing psychological networks: A tutorial in R. Frontiers in Psychology, 9, 1742. https://doi.org/10.3389/fpsyg.2018.01742 plot.bridge Plot "bridge" objects Description Convenience function for plotting bridge centrality Usage ## S3 method for class 'bridge' plot( x, order = c("given", "alphabetical", "value"), zscore = FALSE, include, color = FALSE, colpalette = "Dark2", plotNA = FALSE, ... ) Arguments x an output object from bridge (class bridge) order "alphabetical" orders nodes alphabetically, "value" orders nodes from highest to lowest centrality values zscore logical. Converts raw impact statistics to z-scores for plotting include a vector of centrality measures to include ("Bridge Strength", "Bridge Between- ness", "Bridge Closeness", "Bridge Expected Influence (1-step)", "Bridge Ex- pected Influence (2-step)"), if missing all available measures will be plotted color logical. Color each community separately in the plot? colpalette A palette name from RColorBrewer, for coloring of axis labels plotNA should nodes with NA values be included on the y axis? ... other plotting specifications in ggplot2 (aes) Details Inputting an object of class bridge will return a line plot that shows the bridge centrality values of each node Examples b <- bridge(cor(depression)) plot(b) plot(b, order="value", zscore=TRUE,include=c("Bridge Strength", "Bridge Betweenness")) plot.expectedInf Plot "expectedInf" objects Description Convenience function for plotting expected influence Usage ## S3 method for class 'expectedInf' plot(x, order = c("given", "alphabetical", "value"), zscore = TRUE, ...) Arguments x an output object from an expectedInf (class expectedInf) order "alphabetical" orders nodes alphabetically, "value" orders nodes from highest to lowest impact value zscore logical. Converts raw impact statistics to z-scores for plotting ... other plotting specifications (ggplot2) Details Inputting an object of class expectedInf will return a line plot that shows the relative one-step and/or two-step expected influence of each node. Examples myNetwork <- cor(depression[,1:5]) out1 <- expectedInf(myNetwork) plot(out1$step1) plot(out1, order="value", zscore=TRUE) PROCRUSTESnet PROCRUSTESnet Description Convenience function for simultaneously plotting two networks containing the same nodes. Usage PROCRUSTESnet( qgraph_net1, qgraph_net2, type1 = c("ordinal", "interval", "ratio", "mspline"), type2 = type1, MDSadj1 = NULL, MDSadj2 = NULL, stressTxt = F, congCoef = F, repulse = F, repulsion = 1, mdsArgs = list(), ... ) Arguments qgraph_net1 an object of type qgraph qgraph_net2 an object of type qgraph. Contains the same nodes as qgraph_net2 type1 transformation function for first MDS, defaults to "ordinal" type2 transformation function for second MDS, defaults to the same as type1 MDSadj1 to use a proximities matrix other than the adjacency matrix stored in qgraph_net1, provide it in this argument MDSadj2 to use a proximities matrix other than the adjacency matrix stored in qgraph_net2, provide it in this argument stressTxt logical. Print the stress value in the lower left corner of the plots? congCoef logical. Print the congruence coefficient for the two layouts? repulse logical. Add a small repulsion force with wordcloud package to avoid node overlap? repulsion scalar for the repulsion force. Larger values add more repulsion mdsArgs additional arguments in list format passed to smacof::mds ... additional arguments passed to qgraph Details Each network’s layout is determined by multidimensional scaling, and then the layouts are brought into a similar space by using the Procrustes algorithm. A network plotted with multidimensional scaling can be interpreted based on the distances between nodes. Nodes close together represent closely associated nodes, whereas nodes that are far apart represent unassociated or negatively associated nodes. The Procrustes algorithm brings the two layouts into a similar space through rotations and dilations that do not impact the fit of the MDS solutions. In this implementation, the second network is rotated and dilated to fit the first. References <NAME>., <NAME>., & <NAME>. (2018). Visualizing psychological networks: A tutorial in R. Frontiers in Psychology, 9, 1742. https://doi.org/10.3389/fpsyg.2018.01742 social Simulated Social Engagement Data Description This simulated dataset contains binary social engagement scores for 16 individuals. For 400 so- cial media posts on a group forum, individuals were given a score of 1 if they engaged in group conversation regarding the post, and a score of 0 if they did not engage with the post. Usage social Format a dataframe. Columns represent individuals (nodes) and rows represent engagement in social media group conversations Examples head(social)
suncalc
cran
R
Package ‘suncalc’ October 14, 2022 Version 0.5.1 Title Compute Sun Position, Sunlight Phases, Moon Position and Lunar Phase Description Get sun position, sunlight phases (times for sunrise, sunset, dusk, etc.), moon position and lunar phase for the given location and time. Most calculations are based on the formulas given in Astronomy Answers articles about position of the sun and the planets : <https://www.aa.quae.nl/en/reken/zonpositie.html>. Imports data.table, lubridate, magrittr License GPL-2 | file LICENSE URL https://github.com/datastorm-open/suncalc NeedsCompilation no RoxygenNote 7.1.2 Encoding UTF-8 Author <NAME> [aut, cre] (R interface), <NAME> [aut] (R interface) Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2022-09-29 16:20:14 UTC R topics documented: getMoonIlluminatio... 2 getMoonPositio... 3 getMoonTime... 5 getSunlightPositio... 6 getSunlightTime... 8 getMoonIllumination Get Moon illumination Description Get Moon illumination Usage getMoonIllumination(date = Sys.Date(), keep = c("fraction", "phase", "angle")) Arguments date : Single or multiple DateTime. Can be a Date (YYYY-MM-DD), a character in UTC (YYYY-MM-DD HH:mm:ss) or a POSIXct keep : character. Vector of variables to keep. See Details Details Returns an object with the following properties: • "fraction" : illuminated fraction of the moon; varies from 0.0 (new moon) to 1.0 (full moon) • "phase" : moon phase; varies from 0.0 to 1.0, described below • "angle" : midpoint angle in radians of the illuminated limb of the moon reckoned eastward from the north point of the disk; the moon is waxing if the angle is negative, and waning if positive Moon phase value should be interpreted like this: • 0 : New Moon • Waxing Crescent • 0.25 : First Quarter • : Waxing Gibbous • 0.5Full Moon • : Waning Gibbous • 0.75Last Quarter • : Waning Crescent By subtracting the parallacticAngle from the angle one can get the zenith angle of the moons bright limb (anticlockwise). The zenith angle can be used do draw the moon shape from the observers perspective (e.g. moon lying on its back). Value data.frame See Also getSunlightTimes, getMoonTimes, getMoonIllumination, getMoonPosition,getSunlightPosition Examples # one date getMoonIllumination(date = Sys.Date()) # in character getMoonIllumination(date = c("2017-05-12", "2017-05-12 00:00:00"), keep = c("fraction", "phase")) # in POSIXct getMoonIllumination(date = as.POSIXct("2017-05-12 00:00:00", tz = "UTC")) getMoonIllumination(date = as.POSIXct("2017-05-12 02:00:00", tz = "CET")) date <- seq(ISOdate(2009,1,1), ISOdate(2010,1,1), "hours") date_cet <- date attr(date_cet, "tzone") <- "CET" res <- getMoonIllumination(date = date_cet) getMoonPosition Get Moon position Description Get Moon position Usage getMoonPosition( date = NULL, lat = NULL, lon = NULL, data = NULL, keep = c("altitude", "azimuth", "distance", "parallacticAngle") ) Arguments date : Single or multiple DateTime. Can be a Date (YYYY-MM-DD), a character in UTC (YYYY-MM-DD HH:mm:ss) or a POSIXct lat : numeric. Single latitude lon : numeric. Single longitude data : data.frame. Alternative to use date, lat, lon for passing multiple coordi- nates keep : character. Vector of variables to keep. See Details Details Returns an object with the following properties: • "altitude" : moon altitude above the horizon in radians • "azimuth" : moon azimuth in radians • "distance" : distance to moon in kilometers • "parallacticAngle" : parallactic angle of the moon in radians Value data.frame See Also getSunlightTimes, getMoonTimes, getMoonIllumination, getMoonPosition,getSunlightPosition Examples # one date getMoonPosition(date = Sys.Date(), lat = 50.1, lon = 1.83) # in character getMoonPosition(date = c("2017-05-12", "2017-05-12 00:00:00"), lat = 50.1, lon = 1.83) # in POSIXct getMoonPosition(date = as.POSIXct("2017-05-12 00:00:00", tz = "UTC"), lat = 50.1, lon = 1.83) getMoonPosition(date = as.POSIXct("2017-05-12 02:00:00", tz = "CET"), lat = 50.1, lon = 1.83) # multiple date + subset getMoonPosition(date = seq.Date(Sys.Date()-9, Sys.Date(), by = 1), keep = c("altitude", "azimuth"), lat = 50.1, lon = 1.83) # multiple coordinates data <- data.frame(date = seq.Date(Sys.Date()-9, Sys.Date(), by = 1), lat = c(rep(50.1, 10), rep(49, 10)), lon = c(rep(1.83, 10), rep(2, 10))) getMoonPosition(data = data, keep = c("altitude", "azimuth")) getMoonTimes Get Moon times Description Get Moon times Usage getMoonTimes( date = NULL, lat = NULL, lon = NULL, data = NULL, keep = c("rise", "set", "alwaysUp", "alwaysDown"), tz = "UTC", inUTC = FALSE ) Arguments date : Date. Single or multiple Date. YYYY-MM-DD lat : numeric. Single latitude lon : numeric. Single longitude data : data.frame. Alternative to use date, lat, lon for passing multiple coordi- nates keep : character. Vector of variables to keep. See Details tz : character. Timezone of results inUTC : logical. By default, it will search for moon rise and set during local user’s day (from 0 to 24 hours). If TRUE, it will instead search the specified date from 0 to 24 UTC hours. Details Available variables are : • "rise" : Date. moonrise time • "set" : Date. moonset time • "alwaysUp" : Logical. TRUE if the moon never rises or sets and is always above the horizon during the day • "alwaysDown" : Logical. TRUE if the moon is always below the horizon Value data.frame See Also getSunlightTimes, getMoonTimes, getMoonIllumination, getMoonPosition,getSunlightPosition Examples # one date getMoonTimes(date = Sys.Date(), lat = 47.21, lon = -1.557, tz = "CET") # multiple date + subset getMoonTimes(date = seq.Date(Sys.Date()-9, Sys.Date(), by = 1), keep = c("rise", "set", "alwaysUp"), lat = 47.21, lon = -1.557, tz = "CET") # multiple coordinates data <- data.frame(date = seq.Date(Sys.Date()-9, Sys.Date(), by = 1), lat = c(rep(50.1, 10), rep(49, 10)), lon = c(rep(1.83, 10), rep(2, 10))) getMoonTimes(data = data, tz = "CET") getSunlightPosition Get Sunlight position Description Get Sunlight position Usage getSunlightPosition( date = NULL, lat = NULL, lon = NULL, data = NULL, keep = c("altitude", "azimuth") ) Arguments date : Single or multiple DateTime. Can be a Date (YYYY-MM-DD), a character in UTC (YYYY-MM-DD HH:mm:ss) or a POSIXct lat : numeric. Single latitude lon : numeric. Single longitude data : data.frame. Alternative to use date, lat, lon for passing multiple coordi- nates keep : character. Vector of variables to keep. See Details Details Returns an object with the following properties: • "altitude" : sun altitude above the horizon in radians, e.g. 0 at the horizon and PI/2 at the zenith (straight over your head) • "azimuth" : sun azimuth in radians (direction along the horizon, measured from south to west), e.g. 0 is south and Math.PI * 3/4 is northwest Value data.frame See Also getSunlightTimes, getMoonTimes, getMoonIllumination, getMoonPosition,getSunlightPosition Examples # one date getSunlightPosition(date = Sys.Date(), lat = 50.1, lon = 1.83) # in character getSunlightPosition(date = c("2017-05-12", "2017-05-12 00:00:00"), lat = 50.1, lon = 1.83) # in POSIXct getSunlightPosition(date = as.POSIXct("2017-05-12 00:00:00", tz = "UTC"), lat = 50.1, lon = 1.83) getSunlightPosition(date = as.POSIXct("2017-05-12 02:00:00", tz = "CET"), lat = 50.1, lon = 1.83) # multiple date + subset getSunlightPosition(date = seq.Date(Sys.Date()-9, Sys.Date(), by = 1), keep = c("altitude"), lat = 50.1, lon = 1.83) # multiple coordinates data <- data.frame(date = seq.Date(Sys.Date()-9, Sys.Date(), by = 1), lat = c(rep(50.1, 10), rep(49, 10)), lon = c(rep(1.83, 10), rep(2, 10))) getSunlightPosition(data = data, keep = c("altitude", "azimuth")) getSunlightTimes Get Sunlight times Description Get Sunlight times Usage getSunlightTimes( date = NULL, lat = NULL, lon = NULL, data = NULL, keep = c("solarNoon", "nadir", "sunrise", "sunset", "sunriseEnd", "sunsetStart", "dawn", "dusk", "nauticalDawn", "nauticalDusk", "nightEnd", "night", "goldenHourEnd", "goldenHour"), tz = "UTC" ) Arguments date : Date. Single or multiple Date. YYYY-MM-DD lat : numeric. Single latitude lon : numeric. Single longitude data : data.frame. Alternative to use date, lat, lon for passing multiple coordi- nates keep : character. Vector of variables to keep. See Details tz : character. Timezone of results Details Available variables are : • "sunrise" : sunrise (top edge of the sun appears on the horizon) • "sunriseEnd" : sunrise ends (bottom edge of the sun touches the horizon) • "goldenHourEnd" : morning golden hour (soft light, best time for photography) ends • "solarNoon" : solar noon (sun is in the highest position) • "goldenHour" : evening golden hour starts • "sunsetStart" : sunset starts (bottom edge of the sun touches the horizon) • "sunset" : sunset (sun disappears below the horizon, evening civil twilight starts) • "dusk" : dusk (evening nautical twilight starts) • "nauticalDusk" : nautical dusk (evening astronomical twilight starts) • "night" : night starts (dark enough for astronomical observations) • "nadir" : nadir (darkest moment of the night, sun is in the lowest position) • "nightEnd" : night ends (morning astronomical twilight starts) • "nauticalDawn" : nautical dawn (morning nautical twilight starts) • "dawn" : dawn (morning nautical twilight ends, morning civil twilight starts) Value data.frame See Also getSunlightTimes, getMoonTimes, getMoonIllumination, getMoonPosition,getSunlightPosition Examples # one date getSunlightTimes(date = Sys.Date(), lat = 50.1, lon = 1.83, tz = "CET") # multiple date + subset getSunlightTimes(date = seq.Date(Sys.Date()-9, Sys.Date(), by = 1), keep = c("sunrise", "sunriseEnd", "sunset", "sunsetStart"), lat = 50.1, lon = 1.83, tz = "CET") # multiple coordinates data <- data.frame(date = seq.Date(Sys.Date()-9, Sys.Date(), by = 1), lat = c(rep(50.1, 10), rep(49, 10)), lon = c(rep(1.83, 10), rep(2, 10))) getSunlightTimes(data = data, keep = c("sunrise", "sunriseEnd", "sunset", "sunsetStart"), tz = "CET")
chef
devdocs
Markdown
Chef Documentation ================== Welcome to the Chef Software Documentation! This is the documentation for: * Chef Automate * Chef Desktop * Chef Habitat * Chef Infra Client * Chef Infra Server * Chef InSpec * Chef Workstation #### Getting Started * [Platform Overview](platform_overview/index) * [Chef Infra Overview](chef_overview/index) * [Chef Infra Quick Start](quick_start/index) * [Chef Automate Quickstart](automate/index) * [Learn Chef](https://learn.chef.io/) #### Chef Infra * [Chef Infra Client Overview](chef_client_overview/index) * [Chef Infra Server Overview](server/index) * [Install Chef Infra Server](server/install_server/index) #### Chef Workstation * [About Workstation](workstation/index) * [Install Workstation](workstation/install_workstation/index) * [Knife](workstation/knife/index) * [config.rb](workstation/config_rb) #### Chef Automate * [Chef Automate Install Guide](automate/install/index) * [Chef Automate API](https://docs.chef.io/automate/api/) * [Chef Automate CLI](automate/cli_chef_automate/index) * [Chef Automate Desktop Dashboard](automate/desktop/index) #### Chef InSpec * [Chef InSpec Overview](inspec/index) * [Chef InSpec CLI](inspec/cli/index) * [Chef InSpec Profiles](inspec/profiles/index) * [Chef InSpec Resources](inspec/resources/index) #### Chef Infra Cookbooks * [About Cookbooks](cookbooks/index) * [Recipes](recipes/index) * [Chef Infra Language](infra_language/index) * [Chef Supermarket](supermarket/index) #### Chef Infra Resources * [About Resources](resource/index) * [Resources Reference](resources/index) * [Common Functionality](resource_common/index) * [Custom Resources](custom_resources/index) #### Release Notes * [Chef Automate](https://docs.chef.io/release_notes_automate/) * [Chef Infra Client](https://docs.chef.io/release_notes_client/) * [Chef Infra Server](https://docs.chef.io/release_notes_server/) * [Chef InSpec](https://docs.chef.io/release_notes_inspec/) * [Chef Manage](https://docs.chef.io/release_notes_manage/) If you need documentation for previous versions, see the [Docs Archive](https://docs-archive.chef.io). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/Platform Overview ================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/platform_overview.md) Chef is an automation company. Ever since it was founded in 2008, we’ve been bringing together developers and system administrators with our namesake product, Chef Infra. Over the years, what we mean by automation has expanded. Today, Chef has a complete automation solution for both infrastructure and applications that takes you all the way from development to production. Here’s the complete Chef solution. ![Diagram of Automate architecture.](https://docs.chef.io/images/automate_architecture.svg) Chef Infra ---------- Chef Infra is a powerful automation platform that transforms infrastructure into code. Whether you’re operating in the cloud, on-premises, or in a hybrid environment, Chef Infra automates how infrastructure is configured, deployed, and managed across your network, no matter its size. This diagram shows how you develop, test, and deploy your Chef Infra code. ![image] ### Using Chef Workstation Chef Workstation allows you to author cookbooks and administer your infrastructure. Chef Workstation runs on the computer you use everyday, whether it’s Linux, macOS, or Windows. Chef Workstation ships with Cookstyle, ChefSpec, Chef InSpec, and Test Kitchen testing tools. With them, you can make sure your Chef Infra code does what you intended before you deploy it to environments used by others, such as staging or production. When you write your code, you use resources to describe your infrastructure. A resource corresponds to some piece of infrastructure, such as a file, a template, or a package. Each resource declares what state a part of the system should be in, but not how to get there. Chef Infra handles these complexities for you. Chef Infra provides many resources that are ready for you to use. You can also utilize resources shipped in community cookbooks, or write your own resources specific to your infrastructure. A Chef Infra recipe is a file that groups related resources, such as everything needed to configure a web server, database server, or a load balancer. A Chef Infra cookbook provides structure to your recipes and, in general, helps you stay organized. The Chef Workstation includes other command line tools for interacting with Chef Infra. These include knife for interacting with the Chef Infra Server, and chef for interacting with your local chef code repository (chef-repo). ### Uploading your code to Chef Infra Server Once you’re done developing and testing code on your local workstation, you can upload it to the Chef Infra Server. The Chef Infra Server acts as a hub for configuration data. It stores cookbooks, the policies that are applied to the systems in your infrastructure and metadata that describes each system. The knife command lets you communicate with the Chef Infra Server from your workstation. For example, you use it to upload your cookbooks. ### Configuring nodes with Chef Infra Client Chef Infra is constructed so that most of the computational effort occurs on the nodes rather than on the Chef Infra Server. A node represents any system you manage and is typically a virtual machine, container instance, or physical server. Basically, it’s any compute resource in your infrastructure that’s managed by Chef Infra. All nodes have Chef Infra Client installed on them, and Chef Infra Client is available for multiple platforms including Linux, macOS, Windows, AIX, and Solaris. Periodically, Chef Infra Client contacts the Chef Infra Server to retrieve the latest cookbooks. If (and only if) the current state of the node doesn’t conform to what the cookbook says it should be, Chef Infra Client executes the cookbook instructions. This iterative process ensures that the network as a whole converges to the state envisioned by business policy. Chef Habitat ------------ Chef Habitat offers a new approach to deploying applications called application automation. Application automation means that the automation is packaged with the application and travels with it, no matter where that application is deployed. The unit of deployment becomes the application and its associated automation. The runtime environment, whether it is a container, bare metal, or PaaS does not in any way define the application. Chef Habitat is comprised of a packaging format and a supervisor. The format defines Chef Habitat packages, which are isolated, immutable, and auditable. The Chef Habitat supervisor knows how to take the packages and run them. It’s aware of the package’s peer relationships, its upgrade strategy and security policies. To learn everything about Chef Habitat, go to the Chef Habitat web site at [https://www.habitat.sh](https://www.habitat.sh/). Chef InSpec ----------- Chef InSpec is an open-source testing framework with a human- and machine-readable language for specifying compliance, security and policy requirements. When compliance is expressed as code, you can integrate it into your deployment pipeline and automatically test for adherence to security policies. Chef InSpec code can run in multiple platforms. You can execute the same set of tests locally, with remote commands that use SSH or WinRM, or with external mechanisms such as the Docker API. With Chef InSpec, you can do more than ensure that your physical servers are in compliance. You can, for example, assess data in a database or inspect the configuration of virtual resources by using their API. To get a sense of how the Chef InSpec language works, here are some examples. This Chef InSpec rule ensures that insecure services and protocols, such as telnet, are not used. ``` describe package('telnetd') do it { should_not be_installed } end describe inetd_conf do its('telnet') { should eq nil } end ``` Chef Automate ------------- Chef Automate provides a full suite of enterprise capabilities for node visibility and compliance. Chef Automate integrates with the open-source products Chef Infra Client, Chef InSpec and Chef Habitat. Chef Automate comes with comprehensive 24x7 support services for the entire platform, including open source components. Chef Automate gives you a full-stack continuous compliance and security, as well as visibility into your applications and infrastructure. ### Nodes Chef Automate gives you a data warehouse that accepts input from Chef Server, Chef Habitat, and Chef Automate workflow and compliance. It provides views into operational and workflow events. There is a query language available through the UI and customizable dashboards. Here is an example of the Chef Automate dashboard. ![Image of Chef Automate dashboard showing the status of nodes under management with Chef Automate.] ### Compliance Chef Automate creates customizable reports that identify compliance issues, security risks, and outdated software. You can write your own compliance rules in Chef InSpec, or you can get started quickly by using built-in profiles, which are predefined rule sets for a variety of security frameworks, such as Center for Internet Security (CIS) benchmarks, included as part of Chef Automate. For information on the integrated reporting capabilities in Chef Automate, see [Compliance Overview](../automate/reports/index). ### High availability Chef Automate includes a high-availability Chef Infra Server with fault tolerance, immediately consistent search results, and accurate real-time data about your infrastructure. Chef Automate also provides a graphical management console for the Chef Infra Server. Learning More ------------- If you’re interested in getting hands-on experience, go to <https://learn.chef.io/> for tutorials, information about formal training classes and community resources. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/platform_overview/Chef Contributor Covenant Code of Conduct ========================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/community_guidelines.md) **Note**: If you are in a physical space (e.g. ChefConf, Meetup, etc), please see the [Physical Spaces Code of Conduct](https://www.chef.io/code-of-conduct/physical-spaces/). Our Pledge ---------- Diversity is one of the greatest strengths that a community can have, and many times that strength is born from the friction that can only come through sharing of differing perspectives. In the interest of fostering an open, welcoming, and encouraging environment, we as contributors, maintainers, and community members pledge to making participation in our projects and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, veteran status, or sexual identity and orientation. Our Standards ------------- The Chef community contains a diverse group of professionals and volunteers who come from all over the world to make Chef better. Community members may fulfill many roles including mentoring, teaching, and connecting with other members of the community. Be careful in the words that you choose. Be kind to others. Practice empathy. Don’t insult or put down others. Remember that sexist, racist, ableist, ageist, and other exclusionary jokes can be offensive to those around you. If you think your conversation is making another community member uncomfortable *or* if they tell you so, stop immediately, make amends, and move forward. As you are working with other members of the community, please keep in mind that the following guidelines apply equally to founders, mentors, those who submit new features/pull requests, and anyone who is seeking help and guidance. The following list isn’t exhaustive, but these few examples can help all of us communicate well, so that the community can work better together: * Use welcoming and inclusive language * Exercise patience and friendliness * Be respectful of differing viewpoints and experiences * Gracefully accept constructive criticism * Focus on what is best for the community * Show empathy towards other community members The previous list applies to all forms of communication: Slack (or any web chat), Discourse, the issue tracker, and any other forum that is used by the community. Please keep in mind that: * Your work will be used by other people, and you, in turn, will depend on the work of others. * Decisions that you make often will affect others in the community. * Disagreements happen, but should not be an excuse for poor behavior and bad manners. When disagreements do happen, let’s work together to solve them effectively and in a way that ensures that everyone understands what the disagreements were. * Our community spans languages, cultures, perspectives (and continents!), and as such people may not understand jokes, sarcasm, and oblique references in the same way that you do. Remember that and be kind to the other members of the community. * Be cautious about making assumptions about what someone does or does not know about something - assuming that someone does not understand an issue and over explaining can be condescending (even when not intended to be so). * Sexist, racist, ableist, ageist, and other prejudicial or exclusionary comments are not welcome in the community. Unacceptable Behavior --------------------- Harassment comes in many forms, including but not limited to: * Offensive comments related to gender, sexual orientation, age, disability, physical appearance, body size, race, veteran status, or religion. * Posting/Exposing sexually explicit or violent images. * Deliberate (or implied) intimidation. * Trolling, insulting/derogatory comments, and personal or political attacks particularly those related to gender, sexual orientation, age, race, religion or disability. * Publishing others' private information, such as a physical or electronic address, without explicit permission (“doxing”). As a community that meets in physical public spaces, harassment also includes: * Stalking or persistent following. * Intrusive or otherwise unwanted photography or recording. * Sustained disruption of talks or other events. * Inappropriate physical contact or unwelcome sexual attention. **NOTE**: If you are in a physical space – e.g. Chef Conf, Meetup, etc. – please see the [Physical Spaces Code of Conduct](https://www.chef.io/code-of-conduct/physical-spaces/). If you have any lack of clarity about behaviors we include in the definition of “harassment”, please read the [Citizen Code of Conduct](http://citizencodeofconduct.org/). In particular, we do not tolerate behavior that excludes people in socially marginalized groups. Enforcement/Getting Help ------------------------ Instances of abusive, harassing, or otherwise unacceptable behavior should be reported by contacting any of the Community Advocates directly. Each person’s contact information and role is listed in the repo that links to this document. If you were not linked here, then contact the [individuals listed below](#roles). All complaints will be reviewed, investigated, and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Community Organizers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership. Roles ----- The following are the various roles of our **Community Organizers** and the person(s) assigned to each role: * The **Deciders** have final say on community guidelines and final authority on correct actions and appeals. * The **Community Advocates** may be assigned for each area where the community convenes online (Slack, email list, GitHub, etc.). Community Advocates are volunteers who have the best interests of our community in mind. They act in good faith to help enforce our community guidelines and respond to incidents when they occur. * The **Project Maintainers** are expected to conduct their behavior in line with the Code of Conduct and are individually responsible for both escalating to a **Community Advocate** in case of witnessing an incident, and helping to foster the community. * A **Community Member** is anyone who participates with the community whether in-person or via online channels. Community members are responsible for following the community guidelines, suggesting updates to the guidelines when warranted, and helping enforce community guidelines. | Role | Name | Contact Info | | --- | --- | --- | | Community Advocate | <NAME> | <<EMAIL>> | Consequences of Unacceptable Behavior ------------------------------------- Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will *not* be tolerated. Anyone who is asked to stop unacceptable behavior is expected to comply immediately. If a community member engages in unacceptable behavior, the community organizers may take action that they deem appropriate – up to and including a temporary ban or permanent expulsion from the community *without warning* (and without refund, in the case of a paid event). If you have been involved in unacceptable behavior with current Chef community members outside the boundaries of the Chef Community, the Community Organizers retain the right to treat those external incidents in the same manner as internal incidents. Any physical violence *or* intimidation, threatened or acted on, is a serious offense and will result in immediate exclusion from the community and appropriate follow up with law enforcement. No, we are not kidding. Procedure for Handling Disagreements and Incidents -------------------------------------------------- Disagreements are inherent to a group of impassioned people. When they occur, we seek to resolve disagreements and differing views constructively and with the help of the community and community processes. When disagreements escalate, we ask our Community Advocates to step in to moderate, mediate, and help resolve tense situations. The Chef Community Advocates are well informed on how to deal with incidents. Report the incident (preferably in writing) to one of the Community Advocates listed in the [Roles](#roles) section. ### Handling Incidents **NOTE**: If you are in a physical space – e.g. Chef Conf, Meetup, etc. – please see the [Physical Spaces Code of Conduct](https://www.chef.io/code-of-conduct/physical-spaces/). When a Community Organizer or Project Maintainer notices someone behaving in a way that is outside of our guidelines (a violator), the Community Advocate should make every reasonable attempt to help curtail that behavior. The Community Advocate may: * Remind the violator about our Community Code of Conduct and provide a link to this document. * Ask the violator to stop the unacceptable behavior. * Raise the issue with a maintainer, the community manager, or any member of the core project team. * Allow time for the violator to correct the behavior. The Community Advocate should take the following steps if the behavior is not brought in-line with our guidelines or the incident is not resolved: * Consult with another Community Organizer to make a judgment call about what reasonable corrective actions are warranted. * In the case that no conclusion can be made, escalate to include the next level of Community Organizers. * If still no conclusion can be made, report the incident to the **Deciders** listed above. * Apply the corrective action. * Document the incident as described below. #### Documenting Incidents All incident reports will be kept in a private repository that is shared with the aforementioned Community Advocates and Deciders under the [Roles](#roles) section. No other individuals or project contributors will be given access to these incident reports. **This repo will hold no personal information on the victim of an incident.** On the displacement of any Community Organizer in the [Roles](#roles) list above, that individual will immediately lose access to this repository and will terminate any local copies of the repository. The important information to report consists of: * Identifying information (name, email address, Slack username, etc.) of the person doing the harassing. * The behavior that was in violation. * The approximate time and date of the behavior. * The circumstances surrounding the incident. * Where applicable, contextual information/proof (email body, chat log, GitHub Issue, etc.). * Contact information for witnesses to the incident. If you feel your safety is in jeopardy, please do not hesitate to contact local law enforcement. **Note:** Incidents that violate the Community Code of Conduct are extremely damaging to the community. The silver lining is that, in many cases, these incidents present a chance for the community as a whole to grow, learn, and become better. Our Responsibilities -------------------- Community Organizers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Community Organizers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, messages, tweets, and other contributions that are not aligned with this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. Scope ----- Our community will convene in both physical and virtual spaces. This Code of Conduct applies within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers and community organizers. Attribution ----------- This Code of Conduct is adapted from the following: * [Contributor Covenant](https://www.contributor-covenant.org/), version 1.4, available [here](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html) * [Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct) * [Citizen Code of Conduct](http://citizencodeofconduct.org/) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/community_guidelines/Chef House Style ================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/style_house.md) We recommend that you use the conventions described in this guide when contributing to the Chef reference documentation. Official Names -------------- For Chef applications and components, use: * Chef Automate * Chef Habitat * Chef Infra (formerly Chef) * Chef Infra Client (Use Chef Client up to version 14.x) * Chef Infra Server (Formerly Chef Server) * Chef InSpec Grammar ------- Chef does not follow a specific grammar convention. Be clear and consistent as often as possible. Follow the established patterns in the docs. ### Tautologies A tautology, when used as a description for a component, setting, method, etc. should be avoided. If a string is a tautology, some effort should be made to make it not so. An example of a tautology is something like “Create a new user” (a user created **is** a new user) or (for a setting named `cidr_block`) “The CIDR block for the VPC.” Examples -------- ### Example Company We use the fictional company “Fourth Cafe, Inc.” as an example throughout the docs. Fourth Cafe, Inc. 123579 4th Ave Seattle, WA 98122 Examples in code: `<EMAIL>` `4thcafe.pem` ### Example Domains Use the `4thcafe.com` domain for generic domains and email addresses in the documentation. Use the `chef.io` or `progress.com` for examples that should refer directly back to the company. ### Example Names Don’t reveal personal information in examples, such as the names of real people, real email addresses, or phone numbers. Don’t use the names of bands, musicians, or characters from works that are under copyright. When writing about security, follow the accepted convention and use “Alice” and “Bob”. Following this convention helps readers see that they are reading a topic about security and integrate the Chef information with their existing knowledge. Here is a list of some example names for you to use (the last names are translations of “Chef”): * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> ### Example Email Addresses * [<EMAIL>](mailto:<EMAIL>) * [<EMAIL>](mailto:<EMAIL>) * [<EMAIL>](mailto:<EMAIL>) * [<EMAIL>](mailto:<EMAIL>) * [<EMAIL>](mailto:<EMAIL>) * [<EMAIL>](mailto:<EMAIL>) * [<EMAIL>](mailto:<EMAIL>) * [<EMAIL>](mailto:<EMAIL>) Use `<EMAIL>` for the Chef Technical Documentation team. #### Example Phone Numbers Never use a real phone number in an example. For a US phone number, use one from the range reserved for examples in fiction, which is (800) 555–0100 through (800) 555–0199. ### Example Addresses Use fictional street addresses in examples. Use these fictional addresses: 2943 Conifer Drive Seattle, WA 98122 1214 Hollow Road Boston, MA 02110 ### Example IP Addresses For IPv4 addresses, use one of the addresses provided in [RFC 5735](https://tools.ietf.org/html/rfc5737) for documentation. IPv4 addresses: * `192.0.2.0` * `198.51.100.0` * `203.0.113.0` IPv4 address ranges: * `192.0.2.0/24` (TEST-NET-1) * `198.51.100.0/24` (TEST-NET-2) * `203.0.113.0/24` (TEST-NET-3) For IPv6 addresses, use one of the addresses provided in [RFC 3849](https://tools.ietf.org/html/rfc3849) range for documentation. IPv6 address range: * `2001:DB8::/32` ### Some Existing Example Patterns The Chef docs have some useful example patterns of unknown origin. * Cookbook documentation uses `custom_web` as the example cookbook * Custom resource documentation uses `site` as the example custom resource * Templates documentation uses `httpd` as the template example * The documentation uses `webserver` as an example role in Chef Infra Client and Chef Infra Server documentation,`name: webserver`, `role[webserver]`, and `role:webserver`. * These examples often draw on each other. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/style_house/About the Chef Community ======================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/community.md) The Chef community is an active, caring, wickedly smart, and fast growing group of practitioners who want to help you succeed with Chef. There are a number of ways for you to engage with, learn from, follow, and contribute, such as reading books, going to meetups, listening to podcasts, taking some training, and simply being a part of the community. ![image](https://docs.chef.io/images/ChefRally.jpg) Meet ---- * [Chef events](https://www.chef.io/events) * [Chef meetups](https://www.meetup.com/topics/opscode/) * [Continuous delivery meetups](https://www.meetup.com/topics/continuous-delivery/) * [DevOps meetups](https://www.meetup.com/topics/devops/) Learn ----- * [Chef training](https://www.chef.io/training) * [Self-guided learning](https://learn.chef.io/) Interact -------- * [Community Guidelines](../community_guidelines/index) * [@chef](https://twitter.com/chef) * [@opscode_status](https://twitter.com/opscode_status) * [Facebook](https://www.facebook.com/getchefdotcom) * [Chef Community Slack](https://community-slack.chef.io/) * Join the “Chef Software Users Group” on LinkedIn * [Chef Software Mailing List](https://discourse.chef.io/) (for discussion among users, developers, and other interested parties) * [Chef Software on Twitch](https://www.twitch.tv/chefsoftware) Read ---- * [Effective DevOps (Building a Culture of Collaboration, Affinity, and Tooling at Scale)](http://shop.oreilly.com/product/0636920039846.do) * [Customizing Chef (Getting the Most Out of Your Infrastructure Automation)](http://shop.oreilly.com/product/0636920032984.do) * [Chef: Powerful Infrastructure Automation [Packt Publishing]](https://www.packtpub.com/virtualization-and-cloud/chef-powerful-infrastructure-automation) * [Chef Cookbook - Third Edition [Packt Publishing]](https://www.packtpub.com/networking-and-servers/chef-cookbook-third-edition) * [Learning Chef [Packt Publishing]](https://www.packtpub.com/networking-and-servers/learning-chef) * [Chef Infrastructure Automation Cookbook - Second Edition [Packt Publishing]](https://www.packtpub.com/networking-and-servers/chef-infrastructure-automation-cookbook-second-edition/) * [Mastering Chef [Packt Publishing]](https://www.packtpub.com/networking-and-servers/mastering-chef/) Contribute ---------- * [Chef on GitHub](https://github.com/chef) * [Community cookbooks](https://supermarket.chef.io) * [Documentation](https://github.com/chef/chef-web-docs) * [Share your Chef product ideas](https://www.chef.io/feedback/) Supermarket ----------- * [About Supermarket](../supermarket/index) * [Visit Supermarket](https://supermarket.chef.io) * [Cookbooks available on Supermarket](https://supermarket.chef.io/cookbooks-directory) Subscribe --------- * [Blog](https://blog.chef.io/) * [Videos](https://www.youtube.com/user/getchef) * [Mailing List](https://discourse.chef.io/) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/community/Community Contributions ======================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/community_contributions.md) We’re glad you want to contribute to a Chef project! This guide will help answer common questions you may have during your first contribution. Submitting Issues ----------------- Not every contribution comes in the form of code. Submitting, confirming, and triaging issues is an important task for any project. At Chef we use GitHub to track all project issues. If you are familiar with Chef projects and know the component that is causing you a problem, you can file an issue in the corresponding GitHub project. All of our Open Source Software can be found in our GitHub organizations. All projects include GitHub issue templates to help gather information needed for a thorough review. The Chef GitHub organizations are: * <https://github.com/chef> * <https://github.com/inspec> * <https://github.com/habitat-sh>. We ask you not to submit security concerns via GitHub. For details on submitting potential security issues please see our [Security Issue Guidelines](https://www.chef.io/security/). In addition to GitHub issues, we also utilize a feedback site that helps our product team track and rank feature requests. If you have a feature request, [this is an excellent place to start](https://feedback.chef.io). The following repositories are the preferred locations for the creation of issues and bug reports: | Repo | URL | | --- | --- | | Chef Infra Client | <https://github.com/chef/chef> | | Ohai | <https://github.com/chef/ohai> | | Chef Workstation | <https://github.com/chef/chef-workstation> | | Chef InSpec | <https://github.com/inspec/inspec> | | Chef Infra Server | <https://github.com/chef/chef-server> | | Chef Habitat | <https://github.com/habitat-sh/habitat> | | Chef Automate | <https://github.com/chef/automate> | For additional support about Chef products, including documentation, learning, and opening tickets with the support team, see [Chef Support](https://www.chef.io/support) . Warning If you require a response from Chef per the terms of a support level agreement (SLA), please contact [Chef Support](https://www.chef.io/support) directly. Note Questions on how to use Chef Infra should be sent as Support Tickets if you have an SLA, or asked on the [Chef Software Mailing List](https://discourse.chef.io/), or [Chef Community Slack](https://community-slack.chef.io/). Bug Trackers are not appropriate for general purpose questions that are not bugs. Contribution Process -------------------- We have a 4 step process for contributions: 1. Fork the project repository to your own GitHub account. 2. Commit your changes to your fork, making sure to sign-off those changes for the Developer Certificate of Origin with `git commit -s` 3. Create a GitHub Pull Request for your change, following the instructions in the pull request template. 4. Perform a Code Review with the project maintainers on the pull request. About the Apache License ------------------------ Chef uses the Apache License Version 2 because it provides the same level of freedom for our users that we desire for ourselves. Based upon the Apache Licensing FAQ, it allows you to: * freely download and use Chef software, in whole or in part, for personal, company internal, or commercial purposes; * use Chef software in packages or distributions that you create. It forbids you to: * redistribute any piece of Chef-originated software without proper attribution; * use any marks owned by Chef in any way that might state or imply that Chef endorses your distribution; * use any marks owned by Chef in any way that might state or imply that you created the Chef software in question. It requires you to: * include a copy of the license in any redistribution you may make that includes Chef software; * provide clear attribution to Chef for any distributions that include Chef software; attribution can be done in the NOTICE file for an application, by adding yourself as an author/copyright holder to the HEADER for an individual file, and by placing text in a header file saying that new work is based on previous work * reuse work as long as the licensing terms of the reused work remains unchanged (i.e. The Apache License Version 2 also applies to the reused work) It does not require you to: * include the source of the Chef software itself, or of any modifications you may have made to it, in any redistribution you may assemble that includes it; * submit changes that you make to the software back to Chef (though such feedback is encouraged). It is our goal to run a successful, truly open source business. To that end, we are protecting our own rights by making them explicit in our choice of licensing: you have the same rights to our open source software that we do. Developer Certification of Origin (DCO) --------------------------------------- To make a good faith effort to ensure the criteria of the Apache License are met, Chef requires the Developer Certificate of Origin (DCO) process to be followed. The DCO is an attestation attached to every contribution made by every developer. In the commit message of the contribution, the developer simply adds a Signed-off-by statement and thereby agrees to the DCO, which you can find below or at <https://developercertificate.org/>. ``` Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as Indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ``` Chef does not merge any pull requests made against a Chef-managed open source repository until each commit has been signed for the DCO, with three exceptions: * “Obvious Fixes” (as described below) * Pull requests made against the docs.chef.io documentation repository (<https://github.com/chef/chef-web-docs>) * Pull requests that contain only documentation updates made against projects where the documentation is embedded in the project’s repository (i.e. the `docs` directory in the `chef/inspec` repository) The “Obvious Fix” Rule ---------------------- Chef’s contribution policy is aimed at encouraging broad participation from our community, and minimizing risks to Chef and our community due to inappropriate contributions of the intellectual property of others. As a general standard, Chef requires every contribution to by signed for the Developer Certificate of Origin (DCO). HOWEVER, very small contributions such as fixing spelling errors, where the content is small enough to not be considered intellectual property, can be submitted by a contributor as a patch, without a DCO sign-off. If you submit an obvious fix without a DCO sign-off, then you are agreeing that your submission is not independently copyrightable. The purpose of this exception is to lower the barrier for new contributors to make contributions while retaining the integrity of the project and our community. ### How does the Obvious Fix Rule Work? Any committer may commit fixes without a DCO sign-off for obvious typos, grammar mistakes, and formatting problems wherever they may be * in the web pages, API documentation, source code, etc. Whenever you invoke the “obvious fix” rule, please say so in your commit message. For example: ``` ------------------------------------------------------------------------ commit 370adb3f82d55d912b0cf9c1d1e99b132a8ed3b5 Author: <NAME> <<EMAIL>> Date: Wed Sep 18 11:44:40 2015 -0700 Fix typo in the README. Obvious fix. ------------------------------------------------------------------------ ``` ### What qualifies as an Obvious Fix? An obvious fix is a pull request that does not contain creative work. We rely on your judgment to determine what is “obvious”; if you’re not sure, just ask by sending an email to: oss AT getchef DOT com. As a rule of thumb, changes are obvious fixes if they do not introduce any new functionality or creative thinking. As long as the change does not affect functionality, some likely examples include the following: * Spelling/grammar fixes; * Correcting typos; * Cleaning up comments in the code; * Changes to white space or formatting; * Bug fixes that change default return values or error codes stored in constants, literals, or simple variable types; * Adding logging messages or debugging output; * Changes to ‘metadata’ files like Gemfile, rebar.config, Makefile, app.config, sys.config, .gitignore, example configuration files, build scripts, etc.; * Changes that reflect outside facts, like renaming a build directory or changing a constant; * Changes in build or installation scripts; * Re-ordering of objects or subroutines within a source file (such as alphabetizing routines); * Moving source files from one directory or package to another, with no changes in code; * Breaking a source file into multiple source files, or consolidating multiple source files into one source file, with no change in code behavior; * Changes to words or phrases isolated from their context; * Changes to typeface. Things that would still require a DCO sign-off before submitting would likely include stuff like the following: * Any of the above actions that result in a change in functionality; * A new feature; * A translation; * Extensive or creative comments. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/community_contributions/Supported Versions ================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/versions.md) This section lists the free and commercial Chef products and versions we currently support. The lifecycle stage defines the involvement by Chef Software in updating and maintaining each product. Lifecycle Definitions --------------------- ### Generally Available (GA) This stage indicates that the product or version is in active development and/or maintenance. * Chef continues to provide releases to the application or version in response to customer needs and security vulnerabilities * Chef welcomes customer feature requests for the product roadmap for the application ### Deprecated This stage indicates that an application or version is no longer in active development and will eventually move to end of life status. Chef continues to provide support [according to our SLAs](https://www.chef.io/service-level-agreement/). * Chef no longer provides scheduled releases * Customers should use the GA alternative to these products; contact us for help with product selection and deployment * Chef may provide a release for a critical defect or security vulnerability ### End of Life (EOL) This stage indicates that Chef has set a date after which the application or version will no longer be supported or recommended for use by customers. * As of the end of life date, the application will no longer be supported by Chef and will no longer be available for download * Documentation for the application will be moved to <https://docs-archive.chef.io ### Versions and Status Important Unless otherwise stated, versions older than those listed below are EOL. Supported Commercial Distributions ---------------------------------- Use of these and later versions of these distributions must be in accordance with the [Chef End User License Agreement](https://www.chef.io/end-user-license-agreement) or a commercial agreement with Chef. Additional information is available in [this announcement](https://blog.chef.io/2019/04/02/chef-software-announces-the-enterprise-automation-stack/). | Product | Version | Lifecycle Status | EOL Date | | --- | --- | --- | --- | | Chef Automate | Latest | GA | n/a | | Chef Infra Client | 17.x | GA | April 30, 2023 | | Chef Infra Server | 14.x | GA | n/a | | Chef Habitat | 0.81+ | GA | n/a | | Chef InSpec | 4.x | GA | n/a | | Chef Workstation | 20.x (2020), 21.x (2021) | GA | n/a | | Chef Backend | 3.x | Releasing 2021 | 2022 | Note **Chef Backend** does not directly require acceptance of the Chef EULA, but it does have functionality that requires its acceptance in other products. Supported Free Distributions ---------------------------- Use of the following distributions is governed by the Apache License, version 2.0. | Product | Version | Lifecycle Status | EOL Date | | --- | --- | --- | --- | | Supermarket | 3.x | GA | TBD | Deprecated Products and Versions -------------------------------- The following products are deprecated. Users are advised to move to newer versions or products. | Product | Version | Lifecycle Status | EOL Date | | --- | --- | --- | --- | | Chef Backend | 2.x | Deprecated | December 31, 2022 | | Chef Infra Client | 16.x | Deprecated | April 30, 2022 | | Chef Manage | 2.5.x+ | Deprecated | December 31, 2022 | End of Life (EOL) Products -------------------------- | Product | Version | Lifecycle Status | EOL Date | | --- | --- | --- | --- | | Analytics | All | EOL | December 31, 2018 | | Automate | 1.x | EOL | December 31, 2019 | | Chef Infra Client | 15 and under | EOL | April 30, 2021 | | Chef Compliance Server | All | EOL | December 31, 2018 | | ChefDK | ALL | EOL | December 31, 2020 | | Chef Infra Server | 13.x | EOL | June 30, 2021 | | Chef InSpec | 2 and under | EOL | December 31, 2019 | | Chef InSpec | 3.x | EOL | April 30, 2020 | | Chef Provisioning | All | EOL | August 31, 2019 | | Chef Push Jobs | All | EOL | December 31, 2020 | | Chef Replication/Sync | All | EOL | August 31, 2019 | | Chef Server DRBD HA | All | EOL | March 31, 2019 | | Chef Workflow (Delivery) | All | EOL | December 31, 2020 | | Enterprise Chef | All | EOL | December 31, 2018 | | Reporting | All | EOL | December 31, 2018 | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/versions/Developing Documentation ======================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/style_tools.md) This document covers the tools used by the @chef-docs team for developing documentation. GitHub ------ If you do not already have one, set up your [GitHub account](https://github.com/). Download and install Git onto your computer from [git-scm.com](https://git-scm.com/download) Configure Git: [First time setup](https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup) After you have Git setup, create a directory for your repositories. Some name this directory `code` or `repos`. Use whatever name makes sense for you. Homebrew -------- [Homebrew](https://brew.sh/) is a package manager for macOS. Install Homebrew with the command: ``` /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` ``` brew tap go-swagger/go-swagger chef/okta-aws && brew install go-swagger okta-aws hugo node go jq direnv readline openssl@1.1 gh vale vagrant virtualbox coreutils gnutls ``` This command installs * go-swagger * okta-aws * [Hugo](https://gohugo.io) * [Node.js](https://nodejs.org/en/) * [Go](https://golang.org/) * [JQ](https://stedolan.github.io/jq/) * [go-swagger](https://goswagger.io/) * [direnv](https://direnv.net/) * [readline](https://tiswww.case.edu/php/chet/readline/rltop.html) * [openssl@1.1](https://www.openssl.org/) * [gh](https://cli.github.com/) * vale * vagrant * virtualbox Chocolatey ---------- Install [Chocolatey](https://chocolatey.org/install) ``` choco install choco install hugo-extended nodejs golang jq gh ``` Install [Docker Desktop](https://www.docker.com/get-started) Install [go-swagger](https://goswagger.io/install.html#for-windows-users) * Download the Docker image: `docker pull quay.io/goswagger/swagger` * Run with: `docker run --rm -it --env GOPATH=/go -v %CD%:/go/src -w /go/src quay.io/goswagger/swagger` Visual Studio Code (VSCode) --------------------------- Microsoft’s VSCode is a free and open source editor. VSCode offers many extensions–including a Chef extension–that provide useful language and documentation support. Install [VSCode](https://code.visualstudio.com/) Learn a bit about VSCode through Microsoft Learn Videos and tutorials. * Setup Guide: [Visual Studio Code on macOS](https://code.visualstudio.com/docs/setup/mac) * Setup Guide: [Visual Studio Code on Windows](https://code.visualstudio.com/docs/setup/windows) * [User Interface](https://code.visualstudio.com/docs/getstarted/userinterface) * [Integrated Terminal](https://code.visualstudio.com/docs/editor/integrated-terminal) * [Getting started with Visual Studio Code Videos](https://code.visualstudio.com/docs/getstarted/introvideos) * [Working with GitHub in VS Code](https://code.visualstudio.com/docs/editor/github) * [Introduction to GitHub in Visual Studio Code](https://docs.microsoft.com/learn/modules/introduction-to-github-visual-studio-code/) Install the extensions: * Docs Authoring Pack (includes Code Street Spell and Markdownlint, adds some automatic configuration.) * Code Street Spell * Markdownlint * Vale * Better TOML * YAML * GitHub Pull Requests and Issues * Chef Extension for Visual Studio Code * LiveShare ### Code Spell Checker Clone the [Chef Dictionary](https://github.com/chef/chef_dictionary) into your repository directory ``` gh repo clone chef/chef_dictionary ``` Navigate to your VSCode settings by selecting the gear icon at the bottom left side of the VSCode screen and find the Code Spell settings. Open the setting for “C Spell Dictionaries” and add the following content, adjusting the path for your local workstation ``` "cSpell.dictionaryDefinitions": [ { "name": "chef_dictionary", "path": "/Users/<username>/<repodir>/chef_dictionary/chef_dictionary/chef.txt"} ], "cSpell.dictionaries": [ "chef_dictionary" ], ``` Add this configuration to exclude code blocks from spellcheck: ``` "cSpell.languageSettings": [ { // use with Markdown files "languageId": "markdown", // Exclude code blocks from spellcheck. "ignoreRegExpList": [ "/^\\s*```[\\s\\S]*?^\\s*```/gm" ] } ] ``` ### Markdownlint [Markdownlint-CLI2](https://github.com/DavidAnson/markdownlint-cli2) is a fast, flexible, configuration-based command-line interface for linting Markdown files. Install the Markdownlint CLI into your local environment: ``` npm install markdownlint-cli2 --global ``` `chef/chef-web-docs/.markdownlint.yaml` is the configuration file with the Markdown rules for Chef documentation files. This is a full list of Markdownlint [rules](https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md) To enable or disable rules for specific lines, add the appropriate marker: * Disable all rules: `<!-- markdownlint-disable -->` * Enable all rules: `<!-- markdownlint-enable -->` * Disable all rules for the next line only: `<!-- markdownlint-disable-next-line -->` * Disable one or more rules by name: `<!-- markdownlint-disable MD001 MD005 -->` * Enable one or more rules by name: `<!-- markdownlint-enable MD001 MD005 -->` * Disable one or more rules by name for the next line only: `<!-- markdownlint-disable-next-line MD001 MD005 -->` * Capture the current rule configuration: `<!-- markdownlint-capture -->` * Restore the captured rule configuration: `<!-- markdownlint-restore -->` To enable or disable rules for entire files, use: * Disable all rules: `<!-- markdownlint-disable-file -->` * Enable all rules: `<!-- markdownlint-enable-file -->` * Disable one or more rules by name: `<!-- markdownlint-disable-file MD001 -->` * Enable one or more rules by name: `<!-- markdownlint-enable-file MD001 -->` For more information about customizing Markdownlint, see the Markdownlint GitHub Repository [README](https://github.com/DavidAnson/markdownlint/blob/main/README.md#configuration). ### Vale [Vale](https://docs.errata.ai/vale/about) ``` # Example Vale config file (`.vale.ini` or `_vale.ini`)# Core settingsStylesPath = /Users/kimberlygarmoe/repos/styles# The minimum alert level to display (suggestion, warning, or error).## CI builds will only fail on error-level alerts.MinAlertLevel = warning# By default, `code` and `tt` are ignored.IgnoredScopes = code, tt, script# SkippedScopes specifies block-level HTML tags to ignore. Any content in these scopes will be ignored.SkippedScopes = script, style, pre, figure# WordTemplate specifies what Vale will consider to be an individual word.WordTemplate = `\b(?:%s)\b`# BlockIgnores allow you to exclude certain block-level sections of text that don't have an associated HTML tag that could be used with SkippedScopes. See Non-Standard Markup for more information.# BlockIgnores = (?s) *({< file [^>]* >}.*?{</ ?file >})# Ignore code fencesBlockIgnores = (((\x60{3}){1,1})([\s\S]*?)((\x60{3}){1,1}))# TokenIgnores allow you to exclude certain inline-level sections of text that don't have an associated HTML tag that could be used with IgnoredScopes. See Non-Standard Markup for more information.# TokenIgnores = (\$+[^\n$]+\$+)# Ignore SVG markupTokenIgnores = (**\{\w*\}**)# The "formats" section allows you to associate an "unknown" format# with one of Vale's supported formats.[formats]mdx = mdproto = md# Global settings (applied to every syntax)[*]Vocab = chef_dictionary# List of styles to loadBasedOnStyles = write-good, vale-chef# Chef, Microsoft# Style.Rule = {YES, NO} to enable or disable a specific rulewrite-good.Editorializing = YES# Microsoft.Contractions = NO# You can also change the level associated with a rulewrite-good.Hedging = warning# Syntax-specific settings# These overwrite any conflicting global settings[*.{md,txt}] ``` Download the Chef Repositories ------------------------------ Clone the following repositories: | Product | GitHub Docs Directory | | --- | --- | | Chef Automate | [https://github.com/chef/automate | | Chef Habitat | <https://github.com/habitat-sh/habitat> | | Chef Infra Client | <https://github.com/chef/chef-web-docs> | | Chef Infra Server | <https://github.com/chef/chef-server> | | Chef Inspec | <https://github.com/inspec/inspec> | For example, you can clone a repo using the GitHub CLI with the command `gh repo clone chef/chef-web-docs`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/style_tools/Hugo Guide ========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/style_hugo.md) Building -------- To build the docs locally, from the root of the `chef-web-docs` directory, run the command: ``` make serve ``` Add a New Page -------------- Adding a new page has two steps: 1. Create the page 2. Add the page to the left navigation bar From the root of the `chef-web-docs` directory, add a completely new page with the command: ``` hugo new content/page_name.md ``` Navigate to your new page in the `chef-web-docs/content` directory and edit the frontmatter accordingly. Add or Remove pages from the Left Nav Bar ----------------------------------------- Adding, removing, and changing the placement of a page in the left nav involves three steps: 1. Defining the page weight in the document’s front matter or the `config.toml` file 2. Verifying that the page appears as you intend in the left nav 3. Adjusting the weighting in affected pages accordingly Contact the documentation team if you have any questions about adding or removing pages. TOML Front Matter ----------------- Each page starts with [TOML front matter](https://gohugo.io/content-management/front-matter/) which contains metadata about the page and places it properly in the left navigation menu. Below is the TOML front matter for this page which you can use as a reference. Contact the Docs Team if you have any questions about properly formatting TOML front matter. ``` +++ title = "Example Documentation Page" description = "DESCRIPTION" draft = false gh_repo = "chef-web-docs" product = ["client", "server"] aliases = "/style_guide.html" [menu] [menu.infra] title = "Example Page" identifier = "infra/Example Documentation Page" parent = "infra" weight = 40 +++ ``` title The title of the page. This will appear at the top of the page. draft Set draft to `true` if you don’t want Hugo to build the page. aliases Add an alias if you want Hugo to automatically redirect the user from another page to the page you are writing. gh_repo The GitHub repository that the document originates from. This is used to generate “Edit on GitHub” links on each page. For example: `chef-server`, `chef-workstation`, `chef-web-docs`, `automate`. product `product` is a list of Chef products that are relevant to a page. Relevant values: * `automate` * `desktop` * `client` * `server` * `habitat` * `inspec` * `workstation` This list is used to facet search results in our documentation search by the product. Each section of the documentation has a default product parameter configured using [Front Matter Cascade](https://gohugo.io/content-management/front-matter#front-matter-cascade), however you may want to add a product if a page references more than one Chef product. For example, if a page in the Chef InSpec documentation describes passing data to Chef Automate, you may want to add `product = ["inspec", "automate"]` to the page frontmatter. menu title The title of the page as it would appear in the left navigation menu. menu identifier The identifier of the page that you are writing. Each identifier must be unique. The convention we’ve adopted is to use the identifier of the page’s parent, a forward slash, then the page file, a space, and then the page title. For example, this page’s parent identifier is `overview/style`, the page file is `style_guide.md` and the page title is `Docs Style Guide`, so the full page identifier is `overview/style/style_guide.md Docs Style Guide` menu parent The menu identifier of the page’s parent. The convention we’ve adopted is to append the different menu levels together, separated by a forward slash, and starting with the highest level. For example, this page is nested under Overview and then style, so the page’s parent identifier is `overview/style`. menu weight The rank that the page will appear in the menu, incremented by 10. Higher numbers are lower in the menu. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/style_hugo/System Requirements =================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/system_requirements.md) Hardware -------- Chef Automate requires a minimum of * 16 GB of RAM * 80 GB of disk space (available to `/hab`) * 4 vCPUs Operating system ---------------- Chef Automate requires * a Linux kernel of version 3.2 or greater * `systemd` as the init system * `useradd` * `curl` or `wget` * The shell that starts Automate should have a max open files setting of at least 65535 Commercial support for Chef Automate is available for platforms that satisfy these criteria. Supported Browsers ------------------ Chef Automate supports the current browser versions for Chrome, Edge, and Firefox. Chef Automate does not support other browsers and may not be compatible with older browser versions. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/system_requirements/Chef Software Packages ====================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/packages.md) Packages for Chef Software products may be installed using platform-native package repositories or the Chef Software Install script. Both installation methods support the following release channels: | Channel | Description | | --- | --- | | `stable` | A build from this channel is an "official" release that has passed full user acceptance testing. Artifacts in this channel are retained indefinitely. | | `current` | A build from this channel is an "integration" build that has passed full testing, but has not been officially released. Artifacts in this channel are retained for 30 days and then removed automatically. | Chef recommends using the stable channel when installing any of these products on production systems. Package Repositories -------------------- The `stable` and `current` release channels support the following package repositories: * Apt (Debian and Ubuntu platforms) * Yum (Enterprise Linux platforms) Chef Software’s GPG public key can be downloaded [here](https://packages.chef.io/chef.asc). ### Debian / Ubuntu To set up an Apt package repository for Debian and Ubuntu platforms: 1. Enable Apt to fetch packages over HTTPS: ``` sudo apt-get install apt-transport-https ``` 2. Install the public key for Chef Software: ``` wget -qO - https://packages.chef.io/chef.asc | sudo apt-key add - ``` 3. Create the Apt repository source file: ``` echo "deb https://packages.chef.io/repos/apt/<CHANNEL> <DISTRIBUTION> main" > chef-<CHANNEL>.list ``` Replace `<CHANNEL>` with the release channel: `stable` or `current`. Replace `<DISTRIBUTION>` with the appropriate distribution name: * For Debian 9: `stretch` * For Debian 10: `buster` * For Debian 11: `bullseye` * For Ubuntu 18.04: `bionic` * For Ubuntu 20.04: `focal` 4. Update the package repository list: ``` sudo mv chef-stable.list /etc/apt/sources.list.d/ ``` 5. Update the cache for the package repository: ``` sudo apt-get update ``` ### Enterprise Linux To set up a Yum package repository for Enterprise Linux platforms: 1. Install the public key for Chef Software: ``` sudo rpm --import https://packages.chef.io/chef.asc ``` 2. Create the Yum repository source file: ``` cat >chef-<CHANNEL>.repo <<EOL [chef-<CHANNEL>] name=chef-<CHANNEL> baseurl=https://packages.chef.io/repos/yum/<CHANNEL>/el/<VERSION>/\$basearch/ gpgcheck=1 enabled=1 EOL ``` Replace `<CHANNEL>` with the release channel: `stable` or `current`. Replace `<VERSION>` with your Enterprise Linux version; the allowable versions are `6`, `7`, or `8`. 3. Update the package repository list: ``` sudo yum-config-manager --add-repo chef-stable.repo ``` Note that the `yum-config-manager` command requires the `yum-utils` package, which is not installed on CentOS by default. You can install the package by running `sudo yum install yum-utils`, or you can use the `mv` command to add the repository to the `/etc/yum.repos.d/` directory: ``` sudo mv chef-stable.repo /etc/yum.repos.d/ ``` Chef Software Install Script ---------------------------- The Chef Software install script can be used to install any Chef Software, including things like Chef Infra Client, Chef Infra Server, Chef InSpec. This script does the following: * Detects the platform, version, and architecture of the machine on which the installer is being executed * Fetches the appropriate package, for the requested product and version * Validates the package content by comparing SHA-256 checksums * Installs the package ### Run the Chef Software Install Script The Chef Software Install script can be run on UNIX, Linux, and Microsoft Windows platforms. The terms ‘omnibus’ and ‘omnitruck’ are only relevant to the build processes used internally at Chef Software. #### UNIX and Linux On UNIX, Linux, and macOS systems, invoke the Chef Software Install script with: ``` curl -L https://omnitruck.chef.io/install.sh | sudo bash ``` and then enter the local password when prompted. #### Microsoft Windows On Microsoft Windows systems, invoke the Chef Software Install script using Windows PowerShell: ``` . { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install ``` ### Chef Software Install Script Options In addition to the default install behavior, the Chef Software Install script supports the following options: `-c` (`-channel` on Microsoft Windows) The release channel from which a package is pulled. Possible values: `current` or `stable`. Default value: `stable`. `-d` (`-download_directory` on Microsoft Windows) The directory into which a package is downloaded. When a package already exists in this directory and the checksum matches, the package is not re-downloaded. When `-d` and `-f` are not specified, a package is downloaded to a temporary directory. `-f` (`-filename` on Microsoft Windows) The name of the file and the path at which that file is located. When a filename already exists at this path and the checksum matches, the package is not re-downloaded. When `-d` and `-f` are not specified, a package is downloaded to a temporary directory. `-P` (`-project` on Microsoft Windows) The product name to install. Supported versions of Chef products are `automate`, `chef`, `chef-server`, `inspec`, `chef-workstation`, `chefdk`, `supermarket`, `chef-backend`, `push-jobs-client`, and `push-jobs-server`. Default value: `chef`. `-s` (`-install_strategy` on Microsoft Windows) The method of package installations. The default strategy is to always install when the install.sh script runs. Set to “once” to skip installation if the product is already installed on the node. `-l` (`-download_url_override` on Microsoft Windows) Install package downloaded from a direct URL. `-a` (`-checksum` on Microsoft Windows) The SHA256 for download_url_override `-v` (`-version` on Microsoft Windows) The version of the package to be installed. A version always takes the form x.y.z, where x, y, and z are decimal numbers that are used to represent major (x), minor (y), and patch (z) versions. A two-part version (x.y) is also allowed. For more information about application versioning, see <https://semver.org/>. ### Examples The following examples show how to use the Chef Software Install script. To install Chef Client 15.8.23: ``` curl -L https://omnitruck.chef.io/install.sh | sudo bash -s -- -v 15.8.23 ``` To install the latest version of Chef Workstation on Microsoft Windows from the `current` channel: ``` . { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install -channel current -project chef-workstation ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/packages/Chef Software Install Script ============================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_install_script.md) The Chef Software install script can be used to install any Chef Software, including things like Chef Infra Client, Chef Infra Server, Chef InSpec. This script does the following: * Detects the platform, version, and architecture of the machine on which the installer is being executed * Fetches the appropriate package, for the requested product and version * Validates the package content by comparing SHA-256 checksums * Installs the package Run the Chef Software Install Script ------------------------------------ The Chef Software Install script can be run on UNIX, Linux, and Microsoft Windows platforms. The terms ‘omnibus’ and ‘omnitruck’ are only relevant to the build processes used internally at Chef Software. ### UNIX, Linux, and macOS On UNIX, Linux, and macOS systems, invoke the Chef Software Install script with: ``` curl -L https://omnitruck.chef.io/install.sh | sudo bash ``` and then enter the local password when prompted. ### Microsoft Windows On Microsoft Windows systems, invoke the Chef Software Install script using Windows PowerShell: ``` . { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install ``` Chef Software Install Script Options ------------------------------------ In addition to the default install behavior, the Chef Software Install script supports the following options: `-c` (`-channel` on Microsoft Windows) The release channel from which a package is pulled. Possible values: `current` or `stable`. Default value: `stable`. `-d` (`-download_directory` on Microsoft Windows) The directory into which a package is downloaded. When a package already exists in this directory and the checksum matches, the package is not re-downloaded. When `-d` and `-f` are not specified, a package is downloaded to a temporary directory. `-f` (`-filename` on Microsoft Windows) The name of the file and the path at which that file is located. When a filename already exists at this path and the checksum matches, the package is not re-downloaded. When `-d` and `-f` are not specified, a package is downloaded to a temporary directory. `-P` (`-project` on Microsoft Windows) The product name to install. Supported versions of Chef products are `automate`, `chef`, `chef-server`, `inspec`, `chef-workstation`, `chefdk`, `supermarket`, `chef-backend`, `push-jobs-client`, and `push-jobs-server`. Default value: `chef`. `-s` (`-install_strategy` on Microsoft Windows) The method of package installations. The default strategy is to always install when the install.sh script runs. Set to “once” to skip installation if the product is already installed on the node. `-l` (`-download_url_override` on Microsoft Windows) Install package downloaded from a direct URL. `-a` (`-checksum` on Microsoft Windows) The SHA256 for download_url_override `-v` (`-version` on Microsoft Windows) The version of the package to be installed. A version always takes the form x.y.z, where x, y, and z are decimal numbers that are used to represent major (x), minor (y), and patch (z) versions. A two-part version (x.y) is also allowed. For more information about application versioning, see <https://semver.org/>. Examples -------- The following examples show how to use the Chef Software Install script. To install Chef Client 15.8.23: ``` curl -L https://omnitruck.chef.io/install.sh | sudo bash -s -- -v 15.8.23 ``` To install the latest version of Chef Workstation on Microsoft Windows from the `current` channel: ``` . { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install -channel current -project chef-workstation ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_install_script/Content Reuse and Hugo Shortcodes ================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/style_reuse.md) Chef docs uses [shortcodes](https://gohugo.io/content-management/shortcodes/) to maintain text that appears in more than one location and must be consistent in every location. Writing a Shortcode ------------------- Shortcode files are written in **Markdown** or **HTML** and are stored in the [`layouts/shortcodes`](https://github.com/chef/chef-web-docs/tree/main/themes/docs-new/layouts/shortcodes) directory in the `chef-web-docs` repo. Most shortcodes are written in Markdown but some are in HTML. Adding a Shortcode to a Page ---------------------------- There are two types of shortcodes, **Markdown** and **HTML**. The type of shortcode determines how it is added to a page and how Hugo processes the text when it renders the page into HTML. Note If you add a **Markdown** shortcode to a page using **HTML** shortcode delimiters, Hugo will assume that the text is already formatted in HTML and won’t run the shortcode file through its Markdown processor, leaving the bare Markdown in the HTML page output. ### Markdown Shortcodes To include a Markdown shortcode in a page, wrap the name of the shortcode file, without the file type suffix, in between double curly braces and percent characters, `{{% SHORTCODE %}}`. For example, if you wanted to add the [`chef.md`](https://github.com/chef/chef-web-docs/blob/main/themes/docs-new/layouts/shortcodes/chef.md) shortcode to a page, add the following text to the Markdown page: ``` {{% chef %}} ``` ### HTML Shortcodes To include an HTML shortcode in a page, wrap the name of the shortcode file, without the file type suffix, in between double curly braces and angle brackets, `{{< SHORTCODE >}}`. For example, add the following text to a page if you wanted to add the [`chef_automate_mark.html`](https://github.com/chef/chef-web-docs/blob/main/themes/docs-new/layouts/shortcodes/chef_automate_mark.html) shortcode: ``` {{< chef_automate_mark >}} ``` ### Parameters Some shortcodes accept positioned or named parameters. For example, the `example_fqdn` shortcode requires a hostname, which is added like this: `{{< example_fqdn "HOSTNAME" >}}`, and produces the following output: `HOSTNAME.example.com`. The [Fontawesome Shortcode](#fontawesome-shortcode) accepts named parameters. For example, it accepts a class value which is added like this: `{{< fontawesome class="fas fa-ellipsis-h" >}}` See the [Fontawesome Shortcode](#fontawesome-shortcode) section for more examples. ### Nested Content We have some shortcodes that nest around Markdown content that is included in the text of a page. Those shortcodes are all written in HTML. Note the slash `/` before the name of the closing shortcode. ``` {{< shortcode_name >}} Some Markdown text. {{< /shortcode_name >}} ``` See the [Notes and Warnings](#notes-warnings-and-admonitions) and the [Foundation Tabs](#foundation-tabs-container) for examples of nested shortcodes. Notes, Warnings, and Admonitions -------------------------------- In general, notes, warnings, and admonitions are not the best way to present important information. Before using them ask yourself how important the information is. If you want the information to be returned in a search result, then it is better for the information to have its own topic or section heading. Notes and warnings have a different color than the surrounding text so they can be easily spotted within a doc. If notes and warnings must be used, the approach for using them is as follows. Notes and warnings are generated by bracketing the text of the note or warning in **note**, **warning**, or **danger** shortcodes. ### Notes ``` {{< note >}} This is a note. {{< /note >}} ``` What a note looks like after it’s built: Note This is a note. ### Warnings Use sparingly so that when the user sees a warning it registers appropriately: ``` {{< warning >}} This is a warning. {{< /warning >}} ``` What a warning looks like after it’s built: Warning This is a warning. ### Danger Danger should be used rarely and only when there are serious consequences for the user: ``` {{< danger >}} This is a danger block. {{< /danger >}} ``` This is what a danger block looks like after it’s built: Danger This is a danger block. Foundation Tabs Container ------------------------- There are four shortcodes that can be combined together to create a container that will allow the user to click on a tab to reveal content in a matching panel. For example, you may want to display matching Ruby and YAML code blocks. You can create two tabs, one titled **Ruby** and the other **YAML**, and the user could click on one tab to show the Ruby code block and another tab to show the YAML code block. See the [example](#example) below. The four shortcodes are: * `foundation_tabs` * `foundation_tab` * `foundation_tabs_panels` * `foundation_tabs_panel` These shortcodes use the [Zurb Foundation Tabs](https://get.foundation/sites/docs/tabs.html) component. The container consists of two parts, the tabs and the panels. ### Tabs Each tab is created with a `foundation_tab` shortcode. Use as many `foundation_tab` shortcodes as you need to display the number of code blocks or text blocks that you want the user to be able click on and reveal. All `foundation_tab` shortcodes must be contained within opening and closing `foundation_tabs` shortcodes. For example: ``` {{< foundation_tabs tabs-id="ruby-python-panel" >}} {{< foundation_tab active="true" panel-link="ruby-panel" tab-text="Ruby" >}} {{< foundation_tab panel-link="python-panel" tab-text="Python" >}} {{< /foundation_tabs >}} ``` #### Tab Parameters The **`foundation_tabs`** shortcode has one parameter: `tabs-id` This value must be identical to the `tabs-id` value in the `foundation_tabs_panels` shortcode, but otherwise it must be unique on the page. The **`foundation_tab`** shortcode has three parameters: `active` Use `active="true"` to highlight the tab that user will see when they first load the page. Only add this value to one tab. The matching `foundation_tabs_panel` should also have `active="true"` in its parameters. `panel-link` This is the value of the panel ID that this tab will link to. This must be identical to the `panel-id` value in the matching `foundation_tabs_panel` shortcode. `tab-text` The text in the tab that the user will click on. ### Panels Each tab has a matching panel which is created with `foundation_tabs_panel` shortcodes. The Markdown text that is displayed in each panel must be contained in opening and closing `foundation_tabs_panel` shortcodes. All `foundation_tab_panel` shortcodes must contained within opening and closing `foundation_tabs_panels` shortcodes. For example: ``` {{< foundation_tabs_panels tabs-id="ruby-python-panel" >}} {{< foundation_tabs_panel active="true" panel-id="ruby-panel" >}} ```ruby puts 'Hello, world!' ``` {{< /foundation_tabs_panel >}} {{< foundation_tabs_panel panel-id="python-panel" >}} ```python print('Hello, world!') ``` {{< /foundation_tabs_panel >}} {{< /foundation_tabs_panels >}} ``` #### Panel Parameters The **`foundation_tabs_panels`** shortcode has one parameter: `tabs-id` This value must be identical to the `tabs-id` value in the `foundation_tabs` shortcode, but otherwise it must be unique on the page. The **`foundation_tabs_panel`** shortcode has two parameters: `active` Use `active="true"` to indicate which panel the user will see when they first load the page. This value should also be added to the panels matching tab. Only add this value to one panel. `panel-id` The HTML ID attribute of the panel. This value must be identical to the `panel-link` value in the matching `foundation_tab` shortcode that will link to this panel. This value must be unique on the page. ### Example Below is an example of a container that shows three code blocks in three languages. You can copy and paste the code below into a page to get started. Note that the `tabs-id` and `panel-id`/`panel-link` values must be unique on the page. * [Ruby](#ruby-panel) * [Python](#python-panel) * [Go](#golang-panel) ``` puts 'Hello, world!' ``` ``` print('Hello, world!') ``` ``` package main import "fmt" func main() { fmt.Println("Hello, world!") } ``` ``` {{< foundation_tabs tabs-id="ruby-python-go-panel" >}} {{< foundation_tab active="true" panel-link="ruby-panel" tab-text="Ruby">}} {{< foundation_tab panel-link="python-panel" tab-text="Python" >}} {{< foundation_tab panel-link="golang-panel" tab-text="Go" >}} {{< /foundation_tabs >}} {{< foundation_tabs_panels tabs-id="ruby-python-go-panel" >}} {{< foundation_tabs_panel active="true" panel-id="ruby-panel" >}} ```ruby puts 'Hello, world!' ``` {{< /foundation_tabs_panel >}} {{< foundation_tabs_panel panel-id="python-panel" >}} ```python print('Hello, world!') ``` {{< /foundation_tabs_panel >}} {{< foundation_tabs_panel panel-id="golang-panel" >}} ```go package main import "fmt" func main() { fmt.Println("Hello, world!") } ``` {{< /foundation_tabs_panel >}} {{< /foundation_tabs_panels >}} ``` Fontawesome Shortcode --------------------- The Fontawesome shortcode will display any free [Font Awesome icon](https://fontawesome.com/icons) in a page. It accepts the following parameters: * `background-color` * `border` * `border-radius` * `class` * `color` * `font-size` * `margin` * `padding` The only required parameter is `class`, which is the same as the class name of the icon. The following shortcode examples will display these icons: ``` {{< fontawesome class="fas fa-ellipsis-h" >}} {{< fontawesome class="fas fa-anchor" font-size="3rem" border="2px dashed" padding="1px" border-radius="5px" >}} {{< fontawesome class="fas fa-archive" color="#cc814b" margin="0 0 0 12px">}} {{< fontawesome class="far fa-address-book" background-color="DarkBlue" color="rgb(168, 218, 220)" >}} ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/style_reuse/About Chef Licenses =================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_license.md) All Chef products have a license that governs the entire product, while some have separate licenses for the project source code and the distribution that we build from it. Third-party software included in our distributions may have individual licenses, which are listed in the `/opt/<PRODUCT-NAME>/LICENSE` file. Individual copies of all referenced licenses can be found in the `/opt/<PRODUCT-NAME>/LICENSES` directory. In April 2019 many of our software distributions switched to being governed under the Chef EULA, while the software projects remained governed by the Apache 2.0 license. To understand which license applies to those distributions, see the [versions page](../versions/index). General information about this change can be found in our [announcement](https://blog.chef.io/2019/04/02/chef-software-announces-the-enterprise-automation-stack/). Chef EULA --------- The commercial distributions of our products—such as Chef Infra Client, Chef Habitat, or Chef InSpec— are governed by either the [Chef End User License Agreement (Chef EULA)](https://www.chef.io/end-user-license-agreement) or your commercial agreement with Progress Software Corporation as a customer. You are required to accept these terms when using the distributions for the first time. For additional information on how to accept the license, see [Accepting the Chef License](../chef_license_accept/index) documentation. Chef MLSA --------- Distributions of older proprietary Chef products—such as Chef Automate 1.x and the Chef Management Console—are governed by the [Chef Master License and Services Agreement (Chef MLSA)](https://www.chef.io/online-master-agreement), which must be accepted as part of any install or upgrade process. Apache 2.0 ---------- All source code of our open source Chef projects—such as Chef Infra Client, Chef Automate, or Chef InSpec—are governed by the [Apache 2.0 license](https://www.apache.org/licenses/LICENSE-2.0). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_license/Markdown Guide ============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/style_markdown.md) Section Headings ---------------- The following sections describe the section heading pattern that Chef is using for topic titles, H1s, H2s, H3s and H4s. As a general rule, limit the number of heading levels to no more than two within a topic. There can be exceptions, especially if the document is very large, but remember that HTML TOC structures usually have width limitations (on the display side) and the more structure within a TOC, the harder it can be for users to figure out what’s in it. Unless the topics are about installing things or about API endpoints, the headings should never wrap. Keep them to a single line. The width of heading adornment must be at least equal to the length of the text in the heading and the same width for headings is used everywhere. Consistent width is preferred. ### H1 The H1 heading is reserved for the page title which is created by the Hugo page template. The Markdown file text should not have any H1 headings. ### H2 Use two hash characters (##) before the heading name to indicate H2 headings: ``` ## H2 Heading This is the body. ``` ### H3 Use three hash characters (###) before the heading name to indicate H3 headings: ``` ### H3 Heading This is the body. ``` ### H4 Use four hash characters (####) before the heading name to indicate H4 headings: ``` #### H4 Heading This is the paragraph. ``` ### Other headings If you need more than four heading levels, use bold emphasis and then white space to make the heading text stand out and separate the heading from the content: ``` **heading name goes here** # bold emphasis # blank line content, as normally authored. ``` Lists ----- The following sections describe conventions for lists and tables in Chef docs. ### Bulleted Lists Bulleted lists break up text blocks and draw attention to a group of items: ``` * text goes here * text goes here * subitem text * subitem text * text goes here * text goes here ``` Use the dash symbol (-) for bulleted lists, even though Hugo supports other symbols. Indent nested list items by **four** spaces. ### Numbered Lists Numbered lists are created like this: ``` 1. text goes here 1. text goes here 1. text goes here 1. sub-list text 1. sub-list text 1. text goes here ``` Start each ordered list item with the number 1 (1.). Hugo will generate the correct sequence of numbers in an ordered list regardless of the numbers that you use. Only using “1.” will save you from having to re-number items if you add or remove an item later. ### Definition Lists Definition lists are used to show the options available to a command line tool: ``` `--name-only` : Show only the names of modified files. `--name-status` : Show only the names of files with a status of `Added`, `Deleted`, `Modified`, or `Type Changed`. ``` Tables ------ Create tables in Markdown like this: ``` Chef Software | Description --------|------ Infra Client | Awesome Infra Server | Fun Habitat | Super cool ``` Use three or more hyphens (—) to separate each column’s header from the content of the table. Separate columns with a vertical bar or pipe (|). Inline Markup ------------- Adding emphasis within text strings can be done using **bold** and `code strings`. ### Bold Use two asterisks (*) to mark a text string as **bold**: ``` **text goes here** text ### Code Strings Sometimes the name of a method or database field needs to be used inline in a paragraph. Use **one** back quote to mark certain strings as `code` within a regular string of text: `code goes here` ## Links To make a link in Markdown put the page title in square brackets followed by the link in parentheses. For example this: `[Ruby Programming Language](https://www.ruby-lang.org/)` will produce this: [Ruby Programming Language](https://www.ruby-lang.org/) External links requires an HTTP address. ### relref Links We recommend using Hugo's built-in [relref shortcode](https://gohugo.io/content-management/shortcodes/#ref-and-relref) for making relative links to other pages in the documentation. The site build will fail if a link is made to a page that does not exist. This ensures that we catch bad links if a page is deleted but a link to that page isn't removed. #### Examples Link to pages: * `[link text]({{< relref "some_page" >}})` * `[link text]({{< relref "section/some_page" >}})` Link to headings: * `[link text]({{< relref "#heading_on_this_page" >}})`. * `[link text]({{< relref "some_page#heading_on_other_page" >}})`. * `[link text]({{< relref "section/some_page#heading_on_other_page" >}})`. ## Code Blocks Code blocks are used to show code samples, such as those for Ruby, JSON, and command-line strings. ### Ruby Use this approach to show code blocks that use Ruby: ```ruby default['apache']['dir'] = '/etc/apache2' default['apache']['listen_ports'] = [ '80', '443' ] ``` ### Bash Use this approach to show code blocks that use any type of shell command, such as for Knife or the Chef Infra Client or for any other command-line example that may be required: ``` $ knife data bag create admins ``` ### Javascript (and JSON) Use this approach to show code blocks that use any type of JavaScript, including any JSON code sample: ``` { "id": "charlie", "uid": 1005, "gid":"ops", "shell":"/bin/zsh", "comment":"Crazy Charlie" } ``` ### Literal Literals should be used sparingly, but sometimes there is a need for a block of text that doesn’t work in a fenced code block, such as showing a directory structure, basic syntax, or pseudocode. To make a literal code block, indent the text by **four** spaces: ``` a block of literal text indented three spaces with more text as required to complete the block of text. end. ``` Images ------ You have two options for formatting images in Hugo: * Markdown syntax * the `figure` shortcode ### Markdown syntax To add an image in Markdown, use an exclamation point, square brackets around the alt text, parenthesis around the path to the image file starting in the `static` directory, and then optional hover text. For example: ``` ![Alt Text](/path/to/img.png "Optional Title") ``` ### Figure Shortcode The [figure shortcode](https://gohugo.io/content-management/shortcodes/#figure) allows you to specify the image size and include a title, a caption, and alternate text. SVG images should be formatted using the `figure` shortcode. ``` {{< figure src="/images/chef-logo.svg" title="Chef Logo" height="100" width="150" >}} ``` Which looks like this: ![] #### Chef Logo Raster images should be 96 dpi and no larger than 600 pixels wide. This helps ensure that the image can be printed and/or built into other output formats more easily; in some cases, separate 300 dpi files should be maintained for images that require inclusion in formats designed for printing and/or presentations. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/style_markdown/Installation Guide ================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/install.md) Before beginning your installation, check the [System Requirements](../system_requirements/index) for Chef Automate. See [Airgapped Installation](../airgapped_installation/index) for installing Chef Automate to a host with no inbound or outbound internet traffic. Download the Chef Automate Command-Line Tool -------------------------------------------- Download and unzip the Chef Automate command-line tool: ``` curl https://packages.chef.io/files/current/latest/chef-automate-cli/chef-automate_linux_amd64.zip | gunzip - > chef-automate && chmod +x chef-automate ``` Create Default Configuration ---------------------------- Create a `config.toml` file with default values for your Chef Automate installation: ``` sudo ./chef-automate init-config ``` You can customize your FQDN, login name, and other values, by changing the values in the `config.toml` in your editor. If you have requirements around data size and/or redundancy, see [Configuring External Data Stores](#configuring-external-data-stores) for information on configuring Chef Automate to use an externally-deployed PostgreSQL database cluster and/or Elasticsearch cluster. If you have requirements around a highly-available deployment of Chef Automate, please reach out to a Customer Success or Professional Services representative for assistance. See [Configuring Chef Automate](../configuration/index) for more information on configuration settings. Deploy Chef Automate -------------------- ``` sudo ./chef-automate deploy config.toml ``` Deployment takes a few minutes. The first step is accepting the terms of service in the command line, after which the installer performs a series of pre-flight checks; any unsuccessful checks have information for resolving issues or skipping the check. Run the deploy command again, after resolving any pre-flight issues. At the end of the deployment process you will see: ``` Deploy complete ``` The deployment process writes login credentials to the `automate-credentials.toml` in your current working directory. Open Chef Automate ------------------ Navigate to `https://automate.example.com` in a browser and log in to Chef Automate with the credentials provided in `automate-credentials.toml`. Once you log in, Chef Automate prompts you for a license. When your Chef Automate instance is equipped with internet connectivity, you can get a 60-day trial license from there. Alternatively, a license obtained by other means can be applied. ### Configure Data Collection To send data from your Chef Infra Server or Chef Infra Clients to Chef Automate 2, the process is the same as Chef Automate 1. See [“Configure Data Collection”](../data_collection/index) for more information. Upgrades -------- By default, Chef Automate will automatically upgrade to the latest version available. These updates can be taken safely, as we’ve committed to ensuring the stability of the upgrade process - automatic updates will never introduce breaking changes. ### Release Channels The Chef Automate upgrade process makes use of **release channels** to allow greater control over the automatic upgrades applied to your system. Chef Automate will always pull from the latest release within its specified release channel. We’re initially shipping with the default `current` channel, but additional channels will be introduced in the future. To change the release channel that is used for upgrades, modify the `channel` setting in your `config.toml` file: ``` channel = "current" ``` ### Disable Automatic Upgrades You can disable automatic upgrades by modifying the `upgrade_strategy` setting in your `config.toml` file: ``` upgrade_strategy = "none" ``` To manually initiate an upgrade, run ``` chef-automate upgrade run ``` This command upgrades Chef Automate to the latest version available from your release channel. ### Common Problems If you are unable to open Chef Automate, check that the `config.toml` contains the public DNS as the FQDN. ``` # This is a default Chef Automate configuration file. You can run # 'chef-automate deploy' with this config file and it should # successfully create a new Chef Automate instance with default settings. [global.v1] # The external fully qualified domain name. # When the application is deployed you should be able to access 'https://<fqdn>/' # to login. fqdn = "<_Public DNS_name>" ``` Once you correct and save the FQDN, run ``` sudo chef-automate config patch config.toml ``` and retry opening Chef Automate in your browser. ### Configuring External Data Stores You can configure Chef Automate to use PostgreSQL and Elasticsearch clusters that are not deployed via Chef Automate itself. The directions provided below are intended for use only during initial deployment of Chef Automate. #### Configuring External Elasticsearch Note Chef Automate supports the official Elasticsearch Service by Elastic. Chef Automate does not test or support alternative services, such as Amazon Elasticsearch Service (Amazon ES). Add the following to your config.toml: ``` [global.v1.external.elasticsearch] enable = true nodes = ["http://elastic1.example:9200", "http://elastic2.example:9200", "..." ] # Uncomment and fill out if using external elasticsearch with SSL and/or basic auth # [global.v1.external.elasticsearch.auth] # scheme = "basic_auth" # [global.v1.external.elasticsearch.auth.basic_auth] ## Create this elasticsearch user before starting the Automate deployment; ## Automate assumes it exists. # username = "<admin username>" # password = "<admin password>" # [global.v1.external.elasticsearch.ssl] # Specify either a root_cert or a root_cert_file # root_cert = """$(cat </path/to/cert_file.crt>)""" # server_name = "<elasticsearch server name>" # Uncomment and fill out if using external elasticsearch that uses hostname-based routing/load balancing # [esgateway.v1.sys.ngx.http] # proxy_set_header_host = "<your external es hostname>:1234" # Uncomment and add to change the ssl_verify_depth for the root cert bundle # ssl_verify_depth = "2" ``` Because externally-deployed Elasticsearch nodes will not have access to Chef Automate’s built-in backup storage services, you must configure Elasticsearch backup settings separately from Chef Automate’s primary backup settings. You can configure backups to use either the local filesystem or S3. ##### Adding Resolvers for Elasticsearch In case you want to resolve the Elasticsearch node IPs dynamically using DNS servers, you can add resolvers/nameservers to the configuration. Name Servers can be added in two ways: 1. **Add nameserver IPs:** Add the nameservers to your `config.toml` file to resolve the Elasticsearch nodes. ``` [esgateway.v1.sys.ngx.main.resolvers] # Multiple resolvers can be specified by adding the resolvers in the list. nameservers = ["192.0.2.0:24", "198.51.100.0:24"] ``` 2. **Set system DNS entries:** To use existing system nameserver entries from `/etc/resolv.conf`, add the following setting to `config.toml`: ``` [esgateway.v1.sys.ngx.main.resolvers] enable_system_nameservers = true ``` If both options are set, nameserver IPs takes precedence over the system nameserver entries. Apply the changes: ``` sudo chef-automate config patch config.toml ``` If you wish to reset to the default configuration or to modify the configuration: 1. Run `chef-automate config show config.toml`. 2. Open `config.toml` and remove the `esgateway.v1.sys.ngx.main.resolvers` configuration or change the values. 3. Run `chef-automate config set config.toml` to apply your changes. ##### Backup Externally-Deployed Elasticsearch to Local Filesystem To configure local filesystem backups of Chef Automate data stored in an externally-deployed Elasticsearch cluster: 1. Ensure that the filesystems you intend to use for backups are mounted to the same path on all Elasticsearch master and data nodes. 2. Configure the Elasticsearch `path.repo` setting on each node as described in the [Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-snapshots.html#_shared_file_system_repository). 3. Add the following to your `config.toml`: ``` [global.v1.external.elasticsearch.backup] enable = true location = "fs" [global.v1.external.elasticsearch.backup.fs] # The `path.repo` setting you've configured on your Elasticsearch nodes must be # a parent directory of the setting you configure here: path = "/var/opt/chef-automate/backups" ``` ##### Backup Externally-Deployed Elasticsearch to AWS S3 To configure AWS S3 backups of Chef Automate data stored in an externally-deployed Elasticsearch cluster: 1. Install the [`repository-s3` plugin](https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-s3.html) on all nodes in your Elasticsearch cluster. 2. If you wish to use IAM authentication to provide your Elasticsearch nodes access to the S3 bucket, you must apply the appropriate IAM policy to each host system in the cluster. 3. Configure each Elasticsearch node with a S3 client configuration containing the proper S3 endpoint, credentials, and other settings as [described in the Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-s3-client.html). 4. Enable S3 backups by adding the following settings to your `config.toml`: ``` [global.v1.external.elasticsearch.backup] enable = true location = "s3" [global.v1.external.elasticsearch.backup.s3] # bucket (required): The name of the bucket bucket = "<bucket name>" # base_path (optional): The path within the bucket where backups should be stored # If base_path is not set, backups will be stored at the root of the bucket. base_path = "<base path>" # name of an s3 client configuration you create in your elasticsearch.yml # see https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-s3-client.html # for full documentation on how to configure client settings on your # Elasticsearch nodes client = "<client name>" [global.v1.external.elasticsearch.backup.s3.settings] ## The meaning of these settings is documented in the S3 Repository Plugin ## documentation. See the following links: ## https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-s3-repository.html ## Backup repo settings # compress = false # server_side_encryption = false # buffer_size = "100mb" # canned_acl = "private" # storage_class = "standard" ## Snapshot settings # max_snapshot_bytes_per_sec = "40mb" # max_restore_bytes_per_sec = "40mb" # chunk_size = "null" ## S3 client settings # read_timeout = "50s" # max_retries = 3 # use_throttle_retries = true # protocol = "https" ``` ##### Backup Externally-Deployed Elasticsearch to GCS To configure Google Cloud Storage Bucket (GCS) backups of Chef Automate data stored in an externally-deployed Elasticsearch cluster: 1. Install the [`repository-gcs` plugin](https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-gcs.html) on all nodes in your Elasticsearch cluster. 2. Create a storage bucket and configure a service account to access it per the steps [described in the Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-gcs-usage.html). 3. Configure each Elasticsearch node with a GCS client configuration that contains the proper GCS settings as [described in the Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-gcs-client.html). 4. Enable GCS backups by adding the following settings to your `config.toml`: ``` [global.v1.external.elasticsearch] enable = true nodes = ["https://my-es.cluster"] ## If multiple # nodes = ["https://my-es.node-1", "https://my-es.node-2", "etc..."] ## The following settings are required if you have Elasticsearch setup with basic auth #[global.v1.external.elasticsearch.auth] # scheme = "basic_auth" # #[global.v1.external.elasticsearch.auth.basic_auth] # username = "everyuser" # password = "pass123" [global.v1.external.elasticsearch.backup] enable = true location = "gcs" [global.v1.external.elasticsearch.backup.gcs] bucket = "<bucket name>" # Client name is normally default, but can be set here if you have generated service # account credentials with a different client name client = "default" ## GCS Bucket Settings: # type = nearline # access control = uniform ``` #### Configuring an External PostgreSQL Database Add the following settings to your `config.toml`: ``` [global.v1.external.postgresql] enable = true nodes = ["<pghostname1>:<port1>", "<pghostname2>:<port2>", "..."] # To use postgres with SSL, uncomment and fill out the following: # [global.v1.external.postgresql.ssl] # enable = true # root_cert = """$(cat </path/to/root/cert.pem>)""" [global.v1.external.postgresql.auth] scheme = "password" # Create these postgres users before starting the Automate deployment; # Automate assumes they already exist. [global.v1.external.postgresql.auth.password.superuser] username = "<admin username>" password = "<admin password>" [global.v1.external.postgresql.auth.password.dbuser] username = "<dbuser username>" password = "<dbuser password>" [global.v1.external.postgresql.backup] enable = true ``` ##### Adding Resolvers for PostgreSQL Database In case you want to resolve the PostgreSQL cluster node IPs dynamically using DNS servers, you can add resolvers/nameservers to the configuration. Name Servers can be added in two ways: 1. **Add nameserver IPs:** If you are aware of the nameservers which should resolve the PostgreSQL nodes, the nameservers can be added to your `config.toml` file. ``` [pg_gateway.v1.sys.resolvers] # Multiple resolvers can be specified by adding the resolvers in the list. nameservers = ["127.0.0.53:53"] ``` 2. **Set system DNS entries:** To use existing system nameserver entries from `/etc/resolv.conf`, add the following setting to `config.toml`: ``` [pg_gateway.v1.sys.resolvers] enable_system_nameservers = true ``` If both options are set, nameserver IPs takes precedence over the system nameserver entries. Apply the changes: ``` sudo chef-automate config patch config.toml ``` If you wish to reset to the default configuration or to modify the configuration: 1. Run `chef-automate config show config.toml`. 2. Edit `config.toml` to replace/edit the `pg_gateway.v1.sys.resolvers` section with the configuration values. 3. Run `chef-automate config set config.toml` to apply your changes. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/install/Platforms ========= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/platforms.md) Chef software is supported on the operating systems (platforms) listed below. To see which versions of our software we currently support, see the [Supported Versions](../versions/index) page. Support ------- We offer two levels of support for platforms (operating systems), [Commercial Support](#commercial-support) and [Community Support](#community-support). ### Commercial Support Commercial support for platforms is part of paid maintenance contracts with Chef Software. Support contracts allow you to open tickets and receive service level agreement (SLA) assistance from our support desk. Commercially supported platforms are extensively tested as part of Chef’s development and release process. Commercial support generally follows the lifecycle of the underlying operating system vendor. Commercial support is limited to the platforms listed in the “Commercial Support” tables–platforms not listed in these tables are unsupported. ### Community Support Community support for platforms means that members of the Chef community have contributed to these platforms and Chef does not actively work to maintain this functionality. Chef does not explicitly test community supported platforms as part of the development and release process. Many of these platforms are forks, clones, or otherwise derivative of platforms that Chef commercially supports. Continued functionality for these platforms is likely, but not guaranteed. Unsupported platforms may have missing or non-operative functionality. As always, we welcome community contributions from anyone looking to expand community support for platforms in Chef products. Platforms --------- The sections below list the platforms that Chef Software supports. ### Chef Infra Client #### Commercial Support The following table lists the commercially-supported platforms and versions for Chef Infra Client: | Platform | Architecture | Version | | --- | --- | --- | | AIX | `powerpc` | `7.1` (TL5 SP2 or higher, recommended), `7.2` | | Amazon Linux | `x86_64`, `aarch64` | 2.x | | CentOS | `x86_64`, `ppc64le` (7.x only), `ppc64` (7.x only), `aarch64` (7.x / 8.x only) | `6.x`, `7.x`, `8.x` | | Debian | `x86_64``aarch64` (10.x/11.x only) | `9`, `10`, `11` | | FreeBSD | `amd64` | `11.x`, `12.x` | | macOS | `x86_64`, `aarch64` (M1 processors) | `10.15`, `11.x`, `12.x` | | Oracle Enterprise Linux | `x86_64``aarch64` (7.x / 8.x only) | `6.x`, `7.x`, `8.x` | | Red Hat Enterprise Linux | `x86_64`, `ppc64le` (7.x only), `ppc64` (7.x only), `aarch64` (7.x / 8.x only), `s390x` | `6.x`, `7.x`, `8.x` | | Solaris | `sparc`, `i86pc` | `11.3 (16.17.4 and later only)`, `11.4` | | SUSE Enterprise Linux Server | `x86_64`, `aarch64` (15.x only), `s390x` | `12`, `15` | | Ubuntu (LTS releases) | `x86_64`,`aarch64` | `16.04`, `18.04`, `20.04` | | Microsoft Windows | `x86`, `x64` | `8.1`, `2012`, `2012 R2`, `2016`, `10 (all channels except "insider" builds)`, `2019 (Long-term servicing channel (LTSC), both Desktop Experience and Server Core)``11`, `2022` | #### Community Support The following platforms are supported only via the community: | Platform | Architecture | Version | | --- | --- | --- | | AlmaLinux | `x86_64`, `aarch64` | `8.x` | | Alibaba Cloud Linux | `x86_64` | 2.x | | Arch Linux | `x86_64` | current version | | Arista EOS | `x86_64` | current non-EOL releases | | CentOS Stream | `x86_64`, `aarch64` | current non-EOL releases | | Clear Linux | `x86_64` | current non-EOL releases | | Cumulus Linux | `x86_64` | current non-EOL releases | | Fedora | `x86_64`, `aarch64` | current non-EOL releases | | Kali Linux | `x86_64` | current non-EOL releases | | Linux Mint | `x86_64` | current non-EOL releases | | OpenIndiana Hipster | `x86_64` | current non-EOL releases | | openSUSE | `x86_64`, `aarch64` | `15.x` | | Pop!_OS | `x86_64` | current non-EOL releases | | Raspberry Pi OS | `aarch64` | current non-EOL releases | | Rocky Linux | `x86_64`, `aarch64` | 8.x | | SmartOS | `x86_64` | current non-EOL releases | | SUSE Linux Enterprise Desktop | `x86_64`, `aarch64` (15.x only) | `12.x`, `15.x` | | Ubuntu | `x86_64`, `aarch64` | Current non-LTS releases | Virtuozzo | `x86_64` | Current non-LTS releases || Windows | `x64` | `Windows Server, Semi-annual channel (SAC) (Server Core only)` | | XCP-ng | `x86_64` | 8.x | ### Chef Workstation #### Commercial Support The following table lists the commercially-supported platforms and versions for the Chef Workstation: | Platform | Architecture | Version | | --- | --- | --- | | Amazon Linux | `x86_64` | `2.x` | | macOS | `x86_64` | `10.15`, `11.x`, `12.x` | | Debian | `x86_64` | `9`, `10`, `11` | | Red Hat Enterprise Linux | `x86_64` | `7.x`, `8.x` | | Ubuntu | `x86_64` | `16.04`, `18.04`, `20.04` | | Microsoft Windows | `x64` | `8.1`, `2012`, `2012 R2`, `2016`, `10 (all channels except "insider" builds)`, `2019 (Long-term servicing channel (LTSC), Desktop Experience only)`, `11`, `2022` | ### Chef InSpec #### Commercial Support The following table lists the commercially-supported platforms and versions for Chef InSpec: | Platform | Architecture | Version | | --- | --- | --- | | Amazon Linux | `x86_64`, `aarch64` | `2.x` | | Debian | `x86_64``aarch64` (10.x only) | `9`, `10`, `11` | | macOS | `x86_64`, `aarch64` (M1 processors) | `10.15`, `11.x`, `12.x` | | Oracle Enterprise Linux | `x86_64``aarch64` (7.x / 8.x only) | `6.x`, `7.x`, `8.x` | | Red Hat Enterprise Linux | `x86_64`, `aarch64` (7.x and 8.x only) | `6.x`, `7.x`, `8.x` | | SUSE Enterprise Linux Server | `x86_64`, `aarch64` (15.x only) | `12.x`, `15.x` | | Ubuntu | `x86_64` | `16.04`, `18.04`, `20.04` | | Microsoft Windows | `x86_64` | `8.1`, `2012`, `2012 R2`, `2016`, `10 (all channels except "insider" builds)`, `2019`, `11`, `2022` | Chef InSpec Target Mode (`inspec --target`) may be functional on additional platforms, versions, and architectures but are not validated by Chef Software, Inc. ### Chef Infra Server #### Commercial Support The following table lists the commercially-supported platforms and versions for the Chef Infra Server: | Platform | Architecture | Version | | --- | --- | --- | | Amazon Linux 2 | `x86_64` | `2.x` | | CentOS | `x86_64` | `7.x`, `8.x` | | Oracle Enterprise Linux | `x86_64` | `7.x`, `8.x` | | Red Hat Enterprise Linux | `x86_64` | `7.x`, `8.x` | | SUSE Enterprise Linux Server | `x86_64` | `12.x`, `15.x` | | Ubuntu | `x86_64` | `16.04`, `18.04`, `20.04` | ### Chef Automate Server #### Commercial Support Commercial support for the [Chef Automate 2 Server](../automate/system_requirements/index) is available for platforms that use: * a Linux kernel version of 3.2 or greater * `systemd` as the init system * `useradd` * `curl` or `wget` ### Chef Backend #### Commercial Support The following table lists the commercially-supported platforms for Chef Backend, which is the high-availability solution for Chef Infra Server: | Platform | Architecture | Version | | --- | --- | --- | | CentOS | `x86_64` | `6.x`, `7.x`, `8.x` | | Oracle Enterprise Linux | `x86_64` | `6.x`, `7.x`, `8.x` | | Red Hat Enterprise Linux | `x86_64` | `6.x`, `7.x`, `8.x` | | SUSE Linux Enterprise Server | `x86_64` | `12.x` | | Ubuntu (LTS releases) | `x86_64` | `16.04`, `18.04` | ### Chef Manage #### Commercial Support The following table lists the commercially-supported platforms for Chef Manage: | Platform | Architecture | Version | | --- | --- | --- | | CentOS | `x86_64` | `7.x`, `8.x` | | Oracle Enterprise Linux | `x86_64` | `7.x`, `8.x` | | Red Hat Enterprise Linux | `x86_64` | `7.x`, `8.x` | | Ubuntu (LTS releases) | `x86_64` | `16.04`, `18.04`, `20.04` | Platform End-of-Life Policy --------------------------- Chef’s products on particular platforms and versions generally reach end-of-life on the same date as the vendor EOL milestone for that operating systems. Because different vendors use different terminology, the following table clarifies when Chef products are end-of-life according to those vendors' terms: | Platform | Vendor End-of-Life | | --- | --- | | Amazon Linux | End of Life | | Apple macOS | Apple generally supports the last three macOS releases, for example: 10.15, 11.x, and 12.x. Apple does not officially publish EOL dates. | | Debian | End of maintenance updates | | Enterprise Linux (covers Red Hat Enterprise Linux, CentOS) | End of Production 3 | | FreeBSD | End of Life | | IBM AIX | IBM End of Support Date | | Microsoft Windows | End of Extended Support | | Oracle Enterprise Linux | Premier Support Ends | | Oracle Solaris | Premier Support Ends | | SUSE Linux Enterprise Server | General Support Ends | | Ubuntu Linux | End of maintenance updates | At Chef’s option, additional support may be provided to customers beyond the vendor end-of-life in the above table. As such, the following table indicates upcoming product end-of-life dates for particular platforms. On the Chef end-of-life date, Chef discontinues building software for that platform and version. | Platform and Version | Vendor End-of-Life Date | Chef End-of-Life Date | | --- | --- | --- | | Amazon Linux 201X | Dec 31st, 2020 | Dec 31st, 2020 | | Apple macOS 10.13 | Nov 13th, 2020 | Nov 13th, 2020 | | Apple macOS 10.14 | Nov 12th, 2021 | Nov 12th, 2021 | | Debian 7 (Wheezy) | May 31st, 2018 | May 31st, 2018 | | Debian 8 (Jessie) | June 6th, 2020 | June 6th, 2020 | | Debian 9 (Stretch) | June 30th, 2022 | June 30th, 2022 | | Enterprise Linux 5 (covers Red Hat Enterprise Linux, CentOS) | April 30, 2017 | December 31, 2017 | | Enterprise Linux 6 (covers Red Hat Enterprise Linux, CentOS) | November 30, 2020 | No current planned EOL date | | Enterprise Linux 7 (covers Red Hat Enterprise Linux, CentOS) | June 30, 2024 | June 30, 2024 | | FreeBSD 10-STABLE | October 31, 2018 | October 31, 2018 | | FreeBSD 11-STABLE | September 30, 2021 | September 30, 2021 | | IBM AIX 6.1 | April 30, 2017 | December 31, 2017 | | Microsoft Windows Server 2008 (SP2)/R2 (SP1) | January 13, 2015 | January 14, 2020 | | Microsoft Windows Server 2012/2012 R2 | October 10, 2023 | October 10, 2023 | | Microsoft Windows Server 2016 | November 11, 2027 | November 11, 2027 | | Microsoft Windows Server 2019 | October 10, 2028 | October 10, 2028 | | Oracle Enterprise Linux 5 | June 30, 2017 | December 31, 2017 | | Oracle Enterprise Linux 6 | March 31, 2021 | March 31, 2021 | | Oracle Solaris 10 | January 30, 2018 | January 30, 2018 | | Oracle Solaris 11.3 | January 30, 2021 | No current planned EOL date | | SUSE Linux Enterprise Server 11 | March 31, 2019 | March 31, 2019 | | SUSE Linux Enterprise Server 12 | October 31, 2024 | October 31, 2024 | | Ubuntu Linux 12.04 LTS | April 30, 2017 | April 30, 2017 | | Ubuntu Linux 14.04 LTS | April 30, 2019 | April 30, 2019 | | Ubuntu Linux 16.04 LTS | April 30, 2021 | April 30, 2021 | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/platforms/Docs Style ========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/style_index.md) The Chef Documentation is online at [docs.chef.io](../index). Our documentation is open source and we follow a [docs as code](https://www.docslikecode.com/) methodology. Our workflow is based in GitHub, we write in Markdown, and we use Hugo as our static site generator. Any community member can make or suggest a documentation change through pull request (PR) or issue in a documentation repository. Documentation Repositories -------------------------- Our main repository (repo, for short) for [docs.chef.io](../index) is called [chef-web-docs](https://github.com/chef/chef-web-docs). This repo contains the files for Chef Infra Client and the Hugo files for our front-end theme, templates, and shortcodes. The Chef documentation is located in: `https://github.com/chef/chef-web-docs` * The `chef-web-docs` repo contains a `content` directory which holds most the Markdown files in the doc set. * The `static/images` directory stores the image files used in the docs. * The `config.toml` tells Hugo how to build the navigation menus and contains other Hugo settings. Don’t modify this file. ### Repository Locations We try to keep our documentation source as close to the code as possible, which means that our documentation files are distributed across several product repositories. | Product | GitHub Docs Directory | | --- | --- | | Chef Automate | <https://github.com/chef/automate/tree/main/components/docs-chef-io> | | Chef Habitat | <https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io> | | Chef Infra Client | <https://github.com/chef/chef-web-docs> | | Chef Infra Server | <https://github.com/chef/chef-server/tree/main/docs-chef-io> | | Chef Inspec | <https://github.com/inspec/inspec/tree/main/docs-chef-io> | How to Make a Change -------------------- ### Finding the Right Repository The easiest way to find the location of the source file is to select the `Edit on GitHub` link at the top of every documentation file in your browser. Selecting `Edit on GitHub` ![Edit On GitHub] Opens the related documentation file in the correct repository. ### Suggest a Change You can open a change PR directly in the browser by selecting the pen icon in the documentation file–but you will need to add your DCO directly in the commit message. which is circled in red in this image. ![File in Repository] ### DCO Sign-off Chef Software requires all contributors to include a [Developer Certificate of Origin](https://developercertificate.org/) (DCO) sign-off with their pull request as long as the pull request does not fall under the [Obvious Fix](#obvious-fix) rule. This attests that you have the right to submit the work that you are contributing in your pull request. See this [blog post](https://blog.chef.io/2016/09/19/introducing-developer-certificate-of-origin/) to understand why Chef started using the DCO signoff. For more information, review our [full DCO signoff policy](https://github.com/chef/chef/blob/main/CONTRIBUTING.md#developer-certification-of-origin-dco). A proper DCO sign-off looks like: `Signed-off-by: <NAME> <<EMAIL>>` Your commit message should look something like: ![Add DCO] Select `propose changes` and finish opening your PR. You can add a DCO signoff to your pull request by adding it to the text of your commit message, or by using the `-s` or `--signoff` option when you make a commit. #### Add a DCO to a PR If you forget to add a DCO sign-off before submitting a pull request, you can amend your commit from the command line with the Git CLI by entering `git commit --amend --signoff`. After that you’ll need to force push your commit to GitHub using the command `git push -f`. ### Obvious Fix–No DCO Required Small contributions, such as fixing spelling errors, where the content is small enough to not be considered intellectual property, can be submitted without signing the contribution for the DCO. Changes that fall under our Obvious Fix policy include: * Spelling / grammar fixes * Typo correction, white space and formatting changes * Comment clean up * Bug fixes that change default return values or error codes stored in constants * Adding logging messages or debugging output * Changes to ‘metadata’ files like Gemfile, .gitignore, build scripts, etc. To invoke the Obvious Fix rule, simply add `Obvious Fix.` to your commit message. For more information, see our [Obvious Fix policy](https://github.com/chef/chef/blob/main/CONTRIBUTING.md#chef-obvious-fix-policy). Preview the Build ----------------- Deleting Pages or Making New Pages ---------------------------------- Contact the documentation team if you would like to suggest adding or removing pages. Contact ------- See our [feedback](https://docs.chef.io/feedback/) page if you have any questions or comments for the documentation team. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/style_index/Quick Start Demo ================ [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/_index.md) Hello and welcome to Chef Automate! This Quickstart guides you through the initial installation and trial activation. The easiest way to start exploring Chef Automate is to install it on a local virtual machine (VM). This [Vagrant](https://www.vagrantup.com/) file will help you create your own test environment. Prerequisites ------------- For this demonstration, you need: * Administrator (root) access to your system * A virtualization product such as [VirtualBox](https://www.virtualbox.org/) installed on your system * [Vagrant](https://www.vagrantup.com/intro/getting-started/) installed on your system * 8GB RAM, or more, available for the VM Quickstart Overview ------------------- Use the command line script below to create a demonstration instance of Chef Automate. The script is mostly automated, but it does require a few manual steps. By installing Chef Automate with the Vagrantfile provided below you’re automatically consenting to Chef Software, Inc.’s [Terms of Service](https://www.chef.io/terms-of-service) and [Master License and Services Agreement](https://www.chef.io/online-master-agreement) Create a Vagrantfile -------------------- Copy and paste this script into your command line to create the Chef Automate `Vagrantfile`: ``` cat > Vagrantfile <<'EOH' CFG_BOX = 'bento/ubuntu-18.04' CFG_IP = '192.168.33.199' CFG_HOSTNAME = 'chef-automate.test' $deployscript = <<-SCRIPT export DEBIAN_FRONTEND='noninteractive' apt-get -qq update apt-get install -y --no-install-recommends curl unzip apt-get clean sysctl -w vm.max_map_count=262144 sysctl -w vm.dirty_expire_centisecs=20000 echo "${CFG_IP} ${CFG_HOSTNAME}" | tee -a /etc/hosts curl -fsSL https://packages.chef.io/files/current/automate/latest/chef-automate_linux_amd64.zip -o /tmp/chef-automate_linux_amd64.zip unzip -qod /usr/local/bin /tmp/chef-automate_linux_amd64.zip chmod +x /usr/local/bin/chef-automate chef-automate deploy --accept-terms-and-mlsa echo "Server is up and running. Please log in at https://${CFG_HOSTNAME}/" echo 'You may log in using credentials provided below:' cat /home/vagrant/automate-credentials.toml SCRIPT Vagrant.configure(2) do |config| class AcceptLicense def to_s return 'true' if ENV['ACCEPT_CHEF_TERMS_AND_MLSA'] == 'true' puts <<TERMS To continue, you'll need to accept our terms of service: Terms of Service https://www.chef.io/terms-of-service Master License and Services Agreement https://www.chef.io/online-master-agreement I agree to the Terms of Service and the Master License and Services Agreement (y/n) TERMS if STDIN.gets.chomp == 'y' 'true' else puts 'Chef Software Terms of Service and Master License and Services Agreement were not accepted' exit 1 end end end config.vm.box = CFG_BOX config.vm.hostname = CFG_HOSTNAME config.vm.provider "virtualbox" do |v| v.name = 'chef-automate' v.memory = 8192 v.cpus = 4 v.customize ['modifyvm', :id, '--audio', 'none'] end config.vm.synced_folder '.', '/opt/a2-testing', create: true config.vm.network 'private_network', ip: CFG_IP config.vm.provision 'shell', env: {'CFG_IP' => CFG_IP, 'CFG_HOSTNAME' => CFG_HOSTNAME, 'ACCEPT_CHEF_TERMS_AND_MLSA' => AcceptLicense.new}, inline: $deployscript end EOH ``` Add an entry to /etc/hosts -------------------------- The example Vagrantfile sets the VM hostname to `chef-automate.test`. The installer uses this hostname as the FQDN that Chef Automate listens on. For security reasons, you must access Chef Automate with the configured FQDN. To avoid configuring DNS for your test instance, add an entry to your workstation’s `/etc/hosts` file. Use the following command to append the required entry: ``` echo 192.168.33.199 chef-automate.test | sudo tee -a /etc/hosts ``` Start the Virtual Machine ------------------------- Now that you have the `Vagrantfile` in your current directory, provision a new VM by running: ``` vagrant up ``` Downloading the base OS image for the VM takes 1 to 3 minutes the first time you set up Chef Automate. When the command completes, you can access the Chef Automate by browsing to `https://chef-automate.test/`. You can find login credentials by opening the `automate-credentials.toml`, which the installer has written in your current working directory, or in the output log. Start a free 60-day Trial ------------------------- Retrieving a trial license through Chef Automate requires the Vagrant instance to have internet connectivity (at the time of trial license creation only). 1. Sign into Chef Automate at `https://chef-automate.test/` with the credentials in the `automate-credentials.toml` file. 2. Follow the instructions in the welcome screen to get a 60-day trial license by entering your name and email address. Installing without Vagrant -------------------------- You can install Chef Automate on any x86_64 Linux instance running CentOS 7.5, RHEL 7.5, or Ubuntu 16.04 with the following minimum system resources: * 4 CPU * 16 GB RAM * 5 GB free disk space Follow the [Installation Guide](install/index) to install Chef Automate on your own resources. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/Omnitruck API ============= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/api_omnitruck.md) Chef’s Omnitruck API powers the Chef Software install script as well as [Chef’s download](https://www.chef.io/downloads) site. It can be used to query available versions of Chef Software products and to provide direct download URLs. Syntax ------ The URL from which these downloads can be obtained has the following syntax: ``` https://omnitruck.chef.io/<CHANNEL>/<PRODUCT>/download?p=$PLATFORM&pv=$PLATFORM_VERSION&m=$MACHINE_ARCH&v=latest&prerelease=false&nightlies=false ``` or: ``` https://omnitruck.chef.io/<CHANNEL>/<PRODUCT>/metadata?p=$PLATFORM&pv=$PLATFORM_VERSION&m=$MACHINE_ARCH&v=latest&prerelease=false&nightlies=false ``` where the difference between these URLs is the `metadata` and `download` options. Use the `metadata` option to verify the build before downloading it. Use the `download` option to download the package in a single step. Downloads --------- The `/metadata` and/or `/download` endpoints can be used to download packages for all products: ``` https://omnitruck.chef.io/<CHANNEL>/<PRODUCT>/download?p=$PLATFORM&pv=$PLATFORM_VERSION&m=$MACHINE_ARCH&v=latest ``` or: ``` https://omnitruck.chef.io/<CHANNEL>/<PRODUCT>/metadata?p=$PLATFORM&pv=$PLATFORM_VERSION&m=$MACHINE_ARCH&v=latest ``` where: * `<CHANNEL>` is the release channel to install from. See [Chef Software Packages](../packages/index) for full details on the available channels. * `<PRODUCT>` is the Chef Software product to install. A list of valid product keys can be found at <https://github.com/chef/mixlib-install/blob/main/PRODUCT_MATRIX.md> * `p` is the platform. Possible values: `debian`, `el` (for RHEL derivatives), `freebsd`, `mac_os_x`, `solaris2`, `sles`, `suse`, `ubuntu` or `windows`. * `pv` is the platform version. Possible values depend on the platform. For example, Ubuntu: `18.04`, or `20.04` or for macOS: `10.15` or `11`. * `m` is the machine architecture for the machine on which the product will be installed. Possible values depend on the platform. For example, for Ubuntu or Debian: `i386` or `x86_64` or for macOS: `x86_64`. * `v` is the version of the product to be installed. A version always takes the form x.y.z, where x, y, and z are decimal numbers that are used to represent major (x), minor (y), and patch (z) versions. One-part (x) and two-part (x.y) versions are allowed. For more information about application versioning, see <https://semver.org/>. Default value: `latest`. ### Platforms Omnitruck accepts the following platforms: | Platform | p | m | pv | | --- | --- | --- | --- | | AIX | `aix` | `powerpc` | `6.1`, `7.1`, `7.2` | | Amazon Linux | `amazon` | `x86_64`,`aarch64` | `201X, 2` | | Debian | `debian` | `i386`, `x86_64`, `aarch64` | `6`, `7`, `8`, `9`, `10`, `11` | | FreeBSD | `freebsd` | `x86_64` | `9`, `10`, `11`, `12` | | macOS | `mac_os_x` | `x86_64`, `aarch64` | `10.6`, `10.7`, `10.8`, `10.9`, `10.10`, `10.11`, `10.12`, `10.13`, `10.14`, `10.15`, `11`, `12` | | Solaris | `solaris2` | `i386`, `sparc` | `5.10`, `5.11` | | SUSE Linux Enterprise Server | `sles` | `x86_64`, `s390x`, `aarch64` | `11`, `12`, `15` | | Red Hat Enterprise Linux / CentOS / Oracle Linux | `el` | `i386`, `x86_64`, `ppc64`, `ppc64le`, `aarch64`, `s390x`, | `5`, `6`, `7`, `8` | | Ubuntu | `ubuntu` | `i386`, `x86_64`, `aarch64`, `ppc64le` | `10.04`, `10.10`, `11.04`, `11.10`, `12.04`, `12.10`, `13.04`, `13.10`, `14.04`, `14.10`, `16.04`, `16.10`, `17.04`, `17.10`, `18.04`, `18.10`, `19.04`, `20.04`, `20.10`, `21.04`, `21.10` | | Microsoft Windows | `windows` | `x86_64`, `i386` | `7`, `8`, `10`, 2008r2, `2012`, `2012r2`, `2016`, `2019`, `11`, `2022` | ### Examples #### Get the Latest Build To get the latest supported build for Ubuntu 20.04, enter the following: ``` https://omnitruck.chef.io/stable/chef/metadata?p=ubuntu&pv=20.04&m=x86_64 ``` to return something like: ``` sha1 3fe8e8a2f443675f9b82e876cdac8200104451f2 sha256 9f1c1a2c0b1f4e8494664386437bf32f0cb5cbfbd4cb9d23e327767fc65581dc url https://packages.chef.io/files/stable/chef/17.7.29/ubuntu/20.04/chef_17.7.29-1_amd64.deb version 17.7.29 ``` #### Download Directly To use cURL to download a package directly, enter the following: ``` curl -LOJ 'https://omnitruck.chef.io/<CHANNEL>/<PRODUCT>/download?p=debian&pv=10&m=x86_64' ``` To use GNU Wget to download a package directly, enter the following: ``` wget --content-disposition https://omnitruck.chef.io/<CHANNEL>/<PRODUCT>/download?p=debian&pv=10&m=x86_64 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/api_omnitruck/Accepting the Chef License ========================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_license_accept.md) This page aims to document how to accept the Chef license for all Chef Software products. For an overview of the license, see the [Chef license](../chef_license/index) documentation. There are two types of license: MLSA and EULA. The MLSA applies to customers with a commercial contract with Chef Software, and the EULA covers all other cases. Accept the Chef MLSA -------------------- There are three ways to accept the Chef MLSA: 1. When running `chef-<PRODUCT-NAME>-ctl reconfigure` the Chef MLSA is printed. Type `yes` to accept it. Anything other than typing `yes` rejects the Chef MLSA, and the upgrade process will exit. Typing `yes` adds a `.license.accepted` file to the `/etc/chef/accepted_licenses/<PRODUCT-NAME>` file. As long as this file exists in this directory, the Chef MLSA is accepted and the reconfigure process will not prompt for `yes`. 2. Run the `chef-<PRODUCT-NAME>-ctl reconfigure` command using the `--chef-license=accept` option. This automatically types `yes` and skips printing the Chef MLSA. 3. Add a `.license.accepted` file to the `/var/opt/<PRODUCT-NAME>/` directory. The contents of this file do not matter. As long as this file exists in this directory, the Chef MLSA is accepted and the reconfigure process will not prompt for `yes`. Accept the Chef EULA -------------------- Products below are split below into two categories: workstation and server. Affected product versions which require accepting the EULA to use are shown. Versions before this do not require accepting the EULA. More information on supported versions can be seen at the [Supported Versions](../versions/index) documentation. ### Workstation Products * Chef Workstation >= 0.4, which also contains: + Chef Infra Client + Chef InSpec * Chef Infra Client >= 15.0 * Chef InSpec >= 4.0 * Chef Habitat >= 0.80 These products are typically installed on a user’s workstation. Two methods are generally used to accept the license for these products: 1. `--chef-license <value>` argument passed to the command line invocation. 2. `CHEF_LICENSE="<value>"` as an environment variable. `<value>` can be specified as one of the following: 1. `accept` - Accepts the license and attempts to persist a marker file locally. Persisting these marker files means future invocations do not require accepting the license again. 2. `accept-silent` - Similar to `accept` except no messaging is sent to STDOUT 3. `accept-no-persist` - Similar to `accept-silent` except no marker file is persisted. Future invocation will require accepting the license again. If no command line argument or environment variable is set, these products will attempt to request acceptance through an interactive prompt. If the prompt cannot be displayed, then the product will fail with an exit code 172. If the product attempts to persist the accepted license and fails, a message will be sent to STDOUT, but product invocation will continue successfully. In a future invocation, however, the license would need to be accepted again. Please see [License File Persistence](https://github.com/chef/license-acceptance#license-file-persistence) for details about persisted marker files. The `--chef-license` command line argument is not backwards compatible to older non-EULA versions. If you are managing a multi-version environment, we recommend using the environment variable as that is ignored by older versions. Products with specific features or differences from this general behavior are documented below. #### Chef Workstation Chef Workstation contains multiple Chef Software products. When invoking the `chef` command line tool and accepting the license, users are required to accept the license for all the embedded products as well. The same license applies to all products, but each product must have its own license acceptance. `chef <command> --chef-license accept` will accept the license for Chef Workstation, Chef Infra Client, and Chef InSpec. For example, `chef env --chef-license accept`. #### Chef Infra Client In addition to the above methods, users can specify `chef_license 'accept'` in their Chef Infra Client and Chef Infra Server config. On a workstation, this can be specified in `~/.chef/config.rb` or `~/.chef/knife.rb`, and on a node, it can be specified in `/etc/chef/client.rb`. This method of license acceptance is backwards-compatible to non-EULA versions of Chef Infra Client. #### Habitat Two methods are generally used to accept the Chef Habitat license: 1. Users can execute `hab license accept` on the command line. 2. Alternatively, users can set `HAB_LICENSE="<value>"` as an environment variable. `<value>` can be specified as one of the following: 1. `accept` - Accepts the license and persists a marker file locally. Future invocations do not require accepting the license again. 2. `accept-no-persist` - accepts the license without persisting an marker file. Future invocation will require accepting the license again. If the license isn’t accepted through either of these methods, Habitat will request acceptance through an interactive prompt. Additionally, to accepting the license in CI or other automation, user may choose to create an empty file on the filesystem at `/hab/accepted-licenses/habitat` (if your hab commands run as root) or at `$HOME/.hab/accepted-licenses/habitat` (if your hab commands run as a user other than root). For situations where hab commands run as multiple users, it is advisable to create both files. #### Errors If the Chef Habitat License prompt cannot be displayed, then the product fails with an exit code 172. If Chef Habitat cannot persist the accepted license, it sends a message STDOUT, but the product invocation will continue successfully. In a future invocation, however, the user will need to accept the license again. #### Chef as Habitat packages Chef Software products are also distributed as Habitat packages, such as Chef Infra Client, Chef InSpec, etc. When Chef products are installed as Habitat, the products request license acceptance at product usage time. Whether installed as system packages or as Habitat packages, users accept the licenses in the same way detailed above. ### Server Products Some Chef products distributed as Habitat packages contain servers. In these cases, Habitat runs the server products as a supervisor. See the below sections for information on how to accept the license for these products when they are distributed as Habitat packages. | Product | Version | | --- | --- | | Chef Infra Server | >= 13.0 | | Chef Automate | >= 2.0 | | Supermarket | >= 4.0 | Server products are typically installed and managed by some kind of process supervisor. Chef Software server products do not allow interactive license acceptance because process supervisors do not easily allow interactivity. Instead, the license is accepted during the `reconfigure` command or `upgrade` command for the Omnibus ctl command. For example: * `chef-server-ctl reconfigure --chef-license=accept` * `CHEF_LICENSE="accept-no-persist" supermarket-ctl reconfigure` In addition, the Chef license can be accepted via the omnibus configuration file. Specify `chef_license 'accept'` in the `chef-server.rb` or `supermarket.rb` configuration. #### Chef Automate Automate has its own reconfigure tool, `automate-ctl`. This tool walks users through the install and setup of Automate. The Chef license is accepted after that in the browser. Please follow the in-product prompts. #### Chef Infra Server When installed as a system package, users accept the license with the ctl command. For example, `chef-server-ctl reconfigure --chef-license=accept`. Acceptance can also be set in the configuration file `chef-server.rb` as `chef_license "accept"`. Chef Infra Server is also distributed as a Habitat package and ran using the Habitat supervisor. In this mode, users accept the license by setting the correct Habitat configuration values. The key is `chef_license.acceptance`. For example: Against a supervisor running Chef Infra Server, run `echo "chef_license.acceptance = accept" | hab config apply server.default 100`. See the [Habitat config updates documentation](https://www.habitat.sh/docs/using-habitat/#config-updates) for more information about how to apply this configuration to a service group. ### Remote Management Products * Test Kitchen * `knife bootstrap` in Chef Infra Client * `chef-run` in Chef Workstation * Packer * Terraform Chef Provider (Deprecated) * Vagrant These products install or manage Chef on a remote instance. If a user has accepted the appropriate product license locally, it will be automatically transferred to the remote instance. For example, if a user has accepted the Chef Infra Client license locally and converges a Test Kitchen instance with the Chef provisioner, it will succeed by copying the acceptance to the remote instance. We aim to support this behavior, so Workstation users do not have their workflow affected, but any differences from that behavior are documented below. #### Test Kitchen Test Kitchen is not owned by or covered by the Chef license, but installing Chef Infra Client on a test instance is covered by the EULA. Without accepting the license, the converge will fail on the test instance. The Chef provisioner in Test Kitchen >= 2.3 has been updated to simplify accepting this license on behalf of the test instance. Users can set the `CHEF_LICENSE` environment variable or add `chef_license: accept` to their provisioner config in their **kitchen.yml**. Specifying **accept** will attempt to persist the license acceptance locally. If a local license marker file is detected, no configuration is required; acceptance is automatically transferred to the test instance. To disable this persistence, specify `accept-no-persist` on every test instance converge. `kitchen-inspec` uses Chef InSpec as a library, and is not covered by the EULA when installed as a gem, but is covered by the EULA when packaged as part of the Chef Workstation installation. Accept the license in a similar way to the Chef Infra Client license - specify the `CHEF_LICENSE` environment variable, specify the `chef_license` config under the verifier section in `kitchen.yml` or persist the acceptance locally. ##### Test Kitchen: Pin to Chef 14 You can pin to a specific version of chef in your kitchen.yml: ``` provisioner: name: chef_zero product_name: chef product_version: 14.12.3 ``` #### `knife bootstrap` `knife` usage does not require accepting the EULA. A Chef Infra Client instance does require EULA acceptance. Using `knife bootstrap` to manage a Chef Infra Client instance will prompt a user to accept the license locally before allowing for bootstrapping the remote instance. Without this, `knife bootstrap` would fail. In most usage cases via Chef Workstation, this license will already have been accepted and will transfer across transparently. But if a user installs Chef Workstation and the first command they ever run is `knife bootstrap`, it will perform the same license acceptance flow as the Chef Infra Client product. ##### `knife bootstrap` in Chef Client 14 The `knife bootstrap` command in Chef Client 14 cannot accept the Chef Infra Client 15 EULA on remote nodes unless you use a [custom template](../workstation/knife_bootstrap/index#custom-templates) and add chef_license “accept” to the client.rb. This applies to workstations who have Chef Infra Client <= 14.x, ChefDK <= 3.x or Chef Workstation <= 0.3 installed. ##### `knife bootstrap`: Pin to Chef 14 Specify the following argument: ``` knife bootstrap --bootstrap-version 14.12.3 ``` #### `chef-run` `chef-run` in Chef Workstation >= 0.3 has been updated to add support for accepting the license locally when remotely running Chef Infra Client 15. As of Chef Workstation <= 0.4 there is no way to manage the version of Chef Infra Client installed on the remote node. It defaults to the latest stable version available. To accept the license, complete one of the following three tasks. Either pass the `--chef-license` command line flag, set the `CHEF_LICENSE` environment variable, or add the following to your `~/.chef-workstation/config.toml` file: ``` [chef] chef_license = "accept" ``` #### Packer Use a custom [Chef configuration template](https://www.packer.io/docs/provisioners/chef/chef-client#chef-configuration). In your provisioners config, include: ``` { "type": "chef-client", "config_template": "path/to/client.rb" } ``` In `path/to/client.rb`, include: ``` chef_license 'accept' ``` You may also add it to the [execute_command](https://www.packer.io/docs/provisioners/chef-client.html#execute_command), but this is not backwards-compatible, so it is not suggested. ##### Packer: Pin to Chef 14 In your [Packer provisioners config](https://www.packer.io/docs/provisioners/chef-client.html#install_command), include: ``` { "type": "chef-client", "install_command": "curl -L https://omnitruck.chef.io/install.sh | sudo bash -s -- -v 14.12.9" } ``` #### Terraform Chef Provisioner Warning Terraform deprecated the Chef Provisioner in the [0.13.4](https://www.terraform.io/docs/language/resources/provisioners/chef.html) release and they will remove it in a future version. Terraform continues to support the Chef Provider. The license can be accepted via the Chef Infra Client config file, which is specified by the `client_options` [Terraform provisioner config](https://www.terraform.io/docs/provisioners/chef.html#client_options-array-): ``` provisioner "chef" { client_options = ["chef_license 'accept'"] } ``` ##### Terraform: Pin to Chef 14 In your [Terraform provisioner config](https://www.terraform.io/docs/provisioners/chef.html#version-string-), include: ``` provisioner "chef" { version = "14.12.3" } ``` #### Terraform Habitat Provisioner Default behavior of this provisioner is to install the latest version of Habitat. [Documentation for this provisioner](https://www.terraform.io/docs/provisioners/habitat.html) will be updated in the near future once the provisioner is updated with options to accept license. For the time being, the provisioner can be pinned to a prior Habitat version as below. ##### Terraform: Pin to Chef Habitat 0.79 In your [Terraform provisioner config](https://www.terraform.io/docs/provisioners/habitat.html#version-string-), include: ``` provisioner "habitat" { version = "0.79.1" } ``` #### Vagrant This license acceptance can be done via the arguments API: ``` config.vm.provision 'chef_zero' do |chef| chef.arguments = '--chef-license accept' end ``` See the [Vagrant documentation](https://www.vagrantup.com/docs/provisioning/chef_common.html#arguments) for details. The `--chef-license` argument is not backwards-compatible to non-EULA Chef Infra Client versions. So instead, users can use the [custom config path](https://www.vagrantup.com/docs/provisioning/chef_common.html#custom_config_path) and point at a local file, which specifies the `chef_license` config. The environment variable is not currently supported. ##### Vagrant: Pin to Chef 14 This version pinning can be done via the [version API](https://www.vagrantup.com/docs/provisioning/chef_common.html#version). In your Chef provisioner config: ``` config.vm.provision 'chef_zero' do |chef| chef.version = '14.12.3' end ``` ### Pre-upgrade support Chef Software aims to make upgrading from a non-EULA version to a EULA version as simple as possible. For some products (Chef Client 14.12.9, Chef InSpec 3.9.3), we added backwards-compatible support for the `--chef-license` command that performs a no-op. This allows customers to start specifying that argument in whatever way they manage those products before upgrading. Alternatively, users can specify the `CHEF_LICENSE` environment variable when invoking any of the EULA products to accept the license. This environment variable is ignored by non-EULA products, and so is backwards-compatible to older versions. #### `chef-client` cookbook For users that manage their Chef Infra Client installation using the `chef-client` cookbook, we added a new attribute that can be specified. Specify the node attribute `node['chef_client']['chef_license'] = 'accept'` when running the cookbook to apply the license acceptance in a backwards-compatible way. This functionality allows users to set that attribute for a Chef Client 14 install, upgrade to Chef Infra Client 15, and have the product continue to work correctly. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_license_accept/Disclosure Panel and Banner =========================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/disclosure_panel_and_banner.md) Customize your Chef Automate installation with a **Disclosure Panel** to add critical information about your unique environment on the sign-in page and a **Banner** at the top of every page to highlight important information. Disclosure Panel ---------------- The **Disclosure Panel** is a space where you can add custom content to the Chef Automate sign-in page. Use this panel to display information, such as a message, warning, or instructions, that appears during the sign-in process. An example disclosure panel: ![An example Disclosure Panel in Chef Automate with Lorem Ipsum text] To add a disclosure panel to the sign-in page: 1. Create a file with the message in `.html` or `.txt` format and save to a location that is available to Chef Automate. 2. Create a `patch.toml` if one does not already exist for your Chef Automate installation. 3. Add the disclosure panel configuration to the `patch.toml` file. Your configuration should look like: ``` [global.v1] [global.v1.disclosure] show = true # Set 'show' to 'true' to enable the disclosure panel on the sign-in page. Set to 'false' to disable the disclosure panel. Default: false. message_file_path = "/src/dev/disclosure-panel-message.txt" # The location of the file containing the disclosure panel message. # Validate your HTML at https://validator.w3.org/ ``` Banner ------ The **Banner** displays custom content at the top of every page in Chef Automate, including the sign-in page. Use it to add a message, warning, or instructions to Chef Automate users. The banner can display only one message, warning or instruction throughout the interface. An example banner: ![Banner in Chef Automate Interface] To add a banner to Chef Automate: 1. Create a `patch.toml` if one does not already exist for your Chef Automate installation. 2. Add the banner configuration to the `patch.toml` file. Your configuration should look like: ``` [global.v1] [global.v1.banner] show = true # Set 'show' to 'true' to enable the banner. Set to 'false' to disable the banner. Default: false. message = "Lorem ipsum dolor sit amet" # Add the Message for the banner background_color = "3864f2" # Set the background color using the Hex Color Code (Do not add # to the code) text_color = "FFF" # Set the color of the text using the Hex Color Code (Do not add # to the code) # Find valid HEX codes at https://htmlcolorcodes.com/ ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/disclosure_panel_and_banner/Telemetry ========= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/telemetry.md) ### About Telemetry Users of this Chef Automate server may elect to share user-anonymized usage data with Chef Software, Inc. Chef uses this shared data to improve Chef Automate. Please see the [Chef Privacy Policy](https://chef.io/privacy-policy) for more information about the information Chef collects, and how that information is used. ### Opting Out of Telemetry Admins can opt out of telemetry for the Automate server and all of its users, by editing an existing `configuration.toml` or create a new TOML file. Add the following to the TOML file: ``` [license_control.v1.sys.telemetry] opt_out= true ``` Save the file and apply the changes with: `chef-automate config patch configuration.toml` This will apply the configuration change for telemetry. Individual users can opt out of telemetry by unchecking the telemetry box on the welcome pop-up the first time they log into Automate. To opt out of telemetry at any later point in time, navigate to the profile icon, select “About Chef Automate” from the drop-down, and uncheck the telemetry checkbox. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/telemetry/Airgapped Installation ====================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/airgapped_installation.md) Overview -------- An airgapped host is one that has no direct inbound or outbound internet traffic. To install or upgrade Chef Automate on an airgapped host, you will need to create an Airgap Installation Bundle (`.aib`) on an internet-connected host and then transfer both the Airgap Installation Bundle and the `chef-automate` binary that you used to create it to the airgapped host for use. Get a License ------------- To get a trial license for an airgapped host [contact Chef](https://www.chef.io/contact-us/). Create an Airgap Installation Bundle ------------------------------------ On an internet-connected host, download the Chef Automate command-line tool and use it to prepare an Airgap Installation Bundle. ### Get Chef Automate Installer and Admin Tool Download the Chef Automate command-line tool from the `current` [release channel](../install/index#release-channels). ``` curl https://packages.chef.io/files/current/latest/chef-automate-cli/chef-automate_linux_amd64.zip | gunzip - > chef-automate && chmod +x chef-automate ``` ### Prepare Airgap Installation Bundle To download and bundle the software included in the most recent Chef Automate release, run: ``` ./chef-automate airgap bundle create ``` To download and bundle the software included in a specific Chef Automate release, run ``` ./chef-automate airgap bundle create --version VERSION ``` These commands produce an Airgap Installation Bundle named: `automate-<timestamp>.aib`. Deploy the Airgap Installation Bundle ------------------------------------- Transfer the `chef-automate` binary and the Airgap Installation Bundle to the airgapped host. Save the Chef Automate command-line tool in a directory that is not in your `$PATH`. The Chef Automate installation process puts a copy of `chef-automate` into `/bin` and manages it. ### Create Default Configuration ``` sudo ./chef-automate init-config --upgrade-strategy none ``` creates a `config.toml` file with default values. Setting an upgrade strategy of `none` prevents Chef Automate from checking its release channel for updates via the internet. Edit `config.toml` to make changes to FQDN and other configuration settings. See [Configuring Chef Automate](../configuration/index) for more information on configuration settings. ### Deploy Chef Automate ``` sudo ./chef-automate deploy config.toml --airgap-bundle </path/to/airgap-install-bundle``` Deploying Chef Automate takes ten minutes for a clean install. At the command prompt, accept the terms of service with a `y`, The installer then performs a series of pre-flight checks. Any unsuccessful checks offer information for resolving issues or skipping the check. After resolving any pre-flight issues, run the deploy command again. At the end of the deployment process you will see: ``` Deploy complete ``` The deployment process writes login credentials to the `automate-credentials.toml` in your current working directory. ### Open Chef Automate Navigate to `https://automate.example.com` in a browser and log in to Chef Automate with the credentials provided in `automate-credentials.toml`. Once you log in, Chef Automate prompts you for a license. #### Configure Data Collection To send data from your Chef Infra Server or Chef Infra Clients to Chef Automate 2, the process is the same as Chef Automate 1. See [Configure Data Collection](../data_collection/index) for more information. ### Upgrades Chef is committed to ensuring the stability of the upgrade and to supporting Chef Automate automatic upgrades. To upgrade an airgapped installation, you must first create an airgap bundle. Follow the steps in [Create an Airgap Installation Bundle](#create-an-airgap-installation-bundle) on a machine that connects to the internet to upgrade your Chef Automate command-line tool and prepare an Airgap Installation Bundle. Transfer the bundle and Chef Automate command-line tool to the airgapped host and run: ``` sudo chef-automate upgrade run --airgap-bundle </path/to/bundle``` ### Common Problems If you are unable to open Chef Automate, check that the `config.toml` lists the host’s public DNS name as the FQDN. ``` # This is a default Chef Automate configuration file. You can run # 'chef-automate deploy' with this config file and it should # successfully create a new Chef Automate instance with default settings. [global.v1] # The external fully qualified domain name. # When the application is deployed you should be able to access 'https://<fqdn>/' # to login. fqdn = "<_Public DNS_name_>" ``` Once you correct and save the FQDN, run ``` sudo chef-automate config patch config.toml ``` and retry opening Chef Automate in your browser. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/airgapped_installation/Data Collection =============== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/data_collection.md) Audit Cookbook + InSpec + Automate 2 Versions Support Matrix ============================================================ Refer to the [following Supported Versions list](https://github.com/chef-cookbooks/audit#chef-automate) to confirm a full set of working versions for your chef-client, Audit cookbook, InSpec, and Automate 2. When these do not match up, ingestion problems can occur because the messages will not show up in the expected format. Node Run and Audit Data Collection ================================== Nodes can send their run data to Chef Automate. There are two steps to getting data collection running in Chef Automate: 1. You must first have an API token. You have two options: * [Create a new API token](../api_tokens/index#creating-api-tokens) and add the API token to the Ingest policy, preferably at time of creation. * Or you can [use your existing data collector token](#existing-data-collector-token-setup) if you are migrating from Chef Automate 1. 2. Once you have an API token, you can either: * [Configure your Chef Infra Server to point to Chef Automate](#configure-your-chef-infra-server-to-send-data-to-chef-automate). **If you are using Chef Infra Server, this is the recommended method of sending data to Chef Automate.** * Or, you can have [Chef Infra Client send the data directly to Chef Automate](#configure-your-chef-client-to-send-data-to-chef-automate-without-chef-server). Set Up an Existing Chef Automate 1 Data Collector Token in Chef Automate 2 -------------------------------------------------------------------------- ### Porting the Existing Chef Automate 1 Data Collector Token to Chef Automate 2 If you are migrating from Chef Automate 1, you probably have already deployed a data collector token on either your Chef Infra Servers or your Chef Infra Clients. To re-use your existing data collector token from your Chef Automate 1 installation, you need to perform the configuration change outlined here. For this process, you need the existing token (let’s call it `A1_DC_TOKEN`), and access to the machine running the `chef-automate` CLI client. Create a file (in this example, `data-collector-token.toml`) containing your existing token: ``` [auth_n.v1.sys.service] a1_data_collector_token = "<A1_DC_TOKEN>" ``` Now apply that configuration to your Chef Automate 2 deployment: ``` # chef-automate config patch data-collector-token.toml [...output omitted...] Success: Configuration patched ``` The system will notice that configuration change after a short interval. From that point on, requests using the `x-data-collector-token: <A1_DC_TOKEN>` header will be accepted. When logged in with admin permissions, you will also find your added token in `https://automate.example.com/admin/tokens`, under the name > Legacy data collector token ported from A1 Now that you have a valid API token, you’ll need to [update your Chef Infra Server data collector configuration](#configure-your-chef-infra-server-to-send-data-to-chef-automate) if you are using a Chef Infra Server. Otherwise, you must [configure your Chef Infra Clients to send data directly to Chef Automate](#configure-your-chef-client-to-send-data-to-chef-automate-without-chef-server). Configure your Chef Infra Server to Send Data to Chef Automate -------------------------------------------------------------- Note Multiple Chef Infra Servers can send data to a single Chef Automate server. In addition to forwarding Chef run data to Chef Automate, Chef Infra Server will send messages to Chef Automate whenever an action is taken on a Chef Infra Server object, such as when a cookbook is uploaded to the Chef Infra Server or when a user edits a role. In order to have Chef Infra Server send run data from connected Chef Infra Clients, set the data collection proxy attribute to `true`. ### Setting Up Data Collection on Chef Infra Server Deployed with the Chef Automate Installer This step sets up data collection from a standalone Chef Infra Server deployed with the Chef Automate Installer to a separate Chef Automate server. Open the `config.toml` file and include the external automate configuration settings: ``` [global.v1.external.automate] enable = true node = "https://<automate server url>" [global.v1.external.automate.auth] token = "<data-collector token>" [global.v1.external.automate.ssl] server_name = "<server name from the automate server ssl cert>" root_cert = """<pem format root CA cert> """ [auth_n.v1.sys.service] a1_data_collector_token = "<data-collector token>" [erchef.v1.sys.data_collector] enabled = true ``` Then, run `chef-automate config patch config.toml`. ### Setting Up Data Collection on Chef Infra Server Versions 12.14 and Higher Instead of setting the token directly in `/etc/opscode/chef-server.rb` as was done in older versions of the Chef Infra Server, we’ll use the `set-secret` command, so that your API token does not live in plaintext in a file: ``` sudo chef-server-ctl set-secret data_collector token '<API_TOKEN_FROM_STEP_1>' sudo chef-server-ctl restart nginx sudo chef-server-ctl restart opscode-erchef ``` Next, configure the Chef Infra Server for data collection forwarding by adding the following setting to `/etc/opscode/chef-server.rb`: ``` data_collector['root_url'] = 'https://automate.example.com/data-collector/v0/' # Add for Chef Infra Client run forwarding data_collector['proxy'] = true # Add for compliance scanning profiles['root_url'] = 'https://automate.example.com' # Save and close the file ``` To apply the changes, run: ``` sudo chef-server-ctl reconfigure ``` ### Setting Up Chef Infra Client to Send Compliance Scan Data Through the Chef Infra Server to Chef Automate Now that the Chef Infra Server is configured for data collection, you can also enable Compliance Scanning on your Chef Infra Clients via the [Audit Cookbook](https://github.com/chef-cookbooks/audit). * Set the following attributes for the audit cookbook: ``` default['audit']['reporter'] = 'chef-server-automate' default['audit']['fetcher'] = 'chef-server' default['audit']['profiles'].push( 'name': 'cis-centos7-level2', 'compliance': 'user-name/cis-centos7-level2' # in the ui for automate, this value is the identifier for the profile ) default['audit']['interval'] = { 'enabled': true 'time': 1440 # once a day, the default value } ``` Now, any node with `audit::default` its runlist will fetch and report data to and from Chef Automate via the Chef Infra Server. Please see the audit cookbook for an [exhaustive list of configuration options](https://github.com/chef-cookbooks/audit). ### Additional Chef Infra Server Data Collection Configuration Options | Option | Description | Default | | --- | --- | --- | | `data_collector['proxy']` | If set to true, Chef Infra Server will proxy all requests sent to /data-collector to the configured Chef Automate `data_collector['root_url']`. Note that this route does not check the request signature and add the right data_collector token, but just proxies the Chef Automate endpoint as-is. | Default: `nil` | | `data_collector['timeout']` | Timeout in milliseconds to abort an attempt to send a message to the Chef Automate server. | Default: `30000` | | `data_collector['http_init_count']` | Number of Chef Automate HTTP workers Chef Infra Server should start. | Default: `25` | | `data_collector['http_max_count']` | Maximum number of Chef Automate HTTP workers Chef Infra Server should allow to exist at any time. | Default: `100` | | `data_collector['http_max_age']` | Maximum age a Chef Automate HTTP worker should be allowed to live, specified as an Erlang tuple. | Default: `{70, sec}` | | `data_collector['http_cull_interval']` | How often Chef Infra Server should cull aged-out Chef Automate HTTP workers that have exceeded their `http_max_age`, specified as an Erlang tuple. | Default: `{1, min}` | | `data_collector['http_max_connection_duration']` | Maximum duration an HTTP connection is allowed to exist before it is terminated, specified as an Erlang tuple. | Default: `{70, sec}` | Configure your Chef Infra Client to Send Data to Chef Automate without Chef Infra Server ---------------------------------------------------------------------------------------- If you do not use a Chef Infra Server in your environment (if you only use `chef-solo`, for example), you can configure your Chef Infra Clients to send their run data to Chef Automate directly by performing the following: 1. Add Chef Automate SSL certificate to `trusted_certs` directory. 2. Configure Chef Infra Client to use the Data Collector endpoint and API token in Chef Automate. ### Add Chef Automate certificate to `trusted_certs` directory **Note:** This step only applies to self-signed SSL certificates. If you are using an SSL certificate signed by a valid certificate authority, you may skip this step. Chef requires that the self-signed Chef Automate SSL certificate (`HOSTNAME.crt`) is located in the `/etc/chef/trusted_certs` directory on any node that wants to send data to Chef Automate. This directory is the location into which SSL certificates are placed when a node has been bootstrapped with chef-client. To fetch the certificate onto your workstation, use `knife ssl fetch` and pass in the URL of the Chef Automate server. You can then use utilities such as `scp` or `rsync` to copy the downloaded cert files from your `.chef/trusted_certs` directory to the `/etc/chef/trusted_certs` directory on the nodes in your infrastructure that will be sending data directly to the Chef Automate server. ### Configure Chef Infra Client to Use the Data Collector Endpoint in Chef Automate Warning Chef version 12.12.15 or greater is required. The data collector functionality is used by the Chef Infra Client to send node and converge data to Chef Automate. This feature works for Chef Infra Client, as well as both the default and legacy modes of `chef-solo`. To send node, converge, and compliance data to Chef Automate, modify your Chef config (that is `client.rb`, `solo.rb`, or add an additional config file in an appropriate directory, such as `client.d`) to contain the following configuration: ``` data_collector.server_url "https://automate.example.com/data-collector/v0/" data_collector.token '<API_TOKEN_FROM_STEP_1>' ``` ### Setting Up Chef Infra Client to Send Compliance Scan Data Directly to Chef Automate Now that the Chef Infra Client is configured for data collection, you can also enable Compliance Scanning on via the [Audit Cookbook](https://github.com/chef-cookbooks/audit). * Set the following attributes for the audit cookbook: ``` default['audit']['reporter'] = 'chef-automate' default['audit']['fetcher'] = 'chef-automate' default['audit']['token'] = '<API_TOKEN_FROM_STEP_1>' default['audit']['profiles'].push( 'name': 'cis-centos7-level2', 'compliance': 'user-name/cis-centos7-level2' # in the ui for automate, this value is the identifier for the profile ) default['audit']['interval'] = { 'enabled': true 'time': 1440 # once a day, the default value } ``` Now, any node with `audit::default` its runlist will fetch and report data directly to and from Chef Automate. Please see the audit cookbook for an [exhaustive list of configuration options](https://github.com/chef-cookbooks/audit). #### Additional Chef Infra Client Data Collection Configuration Options | Configuration | Description | Options | Default | | --- | --- | --- | --- | | `data_collector.mode` | The mode in which the data collector is allowed to operate. This can be used to run data collector only when running as Chef solo but not when using Chef Infra Client. | `:solo`, `:client`, or `:both` | `:both` | | `data_collector.raise_on_failure` | When the data collector cannot send the “starting a run” message to the data collector server, the data collector will be disabled for that run. In some situations, such as highly-regulated environments, it may be more reasonable to Prevents data collection when the data collector cannot send the “starting a run” message to the data collector server. In these situations, setting this value to `true` will cause the Chef run to raise an exception before starting any converge activities. | `true`, `false` | `false` | | `data_collector.organization` | A user-supplied organization string that can be sent in payloads generated by the data collector when Chef is run in Solo mode. This allows users to associate their Solo nodes with faux organizations without the nodes being connected to an actual Chef Infra Server. | `string` | `none` | Troubleshooting: My Data Does Not Show Up in the User Interface --------------------------------------------------------------- Organizations without associated nodes will not show up on the Chef Automate *Nodes* page. A node is not associated with Automate until a Chef Infra Client run has completed. This is also true for roles, cookbooks, recipes, attributes, resources, node names, and environments but does not highlight them in the UI. This is designed to keep the UI focused on the nodes in your cluster. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/data_collection/Session Timeout =============== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/session_timeout.md) Chef Automate has an optional session timeout configuration for signing out idle workstations. Chef Automate measure session activity as any interaction from a workstation, from a mouse, keyboard, or touchpad. With session timeout enabled, Chef Automate signs out idle workstations after a set number of minutes. To enable session_timeout in Chef Automate: * Set the value of `enable_idle_timeout` property to **true** in *config.toml* file. * Set the value of `idle_timeout_minutes` property to your desired time in minutes(for example **30**). (Setting the value of this property to **30** will set the session timeout time to 30 minutes). Note The minimum value of `idle_timeout_minutes` can be 5 minutes. This example sets the session timeout to 30 minutes, which means that Chef Automate signs out any connected workstation after 30 minutes of inactivity: ``` [global.v1] [global.v1.session_settings] enable_idle_timeout = true idle_timeout_minutes = 30 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/session_timeout/Install Chef Infra Server With Automate ======================================= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/infra_server.md) Warning Chef Automate will not deploy the Chef Manage add-on for Chef Infra Server. Warning Supermarket cannot authenticate users on Chef Infra Server deployed with Chef Automate. Use Chef Automate to install Chef Infra Server either for a single-host installation that contains both Chef Infra Server and Chef Automate, or for a standalone Chef Infra Server instance. See the [Chef Infra Server documentation](../../server/index) for instructions and guidance on using and managing your Chef Infra Server. System Requirements and Prerequisites ------------------------------------- Before beginning your installation, check the [System Requirements](../system_requirements/index) for Chef Automate, and ensure that the `chef-automate` command line tool installed. To download the `chef-automate` command line tool, run the following command in your command line interface: ``` curl https://packages.chef.io/files/current/latest/chef-automate-cli/chef-automate_linux_amd64.zip | gunzip - > chef-automate && chmod +x chef-automate ``` Install Chef Automate and Chef Infra Server on the Same Host ------------------------------------------------------------ Use either a command line interface or a configuration file to install Chef Automate and Chef Infra Server on the same host. Installations require elevated privileges, so run the commands as the superuser or use `sudo` at the start of each command. ### Hardware Requirements for Single-Host Installation For a single-host installation that contains Chef Infra Server and Chef Automate, we recommend the following memory and vCPU minimums: * up to 200 managed nodes: 8GB RAM, 2 vCPUs * between 200 and 500 managed nodes: 30GB RAM, 4 vCPUs * between 500 and 5000 managed nodes: 61GB RAM, 8vCPUs A single-host installation that contains Chef Infra Server and Chef Automate requires a `/hab` directory that contains 80 GB of disk space for software artifacts plus 2 MB of disk space per managed node. ### Command Line Install of Chef Automate and Infra Server Install Chef Automate and Chef Infra Server on the same host with this command: ``` sudo chef-automate deploy --product automate --product infra-server ``` Then, [set up knife](../../workstation/knife_setup/index) for use with Chef Infra Server. ### Configuration File Install of Chef Automate and Infra Server Installing Chef Automate and Chef Infra Server on the same host using a configuration file also requires the use of the Chef Automate CLI. Installations require elevated privileges, so run the commands as the superuser or use `sudo` at the start of each command. 1. First, generate a skeleton configuration file by running this command: ``` sudo chef-automate init-config ``` 2. Add a stanza to the configuration file to deploy Chef Automate and Chef Infra Server: ``` [deployment.v1.svc] products=["automate", "infra-server"] ``` 3. Make any other configuration changes desired. 4. Run the `chef-automate deploy` command with your configuration file: ``` sudo chef-automate deploy config.toml ``` 5. [Set up knife](../../workstation/knife_setup/index) for use with Chef Infra Server. Install A Standalone Chef Infra Server -------------------------------------- Use either a command line interface or a configuration file to install Chef Infra Server using the Chef Automate `deploy` command. Refer to the Chef Infra Server [hardware requirements](../../server/install_server_pre/index) for guidance on memory and number of CPUs. ### Command Line Install of Standalone Chef Infra Server When Chef Automate deploys the Chef Infra Server, it automatically configures the Chef Infra Server to collect data to send to Chef Automate. To deploy a standalone Chef Infra Server with Chef Automate, you must turn off data collection in the configuration. Installations require elevated privileges, so run the commands as the superuser or use `sudo` at the start of each command. 1. First, generate a skeleton configuration file by running: ``` sudo chef-automate init-config ``` 2. Add a stanza to the configuration file to disable Chef Automate data collection: ``` [erchef.v1.sys.data_collector] enabled = false ``` 3. Use the configuration file to deploy Chef Infra Server by running the following command: ``` sudo chef-automate deploy --product infra-server <configuration_file``` 4. [Set up knife](../../workstation/knife_setup/index) for use with Chef Infra Server. 5. To send data from the Chef Infra Server to an external Chef Automate installation, first create a `patch.toml` file that contains the configuration stanza: ``` [global.v1.external.automate] enable = true node = "https://<automate server url>" [global.v1.external.automate.auth] token = "<data-collector token>" [global.v1.external.automate.ssl] server_name = "<server name from the automate server ssl cert>" root_cert = """<pem format root CA cert> """ [auth_n.v1.sys.service] # It is fine to use an A2 data collector token. a1_data_collector_token = "<data-collector token>" [erchef.v1.sys.data_collector] enabled = true ``` Then run `chef-automate config patch patch.toml` to patch your Chef Infra Server configuration. ### Install a Standalone Chef Infra Server with a Configuration File Installing Chef Infra Server through Chef Automate using a configuration file also requires the use of the Chef Automate CLI. When Chef Automate deploys the Chef Infra Server, it automatically configures the Chef Infra Server to collect data to send to Chef Automate. To deploy a standalone Chef Infra Server with Chef Automate, you must turn off data collection in the configuration. Installations require elevated privileges, so run the commands as the superuser or use `sudo` at the start of each command. 1. First, generate a skeleton configuration file by running the following command: ``` sudo chef-automate init-config ``` 2. Add a stanza to the configuration file to deploy Chef Infra Server: ``` [deployment.v1.svc] products=["infra-server"] # Disable Automate data collection as Automate will not be deployed [erchef.v1.sys.data_collector] enabled = false ``` 3. Run the `chef-automate deploy` command with your configuration file (config.toml): ``` sudo chef-automate deploy config.toml ``` 4. [Set up knife](../../workstation/knife_setup/index) for use with Chef Infra Server. 5. To send data from the Chef Infra Server to an external Chef Automate installation, first create a `patch.toml` file that contains the configuration stanza: ``` [global.v1.external.automate] enable = true node = "https://<automate server url>" [global.v1.external.automate.auth] token = "<data-collector token>" [global.v1.external.automate.ssl] server_name = "<server name from the automate server ssl cert>" root_cert = """<pem format root CA cert> """ [auth_n.v1.sys.service] # It is fine to use an A2 data collector token. a1_data_collector_token = "<data-collector token>" [erchef.v1.sys.data_collector] enabled = true ``` Then run `chef-automate config patch patch.toml` to patch your Chef Infra Server configuration. Add a New Chef Infra Server to an Existing Chef Automate Installation --------------------------------------------------------------------- Patch an existing Chef Automate installation to add Chef Infra Server: 1. Create a `patch.toml` file to add `infra-server` to the list of products to deploy: ``` [deployment.v1.svc] products=["automate", "infra-server"] ``` 2. Apply the patch to the Chef Automate installation: ``` sudo chef-automate config patch ./patch.toml ``` The command output shows the added Chef Infra Server services: ``` Updating deployment configuration Applying deployment configuration Installed automate-cs-bookshelf Installed automate-cs-oc-bifrost Installed automate-cs-oc-erchef Installed automate-cs-nginx Started automate-cs-bookshelf Started automate-cs-oc-bifrost Started automate-cs-oc-erchef Started automate-cs-nginx Started automate-load-balancer Success: Configuration patched ``` Set Up the Chef Infra Server ---------------------------- The [`knife` command-line utility](../../workstation/knife/index) provides an interface to interact with a Chef Infra Server from a workstation. On the Chef Infra Server host: 1. Run the following command to create a user: ``` sudo chef-server-ctl user-create USER_NAME FIRST_NAME LAST_NAME EMAIL 'PASSWORD' --filename USER_NAME.pem ``` An RSA private key generates automatically and is the chef-validator key. Save this RSA private key to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. 2. Run the following command to create an organization, generate its validator key, and assign the user created in the previous step as an administrator: ``` sudo chef-server-ctl org-create SHORT_NAME 'FULL_ORGANIZATION_NAME' --association_user USER_NAME --filename ORGANIZATION-validator.pem ``` The short name must begin with a lower-case letter or digit, may contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `4thcoffee`. The full organization name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `'Fourth Coffee, Inc.'`. The `--association_user` option will associate the `USER_NAME` with the `admins` security group on the Chef Infra Server. An RSA private key generates automatically and is the chef-validator key. Save this RSA private key to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. On the workstation: 1. Install [Chef Workstation](../../workstation/install_workstation/index). 2. Create a Chef repository by using the `chef generate repo` subcommand. For example, create a Chef repository named `chef-repo` by running: ``` chef generate repo chef-repo ``` Replace `chef-repo` with your desired repository name. 3. Within your named Chef repository, create a `.chef` directory with the `mkdir` command. For example: ``` mkdir /chef-repo/.chef ``` 4. Copy `ORGANIZATION-validator.pem` and `USER_NAME.pem` to the `.chef` directory. 5. In the `.chef` directory, create a `config.rb` file that contains: ``` current_dir = File.dirname(__FILE__) node_name 'USER_NAME' client_key "#{current_dir}/USER_NAME.pem" validation_client_name 'ORGANIZATION-validator' validation_key "#{current_dir}/ORGANIZATION.pem" chef_server_url 'https://automate.example.com/organizations/ORGANIZATION' cookbook_path ["#{current_dir}/../cookbooks"] ``` For airgapped installations, [create a bootstrap template](../../install_chef_air_gap/index#create-a-bootstrap-template) and [add it](../../install_chef_air_gap/index#configure-knife) to your `config.rb`. 6. Run `knife ssl fetch` to get the SSL certificates from Chef Infra Server and make them available to `knife`. For more information on how to set up the workstation, see [the Chef Workstation documentation](../../workstation/getting_started/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/infra_server/Log Management ============== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/log_management.md) Chef Automate 2.0 uses `systemd`. Log management is performed according to the configuration defined for the system service `journald`. ### Viewing Logs To view the logs you can run: ``` journalctl -u chef-automate ``` To follow the logs in realtime: ``` journalctl -u chef-automate -f ``` For information on changing the output, please refer to the man page or run: ``` journalctl --help ``` ### Configuring Log Level You can configure Chef Automate log level for all services by creating a TOML file and configuring the log level. By default each service will initialize at the “info” level but can be any of ‘debug, ‘info’, ‘warning’, ‘panic’, or ‘fatal’. ``` [global.v1.log] level = "debug" ``` Then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. ### Configuring Log Rotation and Retention Log rotation and retention settings are managed at a system level using `journald`. At this point, `journald` does not support log retention policies at a granular level for units within itself. See the [man page](https://www.freedesktop.org/software/systemd/man/journald.conf.html) for more configuration options in `/etc/systemd/journald.conf`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/log_management/SAML ==== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/saml.md) Authentication via Existing Identity Management Systems ------------------------------------------------------- Chef Automate can integrate with existing SAML services to authenticate users in Chef Automate, and thus use their existing group memberships to determine their Chef Automate permissions. Chef Automate supports using both local users and externally managed users from an external identity provider (IdP). Both *one* LDAP service (or MSAD for simplified configuration of Active Directory setups) and *one* SAML IdP can be used. You do not need to configure an external IdP if you simply want to create users and teams local to Chef Automate. See the [Users](../users/index) documentation for additional information. Chef Automate uses [Dex](https://github.com/dexidp/dex) to support SAML integrations. To configure authentication for your Chef Automate installation, create a TOML file that contains the partial SAML configuration. Then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. Warning You may only integrate one IdP using SAML and one IdP using LDAP at a time. Chef Automate does not support using *two* SAML IdPs or *two* LDAP services simultaneously. If you need to change your configured IdP, you will need to replace your existing configuration by following these steps: 1. Run `chef-automate config show config.toml`. 2. Edit `config.toml` to replace the `dex.v1.sys.connectors` section with the config values for your new identity provider. 3. Run `chef-automate config set config.toml` to set your updated config. Note Users who sign in via SAML will have a session time of 24 hours before needing to sign in again. Supported Identity Management Systems ------------------------------------- * [Azure AD](#azure-ad) * Office365 * OKTA * OneLogin * Ping * Tivoli Federated Identity Manager ### Azure AD Using Azure AD as an SAML IdP requires specific configuration for both Azure AD and Chef Automate. Note The signing certificate used for Chef Automate’s SAML integration with Azure AD requires manual management. Signing key rotation is not done automatically. In Azure AD, add Chef Automate as a *“non-gallery application”*, and then configure its SAML sign-in method. [The Azure AD documentation](https://docs.microsoft.com/en-us/azure/active-directory/manage-apps/configure-saml-single-sign-on) provides a detailed guide. Enter `https://automate.example.com/dex/callback` as the value for both *Identifier (Entity ID)* and *Reply URL (Assertion Consumer Service URL)*. You may use the default claims provided by Azure AD. Remember to edit the Chef Automate configuration in `config.toml` to reflect this claims information. Download the *Certificate (Base64)* in Azure AD and take note of the *Login URL* for use in the Chef Automate configuration. After configuring Azure AD, edit your Chef Automate `config.toml` configuration file to reflect the values entered in the Azure AD interface. The minimal configuration snippet in `config.toml` will look similar to: ``` [dex.v1.sys.connectors.saml] ca_contents=""" <<Certificate (Base64)>> """ sso_url = "<<Login URL>>" email_attr = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" username_attr = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" entity_issuer = "https://automate.example.com/dex/callback" ``` where: * `ca_contents` contains the value of the *Certificate (Base64)*, and includes the `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----` markers * `sso_url` contains the value of *Login URL* * `entity_issuer` contains the value of *Identifier (Entity ID)* See the [SAML Configuration Settings](index#saml-configuration-settings) for further configuration options. Warning Azure AD lets you choose the *NameID* field, and optionally apply *transformations* to it. The SAML configuration setting is only respected if the selected value in “Choose name identifier format” in Azure AD matches the `name_id_policy_format` configuration in Chef Automate. SAML Configuration Settings --------------------------- The SAML configuration settings are: ``` [dex.v1.sys.connectors.saml] ca_contents = "<your ca contents>" # required sso_url = "<your SSO URL>" # required email_attr = "<your email attribute>" # required username_attr = "<your username attribute>" # required groups_attr = "<your groups attribute>" # optional allowed_groups = ["group1", "group 2"] # optional entity_issuer = "<your entity issuer>" # optional name_id_policy_format = "<see below>" # optional ``` `ca_contents` must contain a copy of the certificate used to sign the SAML assertions. The certificate should be a PEM-encoded string. For example, ``` ca_contents = """-----BEGIN CERTIFICATE----- MIIE+DCCAuCgAwIBAgIBATANBgkqhkiG9w0BAQsFADAcMRowGAYDVQQDExFDaGVm [...] s1V9oZ7+NcK8vtcdXhjB5N65LbPlaT3nbvXGIvsQmoGc+FQ5WI4agoNlofOCogdW k2WFcoiiKyeIznNScx/K6AeykKR/lPrJedanSA== -----END CERTIFICATE----- """ ``` Warning The `groups_attr` setting is optional, but if not provided, users authenticating via SAML will not be members of any teams. Setting `allowed_groups` provides SAML sign in to members of the listed groups. All of the other user groups that are *not* in the list are discarded, and not available to Chef Automate. In the configuration example above, only users in either “group1” or “group2” may sign in, and those groups would appear as `team:saml:group1` and `team:saml:group2` respectively. Chef Automate supports using SAML to authenticate users and apply permissions to SAML groups. See [IAM Overview](../iam_v2_overview/index). Member expressions are required for externally managed users and teams, as well as API tokens. See [IAM_v2_Guide](../iam_v2_guide/index#member-expressions). ``` [dex.v1.sys.connectors.saml] ca_contents = "<your ca contents>" sso_url = "<your SAML SSO URL>" ### # SAML Attributes to map to a user's Chef Automate session ### # Example: "email" email_attr = "<your email attribute>" # Example: "name" username_attr = "<your username attribute>" # Example: "groups" groups_attr = "<your groups attribute>" # Optional: Manually specify Chef Automate's Issuer value. # # When provided Chef Automate will include this as the Issuer value in the SAML # AuthnRequest. It will also override the redirectURI as the required audience # when evaluating AudienceRestriction elements in the response. # Example: "https://automate.example.com/dex/callback" entity_issuer = "<your entity issuer>" # Optional: Specify the NameIDPolicy to use # # When provided, Chef Automate will request a name ID of the configured format # in the SAML AuthnRequest. # Defaults to "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent". # # Note: Even when configured otherwise, the username gathered from the SAML # response is _treated_ as persistent. So, if this is set to # "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" # and a user has changed their email address, they will be a _new_ user to Chef # Automate. name_id_policy_format = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified" ``` In your SAML Identity Provider (IdP), your Chef Automate instance needs to be referenced as a Service Provider (SP). To do so, use `https://automate.example.com/dex/callback`. The concrete configuration items differ between IdP products, but it is often something like “Assertion Consumption URI” or “Single sign on URL”. For “Audience URI” or “SP Entity ID”, use the same address. These values are accepted for `name_id_policy_format`: * `urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress` * `urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified` * `urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName` * `urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName` * `urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted` * `urn:oasis:names:tc:SAML:2.0:nameid-format:entity` * `urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos` * `urn:oasis:names:tc:SAML:2.0:nameid-format:persistent` * `urn:oasis:names:tc:SAML:2.0:nameid-format:transient` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/saml/Install Chef Automate with Chef Habitat Builder On-prem ======================================================= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/on_prem_builder.md) This guide details how to install Chef Automate and deploy Chef Habitat Builder on-prem together. Enterprise customers may wish to set up an on-premises Chef Habitat Builder depot to store Chef Habitat packages for use by their own Chef Habitat Studios and Supervisors. This guide covers setting up Chef Automate and Chef Habitat Builder on-prem, and bootstrapping Chef Habitat Builder on-prem with curated core seed lists from the Chef Habitat public Builder. The Chef installer includes everything necessary to get started with Chef Automate and Chef Habitat Builder on-prem. Bootstrapping Chef Habitat Builder requires: * An outward bound HTTPS connection * An existing Chef Habitat [public Builder](https://bldr.habitat.sh) account. System Requirements ------------------- This guide demonstrates setup of Chef Habitat Builder on-prem by installing the components with the Chef Automate deployment utility. Contact your Chef representative before using this implementation in production for more specific scale recommendations. ### Hardware Requirements The minimum with which Chef Automate and Chef Habitat Builder can be deployed on a single host is: * 16 GB of RAM. * 130 GB of disk space, available to /hab. * 4 vCPUs. * Inbound network connectivity from LAN (HTTP/HTTPS) is required for internal clients to access the on-premises Chef Habitat Builder. For deployments that are expected to see production-scale workload, we recommend: * 64 GB of RAM. * 200 GB of diskspace, available to /hab. * 16 vCPUs. Roughly 80 GB of the disk space is designated for Chef Automate; the rest is used for Chef Habitat Builder and the artifacts it stores. The current implementation uses MinIO for Chef Habitat artifact storage; we do not support using Artifactory for artifact storage. ### Operating System Chef Automate and Chef Habitat Builder require: * a Linux kernel of version 3.2 or greater * `systemd` as the init system * `useradd` * `curl` or `wget` * The shell that starts Chef Automate should have a max open files setting of at least 65535 * Run the installation and bootstrapping procedures as the superuser or use `sudo` at the start of each command. ### Supported Topologies * Chef Automate and Chef Habitat Builder on the same host * Chef Automate and Chef Habitat Builder on different hosts ### Unsupported Topologies * high-availability/DR/multinode Builder Get Started with Chef Automate and Chef Habitat On-prem ------------------------------------------------------- ### Download the Chef Automate Installer Download and unzip the installer: ``` curl https://packages.chef.io/files/current/latest/chef-automate-cli/chef-automate_linux_amd64.zip | gunzip - > chef-automate && chmod +x chef-automate ``` ### Deploy Chef Automate and Chef Habitat Builder On-prem Deploying Chef Habitat Builder with Chef Automate requires a Chef Automate license. If you already have a Chef Automate license, you may use it for the deployment. Otherwise, you can accept the 30-day trial license when you first sign in to Chef Automate. If you are deploying Chef Habitat Builder with Chef Automate in an airgapped environment, follow [the documentation on building an airgap bundle](../airgapped_installation/index). You can deploy Chef Habitat Builder either with a full Chef Automate installation or with the Chef Automate auth stack only. When deploying Chef Habitat Builder on the same host as Chef Automate, authentication to Chef Automate will be configured as part of the deployment. #### Deploy Chef Automate and Chef Habitat Builder To deploy Chef Automate and Chef Habitat Builder on the same host, specify both the `builder` and `automate` products on the command line. For example: ``` ./chef-automate deploy --product builder --product automate ``` Accept the license with `y`. #### Deploy Chef Habitat Builder with Chef Automate Auth To deploy Chef Habitat Builder on a different host than Chef Automate, specify only the `builder` product on the command line. Chef Automate UI and Auth services only will also be deployed to support authentication. When deploying Chef Habitat Builder on a different host than Chef Automate the supported authentication options are LDAP or SAML. Follow the standard instructions for [Chef Automate LDAP](../ldap/index) or [Chef Automate SAML](../saml/index) configuration. For example: ``` ./chef-automate deploy --product builder ``` Accept the license with `y`. Please note that the Chef Automate UI will only support managing Users, Groups, and Authorization policies when deployed without the full Chef Automate stack. If you wish to enable all of Chef Automate at a later time, you can update the product configuration to include the complete Chef Automate stack. For example: 1. Create a new patch configuration toml as `config.toml` and update the products to include both `builder` and `automate`: ``` [deployment.v1.svc] products = ["builder", "automate"] ``` 2. Patch the configuration to deploy the rest of the Chef Automate services: ``` ./chef-automate config patch config.toml ``` You should see output similar to: ``` Updating deployment configuration Applying deployment configuration Installed automate-elasticsearch Installed automate-es-gateway Installed event-service Installed es-sidecar-service Installed event-feed-service Installed secrets-service Installed applications-service Installed notifications-service Installed nodemanager-service Installed compliance-service Installed ingest-service Installed config-mgmt-service Installed data-feed-service Installed event-gateway Started automate-elasticsearch Started automate-es-gateway Started event-service Started es-sidecar-service Started event-feed-service Started secrets-service Started applications-service Started notifications-service Started nodemanager-service Started compliance-service Started ingest-service Started config-mgmt-service Started data-feed-service Started event-gateway Started automate-load-balancer Success: Configuration patched ``` #### Add Chef Habitat Builder to a Chef Automate Installation Patch an existing Chef Automate installation to add Chef Habitat Builder: 1. Create a `patch.toml` file to add `builder` to the list of products to deploy: ``` [deployment.v1.svc] products=["automate", "builder"] ``` 2. Apply the patch to the Chef Automate installation: ``` sudo chef-automate config ./patch.toml ``` The command output shows the Chef Habitat Builder services being added: ``` Updating deployment configuration Applying deployment configuration Installed automate-minio Installed automate-builder-memcached Installed automate-builder-api Installed automate-builder-api-proxy Started automate-minio Started automate-builder-memcached Started automate-builder-api Started automate-builder-api-proxy Started automate-load-balancer Success: Configuration patched ``` ### Sign in to Chef Automate and the Chef Habitat Builder 1. View your login credentials in the terminal with: ``` cat automate-credentials.toml ``` You should see output similar to: ``` url = "https://automate.example.com" username = "admin" password = "abcdefgh1234567890PASSWORDSTRING" ``` 2. Navigate to `https://automate.example.com` in your browser. If you cannot access the site in Google Chrome, try Mozilla Firefox or Microsoft Edge. 3. Sign in to Chef Automate using the [credentials provided during deployment](../install/index#open-chef-automate). 4. Select **Applications** in the top navigation bar 5. Select **Chef Habitat Builder** in the left sidebar, which redirects the browser to the Chef Habitat Builder login site 6. Select **Sign in with Chef Automate** 7. Sign into Chef Habitat Builder using the same credentials used with Chef Automate ### Generate a Chef Habitat on-prem Builder Personal Access Token You need a Personal Access Token for Chef Habitat on-prem in order to bootstrap packages and to perform authenticated operations with the `hab` client. Select your Gravatar icon on the top right corner of the Chef Habitat Builder web page, and then select Profile. This will take you to a page where you can generate your access token. Make sure to save it securely. ### Create the Core Origin Once you are signed in to the Chef Habitat Builder UI, select the **New Origin** button and enter `core` as the name for the origin. Access Chef Habitat Builder On-prem With Chef Habitat Command-Line Tools ------------------------------------------------------------------------ Use the `https://automate.example.com/bldr/v1` URL when accessing your Chef Habitat Builder installation with the Chef Habitat command-line tools. The Chef Habitat command-line tools recognize the [`HAB_BLDR_URL` environment variable](../../habitat/environment_variables/index), which you can set on the command line with: ``` export HAB_BLDR_URL=https://automate.example.com/bldr/v1/ ``` Access the Chef Habitat Builder On-prem REST API ------------------------------------------------ To access the [REST API](https://docs.chef.io/habitat/builder_api/) for your on-prem installation of Chef Habitat Builder, you must specify your Builder authentication token as a bearer token in your request’s `Authorization` header. For example: ``` curl -H "Authorization: Bearer <your-habitat-builder-auth-token>" https://automate.example.com/bldr/v1/... ``` Bootstrap Chef Habitat Builder with Core Packages (Optional) ------------------------------------------------------------ Prerequisites: * HTTPS connection * GitHub account * Public Chef Habitat Builder account * Public Chef Habitat Builder personal access token Use [seed lists](https://github.com/habitat-sh/on-prem-builder/blob/main/package_seed_lists/README.md) to populate your on-premises Chef Habitat Builder installation with the packages required by your builds. [Sample seed lists](https://github.com/habitat-sh/on-prem-builder/tree/main/package_seed_lists) exist for the following scenarios: * Full `core`: the full contents of the upstream `core` origin. The x86_64 Linux set expands to 12GB, the Linux kernel2 set to 1GB, and the Windows set to 3.5GB. * Core dependencies: a subset of `core` consisting of commonly-used buildtime dependencies. * Effortless: packages used to start with the [Effortless pattern](https://github.com/chef/effortless). A complete Effortless implementation requires the contents of both the `stable` and the `unstable` channel. ### Clone the Chef Habitat Builder On-prem Repository To access the curated seed lists for bootstrapping Chef Habitat Builder on-prem, you will need to clone the Chef Habitat Builder on-prem repository using https. ``` git clone https://github.com/habitat-sh/on-prem-builder.git ``` Once the repository is successfully cloned, move into the `on-prem-builder` repository: ``` cd on-prem-builder ``` The Chef Automate installer uses a self-signed certificate. Copy the SSL public key certificate chain from Chef Automate into `/hab/cache/ssl` with this command: ``` cp /hab/svc/automate-load-balancer/data/automate.example.com.cert /hab/cache/ssl/automate.example.com.cert ``` ### Download Seed List Packages from the Public Chef Habitat Builder Your host must have access to the internet to download the curated seed list packages from the **public** [Chef Habitat Builder](https://bldr.habitat.sh). If you have not already done so, create a user account and personal access token on the **public** [Chef Habitat Builder](https://bldr.habitat.sh/). Use the `hab pkg download` command with a seed list `</path/to/seed_list>` to download packages for your desired architecture `<arch>` from a channel `<channel>` to a directory `<artifact-dir>`: ``` HAB_AUTH_TOKEN=<your_public_builder_personal_access_token> hab pkg download --target <arch> --channel <channel> --file </path/to/seed_list> --download-directory <artifact-dir``` For example, to use the Effortless seed list to download `x86_64-linux` packages from the `stable` channel to the `builder_bootstrap` directory: ``` HAB_AUTH_TOKEN=<your_public_builder_personal_access_token> hab pkg download --target x86_64-linux --channel stable --file package_seed_lists/effortless_x86_64-linux_stable --download-directory builder_bootstrap ``` ### Bulk-Upload Seed List Packages to Chef Habitat Builder on-prem Run the `bulkupload` command to upload artifacts from `<artifact-dir>` to the `<channel>` channel in the on-premises Chef Habitat Builder using the [Builder API endpoint](index#access-chef-habitat-builder-on-prem-with-chef-habitat-command-line-tools): ``` HAB_AUTH_TOKEN=<your_on-prem_Builder_personal_access_token> hab pkg bulkupload --url https://automate.example.com/bldr/v1 --channel <channel> <artifact-dir> --auto-create-origins ``` For example, ``` HAB_AUTH_TOKEN=<your_on-prem_Builder_personal_access_token> hab pkg bulkupload --url https://automate.example.com/bldr/v1 --channel stable builder_bootstrap/ --auto-create-origins ``` Should produce the output: ``` Preparing to upload artifacts to the 'stable' channel on https://automate.example.com/bldr/v1 Using builder_bootstrap/artifacts for artifacts and builder_bootstrap/keys signing keys Found 46 artifact(s) for upload. Discovering origin names from local artifact cache Missing origin 'chef' Origin 'core' already exists Missing origin 'effortless' Creating origin chef. Created origin chef. Creating origin effortless. Created origin effortless. 75 B / 75 B | [===========================================] 100.00 % 1.31 MB/s d Uploading public origin key chef-20160614114050.pub ... ``` The `--auto-create-origins` flag creates each origin listed in the `<artifact-dir>/artifacts` directory. If you omit the `--auto-create-origins` flag, use the Chef Habitat Builder UI to create the necessary origins before running the `bulkupload` command. To finish up, return to your Chef Habitat Builder on-prem installation and view the packages that you’ve added to your `core` origin at `https://automate.example.com/bldr/#/origins/core/packages`. Using Chef Habitat Builder -------------------------- Because you are using an on-prem installation of Chef Habitat Builder, you must specify the [Builder API endpoint of your installation](index#access-chef-habitat-builder-on-prem-with-habitat-command-line-tools) when following the [Habitat Builder documentation](../../habitat/builder_overview/index). This documentation covers [using origin keys](../../habitat/builder_origins/index#origin-keys), [using origin secrets](../../habitat/builder_origins/index#origin-secrets), and [uploading and promoting packages](../../habitat/builder_origin_packages/index). Operating Chef Habitat Builder ------------------------------ Chef Habitat Builder uses the same mechanisms that Chef Automate does for [backups](../backup/index), [log management](../log_management/index), and [uninstalling](../troubleshooting/index#uninstalling-chef-automate). ### Logging errors To change the log level for Chef Habitat Builder only, create a TOML file that contains the partial configuration below. Uncomment and change settings as needed, and then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. ``` [builder_api.v1.sys.log] level = "debug" scoped_levels = ["tokio_core=error", "tokio_reactor=error", "zmq=error", "hyper=error" ] ``` Setting up Automate as an OAuth Provider for Habitat Builder (Deprecated) ------------------------------------------------------------------------- Warning These instructions have been deprecated in favor of using the Chef Automate installer to deploy Chef Habitat on-prem. To configure Chef Automate as an OAuth Provider for Chef Habitat Builder, create a TOML file with the partial configuration below. Run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. `bldr_client_id` and `bldr_client_secret` simply need to match what you configured for the corresponding values in Chef Habitat Builder (see below). However, we strongly recommend those values follow [best practices](https://www.oauth.com/oauth2-servers/client-registration/client-id-secret/) for `client_id` and `client_secret` in the Oauth2 standard. ``` [session.v1.sys.service] bldr_signin_url = "<your Builder fqdn>" # for example, "http://builder.test/" # This needs to match what you configured OAUTH_CLIENT_ID as when you configured Habitat Builder. bldr_client_id = "<your Habitat Builder Oauth2 Client ID>" # This needs to match what you configured OAUTH_CLIENT_SECRET as when you configured Habitat Builder. bldr_client_secret = "<your Habitat Builder Oauth2 Client Secret>" ``` In addition, add Chef Automate’s TLS certificate to Builder’s list of accepted certificates. Locate Chef Automate’s default self-signed certificate by running `cat /hab/svc/automate-load-balancer/data/automate.example.com.cert`, copy this default certificate, and then add it to your Builder instance’s list of accepted certificates. ``` -----BEGIN CERTIFICATE----- MIIDfDCCAmSgAcaSldKaf... -----END CERTIFICATE----- ``` If you are using a certificate signed by a trusted certificate authority instead of the default certificate, you can provide Builder with the root certificate authority for the signed certificate. For more information, check out this further explanation on how to [configure Builder to authenticate via Chef Automate](https://github.com/habitat-sh/on-prem-builder). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/on_prem_builder/Monitoring Chef Automate ======================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/monitoring.md) Use the authenticated https endpoint `/status` to monitor your Chef Automate installation. Checking the Status Endpoint ---------------------------- The authenticated endpoint `/status` provides status for the Chef Automate installation as well as for its component services. When all Chef Automate component services are up, `/status` returns a response code of 200. Otherwise, `/status` returns 500. The status of a service can be `OK`, `UNKNOWN`, or `CRITICAL`, and is shown in the JSON output: ``` { "ok": false, "service_status": [ { "service": "deployment-service", "status": "OK" }, { "service": "config-mgmt-service", "status": "UNKNOWN" }, { "service": "ingest-service", "status": "CRITICAL" }, ] } ``` To use `/status`, set up an authentication token for use with your monitoring system by following the steps below: 1. Generate a token: ``` chef-automate iam token create --id <token-id> <token-name``` 2. Create a policy that allows your created token to access the `/status` endpoint. ``` curl -k -H "api-token: <admin-token>" -d '{ "name": "Monitoring", "id": "monitoring", "members": [ "token:<token-id>" ], "statements": [ { "effect": "ALLOW", "actions": [ "system:status:get" ], "projects": [ "*" ] } ] }' -X POST https://automate.example.com/apis/iam/v2/policies?pretty ``` 3. Test that your token and policy give you access to the `/status` endpoint by running the following command: ``` curl -k -H "api-token: <token-id>" https://automate.example.com/api/v0/status?pretty ``` The output appears in the following JSON format: ``` { "ok": true, "services": [ { "name": "deployment-service", "status": "OK" }, { "name": "backup-gateway", "status": "OK" }, { "name": "automate-postgresql", "status": "OK" }, ] } ``` 4. After establishing your authentication token and confirming access, connect to the `/status` endpoint. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/monitoring/Configuration Overview ====================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/configuration.md) The `chef-automate` CLI provides commands to help you work with your existing Chef Automate configuration: * `chef-automate config show` shows your current configuration, not including default settings * `chef-automate config patch </path/to/partial-config.toml>` updates an existing Chef Automate configuration by merging the contents of`</path/to/partial-config.toml>` with your current Chef Automate configuration, and applying any changes. This command is enough in most situations * `chef-automate config set </path/to/full-config.toml>` replaces the current Chef Automate configuration with the provided configuration, and applies any changes. Use this command to replace your Chef Automate configuration Update your Chef Automate configuration by generating a section of a configuration, and applying it with `chef-automate config patch`. The rest of this document describes how to make common configuration changes. Use Cases --------- ### Minimal Configuration The `chef-automate init-config` command generates an annotated Chef Automate configuration file with the basic settings needed to deploy Chef Automate. This section describes those settings and how to change them on an existing Chef Automate installation. #### Chef Automate FQDN Your Chef Automate fully qualified domain name (FQDN) is customizable. There isn’t a maximum length for a FQDN, but the top-level domain length has a limit of 25 characters. For reference, these are the parts of a URL: ``` https://automate.4thcafe.com <scheme>://<subdomain>.<second-level domain>.<top-level domain``` To change the FQDN of your Chef Automate installation, create a TOML file that contains the partial configuration: ``` [global.v1] fqdn = "automate.example.com" ``` Then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. #### Install Channel Chef Automate consists of [Habitat](../../habitat/index) packages installed from a release channel. The default channel is `current`. #### Upgrade Strategy The upgrade strategy determines when a Chef Automate installation upgrades. The upgrade strategy settings include: * `at-once` (default) upgrades the installation after detecting new packages in the install channel * `none` freezes the installation with its current set of packages Changing the upgrade strategy from `none` to `at-once` will install the latest packages from the install channel. To change the upgrade strategy of your Chef Automate installation, create a TOML file that contains the partial configuration: ``` [deployment.v1.svc] upgrade_strategy = "at-once" ``` Then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. To upgrade a Chef Automate installation with `upgrade_strategy` set to `none`, run: ``` chef-automate upgrade run ``` This command will upgrade Chef Automate to the latest version from your install channel. #### Deployment Type Do not change `deployment_type`. The only supported `deployment_type` is `local`. #### Settings You cannot change the admin username, name, and password set during initial deployment. To change the admin password after deployment, use the Chef Automate UI. Sign in as the admin user, navigate to the *Users* page under the **Settings** tab. Select “Local Administrator” to show the admin’s *User Details* page. Navigate to the *Reset Password* tab. Enter your previous password, and enter and confirm your new password in the interface. Select the **Reset Password** button to save your changes. To change the admin password from the command-line, first [fetch the admin user record](https://docs.chef.io/automate/api/), copy the User ID, and then use: ``` export TOKEN=`chef-automate iam token create admin-token-1 --admin` curl -X PUT -H "api-token: $TOKEN" -H "Content-Type: application/json" -d '{"name":"Local Administrator", "id": "<admin user ID>", "password":"<password>"}' https://automate.example.com/api/v0/auth/users/admin?pretty ``` #### Load Balancer Certificate and Private Key To change the load balancer certificate and private key of your Chef Automate installation, create a TOML file that contains the partial configuration: ``` [[global.v1.frontend_tls]] # The TLS certificate for the load balancer frontend. cert = """-----BEGIN CERTIFICATE----- <your certificate> -----END CERTIFICATE----- """ # The TLS RSA key for the load balancer frontend. key = """-----BEGIN RSA PRIVATE KEY----- <your private key> -----END RSA PRIVATE KEY----- """ ``` Then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. #### License Key You can apply your Chef Automate license with the `chef-automate license apply` command in one of two ways: * `chef-automate license apply </path/to/license-file.jwt>` * `chef-automate license apply <content-of-license>` You cannot apply a license after your initial deployment by patching the configuration file. #### Proxy Settings You can configure Chef Automate to use a proxy either by setting environment variables, or by setting configuration options. The command `chef-automate deploy` without a configuration file will respect the proxy environment variables: * `HTTPS_PROXY`/`https_proxy` * `HTTP_PROXY`/`http_proxy` * `NO_PROXY`/`no_proxy` (See [Required Sites and Domains](#required-sites-and-domains).) Setting these environment variables before the initial deployment of Chef Automate adds them to the configuration that Chef Automate generates. If you provide a configuration file during deployment (`chef-automate deploy /path/to/config.toml`), you must specify any proxy settings in that configuration file. ``` [global.v1.proxy] host = "<your proxy host>" port = <your proxy port> no_proxy = ["0.0.0.0", "127.0.0.1"] # user = "<your proxy user>" # password = "<your proxy password>" ``` To patch the proxy settings, create a TOML file that contains the `[global.v1.proxy]` section and settings. Then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. ##### Required Sites and Domains Chef Automate must be able to access the following: * `packages.chef.io` * `licensing.chef.io` * `raw.githubusercontent.com` * `api.bintray.com` * `bldr.habitat.sh` * `akamai.bintray.com` * `dl.bintray.com` * `bintray.com` * `localhost` * `127.0.0.1` * `0.0.0.0` #### Global Log Level Configure the log level for all Chef Automate services by creating a TOML file. By default each service will initialize at the `info` level, but the following settings are available: `debug`, `info`, `warning`, `panic`, or `fatal`. ``` [global.v1.log] level = "debug" ``` Then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. #### Sample Configuration ``` # This is a default Chef Automate configuration file. You can run # 'chef-automate deploy' with this config file and it should # successfully create a new Chef Automate instance with default settings. [global.v1] # The external fully qualified domain name. # When the application is deployed you should be able to access 'https://<fqdn>/' # to login. fqdn = "chef-automate.test" # The following TLS certificate and RSA public key were # automatically generated. The certificate is a self-signed # certificate and will likely produce security warnings when you # visit Chef Automate in your web browser. We recommend using a # certificate signed by a certificate authority you trust. [[global.v1.frontend_tls]] # The TLS certificate for the load balancer frontend. cert = """-----BEGIN CERTIFICATE----- <the load balancer's certificate> -----END CERTIFICATE----- """ # The TLS RSA key for the load balancer frontend. key = """-----BEGIN RSA PRIVATE KEY----- <the load balancer's TLS RSA key> -----END RSA PRIVATE KEY----- """ # Deployment service configuration. [deployment.v1] [deployment.v1.svc] # Habitat channel to install hartifact from. # Can be 'dev', 'current', or 'acceptance' channel = "current" upgrade_strategy = "at-once" deployment_type = "local" ``` ### Additional Configuration #### General Elasticsearch Configuration To configure Elasticsearch for your Chef Automate installation, create a TOML file that contains the partial configuration below. Uncomment and change settings as needed, and then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. ``` [elasticsearch.v1.sys.proxy] # NOTE: The elasticsearch proxy settings are derived from the global proxy settings. # host = "<proxy host>" # port = <proxy port> # user = "<proxy username>" # password = "<proxy password>" # no_proxy = <["0.0.0.0", "127.0.0.1"]> [elasticsearch.v1.sys.cluster] # name = "chef-insights" [elasticsearch.v1.sys.cluster.routing.allocation] # node_concurrent_recoveries = 2 # node_initial_primaries_recoveries = 4 # same_shard_host = false [elasticsearch.v1.sys.node] # max_local_storage_nodes = 1 # master = true # data = true [elasticsearch.v1.sys.path] # logs = "logs" [elasticsearch.v1.sys.indices.recovery] # max_bytes_per_sec = "20mb" [elasticsearch.v1.sys.indices.breaker] # total_limit = "70%" # fielddata_limit = "60%" # fielddata_overhead = "1.03" # request_limit = "40%" # request_overhead = "1" [elasticsearch.v1.sys.bootstrap] # memory_lock = false [elasticsearch.v1.sys.network] # host = "0.0.0.0" # port = 10141 [elasticsearch.v1.sys.transport] # port = "10142" [elasticsearch.v1.sys.discovery] # ping_unicast_hosts = "[]" # minimum_master_nodes = 1 # zen_fd_ping_timeout = "30s" [elasticsearch.v1.sys.gateway] # expected_nodes = 0 # expected_master_nodes = 0 # expected_data_nodes = 0 [elasticsearch.v1.sys.action] # destructive_requires_name = true [elasticsearch.v1.sys.logger] # level = "info" [elasticsearch.v1.sys.runtime] # max_locked_memory = "unlimited" # es_java_opts = "" # NOTE: see https://www.elastic.co/guide/en/elasticsearch/guide/current/heap-sizing.html # for important guidance regarding the configuration of the heap size setting # heapsize = "4g" ``` #### Setting Elasticsearch Heap The Elasticsearch heap size can, and in most cases should, be set to 50% of the available system memory. However, you should review and consider the important caveats covered in the [Elasticsearch heap size documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/heap-size.html). For example, a system with 32GB of memory can have its Elasticsearch heap size set to `16g`; to do so, one would first create a TOML file that contains the partial configuration below, and then run `chef-automate config patch </path/to/your-file.toml>` to deploy the change. ``` [elasticsearch.v1.sys.runtime] heapsize = "16g" ``` #### PostgreSQL To configure PostgreSQL for your Chef Automate installation, create a TOML file that contains the partial configuration below. Uncomment and change settings as needed, with the following caveats: * These configuration settings affect only the Chef Automate-deployed PostgreSQL database. They do not affect an [externally-deployed PostgreSQL database](../install/index#configuring-an-external-postgresql-database). * Chef Automate uses TLS mutual authentication to communicate with its PostgreSQL database. Then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. ``` [postgresql.v1.sys.service] # host = "0.0.0.0" # port = 5432 [postgresql.v1.sys.pg] # md5_auth_cidr_addresses = ["0.0.0.0/0", "::0/0"] # max_wal_size = "1GB" # min_wal_size = "80MB" # wal_keep_segments = 32 # checkpoint_timeout = "5min" # checkpoint_completion_target = 0.5 # max_connections = 100 # max_locks_per_transaction = 64 [postgresql.v1.sys.logger] # level = "ERROR" [postgresql.v1.sys.superuser] # name = "automate" ``` #### Load Balancer To configure your Chef Automate installation’s load balancer, create a TOML file that contains the partial configuration below. Uncomment and change settings as needed, and then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. ``` [load_balancer.v1.sys.service] # https_port = 443 # http_port = 80 # NOTE: the external_fqdn setting is derived from the global settings and # should be configured via the `[global.v1]` setting. # external_fqdn = "<your Chef Automate fqdn>" [load_balancer.v1.sys.log] # level = "info" [load_balancer.v1.sys.ngx.main] # worker_processes = 4 # error_log = "/dev/stderr" [load_balancer.v1.sys.ngx.events] # worker_connections = 1024 # worker_processor_method = "epoll" # multi_accept = "on" [load_balancer.v1.sys.ngx.http] # access_log = "/dev/stdout" # client_max_body_size = "250m" # default_type = "application/octet-stream" # keepalive_timeout = 60 # keepalive_requests = 10000 # gzip = "on" # gzip_comp_level = "2" # gzip_disable = "MSIE [1-6]\\." # gzip_http_version = "1.0" # gzip_min_length = 10240 # gzip_proxied = "expired no-cache no-store private auth" # gzip_types = "text/plain text/css text/xml text/javascript application/x-javascript application/xml" # gzip_vary = "on" # large_client_header_buffers_size = "8k" # large_client_header_buffers_number = 4 # sendfile = "on" # ssl_ciphers = "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:!aNULL:!eNULL:!EXPORT:AES256-GCM-SHA384" # ssl_protocols = "TLSv1.2" # tcp_nodelay = "on" # tcp_nopush = "on" # enable_csp_header = false [load_balancer.v1.sys.proxy] # NOTE: The load_balancer proxy settings are derived from the global proxy settings. # host = "<proxy host>" # port = <proxy port> # user = "<proxy username>" # password = "<proxy password>" # no_proxy = <["0.0.0.0", "127.0.0.1"]> [[load_balancer.v1.sys.frontend_tls]] # NOTE: the load_balancer TLS certificate settings are derived from global # settings and should be configured via `[[global.v1.frontend_tls]]` settings # server_name = "<your Chef Automate server name>" # cert = "-----BEGIN CERTIFICATE-----\n<your load balancer cert>\n-----END CERTIFICATE-----\n" # key = "-----BEGIN RSA PRIVATE KEY-----\n<your load balancer private key>\n-----END RSA PRIVATE KEY-----\n" ``` #### Buffer Size Configure message buffer ingest size: ``` [compliance.v1.sys.service] message_buffer_size = 200 [ingest.v1.sys.service] message_buffer_size = 200 ``` #### Compliance Configuration To configure your Chef Automate InSpec agent scans, create a TOML file that contains the partial configuration below. Uncomment and change settings as needed, and then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. ``` [compliance.v1.sys.agent] ## Max number of inspec workers to run in parallel for detect and scan jobs. Default: 10 # workers = 20 ## Max number of detect and scan jobs that can be accepted in the jobs workers queue. Default: 1000 # buffer_size = 2000 ## Option to specify the version of inspec to use for remote(e.g. AWS SSM) scan jobs # remote_inspec_version = "4.3.2" ## A control result message that exceeds this character limit will be truncated. Default: 10000 # result_message_limit = 20000 ## The array of results per control will be truncated at this limit to avoid large reports that cannot be processed. Default: 50 # control_results_limit = 100 ## Control results that have a `run_time` (in seconds) below this limit will be stripped of the `start_time` and `run_time` fields. Default: 1.0 # run_time_limit = 0.5 ``` #### Configure Inflight Data Collector Request Maximum You can specify the maximum number of inflight data collector requests. The default value is sixty times the number of the machine’s available CPUs. ``` [gateway.v1.sys.data_collector.limiter] # Setting disable to true will allow an unbounded number of # data collector requests to remain inflight concurrently. disable = false # max_inflight_requests will set the maximum number of # concurrent inflight data collector requests. By default, # this value is 60 * runtime.CpuCount() max_inflight_requests = 100 ``` #### Sign-out on Browser Close Configuration to sign out users from Chef Automate when they close the browser. ``` [session.v1.sys.service] # Setting persistent to false will disable persistent sessions. # Users will be signed out when their browser closes. persistent = false ``` #### Disclosure Banner Configuration to display a custom banner on every Chef Automate page, including the sign-in page. Default: `false`. ``` [global.v1] [global.v1.banner] show = true # Set 'show' to 'true' to enable the banner. Set to 'false' to disable the banner. Default: false. message = "Lorem ipsum dolor sit amet" # Add the Message for the banner background_color = "3864f2" # Set the background color using the Hex Color Code (Do not add # to the code) text_color = "FFF" # Set the color of the text using the Hex Color Code (Do not add # to the code) # Find valid HEX codes at https://htmlcolorcodes.com/ ``` #### Disclosure Panel Configuration to display a disclosure on the sign-in page. Requires a `.txt` or `.html` message stored in a location accessible to Chef Automate. Default: `false`. ``` [global.v1] [global.v1.disclosure] show = true # Set 'show' to 'true' to enable the disclosure panel on the sign in page. Set to 'false' to disable the disclosure panel. Default: false. message_file_path = "/src/dev/disclosure-panel-message.txt" # The location of the file containing the disclosure panel message. # Validate your HTML at https://validator.w3.org/ ``` ### Content Security Policy Header Content-Security-Policy is the name of a HTTP response header that modern browsers use to enhance the security of the document (or web page). The Content-Security-Policy header allows you to restrict how resources such as JavaScript, CSS, or pretty much anything that the browser loads. Refer: <https://owasp.org/www-community/controls/Content_Security_Policy Content Security Policy header can be enabled in Automate by patching the following configuration ``` [load_balancer.v1.sys.ngx.http] enable_csp_header = true ``` Warning Enabling CSP header may break the SAML login. This may happen if the IDP Login page has inline javascripts which CSP header prevents from getting evaluated by default. ### Troubleshooting Common syntax errors may cause issues in configuration files: * Keys: Names use underscores, not dashes. * Ports: Use the correct type. Single numbers are integers and don’t need quotation marks. Ranges are strings and require quotation marks. * Whitespace: Both tabs and spaces are whitespace. * Arrays: Use square brackets with comma-separated entries of the same type. See the [TOML README](https://github.com/BurntSushi/toml-1) for more details. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/configuration/Backup ====== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/backup.md) Backups are crucial for protecting your data from catastrophic loss and preparing a recovery procedure. The `chef-automate backup create` command creates a single backup that contains data for all products deployed with Chef Automate, including [Chef Infra Server](../infra_server/index) and [Chef Habitat Builder on-prem](../on_prem_builder/index). By default, Chef Automate stores backups to the filesystem in the directory `/var/opt/chef-automate/backups`. You can also configure Chef Automate to store backups in AWS S3 buckets or in Google Cloud Storage (GCS) buckets. After configuring your backups, see how to [restore](../restore/index) a Chef Automate installation. Backup Space Requirements ------------------------- This amount of space needed for a backup varies depending on your Chef Automate use. You need enough free space for: * Complete copies of each Chef Automate service PostgreSQL database * Complete copies of your configuration files * Elasticsearch snapshots of your Chef Automate configuration and data, such as converge, scan, and report data. You will need enough disk space for the each Elasticsearch snapshot and the delta–or the list of changes–for each successive snapshot * Chef Habitat Builder artifacts Backup to a Filesystem ---------------------- To store backups in a configurable backup directory, the backup directory should be on network-attached storage or synced periodically to a disk on another machine. This best practice ensures that you can restore from your backup data during a hardware failure. The default backup directory is `/var/opt/chef-automate/backups`. If it does not exist, the deployment process creates it. To configure your Chef Automate installation’s backup directory to another location: 1. Create a `backup_config.toml` file in your current directory with the following content. Replace `/path/to/backups` with the path to your backup directory: ``` [global.v1.backups.filesystem] path = "/path/to/backups" ``` 2. Run the following command to apply your configuration: ``` chef-automate config patch backup_config.toml ``` 3. Remove the now-redundant `backup_config.toml` file. ### Store a Filesystem Backup in a Single-file Archive To store backups offline in single-file archives, single-file archives must include both the configuration data and the reporting data contained in the standard backup. The [configured backup directory](index#backup-to-a-filesystem) contains both the timestamp-based directory for the configuration and the reporting data stored in the `automate-elasticsearch-data` directory. A timestamp-based directory has a date-based name, such as `20180518010336`, in the `automate-elasticsearch-data` directory. To provide externally-deployed Elasticsearch nodes access to Chef Automate’s built-in backup storage services, you must [configure Elasticsearch backup](../install/index#configuring-external-elasticsearch) settings separately from Chef Automate’s primary backup settings. Backup to AWS S3 ---------------- To store backups in an existing AWS S3 bucket, use the supported S3-related settings below: ``` [global.v1.backups] location = "s3" [global.v1.backups.s3.bucket] # name (required): The name of the bucket name = "<bucket name>" # endpoint (required): The endpoint for the region the bucket lives in. # See https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region endpoint = "https://<region endpoint>" # base_path (optional): The path within the bucket where backups should be stored # If base_path is not set, backups will be stored at the root of the bucket. base_path = "<base path>" [global.v1.backups.s3.credentials] # Optionally, AWS credentials may be provided. If these are not provided, IAM instance # credentials will be used. It's also possible for these to be read through the standard # AWS environment variables or through the shared AWS config files. access_key = "<access_key>" secret_key = "<secret_key>" session_key = "<session_key>" [global.v1.backups.s3.ssl] # root_cert (optional): The root certificate used for SSL validation. # For S3 compatible APIs, you can set the SSL root cert if needed root_cert = """ -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- ``` See how to [restore from AWS S3](../restore/index#restore-from-an-aws-s3-backup). ### AWS S3 Permissions The following IAM policy describes the basic permissions Chef Automate requires to run backup and restore operations. ``` { "Statement": [ { "Action": [ "s3:ListBucket", "s3:GetBucketLocation", "s3:ListBucketMultipartUploads", "s3:ListBucketVersions" ], "Effect": "Allow", "Resource": [ "arn:aws:s3:::automate-backups.example.com" ] }, { "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts" ], "Effect": "Allow", "Resource": [ "arn:aws:s3:::automate-examples.example.com/*" ] } ], "Version": "2012-10-17" } ``` Backup to GCS ------------- To store backups in an existing Google Cloud Storage (GCS) bucket, [generate a service account key](https://cloud.google.com/iam/docs/creating-managing-service-account-keys) with the `storage.admin` permission for the associated project and GCS bucket, and use the supported GCS-related settings below: ``` [global.v1.backups] location = "gcs" [global.v1.backups.gcs.bucket] # name (required): The name of the bucket name = "<bucket name>" # base_path (optional): The path within the bucket where backups should be stored. # If base_path is not set, backups will be stored at the root of the bucket. base_path = "<base path>" [global.v1.backups.gcs.credentials] # This is the JSON credentials file you generate during service account # creation, you must copy/paste the entire contents here (this is just an example) json = ''' { "type": "service_account", "project_id": "my-favorite-project", "private_key_id": "<KEY>", "private_key": "<KEY>", "client_email": "<EMAIL>", "client_id": "XXXXXXXXXXXXXXXXXXXXX", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/chef%40my-favorite-project.iam.gserviceaccount.com" } ''' ``` See how to [restore from GCS](../restore/index#restore-from-a-google-cloud-storage-backup). Backup Commands --------------- ### Create a Backup Make a backup with the [`backup create`](../cli_chef_automate/index#chef-automate-backup-create) command: ``` chef-automate backup create ``` The output shows the backup progress for each service. A successful backup displays a success message containing the timestamp of the backup: ``` Success: Created backup 20180518010336 ``` Restores from a filesystem backup may fail with incorrect directory permissions. Run the [`fix-repo-permissions` command](../cli_chef_automate/index#chef-automate-backup-fix-repo-permissions) to address such issues: ``` sudo chef-automate backup fix-repo-permissions <path``` ### List Backups You can list existing backups with the [`backup list`](../cli_chef_automate/index#chef-automate-backup-list) command: ``` chef-automate backup list ``` The output shows each backup and its age: ``` Backup State Age 20180508201548 completed 8 minutes old 20180508201643 completed 8 minutes old 20180508201952 completed 4 minutes old ``` By default, this command communicates with your running Chef Automate installation to list the backups. If the Chef Automate installation is down, you can still list the backups. To list filesystem backups: ``` chef-automate backup list /var/opt/chef-automate/backups Listing backups from local directory /var/opt/chef-automate/backups Backup State Age 20180508201548 completed 12 minutes old 20180508201643 completed 11 minutes old 20180508201952 completed 8 minutes old ``` For backups stored in an AWS S3 bucket, use: ``` chef-automate backup list s3://bucket_name/base_path ``` where `bucket_name` is the name of the S3 bucket and `base_path` is an optional path within the bucket where the backups live. For backups stored in a Google Cloud Storage (GCS) bucket, use: ``` chef-automate backup list gs://bucket_name/base_path ``` where `bucket_name` is the name of the GCS bucket and `base_path` is an optional path within the bucket where the backups live. Delete Backups -------------- To delete backups from a running instance of Chef Automate, first find the relevant backup ID with `chef-automate backup list` and then delete the backup using [`chef automate backup delete ID`](../cli_chef_automate/index#chef-automate-backup-delete). ``` chef-automate backup list Backup State Age 20181026183901 completed 1 minute old 20181026183954 completed 33 seconds old 20181026184012 completed 15 seconds old ``` Delete a single backup with `chef-automate backup delete`: ``` chef-automate backup delete 20181026183901 The following backups will be permanently deleted: 20181026183901 Are you sure you want to continue? (y/n) y Success: Backups deleted ``` To delete two or more backups, use `chef-automate backup delete` followed by the backup IDs: ``` chef-automate backup delete 20181026183954 20181026184012 The following backups will be permanently deleted: 20181026183954 20181026184012 Are you sure you want to continue? (y/n) y Success: Backups deleted ``` To prune all but a certain number of the most recent backups manually, parse the output of `chef-automate backup list` and apply the command `chef-automate backup delete`. For example: ``` export KEEP=10; chef-automate backup list --result-json backup.json > /dev/null && jq "[.result.backups[].id] | sort | reverse | .[]" -rM backup.json | tail -n +$(($KEEP+1)) | xargs -L1 -i chef-automate backup delete --yes {} ``` Troubleshooting --------------- To debug a failed backup, set the log level to `debug` and re-run the backup. This outputs the debug information to the Chef Automate log: ``` chef-automate debug set-log-level deployment-service debug ``` References ---------- See the [`chef-automate backup` command reference](../cli_chef_automate/index#chef-automate-backup). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/backup/Migrate from Chef Automate 1 ============================ [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/migrate.md) Chef Automate versions 1.0.0-1.8.96 reached end-of-life on December 31, 2019 and are no longer supported. For more information and for help upgrading your system, please contact your Chef account representative. The current Chef Automate versions includes significant architectural and technical improvements to the core product platform. This guide shows you how to migrate your existing Chef Automate installation to the current Chef Automate. In this guide, we call Chef Automate versions 1.0.0-1.8.96 “Chef Automate 1” and the current version “Chef Automate 2”. Overview -------- The Chef Automate migration process performs the following steps, in order: 1. Runs preflight checks to ensure the system is suitable for Chef Automate 2, your Chef Automate 1 installation can be migrated safely, and that the upgrade process will be able to migrate your data. 2. Analyzes your Chef Automate 1 configuration files and migrates the relevant settings to a configuration file for Chef Automate 2. If incompatibilities are detected, the migration process fails and emits a description of the problem. You will have an opportunity to make any necessary changes to the generated Chef Automate 2 configuration. 3. Downloads Chef Automate 2. Chef Automate 2 is distributed via [Habitat](../../habitat/index) packages that are installed early in the process to minimize the downtime required for the migration. 4. Puts your Chef Automate 1 installation into maintenance mode, waits for queued data to be processed, and then backs up all Chef Automate 1 data. This ensures that data will not be lost in the migration process and that you will be able to recover to a working state should an unforeseen error occur. 5. Creates a local snapshot of Chef Automate 1 data for import into Chef Automate 2. 6. Shuts down Chef Automate 1. 7. Imports the Chef Automate 1 snapshot into Chef Automate 2. 8. Starts Chef Automate 2. On startup, each component service of Chef Automate 2 detects imported data. Once all component services perform this step, Chef Automate 2 is ready to use and can accept new data. 9. Migrates imported historical data in the background. You will be notified when the migration completes. Warning Chef Automate 2 migrates only the LDAP configuration and local users (also referred to as “internal users”). SAML configuration is not migrated. Prerequisites ------------- Before you start the migration process, fulfill the requirements detailed in this section. ### Command Line Tool You will need the `chef-automate` command line tool to initiate your upgrade. 1. Download the latest version of the Chef Automate CLI: ``` wget https://packages.chef.io/files/current/automate/latest/chef-automate_linux_amd64.zip ``` 2. Unzip the package: ``` unzip chef-automate_linux_amd64.zip ``` 3. Move the unzipped `chef-automate` binary to `/usr/local/bin`: ``` mv chef-automate /usr/local/bin ``` ### Internet Access The Chef Automate upgrade process requires connectivity to the internet to install the Chef Automate 2 binaries. The standard Chef Automate installation requires current versions for Chrome, Edge, or Firefox browsers. If you filter internet access via proxy or by other means, you must ensure the following domains are accessible: * `packages.chef.io` * `licensing.chef.io` * `raw.githubusercontent.com` * `api.bintray.com` * `bldr.habitat.sh` * `akamai.bintray.com` * `dl.bintray.com` * `bintray.com` #### Proxies The Chef Automate 2 installer respects the following environment variables: * `HTTPS_PROXY`/`https_proxy` * `HTTP_PROXY`/`http_proxy` * `NO_PROXY`/`no_proxy` If you use a proxy to manage outbound HTTP(S) connections, ensure these variables are set when running the migration. ### Chef Automate 1 Version Recent versions of Chef Automate 1 contain enhancements that the migration process relies upon to ensure your data is safely migrated. Chef Automate 1.8.38 or greater is required. ### Systemd Chef Automate 2 requires the systemd init system. If you’re using Chef Automate 1 on an operating system that makes use of a different init system, we recommend consulting Customer Support for the appropriate migration strategy. Considerations -------------- While we’ve taken care to make the migration process as smooth as possible, this section outlines some caveats to consider before you proceed. ### Plan for Downtime The Chef Automate 2 migration process puts your Chef Automate 1 installation into maintenance mode, shuts it down, and starts Chef Automate 2. During the downtime, the migration process takes a backup of your Chef Automate 1 data and exports some of its data to a local snapshot, which is imported into Chef Automate 2. To minimize this downtime, we recommended that you create an online backup of Chef Automate 1 just prior to the upgrade. Historical information such as Chef Infra Client run data and compliance scan data is backed up incrementally, which means that the upgrade only needs to transfer data that has been added since the last backup. By default, the Chef Automate 2 upgrade process will not proceed if your Chef Automate 1 installation does not have backups configured. Invoke the migration using the `--skip-backup-check` flag to avoid this check. ### Unsupported Features and Topologies Chef Automate 2 includes significant architectural and technical improvements to the core product platform. If you rely on any of the capabilities listed below, we recommend you continue to using your existing Chef Automate installation. * **Chef Manage:** Chef Automate 2, unlike Chef Automate 1, cannot serve as a SAML auth proxy * **FIPS:** Chef Automate 2 cannot operate in FIPS mode * **Disaster Recovery:** Chef Automate 2 cannot operate in a primary/standby mode * **Custom Kibana dashboards:** Chef Automate 2 does not include Kibana in its technology stack * **SAML config migration:** Chef Automate 2 supports SAML integration, however due to configuration incompatibilities Chef Automate 2 cannot migrate Chef Automate 1 SAML settings to Chef Automate 2 as part of the upgrade. After the upgrade is completed, you may follow [these configuration instructions](../configuration/index#saml) to set up SAML. To migrate to Chef Automate 2 without these features, invoke the migration with the appropriate flags: * `--skip-fips-check` * `--skip-disaster-recovery-check` * `--skip-saml-check` These flags enable you to migrate by skipping preflight checks for unsupported features. ### External Elasticsearch cluster The Chef Automate 2 migration process requires manual intervention to migrate a Chef Automate 1 installation that uses external Elasticsearch. To migrate an external Elasticsearch cluster, please reach out to a Customer Success or Customer Support representative for assistance. ### New Data Paths Chef Automate 2 stores its data in directories named `/hab/svc/$service-name/data`. In particular: * Elasticsearch data is stored in `/hab/svc/automate-elasticsearch/data/` * PostgreSQL data is stored in `/hab/svc/automate-postgresql/data/` If you use dedicated disks or partitions for either of these applications in Chef Automate 1, you must modify your disk mount configuration to make these disks/partitions available to Chef Automate 2. ### Chef Automate 2 License Login to Chef Automate to start a trial. The trial provides you with a 60-day license. Requesting a trial license requires internet connectivity in your Chef Automate 2 instance (only at the time of the license request). If you are migrating an [airgapped Chef Automate installation](../../install_chef_air_gap/index#chef-automate), contact your Chef account representative for a Chef Automate 2 license. Migrate ------- 1. Create a backup your Chef Automate 1 installation: ``` automate-ctl create-backup ``` 2. Once the backup has completed, initiate the migration process. If your host is internet-connected, run the command: ``` ./chef-automate migrate-from-v1 --channel current ``` If your host is airgapped, run the command: ``` ./chef-automate migrate-from-v1 --airgap-bundle </path/to/bundle``` After the migration runs the preflight checks and analyzes your Chef Automate 1 configuration, it asks for confirmation to continue. Review the generated configuration file and if it is correct, type `yes` to continue. The migration process backs up your Chef Automate 1 data, shuts down Chef Automate 1, imports your data to Chef Automate 2, then starts Chef Automate 2. At this point, you can use your existing Chef Automate 1 user credentials to login to Chef Automate 2. If you’ve been using LDAP for authenticating users, that configuration will have been migrated as well, and you can use your LDAP credentials to login. Historical data will be migrated in the background. ### Upgrades Chef Automate 2 handles upgrades differently than Chef Automate 1 did. The [Installation](../install/index#upgrade) documentation and [Airgapped Installation](../airgapped_installation/index#upgrade) documentation provide further detail. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/migrate/LDAP ==== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/ldap.md) Authentication via Existing Identity Management Systems ------------------------------------------------------- Chef Automate can integrate with existing LDAP services to authenticate users in Chef Automate, and thus use their existing group memberships to determine their Chef Automate permissions. Chef Automate supports using both local users and externally managed users from an external identity provider (IdP). Both *one* LDAP service (or MSAD for simplified configuration of Active Directory setups) and *one* SAML IdP can be used. You do not need to configure an external IdP if you simply want to create users and teams local to Chef Automate. See the [Users](../users/index) documentation for additional information. Chef Automate uses [Dex](https://github.com/dexidp/dex) to support LDAP integrations. To configure authentication for your Chef Automate installation, create a TOML file that contains the partial LDAP configuration. Then run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. Warning You may only integrate one IdP using SAML and one IdP using LDAP at a time. Chef Automate does not support using *two* SAML IdPs or *two* LDAP services simultaneously. Switching between a Microsoft AD configuration and generic LDAP configuration will not affect your policies, as they are both LDAP configurations. However, switching between either of those configurations and a SAML configuration will require you to adjust the [IAM](../iam_v2_overview/index) policy membership. Note Local, MSAD, and LDAP users will have their Chef Automate sessions refreshed while their Chef Automate browser window remains open or until they sign out directly. Supported Identity Management Systems ------------------------------------- * Azure Active Directory * Microsoft Active Directory (MSAD) Overview -------- This is documentation for configuring Chef Automate’s Lightweight Directory Application Protocol (LDAP) and Microsoft Active Directory (MSAD) integrations. LDAP is an established and open standard protocol for interacting with directory servers. A directory server stores information–in this case information for authenticating and authorizing users–in a tree of entries. (It is not a relational database.) Microsoft Active Directory -------------------------- Microsoft Active Directory (MSAD) is a type of directory server that supports LDAP. Chef Automate comes with a default LDAP configuration for MSAD. The Chef Automate default MSAD configuration is a minimal configuration for standard MSAD systems, which you can extend by overriding default values and using additional configuration options. Chef Automate’s default configuration for Microsoft AD is specific to LDAP. To configure Microsoft AD using SAML, see the [SAML documentation](../saml/index). Changing Chef Automate Configuration ------------------------------------ If you need to change your configured external identity provider settings, replace your existing configuration by following these steps: 1. Run `chef-automate config show config.toml`. 2. Edit `config.toml` to replace the `dex.v1.sys.connectors` section with the configuration values for your new identity provider. 3. Run `chef-automate config set config.toml` to set your updated configuration. ### Minimal MSAD Configuration base_user_search_dn “your base user search DN” base_group_search_dn “your base group search DN” bind_dn “your bind_dn” bind_password “your bind_password” `bind_password` may also be passed via the `AUTOMATE_SECRET_MSAD_PASSWORD` environment variable when running `chef-automate` commands. ca_contents Your certificate authority (CA) certificate contents. You can provide multiple PEM-encoded CA certs. Optional. ``` # Example ca_contents setting: ca_contents = """-----BEGIN CERTIFICATE----- MIICsDCCAhmgAwIBAgIJAJxMopMJbhPkMA0GCSqGSIb ... X0uRzUPlpTtd5tYFs43nKqxJT6s= -----END CERTIFICATE-----""" ``` host The domain name of your directory server, for example `"ldap.corp.com"`. Default port: `636`. Override the port by appending it to the host setting, `"ldap.corp.com:10636"` #### Minimal MSAD config.toml ``` [dex.v1.sys.connectors.msad_ldap] host = "<your host>" bind_dn = "<your bind_dn>" bind_password = "<your bind_password>" base_user_search_dn = "<your base user search DN>" base_group_search_dn = "<your base group search DN>" ca_contents = "<your ca contents>" # optional, but recommended ``` ### Full MSAD Configuration The MSAD configuration is an LDAP configuration with more provided default values that are commonly a good fit for Active Directory. Override any single default value by uncommenting it in the configuration and setting its value: email_attr “mail” filter_groups_by_user_attr “member” filter_groups_by_user_value “DN” group_query_filter “(objectClass=group)” group_display_name_attr “displayName” insecure_no_ssl false Warning Connecting to an LDAP service without TLS is not recommended. user_display_name_attr “displayName” user_id_attr “sAMAccountName” user_query_filter “(objectClass=person)” username_attr “sAMAccountName” #### Example Full MSAD config.toml ``` [dex.v1.sys.connectors.msad_ldap] host = "<your host>" bind_dn = "<your bind_dn>" bind_password = "<your bind_password>" base_user_search_dn = "<your base user search DN>" base_group_search_dn = "<your base group search DN>" ca_contents = "<your ca contents>" # optional # MSAD default values (uncomment to override a specific one) # insecure_no_ssl = false # user_query_filter = "(objectClass=person)" # user_id_attr = "sAMAccountName" # username_attr = "sAMAccountName" # email_attr = "mail" # user_display_name_attr = "displayName" # group_query_filter = "(objectClass=group)" # filter_groups_by_user_value = "DN" # filter_groups_by_user_attr = "member" # group_display_name_attr = "displayName" ``` Extended LDAP Settings ---------------------- For those who do not use Microsoft AD or require greater control over their configuration, Chef Automate has the following customizable LDAP configuration settings: base_group_search_dn “your base group search DN” base_user_search_dn “your base user search DN” bind_dn “your bind_dn” bind_password “your bind_password” ca_contents “your ca contents” email_attr “your email attribute” filter_groups_by_user_attr “groups to filter by user attribute” filter_groups_by_user_value “groups to filter by user value” group_display_name_attr “group display name attribute” group_query_filter “your group query filter” host “your host” insecure_no_ssl :true or false user_query_filter “your user query filter” username_attr “your username attribute” user_id_attr “your userid attribute” user_display_name_attr “your user display name attribute” ### Example Extended LDAP config.toml ``` [dex.v1.sys.connectors.ldap] # authentication options ca_contents = "<your ca contents>" host = "<your host>" bind_dn = "<your bind_dn>" bind_password = "<your bind_password>" insecure_no_ssl = true or false # ldapsearch options base_user_search_dn = "<your base user search DN>" user_query_filter = "<your user query filter>" username_attr = "<your username attribute>" user_id_attr = "<your userid attribute>" email_attr = "<your email attribute>" user_display_name_attr = "<your user display name attribute>" base_group_search_dn = "<your base group search DN>" group_query_filter = "<your group query filter>" filter_groups_by_user_attr = "<groups to filter by user attribute>" filter_groups_by_user_value = "<groups to filter by user value>" group_display_name_attr = "<group display name attribute>" ``` See the [LDAP](index) for more information on configuration fields. You have the full extent of TOML is at your disposal for declaring configuration fields. Warning Connecting to an LDAP service without TLS is not recommended. However, if you wish to integrate with an LDAP server with TLS disabled: ``` insecure_no_ssl = true ``` ### Sign In with LDAP Once the user has provided a username and password at the sign in screen, Chef Automate goes through a sequence of operations to complete the sign in: 1. [Connect](#connect) 2. [Bind](#bind) 3. [User Search](#user-search) 4. [Sign in Bind](#signin-bind) 5. [Group Search](#group-search) #### Authorization with LDAP Chef Automate supports defining permissions for LDAP users and their groups. See [IAM members and policies](../iam_v2_overview/index#members-and-policies). #### Connect Chef Automate first needs to establish a TCP connection to your LDAP service, secured by TLS. It will connect to the host configured in your TOML configuration, for example: ``` host = "ldap.corp.com" ``` Automate uses port `636` by default. To override the port, append it to the host setting, e.g. ``` host = "ldap.corp.com:10636" ``` Whether the validity of the server’s TLS certificate will be enforced depends on the TLS setup: if you provide a certificate authority’s (CA) certificate(s), Chef Automate will only communicate with the LDAP service if the certificate provided by the host can be validated using the CA certificate(s). Warning Connecting to an LDAP service without TLS is not recommended. However, if you wish to integrate with an LDAP server with TLS disabled: ``` insecure_no_ssl = true ``` See [Troubleshoot your Connection](#troubleshoot-your-connection) for common issues related to *Connect*. #### Bind Chef Automate then authenticates with (or “binds to”) the LDAP service using *bind credentials*. In your configuration TOML file, these would be (for example): ``` bind_dn = "cn=service_account,dc=corp,dc=com" bind_password = "i<3ldap" ``` If your LDAP server supports *anonymous bind*, and you want to use that, unset both bind DN and password: ``` bind_dn = "" bind_password = "" ``` Wrap special characters in a bind_password in triple single quotes. ``` bind_password = '''$p3c"i'@l ! %#''' ``` See [Troubleshoot Bind](#troubleshoot-bind) for common issues related to *Bind*. #### User Search After binding successfully, Chef Automate will try to obtain the directory name of the user that is trying to sign in. To do so, it will search, using the configured *base* `base_user_search_dn`, for an entry such that `username_attr` equals the username that attempted to sign in. If configured, it will retrieve additional attributes, using the configured names (`user_id_attr`, `email_attr`, and `user_display_name_attr`). See [Configuration: LDAP](../configuration/index#ldap) for an overview. Note The `ldapsearch` command line corresponding to *User Search* is ``` ldapsearch -h $host -D $bind_dn -w $bind_password \ -s sub \ -b $base_user_search_dn \ "($username_attr=$username)" \ $user_id_attr $user_display_name_attr $email_attr ``` where `username` is what was typed into the **username input box** in the Sign in form. Warning If the LDAP search fails to retrieve the configured attributes, the sign in process will fail. See [Troubleshoot User Search](#troubleshoot-user-search) for common issues related to *User Search*. ##### Filtering Which Users Can Sign In You can further restrict the user search by providing a valid LDAP filter to `user_query_filter`. For example, ``` user_query_filter = "(objectClass=person)" ``` which will be concatenated with the search filter constructed from the provided username in the sign in screen. The contents of `user_query_filter` gets expanded to `(&<user_query_filter_value>)` so you can pass in multiple filters. For example, if you wanted to only allow people that were members of a specific Active Directory group to sign in to Chef Automate, you could define a `user_query_filter` with multiple filters like: ``` user_query_filter = "(objectClass=person)(memberof=CN=YourGroupToFilterOn,OU=Users,DC=YourDomain,DC=com)" ``` This filter says “only allow people who are members of YourGroupToFilterOn to sign in to Chef Automate”. When a user tries to sign in, they would only be authorized if they were found after the filter is applied: ``` (&(objectClass=person)(memberof=CN=YourGroupToFilterOn,OU=Users,DC=YourDomain,DC=com)) ``` Note The `ldapsearch` command line corresponding to *User Search* with restricted groups is ``` ldapsearch -h $host -D $bind_dn -w $bind_password \ -s sub \ -b $base_user_search_dn \ "(&$user_query_filter($username_attr=$username))" ``` where `username` is what was typed into the username input box in the Sign in form. See [`ldapsearch` Example Queries](#ldapsearch-example-queries) for an example on using `ldapsearch`, and different directory layouts. #### Sign In Bind When the search for a user directory entry has succeeded, the LDAP connector will attempt to bind as the user entry, using the supplied password. For example, if the sign in using `jane:janespassword` has resulted in a successful user search, returning `cn=jane,ou=People,dc=corp,dc=com`, the next step will be to *bind again* using that DN, and the password `janespassword`. Note The `ldapsearch` command line corresponding to *User Search* is ``` ldapsearch -h $host -D $user_dn -w $password ``` where `user_dn` is the DN of the user that was returned in [User Search](#user-search), and `password` is what was typed into the **password input box** in the Sign in form. Note that `result: 32 No such object` is the successful response here, a failed sign in bind using `ldapsearch` returns: ``` ldap_bind: Invalid credentials (49) additional info: INVALID_CREDENTIALS: Bind failed: Cannot authenticate user uid=test2,ou=users,ou=system ``` See [Troubleshoot Sign In Bind](#troubleshoot-sign-in-bind) for common issues related to *Sign_In_Bind*. #### Group Search Finally, after the user has been authenticated, their internal record is enriched with LDAP-provided groups. This happens by executing another search using the same bind DN and password that was used for user search. Similar to user search, a base DN has to be provided; and the result can be restricted by providing an additional filter: ``` base_group_search_dn = "ou=Groups,dc=corp,dc=com" group_query_filter = "(objectClass=group)" ``` The correct configuration settings again depend on your directory server’s schema; see the example configs below. Warning The `base_group_search_dn` setting is optional. However, if it is not provided, users authenticating via LDAP (or MSAD) will not be members of any teams. Note The `ldapsearch` command line corresponding to *Group Search* is ``` ldapsearch -h $host -D $bind_dn -w $bind_password \ -s sub \ -b $base_group_search_dn \ "($filter_groups_by_user_attr=$user_attr)" \ $group_display_name_attr ``` where `user_attr` is the `$filter_groups_by_user_value` of the user that was returned in [User Search](#user-search). See [Troubleshoot Group Search](#troubleshoot-group-search) for common issues related to *Group Search*. #### Configuration Overview See below for the full configuration and additional details about all LDAP configuration options. ``` [dex.v1.sys.connectors.ldap] ### # Configuration for querying your LDAP server ### ca_contents = "<your ca contents>" host = "<your host>" # The DN and password you wish to bind to your LDAP server to search for # users to authenticate for Chef Automate (and also to search for their group membership). # Example: "uid=seviceaccount,cn=users,dc=example,dc=com" bind_dn = "<your bind_dn>" # bind_password may also be passed via the AUTOMATE_SECRET_LDAP_PASSWORD environment # variable when running `chef-automate` commands. bind_password = "<your bind_password>" ### # User Query (search for LDAP users to authenticate for Chef Automate) ### # The base DN to start the user query. # Chef Automate will use this as the base DN on which to search for users to authenticate against your LDAP server. # Example: "cn=users,dc=example,dc=com" base_user_search_dn = "<your base user search DN>" # The LDAP field used to filter the query for users to authenticate for Chef Automate. # Example: Setting this to "uid" would result in a filter of "(uid=<username_for_user_trying_to_authenticate>)". username_attr = "<your username attribute>" # Optional: LDAP query filter to apply when searching for users to authenticate. # This will be combined with username_attr filter above. # Example: Setting this to "(objectClass=person)" will filter on human actors only. user_query_filter = "<your user query filter>" ### # Populating the Chef Automate User via LDAP ### # Determines which LDAP field populates the username in a user's Chef Automate session on successful authentication. user_id_attr = "<your userid attribute>" # Optional: determines which LDAP field populates the email in a user's Chef Automate session on successful authentication. # Defaults to "user_id_attr" if not specified. email_attr = "<your email attribute>" # Optional: determines which LDAP field populates the display name in a user's Chef Automate session on successful authentication. # Defaults to "name" if not specified. user_display_name_attr = "<your user display name attribute>" ### # Group Query (search for LDAP group membership for an authenticated user) ### # The base DN to start the group membership query. # Chef Automate will use this as the base DN on which to search for LDAP group membership for a specific LDAP user. # Example: "cn=groups,dc=freeipa,dc=example,dc=com" base_group_search_dn = "<your base group search DN>" # The following two fields are used to match a user to a group. # If the defaults are used, then you end up with a group membership # filter of "(&(objectClass=group)(member=<user's DN>))". # Optional: The LDAP field by which you wish to filter group membership. # Defaults to "member". filter_groups_by_user_attr = "<groups to filter by user attribute>" # Optional: The LDAP field from the authenticated user you wish to use as input to the above filter. # Defaults to "DN". filter_groups_by_user_value = "<groups to filter by user value>" # Optional: Additional LDAP filter you can define to further filter group membership results. group_query_filter = "<your group query filter>" # The LDAP field on the group you wish to use as the Chef Automate Team name for the group. # Defaults to "name". group_display_name_attr = "<group display name attribute>" ``` ##### Example Configs Depending on your directory’s schema, different Group Search settings are required: If your directory looks like this ``` dn: dc=corp,dc=com objectClass: dcObject objectClass: organization o: Example Company dc: corp dn: ou=People,dc=corp,dc=com objectClass: organizationalUnit ou: People dn: cn=jane,ou=People,dc=corp,dc=com objectClass: person objectClass: inetOrgPerson sn: doe cn: jane dn: cn=john,ou=People,dc=corp,dc=com objectClass: person objectClass: inetOrgPerson sn: doe cn: john # Groups dn: ou=Groups,dc=corp,dc=com objectClass: organizationalUnit ou: Groups dn: cn=admins,ou=Groups,dc=corp,dc=com objectClass: groupOfNames cn: admins member: cn=john,ou=People,dc=corp,dc=com member: cn=jane,ou=People,dc=corp,dc=com dn: cn=developers,ou=Groups,dc=corp,dc=com objectClass: groupOfNames cn: developers member: cn=jane,ou=People,dc=corp,dc=com ``` then the following would be required: ``` base_user_search = "ou=People,dc=corp,dc=com" username_attr = "cn" user_id_attr = "cn" user_display_name_attr = "cn" base_group_search = "ou=Groups,dc=corp,dc=com" filter_groups_by_user_value = "DN" filter_groups_by_user_attr = "member" # default group_display_name_attr = "cn" ``` However, if your schema looks like this – with no list of members in your group entries: ``` dn: dc=corp,dc=com objectClass: dcObject objectClass: organization o: Example Company dc: corp dn: ou=People,dc=corp,dc=com objectClass: organizationalUnit ou: People dn: cn=jane,ou=People,dc=corp,dc=com objectClass: person objectClass: inetOrgPerson sn: doe cn: jane departmentNumber: 1000 departmentNumber: 1001 dn: cn=john,ou=People,dc=corp,dc=com objectClass: person objectClass: inetOrgPerson sn: doe cn: john departmentNumber: 1000 departmentNumber: 1002 dn: ou=Groups,dc=corp,dc=com objectClass: organizationalUnit ou: Groups dn: cn=admins,ou=Groups,dc=corp,dc=com objectClass: posixGroup cn: admins gidNumber: 1000 dn: cn=developers,ou=Groups,dc=corp,dc=com objectClass: posixGroup cn: developers gidNumber: 1001 dn: cn=designers,ou=Groups,dc=corp,dc=com objectClass: posixGroup cn: designers gidNumber: 1002 ``` You will need different settings to tie users and groups together: ``` base_user_search = "ou=People,dc=corp,dc=com" username_attr = "cn" user_id_attr = "cn" user_display_name_attr = "cn" base_group_search = "ou=Groups,dc=corp,dc=com" filter_groups_by_user_value = "departmentNumber" filter_groups_by_user_attr = "gidNumber" group_display_name_attr = "cn" ``` ### Troubleshooting The following section will lay down some indicators to determine which step of the sign in process has failed. #### Troubleshoot your Connection If the host or port was wrong, or Chef Automate was not able to reach the LDAP service, the sign in screen will display > Internal Server Error > Login error. In the logs (`journalctl -u chef-automate`), you will find a line from `automate-dex.default` like this – note that for readability, the timestamp and service name has been removed from this example log): ``` level=error msg="Failed to login user: failed to connect: LDAP Result Code 200 \"\": dial tcp 192.168.33.223:10637: getsockopt: connection refused" ``` Note that the log contains the *IP address* even when the LDAP server was configured via hostname. Double-checking that can be helpful to exclude issues in domain-name resolution. Issues in TLS verification manifest in the same way, but the log indicates that: ``` level=error msg="Failed to login user: failed to connect: LDAP Result Code 200 \"\": x509: certificate is valid for localhost, not dex-dev.test" ``` #### Troubleshoot Bind Issues in bind manifest in the same way (“Internal Server Error”) as Connect issues. However, they differ in what gets logged: ``` level=error msg="Failed to login user: ldap: initial bind for user \"cn=service_account,dc=corp,dc=com\" failed: LDAP Result Code 49 \"Invalid Credentials\": " ``` #### Troubleshoot User Search There’s two main ways the user search could fail, and they lead to different sign in failures: One is queries that cannot be executed at all, leading to > Internal Server Error > Login error. in the browser and a line like ``` level=info msg="performing ldap search ou=Peoples,dc=example,dc=org sub (cn=jane)" level=error msg="Failed to login user: ldap: search with filter \"(cn=jane)\" failed: LDAP Result Code 32 \"No Such Object\": " ``` in the logs. One possible cause (whose logs you see here) is a misconfigured `base_user_search_dn`. When the user search is executed successfully, but fails to return a useful user record, the browser will show the sign in prompt with an error banner saying > Username or password is incorrect. In the logs, you will find more information. There is a line informing you about the actual *search* query, ``` level=info msg="performing ldap search ou=People,dc=corp,dc=com sub (cnn=jane)" ``` together with an entry saying that nothing was returned by the attempted query: ``` level=error msg="ldap: no results returned for filter: \"(cnn=jane)\"" ``` In this example output, the `username_attr` was set to `cnn` (not `cn`). Since there is no way for the LDAP integration to determine whether a configuration was *wrong* or the provided user does not exist, the sign in UI can only assume that the credentials were invalid. Note that invalid entries for `user_query_filter` will lead to queries that return no entries, too. Setting ``` user_query_filter = "(objectClass=person)" ``` will lead to the following logs: ``` level=info msg="performing ldap search ou=People,dc=example,dc=org sub (&(objectClass=person(cn=jane))" connector=LDAP level=error msg="ldap: no results returned for filter: \"(&(objectClass=person(cn=jane))\"" connector=LDAP ``` Warning User search also fails if more than one user is returned. Ensure that a search for `username_attr` with the given search base can only return one user. Something like this could happen (simplified for demonstration): ``` dn: cn=jane,ou=Denver,ou=People,dc=corp,dc=com sn: doe cn: jane username: jdoe dn: cn=john,ou=Boston,ou=People,dc=corp,dc=com sn: doe cn: john username: jdoe ``` with ``` base_user_search_dn = "ou=People,dc=corp,dc=com" username_attr = "username" ``` neither <NAME> nor her brother could sign in to Chef Automate. There would be a log indicating that multiple users have been returned. This situation would be averted by setting `username_attr = "cn"`; or by restricting `base_user_search_dn`, if you only want to allow people from one of either cities to use Chef Automate. Warning Attributes that have been configured, but are not found in the results, lead to user search failures, too. Note that this also affects default values. Finally, a successful user search logs a line like the following: ``` level=info msg="username \"jane\" mapped to entry cn=jane,ou=People,dc=corp,dc=com" ``` #### Troubleshoot Sign In Bind Failures in sign in bind that are not caused by invalid credentials will lead to > Internal Server Error > Login error. accompanied by a log line with more details, starting with `Failed to sign in user`. #### Troubleshoot Group Search Failures in retrieving a user’s groups will inhibit their sign in with > Internal Server Error > Login error. and logs like ``` level=info msg="performing ldap search ou=Groups,dc=example,dc=org sub (member=cn=jane,ou=People,dc=example,dc=org)" level=error msg="Failed to login user: ldap: failed to query groups: ldap: search failed: LDAP Result Code 32 \"No Such Object\": " ``` This, for example, is what you see when the `base_group_search_dn` does not exist (`"ou=Groups,dc=..."`). However, contrary to how *User Search* works, an empty result from *Group Search* will not inhibit sign in, it will merely not populate the user’s internal record with any groups. A successful sign in causes log entries like the following: ``` level=info msg="performing ldap search ou=People,dc=corp,dc=com sub (cn=jane)" level=info msg="username \"jane\" mapped to entry cn=jane,ou=People,dc=corp,dc=com" level=info msg="performing ldap search ou=Groups,dc=corp,dc=com sub (member=cn=jane,ou=People,dc=corp,dc=com)" level=info msg="login successful: connector \"ldap\", username=\"jane\", email=\"<EMAIL>\", groups=[\"admins\" \"developers\"]" ``` and subsequent API authorization request logs containing the user’s *subjects*: ``` level=info msg="Authorization Query" action=search resource="compliance:profiles" result=true subject="[team:ldap:admins team:ldap:developers user:ldap:jane]" ``` #### `ldapsearch` Example Queries For debugging purposes it can be useful to execute LDAP queries manually using the `ldapsearch` utility. On Ubuntu, it is provided via `ldap-utils` (i.e., `sudo apt-get install ldap-utils`). In what follows, we will outline an example directory layout, and the `ldapsearch` queries corresponding to the different phases. The *User Search* query looks like this, with comments referencing the configurables for LDAP integration: ``` ldapsearch -H ldap://ldap-server:636/ \ # host -D cn=service_account,dc=corp,dc=com \ # bind_dn -w admin \ # bind_password -b ou=People,dc=corp,dc=com \ # base_user_search_dn -s sub \ '(cn=jane)' # (username_attr=what-was-provided-via-sign-in-form) ``` When using anonymous bind: ``` ldapsearch -H ldap://ldap-server:636/ \ # host -b ou=People,dc=corp,dc=com \ # base_user_search_dn -s sub \ '(cn=jane)' # (username_attr=what-was-provided-via-sign-in-form) ``` If you have configured a `user_query_filter`, it is wrapped into the filter argument: ``` '(&(objectClass=person)(cn=jane))' # (&user_query_filter(username_attr=what-was-provided-via-sign-in-form)) ``` Once a user directory entry has been retrieved, the password can be verified, and the group query can be constructed from it: Let us assume we have gotten the entry for user `jane`: ``` # jane, People, corp.com dn: cn=jane,ou=People,dc=corp,dc=com objectClass: person objectClass: inetOrgPerson sn: doe cn: jane ``` then the password verification can be simulated by ``` ldapsearch -H ldap://ldap-server:636/ \ # host -b cn=jane,ou=People,dc=corp,dc=com \ # always the entry's DN -w janespassword # as provided via sign in from ``` where any non-failure result (such as `32 No such object`) would indicate valid credentials. Finally, the group search query for that user entry looks like ``` ldapsearch -H ldap://ldapserver:636/ \ # host -D cn=service_account,dc=corp,dc=com \ # bind_dn -w admin \ # bind_password -b ou=Groups,dc=corp,dc=com \ # base_group_search_dn -s sub \ '(member=cn=jane,ou=People,dc=corp,dc=com)' # (filter_groups_by_user_attr=[that attr of user entry]) ``` With an additional `group_query_filter`, the final filter is ``` '(&(objectClass=group)(member=cn=jane,ou=People,dc=corp,dc=com))' # (&group_query_filter(filter_groups_by_user_attr=[...]) ``` Note: if the user entry contains more than one `filter_groups_by_user_attr` attribute, multiple queries will be executed, and their results combined. #### Other Common Issues If a user, following a sign in through LDAP or SAML, sees a > 502 Bad Gateway error page, the group information collected for the user exceeds some internal limits. This can have two causes: the user having too many groups, or referencing LDAP groups by distinguished names (DN). The latter can cause little information (e.g. the group name *“admins”*) to grow out of proportion (e.g. *“cn=admins,ou=DeptA,ou=CityB,ou=StateWA,dc=subcorp,dc=corp,dc=com”*). This can be mitigated by changing the `group_display_name_attr` from `DN` to `cn` (common name). Note that for authorization purposes, that is also advisable. LDAP-provided groups are referenced in policies using `team:ldap:<group-name>`. Thus `team:ldap:admins` is handier than `team:ldap:cn=admins,ou=DeptA,ou=CityB,ou=StateWA,dc=subcorp,dc=corp,dc=com`. The other cause, having too many groups for a user, can be addressed by using the `group_query_filter` to restrict the group results (for all users). Anything expressible in an LDAP search query and supported by the LDAP service can be configured there. For example, given a flat list of groups in a directory service like ``` cn=group1,ou=Groups,dc=corp,dc=com cn=group2,ou=Groups,dc=corp,dc=com cn=group3,ou=Groups,dc=corp,dc=com cn=group4,ou=Groups,dc=corp,dc=com cn=group5,ou=Groups,dc=corp,dc=com ``` a `group_query_filter` of `(|(cn=group1)(cn=group2))` would restrict the group search results to either one of those groups. Note that this has no implications on which users get authenticated; it only affects the groups recognized by Chef Automate. For example, given users Jane and Jack, where Jane is a member of `group1` and `group3`, and Jack of `group3` and `group4`: Jane’s groups would resolve to `group1` only, and Jack would have no groups – but still be able to access Chef Automate. In a similar manner, selected groups could be excluded from the results explicitly, by using a filter like `(!cn=group2)` Given a more structured directory service layout, including multiple trees of groups, further options become possible: Assuming the layout is like ``` cn=group1,ou=AGroups,dc=corp,dc=com cn=group2,ou=AGroups,dc=corp,dc=com cn=group3,ou=BGroups,dc=corp,dc=com cn=group4,ou=BGroups,dc=corp,dc=com cn=group5,ou=CGroups,dc=corp,dc=com ``` you can use your directory server’s query capabilities to restrict the results to a subtree. The concrete details depend on the product in use; for example in servers supporting *extensible match*, all group entries below `AGroups` and `BGroups` could be retrieved using a `group_query_filter` of `(|(ou:dn:=AGroups)(ou:dn:=BGroups))`. See [LDAP Wiki Extensible Match Search Filter](http://ldapwiki.com/wiki/ExtensibleMatch) for details. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/ldap/Restore ======= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/restore.md) Restore Chef Automate from a [filesystem backup](index#restore-from-a-filesystem-backup), an [Amazon S3 bucket backup](index#restore-from-an-aws-s3-backup), or a [Google Cloud Storage (GCS) bucket backup](index#restore-from-a-google-cloud-storage-backup). Before restoring a Chef Automate installation, see how to [configure your backups](../backup/index). Prerequisites ------------- 1. On the restore host, download and unzip the Chef Automate command-line tool: ``` curl https://packages.chef.io/files/current/latest/chef-automate-cli/chef-automate_linux_amd64.zip | gunzip - > chef-automate && chmod +x chef-automate ``` 2. To restore from **filesystem backups**, Chef Automate requires access to a backup directory in the [configured location](../backup/index#backup-to-a-filesystem). Ensure access for the backup type used: 1. To restore [a network-attached filesystem backup](../backup/index#backup-to-a-filesystem), mount the shared backup directory to the same mount point configured at the time of the backup. 2. To restore [a backup directory that is not a network-attached filesystem](../backup/index#backup-to-a-filesystem), copy the backup directory to the configured location at the time of the backup. 3. To restore a [single-file backup archive](../backup/index#store-a-filesystem-backup-in-a-single-file-archive), copy your archive to the restore host and extract it to the configured backup directory. 3. To restore a backup to a host with a different fully qualified domain name (FQDN) than the original backup host, create a `patch.toml` file that specifies the new FQDN and provide it at restore time: ``` [global.v1] fqdn = "<new-fqdn>" # To provide a cert and key for the restore host, uncomment and fill # these sections. # [[global.v1.frontend_tls]] # The TLS certificate for the load balancer frontend. # cert = """-----BEGIN CERTIFICATE----- # <certificate-for-new-fqdn> # -----END CERTIFICATE----- # """ # The TLS RSA key for the load balancer frontend. # key = """-----BEGIN RSA PRIVATE KEY----- # <key-for-new-fqdn> # -----END RSA PRIVATE KEY----- # """ ``` 4. To restore a backup to a machine with less memory than the original system, adjust for the appropriate lower memory settings by creating a `patch.toml` file that specifies the heapsize, and providing the file at restore time: ``` [elasticsearch.v1.sys.runtime] heapsize = "4096m" # Use "m" for megabytes and "g" for gigabytes ``` Restore From a Filesystem Backup -------------------------------- Meet the required [prerequisites](index#prerequisites) before beginning your restore process. ### Restore in an Internet-Connected Environment If you have [configured the backup directory](../backup/index#backup-to-a-filesystem) to a directory other than the default directory (`/var/opt/chef-automate/backups`), you must supply the backup directory. Without a backup ID, Chef Automate uses the most recent backup in the backup directory. To restore on a new host, run: ``` chef-automate backup restore </path/to/backups/>BACKUP_ID ``` To restore on an existing Chef Automate host by overwriting the existing installation with the backup, run: ``` chef-automate backup restore </path/to/backups/>BACKUP_ID --skip-preflight ``` Use the `--patch-config` option with a [configuration patch file](index#prerequisites) to restore to a host with a different FQDN than that of the backup host: ``` chef-automate backup restore </path/to/backups/>BACKUP_ID --patch-config </path/to/patch.toml> --skip-preflight ``` Restores from a filesystem backup may fail with incorrect directory permissions. Run the [`fix-repo-permissions` command](../cli_chef_automate/index#chef-automate-backup-fix-repo-permissions) to address such issues: ``` sudo chef-automate backup fix-repo-permissions <path``` ### Restore in an Airgapped Environment To restore a backup of an [airgapped installation](../airgapped_installation/index), you must specify the [Airgap Installation Bundle](../airgapped_installation/index#create-an-airgap-installation-bundle) used by the installation. If you have [configured the backup directory](../backup/index#backup-to-a-filesystem) to a directory that is not the default `/var/opt/chef-automate/backups`, then you must supply the backup directory. If you do not provide a backup ID, Chef Automate uses the most recent backup in the backup directory. To restore on a new host, run: ``` chef-automate backup restore --airgap-bundle </path/to/bundle> </path/to/backups/>BACKUP_ID ``` To restore on an existing Chef Automate host, run: ``` chef-automate backup restore --airgap-bundle </path/to/bundle> </path/to/backups/>BACKUP_ID --skip-preflight ``` To restore using AWS S3 on an existing Chef Automate host, run: ``` chef-automate backup restore --airgap-bundle </path/to/bundle> s3://bucket_name/</path/to/backups/>BACKUP_ID --skip-preflight ``` To restore using Google Cloud Storage (GCS) on an existing Chef Automate host, run: ``` chef-automate backup restore --airgap-bundle </path/to/bundle> gs://bucket_name/</path/to/backups/>BACKUP_ID --skip-preflight ``` Use the `--patch-config` option with a [configuration patch file](index#prerequisites) to restore to a host with a different FQDN than that of the backup host. Restores from a filesystem backup may fail with incorrect directory permissions. Run the [`fix-repo-permissions` command](../cli_chef_automate/index#chef-automate-backup-fix-repo-permissions) to address such issues: ``` sudo chef-automate backup fix-repo-permissions <path``` Restore From an AWS S3 Backup ----------------------------- Meet the required [prerequisites](index#prerequisites) before beginning your restore process. See how to [back up to AWS S3](../backup/index#backup-to-aws-s3). To restore from an AWS S3 bucket backup on a new host, run: ``` chef-automate backup restore s3://bucket_name/path/to/backups/BACKUP_ID ``` To restore from an AWS S3 bucket backup on an existing Chef Automate host, run: ``` chef-automate backup restore s3://bucket_name/path/to/backups/BACKUP_ID --skip-preflight ``` Use the `--patch-config` option with a [configuration patch file](index#prerequisites) to restore to a host with a different FQDN than that of the backup host: ``` chef-automate backup restore s3://bucket_name/path/to/backups/BACKUP_ID --patch-config </path/to/patch.toml> --skip-preflight ``` A successful restore shows the timestamp of the backup used at the end of the status output: ``` Success: Restored backup 20180517223558 ``` Restore From a Google Cloud Storage Backup ------------------------------------------ Meet the required [prerequisites](index#prerequisites) before beginning your restore process. See how to [back up to GCS](../backup/index#backup-to-gcs). To restore from a Google Cloud Storage (GCS) bucket backup on a new host, run: ``` chef-automate backup restore gs://bucket_name/path/to/backups/BACKUP_ID ``` To restore from a Google Cloud Storage (GCS) bucket backup on an existing Chef Automate host, run: ``` chef-automate backup restore gs://bucket_name/path/to/backups/BACKUP_ID --skip-preflight ``` Use the `--patch-config` option with a [configuration patch file](index#prerequisites) to restore to a host with a different FQDN than that of the backup host: ``` chef-automate backup restore gs://bucket_name/path/to/backups/BACKUP_ID --patch-config </path/to/patch.toml> --skip-preflight ``` A successful restore shows the timestamp of the backup used at the end of the status output: ``` Success: Restored backup 20180517223558 ``` Troubleshooting --------------- Set the log level to `debug` before re-running a failed restore to output debug info to the Chef Automate log: ``` chef-automate debug set-log-level deployment-service debug ``` References ---------- See the [`chef-automate backup restore` command reference](../cli_chef_automate/index#chef-automate-backup-restore). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/restore/Elasticsearch ============= You can configure Chef Automate to use Elasticsearch clusters that are not deployed via Chef Automate itself. Configure External Elasticsearch -------------------------------- These configuration directions are intended for in the initial deployment of Chef Automate. Note Chef Automate supports the official Elasticsearch Service by Elastic. Chef Automate does not test or support alternative services, such as Amazon Elasticsearch Service (Amazon ES). Add the following to your config.toml: ``` [global.v1.external.elasticsearch] enable = true nodes = ["http://elastic1.example:9200", "http://elastic2.example:9200", "..." ] # Uncomment and fill out if using external elasticsearch with SSL and/or basic auth # [global.v1.external.elasticsearch.auth] # scheme = "basic_auth" # [global.v1.external.elasticsearch.auth.basic_auth] ## Create this elasticsearch user before starting the Automate deployment; ## Automate assumes it exists. # username = "<admin username>" # password = "<admin password>" # [global.v1.external.elasticsearch.ssl] # Specify either a root_cert or a root_cert_file # root_cert = """$(cat </path/to/cert_file.crt>)""" # server_name = "<elasticsearch server name>" # Uncomment and fill out if using external elasticsearch that uses hostname-based routing/load balancing # [esgateway.v1.sys.ngx.http] # proxy_set_header_host = "<your external es hostname>:1234" # Uncomment and add to change the ssl_verify_depth for the root cert bundle # ssl_verify_depth = "2" ``` Because externally-deployed Elasticsearch nodes will not have access to Chef Automate’s built-in backup storage services, you must configure Elasticsearch backup settings separately from Chef Automate’s primary backup settings. You can configure backups to use either the local filesystem or S3. ### Add Resolvers for Elasticsearch In case you want to resolve the Elasticsearch node IPs dynamically using DNS servers, you can add resolvers/nameservers to the configuration. Name Servers can be added in two ways: 1. **Add nameserver IPs:** Add the nameservers to your `config.toml` file to resolve the Elasticsearch nodes. ``` [esgateway.v1.sys.ngx.main.resolvers] # Multiple resolvers can be specified by adding the resolvers in the list. nameservers = ["192.0.2.0:24", "198.51.100.0:24"] ``` 2. **Set system DNS entries:** To use existing system nameserver entries from `/etc/resolv.conf`, add the following setting to `config.toml`: ``` [esgateway.v1.sys.ngx.main.resolvers] enable_system_nameservers = true ``` If both options are set, nameserver IPs takes precedence over the system nameserver entries. Apply the changes: ``` sudo chef-automate config patch config.toml ``` If you wish to reset to the default configuration or to modify the configuration: 1. Run `chef-automate config show config.toml`. 2. Open `config.toml` and remove the `esgateway.v1.sys.ngx.main.resolvers` configuration or change the values. 3. Run `chef-automate config set config.toml` to apply your changes. Backup External Elasticsearch ----------------------------- ### Backup External Elasticsearch to a Local Filesystem To configure local filesystem backups of Chef Automate data stored in an externally-deployed Elasticsearch cluster: 1. Ensure that the filesystems you intend to use for backups are mounted to the same path on all Elasticsearch master and data nodes. 2. Configure the Elasticsearch `path.repo` setting on each node as described in the [Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-snapshots.html#_shared_file_system_repository). 3. Add the following to your `config.toml`: ``` [global.v1.external.elasticsearch.backup] enable = true location = "fs" [global.v1.external.elasticsearch.backup.fs] # The `path.repo` setting you've configured on your Elasticsearch nodes must be # a parent directory of the setting you configure here: path = "/var/opt/chef-automate/backups" ``` ### Backup External Elasticsearch to AWS S3 To configure AWS S3 backups of Chef Automate data stored in an externally-deployed Elasticsearch cluster: 1. Install the [`repository-s3` plugin](https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-s3.html) on all nodes in your Elasticsearch cluster. 2. If you wish to use IAM authentication to provide your Elasticsearch nodes access to the S3 bucket, you must apply the appropriate IAM policy to each host system in the cluster. 3. Configure each Elasticsearch node with a S3 client configuration containing the proper S3 endpoint, credentials, and other settings as [described in the Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-s3-client.html). 4. Enable S3 backups by adding the following settings to your `config.toml`: ``` [global.v1.external.elasticsearch.backup] enable = true location = "s3" [global.v1.external.elasticsearch.backup.s3] # bucket (required): The name of the bucket bucket = "<bucket name>" # base_path (optional): The path within the bucket where backups should be stored # If base_path is not set, backups will be stored at the root of the bucket. base_path = "<base path>" # name of an s3 client configuration you create in your elasticsearch.yml # see https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-s3-client.html # for full documentation on how to configure client settings on your # Elasticsearch nodes client = "<client name>" [global.v1.external.elasticsearch.backup.s3.settings] ## The meaning of these settings is documented in the S3 Repository Plugin ## documentation. See the following links: ## https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-s3-repository.html ## Backup repo settings # compress = false # server_side_encryption = false # buffer_size = "100mb" # canned_acl = "private" # storage_class = "standard" ## Snapshot settings # max_snapshot_bytes_per_sec = "40mb" # max_restore_bytes_per_sec = "40mb" # chunk_size = "null" ## S3 client settings # read_timeout = "50s" # max_retries = 3 # use_throttle_retries = true # protocol = "https" ``` ### Backup External Elasticsearch to GCS To configure Google Cloud Storage Bucket (GCS) backups of Chef Automate data stored in an externally-deployed Elasticsearch cluster: 1. Install the [`repository-gcs` plugin](https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-gcs.html) on all nodes in your Elasticsearch cluster. 2. Create a storage bucket and configure a service account to access it per the steps [described in the Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-gcs-usage.html). 3. Configure each Elasticsearch node with a GCS client configuration that contains the proper GCS settings as [described in the Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/plugins/current/repository-gcs-client.html). 4. Enable GCS backups by adding the following settings to your `config.toml`: ``` [global.v1.external.elasticsearch] enable = true nodes = ["https://my-es.cluster"] ## If multiple # nodes = ["https://my-es.node-1", "https://my-es.node-2", "etc..."] ## The following settings are required if you have Elasticsearch setup with basic auth #[global.v1.external.elasticsearch.auth] # scheme = "basic_auth" # #[global.v1.external.elasticsearch.auth.basic_auth] # username = "everyuser" # password = "pass123" [global.v1.external.elasticsearch.backup] enable = true location = "gcs" [global.v1.external.elasticsearch.backup.gcs] bucket = "<bucket name>" # Client name is normally default, but can be set here if you have generated service # account credentials with a different client name client = "default" ## GCS Bucket Settings: # type = nearline # access control = uniform ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/elasticsearch/PostgreSQL ========== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/postgresql.md) You can configure Chef Automate to use external PostgreSQL clusters that are not deployed via Chef Automate itself. Configuring an External PostgreSQL Database ------------------------------------------- These configuration directions are intended for in the initial deployment of Chef Automate. Add the following settings to your `config.toml`: ``` [global.v1.external.postgresql] enable = true nodes = ["<pghostname1>:<port1>", "<pghostname2>:<port2>", "..."] # To use postgres with SSL, uncomment and fill out the following: # [global.v1.external.postgresql.ssl] # enable = true # root_cert = """$(cat </path/to/root/cert.pem>)""" [global.v1.external.postgresql.auth] scheme = "password" # Create these postgres users before starting the Automate deployment; # Automate assumes they already exist. [global.v1.external.postgresql.auth.password.superuser] username = "<admin username>" password = "<admin password>" [global.v1.external.postgresql.auth.password.dbuser] username = "<dbuser username>" password = "<dbuser password>" [global.v1.external.postgresql.backup] enable = true ``` Adding Resolvers for PostgreSQL Database ---------------------------------------- In case you want to resolve the PostgreSQL cluster node IPs dynamically using DNS servers, you can add resolvers/nameservers to the configuration. Name Servers can be added in two ways: 1. **Add nameserver IPs:** If you are aware of the nameservers which should resolve the PostgreSQL nodes, the nameservers can be added to your `config.toml` file. ``` [pg_gateway.v1.sys.resolvers] # Multiple resolvers can be specified by adding the resolvers in the list. nameservers = ["127.0.0.53:53"] ``` 2. **Set system DNS entries:** To use existing system nameserver entries from `/etc/resolv.conf`, add the following setting to `config.toml`: ``` [pg_gateway.v1.sys.resolvers] enable_system_nameservers = true ``` If both options are set, nameserver IPs takes precedence over the system nameserver entries. Apply the changes: ``` sudo chef-automate config patch config.toml ``` If you wish to reset to the default configuration or to modify the configuration: 1. Run `chef-automate config show config.toml`. 2. Edit `config.toml` to replace/edit the `pg_gateway.v1.sys.resolvers` section with the configuration values. 3. Run `chef-automate config set config.toml` to apply your changes. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/postgresql/Setting up the Applications Dashboard ===================================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/applications_setup.md) This Enterprise Application Stack (EAS) integration gives you immediate insight into the status of your Chef Habitat services, even when scaling out to large numbers of services. The Chef Automate Applications Dashboard gives you operational observability into your Chef Habitat systems, so you can monitor and respond quickly to changes in your Chef Habitat environments. The Applications Dashboard *Service Groups* table is an overview of your Chef Habitat network, grouped together by package, environment, service group, and application. The right-hand sidebar contains detailed status report cards for each individual service. Requirements and Capacity Planning ---------------------------------- Chef Enterprise Application Stack with Chef Automate + Chef Habitat can scale up to 15,000 services on a system using: * 4 CPU * 16GB RAM * 50 GB disk space * Chef Automate, current version * Chef Habitat, minimum version 1.5.0 Chef Automate’s Compliance and Infrastructure observability features require additional computing and memory capacity. Larger scale systems (15,000+ services) consume significant CPU resources for processing applications data. Chef Habitat Service Group Best Practices ----------------------------------------- A service group contains all of the services for a single package. The services in a group share a single relationship structure (topology) and are connected within a Chef Habitat supervisor network. For best results: * Use a separate Chef Habitat network for each application deployment environment (“Development”, “Test”, “Acceptance”, “Production”) * Use the default Chef Habitat service group names For services that do not follow this layout, you should select environment and application names that help you find and filter the application data and are relevant to your typical job tasks. For more information on setting up Chef Habitat, see the Chef Habitat [Service Groups](../../habitat/about_services/index#service-group) documentation. Setting up the Applications Dashboard ------------------------------------- To get started, you need: 1. Running installations of Chef Automate and Chef Habitat Builder SasS or Builder on-prem 2. A [Chef Automate API token](../api_tokens/index#creating-a-standard-api-token) specifically for this integration Sending Event Data to Chef Automate ----------------------------------- If you have not already done so, [create an API token](../api_tokens/index#creating-a-standard-api-token) in Chef Automate. Save it somewhere safe and accessible to you for use in this step. ### Customize the Event Stream Command Copy the following event stream command into your editor and replace `MY_APP`, `MY_ENV`, `MY_SITE`, `AUTOMATE_HOSTNAME`, and `API_TOKEN` with the appropriate values. ``` hab sup run \ --event-stream-application="MY_APP" \ --event-stream-environment="MY_ENV" \ --event-stream-site="MY_SITE" \ --event-stream-url="AUTOMATE_HOSTNAME:4222" \ --event-stream-token="API_TOKEN" \ ``` * [hab sup run](../../habitat/habitat_cli/index#hab-sup-run) is the hab cli commant to start the Habitat supervisor. * `MY_APP` is the name of your application. Chef Automate groups services by application name in the Applications Dashboard * `MY_ENV` is the application environment for this supervisor. Chef Automate groups services by environment in the Applications Dashboard * `MY_SITE` describes the physical (for example, datacenter) or cloud-specific (for example, the AWS region) location where your services are deployed. The site field is a value filtering for services in the Applications Dashboard. * `AUTOMATE_HOSTNAME:4222` is the Chef Automate URL with port 4222 specified. * `API_TOKEN` is the token you created in Chef Automate. ### Run the Event Stream Command Paste your customized event stream command into the Chef Habitat command line. For example: ``` hab sup run \ --event-stream-application="AmazingEnterpriseApp" \ --event-stream-environment="acceptance" \ --event-stream-site="us-west-2" \ --event-stream-url="automate.company.com:4222" \ --event-stream-token="1234567890abcdefgh" \ ``` Authorize Communication from Chef Habitat to Chef Automate ---------------------------------------------------------- The Transport Layer Security (TLS) protocol provides privacy and data integrity during communication between Chef Automate and Chef Habitat. Provide Chef Habitat with Chef Automate’s TLS certificate to authorize communication between the two. ### Retrieve Chef Automate’s TLS Certificate Chef Automate’s TLS certificate file is located at `/hab/svc/automate-load-balancer/data/<servername>.cert`. For example, if your FQDN is `automate`, then the file location is: `/hab/svc/automate-load-balancer/data/automate.cert`. From Chef Automate: 1. On the command line, run `chef-automate external-cert show` 2. Copy the certificate contents from the output 3. Make sure to copy it entirely, including `-----BEGIN CERTIFICATE...END CERTIFICATE-----` 4. Save the file as `automate.cert` somewhere safe and accessible to you ### Share the TLS Certificate with Chef Habitat Share the automate certificate with the Chef Habitat supervisor. Use **one** of these three options: #### Copy the Chef Automate Certificate into the `/hab/cache/ssl` Directory Chef Habitat automatically searches that directory and uses the certificate at start up. **On Linux systems**, as a root user, copy the certificate to`/hab/cache/ssl` . As a non-root user, copy it to `~/.hab/cache/ssl`. The full file path for a non-root user certificate in your local directory is `/Users/username/.hab/cache/ssl/automate.cert`. You may need to use `sudo` with the command. As the root user, copy the file with: ``` cp /path/to/automate.cert /hab/cache/ssl/automate.cert ``` As a non-root user, copy it with: ``` sudo /path/to/automate.cert ~/.hab/cache/ssl ``` **On Windows systems**, store your certs in `C:\hab\cache\ssl`. For example, copy the file with: ``` Copy-Item "C:\path\to\automate.cert" -Destination "C:\hab\cache\ssl" ``` #### Add the TLS Certificate to Your Event Stream Command Pass the certificate file as a parameter by adding it to your event stream command: ``` --event-stream-server-certificate=/path/to/automate.cert ``` For example: ``` hab sup run \ --event-stream-application=MY_APP \ --event-stream-environment=MY_ENV \ --event-stream-site=MY_SITE \ --event-stream-url=AUTOMATE_HOSTNAME:4222 \ --event-stream-token=API_TOKEN \ --event-stream-server-certificate=/path/to/automate.cert \ ``` #### Add the TLS Certificate to Your Certificate Store Add the certificate to your systems platform-specific certificate store. These are: `SChannel` on Windows, `Secure Transport` on OSX, and `OpenSSL` on all other platforms. Please follow the instructions for your specific operating system. Troubleshooting --------------- ### Create a New TLS Key Pair You can change Chef Automate’s automate front-end TLS key pair by following the [load balancing configuration](../configuration/index#load-balancer-certificate-and-private-key) documentation. ### Re-Enable TLS on Chef Automate In some cases, front-end TLS communication may be previously disabled. To re-enable front-end TLS communication, which allows Chef Automate to receive encrypted event data from Chef Habitat, on the Chef Automate host: 1. Create a file with the following content: ``` [event_gateway] [event_gateway.v1] [event_gateway.v1.sys] [event_gateway.v1.sys.service] disable_frontend_tls = false ``` 1. Save the file in the `.toml` file format. Use any name. 2. Apply the configuration change with `chef-automate config patch FILENAME.TOML`. You should see output similar to: ``` Updating deployment configuration Applying deployment configuration Started event-gateway ``` #### Disable TLS Encryption on Chef Automate To disable front-end TLS encryption on Chef Automate and allow un-encrypted event data from Chef Habitat, on the Chef Automate host: 1. Create a file with the following content: ``` [event_gateway] [event_gateway.v1] [event_gateway.v1.sys] [event_gateway.v1.sys.service] disable_frontend_tls = true ``` 1. Save the file in the `.toml` file format. Use any name. 2. Apply the configuration change with `chef-automate config patch FILENAME.TOML`. You should see output similar to: ``` Updating deployment configuration Applying deployment configuration Started event-gateway ``` ### Authenticating Existing Chef Automate and Builder Installations To configure Chef Automate as an OAuth Provider for Habitat Builder, create a TOML file that contains the partial configuration below. Run `chef-automate config patch </path/to/your-file.toml>` to deploy your change. `bldr_client_id` and `bldr_client_secret` need to match the settings of the values in Habitat Builder. Follow the [best practices](https://www.oauth.com/oauth2-servers/client-registration/client-id-secret/) for setting these values `client_id` and `client_secret` in the Oauth2 standard. ``` [session.v1.sys.service] bldr_signin_url = "<your Builder fqdn>" # for example, "http://builder.test/" # This needs to match what you configured OAUTH_CLIENT_ID as when you configured Habitat Builder. bldr_client_id = "<your Habitat Builder Oauth2 Client ID>" # This needs to match what you configured OAUTH_CLIENT_SECRET as when you configured Habitat Builder. bldr_client_secret = "<your Habitat Builder Oauth2 Client Secret>" ``` You’ll need to add Automate’s TLS certificate to Builder’s list of accepted certificates in addition to these configuration changes. Locate Automate’s default self-signed certificate by running `cat /hab/svc/automate-load-balancer/data/automate.example.com.cert` You can copy this default certificate, and then add it to your Builder instance’s list of accepted certs. ``` -----BEGIN CERTIFICATE----- MIIDfDCCAmSgAcasldkaf... -----END CERTIFICATE----- ``` If you are using a certificate signed by a trusted certificate authority instead of the default certificate, you can provide Builder with the root certificate authority for the signed certificate. For more information, check out this further explanation on how to [configure Builder to authenticate via Chef Automate](https://github.com/habitat-sh/on-prem-builder). Related Resources ----------------- For more information, see the [Chef Habitat documentation](../../habitat/index). In particular, see the entries on: * [Service Groups](../../habitat/service_groups/index) * [Services](../../habitat/about_services/index) * [Supervisor](../../habitat/sup/index) * [Topology](../../habitat/about_services/index#topology) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/applications_setup/IAM Overview ============ [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/iam_v2_overview.md) Note This documentation covers Chef Automate’s IAM feature in release 20200326170928 and later. Chef Automate’s Identity and Access Management (IAM) allows direct management of policy members from Chef Automate in the browser. IAM supports the projects feature, which allow for filtering and segregation of your data amongst your user base. IAM policies allow you to use multiple permissions, distinguish policy membership from policy definition for fine-grained control, and include roles for role-based access control. The *policy* exists at the heart of Chef Automate’s IAM system. A policy defines permissions for who may perform what action on which resource and scopes these permissions by project. The “who” may be a user, a team, or an API token. The following diagram shows the new policy structure. We detail the specifics in the next sections. ![] Policy Definition ----------------- IAM uses multi-statement policies that support complex permissions. Each statement in a policy specifies a single permission. Chef Automate determines a policy’s net effect through the evaluation and combinations of permission statements. If at least one statement allows access, and none denies it, then the policy allows access. Otherwise, access denied. Access is granted if explicitly allowed in some policy and not explicitly denied in any policy. IAM policy evaluation order is: 1. By default, all requests are denied. 2. Any explicit ALLOW overrides the default DENY. 3. Any explicit DENY in any policy overrides any ALLOWs in any policy. ### Net Effect Examples The following examples illustrate the net effect of a policy and how it grants access to a user: * User1, or any team that user1 belongs to, does not include a policy with the `iam:users:list` action. *Net effect*: Access denied to user1 to view the list of users. This example illustrates the global default DENY condition. * Bob is a member of team alpha and team omega. Team alpha contains a broad range of permissions, while team omega experiences severe restrictions in what its members may access. The “major teams” policy has a statement that allows team alpha to access the resource `compliance:reporting:nodes`, while it has another statement that denies Team Omega access to the same resource. *Net effect*: The policy denies Bob access because at least one statement denies access. * Mary is a member of the default viewers team, which allows read access to everything because of the default Viewers policy. Mary is also a member of the deployment team, which has permission to upload and download profiles. *Net effect*: The policy grants Mary access because membership in both teams effectively allows access. ### Properties of a Policy An IAM policy consists of a list of **statements**, where each statement describes a permission. ### Properties of a Statement A policy statement must include a `Role`, or a list of inline `Actions`. | Property | Description | | --- | --- | | Role | a named list of actions | | Effect | ALLOW or DENY | | Projects | list of project IDs to constrain the role | ### Properties of a Role An IAM role consists of a list of **actions**. Some examples of these actions include listing IAM users, getting compliance profiles, or updating node status. Find more details about roles in [Role-Based Access Control](index#role-based-access-control). Members and Policies -------------------- A **member** may be a user, a team, or an API token. Users and teams may be *local*, meaning their definition exists within Chef Automate only, or managed by an external identity provider, specifically LDAP or SAML. IAM v2 policy *membership* is separate and distinct from policy *definition*. (Notice that members were **not** included as part of the [Policy Definition](index#policy-definition).) You can edit policy membership for any policy, but you can adjust only the policy definition for *Custom* policies. Policy Types ------------ IAM distinguishes two types of policies: *Chef-managed* and *Custom*. Chef provides *Chef-managed* policies, which are integral to the operation of Chef Automate. You cannot change the policy statements in Chef-managed policies. *Custom* policies are policies that you create for your own needs. You can add, edit, and delete policy statements in your custom policies. Both types of policies allow for membership modification. Role-Based Access Control ------------------------- A role is a named list of actions. This list provides the benefit of *encapsulation*. A policy statement needs only the role’s name, and the policy is not burdened by all the details. Also, the list offers *reusability* as you can apply the role to any statement that needs it. Just like policies, roles are either *Chef-managed* or *Custom* types. Default Chef-managed roles cannot change, like Chef-managed policies. Chef Automate includes five *Chef-managed* roles and two *Custom* roles by default. You can edit these Custom roles, *Compliance Viewer* and *Compliance Editor*. To see the actions comprising the roles, see [IAM Actions](../iam_actions/index). | Role | Type | Description | | --- | --- | --- | | Viewer | Chef-managed | **View** everything in the system *except* IAM | | Editor | Chef-managed | **Do** everything in the system *except* IAM and license application | | Owner | Chef-managed | **Do** everything in the system *including* IAM | | Project Owner | Chef-managed | Editor + **view** and **assign** projects | | Ingest | Chef-managed | Ingest data into the system | | Compliance Viewer | Custom | Viewer for compliance resources | | Compliance Editor | Custom | Editor for compliance resources | You can use these default Chef-created roles in your policies, or create more custom roles for further customized permissions. You can later edit any roles you create. Chef Automate also ships with policies that leverage these roles. Those Chef-managed policies are Viewers, Editors, Administrator, and Ingest. The custom policies are Compliance Viewers and Compliance Editors. Working with Projects --------------------- IAM projects are collections of resources either created in Chef Automate or ingested from external data providers, such as Chef Infra and Chef InSpec. Projects used in a policy reduce the scope of that policy’s permissions to only the resources assigned to the given projects. Note Chef Automate limits you to 300 projects. See [Configuring Project Limit](../iam_v2_guide/index#configuring-project-limit) for configuration instructions. ### Setting Up Projects Set up IAM projects using the following steps: 1. Define each project using the browser. Start on the *Projects List* page to create your projects. 2. Create or edit IAM policy statements to restrict permissions to specific projects as needed. *Every* statement must either name specific projects, specify the wildcard (`*`), which denotes all projects, or specify as `(unassigned)`, which provides permissions on objects without projects. By default, any pre-upgrade previous policies are automatically set up with that wildcard, so they apply to all projects. 3. [Assign teams or tokens to projects](../iam_v2_guide/index#assigning-teams-and-tokens-to-projects). 4. Select the projects to filter in the UI. After creating projects, use the **global project filter** in the top navigation to select one or more projects for viewing. No selection displays all resources for which you have permission. By default, Chef Automate includes a *project-owner* role, so the global admin may delegate much of these responsibilities for project management to others and share some of the global admin’s burden. ### Assigning Resources to Projects Two categories of resources exist for project assignment: * Ingested client run and compliance nodes * Teams, API Tokens, Policies, and Roles created in Automate Any of these resources not explicitly assigned to a project is *unassigned*. After upgrading and before creating projects, all your resources exist as *unassigned*. Assign your set of ingested Client Run and Compliance Nodes to projects via the project ingest rules that you create for the project. An ingest rule specifies one or more conditions, and each condition specifies a set of attribute values that a node must include for assignment to the given project. Once you define your set of projects with their contained ingest rules and conditions, use the **Update Projects** button on the bottom of any page to apply those definitions. You can assign teams and API tokens to projects directly in the browser. You can assign policies and roles only through the command line. These resources created within Chef Automate do not make use of, nor do they require, any project ingest rules. Some resources in Chef Automate respect projects, and will filter when using the project filter. Resources that do not respect projects will always display and will ignore any applied project filters. #### Resources that respect projects * API Tokens * Ingested Client Run nodes * Ingested Compliance nodes (including the results of a scan job) * Policies * Teams * Roles #### Resources that do not respect projects * Compliance Profiles * Data Feeds * Habitat Services * Node Credentials * Node Managers (also called Node Integrations) * Notifications * Users ### Properties of a Project To assign a project to a set of ingested client run and compliance nodes, the project requires a list of **ingest rules**, where each rule describes a group of node characteristics. #### Project Ingest Rules A rule consists of a list of **conditions**, where each condition describes a single characteristic. It also contains a type: *node* or *event*. *node* corresponds to ingested client run and compliance nodes, and *event* corresponds to ingested events on the *Event Feed* page. | Property | Description | | --- | --- | | Type | node or event | | Conditions | list of node characteristics | #### Project Ingest Rule Conditions A condition consists of these properties: | Property | Description | | --- | --- | | Event Attribute | Chef Organization or Chef Infra Server | | Node Attribute | Chef Organization, Chef Infra Server, Environment, Chef Role, Chef Tag, Chef Policy Name, or Chef Policy Group | | Operator | equals or member of | | Values | list of one or more values to match on the specified attribute | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/iam_v2_overview/Chef EAS ======== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/eas.md) The Chef Enterprise Application Stack (EAS) allows organizations to automate infrastructure, security, and application delivery together, helping them deploy software quickly while maintaining compliance with industry regulations. Chef EAS helps teams drive efficiency and consistency for any application across multi-cloud and heterogeneous infrastructure. Chef EAS includes the following Chef solutions: * **Chef Habitat** builds and deploys your applications because delivering applications is where you derive your business value * **Chef Infra** configures your infrastructure, because your applications also needs to run on a stable and scalable system * **Chef InSpec** validates and secures both your applications and your infrastructure * **Chef Automate** visualizes your applications, their infrastructure, and the compliance status for both. * **Chef Workstation** provides a unified experience for all of Chef EAS Chef EAS Application Management with Chef Habitat ------------------------------------------------- Chef Habitat automates building and deploying applications, turning a web of delicate procedures into a resilient and repeatable process. A Chef Habitat package contains the compiled binary and a manifest of all the dependencies required for building and running your application. This results in a lightweight and portable artifact that you can deploy to bare metal or virtual machines, as well as export to immutable formats, such as Docker containers or Kubernetes pods. Bundling applications with a complete dependency manifest ensures that your application behaves as consistently on a developer’s laptop as it does in its on-prem VM farm staging environment, and it also behaves as consistently there as it does in its cloud-based deployment environment. The Chef Automate EAS Application Tab ------------------------------------- With the new application operations dashboard in Chef Automate, operations teams gain comprehensive and customizable visibility into the health of the services that make up the application. This makes it easier to understand what is degrading the health of an applications and to keep it running smoothly. The Chef Automate EAS Application dashboard allows you to organize and display your applications data from Chef Habitat in an intuitive way. The Chef Automate EAS Application Dashboard provides visibility into your application artifacts and channels by letting you see which versions of your packages are running on your system. Chef Automate organizes data from the application and environment tags provided by the Chef Habitat supervisor. Prerequisites ------------- The Chef Automate EAS application feature introduces several concepts from Chef Habitat, which are introduced in the following [Glossary](../applications_dashboard/index#Glossary). Find Chef Automate EAS system requirements, installation, and configuration instructions in the [Setting up the Applications Dashboard](../applications_setup/index). ### Glossary *Application* - An application is a program that is made up of multiple underlying services. Chef Habitat provides automation capabilities for building and delivering your applications service-by-service to any environment regardless of the infrastructure on which it is deployed. In Chef Habitat, you define your application and its dependencies, configuration, management, and behavior in a `plan.sh` or `plan.ps1` file. *Application Lifecycle* - In a typical enterprise software an application goes through stages of development, testing, acceptance, production, which together are called the *application lifecycle*. The application lifecycle is supported by codified infrastructure and configuration that correlates with each stage, which is called an *application delivery pipeline*. *Artifact* - A Chef Habitat artifact (also known as a “hart file”) is a software package produced by the Chef Habitat build tools. It is comparable to a deb file on Debian-based Linux systems, or a rpm file on RedHat-based Linux systems. While very simple application have two or three underlying services, most modern applications follow architecture patterns with many services that result in multiple artifacts. Artifacts are built according to the instructions in the `plan.sh` or `plan.ps1` file. Each artifact contains a software library or application, configuration settings for the application, and lifecycle hooks. *Channel* - Chef Habitat supports continuous deployments through the use of channels, which are tags used to describe the status of your artifact. Channel are conceptual spaces expressed in code by adding a tag to an artifact, which is called a “promotion”. Once promoted, an artifact is considered to “be” in that channel. In most cases, artifacts have three possible channels: “unstable”, “testing”, and “stable”. The “unstable” tag denotes an artifact that is still in active development, “testing” means that the artifact is a candidate for release, and “stable” means that it is ready for consumption. When you upload your artifact to Builder, Chef Habitat labels your application artifact with the `unstable` tag, which means that it is in the “unstable” channel. When you promote your application artifact to another channel, such as “test” or “stable”, Chef Habitat applies the new tag and makes it available to the respective channel. You can apply more than one tag to a single artifact, for example, artifacts are often tagged for both the “unstable” and “test” channels. For more information, see the Chef Habitat [Continuous Deployment Using Channels](../../habitat/pkg_promote/index#continuous-deployment-using-channels) documentation. *Deployment* - Each instance of an artifact downloaded from a channel into an environment is called a deployment. *Environment* - An environment is the coded expression of the combined infrastructure and configuration that your application requires. Chef Habitat supports continuous delivery by letting you define how the environments in your application’s delivery pipeline consume each of your artifacts. Examples of environments include “development,” “acceptance,” and “production”. Every environment in your application lifecycle has its own Supervisors, service groups, and services. *Supervisor* - The Supervisor is Chef Habitat’s process manager, which means it controls the processes related to a package, including starting, monitoring, and updating services. Each Supervisor runs a single instance of a service. Each Supervisor in an environment subscribes to a channel, which means they watch for new versions of services promoted in that channel. Once a supervisor detects a new artifact in a channel, it deploys the new package into its own environment and updates all of the services for that service group. For more information about automated deployments, see the Chef Habitat [update-strategy](../../habitat/service_group_updates/index#configuring-an-update-strategy) documentation. *Service* - A service is any single running instance of a Chef Habitat package running in an environment and managed by a Supervisor. *Service Group* - A service group is a label that you apply to multiple instances of a single service running in an environment. Service groups let you manage all of the services with this label as a single entity with a single operation. For example, if you have five Redis replicas running in your test environment, then these as a service group collects them as a single thing. This lets you stop, restart, or reconfigure all five examples of this Redis service in a single operation. Service groups also let you gather information for configuration templating by extracting information from each of them–such as their ip addresses–in a single operation. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/eas/External PostgreSQL Upgrade =========================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/postgres_external_upgrade.md) This guide covers upgrading services used by Chef Automate. Upgrade Amazon RDS for PostgreSQL --------------------------------- Amazon Web Services Relational Database Service (AWS RDS) should upgrade by Monday, January 17. Amazon is automatically migrating all AWS RDS customers from PostgreSQL from 9.6 to 13 starting Tuesday, January 18, 2022. To upgrade AWS RDS, please follow instructions on [Upgrading the PostgreSQL DB engine for Amazon RDS - Amazon Relational Database Service](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.PostgreSQL.html) Upgrade External PostgreSQL from 9.6 to 13.4 -------------------------------------------- Chef Automate uses PostgreSQL as the primary database for storing node data. [PostgreSQL 9.6 is EOL](https://endoflife.date/postgresql) and Chef customers running Chef Automate with PostgreSQL 9.6 should upgrade to [Postgres 13](https://www.postgresql.org/about/news/postgresql-13-released-2077/). ### Migration Planning The upgrade process for PostgreSQL from 9.6 to 13.4 requires a one-time downtime to vacuum, upgrade, and re-index the database. The entire upgrade operation takes about five minutes for each 2GB of data in PostgreSQL. This process may take longer depending on your server hardware and the size of the node objects in Chef Automate. ### Requirements Warning Upgrading PostgreSQL upgrades the database for all connected services. If you have multiple services connected to PostgreSQL, make sure that you have stopped the other services and prepared them for the upgrade. This upgrade guide is for systems running: * A Single PostgreSQL 9.6 installation * Using Ubuntu 18.04 or higher * On a virtual machine such as an EC2 instance or on a single physical machine * Enough free space to run a second copy of the data that is in the existing PostgreSQL 9.6 installation. This upgrade requires a minimum of 55% free space on the machine. ### Backup Chef Automate Danger **BACKUP CHEF AUTOMATE AND SECURE THE DATA**. Preserve your backup at all costs. Copy the backup to a second and separate location. Database migrations have inherent risk to your system. Create a backup before beginning any migration or update. This ensures that you have a recoverable state in case any step in the process fails. Copy the backup to a another disk that is not connected to Chef Automate. This ensures that you have state to restore, in case of a failure in the upgrade process. Follow the [Backup](../backup/index) documentation to make a copy of your Chef Automate data. ### Upgrade Chef Automate * For **airgapped** Chef Automate systems, follow the instructions in the [Airgap Installation Guide](../airgapped_installation/index) to upgrade to the latest version. * Upgrade standard Chef Automate installations to the latest version that supports External PostgreSQL v13 with the command: ``` chef-automate upgrade run ``` ### Stop Chef Automate After successful upgrade, stop Chef Automate Services. ``` sudo chef-automate stop ``` ### Upgrade from PostgreSQL 9.6 to 13.4 #### Install PostgreSQL 13.4 1. SSH or Login to the machine running PostgreSQL 9.6 with user who has sudo or root access. ``` ssh -i "<xyz.pem>" <sudo_username>@<postgres_machine_ip``` 2. Install PostgreSQL v13 ``` sudo apt-get update sudo apt-get install postgresql-13 ``` 3. If the PostgreSQL v9.6 config was modified or customized. Please check the differences and update the new PostgreSQL v13 config with similar changes. Please connect with your database administrator if you don’t know these changes. ``` sudo sdiff -s /etc/postgresql/9.6/main/postgresql.conf /etc/postgresql/13/main/postgresql.conf sudo sdiff -s /etc/postgresql/9.6/main/pg_hba.conf /etc/postgresql/13/main/pg_hba.conf ``` ### Stop PostgreSQL Services 1. Stop Both PostgreSQL Servers: ``` sudo systemctl stop postgresql.service ``` 2. Login as the `postgres` user ``` sudo su - postgres ``` ### Prepare the Database for Migration Run `vacuumdb --all --full` on the PostgreSQL database if you don’t have automatic vacuuming set up. This process will reduce the size of the database by deleting unnecessary data and speeds up the migration. This operation takes around 1 to 2 minutes per gigabyte of data depending on the complexity of the data, and requires at least as much free disk space as the size of your database. For more information on upgrading using `vacuumdb` see the PostgreSQL 13 documentation for [vacuumdb](https://www.postgresql.org/docs/13/app-vacuumdb.html). 1. Run Vacuum DB before moving data from PostgreSQL v9.6 to v13 ``` vacuumdb --all --full ``` Expected output: ``` vacuumdb: vacuuming database "automate-cs-bookshelf" vacuumdb: vacuuming database "automate-cs-oc-bifrost" vacuumdb: vacuuming database "automate-cs-oc-erchef" vacuumdb: vacuuming database "chef_applications_service" vacuumdb: vacuuming database "chef_authn_service" vacuumdb: vacuuming database "chef_authz_service" vacuumdb: vacuuming database "chef_cereal_service" vacuumdb: vacuuming database "chef_compliance_service" vacuumdb: vacuuming database "chef_config_mgmt_service" vacuumdb: vacuuming database "chef_infra_proxy" vacuumdb: vacuuming database "chef_ingest_service" vacuumdb: vacuuming database "chef_license_control_service" vacuumdb: vacuuming database "chef_session_service" vacuumdb: vacuuming database "chef_teams_service" vacuumdb: vacuuming database "chef_user_settings_service" vacuumdb: vacuuming database "data_feed_service" vacuumdb: vacuuming database "dex" vacuumdb: vacuuming database "nodemanager_service" vacuumdb: vacuuming database "notifications_service" vacuumdb: vacuuming database "postgres" vacuumdb: vacuuming database "secrets_service" vacuumdb: vacuuming database "template1" ``` #### Upgrade For more information on upgrading using `pg_upgrade` and `pg_upgrade --check` see the PostgreSQL 13 documentation for [pg_upgrade](https://www.postgresql.org/docs/13/pgupgrade.html). 1. Run pg_upgrade check command. ``` cd ~ /usr/lib/postgresql/13/bin/pg_upgrade \ --old-datadir=/var/lib/postgresql/9.6/main \ --new-datadir=/var/lib/postgresql/13/main \ --old-bindir=/usr/lib/postgresql/9.6/bin \ --new-bindir=/usr/lib/postgresql/13/bin \ --old-options '-c config_file=/etc/postgresql/9.6/main/postgresql.conf' \ --new-options '-c config_file=/etc/postgresql/13/main/postgresql.conf' \ --check ``` 2. Migrate the Data (run pg_upgrade command without –check): ``` cd ~ /usr/lib/postgresql/13/bin/pg_upgrade \ --old-datadir=/var/lib/postgresql/9.6/main \ --new-datadir=/var/lib/postgresql/13/main \ --old-bindir=/usr/lib/postgresql/9.6/bin \ --new-bindir=/usr/lib/postgresql/13/bin \ --old-options '-c config_file=/etc/postgresql/9.6/main/postgresql.conf' \ --new-options '-c config_file=/etc/postgresql/13/main/postgresql.conf' ``` #### Configure 1. Exit the PostgreSQL shell ``` exit ``` 2. Swap the ports of PostgreSQL v9.6 and 13.4: ``` PG_9_6_PORT=5432 # Assuming Postgres v9.6 is currently running on this port PG_13_PORT=5433 # Assuming Postgres 13 is currently running on this port sudo sed -i "s/port = $PG_9_6_PORT/port = $PG_13_PORT/g" /etc/postgresql/9.6/main/postgresql.conf sudo sed -i "s/port = $PG_13_PORT/port = $PG_9_6_PORT/g" /etc/postgresql/13/main/postgresql.conf ``` 3. Start both PostgreSQL Servers: ``` sudo systemctl start postgresql.service ``` #### Validate 1. Confirm the installed version: ``` sudo su - postgres psql -c "SELECT version();" ``` 2. Run the generated `analyze_new_cluster.sh` script ``` cd ~ ./analyze_new_cluster.sh ``` Reindexing is not required for Chef Automate. If `pg_upgrade` reported errors or need for reindexing please refer to [pg_upgrade documentation](https://www.postgresql.org/docs/13/pgupgrade.html) for details. 3. Exit postgres user: ``` exit ``` #### Cleanup PostgreSQL 9.6 After you have confirmed the installation and you no longer need PostgreSQL 9.6, remove PostgreSQL v9.6 and its data: ``` sudo su - postgres ./delete_old_cluster.sh ``` ### Restart Chef Automate 1. Start Chef Automate: ``` sudo chef-automate start ``` 2. Check that the Chef Automate services are up and running: ``` sudo chef-automate status ``` Troubleshoot Upgrade Failures ----------------------------- 1. If the upgrade failed and you are left with a corrupted Chef Automate or a corrupted PostgreSQL database, **DO NOT RISK YOUR BACKUP OF AUTOMATE**. Take all steps necessary to preserve the backup, including copying it to another disk. 2. Contact Chef customer support. 3. If you have configured the backup directory as a location other than the default directory (`/var/opt/chef-automate/backups`), you must supply the backup directory path to the `backup restore` command as shown in the snippet below. Without a backup ID, Chef Automate uses the most recent backup in the backup directory. To restore on a new host, run: ``` chef-automate backup restore </path/to/backups/>BACKUP_ID ``` For other restoration types please refer this [Restore](../restore/index) 4. Do not upgrade PostgreSQL until you have an uncorrupted Chef Automate and an uncorrupted PostgreSQL database. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/postgres_external_upgrade/Desktop Dashboard ================= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/desktop.md) The Chef Automate *Desktop* dashboard displays status information about all desktops connected to Chef Automate. Desktop information populates this dashboard after a Chef Infra Client run has executed. Setting Up the Desktop Dashboard -------------------------------- Warning We recommend starting with a fresh installation of Chef Automate, Chef Infra Server, and Chef Desktop because the servers do not distinguish between the types of managed nodes when combining existing Chef Automate nodes with a new Chef Desktop installation. For guidance on installing Chef Desktop, see the [installing Chef Desktop documentation](../../desktop/desktop_setup_chef/index#install-chef-automate-and-chef-infra-server). The Desktop dashboard has no supported compliance profiles, and Chef Desktop installation includes no compliance profiles. Note When installing Chef Automate with Chef Desktop, *Data Lifecycle* settings will not mark nodes as missing and not delete missing nodes by default. We encourage users to not change these specific settings and not defeat the monitoring purpose of the Desktop dashboard. Desktop Dashboard Display ------------------------- Within Chef Automate, the *Desktop* dashboard uses four panels to summarize information: *Daily Check-in* *Check-in History*, *Top 10 Errors*, and *Time since Last Check-in*. Selecting rows within these displays will list relevant desktops and selecting a singular desktop reveals its detailed information. The *Desktop* dashboard does not support project filtering. Node counts in the *Desktop* dashboard may include liveness agents. ### Daily Check-in The *Daily Check-in* display shows a top-level view of daily desktop check-in statistics. A bar graphic illustrates the proportion of desktops with `unknown` and `checked-in` statuses. Below the bar, boxes display counts of all desktops, desktops with an `unknown` status, and desktops with a `checked-in` status. `Checked-in` refers to desktops reporting into Chef Automate. `Unknown` desktops did not report to Chef Automate during the last twenty-four hours. Selecting a box will display a Filtered Desktop List of desktops for the selected status. The selected filters will not persist when selecting a different box. ### Check-in History *Check-in History* shows the history of checked-in desktop counts as graphed over a selected period of time. Use the drop-down menu to select a different period of time. The time period options are “Last 3 Days,” “Last 7 Days,” and “Last 14 Days”. ### Time Since Last Check-in The *Time since Last Check-in* display shows a count of desktops with an `unknown` status for defined timefames. Selecting a row will reveal a Filtered Desktop List of desktops for the selected timeframe. ### Top 10 Errors The *Top 10 Errors* display shows the ten most common errors that have occurred across all desktops over the last twenty-four hours, and a count of the machines that experienced each error. Selecting an error opens the Filter Desktop List with the applied error filter to enable further investigation. ### Filtered Desktop Lists Selecting rows in *Daily Check-in*, *Time since Last Check-in*, or *Top 10 Errors* activates the Filtered Desktop List. The Filtered Desktop List displays a list of desktops filtered according to the selected status, timeframe, or error in the previous display. Apply more filters to this initial list if desired. Specific filter values populate according to available desktop information and include the categories of “platform,” “environment,” “domain,” and “last run status.” Select an individual desktop row to display the individual desktop’s node details. #### Node Details The *Node Details* display shows the details of a single desktop and includes a visualization of its check-in history. The individual check-in history displays the desktop’s latest status for each day with an associated icon. Hover over a status icon to see the status label. Statuses include “converged” (check box icon), “unchanged” (dash icon), “error” (exclamation point icon), or “missing” (question mark icon). The timescale of the check-in history can also switch between “Last 2 Weeks” and “Last 4 Weeks.” The individual desktop has an information panel that displays the following data: Overview, Chef Infra Client, System, Virtualization, and Kernel. Select **Download** and choose the output format – **JSON** or **CSV** – to download the individual desktop’s historical data. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/desktop/IAM Actions =========== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/iam_actions.md) Reference the chart on this page when creating a *Role* to know which action grants access to what page in the browser. *IAM Action* lists the associated action or actions required to access that page in the browser. Use `*` in these actions to give broad permissions to perform all associated actions such as get, list, create, delete, etc. Specify the action to restrict user access to the specific action. | Task | Browser Tab | IAM Action | API endpoint | URL | | --- | --- | --- | --- | --- | | View Events | Dashboards | event:* | /event_feed | <https://automate.example.com/dashboards/event-feed> | | View and Search Events | Dashboards | [event:*, infra:nodes:list] | /event_feed | <https://automate.example.com/dashboards/event-feed> | | View Service Group Data | Applications | applications:* | /applications/service-groups | <https://automate.example.com/applications/service-groups> | | View Client Runs | Infrastructure | infra:nodes:* | /cfgmgmt/nodes | <https://automate.example.com/infrastructure/client-runs> | | View Chef Servers | Infrastructure | infra:infraServers:* | /infra/servers | <https://automate.example.com/infrastructure/chef-servers> | | List Reports | Compliance | compliance:reporting:* | /compliance/reporting/reports | <https://automate.example.com/compliance/reports/overview> | | List Scan Jobs | Compliance | compliance:scannerJobs:* | /compliance/scanner/jobs | <https://automate.example.com/compliance/scan-jobs/jobs> | | Manage Scan Jobs | Compliance | [compliance:scannerJobs:* , infra:nodes:* , infra:nodeManagers:* , compliance:profiles:* ] | /compliance/scanner/jobs | <https://automate.example.com/compliance/scan-jobs/jobs> | | Manage Compliance Profiles | Compliance | compliance:profiles:* | /compliance/profiles | <https://automate.example.com/compliance/compliance-profiles> | | Manage Notifications | Settings | notifications:* | /notifications | <https://automate.example.com/settings/notifications> | | Manage Data Feed | Settings | datafeed:* | /data_feed/destination | <https://automate.example.com/settings/data-feed> | | Manage Node Integrations | Settings | [infra:nodeManagers:* , infra:nodes:* , secrets:* ] | /nodemanagers , /cfgmgmt/nodes , /secrets | <https://automate.example.com/settings/node-integrations> | | Manage Node Credentials | Settings | secrets:* | /secrets | <https://automate.example.com/settings/node-credentials> | | Manage Data Lifecycle | Settings | dataLifecycle:* | /data-lifecycle | <https://automate.example.com/settings/data-lifecycle> | | Manage Users | Settings | iam:users:* | /iam/v2/users | <https://automate.example.com/settings/users> | | Manage Teams | Settings | iam:teams:* | /iam/v2/teams | <https://automate.example.com/settings/teams> | | Manage API Tokens | Settings | iam:tokens:* | /iam/v2/tokens | <https://automate.example.com/settings/tokens> | | Manage Policies | Settings | iam:policies:* | /iam/v2/policies | <https://automate.example.com/settings/policies> | | Manage Roles | Settings | iam:roles:* | /iam/v2/roles | <https://automate.example.com/settings/roles> | | Manage Projects | Settings | iam:projects:* | /iam/v2/projects | <https://automate.example.com/settings/projects> | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/iam_actions/Reports ======= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/reports.md) The *Reports* page (Compliance > Reports) provides comprehensive insight into the compliance status of all scanned infrastructure. Scan results for audit cookbook configurations also appear in this view. Note If the size of a Compliance Report is over 4MB, then the *Reports* page may not display as expected. ![Reports] ### Dates in Compliance Reports The dashboard shows the results of all scans with end times on the *current selected day*. The *current selected day* is based on timestamps in Coordinated Universal Time (UTC). The trend graph provides a historical overview of node status over time. You can change it to display overviews of the past 10 days, 1 month, 3 months, or 1 year. To view scan reports in the past, users can select a different date from the calendar located in the search bar. ![Reports Date Selector] ### Search Bar and Filters The Compliance search allows you to view and filter compliance scan results based on a defined set of filters. Wildcard searches on field values will not return suggestions, but they will filter the results. For example, you can search for `Node Name: prod*` and filter the results to list all the node names that begin with `prod`. Chef Infra Server Filter your results by Chef Infra Server. Chef Organization Filter your results by Chef organization. Chef Tag Filter your results by Chef tag. Control Tag Filter your results by control tag. Controls Filter your results by control name. Filtered results display the status of nodes that ran the selected control. Environment Filter your results by environment. InSpec Version Filter your results by Chef InSpec version. Node Name Filter your results by node name. Platform Filter your results by platform. Policy Group Filter your results by policy group. Policy Name Filter your results by policy name. Profile Filter your results by profile name. This lists executed profiles, which are profiles with received scan results. Recipe Filter by Chef recipe, on all applicable nodes. Role Filter by Chef role, on all applicable nodes. ### Deep Filtering Deep filtering provides reports on compliance profiles and controls. Apply deep filtering to see the compliance reporting for a profile version or one of its controls. Chef Automate saves computational time and storage space by calculating compliance reporting statistics at the aggregate level. Deep filtering uses the `profile_id` attribute to drill down to the granular level of your compliance status. In contrast, filtering with the `profile_name` attribute instead of `profile_id` creates a report for every version of `profile_name` in your infrastructure. Deep filtering supports reports for: * one profile * one profile and one of its associated controls #### Profile Deep Filtering Deep Filtering with `profile_id` scopes a compliance report to a versioned profile. To create a report at the profile level: ``` 1. Specify the profile in the filter using `profile_id` 1. Leave the control filter empty 1. Apply additional reporting filters ``` #### Control Deep Filtering Deep filtering for a control scopes a compliance report to a single control within a versioned profile. To create a report at the control level: ``` 1. Enter the `profile_id` in the filter 1. Add a control 1. Apply additional reporting filters ``` If the results returned by your deep filter are incorrectly scoped, review the `profile_id` and control field contents. ### Waivers A node’s waived status appears if applicable in displays where a node’s status appears in Chef Automate. The Compliance Reports overview displays the node count and history of waived nodes, and the count and history of waived controls. *Nodes* and *Profiles* views include *Waived Nodes* and *Waived Profiles* status filters respectively. Selecting the *Waived* status filter displays the respective Node or Profile reporting with the `waived` status. Hover over the control’s Waived icon under the Node Status column in *Controls* to view more details about the waiver applied to the control. Use Chef InSpec to configure [waivers](../../inspec/waivers/index). ### Download Report Results The download button located to the right of the search bar allows users to download a JSON or CSV format of the reports. The downloaded contents are the result of all of the applied filters–including end time selected in calendar. Compliance Status and Report Metadata ------------------------------------- The *Compliance Status and Report Metadata* bar is directly beneath the search bar. Expand the `Report Metadata` information by selecting the compliance status bar. The report metadata shows a summary of the nodes, report date, duration, status, number of platforms, number of environments, and number of profiles used in your scan. ![Reports Metadata] Compliance Overview ------------------- Toggle between *Node Status* and *Profile Status* to view your system’s compliance state. ### Node Status The *Node Status* view shows your system’s compliance status from the operational perspective of nodes. Node Status Shows the number of nodes that passed or failed compliance scans, and the number of skipped or waived nodes. Severity of Node Failures Shows the severity of the compliance scan failures on your system’s nodes. Node Status Over Time Shows the changes in size and compliance status of your system over time. Use the dropdown menu in the upper left corner to change the date range. Changing the date range also changes the displays in related charts and tables. Top Platform Failures Shows the number of compliance scan failures grouped by operating system. Hovering over an individual bubble shows the platform name and the number of failed nodes. Top Environment Failures Shows the number of compliance scan failures grouped by environment. Hovering over an individual bubble shows the environment name and the number of failed nodes. ### Profile Status The *Profile Status* view shows your system’s compliance status from the compliance perspective of Compliance profiles run during scans. Note The control count in the *Profile Status* pane (Reports > Profile Status) shows the total number of executed controls, not the total number of unique controls. Control Status Shows the number of controls in your system, grouped by passing, failing, and skipped controls. Severity of Control Failures Shows failed controls, ranked by number and importance of the control failure, grouped as critical, major, and minor. Control Status Over Time A line graph showing the number of controls and Compliance scan results over time. Use the calendar button in the upper right corner of the chart to change the time frame. Top Profile Failures Indicates the profiles with the highest failure rate. Hover over an individual bubble to show the full profile name and the number of failed nodes. Top Control Failures Indicates the most frequently failing controls. Hover over an individual bubble to show the control name and the number of failed nodes. Switching Views --------------- Switch your views by selecting the appropriate tabs and see compliance report results from the perspective of *Nodes*, *Profiles*, and *Controls*. ### Nodes The *Nodes* view provides more detailed insight into the compliance status of the nodes in your system. Sort this table by node name, platform, environment, last scan, and the number of control failures from the most recent compliance scan. Scroll to the bottom of the page for pagination navigation options. ![Reports Nodes] Node A node is any machine that is under management by Chef. Platform The operating system on your node, such as AIX, Amazon Linux, Apache, macOS, CentOS, Oracle Linux, Oracle Solaris, RHEL, SUSE Linux, Ubuntu, and Windows. Environment You can filter compliance reports by the environments in any stage of your workflow. Last Scan Time in hours, days, or months since the last scan on that node. Control Failures Shows the number of failing controls, if any. Filter Select the filter icon on the right side of the row to select a node. More Options Select the (&mldr;) icon to display a menu with two additional options: *Add Filter* and *Scan Results*. Use *Add Filter* to narrow the results to the `id` of the selected node. Use *Scan Results* to show the scan results of controls for the specific node in a side window. ### Profiles Use the **Profiles** tab to examine the compliance profiles installed under your individual user account. ![Reports Profiles] Profile Title The name of the profile obtained from the *Profile Store* or uploaded. Version The semantic version identifier of the profile; you may need to update your profiles to get the most recent version. Identifier The name under which the profile is installed and a short profile title. More Options Select the (&mldr;) icon to display a menu with two additional options: *Add Filter* and *Scan Results*. Use *Add Filter* to narrow the results to the `id` of the selected profile. Use *Scan Results* to show the scan results of controls for the specific node in a side window. ### Controls Use the **Controls** tab to examine the compliance controls installed under your individual user account. ![Reports Controls] Control Name Control name and short description of its purpose Profile Profile containing the controls Impact Importance of the control Last Scan When the last scan occurred Node Status Shows the number of failed, passed, and skipped nodes More Information Select the (&mldr;) icon to display a menu with one additional option: *Add Filter*. Use *Add Filter* to narrow the results to the `id` of the selected profile and to the `id` of the selected control. ### Individual Node Display The node name is at the top of the header, directly above the node compliance status. ![Reports Node Detail] The node history table displays the following information: Control Control name and short description of its purpose Severity Importance of the control Root Profile Profile containing the controls Test Results Number of tests within an individual control More Information Select the plus icon to display a control description and to toggle between **Results** and **Source**. **Results** describes the node compliance status and **Source** displays the Chef InSpec control source code. #### Scan History Select **Scan History** in the upper right corner to open a side-window. Choosing a compliance scan from this list redirects you to a view of all controls run during the selected scan. ![Scan History] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/reports/Client Runs =========== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/client_runs.md) Overview -------- The *Client Runs* page shows all nodes connected to Chef Automate, either directly or via a Chef Infra Server proxy. Nodes appear in this view after a Chef Infra Client run has executed. Chef Infra Client Run Status Overview ------------------------------------- The Chef Infra Client Run Status chart displays a summary of node statuses: failed, successful, or missing, as well as the total node count. The chart changes as you select filters. ![Client Runs Overview] Node List Table --------------- The node list table shows all nodes connected to Chef Automate. Filter the node list table by selecting any of the status tabs below the **Chef Infra Client Run Status** box. Sort the nodes listed on the table by selecting the arrows to the right of the column headers: *Node Name*, *Check-In*, *Uptime*, *Platform*, *Environment* or *Policy Group*. Selecting an entry in this table will take you to a *Node details* page with more information about the Chef Infra Client runs associated with this node. A node may be present in this table without any associated run history. This situation happens when data retention settings erase the most recent run history for such a node. In this case, a **no data** icon appears and you will be unable to view any node details. The node remains listed as a missing node until it is deleted from Automate. Automate automatically removes any nodes deleted from the Chef Infra Server. Node Details ------------ The Node Details table displays the most recent converge results. Find more information about *Resources*, *Run List*, and *Attributes* in the tabs below the node detail chart. Select the tabs to switch between these three views. *Resources* displays the status of the most recent resources as failed, successful, unchanged, or unprocessed. Selecting the tabs with these names will filter the list to show only those resources. *Run List* shows cookbooks, roles and recipes. For a node using policyfiles, you will be able to see the policy ID’s for each cookbook listed. *Attributes* shows an expandable list of node properties. Use the search bar to discover the node attributes by attribute name, key name, or value. The search results show by highlighting matching attributes. Use the *default*, *normal*, *override*, and *automatic* buttons beneath the search bar to filter attributes by to these categories. Learn more about [attributes](../../attributes/index). When looking at a failed Chef Infra Client run, select **View Error Log** at the top of the page to open a window showing the error message and backtrace. Use the downloaded button to save the error message. Selecting a node from the node list table opens the *Node details* page with the most recent information about that node. To look at past run data, select **Run History** on the upper right of the page, which opens a side panel containing historical run data. You can filter this data by using the Run Status icons and Date Range selections. Node history data supports up to three months of Chef Infra Client run information. Scroll through the node history using the pagination buttons at the bottom of the side panel. Use the **X** button at the top of the panel to close the side panel. Filtering --------- ### Search Bar Filter nodes from the search bar based on existing node information. You can apply more than one filter to a search. The node list table changes to display only nodes that match all applied filters. To apply a filter, first select the filter from the dropdown list and begin typing to display autocomplete options. To save a search, select **Share** to the right of the search bar, and copy the private URL. #### Node Filters [Attribute](../../attributes/index) Search for an attribute key, this will not search across attribute values. [Chef Organization](../../server_orgs/index) A Chef Infra Server organization name. [Chef Infra Server](../../server_overview/index) A Chef Infra Server URL. [Cookbook](../../cookbooks/index) A cookbook name. [Environment](../../environments/index) Nodes can have one environment. [Node Name](../../nodes/index#about-node-names) Name of the node. [Platform](../../platforms/index#chef-automate-server) OS Platform of a node. [Policy Group](../../policyfile/index#settings) Policy group name, only nodes using policyfiles will appear. [Policy Name](../../policyfile/index#settings) Name of the policy as set in policyfile.rb, only nodes using policyfiles will appear. [Policy Revision](https://docs.chef.io/release_notes_server/#policiesnamerevisions) The policy revision ID, only nodes using policyfiles will appear. [Recipe](../../recipes/index) A recipe within a cookbook. [Resource Name](../../resources/index) A resource within a cookbook. [Role](../../roles/index) Search by nodes assigned to a role. Nodes can have zero or multiple roles. See more about [policyfiles](../../policyfile/index). Managing Node Data ------------------ ### Managing Missing Nodes Configure the timing for labeling nodes as missing and then deleting them from [Data Lifecycle](../data_lifecycle/index) on the Settings tab. ### Deleting Missing Nodes Admins and users with the relevant permissions defined in access policies can delete missing nodes from the Chef Infra Client Runs page. You cannot delete active nodes. To delete one or more missing nodes, tick the checkbox to the left of the node name, and then select the red **Delete** button above the table header. Confirm the delete action in the pop-up window. To delete all missing nodes, tick the checkbox at the top of the Client Runs table, which selects all missing nodes on the current page. The user can choose to deselect individual nodes by unchecking the checkboxes next to nodes. Select the delete button and confirm the delete action in the pop-up window. ### Deleting Missing Nodes from the Command Line Delete nodes using the Chef Automate CLI or through the Chef Automate REST API. To delete a node from the *Client Runs* page using the Chef Automate CLI, first locate the `node ID` on the *Node Details* page, and then use this node ID with the `node-delete` command: ``` chef-automate infrastructure node-delete 3f2a2830-0ef3-474a-a835-3a7dd25361fe ``` To delete nodes using the REST API, use the `"https://automate-url/api/v0/ingest/events/chef/nodedelete"` endpoint to delete a single node, or the `"https://automate-url/api/v0/ingest/events/chef/node-multiple-deletes"` endpoint to delete multiple nodes. Identify your node or nodes with either the *node_id* –which is the UUID of the node as it appears in Chef Automate–or the combination of *node name*, *organization name*, and *service hostname*. The *service hostname* is the `fqdn` of your Chef Infra Server, or the `localhost` of chef-solo nodes. #### Request for deleting a node using the *node_id* ``` curl -sSX POST "https://automate-url/api/v0/ingest/events/chef/nodedelete" -d '{ "node_id": "3f2a2830-0ef3-474a-a835-3a7dd25361fe" }' -H "X-Data-Collector-Token: $TOKEN" ``` #### Request for deleting multiple nodes using the *node_id* ``` curl -sSX POST "https://automate-url/api/v0/ingest/events/chef/node-multiple-deletes" -d '{ "node_ids": ["3f2a2830-0ef3-474a-a835-3a7dd25361fe", "9c139ad0-89a5-44bc-942c-d7f248b155ba"] }' -H "X-Data-Collector-Token: $TOKEN" ``` #### Request for deleting a node using the *node name*, *organization name*, and *service hostname* ``` curl -sSX POST "https://automate-url/api/v0/ingest/events/chef/nodedelete" -d '{ "node_name": "somenode", "organization_name": "yourorg", "service_hostname": "chef-infra-server-fqdn" }' -H "X-Data-Collector-Token: $TOKEN" ``` ### Managing Ephemeral Nodes Chef Automate considers the instances of ephemeral nodes, which are nodes that are frequently created and destroyed, as new nodes by default, even if the node indefinitely uses the same name. Set Chef Automate to consider ephemeral nodes as manifestations of the same node by configuring the UUID on the client side. Configuring the UUID on the client side keeps the node associated with the same id, which makes Chef Automate consider it as the same node every time it recreates. In the node’s `client.rb`, set `chef_guid` to the *desired UUID*. If the node already exists, check that it uses the correct UUID, otherwise it will appear as a new node the next time it recreates. See the `client.rb` documentation for more information about [configuring your client nodes](../../config_rb_client/index). The following are the configuration parameters available: | Parameter | Type | Explanation | Format | Default | | --- | --- | --- | --- | --- | | `threshold` | string | The duration after which unreported nodes are marked as missing. | `1h30m`, `1m`, `2h30m`, `1d`, etc. | `1d` | | `every` | string | How often to scan the nodes to check if they are missing. | `1h30m`, `1m`, `2h30m`, `1d`, etc. | `15m` | | `running` | boolean | Is the job running? Set to false to turn off missing node functionality. | n/a | `true` | Below is an example curl command: ``` curl -sSX POST "https://automate-url/api/v0/retention/nodes/missing-nodes/config" -d '{ "threshold": "1d", "every": "15m", "running": true }' -H "api-token: $TOKEN" ``` You will need an [API token](../api_tokens/index#creating-api-tokens) to send API requests. ### Configuring Data Cleanup By default, Chef Automate prevents irreversible destructive operations by keeping deleted node history in Elasticsearch, unless users configure this functionality. Chef Software recommends setting the `threshold` for destroying deleted node history to 1 day and running data cleanup every 15 minutes. Available data cleanup configuration parameters: | Parameter | Type | Explanation | Format | Default | | --- | --- | --- | --- | --- | | `threshold` | string | The duration after which nodes marked for deletion are removed. | `1h30m`, `1m`, `2h30m`, `1d`, etc. | `1d` | | `every` | string | How often to scan for marked nodes for deletion and removal. | `1h30m`, `1m`, `2h30m`, `1d`, etc. | `15m` | | `running` | boolean | Is the job running, set to true to turn on data cleanup functionality. | n/a | `false` | Below is an example curl command with the recommended data cleanup settings: ``` curl -sSX POST "https://automate-url/api/v0/retention/nodes/delete-nodes/config" -d '{ "threshold": "1d", "every": "15m", "running": true }' -H "api-token: $TOKEN" ``` You will need an [API token](../api_tokens/index#creating-api-tokens) to send API requests. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/client_runs/Applications Dashboard ====================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/applications_dashboard.md) The Chef Automate *Applications* dashboard allows you to organize and display your applications data from Chef Habitat in an intuitive way. Chef Automate organizes data from the application and environment tags provided by the Chef Habitat supervisor. Under the Chef Automate *Applications* dashboard, the *Service Groups* display lets you understand the status of your Chef Habitat services, even when scaling out to large numbers of services. Prerequisites ------------- The Chef Automate EAS applications feature introduces concepts from Chef Habitat, as introduced in the [Glossary](../eas/index#Glossary). See [Setting up the Applications Dashboard](../applications_setup/index) for instructions on configuring Chef Automate and Chef Habitat to work together. Service Groups -------------- Service groups are Chef Habitat services, which Chef Automate orders by package identifiers and configurations. The *Applications* dashboard *Service Groups* display gives you a top-level view of your Chef Habitat services groups and lets you drill down into the status of individual instances to understand the health and contentents of any individual instance of a service. The default *Service Groups* view shows only the services that are available. The right sidebar provides detailed reporting for each individual service. ![EAS Service Groups List](https://docs.chef.io/images/automate/eas-service-groups.png) ### Service Health Status Count The *Service Health Status Count* is the first collection of information on the page, which is a series of five containers. The first container on the left reports the total number of service groups and the remaining containers sort the services into four categories of criticality, on the basis of the health status of the most critical service in the group. The service health status containers are *Critical*, *Warning*, *OK*, and *Unknown*. Each service group is classified by its most critical service, which means that if any one instance in a service group reports a “critical” status, then Chef Automate counts that entire group counts as having a “critical” status. Selecting a container changes the Service Groups table to display only the service groups reporting with that health status. ### Service Groups Table Each row of the *Service Groups* table displays the results for an individual service group. The rows sort according to the highest criticality, meaning that the service groups reporting the lowest percentage of healthy services–and the highest percentage of “critical” services–appear at the top. By default, the table rows sort from the smallest to the largest percentage of “OK” services. Selecting the *Health* column reverses the order, and displays the percentage of “OK” services from largest to smallest. ### Health Under the *Health* column, the donut chart display shows the proportion of health status via color for the service group. The percentage inside the circle shows the percentage of services with the *OK* status. A corresponding status icon with a matching color appears next the circle display if applicable. For example, if a service group is 20% *OK* and 80% *Critical*, a magenta triangle exclamation icon appears next to the service group’s circle display and draws attention to the critical status. If there are multiple Service Groups with the same *OK* health percentage, then the Service Groups will display in the same order of priority: *Critical*, *Unknown*, and *Warning*. ### Service Group The *Service Group* column lists the Service Group name and the number of healthy services, which are services reporting an *OK* status, out of the total number of services in the group. A broken chain icon appears if there are any disconnected services in the group, along with the number of disconnected services. ### Additional Service Group Information The *Package* column shows the origin and package name. The *Release* column displays the version and build in use. The *Env* column, which is short for *Environment*, contains the deployment environment of the service group. The *App* column, which is short for *Application*, displays the application name. Service Group Details Sidebar ----------------------------- Selecting a Service Group in a row populates the right-hand sidebar with information about each service in the Service Group. To filter the individual services in the side bar by their health status, select one of the health status buttons at the top of the sidebar. The individual service rows sort by their level of criticality, from the “most critical” status to the “least critical” status - “critical”, “warning”, “unknown”, and “OK” respectively. Individual disconnected services display a broken chain icon with a note of when the last received health check ocurred. The most critical issues appear at the top of the list, allowing you to determine the next steps for remediation. Filtering Results ----------------- Use the search bar at the top of the page to filter the results in the main table. Select the search bar, select your search field type from the drop-down menu. Available search field types include *Origin*, *Service Name*, *Version*, *Channel*, *Application*, *Environment*, *Site*, *Build Timestamp*, and *Group Name*. After selecting your search field type, enter your specific search term, or select one from the auto-populated list of existing values. Applying the filter changes the Service Groups list to display matching results and updates health status display accordingly. ![EAS Filtered Service Groups List](https://docs.chef.io/images/automate/eas-filtered-service-groups.png) Lifecycle Management -------------------- Disconnected services are defined services that have not reported back with a health check message for a user-defined period of time. Use the [Service Group Data Lifecycle settings](../data_lifecycle/index#service-groups) to manage the activity of periodic jobs, and to assess disconnection status and removal of services. ### Periodic Disconnection Checks Chef Automate assesses the status of Chef Habitat services based on the receipt of a health check message. Chef Automate marks a node as disconnected when it does not receive a health check message in a set amount of time. Use the `threshold` configuration to set the amount of time between the last node health check message and when Chef Automate marks it as disconnected. Health checks are mandatory and you cannot disable health checks. The default time for a node to report to Chef Automate is 5 minutes. Chef Habitat sends the health check messages every 30 seconds by default. Configure this setting using the `--health-check-interval` option with the `hab sup run` command. See the [Habitat CLI documentation](../../habitat/habitat_cli/index#hab-sup-run) for more information. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/applications_dashboard/IAM Users Guide =============== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/iam_v2_guide.md) Note This documentation covers Chef Automate’s IAM feature in release 20200326170928 and later. This guide shows you how to perform important administrative operations. You will add members to Chef-managed v2 policies, delete a legacy policy, and write a Team Admin v2 policy that lets a Team Admin manage their users and teams. View Policies ------------- After you have signed in to Chef Automate, select the **Settings** tab in the top navigation bar, and then select and locate the `Policies` section in the left navigation. In this section, you can view all of your v2 policies. This policy display includes the following: * New default, *Chef-managed* policies: Administrator, Ingest, Editors, and Viewers. * Imported v1 default policies–now called *legacy policies*–in the new v2 policy format and marked with the `[Legacy]` prefix. * Imported v1 custom policies that you created, which are marked with the `[Legacy]` prefix and a `(custom)` suffix. ![] Policy Conversion ----------------- If you started on IAM v1 and migrated your IAM v1 policies to IAM v2, then you should move any members of your IAM v1 legacy policies to the appropriate IAM v2 policies, and afterwards, delete the IAM v1 legacy policies. To delete a legacy policy, open the menu on any custom policy, which is located at the end of the policy row, and select **Delete Policy** from the menu. A warning appears if members are still attached to the policy because deleting that policy disrupts access for all of its members. However, you will still be able to delete the policy. The next few sections explain how to use Chef-managed policies and how to create custom policies. ### Using Chef-Managed Policies In this example conversion, you will create two local users and add them to default teams that are automatically included in default policies. Note that you could also add users directly to policies without the intermediate teams, but using teams can make managing your system more flexible. #### Create Users Follow the instructions on [Creating Users](../users/index#creating-local-users) to: * Create a local user with the username `test_viewer`. * Create a local user with the username `test_editor`. #### Add Users to Teams Select `Teams` from the left navigation of the **Settings** tab. Three teams are provided by default: `admins`, `viewers`, and `editors`. Follow the instructions for [Adding Users to a Team](../teams/index#adding-local-users-to-teams) to: * Add the user `test_viewer` to the Chef-managed `viewers` team. * Add the user `test_editor` to the Chef-managed `editors` team. After upgrading, those teams will be part of the `Viewers` and `Editors` policies, respectively. The default `Viewers` policy is provided, so you can quickly grant read-only access to everything in Chef Automate, except for admin resources. Similarly, the default `Editors` policy is provided, so you can quickly grant complete access to everything in Chef Automate, except for admin resources. Once this step is done, the `test_viewer` and `test_editor` users may log in with appropriate system access. ### Creating Custom Policies The Chef-managed policies give you a starting point for permissions. You may want to write more fine-grained policies, tailored to the demands of your organization. Defining your own policies must be done from the command line. As an example, let us say that you, the admin, want to delegate a portion of your tasks to a colleague, but without granting them full admin access. In this case, you could create a policy called `Team Devops Managers`, which grants its members some–but not all–administrative privileges. Create a JSON file in the editor of your choice. Following JSON syntax, begin with the name property. See the end of this section for a [complete JSON policy example](index#complete-json-policy-example) ``` "name": "Team Devops Managers", ``` The `name` field is for human consumption. When you want to refer to the policy in commands, you will need to know the policy’s ID. Let us give this policy the ID value: `team-managers-devops`. ``` "id": "team-managers-devops", ``` Additionally, we can permission actions on this policy just like any other IAM resource by assigning it to one or more projects. If we leave the projects array empty, then we indicate the policy is *unassigned*. For example, anyone with permission to view *unassigned* policies can view this policy. ``` "projects": [], ``` Let us further assume you want user `Bob` as well as anyone on team `gamma` to be authorized by this policy. This grouping comprises the `members` array, as seen below. ``` "members": [ "user:local:bob", "team:local:gamma", ], ``` Next, you will specify the permissions themselves–which in IAM v2 are the `statements`– declared as an array. The statement allows us to specify the `actions` a user is permitted to take upon resources that have been assigned to a `project`. The `projects` field on a statement is an array that may contain more than one existing project, a wildcard `*` to indicate permission to resources in *any project*, or `(unassigned)` to indicate permission to resources that have not been assigned to a project. Note that the `projects` property in statements designates permission for the resources within the statement (here, that is `iam:users` and `iam:teams`), *not* for the policy itself, and *cannot* be left empty. For more about projects, see [Projects in the IAM Guide](index#projects) documentation. In this case, we only need a single statement providing access to the *get*, *list*, and *update* actions for *users* and *teams* that have been assigned to the project `project-devops`. ``` { "effect": "ALLOW", "actions": [ "iam:users:update", "iam:users:list", "iam:users:get", "iam:teams:update", "iam:teams:list", "iam:teams:get" ], "projects": ["project-devops"], }, ``` #### Complete JSON Policy Example ``` { "name": "Team Devops Managers", "id": "team-managers-devops", "projects": [], "members": [ "user:local:bob", "team:local:gamma" ], "statements": [ { "effect": "ALLOW", "actions": [ "iam:users:update", "iam:users:list", "iam:users:get", "iam:teams:update", "iam:teams:list", "iam:teams:get" ], "projects": ["project-devops"] } ] } ``` Save your JSON file and refer to the [IAM Policies API reference](https://docs.chef.io/automate/api/#tag/policies) to send that policy data to Chef Automate. ### Policy Membership Users, teams, and API tokens can all be policy members. Both users and teams can be either locally or externally managed with LDAP or SAML. #### Local Users and Teams Local users and teams are managed directly by Chef Automate. To add or delete members, navigate to the Policies list in the **Settings** tab, and then select a policy in the list to open its details. Select **Members** to view the current membership. Use the **Add Members** button to open a list of candidate members. This lists all those local members (both users and teams) that are *not* members of this policy. If all of the local members are already included in the policy, then this list will be empty. Select any members you wish to add to the policy. Use the **Add Members** button to complete the operation. This takes you back to the policy details, showing the revised membership list. #### Member Expressions Member expressions are required for externally managed users, and teams, as well as API tokens. LDAP and SAML users' information is saved outside of Chef Automate. You will need to manually enter the provider-qualified user or team. To do this, open any policy from the *Policies* list, then select **Members**. Select **Add Members** to open the list of candidate local users and teams. Near the bottom of the page, select the **Add Member Expression** button. Note The member expression dialog box appears after selecting **Add Member Expression** and guides you through creating a member expression. This dialog box ensures correct syntax use in a user-friendly way. The next few paragraphs explain the syntax if you want to add members via the API. Enter a member expression using the format `team:<type>:<name>` or `user:<type>:<name>`. Note that these expressions are case-sensitive. * The `<type>` expression is either `ldap` or `saml`. * The `<name>` expression is the name of the user or team that the external identity provider knows. For example, this is a valid member expression `team:ldap:editors_team_1`, assuming the `editors_team_1` team is known by your identity provider. Alternately, you may add *all* teams to a policy using a wildcard as the last term in the member expression: `team:ldap:*` or `team:saml:*`. The member expression dialog also supports tokens. You enter a token using the expression `token:<id>`. In order to find a token’s ID, visit the *API Tokens* page. ### Projects Projects are used to group and permission Chef Automate resources as well as ingested data, specifically Compliance reports, Chef Infra Server events, and Infrastructure nodes. Projects can be managed via the Projects list under the **Settings** tab and consist of an ID, a name, and a collection of ingest rules. Project ingest rules are lists of conditions used only when [assigning ingested resources to projects](index#assigning-ingested-resources-to-projects), so they are not relevant when assigning IAM resources such as teams or roles. #### Configuring Project Limit By default, Chef Automate limits you to 300 projects. You can increase the project limit using the command line. First, write the file with your new project limit: ``` cat << EOF > authz.toml [auth_z.v1.sys.service] project_limit = <desired-max-projects> EOF ``` Then, update the existing Chef Automate configuration: `chef-automate config patch authz.toml` Note: As a consequence of increasing the project limit, you may see slower loading times in the UI. #### Creating a Project To create a project, navigate to the Projects list under the **Settings** tab and select **Create Project**. You will need to provide a name and can optionally edit the ID. You must create a project before you can assign any resources to it. When you initiate the project creation, the system creates the project, but also three supplemental policies for your convenience: | Policy Name | Policy ID | Associated Role | | --- | --- | --- | | `<project-name>` Project Owners | `<project-name>`-project-owners | Project Owner | | `<project-name>` Project Editors | `<project-name>`-project-editors | Editor | | `<project-name>` Project Viewers | `<project-name>`-project-viewers | Viewer | These policies are discussed in more detail in [Project Policies](index#project-policies). #### Assigning Teams and Tokens to Projects Projects can be assigned to Automate-created teams or tokens on creation or update. To assign a team to projects, select a team from the *Teams* list, then select **Details**. Likewise, to assign a token to projects, select a token from the API tokens list, then select **Details**. In either case, you can select projects from the projects dropdown to assign. You may also assign teams and tokens to projects on creation. In the creation modal, select any projects to which the new resource should belong. If you would like to delegate ownership of a project to another user so that they may assign resources, you will want to make that user a [Project Owner](index#project-owners) of that project. #### Assigning Ingested Resources to Projects While Automate’s local teams and tokens can be directly assigned to a project, ingested resources must be assigned to projects using ingest rules. Project ingest rules are used to associate ingested resources with projects within Automate. An ingest rule contains conditions that determine if an ingested resource should be moved into the rule’s project. Each condition contains an attribute, operator, and value. See [IAM Project Rules API reference](https://docs.chef.io/automate/api/#tag/rules) for details on how to manage project rules. In this example, after [creating a project](index#creating-a-project) with the ID `project-devops`, you will add an ingest rule to this new project. You will update projects to apply this new project rule, causing all matching ingested resources to be associated with `project-devops`. You will then use the global project filter to filter your ingested data by `project-devops`. First, determine which ingested resources should belong to the project. In this example, we want to add the following ingested resources to `project-devops`: * Compliance reports with Chef Organization `devops` * Infrastructure nodes with Environment `dev` and Chef Tag `devops-123` * Actions on Chef Infra Servers `devops.pizza` or `devops.dog` You may want to verify that those filters work as expected on the *Event Feed*, *Client Runs*, and *Reports* pages. Navigate to the project details page of `project-devops`, by selecting the project name on the project list page. Select the `Create Rule` button to create a new project rule. Choose the resource type `Node`, then fill in the first condition’s fields. Feel free to create fake ingest data that corresponds to the example json below, or come up with a condition that matches your existing data set. Warning Compliance reports must be using **audit cookbook 7.5+** in order to make use of all of the available project rule attributes. Older reports will only have **Environment** and **Chef Role** available as attributes. ``` { "id": "devops-rule", "name": "devops rule", "type": "NODE", "project_id": "project-devops", "conditions": [ { "operator": "EQUALS", "attribute": "CHEF_ORGANIZATION", "values": [ "devops" ] } ] } ``` ![] Save the rule. If you later need to change the name or the conditions, select the project rule name on the project details page. When edits are pending, a banner will be shown at the bottom of every page. Selecting the `Update Projects` button on that banner will apply those changes. ![] Updating a project begins an operation that applies all pending rule edits and then moves ingested resources into the correct projects according to those latest changes. An ingested resource is moved into a project if it matches at least one of the project’s rules. In this example, upon successful update, all ingested resources whose Chef Organization matches `devops` will be considered a part of the project `project-devops`. Only these resources will appear in Automate’s dashboards when the `project-devops` project has been selected in the global project filter. A percentage count appears in the bottom banner while the operation takes place. You may cancel the update at any time by selecting the `Stop Project Update` button in the banner and confirming the cancel in the modal that pops up. Warning Avoid stopping an update unless absolutely necessary. It will leave your system in an unknown state where only some resources have been moved into their projects while others still remain in old projects. Only another successful update will restore the system to an up-to-date state. Once rules have been successfully applied, the banner will be dismissed until the next time there are *pending edits* to any project. To verify that the ingested resources have been moved into the correct projects, select `project-devops` in the global projects filter, which is on the top navigation. The data in Automate filters by the selected `project-devops` project. In this example, the effect is revealed by navigating to the Compliance Reports' Nodes tab, which only features nodes that belong to the `devops` Chef Organization. ![] Now that we have the first set of our ingested data associated with our new project, let us add another condition and a new rule to add more data to `project-devops`. Note Compliance and Infrastructure ingested resources are not the exact same nodes, so their properties may not be the same. Separate conditions governing said resources *may* need to be used if their properties do not match exactly. Note Ingested events require conditions of `Event` type to be associated with the correct project. A condition of type `Node` will not match an event, even if the condition’s operator, attribute, and value all match exactly (and vice versa with `Event` project rules and nodes). Return again to the project detail page and create two new ingest rules by selecting `Create Rule`. Creating new rules will expand the data set under `project-devops`, because an ingested resource need only match one rule to be placed in the project. The first rule should contain two conditions. Fill in the first condition with attribute `Environment`, operator `equals`, and value `dev`, or any value matching your data set. Select `Add Condition` to add another condition with attribute `Chef Tag`, operator `equals`, and `devops-123`. Save the rule. Note Adding conditions further restricts the ingested data because every condition must be true for an ingested resource to be placed in the project. For the second rule, choose resource type `Event`. Fill in the first condition with attribute `Chef Server`, operator `member of`, and value `devops.pizza, devops.dog`, or any values matching your data set. Setting the project rule `Resource Type` determines what condition attributes are available to select. `Event` rule conditions can only have the attributes `Chef Organization` or `Chef Server`. Rules of type `Node` can have conditions with attributes `Chef Organization`, `Chef Server`, `Environment`, `Chef Role`, `Chef Tag`, `Chef Policy Name`, `Chef Policy Group`. Select the `Update Projects` button from the bottom banner. Upon completion of the update, you should be able to filter by `project-devops` across Automate’s dashboards and see only the ingested data that you expect. #### Effortless Infra Project To create a project that contains all Effortless Infra nodes, create a ingest rule with resource type `Node` and a condition that uses attribute `Chef Server`, operator `equals`, and value `localhost`. ![] The above rule matches on a node’s Chef Infra Server field, which is set to `localhost`. This rule works because all Effortless Infra nodes list the `Chef Infra Server` attribute as `localhost`. If desired, create subgroups of Effortless Infra nodes by adding a second condition that matches a specific `Chef Policy Name`. #### Project Policies When you create a project, Chef Automate automatically creates three supplemental policies. This next table further describes the roles associated with these policies. | Policy Name | Role | Description of role | | --- | --- | --- | | `<project-name>` Project Viewers | Viewer | **View** everything in the project *except* IAM | | `<project-name>` Project Editors | Editor | **Do** everything in the project *except* IAM | | `<project-name>` Project Owners | Project Owner | Editor + **view** and **assign** projects | Consider the **Project Viewers** policy, which uses the **Viewer** role. The same **Viewer** role is also used in the default **Viewer** policy, which lets a user view everything in the system except IAM. Using the **Viewer** role in **Project Viewers** policy restricts the scope to your new project, and users attached to your **Project Viewers** policy will be able to view objects only associated with your project. Assume you named your project `Devops`, and have two users: Terry and Kelly. If Terry needs to *view* `Devops`-scoped resources, then add Terry as a member to the `Devops` Project Viewers policy. If Kelly needs the ability to *edit* `Devops`-scoped resources, then add Kelly to the `Devops` Project Editor policy. When Terry is a member of the `Devops Project Viewers` policy and not a member of any other policy, they will only be able to see resources assigned to `Devops`. They will not be able to update or delete them. Kelly, however, will be able to update and delete. See [Policy Membership](index#policy-membership) for more information on policy membership. Restoring Admin Access ---------------------- While we have safeguards to prevent it, it is possible to lock yourself out of Chef Automate. If you have root access to the node where Chef Automate is installed, use the following commands to restore admin access: This command resets the local `admin` user’s password and ensures that the user is a member of the local `admins` team, which is a permanent member of the Chef-managed `Administrator` policy. ``` chef-automate iam admin-access restore <your new password here``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/iam_v2_guide/Scan Jobs ========= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/scan_jobs.md) Overview -------- A scan job is the equivalent of running `inspec exec` against a given set of targets. The results of a scan job are sent to compliance reporting. Any profiles installed to the user’s namespace may be used in a scan job. ### Scanning Run scan jobs on: * manually added nodes * aws-ec2 instances * aws-api regions * azure-vm virtual machines * azure-api subscriptions ### Scheduled Jobs Jobs may be scheduled to be executed now, at some later point in time, as a one-off job, or a job that is executed at a given interval (like once a day, or every two hours). ### Creating a Job When creating a scan job via ui, the user may select one or many managers. These managers would be the `Automate` manager (for nodes added manually in the ui), as well as any other managers added via the integrations (such as `aws-ec2`, or `aws-api`). The user may then build a query based on the base manager used to limit the set of items being scanned. ### Create a Scan Job Using the API ``` curl -sSX POST "https://automate-url/api/v0/compliance/scanner/jobs" -d '{ "name": "my scan job", "tags": [], "type": "exec", "profiles": [ "https://github.com/dev-sec/linux-baseline", # external url profile "compliance://admin/linux-baseline#2.1.1" # installed profile (see profile) ], "recurrence": "FREQ=HOURLY;INTERVAL=1", "nodes": ["6c0c7942-acb6-4ede-8a3a-bf8f6beee362"], # this field can be used to run a job on a specific (static) node "node_selectors": [ { "manager_id": "e69dc612-7e67-43f2-9b19-256afd385820", "filters": [ {"key": "name", "values": ["vj-nodes*"]}, # query by name of manually added nodes {"key": "my-manual-node-tag-key", "values": ["unicorn"]} # query by tags of manually added nodes ] }, { "manager_id": "2683f1f2-ebfd-4faa-807b-7801ec28ed17", # we could pretend this is the uuid for a user's aws-ec2 mgr "filters": [ {"key": "region", "values": ["eu*", "us-east-1"], "exclude": true }, {"key": "Name", "values": ["test*"]}, {"key": "X-Contact", "values": ["vjeffrey"]} ] } ] }' -H "X-Data-Collector-Token: $DC_TOKEN" ``` ### Supported Filters * manual nodes mgr + name (exclude/include, multiple values, wildcard match) + tags(by key) (exclude/include, multiple values, wildcard match) + status (reachable, unreachable) * aws-ec2 mgr + region (exclude/include, multiple values, wildcard match) + tags(by key) (exclude/include, multiple values, wildcard match) * aws-api mgr + region (include, exclude, multiple values, exact match (“us-east-1”)) * azure-vm mgr + region (exclude/include, multiple values) + name (include/exclude, wildcard match only supported for include) + tags (include, multiple values, exact match) * azure-api mgr + subscriptions (include, exclude, multiple values, exact match) ### Manual Nodes For users that wish to scan nodes that are not otherwise discoverable via integrations, we provide a `manually added nodes manager`. Users may add nodes via ui or api, specifying the node’s ip/hostname, port configuration, and sudo requirement (if any). In order to be able to run a scan job on a node, the correct set of ssh, winrm, and/or sudo credentials must be associated with that node. This is done by associating the desired credential ids with the node. ``` curl -sSX POST "https://automate-url/api/v0/nodes" -d '{ "name": "my-localhost-node", "tags": [ "key": "department", "value": "engineering" ], "target_config": { "backend": "ssh", "secrets": ["df312aa3-99c8-4f8a-af81-067307b31ee6"], "port":22, "sudo":false, "host":"localhost" } }' -H "X-Data-Collector-Token: $DC_TOKEN" ``` ### Unreachable and Reachable (status) Whenever we are provided with information about a scannable node, we run a detect job (`inspec detect`) against that scannable node. If we are able to successfully connect, it is marked as reachable. An unreachable scannable node will have an error message attached to it. A user may edit the credentials associated with the item to resolve the problem, or in some cases a user may just want to rerun a node (as in the case of a network error). ``` curl -sSX GET "https://automate-url/api/v0/nodes/rerun/id/d92b0c26-0c9a-4a04-b694-82fa979b2578" ``` ### How to Add an Environment Value for Project Assignment When creating a manually added node, use the ‘Environment’ tag to assign an environment to the node. `Environment` is the only supported field for project filtering on scan job results. ![Manual Node With Environment Tag] ### FAQ * I scheduled a job to run against my aws-ec2 instances once a day. What happens when I add new instances to the account, or remove some? Every time the scan job is scheduled to run, we will query the provider for a current list of nodes, so we always have the most current list. These are the instances we will run the scan job against. If a query (limiting the set of items to scan) was included during job creation, we will also respect that query against the most current list of instances. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/scan_jobs/Event Feed ========== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/event_feed.md) Use the *Event Feed* for actionable insights and operational visibility. The *Event Feed* shows the time of the event, its type, the object acted upon, the action, and the initiating action. The Guitar Strings visualization helps you drill into infrastructure and compliance automation events and quickly isolate errors. Users require permission for the `event:*` action to view and interact with *Event Feed*. Filter and search ability in *Event Feed* requires user permission for the `infra:nodes:list` action. ![Event feed] Event Guitar Strings -------------------- The Event Guitar Strings is a timeline representing Chef Infra Server and Compliance events. The events are separated into create, update, and delete. Blue circles show create events, red circles show delete events, and purple diamonds show update events. The icons inside of the shapes represent different types of events, and a multi-event icon denotes a case where multiple events happened within the same 4-hour window. Hovering over the icon shows a text box summarizing the events for that 4-hour window. Icon Legend ----------- ![Event feed icon legend] Grouped Events -------------- The *Event Feed* groups events of the same type by the same user. The event list entry shows how many events are grouped into an individual entry, which is also a link. Selecting this link opens a side panel showing the details of the collapsed events. Filtering Events ---------------- To filter the event feed and event timeline by Event Type, Chef Infra Server, or Chef Organization, use the search bar. The search bar appears to users with permission for the `infra:nodes:list` action. Available event type filters are clients, cookbooks, data bags, environments, nodes, policyfiles, profiles, roles, and scan jobs. To filter, select Event Type, Chef Infra Server, or Chef Organization in the search bar and start typing the name. You cannot filter compliance events – profiles and scan jobs – by organization or Chef Infra Server. Compliance events are not visible when either of these filters are applied. You can also filter the *Event Feed* event timeline by day or by set of days within the past week. The *Event Feed* defaults to show all events in the past week. Moving the indicators to the right or left will activate the filter. You can move the indicators back to their start position to reset the time scale. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/event_feed/Profiles ======== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/profiles.md) Overview -------- Compliance profiles help you secure your infrastructure continuously. Chef Automate compliance profiles translate CIS Benchmarks and other security standards into easily readable policy. You can install and download one of our 300+ ready-to-use compliance profiles from Profiles, or upload your custom profiles. ![Chef Automate Profiles] Using Profiles -------------- Navigate to compliance profiles by selecting the **Compliance** tab and then selecting the *Profiles* page, or by heading to `https://automate.example.com/compliance/compliance-profiles`. Profiles has a search bar and two views: the *Profiles* page, which displays the profiles you’ve installed in your unique namespace within Chef Automate, and the *Available* page, which displays all of the ready-to-use compliance profiles in Chef Automate. ### Installing Profiles ![Available Profiles] Locate profiles by browsing the list, or by using the search bar. To install a compliance profile into your namespace, simply select **Get** on the right side of the profile name. Download compliance profiles to your workstation for use with [*Scan Jobs*](../scan_jobs/index) and the [*Audit Cookbook*](https://github.com/chef-cookbooks/audit/blob/main/README.md), or as a basis for your own customizations. Start by selecting the arrow on the far right side of the profile, which redirects you to the *Profile Details* view. Select the download button on the upper right corner of the profile description and download your selected profile as a tarball compressed with gzip ('.tar.gz'). ### Uploading profiles Upload Any InSpec2 compatible profile–including inherited profiles–to Chef Automate with the **upload** button on the *Profiles* page. Uploads use either the `.tar.gz` or zip archive file formats. All profiles are stored in PostgreSQL, and are covered by backup and restore functionality. Note All profiles should have a valid version in their `inspec.yml`. Older builds of Chef Automate require at least three elements of the x.y.z form – for example, “1.2.0” – and optionally can have one additional element, such as “1.2.0-20”. Newer Chef Automate builds allow both two-element and three-element profile versions. ### Updating profiles New releases of profiles are shipped with the product when available. Chef ships only the latest versions of profiles. When Chef publishes a newer profile version that a user has installed to their namespace, a small notification appears, prompting the user to download the newest version. Installing the newest version adds the updated profile to the user namespace, but it does not overwrite an existing profile. You can keep multiple versions of a profile and it is up to you to curate your installed profiles. Understanding Profiles ---------------------- The *Profile Details* page appearance varies, depending on if a profile is installed or not. You can **Get** or **Download** uninstalled profiles from the details page of an uninstalled profile. You can **Download** or **Delete** a profile from the page of an installed profile. Deleting a profile removes it from the profiles collection in your namespace, but it remains available in Profiles. Installed or uninstalled, a profile’s header and body contains important information. ### Profile Header The profile header displays the profile title, a brief description and **Get** and **Delete** buttons. If you have installed the profile, and **Get** or **Download** button if the profile is available but not installed in your unique namespace. In either case, the profile header displays a status box detailing the: Status Installed or uninstalled Version The version number of the profile, which changes with updates Author The organization responsible for composing and updating the profile License Restrictions on the profile’s re-use. Installed profiles display a cURL command for an ad-hoc profile run. ![Installed Profile Details] ### Profile Body A profile is made up of a series of controls, which are listed in the Profile Detail’s body. Each control has one or more InSpec tests. The control table shows the number and names of controls in the profile, as well as the: Total tests the number of tests in the control Severity The impact of a control, from 0 to 1. See the Chef InSpec documentation for more information about the [severity measure](../../inspec/dsl_inspec#syntax) Selecting the shaded area next to the control name or the `+` on the right side expands the control to show a more detailed description. Selecting **View Code** displays the control’s InSpec code. ![Profiles Body] ### About the Profile Identifier The profile identifier is composed of the user’s username and the profile name, found in the installed profiles list at `https://automate.example.com/profiles`. Use this identifier when specifying profiles for the audit cookbook as well as specifying profiles through the InSpec CLI. Note The identifier is mapped to user’s username. This is only guaranteed to be unique for a user group, either local or saml. Users in a Chef Automate instance with the same username in both saml and local groups have access to each other’s profiles. Interacting with Chef Automate Profiles --------------------------------------- You can interact with Chef Automate Profiles from the command line, as well as from the user interface. For more information, see the [InSpec CLI](../../inspec/cli/index) subcommand. ### API Calls We’ve provided you with some essential cURL commands for interacting with Chef Automate Profiles. In these examples, the owner is same value as first part of identifier, as discussed in [About the Profile Identifier](#about-the-profile-identifier). #### Get All Installed Profiles ``` curl --insecure -H "X-Data-Collector-Token: token-value" https://automate.example.com/api/v0/compliance/profiles/search -d '{"owner": "test"}' ``` #### Get All Available Profiles ``` curl --insecure -H "X-Data-Collector-Token: token-value" https://automate.example.com/api/v0/compliance/profiles/search -d '{}' ``` #### Download .tar ``` curl --insecure -H "x-data-collector-token: token-val" https://automate.example.com/api/v0/compliance/profiles/tar -d '{"name":"cis-aix-5.3-6.1-level1","owner":"admin","version":"1.1.0-3"}' ``` #### Upload tar ``` curl --insecure -F file=@cis-ubuntu12_04lts-level1-1.1.0-2.tar.gz -H "x-data-collector-token: token-val" https://automate.example.com/api/v0/compliance/profiles?owner=admin ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/profiles/Nodes API ========= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/nodes.md) ### Nodes The `/nodes` endpoint in Chef Automate is something of a ‘logbook’ of the nodes in your infrastructure. When a user creates a node, that node is added to the `/nodes` endpoint. When a user adds a node integration, like aws or azure, nodes are added to the `/nodes` endpoint. When a Chef InSpec report or a Chef Infra Client run is ingested, a node is added to the `/nodes` endpoint. If the node already exists, its last contact time, run data, and scan data are updated. When run data and scan data are updated, the latest information is stored for the run id or report id, the status, and the penultimate status. ### Node Status All nodes have one of three possible statuses: ‘unknown’, ‘reachable’, and ‘unreachable’. The default status is ‘unknown’. Each time a user adds one or more nodes manually or with a node integration (AWS, Azure, or GCP), Chef Automate runs an`inspec detect` job on the newly added node(s). If the detect job is successful, the node status updates from ‘unknown’ to ‘reachable’, and the platform information is updated from the `inspec detect` results. If the detect job is unsuccessful, meaning the node could not be reached, the node’s status updates to ‘unreachable’. The status updates every time a scan job runs on the node. ### Node State All nodes have a state. Possible states are unknown(''), ‘running’, ‘stopped’, and ‘terminated’. Default state: '' (unknown). For all nodes added through integrations, node state is updated both when nodes are added and on a scheduled polling interval. If a node is found to have a state other than ‘running’, the node status is then also updated to ‘unreachable’. Node state is updated to ‘running’ on report ingestion if the end time recorded by the inspec report is less than ten minutes from the ingestion time. ### Filtering Nodes The `/nodes` endpoint supports filtering by: * name * platform_name * platform_release * manager_type (‘automate’, ‘aws-ec2’, ‘aws-api’, &mldr;) * manager_id * account_id (the aws account ID or azure tenant ID) * region * source_id (a reference to the primary provider’s node) * state * statechange_timerange (supports two timestamps of type “2019-03-05T00:00:00Z”) * status * tags * last_run_timerange (last time reported on ingested ccr: supports two timestamps of type “2019-03-05T00:00:00Z” (RFC3339)) * last_scan_timerange (last time reported on ingested scan: supports two timestamps of type “2019-03-05T00:00:00Z” (RFC3339)) * last_run_status (status on last ingested ccr) * last_scan_status (status on last ingested scan) * last_run_penultimate_status (status on second to last ingested ccr) * last_scan_penultimate_status (status on second to last ingested scan) Examples -------- * Show me all nodes whose last scan had a status of failed and a penultimate status of passed *or in other words, which nodes were previously passing their scans and just started failing?* sample request: ``` curl -s --insecure -H "api-token: $token_val" https://a2-dev.test/api/v0/nodes/search -d '{ "filters": [ {"key": "last_scan_status", "values": ["FAILED"]}, {"key": "last_scan_penultimate_status", "values": ["PASSED"]} ] }' ``` sample truncated response: ``` {"nodes":[{"id":"0e05fcf2-2fab-36ee-bb84-5b7d5888c33a","name":"chef-load-blue-delladonna-indigo","platform":"debian","platform_version":"8.11","last_contact":"2019-05-14T18:08:43Z","run_data":{"id":"","status":"UNKNOWN","penultimate_status":"UNKNOWN","end_time":null},"scan_data":{"id":"5640fbb7-d1ba-4c67-b0cd-9db4fcfc2598","status":"FAILED","penultimate_status":"PASSED","end_time":"2019-05-14T18:08:43Z"}}]} ``` * Show me all nodes whose last ccr passed and last scan failed, that had a penultimate ccr status of failed *or in other words, which nodes just started passing their ccrs but are failing their scans?* sample request: ``` curl -s --insecure -H "api-token: $token_val" https://a2-dev.test/api/v0/nodes/search -d '{ "filters": [ {"key": "last_run_status", "values": ["PASSED"]}, {"key": "last_scan_status", "values": ["FAILED"]}, {"key": "last_run_penultimate_status", "values": ["FAILED"]} ] }' ``` * Show me all nodes that had a last scan ingested sometime in the last 48 hours with a status of failed *or in other words, which nodes that were ingested in the last 48 hours failed their scans?* sample request: ``` curl -s --insecure -H "api-token: $token_val" https://a2-dev.test/api/v0/nodes/search -d '{ "filters": [ {"key": "last_scan_status", "values": ["FAILED"]}, {"key": "last_scan_timerange", "values": ["2019-05-12T00:00:00Z", "2019-05-16T00:00:00Z" ]} ] }' ``` * Show me all nodes tagged with `deployment:staging` OR `deployment:test`. We OR between multiple values of the same key sample request: ``` curl -s --insecure -H "api-token: $token_val" https://a2-dev.test/api/v0/nodes/search -d '{ "filters": [ {"key": "deployment", "values": ["staging", "test"]} ] }' ``` * Show me all nodes tagged with `deployment:prod` AND `org:marketing`. We AND between different tag key filters sample request: ``` curl -s --insecure -H "api-token: $token_val" https://a2-dev.test/api/v0/nodes/search -d '{ "filters": [ {"key": "deployment", "values": ["prod"]}, {"key": "org", "values": ["marketing"]} ] }' ``` ### Bulk Node Add Use the `nodes/bulk-create` endpoint to add multiple nodes with the same set of tags and credentials. Specifying a `name_prefix` for the nodes in question results in a node name of `prefix-host`. Specified tags will be added to each node. The endpoint takes an array of node objects, allowing users to add as many nodes as needed. ``` curl -s --insecure -H "api-token: $token_val" https://a2-dev.test/api/v0/nodes/bulk-create -d ' {"nodes": [{ "name_prefix": "my-ssh-node", "manager":"automate", "target_config": { "backend":"ssh", "hosts":["localhost","127.0.0.1"], "secrets":["2998c3a1-d596-43d4-b2b3-4837a46cee19"], "port": 22 }, "tags": [ { "key":"test-node", "value":"is-amazing" }, { "key":"compliance-service", "value":"rockin-like-whoa" }, { "key":"_no_auto_detect", "value":"true" } ] }, { "name": "my-other-node", "manager":"automate", "target_config": { "backend":"ssh", "hosts":["localhost"], "secrets":["2998c3a1-d596-43d4-b2b3-4837a46cee19"], "port": 22 }, "tags": [ { "key":"test-node", "value":"is-more-amazing" } ] } ] }' ``` ### Bulk Node Delete The `/nodes/delete` endpoint allows users to bulk-delete nodes based on a query. To examine the outcome of this destructive action before running it, test the query first on the `api/v0/nodes/search` endpoint. ``` curl -s --insecure -H "api-token: $token_val" https://a2-dev.test/api/v0/nodes/delete -d '{ "filters": [ {"key": "name", "values": ["vj*"]} ] }' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/nodes/Chef Infra Server ================= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/chef_infra_server.md) Overview -------- The *Chef Infra Server* page (**Infrastructure > Chef Servers**) lets you connect existing Chef Infra Servers to Chef Automate, view all the connected Chef Infra Servers, and manage all of the objects on your connected Chef Infra Servers. The *Chef Infra Server* acts as a hub for configuration data. The Chef Infra Server stores *cookbooks*, the policies that are applied to *nodes*, and metadata that describes each registered node managed by Chef Infra Client. Nodes use Chef Infra Client to ask the Chef Infra Server for configuration details, such as recipes, templates, and file distributions. Chef Infra Client then does as much configuration work as possible on the nodes themselves (and not on the Chef Infra Server). This scalable approach distributes the configuration effort throughout the organization. ![Chef Infra Server Page] The objects that you can manage from the Chef Infra Server are: * Cookbooks * Roles * Environments * Data Bags * Clients * Nodes * Policyfiles * PolicyGroup Connect Chef Infra Servers to Chef Automate ------------------------------------------- The *Chef Infra Server* panel starts with an empty list of servers. To add existing Chef Infra Servers to the Chef Automate infrastructure, select **Add Chef Server**, which will request the name, FQDN, and IP address of your Chef Infra Server: ![Add Chef Server Form] Chef Automate warns you if you enter an invalid FQDN or IP address: ![Add Chef Server Form] Once done, select **Add Chef Server** and see the server in the list of Chef Infra Servers. Connect a Chef Organization to a Chef Infra Server -------------------------------------------------- To view a list of existing [organizations](../../server_orgs/index) on a Chef Infra Server, select a Chef Infra Server from the **Chef Servers** list, then select the **Organizations** tab, as shown below: ![Chef Infra Server Organization]. To add an existing organization, select **Add Chef Organization**, which opens a dialog box as shown below: ![Add Chef Organization Form] Enter the *Name*, *Projects*, *Admin User*, and *Admin Key* fields using the same values provided when the organization gets configured using *Knife*. Copy the contents of the `~/.chef/USER.pem` file and paste it into the **Admin Key** field. Then select **Add Chef Organization** to add the organization to the Chef Infra Server. Access Chef Infra Server Components ----------------------------------- Manage the following Chef Infra Server components for an organization using Chef Automate: * Cookbooks * Roles * Environments * Data Bags * Clients To access these components for an organization, select **Chef Servers > Organizations** and then select an organization. Refer to the image below: ![Chef Infra Server Objects] ### Cookbooks A [cookbook](../../cookbooks/index) is the fundamental unit of configuration and policy distribution. A cookbook contains recipes and other files, components, or directories. The Chef Infra Server lets you view: * List of cookbooks with their latest version * Different versions of a cookbook * Contents of a cookbook * Details of a cookbook #### List of Cookbooks In Chef Infra Server, you can view all the cookbooks of an organization. The latest version of the cookbooks is mentioned in the list. ![List of Cookbooks] Select a cookbook from the list to view the details of that cookbook. #### Different Versions of Cookbooks To view different versions of a cookbook: * Select a cookbook from the list. * View the different versions of the cookbook using the dropdown list. ![Versions of a Cookbook] #### Cookbook Content Select the **Content** tab to view the recipes and other components of a cookbook. This view also contains the files or directories of the components. To view the cookbook content, select the file from the component list. ![Cookbook Contents] #### Details of a Cookbook Select the **Details** tab to view the requirements, usage, resources, and license. ![Details of a Cookbook] ### Roles [Roles](../roles/index) let you define patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. The Chef Infra Server lets you: * Create a role * View all roles * Search for a specific role * View the details of roles: + Run List + Attributes * Delete a role #### Create a Role To create a new role, select **Create Role**: ![Create Roles Button] Selecting the **Create Role** button opens a dialog box. The dialog box contains four sections: *Details*, *Run List*, *Default Attributes*, and *Override Attributes*. Enter the details in the possible sections and select **Create** to create a new role. ![Create Roles Dialog Box] #### Search for a Role Use the **Search Roles** bar to find the existing role from the list of roles. Entering the name of a role in the search box returns roles matching your search criteria. ![Select Create Roles Button] #### View Role Details Select a specific role to view the details of that particular role. It contains two tabs, *Details* and *Attributes*. ![View Role Details] The *Details* contains the Run List, whereas the attributes tab displays the *default* and the *override* attributes of the role. ![View Attributes Details] You can edit the *default* and *override* attributes by selecting the **Edit** option. It opens a pop-up window where you can make the changes and select **Save**. #### Delete a Role Chef Infra Server lets you delete the existing roles one at a time. To delete a role, select the ellipses icon and then **Delete**, as illustrated below: ![Delete A Role] ### Environments An [environment](../../environments/index) can be used to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. The Chef Infra Server UI lets you: * Create an environment * View all environments * Search for a specific environment * View the details of an environment * Edit an environment * Delete an environment #### Create an Environment To create a new Environment, select **Create Environment**, as shown below: ![Create Environment Button] Selecting the **Create Environment** button opens a dialog box. The dialog box contains four sections: *Details*, *Constraints*, *Default Attributes*, and *Override Attributes*. Enter the details in the possible sections, and select **Create** to create a new environment. ![Create Environment Dialog Box] #### Search for an Environment Use the **Search environments** bar to find an existing environment from the list. Entering the name of an environment in the search box returns environments matching your search criteria. ![Create Environment Button] #### Details of an Environment Select a specific environment to view that environment’s cookbook constraints and attributes. ##### Cookbook Constraints The selected bar contains the list of all the cookbook constraints with *Name*, their *Operator*, and *Version* respectively. Select **Edit** to change the *Cookbook Constraints*. ![Cookbook Constraints In Environment] ##### Attributes The attributes window shows all the default and overridden [attributes](../../attributes/index). Select **Expand All** or **Collapse All** to view or hide the attributes. Select **Edit** to change the *Default Attributes* and *Override Attributes*. Note You can edit *Cookbook Constraints* and the *Attributes* only for environments with an existing *client* for that *organization*. ![Attributes In Environment] #### Delete an Environment The Chef Infra Server lets you delete environments one at a time. Select **Delete** from the more information (three dots) icon on the far right side of the environment that you want to delete, as shown below: ![Delete an Environment by selecting the more information icon on the right side of an environment list item] ### Data Bags [Data bags](../../data_bags/index) store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. Chef Infra Server UI lets you: * Create a data bag * View all data bags * Search for a specific data bag item * Create a data bag item * Edit a data bag item * Delete a data bag item * Delete a data bag #### Create a Data Bag To create a new data bag, select **Create Data Bag**, as shown below: ![Create Data Bag Button] Selecting the **Create Data Bag** button opens a dialog box. Enter the name and select **Create**. ![Create Data Bag Dialog Box] #### Create a Data Bag Item To create a data bag item, select the data bag from the list of data bags and follow the steps given below: Select **Create Item**, as shown below: ![Create Data Bag Item Button] Selecting the **Create Item** button opens a dialog box. Enter the **Data Bag Item ID** and the details of the key value pairs of that particular item. Select **Create**. ![Create Data Bag Item Dialog Box] #### Search for an Item Use the **Search data bag items** bar to find an item from the list of data bag items. Entering the name of an item in the search bar returns data bag items that match your search criteria. ![Search Data Bag Item Bar] #### Edit a Data Bag Item Select a specific data bag item to view the details. The details contain an *id*, and a couple of *key values*. Chef Infra Server lets you **edit** a data bag item. ![Edit and Delete a Data Bag Item] To edit the details of the data bag items, select **Edit**. In the dialog box, you can edit the details for the specific data bag item. Once done, select **Save Item**. ![Edit a Data Bag Item] #### Delete a Data Bag Item Select a specific data bag item to view the details. The details contain an *id* and a couple of *key values*. Chef Infra Server lets you **delete** a data bag item. ![Edit and Delete a Data Bag Item] To delete a data bag item, select **Delete**. In the dialog box displayed, select **Delete** to delete the data bag item. ![Delete a Data Bag Item] #### Delete a Data Bag Chef Infra Server lets you delete the existing data bag one at a time. To delete a data bag, select the ellipses icon and then **Delete**, as illustrated below: ![Delete a Data Bag] ### Clients Chef Infra Clients provide secure API access to the Chef Infra Server. Chef Infra Server UI lets you: * Create a client * View all clients * Search for a specific client * Reset a client key * Delete a client #### Create a Client To create a new client, select **Create Client**. ![Create Client Button] The **Create Client** button opens a dialog box. Enter the *Client Name* and select *Validation Client* to create a Validation Client. Select **Create**. ![Create Client Dialog Box] Selecting **Create** opens a dialog box that contains the *Private Key* of that particular client. Select **Download** to download the *Private Key*. ![Create Private Key of a Client] #### Search for a Client Use the **Search Clients** bar to find a client from the list of clients. Entering the name of a client in the search bar returns clients matching your search criteria. ![Create Client Button] #### Public Key of a Client Select the client to view the *Public Key* for that client. The *Public Key* of that client will be displayed in **Details**. ![Public Key of Clients] The Chef Infra Server lets you reset the *Public Key* using the *Reset Key* option. Selecting the *Reset Key* option opens an alert stating *The current key will no longer be accepted.* ![Reset Key Option of a Client] Selecting the *Reset Key* shown in the above image opens a new dialog box containing the client’s new *Private Key*. To download the new *Private Key*, select **Download**. ![Reset Public Key of a Clients] #### Delete a Client Chef Infra Server lets you delete the existing clients one at a time. To delete a client, select the ellipses icon and then **Delete**, as illustrated below: ![Delete a Client] ### Nodes A [node](../../nodes/index) is a device that is managed by Chef Infra. During the Chef Infra Client run, the Infra Client retrieves [attributes](../../nodes#attributes) that defines the expected state of the node and a [run-list](../../nodes#run-lists) that defines how a node can be configured to that state from the Infra Server. The Infra Client then uses that information to update the node to its expected state. The Chef Infra Server integration lets you: * Search for a specific node * View all nodes * Details of a node * Edit Run list * Edit Attributes * Manage tags * Reset a node key * Delete a node #### Search for a Node Use the search bar on the Nodes tab (**Chef Infra Servers > Nodes**) to find a node from the list of nodes. Entering the name of a node in the search bar returns nodes matching your search criteria. ![Search a Node] #### Details of a Node Select a specific node to view the node information, metadata, and details of the node’s environment. The first section of the page has the **Node Information** like `Environment`, `Policy Group`, and `Policy Name`. You can also view the **Metadata** for the node that contains the name of the `Chef Server`, and the name of the `Chef Organization`. The above information looks like as shown below: ![Node Information & Metadata] The next section of the page contains two options: * Details * Run List * Attributes ##### Details The **Details** section lets you view and update the node environment. The drop-down menu consists of the list of environments created in the chef server. You can select any one environment for the selected node. To select the environment: * Select the dropdown menu and the name of the environment. * You can add tags to the environment from the text bar below the dropdown menu. **Note:** To add multiple tags at a time, use a comma separator. Example: Tag1, Tag2, Tag3. * Selecting an environment opens a pop-up to save the node environment. Select **Save** to change the node environment. ![Update Node Environment] ##### Run List You can edit, expand or collapse a node’s run list. ![Run List of a Node] Edit a run list by: 1. Select **edit**. A pop-up window opens. 2. The left side of the window contains the list of environments. Select an environment from the list. 3. The right side of the window shows the run list for the selected environment. 4. Select the run list for a specific environment. 5. Select **Create**. This opens a pop-up window similar to: ![Edit Run List] You can find the editing window directly by selecting the ellipses icon and then **Edit Run List** of a specific node in the node list. Selecting the option opens a pop-up for editing the run list. ##### Attributes The attributes window shows all the default and overridden [attributes](../../attributes/index). Select **Expand All** or **Collapse All** to view or hide the attributes. Select **Edit** to change or update the existing attributes. ![Node Attributes List] You can find the editing window directly by selecting the ellipses icon and then **Edit Attributes** of a specific node in the node list. Selecting the option opens a pop-up for editing the attributes. #### Manage Tags Chef Infra allows you to manage tags of the environment. You can add or remove multiple tags in two ways: 1. Selecting the node and add the tags from the text bar below the dropdown menu of environments. 2. Select the ellipses icon and then **Manage Tags** for a specific node. Add and remove tags in tag editor and select **Update Tags** to save your changes. ![Manage Tags] #### Reset a Client Key Reset a client key by selecting the ellipses icon and then **Reset Key** of a specific node in the node list. Selecting **Reset Key** opens a warning *The current key will no longer be accepted*. Select **Reset Key** once again to confirm. ![Reset the Client Key] #### Delete a Node Delete individual existing nodes by selecting the ellipses icon and then **Delete**: ![Delete a Node] ### Policyfiles [Policyfiles](../../policyfile/index) are preferred way of managing roles, environments, and community cookbooks data with a single document that is uploaded to the Chef Infra Server. Policyfiles lets you test and promote codes with a simpler interface. The Chef Infra Server integration lets you: * Search for specific Policyfiles * View all the Policyfiles * View the details of Policyfiles: + Content + Attributes + Revision ID * Delete Policyfiles #### Search for Policyfiles Use the search bar on the Policyfile tab (**Chef Infra Server > Policyfile**) to find a policy file from the list. Enter the name of a policy file in the search bar to view matching Policyfiles. ![Policyfile] #### Details of Policyfiles Select a Policyfile to view the **METADATA**, **Content**, **Attributes**, **Revision ID**, and **Cookbook Dependencies** of that Policyfile. ![Details of Policyfiles] ##### Content Tab The **Content** tab contains the list of all: * Included Policies * Run Lists ###### Included Policies Select a specific Policyfile from the *Included Policies* to view the details. ![Content Scroller in Policyfiles Details] In the above image, the slider tab shows the *Details* of the selected policyfile. To view the *Revision ID* select the **Revisions** option in the tab. ###### Run List Select a specific Run Item from the Run List to view the details in a slider tab. ![Runlist Tab under Policyfiles] To view the cookbook details of the item, select the **Go to Cookbook Details** option in the tab. ##### Attributes Tab The **Attributes** tab displays the *default* and the *override* attributes of a Policyfile. ![Attributes tab of Policyfiles] You can **Expand** and **Collapse** the *default* and *override* attributes by selecting the option. ##### Cookbook Dependencies Select the **Cookbook Dependencies** button to view all the *Dependencies Rules* and *Cookbook* of the policyfile in table format. Select a specific cookbook from the list to view the details of the cookbook. Note Selecting a specific cookbook redirects you to the audit section of the **Cookbook** main tab. The slider tab contains the `Operator` and `Version` of the cookbooks. ![Cookbook Dependencies Button] Note You can find the **Revision ID** window directly by selecting the ellipses icon of a Policyfile. Selecting the option opens a pop-up that contains the detailed revision ID. ![Revision id of Policyfiles] #### Delete Policyfiles Delete individual Policyfiles by selecting the ellipses icon and then **Delete**: ![Delete Policyfiles] ### Policy Group The Chef Infra Server integration lets you: * Search for a Policy Group * View all the Policy Groups * View the details of a Policy Group + Policyfiles + Nodes #### Search for a Policy Group The search bar on the Policy Groups tab (**Chef Infra Server > Policy Groups**) finds a policy group from the list. Enter the name of a policy group in the search bar to view matching Policy Groups. ![Search for a Policy Group] #### View the details of a Policy Group Select a Policy Group to view the Policy Group Information and METADATA of that Policy Group. ![Details of a Policy Group] ##### Policyfiles Tab The details page of the policy group view the list of **Policyfiles**. ![Policyfiles under Policy Group] Select a Policyfile from the list to view its details. Note Selecting a specific policyfile redirects you to the details section of the **Policyfiles** main tab. ##### Nodes Tab The details page of the policy group lets you view the list of **Nodes**. ![Nodes Tab in Policy Group] Select a node from the list to view its details Note Selecting a specific node opens details section of the **Nodes** tab. Troubleshoot ------------ While fetching any objects like cookbooks, you might face an error `Could not get cookbooks: organization 'no-org' does not exist`, which means the provided organization does not exist on Chef Infra Server. ![Could not get cookbooks: Organization] Create the organization using the knife command, `knife opc org create` or the Chef Infra Server CLI command, `chef-server-ctl org-create`, then add the *Name*, *Projects*, *Admin User*, and *Admin Key* to fetch the objects. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/chef_infra_server/ServiceNow Integration App ========================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/servicenow_integration.md) [ServiceNow](https://www.servicenow.com/) provides cloud-based services that automate enterprise IT operations. ServiceNow specializes in IT service management (ITSM) applications and provides forms-based workflow application development. It supports third-party application and data integrations. The most common integrations are for configuration management, incident management, problem management, change management, user administration, and single sign-on authentication. The Chef Automate Integration App for ServiceNow, also called the Integration App, integrates Chef Automate with ServiceNow. This app is a ServiceNow-certified scoped application available from the ServiceNow store. It integrates existing Chef Automate infrastructure and compliance functionality with ServiceNow enterprise services. Once installed and configured, this integration enables Chef Automate to create and update a ServiceNow Configuration Management Database (CMDB) with data from nodes managed by Chef Automate. Chef Automate aggregates information about infrastructure nodes, the Chef Infra Client runs, and Chef Compliance scans, helping you monitor your infrastructure in real time. The Integration App works by exposing the REST API endpoints for communication between Chef Automate and ServiceNow. Chef Automate sends HTTPS JSON data feeds to the app in ServiceNow to create and update the *ServiceNow CMDB*, client run, and compliance report tables. ![Data Flow Diagram](https://docs.chef.io/images/automate/snow_integration_dataflow_diagram.png) Prequisites ----------- ### User Requirements * Your unique ServiceNow URL. It has the format: `https://ven12345.service-now.com`. * Once the Integration App requires the `x_chef_automate.api` role to configure it. Your ServiceNow administrator can enable this for you. ### System Requirements * A running [Chef Automate](https://www.chef.io/automate/) instance. * Chef Automate has a valid SSL/TLS certificate from a trusted certificate authority (CA). * A running [ServiceNow](https://www.servicenow.com/) instance. * The ServiceNow instance is reachable on port 443. ### Required ServiceNow Plugins Install following ServiceNow plugins from the Service Management dashboard: * System Import Sets `com.glide.system_import_set`, min version 1.0.0. * Configuration Management (CMDB) 1.1. * Configuration Management for Scoped Apps (com.snc.cmdb.scoped) 1.0.0. Install ------- Get the app from the [ServiceNow](https://store.servicenow.com) store and then install it to your account from the **Service Management** dashboard. Setup ----- To see your data in ServiceNow, you need to create a data feed for Chef Automate. You can set up the data feed either in Chef Automate or in ServiceNow. Setting up the data feed requires the `x_chef_automate.api` role permissions. Your ServiceNow administrator can enable this for you. ### Create a Data Feed in Chef Automate Set up a data feed to send data from Chef Automate: 1. Confirm that you have the `x_chef_automate.api` role. 2. Navigate to **Settings** > **Data Feeds** > **Create Data Feed**. 3. Enter or select: * **Name**: A unique name for this integration. * **Data Feed URL**:The API address that the notification uses. It has the format: `https://ven12345.service-now.com/api/x_chef_automate/asset`. * **Username**: The name you use to sign in to ServiceNow. * **Password**: The password you use to sign in to ServiceNow. 4. Select **Test Data Feed**. A successful test displays **service-now automate connectivity passed**. An unsuccessful test returns a message with infomation for the connectivity or credentials issues to helps resolve the error. 5. Select **Create Data Feed** to save the setup. ![Create Data Feed] ### Create a Connection from ServiceNow Follow these steps connect the Integration App to Chef Automate: 1. Confirm that you have the `x_chef_automate.api` role. 2. Navigate to the **ServiceNow** instance. 3. Locate **Chef Automate** from the search bar. 4. Select the **Automate Instances** module. 5. Select the **New** button. 6. Enter the following details: * **Name**: A unique name for this integration. * **Instance URL**: The Chef Automate URL. * **Automate API token**: A Chef Automate API token with data-feed-service authorization. * **ServiceNow user**: The name you use to sign in to ServiceNow. * **ServiceNow password**: The password you use to sign in to ServiceNow. 7. Select the **Test Connectivity** button. The Integration App checks that the values are correct and test the connection with Chef Automate. * A successful test displays a **service-now automate connectivity passed** message. * An unsuccessful test results in an error message with suggestions for resolving the connection or credentials problems. 8. Select **Submit**. The ServiceNow app creates the Chef Automate instance detail. ![Chef Automate Instances] Integration App Overview ------------------------ When you install and setup the Integration App, the **Chef Automate** appears in the ServiceNow navigation pane. ![Navigation] * **Automate Instances** module allows the user to configure the integration with Chef Automate. * **Server** module displays a list of servers in the **CMDB** module. ![Discovery Source] ### Server Module Integration App updates the CMDB file systems and software tables. It adds associated data from Chef Automate to the servers for: * Client Runs * Attributes * Compliance Reports #### Discovery Source The Integration App augments the existing CMDB servers and inserts new servers into the ServiceNow CMDB. The Integration App uses the ServiceNow Discovery IRE (Identification and Reconciliation Engine) to insert or update servers. The Integration App distinguishes between discovered Configuration Items (CIs) and imported CIs. CIs discovered by the Integration App have a default value of **Chef Automate** in the **Discovery Source** field in the `cmdb_servers` table. #### Client Runs You can view the data for a Chef Infra Client run by selecting a server from the list. The **Client Run** record displays information for: * Client run cookbooks: cookbooks executed during the Chef Infra Client run. * Client run lists: run lists executed during the Chef Infra Client run. * Client run recipes: recipes executed during the Chef Infra Client run. The complete Chef Infra Client run details are available for each server. Chef Infra Client runs are available from the **Client Runs** module. #### Attributes You can view the current attributes for a server by selecting the attributes record. The entire OHAI attributes are available for each server. #### Compliance Reports You can view the **Compliance** report detail from a server record by selecting the name on an individual **Compliance** report. The Compliance Report record displays related information for: * Compliance report profiles: all profiles executed during the compliance scan. * Compliance report results: all results from the compliance scan. Also, you can view the **Compliance** report profile to display the individual results for each profile. The entire Chef Compliance Report details are available for each server. Compliance reports are also available from the **Compliance** report module. ### Automate Instances Module You can configure the Integration App from either ServiceNow or Chef Automate. #### Change Integration App Properties in ServiceNow 1. Find Chef Automate in ServiceNow. 2. Select the **Chef Automate** > **Properties** in the left navigation pane to open the **Chef Automate Properties**. ![Chef Automate Properties](https://docs.chef.io/images/automate/snow_integration_appproperties.png) 3. Make your changes. 4. Select **Save**. #### Chef Automate Settings `feed_interval` The frequency in hours for refreshing the data feed. The duration between data feed refreshes is proportional to the node count, with more nodes requiring higher settings. Valid values: Any integer in the range of `2` to `8`. Default: `4`. `node_batch_size` The testing executed for a benchmark. The size of a compliance scan is proportional to the number of profiles applied. Scans exceeding 4MB may fail or display incorrectly in reports. Use a lower `node_batch_size` setting to reduce the number of profiles applied in a single batch. Valid values: Between `1` and `30`. Default: `15`. #### Integration App Properties The Integration App has nine configurable **Application Properties**. Changing these settings requires the ServiceNow `admin` or `x_chef_automate.admin` permissions. `x_chef_automate.chef.default.status` Used to set up the status of the service record as **inserted** or **updated**. Default: `1`. `x_chef_automate.client_runs_per_node` Used to set a highest number of clients runs for a node. Default: `5`. `x_chef_automate.compliance_reports_per_node` Used to set a highest number of compliance reports for a node. Default: `5`. `x_chef_automate.insert_manufacturer` Inserts the new record during the import if a model is not found in the *core_company* table by settingthe property to **Yes**. Default: `Yes`. `x_chef_automate.insert_model` Inserts the new record during the import if a model is not found in the *cmdb_model* table by setting the property to **Yes**. Default: `Yes` `x_chef_automate. logging.enabled` Used to flag the logging with **enable** or **disable** values. Default: `No`. `x_chef_automate.logging.verbosity` Debugs the data in ServiceNow. Enables the selected logging level and is visible in logs. Valid values: `Debug`, `Warn`, `Info`, `Error`. Default: `Error`. `x_chef_automate.Rest.api` Enables the Chef Automate API from ServiceNow. Set to `Yes` to enable and `No` to disable. Valid Values: `Yes`, `No`. Default: `Yes`. `x_chef_automate.enable.system.app` Used to enable software installed mappings. Valid Values: `Yes`, `No`. Default: `No`. Uninstall --------- To uninstall the Integration App: 1. Navigate to the **System Applications** > **Applications** in ServiceNow. 2. Open the **Downloads** tab and select the **Chef Automate Incident Creation**. 3. Navigate to **Related Links**. 4. Select **Uninstall**. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/servicenow_integration/ServiceNow Incident App ======================= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/servicenow_incident_creation.md) The Chef Automate Incident Creation App for ServiceNow is a certified app available in the [ServiceNow](https://store.servicenow.com) store. The Incident App generates incidents in the ServiceNow Incident Management environment for configuration run or compliance check failures in Chef Automate. This helps you capture the failures in your automated infrastructure and improve your incident tracking and resolution. The Incident App exposes the REST API endpoint for communication between Chef Automate and the ServiceNow instance. Chef Automate sends HTTPS JSON notifications to the Incident App in a ServiceNow instance to creates and update incident failures. ![ServiceNow and Chef Automate Flow] Key Features of the Incident App -------------------------------- * Incident management for infrastructure and compliance automation * Intelligent data management and event de-duplication * Compliance-related integrations within ServiceNow The Incident App generates a data stream of compliance events that you can leverage by using this data to other ServiceNow applications. For example, you can integrate the Chef Automate compliance scan data with Governance and Risk Compliance (GRC) or Security and Incident Management (SIEM) systems in ServiceNow. You can personalize the Chef Automate compliance data stream by prioritizing the scan results, which helps you enhance your risk dashboard with real-time and ranked compliance events instead of low-information and context-free standard data streams. User Requirements ----------------- * Your unique ServiceNow URL. It has the format: `https://ven12345.service-now.com`. * Setting up the Incident App requires the `x_chef_automate.api` role to configure it. Your ServiceNow administrator can enable this for you. System Requirements ------------------- * The [Integration App](../servicenow_integration/index) is already installed and configured. Install ------- Get the app from the [ServiceNow](https://store.servicenow.com) store and then install it to your account from the **Service Management** dashboard. Setup ----- You can setup automatic incident creation for: * Chef Infra Client failures * Chef InSpec scan failures ### Chef Infra Client Incidents To set up automatic incident reporting for failed Chef Infra Client runs from Chef Automate: 1. Confirm that you have the `x_chef_automate.api` role. 2. Navigate to **Settings** > **Notifications** 3. Select **Create Notification** 4. Enter or select: * **Name**: A unique name for this notification. * **Webhook Type**: The product or proccess receiving the notification. Options: **Slack**, **Webhook**, and **ServiceNow**. * **Failure Type**: The Chef process for the notification. Select **Infra Client Run failures**. * **Webhook URL**: The API address that the notification uses. It has the format: `https://ven12345.service-now.com/api/x_chef_automate/client_run`. * **ServiceNow Username**: The name you use to sign in to ServiceNow. * **ServiceNow Password**: The password you use to sign in to ServiceNow. 5. Select **Test Connectivity**. A successful test displays **Notification test connected successfully**. An unsuccessful test displays a message with information about any connection or credential problems to help you fix the error. ![Chef Automate Notification for CCR Failures] 6. Select **Create Notification** to save this notification. ### Chef InSpec Scan Incidents Follow these steps to report failed Chef InSpec scans from Chef Automate: 1. Navigate to **Settings** > **Notifications** > **Create Notification** button. 2. Enter or select: * **Name**: A unique name for this notification. * **Webhook Type**: The product or proccess receiving the notification. Select the **ServiceNow** option. * **Failure Type**: The Chef process for the notification. Select the **Inspec compliance scan failures** option. * **Webhook URL**: The API address that the notification uses. It has the format:`https://ven12345.service-now.com/api/x_chef_automate/inspec_scan` * **ServiceNow Username**: The name you use to sign in to ServiceNow. * **ServiceNow Password**: The password you use to sign in to ServiceNow. 3. Select **Test Connectivity**. A successful test displays **Notification test connected successfully**. An unsuccessful test displays a message with information about any connection or credential problems to help you fix the error. ![Chef Automate Notification for InSpec Scan Failures] 4. Select **Create Notification** to save this notification. Properties ---------- The Chef Automate Incident App has nine configurable **Application Properties**. You must have the `admin` or `x_chef_incident.admin` roles to change the default values in the **Application Properties**. To change the Incident App properties: 1. Find **Chef Incidents** in ServiceNow 2. Select **Chef Incidents** > **Properties** from the navigation. 3. Enter your changes in the **Chef Incident Properties** form. 4. Select **Save**. ![ServiceNow Configuration Page] ### Incident App Properties `x_chef_incident.association` Used to associate a Chef Infra Client run record with an Incident record. Possible values: `cookbook` and `node`. Default: `cookbook`. Create an incident for `cookbook` creates a failed cookbook by setting the value to `cookbook`. This associates all failing Chef Infra Client runs with the corresponding incident. `cookbook` is the default value because the number of nodes exceeds the number of cookbooks in any system. The short description of the incident provides information about the failure: ![CCR Failed Cookbook Description] The **Chef Infra Client runs** tab of the incident displays the associated client runs. Setting the value to `node` creates an incident for each failed node. All failing Chef Infra Client runs for a node associates with the corresponding incident. The short description of the incident provides information about the run failure for one node. ![CCR Failed Node Description] `x_chef_incident.scan_association` Associate a Chef InSpec scan record with an incident record. Possible values: `profile` and `node`. Default: `profile`. Create a Chef InSpec compliance scan incident by setting this value to `profile`. This associates all failed Chef InSpec scans with the corresponding incident. `profile` is the default value because the number of nodes exceeds the number of profiles. The short description of the incident provides information about the failure. ![Scan Failed Profile Description] The **Chef InSpec scans** tab of the incident displays the associated Chef InSpec scans. Setting the value to `node` creates an incident for each failed node. All Chef InSpec scans failing for a node associates with the corresponding incident. The short description of the incident indicates the failed node. ![Scan Failed Node Description] `x_chef_incident.assigned_to` Assign a ServiceNow user ID to incidents. If the user is part of a group, then that group is also automatically assigned to the incident. Default: `none`. `x_chef_incident.assignment_group` Assign a group to the incident instead of the individual user in the `x_chef_incident.assigned_to` property. Default: `blank`. `x_chef_incident.impact` Set an incident impact value. Possible values: `1`, `2`, `3`. Default: `2`. `x_chef_incident.urgency` Set an incident urgency value. Possible values: `1`, `2`, `3`. Default: `2`. `x_chef_incident.retention_days` Define the number of days to retain Chef Infra Client run and Chef InSpec scan reports in ServiceNow. The ServiceNow app automatically updates the records associated with reports when they are closed, deleted, or removed. Default: `30`. `x_chef_incident.logging.enabled` Set to `Yes` to enable logging and `No` to disable it. Once enabled, authorized users can view the logs at **Chef incidents** > **Logs** and **System logs** > **Application logs**. Default: `No`. `x_chef_incident.logging.verbosity` Set the amount of information visible in logs. Possible values: `debug`, `warn`, `info`, and `error`. Default: `error`. Uninstall --------- To uninstall the Chef Automate Incident App: 1. Navigate to the **System Applications** > **Applications** in ServiceNow. 2. Open the **Downloads** tab and select the **Chef Automate Incident Creation**. 3. Navigate to **Related Links**. 4. Select **Uninstall**. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/servicenow_incident_creation/Notifications ============= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/notifications.md) About Notifications ------------------- Chef Automate notifications uses webhooks to send alerts for failures of Chef Infra Client runs and InSpec compliance scans. You can send notifications to Slack channels, Slack users, or any other service that supports webhook integrations. Notifications are sent for all failures. To ignore a failure, set the `ignore_failure` attribute to `true` on the resource. By default only Admins of Chef Automate may create and manage notifications. Warning Notifications sent by Chef Automate do not support retries; therefore, notifications sent while Slack or the external service receiving the notification is experiencing API issues, outages, or some other unplanned downtime may never be received. Undelivered notifications are not re-sent. Attempts to send notifications do generate log messages in your Chef Automate server. Slack Notifications ------------------- ### Add a Slack Notification To add a Slack notification for Chef Automate: ![Notifications Navigation] 1. In the **Settings** tab, navigate to the *Notifications* page in the sidebar. 2. Select **Create Notification**. 3. Select **Slack**. 4. Enter a unique notification name. 5. Select the failure type to be notified on from the drop-down menu. Current options are Chef Infra Client run or InSpec scan 6. Get your Slack webhook address by using the **What’s this?** link, which opens an external Slack site. 7. On the Slack page, select a channel or user for the notification. Slack will create the new webhook and then provide a webhook URL for you to copy. After entering a recipient, use the **Add Incoming WebHooks Integration** button. 8. Copy the URL, return to the Chef Automate page, paste the URL into the *Notifications* form. 9. Use the **Send a test** button to try out your Slack notification. If your Slack notification does not appear, return to the Slack Webhooks Integration page to re-check the recipient and URL. 10. Use the **Save Notification** button to create the Slack notification. ### Edit Slack Notifications To edit a Slack notification for Chef Automate: 1. From the *Notifications* page, select the notification name to open its detail page. 2. Edit the notification type, name, failure type, or URL. 3. Use the **Save Notification** button to save the Slack notification. ### Delete Slack Notifications To delete a Slack notification for Chef Automate: 1. From the Notifications page, select **Delete** from the menu at the end of the table row. 2. Confirm that you wish to permanently delete this notification. Webhook Notifications --------------------- ### Add a Webhook Notification To add a webhook notification for Chef Automate: ![Notifications Navigation] 1. In the **Settings** tab navigate to the *Notifications* page in the sidebar. 2. Select **Create Notification**. 3. Select **Webhooks**. 4. Enter a unique notification name. 5. Select the failure type to be notified on from the drop-down menu. Current options are Chef Infra Client run or InSpec scan 6. Enter the webhook URL the notification should be sent to. 7. Use the **Send Test** button to try out your webhook notification. 8. Use the **Save Notification** button to create the webhook notification. ### Edit Webhook Notifications To edit a webhook notification for Chef Automate: 1. From the *Notifications* page, select the notification name to open its detail page. 2. Edit the notification type, name, failure type, or URL. 3. Use the **Save Notification** button to save the webhook notification. ### Delete Webhook Notifications To delete a webhook notification for Chef Automate: 1. From the Notifications page, select **Delete** from the menu at the end of the table row. 2. Confirm that you wish to permanently delete this notification in the helper screen. ### Webhook Notification Payload The body of the notification payload contains complex JSON data. One attribute to note is `type`. Chef Infra Client run failures have a `type` of `converge_failure` where the Chef InSpec scan failures have a `type` of `compliance_failure`. The `controls` section of the Chef InSpec scan failures notification payload contains information about each failed control, so the payload can be rather large if the node has a lot of failed controls. #### Chef Infra Client Run Failure Example Payload ``` { "type": "converge_failure", "start_time_utc": "2020-05-28T18:43:33.000000Z", "node_name": "winnode1", "failure_snippet": "Chef client run failure on [localhost] winnode1 : https://automate.example.com/infrastructure/client-runs/e9c01d6d46543c19fba3b7bfc17a22d/runs/advff4a3-7890-4b74-98c1-fb00ae6dd251\nError executing action `run` on resource 'execute[name]'\nexecute[name] (cookbook::default line 10) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'\n---- Begin output of command ----\nSTDOUT: \nSTDERR: 'command' is not recognized as an internal or external command,\r\noperable program or batch file.\n---- End output of command ----\nRan command returned 1 \n", "exception_title": "Error executing action `run` on resource 'execute[name]'", "exception_message": "execute[name] (cookbook::default line 10) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'\n---- Begin output of command ----\nSTDOUT: \nSTDERR: 'command' is not recognized as an internal or external command,\r\noperable program or batch file.\n---- End output of command ----\nRan command returned 1", "exception_backtrace": [ "C:/hab/pkgs/chef/chef-infra-client/15.6.10/20191210013214/vendor/gems/mixlib-shellout-3.0.7-universal-mingw32/lib/mixlib/shellout.rb:300:in `invalid!'", "C:/hab/pkgs/chef/chef-infra-client/15.6.10/20191210013214/vendor/gems/mixlib-shellout-3.0.7-universal-mingw32/lib/mixlib/shellout.rb:287:in `error!'", . . . "C:/hab/pkgs/chef/chef-infra-client/15.6.10/20191210013214/bin/chef-client:172:in `load'", "C:/hab/pkgs/chef/chef-infra-client/15.6.10/20191210013214/bin/chef-client:172:in `<main>'" ], "end_time_utc": "2020-05-28T18:43:34.000000Z", "automate_fqdn": "automate.example.com", "automate_failure_url": "https://automate.example.com/infrastructure/client-runs/e9c01d6d46543c19fba3b7bfc17a22d/runs/advff4a3-7890-4b74-98c1-fb00ae6dd251" } ``` #### Chef InSpec Scan Failure Example Payload ``` { "type": "compliance_failure", "total_number_of_tests": 436, "total_number_of_skipped_tests": 142, "total_number_of_passed_tests": 79, "total_number_of_failed_tests": 215, "number_of_failed_critical_tests": 212, "number_of_critical_tests": 372, "node_uuid": "e9c01d6d46543c19fba3b7bfc17a22d", "node_name": "winnode1", "inspec_version": "4.18.97", "failure_snippet": "InSpec found a critical control failure on [winnode1](https://automate.example.com/compliance/reporting/nodes/e9c01d6d46543c19fba3b7bfc17a22d)", "failed_critical_profiles": [ { "version": "1.0.1", "title": "Windows Audit", "supports": [], "summary": "Windows Audit Baseline", "sha256": "2e2a41ee574b4ffbe9e190de85e01c57a49b35f047d60bb0e541e95d776fd30e", "number_of_controls": 436, "name": "windows-audit", "maintainer": "<EMAIL>", "license": "Apache-2.0", "copyright_email": "<EMAIL>", "copyright": "Code Owners", "controls": [ { "title": "All important updates are installed", "status": "failed", "source_location": { "ref": "C:/Windows/System32/config/systemprofile/.inspec/cache/f4167795b8659a357e0991a731b3a08321e36f1b29dc2c8ac90e2035ea9db9b6/windows-patch-baseline-0.4.0/controls/patches.rb", "line": 28 }, "results": [ { "status": "failed", "start_time": "2020-05-28T19:02:53+00:00", "skip_message": "", "run_time": 0.00010469999688211828, "message": "expected that `Windows Update 'Windows Malicious Software Removal Tool x64 - v5.82 (KB890830)'` is installed", "code_desc": "Windows Update 'Windows Malicious Software Removal Tool x64 - v5.82 (KB890830)' is expected to be installed" }, { "status": "failed", "start_time": "2020-05-28T19:02:53+00:00", "skip_message": "", "run_time": 0.00013299999409355223, "message": "expected that `Windows Update '2020-02 Security Update for Adobe Flash Player for Windows Server 2019 for x64-based Systems (KB4537759)'` is installed", "code_desc": "Windows Update '2020-02 Security Update for Adobe Flash Player for Windows Server 2019 for x64-based Systems (KB4537759)' is expected to be installed" } ], "refs": [], "number_of_tests": 2, "number_of_failed_tests": 2, "impact": 1, "id": "important-patches", "desc": "", "code": "control 'important-patches' do\n impact 1.0\n title 'All important updates are installed'\n win_update.important.each { |update|\n describe update do\n it { should be_installed }\n end\n }\nend\n" } ], "attributes": [] } ], "automate_fqdn": "automate.example.com", "automate_failure_url": "https://automate.example.com/compliance/reporting/nodes/e9c01d6d46543c19fba3b7bfc17a22d" } ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/notifications/ServiceNow Administrator Reference ================================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/servicenow_reference.md) This page details information on the topics that will aid you while installing and configuring the Chef Automate applications in the ServiceNow ecosystem. * [Integration App](../servicenow_integration/index) * [Incident App](../servicenow_incident_creation/index) Find the Chef Automate features in the ServiceNow instance by searching **Chef** in the **Filer Navigator** . All Chef features display within **Chef Automate** menu. Integration App --------------- ### Benchmarking The Chef Automate Installation team has tested the integration of the Integration App with 10K nodes of Chef Infra Client Run data. Infrastructure with more than 10K nodes may have performance issues. The system performance will decrease with other applications running in your environment. The typical production instance of ServiceNow can have between 8-12K nodes, and will perform at +10K nodes per hour processed with Chef Infra Client run data. Benchmarking indicates that the increase in the number of nodes in the ServiceNow instance reduces the processing time. | Client Nodes | Total Time Taken (Dev 1 Node) | Total Time Taken (Vendor 2 Node) | | --- | --- | --- | | 200 | 7m48s | 4m4s | | 500 | 17m47s | 10m16s | | 2000 | 1h15m | 45m | | 10,000 | 5h40m | 3h3m | ### Events Navigate to the **Events** section by selecting **Chef Automate** > **Events** from ServiceNow. `x_chef_automate.chef.process.data` Triggers when ServiceNow receives node data from either the terminal or the app. ![Event Registration - Process Data] ### Scripts #### Script Actions Navigate to the **Script Actions** section by selecting **Chef Automate** > **Script Actions** from ServiceNow. * The **Asset Process** script action processes events and updates the node data into the *asset import* table. ![Asset Process] * The **Process Software Instance** script action processes events and updates the software installation data in the *CMDB* sever table. ![Process Software Instance] #### Script Includes You can navigate to the **Script Includes** section by selecting **Chef Automate** > **Script Includes** from ServiceNow. `AutomateApi` Calls the Chef Automate API and checks the status of the response. `AutomateApiClient` Updates the token and password in the Chef Automate instance. `BufferToImportUtil` Updates the CPU speed in Linux server, CMDB server, CMDB OSX server, and CMDB win server. `ImportUtil` Updates the compliance import data. `JsonUtil` Updates the JSON objects. `Logger` Updates logging status as `enabled` or `disabled`. `PropertiesUtil` Updates the role in the property. `Util` Updates manufacturer data in the core company table and updates the category and manufacturer data in the *CMDB model* table. ![Script Includes] #### Scripted REST API The **Scripted Rest API** feature aids in establishing a connection between ServiceNow and the Chef Automate application with authentication. You can navigate to this section by selecting **Chef Automate** > **Script Rest API** from ServiceNow. ![Scripted REST Service] ### Transform Maps The **Transform Maps** feature maps the source table, asset import to the target table, and the CMDB Server. You can navigate to the **Transform Maps** section by selecting **Chef Automate** > **Transform Maps** from ServiceNow, and make the required changes. ![Table Transaction Map] ### Field Maps The **Field Maps** establishes a relationship between a field in an import set table and the target table. | Source field | Target field | | --- | --- | | asset_tag | asset_tag | | attributes | attributes | | cpu_core_count | cpu_core_count | | cpu_count | cpu_count | | cpu_manufacturer | cpu_manufacturer | | cpu_speed | cpu_speed | | cpu_type | cpu_type | | disk_space | disk_space | | dns_domain | dns_domain | | host_name | host_name | | ip_address | ip_address | | mac_address | mac_address | | manufacturer | manufacturer | | model | model_id | | model_category_name | x_chef_automate_model_categoryname | | name | name | | os | os | | os_service_pack | os_service_pack | | os_version | os_version | | ram | ram | | serial_number | serial_number | | short_description | short_description | | system_class_name | sys_class_name | | virtual | virtual | | [Script] | install_status | #### Transform Map Scripts **Transformation** events occur while transforming an import set table into a target table. `On Before` Mapping manufacturer, CPU manufacturer, model category, and model by using this script. `On After` The five `On After` scripts required to update the values are: 1. Update **node id**, **node name**, **organization**, **IP address** and insert the record into Chef Automate client run cookbooks, Chef Automate client run recipes, Chef Automate client run lists. 2. Update **software**, **name** and installed in *CMDB software instance* table. 3. Update data in the *cmdb_ci_spkg* table and the *cmdb_software_instance* table. 4. Insert or update data in the *cmdb_ci_file_system* table. 5. Insert or update data in the *cmdb_ci_network_adapter* table. ![Transform Map Scripts] ### Identification and Reconciliation The Identification and Reconciliation rules maintain the integrity of the CMDB by managing duplicate CIs and controlling updates to CIs when multiple data sources are used to create and update CI records. These rules help prevent duplication of CI records, reconcile CI attributes, reclassify CIs, and allow authoritative data sources to update CI records in the CMDB. Identification rules identify new CIs and existing CIs. Identification rules apply to a CI class and consist of a single CI identifier with one or more entries that match CIs based on related attributes or by tables of related CIs. Reconciliation is the synchronization of two or more matching database segments to ensure consistency across them. Reconciliation rules specify which discovery sources can update a table or a set of table attributes, and the precedence order among these discovery sources. You can define these rules at the parent or at the child class level. Without reconciliation rules, discovery sources may be overwritten by updates to attribute from other discovery sources. Refer to ServiceNow’s [CMDB Identification and Reconciliation](https://docs.servicenow.com/bundle/quebec-servicenow-platform/page/product/configuration-management/concept/c_CMDBIdentifyandReconcile.html) page for detailed information on these rules. You can view the reconciliation rules by selecting **CI Class Manager** > **Hierarchy** > **CI Classes** > **Reconciliation Rules** from ServiceNow. ![Reconciliation Rules] page on how to set a reconciliation rule. ![Create Reconcile Rule] Note The Chef Automate Integration App does not provide any reconciliation rules. ### Discovery [ServiceNow’s](https://www.servicenow.com/) Discovery feature finds applications and devices on your network, and then updates the Configuration Management Database (CMDB) with the information it finds. It discovers both physical and logical components, including virtual machines, servers, storage, databases, applications, and more. Refer to ServiceNow’s [Discovery](https://docs.servicenow.com/bundle/paris-it-operations-management/page/product/discovery/reference/r-discovery.html) page for information on Discovery and its types. Integration App Roles --------------------- You can associate a single user with more than one roles. #### Role x_chef_automate.admin You can assign the `x_chef_automate.admin` role to a user other than a System Administrator to allow another user to manage the application properties and logs. The System Administrator authorization includes access to the tasks in the **Admin** role. The **Admin** role grants user access to the: * Asset Imports module * Properties * Chef Automate instances * Servers * Chef Infra Client runs * Compliance reports profiles * Compliance report results * Compliance Profiles * Compliance Profiles results * Support * Events * Script includes * Transform maps * Chef Infra Servers ### Role x_chef_automate.user The `x_chef_automate.user` role is suitable for those users who require application access without administration rights. The role grants a user access to the: * Chef Automate menu * Servers module * Client runs module * CI cookbooks module * Compliance reports module * Compliance reports profiles module * Compliance reports module * Compliance profiles module * Compliance profiles controls module * Logs module * Properties module * Support module Note For integration with CMDB data, you need to assign the *OOB ITIL* role.role for integration with CMDB data in ServiceNow. ### Role x_chef_automate.api The `x_chef_automate.api` role is suitable for users responsible for integrating the Chef Automate data into ServiceNow. We recommend creating a new user specifically for this role. The Chef Automate Integration App requires the API role to set up communication with Chef Automate. Note For integration with CMDB data, you need to assign the *OOB ITIL* role. Also, you must select **Web service** access for this user role. Integration App Properties -------------------------- ### Chef Automate Properties `feed_interval` The frequency in hours for refreshing the data feed. The duration between data feed refreshes is proportional to the node count, with more nodes requiring higher settings. Valid values: Any integer in the range of `2` to `8`. Default: `4`. `node_batch_size` The testing executed for a benchmark. The size of a compliance scan is proportional to the number of profiles applied. Scans exceeding 4MB may fail or display incorrectly in reports. Use a lower `node_batch_size` setting to reduce the number of profiles applied in a single batch. Valid values: Between `1` and `30`. Default: `15`. ### Application Properties The Integration App has nine configurable **Application Properties**. Changing these settings requires the ServiceNow `admin` or `x_chef_automate.admin` permissions. `x_chef_automate.chef.default.status` Used to set up the status of the service record as **inserted** or **updated**. Default: `1`. `x_chef_automate.client_runs_per_node` Used to set a highest number of clients runs for a node. Default: `5`. `x_chef_automate.compliance_reports_per_node` Used to set a highest number of compliance reports for a node. Default: `5`. `x_chef_automate.insert_manufacturer` Inserts the new record during the import if a model is not found in the *core_company* table by settingthe property to **Yes**. Default: `Yes`. `x_chef_automate.insert_model` Inserts the new record during the import if a model is not found in the *cmdb_model* table by setting the property to **Yes**. Default: `Yes` `x_chef_automate. logging.enabled` Used to flag the logging with **enable** or **disable** values. Default: `No`. `x_chef_automate.logging.verbosity` Debugs the data in ServiceNow. Enables the selected logging level and is visible in logs. Valid values: `Debug`, `Warn`, `Info`, `Error`. Default: `Error`. `x_chef_automate.Rest.api` Enables the Chef Automate API from ServiceNow. Set to `Yes` to enable and `No` to disable. Valid Values: `Yes`, `No`. Default: `Yes`. `x_chef_automate.enable.system.app` Used to enable software installed mappings. Valid Values: `Yes`, `No`. Default: `No`. Incident App Roles ------------------ You can associate a single user with more than one role. ### Role `x_chef_incident.admin` You can assign the `x_chef_incident.admin` role to a user other than a System Administrator to allow another user to manage the application properties and logs. The System Administrator authorization includes access to the tasks in the **Admin** role. The **Admin** role grants user access to the: * Chef incidents menu * Client runs menu item * Chef InSpec scans menu item * Properties menu item * Support menu item * Logs menu item ### Role `x_chef_incident.user` The `x_chef_incident.user` role is suitable for those users who require application access without administration rights. The role grants a user access to the: * Chef Incidents menu * Chef Infra Client runs menu item * Chef InSpec scans menu item * Support menu item Note Client run and Chef InSpec scan records are linked to incidents and is appropriate to assign this role to users who manage incidents in ServiceNow. ### Role x_chef_incident.api The `x_chef_incident.api` role is suitable for users responsible for integrating the Chef Automate data into ServiceNow. We recommend creating a new user specifically for this role. The Chef Automate Incident App requires the API role to set up communication with Chef Automate. Incident App Propertie ---------------------- `x_chef_incident.association` Used to associate a Chef Infra Client run record with an Incident record. The possible values are: `cookbook` and `node`. Default: `cookbook`. Setting the value to `cookbook` creates an incident for the failed cookbook. All failing Chef Infra Client runs on nodes associates with the corresponding incident. `cookbook` is the default value as the number of nodes exceeds the number of cookbooks. The short description of the incident indicates the failed cookbook: ![CCR Failed Cookbook Description] The **Chef Infra Client runs** tab of the incident displays the associated client runs. Setting the value to `node` creates an incident for each failed node. All failing Chef Infra Client runs for a node associates with the corresponding incident. The short description of the incident indicates the failed node. ![CCR Failed Node Description] `x_chef_incident.scan_association` Used to associate the Chef InSpec scan record with an incident record. The possible values are: `profile` and `node`. Deault: `profile`. Setting the value to `profile` creates an incident for the failed Chef InSpec compliance profile. All Chef InSpec scans on failing nodes associates with the corresponding incident. `profile` is the default value as the number of nodes exceeds the number of profiles. The short description of the incident indicates the failed profile. ![Scan Failed Profile Description] The **Chef InSpec scans** tab of the incident displays the associated Chef InSpec scans. Setting the value to `node` creates an incident for each failed node. All Chef InSpec scans failing for a node associates with the corresponding incident. The short description of the incident indicates the failed node. ![Scan Failed Node Description] `x_chef_incident.assigned_to` Used to set up the ServiceNow user ID to assign incidents raised by the application. The corresponding group assigns automatically to the incident if the user is in an assignment group. Default: `blank`. `x_chef_incident.assignment_group` Used to set up a group rather than an individual user in the `x_chef_incident.assigned_to` property to assign the incident to a group. Default: `blank`. `x_chef_incident.impact` Used to set an impact value in an incident raised by the application. Possible values are `1`, `2` or `3`. Default: `2`. `x_chef_incident.urgency` Used to set an urgency value in an incident raised by the application. Possible values are `1`, `2` or `3`. Default: `2`. `x_chef_incident.retention_days` Used to define number of days to maintain the Chef Infra Client run and Chef InSpec scan records in ServiceNow. Default: `30`. The ServiceNow app deletes these records of the corresponding closed incidents, deleted incidents, and the removed incidents from the Chef Infra Client run or Chef InSpec scan record by a user update. `x_chef_incident.logging.enabled` Used to flag the logging with **enable** or **disable** status. Once enabled, you can view the logs from the **Chef incidents** > **Logs** menu and the **System logs** > **Application logs** menu by authorized users. Default: `No`. `x_chef_incident.logging.verbosity` Used to debug the data in ServiceNow. Enables the selected logging level and is visible in logs. The possible values are `debug`, `warn`, `info`, and `error`. Default: `error`. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/servicenow_reference/Data Feeds ========== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/datafeed.md) The Data Feed service sends node data to a 3rd party service. This can be useful when updating configuration management databases, external security dashboards, and IT service management platforms. The following types of information are sent: * Ohai data gathered from each managed node - This data includes hardware, operating system, and installed program information. Some variation depends on the managed operating system. * Configuration information about each managed node - This information includes Chef Client Run status, Runlists, Cookbooks, and Recipes running against each node. * Compliance information about each node that shows the compliance state - This information includes passed and failed controls for each profile executed against that node. A Data Feed operates by doing the following: * Every 4 hours, the data-feed-service will aggregate the client runs and compliance reports from the previous 4 hours and send this information to the registered destinations. This time interval is 4 hours by default but is configurable. * If there are no destinations, the aggregation will not occur. * The data aggregates and sends in batches of 50 nodes at a time. The batch amount is 50 by default but is configurable. By default, only Admin users of Chef Automate may create and manage Data Feeds. Data Feed Integration --------------------- Data Feed instance sends client run and compliance scan data to the 3rd party integrations available. To add a Data Feed instance in Chef Automate: * In the **Settings** tab, navigate to *Data Feeds* in the sidebar * Select **New Integration** Currently, the data feed has two types of integrations: * Webhook Integration + ServiceNow + Splunk + ELK + Custom * Storage Integration + Minio + Amazon S3 ![Choose a Data Feed Integration] Webhook Integration ------------------- Create a data feed using a webhook integration. ### ServiceNow To create a data feed select **ServiceNow** from **Settings > Data Feed > New Integration**. 1. **Data Feed Name**: A unique name for this notification. 2. **URL**: The endpoint for the data feed integration, including any specific port details. 3. **Authentication**: Select an authentication method. 1. **Username and Password** * **Username**: The name you use to sign in to ServiceNow. * **Password**: The password you use to sign in to ServiceNow. 2. **Access Token**: * **Token Type**: The prefix for the authorization used to access ServiceNow endpoints. * **Token**: The authorization token value used to access ServiceNow endpoints. 4. Select **Test Connection** to start validating the connection details. 5. Once the test is successful, select **Save** to save the Data Feed configuration. ![Data Feed Instance using ServiceNow Integration] #### Edit a ServiceNow Data Feed Instance To edit a Data Feed instance of ServiceNow Integration: 1. Select the data feed instance name to open its detail page. 2. Edit the Data Feed **Name** or **URL**. 3. Select the **Test Data Feed** button to test the URL. 4. Select **Save** to save your changes. ![Details of Data Feed Instance using ServiceNow Integration] the instance from the buttons provided on the details page. ### Splunk To create a data feed select **Splunk** from **Settings > Data Feed > New Integration**. 1. **Data Feed Name**: A unique name for this notification. 2. **URL**: The endpoint for the data feed integration, including any specific port details. 3. **Authentication**: Select an authentication method. 1. **Username and Password** * **Username**: The name you use to sign in to Splunk. * **Password**: The password you use to sign in to Splunk. 2. **Access Token**: * **Token Type**: The prefix for the authorization used to access Splunk endpoints. * **Token**: The authorization token value used to access Splunk endpoints. 4. Select **Test Connection** to start validating the connection details. 5. Once the test is successful, select **Save** to save the Data Feed configuration. ![Data Feed Instance using Splunk Integration] #### Edit a Splunk Data Feed Instance To edit a Data Feed instance of Splunk Integration: 1. Select the data feed instance name to open its detail page. 2. Edit the Data Feed **Name** or **URL**. 3. Select the **Test Data Feed** button to test the URL. 4. Select **Save** to save your changes. ![Details of Data Feed Instance using Splunk Integration] the instance from the buttons provided on the details page. ### ELK To create a data feed select **ELK** from **Settings > Data Feed > New Integration**. 1. **Data Feed Name**: A unique name for this notification. 2. **URL**: The endpoint for the data feed integration, including any specific port details. 3. **Authentication**: Select an authentication method. 1. **Username and Password** * **Username**: The name you use to sign in to ELK. * **Password**: The password you use to sign in to ELK. 2. **Access Token**: * **Token Type**: The prefix for the authorization used to access ELK endpoints. * **Token**: The authorization token value used to access ELK endpoints. 4. Select **Test Connection** to start validating the connection details. 5. Once the test is successful, select **Save** to save the Data Feed configuration. ![Data Feed Instance using ELK Integration] #### Edit an ELK Data Feed Instance To edit a Data Feed instance of ELK Integration: 1. Select the data feed instance name to open its detail page. 2. Edit the Data Feed **Name** or **URL**. 3. Select the **Test Data Feed** button to test the URL. 4. Select **Save** to save your changes. ![Details of Data Feed Instance using ELK Integration] the instance from the buttons provided on the details page. ### Custom To create a data feed select **Custom** from **Settings > Data Feed > New Integration**. 1. **Data Feed Name**: A unique name for this notification. 2. **URL**: The endpoint for the data feed integration, including any specific port details. 3. **Authentication**: Select an authentication method. 1. **Username and Password** * **Username**: The name you use to sign in to Custom Integration. * **Password**: The password you use to sign in to Custom Integration. 2. **Access Token**: * **Token Type**: The prefix for the authorization used to access Custom Integration endpoints. * **Token**: The authorization token value used to access Custom Integration endpoints. 4. Select **Use Headers** checkbox to add custom headers (For example: `key:value`). 5. Select **Test Connection** to start validating the connection details. 6. Once the test is successful, select **Save** to save the Data Feed configuration. ![Data Feed Instance using Custom Integration] #### Edit a Custom Data Feed Instance To edit a Data Feed instance of Custom Integration: 1. Select the data feed instance name to open its detail page. 2. Edit the Data Feed **Name** or **URL**. 3. Select the **Test Data Feed** button to test the URL. 4. Select **Save** to save your changes. ![Details of Data Feed Instance using Custom Integration] the instance from the buttons provided on the details page. Storage Integration ------------------- Create a data feed using a storage integration. ### Minio To create a data feed select **Minio** from **Settings > Data Feed > New Integration**. 1. **Data Feed Name**: A unique name for this notification. 2. **Endpoint**: The endpoint for the data feed integration, including any specific port details. 3. Enter a **Bucket Name**, **Access Key**, and the **Secret Key** of the instance. 4. Select **Test Connection** to start validating the connection details. 5. Once the test is successful, select **Save** to save the Data Feed configuration. ![Data Feed Instance using Minio Integration] #### Edit a Minio Data Feed Instance To edit a Data Feed instance of Minio Integration: 1. Select the data feed instance name to open its detail page. 2. Edit the Data Feed **Name**, **End Point**, or the **Bucket**. 3. Select the **Test Data Feed** button to test the Endpoint. 4. Select **Save** to save your changes. ![Details of Data Feed Instance using Minio Integration] the instance from the buttons provided on the details page. ### Amazon S3 To create a data feed select **S3** from **Settings > Data Feed > New Integration**. 1. **Data Feed Name**: A unique name for this notification. 2. **URL**: The endpoint for the data feed integration, including any specific port details. 3. Select your **Region** from the drop-down list. 4. Enter a **Bucket Name**, **Access Key**, and the **Secret Key** of the instance. 5. Select **Test Connection** to start validating the connection details. 6. Once the test is successful, select **Save** to save the Data Feed configuration. ![Data Feed Instance using S3 Integration] #### Edit an S3 Data Feed Instance To edit a Data Feed instance of S3 Integration: 1. Select the data feed instance name to open its detail page. 2. Edit the Data Feed **Name**, **Region** or the **Bucket**. 3. Select the **Test Data Feed** button to test the Endpoint. 4. Select **Save** to save your changes. ![Details of Data Feed Instance using S3 Integration] the instance from the buttons provided on the details page. Enable/Disable a Data Feed Instance ----------------------------------- Chef Automate lets you temporarily disable the data feed. It can be helpful if the data feed is going under maintenance or you don’t want to send the node or compliance data to a data feed. The data feed instances are by default enabled when created. To disable a feed: * Select **Disable** from the top left corner of the details page. OR * Select the ellipses icon from the list of data feeds and select **Disable**. ![Disable a Data Feed Instance] To enable a disabled data feed: * Select **Enable** from the top left corner of the details page. OR * Select the ellipses icon from the list of data feeds and select **Enable**. ![Enable a Data Feed Instance] Delete a Data Feed Instance --------------------------- To delete an individual instance: 1. Select the ellipses icon . 2. Select **Delete**. 3. Select **Delete Data Feed** to confirm the action. ![Delete the Data Feed Instance] Configuring Global Data Feed Behavior ------------------------------------- Note The Data Feed configuration settings apply across all configured Data Feed instances. To modify Data Feed behavior with the available configuration settings: * Create a configuration patch file to update the configuration settings. Save this file in the `.toml` file format and name your file as desired. For example, `data-feed-patch.toml` * Include one or more configuration settings and their updated value(s) in your configuration patch `.toml` file to reflect the desired global Data Feed behavior: + Use the `feed_interval` setting to change the interval for the Data Feed collection. The default value is four hours + Use the `node_batch_size` setting to change the number of sets of node data sent in each batch to your endpoint. The default value is 50 nodes + Use the `updated_nodes_only` setting to determine what data to include in each export. The default setting is `true`, which causes the aggregation of only the *changed* data of updated nodes since the last export. Set `updated_nodes_only` to `false`, and it aggregates *all* data of updated nodes since the last export + To reduce the IP address range for the collected and processed node data, update the `disable_cidr_filter` setting to `false` **and** update the `cidr_filter` setting to cover the required IP address range. For example, you may wish to send only production or test node traffic + Use the `accepted_status_codes` setting to define an array of HTTP status codes that the Data Feed Service will treat as `success` if returned by the 3rd party endpoint. If the status code is not in the `accepted_status_codes` list, then an error will be logged * Save your configuration patch file changes before continuing to the next step. * Apply your configuration changes with the Chef Automate command-line tool: ``` chef-automate config patch data-feed-patch.toml ``` ``` where `data-feed-patch.toml` is this example's configuration patch file. ``` ### Configuration Patch File Example ``` [data_feed_service.v1.sys] [data_feed_service.v1.sys.service] feed_interval = "4h" node_batch_size = 50 updated_nodes_only = true disable_cidr_filter = true cidr_filter = "0.0.0.0/0" accepted_status_codes = [200, 201, 202, 203, 204] [data_feed_service.v1.sys.log] level = "info" ``` To debug any issues with the Data Feed Service in Chef Automate, update the following section in your configuration patch file by changing the `log_level` value to “debug”: ``` [data_feed_service.v1.sys.log] log_level = "debug" ``` Data Feed Output Syntax and Details ----------------------------------- The outputted data from Data Feed consists of line-separated JSON strings. Each line represents the data for one node and contains the following properties: ``` { "attributes": { "node_id": "", "name": "", "run_list": [], "chef_environment": "", "normal": {}, "default": {}, "override":{}, "automatic":{}, "normal_value_count": 0, "default_value_count": 1, "override_value_count": 1, "all_value_count": 10, "automatic_value_count": 8 }, "report": { ... }, "client_run": { ... }, "node": { "automate_fqdn": "", "ip_address" : "", "mac_address": "", "description":"", "serial_number":"", "os_service_pack":"" } } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/datafeed/Node Integrations ================= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/node_integrations.md) Set up Chef Automate to detect and monitor the nodes in your AWS EC2 and Azure accounts by providing your credentials and creating a node manager. Chef Automate creates a node reference for each instance in your account. Associate your EC2 and Azure instances with ssh and WinRM credentials using tags–the values support wildcard matching–in your node manager. Run scan jobs with your node manager reference and you’re suddenly running an `inspec exec` across your instances. Every two hours Chef Automate queries your AWS or Azure account to see the current state of all your nodes to determine if they are running, stopped, or terminated, and then updates Chef Automate accordingly. If the node manager finds an instance that used to be running and reachable but which no longer is (the node stopped, terminated, or is in a transition state), the node manager updates the status of that node in Chef Automate accordingly. Access the *Node Integrations* page from the **Settings** tab. ![Node Integrations] Add an AWS EC2 Node Manager --------------------------- Set up Chef Automate to detect and scan the nodes in your AWS EC2 account by providing your AWS Credentials and creating an *AWS EC2 Node Manager* from the **Node Credentials** page in the **Settings** tab. Chef Automate requires your information to detect the nodes in your AWS EC2 account. Chef Automate creates a node reference for each EC2 instance in your account and collects all of the tags associated with each instance. InSpec 2+ supports running scan jobs against your AWS account configuration, such as CloudWatch or IAM, [see more here](../../inspec/resources/index#aws). Set up Chef Automate to run these scan jobs by providing your AWS Credentials and creating an *AWS API Node Manager* in the **Node Integrations** page in the **Settings** tab. To create an AWS EC2 Node Manager, you need the following information: 1. A name for your manager 2. Your AWS credentials (access key ID and secret access key) 3. The default region to target (if `us-east-1` is not desired) ![Chef Automate Create AWS-EC2 Manager] You can use associate your `ssh` or `WinRM` credentials with your EC2 instances using tag keys or values, using the option at the bottom of the screen. This feature supports wildcard matching, which is useful for grouping nodes. Chef Automate detects your nodes immediately after any update to the Node Manager, and maintains a current list of your node status. The following example uses tag with the key ‘Name’ and the value ‘vj-’ to associate those nodes with the ‘ssh ec22’ credential. Filter instances for scanning by specifying either regions or tags by their keys and values. ![Chef Automate Instance Credentials] ### AWS EC2 Node Discovery The service makes these API calls: * `STS-GetCallerIdentity` * `EC2-DescribeRegions` * `EC2-DescribeInstances` * `EC2-DescribeInstanceStatus` * `IAM-ListAccountAliases` Chef Automate’s Node Manager discovers EC2 instances using polling and scan jobs. Polling Chef Automate’s Node Manager calls out to the AWS `DescribeInstanceStatus` API every two hours and discovers the state of all the instances in the account. If the node manager finds any instances that aren’t in its database, it adds them. This sometimes results in “bare bones info” and stopped instances in the database. The node manager updates node information in the database after an instance returns to a running state and a scan job has run on the node. Scan Jobs Whenever a scan job is triggered, the node manager queries the AWS API for all nodes. Any scan reports created for nodes that are not already in the database results in creating a new node in the database. ### Create a Scan Job Targeting Your AWS Account Configuration ![Chef Automate Create AWS-API Scan Job] ### AWS API Scanning Endpoints The service makes calls to these APIs: * `STS-GetCallerIdentity` * `EC2-DescribeRegions` * `IAM-ListAccountAliases` * `IAM-GetAccountSummary` * `IAM-ListUsers` Permissions: You’ll need at least a global read permission; `arn:aws:iam::aws:policy/ReadOnlyAccess` AWS Credential-less Scanning with Chef Automate ----------------------------------------------- For users running Chef Automate 2 in EC2, we invite you to try out our “AWS-EC2 Credential-less Scanning”! Please note that credential-less scanning is not supported for AWS GovCloud. ### Ensure Minimum Permissions Ensure the policy attached to the role used by the instance you have Chef Automate running on has at least these permissions: ``` { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:DescribeInstances", "ssm:*", "ec2:DescribeRegions", "sts:GetCallerIdentity", "ec2:DescribeInstanceStatus", "iam:ListAccountAliases", "iam:GetAccountSummary", "iam:ListUsers", ], "Resource": "*" } ] } ``` Note `"ssm:*"` uses a wildcard match on the AWS EC2 Systems Manager (SSM); You may wish to use a more restrictive policy. ### Install AWS EC2 Systems Manager on Instances Please follow the instructions on [AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html) ### Enable AWS EC2 Systems Manager on Instances In order to use the SSM scan job functionality, your instances must have access to `AmazonEC2RoleforSSM`, or `arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM`. ### Adding an AWS EC2 Node Manager Using IAM Credentials When running in EC2, AWS has the ability to use the IAM role associated with your instance to create and use temporary credentials for accessing the AWS API. If you enable this feature, then you won’t need to provide credentials for your AWS account. You will only be required to provide a name for your node manager. Chef Automate creates a node reference for each EC2 instance in your account, collecting all tags associated with each instance. Chef Automate calls the Amazon System Manager (SSM) to describe instance information and to get ping status for the SSM agent on all instances. A detect job is *not* run on the instances; all instances with an SSM ping status of “Online” will be marked as reachable. ### Create a Scan Job Targeting Your AWS EC2 Instances using AWS SSM The `ssm` Scan Job: 1. Installs the latest stable InSpec from `packages.chef.io` 2. Executes InSpec locally, providing InSpec with the `fqdn` of Chef Automate and a data collector token, so each instance reports directly back to Chef Automate Your Automate instance must be reachable (open to incoming traffic) from the instances being scanned in order for the SSM scanning to work. You can filter the instances to be scanned by specifying tag key/value matches or regions. ![Chef Automate Create AWS-EC2 Scan Job] ### AWS Credential-less Scanning The service makes these API calls: * `STS-GetCallerIdentity` * `EC2-DescribeRegions` * `EC2-DescribeInstances` * `EC2-DescribeInstanceStatus` * `SSM-DescribeInstanceInformation` * `SSM-SendCommand` * `SSM-ListCommands` Azure VM Scanning with Chef Automate ------------------------------------ Set up Chef Automate to detect and scan the nodes in your Azure account by providing your Azure Credentials and creating an *Azure VM Node Manager*. To add an Azure VM Node Manager, navigate to the [*Node Integrations*](index) page in the Settings tab, select `Create Integration`, and you should see *Azure* as one of your node management service options. Note We do not support Azure Government Cloud. ### Adding an Azure VM Node Manager When creating an Azure VM Node Manager, you will be required to provide: 1. A name for your manager 2. Your Azure credentials (client ID, client secret, and tenant ID) This information is required to detect the nodes in your Azure account. Chef Automate creates a nodes reference for each VM in your account, reading in all tags associated with each instance. Chef Automate detects your nodes immediately after any update to the Node Manager in order to maintain a current list of your node status. The following example uses a tag with the key ‘Name’ and the value ‘vj-’ to associate those nodes with the ‘ssh ec2’ credential. ![Chef Automate Create Azure-VM Manager] Chef Automate uses Azure’s RunCommand functionality to run scan jobs on instances without needing `ssh` and `WinRM` credentials. In order for this functionality to work, the Automate instance must be reachable (open to incoming traffic) from the instances being scanned. You also have the option of using the traditional `ssh` and `WinRM` scanning by providing such credentials for the VMs. At the bottom of the screen there is an option to associate `ssh` and `WinRM` credentials with your VMs using tag keys and values (supports wildcard match) to group nodes. If the tag key matches, the value of the tag is evaluated against the user provided value: ``` - foo* -> tag value has a prefix of "foo" == match - *foo -> tag value has a suffix of "foo" == match - *foo* -> tag value contains substring "foo" == match - foo -> tag value is exactly "foo" == match ``` Chef Automate detects your nodes immediately after any update to the Node Manager, keeping a current view of your nodes' reachability. ![Chef Automate Instance Credentials] ### Create a Scan Job Targeting Your Azure VMs Filter the regions for the scan job by specifying regions to include or exclude. Filter instances for scanning by specifying either regions or tags by their keys and values. ![Chef Automate Create Azure-VM Scan Job] Use Case: Azure Account Scanning with Chef Automate --------------------------------------------------- InSpec 2+ supports running scan jobs against your Azure account configuration, such as network security groups and ad users. See [Azure resources](../../inspec/resources/index#azure) for more information. Set up Chef Automate to run these scan jobs by providing your Azure credentials and creating an *Azure API Node Manager*. ### Adding an Azure API Node Manager When creating an Azure API Node Manager, you will be required to provide: 1. A name for your manager 2. Your Azure credentials (client ID, client secret, and tenant ID) 3. Subscription ID (optional) This information is required to detect all subscriptions available to your Azure account. Chef Automate creates a nodes reference for each subscription in your account. ![Chef Automate Create API-Azure Manager] ### Create a Scan Job Targeting Your Azure Account Configuration From the **Scan Jobs** tab, select the “Create new job” button. Filter the regions for the scan job by specifying regions to include or exclude. ![Chef Automate Create Azure-API Scan Job] Google Cloud Platform Account Scanning with Chef Automate --------------------------------------------------------- Run scans against your GCP account infrastructure using Chef Automate. Set up Chef Automate to detect and scan the nodes in your Google Cloud Platform (GCP) account by providing your GCP Credentials and creating a *GCP Node Manager*. To create a GCP Node Manager, navigate to *Node Integrations*, select `Create Integration`, and you should see *Google Cloud* as one of your node management service options. See the Chef InSpec documentation for more infomation about [GCP resources](../../inspec/resources/index#gcp). To run a GCP scan in Chef Automate: 1. Add a GCP-API Node Manager using a service account json credential 2. The service adds a node reference in the database for the project tied to the service account credential 3. Execute a profile against the project reference with a scan job This information is required to detect all subscriptions available to your Azure account. Chef Automate creates a nodes reference for each subscription in your account. Note: The service account json credential requires the following fields: `type`, `project_id`, `client_id`, `private_key_id`, `private_key`, `client_email`, `auth_uri`, `token_uri`, `auth_provider_x509_cert_url`, `client_x509_cert_url` ![Chef Automate Create GCP-API Integration] Set up Chef Automate to detect and monitor the nodes in your AWS EC2 and Azure accounts by providing your credentials in the [Node Credentials](../node_credentials/index) page in the Settings tab and creating a node manager. Chef Automate creates a node reference for each instance in your account. Associate your EC2 and Azure instances with ssh and WinRM credentials using tags–the values support wildcard match–in your node manager. Run scan jobs with your node manager reference and you’re suddenly running an `inspec exec` across your instances. Every two hours Chef Automate queries your AWS or Azure account to see the current state of all your nodes, if they are running, stopped, or terminated, and then updates Chef Automate accordingly. If the node manager finds an instance that used to be running and reachable, but which no is–if the node is stopped, terminated, or a transition state–it updates the status of that node in Chef Automate accordingly. ### Create a Scan Job Targeting Your GCP Account Configuration From the **Scan Jobs** tab, select the “Create new job” button. Filter the regions for the scan job by specifying regions to include or exclude. ![Chef Automate Create GCP-API Scan Job] © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/node_integrations/Data Lifecycle ============== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/data_lifecycle.md) Data Lifecycle manages the retention of events, service groups, Chef Infra Client runs, compliance reports and scans in Chef Automate. Chef Automate stores data from the ingest-service,event-feed-service, compliance-service and applications-service in Elasticsearch or PostgreSQL. Over time, you may wish to remove that data from Chef Automate by using the data lifecycle settings. Data Lifecycle UI ----------------- Navigate to *Settings* > *Data Lifecycle* and adjust any settings you would like to change. After making changes, use the **Save Changes** button to apply your changes. Users with `dataLifecycle:*` IAM access are able to see the data lifecycle job statuses, configure jobs, or run jobs. ![Data Lifecycle] ### Event Feed The Event Feed Data Lifecycle settings allow you to remove all event feed data and Chef Infra Server actions after a set amount of days. The default is to remove event feed data after 7 days, and Chef Infra Server actions after 30 days. ### Service Groups The Service Group Data Lifecycle settings allow you to label health check reports as disconnected and automatically remove them after a set amount of time. The default is to label health check reports as disconnected after 5 minutes, and remove disconnected services after 7 days. ### Client Runs The Client Runs data lifecycle settings allow you to remove data after a set amount of days. They also allow you to label nodes as missing and automatically remove them after a set amount of days. The default is to remove Chef Infra Client run data after 30 days, to label nodes as missing after 1 day, and to remove nodes labeled as missing after 30 days. ### Compliance The Compliance data lifecycle settings allow you to remove compliance reports and compliance scans after a set amount of days. The default is to remove compliance reports after 60 days, and to remove compliance scans after 60 days. Data Lifecycle API ------------------ Chef Automate stores data from the `ingest-service`, `event-feed-service`, `compliance-service` and `applications-service` in Elasticsearch or PostgreSQL. The `data-lifecycle` API allows configuring and running lifecycle jobs by data type: * `infra` - Chef Infra Server actions and Chef Infra Client converge data * `compliance` - Chef InSpec reports and Chef Compliance scans * `event-feed` - Event metadata that powers the operational visibility and query language * `services` - Chef Habitat Services data To see the data lifecycle job statuses, configure jobs, or run jobs requires an [api token](../api_tokens/index) with `dataLifecycle:*` IAM access. ### Status To see the combined status and configuration for all data lifecycle jobs, you can use the global status endpoint: ``` curl -s -H "api-token: $TOKEN" https://automate.example.com/api/v0/data-lifecycle/status ``` To see individual statuses by data type, you can access the data type sub-status endpoints: ``` curl -s -H "api-token: $TOKEN" https://automate.example.com/api/v0/data-lifecycle/event-feed/status ``` Swap `event-feed` for `infra` or `compliance` or `services` to see their corresponding jobs. The status is the total of the job configuration, details about its next scheduled run, and details about any previous runs. ### Configuration Configure the data lifecycle job settings by creating a JSON file with the desired configuration. ``` { "infra": { "job_settings": [ { "name":"delete_nodes", "disabled": true, "recurrence": "FREQ=MINUTELY;DTSTART=20191106T180240Z;INTERVAL=15", "threshold": "365d" }, { "name":"missing_nodes", "disabled": false, "recurrence": "FREQ=MINUTELY;DTSTART=20191106T180240Z;INTERVAL=15", "threshold": "1d" }, { "name":"missing_nodes_for_deletion", "disabled": false, "recurrence": "FREQ=MINUTELY;DTSTART=20191106T180240Z;INTERVAL=15", "threshold": "30d" }, { "name":"periodic_purge_timeseries", "disabled": false, "recurrence": "FREQ=DAILY;DTSTART=20191106T180240Z;INTERVAL=1", "purge_policies": { "elasticsearch": [ { "policy_name": "actions", "older_than_days": 30, "disabled": false }, { "policy_name": "converge-history", "older_than_days": 30, "disabled": false } ] } } ] }, "compliance": { "job_settings": [ { "name": "periodic_purge", "disabled": false, "recurrence": "FREQ=DAILY;DTSTART=20191106T180323Z;INTERVAL=1", "purge_policies": { "elasticsearch": [ { "policy_name": "compliance-reports", "older_than_days": 100, "disabled": false }, { "policy_name": "compliance-scans", "older_than_days": 100, "disabled": false } ] } } ] }, "event_feed": { "job_settings": [ { "name": "periodic_purge", "disabled": false, "recurrence": "FREQ=DAILY;DTSTART=20191106T180243Z;INTERVAL=2", "purge_policies": { "elasticsearch": [ { "policy_name": "feed", "older_than_days": 90, "disabled": false } ] } } ] }, "services": { "job_settings": [ { "name": "disconnected_services", "disabled": false, "recurrence": "FREQ=SECONDLY;DTSTART=20200612T182105Z;INTERVAL=60", "threshold": "5m" }, { "name": "delete_disconnected_services", "disabled": false, "recurrence": "FREQ=SECONDLY;DTSTART=20200612T182105Z;INTERVAL=60", "threshold": "7d" } ] } } ``` Configure the jobs by sending the JSON payload to the `config` endpoint. Note The data sent to the `config` endpoint intentionally follows a different format than the data returned from the `status` endpoint. You cannot read the data on the `status` endpoint, change some values, and feed the modified data back on the `config` endpoint. Save the JSON file as `config.json` in the current working directory: ``` curl -s -H "api-token: $TOKEN" -X PUT --data "@config.json" https://automate.example.com/api/v0/data-lifecycle/config ``` If you wish to configure a specific endpoint, you can specify the `job_settings` for that data type and configure it using data types sub-resource. For example, if you want to configure compliance settings, create a smaller JSON payload: ``` { "job_settings": [ { "name": "periodic_purge", "disabled": false, "recurrence": "FREQ=DAILY;DTSTART=20191106T180323Z;INTERVAL=1", "purge_policies": { "elasticsearch": [ { "policy_name": "compliance-reports", "older_than_days": 100, "disabled": false }, { "policy_name": "compliance-scans", "older_than_days": 100, "disabled": false } ] } } ] } ``` And update the specific endpoint using the `compliance` sub-resource: ``` curl -s -H "api-token: $TOKEN" -X PUT --data "@config.json" https://automate.example.com/api/v0/data-lifecycle/compliance/config ``` #### Job Settings All jobs have the following options: * `recurrence` (string) - A recurrence rule that determines how often, at what interval, and when to initially start a scheduled job. Any valid recurrence rule [as defined in section 4.3.10 of RFC 2445](https://www.ietf.org/rfc/rfc2445.txt) is valid in this field. * `disabled` (bool) - True or false if this job is enabled. Infra node lifecycle jobs have the following options: * `threshold` (string) - Setting that allows the user to use `1w` style notation to denote how long before the Infra job triggers. Purge jobs have the following options: * `purge_polices` (map) - Configures how old the corresponding data must be in the configured storage backend before purging occurs. + `elasticsearch` (array) - An array of Elasticsearch purge policies - `disabled` (bool) - True or false if this job is enabled. - `policy_name` (string) - The name of the purge policy you wish to update. - `older_than_days` (int) - The threshold for what qualifies for deletion. Services jobs have the following options: * `threshold` (string) - Setting that allows the user to use `1m` style notation to select the services the task operates on. ##### Infra Job Settings The `infra` data type has four data lifecycle jobs: three are for node lifecycle and one is for purge job with two Elasticsearch purge policies. ``` { "job_settings": [ { "name":"delete_nodes", "disabled": true, "recurrence": "FREQ=MINUTELY;DTSTART=20191106T180240Z;INTERVAL=15", "threshold": "365d" }, { "name":"missing_nodes", "disabled": false, "recurrence": "FREQ=MINUTELY;DTSTART=20191106T180240Z;INTERVAL=15", "threshold": "1d" }, { "name":"missing_nodes_for_deletion", "disabled": false, "recurrence": "FREQ=MINUTELY;DTSTART=20191106T180240Z;INTERVAL=15", "threshold": "30d" }, { "name":"periodic_purge_timeseries", "disabled": false, "recurrence": "FREQ=DAILY;DTSTART=20191106T180240Z;INTERVAL=1", "purge_policies": { "elasticsearch": [ { "policy_name": "actions", "older_than_days": 30, "disabled": false }, { "policy_name": "converge-history", "older_than_days": 30, "disabled": false } ] } } ] } ``` * `delete_nodes` - How long a node can exist before deletion. * `missing_nodes` - How long between a node’s last check-in before marked as missing. * `missing_nodes_for_deletion` - How long a node can be missing before deletion * `periodic_purge_timeseries` - How often to run the purge job + `actions` - Chef Infra Server actions + `converge-history` - Chef Infra Client converge data ##### Compliance Job Settings The `compliance` data type has one compliance purge job with two Elasticsearch purge policies. ``` { "job_settings": [ { "name": "periodic_purge", "disabled": false, "recurrence": "FREQ=DAILY;DTSTART=20191106T180323Z;INTERVAL=1", "purge_policies": { "elasticsearch": [ { "policy_name": "compliance-reports", "older_than_days": 100, "disabled": false }, { "policy_name": "compliance-scans", "older_than_days": 100, "disabled": false } ] } } ] } ``` * `periodic_purge` - How often to run the purge job + `compliance-reports` - Chef InSpec reports + `compliance-scans` - Chef Compliance scans ##### Event Feed Job Settings The `event_feed` data type has one event feed purge job with one Elasticsearch purge policy. ``` { "job_settings": [ { "name": "periodic_purge", "disabled": false, "recurrence": "FREQ=DAILY;DTSTART=20191106T180243Z;INTERVAL=2", "purge_policies": { "elasticsearch": [ { "policy_name": "feed", "older_than_days": 90, "disabled": false } ] } } ] } ``` * `periodic_purge` - How often to run the purge job + `feed` - Queryable event feed ##### Services Job Settings The `services` data type has two jobs, one to mark services as disconnected when the elapsed time since Chef Automate last received a health check message exceeds the threshold, and one to delete services when the time since the last health check exceeds the threshold. ``` { "job_settings": [ { "name": "disconnected_services", "disabled": false, "recurrence": "FREQ=SECONDLY;DTSTART=20200612T182105Z;INTERVAL=61", "threshold": "5m" }, { "name": "delete_disconnected_services", "disabled": false, "recurrence": "FREQ=SECONDLY;DTSTART=20200612T182105Z;INTERVAL=61", "threshold": "7d" } ] } ``` ### Run As with `status` and `configure`, you can run data lifecycle jobs globally across all data or by using the data type sub-resource. To run all data lifecycle jobs, run the following command: ``` curl -s -H "api-token: $TOKEN" -X POST https://automate.example.com/api/v0/data-lifecycle/run ``` To run jobs for a specific data type, you can make the request to the sub-resource: ``` curl -s -H "api-token: $TOKEN" -X POST https://automate.example.com/api/v0/data-lifecycle/infra/run ``` Swap `infra` for `event-feed` or `compliance` to run their corresponding jobs. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/data_lifecycle/Teams ===== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/teams.md) Overview -------- A Chef Automate team is an assigned grouping of users. You can import existing teams into Chef Automate with [Microsoft AD (LDAP)](../ldap/index#microsoft-active-directory), [generic LDAP](../ldap/index), or [SAML](../saml/index). You can also create local Chef Automate teams that are independent of LDAP or SAML. Permission for the `iam:teams` action is required to interact with teams. Any user that is part of the `admins` team or the `Administrator` policy will have this permission. Otherwise, [IAM custom policies](../iam_v2_guide/index#creating-custom-policies) can be created to assign this permission. Managing Local Teams -------------------- ### Admins Team Chef Automate comes with an *Admins* team by default. Local users can be added directly to this team, which assigns admin permissions to users. ### Creating Local Teams Navigate to *Teams* in the **Settings** tab. Select the **Create Team** button, which opens a dialog box to enter the team’s *Name* and optionally assign the team to one or more *Projects*. A team ID automatically generates upon creation. If you would like to change the team ID, use the **Edit ID** button. ![Create Local Team] ### Adding Local Users to Teams To add local users to a team, navigate to *Teams* from the **Settings** tab and locate the team. Navigate to the team’s page, and then use the **Add Users** button. ### Removing Local Users from Teams To remove local users from a team, navigate to *Teams* from the **Settings** tab and locate the team. Navigate to the team’s page, locate the user to remove, and then use the menu at the end of the table row to remove the user. ### Changing Team Details Teams have both a team name and the projects that a team belongs to. To change, navigate to *Teams* from the **Settings** tab, select an individual team, and then navigate to the **Details** tab. ### Deleting Local Teams Navigate to *Teams* in the **Settings** tab. Then open the menu at the end of the table row and select **Delete Team**. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/teams/Troubleshooting =============== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/troubleshooting.md) chef-automate CLI Errors ------------------------ ### Error: Unable to make a request to the deployment-service The `chef-automate` CLI emits this error when the CLI is unable to communicate with a Chef Automate deployment. In particular, when Chef Automate 2 (as distinct from Chef Automate 1) is not deployed, running `chef-automate` CLI commands such as `version` or `status` causes this error. File exists (os error 17) ------------------------- It’s possible for the following error to be emitted when deploying Chef Automate: ``` DeploymentServiceCallError: A request to the deployment-service failed: Request to configure deployment failed: rpc error: code = Unknown desc = failed to binlink command "chef-automate" in pkg "chef/automate-cli/0.1.0/20181212085335" - hab output: >> Binlinking chef-automate from chef/automate-cli/0.1.0/20181212085335 into /bin xxx xxx File exists (os error 17) xxx : exit status 1 ``` This problem can be fixed by removing the `chef-automate` binary from the `/bin` directory. The binary should not be placed in the PATH manually as the deployment process will do it. Compliance Report Display ------------------------- If the size of a Compliance Report is over 4MB, then the *Reports* page (Compliance > Reports) may not display as expected. [Audit Cookbook 9.4.0 and later](https://github.com/chef-cookbooks/audit) supports some attribute options that trims a report to its smallest size when combined with latest Chef Automate version. Contact Chef Support to determine the best way to manage your Compliance Report size. Low Disk Space -------------- Chef Automate emits a warning when the available disk space on the system drops below 1 GB, for example: ``` es-sidecar-service.default(O): time="2018-05-16T00:07:16Z" level=error msg="Disk free below critical threshold" avail_bytes=43368448 host=127.0.0.1 mount="/ (overlay)" threshold_bytes=536870912 total_bytes=31361703936 ``` ### Recovering from Low Disk Conditions Chef Automate disables disk writes if available disk space drops below 250 MB and logs a message similar to: ``` ingest-service.default(O): time="2018-05-16T00:10:09Z" level=error msg="Message failure" error="rpc error: code = Internal desc = elastic: Error 403 (Forbidden): blocked by: [FORBIDDEN/12/index read-only / allow delete (api)]; [type=cluster_block_exception] elastic: Error 403 (Forbidden): blocked by: [FORBIDDEN/12/index read-only / allow delete (api)]; [type=cluster_block_exception]" ``` After freeing up disk space, you will need to remove the write block on the Elasticsearch indices by running: ``` curl -X PUT "localhost:10141/_all/_settings" -H 'Content-Type: application/json' -d' { "index.blocks.read_only_allow_delete": null } ' ``` To confirm that you’ve successfully removed the blocks, run: ``` curl 'localhost:10141/_all/_settings' ``` Verify that the output does not contain `"blocks":{"read_only_allow_delete":"true"}`. Uninstalling Chef Automate -------------------------- The following procedure will remove Chef Automate from your system, including all data. If you wish to preserve the data, make a backup before uninstalling. With the `chef-automate` CLI: ``` chef-automate uninstall ``` Resetting the Admin Password ---------------------------- Use the following command to completely reset a lost, forgotten, or compromised admin password: ``` chef-automate iam admin-access restore NEW_PASSWORD ``` This command causes Automate to inspect your A2 IAM resource and initiates a series of steps for applying the new password to the “admin” user–in effect reconstituting the admin–and connecting it with full administrative permissions. The process Automate follows for resetting the admin password may include: recreating the user record, recreating the “admins” local team, and recreating the default policy that grants access to all resources for the newly reconstituted local admin team. To see what exactly will happen in your system, pass `--dry-run`: ``` chef-automate iam admin-access restore NEW_PASSWORD --dry-run ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/troubleshooting/Node Credentials ================ [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/node_credentials.md) The Chef Automate Credentials page allows you to add, edit, and delete `SSH`, `WinRm`, and `Sudo` credentials for remotely access to your nodes. To manage your credentials, navigate to the *Node Credentials* page from the **Settings** tab. ![Node Credentials] Adding SSH, WinRM, and Sudo credentials is the first step for using the Chef Automate Compliance Scanner. After adding credentials, you’ll be able to add nodes and create scan jobs. Depending on how you’ve set up your nodes, you may need to set up more than one key that uses the same SSH Private Key with different usernames. For example, AWS EC2 Amazon Linux nodes require the username `ec2-user`, while AWS EC2 Ubuntu nodes require the username `ubuntu` or `root`. The **Credentials** page enables saving two different sets of credentials, both using the same SSH Private Key and different user names. However, credentials with different content may also reuse identical key names; it may be advisable to reduce confusion by follow a naming pattern specifying the key name and platform to distinguish between similar credentials. Warning A credential name may be reused, even when it contains different usernames or keys. Add a Credential ---------------- Select *Add Credential* and a dialog box appears as shown below. Select the *Credential Type* drop box to choose the desired credential type. ### Add a SSH Credential ![SSH Credential Form] **SSH** requires a credential name, a user name and either a SSH password **or** a SSH Private key, but not both. ### Add a WinRM Credential ![WINRM Credential Form] **WinRM** requires a credential name, a user name, and a WinRM password. Windows machines **must have** the following configurations: * Ports 3389(RDP), 80(HTTP), 443(HTTPS), 5985(WinRM) and 5986(WinRM) must be open and reachable from Chef Automate. * Use the below script to configure WinRM: ``` winrm quickconfig -q winrm create winrm/config/Listener?Address=*+Transport=HTTP winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="1024"}' winrm set winrm/config '@{MaxTimeoutms="1800000"}' winrm set winrm/config/winrs '@{MaxShellsPerUser="50"}' winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="1024"}' winrm set winrm/config/service '@{AllowUnencrypted="true"}' winrm set winrm/config/service/auth '@{Basic="true"}' netsh advfirewall firewall add rule name="WinRM 5985" protocol=TCP dir=in localport=5985 action=allow netsh advfirewall firewall add rule name="WinRM 5986" protocol=TCP dir=in localport=5986 action=allow NetSh Advfirewall set allprofiles state off net stop winrm sc.exe config winrm start=auto net start winrm ``` ### Add a Sudo Credential ![Sudo Credential Form] **Sudo** requires a credential name, a user name, and a password **or** sudo options, but not both. Credentials will be visible in the *Node Credentials* view after using the **Save Credential** button. If you are not redirected to the credentials list, then review the credential you are attempting to add. Manage Credentials ------------------ * Edit a credential by selecting the credential’s name, which opens the credential’s detail page. * Delete a credential by selecting **Delete** from the menu at the end of the table row. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/node_credentials/Policies ======== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/policies.md) Overview -------- Identity and Access Management policies manage the resources and actions used by identities. Policies are composed of statements that specify permissions. Permission for the `iam:policies` action is required to interact with policies. Any user that is part of the `admins` team or the `Administrator` policy will have this permission. Otherwise, [IAM custom policies](../iam_v2_guide/index#creating-custom-policies) can be created to assign this permission. ![] ### Chef-Managed Policies *Chef-managed* policies are provided by Chef and are integral to the operation of Chef Automate. The policy statements in Chef-managed policies cannot be changed. ### Custom Policies *Custom* policies are policies that you create for your own needs. You can add, edit, and delete policy statements in your custom policies. Chef Automate ships with two custom policies, Compliance Viewers and Compliance Editors, which you can edit like other custom policies. Managing Policies ----------------- ### Creating Policies *Custom* policies can only be created using the [Policies API](https://docs.chef.io/automate/api/#tag/policies). ### Deleting Policies Navigate to *Policies* in the **Settings** tab. Then open the menu at the end of the table row and select **Delete Policy**. ### Policy Membership The policy membership can be changed for both *Chef-Managed* and *Custom* policies. The only exception is that the *admins* team cannot be removed from the *Administrator* policy. #### Adding Members to Policies To add members to a policy, navigate to *Policies* in the **Settings** tab and locate the policy. Navigate to the policy’s detail page and use the **Add Members** button. Select local users or teams from the list, or use the **Add Member Expression** button to add API Tokens, and SAML or LDAP users or groups. #### Removing Members from Policies To remove members from a policy, navigate to *Policies* in the **Settings** tab and locate the policy. Navigate to the policy’s detail page and select the **Members** tab. Then locate the member to remove and use the menu at the end of the table row to remove the user. ### Changing Policy Details For *custom* policies, use the [Policies API](https://docs.chef.io/automate/api/#tag/policies) to change the policy name, statements, and projects. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/policies/API Tokens ========== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/api_tokens.md) Overview -------- API Tokens are used to access the Chef Automate API. They are the only way to authenticate against the Chef Automate API. Tokens can be added as members of policies in order to grant them permissions. Permission for the `iam:tokens` action is required to interact with tokens. Any user that is part of the `admins` team or the `Administrator` policy will have this permission. Otherwise, [IAM custom policies](../iam_v2_guide/index#creating-custom-policies) can be created to assign this permission. Managing API Tokens ------------------- ### Creating API Tokens Navigate to *API Tokens* in the **Settings** tab. Then, use the **Create Token** button, which opens a dialog box for entering the API token’s *name* and optionally assigning the API token to one or more *Policies* and to one or more *Projects*. A token ID automatically generates upon creation. If you would like to change the token ID, select the **Edit ID** button. If a policy is assigned to an API token on creation, the API token will have permissions. If no policy is selected during its creation, the API token will have no permissions. To assign permissions to the API token any time after creation, navigate to *Policies* in the **Settings** tab, locate the appropriate policy, and then add the API token as a member of the policy using a [member expression](../iam_v2_guide/index#member-expressions). ![API Tokens] #### API Token Value After creating an API Token, you can obtain the token’s value by opening the menu at the end of the table row and selecting **Copy Token**. #### Admin Tokens Admin tokens are tokens that are automatically added to the Administrator policy, which grants full access to Chef Automate. Admin tokens can only be created using the `chef-automate` command line. ``` chef-automate iam token create <your-token-name> --admin ``` To create an admin token and immediately store it in an environment variable for easy access, you can instead run: ``` export TOKEN=`chef-automate iam token create <your-token-name> --admin` echo $TOKEN ``` Once you have an Admin API token, you can use it to make requests by passing it in the `api-token` header: ``` curl -s -H "api-token: $TOKEN" https://automate.example.com/apis/iam/v2/policies -v ``` ### Deleting API Tokens Navigate to *API Tokens* in the **Settings** tab. Then open the menu at the end of the table row and select **Delete Token**. ### Changing API Token Details The API token name, projects the token belongs to, and the token’s status can be changed by navigating to *API Tokens* from the **Settings** tab, selecting an individual token and then navigating to the **Details** tab. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/api_tokens/User Profile ============ [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/chef_automate_profile.md) Overview -------- Chef Automate users can manage their display name, date/time format, and password. Select the user icon in the top navigation bar, and select **Profile** from the drop-down menu. ![Profile Section in Chef Automate] Select **Profile** to view the details. The **Details** tab updates the *Display Name* and the *Time Format*, whereas the **Reset Password** tab edits the password. ### Change a Display Name Change the display name by entering any preferred name. Select **Save** to update the name. ![Display Name of Chef Automate] Every user needs a display name. An empty display name causes an error. ![Error in Display Name] ### Change the Date/Time Format Select one of the five date and time formats from the drop-down menu. Select **Save** to change the appearance of the date and time across Chef Automate. ![Date/Time Format] Select the date/time format and save to get the changes reflected in the interface. ### Reset Password Reset the password of Chef Automate login from the **Reset Password** tab in Profile. ![Reset Password From Profile] Insert the *Previous Password* and the *New Password* and select **Reset Password**. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/chef_automate_profile/Users ===== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/users.md) Overview -------- Chef Automate supports three different types of users: local users, [LDAP users](../ldap/index), and [SAML users](../saml/index). Manage local users from the **Settings** tab. Local users can sign in and interact with the system independent of LDAP or SAML. Local users will have their Chef Automate sessions refreshed while their Chef Automate browser window remains open or until they sign out directly. Permission for the `iam:users` action is required to interact with users other than yourself. Any user that is part of the `admins` team or the `Administrator` policy will have this permission. Otherwise, [IAM custom policies](../iam_v2_guide/index#creating-custom-policies) can be created to assign this permission. Managing Local Users -------------------- ### Creating Local Users Navigate to *Users* in the **Settings** tab. Select the **Create User** button, which opens a dialog box for entering the user’s *display name*, and *password*. A username automatically generates upon creation. If you would like to change the username, use the **Edit Username** button. ![Add Local User] ### Changing Display Names Navigate to *Users* in the **Settings** tab and locate the user who needs their display name changed. Navigate to their user page, provide a new display name, and select the **Save** button. All local users can also change their own display names from the *Profile* menu. ### Resetting Passwords Navigate to *Users* in the **Settings** tab and locate the user who needs a password reset. Navigate to their user page, and then the **Reset Password** tab. Provide a new password, confirm the new password, and then select the **Reset Password** button. All local users can also reset their own passwords from the *Profile* menu. ### Deleting Local Users Navigate to *Users* in the **Settings** tab. Then open the menu at the end of the table row and select **Delete User**. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/users/Roles ===== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/roles.md) Overview -------- Chef Automate Identity and Access Management roles are named groups of actions used to define [policies](../policies/index). Actions describe what is allowed by users in Automate. [IAM Actions](../iam_actions/index) describes the associated action or actions required to access certain pages in the browser. Users require permission for the `iam:roles` action to interact with roles. Any user that is part of the `admins` team or the `Administrator` policy will have this permission. Otherwise, [IAM custom policies](../iam_v2_guide/index#creating-custom-policies) can be created to assign this permission. ![] ### Chef-Managed Roles Chef-managed roles are roles provided by Chef that cannot be changed. | Role | Description | | --- | --- | | Viewer | **View** everything in the system *except* IAM | | Editor | **Do** everything in the system *except* IAM and license application | | Owner | **Do** everything in the system *including* IAM | | Project Owner | Editor + **view** and **assign** projects | | Ingest | Ingest data into the system | #### Actions for Chef-Managed Roles | Name | ID | Actions | | --- | --- | --- | | Owner | owner | * | | Project Owner | project-owner | infra:nodes:*, infra:nodeManagers:*, compliance:*, event:*, ingest:*, secrets:*, iam:projects:list, iam:projects:get, iam:projects:assign, iam:policies:list, iam:policies:get, iam:policyMembers:*, iam:teams:list, iam:teams:get, iam:teamUsers:*, iam:users:get, iam:users:list, applications:* | | Editor | editor | infra:infraServers:list, infra:infraServers:get, infra:nodes:*, infra:nodeManagers:*, compliance:*, event:*, ingest:*, secrets:*, iam:projects:list, iam:projects:get, iam:projects:assign, applications:* | | Viewer | viewer | infra:infraServers:list, infra:infraServers:get, secrets:*:get, secrets:*:list, infra:nodes:get, infra:nodes:list, infra:nodeManagers:get, infra:nodeManagers:list, compliance:*:get, compliance:*:list, event:*:get, event:*:list, ingest:*:get, ingest:*:list, iam:projects:list, iam:projects:get, applications:*:get, applications:*:list | | Ingest | ingest | infra:ingest:*, compliance:profiles:get, compliance:profiles:list | ### Custom Roles Custom roles are roles that any user with the permission for `iam:roles:update` can change. In addition to the Chef-managed roles above, Chef Automate includes two custom roles by default. | Role | Description | | --- | --- | | Compliance Viewer | Viewer for compliance resources | | Compliance Editor | Editor for compliance resources | You can edit these custom roles like other user-created custom roles. Managing Roles -------------- ### Creating Roles *Custom* roles can only be created using the [Roles API](https://docs.chef.io/automate/api/#tag/roles). #### Example Custom Role ``` { "name": "Advocate", "id": "advocate-role", "actions": [ "infra:*", "compliance:*", "teams:*", "users:*" ], "projects": [ "east-region", "west-region" ] } ``` ### Changing Role Details For *custom* roles, use the [Roles API](https://docs.chef.io/automate/api/#tag/roles) to change the role name, actions list, and projects. ### Deleting Roles Navigate to *Roles* in the **Settings** tab. Then open the menu at the end of the table row and select **Delete Role**. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/roles/Architecture ============ [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/architectural_overview.md) Automate 2 Architecture ----------------------- ![Automate 2 Architecture] Component overview ------------------ ### Automate Gateway The Automate Gateway serves as the application layer of Chef Automate’s architecture. All public facing requests go through the gateway and authentication/authorization takes place here. ### Deployment Service This service collects the initial service configuration from the user. It does everything required to set up Chef Automate initially. The deployment service manages configuration patches, as well. ### Configuration Management Service This service serves all configuration management related information to the API and user interface, including Chef Infra Server action data and Chef Infra Client run data. ### Ingest Service This service is the primary ingress event handler for configuration management related events such as Chef Infra Client runs and Chef Infra Server actions. It also manages the data related to these domains, such as cleanup, migration and index initialization. ### Compliance Service This service handles InSpec and scan job-related data, including event ingestion and reporting. ### Notification Service This service is responsible for sending notifications based on configured rules in response to events. ### License Control Service This service provides policy information to the rest of the system derived from the license file. It also provides telemetry configuration. ### AuthZ Service This service provides the API to determine which actions a requestor is allowed to take on in Chef Automate. ### AuthN Service This service provides the API to verify a requestor is allowed to interact with Chef Automate. ### Teams Service This service is an API for defining local teams that are used as part of the authorization model for Chef Automate. ### Users Service This service is used to manage users local to Chef Automate (as opposed to users defined in an external identity provider). ### Session Service This service stands between the browser and Dex. It acts as an [OpenID Connect](http://openid.net/connect/) client to Dex, and uses the [Authorization Code Grant Flow](https://auth0.com/docs/api-auth/tutorials/authorization-code-grant). ### Secrets Service Service securely stores credentials for other services. ### Elasticsearch Sidecar Service This service runs alongside Elasticsearch. It provides common Elasticsearch functionality such as monitoring disk usage and handling index purges. ### Dex [Dex](https://github.com/dexidp/dex) is a federated OpenID Connect (OIDC) provider that allows Automate to integrate with external identity providers via LDAP, SAML or OpenID Connect. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/architectural_overview/Projects ======== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/projects.md) Overview -------- Identity and Access Management projects allow for filtering and segregation of your data among your user base. Permission for the `iam:projects` action is required to interact with projects. Managing Projects ----------------- ### Creating Projects Navigate to *Projects* in the **Settings** tab. Then use the **Create Project** button, which opens a dialog box for entering the project’s *Name*. A project ID automatically generates upon creation. If you would like to change the project ID, use the **Edit ID** button. When a project is created, three policies that control access to that project are also created. Those policies include: *Project Owner*, *Project Editor*, and *Project Viewer*. Adding members to these policies will grant them access to the project. ![] ### Deleting Projects Only projects with zero ingest rules and no pending edits can be deleted. To delete a project, navigate to *Projects* in the **Settings** tab. Then open the menu at the end of the table row and select **Delete Role**. ### Changing Project Details #### Ingest Rules Ingest rules allow ingested events and nodes to be added to projects. *Node* corresponds to ingested client run and compliance nodes, and *Event* corresponds to ingested events on the *Event Feed* page. Ingest rules can be created or changed by navigating to *Projects* in the **Settings** tab and then selecting a project. When you create or update ingest rules, those changes are staged and **not** directly applied. Other users may also stage changes. Each rule describes a list of **conditions**, where each condition describes a single characteristic. ##### Project Ingest Rule Conditions A condition consists of these properties: | Property | Description | | --- | --- | | Event Attribute | Chef Organization or Chef Infra Server | | Node Attribute | Chef Organization, Chef Infra Server, Environment, Chef Role, Chef Tag, Chef Policy Name, or Chef Policy Group | | Operator | equals of member of | | Values | list of one or more values to match on the specified attribute | #### Details To change the name of a project, navigate to *Projects* in the **Settings** tab and then select the **Details** tab. ### Updating Projects The *Project List* page displays the status of project ingest rules (*No rules*, *Edits pending*, or *Applied*). If a project has pending edits from changes to ingest rules, then all projects must be updated for those pending edits to take effect. Updating projects will apply all pending edits and move ingested resources into the correct projects. This background process can take a few minutes for systems with a limited number of nodes, and **several days** for systems with a large number of nodes. All changes will be applied together when you update projects. To update projects navigate to *Projects* in the **Settings** tab and use the **Update Projects** button. #### Stopping the Project Update Early Stopping a project update early will leave your resources in a bad state. Some resources will be in the correct projects and others will not be. To resolve this, make sure to start another project update. To stop the project update background process before it finishes, navigate to *Projects* in the **Settings** tab and select the **Stop Updating Projects** button. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/projects/Feature Flags ============= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/flags.md) Use the beta, lega, or feat flags to turn on or off beta, legacy, or in-development features. Select anywhere on the Chef Automate interface and enter “feat”, “lega”, or “beta” to open the feature flags window. Toggle your desired feature to either the “ON” or “OFF” position. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/flags/Upgrade Chef Automate ===================== [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/upgrade.md) By default, Chef Automate automatically upgrades to the latest version. Release Channels ---------------- The Chef Automate upgrade process makes use of **release channels** to allow greater control over the automatic upgrades applied to your system. Chef Automate pulls the latest release within a specified release channel. The default channel is the `current` channel. To change the release channel that is used for upgrades, modify the `channel` setting in your `config.toml` file: ``` channel = "current" ``` Disable Automatic Upgrades -------------------------- You can disable automatic upgrades by changing the `upgrade_strategy` setting to `none` in your `config.toml`: ``` upgrade_strategy = "none" ``` To manually initiate an upgrade, run ``` chef-automate upgrade run ``` This command upgrades Chef Automate to the latest version available from your release channel. Troubleshoot an Upgrade ----------------------- If you are unable to open Chef Automate, check that the `config.toml` contains the public DNS as the FQDN. ``` # This is a default Chef Automate configuration file. You can run # 'chef-automate deploy' with this config file and it should # successfully create a new Chef Automate instance with default settings. [global.v1] # The external fully qualified domain name. # When the application is deployed you should be able to access 'https://<fqdn>/' # to login. fqdn = "<_Public DNS_name>" ``` Once you correct and save the FQDN, run: ``` sudo chef-automate config patch config.toml ``` Open Chef Automate in your browser. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/upgrade/About Chef Desktop ================== [[edit on GitHub]](https://github.com/chef/desktop-config/tree/main/docs-chef-io/content/desktop/_index.md) Chef Desktop is a deployment pattern that automates desktop and laptop management with code. Use Chef curated Desktop content with YAML support to define profiles for your devices, audit the profiles with Chef curated Desktop CIS profiles before deploying them with Chef Infra, and gain continuous visibility into the configuration status of your fleet in Chef Automate. The desktop services target the following basic functions: * Hard drive encryption * Screensaver with a password * Password policy to set complexity and other elements * Creating a rescue account or additional user accounts * Application management to deploy and manage apps that you care about * Update management to control where, when, and how OS and related patches are installed * Desktop control to limit access to features or services Target Audience --------------- The target audience for Chef Desktop are administrators with limited command-line or tools experience. Our goal is to create a work pattern that leads you to explore the Chef Infra Client from the command line on your own. The instructions for the Chef Desktop pattern should guide you from starting from scratch to managing your fleet in less than a day. Configuration Overview ---------------------- A work triangle is in play in Chef Desktop. The first leg is the Chef Automate with Chef Infra Server that holds and applies configurations to your nodes. The second leg is your administrator’s development environment, which runs Chef Workstation, where you will create and define the policies and settings that the Chef Infra Server metes out. The third leg of the triangle is the list of devices, or “nodes”, to which you apply the polices and settings. The Chef Software Stack ----------------------- Chef Infra Chef Infra is a powerful automation platform that transforms infrastructure into code. Chef Infra automates how infrastructure is configured, deployed, and managed across your network, no matter its size. Chef Workstation Chef Workstation gives you everything you need to get started with Chef. Start scanning and configuring your environments today with Chef InSpec and the `chef-run` tool. Chef Workstation runs on the computer you use everyday, whether it’s Linux, macOS, or Windows. Chef Workstation ships with Chef Infra Client, Chef InSpec, Chef CLI, Test Kitchen, Cookstyle, and other useful Chef tools. With this collection of programs and tools, you can make sure your Chef Infra code does what you intended before you deploy it to environments used by others. Chef InSpec Chef InSpec is a testing framework with a human- and machine-readable language for specifying compliance, security and policy requirements. When compliance is expressed as code, you can integrate it into your deployment pipeline and automatically test for adherence to security policies. * Next: [Chef Desktop Requirements](requirements/index) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/Chef Desktop Requirements ========================= [[edit on GitHub]](https://github.com/chef/desktop-config/tree/main/docs-chef-io/content/desktop/requirements.md) Estimated time: 1 hour System Requirements ------------------- Chef Desktop utilizes the following system architecture: * A Chef Automate Server * A Chef Infra Server * A developer environment running Chef Workstation * One or more “nodes”, which are the Windows or macOS computers that you will manage. ### Chef Automate System requirements: * 16 GB of RAM * 80 GB of disk space (available to `/hab`) * 4 vCPUs Operating system requirements: * a Linux kernel of version 3.2 or greater * systemd as the init system * useradd * cURL or GNU Wget * The shell that starts Chef Automate should have a max open files setting of at least 65535 For more information, see the Chef Automate [system requirements](https://automate.chef.io/docs/system-requirements/). ### Chef Infra Server Chef recommends a single virtual machine instance: * 2 CPU cores and 8GB of RAM, which is equivalent to an Amazon EC2 m3.large instance * 2MB of disk space on the data partition per managed node For more information, see [Install Chef Infra Server](../../install_server/index) and [Chef Infra Server Prerequisites](../../install_server_pre/index). ### Chef Workstation Recommended system requirements: * 4GB of RAM * 8GB of disk space For more information, see [Install Chef Workstation](../../workstation/install_workstation/index). ### Developer Environment #### Visual Studio Code Chef does not prescribe any specific editor. However, we highly recommend using [Visual Studio Code](https://code.visualstudio.com/) (VSCode) and the [Chef Infra extension for VSCode](https://marketplace.visualstudio.com/items?itemName=chef-software.Chef), which features code generators and helpful features, such as running Cookstyle linting each time you save a recipe. In addition to VSCode, for this guide you need the following extensions from the Visual Studio Code Marketplace: * [Chef Infra Extension](https://marketplace.visualstudio.com/items?itemName=chef-software.Chef) * [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) * [PowerShell](https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell) #### Virtualization Test Kitchen, the environment that you will use for testing your Chef Desktop cookbooks before deploying them to your devices, relies on virtualization. Download VirtualBox and Vagrant to use with Test Kitchen: [VirtualBox](https://www.virtualbox.org/wiki/Downloads) The VirtualBox Base Package is licensed under the [GPL V2](https://www.gnu.org/licenses/old-licenses/gpl-2.0.html). (Some parts of VirtualBox, especially libraries, may also be released under other licenses as well.) [VirtualBox Extensions](https://www.virtualbox.org/wiki/Downloads) VirtualBox Extensions is licensed under the [VirtualBox Extension Pack Personal Use and Evaluation License (PUEL)](https://www.virtualbox.org/wiki/VirtualBox_PUEL) [Vagrant](https://www.vagrantup.com/downloads.html) Vagrant is governed by a [EULA](https://www.vagrantup.com/vmware/eula.html) #### Windows Developer Tools [WinSCP](https://winscp.net/eng/download.php) WinSCP lets you transfer files to and from the Linux-based Chef Infra Server to your Windows workstation. You will use this for managing your keys and configurations between machines. [Microsoft Azure](https://azure.microsoft.com) [Microsoft Intune](https://www.microsoft.com/microsoft-365/enterprise-mobility-security/microsoft-intune) Microsoft Intune is a cloud-based that you will used to capture and push configuration to devices. [Windows Autopilot](https://docs.microsoft.com/windows/deployment/windows-autopilot/windows-autopilot) Windows Autopilot simplifies the IT-side of managing Windows devices. [Gorilla](https://github.com/autopkg/autopkg/releases) Gorilla is an [open source project](https://github.com/1dustindavis/gorilla). It is a set of tools for managing applications on Windows computers. [Storage Explorer](https://azure.microsoft.com/features/storage-explorer/) Storage Explorer is a free tool from Microsoft for managing your Azure cloud storage resources. #### macOS Developer Tools [Apple Enterprise Developer Account](https://developer.apple.com/programs/enterprise/) The Apple Developer Enterprise Program is a program that supports large organizations in developing and deploying proprietary, internal-use apps to their employees. [AutoPkg](https://github.com/autopkg/autopkg/releases/tag/v2.1) AutoPkg is an automation framework for macOS software packaging and distribution, oriented towards the tasks one would normally perform manually to prepare third-party software for mass deployment to managed clients. [Munki](https://www.munki.org/munki/) Munki is an [open source project](https://github.com/munki/munki) from Walt Disney Animation Studios. It is a set of tools for managing applications on macOS computers. [MunkiAdmin](https://github.com/hjuutilainen/munkiadmin/releases/) MunkiAdmin is a graphical user interface (GUI) for managing munki repositories [Storage Explorer](https://azure.microsoft.com/features/storage-explorer/) Storage Explorer is a free tool from Microsoft for managing your Azure cloud storage resources. Last: [About Chef Desktop](../index) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/requirements/Setup and Installation ====================== Chef Workstation gives you everything you need to get started with Chef. Start scanning and configuring your environments today with Chef InSpec and chef-run. Chef Workstation runs on the computer you use everyday, whether it’s Linux, macOS, or Windows. Chef Workstation ships with Chef Infra Client, Chef InSpec, Chef CLI, Test Kitchen, Cookstyle, and several other useful Chef tools. With this collection of programs and tools, you can make sure your Chef Infra code does what you intended before you deploy it to environments used by others. Install Chef Workstation ------------------------ [Download Chef Workstation](https://downloads.chef.io/chef-workstation) and run the installer on the developer machine. Once downloaded, run the installer, accept the default options and wait for it to complete. Once the installation is complete, you can verify the installation by opening the command line and run: ``` chef --version ``` This should list out all the Chef tools that we installed in our system. Workstation Environment Setup ----------------------------- Create a `.chef` folder for storing your configuration and keys. Creating the `.chef` directory it in your “home” or “root” folder makes those settings globally available. Navigate to the root directory and create a `.chef` directory: For Powershell: ``` Set-Location -Path C:\Users\<user_name> New-Item -Path . -Name ".chef" -ItemType "directory" ``` For macOS: ``` cd ~ mkdir .chef ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/install/chef-automate CLI ================= [[edit on GitHub]](https://github.com/chef/automate/blob/master/components/docs-chef-io/content/automate/cli_chef_automate.md) Automate CLI Commands --------------------- ### chef-automate A helpful utility to deploy and manage Chef Automate. Docs: https://docs.chef.io/automate/cli_chef_automate/ Patents: https://www.chef.io/patents #### Usage ``` chef-automate COMMAND [flags] ``` Flags -d, --debug Enable debug output (default: false) -h, --help help for chef-automate (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [airgap](#chef-automate-airgap) [applications](#chef-automate-applications) Manage applications observability features [backup](#chef-automate-backup) Chef Automate backup [config](#chef-automate-config) Chef Automate configuration [deploy](#chef-automate-deploy) Deploy Chef Automate [external-cert](#chef-automate-external-cert) Manage Chef Automate's external certificate [gather-logs](#chef-automate-gather-logs) Gather system diagnostics and logs [iam](#chef-automate-iam) Chef Automate iam commands [info](#chef-automate-info) Info about Automate HA [infrastructure](#chef-automate-infrastructure) Chef Automate infrastructure [init-config](#chef-automate-init-config) Initialize default config [init-config-ha](#chef-automate-init-config-ha) Initialize default config for Automate HA [internal-ca](#chef-automate-internal-ca) Manage Chef Automate's internal certificate authority [license](#chef-automate-license) Chef Automate license management [maintenance](#chef-automate-maintenance) Put Chef Automate into or out of maintenance mode [migrate-from-v1](#chef-automate-migrate-from-v1) Migrate from Chef Automate v1 [migrate-from-v1-status](#chef-automate-migrate-from-v1-status) Watch the status of the migration to Chef Automate 2 [preflight-check](#chef-automate-preflight-check) Perform preflight check [provision-infra](#chef-automate-provision-infra) Provision Automate HA infra. [restart-services](#chef-automate-restart-services) restart deployment services [secrets](#chef-automate-secrets) Set secrets to Automate HA [service-versions](#chef-automate-service-versions) Retrieve the versions of the individual Chef Automate services [ssh](#chef-automate-ssh) SSH into Automate HA servers [start](#chef-automate-start) Start Chef Automate [status](#chef-automate-status) Retrieve Chef Automate status [stop](#chef-automate-stop) Stop deployment [system-logs](#chef-automate-system-logs) Tail Chef Automate logs [test](#chef-automate-test) Run Automate HA smoke tests [uninstall](#chef-automate-uninstall) Uninstall Chef Automate [upgrade](#chef-automate-upgrade) upgrade automate to the latest version [validate-ha-infrastructure](#chef-automate-validate-ha-infrastructure) Validate existing infrastructure of Automate HA [validate-ha-infrastructure](#chef-automate-validate-ha-infrastructure) Validate existing infrastructure of Automate HA [version](#chef-automate-version) Show CLI version [workspace](#chef-automate-workspace) Set workspace env for Automate HA. chef-automate airgap #### Usage ``` chef-automate airgap COMMAND [flags] ``` Flags -h, --help help for airgap (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [bundle](#chef-automate-bundle) chef-automate airgap bundle #### Usage ``` chef-automate airgap bundle COMMAND [flags] ``` Flags -h, --help help for bundle (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate airgap](#chef-automate-airgap) [create](#chef-automate-create) [info](#chef-automate-info) chef-automate airgap bundle create #### Usage ``` chef-automate airgap bundle create [/path/to/bundle.aib] [flags] ``` Flags -c, --channel Release channel to pull packages from -h, --help help for create (default: false) -m, --manifest Path to a release manifest.json -r, --retries Number of times to retry failed hab package downloads (default: 2) --retry-delay Number of seconds to wait between retries (exponential backoff is used if not provided) (default: -1) --version Chef Automate version to create an airgap bundle for -w, --workspace Path to workspace storage location where temporary data will be stored -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate airgap bundle](#chef-automate-airgap-bundle) chef-automate airgap bundle info #### Usage ``` chef-automate airgap bundle info /path/to/bundle.aib [flags] ``` Flags -h, --help help for info (default: false) --verbose Output full AIB metadata (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate airgap bundle](#chef-automate-airgap-bundle) chef-automate applications #### Usage ``` chef-automate applications COMMAND [flags] ``` Flags -h, --help help for applications (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [remove-svcs](#chef-automate-remove-svcs) Remove services from the applications database [show-svcs](#chef-automate-show-svcs) Show services in the applications database chef-automate applications remove-svcs Remove services from the applications database. You must fully decommission services by retiring physical hardware, terminating the VM or container, or by using 'hab svc unload', before using the 'remove-svcs' command. Services that are incompletely decommissioned will send a health-check at the appointed time and Automate will re-add them to the services database. #### Usage ``` chef-automate applications remove-svcs [flags] ``` Flags --all Delete all services in the database. This flag must be given if no other filter is given. (default: false) -a, --application Select only services where the application name matches the given pattern -b, --buildstamp Select only services where the buildstamp matches the given pattern -c, --channel Select only services where the subscribed channel matches the given pattern -D, --disconnected Select only services that are disconnected (default: false) -e, --environment Select only services where the application environment matches the given pattern -g, --group Select only services where the group name (suffix) matches the given pattern -h, --help help for remove-svcs (default: false) -o, --origin Select only services where the origin matches the given pattern -n, --service-name Select only services where the name matches the given pattern -s, --site Select only services where the site matches the given pattern -v, --version Select only services where the package version matches the given pattern -y, --yes Delete the services without a confirmation prompt (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate applications](#chef-automate-applications) Manage applications observability features chef-automate applications show-svcs Display a list of the habitat services stored in the applications database. #### Usage ``` chef-automate applications show-svcs [flags] ``` Flags -a, --application Select only services where the application name matches the given pattern -b, --buildstamp Select only services where the buildstamp matches the given pattern -c, --channel Select only services where the subscribed channel matches the given pattern -D, --disconnected Select only services that are disconnected (default: false) -e, --environment Select only services where the application environment matches the given pattern -g, --group Select only services where the group name (suffix) matches the given pattern -h, --help help for show-svcs (default: false) -o, --origin Select only services where the origin matches the given pattern -n, --service-name Select only services where the name matches the given pattern -s, --site Select only services where the site matches the given pattern -v, --version Select only services where the package version matches the given pattern -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate applications](#chef-automate-applications) Manage applications observability features chef-automate backup #### Usage ``` chef-automate backup COMMAND [flags] ``` Flags --gcs-credentials-path The path to the GCP service account json file -h, --help help for backup (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [cancel](#chef-automate-cancel) cancel the running backup operation [create](#chef-automate-create) create a backup of Chef Automate [delete](#chef-automate-delete) delete backups of Chef Automate [fix-repo-permissions](#chef-automate-fix-repo-permissions) Ensure the hab user has the required permissions on the given path [integrity](#chef-automate-integrity) Chef Automate shared object integrity [list](#chef-automate-list) list all Chef Automate backups [restore](#chef-automate-restore) restore a Chef Automate backup [show](#chef-automate-show) show the Chef Automate backup details [status](#chef-automate-status) show the Chef Automate backup runner status chef-automate backup cancel Cancel the currently running backup create, delete, or restore operation #### Usage ``` chef-automate backup cancel [flags] ``` Flags -h, --help help for cancel (default: false) -t, --wait-timeout How long to wait for a operation to complete before raising an error (default: 60) -d, --debug Enable debug output (default: false) --gcs-credentials-path The path to the GCP service account json file --no-check-version Disable version check (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --result-json Write command result as JSON to PATH --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role See Also [chef-automate backup](#chef-automate-backup) Chef Automate backup chef-automate backup create Create a backup of Chef Automate #### Usage ``` chef-automate backup create [flags] ``` Flags -h, --help help for create (default: false) -t, --wait-timeout How long to wait for a operation to complete before raising an error (default: 7200) -d, --debug Enable debug output (default: false) --gcs-credentials-path The path to the GCP service account json file --no-check-version Disable version check (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --result-json Write command result as JSON to PATH --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role See Also [chef-automate backup](#chef-automate-backup) Chef Automate backup chef-automate backup delete Delete one or many backups of Chef Automate that match the space separated strings of backup IDs #### Usage ``` chef-automate backup delete ID [ID2 IDN...] [flags] ``` Flags -h, --help help for delete (default: false) -t, --wait-timeout How long to wait for a operation to complete before raising an error (default: 120) --yes Agree to all prompts (default: false) -d, --debug Enable debug output (default: false) --gcs-credentials-path The path to the GCP service account json file --no-check-version Disable version check (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --result-json Write command result as JSON to PATH --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role See Also [chef-automate backup](#chef-automate-backup) Chef Automate backup chef-automate backup fix-repo-permissions Ensure the hab user has the required permissions on the given path #### Usage ``` chef-automate backup fix-repo-permissions PATH [flags] ``` Flags -h, --help help for fix-repo-permissions (default: false) -d, --debug Enable debug output (default: false) --gcs-credentials-path The path to the GCP service account json file --no-check-version Disable version check (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --result-json Write command result as JSON to PATH --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role See Also [chef-automate backup](#chef-automate-backup) Chef Automate backup chef-automate backup integrity #### Usage ``` chef-automate backup integrity COMMAND [flags] ``` Flags -h, --help help for integrity (default: false) -t, --wait-timeout How long to wait for a operation to complete before raising an error (default: 60) -d, --debug Enable debug output (default: false) --gcs-credentials-path The path to the GCP service account json file --no-check-version Disable version check (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --result-json Write command result as JSON to PATH --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role See Also [chef-automate backup](#chef-automate-backup) Chef Automate backup [show](#chef-automate-show) show the shared object integrity metadata [validate](#chef-automate-validate) validate the shared object integrity chef-automate backup integrity show Show the shared object integrity metadata #### Usage ``` chef-automate backup integrity show [flags] ``` Flags -h, --help help for show (default: false) -d, --debug Enable debug output (default: false) --gcs-credentials-path The path to the GCP service account json file --no-check-version Disable version check (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --result-json Write command result as JSON to PATH --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role -t, --wait-timeout How long to wait for a operation to complete before raising an error (default: 60) See Also [chef-automate backup integrity](#chef-automate-backup-integrity) Chef Automate shared object integrity chef-automate backup integrity validate Validate the shared object integrity. If one or more snapshot IDs is not given all snapshots will be validated #### Usage ``` chef-automate backup integrity validate [ID IDN] [flags] ``` Flags -h, --help help for validate (default: false) -d, --debug Enable debug output (default: false) --gcs-credentials-path The path to the GCP service account json file --no-check-version Disable version check (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --result-json Write command result as JSON to PATH --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role -t, --wait-timeout How long to wait for a operation to complete before raising an error (default: 60) See Also [chef-automate backup integrity](#chef-automate-backup-integrity) Chef Automate shared object integrity chef-automate backup list List all Chef Automate backups #### Usage ``` chef-automate backup list [flags] ``` Flags -h, --help help for list (default: false) -t, --wait-timeout How long to wait for a operation to complete before raising an error (default: 60) -d, --debug Enable debug output (default: false) --gcs-credentials-path The path to the GCP service account json file --no-check-version Disable version check (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --result-json Write command result as JSON to PATH --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role See Also [chef-automate backup](#chef-automate-backup) Chef Automate backup chef-automate backup restore Restore a Chef Automate backup. If no ID or path is given the latest found backup will be restored. #### Usage ``` chef-automate backup restore [ID_OR_PATH] [flags] ``` Flags --airgap-bundle The artifact to use for an air-gapped installation -b, --backup-dir Directory used for backups (default: /var/opt/chef-automate/backups) -h, --help help for restore (default: false) --patch-config Path to patch config if required --sha256 The SHA256 checksum of the backup --skip-preflight Skip preflight checks when restoring a backup (default: false) -u, --upgrade Upgrade to the latest package versions when restoring backups (default: false) -t, --wait-timeout How long to wait for a operation to complete before raising an error (default: 7200) --yes Agree to all prompts (default: false) -d, --debug Enable debug output (default: false) --gcs-credentials-path The path to the GCP service account json file --no-check-version Disable version check (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --result-json Write command result as JSON to PATH --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role See Also [chef-automate backup](#chef-automate-backup) Chef Automate backup chef-automate backup show Show the details of a Chef Automate backup #### Usage ``` chef-automate backup show ID [flags] ``` Flags -h, --help help for show (default: false) -t, --wait-timeout How long to wait for a operation to complete before raising an error (default: 60) -d, --debug Enable debug output (default: false) --gcs-credentials-path The path to the GCP service account json file --no-check-version Disable version check (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --result-json Write command result as JSON to PATH --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role See Also [chef-automate backup](#chef-automate-backup) Chef Automate backup chef-automate backup status Show the Chef Automate backup runner status #### Usage ``` chef-automate backup status [flags] ``` Flags -h, --help help for status (default: false) -t, --wait-timeout How long to wait for a operation to complete before raising an error (default: 60) -d, --debug Enable debug output (default: false) --gcs-credentials-path The path to the GCP service account json file --no-check-version Disable version check (default: false) --no-progress Don't follow operation progress (default: false) -r, --request-timeout API request timeout for deployment-service in seconds (default: 20) --result-json Write command result as JSON to PATH --s3-access-key The S3 access key ID --s3-endpoint The S3 region endpoint URL --s3-secret-key The S3 secret access key --s3-session-token The S3 session token when assuming an IAM role See Also [chef-automate backup](#chef-automate-backup) Chef Automate backup chef-automate config #### Usage ``` chef-automate config COMMAND [flags] ``` Flags -h, --help help for config (default: false) -t, --timeout Request timeout in seconds (default: 10) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [patch](#chef-automate-patch) patch the Chef Automate configuration [set](#chef-automate-set) set the Chef Automate configuration [show](#chef-automate-show) show the Chef Automate configuration chef-automate config patch Apply a partial Chef Automate configuration to the deployment. It will take the partial configuration, merge it with the existing configuration, and apply and required changes. #### Usage ``` chef-automate config patch path/to/config.toml [flags] ``` Flags -h, --help help for patch (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH -t, --timeout Request timeout in seconds (default: 10) See Also [chef-automate config](#chef-automate-config) Chef Automate configuration chef-automate config set Set the Chef Automate configuration for the deployment. It will replace the Chef Automate configuration with the given configuration and apply any required changes. #### Usage ``` chef-automate config set path/to/config.toml [flags] ``` Flags -h, --help help for set (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH -t, --timeout Request timeout in seconds (default: 10) See Also [chef-automate config](#chef-automate-config) Chef Automate configuration chef-automate config show Show the Chef Automate configuration. When given a filepath, the output will be written to the file instead of printed to STDOUT #### Usage ``` chef-automate config show [/path/to/write/config.toml] [flags] ``` Flags -h, --help help for show (default: false) -o, --overwrite Overwrite existing config.toml (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH -t, --timeout Request timeout in seconds (default: 10) See Also [chef-automate config](#chef-automate-config) Chef Automate configuration chef-automate deploy Deploy a new Chef Automate instance using the supplied configuration. - <CONFIG_FILE> must be a valid path to a TOML formatted configuration file #### Usage ``` chef-automate deploy [/path/to/config.toml] [flags] ``` Flags --accept-terms-and-mlsa Agree to the Chef Software Terms of Service and the Master License and Services Agreement (default: false) --airgap-bundle Path to an airgap install bundle --certificate The path to a certificate that should be used for external TLS connections (web and API). --channel Release channel to deploy all services from --fqdn The fully-qualified domain name that Chef Automate can be accessed at. (default: hostname of this machine) -h, --help help for deploy (default: false) --private-key The path to a private key corresponding to the TLS certificate. --product Product to deploy (default: []) --skip-preflight Deploy regardless of pre-flight conditions (default: false) --upgrade-strategy Upgrade strategy to use for this deployment. (default: at-once) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate external-cert Manage Chef Automate's external certificate authority. Used for establishing TLS/SSL communication with automate. #### Usage ``` chef-automate external-cert COMMAND [flags] ``` Flags -f, --file File path to save automate TLS certifcate to. -h, --help help for external-cert (default: false) -n, --hostname Hostname for the automate TLS certificate -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [show](#chef-automate-show) Show the external TLS/SSL certificates in Automate. Optionally, save the certificates to a file in the specified path. chef-automate external-cert show #### Usage ``` chef-automate external-cert show [flags] ``` Flags -h, --help help for show (default: false) -d, --debug Enable debug output (default: false) -f, --file File path to save automate TLS certifcate to. -n, --hostname Hostname for the automate TLS certificate --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate external-cert](#chef-automate-external-cert) Manage Chef Automate's external certificate chef-automate gather-logs Collect system diagnostics and logs from Chef Automate and other services #### Usage ``` chef-automate gather-logs [/path/to/log/bundle.tar.gz] [flags] ``` Flags -h, --help help for gather-logs (default: false) -l, --local-fallback run gather-logs in local fallback mode (default: false) --log-lines Number of system log lines (journald logs) to collect (0 for all logs) (default: 500000) -o, --overwrite Overwrite existing log archive (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate iam #### Usage ``` chef-automate iam COMMAND [flags] ``` Flags -h, --help help for iam (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [admin-access](#chef-automate-admin-access) Manage and restore default admin access [token](#chef-automate-token) Manage tokens [version](#chef-automate-version) Retrieve IAM version in use chef-automate iam admin-access #### Usage ``` chef-automate iam admin-access COMMAND [flags] ``` Flags -h, --help help for admin-access (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate iam](#chef-automate-iam) Chef Automate iam commands [restore](#chef-automate-restore) Restore the factory default admin user, team, and access chef-automate iam admin-access restore Recreate the admin user, admin team, and related admin policy as needed to restore to factory default and update the admin user's password #### Usage ``` chef-automate iam admin-access restore PASSWORD [flags] ``` Flags --dry-run Show what would be updated by this command without performing any changes (default: false) -h, --help help for restore (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate iam admin-access](#chef-automate-iam-admin-access) Manage and restore default admin access chef-automate iam token #### Usage ``` chef-automate iam token COMMAND [flags] ``` Flags -h, --help help for token (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate iam](#chef-automate-iam) Chef Automate iam commands [create](#chef-automate-create) Generate a token chef-automate iam token create #### Usage ``` chef-automate iam token create NAME [flags] ``` Flags --admin Generate a token and add it to the chef-managed admin policy (default: false) -h, --help help for create (default: false) --id Specify a custom ID (if omitted, an ID will be generated based on NAME) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate iam token](#chef-automate-iam-token) Manage tokens chef-automate iam version #### Usage ``` chef-automate iam version [flags] ``` Flags -h, --help help for version (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate iam](#chef-automate-iam) Chef Automate iam commands chef-automate info Info for Automate HA cluster #### Usage ``` chef-automate info [flags] ``` Flags -h, --help help for info (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate infrastructure Commands for automation infrastructure management, for data related to chef-client runs and chef-server actions. #### Usage ``` chef-automate infrastructure COMMAND [flags] ``` Flags -h, --help help for infrastructure (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [node-delete](#chef-automate-node-delete) Delete node by node uuid chef-automate infrastructure node-delete #### Usage ``` chef-automate infrastructure node-delete [uuid] [flags] ``` Flags -h, --help help for node-delete (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate infrastructure](#chef-automate-infrastructure) Chef Automate infrastructure chef-automate init-config Initialize default configuration and save it to a file. #### Usage ``` chef-automate init-config [flags] ``` Flags --certificate The path to a certificate that should be used for external TLS connections (web and API). --channel Release channel to deploy all services from (default: current) --es-mem The amount of system memory to allocate to Elasticsearch's heap. (default: 25% of system memory) --file File path to write the config (default: config.toml) --fqdn The fully-qualified domain name that Chef Automate can be accessed at. (default: hostname of this machine) -h, --help help for init-config (default: false) --private-key The path to a private key corresponding to the TLS certificate. --upgrade-strategy Upgrade strategy to use for this deployment. (default: at-once) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate init-config-ha Initialized default configuration for HA and save it to a file. #### Usage ``` chef-automate init-config-ha [flags] ``` Flags --file File path to write the config (default: config.toml) -h, --help help for init-config-ha (default: false) --path a2ha hab workspace dir path (default: /hab/a2_deploy_workspace/) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate internal-ca Manage Chef Automate's internal certificate authority. Used for inter-service encryption and authentication. #### Usage ``` chef-automate internal-ca COMMAND [flags] ``` Flags -h, --help help for internal-ca (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [info](#chef-automate-info) Print information the root certificate for the internal certificate authority [regenerate](#chef-automate-regenerate) Commands to regenerate certificates issued by the internal certificate authority chef-automate internal-ca info #### Usage ``` chef-automate internal-ca info [flags] ``` Flags -h, --help help for info (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate internal-ca](#chef-automate-internal-ca) Manage Chef Automate's internal certificate authority chef-automate internal-ca regenerate #### Usage ``` chef-automate internal-ca regenerate [flags] ``` Flags -h, --help help for regenerate (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate internal-ca](#chef-automate-internal-ca) Manage Chef Automate's internal certificate authority [root](#chef-automate-root) Regenerate the root certificate for the internal certificate authority chef-automate internal-ca regenerate root #### Usage ``` chef-automate internal-ca regenerate root [flags] ``` Flags -h, --help help for root (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate internal-ca regenerate](#chef-automate-internal-ca-regenerate) Commands to regenerate certificates issued by the internal certificate authority chef-automate license #### Usage ``` chef-automate license COMMAND [flags] ``` Flags -h, --help help for license (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [apply](#chef-automate-apply) Apply Chef Automate license [complianceResourceRunCount](#chef-automate-complianceresourceruncount) Generates the unique count of reported Compliance scans on hourly basis between the time duration [complianceResourceRunReport](#chef-automate-complianceresourcerunreport) Generates daily Infra Client Run reports for a span of time duration [nodeRunReport](#chef-automate-noderunreport) Generates daily Infra Client Run reports for a span of time duration [status](#chef-automate-status) Retrieve Chef Automate license status [uniqNodeRunReport](#chef-automate-uniqnoderunreport) Generates the unique count of reported Infra Client nodes on hourly basis between the time duration chef-automate license apply Apply Chef Automate license token. - <LICENSE> must be valid encoded license string #### Usage ``` chef-automate license apply LICENSE [flags] ``` Flags -f, --force Force set license (default: false) -h, --help help for apply (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate license](#chef-automate-license) Chef Automate license management chef-automate license complianceResourceRunCount #### Usage ``` chef-automate license complianceResourceRunCount [flags] ``` Flags -e, --end_time end time of the report in yyyy-mm-dd format -n, --es_hostname hostname of the ES host (default: localhost) -p, --es_port port of the ES host (default: 10141) -h, --help help for complianceResourceRunCount (default: false) -s, --start_time start time of the report in yyyy-mm-dd format -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate license](#chef-automate-license) Chef Automate license management chef-automate license complianceResourceRunReport #### Usage ``` chef-automate license complianceResourceRunReport [flags] ``` Flags -e, --end_time end time of the report in yyyy-mm-dd format -n, --es_hostname hostname of the ES host (default: localhost) -p, --es_port port of the ES host (default: 10141) -h, --help help for complianceResourceRunReport (default: false) -s, --start_time start time of the report in yyyy-mm-dd format -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate license](#chef-automate-license) Chef Automate license management chef-automate license nodeRunReport #### Usage ``` chef-automate license nodeRunReport [flags] ``` Flags -e, --end_time end time of the report in yyyy-mm-dd format -n, --es_hostname hostname of the ES host (default: localhost) -p, --es_port port of the ES host (default: 10141) -h, --help help for nodeRunReport (default: false) -s, --start_time start time of the report in yyyy-mm-dd format -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate license](#chef-automate-license) Chef Automate license management chef-automate license status #### Usage ``` chef-automate license status [flags] ``` Flags -h, --help help for status (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate license](#chef-automate-license) Chef Automate license management chef-automate license uniqNodeRunReport #### Usage ``` chef-automate license uniqNodeRunReport [flags] ``` Flags -e, --end_time end time of the report in yyyy-mm-dd format -n, --es_hostname hostname of the ES host (default: localhost) -p, --es_port port of the ES host (default: 10141) -h, --help help for uniqNodeRunReport (default: false) -s, --start_time start time of the report in yyyy-mm-dd format -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate license](#chef-automate-license) Chef Automate license management chef-automate maintenance Chef Automate maintenance mode keeps all services running but rejects new connections at the load balancer so that maintenance operations can be performed. #### Usage ``` chef-automate maintenance [on|off] [flags] ``` Flags -h, --help help for maintenance (default: false) -t, --timeout Request timeout in seconds (default: 10) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate migrate-from-v1 Migrate an existing Chef Automate v1 deployment to Chef Automate v2. - <CONFIG_FILE> must be a valid path to a TOML formatted configuration file #### Usage ``` chef-automate migrate-from-v1 [/path/to/automate-deploy.toml] [flags] ``` Flags --airgap-bundle Path to an airgap install bundle --channel Optional channel to use when installing packages from the depot --chef-server-running Path to chef-server-running.json (default: /etc/opscode/chef-server-running.json) -c, --config Path to an automate-deploy.toml -r, --delivery-running Path to delivery-running.json (default: /etc/delivery/delivery-running.json) -s, --delivery-secrets Path to delivery-secrets.json (default: /etc/delivery/delivery-secrets.json) --enable-chef-server Enable integrated Chef Server migration and deployment; only valid for all-in-one topology (default: false) --file-move-timeout Optional timeout for moving elasticsearch, compliance, and notifications files during Chef Automate v1 migration (0 to disable timeout) (default: 0) -h, --help help for migrate-from-v1 (default: false) --postgres-dump-wait-seconds Optional timeout for Chef Automate v1 PostgreSQL dump (0 to disable timeout) (default: 0) --postgres-restore-wait-seconds Optional timeout for Chef Automate v1 PostgreSQL restore (0 to disable timeout) (default: 0) --skip-backup Optionally skip backup of your Chef Automate v1 installation (default = false) (default: false) --skip-backup-check Optionally do not check if your Chef Automate v1 installation has backups configured (default = false) (default: false) --skip-disaster-recovery-check Optionally do not check if your Chef Automate v1 installation has disaster recovery configured (default = false) (default: false) --skip-external-es-check Optionally do not check if your Chef Automate v1 installation has external Elasticsearch configured (default = false) (default: false) --skip-fips-check Optionally do not check if your Chef Automate v1 installation has FIPS configured (default = false) (default: false) --skip-preflight Deploy regardless of pre-flight conditions (default: false) --skip-saml-check Optionally do not check if your Chef Automate v1 installation has SAML configured (default = false) (default: false) --skip-workflow-check Optionally do not check if your Chef Automate v1 installation has workflow configured (default = false) (default: false) --upgrade-strategy Optional upgrade strategy to use when configuring the deployment service -y, --yes Do not prompt for confirmation; accept defaults and continue (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [gen-config](#chef-automate-gen-config) Generate a config file chef-automate migrate-from-v1-status #### Usage ``` chef-automate migrate-from-v1-status [flags] ``` Flags -h, --help help for migrate-from-v1-status (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate migrate-from-v1 gen-config Generate a Chef Automate v2 configuration file from Chef Automate v1 #### Usage ``` chef-automate migrate-from-v1 gen-config [flags] ``` Flags -h, --help help for gen-config (default: false) -o, --out Output file (default: ./automate-migrate.toml) --airgap-bundle Path to an airgap install bundle --channel Optional channel to use when installing packages from the depot --chef-server-running Path to chef-server-running.json (default: /etc/opscode/chef-server-running.json) -c, --config Path to an automate-deploy.toml -d, --debug Enable debug output (default: false) -r, --delivery-running Path to delivery-running.json (default: /etc/delivery/delivery-running.json) -s, --delivery-secrets Path to delivery-secrets.json (default: /etc/delivery/delivery-secrets.json) --enable-chef-server Enable integrated Chef Server migration and deployment; only valid for all-in-one topology (default: false) --file-move-timeout Optional timeout for moving elasticsearch, compliance, and notifications files during Chef Automate v1 migration (0 to disable timeout) (default: 0) --no-check-version Disable version check (default: false) --postgres-dump-wait-seconds Optional timeout for Chef Automate v1 PostgreSQL dump (0 to disable timeout) (default: 0) --postgres-restore-wait-seconds Optional timeout for Chef Automate v1 PostgreSQL restore (0 to disable timeout) (default: 0) --result-json Write command result as JSON to PATH --skip-backup Optionally skip backup of your Chef Automate v1 installation (default = false) (default: false) --skip-backup-check Optionally do not check if your Chef Automate v1 installation has backups configured (default = false) (default: false) --skip-disaster-recovery-check Optionally do not check if your Chef Automate v1 installation has disaster recovery configured (default = false) (default: false) --skip-external-es-check Optionally do not check if your Chef Automate v1 installation has external Elasticsearch configured (default = false) (default: false) --skip-fips-check Optionally do not check if your Chef Automate v1 installation has FIPS configured (default = false) (default: false) --skip-preflight Deploy regardless of pre-flight conditions (default: false) --skip-saml-check Optionally do not check if your Chef Automate v1 installation has SAML configured (default = false) (default: false) --skip-workflow-check Optionally do not check if your Chef Automate v1 installation has workflow configured (default = false) (default: false) --upgrade-strategy Optional upgrade strategy to use when configuring the deployment service -y, --yes Do not prompt for confirmation; accept defaults and continue (default: false) See Also [chef-automate migrate-from-v1](#chef-automate-migrate-from-v1) Migrate from Chef Automate v1 chef-automate preflight-check Perform preflight check to verify host meets installation criteria. #### Usage ``` chef-automate preflight-check [flags] ``` Flags --airgap Pass this flag when the environment is airgapped (default: false) --config Optional config file to use -h, --help help for preflight-check (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [migrate-from-v1](#chef-automate-migrate-from-v1) Run preflight checks specific to migrating from Chef Automate v1 chef-automate preflight-check migrate-from-v1 #### Usage ``` chef-automate preflight-check migrate-from-v1 [flags] ``` Flags -r, --delivery-running Path to delivery-running.json (default: /etc/delivery/delivery-running.json) -s, --delivery-secrets Path to delivery-secrets.json (default: /etc/delivery/delivery-secrets.json) -h, --help help for migrate-from-v1 (default: false) --skip-backup-check Optionally do not check if your Chef Automate v1 installation has backups configured (default = false) (default: false) --skip-disaster-recovery-check Optionally do not check if your Chef Automate v1 installation has disaster recovery configured (default = false) (default: false) --skip-external-es-check Optionally do not check if your Chef Automate v1 installation has external Elasticsearch configured (default = false) (default: false) --skip-fips-check Optionally do not check if your Chef Automate v1 installation has FIPS configured (default = false) (default: false) --skip-saml-check Optionally do not check if your Chef Automate v1 installation has SAML configured (default = false) (default: false) --skip-workflow-check Optionally do not check if your Chef Automate v1 installation has workflow configured (default = false) (default: false) --airgap Pass this flag when the environment is airgapped (default: false) --config Optional config file to use -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate preflight-check](#chef-automate-preflight-check) Perform preflight check chef-automate provision-infra Provision infra for Automate HA deployment. #### Usage ``` chef-automate provision-infra [flags] ``` Flags --airgap-bundle Path to an airgap install bundle --channel Release channel to deploy all services from -h, --help help for provision-infra (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate restart-services Restart services for a deployment #### Usage ``` chef-automate restart-services [flags] ``` Flags -h, --help help for restart-services (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate secrets Set secrets for Automate sudo password and admin password in HA mode. #### Usage ``` chef-automate secrets [flags] ``` Flags -h, --help help for secrets (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate service-versions Retrieve the versions of the individual Chef Automate services #### Usage ``` chef-automate service-versions [flags] ``` Flags -h, --help help for service-versions (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate ssh SSH into Automate HA servers #### Usage ``` chef-automate ssh [flags] ``` Flags -h, --help help for ssh (default: false) --hostname Automate ha server name to ssh -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate start #### Usage ``` chef-automate start [flags] ``` Flags -h, --help help for start (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate status Retrieve Chef Automate status. Includes status of Automate services. #### Usage ``` chef-automate status [flags] ``` Flags -h, --help help for status (default: false) -w, --wait-for-healthy Wait until the status response is healthy or the timeout is reached (default: false) -r, --wait-refresh-interval How many seconds to wait between polling for status updates (default: 2) -t, --wait-timeout How many seconds to wait for the status to be healthy before returning an error (default: 600) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate stop Stop a running deployment of Automate. #### Usage ``` chef-automate stop [flags] ``` Flags -h, --help help for stop (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate system-logs Start streaming logs from the Chef Automate server. Ctrl + c to stop. #### Usage ``` chef-automate system-logs [flags] ``` Flags -h, --help help for system-logs (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate test Run smoke test for Automate HA services. #### Usage ``` chef-automate test [flags] ``` Flags --full Automate ha cluster test full (default: false) -h, --help help for test (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate uninstall Uninstall Chef Automate, deleting all data and configuration #### Usage ``` chef-automate uninstall [flags] ``` Flags -h, --help help for uninstall (default: false) --preserve-package-cache Preserve Habitat package cache (useful for faster reinstall) (default: false) --yes Uninstall Chef Automate and destroy data without confirmation prompt (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate upgrade #### Usage ``` chef-automate upgrade COMMAND [flags] ``` Flags -h, --help help for upgrade (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI [run](#chef-automate-run) Run an upgrade of Chef Automate [status](#chef-automate-status) Get upgrade status of Chef Automate chef-automate upgrade run Run an upgrade of Chef Automate #### Usage ``` chef-automate upgrade run [flags] ``` Flags --airgap-bundle Path to an airgap install bundle -h, --help help for run (default: false) --skip-deploy will only upgrade and not deploy the bundle (default: false) --upgrade-airgap-bundles Update Chef Automate both frontend and backend version to install (default: false) --upgrade-backends Update Chef Automate backends version to install (default: false) --upgrade-frontends upgrade Chef Automate HA frontends version to install (default: false) --version The exact Chef Automate version to install -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate upgrade](#chef-automate-upgrade) upgrade automate to the latest version chef-automate upgrade status Get upgrade status of Chef Automate #### Usage ``` chef-automate upgrade status [flags] ``` Flags -h, --help help for status (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate upgrade](#chef-automate-upgrade) upgrade automate to the latest version chef-automate validate-ha-infrastructure Validate existing infrastructure of automate HA #### Usage ``` chef-automate validate-ha-infrastructure [flags] ``` Flags --airgap-bundle Path to airgap bundle --habitat-bundle Path to haitat tar bundle -h, --help help for validate-ha-infrastructure (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate version Show the CLI version. #### Usage ``` chef-automate version [flags] ``` Flags --connection-timeout Most time to wait to connect to service (default: 0s) --endpoint The endpoint the service is listening on -h, --help help for version (default: false) -v, --verbose Show additional version information (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI chef-automate workspace Set up Automate HA cluster workspace. #### Usage ``` chef-automate workspace [flags] ``` Flags -h, --help help for workspace (default: false) -d, --debug Enable debug output (default: false) --no-check-version Disable version check (default: false) --result-json Write command result as JSON to PATH See Also [chef-automate](#chef-automate) Chef Automate CLI Error Codes If `chef-automate` encounters an error during execution, it exits with a non-zero error code. Here’s what our error codes mean: | Exit Code | Name | Description | | --- | --- | --- | | 68 | HabUserAccessError | Unable to access file or directory with the hab user | | 69 | SnapshotChecksumMismatchError | A file in the snapshot did not have the expected checksum | | 70 | DatabaseError | An issue occurred with the database | | 71 | CommandExecutionError | An issue occurred when running an executable command | | 72 | TraceError | An issue occurred when attempting to trace the request | | 73 | ProfileError | An issue occurred when attempting to profile the request | | 74 | HabCommandError | An issue occurred when running a hab command | | 75 | HabAPIError | An issue occurred when attempting to query the Habitat API | | 76 | GatherLogsError | Unable to complete log gathering | | 77 | PackageInstallError | Unable to install the habitat package | | 78 | TimedOutError | Timed out waiting for the operation to complete | | 79 | BackupRestoreError | Unable to restore backup | | 80 | ServiceUnloadError | Unable to unload the habitat service | | 81 | ServiceStartError | Unable to start the habitat service | | 82 | AirgapUnpackInstallBundleError | An issue occurred when attempting to unpack the airgap install bundle | | 83 | AirgapCreateInstallBundleError | An issue occurred when attempting to create the airgap install bundle | | 84 | DownloadError | An issue occurred when attempting to perform a file download | | 85 | UninstallError | An issue occurred when attempting to uninstall Chef Automate | | 86 | BackupError | An issue occurred when creating or restoring a backup | | 87 | UpgradeError | An issue occurred during the upgrade | | 88 | MarshalError | Unable to convert or deconvert a textual representation of an internal object | | 89 | LicenseError | The license is invalid, expired or incomplete | | 90 | FileAccessError | Unable to access the file or directory | | 91 | DiagnosticsError | One or more diagnostics checks failed | | 92 | MustBeRootError | The command must be run as the root user | | 93 | ConfigError | The configuration is invalid | | 94 | DeployError | Unable to install, configure and start the service | | 95 | PreflightError | One or more preflight checks failed | | 96 | InvalidCommandArgsError | The arguments provided are invalid | | 97 | UnhealthyStatusError | System status is unhealthy | | 98 | DeploymentServiceCallError | A request to the deployment-service failed | | 99 | DeploymentServiceUnreachableError | Unable to make a request to the deployment-service | | 100 | APIError | An API error occurred during execution | | 112 | UpdateExecError | An issue occurred when trying to run an auto-updated CLI executable | | 113 | UnknownError | An unknown issue occurred during execution | | 114 | APIUnreachableError | Could not connect to Automate API | | 115 | UnknownError | Failed to upgrade IAM to v2 | | 116 | UnknownError | Failed to reset IAM state to v1 | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/automate/cli_chef_automate/Set up Automate Server ====================== We recommend starting with a clean installation of Chef Automate, Chef Infra Server, and Chef Desktop. Combining existing Chef Automate nodes with new Chef Desktop leads to significant confusion, because the servers do not distinguish between the types of nodes that they mange. For the purposes of this demonstration, we recommend installing Chef Automate and Chef Infra Server together on the same host. Talk to your account representative to decide if you should follow a different deployment pattern in production. Note Proceed with the instructions provided in the following sections after you have logged in to the server where you want to install and set up Automate. Prepare the System ------------------ In your clean Linux environment, update and install the system packages: ``` apt-get -qq update apt-get install -y --no-install-recommends apt-get clean ``` The Chef Automate installation requires the following settings: ``` sysctl -w vm.max_map_count=262144 sysctl -w vm.dirty_expire_centisecs=20000 ``` Download Automate and install with Desktop dashboard ---------------------------------------------------- Download the Chef Automate CLI: ``` curl https://packages.chef.io/files/current/latest/chef-automate-cli/chef-automate_linux_amd64.zip | gunzip - > chef-automate chmod +x chef-automate ``` Deploy the packages with the following command: ``` sudo chef-automate deploy --product automate --product infra-server --product desktop --accept-terms-and-mlsa ``` *You will need the host names and user information later in this guide. They are located them in the `automate-credentials.toml`.* Configure the Infra server -------------------------- You need run these commands as an administrator or use `sudo` before each command. ***Note**: You will need information from both of these commands. Copy them from your command line to a file. Store the file securely.* ``` chef-server-ctl user-create USER_NAME FIRST_NAME LAST_NAME EMAIL 'PASSWORD' --filename USER_NAME.pem ``` Create an organization: ``` chef-server-ctl org-create SHORT_NAME 'FULL_ORGANIZATION_NAME' --association_user USER_NAME --filename ORGANIZATION-validator.pem ``` Transfer the generated user and validator keys to your workstation and put them in the `.chef` directory. If you already logged out of the server, you can read the next section on key management to find instructions on how to transfer them to your local workstation. Key Management -------------- “Key management” is a software term that means “Safely and securely getting the right credentials from remote and local computers into the right directories–usually, but not always, on your local computer–in order to use software to run commands between computers”. We recommend using a secure copy protocol (SCP) to move the public key and configuration file from the Chef Infra Server to the `.chef` directory on your workstation. * macOS workstations should have the `scp` command, * Windows workstations will need to install [WinSCP](https://winscp.net/eng/index.php) or another similar tool. + The public key is `ORGANIZATION-validator.pem` + The configuration file is `config.toml` *This step is the reason that you copied output of the above commands to files.* To manage your keys and credentials, you need to know: * The host name (also called a FQDN) or ip of the Chef Infra Server * The user name on the Chef Infra Server * The password on the Chef Infra Server ### Transfer Keys on Windows Workstations 1. Install WinSCP 2. Open the program using the icon on your workstation desktop. 3. Select **SCP** as the file protocol 4. Set port **22** 5. Fill in the host name, the user name, and the password that you created on your Chef Infra Server. ### Transfer Keys on macOS Workstations macOS systems come with `scp` installed. Download the key and configuration files: ``` scp user_name@chef-<EMAIL>.<EMAIL>:/remote/ORGANIZATION-validator.pem ~/.chef scp user_name@chef-automate.test:/remote/config.toml ~/.chef ``` ### More Information on SCP [SCP for macOS](https://linuxize.com/post/how-to-use-scp-command-to-securely-transfer-files/) SCP is used to move files between your workstation to a remote computer. It uses ssh for data transfer. `scp` asks for passwords or passphrases if needed for authentication. [WinSCP for Windows](https://winscp.net/index.php) WinSCP is an open source application for Windows used to move files between your workstation and a remote computer. WinSCP offers scripting and basic file manager functionality. The download page has many junk buttons, make sure you select **Download WinSPC**. [SCP on Azure](https://docs.microsoft.com/azure/virtual-machines/linux/copy-files-to-linux-vm-using-scp) SCP on Azure is used to move files from your workstation up to an Azure Linux VM, or from an Azure Linux VM down to your workstation. * Next: [Chef Desktop Cookbook Development Environment](../cookbook_repository/index) * Last: [Chef Desktop Requirements](../requirements/index) © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/automate_server/Set up Cookbook for Windows 10 and macOS Platforms ================================================== Estimated time: 1 hour (with your own virtual machines) This step introduces you to fundamentals of cookbook development and walks you through the process of creating, editing, and testing a simple cookbook. These are the same basic steps that you will expand on in developing your Chef Desktop cookbook. 1. Learn about testing with Test Kitchen 2. Set up your Chef development environment 3. Make a demo cookbook 4. Test your cookbook locally 5. Test your cookbook with Test Kitchen, once you have your virtual machine images Developing Cookbooks -------------------- Testing is central to good software development. Testing your Chef Desktop cookbook provides you the opportunity to detect and correct problems before putting changes into production. Testing saves time and money, but it adds value by helping your organization achieve and maintain operational velocity. ### Licenses It is important to understand your operating license and service agreements. The best place to begin is find and understand your SLA: * [Windows Licenses](https://www.microsoft.com/licensing/default) * [Apple macOS SLA](https://www.apple.com/legal/sla/) ### Setup Your Development Environment In this step, you will prepare your workstation for developing, testing, and deploying the Chef Desktop cookbook. 1. Create your local repo You will need a local repository on your workstation for storing your cookbooks and related chef work, and for sharing it with GitHub or another version control system. From the command line in your root folder (c:\ or ~/), run: ``` chef generate repo my_repo ``` ### Make Your First Cookbook This is a practice cookbook to understand how to test. 1. Create your cookbook ``` chef generate cookbook my_repo/cookbooks/my_cookbook ``` 2. Edit the `metadata.rb` file Open your repo in Visual Studio Code. The one key file you will want to manage is the `metadata.rb` file. Please take a moment now to add your contact information and enter a starting version number for your cookbook. ``` name 'my_cookbook' maintainer 'The Authors' maintainer_email '<EMAIL>' license 'All Rights Reserved' description 'Installs/Configures my_cookbook' version '0.1.0' chef_version '>= 16.0' ``` 3. Edit the default recipe Open `my_repo\cookbook\my_cookbook\recipes\default.rb` in Visual Studio and add: For Windows: ``` powershell_script 'get my path' do code <<-CODE [Environment]::GetEnvironmentVariable("Path") CODE end ``` For macOS: ``` bash 'get my path' do user 'root' code <<-EOH echo $PATH EOH end ``` * Spacing matters! Be mindful of spaces * Use LF line spacing and not CRLF. (Look to the bottom right of the status bar in Visual Studio Code) Note If you want to use the Chef Desktop cookbook you received from Chef instead of creating a new one, then navigate and unzip that file into your cookbooks directory. Now you have two cookbooks. Update the `metadata.rb` file for the Chef Desktop cookbook to add your contact details. Chef Desktop comes with a large number of options for configuring your Windows and Mac desktops. Look through the `mac.rb` and `windows.rb` files to explore what settings you want to turn on for your testing and evaluation. For those resources you do not want to explore yet, set their action to ‘:nothing’. See the [Chef Desktop cookbook documentation](../desktop-cookbook/index) for more information about settings. Testing cookbooks with Test Kitchen ----------------------------------- Test Kitchen was installed with Chef Workstation. It provides Chef Infra with a testing harness for cookbooks that uses virtual machines(VMs). Consult your Apple and Microsoft licenses and service level agreements (SLA) to understand your options for acquiring or creating VMs for development. ### Test Kitchen Integrations Test Kitchen uses a driver plugin architecture to enable Test Kitchen to test instances on cloud providers such as Amazon EC2, Google Compute Engine, and Microsoft Azure. You can also test on multiple local hypervisors, such as VMware, Hyper-V, or VirtualBox. [Test Kitchen Documentation](../../workstation/kitchen/index) and the [Test Kitchen GitHub Repository](https://github.com/test-kitchen). ### Run Test Kitchen 1. **Run the Virtual Devices** When working with desktop cookbook that you received from Chef, you downloaded the two virtual devices, also called testing images. Now issue the following command to get them started: ``` kitchen create ``` 2. **Apply the Cookbooks to the Images** Run the following command to apply, or ‘converge’, the cookbooks with the base OS image: ``` kitchen converge ``` 3. **Verify the settings** Confirm that the converged code is the code that you meant to apply. In VSCode, navigate to the `test\integration\default` directory and examine the generated integration tests. Carefully go through these tests and adjust them to match the setting to the changes in the `default.rb` file. Next, run: ``` kitchen verify ``` If any of the tests fail, check the output and compare your settings in the `mac.rb` or `windows.rb` files against the matching tests. 4. **Cleanup** When you finish with your testing, you can run the following command to delete the running test images: ``` kitchen destroy ``` #### Kitchen Test Once you are familiar with Test Kitchen, you can perform all of the steps at once, including cleanup, with: ``` kitchen test ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/cookbook_repository/Deploy Desktop Cookbook to a Node ================================= Configure the node ------------------ Once you have uploaded the policy to server, now you are ready to try out your Chef Desktop cookbook on your first test node. Before you begin, you need to: ### Bootstrap the First Test Node 1. Create a [`client.rb` file](../../config_rb_client/index#example) with the basic information needed to connect to the Chef Infra Server instance 2. Identify a ‘test node’ - a virtual machine or laptop/desktop that you can test your working cookbook against 3. Get the serial number of your ‘test node’ From your workstation, configure the server and the `client.rb` file for your node. `S90T7HK2` is an example node serial number. ### Create a client.rb Create a local `client.rb` file with settings similar to: ``` validation_client_name 'my_org-validator' validation_key File.expand_path('c:\chef\my_org-validator.pem') chef_server_url "https://my.fqdn.com/my_chef_server_instance" ssl_verify_mode :verify_peer local_key_generation true rest_timeout 30 http_retry_count 3 chef_license 'accept' node_name 'S90T7HK2' ``` ### Identify a Test Node ``` C:\> knife node create S90T7HK2 Created node [S90T7HK2] ``` ### Apply the Chef Desktop Policy Use `knife node policy set` to apply the policy to a node. Use the name of the policy specified in the Policyfile.rb that was uploaded to the Chef Infra Server. ``` knife node policy set S90T7HK2 'Windows_Node_Policy_Group' 'desktop-config' ``` ### Install the Chef Infra Client Go to your test node and install the Chef Infra Client from an elevated PowerShell window, or use `sudo` if you are installing it from MacOS. For additional information, see the [Chef Install Script](../../chef_install_script/index) documentation. #### On Windows ``` . { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install -project chef ``` #### On macOS ``` curl -L https://omnitruck.chef.io/install.sh | sudo bash ``` ### Load the client.rb After Chef Infra Client finishes installing, copy the `client.rb` file with the correct data for your node and Chef Infra Server, and place that in `c:\chef`. ### Load the Key Then copy the `validator.pem` file you downloaded from your Chef Infra Server at the beginning of the guide and put it in the same folder. Deploy the Chef Desktop Cookbook to Your Test Node -------------------------------------------------- Run the client: ``` chef-client ``` * Next: [Zero-touch Deployment with Azure](../zero_touch/windows/index) * Last: [Chef Desktop Cookbook Development Environment](../cookbook_repository/index) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/nodes/Setting up Munki and AutoPkg for Application Management ======================================================= Note The application management documentation for Chef Desktop is under active development. Check back for upcoming enhancements and improvements. One of the great things about an automated management setup like this is being able to actively manage the applications that show up on user’s desktops. To handle that on macOS we use Munki. Our initial goal is to push a couple of required applications out to our users. Munki will handle managed installations and uninstallations. Munki also provides a ready-made application that offers users unmanaged applications that they can download if they choose. ### Create a CDN to hold the content To get started, follow [these instructions](https://docs.microsoft.com/azure/cdn/cdn-create-a-storage-account-with-cdn) for setting up an empty Azure CDN or [these instructions](https://github.com/grahamgilbert/terraform-aws-munki-repo) for setting up an empty AWS CDN. This empty CDN will host all the application content that will be deployed for both macOS and Windows devices. However, each OS type requires a slightly different directory and file structure. ### Create containers in your Storage account Create a container in the storage account to hold the content for users. For macOS, all the content, either managed or unmanaged, goes here. 1. Go to your storage account 2. Navigate to Blob Storage -> Containers. 3. Create a container labeled Munki 4. Set the access level to ‘Container’ Next, create the basic directory structure in each container that the app clients expect to see. In the Gorilla container, create folders to match this structure. We’re going to build the files that go in the folders just below. Build the top level folders for both clients, the child folders are indicated to give you a reference of how the whole thing looks over time as applications are added. Build out a folder structure that looks like this: ``` [Munki web root]├── catalogs│ ├── *.yaml├── manifests│ ├── *.yaml├── icons│ ├── *.ico├── pkgsinfo│ ├── *.*└── pkgs├── *.pkg ``` ### Create a Catalog and Manifest for your Clients These steps demonstrate installing Firefox and VS Code on clients to give you an idea of how to deploy an application on each OS type. #### Munki Setup With [Munki](https://github.com/munki/munki), the configuration files are in XML and editing them directly can produce errors so we recommend using command line tools. 1. Install the Munki tools locally [Download](https://github.com/munki/munki/releases) the whole Munki package to the macOS machine and install it. 2. Setup a local File Share on the macOS machine Setup a local file share on the macOS machine. Use the tools below to populate it with the settings and configuration you need. Follow this [document](https://github.com/munki/munki/wiki/Demonstration-Setup) to setup a local repo, use Server Explorer to sync it to Azure - go to “Building a “server” repository” 3. Configure Munki Run this command to configure Munki. The repo path must match the one you created above. Note that the path must have 3 slashes in it, e.g. “file:///”. ``` munkiimport --configure ``` 4. Now import the pkg files. When you import the first package the catalog will build automatically. ``` munkiimport - firefox munkiimport - VSCode ``` 5. Next, run the following Autopkg commands to get all the Munki tools pulled in for the nodes (laptops) to use ``` autopkg repo-add recipes autopkg run -k MUNKI_REPO=/Users/Shared/Munki_repo Munkitools4.Munki ``` 6. After that, run `makecatalogs` to pull the Munki updates in: ``` makecatalogs ``` 7. Finally, run `manifestutil` too create the manifest and pull your apps under managed installs. If you run into issues with the tool, use the MunkiAdmin GUI. It makes it much easier to see what’s going on with the configuration files. ``` /usr/local/Munki/manifestutil Entering interactive mode... (type "help" for commands) > new-manifest site_default > add-catalog my_catalog --manifest site_default Added testing to catalogs of manifest site_default. > add-pkg Firefox --manifest site_default Added Firefox to section managed_installs of manifest site_default. > add-pkg VSCode --manifest site_default Added VSCode to section managed_installs of manifest site_default. > add-pkg Munkitools_admin --manifest site_default Added Munkitools_admin to section managed_installs of manifest site_default. ... > exit ``` Now you can use Storage Explorer to move the entire thing into your Azure Blob Storage #### Example Munki Catalog Below is a section of a Munki catalog. You can manually edit the details if you need to, but we strongly encourage you to use the tools above to reduce the chances of introducing an error. ``` <plist version="1.0"> <array> <dict> <key>autoremove</key> <false/> <key>catalogs</key> <array> <string>mycatalog</string> </array> <key>display_name</key> <string>VSCode</string> <key>installed_size</key> <integer>1285143</integer> <key>installer_item_hash</key> <string> b9a5b90ff2b0bb733a9b719fe2afea5d5dc02875dc96b969a9fcf8b9de9214a6 </string> <key>installer_item_location</key> <string>VSCode.pkg</string> <key>installer_item_size</key> <integer>513821</integer> <key>minimum_os_version</key> <string>10.5.0</string> <key>name</key> <string>VSCode</string> <key>receipts</key> <array> <dict> <key>installed_size</key> <integer>1285143</integer> <key>packageid</key> <string>com.microsoft.visual-studio</string> <key>version</key> <string>8.5.2</string> </dict> </array> <key>unattended_install</key> <true/> <key>uninstall_method</key> <string>removepackages</string> <key>uninstallable</key> <true/> <key>version</key> <string>1.45.1</string> </dict``` #### Example Munki Manifest Notice that the format for the manifest is similar to what Gorilla uses: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>catalogs</key> <array> <string>my_catalog</string> </array> <key>included_manifests</key> <array> </array> <key>managed_installs</key> <array> <string>munkitools_app</string> <string>munkitools_app_usage</string> <string>munkitools_core</string> <string>munkitools_launchd</string> <string>Firefox</string> <string>VSCode</string> </array> <key>managed_uninstalls</key> <array> </array> <key>managed_updates</key> <array> </array> <key>optional_installs</key> <array> </array> </dict> </plist``` Now that the catalog and manifest are ready, test this out from a macOS node by running the following commands from a terminal window. Run the first command from the macOS client to verify that the correct configuration got to that node and then run the second command to actually install the managed applications. ``` sudo /usr/local/munki/managedsoftwareupdate --show-config sudo /usr/local/munki/managedsoftwareupdate ``` Final Checklist --------------- You are almost ready to start the process. Please ensure that you have completed the following steps: * You have setup Apple Business Manager * You have imported the serial number for at least one of your macOS machine * You have configured your MDM server in Apple Business Manager to accept your devices * You have setup and configured the MDM to accept devices from Apple Business Manager + You have all your certificates in place + You have built and uploaded the InstallApplications package and imported it into the MDM * If you are going to use Munki, is the S3 bucket correctly configured for it? Bootstrapping the first Node ---------------------------- If all goes according to plan, the first node should be ready to restart, pull down all the packages and/or scripts, load Chef Infra Client, and do the first client run. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/zero_touch/macos/application_management/Set up policy ============= Upload the Chef Desktop Cookbook -------------------------------- Upload the Chef Desktop Cookbook to your Chef Infra Server. From the development environment command line, navigate to the `/cookbooks` directory and run: ``` knife cookbook upload <your cookbook name``` Knife and other Chef tools use the cookbook name specified inside of either the `metadata.rb` file or the `policyfile.rb` file, which is case sensitive. Naming cookbooks in all lower-case is the easiest way to avoid conflicts with your `knife` or `chef` commands. Now your Chef Infra Server has the cookbook and settings it needs to apply to the nodes. Configure and upload the Policyfile to Chef Server -------------------------------------------------- Check the Policyfile and apply it to our test nodes. Policies are a convenient strategy for managing nodes. Read [more about policies](../../policy/index). ### Check the Policyfile Your Chef Desktop `Policyfile.rb` should look similar to: ``` name 'desktop-config' # default_source :supermarket, 'https://supermarket.chef.io' do |s| # s.preferred_for 'chef-client' # end # run_list: chef-client will run these recipes in the order specified. # cookbook::recipe run_list 'desktop-config::default' # Specify a custom source for a single cookbook: cookbook 'desktop-config', path: '.' ``` ### Upload the Policyfile Upload the Policyfile to the Chef Infra Server. Call `chef update` first to do some needed housekeeping around your policyfile. If this is the first time that you are using a Policyfile, use the `chef install` command to generate a lock file: ``` chef install Policyfile.rb ``` Run `chef update` and `chef push` every time you update the version of your cookbook: ``` chef update chef push 'my_Policy_Group' 'Policyfile.rb' ``` * Next: [Zero-touch Deployment with Azure](../zero_touch/windows/index) * Last: [Chef Desktop Cookbook Development Environment](../cookbook_repository/index) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/policies/Enrolling the devices ===================== Note The application management documentation for Chef Desktop is under active development. Check back for upcoming enhancements and improvements. Introduction ------------ The Chef Desktop management pattern allows you to manage all your macOS devices using a MicroMDM server for a fully automated experience. If you have not done so, read [The Chef Desktop Development Pattern](../../desktop_pattern/index) to familiarize yourself with some of the basic steps for getting started. We will repeat a number of those steps here. Overview -------- This document describes how to set up the following things: * Install Chef Infra Server and Chef Automate * Build your local repo and test Chef Desktop * Build the InstallApplications package. * Build the MDM server * Build and deploy Munki to deploy apps to the laptops Setting up the MDM ------------------ We need a Mobile Device Management (MDM) service to capture macOS machines as they boot, and to securely connect and push applications and configuration settings to them. In this document we use MicroMDM, but there are others on the market like VMware Airwatch, SimpleMDM, and others. Your configuration and setup may begin like this: 1. Stand up a new Linux instance in Azure or AWS and ensure that you use SSH keys for authentication rather than passwords. 2. Once the instance is running, upgrade the installed packages: ``` sudo apt-get update && sudo apt-get upgrade -y sudo reboot ``` 3. Create a micromdm directory on the drive. 4. Clone MicroMDM from Github: ``` curl -L https://github.com/micromdm/micromdm/releases/download/v1.6.0/micromdm_v1.6.0.zip ``` 5. Open a terminal window on the Linux box. ``` sudo apt-get install unzip unzip micromdm_v1.6.0.zip cd /micromdm/build/linux ./mdmctl config set -name <some name> -api-token <password> -server-url https://somefqdn ``` Where: `-name` is the label you choose to identify your MicroMDM server `-api-token` is a password you will use to connect to your server to configure it `-server-url` is the publicly accessible IP or FQDN of your created server 6. Start the MDM and note the password you use. You will need this password with `mdmctl` to configure the server. ``` sudo ./micromdm serve -server-url https://somefqdn/ -api-key <password``` 7. There are three important certificates on your MDM server: * A TLS capable certificate that allows you to connect to your MDM server via port 443. * An APNS certificate, which is a Push certificate, that allows your MDM server to talk to your macOS clients. * A DEP certificate that allows your MDM server to talk to deploy.apple.com and accept incoming boot requests from Apple’s servers. ### Securing the MDM Read this [guide](https://github.com/micromdm/micromdm/blob/main/docs/user-guide/quickstart.md) which describes the steps necessary to create both the DEP and APNS certificates that you need for your MicroMDM server. Initial App Deployment to a Node -------------------------------- `InstallApplication` is a stage in the Apple setup process that occurs between the time the display shows up for the user and when the user reaches the desktop for the first time. [InstallApplications](https://github.com/macadmins/installapplications) (plural) is a corresponding application that will install applications or settings during that stage of configuration. 1. Start by loading these apps on your macOS machines: * The current release of Chef Infra Client * DepNotify [Depnotify](https://gitlab.com/Mactroll/DEPNotify) is an open source tool that tells users how much more time their macOS machine needs to install applications before they can starting using it. * Caffeinate [Caffeinate](https://ss64.com/osx/caffeinate.html) keeps the desktop active so that the screensaver does not turn on during installation. The screensaver will turn off network connections and break the setup if it activates. * [Chef Bootstrap](../../../install_bootstrap/index) The last thing we pull down is a python script to configure the `chef/client.rb` file and run `chef-client` the first time to configure the laptop to its desired state and keep it in that state. 2. Install the latest version of [InstallApplications](https://github.com/macadmins/installapplications). 3. Modify the LaunchDaemon plist to look like the [first example](#example-munki-catalog) below. Notice that we updated the JSONUrl and a couple of the identity sections. Also notice that we enabled some of the commands needed to properly populate DepNotify so it displays useful information to the user. 4. Modify the build-info.json file on the identity line to correctly reference your developer certificate. Read the [InstallApplications documentation](https://github.com/erikng/installapplications/wiki/Packaging) for information about the type of accounts that Apple requires to install packages. 5. Use `munkipkg` to create the actual pkg file. See the [munkipkg documentation](https://github.com/munki/munki-pkg) for instructions. 6. Upload the compiled package to your MDM server. 7. Issue the following commands on your MDM: ``` ~/mdm/build/linux/mdmctl apply app -pkg ~/Desktop/mdmvid/InstallApplications.pkg -sign "Developer ID Installer: groob (myid)" -upload [WARNING] package signing only implemented on macOS. An unsigned macOS package will not install with MDM. ``` 8. In the example above, the developer ID should match the one you specify in the `build-info` file below. Signing Your Apps ----------------- Sign and/or notarize everything that the MDM server touches. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/zero_touch/macos/macos_firewall Resource ======================== [All Desktop resources page](../index) --- Use the **macos_firewall** resource to enable the firewall on macOS systems. Syntax ------ --- The full syntax for all of the properties that are available to the **macos_firewall** resource is: ``` macos_firewall 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `macos_firewall` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. Actions ------- --- The **macos_firewall** resource has the following actions: `:disable` `:enable` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- This resource does not have any properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **macos_firewall** resource in recipes: **Turn on the macOS Firewall**: ``` macos_firewall 'Enable Firewall Protection' do action :enable end ``` **Turn off the macOS Firewall**: ``` macos_firewall 'Disable Firewall Protection' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/macos_firewall/Enrolling the devices ===================== Note The application management documentation for Chef Desktop is under active development. Check back for upcoming enhancements and improvements. Chef Software’s Desktop pattern and tools expands familiar device management systems with extensive application and configuration capabilities that are designed to scale with automation. Chef Desktop provides a cookbook with YAML settings that covers the most common (and some less common) device configuration needs. Of course, we continue to support and improve our classic Ruby cookbook customizations for when you need to go beyond the ordinary. The Chef Desktop pattern sets you up to manage applications with a CDN, so even when one thousand devices in your fleet means managing ten thousand applications, your Windows and macOS users can still access them through a unified catalog. Chef Desktop uses Chef Software’s leading tools, providing observability, compliance reporting, and an audit trail as part of the process. This guide covers automating the Chef Desktop pattern to manage your macOS and Windows devices. Configuration Overview ---------------------- A work triangle is in play in Chef Desktop. The first leg is the Chef Infra Server with Chef Automate that holds and applies configurations to your nodes. The second leg is a Developer node running Chef Workstation from which you create and define the policies and settings that the Chef Infra Server metes out. The third leg of the triangle is the list of nodes to which the various polices and settings are applied. The automation process follows these steps: 1. A node, such as a laptop or desktop, boots up the very first time and checks in with either Apple Business Manager (ABM) or Azure. 2. ABM or Azure reports the device as managed and redirects it to Microsoft Intune for management. 3. Microsoft Intune captures and provisions the device in the time between a user selecting **next** on the sign in screen and the desktop opening. This guide helps you: * Build out your Azure Instance * Build a InstallApplications package to bootstrap macOS * Build and deploy Munki to deploy apps to the macOS devices * Write the PowerShell scripts needed to bootstrap Windows * Build and deploy Gorilla to deploy apps to Windows devices Prerequisites ------------- This guide assumes you have completed the previous steps: 1. [Install Chef Components](../../desktop_setup_chef/index) 2. [Chef Desktop Cookbook Development Environment](../../desktop_setup_cookbook/index) 3. [The Chef Desktop Development Pattern](../../desktop_pattern/index) ### Required Software Integrating Chef Desktop with Microsoft Intune and Windows Autopilot software and subscriptions as well as specific software for macOS and Windows systems. The solution in this guide requires: [Microsoft Azure](https://azure.microsoft.com) If you do not already have one, sign up for an [Azure account](https://azure.microsoft.com) [Microsoft Intune](https://www.microsoft.com/microsoft-365/enterprise-mobility-security/microsoft-intune) Microsoft Intune is a cloud-based service that you will use to capture and push configuration to devices. [Windows Autopilot](https://docs.microsoft.com/windows/deployment/windows-autopilot/windows-autopilot) Windows Autopilot simplifies the IT-side of managing Windows devices. #### macOS [Apple Enterprise Developer Account](https://developer.apple.com/programs/enterprise/) This program allows for macOS devices to be auto-assigned to an MDM service, which then provisions the devices for you. The Apple Developer Enterprise Program is a program that supports large organizations in developing and deploying proprietary, internal-use apps to their employees. You may find mentions of Apple Device Enrollment Program (DEP) elsewhere, which is the predecessor to ABM and used interchangeably with ABM. [AutoPkg](https://github.com/autopkg/autopkg) AutoPkg is an automation framework for macOS software packaging and distribution, oriented towards the tasks one would perform manually to prepare third-party software for mass deployment to managed clients. [Munki](https://www.munki.org/munki/) Munki is an [open source project](https://github.com/munki/munki) from Walt Disney Animation Studios. It is a set of tools for managing applications on macOS computers. [MunkiAdmin](https://github.com/hjuutilainen/munkiadmin/releases/) MunkiAdmin is a graphical user interface (GUI) for managing munki repositories [Storage Explorer](https://azure.microsoft.com/features/storage-explorer/) Storage Explorer is a free tool from Microsoft for managing your Azure cloud storage resources. #### Windows [Gorilla](https://github.com/autopkg/autopkg/releases) Gorilla is an [open source project](https://github.com/1dustindavis/gorilla). It is a set of tools for managing applications on Windows computers. [Storage Explorer](https://azure.microsoft.com/features/storage-explorer/) Storage Explorer is a free tool from Microsoft for managing your Azure cloud storage resources. Setup Azure ----------- ### Configure Microsoft Intune and Active Directory First, read about [setting up Microsoft Intune](https://docs.microsoft.com/mem/intune/fundamentals/setup-steps) You will want to spend a bit of time going through that document to get your Microsoft Intune and Azure Active Directory instances configured. ### Register Devices in Azure The fastest and best way to set up a macOS device is by never physically touching it. In this case, you will sign on to Apple Business Manager and use the article above to set up Azure as the MDM which receives the laptops and other devices you wish to manage. #### Windows Options First, read about [getting started with Windows Autopilot](https://docs.microsoft.com/en-us/mem/intune/enrollment/enrollment-autopilot) For Windows devices, Azure acts as both the enrollment service and the MDM at the same time. Also, current iterations of Windows 10 will bootstrap from Azure when the correct settings from a laptop are captured. ##### Dynamic Device Management Use dynamic device groups to capture both macOS and Windows devices and automatically assign profiles and configuration policies. Dynamic device groups are essential for macOS devices and Windows-kiosk style devices, because all devices in the groups are assigned the correct policies. [Create an Autopilot Dynamic Device Group](https://docs.microsoft.com/en-us/mem/autopilot/enrollment-autopilot#create-an-autopilot-device-group) ##### Dynamic User Management But what happens if you want more flexibility to manage the users instead of devices? This approach creates a user group that applies the same policies to individuals. That way, if a user logs onto a different system their account is still managed correctly. [Create a Dynamic User Group](https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/groups-dynamic-membership) #### OS X Options [OSX Auto Enrollment](https://docs.microsoft.com/en-us/mem/intune/enrollment/device-enrollment-program-enroll-ios) This article walks you through the configuration of Windows Autopilot and Microsoft Intune to ingest macOS devices as they boot the first time. ### Create Device Groups You will need to create two device groups for macOS devices and two for Windows (a total of four device groups). You will use the first device group to apply the initial enrollment profile. The second device group is for applying, updating, and removing packages, scripts, etc. on the devices. ### Create Enrollment/Deployment Profiles Now that you have your systems listed in Azure, we need to get them under an enrollment or deployment profile. This initial configuration of the device will bring it under management. First, read about [getting started with Microsoft Intune](https://docs.microsoft.com/mem/intune/enrollment/enrollment-autopilot) ### Configuration Scripts For Windows devices, develop your PowerShell configuration scripts to create and populate the `validation.pem` file and the `client.rb` file in the `c:\chef` directory. You will also want to install the Chef Infra Client. ### Registering the Devices with Chef Infra Server The `knife` command-line tool provides an interface for interacting with a Chef Infra Server from a local workstation. You’ll use two `knife` commands from your developer workstation to the Chef Infra Server. The first command creates the node on the Chef Infra Server, and the second assigns a Chef policy to that node. ``` # knife node policy set SERIAL_NUMBER_OR_FQDN 'NODE_GROUP' 'POLICYFILE' knife node create S90T7HK2 Created node [S90T7HK2] knife node policy set S90T7HK2 'Windows_Node_Policy_Group' 'ChefDesktop' Successfully set the policy on node S90T7HK2 ``` ### Re-Registering the Devices with Chef Infra Server During testing–and in any other time that you change the contents of a device–you may need to re-register it. Follow these steps to re-register a device: ``` # Chef Infra Server distinguishes between a Node object and a Client object knife node delete S90T7HK2 Deleted node [S90T7HK2] knife client delete S90T7HK2 Deleted client [S90T7HK2] knife node create S90T7HK2 Created node [S90T7HK2] knife node policy set S90T7HK2 'Windows_Node_Policy_Group' 'desktop-config' Successfully set the policy on node S90T7HK2 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/zero_touch/windows/Setting up Gorilla for Application Management ============================================= Note The application management documentation for Chef Desktop is under active development. Check back for upcoming enhancements and improvements. One of the great things about an automated management setup like this is the ability to actively manage the applications that show up on users' desktops. To handle applications on macOS, we use Munki. To handle applications for Windows, we use Gorilla. Our initial goal is to push a couple of required Apps out to our users. The two apps will handle both managed installations and managed uninstallations. Also, Munki for macOS provides a ready-made application can display to users and offer them unmanaged apps. For Windows users, we will publish unmanaged apps via the private Microsoft Store. ### Create a CDN To get started, follow this document to set up an Azure Content Delivery Network (CDN). After setting up, you will have an empty CDN. Use this empty CDN to host all the App content we want to deploy for both our Macs and Windows devices. We will need to set up slightly different directory and file structures for each OS type. [Create an Azure CDN](https://docs.microsoft.com/azure/cdn/cdn-create-a-storage-account-with-cdn) ### Create Containers in your Storage Account Now, create two containers in your storage account to hold the content for our users. For macOS devices, all content we want them to have - either ‘managed’ (we push it to them) or ‘unmanaged’ (users can download if they wish) goes here. For Windows users, only the managed content goes in the corresponding bucket and we will use the App Store to make things we license available to them. 1. Go to your storage account 2. Navigate to Blob Storage > Containers 3. Create 2 containers with one labeled “Munki” and the other labeled “Gorilla” 4. Set their access level to ‘Container’ The next step is to create the basic directory structure in each container that the app clients expect to see. In the Gorilla container, create folders to match this structure. We are going to build the files that go in the folders just below. Just build the top level folders for both clients, the child folders are indicated in the example below to give you a reference of how the file structure will look over time as apps are added. ``` [Gorilla web root] ├── manifests │ ├── *.yaml ├── catalogs │ ├── *.yaml └── packages ├── Firefox ├── Chrome ├── *.nupkg ├── *.msi ├── *.exe └── *.ps1 ``` Now for your Munki container, build out a folder structure that looks like this: ``` [Munki web root] ├── catalogs │ ├── *.yaml ├── manifests │ ├── *.yaml ├── icons │ ├── *.ico ├── pkgsinfo │ ├── *.* └── pkgs ├── *.pkg ``` macOS (Munki) Catalog and Manifest ---------------------------------- Spend some time thinking about and planning what you ultimately want to put into your manifests and catalogs that your users can access. For simplicity, we will demonstrate installing Firefox and VS Code on clients to give you an idea of how to deploy for each OS type. ### Install Munki We are going to take a different approach with Munki because the configuration files are in XML and editing them directly can be fraught with peril so we are going to rely on using command line tools for the most part. Get started by reviewing the [Munki documentation](https://github.com/munki/munki). Next, [download Munki](https://github.com/munki/munki/releases) to your macOS and install it. #### Set up a local File Share on your Mac We are going to set up a local file share on your Mac. We will use the tools below to populate it with the settings and configuration we need. Follow this doc to set up a local repo, we will use Server Explorer to sync it to Azure - go to “Building a “server” repository” For guidance, follow the [Munki setup demonstration](https://github.com/munki/munki/wiki/Demonstration-Setup). ### Configure Munki Run this command to configure Munki. The repo path must match the one you created just above. Note that the path must have 3 slashes in it `file:///` ``` munkiimport --configure ``` Now you can import pkg files. When you import the first package, the catalog gets built for you automatically. ``` munkiimport - firefox munkiimport - VSCode ``` Next, run the following `autopkg` commands to get all the Munki tools pulled in for the nodes (laptops) to use.` ``` autopkg repo-add recipes autopkg run -k MUNKI_REPO=/Users/Shared/munki_repo munkitools4.munki ``` After that, run `makecatalogs` to pull the Munki updates in. ``` makecatalogs ``` Finally, run `manifestutil` to create the manifest and pull your apps under managed installs. If you run into issues with the tool, you can flip over to the MunkiAdmin GUI. The MunkiAdmin GUI makes it much easier to see what is going on with the configuration files. ``` /usr/local/munki/manifestutil Entering interactive mode... (type "help" for commands) > new-manifest site_default > add-catalog my_catalog --manifest site_default Added testing to catalogs of manifest site_default. > add-pkg Firefox --manifest site_default Added Firefox to section managed_installs of manifest site_default. > add-pkg VSCode --manifest site_default Added VSCode to section managed_installs of manifest site_default. > add-pkg munkitools_admin --manifest site_default Added munkitools_admin to section managed_installs of manifest site_default. ... > exit ``` Now you can use Storage Explorer to move the entire thing into your Azure Blob Storage. #### Example Munki Catalog Below is a section of a Munki catalog. You CAN edit the details if needed, but using the tools above is strongly encouraged to reduce the probability of introducing an error. ``` <plist version="1.0"> <array> <dict> <key>autoremove</key> <false/> <key>catalogs</key> <array> <string>mycatalog</string> </array> <key>display_name</key> <string>VSCode</string> <key>installed_size</key> <integer>1285143</integer> <key>installer_item_hash</key> <string> b9a5b90ff2b0bb733a9b719fe2afea5d5dc02875dc96b969a9fcf8b9de9214a6 </string> <key>installer_item_location</key> <string>VSCode.pkg</string> <key>installer_item_size</key> <integer>513821</integer> <key>minimum_os_version</key> <string>10.5.0</string> <key>name</key> <string>VSCode</string> <key>receipts</key> <array> <dict> <key>installed_size</key> <integer>1285143</integer> <key>packageid</key> <string>com.microsoft.visual-studio</string> <key>version</key> <string>8.5.2</string> </dict> </array> <key>unattended_install</key> <true/> <key>uninstall_method</key> <string>removepackages</string> <key>uninstallable</key> <true/> <key>version</key> <string>1.45.1</string> </dict``` #### Example Munki Manifest Notice that the format for the Munki manifest is similar to what Gorilla uses: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>catalogs</key> <array> <string>my_catalog</string> </array> <key>included_manifests</key> <array> </array> <key>managed_installs</key> <array> <string>munkitools_app</string> <string>munkitools_app_usage</string> <string>munkitools_core</string> <string>munkitools_launchd</string> <string>Firefox</string> <string>VSCode</string> </array> <key>managed_uninstalls</key> <array> </array> <key>managed_updates</key> <array> </array> <key>optional_installs</key> <array> </array> </dict> </plist``` You can also [use AWS for your CDN](https://github.com/grahamgilbert/terraform-aws-munki-repo). Once you have your catalog and manifest ready, you can test this out from a macOS node by running the following commands from a terminal window. Run the first command from your macOS client to verify that the correct configuration got to that node and then run the second command to actually install the managed applications ``` sudo /usr/local/munki/managedsoftwareupdate --show-config sudo /usr/local/munki/managedsoftwareupdate ``` Windows (Gorilla) Catalog and Manifest -------------------------------------- Spend some time thinking about and planning what you ultimately want to put into your manifests and catalogs that your users can access. For simplicity, we will demonstrate installing Firefox and VS Code on clients to give you an idea of how to deploy for each OS type. ### How Gorilla Operates Save the `config.yaml` file to the `/files` directory of your Chef Desktop cookbook. Configuring the app resource in the Windows recipe file deploys the `config.yaml` setting to your Windows 10 desktops. The next time Gorilla checks in with your CDN, it pull down the manifest, parses the applications and catalog listings for loading, and finally loads the applications by first loading the catalog(s) and then attempting to load the apps from the catalog(s). To see this in action, use `gorilla -d` from the command line to get the debug output. [Gorilla Documentation](https://github.com/1dustindavis/gorilla) #### Sample Gorilla catalog.yaml ``` ---Chocolatey:display_name:Chocolateycheck:file:- path:C:\ProgramData\chocolatey\choco.exeversion:0.10.15installer:hash:0C1282378641E03564844D04881209AA946D7D2475049BE32B3151BD68F2758Flocation:packages/chocolatey/chocolatey_installer-1.0.ps1type:ps1version:1.0ChocolateyCoreExtension:dependencies:- Chocolateydisplay_name:Chocolatey Core Extensioncheck:file:- path:C:\ProgramData\chocolatey\extensions\chocolatey-core\chocolatey-core.psm1hash:376E6EDA567DDDD6AA70CFC9EC5380CE0EB1383BE83C2FBDC87F6FC79252E4E8installer:hash:5ECEF3B776508CEBC4B52E9AC7F04D213C2045A6765F12E17545A5FBE2F41928location:packages/chocolatey/extensions/core/chocolatey-core.extension.1.3.5.1.nupkgtype:nupkgversion:1.3.5.1FireFox:display_name:Firefoxcheck:file:- path:C:\Program Files\Mozilla Firefox\firefox.exeversion:75.0installer:hash:FF029F6E59D9D92D3AC5F8E837C973B641B3400980624D3A830DCFE55D4C71FClocation:packages/firefox/Firefox Setup 75.0.exearguments:- /S- /INI=c:\gorilla\cache\install.initype:exeversion:75.0VSCode:display_name:VSCodecheck:file:- path:C:\Program Files\Microsoft VS Code\Code.exeversion:1.45.1installer:location:packages/vscode/VSCodeSetup-x64-1.45.1.exehash:E9E107CF53F8F06688C881E4616BD9A8553D012A657389399827E0EC2155633Carguments:- /VERYSILENT- /MERGETASKS=!runcodetype:exeuninstaller:location:packages/vscode/VSCodeSetup-x64-1.45.1.exehash:E9E107CF53F8F06688C881E4616BD9A8553D012A657389399827E0EC2155633Ctype:exeversion:1.45.1 ``` #### Sample Gorilla Manifest.yaml ``` ---name:my_manifestmanaged_installs:- Chocolatey- ChocolateyCoreExtension- VSCode- Firefoxmanaged_uninstalls:managed_updates:included_manifests:catalogs:- my_catalog ``` #### Sample Gorilla config.yaml file ``` ---url:https://<your_cdn_name>.blob.core.windows.net/gorilla/manifest:my_manifestcatalogs:- my_catalogapp_data_path:C:/gorilla/cache ``` ### Configuring Apps in a Private Store for Windows We talked about a second way to get apps to your users in Windows. That method involves you licensing apps and then letting your users have them through your Private Microsoft Store. Follow the directions here to make that work for you. [Set up a Private Store in Azure](https://docs.microsoft.com/en-us/microsoft-store/distribute-apps-from-your-private-store) Final Checklist --------------- You are almost ready to start the process. Please ensure that you have completed the following steps: * You have set up Apple Business Manager * You have imported the serial number for at least one of your macOS devices * You have configured your MDM in Apple Business Manager to accept your devices * You have set up and configured the MDM to accept devices from Apple Business Manager + You have all your certificates in place + You have built and uploaded the InstallApplications package and imported it into the MDM * If you are going to use Munki, confirm if the S3 bucket is correctly configured for it. If all goes according to plan, then you should be ready to reset/restart your first node, have it pull down all the packages and/or scripts, load Chef Infra Client, and do the first client run. * Next: [Zero Touch Deployment with MicroMDM for macOS](../../macos/index) © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/zero_touch/windows/application_management/Chef Desktop Cookbook Reference =============================== [[edit on GitHub]](https://github.com/chef/desktop-config/tree/main/docs-chef-io/content/desktop/desktop-cookbook.md) The Chef Desktop cookbook provides Windows and macOS desktop administrators a straightforward experience for configuring and managing remote devices without requiring deep command-line knowledge or experience with Ruby or Chef Infra. Administrators can set common configuration options in Chef Desktop cookbook, such as using FileVault or BitLocker drive encryption, and then deploy the configuration to the fleet. Requirements ------------ The Chef Desktop cookbook installs onto your development environment. Once configured and tested, you then upload the Chef Desktop cookbook to your Chef Infra Server. From there, you deliver the Chef Desktop cookbook to your managed devices by adding the cookbook to the runlist in one of your Policyfiles. Like the Chef Desktop cookbook, you edit the Policyfiles for your Windows and macOS devices in your development environment and upload them to the Chef Infra Server. ### Supported Platforms * Microsoft Windows 10 * macOS 10.13 and later ### Chef Infra Client * Chef Infra Client 16+ Recipes ------- default.rb The Chef Desktop cookbook’s default recipe finds the underlying operating system (OS) and then calls the operating system-specific recipe. Each OS recipe is easy to understand and configure. windows.rb The Windows recipe is a series of settings for Windows 10 desktops. Example: ``` disk_encryption 'Turns on BitLocker Drive Encryption' do action :enable # valid options include :enable, :disable, :nothing end ``` mac.rb The macOS recipe follows the same format, and as much as possible, the same spelling and parameters for a strong consistency between the recipes and no change in verbiage. Example: ``` chef_client_launchd 'Setup the Chef client to run every 30 minutes' do interval 30 action :enable # valid options include :enable, :disable end ``` ### Usage Policyfile Policyfiles are the preferred way to manage role, environment, and community cookbook data. It is a single file that you upload to Chef Infra Server. A Policyfile is associated with a group of nodes, cookbooks, and settings. When these nodes perform a Chef Infra Client run, they use the recipes specified in the Policyfile run-list. Versioned Policyfiles are safe to promote through your deployment pipeline and reliably deploy new configuration settings. This cookbook uses a Policyfile, which is preset to run the cookbook when you call from the directory above where your Chef Desktop cookbook lives. Example: ``` chef-client -z -o chefdesktop ``` Resources --------- Resources with operating system label prefixes indicate the operating system they belong to, such as `osName_app_management` or `(os name) disk_encryption`. Resources with no operating system label prefix work interchangeably between macOS and Windows. See the [Desktop resources documentation](../resources/index) for information about each resource. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/desktop-cookbook/macos_admin_control Resource ============================== [All Desktop resources page](../index) --- Use the **macos_admin_control** resource to require Admin level privileges to make system-wide changes **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **macos_admin_control** resource is: ``` macos_admin_control 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `macos_admin_control` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. Actions ------- --- The **macos_admin_control** resource has the following actions: `:disable` `:enable` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- This resource does not have any properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **macos_admin_control** resource in recipes: **Set Admin control to require Admin access**: ``` admin_control 'Require Admin rights to perform system-wide changes' do action :enable end ``` **Do not require Admin access for System-Wide changes**: ``` admin_control 'Require Admin rights to perform system-wide changes' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/macos_admin_control/macos_disk_encryption Resource ================================ [All Desktop resources page](../index) --- Use the **macos_disk_encryption** resource to enforce FileVault encryption on macOS systems. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **macos_disk_encryption** resource is: ``` macos_disk_encryption 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `macos_disk_encryption` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. Actions ------- --- The **macos_disk_encryption** resource has the following actions: `:enable` Turns on FileVault. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- This resource does not have any properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/macos_disk_encryption/macos_power_management Resource ================================= [All Desktop resources page](../index) --- Use the **macos_power_management** resource to set the power settings of a kiosk-style device when you need it always-on **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **macos_power_management** resource is: ``` macos_power_management 'name' do computer_sleep_time String # default value: "never" disk_sleep_time String # default value: "never" display_sleep_time String # default value: "never" action Symbol # defaults to :set if not specified end ``` where: * `macos_power_management` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `computer_sleep_time`, `disk_sleep_time`, and `display_sleep_time` are the properties available to this resource. Actions ------- --- The **macos_power_management** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` This action sets the policy as defined in its properties. Properties ---------- --- The **macos_power_management** resource has the following properties: `computer_sleep_time` **Ruby Type:** String | **Default Value:** `never` A time value between 1-60 minutes or “never” to use to set the computer to sleep after. Defaults to never `disk_sleep_time` **Ruby Type:** String | **Default Value:** `never` A time value between 1-60 minutes or “never” to use to set the hard disk to sleep after. Defaults to never `display_sleep_time` **Ruby Type:** String | **Default Value:** `never` A time value between 1-60 minutes or “never” to use to set the display to sleep after. Defaults to never Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **macos_power_management** resource in recipes: **Configure Power Management settings**: ``` macos_power_management 'Set the Device to a defined power level' do computer_sleep_time 'never' display_sleep_time 'never' disk_sleep_time 'never' action :set end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/macos_power_management/macos_password_policy Resource ================================ [All Desktop resources page](../index) --- Use the **macos_password_policy** resource to set password complexity, password length, etc on macOS systems. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **macos_password_policy** resource is: ``` macos_password_policy 'name' do exempt_user String lockout_time Integer max_failed_logins Integer maximum_password_age Integer # default value: 365 minimum_lowercase_letters Integer # default value: 0 minimum_numeric_characters Integer # default value: 0 minimum_password_length Integer # default value: 12 minimum_special_characters Integer # default value: 0 minimum_uppercase_letters Integer # default value: 0 remember_how_many_passwords Integer # default value: 3 action Symbol # defaults to :set if not specified end ``` where: * `macos_password_policy` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `exempt_user`, `lockout_time`, `max_failed_logins`, `maximum_password_age`, `minimum_lowercase_letters`, `minimum_numeric_characters`, `minimum_password_length`, `minimum_special_characters`, `minimum_uppercase_letters`, and `remember_how_many_passwords` are the properties available to this resource. Actions ------- --- The **macos_password_policy** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` This action sets the password policy as defined in its properties. Properties ---------- --- The **macos_password_policy** resource has the following properties: `exempt_user` **Ruby Type:** String A user to whom the password policy is not applied `lockout_time` **Ruby Type:** Integer The amount of time your account is locked out after you exceed max failed logins `max_failed_logins` **Ruby Type:** Integer The maximum number of failed logins before you are locked out `maximum_password_age` **Ruby Type:** Integer | **Default Value:** `365` The maximum age in days for a password before it must be changed, defaults to 365 `minimum_lowercase_letters` **Ruby Type:** Integer | **Default Value:** `0` The minimum number of lower case letters that must be in a password `minimum_numeric_characters` **Ruby Type:** Integer | **Default Value:** `0` The minimum number of numbers that must be in a password `minimum_password_length` **Ruby Type:** Integer | **Default Value:** `12` The minimum length a password must be `minimum_special_characters` **Ruby Type:** Integer | **Default Value:** `0` The minimum number of special characters that must be in a password. Eg. *&^% `minimum_uppercase_letters` **Ruby Type:** Integer | **Default Value:** `0` The minimum number of upper case letters that must be in a password `remember_how_many_passwords` **Ruby Type:** Integer | **Default Value:** `3` The number of previous passwords to remember to prevent users for keeping stale passwords Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **macos_password_policy** resource in recipes: **Set the local password policy**: ``` macos_password_policy 'Setup appropriate password complexity and rules' do max_failed_logins 5 lockout_time 2 maximum_password_age 365 minimum_password_length 12 minimum_numeric_characters 0 minimum_lowercase_letters 0 minimum_uppercase_letters 0 minimum_special_characters 0 remember_how_many_passwords 3 exempt_user 'MyAdmin' action :set end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/macos_password_policy/macos_app_management Resource =============================== [All Desktop resources page](../index) --- Use the **macos_app_management** resource to configure nodes to use Munki to manage apps **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **macos_app_management** resource is: ``` macos_app_management 'name' do munki_client_download_url String munki_password String munki_repo_url String munki_user String action Symbol # defaults to :install if not specified end ``` where: * `macos_app_management` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `munki_client_download_url`, `munki_password`, `munki_repo_url`, and `munki_user` are the properties available to this resource. Actions ------- --- The **macos_app_management** resource has the following actions: `:install` Installs the client on the macOS node. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **macos_app_management** resource has the following properties: `munki_client_download_url` **Ruby Type:** String The URL where nodes will download the Munki client from `munki_password` **Ruby Type:** String The password associated with the munki_user account `munki_repo_url` **Ruby Type:** String The URL of the repository nodes will use to download apps, settings, etc `munki_user` **Ruby Type:** String A username used to connect to the munki_repo_url with Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **macos_app_management** resource in recipes: **Set up managed app management for clients**: ``` macos_app_management 'Configure Munki on the node' do munki_client_download_url 'https://github.com/munki/munki/releases/download/v5.0.0/munkitools-5.0.0.4034.pkg' munki_repo_url 'https://something.something.tld' munki_user 'munki' munki_password 'ILoveMunki' action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/macos_app_management/windows_admin_control Resource ================================ [All Desktop resources page](../index) --- Use the **windows_admin_control** resource to enforce Admin level access for system-wide changes. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_admin_control** resource is: ``` windows_admin_control 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `windows_admin_control` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. Actions ------- --- The **windows_admin_control** resource has the following actions: `:disable` `:enable` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- This resource does not have any properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_admin_control** resource in recipes: **Turns on UAC to enforce Admin access for changes**: ``` admin_control 'Require Admin rights to perform system-wide changes' do action :enable end ``` **Turns off UAC**: ``` admin_control 'Do Not Require Admin rights to perform system-wide changes' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_admin_control/macos_automatic_logout Resource ================================= [All Desktop resources page](../index) --- Use the **macos_automatic_logout** resource to set the system to automatically logout after a set time. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **macos_automatic_logout** resource is: ``` macos_automatic_logout 'name' do autologout_time Integer # default value: 3600 action Symbol # defaults to :enable if not specified end ``` where: * `macos_automatic_logout` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `autologout_time` is the property available to this resource. Actions ------- --- The **macos_automatic_logout** resource has the following actions: `:disable` `:enable` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **macos_automatic_logout** resource has the following properties: `autologout_time` **Ruby Type:** Integer | **Default Value:** `3600` The amount of time in seconds to elapse before logging the system out. Defaults to 1 hour Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **macos_automatic_logout** resource in recipes: **Setup Automatic Logouts**: ``` automatic_logout 'Automatically logout for inactivity' do autologout_time 900 action :enable end ``` **Disable Automatic Logouts**: ``` automatic_logout 'Automatically logout for inactivity' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/macos_automatic_logout/macos_desktop_screensaver Resource ==================================== [All Desktop resources page](../index) --- Use the **macos_desktop_screensaver** resource to configure secure screensaver settings on macOS systems. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **macos_desktop_screensaver** resource is: ``` macos_desktop_screensaver 'name' do delay_before_password_prompt Integer idle_time Integer # default value: 20 require_password true, false action Symbol # defaults to :set if not specified end ``` where: * `macos_desktop_screensaver` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `delay_before_password_prompt`, `idle_time`, and `require_password` are the properties available to this resource. Actions ------- --- The **macos_desktop_screensaver** resource has the following actions: `:disable` Turns off the screensaver. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Sets the properties and enables the screen saver. Properties ---------- --- The **macos_desktop_screensaver** resource has the following properties: `delay_before_password_prompt` **Ruby Type:** Integer Time in seconds for screensaver to be active before the system will prompt for password input New in Chef Client 2.0 `idle_time` **Ruby Type:** Integer | **Default Value:** `20` **Allowed Values:** `0, 1, 2, 5, 10, 20, 30, 60` Time in minutes before the the Screensaver comes on. Must be one of these values: 1, 2, 5, 10, 20, 30, 60 `require_password` **Ruby Type:** true, false Require a password when waking from the screensaver. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **macos_desktop_screensaver** resource in recipes: **Turn on the Screensaver**: ``` desktop_screensaver 'Sets up the screensaver to come on after 30 minutes of idle time and require a password' do idle_time 30 require_password true delay_before_password_prompt 5 action :set end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/macos_desktop_screensaver/macos_automatic_software_updates Resource ============================================ [All Desktop resources page](../index) --- Use the **macos_automatic_software_updates** resource to configure system and application updates on macOS systems. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **macos_automatic_software_updates** resource is: ``` macos_automatic_software_updates 'name' do check true, false download true, false install_app_store true, false install_critical true, false install_os true, false action Symbol # defaults to :set if not specified end ``` where: * `macos_automatic_software_updates` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `check`, `download`, `install_app_store`, `install_critical`, and `install_os` are the properties available to this resource. Actions ------- --- The **macos_automatic_software_updates** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Properties ---------- --- The **macos_automatic_software_updates** resource has the following properties: `check` **Ruby Type:** true, false Tell the OS to check for updates `download` **Ruby Type:** true, false Tell the OS to download updates `install_app_store` **Ruby Type:** true, false Set this to add app updates `install_critical` **Ruby Type:** true, false Set this to install critical updates `install_os` **Ruby Type:** true, false Set to update the OS Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **macos_automatic_software_updates** resource in recipes: **Setup automatic patch management**: ``` macos_automatic_software_updates 'Settings for OS and Patch updates' do check true download true install_os true install_app_store true install_critical true action :set end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/macos_automatic_software_updates/rescue_account Resource ======================== [All Desktop resources page](../index) --- Use the **rescue_account** resource to provide Administrators with a rescue account. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **rescue_account** resource is: ``` rescue_account 'name' do account_name String password String action Symbol # defaults to :create if not specified end ``` where: * `rescue_account` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `account_name` and `password` are the properties available to this resource. Actions ------- --- The **rescue_account** resource has the following actions: `:create` Creates the user specified in the property field. `:delete` Deletes the named user. `:disable` Turns off the account if it was enabled. `:enable` Turns the account on if previously disabled. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **rescue_account** resource has the following properties: `account_name` **Ruby Type:** String | `REQUIRED` Name of the user to be created as a rescue account `password` **Ruby Type:** String | `REQUIRED` Corresponding password for that user Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **rescue_account** resource in recipes: **Create a managed user account**: ``` rescue_account 'Configure an Admin level account for IT to use' do account_name 'MyAdmin' password '123Opscode!!' action :create end ``` **Delete a managed user account**: ``` rescue_account 'Delete an Admin level account for IT to use' do account_name 'MyAdmin' action :delete end ``` **Enable an existing managed user account**: ``` rescue_account 'Enable an Admin level account for IT to use' do account_name 'MyAdmin' action :enable end ``` **Disable an existing managed user account**: ``` rescue_account 'Disable an Admin level account' do account_name 'MyAdmin' action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/rescue_account/windows_choco_installer Resource ================================== [All Desktop resources page](../index) --- Use the **windows_choco_installer** resource to install the Chocolatey package manager on Windows clients. **New in Chef Infra Client 2.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_choco_installer** resource is: ``` windows_choco_installer 'name' do action Symbol # defaults to :install if not specified end ``` where: * `windows_choco_installer` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. Actions ------- --- The **windows_choco_installer** resource has the following actions: `:install` Install the Chocolatey package manager (default). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- This resource does not have any properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_choco_installer** resource in recipes: **Configure Chocolatey Package Manager**: ``` windows_choco_installer 'Install Chocolatey Package Manager' do action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_choco_installer/windows_automatic_logout Resource =================================== [All Desktop resources page](../index) --- Use the **windows_automatic_logout** resource to set the system to automatically logout after a set time. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_automatic_logout** resource is: ``` windows_automatic_logout 'name' do autologout_time Integer # default value: 3600 action Symbol # defaults to :enable if not specified end ``` where: * `windows_automatic_logout` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `autologout_time` is the property available to this resource. Actions ------- --- The **windows_automatic_logout** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Properties ---------- --- The **windows_automatic_logout** resource has the following properties: `autologout_time` **Ruby Type:** Integer | **Default Value:** `3600` The amount of time in seconds to elapse before logging the system out. Defaults to 3600s (1 hour) Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_automatic_logout** resource in recipes: **Set the node to auto-logout when not being used**: ``` automatic_logout 'Automatically logout for inactivity' do autologout_time 900 action :enable end ``` **Disable auto-logout**: ``` automatic_logout 'Disable automatic inactivity logout' do autologout_time 900 action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_automatic_logout/windows_app_management Resource ================================= [All Desktop resources page](../index) --- Use the **windows_app_management** resource to configure nodes to use Gorilla for application management. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_app_management** resource is: ``` windows_app_management 'name' do update_check_frequency String action Symbol # defaults to :enable if not specified end ``` where: * `windows_app_management` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `update_check_frequency` is the property available to this resource. Actions ------- --- The **windows_app_management** resource has the following actions: `:disable` Disables the Windows Scheduled Task. `:enable` Sets the property, installs Gorilla, configures the local install with the yaml file, and sets a Windows Scheduled Task to run at the interval set by `how_often_to_check_for_updates`. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_app_management** resource has the following properties: `update_check_frequency` **Ruby Type:** String **Allowed Values:** `"daily", "minute", "monthly", "none", "on_idle", "on_logon", "once", "onstart", "weekly"` How often should the Gorilla client check for updates. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_app_management** resource in recipes: **Configure managed application management**: ``` windows_app_management 'Use Gorilla to manage Apps' do update_check_frequency 'daily' action :enable end ``` **Disable managed application management**: ``` windows_app_management 'Do Not Use Gorilla to manage Apps' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_app_management/windows_desktop_winrm_settings Resource ========================================== [All Desktop resources page](../index) --- Use the **windows_desktop_winrm_settings** resource to setup and teardown WinRM settings on a node. Chef Infra Client does not require this for operation. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_desktop_winrm_settings** resource is: ``` windows_desktop_winrm_settings 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `windows_desktop_winrm_settings` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. Actions ------- --- The **windows_desktop_winrm_settings** resource has the following actions: `:disable` Turns off WinRM and disables the firewall policy. `:enable` Turns on WinRM and sets a firewall policy. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- This resource does not have any properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_desktop_winrm_settings** resource in recipes: **Turn WinRM On**: ``` windows_desktop_winrm_settings 'Settings to enable WinRM on a node for desktop-config' do action :enable end ``` **Turn WinRM Off**: ``` windows_desktop_winrm_settings 'Settings to disable WinRM on a node for desktop-config' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_desktop_winrm_settings/windows_defender_exclusion Resource ===================================== [All Desktop resources page](../index) --- Use the **windows_defender_exclusion** resource to exclude paths, processes, or file types from Windows Defender realtime protection scanning. **New in Chef Infra Client 1.1.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_defender_exclusion** resource is: ``` windows_defender_exclusion 'name' do extensions String, Array # default value: [] paths String, Array # default value: [] process_paths String, Array # default value: [] action Symbol # defaults to :add if not specified end ``` where: * `windows_defender_exclusion` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `extensions`, `paths`, and `process_paths` are the properties available to this resource. Actions ------- --- The **windows_defender_exclusion** resource has the following actions: `:add` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Properties ---------- --- The **windows_defender_exclusion** resource has the following properties: `extensions` **Ruby Type:** String, Array | **Default Value:** `[]` File extensions to exclude from scanning. `paths` **Ruby Type:** String, Array | **Default Value:** `[]` File or directory paths to exclude from scanning. `process_paths` **Ruby Type:** String, Array | **Default Value:** `[]` Paths to executables to exclude from scanning. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_defender_exclusion** resource in recipes: **Add excluded items to Windows Defender scans**: ``` windows_defender_exclusion 'Add to things to be excluded from scanning' do paths 'c:\foo\bar, d:\bar\baz' extensions 'png, foo, ppt, doc' process_paths 'c:\windows\system32' action :add end ``` **Remove excluded items from Windows Defender scans**: ``` windows_defender_exclusion 'Remove things from the list to be excluded' do process_paths 'c:\windows\system32' action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_defender_exclusion/windows_firewall Resource ========================== [All Desktop resources page](../index) --- Use the **windows_firewall** resource to enable or disable the Windows firewall service and all profiles. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_firewall** resource is: ``` windows_firewall 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `windows_firewall` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. Actions ------- --- The **windows_firewall** resource has the following actions: `:disable` Disable the Windows Firewall service `:enable` Enable the Windows Firewall service and all profiles `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- This resource does not have any properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_firewall** resource in recipes: **Set the Windows firewall**: ``` windows_firewall 'Enable the node firewall' do action :enable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_firewall/windows_desktop_screensaver Resource ====================================== [All Desktop resources page](../index) --- Use the **windows_desktop_screensaver** resource to configure secure screensaver settings on Windows systems. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_desktop_screensaver** resource is: ``` windows_desktop_screensaver 'name' do allow_lower_user_idle_time true, false # default value: false idle_time Integer # default value: 20 require_password true, false # default value: true screensaver_name String action Symbol # defaults to :enable if not specified end ``` where: * `windows_desktop_screensaver` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_lower_user_idle_time`, `idle_time`, `require_password`, and `screensaver_name` are the properties available to this resource. Actions ------- --- The **windows_desktop_screensaver** resource has the following actions: `:disable` Disable the desktop screen saver. `:enable` Enable the desktop screen saver. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_desktop_screensaver** resource has the following properties: `allow_lower_user_idle_time` **Ruby Type:** true, false | **Default Value:** `false` Allow users to set their screen saver idle time lower than the system requirements. `idle_time` **Ruby Type:** Integer | **Default Value:** `20` The amount of idle time in minutes before the screensaver comes on. `require_password` **Ruby Type:** true, false | **Default Value:** `true` Require a password when waking from the screensaver. `screensaver_name` **Ruby Type:** String The name of a specific or custom screensaver to enable. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_desktop_screensaver** resource in recipes: **Secure the desktop with a screensaver and password**: ``` desktop_screensaver 'Sets up a Screensaver to come on and require a password after xx minutes' do require_password true idle_time 20 allow_lower_user_idle_time false screensaver_name 'mystify.scr' action :enable end ``` **Disable requiring a screensaver with a password**: ``` desktop_screensaver 'Disable the screensaver' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_desktop_screensaver/windows_ie_esc Resource ========================= [All Desktop resources page](../index) --- Use the **windows_ie_esc** resource to adjust the Internet Explorer extensibility and security settings. **New in Chef Infra Client 2.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_ie_esc** resource is: ``` windows_ie_esc 'name' do scopes Array action Symbol # defaults to :enable if not specified end ``` where: * `windows_ie_esc` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `scopes` is the property available to this resource. Actions ------- --- The **windows_ie_esc** resource has the following actions: `:disable` Disable Internet Explorer extensibility and security settings for scoped users. `:enable` Enable Internet Explorer extensibility and security settings for scoped users (default). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_ie_esc** resource has the following properties: `scopes` **Ruby Type:** Array | `REQUIRED` Windows user scopes targeted by this security config Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_ie_esc** resource in recipes: **Turns off Internet Explorer ESC**: ``` windows_ie_esc 'Turn off Internet Explorer ESC for admin' do scopes [:admin] action :disable end ``` **Turns on Internet Explorer ESC to reduce risks from exposure to websites**: ``` windows_ie_esc 'Enforce Internet Explorer ESC for all user scopes' do scopes [:admin, :user] action :enable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_ie_esc/windows_update_settings Resource ================================== [All Desktop resources page](../index) --- Use the **windows_update_settings** resource to manage the various Windows Update patching options. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_update_settings** resource is: ``` windows_update_settings 'name' do add_to_target_wsus_group true, false # default value: false automatic_update_option Integer # default value: 4 automatically_install_minor_updates true, false # default value: false block_windows_update_website true, false # default value: false custom_detection_frequency Integer # default value: 22 disable_automatic_updates true, false # default value: false disable_os_upgrades true, false # default value: false elevate_non_admins true, false # default value: true enable_detection_frequency true, false # default value: false no_reboot_with_users_logged_on true, false # default value: true scheduled_install_day String # default value: "Everyday" scheduled_install_hour Integer target_wsus_group_name String update_other_ms_products true, false # default value: true use_custom_update_server true, false # default value: false wsus_server_url String wsus_status_server_url String action Symbol # defaults to :enable if not specified end ``` where: * `windows_update_settings` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `add_to_target_wsus_group`, `automatic_update_option`, `automatically_install_minor_updates`, `block_windows_update_website`, `custom_detection_frequency`, `disable_automatic_updates`, `disable_os_upgrades`, `elevate_non_admins`, `enable_detection_frequency`, `no_reboot_with_users_logged_on`, `scheduled_install_day`, `scheduled_install_hour`, `target_wsus_group_name`, `update_other_ms_products`, `use_custom_update_server`, `wsus_server_url`, and `wsus_status_server_url` are the properties available to this resource. Actions ------- --- The **windows_update_settings** resource has the following actions: `:enable` Overrides the default settings with these custom options. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_update_settings** resource has the following properties: `add_to_target_wsus_group` **Ruby Type:** true, false | **Default Value:** `false` If you have a WSUS Server and Target Groups, set this True `automatic_update_option` **Ruby Type:** Integer | **Default Value:** `4` An Integer value to tell nodes when and how to download updates. Default is 4 - Auto-download and schedule updates to install `automatically_install_minor_updates` **Ruby Type:** true, false | **Default Value:** `false` Automatically install minor updates. Default is False `block_windows_update_website` **Ruby Type:** true, false | **Default Value:** `false` Denies access to Windows Update to get updates `custom_detection_frequency` **Ruby Type:** Integer | **Default Value:** `22` If you decided to override the OS default detection frequency, specify your choice here. Valid choices are 0 - 22 `disable_automatic_updates` **Ruby Type:** true, false | **Default Value:** `false` Prevents automatic updates. Defaults to False to allow automatic updates `disable_os_upgrades` **Ruby Type:** true, false | **Default Value:** `false` True/False to disable OS upgrades. `elevate_non_admins` **Ruby Type:** true, false | **Default Value:** `true` This property allows normal user accounts to temporarily be elevated to install patches `enable_detection_frequency` **Ruby Type:** true, false | **Default Value:** `false` Used to override the OS default of how often to check for updates `no_reboot_with_users_logged_on` **Ruby Type:** true, false | **Default Value:** `true` Prevents the OS from rebooting while someone is on the console. Default is True `scheduled_install_day` **Ruby Type:** String | **Default Value:** `Everyday` **Allowed Values:** `"Everyday", "Friday", "Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday"` A day of the week to tell Windows when to install updates. Defaults to Everyday `scheduled_install_hour` **Ruby Type:** Integer If you chose a scheduled day to install, then choose an hour on that day for you installation `target_wsus_group_name` **Ruby Type:** String This is the name of the WSUS Target Group you want the node to be in `update_other_ms_products` **Ruby Type:** true, false | **Default Value:** `true` Allows for other Microsoft products to get updates too `use_custom_update_server` **Ruby Type:** true, false | **Default Value:** `false` Used to tell nodes to use a WSUS server, Defaults to False - Use Microsoft for updates `wsus_server_url` **Ruby Type:** String The URL of your WSUS server if you use one `wsus_status_server_url` **Ruby Type:** String URL for the WSUS Status server. It can be the same as the URL for the WSUS server itself Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_update_settings** resource in recipes: **Set Windows Update settings**: ``` windows_update_settings 'Settings to Configure Windows Nodes to automatically receive updates' do disable_os_upgrades false elevate_non_admins true add_to_target_wsus_group false block_windows_update_website false automatic_update_option 4 automatically_install_minor_updates false enable_detection_frequency false custom_detection_frequency 22 no_reboot_with_users_logged_on true disable_automatic_updates false scheduled_install_day 'Monday' scheduled_install_hour 20 update_other_ms_products false use_custom_update_server false action :enable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_update_settings/windows_disk_encryption Resource ================================== [All Desktop resources page](../index) --- Use the **windows_disk_encryption** resource to enable or disable BitLocker Drive Encryption on Windows systems. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_disk_encryption** resource is: ``` windows_disk_encryption 'name' do reboot_after_update true, false # default value: true action Symbol # defaults to :enable if not specified end ``` where: * `windows_disk_encryption` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `reboot_after_update` is the property available to this resource. Actions ------- --- The **windows_disk_encryption** resource has the following actions: `:disable` Turns off BitLocker. `:enable` Turns on BitLocker. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_disk_encryption** resource has the following properties: `reboot_after_update` **Ruby Type:** true, false | **Default Value:** `true` Control the reboot behavior after enabling BitLocker New in Chef Client 1.1 Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_disk_encryption** resource in recipes: **Enable BitLocker**: ``` disk_encryption 'Turns on BitLocker Drive Encryption' do action :enable reboot_after_update true end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_disk_encryption/windows_power_management Resource =================================== [All Desktop resources page](../index) --- Use the **windows_power_management** resource to set the power settings of a kiosk-style device when you need it always-on **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_power_management** resource is: ``` windows_power_management 'name' do disk_timeout Integer hibernate_timeout Integer monitor_timeout Integer power_level String # default value: "balanced" power_scheme_label String standby_timeout Integer action Symbol # defaults to :set if not specified end ``` where: * `windows_power_management` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `disk_timeout`, `hibernate_timeout`, `monitor_timeout`, `power_level`, `power_scheme_label`, and `standby_timeout` are the properties available to this resource. Actions ------- --- The **windows_power_management** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set the power scheme on a node to ‘balanced’ or ‘ultimate’. Properties ---------- --- The **windows_power_management** resource has the following properties: `disk_timeout` **Ruby Type:** Integer The amount of time in minutes to wait before turning off the HD `hibernate_timeout` **Ruby Type:** Integer The amount of time in minutes to wait before hibernating the system `monitor_timeout` **Ruby Type:** Integer The amount of time in minutes to wait before turning off the display `power_level` **Ruby Type:** String | **Default Value:** `balanced` There are 2 levels of power - balanced, and ultimate. `power_scheme_label` **Ruby Type:** String A label name to prefix your power scheme with. The code duplicates the existing power scheme to keep it distinct `standby_timeout` **Ruby Type:** Integer The amount of time in minutes to wait before putting the system into standby Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_power_management** resource in recipes: **Setup a Power Management Policy**: ``` windows_power_management 'Set the Device to a defined power level' do power_scheme_label 'Unrestricted' power_level 'ultimate' monitor_timeout 15 disk_timeout 0 standby_timeout 0 hibernate_timeout 0 action :set end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_power_management/windows_defender Resource ========================== [All Desktop resources page](../index) --- Use the **windows_defender** resource to enable or disable the Microsoft Windows Defender service. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_defender** resource is: ``` windows_defender 'name' do intrusion_protection_system true, false # default value: true lock_ui true, false # default value: false realtime_protection true, false # default value: true scan_archives true, false # default value: true scan_email true, false # default value: false scan_mapped_drives true, false # default value: true scan_network_files true, false # default value: false scan_removable_drives true, false # default value: false scan_scripts true, false # default value: false action Symbol # defaults to :enable if not specified end ``` where: * `windows_defender` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `intrusion_protection_system`, `lock_ui`, `realtime_protection`, `scan_archives`, `scan_email`, `scan_mapped_drives`, `scan_network_files`, `scan_removable_drives`, and `scan_scripts` are the properties available to this resource. Actions ------- --- The **windows_defender** resource has the following actions: `:disable` Disable Windows Defender. `:enable` Enable Windows Defender and configure settings. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_defender** resource has the following properties: `intrusion_protection_system` **Ruby Type:** true, false | **Default Value:** `true` Enable network protection against exploitation of known vulnerabilities. New in Chef Client 1.1 `lock_ui` **Ruby Type:** true, false | **Default Value:** `false` Lock the UI to prevent users from changing Windows Defender settings. New in Chef Client 1.1 `realtime_protection` **Ruby Type:** true, false | **Default Value:** `true` Enable realtime scanning of downloaded files and attachments. New in Chef Client 1.1 `scan_archives` **Ruby Type:** true, false | **Default Value:** `true` Scan file archives such as .zip or .gz archives. New in Chef Client 1.1 `scan_email` **Ruby Type:** true, false | **Default Value:** `false` Scan e-mails for malware. New in Chef Client 1.1 `scan_mapped_drives` **Ruby Type:** true, false | **Default Value:** `true` Scan files on mapped network drives. New in Chef Client 1.1 `scan_network_files` **Ruby Type:** true, false | **Default Value:** `false` Scan files on a network. New in Chef Client 1.1 `scan_removable_drives` **Ruby Type:** true, false | **Default Value:** `false` Scan content of removable drives. New in Chef Client 1.1 `scan_scripts` **Ruby Type:** true, false | **Default Value:** `false` Scan scripts in malware scans. New in Chef Client 1.1 Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_defender** resource in recipes: **Configure Windows Defender AV settings**: ``` windows_defender 'Configure Defender' do realtime_protection true intrusion_protection_system true lock_ui true scan_archives true scan_scripts true scan_email true scan_removable_drives true scan_network_files false scan_mapped_drives false action :enable end ``` **Disable Windows Defender AV**: ``` windows_defender 'Disable Defender' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_defender/windows_password_policy Resource ================================== [All Desktop resources page](../index) --- Use the **windows_password_policy** resource to setup password complexity, password length, etc. **New in Chef Infra Client 1.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_password_policy** resource is: ``` windows_password_policy 'name' do change_password_at_next_logon true, false # default value: false group_name_for_expired_passwords String # default value: "Users" group_name_for_password_never_expires String # default value: "Administrators" maximum_password_age Integer # default value: 365 minimum_password_length Integer # default value: 12 password_never_expires true, false require_complex_passwords true, false # default value: true action Symbol # defaults to :set if not specified end ``` where: * `windows_password_policy` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `change_password_at_next_logon`, `group_name_for_expired_passwords`, `group_name_for_password_never_expires`, `maximum_password_age`, `minimum_password_length`, `password_never_expires`, and `require_complex_passwords` are the properties available to this resource. Actions ------- --- The **windows_password_policy** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Sets the password policy using the properties. Properties ---------- --- The **windows_password_policy** resource has the following properties: `change_password_at_next_logon` **Ruby Type:** true, false | **Default Value:** `false` Force all users in a local user group to change passwords at next logon `group_name_for_expired_passwords` **Ruby Type:** String | **Default Value:** `Users` The group whose passwords were just to change at the next login `group_name_for_password_never_expires` **Ruby Type:** String | **Default Value:** `Administrators` The group to which the password_never_expires rule applies. Defaults to Admins `maximum_password_age` **Ruby Type:** Integer | **Default Value:** `365` The maximum age in days for a password before it must be changed, defaults to 365 `minimum_password_length` **Ruby Type:** Integer | **Default Value:** `12` Sets the minimum password length, defaults to 12 Characters `password_never_expires` **Ruby Type:** true, false True/False to never expire the passwords, set to True by default `require_complex_passwords` **Ruby Type:** true, false | **Default Value:** `true` A True/False option to require special characters, upper, lower, etc in the password Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_password_policy** resource in recipes: **Configure the local password policy**: ``` windows_password_policy 'Settings for password complexity, length and duration' do require_complex_passwords true minimum_password_length 12 maximum_password_age 365 action :set end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/windows_password_policy/About Chef Habitat ================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/_index.md) Chef Habitat centers application configuration, management, and behavior around the application itself, not the infrastructure that the app runs on. It provides automation that can programmatically and declaratively build, deploy, and manage your application and services, both stateful and stateless. You can deploy and run your Chef Habitat app on many different infrastructure environments including bare metal, VM, containers, and PaaS. Chef Habitat Builder -------------------- [Chef Habitat Builder](builder_overview/index) acts as the core of Chef’s Application Delivery Enterprise hub. You can run Chef Habitat Builder as a cloud-based service or on-premises. Chef Habitat Builder provides package storage, search, and an API for clients. The contents of your app are stored in the Chef Habitat Builder SaaS, where the Chef Habitat community can view and access them. You can also use the on-prem version of Chef Habitat Builder, where you can store and maintain your apps locally. Plans ----- A [plan](plan_writing/index) is the file where you define how you will build, deploy, and manage your app. A plan file is named `plan.sh` for Linux systems or `plan.ps1` for Windows, and your app can have plan files for both Linux and Windows operating systems. You can find your plan file in the `habitat` directory, which you install at the root of your app with `hab plan init`. Supervisor ---------- A Supervisor is a process manager that runs the app packages that you defined in your plan. A Supervisor has two primary responsibilities: 1. A Supervisor is a process manager and is responsible for running your app’s services. It starts, stops, updates, and monitors the services according to your plan. 2. Supervisors can talk to each other. You can connect Supervisors together into a network and instruct them to send information to each other and take actions based on that information. Services -------- A [service](about_services/index) is your Chef Habitat package that is run and managed by a Supervisor. Services can be joined together into a [service group](service_groups/index), which is a collection of services with the same package and topology type that are connected together across a Supervisor network. Installing Chef Habitat ----------------------- The Chef Habitat CLI can be [installed](install_habitat/index) on Linux, Mac, and Windows. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/Configure the Chef Habitat CLI ============================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/hab_setup.md) Once Chef Habitat has been installed, the `hab` CLI makes it easy to get your workstation configured by guiding through the setup process. To set up your workstation, run `hab cli setup` and follow the instructions. ![screenshot of hab cli setup output in CLI] Setup asks you to create a new origin and a set of origin keys. Optionally, you can also provide a Chef Habitat personal access token to upload packages to the public depot and share them with the Chef Habitat community. See the [access token documentation](../builder_profile/index#create-a-personal-access-token) for details on generating and using your access token. > For more information about using Chef Habitat Builder, see the section on [Using Builder](../builder_overview/index). You will also be asked if you want to register Supervisor control gateway secret (see [Remote Command-and-Control of Supervisors](../sup_remote_control/index) for further details). You can change your settings at any time by re-running the `hab cli setup` command. ![screenshot of completed hab cli setup in CLI] That’s it. You’re all set up and ready to use Chef Habitat to build and run packages! © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/hab_setup/All Desktop Resources ===================== macos_admin_control resource ------------------------------ [macos_admin_control resource page](macos_admin_control/index) --- Use the **macos_admin_control** resource to require Admin level privileges to make system-wide changes **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **macos_admin_control** resource is: ``` macos_admin_control 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `macos_admin_control` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. ### Actions --- The **macos_admin_control** resource has the following actions: `:disable` `:enable` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- This resource does not have any properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macos_admin_control** resource in recipes: **Set Admin control to require Admin access**: ``` admin_control 'Require Admin rights to perform system-wide changes' do action :enable end ``` **Do not require Admin access for System-Wide changes**: ``` admin_control 'Require Admin rights to perform system-wide changes' do action :disable end ``` macos_app_management resource ------------------------------- [macos_app_management resource page](macos_app_management/index) --- Use the **macos_app_management** resource to configure nodes to use Munki to manage apps **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **macos_app_management** resource is: ``` macos_app_management 'name' do munki_client_download_url String munki_password String munki_repo_url String munki_user String action Symbol # defaults to :install if not specified end ``` where: * `macos_app_management` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `munki_client_download_url`, `munki_password`, `munki_repo_url`, and `munki_user` are the properties available to this resource. ### Actions --- The **macos_app_management** resource has the following actions: `:install` Installs the client on the macOS node. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **macos_app_management** resource has the following properties: `munki_client_download_url` **Ruby Type:** String The URL where nodes will download the Munki client from `munki_password` **Ruby Type:** String The password associated with the munki_user account `munki_repo_url` **Ruby Type:** String The URL of the repository nodes will use to download apps, settings, etc `munki_user` **Ruby Type:** String A username used to connect to the munki_repo_url with ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macos_app_management** resource in recipes: **Set up managed app management for clients**: ``` macos_app_management 'Configure Munki on the node' do munki_client_download_url 'https://github.com/munki/munki/releases/download/v5.0.0/munkitools-5.0.0.4034.pkg' munki_repo_url 'https://something.something.tld' munki_user 'munki' munki_password 'ILoveMunki' action :install end ``` macos_automatic_logout resource --------------------------------- [macos_automatic_logout resource page](macos_automatic_logout/index) --- Use the **macos_automatic_logout** resource to set the system to automatically logout after a set time. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **macos_automatic_logout** resource is: ``` macos_automatic_logout 'name' do autologout_time Integer # default value: 3600 action Symbol # defaults to :enable if not specified end ``` where: * `macos_automatic_logout` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `autologout_time` is the property available to this resource. ### Actions --- The **macos_automatic_logout** resource has the following actions: `:disable` `:enable` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **macos_automatic_logout** resource has the following properties: `autologout_time` **Ruby Type:** Integer | **Default Value:** `3600` The amount of time in seconds to elapse before logging the system out. Defaults to 1 hour ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macos_automatic_logout** resource in recipes: **Setup Automatic Logouts**: ``` automatic_logout 'Automatically logout for inactivity' do autologout_time 900 action :enable end ``` **Disable Automatic Logouts**: ``` automatic_logout 'Automatically logout for inactivity' do action :disable end ``` macos_automatic_software_updates resource -------------------------------------------- [macos_automatic_software_updates resource page](macos_automatic_software_updates/index) --- Use the **macos_automatic_software_updates** resource to configure system and application updates on macOS systems. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **macos_automatic_software_updates** resource is: ``` macos_automatic_software_updates 'name' do check true, false download true, false install_app_store true, false install_critical true, false install_os true, false action Symbol # defaults to :set if not specified end ``` where: * `macos_automatic_software_updates` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `check`, `download`, `install_app_store`, `install_critical`, and `install_os` are the properties available to this resource. ### Actions --- The **macos_automatic_software_updates** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` ### Properties --- The **macos_automatic_software_updates** resource has the following properties: `check` **Ruby Type:** true, false Tell the OS to check for updates `download` **Ruby Type:** true, false Tell the OS to download updates `install_app_store` **Ruby Type:** true, false Set this to add app updates `install_critical` **Ruby Type:** true, false Set this to install critical updates `install_os` **Ruby Type:** true, false Set to update the OS ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macos_automatic_software_updates** resource in recipes: **Setup automatic patch management**: ``` macos_automatic_software_updates 'Settings for OS and Patch updates' do check true download true install_os true install_app_store true install_critical true action :set end ``` macos_desktop_screensaver resource ------------------------------------ [macos_desktop_screensaver resource page](macos_desktop_screensaver/index) --- Use the **macos_desktop_screensaver** resource to configure secure screensaver settings on macOS systems. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **macos_desktop_screensaver** resource is: ``` macos_desktop_screensaver 'name' do delay_before_password_prompt Integer idle_time Integer # default value: 20 require_password true, false action Symbol # defaults to :set if not specified end ``` where: * `macos_desktop_screensaver` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `delay_before_password_prompt`, `idle_time`, and `require_password` are the properties available to this resource. ### Actions --- The **macos_desktop_screensaver** resource has the following actions: `:disable` Turns off the screensaver. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Sets the properties and enables the screen saver. ### Properties --- The **macos_desktop_screensaver** resource has the following properties: `delay_before_password_prompt` **Ruby Type:** Integer Time in seconds for screensaver to be active before the system will prompt for password input New in Chef Client 2.0 `idle_time` **Ruby Type:** Integer | **Default Value:** `20` **Allowed Values:** `0, 1, 2, 5, 10, 20, 30, 60` Time in minutes before the the Screensaver comes on. Must be one of these values: 1, 2, 5, 10, 20, 30, 60 `require_password` **Ruby Type:** true, false Require a password when waking from the screensaver. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macos_desktop_screensaver** resource in recipes: **Turn on the Screensaver**: ``` desktop_screensaver 'Sets up the screensaver to come on after 30 minutes of idle time and require a password' do idle_time 30 require_password true delay_before_password_prompt 5 action :set end ``` macos_disk_encryption resource -------------------------------- [macos_disk_encryption resource page](macos_disk_encryption/index) --- Use the **macos_disk_encryption** resource to enforce FileVault encryption on macOS systems. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **macos_disk_encryption** resource is: ``` macos_disk_encryption 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `macos_disk_encryption` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. ### Actions --- The **macos_disk_encryption** resource has the following actions: `:enable` Turns on FileVault. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- This resource does not have any properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. macos_firewall resource ------------------------ [macos_firewall resource page](macos_firewall/index) --- Use the **macos_firewall** resource to enable the firewall on macOS systems. ### Syntax --- The full syntax for all of the properties that are available to the **macos_firewall** resource is: ``` macos_firewall 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `macos_firewall` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. ### Actions --- The **macos_firewall** resource has the following actions: `:disable` `:enable` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- This resource does not have any properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macos_firewall** resource in recipes: **Turn on the macOS Firewall**: ``` macos_firewall 'Enable Firewall Protection' do action :enable end ``` **Turn off the macOS Firewall**: ``` macos_firewall 'Disable Firewall Protection' do action :disable end ``` macos_password_policy resource -------------------------------- [macos_password_policy resource page](macos_password_policy/index) --- Use the **macos_password_policy** resource to set password complexity, password length, etc on macOS systems. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **macos_password_policy** resource is: ``` macos_password_policy 'name' do exempt_user String lockout_time Integer max_failed_logins Integer maximum_password_age Integer # default value: 365 minimum_lowercase_letters Integer # default value: 0 minimum_numeric_characters Integer # default value: 0 minimum_password_length Integer # default value: 12 minimum_special_characters Integer # default value: 0 minimum_uppercase_letters Integer # default value: 0 remember_how_many_passwords Integer # default value: 3 action Symbol # defaults to :set if not specified end ``` where: * `macos_password_policy` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `exempt_user`, `lockout_time`, `max_failed_logins`, `maximum_password_age`, `minimum_lowercase_letters`, `minimum_numeric_characters`, `minimum_password_length`, `minimum_special_characters`, `minimum_uppercase_letters`, and `remember_how_many_passwords` are the properties available to this resource. ### Actions --- The **macos_password_policy** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` This action sets the password policy as defined in its properties. ### Properties --- The **macos_password_policy** resource has the following properties: `exempt_user` **Ruby Type:** String A user to whom the password policy is not applied `lockout_time` **Ruby Type:** Integer The amount of time your account is locked out after you exceed max failed logins `max_failed_logins` **Ruby Type:** Integer The maximum number of failed logins before you are locked out `maximum_password_age` **Ruby Type:** Integer | **Default Value:** `365` The maximum age in days for a password before it must be changed, defaults to 365 `minimum_lowercase_letters` **Ruby Type:** Integer | **Default Value:** `0` The minimum number of lower case letters that must be in a password `minimum_numeric_characters` **Ruby Type:** Integer | **Default Value:** `0` The minimum number of numbers that must be in a password `minimum_password_length` **Ruby Type:** Integer | **Default Value:** `12` The minimum length a password must be `minimum_special_characters` **Ruby Type:** Integer | **Default Value:** `0` The minimum number of special characters that must be in a password. Eg. *&^% `minimum_uppercase_letters` **Ruby Type:** Integer | **Default Value:** `0` The minimum number of upper case letters that must be in a password `remember_how_many_passwords` **Ruby Type:** Integer | **Default Value:** `3` The number of previous passwords to remember to prevent users for keeping stale passwords ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macos_password_policy** resource in recipes: **Set the local password policy**: ``` macos_password_policy 'Setup appropriate password complexity and rules' do max_failed_logins 5 lockout_time 2 maximum_password_age 365 minimum_password_length 12 minimum_numeric_characters 0 minimum_lowercase_letters 0 minimum_uppercase_letters 0 minimum_special_characters 0 remember_how_many_passwords 3 exempt_user 'MyAdmin' action :set end ``` macos_power_management resource --------------------------------- [macos_power_management resource page](macos_power_management/index) --- Use the **macos_power_management** resource to set the power settings of a kiosk-style device when you need it always-on **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **macos_power_management** resource is: ``` macos_power_management 'name' do computer_sleep_time String # default value: "never" disk_sleep_time String # default value: "never" display_sleep_time String # default value: "never" action Symbol # defaults to :set if not specified end ``` where: * `macos_power_management` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `computer_sleep_time`, `disk_sleep_time`, and `display_sleep_time` are the properties available to this resource. ### Actions --- The **macos_power_management** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` This action sets the policy as defined in its properties. ### Properties --- The **macos_power_management** resource has the following properties: `computer_sleep_time` **Ruby Type:** String | **Default Value:** `never` A time value between 1-60 minutes or “never” to use to set the computer to sleep after. Defaults to never `disk_sleep_time` **Ruby Type:** String | **Default Value:** `never` A time value between 1-60 minutes or “never” to use to set the hard disk to sleep after. Defaults to never `display_sleep_time` **Ruby Type:** String | **Default Value:** `never` A time value between 1-60 minutes or “never” to use to set the display to sleep after. Defaults to never ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macos_power_management** resource in recipes: **Configure Power Management settings**: ``` macos_power_management 'Set the Device to a defined power level' do computer_sleep_time 'never' display_sleep_time 'never' disk_sleep_time 'never' action :set end ``` rescue_account resource ------------------------ [rescue_account resource page](rescue_account/index) --- Use the **rescue_account** resource to provide Administrators with a rescue account. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **rescue_account** resource is: ``` rescue_account 'name' do account_name String password String action Symbol # defaults to :create if not specified end ``` where: * `rescue_account` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `account_name` and `password` are the properties available to this resource. ### Actions --- The **rescue_account** resource has the following actions: `:create` Creates the user specified in the property field. `:delete` Deletes the named user. `:disable` Turns off the account if it was enabled. `:enable` Turns the account on if previously disabled. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **rescue_account** resource has the following properties: `account_name` **Ruby Type:** String | `REQUIRED` Name of the user to be created as a rescue account `password` **Ruby Type:** String | `REQUIRED` Corresponding password for that user ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **rescue_account** resource in recipes: **Create a managed user account**: ``` rescue_account 'Configure an Admin level account for IT to use' do account_name 'MyAdmin' password '123Opscode!!' action :create end ``` **Delete a managed user account**: ``` rescue_account 'Delete an Admin level account for IT to use' do account_name 'MyAdmin' action :delete end ``` **Enable an existing managed user account**: ``` rescue_account 'Enable an Admin level account for IT to use' do account_name 'MyAdmin' action :enable end ``` **Disable an existing managed user account**: ``` rescue_account 'Disable an Admin level account' do account_name 'MyAdmin' action :disable end ``` windows_admin_control resource -------------------------------- [windows_admin_control resource page](windows_admin_control/index) --- Use the **windows_admin_control** resource to enforce Admin level access for system-wide changes. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_admin_control** resource is: ``` windows_admin_control 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `windows_admin_control` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. ### Actions --- The **windows_admin_control** resource has the following actions: `:disable` `:enable` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- This resource does not have any properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_admin_control** resource in recipes: **Turns on UAC to enforce Admin access for changes**: ``` admin_control 'Require Admin rights to perform system-wide changes' do action :enable end ``` **Turns off UAC**: ``` admin_control 'Do Not Require Admin rights to perform system-wide changes' do action :disable end ``` windows_app_management resource --------------------------------- [windows_app_management resource page](windows_app_management/index) --- Use the **windows_app_management** resource to configure nodes to use Gorilla for application management. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_app_management** resource is: ``` windows_app_management 'name' do update_check_frequency String action Symbol # defaults to :enable if not specified end ``` where: * `windows_app_management` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `update_check_frequency` is the property available to this resource. ### Actions --- The **windows_app_management** resource has the following actions: `:disable` Disables the Windows Scheduled Task. `:enable` Sets the property, installs Gorilla, configures the local install with the yaml file, and sets a Windows Scheduled Task to run at the interval set by `how_often_to_check_for_updates`. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_app_management** resource has the following properties: `update_check_frequency` **Ruby Type:** String **Allowed Values:** `"daily", "minute", "monthly", "none", "on_idle", "on_logon", "once", "onstart", "weekly"` How often should the Gorilla client check for updates. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_app_management** resource in recipes: **Configure managed application management**: ``` windows_app_management 'Use Gorilla to manage Apps' do update_check_frequency 'daily' action :enable end ``` **Disable managed application management**: ``` windows_app_management 'Do Not Use Gorilla to manage Apps' do action :disable end ``` windows_automatic_logout resource ----------------------------------- [windows_automatic_logout resource page](windows_automatic_logout/index) --- Use the **windows_automatic_logout** resource to set the system to automatically logout after a set time. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_automatic_logout** resource is: ``` windows_automatic_logout 'name' do autologout_time Integer # default value: 3600 action Symbol # defaults to :enable if not specified end ``` where: * `windows_automatic_logout` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `autologout_time` is the property available to this resource. ### Actions --- The **windows_automatic_logout** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` ### Properties --- The **windows_automatic_logout** resource has the following properties: `autologout_time` **Ruby Type:** Integer | **Default Value:** `3600` The amount of time in seconds to elapse before logging the system out. Defaults to 3600s (1 hour) ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_automatic_logout** resource in recipes: **Set the node to auto-logout when not being used**: ``` automatic_logout 'Automatically logout for inactivity' do autologout_time 900 action :enable end ``` **Disable auto-logout**: ``` automatic_logout 'Disable automatic inactivity logout' do autologout_time 900 action :disable end ``` windows_choco_installer resource ---------------------------------- [windows_choco_installer resource page](windows_choco_installer/index) --- Use the **windows_choco_installer** resource to install the Chocolatey package manager on Windows clients. **New in Chef Infra Client 2.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_choco_installer** resource is: ``` windows_choco_installer 'name' do action Symbol # defaults to :install if not specified end ``` where: * `windows_choco_installer` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. ### Actions --- The **windows_choco_installer** resource has the following actions: `:install` Install the Chocolatey package manager (default). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- This resource does not have any properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_choco_installer** resource in recipes: **Configure Chocolatey Package Manager**: ``` windows_choco_installer 'Install Chocolatey Package Manager' do action :install end ``` windows_defender resource -------------------------- [windows_defender resource page](windows_defender/index) --- Use the **windows_defender** resource to enable or disable the Microsoft Windows Defender service. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_defender** resource is: ``` windows_defender 'name' do intrusion_protection_system true, false # default value: true lock_ui true, false # default value: false realtime_protection true, false # default value: true scan_archives true, false # default value: true scan_email true, false # default value: false scan_mapped_drives true, false # default value: true scan_network_files true, false # default value: false scan_removable_drives true, false # default value: false scan_scripts true, false # default value: false action Symbol # defaults to :enable if not specified end ``` where: * `windows_defender` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `intrusion_protection_system`, `lock_ui`, `realtime_protection`, `scan_archives`, `scan_email`, `scan_mapped_drives`, `scan_network_files`, `scan_removable_drives`, and `scan_scripts` are the properties available to this resource. ### Actions --- The **windows_defender** resource has the following actions: `:disable` Disable Windows Defender. `:enable` Enable Windows Defender and configure settings. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_defender** resource has the following properties: `intrusion_protection_system` **Ruby Type:** true, false | **Default Value:** `true` Enable network protection against exploitation of known vulnerabilities. New in Chef Client 1.1 `lock_ui` **Ruby Type:** true, false | **Default Value:** `false` Lock the UI to prevent users from changing Windows Defender settings. New in Chef Client 1.1 `realtime_protection` **Ruby Type:** true, false | **Default Value:** `true` Enable realtime scanning of downloaded files and attachments. New in Chef Client 1.1 `scan_archives` **Ruby Type:** true, false | **Default Value:** `true` Scan file archives such as .zip or .gz archives. New in Chef Client 1.1 `scan_email` **Ruby Type:** true, false | **Default Value:** `false` Scan e-mails for malware. New in Chef Client 1.1 `scan_mapped_drives` **Ruby Type:** true, false | **Default Value:** `true` Scan files on mapped network drives. New in Chef Client 1.1 `scan_network_files` **Ruby Type:** true, false | **Default Value:** `false` Scan files on a network. New in Chef Client 1.1 `scan_removable_drives` **Ruby Type:** true, false | **Default Value:** `false` Scan content of removable drives. New in Chef Client 1.1 `scan_scripts` **Ruby Type:** true, false | **Default Value:** `false` Scan scripts in malware scans. New in Chef Client 1.1 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_defender** resource in recipes: **Configure Windows Defender AV settings**: ``` windows_defender 'Configure Defender' do realtime_protection true intrusion_protection_system true lock_ui true scan_archives true scan_scripts true scan_email true scan_removable_drives true scan_network_files false scan_mapped_drives false action :enable end ``` **Disable Windows Defender AV**: ``` windows_defender 'Disable Defender' do action :disable end ``` windows_defender_exclusion resource ------------------------------------- [windows_defender_exclusion resource page](windows_defender_exclusion/index) --- Use the **windows_defender_exclusion** resource to exclude paths, processes, or file types from Windows Defender realtime protection scanning. **New in Chef Infra Client 1.1.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_defender_exclusion** resource is: ``` windows_defender_exclusion 'name' do extensions String, Array # default value: [] paths String, Array # default value: [] process_paths String, Array # default value: [] action Symbol # defaults to :add if not specified end ``` where: * `windows_defender_exclusion` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `extensions`, `paths`, and `process_paths` are the properties available to this resource. ### Actions --- The **windows_defender_exclusion** resource has the following actions: `:add` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` ### Properties --- The **windows_defender_exclusion** resource has the following properties: `extensions` **Ruby Type:** String, Array | **Default Value:** `[]` File extensions to exclude from scanning. `paths` **Ruby Type:** String, Array | **Default Value:** `[]` File or directory paths to exclude from scanning. `process_paths` **Ruby Type:** String, Array | **Default Value:** `[]` Paths to executables to exclude from scanning. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_defender_exclusion** resource in recipes: **Add excluded items to Windows Defender scans**: ``` windows_defender_exclusion 'Add to things to be excluded from scanning' do paths 'c:\foo\bar, d:\bar\baz' extensions 'png, foo, ppt, doc' process_paths 'c:\windows\system32' action :add end ``` **Remove excluded items from Windows Defender scans**: ``` windows_defender_exclusion 'Remove things from the list to be excluded' do process_paths 'c:\windows\system32' action :remove end ``` windows_desktop_screensaver resource -------------------------------------- [windows_desktop_screensaver resource page](windows_desktop_screensaver/index) --- Use the **windows_desktop_screensaver** resource to configure secure screensaver settings on Windows systems. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_desktop_screensaver** resource is: ``` windows_desktop_screensaver 'name' do allow_lower_user_idle_time true, false # default value: false idle_time Integer # default value: 20 require_password true, false # default value: true screensaver_name String action Symbol # defaults to :enable if not specified end ``` where: * `windows_desktop_screensaver` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_lower_user_idle_time`, `idle_time`, `require_password`, and `screensaver_name` are the properties available to this resource. ### Actions --- The **windows_desktop_screensaver** resource has the following actions: `:disable` Disable the desktop screen saver. `:enable` Enable the desktop screen saver. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_desktop_screensaver** resource has the following properties: `allow_lower_user_idle_time` **Ruby Type:** true, false | **Default Value:** `false` Allow users to set their screen saver idle time lower than the system requirements. `idle_time` **Ruby Type:** Integer | **Default Value:** `20` The amount of idle time in minutes before the screensaver comes on. `require_password` **Ruby Type:** true, false | **Default Value:** `true` Require a password when waking from the screensaver. `screensaver_name` **Ruby Type:** String The name of a specific or custom screensaver to enable. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_desktop_screensaver** resource in recipes: **Secure the desktop with a screensaver and password**: ``` desktop_screensaver 'Sets up a Screensaver to come on and require a password after xx minutes' do require_password true idle_time 20 allow_lower_user_idle_time false screensaver_name 'mystify.scr' action :enable end ``` **Disable requiring a screensaver with a password**: ``` desktop_screensaver 'Disable the screensaver' do action :disable end ``` windows_desktop_winrm_settings resource ------------------------------------------ [windows_desktop_winrm_settings resource page](windows_desktop_winrm_settings/index) --- Use the **windows_desktop_winrm_settings** resource to setup and teardown WinRM settings on a node. Chef Infra Client does not require this for operation. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_desktop_winrm_settings** resource is: ``` windows_desktop_winrm_settings 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `windows_desktop_winrm_settings` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. ### Actions --- The **windows_desktop_winrm_settings** resource has the following actions: `:disable` Turns off WinRM and disables the firewall policy. `:enable` Turns on WinRM and sets a firewall policy. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- This resource does not have any properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_desktop_winrm_settings** resource in recipes: **Turn WinRM On**: ``` windows_desktop_winrm_settings 'Settings to enable WinRM on a node for desktop-config' do action :enable end ``` **Turn WinRM Off**: ``` windows_desktop_winrm_settings 'Settings to disable WinRM on a node for desktop-config' do action :disable end ``` windows_disk_encryption resource ---------------------------------- [windows_disk_encryption resource page](windows_disk_encryption/index) --- Use the **windows_disk_encryption** resource to enable or disable BitLocker Drive Encryption on Windows systems. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_disk_encryption** resource is: ``` windows_disk_encryption 'name' do reboot_after_update true, false # default value: true action Symbol # defaults to :enable if not specified end ``` where: * `windows_disk_encryption` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `reboot_after_update` is the property available to this resource. ### Actions --- The **windows_disk_encryption** resource has the following actions: `:disable` Turns off BitLocker. `:enable` Turns on BitLocker. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_disk_encryption** resource has the following properties: `reboot_after_update` **Ruby Type:** true, false | **Default Value:** `true` Control the reboot behavior after enabling BitLocker New in Chef Client 1.1 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_disk_encryption** resource in recipes: **Enable BitLocker**: ``` disk_encryption 'Turns on BitLocker Drive Encryption' do action :enable reboot_after_update true end ``` windows_firewall resource -------------------------- [windows_firewall resource page](windows_firewall/index) --- Use the **windows_firewall** resource to enable or disable the Windows firewall service and all profiles. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_firewall** resource is: ``` windows_firewall 'name' do action Symbol # defaults to :enable if not specified end ``` where: * `windows_firewall` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. ### Actions --- The **windows_firewall** resource has the following actions: `:disable` Disable the Windows Firewall service `:enable` Enable the Windows Firewall service and all profiles `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- This resource does not have any properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_firewall** resource in recipes: **Set the Windows firewall**: ``` windows_firewall 'Enable the node firewall' do action :enable end ``` windows_ie_esc resource ------------------------- [windows_ie_esc resource page](windows_ie_esc/index) --- Use the **windows_ie_esc** resource to adjust the Internet Explorer extensibility and security settings. **New in Chef Infra Client 2.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_ie_esc** resource is: ``` windows_ie_esc 'name' do scopes Array action Symbol # defaults to :enable if not specified end ``` where: * `windows_ie_esc` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `scopes` is the property available to this resource. ### Actions --- The **windows_ie_esc** resource has the following actions: `:disable` Disable Internet Explorer extensibility and security settings for scoped users. `:enable` Enable Internet Explorer extensibility and security settings for scoped users (default). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_ie_esc** resource has the following properties: `scopes` **Ruby Type:** Array | `REQUIRED` Windows user scopes targeted by this security config ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_ie_esc** resource in recipes: **Turns off Internet Explorer ESC**: ``` windows_ie_esc 'Turn off Internet Explorer ESC for admin' do scopes [:admin] action :disable end ``` **Turns on Internet Explorer ESC to reduce risks from exposure to websites**: ``` windows_ie_esc 'Enforce Internet Explorer ESC for all user scopes' do scopes [:admin, :user] action :enable end ``` windows_password_policy resource ---------------------------------- [windows_password_policy resource page](windows_password_policy/index) --- Use the **windows_password_policy** resource to setup password complexity, password length, etc. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_password_policy** resource is: ``` windows_password_policy 'name' do change_password_at_next_logon true, false # default value: false group_name_for_expired_passwords String # default value: "Users" group_name_for_password_never_expires String # default value: "Administrators" maximum_password_age Integer # default value: 365 minimum_password_length Integer # default value: 12 password_never_expires true, false require_complex_passwords true, false # default value: true action Symbol # defaults to :set if not specified end ``` where: * `windows_password_policy` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `change_password_at_next_logon`, `group_name_for_expired_passwords`, `group_name_for_password_never_expires`, `maximum_password_age`, `minimum_password_length`, `password_never_expires`, and `require_complex_passwords` are the properties available to this resource. ### Actions --- The **windows_password_policy** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Sets the password policy using the properties. ### Properties --- The **windows_password_policy** resource has the following properties: `change_password_at_next_logon` **Ruby Type:** true, false | **Default Value:** `false` Force all users in a local user group to change passwords at next logon `group_name_for_expired_passwords` **Ruby Type:** String | **Default Value:** `Users` The group whose passwords were just to change at the next login `group_name_for_password_never_expires` **Ruby Type:** String | **Default Value:** `Administrators` The group to which the password_never_expires rule applies. Defaults to Admins `maximum_password_age` **Ruby Type:** Integer | **Default Value:** `365` The maximum age in days for a password before it must be changed, defaults to 365 `minimum_password_length` **Ruby Type:** Integer | **Default Value:** `12` Sets the minimum password length, defaults to 12 Characters `password_never_expires` **Ruby Type:** true, false True/False to never expire the passwords, set to True by default `require_complex_passwords` **Ruby Type:** true, false | **Default Value:** `true` A True/False option to require special characters, upper, lower, etc in the password ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_password_policy** resource in recipes: **Configure the local password policy**: ``` windows_password_policy 'Settings for password complexity, length and duration' do require_complex_passwords true minimum_password_length 12 maximum_password_age 365 action :set end ``` windows_power_management resource ----------------------------------- [windows_power_management resource page](windows_power_management/index) --- Use the **windows_power_management** resource to set the power settings of a kiosk-style device when you need it always-on **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_power_management** resource is: ``` windows_power_management 'name' do disk_timeout Integer hibernate_timeout Integer monitor_timeout Integer power_level String # default value: "balanced" power_scheme_label String standby_timeout Integer action Symbol # defaults to :set if not specified end ``` where: * `windows_power_management` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `disk_timeout`, `hibernate_timeout`, `monitor_timeout`, `power_level`, `power_scheme_label`, and `standby_timeout` are the properties available to this resource. ### Actions --- The **windows_power_management** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set the power scheme on a node to ‘balanced’ or ‘ultimate’. ### Properties --- The **windows_power_management** resource has the following properties: `disk_timeout` **Ruby Type:** Integer The amount of time in minutes to wait before turning off the HD `hibernate_timeout` **Ruby Type:** Integer The amount of time in minutes to wait before hibernating the system `monitor_timeout` **Ruby Type:** Integer The amount of time in minutes to wait before turning off the display `power_level` **Ruby Type:** String | **Default Value:** `balanced` There are 2 levels of power - balanced, and ultimate. `power_scheme_label` **Ruby Type:** String A label name to prefix your power scheme with. The code duplicates the existing power scheme to keep it distinct `standby_timeout` **Ruby Type:** Integer The amount of time in minutes to wait before putting the system into standby ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_power_management** resource in recipes: **Setup a Power Management Policy**: ``` windows_power_management 'Set the Device to a defined power level' do power_scheme_label 'Unrestricted' power_level 'ultimate' monitor_timeout 15 disk_timeout 0 standby_timeout 0 hibernate_timeout 0 action :set end ``` windows_update_settings resource ---------------------------------- [windows_update_settings resource page](windows_update_settings/index) --- Use the **windows_update_settings** resource to manage the various Windows Update patching options. **New in Chef Infra Client 1.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_update_settings** resource is: ``` windows_update_settings 'name' do add_to_target_wsus_group true, false # default value: false automatic_update_option Integer # default value: 4 automatically_install_minor_updates true, false # default value: false block_windows_update_website true, false # default value: false custom_detection_frequency Integer # default value: 22 disable_automatic_updates true, false # default value: false disable_os_upgrades true, false # default value: false elevate_non_admins true, false # default value: true enable_detection_frequency true, false # default value: false no_reboot_with_users_logged_on true, false # default value: true scheduled_install_day String # default value: "Everyday" scheduled_install_hour Integer target_wsus_group_name String update_other_ms_products true, false # default value: true use_custom_update_server true, false # default value: false wsus_server_url String wsus_status_server_url String action Symbol # defaults to :enable if not specified end ``` where: * `windows_update_settings` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `add_to_target_wsus_group`, `automatic_update_option`, `automatically_install_minor_updates`, `block_windows_update_website`, `custom_detection_frequency`, `disable_automatic_updates`, `disable_os_upgrades`, `elevate_non_admins`, `enable_detection_frequency`, `no_reboot_with_users_logged_on`, `scheduled_install_day`, `scheduled_install_hour`, `target_wsus_group_name`, `update_other_ms_products`, `use_custom_update_server`, `wsus_server_url`, and `wsus_status_server_url` are the properties available to this resource. ### Actions --- The **windows_update_settings** resource has the following actions: `:enable` Overrides the default settings with these custom options. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_update_settings** resource has the following properties: `add_to_target_wsus_group` **Ruby Type:** true, false | **Default Value:** `false` If you have a WSUS Server and Target Groups, set this True `automatic_update_option` **Ruby Type:** Integer | **Default Value:** `4` An Integer value to tell nodes when and how to download updates. Default is 4 - Auto-download and schedule updates to install `automatically_install_minor_updates` **Ruby Type:** true, false | **Default Value:** `false` Automatically install minor updates. Default is False `block_windows_update_website` **Ruby Type:** true, false | **Default Value:** `false` Denies access to Windows Update to get updates `custom_detection_frequency` **Ruby Type:** Integer | **Default Value:** `22` If you decided to override the OS default detection frequency, specify your choice here. Valid choices are 0 - 22 `disable_automatic_updates` **Ruby Type:** true, false | **Default Value:** `false` Prevents automatic updates. Defaults to False to allow automatic updates `disable_os_upgrades` **Ruby Type:** true, false | **Default Value:** `false` True/False to disable OS upgrades. `elevate_non_admins` **Ruby Type:** true, false | **Default Value:** `true` This property allows normal user accounts to temporarily be elevated to install patches `enable_detection_frequency` **Ruby Type:** true, false | **Default Value:** `false` Used to override the OS default of how often to check for updates `no_reboot_with_users_logged_on` **Ruby Type:** true, false | **Default Value:** `true` Prevents the OS from rebooting while someone is on the console. Default is True `scheduled_install_day` **Ruby Type:** String | **Default Value:** `Everyday` **Allowed Values:** `"Everyday", "Friday", "Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday"` A day of the week to tell Windows when to install updates. Defaults to Everyday `scheduled_install_hour` **Ruby Type:** Integer If you chose a scheduled day to install, then choose an hour on that day for you installation `target_wsus_group_name` **Ruby Type:** String This is the name of the WSUS Target Group you want the node to be in `update_other_ms_products` **Ruby Type:** true, false | **Default Value:** `true` Allows for other Microsoft products to get updates too `use_custom_update_server` **Ruby Type:** true, false | **Default Value:** `false` Used to tell nodes to use a WSUS server, Defaults to False - Use Microsoft for updates `wsus_server_url` **Ruby Type:** String The URL of your WSUS server if you use one `wsus_status_server_url` **Ruby Type:** String URL for the WSUS Status server. It can be the same as the URL for the WSUS server itself ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_update_settings** resource in recipes: **Set Windows Update settings**: ``` windows_update_settings 'Settings to Configure Windows Nodes to automatically receive updates' do disable_os_upgrades false elevate_non_admins true add_to_target_wsus_group false block_windows_update_website false automatic_update_option 4 automatically_install_minor_updates false enable_detection_frequency false custom_detection_frequency 22 no_reboot_with_users_logged_on true disable_automatic_updates false scheduled_install_day 'Monday' scheduled_install_hour 20 update_other_ms_products false use_custom_update_server false action :enable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/desktop/resources/Download and Install FAQ ======================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/install_faq.md) This section tracks some questions that are frequently encountered when downloading and installing the `hab` binary. **Q: Can I just download a GitHub release of Chef Habitat?** A: While we do cut releases in GitHub as part of our release process those archives are going to be a `.tar` point in time of our source code. As the `hab` cli is written in Rust, if you follow this approach you’ll need to compile the source for your platform. **Q: Compile for my platform? Does that mean there aren’t any OS native packages of `hab`?** A: We publish compiled packages for OSX, Linux, and Windows. `hab` has a requirement of either a Linux kernel >= 2.6.32, OSX >= 10.9, or 64-bit Windows 10 Pro, Enterprise, or Education editions (1511 November update, build 10586 or later) with Hyper-V enabled. **Q: What if I need an old version of `hab`?** A: We’ve got you covered! The script we provide for doing curl-bash installations will allow you to specify a `-v` flag to pull down a specific version of Chef Habitat, eg: ``` curl https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh \ | sudo bash -s -- -v 0.56.0 ``` **Q: Oh! A curl bash I (love||hate) those.** A: Indeed they are divisive, we know, that’s why we provide a few different ways for you to download. If you’d like to take a look at the script before running it, you can find it in [the core Chef Habitat repo](https://github.com/habitat-sh/habitat/blob/main/components/hab/install.sh). If you’re staunchly in the anti-curl-bash camp, you can get the latest packages from the [download links](../install_habitat/index) listed previously. **Q: How do I install `hab` across my server fleet?** A: For the most part, we leave that up to you. You could just use the aforementioned curl-bash with your provisioner of choice. If your app was dockerized with Chef Habitat then you won’t even need to ask this question, because you’ll have everything you need inside your container. We are working on first class Mesosphere DC/OS, and Cloud Foundry integrations - which you can keep up to date on in our [Apache Mesos and DC/OS documentation](../mesos_dcos/index) and [blog](https://blog.chef.io/). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/install_faq/Download and Install the Chef Habitat CLI Tool ============================================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/install_habitat.md) Below you’ll find installation instructions for each platform and their requirements. The Chef Habitat CLI is currently supported on Linux, Mac, and Windows. From building packages to running services, everything in Chef Habitat is done through the hab command-line interface (CLI) tool. To get started using Chef Habitat, you need to download and install the hab CLI tool that corresponds to your workstation OS. hr Chef Habitat for Linux ---------------------- Chef Habitat for Linux requires a 64-bit processor with kernel 2.6.32 or later. On Linux, exporting your Chef Habitat artifact to a Docker image requires the Docker Engine supplied by Docker. Packages from distribution-specific or otherwise alternative providers are currently not supported. Once you have downloaded the package, extract the hab binary with tar to `/usr/local/bin` or add its location to your `PATH` (e.g. `tar -xvzf hab.tgz -C /usr/local/bin --strip-components 1`). [Download Chef Habitat for Linux](https://downloads.chef.io/products/habitat) ### Install Chef Habitat from the Command Line Alternatively, you can install Chef Habitat via the command line by downloading and running the installation script: ``` curl https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh | sudo bash ``` ### Install Chef Habitat for Linux Kernel 2.x from the Command Line Please note that support for Linux Kernel 2.x is limited. Not all core plans are available for Kernel 2.x, nor are there plans to backport all of the existing core plans to Kernel 2.x. Kernel 2.x is legacy technology by definition, and its use should be viewed as a stop-gap to provide interim solutions for old systems, as they are upgraded to more recent versions of the Linux kernel. ``` curl https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh | sudo bash -s -- -t x86_64-linux-kernel2 ``` Chef Habitat for Mac -------------------- Requires 64-bit processor running 10.9 or later Once you have downloaded the `hab` CLI, unzip it onto your machine. Unzipping to `/usr/local/bin` should place it on your `PATH`. In order to use the Chef Habitat Studio, you’ll also need to install Docker for Mac. [Download Chef Habitat for Mac](https://downloads.chef.io/products/habitat) [Download Docker for Mac](https://store.docker.com/editions/community/docker-ce-desktop-mac) ### Install Chef Habitat Using Homebrew Chef Habitat can also be installed with Homebrew, by running the following commands: ``` brew tap habitat-sh/habitat brew install hab ``` Chef Habitat for Windows ------------------------ Minimum Windows version supported: Windows Server 2012 or Windows 8 64-bit Chocolatey is a package manager for Windows. You can use it to easily install, configure, upgrade, and even uninstall Windows software packages. We recommend using Chocolatey for installing Chef Habitat. Install Chef Habitat with Chocolatey, by running the following command: ``` choco install habitat ``` ### Install Chef Habitat using a Powershell install script Alternatively, you can install Chef Habitat by downloading and running the installation script: ``` Set-ExecutionPolicy Bypass -Scope Process -Force iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.ps1')) ``` ### Installing Habitat for Windows using the dowloaded Chef Habitat package. Downloaded the `hab` CLI, unzip it onto your machine. We suggest unzipping to `C:\habitat`, so that the full path to Chef Habitat is similar to `C:\habitat\hab-0.79.1-20190410221450-x86_64-windows`. If you’ve downloaded a more recent version of Chef Habitat, you’ll see a different set of numbers following `hab-`. Replace the package name used in these examples with the filename you see on your computer. Next, add that folder to your `PATH` variable so your computer will know where to find it. Here’s how to do that with Powershell: ``` $env:PATH += ";C:\habitat\hab-0.79.1-20190410221450-x86_64-windows\" ``` To use a Docker Chef Habitat Studio as an isolated environment, you’ll also need to install Docker for Windows. Docker for Windows requires 64-bit Windows 10 Pro, Enterprise, or Education editions (1607 Anniversary Update, Build 14393 or later) with Hyper-V enabled [Download Chef Habitat for Windows](https://downloads.chef.io/products/habitat) [Download Docker for Windows](https://store.docker.com/editions/community/docker-ce-desktop-windows) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/install_habitat/About Chef Habitat Builder ========================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/builder_overview.md) Chef Habitat Builder acts as the core of Chef’s Application Delivery Enterprise hub. Chef Habitat Builder was first launched as a cloud service and as the repository of all available plan templates built by Chef and the supporting community. Due to the fact that the application source code is stored alongside the build package, many users expressed a preference for storing packages and running Chef Habitat Builder on-prem. As a result, Chef Habitat Builder can be consumed either as a cloud based or on-premises solution. Plan files are stored in the Chef Habitat Builder SaaS, where they can be viewed and accessed by the Chef Habitat community and then shared with the on-premises version of the builder where they can then be copied and maintained locally. Chef Habitat Builder Enterprise Components Include: --------------------------------------------------- * **Application Manifest** - The Application Manifest provides a single application directory, which includes—at a minimum—the compiled app artifact, dynamic links to all direct and transitive runtime dependencies ,and instructions to install and run the app. * **Deployment Channel Management** - Pre-canned deployment channels that can be used as-is or a user can custom design their own channels. Apps that are deployed through Chef Habitat can subscribe to a channel and be auto-upgraded whenever the app is promoted. * **Origin Management** - Save your application delivery content in uniquely named spaces that you can control. * **Content Library** - Hundreds of pre-built [application delivery packages](https://bldr.habitat.sh/#/pkgs/core) and core dependencies, which makes it easy to get started with Chef Habitat. * **Custom Data and Reporting APIs** - Rich APIs enable the capability to export to CSV or JSON. * **DevOps Integration APIs** - Provides an API so that clients can find and download the necessary packages to run their applications. Additional APIs also enable easy integration with other popular DevOps tools, including Jenkins, Terraform, Artifactory, Hashi Vault, and many others. * **Role Based User Access** - Improves your organizations operational safety by letting you assign specific levels of access to each origin member. For more information on how the SaaS and On-Prem versions of Chef Habitat Builder work together, read the blog - [Chef Habitat Builder On-Prem Enhancements that Extend Support to Airgap Environments and Simplify Set-Up](https://blog.chef.io/chef-habitat-product-announcement-builder-on-prem-enhancements-that-extend-support-to-airgap-environments-and-simplify-set-up/) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/builder_overview/Create an Account ================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/builder_account.md) Whether you are looking to leverage the SaaS or on-prem version of Chef Habitat Builder, you will need to create an account on the SaaS version of Chef Habitat Builder. After you have then downloaded the version, you will then sync the two accounts. Prerequisites ------------- You need to set a few things up before you can get started with Chef Habitat Builder: * Download and install the [Chef Habitat CLI](../install_habitat/index) * A [GitHub account](https://github.com/join) Sign-in and Authorize Chef Habitat Builder ------------------------------------------ Chef Habitat Builder automatically creates your account the first time you sign in using the GitHub authentication process. You’ll also need to authorize the Chef Habitat Builder application in Github. Head over to the Chef Habitat Builder sign-in page at <https://bldr.habitat.sh/#/sign-in> to get started. 1. To sign in with an existing GitHub account, select **Sign in with GitHub** 2. If you need to set up a GitHub account, select the **Sign up here** link ![Chef Habitat sign in with Github] Signing in with your GitHub account and authorizing the Chef Habitat Builder application the first time you sign in grants you access to the Chef Habitat Builder platform. Once you’ve completed signing in and authorizing Chef Habitat Builder, you’ll arrive at the ‘My Origins’ view. ![Authorize the Chef Habitat Application] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/builder_account/Builder Profile =============== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/builder_profile.md) Whether you are looking to leverage the SaaS or on-prem version of Chef Habitat Builder, you will need to create an account on the SaaS version of Chef Habitat Builder. After you have then downloaded the version, you will then sync the two accounts. This documentation covers everything from creating an account to setting up automated builds and exporting packages to a variety of container registries. Get an Account -------------- ### Prerequisites You need to set a few things up before you can get started with Chef Habitat Builder: * Download and install the [Chef Habitat CLI](../install_habitat/index) * A [GitHub account](https://github.com/join) ### Sign-in and Authorize Chef Habitat Builder Chef Habitat Builder automatically creates your account the first time you sign in using the GitHub authentication process. You’ll also need to authorize the Chef Habitat Builder application in Github. Head over to the Chef Habitat Builder sign-in page at <https://bldr.habitat.sh/#/sign-in> to get started. 1. To sign in with an existing GitHub account, select **Sign in with GitHub** 2. If you need to set up a GitHub account, select the **Sign up here** link ![Chef Habitat sign in with Github] Signing in with your GitHub account and authorizing the Chef Habitat Builder application the first time you sign in grants you access to the Chef Habitat Builder platform. Once you’ve completed signing in and authorizing Chef Habitat Builder, you’ll arrive at the ‘My Origins’ view. ![Authorize the Chef Habitat Application] Set up your Profile ------------------- Use the *Profile* tab to: * See the GitHub account used to sign in * Add an email to your profile * Create your personal access token Access your profile by selecting the **round icon at the top right corner** of any page. Select the **profiles** option from the drop-down menu to customize your profile and create your personal access token. ![Access your Chef Habitat Builder profile] ### Register an Email Address Adding an email address to your profile gives the Chef Habitat team permission to contact you directly about important information. If you use an email address associated with a GitHub account, it will also use your GitHub avatar. Save your changes by selecting **save**. ![Register your email address] ### Create a Personal Access Token Chef Habitat Builder uses an access token, called a *personal access token* or a *Habitat authentication token* (HAB_AUTH_TOKEN), to give you access to actions that you would like to take on Chef Habitat Builder. The *personal access token* is the first level of permissions that you need to for any interactions with Chef Habitat Builder, such as uploading packages or checking the status of build jobs. Create your personal access token at the bottom of the profile page (below the save button), by selecting **Generate Token**. ![Create your personal access token] Your generated access token will appear in the field. The access token is visible in the tab once, and navigating away from or reloading the page will cause it to vanish from the display. Copy your access token by selecting the icon on the right side of the field and set it as an environment variable before continuing. ![Copy your personal access token] #### Set the personal access token as a Windows Environment Variable You can use your personal access token as a [Windows environment variable](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_environment_variables?view=powershell-7) for a single session by passing it in the command line or save it in your user settings for use across sessions. Save your personal authorization token as a permanent environment variable in Windows using: ``` SETX HAB_AUTH_TOKEN <token> /m ``` Replacing with the contents of your generated personal access token. You can also save your personal access token as a permanent environment variable using the Windows user interface. In your Windows help bar, enter `environment` and select **Edit the system environment variables** from the list of suggestions. This opens the `System Properties` window on the `Advanced` tab. Select the `Environment Variables` button. ![Navigate to Windows Environment Variables] In the next window, select the `New` button in the top part. This opens a dialog box that lets you set individual user variables. ![Make new user variable] Create a permanent environment variable by entering `HAB_AUTH_TOKEN` as the variable name. Next, paste the authorization token that you copied after you generated a new token on your profile page as the variable value. After you select the `OK`, you will see the new token in the user variables field. ![Save your HAB_AUTH_TOKEN] To test that your new token works correctly, open the Command Prompt—which you can find by entering command in the Windows search box—and entering `echo %HAB_AUTH_TOKEN%`. You should see the value that you pasted into the environment variable. #### Set the personal access token as a macOS Environment Variable Set the `HAB_AUTH_TOKEN` in the CLI with: ``` export HAB_AUTH_TOKEN=<token``` Replacing `<token>` with the contents of your generated personal access token. To use your personal access token across sessions, set it as an environment variable in your interactive shell configuration file, such as your `.bashrc`. ``` export HAB_AUTH_TOKEN=<token``` Then initialize the path from the command line, by running: ``` source ~/.bashrc ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/builder_profile/Create an Origin ================ [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/origins.md) An origin is a space on Chef Habitat Builder where you can store, share, and build packages. It is a unique namespace within Chef Habitat Builder, and while you can delete or transfer an origin, you can’t rename an origin after it is created. One example of an origin is the “core” origin, which is the set of foundational packages managed and versioned by the core Chef Habitat maintainers. You can join existing origins by invitation and you can create your own origins. For more on invitations, see [origin membership and RBAC](../origin_rbac/index#origin-membership). ### Create an Origin ![Chef Habitat Builder without origins] To create an origin, select the **Create origin** button on the *My Origins* page which opens the *Create New Origin* form. (Chef Habitat Builder > My Origins ) ![Creating an origin] First, enter a unique name that you want to associate with your packages. Chef Habitat will only let you create an origin with a unique name. Some examples that you’ll see in Chef Habitat Builder are team names, user names, and abstract concepts. Next, choose a privacy setting to set as the default for new packages. You can override this setting when uploading individual packages from the CLI or by connecting a plan file that declares a package as private. The difference between public and private packages is: * Anyone can find and use public packages * Only users with origin membership can find and use private packages When you select **Save and Continue**, Chef Habitat Builder: 1. Creates your origin 2. Creates an [origin key pair](../origin_keys/index) 3. Redirects Chef Habitat Builder to the origin page ![Origin successfully created] #### Create an Origin with the Chef Habitat CLI Use the [hab origin](../habitat_cli/index#hab-origin) commands to manage your origins from the command line. Create an origin from the command line with the [hab origin create](../habitat_cli/index#hab-origin-create) command ``` hab origin create <origin``` The results of this command differ slightly from creating an origin on the Chef Habitat Builder site. The CLI command: 1. Creates an origin on the Chef Habitat Builder site 2. Does *not* generate an origin key pair For more information, see the [`hab origin create`](../habitat_cli/index#hab-origin-create) CLI documentation. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/origins/Origin Membership & RBAC ======================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/origin_rbac.md) Prerequisites: * [Download the Chef Habitat CLI](../install_habitat/index) * [Create a Chef Habitat Builder account](../builder_account/index) * [Generate a personal access token](../builder_profile/index#create-a-personal-access-token) * [Create an origin](../origins/index#create-origin) or accept an [invitation](#manage-origin-membership-with-hab-origin-invitations) to an existing origin * [Get origin keys](../origins/index#origin-keys) Role-Based Access Control (RBAC) for Chef Habitat Builder (SaaS and on-prem) ---------------------------------------------------------------------------- **New in: 1.6.140** Note RBAC improves operational safety by letting you enable specific levels of access to each user of an origin. With this upgrade, existing origins and their users are automatically converted to RBAC. The RBAC upgrade assigns the ‘Maintainer’ role to existing users with a generic ‘Member’ role. The differences between ‘Member’ and ‘Maintainer’ are detailed below. The origin owner role remains unchanged. RBAC membership is a token-based authentication process that works at the origin level. Your membership role defines the level of access that you have to the resources within an origin. When you first join or create an origin, Chef Habitat Builder identifies your personal access token and assigns a membership role to it for that origin. By default, when you join an origin you’re assigned the “read-only” role and when you create an an origin you’re assigned the ‘owner’ role. Role access is cumulative and progressive–each RBAC role includes all of the privileges of the previous roles and adds new access privileges. RBAC Origin Member Roles: Read-Only The default membership role for any user joining an origin. ‘Read-Only’ users can read an origin’s packages, channels, origin membership, jobs, keys, integrations, invitations, roles, settings but cannot add to, change, or delete anything in the origin, including uploading packages and inviting users to the origin. Member In addition to read-only access, an origin ‘Member’ can upload and build packages in the ‘unstable’ channel, but they cannot promote packages to other channels. Maintainer Origin ‘Members’ from Chef Habitat versions before 1.6.140 are now called ‘Maintainers’. This role has full read and write access to packages, channels, origin membership, jobs, integrations, invitations, settings. However, the ‘Maintainer’ role is more limited than the past role, in that ‘Maintainers’ only have read access to packages, channels, origin membership, jobs, keys, integrations, and settings. Origin ‘Maintainers’ can read origin membership roles and see and send invitations, but they cannot otherwise change origin membership–their own or anybody else’s. Finally, ‘Maintainers’ can neither read nor write origin secrets. Administrator In addition to ‘Maintainer’ access, the ‘Administrator’ role adds the privileges for writing origin keys and membership roles, as well as for reading and writing origin secrets. Administrators have full read and write access to packages, channels, origin membership, jobs, keys, integrations, invitations, roles, secrets, settings. Owner As in the past, the origin ‘Owner’ has full read and write access to the origin. Only Owners can delete the origin or transfer ownership to another member. Comparison of RBAC Membership Roles and Actions ----------------------------------------------- | Action | Read-Only | Member | Maintainer | Administrator | Owner | | --- | --- | --- | --- | --- | --- | | **Packages** | | | | | | | View packages | Y | Y | Y | Y | Y | | Upload packages to `unstable` | N | Y | Y | Y | Y | | Promote packages from `unstable` | N | N | Y | Y | Y | | **Build Jobs** | | | | | | | View build jobs | Y | Y | Y | Y | Y | | Trigger `unstable` build job | N | Y | Y | Y | Y | | **Channels** | | | | | | | View channels | Y | Y | Y | Y | Y | | Add/Update/Delete channels | N | N | Y | Y | Y | | **Origin Keys** | | | | | | | View keys | Y | Y | Y | Y | Y | | Add/Update/Delete keys | N | N | N | Y | Y | | **Origin Membership** | | | | | | | View origin membership | Y | Y | Y | Y | Y | | View invitations | Y | Y | Y | Y | Y | | Send Invitations | N | N | Y | Y | Y | | Revoke Invitations | N | N | Y | Y | Y | | **Member Roles** | | | | | | | View member roles | Y | Y | Y | Y | Y | | Update member roles | N | N | N | Y | Y | | **Origin Settings** | | | | | | | View settings | Y | Y | Y | Y | Y | | Add/Update/Delete settings | N | N | N | Y | Y | | **Origin Secrets** | | | | | | | View secrets | N | N | N | Y | Y | | Add/Update/Delete secrets | N | N | N | Y | Y | | **Cloud Integrations** | | | | | | | View integrations | Y | Y | Y | Y | Y | | Add/Update/Delete integrations | N | N | Y | Y | Y | | **Ownership** | | | | | | | Transfer Origin | N | N | N | N | Y | | Delete Origin | N | N | N | N | Y | Manage Origin Membership ------------------------ In tandem with the changes to the Builder membership roles, we’ve also updated the `hab` CLI to support RBAC. We’re working on adding role management to the Chef Habitat Builder site, but in the meantime, you’ll need to use the CLI for now. ![Manage origin membership] ### Manage origin membership with `hab origin invitations` Use the [hab origin invitations](../habitat_cli/index#hab-origin-invitations) command to invite users to join your origin and to respond to invitations. Origin Administrators and Owners can use this command to manage invitations. All Chef Habitat Builder users can accept, ignore, and see invitations for their accounts. View origin invitations: ``` hab origin invitations list ``` Accept origin invitations: ``` hab origin invitations accept <ORIGIN> <INVITATION_ID``` Ignore origin invitations: ``` hab origin invitations ignore <ORIGIN> <INVITATION_ID``` Send origin membership invitations: ``` hab origin invitations send <ORIGIN> <INVITEE_ACCOUNT``` Origin administrators and owners can see all pending origin membership invitations: ``` hab origin invitations pending <ORIGIN``` Origin administrators and owners can rescind an origin membership invitation: ``` hab origin invitations rescind <ORIGIN> <INVITATION_ID``` Origin owners can transfer origin ownership to another member: ``` hab origin transfer [OPTIONS] <ORIGIN> <NEW_OWNER_ACCOUNT``` ### Manage membership roles with `hab origin rbac` Use the [hab origin rbac](../habitat_cli/index#hab-origin-rbac) command to see and set role based access control (RBAC) from the command line. An origin `MEMBER_ACCOUNT` is the name used to sign in to Chef Habitat builder. You can find the list of user names on an origin’s *Members Tab*. (Builder > Origin > Members) The RBAC command syntax is: ``` hab origin rbac <SUBCOMMAND``` The syntax for the `show` subcommand is: ``` hab origin rbac show <MEMBER_ACCOUNT> --origin <ORIGIN``` See an origin member’s RBAC role: ``` hab origin rbac show bluewhale --origin two-tier-app ``` The syntax for the `set` subcommand is: ``` hab origin rbac set [FLAGS] [OPTIONS] <MEMBER_ACCOUNT> <ROLE> --origin <ORIGIN``` Set an origin membership RBAC role with: ``` hab origin rbac set bluewhale admin --origin two-tier-app ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/origin_rbac/Create an Origin on Builder =========================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/builder_origins.md) An origin is a place on Chef Habitat Builder where you can store, share, and build packages. It is a unique namespace within Chef Habitat Builder, and while you can delete or transfer an origin, you can’t rename an origin after it is created. One example of an origin is the “core” origin, which is the set of foundational packages managed and versioned by the core Chef Habitat maintainers. You can join existing origins by invitation and you can create your own origins. For more on invitations, see [origin membership and RBAC](#origin-membership). ### Create an Origin ![Chef Habitat Builder without origins] To create an origin, select the **Create origin** button on the *My Origins* page which opens the *Create New Origin* form. (Chef Habitat Builder > My Origins ) ![Creating an origin] First, enter a unique name that you want to associate with your packages. Chef Habitat will only let you create an origin with a unique name. Some examples that you’ll see in Chef Habitat Builder are team names, user names, and abstract concepts. Next, choose a privacy setting to set as the default for new packages. You can override this setting when uploading individual packages from the CLI or by connecting a plan file that declares a package as private. The difference between public and private packages is: * Anyone can find and use public packages * Only users with origin membership can find and use private packages When you select **Save and Continue**, Chef Habitat Builder: 1. Creates your origin 2. Creates an [origin key pair](#origin-keys) 3. Redirects Chef Habitat Builder to the origin page ![Origin successfully created] #### Create an Origin with the Chef Habitat CLI Use the [hab origin](../habitat_cli/index#hab-origin) commands to manage your origins from the command line. Create an origin from the command line with the [hab origin create](../habitat_cli/index#hab-origin-create/) command ``` hab origin create <origin``` The results of this command differ slightly from creating an origin on the Chef Habitat Builder site. The CLI command: 1. Creates an origin on the Chef Habitat Builder site 2. Does *not* generate an origin key pair For more information, see the [`hab origin create`](../habitat_cli/index#hab-origin-create) CLI documentation. Origin Membership & RBAC ------------------------ Prerequisites: * [Download the Chef Habitat CLI](../install_habitat/index) * [Create a Chef Habitat Builder account](#builder-account) * [Generate a personal access token](#builder-token) * [Create an origin](#create-origin) or accept an invitation to an existing origin * [Get origin keys](#origin-keys) ### Role-Based Access Control (RBAC) for Chef Habitat Builder (SaaS and on-prem) New in: 1.6.140 RBAC provides your organization with better operational safety by letting you assign specific levels of access to each user that belongs to an origin. With RBAC in place, existing standard origin ‘members’ from earlier versions are assigned the ‘Maintainer’ role. This role has similar permissions of the previous generic ‘member’ role, and the areas of difference are detailed below. The origin owner role remains unchanged. When you join or create an origin, Chef Habitat Builder identifies your personal access token and assigns it a membership role for that origin. Your membership role defines the level of access that you have to the resources in an origin. By default, you’re assigned the “read-only” role when you join an origin, and you’re assigned the ‘owner’ role when you create an origin. RBAC Origin Member Roles: * Read-Only: This user can read an origin’s packages, channels, origin membership, jobs, keys, integrations, invitations, roles, settings but cannot add to, change, or delete anything else in the origin, including uploading packages and inviting users to the origin. Read-Only is the default membership role for users joining the origin. * Member: In addition to read-only access, an origin ‘Member’ can upload and build packages in the ‘unstable’ channel, but they cannot promote packages to other channels. * Maintainer: Existing origin ‘members’ are now ‘Maintainers’. This role has full read and write access to packages, channels, origin membership, jobs, integrations, invitations, settings. However, the ‘Maintainer’ role is more limited than the past role, in that ‘Maintainers’ only have read access to packages, channels, origin membership, jobs, keys, integrations, and settings. Origin ‘Maintainers’ can read origin membership roles and see and send invitations, but they cannot otherwise change origin membership–their own or anybody else’s. Finally, ‘Maintainers’ can neither read nor write origin secrets. * Administrator: In addition to ‘Maintainer’ access, the ‘Administrator’ role adds the missing privileges for writing origin keys and membership roles, as well as for reading and writing origin secrets. Administrators have full read and write access to packages, channels, origin membership, jobs, keys, integrations, invitations, roles, secrets, settings. * Owner: As in the past, the origin ‘Owner’ has full read and write access to the origin. Only Owners can delete the origin or transfer ownership to another member. ### Comparison of RBAC Member Roles and Actions | Action | Read-Only | Member | Maintainer | Administrator | Owner | | --- | --- | --- | --- | --- | --- | | **Packages** | | | | | | | View packages | Y | Y | Y | Y | Y | | Upload packages to `unstable` | N | Y | Y | Y | Y | | Promote packages from `unstable` | N | N | Y | Y | Y | | **Build Jobs** | | | | | | | View build jobs | Y | Y | Y | Y | Y | | Trigger `unstable` build job | N | Y | Y | Y | Y | | **Channels** | | | | | | | View channels | Y | Y | Y | Y | Y | | Add/Update/Delete channels | N | N | Y | Y | Y | | **Origin Keys** | | | | | | | View keys | Y | Y | Y | Y | Y | | Add/Update/Delete keys | N | N | N | Y | Y | | **Origin Membership** | | | | | | | View origin membership | Y | Y | Y | Y | Y | | View invitations | Y | Y | Y | Y | Y | | Send Invitations | N | N | Y | Y | Y | | Revoke Invitations | N | N | Y | Y | Y | | **Member Roles** | | | | | | | View member roles | Y | Y | Y | Y | Y | | Update member roles | N | N | N | Y | Y | | **Origin Settings** | | | | | | | View settings | Y | Y | Y | Y | Y | | Add/Update/Delete settings | N | N | N | Y | Y | | **Origin Secrets** | | | | | | | View secrets | N | N | N | Y | Y | | Add/Update/Delete secrets | N | N | N | Y | Y | | **Cloud Integrations** | | | | | | | View integrations | Y | Y | Y | Y | Y | | Add/Update/Delete integrations | N | N | Y | Y | Y | | **Ownership** | | | | | | | Transfer Origin | N | N | N | N | Y | | Delete Origin | N | N | N | N | Y | ### Manage Origin Membership In tandem with the changes to the Builder membership roles, we’ve also updated the `hab` CLI to support RBAC. We’re working on adding role management to the Chef Habitat Builder site, but in the meantime, you’ll need to use the CLI for now. ![Manage origin membership] #### Manage origin membership with `hab origin invitations` Manage Chef Habitat Builder origin membership with the Chef Habitat CLI, using the [hab origin invitations](../habitat_cli/index#hab-origin-invitations) command. All Chef Habitat Builder users can accept, ignore, and see invitations for their accounts. View origin invitations: ``` hab origin invitations list ``` Accept origin invitations: ``` hab origin invitations accept <ORIGIN> <INVITATION_ID``` Ignore origin invitations: ``` hab origin invitations ignore <ORIGIN> <INVITATION_ID``` Send origin membership invitations: ``` hab origin invitations send <ORIGIN> <INVITEE_ACCOUNT``` Origin administrators and owners can see all pending origin membership invitations: ``` hab origin invitations pending <ORIGIN``` Origin administrators and owners can rescind an origin membership invitation: ``` hab origin invitations rescind <ORIGIN> <INVITATION_ID``` Origin owners can transfer origin ownership to another member: ``` hab origin transfer [OPTIONS] <ORIGIN> <NEW_OWNER_ACCOUNT``` #### Manage membership roles with `hab rbac` You can use role based access control (RBAC) from the command line. An origin `MEMBER_ACCOUNT` is the name used to sign in to Chef Habitat builder. You can find the list of user names on an origin’s *Members Tab*. (Builder > Origin > Members) The RBAC command syntax is: ``` hab origin rbac <SUBCOMMAND``` The syntax for the `show` subcommand is: ``` hab origin rbac show <MEMBER_ACCOUNT> --origin <ORIGIN``` See an origin member’s RBAC role: ``` hab origin rbac show bluewhale --origin two-tier-app ``` The syntax for the `set` subcommand is: ``` hab origin rbac set [FLAGS] [OPTIONS] <MEMBER_ACCOUNT> <ROLE> --origin <ORIGIN``` Set an origin membership RBAC role with: ``` hab origin rbac set bluewhale admin --origin two-tier-app ``` Origin Keys ----------- Prerequisites: * [Download the Chef Habitat CLI](../install_habitat/index) * [Create a Chef Habitat Builder account](#builder-account) * [Generate a personal access token](#builder-token) * [Create an origin with `hab origin create` or join an origin by invitation](#create-origin) When you create an origin, Chef Habitat Builder automatically generates *origin keys*. Origin key cryptography is asymmetric: it has a public origin key that you can distribute freely, and a private origin key that you should distribute only to users belonging to the origin. All Chef Habitat Builder users with access to the origin can view the origin public key revisions in the origin key tab (Builder > Origin > Keys) and download the origin public key, but only users with the origin ‘administrator’ or ‘owner’ roles can view or download the origin private key, or change the origin key pair. | Keys Actions | Read-Only | Member | Maintainer | Administrator | Owner | | --- | --- | --- | --- | --- | --- | | View keys | Y | Y | Y | Y | Y | | Add/Update/Delete keys | N | N | N | Y | Y | Chef Habitat uses origin keys: * When you build an artifact in your local environment, Chef Habitat signs the artifact with a public key * When you upload an artifact to Chef Habitat Builder or Builder on-prem, Chef Habitat verifies that the artifact was signed with its public key * When you install an artifact on a Chef Habitat Supervisor, Chef Habitat uses the public origin key to authorize the artifact’s installation; Chef Habitat only installs artifacts for which it has the public origin key * When you download an artifact to your local environment, Chef Habitat uses the public origin key to verify the artifact’s integrity before it starts the installation Chef Habitat Builder origin key names follow the format: ``` <origin>-<datetime>.pub (public key) <origin>-<datetime>.sig.key (private key, also called a "signing key") ``` For example, in: ``` testorigin-20190416223046.pub testorigin-20190416223046.sig.key ``` * “testorigin” is the origin’s name * “20190416223046” is the date and time of the key’s creation, which was 2019-04-16 22:30:46. * `.pub` is the file extension for the public key * `.sig.key` is the file extension for the private key, which is also called a “signing key” ### The Keys Tab When you create an origin, Chef Habitat Builder automatically generates an origin key pair and saves both keys. To view your origin keys on Chef Habitat Builder, navigate to your origin and select the **Keys** tab. (Builder > Origins > Keys) You will always be able to view and download origin public keys, but you will only see the private keys for origins in which you are an “administrator” or “owner”. ![Viewing your origin keys] #### Download Origin Keys Download your private or public origin key by selecting the **download** icon from the right end of the key details, under the *Actions* heading. ![Detail of the download icon] #### Upload Origin Keys You can upload origin keys that you generate on the command line to Chef Habitat Builder by selecting either the **Upload a private key** or **Upload a public key** icon, and copy your key into the form that appears. ![Example form content for uploading an origin key in Builder] ### Managing Origin Keys with the CLI Run Chef Habitat CLI commands from your local environment or from within the Chef Habitat Studio. See the CLI documentation for more information on the [`hab origin key`](../habitat_cli/index#hab-origin-key) commands. #### Find Your Local Origin Keys Chef Habitat stores your public and private origin keys at `~/.hab/cache/keys` on Linux systems, `C:\hab\cache\keys` on Windows, and at `/hab/cache/keys` inside of the Chef Habitat Studio environment. ##### To find your origin keys in your local environment: On Windows: ``` Get-ChildItem C:\hab\cache\keys ``` On Linux or macOS: ``` ls -la ~/.hab/cache/keys ``` ##### To find your existing origin keys from inside of the Chef Habitat Studio: On Windows: ``` Get-ChildItem C:\hab\cache\keys ``` On Linux or macOS: ``` ls -la /hab/cache/keys ``` #### Generate Origin Keys with the CLI When you create an origin through the site, Chef Habitat Builder automatically generates an origin key pair. The Chef Habitat CLI creates origin key pairs through two different commands, for two different uses: * Use [`hab setup`](../install_habitat/index) to generate your first origin key pair as part of setting up the `hab` CLI * Use the `hab origin key generate <ORIGIN>` command to create an key pair for an origin created with the `hab origin create` command Create origin keys with the `hab` command: ``` hab origin key generate <ORIGIN``` #### Download Origin Keys with the CLI To get your public origin key using the command line, use: ``` hab origin key download <ORIGIN``` #### Upload Origin Keys with the CLI Creating an origin with the `hab origin create` command registers the origin on Chef Habitat Builder without creating an origin key pair. The `hab origin key generate` command creates the key pair and saves them in your local environment, but it does not upload either origin key to Chef Habitat Builder. * Only “administrators” and “owners” can upload new keys to an origin. * Builder requires the public origin key to upload artifacts for that origin, so you’ll need to upload it. * Builder requires the private origin key to enable new artifact builds from packages with plans linked to that origin. Upload origin keys with the `hab` command: ``` hab origin key upload <ORIGIN``` Upload the origin private key: ``` hab origin key upload --secret <ORIGIN``` Upload both origin keys at the same time: ``` hab origin key upload --secfile <PATH_TO_PRIVATE_KEY> --pubfile <PATH_TO_PUBLIC_KEY``` #### Import Origin Keys with the CLI Use `hab origin key import` to read the key from a standard input stream into Chef Habitat Builder: ``` hab origin key import <enter or paste key> hab origin key import <PATH_TO_KEY> curl <URL_THAT_RETURNS_KEY> | hab origin key import ``` ##### Troubleshoot Origin Key Import On a macOS, you may encounter an upload failure. To remediate this failure: * Check that your `HAB_AUTH_TOKEN` environment variable is properly set and initialized * Add your `SSL_CERT_FILE` to the environment variables in your interactive shell configuration file, such as your `.bashrc`. ``` export SSL_CERT_FILE=/usr/local/etc/openssl/cert.pem ``` Initialize the setting from the command line with: ``` source ~/.bashrc ``` Origin Settings --------------- The *Origin Settings* tab contains: * Default Package Settings * Origin Secrets Everyone with origin membership can see the *Settings* tab, but only origin administrators and owners can add, update, or delete settings content. | Settings Actions | Read-Only | Member | Maintainer | Administrator | Owner | | --- | --- | --- | --- | --- | --- | | View settings | Y | Y | Y | Y | Y | | Add/Update/Delete settings | N | N | N | Y | Y | | **Origin Secrets Actions** | | | | | | | View secrets | N | N | Y | Y | Y | | Add/Update/Delete secrets | N | N | N | Y | Y | ![The administrator or owner’s view of the origin settings tab with a public default package setting and a saved origin secret] ### Default Package Settings The *Default Package Settings* define the visibility of build artifacts (.hart files). Everyone with origin membership can view the origin settings, but only origin administrators and owners can add, update, or delete settings. * Public packages are visible in search results and can be used by every Chef Habitat Builder user * Private artifacts do not appear in search results and are available only to users with origin membership Change the default setting for the origin by switching from **Public Packages** to **Private Packages**. The default setting required for each origin and users with more than one origin can set some as public and others as private. Packages can have different default visibility settings than their origin’s. Change the default visibility setting in for individual packages in that package’s setting tab (Builder > Origin > Package > Settings). ### Origin Secrets Everyone with origin membership can view origin secrets, but only origin administrators and owners can add, update, or delete settings. *Origin Secrets* are located at the bottom of the *Settings* tab (Builder > Origin > Settings > Origin Secrets) and they let you encrypt and store secrets as environment variables. Origin secrets are useful for plans that require access to protected resources at build time, such as private source-code repositories and cloud storage providers. Origin secrets are retained by the origin and are available for any of that origin’s packages. The origin secrets in your local environment are encrypted with an origin encryption key. Only Chef Habitat Builder can read encrypted origin secrets. #### Manage Origin Secrets with the Chef Habitat CLI You can view the list of origin secrets and delete them in Chef Habitat Builder. However, the primary way of interacting with origin secrets is with the Chef Habitat CLI. ##### List Secrets To list all of the secrets in an origin, use: ``` hab origin secret list --origin <ORIGIN``` ##### Set Origin Secrets as Environment Variables Add your origin secrets as environment variables in your local environment: ``` export HAB_ORIGIN=<ORIGIN> export HAB_AUTH_TOKEN=<TOKEN> hab origin secret list ``` ##### Save an Origin Secret To save an origin secret give the secret a name and the key value: ``` hab origin secret upload AWS_ACCESS_KEY_ID <your-key-id> hab origin secret upload AWS_SECRET_ACCESS_KEY <your-secret-access-key``` The output should similar to: ``` $ hab origin secret upload AWS_ACCESS_KEY_ID 1234567890EXAMPLE ↓ Downloading latest public encryption key 79 B / 79 B | [========================================] 100.00 % 120.23 KB/s ☑ Cached habicat-20200123456789.pub ☛ Encrypting value for key AWS_ACCESS_KEY_ID. ✓ Encrypted AWS_ACCESS_KEY_ID=[REDACTED]. ↑ Uploading secret for key AWS_ACCESS_KEY_ID. ✓ Uploaded secret for AWS_ACCESS_KEY_ID. ``` ##### Delete an Origin Secret To delete an origin secret from an origin with the CLI ``` hab origin secret delete AWS_ACCESS_KEY_ID hab origin secret delete AWS_SECRET_ACCESS_KEY ``` See [Using Origin Secrets in Plans](../plan_writing/index#buildtime-workflow) for guidance on using origin secrets. See the [`hab origin secret`](../habitat_cli/index#hab-origin-secret) CLI documentation for more information on these commands. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/builder_origins/Origin Keys =========== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/origin_keys.md) Prerequisites: * [Get Chef Habitat](../install_habitat/index) * [Create a Chef Habitat Builder account](../builder_account/index#builder-account) * [Generate a personal access token](../builder_profile/index#create-a-personal-access-token) * [Create an origin](../origins/index) or join an origin by [invitation](../origin_rbac/index#manage-origin-membership-with-hab-origin-invitations) When you create an origin, Chef Habitat Builder automatically generates *origin keys*. Origin key cryptography is asymmetric: it has a public origin key that you can distribute freely, and a private origin key (also called a “signing key”) that you should distribute only to users of the origin. All Chef Habitat Builder users with access to the origin can view the public origin key revisions in the origin key tab (Builder > Origin > Keys) and download the public origin key, but only users with the origin ‘administrator’ or ‘owner’ roles can view or download the private origin key, or change the origin key pair. | Keys Actions | Read-Only | Member | Maintainer | Administrator | Owner | | --- | --- | --- | --- | --- | --- | | View keys | Y | Y | Y | Y | Y | | Add/Update/Delete keys | N | N | N | Y | Y | Chef Habitat uses origin keys: * When you build an artifact in your local environment, Chef Habitat signs the artifact with the private origin key * When you upload an artifact to Chef Habitat Builder or Builder on-prem, Chef Habitat uses the public origin key to verify that the artifact was signed with the private origin key * When you install any package onto a Chef Habitat Supervisor, Chef Habitat uses the public origin key to verify the package’s integrity before it starts the installation * When you download an artifact to your local Chef Habitat Studio, Chef Habitat uses the public origin key to verify the artifact’s integrity before it starts the installation Chef Habitat Builder origin key names follow the format: ``` <origin>-<datetime>.pub (public key) <origin>-<datetime>.sig.key (private key, also called a "signing key") ``` For example, in: ``` testorigin-20190416223046.pub testorigin-20190416223046.sig.key ``` * “testorigin” is the origin’s name * “20190416223046” is the date and time of the key’s creation, which was 2019-04-16 22:30:46. * `.pub` is the file extension for the public key * `.sig.key` is the file extension for the private key, which is also called a “signing key” The Keys Tab ------------ When you create an origin, Chef Habitat Builder automatically generates an origin key pair and saves both keys. To view your origin keys on Chef Habitat Builder, navigate to your origin and select the **Keys** tab. (Builder > Origins > Keys) You will always be able to view and download public origin keys, but you will only see the private keys for origins in which you are an “administrator” or “owner”. ![Viewing your origin keys] ### Download Origin Keys from the Keys Tab Download your private or public origin key by selecting the **download** icon from the right end of the key details, under the *Actions* heading. ![Detail of the download icon] ### Upload Origin Keys from the Keys Tab You can upload origin keys that you generate on the command line to Chef Habitat Builder by selecting either the **Upload a private key** or **Upload a public key** icon, and copy your key into the form that appears. ![Example form content for uploading an origin key in Builder] Managing Origin Keys with the CLI --------------------------------- Run Chef Habitat CLI commands from your local environment or from within the Chef Habitat Studio. See the CLI documentation for more information on the [`hab origin key`](../habitat_cli/index#hab-origin-key) commands. ### Find Your Origin Keys Chef Habitat stores your public and private origin keys at `~/.hab/cache/keys` on Linux systems, `C:\hab\cache\keys` on Windows, and at `/hab/cache/keys` inside of the Chef Habitat Studio environment. #### Find Origin Keys in a Local Environment On Windows: ``` Get-ChildItem C:\hab\cache\keys ``` On Linux or macOS: ``` ls -la ~/.hab/cache/keys ``` #### Find Origin Keys in the Chef Habitat Studio On Windows: ``` Get-ChildItem C:\hab\cache\keys ``` On Linux or macOS: ``` ls -la /hab/cache/keys ``` ### Generate Origin Keys When you create an origin through the site, Chef Habitat Builder automatically generates an origin key pair. The Chef Habitat CLI creates origin key pairs through two different commands, for two different uses: * Use [`hab setup`](../install_habitat/index) to generate your first origin key pair as part of setting up the `hab` CLI * Use the `hab origin key generate <ORIGIN>` command to create a key pair for an origin Create origin keys with the `hab` command: ``` hab origin key generate <ORIGIN``` ### Download Origin Keys To get your public origin key using the command line, use: ``` hab origin key download <ORIGIN``` ### Upload Origin Keys Creating an origin with the `hab origin create` command registers the origin on Chef Habitat Builder without creating an origin key pair. The `hab origin key generate` command creates the key pair and saves them in your local environment, but it does not upload either origin key to Chef Habitat Builder. * Only “administrators” and “owners” can upload new keys to an origin. * Builder requires the public origin key to upload artifacts for that origin, so you’ll need to upload it. * Builder requires the private origin key to enable new artifact builds from packages with plans linked to that origin. Upload origin keys with the `hab` command: ``` hab origin key upload <ORIGIN``` Upload the private origin key: ``` hab origin key upload --secret <ORIGIN``` Upload both origin keys at the same time: ``` hab origin key upload --secfile <PATH_TO_PRIVATE_KEY> --pubfile <PATH_TO_PUBLIC_KEY``` ### Import Origin Keys Use `hab origin key import` to read the key from a standard input stream into Chef Habitat Builder: ``` hab origin key import <enter or paste key> hab origin key import <PATH_TO_KEY> cat <PATH_TO_KEY> | hab origin key import ``` #### Troubleshoot Origin Key Import On a macOS, you may encounter an upload failure. To remediate this failure: * Check that your `HAB_AUTH_TOKEN` environment variable is properly set and initialized * Add your `SSL_CERT_FILE` to the environment variables in your interactive shell configuration file, such as your `.bashrc`. ``` export SSL_CERT_FILE=/usr/local/etc/openssl/cert.pem ``` Initialize the setting from the command line with: ``` source ~/.bashrc ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/origin_keys/Upload and Promote Packages =========================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/builder_origin_packages.md) While you can build and run Chef Habitat packages without sharing them on [Chef Habitat Builder](https://bldr.habitat.sh), uploading them there enables greater collaboration and automated package rebuilds as underlying dependencies or your connected GitHub repository are updated. > Note: Chef Habitat Builder can only build Linux based plans (`plan.sh`) at this time. Setting up Chef Habitat Builder is easily done on the website: these steps take you through connecting your local Studio development experience with Builder. You interact with Chef Habitat Builder by: * Creating an account. * Creating an origin, or being invited to join an origin that already exists. * Setting up `hab` to authenticate with Builder. * Uploading the private and public keys for that origin. * Connecting your Github repositories and opting into rebuilds. Chef Habitat Builder supports both public and private origins, packages, and Github repositories. Create a Builder Account ------------------------ If you haven’t created an account yet, see the [Create a Builder Account](../builder_account/index) section above. Create or Join an Existing Origin --------------------------------- You can create your own origin in Builder or be invited to join an existing one. If you already built some Chef Habitat packages on your local computer prior to signing up for an account, you must rename your local packages' `pkg_origin` if the origin you want already exists. Set up Chef Habitat to Authenticate to Builder ---------------------------------------------- When you upload a package to Builder, you are required to supply an auth token as part of the `hab pkg upload` subcommand. You can generate a Chef Habitat personal access token via the Builder site [Profile page](https://bldr.habitat.sh/#/profile) for use with the `hab` command-line utility. Once you have this token, you can set the `HAB_AUTH_TOKEN` [environment variable](../environment_variables/index) to this value, so that any commands requiring authentication will use it. Create an Origin Key Pair ------------------------- After finishing the basic account creation steps, you need to create your origin key pair. Habitat will use the private origin key to sign the artifacts (`.hart` files) created by building your plan and verify the integrity of your artifacts with the public origin key. You can create an origin key pair by running `hab cli setup` from your host machine, or by running `hab origin key generate <ORIGIN>` from either the host machine or from within the studio. Your public and private origin keys are located at `~/.hab/cache/keys` on your host machine and at `/hab/cache/keys` inside the studio environment. Upload Your Origin Keys ----------------------- If you created a new Habitat origin from your host machine or from the Studio, Builder will not have either of the origin keys corresponding to your artifact. Builder will not accept uploaded artifacts without first having the correct public origin key. You can upload keys for the origin through the web interface for Builder, or by using the `hab origin key upload` command. You must have the access token for authentication, as described earlier, before you can upload keys. Upload Packages to Builder -------------------------- As long as you are already a member of the Habitat origin, once Builder possesses at least the public origin key, then you may upload one or more artifacts to that origin with the `hab pkg upload` command. After Habitat validates the cryptographic integrity of the artifact, it is then uploaded and stored on Builder. Uploading artifacts is a privileged operation for which you must have the access token. Promote Packages ---------------- By default, newly uploaded packages are placed in the `unstable` channel. However, the default package that is downloaded is the latest `stable` version of a package, unless overridden in commands such as `hab sup run`, `hab svc load`, and `hab pkg install`. If you want to promote your package to the `stable` channel, run the `hab pkg promote` command as follows: ``` $ hab pkg promote -z <TOKEN> origin/package/version/release stable ``` > **Note** You can also promote packages to the `stable` channel using the *promote to stable* button in the web app. For more information on how to use channels, see [Continuous Deployment Using Channels](../pkg_promote/index). ### Running Packages from Builder > **Note:** When running private packages from Builder, it’s necessary to add your [Chef Habitat access token](../builder_profile/index#create-a-personal-access-token) to the machine where you intend to deploy the package, via `export HAB_AUTH_TOKEN=<token>`. You can instruct the Supervisor to download and run packages from Builder by using the `hab sup` and `hab svc` commands, for example: ``` $ hab sup run $ hab svc load core/postgresql ``` If the Supervisor does not have the `core/postgresql` package in its local cache, it will contact Builder, retrieve the latest version and the public key for the `core` origin, verify the cryptographic integrity of the package, and then start it. You may also supply a `--channel` argument to instruct the Supervisor to use a different channel for the purposes of continuous deployment: ``` $ hab svc load core/postgresql --channel unstable ``` ### Running Packages from Exported Tarballs An exported tarball package contains the Chef Habitat client/binary as well as dependencies specified by your artifact. After deploying the tarball to your target server, extract the contents to the root filesystem (`/`): ``` $ tar zxf core-nginx-1.11.10-20170616000025.tar.gz --directory / ``` You can instruct the Supervisor to run packages from an exported tarball: ``` $ /hab/bin/hab svc start core/nginx ``` Note: On a clean server, this will download additional packages to satisfy the Supervisor dependencies. You will also require a `hab` group and `hab` user on the system for most services. Building Packages with Multiple Plans ------------------------------------- If you have a GitHub repository with multiple components inside, you will most likely also have individual plans for those components that are located inside of component subfolders. By default, Builder will only look for a package plan in either the root of the repository, or in a `habitat` subfolder at the root. If it does not find a plan file in those locations, it will not automatically issue builds when it detects file changes in the repository. In order to tell Builder about the location of the individual plan files, and in order provide more fine-grained control over when component packages are built, you can programmatically customize how and when Builder will build your plans by specifying build behavior in a `.bldr.toml` file at the root of the repository that you connect to Builder. Using this file, Builder only builds packages when source files or directories are updated in paths specified in `.bldr.toml`. This allows you to configure the building, publishing, and post-processing phases of a plan build in Builder. To enable this functionality, do the following: 1. Create a `.bldr.toml` in the root of your repository. 2. Open it and add an entry for each component package that you want to build. The `.bldr.toml` file is in TOML format, so create a TOML table specifying the `$pkg_name` value for that plan and then add a `plan_path` field specifying the path to your `plan.sh` file (you do not need to include plan.sh explicitly in the path). If all the files related to the plan are under the plan path, then you are done. Otherwise, you will need an additional ‘paths’ field specifying Unix-style path globs to files that are associated with the plan you specified in the ‘plan_path’. File or directory changes made in these path locations determine which packages will be rebuilt. Basically, when a file is committed, Builder will check to see whether it falls underneath the `plan_path` hierarchy, or matches one of the globs in the `paths` field if it was specified - if the answer is yes, then Builder will issue a build for that commit. It’s important to note that the entries for `plan_path` and `paths` do not behave the same. If you have something like `plan_path = "habitat"`, that behaves as if you had written `plan_path = "habitat/*"` - that is, it will automatically check every file under the `habitat` directory. However, if you have something like `paths = [ "src" ]`, that is *not* automatically expanded to `src/*`. That line will only watch for changes to a file called `src`. If you’re wanting to watch for changes to any file inside the `src` directory, then you must explicitly specify the glob, like so: `paths = [ "src/*" ]`. For example, in the Chef Habitat repository itself, this TOML states that the `hab-launcher`, `hab-studio`, and `hab-sup` packages will be rebuilt if there are any changes in any of the specified `components` sub-directories. Note that `hab-studio` does not need to specify a `path` because all of it’s files are within the `plan_path` hierarchy, but that is not the case for the other projects. ``` # .bldr.toml [hab-launcher] plan_path = "components/launcher/habitat" paths = [ "components/launcher/*", "components/launcher-protocol/*", "support/ci/builder-base-plan.sh", ] [hab-studio] plan_path = "components/studio" [hab-sup] plan_path = "components/sup" paths = [ "components/sup/*", "components/eventsrv-client/*", "components/launcher-client/*", "components/butterfly/*", "components/core/*", "components/builder-depot-client/*", ] ``` Notice that in order to specify that we’re interested in all files inside of the directories in our `paths` entries, we had to add the `/*` glob to the end manually. It’s also worth pointing out that there are multiple wildcard characters you can use when specifying path components. * `?` will match any single character. * `*` will match any (possibly empty) sequence of characters * `**` matches the current directory and arbitrary subdirectories. This sequence must form a single path component, so both `**a` and `b**` are invalid. More than two consecutive `*` characters is also invalid. * `[...]` matches any character inside the brackets. You can also specify a range, such as `[0-9]` to match any digit or `[a-z]` to match any lowercase letter. * `[!...]` is the negation of `[...]` so it will match any character *not* in the brackets. Note that while the above set of rules bears a remarkable resemblance to regular expressions, we do not support full regular expression syntax. Only what’s shown here is supported. Here is an example. ``` # .bldr.toml [hab-sup] plan_path = "components/sup" # automatically checks every file inside the 'sup' directory paths = [ "components/sup/?", # matches any file with a single character file name inside the 'sup' directory "components/eventsrv-client/*", # matches any file inside the 'eventsrv-client' directory "components/launcher-client/**/*", # matches any file inside the 'launcher-client' directory and also any of its sub-directories "components/butterfly/[0-9]*" # matches any file inside the 'butterfly' directory that begins with a number ] ``` Automated Builds ---------------- By connecting a plan file in [Chef Habitat Builder](https://bldr.habitat.sh/#/sign-in), you can trigger both manual (via the web UI, or via the `hab` command line) as well as automated package rebuilds whenever a change is merged into the `master` branch of the repository containing your Chef Habitat plan, or when a dependent package updates (rebuilds). ### Connect a Plan To connect a plan to Builder, view one of your origins (while signed in), click the **Connect a plan file** button, and complete the following steps: * Install the Builder GitHub App * Choose the GitHub organization and repository containing your Chef Habitat plan * Choose a privacy setting for the package * Specify container-registry publishing settings (optional) * Specify auto-build option (default is off) ### Auto-build Option The auto-build option controls whether or not your package will get automatically re-built. This option is a useful capability to have - for example, if you have a demo app that doesn’t need to be kept constantly up to date when some underlying dependency updates. Auto-build encompasses both builds that are triggered by Github web hooks (on commits to master), as well as builds that are triggered by a dependency updating. By default, new plan connections will have auto-build turned off. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/builder_origin_packages/Origin Settings =============== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/origin_settings.md) The *Origin Settings* tab contains: * Default Package Settings * Origin Secrets Everyone with origin membership can see the *Settings* tab, but only origin administrators and owners can add, update, or delete settings content. | Settings Actions | Read-Only | Member | Maintainer | Administrator | Owner | | --- | --- | --- | --- | --- | --- | | View settings | Y | Y | Y | Y | Y | | Add/Update/Delete settings | N | N | N | Y | Y | | **Origin Secrets Actions** | | | | | | | View secrets | N | N | Y | Y | Y | | Add/Update/Delete secrets | N | N | N | Y | Y | ![The administrator or owner’s view of the origin settings tab with a public default package setting and a saved origin secret] Default Package Settings ------------------------ The *Default Package Settings* define the visibility of build artifacts (.hart files). Everyone with origin membership can view the origin settings, but only origin administrators and owners can add, update, or delete settings. * Public packages are visible in search results and can be used by every Chef Habitat Builder user * Private artifacts do not appear in search results and are available only to users with origin membership Change the default setting for an origin by switching from **Public Packages** to **Private Packages**. The default setting is required for each origin. Packages can have different default visibility settings than the origin to which they belong. You can change the default visibility setting in for an individual packages in the package setting tab (Builder > Origin > Package > Settings). Origin Secrets -------------- Everyone with origin membership can view origin secrets, but only origin administrators and owners can add, update, or delete settings. *Origin Secrets* are located at the bottom of the *Settings* tab (Builder > Origin > Settings > Origin Secrets) and they let you encrypt and store secrets as environment variables. Origin secrets are useful for plans that require access to protected resources at build time, such as private source-code repositories and cloud storage providers. Only Chef Habitat Builder can read encrypted origin secrets. The origin secrets in your local environment are encrypted with an origin encryption key. Origin secrets are retained by the origin and are available for any of its packages. ### Manage Origin Secrets with the Chef Habitat CLI You can view the list of origin secrets and delete them in Chef Habitat Builder. However, the primary way of interacting with origin secrets is with the Chef Habitat CLI. #### List Secrets To list all of the secrets in an origin, use: ``` hab origin secret list --origin <ORIGIN``` #### Set Origin Secrets as Environment Variables Add your origin secrets as environment variables in your local environment: ``` export HAB_ORIGIN=<ORIGIN> export HAB_AUTH_TOKEN=<TOKEN> hab origin secret list ``` #### Save an Origin Secret To save an origin secret give the secret a name and the key value: ``` hab origin secret upload AWS_ACCESS_KEY_ID <your-key-id> hab origin secret upload AWS_SECRET_ACCESS_KEY <your-secret-access-key``` The output should similar to: ``` $ hab origin secret upload AWS_ACCESS_KEY_ID 1234567890EXAMPLE ↓ Downloading latest public encryption key 79 B / 79 B | [========================================] 100.00 % 120.23 KB/s ☑ Cached habicat-20200123456789.pub ☛ Encrypting value for key AWS_ACCESS_KEY_ID. ✓ Encrypted AWS_ACCESS_KEY_ID=[REDACTED]. ↑ Uploading secret for key AWS_ACCESS_KEY_ID. ✓ Uploaded secret for AWS_ACCESS_KEY_ID. ``` #### Delete an Origin Secret To delete an origin secret from an origin with the CLI ``` hab origin secret delete AWS_ACCESS_KEY_ID hab origin secret delete AWS_SECRET_ACCESS_KEY ``` See [Using Origin Secrets in Plans](../plan_writing/index#buildtime-workflow) for guidance on using origin secrets. See the [`hab origin secret`](../habitat_cli/index#hab-origin-secret) CLI documentation for more information on these commands. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/origin_settings/Promote Packages ================ [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/pkg_promote.md) Continuous deployment is a well-known software development practice of building and testing code changes in preparation for a release to a production environment. Continuous Deployment Using Channels ------------------------------------ Chef Habitat supports continuous deployment workflows through the use of channels. A channel is a tag for a package that the Supervisors in a service group can subscribe to. Channels are useful in CI/CD scenarios where you want to gate a package before making it the default version of the package that users should consume. You can think of this split as the difference between test and production, or nightly releases versus stable releases of products. By default, every new package is placed in the `unstable` channel by Builder. Packages in the `unstable` channel cannot be started or installed unless you specify the `--channel` flag in the `hab` CLI, or set the `HAB_BLDR_CHANNEL` environment variable to a non-stable channel. This is because the default channel used by the `hab` CLI when starting, installing, or loading packages is the `stable` channel. The `stable` channel indicates a level of stability and functionality suitable for use in multi-service applications or as a dependency for your service. To promote your package to a channel, you must either use Builder to build your package or upload it to Builder yourself, and then use the `hab pkg promote` subcommand to promote the package to the intended channel. To combine operations, the `hab` CLI allows you to do both in one command by using the `--channel` option when uploading your package. The following shows how to upload and promote a package to a custom channel named `test`. ``` $ hab pkg upload -z <TOKEN> results/<hart file> --channel test ``` In the example above, if you look up your package in the Builder UI, or using the `hab pkg channels` subcommand, you can see that your package is tagged for both the `test` and `unstable` channels. > **Note** Custom channels like `test` are scoped to each package. Builder does not create channels scoped to an origin, so if you want to use custom channels for future releases of a package, you must promote to those channels for each release. If you have already uploaded your package to a channel and wish to promote it to a different channel, use the `hab pkg promote` subcommand as shown below. ``` $ hab pkg promote -z <TOKEN> <origin>/<package>/<version>/<release> stable ``` ### Combining an Update Strategy with Channels By using both channels and either the `at-once` or `rolling` [update strategies](#using-updates), you can automatically update packages in a given channel as shown below: ![Promoting packages through channels] Using the infographic as a guide, a typical continuous deployment scenario would be as follows: 1. You build a new version of your package either through Builder or through a local Studio environment and then upload it to Builder. 2. When you are ready to roll out a new version of the package, you promote that package to the channel corresponding to the intended environment (e.g. `dev`). You can have multiple service groups in the same environment pointing to different channels, or the same channel. 3. An existing set of running Supervisors in that service group see that the channel they are subscribed to has an update, so they update their underlying Chef Habitat package, coordinating with one another per their update strategy, and restart their service. 4. When you are ready, you then promote that version of your package to a new channel (e.g. `acceptance`). The running Supervisors in that group see the update and perform the same service update as in step 3. You repeat steps 3 and 4 until your package makes its way through your continuous deployment pipeline. Configuring a Supervisor’s update strategy to point to a channel ensures that new versions of the application do not get deployed until the channel is updated, thereby preventing unstable versions from reaching environments for which they are not intended. To start a service with an update strategy and pointing to a channel, specify them as options when loading the service. ``` $ hab svc load <origin>/<package> --strategy rolling --channel test ``` While that service is running, update your package, rebuild it, and then promote it to the same channel that the previous release of that service is currently running in (e.g. `test`). Those running instances should now update according to their update strategy. ### Demoting a Package from a Channel If you need to un-associate a channel from a specific package release, you can do so using the `hab pkg demote` subcommand. Packages can be demoted from all channels except `unstable`. ``` $ hab pkg demote -z <TOKEN> <origin>/<package>/<version>/<release> test ``` The Builder UI for that package release and `hab pkg channels` will both reflect the removal of that channel. If you are running a package in a specific channel and demote > **Note** If you demote a package from the `stable` channel, then any other packages that depend on the stable version of that package will either fail to load or build depending on how that demoted packaged was used. > Also, downgrading to another release for a specific channel is not available at this time. This means if you run the latest release of a package from a specific channel, and demote the channel for that release, the package will not downgrade to the next most recent release from that channel. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/pkg_promote/Chef Habitat and Continuous Integration ======================================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/continuous_integration.md) **Examples: [Jenkins](https://jenkins.io/), [TravisCI](https://travis-ci.org/), and [Drone](https://drone.io/)** Continuous integration allows you to build, test, and deploy your code by using CLI tools and plugins. Chef Habitat includes the [Chef Habitat Studio](../pkg_build/index) which allows you to do interactive builds on your developer workstation, or non-interactive builds with your continuous integration server. Your continuous integration server can also call the Chef Habitat CLI to promote your Chef Habitat packages to different channels, enabling your applications to update themselves. Chef Habitat is not a continuous integration server and can make builds and promotion processes done by your continuous integration server easier. The [Chef Habitat Studio](../pkg_build/index) provides a clean room build environment for your application build. In effect, builds that occur on a developer’s workstation, or on a continuous integration server, will build in the same manner. Developers no longer need to worry about entire classes of “it works on my box” problems. Build engineers no longer need to create unique and difficult to maintain worker nodes for continuous integration servers. Instead, the Chef Habitat plan.sh file contains all the information needed to build the entire application, from dependency management, runtime environment binaries, packaging, and application lifecycle hooks. When using the [Chef Habitat Studio](../pkg_build/index), your continuous integration server can focus more on what it is good at doing, instead of worrying about managing custom plugins and their potential conflicts. Your continuous integration server can promote a Chef Habitat package (a .hart file) to a channel by calling the [Chef Habitat CLI](../install_habitat/index). This promotion method allows you to deploy a new version of your application in a pull-based manner by using the Chef Habitat Supervisor. Because this promotion process can be invoked non-interactively through the [Chef Habitat CLI](../install_habitat/index), you can manage your deployments using your existing tooling. If you choose, you can also do this promotion process manually. More complex application environments can also invoke the promotion process using a scheduling tool or provisioning tool to help manage infrastructure resources in addition to promoting Chef Habitat packages. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/continuous_integration/Building Packages ================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/pkg_build.md) When you have finished creating your plan and call `build` in Chef Habitat Studio, the build script does following steps: 1. Checks that Studio has the private origin key is available to sign the artifact 2. Downloads the source code from the location in `pkg_source`, if specified 3. Validates checksum of the downloaded file using the `pkg_shasum` value, if it is specified. 4. Extracts the source into a temporary cache. 5. Builds and installs the binary or library using `make` and `make install` for Linux based builds, and TODO: WHAT DOES WINDOWS USE? Invoke-Unpack function with Start-Process? Invoke-Install & Copy-Item? unless the callback methods are overridden in the plan. 6. Compresses the package contents (binaries, runtime dependencies, libraries, assets, etc.) into a tarball. 7. Signs the tarball with your private origin key and gives it a `.hart` file extension. After the build script completes, you can then upload your package to Chef Habitat Builder, or install and start your package locally. Packages need to be signed with a private origin key at buildtime. Generate an origin key pair manually by running the following command on your host machine: ``` hab origin key generate <ORIGIN``` The `hab-origin` subcommand will place the origin key files, originname-*timestamp*.sig.key (the private key) and originname-*timestamp*.pub files (the public key), in the `$HOME/.hab/cache/keys` directory. If you’re creating origin keys in the Studio container, or you are running as root on a Linux machine, your keys will be stored in `/hab/cache/keys`. Because the private key is used to sign your artifact, it should not be shared freely; however, if anyone wants to download and use your artifact, then they must have your public key (.pub) installed in their local `$HOME/.hab/cache/keys` or `/hab/cache/keys` directory. If the origin’s public key is not present, Chef Habitat attempts to download it from the Builder endpoint specified by the `--url` argument (<https://bldr.habitat.sh> by default) to `hab pkg install`. ### Passing Origin Keys into the Studio The Habitat Studio is a self-contained and minimal environment, which means that you’ll need to share your private origin keys with the Studio to sign artifacts. You can do this in three ways: 1. Set `HAB_ORIGIN` to the name of the origin you intend to use before entering the Studio: ``` export HAB_ORIGIN=originname ``` This approach overrides the `HAB_ORIGIN` environment variable and imports your public and private origin keys into the Studio environment. It also overrides any `pkg_origin` values in the packages that you build. This is useful because you can use it to build your own artifact, as well as to build your own artifacts from other packages' source code, for example, `originname/node` or `originname/glibc`. 2. Set `HAB_ORIGIN_KEYS` to the names of your origins. If you’re using more than one origin, separate them with commas: ``` export HAB_ORIGIN_KEYS=originname-internal,originname-test,originname ``` This imports the private origin keys, which must exactly match the origin names for the plans you intend to build. 3. Use the `-k` flag (short for “keys”) which accepts one or more key names separated by commas with: ``` hab studio -k originname-internal,originname-test enter ``` This imports the private origin keys, which must exactly match the origin names for the plans you intend to build. After you create or receive your private origin key, you can start up the Studio and build your artifact. ### Interactive Build Any build that you perform from a Chef Habitat Studio is an interactive build. Studio interactive builds allow you to examine the build environment before, during, and after the build. The directory where your plan is located is known as the plan context. 1. Change to the parent directory of the plan context. 2. Create and enter a new Chef Habitat Studio. If you have defined an origin and origin key during `hab cli setup` or by explicitly setting the `HAB_ORIGIN` and `HAB_ORIGIN_KEYS` environment variables, then type the following: ``` hab studio enter ``` The directory you were in is now mounted as `/src` inside the Studio. By default, a Supervisor runs in the background for iterative testing. You can see the streaming output by running `sup-log`. Type `Ctrl-C` to exit the streaming output and `sup-term` to terminate the background Supervisor. If you terminate the background Supervisor, then running `sup-run` will restart it along with every service that was previously loaded. You have to explicitly run `hab svc unload origin/package` to remove a package from the “loaded” list. 3. Enter the following command to create the package. ``` build /src/planname ``` 4. If the package builds successfully, it is placed into a `results` directory at the same level as your plan. #### Managing the Studio Type (Docker/Linux/Windows) Depending on the platform of your host and your Docker configuration, the behavior of `hab studio enter` may vary. Here is the default behavior listed by host platform: * **Linux** - A local chrooted Linux Studio. You can force a Docker based studio by adding the `-D` flag to the `hab studio enter` command. * **Mac** - A Docker container based Linux Studio * **Windows** - A local Windows studio. You can force a Docker based studio by adding the `-D` flag to the `hab studio enter` command. The platform of the spawned container depends on the mode your Docker service is running, which can be toggled between Linux Containers and Windows Containers. Make sure your Docker service is running in the correct mode for the kind of studio you wish to enter. > Note: For more details related to Windows containers see [Running Chef Habitat Windows Containers](../running_habitat_windows_containers/index). #### Building Dependent Plans in the Studio Writing plans for multiple packages that are dependent on each other can prove cumbersome when using multiple studios, as you need update dependencies frequently. On the other hand, using a single studio allows you to quickly test your changes by using locally built packages. To do so, you should use a folder structure like this: ``` tree projects projects/ ├── project-a └── project-b ``` This way, you can `hab studio enter` in `projects/`. If `project-b` depends on `project-a`, you can call `build project-a && build project-b` for example. ### Non-interactive Build A non-interactive build is one in which Chef Habitat creates a Studio for you, builds the package inside it, and then destroys the Studio, leaving the resulting `.hart` on your computer. Use a non-interactive build when you are sure the build will succeed, or in conjunction with a continuous integration system. 1. Change to the parent directory of the plan context. 2. Build the artifact in an unattended fashion, passing the name of the origin key to the command. ``` hab pkg build yourpackage -k yourname ``` > Similar to the `hab studio enter` command above, the type of studio where the build runs is determined by your host platform and `hab pkg build` takes the same `-D` flag to force a Docker environment if desired. > 3. The resulting artifact is inside a directory called `results`, along with any build logs and a build report (`last_build.env`) that includes machine-parsable metadata about the build. By default, the Studio is reset to a clean state after the package is built; however, *if you are using the Linux version of `hab`*, you can reuse a previous Studio when building your package by specifying the `-R` option when calling the `hab pkg build` subcommand. For information on the contents of an installed package, see [Package contents](../package_contents/index). Troubleshooting Builds ---------------------- ### Bash Plans: `attach` While working on plans, you may wish to stop the build and inspect the environment at any point during a build phase (e.g. download, build, unpack, etc.). In Bash-based plans, Chef Habitat provides an `attach` function for use in your plan.sh that functions like a debugging breakpoint and provides an easy REPL at that point. For PowerShell-based plans, you can use the PowerShell built-in `Set-PSBreakpoint` cmdlet prior to running your build. To use `attach`, insert it into your plan at the point where you would like to use it, e.g. ``` do_build() { attach make } ``` Now, perform a [build](index) – we recommend using an interactive studio so you do not need to set up the environment from scratch for every build. ``` hab studio enter ``` ``` build yourapp ``` The build system will proceed until the point where the `attach` function is invoked, and then drop you into a limited shell: ``` ## Attaching to debugging session From: /src/yourapp/plan.sh @ line 15 : 5: pkg_maintainer="The Chef Habitat Maintainers <<EMAIL>.sh>" 6: pkg_source=http://download.yourapp.io/releases/${pkg_name}-${pkg_version}.tar.gz 7: pkg_shasum=c2a791c4ea3bb7268795c45c6321fa5abcc24457178373e6a6e3be6372737f23 8: pkg_bin_dirs=(bin) 9: pkg_build_deps=(core/make core/gcc) 10: pkg_deps=(core/glibc) 11: pkg_exports=( 12: [port]=srv.port 13: ) 14: 15: do_build() { => 16: attach 17: make 18: } [1] yourapp(do_build)``` You can use basic Linux commands like `ls` in this environment. You can also use the `help` command the Chef Habitat build system provides in this context to see what other functions can help you debug the plan. ``` [1] yourapp(do_build)> help Help help Show a list of command or information about a specific command. Context whereami Show the code surrounding the current context (add a number to increase the lines of context). Environment vars Prints all the environment variables that are currently in scope. Navigating exit Pop to the previous context. exit-program End the /hab/pkgs/core/hab-plan-build/0.6.0/20160604180818/bin/hab-plan-build program. Aliases @ Alias for `whereami`. quit Alias for `exit`. quit-program Alias for `exit-program`. ``` Type `quit` when you are done with the debugger, and the remainder of the build will continue. If you wish to abort the build entirely, type `quit-program`. ### PowerShell Plans: `Set-PSBreakpoint` While there is no `attach` function exposed in a `plan.ps1` file, one can use the native Powershell cmdlet `Set-PSBreakpoint` to access virtually the same functionality. Instead of adding `attach` to your `Invoke-Build` function, enter the following from inside your studio shell: ``` [HAB-STUDIO] Habitat:\src> Set-PSBreakpoint -Command Invoke-Build ``` Now upon running `build` you should enter an interactive prompt inside the context of the Invoke-Build function: ``` habitat-aspnet-sample: Building Entering debug mode. Use h or ? for help. Hit Command breakpoint on 'Invoke-Build' At C:\src\habitat\plan.ps1:26 char:23 + function Invoke-Build { + ~ [HAB-STUDIO] C:\hab\cache\src\habitat-aspnet-sample-0.2.0>``` You can now call Powershell commands to inspect variables (like `Get-ChildItem variable:\`) or files to debug your build. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/pkg_build/Plan Quickstart =============== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/plan_quickstart.md) All plans must have a `plan.sh` or `plan.ps1` at the root of the plan context. They may even include both if a package is targeting both Windows and Linux platforms. This file will be used by the `hab-plan-build` command to build your package. To create a plan, do the following: 1. If you haven’t done so already, [download the `hab` CLI](../install_habitat/index) and install it per the instructions on the download page. 2. Run `hab cli setup` and follow the instructions in the setup script. 3. The easiest way to create a plan is to use the `hab plan init` subcommand. This subcommand will create a directory, known as the plan context, that contains your plan file and any runtime hooks and/or templated configuration data. To use `hab plan init` as part of your project repo, navigate to the root of your project repo and run `hab plan init`. It will create a new `habitat` sub-directory with a plan.sh (or plan.ps1 on Windows) based on the name of the parent directory, and include a `default.toml` file as well as `config` and `hooks` directories for you to populate as needed. For example: ``` cd /path/to/<reponame> hab plan init ``` will result in a new `habitat` directory located at `/path/to/<reponame>/habitat`. A plan file will be created and the `pkg_name` variable will be set to *<reponame>*. Also, any environment variables that you have previously set (such as `HAB_ORIGIN`) will be used to populate the respective `pkg_*` variables. If you want to auto-populate more of the `pkg_*` variables, you also have the option of setting them when calling `hab plan init`, as shown in the following example: ``` env pkg_svc_user=someuser pkg_deps="(core/make core/coreutils)" \ pkg_license="('MIT' 'Apache-2.0')" pkg_bin_dirs="(bin sbin)" \ pkg_version=1.0.0 pkg_description="foo" pkg_maintainer="you" \ hab plan init yourplan ``` See [hab plan init](../habitat_cli/index#hab-plan-init) for more information on how to use this subcommand. 4. Now that you have stubbed out your plan file in your plan context, open it and begin modifying it to suit your needs. When writing a plan, it’s important to understand that you are defining both how the package is built and the actions Chef Habitat will take when the Supervisor starts and manages the child processes in the package. The following sections explain what you need to do for each phase. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/plan_quickstart/Exporting Packages ================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/pkg_exports.md) Chef Habitat Artifacts–`.hart` files–can be exported in a number of different formats depending on what you need and where you need it. This is powerful because you can use the same immutable Chef Habitat artifact by exporting it into a format that you need for a specific job. You can export packages into several different external, immutable runtime formats. Currently there are exports for: docker, mesos, tar, and cloudfoundry. The command to export a package is `hab pkg export <FORMAT> <PKG_IDENT>`. See the [Chef Habitat CLI Reference Guide](../habitat_cli/index#hab-pkg-export) for more CLI information. > **Note** If you specify an `origin/package` identifier, such as `core/postgresql`, the Chef Habitat CLI will check Builder for the latest stable version of the package and export that. > If you wish to export a package that is not on Builder, create a Chef Habitat artifact by running the `build` command, then point `hab pkg` to the `.hart` file within the `/results` directory: ``` hab pkg export tar ./results/example-app.hart ``` Read on for more detailed instructions. ### Exporting to Docker You can create a Docker container image for any package by performing the following steps: 1. Ensure you have a Docker daemon running on your host system. On Linux, the exporter shares the Docker socket (`unix:///var/run/docker.sock`) into the studio. 2. Create an interactive studio with the `hab studio enter` command. 3. [Build](../pkg_build/index) the Chef Habitat package from which you want to create a Docker container image and then run the Docker exporter on the package. ``` hab pkg export docker ./results/<hart-filename>.hart ``` > **Note** The command above is for local testing only. If you have uploaded your package to Builder, you can export it by calling `hab pkg export docker origin/package`. The default is to use the latest stable release; however, you can override that by specifying a different channel in an optional flag. > **Note** On Linux, exporting your Chef Habitat artifact to a Docker image requires the Docker Engine supplied by Docker. Packages from distribution-specific or otherwise alternative providers are currently not supported. > **Note** In a Windows container studio, the `export` command will not be able to access the host docker engine. To export a Windows package or hart file built inside of a Windows container studio, first exit the studio and then export the `.hart` file in your local `results` directory. > 4. You may now exit the studio. The new Docker image exists on your computer and can be examined with `docker images` or run with `docker run`. 5. Please note that when you run this docker container, you will need to pass the `HAB_LICENSE` environment variable into the container in order to accept the Habitat license. If you don’t, your container will abort at a license acceptance prompt. One way to do this would be `docker run --env HAB_LICENSE=accept-no-persist IMAGE`. Alternatively, if you use a scheduler to run these docker containers, you should add that environment variable to your scheduler configuration. ### Exporting to a Tarball 1. Enter the Chef Habitat studio by using `hab studio enter`. 2. Install or [build](../pkg_build/index) the Chef Habitat package from which you want to create a tarball, for example: ``` hab pkg install <ORIGIN>/<NAME``` 3. Run the tar exporter on the package. ``` hab pkg export tar <ORIGIN>/<NAME``` If you receive an error, try running ``` hab pkg export tar /results/<your_package>.hart ``` 4. Your package is now in a tar file that exists locally on your computer in the format `<ORIGIN>-<NAME>-<VERSION>-<TIMESTAMP>.tar.gz` and can be deployed and run on a target machine. 5. If you wish to run this tar file on a remote machine (i.e. a virtual machine in a cloud environment), scp (or whatever transfer protocol you prefer) the file to whatever you wish to run it. 6. SSH into the virtual machine 7. Run these commands to set up the required user and group: ``` sudo adduser --group hab sudo useradd -g hab hab ``` 8. Next, unpack the tar file: ``` sudo tar xf your-origin-package-version-timestamp.tar.gz sudo cp -R hab /hab ``` 9. Now, start the Supervisor and load your service package using the `hab` binary, which is included in the tar archive: ``` sudo /hab/bin/hab sup run sudo /hab/bin/hab svc load <ORIGIN>/<NAME``` ### Exporting to Apache Mesos and DC/OS 1. Create an interactive studio in any directory with the `hab studio enter` command. 2. Install or [build](../pkg_build/index) the Chef Habitat package from which you want to create a Marathon application, for example: ``` hab pkg install <ORIGIN>/<NAME``` 3. Run the Mesos exporter on the package. ``` hab pkg export mesos <ORIGIN>/<NAME``` 4. This will create a Mesos container-format tarball in the results directory, and also print the JSON needed to load the application into Marathon. Note that the tarball needs to be uploaded to a download location and the “uris” in the JSON need to be updated manually. This is an example of the output: ``` { "id": "yourorigin/yourpackage", "cmd": "/bin/id -u hab &>/dev/null || /sbin/useradd hab; /bin/chown -R hab:hab *; mount -t proc proc proc/; mount -t sysfs sys sys/;mount -o bind /dev dev/; /usr/sbin/chroot . ./init.sh start yourorigin/yourpackage", "cpus": 0.5, "disk": 0, "mem": 256, "instances": 1, "uris": ["https://storage.googleapis.com/mesos-habitat/yourorigin/yourpackage-0.0.1-20160611121519.tgz" ] } ``` 5. Note that the default resource allocation for the application is very small: 0.5 units of CPU, no disk, one instance, and 256MB of memory. To change these resource allocations, pass different values to the Mesos exporter as command line options (defaults are documented with `--help`). 6. See the [Apaches Mesos and DC/OS documentation](../mesos_dcos/index) for more information on getting your application running on Mesos. ### Exporting to Cloud Foundry Packages can be exported to run in a [Cloud Foundry platform](https://www.cloudfoundry.org/certified-platforms/) through the use of a Docker image that contains additional layers meant to handle mapping from the Cloud Foundry environment to a Chef Habitat default.toml file. #### Setting up Docker Support in Cloud Foundry If you have not done so already, you must enable Docker support for Cloud Foundry before you can upload your Cloud Foundry-specific Docker image. To do so, make sure you have done the following: 1. Log in as an Admin user. 2. Enable Docker support on your Cloud Foundry deployment by enabling the `diego_docker` feature flag. ``` cf enable-feature-flag diego_docker ``` #### Creating a Mapping File The mapping file is a TOML file that can add Bash-interpolated variables and scripts. The Bash code will have access to: * all environment variables * the jq binary * the helper methods listed below Here’s an example of a mapping TOML file named `cf-mapping.toml`: ``` secret_key_base = "$SECRET_KEY_BASE" rails_env = "$RAILS_ENV" port = ${PORT} [db] user = "$(service "elephantsql" '.credentials.username')" password = "$(service "elephantsql" '.credentials.password')" host = "$(service "elephantsql" '.credentials.host')" name = "$(service "elephantsql" '.credentials.database')" ``` #### Helpers The helper methods are designed to extract information from the standard Cloud Foundry environment variables [VCAP_SERVICES](https://docs.cloudfoundry.org/devguide/deploy-apps/environment-variable.html#VCAP-SERVICES) and [VCAP_APPLICATION](https://docs.cloudfoundry.org/devguide/deploy-apps/environment-variable.html#VCAP-APPLICATION). * `service <service-name> <jq-expression>` will extract the JSON associated with the given service-name from the `VCAP_SERVICES` environment variable and apply the jq-expression to it. * `application <jq-expression>` will apply the jq-expression to the `VCAP_APPLICATION` environment variable ### Exporting and Pushing to a Cloud Foundry Endpoint 1. Create a mapping.toml file using the format specified above and place that file in your local project repo. 2. Enter the Studio through `hab studio enter`. 3. Install or [build](../pkg_build/index) the package that you want to export. ``` hab pkg install <ORIGIN>/<NAME``` 4. Run the Cloud Foundry exporter on the package. ``` hab pkg export cf <ORIGIN>/<NAME> /path/to/mapping.toml ``` > **Note** To generate this image, a base Docker image is also created. The Cloud Foundry version of the docker image will have `cf-` as a prefix in the image tag. > 5. (Optional) If you are creating a web app that binds to another Cloud Foundry service, such as ElephantSQL, you must have this service enabled in your deployment before running your app. 6. [Upload your Docker image to a supported registry](https://docs.cloudfoundry.org/devguide/deploy-apps/push-docker.html). Your Docker repository should be match the `origin/package` identifier of your package. ``` docker push origin/package:cf-version-release ``` 7. After your Cloud Foundry Docker image is built, you can deploy it to a Cloud Foundry platform. ``` cf push APP-NAME --docker-image docker_org/repository ``` Your application will start after it has been successfully uploaded and deployed. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/pkg_exports/Runtime Binds ============= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/pkg_binds.md) *Runtime binding* in Chef Habitat refers to the ability for one service group to connect to another, forming a producer-consumer relationship where the consumer service can use the producer service’s current configuration in order to configure itself at runtime. When the producer’s configuration change, the consumer is notified and can reconfigure itself as needed. With runtime binding, a consumer service can use a “binding name” of their choosing in their configuration and lifecycle hook templates as a kind of handle to refer to the configuration values they need from the producer service. This name isn’t inherently tied to any particular package or service group name. Instead, when the service is run, users associate a service group with that binding name, which gives Chef Habitat all the information it needs to wire the producer and consumer services together. Let’s look at how we set up this relationship in detail. ### Defining the Producer Contract A producer service defines its contract by “exporting” a subset of its runtime configuration. This is done by defining values in the `pkg_exports` associative array defined in your package’s `plan.sh`. For example, a database server named `amnesia` might define the following exports: ``` pkg_exports=( [port]=network.port [ssl-port]=network.ssl.port ) ``` Note that Powershell plans use hashtables where Bash plans use associative arrays. A `plan.ps1` would declare its exports as: ``` $pkg_exports=@{ port="network.port" ssl-port="network.ssl.port" } ``` This will export the runtime values of its `network.port` and `network.ssl.port` configuration entries publicly as `port` and `ssl-port`, respectively. All configuration entries in `pkg_exports` must have a default value in `default.toml`, but the actual exported values will change at runtime to reflect the producer’s current configuration. When values change (for example, by `hab config apply`), the consumer service will be notified that its producer service configuration has changed. We’ll see how to use this on the consumer in the sections below. Producer services export only the *subset* of their configuration that is defined through `pkg_exports` and not the entire thing. Consumer services see only what the producer service exports, and nothing more. This is important, because it means that configuration that must remain secret–such as passwords–are not shared *unless* they are explicitly defined in `pkg_exports`. Additionally, the internal structure of the producer’s configuration is independent of the exported interface it presents. In our example, `ssl-port` originally comes from a deeply-nested `network.ssl.port` value. However, the exported interface is *flat*, effectively a non-nested set of key-value pairs. ### Defining the Consumer Contract The consumer service defines a “binding name” as a handle to refer to a service group from which it receives configuration data. However, it must do more than just name the bind, it must also state the configuration values it expects from the service group. Chef Habitat will make sure that whatever service group is bound actually exports the expected values to the consumer service. As an example, let’s say we have an application server, called `session-server`, that needs to connect to a database service, and needs both a “port” and an “ssl-port” in order to make that connection. We can describe this relationship in our `plan.sh` file like so: ``` pkg_binds=( [database]="port ssl-port" ) ``` Here, `pkg_binds` is an associative array. The key (“database”) is the binding name, while the value (“port ssl-port”) is a space-delimited list of the exported configuration the binding requires. A consumer can specify multiple binds; each would be an individual entry in this associative array. Judging from this, the producer we described above would be a good candidate for this application server to bind to, because it exports both a “port” and an “ssl-port”. A bound service group may export additional values, but they cannot export less and still satisfy the contract. Chef Habitat only matches services up at the syntactic, not semantic, level of this contract. If you bind to a service that exports a “port”, Chef Habitat only knows that the service exports something called “port”; it could be the port for a PostgreSQL database, or it could be the port of an application server. You will need to ensure that you connect the correct services together; Chef Habitat’s binds provide the means by which you express these relationships. You are, however, free to create bind names and export names that are meaningful for you. #### The Difference Between *pkg_binds* and *pkg_binds_optional* In addition to the `pkg_binds` array, Plan authors may also specify `pkg_binds_optional`. It has exactly the same structure as `pkg_binds`, but, as the name implies, these bindings are *optional*; however, it is worth examining exactly what is meant by “optional” in this case. In order to load a service into the Supervisor, each bind defined in `pkg_binds` *must* be mapped to a service group; if any of these binds are not mapped, then the Supervisor will refuse to load the service. Binds defined in `pkg_binds_optional`, on the other hand, *may* be mapped when loading a service. If a service group mapping is not defined at load time, the Supervisor will load the service without question. As an extreme example, a service could have no `pkg_binds` entries, and five `pkg_binds_optional` entries; such a service could be loaded with no binds mapped, one bind mapped, all the way to mapping all five binds. There are several scenarios where optional binds may be useful: * A service may have some default functionality which may be overridden at load-time by mapping an optional binding. Perhaps you have some kind of artifact repository service that, in the absence of a “remote-store” bind stores data on the local filesystem. However, if `remote-store` is bound to an appropriate S3 API-compatible service, such as [Minio](https://www.minio.io), it could modify its behavior to store data remotely. * A service can be optionally bind to a service to unlock additional features. For example, say you have an application that may run with or without a caching layer. You can model this using an optional bind named (say), “cache”. If you wish to run without the caching functionality enabled, you can start the service without specifying a service group mapping for the “cache” bind. Since the bind is optional, it is not needed for Chef Habitat to run your service. However, if you do wish to run with the caching enabled, you can specify a service group mapping, e.g. `hab svc load acme/my-app --bind=cache:redis.prod`. In this scenario, your service’s configuration can pull configuration values from the `redis.prod` service group, enabling it to use Redis as a caching layer. * A service may can optionally bind one of several services; if bind “X” is mapped, operate *this* way; if “Y” is mapped, operate *that* way. An application that could use either a Redis backend or a PostgreSQL backend, depending on the deployment scenario, could declare optional “redis” and “postgresql” bindings, and pick which one to map at service load-time. If this is your use case, Chef Habitat does not have a way to encode the fact that “one and only one of these optional bindings should be mapped”, so you will have to manage that on your own. ### Service Start-up Behavior Prior to Chef Habitat 0.56.0, if the service group that you bound to was not present in the Supervisor network census, or had no live members, your service would not start until the group was present with live members. While this can be desirable behavior in some cases, as with running certain legacy applications, it is not always desirable, particularly for modern microservice applications, which should be able to gracefully cope with the absence of their networked dependencies. With 0.56.0, however, this behavior can be modified using the new runtime service option `--binding-mode`. By setting `--binding-mode=relaxed` when loading a service, that service can start immediately, whether there are any members of a bound service group present or not. (Setting `--binding-mode=strict` will give you the previous, start-only-after-all-bound-groups-are-present behavior. This is also the current default, though `relaxed` will be the eventual default for Chef Habitat 1.0.0.). Such a service should have configuration and lifecycle hook templates written in such a way that the service can remain operational (though perhaps with reduced functionality) when there are no live members of a bound service group present in the network census. #### The Difference Between Required Binds, Optional Binds, and Binding Mode While there is a bit of overlap in these concepts, they are distinct. It’s best to think of required and optional binds as defining “how applications can be wired together” (specifically, which “wires” must be connected in order to provide the minimal amount of information needed to run a service). Binding mode, on the other hand, defines how the application’s start-up behavior is affected the presence or absence of its networked dependencies. Another useful thing to keep in mind when thinking about required and optional binds is that service group mappings currently cannot be dynamically changed at runtime. They can only be changed by stopping a service, reloading the service with a new set of options, and then starting it up again. This constraint (which may change in future versions of Chef Habitat) may help guide your choice between what should be a required bind, and what should be optional, particularly when using the relaxed binding mode. ### Using Runtime Binds with Consumer Services Once you’ve defined both ends of the contract, you can leverage the bind in any of your package’s hooks or configuration files. Given the two example services above, a section of a configuration file for `session-server` might look like this: ``` {{~#each bind.database.members as |member|}} database = "{{member.sys.ip}}:{{member.cfg.port}}" database-secure = "{{member.sys.ip}}:{{member.cfg.ssl-port}}" {{~/each}} ``` Here, `bind.<BINDING_NAME>` will be “truthy” (and can thus be used in boolean expressions) only if the bind has been satisfied, and `bind.<BINDING_NAME>.members` will be an array of only active members. (Prior to Chef Habitat 0.56.0, `bind.<BINDING_NAME>` was always present, and `bind.<BINDING_NAME>.members` had *all* members, even ones that had left the Supervisor network long ago. This necessitated using the `eachAlive` helper function, instead of just `each`.) ### Starting a Consumer Service Since your application server defined `database` as a required bind, you’ll need to provide the name of a service group running a package which fulfills the contract using the `--bind` parameter to the Supervisor. For example, running the following: ``` hab svc load <ORIGIN>/<NAME> --bind database:amnesia.default ``` would create a bind aliasing `database` to the `amnesia` service in the `default` service group. The service group passed to `--bind database:{service}.{group}` doesn’t *need* to be the service `amnesia`. This bind can be any service as long as they export a configuration key for `port` and `ssl-port`. You can declare bindings to multiple service groups in your templates by using the `--bind` option multiple times on the command line. Your service will not start if your package has declared a required bind and a value for it was not specified by `--bind`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/pkg_binds/Scaffolding =========== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/scaffolding.md) Chef Habitat scaffoldings are standardized plans for automated building and running your application. Each scaffolding is tuned to the way your application was built, which allows it to create the appropriate [application lifecycle hooks](../application_lifecycle_hooks/index) and add in the correct runtime dependencies when building the package for your application. Scaffoldings also provide some default health check hooks where appropriate to ensure your application is functioning reliably. Customized Scaffolding can be created to facilitate re-usability of common patterns in your organization for developing, building, and running your applications. Automated Scaffolding --------------------- While we are targeting many platforms for automated scaffolding we currently support Ruby, Node.js and Gradle. * [core/scaffolding-ruby](https://github.com/habitat-sh/core-plans/blob/main/scaffolding-ruby/doc/reference.md) * [core/scaffolding-node](https://github.com/habitat-sh/core-plans/tree/main/scaffolding-node) * [core/scaffolding-gradle](https://github.com/habitat-sh/core-plans/blob/main/scaffolding-gradle) Variables --------- Scaffolding provides certain customizable variables for language-specific behavior. Please see the appropriate scaffolding documentation for details. ### Overriding Scaffolding Callbacks If you want to override phases of a scaffold’s build in your plans, make sure to override the main `do_xxx` phase, not the callback directly. ex override `do_install()` instead of `do_default_install` or `do_node_install`. ### Scaffolding Internals A language or framework scaffolding is shipped as a Chef Habitat package, which means that each scaffolding runtime dependency becomes a build dependency for the application being built. lib/scaffolding.sh File ----------------------- To create scaffolding, a package must contain a `lib/scaffolding.sh` file which gets sourced by the build program running Bash. scaffolding_load() Function ---------------------------- A optional function named `scaffolding_load()` may be created in `lib/scaffolding.sh` which will be called early in the build program which allows a Scaffolding author to control and augment the `pkg_deps` and `pkg_build_deps` arrays. At this point, no other build or run dependencies have been resolved so the code in this function can only rely on what the build program provides or software pulled in via the Scaffolding’s Plan. Default Build Phases Implementations ------------------------------------ The remainder of the `lib/scaffolding.sh` contains one or more default implementations for the build phases. These include, but are not limited to: * `do_default_prepare()` * `do_default_build()` * `do_default_install()` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/scaffolding/Writing Plans ============= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/plan_writing.md) In Chef Habitat the unit of automation is the application itself. This chapter includes content related specifically to the process and workflow of developing a plan that will instruct Chef Habitat in how to build, deploy, and manage your application. Writing Plans ------------- Artifacts are the cryptographically-signed tarballs that are uploaded, downloaded, unpacked, and installed in Chef Habitat. They are built from shell scripts known as plans, but may also include application lifecycle hooks and service configuration files that describe the behavior and configuration of a running service. At the center of Chef Habitat packaging is the plan. This is a directory comprised of shell scripts and optional configuration files that define how you download, configure, make, install, and manage the lifecycle of the software in the artifact. More conceptual information on artifacts can be found in the [Package Identifiers](../pkg_ids/index) page. As a way to start to understand plans, let’s look at an example `plan.sh` for [sqlite](https://www.sqlite.org/): ``` pkg_name=sqlite pkg_version=3130000 pkg_origin=core pkg_license=('Public Domain') pkg_maintainer="The Chef Habitat Maintainers <<EMAIL>>" pkg_description="A software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine." pkg_upstream_url=https://www.sqlite.org/ pkg_source=https://www.sqlite.org/2016/${pkg_name}-autoconf-${pkg_version}.tar.gz pkg_filename=${pkg_name}-autoconf-${pkg_version}.tar.gz pkg_dirname=${pkg_name}-autoconf-${pkg_version} pkg_shasum=e2797026b3310c9d08bd472f6d430058c6dd139ff9d4e30289884ccd9744086b pkg_deps=(core/glibc core/readline) pkg_build_deps=(core/gcc core/make core/coreutils) pkg_lib_dirs=(lib) pkg_include_dirs=(include) pkg_bin_dirs=(bin) ``` > Note: On Windows we would create a plan.ps1 file instead. All the variable names are the same but we use Powershell syntax so, for example, `pkg_deps=(core/glibc core/readline)` becomes `$pkg_deps=@("core/glibc", "core/readline")`. It has the name of the software, the version, where to download it, a checksum to verify the contents are what we expect, run dependencies on `core/glibc` and `core/readline`, build dependencies on `core/coreutils`, `core/make`, `core/gcc`, libraries files in `lib`, header files in `include`, and a binary file in `bin`. Also, because it’s a core plan, it has a description and upstream URL for the source project included. > Note: The `core` prefix is the origin of those dependencies. For more information, see [Create an Origin](../builder_origins/index) When you have finished creating your plan and call `build` in Chef Habitat studio, the following occurs: 1. The build script ensures that the private origin key is available to sign the artifact. 2. If specified in `pkg_source`, a compressed file containing the source code is downloaded. 3. The checksum of that file, specified in `pkg_shasum`, is validated. 4. The source is extracted into a temporary cache. 5. Unless overridden, the callback methods will build and install the binary or library via `make` and `make install`, respectively for Linux based builds. 6. Your package contents (binaries, runtime dependencies, libraries, assets, etc.) are then compressed into a tarball. 7. The tarball is signed with your private origin key and given a `.hart` file extension. After the build script completes, you can then upload your package to Chef Habitat Builder, or install and start your package locally. > Note: The plan.sh or plan.ps1 file is the only required file to create a package. Configuration files, runtime hooks, and other source files are optional. Write Your First Plan --------------------- All plans must have a `plan.sh` or `plan.ps1` at the root of the plan context. They may even include both if a package is targeting both Windows and Linux platforms. This file will be used by the `hab-plan-build` command to build your package. To create a plan, do the following: 1. If you haven’t done so already, [download the `hab` CLI](../install_habitat/index) and install it per the instructions on the download page. 2. Run `hab cli setup` and follow the instructions in the setup script. 3. The easiest way to create a plan is to use the `hab plan init` subcommand. This subcommand will create a directory, known as the plan context, that contains your plan file and any runtime hooks and/or templated configuration data. To use `hab plan init` as part of your project repo, navigate to the root of your project repo and run `hab plan init`. It will create a new `habitat` sub-directory with a plan.sh (or plan.ps1 on Windows) based on the name of the parent directory, and include a `default.toml` file as well as `config` and `hooks` directories for you to populate as needed. For example: ``` cd /path/to/<reponame> hab plan init ``` will result in a new `habitat` directory located at `/path/to/<reponame>/habitat`. A plan file will be created and the `pkg_name` variable will be set to *<reponame>*. Also, any environment variables that you have previously set (such as `HAB_ORIGIN`) will be used to populate the respective `pkg_*` variables. If you want to auto-populate more of the `pkg_*` variables, you also have the option of setting them when calling `hab plan init`, as shown in the following example: ``` env pkg_svc_user=someuser pkg_deps="(core/make core/coreutils)" \ pkg_license="('MIT' 'Apache-2.0')" pkg_bin_dirs="(bin sbin)" \ pkg_version=1.0.0 pkg_description="foo" pkg_maintainer="you" \ hab plan init yourplan ``` See [hab plan init](../habitat_cli/index#hab-plan-init) for more information on how to use this subcommand. 4. Now that you have stubbed out your plan file in your plan context, open it and begin modifying it to suit your needs. When writing a plan, it’s important to understand that you are defining both how the package is built and the actions Chef Habitat will take when the Supervisor starts and manages the child processes in the package. The following sections explain what you need to do for each phase. Writing a Plan for Multiple Platform Targets -------------------------------------------- You may want to create a plan for an application that can run on multiple platform targets. You can create target specific folders beneath either the root of your project or a top level `habitat` folder. Then save the plan, hooks, and configuration templates specific to a single platform all inside of that target specific folder. For example, an application targeting linux, Linux kernel 2, and Windows may have the following structure: ``` app_root/ ├── x86_64-linux/ | | plan.sh | └── hooks/ | run ├── x86_64-linux-kernel2/ | | plan.sh | └── hooks/ | run └── x86_64-windows/ | plan.ps1 └── hooks/ run ``` The build script will look for the base of your plan in the following locations: * `<app_root>/<target>/` * `<app_root>/habitat/<target>/` * `<app_root>/` * `<app_root>/habitat/` If it finds a plan both inside as well as outside of a target folder, the target specific plan will be used as long as that is the target currently being built. However it is strongly recommended that you do not have plans both inside and outside of a target folder. We currently allow this only for backwards compatibility with some existing plans but plan to eventually fail builds where a plan exists in both places. The best practice when you need multiple plans for different targets is to put each plan in its own target folder. Of course if your plan does not include hooks or configuration templates and just requires a plan file, you may choose this simpler structure: ``` app_root/ └── habitat/ plan.sh plan.ps1 ``` > Note: It is recommended to place all plan files inside of a `habitat` parent folder in order to allow for clean separation between your application source code and habitat specific files. However, if you maintain a separate repository solely for the purpose of storing habitat plans, then the use of a `habitat` folder may not be necessary. On Windows, only a `plan.ps1` will be used and a `plan.sh` will only be used on Linux or Linux kernel 2. So if your application requires different plans for Linux and Linux Kernel 2, even without hooks and configuration templates, you will need to use target folders for each platform. ### Buildtime Workflow For buildtime installation and configuration, workflow steps need to be included in the plan file to define how you will install your application source files into a package. Before writing your plan, you should know and understand how your application binaries are currently built, installed, what their dependencies are, and where your application or software library expects to find those dependencies. The main steps in the buildtime workflow are the following: 1. Create your fully-qualified package identifier. 2. Add licensing and contact information. 3. Download and unpack your source files. 4. Define your dependencies. 5. (Optional) Override any default build phases you need to using callbacks. The following sections describe each of these steps in more detail. #### Create your Package Identifier The origin is a place for you to set default privacy rules, store your packages, and collaborate with teammates. For example, the “core” origin is where the core maintainers of Chef Habitat share packages that are foundational to building other packages. If you would like to browse them, they are located in the [core-plans repo](https://github.com/habitat-sh/core-plans), and on [Chef Habitat Builder’s Core Origin](https://bldr.habitat.sh/#/pkgs/core). Creating artifacts for a specific origin requires that you have access to the that origin’s private key. The private origin key will be used to sign the artifact when it is built by the `hab plan build` command. Origin keys are kept in `$HOME/.hab/cache/keys` on the host machine when running `hab` as a non-root user and `/hab/cache/keys` when running as root (including in the studio). For more information on origin keys, see [Keys](../keys/index). The next important part of your package identifier is the name of the package. Standard naming convention is to base the name of the package off of the name of the source or project you download and install into the package. #### Add Licensing and Contact Information You should enter your contact information in your plan. Most importantly, you should update the `pkg_license` value to indicate the type of license (or licenses) that your source files are licensed under. Valid license types can be found at <https://spdx.org/licenses/>. You can include multiple licenses as an array. > Note: Because all arrays in the pkg_* settings are shell arrays, they are whitespace delimited. #### Download and Unpack Your Source Files Add in the `pkg_source` value that points to where your source files are located at. Any `wget` url will work; however, unless you’re downloading a tarball from a public endpoint, you may need to modify how you download your source files and where in your plan.sh you perform the download operation. Chef Habitat supports retrieving source files from [GitHub](https://github.com). When cloning from GitHub, it is recommended to use https URIs because they are proxy friendly, whereas `git@github` or `git://` are not. To download the source from a GitHub repository, implement `do_download()` in your plan.sh (or `Invoke-Download` in a plan.ps1) and add a reference the `core/git` package as a build dependency. Because Chef Habitat does not contain a system-wide CA cert bundle, you must use the `core/cacerts` package and export the `GIT_SSL_CAINFO` environment variable to point the `core/cacerts` package on Linux. Here’s an example of how to do this in the `do_download()` callback. ``` do_download() { export GIT_SSL_CAINFO="$(pkg_path_for core/cacerts)/ssl/certs/cacert.pem" git clone https://github.com/chef/chef pushd chef git checkout $pkg_version popd tar -cjvf $HAB_CACHE_SRC_PATH/${pkg_name}-${pkg_version}.tar.bz2 \ --transform "s,^\./chef,chef-${pkg_version}," ./chef \ --exclude chef/.git --exclude chef/spec pkg_shasum=$(trim $(sha256sum $HAB_CACHE_SRC_PATH/${pkg_filename} | cut -d " " -f 1)) } ``` The plan.ps1 equivalent would be: ``` Function Invoke-Download { git clone https://github.com/chef/chef pushd chef git checkout $pkg_version popd Compress-Archive -Path chef/* -DestinationPath $HAB_CACHE_SRC_PATH/$pkg_name-$pkg_version.zip -Force $script:pkg_shasum = (Get-FileHash -path $HAB_CACHE_SRC_PATH/$pkg_name-$pkg_version.zip -Algorithm SHA256).Hash.ToLower() } ``` After you have either specified your source in `pkg_source`, or overridden the **do_download()** or **Invoke-Download** callback, create a sha256 checksum for your source archive and enter it as the `pkg_shasum` value. The build script will verify this after it has downloaded the archive. > Note: If your computed value does not match the value calculated by the `hab-plan-build` script, an error with the expected value will be returned when you execute your plan. If your package does not download any application or service source files, then you will need to override the **do_download()**, **do_verify()**, and **do_unpack()** callbacks. See [Callbacks](../build_phase_callbacks/index) for more details. #### Define Your Dependencies Applications have two types of dependencies: buildtime and runtime. Declare any build dependencies in `pkg_build_deps` and any run dependencies in `pkg_deps`. You can include version and release information when declaring dependencies if your application is bound to a particular version. The package `core/glibc` is typically listed as a run dependency and `core/coreutils` as a build dependency, however, you should not take any inference from this. There are no standard dependencies that every package must have. For example, the mytutorialapp package only includes the `core/node` as a run dependency. You should include dependencies that would natively be part of the build or runtime dependencies your application or service would normally depend on. There is a third type of dependencies, transitive dependencies, that are the run dependencies of either the build or run dependencies listed in your plan. You do not need to explicitly declare transitive dependencies, but they are included in the list of files when your package is built. See [Package contents](../package_contents/index) for more information. #### Override Build Phase Defaults with Callbacks As shown in an example above, there are occasions when you want to override the default behavior of the hab-plan-build script. The Plan syntax guide lists the default implementations for [build phase callbacks](../build_phase_callbacks/index), but if you need to reference specific packages in the process of building your applications or services, then you need to override the default implementations as in the example below. ``` pkg_name=httpd pkg_origin=core pkg_version=2.4.18 pkg_maintainer="The Chef Habitat Maintainers <<EMAIL>>" pkg_license=('apache') pkg_source=http://www.apache.org/dist/${pkg_name}/${pkg_name}-${pkg_version}.tar.gz pkg_shasum=1c39b55108223ba197cae2d0bb81c180e4db19e23d177fba5910785de1ac5527 pkg_deps=(core/glibc core/expat core/libiconv core/apr core/apr-util core/pcre core/zlib core/openssl) pkg_build_deps=(core/patch core/make core/gcc) pkg_bin_dirs=(bin) pkg_lib_dirs=(lib) pkg_exports=( [port]=serverport ) pkg_svc_run="httpd -DFOREGROUND -f $pkg_svc_config_path/httpd.conf" pkg_svc_user="root" do_build() { ./configure --prefix=$pkg_prefix \ --with-expat=$(pkg_path_for expat) \ --with-iconv=$(pkg_path_for libiconv) \ --with-pcre=$(pkg_path_for pcre) \ --with-apr=$(pkg_path_for apr) \ --with-apr-util=$(pkg_path_for apr-util) \ --with-z=$(pkg_path_for zlib) \ --enable-ssl --with-ssl=$(pkg_path_for openssl) \ --enable-modules=most --enable-mods-shared=most make } ``` In this example, the `core/httpd` plan references several other core packages through the use of the `pkg_path_for` function before `make` is called. You can use a similar pattern if you need reference a binary or library when building your source files. Or consider this override from a plan.ps1: ``` function Invoke-Build { Push-Location "$PLAN_CONTEXT" try { cargo build --release --verbose if($LASTEXITCODE -ne 0) { Write-Error "Cargo build failed!" } } finally { Pop-Location } } ``` Here the plan is building an application written in Rust. So it overrides `Invoke-Build` and uses the `cargo` utility included in its buildtime dependency on `core/rust`. > Note: Powershell plan function names differ from their Bash counterparts in that they use the `Invoke` `verb` instead of the `do_` prefix. When overriding any callbacks, you may use any of the [variables](../plan_variables/index), [settings](../plan_settings/index), or [functions](../build_helpers/index), except for the [runtime template data](../service_templates/index). Those can only be used in Application Lifecycle hooks once a Chef Habitat service is running. ### Runtime Workflow Similar to defining the setup and installation experience at buildtime, behavior for your application or service needs to be defined for the Supervisor. This is done at runtime through Application lifecycle hooks. See [Application Lifecycle hooks](../application_lifecycle_hooks/index) for more information and examples. If you only need to start the application or service when the Chef Habitat service starts, you can instead use the `pkg_svc_run` setting and specify the command as a string. When your package is created, a basic run hook will be created by Chef Habitat. You can use any of the [runtime configuration settings](../service_templates/index), either defined by you in your config file, or defined by Chef Habitat. Once you are done writing your plan, use the studio to [build your package](../pkg_build/index). ### Related Resources * [Write plans](#writing-plans): Describes what a plan is and how to create one. * [Add configuration to plans](../config_templates/index): Learn how to make your running service configurable by templatizing configuration files in your plan. * [Binary-only packages](../binary_wrapper/index): Learn how to create packages from software that comes only in binary form, like off-the-shelf or legacy programs. You may also find the [settings](../plan_settings/index), [variables](../plan_variables/index), and [functions](../build_helpers/index) documentation useful when creating your plan. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/plan_writing/Service Group Configuration =========================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/service_group_configuration.md) Uploading Files to a Service Group ---------------------------------- In addition to [configuration updates](../service_updates/index), you can upload files to a service group. Keep these small - we recommend 4k or less per file, and keep the count of files to a minimum. ### Usage Use the [`hab file upload`](../habitat_cli/index#hab-file-upload) command to submit a file to a service group. Specify a peer in the ring to connect to, the version number of the file, and the new path to the file itself. Note File updates for service groups must be versioned. The version number must be an integer that starts at one and must be incremented with every subsequent update to the same service group. If the version number is less than or equal to the current version number, the change(s) will not be applied. The following example shows how to upload a file to the ring: ``` hab file upload myapp.prod 1 /tmp/yourfile.txt --remote-sup=hab1.mycompany.com ``` Your output would look something like this: ``` » Uploading file yourfile.txt to 1 incarnation myapp.prod Ω Creating service file ↑ Applying via peer 172.0.0.3:9632 ★ Uploaded file ``` The services in the `myapp.prod` service group will receive the file, restarting if necessary: ``` hab-sup(MR): Receiving new version 1 of file secret.txt for myapp.prod ... myapp.prod(SR): Service file updated, yourfile.txt ``` **Note**: Habitat will put the uplodaded file in your service’s `svc/files` directory. ### Encryption Files can be encrypted for the service group they are intended for. To do so, pass the `--user` option with the name of your user key, and the `--org` option with the organization of the service group. If you have the public key for the service group, the data will be encrypted for that key, signed with your user key, and sent to the ring. It will then be stored encrypted in memory, and decrypted on disk. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/service_group_configuration/Binary Wrapper Packages ======================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/binary_wrapper.md) While Chef Habitat provides the best behavior for applications that can be compiled from source into the Chef Habitat ecosystem, it can also bring the same management benefits to applications distributed in binary-only form. You can write plans to package up these binary artifacts with minimal special handling. This article covers some tips and tricks for getting this software into Chef Habitat. Override The Build Phases You Don’t Need ---------------------------------------- A Chef Habitat package build proceeds in phases: download, verification, unpacking (where you would also patch source code, if you had it), build, and finally installation. Each of these phases has [default behavior](../build_phase_callbacks/index) within the build system. When building binary packages, you override the behavior of phases that do not apply to you. At the very minimum, you must override the `do_build` and `do_install` phases, for example: ``` (...) do_build() { # relocate library dependencies here, if needed -- see next topic return 0 } do_install() { mkdir -p $pkg_prefix/bin cp $PLAN_CONTEXT/bin/hello_world $pkg_prefix/bin/hello_world chmod +x $pkg_prefix/bin/hello_world } ``` Relocate Hard-Coded Library Dependencies If Possible ---------------------------------------------------- On Linux, many binaries hardcode library dependencies to `/lib` or `/lib64` inside their ELF symbol table. Unfortunately, this means that Chef Habitat is unable to provide dependency isolation guarantees if packages are dependent on any operating system’s libraries in those directories. These Chef Habitat packages will also fail to run in minimal environments like containers built using `hab-pkg-export-docker`, because there will not be a `glibc` inside `/lib` or `/lib64`. > Note: On Windows, library dependency locations are not maintained in a binary file’s headers. See [this MSDN article](https://msdn.microsoft.com/library/windows/desktop/ms682586(v=vs.85).aspx) for a complete explanation of how Windows binaries are located. However, it’s typically sufficient to ensure that the dependent binaries are on the `PATH`. You should make sure to include all dependencies in the `pkg_deps` of a `plan.ps1` to ensure all of their respective `DLL`s are accessible by your application. Most binaries compiled in a full Linux environment have a hard dependency on `/lib/ld-linux.so` or `/lib/ld-linux-x86_64.so`. In order to relocate this dependency to the Chef Habitat-provided variant, which is provided by `core/glibc`, use the `patchelf(1)` utility within your plan: 1. Declare a build-time dependency on `core/patchelf` as part of your `pkg_build_deps` line. 2. Invoke `patchelf` on any binaries with this problem during the `do_install()` phase. For example: ``` patchelf --interpreter "$(pkg_path_for core/glibc)/lib/ld-linux-x86-64.so.2" \ "${pkg_prefix}/bin/somebinary" ``` 3. The binary may have other hardcoded dependencies on its own libraries that you may need to relocate using other flags to `patchelf` like `--rpath`. For example, Oracle Java provides additional libraries in `lib/amd64/jli` that you will need to relocate to the Chef Habitat location: ``` export LD_RUN_PATH=$LD_RUN_PATH:$pkg_prefix/lib/amd64/jli patchelf --interpreter "$(pkg_path_for core/glibc)/lib/ld-linux-x86-64.so.2" \ --set-rpath ${LD_RUN_PATH} "${pkg_prefix}/bin/java" ``` 4. For more information, please see the [patchelf](https://nixos.org/patchelf.html) documentation. Relocating library dependencies ------------------------------- In some situations it will be impossible for you to relocate library dependencies using `patchelf` as above. For example, if the version of `glibc` the software requires is different than that provided by an available version of `glibc` in a Chef Habitat package, attempting to `patchelf` the program will cause execution to fail due to ABI incompatibility. Your software vendor’s support policy might also prohibit you from modifying software that they ship you. In these situations, you will have to give up Chef Habitat’s guarantees of complete dependency isolation and continue to rely on the library dependencies provided by the host operating system. However, you can continue to use the features of the Chef Habitat Supervisor that provide uniform manageability across your entire fleet of applications. Fixing hardcoded interpreters ----------------------------- Binary packages often come with other utility scripts that have their interpreter, or “shebang”, line (first line of a script) hardcoded to a path that will not exist under Chef Habitat. Examples are: `#!/bin/sh`, `#!/bin/bash`, `#!/bin/env` or `#!/usr/bin/perl`. It is necessary to modify these to point to the Chef Habitat-provided versions, and also declare a runtime dependency in your plan on the corresponding Chef Habitat package (for example, `core/perl`). Use the `fix_interpreter` function within your plan to correct these interpreter lines during any phase, but most likely your `do_build` phase. For example: ``` fix_interpreter ${target} core/coreutils bin/env ``` The arguments to `fix_interpreter` are the file (represented here by `${target}`) you are trying to fix, the origin/name pair of the Chef Habitat package that provides that interpreter, and the interpreter pattern to search and replace in the target. If you have many files you need to fix, or the binary package automatically generates scripts with hardcoded shebang lines, you may need to simply symlink Chef Habitat’s version into where the binary package expects it to go: ``` ln -sv $(pkg_path_for coreutils)/bin/env /usr/bin/env ``` This is a last resort as it breaks the dependency isolation guarantees of Chef Habitat. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/binary_wrapper/Plan Contents ============= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/plan_contents.md) The following is a best practice guide to how to write a production quality plan. These best practices are reflected in the requirements for a user to contribute a plan to the Chef Habitat [Core Plans](https://github.com/habitat-sh/core-plans/). If you haven’t already, a good first step is to read [the Writing Plans](../plan_writing/index) documentation. Package Metadata ---------------- Each package plan should contain a value adhering to the guidelines for each of the following elements: * `pkg_description` * `pkg_license` (in [SPDX format](https://spdx.org/licenses/)) * `pkg_maintainer` in the format of “The Chef Habitat Maintainers [<EMAIL>](mailto:<EMAIL>)” * `pkg_name` see the section of this document on “Package Name Conventions” * `pkg_origin` must be set to `core` * `pkg_source` * `pkg_upstream_url` * `pkg_version` must be the complete version number of the software Package Name Conventions ------------------------ Each package is identified by a unique string containing four sub-strings separated by a forward slash (`/`) called a [PackageIdent](../pkg_ids/index). ``` `origin`/`name`/`version`/`release` ``` The `origin`, `name`, and `version` values of this identifier are user defined by setting their corresponding variable in your `plan.sh` or `plan.ps1` file while the value of `release` is generated at build-time. The value of `name` should exactly match the name of the project it represents and the plan file should be located within a directory of the same name in this repository. > Example: The plan for the [bison project](https://www.gnu.org/software/bison/) project contains setting `pkg_name=bison` and resides in `$root/bison/plan.sh`. Managing Major Versions ----------------------- There is one exception to this rule: Additional plans may be defined for projects for their past major versions by appending the major version number to its name. The plan file for this new package should be located within a directory of the same name. > Example: the [bison project](https://www.gnu.org/software/bison/) maintains the 2.x line along with their current major version (at time of writing: 3.x). A second plan is created as `bison2` and placed within a directory of the same name in this repository. Packages meeting this exception will always have their latest major version found in the package sharing the exact name of their project. A new package will be created for the previous major version following these conventions. > Example: the [bison project](https://www.gnu.org/software/bison/) releases the 4.x line and is continuing to support Bison 3.x. The `bison` package is copied to `bison3` and the `bison` package is updated to build Bison 4.x. Plan Basic Settings ------------------- You can read more about [basic plan settings](../plan_writing/index) here. The minimum requirements for a core plan are: * pkg_name is set * pkg_origin is set * pkg_shasum is set * pkg_description is set Callbacks --------- You can read more about [callbacks](../build_phase_callbacks/index) here. The minimum requirement for a core plan are: ### Callback Do’s * `do_prepare()` (`Invoke-Prepare` in a `plan.ps1`) is a good place to set environment variables and set the table to build the software. Think of it as a good place to do patches. * If you clone a repo from git, you must override `do_verify()` to `return 0` in a `plan.sh` or if you are authoring a `plan.ps1` then override `Invoke-Verify` with an empty implementation. ### Callback Don’t’s * Don’t call `exit` within a build phase. In a `plan.sh`, you should instead return an exit code such as `return 1` for failure, and `return 0` for success. In a `plan.ps1` you should call `Write-Exception` or `throw` an exception upon failure. * Don’t use `pkg_source` unless you are downloading something as a third party. * Don’t shell out to `hab` from inside of a callback. If you think you want to, you should use a [utility function](../plan_helpers/index) instead. * Don’t call any functions or helper sthat begin with an underscore, for example `_dont_call_this_function()`. Those are internal for internal builder functions and are not supported for external use. They will break your plan if you call them. * Don’t run any code or run anything outside of a build phase or a function. Application Lifecycle Hooks --------------------------- The Supervisor dynamically invokes hooks at run-time, triggered by an application lifecycle event. You can read more about [hooks](../application_lifecycle_hooks/index) here. ### Lifecycle Hook Do’s * Do redirect `stderr` to `stdout` (e.g. with `exec 2>&1` at the start of the hook) * Do call the command to execute with `exec <command> <options>` rather than running the command directly in a Linux targeted hook. This ensures the command is executed in the same process and that the service will restart correctly on configuration changes. * You can write to the `/var/`, `/static/`, and `/data/` directories. Access these with your `runtime configuration setting` variable. ### Lifecycle Hook Don’t’s * Don’t call `hab` or `sleep` in a hook that is not the `run` hook. You can only block the thread in a hook if it is in the `run` hook. * Don’t shell out to `hab` from within a hook. If you think you want to, you should use a [runtime configuration setting](../service_templates/index) instead. If none of those will solve your problem, open an issue and tell the core team why. * Don’t use `exec` if you’re running something with a pipe. It won’t work. * Don’t execute commands as a `root` user or try to `sudo hab pkg install`. * Don’t edit any of the Supervisor rendered templates. * Don’t edit anything in `/hab/` directly. * Don’t write to anything in `/hab/` directly. README.md --------- All plans need a `README.md`. Items to strongly consider including: * Your name as maintainer and supporter of this plan. * What Chef Habitat topology it uses (and the plan should have the correct topology for the technology). * Step-by-step instructions for how to use the package. * Describe the best update strategy for different deployments. * Describe the configuration updates a user can make and if a full rebuild is required. * Document how to scale the service. * Instructions for monitoring the health of the service at the application layer. * Describe how to call the package as an application dependency in an application. * Describe how to integrate package into an application. A repo of plans --------------- The best practice is to place all plan files within a `habitat` parent directory, which allows for a clean separation between your application source code and habitat specific files. However, if you maintain a separate repository solely for the purpose of storing habitat plans, then the use of a `habitat` folder may not be necessary. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/plan_contents/Service Groups ============== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/service_groups.md) A service group is a logical grouping of services with the same package and topology type connected together across a Supervisor network. They are created to share configuration and file updates among the services within those groups and can be segmented based on workflow or deployment needs (QA, Production, and so on). Updates can also be [encrypted](../sup_secure/index) so that only members of a specific service group can decrypt the contents. By default, every service joins the `service-name.default` service group unless otherwise specified at runtime. In addition, multiple service groups can reside in the same Supervisor network. This allows data exposed by Supervisors to be shared with other members of the ring, regardless of which group they are in. Joining a Service Group ----------------------- To join services together in a group, they must be running on Supervisors that are participating in the same Supervisor gossip network (i.e., they are ultimately peered together), and they must be using the same group name. To illustrate, we’ll show two `core/redis` services joining into the same group. First, we’ll start up two Supervisors on different hosts, peering the second one back to the first. ``` $ hab sup run # on 172.18.0.2 (Supervisor A) hab-sup(MR): Supervisor Member-ID e89b6616d2c040c8a82f475b00ba8c69 hab-sup(MR): Starting gossip-listener on 0.0.0.0:9638 hab-sup(MR): Starting ctl-gateway on 0.0.0.0:9632 hab-sup(MR): Starting http-gateway on 0.0.0.0:9631 ``` ``` $ hab sup run --peer=172.18.0.2:9638 # on 172.18.0.3 (Supervisor B) hab-sup(MR): Supervisor Member-ID bc8dc23243e44fee8ea7b9023073c28a hab-sup(MR): Starting gossip-listener on 0.0.0.0:9638 hab-sup(MR): Starting ctl-gateway on 0.0.0.0:9632 hab-sup(MR): Starting http-gateway on 0.0.0.0:9631 ``` Now, run the following on each Supervisor to load `core/redis` in the “prod” group: ``` hab svc load core/redis --group=prod ``` Each will start up, and will be joined into the same group; here is Supervisor A’s output: ![Supervisor A running Redis] And here is Supervisor B’s output: ![Supervisor B running Redis] Note that they are both listening on the same port. To prove they are in the same group, we can apply a configuration change; if they are in the same group, they should both receive the change. Let’s change the port they’re running on using the `hab config apply` command, run from Supervisor A. ``` echo 'port = 2112' | hab config apply redis.prod 1 ``` Both service instances restart with the new configuration. Supervisor A’s output is: ![Supervisor A running Redis on a new port] and Supervisor B’s output is: ![Supervisor B running Redis on a new port] Note that they have both restarted (as evidenced by the new PID values), and that both are now running on port 2112, as we instructed. Had the services been in different groups, the configuration change would not have applied to both of them (it was targeted at `redis.prod`). If the Supervisors has not been in gossip communication (achieved here through the use of the `--peer` option when Supervisor B was started), the configuration rumor (injected into Supervisor A’s gossip network) would not have made it to `core/redis` service running on Supervisor B. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/service_groups/Service Group Topologies ======================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/service_group_topologies.md) A topology describes the intended relationship between peers within a service group. Two topologies ship with Chef Habitat by default: **standalone** and **leader-follower**. The leader-follower topology employs [leader election](../sup_crypto/index) to define a leader. Standalone ---------- The standalone topology is what a Supervisor starts with by default if no topology is specified, or if the topology is explicitly specified with `--topology standalone` when starting the Supervisor. The standalone topology means that the service group members do not have any defined relationship with one another, other than sharing the same configuration. Leader-follower Topology ------------------------ In a leader-follower topology, one of the members of the service group is elected the leader, and the other members of that service group become the followers of that leader. This topology is common for database systems like MySQL or PostgreSQL, where applications send writes to one member, and those writes are replicated to one or more read replicas. As with any topology using leader election, you must start at least three peers using the `--topology leader` flag to the Supervisor. ``` hab sup run --topology leader --group production hab svc load <ORIGIN>/<NAME``` The first Supervisor will block until it has quorum. You would start additional members by pointing them at the ring, using the `--peer` argument: ``` hab sup run --topology leader --group production --peer 192.168.5.4 hab svc load <ORIGIN>/<NAME``` Note The `--peer` service does not need a peer that is in the same service group; it merely needs to be in the same ring with the other member(s). Once you have quorum, one member is elected a leader, the Supervisors in the service group update the service’s configuration in concordance with the policy defined at package build time, and the service group starts up. ### Defining Leader and Follower Behavior in Plans Chef Habitat allows you to use the same immutable package in different deployment scenarios. In this example, a configuration template with conditional logic will make the running application to behave differently based on whether it is a leader or a follower: ``` {{#if svc.me.follower}} {{#with svc.leader as |leader|}} replicaof {{leader.sys.ip}} {{leader.cfg.port}} {{/with}} {{/if}} ``` This logic says that if this peer is a follower, it will become a read replica of the IP and port of service leader (`svc.leader`), which is found by service discovery through the ring. However, if this peer is the leader, the entire list of statements here evaluate to empty text – meaning that the peer starts up as the leader. Robustness, Network Boundaries and Recovering from Partitions ------------------------------------------------------------- Within a leader-follower topology, it is possible to get into a partitioned state where nodes are unable to achieve quorum. To solve this, use a permanent peer to heal the netsplit. Pass the `--permanent-peer` option, or it’s short form `-I`, to make a Supervisor act as a permanent peer. ``` hab sup run --topology leader --group production --permanent-peer hab svc load <ORIGIN>/<NAME``` When a Supervisor is instructed to act as a permanent peer, the other Supervisors will attempt to connect with the permanent peer and achieve quorum even if the permanent peer is confirmed to be dead. The notion of a permanent peer is an extension to the original [SWIM](http://www.cs.cornell.edu/projects/Quicksilver/public_pdfs/SWIM.pdf) gossip protocol. It can add robustness provided everyone has a permanent member on both sides of the split. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/service_group_topologies/About Services ============== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/about_services.md) A service is a Chef Habitat package running under a Chef Habitat Supervisor. Service Group ------------- A service group is a set of one or more running services with a shared configuration and topology. If a service is started without explicitly naming the group, it is assigned to the default group for the name of that package. For example: * `redis.default` * `postgres.financialdb` (possibly running in a cluster) * `postgres.userdb` (possibly running in a cluster) Topology -------- Chef Habitat allows you to define the topology of your service groups, which bakes in certain behaviors. ### Standalone This is the default topology, useful for services inside a group that are completely independent from one another. Note that this still means they can share the same configuration. ### Leader / Follower This topology allows a distributed application running on at least three Chef Habitat nodes to use a leader/follower configuration. Leaders are elected with Chef Habitat’s leader election algorithm, and followers are restarted to reflect a configuration that follows the new leader. Subsequent elections due to leader failure will update both leader and follower configuration data. You can read more about the internals behind the elections in our [advanced developer documentation](../sup_crypto/index#leader-election). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/about_services/Service Group Updates ===================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/service_group_updates.md) The Chef Habitat Supervisor can be configured to leverage an optional *update strategy*, which describes how the Supervisor and its peers within a service group should respond when a new version of a package is available. To use an update strategy, configure the Supervisor to subscribe to Chef Habitat Builder, and more specifically, a channel for new versions. Configuring an Update Strategy ------------------------------ Chef Habitat supports three update strategies: `none`, `rolling`, and `at-once`. To start a Supervisor with the auto-update strategy, pass the `--strategy` argument to a Supervisor run command, and optionally specify the depot URL: ``` hab sup run --strategy rolling --url https://bldr.habitat.sh hab svc load <ORIGIN>/<NAME``` ### None Strategy This strategy means your package will not automatically be updated when a newer version is available. By default, Supervisors start with their update strategy set to `none` unless explicitly set to one of the other two update strategies. ### Rolling Strategy This strategy requires Supervisors to update to a newer version of their package one at a time in their service group. An update leader is elected which all Supervisors within a service group will update around. All update followers will first ensure they are running the same version of a service that their leader is running, and then the leader will poll Builder for a newer version of the service’s package. Once the update leader finds a new version, it will update and wait until all other alive members in the service group have also been updated before once again attempting to find a newer version of software to update to. Updates will happen more or less one at a time until completion with the exception of a new node being introduced into the service group during the middle of an update. If your service group is also running with the `--topology leader` flag, the leader of that election will never become the update leader, so all followers within a leader topology will update first. It’s important to note that because we must perform a leader election to determine an update leader, *you must have at least 3 Supervisors running a service group to take advantage of the rolling update strategy*. ### At-Once Strategy This strategy does no peer coordination with other Supervisors in the service group; it merely updates the underlying Chef Habitat package whenever it detects that a new version has either been published to a depot or installed to the local Chef Habitat `pkg` cache. No coordination between Supervisors is done, each Supervisor will poll Builder on their own. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/service_group_updates/Single Service Updates ====================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/service_updates.md) One of the key features of Chef Habitat is the ability to define an immutable package with a default configuration which can then be updated dynamically at runtime. You can update service configuration on two levels: individual services (for testing purposes), or a service group. Apply Configuration Updates to an Individual Service ---------------------------------------------------- When starting a single service, you can provide alternate configuration values to those specified in `default.toml`. ### Using a *user.toml* File You can supply a `user.toml` containing any configuration data that you want to override default values. This file should be placed in the Chef Habitat `user` directory under the `config` subdirectory of the specific service directory that owns the configuration data. For example, to override the default configuration of the `myservice` service, this `user.toml` would be located at `/hab/user/myservice/config/user.toml`. ### Using an Environment Variable Override default configuration data through the use of an environment variable with the following format: ``` HAB_PACKAGENAME='{"keyname1":"newvalue1", "tablename1":{"keyname2":"newvalue2"}}' ``` ``` HAB_MYTUTORIALAPP='{"message":"Chef Habitat rocks!"}' hab run <origin>/<packagename``` Note The syntax used for applying configuration through environment variables can be either JSON or TOML, but TOML is preferred. The package name in the environment variable must be uppercase, any dashes must be replaced with underscores. Note Variables must be set when the Supervisor process starts, not when the service is loaded, which may require a bit of planning on the part of the Chef Habitat user. For multiline environment variables, such as those in a TOML table or nested key value pairs, it can be easier to place your changes in a file and pass the file in. For example: ``` HAB_MYTUTORIALAPP="$(cat my-env-stuff.toml)" hab run hab svc load <origin>/mytutorialapp ``` Or, for [testing scenarios and containerized workflows](../sup_run/index#starting-the-supervisor): ``` HAB_MYTUTORIALAPP="$(cat my-env-stuff.toml)" hab run <origin>/mytutorialapp ``` The main advantage of applying configuration updates to an individual service through an environment variable is that you can quickly test configuration settings to see how your service behaves at runtime. The disadvantages of this method are that configuration changes have to be applied when the Supervisor itself starts up, and you have to restart a running Supervisor (and thus, all services it may be running) in order to change these settings again. Apply Configuration Updates to all Services in a Service Group -------------------------------------------------------------- Similar to specifying updates to individual settings at runtime, you can apply multiple configuration changes to an entire service group at runtime. These configuration updates can be sent in the clear or encrypted in gossip messages through [wire encryption](../sup_secure/index). Configuration updates to a service group will trigger a restart of the services as new changes are applied throughout the group. ### Usage When submitting a configuration update to a service group, you must specify the following: * a Supervisor to connect to * the version number of the configuration update * the new configuration Configuration updates can be either TOML passed into stdin, or passed in a TOML file that is referenced in [`hab config apply`](../habitat_cli/index#hab-config-apply). Note Configuration updates for service groups must be versioned. The version number must be an integer that starts at one and must be incremented with every subsequent update to the same service group. *If the version number is less than or equal to the current version number, the change(s) will not be applied.* Here are some examples of how to apply configuration changes through both the shell and through a TOML file. **Stdin** ``` echo 'buffersize = 16384' | hab config apply --remote-sup=hab1.mycompany.com myapp.prod 1 ``` **TOML file** ``` hab config apply --remote-sup=hab1.mycompany.com myapp.prod 1 /tmp/newconfig.toml ``` Your output would look something like this: ``` » Setting new configuration version 1 for myapp.prod Ω Creating service configuration ↑ Applying via peer 172.18.0.2:9632 ★ Applied configuration ``` The services in the myapp.prod service group will restart. ``` myapp.prod(SR): Service configuration updated from butterfly: acd2c21580748d38f64a014f964f19a0c1547955e4c86e63bf641a4e142b2200 hab-sup(SC): Updated myapp.conf a85c2ed271620f895abd3f8065f265e41f198973317cc548a016f3eb60c7e13c myapp.prod(SV): Stopping ... myapp.prod(SV): Starting ``` Note As with all Supervisor interaction commands, if you do not specify `--remote-sup`, `hab config apply` will attempt to connect to a Supervisor running on the same host. ### Encryption Configuration updates can be encrypted for the service group they are intended. To do so, pass the `--user` option with the name of your user key, and the `--org` option with the organization of the service group. If you have the public key for the service group, the data will be encrypted for that key, signed with your user key, and sent to the ring. It will then be stored encrypted in memory, and decrypted on disk. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/service_updates/Monitoring Services =================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/monitor_services.md) Use the HTTP API to monitor services. When a service starts, the [Supervisor](../sup_networks/index) exposes the status of its services' health and other information through an HTTP API endpoint. This information can be useful in monitoring service health, results of leader elections, and so on. Authentication -------------- The Supervisor currently supports simple HTTP authentication using Bearer tokens. By default, no authentication is used. If you would like to require authentication, export the `HAB_SUP_GATEWAY_AUTH_TOKEN` environment variable before starting the Supervisor. All HTTP requests will then require that same token to be present in an Authorization header, or they will receive a 401 Unauthorized response. Endpoints --------- The HTTP API provides information on the following endpoints: * `/butterfly` - Debug information about the rumors stored via Butterfly. * `/census` - Returns the current Census of Services on the Ring (roughly what you see as a service in config.toml). * `/services` - Returns an array of all the services running under this Supervisor. * `/services/{name}/{group}` - Returns the information of a single loaded service. * `/services/{name}/{group}/config` - Returns this service group’s current configuration. * `/services/{name}/{group}/health` - Returns the current health check for this service. * `/services/{name}/{group}/{organization}` - Returns information of a single loaded service scoped to an organization * `/services/{name}/{group}/{organization}/config` - Returns the service group’s current configuration, but includes the organization. * `/services/{name}/{group}/{organization}/health` - Same as above, but includes the organization. ### Errors Most of the HTTP API endpoint return these errors: | Error | Description | | --- | --- | | 404 | Service not loaded | | 503 | Supervisor hasn’t fully started. Try again later. | The `/health` endpoints return: | Error | Description | | --- | --- | | 404 | Service not loaded | | 500 | Health Check - Unknown | | 503 | Health Check - Critical | Usage ----- Connect to the Supervisor of the running service using the following syntax. This example uses `curl` to do the GET request. ``` curl http://172.17.0.2:9631/services ``` **Note**: The default listening port on the Supervisor is 9631; however, you can change the listening port by using the `--listen-http` option when starting a service. Depending on the endpoint you hit, the data may be formatted in JSON, TOML, or plain text. ### Example ``` $ HAB_SUP_GATEWAY_AUTH_TOKEN="sekret" hab sup run hab-sup(MR): Supervisor Member-ID e89b6616d2c040c8a82f475b00ba8c69 hab-sup(MR): Starting gossip-listener on 0.0.0.0:9638 hab-sup(MR): Starting ctl-gateway on 0.0.0.0:9632 hab-sup(MR): Starting http-gateway on 0.0.0.0:9631 ``` ``` $ curl -v http://172.17.0.2:9631/services * Trying 172.17.0.2... * TCP_NODELAY set * Connected to 172.17.0.2 (172.17.0.2) port 9631 (#0) > GET /services HTTP/1.1 > Host: 172.17.0.2:9631 > User-Agent: curl/7.54.0 > Accept: */* > < HTTP/1.1 401 Unauthorized < content-length: 0 < date: Thu, 15 Nov 2018 22:39:41 GMT < * Connection #0 to host 172.17.0.2 left intact ``` ``` $ curl -v -H "Authorization: Bearer sekret" http://172.17.0.2:9631/services * Trying 172.17.0.2... * TCP_NODELAY set * Connected to 172.17.0.2 (172.17.0.2) port 9631 (#0) > GET /services HTTP/1.1 > Host: 172.17.0.2:9631 > User-Agent: curl/7.54.0 > Accept: */* > Authorization: Bearer sekret > < HTTP/1.1 200 OK < content-length: 2 < content-type: application/json < date: Thu, 15 Nov 2018 22:41:42 GMT < * Connection #0 to host 172.17.0.2 left intact [] ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/monitor_services/Chef Habitat Supervisor ======================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup.md) The Supervisor is a process manager that has two primary responsibilities. First, it starts and monitors child services defined in the plan it is running. Second, it receives and acts upon information from the other Supervisors to which it is connected. A service will be reconfigured through application lifecycle hooks if its configuration has changed. The Supervisor Ring ------------------- Supervisors typically run in a network, which we refer to as a *ring* (although it is more like a peer-to-peer network rather than a circular ring). The ring can be very large; it could contain hundreds or thousands of supervisors. The membership list of this ring is maintained independently by each Supervisor and is known as the *census*. Census ------ The census is the core of the service discovery mechanism in Chef Habitat. It keeps track of every Supervisor in the ring, and handles reading, writing, and serializing it with the discovery backend. Each Supervisor in the system is a *census entry* that together form a *census*. Operations to discover or mutate the state of the census happen through algorithms that arrive at the same conclusion given the same inputs. An example is leader election: it’s handled here by having a consistent (and simple) algorithm for selecting a leader deterministically for the group. We rely on the eventual consistency of every Supervisor’s census entry to elect a new leader in a reasonable amount of time. Supervisor REST API ------------------- The Chef Habitat Supervisor provides a HTTP API to expose cluster metadata, statistics, and general diagnostic information useful for monitoring and support in the form of a JSON document. It also provides detailed information about the Chef Habitat package that it is supervising, including metadata such as the build and runtime dependencies and their versions. Control Gateway --------------- The Supervisor control gateway is used to issue commands to a remote Supervisor. When a new Supervisor is created, a key for the `HAB_CTL_SECRET` environment variable is generated for it by default, if one is not already present; this key is used to authenticate requests that are made via the control gateway. See the [control gateway](../keys/index#control-gateway) documentation for more details. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup/Setting Up a Ring ================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_rings.md) Bastion Ring / Permanent Peers ------------------------------ A “Bastion Ring” is a pattern for preventing rumor loss and a split brain in a network of Chef Habitat Supervisors - it is highly recommended for any real environment use case. Create a minimum of 3 Supervisors and join them together. They should not run any services and they should be marked as permanent peers - their only job is to spread rumors to each other. Then, when you provision additional Supervisors pass the network address of each Supervisor running in the Bastion Ring to the `--peer` argument of `hab sup run`. It’s recommended to create a Bastion Ring in any network zones which may become partitioned due to a hardware failure. For example, if you have a Chef Habitat ring spanning multiple data centers and clouds, each should have a bastion ring of a minimum of 3 Supervisors in addition to the Supervisors running your services. Using a Scheduler ----------------- **Note:** If you are using a container scheduler such as the Kubernetes `kube-scheduler`, Docker Swarm mode, Mesos DC/OS’s Marathon or Chronos, or a PaaS such as Cloud Foundry, you should not follow the bastion ring pattern, because the scheduler handles persistence and orchestration on your behalf. More resources on schedulers: * [Chef Habitat Container Orchestration](../container_orchestration/index) * Kubernetes `kube-scheduler`: <https://kubernetes.io/docs/concepts/scheduling-eviction/kube-scheduler> * Docker Swarm mode: <https://docs.docker.com/engine/swarm> * Mesos DC/OS Marathon or Chronos: <https://mesosphere.github.io/marathon/> * Cloud Foundry: <https://www.habitat.sh/get-started/cloudfoundry Initial Peer(s) --------------- The initial peer(s) is a requirement of any distributed system. In Chef Habitat, a new Supervisor that is starting up looks for an initial peer(s) to join to begin sharing information about the health and status of peers and other services, to increase the health of the overall Ring. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_rings/Running Chef Habitat Supervisors ================================ [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_run.md) Use Chef Habitat packages to start services under the Chef Habitat Supervisor. At runtime, you can join services together in a service group running the same topology, send configuration updates to that group, and more. You can also export the Supervisor together with the package to an external immutable format, such as a Docker container or a virtual machine. > Note Linux-based packages can run on Linux distributions running kernel 2.6.32 or later. Windows-based packages can run on Windows Server 2012 or later and Windows 8 64-bit or later. Information about [installing Chef Habitat](../install_habitat/index) and configuring your workstation can be found in the previous section. Starting the Supervisor ----------------------- In order to run a Chef Habitat-packaged service, you must first run a Chef Habitat Supervisor. There are two ways to start up a Supervisor, and it is important to know the implications of each, and which method is appropriate for your circumstances. These instructions describe the behavior of the 0.56.0 Supervisor and later, which dramatically simplified how Supervisors start up. These instructions also deal with the Supervisor “by itself”; later on, we’ll see how to integrate it into different operational scenarios (e.g., SystemD, Windows Services, etc.). It is useful to understand the underlying concepts first. For further details about these commands, including all the arguments and options they take, please consult [the hab documentation](../habitat_cli/index). hab sup run Executing `hab sup run` will start a Supervisor process in the foreground. If this is the first time a Supervisor has been run on the system, nothing else will happen; the process will be waiting for the user to “load” services into it. However, if this is *not* the first time the Supervisor has been run, any previously loaded services that were not “stopped” (i.e., told not to run) will be started up as well. When executing `hab sup run`, additional options can be passed that allow the Supervisor to communicate with other Supervisors (such as `--peer`, `--permanent-peer`, etc.), forming a connected network of Supervisors; this is the communication backbone that any services running on the Supervisors use to communicate with each other. hab sup run <PACKAGE_IDENTIFIER> When you pass a package identifier (e.g., `core/redis`) as an argument to `hab sup run`, it will start up a Supervisor process, and then load and start the given package in what is effectively a single operation. This is a convenience that is intended primarily for container entry-point workflows, where a single defined service is the only thing ever intended to run on the Supervisor, but it can also be used for local testing or experimentation. This version of `hab sup run` can also accept options that affect how the *package* should run, such as `--strategy` and `--topology`, in addition to the aforementioned Supervisor-specific options. It can be thought of as running the identifier-less `hab sup run`, along with a `hab sup load`, all as a single command. ### Selecting a startup method In most cases, you should always start up a Supervisor explicitly, using `hab sup run` *without* a package identifier argument, *especially* in production environments. The `<PACKAGE_IDENTIFIER>` invocation mixes Supervisor-specific and service-specific options, it can sometimes be difficult to reason about, depending on how complex your usecase is. As a result, that form should be limited to constrained container-based usecases, and perhaps local simple testing or evaluation scenarios. Additionally, since a Supervisor has state – the services it is manages – you may end up starting additional services, depending on what you’ve done in the past on the same machine. That is, `hab sup run <PACKAGE_IDENTIFIER>` is not, in general, synonymous with “only run this single service”. For all other uses, it is far preferable to start a Supervisor using the identifier-less `hab sup run` invocation, and manage the population of services it runs using `hab svc load` and other commands. Throughout this documentation, unless otherwise explicitly stated, assume that a Supervisor has been started with `hab sup run`, and that any services were loaded using a separate `hab svc load` invocation. Testing a package locally ------------------------- Packages can be tested in the interactive studio environment or natively on a workstation running Linux or Windows. When entering an interactive studio, a Supervisor is started for you in the background by default. To run packages inside of this Supervisor: 1. [Build a package](../pkg_build/index) inside an interactive studio. Do not exit the studio after it is built. 2. To start your service in the running Supervisor, type `hab svc load yourorigin/yourname`, substituting the name and origin of the package you built in Step 1. Your service should now be running. Because the Supervisor is running in the background, you will not see the Supervisor output as you start your service. However you can use the `sup-log` (or `Get-SupervisorLog` on Windows) command that will stream the tail of the Supervisor output (you can also look at the contents of `/hab/sup/default/sup.log`, which is where the Studio directs its Supervisor output). If your host machine is running Linux, do the following to run your packages for one-off evaluations (not production uses!): * Add the `hab` user and group. ``` $ sudo adduser --group hab $ sudo useradd -g hab hab ``` * Run the `hab` Supervisor as root. ``` $ sudo hab sup run yourorigin/yourname ``` You may use the same `hab run` command on Windows but omit the `sudo` command. However, you should be inside of an elevated shell. Also, note that the `hab` user is not necessary on Windows. If it is absent, services will run under the identity of the current user. If a `hab` user is present, you will need to provide its password via the`--password` argument: ``` PS C:\> $cred = Get-Credential hab PS C:\> hab sup run yourorigin/yourname --password $cred.GetNetworkCredential().Password ``` In all cases, you may wish to run `hab svc unload <yourorigin>/<yourname>` when you are done working with your package, to remove it from the Supervisor. Otherwise, your Supervisor will try to start your service each time it start up. For more structured ways of running the Chef Habitat Supervisor on servers, please see [Running Chef Habitat on Servers](../running_habitat_servers/index). Loading a Service ----------------- To load a service into a Supervisor, you use the `hab svc load` subcommand. As an example, to load `yourorigin/yourname` in a Leader topology, with a Rolling update strategy, and a Group of “acme”, run the following: ``` $ hab svc load yourorigin/yourname --topology leader --strategy rolling --group acme ``` Running the `hab svc load` subcommand multiple times with different package identifiers will result in multiple services running on the same Supervisor. Let’s add `core/redis` to the Supervisor for some fun: ``` $ hab svc load core/redis ``` Unloading a Service ------------------- To remove a service from a Supervisor, you use the `hab svc unload` subcommand. If the service is was running, then it will be stopped first, then removed. This means that the next time the Supervisor is started (or restarted), it will not run this unloaded service. For example, to remove the `yourorigin/yourname` service: ``` $ hab svc unload yourorigin/yourname ``` Stopping a Running Service -------------------------- Sometimes you need to stop a running service for a period of time, for example during a maintenance outage. Rather than completely removing a service from supervision, you can use the `hab svc stop` subcommand which will shut down the running service and leave it in this state until you start it again with the `hab svc start` subcommand, explained next. This means that all service-related options such as service topology, update strategy, etc. are preserved until the service is started again. For example, to stop the running `core/redis` service: ``` $ hab svc stop core/redis ``` Restarting a Stopped Service ---------------------------- To resume running a service which has been loaded but stopped (via the `hab svc stop` subcommand explained above), you use the `hab svc start` subcommand. Let’s resume our `core/redis` service with: ``` $ hab svc start core/redis ``` > Note: in Chef Habitat versions prior to 0.56.0, `hab svc start` could also be used to load up a service if it wasn’t already loaded. In 0.56.0 and later, however, this has changed; `hab svc start` can only operate on services that have previously been loaded. Querying the Supervisor for Service Status ------------------------------------------ You can query all services currently loaded or running under the local Supervisor using the `hab svc status` command. This command will list all services loaded by the Supervisor along with their current state. The `status` command includes the version and release of the service and for services that are running, it will include the `PID` of the running service. To retrieve status for an individual service, you can pass the service identifier: ``` $ hab svc status core/mysql ``` The following exit codes are emitted by the `status` command: * `0` - The status command successfully reports status on loaded services * `1` - A generic error has occurred calling the `hab` cli * `2` - A service identifier was passed to `hab svc status` and that service is not loaded by the Supervisor * `3` - There is no local running Supervisor © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_run/Leader Elections ================ [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_elections.md) The Chef Habitat Supervisor performs leader election natively for service groups [topologies](../service_group_topologies/index) that require one, such as *leader-follower*. Because Chef Habitat is an eventually-consistent distributed system, the role of the leader is different than in strongly-consistent systems. It only serves as the leader for *application level semantics*, e.g. a database write leader. The fact that a Supervisor is a leader has no bearing upon other operations in the Chef Habitat system, including rumor dissemination for configuration updates. It is *not* akin to a [Raft](https://raft.github.io/) leader, through which writes must all be funneled. This allows for very high scalability of the Chef Habitat Supervisor ring. Services grouped using a leader need to have a minimum of three supervisors in order to break ties. It is also strongly recommended that you do not run the service group with an even number of members. Otherwise, in the event of a network partition with equal members on each side, both sides will elect a new leader, causing a full split-brain from which the algorithm cannot recover. Supervisors in a service group will warn you if you are using leader election and have an even number of supervisors. ### Protocol for electing a leader When a service group starts in a leader topology, it will wait until there are sufficient members to form a quorum (at least three). At this point, an election cycle can happen. Each Supervisor injects an election rumor into ring, targeted at the service group, with the *exact same* rumor, which demands an election and insists that the peer itself is the leader. This algorithm is known as [Bully](https://en.wikipedia.org/wiki/Bully_algorithm). Every peer that receives this rumor does a simple lexicographic comparison of its GUID with the GUID of the peer contained in that rumor. The winner is the peer whose GUID is higher. The peer then adds a vote for the GUID of the winner, and shares the rumor with others, including the total number of votes of anyone who previously voted for this winner. An election ends when a candidate peer X gets a rumor back from the ring saying that it (X) is the winner, with all members voting. At this point, it sends out a rumor saying it is the declared winner, and the election cycle ends. ### Related reading * For more information about the Bully algorithm, see [Elections in a Distributed Computing System](http://dl.acm.org/citation.cfm?id=1309451) by <NAME>. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_elections/Running Chef Habitat on Servers (Linux and Windows) =================================================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/running_habitat_servers.md) Chef Habitat can be run on bare metal servers, as well as virtual machines. Currently, Chef Habitat can run on Linux and Windows platforms, and in all cases, running a Supervisor boils down to running `hab sup run`. How that happens depends on which platform you choose to use. Running Chef Habitat on Linux ----------------------------- First, you must [install Chef Habitat](../install_habitat/index) itself on the machine. Second, many packages default to running as the `hab` user, so you should ensure that both a `hab` user and group exist: ``` sudo groupadd hab sudo useradd -g hab hab ``` Finally, you will need to wire Chef Habitat up to your systems init system. This may be SysVinit, SystemD, runit, etc. The details will be different for each system, but in the end, you must call `hab sup run`. ### Running under SystemD A basic SystemD unit file for Chef Habitat might look like this. This assumes that you have already created the `hab` user and group, as instructed above, and that your `hab` binary is linked to `/bin/hab`. ``` [Unit] Description=The Chef Habitat Supervisor [Service] ExecStart=/bin/hab sup run [Install] WantedBy=default.target ``` Depending on your needs and deployment, you will want to modify the options passed to `hab sup run`. In particular, if you wish to participate in larger Supervisor networks, you will need to pass at least one `--peer` option. Running Chef Habitat on Windows ------------------------------- As with Linux, you must first [install Chef Habitat](../install_habitat/index) on the machine. Unlike Linux, however, the Windows Supervisor has no requirements for any `hab` user. On Windows, you can run the Supervisor as a Windows Service. You can use the `windows-service` Chef Habitat package to host the Supervisor inside the Windows Service Control Manager: ``` hab pkg install core/windows-service ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/running_habitat_servers/Supervisor Design ================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_design.md) This section will dive into the implementation details of important Chef Habitat components. These topics are for advanced users. It is not necessary to learn these concepts in order to use Chef Habitat. The Chef Habitat Supervisor is similar in some ways to well-known process supervisors like [systemd](https://www.freedesktop.org/wiki/Software/systemd/), [runit](http://smarden.org/runit/) or [smf](https://en.wikipedia.org/wiki/Service_Management_Facility). It accepts and passes POSIX signals to its child processes, restarts child processes if and when they fail, ensures that children processes terminate cleanly, and so on. Because the basic functionality of process supervision is well-known, this document does not discuss those details. Instead, this document focuses strictly on the internals of the feature that makes the Chef Habitat Supervisor special: the fact that each Supervisor is connected to others in a peer-to-peer network which we refer to as a *ring*. This allows Supervisors to share configuration data with one another and adapt to changing conditions in the ring by modifying their own configuration. Important Terms --------------- Members The Butterfly keeps track of “members”; each Chef Habitat Supervisor is a single member. Peer All the members a given member is connected to are its “peers”. A member is seeded with a list of “initial peers”. Health The status of a given member, from the perspective of its peers. Rumor A piece of data shared with all the members of a ring; examples are election, membership, services, or configuration. Heat How many times a given rumor has been shared with a given member Ring All the members connected to one another form a Ring Incarnation A counter used to determine which message is “newer” Supervisor Internals -------------------- The Chef Habitat Supervisor is similar in some ways to well-known process supervisors like [systemd](https://www.freedesktop.org/wiki/Software/systemd/), [runit](http://smarden.org/runit/) or [smf](https://en.wikipedia.org/wiki/Service_Management_Facility). It accepts and passes POSIX signals to its child processes, restarts child processes if and when they fail, ensures that children processes terminate cleanly, and so on. Because the basic functionality of process supervision is well-known, this document does not discuss those details. Instead, this document focuses strictly on the internals of the feature that makes the Chef Habitat Supervisor special: the fact that each Supervisor is connected to others in a peer-to-peer network which we refer to as a *ring*. This allows Supervisors to share configuration data with one another and adapt to changing conditions in the ring by modifying their own configuration. Architecture ------------ Supervisors are configured to form a network by using the `--peer` argument and pointing them at peers that already exist. In a real-life deployment scenario, Supervisors in a network may also have a shared encryption key, so that inter-Supervisor traffic is encrypted. (See the [security](../keys/index) documentation for more details.) Supervisor rings can be very large, comprising thousands of supervisors. The Supervisor communication protocol is low-bandwidth and designed to not interfere with your application’s actual production traffic. Rings are divided into *service groups*, each of which has a name. All Supervisors within a service group share the same configuration and topology. ### Butterfly Chef Habitat uses a gossip protocol named “Butterfly”. This protocol provides failure detection, service discovery, and leader election to the Chef Habitat Supervisor. Butterfly is an eventually consistent system - it says, with a very high degree of probability, that a given piece of information will be received by every member of the network. It makes no guarantees as to when that state will arrive; in practice, the answer is usually “quite quickly”. ### Transport Protocols Supervisors communicate with each other using UDP and TCP, both using port 9638. ### Information Security Butterfly encrypts traffic on the wire using Curve25519 and a symmetric key. If a ring is configured to use transport level encryption, only members with a matching key are allowed to communicate. Service Configuration and Files can both be encrypted with public keys. ### Membership and Failure Detection Butterfly servers keep track of what members are present in a ring, and are constantly checking each other for failure. #### Health States Ring members have one of four health states: Alive This member is responding to health checks. Suspect This member has stopped responding to our health check, and will be marked confirmed if we do not receive proof it is still alive soon. Confirmed This member has been un-responsive long enough that we can cease attempting to check its health. Departed This member has been intentionally kicked out of the ring for behavior unbecoming of a Supervisor, and is prevented from rejoining. This is accomplished with `hab` CLI commands. #### Failure Detection The essential flow for detecting a failure is: 1. Randomize the list of all known members who are not Confirmed or Departed. 2. Every 3.1 seconds, pop a member off the list, and send it a “PING” message. 3. If we receive an “ACK” message before 1 second elapses, the member remains Alive. 4. If we do not receive an “ACK” in 1 second, choose 5 peers (the “PINGREQ targets”), and send them a “PINGREQ(member)” message for the member who failed the PING. 5. If any of our PINGREQ targets receive an ACK, they forward it to us, and the member remains Alive. 6. If we do not receive an ACK via PINGREQ with 2.1 seconds, we mark the member as Suspect, and set an expiration timer of 9.3 seconds. 7. If we do not receive an Alive status for the member within the 9.3 second suspicion expiration window, the member is marked as Confirmed. 8. Move on to the next member, until the list is exhausted; start the process again. When a Supervisor sends the PING, ACK and PINGREQ messages, it includes information about the 5 most recent members. This enables membership to be gossiped through the failure protocol itself. This process provides several nice attributes: * It is resilient to partial network partitions. * Due to the expiration of suspected members, confirmation of death spreads quickly. * The amount of network traffic generated by a given node is constant, regardless of network size. * The protocol uses single UDP packets which fit within 512 bytes. ### Gossip Butterfly uses ZeroMQ to disseminate rumors throughout the network. Its flow: * Randomize the list of all known members who are not Confirmed dead. * Every second, take 5 members from the list. * Send each member every rumor that has a Heat lower than 3; update the heat for each rumor sent. * When the list is exhausted, start the loop again. Whats good about this system: * ZeroMQ provides a scalable PULL socket, that processes incoming messages from multiple peers as a single fair-queue. * It has no back-chatter - messages are PUSH-ed to members, but require no receipt acknowledgement. * Messages are sent over TCP, giving them some durability guarantees. * In common use, the gossip protocol becomes inactive; if there are no rumors to send to a given member, nothing is sent. Butterfly and SWIM ------------------ The Butterfly protocol is a variant of [SWIM](https://prakhar.me/articles/swim) for membership and failure detection (over UDP), and a ZeroMQ based variant of [Newscast](https://www.cs.unibo.it/bison/publications/ap2pc03.pdf) for gossip. Butterfly differs from SWIM in the following ways: * Rather than sending messages to update member state, we send the entire member. * We support encryption on the wire. * Payloads are protocol buffers. * We support “persistent” members - these are members who will continue to have the failure detection protocol run against them, even if they are confirmed dead. This enables the system to heal from long-lived total partitions. * Members who are confirmed dead, but who later receive a membership rumor about themselves being suspected or confirmed, respond by spreading an Alive rumor with a higher incarnation. This allows members who return from a partition to re-join the ring gracefully. ### Further Reading * [SWIM: Scalable Weakly-consistent Infection-style Process Group Membership Protocol](https://www.cs.cornell.edu/projects/Quicksilver/public_pdfs/SWIM.pdf) by <NAME>, <NAME>, and <NAME>. * [A Robust and Scalable Peer-to-Peer Gossiping Protocol](https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.8773&rep=rep1&type=pdf) by <NAME>, <NAME>, and <NAME>. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_design/Supervisor Cryptography ======================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_crypto.md) Chef Habitat implements cryptography using a Rust [implementation](https://github.com/jedisct1/libsodium) of [NaCl](https://nacl.cr.yp.to/) called `libsodium`. `libsodium` provides a fast, modern framework for encryption, decryption, signing, and verification. Chef Habitat uses both symmetric encryption (for wire encryption) and asymmetric encryption (for everything else). If you are not familiar with the difference between the two, please consult [this article](https://support.microsoft.com/kb/246071). ### Message Encryption When you have either wire encryption or service group encryption turned on, the messages use the Curve25519, Salsa20, and Poly1305 ciphers specified in [Cryptography in NaCl](https://nacl.cr.yp.to/valid.html). ### Package Signing Chef Habitat packages are signed using [BLAKE2b](https://blake2.net/) checksums. BLAKE2b is a cryptographic hash function faster than MD5, SHA-1, SHA-2 and SHA3, yet provides at least as much security as the latest standard SHA-3. You can examine the first four lines of a `.hart` file to extract the signature from it, because it is an `xz`-compressed tarball with a metadata header. The `hab pkg header` command will do this for you. ``` hab pkg header somefile.hart ``` outputs: ``` » Reading package header for somefile.hart Package : somefile.hart Format Version : HART-1 Key Name : myorigin-19780608081445 Hash Type : BLAKE2b Raw Signature : a8yDoiA0Mv0CcW6xVyfkSOIZ0LW0beef4RPtvKL56MxemgG6dMVlKG1Ibplp7DUByr5az0kI5dmJKXgK6KURDzM1N2Y2MGMxYWJiMTNlYjQxMjliZTMzNGY0MWJlYTAzYmI4NDZlZzM2MDRhM2Y5M2VlMDkyNDFlYmVmZDk1Yzk= ``` The `.hart` file format is designed in this way to allow you to extract both the signature and the payload separately for inspection. To extract only the `xz`-compressed content, bypassing the signature, you could type this: ``` tail -n +6 somefile.hart | xzcat | tar x ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_crypto/Securing Supervisor Networks ============================ [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_secure.md) By default, a Supervisor runs unsecured. It communicates with other Supervisors in cleartext, and it allows any user to apply new configuration without authentication. While this is beneficial for demonstrating the concepts of Chef Habitat, users will want to provide external security on production deployments of Chef Habitat Supervisor networks. There are several types of security measures: * Wire encryption of inter-Supervisor traffic * Trust relationships between supervisors and users Wire Encryption --------------- Supervisors running in a ring can be configured to encrypt all traffic between them. This is accomplished by generating a *ring key*, which is a symmetric shared secret placed into the Supervisor environment prior to starting it. ### Generating a Ring Key 1. Generate a ring key using the `hab` command-line tool. This can be done on your workstation. The generated key has the `.sym.key` extension, indicating that it is a symmetric pre-shared key, and is stored in the `$HOME/.hab/cache/keys` directory. ``` $ hab ring key generate <RING``` 2. Copy the key file to the environment where the Supervisor will run, into the `/hab/cache/keys` directory. Ensure that it has the appropriate permissions so only the Supervisor can read it. 3. Start the Supervisor with the `-r` or `--ring` parameter, specifying the name of the ring key to use. ``` $ hab sup run --ring <RING> $ hab svc load <ORIGIN>/<NAME``` 4. The Supervisor becomes part of the named ring `<RING>` and uses the key for network encryption. Other supervisors that now attempt to connect to it without presenting the correct ring key will be rejected. 5. It is also possible to set the environment variable `HAB_RING_KEY` to the contents of the ring key; for example: ``` $ env HAB_RING_KEY=$(cat /hab/cache/keys/ring-key-file) hab sup run $ hab svc load <ORIGIN>/<NAME``` Service Group Encryption ------------------------ Supervisors in a service group can be configured to require key-based authorization prior to allowing configuration changes. In this scenario, the Supervisor in a named service group starts up with a key for that group bound to an *organization*. This allows for multiple service groups with the same name in different organizations. As explained in the [security overview](../sup_crypto/index), this process also requires the generation of a user key for every user making configuration updates to the Supervisor network. ### Generating Service Group Keys 1. Generate a service group key using the `hab` command-line tool. This can be done on your workstation. Because asymmetric encryption is being used, two files will be generated: a file with a `.box.key` extension, which is the service group’s private key, and a file with a `.pub` extension, which is the service group’s public key. ``` $ hab svc key generate service-group-name.example <ORG``` 2. This generated a service group key for the service group `service-group-name.example` in the organization `<ORG>`. Copy the `.box.key` private key to the environment where the Supervisor will run into the `/hab/cache/keys` directory. Ensure that it has the appropriate permissions so that only the Supervisor can read it. 3. Start the Supervisor, specifying both the service group and organization that it belongs to: ``` $ hab sup run --org <ORG> --group service-group-name.example $ hab svc load <ORIGIN>/<NAME``` 4. Only users whose public keys that the Supervisor already has in its cache will be allowed to reconfigure this service group. If you need to generate a user key pair, see the next section. ### Generating User Keys The user key is used to encrypt configuration data targeted for a particular service group. 1. Generate a user key using the `hab` command-line tool. This can be done on your workstation. Because asymmetric encryption is being used, two files will be generated: a file with a `.box.key` extension, which is the user’s private key, and a file with a `.pub` extension, which is the user’s public key. 2. Distribute the user’s public key to any Supervisor that needs it, into the `/hab/cache/keys` directory. The user will be able to reconfigure that Supervisor, provided they encrypted the configuration update using the service group’s public key. Apply Configuration Changes --------------------------- The `hab config apply` and `hab file upload` commands will work as usual when user/service group trust relationships are set up in this way. If a running Supervisor cannot decrypt a secret due to a missing key, it will retry with exponential backoff starting with a one-second interval. This allows an administrator to provide the Supervisor with the key to resume normal operations, without taking down the Supervisor. Identifying Key Types --------------------- To aid the user in the visual identification of the many varieties of keys in use by Chef Habitat, a key itself is in cleartext and contains a header on the first line indicating what kind of key it is. The file extension and, in some situations, the format of the file name, provide additional guidance to the user in identifying the type of key. `YYYYMMDDRRRRRR` denotes the creation time and release identifier of that key. | Key Type | Header | Filename Format | | --- | --- | --- | | Private origin signing key | SIG-SEC-1 | originname-YYYYMMDDRRRRRR.sig.key | | Public origin signing key | SIG-PUB-1 | originname-YYYYMMDDRRRRRR.pub.key | | Ring wire encryption key | SYM-SEC-1 | ringname-YYYYMMDDRRRRRR.sym.key | | Private service group key | BOX-SEC-1 | [service-<EMAIL>](mailto:<EMAIL>) | | Public service group key | BOX-PUB-1 | [service-group.env@org-YYYYMMDDRRRRRR.pub](mailto:service-group.env@org-YYYYMMDDRRRRRR.pub) | | Private user key | BOX-SEC-1 | username-YYYYMMDDRRRRRR.box.key | | Public user key | BOX-PUB-1 | username-YYYYMMDDRRRRRR.pub | Keys that contain `SEC` in their header should be guarded carefully. Keys that contain `PUB` in their header can be distributed freely with no risk of information compromise. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_secure/Supervisor Configuration File ============================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_config.md) Generate a Supervisor configuration file and use it to set any of the 40+ Supervisor configuration settings instead of configuring them on the command line. Chef Habitat looks for Supervisor configuration settings in four locations and applies them in order, which means that settings defined in later locations overwrite earlier ones. ``` hab sup run --generate-config ``` ``` hab sup run --generate-config > config.toml ``` The Supervisor settings look-up order: 1. The fixed config file location `/hab/sup/default/config/sup.toml` on the Supervisor 2. Files passed with the command, `hab sup run --config-files /config/file1.toml /config/file2.toml`, where * You can pass more than one file command * The settings in the later files overwrite those from the earlier, which means that for the same settings specified in both files in the command `hab sup run --config-files /config/file1.toml /config/file2.toml`, you will end up with the settings from `file2.toml` applied to the Supervisor 3. From [environment variables](../environment_variables/index), if they exist 4. From settings passed from the [`hab sup run` command](../habitat_cli/index#hab-sup-run) ``` ### The listen address for the Gossip Gateway listen_gossip = "0.0.0.0:9638" ### Start the supervisor in local mode local_gossip_mode = false ### The listen address for the HTTP Gateway listen_http = "0.0.0.0:9631" ### Disable the HTTP Gateway completely http_disable = false ### The listen address for the Control Gateway listen_ctl = "127.0.0.1:9632" ### The organization the Supervisor and its services are part of organization = "my-org" ### The listen address of one or more initial peers (IP[:PORT]) peer = ["1.1.1.1:9632", "2.2.2.2:9632", "3.3.3.3:9632"] ### Make this Supervisor a permanent peer permanent_peer = false ### Watch this file for connecting to the ring peer_watch_file = "/path/to/file" ### Cache for creating and searching for encryption keys cache_key_path = "/path/to/file" ### The name of the ring used by the Supervisor when running with wire encryption ring = "my-ring" ### Use the package config from this path rather than the package itself config_from = "/path/to/file" ### Enable automatic updates for the Supervisor itself auto_update = false ### The private key for HTTP Gateway TLS encryption ### ### Read the private key from KEY_FILE. This should be an RSA private key or PKCS8-encoded private key in PEM format. key_file = "/path/to/file" ### The server certificates for HTTP Gateway TLS encryption ### ### Read server certificates from CERT_FILE. This should contain PEM-format certificates in the right order. The first certificate should certify KEY_FILE. The last should be a root CA. cert_file = "/path/to/file" ### The CA certificate for HTTP Gateway TLS encryption ### ### Read the CA certificate from CA_CERT_FILE. This should contain PEM-format certificate that can be used to validate client requests ca_cert_file = "/path/to/file" ### Load a Habitat package as part of the Supervisor startup ### ### The package can be specified by a package identifier (ex: core/redis) or filepath to a Habitat artifact (ex: /home/core-redis-3.0.7-21120102031201-x86_64-linux.hart). pkg_ident_or_artifact = "core/redis" ### Verbose output showing file and line/column numbers verbose = false ### Turn ANSI color off no_color = false ### Use structured JSON logging for the Supervisor ### ### This option also sets NO_COLOR. json_logging = false ### The IPv4 address to use as the `sys.ip` template variable ### ### If this argument is not set, the supervisor tries to dynamically determine an IP address. If that fails, the supervisor defaults to using `127.0.0.1`. sys_ip_address = "1.2.3.4" ### The name of the application for event stream purposes ### ### This will be attached to all events generated by this Supervisor. event_stream_application = "my-app" ### The name of the environment for event stream purposes ### ### This will be attached to all events generated by this Supervisor. event_stream_environment = "my-env" ### Event stream connection timeout before exiting the Supervisor ### ### Set to '0' to immediately start the Supervisor and continue running regardless of the initial connection status. event_stream_connect_timeout = 60 ### The event stream connection url used to send events to Chef Automate ### ### This enables the event stream and requires EVENT_STREAM_APPLICATION, EVENT_STREAM_ENVIRONMENT, and EVENT_STREAM_TOKEN also be set. event_stream_url = "nats://127.0.0.1:4222" ### The name of the site where this Supervisor is running for event stream purposes event_stream_site = "my-site" ### The authentication token for connecting the event stream to Chef Automate event_stream_token = "my-token" ### An arbitrary key-value pair to add to each event generated by this Supervisor event_meta = ["my-key1=my-val1", "my-key2=my-val2", "abc=123"] ### The path to Chef Automate's event stream certificate used to establish a TLS connection ### ### The certificate should be in PEM format. event_stream_server_certificate = "/path/to/file" ### Automatically cleanup old packages ### ### The Supervisor will automatically cleanup old packages only keeping the KEEP_LATEST_PACKAGES latest packages. If this argument is not specified, no automatic package cleanup is performed. keep_latest_packages = 1 ### Receive updates from the specified release channel channel = "my-channel" ### Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) bldr_url = "https://my-bldr.url" ### The service group with shared config and topology group = "my-group" ### Service topology topology = "leader" ### The update strategy strategy = "at-once" ### The condition dictating when this service should update ### ### latest: Runs the latest package that can be found in the configured channel and local packages. ### ### track-channel: Always run what is at the head of a given channel. This enables service rollback where demoting a package from a channel will cause the package to rollback to an older version of the package. A ramification of enabling this condition is packages newer than the package at the head of the channel will be automatically uninstalled during a service rollback. update_condition = "track-channel" ### One or more service groups to bind to a configuration bind = ["port:redis.default"] ### Governs how the presence or absence of binds affects service startup ### ### strict: blocks startup until all binds are present. binding_mode = "strict" ### The interval in seconds on which to run health checks health_check_interval = 60 ### The delay in seconds after sending the shutdown signal to wait before killing the service process ### ### The default value can be set in the packages plan file. shutdown_timeout = 10 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_config/Supervisor Configuration ======================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_pkg_config.md) To assist in creating new packages, or modifying existing ones, the Supervisor has an option to allow you to use the configuration directly from a specific directory, rather than the one it includes in the compiled artifact. This can significantly shorten the cycle time when working on configuration and application lifecycle hooks. Build the plan as you normally would. When you start the Supervisor, pass the name of the directory with your plan inside it: ``` $ hab sup run core/redis --config-from /src ``` The Supervisor will now take its configuration and hooks from /src, rather than from the package you previously built. When the configuration is as you want it, do a final rebuild of the package. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_pkg_config/Launcher ======== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_launcher.md) Chef Habitat’s Launcher is a sidecar process for the Supervisor which provides a mechanism for launching processes on behalf of the Supervisor. It is the entry point for running the Supervisor and is the Supervisor for the Supervisor. Whereas the Supervisor is able to automatically update itself, the Launcher is currently released a bit differently, by design; it should be rare that the Launcher ever needs to change. To update your Launchers, run: ``` hab pkg install core/hab-launcher ``` Then restart the Supervisor. This will, by necessity, require a restart of supervised services, so factor that into your planning. The Launcher is designed to run as process 1; it is minimal by design. Its responsibilities are simply to be the parent process for the Supervisor. The Launcher enables the Supervisor to update itself without shutting down or re-parenting the services that the Supervisor is supervising. The Launcher is versioned separately from the Supervisor and should be updated very infrequently since an update of the Launcher could require a system restart if it is running as process 1. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_launcher/Supervisor Networks =================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_networks.md) Chef Habitat Supervisors communicate amongst each other using “gossip” algorithms, which underpin the membership management, leadership election, and service discovery mechanics of Chef Habitat. By simply being “peered” to a single existing Supervisor, a new Supervisor will gradually come to know about *all* the Supervisors in a Chef Habitat network. The gossip algorithm has built-in features to counteract brief network splits, but care must be taken to set up a robust Supervisor network. The Initial Peer ---------------- While a Chef Habitat Supervisor does not need to connect with any other Supervisors in order to be useful, leveraging a network of Supervisors unlocks the full potential of Chef Habitat as a platform. In order to do this, a Supervisor must be given the address of at least one other Supervisor in this network when it starts up; this is known as the “initial peer problem”. You might think of a Supervisor network as an exclusive members-only club; you must first know a member in order to become a member yourself. This Supervisor does *not* know about any other Supervisors, and will (at least initially) run in complete isolation. ``` hab sup run ``` This Supervisor, on the other hand, will start up knowing about three other Supervisors, and will quickly establish contact with each of them. Thanks to the gossip mechanism, it will also find out about every other Supervisor those initial Supervisors know about. Similarly, every other Supervisor will discover the presence of *this* new Supervisor. ``` hab sup run --peer=192.168.0.1 --peer=192.168.0.2 --peer=192.168.0.3 ``` It should be noted that peering is symmetric. Even though our first Supervisor above did not start out peered with any other Supervisors, it can still become part of a Supervisor network if some other Supervisor declares it to be a peer. Managing Membership with SWIM ----------------------------- In order for Chef Habitat’s network functionality to work, the Supervisors must first know which other Supervisors they can communicate with. This is a problem of maintaining “membership lists”, and is achieved using the membership protocol known as [SWIM][SWIM]. As detailed above, we must first “seed” a Supervisor’s membership list with at least one “peer”; that is, another Supervisor that it can communicate with. Given a non-empty membership list, the Supervisor can begin probing the members of that list to see if they are still alive and running. Supervisor A sends a message to Supervisor B, effectively asking “are you still there?”. If Supervisor B *is* available, it will reply to Supervisor A, also sending contact information for up to five Supervisors that *it* has in its membership lists (Supervisor A sends these introductions in its initial message, as well). In this way, Supervisors can both maintain and *grow* their membership lists. In short order, Supervisor A will come to know of all the other Supervisors in the network, and they, too, will come to know of Supervisor A. If Supervisor A cannot establish contact with Supervisor B for some reason, it does not immediately consider it to be dead. This would be too strict, and could lead to unnecessary service “flapping”. Instead, Supervisor A will consider Supervisor B “suspect”. In this case, it will ask Supervisor C (another Supervisor in its membership list) if *it* can contact Supervisor B. If Supervisor C can make contact, it relays that information back to Supervisor A, which will then consider Supervisor B to be alive again, and *not* suspect. This scenario can arise, for example, if there is a network split between Supervisors A and B, but not between A and C, or B and C. Similarly, network congestion could delay messages such that Supervisor A’s request times out before Supervisor B’s reply can make it back. If no Supervisor can make contact with Supervisor B, either directly or indirectly, the network comes to view Supervisor B as “confirmed” dead. In this case, Supervisor B is effectively removed from all membership lists across the network. As a result, no Supervisors try to contact it again. This is ultimately what happens when you shut down a Supervisor; the rest of the network realizes that it is gone and can reconfigure any services to no longer communicate with any services that were running on it. If, on the other hand, Supervisor B is started back up again, it can rejoin the network. All the other Supervisors will (through the same SWIM mechanism described) recognize that it is back, and will mark it as alive once again. Services will be reconfigured to communicate with Supervisor B’s services as appropriate. This mechanism forms the foundation of the Chef Habitat network, but cannot by itself provide a completely robust network. For that, we need something additional. Permanent Peers --------------- An important thing to keep in mind about the basic SWIM mechanism is that if two Supervisors are separated from each other for a long enough amount of time, they will each come to view the other as being dead, and will not try to reestablish contact. While this is the behavior you want when you legitimately shut a Supervisor down, it is definitely *not* the behavior you want if your Chef Habitat network experiences an extended network incident. In such a case, you could end up with two (or more!) smaller Supervisor networks that are all still *internally* connected, but completely disconnected *from each other*. Supervisors in “Network A” would view those in “Network B” as dead, and vice versa. Once network connectivity had been restored, you would continue to have a fractured network, because each network would collectively consider the other to still be dead. By starting a few Supervisors in the network using the `--permanent-peer` option, an additional bit of information is gossipped about these Supervisors. In effect, it tells all other Supervisors it communicates with to *always* try to reestablish contact with it, even if that Supervisor considers the “permanent” Supervisor to be dead. This provides a mechanism by which split networks can stitch themselves together again after the split has been resolved. The “Bastion Ring” ------------------ Defining a few Supervisors to be “permanent peers” *will* provide a robust network, but unless done with care, it can be less than ideal. We recommend running a small number of Supervisors as permanent peers, but *to run no services on those Supervisors*. In modern dynamic architectures, it’s common for nodes to come and go; VMs may get shut down, containers can be rescheduled, and so on. If you were to go to the extreme and have *all* your Supervisors be permanent peers, you would end up with unnecessary network traffic as the Supervisors come and go as the infrastructure evolves across time. Each Supervisor would try to maintain contact with every Supervisor that had ever been a member of the network! If your permanent peer Supervisors are not running any services, they will be less subject to the pressures that would cause service-running Supervisors to come and go. They can exist solely to anchor the entire Supervisor network. Pulling It All Together: A Robust Supervisor Network ---------------------------------------------------- With all this, we can come up with a robust Chef Habitat network architecture. In fact, this is the same architecture the Chef Habitat team uses to run the public [Builder service](https://bldr.habitat.sh). ### Create the Bastion Ring First, set up three Supervisors as permanent peers, all mutually peered to each other (The labels “A”, “B”, and “C” are stand-ins for the IP addresses at which these Supervisors are reachable): ``` # Supervisor "A" hab sup run --permanent-peer --peer=B --peer=C # Supervisor "B" hab sup run --permanent-peer --peer=A --peer=C # Supervisor "C" hab sup run --permanent-peer --peer=A --peer=B ``` These Supervisors should never be used to run services. They *can* however, serve as convenient, well-known, and stable entry points to the network for doing things like injecting configurations using `hab config apply`, adding files using `hab file upload`, or departing Supervisors using `hab sup depart`. ### Peer Additional Supervisors to the Bastion Supervisors Each additional Supervisor you add to the network should be peered to *at least one* of the bastion ring Supervisors. Technically speaking, only one peer is necessary, as that provides access to the rest of the network. However, it could be possible to not fully connect to all of them if, say, the Supervisor joined *during* a network split event. Out of convention and redundancy, we peer to *all* the bastion ring Supervisors, like so: ``` # Supervisor "D" (a "normal" Supervisor) hab sup run --peer=A --peer=B --peer=C ``` This Supervisor *should* be used to run services, but *should not* be started as a permanent peer. Conclusion ---------- Hopefully, the above discussion has given you a better idea of how Chef Habitat’s networking works, and how you can best take advantage of it to provide a robust network foundation for the services you run. For those that like to keep things succinct, the above advice can be summed up thusly: 1. Run three mutually-peered, permanent Supervisors 2. Never run services on those Supervisors 3. Peer all other Supervisors to those first three Related Reading --------------- If you would like additional details, the following technical journal articles describe the algorithms that form the basis of Chef Habitat’s gossip system: * [SWIM: Scalable Weakly-consistent Infection-style Process Group Membership Protocol](https://www.cs.cornell.edu/projects/Quicksilver/public_pdfs/SWIM.pdf) by <NAME>, <NAME>, <NAME>. * [A Robust and Scalable Peer-to-Peer Gossiping Protocol](https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.8773&rep=rep1&type=pdf) by <NAME>, <NAME>, and <NAME>. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_networks/Supervisor Log Configuration ============================ [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_log_configuration.md) With the 0.83.0 release of the Chef Habitat Supervisor, it is possible to have greater control over logging output, including the ability to dynamically adjust the logging configuration of a running Supervisor. There are two main ways of configuring logging, each of which has their own strengths and weaknesses: using environment variables, and using a configuration file. Environment Variable Configuration ---------------------------------- It is still possible to configure logging via the `RUST_LOG` environment variable. This approach is often useful for quickly re-configuring logging (requiring a restart), or for easily configuring logging in container-based deployments. The configuration scheme is essentially the same as that described in the documentation of the Rust [env_logger](https://docs.rs/env_logger/0.6.1/env_logger/#enabling-logging) crate, with the exception that we do not allow additional regular expression-based filtering. The configuration values the Supervisor recognizes are described below: Simple Logging Levels --------------------- The recognized values are, in increasing verbosity (or, equivalently, in decreasing severity): `error`, `warn`, `info`, `debug`, and `trace`. Setting `RUST_LOG` to one of these values will cause all log messages at that verbosity and below (equivalently, that severity and above) to be printed. This includes log messages from Habitat, as well as any libraries that it uses. Rust Logging Levels ------------------- This is much finer grained than the simple logging levels above, and to fully leverage it requires some knowledge of both the internal code structure of Habitat itself, as well as of how Rust code is organized generally. Despite this, it allows you to target specific subsystems, which can be very helpful for troubleshooting. For example, `RUST_LOG=habitat_sup::manager=info` will cause all log messages at the `info` level or more severe (i.e., `error`, `warn`, and `info`) originating anywhere in the module hierarchy rooted at `habitat_sup::manager`. Note that Rust modules are identified first by the crate (or library) they come from, followed by a `::`-delimited path of module names. Variations ---------- Multiple logging specifiers can be submitted, separated by commas. A simple logging level will act as the default, with additional module-targeted levels serving to refine the logging for the target code. If you supply multiple simple logging levels, only the last one will count. Any number of targeted logging levels are allowed, however. For example, `RUST_LOG=info,habitat_sup::manager=debug,tokio_reactor=error` will limit logs generally to the `info` level, while additionally allowing `debug` messages coming from the `habitat_sup::manager` module hierarchy, and restricting log messages from the `tokio_reactor` library to only `error`. Dynamic, File-based Configuration --------------------------------- For further control over logging output, as well as the ability to change the configuration of a running Supervisor, a configuration file is needed. This file is processed by the [log4rs](https://docs.rs/log4rs/) crate, and shares many of the same concepts as the Log4J logging system of the Java ecosystem. The `log4rs` configuration documentation can be found [here](https://docs.rs/log4rs/0.8.3/log4rs/#configuration). Place an appropriate YAML configuration file at `/hab/sup/default/config/log.yml` when the Supervisor starts up if you wish to take advantage of this style of configuration. Note that if such a file is present, it will take priority over any `RUST_LOG` environment variable that may also be present. Here is an example configuration file that mimics the default logging configuration of the Supervisor. It emits UTC timestamped message lines to standard output at the `error` level. ``` # ALWAYS keep this key in the configuration; removing it means changes# to config won't get picked up without a restart.## Uses humantime to parse the duration; see# https://docs.rs/humantime/1.2.0/humantime/fn.parse_duration.htmlrefresh_rate:5secondsappenders:stdout:kind:consoleencoder:# See https://docs.rs/log4rs/0.8.3/log4rs/#configuration for# formatting optionspattern:"[{d(%Y-%m-%dT%H:%M:%SZ)(utc)} {l} {module}] {message}{n}"root:level:errorappenders:- stdout ``` The `refresh_rate` configuration is very important. If it is present when the Supervisor starts, the file will be checked periodically for updates (according to the value of `refresh_rate`; in the above example, the file will be checked every 5 seconds). If the file changes, then the current content of the file becomes the active configuration. This allows you to, for example, increase the logging level of a running supervisor if you suspect you are running into problems. This dynamism also has a catch, though: you can change the refresh rate as well, and even remove it entirely. If you remove it, however, the Supervisor will stop checking for updates to the file. Any subsequent changes you might make would require a Supervisor restart to be recognized. Work is planned to make this more flexible, however. You can also target individual module hierarchies with this configuration scheme, just as you can with the `RUST_LOG` environment variable. For this, you will need to add a new top-level `loggers` key to the file, like so: ``` loggers:habitat_sup::manager:level:debugtokio_reactor:level:error ``` Here, `loggers` is a map of maps. Map keys are module paths (as described above in the `RUST_LOG` environment variable documentation), while the values are maps with additional configuration. Here, we are only setting the logging level, but more advanced configurations are possible. Users are encouraged to read the [log4rs configuration documentation](https://docs.rs/log4rs/0.8.3/log4rs/#configuration) for further details. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_log_configuration/Application Lifecycle Hooks =========================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/application_lifecycle_hooks.md) Each plan can specify lifecycle event handlers, or hooks, to perform certain actions during a service’s runtime. Each hook is a script with a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) defined at the top to specify the interpreter to be used. On Windows, Powershell Core is the only interpreter ever used. To define a hook, simply create a file of the same name in `/my_plan_name/hooks/`, for example, `/postgresql/hooks/health-check`. Optionally you may add an extension to the hook file. For example, you might create `/postgresql/hooks/health-check.sh` which can be useful in some editors to automatically take advantage of syntax highlighting. Note that having two files for the same hook but with different extensions is not permitted. For example you might create a `run.sh` and `run.ps1` to support both Linux and Windows packages. If you would like to create different hooks for different platforms, you must use [target directories](../plan_writing/index#writing-a-plan-for-multiple-platform-targets). Warning You cannot block the thread in a hook unless it is in the `run` hook. Never call `hab` or `sleep` in a hook that is not the `run` hook. Runtime Settings ---------------- [Chef Habitat’s runtime configuration settings](../service_templates/index) can be used in any of the plan hooks and also in any templatized configuration file for your application or service. Note In Chef Habitat 0.68.0 and less, some hooks used `_` in their names. This is now deprecated; if you used them, please use `-` instead. ### file-updated File location: `<plan>/hooks/file-updated`. This hook is run whenever a configuration file that is not related to a user or about the state of the service instances is updated. ### health-check **File location**: `<plan>/hooks/health-check`. **Default**: 30 seconds This hook repeats at a configured interval. There are two exceptions to the interval used between `health-check` runs: * If the `health-check` hook exits with a non-`ok` status the next `health-check` will run after the default `health-check` interval (thirty seconds). This is only done when the configured interval is greater than the default interval. * If the `health-check` hook returns an `ok` status for the first time, then the next `health-check` will run after a randomly chosen delay between 0 and the configured `health-check` interval. This introduces a splay - a degree of difference - in the timing between the first and second `health-check` runs. All following health-check hooks run at the configured interval. The splay prevents more than one health-check hook from starting at the same time by giving each of them a unique starting point. The `health-check` script must return a valid exit code from the list below. * **0**- ok * **1**- warning * **2**- critical * **3**- unknown * any other code - failed health check with additional output taken from `health-check` stdout. A `health-check` hook can use the following as a template: ``` #!/bin/sh # define default return code as 0 rc=0 program_that_returns_a_status case $? in 0) rc=1 ;; 3) rc=0 ;; 4) rc=2 ;; *) rc=3 ;; esac exit $rc ``` ### init File location: `<plan>/hooks/init`. This hook is run when a Chef Habitat topology starts. ### install File location: `<plan>/hooks/install`. This hook is run when a package is initially installed. An `install` hook may be triggered by `hab pkg install` or by a Supervisor loading a new package. Note that any package can define an `install` hook and it is not limited to packages that are loaded as services into a Supervisor. A package may have dependencies defined in `pkg_deps` or `pkg_build_deps` that define their own `install` hook. An `install` hook defined in an dependant package that has not yet been installed will run when the parent package is installed. However `install` hooks in a runtime dependency (`pkg_deps`) will not run when loaded via a package `build` inside of a Studio. The exit code returned from an `install` hook will be “remembered”. If a previously installed package is either installed again via `hab pkg install` or loaded into a Supervisor, its `install` hook will be rerun if it previously failed (exited with a non `0` result) or has not been previously run (perhaps because `--ignore-install-hook` was passed to `hab pkg install`). An `install` hook, unlike other hooks, will not have access to any census data exposed via binds or the `svc` namespace. Also, configuration in `svc_config_path` is not accessible to an `install` hook. If an `install` hook needs to use templated configuration files, templates located in the `svc_config_install_path` may be referenced. This location will contain rendered templates in a package’s `config_install` folder. Finally, any configuration updates made during a service’s runtime that would alter an `install` hook or any configuration template in `svc_config_install_path` will not cause a service to reload. ### reload File location: `<plan>/hooks/reload`. This hook is now deprecated; you should use `reconfigure` instead (see below). To provide backward compatibility, if a `reload` hook is provided, the service will restart in response to configuration changes. ### reconfigure File location: `<plan>/hooks/reconfigure`. A `reconfigure` hook can be written for services that can respond to changes in `<plan>/config` without requiring a restart. This hook will execute **instead** of the default behavior of restarting the process. `{{pkg.svc_pid_file}}` can be used to get the `PID` of the service. Habitat does not support changing the `PID` of the underlying service in any lifecycle hook. If part of a service’s reconfiguration relies on changing the `PID`, you should not provide a `reconfigure` hook, and instead, use the default behavior of restarting the service for reconfiguration. The `reconfigure` hook is not necessarily run on every change to `<plan>/config`. The `reconfigure` hook will not be run if the service restarts before the `reconfigure` hook has run. The restart is considered sufficient for reconfiguring the service. For example, when applying a configuration that changes both the `run` hook and `<plan>/config`, the change to the `run` hook will trigger a restart. Therefore, the `reconfigure` hook will not be run. To put it another way, the `reconfigure` hook will only respond to changes in `<plan>/config` after the service has started. ### suitability File location: `<plan>/hooks/suitability`. The suitability hook allows a service to report a priority by which it should be elected leader. The hook is called when a new election is triggered and the last line it outputs to `stdout` should be a number parsable as a `u64`. In the event that a leader goes down and an election is started the service with the highest reported suitability will become the new leader. ### run File location: `<plan>/hooks/run`. This hook is run when one of the following conditions occur: * The main topology starts, after the `init` hook has been called. * When a package is updated, after the `init` hook has been called. * When the package config changes, after the `init` hook has been called, but before a `reconfigure` hook is called. You can use this hook in place of `$pkg_svc_run` when you need more complex behavior such as setting environment variables or command options that are based on dynamic configuration. Services run using this hook should do two things: * Redirect stderr to stdout (e.g. with `exec 2>&1` at the start of the hook) * Call the command to execute with `exec <command> <options>` rather than running the command directly. This ensures the command is executed in the same process and that the service will restart correctly on configuration changes. It is important to also consider what side effects the command to execute will have. For example, does the command spin off other processes in separate process groups? If so, they may not be cleaned up automatically when the system is reconfigured. In general, the command executed should behave in a manner similar to a daemon, and be able to clean up properly after itself when it receives a SIGTERM, and properly forward signals to other processes that it creates. For an even more specific example: let’s say you are trying to start a node.js service. Instead of your command being `npm start`, you should use `node server.js` directly. A run hook can use the following as a template: ``` #!/bin/sh #redirect stderr exec 2>&1 # Set some environment variables export MY_ENVIRONMENT_VARIABLE=1 export MY_OTHER_ENVIRONMENT_VARIABLE=2 # Run the command exec my_command --option {{cfg.option}} --option2 {{cfg.option2}} ``` ### post-run File location: `<plan>/hooks/post-run`. The post run hook will get executed after initial startup. For many data services creation of specific users / roles or datastores is required. This needs to happen once the service has already started. ### post-stop File location: `<plan>/hooks/post-stop`. The post-stop hook will get executed after service has been stopped successfully. You may use this hook to undo what the `init` hook has done. ### uninstall File location: `<plan>/hooks/uninstall`. This hook is run when a package is uninstalled. The `uninstall` hook runs when the last package of an `origin/package` is uninstalled. If there are other versions or revisions installed for the package, the `uninstall` hook is skipped. When more than one revision of an origin are uninstalled at the same time, the process removes them from oldest to newest. This ensures that the uninstall hook of the latest revision is the version that runs. Like the `install` hook, the `uninstall` hook is not limited to packages that are loaded as services into a Supervisor. Also like the `install` hook, configuration in `svc_config_path` is not accessible to an `uninstall` hook. If an `uninstall` hook needs to use templated configuration files, templates located in the `svc_config_install_path` may be referenced. This location will contain rendered templates in a package’s `config_install` folder. Finally, any configuration updates made during a service’s runtime that would alter an `uninstall` hook or any configuration template in `svc_config_install_path` will not cause a service to reload. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/application_lifecycle_hooks/Build Phase Callbacks ===================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/build_phase_callbacks.md) When defining your plan, you can override the default behavior of Chef Habitat in each build phase through a callback. To define a callback, simply create a shell function of the same name in your plan file and then write your script. If you do not want to use the default callback behavior, you must override the callback and `return 0` in the function definition or simply provide no implementation in a `plan.ps1`. These callbacks are listed in the order that they executed by the package build script. Note Bash callbacks are prefixed with `do_` and use an underscore convention. Powershell plans prefix callbacks with `Invoke-` and use a PascalCase convention. You can also use [plan variables](../plan_variables/index) in your plans to place binaries, libraries, and files into their correct locations during package compilation or when running as a service. Additionally, [plan helper functions](../build_helpers/index) can be useful in your plan to help you build your package correctly. They are mostly used for building packages - attach() is used for debugging. do_begin()/Invoke-Begin Used to execute arbitrary commands before anything else happens. Note that at this phase of the build, no dependencies are resolved, the `$PATH` and environment is not set, and no external source has been downloaded. For a phase that is more completely set up, see the `do_before()` phase. do_begin_default()/Invoke-BeginDefault There is an empty default implementation of this callback. do_setup_environment()/Invoke-SetupEnvironment Use this to declare buildtime and runtime environment variables that overwrite or are in addition to the default environment variables created by Chef Habitat during the build process. Examples of common environment variables you might wish to add or modify are those such as `JAVA_HOME` or `GEM_PATH`. Note You do not have to override this callback if you do not wish to modify your environment variables. The build system will always set up your environment according to your dependencies. For example, it will ensure that dependency binaries are always present on your `PATH` variable, and so on. Runtime environments of dependencies are layered together in the order they are declared in your `pkg_deps` array, followed by modifications made in this callback. In turn, these computed values will be made available to packages that use the current package as a dependency, and so on. The buildtime environment is assembled by processing the *runtime* environments of your `pkg_build_deps` dependencies (because they will be running in your build) in a similar manner. The final environment in which your package will be built consists of: * The system environment of your Studio as the base layer * The assembled runtime environment of your package on top of the base * Any buildtime environment information on top of the assembled runtime environment Only the runtime portion of this combined buildtime environment is made available to your package when it is running in a Supervisor (or when it is being used as a dependency of another Chef Habitat package). To add or modify your environment variables, there are special functions to call within this callback to ensure that the variables are set up appropriately. * [Bash](#bash-panel1) * [Powershell](#powershell-panel1) ``` set_runtime_env [-f] VARIABLE_NAME VALUE set_buildtime_env [-f] VARIABLE_NAME VALUE ``` ``` Set-RuntimeEnv VARIABLE_NAME VALUE [-force] [-IsPath] Set-BuildtimeEnv VARIABLE_NAME VALUE [-force] [-IsPath] ``` In Powershell plans, if your variable contains values that are file paths pointing inside the Chef Habitat `/hab` directory, you can use the `-IsPath` flag to ensure that the path remains portable accross different Chef Habitat environments. For example in a local (non-Docker) Windows Studio, the following line: ``` Set-RuntimeEnv SSL_CERT_FILE "$(Get-HabPackagePath cacerts)/ssl/cert.pem" ``` will set `SSL_CERT_FILE` to the `ssl/cert.pem` file inside of the `cacerts` package path. This path will be located inside of `c:/hab/studios` which will not be valid inside of a non-Studio Supervisor or inside of a Docker Studio. Instead, use the following code: ``` Set-RuntimeEnv SSL_CERT_FILE "$(Get-HabPackagePath cacerts)/ssl/cert.pem" -IsPath ``` This will hint to the packaging system that this path should be properly rooted inside of the Chef Habitat filesystem of the current running environment. These functions allow you to *set* an environment variable’s value. If one of your dependencies has already declared a value for this, it will result in a build failure, protecting you from inadvertently breaking anything. If you really do want to replace the value, you can supply the `-f` or `-force` flag. For pushing new values onto a multi-valued environment variable (like `PATH`), use the following functions: * [Bash](#bash-panel2) * [Powershell](#powershell-panel2) ``` push_runtime_env VARIABLE_NAME VALUE push_buildtime_env VARIABLE_NAME VALUE ``` ``` Push-RuntimeEnv VARIABLE_NAME VALUE [-IsPath] Push-BuildtimeEnv VARIABLE_NAME VALUE [-IsPath] ``` These functions allow you to push a new value onto a multi-valued environment variable without overwriting the existing values. These multi-valued variables are referred to as “aggregate” variables in Chef Habitat. Single-value environment variables are known as “primitive” variables. By default, Chef Habitat treats all variables as “primitive” variables. If you are working with a value that is actually an “aggregate” type, you must set the following special environment variable somewhere in the top level of your plan. * [Bash](#bash-panel3) * [Powershell](#powershell-panel3) ``` export HAB_ENV_FOO_TYPE=aggregate ``` ``` $env:HAB_ENV_FOO_TYPE="aggregate" ``` Similarly, Chef Habitat defaults to using the colon (`:`) as a separator for aggregate variables on Linux. If the hypothetical `FOO` variable uses a semicolon (`;`) as a separator instead, then you must add `export HAB_ENV_FOO_SEPARATOR=;` at the top level of the plan. On Windows, `;` is the default separator. In all cases, when Chef Habitat is assuming a default strategy, it will emit log messages to notify you of that along with instructions on how to change the behavior. Note If you discover common environment variables that Chef Habitat doesn’t currently treat appropriately, feel free to request an addition to the codebase, or even to submit a pull request yourself. do_before()/Invoke-Before At this phase of the build, the origin key has been checked for, all package dependencies have been resolved and downloaded, and the `$PATH` and environment are set, but this is just before any source downloading would occur (if `$pkg_source` is set). This could be a suitable phase in which to compute a dynamic version of a package given the state of a Git repository, fire an API call, start timing something, etc. do_before_default()/Invoke-BeforeDefault There is an empty default implementation of this callback. do_download()/Invoke-Download If `$pkg_source` is being used, download the software and place it in `$HAB_CACHE_SRC_PATH/$pkg_filename`. If the source already exists in the cache, verify that the checksum is what we expect, and skip the download. Delegates most of the implementation to the `do_default_download()` function. do_download_default()/Invoke-DownloadDefault The default implementation is that the software specified in `$pkg_source` is downloaded, checksum-verified, and placed in `$HAB_CACHE_SRC_PATH/$pkg_filename`, which resolves to a path like `/hab/cache/src/filename.tar.gz`. You should override this behavior if you need to change how your binary source is downloaded, if you are not downloading any source code at all, or if you are cloning from git. If you do clone a repo from git, you must override do_verify() to return 0. do_verify()/Invoke-Verify If `$pkg_source` is being used, verify that the package we have in `$HAB_CACHE_SRC_PATH/$pkg_filename` has the `$pkg_shasum` we expect. Delegates most of the implementation to the `do_default_verify()` function. If you do clone a repo from git, you must override do_verify() to return 0. do_verify_default()/Invoke-VerifyDefault The default implementation tries to verify the checksum specified in the plan against the computed checksum after downloading the source tarball to disk. If the specified checksum doesn’t match the computed checksum, then an error and a message specifying the mismatch will be printed to stderr. You should not need to override this behavior unless your package does not download any files. do_clean()Invoke-Clean Clean up the remnants of any previous build job, ensuring it can’t pollute out new output. Delegates most of the implementation to the `do_default_clean()` function. do_default_clean()/Invoke-DefaultClean The default implementation removes the `HAB_CACHE_SRC_PATH/$pkg_dirname` folder in case there was a previously-built version of your package installed on disk. This ensures you start with a clean build environment. do_unpack()/Invoke-Unpack If `$pkg_source` is being used, we take the `$HAB_CACHE_SRC_PATH/$pkg_filename` from the download step and unpack it,as long as the method of extraction can be determined. This takes place in the $HAB_CACHE_SRC_PATH directory. Delegates most of the implementation to the `do_default_unpack()` function. do_default_unpack()/Invoke-DefaultUnpack The default implementation extracts your tarball source file into `HAB_CACHE_SRC_PATH`. The supported archive extensions on Linux are: .tar, .tar.bz2, .tar.gz, .tar.xz, .rar, .zip, .Z, .7z. Only .zip is supported on Windows. If the file archive could not be found or has an unsupported extension, then a message will be printed to stderr with additional information. do_prepare()/Invoke-Prepare There is no default implementation of this callback. At this point in the build process, the tarball source has been downloaded, unpacked, and the build environment variables have been set, so you can use this callback to perform any actions before the package starts building, such as exporting variables, adding symlinks, and so on. A step that exists to be overridden. Do what you need to do before we actually run the build steps. do_default_prepare()/Invoke-DefaultPrepare There is an empty default implementation of this callback. do_build()/Invoke-Build You should override this behavior if you have additional configuration changes to make or other software to build and install as part of building your package. This step builds the software; assumes the GNU pattern. Delegates most of the implementation to the `do_default_build()` function. do_default_build()/Invoke-DefaultBuild The default implementation is to update the prefix path for the configure script to use `$pkg_prefix` and then run `make` to compile the downloaded source. This means the script in the default implementation does `./configure --prefix=$pkg_prefix && make`. do_check()/Invoke-Check Will run post-compile tests and checks, provided 2 conditions are true: 1. A `do_check()` function has been declared. By default, no such function exists, so Plan author must add one explicitly–there is no reasonably good default here. 2. A `$DO_CHECK` environment variable is set to some non-empty value. As tests can dramatically inflate the build time of a Plan, this has been left as an opt-in option. Here’s an example of a vanilla Plan such as `sed`: ``` core-plans/sed/plan.sh pkg_name=sed # other Plan metadata... do_check() { make check } ``` do_install()/Invoke-Install Installs the software. Delegates most of the implementation to the `do_default_install()` function. You should override this behavior if you need to perform custom installation steps, such as copying files from `HAB_CACHE_SRC_PATH` to specific directories in your package, or installing pre-built binaries into your package. do_default_install()/Invoke-DefaultInstall The default implementation is to run `make install` on the source files and place the compiled binaries or libraries in `HAB_CACHE_SRC_PATH/$pkg_dirname`, which resolves to a path like `/hab/cache/src/packagename-version/`. It uses this location because of do_build() using the `--prefix` option when calling the configure script. do_build_config()/Invoke-BuildConfig Copy the `./config` directory, relative to the Plan, to `$pkg_prefix/config`. Do the same with `default.toml`. Delegates most of the implementation to the `do_default_build_config()` function. Allows users to depend on a core plan and pull in its configuration but set their own unique configurations at build time. do_default_build_config()/Invoke-DefaultBuildConfig Default implementation for the `do_build_config()` phase. do_build_service()/Invoke-BuildService Write out the `$pkg_prefix/run` file. If a file named `hooks/run` exists, we skip this step. Otherwise, we look for `$pkg_svc_run`, and use that. We assume that the binary used in the `$pkg_svc_run` command is set in the $PATH. This will write a `run` script that uses `chpst` to run the command as the `$pkg_svc_user` and `$pkg_svc_group`. These are `hab` by default. Delegates most of the implementation to the `do_default_build_server()` function. do_default_build_service()/Invoke-DefaultBuildService Default implementation of the `do_build_service()` phase. do_strip() `plan.sh` only. You should override this behavior if you want to change how the binaries are stripped, which additional binaries located in subdirectories might also need to be stripped, or whether you do not want the binaries stripped at all. do_default_strip() `plan.sh` only. The default implementation is to strip any binaries in `$pkg_prefix` of their debugging symbols. Goal of this step is to reduce our total size. do_after()/Invoke-After At this phase, the package has been built, installed, stripped, but before the package metadata is written and the artifact is created and signed. do_default_after()/Invoke-DefaultAfter There is an empty default implementation of this callback. do_end()/Invoke-End A function for cleaning up after yourself, this is called after the package artifact has been created. You can use this callback to remove any temporary files or perform other post-build clean-up actions. do_default_end()/Invoke-DefaultEnd There is an empty default implementation of this callback. do_after_success() `plan.sh` only. A function that is called at the absolute end of a successful build process. This can be used to provide integration points with external systems, among other things, particularly if you are not using Builder (a Notifications feature is coming to Builder in H2 2018). Failure of this callback will not fail your build, nor will it trigger a `do_after_failure` call. do_after_failure() `plan.sh` only. A function that is called at the absolute end of a failed build process. This can be used to provide integration points with external systems, among other things, particularly if you are not using Builder (a Notifications feature is coming to Builder in H2 2018). The result of this callback cannot affect the disposition of the overall build; once the build has failed, it’s failed. Keep in mind that since a build could potentially fail at any time, certain variables or data structures may not be present or initialized when this callback is called, so code accordingly. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/build_phase_callbacks/Control Supervisors Remotely ============================ [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_remote_control.md) Since the 0.56.0 Supervisor release, it is possible to command and control one or more Supervisors from a remote location. Before this, the only way to interact with a Supervisor was by taking action directly on machine on which the Supervisor was running. While that is still an option (and is indeed the default behavior), remote command and control opens up more possibilities for using and managing Chef Habitat. Here, we’ll discuss how this is implemented, how it can be enabled in your Chef Habitat deployments, and how it can be used. Remote Command and Control Overview ----------------------------------- The Chef Habitat Supervisor uses a defined TCP protocol for all interactions; the `hab` CLI tool is the client for this protocol, and the Supervisor is the server. Interactions are authenticated using a shared secret. Previously, in order to run `core/redis` on a Supervisor running on (say), `hab1.mycompany.com`, you would have to have direct access to the machine (as well as root privileges) in order to load the service, which might look like this: ``` ssh hab1.mycompany.com sudo hab svc load core/redis ``` Now, using the remote control capabilities of the Supervisor, this could be accomplished from a workstation or bastion host with an invocation that could be as simple as this: ``` hab svc load core/redis --remote-sup=hab1.mycompany.com:9632 ``` No direct host access is necessary, and multiple Supervisors can be controlled from one central location. ### Remote Control is Optional Operating Chef Habitat Supervisors remotely is purely optional; you must take positive action to enable this behavior. If you prefer, you can continue to manage Supervisors through on-the-box direct action, as before, and likely without any changes to your current procedures. Read on for further details about how to enable this ability, and how local interaction continues to operate through a new implementation. Managing Shared Supervisor Secrets ---------------------------------- Authentication between client (`hab` CLI) and server (Supervisor) is achieved using a shared secret. The `hab` CLI receives its secret from a configuration file (`~/.hab/config/cli.toml`) or from an environment variable (`HAB_CTL_SECRET`). The Supervisor reads its secret from its `CTL_SECRET` file, located at `/hab/sup/default/CTL_SECRET`. When the value used by `hab` matches the one used by the Supervisor, the requested command is carried out. ### Create a Secret Shared secrets are created in one of two ways. First, when a Supervisor starts up, will create a new secret in `/hab/sup/default/CTL_SECRET` automatically if one does not already exist. This is helpful for transparently upgrading older Supervisors and continuing to allow local interactions. Second, and most recommended, users can generate a new secret using `hab sup secret generate`: ``` hab sup secret generate VKca6ezRD0lfuwvhgeQLPSD0RMwE/ZYX5nYfGi2x0R1mXNh4QZSpa50H2deB85HoV/Ik48orF4p0/7MuVNPwNA== ``` This generates a new secret, printing it to standard output. Using the provisioner or configuration management tool of your choice, you can then use this value to create your own `/hab/sup/default/CTL_SECRET` file, ensuring that your Supervisor(s) are using a pre-determined key, instead of each making their own. If you have a pre-existing fleet of Supervisors which have already been started up with their own individually-generated secrets, you will likely want to overwrite their existing `CTL_SECRET` files with one that has a key of your own creation. If you are using a raw container-based deployment (i.e., not a managed platform like Kubernetes), you will want to mount an appropriate `CTL_SECRET` file into the container. ### Configure the Hab Cli with Your Secret Once you have a secret, you can add it to your local `hab` configuration file, preferably by running `hab cli setup` and following the interactive prompts. Alternatively, you can export it into your environment: ``` export HAB_CTL_SECRET="<KEY> ``` Note that your `hab` configuration file only keeps a single “secret” entry, and exporting a single secret into your environment does effectively the same thing. An assumption of this arrangement is that all Supervisors you wish to interact with have the same shared secret; if you wish to control a set of Supervisors that do not all use the same shared secret, you will need to manage the mapping of secret-to-supervisor yourself, which might look something like this: ``` HAB_CTL_SECRET=${secret_for_supervisor_1} hab svc load ... --remote-sup=${address_of_supervisor_1} HAB_CTL_SECRET=${secret_for_supervisor_2} hab svc load ... --remote-sup=${address_of_supervisor_2} # etc. ``` Configuring Supervisors for Remote Command and Control ------------------------------------------------------ As stated earlier, the Supervisor reads its secret from its `/hab/sup/default/CTL_SECRET` file, the contents of which you can control using `hab sup secret generate` and your chosen provisioner / deployment tooling. This ensures that the shared secret is in place, but one more step must be taken to fully enable the feature. By default, the Supervisor’s “control gateway” listens on the `127.0.0.1` interface for incoming commands. This means that it can only receive commands from the same machine, and not from remote clients. If you wish to control a Supervisor remotely, you’ll have to start the Supervisor setting its `--listen-ctl` option to an appropriate interface and port (9632 is the default control gateway port): ``` hab sup run --listen-ctl=0.0.0.0:9632 ``` This Supervisor would now be able to be controlled via any network interface (provided the request used the appropriate shared secret, of course). As always, be sure to use the appropriate interface values for your specific situation (e.g., pass an internal network-facing interface rather than a publicly-exposed interface). Targeting a Remote Supervisor ----------------------------- Throughout this documentation are numerous examples of interacting with a Supervisor; commands like `hab svc load`, `hab svc start`, `hab svc stop`, etc. all generate requests using the Supervisor’s defined interaction protocol. They all operate over TCP, even in the default case of interacting with a Supervisor on the same host. In order to target a remote Supervisor, you must have the appropriate shared secret available, as described above (either in the environment or in the `hab` CLI configuration file), and you must also specify the specific Supervisor using the `--remote-sup` option. The value for this option should correspond to the value of `--listen-ctl` the Supervisor was started with; it is the address and port at which the Supervisor’s control gateway may be reached. All Supervisor interaction commands accept a `--remote-sup` option for such targeting. Local Supervisor Interactions ----------------------------- Without specifying `--remote-sup`, the `hab` CLI will always try to connect to a Supervisor running on the current host. It must still use the correct shared secret, however. As a last resort, if no secret is found in either a configuration file or an environment variable, the `hab` CLI will attempt to read one from `/hab/sup/default/CTL_SECRET`. In this way, it will use the same secret that the local Supervisor is using, enabling the request to proceed. Protocol Versioning and `hab` Versions -------------------------------------- Before the 0.56.0 release of Chef Habitat, the interaction between `hab` and the Supervisor was not formally defined, and relied on making changes to files on disk. As a result, it was often possible to continue interacting with a newer Supervisor using an older version of the `hab` CLI. This was particularly noticeable when the Supervisor was configured to automatically update itself; the Supervisor would continue upgrading over time, while the `hab` CLI binary remained at whatever version it was when it was originally installed, because each of the two executable were distributed in separate packages. For the near term, `hab` and the Supervisor are still distributed separately, as `core/hab` and `core/hab-sup`, respectively. To interact with 0.56.0 or later Supervisors, users will need to use an 0.56.0 or later `hab` binary, even if they wish to continue interacting with their Supervisors only locally. This may require a manual upgrade for the `hab` binary, which can be done by running `hab pkg install core/hab -b -f`. In the near future, we hope to consolidate all of Chef Habitat’s functionality into a single package (if not a single binary), which will make it easier to manage going forward. The interaction protocol is defined using Google’s [Protocol Buffers](https://developers.google.com/protocol-buffers/); it is our explicit goal that all future changes to the protocol will happen in a backward-compatible way. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_remote_control/Build Helpers ============= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/build_helpers.md) The following helper functions can be useful in your plan to help you build your package correctly. `Attach()` specifically is to help with debugging - the other helper functions are to help you in building your package. Note Most of the following helper functions are not available in Powershell plans (`plan.ps1`). However in most cases, the standard Powershell cmdlets provide the same functionality. For example: use `Resolve-Path` instead of `abspath` or `Get-Command` instead of `exists`. attach() `plan.sh` only. Attaches your script to an interactive debugging session, which lets you check the state of variables, call arbitrary functions, and turn on higher levels of logging by using the `set -x` command and switch. To use attach, add `attach` to any callback or part of your plan.sh file and the debugging session with start up when hab-plan-build comes to that part in the file. Note Use the native Powershell cmdlet `Set-PSBreakpoint` for debugging plan.ps1 functions. You can set its `-Command` parameter to any build phase function. download_file() `plan.sh` only. Downloads a file from a source URL to a local file and uses an optional shasum to determine if an existing file can be used. ``` download_file <source_url> <local_file> [<shasum>] ``` If an existing file is present and the third argument is set with a shasum digest, the file will be checked to see if it’s valid. If so, the function ends early and returns 0. Otherwise, the shasums do not match so the file-on-disk is removed and a normal download proceeds as though no previous file existed. This is designed to restart an interrupted download. Any valid `wget` URL will work. Downloads every time, even if the file exists locally: ``` download_file http://example.com/file.tar.gz file.tar.gz ``` Downloads if no local file is found: ``` download_file http://example.com/file.tar.gz file.tar.gz expected_shasum ``` File matches checksum: download is skipped, local file is used: ``` download_file http://example.com/file.tar.gz file.tar.gz expected_shasum ``` File doesn’t match checksum: local file removed, download attempted: ``` download_file http://example.com/file.tar.gz file.tar.gz mismatching_shasum ``` Will return 0 if a file was downloaded or if a valid cached file was found. pkg_path_for()/Get-HabPackagePath Returns the path for a build or runtime package dependency on stdout from the list of dependencies referenced in `pkg_deps` or `pkg_build_deps`. This is useful if you need to install or reference specific dependencies from within a callback, such as `do_build()` or `do_install()`. Here’s an example of how to use this function to retrieve the path to the perl binary in the core/perl package: ``` _perl_path="$(pkg_path_for core/perl)/bin/perl" ``` fix_interpreter() `plan.sh` only. Edits the `#!` shebang of the target file in-place. This is useful for changing hard-coded paths defined by your source files to the equivalent path in a Chef Habitat package. You must include the required package that provides the expected path for the shebang in pkg_deps. This function performs a greedy match against the specified interpreter in the target file(s). To use this function in your plan, you must specify the following arguments: 1. The target file or files 2. The name of the package that contains the interpreter 3. The relative directory and binary path to the interpreter For example, to replace all the files in `node_modules/.bin` that have `#!/usr/bin/env` with the coreutils path to `bin/env` (/hab/pkgs/core/coreutils/8.24/20160219013458/bin/env), you must quote the wildcard target as shown below. ``` fix_interpreter "node_modules/.bin/*" core/coreutils bin/env ``` For a single target, reference the file directly: ``` fix_interpreter node_modules/.bin/concurrent core/coreutils bin/env ``` pkg_interpreter_for() `plan.sh` only. Returns the path for the given package and interpreter by reading it from the INTERPRETERS metadata in the package. The directory of the interpreter needs to be specified, as an interpreter binary might live in `bin`, `sbin`, or `libexec`, depending on the software. The following shows how to call pkg_interpreter_for with the package and interpreter arguments specified. ``` pkg_interpreter_for core/coreutils bin/env ``` This function will return 0 if the specified package and interpreter were found, and 1 if the package could not be found or the interpreter is not specified for that package. pkg_version() An optional way to determine the value for `$pkg_version`. The function must print the computed version string to standard output and will be called when the Plan author invokes the `update_pkg_version()` helper in a `plan.sh` or `Set-PkgVersion` in a `plan.ps1`. update_pkg_version()/Set-PkgVersion Updates the value for `$pkg_version` by calling a Plan author-provided `pkg_version()` function. This function must be explicitly called in a Plan in or after the `do_before()`/`Invoke-Before` build phase but before the `do_prepare()`/`Invoke-Prepare` build phase. The `$pkg_version` variable will be updated and any other relevant variables will be recomputed. The following examples show how to use these functions to set a dynamic version number. This plan concatenates a static file in the source root of the project to determine the version in the `before` phase: * [Bash](#bash-panel1) * [Powershell](#powershell-panel1) ``` pkg_version() { cat "$SRC_PATH/version.txt" } do_before() { do_default_before update_pkg_version } ``` ``` function pkg_version { Get-Content "$SRC_PATH/version.txt" } Invoke-Before { Invoke-DefaultBefore Set-PkgVersion } ``` The `pkg_version` function in this plan dynamically creates a version with a date stamp to format the final version string to standard output. As the downloaded file is required before running the version logic, this helper function is called in the `download` build phase: * [Bash](#bash-panel2) * [Powershell](#powershell-panel2) ``` pkg_version() { local build_date # Extract the build date of the certificates file build_date=$(cat $HAB_CACHE_SRC_PATH/$pkg_filename \ | grep 'Certificate data from Mozilla' \ | sed 's/^## Certificate data from Mozilla as of: //') date --date="$build_date" "+%Y.%m.%d" } do_download() { do_default_download update_pkg_version } ``` ``` function pkg_version { # Extract the build date of the certificates file $matchStr = "## Certificate data from Mozilla as of: " foreach($line in (Get-Content "$HAB_CACHE_SRC_PATH/$pkg_filename")) { if($line.StartsWith($matchStr)) { $build_date = $line.Substring($matchStr.Length) } } [DateTime]::Parse($build_date).ToString("yyyy.mm.dd") } function Invoke-Download { Invoke-DefaultDownload Set-PkgVersion } ``` abspath() `plan.sh` only. Return the absolute path for a path, which might be absolute or relative. exists() `plan.sh` only. Checks that the command exists. Returns 0 if it does, 1 if it does not. build_line()/Write-BuildLine Print a line of build output. Takes a string as its only argument. ``` build_line "Checksum verified - ${pkg_shasum}" ``` warn()/Write-Warning Print a warning line on stderr. Takes a string as its only argument. ``` warn "Checksum failed" ``` debug()/Write-Debug Prints a line only if the `$DEBUG` environment value is set to 1. The `debug` function takes a string as its only argument. ``` DEBUG=1 debug "Only if things are set" ``` exit_with() `plan.sh` only. Exits the program with an error message and a status code. ``` exit_with "Something bad happened" 55 ``` trim() `plan.sh` only. Trims leading and trailing whitespace characters from a bash variable. record() `plan.sh` only. Takes a session name and command to run as arguments function appends a timestamp to the log file. Alternative to piping build through tee. ``` # Usage: record <SESSION> [CMD [ARG ...]] record mysoftware build /src/mysoftware ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/build_helpers/Configuration Templates ======================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/config_templates.md) Chef Habitat allows you to templatize your application’s native configuration files using [Handlebars](https://handlebarsjs.com/) syntax. The following sections describe how to create tunable configuration elements for your application or service. Template variables, also referred to as tags, are indicated by double curly braces: `{{a_variable}}`. In Chef Habitat, tunable config elements are prefixed with `cfg.` to indicate that the value is user-tunable. Here’s an example of how to make a configuration element user-tunable. Assume that we have a native configuration file named `service.conf`. In `service.conf`, the following configuration element is defined: ``` recv_buffer 128 ``` We can make this user tunable like this: ``` recv_buffer {{cfg.recv_buffer}} ``` Chef Habitat can read values that it will use to render the templatized config files in three ways: 1. `default.toml` - Each plan includes a `default.toml` file that specifies the default values to use in the absence of any user provided inputs. These files are written in [TOML](https://github.com/toml-lang/toml), a simple config format. 2. At runtime - Users can alter config at runtime using `hab config apply`. The input for this command also uses the TOML format. 3. Environment variable - At start up, tunable config values can be passed to Chef Habitat using environment variables; this most over-riding way of setting these but require you to restart the supervisor to change them. Here’s what we’d add to our project’s `default.toml` file to provide a default value for the `recv_buffer` tunable: ``` recv_buffer = 128 ``` All templates located in a package’s `config` folder are rendered to a config directory, `/hab/svc/<pkg_name>/config`, for the running service. The templates are re-written whenever configuration values change. The path to this directory is available at build time in the plan as the variable `$pkg_svc_config_path` and available at runtime in templates and hooks as `{{pkg.svc_config_path}}`. All templates located in a package’s `config_install` folder are rendered to a config_install directory, `/hab/svc/<pkg_name>/config_install`. These templates are only accessible to the execution of an `install` hook and any changes to the values referenced by these templates at runtime will not result in re-rendering the template. The path to this directory is available at build time in the plan as the variable `$pkg_svc_config_install_path` and available at runtime in templates and `install` hooks as `{{pkg.svc_config_install_path}}`. Chef Habitat not only allows you to use Handlebars-based tunables in your plan, but you can also use both built-in Handlebars helpers as well as Chef Habitat-specific helpers to define your configuration logic. See [Reference](../build_helpers/index) for more information. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/config_templates/Configuration Management ======================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/configuration_management.md) **Examples: [Ansible](https://www.ansible.com/), [Chef](https://www.chef.io/chef/), [Puppet](https://puppet.com/), and [Salt](https://saltstack.com/)** Configuration management tools allow you write configuration files, using a declarative language to manage a server. These tools focus on building working servers by installing and configuring system settings, system libraries, and application libraries before an application is installed on the server. Chef Habitat focuses on the application first instead of the server. Chef Habitat builds and packages your application’s entire binary toolchain, including the system libraries, application libraries, and runtime dependencies necessary for your application to function. As a result, Chef Habitat can replace many use-cases that configuration management tools perform related to installing system binaries, application dependent libraries, or templating configuration files. Configuration management tools perform tasks at run time by converging resources. The value from configuration management tools comes from this converging process – checking the existing state of a server, and fixing it if it does not match the intended state. Because converging modifies resources at runtime, it can result in surprising and complex runtime errors. In addition, since environments are often mutable and unique, maintaining server automation occurs out-of-band with application development, creating conflict between application developers and software reliability engineers. Chef Habitat avoids these classes of errors entirely by shifting these processes to build time, and by creating an atomic package of an application’s binaries, application lifecycle hooks, and configuration files. Chef Habitat’s approach to packaging automation with the application package allows application developers and software reliability engineers to work closer together. Chef Habitat is not a full replacement for configuration management tools on mutable infrastructure. Instead, it allows configuration management tools to focus better on system-level tasks for virtual machines and bare metal, such as kernel tuning, system hardening tasks, and compliance remediation tasks. Chef Habitat can then take over application automation roles, which results in a significant reduction in automation complexity for both infrastructure-focused automation and application-focused automation. Chef Habitat can make it easier to run your existing configuration management tool. You can create a Chef Habitat package of your configuration management tool’s agent and/or dependencies, and run it on your existing mutable infrastructure. The Chef Habitat Supervisor’s responsibility is to update your configuration management tool’s agent, while your configuration management tool can still perform its normal tasks. Chef Habitat can provide an easier transition from virtual machine or bare metal workloads to containers, without needing to rewrite a monolithic application into microservices all at once. In this scenario, you can run the [Chef Habitat Supervisor](../sup/index) on your existing virtual machine or bare metal infrastructure as you migrate away from your configuration management tool. Then, when you’re ready, you export your application to the container format of your choice using the [Chef Habitat Studio](../pkg_build/index). While you migrate your applications and services, the [Chef Habitat Supervisor](../sup/index) runs on your existing mutable infrastructure, and runs your existing configuration management tool. New packages that do not require configuration management can also run under the [Chef Habitat Supervisor](../sup/index) on your existing mutable infrastructure. As a result, you can continue to verify the working state of your application as you incrementally migrate your services. This approach provides an alternative to the “all-or-nothing” migration many teams are faced with when moving workloads to containers. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/configuration_management/Configuration Helpers ===================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/plan_helpers.md) Chef Habitat allows you to use [Handlebars-based](http://handlebarsjs.com) tuneables in your plan, and you can also use both built-in Handlebars helpers and Chef Habitat-specific helpers in defining your configuration logic. Built-in Helpers ---------------- You can use block expressions to add basic logic to your template such as checking if a value exists or iterating through a list of items. Block expressions use a helper function to perform the logic. The syntax is the same for all block expressions and looks like this: ``` {{#helper blockname}} {{expression}} {{/helper}} ``` Chef Habitat supports the standard [built-in helpers](https://handlebarsjs.com/builtin_helpers.html): * `if` * `unless` * `each` * `with` * `lookup` * `>` ([partials](http://handlebarsjs.com/partials.html)) * `log` Note Per [Handlebars Paths](http://handlebarsjs.com/#paths), when using `each` in a block expression, you must reference the parent context of that block to use any user-defined configuration values referenced *within* the block, such as those that start with `cfg`. For example, if your block looked like the following, you must reference `cfg.port` from the parent context of the block: ``` {{#each svc.members ~}} server {{sys.ip}}:{{../cfg.port}} {{/each}} ``` The most common block helpers that you will probably use are the `if` and `with` helpers. if The `if` helper evaluates conditional statements. The values `false`, 0, “”, as well as undefined values all evaluate to false in `if` blocks. Here’s an example that will only write out configuration for the unixsocket tunable if a value was set by the user: ``` {{#if cfg.unixsocket ~}} unixsocket {{cfg.unixsocket}} {{/if ~}} ``` Note The `~` indicates that whitespace should be omitted when rendering. TOML allows you to create sections (called [TOML tables](https://github.com/toml-lang/toml#table)) to better organize your configuration variables. For example, your `default.toml` or user defined TOML could have a `[repl]` section for variables controlling replication behavior. Here’s what that looks like: ``` [repl] backlog-size = 200 backlog-ttl = 100 disable-tcp-nodelay = no ``` When writing your template, you can use the `with` helper to reduce duplication: ``` {{#with cfg.repl ~}} repl-backlog-size {{backlog-size}} repl-backlog-ttl {{backlog-ttl}} repl-disable-tcp-nodelay {{disable-tcp-nodelay}} {{/with ~}} ``` Helpers can also be nested and used together in block expressions. Here is another example from the redis.config file where the `if` and `with` helpers are used together to set up `core/redis` Chef Habitat services in a leader-follower topology. ``` {{#if svc.me.follower ~}} replicaof {{svc.leader.sys.ip}} {{svc.leader.cfg.port}} {/if ~}} ``` each Here’s an example using each to render multiple server entries: {{#each cfg.servers as |server| ~}} server { host {{server.host}} port {{server.port}} } {{/each ~}} You can also use each with `@key` and `this`. Here is an example that takes the `[env]` section of your default.toml and makes an env file you can source from your run hook: ``` {{#each cfg.env ~}} export {{toUppercase @key}}={{this}} {{/each ~}} ``` You would specify the corresponding values in a TOML file using an [array of tables](https://github.com/toml-lang/toml#array-of-tables) like this: ``` [[servers]] host = "host-1" port = 4545 [[servers]] host = "host-2" port = 3434 ``` And for both each and unless, you can use `@first` and `@last` to specify which item in an array you want to perform business logic on. For example: ``` "mongo": { {{#each bind.database.members as |member| ~}} {{#if @first ~}} "host" : "{{member.sys.ip}}", "port" : "{{member.cfg.port}}" {{/if ~}} {{/each ~}} } ``` Note The `@first` and `@last` variables also work with the Chef Habitat helper `eachAlive`, and in the example above, it would be preferable to the built-in `each` helper because it checks whether the service is available before trying to retrieve any values. unless For `unless`, using `@last` can also be helpful when you need to optionally include delimiters. In the example below, the IP addresses of the alive members returned by the `servers` binding is comma-separated. The logic check `{{#unless @last}}, {{/unless}}` at the end ensures that the comma is written after each element except the last element. {{#eachAlive bind.servers.members as |member| ~}} “{{member.sys.ip}}” {{#unless @last ~}}, {{/unless ~}} {{/eachAlive ~}}] Plan Helpers ------------ Chef Habitat’s templating flavour includes a number of custom helpers for writing configuration and hook files. toLowercase Returns the lowercase equivalent of the given string literal. ``` my_value={{toLowercase "UPPER-CASE"}} ``` toUppercase Returns the uppercase equivalent of the given string literal. ``` my_value={{toUppercase "lower-case"}} ``` strReplace Replaces all matches of a pattern within the given string literal. ``` my_value={{strReplace "this is old" "old" "new"}} ``` This sets `my_value` to “this is new”. pkgPathFor Returns the absolute filepath to the package directory of the package best resolved from the given package identifier. The named package must exist in the `pkg_deps` of the plan from which the template resides. The helper will return a nil string if the named package is not listed in the `pkg_deps`. As result you will always get what you expect and the template won’t leak to other packages on the system. Example Plan Contents: ``` pkg_deps=("core/jre8") ``` Example Template: ``` export JAVA_HOME={{pkgPathFor "core/jre8"}} ``` Example pointing to specific file in `core/nginx` package on disk: ``` {{pkgPathFor "core/nginx"}}/config/fastcgi.conf ``` eachAlive Iterates over a collection of members and renders the template for members that are marked alive. ``` {{~#eachAlive bind.backend.members as |member|}} server ip {{member.sys.ip}}:{{member.cfg.port}} {{~/eachAlive}} ``` toJson To output configuration data as JSON, you can use the `toJson` helper. Given a default.toml that looks like: ``` [web] [[servers]] host = "host-1" port = 4545 [[servers]] host = "host-2" port = 3434 ``` and a template: ``` {{toJson cfg.web}} ``` when rendered, it will look like: ``` { "servers": [ { "host": "host-1", "port": 4545 }, { "host": "host-2", "port": 3434 } ] } ``` This can be useful if you have a configuration file that is in JSON format and has the same structure as your TOML configuration data. toToml The `toToml` helper can be used to output TOML. Given a default.toml that looks like: ``` [web] port = 80 ``` and a template: ``` {{toToml cfg.web}} ``` when rendered, it will look like: ``` port = 80 ``` This can be useful if you have an app that uses TOML as its configuration file format, but may have not been designed for Chef Habitat, and you only need certain parts of the configuration data in the rendered TOML file. toYaml The `toYaml` helper can be used to output [YAML](https://yaml.org/). Given a default.toml that looks like: ``` [web] port = 80 ``` and a template: ``` {{toYaml cfg}} ``` when rendered, it will look like: ``` +++web:port:80 ``` The helper outputs a YAML document (with a line beginning with `+++`), so it must be used to create complete documents: you cannot insert a section of YAML into an existing YAML document with this helper. strJoin The `join` helper can be used to create a string with the variables in a list with a separator specified by you. For example, where `list: ["foo", "bar", "baz"]`, `{{strJoin list ","}}` would return `"foo,bar,baz"`. You cannot join an object (e.g. `{{strJoin web}}`), but you could join the variables in an object (e.g. `{{strJoin web.list "/"}}`). strConcat The `concat` helper can be used to connect multiple strings into one string without a separator. For example, `{{strConcat "foo" "bar" "baz"}}` would return `"foobarbaz"`.\ You cannot concatenate an object (e.g. `{{strConcat web}}`), but you could concatenate the variables in an object (e.g. `{{strConcat web.list}}`). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/plan_helpers/Keys ==== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/keys.md) Chef Habitat has strong cryptography built into Chef Habitat Builder, the Supervisor, and the `hab` CLI commands. This means there are several different kinds of keys. Origin Key Pairs ---------------- Every Chef Habitat artifact belongs to an [origin](../pkg_ids/index) and is cryptographically signed with that origin’s private key. Chef Habitat requires the private key for producing artifacts and requires the public key for verification of artifacts before installation. If it is present on Builder, Chef Habitat will automatically download the public key for an origin when necessary. Origin key cryptography is asymmetric: it has a public key that you can distribute freely, and a private key that you should keep safe. Chef Habitat uses the public origin key to verify the integrity of downloaded artifacts before installing them. Chef Habitat will only install artifacts for which it has the public origin key. You can provide a public origin key to Chef Habitat by pointing it to a Builder site that has the origin key with the `--url` argument to `hab pkg install` or using the `hab origin key import` command. Use `hab origin key upload` to upload origin keys to Builder. Use `hab origin key download` to download your origin keys from Builder to your environment. Use `hab origin key import` to read the key from a standard input stream or local file: ``` hab origin key import <enter or paste key> hab origin key import < <PATH_TO_KEY> curl <URL_THAT_RETURNS_KEY> | hab origin key import ``` See the [hab origin key](../habitat_cli/index#hab-origin-key) command documentation for more information about working with origin keys from the command line. User and Service Group Keys --------------------------- User and service group keys are used to set up trust relationships between these two entities. Service groups can be set up to reject communication (e.g. applying new configuration via `hab config apply`) from untrusted users. By default, service groups will trust *any* communication, so for a production deployment of Chef Habitat, setting up these relationships is essential. User and service group keys also use asymmetric cryptography. To apply configuration changes to service groups when running in this mode, a user uses their own private key to encrypt configuration information for a service group, using that service group’s public key. The service group then uses its private key to decrypt the configuration information, and the user’s public key to verify. Ring Encryption Key ------------------- A Supervisor network can be optionally set up to encrypt *all* supervisor-to-supervisor communication. This requires the use of a symmetric, pre-shared key. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/keys/Custom Certificates =================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/certs_custom.md) Many enterprise environments use custom certificates (for example, self-signed). For example, an on-premises Chef Habitat Builder Depot might have a self-signed SSL certificate. Attempting to perform an operation using the Habitat client to communicate with a service that has a custom certificate can produce an error, such as: ``` ✗✗✗ ✗✗✗ the handshake failed: The OpenSSL library reported an error: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed:s3_clnt.c:1269:: unable to get local issuer certificate ✗✗✗ ``` One option to remediate this error is to define a `SSL_CERT_FILE` environment variable pointing to the custom certificate path before performing the client operation. The Habitat 0.85.0 release in September 2019 improved the handling of custom certificates. Now Habitat knows to look for custom certificates in the `~/.hab/cache/ssl` directory, which is `/hab/cache/ssl` when you are running as root. Copying multiple certificates–for example, a self-signed certificate and a custom certificate authority certificate–to the Chef Habitat cache directory makes them automatically available to the Habitat client. The `/hab/cache/ssl` directory is also available inside a Habitat Studio. As long as the certificates are inside the cache directory before you enter the Studio, you’ll also find them inside the Studio. In addition, if you’ve set the `SSL_CERT_FILE` environment variable, you’ll also find both it and the file that it points to inside the Studio`/hab/cache/ssl` directory. Note: The `cert.pem` file name is reserved for Habitat. Do not use `cert.pem` as a file name when copying certs into the cache directory. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/certs_custom/Package Contents ================ [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/package_contents.md) During the build process, the hab-plan-build script creates several files that specify dependency, build, and configuration information. When packages are unpacked (extracted) and installed during the initialization phase of a Chef Habitat service, these files define what those packages need to run. Packages are installed in the `/hab/pkgs/` directory, and then further organized in subdirectories corresponding to fully-qualified package identifiers: `origin/name/version/release`. For more information on package identifiers, see [Packages](../pkg_ids/index). Contents of a Chef Habitat package ---------------------------------- BUILD_DEPS Fully-qualified package identifiers of any build dependencies that your package depends on. These are listed in the root plan.sh file of your plan directory. BUILD_TDEPS Fully-qualified package identifiers of any runtime dependencies that the build dependencies for your project depend on. This is essentially a flattened tree of dependencies all the way up to the root dependency (`linux-headers` in most cases). BUILDTIME_ENVIRONMENT A file that contains similar information as the RUNTIME_ENVIRONMENT file, but is constructed from a package’s build-time dependencies instead of its runtime dependencies. This file is not currently consumed by any other software in the Chef Habitat ecosystem, but can be used for troubleshooting and informative purposes. BUILDTIME_ENVIRONMENT_PROVENANCE A file that provides information on which specific dependencies have influenced the final value of a given variable in the BUILDTIME_ENVIRONMENT file. This file is not currently consumed by any other software in the Chef Habitat ecosystem, but can be used for troubleshooting and informative purposes. CFLAGS Additional switches to be passed to the compiler when this package is used as a build dependency. DEPS Runtime dependencies for your package. These dependencies are processed by Chef Habitat and their corresponding environment variables (such as `PATH` and `LD_LIBRARY_PATH`) are added to the current environment. FILES List of all files in this package along with their blake2b checksums. The FILES file itself is signed using `hab pkg sign` to provide an assurance that its contents haven’t been tampered with. IDENT The fully-qualified identifier for the package. The format is `origin/name/version/release`. INTERPRETERS If `pkg_interpreters` is specified in your plan.sh, then this file will be generated and contain a list of absolute paths to any interpreters that a package can provide. Code in a `plan.sh` may use the `fix_interpreter` function to replace hard-coded instances of interpreters, such as `/bin/env`. The location of interpreters in Chef Habitat will be nested under `/hab/pkgs/`. For more information on interpreters, see the fix_interpreter description in [Plan helper functions](../build_helpers/index). LDFLAGS Additional switches to be passed to the compiler when this package is used as a build dependency. LD_RUN_PATH Additional switches to be passed to the compiler when this package is used as a build dependency. MANIFEST A file containing package information, such as checksum, maintainer, build variables, and other metadata specified in plan.sh as well as the contents of the plan.sh itself. PATH A file that contains all directories in the package which contain program binaries. The directories are separated with the target platform’s path separator character (i.e. either `:` or `;`). RUNTIME_ENVIRONMENT A file containing the result of the layering operation of the current package’s runtime environment variables on top of those of its dependencies. This is what the build process consults when it processes dependencies, and this is what the Supervisor consults in concert with `RUNTIME_PATH` when generating the full set of environment variables that should be added to an environment before running a supervised process. RUNTIME_ENVIRONMENT_PROVENANCE A file that provides information on which specific dependencies have influenced the final value of a given variable in the RUNTIME_ENVIRONMENT file. This file is not currently consumed by any other software in the Chef Habitat ecosystem, but can be used for troubleshooting and informative purposes. RUNTIME_PATH A file that contains all directories that need to be prepended to an environment’s `$PATH` before a program in this package can be expected to run correctly. The order of the elements are precise and meaningful so should not be altered. This file is used in concert with `RUNTIME_ENVIRONMENT` to compute the full set of environment variables that should be added to an environment before running a program in this package. TARGET The CPU architecture and platform for the package. The format is `architecture-platform`. For example, x86_64-linux. TDEPS Fully-qualified package identifiers of any runtime dependencies that the runtime dependencies for your project depend on. This is essentially a flattened tree of dependencies all the way up to the root dependency (`linux-headers` in most cases). SVC_GROUP The value of `pkg_svc_group` from a plan. The Chef Habitat Supervisor will try to start a service with this group if it exists. SVC_USER The value of `pkg_svc_user` from a plan. The Chef Habitat Supervisor will try to start a service with this user if it exists. default.toml If you have defined a `default.toml` file in the root of your plan, then it will be included in the same relative location within the installed package directory. For more information on configuration and the default.toml file, see [Configuration Updates](../service_updates/index). config directory If you have defined a `config` subdirectory with a templatized configuration file in your plan, then they will be included in the same relative location within the installed package directory. For more information on templatized configuration files, see [Add configuration to plans](../config_templates/index). config_install directory If you have defined a `config_install` subdirectory with a templatized configuration file in your plan, then they will be included in the same relative location within the installed package directory. For more information on templatized configuration files, see [Add configuration to plans](../config_templates/index). hooks directory If you have defined a `hooks` subdirectory with hook scripts in your plan, then they will be included in the same relative location within the installed package directory. Read more about [Application Lifecycle Hooks](../application_lifecycle_hooks/index). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/package_contents/Package Identifiers =================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/pkg_ids.md) A Chef Habitat artifact the binary distribution for a given package built with Chef Habitat. A Chef Habitat artifact is a signed tarball with a `.hart` file extension. Chef Habitat artifacts are composed of a software library or application, the configuration information for that software, and lifecycle hooks. They are created from a the plan file, a `plan.sh` on Linux systems or a `plan.ps1` on Windows systems, and are built with Chef Habitat tools. Chef Habitat artifacts can be exported to a specific format, such as when creating a Docker image. When referring to Chef Habitat artifacts from either Builder or the Studio, you can refer to them in two ways: * Fully-qualified package identifier (FQPI) - Uses four components in the following format: `origin/name/version/release`. For example, `core/glibc/2.22/20160310192356`. * Short package identifier - Uses two components in the following format `origin/name`. For example, `core/redis` or `core/openssl`. Use the three-component form `origin/name/version`, such as `core/redis/5.0.4`, when you need a specific version of an artifact. Package Identifier Components ----------------------------- * `Origin`: A name that defines a set of related Chef Habitat packages and the artifacts they generate. For example, “sample”, “core”, or “mycompany”. * `Name`: The name of the application or service. For example, “postgres”. * `Version`: The version number designation by the author(s) of the application or service. For example, “3.1.1”, or “20160118”. * `Release`: The unique Chef Habitat id for a given version based on the timestamp pattern *YYYYMMDDhhmmss*. For example, “20160204220358” would be a Chef Habitat artifact built at 22:03:58 on February 4th, 2016. Package Lookup -------------- If the Chef Habitat artifact identifier isn’t fully qualified (having fewer than four components), and exactly one artifact is required, then the missing components are assumed to be the most recent values. For example: * `core/glibc` assumes that version and release values are for the latest version of core/glibc. * `core/glibc/2.22` assumes that the version of core/glibc is 2.22 and that the release is for the most recent value of core/glibc/2.22. * `core/glibc/2.22/20160310192356` only refers to the specific Chef Habitat artifact 20160310192356. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/pkg_ids/Pattern Library Introduction ============================ [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/pattern_library.md) Chef Habitat Pattern Library ---------------------------- The Chef Habitat Pattern Library is an evolving set of design patterns to use as starting-points. These patterns are examples and require configuration and customization for your unique situation. For help with Chef Habitat and these patterns, ask: * Your customer support agent * In the [Chef Discourse](https://discourse.chef.io/c/habitat/) Kubernetes Bastion Ring Pattern ------------------------------- A *bastion ring* is a robust type of Supervisor network in which a small number of Supervisors are set up as permanent peers and that are dedicated to anchoring Supervisor network communication. These Supervisors are designated solely for communication between Supervisor and *do not run services*. These solely to anchor the entire Supervisor network. See [Supervisor Networks](../sup_networks/index) for more information. The following examples demonstrate running a bastion ring in Kubernetes. ### Kubernetes Bastion Ring Plan ``` pkg_name=hab_bastion pkg_origin=habitat pkg_version="0.1.0" pkg_maintainer="irvingpop" pkg_license=("Apache-2.0") pkg_deps=(core/busybox-static) pkg_svc_run="while true; do sleep 60; done" do_build() { return 0 } do_install() { return 0 } ``` ### Kubernetes Bastion Ring Producer Pattern ``` ---apiVersion:v1kind:Servicemetadata:name:hab-bastionspec:ports:- name:gossip-listenerprotocol:UDPport:9638targetPort:9638- name:http-gatewayprotocol:TCPport:9631targetPort:9631selector:app:hab-bastionclusterIP:None---apiVersion:apps/v1kind:StatefulSetmetadata:name:hab-bastionspec:selector:matchLabels:app:hab-bastionserviceName:hab-bastionreplicas:1template:metadata:labels:app:hab-bastionspec:terminationGracePeriodSeconds:10securityContext:fsGroup:42containers:- name:hab-bastionimage:irvingpop/hab_bastion:latestargs:- '--permanent-peer'resources:requests:memory:"100Mi"cpu:"100m"# equivalent to 0.1 of a CPU coreports:- name:gossip-listenerprotocol:UDPcontainerPort:9638- name:http-gatewayprotocol:TCPcontainerPort:9631readinessProbe:httpGet:path:/port:9631initialDelaySeconds:5periodSeconds:10livenessProbe:httpGet:path:/port:9631initialDelaySeconds:15periodSeconds:20volumeMounts:- name:hab-bastionmountPath:/hab/supvolumeClaimTemplates:- metadata:name:hab-bastionspec:accessModes:["ReadWriteOnce"]# uncomment if you don't have a default storageclass# storageClassName: "standard"resources:requests:storage:10Gi ``` ### Kubernetes Bastion Ring Consumer Pattern ``` apiVersion:apps/v1kind:StatefulSetmetadata:name:cockroachdbspec:selector:matchLabels:app:cockroachdbserviceName:cockroachdbreplicas:3template:metadata:labels:app:cockroachdbspec:terminationGracePeriodSeconds:10securityContext:fsGroup:42containers:- name:cockroachdbimage:irvingpop/cockroach:latestargs:- --peer- hab-bastion- --topology- leader# env:# - name: HAB_COCKROACH# value: |resources:requests:memory:"300Mi"cpu:"500m"# equivalent to 0.5 CPU coreports:- name:httpcontainerPort:8080- name:cockroachdbcontainerPort:26257volumeMounts:- name:cockroachdb-datamountPath:/hab/svc/cockroach/datavolumeClaimTemplates:- metadata:name:cockroachdb-dataspec:accessModes:["ReadWriteOnce"]resources:requests:storage:10Gi ``` hab pkg download Patterns ------------------------- The `hab pkg download` command can be used to download individual packages (along with their dependencies and keys) from Builder, without installing them. This allows you to more easily transfer packages from one Builder instance to another, or to take a selective snapshot of particular packages. While you can download packages one-at-a-time, it can be more convenient to use a file to specify your packages. Two formats are recognized: plain text and TOML. ### Plain Text Download Descriptors The simplest thing you can do is create a plain text file with a package identifier on each line, like so: ``` # These are the packages needed to run a Supervisor core/hab-launcher core/hab core/hab-sup ``` Each line is a valid package identifier. You can also add comments using `#`. To download these packages (and their dependencies), save that to a file named `supervisor.txt` and run: ``` hab pkg download --file=supervisor.txt ``` This will download the packages into your existing Habitat cache directory. Alternatively, you can specify a directory using the `--download-directory` option. (You can also specify `--channel` and `--target` to further control which specific packages you download; run `hab pkg download --help` for more). ### TOML Download Descriptors Plain text is fine for simple cases, but has drawbacks. For instance, all packages will come from the same channel and will be for the same platform target. For maximum flexibility, you’ll want to use TOML to write your download descriptor. Here is an example of one that the Habitat core team uses to take periodic snapshots of everything needed to run Builder itself: ``` format_version = 1 file_descriptor = "Packages needed to run an instance of Builder" [[x86_64-linux]] channel = "stable" packages = [ # Supervisor and prerequisites "core/hab-launcher", "core/hab", "core/hab-sup", # Utilities "core/sumologic", "core/nmap" ] # Targets can be repeated to specify additional subsets of packages, # possibly from different channels [[x86_64-linux]] channel = "stable" packages = [ # Builder services "habitat/builder-api", "habitat/builder-api-proxy", "habitat/builder-jobsrv", "habitat/builder-worker", "habitat/builder-memcached", ] [[x86_64-linux-kernel2]] channel = "stable" packages = [ # Supervisor and prerequisites "core/hab-launcher", "core/hab", "core/hab-sup", "habitat/builder-worker" ] [[x86_64-windows]] channel = "stable" packages = [ # Supervisor and prerequisites "core/windows-service", "core/hab", "core/hab-sup", "habitat/builder-worker" ] ``` This format allows us to specify multiple subsets of packages from different channels and for different architectures. Here, we are pulling down all the core service packages, which run on Linux, but are also pulling down the platform-specific versions of the `habitat/builder-worker` package. Without this format, we would have to invoke `hab pkg download` multiple times with different parameters. The file allows us to capture our full intention in one place. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/pattern_library/Environment Variables ===================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/environment_variables.md) This is a list of all environment variables that can be used to modify the operation of the Chef Habitat Studio and Supervisor. | Variable | Context | Default | Description | | --- | --- | --- | --- | | `HAB_AUTH_TOKEN` | build system | no default | Authorization token used to perform privileged operations against the depot, e.g. uploading packages or keys. | | `HAB_BINLINK_DIR` | build system | `/hab/bin` | Allows you to change the target directory for the symlink created when you run `hab pkg binlink`. The default value is already included in the `$PATH` variable inside the Studio. | | `HAB_CACHE_KEY_PATH` | build system, Supervisor | `/hab/cache/keys` if running as root; `$HOME/.hab/cache/keys` if running as non-root | Cache directory for origin signing keys | | `HAB_CTL_SECRET` | Supervisor | no default | Shared secret used for [communicating with a Supervisor](../sup_remote_control/index). | | `HAB_BLDR_CHANNEL` | build system, Supervisor | `stable` | Set the Chef Habitat Builder channel you are subscribing to, to a specific channel. Defaults to `stable`. | | `HAB_BLDR_URL` | build system, Supervisor | `https://bldr.habitat.sh` | Sets an alternate default endpoint for communicating with Builder. Used by the Chef Habitat build system and the Supervisor | | `HAB_DOCKER_OPTS` | build system | no default | When running a Studio on a platform that uses Docker (macOS), additional command line options to pass to the `docker` command. | | `HAB_INTERNAL_BLDR_CHANNEL` | build system, Supervisor, exporters | `stable` | Channel from which Chef Habitat-specific packages (e.g., `core/hab-sup`, `core/hab-launcher`, etc.) are downloaded on-demand when first called. Generally of use only for those developing Chef Habitat. Only applies to Chef Habitat-specific packages, and nothing else. | | `HAB_LICENSE` | build system, Supervisor, exporters | no default | Used to accept the [Chef EULA](../../chef_license#chef-eula). See [Accepting the Chef License](../../chef_license_accept#habitat) for valid values. | | `HAB_LISTEN_CTL` | Supervisor | 127.0.0.1:9632 | The listen address for the Control Gateway. This also affects `hab` commands that interact with the Supervisor via the Control Gateway, for example: `hab sup status`. | | `HAB_LISTEN_GOSSIP` | Supervisor | 0.0.0.0:9638 | The listen address for the Gossip System Gateway | | `HAB_LISTEN_HTTP` | Supervisor | 0.0.0.0:9631 | The listen address for the HTTP Gateway | | `HAB_NOCOLORING` | build system | no default | If set to the lowercase string `"true"` this environment variable will unconditionally disable text coloring where possible | | `HAB_NONINTERACTIVE` | build system | no default | If set to the lowercase string `"true"` this environment variable will unconditionally disable interactive progress bars (i.e. “spinners”) where possible | | `HAB_ORG` | Supervisor | no default | Organization to use when running with [service group encryption](../sup_secure/index) | | `HAB_ORIGIN` | build system | no default | Origin used to build packages. The signing key for this origin is passed to the build system. | | `HAB_ORIGIN_KEYS` | build system | no default | Comma-separated list of origin keys to automatically share with the build system | | `HAB_RING` | Supervisor | no default | The name of the ring used by the Supervisor when running with [wire encryption](../sup_secure/index) | | `HAB_RING_KEY` | Supervisor | no default | The contents of the ring key when running with [wire encryption](../sup_secure/index). Useful when running in a container. | | `HAB_STUDIO_SECRET_<VARIABLE>` | build system | no default | Prefix to allow environment variables into the Studio. The prefix will be removed and your variable will be passed into the Studio at build time. | | `HAB_STUDIOS_HOME` | build system | `/hab/studios` | Directory in which to create build Studios | | `HAB_STUDIO_BACKLINE_PKG` | build system | `core/hab-backline/{{studio_version}}` | Overrides the default package identifier for the “backline” package which installs the Studio baseline package set. | | `HAB_STUDIO_ROOT` | build system | no default | Root of the current Studio under `$HAB_STUDIOS_HOME`. Infrequently overridden. | | `HAB_STUDIO_NOSTUDIORC` | build system | no default | When set to a non-empty value, a `.studiorc` will not be sourced when entering an interactive Studio via `hab studio enter`. | | `HAB_STUDIO_SUP` | build system | no default | Used to customize the arguments passed to an automatically launched Supervisor, or to disable the automatic launching by setting it to `false`, `no`, or `0`. | | `HAB_GLYPH_STYLE` | build system | `full` (`limited` on Windows) | Used to customize the rendering of unicode glyphs in UI messages. Valid values are `full`, `limited`, or `ascii`. | | `HAB_SUP_UPDATE_MS` | Supervisor | 60000 | Interval in milliseconds governing how often to check for Supervisor updates when running with the [–auto-update](../habitat_cli/index#hab-sup-run) flag. Note: This variable has been deprecated. Users should instead use the [–auto-update-period](../habitat_cli/index#hab-sup-run) flag. | | `HAB_UPDATE_STRATEGY_FREQUENCY_MS` | Supervisor | 60000 | Interval in milliseconds governing how often to check for service updates when running with an [update strategy](../service_updates/index). Note: This variable has been deprecated. Users should instead use the [–service-update-period](../habitat_cli/index#hab-sup-run) flag. | | `HAB_USER` | Supervisor | no default | User key to use when running with [service group encryption](../sup_secure/index) | | `http_proxy` | build system, Supervisor | no default | A URL for a local HTTP proxy server optionally supporting basic authentication | | `https_proxy` | build system, Supervisor | no default | A URL for a local HTTPS proxy server optionally supporting basic authentication | | `NO_INSTALL_DEPS` | build system | no default | Set this variable to prevent dependencies install during build | | `no_proxy` | build system, Supervisor | no default | A comma-separated list of domain exclusions for the `http_proxy` and `https_proxy` environment variables | | `SSL_CERT_FILE` | system | no default | Standard OpenSSL environment variable to override the system certificate file. This is particularly important for the secure HTTPS connection with a Builder instance. Can be used to help you navigate corporate firewalls. | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/environment_variables/Chef Habitat Command-Line Interface (CLI) Reference =================================================== The commands for the Chef Habitat CLI (`hab`) are listed below. | Applies to Version | Last Updated | | --- | --- | | hab 1.6.420/20211101172443 (linux) | 1 Nov 2021 | hab --- **USAGE** ``` hab <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **ALIASES** ``` apply Alias for: 'config apply' install Alias for: 'pkg install' run Alias for: 'sup run' setup Alias for: 'cli setup' start Alias for: 'svc start' stop Alias for: 'svc stop' term Alias for: 'sup term' ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab bldr](#hab-bldr) | Commands relating to Habitat Builder | | [hab cli](#hab-cli) | Commands relating to Habitat runtime config | | [hab config](#hab-config) | Commands relating to a Service’s runtime config | | [hab file](#hab-file) | Commands relating to Habitat files | | [hab license](#hab-license) | Commands relating to Habitat license agreements | | [hab origin](#hab-origin) | Commands relating to Habitat Builder origins | | [hab pkg](#hab-pkg) | Commands relating to Habitat packages | | [hab plan](#hab-plan) | Commands relating to plans and other app-specific configuration | | [hab ring](#hab-ring) | Commands relating to Habitat rings | | [hab studio](#hab-studio) | Commands relating to Habitat Studios | | [hab sup](#hab-sup) | The Habitat Supervisor | | [hab supportbundle](#hab-supportbundle) | Create a tarball of Habitat Supervisor data to send to support | | [hab svc](#hab-svc) | Commands relating to Habitat services | | [hab user](#hab-user) | Commands relating to Habitat users | --- hab bldr -------- Commands relating to Habitat Builder **USAGE** ``` hab bldr <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab bldr channel](#hab-bldr-channel) | Commands relating to Habitat Builder channels | | [hab bldr job](#hab-bldr-job) | Commands relating to Habitat Builder jobs | --- ### hab bldr channel Commands relating to Habitat Builder channels **USAGE** ``` hab bldr channel <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab bldr channel create](#hab-bldr-channel-create) | Creates a new channel | | [hab bldr channel demote](#hab-bldr-channel-demote) | Atomically demotes selected packages in a target channel | | [hab bldr channel destroy](#hab-bldr-channel-destroy) | Destroys a channel | | [hab bldr channel list](#hab-bldr-channel-list) | Lists origin channels | | [hab bldr channel promote](#hab-bldr-channel-promote) | Atomically promotes all packages in channel | --- ### hab bldr channel create Creates a new channel **USAGE** ``` hab bldr channel create [OPTIONS] <CHANNEL``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -o, --origin <ORIGIN> Sets the origin to which the channel will belong. Default is from 'HAB_ORIGIN' or cli.toml ``` **ARGS** ``` <CHANNEL> The channel name ``` --- ### hab bldr channel demote Atomically demotes selected packages in a target channel **USAGE** ``` hab bldr channel demote [OPTIONS] <SOURCE_CHANNEL> <TARGET_CHANNEL> --origin <ORIGIN``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -o, --origin <ORIGIN> The origin for the channels. Default is from 'HAB_ORIGIN' or cli.toml ``` **ARGS** ``` <SOURCE_CHANNEL> The channel from which all packages will be selected for demotion <TARGET_CHANNEL> The channel selected packages will be removed from ``` --- ### hab bldr channel destroy Destroys a channel **USAGE** ``` hab bldr channel destroy [OPTIONS] <CHANNEL``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -o, --origin <ORIGIN> Sets the origin to which the channel belongs. Default is from 'HAB_ORIGIN' or cli.toml ``` **ARGS** ``` <CHANNEL> The channel name ``` --- ### hab bldr channel list Lists origin channels **USAGE** ``` hab bldr channel list [OPTIONS] [ORIGIN] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <ORIGIN> The origin for which channels will be listed. Default is from 'HAB_ORIGIN' or cli.toml ``` --- ### hab bldr channel promote Atomically promotes all packages in channel **USAGE** ``` hab bldr channel promote [OPTIONS] <SOURCE_CHANNEL> <TARGET_CHANNEL> --origin <ORIGIN``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -o, --origin <ORIGIN> The origin for the channels. Default is from 'HAB_ORIGIN' or cli.toml ``` **ARGS** ``` <SOURCE_CHANNEL> The channel from which all packages will be selected for promotion <TARGET_CHANNEL> The channel to which packages will be promoted ``` --- ### hab bldr job Commands relating to Habitat Builder jobs **USAGE** ``` hab bldr job <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab bldr job cancel](#hab-bldr-job-cancel) | Cancel a build job group and any in-progress builds | | [hab bldr job demote](#hab-bldr-job-demote) | Demote packages from a completed build job from a specified channel | | [hab bldr job promote](#hab-bldr-job-promote) | Promote packages from a completed build job to a specified channel | | [hab bldr job start](#hab-bldr-job-start) | Schedule a build job or group of jobs | | [hab bldr job status](#hab-bldr-job-status) | Get the status of one or more job groups | --- ### hab bldr job cancel Cancel a build job group and any in-progress builds **USAGE** ``` hab bldr job cancel [FLAGS] [OPTIONS] <GROUP_ID``` **FLAGS** ``` -f, --force Don't prompt for confirmation -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <GROUP_ID> The job group id that was returned from "hab bldr job start" (ex: 771100000000000000) ``` --- ### hab bldr job demote Demote packages from a completed build job from a specified channel **USAGE** ``` hab bldr job demote [FLAGS] [OPTIONS] <GROUP_ID> <CHANNEL``` **FLAGS** ``` -i, --interactive Allow editing the list of demotable packages -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -o, --origin <ORIGIN> Limit the demotable packages to the specified origin ``` **ARGS** ``` <GROUP_ID> The job group id that was returned from "hab bldr job start" (ex: 771100000000000000) <CHANNEL> The name of the channel to demote from ``` --- ### hab bldr job promote Promote packages from a completed build job to a specified channel **USAGE** ``` hab bldr job promote [FLAGS] [OPTIONS] <GROUP_ID> <CHANNEL``` **FLAGS** ``` -i, --interactive Allow editing the list of promotable packages -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -o, --origin <ORIGIN> Limit the promotable packages to the specified origin ``` **ARGS** ``` <GROUP_ID> The job group id that was returned from "hab bldr job start" (ex: 771100000000000000) <CHANNEL> The target channel name ``` --- ### hab bldr job start Schedule a build job or group of jobs **USAGE** ``` hab bldr job start [FLAGS] [OPTIONS] <PKG_IDENT> [PKG_TARGET] ``` **FLAGS** ``` -g, --group Schedule jobs for this package and all of its reverse dependencies -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) <PKG_TARGET> A package target (ex: x86_64-windows) (default: system appropriate target) [env: HAB_PACKAGE_TARGET=] ``` --- ### hab bldr job status Get the status of one or more job groups **USAGE** ``` hab bldr job status [FLAGS] [OPTIONS] <GROUP_ID|--origin <ORIGIN>``` **FLAGS** ``` -s, --showjobs Show the status of all build jobs for a retrieved job group -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -l, --limit <LIMIT> Limit how many job groups to retrieve, ordered by most recent (default: 10) -o, --origin <ORIGIN> Show the status of recent job groups created in this origin (default: 10 most recent) ``` **ARGS** ``` <GROUP_ID> The job group id that was returned from "hab bldr job start" (ex: 771100000000000000) ``` --- hab cli ------- Commands relating to Habitat runtime config **USAGE** ``` hab cli <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab cli completers](#hab-cli-completers) | Creates command-line completers for your shell | | [hab cli setup](#hab-cli-setup) | Sets up the CLI with reasonable defaults | --- ### hab cli completers Creates command-line completers for your shell **USAGE** ``` hab cli completers --shell <SHELL``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -s, --shell <SHELL> The name of the shell you want to generate the command-completion [possible values: Bash, Fish, Zsh, PowerShell] ``` --- ### hab cli setup Sets up the CLI with reasonable defaults **USAGE** ``` hab cli setup [OPTIONS] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] ``` --- hab config ---------- Commands relating to a Service’s runtime config **USAGE** ``` hab config <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab config apply](#hab-config-apply) | Sets a configuration to be shared by members of a Service Group | | [hab config show](#hab-config-show) | Displays the default configuration options for a service | --- ### hab config apply Sets a configuration to be shared by members of a Service Group **USAGE** ``` hab config apply [OPTIONS] <SERVICE_GROUP> <VERSION_NUMBER> [FILE] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] -u, --user <USER> Name of a user key to use for encryption ``` **ARGS** ``` <SERVICE_GROUP> Target service group service.group[@organization] (ex: redis.default or foo.default@bazcorp) <VERSION_NUMBER> A version number (positive integer) for this configuration (ex: 42) <FILE> Path to local file on disk (ex: /tmp/config.toml, default: <stdin>) ``` --- ### hab config show Displays the default configuration options for a service **USAGE** ``` hab config show [OPTIONS] <PKG_IDENT``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- hab file -------- Commands relating to Habitat files **USAGE** ``` hab file <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab file upload](#hab-file-upload) | Uploads a file to be shared between members of a Service Group | --- ### hab file upload Uploads a file to be shared between members of a Service Group **USAGE** ``` hab file upload [OPTIONS] <SERVICE_GROUP> <VERSION_NUMBER> <FILE``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] -u, --user <USER> Name of the user key ``` **ARGS** ``` <SERVICE_GROUP> Target service group service.group[@organization] (ex: redis.default or foo.default@bazcorp) <VERSION_NUMBER> A version number (positive integer) for this configuration (ex: 42) <FILE> Path to local file on disk ``` --- hab license ----------- Commands relating to Habitat license agreements **USAGE** ``` hab license <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab license accept](#hab-license-accept) | Accept the Chef Binary Distribution Agreement without prompting | --- ### hab license accept Accept the Chef Binary Distribution Agreement without prompting **USAGE** ``` hab license accept ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` --- hab origin ---------- Commands relating to Habitat Builder origins **USAGE** ``` hab origin <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab origin create](#hab-origin-create) | Creates a new Builder origin | | [hab origin delete](#hab-origin-delete) | Removes an unused/empty origin | | [hab origin depart](#hab-origin-depart) | Departs membership from selected origin | | [hab origin info](#hab-origin-info) | Displays general information about an origin | | [hab origin invitations](#hab-origin-invitations) | Manage origin member invitations | | [hab origin key](#hab-origin-key) | Commands relating to Habitat origin key maintenance | | [hab origin rbac](#hab-origin-rbac) | Role Based Access Control for origin members | | [hab origin secret](#hab-origin-secret) | Commands related to secret management | | [hab origin transfer](#hab-origin-transfer) | Transfers ownership of an origin to another member of that origin | --- ### hab origin create Creates a new Builder origin **USAGE** ``` hab origin create [OPTIONS] <ORIGIN``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <ORIGIN> The origin to be created ``` --- ### hab origin delete Removes an unused/empty origin **USAGE** ``` hab origin delete [OPTIONS] <ORIGIN``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <ORIGIN> The origin name ``` --- ### hab origin depart Departs membership from selected origin **USAGE** ``` hab origin depart [OPTIONS] <ORIGIN``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <ORIGIN> The origin name ``` --- ### hab origin info Displays general information about an origin **USAGE** ``` hab origin info [FLAGS] [OPTIONS] <ORIGIN``` **FLAGS** ``` -j, --json Output will be rendered in json -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <ORIGIN> The origin name to be queried ``` --- ### hab origin invitations Manage origin member invitations **USAGE** ``` hab origin invitations <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab origin invitations accept](#hab-origin-invitations-accept) | Accept an origin member invitation | | [hab origin invitations ignore](#hab-origin-invitations-ignore) | Ignore an origin member invitation | | [hab origin invitations list](#hab-origin-invitations-list) | List origin invitations sent to your account | | [hab origin invitations pending](#hab-origin-invitations-pending) | List pending invitations for a particular origin. Requires that you are the origin owner | | [hab origin invitations rescind](#hab-origin-invitations-rescind) | Rescind an existing origin member invitation | | [hab origin invitations send](#hab-origin-invitations-send) | Send an origin member invitation | --- ### hab origin invitations accept Accept an origin member invitation **USAGE** ``` hab origin invitations accept [OPTIONS] <ORIGIN> <INVITATION_ID``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <ORIGIN> The origin name the invitation applies to <INVITATION_ID> The id of the invitation to accept ``` --- ### hab origin invitations ignore Ignore an origin member invitation **USAGE** ``` hab origin invitations ignore [OPTIONS] <ORIGIN> <INVITATION_ID``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <ORIGIN> The origin name the invitation applies to <INVITATION_ID> The id of the invitation to ignore ``` --- ### hab origin invitations list List origin invitations sent to your account **USAGE** ``` hab origin invitations list [OPTIONS] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` --- ### hab origin invitations pending List pending invitations for a particular origin. Requires that you are the origin owner **USAGE** ``` hab origin invitations pending [OPTIONS] <ORIGIN``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <ORIGIN> The name of the origin you wish to list invitations for ``` --- ### hab origin invitations rescind Rescind an existing origin member invitation **USAGE** ``` hab origin invitations rescind [OPTIONS] <ORIGIN> <INVITATION_ID``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <ORIGIN> The origin name the invitation applies to <INVITATION_ID> The id of the invitation to rescind ``` --- ### hab origin invitations send Send an origin member invitation **USAGE** ``` hab origin invitations send [OPTIONS] <ORIGIN> <INVITEE_ACCOUNT``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <ORIGIN> The origin name the invitation applies to <INVITEE_ACCOUNT> The account name to invite into the origin ``` --- ### hab origin key Commands relating to Habitat origin key maintenance **USAGE** ``` hab origin key <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab origin key download](#hab-origin-key-download) | Download origin key(s) | | [hab origin key export](#hab-origin-key-export) | Outputs the latest origin key contents to stdout | | [hab origin key generate](#hab-origin-key-generate) | Generates a Habitat origin key pair | | [hab origin key import](#hab-origin-key-import) | Reads a stdin stream containing a public or private origin key contents and writes the key to disk | | [hab origin key upload](#hab-origin-key-upload) | Upload origin keys to Builder | --- ### hab origin key download Download origin key(s) **USAGE** ``` hab origin key download [FLAGS] [OPTIONS] <ORIGIN> [REVISION] ``` **FLAGS** ``` -e, --encryption Download public encryption key instead of origin public key -s, --secret Download origin private key instead of origin public key -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder (required for downloading origin private keys) -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] ``` **ARGS** ``` <ORIGIN> The origin name <REVISION> The origin key revision ``` --- ### hab origin key export Outputs the latest origin key contents to stdout **USAGE** ``` hab origin key export [OPTIONS] <ORIGIN``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] -t, --type <KEY_TYPE> Export either the 'public' or 'secret' key. The 'secret' key is the origin private key ``` **ARGS** ``` <ORIGIN> The origin name ``` --- ### hab origin key generate Generates a Habitat origin key pair **USAGE** ``` hab origin key generate [OPTIONS] [ORIGIN] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] ``` **ARGS** ``` <ORIGIN> The origin name ``` --- ### hab origin key import Reads a stdin stream containing a public or private origin key contents and writes the key to disk **USAGE** ``` hab origin key import [OPTIONS] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] ``` --- ### hab origin key upload Upload origin keys to Builder **USAGE** ``` hab origin key upload [FLAGS] [OPTIONS] <ORIGIN|--pubfile <PUBLIC_FILE>``` **FLAGS** ``` -s, --secret Upload origin private key in addition to the public key -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] --pubfile <PUBLIC_FILE> Path to a local public origin key file on disk --secfile <SECRET_FILE> Path to a local origin private key file on disk ``` **ARGS** ``` <ORIGIN> The origin name ``` --- ### hab origin rbac Role Based Access Control for origin members **USAGE** ``` hab origin rbac <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab origin rbac set](#hab-origin-rbac-set) | Change an origin member’s role | | [hab origin rbac show](#hab-origin-rbac-show) | Display an origin member’s current role | --- ### hab origin rbac set Change an origin member’s role **USAGE** ``` hab origin rbac set [FLAGS] [OPTIONS] <MEMBER_ACCOUNT> <ROLE> --origin <ORIGIN``` **FLAGS** ``` -n, --no-prompt Do not prompt for confirmation -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -o, --origin <ORIGIN> The Builder origin name to target ``` **ARGS** ``` <MEMBER_ACCOUNT> The account name whose role will be changed <ROLE> The role name to enforce for the member account [possible values: readonly_member, member, maintainer, administrator, owner] ``` --- ### hab origin rbac show Display an origin member’s current role **USAGE** ``` hab origin rbac show [FLAGS] [OPTIONS] <MEMBER_ACCOUNT> --origin <ORIGIN``` **FLAGS** ``` -j, --json Output will be rendered in json -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -o, --origin <ORIGIN> The Builder origin name to target ``` **ARGS** ``` <MEMBER_ACCOUNT> The account name of the role to display ``` --- ### hab origin secret Commands related to secret management **USAGE** ``` hab origin secret <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab origin secret delete](#hab-origin-secret-delete) | Delete a secret for your origin | | [hab origin secret list](#hab-origin-secret-list) | List all secrets for your origin | | [hab origin secret upload](#hab-origin-secret-upload) | Create and upload a secret for your origin | --- ### hab origin secret delete Delete a secret for your origin **USAGE** ``` hab origin secret delete [OPTIONS] <KEY_NAME``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -o, --origin <ORIGIN> The origin for which the secret will be deleted. Default is from 'HAB_ORIGIN' or cli.toml ``` **ARGS** ``` <KEY_NAME> The name of the variable key to be injected into the studio ``` --- ### hab origin secret list List all secrets for your origin **USAGE** ``` hab origin secret list [OPTIONS] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -o, --origin <ORIGIN> The origin for which secrets will be listed. Default is from 'HAB_ORIGIN' or cli.toml ``` --- ### hab origin secret upload Create and upload a secret for your origin **USAGE** ``` hab origin secret upload [OPTIONS] <KEY_NAME> <SECRET``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] -o, --origin <ORIGIN> The origin for which the secret will be uploaded. Default is from HAB_ORIGIN' or cli.toml ``` **ARGS** ``` <KEY_NAME> The name of the variable key to be injected into the studio. Ex: KEY="some_value" <SECRET> The contents of the variable to be injected into the studio ``` --- ### hab origin transfer Transfers ownership of an origin to another member of that origin **USAGE** ``` hab origin transfer [OPTIONS] <ORIGIN> <NEW_OWNER_ACCOUNT``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <ORIGIN> The origin name <NEW_OWNER_ACCOUNT> The account name of the new origin owner ``` --- hab pkg ------- Commands relating to Habitat packages **USAGE** ``` hab pkg <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab pkg binds](#hab-pkg-binds) | Displays the binds for a service | | [hab pkg binlink](#hab-pkg-binlink) | Creates a binlink for a package binary in a common ‘PATH’ location | | [hab pkg build](#hab-pkg-build) | Builds a Plan using a Studio | | [hab pkg bulkupload](#hab-pkg-bulkupload) | Bulk Uploads Habitat Artifacts to a Depot from a local directory | | [hab pkg channels](#hab-pkg-channels) | Find out what channels a package belongs to | | [hab pkg config](#hab-pkg-config) | Displays the default configuration options for a service | | [hab pkg delete](#hab-pkg-delete) | Removes a package from Builder | | [hab pkg demote](#hab-pkg-demote) | Demote a package from a specified channel | | [hab pkg dependencies](#hab-pkg-dependencies) | Returns the Habitat Artifact dependencies. By default it will return the direct dependencies of the package | | [hab pkg download](#hab-pkg-download) | Download Habitat artifacts (including dependencies and keys) from Builder | | [hab pkg env](#hab-pkg-env) | Prints the runtime environment of a specific installed package | | [hab pkg exec](#hab-pkg-exec) | Executes a command using the ‘PATH’ context of an installed package | | [hab pkg export](#hab-pkg-export) | Exports the package to the specified format | | [hab pkg hash](#hab-pkg-hash) | Generates a blake2b hashsum from a target at any given filepath | | [hab pkg info](#hab-pkg-info) | Returns the Habitat Artifact information | | [hab pkg install](#hab-pkg-install) | Installs a Habitat package from Builder or locally from a Habitat Artifact | | [hab pkg list](#hab-pkg-list) | List all versions of installed packages | | [hab pkg path](#hab-pkg-path) | Prints the path to a specific installed release of a package | | [hab pkg promote](#hab-pkg-promote) | Promote a package to a specified channel | | [hab pkg provides](#hab-pkg-provides) | Search installed Habitat packages for a given file | | [hab pkg search](#hab-pkg-search) | Search for a package in Builder | | [hab pkg sign](#hab-pkg-sign) | Signs an archive with an origin key, generating a Habitat Artifact | | [hab pkg uninstall](#hab-pkg-uninstall) | Safely uninstall a package and dependencies from the local filesystem | | [hab pkg upload](#hab-pkg-upload) | Uploads a local Habitat Artifact to Builder | | [hab pkg verify](#hab-pkg-verify) | Verifies a Habitat Artifact with an origin key | --- ### hab pkg binds Displays the binds for a service **USAGE** ``` hab pkg binds <PKG_IDENT``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab pkg binlink Creates a binlink for a package binary in a common ‘PATH’ location **USAGE** ``` hab pkg binlink [FLAGS] [OPTIONS] <PKG_IDENT> [BINARY] ``` **FLAGS** ``` -f, --force Overwrite existing binlinks -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -d, --dest <DEST_DIR> Sets the destination directory [env: HAB_BINLINK_DIR=] [default: /bin] ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) <BINARY> The command to binlink (ex: bash) ``` --- ### hab pkg build Builds a Plan using a Studio **USAGE** ``` hab pkg build [FLAGS] [OPTIONS] <PLAN_CONTEXT``` **FLAGS** ``` -D, --docker Uses a Dockerized Studio for the build -R, --reuse Reuses a previous Studio for the build (default: clean up before building) -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] -k, --keys <HAB_ORIGIN_KEYS> Installs secret origin keys (ex: "unicorn", "acme,other,acme-ops") -r, --root <HAB_STUDIO_ROOT> Sets the Studio root (default: /hab/studios/<DIR_NAME>) -s, --src <SRC_PATH> Sets the source path (default: $PWD) ``` **ARGS** ``` <PLAN_CONTEXT> A directory containing a plan file or a habitat/ directory which contains the plan file ``` --- ### hab pkg bulkupload Bulk Uploads Habitat Artifacts to a Depot from a local directory **USAGE** ``` hab pkg bulkupload [FLAGS] [OPTIONS] <UPLOAD_DIRECTORY``` **FLAGS** ``` --auto-build Enable auto-build for all packages in this upload. Only applicable to SaaS Builder --auto-create-origins Skip the confirmation prompt and automatically create origins that do not exist in the target Builder --force Skip checking availability of package and force uploads, potentially overwriting a stored copy of a package -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -c, --channel <CHANNEL> Optional additional release channel to upload package to. Packages are always uploaded to unstable, regardless of the value of this option ``` **ARGS** ``` <UPLOAD_DIRECTORY> Directory Path from which artifacts will be uploaded ``` --- ### hab pkg channels Find out what channels a package belongs to **USAGE** ``` hab pkg channels [OPTIONS] <PKG_IDENT> [PKG_TARGET] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <PKG_IDENT> A fully qualified package identifier (ex: core/busybox-static/1.42.2/20170513215502) <PKG_TARGET> A package target (ex: x86_64-windows) (default: system appropriate target) [env: HAB_PACKAGE_TARGET=] ``` --- ### hab pkg config Displays the default configuration options for a service **USAGE** ``` hab pkg config <PKG_IDENT``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab pkg delete Removes a package from Builder **USAGE** ``` hab pkg delete [OPTIONS] <PKG_IDENT> [PKG_TARGET] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <PKG_IDENT> A fully qualified package identifier (ex: core/busybox-static/1.42.2/20170513215502) <PKG_TARGET> A package target (ex: x86_64-windows) (default: system appropriate target) [env: HAB_PACKAGE_TARGET=] ``` --- ### hab pkg demote Demote a package from a specified channel **USAGE** ``` hab pkg demote [OPTIONS] <PKG_IDENT> <CHANNEL> [PKG_TARGET] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <PKG_IDENT> A fully qualified package identifier (ex: core/busybox-static/1.42.2/20170513215502) <CHANNEL> Demote from the specified release channel <PKG_TARGET> A package target (ex: x86_64-windows) (default: system appropriate target) [env: HAB_PACKAGE_TARGET=] ``` --- ### hab pkg dependencies Returns the Habitat Artifact dependencies. By default it will return the direct dependencies of the package **USAGE** ``` hab pkg dependencies [FLAGS] <PKG_IDENT``` **FLAGS** ``` -r, --reverse Show packages which are dependant on this one -t, --transitive Show transitive dependencies -h, --help Prints help information -V, --version Prints version information ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab pkg download Download Habitat artifacts (including dependencies and keys) from Builder **USAGE** ``` hab pkg download [FLAGS] [OPTIONS] [--] [PKG_IDENT]... ``` **FLAGS** ``` --ignore-missing-seeds Ignore packages specified that are not present on the target Builder --verify Verify package integrity after download (Warning: this can be slow) -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -c, --channel <CHANNEL> Download from the specified release channel. Overridden if channel is specified in toml file [env: HAB_BLDR_CHANNEL=] [default: stable] --download-directory <DOWNLOAD_DIRECTORY> The path to store downloaded artifacts --file <PKG_IDENT_FILE>... File with newline separated package identifiers, or TOML file (ending with .toml extension) -t, --target <PKG_TARGET> Target architecture to fetch. E.g. x86_64-linux. Overridden if architecture is specified in toml file ``` **ARGS** ``` <PKG_IDENT>... One or more Habitat package identifiers (ex: acme/redis) ``` --- ### hab pkg env Prints the runtime environment of a specific installed package **USAGE** ``` hab pkg env <PKG_IDENT``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab pkg exec Executes a command using the ‘PATH’ context of an installed package **USAGE** ``` hab pkg exec <PKG_IDENT> <CMD> [ARGS]... ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) <CMD> The command to execute (ex: ls) <ARGS>... Arguments to the command ``` --- ### hab pkg export Exports the package to the specified format **USAGE** ``` hab pkg export <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab pkg export cf](#hab-pkg-export-cf) | Cloud Foundry exporter | | [hab pkg export container](#hab-pkg-export-container) | Container exporter | | [hab pkg export mesos](#hab-pkg-export-mesos) | Mesos exporter | | [hab pkg export tar](#hab-pkg-export-tar) | Tar exporter | --- ### hab pkg hash Generates a blake2b hashsum from a target at any given filepath **USAGE** ``` hab pkg hash [SOURCE] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **ARGS** ``` <SOURCE> A filepath of the target ``` --- ### hab pkg info Returns the Habitat Artifact information **USAGE** ``` hab pkg info [FLAGS] <SOURCE``` **FLAGS** ``` -j, --json Output will be rendered in json. (Includes extended metadata) -h, --help Prints help information -V, --version Prints version information ``` **ARGS** ``` <SOURCE> A path to a Habitat Artifact (ex: /home/acme-redis-3.0.7-21120102031201-x86_64-linux.hart) ``` --- ### hab pkg install Installs a Habitat package from Builder or locally from a Habitat Artifact **USAGE** ``` hab pkg install [FLAGS] [OPTIONS] <PKG_IDENT_OR_ARTIFACT>... ``` **FLAGS** ``` -b, --binlink Binlink all binaries from installed package(s) into BINLINK_DIR -f, --force Overwrite existing binlinks --ignore-install-hook Do not run any install hooks -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder --binlink-dir <BINLINK_DIR> Binlink all binaries from installed package(s) into BINLINK_DIR [env: HAB_BINLINK_DIR=] [default: /bin] -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -c, --channel <CHANNEL> Install from the specified release channel [env: HAB_BLDR_CHANNEL=] [default: stable] ``` **ARGS** ``` <PKG_IDENT_OR_ARTIFACT>... One or more Habitat package identifiers (ex: acme/redis) and/or filepaths to a Habitat Artifact (ex: /home/acme-redis-3.0.7-21120102031201-x86_64-linux.hart) ``` --- ### hab pkg list List all versions of installed packages **USAGE** ``` hab pkg list [OPTIONS] <--all|--origin <ORIGIN>|PKG_IDENT``` **FLAGS** ``` -a, --all List all installed packages -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -o, --origin <ORIGIN> An origin to list ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab pkg path Prints the path to a specific installed release of a package **USAGE** ``` hab pkg path <PKG_IDENT``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab pkg promote Promote a package to a specified channel **USAGE** ``` hab pkg promote [OPTIONS] <PKG_IDENT> <CHANNEL> [PKG_TARGET] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) ``` **ARGS** ``` <PKG_IDENT> A fully qualified package identifier (ex: core/busybox-static/1.42.2/20170513215502) <CHANNEL> Promote to the specified release channel <PKG_TARGET> A package target (ex: x86_64-windows) (default: system appropriate target) [env: HAB_PACKAGE_TARGET=] ``` --- ### hab pkg provides Search installed Habitat packages for a given file **USAGE** ``` hab pkg provides [FLAGS] <FILE``` **FLAGS** ``` -p Show full path to file -r Show fully qualified package names (ex: core/busybox-static/1.24.2/20160708162350) -h, --help Prints help information -V, --version Prints version information ``` **ARGS** ``` <FILE> File name to find ``` --- ### hab pkg search Search for a package in Builder **USAGE** ``` hab pkg search [OPTIONS] <SEARCH_TERM``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) -l, --limit <LIMIT> Limit how many packages to retrieve [default: 50] ``` **ARGS** ``` <SEARCH_TERM> Search term ``` --- ### hab pkg sign Signs an archive with an origin key, generating a Habitat Artifact **USAGE** ``` hab pkg sign [OPTIONS] <SOURCE> <DEST``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] --origin <ORIGIN> Origin key used to create signature ``` **ARGS** ``` <SOURCE> A path to a source archive file (ex: /home/acme-redis-3.0.7-21120102031201.tar.xz) <DEST> The destination path to the signed Habitat Artifact (ex: /home/acme-redis-3.0.7-21120102031201- x86_64-linux.hart) ``` --- ### hab pkg uninstall Safely uninstall a package and dependencies from the local filesystem **USAGE** ``` hab pkg uninstall [FLAGS] [OPTIONS] <PKG_IDENT``` **FLAGS** ``` -d, --dryrun Just show what would be uninstalled, don't actually do it --ignore-uninstall-hook Do not run any uninstall hooks --no-deps Don't uninstall dependencies -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --exclude <EXCLUDE>... Identifier of one or more packages that should not be uninstalled. (ex: core/redis, core/busybox-static/1.42.2/21120102031201) --keep-latest <KEEP_LATEST> Only keep this number of latest packages uninstalling all others ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab pkg upload Uploads a local Habitat Artifact to Builder **USAGE** ``` hab pkg upload [FLAGS] [OPTIONS] <HART_FILE>... ``` **FLAGS** ``` --force Skips checking availability of package and force uploads, potentially overwriting a stored copy of a package. (default: false) --no-build Disable auto-build for all packages in this upload -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -z, --auth <AUTH_TOKEN> Authentication token for Builder -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] -c, --channel <CHANNEL> Optional additional release channel to upload package to. Packages are always uploaded to unstable, regardless of the value of this option ``` **ARGS** ``` <HART_FILE>... One or more filepaths to a Habitat Artifact (ex: /home/acme-redis-3.0.7-21120102031201-x86_64- linux.hart) ``` --- ### hab pkg verify Verifies a Habitat Artifact with an origin key **USAGE** ``` hab pkg verify [OPTIONS] <SOURCE``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] ``` **ARGS** ``` <SOURCE> A path to a Habitat Artifact (ex: /home/acme-redis-3.0.7-21120102031201-x86_64-linux.hart) ``` --- hab plan -------- Commands relating to plans and other app-specific configuration **USAGE** ``` hab plan <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab plan init](#hab-plan-init) | Generates common package specific configuration files. Executing without argument will create a habitat directory in your current folder for the plan. If PKG_NAME is specified it will create a folder with that name. Environment variables (those starting with ‘pkg_') that are set will be used in the generated plan | | [hab plan render](#hab-plan-render) | Renders plan config files | --- ### hab plan init Generates common package specific configuration files. Executing without argument will create a habitat directory in **USAGE** ``` hab plan init [FLAGS] [OPTIONS] [PKG_NAME] ``` **FLAGS** ``` -m, --min Create a minimal plan file -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -o, --origin <ORIGIN> Origin for the new app -s, --scaffolding <SCAFFOLDING> Specify explicit Scaffolding for your app (ex: node, ruby) ``` **ARGS** ``` <PKG_NAME> Name for the new app ``` --- ### hab plan render Renders plan config files **USAGE** ``` hab plan render [FLAGS] [OPTIONS] <TEMPLATE_PATH``` **FLAGS** ``` -n, --no-render Don't write anything to disk, ignores --render-dir -p, --print Prints config to STDOUT -q, --quiet Don't print any helper messages. When used with --print will only print config file -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -d, --default-toml <DEFAULT_TOML> Path to default.toml [default: ./default.toml] -m, --mock-data <MOCK_DATA> Path to json file with mock data for template, defaults to none -r, --render-dir <RENDER_DIR> Path to render templates [default: ./results] -u, --user-toml <USER_TOML> Path to user.toml, defaults to none ``` **ARGS** ``` <TEMPLATE_PATH> Path to config to render ``` --- hab ring -------- Commands relating to Habitat rings **USAGE** ``` hab ring <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab ring key](#hab-ring-key) | Commands relating to Habitat ring keys | --- ### hab ring key Commands relating to Habitat ring keys **USAGE** ``` hab ring key <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab ring key export](#hab-ring-key-export) | Outputs the latest ring key contents to stdout | | [hab ring key generate](#hab-ring-key-generate) | Generates a Habitat ring key | | [hab ring key import](#hab-ring-key-import) | Reads a stdin stream containing ring key contents and writes the key to disk | --- ### hab ring key export Outputs the latest ring key contents to stdout **USAGE** ``` hab ring key export [OPTIONS] <RING``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] ``` **ARGS** ``` <RING> Ring key name ``` --- ### hab ring key generate Generates a Habitat ring key **USAGE** ``` hab ring key generate [OPTIONS] <RING``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] ``` **ARGS** ``` <RING> Ring key name ``` --- ### hab ring key import Reads a stdin stream containing ring key contents and writes the key to disk **USAGE** ``` hab ring key import [OPTIONS] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] ``` --- hab studio ---------- **USAGE** ``` hab studio [FLAGS] [OPTIONS] <SUBCOMMAND> [ARG ..] ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab studio build](#hab-studio-build) | Build using a Studio | | [hab studio enter](#hab-studio-enter) | Interactively enter a Studio | | [hab studio new](#hab-studio-new) | Creates a new Studio | | [hab studio rm](#hab-studio-rm) | Destroys a Studio | | [hab studio run](#hab-studio-run) | Run a command in a Studio | | [hab studio version](#hab-studio-version) | Prints version information | --- ### hab studio build **USAGE** ``` hab studio [COMMON_FLAGS] [COMMON_OPTIONS] build [FLAGS] [PLAN_DIR] ``` **FLAGS** ``` -R Reuse a previous Studio state (default: clean up before building) ``` --- ### hab studio enter **USAGE** ``` hab studio [COMMON_FLAGS] [COMMON_OPTIONS] enter ``` --- ### hab studio new **USAGE** ``` hab studio [COMMON_FLAGS] [COMMON_OPTIONS] new ``` --- ### hab studio rm **USAGE** ``` hab studio [COMMON_FLAGS] [COMMON_OPTIONS] rm ``` --- ### hab studio run **USAGE** ``` hab studio [COMMON_FLAGS] [COMMON_OPTIONS] run [CMD] [ARG ..] ``` --- ### hab studio version --- hab sup ------- **USAGE** ``` hab sup <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab sup bash](#hab-sup-bash) | Start an interactive Bash-like shell | | [hab sup depart](#hab-sup-depart) | Depart a Supervisor from the gossip ring; kicking and banning the target from joining again with the same member-id | | [hab sup restart](#hab-sup-restart) | Restart a Supervisor without restarting its services | | [hab sup run](#hab-sup-run) | Run the Habitat Supervisor | | [hab sup secret](#hab-sup-secret) | Commands relating to a Habitat Supervisor’s Control Gateway secret | | [hab sup sh](#hab-sup-sh) | Start an interactive Bourne-like shell | | [hab sup status](#hab-sup-status) | Query the status of Habitat services | | [hab sup term](#hab-sup-term) | Gracefully terminate the Habitat Supervisor and all of its running services | --- ### hab sup bash Start an interactive Bash-like shell **USAGE** ``` hab sup bash ``` **FLAGS** ``` -h, --help Prints help information ``` --- ### hab sup depart Depart a Supervisor from the gossip ring; kicking and banning the target from joining again with the same member-id **USAGE** ``` hab sup depart [OPTIONS] <MEMBER_ID``` **FLAGS** ``` -h, --help Prints help information ``` **OPTIONS** ``` -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] ``` **ARGS** ``` <MEMBER_ID> The member-id of the Supervisor to depart ``` --- ### hab sup restart Restart a Supervisor without restarting its services **USAGE** ``` hab sup restart [OPTIONS] ``` **FLAGS** ``` -h, --help Prints help information ``` **OPTIONS** ``` -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] ``` --- ### hab sup run Run the Habitat Supervisor **USAGE** ``` hab sup run [FLAGS] [OPTIONS] [--] [PKG_IDENT_OR_ARTIFACT] ``` **FLAGS** ``` -A, --auto-update Enable automatic updates for the Supervisor itself --generate-config Generate a TOML config -D, --http-disable Disable the HTTP Gateway completely --json-logging Use structured JSON logging for the Supervisor --local-gossip-mode Start the supervisor in local mode --no-color Turn ANSI color off -I, --permanent-peer Make this Supervisor a permanent peer -v Verbose output showing file and line/column numbers -h, --help Prints help information ``` **OPTIONS** ``` --auto-update-period <AUTO_UPDATE_PERIOD> The period of time in seconds between Supervisor update checks [default: 60] --bind <BIND>... One or more service groups to bind to a configuration --binding-mode <BINDING_MODE> Governs how the presence or absence of binds affects service startup [default: strict] [possible values: strict, relaxed] -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] --ca-certs <CA_CERT_FILE> The CA certificate for HTTP Gateway TLS encryption --certs <CERT_FILE> The server certificates for HTTP Gateway TLS encryption --channel <CHANNEL> Receive updates from the specified release channel [default: stable] --config-files <CONFIG_FILES>... Paths to config files to read --config-from <CONFIG_FROM> Use the package config from this path rather than the package itself --ctl-client-ca-certificate <CTL_CLIENT_CA_CERTIFICATE> Enable client authentication for the control gateway and set the certificate authority to use when authenticating the client [default: /hab/cache/keys/ctl] --ctl-server-certificate <CTL_SERVER_CERTIFICATE> The control gateway server's TLS certificate [default: /hab/cache/keys/ctl] --ctl-server-key <CTL_SERVER_KEY> Enable TLS for the control gateway and set the server's private key [default: /hab/cache/keys/ctl] --event-meta <EVENT_META>... An arbitrary key-value pair to add to each event generated by this Supervisor --event-stream-application <EVENT_STREAM_APPLICATION> The name of the application for event stream purposes --event-stream-connect-timeout <EVENT_STREAM_CONNECT_TIMEOUT> Event stream connection timeout before exiting the Supervisor [env: HAB_EVENT_STREAM_CONNECT_TIMEOUT=] default: 0] --event-stream-environment <EVENT_STREAM_ENVIRONMENT> The name of the environment for event stream purposes --event-stream-server-certificate <EVENT_STREAM_SERVER_CERTIFICATE> The path to Chef Automate's event stream certificate used to establish a TLS connection --event-stream-site <EVENT_STREAM_SITE> The name of the site where this Supervisor is running for event stream purposes --event-stream-token <EVENT_STREAM_TOKEN> The authentication token for connecting the event stream to Chef Automate [env: HAB_AUTOMATE_AUTH_TOKEN=] --event-stream-url <EVENT_STREAM_URL> The event stream connection url used to send events to Chef Automate --group <GROUP> The service group with shared config and topology [default: default] -i, --health-check-interval <HEALTH_CHECK_INTERVAL> The interval in seconds on which to run health checks [default: 30] --keep-latest-packages <KEEP_LATEST_PACKAGES> Automatically cleanup old packages [env: HAB_KEEP_LATEST_PACKAGES=] --key <KEY_FILE> The private key for HTTP Gateway TLS encryption --listen-ctl <LISTEN_CTL> The listen address for the Control Gateway [env: HAB_LISTEN_CTL=] [default: 127.0.0.1:9632] --listen-gossip <LISTEN_GOSSIP> The listen address for the Gossip Gateway [env: HAB_LISTEN_GOSSIP=] [default: 0.0.0.0:9638] --listen-http <LISTEN_HTTP> The listen address for the HTTP Gateway [env: HAB_LISTEN_HTTP=] [default: 0.0.0.0:9631] --org <ORGANIZATION> The organization the Supervisor and its services are part of --peer <PEER>... The listen address of one or more initial peers (IP[:PORT]) --peer-watch-file <PEER_WATCH_FILE> Watch this file for connecting to the ring -r, --ring <RING> The name of the ring used by the Supervisor when running with wire encryption [env: HAB_RING=] --service-update-period <SERVICE_UPDATE_PERIOD> The period of time in seconds between service update checks [default: 60] --shutdown-timeout <SHUTDOWN_TIMEOUT> The delay in seconds after sending the shutdown signal to wait before killing the service process -s, --strategy <STRATEGY> The update strategy [default: none] [possible values: none, at-once, rolling] --sys-ip-address <SYS_IP_ADDRESS> The IPv4 address to use as the sys.ip template variable -t, --topology <TOPOLOGY> Service topology [possible values: standalone, leader] --update-condition <UPDATE_CONDITION> The condition dictating when this service should update [default: latest] [possible values: latest, track- channel] ``` **ARGS** ``` <PKG_IDENT_OR_ARTIFACT> Load a Habitat package as part of the Supervisor startup ``` --- ### hab sup secret Commands relating to a Habitat Supervisor’s Control Gateway secret **USAGE** ``` hab sup secret <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab sup secret generate](#hab-sup-secret-generate) | Generate a secret key to use as a Supervisor’s Control Gateway secret | | [hab sup secret generate-tls](#hab-sup-secret-generate-tls) | Generate a private key and certificate for the Supervisor’s Control Gateway TLS connection | --- ### hab sup secret generate Generate a secret key to use as a Supervisor’s Control Gateway secret **USAGE** ``` hab sup secret generate ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` --- ### hab sup secret generate-tls Generate a private key and certificate for the Supervisor’s Control Gateway TLS connection **USAGE** ``` hab sup secret generate-tls [OPTIONS] --subject-alternative-name <subject-alternative-name``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --path <path> The directory to store the generated private key and certificate [default: /hab/cache/keys/ctl] --subject-alternative-name <subject-alternative-name> The DNS name to use in the certificates subject alternative name extension ``` --- ### hab sup sh Start an interactive Bourne-like shell **USAGE** ``` hab sup sh ``` **FLAGS** ``` -h, --help Prints help information ``` --- ### hab sup status Query the status of Habitat services **USAGE** ``` hab sup status [OPTIONS] [PKG_IDENT] ``` **FLAGS** ``` -h, --help Prints help information ``` **OPTIONS** ``` -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab sup term Gracefully terminate the Habitat Supervisor and all of its running services **USAGE** ``` hab sup term ``` **FLAGS** ``` -h, --help Prints help information ``` --- hab supportbundle ----------------- Create a tarball of Habitat Supervisor data to send to support **USAGE** ``` hab supportbundle ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` --- hab svc ------- Commands relating to Habitat services **USAGE** ``` hab svc <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab svc key](#hab-svc-key) | Commands relating to Habitat service keys | | [hab svc load](#hab-svc-load) | Load a service to be started and supervised by Habitat from a package identifier. If an installed package doesn’t satisfy the given package identifier, a suitable package will be installed from Builder | | [hab svc start](#hab-svc-start) | Start a loaded, but stopped, Habitat service | | [hab svc status](#hab-svc-status) | Query the status of Habitat services | | [hab svc stop](#hab-svc-stop) | Stop a running Habitat service | | [hab svc unload](#hab-svc-unload) | Unload a service loaded by the Habitat Supervisor. If the service is running it will additionally be stopped | | [hab svc update](#hab-svc-update) | Update how the Supervisor manages an already-running service. Depending on the given changes, they may be able to be applied without restarting the service | --- ### hab svc key Commands relating to Habitat service keys **USAGE** ``` hab svc key <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab svc key generate](#hab-svc-key-generate) | Generates a Habitat service key | --- ### hab svc key generate Generates a Habitat service key **USAGE** ``` hab svc key generate [OPTIONS] <SERVICE_GROUP> [ORG] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] ``` **ARGS** ``` <SERVICE_GROUP> Target service group service.group[@organization] (ex: redis.default or foo.default@bazcorp) <ORG> The service organization ``` --- ### hab svc load Load a service to be started and supervised by Habitat from a package identifier. If an installed package doesn’t **USAGE** ``` hab svc load [FLAGS] [OPTIONS] <PKG_IDENT``` **FLAGS** ``` -f, --force Load or reload an already loaded service. If the service was previously loaded and running this operation will also restart the service -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --bind <BIND>... One or more service groups to bind to a configuration --binding-mode <BINDING_MODE> Governs how the presence or absence of binds affects service startup [default: strict] [possible values: strict, relaxed] -u, --url <BLDR_URL> Specify an alternate Builder endpoint. If not specified, the value will be taken from the HAB_BLDR_URL environment variable if defined. (default: https://bldr.habitat.sh) --channel <CHANNEL> Receive updates from the specified release channel [default: stable] --config-from <CONFIG_FROM> Use the package config from this path rather than the package itself --group <GROUP> The service group with shared config and topology [default: default] -i, --health-check-interval <HEALTH_CHECK_INTERVAL> The interval in seconds on which to run health checks [default: 30] -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] --shutdown-timeout <SHUTDOWN_TIMEOUT> The delay in seconds after sending the shutdown signal to wait before killing the service process -s, --strategy <STRATEGY> The update strategy [default: none] [possible values: none, at-once, rolling] -t, --topology <TOPOLOGY> Service topology [possible values: standalone, leader] --update-condition <UPDATE_CONDITION> The condition dictating when this service should update [default: latest] [possible values: latest, track- channel] ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab svc start Start a loaded, but stopped, Habitat service **USAGE** ``` hab svc start [OPTIONS] <PKG_IDENT``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab svc status Query the status of Habitat services **USAGE** ``` hab svc status [OPTIONS] [PKG_IDENT] ``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab svc stop Stop a running Habitat service **USAGE** ``` hab svc stop [OPTIONS] <PKG_IDENT``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] --shutdown-timeout <SHUTDOWN_TIMEOUT> The delay in seconds after sending the shutdown signal to wait before killing the service process ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab svc unload Unload a service loaded by the Habitat Supervisor. If the service is running it will additionally be stopped **USAGE** ``` hab svc unload [OPTIONS] <PKG_IDENT``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] --shutdown-timeout <SHUTDOWN_TIMEOUT> The delay in seconds after sending the shutdown signal to wait before killing the service process ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- ### hab svc update Update how the Supervisor manages an already-running service. Depending on the given changes, they may be able to be **USAGE** ``` hab svc update [OPTIONS] <PKG_IDENT``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --bind <BIND>... One or more service groups to bind to a configuration --binding-mode <BINDING_MODE> Governs how the presence or absence of binds affects service startup [possible values: strict, relaxed] -u, --url <BLDR_URL> Specify an alternate Builder endpoint --channel <CHANNEL> Receive updates from the specified release channel --group <GROUP> The service group with shared config and topology -i, --health-check-interval <HEALTH_CHECK_INTERVAL> The interval in seconds on which to run health checks -r, --remote-sup <REMOTE_SUP> Address to a remote Supervisor's Control Gateway [default: 127.0.0.1:9632] --shutdown-timeout <SHUTDOWN_TIMEOUT> The delay in seconds after sending the shutdown signal to wait before killing the service process -s, --strategy <STRATEGY> The update strategy [possible values: none, at-once, rolling] -t, --topology <TOPOLOGY> Service topology [possible values: standalone, leader] --update-condition <UPDATE_CONDITION> The condition dictating when this service should update [possible values: latest, track-channel] ``` **ARGS** ``` <PKG_IDENT> A package identifier (ex: core/redis, core/busybox-static/1.42.2) ``` --- hab user -------- Commands relating to Habitat users **USAGE** ``` hab user <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab user key](#hab-user-key) | Commands relating to Habitat user keys | --- ### hab user key Commands relating to Habitat user keys **USAGE** ``` hab user key <SUBCOMMAND``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **SUBCOMMANDS** | Command | Description | | --- | --- | | [hab user key generate](#hab-user-key-generate) | Generates a Habitat user key | --- ### hab user key generate Generates a Habitat user key **USAGE** ``` hab user key generate [OPTIONS] <USER``` **FLAGS** ``` -h, --help Prints help information -V, --version Prints version information ``` **OPTIONS** ``` --cache-key-path <CACHE_KEY_PATH> Cache for creating and searching for encryption keys [env: HAB_CACHE_KEY_PATH=] [default: /hab/cache/keys] ``` **ARGS** ``` <USER> Name of the user key ``` --- © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/habitat_cli/Supervisor Log Codes ==================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/sup_log_keys.md) When running services with the Chef Habitat Supervisor you’ll see log output similar to this: ``` redis.default(SR): Initializing redis.default(SV): Starting redis.default(O): ``` The letters in parentheses are called “log keys” and signify what type of log message is being shown. This can be useful for log filtering. They are mostly organized by the part of the Chef Habitat Supervisor code base that they are running from, so they often are of value to somebody troubleshooting problems in the Chef Habitat Supervisor source code. The meanings of the keys are as follows: | Key | Description | | --- | --- | | CE | Census | | CFG | Global configuration | | CS | Create service: When a service is being started | | ER | Errors | | FW | Generic file watcher | | HG | Messages from the HTTP gateway | | MN | Main | | MR | Manager | | O | Standard output | | PH | Package hooks | | PK | Package | | PT | Path | | PW | Peer file watcher | | SC | Service configuration | | SH | Starting a shell with `hab sup sh` | | SI | Unix signals | | SOT | Structured output | | SR | Service runtime | | SU | Service updater | | SV | Supervisor | | SY | “sys” utility | | UCW | User-config watcher | | UR | Users utility | | UT | Utilities | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/sup_log_keys/Plan Variables ============== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/plan_variables.md) The following variables can be used in your plans to help get binaries and libraries to build and install in the correct locations in your package. The values for the variables listed below are default values or read-only values. pkg_prefix The absolute path for your package. pkg_dirname The directory created when Habitat extracts an archive. If a .tar file extracts to a directory that’s different from the filename, then you would need to override this value to match the directory name created during extraction. Default value: `${pkg_name}-${pkg_version}` pkg_svc_path Where the running service is located. Read-only value: `${HAB_ROOT_PATH}/svc/${pkg_name}` pkg_svc_data_path Where the running service data is located. Read-only value: `${pkg_svc_path}/data` pkg_svc_files_path Where the gossiped configuration files are located. Read-only value: `${pkg_svc_path}/files` pkg_svc_var_path Where the running service variable data is located. Read-only value: `${pkg_svc_path}/var` pkg_svc_config_path Where the running service configuration is located. Read-only value: `${pkg_svc_path}/config` pkg_svc_static_path Where the running service static data is located. Read-only value: `${pkg_svc_path}/static` CACHE_PATH A temporary directory that will be clean on every build. Read-only value: `${HAB_CACHE_SRC_PATH}/${pkg_dirname}` HAB_CACHE_SRC_PATH The default path where source archives are downloaded, extracted, and compiled. Read-only value: `${HAB_ROOT_PATH}/cache/src` HAB_CACHE_ARTIFACT_PATH The default download root path for packages. Read-only value: `${HAB_ROOT_PATH}/cache/artifacts` HAB_PKG_PATH The root path containing all locally installed packages. Read-only value: `${HAB_ROOT_PATH}/pkgs` PLAN_CONTEXT The location on your local dev machine for the files in your plan directory. CFLAGS C compiler options. LDFLAGS C linker options. PREFIX Where to install the software; same as `pkg_prefix`. LD_RUN_PATH Where to find the binaries at run time. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/plan_variables/Chef Habitat and Containers =========================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/containers.md) **Examples: [Docker](https://www.docker.com/) and [CoreOS](https://coreos.com/)** Containers enable you to build an immutable snapshot of your runtime environment, including your operating system, system libraries, application libraries, and application. The container is built with a CLI tool, and then pushed to a container-specific artifact repository, known as a container registry. Chef Habitat is not a container format and exports your application to the container format of your choice. Chef Habitat builds more secure containers by exporting your application and any of its runtime dependencies directly into the container. When you build your application with Chef Habitat, your application takes ownership of the entire toolchain of its runtime dependencies. As a result, you no longer have to rely on a large operating system and unnecessary system libraries. This enables you to include only the binaries your application uses inside your container, which can decrease your container size. By eliminating the need for a large operating system, you also avoid including binaries that an attacker could use, which further increases the security of your container. Visit the [Running Chef Habitat Containers](../running_habitat_linux_containers/index) section of the docs to find more details about how containers are built with Chef Habitat. Finally, [Chef Habitat’s HTTP API](../monitor_services/index) allows all of your application’s runtime dependencies to be audited at any time. If a brand new vulnerability is revealed, [Chef Habitat’s HTTP API](../monitor_services/index) makes it easy to programmatically inspect and audit the entire toolchain of your runtime environment without needing to worry about how your containers got built in the first place. If your situation requires it, Chef Habitat makes it simple to switch from containerized to non-containerized workloads. This is because Chef Habitat packages only have a requirement on the kernel version of your operating system. (Linux: kernel 2.6.32 or later, Windows: Windows Server 2008 R2 or later and Windows 7 64-bit or later). You can take the same .hart file you use to export to a Docker container and run it on a virtual machine or bare metal. By only requiring the kernel, Chef Habitat gives you the ability to switch container formats or to switch to non-containerized workloads without significant rework. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/containers/Plan Settings ============= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/plan_settings.md) Habitat reserves some names for internal use. You can set all of these values in your plan and use them as variables in your Habitat code. For example: ``` # Set the packag name pkg_name=two-tier-app # Call the package by name ${pkg_name} ``` ``` # Set the packag name pkg_name=two-tier-app # Call the package by name ${"pkg_name"} ``` General Settings ---------------- FORMAT: setting Short definition. How to use. How habitat uses. If required other settings. Type: String, array, boolean,etc. Default: if any. Optional/Required pkg_name Sets the name of the package. Can contain upper and lowercase letters, numbers, dashes, and underscores. By default, Chef Habitat uses `pkg_name`, `pkg_origin`, and `pkg_version` to create the fully-qualified package name. Type: string. *Required*. * [Bash](#bash-panel) * [Powershell](#powershell-panel) ``` pkg_name=zlib ``` ``` $pkg_name="zlib" ``` pkg_origin The name of the origin for this package. Can contain upper and lowercase letters, numbers, dashes, and underscores. The `HAB_ORIGIN` environment variable overrides the `pkg_origin` Type: string. *Required*. * [Bash](#bash-panel1) * [Powershell](#powershell-panel1) ``` pkg_origin=Habitat ``` ``` $pkg_origin="Habitat" ``` pkg_version Sets the version of the package By default, Chef Habitat uses `pkg_name`, `pkg_origin`, and `pkg_version` to create the fully-qualified package name. You can set the value through the `pkg_version()` function. Type: string. *Required*. * [Bash](#bash-panel2) * [Powershell](#powershell-panel2) ``` pkg_version=1.2.8 ``` ``` $pkg_version="1.2.8" ``` Note Habitat uses the guidelines of the semantic versioning specification to determine version order (see <https://semver.org/)>. Keep in mind that including a hyphen in your version indicates that the package is a pre-release that will be given lower precedence to other versions. pkg_maintainer The name and email address of the package maintainer. Type: string.*Optional*. * [Bash](#bash-panel3) * [Powershell](#powershell-panel3) ``` pkg_maintainer="<NAME> <<EMAIL>>" ``` ``` $pkg_maintainer="<NAME> <<EMAIL>>" ``` pkg_license One or more [valid software licenses](https://spdx.org/licenses/) that relate to this package. Type: array. *Optional*. * [Bash](#bash-panel4) * [Powershell](#powershell-panel4) ``` pkg_license=('Apache-2.0') ``` ``` $pkg_license=("'Apache-2.0'") ``` Note If your package has a custom license, use a string literal matching the title of the license. For example, you’ll see `pkg_license=('Boost Software License')` for the `cmake` plan. pkg_source A URL that specifies the location from which to download an external source. Any valid `wget` url will work. Typically, the relative path for the URL typically contains the `pkg_name` and `pkg_version` values. Type: URL. *Optional*. * [Bash](#bash-panel5) * [Powershell](#powershell-panel5) ``` pkg_source=http://downloads.sourceforge.net/project/libpng/$pkg_name/${pkg_version}/${pkg_name}-${pkg_version}.tar.gz ``` ``` $pkg_source="http://downloads.sourceforge.net/project/libpng/$pkg_name/${pkg_version}/${pkg_name}-${pkg_version}.tar.gz" ``` pkg_filename The filename for the finished artifact. By default, Chef Habitat ] constructs this from `pkg_name` and `pkg_version`. Type: string. *Optional*. * [Bash](#bash-panel6) * [Powershell](#powershell-panel6) ``` pkg_filename=${pkg_name}-${pkg_version}.tar.gz ``` ``` $pkg_filename="${pkg_name}-${pkg_version}.tar.gz" ``` pkg_shasum The sha-256 sum of the downloaded `pkg_source`. If you do not have the checksum, generate it by downloading the source and using the `sha256sum` or `gsha256sum` tools. Override with `do_verify()`. When the value is unset or incorrect and you do not override it with `do_verify()`, then the build output of your package will show the expected value. Type: varchar(64) or char(64). *Required* when providing a valid URL is provided for `pkg_source`, but is otherwise *Optional*. * [Bash](#bash-panel7) * [Powershell](#powershell-panel7) ``` pkg_shasum=36658cb768a54c1d4dec43c3116c27ed893e88b02ecfcb44f2166f9c0b7f2a0d ``` ``` $pkg_shasum="36658cb768a54c1d4dec43c3116c27ed893e88b02ecfcb44f2166f9c0b7f2a0d" ``` pkg_deps The dependencies that your packages needs at runtime. Refer to packages at three levels of specificity: origin/package, origin/package/version, or origin/package/version/release. Type: array. *Optional*. * [Bash](#bash-panel8) * [Powershell](#powershell-panel8) ``` pkg_deps=(core/glibc core/pcre core/openssl core/zlib) ``` ``` $pkg_deps="(core/glibc core/pcre core/openssl core/zlib)" ``` pkg_build_deps The dependencies your package requires at build time. Type: array. *Optional*. * [Bash](#bash-panel9) * [Powershell](#powershell-panel9) ``` pkg_build_deps=(core/gcc core/linux-headers) ``` ``` $pkg_build_deps="(core/gcc core/linux-headers)" ``` pkg_lib_dirs An array of paths, relative to the final install of the software, where libraries can be found. Used to populate `LD_FLAGS` and `LD_RUN_PATH` for software that depends on your package. *Optional*. ``` pkg_lib_dirs=(lib) ``` pkg_include_dirs An array of paths, relative to the final install of the software, where headers can be found. Used to populate `CFLAGS` for software that depends on your package. *Optional*. ``` pkg_include_dirs=(include) ``` pkg_bin_dirs An array of paths, relative to the final install of the software, where binaries can be found. Used to populate `PATH` for software that depends on your package. *Optional*. ``` pkg_bin_dirs=(bin) ``` pkg_pconfig_dirs An array of paths, relative to the final install of the software, where pkg-config metadata (.pc files) can be found. Used to populate `PKG_CONFIG_PATH` for software that depends on your package. *Optional*. ``` pkg_pconfig_dirs=(lib/pkgconfig) ``` pkg_svc_run The command for the Supervisor to execute when starting a service. This setting requires `pkg_bin_dirs` to place package binaries in the path. If your package hs complex start-up behaviors, use a [run hook](#hooks) instead. Omit this setting for packages that are designed for consumption by other packages instead of being run directly by a Supervisor. *Optional*. ``` pkg_svc_run="haproxy -f $pkg_svc_config_path/haproxy.conf" ``` pkg_exports Configuration data that will be passed between peers. The keys in this array are used with `pkg_exposes` and for any consuming services that set `pkg_binds` or `pkg_binds_optional`. An [associative array](https://www.linuxjournal.com/content/bash-associative-arrays) in Bash or a `hashtable` in Powershell. Type: array. *Optional*. ``` pkg_exports=( [port]=server.port [host]=server.host [ssl-port]=ssl.port ) ``` In this example, the corresponding `default.toml` file would have the following key/value pairs defined: ``` [server] port = 80 host = "www.example.com" [ssl] port = 443 ``` pkg_exposes An array of `pkg_exports` keys containing default values for the ports that this package exposes. These values are used as sensible defaults for other tools, such as when exporting a package to a container format. *Optional*. ``` pkg_exposes=(port ssl-port) ``` Note In addition to specifying the keys you defined in `pkg_exports`, you must have a default.toml file indicating the port values to expose. pkg_binds An associative array (or `hashtable` in Powershell) representing services which you depend on and the configuration keys that you expect the service to export (by their `pkg_exports`). These binds *must* be set for the Supervisor to load the service. The loaded service will wait to run until its bind becomes available. If the bind does not contain the expected keys, the service will not start successfully. *Optional*. ``` pkg_binds=( [database]="port host" ) ``` pkg_binds_optional Same as `pkg_binds` but these represent optional services to connect to. *Optional*. ``` pkg_binds_optional=( [storage]="port host" ) ``` pkg_interpreters An array of interpreters used in [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) lines for scripts. Specify the subdirectory where the binary is relative to the package, for example, `bin/bash` or `libexec/neverland`, since binaries can be located in directories besides `bin`. This list of interpreters will be written to the metadata INTERPRETERS file, located inside a package, with their fully-qualified path. Then these can be used with the fix_interpreter function. For more information on declaring shebangs in Chef Habitat, see [Plan hooks](#hooks), and for more information on the fix_interpreter function, see [Plan utility functions](#plan-helpers). *Optional*. ``` pkg_interpreters=(bin/bash) ``` pkg_svc_user The user to run the service as. Default: `hab`. On Windows, if the `hab` user does not exist then the service will run under the same account as the Supervisor. *Optional*. ``` pkg_svc_user=hab ``` pkg_svc_group Assigned service group for the package. **Not used in a `plan.ps1`.** Type: string. Default: `hab`. *Optional*. ``` pkg_svc_group=$pkg_svc_user ``` pkg_shutdown_signal The signal to send the service to shutdown. **Not used in a `plan.ps1`.** Default: `TERM`. *Optional*. ``` pkg_shutdown_signal=HUP ``` pkg_shutdown_timeout_sec The number of seconds to wait for a service to shutdown. After this interval the service will forcibly be killed. **Not used in a `plan.ps1`.** Default: `8`. *Optional*. ``` pkg_shutdown_timeout_sec=$pkg_shutdown_timeout_sec ``` pkg_description A short description of the package. It can be a simple string, or you can create a multi-line description using markdown to provide a rich description of your package. This description will be displayed on the Web app when users search for or browse to your package. Type: Text.*Required* for [core](https://github.com/habitat-sh/core-plans) plans, but otherwise *Optional*. ``` pkg_description=$(cat << EOF # My package description This is the package for the foo library. It's pretty awesome. EOF ) ``` Note Escape all special characters other than `#`. The hab-plan-build script interprets unescaped characters as code during the package build. pkg_upstream_url An upstream project homepage or website URL. *Optional*. ``` pkg_upstream_url=https://github.com/myrepo ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/plan_settings/Container Orchestration ======================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/container_orchestration.md) Chef Habitat packages may be exported with the Supervisor directly into a [variety of container formats](../pkg_exports/index), but frequently the container is running in a container orchestrator such as Kubernetes or Mesos. Container orchestrators provide scheduling and resource allocation, ensuring workloads are running and available. Containerized Chef Habitat packages can run within these runtimes, managing the applications while the runtimes handle the environment surrounding the application (ie. compute, networking, security). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/container_orchestration/Service Template Data ===================== The following settings can be used during a Chef Habitat service’s lifecycle. This means that you can use these settings in any of the plan hooks, such as `init`, or `run`, and also in any templatized configuration file for your application or service. These configuration settings are referenced using the [Handlebars.js](https://github.com/wycats/handlebars.js/) version of [Mustache-style](https://mustache.github.io/mustache.5.html) tags. sys --- System information | Property | Type | Description | | --- | --- | --- | | ctl_gateway_ip | string | Listening address for Supervisor’s Control Gateway. | | ctl_gateway_port | integer | Listening port for Supervisor’s Control Gateway. | | gossip_ip | string | Listening address for Supervisor’s gossip connection. | | gossip_port | integer | Listening port for Supervisor’s gossip connection. | | hostname | string | The hostname of the running service. | | http_gateway_ip | string | Listening address for Supervisor’s HTTP gateway. | | http_gateway_port | integer | Listening port for Supervisor’s HTTP gateway. | | ip | string | The IP address of the running service. | | member_id | string | The member’s Supervisor ID, e.g., `3d1e73ff19464a27aea3cdc5c2243f74` | | permanent | boolean | Set to true if a Supervisor is being used as a permanent peer, to increase Ring network traffic stability. | | version | string | Version of the Habitat Supervisor, e.g., `0.54.0/20180221023448` | pkg --- Details about the package currently running the service | Property | Type | Description | | --- | --- | --- | | ident | string | The fully-qualified identifier of the running package, e.g., `core/redis/3.2.4/20170514150022` | | origin | string | The origin of the Habitat package | | name | string | The name of the Habitat package | | version | string | The version of the Habitat package | | release | string | The release of the Habitat package | | deps | array | An array of runtime dependencies for your package based on the `pkg_deps` setting in a plan | | env | object | The runtime environment of your package, mirroring the contents of the `RUNTIME_ENVIRONMENT` metadata file. The `PATH` variable is set, containing all dependencies of your package, as well as any other runtime environment variables that have been set by the package. Individual variables can be accessed directly, like `{{pkg.env.PATH}}` (the keys are case sensitive). | | exposes | array | The array of ports to expose for an application or service. This value is pulled from the pkg_exposes setting in a plan. | | exports | object | A map of export key to internal configuration value key (i.e., the contents of `pkg_exports` in your plan). The key is what external services consume. The value is a key in your `default.toml` file that corresponds to the data being exported. | | path | string | The location where the package is installed locally, e.g., `/hab/pkgs/core/redis/3.2.4/20170514150022`. Note that this is *not* a `PATH` environment variable; for that, please see the `env` key above. | | svc_path | string | The root location of the source files for the Habitat service, e.g., `/hab/svc/redis`. | | svc_config_path | string | The location of any templated configuration files for the Habitat service, e.g., `/hab/svc/redis/config`. | | svc_data_path | string | The location of any data files for the Habitat service, e.g., `/hab/svc/redis/data`. | | svc_files_path | string | The location of any gossiped configuration files for the Habitat service, e.g., `/hab/svc/redis/files`. | | svc_static_path | string | The location of any static content for the Habitat service, e.g., `/hab/svc/redis/static`. | | svc_var_path | string | The location of any variable state data for the Habitat service, e.g., `/hab/svc/redis/var`. | | svc_pid_file | string | The location of the Habitat service pid file, e.g., `/hab/svc/redis/PID`. | | svc_run | string | The location of the rendered run hook for the Habitat service, e.g., `/hab/svc/redis/run`. | | svc_user | string | The value of `pkg_svc_user` specified in a plan. | | svc_group | string | The value of `pkg_svc_group` specified in a plan. | cfg --- These are settings defined in your templatized configuration file. The values for those settings are pulled from the `default.toml` file included in your package. svc --- Information about the current service’s service group | Property | Type | Description | | --- | --- | --- | | service | string | The name of the service. If the service is running from the package `core/redis`, the value will be `redis`. | | group | string | The group portion of the service’s complete group name. In the group name `redis.default`, the group’s value is `default`. | | org | string | The organization portion of a service group specification. Unused at this time. | | election_is_running | boolean | Whether a leader election is currently running for this service | | election_is_no_quorum | boolean | Whether there is quorum for a leader election for this service | | election_is_finished | boolean | Whether a leader election for this service has finished | | update_election_is_running | boolean | Whether an update leader election is currently running for this service | | update_election_is_no_quorum | boolean | Whether there is quorum for an update leader election for this service | | update_election_is_finished | boolean | Whether an update leader election for this service has finished | | me | [svc_member](#svc_member) | An object that provides information about the service running on the local Supervisor | | first | [svc_member](#svc_member) | The first member of this service group, or the leader, if running in a leader topology | | members | array | All active members (`alive` and `suspect`) of the service group, across the entire ring. As of 0.56.0, does *not* include `departed` or `confirmed` members | | leader | [svc_member](#svc_member) | The current leader of the service group, if any (`null` otherwise) | | update_leader | [svc_member](#svc_member) | The current update_leader of the service group, if any (`null` otherwise) | bind ---- Exposes information about the service groups this service is bound to. Each key is the name of a bind, while each value is one of the objects described below | Property | Type | Description | | --- | --- | --- | | first | [svc_member](#svc_member) | The first member of this service group. If the group is running in a leader topology, this will also be the leader. | | leader | [svc_member](#svc_member) | The current leader of this service group, if running in a leader topology | | members | array | All active members (`alive` and `suspect`) of the service group, across the entire ring. As of 0.56.0, does *not* include `departed` or `confirmed` members | Reference Objects ----------------- Some of the template expressions referenced above return objects of a specific shape; for example, the `svc.me` and `svc.first` expressions return “service member” objects, and the `pkg` property of a service member returns a “package identifier” object. These are defined below. package_identifier ------------------- A Habitat package identifier, split apart into its constituent components | Property | Type | Description | | --- | --- | --- | | origin | string | The origin of the Habitat package | | name | string | The name of the Habitat package | | version | string | The version of the Habitat package | | release | string | The release of the Habitat package | svc_member ----------- Represents a member of a service group | Property | Type | Description | | --- | --- | --- | | member_id | string | the member’s Supervisor id, e.g., 3d1e73ff19464a27aea3cdc5c2243f74 | | alive | boolean | Whether this member is considered alive and connected to the ring, from a network perspective. | | suspect | boolean | Whether this member is considered “suspect”, or possibly unreachable, from a network perspective. | | confirmed | boolean | Whether this member is confirmed dead / unreachable, from a network perspective. | | departed | boolean | Whether this member has been departed from the ring (i.e., permanently gone, never to return). | | election_is_running | boolean | Whether a leader election is currently running for this service | | election_is_no_quorum | boolean | Whether there is quorum for a leader election for this service | | election_is_finished | boolean | Whether a leader election for this service has finished | | update_election_is_running | boolean | Whether an update leader election is currently running for this service | | update_election_is_no_quorum | boolean | Whether there is quorum for an update leader election for this service | | update_election_is_finished | boolean | Whether an update leader election for this service has finished | | leader | boolean | Whether this member is the leader in the service group (only meaningful in a leader topology) | | follower | boolean | Whether this member is a follower in the service group (only meaningful in a leader topology) | | update_leader | boolean | Whether this member is the update leader in the service group (only meaningful in a leader topology) | | update_follower | boolean | Whether this member is an update follower in the service group (only meaningful in a leader topology) | | pkg | [package_identifier](#package_identifier) | The identifier of the release the member is running | | package | string | The package identifier | | sys | object | An abbreviated version of the top-level {{sys}} object, containing networking information for the member. | | cfg | object | The configuration the member is currently exporting. This is constrained by what is defined in `pkg_exports`, where the values are replaced with the current values (e.g., taking into account things like user.toml, gossiped configuration values, etc.) | | persistent | boolean | A misspelling of `permanent`; indicates whether a member is a permanent peer or not | | service | string | The name of the service. If the service is running from the package `core/redis`, the value will be `redis`. | | group | string | The group portion of the service’s complete group name. In the group name `redis.default`, the group’s value is `default`. | | org | string | The organization portion of a service group specification. Unused at this time. | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/service_templates/Kubernetes ========== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/kubernetes.md) [Kubernetes](https://kubernetes.io/) is an open source container cluster manager that is available as a stand-alone platform or embedded in several distributed platforms including [Google’s Container Engine](https://cloud.google.com/container-engine/), [AWS Elastic Kubernetes Service](https://aws.amazon.com/eks/), [Azure Kubernetes Service](https://azure.microsoft.com/services/kubernetes-service/), and [Red Hat OpenShift](https://openshift.com/). Chef Habitat and Kubernetes are complementary. While Kubernetes provides a platform for deployment, scaling, and operations of application containers across clusters of hosts, Chef Habitat manages the build pipeline and lifecycle of those application containers. Chef Habitat on Kubernetes -------------------------- Chef Habitat can export your package as a Docker container that runs on Kubernetes in the form of a pod. Additionally, a Chef Habitat bastion pod provides essential gossip ring features like service discovery (binds), secrets and the required [initial peer](../sup_networks/index) to all other pods. Chef Habitat robustly deploys the bastion pod with a Kubernetes stateful set, persistent volume, and liveness checking, which ensures node availability and ring data persistence. The Kubernetes stateful set comes with an attached Kubernetes service that makes discoverable with DNS. Each namespace should contain a single service and stateful set. Deploy the Chef Habitat Bastion on Kubernetes --------------------------------------------- Complete examples may be downloaded from [this folder](../pattern_library/index#kubernetes-bastion-ring-pattern) To explain how this works, let’s break down the hab-bastion.yaml file: ``` apiVersion:v1kind:Servicemetadata:name:hab-bastionspec:ports:- name:gossip-listenerprotocol:UDPport:9638targetPort:9638- name:http-gatewayprotocol:TCPport:9631targetPort:9631selector:app:hab-bastionclusterIP:None ``` This service definition creates a virtual IP (VIP), opening access to the Chef Habitat service that runs on the pod. * The habitat gossip port (9638/UDP) listener * The habitat http-gateway (9631/TCP) listener * makes service name available in DNS (as `hab-bastion` or `hab-bastion.namespace-name`, etc) and discoverable by any pod ``` apiVersion:apps/v1kind:StatefulSetmetadata:name:hab-bastionspec:spec:securityContext:fsGroup:42 ``` This section sets the group ownership for the persistent volume mount point so the Habitat Supervisor can write to it. The Habitat user (`hab`) by default has the uid `42` and the gid `42`. ``` containers:- name:hab-bastionimage:mydockerorigin/hab_bastion:latestargs:- '--permanent-peer' ``` The `image:` line defines the source of the docker container. In this case, the instructions create an image from a Chef Habitat plan using the `hab pkg export docker` command. It only runs the Chef Habitat Supervisor (hab-sup) service. The argument `--permanent-peer` instructs the Supervisor to act as a permanent peer. ``` resources:requests:memory:"100Mi"cpu:"100m"# equivalent to 0.1 of a CPU core ``` Resource requests are important because they give instructions to the Kubernetes scheduler–without them, you might overload some nodes while under-using others. ``` ports:- name:gossip-listenerprotocol:UDPcontainerPort:9638- name:http-gatewayprotocol:TCPcontainerPort:9631readinessProbe:httpGet:path:/port:9631initialDelaySeconds:5periodSeconds:10livenessProbe:httpGet:path:/port:9631initialDelaySeconds:15periodSeconds:20 ``` The `livenessProbe` tells Kubernetes if the pod is healthy or not. If not, the pod gets restarted. The `readinessProbe` signals to Kubernetes that the pod has started up successfully. ``` volumeMounts:- name:hab-bastionmountPath:/hab/supvolumeClaimTemplates:- metadata:name:hab-bastionspec:accessModes:["ReadWriteOnce"]# uncomment if you don't have a default StorageClass# storageClassName: "standard"resources:requests:storage:10Gi ``` All of the Habitat Supervisor’s state data is stored under `/hab/sup` - we mount this on a persistent volume so it gets re-attached if the pod is ever rescheduled. The data persists! Create a Kubernetes Deployment That Works with the Bastion ---------------------------------------------------------- The following is an example of a Kubernetes `Stateful Set` built from the CockroachDB plan. The Bastion pattern uses the `--peer hab-bastion` configuration arguments to instruct the Kubernetes pods to use the `hab-bastion` service as a DNS-resolvable host name. ``` +++apiVersion:apps/v1kind:StatefulSetmetadata:name:cockroachdbspec:selector:matchLabels:app:cockroachdbserviceName:cockroachdbreplicas:3template:metadata:labels:app:cockroachdbspec:terminationGracePeriodSeconds:10securityContext:fsGroup:42containers:- name:cockroachdbimage:irvingpop/cockroach:latestargs:- --peer- hab-bastion- --topology- leaderresources:requests:memory:"300Mi"cpu:"500m"ports:- name:httpcontainerPort:8080- name:cockroachdbcontainerPort:26257volumeMounts:- name:cockroachdb-datamountPath:/hab/svc/cockroach/datavolumeClaimTemplates:- metadata:name:cockroachdb-dataspec:accessModes:["ReadWriteOnce"]resources:requests:storage:10Gi ``` Bare Kubernetes --------------- If your packages don’t require communication with the Chef Habitat Supervisor ring, such as binds, secrets, etc., then you can execute your packages directly on the cluster. You can deploy Chef Habitat packages exported as containers to Kubernetes with the [`kubectl` command](http://kubernetes.io/docs/user-guide/pods/single-container/). Using the [Docker exporter](../pkg_exports/index#exporting-to-docker) to create a containerized application, you can launch the container like this example: ``` $ kubectl run mytutorial --image=myorigin/mytutorial --port=8080 ``` Assuming you’re using the Docker image pulled from `myorigin/mytutorial`, port 8080 on the container should be accessible. Pass networking ports exposed by Chef Habitat with `kubectl run` as `--port` options. In this example, the `kubectl get` command is: ``` $ kubectl get pods -l run=mytutorial ``` Docker and ACI -------------- Chef Habitat packages can be exported in both Docker and ACI formats (as well as others). Kubernetes currently supports the Docker runtime and integration of the rkt container runtime (an implementation of the App Container spec) is under active development. Environment Variables and Networking ------------------------------------ Kubernetes supports passing [environment variables](https://kubernetes.io/docs/user-guide/environment-guide/) into containers. Related Reading --------------- * [Export a Chef Habitat package](../pkg_exports/index) * [Chef Habitat CLI](../habitat_cli/index) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/kubernetes/Azure Container Services (AKS) ============================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/aks.md) [Azure Container Services (AKS)](https://azure.microsoft.com/services/container-service/) is a fully managed Kubernetes service running on the Azure platform. Azure Container Registry (ACR) ------------------------------ Azure Container Registry is a managed Docker container registry service used for storing private Docker container images. It’s a fully managed Azure resource and gives you local, network-close storage of your container images when deploying to AKS. Chef Habitat Builder has native integration with this service so you can publish your packages directly to Azure Container Registry. In order to do this you need to create an Azure Service Principal that has `Owner` rights on your ACR instance. You can do this with the following script, changing the environment variable values to match your environment. ``` !/bin/bash R_RESOURCE_GROUP=myACRResourceGroup R_NAME=myACRRegistry BLDR_PRINCIPAL_NAME=myPrincipalName BLDR_PRINCIPAL_PASSWORD="ThisIsVeryStrongPassword" Create Service Principal for Chef Habitat Builder R_ID=$(az acr show --name $ACR_NAME --resource-group $ACR_RESOURCE_GROUP --query "id" --output tsv) ad sp create-for-rbac --scopes $ACR_ID --role Owner --password "$BLDR_PRINCIPAL_PASSWORD" --name $BLDR_PRINCIPAL_NAME BLDR_ID=$(az ad sp list --display-name $BLDR_PRINCIPAL_NAME --query "[].appId" --output tsv) ho "Configuration details for Habitat Builder Principal:" echo " ID : $BLDR_ID" echo " Password : $BLDR_PRINCIPAL_PASSWORD" ``` Note: The unique Service Principal Name (the UUID) should be provided in the Chef Habitat Builder configuration. Connecting ACR and AKS ---------------------- Since ACR is a private Docker registry, AKS must be authorized to pull images from it. The best way is to create a role assignment on the Service Principal that is automatically created for AKS, granting it `Reader` access on your ACR instance. To do this you can use the following script, changing the environment variable values to match your configuration. ``` #!/bin/bash AKS_RESOURCE_GROUP=myAKSResourceGroup AKS_CLUSTER_NAME=myAKSCluster ACR_RESOURCE_GROUP=myACRResourceGroup ACR_NAME=myACRRegistry # Get the id of the service principal configured for AKS CLIENT_ID=$(az aks show --resource-group $AKS_RESOURCE_GROUP --name $AKS_CLUSTER_NAME --query "servicePrincipalProfile.clientId" --output tsv) # Get the ACR Registry Resource ID ACR_ID=$(az acr show --name $ACR_NAME --resource-group $ACR_RESOURCE_GROUP --query "id" --output tsv) # Create Role Assignment az role assignment create --assignee $CLIENT_ID --role Reader --scope $ACR_ID ``` Related Reading --------------- * [Authenticate with Azure Container Registry from Azure Container Service](https://docs.microsoft.com/azure/container-registry/container-registry-auth-aks#grant-aks-access-to-acr) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/aks/Google Container Registry (GCR) =============================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/gcr.md) [Google Container Registry](https://cloud.google.com/container-registry/) is a private Docker repository that works with popular continuous delivery systems. It runs on GCP to provide consistent uptime on an infrastructure protected by Google’s security. The registry service hosts your private images in Cloud Storage under your GCP project. Before you can push or pull images, you must configure Docker to use the gcloud command-line tool to authenticate requests to Container Registry. To do so, run the following command (you are only required to do this once): ``` $ gcloud auth configure-docker ``` Further access control information is [available here](https://cloud.google.com/container-registry/docs/access-control). After a successful Chef Habitat package build, images can be pushed to the Container Registry using the registry URI. The format of this follows: `[HOSTNAME]/[PROJECT-ID]/[IMAGE]:[TAG]`, more details at [this link](https://cloud.google.com/container-registry/docs/pushing-and-pulling): ``` $ hab pkg export docker ./results/habskp-hab-gcr-demo-0.1.0-20180710145742-x86_64-linux.hart $ docker tag habskp/hab-gcr-demo:latest eu.gcr.io/user-project/hab-gcr-demo:latest $ docker push eu.gcr.io/user-project/hab-gcr-demo:latest ``` Related Reading --------------- * [Google Container Registry](https://cloud.google.com/container-registry/) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/gcr/Running Chef Habitat Linux Containers ===================================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/running_habitat_linux_containers.md) When you run `hab pkg export docker`, you’ll get a Docker container that provides a few things. First, a minimal Linux OS filesystem is provided, with just enough configuration (e.g., `/etc/passwd`, `/etc/resolv.conf`, etc.) to run. Second, the contents of the exported Chef Habitat package, along with its complete dependency tree, as well as a complete Chef Habitat Supervisor installation, are provided, unpacked, in the `/hab/pkgs` directory. Finally, an entry-point script that will start the Supervisor, running the exported Chef Habitat package, is provided, allowing the container itself to behave as though it were the Supervisor. On Linux, the Chef Habitat Supervisor will normally run as the `root` user, and will start Chef Habitat services as the `pkg_svc_user` specified by that service. However, in some deployment scenarios, it undesirable–or even impossible–to run the Supervisor as `root`. The [OpenShift](https://www.openshift.com/) container platform, for instance, does not run containers as `root` by default, but as randomly-chosen anonymous user IDs. From version 0.53.0 onward, the Chef Habitat Supervisor can now run as an arbitrary user, providing users with more flexibility in how and where the use Chef Habitat. In order to support this in containers and provide maximal flexibility, the contents of the `/hab` directory are both readable *and writable* by the `root` *group*. When specifying a user to run a container process as, the user’s primary group will be reported as `root` if no matching group can be found in `/etc/group`. This will allow the user to create and populate the `/hab/sup` directory for managing Supervisor state, as well as the `/hab/svc` directory, which will contain all the service’s state. This is in line with [recommendations from OpenShift](https://docs.openshift.com/container-platform/3.3/creating_images/habitat/guidelines.html#openshift-container-platform-specific-guidelines) on how to create containers that can run as a non-root user, but nothing in Chef Habitat’s implementation is specific to OpenShift; indeed, all the examples provided below use pure Docker. Caveats to Running as a Non-root User ------------------------------------- “There’s no such thing as a free lunch”, as the saying goes, and that holds true here. If the Supervisor is running as a non-root user, any processes that it supervises will be run as the same user; any values that the process might specify via `pkg_svc_user` and `pkg_svc_group` are essentially ignored. Furthermore, any files written out by the service during its operation are also owned by that same user. ### Details Actually, the Supervisor does not care what user it is running as; rather, it uses Linux capabilities to guide its behavior. If the process has the `CAP_SETUID`, `CAP_SETGID`, and `CAP_CHOWN` capabilities, it will be able to run processes as the specified `pkg_svc_user` and `pkg_svc_group` (`CAP_CHOWN` is needed to ensure that the service processes can read and write files within the service’s state directories). The Supervisor checks for the presence of these capabilities, and does not rely on having a user ID of 0 or the username `root`. Container Deployment Scenarios ------------------------------ ### Running a Chef Habitat Container as a Root User This is the base case. If you are fine with running your container as `root`, you can do that directly: ``` docker run --rm -it core/redis:latest ``` Here, `core/redis:latest` would be the image exported from the `core/redis` Chef Habitat package. The Supervisor will run as normal, with supervised processes running as the desired user. ### Running a Chef Habitat Container as a Non-root User If you cannot run as the `root` user, but you are fine with `root` being the container user’s primary group, you can simply specify a user ID to run as. This user need not exist in the container itself, and it’s better if it doesn’t. Using pure Docker, it might look like this: ``` docker run --rm -it --user=888888 core/redis:latest ``` Again, we use our `core/redis` Chef Habitat package container; the user ID 888888 is simply a number chosen at random (this is how platforms like OpenShift operate). No user inside the container has this ID, meaning that the user will be an anonymous user with `root` as its primary group. Because of how we generate Chef Habitat containers, this fact ensures that the user has write permissions within the `/hab` directory. Due to the current logic around package installation, there is an extra step needed if you would like to have your containerized Supervisors update either themselves or the services they supervise. When installing packages as a non-root user, Chef Habitat will download the origin keys and compressed hart files into the user’s `${HOME}/.hab` directory, rather than the global `/hab/cache` directory. You will need to ensure that a user-writable directory is mounted into the container, and specify it as the user’s home directory using the `HOME` environment variable. Using pure Docker with a volume that is accessible by the user, that might look like this: ``` docker volume create --driver local \\ --opt type=tmpfs \\ --opt device=tmpfs \\ --opt o=size=100m,uid=888888 \\ test_home docker run --rm -it \\ --user=888888 \\ --mount type=volume,src=test_home,dst=/myhome \\ --env HOME=/myhome \\ core/redis:latest --auto-update --strategy=at-once ``` This is merely an illustration; use whatever volume management approaches and service update strategies that are appropriate for your container scheduling system and your local deployment. As illustrated, updates of this kind are completely optional; you may prefer to move update responsibility to your container scheduler and treat your containers as immutable in this regard. Running a Chef Habitat Container as a Non-root User in a Non-root Group ----------------------------------------------------------------------- If for whatever reason you do not want your user to be in the `root` group inside the container, you will need to add some additional volumes in order to create the needed directories. However, since you will (by definition) not have write permissions on the `/hab` directory as a whole, your Supervisor *will not* be able to update either itself or the services it supervises. To implement this using pure Docker, you could do something like this (the group ID of `999999` was again chosen arbitrarily, as with the user ID): ``` docker volume create --driver local \\ --opt type=tmpfs \\ --opt device=tmpfs \\ --opt o=size=100m,uid=888888 \\ sup_state docker volume create --driver local \\ --opt type=tmpfs \\ --opt device=tmpfs \\ --opt o=size=100m,uid=888888 \\ svc_state docker volume create --driver local \\ --opt type=tmpfs \\ --opt device=tmpfs \\ --opt o=size=100m,uid=888888 \\ launcher_state docker run --rm -it \\ --user=888888:999999 \\ --mount type=volume,src=sup_state,dst=/hab/sup \\ --mount type=volume,src=svc_state,dst=/hab/svc \\ --mount type=volume,src=launcher_state,dst=/hab/launcher \\ core/redis:latest ``` Again, this is just an illustrative example; use the appropriate strategies for your specific circumstances. The key information here is to ensure that the `/hab/sup`, `/hab/svc`, and `/hab/launcher` directories are writable by the user inside the container. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/running_habitat_linux_containers/Amazon ECS ========== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/ecs.md) Amazon Web Services provides a container management service called [EC2 Container Service (ECS)](https://aws.amazon.com/ecs/). ECS provides a Docker registry, container hosting and tooling to make deploying Docker-based containers fairly straightforward. ECS will schedule and deploy your Docker containers within a Task while Chef Habitat manages the applications. EC2 Container Registry ---------------------- [EC2 Container Registry (ECR)](https://aws.amazon.com/ecr/) is a fully-managed Docker registry provided by Amazon Web Services. Applications exported to Docker with `hab pkg export docker` put the containers into namespaced repositories, so you will need to create these within ECR. For example, if you were building `core/mongodb` containers you would use the following command: ``` $ aws ecr create-repository --repository-name core/mongodb ``` To tag and push the images to the ECR you will use your Repository URI (substituting your **aws_account_id** and availability zone). ``` $ docker tag core/mongodb:latest aws_account_id.dkr.ecr.ap-southeast-2.amazonaws.com/core/mongodb:latest $ docker push aws_account_id.dkr.ecr.ap-southeast-2.amazonaws.com/core/mongodb:latest ``` EC2 Compute Service ------------------- Once Docker images are pushed to ECR, they may be run on Amazon’s ECS within a [Task Definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_defintions.html) which may be expressed as a [Docker Compose file](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cmd-ecs-cli-compose.html). Here is an example of a Tomcat application using a Mongo database demonstrating using Chef Habitat-managed containers: ``` version:'2'services:mongo:image:aws_account_id.dkr.ecr.ap-southeast-2.amazonaws.com/username/mongodb:latesthostname:"mongodb"national-parks:image:aws_account_id.dkr.ecr.ap-southeast-2.amazonaws.com/username/national-parks:latestports:- "8080:8080"links:- mongocommand:--peer mongodb --bind database:mongodb.default ``` From the example, the `mongo` and `national-parks` services use the Docker images from the ECR. The `links` entry manages the deployment order of the container and according to the [Docker Compose documentation](https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/#/updating-the-etchosts-file) `links` should create `/etc/hosts` entries. This does not appear to currently work with ECS so we assign the `hostname: "mongodb"`. The `command` entry for the National Parks Tomcat application allows the Chef Habitat Supervisor to `--peer` to the `mongo` gossip ring and `--bind` applies `database` entries to its Mongo configuration. Related Reading --------------- * [A Journey with Chef Habitat on Amazon ECS, Part 1](https://blog.chef.io/a-journey-with-habitat-on-amazon-ecs-part-1/)) * [A Journey with Chef Habitat on Amazon ECS, Part 2](https://blog.chef.io/a-journey-with-habitat-on-amazon-ecs-part-2/) © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/ecs/Chef Habitat Architecture Overview ================================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/architecture_overview.md) ![Chef Habitat Architecture Overview Diagram] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/architecture_overview/Apache Mesos and DC/OS ====================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/mesos_dcos.md) [Apache Mesos](https://mesos.apache.org/) is an open source distributed systems kernel and the distributed systems kernel for [Mesosphere’s DC/OS](https://dcos.io) distributed platform. Mesos Containerizers -------------------- Mesos has support for [containerizers](https://mesos.apache.org/documentation/latest/containerizer/) for running commands and applications within isolated containers. Mesos supports Docker and its own [Mesos containerizer](https://mesos.apache.org/documentation/latest/mesos-containerizer/) format. The Mesos containerizer provides lightweight containerization with `cgroups/namespaces` isolation without actual isolation. The `hab pkg export mesos` command creates a mostly empty base filesystem with the application and the Chef Habitat Supervisor and packages it into a compressed tarball. Marathon Applications --------------------- [Marathon](https://mesosphere.github.io/marathon/) is a container orchestration platform for Mesos and DC/OS, handling the scheduling and deployment of applications. [Marathon applications](https://mesosphere.github.io/marathon/docs/application-basics.html) support Docker and the Mesos container formats, wrapping them in JSON metadata describing the resources needed to deploy the application. Once the application has been deployed to Marathon, it schedules it across the Mesos cluster and ensures the application is running optimally. ### Export to a Mesos Container and Marathon Application You can create native Mesos containers from Chef Habitat packages by following these steps: 1. Create an interactive studio in any directory with the `hab studio enter` command. 2. Install or [build](../pkg_build/index) the Chef Habitat package from which you want to create a Marathon application, for example: ``` $ hab pkg install yourorigin/yourpackage ``` 3. Run the Mesos exporter on the package. ``` $ hab pkg export mesos yourorigin/yourpackage ``` 4. This will create a Mesos container-format tarball in the results directory, and also print the JSON needed to load the application into Marathon. Note that the tarball needs to be uploaded to a download location and the `"uris"` in the JSON need to be updated manually. This is an example of the output: ``` { "id": "yourorigin/yourpackage", "cmd": "/bin/id -u hab &>/dev/null || /sbin/useradd hab; /bin/chown -R hab:hab *; mount -t proc proc proc/; mount -t sysfs sys sys/;mount -o bind /dev dev/; /usr/sbin/chroot . ./init.sh start yourorigin/yourpackage", "cpus": 0.5, "disk": 0, "mem": 256, "instances": 1, "uris": [ "https://storage.googleapis.com/mesos-habitat/yourorigin/yourpackage-0.0.1-20160611121519.tgz" ] } ``` 5. Note that the default resource allocation for the application is very small: 0.5 units of CPU, no disk, one instance, and 256MB of memory. To change these resource allocations, pass different values to the Mesos exporter as command line options (defaults are documented with `--help`). 6. From the DC/OS web interface, launch the Marathon Service. ![Screen shot of DC/OS Services] 7. Select “Create Application”. ![Screen shot of Marathon Applications List] 8. Click on the “JSON Mode” selector and enter the JSON output of the Mesos exporter and click “Create Application”. ![Screen shot of Marathon New Application JSON Mode] 9. Marathon will then deploy the application and enter the “Running” status. ![Screen shot of Marathon Application Running] Debugging --------- You can get to the output from the running application by clicking on the “Marathon” service from the DC/OS “Services” tab. Select the application and the “Log Viewer” and choose either the “Error” or “Output” to see `stderr` and `stdout` respectively. If you have SSH access into the nodes, the Mesos container directories are beneath `/var/lib/mesos/slave/slaves`. ![Screen shot of Debugging a Running Application] Future Enhancements ------------------- This is a basic integration, there are many improvements yet to be made. Here are a few examples: * Marathon environment variables are not passed into the Chef Habitat package “cmd” yet. * Networking ports exposed by Chef Habitat need to be added to the JSON. * The Chef Habitat gossip protocol needs to be included as a default exposed port. * If Marathon is running the [artifact store](https://mesosphere.github.io/marathon/docs/artifact-store.html), support uploading the tarball directly into it. * Upload applications directly to the [Marathon application API](https://mesosphere.github.io/marathon/docs/application-basics.html). * Marathon supports unpacking several archive formats. Native `.hart` support could be added directly to Marathon. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/mesos_dcos/Running Chef Habitat Windows Containers ======================================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/running_habitat_windows_containers.md) Exported Windows images use `microsoft/windowsservercore` as their base. This is the equivalent of a minimal Windows Server 2016 Core install. So you should not expect non default features and roles to be enabled such as IIS or Active Directory. Consider using an `init` hook to install any features needed by your Chef Habitat service. Container Pull and Startup Time ------------------------------- The `microsoft/windowsservercore` image is approximately 5GB. Due to this large size, you can expect that the first time you run an exported Chef Habitat service, pulling down the image may take several minutes. This wait should only occur on the very first `docker run` of any Chef Habitat Windows service. Additionally, depending on the Windows host operating system, running the container may also take considerably longer than what one is accustomed to with Linux based containers. This startup time will be highly influenced by the container isolation mode described below. Windows Containers and Host Kernel Isolation -------------------------------------------- There are two types of Windows containers and each runs under a different level of kernel isolation. ### Windows Server Containers These containers, like their Linux counterparts, share the host’s kernel. You can expect these containers to start pretty quickly and this is the default container type on Windows Server 2016 hosts. ### Hyper-V Containers Windows Hyper-V containers run inside of a very minimal Hyper-V VM. As a result, they do not share the host’s kernel and offer a higher level of security and isolation. The cost of this isolation is that it will take longer for the container to start - perhaps a noticeable delay. Also be aware that the VM is provisioned with a default 1 GB limit of memory. If your service requires more than a gigabyte of memory, you can use the `--memory` argument with `docker run` and pass a larger limit. ``` docker run --memory 2GB -it core/mysql ``` On a Windows 10 host, Windows containers will always run inside of Hyper-V isolation. Kernel sharing Windows Server containers are only available on Windows Server 2016 hosts. On Windows Server 2016, Windows Server containers are the default container type but you can force `docker run` to use Hyper-V containers by setting the `--isolation` argument to `hyperv`. ``` docker run --isolation hyperv -it core/mysql ``` Host Loopback Network --------------------- A common container pattern is to forward the container port to a local port and then access the container application by accessing `localhost` on the forwarded port. With Windows containers, published ports cannot be accessed using `localhost`. You will instead need to use the IP address of the host or the IP of the individual container to access the application’s endpoint. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/running_habitat_windows_containers/Initial Package Build Flow ========================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/package_build_flow.md) ![Chef Habitat Initial Package Build Flow Diagram] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/package_build_flow/Application Rebuild Flow ======================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/application_rebuild_flow.md) ![Chef Habitat Application Rebuild Flow Diagram] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/application_rebuild_flow/Automate Docker Container Publishing Flow ========================================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/docker_automated_flow.md) ![Chef Habitat Automated Docker Container Publishing Flow Diagram] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/docker_automated_flow/Docker Container Publishing Flow ================================ [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/docker_flow.md) ![Chef Habitat Initial Docker Container Publishing Flow Diagram] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/docker_flow/Dependency Update Flow ====================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/dependency_update_flow.md) ![Chef Habitat Dependency Update Flow Diagram](https://docs.chef.io/images/habitat/habitat-dependency-update-flow.png) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/dependency_update_flow/Promote Packages Through Channels ================================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/promote_packages.md) ![Chef Habitat Promote Packages Through Channels Diagram] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/promote_packages/Runtime Services Group Binding ============================== [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/runtime_binding.md) ![Chef Habitat Runtime Services Group Binding Diagram](https://docs.chef.io/images/habitat/habitat-runtime-service-group-binding.png) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/runtime_binding/Chef Habitat Builder Architecture ================================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/builder_architecture.md) ![Chef Habitat Builder Architecture Diagram](https://docs.chef.io/images/habitat/habitat-builder-architecture.png) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/builder_architecture/Chef Habitat Builder on-prem Flow ================================= [[edit on GitHub]](https://github.com/habitat-sh/habitat/tree/main/components/docs-chef-io/content/habitat/on_prem_flow.md) ![Chef Habitat On-premises Builder Depot Flow Diagram](https://docs.chef.io/images/habitat/habitat-on-premises-builder-depot-flow.png) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/habitat/on_prem_flow/Chef Infra Overview =================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_overview.md) Chef Infra is a powerful automation platform that transforms infrastructure into code. Whether you’re operating in the cloud, on-premises, or in a hybrid environment, Chef Infra automates how infrastructure is configured, deployed, and managed across your network, no matter its size. This diagram shows how you develop, test, and deploy your Chef Infra code. ![image] command line tools. * **Chef Infra Client** Chef Infra Client runs on systems that are managed by Chef Infra. The Chef Infra Client executes on a schedule to configure a system to the desired state. * **Chef Infra Server** acts as [a hub for configuration data](../server/index). Chef Infra Server stores cookbooks, the policies that are applied to nodes, and metadata that describes each registered node that is being managed by Chef. Nodes use the Chef Infra Client to ask the Chef Infra Server for configuration details, such as recipes, templates, and file distributions. Chef Infra Components --------------------- The following diagram shows the relationships between the various elements of Chef Infra, including the nodes, the server, and the workstation. These elements work together to provide the Chef Infra Client the information and instruction that it needs so that it can do its job. As you are reviewing the rest of this topic, use the icons in the tables to refer back to this image. ![Diagram of Chef Infra Client, Server, and Workstation] Chef Infra has the following major components: | Component | Description | | --- | --- | | image | One (or more) workstations are configured to allow users to author, test, and maintain cookbooks. Workstation systems run the Chef Workstation package which includes tools such as Chef Infra Client, Chef InSpec, Test Kitchen, ChefSpec, Cookstyle, and other tools necessary for developing and testing your infrastructure with Chef products. | | image | Cookbooks are uploaded to the Chef Infra Server from these workstations. Some cookbooks are custom to the organization and others are based on community cookbooks available from the Chef Supermarket. | | image | Ruby is the programming language that is the authoring syntax for cookbooks. Most recipes are simple patterns (blocks that define properties and values that map to specific configuration items like packages, files, services, templates, and users. The full power of Ruby is available for when you need a programming language. | | image | A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. | | image | Chef Infra Client is installed on each node that is managed with Chef Infra. Chef Infra Client configures the node locally by performing the tasks specified in the run-list. Chef Infra Client will also pull down any required configuration data from the Chef Infra Server during a Chef Infra Client run. | | image | The Chef Infra Server acts as a hub of information. Cookbooks and policy settings are uploaded to the Chef Infra Server by users from workstations. The Chef Infra Client accesses the Chef Infra Server from the node on which it's installed to get configuration data, performs searches of historical Chef Infra Client run data, and then pulls down the necessary configuration data. After a Chef Infra Client run is finished, the Chef Infra Client uploads updated run data to the Chef Infra Server. | | image | Chef Supermarket is the location in which community cookbooks are shared and managed. Cookbooks that are part of the Chef Supermarket may be used by any Chef user. How community cookbooks are used varies from organization to organization. | Chef Infra Client run reporting, compliance reporting, high availability configurations, and Chef Infra Server replication are available as part of Chef Automate. The following sections discuss these elements (and their various components) in more detail. Workstations ------------ A workstation is your local computer running Chef Workstation that you use to author cookbooks, interact with the Chef Infra Server, and interact with nodes. The workstation is where users do most of their work, including: * Developing and testing cookbooks * Keeping the Chef Infra repository synchronized with version source control * Configuring organizational by including defining and applying Policyfiles or Policy Groups * Interacting with nodes, as (or when) required, such as performing a bootstrap operation ### Chef Workstation Components and Tools Some important tools and components of Chef Workstation include: | Component | Description | | --- | --- | | image | Start your infrastructure automation quickly and easily with [Chef Workstation](../workstation/index). Chef Workstation gives you everything you need to get started with Chef - ad hoc remote execution, remote scanning, configuration tasks, cookbook creation tools as well as robust dependency and testing software - all in one easy-to-install package. Chef Workstation includes:* Chef Infra Client * Chef InSpec * Chef Habitat * chef and knife command line tools * Testing tools such as Test Kitchen and Cookstyle * Everything else needed to author cookbooks and upload them to the Chef Infra Server | | image image | Chef Workstation includes important command-line tools:* Chef Infra: Use the chef command-line tool to work with items in a chef-repo, which is the primary location in which cookbooks are authored, tested, and maintained, and from which policy is uploaded to the Chef Infra Server * Knife: Use the knife command-line tool to interact with nodes or work with objects on the Chef Infra Server * Chef Infra Client: an agent that configures your nodes * Test Kitchen: a testing harness for rapid validation of Chef code * Chef InSpec: Chef's open source security & compliance automation framework * chef-run: a tool for running ad-hoc tasks * Chef Workstation App: for updating and managing your chef tools | | image | The chef-repo is the repository structure in which cookbooks are authored, tested, and maintained:* Cookbooks contain recipes, attributes, custom resources, libraries, files, templates, tests, and metadata * The chef-repo should be synchronized with a version control system (such as git), and then managed as if it were source code The directory structure within the chef-repo varies. Some organizations prefer to keep all of their cookbooks in a single chef-repo, while other organizations prefer to use a chef-repo for every cookbook. | | image | Use [Test Kitchen](https://kitchen.ci/) to automatically test cookbooks across any combination of platforms and test suites:* Test suites are defined in a kitchen.yml file. See the [configuration](../workstation/config_yml_kitchen/index) documentation for options and syntax information. * Supports cookbook testing across many cloud providers and virtualization technologies. * Uses a comprehensive set of operating system base images from Chef’s [Bento](https://github.com/chef/bento) project. | | image | Use ChefSpec to simulate the convergence of resources on a node:* Is an extension of RSpec, a behavior-driven development (BDD) framework for Ruby * Is the fastest way to test resources and recipes | Cookbooks --------- A cookbook is the fundamental unit of configuration and policy distribution in Chef Infra. A cookbook defines a scenario and contains everything that is required to support that scenario: * Recipes that specify which Chef Infra built-in resources to use, as well as the order in which they are to be applied * Attribute values, which allow environment-based configurations such as `dev` or `prodution`. * Custom Resources for extending Chef Infra beyond the built-in resources. * Files and Templates for distributing information to systems. * Custom Ohai Plugins for extending system configuration collection beyond the Ohai defaults. * The `metadata.rb` file, which describes the cookbook itself and any dependencies it may have. The Chef Infra Client uses Ruby as its reference language for creating cookbooks and defining recipes, with an extended DSL for specific resources. A reasonable set of resources are available to the Chef Infra Client, enough to support many of the most common infrastructure automation scenarios; however, this DSL can also be extended when additional resources and capabilities are required. ### Components Cookbooks are comprised of the following components: | Component | Description | | --- | --- | | image | An attribute can be defined in a cookbook (or a recipe) and then used to override the default settings on a node. When a cookbook is loaded during a Chef Infra Client run, these attributes are compared to the attributes that are already present on the node. Attributes that are defined in attribute files are first loaded according to cookbook order. For each cookbook, attributes in the `default.rb` file are loaded first, and then additional attribute files (if present) are loaded in lexical sort order. When the cookbook attributes take precedence over the default attributes, Chef Infra Client applies those new settings and values during a Chef Infra Client run on the node. | | image | Use the **cookbook_file** resource to transfer files from a sub-directory of `COOKBOOK_NAME/files/` to a specified path located on a host that is running Chef Infra Client. The file is selected according to file specificity, which allows different source files to be used based on the hostname, host platform (operating system, distro, or as appropriate), or platform version. Files that are located in the `COOKBOOK_NAME/files/default` sub-directory may be used on any platform. | | image | A library allows arbitrary Ruby code to be included in a cookbook. The most common use for libraries is to write helpers that are used throughout recipes and custom resources. A library file is a Ruby file that is located within a cookbook’s `/libraries` directory. Because a library is built using Ruby, anything that can be done with Ruby can be done in a library file, including advanced functionality such as extending built-in Chef classes. | | image | Every cookbook requires a small amount of metadata. The contents of the `metadata.rb` file provides information that helps Chef Infra Client and Server correctly deploy cookbooks to each node. A `metadata.rb` file is:* Located at the top level of a cookbook’s directory structure. * Compiled whenever a cookbook is uploaded to the Chef Infra Server or when the `knife cookbook metadata` subcommand is run, and then stored as JSON data. * Created automatically by knife whenever the `knife cookbook create` subcommand is run. * Edited using a text editor, and then re-uploaded to the Chef Infra Server as part of a cookbook upload. | | image | A recipe is the most fundamental configuration element within the organization. A recipe:* Is authored using Ruby, which is a programming language designed to read and behave in a predictable manner * Is mostly a collection of [resources](../resources/index), defined using patterns (resource names, attribute-value pairs, and actions); helper code is added around this using Ruby, when needed * Must define everything that is required to configure part of a system * Must be stored in a cookbook * May be included in another recipe * May use the results of a search query and read the contents of a data bag (including an encrypted data bag) * May have a dependency on one (or more) recipes * Must be added to a run-list before it can be used by Chef Infra Client * Is always executed in the same order as listed in a run-list The Chef Infra Client will run a recipe only when asked. When the Chef Infra Client runs the same recipe more than once, the results will be the same system state each time. When a recipe is run against a system, but nothing has changed on either the system or in the recipe, the Chef Infra Client won't change anything. The Chef Infra Language is a comprehensive systems configuration language with resources and helpers for configuring operating systems. The language is primarily used in Chef Infra recipes and custom resources to tell the Chef Infra Client what action(s) to take to configure a system. The Chef Infra Language provides resources for system-level components such as packages, users, or firewalls, and it also includes helpers to allow you to make configuration decisions based on operating systems, clouds, virtualization hypervisors, and more. | | image | A resource is a statement of configuration policy that:* Describes the desired state for a configuration item * Declares the steps needed to bring that item to the desired state * Specifies a resource type—such as `package`, `template`, or `service` * Lists additional details (also known as resource properties), as necessary * Are grouped into recipes, which describe working configurations Chef has [many built-in resources](../resources/index) that cover all of the most common actions across all of the most common platforms. You can [build your own resources](../custom_resources/index) to handle any situation that isn't covered by a built-in resource. | | image | A cookbook template is an Embedded Ruby (ERB) template that is used to dynamically generate static text files. Templates may contain Ruby expressions and statements, and are a great way to manage configuration files. Use the **template** resource to add cookbook templates to recipes; place the corresponding Embedded Ruby (ERB) template file in a cookbook’s `/templates` directory. | | image | Testing cookbooks improves the quality of those cookbooks by ensuring they are doing what they are supposed to do and that they are authored in a consistent manner. Unit and integration testing validates the recipes in cookbooks. Syntax testing---often called linting---validates the quality of the code itself. The following tools are popular tools used for testing Chef recipes: Test Kitchen, ChefSpec, and Cookstyle. | Nodes ----- A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. ### Node Types The types of nodes that can be managed by Chef include, but are not limited to, the following: | Node Type | Description | | --- | --- | | image | A physical node is typically a server or a virtual machine, but it can be any active device attached to a network that is capable of sending, receiving, and forwarding information over a communications channel. In other words, a physical node is any active device attached to a network that can run a Chef Infra Client and also allow that Chef Infra Client to communicate with a Chef Infra Server. | | image | A cloud-based node is hosted in an external cloud-based service, such as Amazon Web Services (AWS), OpenStack, Rackspace, Google Compute Engine, or Microsoft Azure. Plugins are available for knife that provide support for external cloud-based services. knife can use these plugins to create instances on cloud-based services. Once created, Chef Infra Client can be used to deploy, configure, and maintain those instances. | | image | A virtual node is a machine that runs only as a software implementation, but otherwise behaves much like a physical machine. | | image | A network node is any networking device---a switch, a router---that is being managed by a Chef Infra Client, such as networking devices by Juniper Networks, Arista, Cisco, and F5. Use Chef to automate common network configurations, such as physical and logical Ethernet link properties and VLANs, on these devices. | | image | Containers are an approach to virtualization that allows a single operating system to host many working configurations, where each working configuration---a container---is assigned a single responsibility that is isolated from all other responsibilities. Containers are popular as a way to manage distributed and scalable applications and services. | ### Chef on Nodes The key components of nodes that are under management by Chef include: | Component | Description | | --- | --- | | image | Chef Infra Client is an agent that runs locally on every node that is under management by Chef Infra Server. When Chef Infra Client runs, it performs all of the steps required for bringing a node into the expected state, including:* Registering and authenticating the node with Chef Infra Server * Synchronizing cookbooks from the Chef Infra Server to the node * Compiling the resource collection by loading each of the required cookbooks, including recipes, attributes, and all other dependencies * Taking the appropriate and required actions to configure the node based on recipes and attributes * Reporting summary information on the run to Chef Automate Chef Infra Client authenticates with the Chef Infra Server using RSA public key-pairs each time a Chef Infra Client needs access to data that is stored on the Chef Infra Server. This prevents any node from accessing data that it shouldn’t and it ensures that only nodes that are properly registered with the Chef Infra Server can be managed. | | image | Ohai is a tool for collecting system configuration data, which it then provides to Chef Infra Client to use in cookbooks. Chef Infra Client runs Ohai at the start of every Chef Infra run to determine system state. The attributes that Ohai collects are called `automatic attributes`. Chef Infra Client uses these attributes to ensure that nodes are in the desired state after each configuration run. The types of attributes Ohai collects include but are not limited to:* Operating System * Network * Memory * Disk * CPU * Kernel * Host names * Fully qualified domain names * Virtualization * Cloud provider metadata Ohai includes required and optional plugins to detect common configuration information. Ohai has a plugin model and language to write [custom plugins](../ohai_custom/index) to collect additional system state information. | The Chef Infra Server --------------------- The Chef Infra Server acts as a hub for configuration data. The Chef Infra Server stores cookbooks, the policies that are applied to nodes, and the metadata that describes each registered node that is under management by Chef Infra Client. Nodes use Chef Infra Client to ask the Chef Infra Server for configuration details, such as recipes, templates, and file distributions. Chef Infra Client then does as much of the configuration work as possible on the nodes themselves (and not on the Chef Infra Server). This scalable approach distributes the configuration effort throughout the organization. | Feature | Description | | --- | --- | | image | Search indexes allow queries to be made for any type of data that is indexed by the Chef Infra Server, including data bags (and data bag items), environments, nodes, and roles. A defined query syntax is used to support search patterns like exact, wildcard, range, and fuzzy. A search is a full-text query that can be done from several locations, including from within a recipe, by using the `search` subcommand in knife, the `search` method in the Chef Infra Language, the search box in the Chef management console, and by using the `/search` or `/search/INDEX` endpoints in the Chef Infra Server API. The search engine is based on Elasticsearch and is run from the Chef Infra Server. | | image | Chef management console is a web-based interface for the Chef Infra Server that provides users a way to manage the following objects:* Nodes * Cookbooks and recipes * Roles * Stores of JSON data (data bags), including encrypted data * Environments * Searching of indexed data * User accounts and user data for the individuals who have permission to log on to and access the Chef server | | image | Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. | | image | Policy defines how business and operational requirements, processes, and production workflows map to objects that are stored on the Chef Infra Server. Policy objects on the Chef Infra Server include roles, environments, and cookbook versions. | ### Policy Policy maps business and operational requirements, process, and workflow to settings and objects stored on the Chef Infra Server: * Roles define server types, such as “web server” or “database server” * Environments define process, such as “dev”, “staging”, or “production” * Certain types of data—passwords, user account data, and other sensitive items—can be placed in data bags, which are located in a secure sub-area on the Chef Infra Server that can only be accessed by nodes that authenticate to the Chef Infra Server with the correct SSL certificates * The cookbooks (and cookbook versions) in which organization-specific configuration policies are maintained Some important aspects of policy include: | Feature | Description | | --- | --- | | image | A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. | | image | An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. | | image | A cookbook version represents a set of functionality that is different from the cookbook on which it is based. A version may exist for many reasons, such as ensuring the correct use of a third-party component, updating a bug fix, or adding an improvement. A cookbook version is defined using syntax and operators, may be associated with environments, cookbook metadata, and/or run-lists, and may be frozen (to prevent unwanted updates from being made). A cookbook version is maintained just like a cookbook, with regard to source control, uploading it to the Chef Infra Server, and how Chef Infra Client applies that cookbook when configuring nodes. | | image | A run-list defines all of the information necessary for Chef to configure a node into the desired state. A run-list is:* An ordered list of roles and/or recipes that are run in the exact order defined in the run-list; if a recipe appears more than once in the run-list, Chef Infra Client will not run it twice * Always specific to the node on which it runs; nodes may have a run-list that is identical to the run-list used by other nodes * Stored as part of the node object on the Chef server * Maintained using knife and then uploaded from the workstation to the Chef Infra Server, or maintained using Chef Automate | Conclusion ---------- Chef is a thin DSL (domain-specific language) built on top of Ruby. This approach allows Chef to provide just enough abstraction to make reasoning about your infrastructure easy. Chef includes a built-in taxonomy of all the basic resources one might configure on a system, plus a defined mechanism to extend that taxonomy using the full power of the Ruby language. Ruby was chosen because it provides the flexibility to use both the simple built-in taxonomy, as well as being able to handle any customization path your organization requires. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_overview/Chef Infra Client Overview ========================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_client_overview.md) Note For the `chef-client` command line tool, see [chef-client(executable)](../ctl_chef_client/index). **New in Chef Infra Client 17** Chef Infra Client’s Compliance Phase lets you automatically execute compliance audits and view the results as part of any Chef Infra Client Run. The Compliance Phase replaces the legacy audit cookbook and works with your existing audit cookbook attributes. You can also set up the Compliance Phase for new cookbooks. See [Compliance Phase](../chef_compliance_phase/index) documentation to upgrade. | image | Chef Infra Client is an agent that runs locally on every node that is under management by Chef Infra Server. When Chef Infra Client runs, it performs all of the steps required for bringing a node into the expected state, including:* Registering and authenticating the node with Chef Infra Server * Synchronizing cookbooks from the Chef Infra Server to the node * Compiling the resource collection by loading each of the required cookbooks, including recipes, attributes, and all other dependencies * Taking the appropriate and required actions to configure the node based on recipes and attributes * Reporting summary information on the run to Chef Automate Chef Infra Client authenticates with the Chef Infra Server using RSA public key-pairs each time a Chef Infra Client needs access to data that is stored on the Chef Infra Server. This prevents any node from accessing data that it shouldn’t and it ensures that only nodes that are properly registered with the Chef Infra Server can be managed. | The Chef Infra Client Run ------------------------- A “Chef Infra Client run” is the term used to describe the steps Chef Infra Client takes to configure a node when the chef-client command is run. The following diagram shows the various stages that occur during a Chef Infra Client run. ![Anatomy of a Chef Infra Client Run](https://docs.chef.io/images/chef_run.svg) During every Chef Infra Client run, the following happens: | Stages | Description | | --- | --- | | **Get configuration data** | Chef Infra Client gets process configuration data from the [client.rb](../config_rb_client/index) file on the [node](../nodes/index), and then gets node configuration data from Ohai. One important piece of configuration data is the name of the node, which is found in the `node_name` attribute in the client.rb file or is provided by Ohai. If Ohai provides the name of a node, it is typically the FQDN for the node, which is always unique within an organization. | | **Authenticate to the Chef Infra Server** | Chef Infra Client [authenticates](../server/auth/index) to the Chef Infra Server using an RSA private key and the Chef Infra Server API. The name of the node is required as part of the authentication process to the Chef Infra Server. If this is the first Chef Infra Client run for a node, the chef-validator will be used to generate the RSA private key. | | **Get, rebuild the node object** | Chef Infra Client pulls down the node object from the Chef Infra Server and then rebuilds it. A node object is made up of the system attributes discovered by Ohai, the attributes set in Policyfiles or Cookbooks, and the run list of cookbooks. The first time Chef Infra Client runs on a node, it creates a node object from the default run-list. A node that has not yet had a Chef Infra Client run will not have a node object or a Chef Infra Server entry for a node object. On any subsequent Chef Infra Client runs, the rebuilt node object will also contain the run-list from the previous Chef Infra Client run. | | **Expand the run-list** | Chef Infra Client expands the [run-list](../run_lists/index) from the rebuilt node object and compiles a complete list of recipes in the exact order that they will be applied to the node. | | **Synchronize cookbooks** | Chef Infra Client requests all the [cookbook files](../cookbooks/index) (including recipes, templates, resources, providers, attributes, and libraries) that it needs for every action identified in the run-list from the Chef Infra Server. The Chef Infra Server responds to Chef Infra Client with the complete list of files. Chef Infra Client compares the list of files to the files that already exist on the node from previous runs, and then downloads a copy of every new or modified file from the Chef Infra Server. | | **Reset node attributes** | All attributes in the rebuilt node object are reset. All attributes from attribute files, Policyfiles, and Ohai are loaded. Attributes that are defined in attribute files are first loaded according to cookbook order. For each cookbook, attributes in the `default.rb` file are loaded first, and then additional attribute files (if present) are loaded in lexical sort order. If attribute files are found within any cookbooks that are listed as dependencies in the `metadata.rb` file, these are loaded as well. All attributes in the rebuilt node object are updated with the attribute data according to attribute precedence. When all the attributes are updated, the rebuilt node object is complete. | | **Compile the resource collection** | Chef Infra Client identifies each resource in the node object and builds the resource collection. Libraries are loaded first to ensure that all language extensions and Ruby classes are available to all resources. Next, attributes are loaded, followed by custom resources. Finally, all recipes are loaded in the order specified by the expanded run-list. This is also referred to as the "compile phase". | | **Converge the node** | Chef Infra Client configures the system based on the information that has been collected. Each resource is executed in the order identified by the run-list, and then by the order in which each resource is listed in each recipe. Each resource defines an action to run, which configures a specific part of the system. This process is also referred to as convergence. This is also referred to as the "execution phase". | | **Update the node object, process exception and report handlers** | When all the actions identified by resources in the resource collection have been done and Chef Infra Client finishes successfully, then Chef Infra Client updates the node object on the Chef Infra Server with the node object built during a Chef Infra Client run. (This node object will be pulled down by Chef Infra Client during the next Chef Infra Client run.) This makes the node object (and the data in the node object) available for search. Chef Infra Client always checks the resource collection for the presence of exception and report handlers. If any are present, each one is processed appropriately. | | **Get, run Chef InSpec Compliance Profiles** | After the Chef Infra Client run finishes, it begins the Compliance Phase, which is a Chef InSpec run within the Chef Infra Client. Chef InSpec retrieves tests from either a legacy audit cookbook or a current InSpec profile. | | **Send or Save Compliance Report** | When all the InSpec tests finish running, Chef InSpec checks the reporting handlers defined in the legacy audit cookbook or in a current InSpec profile and processes them appropriately. | | **Stop, wait for the next run** | When everything is configured and the Chef Infra Client run is complete, Chef Infra Client stops and waits until the next time it is asked to run. | Related Content --------------- * [Chef Infra Client (executable)](../ctl_chef_client/index) * [Chef Infra Server](../server/index) * [Cookbooks](../cookbooks/index) * [Nodes](../nodes/index) * [Run Lists](../run_lists/index) Next Steps ---------- * [Install Chef Workstation](../workstation/install_workstation/index) * [Bootstrap Nodes](../install_bootstrap/index) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_client_overview/About Nodes =========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/nodes.md) A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. The types of nodes that can be managed by Chef include, but are not limited to, the following: | Node Type | Description | | --- | --- | | image | A physical node is typically a server or a virtual machine, but it can be any active device attached to a network that is capable of sending, receiving, and forwarding information over a communications channel. In other words, a physical node is any active device attached to a network that can run a Chef Infra Client and also allow that Chef Infra Client to communicate with a Chef Infra Server. | | image | A cloud-based node is hosted in an external cloud-based service, such as Amazon Web Services (AWS), OpenStack, Rackspace, Google Compute Engine, or Microsoft Azure. Plugins are available for knife that provide support for external cloud-based services. knife can use these plugins to create instances on cloud-based services. Once created, Chef Infra Client can be used to deploy, configure, and maintain those instances. | | image | A virtual node is a machine that runs only as a software implementation, but otherwise behaves much like a physical machine. | | image | A network node is any networking device---a switch, a router---that is being managed by a Chef Infra Client, such as networking devices by Juniper Networks, Arista, Cisco, and F5. Use Chef to automate common network configurations, such as physical and logical Ethernet link properties and VLANs, on these devices. | | image | Containers are an approach to virtualization that allows a single operating system to host many working configurations, where each working configuration---a container---is assigned a single responsibility that is isolated from all other responsibilities. Containers are popular as a way to manage distributed and scalable applications and services. | The key components of nodes that are under management by Chef include: | Component | Description | | --- | --- | | image | Chef Infra Client is an agent that runs locally on every node that is under management by Chef Infra Server. When Chef Infra Client runs, it performs all of the steps required for bringing a node into the expected state, including:* Registering and authenticating the node with Chef Infra Server * Synchronizing cookbooks from the Chef Infra Server to the node * Compiling the resource collection by loading each of the required cookbooks, including recipes, attributes, and all other dependencies * Taking the appropriate and required actions to configure the node based on recipes and attributes * Reporting summary information on the run to Chef Automate Chef Infra Client authenticates with the Chef Infra Server using RSA public key-pairs each time a Chef Infra Client needs access to data that is stored on the Chef Infra Server. This prevents any node from accessing data that it shouldn’t and it ensures that only nodes that are properly registered with the Chef Infra Server can be managed. | | image | Ohai is a tool for collecting system configuration data, which it then provides to Chef Infra Client to use in cookbooks. Chef Infra Client runs Ohai at the start of every Chef Infra run to determine system state. The attributes that Ohai collects are called `automatic attributes`. Chef Infra Client uses these attributes to ensure that nodes are in the desired state after each configuration run. The types of attributes Ohai collects include but are not limited to:* Operating System * Network * Memory * Disk * CPU * Kernel * Host names * Fully qualified domain names * Virtualization * Cloud provider metadata Ohai includes required and optional plugins to detect common configuration information. Ohai has a plugin model and language to write [custom plugins](../ohai_custom/index) to collect additional system state information. | Node Names ---------- The name of a node is required as part of the authentication process to the Chef Infra Server. The name of each node must be unique within an organization, but otherwise can be any string that matches the following regular expression: ``` /^[\-[:alnum:]_:.]+$/ ``` The name of a node can be obtained from the `node_name` attribute in the client.rb file or by allowing Ohai to collect this data during a Chef Infra Client run. When Ohai collects this data during a Chef Infra Client run, it uses the node’s FQDN, which is always unique within an organization, as the name of the node. Using the FQDN as the node name, and then allowing Ohai to collect this information during each Chef Infra Client run, is the recommended approach and the easiest way to ensure that the names of all nodes across the organization are unique. Node Objects ------------ For Chef Infra Client, two important aspects of nodes are groups of attributes and run-lists. An attribute is a specific piece of data about the node, such as a network interface, a file system, the number of clients a service running on a node is capable of accepting, and so on. A run-list is an ordered list of recipes and/or roles that are run in an exact order. The node object consists of the run-list and node attributes, which is a JSON file that is stored on the Chef Infra Server. Chef Infra Client gets a copy of the node object from the Chef Infra Server during each Chef Infra Client run and places an updated copy on the Chef Infra Server at the end of each Chef Infra Client run. An attribute is a specific detail about a node. Attributes are used by Chef Infra Client to understand: * The current state of the node * What the state of the node was at the end of the previous Chef Infra Client run * What the state of the node should be at the end of the current Chef Infra Client run Attributes are defined by: * The node as saved on the Chef Infra Server * Attributes passed via JSON on the command line * Cookbooks (in attribute files and/or recipes) * Policyfiles During every Chef Infra Client run, Chef Infra Client builds the attribute list using: * Attributes passed via JSON on the command line * Data about the node collected by [Ohai](../ohai). * The node object that was saved to the Chef Infra Server at the end of the previous Chef Infra Client run. * The rebuilt node object from the current Chef Infra Client run, after it is updated for changes to cookbooks (attribute files and/or recipes) and/or Policyfiles, and updated for any changes to the state of the node itself. After the node object is rebuilt, all of the attributes are compared, and then the node is updated based on attribute precedence. At the end of every Chef Infra Client run, the node object that defines the current state of the node is uploaded to the Chef Infra Server so that it can be indexed for search. ### Attributes An attribute is a specific detail about a node, such as an IP address, a host name, a list of loaded kernel modules, the version(s) of available programming languages that are available, and so on. An attribute may be unique to a specific node or it can be identical across every node in the organization. Attributes are most commonly set from a cookbook, by using knife, or are retrieved by Ohai from each node prior to every Chef Infra Client run. All attributes are indexed for search on the Chef Infra Server. Good candidates for attributes include: * any cross-platform abstraction for an application, such as the path to a configuration file * default values for tunable settings, such as the amount of memory assigned to a process or the number of workers to spawn * anything that may need to be persisted in node data between Chef Infra Client runs In general, attribute precedence is set to enable cookbooks and roles to define attribute defaults, for normal attributes to define the values that should be specific for a node, and for override attributes to force a certain value, even when a node already has that value specified. One approach is to set attributes at the same precedence level by setting attributes in a cookbook’s attribute files, and then also setting the same default attributes (but with different values) using a role. The attributes set in the role will be deep merged on top of the attributes from the attribute file, and the attributes set by the role will take precedence over the attributes specified in the cookbook’s attribute files. See [Attributes](../attributes) for detailed information on the different types of node attributes and how they are used to set policy on nodes. ### Run-lists A run-list defines all of the information necessary for Chef to configure a node into the desired state. A run-list is: * An ordered list of roles and/or recipes that are run in the exact order defined in the run-list; if a recipe appears more than once in the run-list, Chef Infra Client will not run it twice * Always specific to the node on which it runs; nodes may have a run-list that is identical to the run-list used by other nodes * Stored as part of the node object on the Chef server * Maintained using knife and then uploaded from the workstation to the Chef Infra Server, or maintained using Chef Automate #### Run-list Format A run-list must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: ``` "role[NAME]" ``` or ``` "recipe[COOKBOOK::RECIPE]" ``` Use a comma to separate roles and recipes when adding more than one item the run-list: ``` "recipe[COOKBOOK::RECIPE],COOKBOOK::RECIPE,role[NAME]" ``` Managing Nodes -------------- You can manage nodes directly using Knife, Chef Automate, or by using command-line tools that are specific to Chef Infra Client. * [Knife](../workstation/knife/index) can be used to create, edit, view, list, tag, and delete nodes. * Knife plug-ins can be used to create, edit, and manage nodes that are located on cloud providers. * Chef Infra Client can be used to manage node data using the command line and JSON files. Each JSON file contains a hash, the elements of which are added as node attributes. In addition, the `run_list` setting allows roles and/or recipes to be added to the node. * The command line can also be used to edit JSON files and files that are related to third-party services, such as Amazon EC2, where the JSON files can contain per-instance metadata that is stored in a file on-disk and then read by Chef Infra Client as required. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/nodes/Quick Start =========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/quick_start.md) The quickest way to get started using Chef Infra is to install Chef Workstation and create your first Chef Infra Cookbook: 1. Install Chef Workstation: <https://www.chef.io/downloads/tools/tools/workstation>. 2. Generate a Chef Infra repository with an example cookbook: ``` chef generate repo my_first_repo ``` where `my_first_repo` is an arbitrary name for your Chef Infra repository. 3. Navigate to the `cookbooks/example` directory. 4. Update the `cookbooks/example/recipes/default.rb` recipe in the generated cookbook to contain: ``` file "#{ENV['HOME']}/test.txt" do content 'This file was created by Chef Infra!' end ``` 5. Run Chef Infra Client using the `default.rb` recipe: ``` chef-client --local-mode --override-runlist example ``` This creates a file named `test.txt` at the home path on your computer. Open that file and it will say `This file was created by Chef Infra!`. * Delete the file, run Chef Infra Client again, and Chef Infra will replace the file. * Change the string in the file, run Chef Infra Client again, and Chef Infra will make the string in the file the same as the string in the recipe. * Change the string in the recipe, run Chef Infra Client again, and Chef Infra will update that string to be the same as the one in the recipe. There’s a lot more that Chef Infra can do, obviously, but that was super easy! * See <https://learn.chef.io/> for more detailed setup scenarios. * Keep reading for more information about setting up a workstation, configuring Test Kitchen to run virtual environments, setting up a more detailed cookbook, resources, and more. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/quick_start/System Requirements =================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_system_requirements.md) Before installing Chef Infra: * Ensure that each system you will be managing is running a [supported platform](../platforms/index) * Ensure that the machine that will run the Chef Infra Server is sufficiently powerful * Ensure that any network and firewall settings are configured correctly Install and configure the Chef Infra Server, then install and configure Chef Workstation, and then run the bootstrap command from Chef Workstation to install Chef Infra Client on each node. The Chef Infra Server --------------------- The following sections describe the various requirements for the Chef Infra Server. ### Hosted Chef Infra Server Requirements Every node that will be configured by Chef Infra Client and every workstation that will upload data to the Chef Infra Server must be able to communicate with the hosted Chef server. ### Chef Infra Server, On-premises or in Cloud Environment All machines in a Chef Infra Server deployment have the following hardware requirements. Disk space for standalone and backend servers should scale up with the number of nodes that the servers are managing. A good rule to follow is to allocate 2 MB per node. The disk values listed below should be a good default value that you will want to modify later if/when your node count grows. Fast, redundant storage (SSD/RAID-based solution either on-prem or in a cloud environment) is preferred. **All Deployments** * 64-bit CPU architecture * CPU support for SSE4.2 extensions (Xeons starting in 2007 and Opterons in 2012) **Standalone Deployments** * 4 total cores (physical or virtual) * 8 GB of RAM or more * 5 GB of free disk space in `/opt` * 10 GB of free disk space in `/var` For a high availability deployment: **General Requirements** * Three backend servers; as many frontend servers as required * 1 x GigE NIC interface (if on premises) **Frontend Requirements** * 4 cores (physical or virtual) * 4GB RAM * 20 GB of free disk space (SSD if on premises, Premium Storage in Microsoft Azure, EBS-Optimized GP2 in AWS) **Backend Requirements** * 2 cores (physical or virtual) * 8GB RAM * 50 GB/backend server (SSD if on premises, Premium Storage in Microsoft Azure, EBS-Optimized GP2 in AWS) Warning The Chef Infra Server MUST NOT use a network file system of any type—virtual or physical—for backend storage. The Chef Infra Server database operates quickly. The behavior of operations, such as the writing of log files, will be unpredictable when run over a network file system. Before installing the Chef Infra Server, ensure that each machine has the following installed and configured properly: * **Hostnames** — Ensure that all systems have properly configured hostnames. The hostname for the Chef Infra Server must be a FQDN, have fewer than 64 characters including the domain suffix, be lowercase, and resolvable. See [Hostnames, FQDNs](../install_server_pre#hostnames) for more information * **FQDNs** — Ensure that all systems have a resolvable FQDN * **NTP** — Ensure that every server is connected to NTP; the Chef Infra Server is sensitive to clock drift * **Mail Relay** — The Chef Infra Server uses email to send notifications for various events; a local mail transfer agent should be installed and available to the Chef server * **cron** — Periodic maintenance tasks are performed using cron * **git** — git must be installed so that various internal services can confirm revisions * **Apache Qpid** — This daemon must be disabled on CentOS and Red Hat systems * **Required users** — If the environment in which the Chef Infra Server will run has restrictions on the creation of local user and group accounts, ensure that the correct users and groups exist before reconfiguring * **Firewalls and ports** — If host-based firewalls (iptables, ufw, etc.) are being used, ensure that ports 80 and 443 are open. In addition: * **Browser** — Firefox, Google Chrome, Safari, or Internet Explorer (versions 9 or better) * **Chef Infra Client communication with the Chef Infra Server** The Chef Infra Server must be able to communicate with every node that will be configured by Chef Infra Client and every workstation that will upload data to the Chef Infra Chef Infra Client ----------------- * The recommended amount of RAM available to Chef Infra Client during a Chef Infra Client run is 512MB * The Chef Infra Client binaries are stored in the `/opt/chef` directory, which requires a minimum of 200MB of disk space. On Windows, the Chef Infra Client binaries can be found in `C:\opscode\`, and they require a minimum of 600MB of disk space. * The processor must be [supported](../platforms/index). We recommend a 1 gigahertz (GHz) or faster processor, but the processor speed should be based on the other system loads. * Chef Infra Client caches to `/var/chef/cache` during a Chef Infra Client run. This is the location in which downloaded cookbooks, packages required by those cookbooks, and other large files are stored. This directory requires enough space to save all of this data and should be generously sized. 5GB is a safe number as a starting point, but tune the size of `/var/chef/cache` as necessary. This location is tunable in a node’s [client.rb](../config_rb_client/index) file via the `file_cache_path` setting. Chef Workstation ---------------- * 64-bit architecture * 4 GB of RAM or more * 2 GB of free disk space © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_system_requirements/Working with Proxies ==================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/proxies.md) In an environment that requires proxies to reach the Internet, many Chef commands will not work until they are configured correctly. To configure Chef to work in an environment that requires proxies, set the `http_proxy`, `https_proxy`, `ftp_proxy`, and/or `no_proxy` environment variables to specify the proxy settings using a lowercase value. Microsoft Windows ----------------- To determine the current proxy server on the Microsoft Windows platform: 1. Open **Internet Properties**. 2. Open **Connections**. 3. Open **LAN settings**. 4. View the **Proxy server** setting. If this setting is blank, then a proxy server may not be available. To configure proxy settings in Microsoft Windows: 1. Open **System Properties**. 2. Open **Environment Variables**. 3. Open **System variables**. 4. Set `http_proxy` and `https_proxy` to the location of your proxy server. This value **MUST** be lowercase. Linux ----- To determine the current proxy server on the macOS and Linux platforms, check the environment variables. Run the following: ``` env | grep -i http_proxy ``` If an environment variable is set, it **MUST** be lowercase. If it is not, add a lowercase version of that proxy variable to the shell (e.g. `~/.bashrc`) using one (or more) the following commands. For HTTP: ``` export http_proxy=http://myproxy.com:3168 ``` For HTTPS: ``` export https_proxy=http://myproxy.com:3168 ``` For FTP: ``` export ftp_proxy=ftp://myproxy.com:3168 ``` Proxy Settings -------------- Proxy settings are defined in configuration files for Chef Infra Client and for knife and may be specified for HTTP, HTTPS, and FTP. ### HTTP Use the following settings in the client.rb or config.rb files for environments that use an HTTP proxy: | Setting | Description | | --- | --- | | `http_proxy` | The proxy server for HTTP connections. Default value: `nil`. | | `http_proxy_pass` | The password for the proxy server when the proxy server is using an HTTP connection. Default value: `nil`. | | `http_proxy_user` | The user name for the proxy server when the proxy server is using an HTTP connection. Default value: `nil`. | ### HTTPS Use the following settings in the client.rb or config.rb files for environments that use an HTTPS proxy: | Setting | Description | | --- | --- | | `https_proxy` | The proxy server for HTTPS connections. Default value: `nil`. | | `https_proxy_pass` | The password for the proxy server when the proxy server is using an HTTPS connection. Default value: `nil`. | | `https_proxy_user` | The user name for the proxy server when the proxy server is using an HTTPS connection. Default value: `nil`. | ### FTP Use the following settings in the client.rb or config.rb files for environments that use an FTP proxy: | Setting | Description | | --- | --- | | `ftp_proxy` | The proxy server for FTP connections. | | `ftp_proxy_pass` | The password for the proxy server when the proxy server is using an FTP connection. Default value: `nil`. | | `ftp_proxy_user` | The user name for the proxy server when the proxy server is using an FTP connection. Default value: `nil`. | ### No Proxy The `no_proxy` setting is used to specify addresses for which the proxy should not be used. This can be a single address or a comma-separated list of addresses. Example: ``` no_proxy 'test.example.com,test.example2.com,test.example3.com' ``` Note Wildcard matching may be used in the `no_proxy` list—such as `no_proxy '*.*.example.*'`—however, many situations require hostnames to be specified explicitly (i.e. “without wildcards”). Environment Variables --------------------- Consider the following for situations where environment variables are used to set the proxy: * Proxy settings may not be honored by all applications. For example, proxy settings may be ignored by the underlying application when specifying a `ftp` source with a `remote_file` resource. Consider a workaround. For example, in this situation try doing a `wget` with an `ftp` URL instead. * Proxy settings may be honored inconsistently by applications. For example, the behavior of the `no_proxy` setting may not work with certain applications when wildcards are specified. Consider specifying the hostnames without using wildcards. ### ENV If `http_proxy`, `https_proxy`, `ftp_proxy`, or `no_proxy` is set in the client.rb file but not set in the `ENV`, Chef Infra Client will configure the `ENV` variable based on these (and related) settings. For example: ``` http_proxy 'http://proxy.example.org:8080' http_proxy_user 'myself' http_proxy_pass 'Password1' ``` Or an alternative way to define the proxy (if the previous version does not work): ``` http_proxy 'http://myself:Password1@proxy.example.org:8080' ``` will be set to: ``` ENV['http_proxy'] = 'http://myself:Password1@proxy.example.org:8080' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/proxies/client.rb ========= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/config_rb_client.md) The client.rb file specifies how Chef Infra Client is configured on a node and has the following characteristics: * This file is loaded every time the chef-client executable is run. * On Microsoft Windows machines, the default location for this file is `C:\chef\client.rb`. On all other systems the default location for this file is `/etc/chef/client.rb`. * Use the `--config` option from the command line to override the default location of the configuration file. * This file is not created by default Settings -------- This configuration file has the following settings: `add_formatter` A 3rd-party formatter. (See [nyan-cat](https://github.com/andreacampi/nyan-cat-chef-formatter) for an example of a 3rd-party formatter.) Each formatter requires its own entry. `allowed_automatic_attributes` A hash that allows `default` attributes, preventing non-allowed attributes from being saved. `allowed_default_attributes` A hash that allows `default` attributes, preventing non-allowed attributes from being saved. `allowed_normal_attributes` A hash that allows `normal` attributes, preventing non-allowed attributes from being saved. `allowed_override_attributes` A hash that allows `override` attributes, preventing non-allowed attributes from being saved. `authentication_protocol_version` Sets the authentication protocol that is used to communicate with Chef Infra Server. For example, specify protocol version 1.3 to enable support for SHA-256 algorithms: ``` knife[:authentication_protocol_version] = '1.3' ``` Note Authentication protocol 1.3 is only supported on Chef Server versions 12.4.0 and above. `automatic_attribute_blacklist` A hash that blocks `automatic` attributes, preventing blocked attributes from being saved. **Deprecated. EOL Chef Infra Client 18 (April 2022)**: Use `blocked_automatic_attributes`. `automatic_attribute_whitelist` A hash that allows `automatic` attributes, preventing non-allowed attributes from being saved. **Deprecated. EOL Chef Infra Client 18 (April 2022)**: Use `allowed_automatic_attributes`. `blocked_automatic_attributes` A hash that blocks `automatic` attributes, preventing blocked attributes from being saved. `blocked_default_attributes` A hash that blocks `default` attributes, preventing block attributes from being saved. `blocked_normal_attributes` A hash that allows `automatic` attributes, preventing non-allowed attributes from being saved. `blocked_override_attributes` A hash that blocks `override` attributes, preventing blocked attributes from being saved. `cache_path` The home directory for the user that runs Chef Infra Client as a non-root user. `checksum_path` The location in which checksum files are stored. These are used to validate individual cookbook files, such as recipes. The checksum itself is stored in the Chef Infra Server database and is then compared to a file in the checksum path that has a filename identical to the checksum. `chef_guid` The node UUID used by Automate. Setting this allows the node UUID to be specified, and can be carried across instances of a node. `chef_license` Used to accept the Chef license. Can be set to `accept` or `accept-no-persist`, which persists the license acceptance to disk. If passed to versions where the license is not required this configuration option is a no-op. `chef_repo_path` The path to the chef-repo containing cookbooks and other files, such as environments or data bags, when running Chef Infra Client in local mode. `chef_server_url` The URL of the Chef Infra Server. For example: ``` https://localhost/organizations/ORG_NAME ``` `chef_zero.enabled` Enable chef-zero. This setting requires `local_mode` to be set to `true`. Default value: `true` if running in local-mode, otherwise `false`. `chef_zero.port` The port on which chef-zero is to listen. If specified as a range, Chef Infra Client will take the first available port in the range. For example `10,20,30` or `10000-20000`. Default value: `8889-9999`. `clear_gem_sources` Globally sets the default of the `clear_sources` property on the `gem_package` and `chef_gem` resources. Default value: `false`. `client_fork` Contain Chef Infra Client runs in a secondary process with dedicated RAM. When a Chef Infra Client run is complete, the RAM is returned to the master process. This setting helps ensure that a Chef Infra Client uses a steady amount of RAM over time because the master process does not run recipes. This setting also helps prevent memory leaks such as those that can be introduced by the code contained within a poorly designed cookbook. Default value: `true`. Set to `false` to disable running Chef Infra Client in fork node. Note Must be set to `false` up to Chef Client 13.11.3 to gather the standard return code offered by `exit_status true`. Later versions run as expected without changes to the configuration file. `client_key` The location of the file that contains the client key. Default value: `/etc/chef/client.pem`. `client_registration_retries` The number of times a Chef Infra Client will attempt to register with a Chef Infra Server. Default value: `5`. `client_d_dir` A directory that contains additional configuration files for Chef Infra Client. `cookbook_path` The sub-directory for Chef Infra Client cookbooks. This value can be a string or an array of file system locations, processed in the specified order. The last cookbook is considered to override local modifications. `cookbook_sync_threads` The number of helper threads available for parallel cookbook synchronization. Increasing this value **may** increase the frequency of gateway errors from the Chef Infra Server (503 and 504 errors). Decreasing this number reduces the frequency of gateway errors, if present. Default value: `10`. `data_bag_decrypt_minimum_version` The minimum required version of data bag encryption. Possible values: `1`, `2`, and `3`. It is recommended to use the default value of `3` for additional encrypted data bag security. `data_bag_path` The location from which a data bag is loaded. Default value: `/var/chef/data_bags`. `data_collector.server_url` The fully qualified URL to the data collector server API. `data_collector.token` The shared data collector security token. When configured, the token will be passed as an HTTP header named `x-data-collector-token` which the server can choose to accept or reject. `data_collector.mode` The Chef Infra Client mode in which the Data Collector will be enabled. Possible values: `:solo`, `:client`, or `:both`. The `:solo` value is used for Chef Infra Client operating in Chef Solo Mode or Chef Solo Legacy Mode. Default value: `both`. `data_collector.raise_on_failure` When enabled, Chef Infra Client raises an error if it cannot successfully POST to the data collector server. Default value: `false`. `default_attribute_blacklist` A hash that blocks `default` attributes, preventing block attributes from being saved. **Deprecated. EOL Chef Infra Client 18 (April 2022)**: Use `blocked_default_attributes`. `default_attribute_whitelist` A hash that allows `default` attributes, preventing non-allowed attributes from being saved. **Deprecated. EOL Chef Infra Client 18 (April 2022)**: Use `allowed_default_attributes`. `diff_disabled` Cause Chef Infra Client to create a diff when changes are made to a file. Default value: `false`. `diff_filesize_threshold` The maximum size (in bytes) of a file for which Chef Infra Client can create a diff. Default value: `10000000`. `diff_output_threshold` The maximum size (in bytes) of a diff file Chef Infra Client can create. Default value: `1000000`. `disable_event_logger` Enable or disable sending Chef Infra Client internal state events to the Microsoft Windows “Application” event log. Set to `false` to send events to the Microsoft Windows “Application” event log at the start and end of a Chef Infra Client run, and also if a Chef Infra Client run fails. Use `log_location` to set the destination of your Chef Infra Client logs to the Windows event log. Set to `true` to disable event logging. Default value: `false`. `enable_reporting` Cause Chef Infra Client to send run data to the Automate server. `enable_reporting_url_fatals` Cause a Chef Infra Client run to fail when run data cannot be sent to the Automate server (for any reason). `enable_selinux_file_permission_fixup` SELinux environments only. Cause Chef Infra Client to attempt to apply the correct file permissions to an updated file via the `restorecon` command. Set to `false` to prevent Chef Infra Client from attempting this action. `encrypted_data_bag_secret` The subdirectory in which encrypted data bag secrets are located. `enforce_default_paths` Turn on path sanity in resources that shellout so that expected paths like /sbin or /bin are added to the PATH. Disabled by default. `enforce_path_sanity` Turn on path sanity in resources that shellout so that expected paths like /sbin or /bin are added to the PATH. Disabled by default. **Deprecated. EOL Chef Infra Client 18 (April 2022)**: Use `enforce_default_paths`. `environment` The name of the Chef Infra environment. `environment_path` The path to the environment file. Default value: `/var/chef/environments`. `exit_status` When set to `:enabled`, Chef Infra Client will use [standardized exit codes](https://github.com/chef/chef/blob/main/docs/dev/design_documents/client_exit_codes.md#exit-codes-in-use) for the Chef Infra Client run status, and any non-standard exit codes will be converted to `1` or `GENERIC_FAILURE`. This setting can also be set to `:disabled` to use the pre-Chef Infra Client 13 exit code behavior. Default value: `nil`. `file_atomic_update` Apply atomic file updates to all resources. Set to `true` for global atomic file updates. Set to `false` for global non-atomic file updates. (Use the `atomic_update` setting on a per-resource basis to override this setting.) Default value: `true`. Warning Changing this setting to `false` may cause file corruption, data loss, or instability. Use the `atomic_update` property on the **cookbook_file**, **file**, **remote_file**, and **template** resources to tune this behavior at the recipe level. `file_backup_path` The location in which backup files are stored. If this value is empty, backup files are stored in the directory of the target file. Default value: `/var/chef/backup`. `file_cache_path` The location in which cookbooks (and other transient data) files are stored when they are synchronized. This value can also be used in recipes to download files with the **remote_file** resource. `file_staging_uses_destdir` How file staging (via temporary files) is done. When `true`, temporary files are created in the directory in which files will reside. When `false`, temporary files are created under `ENV['TMP']`. Default value: `true`. `fips` Allows OpenSSL to enforce FIPS-validated security during a Chef Infra Client run. Set to `true` to enable FIPS-validated security. `force_formatter` Using force_formatter causes chef to default to formatter output when STDOUT is not a tty `force_logger` Using force_logger causes chef to default to logger output when STDOUT is a tty `ftp_proxy` The proxy server for FTP connections. `ftp_proxy_pass` The password for the proxy server when the proxy server is using an FTP connection. Default value: `nil`. `ftp_proxy_user` The user name for the proxy server when the proxy server is using an FTP connection. Default value: `nil`. `group` The group that owns a process. This is required when starting any executable as a daemon. Default value: `nil`. `gem_installer_bundler_options` Additional options to pass to bundler when installing metadata for cookbook. Default value: `nil`. For example ``` gem_installer_bundler_options = [ "--local", "--clean" ] ``` or ``` gem_installer_bundler_options = "--local" ``` `http_proxy` The proxy server for HTTP connections. Default value: `nil`. `http_proxy_pass` The password for the proxy server when the proxy server is using a HTTP connection. Default value: `nil`. `http_proxy_user` The user name for the proxy server when the proxy server is using a HTTP connection. Default value: `nil`. `http_retry_count` The number of retry attempts. Default value: `5`. `http_retry_delay` The delay (in seconds) between retry attempts. Default value: `5`. `https_proxy` The proxy server for HTTPS connections. Default value: `nil`. `https_proxy_pass` The password for the proxy server when the proxy server is using a HTTPS connection. Default value: `nil`. `https_proxy_user` The user name for the proxy server when the proxy server is using a HTTPS connection. Default value: `nil`. `interval` The frequency (in seconds) at which Chef Infra Client runs when running in daemonized mode. We do not recommend running in daemonized mode. Instead you should rely on scheduled execution from system schedulers like systemd timers, cron jobs, or Windows Scheduled Tasks. Default value: `1800`. `json_attribs` The path to a file that contains JSON data. `listen` Run chef-zero in socketless mode. Set to `false` to disable port binding and HTTP requests on localhost. `local_key_generation` Whether the Chef Infra Server or Chef Infra Client generates the private/public key pair. When `true`, Chef Infra Client generates the key pair, and then sends the public key to the Chef Infra Server. Default value: `true`. `local_mode` Run Chef Infra Client in local mode. This allows all commands that work against the Chef Infra Server to also work against the local chef-repo. `lockfile` The location of the Chef Infra Client lock file. This value is typically platform dependent, so it should be a location defined by `file_cache_path`. The default location of a lock file should not be on an NFS mount. Default value: a location defined by `file_cache_path`. `log_level` The level of logging to be stored in a log file. Possible levels: `:auto` (default), `:trace`, `:debug`, `:info`, `:warn`, `:error`, or `:fatal`. The `:auto` level will use `:warn` when a terminal is available or `:info` when a terminal is not available. `log_location` The location of the log file. Possible values: `/path/to/log_location`, `STDOUT`, `STDERR`, `:win_evt` (Windows Event Logger), or `:syslog` (writes to the syslog daemon facility with the originator set as `chef-client`). The application log will specify the source as `Chef`. Default value: `STDOUT`. `minimal_ohai` Run a minimal set of Ohai plugins providing data necessary for the execution of Chef Infra Client’s built-in resources. Setting this to true will skip many large and time consuming plugins such as `cloud` or `packages`. Setting this to true may break cookbooks that assume all Ohai data will be present. `named_run_list` A specific named runlist defined in the node’s applied Policyfile which should be used when running Chef Infra Client. `no_lazy_load` Download all cookbook files and templates at the beginning of a Chef Infra Client run. Default value: `true`. `no_proxy` A comma-separated list of URLs that do not need a proxy. Default value: `nil`. `node_name` The unique identifier of the node. This determines which configuration should be applied and sets the `client_name`, which is the name used when authenticating to a Chef Infra Server. By default, Chef Infra Client will use the system’s FQDN as the node name. In general, Chef recommends that you leave this setting blank and let the client assign the FQDN of the node as the `node_name` during each Chef Infra Client run. `node_path` The location in which nodes are stored during a Chef Infra Client run in local mode. Default value: `/var/chef/node`. `normal_attribute_blacklist` A hash that blocks `normal` attributes, preventing blocked attributes from being saved. **Deprecated. EOL Chef Infra Client 18 (April 2022)**: Use `blocked_normal_attributes`. `override_attribute_blacklist` A hash that blocks `override` attributes, preventing blocked attributes from being saved. **Deprecated. EOL Chef Infra Client 18 (April 2022)**: Use `blocked_override_attributes`. `normal_attribute_whitelist` A hash that allows `normal` attributes, preventing non-allowed attributes from being saved. **Deprecated. EOL Chef Infra Client 18 (April 2022)**: Use `allowed_normal_attributes`. `override_normal_attributes` A hash that allows `override` attributes, preventing non-allowed attributes from being saved. `override_attribute_whitelist` A hash that allows `override` attributes, preventing non-allowed attributes from being saved. **Deprecated. EOL Chef Infra Client 18 (April 2022)**: Use `allowed_override_attributes`. `pid_file` The location in which a process identification number (pid) is saved. An executable, when started as a daemon, writes the pid to the specified file. Default value: `/tmp/name-of-executable.pid`. `policy_group` The name of a policy group that exists on the Chef Infra Server. `policy_name` must also be specified. `policy_group_path` The location of policy_groups on disk. `policy_name` The name of a policy, as identified by the `name` setting in a Policyfile.rb file. `policy_group` must also be specified. `policy_path` The location of policies on disk. `recipe_url` A URL to download recipes from when running in local mode. `rest_timeout` The time (in seconds) after which an HTTP REST request is to time out. Default value: `300`. `role_path` The location in which role files are located. Default value: `/var/chef/roles`. `rubygems_url` The location to source rubygems. It can be set to a string or array of strings for URIs to set as rubygems sources. This allows individuals to setup an internal mirror of rubygems for “airgapped” environments. Default value: `https://www.rubygems.org`. If a `source` is specified in either `gem_package` of `chef_gem` resources it will be added to the values provided here. `run_lock_timeout` The amount of time (in seconds) to wait for a Chef Infra Client lock file to be deleted. A Chef Infra Client run will not start when a lock file is present. If a lock file is not deleted before this time expires, the pending Chef Infra Client run will exit. Default value: not set (indefinite). Set to `0` to cause a second Chef Infra Client to exit immediately. `script_path` An array of paths to search for knife exec scripts if they aren’t in the current directory `skip_gem_metadata_installation` when `skip_gem_metadata_installation` is set to true, cookbook gem installation will be skipped. Default value: `false` `splay` A random number between zero and `splay` that is added to `interval`. Use splay to help balance the load on the Chef Infra Server by ensuring that many Chef Infra Client runs are not occurring at the same interval. Default value: `nil`. `stream_execute_output` Always stream the output of `execute` resources even if the `live_stream` property isn’t set to true. Default value: `false` `show_download_progress` Using show_download_progress will display the overall progress of a `remote_file` download. Default value: `false` `download_progress_interval` When `show_download_progress` is set to true this is the interval in seconds to write out download progress. Default value: `10` `ssl_ca_file` The file in which the OpenSSL key is saved. Chef Infra Client generates this setting automatically and most users do not need to modify it. `ssl_ca_path` The path to where the OpenSSL key is located. Chef Infra Client generates this setting automatically and most users do not need to modify it. `ssl_client_cert` The OpenSSL X.509 certificate used for mutual certificate validation. This setting is only necessary when mutual certificate validation is configured on the Chef Infra Server. Default value:`nil`. `ssl_client_key` The OpenSSL X.509 key used for mutual certificate validation. This setting is only necessary when mutual certificate validation is configured on the Chef Infra Server. Default value: `nil`. `ssl_verify_mode` Set the verify mode for HTTPS requests. * Use `:verify_none` for no validation of SSL certificates. * Use `:verify_peer` for validation of all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS **remote_file** resource URLs used in Chef Infra Client runs. This is the recommended setting. Depending on how OpenSSL is configured, the `ssl_ca_path` may nee to be specified. Default value: `:verify_peer`. `trusted_certs_dir` A directory that contains additional SSL certificates to trust. Any certificates in this directory will be added to whatever CA bundle ruby is using. Use this to add self-signed certs for your Chef Infra Server or local HTTP file servers. Default value: `trusted_certs` directory in your chef configuration directory. `umask` The file mode creation mask, or umask. Default value: `0022`. `use_policyfile` Chef Infra Client automatically checks the configuration, node JSON, and the stored node on the Chef Infra Server to determine if Policyfile files are in use, and then automatically updates this flag. Default value: `false`. `user` The user that owns a process. This is required when starting any executable as a daemon. Default value: `nil`. `validation_client_name` The name of the chef-validator key that Chef Infra Client uses to access the Chef Infra Server during the initial Chef Infra Client run. This is only used by the legacy validator based bootstrapping. `validation_key` The location of the file that contains the key used when a Chef Infra Client is registered with a Chef Infra Server. A validation key is signed using the `validation_client_name` for authentication. Default value: `/etc/chef/validation.pem`. This is only used by the legacy validator based bootstrapping. `verbose_logging` Set the log level. Options: `true`, `nil`, and `false`. When this is set to `false`, notifications about individual resources being processed are suppressed (and are output at the `:info` logging level). Setting this to `false` can be useful when a Chef Infra Client is run as a daemon. Default value: `nil`. `verify_api_cert` Verify the SSL certificate on the Chef Infra Server. When `true`, Chef Infra Client always verifies the SSL certificate. When `false`, Chef Infra Client uses the value of `ssl_verify_mode` to determine if the SSL certificate requires verification. Default value: `false`. A job entry may also be `'job-name' => {:lock => true}`, which will check the `lockfile` setting in the client.rb file before starting the job. ### Automatic Proxy Config If `http_proxy`, `https_proxy`, `ftp_proxy`, or `no_proxy` is set in the client.rb file but not set in the `ENV`, Chef Infra Client will configure the `ENV` variable based on these (and related) settings. For example: ``` http_proxy 'http://proxy.example.org:8080' http_proxy_user 'myself' http_proxy_pass 'Password1' ``` Or an alternative way to define the proxy (if the previous version does not work): ``` http_proxy 'http://myself:Password1@proxy.example.org:8080' ``` will be set to: ``` ENV['http_proxy'] = 'http://myself:Password1@proxy.example.org:8080' ``` .d Directories -------------- Chef Infra Client supports reading multiple configuration files by putting them inside a `.d` configuration directory. For example: `/etc/chef/client.d`. All files that end in `.rb` in the `.d` directory are loaded; other non-`.rb` files are ignored. `.d` directories may exist in any location where the `client.rb`, `config.rb`, or `solo.rb` files are present, such as: * `/etc/chef/client.d` * `/etc/chef/config.d` * `~/chef/solo.d` (There is no support for a `knife.d` directory; use `config.d` instead.) For example, when using knife, the following configuration files would be loaded: * `~/.chef/config.rb` * `~/.chef/config.d/company_settings.rb` * `~/.chef/config.d/ec2_configuration.rb` * `~/.chef/config.d/old_settings.rb.bak` The `old_settings.rb.bak` file is ignored because it’s not a configuration file. The `config.rb`, `company_settings.rb`, and `ec2_configuration` files are merged together as if they are a single configuration file. Note If multiple configuration files exists in a `.d` directory, ensure that the same setting has the same value in all files. Ohai Settings ------------- Ohai configuration settings can be added to the client.rb file. `ohai.directory` The directory in which Ohai plugins are located. `ohai.disabled_plugins` An array of Ohai plugins to be disabled on a node. The list of plugins included in Ohai can be found in the [ohai/lib/ohai/plugins](https://github.com/chef/ohai/tree/main/lib/ohai/plugins) source. For example, disabling a single plugin: ``` ohai.disabled_plugins = [ :MyPlugin ] ``` or disabling multiple plugins: ``` ohai.disabled_plugins = [ :MyPlugin, :MyPlugin2, :MyPlugin3 ] ``` When a plugin is disabled, the Chef Infra Client log file will contain entries similar to: ``` [2014-06-13T23:49:12+00:00] DEBUG: Skipping disabled plugin MyPlugin ``` `ohai.hints_path` The path to the file that contains hints for Ohai. `ohai.log_level` The level of logging to be stored in a log file. `ohai.log_location` The location of the log file. `ohai.plugin_path` An array of paths at which Ohai plugins are located. Default value: `[<CHEF_GEM_PATH>/ohai-9.9.9/lib/ohai/plugins]`. When custom Ohai plugins are added, the paths must be added to the array. For example, a single plugin: ``` ohai.plugin_path << '/etc/chef/ohai_plugins' ``` and for multiple plugins: ``` ohai.plugin_path += [ '/etc/chef/ohai_plugins', '/path/to/other/plugins' ] ``` Note The Ohai executable ignores settings in the client.rb file when Ohai is run independently of Chef Infra Client. Example ------- A sample client.rb file that contains the most simple way to connect to Hosted Chef ``` chef_server_url 'https://api.chef.io/organizations/<orgname>' validation_client_name '<orgname>-validator' validation_key '/etc/chef/validator.pem' client_key '/etc/chef/client.pem' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/config_rb_client/Bootstrap a Node ================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/install_bootstrap.md) A node is any physical, virtual, or cloud device that is configured and maintained by an instance of Chef Infra Client. Bootstrapping installs Chef Infra Client on a target system so that it can run as a client and sets the node up to communicate with a Chef Infra Server. There are two ways to do this: * Run the `knife bootstrap` command from a workstation. * Perform an unattended install to bootstrap from the node itself, without requiring SSH or WinRM connectivity. The following diagram shows the stages of the bootstrap operation, and the list below the diagram describes each of those stages in greater detail. ![image] During a `knife bootstrap` bootstrap operation, the following happens: | Stages | Description | | --- | --- | | **knife bootstrap** | Enter the `knife bootstrap` subcommand from a workstation. Include the hostname, IP address, or FQDN of the target node as part of this command. Knife will establish an SSH or WinRM connection with the target system and run a bootstrap script. | | **Get the install script from Chef** | The shell script will make a request to the Chef website to get the most recent version of a the Chef Infra Client install script(`install.sh` or `install.ps1`). | | **Get the Chef Infra Client package from Chef** | The install script then gathers system-specific information and determines the correct package for Chef Infra Client, and then downloads the appropriate package from `omnitruck-direct.chef.io`. | | **Install Chef Infra Client** | Chef Infra Client is installed on the target node using a system native package (.rpm, .msi, etc). | | **Start a Chef Infra Client run** | On UNIX and Linux-based machines: The second shell script executes the `chef-client` binary with a set of initial settings stored within `first-boot.json` on the node. `first-boot.json` is generated from the workstation as part of the initial `knife bootstrap` subcommand. On Microsoft Windows machines: The batch file that is derived from the windows-chef-client-msi.erb bootstrap template executes the `chef-client` binary with a set of initial settings stored within `first-boot.json` on the node. `first-boot.json` is generated from the workstation as part of the initial `knife bootstrap` subcommand. | | **Complete a Chef Infra Client run** | a Chef Infra Client run proceeds, using HTTPS (port 443), and registers the node with the Chef Infra Server. The first Chef Infra Client run, by default, contains an empty run-list. A [run-list can be specified](../workstation/knife_bootstrap/index) as part of the initial bootstrap operation using the `--run-list` option as part of the `knife bootstrap` subcommand. | knife bootstrap --------------- The `knife bootstrap` command is a common way to install Chef Infra Client on a node. The default for this approach assumes that a node can access the Chef website so that it may download the Chef Infra Client package from that location. The Chef Infra Client installer will detect the version of the operating system, and then install the appropriate Chef Infra Client version using a single command to install Chef Infra Client and all of its dependencies, including an embedded version of Ruby, OpenSSL, parsers, libraries, and command line utilities. The Chef Infra Client installer puts everything into a unique directory (`/opt/chef/`) so that Chef Infra Client will not interfere with other applications that may be running on the target machine. Once installed, Chef Infra Client requires a few more configuration steps before it can perform its first Chef Infra Client run on a node. ### Run the bootstrap command The `knife bootstrap` subcommand is used to run a bootstrap operation that installs Chef Infra Client on the target node. The following steps describe how to bootstrap a node using knife. 1. Identify the FQDN or IP address of the target node. The `knife bootstrap` command requires the FQDN or the IP address for the node in order to complete the bootstrap operation. 2. Once the workstation machine is configured, it can be used to install Chef Infra Client on one (or more) nodes across the organization using a knife bootstrap operation. The `knife bootstrap` command is used to SSH into the target machine, and then do what is needed to allow Chef Infra Client to run on the node. It will install the Chef Infra Client executable (if necessary), generate keys, and register the node with the Chef Infra Server. The bootstrap operation requires the IP address or FQDN of the target system, the SSH credentials (username, password or identity file) for an account that has root access to the node, and (if the operating system is not Ubuntu, which is the default distribution used by `knife bootstrap`) the operating system running on the target system. In a command window, enter the following: ``` knife bootstrap 172.16.1.233 -U USERNAME --sudo ``` where `172.16.1.233` is the IP address or the FQDN for the node, and `USERNAME` is the username you want to use to connect, and `--sudo` specifies to elevate privileges using the sudo command on UNIX-based systems. Then while the bootstrap operation is running, the command window will show something similar to the following: ``` Enter password for ubuntu@172.16.1.233: Connecting to 172.16.1.233 Performing legacy client registration with the validation key at /Users/USERNAME/.chef/validator.pem... Delete your validation key in order to use your user credentials for client registration instead. Bootstrapping 172.16.1.233 [172.16.1.233] -----> Installing Chef Omnibus (stable/16) downloading https://omnitruck.chef.io/chef/install.sh [172.16.1.233] to file /tmp/install.sh.1624/install.sh [172.16.1.233] trying wget... [172.16.1.233] ubuntu 20.04 aarch64 [172.16.1.233] Getting information for chef stable 16 for ubuntu... [172.16.1.233] downloading https://omnitruck.chef.io/stable/chef/metadata?v=16&p=ubuntu&pv=20.04&m=aarch64 to file /tmp/install.sh.1628/metadata.txt [172.16.1.233] trying wget... [172.16.1.233] sha1 8d89f8ac2e7f52d170be8ec1c2a028a6449d7e3a sha256 85cc73bed06e8d6699fc5c0b26c20d2837bf03831873444febccfc8bfa561f00 url https://packages.chef.io/files/stable/chef/16.1.16/ubuntu/20.04/chef_16.1.16-1_arm64.deb version 16.1.16 [172.16.1.233] [172.16.1.233] downloaded metadata file looks valid... [172.16.1.233] downloading https://packages.chef.io/files/stable/chef/16.1.16/ubuntu/20.04/chef_16.1.16-1_arm64.deb to file /tmp/install.sh.1628/chef_16.1.16-1_arm64.deb [172.16.1.233] trying wget... [172.16.1.233] Comparing checksum with sha256sum... [172.16.1.233] Installing chef 16 installing with dpkg... [172.16.1.233] Selecting previously unselected package chef. [172.16.1.233] (Reading database ... 99114 files and directories currently installed.) [172.16.1.233] Preparing to unpack .../chef_16.1.16-1_arm64.deb ... [172.16.1.233] Unpacking chef (16.1.16-1) ... [172.16.1.233] Setting up chef (16.1.16-1) ... [172.16.1.233] Thank you for installing Chef Infra Client! For help getting started visit https://learn.chef.io [172.16.1.233] Starting the first Chef Infra Client Client run... [172.16.1.233] +---------------------------------------------+ ✓ 2 product licenses accepted. +---------------------------------------------+ [172.16.1.233] Starting Chef Infra Client, version 16.1.16 [172.16.1.233] [2020-06-08T23:49:10+00:00] ERROR: shard_seed: Failed to get dmi property serial_number: is dmidecode installed? [172.16.1.233] Creating a new client identity for name_of_node using the validator key. [172.16.1.233] resolving cookbooks for run list: [] [172.16.1.233] Synchronizing Cookbooks: [172.16.1.233] Installing Cookbook Gems: [172.16.1.233] Compiling Cookbooks... [172.16.1.233] [2020-06-08T23:49:17+00:00] WARN: Node name_of_node has an empty run list. [172.16.1.233] Converging 0 resources [172.16.1.233] [172.16.1.233] Running handlers: [172.16.1.233] Running handlers complete [172.16.1.233] Chef Infra Client finished, 0/0 resources updated in 11 seconds ``` 3. After the bootstrap operation has finished, verify that the node is recognized by the Chef Infra Server. To show only the node that was just bootstrapped, run the following command: ``` knife client show NAME_OF_NODE ``` where `NODE_NAME` is the name of the node that was just bootstrapped. The Chef Infra Server will return something similar to: ``` admin: false chef_type: client name: NODE_NAME validator: false ``` and to show the full list of nodes (and workstations) that are registered with the Chef Infra Server, run the following command: ``` knife client list ``` The Chef Infra Server will return something similar to: ``` workstation1 workstation2 ... client1 client2 ``` Validatorless and Legacy Validator Bootstraps --------------------------------------------- We recommended using “validatorless bootstrapping” to authenticate new nodes with the Chef Infra Server. The legacy Chef Infra validator-based node bootstrapping process depended on using a shared “validatory” key throughout an organization for authenticating new nodes with the Chef Infra Server. Shortcomings of the legacy validator process are: * All users share the same key for bootstrapping new systems * Key sharing makes key rotation difficult, if it is compromised or if an employee leaves the organization. The “validatorless bootstrap” generates a key for each node, which is then transferred to the new node and used to authenticate with the Chef Infra Server instead of relying on a shared “validator” key. The Chef Infra bootstrap process is validatorless by default. If you receive a warning during a bootstrap that a validator key is in use, remove the configuration for this legacy bootstrap mode. Edit your [config.rb (knife.rb)](../workstation/config_rb/index) file and remove any `validation_key` or `validation_client_name` entries. Bootstrapping with chef-vault ----------------------------- Use the following options with a validatorless bootstrap to specify items that are stored in chef-vault: `--bootstrap-vault-file VAULT_FILE` The path to a JSON file that contains a list of vaults and items to be updated. `--bootstrap-vault-item VAULT_ITEM` A single vault and item to update as `vault:item`. `--bootstrap-vault-json VAULT_JSON` A JSON string that contains a list of vaults and items to be updated. –bootstrap-vault-json ‘{ “vault1”: [“item1”, “item2”], “vault2”: “item2” }’ Examples -------- The `--bootstrap-vault-*` options add the client identify of the bootstrapping node to the permissions list of the specified vault item. This enables the newly-bootstrapped Chef Infra Client to be able to read items from the vault. Only a single client is authorized at a time for access to the vault. (The `-S` search query option with the `knife vault create` subcommand does the same.) ### Recreate a data bag item The following example shows how to recreate a data bag item: ``` knife vault delete sea power Do you really want to delete sea/power? (Y/N) Y Deleted chef_vault_item[sea/power] echo "{\"some\":\"content for them\"}" > sea-power-content.json cat sea-power-content.json {"some":"content for them"} knife vault create sea power -M client -A sean_horn,angle -J sea-power-content.json ``` No clients, because the `-S` option was not specified while creating the vault. At this time, only the users `sean_horn` and `angle` are authorized to read and manage the vault. ``` knife vault show sea power --mode client -p all admins: sean_horn angle clients: id: power search_query: some: content for them ``` It is definitely an encrypted databag, see? ``` knife data_bag show sea power WARNING: Encrypted data bag detected, but no secret provided for decoding. Displaying encrypted data. id: power some: cipher: aes-256-cbc encrypted_data: c7Axnyg+1KDxBPOZdYN9QuIYx6dmSmK70unAQbn12Lygvsv2g9DPJJbueXVh +yxL iv: ONoVR7OjPZiAzaqOZ30bjg== version: 1 ``` ### Use –bootstrap-vault-file Use the `sea:power` recreation step above first, to follow the difference in the vault permissions. ``` echo "{\"sea\":\"power\"}" > sea-power-bootstrap-vault-file.json knife bootstrap localhost -p 2200 -N ubuntu-20.04 -r 'role[group1]' --connection-user vagrant --sudo --bootstrap-vault-file sea-power-bootstrap-vault-file.json Node ubuntu-20.04 exists, overwrite it? (Y/N) Y Client ubuntu-20.04 exists, overwrite it? (Y/N) Y Creating new client for ubuntu-20.04 Creating new node for ubuntu-20.04 Connecting to localhost localhost -----> Existing Chef installation detected localhost Starting first Chef Client run... localhost Starting Chef Client, version 12.2.1 localhost resolving cookbooks for run list: ["delay-test-reporting"] localhost Synchronizing Cookbooks: localhost - delay-test-reporting localhost Compiling Cookbooks... localhost Converging 1 resources localhost Recipe: delay-test-reporting::default localhost * execute[sleep 30] action run localhost - execute sleep 30 localhost localhost Running handlers: localhost Running handlers complete localhost Chef Client finished, 1/1 resources updated in 34.307257232 seconds ``` The client `ubuntu-20.04` was added to the `chef-vault` during the bootstrap. ``` knife vault show sea power --mode client -p all admins: sean_horn angle clients: ubuntu-20.04 id: power search_query: some: content for them ``` ### Use –bootstrap-vault-item Use the `sea:power` re-creation step above first, to follow the difference in the vault permissions. ``` knife bootstrap localhost -p 2200 -N ubuntu-20.04 -r 'role[group1]' --connection-user vagrant --sudo --bootstrap-vault-item sea:power Node ubuntu-20.04 exists, overwrite it? (Y/N) Y Client ubuntu-20.04 exists, overwrite it? (Y/N) Y Creating new client for ubuntu-20.04 Creating new node for ubuntu-20.04 Connecting to localhost localhost -----> Existing Chef installation detected localhost Starting first Chef Client run... localhost Starting Chef Client, version 12.2.1 localhost resolving cookbooks for run list: ["delay-test-reporting"] localhost Synchronizing Cookbooks: localhost - delay-test-reporting localhost Compiling Cookbooks... localhost Converging 1 resources localhost Recipe: delay-test-reporting::default localhost * execute[sleep 30] action run localhost - execute sleep 30 localhost localhost Running handlers: localhost Running handlers complete localhost Chef Client finished, 1/1 resources updated in 34.322229474 seconds ``` During the above run, the `sea:power` vault item was updated with the `ubuntu-20.04` client during the validatorless bootstrap. Previously, it only had the two admins authorized to view the content ``` knife vault show sea power -p all admins: sean_horn angle clients: ubuntu-20.04 id: power search_query: role:stuff some: secret stuff for them ``` Then, let’s check the `ubuntu-20.04` client. The client itself can decrypt and read the encrypted databag contents as well using the embedded knife CLI in the Chef Infra Client package. ``` sudo /opt/chef/bin/knife vault show sea power -c /etc/chef/client.rb -M client -p all admins: sean_horn angle clients: ubuntu-20.04 id: power search_query: role:group1 some: secret stuff for them ``` Success! The client is authorized to view the content of the `sea:power` databag item ### Use –bootstrap-vault-json Use the `sea:power` re-creation step above first, to follow the difference in the vault permissions. ``` knife bootstrap localhost -p 2200 -N ubuntu-20.04 -r 'role[group1]' --connection-user vagrant --sudo --bootstrap-vault-json '{"sea": "power"}' Node ubuntu-20.04 exists, overwrite it? (Y/N) Y Client ubuntu-20.04 exists, overwrite it? (Y/N) Y Creating new client for ubuntu-.04 Creating new node for ubuntu-20.04 Connecting to localhost localhost -----> Existing Chef installation detected localhost Starting first Chef Client run... localhost Starting Chef Client, version 12.2.1 localhost resolving cookbooks for run list: ["delay-test-reporting"] localhost Synchronizing Cookbooks: localhost - delay-test-reporting localhost Compiling Cookbooks... localhost Converging 1 resources localhost Recipe: delay-test-reporting::default localhost * execute[sleep 30] action run localhost - execute sleep 30 localhost localhost Running handlers: localhost Running handlers complete localhost Chef Client finished, 1/1 resources updated in 33.732784033 seconds ``` ``` knife vault show sea power -M client -p all admins: sean_horn angle clients: ubuntu-20.04 id: power search_query: some: content for them ``` Unattended Installs ------------------- Chef Infra Client can be installed using an unattended bootstrap. This allows Chef Infra Client to be installed from itself, without requiring SSH. For example, machines are often created using environments like AWS Auto Scaling, AWS CloudFormation, Rackspace Auto Scale, and PXE. In this scenario, using tooling for attended, single-machine installs like `knife bootstrap` or `knife CLOUD_PLUGIN create` is not practical because the machines are created automatically and someone cannot always be on-hand to initiate the bootstrap process. When Chef Infra Client is installed using an unattended bootstrap, remember that Chef Infra Client: * Must be able to authenticate to the Chef Infra Server * Must be able to configure a run-list * May require custom attributes, depending on the cookbooks that are being used * Must be able to access the chef-validator.pem so that it may create a new identity on the Chef Infra Server * Must have a unique node name; Chef Infra Client will use the FQDN for the host system by default When Chef Infra Client is installed using an unattended bootstrap, it may be built into an image that starts Chef Infra Client on boot, or installed using User Data or some other kind of post-deployment script. The type of image or User Data used depends on the platform on which the unattended bootstrap will take place. ### Bootstrapping with User Data The method used to inject a user data script into a server will vary depending on the infrastructure platform being used. For example, on AWS you can pass this data in as a text file using the command line tool. The following user data examples demonstrate the process of bootstrapping Windows and Linux nodes. #### PowerShell User Data ``` ## Set host file so the instance knows where to find chef-server $hosts = "1.2.3.4 hello.example.com" $file = "C:\Windows\System32\drivers\etc\hosts" $hosts | Add-Content $file ## Download the Chef Client $clientURL = "https://packages.chef.io/files/stable/chef/12.19.36/windows/2012/chef-client-<version-here>.msi" $clientDestination = "C:\chef-client.msi" Invoke-WebRequest $clientURL -OutFile $clientDestination ## Install the Chef Client Start-Process msiexec.exe -ArgumentList @('/qn', '/lv C:\Windows\Temp\chef-log.txt', '/i C:\chef-client.msi', 'ADDLOCAL="ChefClientFeature,ChefSchTaskFeature,ChefPSModuleFeature"') -Wait ## Create first-boot.json $firstboot = @{ "run_list" = @("role[base]") } Set-Content -Path c:\chef\first-boot.json -Value ($firstboot | ConvertTo-Json -Depth 10) ## Create client.rb $nodeName = "lab-win-{0}" -f (-join ((65..90) + (97..122) | Get-Random -Count 4 | % {[char]$_})) $clientrb = @" chef_server_url 'https://chef-server/organizations/my-org' validation_client_name 'validator' validation_key 'C:\chef\validator.pem' node_name '{0}' "@ -f $nodeName Set-Content -Path c:\chef\client.rb -Value $clientrb ## Run Chef C:\opscode\chef\bin\chef-client.bat -j C:\chef\first-boot.json ``` #### Bash User Data ``` #!/bin/bash -xev # Do some chef pre-work /bin/mkdir -p /etc/chef /bin/mkdir -p /var/lib/chef /bin/mkdir -p /var/log/chef # Setup hosts file correctly cat >> "/etc/hosts" << EOF 10.0.0.5 compliance-server compliance-server.automate.com 10.0.0.6 infra-server infra-server.automate.com 10.0.0.7 automate-server automate-server.automate.com EOF cd /etc/chef/ # Install chef curl -L https://omnitruck.chef.io/install.sh | bash || error_exit 'could not install chef' # Create first-boot.json cat > "/etc/chef/first-boot.json" << EOF { "run_list" :[ "role[base]" ] } EOF NODE_NAME=node-$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 4 | head -n 1) # Create client.rb cat > '/etc/chef/client.rb' << EOF log_location STDOUT chef_server_url 'https://aut-chef-server/organizations/my-org' validation_client_name 'my-org-validator' validation_key '/etc/chef/my_org_validator.pem' node_name "${NODE_NAME}" EOF chef-client -j /etc/chef/first-boot.json ``` It is important that settings in the [client.rb file](../config_rb_client/index)—`chef_server_url`, `http_proxy`, and so on are used—to ensure that configuration details are built into the unattended bootstrap process. ##### Setting the initial run-list A node’s initial run-list is specified using a JSON file on the host system. When running Chef Infra Client as an executable, use the `-j` option to tell Chef Infra Client which JSON file to use. For example: ``` chef-client -j /etc/chef/file.json --environment _default ``` where `file.json` is similar to: ``` { "resolver": { "nameservers": [ "10.0.0.1" ], "search":"int.example.com" }, "run_list": [ "recipe[resolver]" ] } ``` and where `_default` is the name of the environment that is assigned to the node. Warning This approach may be used to update [normal](../attributes#attribute-types) attributes, but should never be used to update any other attribute type, as all attributes updated using this option are treated as `normal` attributes. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/install_bootstrap/Upgrade Chef Infra Client ========================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/upgrade_client.md) The following sections describe the upgrade process for Chef Infra Client. If you are also [upgrading the Chef Infra Server](../server/upgrades/index) complete that process **first** and **then** upgrade the Chef Infra Client. Command Line Upgrades --------------------- To upgrade Chef Infra Client on a node from the command line, run the install script to install the latest Chef Infra Client release: Linux, macOS, and Unix-based hosts: ``` curl -L https://chef.io/chef/install.sh | sudo bash ``` Windows hosts: ``` . { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install ``` ### Specifying the Version to Install The install script accepts arguments to allow installing specific versions of Chef Infra Client on systems. Linux, macOS, and Unix-based hosts: ``` curl -L https://chef.io/chef/install.sh | sudo bash -s -- -v 17.9.26 ``` Windows hosts: ``` . { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install -version 17.9.26 ``` ### Upgrading Multiple Hosts with Knife The `knife ssh` command in Chef Workstation can be used to execute the install script on multiple Linux, macOS, and Unix-based hosts at once: ``` knife ssh 'name:*' 'curl -L https://chef.io/chef/install.sh | sudo bash' ``` Cookbook-Based Upgrade ---------------------- The [chef_client_updater](https://supermarket.chef.io/cookbooks/chef_client_updater) cookbook can be used to install or upgrade Chef Infra Client package on a node. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/upgrade_client/solo.rb ======= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/config_rb_solo.md) A solo.rb file is used to specify the configuration details for chef-solo. * This file is loaded every time this executable is run * The default location in which chef-solo expects to find this file is `/etc/chef/solo.rb`; use the `--config` option from the command line to change this location * This file is not created by default * When a `solo.rb` file is present in this directory, the settings contained within that file will override the default configuration settings Settings -------- This configuration file has the following settings: `add_formatter` A 3rd-party formatter. (See [nyan-cat](https://github.com/andreacampi/nyan-cat-chef-formatter) for an example of a 3rd-party formatter.) Each formatter requires its own entry. `checksum_path` The location in which checksum files are stored. These are used to validate individual cookbook files, such as recipes. The checksum itself is stored in the Chef Infra Server database and is then compared to a file in the checksum path that has a filename identical to the checksum. `cookbook_path` The Chef Infra Client sub-directory for cookbooks. This value can be a string or an array of file system locations, processed in the specified order. The last cookbook is considered to override local modifications. `data_bag_path` The location from which a data bag is loaded. Default value: `/var/chef/data_bags`. `environment` The name of the environment. `environment_path` The path to the environment. Default value: `/var/chef/environments`. `file_backup_path` The location in which backup files are stored. If this value is empty, backup files are stored in the directory of the target file. Default value: `/var/chef/backup`. `file_cache_path` The location in which cookbooks (and other transient data) files are stored when they are synchronized. This value can also be used in recipes to download files with the **remote_file** resource. `json_attribs` The path to a file that contains JSON data. `lockfile` The location of the Chef Infra Client lock file. This value is typically platform-dependent, so should be a location defined by `file_cache_path`. The default location of a lock file should not on an NF mount. Default value: a location defined by `file_cache_path`. `log_level` The level of logging to be stored in a log file. Possible levels: `:auto` (default), `debug`, `info`, `warn`, `error`, or `fatal`. `log_location` The location of the log file. Default value: `STDOUT`. `minimal_ohai` Run the Ohai plugins for name detection and resource/provider selection and no other Ohai plugins. Set to `true` during integration testing to speed up test cycles. `node_name` The unique identifier of the node. `recipe_url` The URL location from which a remote cookbook tar.gz is to be downloaded. `rest_timeout` The time (in seconds) after which an HTTP REST request is to time out. Default value: `300`. `role_path` The location in which role files are located. Default value: `/var/chef/roles`. `run_lock_timeout` The amount of time (in seconds) to wait for a Chef Infra Client lock file to be deleted. A Chef Infra Client run will not start when a lock file is present. If a lock file is not deleted before this time expires, the pending Chef Infra Client run will exit. Default value: not set (indefinite). Set to `0` to cause a second Chef Infra Client to exit immediately. `sandbox_path` The location in which cookbook files are stored (temporarily) during upload. `solo` Run Chef Infra Client in chef-solo mode. This setting determines if Chef Infra Client is to attempt to communicate with the Chef Infra Server. Default value: `false`. `syntax_check_cache_path` All files in a cookbook must contain valid Ruby syntax. Use this setting to specify the location in which knife caches information about files that have been checked for valid Ruby syntax. `umask` The file mode creation mask, or umask. Default value: `0022`. `verbose_logging` Set the log level. Options: `true`, `nil`, and `false`. When this is set to `false`, notifications about individual resources being processed are suppressed (and are output at the `:info` logging level). Setting this to `false` can be useful when a Chef Infra Client is run as a daemon. Default value: `nil`. Examples -------- ### Using Chef Automate Data Collector This example solo.rb file uses the `data_collector` settings to send data to an available Chef Automate system. Since Chef Automate generates a self-signed SSL certificate by default, you will need to add the certificate (located under `/var/opt/delivery/nginx/` on the Chef Automate server) to your `trusted_certs_dir` directory, as seen in this example: ``` chef_server_url "https://localhost:8989" log_location STDOUT node_name "YOUR_NODES_FQDN" trusted_certs_dir "/etc/chef/trusted_certs" data_collector.server_url "https://YOUR_AUTOMATE_FQDN/data-collector/v0" data_collector.mode :both data_collector.token = "YOURTOKEN" ``` You can run it like this ``` chef-solo -c solo.rb ``` ### All Options A sample solo.rb file that contains all possible settings (listed alphabetically): ``` add_formatter :nyan add_formatter :foo add_formatter :bar checksum_path '/var/chef/checksums' cookbook_path [ '/var/chef/cookbooks', '/var/chef/site-cookbooks' ] data_bag_path '/var/chef/data_bags' environment 'production' environment_path '/var/chef/environments' file_backup_path '/var/chef/backup' file_cache_path '/var/chef/cache' json_attribs nil lockfile nil log_level :info log_location STDOUT node_name 'mynode.example.com' recipe_url 'http://path/to/remote/cookbook' rest_timeout 300 role_path '/var/chef/roles' sandbox_path 'path_to_folder' solo false syntax_check_cache_path umask 0022 verbose_logging nil ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/config_rb_solo/Uninstall ========= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/uninstall.md) The following sections describe how to uninstall Chef, add-ons, and other components. Chef Infra Server ----------------- The `uninstall` subcommand is used to remove the Chef Infra Server application, but without removing any of the data. This subcommand will shut down all services (including the `runit` process supervisor). This subcommand has the following syntax: ``` chef-server-ctl uninstall ``` Note To revert the `uninstall` subcommand, run the `reconfigure` subcommand (because the `start` subcommand is disabled by the `uninstall` command). Chef Manage ----------- To uninstall the Chef management console, do the following: 1. Run the following command: ``` chef-manage-ctl cleanse ``` 2. Use the package manager for the platform on which the Chef management console is installed, and then uninstall the package named `chef-manage`. Note This package used to be named `opscode-manage` and the command line tool used to be named `opscode-manage-ctl`. Chef Analytics -------------- The `uninstall` subcommand is used to remove the Chef Analytics application, but without removing any of the data. This subcommand will shut down all services (including the `runit` process supervisor). This subcommand has the following syntax: ``` opscode-analytics-ctl uninstall ``` Note To revert the `uninstall` subcommand, run the `reconfigure` subcommand (because the `start` subcommand is disabled by the `uninstall` command). Reporting --------- The `uninstall` subcommand is used to remove the Reporting add-on to the Chef Infra Server, but without removing any of the data. This subcommand will shut down all services (including the `runit` process supervisor). This subcommand has the following syntax: ``` opscode-reporting-ctl uninstall ``` Note To revert the `uninstall` subcommand, run the `reconfigure` subcommand (because the `start` subcommand is disabled by the `uninstall` command). Chef Workstation ---------------- Chef Workstation can be uninstalled using the steps below that are appropriate for the platform on which Chef Workstation is installed. ### Debian Use the following command to remove Chef Workstation on Debian-based platforms: ``` dpkg -P chef-workstation ``` ### macOS Use the following commands to remove Chef Workstation on macOS. To remove installed files: ``` sudo rm -rf /opt/chef-workstation ``` To remove the system installation entry: ``` sudo pkgutil --forget com.getchef.pkg.chef-workstation ``` To remove symlinks: > ``` > sudo find /usr/local/bin -lname '`/opt/chef-workstation/*' -delete > ``` ### Red Hat Enterprise Linux Use the following commands to remove Chef Workstation on Red Hat Enterprise Linux-based platforms: ``` rpm -qa *chef-workstation* sudo yum remove -y <package``` ### Microsoft Windows Use **Add / Remove Programs** to remove Chef Workstation on the Microsoft Windows platform. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/uninstall/chef-solo ========= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_solo.md) chef-solo is a command that executes Chef Infra Client in a way that does not require the Chef Infra Server in order to converge cookbooks. chef-solo uses Chef Infra Client’s [Chef local mode](../ctl_chef_client#run-in-local-mode), and **does not support** the following functionality present in Chef Infra Client / server configurations: * Centralized distribution of cookbooks * A centralized API that interacts with and integrates infrastructure components * Authentication or authorization Note chef-solo can be run as a daemon. The chef-solo executable is run as a command-line tool. Cookbooks --------- chef-solo supports two locations from which cookbooks can be run: * A local directory. * A URL at which a tar.gz archive is located. Using a tar.gz archive is the more common approach, but requires that cookbooks be added to an archive. For example: ``` tar zcvf chef-solo.tar.gz ./cookbooks ``` If multiple cookbook directories are being used, chef-solo expects the tar.gz archive to have a directory structure similar to the following: ``` cookbooks/ |---- cbname1/ |--attributes/ ... etc ... |---- cbname2/ |--attributes/ ``` The `cookbook_path` variable in the solo.rb file must include both directories. For example: ``` tar zcvf chef-solo.tar.gz ./cookbooks ./site-cookbooks ``` When the tar.gz archive contains all of the cookbooks required by chef-solo, upload it to the web server from which chef-solo will access the archive. Nodes ----- Unlike Chef Infra Client, where the node object is stored on the Chef Infra Server, chef-solo stores its node objects as JSON files on local disk. By default, chef-solo stores these files in a `nodes` folder in the same directory as your `cookbooks` directory. You can control the location of this directory via the `node_path` value in your configuration file. Attributes ---------- chef-solo does not interact with the Chef Infra Server. Consequently, node-specific attributes must be located in a JSON file on the target system, a remote location (such as Amazon Simple Storage Service (S3)), or a web server on the local network. The JSON file must also specify the recipes that are part of the run-list. For example: ``` { "resolver": { "nameservers": [ "10.0.0.1" ], "search":"int.example.com" }, "run_list": [ "recipe[resolver]" ] } ``` Data Bags --------- A data bag is defined using JSON. chef-solo will look for data bags in `/var/chef/data_bags`, but this location can be modified by changing the setting in solo.rb. For example, the following setting in solo.rb: ``` data_bag_path '/var/chef-solo/data_bags' ``` Create a data bag by creating folders. For example: ``` mkdir /var/chef-solo/data_bags ``` and: ``` mkdir /var/chef-solo/data_bags/admins ``` and then create a JSON file in that location: ``` { "id": "ITEM_NAME" } ``` where the name of the file is the `ITEM_NAME`, for example: ``` /var/chef-solo/data_bags/admins/ITEM_NAME.json ``` Roles ----- A role is defined using JSON or the Ruby DSL. chef-solo will look for roles in `/var/chef/roles`, but this location can be modified by changing the setting for `role_path` in solo.rb. For example, the following setting in solo.rb: ``` role_path '/var/chef-solo/roles' ``` Role data looks like the following in JSON: ``` { "name": "test", "default_attributes": { }, "override_attributes": { }, "json_class": "Chef::Role", "description": "This is just a test role, no big deal.", "chef_type": "role", "run_list": [ "recipe[test]" ] } ``` and like the following in the Ruby DSL: ``` name 'test' description 'This is just a test role, no big deal.' run_list 'recipe[test]' ``` and finally, JSON data passed to chef-solo: ``` { 'run_list': 'role[test]' } ``` Environments ------------ An environment is defined using JSON or the Ruby DSL. chef-solo will look for environments in `/var/chef/environments`, but this location can be modified by changing the setting for `environment_path` in solo.rb. For example, the following setting in solo.rb: ``` environment_path '/var/chef-solo/environments' ``` Environment data looks like the following in JSON: ``` { "name": "dev", "default_attributes": { "apache2": { "listen_ports": [ "80", "443" ] } }, "json_class": "Chef::Environment", "description": "", "cookbook_versions": { "couchdb": "= 11.0.0" }, "chef_type": "environment" } ``` and like the following in the Ruby DSL: ``` name 'environment_name' description 'environment_description' cookbook OR cookbook_versions 'cookbook' OR 'cookbook' => 'cookbook_version' default_attributes 'node' => { 'attribute' => %w(value value etc.) } override_attributes 'node' => { 'attribute' => %w(value value etc.) } ``` chef-solo (executable) ---------------------- See [chef-solo (executable)](../ctl_chef_solo/index) for complete CTL documentation. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_solo/chef-solo (executable) ====================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/ctl_chef_solo.md) chef-solo is a command that executes Chef Infra Client in a way that does not require the Chef Infra Server in order to converge cookbooks. chef-solo uses Chef Infra Client’s [Chef local mode](../ctl_chef_client#run-in-local-mode), and **does not support** the following functionality present in Chef Infra Client / server configurations: * Centralized distribution of cookbooks * A centralized API that interacts with and integrates infrastructure components * Authentication or authorization Note chef-solo can be run as a daemon. The chef-solo executable is run as a command-line tool. Options ------- This command has the following syntax: ``` chef-solo OPTION VALUE OPTION VALUE ... ``` This command has the following options: `-c CONFIG`, `--config CONFIG` The configuration file to use. `-d`, `--daemonize` Run the executable as a daemon. This option may not be used in the same command with the `--[no-]fork` option. This option is only available on machines that run in UNIX or Linux environments. For machines that are running Microsoft Windows that require similar functionality, use the `chef-client::service` recipe in the `chef-client` cookbook: <https://supermarket.chef.io/cookbooks/chef-client>. This will install a Chef Infra Client service under Microsoft Windows using the Windows Service Wrapper. `-E ENVIRONMENT_NAME`, `--environment ENVIRONMENT_NAME` The name of the environment. `-f`, `--[no-]fork` Contains Chef Infra Client runs in a secondary process with dedicated RAM. When a Chef Infra Client run is complete, the RAM is returned to the master process. This option helps ensure that a Chef Infra Client uses a steady amount of RAM over time because the master process does not run recipes. This option also helps prevent memory leaks such as those that can be introduced by the code contained within a poorly designed cookbook. Use `--no-fork` to disable running Chef Infra Client in fork node. Default value: `--fork`. This option may not be used in the same command with the `--daemonize` and `--interval` options. `-F FORMAT`, `--format FORMAT` The output format: `doc` (default) or `min`. * Use `doc` to print the progress of a Chef Infra Client run using full strings that display a summary of updates as they occur. * Use `min` to print the progress of a Chef Infra Client run using single characters. A summary of updates is printed at the end of a Chef Infra Client run. A dot (`.`) is printed for events that do not have meaningful status information, such as loading a file or synchronizing a cookbook. For resources, a dot (`.`) is printed when the resource is up to date, an `S` is printed when the resource is skipped by `not_if` or `only_if`, and a `U` is printed when the resource is updated. Other formatting options are available when those formatters are configured in the client.rb file using the `add_formatter` option. `--force-formatter` Show formatter output instead of logger output. `--force-logger` Show logger output instead of formatter output. `-g GROUP`, `--group GROUP` The name of the group that owns a process. This is required when starting any executable as a daemon. `-h`, `--help` Show help for the command. `-i SECONDS`, `--interval SECONDS` The frequency (in seconds) at which Chef Infra Client runs. When running Chef Infra Client at intervals, apply `--splay` and `--interval` values before a Chef Infra Client run. This option may not be used in the same command with the `--[no-]fork` option. `-j PATH`, `--json-attributes PATH` The path to a file that contains JSON data. Use this option to define a `run_list` object. For example, a JSON file similar to: ``` "run_list": [ "recipe[base]", "recipe[foo]", "recipe[bar]", "role[webserver]" ], ``` may be used by running `chef-client -j path/to/file.json`. In certain situations this option may be used to update `normal` attributes. Warning Any other attribute type that is contained in this JSON file will be treated as a `normal` attribute. Setting attributes at other precedence levels is not possible. For example, attempting to update `override` attributes using the `-j` option: ``` { "name": "dev-99", "description": "Install some stuff", "override_attributes": { "apptastic": { "enable_apptastic": "false", "apptastic_tier_name": "dev-99.bomb.com" } } } ``` will result in a node object similar to: ``` { "name": "maybe-dev-99", "normal": { "name": "dev-99", "description": "Install some stuff", "override_attributes": { "apptastic": { "enable_apptastic": "false", "apptastic_tier_name": "dev-99.bomb.com" } } } } ``` `-l LEVEL`, `--log_level LEVEL` The level of logging to be stored in a log file. Possible levels: `auto` (default), `debug`, `error`, `fatal`, `info`, `trace`, or `warn`. Default value: `warn` (when a terminal is available) or `info` (when a terminal is not available). `-L LOGLOCATION`, `--logfile c` The location of the log file. This is recommended when starting any executable as a daemon. `--legacy-mode` Cause Chef Infra Client to use the original chef-solo mode instead of chef local mode. This is not recommended. **Removed in Chef Client 14.** `--minimal-ohai` Run the Ohai plugins for name detection and resource/provider selection and no other Ohai plugins. Set to `true` during integration testing to speed up test cycles. `--[no-]color` View colored output. Default setting: `--color`. `-N NODE_NAME`, `--node-name NODE_NAME` The unique identifier of the node. `-o RUN_LIST_ITEM`, `--override-runlist RUN_LIST_ITEM` Replace the current run-list with the specified items. `-r RECIPE_URL`, `--recipe-url RECIPE_URL` The URL of the remote cookbook `tar.gz` file that you want to download. In Chef Client 14, the short `-r` form will be removed, as it conflicts with the ability to specify a run list. `--run-lock-timeout SECONDS` The amount of time (in seconds) to wait for a Chef Infra Client lock file to be deleted. Default value: not set (indefinite). Set to `0` to cause a second Chef Infra Client to exit immediately. `-s SECONDS`, `--splay SECONDS` A random number between zero and `splay` that is added to `interval`. Use splay to help balance the load on the Chef Infra Server by ensuring that many Chef Infra Client runs are not occurring at the same interval. When running Chef Infra Client at intervals, apply `--splay` and `--interval` values before a Chef Infra Client run. `-u USER`, `--user USER` The user that owns a process. This is required when starting any executable as a daemon. `-v`, `--version` The Chef Infra Client version. `-W`, `--why-run` Run the executable in why-run mode, which is a type of Chef Infra Client run that does everything except modify the system. Use why-run mode to understand the decisions that Chef Infra Client makes during a run and to learn more about the current and proposed state of the system. Run as Non-root User -------------------- Warning This configuration for the `chef` user provides root-level access through Chef script files that call system commands with `sudo` privileges. Use an alternative approach if your security profile forbids the `chef` user from having built-in root level access. chef-solo may be run as a non-root user. For example, you can update the `sudoers` file: ``` # chef-solo privilege specification chef ALL=(ALL) NOPASSWD: /usr/bin/chef-solo ``` where `chef` is the name of the non-root user. This would allow chef-solo to run any command on the node without requiring a password. Examples -------- ### Run chef-solo using solo.rb settings ``` chef-solo -c ~/chef/solo.rb ``` ### Use a URL ``` chef-solo -c ~/solo.rb -j ~/node.json -r http://www.example.com/chef-solo.tar.gz ``` The tar.gz is archived into the `file_cache_path`, and then extracted to `cookbooks_path`. ### Use a directory ``` chef-solo -c ~/solo.rb -j ~/node.json ``` chef-solo will look in the `solo.rb` file to determine the directory in which cookbooks are located. ### Use a URL for cookbook and JSON data ``` chef-solo -c ~/solo.rb -j http://www.example.com/node.json --recipe-url http://www.example.com/chef-solo.tar.gz ``` where `--recipe-url` corresponds to `recipe_url` and `-j` corresponds to `json_attribs`, both of which are [configuration options](../config_rb_solo/index) in `solo.rb`. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ctl_chef_solo/Install Chef in an air-gapped environment ========================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/install_chef_air_gap.md) This guide will show you how to run a fully functional Chef environment within an [air-gapped](https://en.wikipedia.org/wiki/Air_gap_(networking)) network. Prerequisites ------------- Since a variety of different practices are used to create an air-gapped network, this guide focuses solely on the implementation of Chef software - as such, it makes the following assumptions: * You have a way to get packages to your air-gapped machines * Machines on your air-gapped network are able to resolve each other via DNS * A server’s Fully Qualified Domain Name (FQDN) is the name that will be used by other servers to access it * You have a private Ruby gem mirror to supply gems as needed * You have an artifact store for file downloads. At a minimum, it should have the following packages available: + Chef Workstation + Chef Infra Client + Chef Supermarket + An [install script](index#create-an-install-script) for Chef Infra Client ### Required cookbooks This guide will link to the required cookbooks for each piece of software in that software’s respective section, but this is a full list of the cookbooks required to complete the entire guide: For Chef Supermarket: * [supermarket-omnibus-cookbook](https://supermarket.chef.io/cookbooks/supermarket-omnibus-cookbook) * [chef-ingredient](https://supermarket.chef.io/cookbooks/chef-ingredient) * [hostsfile](https://supermarket.chef.io/cookbooks/hostsfile) ### Required Gems The following Ruby gems are required to install private Supermarket via the supermarket-omnibus-cookbook: * mixlib-install * mixlib-shellout * mixlib-versioning * artifactory These should be accessible from your Gem mirror. ### Create an install script An install script is used to install Chef Infra Client when bootstrapping a new node. It simply pulls the Chef Infra Client package from your artifact store, and then installs it. For example, on Debian-based Linux systems, it would look similar to this: ``` #!/bin/bash cd /tmp/ wget http://packages.example.com/chef_13.2.20-1_amd64.deb dpkg -i chef_13.2.20-1_amd64.deb ``` The install script should be accessible from your artifact store. Chef Infra Server ----------------- In this section you’ll install the Chef Infra Server, and create your organization and user. Note that in order to configure Supermarket later in this guide, you will need a user that is a member of the `admins` group. 1. Download the package from <https://www.chef.io/downloads/tools/infra-server>. 2. Upload the package to the machine that will run the Chef Infra Server, and then record its location on the file system. The rest of these steps assume this location is in the `/tmp` directory. 3. As a root user, install the Chef Infra Server package on the server, using the name of the package provided by Chef. For Red Hat Enterprise Linux and CentOS: ``` sudo rpm -Uvh /tmp/chef-server-core-<version>.rpm ``` For Ubuntu: ``` sudo dpkg -i /tmp/chef-server-core-<version>.deb ``` After a few minutes, the Chef Infra Server will be installed. 4. Run the following to start all of the services: ``` sudo chef-server-ctl reconfigure ``` Because the Chef Infra Server is composed of many different services that work together to create a functioning system, this step may take a few minutes to complete. 5. Run the following command to create an administrator: ``` sudo chef-server-ctl user-create USER_NAME FIRST_NAME LAST_NAME EMAIL 'PASSWORD' --filename FILE_NAME ``` An RSA private key is generated automatically. This is the user’s private key and should be saved to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. For example: ``` sudo chef-server-ctl user-create janedoe <NAME> <EMAIL> 'abc123' --filename /path/to/janedoe.pem ``` 6. Run the following command to create an organization: ``` sudo chef-server-ctl org-create short_name 'full_organization_name' --association_user user_name --filename ORGANIZATION-validator.pem ``` For example: ``` sudo chef-server-ctl org-create 4thcafe 'Fourth Cafe, Inc.' --association_user janedoe --filename /path/to/4thcafe-validator.pem ``` The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `4thcafe`. The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `'Fourth Cafe, Inc.'`. The `--association_user` option will associate the `user_name` with the `admins` security group on the Chef Infra Server. An RSA private key is generated automatically. This is the chef-validator key and should be saved to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. Chef Workstation ---------------- ### Install Chef Workstation 1. First, install the Chef Workstation [installer package](https://www.chef.io/downloads/tools/workstation). Use the appropriate tool to run the installer: ``` dpkg -i chef-workstation_0.14.16-1_amd64.deb ``` 2. Use the `chef generate repo` command to generate your Chef repo: ``` chef generate repo chef-repo ``` 3. Within your Chef repo, create a `.chef` directory: ``` mkdir /chef-repo/.chef ``` 4. Copy the `USER.pem` and `ORGANIZATION.pem` files from the server, and move them into the `.chef` directory. ``` scp ssh-user@chef-server.example.com:/path/to/pem/files /chef-repo/.chef/ ``` ### Create a bootstrap template By default, `knife bootstrap` uses the `chef-full` template to bootstrap a node. This template contains a number of useful features, but it also attempts to pull an installation script from `packages.chef.io`. In this section, you’ll copy the contents of the `chef-full` template to a custom template, and then modify the package and Ruby gem sources. 1. Navigate to the `.chef` directory, and create a `bootstrap` directory within it: ``` mkdir bootstrap ``` 2. Move to the `bootstrap` directory and create a blank template file; this example will use `airgap.erb` for the template name: ``` touch airgap.erb ``` 3. Still in the `bootstrap` directory, issue the following command to copy the `chef-full` configuration to your new template: ``` find /opt/chef-workstation/embedded/lib/ruby -type f -name chef-full.erb -exec cat {} \; > airgap.erb ``` This command searches for the `chef-full` template file under `/opt/chef-workstation/embedded/lib/ruby`, and then outputs the contents of the file to `airgap.erb`. If you used a different template file name, be sure to replace `airgap.erb` with the template file you created during the last step. 4. Update `airgap.erb` to replace `omnitruck.chef.io` with the URL of `install.sh` on your artifact store: ``` install_sh="<%= knife_config[:bootstrap_url] ? knife_config[:bootstrap_url] : "http://packages.example.com/install.sh" %>" ``` 5. Still in your text editor, locate the following line near the bottom of your `airgap.erb` file: ``` cat > /etc/chef/client.rb <<'EOP' <%= config_content %> EOP ``` Beneath it, add the following, replacing `gems.example.com` with the URL of your gem mirror: ``` cat >> /etc/chef/client.rb <<'EOP' rubygems_url "http://gems.example.com" EOP ``` This appends the appropriate `rubygems_url` setting to the `/etc/chef/client.rb` file that is created during bootstrap, which ensures that your nodes use your internal gem mirror. ### Configure knife Within the `.chef` directory, create a `config.rb` file and replace `USER` and `ORGANIZATION` with the user and organization that you created on your Chef Infra Server; replace `chef-server.example.com` with your Chef Infra Server URL: ``` current_dir = File.dirname(__FILE__) node_name 'USER' client_key "#{current_dir}/USER.pem" validation_client_name 'ORGANIZATION-validator' validation_key "#{current_dir}/ORGANIZATION.pem" chef_server_url 'https://chef-server.example.com/organizations/ORGANIZATION' cookbook_path ["#{current_dir}/../cookbooks"] knife[:bootstrap_template] = "#{current_dir}/bootstrap/airgap.erb" ``` The `knife[:bootstrap_template]` option in this example allows you to specify the template that `knife bootstrap` will use by default when bootstrapping a node. It should point to your custom template within the `bootstrap` directory. Now that `knife` is configured, copy the SSL certificates from your Chef Infra Server to your trusted certificates: ``` knife ssl fetch ``` Private Supermarket ------------------- Private Supermarket allows you to host your own internal version of the [Chef Supermarket](https://supermarket.chef.io) within your air-gapped network. ### Requirements In this section, you will use a wrapper around the [supermarket-omnibus-cookbook](https://supermarket.chef.io/cookbooks/supermarket-omnibus-cookbook) to install private Supermarket. The Supermarket cookbook depends upon the following cookbooks: * [chef-ingredient](https://supermarket.chef.io/cookbooks/chef-ingredient) * [hostsfile](https://supermarket.chef.io/cookbooks/hostsfile) The following Gems must be accessible via your Gem mirror: * mixlib-install * mixlib-shellout * mixlib-versioning * artifactory Your `cookbooks` directory must have all three of these cookbooks installed before you will be able to use the Supermarket cookbook wrapper. In addition the necessary cookbooks, a private Chef Supermarket has the following requirements: * An operational Chef Infra Server to act as the OAuth 2.0 provider * A user account on the Chef Infra Server with `admins` privileges * A key for the user account on the Chef server * An x86_64 Ubuntu, RHEL, or Amazon Linux host with at least 1 GB memory * System clocks synchronized on the Chef Infra Server and Supermarket hosts * Sufficient disk space to meet project cookbook storage capacity or credentials to store cookbooks in an Amazon Simple Storage Service (S3) bucket ### Configure credentials First, you’ll configure Chef Identity credentials for Supermarket. Chef Identity is an OAuth 2.0 service packaged with the Chef Infra Server, that allows you to use the same credentials to access both server and Supermarket. 1. Log on to the Chef Infra Server via SSH and elevate to an admin-level user. If running a multi-node Chef Infra Server cluster, log on to the node acting as the primary node in the cluster. 2. Update the `/etc/opscode/chef-server.rb` configuration file. To define OAuth 2 information for Chef Supermarket, create a Hash similar to: ``` oc_id['applications'] ||= {} oc_id['applications']['supermarket'] = { 'redirect_uri' => 'https://supermarket.mycompany.com/auth/chef_oauth2/callback', } ``` 3. Reconfigure the Chef Infra Server. ``` sudo chef-server-ctl reconfigure ``` 4. Retrieve Supermarket’s OAuth 2.0 client credentials: Depending on your Chef Infra Server version and configuration (see [chef-server.rb](../server/config_rb_server_optional_settings/index#config-rb-server-insecure-addon-compat)), this can be retrieved via [chef-server-ctl oc-id-show-app supermarket](../ctl_chef_server/index#ctl-chef-server-oc-id-show-app) or is located in `/etc/opscode/oc-id-applications/supermarket.json`: ``` { "name": "supermarket", "uid": "0bad0f2eb04e935718e081fb71asdfec3681c81acb9968a8e1e32451d08b", "secret": "17cf1141cc971a10ce307611beda7ffadstr4f1bc98d9f9ca76b9b127879", "redirect_uri": "https://supermarket.mycompany.com/auth/chef_oauth2/callback" } ``` ### Create a Wrapper 1. Generate the cookbook: ``` chef generate cookbook my_supermarket_wrapper ``` 2. Change directories into that cookbook: ``` cd my_supermarket_wrapper ``` 3. Defines the wrapper cookbook’s dependency on the `supermarket-omnibus-cookbook` cookbook. Open the `metadata.rb` file of the newly-created cookbook, and then add the following line: ``` depends 'supermarket-omnibus-cookbook' ``` 4. Save and close the `metadata.rb` file. 5. Open the `/recipes/default.rb` recipe located within the newly-generated cookbook and add the following content: ``` include_recipe 'supermarket-omnibus-cookbook' ``` This ensures that the `default.rb` file in the `supermarket-omnibus-cookbook` is run. ### Define Attributes Define the attributes for the Chef Supermarket installation and how it connects to the Chef Infra Server. One approach would be to hard-code attributes in the wrapper cookbook’s `default.rb` recipe. A better approach is to place these attributes in a [data bag](../data_bags/index), and then reference them from the recipe. For example, the data bag could be named `apps` and then a data bag item within the data bag could be named `supermarket`. The following attributes are required: * `chef_server_url`: the url for your chef server. * `chef_oauth2_app_id`: the Chef Identity uid from `/etc/opscode/oc-id-applications/supermarket.json` * `chef_oauth2_secret`: The Chef Identity secret from `/etc/opscode/oc-id-applications/supermarket.json` * `package_url`: The location of the Supermarket package on your artifact store To define these attributes, do the following: 1. Open the `recipes/default.rb` file and add the following, **before** the `include_recipe` line that was added in the previous step. This example uses a data bag named `apps` and a data bag item named `supermarket`: ``` app = data_bag_item('apps', 'supermarket') ``` 2. Set the attributes from the data bag: ``` node.override['supermarket_omnibus']['chef_server_url'] = app['chef_server_url'] node.override['supermarket_omnibus']['chef_oauth2_app_id'] = app['chef_oauth2_app_id'] node.override['supermarket_omnibus']['chef_oauth2_secret'] = app['chef_oauth2_secret'] node.override['supermarket_omnibus']['package_url'] = app['package_url'] ``` Note that the `['package_url']` setting points to the location of the Supermarket package on your artifact store. When finished, the `/recipes/default.rb` file should have code similar to: ``` app = data_bag_item('apps', 'supermarket') node.override['supermarket_omnibus']['chef_server_url'] = app['chef_server_url'] node.override['supermarket_omnibus']['chef_oauth2_app_id'] = app['chef_oauth2_app_id'] node.override['supermarket_omnibus']['chef_oauth2_secret'] = app['chef_oauth2_secret'] include_recipe 'supermarket-omnibus-cookbook' ``` Alternatively, if you chose not to use a data bag to store these values, your `default.rb` should look similar to this: ``` node.override['supermarket_omnibus']['chef_server_url'] = 'https://chef-server.example.com:443' node.override['supermarket_omnibus']['chef_oauth2_app_id'] = '0bad0f2eb04e935718e081fb71asdfec3681c81acb9968a8e1e32451d08b' node.override['supermarket_omnibus']['chef_oauth2_secret'] = '17cf1141cc971a10ce307611beda7ffadstr4f1bc98d9f9ca76b9b127879' node.override['supermarket_omnibus']['package_url'] = 'http://packages.example.com/supermarket_3.1.22-1_amd64.deb' include_recipe 'supermarket-omnibus-cookbook' ``` 3. Save and close the `recipes/default.rb` file. 4. Upload all of your cookbooks to the Chef Infra Server: ``` knife cookbook upload -a ``` ### Bootstrap Supermarket Bootstrap the node on which Chef Supermarket is to be installed. For example, to bootstrap a node running Ubuntu on Amazon Web Services (AWS), the command is similar to: ``` knife bootstrap ip_address -N supermarket-node -x ubuntu --sudo ``` where: * `-N` defines the name of the Chef Supermarket node: `supermarket-node` * `-x` defines the (ssh) user name: `ubuntu` * `--sudo` ensures that sudo is used while running commands on the node during the bootstrap operation When the bootstrap operation is finished, do the following: 1. Add the wrapper cookbook’s `/recipes/default.rb` recipe to the run-list: ``` knife node run_list set supermarket-node recipe[my_supermarket_wrapper::default] ``` where `supermarket-node` is the name of the node that was just bootstrapped. 2. Start Chef Infra Client on the newly-bootstrapped Chef Supermarket node. For example, using SSH: ``` ssh ubuntu@your-supermarket-node-public-dns ``` 3. After accessing the Chef Supermarket node, run Chef Infra Client: ``` sudo chef-client ``` ### Connect to Supermarket To reach the newly spun up private Chef Supermarket, the hostname must be resolvable from a workstation. For production use, the hostname should have a DNS entry in an appropriate domain that is trusted by each user’s workstation. 1. Visit the Chef Supermarket hostname in the browser. A private Chef Supermarket will generate and use a self-signed certificate, if a certificate is not supplied as part of the installation process (via the wrapper cookbook). 2. If an SSL notice is shown due to your self-signed certificate while connecting to Chef Supermarket via a web browser, accept the SSL certificate. A trusted SSL certificate should be used for private Chef Supermarket that is used in production. 3. After opening Chef Supermarket in a web browser, click the **Create Account** link. A prompt to log in to the Chef Infra Server is shown. Authorize the Chef Supermarket to use the Chef Infra Server account for authentication. Note The redirect URL specified for Chef Identity **MUST** match the FQDN hostname of the Chef Supermarket server. The URI must also be correct: `/auth/chef_oauth2/callback`. Otherwise, an error message similar to `The redirect uri included is not valid.` will be shown. ### Configuration updates #### Knife Update the `config.rb` file on your workstation to use your private Supermarket: ``` knife[:supermarket_site] = 'https://supermarket.example.com' ``` #### Berkshelf If you’re using Berkshelf, update your `Berksfile` to replace `https://supermarket.chef.io` with the URL of your private Supermarket: ``` source 'https://supermarket.example.com' ``` ### Upload cookbooks to Supermarket To upload new cookbooks to your private Supermarket, use the `knife supermarket share` command on your workstation: ``` knife supermarket share chef-ingredient ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/install_chef_air_gap/ohai (executable) ================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/ctl_ohai.md) ohai is the command-line interface for Ohai, a tool that is used to detect attributes on a node, and then provide these attributes to Chef Infra Client at the start of every Chef Infra Client run. Options ------- This command has the following syntax: ``` ohai OPTION ``` This tool has the following options: `ATTRIBUTE_NAME ATTRIBUTE NAME ...` Use to have Ohai show only output for named attributes. `-c CONFIG`, `--config CONFIG` The path to a configuration file to use For example: `/etc/ohai/config.rb`. `-d DIRECTORY`, `--directory DIRECTORY` The directory in which additional Ohai plugins are located. For example: `/my/extra/plugins`. `-h`, `--help` Show help for the command. `-l LEVEL`, `--log_level LEVEL` The level of logging to be stored in a log file. `-L LOGLOCATION`, `--logfile LOGLOCATION` The location of the log file. `-v`, `--version` The version of Ohai. Examples -------- The following examples show how to use the Ohai command-line tool: ### Run a plugin independently of a Chef Infra Client run An Ohai plugin can be run independently of a Chef Infra Client run. First, ensure that the plugin is located in the `/plugins` directory and then use the `-f` option when running Ohai from the command line. For example, a plugin named `sl_installed` may look like the following: ``` Ohai.plugin(:Sl) do provides "sl" collect_data(:default) do sl Mash.new if ::File.exist?("/usr/games/sl") sl[:installed] = true else sl[:installed] = false end # sl[:installed] = ::File.exist?("/usr/games/sl") end end ``` To run that plugin from the command line, use the following command: ``` ohai --directory /path/to/directory sl ``` The command will return something similar to: ``` { "sl": { "installed": true } } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ctl_ohai/About the Compliance Phase ========================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_compliance_phase.md) Chef Infra Client’s Compliance Phase lets you automatically execute compliance audits and view the results as part of any Chef Infra Client run. The Compliance Phase of the Chef Infra Client run replaces the legacy [audit cookbook](https://supermarket.chef.io/cookbooks/audit) and works with your existing audit cookbook attributes, and you can also set it up for new cookbooks. This additional phase gives you the latest compliance capabilities without having to manage cookbook dependencies or juggle versions during Chef Infra Client updates. Existing audit cookbook users can migrate to the new Compliance Phase by removing the audit cookbook from their run_list and setting the `node['audit']['compliance_phase']` attribute to `true`. The Compliance Phase replaces the `audit cookbook` by integrating InSpec compliance checks into the [Chef Infra Client run](../chef_client_overview/index) The Compliance Phase is designed to run on any node in your system that is set up–or [“bootstrapped”](../install_bootstrap/index)–for a `chef-client` run. Upgrade to Compliance Phase from Audit Cookbook ----------------------------------------------- The Compliance Phase requires Chef Infra Client 17 or higher. If your system is configured to use the `audit cookbook`, make these changes to switch to the Compliance Phase: 1. Set the `node['audit']['compliance_phase']` attribute to `true` through a Policyfile or cookbook attributes file. 2. Remove the `audit cookbook` from your [‘run-list’](../run_lists/index). 3. On your next Chef Infra Client run, you should see the Compliance Phase results. Set up the Compliance Phase in new Cookbooks -------------------------------------------- ### Enable the Compliance Phase The Compliance Phase is enabled by setting the `node['audit']['compliance_phase']` attribute to `true` through cookbook attributes or Policyfiles. To enable Compliance Phase using cookbook attributes add the following line to the `attributes/default.rb` file in your cookbook. ``` default['audit']['compliance_phase'] = true ``` ### Set InSpec Profiles Setting one or more Chef InSpec profiles enables the compliance phase in a Chef Infra Client run. The presence of this configuration in your attributes file instructs Chef Infra Client to fetch and execute the specific Chef InSpec profiles and write the results to disk using the default `cli` and `json-file` reporters. Retrieve [‘Chef InSpec profiles’](../inspec/profiles/index) from Chef Automate, Supermarket, a local file, GitHub, or over HTTP with the `node['audit']['profiles']` attribute. The following examples: * Retrieve profiles from Chef Automate, Supermarket, a local file, GitHub, or over HTTP. * Display the results on the command line using the default `cli` reporter. * Write the results to disk using the default `json-file` reporter to `<chef_cache_path>/compliance_reports/compliance-<timestamp>.json`. * [Automate](#automate-panel) * [Supermarket](#supermarket-panel) * [File](#local-path-panel) * [GitHub](#git-panel) * [HTTP](#http-panel) ``` # Invoke the Compliance Phase default['audit']['compliance_phase'] = true # Set profile locations default['audit']['profiles']['linux-baseline'] = { 'compliance': 'user/linux-baseline', 'version': '2.1.0' } ``` Warning Fetching profiles from Automate requires setting `data_collector.server_url` and `data_collector.token` in your `client.rb` to fetch profiles from Chef Automate. This configuration is described in more detail in the Chef Automate [data collector documentation](../automate/data_collection/index). ``` # Invoke the Compliance Phase default['audit']['compliance_phase'] = true # Set profile locations default['audit']['profiles']['ssh'] = { 'supermarket': 'hardening/ssh-hardening' } ``` ``` # Invoke the Compliance Phase default['audit']['compliance_phase'] = true # Set profile locations default['audit']['profiles']['4thcafe/win2012_audit'] = { 'path': 'E:/profiles/win2012_audit' } ``` ``` # Invoke the Compliance Phase default['audit']['compliance_phase'] = true # Set profile locations default['audit']['profiles']['ssl'] = { 'git': 'https://github.com/dev-sec/ssl-benchmark.git' } ``` ``` # Invoke the Compliance Phase default['audit']['compliance_phase'] = true # Set profile locations default['audit']['profiles']['ssh2'] = { 'url': 'https://github.com/dev-sec/tests-ssh-hardening/archive/master.zip' } ``` ### Fetch Profiles Set the fetcher attribute with `default['audit']['fetcher']` to retrieve InSpec compliance profiles from either Chef Automate or Chef Infra Server in addition to the location defined by `default ['audit']['profile']`. Left unset, the Compliance Phase defaults to the [fetchers included in Chef InSpec](../inspec/profiles/index#profile-dependencies). Chef Infra and Chef InSpec fetchers are mutually exclusive so, you can only use one of these configurations. The following examples: * Retrieve the ‘ssh’ profile from Chef Supermarket. * Fetch additional profiles from Chef Automate or Chef Server. * Display the results on the command line using the default `cli` reporter. * Write the results to disk using the default `json-file` reporter to `<chef_cache_path>/compliance_reports/compliance-<timestamp>.json`. * [Automate](#automate-fetcher) * [Infra Server](#server-fetcher) ``` # Invoke the Compliance Phase default['audit']['compliance_phase'] = true # Set profile location default['audit']['profiles']['ssh'] = { 'supermarket': 'hardening/ssh-hardening' } # Fetch additional profiles default['audit']['fetcher'] = 'chef-automate' ``` Warning Fetching profiles from Automate requires setting `data_collector.server_url` and `data_collector.token` in your `client.rb` to fetch profiles from Chef Automate. This configuration is described in more detail in the Chef Automate [data collector documentation](../automate/data_collection/index). ``` # Invoke the Compliance Phase default['audit']['compliance_phase'] = true # Set profile location default['audit']['profiles']['ssh'] = { 'supermarket': 'hardening/ssh-hardening' } # Fetch additional profiles default['audit']['fetcher'] = 'chef-server' ``` ### Reporters Reporters control what is done with the resulting report after the Chef InSpec run. Either a single value or a list of multiple values is supported. The default is the `cli` and `json-file` reporters. Reporters can send Compliance Phase results to: * Chef Automate proxied by Chef Infra Server. * Directly to Chef Automate (requires additional authentication). * The terminal if Chef Infra Client is run interactively by a user. * A file on disk. The following examples: * Retrieve the ‘ssh’ profile from Chef Supermarket * Fetch additional profiles from Chef Automate * Send the results to Chef Automate, Chef Automate proxied by Chef Infra Server, or to a file on disk. * [Automate](#automate-reporter) * [Automate via Infra Server](#server-reporter) * [File](#local-reporter) ``` # Invoke the Compliance Phase default['audit']['compliance_phase'] = true # Set profile location default['audit']['profiles']['ssh'] = { 'supermarket': 'hardening/ssh-hardening' } # Fetch additional profiles default['audit']['fetcher'] = 'chef-automate' # Set reporter default['audit']['reporter'] = 'chef-automate' ``` Warning Reporting Compliance Phase results directly to Chef Automate requires setting `data_collector.server_url` and `data_collector.token` in your `client.rb` to fetch profiles from Chef Automate. This configuration is described in more detail in the Chef Automate [‘data collector documentation’](../automate/data_collection/index). ``` # Invoke the Compliance Phase default['audit']['compliance_phase'] = true # Set profile location default['audit']['profiles']['ssh'] = { 'supermarket': 'hardening/ssh-hardening' } # Fetch additional profiles default['audit']['fetcher'] = 'chef-automate' # Set reporter default['audit']['reporter'] = 'chef-server-automate' ``` ``` # Invoke the Compliance Phase default['audit']['compliance_phase'] = true # Set profile location default['audit']['profiles']['ssh'] = { 'supermarket': 'hardening/ssh-hardening' } # Fetch additional profiles default['audit']['fetcher'] = 'chef-automate' # Set two reporters default['audit']['reporter'] = 'json-file', 'cli' # Set the location of the json-file output # Note that the location attribute uses json_file default['audit']['json_file']['location'] = '/file/path/report.json' ``` The default `json-file` path is: `<chef_cache_path>/compliance_reports/compliance-<timestamp>.json`. The path will also be output to the Chef Infra Client log: ``` ['2017-08-29T00:22:10+00:00'] INFO: Reporting to json-file ['2017-08-29T00:22:10+00:00'] INFO: Writing report to /opt/kitchen/cache/compliance-reports/compliance-20170829002210.json ['2017-08-29T00:22:10+00:00'] INFO: Report handlers complete ``` Customize Profiles ------------------ You can upload profiles to Chef Automate using the [Chef Automate API](https://docs.chef.io/automate/api/#operation/Create) or the `inspec compliance` command. ### Waivers Use [‘waivers’](../inspec/waivers/index) to mark individual failing controls as administratively accepted, either on a temporary or permanent basis. To use waivers: 1. Prepare a YAML waiver file. 2. Deliver the waiver file to the node in a [‘cookbook_file’](../resources/cookbook_file/index) or [‘remote_file’](../resources/remote_file/index). 3. Set the `waiver_file` attribute for the compliance phase to that location. For example: ``` default['audit']['waiver_file'] = "waivers.yaml" ``` ### External Data InSpec profiles should be self-contained and independent from external data. In some cases, a profile’s test may exhibit different behavior depending on aspects of the node being tested and in these cases, you may want to use external data. Chef InSpec profiles accept [‘inputs’](../inspec/inputs/index) that let you customize the test. #### InSpec Input You can pass [‘Chef InSpec inputs’](../inspec/inputs/index) to the Chef InSpec runner. Chef InSpec inputs were previously called `attributes` and you will set them in an `['audit']['attributes']` hash in your attributes file. Any data added to `['audit']['attributes']` as a hash is passed to Chef InSpec as individual attributes. ``` default['audit']['attributes'] = { first_input: 'some value', second_input: 'another value', } ``` #### Chef Node Data There are two primary ways to pass Chef Infra node data to Chef InSpec run during the compliance phase. ##### Explicitly pass necessary data (recommended) Any data added to the `node['audit']['attributes']` hash will be passed as individual Chef InSpec attributes. This provides a clean interface between the Chef Infra client run and Chef InSpec profile, allowing for easy assignment of default values in the InSpec profile. This method is especially recommended if the Chef InSpec profile is expected to be used outside of the context of Compliance Phase so it’s made explicit to profile consumers what attributes are necessary. Set the attributes in your cookbook attributes file and then use them in your InSpec profile. Set the attributes in a cookbook attributes file: ``` node['audit']['attributes']{ 'key1' = 'value1', 'debug_enabled' = node['my_cookbook']['debug_enabled'], 'environment' = node.chef_environment } ``` Use the attributes in an InSpec profile: ``` environment = attribute('environment', description: 'The Chef Infra environment for the node', default: 'dev') control 'debug-disabled-in-production' do title 'Debug logs disabled in production' desc 'Debug logs contain potentially sensitive information and should not be on in production.' impact 1.0 describe file('/path/to/my/app/config') do its('content') { should_not include "debug=true" } end only_if { environment == 'production' } end ``` #### Use the Chef Infra Node Object Compliance Phase can be configured to pass the Chef Infra node object as a Chef InSpec attribute named `chef_node`. While using the `chef_node` object provides the ability to write more flexible profiles, it is very difficult to reuse these profiles outside of the Compliance Phase. To reuse these profiles, you will need to understand how to pass in a single attribute containing Chef Infra-like data. We recommend passing external data explicitly whenever possible. To use this option, first enable it in a wrapper cookbook or similar: ``` node.override['audit']['chef_node_attribute_enabled'] = true ``` &mldr; and then use it in your profile: ``` chef_node = attribute('chef_node', description: 'Chef Node') control 'no-password-auth-in-prod' do title 'No Password Authentication in Production' desc 'Password authentication is allowed in all environments except production' impact 1.0 describe sshd_config do its('PasswordAuthentication') { should cmp 'No' } end only_if { chef_node['chef_environment'] == 'production' } end ``` Useful Compliance Phase Attributes ---------------------------------- ### audit-enforcer A special reporter that causes the compliance run to raise an error and immediately terminates the Chef Infra Client run if any control of any Chef InSpec profile fails. If you specify multiple reporters, place the `audit-enforcer` at the end of the list, allowing the other reporters to generate their output prior to run termination. Example: ``` # fail on error default['audit']['reporter'] = 'audit-enforcer'. ``` ### chef_node_attribute_enabled If enabled, a hash representation of the Chef Infra node object will be sent to an input named `chef_node`. Default: false ``` # enable sending a hash representation of the Chef Infra node object default['audit']['chef_node_attribute_enabled'] = true ``` ### compliance_phase Enable the built-in compliance phase run. Possible values: true, false, nil ``` # Turn on Compliance Phase default['audit']['compliance_phase] = true ``` ### control_results_limit The list of results per control will be truncated to this amount to reduce the size of reports. A summary of removed results will be sent with each impacted control. Defaults to `50`. ``` # allow 100 results default['audit']['control_results_limit'] = 100 ``` ### fetcher Controls the location for additional profile locations for Chef InSpec profiles default fetch locations provided through the `[audit][profiles]` attribute. Accepted values: nil, ‘chef-server’, ‘chef-automate’. ``` # fetch additional profiles from Chef Server default[audit][fetcher] = 'chef-server' ``` ### insecure Setting the attribute `default['audit']['insecure']` to `true` will skip SSL certificate verification for the `chef-automate` and `chef-server-automate` reporters. This allows connections to HTTPS endpoints with self-signed ssl certificates. Default is `false` ``` # allow self-signed certificates default['audit']['insecure'] = true ``` ### json_file The location on disk that Chef InSpec’s json reports are saved to when using the ‘json-file’ reporter. Defaults to: `<chef_cache_path>/compliance_reports/compliance-<timestamp>.json` ``` default['audit']['reporter'] = 'json-file' default['audit']['json_file']['location'] = '/path/to/file.json' ``` ### inspec_backend_cache Chef InSpec caches the results of commands executed on the node during the compliance phase. Caching improves the compliance phase performance when slower-running commands are executed multiple times during a Chef Infra Client run. Disable this feature if your Chef InSpec profile runs a command multiple times expecting different output during the run. Default: true. Example: ``` # Disable caching of commands default['audit']['inspec_backend_cache'] = false ``` ### profiles Chef InSpec Compliance profiles to be used for scanning nodes. ``` # use the ssh-hardening profile from Supermarket default['audit']['profiles']['ssh'] = { 'supermarket': 'hardening/ssh-hardening' } ``` ### quiet Controls verbosity of the Chef InSpec runner. Defaults to `true`. To turn this off, set the attribute `default['audit']['quiet']` to `false`. ``` # verbose default['audit']['quiet'] = false ``` ### reporter Controls what is done with the resulting report after the Chef InSpec run. Accepts a single string value or an array of multiple values. The ‘cli’ reporter mimics the InSpec command line output in your terminal, which lets you see your system’s compliance status at the end of the Compliance Phase. Accepted values: ‘chef-server-automate’, ‘chef-automate’, ‘json-file’, ‘audit-enforcer’, ‘cli’ ``` # set the reporter to Chef Automate default['audit']['reporter'] = 'chef-automate', 'cli' ``` ### run_time_limit Control results that have a `run_time` below this limit will be stripped of the `start_time` and `run_time` fields to reduce the size of reports. Defaults to `1.0`. Set this attribute with `default['audit']['run_time_limit']`. ``` # allow 5 minutes run time default['audit']['run_time_limit'] = 5.0 ``` ### result_include_backtrace When a Chef InSpec resource throws an exception, results contain a short error message and a detailed ruby stacktrace of the error. Default: false (does not send backtrace). Example: ``` # include backtrace default['audit']['result_include_backtrace'] = true ``` ### result_message_limit Truncates any control result messages exceeding this character limit. Chef Automate has a 4 MB report size limit and cannot ingest reports exceeding this limitation. Chef InSpec will append this text at the end of any truncated messages: `[Truncated to 10000 characters]` Default: 10000. ``` default['audit']['result_message_limit] = 10000 ``` ### server When reporting to a Chef Automate instance proxied via Chef Infra Server, the Compliance Phase can be configured to use a different URL than the `chef_server_url` configured in `client.rb`. This is enabled with the attribute `default['audit']['server']`. ``` default['audit']['server'] = 'https://server.4thcafe.com'. ``` ### waiver_file A string path or an array of paths to Chef InSpec waiver files. ``` default['audit']['waiver_file'] = 'path/to/waiver.yml'. ``` Errors and Troubleshooting -------------------------- ### Cache Results Chef InSpec caches the results of commands executed on the node during the compliance phase. Caching improves the compliance phase performance when slower-running commands are executed multiple times during a Chef Infra Client run. Disable this feature if your Chef InSpec profile runs a command multiple times expecting different output during the run. Default: true. Example: ``` # Disable caching of commands default['audit']['inspec_backend_cache'] = false ``` ### Chef InSpec Report Size Limits The size of the report being generated from running the Compliance Phase is influenced by a few factors like: * number of controls and tests in a profile * number of profile failures for the node * controls metadata (title, description, tags, etc) * number of resources (users, processes, etc) that are being tested Depending on your setup, there are some limits you need to be aware of. A common one is Chef Infra Server default (1MB) request size. Exceeding this limit will reject the report with `ERROR: 413 "Request Entity Too Large"`. For more details about these limits, please refer to [‘the documentation on troubleshooting 413 errors’](#413-request-entity-too-large). ### HTTP Errors #### 401, 403 Unauthorized - bad clock Occasionally, the system date/time will drift between client and server. If this drift is greater than a couple of minutes, the Chef Infra Server will throw a 401 unauthorized and the request will not be forwarded to the Chef Automate server. On the Chef Infra Server you can see this in the following logs: ``` # chef-server-ctl tail ==> /var/log/opscode/nginx/access.log <== 192.168.200.102 - - ['28/Aug/2016:14:57:36 +0000'] "GET /organizations/4thcafe/nodes/vagrant-c0971990 HTTP/1.1" 401 "0.004" 93 "-" "Chef Client/12.14.38 (ruby-2.3.1-p112; ohai-8.19.2; x86_64-linux; +https://chef.io)" "127.0.0.1:8000" "401" "0.003" "12.14.38" "algorithm=sha1;version=1.1;" "vagrant-c0971990" "2013-09-25T15:00:14Z" "2jmj7l5rSw0yVb/vlWAYkK/YBwk=" 1060 ==> /var/log/opscode/opscode-erchef/crash.log <== 2016-08-28 14:57:36 =ERROR REPORT==== {<<"method=GET; path=/organizations/4thcafe/nodes/vagrant-c0971990; status=401; ">>,"Unauthorized"} ==> /var/log/opscode/opscode-erchef/erchef.log <== 2016-08-28 14:57:36.521 ['error'] {<<"method=GET; path=/organizations/4thcafe/nodes/vagrant-c0971990; status=401; ">>,"Unauthorized"} ==> /var/log/opscode/opscode-erchef/current <== 2016-08-28_14:57:36.52659 ['error'] {<<"method=GET; path=/organizations/4thcafe/nodes/vagrant-c0971990; status=401; ">>,"Unauthorized"} ==> /var/log/opscode/opscode-erchef/requests.log.1 <== 2016-08-28T14:57:36Z erchef@127.0.0.1 method=GET; path=/organizations/4thcafe/nodes/vagrant-c0971990; status=401; req_id=g3IAA2QAEGVyY2hlZkAxMjcuMC4wLjEBAAOFrgAAAAAAAAAA; org_name=4thcafe; msg=bad_clock; couchdb_groups=false; couchdb_organizations=false; couchdb_containers=false; couchdb_acls=false; 503_mode=false; couchdb_associations=false; couchdb_association_requests=false; req_time=1; user=vagrant-c0971990; req_api_version=1; ``` Additionally, the chef_gate log will contain a similar message: ``` # /var/log/opscode/chef_gate/current 2016-08-28_15:01:34.88702 ['GIN'] 2016/08/28 - 15:01:34 | 401 | 13.650403ms | 192.168.200.102 | POST /compliance/organizations/4thcafe/inspec 2016-08-28_15:01:34.88704 Error #01: Authentication failed. Please check your system's clock. ``` #### 401 Token and Refresh Token Authentication In the event of a malformed or unset token, the Chef Automate server will log the token error: ``` ==> /var/log/chef-compliance/core/current <== 2016-08-28_20:41:46.17496 20:41:46.174 ERR => Token authentication: %!(EXTRA *errors.errorString=malformed JWS, only 1 segments) 2016-08-28_20:41:46.17498 ['GIN'] 2016/08/28 - 20:41:46 | 401 | 53.824us | 192.168.200.102 | GET /owners/base/compliance/linux/tar ==> /var/log/chef-compliance/nginx/compliance.access.log <== 192.168.200.102 - - ['28/Aug/2016:21:23:46 +0000'] "GET /api/owners/base/compliance/linux/tar HTTP/1.1" 401 0 "-" "Ruby" ``` #### 413 Request Entity Too Large This error indicates that you have exceeded limit the `erchef` request size in Chef Infra Server. The default for versions before 13.0 was 1MB. Starting with version 13.0 the default is 2MB. To resolve this error, set the `opscode_erchef['max_request_size']` in Chef Infra Server’s `/etc/opscode/chef-server.rb` to a larger amount. This example sets the limit to 3MB: ``` opscode_erchef['max_request_size'] = 3000000 ``` Then run `chef-server-ctl reconfigure` to apply this change. ##### 413 Error Logs The 413 “Request Entity Too Large” error appears in both the stacktrace and the Chef Infra Server Nginx logs. * [Stacktrace](#413-stacktrace) * [Nginx logs](#413-server-nginx) The stacktrace shows the 413 error: ``` Running handlers: ['2017-12-21T16:21:15+00:00'] WARN: Compliance report size is 1.71 MB. ['2017-12-21T16:21:15+00:00'] ERROR: 413 "Request Entity Too Large" (Net::HTTPServerException) /opt/chef/embedded/lib/ruby/2.4.0/net/http/response.rb:122:in `error!' /opt/chef/embedded/lib/ruby/gems/2.4.0/gems/chef-13.6.4/lib/chef/http.rb:152:in `request' /opt/chef/embedded/lib/ruby/gems/2.4.0/gems/chef-13.6.4/lib/chef/http.rb:131:in `post' /var/chef/cache/cookbooks/audit/libraries/reporters/cs_automate.rb:37:in `block in send_report' ... ``` The Chef Infra Server Nginx log confirms the `413` error: ``` ==> /var/log/opscode/nginx/access.log <== 192.168.56.40 - - ['21/Dec/2017:11:35:30 +0000'] "POST /organizations/eu_org/data-collector HTTP/1.1" 413 "0.803" 64 "-" "Chef Client/13.6.4 (ruby-2.4.2-p198; ohai-13.6.0; x86_64-linux; +https://chef.io)" "-" "-" "-" "13.6.4" "algorithm=sha1;version=1.1;" "bootstrapped-node" "2017-12-21T11:35:31Z" "GR6RyPvKkZDaGyQDYCPfoQGS8G4=" 1793064 ``` Chef Automate Backend Errors ---------------------------- Chef Automate sets the `logstash` limit to 10% of the system memory automatically as part of the `automate-ctl reconfigure` command execution. You have reached the java heap size(`-Xmx`) limit of `logstash` if a Chef InSpec report does not become available in Chef Automate and this error is in the `logstash` logs: ``` /var/log/delivery/logstash/current 2017-12-21_13:59:54.69949 DEBUG: Ruby filter is processing an 'inspec_profile' event 2017-12-21_14:00:16.51553 java.lang.OutOfMemoryError: Java heap space 2017-12-21_14:00:16.51556 Dumping heap to /opt/delivery/embedded/logstash/heapdump.hprof ... 2017-12-21_14:00:16.51556 Unable to create /opt/delivery/embedded/logstash/heapdump.hprof: File exists 2017-12-21_14:00:18.50676 Error: Your application used more memory than the safety cap of 383M. 2017-12-21_14:00:18.50694 Specify -J-Xmx####m to increase it (#### = cap size in MB). 2017-12-21_14:00:18.50703 Specify -w for full OutOfMemoryError stack trace ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_compliance_phase/About Ohai ========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/ohai.md) Ohai is a tool for collecting system configuration data, which it then provides to Chef Infra Client to use in cookbooks. Chef Infra Client runs Ohai at the start of every Chef Infra run to determine system state. The attributes that Ohai collects are called `automatic attributes`. Chef Infra Client uses these attributes to ensure that nodes are in the desired state after each configuration run. The types of attributes Ohai collects include but are not limited to: * Operating System * Network * Memory * Disk * CPU * Kernel * Host names * Fully qualified domain names * Virtualization * Cloud provider metadata Ohai includes required and optional plugins to detect common configuration information. Ohai has a plugin model and language to write [custom plugins](../ohai_custom/index) to collect additional system state information. Ohai collects data for many platforms, including AIX, macOS, Linux, FreeBSD, Solaris, and any Microsoft Windows operating systems. See the [Chef Infra Client release notes](https://docs.chef.io/release_notes_client/) for the latest information on Ohai. Automatic Attributes -------------------- Note Attributes can be configured in cookbooks (attribute files and recipes), roles, and environments. In addition, Ohai collects attribute data about each node at the start of a Chef Infra Client run. See [Attributes](../attributes/index) for more information about how all of these attributes fit together. An automatic attribute is a specific detail about a node, such as an IP address, a host name, a list of loaded kernel modules, and so on. Automatic attributes are detected by Ohai and are then used by Chef Infra Client to ensure that they are handled properly during every Chef Infra Client run. The most commonly accessed automatic attributes are: | Attribute | Description | | --- | --- | | `node['platform']` | The platform on which a node is running. This attribute helps determine which providers will be used. | | `node['platform_family']` | The platform family is a Chef Infra specific grouping of similar platforms where cookbook code can often be shared. For example, `rhel` includes Red Hat Linux, Oracle Linux, CentOS, and several other platforms that are nearly identical to Red Hat Linux. | | `node['platform_version']` | The version of the platform. This attribute helps determine which providers will be used. | | `node['ipaddress']` | The IP address for a node. If the node has a default route, this is the IPV4 address for the interface. If the node does not have a default route, the value for this attribute should be `nil`. The IP address for default route is the recommended default value. | | `node['macaddress']` | The MAC address for a node, determined by the same interface that detects the `node['ipaddress']`. | | `node['fqdn']` | The fully qualified domain name for a node. This is used as the name of a node unless otherwise set. | | `node['hostname']` | The host name for the node. | | `node['domain']` | The domain for the node. | | `node['recipes']` | A list of recipes associated with a node (and part of that node's run-list). | | `node['roles']` | A list of roles associated with a node (and part of that node's run-list). | | `node['ohai_time']` | The time at which Ohai was last run. This attribute is not commonly used in recipes, but it is saved to the Chef Infra Server and can be accessed using the `knife status` subcommand. | ### Get a list of automatic attributes for a node Ohai collects a list of automatic attributes at the start of each Chef Infra Client run. This list will vary from organization to organization, by server type, and by the platform that runs those servers. All the attributes collected by Ohai are unmodifiable by Chef Infra Client. Run the `ohai` command on a system to see which automatic attributes Ohai has collected for a particular node. ### Attributes Blocklist Warning When attribute blocklist settings are used, any attribute defined in a blocklist will not be saved to the Chef Infra Server and any attribute that is not defined in a blocklist will be saved. Each attribute type must be blocklisted independently of the other attribute types. For example, if `blocked_automatic_attributes` defines attributes that will not be saved, but `blocked_normal_attributes`, `blocked_default_attributes`, and `blocked_override_attributes` are not defined, then all normal attributes, default attributes, and override attributes will be saved, as well as the automatic attributes that were not specifically excluded through blocklisting. Attributes that should not be saved by a node may be blocklisted in the [client.rb](../config_rb_client/index) file. The blocklist is a Hash of keys that specify each attribute to be filtered out. Attributes are blocklisted by attribute type, with each attribute type being blocklisted independently. Each attribute type—`automatic`, `default`, `normal`, and `override`—may define blocklists by using the following settings in the client.rb file: | Setting | Description | | --- | --- | | `blocked_automatic_attributes` | A hash that blocklists `automatic` attributes, preventing blocklisted attributes from being saved. For example: `['network/interfaces/eth0']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | | `blocked_default_attributes` | A hash that blocklists `default` attributes, preventing blocklisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | | `blocked_normal_attributes` | A hash that blocklists `normal` attributes, preventing blocklisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | | `blocked_override_attributes` | A hash that blocklists `override` attributes, preventing blocklisted attributes from being saved. For example: `['map - autohome/size']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | #### Blocklisting Ohai (automatic) Attributes The recommended practice is to use `blocked_automatic_attributes` to block attributes populated by Ohai’s system information gathering. Ohai gathers a large number of attributes that can consume a signicant amount of storage space on the Chef Infra Server. Many of these attributes may be considered highly valuable, while others could be blocklisted without any impact to data available in search. Normal, default, and override attributes are typically much more important attributes used within cookbooks and are more likely to cause issues if they are blocklisted incorrectly. For example, automatic attribute data similar to: ``` { "filesystem" => { "/dev/disk0s2" => { "size" => "10mb" }, "map - autohome" => { "size" => "10mb" } }, "network" => { "interfaces" => { "eth0" => {...}, "eth1" => {...}, } } } ``` To blocklist the `filesystem` attributes and allow the other attributes to be saved, update the client.rb file: ``` blocked_automatic_attributes ['filesystem'] ``` When a blocklist is defined, any attribute of that type that is not specified in that attribute blocklist **will** be saved. So based on the previous blocklist for automatic attributes, the `filesystem` and `map - autohome` attributes will not be saved, but the `network` attributes will. For attributes that contain slashes (`/`) within the attribute value, such as the `filesystem` attribute `'/dev/diskos2'`, use an array. For example: ``` blocked_automatic_attributes [['filesystem', '/dev/diskos2']] ``` ### Attribute Allowlist Warning When attribute allowlist settings are used, only the attributes defined in a allowlist will be saved and any attribute that is not defined in a allowlist will not be saved. Each attribute type is allowlisted independently of the other attribute types. For example, if `automatic_attribute_allowlist` defines attributes to be saved, but `normal_attribute_allowlist`, `default_attribute_allowlist`, and `override_attribute_allowlist` are not defined, then all normal attributes, default attributes, and override attributes are saved, as well as the automatic attributes that were specifically included through allowlisting. Attributes that should be saved by a node may be allowlisted in the client.rb file. The allowlist is a hash of keys that specifies each attribute to be saved. Attributes are allowlisted by attribute type, with each attribute type being allowlisted independently. Each attribute type—`automatic`, `default`, `normal`, and `override`—may define allowlists by using the following settings in the client.rb file: | Setting | Description | | --- | --- | | `allowed_automatic_attributes` | A hash that allowlists `automatic` attributes, preventing non-allowlisted attributes from being saved. For example: `['network/interfaces/eth0']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | | `allowed_default_attributes` | A hash that allowlists `default` attributes, preventing non-allowlisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | | `allowed_normal_attributes` | A hash that allowlists `normal` attributes, preventing non-allowlisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | | `allowed_override_attributes` | A hash that allowlists `override` attributes, preventing non-allowlisted attributes from being saved. For example: `['map - autohome/size']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | #### Allowlisting Ohai (automatic) Attributes The recommended practice is to use `allowed_automatic_attributes` to allow specific attributes populated by Ohai’s system information gathering. Ohai gathers a large number of attributes that can consume a signicant amount of storage space on the Chef Infra Server. Many of these attributes may be considered highly valuable, while others could be skipped without any impact to data available in search. Normal, default, and override attributes are typically much more important attributes used within cookbooks and are more likely to cause issues if they are ommited from an allowlist incorrectly. For example, automatic attribute data similar to: ``` { "filesystem" => { "/dev/disk0s2" => { "size" => "10mb" }, "map - autohome" => { "size" => "10mb" } }, "network" => { "interfaces" => { "eth0" => {...}, "eth1" => {...}, } } } ``` To allowlist the `network` attributes and prevent the other attributes from being saved, update the client.rb file: ``` allowed_automatic_attributes ['network/interfaces/'] ``` When a allowlist is defined, any attribute of that type that is not specified in that attribute allowlist **will not** be saved. So based on the previous allowlist for automatic attributes, the `filesystem` and `map - autohome` attributes will not be saved, but the `network` attributes will. Leave the value empty to prevent all attributes of that attribute type from being saved: ``` allowed_automatic_attributes [] ``` For attributes that contain slashes (`/`) within the attribute value, such as the `filesystem` attribute `'/dev/diskos2'`, use an array. For example: ``` allowed_automatic_attributes [['filesystem', '/dev/diskos2']] ``` Default Plugins --------------- The following list shows the type of plugins that are included with Ohai. See the `ohai/lib/ohai/plugins` directory in the version of Ohai installed on your system for the full list: ### General Purpose Plugins ``` azure.rb c.rb chef.rb cloud.rb command.rb cpu.rb digital_ocean.rb dmi.rb docker.rb ec2.rb elixir.rb erlang.rb eucalyptus.rb filesystem.rb freebsd gce.rb go.rb groovy.rb haskell.rb hostname.rb init_package.rb java.rb joyent.rb kernel.rb keys.rb languages.rb libvirt.rb linode.rb lua.rb mono.rb network.rb nodejs.rb ohai_time.rb ohai.rb memory.rb network.rb platform.rb openstack.rb os.rb packages.rb perl.rb php.rb platform.rb powershell.rb ps.rb python.rb rackspace.rb root_group.rb ruby.rb rust.rb scala.rb scaleway.rb shard.rb shells.rb softlayer.rb ssh_host_key.rb timezone.rb uptime.rb virtualbox.rb vmware.rb zpools.rb ``` ### Platform Specific Plugins ``` aix kernel.rb memory.rb network.rb platform.rb uptime.rb virtualization.rb bsd virtualization.rb darwin cpu.rb filesystem.rb hardware.rb memory.rb network.rb platform.rb system_profiler.rb virtualization.rb dragonflybsd cpu.rb memory.rb network.rb os.rb platform.rb freebsd cpu.rb memory.rb network.rb os.rb platform.rb linux block_device.rb cpu.rb filesystem.rb fips.rb hostnamectl.rb lsb.rb machineid.rb mdadm.rb memory.rb network.rb platform.rb sessions.rb virtualization.rb netbsd cpu.rb memory.rb network.rb platform.rb openbsd cpu.rb memory.rb network.rb platform.rb solaris2 cpu.rb dmi.rb filesystem.rb memory.rb network.rb platform.rb virtualization.rb windows cpu.rb drivers.rb filesystem.rb fips.rb memory.rb network.rb platform.rb system_enclosure.rb virtualization.rb ``` Optional Plugins ---------------- Ohai ships several optional plugins that you can enable in the [client.rb configuration file](../config_rb_client/index). * `:Grub2` - Information from the Linux Grub2 bootloader * `:IPC` - SysV IPC shmem information (New in Chef Infra Client 16) * `:Interupts` - Data from /proc/interrupts and /proc/irq (New in Chef Infra Client 16) * `:Lspci` - PCI device information on Linux hosts. * `:Lsscsi` - SCSI device information on Linux hosts. * `:Passwd` - User and Group information on non-Windows hosts. This plugin can result in large node sizes if a system connects to Active Directory or LDAP. * `:Sessions` - Sessions data from loginctl on Linux hosts. * `:Sysctl` - All sysctl values on Linux hosts. ### Enabling Optional Plugins Optional plugins can be enabled in the [client.rb configuration file](../config_rb_client/index): ``` ohai.optional_plugins = [ :Sessions, :Lspci, ] ``` Note The Ohai optional_plugins config array must contain an array of plugin names as Symbols not Strings. Ohai Settings in client.rb -------------------------- Ohai configuration settings can be added to the client.rb file. `ohai.directory` The directory in which Ohai plugins are located. `ohai.disabled_plugins` An array of Ohai plugins to be disabled on a node. The list of plugins included in Ohai can be found in the [ohai/lib/ohai/plugins](https://github.com/chef/ohai/tree/main/lib/ohai/plugins) source. For example, disabling a single plugin: ``` ohai.disabled_plugins = [ :MyPlugin ] ``` or disabling multiple plugins: ``` ohai.disabled_plugins = [ :MyPlugin, :MyPlugin2, :MyPlugin3 ] ``` When a plugin is disabled, the Chef Infra Client log file will contain entries similar to: ``` [2014-06-13T23:49:12+00:00] DEBUG: Skipping disabled plugin MyPlugin ``` `ohai.hints_path` The path to the file that contains hints for Ohai. `ohai.log_level` The level of logging to be stored in a log file. `ohai.log_location` The location of the log file. `ohai.plugin_path` An array of paths at which Ohai plugins are located. Default value: `[<CHEF_GEM_PATH>/ohai-9.9.9/lib/ohai/plugins]`. When custom Ohai plugins are added, the paths must be added to the array. For example, a single plugin: ``` ohai.plugin_path << '/etc/chef/ohai_plugins' ``` and for multiple plugins: ``` ohai.plugin_path += [ '/etc/chef/ohai_plugins', '/path/to/other/plugins' ] ``` Note The Ohai executable ignores settings in the client.rb file when Ohai is run independently of Chef Infra Client. Custom Plugins -------------- Custom Ohai plugins can be written to collect additional information from systems as necessary. See the [Ohai Custom Plugins](../ohai_custom/index) docs for more information. Hints ----- Ohai hints are used to tell Ohai something about the system that it is running on that it would not be able to discover itself. An Ohai hint exists if a JSON file exists in the hint directory with the same name as the hint. For example, calling `hint?('antarctica')` in an Ohai plugin would return an empty hash if the file `antarctica.json` existed in the hints directory, and return nil if the file does not exist. If the hint file contains JSON content, it will be returned as a hash from the call to `hint?`. ``` { "snow": true, "penguins": "many" } ``` ``` antarctica_hint = hint?('antarctica') if antarctica_hint['snow'] "There are #{antarctica_hint['penguins']} penguins here." else 'There is no snow here, and penguins like snow.' end ``` Hint files are located in the `/etc/chef/ohai/hints/` directory by default. Use the `Ohai.config[:hints_path]` setting in the [client.rb configuration file](../config_rb_client/index) to customize this location. `ohai` Resource ---------------- Chef Infra Client includes an `ohai` resource that allows you to reload the Ohai data on a node. This allows recipes or resources that change system attributes (like a recipe that adds a user) to refer to those attributes later on during a Chef Infra Client run. See the [ohai resource](../resources/ohai) for complete usage information. ohai Command Line Tool ---------------------- Ohai can be run on the command line outside of the Chef Infra Client run. See [Ohai (executable)](../ctl_ohai) for more information. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ohai/About Policy ============ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/policy.md) Policy maps business and operational requirements, process, and workflow to settings and objects stored on the Chef Infra Server: * Roles define server types, such as “web server” or “database server” * Environments define process, such as “dev”, “staging”, or “production” * Certain types of data—passwords, user account data, and other sensitive items—can be placed in data bags, which are located in a secure sub-area on the Chef Infra Server that can only be accessed by nodes that authenticate to the Chef Infra Server with the correct SSL certificates * The cookbooks (and cookbook versions) in which organization-specific configuration policies are maintained Cookbook Versions ----------------- A cookbook version represents a set of functionality that is different from the cookbook on which it is based. A version may exist for many reasons, such as ensuring the correct use of a third-party component, updating a bug fix, or adding an improvement. A cookbook version is defined using syntax and operators, may be associated with environments, cookbook metadata, and/or run-lists, and may be frozen (to prevent unwanted updates from being made). A cookbook version is maintained just like a cookbook, with regard to source control, uploading it to the Chef Infra Server, and how Chef Infra Client applies that cookbook when configuring nodes. Note For more information about cookbook versioning, see [About Cookbook Versioning](../cookbook_versioning/index) Data Bags (Secrets) ------------------- Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. Note For more information about data bags, see [About Data Bags](../data_bags/index) Environments ------------ An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. Note For more information about environments, see [About Environments](../environments/index) Roles ----- A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. Note For more information about roles, see [About Roles](../roles/index) Policyfile ---------- A Policyfile is a way to create immutable collections of cookbooks, cookbook dependencies, and attributes defined in a single document that is uploaded to the Chef Infra Server. The Policyfile is then associated with a group of nodes. When these nodes perform a Chef Infra Client run, they utilize recipes specified in the Policyfile. Note For more information about Policyfile, see [About Policyfile](../policyfile/index) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/policy/About Search ============ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_search.md) Search indexes allow queries to be made for any type of data that is indexed by the Chef Infra Server, including data bags (and data bag items), environments, nodes, and roles. A defined query syntax is used to support search patterns like exact, wildcard, range, and fuzzy. A search is a full-text query that can be done from several locations, including from within a recipe, by using the `search` subcommand in knife, the `search` method in the Chef Infra Language, the search box in the Chef management console, and by using the `/search` or `/search/INDEX` endpoints in the Chef Infra Server API. The search engine is based on Elasticsearch and is run from the Chef Infra Server. Many of the examples in this section use knife, but the search indexes and search query syntax can be used in many locations, including from within recipes and when using the Chef Infra Server API. Search Indexes -------------- A search index is a full-text list of objects that are stored on the Chef Infra Server, against which search queries can be made. The following search indexes are built: | Search Index Name | Description | | --- | --- | | `client` | API client | | `DATA_BAG_NAME` | A data bag is a global variable that is stored as JSON data and is accessible from a Chef Infra Server. The name of the search index is the name of the data bag. For example, if the name of the data bag was "admins" then a corresponding search query might look something like `search(:admins, "*:*")`. | | `environment` | An environment is a way to map an organization's real-life workflow to what can be configured and managed when using Chef Infra Server. | | `node` | A node is any server or virtual server that is configured to be maintained by a Chef Infra Client. | | `role` | A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. | ### Using Knife Use the `knife search` subcommand to run a search query for information that is indexed on a Chef Infra Server. #### Search by platform ID To search for the IDs of all nodes running on the Amazon EC2 platform, enter: ``` knife search node 'ec2:*' -i ``` to return something like: ``` 4 items found ip-0A7CA19F.ec2.internal ip-0A58CF8E.ec2.internal ip-0A58E134.ec2.internal ip-0A7CFFD5.ec2.internal ``` #### Search by instance type To search for the instance type (flavor) of all nodes running on the Amazon EC2 platform, enter: ``` knife search node 'ec2:*' -a ec2.instance_type ``` to return something like: ``` 4 items found ec2.instance_type: m1.large id: ip-0A7CA19F.ec2.internal ec2.instance_type: m1.large id: ip-0A58CF8E.ec2.internal ec2.instance_type: m1.large id: ip-0A58E134.ec2.internal ec2.instance_type: m1.large id: ip-0A7CFFD5.ec2.internal ``` #### Search by recipe To search for recipes that are used by a node, use the `recipes` attribute to search for the recipe names, enter something like: ``` knife search node 'recipes:recipe_name' ``` or: ``` knife search node '*:*' -a recipes | grep 'recipe_name' ``` #### Search by cookbook, then recipe To search for cookbooks on a node, use the `recipes` attribute followed by the `cookbook::recipe` pattern, escaping both of the `:` characters. For example: ``` knife search node 'recipes:cookbook_name\:\:recipe_name' ``` #### Search by node To search for all nodes running Ubuntu, enter: ``` knife search node 'platform:ubuntu' ``` #### Search by node and environment To search for all nodes running CentOS in the production environment, enter: ``` knife search node 'chef_environment:production AND platform:centos' ``` #### Search for nested attributes To find a nested attribute, use a pattern similar to the following: ``` knife search node <query_to_run> -a <main_attribute>.<nested_attribute``` #### Search for multiple attributes To build a search query to use more than one attribute, use an underscore (`_`) to separate each attribute. For example, the following query will search for all nodes running a specific version of Ruby: ``` knife search node "languages_ruby_version:2.7.0" ``` #### Search for nested attributes using a search query To build a search query that can find a nested attribute: ``` knife search node name: <node_name> -a kernel.machine ``` #### Use a test query To test a search query that will be used in a `knife ssh` subcommand: ``` knife search node "role:web NOT name:web03" ``` where the query in the previous example will search all servers that have the `web` role, but not on the server named `web03`. Query Syntax ------------ A search query is comprised of two parts: the key and the search pattern. A search query has the following syntax: ``` key:search_pattern ``` where `key` is a field name that is found in the JSON description of an indexable object on the Chef Infra Server (a role, node, client, environment, or data bag) and `search_pattern` defines what will be searched for, using one of the following search patterns: exact, wildcard, range, or fuzzy matching. Both `key` and `search_pattern` are case-sensitive; `key` has limited support for multiple character wildcard matching using an asterisk ("*") (and as long as it is not the first character). Note Search queries may not contain newlines. Filter Search Results --------------------- Use `:filter_result` as part of a search query to filter the search output based on the pattern specified by a Hash. Only attributes in the Hash will be returned. The syntax for the `search` method that uses `:filter_result` is as follows: ``` search(:index, 'query', filter_result: { 'foo' => [ 'abc' ], 'bar' => [ '123' ], 'baz' => %w(sea power), } ).each do |result| puts result['foo'] puts result['bar'] puts result['baz'] end ``` where: * `:index` is of name of the index on the Chef Infra Server against which the search query will run: `:client`, `:data_bag_name`, `:environment`, `:node`, and `:role` * `'query'` is a valid search query against an object on the Chef server * `:filter_result` defines a Hash of values to be returned For example: ``` search(:node, 'role:web', filter_result: { 'name' => [ 'name' ], 'ip' => [ 'ipaddress' ], 'kernel_version' => %w(kernel version), } ).each do |result| puts result['name'] puts result['ip'] puts result['kernel_version'] end ``` Keys ---- A field name/description pair is available in the JSON object. Use the field name when searching for this information in the JSON object. Any field that exists in any JSON description for any role, node, Chef Infra Client, environment, or data bag can be searched. ### Nested Fields A nested field appears deeper in the JSON data structure. For example, information about a network interface might be several layers deep: `node['network']['interfaces']['en1']`. When nested fields are present in a JSON structure, Chef Infra Client will extract those nested fields to the top-level, flattening them into compound fields that support wildcard search patterns. By combining wildcards with range-matching patterns and wildcard queries, it is possible to perform very powerful searches, such as using the vendor part of the MAC address to find every node that has a network card made by the specified vendor. Consider the following snippet of JSON data: ``` {"network": [ //snipped... "interfaces", {"en1": { "number": "1", "flags": [ "UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST" ], "addresses": { "fe80::fa1e:dfff:fed8:63a2": { "scope": "Link", "prefixlen": "64", "family": "inet6" }, "f8:1e:df:d8:63:a2": { "family": "lladdr" }, "192.0.2.0": { "netmask": "255.255.255.0", "broadcast": "192.168.0.255", "family": "inet" } }, "mtu": "1500", "media": { "supported": { "autoselect": { "options": [ ] } }, "selected": { "autoselect": { "options": [ ] } } }, "type": "en", "status": "active", "encapsulation": "Ethernet" }, //snipped... ``` Before this data is indexed on the Chef Infra Server, the nested fields are extracted into the top level, similar to: ``` "broadcast" => "192.168.0.255", "flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"] "mtu" => "1500" ``` which allows searches like the following to find data that is present in this node: ``` node "broadcast:192.168.0.*" ``` or: ``` node "mtu:1500" ``` or: ``` node "flags:UP" ``` This data is also flattened into various compound fields, which follow the same pattern as the JSON hierarchy and use underscores (`_`) to separate the levels of data, similar to: ``` # ...snip... "network_interfaces_en1_addresses_192.0.2.0_broadcast" => "192.168.0.255", "network_interfaces_en1_addresses_fe80::fa1e:tldr_family" => "inet6", "network_interfaces_en1_addresses" => ["fe80::fa1e:tldr","f8:1e:df:tldr","192.0.2.0"] # ...snip... ``` which allows searches like the following to find data that is present in this node: ``` node "network_interfaces_en1_addresses:192.0.2.0" ``` This flattened data structure also supports using wildcard compound fields, which allow searches to omit levels within the JSON data structure that are not important to the search query. In the following example, an asterisk (`*`) is used to show where the wildcard can exist when searching for a nested field: ``` "network_interfaces_*_flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"] "network_interfaces_*_addresses" => ["fe80::fa1e:dfff:fed8:63a2", "192.0.2.0", "f8:1e:df:d8:63:a2"] "network_interfaces_en0_media_*" => ["autoselect", "none", "1000baseT", "10baseT/UTP", "100baseTX"] "network_interfaces_en1_*" => ["1", "UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST", "fe80::fa1e:dfff:fed8:63a2", "f8:1e:df:d8:63:a2", "192.0.2.0", "1500", "supported", "selected", "en", "active", "Ethernet"] ``` For each of the wildcard examples above, the possible values are shown contained within the brackets. When running a search query, the query syntax for wildcards is to simply omit the name of the node (while preserving the underscores), similar to: ``` network_interfaces__flags ``` This query will search within the `flags` node, within the JSON structure, for each of `UP`, `BROADCAST`, `SMART`, `RUNNING`, `SIMPLEX`, and `MULTICAST`. ### Examples To see the available keys for a node, enter the following (for a node named `staging`): ``` knife node show staging -Fj | less ``` to return a full JSON description of the node and to view the available keys with which any search query can be based. To use a question mark (`?`) to replace a single character in a wildcard search, enter the following: ``` knife search node 'platfor?:ubuntu' ``` To use an asterisk (`*`) to replace zero (or more) characters in a wildcard search, enter the following: ``` knife search node 'platfo*:ubuntu' ``` To find all IP address that are on the same network, enter the following: ``` knife search node 'ipaddress:192.168*' ``` where `192.168*` is the network address for which the search will be run. To use a range search to find IP addresses within a subnet, enter the following: ``` knife search node 'ipaddress:[192.168.0.* TO 192.0.2.*]' ``` where `192.168.0.* TO 192.0.2.*` defines the subnet range. Patterns -------- A search pattern is a way to fine-tune search results by returning anything that matches some type of incomplete search query. There are four types of search patterns that can be used when searching the search indexes on the Chef Infra Server: exact, wildcard, range, and fuzzy. ### Exact Matching An exact matching search pattern is used to search for a key with a name that exactly matches a search query. If the name of the key contains spaces, quotes must be used in the search pattern to ensure the search query finds the key. The entire query must also be contained within quotes, so as to prevent it from being interpreted by Ruby or a command shell. The best way to ensure that quotes are used consistently is to quote the entire query using single quotes (' ‘) and a search pattern with double quotes (" “). To search in a specific data bag for a specific data bag item, enter the following: ``` knife search admins 'id:charlie' ``` where `admins` is the name of the data bag and `charlie` is the name of the data bag item. Something similar to the following will be returned: ``` 1 items found _rev: 1-39ff4099f2510f477b4c26bef81f75b9 chef_type: data_bag_item comment: <NAME> data_bag: admins gid: ops id: charlie shell: /bin/zsh uid: 1005 ``` To search in a specific data bag using a string to find any matching data bag item, enter the following: ``` knife search admins 'comment:"<NAME>"' ``` where `admins` is the name of the data bag and `<NAME>` is the string that will be used during the search. Something similar to the following will be returned: ``` 1 items found _rev: 1-39ff4099f2510f477b4c26bef81f75b9 chef_type: data_bag_item comment: Charlie the Unicorn data_bag: admins gid: ops id: charlie shell: /bin/zsh uid: 1005 ``` ### Wildcard Matching A wildcard matching search pattern is used to query for substring matches that replace zero (or more) characters in the search pattern with anything that could match the replaced character. There are two types of wildcard searches: * A question mark (`?`) can be used to replace exactly one character (as long as that character is not the first character in the search pattern) * An asterisk (`*`) can be used to replace any number of characters (including zero) To search for any node that contains the specified key, enter the following: ``` knife search node 'foo:*' ``` where `foo` is the name of the node. To search for a node using a partial name, enter one of the following: ``` knife search node 'name:app*' ``` or: ``` knife search node 'name:app1*.example.com' ``` or: ``` knife search node 'name:app?.example.com' ``` or: ``` knife search node 'name:app1.example.???' ``` to return `app1.example.com` (and any other node that matches any of the string searches above). ### Range Matching A range matching search pattern is used to query for values that are within a range defined by upper and lower boundaries. A range matching search pattern can be inclusive or exclusive of the boundaries. Use square brackets ("[ ]") to denote inclusive boundaries and curly braces ("{ }") to denote exclusive boundaries and with the following syntax: ``` boundary TO boundary ``` where `TO` is required (and must be capitalized). A data bag named `sample` contains four data bag items: `abc`, `bar`, `baz`, and `quz`. All of the items in-between `bar` and `foo`, inclusive, can be searched for using an inclusive search pattern. To search using an inclusive range, enter the following: ``` knife search sample "id:[bar TO foo]" ``` where square brackets (`[ ]`) are used to define the range. A data bag named `sample` contains four data bag items: `abc`, `bar`, `baz`, and `quz`. All of the items that are exclusive to `bar` and `foo` can be searched for using an exclusive search pattern. To search using an exclusive range, enter the following: ``` knife search sample "id:{bar TO foo}" ``` where curly braces (`{ }`) are used to define the range. ### Fuzzy Matching A fuzzy matching search pattern is used to search based on the proximity of two strings of characters. An (optional) integer may be used as part of the search query to more closely define the proximity. A fuzzy matching search pattern has the following syntax: ``` "search_query"~edit_distance ``` where `search_query` is the string that will be used during the search and `edit_distance` is the proximity. A tilde ("~") is used to separate the edit distance from the search query. To use a fuzzy search pattern enter something similar to: ``` knife search client "name:boo~" ``` where `boo~` defines the fuzzy search pattern. This will return something similar to: ``` { "total": 1, "start": 0, "rows": [ { "public_key": "too long didn't read", "name": "foo", "_rev": "1-f11a58043906e33d39a686e9b58cd92f", "json_class": "Chef::ApiClient", "admin": false, "chef_type": "client" } ] } ``` Operators --------- An operator can be used to ensure that certain terms are included in the results, are excluded from the results, or are not included even when other aspects of the query match. Searches can use the following operators: | Operator | Description | | --- | --- | | `AND` | Use to find a match when both terms exist. | | `OR` | Use to find a match if either term exists. | | `NOT` | Use to exclude the term after `NOT` from the search results. | Operators must be in ALL CAPS. Parentheses can be used to group clauses and to form sub-queries. Warning Using `AND NOT` together may trigger an error. For example: ``` ERROR: knife search failed: invalid search query: 'datacenter%3A123%20AND%20NOT%20hostname%3Adev-%20AND%20NOT%20hostanem%3Asyslog-' Parse error at offset: 38 Reason: Expected one of \ at line 1, column 42 (byte 42) after AND ``` Use `-` instead of `NOT`. For example: ``` knife search sample "id:foo AND -id:bar" ``` ### AND To join queries using the `AND` boolean operator, enter the following: ``` knife search sample "id:b* AND animal:dog" ``` to return something like: ``` { "total": 1, "start": 0, "rows": [ { "comment": "an item named baz", "id": "baz", "animal": "dog" } ] } ``` Or, to find all of the computers running on the Microsoft Windows platform that are associated with a role named `jenkins`, enter: ``` knife search node 'platform:windows AND roles:jenkins' ``` to return something like: ``` 2 items found Node Name: windows-server-2012r2.domain.com Environment: _default FQDN: windows-server-2012r2 IP: 0000::0000:0000:0000:0000 Run List: role[jenkins-windows] Roles: jenkins-windows, jenkins Recipes: jenkins-client::windows, jenkins::node_windows Platform: windows 6.3.9600 Tags: Node Name: 123-windows-2012r2-amd64-builder Environment: _default FQDN: ABC-1234567890AB IP: 123.45.6.78 Run List: role[123-windows-2012r2-amd64-builder] Roles: 123-windows-2012r2-amd64-builder, jenkins Recipes: jenkins::node_windows, git_windows Platform: windows 6.3.9600 Tags: ``` ### NOT To negate search results using the `NOT` boolean operator, enter the following: ``` knife search sample "(NOT id:foo)" ``` to return something like: ``` { "total": 4, "start": 0, "rows": [ { "comment": "an item named bar", "id": "bar", "animal": "cat" }, { "comment": "an item named baz", "id": "baz" "animal": "dog" }, { "comment": "an item named abc", "id": "abc", "animal": "unicorn" }, { "comment": "an item named qux", "id": "qux", "animal", "penguin" } ] } ``` ### OR To join queries using the `OR` boolean operator, enter the following: ``` knife search sample "id:foo OR id:abc" ``` to return something like: ``` { "total": 2, "start": 0, "rows": [ { "comment": "an item named foo", "id": "foo", "animal": "pony" }, { "comment": "an item named abc", "id": "abc", "animal": "unicorn" } ] } ``` Special Characters ------------------ A special character can be used to fine-tune a search query and to increase the accuracy of the search results. The following characters can be included within the search query syntax, but each occurrence of a special character must be escaped with a backslash (`\`), also (`/`) must be escaped against the Elasticsearch: ``` + - && | | ! ( ) { } [ ] ^ " ~ * ? : \ / ``` For example: ``` \(1\+1\)\:2 ``` Targets ------- A search target is any object that has been indexed on the Chef Infra Server, including roles (and run-lists), nodes, environments, data bags, and any API client. ### Roles in Run-lists A search query can be made for roles that are at the top-level of a run-list and also for a role that is part of an expanded run-list. Note The `roles` field is updated with each Chef Infra Client run; changes to a run-list will not affect `roles` until the next Chef Infra Client run on the node. | Role Location | Description | | --- | --- | | Top-level | To find a node with a role in the top-level of its run-list, search within the `role` field (and escaping any special characters with the slash symbol) using the following syntax: ``` role:ROLE_NAME ``` where `role` (singular!) indicates the top-level run-list. | | Expanded | To find a node with a role in an expanded run-list, search within the `roles` field (and escaping any special characters with the slash symbol) using the following syntax: ``` roles:ROLE_NAME ``` where `roles` (plural!) indicates the expanded run-list. | To search a top-level run-list for a role named `load_balancer` use the `knife search` subcommand from the command line or the `search` method in a recipe. For example: ``` knife search node role:load_balancer ``` and from within a recipe: ``` search(:node, 'role:load_balancer') ``` To search an expanded run-list for all nodes with the role `load_balancer` use the `knife search` subcommand from the command line or the `search` method in a recipe. For example: ``` knife search node roles:load_balancer ``` and from within a recipe: ``` search(:node, 'roles:load_balancer') ``` ### Nodes A node can be searched from a recipe by using the following syntax: ``` search(:node, "key:attribute") ``` A wildcard can be used to replace characters within the search query. Expanded lists of roles (all of the roles that apply to a node, including nested roles) and recipes to the role and recipe attributes on a node are saved on the Chef Infra Server. The expanded lists of roles allows for searching within nodes that run a given recipe, even if that recipe is included by a role. Note The `recipes` field is with each Chef Infra Client run; changes to a run-list will not affect `recipes` until the next Chef Infra Client run on the node. | Node Location | Description | | --- | --- | | In a specified recipe | To find a node with a specified recipe in the run-list, search within the `run_list` field (and escaping any special characters with the slash symbol) using the following syntax: ``` search(:node, 'run_list:recipe\[foo\:\:bar\]') ``` where `recipe` (singular!) indicates the top-level run-list. Variables can be interpolated into search strings using the Ruby alternate quoting syntax: ``` search(:node, %Q{run_list:"recipe[#{the_recipe}]"} ) ``` | | In an expanded run-list | To find a node with a recipe in an expanded run-list, search within the `recipes` field (and escaping any special characters with the slash symbol) using the following syntax: ``` recipes:RECIPE_NAME ``` where `recipes` (plural!) indicates to search within an expanded run-list. | If you just want to use each result of the search and don’t care about the aggregate result you can provide a code block to the search method. Each result is then passed to the block: ``` # Print every node matching the search pattern search(:node, "*:*").each do |matching_node| puts matching_node.to_s end ``` ### API Clients An API client is any machine that has permission to use the Chef Infra Server API to communicate with the Chef Infra Server. An API client is typically a node (that runs Chef Infra Client) or a workstation (that runs knife), but can also be any other machine configured to use the Chef Infra Server API. Sometimes when a role isn’t fully defined (or implemented), it may be necessary for a machine to connect to a database, search engine, or some other service within an environment by using the settings located on another machine, such as a host name, IP address, or private IP address. The following example shows a simplified settings file: ``` username: "mysql" password: "MoveAlong" host: "10.40.64.202" port: "3306" ``` where `host` is the private IP address of the database server. Use the following knife query to view information about the node: ``` knife search node "name:name_of_database_server" --long ``` To access these settings as part of a recipe that is run on the web server, use code similar to: ``` db_server = search(:node, "name:name_of_database_server") private_ip = "#{db_server[0][:rackspace][:private_ip]}" puts private_ip ``` where the “[0]” is the 0 (zero) index for the `db_server` identifier. A single document is returned because the node is being searched on its unique name. The identifier `private_ip` will now have the value of the private IP address of the database server (`10.40.64.202`) and can then be used in templates as a variable, among other possible uses. ### Environments An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. When searching, an environment is an attribute. This allows search results to be limited to a specified environment by using Boolean operators and extra search terms. For example, to use knife to search for all of the servers running CentOS in an environment named “QA”, enter the following: ``` knife search node "chef_environment:QA AND platform:centos" ``` Or, to include the same search in a recipe, use a code block similar to: ``` qa_nodes = search(:node, 'chef_environment:QA') qa_nodes.each do |qa_node| # Do useful work specific to qa nodes only end ``` ### Data Bags Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. Any search for a data bag (or a data bag item) must specify the name of the data bag and then provide the search query string that will be used during the search. For example, to use knife to search within a data bag named “admin_data” across all items, except for the “admin_users” item, enter the following: ``` knife search admin_data "(NOT id:admin_users)" ``` Or, to include the same search query in a recipe, use a code block similar to: ``` search(:admin_data, 'NOT id:admin_users') ``` It may not be possible to know which data bag items will be needed. It may be necessary to load everything in a data bag (but not know what “everything” is). Using a search query is the ideal way to deal with that ambiguity, yet still ensure that all of the required data is returned. The following examples show how a recipe can use a series of search queries to search within a data bag named “admins”. For example, to find every administrator: ``` search(:admins, '*:*') ``` Or to search for an administrator named “charlie”: ``` search(:admins, 'id:charlie') ``` Or to search for an administrator with a group identifier of “ops”: ``` search(:admins, 'gid:ops') ``` Or to search for an administrator whose name begins with the letter “c”: ``` search(:admins, 'id:c*') ``` Data bag items that are returned by a search query can be used as if they were a hash. For example: ``` charlie = search(:admins, 'id:charlie').first # => variable 'charlie' is set to the charlie data bag item charlie['gid'] # => "ops" charlie['shell'] # => "/bin/zsh" ``` The following recipe can be used to create a user for each administrator by loading all of the items from the “admins” data bag, looping through each admin in the data bag, and then creating a user resource so that each of those admins exist: ``` admins = data_bag('admins') admins.each do |login| admin = data_bag_item('admins', login) home = "/home/#{login}" user(login) do uid admin['uid'] gid admin['gid'] shell admin['shell'] comment admin['comment'] home home manage_home true end end ``` And then the same recipe, modified to load administrators using a search query (and using an array to store the results of the search query): ``` admins = [] search(:admins, '*:*').each do |admin| login = admin['id'] admins << login home = "/home/#{login}" user(login) do uid admin['uid'] gid admin['gid'] shell admin['shell'] comment admin['comment'] home home manage_home true end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_search/About Handlers ============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/handlers.md) Use a handler to identify situations that arise during a Chef Infra Client run, and then tell Chef Infra Client how to handle these situations when they occur. There are three types of handlers: | Handler | Description | | --- | --- | | exception | An exception handler is used to identify situations that have caused a Chef Infra Client run to fail. An exception handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the **chef_handler** resource to a node's run-list. An exception handler runs when the `failed?` property for the `run_status` object returns `true`. | | report | A report handler is used when a Chef Infra Client run succeeds and reports back on certain details about that Chef Infra Client run. A report handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the **chef_handler** resource to a node's run-list. A report handler runs when the `success?` property for the `run_status` object returns `true`. | | start | A start handler is used to run events at the beginning of a Chef Infra Client run. A start handler can be loaded at the start of a Chef Infra Client run by adding the start handler to the `start_handlers` setting in the client.rb file or by installing the gem that contains the start handler by using the **chef_gem** resource in a recipe in the **chef-client** cookbook. (A start handler may not be loaded using the `chef_handler` resource.) | Exception/Report Handlers ------------------------- Exception and report handlers are used to trigger certain behaviors in response to specific situations, typically identified during a Chef Infra Client run. * An exception handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run fails. * A report handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run is successful. Both types of handlers can be used to gather data about a Chef Infra Client run and can provide rich levels of data about all types of usage, which can be used later for trending and analysis across the entire organization. Exception and report handlers are made available to a Chef Infra Client run in one of the following ways: * By adding the **chef_handler** resource to a recipe, and then adding that recipe to the run-list for a node. (The **chef_handler** resource is available from the **chef_handler** cookbook.) * By adding the handler to one of the following settings in the node’s client.rb file: `exception_handlers` and/or `report_handlers` ### Run from Recipes The **chef_handler** resource allows exception and report handlers to be enabled from within recipes, which can then added to the run-list for any node on which the exception or report handler should run. The **chef_handler** resource is available from the **chef_handler** cookbook. To use the **chef_handler** resource in a recipe, add code similar to the following: ``` chef_handler 'name_of_handler' do source '/path/to/handler/handler_name' action :enable end ``` For example, a handler for Growl needs to be enabled at the beginning of a Chef Infra Client run: ``` chef_gem 'chef-handler-growl' ``` and then is activated in a recipe by using the **chef_handler** resource: ``` chef_handler 'Chef::Handler::Growl' do source 'chef/handler/growl' action :enable end ``` ### Run from client.rb A simple exception or report handler may be installed and configured at run-time. This requires editing of a node’s client.rb file to add the appropriate setting and information about that handler to the client.rb or solo.rb files. Depending on the handler type, one (or more) of the following settings must be added: | Setting | Description | | --- | --- | | `exception_handlers` | A list of exception handlers that are available to Chef Infra Client during a Chef Infra Client run. | | `report_handlers` | A list of report handlers that are available to Chef Infra Client during a Chef Infra Client run. | When this approach is used, the client.rb file must also tell Chef Infra Client how to install and run the handler. There is no default install location for handlers. The simplest way to distribute and install them is via RubyGems, though other methods such as GitHub or HTTP will also work. Once the handler is installed on the system, enable it in the client.rb file by requiring it. After the handler is installed, it may require additional configuration. This will vary from handler to handler. If a handler is a very simple handler, it may only require the creation of a new instance. For example, if a handler named `MyOrg::EmailMe` is hardcoded for all of the values required to send email, a new instance is required. And then the custom handler must be associated with each of the handler types for which it will run. For example: ``` require '/var/chef/handlers/email_me' # the installation path email_handler = MyOrg::EmailMe.new # a simple handler start_handlers << email_handler # run at the start of the run report_handlers << email_handler # run at the end of a successful run exception_handlers << email_handler # run at the end of a failed run ``` Start Handlers -------------- A start handler is not loaded into a Chef Infra Client run from a recipe, but is instead listed in the client.rb file using the `start_handlers` attribute. The start handler must be installed on the node and be available to Chef Infra Client prior to the start of a Chef Infra Client run. Use the **chef-client** cookbook to install the start handler. Start handlers are made available to a Chef Infra Client run in one of the following ways: * By adding a start handler to the **chef-client** cookbook, which installs the handler on the node so that it is available to Chef Infra Client at the start of a Chef Infra Client run * By adding the handler to one of the following settings in the node’s client.rb file: `start_handlers` ### Run from Recipes The **chef-client** cookbook can be configured to automatically install and configure gems that are required by a start handler. For example: ``` node.override['chef_client']['load_gems']['chef-reporting'] = { require_name: 'chef_reporting', action: :install, } node.override['chef_client']['config']['start_handlers'] = [ { class: 'Chef::Reporting::StartHandler', arguments: [], }, ] include_recipe 'chef-client::config' ``` ### Run from client.rb A start handler can be configured in the client.rb file by adding the following setting: | Setting | Description | | --- | --- | | `start_handlers` | A list of start handlers that are available to Chef Infra Client at the start of a Chef Infra Client run. | For example, the Reporting start handler adds the following code to the top of the client.rb file: ``` begin require 'chef_reporting' start_handlers << Chef::Reporting::StartHandler.new() rescue LoadError Chef::Log.warn 'Failed to load #{lib}. This should be resolved after a chef run.' end ``` This ensures that when a Chef Infra Client run begins the `chef_reporting` event handler is enabled. The `chef_reporting` event handler is part of a gem named `chef-reporting`. The **chef_gem** resource is used to install this gem: ``` chef_gem 'chef-reporting' do action :install end ``` Event Handlers -------------- Use the Handler DSL to attach a callback to an event. If the event occurs during a Chef Infra Client run, the associated callback is executed. For example: * Sending email if a Chef Infra Client run fails * Aggregating statistics about resources updated during a Chef Infra Client runs to StatsD ### on Method Use the `on` method to associate an event type with a callback. The callback defines what steps are taken if the event occurs during a Chef Infra Client run and is defined using arbitrary Ruby code. The syntax is as follows: ``` Chef.event_handler do on :event_type do # some Ruby end end ``` where * `Chef.event_handler` declares a block of code within a recipe that is processed when the named event occurs during a Chef Infra Client run * `on` defines the block of code that will tell Chef Infra Client how to handle the event * `:event_type` is a valid exception event type, such as `:run_start`, `:run_failed`, `:converge_failed`, `:resource_failed`, or `:recipe_not_found` For example: ``` Chef.event_handler do on :converge_start do puts "Ohai! I have started a converge." end end ``` ### Event Types The following table describes the events that may occur during a Chef Infra Client run. Each of these events may be referenced in an `on` method block by declaring it as the event type. | Event | Description | | --- | --- | | `:run_start` | The start of a Chef Infra Client run. | | `:run_started` | The Chef Infra Client run has started. | | `:run_completed` | The Chef Infra Client run has completed. | | `:run_failed` | The Chef Infra Client run has failed. | | `:ohai_completed` | The Ohai run has completed. | | `:skipping_registration` | The Chef Infra Client is not registering with the Chef Infra Server because it already has a private key or because it does not need one. | | `:registration_start` | The Chef Infra Client is attempting to create a private key with which to register to the Chef Infra Server. | | `:registration_completed` | The Chef Infra Client created its private key successfully. | | `:registration_failed` | The Chef Infra Client encountered an error and was unable to register with the Chef Infra Server. | | `:node_load_start` | The Chef Infra Client is attempting to load node data from the Chef Infra Server. | | `:node_load_success` | The Chef Infra Client successfully loaded node data from the policy builder. | | `:node_load_failed` | The Chef Infra Client encountered an error and was unable to load node data from the Chef Infra Server. | | `:run_list_expand_failed` | The Chef Infra Client failed to expand the run-list. | | `:node_load_completed` | The Chef Infra Client successfully loaded node data from the Chef Infra Server. Default and override attributes for roles have been computed, but are not yet applied. | | `:policyfile_loaded` | The policy file was loaded. | | `:cookbook_resolution_start` | The Chef Infra Client is attempting to pull down the cookbook collection from the Chef Infra Server. | | `:cookbook_resolution_failed` | The Chef Infra Client failed to pull down the cookbook collection from the Chef Infra Server. | | `:cookbook_resolution_complete` | The Chef Infra Client successfully pulled down the cookbook collection from the Chef Infra Server. | | `:cookbook_clean_start` | The Chef Infra Client is attempting to remove unneeded cookbooks. | | `:removed_cookbook_file` | The Chef Infra Client removed a file from a cookbook. | | `:cookbook_clean_complete` | The Chef Infra Client is done removing cookbooks and/or cookbook files. | | `:cookbook_sync_start` | The Chef Infra Client is attempting to synchronize cookbooks. | | `:synchronized_cookbook` | The Chef Infra Client is attempting to synchronize the named cookbook. | | `:updated_cookbook_file` | The Chef Infra Client updated the named file in the named cookbook. | | `:cookbook_sync_failed` | The Chef Infra Client was unable to synchronize cookbooks. | | `:cookbook_sync_complete` | The Chef Infra Client is finished synchronizing cookbooks. | | `:cookbook_gem_start` | The Chef Infra Client is collecting gems from the cookbooks. | | `:cookbook_gem_installing` | The Chef Infra Client is installing a cookbook gem. | | `:cookbook_gem_using` | The Chef Infra Client is using a cookbook gem. | | `:cookbook_gem_finished` | The Chef Infra Client finished installing cookbook gems. | | `:cookbook_gem_failed` | The Chef Infra Client failed to install cookbook gems. | | `:cookbook_compilation_start` | The Chef Infra Client created the run_context and is starting cookbook compilation. | | `:library_load_start` | The Chef Infra Client is loading library files. | | `:library_file_loaded` | The Chef Infra Client successfully loaded the named library file. | | `:library_file_load_failed` | The Chef Infra Client was unable to load the named library file. | | `:library_load_complete` | The Chef Infra Client is finished loading library files. | | `:lwrp_load_start` | The Chef Infra Client is loading custom resources. | | `:lwrp_file_loaded` | The Chef Infra Client successfully loaded the named custom resource. | | `:lwrp_file_load_failed` | The Chef Infra Client was unable to load the named custom resource. | | `:lwrp_load_complete` | The Chef Infra Client is finished loading custom resources. | | `:ohai_plugin_load_start` | Ohai has started loading plugins. | | `:ohai_plugin_file_loaded` | Ohai has loaded a plugin. | | `:ohai_plugin_file_load_failed` | Ohai failed to load a plugin. | | `:ohai_plugin_load_complete` | Ohai has completed loading plugins. | | `:attribute_load_start` | The Chef Infra Client is loading attribute files. | | `:attribute_file_loaded` | The Chef Infra Client successfully loaded the named attribute file. | | `:attribute_file_load_failed` | The Chef Infra Client was unable to load the named attribute file. | | `:attribute_load_complete` | The Chef Infra Client is finished loading attribute files. | | `:definition_load_start` | The Chef Infra Client is loading definitions. | | `:definition_file_loaded` | The Chef Infra Client successfully loaded the named definition. | | `:definition_file_load_failed` | The Chef Infra Client was unable to load the named definition. | | `:definition_load_complete` | The Chef Infra Client is finished loading definitions. | | `:recipe_load_start` | The Chef Infra Client is loading recipes. | | `:recipe_file_loaded` | The Chef Infra Client successfully loaded the named recipe. | | `:recipe_file_load_failed` | The Chef Infra Client was unable to load the named recipe. | | `:recipe_not_found` | The Chef Infra Client was unable to find the named recipe. | | `:recipe_load_complete` | The Chef Infra Client is finished loading recipes. | | `:cookbook_compilation_complete` | The Chef Infra Client completed all cookbook compilation phases. | | `:converge_start` | The Chef Infra Client run converge phase has started. | | `:action_collection_registration` | Provides a reference to the action_collection before cookbooks are compiled. | | `:converge_complete` | The Chef Infra Client run converge phase is complete. | | `:converge_failed` | The Chef Infra Client run converge phase has failed. | | `:control_group_started` | The named control group is being processed. | | `:control_example_success` | The named control group has been processed. | | `:control_example_failure` | The named control group's processing has failed. | | `:resource_action_start` | A resource action is starting. | | `:resource_skipped` | A resource action was skipped. | | `:resource_current_state_loaded` | A resource's current state was loaded. | | `:resource_after_state_loaded` | A resource's after state was loaded. | | `:resource_current_state_load_bypassed` | A resource's current state was not loaded because the resource does not support why-run mode. | | `:resource_bypassed` | A resource action was skipped because the resource does not support why-run mode. | | `:resource_update_applied` | A change has been made to a resource. (This event occurs for each change made to a resource.) | | `:resource_update_progress` | A resource sent a progress notification to the user to indicate overall progress of a long running operation. | | `:resource_failed_retriable` | A resource action has failed and will be retried. | | `:resource_failed` | A resource action has failed and will not be retried. | | `:resource_updated` | A resource requires modification. | | `:resource_up_to_date` | A resource is already correct. | | `:resource_completed` | All actions for the resource are complete. | | `:stream_opened` | A stream has opened. | | `:stream_closed` | A stream has closed. | | `:stream_output` | A chunk of data from a single named stream. | | `:handlers_start` | The handler processing phase of a Chef Infra Client run has started. | | `:handler_executed` | The named handler was processed. | | `:handlers_completed` | The handler processing phase of a Chef Infra Client run is complete. | | `:provider_requirement_failed` | An assertion declared by a provider has failed. | | `:whyrun_assumption` | An assertion declared by a provider has failed, but execution is allowed to continue because the Chef Infra Client is running in why-run mode. | `:deprecation` | A deprecation message has been emitted. || `:attribute_changed` | Prints out all the attribute changes in cookbooks or sets a policy that override attributes should never be used. | ### Examples The following examples show ways to use the Handler DSL. #### Send Email Use the `on` method to create an event handler that sends email when a Chef Infra Client run fails. This will require: * A way to tell Chef Infra Client how to send email * An event handler that describes what to do when the `:run_failed` event is triggered * A way to trigger the exception and test the behavior of the event handler ##### Define How Email is Sent Use a library to define the code that sends email when a Chef Infra Client run fails. Name the file `helper.rb` and add it to a cookbook’s `/libraries` directory: ``` require 'net/smtp' module HandlerSendEmail class Helper def send_email_on_run_failure(node_name) message = "From: Chef <<EMAIL>>\n" message << "To: Grant <<EMAIL>>\n" message << "Subject: Chef run failed\n" message << "Date: #{Time.now.rfc2822}\n\n" message << "Chef run failed on #{node_name}\n" Net::SMTP.start('localhost', 25) do |smtp| smtp.send_message message, '<EMAIL>', '<EMAIL>' end end end end ``` ##### Add the Handler Invoke the library helper in a recipe: ``` Chef.event_handler do on :run_failed do HandlerSendEmail::Helper.new.send_email_on_run_failure( Chef.run_context.node.name ) end end ``` * Use `Chef.event_handler` to define the event handler * Use the `on` method to specify the event type Within the `on` block, tell Chef Infra Client how to handle the event when it’s triggered. ##### Test the Handler Use the following code block to trigger the exception and have the Chef Infra Client send email to the specified email address: ``` ruby_block 'fail the run' do block do raise 'deliberately fail the run' end end ``` #### etcd Locks The following example shows how to prevent concurrent Chef Infra Client runs from both holding a lock on etcd: ``` lock_key = "#{node.chef_environment}/#{node.name}" Chef.event_handler do on :converge_start do |run_context| Etcd.lock_acquire(lock_key) end end Chef.event_handler do on :converge_complete do Etcd.lock_release(lock_key) end end ``` #### HipChat Notifications Event messages can be sent to a team communication tool like HipChat. For example, if a Chef Infra Client run fails: ``` Chef.event_handler do on :run_failed do |exception| hipchat_notify exception.message end end ``` or send an alert on a configuration change: ``` Chef.event_handler do on :resource_updated do |resource, action| if resource.to_s == 'template[/etc/nginx/nginx.conf]' Helper.hipchat_message("#{resource} was updated by chef") end end end ``` Handlers and Cookbooks ---------------------- The following cookbooks can be used to load handlers during a Chef InfraClient run. ### chef_handler Exception and report handlers can be distributed using the **chef_handler** resource. This resource is included with Chef 14 and above. It can be used to enable custom handlers from within recipes and to include product-specific handlers from cookbooks. See the [chef_handler Resource](../resources/chef_handler/index) documentation for more information. ### Chef Infra Client Start handlers can be distributed using the **chef-client** cookbook, which will install the handler on the target node during the initial configuration of the node. This ensures that the start handler is always present on the node so that it is available to Chef Infra Client at the start of every run. Custom Handlers --------------- A custom handler can be created to support any situation. The easiest way to build a custom handler: 1. Download the **chef_handler** cookbook 2. Create a custom handler 3. Write a recipe using the **chef_handler** resource 4. Add that recipe to a node’s run-list, often as the first recipe in that run-list ### Syntax The syntax for a handler can vary, depending on what the the situations the handler is being asked to track, the type of handler being used, and so on. All custom exception and report handlers are defined using Ruby and must be a subclass of the `Chef::Handler` class. ``` require 'chef/log' module ModuleName class HandlerName < Chef::Handler def report # Ruby code goes here end end end ``` where: * `require` ensures that the logging functionality of Chef Infra Client is available to the handler * `ModuleName` is the name of the module as it exists within the `Chef` library * `HandlerName` is the name of the handler as it is used in a recipe * `report` is an interface that is used to define the custom handler For example, the following shows a custom handler that sends an email that contains the exception data when a Chef Infra Client run fails: ``` require 'net/smtp' module OrgName class SendEmail < Chef::Handler def report if run_status.failed? message = "From: sender_name <<EMAIL>>\n" message << "To: recipient_address <<EMAIL>>\n" message << "Subject: chef-client Run Failed\n" message << "Date: #{Time.now.rfc2822}\n\n" message << "Chef run failed on #{node.name}\n" message << "#{run_status.formatted_exception}\n" message << Array(backtrace).join('\n') Net::SMTP.start('your.smtp.server', 25) do |smtp| smtp.send_message message, 'sender@example', 'recipient@example' end end end end end ``` and then is used in a recipe like: ``` send_email 'blah' do # recipe code end ``` ### report Interface The `report` interface is used to define how a handler will behave and is a required part of any custom handler. The syntax for the `report` interface is as follows: ``` def report # Ruby code end ``` The Ruby code used to define a custom handler will vary significantly from handler to handler. Chef Infra Client includes two default handlers: `error_report` and `json_file`. Their use of the `report` interface is shown below. The [error_report](https://github.com/chef/chef/blob/main/lib/chef/handler/error_report.rb) handler: ``` require 'chef/handler' require 'chef/resource/directory' class Chef class Handler class ErrorReport < ::Chef::Handler def report Chef::FileCache.store('failed-run-data.json', Chef::JSONCompat.to_json_pretty(data), 0640) Chef::Log.fatal("Saving node information to #{Chef::FileCache.load('failed-run-data.json', false)}") end end end end ``` The [json_file](https://github.com/chef/chef/blob/main/lib/chef/handler/json_file.rb) handler: ``` require 'chef/handler' require 'chef/resource/directory' class Chef class Handler class JsonFile < ::Chef::Handler attr_reader :config def initialize(config = {}) @config = config @config[:path] ||= '/var/chef/reports' @config end def report if exception Chef::Log.error('Creating JSON exception report') else Chef::Log.info('Creating JSON run report') end build_report_dir savetime = Time.now.strftime('%Y%m%d%H%M%S') File.open(File.join(config[:path], 'chef-run-report-#{savetime}.json'), 'w') do |file| run_data = data run_data[:start_time] = run_data[:start_time].to_s run_data[:end_time] = run_data[:end_time].to_s file.puts Chef::JSONCompat.to_json_pretty(run_data) end end def build_report_dir unless File.exist?(config[:path]) FileUtils.mkdir_p(config[:path]) File.chmod(00700, config[:path]) end end end end end ``` ### Optional Interfaces The following interfaces may be used in a handler in the same way as the `report` interface to override the default handler behavior in Chef Infra Client. That said, the following interfaces are not typically used in a handler and, for the most part, are completely unnecessary for a handler to work properly and/or as desired. #### data The `data` method is used to return the Hash representation of the `run_status` object. For example: ``` def data @run_status.to_hash end ``` #### run_report_safely The `run_report_safely` method is used to run the report handler, rescuing and logging errors that may arise as the handler runs and ensuring that all handlers get a chance to run during a Chef Infra Client run (even if some handlers fail during that run). In general, this method should never be used as an interface in a custom handler unless this default behavior simply must be overridden. ``` def run_report_safely(run_status) run_report_unsafe(run_status) rescue Exception => e Chef::Log.error('Report handler #{self.class.name} raised #{e.inspect}') Array(e.backtrace).each { |line| Chef::Log.error(line) } ensure @run_status = nil end ``` #### run_report_unsafe The `run_report_unsafe` method is used to run the report handler without any error handling. This method should never be used directly in any handler, except during testing of that handler. For example: ``` def run_report_unsafe(run_status) @run_status = run_status report end ``` ### run_status Object The `run_status` object is initialized by Chef Infra Client before the `report` interface is run for any handler. The `run_status` object keeps track of the status of a Chef Infra Client run and will contain some (or all) of the following properties: | Property | Description | | --- | --- | | `all_resources` | A list of all resources that are included in the `resource_collection` property for the current Chef Infra Client run. | | `backtrace` | A backtrace associated with the uncaught exception data that caused a Chef Infra Client run to fail, if present; `nil` for a successful Chef Infra Client run. | | `elapsed_time` | The amount of time between the start (`start_time`) and end (`end_time`) of a Chef Infra Client run. | | `end_time` | The time at which a Chef Infra Client run ended. | | `exception` | The uncaught exception data which caused a Chef Infra Client run to fail; `nil` for a successful Chef Infra Client run. | | `failed?` | Show that a Chef Infra Client run has failed when uncaught exceptions were raised during a Chef Infra Client run. An exception handler runs when the `failed?` indicator is `true`. | | `node` | The node on which a Chef Infra Client run occurred. | | `run_context` | An instance of the `Chef::RunContext` object; used by Chef Infra Client to track the context of the run; provides access to the `cookbook_collection`, `resource_collection`, and `definitions` properties. | | `start_time` | The time at which a Chef Infra Client run started. | | `success?` | Show that a Chef Infra Client run succeeded when uncaught exceptions were not raised during a Chef Infra Client run. A report handler runs when the `success?` indicator is `true`. | | `updated_resources` | A list of resources that were marked as updated as a result of a Chef Infra Client run. | Note These properties are not always available. For example, a start handler runs at the beginning of Chef Infra Client run, which means that properties like `end_time` and `elapsed_time` are still unknown and will be unavailable to the `run_status` object. Examples -------- The following sections show examples of handlers. ### Cookbook Versions Community member `juliandunn` created a custom [report handler that logs all of the cookbooks and cookbook versions](https://github.com/juliandunn/cookbook_versions_handler) that were used during a Chef Infra Client run, and then reports after the run is complete. This handler requires the **chef_handler** resource (which is available from the **chef_handler** cookbook). #### cookbook_versions.rb The following custom handler defines how cookbooks and cookbook versions that are used during a Chef Infra Client run will be compiled into a report using the `Chef::Log` class in Chef Infra Client: ``` require 'chef/log' module Opscode class CookbookVersionsHandler < Chef::Handler def report cookbooks = run_context.cookbook_collection Chef::Log.info('Cookbooks and versions run: #{cookbooks.keys.map {|x| cookbooks[x].name.to_s + ' ' + cookbooks[x].version} }') end end end ``` #### default.rb The following recipe is added to the run-list for every node on which a list of cookbooks and versions will be generated as report output after every Chef Infra Client run. ``` include_recipe 'chef_handler' cookbook_file "#{node['chef_handler']['handler_path']}/cookbook_versions.rb" do source 'cookbook_versions.rb' owner 'root' group 'root' mode '0755' action :create end chef_handler 'Opscode::CookbookVersionsHandler' do source "#{node['chef_handler']['handler_path']}/cookbook_versions.rb" supports :report => true action :enable end ``` This recipe will generate report output similar to the following: ``` [2013-11-26T03:11:06+00:00] INFO: Chef Run complete in 0.300029878 seconds [2013-11-26T03:11:06+00:00] INFO: Running report handlers [2013-11-26T03:11:06+00:00] INFO: Cookbooks and versions run: ["chef_handler 1.1.4", "cookbook_versions_handler 1.0.0"] [2013-11-26T03:11:06+00:00] INFO: Report handlers complete ``` ### Reporting Start handler functionality was added when Chef started building add-ons for the Chef Infra Server. The Reporting add-on is designed to create reporting data based on a Chef Infra Client run. And since Reporting needs to be able to collect data for the entire Chef Infra Client run, Reporting needs to be enabled before anything else happens at the start of a Chef Infra Client run. Note The start handler used by the Reporting add-on for the Chef Infra Server is always installed using the **chef-client** cookbook. #### start_handler.rb The following code shows the start handler used by the Reporting add-in for the Chef Infra Server: ``` require 'chef/handler' require 'chef/rest' require 'chef/version_constraint' class Chef class Reporting class StartHandler < ::Chef::Handler attr_reader :config def initialize(config = {}) @config = config end def report version_checker = Chef::VersionConstraint.new('< 11.6.0') if version_checker.include?(Chef::VERSION) Chef::Log.info('Enabling backported resource reporting Handler') rest = Chef::REST.new(Chef::Config[:chef_server_url], @run_status.node.name, Chef::Config[:client_key]) resource_reporter = Chef::Reporting::ResourceReporter.new(rest) @run_status.events.register(resource_reporter) resource_reporter.run_started(@run_status) else Chef::Log.debug('Chef Version already has new Resource Reporter - skipping startup of backport version') end end end end end ``` ### json_file Handler The [json_file](https://github.com/chef/chef/blob/main/lib/chef/handler/json_file.rb) handler is available from the **chef_handler** cookbook and can be used with exceptions and reports. It serializes run status data to a JSON file. This handler may be enabled in one of the following ways. By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how Chef Infra Client is being run: ``` require 'chef/handler/json_file' report_handlers << Chef::Handler::JsonFile.new(:path => '/var/chef/reports') exception_handlers << Chef::Handler::JsonFile.new(:path => '/var/chef/reports') ``` By using the **chef_handler** resource in a recipe, similar to the following: ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments :path => '/var/chef/reports' action :enable end ``` After it has run, the run status data can be loaded and inspected via Interactive Ruby (IRb): ``` irb(main):002:0> require 'json' => true irb(main):003:0> require 'chef' => true irb(main):004:0> r = JSON.parse(IO.read('/var/chef/reports/chef-run-report-20110322060731.json')) => ... output truncated irb(main):005:0> r.keys => ['end_time', 'node', 'updated_resources', 'exception', 'all_resources', 'success', 'elapsed_time', 'start_time', 'backtrace'] irb(main):006:0> r['elapsed_time'] => 0.00246 ``` ### error_report Handler The [error_report](https://github.com/chef/chef/blob/main/lib/chef/handler/error_report.rb) handler is built into Chef Infra Client and can be used for both exceptions and reports. It serializes error report data to a JSON file. This handler may be enabled in one of the following ways. By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how Chef Infra Client is being run: ``` require 'chef/handler/error_report' report_handlers << Chef::Handler::ErrorReport.new() exception_handlers << Chef::Handler::ErrorReport.new() ``` By using the [chef_handler](../resources/chef_handler/index) resource in a recipe, similar to the following: ``` chef_handler 'Chef::Handler::ErrorReport' do source 'chef/handler/error_report' action :enable end ``` ### Community Handlers The following open source handlers are available from the Chef community: | Handler | Description | | --- | --- | | [Airbrake](https://github.com/timops/ohai-plugins/blob/master/win32_svc.rb) | A handler that sends exceptions (only) to Airbrake, an application that collects data and aggregates it for review. | | [Asynchronous Resources](https://github.com/rottenbytes/chef/tree/master/async_handler) | A handler that asynchronously pushes exception and report handler data to a STOMP queue, from which data can be processed into data storage. | | [Campfire](https://github.com/ampledata/chef-handler-campfire) | A handler that collects exception and report handler data and reports it to Campfire, a web-based group chat tool. | | [Datadog](https://github.com/DataDog/chef-handler-datadog) | A handler that collects Chef Infra Client stats and sends them into a Datadog newsfeed. | | [Flowdock](https://github.com/mmarschall/chef-handler-flowdock) | A handler that collects exception and report handler data and sends it to users via the Flowdock API.. | | [Graphite](https://github.com/imeyer/chef-handler-graphite/wiki) | A handler that collects exception and report handler data and reports it to Graphite, a graphic rendering application. | | [Graylog2 GELF](https://github.com/jellybob/chef-gelf/) | A handler that provides exception and report handler status (including changes) to a Graylog2 server, so that the data can be viewed using Graylog Extended Log Format (GELF). | | [Growl](https://rubygems.org/gems/chef-handler-growl) | A handler that collects exception and report handler data and then sends it as a Growl notification. | | [HipChat](https://github.com/mojotech/hipchat/blob/master/lib/hipchat/chef.rb) | A handler that collects exception handler data and sends it to HipChat, a hosted private chat service for companies and teams. | | [IRC Snitch](https://rubygems.org/gems/chef-irc-snitch) | A handler that notifies administrators (via Internet Relay Chat (IRC)) when a Chef Infra Client run fails. | | [Journald](https://github.com/marktheunissen/chef-handler-journald) | A handler that logs an entry to the systemd journal with the Chef Infra Client run status, exception details, configurable priority, and custom details. | | [net/http](https://github.com/b1-systems/chef-handler-httpapi/) | A handler that reports the status of a Chef run to any API via net/HTTP. | | [Simple Email](https://rubygems.org/gems/chef-handler-mail) | A handler that collects exception and report handler data and then uses pony to send email reports that are based on `.erb` (Embedded Ruby ) templates. | | [SNS](http://onddo.github.io/chef-handler-sns/) | A handler that notifies exception and report handler data and sends it to a SNS topic. | | [Slack](https://github.com/rackspace-cookbooks/chef-slack_handler) | A handler to send Chef Infra Client run notifications to a Slack channel. | | [Splunk Storm](http://ampledata.org/splunk_storm_chef_handler.html) | A handler that supports exceptions and reports for Splunk Storm. | | [Syslog](https://github.com/jblaine/syslog_handler) | A handler that logs basic essential information, such as about the success or failure of a Chef Infra Client run. | | [Updated Resources](https://rubygems.org/gems/chef-handler-updated-resources) | A handler that provides a simple way to display resources that were updated during a Chef Infra Client run. | | [ZooKeeper](http://onddo.github.io/chef-handler-zookeeper/) | A Chef report handler to send Chef run notifications to ZooKeeper. | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/handlers/About Policyfiles ================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/policyfile.md) A Policyfile is a way to create immutable collections of cookbooks, cookbook dependencies, and attributes defined in a single document that is uploaded to the Chef Infra Server. The Policyfile is then associated with a group of nodes. When these nodes perform a Chef Infra Client run, they utilize recipes specified in the Policyfile. Why Policyfiles? ---------------- Policyfiles make it easier to test and promote code safely with a simpler interface. Using a Policyfile improves the user experience and resolves real-world problems that some workflows built around Chef Infra must deal with. The following sections discuss in more detail some of the good reasons to use Policyfile, including: * Focus the workflow on the entire system * Safer development workflows * Less expensive computation * Code visibility * Role mutability * Cookbook mutability * Replaces Berkshelf and the environment cookbook pattern ### Focused System Workflows The knife command line tool maps very closely to the Chef Infra Server API and the objects defined by it: roles, environments, run-lists, cookbooks, data bags, nodes, and so on. Chef Infra Client assembles these pieces at run-time and configures a host to do useful work. Policyfile focuses that workflow onto the entire system, rather than the individual components. For example, Policyfile describes whole systems, whereas each individual revision of the `Policyfile.lock.json` file uploaded to the Chef Infra Server describes a part of that system, inclusive of roles, environments, cookbooks, and the other Chef Infra Server objects necessary to configure that part of the system. ### Safer Workflows Policyfile encourages safer workflows by making it easier to publish development versions of cookbooks to the Chef Infra Server without the risk of mutating the production versions and without requiring a complicated versioning scheme to work around cookbook mutability issues. Roles are mutable and those changes are applied only to the nodes specified by the policy. Policyfile does not require any changes to your normal workflows. Use the same repositories you are already using, the same cookbooks, and workflows. Policyfile will prevent an updated cookbook or role from being applied immediately to all machines. ### Code Visibility When running Chef Infra without a Policyfile, the exact set of cookbooks that are applied to a node is defined by: * The node’s `run_list` property * Any roles that are present in the node’s run-list or recursively included by those roles * The environment, which may restrict the set of valid cookbook versions for a node based on a variety of constraint operators * Dependencies, as defined by each cookbook’s metadata * Dependency resolution picks the “best” set of cookbooks that meet dependency and environment criteria These conditions are re-evaluated every time Chef Infra Client runs, which can make it harder to know which cookbooks will be run by Chef Infra Client or what the effects of updating a role or uploading a new cookbook will be. Policyfile simplifies this behavior by computing the cookbook set on the workstation, and then producing a readable document of that solution: a `Policyfile.lock.json` file. This pre-computed file is uploaded to the Chef Infra Server, and is then used in each Chef Infra Client run that is managed by that particular policy name and policy group. ### Less Expensive Computation When running Chef Infra without Policyfile, the Chef Infra Server loads dependency data for all known versions of all known cookbooks, and then runs an expensive computation to determine the correct set. Policyfile moves this computation to the workstation, where it is done less frequently. ### Role and Environment Mutability When running Chef Infra without Policyfile roles and environments are global objects. Changes to roles and environments are applied immediately to any node that contains that role in its run-list or belong to a particular environment. This can make it hard to update roles and environments and in some use cases discourages using them at all. Policyfile effectively replaces roles and environments. Policyfile files are versioned automatically and new versions are applied to systems only when promoted. ### Cookbook Mutability When running Chef without Policyfile, existing versions of cookbooks are mutable. This is convenient for many use cases, especially if users upload in-development cookbook revisions to the Chef Infra Server. But this sometimes creates issues that are similar to role mutability by allowing those cookbook changes to be applied immediately to nodes that use that cookbook. Users account for this by rigorous testing processes to ensure that only fully integrated cookbooks are ever published. This process does enforce good development habits, but at the same time it shouldn’t be a required part of a workflow that ends with publishing an in-development cookbook to the Chef Infra Server for testing against real nodes Policyfile solves this issue by using a cookbook publishing API for the Chef Infra Server that does not provide cookbook mutability. Name collisions are prevented by storing cookbooks by name and an opaque identifier that is computed from the content of the cookbook itself. For example, name/version collisions can occur when users temporarily fork an upstream cookbook. Even if the user contributes their change and the maintainer is responsive, there may be a period of time where the user needs their fork in order to make progress. This situation presents a versioning dilemma: if the user doesn’t update their own version, they must overwrite the existing copy of that cookbook on the Chef Infra Server, wheres if they do update the version number it might conflict with the version number of the future release of that upstream cookbook. #### Opaque IDs The opaque identifier that is computed from the content of a cookbook is the only place where an opaque identifier is necessary. When working with Policyfile, be sure to: * Use the same names and version constraints as normal in the `Policyfile.rb` file * Use the same references to cookbooks pulled from Chef Supermarket * Use the same branch, tag, and revision patterns for cookbooks pulled from git * Use the same paths for cookbooks pulled from disk Extra metadata about the cookbook is stored and included in Chef Infra Server API responses and in the `Policyfile.lock.json` file, including the source of a cookbook (Chef Supermarket, git, local disk, etc.), as well as any upstream identifiers, such as git revisions. For cookbooks that are loaded from the local disk that are in a git repo, the upstream URL, current revision ID, and the state of the repo are stored also. The opaque identifier is mostly behind the scenes and is only visible once published to the Chef Infra Server. Cookbooks that are uploaded to the Chef Infra Server may have extended version numbers such as `1.0.0-dev`. ### Environment Cookbooks Policyfile replaces the environment cookbook pattern that is often required by Berkshelf, along with a dependency solver and fetcher. That said, Policyfile does not replace all Berkshelf scenarios. Knife Commands -------------- The following knife commands used to set the policy group and policy name on the Chef Infra Server. For example: ``` knife node policy set test-node 'test-policy-group-name' 'test-policy-name' ``` Policyfile.rb ------------- A Policyfile file allows you to specify in a single document the cookbook revisions and recipes that Chef Infra Client will apply. A Policyfile file is uploaded to the Chef Infra Server, where it is associated with a group of nodes. When these nodes are configured during a Chef Infra Client run, Chef Infra Client will make decisions based on your Policyfile settings and will build a run-list based on that information. A Policyfile file may be versioned, and then promoted through deployment stages to safely and reliably deploy new configuration. ### Syntax A `Policyfile.rb` is a Ruby file in which run-list and cookbook locations are specified. The syntax is as follows: ``` name "name" run_list "ITEM", "ITEM", ... default_source :SOURCE_TYPE, *args cookbook "NAME" [, "VERSION_CONSTRAINT"] [, SOURCE_OPTIONS] ``` ### Settings A `Policyfile.rb` file may contain the following settings: `name "name"` Required. The name of the policy. Use a name that reflects the purpose of the machines against which the policy will run. `run_list "ITEM", "ITEM", ...` Required. The run-list Chef Infra Client will use to apply the policy to one (or more) nodes. `default_source :SOURCE_TYPE, *args` The location in which any cookbooks not specified by `cookbook` are located. Possible values: `chef_repo`, `chef_server`, `:supermarket`, and `:artifactory`. Use more than one `default_source` to specify more than one location for cookbooks. `default_source :supermarket` pulls cookbooks from the public Chef Supermarket. `default_source :supermarket, "https://mysupermarket.example"` pulls cookbooks from a named private Chef Supermarket. `default_source :chef_server, "https://chef-server.example/organizations/example"` pulls cookbooks from the Chef Infra Server. `default_source :chef_repo, "path/to/repo"` pulls cookbooks from a monolithic cookbook repository. This may be a path to the top-level of a cookbook repository or to the `/cookbooks` directory within that repository. `default_source :artifactory, "https://artifactory.example/api/chef/my-supermarket"` pulls cookbooks from an Artifactory server. Requires either `artifactory_api_key` to be set in `config.rb` or `ARTIFACTORY_API_KEY` to be set in your environment. Multiple cookbook sources may be specified. For example from the public Chef Supermarket and a monolithic repository: ``` default_source :supermarket default_source :chef_repo, 'path/to/repo' ``` or from both a public and private Chef Supermarket: ``` default_source :supermarket default_source :supermarket, 'https://supermarket.example' ``` Note If a run-list or any dependencies require a cookbook that is present in more than one source, be explicit about which source is preferred. This will ensure that a cookbook is always pulled from an expected source. For example, an internally-developed cookbook named `chef-client` will conflict with the public `chef-client` cookbook that is maintained by Chef. To specify a named source for a cookbook: ``` default_source :supermarket default_source :supermarket, 'https://supermarket.example' do |s| s.preferred_for 'chef-client' end ``` List multiple cookbooks on the same line: ``` default_source :supermarket default_source :supermarket, 'https://supermarket.example' do |s| s.preferred_for 'chef-client', 'nginx', 'mysql' end ``` `cookbook "NAME" [, "VERSION_CONSTRAINT"] [, SOURCE_OPTIONS]` Add cookbooks to the policy, specify a version constraint, or specify an alternate source location, such as Chef Supermarket. For example, add a cookbook: ``` cookbook 'apache2' ``` Specify a version constraint: ``` run_list 'jenkins::master' # Restrict the jenkins cookbook to version 2.x, greater than 2.1 cookbook 'jenkins', '~> 2.1' ``` Specify an alternate source: ``` cookbook 'my_app', path: 'cookbooks/my_app' ``` or: ``` cookbook 'mysql', github: 'opscode-cookbooks/mysql', branch: 'master' ``` or: ``` cookbook 'chef-ingredient', git: 'https://github.com/chef-cookbooks/chef-ingredient.git', tag: 'v0.12.0' ``` `named_run_list "NAME", "ITEM1", "ITEM2", ...` Specify a named run-list to be used as an alternative to the override run-list. This setting should be used carefully and for specific use cases, like running a small set of recipes to quickly converge configuration for a single application on a host or for one-time setup tasks. For example: ``` named_run_list :update_app, 'my_app_cookbook::default' ``` `include_policy "NAME", *args` Specify a policyfile lock to be merged with this policy. Chef Workstation supports pulling this lock from a local or remote file, from a Chef Infra Server, or from a git repository. When the policyfile lock is included, its run-list will appear before the current policyfile’s run-list. This setting requires that the solved cookbooks appear as-is from the included policyfile lock. If conflicting attributes or cookbooks are provided, an error will be presented. See [RFC097](https://github.com/chef-boneyard/chef-rfc/blob/master/rfc097-policyfile-includes.md) for the full specifications of this feature. Pull the policyfile lock from `./NAME.lock.json`: ``` include_policy 'NAME', path: '.' ``` Pull the policyfile lock from `./foo.lock.json`. ``` include_policy 'NAME', path: './foo.lock.json' ``` Pull the policyfile lock `foo.lock.json` from the `example/foo` Git repository on the `git.example.com` Git server. ``` include_policy 'NAME', git: 'https://git.example.com/example/foo', path: 'foo.lock.json' ``` Pull the policyfile lock from `./bar.lock.json` with revision ID ‘revision1’. ``` include_policy 'NAME', policy_revision_id: 'revision1', path: './bar.lock.json' ``` Pull the policyfile lock from a remote server `https://internal.example.com/foo.lock.json`. ``` include_policy 'NAME', remote: 'https://internal.example.com/foo.lock.json' ``` Pull the policyfile lock from a remote server `https://internal.example.com/bar.lock.json` and with revision ID ‘revision1’. ``` include_policy 'NAME', policy_revision_id: 'revision1', remote: 'https://internal.example.com/foo.lock.json' ``` Pull the policy `NAME` with revision ID `revision1` from the `http://chef-server.example` Chef Infra Server: ``` include_policy 'NAME', policy_revision_id: 'revision1', server: 'http://chef-server.example' ``` Pull the policy `foo` with revision ID `revision1`: ``` include_policy 'NAME', policy_name: 'foo', policy_revision_id: 'revision1', server: 'http://chef-server.example' ``` Pull and lock the current revision for policy `foo` in policy group `prod`: ``` include_policy 'NAME', policy_name: 'foo', policy_group: 'prod', server: 'http://chef-server.example' ``` ### Example For example: ``` name 'jenkins-master' run_list 'java', 'jenkins::master', 'recipe[policyfile_demo]' default_source :supermarket, 'https://mysupermarket.example' cookbook 'policyfile_demo', path: 'cookbooks/policyfile_demo' cookbook 'jenkins', '~> 8.2' cookbook 'mysql', github: 'sous-chefs/mysql', branch: 'master' ``` client.rb Settings ------------------ The following settings may be configured in the client.rb file for use with Policyfile: `named_run_list` The run-list associated with a policy file. `policy_group` The name of a policy group that exists on the Chef Infra Server. `policy_name` must also be specified. `policy_name` The name of a policy, as identified by the `name` setting in a `Policyfile.rb` file. `policy_group` must also be specified. `use_policyfile` Chef Infra Client automatically checks the configuration, node JSON, and the stored node on the Chef Infra Server to determine if Policyfile files are being used, and then automatically updates this flag. Default value: `false`. knife bootstrap --------------- A node may be bootstrapped to use Policyfile files. Use the following options as part of the bootstrap command: `--policy-group POLICY_GROUP` The name of a policy group that exists on the Chef Infra Server. `--policy-name POLICY_NAME` The name of a policy, as identified by the `name` setting in a `Policyfile.rb` file. For a customized bootstrap process, add `policy_name` and `policy_group` to the first-boot JSON file that is passed to Chef Infra Client. knife search ------------ The `policy_name` and `policy_group` settings for a node are stored as searchable attributes and as such are available when using a fuzzy matching search pattern. For example: `knife search dev` will return nodes that are part of the `dev` policy group. Test w/Kitchen -------------- Kitchen may be used to test Policyfile files. Add the following to kitchen.yml: ``` provisioner:name:chef_zero ``` A named run-list may be used on a per-suite basis: ``` suites:- name:clientprovisioner:named_run_list:test_client_recipe- name:serverprovisioner:named_run_list:test_server_recipe ``` or globally: ``` provisioner:name:chef_zeronamed_run_list:integration_test_run_list ``` or testing with policies per-suite, once the Policyfile files are available in your repo: ``` suites:- name:defaultmegaprovisioner:policyfile:policies/default.rb- name:defaultultraprovisioner:policyfile:policies/defaulttwo.rb ``` Note As `chef_zero` explicitly tests outside the context of a Chef Infra Server, the `policy_groups` concept is not applicable. The value of `policy_group` during a converge will be set to `local`. chef Commands ------------- The following commands are built into the `chef` executable and support the use of Policyfile files. ### chef clean-policy-cookbooks Use the `chef clean-policy-cookbooks` subcommand to delete cookbooks that are not used by Policyfile files. Cookbooks are considered unused when they are not referenced by any policy revisions on the Chef Infra Server. Note Cookbooks that are referenced by orphaned policy revisions are not removed. Use `chef clean-policy-revisions` to remove orphaned policies. #### Syntax This subcommand has the following syntax: ``` chef clean-policy-cookbooks (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### chef clean-policy-revisions Use the `chef clean-policy-revisions` subcommand to delete orphaned policy revisions to Policyfile files from the Chef Infra Server. An orphaned policy revision is not associated to any policy group and therefore is not in active use by any node. Use `chef show-policy --orphans` to view a list of orphaned policy revisions. #### Syntax This subcommand has the following syntax: ``` chef clean-policy-revisions (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### chef delete-policy Use the `chef delete-policy` subcommand to delete all revisions of the named policy that exist on the Chef Infra Server. (The state of the policy revision is backed up locally and may be restored using the `chef undelete` subcommand.) #### Syntax This subcommand has the following syntax: ``` chef delete-policy POLICY_NAME (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### chef delete-policy-group Use the `chef delete-policy-group` subcommand to delete the named policy group from the Chef Infra Server. Any policy revision associated with that policy group is not deleted. (The state of the policy group is backed up locally and may be restored using the `chef undelete` subcommand.) #### Syntax This subcommand has the following syntax: ``` chef delete-policy-group POLICY_GROUP (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### chef diff Use the `chef diff` subcommand to display an itemized comparison of two revisions of a `Policyfile.lock.json` file. #### Syntax This subcommand has the following syntax: ``` chef diff POLICY_FILE --head | --git POLICY_GROUP | POLICY_GROUP...POLICY_GROUP (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-g GIT_REF`, `--git GIT_REF` Compare the specified git reference against the current revision of a `Policyfile.lock.json` file or against another git reference. `-h`, `--help` Show help for the command. `--head` A shortcut for `chef diff --git HEAD`. When a git-specific flag is not provided, the on-disk `Policyfile.lock.json` file is compared to one on the Chef Infra Server or (if a `Policyfile.lock.json` file is not present on-disk) two `Policyfile.lock.json` files in the specified policy group on the Chef Infra Server are compared. `--[no-]pager` Use `--pager` to enable paged output for a `Policyfile.lock.json` file. Default value: `--pager`. `-v`, `--version` The Chef Infra Client version. #### Examples ##### Compare current lock to latest commit on latest branch ``` chef diff --git HEAD ``` ##### Compare current lock with latest commit on master branch ``` chef diff --git master ``` ##### Compare current lock to specified revision ``` chef diff --git v1.0.0 ``` ##### Compare lock on master branch to lock on revision ``` chef diff --git master...dev ``` ##### Compare lock for version with latest commit on master branch ``` chef diff --git v1.0.0...master ``` ##### Compare current lock with latest lock for policy group ``` chef diff staging ``` ##### Compare locks for two policy group ``` chef diff production...staging ``` ### chef export Use the `chef export` subcommand to create a chef-zero-compatible chef-repo that contains the cookbooks described by a `Policyfile.lock.json` file. After a chef-zero-compatible chef-repo is copied to a node, the policy can be applied locally on that machine by running `chef-client -z` (local mode). #### Syntax This subcommand has the following syntax: ``` chef export POLICY_FILE DIRECTORY (options) ``` #### Options This subcommand has the following options: `-a`, `--archive` Export an archive as a tarball, instead as a directory. Default value: `false`. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-f`, `--force` Remove the contents of the destination directory if that directory is not empty. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### chef generate policyfile Use the `chef generate policyfile` subcommand to generate a file to be used with Policyfile. #### Syntax This subcommand has the following syntax: ``` chef generate policyfile POLICY_NAME (options) ``` #### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### chef generate repo Use the `chef generate repo` subcommand to create a chef-repo. By default, the repo is a cookbook repo with options available to support generating a cookbook that supports Policyfile. Note This subcommand requires using one (or more) of the options (below) to support Policyfile files. #### Syntax This subcommand has the following syntax: ``` chef generate repo REPO_NAME (options) ``` #### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-p`, `--policy-only` Create a repository that does not store cookbook files, only Policyfile files. `-P`, `--policy` Use Policyfile instead of Berkshelf. `-r`, `--roles` Create directories for `/roles` and `/environments` instead of creating directories for Policyfile. `-v`, `--version` The Chef Infra Client version. ### chef install Use the `chef install` subcommand to evaluate a policy file and find a compatible set of cookbooks, build a run-list, cache it locally, and then emit a `Policyfile.lock.json` file that describes the locked policy set. The `Policyfile.lock.json` file may be used to install the locked policy set to other machines and may be pushed to a policy group on the Chef Infra Server to apply that policy to a group of nodes that are under management by Chef. #### Syntax This subcommand has the following syntax: ``` chef install POLICY_FILE (options) ``` #### Options This subcommand has the following options: `-D`, `--debug` Enable stack traces and other debug output. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Policyfile.lock.json When the `chef install` command is run, Chef Workstation caches any necessary cookbooks and emits a `Policyfile.lock.json` file that describes: * The versions of cookbooks in use * A Hash of cookbook content * The source for all cookbooks A `Policyfile.lock.json` file is associated with a specific policy group, i.e. is associated with one (or more) nodes that use the same revision of a given policy. A `Policyfile.lock.json` file is similar to: ``` { "revision_id": "288ed244f8db8bff3caf58147e840bbe079f76e0", "name": "jenkins", "run_list": [ "recipe[java::default]", "recipe[jenkins::master]", "recipe[policyfile_demo::default]" ], "cookbook_locks": { "policyfile_demo": { "version": "0.1.0", "identifier": "f04cc40faf628253fe7d9566d66a1733fb1afbe9", "dotted_decimal_identifier": "67638399371010690.23642238397896298.25512023620585", "source": "cookbooks/policyfile_demo", "cache_key": null, "scm_info": null, "source_options": { "path": "cookbooks/policyfile_demo" } }, "java": { "version": "1.24.0", "identifier": "4c24ae46a6633e424925c24e683e0f43786236a3", "dotted_decimal_identifier": "21432429158228798.18657774985439294.16782456927907", "cache_key": "java-1.24.0-supermarket.chef.io", "origin": "https://supermarket.chef.io/api/v1/cookbooks/java/versions/1.24.0/download", "source_options": { "artifactserver": "https://supermarket.chef.io/api/v1/cookbooks/java/versions/1.24.0/download", "version": "1.24.0" } ``` ### chef push Use the `chef push` subcommand to upload an existing `Policyfile.lock.json` file to the Chef Infra Server, along with all of the cookbooks that are contained in the file. The `Policyfile.lock.json` file will be applied to the specified policy group, which is a set of nodes that share the same run-list and cookbooks. #### Syntax This subcommand has the following syntax: ``` chef push POLICY_GROUP POLICY_FILE (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### chef push-archive The `chef push-archive` subcommand is used to publish a policy archive file to the Chef Infra Server. (A policy archive is created using the `chef export` subcommand.) The policy archive is assigned to the specified policy group, which is a set of nodes that share the same run-list and cookbooks. #### Syntax This subcommand has the following syntax: ``` chef push-archive POLICY_GROUP ARCHIVE_FILE (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### chef show-policy Use the `chef show-policy` subcommand to display revisions for every `Policyfile.rb` file that is on the Chef Infra Server. By default, only active policy revisions are shown. When both a policy and policy group are specified, the contents of the active `Policyfile.lock.json` file for the policy group is returned. #### Syntax This subcommand has the following syntax: ``` chef show-policy POLICY_NAME POLICY_GROUP (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-o`, `--orphans` Show policy revisions that are not currently assigned to any policy group. `--[no-]pager` Use `--pager` to enable paged output for a `Policyfile.lock.json` file. Default value: `--pager`. `-v`, `--version` The Chef Infra Client version. ### chef undelete Use the `chef undelete` subcommand to recover a deleted policy or policy group. This command: * Does not detect conflicts. If a deleted item has been recreated, running this command will overwrite it * Does not include cookbooks that may be referenced by policy files; cookbooks that are cleaned after running this command may not be fully restorable to their previous state * Does not store access control data #### Syntax This subcommand has the following syntax: ``` chef undelete (options) ``` When run with no arguments, returns a list of available operations. #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. `-h`, `--help` Show help for the command. `-i ID`, `--id ID` Undo the delete operation specified by `ID`. `-l`, `--last` Undo the most recent delete operation. `--list` Default. Return a list of available operations. `-v`, `--version` The Chef Infra Client version. ### chef update Use the `chef update` subcommand to read the `Policyfile.rb` file, and then apply any changes. This will resolve dependencies and will create a `Policyfile.lock.json` file. The locked policy will reflect any changes to the run-list and will pull in any cookbook updates that are compatible with any version constraints defined in the `Policyfile.rb` file. #### Syntax This subcommand has the following syntax: ``` chef update POLICY_FILE (options) ``` #### Options This subcommand has the following options: `-a`, `--attributes` Update attributes. Default value: `false`. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/policyfile/Policyfile.rb ============= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/config_rb_policyfile.md) A Policyfile is a way to create immutable collections of cookbooks, cookbook dependencies, and attributes defined in a single document that is uploaded to the Chef Infra Server. The Policyfile is then associated with a group of nodes. When these nodes perform a Chef Infra Client run, they utilize recipes specified in the Policyfile. A Policyfile file allows you to specify in a single document the cookbook revisions and recipes that Chef Infra Client will apply. A Policyfile file is uploaded to the Chef Infra Server, where it is associated with a group of nodes. When these nodes are configured during a Chef Infra Client run, Chef Infra Client will make decisions based on your Policyfile settings and will build a run-list based on that information. A Policyfile file may be versioned, and then promoted through deployment stages to safely and reliably deploy new configuration. Note For more information about Policyfile, see [About Policyfile](../policyfile/index) Syntax ------ A `Policyfile.rb` is a Ruby file in which run-list and cookbook locations are specified. The syntax is as follows: ``` name "name" run_list "ITEM", "ITEM", ... default_source :SOURCE_TYPE, *args cookbook "NAME" [, "VERSION_CONSTRAINT"] [, SOURCE_OPTIONS] ``` Settings -------- A `Policyfile.rb` file may contain the following settings: `name "name"` Required. The name of the policy. Use a name that reflects the purpose of the machines against which the policy will run. `run_list "ITEM", "ITEM", ...` Required. The run-list Chef Infra Client will use to apply the policy to one (or more) nodes. `default_source :SOURCE_TYPE, *args` The location in which any cookbooks not specified by `cookbook` are located. Possible values: `chef_repo`, `chef_server`, `:supermarket`, and `:artifactory`. Use more than one `default_source` to specify more than one location for cookbooks. `default_source :supermarket` pulls cookbooks from the public Chef Supermarket. `default_source :supermarket, "https://mysupermarket.example"` pulls cookbooks from a named private Chef Supermarket. `default_source :chef_server, "https://chef-server.example/organizations/example"` pulls cookbooks from the Chef Infra Server. `default_source :chef_repo, "path/to/repo"` pulls cookbooks from a monolithic cookbook repository. This may be a path to the top-level of a cookbook repository or to the `/cookbooks` directory within that repository. `default_source :artifactory, "https://artifactory.example/api/chef/my-supermarket"` pulls cookbooks from an Artifactory server. Requires either `artifactory_api_key` to be set in `config.rb` or `ARTIFACTORY_API_KEY` to be set in your environment. Multiple cookbook sources may be specified. For example from the public Chef Supermarket and a monolithic repository: ``` default_source :supermarket default_source :chef_repo, 'path/to/repo' ``` or from both a public and private Chef Supermarket: ``` default_source :supermarket default_source :supermarket, 'https://supermarket.example' ``` Note If a run-list or any dependencies require a cookbook that is present in more than one source, be explicit about which source is preferred. This will ensure that a cookbook is always pulled from an expected source. For example, an internally-developed cookbook named `chef-client` will conflict with the public `chef-client` cookbook that is maintained by Chef. To specify a named source for a cookbook: ``` default_source :supermarket default_source :supermarket, 'https://supermarket.example' do |s| s.preferred_for 'chef-client' end ``` List multiple cookbooks on the same line: ``` default_source :supermarket default_source :supermarket, 'https://supermarket.example' do |s| s.preferred_for 'chef-client', 'nginx', 'mysql' end ``` `cookbook "NAME" [, "VERSION_CONSTRAINT"] [, SOURCE_OPTIONS]` Add cookbooks to the policy, specify a version constraint, or specify an alternate source location, such as Chef Supermarket. For example, add a cookbook: ``` cookbook 'apache2' ``` Specify a version constraint: ``` run_list 'jenkins::master' # Restrict the jenkins cookbook to version 2.x, greater than 2.1 cookbook 'jenkins', '~> 2.1' ``` Specify an alternate source: ``` cookbook 'my_app', path: 'cookbooks/my_app' ``` or: ``` cookbook 'mysql', github: 'opscode-cookbooks/mysql', branch: 'master' ``` or: ``` cookbook 'chef-ingredient', git: 'https://github.com/chef-cookbooks/chef-ingredient.git', tag: 'v0.12.0' ``` `named_run_list "NAME", "ITEM1", "ITEM2", ...` Specify a named run-list to be used as an alternative to the override run-list. This setting should be used carefully and for specific use cases, like running a small set of recipes to quickly converge configuration for a single application on a host or for one-time setup tasks. For example: ``` named_run_list :update_app, 'my_app_cookbook::default' ``` `include_policy "NAME", *args` Specify a policyfile lock to be merged with this policy. Chef Workstation supports pulling this lock from a local or remote file, from a Chef Infra Server, or from a git repository. When the policyfile lock is included, its run-list will appear before the current policyfile’s run-list. This setting requires that the solved cookbooks appear as-is from the included policyfile lock. If conflicting attributes or cookbooks are provided, an error will be presented. See [RFC097](https://github.com/chef-boneyard/chef-rfc/blob/master/rfc097-policyfile-includes.md) for the full specifications of this feature. Pull the policyfile lock from `./NAME.lock.json`: ``` include_policy 'NAME', path: '.' ``` Pull the policyfile lock from `./foo.lock.json`. ``` include_policy 'NAME', path: './foo.lock.json' ``` Pull the policyfile lock `foo.lock.json` from the `example/foo` Git repository on the `git.example.com` Git server. ``` include_policy 'NAME', git: 'https://git.example.com/example/foo', path: 'foo.lock.json' ``` Pull the policyfile lock from `./bar.lock.json` with revision ID ‘revision1’. ``` include_policy 'NAME', policy_revision_id: 'revision1', path: './bar.lock.json' ``` Pull the policyfile lock from a remote server `https://internal.example.com/foo.lock.json`. ``` include_policy 'NAME', remote: 'https://internal.example.com/foo.lock.json' ``` Pull the policyfile lock from a remote server `https://internal.example.com/bar.lock.json` and with revision ID ‘revision1’. ``` include_policy 'NAME', policy_revision_id: 'revision1', remote: 'https://internal.example.com/foo.lock.json' ``` Pull the policy `NAME` with revision ID `revision1` from the `http://chef-server.example` Chef Infra Server: ``` include_policy 'NAME', policy_revision_id: 'revision1', server: 'http://chef-server.example' ``` Pull the policy `foo` with revision ID `revision1`: ``` include_policy 'NAME', policy_name: 'foo', policy_revision_id: 'revision1', server: 'http://chef-server.example' ``` Pull and lock the current revision for policy `foo` in policy group `prod`: ``` include_policy 'NAME', policy_name: 'foo', policy_group: 'prod', server: 'http://chef-server.example' ``` Example ------- For example: ``` name 'jenkins-master' run_list 'java', 'jenkins::master', 'recipe[policyfile_demo]' default_source :supermarket, 'https://mysupermarket.example' cookbook 'policyfile_demo', path: 'cookbooks/policyfile_demo' cookbook 'jenkins', '~> 8.2' cookbook 'mysql', github: 'sous-chefs/mysql', branch: 'master' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/config_rb_policyfile/About Data Bags =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/data_bags.md) Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. Create a Data Bag ----------------- A data bag can be created in two ways: using knife or manually. In general, using knife to create data bags is recommended, but as long as the data bag folders and data bag item JSON files are created correctly, either method is safe and effective. ### Create a Data Bag with Knife knife can be used to create data bags and data bag items when the `knife data bag` subcommand is run with the `create` argument. For example: ``` knife data bag create DATA_BAG_NAME (DATA_BAG_ITEM) ``` knife can be used to update data bag items using the `from file` argument: ``` knife data bag from file BAG_NAME ITEM_NAME.json ``` As long as a file is in the correct directory structure, knife will be able to find the data bag and data bag item with only the name of the data bag and data bag item. For example: ``` knife data bag from file BAG_NAME ITEM_NAME.json ``` will load the following file: ``` data_bags/BAG_NAME/ITEM_NAME.json ``` Continuing the example above, if you are in the “admins” directory and make changes to the file charlie.json, then to upload that change to the Chef Infra Server use the following command: ``` knife data bag from file admins charlie.json ``` In some cases, such as when knife is not being run from the root directory for the chef-repo, the full path to the data bag item may be required. For example: ``` knife data bag from file BAG_NAME /path/to/file/ITEM_NAME.json ``` ### Manually One or more data bags and data bag items can be created manually under the `data_bags` directory in the chef-repo. Any method can be used to create the data bag folders and data bag item JSON files. For example: ``` mkdir data_bags/admins ``` would create a data bag folder named “admins”. The equivalent command for using knife is: ``` knife data bag create admins ``` A data bag item can be created manually in the same way as the data bag, but by also specifying the file name for the data bag item (this example is using vi, a visual editor for UNIX): ``` vi data_bags/admins/charlie.json ``` would create a data bag item named “charlie.json” under the “admins” sub-directory in the `data_bags` directory of the chef-repo. The equivalent command for using knife is: ``` knife data bag create admins charlie ``` Store Data in a Data Bag ------------------------ When the chef-repo is cloned from GitHub, the following occurs: * A directory named `data_bags` is created. * For each data bag, a sub-directory is created that has the same name as the data bag. * For each data bag item, a JSON file is created and placed in the appropriate sub-directory. The `data_bags` directory can be placed under version source control. When deploying from a private repository using a data bag, use the `deploy_key` option to ensure the private key is present: ``` { 'id': 'my_app', ... (truncated) ... 'deploy_key': 'ssh_private_key' } ``` where `ssh_private_key` is the same SSH private key as used with a private git repository and the new lines converted to `\n`. ### Directory Structure All data bags are stored in the `data_bags` directory of the chef-repo. This directory structure is understood by knife so that the full path does not need to be entered when working with data bags from the command line. An example of the `data_bags` directory structure: ``` - data_bags - admins - charlie.json - bob.json - tom.json - db_users - charlie.json - bob.json - sarah.json - db_config - small.json - medium.json - large.json ``` where `admins`, `db_users`, and `db_config` are the names of individual data bags and all of the files that end with `.json` are the individual data bag items. ### Data Bag Items A data bag is a container of related data bag items, where each individual data bag item is a JSON file. knife can load a data bag item by specifying the name of the data bag to which the item belongs and then the filename of the data bag item. The only structural requirement of a data bag item is that it must have an `id`: ``` { /* This is a supported comment style */ // This style is also supported "id": "ITEM_NAME", "key": "value" } ``` where * `key` and `value` are the `key:value` pair for each additional attribute within the data bag item * `/* ... */` and `// ...` show two ways to add comments to the data bag item Encrypt a Data Bag Item ----------------------- A data bag item may be encrypted using [shared secret encryption](https://en.wikipedia.org/wiki/Symmetric-key_algorithm). This allows each data bag item to store confidential information (such as a database password) or to be managed in a source control system (without plain-text data appearing in revision history). Each data bag item may be encrypted individually; if a data bag contains multiple encrypted data bag items, these data bag items are not required to share the same encryption keys. Note Because the contents of encrypted data bag items are not visible to the Chef Infra Server, search queries against data bags with encrypted items will not return any results. ### Encryption Versions The manner by which a data bag item is encrypted depends on the Chef Infra Client version used. See the following: | Infra Client version | Encryption v0 | Encryption v1 | Encryption v2 | Encryption v3 | | --- | --- | --- | --- | --- | | 10.x | `R` `W` | | | | | 11.0+ | `R` | `R` `W` | | | | 11.6+ | `R` `D` | `R` `D` | `R` `W` | | | 13.0 | `R` `D` | `R` `D` | `R` `D` | `R` `W` | `R` = read `W` = write `D` = disable #### Version 0 Chef Infra Client 0.10+ * Uses YAML serialization format to encrypt data bag items * Uses Base64 encoding to preserve special characters * Uses AES-256-CBC encryption, as defined by the OpenSSL package in the Ruby Standard Library * [Shared secret encryption](https://en.wikipedia.org/wiki/Symmetric-key_algorithm); an encrypted file can only be decrypted by a node or a user with the same shared secret * Recipes load encrypted data with access to the shared secret in a file on the node or from a URI path * Decrypts only data bag item values. Keys are encrypted but searchable * Data bag `id` value is unencrypted for tracking data bag items #### Version 1 Chef Infra Client 11.0+ * Version 0 * Uses JSON serialization format *instead of* YAML to encrypt data bag items * Adds random initialization vector encryption for each value to protect against cryptanalysis #### Version 2 Chef Infra Client 11.6+ * Version 1 * Option to disable versions 0 and 1 * Adds Encrypt-then-MAC(EtM) protection #### Version 3 Chef Infra Client 13.0+ * Option to disable version 0, 1, and 2 ### Knife Options knife can encrypt and decrypt data bag items when the `knife data bag` subcommand is run with the `create`, `edit`, `from file`, or `show` arguments and the following options: | Option | Description | | --- | --- | | `--secret SECRET` | The encryption key that is used for values contained within a data bag item. If `secret` is not specified, Chef Infra Client looks for a secret at the path specified by the `encrypted_data_bag_secret` setting in the client.rb file. | | `--secret-file FILE` | The path to the file that contains the encryption key. | ### Secret Keys Encrypting a data bag item requires a secret key. A secret key can be created in any number of ways. For example, OpenSSL can be used to generate a random number, which can then be used as the secret key: ``` openssl rand -base64 512 | tr -d '\r\n' > encrypted_data_bag_secret ``` where `encrypted_data_bag_secret` is the name of the file which will contain the secret key. For example, to create a secret key named “my_secret_key”: ``` openssl rand -base64 512 | tr -d '\r\n' > my_secret_key ``` The `tr` command eliminates any trailing line feeds. Doing so avoids key corruption when transferring the file between platforms with different line endings. ### Encrypt A data bag item is encrypted using a knife command similar to: ``` knife data bag create passwords mysql --secret-file /tmp/my_data_bag_key ``` where “passwords” is the name of the data bag, “mysql” is the name of the data bag item, and “/tmp/my_data_bag_key” is the path to the location in which the file that contains the secret-key is located. knife will ask for user credentials before the encrypted data bag item is saved. ### Verify Encryption When the contents of a data bag item are encrypted, they will not be readable until they are decrypted. Encryption can be verified with a knife command similar to: ``` knife data bag show passwords mysql ``` where “passwords” is the name of the data bag and “mysql” is the name of the data bag item. This will return something similar to: ``` id: mysql pass: cipher: aes-256-cbc encrypted_data: JZtwXpuq4Hf5ICcepJ1PGQohIyqjNX6JBc2DGpnL2WApzjAUG9SkSdv75TfKSjX4 iv: VYY2qx9b4r3j0qZ7+RkKHg== version: 1 user: cipher: aes-256-cbc encrypted_data: 10BVoNb/plkvkrzVdybPgFFII5GThZ3Op9LNkwVeKpA= iv: uIqKHZ9skJlN2gpJoml6rQ== version: 1 ``` ### Decrypt An encrypted data bag item is decrypted with a knife command similar to: ``` knife data bag show --secret-file /tmp/my_data_bag_key passwords mysql ``` that will return JSON output similar to: ``` { "id": "mysql", "pass": "thesecret123", "user": "fred" } ``` Edit a Data Bag Item -------------------- A data bag can be edited in two ways: using knife or by using the Chef management console. ### Edit a Data Bag with Knife Use the `edit` argument to edit the data contained in a data bag. If encryption is being used, the data bag will be decrypted, the data will be made available in the $EDITOR, and then encrypted again before saving it to the Chef Infra Server. To edit an item named “charlie” that is contained in a data bag named “admins”, enter: ``` knife data bag edit admins charlie ``` to open the $EDITOR. Once opened, you can update the data before saving it to the Chef Infra Server. For example, by changing: ``` { "id": "charlie" } ``` to: ``` { "id": "charlie", "uid": 1005, "gid": "ops", "shell": "/bin/zsh", "comment": "Crazy Charlie" } ``` Use Data Bags ------------- Data bags can be accessed in the following ways: ### Search Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. Any search for a data bag (or a data bag item) must specify the name of the data bag and then provide the search query string that will be used during the search. For example, to use knife to search within a data bag named “admin_data” across all items, except for the “admin_users” item, enter the following: ``` knife search admin_data "(NOT id:admin_users)" ``` Or, to include the same search query in a recipe, use a code block similar to: ``` search(:admin_data, 'NOT id:admin_users') ``` It may not be possible to know which data bag items will be needed. It may be necessary to load everything in a data bag (but not know what “everything” is). Using a search query is the ideal way to deal with that ambiguity, yet still ensure that all of the required data is returned. The following examples show how a recipe can use a series of search queries to search within a data bag named “admins”. For example, to find every administrator: ``` search(:admins, '*:*') ``` Or to search for an administrator named “charlie”: ``` search(:admins, 'id:charlie') ``` Or to search for an administrator with a group identifier of “ops”: ``` search(:admins, 'gid:ops') ``` Or to search for an administrator whose name begins with the letter “c”: ``` search(:admins, 'id:c*') ``` Data bag items that are returned by a search query can be used as if they were a hash. For example: ``` charlie = search(:admins, 'id:charlie').first # => variable 'charlie' is set to the charlie data bag item charlie['gid'] # => "ops" charlie['shell'] # => "/bin/zsh" ``` The following recipe can be used to create a user for each administrator by loading all of the items from the “admins” data bag, looping through each admin in the data bag, and then creating a user resource so that each of those admins exist: ``` admins = data_bag('admins') admins.each do |login| admin = data_bag_item('admins', login) home = "/home/#{login}" user(login) do uid admin['uid'] gid admin['gid'] shell admin['shell'] comment admin['comment'] home home manage_home true end end ``` And then the same recipe, modified to load administrators using a search query (and using an array to store the results of the search query): ``` admins = [] search(:admins, '*:*').each do |admin| login = admin['id'] admins << login home = "/home/#{login}" user(login) do uid admin['uid'] gid admin['gid'] shell admin['shell'] comment admin['comment'] ``` home home manage_home <span style="color:#007020">true</span``` end end ``` ### Environments Values that are stored in a data bag are global to the organization and are available to any environment. There are two main strategies that can be used to store per-environment data within a data bag: by using a top-level key that corresponds to the environment or by using separate items for each environment. A data bag that is storing a top-level key for an environment might look something like this: ``` { "id": "some_data_bag_item", "production" : { # Hash with all your data here }, "testing" : { # Hash with all your data here } } ``` When using the data bag in a recipe, that data can be accessed from a recipe using code similar to: ``` data_bag_item[node.chef_environment]['some_other_key'] ``` The other approach is to use separate items for each environment. Depending on the amount of data, it may all fit nicely within a single item. If this is the case, then creating different items for each environment may be a simple approach to providing per-environment values within a data bag. However, this approach is more time-consuming and may not scale to very large environments or when the data must be stored in many data bag items. ### Recipes Data bags can be accessed by a recipe in the following ways: * Loaded by name when using the Chef Infra Language. Use this approach when a only single, known data bag item is required. * Accessed through the search indexes. Use this approach when more than one data bag item is required or when the contents of a data bag are looped through. The search indexes will bulk-load all of the data bag items, which will result in a lower overhead than if each data bag item were loaded by name. #### Load with Chef Infra Language The Chef Infra Language provides access to data bags and data bag items (including encrypted data bag items) with the following methods: * `data_bag(bag)`, where `bag` is the name of the data bag. * `data_bag_item('bag_name', 'item', 'secret')`, where `bag` is the name of the data bag and `item` is the name of the data bag item. If `'secret'` is not specified, Chef Infra Client will look for a secret at the path specified by the `encrypted_data_bag_secret` setting in the client.rb file. The `data_bag` method returns an array with a key for each of the data bag items that are found in the data bag. Some examples: To load the secret from a file: ``` data_bag_item('bag', 'item', IO.read('secret_file')) ``` To load a single data bag item named `admins`: ``` data_bag('admins') ``` The contents of a data bag item named `justin`: ``` data_bag_item('admins', 'justin') ``` will return something similar to: ``` # => {'comment'=>'<NAME>', 'gid'=>1005, 'id'=>'justin', 'uid'=>1005, 'shell'=>'/bin/zsh'} ``` If `item` is encrypted, `data_bag_item` will automatically decrypt it using the key specified above, or (if none is specified) by the `Chef::Config[:encrypted_data_bag_secret]` method, which defaults to `/etc/chef/encrypted_data_bag_secret`. #### Create and edit Creating and editing the contents of a data bag or a data bag item from a recipe is not recommended. The recommended method of updating a data bag or a data bag item is to use knife and the `knife data bag` subcommand. If this action must be done from a recipe, please note the following: * If two operations concurrently attempt to update the contents of a data bag, the last-written attempt will be the operation to update the contents of the data bag. This situation can lead to data loss, so organizations should take steps to ensure that only one Chef Infra Client is making updates to a data bag at a time. * Altering data bags from the node when using the open source Chef Infra Server requires the node’s API client to be granted admin privileges. In most cases, this is not advisable. and then take steps to ensure that any subsequent actions are done carefully. The following examples show how a recipe can be used to create and edit the contents of a data bag or a data bag item using the `Chef::DataBag` and `Chef::DataBagItem` objects. To create a data bag from a recipe: ``` users = Chef::DataBag.new users.name('users') users.create ``` To create a data bag item from a recipe: ``` sam = { 'id' => 'sam', 'Full Name' => 'Sammy', 'shell' => '/bin/zsh', } databag_item = Chef::DataBagItem.new databag_item.data_bag('users') databag_item.raw_data = sam databag_item.save ``` To edit the contents of a data bag item from a recipe: ``` sam = data_bag_item('users', 'sam') sam['Full Name'] = 'Samantha' sam.save ``` #### Create users Chef Infra Client can create users on systems based on the contents of a data bag. For example, a data bag named “admins” can contain a data bag item for each of the administrators that will manage the various systems that each Chef Infra Client is maintaining. A recipe can load the data bag items and then create user accounts on the target system with code similar to the following: ``` # Load the keys of the items in the 'admins' data bag admins = data_bag('admins') admins.each do |login| # This causes a round-trip to the server for each admin in the data bag admin = data_bag_item('admins', login) homedir = '/home/#{login}' # for each admin in the data bag, make a user resource # to ensure they exist user(login) do uid admin['uid'] gid admin['gid'] shell admin['shell'] comment admin['comment'] home homedir manage_home true end end # Create an "admins" group on the system # You might use this group in the /etc/sudoers file # to provide sudo access to the admins group 'admins' do gid '999' members 'admins' end ``` ### chef-solo chef-solo can load data from a data bag as long as the contents of that data bag are accessible from a directory structure that exists on the same machine as chef-solo. The location of this directory is configurable using the `data_bag_path` option in the solo.rb file. The name of each sub-directory corresponds to a data bag and each JSON file within a sub-directory corresponds to a data bag item. Search is not available in recipes when they are run with chef-solo; use the `data_bag()` and `data_bag_item()` functions to access data bags and data bag items. Note Use the `chef-solo-search` cookbook library (developed by Chef community member “edelight” and available from GitHub) to add data bag search capabilities to a chef-solo environment: <https://github.com/edelight/chef-solo-search>. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/data_bags/About Roles =========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/roles.md) A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. Role Attributes --------------- Note Attributes can be configured in cookbooks (attribute files and recipes), roles, and environments. In addition, Ohai collects attribute data about each node at the start of a Chef Infra Client run. See [Attributes](../attributes/index) for more information about how all of these attributes fit together. An attribute can be defined in a role and then used to override the default settings on a node. When a role is applied during a Chef Infra Client run, these attributes are compared to the attributes that are already present on the node. When the role attributes take precedence over the default attributes, Chef Infra Client applies those new settings and values during a Chef Infra Client run. A role attribute can only be set to be a default attribute or an override attribute. A role attribute cannot be set to be a normal attribute. Use the `default_attribute` and `override_attribute` methods in the `.rb` attributes file or the `default_attributes` and `override_attributes` hashes in a JSON data file. ### Attribute Types There are two types of attributes that can be used with roles: | Attribute Type | Description | | --- | --- | | `default` | A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. | | `override` | An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. | Role Formats ------------ Role data is stored in two formats: as a Ruby file that contains domain-specific language and as JSON data. ### Chef Language Ruby is a simple programming language: * Chef uses Ruby as its reference language to define the patterns that are found in resources, recipes, and cookbooks * Use these patterns to configure, deploy, and manage nodes across the network Ruby is also a powerful and complete programming language: * Use the Ruby programming language to make decisions about what should happen to specific resources and recipes * Extend Chef in any manner that your organization requires To learn more about Ruby, see: * [Ruby Documentation](https://www.ruby-lang.org/en/documentation/) * [Ruby Standard Library Documentation](https://www.ruby-doc.org/stdlib/) Domain-specific Ruby attributes: | Setting | Description | | --- | --- | | `default_attributes` | Optional. A set of attributes to be applied to all nodes, assuming the node does not already have a value for the attribute. This is useful for setting global defaults that can then be overridden for specific nodes. If more than one role attempts to set a default value for the same attribute, the last role applied is the role to set the attribute value. When nested attributes are present, they are preserved. For example, to specify that a node that has the attribute `apache2` should listen on ports 80 and 443 (unless ports are already specified): ``` default_attributes 'apache2' => { 'listen_ports' => [ '80', '443' ] } ``` | | `description` | A description of the functionality that is covered. For example: ``` description 'The base role for systems that serve HTTP traffic' ``` | | `env_run_lists` | Optional. A list of environments, each specifying a recipe or a role to be applied to that environment. This setting must specify the `_default` environment. If the `_default` environment is set to `[]` or `nil`, then the run-list is empty. For example: ``` env_run_lists 'prod' => ['recipe[apache2]'], 'staging' => ['recipe[apache2::staging]' ``` Warning Using `env_run_lists` with roles is discouraged as it can be difficult to maintain over time. Instead, consider using multiple roles to define the required behavior. | | `name` | A unique name within the organization. Each name must be made up of letters (upper- and lower-case), numbers, underscores, and hyphens: [A-Z][a-z][0-9] and [_-]. Spaces are not allowed. For example: ``` name 'dev01-24' ``` | | `override_attributes` | Optional. A set of attributes to be applied to all nodes, even if the node already has a value for an attribute. This is useful for ensuring that certain attributes always have specific values. If more than one role attempts to set an override value for the same attribute, the last role applied wins. When nested attributes are present, they are preserved. For example: ``` override_attributes 'apache2' => { 'max_children' => '50' } ``` The parameters in a Ruby file are Ruby method calls, so parentheses can be used to provide clarity when specifying numerous or deeply-nested attributes. For example: ``` override_attributes( :apache2 => { :prefork => { :min_spareservers => '5' } } ) ``` Or: ``` override_attributes( :apache2 => { :prefork => { :min_spareservers => '5' } }, :tomcat => { :worker_threads => '100' } ) ``` | | `run_list` | A list of recipes and/or roles to be applied and the order in which they are to be applied. For example, the following run-list: ``` run_list 'recipe[apache2]', 'recipe[apache2::mod_ssl]', 'role[monitor]' ``` would apply the `apache2` recipe first, then the `apache2::mod_ssl` recipe, and then the `role[monitor]` recipe. | Each role must be saved as a ruby file the `roles/` subdirectory of the chef-repo. (If the repository does not have this subdirectory, then create it using knife.) Each Ruby file should have the .rb suffix. A complete role has the following syntax: ``` name "role_name" description "role_description" run_list "recipe[name]", "recipe[name::attribute]", "recipe[name::attribute]" env_run_lists "name" => ["recipe[name]"], "environment_name" => ["recipe[name::attribute]"] default_attributes "node" => { "attribute" => [ "value", "value", "etc." ] } override_attributes "node" => { "attribute" => [ "value", "value", "etc." ] } ``` where both default and override attributes are optional and at least one run-list (with at least one run-list item) is specified. For example, a role named `webserver` that has a run-list that defines actions for three different roles, and for certain roles takes extra steps (such as the `apache2` role listening on ports 80 and 443): ``` name "webserver" description "The base role for systems that serve HTTP traffic" run_list "recipe[apache2]", "recipe[apache2::mod_ssl]", "role[monitor]" env_run_lists "prod" => ["recipe[apache2]"], "staging" => ["recipe[apache2::staging]"], "_default" => [] default_attributes "apache2" => { "listen_ports" => [ "80", "443" ] } override_attributes "apache2" => { "max_children" => "50" } ``` ### JSON The JSON format for roles maps directly to the domain-specific Ruby format: same settings, attributes, and values, and a similar structure and organization. For example: ``` { "name": "webserver", "chef_type": "role", "json_class": "Chef::Role", "default_attributes": { "apache2": { "listen_ports": [ "80", "443" ] } }, "description": "The base role for systems that serve HTTP traffic", "run_list": [ "recipe[apache2]", "recipe[apache2::mod_ssl]", "role[monitor]" ], "env_run_lists" : { "production" : [], "preprod" : [], "dev": [ "role[base]", "recipe[apache]", "recipe[apache::copy_dev_configs]", ], "test": [ "role[base]", "recipe[apache]" ] }, "override_attributes": { "apache2": { "max_children": "50" } } } ``` The JSON format has two additional settings: | Setting | Description | | --- | --- | | `chef_type` | Always set this to `role`. Use this setting for any custom process that consumes role objects outside of Ruby. | | `json_class` | Always set this to `Chef::Role`. The Chef Infra Client uses this setting to auto-inflate a role object. If objects are being rebuilt outside of Ruby, ignore it. | Manage Roles ------------ There are several ways to manage roles: * knife can be used to create, edit, view, list, tag, and delete roles. * The Chef Infra Client can be used to manage role data using the command line and JSON files (that contain a hash, the elements of which are added as role attributes). In addition, the `run_list` setting allows roles and/or recipes to be added to the role. * The open source Chef Infra Server can be used to manage role data using the command line and JSON files (that contain a hash, the elements of which are added as role attributes). In addition, the `run_list` setting allows roles and/or recipes to be added to the role. * The Chef Infra Server API can be used to create and manage roles directly, although using knife directly is the most common way to manage roles. * The command line can also be used with JSON files and third-party services, such as Amazon EC2, where the JSON files can contain per-instance metadata stored in a file on-disk and then read by chef-solo or Chef Infra Client as required. By creating and editing files using the Chef Language (Ruby) or JSON, you can dynamically generate role data. Roles created and edited using files are compatible with all versions of Chef, including chef-solo. Roles created and edited using files can be kept in version source control, which also keeps a history of what changed when. When roles are created and edited using files, they should not be managed using knife, as changes will be overwritten. A run-list that is associated with a role can be edited using the Chef management console add-on. The canonical source of a role’s data is stored on the Chef Infra Server, which means that keeping role data in version source control can be challenging. If roles are created and managed using knife and then arbitrarily updated uploaded through JSON data, that action will overwrite the previous work with knife. It is strongly recommended to keep to one process and not switch back and forth. ### Set Per-environment Run-lists A per-environment run-list is a run-list that is associated with a role and a specific environment. More than one environment can be specified in a role, but each specific environment may be associated with only one run-list. If a run-list is not specified, the default run-list will be used. For example: ``` { "name": "webserver", "default_attributes": { }, "json_class": "Chef::Role", "env_run_lists": { "production": [], "preprod": [], "test": [ "role[base]", "recipe[apache]", "recipe[apache::copy_test_configs]" ], "dev": [ "role[base]", "recipe[apache]", "recipe[apache::copy_dev_configs]" ] }, "run_list": [ "role[base]", "recipe[apache]" ], "description": "The webserver role", "chef_type": "role", "override_attributes": { } } ``` where: * `webserver` is the name of the role * `env_run_lists` is a hash of per-environment run-lists for `production`, `preprod`, `test`, and `dev` * `production` and `preprod` use the default run-list because they do not have a per-environment run-list * `run_list` defines the default run-list ### Delete from Run-list When an environment is deleted, it will remain within a run-list for a role until it is removed from that run-list. If a new environment is created that has an identical name to an environment that was deleted, a run-list that contains an old environment name will use the new one. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/roles/Chef and Google =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/google.md) Google Cloud Platform is a suite of cloud computing services that run on the same infrastructure that Google uses internally for its end-user products, such as Google Search and YouTube. Alongside a set of management tools, it provides a series of modular cloud services including computing, data storage, data analytics, and machine learning. This page outlines the different tools that can be used to integrate Chef with the Google Cloud Platform. knife-google ------------ [[GitHub]](https://github.com/chef/knife-google) This plugin gives knife the ability to create, bootstrap, and manage Google Compute Engine (GCE) instances. ### Authentication and Authorization `knife-google` relies on the Google Auth Library to handle authentication to the Google Cloud API. The auth library expects to find a JSON credentials file located under `~/.config/gcloud/application_default_credentials.json`. The easiest way to create this is to download and install the [Google Cloud SDK](https://cloud.google.com/sdk/) and run the `gcloud auth application-default login` command, which will create the credentials file for you. If you already have a file you’d like to use that is in a different location, set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable with the full path to that file. These are the necessary settings for your `config.rb` file: ``` knife[:gce_project] = 'my-test-project' knife[:gce_zone] = 'us-east1-b' ``` ### Usage Examples **Create a server:** ``` knife google server create test-instance-1 --gce-image centos-7-v20160219 \ --gce-machine-type n1-standard-2 --gce-public-ip ephemeral --connection-user myuser \ --identity-file /Users/myuser/.ssh/google_compute_engine ``` **Delete multiple servers:** ``` knife google server delete my-instance-1 my-instance-2 --purge ``` **List all servers:** ``` knife google server list ``` kitchen-google -------------- [[GitHub]](https://github.com/test-kitchen/kitchen-google) A test kitchen driver for Google Cloud Platform. ### Usage Examples The following is a basic `kitchen.yml` example: ``` ---driver:name:gceproject:mycompany-testzone:us-east1-cemail:<EMAIL>.comtags:- devteam- test-kitchenservice_account_scopes:- devstorage.read_write- userinfo.emailprovisioner:name:chef_zerotransport:username:chefuserplatforms:- name:centos-7driver:image_project:centos-cloudimage_name:centos-7-v20170124- name:ubuntu-18.04driver:image_project:ubuntu-os-cloudimage_family:ubuntu-1804-lts- name:windowsdriver:image_project:windows-cloudimage_name:windows-server-2012-r2-dc-v20170117disk_size:50suites:- name:defaultrun_list:- recipe[COOKBOOK::default]attributes: ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/google/AWS Marketplace =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/aws_marketplace.md) Chef Automate is an enterprise platform that allows developers, operations, and security engineers to collaborate on application and infrastructure changes with speed and at scale. Chef Automate provides actionable insights across data centers and cloud providers, wherever your nodes live. Chef Automate is the center of the modern Chef platform, providing users with a single source of truth for infrastructure, security, and application automation. The comprehensive dashboard provides real-time views of your configuration management activity. Chef Automate comes bundled with the latest Chef Infra Server, providing the core tools you need to manage your enterprise infrastructure. Data collection is enabled by default, allowing your nodes to report activity in real-time. This instance is free for 60 days or you can bring your own license (BYOL). Use this instance with Chef Workstation installed on your laptop or a separate AWS instance. Chef Workstation includes: * Chef Infra Client * Chef InSpec * Chef Habitat * `chef` and `knife` command line tools * Testing tools, such as Test Kitchen and Cookstyle * Everything else needed to author cookbooks and upload them to the Chef Infra Server. If you need to run Automate with a high availability (HA) topology, please contact [Chef Support](https://www.chef.io/support). Installation ------------ Select [Chef Automate](https://aws.amazon.com/marketplace/pp/prodview-r26bs6uknftps?ref_=srh_res_product_title) in the AWS Marketplace. The Chef Automate AWS deployment uses [CloudFormation](https://aws.amazon.com/cloudformation/). [Download the CloudFormation template](https://aws-ami-chef-automate-v2.s3.amazonaws.com/cloudformation_template.yaml) or use the [view the template in CloudFormation Designer](https://console.aws.amazon.com/cloudformation/designer/home?templateURL=https://s3.amazonaws.com/awsmp-fulfillment-cf-templates-prod/658820ac-955d-4f73-bbcd-ab19b598d852/ec282ef4e8434b46a9df737571e1e0ac.template) Every CloudFormation Stack deployment creates a new [Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) (VPC). Note AWS provides 5 VPCs per region. If you require more VPCs, please contact [AWS Support](https://aws.amazon.com/contact-us/). ### Start Chef Automate with CloudFormation 1. Enter the following values for your deployment. * Stack Name: `Chef-Automate` * EC2RootVolumeSize: `Default: 40` * Instance Type:`Default: t2.xlarge` * KeyName: *Enter your existing keypair* * SecurityGroupCidrIp: `0.0.0.0/0` * SubnetCIDR: `10.0.0.0/24` * VpcCIDR: `10.0.0.0/16` 2. Select **Next** and create your Chef Automate deployment. This process can take several minutes. 3. Give Chef Automate an additional five minutes for all the services to start running. ![Select next to create stack] Post-Installation ----------------- 1. Navigate to the AWS deployment **Outputs** tab and locate the Chef Automate URL, user name, and password. You will need these in the next steps. ![AWS Chef Automate deployment Outputs tab contains your instance URL, user name, and password ] 2. Open your browser and paste the Chef Automate URL, which will open an alert page. 3. Select **Advanced** and continue. ![Select ‘advanced’ to bypass the warning that the page is not secure]. 4. Enter your **Username** and **Password** and select **Sign In**. ![ ] 5. Fill out the registration form and [Accept the Chef License](../chef_license_accept/index). 6. Select **Register** to enter Chef Automate. ![ ] 7. Congratulations! You’ve started Chef Automate! ![ ] Add Chef Servers ---------------- 1. Add Chef-Server Details, select the Add Chef Infra Server Button. ![ ] 2. Enter the server name, FQDN, and IP address. Then select **Add Chef Infra Server** to create the server. * Name: Add Proper Name for the Sever. * FQDN: It would be the same as Automate FQDN. * IP Address: Public IP Address of the EC2-Instance.![Add Chef Infra Server Form] 3. The Chef Infra Server will appear in the list of servers. Select the server and view information about it. ![Select a server from the list] 4. Select **Add Chef Organization**. ![] 5. Enter the following information: * Name: **demo** * Admin User: **admin** * Admin Key: *copy the key from starter kit* 6. Select **Add Chef Organization**. ![Select the Add Chef Organization button to complete this action] AWS Deployment Security ----------------------- Update the AWS Deployment **Security Group** to require source IP addresses for a secure SSH connection. 1. Select the **Instance Security** group in the **Resources** tab of your AWS Chef Automate deployment. ![ ] 2. Select the **Security Group ID** for your Chef Automate deployment. ![Locate and copy your security group ID from the second column] 3. Select **Edit inbound rules**. ![Select the Edit inbound rules button] 4. Select **Add rule** and then **SSH** and enter the source IP. 5. Select **Save rules** to finish. ![Add your IP address range as a custom SSH rule] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/aws_marketplace/Chef and Terraform ================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/terraform.md) Warning Terraform deprecated the Chef Provisioner in the [0.13.4](https://www.terraform.io/docs/language/resources/provisioners/chef.html) release and they will remove it in a future version. Terraform continues to support the Chef Provider. [Terraform](https://www.terraform.io/) is an open-source infrastructure-as-code provisioning tool from [HashiCorp](https://www.hashicorp.com/). Terraform allows you to write code to define and provision infrastructure for the cloud, virtual machines, and on-premises machines. Terraform is not a configuration management tool, it is responsible for deploying, maintaining, and destroying the infrastructure that servers and applications run on. When Terraform creates cloud or virtual servers, it uses [Provisioners](https://www.terraform.io/docs/provisioners/index.html) to enable configuration management to manage them. When Terraform talks to APIs to define or configure resources, it uses [Providers](https://www.terraform.io/docs/providers/index.html) to request those resources. Chef Infra Provisioner ---------------------- The [Terraform Chef Provisioner](https://www.terraform.io/docs/provisioners/chef.html) bootstraps Terraform, provisioned with Chef Infra via SSH or WinRM, and configures them to work with a [Chef Infra Server](../server/index). Standard bootstrap options such as Chef Infra versions, secrets, proxies, and assigning run lists via Policyfiles or Roles and Environments are all supported. The referenced documentation provides a complete list of supported options and an example of usage. HashiCorp provides support for the [Terraform Chef Provisioner](https://www.terraform.io/docs/provisioners/chef.html) and it is not officially supported by Chef Software. ### Terraform and Chef Solo If you are using [Chef Solo](../chef_solo/index), you will most likely want to use the [Terraform remote-exec Provisioner](https://www.terraform.io/docs/provisioners/remote-exec.html) rather than the Terraform Chef Provisioner. The remote-exec Provisioner may be used to run a script or an inline set of commands on the newly created machine. Please refer to the [Terraform remote-exec Provisioner documentation](https://www.terraform.io/docs/provisioners/remote-exec.html) for further options and examples. #### Example remote-exec inline ``` resource "aws_instance" "web" { # ... provisioner "remote-exec" { inline = [ "wget -O /tmp/chef.rpm https://MYSERVER/chef_installers/chef-15.8.23-1.el7.x86_64.rpm", "rpm -Uvh /tmp/chef.rpm", "wget -O /tmp/base.tgz https://MYSERVER/policyfiles/base.tgz", "tar -C /tmp -xzf /tmp/base.tgz", "PWD=/tmp/base chef-client -z", ] } } ``` Chef Infra Provider ------------------- The [Terraform Chef Provider](https://www.terraform.io/docs/providers/chef/index.html) allows you to manage Chef Infra Server resources (nodes, data bags, etc.) using the Chef Infra Server API. Policyfiles, cookbooks, clients, and ACLs are not currently managed with the Provider. The [Terraform Chef Provider documentation](https://www.terraform.io/docs/providers/chef/index.html) provides a complete list of supported options and an example of usage. HashiCorp provides support for the Terraform Chef Provider and it is not officially supported by Chef Software. Additional Terraform Integrations --------------------------------- * The [Habitat Provisioner](https://www.habitat.sh/docs/habitat-and-other-software/#habitat-and-provisioning) may be used to install and load the Chef Habitat Supervisor and configure the services to be managed by the supervisor. * [Kitchen Terraform](https://newcontext-oss.github.io/kitchen-terraform/) is a community [Test Kitchen](../kitchen/index) driver that allows for multi-node testing. * [InSpec-Iggy](https://github.com/mattray/inspec-iggy/) is a community [InSpec](../inspec/index) plugin that generates InSpec compliance controls and profiles from Terraform `tfstate` files and AWS CloudFormation templates. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/terraform/About Run-lists =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/run_lists.md) A run-list defines all of the information necessary for Chef to configure a node into the desired state. A run-list is: * An ordered list of roles and/or recipes that are run in the exact order defined in the run-list; if a recipe appears more than once in the run-list, Chef Infra Client will not run it twice * Always specific to the node on which it runs; nodes may have a run-list that is identical to the run-list used by other nodes * Stored as part of the node object on the Chef server * Maintained using knife and then uploaded from the workstation to the Chef Infra Server, or maintained using Chef Automate Run-list Format --------------- A run-list must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: ``` "role[NAME]" ``` or ``` "recipe[COOKBOOK::RECIPE]" ``` Use a comma to separate roles and recipes when adding more than one item the run-list: ``` "recipe[COOKBOOK::RECIPE],COOKBOOK::RECIPE,role[NAME]" ``` ### Empty Run-lists Use an empty run-list to determine if a failed Chef Infra Client run has anything to do with the recipes that are defined within that run-list. This is a quick way to discover if the underlying cause of a Chef Infra Client run failure is a configuration issue. If a failure persists even if the run-list is empty, check the following: * Configuration settings in the config.rb file * Permissions for the user to both the Chef Infra Server and to the node on which a Chef Infra Client run is to take place Knife Commands -------------- The following knife commands may be used to manage run-lists on the Chef Infra Server. ### Quotes, Windows When running knife in Microsoft Windows, a string may be interpreted as a wildcard pattern when quotes are not present in the command. The number of quotes to use depends on the shell from which the command is being run. When running knife from the command prompt, a string should be surrounded by single quotes (`' '`). For example: ``` knife node run_list set test-node 'recipe[iptables]' ``` When running knife from Windows PowerShell, a string should be surrounded by triple single quotes (`''' '''`). For example: ``` knife node run_list set test-node '''recipe[iptables]''' ``` #### Import-Module chef The Chef Client 12.4 release adds an optional feature to the Microsoft Installer Package (MSI) for Chef. This feature enables the ability to pass quoted strings from the Windows PowerShell command line without the need for triple single quotes (`''' '''`). This feature installs a Windows PowerShell module (typically in `C:\opscode\chef\modules`) that is also appended to the `PSModulePath` environment variable. This feature is not enabled by default. To activate this feature, run the following command from within Windows PowerShell: ``` Import-Module chef ``` or add `Import-Module chef` to the profile for Windows PowerShell located at: ``` ~\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 ``` This module exports cmdlets that have the same name as the command-line tools—chef-client, knife—that are built into Chef. For example: ``` knife exec -E 'puts ARGV' """&s0meth1ng""" ``` is now: ``` knife exec -E 'puts ARGV' '&s0meth1ng' ``` and: ``` knife node run_list set test-node '''role[ssssssomething]''' ``` is now: ``` knife node run_list set test-node 'role[ssssssomething]' ``` To remove this feature, run the following command from within Windows PowerShell: ``` Remove-Module chef ``` ### run_list add Use the `run_list add` argument to add run-list items (roles or recipes) to a node. A run-list must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: ``` "role[NAME]" ``` or ``` "recipe[COOKBOOK::RECIPE]" ``` Use a comma to separate roles and recipes when adding more than one item the run-list: ``` "recipe[COOKBOOK::RECIPE],COOKBOOK::RECIPE,role[NAME]" ``` #### Syntax This argument has the following syntax: ``` knife node run_list add NODE_NAME RUN_LIST_ITEM (options) ``` #### Options This argument has the following options: `-a ITEM`, `--after ITEM` Add a run-list item after the specified run-list item. `-b ITEM`, `--before ITEM` Add a run-list item before the specified run-list item. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. #### Examples The following examples show how to use this knife subcommand: ##### Add a role To add a role to a run-list, enter: ``` knife node run_list add NODE_NAME 'role[ROLE_NAME]' ``` ##### Add roles and recipes To add roles and recipes to a run-list, enter: ``` knife node run_list add NODE_NAME 'recipe[COOKBOOK::RECIPE_NAME],recipe[COOKBOOK::RECIPE_NAME],role[ROLE_NAME]' ``` ##### Add a recipe with a FQDN To add a recipe to a run-list using the fully qualified format, enter: ``` knife node run_list add NODE_NAME 'recipe[COOKBOOK::RECIPE_NAME]' ``` ##### Add a recipe with a cookbook To add a recipe to a run-list using the cookbook format, enter: ``` knife node run_list add NODE_NAME 'COOKBOOK::RECIPE_NAME' ``` ##### Add the default recipe To add the default recipe of a cookbook to a run-list, enter: ``` knife node run_list add NODE_NAME 'COOKBOOK' ``` ### run_list remove Use the `run_list remove` argument to remove run-list items (roles or recipes) from a node. A recipe must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: `'role[ROLE_NAME]'` or `'recipe[COOKBOOK::RECIPE_NAME]'`. Use a comma to separate roles and recipes when removing more than one, like this: `'recipe[COOKBOOK::RECIPE_NAME],COOKBOOK::RECIPE_NAME,role[ROLE_NAME]'`. #### Syntax This argument has the following syntax: ``` knife node run_list remove NODE_NAME RUN_LIST_ITEM ``` #### Options This command does not have any specific options. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. #### Examples The following examples show how to use this knife subcommand: ##### Remove a role To remove a role from a run-list, enter: ``` knife node run_list remove NODE_NAME 'role[ROLE_NAME]' ``` ##### Remove a run-list To remove a recipe from a run-list using the fully qualified format, enter: ``` knife node run_list remove NODE_NAME 'recipe[COOKBOOK::RECIPE_NAME]' ``` ### run_list set Use the `run_list set` argument to set the run-list for a node. A recipe must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: `"role[ROLE_NAME]"` or `"recipe[COOKBOOK::RECIPE_NAME]"`. Use a comma to separate roles and recipes when setting more than one, like this: `"recipe[COOKBOOK::RECIPE_NAME],COOKBOOK::RECIPE_NAME,role[ROLE_NAME]"`. #### Syntax This argument has the following syntax: ``` knife node run_list set NODE_NAME RUN_LIST_ITEM ``` #### Options This command does not have any specific options. #### Examples None. ### status The following examples show how to use the `knife status` subcommand to verify the status of run-lists. #### View status, include run-lists To include run-lists in the status, enter: ``` knife status --run-list ``` to return something like: ``` 20 hours ago, dev-vm.chisamore.com, ubuntu 10.04, dev-vm.chisamore.com, 10.66.44.126, role[lb]. 3 hours ago, i-225f954f, ubuntu 10.04, ec2-67-202-63-102.compute-1.amazonaws.com, 67.202.63.102, role[web]. 3 hours ago, i-a45298c9, ubuntu 10.04, ec2-174-129-127-206.compute-1.amazonaws.com, 174.129.127.206, role[web]. 3 hours ago, i-5272a43f, ubuntu 10.04, ec2-184-73-9-250.compute-1.amazonaws.com, 184.73.9.250, role[web]. 3 hours ago, i-226ca64f, ubuntu 10.04, ec2-75-101-240-230.compute-1.amazonaws.com, 75.101.240.230, role[web]. 3 hours ago, i-f65c969b, ubuntu 10.04, ec2-184-73-60-141.compute-1.amazonaws.com, 184.73.60.141, role[web]. ``` #### View status using a query To show the status of a subset of nodes that are returned by a specific query, enter: ``` knife status "role:web" --run-list ``` to return something like: ``` 3 hours ago, i-225f954f, ubuntu 10.04, ec2-67-202-63-102.compute-1.amazonaws.com, 67.202.63.102, role[web]. 3 hours ago, i-a45298c9, ubuntu 10.04, ec2-174-129-127-206.compute-1.amazonaws.com, 174.129.127.206, role[web]. 3 hours ago, i-5272a43f, ubuntu 10.04, ec2-184-73-9-250.compute-1.amazonaws.com, 184.73.9.250, role[web]. 3 hours ago, i-226ca64f, ubuntu 10.04, ec2-75-101-240-230.compute-1.amazonaws.com, 75.101.240.230, role[web]. 3 hours ago, i-f65c969b, ubuntu 10.04, ec2-184-73-60-141.compute-1.amazonaws.com, 184.73.60.141, role[web]. ``` Run-lists, Applied ------------------ A run-list will tell Chef Infra Client what to do when bootstrapping that node for the first time, and then how to configure that node on every subsequent Chef Infra Client run. ### Bootstrap Operations The `knife bootstrap` command is a common way to install Chef Infra Client on a node. The default for this approach assumes that a node can access the Chef website so that it may download the Chef Infra Client package from that location. The Chef Infra Client installer will detect the version of the operating system, and then install the appropriate Chef Infra Client version using a single command to install Chef Infra Client and all of its dependencies, including an embedded version of Ruby, OpenSSL, parsers, libraries, and command line utilities. The Chef Infra Client installer puts everything into a unique directory (`/opt/chef/`) so that Chef Infra Client will not interfere with other applications that may be running on the target machine. Once installed, Chef Infra Client requires a few more configuration steps before it can perform its first Chef Infra Client run on a node. A node is any physical, virtual, or cloud device that is configured and maintained by an instance of Chef Infra Client. Bootstrapping installs Chef Infra Client on a target system so that it can run as a client and sets the node up to communicate with a Chef Infra Server. There are two ways to do this: * Run the `knife bootstrap` command from a workstation. * Perform an unattended install to bootstrap from the node itself, without requiring SSH or WinRM connectivity. The following diagram shows the stages of the bootstrap operation, and the list below the diagram describes each of those stages in greater detail. ![image] During a `knife bootstrap` bootstrap operation, the following happens: | Stages | Description | | --- | --- | | **knife bootstrap** | Enter the `knife bootstrap` subcommand from a workstation. Include the hostname, IP address, or FQDN of the target node as part of this command. Knife will establish an SSH or WinRM connection with the target system and run a bootstrap script. | | **Get the install script from Chef** | The shell script will make a request to the Chef website to get the most recent version of a the Chef Infra Client install script(`install.sh` or `install.ps1`). | | **Get the Chef Infra Client package from Chef** | The install script then gathers system-specific information and determines the correct package for Chef Infra Client, and then downloads the appropriate package from `omnitruck-direct.chef.io`. | | **Install Chef Infra Client** | Chef Infra Client is installed on the target node using a system native package (.rpm, .msi, etc). | | **Start a Chef Infra Client run** | On UNIX and Linux-based machines: The second shell script executes the `chef-client` binary with a set of initial settings stored within `first-boot.json` on the node. `first-boot.json` is generated from the workstation as part of the initial `knife bootstrap` subcommand. On Microsoft Windows machines: The batch file that is derived from the windows-chef-client-msi.erb bootstrap template executes the `chef-client` binary with a set of initial settings stored within `first-boot.json` on the node. `first-boot.json` is generated from the workstation as part of the initial `knife bootstrap` subcommand. | | **Complete a Chef Infra Client run** | a Chef Infra Client run proceeds, using HTTPS (port 443), and registers the node with the Chef Infra Server. The first Chef Infra Client run, by default, contains an empty run-list. A [run-list can be specified](../workstation/knife_bootstrap/index) as part of the initial bootstrap operation using the `--run-list` option as part of the `knife bootstrap` subcommand. | ### The Chef Infra Client Run A “Chef Infra Client run” is the term used to describe the steps Chef Infra Client takes to configure a node when the chef-client command is run. The following diagram shows the various stages that occur during a Chef Infra Client run. ![Anatomy of a Chef Infra Client Run](https://docs.chef.io/images/chef_run.svg) During every Chef Infra Client run, the following happens: | Stages | Description | | --- | --- | | **Get configuration data** | Chef Infra Client gets process configuration data from the [client.rb](../config_rb_client/index) file on the [node](../nodes/index), and then gets node configuration data from Ohai. One important piece of configuration data is the name of the node, which is found in the `node_name` attribute in the client.rb file or is provided by Ohai. If Ohai provides the name of a node, it is typically the FQDN for the node, which is always unique within an organization. | | **Authenticate to the Chef Infra Server** | Chef Infra Client [authenticates](../server/auth/index) to the Chef Infra Server using an RSA private key and the Chef Infra Server API. The name of the node is required as part of the authentication process to the Chef Infra Server. If this is the first Chef Infra Client run for a node, the chef-validator will be used to generate the RSA private key. | | **Get, rebuild the node object** | Chef Infra Client pulls down the node object from the Chef Infra Server and then rebuilds it. A node object is made up of the system attributes discovered by Ohai, the attributes set in Policyfiles or Cookbooks, and the run list of cookbooks. The first time Chef Infra Client runs on a node, it creates a node object from the default run-list. A node that has not yet had a Chef Infra Client run will not have a node object or a Chef Infra Server entry for a node object. On any subsequent Chef Infra Client runs, the rebuilt node object will also contain the run-list from the previous Chef Infra Client run. | | **Expand the run-list** | Chef Infra Client expands the [run-list](index) from the rebuilt node object and compiles a complete list of recipes in the exact order that they will be applied to the node. | | **Synchronize cookbooks** | Chef Infra Client requests all the [cookbook files](../cookbooks/index) (including recipes, templates, resources, providers, attributes, and libraries) that it needs for every action identified in the run-list from the Chef Infra Server. The Chef Infra Server responds to Chef Infra Client with the complete list of files. Chef Infra Client compares the list of files to the files that already exist on the node from previous runs, and then downloads a copy of every new or modified file from the Chef Infra Server. | | **Reset node attributes** | All attributes in the rebuilt node object are reset. All attributes from attribute files, Policyfiles, and Ohai are loaded. Attributes that are defined in attribute files are first loaded according to cookbook order. For each cookbook, attributes in the `default.rb` file are loaded first, and then additional attribute files (if present) are loaded in lexical sort order. If attribute files are found within any cookbooks that are listed as dependencies in the `metadata.rb` file, these are loaded as well. All attributes in the rebuilt node object are updated with the attribute data according to attribute precedence. When all the attributes are updated, the rebuilt node object is complete. | | **Compile the resource collection** | Chef Infra Client identifies each resource in the node object and builds the resource collection. Libraries are loaded first to ensure that all language extensions and Ruby classes are available to all resources. Next, attributes are loaded, followed by custom resources. Finally, all recipes are loaded in the order specified by the expanded run-list. This is also referred to as the "compile phase". | | **Converge the node** | Chef Infra Client configures the system based on the information that has been collected. Each resource is executed in the order identified by the run-list, and then by the order in which each resource is listed in each recipe. Each resource defines an action to run, which configures a specific part of the system. This process is also referred to as convergence. This is also referred to as the "execution phase". | | **Update the node object, process exception and report handlers** | When all the actions identified by resources in the resource collection have been done and Chef Infra Client finishes successfully, then Chef Infra Client updates the node object on the Chef Infra Server with the node object built during a Chef Infra Client run. (This node object will be pulled down by Chef Infra Client during the next Chef Infra Client run.) This makes the node object (and the data in the node object) available for search. Chef Infra Client always checks the resource collection for the presence of exception and report handlers. If any are present, each one is processed appropriately. | | **Get, run Chef InSpec Compliance Profiles** | After the Chef Infra Client run finishes, it begins the Compliance Phase, which is a Chef InSpec run within the Chef Infra Client. Chef InSpec retrieves tests from either a legacy audit cookbook or a current InSpec profile. | | **Send or Save Compliance Report** | When all the InSpec tests finish running, Chef InSpec checks the reporting handlers defined in the legacy audit cookbook or in a current InSpec profile and processes them appropriately. | | **Stop, wait for the next run** | When everything is configured and the Chef Infra Client run is complete, Chef Infra Client stops and waits until the next time it is asked to run. | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/run_lists/About Environments ================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/environments.md) An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. The _default Environment ------------------------- Every Chef Infra Server organization must have at least one environment. Each organization starts out with a single `_default` environment. The `_default` environment cannot be modified in any way. Nodes, roles, run-lists, cookbooks (and cookbook versions), and attributes specific to an organization can only be associated with a custom environment. Additional environments can be created to reflect each organization’s patterns and workflow. For example, creating `production`, `staging`, `testing`, and `development` environments. Environment Attributes ---------------------- Note Attributes can be configured in cookbooks (attribute files and recipes), roles, and environments. In addition, Ohai collects attribute data about each node at the start of a Chef Infra Client run. See [Attributes](../attributes/index) for more information about how all of these attributes fit together. Attributes can be defined in an environment and then used to override the default attributes in a cookbook. When an environment is applied during a Chef Infra Client run, environment attributes are compared to the attributes that are already present on the node. When the environment attributes take precedence over the default attributes, Chef Infra Client applies those new settings and values during a Chef Infra Client run. Environment attributes can be set to either `default` attribute level or an `override` attribute level. ### Environment Attribute Types There are two types of attributes that can be used with environments: | Attribute Type | Description | | --- | --- | | `default` | A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. | | `override` | An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. | Pinning Cookbooks in Environments --------------------------------- Cookbook versions can be pinned in each environment, which allows you to control the rollout of new cookbook releases through successive testing environments before releasing new cookbook versions into production environments. See the environment format examples below for the cookbook pinning syntax. Environment Formats ------------------- Environments may be stored on disk (any in source control) in two formats: * As Ruby (i.e. a file that ends with `.rb`); this format is not available when running Chef Infra Client in local mode * As JSON (i.e. a file that ends with `.json`) ### Chef Language Each environment is defined as a Ruby file (i.e. a file that ends with `.rb`). Each environment file should contain the following domain-specific attributes: | Setting | Description | | --- | --- | | `cookbook` | A version constraint for a single cookbook. For example: ``` cookbook 'couchdb', '< 11.0.0' ``` or: ``` cookbook 'my_rails_app', '= 1.2.0' ``` or: ``` cookbook 'gems', '~> 1.4' ``` | | `cookbook_versions` | A version constraint for a group of cookbooks. For example: ``` cookbook_versions( 'couchdb' => '= 11.0.0', 'my_rails_app' => '~> 1.2.0' ) ``` | | `default_attributes` | Optional. A set of attributes to be applied to all nodes, assuming the node does not already have a value for the attribute. This is useful for setting global defaults that can then be overridden for specific nodes. If more than one role attempts to set a default value for the same attribute, the last role applied is the role to set the attribute value. When nested attributes are present, they are preserved. For example, to specify that a node that has the attribute `apache2` should listen on ports 80 and 443 (unless ports are already specified): ``` default_attributes 'apache2' => { 'listen_ports' => %w(80 443) } ``` | | `description` | A description of the functionality that is covered. For example: ``` description 'The development environment' ``` | | `name` | A unique name within the organization. Each name must be made up of letters (upper- and lower-case), numbers, underscores, and hyphens: [A-Z][a-z][0-9] and [_-]. Spaces are not allowed. For example: ``` name 'dev01-24' ``` | | `override_attributes` | Optional. A set of attributes to be applied to all nodes, even if the node already has a value for an attribute. This is useful for ensuring that certain attributes always have specific values. If more than one role attempts to set an override value for the same attribute, the last role applied wins. When nested attributes are present, they are preserved. For example: ``` override_attributes 'apache2' => { 'max_children' => '50' } ``` The parameters in a Ruby file are actually Ruby method calls, so parentheses can be used to provide clarity when specifying numerous or deeply-nested attributes. For example: ``` override_attributes( apache2: { prefork: { min_spareservers: '5' }, } ) ``` or: ``` override_attributes( apache2: { prefork: { min_spareservers: '5' }, }, tomcat: { worker_threads: '100', } ) ``` | A Ruby file for each non-default environment must exist in the `environments/` subdirectory of the chef-repo. (If the chef-repo does not have this subdirectory, then it should be created.) The complete environment has the following syntax: ``` name 'environment_name' description 'environment_description' cookbook OR cookbook_versions 'cookbook' OR 'cookbook' => 'cookbook_version' default_attributes 'node' => { 'attribute' => [ 'value', 'value', 'etc.' ] } override_attributes 'node' => { 'attribute' => [ 'value', 'value', 'etc.' ] } ``` where both default and override attributes are optional and either a cookbook or cookbook versions (one or more) are specified. For example, an environment named `dev` that uses the `couchdb` cookbook (version 11.0.0 or higher) that listens on ports 80 and 443: ``` name 'dev' description 'The development environment' cookbook_versions 'couchdb' => '= 11.0.0' default_attributes 'apache2' => { 'listen_ports' => %w(80 443) } ``` Or (using the same scenario) to specify a version constraint for only one cookbook: ``` cookbook 'couchdb', '= 11.0.0' ``` More than one cookbook version can be specified: ``` cookbook_versions({ 'couchdb' => '= 11.0.0', 'my_rails_app' => '~> 1.2.0' }) ``` Attributes are optional and can be set at the default and override levels. These will be processed according to attribute precedence. An environment attribute will be applied to all nodes within the environment, except in places where it is overridden by an attribute with higher precedence. For example: ``` default_attributes 'apache2' => { 'listen_ports' => %w(80 443) } ``` will have all nodes in the environment (`node[:apache2][:listen_ports]`) set to `'80'` and `'443'` unless they were overridden by an attribute with higher precedence. For example: ``` override_attributes 'apache2' => { 'listen_ports' => %w(80 443) } ``` ### JSON The JSON format for environments maps directly to the domain-specific Ruby format: the same settings, attributes, and values, and a similar structure and organization, just formatted as JSON. When an environment is defined as JSON the file that contains that data must be defined as a file that ends with `.json`. For example: ``` { "name": "dev", "default_attributes": { "apache2": { "listen_ports": [ "80", "443" ] } }, "json_class": "Chef::Environment", "description": "", "cookbook_versions": { "couchdb": "= 11.0.0" }, "chef_type": "environment" } ``` The JSON format has two additional settings: | Setting | Description | | --- | --- | | `chef_type` | Always set this to `environment`. Use this setting for any custom process that consumes environment objects outside of Ruby. | | `json_class` | Always set this to `Chef::Environment`. Chef Infra Client uses this setting to auto-inflate an environment object. If objects are being rebuilt outside of Ruby, ignore it. | Create Environments ------------------- An environment can be created in four different ways: * Creating a Ruby file in the environments sub-directory of the chef-repo and then pushing it to the Chef server * Creating a JSON file directly in the chef-repo and then pushing it to the Chef server * Using knife * Using the Chef Infra Server REST API Once an environment exists on the Chef Infra Server, a node can be associated with that environment using the `chef_environment` method. Manage Environments ------------------- Once created, an environment can be managed in several ways: * By using knife and passing the `-E ENVIRONMENT_NAME` option with `knife cookbook upload` * By using Ruby or JSON files that are stored in a version source control system. These files are pushed to the Chef Infra Server using the `knife environment` subcommand and the `from file` argument. This approach allows environment data to be dynamically generated. This approach will not work unless these files are defined in the proper format—Ruby file end with `.rb`; JSON files end with `.json`. These workflows are mutually exclusive: only the most recent environment changes will be kept on the Chef Infra Server, regardless of the source of those changes. All previous changes are overwritten when environment data is updated. The settings for environments can be modified and environments can be integrated into the larger infrastructure by associating them with nodes and by using recipes to call specific environment settings. ### Find Environment from Recipe Use the following syntax to find the current environment from a recipe: ``` node.environment ``` or: ``` node.chef_environment ``` ### Save in a Data Bag Values that are stored in a data bag are global to the organization and are available to any environment. There are two main strategies that can be used to store per-environment data within a data bag: by using a top-level key that corresponds to the environment or by using separate items for each environment. A data bag that is storing a top-level key for an environment might look something like this: ``` { "id": "some_data_bag_item", "production" : { // Hash with all your data here }, "testing" : { // Hash with all your data here } } ``` When using the data bag in a recipe, that data can be accessed from a recipe using code similar to: ``` bag_item[node.chef_environment]['some_other_key'] ``` The other approach is to use separate items for each environment. Depending on the amount of data, it may all fit nicely within a single item. If this is the case, then creating different items for each environment may be a simple approach to providing per-environment values within a data bag. However, this approach is more time-consuming and may not scale to very large environments or when the data must be stored in many data bag items. ### Override Attributes in Roles Environment attributes that are used with roles can be overridden. Typically, this is done by using attribute precedence, but sometimes it may be necessary to ensure that specific attributes are used based on the presence of specific environments. This type of scenario is best addressed in using a recipe that relies on a top-level key that is stored in a data bag. For example, to retrieve a value from a data bag based on a specific environment: ``` mything = data_bag_item('things', 'mything') attribute_i_want = mything[node.chef_environment] ``` ### Set for a Node A node is considered to be associated with an environment when the `chef_environment` attribute is set. The `chef_environment` attribute cannot be set with normal or override attributes (i.e. in a role) because it is actually a method. An environment may be set explicitly using the following methods: * By using the `knife edit` and `knife exec` subcommands * By editing the `environment` configuration details in the client.rb file, and then using `knife bootstrap -e environment_name` to bootstrap the changes to the specified environment Note After the environment has been set via bootstrap, the environment is set in the client.rb file and may not be modified using the `edit` argument of the `knife node` subcommand. * By setting the `environment` configuration entry in the client.rb file ; when Chef Infra Client runs, it will pick up the value and then set the `chef_environment` attribute of the node ### Move Nodes Use the `knife exec` subcommand to move nodes between environments, such as from a “dev” to a “production” environment. For example: ``` knife exec -E 'nodes.transform("chef_environment:dev") { |n| n.chef_environment("production") }' ``` ### Search Environments When searching, an environment is an attribute. This allows search results to be limited to a specified environment by using Boolean operators and extra search terms. For example, to use knife to search for all of the servers running CentOS in an environment named “QA”, enter the following: ``` knife search node "chef_environment:QA AND platform:centos" ``` Or, to include the same search in a recipe, use a code block similar to: ``` qa_nodes = search(:node, 'chef_environment:QA') qa_nodes.each do |qa_node| # Do useful work specific to qa nodes only end ``` Environments in Chef Solo ------------------------- An environment is defined using JSON or the Ruby DSL. chef-solo will look for environments in `/var/chef/environments`, but this location can be modified by changing the setting for `environment_path` in solo.rb. For example, the following setting in solo.rb: ``` environment_path '/var/chef-solo/environments' ``` Environment data looks like the following in JSON: ``` { "name": "dev", "default_attributes": { "apache2": { "listen_ports": [ "80", "443" ] } }, "json_class": "Chef::Environment", "description": "", "cookbook_versions": { "couchdb": "= 11.0.0" }, "chef_type": "environment" } ``` and like the following in the Ruby DSL: ``` name 'environment_name' description 'environment_description' cookbook OR cookbook_versions 'cookbook' OR 'cookbook' => 'cookbook_version' default_attributes 'node' => { 'attribute' => %w(value value etc.) } override_attributes 'node' => { 'attribute' => %w(value value etc.) } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/environments/Chef and VMware =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/vmware.md) VMware, Inc. is a subsidiary of Dell Technologies that provides cloud computing and platform virtualization software and services. This page outlines the different tools that can be used to integrate Chef with the VMware platform. For discussions on VMware and Chef, visit the [VMware{code}](https://code.vmware.com/web/code/join) Slack team, located in the **#chef** channel. knife ----- There are multiple knife plugins that interact with the VMware stack in different ways. The following knife plugins are directly supported by Chef: ### knife-vsphere [[GitHub]](https://github.com/chef-partners/knife-vsphere) * Supports vCenter > 5.0 * Most VMware compute use cases are covered * The main starting point for Chef and VMware These are the necessary settings for your `config.rb` file: ``` knife[:vsphere_host] = 'vcenter-hostname' knife[:vsphere_user] = 'privileged username' # Domain logins may need to be "<EMAIL>" knife[:vsphere_pass] = 'password' # or %Q(mypasswordwithfunnycharacters) knife[:vsphere_dc] = 'your-datacenter' knife[:vsphere_insecure] = true # Set this if you have self signed certs ``` #### Usage Examples **Clone from a VMware template and bootstrap Chef with generic DHCP options:** ``` knife vsphere vm clone MACHINENAME --template TEMPLATENAME --bootstrap --cips dhcp ``` **Clone a virtual machine from a VMware template, use a customization template called “SPEC” to assist the bootstrapping process, and specify the SSH user and password:** ``` knife vsphere vm clone MACHINENAME --template TEMPLATENAME --bootstrap --cips dhcp \ --cspec SPEC --connection-user USER --connection-password PASSWORD ``` Note Add a `-f FOLDERNAME` if you put your `--template` in a directory other than the root folder. Use `--dest-folder FOLDERNAME` if you want your VM created in `FOLDERNAME` instead of the root folder. **Clone from a folder into the “Datacenter Root” directory:** ``` knife vsphere vm clone MACHINENAME --template TEMPLATENAME -f /path/to/template \ --bootstrap --start --cips dhcp --dest-folder / ``` **List the available VMware templates:** ``` knife vsphere template list Template Name: ubuntu16-template knife vsphere template list -f FOLDERNAME Template Name: centos7-template ``` **Delete a machine:** ``` knife vsphere vm delete MACHINENAME ``` This command can be used with the `-P` option to remove the machine from the Chef Infra Server. ### knife-vcenter [[GitHub]](https://github.com/chef/knife-vcenter) * Supports vCenter >= 6.5 REST API * Supports the main use cases of knife: `bootstrap`, `create`, `destroy`, and `list` * If you have the [VCSA](https://docs.vmware.com/en/VMware-vSphere/6.5/com.vmware.vsphere.vcsa.doc/GUID-223C2821-BD98-4C7A-936B-7DBE96291BA4.html) or are planning on upgrading to vCenter 6.5+, this is the plugin to use The main settings for your `config.rb`: ``` knife[:vcenter_username] = 'user' knife[:vcenter_password] = 'password' knife[:vcenter_host] = '172.16.20.2' knife[:vcenter_disable_ssl_verify] = true # if you want to disable SSL checking ``` #### Usage Examples **Clone a machine:** ``` knife vcenter vm clone example-01 --targethost 172.16.20.3 --folder example --connection-password \ P@ssw0rd! --datacenter Datacenter --template ubuntu16-template -N example-01 Creating new machine Waiting for network interfaces to become available... ID: vm-183 Name: example-01 Power State: POWERED_ON Bootstrapping the server by using bootstrap_protocol: ssh and image_os_type: linux Waiting for sshd to host (10.0.0.167) ... ``` **Delete a machine:** ``` knife vcenter vm delete example-01 -N example-01 --purge Creating new machine Waiting for network interfaces to become available... ID: vm-183 Name: example-01 Power State: POWERED_ON Bootstrapping the server by using bootstrap_protocol: ssh and image_os_type: linux Waiting for sshd to host (10.0.0.167) WARNING: Deleted node example-01 WARNING: Deleted client example-01 ``` ### knife-vrealize [[GitHub]](https://github.com/chef-partners/knife-vrealize) * Supports both vRealize Automation and vRealize Orchestrator * Supports vRealize Automation 7.0+ * If you have vRealize Automation < 7.0, you will need to downgrade the [vmware-vra-gem](https://github.com/chef-partners/vmware-vra-gem) to version `1.7.0` * Supports the main use cases of knife: `bootstrap`, `create`, `destroy`, and `list` * Directly integrates with vRA to call out predetermined blueprints or catalogs * Can integrate directly with vRO to call out predetermined workflows The main settings for your `config.rb`: ``` knife[:vra_username] = 'user' knife[:vra_password] = 'password' knife[:vra_base_url] = 'https://vra.corp.local' knife[:vra_tenant] = 'tenant' knife[:vra_disable_ssl_verify] = true # if you want to disable SSL checking. ``` Additional `config.rb` settings are required to integrate with vRO: ``` knife[:vro_username] = 'user' knife[:vro_password] = 'password' knife[:vro_base_url] = 'https://vra.corp.local:8281' ``` A basic clone example for vRA is: Creates a server from a catalog blueprint. Find the catalog ID with the `knife vra catalog list` command. After the resource is created, knife will attempt to bootstrap it. Each blueprint may require different parameters to successfully complete provisioning. See your vRA administrator with questions. Knife will attempt to provide any helpful error messages from vRA if they’re available. Common parameters to specify are: * `--cpus`: number of CPUs * `--memory`: amount of RAM in MB * `--requested-for`: vRA login that should be listed as the owner * `--lease-days`: number of days for the resource lease * `--notes`: any optional notes you’d like to be logged with your request * `--subtenant-id`: all resources must be tied back to a Business Group, or “subtenant.” If your catalog item is tied to a specific Business Group, you do not need to specify this. However, if your catalog item is a global catalog item, then the subtenant ID is not available to knife; you will need to provide it. It usually looks like a UUID. See your vRA administrator for assistance in determining your subtenant ID. * `--connection-password`: for Linux hosts, the password to use during bootstrap * `--winrm-password`: for Windows hosts, the password to use during bootstrap ``` knife vra server create 5dcd1900-3b89-433d-8563-9606ae1249b8 --cpus 1 --memory 512 \ --requested-for <EMAIL> --connection-password my_password --lease-days 5 Catalog request d282fde8-6fd2-406c-998e-328d1b659078 submitted. Waiting for request to complete. Current request status: PENDING_PRE_APPROVAL. Current request status: IN_PROGRESS.. ... ``` #### Usage Examples **Delete a server from vRA:** ``` knife vra server delete 2e1f6632-1613-41d1-a07c-6137c9639609 --purge Server ID: 2e1f6632-1613-41d1-a07c-6137c9639609 Server Name: hol-dev-43 IP Addresses: 192.168.110.203 Status: ACTIVE Catalog Name: CentOS 6.6 Do you really want to delete this server? (Y/N) Y Destroy request f2aa716b-ab24-4232-ac4a-07635a03b4d4 submitted. Waiting for request to complete. Current request status: PENDING_PRE_APPROVAL. Current request status: IN_PROGRESS... ... ``` If you supply the `--purge` option, the server will also be removed from the Chef Infra Server **Execute a vRO workflow:** ``` knife vro workflow execute "knife testing" key1=value1 Starting workflow execution... Workflow execution 4028eece4effc046014f27da864d0187 started. Waiting for it to complete... Workflow execution complete. Output Parameters: outkey1: some value (string) Workflow Execution Log: 2015-08-13 09:17:57 -0700 info: cloudadmin: Workflow 'Knife Testing' has started 2015-08-13 09:17:58 -0700 info: cloudadmin: Workflow 'Knife Testing' has completed ``` This requires the workflow name. You may supply any input parameters, as well. If your workflow name is not unique in your vRO workflow list, you can specify a workflow to use with `--vro-workflow-id ID`. You can find the workflow ID from within the vRO UI. However, a workflow name is still required by the API. test-kitchen ------------ The following test-kitchen drivers for VMware are directly supported by Chef: ### kitchen-vsphere (chef-provisioning-vsphere) [[GitHub]](https://github.com/chef-partners/chef-provisioning-vsphere) * Built into the chef-provisioning-vsphere driver * A community driven project, with Chef Partners maintaining the releases * Leverages the typical test-kitchen workflow for vCenter > 5.0+ * There is a [kitchen-vsphere](https://rubygems.org/gems/kitchen-vsphere) gem, but it is not supported at this time #### Usage Examples There is an [example cookbook](https://github.com/jjasghar/vsphere_testing) that attempts to capture everything required. The following is a basic `kitchen.yml` example: ``` ---driver:name:vspheredriver_options:host:FQDN or IP of vCenteruser:'<EMAIL>'password:'PASSWORD'insecure:truemachine_options:start_timeout:600create_timeout:600ready_timeout:90bootstrap_options:use_linked_clone:truedatacenter:'Datacenter'template_name:'ubuntu16'template_folder:'Linux'resource_pool:'Cluster'num_cpus:2memory_mb:4096ssh:user:ubuntuparanoid:falsepassword:PASSWORDport:22provisioner:name:chef_zerosudo_command:sudoverifier:name:inspectransport:username:root or ssh enabled userpassword:PASSWORD for root or userplatforms:- name:ubuntu-18.04- name:centos-8suites:- name:defaultrun_list:- recipe[COOKBOOK::default]attributes: ``` ### kitchen-vcenter [[GitHub]](https://github.com/chef/kitchen-vcenter) * Supports vCenter >= 6.5 REST API * Leverages the typical test-kitchen workflow for vCenter >= 6.5+ * If you have the [VCSA](https://docs.vmware.com/en/VMware-vSphere/6.5/com.vmware.vsphere.vcsa.doc/GUID-223C2821-BD98-4C7A-936B-7DBE96291BA4.html) or are planning on upgrading to vCenter 6.5+, use this plugin #### Usage Examples The following is a basic `kitchen.yml` for vCenter: ``` driver:name:vcentervcenter_username:<%= ENV['VCENTER_USER'] || "<EMAIL>" %>vcenter_password:<%= ENV['VCENTER_PASSWORD'] || "password" %>vcenter_host:vcenter.chef.iovcenter_disable_ssl_verify:truedriver_config:targethost:172.16.20.41datacenter:"Datacenter"platforms:- name:ubuntu-2004driver_config:template:ubuntu16-template- name:centos-8driver_config:template:centos7-template ``` ### kitchen-vra [[GitHub]](https://github.com/chef-partners/kitchen-vra) * An integration point with vRA and test-kitchen * For companies required to use vRA this is a natural progression for Chef Development #### Usage Examples The following is a basic `kitchen.yml` example: ``` driver:name:vrausername:<EMAIL>password:passwordtenant:tenantbase_url:https://vra.corp.localverify_ssl:trueplatforms:- name:centos6driver:catalog_id:e9db1084-d1c6-4c1f-8e3c-eb8f3dc574f9- name:centos7driver:catalog_id:c4211950-ab07-42b1-ba80-8f5d3f2c8251 ``` ### kitchen-vro [[GitHub]](https://github.com/chef-partners/kitchen-vro) * An integration point with vRO and test-kitchen * Leverages specific Workflows in vRO if it’s required by VMware admins #### Usage Examples The following is a basic `kitchen.yml` example: ``` driver:name:vrovro_username:user@domain.comvro_password:passwordvro_base_url:https://vra.corp.local:8281create_workflow_name:Create TK Serverdestroy_workflow_name:Destroy TK Serverplatforms:- name:centosdriver:create_workflow_parameters:os_name:centosos_version:6.7- name:windowsdriver:create_workflow_parameters:os_name:windowsos_version:server2012cpus:4memory:4096 ``` Chef InSpec ----------- The Chef InSpec VMware plugin is used to verify the vCenter and ESXi VMware stack. ### inspec-vmware [[GitHub]](https://github.com/chef/inspec-vmware) * Supports vCenter > 5.0 * 11 resources available at the time of writing, with more planned #### Usage Examples An example demo control: ``` control 'vmware-1' do impact 0.7 title 'Checks that soft power off is disabled' describe vmware_vm_advancedsetting({ datacenter: 'ha-datacenter', vm: 'testvm' }) do its('softPowerOff') { should cmp 'false' } end end ``` Chef integrations inside of the VMware Suite -------------------------------------------- ### vRA Example Blueprints * [Linux](https://code.vmware.com/samples?id=1371) * [Windows](https://code.vmware.com/samples?id=1390) ### vRO plugin * The [Chef plugin for vRealize Orchestrator](https://solutionexchange.vmware.com/store/products/chef-plugin-for-vrealize-orchestrator) (vRO) is a VMware-supplied plugin * If you use vRO this provides the majority of the necessary features For more information, see the plugin demo on [YouTube](https://www.youtube.com/watch?v=HlvoZ4Zdwc4). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/vmware/Azure Test Drive ================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/azure_testdrive.md) Chef Automate is an enterprise platform that allows developers, operations, and security engineers to collaborate on application and infrastructure changes with speed and at scale. Chef Automate provides actionable insights across data centers and cloud providers, wherever your nodes live. Chef Automate is the center of the modern Chef platform, providing users with a single source of truth for infrastructure, security, and application automation. The comprehensive dashboard provides real-time views of your configuration management activity. Chef Automate comes bundled with the latest Chef Infra Server, providing the core tools you need to manage your enterprise infrastructure. Data collection is enabled by default, allowing your nodes to report activity in real-time. This instance is free for 60 days or you can bring your own license (BYOL). Use this instance with Chef Workstation installed on your laptop or a separate Azure instance. Chef Workstation includes: * Chef Infra Client * Chef InSpec * Chef Habitat * `chef` and `knife` command line tools * Testing tools, such as Test Kitchen and Cookstyle * Everything else needed to author cookbooks and upload them to the Chef Infra Server. If you need to run Automate with a high availability (HA) topology, please contact [Chef Support](https://www.chef.io/support). Test Drive ---------- A **Test Drive** is a ready-to-go environment that allows you to experience Chef Automate for free, without an Azure subscription (You will need a [Microsoft account](https://signup.live.com/). The Test Drive comes already provisioned—you don’t need to download, set up, or configure it—instead, you can spend two hours evaluating the user experience, key features, and benefits of the product. ### Get Started 1. Navigate to Chef Automate on the [Azure Marketplace](https://azuremarketplace.microsoft.com/en-us/marketplace/apps/chef-software.chef-automate). ![Azure Home Page] 2. Select **Test Drive**. ![Test Drive] 3. Sign in with your Microsoft account email address. ![Sign In] 4. Enter your password and select **Sign In**. ![Enter Password] 5. Select **Continue** to accept the Microsoft information terms. ![ Agree to MS information use policy and select continue] ### Deploy Automate 1. Chef Automate deploys automatically. It takes about 15 minutes to finish. ![Deploy In Progress] 2. Once Chef Automate deploys, you have **2 hours** to explore. ![Chef Automate Deployed] ### Connect 1. Within 5 minutes of the Chef Automate deployment, you will receive an email with your username, password, and the URL for your deployment. ![GoToTDPage] 2. Open your browser and access the Chef Automate URL and select Advanced and continue as shown below ![insecure site warning] 3. Enter your username, password from the email and select **Sign In** to Access Chef Automate ![automate_signin] 4. Enter your name and email address, accept the Chef license, and then select **Register** ![AutomateWelcomePage] 5. Congratulations! You’re ready to explore Chef Automate! ![automate_event_feed] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/azure_testdrive/Azure Marketplace ================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/azure_marketplace.md) Chef Automate is an enterprise platform that allows developers, operations, and security engineers to collaborate on application and infrastructure changes with speed and at scale. Chef Automate provides actionable insights across data centers and cloud providers, wherever your nodes live. Chef Automate is the center of the modern Chef platform, providing users with a single source of truth for infrastructure, security, and application automation. The comprehensive dashboard provides real-time views of your configuration management activity. Chef Automate comes bundled with the latest Chef Infra Server, providing the core tools you need to manage your enterprise infrastructure. Data collection is enabled by default, allowing your nodes to report activity in real-time. This instance is free for 60 days or you can bring your own license (BYOL). Use this instance with Chef Workstation installed on your laptop or a separate Azure instance. Chef Workstation includes: * Chef Infra Client * Chef InSpec * Chef Habitat * `chef` and `knife` command line tools * Testing tools, such as Test Kitchen and Cookstyle * Everything else needed to author cookbooks and upload them to the Chef Infra Server. If you need to run Automate with a high availability (HA) topology, please contact [Chef Support](https://www.chef.io/support). Marketplace Deployment ---------------------- The **Marketplace Deployment** is a test-level Chef Automate environment. This deployment requires an Azure account or subscription. You can provision Chef Automate directly from Azure. This Chef Automate solution requires that you bring your own license (BYOL). New users may try this solution for up to 60 days. Contact us at [<EMAIL>](mailto:<EMAIL>) to obtain a license. ### Get Started 1. Navigate to Chef Automate on the [Azure Marketplace](https://azuremarketplace.microsoft.com/marketplace/apps/chef-software.chef-automate). ![Azure Home Page] 2. Select **Get it Now**. ![Get It Now] 3. Sign in to your Microsoft account with your Microsoft account email address. ![Sign In] 4. Enter your password and select **Sign In**. ![Enter Password] 5. Select **Continue** to accept the Microsoft information terms. ![Continue] ### Deploy Automate 1. Select **Create** to create your Chef Automate instance. ![Create Automate] 2. Enter the project details and select **Next**: 1. `Subscription`: Select the your subscription 2. `Resource group`: Create new or select an existing one 3. `Region`: Select the region for your instance![Subscription Page] 3. Enter your custom settings and select **Next: Review + create** to validate your configuration. 1. `Username`: Example:`chefuser` 2. `SSH public key`: Copy your existing public key or make a new key pair. 3. `Size`: The vCPUs and memory for your instance. The recommended minimum is 4vCPUs and 16GB memory. Example: `Standard D4s v3`![ Custom Settings] 4. Review your validated configuration and select **Create** to deploy Chef Automate. ![Validation Page] 5. Chef Automate takes about 15 minutes to deploy. ![Deploy In Progress Page] 6. Once the Chef Automate deployment completes, select **Go to resource group**. ![Deploy Complete Page] ### Connect 1. On the *Resource group* page for your installation, select the Chef Automate virtual machine (VM), which is named `RESOURCE-GROUP-ipg6-VM`. ![Overview Page] 2. Locate and copy the `Public IP` on the *Virtual machine* page. You will use this to connect to your VM. ![Deploy Description] 3. From the command line, connect to your VM: ``` ssh -i chefkey.pem chefuser@13.92.241.41 ``` ![SSH into your instance with your Automate pem key] 1. Get your Chef Automate URL and login credentials from the command line: ``` sudo cat /root/automate-credentials.toml ``` Which returns something like: ``` url = "https://chef-automate-example.eastus.cloudapp.azure.com" username = "admin" password = "EXAMPLE1234567890abcdefghijklmno" ``` 2. Open your favorite browser and Access the Chef Automate URL and Select **Advanced** and continue as shown below: ![Insecure site warning] 3. Enter your username, password and select **Sign In to Access Chef Automate WebUI**. ![Automate Sign In ] 4. Enter your name and email address, accept the Chef license, and then select **Register**. ![Automate Welcome] 5. Congratulations! You’re ready to explore Chef Automate! ![Automate Event Feed] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/azure_marketplace/Chef Workstation in Azure Cloud Shell ===================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/azure_cwa_cloud_shell.md) Chef Workstation is available in Azure Cloud Shell, allowing users to run ad-hoc configurations on target systems and any other Chef command when connected to an Azure subscription. This makes all of the Chef command line tools available, without installing software on a local machine. Chef Workstation on Azure Cloud Shell lets you use: * [chef](../ctl_chef/index) * [kitchen](../workstation/ctl_kitchen/index) * [inspec](../inspec/cli/index) * [knife](../workstation/knife/index) * [cookstyle](../workstation/cookstyle/index) * [chef-run](../workstation/chef_run/index) Combine the Chef Workstation command utilities with the other tools available in Cloud Shell, such as git, az-cli, terraform to write your infrastructure and compliance automation from the browser–without the need for a local shell. Azure Cloud Shell Installation ------------------------------ Ensure you have an accessible Azure Cloud Shell instance. You may need to create a storage account to use Azure Cloud Shell if you haven’t used it before in this tenant. For more information on accessing, setting up, and using Azure Cloud Shell, see the [Cloud Shell Documentation](https://docs.microsoft.com/en-us/azure/cloud-shell/quickstart). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/azure_cwa_cloud_shell/Microsoft Azure PowerShell ========================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/azure_powershell.md) PowerShell Cmdlets ------------------ If Windows PowerShell is installed on the workstation, along with the Azure Chef Extension, the `Get-AzureVMChefExtension` and `Set-AzureVMChefExtension` extensions may be used to manage Chef running on virtual machines in Microsoft Azure. ### Get-AzureVMChefExtension Use the `Get-AzureVMChefExtension` cmdlet to get the details for the Azure Chef Extension that is running on the named virtual machine. #### Syntax This cmdlet has the following syntax: ``` Get-AzureVMChefExtension -VM <string``` #### Example The following examples show how to use the `Get-AzureVMChefExtension` cmdlet: ##### Get details for a virtual machine ``` Get-AzureVM -ServiceName cloudservice1 -Name azurevm1 | Get-AzureVMExtension ``` ### Set-AzureVMChefExtension Use the `Set-AzureVMChefExtension` cmdlet to enable Chef on any virtual machine running on Microsoft Azure. #### Syntax This cmdlet has the following syntax. For Microsoft Windows: ``` Set-AzureVMChefExtension -ValidationPem <String> -VM <IPersistentVM> -Windows [-ChefServerUrl <String> ] [-ClientRb <String> ] [-OrganizationName <String> ] [-RunList <String> ] [-ValidationClientName <String> ] [-Version <String> ] [ <CommonParameters>] ``` For Linux: ``` Set-AzureVMChefExtension -Linux -ValidationPem <String> -VM <IPersistentVM> [-ChefServerUrl <String> ] [-ClientRb <String> ] [-OrganizationName <String> ] [-RunList <String> ] [-ValidationClientName <String> ] [-Version <String> ] [ <CommonParameters>] ``` #### Options This cmdlet has the following options: `-AutoUpdateChefClient` Auto-update . Set to `true` to auto update the version of the Azure Chef Extension when the virtual machine is restarted. For example, if this option is enabled, a virtual machine that has version `1205.12.2.0` will be updated automatically to `1205.12.2.1` when it is published. `-BootstrapOptions <string>` A JSON string that is added to the first run of a Chef Infra Client. For example: ``` -BootstrapOptions '{"chef_node_name":"test_node"}' ``` Supported options: `"chef_node_name"`, `"chef_server_url"` (required), `"environment"`, `"secret"`, and `"validation_client_name"` (required). `-ChefServerUrl <string>` The URL for the Chef Infra Server. `-ClientRb <string>` The path to the `client.rb` file. `-DeleteChefConfig` Disable the Azure Chef Extension extension. `-Linux` Sets the Azure Chef Extension to run Linux. `-OrganizationName <string>` The name of the organization on the Chef Infra Server. `-RunList <string>` A comma-separated list of roles and/or recipes to be applied. `-ValidationClientName <string>` The name of the chef-validator key Chef Infra Client uses to access the Chef Infra Server during the initial Chef Infra Client run. `-ValidationPem <string>` The location of the file that contains the key used when a Chef Infra Client is registered with a Chef Infra Server. A validation key is signed using the `validation_client_name` for authentication. Default value: `/etc/chef/validation.pem`. `-Version <string>` Specify the version number for the Azure Chef Extension extension. Default is to use the latest extension’s version number. `-Windows` Sets the Azure Chef Extension to run Microsoft Windows. #### Examples The following examples show how to use the `Set-AzureVMChefExtension` cmdlet: ##### Create Windows virtual machine ``` $vm1 = "azurechefwin" $svc = "azurechefwin" $username = 'azure' $password = 'azure@123' $img = "a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-201406.01-en.us-127GB.vhd" $vmObj1 = New-AzureVMConfig -Name $vm1 -InstanceSize Small -ImageName $img $vmObj1 = Add-AzureProvisioningConfig -VM $vmObj1 -Password $password -AdminUsername $username -Windows # set azure chef extension $vmObj1 = Set-AzureVMChefExtension -VM $vmObj1 -ValidationPem "C:\\users\\azure\\msazurechef-validator.pem" -ClientRb "C:\\users\\azure\\client.rb" -RunList "getting-started" -Windows New-AzureVM -Location 'West US' -ServiceName $svc -VM $vmObj1 ``` ##### Create CentOS virtual machine ``` $vm1 = "azurecheflnx" $svc = "azurecheflnx" $username = 'azure' $password = 'azure@123' # CentOS image id $img = "5112500ae3b842c8b9c604889f8753c3__OpenLogic-CentOS-71-20150605" $vmObj1 = New-AzureVMConfig -Name $vm1 -InstanceSize Small -ImageName $img $vmObj1 = Add-AzureProvisioningConfig -VM $vmObj1 -Password $password -Linux -LinuxUser $username # set azure chef extension $vmObj1 = Set-AzureVMChefExtension -VM $vmObj1 -ValidationPem "C:\\users\\azure\\msazurechef-validator.pem" -ClientRb "C:\\users\\azure\\client.rb" -RunList "getting-started" -Linux New-AzureVM -Location 'West US' -ServiceName $svc -VM $vmObj1 ``` ##### Create Ubuntu virtual machine ``` $vm1 = "azurecheflnx" $svc = "azurecheflnx" $username = 'azure' $password = 'azure@123' $img = "b39f27a8b8c64d52b05eac6a62ebad85__ubuntu-20_04_5-LTS-amd64-server-20150127-en-us-30GB" $vmObj1 = New-AzureVMConfig -Name $vm1 -InstanceSize Small -ImageName $img $vmObj1 = Add-AzureProvisioningConfig -VM $vmObj1 -Password $password -Linux -LinuxUser $username # set azure chef extension $vmObj1 = Set-AzureVMChefExtension -VM $vmObj1 -ValidationPem "C:\\users\\azure\\msazurechef-validator.pem" -ClientRb "C:\\users\\azure\\client.rb" -RunList "getting-started" -Linux New-AzureVM -Location 'West US' -ServiceName $svc -VM $vmObj1 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/azure_powershell/Microsoft Azure CLI =================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/azure_chef_cli.md) The Azure Chef Extension is an extension for Microsoft Azure to enable Chef on virtual machine instances. The extension makes available two Windows PowerShell cmdlets and two Microsoft Azure CLI commands. Azure CLI --------- If the Microsoft Azure [cross-platform command line tool (Xplat-CLI)](https://github.com/Azure/azure-xplat-cli) is installed on the workstation, along with the Azure Chef Extension, the `get-chef` and `set-chef` extensions may be used to manage Chef running on virtual machines in Microsoft Azure. ### get-chef Use the `get-chef` command to get the details for the Azure Chef Extension that is running on the named virtual machine. #### Syntax This command has the following syntax: ``` azure vm extension get-chef VM_NAME ``` ### set-chef Use the `set-chef` command to enable Chef on any virtual machine running on Microsoft Azure. #### Syntax This command has the following syntax: ``` azure vm extension set-chef VM_NAME (options) ``` #### Options This command has the following options: `-a`, `--auto-update-client` Auto-update Chef Infra Client. Set to `true` to auto update the version of the Azure Chef Extension when the virtual machine is restarted. For example, if this option is enabled, a virtual machine that has version `1205.12.2.0` will be updated automatically to `1205.12.2.1` when it is published. Default value: `false`. `-b`, `--disable` Disable the Azure Chef Extension extension. `-c PATH_TO_CONFIG`, `--client-config PATH_TO_CONFIG` The path to the `client.rb` file. `-C CLIENT_PEM`, `--client-pem CLIENT_PEM` The location of the file that contains the client key. Default value: `/etc/chef/client.pem`. `-D`, `--delete-chef-config` Disable the Azure Chef Extension extension. `-j JSON`, `--bootstrap-options JSON` A JSON string that is added to the first run of a Chef Infra Client. For example: ``` -j '{"chef_node_name":"test_node"}' ``` Supported options: `"chef_node_name"`, `"chef_server_url"`(required), `"environment"`, `"secret"`, and `"validation_client_name"` (required). `-O VALIDATOR_PEM`, `--validation-pem VALIDATOR_PEM` The location of the file that contains the key used when a Chef Infra Client is registered with a Chef Infra Server. A validation key is signed using the `validation_client_name` for authentication. Default value: `/etc/chef/validation.pem`. `-R RUN_LIST`, `--run-list RUN_LIST` A comma-separated list of roles and/or recipes to be applied. `-u`, `--uninstall` Uninstall the Azure Chef Extension. `-V NUMBER`, `--version NUMBER` Specify the version number for the Azure Chef Extension extension. Default is to use the latest extension’s version number. #### Examples The following examples show how to use this knife subcommand: ##### Create a virtual machine ``` azure vm create your-vm-name MSFT__Windows-Server-2012 yourusername yourpassword --location "West US" -r ``` ##### Set the Chef extension without a run-list ``` azure vm extension set-chef your-vm-name --validation-pem ~/chef-repo/.chef/testorg-validator.pem --client-config ~/chef-repo/.chef/client.rb --version "1201.12" ``` ##### Set the Chef extension with a run-list ``` azure vm extension set-chef your-vm-name --validation-pem ~/chef-repo/.chef/testorg-validator.pem --client-config ~/chef-repo/.chef/client.rb --version "1201.12" -R 'recipe[your_cookbook_name::your_recipe_name]' ``` ##### Azure Resource Manager (ARM) Templates If you are using Azure Resource Manager templates to create your infrastructure you can use the Chef extension to have Azure handle the bootstrapping/configuration of your node to your Chef Infra Server. ### Options The extension has the following options that can be provided in the **settings** hash. `runlist` A comma-separated list of roles and/or recipes to be applied. `client_rb` A JSON escaped string containing the content of your `client.rb` file. `validation_key_format` Tells the extension whether the supplied validation key is `plaintext` or `base64encoded`. Note If using the Chef extension in an ARM template, it is recommended that you base64 encode your validation key and set this option to `base64encoded` `bootstrap_version` The version of Chef Infra Client that will be installed on the system. **linux only** Note Due to constraints in Azure, the `bootstrap_version` option is only available on the `LinuxChefClient` extension. `bootstrap_channel` Specify the [channel](../packages/index) for installing the Chef Infra Client version. Options are `stable`, `current` or `unstable` release channels. `chef_package_path` Specifies a local path to install Chef Infra Client from. This feature is mainly used for cases where there are restrictions on internet access. Note Azure extensions have network access limitations. See the [Azure documentation](https://docs.microsoft.com/en-us/azure/virtual-machines/extensions/features-linux#network-access) for more information. `CHEF_LICENSE` Chef Infra Client 15+ requires accepting the CHEF EULA license. Set `CHEF_LICENSE` to one of these values `accept`, `accept-silent` or `accept-no-persist`. Refer to [CHEF EULA license](../chef_license_accept/index#accept-the-chef-eula) `hints` Specifies the [Ohai Hints](../ohai/index#hints) to be set in the Ohai configuration of the target node. `chef_package_url` Specifies a URL to download and install the Chef Infra Client package (.msi .rpm .deb) from. `bootstrap_options` A hash of the following options: `chef_node_name`, `chef_server_url`, `environment`, `secret`, and `validation_client_name`. Note Options that are supplied in the bootstrap items will take precedence over any conflicts found in the `client.rb` file. `chef_node_name` Determines which configuration should be applied and sets the `client_name`, which is the name used when authenticating to a Chef Infra Server. The default value is the the Chef Infra Client FQDN, as detected by Ohai. In general, Chef recommends that you leave this setting blank and let Ohai assign the FQDN of the node as the `node_name` during each Chef Infra Client run. `chef_server_url` The URL for the Chef Infra Server. `environment` The environment this machine will be placed in on your Chef Infra Server. `secret` The encryption key that is used for values contained within a data bag item. `validation_client_name` The name of the chef-validator key that Chef Infra Client uses to access the Chef Infra Server during the initial Chef Infra Client run. `node_ssl_verify_mode` Set the verify mode for HTTPS requests. `node_verify_api_cert` Verify the SSL certificate on the Chef Infra Server. When `true`, Chef Infra Client always verifies the SSL certificate. When `false`, Chef Infra Client uses the value of `ssl_verify_mode` to determine if the SSL certificate requires verification. #### Protected Settings The following options can be provided to the extension through the `protectedSettings` hash: `validation_key` The contents of your organization validator key, the format is dependent on `validation_key_format`. `chef_server_crt` The SSL certificate of your Chef Infra Server that will be added to the trusted certificates. `client_pem` A client key that will be used to communication with the Chef Infra Server. ### Examples The following examples show how Chef Infra Client can be installed and configured from an ARM template. #### Installing the Azure Chef extension on a Linux system ``` { "type": "Microsoft.Compute/virtualMachines/extensions", "name": "myVirtualMachine/LinuxChefClient", "apiVersion": "2015-05-01-preview", "location": "westus", "properties": { "publisher": "Chef.Bootstrap.WindowsAzure", "type": "LinuxChefClient", "typeHandlerVersion": "1210.12", "settings": { "bootstrap_options": { "chef_node_name": "node1", "chef_server_url": "https://api.chef.io/organizations/my-chef-organization", "validation_client_name": "my-chef-organization-validator" }, "runlist": "recipe[awesome_customers_rhel],recipe[yum],role[base]", "validation_key_format": "plaintext" }, "protectedSettings": { "validation_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIB..\n67VT3Dg=\n-----END RSA PRIVATE KEY-----" } } } ``` #### Installing the Azure Chef extension on a Windows system ``` { "type": "Microsoft.Compute/virtualMachines/extensions", "name": "myVirtualMachine/ChefClient", "apiVersion": "2015-05-01-preview", "location": "westus", "properties": { "publisher": "Chef.Bootstrap.WindowsAzure", "type": "ChefClient", "typeHandlerVersion": "1210.12", "settings": { "bootstrap_options": { "chef_node_name": "node12", "chef_server_url": "https://api.chef.io/organizations/my-chef-organization", "validation_client_name": "my-chef-organization-validator" }, "runlist": "recipe[awesome_customers_windows],recipe[iis],role[windows_base]", "chef_package_url" : "https://my.packages.chef.io/chef-client-15.11.8-1-x64.msi", "validation_key_format": "plaintext" }, "protectedSettings": { "validation_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIB..\n67VT3Dg=\n-----END RSA PRIVATE KEY-----" } } } ``` #### Installing the Azure Chef extension on a Linux system with SSL peer verification turned off and given a data bag secret ``` { "type": "Microsoft.Compute/virtualMachines/extensions", "name": "myVirtualMachine/LinuxChefClient", "apiVersion": "2015-05-01-preview", "location": "westus", "properties": { "publisher": "Chef.Bootstrap.WindowsAzure", "type": "LinuxChefClient", "typeHandlerVersion": "1210.12", "settings": { "bootstrap_options": { "chef_node_name": "node1", "chef_server_url": "https://api.chef.io/organizations/my-chef-organization", "validation_client_name": "my-chef-organization-validator", "node_ssl_verify_mode": "none", "secret": "<KEY>..." }, "runlist": "recipe[awesome_customers_rhel],recipe[yum],role[base]", "validation_key_format": "base64encoded" }, "protectedSettings": { "validation_key": "LS0tLS1CRUdJTiBSU0EgUFJ...FIEtFWS0tLS0t" } } } ``` Note Here we’re also base64 encoding our validator key which is a recommended approach when using the Azure Chef extension in an ARM template © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/azure_chef_cli/Chef Infra Client Security ========================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_client_security.md) The Chef Infra Server API handles all communication between Chef Infra Client or Chef Workstation. The Chef Infra Server API is an authenticated REST API, which means all requests require authentication and authorization. The Chef Infra tools such as `knife` and `chef-server` commands use the Chef Infra Server API for you. Authentication -------------- The authentication process ensures that Chef Infra Server only responds to requests made by trusted users or clients. Chef Infra Server uses public key encryption. You create the public and private keys when you configure [Chef Infra Client](../config_rb_client/index) or setup [Chef Workstation](../workstation/getting_started/index#setup-chef-credentials). * Chef Infra Server stores the public key * Chef Workstation saves the private key in `~/.chef/` * Chef Infra Client saves the private key in `/etc/chef` Both Chef Infra Client and Chef Workstation communicate with the Chef Infra Server using the Chef Infra Server API. Each time that Chef Infra Client or Chef Workstation makes a request to Chef Infra Server, they use a special group of HTTP headers and sign the rest with their private key. The Chef Infra Server then uses the public key to verify the headers and the contents. ### chef-validator Every request made by Chef Infra Client to the Chef Infra Server must be an authenticated request using the Chef Infra Server API and a private key. When Chef Infra Client makes a request to the Chef Infra Server, Chef Infra Client authenticates each request using a private key located in `/etc/chef/client.pem`. The private key does not yet exist the first time that Chef Infra Client runs from a new node. During the first Chef Infra Client run: 1. Chef Infra Client uses the chef-validator private key, located in `/etc/chef/validation.pem` to register with Chef Infra Server 2. Chef Infra Server assigns Chef Infra Client a private key for all future authentication requests to the Chef Infra Server 3. Chef Infra Client saves the private key on the node as `/etc/chef/client.pem` If the request to communicate with Chef Infra Server with the chef-validator key fails, then the entire first Chef Infra Client run fails. After the first completed Chef Infra Client run, delete the chef-validator private key at `/etc/chef/validation.pem` SSL Certificates ---------------- Warning The following information applies to on-premises Chef Infra Server and does not apply to Hosted Chef. Chef Infra Server 12 and later enables SSL verification by default for all requests made to the server, such as those made by knife and Chef Infra Client. The certificate that is generated during the installation of the Chef Infra Server is self-signed, which means the certificate is not signed by a trusted certificate authority (CA) recognized by Chef Infra Client. The certificate generated by the Chef Infra Server must be downloaded to any machine from which knife and/or Chef Infra Client will make requests to the Chef Infra Server. For example, without downloading the SSL certificate, the following knife command: ``` knife client list ``` responds with an error similar to: ``` ERROR: SSL Validation failure connecting to host: chef-server.example.com ... ERROR: OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 ... ``` This is by design and will occur until a verifiable certificate is added to the machine from which the request is sent. ### `/.chef/trusted_certs` The `/.chef/trusted_certs` directory stores trusted SSL certificates used to access the Chef Infra Server: * On each workstation, this directory is the location into which SScertificates are placed after they are downloaded from the CheInfra Server using the `knife ssl fetch` subcommand * On every node, this directory is the location into which SSLcertificates are placed when a node has been bootstrapped with ChefInfra Client from a workstation ### SSL_CERT_FILE Use the `SSL_CERT_FILE` environment variable to specify the location for the SSL certificate authority (CA) bundle for Chef Infra Client. A value for `SSL_CERT_FILE` is not set by default. Unless updated, the locations in which Chef Infra will look for SSL certificates are: * Chef Infra Client: `/opt/chef/embedded/ssl/certs/cacert.pem` * Chef Workstation: `/opt/chef-workstation/embedded/ssl/certs/cacert.pem` To use a custom CA bundle, update the environment variable to specify the path to the custom CA bundle. The first step to troubleshoot a failing SSL certificate is to verify the location of the `SSL_CERT_FILE`. ### client.rb Settings Use following client.rb settings to manage SSL certificate preferences: | Setting | Description | | --- | --- | | `local_key_generation` | Whether the Chef Infra Server or Chef Infra Client generates the private/public key pair. When `true`, Chef Infra Client generates the key pair, and then sends the public key to the Chef Infra Server. Default value: `true`. | | `ssl_ca_file` | The file for the OpenSSL key. Chef Infra Client generates this setting automatically. | | `ssl_ca_path` | The location of the OpenSSL key file. Chef Infra Client generates this setting automatically. | | `ssl_client_cert` | The OpenSSL X.509 certificate for mutual certificate validation. Required for mutual certificate validation on the Chef Infra Server. Default value: `nil`. | | `ssl_client_key` | The OpenSSL X.509 key used for mutual certificate validation. Required for mutual certificate validation on the Chef Infra Server. Default value: `nil`. | | `ssl_verify_mode` | Set the verification mode for HTTPS requests. The recommended setting is`:verify_peer`. Depending on your OpenSSL configuration, you may need to set the `ssl_ca_path`. Default value: `:verify_peer`.* Use `:verify_none` to run without validating any SSL certificates. * Use `:verify_peer` to validate all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS **remote_file** resource URLs used in a Chef Infra Client run. | | `verify_api_cert` | Verify the SSL certificate on the Chef Infra Server. Set to `true`, Chef Infra Client always verifies the SSL certificate. Set to `false`, Chef Infra Client uses `ssl_verify_mode` to determine if the SSL certificate requires verification. Default value: `false`. | ### Knife Subcommands The Chef Infra Client includes two knife commands for managing SSL certificates: * Use [knife ssl check](../workstation/knife_ssl_check/index) to troubleshoot SS certificate issues * Use [knife ssl fetch](../workstation/knife_ssl_fetch/index) to pull down a certificate from the Chef Infra Server to the `/.chef/trusted_certs` directory on the workstation. After the workstation has the correct SSL certificate, bootstrap operations from that workstation will use the certificate in the `/.chef/trusted_certs` directory during the bootstrap operation. #### knife ssl check Run the `knife ssl check` subcommand to verify the state of the SSL certificate, and then use the response to help troubleshoot issues that may be present. ##### Verified If the SSL certificate can be verified, the response to ``` knife ssl check ``` is similar to: ``` Connecting to host chef-server.example.com:443 Successfully verified certificates from 'chef-server.example.com' ``` ##### Unverified If the SSL certificate cannot be verified, the response to ``` knife ssl check ``` is similar to: ``` Connecting to host chef-server.example.com:443 ERROR: The SSL certificate of chef-server.example.com could not be verified Certificate issuer data: /C=US/ST=WA/L=S/O=Corp/OU=Ops/CN=chef-server.example.com/emailAddress=<EMAIL> Configuration Info: OpenSSL Configuration: * Version: OpenSSL 1.0.2u 20 Dec 2019 * Certificate file: /opt/chef-workstation/embedded/ssl/cert.pem * Certificate directory: /opt/chef-workstation/embedded/ssl/certs Chef SSL Configuration: * ssl_ca_path: nil * ssl_ca_file: nil * trusted_certs_dir: "/Users/grantmc/Downloads/chef-repo/.chef/trusted_certs" TO FIX THIS ERROR: If the server you are connecting to uses a self-signed certificate, you must configure chef to trust that certificate. By default, the certificate is stored in the following location on the host where your Chef Infra Server runs: /var/opt/opscode/nginx/ca/SERVER_HOSTNAME.crt Copy that file to your trusted_certs_dir (currently: /Users/grantmc/Downloads/chef-repo/.chef/trusted_certs) using SSH/SCP or some other secure method, then re-run this command to confirm that the certificate is now trusted. ``` #### knife ssl fetch Run the `knife ssl fetch` to download the self-signed certificate from the Chef Infra Server to the `/.chef/trusted_certs` directory on a workstation. ##### Verify Checksums The SSL certificate that is downloaded to the `/.chef/trusted_certs` directory should be verified to ensure that it is, in fact, the same certificate as the one located on the Chef Infra Server. This can be done by comparing the SHA-256 checksums. 1. View the checksum on the Chef Infra Server: ``` ssh <EMAIL> sudo sha256sum /var/opt/opscode/nginx/ca/chef-server.example.com.crt ``` The response is similar to: ``` <ABC123checksum> /var/opt/opscode/nginx/ca/chef-server.example.com.crt ``` 2. View the checksum on the workstation: ``` gsha256sum .chef/trusted_certs/chef-server.example.com.crt ``` The response is similar to: ``` <ABC123checksum> .chef/trusted_certs/chef-server.example.com.crt ``` 3. Verify that the checksum values are identical. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_client_security/Install Chef Infra Client on Windows Nodes ========================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/install_windows.md) Installation Methods -------------------- There are several methods available to install Chef Infra Client depending on the needs of your organization. Chef Infra Client can be installed on machines running Microsoft Windows in the following ways: * By bootstraping Chef Infra Client using [knife bootstrap](../workstation/knife_bootstrap/index) from a local workstation using WinRM * By downloading Chef Infra Client to the target node, and then running the Microsoft Installer Package (MSI) locally * By using an existing process already in place for managing Microsoft Windows machines, such as System Center ### Use knife CLI The `knife windows` subcommand is used to interact with Windows systems managed by Chef Infra. Nodes are configured using WinRM, which allows external applications to call native objects like batch scripts, Windows PowerShell scripts, or scripting library variables. The `knife windows` subcommand supports NTLM and Kerberos methods of authentication. #### Necessary Ports WinRM requires that a target node be accessible via the ports configured to support access via HTTP or HTTPS. ### Use MSI Installer A Microsoft Installer Package (MSI) is available for installing Chef Infra Client on a Microsoft Windows machine at [Chef Downloads](https://www.chef.io/downloads/tools/infra-client?os=windows). Msiexec.exe is used to install Chef Infra Client on a node as part of a bootstrap operation. The actual command that is run by the default bootstrap script is: ``` msiexec /qn /i "%LOCAL_DESTINATION_MSI_PATH%" ``` where `/qn` is used to set the user interface level to “No UI”, `/i` is used to define the location in which Chef Infra Client is installed, and `"%LOCAL_DESTINATION_MSI_PATH%"` is a variable defined in the default [windows-chef-client-msi.erb](https://github.com/chef/chef/blob/main/knife/lib/chef/knife/bootstrap/templates/windows-chef-client-msi.erb) bootstrap template. See <https://docs.microsoft.com/en-us/windows/win32/msi/command-line-options> for more information about the options available to Msiexec.exe. #### ADDLOCAL Options The `ADDLOCAL` parameter adds two setup options specific to Chef Infra Client. These options can be passed along with an Msiexec.exe command: | Option | Description | | --- | --- | | `ChefClientFeature` | Use to install Chef Infra Client. | | `ChefSchTaskFeature` | Use to configure Chef Infra Client as a scheduled task in Microsoft Windows. | | `ChefPSModuleFeature` | Used to install the chef PowerShell module. This will enable chef command line utilities within PowerShell. | First install Chef Infra Client, and then enable it to run as a scheduled task. For example: ``` msiexec /qn /i C:\inst\chef-client-15.3.14-1-x64.msi ADDLOCAL="ChefClientFeature,ChefSchTaskFeature,ChefPSModuleFeature" ``` #### Running as a Scheduled Task On Microsoft Windows, run Chef Infra Client periodically as a scheduled task. Scheduled tasks provides visibility, configurability, and reliability around log rotation and permissions. You can configure the Chef Infra Client to run as a scheduled task using the [chef_client_scheduled_task](../resources/chef_client_scheduled_task/index) resource. #### Scheduled Task Options To run Chef Infra Client at periodic intervals (so that it can check in with Chef Infra Server automatically), configure Chef Infra Client to run as a scheduled task. This can be done via the MSI, by selecting the **Chef Unattended Execution Options** –> **Chef Infra Client Scheduled Task** option on the **Custom Setup** page or by running the following command after Chef Infra Client is installed: For example: ``` SCHTASKS.EXE /CREATE /TN ChefClientSchTask /SC MINUTE /MO 30 /F /RU "System" /RP /RL HIGHEST /TR "cmd /c \"C:\opscode\chef\embedded\bin\ruby.exe C:\opscode\chef\bin\chef-client -L C:\chef\chef-client.log -c C:\chef\client.rb\"" ``` Refer to the [Schtasks documentation](https://docs.microsoft.com/en-us/windows/win32/taskschd/schtasks) for more details. After Chef Infra Client is configured to run as a scheduled task, the default file path is: `c:\chef\chef-client.log`. ### Use an Existing Process Many organizations already have processes in place for managing the applications and settings on various Microsoft Windows machines. For example, System Center. Chef Infra Client can be installed using this method. ### PATH System Variable On Microsoft Windows, Chef Infra Client must have two entries added to the `PATH` environment variable: * `C:\opscode\chef\bin` * `C:\opscode\chef\embedded\bin` This is typically done during the installation of Chef Infra Client automatically. If these values (for any reason) are not in the `PATH` environment variable, Chef Infra Client will not run properly. ![image] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/install_windows/Chef for Microsoft Windows ========================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/windows.md) Overview -------- The Chef Infra Client has specific components that are designed to support unique aspects of the Microsoft Windows platform, including PowerShell, PowerShell DSC, and Internet Information Services (IIS). Chef Infra Client can be installed on machines running Microsoft Windows in the following ways: * By bootstraping Chef Infra Client using [knife bootstrap](../workstation/knife_bootstrap/index) from a local workstation using WinRM * By downloading Chef Infra Client to the target node, and then running the Microsoft Installer Package (MSI) locally * By using an existing process already in place for managing Microsoft Windows machines, such as System Center Setting up Windows Workstations ------------------------------- To set up your Windows workstation follow the steps on [Chef for Microsoft Windows](../workstation/install_workstation/index) Install Chef Infra Client on Windows Nodes ------------------------------------------ Chef Infra Client is an agent that runs locally on every node that is under management by Chef Infra Server. When Chef Infra Client runs, it performs all of the steps required for bringing a node into the expected state, including: * Registering and authenticating the node with Chef Infra Server * Synchronizing cookbooks from the Chef Infra Server to the node * Compiling the resource collection by loading each of the required cookbooks, including recipes, attributes, and all other dependencies * Taking the appropriate and required actions to configure the node based on recipes and attributes * Reporting summary information on the run to Chef Automate This command has the following syntax: ``` chef-client OPTION VALUE OPTION VALUE ... ``` This command has the following option specific to Microsoft Windows: `-A`, `--fatal-windows-admin-check` Cause a Chef Infra Client run to fail when Chef Infra Client does not have administrator privileges in Microsoft Windows. ### System Requirements The recommended minimum amount of RAM available to Chef Infra Client during a Chef Infra Client run is 512MB. Each node and workstation must have access to Chef Infra Server via HTTPS. The Chef Infra Client can be used to manage machines that run on the following versions of Microsoft Windows: | Operating System | Architecture | Version | | --- | --- | --- | | Windows | `x86`, `x64` | `8.1`, `2012`, `2012 R2`, `2016`, `10 (all channels except "insider" builds)`, `2019 (Long-term servicing channel (LTSC), both Desktop Experience and Server Core)` | After Chef Infra Client is installed, it is located at `C:\opscode`. The main configuration file for Chef Infra Client is located at `C:\chef\client.rb`. ### Information for Windows Users #### Run With Elevated Privileges The Chef Infra Client may need to be run with elevated privileges in order to get a recipe to converge correctly. On UNIX and UNIX-like operating systems this can be done by running the command as root. On Microsoft Windows this can be done by running the command prompt as an administrator. On Microsoft Windows, running without elevated privileges (when they are necessary) is an issue that fails silently. It will appear that Chef Infra Client completed its run successfully, but the changes will not have been made. When this occurs, do one of the following to run Chef Infra Client as the administrator: * Log in to the administrator account. (This is not the same as an account in the administrator’s security group.) * Run Chef Infra Client process from the administrator account while being logged into another account. Run the following command: ``` runas /user:Administrator "cmd /C chef-client" ``` This will prompt for the administrator account password. * Open a command prompt by right-clicking on the command prompt application, and then selecting **Run as administrator**. After the command window opens, Chef Infra Client can be run as the administrator #### Spaces and Directories Directories that are used by Chef products on Windows cannot have spaces. For example, `C:\Users\User Name` will not work, but `C:\Users\UserName` will. Chef commands may fail if used against a directory with a space in its name. #### Top-level Directory Names Windows will throw errors when path name lengths are too long. For this reason, it’s often helpful to use a very short top-level directory, much like what is done in UNIX and Linux. For example, Chef uses `/opt/` to install Chef Workstation on macOS. A similar approach can be done on Microsoft Windows, by creating a top-level directory with a short name. For example: `C:\chef`. #### PATH System Variable On Microsoft Windows, Chef Infra Client must have two entries added to the `PATH` environment variable: * `C:\opscode\chef\bin` * `C:\opscode\chef\embedded\bin` This is typically done during the installation of Chef Infra Client automatically. If these values (for any reason) are not in the `PATH` environment variable, Chef Infra Client will not run properly. ![image] #### Proxy Settings To determine the current proxy server on the Microsoft Windows platform: 1. Open **Internet Properties**. 2. Open **Connections**. 3. Open **LAN settings**. 4. View the **Proxy server** setting. If this setting is blank, then a proxy server may not be available. To configure proxy settings in Microsoft Windows: 1. Open **System Properties**. 2. Open **Environment Variables**. 3. Open **System variables**. 4. Set `http_proxy` and `https_proxy` to the location of your proxy server. This value **MUST** be lowercase. ### Remotely administering nodes The `knife windows` subcommand is used to interact with Windows systems managed by Chef Infra. Nodes are configured using WinRM, which allows external applications to call native objects like batch scripts, Windows PowerShell scripts, or scripting library variables. The `knife windows` subcommand supports NTLM and Kerberos methods of authentication. Se the [knife windows](../workstation/knife_windows/index) for more information. #### Ports WinRM requires that a target node be accessible via the ports configured to support access via HTTP or HTTPS. ### Install Chef Infra Client using the MSI Installer A Microsoft Installer Package (MSI) is available for installing Chef Infra Client on a Microsoft Windows machine from [Chef Downloads](https://www.chef.io/downloads/tools/infra-client?os=windows). #### Msiexec.exe Msiexec.exe is used to install Chef Infra Client on a node as part of a bootstrap operation. The actual command that is run by the default bootstrap script is: ``` msiexec /qn /i "%LOCAL_DESTINATION_MSI_PATH%" ``` where `/qn` is used to set the user interface level to “No UI”, `/i` is used to define the location in which Chef Infra Client is installed, and `"%LOCAL_DESTINATION_MSI_PATH%"` is a variable defined in the default [windows-chef-client-msi.erb](https://github.com/chef/chef/blob/main/knife/lib/chef/knife/bootstrap/templates/windows-chef-client-msi.erb) bootstrap template. See <https://docs.microsoft.com/en-us/windows/win32/msi/command-line-options> for more information about the options available to Msiexec.exe. #### ADDLOCAL Options The `ADDLOCAL` parameter adds two setup options specific to Chef Infra Client. These options can be passed along with an Msiexec.exe command: | Option | Description | | --- | --- | | `ChefClientFeature` | Use to install Chef Infra Client. | | `ChefSchTaskFeature` | Use to configure Chef Infra Client as a scheduled task in Microsoft Windows. | | `ChefPSModuleFeature` | Used to install the chef PowerShell module. This will enable chef command line utilities within PowerShell. | First install Chef Infra Client, and then enable it to run as a scheduled task. For example: ``` msiexec /qn /i C:\inst\chef-client-15.3.14-1-x64.msi ADDLOCAL="ChefClientFeature,ChefSchTaskFeature,ChefPSModuleFeature" ``` #### Enable as a Scheduled Task To run Chef Infra Client at periodic intervals (so that it can check in with Chef Infra Server automatically), configure Chef Infra Client to run as a scheduled task. This can be done via the MSI, by selecting the **Chef Unattended Execution Options** –> **Chef Infra Client Scheduled Task** option on the **Custom Setup** page or by running the following command after Chef Infra Client is installed: For example: ``` SCHTASKS.EXE /CREATE /TN ChefClientSchTask /SC MINUTE /MO 30 /F /RU "System" /RP /RL HIGHEST /TR "cmd /c \"C:\opscode\chef\embedded\bin\ruby.exe C:\opscode\chef\bin\chef-client -L C:\chef\chef-client.log -c C:\chef\client.rb\"" ``` Refer to the [Schtasks documentation](https://docs.microsoft.com/en-us/windows/win32/taskschd/schtasks) for more details. After Chef Infra Client is configured to run as a scheduled task, the default file path is: `c:\chef\chef-client.log`. ### Install Chef Infra Client using an Existing Process Many organizations already have processes in place for managing the applications and settings on various Microsoft Windows machines. For example, System Center. Chef Infra Client can be installed using this method. Windows Cookbooks ----------------- Some of the most popular Chef-maintained cookbooks that contain custom resources useful when configuring machines running Microsoft Windows are listed below: | Cookbook | Description | | --- | --- | | [iis Cookbook](https://github.com/chef-cookbooks/iis) | The `iis` cookbook is used to install and configure Internet Information Services (IIS). | | [iis_urlrewrite Cookbook](https://github.com/chef-cookbooks/iis_urlrewrite) | This cookbook downloads and installs the IIS URL Rewrite 2.0 extension into Microsoft Internet Information Server. | | [PowerShell Cookbook](https://github.com/chef-cookbooks/powershell) | Installs and configures PowerShell 2.0, 3.0, 4.0 or 5.0. | | [Microsoft Visual C++ Runtime Cookbook](https://github.com/chef-cookbooks/vcruntime) | Installs Microsoft Visual C++ runtime version 6 (2005), 9 (2008), 10 (2010), 11 (2012), 12 (2013), 14 (2015) or 15 (2017) on Windows. | | [Mingw Cookbook](https://github.com/chef-cookbooks/mingw) | Installs `msys/mingw` compiler toolchains on windows. | | [Webpi Cookbook](https://github.com/chef-cookbooks/webpi) | The `webpi` cookbook is used to run the Microsoft Web Platform Installer (WebPI). | ### Community Supported Windows Projects Two community supports two provisioners for Kitchen: * [kitchen-dsc](https://github.com/test-kitchen/kitchen-dsc) * [kitchen-pester](https://github.com/test-kitchen/kitchen-pester) Windows Resources ----------------- A resource is a statement of configuration policy that: * Describes the desired state for a configuration item * Declares the steps needed to bring that item to the desired state * Specifies a resource type—such as `package`, `template`, or `service` * Lists additional details (also known as resource properties), as necessary * Are grouped into recipes, which describe working configurations ### Windows Resources Chef Infra provides a growing number of Windows-specific resources. * [cab_package](../resources/cab_package/index) * [chef_client_scheduled_task](../resources/chef_client_scheduled_task/index) * [chocolatey_config](../resources/chocolatey_config/index) * [chocolatey_feature](../resources/chocolatey_feature/index) * [chocolatey_package](../resources/chocolatey_package/index) * [chocolatey_source](../resources/chocolatey_package/index) * [dsc_resource](../resources/dsc_resource/index) * [dsc_script](../resources/dsc_script/index) * [msu_package](../resources/msu_package/index) * [powershell_package_source](../resources/powershell_package_source/index) * [powershell_package](../resources/powershell_package/index) * [powershell_script](../resources/powershell_script/index) * [registry_key](../resources/registry_key/index) * [windows_ad_join](../resources/windows_ad_join/index) * [windows_audit_policy](../resources/windows_audit_policy/index) * [windows_auto_run](../resources/windows_auto_run/index) * [windows_certificate](../resources/windows_certificate/index) * [windows_defender_exclusion](../resources/windows_defender_exclusion/index) * [windows_defender](../resources/windows_defender/index) * [windows_dfs_folder](../resources/windows_dfs_folder/index) * [windows_dfs_namespace](../resources/windows_dfs_namespace/index) * [windows_dfs_server](../resources/windows_dfs_server/index) * [windows_dns_record](../resources/windows_dns_record/index) * [windows_dns_zone](../resources/windows_dns_zone/index) * [windows_env](../resources/windows_env/index) * [windows_feature_dism](../resources/windows_feature_dism/index) * [windows_feature_powershell](../resources/windows_feature_powershell/index) * [windows_feature](../resources/windows_feature/index) * [windows_firewall_profile](../resources/windows_firewall_profile/index) * [windows_firewall_rule](../resources/windows_firewall_rule/index) * [windows_font](../resources/windows_font/index) * [windows_package](../resources/windows_package/index) * [windows_pagefile](../resources/windows_pagefile/index) * [windows_path](../resources/windows_path/index) * [windows_printer_port](../resources/windows_printer_port/index) * [windows_printer](../resources/windows_printer/index) * [windows_security_policy](../resources/windows_security_policy/index) * [windows_service](../resources/windows_service/index) * [windows_share](../resources/windows_share/index) * [windows_shortcut](../resources/windows_shortcut/index) * [windows_task](../resources/windows_task/index) * [windows_uac](../resources/windows_uac/index) * [windows_user_privilege](../resources/windows_user_privilege/index) * [windows_workgroup](../resources/windows_workgroup/index) ### Windows Compatible Resources The most popular core resources in Chef Infra Client work the same way in Microsoft Windows as they do on any UNIX or Linux-based platform. * [cookbook_file](../resources/cookbook_file/index) * [directory](../resources/directory/index) * [execute](../resources/execute/index) * [file](../resources/file/index) * [group](../resources/group/index) * [http_request](../resources/http_request/index) * [link](../resources/link/index) * [mount](../resources/mount/index) * [package](../resources/package/index) * [remote_directory](../resources/remote_directory/index) * [remote_file](../resources/remote_file/index) * [ruby_block](../resources/ruby_block/index) * [service](../resources/service/index) * [template](../resources/template/index) * [user](../resources/user/index) The file-based resources have attributes that support unique requirements within the Microsoft Windows platform, including `inherits` (for file inheritance), `mode` (for octal modes), and `rights` (for access control lists, or ACLs). * [cookbook_file](../resources/cookbook_file/index) * [file](../resources/file/index) * [remote_file](../resources/remote_file/index) * [template](../resources/template/index) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/windows/FIPS (Federal Information Processing Standards) =============================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/fips.md) What is FIPS? ------------- Federal Information Processing Standards (FIPS) are federal standards for computer systems used by contractors of government agencies and non-military government agencies. FIPS 140-2 is a specific federal government security standard used to approve cryptographic modules. Chef Automate uses the OpenSSL FIPS Object Module, which satisfies the requirements of software cryptographic modules under the FIPS 140-2 standard. The OpenSSL Object Module provides an API for invoking FIPS approved cryptographic functions from calling applications. ### Who should enable FIPS? You may be legally required to enable FIPS if you are a United States non-military government agency, or are contracting with one. If you are not sure if you need to enable FIPS, please check with your compliance department. ### Who shouldn’t enable FIPS? You will only need to enable FIPS if you are a US non-military government agency, or contracting with one, and you are contractually obligated to meet federal government security standards. If you are not a US non-military governmental agency, or you are not contracting with one, and you are not contractually obligated to meet federal government security standards, then do not enable FIPS. Chef products have robust security standards even without FIPS, and FIPS prevents the use of certain hashing algorithms you might want to use, so we only recommend enabling FIPS if it is contractually necessary. Supported Products ------------------ **Supported:** * [Chef Infra Client](index#how-to-enable-fips-mode-for-the-chef-client) * [Chef Workstation](index#how-to-enable-fips-mode-for-workstations) * [Chef Infra Server](index#how-to-enable-fips-mode-for-the-chef-server) **Unsupported:** FIPS mode is not supported for Chef Infra Server add-ons. This includes Chef Manage. How to enable FIPS mode in the Operating System ----------------------------------------------- ### FIPS kernel settings Windows and Red Hat Enterprise Linux can both be configured for FIPS mode using a kernel-level setting. After FIPS mode is enabled at the kernel level, the operating system will only use FIPS approved algorithms and keys during operation. All of the tools Chef produces that have FIPS support read this kernel setting and default their mode of operation to match it with the exception of the workstation, which requires designating a port in the `fips_git_port` setting of the `cli.toml`. For the other Chef Infra tools, Chef Infra Client, for example, if `chef-client` is run on an operating system configured into FIPS mode and you run, that Chef Infra run will automatically be in FIPS mode unless the user disables it. To enable FIPS on your platform follow these instructions: * [Red Hat Enterprise Linux 6](https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Security_Guide/sect-Security_Guide-Federal_Standards_And_Regulations-Federal_Information_Processing_Standard.html) * [Red Hat Enterprise Linux 7](https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Security_Guide/chap-Federal_Standards_and_Regulations.html#sec-Enabling-FIPS-Mode) * [Red Hat Enterprise Linux 8](https://www.redhat.com/en/blog/how-rhel-8-designed-fips-140-2-requirements) * [Windows](https://technet.microsoft.com/en-us/library/cc750357.aspx) * [Ubuntu](https://security-certs.docs.ubuntu.com/en/fips) How to enable FIPS mode for the Chef Infra Server ------------------------------------------------- ### Prerequisites * Supported Systems - CentOS or Red Hat Enterprise Linux 6 or greater * Chef Infra Server version 12.13 or greater ### Configuration If you have FIPS compliance enabled at the kernel level and install or reconfigure the Chef Infra Server then it will default to running in FIPS mode. To enable FIPS manually for the Chef Infra Server, can add `fips true` to the `/etc/opscode/chef-server.rb` and reconfigure. For more configuration information see [chef-server.rb Optional Settings](../server/config_rb_server_optional_settings/index). How to enable FIPS mode for the Chef Infra Client ------------------------------------------------- ### Prerequisites * Supported Systems - CentOS, Oracle Linux, Red Hat Enterprise Linux 6 or later, and Ubuntu * Chef Infra Client 16.13 or later for Ubuntu systems ### Configuration If you have FIPS compliance enabled at the kernel level, Chef Infra Client will default to running in FIPS mode. Otherwise, add `fips true` to the `/etc/chef/client.rb` or `C:\\chef\\client.rb`. #### Bootstrap a node using FIPS ``` knife bootstrap 192.0.2.0 -P vanilla -x root -r 'recipe[apt],recipe[xfs],recipe[vim]' --fips ``` which shows something similar to: ``` OpenSSL FIPS 140 mode enabled ... 192.0.2.0 Chef Infra Client finished, 12/12 resources updated in 78.942455583 seconds ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/fips/About the Handler DSL ===================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/dsl_handler.md) Use the Handler DSL to attach a callback to an event. If the event occurs during a Chef Infra Client run, the associated callback is executed. For example: * Sending email if a Chef Infra Client run fails * Aggregating statistics about resources updated during a Chef Infra Client runs to StatsD on Method --------- Use the `on` method to associate an event type with a callback. The callback defines what steps are taken if the event occurs during a Chef Infra Client run and is defined using arbitrary Ruby code. The syntax is as follows: ``` Chef.event_handler do on :event_type do # some Ruby end end ``` where * `Chef.event_handler` declares a block of code within a recipe that is processed when the named event occurs during a Chef Infra Client run * `on` defines the block of code that will tell Chef Infra Client how to handle the event * `:event_type` is a valid exception event type, such as `:run_start`, `:run_failed`, `:converge_failed`, `:resource_failed`, or `:recipe_not_found` For example: ``` Chef.event_handler do on :converge_start do puts "Ohai! I have started a converge." end end ``` Event Types ----------- The following table describes the events that may occur during a Chef Infra Client run. Each of these events may be referenced in an `on` method block by declaring it as the event type. | Event | Description | | --- | --- | | `:run_start` | The start of a Chef Infra Client run. | | `:run_started` | The Chef Infra Client run has started. | | `:run_completed` | The Chef Infra Client run has completed. | | `:run_failed` | The Chef Infra Client run has failed. | | `:ohai_completed` | The Ohai run has completed. | | `:skipping_registration` | The Chef Infra Client is not registering with the Chef Infra Server because it already has a private key or because it does not need one. | | `:registration_start` | The Chef Infra Client is attempting to create a private key with which to register to the Chef Infra Server. | | `:registration_completed` | The Chef Infra Client created its private key successfully. | | `:registration_failed` | The Chef Infra Client encountered an error and was unable to register with the Chef Infra Server. | | `:node_load_start` | The Chef Infra Client is attempting to load node data from the Chef Infra Server. | | `:node_load_success` | The Chef Infra Client successfully loaded node data from the policy builder. | | `:node_load_failed` | The Chef Infra Client encountered an error and was unable to load node data from the Chef Infra Server. | | `:run_list_expand_failed` | The Chef Infra Client failed to expand the run-list. | | `:node_load_completed` | The Chef Infra Client successfully loaded node data from the Chef Infra Server. Default and override attributes for roles have been computed, but are not yet applied. | | `:policyfile_loaded` | The policy file was loaded. | | `:cookbook_resolution_start` | The Chef Infra Client is attempting to pull down the cookbook collection from the Chef Infra Server. | | `:cookbook_resolution_failed` | The Chef Infra Client failed to pull down the cookbook collection from the Chef Infra Server. | | `:cookbook_resolution_complete` | The Chef Infra Client successfully pulled down the cookbook collection from the Chef Infra Server. | | `:cookbook_clean_start` | The Chef Infra Client is attempting to remove unneeded cookbooks. | | `:removed_cookbook_file` | The Chef Infra Client removed a file from a cookbook. | | `:cookbook_clean_complete` | The Chef Infra Client is done removing cookbooks and/or cookbook files. | | `:cookbook_sync_start` | The Chef Infra Client is attempting to synchronize cookbooks. | | `:synchronized_cookbook` | The Chef Infra Client is attempting to synchronize the named cookbook. | | `:updated_cookbook_file` | The Chef Infra Client updated the named file in the named cookbook. | | `:cookbook_sync_failed` | The Chef Infra Client was unable to synchronize cookbooks. | | `:cookbook_sync_complete` | The Chef Infra Client is finished synchronizing cookbooks. | | `:cookbook_gem_start` | The Chef Infra Client is collecting gems from the cookbooks. | | `:cookbook_gem_installing` | The Chef Infra Client is installing a cookbook gem. | | `:cookbook_gem_using` | The Chef Infra Client is using a cookbook gem. | | `:cookbook_gem_finished` | The Chef Infra Client finished installing cookbook gems. | | `:cookbook_gem_failed` | The Chef Infra Client failed to install cookbook gems. | | `:cookbook_compilation_start` | The Chef Infra Client created the run_context and is starting cookbook compilation. | | `:library_load_start` | The Chef Infra Client is loading library files. | | `:library_file_loaded` | The Chef Infra Client successfully loaded the named library file. | | `:library_file_load_failed` | The Chef Infra Client was unable to load the named library file. | | `:library_load_complete` | The Chef Infra Client is finished loading library files. | | `:lwrp_load_start` | The Chef Infra Client is loading custom resources. | | `:lwrp_file_loaded` | The Chef Infra Client successfully loaded the named custom resource. | | `:lwrp_file_load_failed` | The Chef Infra Client was unable to load the named custom resource. | | `:lwrp_load_complete` | The Chef Infra Client is finished loading custom resources. | | `:ohai_plugin_load_start` | Ohai has started loading plugins. | | `:ohai_plugin_file_loaded` | Ohai has loaded a plugin. | | `:ohai_plugin_file_load_failed` | Ohai failed to load a plugin. | | `:ohai_plugin_load_complete` | Ohai has completed loading plugins. | | `:attribute_load_start` | The Chef Infra Client is loading attribute files. | | `:attribute_file_loaded` | The Chef Infra Client successfully loaded the named attribute file. | | `:attribute_file_load_failed` | The Chef Infra Client was unable to load the named attribute file. | | `:attribute_load_complete` | The Chef Infra Client is finished loading attribute files. | | `:definition_load_start` | The Chef Infra Client is loading definitions. | | `:definition_file_loaded` | The Chef Infra Client successfully loaded the named definition. | | `:definition_file_load_failed` | The Chef Infra Client was unable to load the named definition. | | `:definition_load_complete` | The Chef Infra Client is finished loading definitions. | | `:recipe_load_start` | The Chef Infra Client is loading recipes. | | `:recipe_file_loaded` | The Chef Infra Client successfully loaded the named recipe. | | `:recipe_file_load_failed` | The Chef Infra Client was unable to load the named recipe. | | `:recipe_not_found` | The Chef Infra Client was unable to find the named recipe. | | `:recipe_load_complete` | The Chef Infra Client is finished loading recipes. | | `:cookbook_compilation_complete` | The Chef Infra Client completed all cookbook compilation phases. | | `:converge_start` | The Chef Infra Client run converge phase has started. | | `:action_collection_registration` | Provides a reference to the action_collection before cookbooks are compiled. | | `:converge_complete` | The Chef Infra Client run converge phase is complete. | | `:converge_failed` | The Chef Infra Client run converge phase has failed. | | `:control_group_started` | The named control group is being processed. | | `:control_example_success` | The named control group has been processed. | | `:control_example_failure` | The named control group's processing has failed. | | `:resource_action_start` | A resource action is starting. | | `:resource_skipped` | A resource action was skipped. | | `:resource_current_state_loaded` | A resource's current state was loaded. | | `:resource_after_state_loaded` | A resource's after state was loaded. | | `:resource_current_state_load_bypassed` | A resource's current state was not loaded because the resource does not support why-run mode. | | `:resource_bypassed` | A resource action was skipped because the resource does not support why-run mode. | | `:resource_update_applied` | A change has been made to a resource. (This event occurs for each change made to a resource.) | | `:resource_update_progress` | A resource sent a progress notification to the user to indicate overall progress of a long running operation. | | `:resource_failed_retriable` | A resource action has failed and will be retried. | | `:resource_failed` | A resource action has failed and will not be retried. | | `:resource_updated` | A resource requires modification. | | `:resource_up_to_date` | A resource is already correct. | | `:resource_completed` | All actions for the resource are complete. | | `:stream_opened` | A stream has opened. | | `:stream_closed` | A stream has closed. | | `:stream_output` | A chunk of data from a single named stream. | | `:handlers_start` | The handler processing phase of a Chef Infra Client run has started. | | `:handler_executed` | The named handler was processed. | | `:handlers_completed` | The handler processing phase of a Chef Infra Client run is complete. | | `:provider_requirement_failed` | An assertion declared by a provider has failed. | | `:whyrun_assumption` | An assertion declared by a provider has failed, but execution is allowed to continue because the Chef Infra Client is running in why-run mode. | `:deprecation` | A deprecation message has been emitted. || `:attribute_changed` | Prints out all the attribute changes in cookbooks or sets a policy that override attributes should never be used. | Examples -------- The following examples show ways to use the Handler DSL. ### Send Email Use the `on` method to create an event handler that sends email when a Chef Infra Client run fails. This will require: * A way to tell Chef Infra Client how to send email * An event handler that describes what to do when the `:run_failed` event is triggered * A way to trigger the exception and test the behavior of the event handler #### Define How Email is Sent Use a library to define the code that sends email when a Chef Infra Client run fails. Name the file `helper.rb` and add it to a cookbook’s `/libraries` directory: ``` require 'net/smtp' module HandlerSendEmail class Helper def send_email_on_run_failure(node_name) message = "From: Chef <<EMAIL>>\n" message << "To: Grant <<EMAIL>>\n" message << "Subject: Chef run failed\n" message << "Date: #{Time.now.rfc2822}\n\n" message << "Chef run failed on #{node_name}\n" Net::SMTP.start('localhost', 25) do |smtp| smtp.send_message message, '<EMAIL>', '<EMAIL>' end end end end ``` #### Add the Handler Invoke the library helper in a recipe: ``` Chef.event_handler do on :run_failed do HandlerSendEmail::Helper.new.send_email_on_run_failure( Chef.run_context.node.name ) end end ``` * Use `Chef.event_handler` to define the event handler * Use the `on` method to specify the event type Within the `on` block, tell Chef Infra Client how to handle the event when it’s triggered. #### Test the Handler Use the following code block to trigger the exception and have the Chef Infra Client send email to the specified email address: ``` ruby_block 'fail the run' do block do raise 'deliberately fail the run' end end ``` ### etcd Locks The following example shows how to prevent concurrent Chef Infra Client runs from both holding a lock on etcd: ``` lock_key = "#{node.chef_environment}/#{node.name}" Chef.event_handler do on :converge_start do |run_context| Etcd.lock_acquire(lock_key) end end Chef.event_handler do on :converge_complete do Etcd.lock_release(lock_key) end end ``` ### HipChat Notifications Event messages can be sent to a team communication tool like HipChat. For example, if a Chef Infra Client run fails: ``` Chef.event_handler do on :run_failed do |exception| hipchat_notify exception.message end end ``` or send an alert on a configuration change: ``` Chef.event_handler do on :resource_updated do |resource, action| if resource.to_s == 'template[/etc/nginx/nginx.conf]' Helper.hipchat_message("#{resource} was updated by chef") end end end ``` ### `attribute_changed` event hook In a cookbook library file, you can add this in order to print out all attribute changes in cookbooks: ``` Chef.event_handler do on :attribute_changed do |precedence, key, value| puts "setting attribute #{precedence}#{key.map { |n| "[\"#{n}\"]" }.join} = #{value}" end end ``` If you want to setup a policy that override attributes should never be used: ``` Chef.event_handler do on :attribute_changed do |precedence, key, value| raise 'override policy violation' if precedence == :override end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/dsl_handler/metadata.rb =========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/config_rb_metadata.md) Every cookbook requires a small amount of metadata. The contents of the `metadata.rb` file provides information that helps Chef Infra Client and Server correctly deploy cookbooks to each node. A `metadata.rb` file is: * Located at the top level of a cookbook’s directory structure. * Compiled whenever a cookbook is uploaded to the Chef Infra Server or when the `knife cookbook metadata` subcommand is run, and then stored as JSON data. * Created automatically by knife whenever the `knife cookbook create` subcommand is run. * Edited using a text editor, and then re-uploaded to the Chef Infra Server as part of a cookbook upload. * Located at the top level of a cookbook’s directory structure. * Compiled whenever a cookbook is uploaded to the Chef Infra Server or when the `knife cookbook metadata` subcommand is run, and then stored as JSON data. * Created automatically by knife whenever the `knife cookbook create` subcommand is run. * Edited using a text editor, and then re-uploaded to the Chef Infra Server as part of a cookbook upload. Error Messages -------------- The Chef Infra Server will only try to distribute the cookbooks that are needed to configure an individual node. This is determined by identifying the roles and recipes that are assigned directly to that system, and then to expand the list of dependencies, and then to deliver that entire set to the node. In some cases, if the dependency is not specified in the cookbook’s metadata, the Chef Infra Server may not treat that dependency as a requirement, which will result in an error message. If an error message is received from the Chef Infra Server about cookbook distribution, verify the `depends` entries in the `metadata.rb` file, and then try again. Note A metadata.json file can be edited directly, should temporary changes be required. Any subsequent upload or action that generates metadata will cause the existing metadata.json file to be overwritten with the newly generated metadata. Therefore, any permanent changes to cookbook metadata should be done in the `metadata.rb` file, and then re-uploaded to the Chef Infra Server. Version Constraints ------------------- Many fields in a cookbook’s metadata allow the user to constrain versions. There are a set of operators common to all fields: | Specification | Operator | | --- | --- | | Pessimistic (see note below) | `~>` | | Equal to | `=` | | Greater than or equal to | `>=` | | Greater than | `>` | | Less than | `<` | | Less than or equal to | `<=` | Note Pessimistic locking is enabled by proper [semantic versioning](https://semver.org) of cookbooks. If we’re on version 2.2.3 of a cookbook, we know that the API will be stable until the 3.0.0 release. Using traditional operators, we’d write this as `>= 2.2.0, < 3.0`. Instead, we can write this by combining a tilde “~” and right angle bracket “>"–often called a tilde-rocket or “twiddle-wakka”–followed by the major and minor version numbers. For example: `~> 2.2` Settings -------- This configuration file has the following settings: `chef_version` A range of Chef Client versions that are supported by this cookbook. All [version constraint operators](#version-constraints) are applicable to this field. For example, to match any 16.x version of the Chef Client, but not 15.x or 17.x: ``` chef_version '~> 16.0' ``` A more complex example where you set both a lower and upper bound of the Chef Infra Client version: ``` chef_version '>= 17.2', '< 17.4' ``` `depends` This field requires that a cookbook with a matching name and version exists on the Chef Infra Server. When the match exists, the Chef Infra Server includes the dependency as part of the set of cookbooks that are sent to the node during a Chef Infra Client run. It is very important that the `depends` field contain accurate data. If a dependency statement is inaccurate, Chef Infra Client may not be able to complete the configuration of the system. All [version constraint operators](#version-constraints) are applicable to this field. For example, to set a dependency a cookbook named `cats`: ``` depends 'cats' ``` or, to set a dependency on the same cookbook, but only when the version is less than 1.0: ``` depends 'cats', '< 1.0' ``` `description` A short description of a cookbook and its functionality. For example: ``` description 'A fancy cookbook that manages a herd of cats!' ``` `gem` Specifies a gem dependency for installation in Chef Infra Client through bundler. The gem installation occurs after all cookbooks are synchronized but before loading any other cookbooks. Use this attribute one time for each gem dependency. For example: ``` gem 'loofah' gem 'chef-sugar' ``` Warning Use the `gem` setting only for making external chef libraries shipped as gems accessible in a Chef Infra Client run for libraries and attribute files. The `gem` setting in `metadata.rb` allows for the early installation of this specific type of gem, with the fundamental limitation that it cannot install native gems. Do not install native gems with the `gem` setting in `metadata.rb` . The `gem` setting is not a general purpose replacement for the [chef_gem resource](../resources/chef_gem/index), and does not internally re-use the `chef_gem` resource. Native gems require C compilation and must not be installed with `metadata.rb` because `metadata.rb` runs before any recipe code runs. Consequently, Chef Infra Client cannot install the C compilers before the gem installation occurs. Instead, install native gems with the `chef_gem` resource called from the recipe code. You’ll also need to use the `build_essential` resource in the recipe code to install the prerequisite compilers onto the system. Pure ruby gems can also be installed with `metadata.rb`. `issues_url` The URL for the location in which a cookbook’s issue tracking is maintained. This setting is also used by Chef Supermarket. In Chef Supermarket, this value is used to define the destination for the “View Issues” link. For example: ``` issues_url 'https://github.com/chef-cookbooks/chef-client/issues' ``` `license` The type of license under which a cookbook is distributed: `Apache v2.0`, `GPL v2`, `GPL v3`, `MIT`, or `license 'Proprietary - All Rights Reserved` (default). Please be aware of the licenses for files inside of a cookbook and be sure to follow any restrictions they describe. For example: ``` license 'Apache-2.0' ``` or: ``` license 'GPL-3.0' ``` or: ``` license 'MIT' ``` or: ``` license 'Proprietary - All Rights Reserved' ``` `maintainer` The name of the person responsible for maintaining a cookbook, either an individual or an organization. For example: ``` maintainer '<NAME>' ``` `maintainer_email` The email address for the person responsible for maintaining a cookbook. Only one email can be listed here, so if this needs to be forwarded to multiple people consider using an email address that is already setup for mail forwarding. For example: ``` maintainer_email '<EMAIL>' ``` `name` Required. The name of the cookbook. For example: ``` name 'cats' ``` `ohai_version` A range of Ohai versions that are supported by this cookbook. All [version constraint operators](#version-constraints) are applicable to this field. For example, to match any 8.x version of Ohai, but not 7.x or 9.x: ``` ohai_version '~> 8' ``` Note This setting is not visible in Chef Supermarket. `privacy` Specify a cookbook as private. For example: ``` privacy true ``` `source_url` The URL for the location in which a cookbook’s source code is maintained. This setting is also used by Chef Supermarket. In Chef Supermarket, this value is used to define the destination for the “View Source” link. For example: ``` source_url 'https://github.com/chef-cookbooks/chef-client' ``` `supports` Show that a cookbook has a supported platform. Use a version constraint to define dependencies for platform versions: `<` (less than), `<=` (less than or equal to), `=` (equal to), `>=` (greater than or equal to), `~>` (approximately greater than), or `>` (greater than). To specify more than one platform, use more than one `supports` field, once for each platform. For example, to support every version of Ubuntu: ``` supports 'ubuntu' ``` or, to support versions of Ubuntu greater than or equal to 20.04: ``` supports 'ubuntu', '>= 20.04' ``` or, to support only Ubuntu 20.04: ``` supports 'ubuntu', '= 20.04' ``` Here is a list of all of the supported specific operating systems: ``` %w( aix amazon centos fedora freebsd debian oracle mac_os_x redhat suse opensuseleap ubuntu windowszlinux ).each do |os| supports os end ``` `version` The current version of a cookbook. Version numbers always follow a simple three-number version sequence. For example: ``` version '2.0.0' ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/config_rb_metadata/Get Started =========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/cookbook_repo.md) The `cookbooks/` directory of your Chef Infra repository is used to store the cookbooks that Chef Infra Client uses in configuring the various systems in the organization. Chef Repository --------------- The the `\cookbook` directory is automatically generated as part of your Chef Infra repository. ``` chef generate repo REPO_NAME ``` ### Cookbook Directory Structure The default structure of the cookbooks directory is: ``` . chef-repo ├ cookbooks ├ example | ├ attributes | | └ default.rb | ├ recipes | | └ default.rb ├ metadata.rb └ README.rb ``` Cookbook Commands ----------------- Use the following commands to create a cookbook, install a cookbook from Supermarket, and/or download cookbooks. ### Create Chef Workstation generates the `cookbooks` directory as part of your Chef Infra repository, the `chef-repo`. Generate a `chef-repo/cookbooks` directory with the command: ``` chef generate template PATH_TO_COOKBOOKS COOKBOOK_NAME ``` For example, this command generates a `custom_web` cookbook: ``` chef generate cookbook cookbooks/custom_web ``` The `custom_web` cookbook directory has the structure: ``` ├ cookbooks ├ custom_web | ├ .delivery | | └ project.toml | ├ recipes | | └ default.rb | ├ test | | └ integration | | | └ default | | | | └ default_test.rb | ├ .gitignore | ├ CHANGELOG.md | ├ chefignore | ├ kitchen.yml | ├ LICENSE | ├ metadata.rb | ├ Policyfile.rb | └ README.md ``` Any unneeded directory components can be left unused or deleted, if preferred. ### Install To download a cookbook when git is used for version source control, run the following command: ``` knife supermarket install COOKBOOK_NAME ``` where `COOKBOOK_NAME` is the name of a cookbook on [Chef Supermarket](https://supermarket.chef.io/). This will start a process that: * downloads the cookbook from [Chef Supermarket](https://supermarket.chef.io/) as a tar.gz archive * ensures that its using the git master branch, and then checks out the cookbook from a vendor branch (creating a new vendor branch, if required) * removes the old (existing) version * expands the tar.gz archive and adds the expanded files to the git index and commits * creates a tag for the version that was downloaded * checks out the master branch * merges the cookbook into the master (to ensure that any local changes or modifications are preserved) ### Download To download a cookbook when git is not used for version source control, run the following command: ``` knife supermarket download COOKBOOK_NAME ``` where `COOKBOOK_NAME` is the name of a cookbook on [Chef Supermarket](https://supermarket.chef.io/). This will download the tar.gz file associated with the cookbook and will create a file named `COOKBOOK_NAME.tar.gz` in the current directory (`~/chef-repo`). Once downloaded, using a version source control system is recommended. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/cookbook_repo/Chef Infra Client (executable) ============================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/ctl_chef_client.md) Chef Infra Client is an agent that runs locally on every node that is under management by Chef Infra Server. When Chef Infra Client runs, it performs all of the steps required for bringing a node into the expected state, including: * Registering and authenticating the node with Chef Infra Server * Synchronizing cookbooks from the Chef Infra Server to the node * Compiling the resource collection by loading each of the required cookbooks, including recipes, attributes, and all other dependencies * Taking the appropriate and required actions to configure the node based on recipes and attributes * Reporting summary information on the run to Chef Automate Note The Chef Infra Client executable can be run as a daemon. The Chef Infra Client executable is run as a command-line tool. Note The client.rb file specifies how Chef Infra Client is configured on a node and has the following characteristics: * This file is loaded every time the chef-client executable is run. * On Microsoft Windows machines, the default location for this file is `C:\chef\client.rb`. On all other systems the default location for this file is `/etc/chef/client.rb`. * Use the `--config` option from the command line to override the default location of the configuration file. * This file is not created by default Options ------- This command has the following syntax: ``` chef-client OPTION VALUE OPTION VALUE ... ``` This command has the following options: `-A`, `--fatal-windows-admin-check` Cause a Chef Infra Client run to fail when the Chef Infra Client does not have administrator privileges in Microsoft Windows. `-c CONFIG`, `--config CONFIG` The configuration file to use. `--config-option OPTION` Overrides a single configuration option. Can be used to override multiple configuration options by adding another `--config-option OPTION`. ``` property :db_password, String, sensitive: true ``` `--chef-zero-host HOST` The host on which chef-zero is started. `--chef-zero-port PORT` The port on which chef-zero listens. If a port is not specified—individually, as range of ports, or from the `chef_zero.port` setting in the client.rb file—the Chef Infra Client will scan for ports between 8889-9999 and will pick the first port that is available. `-d SECONDS`, `--daemonize SECONDS` Run the executable as a daemon. Use `SECONDS` to specify the number of seconds to wait before the first daemonized Chef Infra Client run. `SECONDS` is set to `0` by default. Left unset, the daemon uses the default `--interval` an `--splay` values. This option is only available on machines that run in UNIX or Linux environments. For machines that are running Microsoft Windows that require similar functionality, use the `chef-client::service` recipe in the `chef-client` cookbook: <https://supermarket.chef.io/cookbooks/chef-client>. This will install a Chef Infra Client service under Microsoft Windows using the Windows Service Wrapper. `--delete-entire-chef-repo` This option deletes an entire repository. This option may only be used when running the Chef Infra Client in local mode, (`--local-mode`). This option requires `--recipe-url` to be specified. `--disable-config` Use to run the Chef Infra Client using default settings. This will prevent the normally-associated configuration file from being used. This setting should only be used for testing purposes and should never be used in a production setting. `-E ENVIRONMENT_NAME`, `--environment ENVIRONMENT_NAME` The name of the environment. `-f`, `--[no-]fork` Contain Chef Infra Client runs in a secondary process with dedicated RAM. When a Chef Infra Client run is complete, the RAM is returned to the master process. This option helps ensure that a Chef Infra Client uses a steady amount of RAM over time because the master process does not run recipes. This option also helps prevent memory leaks such as those that can be introduced by the code contained within a poorly designed cookbook. Use `--no-fork` to disable running Chef Infra Client in fork node. Default value: `--fork`. `-F FORMAT`, `--format FORMAT` The output format: `doc` (default) or `min`. * Use `doc` to print the progress of a Chef Infra Client run using full strings that display a summary of updates as they occur. * Use `min` to print the progress of a Chef Infra Client run using single characters. A summary of updates is printed at the end of a Chef Infra Client run. A dot (`.`) is printed for events that do not have meaningful status information, such as loading a file or synchronizing a cookbook. For resources, a dot (`.`) is printed when the resource is up to date, an `S` is printed when the resource is skipped by `not_if` or `only_if`, and a `U` is printed when the resource is updated. Other formatting options are available when those formatters are configured in the client.rb file using the `add_formatter` option. `--force-formatter` Show formatter output instead of logger output. `--force-logger` Show logger output instead of formatter output. `-g GROUP`, `--group GROUP` The name of the group that owns a process. This is required when starting any executable as a daemon. `-h`, `--help` Show help for the command. `-i SECONDS`, `--interval SECONDS` The frequency (in seconds) at which Chef Infra Client runs. When running Chef Infra Client at intervals, apply `--splay` and `--interval` values before a Chef Infra Client run. Default value: `1800`. `-j PATH`, `--json-attributes PATH` The path to a file that contains JSON data. Used to setup the first client run. The attributes will persist on the Chef Infra Server for all future runs with option `-j`. **Run-lists** Use this option to define a `run_list` object. For example, a JSON file similar to: ``` "run_list": [ "recipe[base]", "recipe[foo]", "recipe[bar]", "role[webserver]" ], ``` may be used by running `chef-client -j path/to/file.json`. In certain situations this option may be used to update `normal` attributes. **Environments** Use this option to set the `chef_environment` value for a node. Note Any environment specified for `chef_environment` by a JSON file will take precedence over an environment specified by the `--environment` option when both options are part of the same command. For example, run the following: ``` chef-client -j /path/to/file.json ``` where `/path/to/file.json` is similar to: ``` { "chef_environment": "pre-production" } ``` This will set the environment for the node to `pre-production`. **All attributes are normal attributes** Any other attribute type that is contained in this JSON file will be treated as a `normal` attribute. Setting attributes at other precedence levels is not possible. For example, attempting to update `override` attributes using the `-j` option: ``` { "name": "dev-99", "description": "Install some stuff", "override_attributes": { "apptastic": { "enable_apptastic": "false", "apptastic_tier_name": "dev-99.bomb.com" } } } ``` will result in a node object similar to: ``` { "name": "maybe-dev-99", "normal": { "name": "dev-99", "description": "Install some stuff", "override_attributes": { "apptastic": { "enable_apptastic": "false", "apptastic_tier_name": "dev-99.bomb.com" } } } } ``` Note This has set the `normal` attribute `node['override_attributes']['apptastic']`. **Specify a policy** Use this option to use policy files by specifying a JSON file that contains the following settings: | Setting | Description | | --- | --- | | `policy_group` | The name of a policy group that exists on the Chef Infra Server. | | `policy_name` | The name of a policy, as identified by the `name` setting in a Policyfile.rb file. | For example: ``` { "policy_name": "appserver", "policy_group": "staging" } ``` `-k KEY_FILE`, `--client_key KEY_FILE` The location of the file that contains the client key. Default value: `/etc/chef/client.pem`. `-K KEY_FILE`, `--validation_key KEY_FILE` The location of the file that contains the key used when a Chef Infra Client is registered with a Chef Infra Server. A validation key is signed using the `validation_client_name` for authentication. Default value: `/etc/chef/validation.pem`. `-l LEVEL`, `--log_level LEVEL` The level of logging to be stored in a log file. Possible levels: `auto` (default), `debug`, `error`, `fatal`, `info`, `trace`, or `warn`. Default value: `warn` (when a terminal is available) or `info` (when a terminal is not available). `-L LOGLOCATION`, `--logfile LOGLOCATION` The location of the log file. This is recommended when starting any executable as a daemon. Default value: `STDOUT`. `--lockfile LOCATION` Use to specify the location of the lock file, which prevents multiple Chef Infra Client processes from converging at the same time. `--minimal-ohai` Run the Ohai plugins for name detection and resource/provider selection and no other Ohai plugins. Set to `true` during integration testing to speed up test cycles. `--[no-]color` View colored output. Default setting: `--color`. `--[no-]fips` Allows OpenSSL to enforce FIPS-validated security during a Chef Infra Client run. `--[no-]skip-cookbook-sync` Use cached cookbooks without overwriting local differences from the server. Use with caution. Useful for patching a set of cookbooks on a machine when iterating during development. `--[no-]listen` Run chef-zero in socketless mode. **This is the default behavior on Chef Client 13.1 and above.** `-n NAME`, `--named-run-list NAME` The run-list associated with a policy file. `-N NODE_NAME`, `--node-name NODE_NAME` The unique identifier of the node. `-o RUN_LIST_ITEM`, `--override-runlist RUN_LIST_ITEM` Replace the current run-list with the specified items. This option will not clear the list of cookbooks (and related files) that is cached on the node. This option will not persist node data at the end of the client run. `--once` Make only one Chef Infra Client run and cancel `interval` and `splay` options. `-P PID_FILE`, `--pid PID_FILE` The location in which a process identification number (pid) is saved. An executable, when started as a daemon, writes the pid to the specified file. Default value: `/tmp/name-of-executable.pid`. `--profile-ruby` Use the `--profile-ruby` option to dump a (large) profiling graph into `/var/chef/cache/graph_profile.out`. Use the graph output to help identify, and then resolve performance bottlenecks in a Chef Infra Client run. This option: * Generates a large amount of data about a Chef Infra Client run. * Has a dependency on the `ruby-prof` gem, which is packaged as part of Chef and Chef Workstation. * Increases the amount of time required to complete a Chef Infra Client run. * Should not be used in a production environment. `-r RUN_LIST_ITEM`, `--runlist RUN_LIST_ITEM` Permanently replace the current run-list with the specified run-list items. `-R`, `--enable-reporting` Enable Reporting, which performs data collection during a Chef Infra Client run. `RECIPE_FILE` The path to a recipe. For example, if a recipe file is in the current directory, use `recipe_file.rb`. This is typically used with the `--local-mode` option. `--recipe-url=RECIPE_URL` The location of a recipe when it exists at a URL. Use this option only when running Chef Infra Client with the `--local-mode` option. `--run-lock-timeout SECONDS` The amount of time (in seconds) to wait for a Chef Infra Client lock file to be deleted. Default value: not set (indefinite). Set to `0` to cause a second Chef Infra Client to exit immediately. `-s SECONDS`, `--splay SECONDS` A random number between zero and `splay` that is added to `interval`. Use splay to help balance the load on the Chef Infra Server by ensuring that many Chef Infra Client runs are not occurring at the same interval. When running Chef Infra Client at intervals, apply `--splay` and `--interval` values before a Chef Infra Client run. Changed in Chef Client 12.0 to be applied before the Chef Client run. `-S CHEF_SERVER_URL`, `--server CHEF_SERVER_URL` The URL for the Chef Infra Server. `-u USER`, `--user USER` The user that owns a process. This is required when starting any executable as a daemon. `-v`, `--version` The Chef Infra Client version. `-W`, `--why-run` Run the executable in why-run mode, which is a type of Chef Infra Client run that does everything except modify the system. Use why-run mode to understand why the Chef Infra Client makes the decisions that it makes and to learn more about the current and proposed state of the system. `-z`, `--local-mode` Run the Chef Infra Client in local mode. This allows all commands that work against the Chef Infra Server to also work against the local chef-repo. ### Chef Infra Client Lock File The Chef Infra Client uses a lock file to ensure that only one Chef Infra Client run is in progress at any time. A lock file is created at the start of a Chef Infra Client run and is deleted at the end of a Chef Infra Client run. A new Chef Infra Client run looks for the presence of a lock file and, if present, will wait for that lock file to be deleted. The location of the lock file can vary by platform. * Use the `lockfile` setting in the client.rb file to specify non-default locations for the lock file. (The default location is typically platform-dependent and is recommended.) * Use the `run_lock_timeout` setting in the client.rb file to specify the amount of time (in seconds) to wait for the lock file associated with an in-progress Chef Infra Client run to be deleted. Run in Local Mode ----------------- Local mode is a way to run the Chef Infra Client against the chef-repo on a local machine as if it were running against the Chef Infra Server. Local mode relies on chef-zero, which acts as a very lightweight instance of the Chef Infra Server. chef-zero reads and writes to the `chef_repo_path`, which allows all commands that normally work against the Chef Infra Server to be used against the local chef-repo. Local mode does not require a configuration file, instead it will look for a directory named `/cookbooks` and will set `chef_repo_path` to be just above that. (Local mode will honor the settings in a configuration file, if desired.) If the client.rb file is not found and no configuration file is specified, local mode will search for a config.rb file. Local mode will store temporary and cache files under the `<chef_repo_path>/.cache` directory by default. This allows a normal user to run the Chef Infra Client in local mode without requiring root access. ### About why-run Mode why-run mode is a way to see what Chef Infra Client would have configured, had an actual Chef Infra Client run occurred. This approach is similar to the concept of “no-operation” (or “no-op”): decide what should be done, but then don’t actually do anything until it’s done right. This approach to configuration management can help identify where complexity exists in the system, where inter-dependencies may be located, and to verify that everything will be configured in the desired manner. When why-run mode is enabled, a Chef Infra Client run will occur that does everything up to the point at which configuration would normally occur. This includes getting the configuration data, authenticating to the Chef Infra Server, rebuilding the node object, expanding the run-list, getting the necessary cookbook files, resetting node attributes, identifying the resources, and building the resource collection, but does not include mapping each resource to a provider or configuring any part of the system. Note why-run mode is not a replacement for running cookbooks in a test environment that mirrors the production environment. Chef uses why-run mode to learn more about what is going on, but also Kitchen on developer systems, along with an internal OpenStack cloud and external cloud providers to test more thoroughly. When Chef Infra Client is run in why-run mode, certain assumptions are made: * If the **service** resource cannot find the appropriate command to verify the status of a service, why-run mode will assume that the command would have been installed by a previous resource and that the service would not be running. * For `not_if` and `only_if` properties, why-run mode will assume these are commands or blocks that are safe to run. These conditions are not designed to be used to change the state of the system, but rather to help facilitate idempotency for the resource itself. That said, it may be possible that these attributes are being used in a way that modifies the system state * The closer the current state of the system is to the desired state, the more useful why-run mode will be. For example, if a full run-list is run against a fresh system, that run-list may not be completely correct on the first try, but also that run-list will produce more output than a smaller run-list For example, the **service** resource can be used to start a service. If the action is `:start`, then the service will start if it isn’t running and do nothing if it is running. If a service is installed from a package, then Chef Infra Client cannot check to see if the service is running until after the package is installed. In that case, why-run mode will indicate what Chef Infra Client would do about the state of the service after installing a package. This is important because service actions often trigger notifications to other resources, so it is important to know that these notifications are triggered correctly. ### About chef-zero chef-zero is a very lightweight Chef Infra Server that runs in-memory on the local machine. This allows the Chef Infra Client to be run against the chef-repo as if it were running against the Chef Infra Server. chef-zero was [originally a standalone tool](https://github.com/chef/chef-zero); it is enabled from within the Chef Infra Client by using the `--local-mode` option. chef-zero is very useful for quickly testing and validating the behavior of the Chef Infra Client, cookbooks, recipes, and run-lists before uploading that data to the actual Chef Infra Server. Note chef-zero does not save data between restarts. Because it is intended to be used locally, chef-zero does not perform input validation, authentication, or authorization, as these security measures are not necessary for local testing. For these reasons, we strongly recommend against using chef-zero as a persistent Chef Infra Server. Changed in Chef Client 12.8, now chef-zero supports all Chef Server API version 12 endpoints, except `/universe`. ### Use Encrypted Data Bags Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. **Create an encrypted data bag for use with Chef Infra Client local mode** To generate an encrypted data bag item in a JSON file for use when Chef Infra Client is run in local mode (via the `--local-mode` option), enter: ``` knife data bag from file my_data_bag /path/to/data_bag_item.json -z --secret-file /path/to/encrypted_data_bag_secret ``` this will create an encrypted JSON file in: ``` data_bags/my_data_bag/data_bag_item.json ``` Run in FIPS Mode ---------------- Federal Information Processing Standards (FIPS) is a United States government computer security standard that specifies security requirements for cryptography. The current version of the standard is FIPS 140-2. Chef Infra Client can be configured to allow OpenSSL to enforce FIPS-validated security during a Chef Infra Client run. This will disable cryptography that is explicitly disallowed in FIPS-validated software, including certain ciphers and hashing algorithms. Any attempt to use any disallowed cryptography will cause Chef Infra Client to throw an exception during a Chef Infra Client run. Note Chef uses MD5 hashes to uniquely identify files that are stored on the Chef Infra Server. MD5 is used only to generate a unique hash identifier and is not used for any cryptographic purpose. Notes about FIPS: * May be enabled for nodes running on Microsoft Windows and Enterprise Linux platforms * Should only be enabled for environments that require FIPS 140-2 compliance **Bootstrap a node using FIPS** ``` knife bootstrap 192.0.2.0 -P vanilla -x root -r 'recipe[apt],recipe[xfs],recipe[vim]' --fips ``` which shows something similar to: ``` OpenSSL FIPS 140 mode enabled ... 192.0.2.0 Chef Infra Client finished, 12/12 resources updated in 78.942455583 seconds ``` Run as a Service ---------------- The Chef Infra Client can be run as a daemon. Use the **Chef Infra Client** cookbook to configure the Chef Infra Client as a daemon. Add the `default` recipe to a node’s run-list, and then use attributes in that cookbook to configure the behavior of the Chef Infra Client. For more information about these configuration options, see the [Chef Infra Client cookbook repository on github](https://github.com/chef-cookbooks/chef-client/). When the Chef Infra Client is run as a daemon, the following signals may be used: `HUP` Use to reconfigure the Chef Infra Client. `INT` Use to terminate immediately without waiting for the current Chef Infra Client run to finish. `QUIT` Use to dump a stack trace, and continue to run. `TERM` Use to terminate but wait for the current Chef Infra Client run to finish, and then exit. `USR1` Use to wake up sleeping Chef Infra Client and trigger node convergence. On Microsoft Windows, both the `HUP` and `QUIT` signals are not supported. Run with Elevated Privileges ---------------------------- The Chef Infra Client may need to be run with elevated privileges in order to get a recipe to converge correctly. On UNIX and UNIX-like operating systems this can be done by running the command as root. On Microsoft Windows this can be done by running the command prompt as an administrator. ### Linux On Linux, the following error sometimes occurs when the permissions used to run the Chef Infra Client are incorrect: ``` chef-client [Tue, 29 Nov 2015 19:46:17 -0800] INFO: *** Chef 12.X.X *** [Tue, 29 Nov 2015 19:46:18 -0800] WARN: Failed to read the private key /etc/chef/client.pem: #<Errno::EACCES: Permission denied - /etc/chef/client.pem``` This can be resolved by running the command as root. There are a few ways this can be done: * Log in as root and then run the Chef Infra Client * Use `su` to become the root user, and then run the Chef Infra Client. For example: ``` su ``` and then: ``` chef-client ``` * Use the sudo utility ``` sudo chef-client ``` * Give a user access to read `/etc/chef` and also the files accessed by the Chef Infra Client. This requires super user privileges and, as such, is not a recommended approach ### Windows On Microsoft Windows, running without elevated privileges (when they are necessary) is an issue that fails silently. It will appear that Chef Infra Client completed its run successfully, but the changes will not have been made. When this occurs, do one of the following to run Chef Infra Client as the administrator: * Log in to the administrator account. (This is not the same as an account in the administrator’s security group.) * Run Chef Infra Client process from the administrator account while being logged into another account. Run the following command: ``` runas /user:Administrator "cmd /C chef-client" ``` This will prompt for the administrator account password. * Open a command prompt by right-clicking on the command prompt application, and then selecting **Run as administrator**. After the command window opens, Chef Infra Client can be run as the administrator Run as Non-root User -------------------- In large, distributed organizations the ability to modify the configuration of systems is sometimes segmented across teams, often with varying levels of access to those systems. For example, core application services may be deployed to systems by a central server provisioning team, and then developers on different teams build tooling to support specific applications. In this situation, a developer only requires limited access to machines and only needs to perform the operations that are necessary to deploy tooling for a specific application. The default configuration of the Chef Infra Client assumes that it is run as the root user. This affords the Chef Infra Client the greatest flexibility when managing the state of any object. However, the Chef Infra Client may be run as a non-root user—i.e. “run as a user with limited system privileges”—which can be useful when the objects on the system are available to other user accounts. When the Chef Infra Client is run as a non-root user the Chef Infra Client can perform any action allowed to that user, as long as that action does not also require elevated privileges (such as sudo or pbrun). Attempts to manage any object that requires elevated privileges will result in an error. For example, when the Chef Infra Client is run as a non-root user that is unable to create or modify users, the **user** resource will not work. ### Set the Cache Path To run a Chef Infra Client in non-root mode, add the `file_cache_path` setting to the client.rb file for the node that will run as the non-root user. Set the value of `file_cache_path` to be the home directory for the user that is running the Chef Infra Client. For example: ``` file_cache_path '~/.chef/cache' ``` or: ``` file_cache_path File.join(File.expand_path('~'), '.chef', 'cache') ``` Note When running the Chef Infra Client using the `--local-mode` option, `~/.chef/local-mode-cache` is the default value for `file_cache_path`. ### Elevate Commands Another example of running the Chef Infra Client as a non-root user involves using resources to pass sudo commands as as an attribute on the resource. For example, the **service** resource uses a series of `_command` attributes (like `start_command`, `stop_command`, and so on), the **package**-based resources use the `options` attribute, and the **script**-based resources use the `code` attribute. A command can be elevated similar to the following: ``` service 'apache2' do start_command 'sudo /etc/init.d/apache2 start' action :start end ``` This approach can work very well on a case-by-case basis. The challenge with this approach is often around managing the size of the `/etc/sudoers` file. Run on IBM AIX -------------- The Chef Infra Client may now be used to configure nodes that are running on the AIX platform, versions 7.1 (TL5 SP2 or higher, recommended) and 7.2. The **service** resource supports starting, stopping, and restarting services that are managed by System Resource Controller (SRC), as well as managing all service states with BSD-based init systems. **System Requirements** The Chef Infra Client has the [same system requirements](../chef_system_requirements/index#chef-infra-client) on the AIX platform as any other platform, with the following notes: * Expand the file system on the AIX platform using `chfs` or by passing the `-X` flag to `installp` to automatically expand the logical partition (LPAR) * The EN_US (UTF-8) character set should be installed on the logical partition prior to installing the Chef Infra Client **Install the Chef Infra Client on the AIX platform** The Chef Infra Client is distributed as a Backup File Format (BFF) binary and is installed on the AIX platform using the following command run as a root user: ``` # installp -aYgd chef-12.0.0-1.powerpc.bff all ``` **Increase system process limits** The out-of-the-box system process limits for maximum process memory size (RSS) and number of open files are typically too low to run the Chef Infra Client on a logical partition (LPAR). When the system process limits are too low, the Chef Infra Client will not be able to create threads. To increase the system process limits: 1. Validate that the system process limits have not already been increased. 2. If they have not been increased, run the following commands as a root user: ``` chsec -f /etc/security/limits -s default -a "rss=-1" ``` and then: ``` chsec -f /etc/security/limits -s default -a "data=-1" ``` and then: ``` chsec -f /etc/security/limits -s default -a "nofiles=50000" ``` Note The previous commands may be run against the root user, instead of default. For example: ``` chsec -f /etc/security/limits -s root_user -a "rss=-1" ``` 3. Reboot the logical partition (LPAR) to apply the updated system process limits. When the system process limits are too low, an error is returned similar to: ``` Error Syncing Cookbooks: ================================================================== Unexpected Error: ----------------- ThreadError: can't create Thread: Resource temporarily unavailable ``` **Install the UTF-8 character set** The Chef Infra Client uses the EN_US (UTF-8) character set. By default, the AIX base operating system does not include the EN_US (UTF-8) character set and it must be installed prior to installing the Chef Infra Client. The EN_US (UTF-8) character set may be installed from the first disc in the AIX media or may be copied from `/installp/ppc/*EN_US*` to a location on the logical partition (LPAR). This topic assumes this location to be `/tmp/rte`. Use `smit` to install the EN_US (UTF-8) character set. This ensures that any workload partitions (WPARs) also have UTF-8 applied. Remember to point `INPUT device/directory` to `/tmp/rte` when not installing from CD. 1. From a root shell type: ``` # smit lang ``` A screen similar to the following is returned: ``` Manage Language Environment Move cursor to desired item and press Enter. Change/Show Primary Language Environment Add Additional Language Environments Remove Language Environments Change/Show Language Hierarchy Set User Languages Change/Show Applications for a Language Convert System Messages and Flat Files F1=Help F2=Refresh F3=Cancel F8=Image F9=Shell F10=Exit Enter=Do ``` 2. Select `Add Additional Language Environments` and press `Enter`. A screen similar to the following is returned: ``` Add Additional Language Environments Type or select values in entry fields. Press Enter AFTER making all desired changes. [Entry Fields] CULTURAL convention to install + LANGUAGE translation to install + INPUT device/directory for software [/dev/cd0] + EXTEND file systems if space needed? yes + WPAR Management Perform Operation in Global Environment yes + Perform Operation on Detached WPARs no + Detached WPAR Names [_all_wpars] + Remount Installation Device in WPARs yes + Alternate WPAR Installation Device [] F1=Help F2=Refresh F3=Cancel F4=List F5=Reset F6=Command F7=Edit F8=Image F9=Shell F10=Exit Enter=Do ``` 3. Cursor over the first two entries—`CULTURAL convention to install` and `LANGUAGE translation to install`—and use `F4` to navigate through the list until `UTF-8 English (United States) [EN_US]` is selected. (EN_US is in capital letters!) 4. Press `Enter` to apply and install the language set. **Providers** The **service** resource has the following providers to support the AIX platform: | Long name | Short name | Notes | | --- | --- | --- | | `Chef::Provider::Service::Aix` | `service` | The provider that is used with the AIX platforms. Use the `service` short name to start, stop, and restart services with System Resource Controller (SRC). | | `Chef::Provider::Service::AixInit` | `service` | The provider that is used to manage BSD-based init services on AIX. | **Enable a service on AIX using the mkitab command** The **service** resource does not support using the `:enable` and `:disable` actions with resources that are managed using System Resource Controller (SRC). This is because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot. One approach for enabling or disabling services that are managed by System Resource Controller (SRC) is to use the **execute** resource to invoke `mkitab`, and then use that command to enable or disable the service. The following example shows how to install a service: ``` execute "install #{node['chef_client']['svc_name']} in SRC" do command "mkssys -s #{node['chef_client']['svc_name']} -p #{node['chef_client']['bin']} -u root -S -n 15 -f 9 -o #{node['chef_client']['log_dir']}/client.log -e #{node['chef_client']['log_dir']}/client.log -a ' -i #{node['chef_client']['interval']} -s #{node['chef_client']['splay']}'" not_if "lssrc -s #{node['chef_client']['svc_name']}" action :run end ``` and then enable it using the `mkitab` command: ``` execute "enable #{node['chef_client']['svc_name']}" do command "mkitab '#{node['chef_client']['svc_name']}:2:once:/usr/bin/startsrc -s #{node['chef_client']['svc_name']} > /dev/console 2>&1'" not_if "lsitab #{node['chef_client']['svc_name']}" end ``` Configuring a Proxy Server -------------------------- See the [proxies](../proxies/index) documentation for information on how to configure Chef Infra Client to use a proxy server. Examples -------- **Run the Chef Infra Client** ``` sudo chef-client ``` **Start a run when the Chef Infra Client is running as a daemon** A Chef Infra Client that is running as a daemon can be woken up and started by sending the process a `SIGUSR1`. For example, to trigger a Chef Infra Client run on a machine running Linux: ``` sudo killall -USR1 chef-client ``` **Setting the initial run-list using a JSON file** A node’s initial run-list is specified using a JSON file on the host system. When running Chef Infra Client as an executable, use the `-j` option to tell Chef Infra Client which JSON file to use. For example: ``` chef-client -j /etc/chef/file.json --environment _default ``` where `file.json` is similar to: ``` { "resolver": { "nameservers": [ "10.0.0.1" ], "search":"int.example.com" }, "run_list": [ "recipe[resolver]" ] } ``` and where `_default` is the name of the environment that is assigned to the node. Warning This approach may be used to update [normal](../attributes#attribute-types) attributes, but should never be used to update any other attribute type, as all attributes updated using this option are treated as `normal` attributes. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ctl_chef_client/Chef Deprecation Warnings ========================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_deprecations_client.md) When we wish to remove a feature or an API in Chef, we try to first mark it with a deprecation warning that contains a link to a description of the change and how to fix it. For example: ``` Deprecated features used! JSON auto inflation is not supported (CHEF-1) at (irb):7:in `irb_binding`. Please see /chef-client/deprecations/json_auto_inflate.html for further details and information on how to correct this problem. ``` Testing for Deprecations ------------------------ To test your code for deprecations, you can put Test Kitchen in a mode where any deprecations cause the chef run to fail. Ensure your `kitchen.yml` includes: ``` provisioner:deprecations_as_errors:true ``` and then run Test Kitchen as usual. Test Kitchen will fail if any deprecation errors are issued. Silencing deprecation warnings ------------------------------ Deprecation warnings are great for ensuring cookbooks are kept up-to-date and to prepare for major version upgrades, sometimes you just can’t fix a deprecation right away. Enabling `treat_deprecation_warnings_as_errors` mode in Test Kitchen integration tests often compounds the problem because it does not distinguish between deprecations from community cookbooks and those in your own code. Two new options are provided for silencing deprecation warnings: `silence_deprecation_warnings` and inline `chef:silence_deprecation` comments. The `silence_deprecation_warnings` configuration value can be set in your `client.rb` or `solo.rb` config file, either to `true` to silence all deprecation warnings or to an array of deprecations to silence. You can specify which to silence either by the deprecation key name (e.g. `"internal_api"`), the numeric deprecation ID (e.g. `25` or “CHEF-25”), or by specifying the filename and line number where the deprecation is being raised from (e.g. `"default.rb:67"`). An example of setting the `silence_deprecation_warnings` option in your `client.rb` or `solo.rb`: ``` silence_deprecation_warnings %w{deploy_resource chef-23 recipes/install.rb:22} ``` or in your `kitchen.yml`: ``` provisioner:name:chef_solosolo_rb:treat_deprecation_warnings_as_errors:truesilence_deprecation_warnings:- deploy_resource- chef-23- recipes/install.rb:22 ``` You can also silence deprecations using a comment on the line that is raising the warning: ``` erl_call 'something' do # chef:silence_deprecation ``` We advise caution in the use of this feature, as excessive or prolonged silencing can lead to difficulty upgrading when the next major release of Chef comes out. All Deprecations ---------------- | ID | Description | Deprecated | Expected Removal | | --- | --- | --- | --- | | [CHEF-0](../deprecations_internal_api/index) | Many internal APIs have been improved. | various | varies | | [CHEF-1](../deprecations_json_auto_inflate/index) | Consumers of JSON are now required to be explicit in how it is turned in to a Chef object. | 12.7 | 13.0 | | [CHEF-2](../deprecations_exit_code/index) | Chef's exit codes are now defined so that it's easy to understand why Chef exited. | 12.11 | 13.0 | | [CHEF-3](../deprecations_chef_gem_compile_time/index) | When using the `chef_gem` resource, the phase to install the gem in must be specified. | 12.1 | 13.0 | | [CHEF-4](../deprecations_attributes/index) | Various improvements have been made to attribute syntax. | various | varies | | [CHEF-5](../deprecations_custom_resource_cleanups/index) | Various improvements have been made to custom resource syntax. | various | varies | | [CHEF-6](../deprecations_easy_install/index) | The `easy_install` resource will be removed. | 12.10 | 13.0 | | [CHEF-7](../deprecations_verify_file/index) | The `verify` metaproperty's `file` substitution will be removed. | 12.5 | 13.0 | | [CHEF-8](../deprecations_supports_property/index) | The `supports` metaproperty will be removed. | 12.14 | 13.0 | | [CHEF-9](../deprecations_chef_rest/index) | The `Chef::REST` API will be removed. | 12.7 | 13.0 | | [CHEF-10](../deprecations_dnf_package_allow_downgrade/index) | DNF package provider and resource do not require `--allow-downgrade` anymore. | 12.18 | 13.0 | | [CHEF-11](../deprecations_property_name_collision/index) | An exception will be raised if a resource property conflicts with an already-existing property or method. | 12.19 | 13.0 | | [CHEF-12](../deprecations_launchd_hash_property/index) | An exception will be raised whenever the `hash` property in the launchd resource is used. | 12.19 | 13.0 | | [CHEF-13](../deprecations_chef_platform_methods/index) | Deprecated `Chef::Platform` methods | 12.18 | 13.0 | | [CHEF-14](../deprecations_run_command/index) | Deprecation of run_command | 12.18 | 13.0 | | [CHEF-18](../deprecations_local_listen/index) | Deprecation of local mode listening. | 13.1 | 15.0 | | [CHEF-19](../deprecations_namespace_collisions/index) | Deprecation of `property_name` within actions. | 13.2 | 14.0 | | [CHEF-20](../deprecations_deploy_resource/index) | Deprecation of the `deploy` resource. | 13.6 | 14.0 | | [CHEF-21](../deprecations_chocolatey_uninstall/index) | Deprecation of the `:uninstall` action in the `chocolatey_package` resource. | 13.7 | 14.0 | | [CHEF-22](../deprecations_erl_call_resource/index) | Deprecation of the `erl_call` resource. | 13.7 | 14.0 | | [CHEF-23](../deprecations_legacy_hwrp_mixins/index) | Deprecation of legacy HWRP mixins. | 12.X | 14.0 | | [CHEF-24](../deprecations_epic_fail/index) | Deprecation of `epic_fail` in favor of `allow_failure` | 13.7 | 14.0 | | [CHEF-25](../deprecations_map_collision/index) | Resource(s) in a cookbook collide with the same resource(s) now included in Chef Infra Client. | XX.X | 15.0 | | [CHEF-26](../deprecations_shell_out/index) | Deprecation of legacy shell_out APIs. | 14.3 | 15.0 | | [CHEF-27](../deprecations_locale_lc_all/index) | Deprecation of lc_all from locale resource | 15.0 | 16.0 | | [CHEF-31](../deprecations_resource_name_without_provides/index) | Deprecation of resource_name declaration without provides | 15.13 | 16.2 | | [CHEF-33](../deprecations_unified_mode/index) | Enabling unified mode in custom resources | 17.0 | | [CHEF-3694](../deprecations_resource_cloning/index) | Resource Cloning will no longer work. | 10.18 | 13.0 | | [OHAI-1](../deprecations_ohai_legacy_config/index) | Ohai::Config removal. | 12.6 | 13.0 | | [OHAI-2](../deprecations_ohai_sigar_plugins/index) | Sigar gem based plugins removal. | 12.19 | 13.0 | | [OHAI-3](../deprecations_ohai_run_command_helpers/index) | run_command and popen4 helper method removal. | 12.8 | 13.0 | | [OHAI-4](../deprecations_ohai_libvirt_plugin/index) | Libvirt plugin attributes changes. | 12.19 | 14.0 | | [OHAI-5](../deprecations_ohai_windows_cpu/index) | Windows CPU plugin attribute changes. | 12.19 | 13.0 | | [OHAI-6](../deprecations_ohai_digitalocean/index) | DigitalOcean plugin attribute changes. | 12.19 | 13.0 | | [OHAI-7](../deprecations_ohai_amazon_linux/index) | Amazon linux moved to the Amazon platform_family. | 13.0 | 13.0 | | [OHAI-8](../deprecations_ohai_cloud/index) | Cloud plugin replaced by the Cloud_V2 plugin. | 13.0 | 13.0 | | [OHAI-9](../deprecations_ohai_filesystem/index) | Filesystem plugin replaced by the Filesystem V2 plugin. | 13.0 | 13.0 | | [OHAI-10](../deprecations_ohai_v6_plugins/index) | Removal of support for Ohai version 6 plugins. | 11.12 | 14.0 | | [OHAI-11](../deprecations_ohai_cloud_v2/index) | Cloud_v2 attribute removal. | 13.1 | 14.0 | | [OHAI-12](../deprecations_ohai_filesystem_v2/index) | Filesystem2 attribute removal. | 13.1 | 14.0 | | [OHAI-13](../deprecations_ohai_ipscopes/index) | Removal of IpScopes plugin | 13.2 | 14.0 | | [OHAI-14](../deprecations_ohai_system_profile/index) | Removal of system_profile plugin | 14.6 | 15.0 | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_deprecations_client/Glossary ======== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/glossary.md) Berkshelf The legacy tool for managing cookbook dependencies. Policyfiles should be used instead. chef `chef` is the Chef Workstation command line tool for managing your Chef development environment including repositories, cookbooks, recipes, attributes, templates, custom resources, and Ruby dependencies. ChefDK The legacy package of tools for developing Chef Infra cookbooks. This product has been superseded by Chef Workstation which should be used instead. ChefSpec ChefSpec is a unit-testing framework for testing Chef Infra cookbooks. Chef Automate A full suite of enterprise capabilities for maintaining continuous visibility into application, infrastructure, and security automation. Chef Infra Client A command-line tool that that runs Chef. Also, the name of Chef as it is installed on a node. Chef Infra Server The Chef Infra Server acts as a hub for configuration data. The Chef Infra Server stores cookbooks, the policies that are applied to nodes, and metadata that describes each registered node that is being managed by Chef Infra Client. Nodes use Chef Infra Client to ask the Chef Infra Server for configuration details, such as recipes, templates, and file distributions. Chef Workstation A collection of tools to aide in development of Chef Infra cookbooks. It uses the full stack installer to give you everything you need to get going in one package. You can download it at [Chef Workstation](https://www.chef.io/downloads/tools/workstation). chef-client The `chef-client` is the name for both the command line tool that runs on your local computer and the program that runs on nodes. The `chef-client` allows you to ensure the configuration compliance of your systems through policy code. You use the chef-client command line tool from your local computer to send instructions to the program on the node. You install the chef-client on nodes with the bootstrap process from your computer and then you configure it to run on an interval to ensure continuous configuration compliance. chef-apply A command-line tool that allows a single recipe to be run from the command line. chef-repo The repository structure in which cookbooks are authored, tested, and maintained. View [an example of the](https://github.com/chef/chef-repo) chef-repo. chef-zero A lightweight Chef Infra Server that runs in-memory on the local machine during a Chef Infra Client run. Also known as local mode. cookbook A cookbook is the fundamental unit of configuration and policy distribution in Chef Infra. Cookstyle A linting tool that helps you write better Chef Infra cookbooks by detecting and automatically correcting style, syntax, and logic mistakes in your code. custom resource An extension to Chef Infra Client that allows you to ship your own reusable resources within a cookbook. data bag A data_bag is a global variable that is stored as JSON data and is accessible from a Chef Infra Server. environment An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra Server. Foodcritic A legacy linting tool for doing static code analysis on cookbooks. This tool has been replaced with Cookstyle which should be used instead. knife A command-line tool that provides an interface between a local chef-repo and the Chef Infra Server. Use it to manage nodes, cookbooks, recipes, roles, data bags, environments, bootstrapping nodes, searching the Chef Infra Server, and more. library A library allows arbitrary Ruby code to be included in a cookbook, either as a way of extending the classes that are built-in to Chef Infra Client or by implementing entirely new functionality. node A node is any physical, virtual, or cloud device that is configured and maintained by an instance of Chef Infra Client. node object A node object is a history of the attributes, run-lists, and roles that were used to configure a node that is under management by Chef Infra. ohai Ohai is a tool that is used to detect attributes on a node, and then provide these attributes to Chef Infra Client at the start of every run. organization An organization is a single instance of a Chef Infra Server, including all of the nodes that are managed by that Chef Infra Server and each of the workstations that will run knife and access the Chef Infra Server using the Chef Infra Server API. policy Policy settings can be used to map business and operational requirements, such as process and workflow, to settings and objects stored on the Chef Infra Server. See roles, environments, and data bags. recipe A recipe is a collection of resources that tells Chef Infra Client how to configure a node. resource A resource is a statement of configuration policy that describes the desired state of an piece within your infrastructure, along with the steps needed to bring that item to the desired state. role A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. run-list A run-list defines all of the configuration settings that are necessary for a node that is under management by Chef to be put into the desired state and the order in which these configuration settings are applied. Test Kitchen Test Kitchen is an integration framework that is used to automatically test cookbook data across any combination of platforms and test suites. Test Kitchen is packaged in Chef Workstation. Unified Mode Unified mode combines the compile and converge stages of the Chef Infra Client run into one phase. Unified mode means that the Chef Infra Client compiles and applies a custom resource in order, from top to bottom. Unified mode works only on custom resources and does not affect other resources or recipes. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/glossary/About Attributes ================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/attributes.md) An attribute is a specific detail about a node. Attributes are used by Chef Infra Client to understand: * The current state of the node * What the state of the node was at the end of the previous Chef Infra Client run * What the state of the node should be at the end of the current Chef Infra Client run Attributes are defined by: * The node as saved on the Chef Infra Server * Attributes passed via JSON on the command line * Cookbooks (in attribute files and/or recipes) * Policyfiles During every Chef Infra Client run, Chef Infra Client builds the attribute list using: * Attributes passed via JSON on the command line * Data about the node collected by [Ohai](../ohai). * The node object that was saved to the Chef Infra Server at the end of the previous Chef Infra Client run. * The rebuilt node object from the current Chef Infra Client run, after it is updated for changes to cookbooks (attribute files and/or recipes) and/or Policyfiles, and updated for any changes to the state of the node itself. After the node object is rebuilt, all of the attributes are compared, and then the node is updated based on attribute precedence. At the end of every Chef Infra Client run, the node object that defines the current state of the node is uploaded to the Chef Infra Server so that it can be indexed for search. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/attributes/supermarket-ctl (executable) ============================ [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/ctl_supermarket.md) The Chef Supermarket installations that are done using the Chef installer include a command-line utility named supermarket-ctl. This command-line tool is used to start and stop individual services, reconfigure the Chef Supermarket server, run smoke tests, and tail the Chef Supermarket log files. make-admin ---------- The `make-admin` subcommand is used to make the named Chef Supermarket user an administrator. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl make-admin USER_NAME ``` where `USER_NAME` represents the name of the user to be granted administrator privileges. spdx ---- The `spdx` subcommands are used to manage SPDX license information in cookbooks. Linked SPDX licenses appear on the cookbook information page. [The Software Package Data Exchange](https://spdx.dev/) (SPDX) is an open standard for software manifests, including components, licenses, copyrights, and security content. SPDX maintains a [License List](https://spdx.org/licenses/) of common licenses and exceptions used in open source development. Changes to the SPDX License List are not automatically reflected in your cookbooks. to To apply changes made by SPDX, rescan your cookbooks with the `spdx` subcommands. ### spdx-all The `spdx-all` command links the licenses known to SPDX for all cookbooks in your system. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl spdx-all ``` ### spdx-latest The `spdx-latest` command links the licenses known to SPDX for the specified cookbook. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl spdx-latest COOKBOOK_NAME ``` Where COOKBOOK_NAME is the name of cookbook for SPDX linking. The latest version of the cookbook receives SPDX linking. ### spdx-on-version The `spdx-on-version` command links the licenses known to SPDX for the specified cookbook version. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl spdx-on-version COOKBOOK_NAME VERSION ``` Where COOKBOOK_NAME is the name of cookbook and VERSION is the version of the cookbook that receives SPDX linking. Quality Metrics --------------- ### qm-flip-admin-only The `qm-flip-admin-only` command is used to make a single named quality metric visible only to admins. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-flip-admin-only "METRIC_NAME" ``` where `METRIC_NAME` is the name of the quality metric to make admin only. Names containing spaces must be surrounded by quotes. ### qm-flip-all-admin-only The `qm-flip-all-admin-only` command is used to make all quality metrics visible only to admins. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-flip-all-admin-only ``` ### qm-flip-all-public The `qm-flip-all-public` command is used to make all quality metrics visible to all users. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-flip-all-public ``` ### qm-flip-public The `qm-flip-public` command is used to make a single named quality metric visible to all users. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-flip-public "METRIC_NAME" ``` where `METRIC_NAME` is the name of the quality metric to make public. Names containing spaces must be surrounded by quotes. ### qm-list The `qm-list` command is used to list the names of quality metrics defined currently in a Supermarket. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-list ``` ### qm-run-all-the-latest The `qm-run-all-the-latest` command is used to run all quality metrics on the latest versions of all cookbooks. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-run-all-the-latest ``` ### qm-run-on-latest The `qm-run-on-latest` command is used to run all quality metrics on the latest version of a named cookbook. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-run-on-version COOKBOOK_NAME ``` where `COOKBOOK_NAME` is the name of the cookbook on which to run all quality metrics on its latest version. ### qm-run-on-version The `qm-run-on-version` command is used to run all quality metrics on a given version of a named cookbook. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-run-on-version COOKBOOK_NAME VERSION ``` where `COOKBOOK_NAME` and `VERSION` are respectively the name and version of the cookbook on which to run all quality metrics. General Commands ---------------- ### cleanse The `cleanse` subcommand is used to re-set the server to the state it was in before the first time the `reconfigure` subcommand is run to destroy all data, configuration files, and logs. This subcommand has the following syntax: ``` supermarket-ctl cleanse ``` ### help The `help` subcommand is used to print a list of all available supermarket-ctl commands. This subcommand has the following syntax: ``` supermarket-ctl help ``` ### reconfigure The `reconfigure` subcommand is used when changes are made to the supermarket.rb file to reconfigure the server. When changes are made to the supermarket.rb file, they will not be applied to the Chef Supermarket configuration until after this command is run. This subcommand will also restart any services for which the `service_name['enabled']` setting is set to `true`. This subcommand has the following syntax: ``` supermarket-ctl reconfigure ``` ### show-config The `show-config` subcommand is used to view the configuration that will be generated by the `reconfigure` subcommand. This command is most useful in the early stages of a deployment to ensure that everything is built properly prior to installation. This subcommand has the following syntax: ``` supermarket-ctl show-config ``` ### uninstall The `uninstall` subcommand is used to remove the Chef Supermarket application, but without removing any of the data. This subcommand will shut down all services (including the `runit` process supervisor). This subcommand has the following syntax: ``` supermarket-ctl uninstall ``` Note To revert the `uninstall` subcommand, run the `reconfigure` subcommand (because the `start` subcommand is disabled by the `uninstall` command). Service Subcommands ------------------- This command has a built in process supervisor that ensures all of the required services are in the appropriate state at any given time. The supervisor starts two processes per service and provides the following subcommands for managing services: `hup`, `int`, `kill`, `once`, `restart`, `service-list`, `start`, `status`, `stop`, `tail`, and `term`. ### hup The `hup` subcommand is used to send a `SIGHUP` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl hup name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. ### int The `int` subcommand is used to send a `SIGINT` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl int name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. ### kill The `kill` subcommand is used to send a `SIGKILL` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl kill name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. ### once The supervisor for Chef Supermarket is configured to restart any service that fails, unless that service has been asked to change its state. The `once` subcommand is used to tell the supervisor to not attempt to restart any service that fails. This command is useful when troubleshooting configuration errors that prevent a service from starting. Run the `once` subcommand followed by the `status` subcommand to look for services in a down state and/or to identify which services are in trouble. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl once name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. ### restart The `restart` subcommand is used to restart all services enabled on Chef Supermarket or to restart an individual service by specifying the name of that service in the command. This subcommand has the following syntax: ``` supermarket-ctl restart name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully restarted the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` ### service-list The `service-list` subcommand is used to display a list of all available services. A service that is enabled is labeled with an asterisk (*). This subcommand has the following syntax: ``` supermarket-ctl service-list ``` ### start The `start` subcommand is used to start all services that are enabled in Chef Supermarket. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl start name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully started the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` The supervisor for Chef Supermarket is configured to wait seven seconds for a service to respond to a command from the supervisor. If you see output that references a timeout, it means that a signal has been sent to the process, but that the process has yet to actually comply. In general, processes that have timed out are not a big concern, unless they are failing to respond to the signals at all. If a process is not responding, use a command like the `kill` subcommand to stop the process, investigate the cause (if required), and then use the `start` subcommand to re-enable it. ### status The `status` subcommand is used to show the status of all services available to Chef Supermarket. The results will vary based on the configuration of a given server. This subcommand has the following syntax: ``` supermarket-ctl status ``` and will return the status for all services. Status can be returned for individual services by specifying the name of the service as part of the command: ``` supermarket-ctl status name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. When service status is requested, the output should be similar to: ``` run: service_name: (pid 12345) 12345s; run: log: (pid 1234) 67890s ``` where * `run:` is the state of the service (`run:` or `down:`) * `service_name:` is the name of the service for which status is returned * `(pid 12345)` is the process identifier * `12345s` is the uptime of the service, in seconds For example: ``` down: actions: (pid 35546) 10s ``` By default, runit will restart services automatically when the services fail. Therefore, runit may report the status of a service as `run:` even when there is an issue with that service. When investigating why a particular service is not running as it should be, look for the services with the shortest uptimes. For example, the list below indicates that the **actions** should be investigated further: ``` run: actions: (pid 6361) 4132s; run: log: (pid 6173) 4146s run: actions_consumer: (pid 6374) 5s; run: log: (pid 6227) 4139s run: actions_messages: (pid 6392) 4131s; run: log: (pid 6324) 4133s run: memcached: (pid 6115) 4157s; run: log: (pid 6129) 4156s ``` #### Log Files A typical status line for a service that is running in Chef Supermarket is similar to the following: ``` run: name_of_service: (pid 1486) 7819s; run: log: (pid 1485) 7819s ``` where: * `run` describes the state in which the supervisor attempts to keep processes. This state is either `run` or `down`. If a service is in a `down` state, it should be stopped * `name_of_service` is the service name * `(pid 1486) 7819s;` is the process identifier followed by the amount of time (in seconds) the service has been running * `run: log: (pid 1485) 7819s` is the log process. It is typical for a log process to have a longer run time than a service; this is because the supervisor does not need to restart the log process in order to connect the supervised process If the service is down, the status line will appear similar to the following: ``` down: actions: 3s, normally up; run: log: (pid 1485) 8526s ``` where * `down` indicates that the service is in a down state * `3s, normally up;` indicates that the service is normally in a run state and that the supervisor would attempt to restart this service after a reboot ### stop The `stop` subcommand is used to stop all services enabled on Chef Supermarket. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl stop name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully stopped the output should be similar to: ``` ok: diwb: service_name: 0s, normally up ``` For example: ``` supermarket-ctl stop ``` will return something similar to: ``` ok: down: actions: 1s, normally up ok: down: actions_consumer: 0s, normally up ok: down: actions_messages: 0s, normally up ok: down: memcached: 1s, normally up ``` ### tail The `tail` subcommand is used to follow all Chef Supermarket logs for all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl tail name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. ### term The `term` subcommand is used to send a `SIGTERM` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl term name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ctl_supermarket/About Cookbooks =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/cookbooks.md) A cookbook is the fundamental unit of configuration and policy distribution in Chef Infra. A cookbook defines a scenario and contains everything that is required to support that scenario: * Recipes that specify which Chef Infra built-in resources to use, as well as the order in which they are to be applied * Attribute values, which allow environment-based configurations such as `dev` or `prodution`. * Custom Resources for extending Chef Infra beyond the built-in resources. * Files and Templates for distributing information to systems. * Custom Ohai Plugins for extending system configuration collection beyond the Ohai defaults. * The `metadata.rb` file, which describes the cookbook itself and any dependencies it may have. The Chef Infra Language is based on Ruby, allowing you to utilize the power of Ruby when the built-in language doesn’t meet your needs out of the box. If you’d like to learn more about extending your Chef Infra code by using Ruby see our [Ruby Guide](../ruby/index) for further information on Ruby functionality. The Chef Infra Language is a comprehensive systems configuration language with resources and helpers for configuring operating systems. The language is primarily used in Chef Infra recipes and custom resources to tell the Chef Infra Client what action(s) to take to configure a system. The Chef Infra Language provides resources for system-level components such as packages, users, or firewalls, and it also includes helpers to allow you to make configuration decisions based on operating systems, clouds, virtualization hypervisors, and more. Chef Infra Client runs a recipe only when instructed. When Chef Infra Client runs the same recipe more than once, the results will be the same system state each time. When a recipe is run against a system, but nothing has changed on either the system or in the recipe, Chef Infra Client won’t change anything. Components ---------- A cookbook is comprised of recipes and other optional components as files or directories. | Component | File/Directory Name | Description | | --- | --- | --- | | [Recipes](../recipes/index) | recipes/ | A recipe is the most fundamental configuration element within the organization. A recipe:* Is authored using Ruby, which is a programming language designed to read and behave in a predictable manner * Is mostly a collection of [resources](../resources/index), defined using patterns (resource names, attribute-value pairs, and actions); helper code is added around this using Ruby, when needed * Must define everything that is required to configure part of a system * Must be stored in a cookbook * May be included in another recipe * May use the results of a search query and read the contents of a data bag (including an encrypted data bag) * May have a dependency on one (or more) recipes * Must be added to a run-list before it can be used by Chef Infra Client * Is always executed in the same order as listed in a run-list | | [Attributes](../attributes/index) | attributes/ | An attribute can be defined in a cookbook (or a recipe) and then used to override the default settings on a node. When a cookbook is loaded during a Chef Infra Client run, these attributes are compared to the attributes that are already present on the node. Attributes that are defined in attribute files are first loaded according to cookbook order. For each cookbook, attributes in the `default.rb` file are loaded first, and then additional attribute files (if present) are loaded in lexical sort order. When the cookbook attributes take precedence over the default attributes, Chef Infra Client applies those new settings and values during a Chef Infra Client run on the node. | | [Files](../files/index) | files/ | A file distribution is a specific type of resource that tells a cookbook how to distribute files, including by node, by platform, or by file version. | | [Libraries](../libraries/index) | libraries/ | A library allows the use of arbitrary Ruby code in a cookbook, either as a way to extend the Chef Infra Client language or to implement a new class. | | [Custom Resources](../custom_resources/index) | resources/ | A custom resource is an abstract approach for defining a set of actions and (for each action) a set of properties and validation parameters. | | [Templates](../templates/index) | templates/ | A template is a file written in markup language that uses Ruby statements to solve complex configuration scenarios. | | [Ohai Plugins](../ohai_custom/index) | ohai/ | Custom Ohai plugins can be written to load additional information about your nodes to be used in recipes. This requires Chef Infra Server 12.18.14 or later. | | [Metadata](../config_rb_metadata/index) | metadata.rb | This file contains information about the cookbook such as the cookbook name, description, and [version](../cookbook_versioning/index). | Community Cookbooks ------------------- Chef maintains a large collection of cookbooks. In addition, there are thousands of cookbooks created and maintained by the community: | Components | Description | | --- | --- | | [Cookbooks Maintained by Chef](https://github.com/chef-cookbooks) | Chef maintains a collection of cookbooks that are widely used by the community. | | [Cookbooks Maintained by Sous Chefs](https://github.com/sous-chefs) | Sous Chefs is a community organization that collaborates to maintain many of the most used Chef cookbooks. | | [Cookbooks Maintained by the Community](https://supermarket.chef.io/cookbooks) | The community has authored thousands of cookbooks, ranging from niche cookbooks that are used by only a few organizations to popular cookbooks used by nearly everyone. | Generate a Cookbook ------------------- Use the [chef generate cookbook subcommand](../workstation/ctl_chef/index#chef-generate-cookbook) to generate a cookbook. A cookbook generated with`chef generate cookbook custom_web` creates a cookbook named `custom_web` with the directory structure: ``` ├ cookbooks ├ custom_web | ├ .delivery | | └ project.toml | ├ recipes | | └ default.rb | ├ test | | └ integration | | | └ default | | | | └ default_test.rb | ├ .gitignore | ├ CHANGELOG.md | ├ chefignore | ├ kitchen.yml | ├ LICENSE | ├ metadata.rb | ├ Policyfile.rb | └ README.md ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/cookbooks/About chef-repo =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_repo.md) The chef-repo is a directory on your workstation that stores everything you need to define your infrastructure with Chef Infra: * Cookbooks (including recipes, attributes, custom resources, libraries, and templates) * Data bags * Policyfiles The chef-repo directory should be synchronized with a version control system, such as git. All of the data in the chef-repo should be treated like source code. You’ll use the `chef` and `knife` commands to upload data to the Chef Infra Server from the chef-repo directory. Once uploaded, Chef Infra Client uses that data to manage the nodes registered with the Chef Infra Server and to ensure that it applies the right cookbooks, policyfiles, and settings to the right nodes in the right order. Generate the chef-repo ---------------------- Use the [chef generate repo command](../ctl_chef/index#chef-generate-repo) to create your chef-repo directory along with the base folder structure. This command uses the `chef` command-line tool that is packaged as part of Chef Workstation to create a chef-repo. ``` chef generate repo REPO_NAME ``` Note `chef generate repo` generates a chef-repo that is configured for Policyfiles by default. To create a repository that is setup for Roles and Environments use the `--roles` flag when running the command. Directory Structure ------------------- The chef-repo contains several directories, each with a README file that describes what it is for and how to use that directory when managing systems. The default structure of a new chef-repo is: ``` . chef-repo ├ cookbooks | └ README.md | ├ example | ├ attribtes | | └ default.rb | ├ recipes | | └ default.rb | └ metadata.rb | └ README.md ├ data_bags | ├ example | | └ example_item.json | └ README.md ├ policyfiles | └ README.md └ .chef-repo.txt └ chefignore └ License └ README.md ``` ### cookbooks/ This directory contains the cookbooks that are used to configure systems in the infrastructure which are are downloaded from the [Chef Supermarket](https://supermarket.chef.io/) or created locally. The Chef Infra Client uses cookbooks to configuring the systems in the organization. Each cookbook can be configured to contain cookbook-specific copyright, email, and license data. ### data_bags/ The `data_bags/` directory is used to store all the data bags that exist for an organization. Each sub-directory corresponds to a single data bag on the Chef Infra Server and contains a JSON file corresponding to each data bag item. ### policyfiles/ The `policyfiles/` directory is used to store Policyfiles in the `.rb` format that define the set of cookbooks and attributes to apply to specific systems managed by the Chef Infra Server. chefignore Files ---------------- The chefignore file is used to tell knife which cookbook files in the chef-repo should be ignored when uploading data to the Chef Infra Server. The type of data that should be ignored includes swap files, version control data, build output data, and so fort. The chefignore file uses the `File.fnmatch` Ruby syntax to define the ignore patterns using `*`, `**`, and `?` wildcards. * A pattern is relative to the cookbook root * A pattern may contain relative directory names * A pattern may match all files in a directory The chefignore file can be located in any subdirectory of a chef-repo: `/`, `/cookbooks`, `/cookbooks/COOKBOOK_NAME/`, etc. It should contain sections similar to the following: ``` ## section *ignore_pattern ## section ignore_pattern* ## section **ignore_pattern ## section ignore_pattern** ## section ?ignore_pattern ## section ignore_pattern? ``` ### Examples The following example shows how to add entries to the `chefignore` file. #### Ignore editor swap files Many text editors leave files behind. To prevent these files from being uploaded to the Chef Infra Server, add an entry to the `chefignore` file. For Emacs: ``` *~ ``` and for vim: ``` *.sw[a-z] ``` Many Users, Same Repo --------------------- The config.rb configuration can include arbitrary Ruby code to extend configuration beyond static values. This can be used to load environmental variables from the workstation. This makes it possible to write a single config.rb file that can be used by all users within your organization. This single file can also be checked into your chef-repo, allowing users to load different config.rb files based on which chef-repo they execute the commands from. This can be especially useful when each chef-repo points to a different chef server or organization. Example config.rb: ``` current_dir = File.dirname(__FILE__) user = ENV['CHEF_USER'] || ENV['USER'] node_name user client_key "#{ENV['HOME']}/chef-repo/.chef/#{user}.pem" chef_server_url "https://api.opscode.com/organizations/#{ENV['ORGNAME']}" syntax_check_cache_path "#{ENV['HOME']}/chef-repo/.chef/syntax_check_cache" cookbook_path ["#{current_dir}/../cookbooks"] cookbook_copyright "Your Company, Inc." cookbook_license "Apache-2.0" cookbook_email "<EMAIL>" # Amazon AWS knife[:aws_access_key_id] = ENV['AWS_ACCESS_KEY_ID'] knife[:aws_secret_access_key] = ENV['AWS_SECRET_ACCESS_KEY'] ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_repo/Attribute Persistence ===================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/attribute_persistence.md) All attributes except for normal attributes are reset at the beginning of a Chef Infra Client run. Attributes set via `chef-client -j` with a JSON file have normal precedence and are persisted between Chef Infra Client runs. Chef Infra Client rebuilds these attributes using automatic attributes collected by Ohai at the beginning of each Chef Infra Client run, and then uses default and override attributes that are specified in cookbooks, roles, environments, and Policyfiles. All attributes are then merged and applied to the node according to attribute precedence. The attributes that were applied to the node are saved to the Chef Infra Server as part of the node object at the conclusion of each Chef Infra Client run. Limiting Attribute Persistence ------------------------------ Some organizations find it helpful to control attribute data stored to the Chef Infra Server in order to limit the disk and CPU resources used when processing unused attributes. For example, your organization may find the data from the Ohai `Package` plugin useful when writing cookbooks, but you don’t see the need in saving ~100k of package information for each Chef Infra Client run. By limiting the data that is saved to the Chef Infra Server, it will still be available on the node within cookbooks, but won’t be saved to the Chef Infra Server where it is available in searches. Note In Chef Infra Client 16.3 the node Blacklist and Whitelist features were renamed to Blocklist and Allowlist. For backwards compatibility the old configuration values will continue to work, but this document will describe the Blocklist and Allowlist names. See each section below for the appropriate legacy configuration values if you are running legacy clients in your organization. Legacy config mapping: * automatic_attribute_blacklist -> blocked_automatic_attributes * default_attribute_blacklist -> blocked_default_attributes * normal_attribute_blacklist -> blocked_normal_attributes * override_attribute_blacklist -> blocked_override_attributes * automatic_attribute_whitelist -> allowed_automatic_attributes * default_attribute_whitelist -> allowed_default_attributes * normal_attribute_whitelist -> allowed_normal_attributes * override_attribute_whitelist -> allowed_override_attributes * enforce_path_sanity -> enforce_default_paths ### Attribute Blocklist Warning When attribute blocklist settings are used, any attribute defined in a blocklist will not be saved to the Chef Infra Server and any attribute that is not defined in a blocklist will be saved. Each attribute type must be blocklisted independently of the other attribute types. For example, if `blocked_automatic_attributes` defines attributes that will not be saved, but `blocked_normal_attributes`, `blocked_default_attributes`, and `blocked_override_attributes` are not defined, then all normal attributes, default attributes, and override attributes will be saved, as well as the automatic attributes that were not specifically excluded through blocklisting. Attributes that should not be saved by a node may be blocklisted in the [client.rb](../config_rb_client/index) file. The blocklist is a Hash of keys that specify each attribute to be filtered out. Attributes are blocklisted by attribute type, with each attribute type being blocklisted independently. Each attribute type—`automatic`, `default`, `normal`, and `override`—may define blocklists by using the following settings in the client.rb file: | Setting | Description | | --- | --- | | `blocked_automatic_attributes` | A hash that blocklists `automatic` attributes, preventing blocklisted attributes from being saved. For example: `['network/interfaces/eth0']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | | `blocked_default_attributes` | A hash that blocklists `default` attributes, preventing blocklisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | | `blocked_normal_attributes` | A hash that blocklists `normal` attributes, preventing blocklisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | | `blocked_override_attributes` | A hash that blocklists `override` attributes, preventing blocklisted attributes from being saved. For example: `['map - autohome/size']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | #### Blocklisting Ohai (automatic) Attributes The recommended practice is to use `blocked_automatic_attributes` to block attributes populated by Ohai’s system information gathering. Ohai gathers a large number of attributes that can consume a signicant amount of storage space on the Chef Infra Server. Many of these attributes may be considered highly valuable, while others could be blocklisted without any impact to data available in search. Normal, default, and override attributes are typically much more important attributes used within cookbooks and are more likely to cause issues if they are blocklisted incorrectly. For example, automatic attribute data similar to: ``` { "filesystem" => { "/dev/disk0s2" => { "size" => "10mb" }, "map - autohome" => { "size" => "10mb" } }, "network" => { "interfaces" => { "eth0" => {...}, "eth1" => {...}, } } } ``` To blocklist the `filesystem` attributes and allow the other attributes to be saved, update the client.rb file: ``` blocked_automatic_attributes ['filesystem'] ``` When a blocklist is defined, any attribute of that type that is not specified in that attribute blocklist **will** be saved. So based on the previous blocklist for automatic attributes, the `filesystem` and `map - autohome` attributes will not be saved, but the `network` attributes will. For attributes that contain slashes (`/`) within the attribute value, such as the `filesystem` attribute `'/dev/diskos2'`, use an array. For example: ``` blocked_automatic_attributes [['filesystem', '/dev/diskos2']] ``` ### Attribute Allowlist Warning When attribute allowlist settings are used, only the attributes defined in a allowlist will be saved and any attribute that is not defined in a allowlist will not be saved. Each attribute type is allowlisted independently of the other attribute types. For example, if `automatic_attribute_allowlist` defines attributes to be saved, but `normal_attribute_allowlist`, `default_attribute_allowlist`, and `override_attribute_allowlist` are not defined, then all normal attributes, default attributes, and override attributes are saved, as well as the automatic attributes that were specifically included through allowlisting. Attributes that should be saved by a node may be allowlisted in the client.rb file. The allowlist is a hash of keys that specifies each attribute to be saved. Attributes are allowlisted by attribute type, with each attribute type being allowlisted independently. Each attribute type—`automatic`, `default`, `normal`, and `override`—may define allowlists by using the following settings in the client.rb file: | Setting | Description | | --- | --- | | `allowed_automatic_attributes` | A hash that allowlists `automatic` attributes, preventing non-allowlisted attributes from being saved. For example: `['network/interfaces/eth0']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | | `allowed_default_attributes` | A hash that allowlists `default` attributes, preventing non-allowlisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | | `allowed_normal_attributes` | A hash that allowlists `normal` attributes, preventing non-allowlisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | | `allowed_override_attributes` | A hash that allowlists `override` attributes, preventing non-allowlisted attributes from being saved. For example: `['map - autohome/size']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | #### Allowlisting Ohai (automatic) Attributes The recommended practice is to use `allowed_automatic_attributes` to allow specific attributes populated by Ohai’s system information gathering. Ohai gathers a large number of attributes that can consume a signicant amount of storage space on the Chef Infra Server. Many of these attributes may be considered highly valuable, while others could be skipped without any impact to data available in search. Normal, default, and override attributes are typically much more important attributes used within cookbooks and are more likely to cause issues if they are ommited from an allowlist incorrectly. For example, automatic attribute data similar to: ``` { "filesystem" => { "/dev/disk0s2" => { "size" => "10mb" }, "map - autohome" => { "size" => "10mb" } }, "network" => { "interfaces" => { "eth0" => {...}, "eth1" => {...}, } } } ``` To allowlist the `network` attributes and prevent the other attributes from being saved, update the client.rb file: ``` allowed_automatic_attributes ['network/interfaces/'] ``` When a allowlist is defined, any attribute of that type that is not specified in that attribute allowlist **will not** be saved. So based on the previous allowlist for automatic attributes, the `filesystem` and `map - autohome` attributes will not be saved, but the `network` attributes will. Leave the value empty to prevent all attributes of that attribute type from being saved: ``` allowed_automatic_attributes [] ``` For attributes that contain slashes (`/`) within the attribute value, such as the `filesystem` attribute `'/dev/diskos2'`, use an array. For example: ``` allowed_automatic_attributes [['filesystem', '/dev/diskos2']] ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/attribute_persistence/Troubleshooting =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/errors.md) The following sections describe how to troubleshoot the Chef Infra Server, Chef Infra Client, and Chef Workstation. 401 Unauthorized ---------------- There are multiple causes of the Chef 401 “Unauthorized” error, so please use the sections below to find the error message that most closely matches your output. If you are unable to find a matching error, or if the provided steps are unhelpful, please [file a help ticket](https://getchef.zendesk.com/hc/en-us). ### Failed to authenticate as ORGANIZATION-validator If you’re receiving an error like the following it most likely means you’ll need to regenerate the ORGANIZATION-validator.pem file: ``` INFO: Client key /etc/chef/client.pem is not present - registering INFO: HTTP Request Returned 401 Unauthorized: Failed to authenticate as ORGANIZATION-validator. Ensure that your node_name and client key are correct. FATAL: Stacktrace dumped to c:/chef/cache/chef-stacktrace.out FATAL: Net::HTTPClientException: 401 "Unauthorized" ``` #### Troubleshooting Steps 1. Check if the ORGANIZATION-validator.pem file exists in one of the following locations: ``` ~/.chef ~/projects/current_project/.chef /etc/chef ``` If one is present, verify that it has the correct read permissions. 2. If there’s no ORGANIZATION-validator.pem file, regenerate it. Recreate this file by going to the Chef management console web user interface and selecting **Organizations** in the upper right side of the screen. You can then select **Reset Validation Key** next to the organization for which the key is to be reset. Failed to authenticate to ------------------------- When the values for certain settings in the client.rb file—`node_name` and `client_key`—are incorrect, it will not be possible to authenticate to the Chef Infra Server. An error similar to the following is shown: ``` ERROR: Failed to authenticate to https://api.opscode.com/organizations/ORGANIZATION as USERNAME with key /path/to/USERNAME.pem Response: Failed to authenticate as USERNAME. Ensure that your node_name and client key are correct. ``` ### Troubleshooting Steps * Verify you have the correct values in your config.rb file, especially for the `node_name` and `client_key` settings. * Check if the file referenced in the `client_key` setting (usually USER.pem) exists. Some common locations include: + `~/.chef` + `~/projects/current_project/.chef` + `/etc/chef` If one is present, verify that it has the correct read permissions. * If there’s no client.rb file, regenerate it and ensure the values for the `node_name` and `client_key` settings are correct. ### Organization not found If you see this error when trying to recreate the ORGANIZATION-validator.pem, it’s possible that Chef Infra Client itself was deleted. In this situation, the ORGANIZATION-validator.pem will need to be recreated. In these directions, `ORGANIZATION` should be replaced with the name of your organization. To reset a chef-validator key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a chef-validator key. 5. Click the **Details** tab. 6. Click **Reset Key**. 7. In the **Reset Key** dialog box, confirm that the key should be regenerated and click the **Reset Key** button: ![image] 8. Copy the private key: ![image] or download and save the private key locally: ![image] ### Synchronize the clock on your host If the system clock drifts more than 15 minutes from the actual time, the following type of error will be shown: ``` INFO: Client key /etc/chef/client.pem is not present - registering INFO: HTTP Request Returned 401 Unauthorized: Failed to authenticate as ORGANIZATION-validator. Synchronize the clock on your host. FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out FATAL: Net::HTTPClientException: 401 "Unauthorized" ``` To resolve this error, synchronize the clock with an NTP server. ### All other 401 errors The general `Net::HTTPClientException: 401 "Unauthorized"` error will usually occur for one of two reasons. #### Troubleshooting Steps 1. Make sure your `client.pem` is valid. This can be fixed by deleting `client.pem` in `/etc/chef` and deleting the client and node with knife. On a management station: ``` # Dump the current node to JSON knife node show NODE_NAME -fJ > NODE_NAME.json knife client delete FQDN -y knife node delete FQDN -y ``` On an affected node (as root): ``` rm /etc/chef/client.pem chef-client ``` When Chef Infra Client runs, it will register the API client and generate the correct key. After successfully running Chef Infra Client on the node, reload the `run_list` and node attributes: ``` knife node from file NODE_NAME.json ``` 2. Make sure to use the same `node_name` as the initial Chef Infra Client run. This can happen for a number of reasons. For example, if the client.rb file does not specify the correct node name and the system’s hostname has changed. Running `chef-client -l debug` will identify the node name being used by Chef Infra Client for authentication attempts: ``` DEBUG: Signing the request as SOME_NODE_NAME ``` This can be fixed by explicitly setting `node_name` in the client.rb file to match the name originally used to register. ``` node_node 'mynode.mycompany.com' ``` Alternatively, re-register the node using the method described previously. 403 Forbidden ------------- If you’re seeing output like this: ``` FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out FATAL: Net::HTTPClientException: 403 "Forbidden" ``` this is an indication that there is an issue with permissions on the Chef Infra Server. ### Troubleshooting Steps In Chef, there are two different types of permissions issues, object specific and global permissions. To figure out which type of permission issue you’re experiencing, run Chef Infra Client again using the `-l debug` options to see debugging output. You should see something like this up the stack trace: ``` DEBUG: Sending HTTP Request to https://api.opscode.com/organizations/ORGNAME/nodes ERROR: Running exception handlers ``` The URL will help identify the type of permission issue. If the URL is an index action (i.e. operating on a collection of resources, like `/nodes`) then this is a global permission. If the URL is operating on an instance of a collection (i.e. `/nodes/NODENAME`) then this is an object permission issue. To fix the global permissions: 1. Log in to the Chef management console and click on the failing object type (most likely **Nodes**). 2. Click on the **Permissions** sub-tab. Which permission it needs, depends on which request that failed: GET - Under the group section, make sure it has the LIST permission checked POST - Under the group section, make sure it has the CREATE permission checked 3. Check the checkboxes needed and save the updates. To fix object permissions: 1. Log in to the Chef management console and click on the failing object type (most likely **Nodes**). 2. Click on the object in the list that is causing the error. 3. Click on the **Permissions** sub-tab. Which permission it needs, depends on the type of request that failed: GET - Make sure it has the READ permission checked PUT - Make sure it has the UPDATE permission checked DELETE - Make sure it has the DELETE permission checked 4. Check the checkboxes needed and save the updates. 500 (Unexpected) ---------------- HTTP 500 is a non-specific error message. The full error message for the error Chef Infra Client is receiving can be found in one of the following log files: * `/var/log/opscode/opscode-account/current` * `/var/log/opscode/opscode-erchef/current` The error will likely found in a stacktrace from the application error. In some cases the error message will clearly indicate a problem with another service which can be investigated further. For non-obvious errors, please contact Chef and attach the log files. 502 / 504 (Gateway) ------------------- Determine which API service is returning 504s using the Nginx access logs. API requests returning 504 can be found with the following command on a frontend: ``` grep 'HTTP/1.1" 504' /var/log/opscode/nginx/access.log ``` The following will extract the URLs and sort them by `uniq` count: ``` grep 'HTTP/1.1" 504' nginx-access.log | cut -d' ' -f8 | sort | uniq -c | sort ``` In a large installation, you may need to restrict this to a subset of the requests: ``` tail -10000 nginx-access.log | grep 'HTTP/1.1" 504' | cut -d' ' -f8 | sort | uniq -c | sort ``` You can also use the `ntail` utility. If the problematic service is a Ruby-based service and the frontend machines have free RAM or CPU, consider increasing the number of worker processes. If the problematic service is **opscode-erchef**, use the request log to determine whether a particular component of requests is slow. Workflow Problems ----------------- In working with Chef, you’ll most likely encounter issues in your regular workflow. This page is a collection of common errors our users have reported while working with Chef. Please use the accordion below to select the error message that most closely matches your output. If you are unable to find a matching error, or if the provided steps are unhelpful, please [file a help ticket](https://getchef.zendesk.com/hc/en-us). ### No such file or directory If you’re seeing an error like: ``` Client key /etc/chef/client.pem is notresent - registering WARN: Failed to read the private key /etc/che/validation.pem: #<Errno::ENOENT: No such file or directory - /etc/chef/validation.pem> FATAL: Stacktrace dumped to /etc/chef/cache/chef-stacktrace.out FATAL: Chef::Exceptions::PrivateKeyMissing: I cannot read /etc/chef/validation.pem, which you told me to use to sign requests ``` It means that Chef Infra Client could not find your validation.pem. #### Troubleshooting Steps 1. Make sure your `validation.pem` or `ORGANIZATION-validator.pem` is downloaded and accessible by the current user. 2. Make sure your client.rb points to the location of your validator pem. ### Commit or stash your changes This isn’t really an error, but can be confusing to new users. When you try to install a cookbook with changes that have not been committed to git you will get this error: ``` Installing getting-started to /home/jes/chef-repo/.chef/../cookbooks ERROR: You have uncommitted changes to your cookbook repo: M cookbooks/getting-started/recipes/default.rb ?? .chef/ ?? log Commit or stash your changes before importing cookbooks ``` #### Troubleshooting Steps Solve this by committing the cookbook changes. For example, the following command would commit all new changes with the message “updates”. ``` git commit -am "Updating so I can install a site cookbook" ``` Re-run the `knife supermarket install` subcommand again to install the community cookbook. ### Cannot find config file If you’re seeing an error like: ``` WARN: *************************************** WARN: Can not find config file: /etc/chef/client.rb, using defaults. WARN: No such file or directory - /etc/chef/client.rb # ... output truncated ... # FATAL: Chef::Exceptions::PrivateKeyMissing: I cannot read /etc/chef/validation.pem, which you told me to use to sign requests! ``` #### Troubleshooting Steps Work around this issue by supplying the full path to the client.rb file: ``` chef-client -c /etc/chef/client.rb ``` ### Pivotal.rb does not exist If you’re seeing an error like: ``` ERROR: CONFIGURATION ERROR:Specified config file /etc/opscode/pivotal.rb does not exist ``` #### Troubleshooting Steps Run the following to restart all of the services: > ``` > chef-server-ctl reconfigure > ``` Because the Chef Infra Server is composed of many different services that work together to create a functioning system, this step may take a few minutes to complete. External PostgreSQL ------------------- The following error messages may be present when configuring the Chef Infra Server to use a remote PostgreSQL server. ### CSPG001 (changed setting) #### Reason The value of `postgresql['external']` has been changed. #### Possible Causes * This setting must be set before running `chef-server-ctl reconfigure`, and may not be changed after Warning Upgrading is not supported at this time. #### Resolution * Back up the data using `knife ec backup`, create a new backend instance, and then restore the data * Re-point front end machines at the new backend instance **or** assign the new backend instance the name/VIP of the old backend instance (including certificates, keys, and so on) ### CSPG010 (cannot connect) #### Reason Cannot connect to PostgreSQL on the remote server. #### Possible Causes * PostgreSQL is not running on the remote server * The port used by PostgreSQL is blocked by a firewall on the remote server * Network routing configuration is preventing access to the host * When using Amazon Web Services (AWS), rules for security groups are preventing the Chef Infra Server from communicating with PostgreSQL ### CSPG011 (cannot authenticate) #### Reason Cannot authenticate to PostgreSQL on the remote server. #### Possible Causes * Incorrect password specified for `db_superuser_password` * Incorrect user name specified for `db_superuser` ### CSPG012 (incorrect rules) #### Reason Cannot connect to PostgreSQL on the remote server because rules in `pg_hba` are incorrect. #### Possible Causes * There is no `pg_hba.conf` rule for the `db_superuser` in PostgreSQL * A rule exists for the `db_superuser` in `pg_hba.conf`, but it does not specify `md5` access * A rule in `pg_hba.conf` specifies an incorrect originating address #### Resolution Entries in the `pg_hba.conf` file should allow: * All user names that originate from any Chef Infra Server instance using `md5` authentication. * A specific application names: `$db_superuser` (the configured superuser name in the chef-server.rb file), `oc_id`, `oc_id_ro`, `opscode_chef`, `opscode_chef_ro`, `bifrost`, and `bifrost_ro` ##### pg_hba.conf User Names For example, a `pg_hba.conf` entry for a valid username and password from the 192.0.2.0 subnet: ``` host postgres all 192.0.2.0/24 md5 ``` or, specific named users with a valid password originating from the 192.0.2.0 subnet. A file named `$PGDATA/chef_users` with the following content must be created: ``` opscode_chef opscode_chef_ro bifrost bifrost_ro oc_id oc_id_ro ``` where `CHEF-SUPERUSER-NAME` is replaced with the same user name specified by `postgresql['db_superuser']`. The corresponding `pg_hba.conf` entry is similar to: ``` host postgres @chef_users 192.168.93.0/24 md5 ``` or, using the same `$PGDATA/chef_users` file (from the previous example), the following example shows a way to limit connections to specific nodes that are running components of the Chef Infra Server.This approach requires more maintenance because the `pg_hba.conf`file must be updated when machines are added to or removed from theChef Infra Server configuration. For example, a high availability configuration with four nodes: `backend-1` (192.0.2.100),`backend-2` (192.0.2.101), `frontend-1` (192.0.2.110), and`frontend-2` (192.0.2.111). The corresponding `pg_hba.conf` entry is similar to: ``` host postgres @chef_users 192.0.2.100 md5 host postgres @chef_users 192.0.2.101 md5 host postgres @chef_users 192.0.2.110 md5 host postgres @chef_users 192.0.2.111 md5 ``` These changes also require a configuration reload for PostgreSQL: ``` pg_ctl reload ``` or: ``` SELECT pg_reload_conf(); ``` ##### pg_hba.conf Application names Rules in the `pg_hba.conf` file should allow only specific application names: * `$db_superuser` (the configured superuser name in the chef-server.rb file) * `oc_id` * `oc_id_ro` * `opscode_chef` * `opscode_chef_ro` * `bifrost` * `bifrost_ro` ### CSPG013 (incorrect permissions) #### Reason The `db_superuser` account has incorrect permissions. #### Possible Causes * The `db_superuser` account has not been granted `SUPERUSER` access * The `db_superuser` account has not been granted `CREATE DATABASE` and `CREATE ROLE` privileges ``` ALTER ROLE "$your_db_superuser_name" WITH SUPERUSER ``` or: ``` ALTER ROLE "$your_db_superuser_name" WITH CREATEDB CREATEROLE ``` ### CSPG014 (incorrect version) #### Reason Bad version of PostgreSQL. #### Possible Causes * The remote server is not running PostgreSQL version 9.2.x ### CSPG015 (missing database) #### Reason The database template `template1` does not exist. #### Possible Causes * The `template1` database template has been removed from the remote server #### Resolution * Run the following command (as a superuser): ``` CREATE DATABASE template1 TEMPLATE template0 ``` or: ``` createdb -T template0 template1 ``` ### CSPG016 (database exists) #### Reason One (or more) of the PostgreSQL databases already exists. #### Possible Causes * The `opscode_chef`, `oc_id`, and/or `bifrost` databases already exist on the remote machine * The PostgreSQL database exists for another application #### Resolution * Verify that the `opscode_chef`, `oc_id`, and/or `bifrost` databases exist, and then verify that they are not being used by another internal application * Back up the PostgreSQL data, remove the existing databases, and reconfigure the Chef server ### CSPG017 (user exists) #### Reason One (or more) of the PostgreSQL predefined users already exists. #### Possible Causes * The `opscode_chef`, `ospcode_chef_ro`, `bifrost`, `bifrost_ro`, `oc_id`, or `oc_id_ro` users already exist on the remote machine * The `postgresql['vip']` setting is configured to a remote host, but `postgresql['external']` is not set to `true`, which causes the `opscode_chef` and `ospcode_chef_ro` users to be created before the machine is reconfigured, which will return a permissions error * Existing, valid naming conflicts are present, where the users were created independently of the Chef server #### Resolution * Run the following, if it is safe to do so, to update the user name that is specified in the error message: ``` DROP ROLE "name-of-user"; ``` or change the name of the user by updating following settings in the chef-server.rb configuration file: ``` oc_id['sql_user'] = 'alternative_username' oc_id['sql_ro_user'] = alternative_username_for_ro_access' opscode_erchef['sql_user'] = 'alternative_username' opscode_erchef['sql_ro_user'] = 'alternative_username_for_ro_access' oc_bifrost['sql_ro_user'] = 'alternative_username' oc_bifrost['sql_ro_user'] = 'alternative_username_for_ro_access' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/errors/Attribute Arrays ================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/attribute_arrays.md) Attributes are typically defined in cookbooks, recipes, roles, and environments. These attributes are rolled-up to the node level during a Chef Infra Client run. A recipe can store attribute values using a multi-level hash or array. For example, a group of attributes for web servers might be: ``` override_attributes( :apache => { :listen_ports => [ 80 ], :prefork => { :startservers => 20, :minspareservers => 20, :maxspareservers => 40 } } ) ``` But what if all of the web servers are not the same? What if some of the web servers required a single attribute to have a different value? You could store these settings in two locations, once just like the preceding example and once just like the following: ``` override_attributes( :apache => { :listen_ports => [ 80 ], :prefork => { :startservers => 30, :minspareservers => 20, :maxspareservers => 40 } } ) ``` But that is not very efficient, especially because most of them are identical. The deep merge capabilities of Chef Infra Client allows attributes to be layered across cookbooks, recipes, roles, and environments. This allows an attribute to be reused across nodes, making use of default attributes set at the cookbook level, but also providing a way for certain attributes (with a higher attribute precedence) to be applied only when they are supposed to be. For example, a role named `baseline.rb`: ``` name "baseline" description "The most basic role for all configurations" run_list "recipe[baseline]" override_attributes( :apache => { :listen_ports => [ 80 ], :prefork => { :startservers => 20, :minspareservers => 20, :maxspareservers => 40 } } ) ``` and then a role named `web.rb`: ``` name 'web' description 'Web server config' run_list 'role[baseline]' override_attributes( :apache => { :prefork => { :startservers => 30 } } ) ``` Both of these files are similar because they share the same structure. When an attribute value is a hash, that data is merged. When an attribute value is an array, if the attribute precedence levels are the same, then that data is merged. If the attribute value precedence levels in an array are different, then that data is replaced. For all other value types (such as strings, integers, etc.), that data is replaced. For example, the `web.rb` references the `baseline.rb` role. The `web.rb` file only provides a value for one attribute: `:startservers`. When Chef Infra Client compares these attributes, the deep merge feature will ensure that `:startservers` (and its value of `30`) will be applied to any node for which the `web.rb` attribute structure should be applied. This approach will allow a recipe like this: ``` include_recipe 'apache2' Chef::Log.info(node['apache']['prefork'].to_hash) ``` and a `run_list` like this: ``` run_list/web.json { "run_list": [ "role[web]" ] } ``` to produce results like this: ``` [Tue, 16 Aug 2011 14:44:26 -0700] INFO: { "startservers"=>30, "minspareservers"=>20, "maxspareservers"=>40, "serverlimit"=>400, "maxclients"=>400, "maxrequestsperchild"=>10000 } ``` Even though the `web.rb` file does not contain attributes and values for `minspareservers`, `maxspareservers`, `serverlimit`, `maxclients`, and `maxrequestsperchild`, the deep merge capabilities pulled them in. Attribute Array Logic --------------------- The following sections show how the logic works for using deep merge to perform substitutions and additions of attributes. ### Substitution The following examples show how the logic works for substituting an existing string using a hash: ``` role_or_environment 1 { :x => '1', :y => '2' } + role_or_environment 2 { :y => '3' } = { :x => '1', :y => '3' } ``` For substituting an existing boolean using a hash: ``` role_or_environment 1 { :x => true, :y => false } + role_or_environment 2 { :y => true } = { :x => true, :y => true } ``` For substituting an array with a hash: ``` role_or_environment 1 [ '1', '2', '3' ] + role_or_environment 2 { :x => '1' , :y => '2' } = { :x => '1', :y => '2' } ``` When items cannot be merged through substitution, the original data is overwritten. ### Addition The following examples show how the logic works for adding a string using a hash: ``` role_or_environment 1 { :x => '1', :y => '2' } + role_or_environment 2 { :z => '3' } = { :x => '1', :y => '2', :z => '3' } ``` For adding a string using an array: ``` role_or_environment 1 [ '1', '2' ] + role_or_environment 2 [ '3' ] = [ '1', '2', '3' ] ``` For adding a string using a multi-level hash: ``` role_or_environment 1 { :x => { :y => '2' } } + role_or_environment 2 { :x => { :z => '3' } } = { :x => { :y => '2', :z => '3' } } ``` For adding a string using a multi-level array: ``` role_or_environment 1 [ [ 1, 2 ] ] + role_or_environment 2 [ [ 3 ] ] = [ [ 1, 2 ], [ 3 ] ] ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/attribute_arrays/Attribute Types =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/attribute_types.md) Chef Infra Client uses six types of attributes to determine the value that is applied to a node during a Chef Infra Client run. In addition, Chef Infra Client gathers attribute values from up to five locations. The combination of attribute types and sources makes up to 15 different competing values available during a Chef Infra Client run: | Attribute Type | Description | | --- | --- | | `default` | A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. | | `force_default` | Use the `force_default` attribute to ensure that an attribute defined in a cookbook (by an attribute file or by a recipe) takes precedence over a `default` attribute set by a role or an environment. | | `normal` | A `normal` attribute is a setting that persists in the node object. A `normal` attribute has a higher attribute precedence than a `default` attribute. | | `override` | An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. | | `force_override` | Use the `force_override` attribute to ensure that an attribute defined in a cookbook (by an attribute file or by a recipe) takes precedence over an `override` attribute set by a role or an environment. | | `automatic` | An `automatic` attribute contains data that is identified by Ohai at the beginning of every Chef Infra Client run. An `automatic` attribute cannot be modified and always has the highest attribute precedence. | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/attribute_types/Cookbook Files ============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/files.md) The `files` directory in Chef Infra cookbooks stores files that are used in your cookbook with the [cookbook_file](../resources/cookbook_file/index) resource. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/files/Attribute Sources ================= Chef Infra Client evaluates attributes in the order that they are defined in the run-list, including any attributes that are in the run-list as cookbook dependencies. Attributes are provided to Chef Infra Client from the following locations: * JSON files passed via the `chef-client -j` * Nodes (collected by Ohai at the start of each Chef Infra Client run) * Attribute files (in cookbooks) * Recipes (in cookbooks) * Environments * Roles * Policyfiles Notes: * Many attributes are maintained in the chef-repo for Policyfiles, environments, roles, and cookbooks (attribute files and recipes) * Many attributes are collected by Ohai on each individual node at the start of every Chef Infra Client run * The attributes that are maintained in the chef-repo are uploaded to the Chef Infra Server from the workstation, periodically * Chef Infra Client will pull down the node object from the Chef Infra Server and then reset all the attributes except `normal`. The node object will contain the attribute data from the previous Chef Infra Client run including attributes set with JSON files via `-j`. * Chef Infra Client will update the cookbooks on the node (if required), which updates the attributes contained in attribute files and recipes * Chef Infra Client will update the role and environment data (if required) * Chef Infra Client will rebuild the attribute list and apply attribute precedence while configuring the node * Chef Infra Client pushes the node object to the Chef Infra Server at the end of a Chef Infra Client run; the updated node object on the Chef Infra Server is then indexed for search and is stored until the next Chef Infra Client run Automatic Attributes (Ohai) --------------------------- An automatic attribute is a specific detail about a node, such as an IP address, a host name, a list of loaded kernel modules, and so on. Automatic attributes are detected by Ohai and are then used by Chef Infra Client to ensure that they are handled properly during every Chef Infra Client run. The most commonly accessed automatic attributes are: | Attribute | Description | | --- | --- | | `node['platform']` | The platform on which a node is running. This attribute helps determine which providers will be used. | | `node['platform_family']` | The platform family is a Chef Infra specific grouping of similar platforms where cookbook code can often be shared. For example, `rhel` includes Red Hat Linux, Oracle Linux, CentOS, and several other platforms that are nearly identical to Red Hat Linux. | | `node['platform_version']` | The version of the platform. This attribute helps determine which providers will be used. | | `node['ipaddress']` | The IP address for a node. If the node has a default route, this is the IPV4 address for the interface. If the node does not have a default route, the value for this attribute should be `nil`. The IP address for default route is the recommended default value. | | `node['macaddress']` | The MAC address for a node, determined by the same interface that detects the `node['ipaddress']`. | | `node['fqdn']` | The fully qualified domain name for a node. This is used as the name of a node unless otherwise set. | | `node['hostname']` | The host name for the node. | | `node['domain']` | The domain for the node. | | `node['recipes']` | A list of recipes associated with a node (and part of that node's run-list). | | `node['roles']` | A list of roles associated with a node (and part of that node's run-list). | | `node['ohai_time']` | The time at which Ohai was last run. This attribute is not commonly used in recipes, but it is saved to the Chef Infra Server and can be accessed using the `knife status` subcommand. | Ohai collects a list of automatic attributes at the start of each Chef Infra Client run. This list will vary from organization to organization, by server type, and by the platform that runs those servers. All the attributes collected by Ohai are unmodifiable by Chef Infra Client. Run the `ohai` command on a system to see which automatic attributes Ohai has collected for a particular node. Attribute Files --------------- An attribute file is located in the `attributes/` sub-directory for a cookbook. When a cookbook is run against a node, the attributes contained in all attribute files are evaluated in the context of the node object. Node methods (when present) are used to set attribute values on a node. For example, the `apache2` cookbook contains an attribute file called `default.rb`, which contains the following attributes: ``` default['apache']['dir'] = '/etc/apache2' default['apache']['listen_ports'] = [ '80','443' ] ``` The use of the node object (`node`) is implicit in the previous example; the following example defines the node object itself as part of the attribute: ``` node.default['apache']['dir'] = '/etc/apache2' node.default['apache']['listen_ports'] = [ '80','443' ] ``` Another (much less common) approach is to set a value only if an attribute has no value. This can be done by using the `_unless` variants of the attribute priority methods: * `default_unless` * `normal_unless` Use the `_unless` variants carefully (and only when necessary) because when they are used, attributes applied to nodes may become out of sync with the values in the cookbooks as these cookbooks are updated. This approach can create situations where two otherwise identical nodes end up having slightly different configurations and can also be a challenge to debug. **File Methods** Use the following methods within the attributes file for a cookbook or within a recipe. These methods correspond to the attribute type of the same name: * `override` * `default` * `normal` * `_unless` **attribute?** A useful method that is related to attributes is the `attribute?` method. This method will check for the existence of an attribute, so that processing can be done in an attributes file or recipe, but only if a specific attribute exists. Using `attribute?()` in an attributes file: ``` if attribute?('ec2') # ... set stuff related to EC2 end ``` Using `attribute?()` in a recipe: ``` if node.attribute?('ec2') # ... do stuff on EC2 nodes end ``` Attributes from Recipes ----------------------- A recipe is the most fundamental configuration element within the organization. A recipe: * Is authored using Ruby, which is a programming language designed to read and behave in a predictable manner * Is mostly a collection of [resources](../resources/index), defined using patterns (resource names, attribute-value pairs, and actions); helper code is added around this using Ruby, when needed * Must define everything that is required to configure part of a system * Must be stored in a cookbook * May be included in another recipe * May use the results of a search query and read the contents of a data bag (including an encrypted data bag) * May have a dependency on one (or more) recipes * Must be added to a run-list before it can be used by Chef Infra Client * Is always executed in the same order as listed in a run-list An attribute can be defined in a cookbook (or a recipe) and then used to override the default settings on a node. When a cookbook is loaded during a Chef Infra Client run, these attributes are compared to the attributes that are already present on the node. Attributes that are defined in attribute files are first loaded according to cookbook order. For each cookbook, attributes in the `default.rb` file are loaded first, and then additional attribute files (if present) are loaded in lexical sort order. When the cookbook attributes take precedence over the default attributes, Chef Infra Client applies those new settings and values during a Chef Infra Client run on the node. Attributes from Roles --------------------- A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. An attribute can be defined in a role and then used to override the default settings on a node. When a role is applied during a Chef Infra Client run, these attributes are compared to the attributes that are already present on the node. When the role attributes take precedence over the default attributes, Chef Infra Client applies those new settings and values during a Chef Infra Client run. A role attribute can only be set to be a default attribute or an override attribute. A role attribute cannot be set to be a normal attribute. Use the `default_attribute` and `override_attribute` methods in the `.rb` attributes file or the `default_attributes` and `override_attributes` hashes in a JSON data file. Attributes from Environments ---------------------------- An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. Attributes can be defined in an environment and then used to override the default attributes in a cookbook. When an environment is applied during a Chef Infra Client run, environment attributes are compared to the attributes that are already present on the node. When the environment attributes take precedence over the default attributes, Chef Infra Client applies those new settings and values during a Chef Infra Client run. Environment attributes can be set to either `default` attribute level or an `override` attribute level. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/attribute_sources/Attribute Precedence ==================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/attribute_precedence.md) Chef Infra Client applies attributes in the following order: | Application Order (Last One Wins) | Attribute Type | Source Order | | --- | --- | --- | | 1 | ``default`` | Cookbook attribute fileRecipeEnvironmentRole | | 2 | ``force_default`` | Cookbook attribute fileRecipe | | 3 | ``normal`` | JSON file passed with ``chef-client -j``Cookbook attribute fileRecipe | | 4 | ``override`` | Cookbook attribute fileRecipeRoleEnvironment | | 5 | ``force_override`` | Cookbook attribute fileRecipe | | 6 | ``automatic`` | Identified by Ohai at the start of a Chef Infra Client Run | Note The attribute precedence order for the sources “roles” and “environments” are opposite in the `default` and `override`. The `default` order is **environment** then **role**. The `override` order is **role** then **environment** Applying the role `override` first lets you use the same role in a set of environments. Applying the environment `override` on top of the role `override` lets you define a subset of these with environment-specific settings. This is useful if you have an environment that is different within a sub-set of a role. For example, the role for an application server may exist in all environments, but one environment may use a different database server. Attribute precedence, viewed from the same perspective as the overview diagram, where the numbers in the diagram match the order of attribute precedence: ![image] Attribute precedence, when viewed as a table: ![image] Examples -------- The following examples are listed from low to high precedence. **Default attribute in /attributes/default.rb** ``` default['apache']['dir'] = '/etc/apache2' ``` **Default attribute in node object in recipe** ``` node.default['apache']['dir'] = '/etc/apache2' ``` **Default attribute in /environments/environment_name.rb** ``` default_attributes({ 'apache' => {'dir' => '/etc/apache2'}}) ``` **Default attribute in /roles/role_name.rb** ``` default_attributes({ 'apache' => {'dir' => '/etc/apache2'}}) ``` **Normal attribute set as a cookbook attribute** ``` normal['apache']['dir'] = '/etc/apache2' ``` **Normal attribute set in a recipe** ``` node.normal['apache']['dir'] = '/etc/apache2' ``` **Override attribute in /attributes/default.rb** ``` override['apache']['dir'] = '/etc/apache2' ``` **Override attribute in /roles/role_name.rb** ``` override_attributes({ 'apache' => {'dir' => '/etc/apache2'}}) ``` **Override attribute in /environments/environment_name.rb** ``` override_attributes({ 'apache' => {'dir' => '/etc/apache2'}}) ``` **Override attribute in a node object (from a recipe)** ``` node.override['apache']['dir'] = '/etc/apache2' ``` **Ensure that a default attribute has precedence over other attributes** When a default attribute is set like this: ``` default['attribute'] = 'value' ``` any value set by a role or an environment will replace it. To prevent this value from being replaced, use the `force_default` attribute precedence: ``` force_default['attribute'] = 'I will crush you, role or environment attribute' ``` or: ``` default!['attribute'] = "The '!' means I win!" ``` **Ensure that an override attribute has precedence over other attributes** When an override attribute is set like this: ``` override['attribute'] = 'value' ``` any value set by a role or an environment will replace it. To prevent this value from being replaced, use the `force_override` attribute precedence: ``` force_override['attribute'] = 'I will crush you, role or environment attribute' ``` or: ``` override!['attribute'] = "The '!' means I win!" ``` Change Attributes ----------------- Attribute precedence levels may be: * Removed for a specific, named attribute precedence level. * Removed for all attribute precedence levels. * Fully assigned attributes. ### Remove Precedence Level A specific attribute precedence level for default, normal, and override attributes may be removed by using one of the following syntax patterns. For default attributes: * `node.rm_default('foo', 'bar')` For normal attributes: * `node.rm_normal('foo', 'bar')` For override attributes: * `node.rm_override('foo', 'bar')` These patterns return the computed value of the key being deleted for the specified precedence level. #### Examples The following examples show how to remove a specific, named attribute precedence level. **Delete a default value when only default values exist** Given the following code structure under `'foo'`: ``` node.default['foo'] = { 'bar' => { 'baz' => 52, 'thing' => 'stuff', }, 'bat' => { 'things' => [5, 6], }, } ``` And some role attributes: ``` # Please don't ever do this in real code :) node.role_default['foo']['bar']['thing'] = 'otherstuff' ``` And a force attribute: ``` node.force_default['foo']['bar']['thing'] = 'allthestuff' ``` When the default attribute precedence `node['foo']['bar']` is removed: ``` node.rm_default('foo', 'bar') #=> {'baz' => 52, 'thing' => 'allthestuff'} ``` What is left under `'foo'` is only `'bat'`: ``` node.attributes.combined_default['foo'] #=> {'bat' => { 'things' => [5,6] } } ``` **Delete default without touching higher precedence attributes** Given the following code structure: ``` node.default['foo'] = { 'bar' => { 'baz' => 52, 'thing' => 'stuff', }, 'bat' => { 'things' => [5, 6], }, } ``` And some role attributes: ``` # Please don't ever do this in real code :) node.role_default['foo']['bar']['thing'] = 'otherstuff' ``` And a force attribute: ``` node.force_default['foo']['bar']['thing'] = 'allthestuff' ``` And also some override attributes: ``` node.override['foo']['bar']['baz'] = 99 ``` Same delete as before: ``` node.rm_default('foo', 'bar') #=> { 'baz' => 52, 'thing' => 'allthestuff' } ``` The other attribute precedence levels are unaffected: ``` node.attributes.combined_override['foo'] #=> { 'bar' => {'baz' => 99} } node['foo'] #=> { 'bar' => {'baz' => 99}, 'bat' => { 'things' => [5,6] } ``` **Delete override without touching lower precedence attributes** Given the following code structure, which has an override attribute: ``` node.override['foo'] = { 'bar' => { 'baz' => 52, 'thing' => 'stuff', }, 'bat' => { 'things' => [5, 6], }, } ``` with a single default value: ``` node.default['foo']['bar']['baz'] = 11 ``` and a force at each attribute precedence: ``` node.force_default['foo']['bar']['baz'] = 55 node.force_override['foo']['bar']['baz'] = 99 ``` Delete the override: ``` node.rm_override('foo', 'bar') #=> { 'baz' => 99, 'thing' => 'stuff' } ``` The other attribute precedence levels are unaffected: ``` node.attributes.combined_default['foo'] #=> { 'bar' => {'baz' => 55} } ``` **Non-existent key deletes return nil** ``` node.rm_default("no", "such", "thing") #=> nil ``` ### Remove All Levels All attribute precedence levels may be removed by using the following syntax pattern: * `node.rm('foo', 'bar')` Note Using `node['foo'].delete('bar')` will throw an exception that points to the new API. #### Examples The following examples show how to remove all attribute precedence levels. **Delete all attribute precedence levels** Given the following code structure: ``` node.default['foo'] = { 'bar' => { 'baz' => 52, 'thing' => 'stuff', }, 'bat' => { 'things' => [5, 6], }, } ``` With override attributes: ``` node.override['foo']['bar']['baz'] = 999 ``` Removing the `'bar'` key returns the computed value: ``` node.rm('foo', 'bar') #=> {'baz' => 999, 'thing' => 'stuff'} ``` Looking at `'foo'`, all that’s left is the `'bat'` entry: ``` node['foo'] #=> {'bat' => { 'things' => [5,6] } } ``` **Non-existent key deletes return nil** ``` node.rm_default("no", "such", "thing") #=> nil ``` ### Full Assignment Use `!` to clear out the key for the named attribute precedence level, and then complete the write by using one of the following syntax patterns: * `node.default!['foo']['bar'] = {...}` * `node.force_default!['foo']['bar'] = {...}` * `node.normal!['foo']['bar'] = {...}` * `node.override!['foo']['bar'] = {...}` * `node.force_override!['foo']['bar'] = {...}` #### Examples The following examples show how to remove all attribute precedence levels. **Just one component** Given the following code structure: ``` node.default['foo']['bar'] = {'a' => 'b'} node.default!['foo']['bar'] = {'c' => 'd'} ``` The `'!'` caused the entire ‘bar’ key to be overwritten: ``` node['foo'] #=> {'bar' => {'c' => 'd'} ``` **Multiple components; one “after”** Given the following code structure: ``` node.default['foo']['bar'] = {'a' => 'b'} # Please don't ever do this in real code :) node.role_default['foo']['bar'] = {'c' => 'd'} node.default!['foo']['bar'] = {'d' => 'e'} ``` The `'!'` write overwrote the “cookbook-default” value of `'bar'`, but since role data is later in the resolution list, it was unaffected: ``` node['foo'] #=> {'bar' => {'c' => 'd', 'd' => 'e'} ``` **Multiple components; all “before”** Given the following code structure: ``` node.default['foo']['bar'] = {'a' => 'b'} # Please don't ever do this in real code :) node.role_default['foo']['bar'] = {'c' => 'd'} node.force_default!['foo']['bar'] = {'d' => 'e'} ``` With `force_default!` there is no other data under `'bar'`: ``` node['foo'] #=> {'bar' => {'d' => 'e'} ``` **Multiple precedence levels** Given the following code structure: ``` node.default['foo'] = { 'bar' => { 'baz' => 52, 'thing' => 'stuff', }, 'bat' => { 'things' => [5, 6], }, } ``` And some attributes: ``` # Please don't ever do this in real code :) node.role_default['foo']['bar']['baz'] = 55 node.force_default['foo']['bar']['baz'] = 66 ``` And other precedence levels: ``` node.normal['foo']['bar']['baz'] = 88 node.override['foo']['bar']['baz'] = 99 ``` With a full assignment: ``` node.default!['foo']['bar'] = {} ``` Role default and force default are left in default, plus other precedence levels: ``` node.attributes.combined_default['foo'] #=> {'bar' => {'baz' => 66}, 'bat'=>{'things'=>[5, 6]}} node.attributes.normal['foo'] #=> {'bar' => {'baz' => 88}} node.attributes.combined_override['foo'] #=> {'bar' => {'baz' => 99}} node['foo']['bar'] #=> {'baz' => 99} ``` If `force_default!` is written: ``` node.force_default!['foo']['bar'] = {} ``` the difference is: ``` node.attributes.combined_default['foo'] #=> {'bat'=>{'things'=>[5, 6]}, 'bar' => {}} node.attributes.normal['foo'] #=> {'bar' => {'baz' => 88}} node.attributes.combined_override['foo'] #=> {'bar' => {'baz' => 99}} node['foo']['bar'] #=> {'baz' => 99} ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/attribute_precedence/About Libraries =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/libraries.md) A library allows arbitrary Ruby code to be included in a cookbook. The most common use for libraries is to write helpers that are used throughout recipes and custom resources. A library file is a Ruby file that is located within a cookbook’s `/libraries` directory. Because a library is built using Ruby, anything that can be done with Ruby can be done in a library file, including advanced functionality such as extending built-in Chef classes. Use a library to: * Connect to a database * Fetch secrets from a cloud provider * Talk to an LDAP provider * Do anything that can be done with Ruby Syntax ------ The syntax for a library varies because library files are created using Ruby and are designed to handle custom situations. See the Examples section below for samples. Template Helper Modules ----------------------- A template helper module can be defined in a library. This is useful when extensions need to be reused across recipes or to make it easier to manage code that would otherwise be defined inline on a per-recipe basis. ``` template '/path/to/template.erb' do helpers(MyHelperModule) end ``` Examples -------- The following examples show how to use cookbook libraries. ### Create a Namespace A database can contain a list of virtual hosts that are used by customers. A custom namespace could be created that looks something like: ``` # Sample provided by "Arjuna (fujin)". Thank you! require 'sequel' class Chef::Recipe::ISP # We can call this with ISP.vhosts def self.vhosts v = [] @db = Sequel.mysql( 'web', user: 'example', password: 'example_pw', host: 'dbserver.example.com' ) @db[ "SELECT virtualhost.domainname, usertable.userid, usertable.uid, usertable.gid, usertable.homedir FROM usertable, virtualhost WHERE usertable.userid = virtualhost.user_name" ].all do |query| vhost_data = { servername: query[:domainname], documentroot: query[:homedir], uid: query[:uid], gid: query[:gid], } v.push(vhost_data) end Chef::Log.debug('About to provision #{v.length} vhosts') v end end ``` After the custom namespace is created, it could then be used in a recipe, like this: ``` ISP.vhosts.each do |vhost| directory vhost[:documentroot] do owner vhost[:uid] group vhost[:gid] mode '0755' action :create end directory "#{vhost[:documentroot]}/#{vhost[:domainname]}" do owner vhost[:uid] group vhost[:gid] mode '0755' action :create end end ``` ### Extend a Recipe A customer record is stored in an attribute file that looks like this: ``` mycompany_customers({ bob: { homedir: '/home/bob', webdir: '/home/bob/web', }, } ) ``` A simple recipe may contain something like this: ``` directory node["mycompany_customers"]["bob"]["webdir"] do owner 'bob' group 'bob' action :create end ``` Or a less verbose version of the same simple recipe: ``` directory customer(:bob)[:webdir] do owner 'bob' group 'bob' action :create end ``` A simple library could be created that extends `Chef::Recipe::`, like this: ``` class Chef class Recipe # A shortcut to a customer def customer(name) node["mycompany_customers"][name] end end end ``` ### Loop Over a Record A customer record is stored in an attribute file that looks like this: ``` mycompany_customers({ bob: { homedir: '/home/bob', webdir: '/home/bob/web', }, } ) ``` If there are many customer records in an environment, a simple recipe can be used to loop over every customer, like this: ``` all_customers do |name, info| directory info[:webdir] do owner name group name action :create end end ``` A simple library could be created that extends `Chef::Recipe::`, like this: ``` class Chef class Recipe def all_customers(&block) node["mycompany_customers"].each do |name, info| block.call(name, info) end end end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/libraries/About the Chef Infra Language ============================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/_index.md) The Chef Infra Language is a comprehensive systems configuration language with resources and helpers for configuring operating systems. The language is primarily used in Chef Infra recipes and custom resources to tell the Chef Infra Client what action(s) to take to configure a system. The Chef Infra Language provides resources for system-level components such as packages, users, or firewalls, and it also includes helpers to allow you to make configuration decisions based on operating systems, clouds, virtualization hypervisors, and more. The Chef Infra Language is based on Ruby, allowing you to utilize the power of Ruby when the built-in language doesn’t meet your needs out of the box. If you’d like to learn more about extending your Chef Infra code by using Ruby see our [Ruby Guide](../ruby/index) for further information on Ruby functionality. Resources --------- Resources are the cornerstone of the Chef Infra Language. Resources define the desired state of an object on a system. A resource can be as simple as a directory or as complex or a complete security policy. Chef Infra Client ships with over 150 resources for configuring components such as packages, files, directories, or firewalls. For more information on resources in Chef Infra Client including a complete list of those included out of the box see [Resources](../resources). Helpers Methods --------------- The Chef Infra Language provides support for using attributes, data bags (and encrypted data), and search results in a recipe, as well as four helper methods that can be used to check for a node’s platform from the recipe to ensure that specific actions are taken for specific platforms. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/Chef Infra Language: Checking Clouds ==================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/checking_clouds.md) Chef Infra Client 15.8 and later include a number of helper methods for checking if a node is running in a public or private cloud. cloud? ------ Determine if the current node is running a known public or private cloud. ec2? ---- Determine if the current node is running in AWS EC2. gce? ---- Determine if the current node is running in Google Compute Engine (GCE) rackspace? ---------- Determine if the current node is running in Rackspace. eucalyptus? ----------- Determine if the current node is running in Eucalyptus. linode? ------- Determine if the current node is running in Linode. openstack? ---------- Determine if the current node is running in OpenStack. azure? ------ Determine if the current node is running in Microsoft Azure. digital_ocean? --------------- Determine if the current node is running in DigitalOcean. softlayer? ---------- Determine if the current node is running in SoftLayer (IBM Cloud). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/checking_clouds/About Templates =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/templates.md) A cookbook template is an Embedded Ruby (ERB) template that is used to dynamically generate static text files. Templates may contain Ruby expressions and statements, and are a great way to manage configuration files. Use the **template** resource to add cookbook templates to recipes; place the corresponding Embedded Ruby (ERB) template file in a cookbook’s `/templates` directory. The `templates` directory does not exist by default in a cookbook. Generate the `templates` directory and a template file from the `chef-repo/cookbooks` directory with the command: ``` chef generate template PATH_TO_COOKBOOK TEMPLATE_NAME ``` For example, this command generates a `httpd` template in the `custom_web` cookbook: ``` chef generate template cookbooks/custom_web httpd ``` The `custom_web` cookbook directory with a template has the structure: ``` ├ cookbooks ├ custom_web ├ .delivery | └ project.toml ├ recipes | └ default.rb ├ templates | └ http.erb ├ test | └ integration | | └ default | | | └ default_test.rb ├ .gitignore ├ CHANGELOG.md ├ chefignore ├ kitchen.yml ├ LICENSE ├ metadata.rb ├ Policyfile.rb └ README.md ``` Requirements ------------ To use a template, two things must happen: 1. A template resource must be added to a recipe 2. An Embedded Ruby (ERB) template must be added to a cookbook For example, the following template file and template resource settings can be used to manage a configuration file named `/etc/sudoers`. Within a cookbook that uses sudo, the following resource could be added to `/recipes/default.rb`: ``` template '/etc/sudoers' do source 'sudoers.erb' mode '0440' owner 'root' group 'root' variables(sudoers_groups: node['authorization']['sudo']['groups'], sudoers_users: node['authorization']['sudo']['users']) end ``` And then create a template called `sudoers.erb` and save it to `templates/default/sudoers.erb`: ``` # # /etc/sudoers # # Generated by Chef for <%= node['fqdn'] %> # Defaults !lecture,tty_tickets,!fqdn # User privilege specification root ALL=(ALL) ALL <% @sudoers_users.each do |user| -%> <%= user %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% end -%> # Members of the sysadmin group may gain root privileges %sysadmin ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% @sudoers_groups.each do |group| -%> # Members of the group '<%= group %>' may gain root privileges <%= group %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% end -%``` And then set the default attributes in `attributes/default.rb`: ``` default['authorization']['sudo']['groups'] = %w(sysadmin wheel admin) default['authorization']['sudo']['users'] = %w(jerry greg) ``` Variables --------- An Embedded Ruby (ERB) template allows Ruby code to be embedded inside a text file within specially formatted tags. Ruby code can be embedded using expressions and statements. An expression is delimited by `<%=` and `%>`. For example: ``` <%= "my name is #{$ruby}" %``` A statement is delimited by a modifier, such as `if`, `elsif`, and `else`. For example: ``` if false # this won't happen elsif nil # this won't either end ``` Using a Ruby expression is the most common approach for defining template variables because this is how all variables that are sent to a template are referenced. Whenever a template needs to use an `each`, `if`, or `end`, use a Ruby statement. When a template is rendered, Ruby expressions and statements are evaluated by Chef Infra Client. The variables listed in the **template** resource’s `variables` parameter and in the node object are evaluated. Chef Infra Client then passes these variables to the template, where they will be accessible as instance variables within the template. The node object can be accessed just as if it were part of a recipe, using the same syntax. For example, a simple template resource like this: ``` node['fqdn'] = 'latte' template '/tmp/foo' do source 'foo.erb' variables(x_men: 'are keen') end ``` And a simple Embedded Ruby (ERB) template like this: ``` The node <%= node[:fqdn] %> thinks the x-men <%= @x_men %``` Would render something like: ``` The node latte thinks the x-men are keen ``` Even though this is a very simple example, the full capabilities of Ruby can be used to tackle even the most complex and demanding template requirements. File Specificity ---------------- A cookbook is frequently designed to work across many platforms and is often required to distribute a specific template to a specific platform. A cookbook can be designed to support the distribution of templates across platforms, while ensuring that the correct template ends up on each system. The pattern for template specificity depends on two things: the lookup path and the source. The first pattern that matches is used: 1. `/host-$fqdn/$source` 2. `/$platform-$platform_version/$source` 3. `/$platform/$source` 4. `/default/$source` 5. `/$source` Note To specify a particular Windows version, use the [operating system version number](https://docs.microsoft.com/en-us/windows/win32/sysinfo/operating-system-version). For example, a template in `templates/windows-6.3` will be deployed on systems installed with Windows 8.1. Use an array with the `source` property to define an explicit lookup path. For example: ``` template '/test' do source ["#{node.chef_environment}.erb", 'default.erb'] end ``` The following example emulates the entire file specificity pattern by defining it as an explicit path: ``` template '/test' do source %W( host-#{node['fqdn']}/test.erb #{node['platform']}-#{node['platform_version']}/test.erb #{node['platform']}/test.erb default/test.erb ) end ``` A cookbook may have a `/templates` directory structure like this: ``` /templates/ windows-10 windows-6.3 windows default ``` and a resource that looks something like the following: ``` template 'C:\path\to\file\text_file.txt' do source 'text_file.txt' mode '0755' owner 'root' group 'root' end ``` This resource would be matched in the same order as the `/templates` directory structure. For a node named `host-node-desktop` that is running Windows 8.1, the second item would be the matching item and the location: ``` /templates windows-10/text_file.txt windows-6.3/text_file.txt windows/text_file.txt default/text_file.txt ``` Host Notation ------------- The naming of folders within cookbook directories must literally match the host notation used for template specificity matching. For example, if a host is named `foo.example.com`, then the folder must be named `host-foo.example.com`. Transfer Frequency ------------------ The Chef Infra Client caches a template when it is first requested. On each subsequent request for that template, the Chef Infra Client compares that request to the template located on the Chef Infra Server. If the templates are the same, no transfer occurs. Partial Templates ----------------- A template can be built in a way that allows it to contain references to one (or more) smaller template files. (These smaller template files are also referred to as partials.) A partial can be referenced from a template file in one of the following ways: * By using the `render` method in the template file * By using the **template** resource and the `variables` property. ### variables Attribute The `variables` property of the **template** resource can be used to reference a partial template file by using a Hash. For example: ``` template '/file/name.txt' do variables partials: { 'partial_name_1.txt.erb' => 'message', 'partial_name_2.txt.erb' => 'message', 'partial_name_3.txt.erb' => 'message', } end ``` where each of the partial template files can then be combined using normal Ruby template patterns within a template file, such as: ``` <% @partials.each do |partial, message| %> Here is <%= partial %> <%= render partial, :variables => {:message => message} %> <% end %``` ### render Method Use the `render` method in a template to reference a partial template file: ``` <%= render 'partial_name.txt.erb', :option => {} %``` where `partial_name` is the name of the partial template file and `:option` is one (or more) of the following: | Option | Description | | --- | --- | | `:cookbook` | By default, a partial template file is assumed to be located in the cookbook that contains the top-level template. Use this option to specify the path to a different cookbook | | `:local` | Indicates that the name of the partial template file should be interpreted as a path to a file in the local file system or looked up in a cookbook using the normal rules for template files. Set to `true` to interpret as a path to a file in the local file system and to `false` to use the normal rules for template files | | `:source` | By default, a partial template file is identified by its file name. Use this option to specify a different name or a local path to use (instead of the name of the partial template file) | | `:variables` | A hash of `variable_name => value` that will be made available to the partial template file. When this option is used, any variables that are defined in the top-level template that are required by the partial template file must have them defined explicitly using this option | For example: ``` <%= render 'simple.txt.erb', :variables => {:user => Etc.getlogin }, :local => true %``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/templates/Debug Recipes, Chef Infra Client Runs ===================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/debug.md) Elements of good approaches to building cookbooks and recipes that are reliable include: * A consistent syntax pattern when constructing recipes * Using the same patterns in Ruby * Using resources included in Chef Infra Client or community cookbooks before creating custom ones Ideally, the best way to debug a recipe is to not have to debug it in the first place. That said, the following sections discuss various approaches to debugging recipes and failed Chef Infra Client runs. Basic ----- Some simple ways to quickly identify common issues that can trigger recipe and/or Chef Infra Client run failures include: * Using an empty run-list * Using verbose logging with knife * Using logging with Chef Infra Client * Using the **log** resource in a recipe to define custom logging ### Empty Run-lists Use an empty run-list to determine if a failed Chef Infra Client run has anything to do with the recipes that are defined within that run-list. This is a quick way to discover if the underlying cause of a Chef Infra Client run failure is a configuration issue. If a failure persists even if the run-list is empty, check the following: * Configuration settings in the config.rb file * Permissions for the user to both the Chef Infra Server and to the node on which a Chef Infra Client run is to take place ### Knife Use the verbose logging that is built into knife: `-V`, `--verbose` Set for more verbose outputs. Use `-VV` for much more verbose outputs. Use `-VVV` for maximum verbosity, which may provide more information than is actually helpful. Note Plugins do not always support verbose logging. ### Chef Infra Client Use the verbose logging that is built into Chef Infra Client: `-l LEVEL`, `--log_level LEVEL` The level of logging to be stored in a log file. Possible levels: `auto` (default), `debug`, `error`, `fatal`, `info`, `trace`, or `warn`. Default value: `warn` (when a terminal is available) or `info` (when a terminal is not available). `-L LOGLOCATION`, `--logfile c` The location of the log file. This is recommended when starting any executable as a daemon. Default value: `STDOUT`. ### log Resource Use the **log** resource to create log entries. The **log** resource behaves like any other resource: built into the resource collection during the compile phase, and then run during the execution phase. (To create a log entry that is not built into the resource collection, use `Chef::Log` instead of the **log** resource.) Note By default, every log resource that executes will count as an updated resource in the updated resource count at the end of a Chef run. You can disable this behavior by adding `count_log_resource_updates false` to your Chef `client.rb` configuration file. New in 12.0, `-o RUN_LIST_ITEM`. Changed in 12.0 `-f` no longer allows unforked intervals, `-i SECONDS` is applied before a Chef Infra Client run. #### Syntax A **log** resource block adds messages to the log file based on events that occur during a Chef Infra Client run: ``` log 'message' do message 'A message add to the log.' level :info end ``` The full syntax for all of the properties that are available to the **log** resource is: ``` log 'name' do level Symbol # default value: :info message String # default value: 'name' unless specified action Symbol # defaults to :write if not specified end ``` where: * `log` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `level` and `message` are the properties available to this resource. #### Actions The log resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:write` Default. Write to log. #### Properties The log resource has the following properties: `level` **Ruby Type:** Symbol | **Default Value:** `:info` The logging level for displaying this message. Options (in order of priority): `:debug`, `:info`, `:warn`, `:error`, and `:fatal`. `message` **Ruby Type:** String | **Default Value:** `The resource block's name` The message to be added to a log file. Default value: the `name` of the resource block. See “Syntax” section above for more information. #### Examples The following examples demonstrate various approaches for using resources in recipes: ##### Specify a log entry ``` log 'a string to log' ``` ##### Set debug logging level ``` log 'a debug string' do level :debug end ``` ##### Create log entry when the contents of a data bag are used ``` log 'a debug string' do level :debug end ``` ##### Add a message to a log file ``` log 'message' do message 'This is the message that will be added to the log.' level :info end ``` Advanced -------- Some more complex ways to debug issues with a Chef Infra Client run include: * Using the **chef_handler** resource * Using the chef-shell and the **breakpoint** resource to add breakpoints to recipes, and to then step through the recipes using the breakpoints * Using the `debug_value` method from chef-shell to identify the location(s) from which attribute values are being set * Using the `ignore_failure` method in a recipe to force Chef Infra Client to move past an error to see what else is going on in the recipe, outside of a known failure * Using chef-solo to run targeted Chef Infra Client runs for specific scenarios ### chef_handler Use a handler to identify situations that arise during a Chef Infra Client run, and then tell Chef Infra Client how to handle these situations when they occur. There are three types of handlers: | Handler | Description | | --- | --- | | exception | An exception handler is used to identify situations that have caused a Chef Infra Client run to fail. An exception handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the **chef_handler** resource to a node's run-list. An exception handler runs when the `failed?` property for the `run_status` object returns `true`. | | report | A report handler is used when a Chef Infra Client run succeeds and reports back on certain details about that Chef Infra Client run. A report handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the **chef_handler** resource to a node's run-list. A report handler runs when the `success?` property for the `run_status` object returns `true`. | | start | A start handler is used to run events at the beginning of a Chef Infra Client run. A start handler can be loaded at the start of a Chef Infra Client run by adding the start handler to the `start_handlers` setting in the client.rb file or by installing the gem that contains the start handler by using the **chef_gem** resource in a recipe in the **chef-client** cookbook. (A start handler may not be loaded using the `chef_handler` resource.) | Read more [about exception, report, and start handlers](../handlers/index). ### chef-shell chef-shell is a recipe debugging tool that allows the use of breakpoints within recipes. chef-shell runs as an Interactive Ruby (IRb) session. chef-shell supports both recipe and attribute file syntax, as well as interactive debugging features. chef-shell is tool that is run using an Interactive Ruby (IRb) session. chef-shell currently supports recipe and attribute file syntax, as well as interactive debugging features. chef-shell has three run modes: | Mode | Description | | --- | --- | | Standalone | Default. No cookbooks are loaded, and the run-list is empty. | | Solo | chef-shell acts as a Chef Solo Client. It attempts to load the chef-solo configuration file at `~/.chef/config.rb` and any JSON attributes passed. If the JSON attributes set a run-list, it will be honored. Cookbooks will be loaded in the same way that chef-solo loads them. chef-solo mode is activated with the `-s` or `--solo` command line option, and JSON attributes are specified in the same way as for chef-solo, with `-j /path/to/chef-solo.json`. | | Client | chef-shell acts as a Chef Infra Client. During startup, it reads the Chef Infra Client configuration file from `~/.chef/client.rb` and contacts the Chef Infra Server to get the node's run_list, attributes, and cookbooks. Chef Infra Client mode is activated with the `-z` or `--client` options. You can also specify the configuration file with `-c CONFIG` and the server URL with `-S SERVER_URL`. | #### Configure chef-shell determines which configuration file to load based on the following: 1. If a configuration file is specified using the `-c` option, chef-shell will use the specified configuration file 2. If a NAMED_CONF is given, chef-shell will load ~/.chef/NAMED_CONF/chef_shell.rb 3. If no NAMED_CONF is given chef-shell will load ~/.chef/chef_shell.rb if it exists 4. If no chef_shell.rb can be found, chef-shell falls back to load: * /etc/chef/client.rb if -z option is given. * /etc/chef/solo.rb if –solo-legacy-mode option is given. * .chef/config.rb if -s option is given. * .chef/knife.rb if -s option is given. #### chef-shell.rb The chef-shell.rb file can be used to configure chef-shell in the same way as the client.rb file is used to configure Chef Infra Client. For example, to configure chef-shell to authenticate to the Chef Infra Server, copy the `node_name`, `client_key`, and `chef_server_url` settings from the config.rb file: ``` node_name 'your-knife-clientname' client_key File.expand_path('~/.chef/my-client.pem') chef_server_url 'https://api.opscode.com/organizations/myorg' ``` and then add them to the chef-shell.rb file. Other configuration possibilities include disabling Ohai plugins (which will speed up the chef-shell boot process) or including arbitrary Ruby code in the chef-shell.rb file. #### Run as a Chef Infra Client By default, chef-shell loads in standalone mode and does not connect to the Chef Infra Server. The chef-shell can be run as a Chef Infra Client to verify functionality that is only available when Chef Infra Client connects to the Chef Infra Server, such as search functionality or accessing data stored in data bags. chef-shell can use the same credentials as knife when connecting to a Chef Infra Server. Make sure that the settings in chef-shell.rb are the same as those in config.rb, and then use the `-z` option as part of the command. For example: ``` chef-shell -z ``` #### Manage When chef-shell is configured to access a Chef Infra Server, chef-shell can list, show, search for and edit cookbooks, clients, nodes, roles, environments, policyfiles, and data bags. The syntax for managing objects on the Chef Infra Server is as follows: ``` chef-shell -z named_configuration ``` Where: * `named_configuration` is an existing configuration file in `~/.chef/named_configuration/chef_shell.rb`, such as `production`, `staging`, or `test`. Once in chef-shell, commands can be run against objects as follows: ``` chef (preprod) > items.command ``` Where: * `items` is the type of item to search for: `cookbooks`, `clients`, `nodes`, `roles`, `environments` or a data bag. * `command` is the command: `list`, `show`, `find`, or `edit`. For example, to list all of the nodes in a configuration named “preprod”, enter: ``` chef (preprod) > nodes.list ``` Which will return something similar to: ``` => [node[i-f09a939b], node[i-049a936f], node[i-eaaaa581], node[i-9154b1fb], node[i-6a213101], node[i-c2687aa9], node[i-7abeaa11], node[i-4eb8ac25], node[i-9a2030f1], node[i-a06875cb], node[i-145f457f], node[i-e032398b], node[i-dc8c98b7], node[i-6afdf401], node[i-f49b119c], node[i-5abfab31], node[i-78b8ac13], node[i-d99678b3], node[i-02322269], node[i-feb4a695], node[i-9e2232f5], node[i-6e213105], node[i-cdde3ba7], node[i-e8bfb083], node[i-743c2c1f], node[i-2eaca345], node[i-aa7f74c1], node[i-72fdf419], node[i-140e1e7f], node[i-f9d43193], node[i-bd2dc8d7], node[i-8e7f70e5], node[i-78f2e213], node[i-962232fd], node[i-4c322227], node[i-922232f9], node[i-c02728ab], node[i-f06c7b9b]] ``` The `list` command can take a code block, which will applied (but not saved), to each object that is returned from the server. For example: ``` chef (preprod) > nodes.list {|n| puts "#{n.name}: #{n.run_list}" } ``` will return something similar to: ``` => i-f09a939b: role[lb], role[preprod], recipe[aws] i-049a936f: role[lb], role[preprod], recipe[aws] i-9154b1fb: recipe[erlang], role[base], role[couchdb], role[preprod], i-6a213101: role[chef], role[preprod] # more... ``` The `show` command can be used to display a specific node. For example: ``` chef (preprod) > load_balancer = nodes.show('i-f09a939b') ``` will return something similar to: ``` => node[i-f09a939b] ``` Or: ``` chef (preprod) > load_balancer.ec2.public_hostname ``` will return something similar to: ``` => "ec2-111-22-333-44.compute-1.amazonaws.com" ``` The `find` command can be used to search the Chef Infra Server from the chef-shell. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') ``` You can also format the results with a code block. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } and nil ``` will return something similar to: ``` => ["ami-f8927a91", "ami-f8927a91", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1" # and more... ``` Or: ``` chef (preprod) > amis = nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } chef (preprod) > puts amis.uniq.sort ``` will return something similar to: ``` => ami-4b4ba522 ami-a89870c1 ami-eef61587 ami-f8927a91 ``` ### breakpoint Resource chef-shell allows the current position in a run-list to be manipulated during a Chef Infra Client run. Add breakpoints to a recipe to take advantage of this functionality. Use the **breakpoint** resource to add breakpoints to recipes. Run the chef-shell in Chef Infra Client mode, and then use those breakpoints to debug recipes. Breakpoints are ignored by Chef Infra Client during an actual Chef Infra Client run. That said, breakpoints are typically used to debug recipes only when running them in a non-production environment, after which they are removed from those recipes before the parent cookbook is uploaded to the Chef Infra Server. #### Syntax A **breakpoint** resource block creates a breakpoint in a recipe: ``` breakpoint 'name' do action :break end ``` where * `:break` will tell Chef Infra Client to stop running a recipe; can only be used when Chef Infra Client is being run in chef-shell mode #### Actions The breakpoint resource has the following actions: `:break` Use to add a breakpoint to a recipe. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. #### Attributes This resource does not have any properties. #### Examples The following examples demonstrate various approaches for using resources in recipes: ##### A recipe without a breakpoint ``` yum_key node['yum']['elrepo']['key'] do url node['yum']['elrepo']['key_url'] action :add end yum_repository 'elrepo' do description 'ELRepo.org Community Enterprise Linux Extras Repository' key node['yum']['elrepo']['key'] mirrorlist node['yum']['elrepo']['url'] includepkgs node['yum']['elrepo']['includepkgs'] exclude node['yum']['elrepo']['exclude'] action :create end ``` ##### The same recipe with breakpoints ``` breakpoint "before yum_key node['yum']['repo_name']['key']" do action :break end yum_key node['yum']['repo_name']['key'] do url node['yum']['repo_name']['key_url'] action :add end breakpoint "after yum_key node['yum']['repo_name']['key']" do action :break end breakpoint "before yum_repository 'repo_name'" do action :break end yum_repository 'repo_name' do description 'description' key node['yum']['repo_name']['key'] mirrorlist node['yum']['repo_name']['url'] includepkgs node['yum']['repo_name']['includepkgs'] exclude node['yum']['repo_name']['exclude'] action :create end breakpoint "after yum_repository 'repo_name'" do action :break end ``` where the name of each breakpoint is an arbitrary string. In the previous examples, the names are used to indicate if the breakpoint is before or after a resource, and then also to specify which resource. ### Step Through Run-list To explore how using the **breakpoint** to manually step through a Chef Infra Client run, create a simple recipe in chef-shell: ``` chef > recipe_mode chef:recipe > echo off chef:recipe > file "/tmp/before-breakpoint" chef:recipe > breakpoint "foo" chef:recipe > file "/tmp/after-breakpoint" ``` and then run Chef Infra Client: ``` chef:recipe > run_chef [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:17:49 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint ``` Chef Infra Client ran the first resource before the breakpoint (`file[/tmp/before-breakpoint]`), but then stopped after execution. Chef Infra Client attempted to name the breakpoint after its position in the source file, but Chef Infra Client was confused because the resource was entered interactively. From here, chef-shell can resume the interrupted Chef Infra Client run: ``` chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:27:08 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` A quick view of the `/tmp` directory shows that the following files were created: ``` after-breakpoint before-breakpoint ``` You can rewind and step through a Chef Infra Client run: ``` chef:recipe > Chef::Log.level = :debug # debug logging won't turn on automatically in this case => :debug chef:recipe > chef_run.rewind => 0 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File => 1 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint => 2 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File => 3 ``` From the output, the rewound run-list is shown, but when the resources are executed again, they will repeat their checks for the existence of files. If they exist, Chef Infra Client will skip creating them. If the files are deleted, then: ``` chef:recipe > ls("/tmp").grep(/breakpoint/).each {|f| rm "/tmp/#{f}" } => ["after-breakpoint", "before-breakpoint"] ``` Rewind, and then resume your Chef Infra Client run to get the expected results: ``` chef:recipe > chef_run.rewind chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:48:56 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:49:20 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` ### Debug Existing Recipe chef-shell can be used to debug existing recipes. The recipe first needs to be added to a run-list for the node, so that it is cached when starting chef-shell and then used for debugging. chef-shell will report which recipes are being cached when it is started: ``` loading configuration: none (standalone session) Session type: standalone Loading.............done. Welcome to the chef-shell 15.8.23 For usage see https://docs.chef.io/chef_shell.html run `help' for help, `exit' or ^D to quit. chef (15.8.23)``` To just load one recipe from the run-list, go into the recipe and use the `include_recipe` command. For example: ``` chef > recipe_mode chef:recipe > include_recipe "getting-started" => [#< Chef::Recipe:0x10256f9e8 @cookbook_name="getting-started", ... output truncated ... ``` To load all of the recipes from a run-list, use code similar to the following: ``` node.run_list.expand(node.chef_environment).recipes.each do |r| include_recipe r end ``` After the recipes that are to be debugged have been loaded, use the `run_chef` command to run them. ### Advanced Debugging In chef-shell, it is possible to get verbose debugging using the tracing feature in Interactive Ruby (IRb). chef-shell provides a shortcut for turning tracing on and off. For example: ``` chef > tracing on tracing is on => nil chef ``` and: ``` chef > tracing off #0:(irb):2:Object:-: tracing off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:109:Shell::Extensions::ObjectCoreExtensions:>: def off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:110:Shell::Extensions::ObjectCoreExtensions:-: :off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:111:Shell::Extensions::ObjectCoreExtensions:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:272:main:>: def tracing(on_or_off) #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:273:main:-: conf.use_tracer = on_or_off.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:162:Shell::Extensions::Symbol:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:163:Shell::Extensions::Symbol:-: to_s.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:149:Shell::Extensions::String:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:150:Shell::Extensions::String:-: case self #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:154:Shell::Extensions::String:-: false #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:158:Shell::Extensions::String:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:164:Shell::Extensions::Symbol:<: end tracing is off => nil chef ``` ### debug_value Use the `debug_value` method to discover the location within the attribute precedence hierarchy from which a particular attribute (or sub-attribute) is set. This method is available when running chef-shell in Chef Infra Client mode: ``` chef-shell -z ``` For example, the following attributes exist in a cookbook. Some are defined in a role file: ``` default_attributes 'test' => { 'source' => 'role default' } override_attributes 'test' => { 'source' => 'role override' } ``` And others are defined in an attributes file: ``` default[:test][:source] = 'attributes default' normal[:test][:source] = 'attributes normal' override[:test][:source] = 'attributes override' ``` To debug the location in which the value of `node[:test][:source]` is set, use chef-shell and run a command similar to: ``` pp node.debug_value('test', 'source') ``` This will pretty-print return all of the attributes and sub-attributes as an array of arrays; `:not_present` is returned for any attribute without a value: ``` [['set_unless_enabled?', false], ['default', 'attributes default'], ['env_default', :not_present], ['role_default', 'role default'], ['force_default', :not_present], ['normal', 'attributes normal'], ['override', 'attributes override'], ['role_override', 'role override'], ['env_override', :not_present], ['force_override', :not_present], ['automatic', :not_present]] ``` where * `set_unless_enabled` indicates if the attribute collection is in `set_unless` mode; this typically returns `false` * Each attribute type is listed in order of precedence * Each attribute value shown is the value that is set for that precedence level * `:not_present` is shown for any attribute precedence level that has no attributes ### ignore_failure Method All resources share a set of common actions, attributes, and so on. Use the following attribute in a resource to help identify where an issue within a recipe may be located: | Attribute | Description | | --- | --- | | `ignore_failure` | Continue running a recipe if a resource fails for any reason. Default value: `false`. | ### chef-solo See [chef-solo (executable)](../ctl_chef_solo/index) for complete CTL documentation. chef-solo is a command that executes Chef Infra Client in a way that does not require the Chef Infra Server in order to converge cookbooks. chef-solo uses Chef Infra Client’s [Chef local mode](../ctl_chef_client#run-in-local-mode), and **does not support** the following functionality present in Chef Infra Client / server configurations: * Centralized distribution of cookbooks * A centralized API that interacts with and integrates infrastructure components * Authentication or authorization Note chef-solo can be run as a daemon. The chef-solo executable is run as a command-line tool. See [chef-solo (executable)](../ctl_chef_solo/index) for complete CTL documentation. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/debug/About Cookbook Versioning ========================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/cookbook_versioning.md) A cookbook version represents a set of functionality that is different from the cookbook on which it is based. A version may exist for many reasons, such as ensuring the correct use of a third-party component, updating a bug fix, or adding an improvement. A cookbook version is defined using syntax and operators, may be associated with environments, cookbook metadata, and/or run-lists, and may be frozen (to prevent unwanted updates from being made). A cookbook version is maintained just like a cookbook, with regard to source control, uploading it to the Chef Infra Server, and how Chef Infra Client applies that cookbook when configuring nodes. Syntax ------ A cookbook version always takes the form x.y.z, where x, y, and z are decimal numbers that are used to represent major (x), minor (y), and patch (z) versions. A two-part version (x.y) is also allowed. Alphanumeric version numbers (1.2.a3) and version numbers with more than three parts (1.2.3.4) are not allowed. Constraints ----------- A version constraint is a string that combines the cookbook version syntax with an operator, in the following format: ``` operator cookbook_version_syntax ``` Note Single digit cookbook versions are not allowed. Cookbook versions must specify at least the major and minor version. For example, use `1.0` or `1.0.1`; do not use `1`. The following operators may be used: | Operator | Description | | --- | --- | | `=` | equal to | | `>` | greater than | | `<` | less than | | `>=` | greater than or equal to; also known as "optimistically greater than", or "optimistic" | | `<=` | less than or equal to | | `~>` | approximately greater than; also known as "pessimistically greater than", or "pessimistic" | For example, a version constraint for “equals version 1.0.7” is expressed like this: ``` = 1.0.7 ``` A version constraint for “greater than version 1.0.2” is expressed like this: ``` > 1.0.2 ``` An optimistic version constraint is one that looks for versions greater than or equal to the specified version. For example: ``` >= 2.6.5 ``` will match cookbooks greater than or equal to 2.6.5, such as 2.6.5, 2.6.7 or 3.1.1. A pessimistic version constraint is one that will find the upper limit version number within the range specified by the minor version number or patch version number. For example, a pessimistic version constraint for minor version numbers: ``` ~> 2.6 ``` will match cookbooks that are greater than or equal to version 2.6, but less than version 3.0. Or, a pessimistic version constraint for patch version numbers: ``` ~> 2.6.5 ``` will match cookbooks that are greater than or equal to version 2.6.5, but less than version 2.7.0. Or, a pessimistic version constraint that matches cookbooks less than a version number: ``` < 2.3.4 ``` or will match cookbooks less than or equal to a specific version number: ``` <= 2.6.5 ``` Metadata -------- Every cookbook requires a small amount of metadata. The contents of the `metadata.rb` file provides information that helps Chef Infra Client and Server correctly deploy cookbooks to each node. A `metadata.rb` file is: * Located at the top level of a cookbook’s directory structure. * Compiled whenever a cookbook is uploaded to the Chef Infra Server or when the `knife cookbook metadata` subcommand is run, and then stored as JSON data. * Created automatically by knife whenever the `knife cookbook create` subcommand is run. * Edited using a text editor, and then re-uploaded to the Chef Infra Server as part of a cookbook upload. Versions and version constraints can be specified in a cookbook’s metadata.rb file by using the following functions. Each function accepts a name and an optional version constraint; if a version constraint is not provided, `>= 0.0.0` is used as the default. | Function | Description | | --- | --- | | `depends` | Show that a cookbook has a dependency on another cookbook. Use a version constraint to define dependencies for cookbook versions: `<` (less than), `<=` (less than or equal to), `=` (equal to), `>=` (greater than or equal to; also known as "optimistically greater than", or "optimistic"), `~>` (approximately greater than; also known as "pessimistically greater than", or "pessimistic"), or `>` (greater than). This field requires that a cookbook with a matching name and version exists on the Chef Infra Server. When the match exists, the Chef Infra Server includes the dependency as part of the set of cookbooks that are sent to the node when Chef Infra Client runs. It is very important that the `depends` field contain accurate data. If a dependency statement is inaccurate, Chef Infra Client may not be able to complete the configuration of the system. For example: ``` depends 'opscode-base' ``` or: ``` depends 'opscode-github', '> 1.0.0' ``` or: ``` depends 'runit', '~> 1.2.3' ``` | | `provides` | Add a recipe, definition, or resource that is provided by this cookbook, should the auto-populated list be insufficient. | | `supports` | Show that a cookbook has a supported platform. Use a version constraint to define dependencies for platform versions: `<` (less than), `<=` (less than or equal to), `=` (equal to), `>=` (greater than or equal to), `~>` (approximately greater than), or `>` (greater than). To specify more than one platform, use more than one `supports` field, once for each platform. | Environments ------------ An environment can use version constraints to specify a list of allowed cookbook versions by specifying the cookbook’s name, along with the version constraint. For example: ``` cookbook 'apache2', '~> 1.2.3' ``` Or: ``` cookbook 'runit', '= 4.2.0' ``` If a cookbook is not explicitly given a version constraint the environment will assume the cookbook has no version constraint and will use any version of that cookbook with any node in the environment. Freeze Versions --------------- A cookbook version can be frozen, which will prevent updates from being made to that version of a cookbook. (A user can always upload a new version of a cookbook.) Using cookbook versions that are frozen within environments is a reliable way to keep a production environment safe from accidental updates while testing changes that are made to a development infrastructure. For example, to freeze a cookbook version using knife, enter: ``` knife cookbook upload redis --freeze ``` To return: ``` Uploading redis... Upload completed ``` Once a cookbook version is frozen, only by using the `--force` option can an update be made. For example: ``` knife cookbook upload redis --force ``` Without the `--force` option specified, an error will be returned similar to: ``` Version 0.0.0 of cookbook redis is frozen. Use --force to override ``` Version Source Control ---------------------- There are two strategies to consider when using version control as part of the cookbook management process: * Use maximum version control when it is important to keep every bit of data within version control * Use branch tracking when cookbooks are being managed in separate environments using git branches and the versioning policy information is already stored in a cookbook’s metadata. ### Branch Tracking Using a branch tracking strategy requires that a branch for each environment exists in the source control and that each cookbook’s versioning policy is tracked at the branch level. This approach is relatively simple and lightweight: for development environments that track the latest cookbooks, just bump the version before a cookbook is uploaded for testing. For any cookbooks that require higher levels of version control, knife allows cookbooks to be uploaded to specific environments and for cookbooks to be frozen (which prevents others from being able to make changes to that cookbook). The typical workflow with a branch tracking version control strategy includes: 1. Bumping the version number as appropriate. 2. Making changes to a cookbook. 3. Uploading and testing a cookbook. 4. Moving a tested cookbook to production. For example, to bump a version number, first make changes to the cookbook, and then upload and test it. Repeat this process as required, and then upload it using a knife command similar to: ``` knife cookbook upload my-app ``` When the cookbook is finished, move those changes to the production environment and use the `--freeze` option to prevent others from making further changes: ``` knife cookbook upload my-app -E production --freeze ``` ### Maximum Versions Using a maximum version control strategy is required when everything needs to be tracked in source control. This approach is very similar to a branch tracking strategy while the cookbook is in development and being tested, but is more complicated and time-consuming (and requires file-level editing for environment data) in order to get the cookbook deployed to a production environment. The typical workflow with a maximum version control strategy includes: 1. Bumping the version number as appropriate. 2. Making changes to a cookbook. 3. Uploading and testing a cookbook. 4. Moving a tested cookbook to production. For example, to bump a version number, first make changes to the cookbook, and then upload and test it. Repeat this process as required, and then upload it using a knife command similar to: ``` knife cookbook upload my-app ``` When the cookbook is finished, move those changes to the production environment and use the `--freeze` option to prevent others from making further changes: ``` knife cookbook upload my-app -E production --freeze ``` Then modify the environment so that it prefers the newly uploaded version: ``` (vim|emacs|mate|ed) YOUR_REPO/environments/production.rb ``` Upload the updated environment: ``` knife environment from file production.rb ``` And then deploy the new cookbook version. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/cookbook_versioning/Chef Infra Language: Checking Architectures =========================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/checking_architectures.md) Chef Infra Client 15.5 and later include a number of helper methods for checking the processor architecture of systems. These methods can be used in attribute files, recipes, and resources. _32_bit? ---------- Determines if the current architecture is 32-bit. _64_bit? ---------- Determines if the current architecture is 64-bit. arm? ---- Determines if the current architecture is arm. armhf? ------ Determines if the current architecture is 32-bit ARM hard float. i386? ----- Determines if the current architecture is i386. intel? ------ Determines if the current architecture is Intel. powerpc? -------- Determines if the current architecture is PowerPC. ppc64? ------ Determines if the current architecture is PowerPC 64bit Big Endian. ppc64le? -------- Determines if the current architecture is PowerPC 64bit Little Endian. s390? ----- Determines if the current architecture is s390. s390x? ------ Determines if the current architecture is s390x. sparc? ------ Determines if the current architecture is SPARC. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/checking_architectures/Chef Infra Language: Checking Hypervisors ========================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/checking_hypervisors.md) Chef Infra Client 15.8 and later include a number of helper methods for checking if a hypervisor host or guest. guest? ------ Determine if the current node is running under any virtualization environment. hypervisor? ----------- Determine if the current node supports running guests under any virtualization environment. physical? --------- Determine if the current node is NOT running under any virtualization environment (bare-metal or hypervisor on metal). kvm? ---- Determine if the current node is a KVM guest. kvm_host? ---------- Determine if the current node is a KVM host. lxc? ---- Determine if the current node is a LXC-based container. lxc_host? ---------- Determine if the current node is a LXC host. parallels? ---------- Determine if the current node is running under Parallels Desktop. parallels_host? ---------------- Determine if the current node is a Parallels Desktop host. vbox? ----- Determine if the current node is a VirtualBox guest. vbox_host? ----------- Determine if the current node is a VirtualBox host. vmware? ------- Determine if the current node is a VMWare guest. vmware_host? ------------- Determine if the current node is VMware host. openvz? ------- Determine if the current node is an openvz guest. openvz_host? ------------- Determine if the current node is an openvz host. vagrant? -------- Determine if the current node is running as a vagrant guest. vagrant_key? ------------- Check if the `vagrant` key exists on the +node+ object. Note: This key is no longer populated by vagrant, but it is kept around for legacy purposes. vagrant_domain? ---------------- Check if `vagrantup.com` is included in the node’s domain. vagrant_user? -------------- Check if the system contains a `vagrant` user. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/checking_hypervisors/About Recipes ============= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/recipes.md) A recipe is the most fundamental configuration element within the organization. A recipe: * Is authored using Ruby, which is a programming language designed to read and behave in a predictable manner * Is mostly a collection of [resources](../resources/index), defined using patterns (resource names, attribute-value pairs, and actions); helper code is added around this using Ruby, when needed * Must define everything that is required to configure part of a system * Must be stored in a cookbook * May be included in another recipe * May use the results of a search query and read the contents of a data bag (including an encrypted data bag) * May have a dependency on one (or more) recipes * Must be added to a run-list before it can be used by Chef Infra Client * Is always executed in the same order as listed in a run-list Recipe Attributes ----------------- An attribute can be defined in a cookbook (or a recipe) and then used to override the default settings on a node. When a cookbook is loaded during a Chef Infra Client run, these attributes are compared to the attributes that are already present on the node. Attributes that are defined in attribute files are first loaded according to cookbook order. For each cookbook, attributes in the `default.rb` file are loaded first, and then additional attribute files (if present) are loaded in lexical sort order. When the cookbook attributes take precedence over the default attributes, Chef Infra Client applies those new settings and values during a Chef Infra Client run on the node. Note Attributes can be configured in cookbooks (attribute files and recipes), roles, and environments. In addition, Ohai collects attribute data about each node at the start of a Chef Infra Client run. See [Attributes](../attributes/index) for more information about how all of these attributes fit together. Environment Variables --------------------- In UNIX, a process environment is a set of key-value pairs made available to a process. Programs expect their environment to contain information required for the program to run. The details of how these key-value pairs are accessed depends on the API of the language being used. If processes is started by using the **execute** or **script** resources (or any of the resources based on those two resources, such as **bash**), use the `environment` attribute to alter the environment that will be passed to the process. ``` bash 'env_test' do code <<-EOF echo $FOO EOF environment ({ 'FOO' => 'bar' }) end ``` The only environment being altered is the one being passed to the child process that is started by the **bash** resource. This will not affect the Chef Infra Client environment or any child processes. Work with Recipes ----------------- The following sections show approaches to working with recipes. ### Use Data Bags Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. The contents of a data bag can be loaded into a recipe. For example, a data bag named `apps` and a data bag item named `my_app`: ``` { "id": "my_app", "repository": "git://github.com/company/my_app.git" } ``` can be accessed in a recipe, like this: ``` my_bag = data_bag_item('apps', 'my_app') ``` The data bag item’s keys and values can be accessed with a Hash: ``` my_bag['repository'] #=> 'git://github.com/company/my_app.git' ``` #### Secret Keys Encrypting a data bag item requires a secret key. A secret key can be created in any number of ways. For example, OpenSSL can be used to generate a random number, which can then be used as the secret key: ``` openssl rand -base64 512 | tr -d '\r\n' > encrypted_data_bag_secret ``` where `encrypted_data_bag_secret` is the name of the file which will contain the secret key. For example, to create a secret key named “my_secret_key”: ``` openssl rand -base64 512 | tr -d '\r\n' > my_secret_key ``` The `tr` command eliminates any trailing line feeds. Doing so avoids key corruption when transferring the file between platforms with different line endings. #### Store Keys on Nodes An encryption key can also be stored in an alternate file on the nodes that need it and specify the path location to the file inside an attribute; however, `EncryptedDataBagItem.load` expects to see the actual secret as the third argument, rather than a path to the secret file. In this case, you can use `EncryptedDataBagItem.load_secret` to slurp the secret file contents and then pass them: ``` # inside your attribute file: # default[:mysql][:secretpath] = 'C:\\chef\\any_secret_filename' # # inside your recipe: # look for secret in file pointed to by mysql attribute :secretpath mysql_secret = Chef::EncryptedDataBagItem.load_secret('#{node['mysql']['secretpath']}') mysql_creds = Chef::EncryptedDataBagItem.load('passwords', 'mysql', mysql_secret) mysql_creds['pass'] # will be decrypted ``` ### Assign Dependencies If a cookbook has a dependency on a recipe that is located in another cookbook, that dependency must be declared in the metadata.rb file for that cookbook using the `depends` keyword. Note Declaring cookbook dependencies is not required with chef-solo. For example, if the following recipe is included in a cookbook named `my_app`: ``` include_recipe 'apache2::mod_ssl' ``` Then the metadata.rb file for that cookbook would have: ``` depends 'apache2' ``` ### Include Recipes A recipe can include one (or more) recipes from cookbooks by using the `include_recipe` method. When a recipe is included, the resources found in that recipe will be inserted (in the same exact order) at the point where the `include_recipe` keyword is located. The syntax for including a recipe is like this: ``` include_recipe 'recipe' ``` For example: ``` include_recipe 'apache2::mod_ssl' ``` Multiple recipes can be included within a recipe. For example: ``` include_recipe 'cookbook::setup' include_recipe 'cookbook::install' include_recipe 'cookbook::configure' ``` If a specific recipe is included more than once with the `include_recipe` method or elsewhere in the run_list directly, only the first instance is processed and subsequent inclusions are ignored. ### Reload Attributes Attributes sometimes depend on actions taken from within recipes, so it may be necessary to reload a given attribute from within a recipe. For example: ``` ruby_block 'some_code' do block do node.from_file(run_context.resolve_attribute('COOKBOOK_NAME', 'ATTR_FILE')) end action :nothing end ``` ### Use Ruby Anything that can be done with Ruby can be used within a recipe, such as expressions (if, unless, etc.), case statements, loop statements, arrays, hashes, and variables. In Ruby, the conditionals `nil` and `false` are false; every other conditional is `true`. #### Assign a value A variable uses an equals sign (`=`) to assign a value. To assign a value to a variable: ``` package_name = 'apache2' ``` #### Use Case Statement A case statement can be used to compare an expression, and then execute the code that matches. To select a package name based on platform: ``` package 'apache2' do case node['platform'] when 'centos', 'redhat', 'fedora', 'suse' package_name 'httpd' when 'debian', 'ubuntu' package_name 'apache2' when 'arch' package_name 'apache' end action :install end ``` #### Check Conditions An if expression can be used to check for conditions (true or false). To check for condition only for Debian and Ubuntu platforms: ``` if platform?('debian', 'ubuntu') # do something if node['platform'] is debian or ubuntu else # do other stuff end ``` #### Execute Conditions An unless expression can be used to execute code when a condition returns a false value (effectively, an unless expression is the opposite of an if statement). To use an expression to execute when a condition returns a false value: ``` unless node['platform_version'] == '5.0' # do stuff on everything but 5.0 end ``` #### Loop over Array A loop statement is used to execute a block of code one (or more) times. A loop statement is created when `.each` is added to an expression that defines an array or a hash. An array is an integer-indexed collection of objects. Each element in an array can be associated with and referred to by an index. To loop over an array of package names by platform: ``` ['apache2', 'apache2-mpm'].each do |p| package p end ``` #### Loop over Hash A hash is a collection of key-value pairs. Indexing for a hash is done using arbitrary keys of any object (as opposed to the indexing done by an array). The syntax for a hash is: `key => "value"`. To loop over a hash of gem package names: ``` { 'fog' => '0.6.0', 'highline' => '1.6.0' }.each do |g, v| gem_package g do version v end end ``` ### Apply to Run-lists A recipe must be assigned to a run-list using the appropriate name, as defined by the cookbook directory and namespace. For example, a cookbook directory has the following structure: ``` cookbooks/ apache2/ recipes/ default.rb mod_ssl.rb ``` There are two recipes: a default recipe (that has the same name as the cookbook) and a recipe named `mod_ssl`. The syntax that applies a recipe to a run-list is similar to: ``` { 'run_list': [ 'recipe[cookbook_name::default_recipe]', 'recipe[cookbook_name::recipe_name]' ] } ``` where `::default_recipe` is implied (and does not need to be specified). On a node, these recipes can be assigned to a node’s run-list similar to: ``` { 'run_list': [ 'recipe[apache2]', 'recipe[apache2::mod_ssl]' ] } ``` #### Chef Infra Server Use knife to add a recipe to the run-list for a node. For example: ``` knife node run list add NODENAME "recipe[apache2]" ``` More than one recipe can be added: ``` % knife node run list add NODENAME "recipe[apache2],recipe[mysql],role[ssh]" ``` which creates a run-list similar to: ``` run_list: recipe[apache2] recipe[mysql] role[ssh] ``` #### chef-solo Use a JSON file to pass run-list details to chef-solo as long as the cookbook in which the recipe is located is available to the system on which chef-solo is running. For example, a file named `dna.json` contains the following details: ``` { "run_list": ["recipe[apache2]"] } ``` To add the run-list to the node, enter the following: ``` sudo chef-solo -j /etc/chef/dna.json ``` ### Use Search Results Search indexes allow queries to be made for any type of data that is indexed by the Chef Infra Server, including data bags (and data bag items), environments, nodes, and roles. A defined query syntax is used to support search patterns like exact, wildcard, range, and fuzzy. A search is a full-text query that can be done from several locations, including from within a recipe, by using the `search` subcommand in knife, the `search` method in the Chef Infra Language, the search box in the Chef management console, and by using the `/search` or `/search/INDEX` endpoints in the Chef Infra Server API. The search engine is based on Elasticsearch and is run from the Chef Infra Server. The results of a search query can be loaded into a recipe. For example, a very simple search query (in a recipe) might look like this: ``` search(:node, 'attribute:value') ``` A search query can be assigned to variables and then used elsewhere in a recipe. For example, to search for all nodes that have a role assignment named `webserver`, and then render a template which includes those role assignments: ``` webservers = search(:node, 'role:webserver') template '/tmp/list_of_webservers' do source 'list_of_webservers.erb' variables(webservers: webservers) end ``` ### Use Tags A tag is a custom description that is applied to a node. A tag, once applied, can be helpful when managing nodes using knife or when building recipes by providing alternate methods of grouping similar types of information. Tags can be added and removed. Machines can be checked to see if they already have a specific tag. To use tags in your recipe simply add the following: ``` tag('mytag') ``` To test if a machine is tagged, add the following: ``` tagged?('mytag') ``` to return `true` or `false`. `tagged?` can also use an array as an argument. To remove a tag: ``` untag('mytag') ``` For example: ``` tag('machine') if tagged?('machine') Chef::Log.info("Hey I'm #{node['tags']}") end untag('machine') unless tagged?('machine') Chef::Log.info('I am not tagged') end ``` Will return something like this: ``` [Thu, 22 Jul 2010 18:01:45 +0000] INFO: Hey I'm machine [Thu, 22 Jul 2010 18:01:45 +0000] INFO: I has no tagz ``` ### End Chef Infra Client Run Sometimes it may be necessary to stop processing a recipe and/or stop processing the entire Chef Infra Client run. There are a few ways to do this: * Use the `return` keyword to stop processing a recipe based on a condition, but continue processing a Chef Infra Client run * Use the `raise` keyword to stop a Chef Infra Client run by triggering an unhandled exception * Use a `rescue` block in Ruby code * Use an [exception handler](../handlers/index) The following sections show various approaches to ending a Chef Infra Client run. #### return Keyword The `return` keyword can be used to stop processing a recipe based on a condition, but continue processing a Chef Infra Client run. For example: ``` file '/tmp/name_of_file' do action :create end return if platform?('windows') package 'name_of_package' do action :install end ``` where `platform?('windows')` is the condition set on the `return` keyword. When the condition is met, stop processing the recipe. This approach is useful when there is no need to continue processing, such as when a package cannot be installed. In this situation, it’s OK for a recipe to stop processing. #### raise Keyword In certain situations it may be useful to stop a Chef Infra Client run entirely by using an unhandled exception. The `raise` keyword can be used to stop a Chef Infra Client run in both the compile and execute phases. Note You may also see code that uses the `fail` keyword, which behaves the same but is discouraged and will result in Cookstyle warnings. Use these keywords in a recipe—but outside of any resource blocks—to trigger an unhandled exception during the compile phase. For example: ``` file '/tmp/name_of_file' do action :create end raise "message" if platform?('windows') package 'name_of_package' do action :install end ``` where `platform?('windows')` is the condition that will trigger the unhandled exception. Use these keywords in the **ruby_block** resource to trigger an unhandled exception during the execute phase. For example: ``` ruby_block "name" do block do # Ruby code with a condition, e.g. if ::File.exist?(::File.join(path, "/tmp")) raise "message" # e.g. "Ordering issue with file path, expected foo" end end ``` Use these keywords in a class. For example: ``` class CustomError < StandardError; end ``` and then later on: ``` def custom_error raise CustomError, "error message" end ``` or: ``` def custom_error raise CustomError, "error message" end ``` #### Rescue Blocks Since recipes are written in Ruby, they can be written to attempt to handle error conditions using the `rescue` block. For example: ``` begin dater = data_bag_item(:basket, 'flowers') rescue Net::HTTPClientException # maybe some retry code here? raise 'message_to_be_raised' end ``` where `data_bag_item` makes an HTTP request to the Chef Infra Server to get a data bag item named `flowers`. If there is a problem, the request will return a `Net::HTTPClientException`. The `rescue` block can be used to try to retry or otherwise handle the situation. If the `rescue` block is unable to handle the situation, then the `raise` keyword is used to specify the message to be raised. ### node.run_state Use `node.run_state` to stash transient data during a Chef Infra Client run. This data may be passed between resources, and then evaluated during the execution phase. `run_state` is an empty Hash that is always discarded at the end of a Chef Infra Client run. For example, the following recipe will install the Apache web server, randomly choose PHP or Perl as the scripting language, and then install that scripting language: ``` package 'httpd' do action :install end ruby_block 'randomly_choose_language' do block do if Random.rand > 0.5 node.run_state['scripting_language'] = 'php' else node.run_state['scripting_language'] = 'perl' end end end package 'scripting_language' do package_name lazy { node.run_state['scripting_language'] } action :install end ``` where: * The **ruby_block** resource declares a `block` of Ruby code that is run during the execution phase of a Chef Infra Client run * The `if` statement randomly chooses PHP or Perl, saving the choice to `node.run_state['scripting_language']` * When the **package** resource has to install the package for the scripting language, it looks up the scripting language and uses the one defined in `node.run_state['scripting_language']` * `lazy {}` ensures that the **package** resource evaluates this during the execution phase of a Chef Infra Client run (as opposed to during the compile phase) When this recipe runs, Chef Infra Client will print something like the following: ``` * ruby_block[randomly_choose_language] action run - execute the ruby block randomly_choose_language * package[scripting_language] action install - install version 5.3.3-27.el6_5 of package php ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/recipes/Chef Infra Language: Cookbook Execution ======================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/cookbook_execution.md) The Chef Infra Language includes helper methods for gathering information on the execution of the Chef Infra Client recipe and resource code. This information can be used in recipes and resources to take specific actions. Chef Infra Client State ----------------------- These helpers allow you to understand the state of the node that Chef Infra Client is executing on. ### node Use the `node` method, often referred to as the node object, to access data collected on the system through [Ohai](../../ohai) as well as node attributes set in cookbooks or Policyfiles. The syntax for the `cookbook_name` method is as follows: ``` node['specific_attribute'] ``` ### cookbook_name Use the `cookbook_name` method to return the name of a cookbook. The syntax for the `cookbook_name` method is as follows: ``` cookbook_name ``` This method is often used as part of a log entry. For example: ``` Chef::Log.info('I am a message from the #{recipe_name} recipe in the #{cookbook_name} cookbook.') ``` ### recipe_name Use the `recipe_name` method to return the name of a recipe. The syntax for the `recipe_name` method is as follows: ``` recipe_name ``` This method is often used as part of a log entry. For example: ``` Chef::Log.info('I am a message from the #{recipe_name} recipe in the #{cookbook_name} cookbook.') ``` ### resources Use the `resources` method to look up a resource in the resource collection. The `resources` method returns the value for the resource that it finds in the resource collection. The preferred syntax for the `resources` method is as follows: ``` resources('resource_type[resource_name]') ``` but the following syntax can also be used: ``` resources(resource_type: 'resource_name') ``` where in either approach `resource_type` is the name of a resource and `resource_name` is the name of a resource that can be configured by Chef Infra Client. The `resources` method can be used to modify a resource later on in a recipe. For example: ``` file '/etc/hosts' do content '127.0.0.1 localhost.localdomain localhost' end ``` and then later in the same recipe, or elsewhere: ``` f = resources('file[/etc/hosts]') f.mode '0644' ``` where `file` is the type of resource, `/etc/hosts` is the name, and `f.mode` is used to set the `mode` property on the **file** resource. ### attribute? Use the `attribute?` method to ensure that certain actions only execute in the presence of a particular node attribute. The `attribute?` method will return true if one of the listed node attributes matches a node attribute that is detected by Ohai during every Chef Infra Client run. The syntax for the `attribute?` method is as follows: ``` attribute?('name_of_attribute') ``` For example: ``` if node.attribute?('ipaddress') # the node has an ipaddress end ``` ### reboot_pending? Use the `reboot_pending?` method to test if a node needs a reboot, or is expected to reboot. `reboot_pending?` returns `true` when the node needs a reboot. The syntax for the `reboot_pending?` method is as follows: ``` reboot_pending? ``` Executing Code -------------- These helpers allow you to include recipes and impact how resources run on the system. ### include_recipe A recipe can include one (or more) recipes from cookbooks by using the `include_recipe` method. When a recipe is included, the resources found in that recipe will be inserted (in the same exact order) at the point where the `include_recipe` keyword is located. The syntax for including a recipe is like this: ``` include_recipe 'recipe' ``` For example: ``` include_recipe 'apache2::mod_ssl' ``` Multiple recipes can be included within a recipe. For example: ``` include_recipe 'cookbook::setup' include_recipe 'cookbook::install' include_recipe 'cookbook::configure' ``` If a specific recipe is included more than once with the `include_recipe` method or elsewhere in the run_list directly, only the first instance is processed and subsequent inclusions are ignored. ### with_run_context Use the `with_run_context` method to define a block that has a pointer to a location in the `run_context` hierarchy. Resources in recipes always run at the root of the `run_context` hierarchy, whereas custom resources and notification blocks always build a child `run_context` which contains their sub-resources. The syntax for the `with_run_context` method is as follows: ``` with_run_context :type do # some arbitrary pure Ruby stuff goes here end ``` where `:type` may be one of the following: * `:root` runs the block as part of the root `run_context` hierarchy * `:parent` runs the block as part of the parent process in the `run_context` hierarchy For example: ``` action :run do with_run_context :root do edit_resource(:my_thing, "accumulated state") do action :nothing my_array_property << accumulate_some_stuff end end log "kick it off" do notifies :run, "my_thing[accumulated state]", :delayed end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/cookbook_execution/Chef Infra Language: Checking Platforms ======================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/checking_platforms.md) platform? --------- Use the `platform?` helper method to ensure that certain actions are run for specific platforms. The `platform?` method will return true if one of the listed parameters matches the `node['platform']` attribute that is detected by [Ohai](../../ohai) during every Chef Infra Client run. The syntax for the `platform?` method is as follows: ``` platform?('parameter', 'parameter') ``` where: * `parameter` is a comma-separated list, each specifying a platform, such as Red Hat, CentOS, or Fedora * `platform?` method is typically used with an `if`, `elsif`, or `case` statement that contains Ruby code that is specific for the platform, if detected ### platform Values | Parameter | Platforms | | --- | --- | | `aix` | IBM AIX | | `alibabalinux` | Alibaba Cloud Linux | | `almalinux` | AlmaLinux | | `amazon` | Amazon Linux | | `arch` | Arch Linux | | `clearos` | ClearOS | | `cloudlinux` | Cloud Linux OS | | `cumulus` | NVIDIA Cumulus Linux | | `debian` | Debian GNU/Linux | | `fedora` | Fedora | | `freebsd` | FreeBSD | | `gentoo` | Gentoo Linux | | `linuxmint` | Linux Mint | | `mac_os_x` | macOS | | `netbsd` | NetBSD | | `openbsd` | OpenBSD | | `openindiana` | OpenIndiana | | `opensuseleap` | openSUSE leap | | `pidora` | Pidora | | `raspbian` | Raspberry Pi OS | | `rocky` | Rocky Linux | | `sangoma` | Sangoma Linux | | `scientific` | Scientific Linux | | `solaris2` | Oracle Solaris | | `suse` | SUSE Enterprise Linux Server. | | `ubuntu` | Ubuntu Linux | | `virtuozzo` | Virtuozzo | | `windows` | Microsoft Windows | | `xenserver` | Citrix XenServer | ### Examples #### Installing the cron package on Debian systems ``` package 'cron' if platform?('debian') ``` #### Deleting a file on Red Hat and Debian systems ``` if platform?('redhat', 'debian') file '/etc/some_config' do action :remove end end ``` #### Installing the correct Firefox package The following example shows how an if statement can be used with the `platform?` method in the Chef Infra Language to run code specific to Microsoft Windows. The code is defined using the **ruby_block** resource: ``` if platform?('windows') chocolatey_package 'firefox' else package 'firefox' end ``` platform_family? ----------------- Use the `platform_family?` method to ensure that certain actions are run for specific platform families. The `platform_family?` method will return true if one of the listed parameters matches the `node['platform_family']` attribute that are detected by [Ohai](../../ohai) during every Chef Infra Client run. The syntax for the `platform_family?` method is as follows: ``` platform_family?('parameter', 'parameter') ``` where: * `'parameter'` is a comma-separated list, each specifying a platform family, such as Debian, or Red Hat Enterprise Linux * `platform_family?` method is typically used with an `if`, `elsif`, or `case` statement that contains Ruby code that is specific for the platform family, if detected ### platform_family Values | Parameter | Platforms | | --- | --- | | `aix` | `aix` platform. | | `alpine` | `alpine` platform. | | `amazon` | `amazon` platform. | | `arch` | `arch`, `manjaro`, and `antergos` platforms. | | `debian` | `debian`, `ubuntu`, `linuxmint`, `raspbian`, `cumulus`, `kali`, `sangoma`, and `pop` platforms. | | `fedora` | `fedora`, `pidora`, and `arista_eos` platforms | | `freebsd` | `freebsd` platform | | `gentoo` | `gentoo` platform | | `mac_os_x` | `mac_os_x` platform | | `netbsd` | `netbsd` platform | | `openbsd` | `openbsd` platform | | `openindiana` | `openindiana` platform | | `rhel` | `redhat`, `centos`, `oracle`, `almalinux`, `rocky`, `scientific`, `xenserver`, `clearos`, `bigip`, `parallels`, `xcp`, `virtuozzo`, `alibabalinux`, and `ibm_powerkvm` platforms | | `solaris2` | `solaris2` platform | | `suse` | `opensuse_leap`, `suse`, and `sled` platforms | | `windows` | `windows` platform | ### Examples For example: ``` platform_family?('gentoo') ``` or: ``` platform_family?('slackware', 'suse', 'arch') ``` #### Use a specific binary for a specific platform The following is an example of using the `platform_family?` method in the Chef Infra Language to create a variable that can be used with other resources in the same recipe. In this example, `platform_family?` is being used to ensure that a specific binary is used for a specific platform before using the **remote_file** resource to download a file from a remote location, and then using the **execute** resource to install that file by running a command. ``` if platform_family?('rhel') pip_binary = '/usr/bin/pip' else pip_binary = '/usr/local/bin/pip' end remote_file "#{Chef::Config[:file_cache_path]}/distribute_setup.py" do source 'http://python-distribute.org/distribute_setup.py' mode '0755' not_if { ::File.exist?(pip_binary) } end execute 'install-pip' do cwd Chef::Config[:file_cache_path] command <<-EOF # command for installing Python goes here EOF not_if { ::File.exist?(pip_binary) } end ``` where a command for installing Python might look something like: ``` #{node['python']['binary']} distribute_setup.py #{::File.dirname(pip_binary)}/easy_install pip ``` value_for_platform -------------------- Use the `value_for_platform` method in a recipe to select a value based on the `node['platform']` and `node['platform_version']` attributes. These values are detected by Ohai during every Chef Infra Client run. The syntax for the `value_for_platform` method is as follows: ``` value_for_platform( ['platform', ...] => { 'version' => 'value' } ) ``` where: * `'platform', ...` is a comma-separated list of platforms, such as Red Hat, openSUSE, or Fedora * `version` specifies the version of that platform * Version constraints—`>`, `<`, `>=`, `<=`, `~>`—may be used with `version`; an exception is raised if two version constraints match; an exact match will always take precedence over a match made from a version constraint * `value` specifies the value that will be used if the node’s platform matches the `value_for_platform` method When each value only has a single platform, use the following syntax: ``` value_for_platform( 'platform' => { 'version' => 'value' }, 'platform' => { 'version' => 'value' }, 'platform' => 'value' ) ``` When each value has more than one platform, the syntax changes to: ``` value_for_platform( ['platform', 'platform', ... ] => { 'version' => 'value' }, ) ``` ### Operators The following operators may be used: | Operator | Description | | --- | --- | | `=` | equal to | | `>` | greater than | | `<` | less than | | `>=` | greater than or equal to; also known as "optimistically greater than", or "optimistic" | | `<=` | less than or equal to | | `~>` | approximately greater than; also known as "pessimistically greater than", or "pessimistic" | ### Examples The following example will set `package_name` to `httpd` for the Red Hat platform and to `apache2` for the Debian platform: ``` package_name = value_for_platform( ['centos', 'redhat', 'suse', 'fedora' ] => { 'default' => 'httpd' }, ['ubuntu', 'debian'] => { 'default' => 'apache2' } ) ``` The following example will set `package` to `apache-couchdb` for OpenBSD platforms, `dev-db/couchdb` for Gentoo platforms, and `couchdb` for all other platforms: ``` package = value_for_platform( 'openbsd' => { 'default' => 'apache-couchdb' }, 'gentoo' => { 'default' => 'dev-db/couchdb' }, 'default' => 'couchdb' ) ``` The following example shows using version constraints to specify a value based on the version: ``` value_for_platform( 'os1' => { '< 1.0' => 'less than 1.0', '~> 2.0' => 'version 2.x', '>= 3.0' => 'greater than or equal to version 3.0', '3.0.1' => '3.0.1 will always use this value' } ) ``` value_for_platform_family ---------------------------- Use the `value_for_platform_family` method in a recipe to select a value based on the `node['platform_family']` attribute. This value is detected by Ohai during every Chef Infra Client run. The syntax for the `value_for_platform_family` method is as follows: ``` value_for_platform_family( 'platform_family' => 'value', ... ) ``` where: * `'platform_family' => 'value', ...` is a comma-separated list of platforms, such as Fedora, openSUSE, or Red Hat Enterprise Linux * `value` specifies the value that will be used if the node’s platform family matches the `value_for_platform_family` method When each value only has a single platform, use the following syntax: ``` value_for_platform_family( 'platform_family' => 'value', 'platform_family' => 'value', 'platform_family' => 'value' ) ``` When each value has more than one platform, the syntax changes to: ``` value_for_platform_family( ['platform_family', 'platform_family', 'platform_family', 'platform_family' ] => 'value', ['platform_family', 'platform_family'] => 'value', 'default' => 'value' ) ``` The following example will set `package` to `httpd-devel` for the Red Hat Enterprise Linux, Fedora, and openSUSE platforms and to `apache2-dev` for the Debian platform: ``` package = value_for_platform_family( ['rhel', 'fedora', 'suse'] => 'httpd-devel', 'debian' => 'apache2-dev' ) ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/checking_platforms/Chef Infra Language: Editing Resources ====================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/editing_resources.md) declare_resource ----------------- Use the `declare_resource` method to instantiate a resource and then add it to the resource collection. The syntax for the `declare_resource` method is as follows: ``` declare_resource(:resource_type, 'resource_name', resource_attrs_block) ``` where: * `:resource_type` is the resource type, such as `:file` (for the **file** resource), `:template` (for the **template** resource), and so on. Any resource available to Chef may be declared. * `resource_name` the property that is the default name of the resource, typically the string that appears in the `resource 'name' do` block of a resource (but not always); see the Syntax section for the resource to be declared to verify the default name property. * `resource_attrs_block` is a block in which properties of the instantiated resource are declared. For example: ``` declare_resource(:file, '/x/y.txy', caller[0]) do action :delete end ``` is equivalent to: ``` file '/x/y.txt' do action :delete end ``` delete_resource ---------------- Use the `delete_resource` method to find a resource in the resource collection, and then delete it. The syntax for the `delete_resource` method is as follows: ``` delete_resource(:resource_type, 'resource_name') ``` where: * `:resource_type` is the resource type, such as `:file` (for the **file** resource), `:template` (for the **template** resource), and so on. Any resource available to Chef may be declared. * `resource_name` the property that is the default name of the resource, typically the string that appears in the `resource 'name' do` block of a resource (but not always); see the Syntax section for the resource to be declared to verify the default name property. For example: ``` delete_resource(:template, '/x/y.erb') ``` delete_resource! ----------------- Use the `delete_resource!` method to find a resource in the resource collection, and then delete it. If the resource is not found, an exception is returned. The syntax for the `delete_resource!` method is as follows: ``` delete_resource!(:resource_type, 'resource_name') ``` where: * `:resource_type` is the resource type, such as `:file` (for the **file** resource), `:template` (for the **template** resource), and so on. Any resource available to Chef Infra may be declared. * `resource_name` the property that is the default name of the resource, typically the string that appears in the `resource 'name' do` block of a resource (but not always); see the Syntax section for the resource to be declared to verify the default name property. For example: ``` delete_resource!(:file, '/x/file.txt') ``` edit_resource -------------- Use the `edit_resource` method to: * Find a resource in the resource collection, and then edit it. * Define a resource block. If a resource block with the same name exists in the resource collection, it will be updated with the contents of the resource block defined by the `edit_resource` method. If a resource block does not exist in the resource collection, it will be created. The syntax for the `edit_resource` method is as follows: ``` edit_resource(:resource_type, 'resource_name', resource_attrs_block) ``` where: * `:resource_type` is the resource type, such as `:file` (for the **file** resource), `:template` (for the **template** resource), and so on. Any resource available to Chef may be declared. * `resource_name` the property that is the default name of the resource, typically the string that appears in the `resource 'name' do` block of a resource (but not always); see the Syntax section for the resource to be declared to verify the default name property. * `resource_attrs_block` is a block in which properties of the instantiated resource are declared. For example: ``` edit_resource(:template, '/x/y.txy') do cookbook 'cookbook_name' end ``` and a resource block: ``` edit_resource(:template, '/etc/aliases') do source 'aliases.erb' cookbook 'aliases' variables({:aliases => {} }) notifies :run, 'execute[newaliases]' end ``` edit_resource! --------------- Use the `edit_resource!` method to: * Find a resource in the resource collection, and then edit it. * Define a resource block. If a resource with the same name exists in the resource collection, its properties will be updated with the contents of the resource block defined by the `edit_resource` method. In both cases, if the resource is not found, an exception is returned. The syntax for the `edit_resource!` method is as follows: ``` edit_resource!(:resource_type, 'resource_name') ``` where: * `:resource_type` is the resource type, such as `:file` (for the **file** resource), `:template` (for the **template** resource), and so on. Any resource available to Chef may be declared. * `resource_name` the property that is the default name of the resource, typically the string that appears in the `resource 'name' do` block of a resource (but not always); see the Syntax section for the resource to be declared to verify the default name property. * `resource_attrs_block` is a block in which properties of the instantiated resource are declared. For example: ``` edit_resource!(:file, '/x/y.rst') ``` find_resource -------------- Use the `find_resource` method to: * Find a resource in the resource collection. * Define a resource block. If a resource block with the same name exists in the resource collection, it will be returned. If a resource block does not exist in the resource collection, it will be created. The syntax for the `find_resource` method is as follows: ``` find_resource(:resource_type, 'resource_name') ``` where: * `:resource_type` is the resource type, such as `:file` (for the **file** resource), `:template` (for the **template** resource), and so on. Any resource available to Chef may be declared. * `resource_name` the property that is the default name of the resource, typically the string that appears in the `resource 'name' do` block of a resource (but not always); see the Syntax section for the resource to be declared to verify the default name property. For example: ``` find_resource(:template, '/x/y.txy') ``` and a resource block: ``` find_resource(:template, '/etc/seapower') do source 'seapower.erb' cookbook 'seapower' variables({:seapower => {} }) notifies :run, 'execute[newseapower]' end ``` find_resource! --------------- Use the `find_resource!` method to find a resource in the resource collection. If the resource is not found, an exception is returned. The syntax for the `find_resource!` method is as follows: ``` find_resource!(:resource_type, 'resource_name') ``` where: * `:resource_type` is the resource type, such as `:file` (for the **file** resource), `:template` (for the **template** resource), and so on. Any resource available to Chef may be declared. * `resource_name` the property that is the default name of the resource, typically the string that appears in the `resource 'name' do` block of a resource (but not always); see the Syntax section for the resource to be declared to verify the default name property. For example: ``` find_resource!(:template, '/x/y.erb') ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/editing_resources/Chef Infra Language: Node Tags ============================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/node_tags.md) A tag is a custom description that is applied to a node. A tag, once applied, can be helpful when managing nodes using knife or when building recipes by providing alternate methods of grouping similar types of information. Tags can be added and removed. Machines can be checked to see if they already have a specific tag. To use tags in your recipe simply add the following: ``` tag('mytag') ``` To test if a machine is tagged, add the following: ``` tagged?('mytag') ``` to return `true` or `false`. `tagged?` can also use an array as an argument. To remove a tag: ``` untag('mytag') ``` For example: ``` tag('machine') if tagged?('machine') Chef::Log.info("Hey I'm #{node['tags']}") end untag('machine') unless tagged?('machine') Chef::Log.info('I am not tagged') end ``` Will return something like this: ``` [Thu, 22 Jul 2010 18:01:45 +0000] INFO: Hey I'm machine [Thu, 22 Jul 2010 18:01:45 +0000] INFO: I has no tagz ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/node_tags/Chef Infra Language: Logging ============================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/logging.md) Log Entries ----------- `Chef::Log` will print log entries to the default logger that is configured for the machine on which Chef Infra Client is running. (To create a log entry that is built into the resource collection, use the [log resource](../../resources/log/index) instead of `Chef::Log`.) ### Supported Log Levels | Log Level | Syntax | | --- | --- | | Fatal | `Chef::Log.fatal('string')` | | Error | `Chef::Log.error('string')` | | Warn | `Chef::Log.warn('string')` | | Info | `Chef::Log.info('string')` | | Debug | `Chef::Log.debug('string')` | ### Examples The following example shows a series of fatal `Chef::Log` entries: ``` unless node['splunk']['upgrade_enabled'] Chef::Log.fatal('The chef-splunk::upgrade recipe was added to the node,') Chef::Log.fatal('but the attribute `node["splunk"]["upgrade_enabled"]` was not set.') Chef::Log.fatal('I am bailing here so this node does not upgrade.') raise end service 'splunk_stop' do service_name 'splunk' supports status: true action :stop end if node['splunk']['is_server'] splunk_package = 'splunk' url_type = 'server' else splunk_package = 'splunkforwarder' url_type = 'forwarder' end splunk_installer splunk_package do url node['splunk']['upgrade']["#{url_type}_url"] end if node['splunk']['accept_license'] execute 'splunk-unattended-upgrade' do command "#{splunk_cmd} start --accept-license --answer-yes" end else Chef::Log.fatal('You did not accept the license (set node["splunk"]["accept_license"] to true)') Chef::Log.fatal('Splunk is stopped and cannot be restarted until the license is accepted!') raise end ``` The following example shows using multiple `Chef::Log` entry types: ``` ... begin aws = Chef::DataBagItem.load(:aws, :main) Chef::Log.info("Loaded AWS information from DataBagItem aws[#{aws['id']}]") rescue Chef::Log.fatal("Could not find the 'main' item in the 'aws' data bag") raise end ... ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/logging/Chef Infra Language: Reading Data Bags ====================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/reading_data_bags.md) data_bag --------- Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. Use the `data_bag` method to get a list of the contents of a data bag. The syntax for the `data_bag` method is as follows: ``` data_bag(bag_name) ``` ### Examples The following example shows how the `data_bag` method can be used in a recipe. #### Get a data bag, and then iterate through each data bag item ``` data_bag('users') #=> ['sandy', 'jill'] ``` Iterate over the contents of the data bag to get the associated `data_bag_item`: ``` data_bag('users').each do |user| data_bag_item('users', user) end ``` The `id` for each data bag item will be returned as a string. data_bag_item --------------- Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. The `data_bag_item` method can be used in a recipe to get the contents of a data bag item. The syntax for the `data_bag_item` method is as follows: ``` data_bag_item(bag_name, item, secret) ``` where `secret` is the secret used to load an encrypted data bag. If `secret` is not specified, Chef Infra Client looks for a secret at the path specified by the `encrypted_data_bag_secret` setting in the `client.rb` file. ### Examples The following examples show how the `data_bag_item` method can be used in a recipe. #### Get a data bag, and then iterate through each data bag item ``` data_bag('users') #=> ['sandy', 'jill'] ``` Iterate over the contents of the data bag to get the associated `data_bag_item`: ``` data_bag('users').each do |user| data_bag_item('users', user) end ``` The `id` for each data bag item will be returned as a string. #### Use the contents of a data bag in a recipe The following example shows how to use the `data_bag` and `data_bag_item` methods in a recipe, also using a data bag named `sea-power`): ``` package 'sea-power' do action :install end directory node['sea-power']['base_path'] do # attributes for owner, group, mode end gale_warnings = data_bag('sea-power').map do |viking_north| data_bag_item('sea-power', viking_north)['source'] end template '/etc/seattle/power.list' do source 'seattle-power.erb' # attributes for owner, group, mode variables( :base_path => node['sea-power']['base_path'], # more variables :repo_location => gale_warnings ) end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/reading_data_bags/Chef Infra Language: Secrets ============================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/secrets.md) Chef Infra Client 17.5 and later includes a beta Secrets Management Integration helper. This helper allows accessing secrets from the following secrets management systems within your Infra recipes or resources: * AWS Secrets Manager * Akeyless Vault * Azure Key Vault * HashiCorp Vault Note This helper is a beta release. It is under active development and may change. We welcome your feedback at [<EMAIL>](mailto:<EMAIL>). Secrets Manager Support ----------------------- ### AWS Secrets Manager The secrets helper supports fetching secrets from AWS Secrets Manager from IAM roles applied to instances. #### Fetching an AWS Secrets Manager secret ``` secret(name: 'test1', service: :aws_secrets_manager) ``` #### Specifying the AWS Region containing the secret ``` secret(name: 'test1', service: :aws_secrets_manager, config: { region: 'us-west-2' }) ``` ### Akeyless Vault The secrets helper supports fetching secrets from Akeyless Vault using Akeyless' access key and access id. #### Fetching Secrets From Akeyless Vault Using Access Key/ID ``` secret(name: '/secret/data/my_secret', service: :akeyless_vault, config: { access_key: '12345678910=', access_id: 'p-12345678910' }) ``` ### Azure Key Vault The secrets helper supports fetching secrets from Akeyless Vault using Akeyless' access key and access id. #### Fetching Secrets From Azure Key Vault ``` secret(name: 'vault-name/test-secret-1', service: :azure_key_vault) ``` #### Fetching a specific version of an Azure Key Vault secret ``` secret(name: 'vault-name/test1', version: 'v1', service: :azure_key_vault) ``` ### HashiCorp Vault #### Fetching Secrets From HashiCorp Vault Using AWS IAM ``` secret(name: 'secret/example', service: :hashi_vault, config: { vault_addr: 'vault.example.com', role_name: 'example-role' }) ``` #### Fetching Secrets From HashiCorp Vault Using Tokens ``` secret(name: 'secret/example', service: :hashi_vault, config: { vault_addr: 'vault.example.com', auth_method: :token, token: '123456' }) ``` #### Fetching Secrets From HashiCorp Vault Using AppRole Authentication Fetching secret data using an AppRole ID and an associated AppRole Secret ID: ``` secret(name: 'secret/example', service: :hashi_vault, config: { vault_addr: 'vault.example.com', auth_method: :approle, approle_id: "11111111-abcd-1111-abcd-111111111111", approle_secret_id: "22222222-abcd-2222-abcd-222222222222" }) ``` Fetching secret data using a token and an AppRole name creates a Secret ID associated with that AppRole: ``` secret(name: 'secret/example', service: :hashi_vault, config: { vault_addr: 'vault.example.com', auth_method: :approle, approle_name: "my-approle", token: '123456' }) ``` Using in Cookbooks ------------------ The secrets helper returns a text string, so it can be used anywhere in Chef Infra where you might hard code a value or access a value from a data bag. ### Writing a Secret To a File ``` file '/home/ubuntu/aws-secret' do content secret(name: 'test1', service: :aws_secrets_manager) end ``` ### Passing a Secret to a Template ``` template '/etc/my_fancy_service/my_fancy_service.conf' do source 'config.erb' variables( db_token: secret(name: 'db_token', service: :aws_secrets_manager) ) end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/secrets/Chef Infra Language: Reading Registry Keys ========================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/registry_keys.md) Six methods are present in the Chef Infra Language to help verify the registry during a Chef Infra Client run on the Microsoft Windows platform—`registry_data_exists?`, `registry_get_subkeys`, `registry_get_values`, `registry_has_subkeys?`, `registry_key_exists?`, and `registry_value_exists?`—these helpers ensure the **powershell_script** resource is idempotent. Note The recommended order in which registry key-specific methods should be used within a recipe is: `key_exists?`, `value_exists?`, `data_exists?`, `get_values`, `has_subkeys?`, and then `get_subkeys`. registry_data_exists? ----------------------- Use the `registry_data_exists?` method to find out if a Microsoft Windows registry key contains the specified data of the specified type under the value. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_data_exists?` method is as follows: ``` registry_data_exists?( KEY_PATH, { name: 'NAME', type: TYPE, data: DATA }, ARCHITECTURE ) ``` where: * `KEY_PATH` is the path to the registry key value. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `{ name: 'NAME', type: TYPE, data: DATA }` is a hash that contains the expected name, type, and data of the registry key value * `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. registry_get_subkeys ---------------------- Use the `registry_get_subkeys` method to get a list of registry key values that are present for a Microsoft Windows registry key. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_get_subkeys` method is as follows: ``` subkey_array = registry_get_subkeys(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This returns an array of registry key values. registry_get_values --------------------- Use the `registry_get_values` method to get the registry key values (name, type, and data) for a Microsoft Windows registry key. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_get_values` method is as follows: ``` subkey_array = registry_get_values(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This returns an array of registry key values. registry_has_subkeys? ----------------------- Use the `registry_has_subkeys?` method to find out if a Microsoft Windows registry key has one (or more) values. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_has_subkeys?` method is as follows: ``` registry_has_subkeys?(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. registry_key_exists? ---------------------- Use the `registry_key_exists?` method to find out if a Microsoft Windows registry key exists at the specified path. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_key_exists?` method is as follows: ``` registry_key_exists?(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. (Any registry key values that are associated with this registry key are ignored.) registry_value_exists? ------------------------ Use the `registry_value_exists?` method to find out if a registry key value exists. Use `registry_data_exists?` to test for the type and data of a registry key value. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_dvalue_exists?` method is as follows: ``` registry_value_exists?( KEY_PATH, { name: 'NAME' }, ARCHITECTURE ) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `{ name: 'NAME' }` is a hash that contains the name of the registry key value; if either `type:` or `:value` are specified in the hash, they are ignored * `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/registry_keys/Chef Infra Language: Shelling Out ================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/shelling_out.md) In most cases when you need to run a particular command in a cookbook, you’ll want to use the [execute resource](../../resources/execute/index). Helper methods for shelling out can be useful when writing custom resources or other more advanced Ruby code. shell_out ---------- The `shell_out` method can be used to run a command against the node, and then display the output to the console when the log level is set to `debug`. The syntax for the `shell_out` method is as follows: ``` shell_out(command_args) ``` where `command_args` is the command that is run against the node. shell_out! ----------- The `shell_out!` method can be used to run a command against the node, display the output to the console when the log level is set to `debug`, and then raise an error when the method returns `false`. The syntax for the `shell_out!` method is as follows: ``` shell_out!(command_args) ``` where `command_args` is the command that is run against the node. This method will return `true` or `false`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/shelling_out/Chef Infra Language: Windows ============================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/windows.md) Chef Infra Client 15.8 and later include Windows-specific helpers for checking platform and package information. windows_server_core? ---------------------- Determine if the current node is Windows Server Core. windows_workstation? --------------------- Determine if the current node is Windows Workstation. windows_server? ---------------- Determine if the current node is Windows Server. windows_nt_version -------------------- Determine the current Windows NT version. The NT version often differs from the marketing version, but offers a good way to find desktop and server releases that are based on the same codebase. For example NT 6.3 corresponds to Windows 8.1 and Windows 2012 R2. powershell_version ------------------- Determine the installed version of PowerShell. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/windows/Chef Infra Language: Search =========================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/infra_language/search.md) search ------ Search indexes allow queries to be made for any type of data that is indexed by the Chef Infra Server, including data bags (and data bag items), environments, nodes, and roles. A defined query syntax is used to support search patterns like exact, wildcard, range, and fuzzy. A search is a full-text query that can be done from several locations, including from within a recipe, by using the `search` subcommand in knife, the `search` method in the Chef Infra Language, the search box in the Chef management console, and by using the `/search` or `/search/INDEX` endpoints in the Chef Infra Server API. The search engine is based on Elasticsearch and is run from the Chef Infra Server. Use the `search` method to perform a search query against the Chef Infra Server from within a recipe. The syntax for the `search` method is as follows: ``` search(:index, 'query') ``` where: * `:index` is of name of the index on the Chef Infra Server against which the search query will run: `:client`, `:data_bag_name`, `:environment`, `:node`, and `:role` * `'query'` is a valid search query against an object on the Chef Infra Server (see below for more information about how to build the query) For example, using the results of a search query within a variable: ``` webservers = search(:node, 'role:webserver') ``` and then using the results of that query to populate a template: ``` template '/tmp/list_of_webservers' do source 'list_of_webservers.erb' variables(:webservers => webservers) end ``` ### :filter_result Use `:filter_result` as part of a search query to filter the search output based on the pattern specified by a Hash. Only attributes in the Hash will be returned. The syntax for the `search` method that uses `:filter_result` is as follows: ``` search(:index, 'query', filter_result: { 'foo' => [ 'abc' ], 'bar' => [ '123' ], 'baz' => %w(sea power), } ).each do |result| puts result['foo'] puts result['bar'] puts result['baz'] end ``` where: * `:index` is of name of the index on the Chef Infra Server against which the search query will run: `:client`, `:data_bag_name`, `:environment`, `:node`, and `:role` * `'query'` is a valid search query against an object on the Chef server * `:filter_result` defines a Hash of values to be returned For example: ``` search(:node, 'role:web', filter_result: { 'name' => [ 'name' ], 'ip' => [ 'ipaddress' ], 'kernel_version' => %w(kernel version), } ).each do |result| puts result['name'] puts result['ip'] puts result['kernel_version'] end ``` ### Query Syntax A search query is comprised of two parts: the key and the search pattern. A search query has the following syntax: ``` key:search_pattern ``` where `key` is a field name that is found in the JSON description of an indexable object on the Chef Infra Server (a role, node, client, environment, or data bag) and `search_pattern` defines what will be searched for, using one of the following search patterns: exact, wildcard, range, or fuzzy matching. Both `key` and `search_pattern` are case-sensitive; `key` has limited support for multiple character wildcard matching using an asterisk ("*") (and as long as it is not the first character). #### Keys A field name/description pair is available in the JSON object. Use the field name when searching for this information in the JSON object. Any field that exists in any JSON description for any role, node, Chef Infra Client, environment, or data bag can be searched. #### Nested Fields A nested field appears deeper in the JSON data structure. For example, information about a network interface might be several layers deep: `node['network']['interfaces']['en1']`. When nested fields are present in a JSON structure, Chef Infra Client will extract those nested fields to the top-level, flattening them into compound fields that support wildcard search patterns. By combining wildcards with range-matching patterns and wildcard queries, it is possible to perform very powerful searches, such as using the vendor part of the MAC address to find every node that has a network card made by the specified vendor. Consider the following snippet of JSON data: ``` {"network": [ //snipped... "interfaces", {"en1": { "number": "1", "flags": [ "UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST" ], "addresses": { "fe80::fa1e:dfff:fed8:63a2": { "scope": "Link", "prefixlen": "64", "family": "inet6" }, "f8:1e:df:d8:63:a2": { "family": "lladdr" }, "192.0.2.0": { "netmask": "255.255.255.0", "broadcast": "192.168.0.255", "family": "inet" } }, "mtu": "1500", "media": { "supported": { "autoselect": { "options": [ ] } }, "selected": { "autoselect": { "options": [ ] } } }, "type": "en", "status": "active", "encapsulation": "Ethernet" }, //snipped... ``` Before this data is indexed on the Chef Infra Server, the nested fields are extracted into the top level, similar to: ``` "broadcast" => "192.168.0.255", "flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"] "mtu" => "1500" ``` which allows searches like the following to find data that is present in this node: ``` node "broadcast:192.168.0.*" ``` or: ``` node "mtu:1500" ``` or: ``` node "flags:UP" ``` This data is also flattened into various compound fields, which follow the same pattern as the JSON hierarchy and use underscores (`_`) to separate the levels of data, similar to: ``` # ...snip... "network_interfaces_en1_addresses_192.0.2.0_broadcast" => "192.168.0.255", "network_interfaces_en1_addresses_fe80::fa1e:tldr_family" => "inet6", "network_interfaces_en1_addresses" => ["fe80::fa1e:tldr","f8:1e:df:tldr","192.0.2.0"] # ...snip... ``` which allows searches like the following to find data that is present in this node: ``` node "network_interfaces_en1_addresses:192.0.2.0" ``` This flattened data structure also supports using wildcard compound fields, which allow searches to omit levels within the JSON data structure that are not important to the search query. In the following example, an asterisk (`*`) is used to show where the wildcard can exist when searching for a nested field: ``` "network_interfaces_*_flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"] "network_interfaces_*_addresses" => ["fe80::fa1e:dfff:fed8:63a2", "192.0.2.0", "f8:1e:df:d8:63:a2"] "network_interfaces_en0_media_*" => ["autoselect", "none", "1000baseT", "10baseT/UTP", "100baseTX"] "network_interfaces_en1_*" => ["1", "UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST", "fe80::fa1e:dfff:fed8:63a2", "f8:1e:df:d8:63:a2", "192.0.2.0", "1500", "supported", "selected", "en", "active", "Ethernet"] ``` For each of the wildcard examples above, the possible values are shown contained within the brackets. When running a search query, the query syntax for wildcards is to simply omit the name of the node (while preserving the underscores), similar to: ``` network_interfaces__flags ``` This query will search within the `flags` node, within the JSON structure, for each of `UP`, `BROADCAST`, `SMART`, `RUNNING`, `SIMPLEX`, and `MULTICAST`. #### Patterns A search pattern is a way to fine-tune search results by returning anything that matches some type of incomplete search query. There are four types of search patterns that can be used when searching the search indexes on the Chef Infra Server: exact, wildcard, range, and fuzzy. #### Exact Match An exact matching search pattern is used to search for a key with a name that exactly matches a search query. If the name of the key contains spaces, quotes must be used in the search pattern to ensure the search query finds the key. The entire query must also be contained within quotes, so as to prevent it from being interpreted by Ruby or a command shell. The best way to ensure that quotes are used consistently is to quote the entire query using single quotes (' ‘) and a search pattern with double quotes (" “). #### Wildcard Match A wildcard matching search pattern is used to query for substring matches that replace zero (or more) characters in the search pattern with anything that could match the replaced character. There are two types of wildcard searches: * A question mark (`?`) can be used to replace exactly one character (as long as that character is not the first character in the search pattern) * An asterisk (`*`) can be used to replace any number of characters (including zero) #### Range Match A range matching search pattern is used to query for values that are within a range defined by upper and lower boundaries. A range matching search pattern can be inclusive or exclusive of the boundaries. Use square brackets ("[ ]") to denote inclusive boundaries and curly braces ("{ }") to denote exclusive boundaries and with the following syntax: ``` boundary TO boundary ``` where `TO` is required (and must be capitalized). #### Fuzzy Match A fuzzy matching search pattern is used to search based on the proximity of two strings of characters. An (optional) integer may be used as part of the search query to more closely define the proximity. A fuzzy matching search pattern has the following syntax: ``` "search_query"~edit_distance ``` where `search_query` is the string that will be used during the search and `edit_distance` is the proximity. A tilde ("~") is used to separate the edit distance from the search query. #### Operators An operator can be used to ensure that certain terms are included in the results, are excluded from the results, or are not included even when other aspects of the query match. Searches can use the following operators: | Operator | Description | | --- | --- | | `AND` | Use to find a match when both terms exist. | | `OR` | Use to find a match if either term exists. | | `NOT` | Use to exclude the term after `NOT` from the search results. | #### Special Characters A special character can be used to fine-tune a search query and to increase the accuracy of the search results. The following characters can be included within the search query syntax, but each occurrence of a special character must be escaped with a backslash (`\`), also (`/`) must be escaped against the Elasticsearch: ``` + - && | | ! ( ) { } [ ] ^ " ~ * ? : \ / ``` For example: ``` \(1\+1\)\:2 ``` ### Examples The following examples show how the `search` method can be used in a recipe. #### Use the search helper to find users The following example shows how to use the `search` method in the Recipe DSL to search for users: ``` # the following code sample comes from the openvpn cookbook: https://github.com/chef-cookbooks/openvpn search("users", "*:*") do |u| execute "generate-openvpn-#{u['id']}" do command "./pkitool #{u['id']}" cwd '/etc/openvpn/easy-rsa' environment( 'EASY_RSA' => '/etc/openvpn/easy-rsa', 'KEY_CONFIG' => '/etc/openvpn/easy-rsa/openssl.cnf', 'KEY_DIR' => node['openvpn']['key_dir'], 'CA_EXPIRE' => node['openvpn']['key']['ca_expire'].to_s, 'KEY_EXPIRE' => node['openvpn']['key']['expire'].to_s, 'KEY_SIZE' => node['openvpn']['key']['size'].to_s, 'KEY_COUNTRY' => node['openvpn']['key']['country'], 'KEY_PROVINCE' => node['openvpn']['key']['province'], 'KEY_CITY' => node['openvpn']['key']['city'], 'KEY_ORG' => node['openvpn']['key']['org'], 'KEY_EMAIL' => node['openvpn']['key']['email'] ) not_if { File.exist?("#{node['openvpn']['key_dir']}/#{u['id']}.crt") } end %w{ conf ovpn }.each do |ext| template "#{node['openvpn']['key_dir']}/#{u['id']}.#{ext}" do source 'client.conf.erb' variables :username => u['id'] end end execute "create-openvpn-tar-#{u['id']}" do cwd node['openvpn']['key_dir'] command <<-EOH tar zcf #{u['id']}.tar.gz \ ca.crt #{u['id']}.crt #{u['id']}.key \ #{u['id']}.conf #{u['id']}.ovpn \ EOH not_if { File.exist?("#{node['openvpn']['key_dir']}/#{u['id']}.tar.gz") } end end ``` where * the search will use both of the **execute** resources, unless the condition specified by the `not_if` commands are met * the `environments` property in the first **execute** resource is being used to define values that appear as variables in the OpenVPN configuration * the **template** resource tells Chef Infra Client which template to use © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/infra_language/search/About Resources =============== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/resource.md) A resource is a statement of configuration policy that: * Describes the desired state for a configuration item * Declares the steps needed to bring that item to the desired state * Specifies a resource type—such as `package`, `template`, or `service` * Lists additional details (also known as resource properties), as necessary * Are grouped into recipes, which describe working configurations Resource Syntax --------------- A resource is a Ruby block with four components: a type, a name, one (or more) properties (with values), and one (or more) actions. The syntax for a resource is like this: ``` type 'name' do attribute 'value' action :type_of_action end ``` Every resource has its own set of actions and properties. Most properties have default values. Some properties are available to all resources, for example those used to send notifications to other resources and guards that help ensure that some resources are idempotent. For example, a resource that is used to install a tar.gz package for version 1.16.1 may look something like this: ``` package 'tar' do version '1.16.1' action :install end ``` All actions have a default value. Only non-default behaviors of actions and properties need to be specified. For example, the **package** resource’s default action is `:install` and the name of the package defaults to the `name` of the resource. Therefore, it is possible to write a resource block that installs the latest tar.gz package like this: ``` package 'tar' ``` and a resource block that installs a tar.gz package for version 1.6.1 like this: ``` package 'tar' do version '1.16.1' end ``` In both cases, Chef Infra Client will use the default action (`:install`) to install the `tar` package. Additional Information ---------------------- See these guides for additional information about resources: | Topic | Description | | --- | --- | | [Common Properties](../resource_common/index) | Provides a detailed list of the common properties that are available in all resources. | | [Resource Reference](../resources/index) | A reference guide that lists both the common and individual options available to every resource that is bundled into Chef. | | [Custom Resources](../custom_resources/index) | Shows you how to create your own Chef resources. | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resource/Ruby Guide ========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/ruby.md) Ruby is a simple programming language: * Chef uses Ruby as its reference language to define the patterns that are found in resources, recipes, and cookbooks * Use these patterns to configure, deploy, and manage nodes across the network Ruby is also a powerful and complete programming language: * Use the Ruby programming language to make decisions about what should happen to specific resources and recipes * Extend Chef in any manner that your organization requires To learn more about Ruby, see: * [Ruby Documentation](https://www.ruby-lang.org/en/documentation/) * [Ruby Standard Library Documentation](https://www.ruby-doc.org/stdlib/) Chef Infra Client 15 ships with Ruby 2.6 and Chef Infra Client 16 ships with Ruby 2.7. Ruby Basics ----------- This section covers the basics of Ruby. ### Verify Syntax Many people who are new to Ruby often find that it doesn’t take very long to get up to speed with the basics. For example, it’s useful to know how to check the syntax of a Ruby file, such as the contents of a cookbook named `my_cookbook.rb`: ``` ruby -c my_cookbook_file.rb ``` to return: ``` Syntax OK ``` ### Comments Use a comment to explain code that exists in a cookbook or recipe. Anything after a `#` is a comment. ``` # This is a comment. ``` ### Local Variables Assign a local variable: ``` x = 1 ``` ### Math Do some basic arithmetic: ``` 1 + 2 # => 3 2 * 7 # => 14 5 / 2 # => 2 (because both arguments are whole numbers) 5 / 2.0 # => 2.5 (because one of the numbers had a decimal place) 1 + (2 * 3) # => 7 (you can use parentheses to group expressions) ``` ### Strings Work with strings: ``` 'single quoted' # => "single quoted" "double quoted" # => "double quoted" 'It\'s alive!' # => "It's alive!" (the \ is an escape character) '1 + 2 = 5' # => "1 + 2 = 5" (numbers surrounded by quotes behave like strings) ``` Convert a string to uppercase or lowercase. For example, a hostname named “Foo”: ``` node['hostname'].downcase # => "foo" node['hostname'].upcase # => "FOO" ``` #### Ruby in Strings Embed Ruby in a string: ``` x = 'Bob' "Hi, #{x}" # => "Hi, Bob" 'Hello, #{x}' # => "Hello, \#{x}" Notice that single quotes don't work with #{} ``` #### Escape Character Use the backslash character (`\`) as an escape character when quotes must appear within strings. However, you do not need to escape single quotes inside double quotes. For example: ``` 'It\'s alive!' # => "It's alive!" "Won\'t you read Grant\'s book?" # => "Won't you read Grant's book?" ``` #### Interpolation When strings have quotes within quotes, use double quotes (`" "`) on the outer quotes, and then single quotes (`' '`) for the inner quotes. For example: ``` Chef::Log.info("Loaded from aws[#{aws['id']}]") ``` ``` "node['mysql']['secretpath']" ``` ``` "#{ENV['HOME']}/chef.txt" ``` ``` antarctica_hint = hint?('antarctica') if antarctica_hint['snow'] "There are #{antarctica_hint['penguins']} penguins here." else 'There is no snow here, and penguins like snow.' end ``` ### Truths Work with basic truths: ``` true # => true false # => false nil # => nil 0 # => true ( the only false values in Ruby are false # and nil; in other words: if it exists in Ruby, # even if it exists as zero, then it is true.) 1 == 1 # => true ( == tests for equality ) 1 == true # => false ( == tests for equality ) ``` #### Untruths Work with basic untruths (`!` means not!): ``` !true # => false !false # => true !nil # => true 1 != 2 # => true (1 is not equal to 2) 1 != 1 # => false (1 is not equal to itself) ``` #### Convert Truths Convert something to either true or false (`!!` means not not!!): ``` !!true # => true !!false # => false !!nil # => false (when pressed, nil is false) !!0 # => true (zero is NOT false). ``` ### Arrays Create lists using arrays: ``` x = ['a', 'b', 'c'] # => ["a", "b", "c"] x[0] # => "a" (zero is the first index) x.first # => "a" (see?) x.last # => "c" x + ['d'] # => ["a", "b", "c", "d"] x # => ["a", "b", "c"] ( x is unchanged) x = x + ['d'] # => ["a", "b", "c", "d"] x # => ["a", "b", "c", "d"] ``` #### Whitespace Arrays The `%w` syntax is a Ruby shortcut for creating an array without requiring quotes and commas around the elements. For example: ``` if %w(debian ubuntu).include?(node['platform']) # do debian/ubuntu things with the Ruby array %w() shortcut end ``` When `%w` syntax uses a variable, such as `|foo|`, double quoted strings should be used. Right: ``` %w(openssl.cnf pkitool vars Rakefile).each do |foo| template "/etc/openvpn/easy-rsa/#{foo}" do source "#{foo}.erb" ... end end ``` Wrong: ``` %w(openssl.cnf pkitool vars Rakefile).each do |foo| template '/etc/openvpn/easy-rsa/#{foo}' do source '#{foo}.erb' ... end end ``` ##### Example WiX includes several tools – such as `candle` (preprocesses and compiles source files into object files), `light` (links and binds object files to an installer database), and `heat` (harvests files from various input formats). The following example uses a whitespace array and the Chef InSpec `file` audit resource to verify if these three tools are present: ``` %w( candle.exe heat.exe light.exe ).each do |utility| describe file("C:/wix/#{utility}") do it { should be_file } end end ``` ### Hash A Hash is a list with keys and values. Sometimes hashes don’t have a set order: ``` h = { 'first_name' => 'Bob', 'last_name' => 'Jones', } ``` And sometimes they do. For example, first name then last name: ``` h.keys # => ["first_name", "last_name"] h['first_name'] # => "Bob" h['last_name'] # => "Jones" h['age'] = 23 h.keys # => ["first_name", "age", "last_name"] h.values # => ["Jones", "Bob", 23] ``` ### Regular Expressions Use Perl-style regular expressions: ``` 'I believe' =~ /I/ # => 0 (matches at the first character) 'I believe' =~ /lie/ # => 4 (matches at the 5th character) 'I am human' =~ /bacon/ # => nil (no match - bacon comes from pigs) 'I am human' !~ /bacon/ # => true (correct, no bacon here) /give me a ([0-9]+)/ =~ 'give me a 7' # => 0 (matched) ``` ### Statements Use conditions! For example, an `if` statement ``` if false # this won't happen elsif nil # this won't either else # code here will run though end ``` or a `case` statement: ``` x = 'dog' case x when 'fish' # this won't happen when 'dog', 'cat', 'monkey' # this will run else # the else is an optional catch-all end ``` #### if An `if` statement can be used to specify part of a recipe to be used when certain conditions are met. `else` and `elsif` statements can be used to handle situations where either the initial condition is not met or when there are other possible conditions that can be met. Since this behavior is 100% Ruby, do this in a recipe the same way here as anywhere else. For example, using an `if` statement with the `platform` node attribute: ``` if node['platform'] == 'ubuntu' # do ubuntu things end ``` ##### if modifier `if` can be used as a modifier that executes the left side of an expression if the right side of the expression is true. The `if` modifier expression must be a single line, and `else` and `elsif` statements are not supported. In the following example, the `do_ubuntu_thing` function will execute if the platform on a node is Ubuntu. ``` do_ubuntu_thing if platform?('ubuntu') ``` #### case A `case` statement can be used to handle a situation where there are a lot of conditions. Use the `when` statement for each condition, as many as are required. For example, using a `case` statement with the `platform` node attribute: ``` case node['platform'] when 'debian', 'ubuntu' # do debian/ubuntu things when 'redhat', 'centos', 'fedora' # do redhat/centos/fedora things end ``` For example, using a `case` statement with the `platform_family` node attribute: ``` case node['platform_family'] when 'debian' # do things on debian-ish platforms (debian, ubuntu, linuxmint) when 'rhel' # do things on RHEL platforms (redhat, centos, scientific, etc) end ``` ### Call a Method Call a method on something with `.method_name()`: ``` x = 'My String' x.split(' ') # => ["My", "String"] x.split(' ').join(', ') # => "My, String" ``` ### Define a Method Define a method (or a function, if you like): ``` def do_something_useless(first_argument, second_argument) puts "You gave me #{first_argument} and #{second_argument}" end do_something_useless('apple', 'banana') # => "You gave me apple and banana" do_something_useless 1, 2 # => "You gave me 1 and 2" # see how the parentheses are optional if there's no confusion about what to do ``` ### Ruby Class Use the Ruby `File` class in a recipe. Because Chef has the **file** resource, use `File` to use the Ruby `File` class. For example: ``` execute 'apt-get-update' do command 'apt-get update' ignore_failure true not_if { ::File.exist?('/var/lib/apt/periodic/update-success-stamp') } end ``` ### Include a Class Use `:include` to include another Ruby class. For example: ``` ::Chef::DSL::Recipe.include MyCookbook::Helpers ``` In non-Chef Ruby, the syntax is `include` (without the `:` prefix), but without the `:` prefix Chef Infra Client will try to find a provider named `include`. Using the `:` prefix tells Chef Infra Client to look for the specified class that follows. ### Include a Parameter The `include?` method can be used to ensure that a specific parameter is included before an action is taken. For example, using the `include?` method to find a specific parameter: ``` if %w(debian ubuntu).include?(node['platform']) # do debian/ubuntu things end ``` or: ``` if %w(rhel).include?(node['platform_family']) # do RHEL things end ``` Patterns to Follow ------------------ This section covers best practices for cookbook and recipe authoring. ### git Etiquette Although not strictly a Chef style thing, please always ensure your `user.name` and `user.email` are set properly in your `.gitconfig` file. * `user.name` should be your given name (e.g., “<NAME>”) * `user.email` should be an actual, working e-mail address This will prevent commit log entries similar to `"guestuser <<EMAIL>>"`, which are unhelpful. ### Use of Hyphens Cookbook and custom resource names should contain only alphanumeric characters. A hyphen (`-`) is a valid character and may be used in cookbook and custom resource names, but it is discouraged. Chef Infra Client will return an error if a hyphen is not converted to an underscore (`_`) when referencing from a recipe the name of a custom resource in which a hyphen is located. ### Cookbook Naming Use a short organizational prefix for application cookbooks that are part of your organization. For example, if your organization is named SecondMarket, use `sm` as a prefix: `sm_postgresql` or `sm_httpd`. ### Cookbook Versioning * Use semantic versioning when numbering cookbooks. * Only upload stable cookbooks from master. * Only upload unstable cookbooks from the dev branch. Merge to master and bump the version when stable. * Always update CHANGELOG.md with any changes, with the JIRA ticket and a brief description. ### Naming Name things uniformly for their system and component. For example: * attributes: `node['foo']['bar']` * recipe: `foo::bar` * role: `foo-bar` * directories: `foo/bar` (if specific to component), `foo` (if not). For example: `/var/log/foo/bar`. Name attributes after the recipe in which they are primarily used. e.g. `node['postgresql']['server']`. ### Parameter Order Follow this order for information in each resource declaration: * Source * Cookbook * Resource ownership * Permissions * Notifications * Action For example: ``` template '/tmp/foobar.txt' do source 'foobar.txt.erb' owner 'someuser' group 'somegroup' mode '0644' variables( foo: 'bar' ) notifies :reload, 'service[whatever]' action :create end ``` ### File Modes Always specify the file mode with a quoted 3-5 character string that defines the octal mode: ``` mode '755' ``` ``` mode '0755' ``` Wrong: ``` mode 755 ``` ### Specify Resource Action? A resource declaration does not require the action to be specified because Chef Infra Client will apply the default action for a resource automatically if it’s not specified within the resource block. For example: ``` package 'monit' ``` will install the `monit` package because the `:install` action is the default action for the **package** resource. However, if readability of code is desired, such as ensuring that a reader understands what the default action is for a custom resource or stating the action for a resource whose default may not be immediately obvious to the reader, specifying the default action is recommended: ``` ohai 'apache_modules' do action :reload end ``` ### String Quoting Use single-quoted strings in all situations where the string doesn’t need interpolation. #### Whitespace Arrays When `%w` syntax uses a variable, such as `|foo|`, double quoted strings should be used. Right: ``` %w(openssl.cnf pkitool vars Rakefile).each do |foo| template "/etc/openvpn/easy-rsa/#{foo}" do source "#{foo}.erb" ... end end ``` Wrong: ``` %w(openssl.cnf pkitool vars Rakefile).each do |foo| template '/etc/openvpn/easy-rsa/#{foo}' do source '#{foo}.erb' ... end end ``` ### Recipes A recipe should be clean and well-commented. For example: ``` ########### # variables ########### connection_info = { host: '127.0.0.1', port: '3306', username: 'root', password: 'm3y3sqlr00t', } ################# # Mysql resources ################# mysql_service 'default' do port '3306' initial_root_password 'm3y3sqlr00t' action [:create, :start] end mysql_database 'wordpress_demo' do connection connection_info action :create end mysql_database_user 'wordpress_user' do connection connection_info database_name 'wordpress_demo' password 'w0rdpr3ssdem0' privileges [:create, :delete, :select, :update, :insert] action :grant end ################## # Apache resources ################## httpd_service 'default' do listen_ports %w(80) mpm 'prefork' action [:create, :start] end httpd_module 'php' do notifies :restart, 'httpd_service[default]' action :create end ############### # Php resources ############### package 'php-gd' do action :install end package 'php-mysql' do action :install end directory '/etc/php.d' do action :create end template '/etc/php.d/mysql.ini' do source 'mysql.ini.erb' action :create end httpd_config 'php' do source 'php.conf.erb' notifies :restart, 'httpd_service[default]' action :create end ##################### # wordpress resources ##################### directory '/srv/wordpress_demo' do user 'apache' recursive true action :create end tar_extract 'https://wordpress.org/wordpress-4.1.tar.gz' do target_dir '/srv/wordpress_demo' tar_flags ['--strip-components 1'] user 'apache' creates '/srv/wordpress_demo/index.php' action :extract end directory '/srv/wordpress_demo/wp-content' do user 'apache' action :create end httpd_config 'wordpress' do source 'wordpress.conf.erb' variables( servername: 'wordpress', server_aliases: %w(computers.biz www.computers.biz), document_root: '/srv/wordpress_demo' ) notifies :restart, 'httpd_service[default]' action :create end template '/srv/wordpress_demo/wp-config.php' do source 'wp-config.php.erb' owner 'apache' variables( db_name: 'wordpress_demo', db_user: 'wordpress_user', db_password: 'w0rdpr3ssdem0', db_host: '127.0.0.1', db_prefix: 'wp_', db_charset: 'utf8', auth_key: 'You should probably use randomly', secure_auth_key: 'generated strings. These can be hard', logged_in_key: 'coded, pulled from encrypted databags,', nonce_key: 'or a ruby function that accessed an', auth_salt: 'arbitrary data source, such as a password', secure_auth_salt: 'vault. Node attributes could work', logged_in_salt: 'as well, but you take special care', nonce_salt: 'so they are not saved to your chef-server.', allow_multisite: 'false' ) action :create end ``` Cookstyle Linting ----------------- Chef Workstation includes Cookstyle for linting the Ruby-specific and Chef-specific portions of your cookbook code. All cookbooks should pass Cookstyle rules before being uploaded. ``` cookstyle your-cookbook ``` should return `no offenses detected` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ruby/About Unified Mode ================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/unified_mode.md) Unified mode combines the compile and converge stages of the Chef Infra Client run into one phase. When a resource has unified mode enabled, the Chef Infra Client compiles and converges that resource’s action block in one pass and in the order that the code inside that block is compiled, from the beginning to the end. In Chef Infra Client 17 (April 2021) and some earlier versions, the default behavior is `unified_mode false`. Enable unified mode on a custom resource with `unified_mode true`. Chef Infra Client displays a deprecation message with `unified_mode false`. In Chef Infra Client 18 (April 2022), `unified_mode true` will become the default behavior. | Chef Infra Client | Unified Mode | | --- | --- | | 18.x (2022) | Default: `unified_mode true` | | 17.x (2021) | Default: `unified_mode false` | | 16.x (2020) | Default: `unified_mode false` | | 15.3 and higher | Default: `unified_mode false` | | 15.0–15.2 | Not available | | 14.14-14.15 | Default: `unified_mode false` | | Lower than 14.14 | Not available | Enable Unified Mode ------------------- Enable unified mode by adding the `unified_mode true` in the custom resource. You can upgrade most custom resources to use unified mode without additional work other than testing and validation. ``` # enable unified mode unified_mode true provides :myresource actions :run do [...] end ``` Troubleshoot Unified Mode ------------------------- Unified mode changes the execution of a custom resource to run in one phase, in the order that the code is written, from the first line of the code to the last. Custom resources designed to use two phases may need modification. These fall into three general types: * Resources with changes to internal sub-resources * Resources with actions on later resources * Resources that rely on the out-of-order execution When designing a custom resource for unified mode: * Declare a resource first and then declare actions on it * Write resources in run-time order ### Resources with Changes to Internal Sub-resources Some custom resources are designed to create and edit other sub-resources as part of the resource declaration. In unified mode, the Chef Infra Client parses a resource code block that creates or edits a sub-resource and immediately tries to apply that change, even though the sub-resource does not yet exist. This results in the execution of an incomplete resource. For example, with unified mode enabled, this code from the *dhcp cookbook* is designed to create and edit a shared `dhcp_subnet` resource, but it will not work as expected: ``` # 'edit_resource' results in an incomple subresource sr = edit_resource(:dhcp_subnet, "#{new_resource.name}_sharedsubnet_#{subnet}") do owner new_resource.owner group new_resource.group mode new_resource.mode ip_version new_resource.ip_version conf_dir new_resource.conf_dir shared_network true end properties.each do |property, value| sr.send(property, value) end ``` To correct custom resources that change sub-resources during their declaration, you can: * Apply properties in the code block (preferred) * Run the resource explicitly (not preferred) #### Apply Properties in the Code Block This pattern declares the sub-resource in one code block and then changes it in the next code block. This is the preferred pattern in unified mode because all resources execute in order at compile time. ``` dhcp_subnet "#{new_resource.name}_sharedsubnet_#{subnet}" do owner new_resource.owner group new_resource.group mode new_resource.mode ip_version new_resource.ip_version conf_dir new_resource.conf_dir shared_network true properties.each do |property, value| send(property, value) end end ``` #### Run the Resource Explicitly Another solution is to continue saving the resource as a variable, declaring `action :nothing` within the codeblock and then explicitly running the action in another codeblock. The pattern of saving a resource as a variable and then forcing it to run at compile time with an explicit `run_action` works as it has in the past, but it is not a preferred pattern. Unified mode forces resource execution to compile time by default, which makes this pattern redundant. ``` sr = edit_resource(:dhcp_subnet, "#{new_resource.name}_sharedsubnet_#{subnet}") do owner new_resource.owner group new_resource.group mode new_resource.mode ip_version new_resource.ip_version conf_dir new_resource.conf_dir shared_network true action :nothing end properties.each do |property, value| sr.send(property, value) end # Run the action explicitly sr.run_action(:create) ``` Actions on Later Resources -------------------------- Since unified mode executes your resource as it is compiled, `:immediate` notifications that execute later resources are handled differently than in the past. ### `:immediate` Notifications to Later Resources Unified mode delays immediate notifications to later resources. In unified mode the Chef Infra Client saves immediate notifications and executes them when the later resource is parsed. Immediate notifications to prior resources and delayed notifications behave the same as they did before unified mode. The end result of sequentially chaining immediate notifications is the same as before unified mode. Instead of immediately notifying results, the notifications fire *in order* as they are parsed, which has the same outcome. If the parse order and the intended execution order are very different, then the results may be different and are a reflection of the parse order. The changes to sending immediate notification could result in subtle changes to behaviors in some resources, but it is not a breaking change to common patterns of writing resources. Chaining immediate notifications to later resources: ``` remote_file "#{Chef::Config[:file_cache_path]}/myservice.tgz" do source "http://acme.com/myservice.tgz" notifies :extract, "archive_file[myservice.tgz]", :immediately end archive_file "#{Chef::Config[:file_cache_path]}/myservice.tgz" do destination '/srv/myservice' notifies :start, "service[myservice]", :immediately action :nothing end service "myservice" do action :nothing end ``` ### `:before` Notifications to Later Resources In unified mode, you must declare a resource before sending a `before` notification to it. Resources that subscribe to a `before` notification to a later resource must be declared after the resource that triggers the notification. This resource declares a `before` notification to a later resource and will no longer work: ``` package "myservice" do notifies :stop, "service[myservice]", :before notifies :start, "service[myservice]", :immediately end service "myservice" do action :nothing end ``` Instead, declare the resource and then declare actions. For example: ``` service "myservice" do action :nothing end package "myservice" do notifies :stop, "service[myservice]", :before notifies :start, "service[myservice]", :immediately end ``` ### Out of Order Execution Unified mode breaks custom resources that rely on the out-of-order execution of compile-time statements. Move any affected compile-time statements to the location in the code where they are intended to execute. Out-of-order execution is rare. Internally at Chef, none of our custom resources broke during our migration to unified mode. Instead, we discovered a few cases in which custom resource code was intended to run in order, but Chef Infra Client executed it out of order. In these cases, unified mode fixed errors instead of introducing bugs. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/unified_mode/Custom Resource Guide ===================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/custom_resources.md) Chef Infra Client ships with over 150 built-in resources for managing system configuration such as `directory`, `remote_file`, and `windows_firewall`. With Custom Resources you can extend the built-in capabilities of Chef Infra Client to create reusable resources for use anywhere in your infrastructure. * Ship directly in cookbooks * Leverage Chef Infra Client built-in resources and any additional custom Ruby code (if needed) * Behave the same as existing built-in resources in your recipes Syntax ------ The layout for a custom resource is: ``` provides :resource_name property :property_name, RubyType, default: 'value' action :action_a do # a mix of built-in Chef Infra resources and Ruby end action :action_b do # a mix of built-in Chef Infra resources and Ruby end ``` The first action listed is the default action. Write a Custom Resource ----------------------- You’ll write the code for a custom resource in a Ruby file and located in a cookbook’s `/resources` directory (you need to generate the resource first). This code: * Declares the properties of the custom resource * Loads current state of properties for existing resources * Defines each action the custom resource may take ### Generate a Custom Resource The `resources` directory does not exist by default in a cookbook. Generate the `resources` directory and a resource file from the `chef-repo/cookbooks` directory with the command: ``` chef generate resource PATH_TO_COOKBOOK RESOURCE_NAME ``` For example, this command generates a `site` resource in the `custom_web` cookbook: ``` chef generate resource cookbooks/custom_web site ``` The `custom_web` cookbook directory with a custom resource has the structure: ``` ├ cookbooks ├ custom_web ├ .delivery | └ project.toml ├ recipes | └ default.rb ├ resources | └ site.rb ├ test | └ integration | | └ default | | | └ default_test.rb ├ .gitignore ├ CHANGELOG.md ├ chefignore ├ kitchen.yml ├ LICENSE ├ metadata.rb ├ Policyfile.rb └ README.md ``` ### Example Resource This example `site` uses Chef Infra’s built-in `file`, `service` and `package` resources, and includes `:create` and `:delete` actions. It also assumes the existence of a [custom httpd template](../templates/index). The code in this custom resource is similar to a typical recipe because it uses built-in Chef Infra Client resources, with the addition of the property and actions definitions for this custom resource. ``` provides :site property :homepage, String, default: '<h1>Hello world!</h1>' action :create do package 'httpd' service 'httpd' do action [:enable, :start] end file '/var/www/html/index.html' do content new_resource.homepage end end action :delete do package 'httpd' do action :remove end file '/var/www/html/index.html' do action :delete end end ``` where * `site` is the name of the custom resource. The `provides` statement makes the custom resource available for use recipes. * `homepage` sets the default HTML for the `index.html` file with a default value of `'<h1>Hello world!</h1>'` * the `action` block uses the built-in collection of resources to tell Chef Infra Client how to install Apache, start the service, and then create the contents of the file located at `/var/www/html/index.html` * `action :create` is the default resource (because it is listed first); `action :delete` must be called specifically (because it is not the default action) Once written, you can use a custom resource may be used in a recipe with the same syntax as Chef Infra Client built-in resources. ### Syntax Call a resource in a recipe by its `resource_name`. For example: Learn More ---------- Learn Chef interactive tutorial: [Extending Chef Infra: Custom Resources](https://learn.chef.io/courses/course-v1:chef+Infra201+Perpetual/about) See the [Custom Resources Glossary](../custom_resource_glossary/index) for a description of available methods. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/custom_resources/Helpers ======= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/helpers.md) Helper classes enable users to share code between Custom Resources. Rspec method test are possible when code is abstracted into plain Ruby files. Example ------- To include the following helper from `libraries/helpers.rb` ``` #libraries/helpers.rb module Haproxy module cookbook module ResourceHelpers def haproxy_version version = Mixlib::ShellOut.new("haproxy -v | grep version | awk '{ print $3 }'") version.run_command.stdout.to_f end end end end ``` Within a Custom Resource file, use the include directive in the action_class, to include all methods in the specified module. ``` action_class do include Haproxy::Cookbook::ResourceHelpers end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/helpers/Partials ======== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/partials.md) [InfoQ article](https://www.infoq.com/news/2020/05/chef-infra-16/) Resource partials are a way of allowing resources to share common code. We recommend using partials any time you need to share code across three or more resources. If you have three resources all which require the properties, `user` and `group` to be set. Instead of writing those property definitions in each of those files, you can write the property definition in one file and include it in the three resources. The `use` method works similarly to the Ruby `require_relative` command. Write the common properties and place them in a folder within the resources folder. This will stop Chef from considering them to be full resources. ``` # resources/_partial/_user.rb property :user, String, default: 'haproxy' property :group, String String, default: 'haproxy' ``` Then include them in each of the three resources with the use directive: ``` # resources/backend.rb use '_partial/_user' ``` ``` # resources/frontend.rb use '_partial/_user' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/partials/Accumulators ============ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/accumulators.md) This is an advanced topic. You should have already written a Custom Resource and be familiar with: * The built-in Chef Infra [`template`](../resources/template/index) resource * Cookbook execution [`with_run_context`](../infra_language/cookbook_execution/index#with_run_context) Overview -------- An accumulator is a programming pattern that gathers multiple values together. In the context of Custom Resources, the accumulator pattern collects a set of properties from Custom Resources, and then applies the collection to a resource. The steps for setting up an accumulator pattern are: * Declare a resource * Edit the resource * Add both resources to the :root `run_context` * Delay the actions on the resources Example Accumulator: Samba -------------------------- Samba Linux tool systems for supporting sharing resources in a network with Windows systems. Samba uses a single file for configuration. In order to share more than one directory using this configuration file, you need to write multiple `samba_share` resources. The accumulator pattern lets you split out each configuration section into its own resource. * [Share Resource 1](#id-1) * [Share Resource 2](#id-2) ``` samba_share 'first_share' do comment 'exported share 1' path '/srv/export' guest_ok true printable false write_list ['test_user_1'] create_mask '0644' directory_mask '0775' options 'inherit permissions' => 'yes' end ``` ``` samba_share 'second_share' do comment 'exported share 2' path '/srv/export_2' guest_ok false printable false write_list ['test_user_2'] create_mask '0644' directory_mask '0775' create_directory false end ``` Example ------- The following example shows how to: * Setup the template resource * Set the `action` to `:nothing` * Set the `delayed_action` to `:create`. * Add the template resource to the `root` run context, which allows the `samba_share` resource to find it. * Use `edit_resource` to find the template * Use `edit_resource` to add new variables to the existing collection *Note*: This uses the `||=` Ruby method to add a new Hash if one does not exist already. ``` # action for the samba_server custom resource action :create do package 'samba' # We need to force both the server template and the # share templates into the root context to find each other with_run_context :root do template new_resource.config_file do source 'smb.conf.erb' owner 'root' group 'root' mode '0644' cookbook 'samba' variables(samba_options: new_resource.options) action :nothing delayed_action :create end end end # action for the samba_share custom resource action :add do with_run_context :root do edit_resource(:template, new_resource.config_file) do |new_resource| variables[:shares] ||= {} variables[:shares][new_resource.share_name] ||= {} variables[:shares][new_resource.share_name]['comment'] = new_resource.comment variables[:shares][new_resource.share_name]['path'] = new_resource.path end end end ``` Further Reading --------------- * [here](https://github.com/chef/chef/issues/5438#issuecomment-351153222) * [DNSimple](https://blog.dnsimple.com/2017/10/chef-accumulators/) * [HAProxy](https://github.com/sous-chefs/haproxy/blob/a9c24d336c01828fef52cedae8cc445d8dbc21dd/libraries/resource.rb#L22) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/accumulators/Converting Definitions to Custom Resources ========================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/definitions_to_custom_resources.md) Migrating from Definitions to Custom Resources ---------------------------------------------- The definitions feature in Chef Infra has been deprecated and will be removed in a future release. Please migrate existing definitions to Custom Resources. This guide describes how to migrate from an existing Definition to a Custom Resource. If you are creating a Custom Resource from scratch please see the [Custom Resource Getting Started Guide](../custom_resources/index) instead. Definitions ----------- A definition behaved like a compile-time macro that was reusable across recipes. A definition was typically created by wrapping arbitrary code around Chef Infra resources that were declared as if they were in a recipe. A definition was then used in one (or more) actual recipes as if the definition were a resource. Though a definition looks like a resource, and at first glance seems like it could be used interchangeably, some important differences exist. Definitions: * Are not true resources * Are processed when resource collection is compiled, not when a node is converged * Do not support common resource properties, such as `notifies`, `compile_time`, `subscribes`, `only_if`, `not_if`, and `sensitive` * Do not support input validation in passed arguments, unlike a resource which supports validation with properties * Do not support `why-run` mode * Cannot report to Chef Automate * Cannot be tested with ChefSpec * Some Definition parameters have known bugs, and will not be fixed Syntax ------ A definition had four components: * A resource name * Zero or more arguments that define parameters and their default values; if a default value was not specified, it was assumed to be `nil` * A hash that could have been used within a definition’s body to provide access to parameters and their values * The body of the definition The basic syntax of a definition was: ``` define :my_definition_name do body end ``` More commonly, the usage incorporated arguments to the definition: ``` define :my_definition_name, parameter: :argument, parameter: :argument do body(likely referencing the params hash) end ``` The following simple example shows a definition with no arguments (a parameter-less macro in the truest sense): ``` define :prime_myfile do file '/etc/myfile' do content 'some content' end end ``` An example showing the use of parameters, with a parameter named `port` that defaults to `4000` rendered into a **template** resource, would look like: ``` define :prime_myfile, port: 4000 do template '/etc/myfile' do source 'myfile.erb' variables({ port: params[:port], }) end end ``` Or the following definition, which looks like a resource when used in a recipe, but also contained **directory** and **file** resources that were repeated, but with slightly different parameters: ``` define :host_porter, port: 4000, hostname: nil do params[:hostname] ||= params[:name] directory '/etc/#{params[:hostname]}' do recursive true end file '/etc/#{params[:hostname]}/#{params[:port]}' do content 'some content' end end ``` which was then used in a recipe like this: ``` host_porter node['hostname'] do port 4000 end host_porter 'www1' do port 4001 end ``` Migrating to Custom Resources ----------------------------- We highly recommend migrating existing definitions to custom resources to unlock the full feature set of Chef Infra resources. The following example shows a definition and that same definition rewritten as a custom resource. ### Initial Definition Code The following definition processes unique hostnames and ports, passed on as parameters: ``` define :host_porter, port: 4000, hostname: nil do params[:hostname] ||= params[:name] directory '/etc/#{params[:hostname]}' do recursive true end file '/etc/#{params[:hostname]}/#{params[:port]}' do content 'some content' end end ``` ### Migrated to a Custom Resource The definition is improved by rewriting it as a custom resource. This uses properties to accept input and has a single `:create` action: ``` property :port, Integer, default: 4000 property :hostname, String, name_property: true action :create do directory "/etc/#{hostname}" do recursive true end file "/etc/#{hostname}/#{port}" do content 'some content' end end ``` Once written, a custom resource may be used in a recipe just like any resource that is built into Chef Infra. A custom resource gets its name from the cookbook and the name of its file in the `/resources` directory with an underscore (`_`) separating them. For example, a cookbook named `host` with a custom resource file named `porter.rb` in the `/resources` directory would be called `host_porter`. Use it in a recipe like this: ``` host_porter node['hostname'] do port 4000 end ``` or: ``` host_porter 'www1' do port 4001 end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/definitions_to_custom_resources/Custom Resources Notes ====================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/custom_resources_notes.md) Warning This page mentions multiple ways of building custom resources. Chef Software recommends you try the approach outlined in the [Custom Resource documentation](../custom_resources/index) first, before trying the resource/provider pair (older approach) or library type (pure Ruby) approaches. If you run into issues while designing 12.5-style custom resources, please ask for help in the [Chef Mailing List](https://discourse.chef.io) or [file a bug](https://github.com/chef/chef/issues/new) for Chef Infra Client. Custom Resources ---------------- This is the recommended way of writing resources for all users. There are two gotchas which we’re working through: 1. For helper functions that you used to write in your provider code or used to mixin to your provider code, you have to use an `action_class.class_eval do ... end` block. 2. You cannot subclass, and must use mixins for code-sharing (which is really a best practice anyway – e.g. see languages like rust which do not support sub-classing). in `resources/whatever.rb`: ``` resource_name :my_resource provides :my_resource property :foo, String, name_property: true extend MyResourceHelperFunctions # probably only used for common properties which is why you extend with class methods action :run do # helpers must be defined inside the action_class block a_helper() # you will save yourself some pain by referring to properties with `new_resource.foo` and not `foo` # since the latter works most of the time, but will troll you with odd scoping problems, while the # former just works. puts new_resource.foo end action_class.class_eval do include MyProviderHelperFunctions def a_helper end end ``` “Old school” LWRPS ------------------ This method is not recommended, but is preferable to writing library resources/providers (as described below). It has the same functionality as library providers, only you cannot subclass and must use mixins for code sharing (which is good). in `resources/my_resource.rb`: ``` resource_name :my_resource provides :my_resource property :foo, String, name_property: true extend MyResourceHelperFunctions # probably only used for common properties which is why you extend with class methods ``` in `providers/my_resource.rb`: ``` # you have to worry about this def whyrun_supported? true end include MyProviderHelperFunctions def a_helper end action :run do a_helper() # here you have to use new_resource.foo puts new_resource.foo end ``` Library Resources/Providers --------------------------- Library resources are discouraged since you can more easily shoot yourself in the foot. They used to be encouraged back before Chef Infra Client 12.0 `provides` was introduced since it allowed for renaming the resource so that it didn’t have to be prefixed by the cookbook name. There are many ways to go wrong writing library providers. One of the biggest issues is that internal Chef Infra Client code superficially looks like a library provider, but it is not. Chef internal resources do not inherit from `LWRPBase` and we’ve had to manually create resources directly through `Chef::Resource::File.new()`, we also have not been able to `use_inline_resources` and not had access to other niceties that cookbook authors have had access to for years now. We’ve got some modernization of internal Chef cookbook code now and resources like `apt_update` and `apt_repository` in core have started to be written more like cookbook code should be written, but core resources are actually behind the curve and are bad code examples. in `libraries/resource_my_resource.rb`: ``` class MyBaseClass class Resource class MyResource < Chef::Resource::LWRPBase # it is very important to inherit from LWRPBase resource_name :my_resource provides :my_resource property :foo, String, name_property: true extend MyResourceHelperFunctions # probably only used for common properties which is why you extend with class methods end end end ``` in `libraries/resource_my_resource.rb`: ``` class MyBaseClass class Resource class MyProvider < Chef::Provider::LWRPBase # it is very important to inherit from LWRPBase # you have to worry about this def whyrun_supported? true end include MyProviderHelperFunctions def a_helper end # NEVER use `def action_run` here -- you defeat use_inline_resources and will break notifications if you do # If you don't understand how use_inline_resources is built and why you have to use the `action` method, and what the implications are and how resource notifications # break if use_inline_resources is not used and/or is broken, then you should really not be using library providers+resources. You might feel "closer to the metal", # but you're now using a chainsaw without any guard... action :run do a_helper() # here you have to use new_resource.foo puts new_resource.foo end end end end ``` updated_by_last_action ------------------------- Modern Chef Infra Client code (since Chef Client version 11.0.0) should never have provider code which directly sets `updated_by_last_action` itself. THIS CODE IS WRONG: ``` action :run do t = file '/tmp/foo' do content 'foo' end t.run_action(:install) # This is Chef Client 10 code which fell through a timewarp into 2016 -- never use updated_by_last_action in modern Chef Client 11.x/12.x code t.new_resource.updated_by_last_action(true) if t.updated_by_last_action? end ``` That used to be kinda-correct-code-with-awful-edge-cases back in Chef Client version 10. If you’re not using that version of Chef Client, please stop writing actions this way. THIS IS CORRECT: ``` def whyrun_supported? true end action :run do file '/tmp/foo' do content 'foo' end end ``` That is the magic of `use_inline_resources` (and why `use_inline_resources` is turned on by default in Chef Client 12.5 resources) The sub-resources are defined in a sub-resource collection which is compiled and converged as part of the provider executing. Any resources that update in the sub-resource collection cause the resource itself to be updated automatically. Notifications then fire normally off the resource. It also works to arbitrary levels of nesting of sub-sub-sub-resources being updating causing the wrapping resources to update and fire notifications. This also gets the why-run case correct. If all the work that you do in your resource is done by calling sub-resources, then why-run should work automatically. All your sub-resources will be NO-OP’d and will report what they would have done instead of doing it. If you do need to write code which mutates the system through pure-Ruby then you should do so like this: ``` def whyrun_supported? true end action :run do unless ::File.exist?('/tmp/foo') converge_by('touch /tmp/foo') do ::FileUtils.touch '/tmp/foo' end end end ``` When the `converge_by` block is run in why-run mode, it will only log `touch "/tmp/foo"` and will not run the code inside the block. A `converge_by` block that is not wrapped in an idempotency check will always cause the resource to be updated, and will always cause notifications to fire. To prevent this, a properly written resource should wrap all `converge_by` checks with an idempotency check. The [`converge_if_changed`](../custom_resources/index#converge_if_changed) block may be used instead which will wrap a `converge_by` block with an idempotency check for you. ``` action :run do # This code is bad, it lacks an idempotency check here. # It will always be updated # Chef Infra Client runs will always report a resource being updated # It will run the code in the block on every run converge_by('touch /tmp/foo') do ::FileUtils.touch '/tmp/foo' end end ``` Of course it is simpler to just use Chef Infra Client resources when you can. Compare the equivalent implementations: ``` action :run do file '/tmp/foo' end ``` is basically the same as this: ``` action :run do unless ::File.exist?('/tmp/foo') converge_by('touch /tmp/foo') do ::FileUtils.touch '/tmp/foo' end end end ``` You may see a lot of `converge_by` and `updated_by_last_action` in the core chef resources. This is because Chef is written as a declarative language with an imperative language, which means someone has to take the first step and write the declarative file resources in imperative Ruby. As such, core Chef resources may not represent ideal code examples of custom resources. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/custom_resources_notes/Migrating from LWRPs to Custom Resources ======================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/lwrp_to_custom_resources.md) Overview -------- It is no longer recommended to write resources in the **Light Weight Resource Provider (LWRP)** format. This guide describes how to migrate from an existing LWRP to a Custom Resource. If you are creating a Custom Resource from scratch please see the [Custom Resource Getting Started Guide](../custom_resources/index) instead. Convert files to Custom Resources Layout ---------------------------------------- LWRPs consist of two library files: a resource and a provider for that resource. ``` |- libraries |- provider_rvm_ruby.rb |- resource_rvm_ruby.rb ``` These files are merged into one, and moved into the resources directory. ``` |- resources |- rvm_ruby.rb ``` Drop LWRP classes ----------------- LWRPs used classes to separate Provider and Resource behaviors, but Custom Resources do not need this distinction. This means that we remove the class definitions in their entirety, as shown in the following example: ``` #rvm/libraries/resource_rvm_ruby.rb require 'chef/resource/lwrp_base' class Chef class Resource class RvmRuby < Chef::Resource::LWRPBase provides :rvm_ruby self.resource_name = :rvm_ruby default_action :install end end end # rvm/libraries/provider_rvm_ruby.rb require 'chef/provider/lwrp_base' class Chef class Provider class RvmRuby < Chef::Provider::LWRPBase provides :rvm_ruby action :install do remote_file 'rvm_installer' do path "#{Chef::Config[:file_cache_path]}/rvm_installer.sh" source node['rvm']['installer_url'] mode '755' not_if { ::File.exist?("#{Chef::Config[:file_cache_path]}/rvm_installer.sh") } action :create end end end end end ``` Replace the above files with a singular resource: ``` #rvm/resources/rvm_ruby.rb provides :rvm_ruby default_action :install action :install do remote_file 'rvm_installer' do path "#{Chef::Config[:file_cache_path]}/rvm_installer.sh" source node['rvm']['installer_url'] mode '755' not_if { ::File.exist?("#{Chef::Config[:file_cache_path]}/rvm_installer.sh") } action :create end end ``` Remove Attributes ----------------- It is best practice to use properties to change the behavior of resources. In the previous example example we used an attribute to change the `installer_url`. Instead, we should use a property that we can perform checks on. In this case, we can make sure we only accept a String. ``` #rvm/resources/rvm_ruby.rb provides :rvm_ruby default_action :install property installer_url, String, default: 'https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer' action :install do remote_file 'rvm_installer' do path "#{Chef::Config[:file_cache_path]}/rvm_installer.sh" source new_resource.installer_url mode '755' not_if { ::File.exist?("#{Chef::Config[:file_cache_path]}/rvm_installer.sh") } action :create end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/lwrp_to_custom_resources/Common Resource Functionality ============================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/resource_common.md) All resources (including custom resources) share a set of common actions, properties, conditional executions, notifications, and relative path options. Actions ------- The following actions may be used with any resource: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Examples The following examples show how to use common actions in a recipe. **Use the :nothing action** ``` service 'memcached' do action :nothing end ``` Properties ---------- The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Examples The following examples show how to use common properties in a recipe. **Use the ignore_failure common property** ``` gem_package 'syntax' do action :install ignore_failure true end ``` **Use the retries and retry_delay common properties** ``` service 'apache' do action [ :enable, :start ] retries 3 retry_delay 5 end ``` Guards ------ A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. Note When using the `not_if` and `only_if` guards with the **execute** resource, the guard’s environment is inherited from the resource’s environment. For example: ``` execute 'bundle install' do cwd '/myapp' not_if 'bundle check' # This is run from /myapp end ``` ### Properties The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Arguments The following arguments can be used with the `not_if` or `only_if` guard properties: `:user` Specify the user that a command will run as. For example: ``` not_if 'grep adam /etc/passwd', user: 'adam' ``` `:group` Specify the group that a command will run as. For example: ``` not_if 'grep adam /etc/passwd', group: 'adam' ``` `:environment` Specify a Hash of environment variables to be set. For example: ``` not_if 'grep adam /etc/passwd', environment: { 'HOME' => '/home/adam', } ``` `:cwd` Set the current working directory before running a command. For example: ``` not_if 'grep adam passwd', cwd: '/etc' ``` `:timeout` Set a timeout for a command. For example: ``` not_if 'sleep 10000', timeout: 10 ``` ### not_if Examples **Update if not already updated** The following example shows how to use `not_if` to guard against running the `apt-get-update` command when a file already exists that is the same as the updated file: ``` execute 'apt-get-update' do command 'apt-get update' ignore_failure true not_if { ::File.exist?('/var/lib/apt/periodic/update-success-stamp') } end ``` **Ensure a node can resolve a host** The following example shows how to use a custom block of Ruby code to ensure that a node can resolve the host. If the node can resolve the host, Chef Infra Client will do nothing. If the node cannot resolve the host, Chef Infra Client will configure the host: ``` ruby_block 'ensure node can resolve API FQDN' do block do fe = Chef::Util::FileEdit.new('/etc/hosts') fe.insert_line_if_no_match(/#{node['chef-server']['api_fqdn']}/, "127.0.0.1 #{node['chef-server']['api_fqdn']}") fe.write_file end not_if { Resolv.getaddress(node['chef-server']['api_fqdn']) rescue false } end ``` **Prevent installs on older versions** The following example shows how to use `not_if` to prevent ZeroMQ from being installed when the node on which the install is to occur has a version of Red Hat Enterprise Linux that is older than version 6.0: ``` ark 'test_autogen' do url 'https://github.com/zeromq/libzmq/tarball/master' extension 'tar.gz' action :configure not_if { platform_family?('rhel') && node['platform_version'].to_f < 6.0 } end ``` **Set the administrator if not already set** The following example shows how to set the administrator for Nagios on multiple nodes, except when the package already exists on a node: ``` %w(adminpassword adminpassword-repeat).each do |setting| execute "debconf-set-selections::#{node['nagios']['server']['vname']}-cgi::#{node['nagios']['server']['vname']}/#{setting}" do command "echo #{node['nagios']['server']['vname']}-cgi #{node['nagios']['server']['vname']}/#{setting} password #{random_initial_password} | debconf-set-selections" not_if "dpkg -l #{node['nagios']['server']['vname']}" end end ``` ### only_if Examples **Install packages only when necessary** The following example shows how to use `only_if` with one (or more) cookbook attributes to ensure that packages are only installed when necessary. In this case, three attributes exist in the `/attributes/default.rb` file: `use_openssl`, `use_pcre`, and `use_zlib`. Each of these attributes are defined as `false` by default. The `only_if` attributes are used to test for the presence of these packages on the target node before then asking Chef Infra Client to complete the process of installing these packages. If the packages are already present, Chef Infra Client will do nothing. ``` package 'libpcre3-dev' do only_if { node['haproxy']['source']['use_pcre'] } end package 'libssl-dev' do only_if { node['haproxy']['source']['use_openssl'] } end package 'zlib1g-dev' do only_if { node['haproxy']['source']['use_zlib'] } end ``` **Remove a recipe if it belongs to a specific run-list** The following example shows how to use `only_if` to only remove a recipe named `recipe[ntp::undo]`, but only when that recipe is part of the `recipe[ntp::default]` run-list: ``` ruby_block 'remove ntp::undo from run list' do block do node.run_list.remove('recipe[ntp::undo]') end only_if { node.run_list.include?('recipe[ntp::default]') } end ``` **Re-register ASP.Net if it’s already installed** The following example shows how to use `only_if` to ensure that Chef Infra Client will attempt to register ASP.NET only if the executable is installed on the system, on both 32- and 64-bit systems: ``` aspnet_regiis = "#{ENV['WinDir']}\\Microsoft.NET\\Framework\\v4.0.30319\\aspnet_regiis.exe" execute 'Register ASP.NET v4' do command "#{aspnet_regiis} -i" only_if { ::File.exist?(aspnet_regiis) } action :nothing end aspnet_regiis64 = "#{ENV['WinDir']}\\Microsoft.NET\\Framework64\\v4.0.30319\\aspnet_regiis.exe" execute 'Register ASP.NET v4 (x64)' do command "#{aspnet_regiis64} -i" only_if { ::File.exist?(aspnet_regiis64) } action :nothing end ``` Guard Interpreters ------------------ Any resource that passes a string command may also specify the interpreter that will be used to evaluate that string command. This is done by using the `guard_interpreter` property to specify a **script**-based resource. ### Attributes The `guard_interpreter` property may be set to any of the following values: `:bash` Evaluates a string command using the **bash** resource. `:batch` Evaluates a string command using the **batch** resource. Default value (within a **batch** resource block): `:batch`. `:csh` Evaluates a string command using the **csh** resource. `:default` Default. Executes the default interpreter as identified by Chef Infra Client. `:perl` Evaluates a string command using the **perl** resource. `:powershell_script` Evaluates a string command using the **powershell_script** resource. Default value (within a **powershell_script** resource block): `:powershell_script`. `:python` Evaluates a string command using the **python** resource. `:ruby` Evaluates a string command using the **ruby** resource. ### Inheritance The `guard_interpreter` property is set to `:default` by default for the **bash**, **csh**, **perl**, **python**, and **ruby** resources. When the `guard_interpreter` property is set to `:default`, `not_if` or `only_if` guard statements **do not inherit** properties that are defined by the **script**-based resource. Warning The **batch** and **powershell_script** resources inherit properties by default. The `guard_interpreter` property is set to `:batch` or `:powershell_script` automatically when using a `not_if` or `only_if` guard statement within a **batch** or **powershell_script** resource, respectively. For example, the `not_if` guard statement in the following resource example **does not inherit** the `environment` property: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` and requires adding the `environment` property to the `not_if` guard statement so that it may use the `JAVA_HOME` path as part of its evaluation: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started', :environment => 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' end ``` To inherit properties, add the `guard_interpreter` property to the resource block and set it to the appropriate value: * `:bash` for **bash** * `:csh` for **csh** * `:perl` for **perl** * `:python` for **python** * `:ruby` for **ruby** For example, using the same example as from above, but this time adding the `guard_interpreter` property and setting it to `:bash`: ``` bash 'javatooling' do guard_interpreter :bash environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` The `not_if` statement now inherits the `environment` property and will use the `JAVA_HOME` path as part of its evaluation. ### Examples For example, the following code block will ensure the command is evaluated using the default interpreter as identified by Chef Infra Client: ``` resource 'name' do guard_interpreter :default # code end ``` Lazy Evaluation --------------- In some cases, the value for a property cannot be known until the execution phase of a Chef Infra Client run. In this situation, using lazy evaluation of property values can be helpful. Instead of a property being assigned a value, it may instead be assigned a code block. The syntax for using lazy evaluation is as follows: ``` property_name lazy { code_block } ``` where `lazy` is used to tell Chef Infra Client to evaluate the contents of the code block later on in the resource evaluation process (instead of immediately) and `{ code_block }` is arbitrary Ruby code that provides the value. For example, a resource that is **not** doing lazy evaluation: ``` template 'template_name' do # some properties path '/foo/bar' end ``` and a resource block that is doing lazy evaluation: ``` template 'template_name' do # some properties path lazy { ' some Ruby code ' } end ``` In the previous examples, the first resource uses the value `/foo/bar` and the second resource uses the value provided by the code block, as long as the contents of that code block are a valid resource property. The following example shows how to use lazy evaluation with template variables: ``` template '/tmp/canvey_island.txt' do source 'canvey_island.txt.erb' variables( lazy do { canvey_island: node.run_state['sea_power'] } end ) end ``` Notifications ------------- A notification is a property on a resource that listens to other resources in the resource collection and then takes actions based on the notification type (`notifies` or `subscribes`). ### Timers A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. ### Notifies A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` Changed in Chef Client 12.6 to use `:before` timer with the `notifies` and `subscribes` properties to specify that the action on a notified resource should be run before processing the resource block in which the notification is located. #### Examples The following examples show how to use the `notifies` notification in a recipe. **Delay notifications** ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :delayed end ``` **Notify immediately** By default, notifications are `:delayed`, that is they are queued up as they are triggered, and then executed at the very end of a Chef Infra Client run. To run an action immediately, use `:immediately`: ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :immediately end ``` and then Chef Infra Client would immediately run the following: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing end ``` **Notify multiple resources** ``` template '/etc/chef/server.rb' do source 'server.rb.erb' owner 'root' group 'root' mode '0755' notifies :restart, 'service[chef-elasticsearch]', :delayed notifies :restart, 'service[chef-server]', :delayed end ``` **Notify in a specific order** To notify multiple resources, and then have these resources run in a certain order, do something like the following: ``` execute 'foo' do command '...' notifies :create, 'template[baz]', :immediately notifies :install, 'package[bar]', :immediately notifies :run, 'execute[final]', :immediately end template 'baz' do ... notifies :run, 'execute[restart_baz]', :immediately end package 'bar' execute 'restart_baz' execute 'final' do command '...' end ``` where the sequencing will be in the same order as the resources are listed in the recipe: `execute 'foo'`, `template 'baz'`, `execute [restart_baz]`, `package 'bar'`, and `execute 'final'`. **Reload a service** ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' notifies :reload, 'service[apache]', :immediately end ``` **Restart a service when a template is modified** ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :immediately end ``` **Send notifications to multiple resources** To send notifications to multiple resources, just use multiple attributes. Multiple attributes will get sent to the notified resources in the order specified. ``` template '/etc/netatalk/netatalk.conf' do notifies :restart, 'service[afpd]', :immediately notifies :restart, 'service[cnid]', :immediately end service 'afpd' service 'cnid' ``` **Execute a command using a template** The following example shows how to set up IPv4 packet forwarding using the **execute** resource to run a command named `forward_ipv4` that uses a template defined by the **template** resource: ``` execute 'forward_ipv4' do command 'echo > /proc/.../ipv4/ip_forward' action :nothing end template '/etc/file_name.conf' do source 'routing/file_name.conf.erb' notifies :run, 'execute[forward_ipv4]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[forward_ipv4]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. **Restart a service, and then notify a different service** The following example shows how start a service named `example_service` and immediately notify the Nginx service to restart. ``` service 'example_service' do action :start notifies :restart, 'service[nginx]', :immediately end ``` **Restart one service before restarting another** This example uses the `:before` notification to restart the `php-fpm` service before restarting `nginx`: ``` service 'nginx' do action :restart notifies :restart, 'service[php-fpm]', :before end ``` With the `:before` notification, the action specified for the `nginx` resource will not run until action has been taken on the notified resource (`php-fpm`). **Notify when a remote source changes** ``` remote_file '/tmp/couch.png' do source 'http://couchdb.apache.org/img/sketch.png' action :nothing end http_request 'HEAD http://couchdb.apache.org/img/sketch.png' do message '' url 'http://couchdb.apache.org/img/sketch.png' action :head if ::File.exist?('/tmp/couch.png') headers 'If-Modified-Since' => File.mtime('/tmp/couch.png').httpdate end notifies :create, 'remote_file[/tmp/couch.png]', :immediately end ``` ### Subscribes A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Examples The following examples show how to use the `subscribes` notification in a recipe. **Verify a configuration update** Use the `:nothing` action (common to all resources) to prevent the test from starting automatically, and then use the `subscribes` notification to run a configuration test when a change to the template is detected: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing subscribes :run, 'template[/etc/nagios3/configures-nagios.conf]', :immediately end ``` **Reload a service when a template is updated** To reload a service that is based on a template, use the **template** and **service** resources together in the same recipe, similar to the following: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' end service 'apache' do action :enable subscribes :reload, 'template[/tmp/somefile]', :immediately end ``` where the `subscribes` notification is used to reload the service whenever the template is modified. Relative Paths -------------- The following relative paths can be used with any resource: `#{ENV['HOME']}` Use to return the `~` path in Linux and macOS or the `%HOMEPATH%` in Microsoft Windows. ### Examples ``` template "#{ENV['HOME']}/chef-getting-started.txt" do source 'chef-getting-started.txt.erb' mode '0755' end ``` Run in Compile Phase -------------------- Chef Infra Client processes recipes in two phases: 1. First, each resource in the node object is identified and a resource collection is built. All recipes are loaded in a specific order, and then the actions specified within each of them are identified. This is also referred to as the “compile phase”. 2. Next, Chef Infra Client configures the system based on the order of the resources in the resource collection. Each resource then examines the node and performs the necessary steps to complete the action. This is also referred to as the “execution phase”. Typically, actions are processed during the execution phase of a Chef Infra Client run. However, sometimes it is necessary to run an action during the compile phase. For example, a resource can be configured to install a package during the compile phase to ensure that application is available to other resources during the execution phase. Note Use the **chef_gem** resource to install gems that are needed by Chef Infra Client during the execution phase. ### Using the compile_time property Use `.run_action(:some_action)` at the end of a resource block to run the specified action during the compile phase. For example: ``` build_essential 'Install compilers' do action :nothing end.run_action(:install) ``` where `action` is set to `:nothing` to ensure the `run_action` is run during the compile phase and not later during the execution phase. This can be simplified by using the `compile_time` flag in Chef Infra Client 16 and later versions: ``` build_essential 'Install compilers' do compile_time true end ``` That flag both forces the resource to run at compile time and sets the converge action to `:nothing`. The following examples show when (and when not) to use `run_action`. **Using Custom Resources preferred to forcing to compile time** Compile time execution is often used to install gems before requiring them in recipe code. This is a poor pattern since gems may depend on native gems which may require installing compilers at compile time. ``` build_essential 'Install compilers' do compile_time true end chef_gem 'aws-dsk' do compile_time true end require 'aws-sdk' ``` A better strategy is to move the code, which requires the gem, into a custom resource. Since all the actions of custom resources run at converge time, this defers requiring the gem until later in the overall Chef Infra Client execution. Unified mode can also be used in the resource to eliminate compile/converge mode issues entirely: ``` unified_mode true action :run do build_essential 'Install compilers' chef_gem 'aws-sdk' require 'aws-sdk' end ``` **Download and parse a configuration file** A common use case is to download a configuration file, parse it, and then use the values in templates and to control other configuration. An important distinction to make is that the downloaded configuration file only exists in a temporary state to be used by the Chef Infra Client. It will not be used directly by the system or applications that are managed by the Chef Infra Client. To download and parse a JSON file and render it in a template, it makes sense to download the file during compile time: ``` # the remote_file is being downloaded to a temporary file remote_file "#{Chef::Config[:file_cache_path]}/users.json" do source "https://jsonplaceholder.typicode.com/users" compile_time true end # this parsing needs to happen after the remote_file is downloaded, but will # be executed at compile time. array = JSON.parse(IO.read("#{Chef::Config[:file_cache_path]}/users.json") # the `array.last["phone"]` expression here will also be evaluated at compile # time and must be lazied via wrapping the expresssion in `lazy {}` file "/tmp/phone_number.txt" do content array.last["phone"] end ``` This is considerably cleaner than the alternative of lazy evaluating both the parsing of the JSON and the rendering of the data into the file template, which will happen if the `remote_file` resource is not run at compile time: ``` # the execution of this is now deferred remote_file "#{Chef::Config[:file_cache_path]}/users.json" do source "https://jsonplaceholder.typicode.com/users" end # it is necessary due to lexical scoping issues to create this variable here array = nil # the parsing of the JSON is now deferred due to the ruby_block ruby_block "parse JSON" do block do array = JSON.parse(IO.read("#{Chef::Config[:file_cache_path]}/users.json") end end # the argument to the content property must now also be deferred file "/tmp/phone_number.txt" do content lazy { array.last["phone"] } end ``` This is an example of code that overuses deferred execution, uses more “lazy” evaluation, and is considerably harder to understand and write correctly. **Notifications will not work** Resources that are executed during the compile phase cannot notify other resources. For example: ``` execute 'ifconfig' package 'vim-enhanced' do compile_time true notifies :run, 'execute[ifconfig]', :immediately end ``` A better approach in this type of situation is to install the package before the resource collection is built to ensure that it is available to other resources later on. The best approach to this problem is to use `unified mode` which eliminates the compile time and converge time distinction, while allowing notifications to work correctly. **Resources that are forced to compile time by default** The `ohai_hint` and `hostname` resources run at compile time by default. This is due to the fact that later resources may consume the node attributes which are set by those resources leading to excessive use of `lazy` in subsequent resources (and similar issues to the `remote_file` example above). The `chef_gem` resource used to execute at compile time by default, but now we recommend that users move code that executes at compile time to custom resources. Windows File Security --------------------- To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. ### Access Control Lists (ACLs) The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(<NAME>) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` ### Inheritance By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resource_common/alternatives Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [alternatives.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/alternatives.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **alternatives** resource to configure command alternatives in Linux using the alternatives or update-alternatives packages. **New in Chef Infra Client 16.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **alternatives** resource is: ``` alternatives 'name' do link String # default value: "/usr/bin/LINK_NAME" link_name String # default value: 'name' unless specified path String priority String, Integer action Symbol # defaults to :install if not specified end ``` where: * `alternatives` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `link`, `link_name`, `path`, and `priority` are the properties available to this resource. Actions ------- --- The **alternatives** resource has the following actions: `:auto` Set an alternative up in automatic mode with the highest priority automatically selected. `:install` Install an alternative on the system including symlinks. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:refresh` Refresh alternatives. `:remove` Remove an alternative and all associated links. `:set` Set the symlink for an alternative. Properties ---------- --- The **alternatives** resource has the following properties: `link` **Ruby Type:** String | **Default Value:** `/usr/bin/LINK_NAME` The path to the alternatives link. `link_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the link to create. This will be the command you type on the command line such as `ruby` or `gcc`. `path` **Ruby Type:** String The absolute path to the original application binary such as `/usr/bin/ruby27`. `priority` **Ruby Type:** String, Integer The priority of the alternative. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **alternatives** resource in recipes: **Install an alternative**: ``` alternatives 'python install 2' do link_name 'python' path '/usr/bin/python2.7' priority 100 action :install end ``` **Set an alternative**: ``` alternatives 'python set version 3' do link_name 'python' path '/usr/bin/python3' action :set end ``` **Set the automatic alternative state**: ``` alternatives 'python auto' do link_name 'python' action :auto end ``` **Refresh an alternative**: ``` alternatives 'python refresh' do link_name 'python' action :refresh end ``` **Remove an alternative**: ``` alternatives 'python remove' do link_name 'python' path '/usr/bin/python3' action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/alternatives/Custom Resources Glossary ========================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/custom_resource_glossary.md) Chef Infra Client Custom Resources Glossary ------------------------------------------- The following **Domain Specific Language (DSL)** methods are available when writing Custom Resources. For further information about how to write custom resources please see [about custom resources](../custom_resources/index) action_class ------------- `action_class` makes methods available to all actions within a single custom resource. ### Example You have a template that requires `'yes'` or `'no'` written as a `String`, but you would like the user to use `true` or `false` for convenience. To allow both the `:add` and `:remove` actions to have access to this method, place the method in the `action_class` block. ``` property :example, [true, false], default: true action :add do template "file.conf" do source 'file.conf.erb' variables( chocolate: bool_to_string(new_resource.example) ) action :create end end action :remove do template "file.conf" do source 'file.conf.erb' variables( chocolate: bool_to_string(new_resource.example) ) action :delete end end action_class do def bool_to_string(b) b ? 'yes' : 'false' end end ``` converge_if_changed --------------------- Use the `converge_if_changed` method inside an `action` block in a custom resource to compare the desired property values against the current property values (as loaded by the `load_current_value` method). Use the `converge_if_changed` method to ensure that updates only occur when property values on the system are not the desired property values and to otherwise prevent a resource from being converged. To use the `converge_if_changed` method, wrap it around the part of a recipe or custom resource that should only be converged when the current state is not the desired state: ``` action :some_action do converge_if_changed do # some property end end ``` The `converge_if_changed` method may be used multiple times. The following example shows how to use the `converge_if_changed` method to compare the multiple desired property values against the current property values (as loaded by the `load_current_value` method). ``` property :path, String property :content, String property :mode, String # Load the current value for content and mode load_current_value do |new_resource| if ::File.exist?(new_resource.path) content IO.read(new_resource.path) mode ::File.stat(new_resource.path).mode end end action :create do # If the value of content has changed # write file converge_if_changed :content do IO.write(new_resource.path, new_resource.content) end # If the value of mode has changed then # chmod file converge_if_changed :mode do ::File.chmod(new_resource.mode, new_resource.path) end end ``` Chef Infra Client will only update the property values that require updates and will not make changes when the property values are already in the desired state. default_action --------------- The default action in a custom resource is, by default, the first action listed in the custom resource. For example, action `aaaaa` is the default resource: ``` property :property_name, RubyType, default: 'value' ... action :aaaaa do # the first action listed in the custom resource end action :bbbbb do # the second action listed in the custom resource end ``` The `default_action` method may also be used to specify the default action. For example: ``` property :property_name, RubyType, default: 'value' # Define bbbbb aas the default action default_action :bbbbb action :aaaaa do # the first action listed in the custom resource end action :bbbbb do # the second action listed in the custom resource end ``` load_current_value -------------------- Use the `load_current_value` method to load the specified property values from the node, and then use those values when the resource is converged. This method may take a block argument. ``` property :path, String property :content, String property :mode, String load_current_value do |new_resource| if ::File.exist?(new_resource.path) content IO.read(new_resource.path) mode ::File.stat(new_resource.path).mode end end ``` Use the `load_current_value` method to guard against property value being replaced. For example: ``` property :homepage, String property :page_not_found, String load_current_value do if ::File.exist?('/var/www/html/index.html') homepage IO.read('/var/www/html/index.html') end if ::File.exist?('/var/www/html/404.html') page_not_found IO.read('/var/www/html/404.html') end end ``` This ensures the values for `homepage` and `page_not_found` are not changed to the default values when Chef Infra Client configures the node. `current_value_does_not_exist!` ------------------------------- When using the `load_current_value` block, use `current_value_does_not_exist!` to indicate that the value does not exist and that `current_resource` should therefore be `nil`. ``` load_current_value do |new_resource| port_data = powershell_exec(%Q{Get-WmiObject -Class Win32_TCPIPPrinterPort -Filter "Name='#{new_resource.port_name}'"}).result if port_data.empty? current_value_does_not_exist! else ipv4_address port_data["HostAddress"] end endo end ``` new_resource.property ---------------------- Custom resources are designed to use resources that are built into Chef Infra and external custom resources. To disambiguate from the current resource being used and other resources, `new_resource.property` is required. For example: ``` property :command, String, name_property: true property :version, String # Useful properties from the `execute` resource property :cwd, String property :environment, Hash, default: {} property :user, [String, Integer] property :sensitive, [true, false], default: false prefix = '/opt/languages/node' load_current_value do current_value_does_not_exist! if node.run_state['nodejs'].nil? version node.run_state['nodejs'][:version] end action :run do execute 'execute-node' do cwd cwd environment environment user user sensitive sensitive # gsub replaces 10+ spaces at the beginning of the line with nothing command <<-CODE.gsub(/^ {10}/, '') #{prefix}/#{new_resource.version}/#{command} CODE end end ``` The following properties are identical to the properties in the execute resource, which we are embedding in the custom resource. * `property :cwd` * `property :environment` * `property :user` * `property :sensitive` Because both the custom properties and the **execute** properties are identical, this will result in an error message similar to: ``` ArgumentError ------------- wrong number of arguments (0 for 1) ``` To prevent this behavior, use `new_resource.` to tell Chef Infra Client to process the properties from the core resource instead of the properties in the custom resource. For example: ``` property :command, String, name_property: true property :version, String # Useful properties from the `execute` resource property :cwd, String property :environment, Hash, default: {} property :user, [String, Integer] property :sensitive, [true, false], default: false prefix = '/opt/languages/node' load_current_value do current_value_does_not_exist! if node.run_state['nodejs'].nil? version node.run_state['nodejs'][:version] end action :run do execute 'execute-node' do cwd new_resource.cwd environment new_resource.environment user new_resource.user sensitive new_resource.sensitive # gsub replaces 10+ spaces at the beginning of the line with nothing command <<-CODE.gsub(/^ {10}/, '') #{prefix}/#{new_resource.version}/#{new_resource.command} CODE end end ``` where: * `cwd new_resource.cwd` * `environment new_resource.environment` * `user new_resource.user` * `sensitive new_resource.sensitive` Correctly use the properties of the **execute** resource and not the identically-named override properties of the custom resource. property -------- Use the `property` method to define properties for the custom resource. The syntax is: ``` property :property_name, ruby_type, default: 'value', parameter: 'value' ``` where * `:property_name` is the name of the property * `ruby_type` is the optional Ruby type or array of types, such as `String`, `Integer`, `true`, or `false` * `default: 'value'` is the optional default value loaded into the resource * `parameter: 'value'` optional parameters For example, the following properties define `username` and `password` properties with no default values specified: ``` property :username, String property :password, String ``` ruby_type ---------- The property ruby_type is a positional parameter. Use to ensure a property value is of a particular ruby class, such as: * `true` * `false` * `nil` * `String` * `Array` * `Hash` * `Integer` * `Symbol` Use an array of Ruby classes to allow a value to be of more than one type. For example: ``` property :aaaa, String property :bbbb, Integer property :cccc, Hash property :dddd, [true, false] property :eeee, [String, nil] property :ffff, [Class, String, Symbol] property :gggg, [Array, Hash] ``` sensitive --------- A property can be marked sensitive by specifying `sensitive: true` on the property. This prevents the contents of the property from being exported to data collection and sent to an Automate server or shown in the logs of the Chef Infra Client run. validators ---------- {{ dsl/property_validation_parameter }} desired_state -------------- Add `desired_state:` to set the desired state property for a resource. | Allowed values | Default | | --- | --- | | `true` `false` | `true` | * When `true`, the state of the property is determined by the state of the system * When `false`, the value of the property impacts how the resource executes, but it is not determined by the state of the system. For example, if you were to write a resource to create volumes on a cloud provider you would need define properties such as `volume_name`, `volume_size`, and `volume_region`. The state of these properties would determine if your resource needed to converge or not. For the resource to function you would also need to define properties such as `cloud_login` and `cloud_password`. These are necessary properties for interacting with the cloud provider, but their state has no impact on decision to converge the resource or not, so you would set `desired_state` to `false` for these properties. ``` property :volume_name, String property :volume_size, Integer property :volume_region, String property :cloud_login, String, desired_state: false property :cloud_password, String, desired_state: false ``` run_context ------------ Chef loads and tracks the current run in the run context object. root_context property_is_set? ------------------ Use the `property_is_set?` method to check if the value for a property has been passed into the resource. The syntax is: ``` property_is_set?(:property_name) ``` The `property_is_set?` method will return `true` if the property is set. For example, the following custom resource creates and/or updates user properties, but not their password. The `property_is_set?` method checks if the user has specified a password and then tells Chef Infra Client what to do if the password is not identical: ``` action :create do converge_if_changed do shell_out!("rabbitmqctl create_or_update_user #{username} --prop1 #{prop1} ... ") end if property_is_set?(:password) if shell_out("rabbitmqctl authenticate_user #{username}#{password}").error? converge_by "Updating password for user #{username} ..." do shell_out!("rabbitmqctl update_user #{username} --password #{password}") end end end end ``` provides -------- ### Introduced Use the `provides` method to associate multiple custom resource files with the same resources name For example: ``` # Provide my_custom_resource to Redhat 7 and above provides :my_custom_resource, platform: 'redhat' do |node| node['platform_version'].to_i >= 7 end # Provide my_custom_resource to all Redhat platforms provides :my_custom_resource, platform: 'redhat' # Provide my_custom_resource to the RedHat platform family provides :my_custom_resource, platform_family: 'rhel' # Provide my_custom_resource to all linux machines provides :my_custom_resource, os: 'linux' # Provide my_custom_resource, useful if your resource file is not named the same as the resource you want to provide provides :my_custom_resource ``` This allows you to use multiple custom resources files that provide the same resource to the user, but for different operating systems or operation system versions. With this you can eliminate the need for platform or platform version logic within your resources. ### Precedent Use the `provides` method to associate a custom resource with the Recipe DSL on different operating systems. When multiple custom resources use the same DSL, specificity rules are applied to determine the priority, from highest to lowest: 1. provides :my_custom_resource, platform_version: ‘0.1.2’ 2. provides :my_custom_resource, platform: ‘platform_name’ 3. provides :my_custom_resource, platform_family: ‘platform_family’ 4. provides :my_custom_resource, os: ‘operating_system’ 5. provides :my_custom_resource reset_property --------------- Use the `reset_property` method to clear the value for a property as if it had never been set, and then use the default value. For example, to clear the value for a property named `password`: ``` reset_property(:password) ``` coerce ------ `coerce` is used to transform user input into a canonical form. The value is passed in, and the transformed value returned as output. Lazy values will **not** be passed to this method until after they are evaluated. `coerce` is run in the context of the instance, which gives it access to other properties. Here we transform,`true`/`false` in to `yes`, `no` for a template later on. ``` property :browseable, [true, false, String], default: true, coerce: proc { |p| p ? 'yes' : 'no' }, ``` If you are modifying the properties type, you will also need to accept that Ruby type as an input. resource_name -------------- Note The `resource_name` setting is necessary for backwards compatibility with Chef Infra Client 12 through 15. It’s use is no longer recommended, please use the [`provides`](#provides) method instead. Introduced: 12.5 Updated: 16.0 Use the `resource_name` method at the top of a custom resource to declare a custom name for that resource. For example: ``` resource_name :my_resource_name ``` The `resource_name` is only used as a fallback name for display purposes. The `provides` statement is the preferred method of specifying the resources name. In Chef Infra Client 16 and later, the first `provides` in a resource declaration also sets the fallback `resource_name`, so we do not recommend that users set the `resource_name` at all. Deprecating entire resources ---------------------------- Deprecate resources that you no longer wish to maintain. This allows you make breaking changes to enterprise or community cookbooks with friendly notifications to downstream cookbook consumers directly in the Chef Infra Client run. Deprecate the `foo_bar` resource in a cookbook ``` deprecated 'The foo_bar resource has been deprecated and will be removed in the next major release of this cookbook scheduled for 25/01/2021!' property :thing, String, name_property: true action :create do # Chef resource code end ``` Deprecating a property ---------------------- Deprecate the `badly_named` property in a resource: ``` property :badly_named, String, deprecated: 'The badly_named property has been deprecated and will be removed in the next major release of this cookbook scheduled for 12/25/2021!' ``` Deprecate and alias ------------------- Rename a property with a deprecation warning for users of the old property name: ``` deprecated_property_alias 'badly_named', 'really_well_named', 'The badly_named property was renamed really_well_named in the 2.0 release of this cookbook. Please update your cookbooks to use the new property name.' ``` unified_mode ------------- © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/custom_resource_glossary/apt_update Resource ==================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [apt_update.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/apt_update.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **apt_update** resource to manage APT repository updates on Debian and Ubuntu platforms. **New in Chef Infra Client 12.7.** Syntax ------ --- The full syntax for all of the properties that are available to the **apt_update** resource is: ``` apt_update 'name' do frequency Integer # default value: 86400 action Symbol # defaults to :periodic if not specified end ``` where: * `apt_update` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `frequency` is the property available to this resource. Nameless -------- This resource can be **nameless**. Add the resource itself to your recipe to get the default behavior: ``` apt_update ``` will behave the same as: ``` apt_update 'update' ``` Actions ------- --- The **apt_update** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:periodic` Update the Apt repository at the interval specified by the `frequency` property. (default) `:update` Update the Apt repository at the start of a Chef Infra Client run. Properties ---------- --- The **apt_update** resource has the following properties: `frequency` **Ruby Type:** Integer | **Default Value:** `86400` Determines how frequently (in seconds) APT repository updates are made. Use this property when the `:periodic` action is specified. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **apt_update** resource in recipes: **Update the Apt repository at a specified interval**: ``` apt_update 'all platforms' do frequency 86400 action :periodic end ``` **Update the Apt repository at the start of a Chef Infra Client run**: ``` apt_update 'update' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/apt_update/apt_package Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [apt_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/apt_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **apt_package** resource to manage packages on Debian, Ubuntu, and other platforms that use the APT package system. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. Syntax ------ --- A **apt_package** resource block manages a package on a node, typically by installing it. The simplest use of the **apt_package** resource is: `apt_package 'package_name'` which will install the named package using all of the default options and the default action of `:install`. The full syntax for all of the properties that are available to the **apt_package** resource is: ``` apt_package 'name' do default_release String options String, Array overwrite_config_files true, false # default value: false package_name String, Array response_file String response_file_variables Hash # default value: {} timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `apt_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `default_release`, `options`, `overwrite_config_files`, `package_name`, `response_file`, `response_file_variables`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **apt_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:lock` Locks the apt package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:unlock` Unlocks the apt package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **apt_package** resource has the following properties: `default_release` **Ruby Type:** String The default release. For example: `stable`. `options` **Ruby Type:** String, Array One (or more) additional options that are passed to the command. For example, common apt-get directives, such as `--no-install-recommends`. See the [apt-get man page](http://manpages.ubuntu.com/manpages/jammy/en/man8/apt-get.8.html) for the full list. `overwrite_config_files` **Ruby Type:** true, false | **Default Value:** `false` Overwrite existing configuration files with those supplied by the package, if prompted by APT. New in Chef Client 14.0 `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `response_file` **Ruby Type:** String The direct path to the file used to pre-seed a package. `response_file_variables` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of response file variables in the form of {‘VARIABLE’ => ‘VALUE’}. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Examples -------- --- The following examples demonstrate various approaches for using the **apt_package** resource in recipes: **Install a package using package manager**: ``` apt_package 'name of package' do action :install end ``` **Install a package without specifying the default action**: ``` apt_package 'name of package' ``` **Install multiple packages at once**: ``` apt_package %w(package1 package2 package3) ``` **Install without using recommend packages as a dependency**: ``` package 'apache2' do options '--no-install-recommends' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/apt_package/apt_repository Resource ======================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [apt_repository.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/apt_repository.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **apt_repository** resource to specify additional APT repositories. Adding a new repository will update the APT package cache immediately. **New in Chef Infra Client 12.9.** Syntax ------ --- The full syntax for all of the properties that are available to the **apt_repository** resource is: ``` apt_repository 'name' do arch String, false cache_rebuild true, false # default value: true components Array # default value: `main` if using a PPA repository. cookbook String, false deb_src true, false # default value: false distribution String, false # default value: The LSB codename of the node such as 'focal'. key String, Array, false # default value: [] key_proxy String, false keyserver String, false # default value: "keyserver.ubuntu.com" repo_name String # default value: 'name' unless specified trusted true, false # default value: false uri String action Symbol # defaults to :add if not specified end ``` where: * `apt_repository` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `arch`, `cache_rebuild`, `components`, `cookbook`, `deb_src`, `distribution`, `key`, `key_proxy`, `keyserver`, `repo_name`, `trusted`, and `uri` are the properties available to this resource. Actions ------- --- The **apt_repository** resource has the following actions: `:add` Creates a repository file at `/etc/apt/sources.list.d/` and builds the repository listing. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes the repository listing. Properties ---------- --- The **apt_repository** resource has the following properties: `arch` **Ruby Type:** String, false Constrain packages to a particular CPU architecture such as `i386` or `amd64`. `cache_rebuild` **Ruby Type:** true, false | **Default Value:** `true` Determines whether to rebuild the APT package cache. `components` **Ruby Type:** Array | **Default Value:** ``main` if using a PPA repository.` Package groupings, such as ‘main’ and ‘stable’. `cookbook` **Ruby Type:** String, false If key should be a cookbook_file, specify a cookbook where the key is located for files/default. Default value is nil, so it will use the cookbook where the resource is used. `deb_src` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not to add the repository as a source repo as well. `distribution` **Ruby Type:** String, false | **Default Value:** `The LSB codename of the node such as 'focal'.` Usually a distribution’s codename, such as `xenial`, `bionic`, or `focal`. `key` **Ruby Type:** String, Array, false | **Default Value:** `[]` If a keyserver is provided, this is assumed to be the fingerprint; otherwise it can be either the URI of GPG key for the repo, or a cookbook_file. `key_proxy` **Ruby Type:** String, false If set, a specified proxy is passed to GPG via `http-proxy=`. `keyserver` **Ruby Type:** String, false | **Default Value:** `keyserver.ubuntu.com` The GPG keyserver where the key for the repo should be retrieved. `repo_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the repository name if it differs from the resource block’s name. The value of this setting must not contain spaces. New in Chef Client 14.1 `trusted` **Ruby Type:** true, false | **Default Value:** `false` Determines whether you should treat all packages from this repository as authenticated regardless of signature. `uri` **Ruby Type:** String The base of the Debian distribution. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **apt_repository** resource in recipes: **Add repository with basic settings**: ``` apt_repository 'nginx' do uri 'http://nginx.org/packages/ubuntu/' components ['nginx'] end ``` **Enable Ubuntu multiverse repositories**: ``` apt_repository 'security-ubuntu-multiverse' do uri 'http://security.ubuntu.com/ubuntu' distribution 'xenial-security' components ['multiverse'] deb_src true end ``` **Add the Nginx PPA, autodetect the key and repository url**: ``` apt_repository 'nginx-php' do uri 'ppa:nginx/stable' end ``` **Add the JuJu PPA, grab the key from the Ubuntu keyserver, and add source repo**: ``` apt_repository 'juju' do uri 'ppa:juju/stable' components ['main'] distribution 'xenial' key 'C8068B11' action :add deb_src true end ``` **Add repository that requires multiple keys to authenticate packages**: ``` apt_repository 'rundeck' do uri 'https://dl.bintray.com/rundeck/rundeck-deb' distribution '/' key ['379CE192D401AB61', 'http://rundeck.org/keys/BUILD-GPG-KEY-Rundeck.org.key'] keyserver 'keyserver.ubuntu.com' action :add end ``` **Add the Cloudera Repo of CDH4 packages for Ubuntu 16.04 on AMD64**: ``` apt_repository 'cloudera' do uri 'http://archive.cloudera.com/cdh4/ubuntu/xenial/amd64/cdh' arch 'amd64' distribution 'xenial-cdh4' components ['contrib'] key 'http://archive.cloudera.com/debian/archive.key' end ``` **Remove a repository from the list**: ``` apt_repository 'zenoss' do action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/apt_repository/apt_preference Resource ======================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [apt_preference.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/apt_preference.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **apt_preference** resource to create APT [preference files](https://wiki.debian.org/AptPreferences). Preference files are used to control which package versions and sources are prioritized during installation. **New in Chef Infra Client 13.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **apt_preference** resource is: ``` apt_preference 'name' do glob String package_name String # default value: 'name' unless specified pin String pin_priority String, Integer action Symbol # defaults to :add if not specified end ``` where: * `apt_preference` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `glob`, `package_name`, `pin`, and `pin_priority` are the properties available to this resource. Actions ------- --- The **apt_preference** resource has the following actions: `:add` Creates a preferences file under `/etc/apt/preferences.d`. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes the preferences file, thus unpinning the package. Properties ---------- --- The **apt_preference** resource has the following properties: `glob` **Ruby Type:** String Pin by a `glob()` expression or with a regular expression surrounded by `/`. `package_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the package name if it differs from the resource block’s name. `pin` **Ruby Type:** String | `REQUIRED` The package version or repository to pin. `pin_priority` **Ruby Type:** String, Integer | `REQUIRED` Sets the Pin-Priority for a package. See <https://wiki.debian.org/AptPreferences> for more details. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **apt_preference** resource in recipes: **Pin libmysqlclient16 to a version 5.1.49-3**: ``` apt_preference 'libmysqlclient16' do pin 'version 5.1.49-3' pin_priority '700' end ``` Note: The `pin_priority` of `700` ensures that this version will be preferred over any other available versions. **Unpin a libmysqlclient16**: ``` apt_preference 'libmysqlclient16' do action :remove end ``` **Pin all packages to prefer the packages.dotdeb.org repository**: ``` apt_preference 'dotdeb' do glob '*' pin 'origin packages.dotdeb.org' pin_priority '700' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/apt_preference/batch Resource ============== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [batch.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/batch.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **batch** resource to execute a batch script using the cmd.exe interpreter on Windows. The batch resource creates and executes a temporary file (similar to how the script resource behaves), rather than running the command inline. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. Syntax ------ --- A **batch** resource block executes a batch script using the cmd.exe interpreter: ``` batch 'echo some env vars' do code <<-EOH echo %TEMP% echo %SYSTEMDRIVE% echo %PATH% echo %WINDIR% EOH end ``` The full syntax for all of the properties that are available to the **batch** resource is: ``` batch 'name' do architecture Symbol code String command String, Array creates String cwd String flags String group String, Integer guard_interpreter Symbol interpreter String returns Integer, Array timeout Integer, Float user String password String domain String action Symbol # defaults to :run if not specified end ``` where: * `batch` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `architecture`, `code`, `command`, `creates`, `cwd`, `flags`, `group`, `guard_interpreter`, `interpreter`, `returns`, `timeout`, `user`, `password` and `domain` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **batch** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Run a batch file. Properties ---------- --- The **batch** resource has the following properties: `architecture` **Ruby Type:** Symbol The architecture of the process under which a script is executed. If a value is not provided, Chef Infra Client defaults to the correct value for the architecture, as determined by Ohai. An exception is raised when anything other than `:i386` is specified for a 32-bit process. Possible values: `:i386` (for 32-bit processes) and `:x86_64` (for 64-bit processes). `code` **Ruby Type:** String | `REQUIRED` A quoted string of code to be executed. `command` **Ruby Type:** String, Array The name of the command to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `guard_interpreter` **Ruby Type:** Symbol | **Default Value:** `:batch` When this property is set to `:batch`, the 64-bit version of the cmd.exe shell will be used to evaluate strings values for the `not_if` and `only_if` properties. Set this value to `:default` to use the 32-bit version of the cmd.exe shell. `interpreter` **Ruby Type:** String The script interpreter to use during code execution. Changing the default value of this property is not supported. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. domainuser or [<EMAIL>](mailto:<EMAIL>) via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified. `password` **Ruby Type:** String *Windows only*: The password of the user specified by the user property. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. `domain` **Ruby Type:** String *Windows only*: The domain of the user user specified by the user property. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef Infra Client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **batch** resource in recipes: Unzip a file, and then move it To run a batch file that unzips and then moves Ruby, do something like: ``` batch 'unzip_and_move_ruby' do code <<-EOH 7z.exe x #{Chef::Config[:file_cache_path]}/ruby-1.8.7-p352-i386-mingw32.7z -oC:\\source -r -y xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y EOH end batch 'echo some env vars' do code <<-EOH echo %TEMP% echo %SYSTEMDRIVE% echo %PATH% echo %WINDIR% EOH end ``` or: ``` batch 'unzip_and_move_ruby' do code <<-EOH 7z.exe x #{Chef::Config[:file_cache_path]}/ruby-1.8.7-p352-i386-mingw32.7z -oC:\\source -r -y xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y EOH end batch 'echo some env vars' do code 'echo %TEMP%\\necho %SYSTEMDRIVE%\\necho %PATH%\\necho %WINDIR%' end ``` Run a command as an alternate user *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] domain "domain" user "username" password "password" end # Passing username = 'domain-name\\username'. No domain is passed batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "domain-name\\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/batch/bash Resource ============= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [bash.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/bash.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **bash** resource to execute scripts using the Bash interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. Syntax ------ --- A **bash** resource block executes scripts using Bash: ``` bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` where: * `cwd` specifies the directory from which the command is run * `code` specifies the command to run The full syntax for all of the properties that are available to the **bash** resource is: ``` bash 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `bash` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **bash** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a script. Properties ---------- --- The **bash** resource has the following properties: `code` **Ruby Type:** String | `REQUIRED` A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **bash** resource in recipes: Use a named provider to run a script ``` bash 'install_something' do user 'root' cwd '/tmp' code <<-EOH wget http://www.example.com/tarball.tar.gz tar -zxf tarball.tar.gz cd tarball ./configure make make install EOH end ``` Install a file from a remote location using bash The following is an example of how to install the `foo123` module for Nginx. This module adds shell-style functionality to an Nginx configuration file and does the following: * Declares three variables * Gets the Nginx file from a remote location * Installs the file using Bash to the path specified by the `src_filepath` variable ``` # the following code sample is similar to the ``upload_progress_module`` # recipe in the ``nginx`` cookbook: # https://github.com/chef-cookbooks/nginx src_filename = "foo123-nginx-module-v#{ node['nginx']['foo123']['version'] }.tar.gz" src_filepath = "#{Chef::Config['file_cache_path']}/#{src_filename}" extract_path = "#{ Chef::Config['file_cache_path'] }/nginx_foo123_module/#{ node['nginx']['foo123']['checksum'] }" remote_file 'src_filepath' do source node['nginx']['foo123']['url'] checksum node['nginx']['foo123']['checksum'] owner 'root' group 'root' mode '0755' end bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` Install an application from git using bash The following example shows how Bash can be used to install a plug-in for rbenv named `ruby-build`, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which `ruby-build` is located, and then runs a command. ``` git "#{Chef::Config[:file_cache_path]}/ruby-build" do repository 'git://github.com/sstephenson/ruby-build.git' revision 'master' action :sync end bash 'install_ruby_build' do cwd "#{Chef::Config[:file_cache_path]}/ruby-build" user 'rbenv' group 'rbenv' code <<-EOH ./install.sh EOH environment 'PREFIX' => '/usr/local' end ``` To read more about `ruby-build`, see here: <https://github.com/sstephenson/ruby-build>. Store certain settings The following recipe shows how an attributes file can be used to store certain settings. An attributes file is located in the `attributes/` directory in the same cookbook as the recipe which calls the attributes file. In this example, the attributes file specifies certain settings for Python that are then used across all nodes against which this recipe will run. Python packages have versions, installation directories, URLs, and checksum files. An attributes file that exists to support this type of recipe would include settings like the following: ``` default['python']['version'] = '2.7.1' if python['install_method'] == 'package' default['python']['prefix_dir'] = '/usr' else default['python']['prefix_dir'] = '/usr/local' end default['python']['url'] = 'http://www.python.org/ftp/python' default['python']['checksum'] = '80e387...85fd61' ``` and then the methods in the recipe may refer to these values. A recipe that is used to install Python will need to do the following: * Identify each package to be installed (implied in this example, not shown) * Define variables for the package `version` and the `install_path` * Get the package from a remote location, but only if the package does not already exist on the target system * Use the **bash** resource to install the package on the node, but only when the package is not already installed ``` # the following code sample comes from the ``oc-nginx`` cookbook on |github|: https://github.com/cookbooks/oc-nginx version = node['python']['version'] install_path = "#{node['python']['prefix_dir']}/lib/python#{version.split(/(^\d+\.\d+)/)[1]}" remote_file "#{Chef::Config[:file_cache_path]}/Python-#{version}.tar.bz2" do source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2" checksum node['python']['checksum'] mode '0755' not_if { ::File.exist?(install_path) } end bash 'build-and-install-python' do cwd Chef::Config[:file_cache_path] code <<-EOF tar -jxvf Python-#{version}.tar.bz2 (cd Python-#{version} && ./configure #{configure_options}) (cd Python-#{version} && make && make install) EOF not_if { ::File.exist?(install_path) } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/bash/archive_file Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [archive_file.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/archive_file.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **archive_file** resource to extract archive files to disk. This resource uses the libarchive library to extract multiple archive formats including tar, gzip, bzip, and zip formats. **New in Chef Infra Client 15.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **archive_file** resource is: ``` archive_file 'name' do destination String group String mode String, Integer # default value: "'755'" options Array, Symbol overwrite true, false, auto # default value: false owner String path String # default value: 'name' unless specified strip_components Integer # default value: 0 action Symbol # defaults to :extract if not specified end ``` where: * `archive_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `destination`, `group`, `mode`, `options`, `overwrite`, `owner`, `path`, and `strip_components` are the properties available to this resource. Actions ------- --- The **archive_file** resource has the following actions: `:extract` Extract and archive file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **archive_file** resource has the following properties: `destination` **Ruby Type:** String | `REQUIRED` The file path to extract the archive file to. `group` **Ruby Type:** String The group of the extracted files. `mode` **Ruby Type:** String, Integer | **Default Value:** `'755'` The mode of the extracted files. Integer values are deprecated as octal values (ex. 0755) would not be interpreted correctly. `options` **Ruby Type:** Array, Symbol | **Default Value:** `lazy default` An array of symbols representing extraction flags. Example: `:no_overwrite` to prevent overwriting files on disk. By default, this properly sets `:time` which preserves the modification timestamps of files in the archive when writing them to disk. `overwrite` **Ruby Type:** true, false, auto | **Default Value:** `false` Should the resource overwrite the destination file contents if they already exist? If set to `:auto` the date stamp of files within the archive will be compared to those on disk and disk contents will be overwritten if they differ. This may cause unintended consequences if disk date stamps are changed between runs, which will result in the files being overwritten during each client run. Make sure to properly test any change to this property. `owner` **Ruby Type:** String The owner of the extracted files. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the file path to the archive to extract if it differs from the resource block’s name. `strip_components` **Ruby Type:** Integer | **Default Value:** `0` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. This behaves similarly to tar’s –strip-components command line argument. New in Chef Infra Client 17.5 Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **archive_file** resource in recipes: **Extract a zip file to a specified directory**: ``` archive_file 'Precompiled.zip' do path '/tmp/Precompiled.zip' destination '/srv/files' end ``` **Set specific permissions on the extracted files**: ``` archive_file 'Precompiled.zip' do owner 'tsmith' group 'staff' mode '700' path '/tmp/Precompiled.zip' destination '/srv/files' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/archive_file/bff_package Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [bff_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/bff_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **bff_package** resource to manage packages for the AIX platform using the installp utility. When a package is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. Note A Backup File Format (BFF) package may not have a `.bff` file extension. Chef Infra Client will still identify the correct provider to use based on the platform, regardless of the file extension. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. Syntax ------ --- The full syntax for all of the properties that are available to the **bff_package** resource is: ``` bff_package 'name' do options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `bff_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **bff_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. Properties ---------- --- The **bff_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String Required. The path to a package in the local file system. The AIX platform requires `source` to be a local file system path because `installp` does not retrieve packages using HTTP or FTP. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **bff_package** resource in recipes: The **bff_package** resource is the default package provider on the AIX platform. The base **package** resource may be used, and then when the platform is AIX, Chef Infra Client will identify the correct package provider. The following examples show how to install part of the IBM XL C/C++ compiler. **Installing using the base package resource** ``` package 'xlccmp.13.1.0' do source '/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0' action :install end ``` **Installing using the bff_package resource** ``` bff_package 'xlccmp.13.1.0' do source '/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0' action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/bff_package/build_essential Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [build_essential.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/build_essential.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **build_essential** resource to install the packages required for compiling C software from source. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **build_essential** resource is: ``` build_essential 'name' do raise_if_unsupported true, false # default value: false action Symbol # defaults to :install if not specified end ``` where: * `build_essential` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `raise_if_unsupported` is the property available to this resource. Nameless -------- This resource can be **nameless**. Add the resource itself to your recipe to get the default behavior: ``` build_essential ``` will behave the same as: ``` build_essential 'install tools' ``` Actions ------- --- The **build_essential** resource has the following actions: `:install` Install build essential packages. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:upgrade` Upgrade the Xcode CLI Tools on macOS hosts. **New in Chef Infra Client 16** Properties ---------- --- The **build_essential** resource has the following properties: `raise_if_unsupported` **Ruby Type:** true, false | **Default Value:** `false` Raise a hard error on platforms where this resource is unsupported. New in Chef Infra Client 15.5 Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **build_essential** resource in recipes: **Install compilation packages**: ``` build_essential ``` **Install compilation packages during the compilation phase**: ``` build_essential 'Install compilation tools' do compile_time true end ``` **Upgrade compilation packages on macOS systems**: ``` build_essential 'Install compilation tools' do action :upgrade end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/build_essential/cab_package Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [cab_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/cab_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **cab_package** resource to install or remove Microsoft Windows cabinet (.cab) packages. **New in Chef Infra Client 12.15.** Syntax ------ --- The full syntax for all of the properties that are available to the **cab_package** resource is: ``` cab_package 'name' do options String, Array package_name String source String # default value: The package name. timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `cab_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **cab_package** resource has the following actions: `:install` Installs the cabinet package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes the cabinet package. Properties ---------- --- The **cab_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String | **Default Value:** `The package name.` The local file path or URL for the CAB package. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **cab_package** resource in recipes: **Using local path in source** ``` cab_package 'Install .NET 3.5 sp1 via KB958488' do source 'C:\Users\xyz\AppData\Local\Temp\Windows6.1-KB958488-x64.cab' action :install end cab_package 'Remove .NET 3.5 sp1 via KB958488' do source 'C:\Users\xyz\AppData\Local\Temp\Windows6.1-KB958488-x64.cab' action :remove end ``` **Using URL in source** ``` cab_package 'Install .NET 3.5 sp1 via KB958488' do source 'https://s3.amazonaws.com/my_bucket/Windows6.1-KB958488-x64.cab' action :install end cab_package 'Remove .NET 3.5 sp1 via KB958488' do source 'https://s3.amazonaws.com/my_bucket/Temp\Windows6.1-KB958488-x64.cab' action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/cab_package/breakpoint Resource =================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [breakpoint.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/breakpoint.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **breakpoint** resource to add breakpoints to recipes. Run the chef-shell in Chef Infra Client mode, and then use those breakpoints to debug recipes. Breakpoints are ignored by the chef-client during an actual chef-client run. That said, breakpoints are typically used to debug recipes only when running them in a non-production environment, after which they are removed from those recipes before the parent cookbook is uploaded to the Chef server. **New in Chef Infra Client 12.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **breakpoint** resource is: ``` breakpoint 'name' do action Symbol # defaults to :break if not specified end ``` where: * `breakpoint` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. Actions ------- --- The **breakpoint** resource has the following actions: `:break` Add a breakpoint for use with chef-shell (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- This resource does not have any properties. Debug Recipes with chef-shell ----------------------------- chef-shell is a recipe debugging tool that allows the use of breakpoints within recipes. chef-shell runs as an Interactive Ruby (IRb) session. chef-shell supports both recipe and attribute file syntax, as well as interactive debugging features. ### Modes chef-shell is tool that is run using an Interactive Ruby (IRb) session. chef-shell currently supports recipe and attribute file syntax, as well as interactive debugging features. chef-shell has three run modes: | Mode | Description | | --- | --- | | Standalone | Default. No cookbooks are loaded, and the run-list is empty. | | Solo | chef-shell acts as a Chef Solo Client. It attempts to load the chef-solo configuration file at `~/.chef/config.rb` and any JSON attributes passed. If the JSON attributes set a run-list, it will be honored. Cookbooks will be loaded in the same way that chef-solo loads them. chef-solo mode is activated with the `-s` or `--solo` command line option, and JSON attributes are specified in the same way as for chef-solo, with `-j /path/to/chef-solo.json`. | | Client | chef-shell acts as a Chef Infra Client. During startup, it reads the Chef Infra Client configuration file from `~/.chef/client.rb` and contacts the Chef Infra Server to get the node's run_list, attributes, and cookbooks. Chef Infra Client mode is activated with the `-z` or `--client` options. You can also specify the configuration file with `-c CONFIG` and the server URL with `-S SERVER_URL`. | ### Configure chef-shell determines which configuration file to load based on the following: 1. If a configuration file is specified using the `-c` option, chef-shell will use the specified configuration file 2. If a NAMED_CONF is given, chef-shell will load ~/.chef/NAMED_CONF/chef_shell.rb 3. If no NAMED_CONF is given chef-shell will load ~/.chef/chef_shell.rb if it exists 4. If no chef_shell.rb can be found, chef-shell falls back to load: * /etc/chef/client.rb if -z option is given. * /etc/chef/solo.rb if –solo-legacy-mode option is given. * .chef/config.rb if -s option is given. * .chef/knife.rb if -s option is given. #### chef-shell.rb The chef-shell.rb file can be used to configure chef-shell in the same way as the client.rb file is used to configure Chef Infra Client. For example, to configure chef-shell to authenticate to the Chef Infra Server, copy the `node_name`, `client_key`, and `chef_server_url` settings from the config.rb file: ``` node_name 'your-knife-clientname' client_key File.expand_path('~/.chef/my-client.pem') chef_server_url 'https://api.opscode.com/organizations/myorg' ``` and then add them to the chef-shell.rb file. Other configuration possibilities include disabling Ohai plugins (which will speed up the chef-shell boot process) or including arbitrary Ruby code in the chef-shell.rb file. #### Run as a Chef Infra Client By default, chef-shell loads in standalone mode and does not connect to the Chef Infra Server. The chef-shell can be run as a Chef Infra Client to verify functionality that is only available when Chef Infra Client connects to the Chef Infra Server, such as search functionality or accessing data stored in data bags. chef-shell can use the same credentials as knife when connecting to a Chef Infra Server. Make sure that the settings in chef-shell.rb are the same as those in config.rb, and then use the `-z` option as part of the command. For example: ``` chef-shell -z ``` ### Manage When chef-shell is configured to access a Chef Infra Server, chef-shell can list, show, search for and edit cookbooks, clients, nodes, roles, environments, policyfiles, and data bags. The syntax for managing objects on the Chef Infra Server is as follows: ``` chef-shell -z named_configuration ``` Where: * `named_configuration` is an existing configuration file in `~/.chef/named_configuration/chef_shell.rb`, such as `production`, `staging`, or `test`. Once in chef-shell, commands can be run against objects as follows: ``` chef (preprod) > items.command ``` Where: * `items` is the type of item to search for: `cookbooks`, `clients`, `nodes`, `roles`, `environments` or a data bag. * `command` is the command: `list`, `show`, `find`, or `edit`. For example, to list all of the nodes in a configuration named “preprod”, enter: ``` chef (preprod) > nodes.list ``` Which will return something similar to: ``` => [node[i-f09a939b], node[i-049a936f], node[i-eaaaa581], node[i-9154b1fb], node[i-6a213101], node[i-c2687aa9], node[i-7abeaa11], node[i-4eb8ac25], node[i-9a2030f1], node[i-a06875cb], node[i-145f457f], node[i-e032398b], node[i-dc8c98b7], node[i-6afdf401], node[i-f49b119c], node[i-5abfab31], node[i-78b8ac13], node[i-d99678b3], node[i-02322269], node[i-feb4a695], node[i-9e2232f5], node[i-6e213105], node[i-cdde3ba7], node[i-e8bfb083], node[i-743c2c1f], node[i-2eaca345], node[i-aa7f74c1], node[i-72fdf419], node[i-140e1e7f], node[i-f9d43193], node[i-bd2dc8d7], node[i-8e7f70e5], node[i-78f2e213], node[i-962232fd], node[i-4c322227], node[i-922232f9], node[i-c02728ab], node[i-f06c7b9b]] ``` The `list` command can take a code block, which will applied (but not saved), to each object that is returned from the server. For example: ``` chef (preprod) > nodes.list {|n| puts "#{n.name}: #{n.run_list}" } ``` will return something similar to: ``` => i-f09a939b: role[lb], role[preprod], recipe[aws] i-049a936f: role[lb], role[preprod], recipe[aws] i-9154b1fb: recipe[erlang], role[base], role[couchdb], role[preprod], i-6a213101: role[chef], role[preprod] # more... ``` The `show` command can be used to display a specific node. For example: ``` chef (preprod) > load_balancer = nodes.show('i-f09a939b') ``` will return something similar to: ``` => node[i-f09a939b] ``` Or: ``` chef (preprod) > load_balancer.ec2.public_hostname ``` will return something similar to: ``` => "ec2-111-22-333-44.compute-1.amazonaws.com" ``` The `find` command can be used to search the Chef Infra Server from the chef-shell. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') ``` You can also format the results with a code block. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } and nil ``` will return something similar to: ``` => ["ami-f8927a91", "ami-f8927a91", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1" # and more... ``` Or: ``` chef (preprod) > amis = nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } chef (preprod) > puts amis.uniq.sort ``` will return something similar to: ``` => ami-4b4ba522 ami-a89870c1 ami-eef61587 ami-f8927a91 ``` ### Use Breakpoints chef-shell allows the current position in a run-list to be manipulated during a Chef Infra Client run. Add breakpoints to a recipe to take advantage of this functionality. #### Step Through Run-list To explore how using the **breakpoint** to manually step through a Chef Infra Client run, create a simple recipe in chef-shell: ``` chef > recipe_mode chef:recipe > echo off chef:recipe > file "/tmp/before-breakpoint" chef:recipe > breakpoint "foo" chef:recipe > file "/tmp/after-breakpoint" ``` and then run Chef Infra Client: ``` chef:recipe > run_chef [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:17:49 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint ``` Chef Infra Client ran the first resource before the breakpoint (`file[/tmp/before-breakpoint]`), but then stopped after execution. Chef Infra Client attempted to name the breakpoint after its position in the source file, but Chef Infra Client was confused because the resource was entered interactively. From here, chef-shell can resume the interrupted Chef Infra Client run: ``` chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:27:08 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` A quick view of the `/tmp` directory shows that the following files were created: ``` after-breakpoint before-breakpoint ``` You can rewind and step through a Chef Infra Client run: ``` chef:recipe > Chef::Log.level = :debug # debug logging won't turn on automatically in this case => :debug chef:recipe > chef_run.rewind => 0 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File => 1 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint => 2 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File => 3 ``` From the output, the rewound run-list is shown, but when the resources are executed again, they will repeat their checks for the existence of files. If they exist, Chef Infra Client will skip creating them. If the files are deleted, then: ``` chef:recipe > ls("/tmp").grep(/breakpoint/).each {|f| rm "/tmp/#{f}" } => ["after-breakpoint", "before-breakpoint"] ``` Rewind, and then resume your Chef Infra Client run to get the expected results: ``` chef:recipe > chef_run.rewind chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:48:56 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:49:20 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` #### Debug Existing Recipe chef-shell can be used to debug existing recipes. The recipe first needs to be added to a run-list for the node, so that it is cached when starting chef-shell and then used for debugging. chef-shell will report which recipes are being cached when it is started: ``` loading configuration: none (standalone session) Session type: standalone Loading.............done. Welcome to the chef-shell 15.8.23 For usage see https://docs.chef.io/chef_shell.html run `help' for help, `exit' or ^D to quit. chef (15.8.23)``` To just load one recipe from the run-list, go into the recipe and use the `include_recipe` command. For example: ``` chef > recipe_mode chef:recipe > include_recipe "getting-started" => [#< Chef::Recipe:0x10256f9e8 @cookbook_name="getting-started", ... output truncated ... ``` To load all of the recipes from a run-list, use code similar to the following: ``` node.run_list.expand(node.chef_environment).recipes.each do |r| include_recipe r end ``` After the recipes that are to be debugged have been loaded, use the `run_chef` command to run them. #### Advanced Debugging In chef-shell, it is possible to get verbose debugging using the tracing feature in Interactive Ruby (IRb). chef-shell provides a shortcut for turning tracing on and off. For example: ``` chef > tracing on tracing is on => nil chef ``` and: ``` chef > tracing off #0:(irb):2:Object:-: tracing off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:109:Shell::Extensions::ObjectCoreExtensions:>: def off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:110:Shell::Extensions::ObjectCoreExtensions:-: :off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:111:Shell::Extensions::ObjectCoreExtensions:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:272:main:>: def tracing(on_or_off) #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:273:main:-: conf.use_tracer = on_or_off.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:162:Shell::Extensions::Symbol:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:163:Shell::Extensions::Symbol:-: to_s.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:149:Shell::Extensions::String:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:150:Shell::Extensions::String:-: case self #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:154:Shell::Extensions::String:-: false #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:158:Shell::Extensions::String:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:164:Shell::Extensions::Symbol:<: end tracing is off => nil chef ``` ### Debug Examples The following examples show how to use chef-shell. #### "Hello World" This example shows how to run chef-shell in standalone mode. (For chef-solo or Chef Infra Client modes, you would need to run chef-shell using the `-s` or `-z` command line options, and then take into consideration the necessary configuration settings.) When Chef Infra Client is installed using RubyGems or a package manager, chef-shell should already be installed. When Chef Infra Client is run from a git clone, it will be located in `chef/bin/chef shell`. To start chef-shell, just run it without any options. You’ll see the loading message, then the banner, and then the chef-shell prompt: ``` bin/chef-shell loading configuration: none (standalone session) Session type: standalone Loading.............done. Welcome to the chef-shell 15.8.23 For usage see https://docs.chef.io/chef_shell.html run `help' for help, `exit' or ^D to quit. chef (15.8.23)``` (Use the help command to print a list of supported commands.) Use the recipe_mode command to switch to recipe context: ``` chef > recipe_mode chef:recipe_mode ``` Typing is evaluated in the same context as recipes. Create a file resource: ``` chef:recipe_mode > file "/tmp/ohai2u_shef" => #< Chef::Resource::File:0x1b691ac @enclosing_provider=nil, @resource_name=:file, @before=nil, @supports={}, @backup=5, @allowed_actions=[:nothing, :create, :delete, :touch, :create_if_missing], @only_if=nil, @noop=nil, @collection=#< Chef::ResourceCollection:0x1b9926c @insert_after_idx=nil, @resources_by_name={"file[/tmp/ohai2u_shef]"=>0}, @resources=[#< Chef::Resource::File:0x1b691ac ...>]>, @updated=false, @provider=nil, @node=< Chef::Node:0xdeeaae @name="eigenstate.local">, @recipe_name=nil, @not_if=nil, @name="/tmp/ohai2u_shef", @action="create", @path="/tmp/ohai2u_shef", @source_line="/Users/username/ruby/chef/chef/(irb#1) line 1", @params={}, @actions={}, @cookbook_name=nil, @ignore_failure=false``` (The previous example was formatted for presentation.) At this point, chef-shell has created the resource and put it in the run-list, but not yet created the file. To initiate a Chef Infra Client run, use the `run_chef` command: ``` chef:recipe_mode > run_chef [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: Processing file[/tmp/ohai2u_shef] [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File [Fri, 15 Jan 2020 10:42:47 -0800] INFO: Creating file[/tmp/ohai2u_shef] at /tmp/ohai2u_shef => true ``` chef-shell can also switch to the same context as attribute files. Set an attribute with the following syntax: ``` chef:recipe_mode > attributes_mode chef:attributes > default[:hello] = "ohai2u-again" => "ohai2u-again" chef:attributes ``` Switch back to recipe_mode context and use the attributes: ``` chef:attributes > recipe_mode => :attributes chef:recipe_mode > file "/tmp/#{node.hello}" ``` Now, run Chef Infra Client again: ``` chef:recipe_mode > run_chef [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u_shef] [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u-again] [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u-again] using Chef::Provider::File [Fri, 15 Jan 2020 10:53:22 -0800] INFO: Creating file[/tmp/ohai2u-again] at /tmp/ohai2u-again => true chef:recipe_mode ``` Because the first resource (`file[/tmp/ohai2u_shef]`) is still in the run-list, it gets executed again. And because that file already exists, Chef Infra Client doesn’t attempt to re-create it. Finally, the files were created using the `ls` method: ``` chef:recipe_mode > ls("/tmp").grep(/ohai/) => ["ohai2u-again", "ohai2u_shef"] Shell Tutorial ``` #### Get Specific Nodes To get a list of nodes using a recipe named `postfix` use `search(:node,"recipe:postfix")`. To get a list of nodes using a sub-recipe named `delivery`, use chef-shell. For example: ``` search(:node, 'recipes:postfix\:\:delivery') ``` Note Single (' ‘) vs. double (" “) is important. This is because a backslash () needs to be included in the string, instead of having Ruby interpret it as an escape. Examples -------- --- The following examples demonstrate various approaches for using the **breakpoint** resource in recipes: **A recipe without a breakpoint** ``` yum_key node['yum']['elrepo']['key'] do url node['yum']['elrepo']['key_url'] action :add end yum_repository 'elrepo' do description 'ELRepo.org Community Enterprise Linux Extras Repository' key node['yum']['elrepo']['key'] mirrorlist node['yum']['elrepo']['url'] includepkgs node['yum']['elrepo']['includepkgs'] exclude node['yum']['elrepo']['exclude'] action :create end ``` **The same recipe with breakpoints** In the following example, the name of each breakpoint is an arbitrary string. ``` breakpoint "before yum_key node['yum']['repo_name']['key']" do action :break end yum_key node['yum']['repo_name']['key'] do url node['yum']['repo_name']['key_url'] action :add end breakpoint "after yum_key node['yum']['repo_name']['key']" do action :break end breakpoint "before yum_repository 'repo_name'" do action :break end yum_repository 'repo_name' do description 'description' key node['yum']['repo_name']['key'] mirrorlist node['yum']['repo_name']['url'] includepkgs node['yum']['repo_name']['includepkgs'] exclude node['yum']['repo_name']['exclude'] action :create end breakpoint "after yum_repository 'repo_name'" do action :break end ``` In the previous examples, the names are used to indicate if the breakpoint is before or after a resource and also to specify which resource it is before or after. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/breakpoint/chef_acl Resource ================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_acl.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_acl.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_acl** resource to interact with access control lists (ACLs) that exist on the Chef Infra Server. Syntax ------ --- The syntax for using the **chef_acl** resource in a recipe is as follows: ``` chef_acl 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_acl` tells Chef Infra Client to use the `Chef::Provider::ChefAcl` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `path` property is not specified as part of a recipe, `name` is also the name of the Chef Infra Client. * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state Actions ------- --- The **chef_acl** resource has the following actions: `:create` Default. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_acl** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a chef-client completely. When `true`, any property not specified by this resource will be reset to default property values. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `path` A path to a directory in the chef-repo against which the ACL is applied. For example: `nodes`, `nodes/*`, `nodes/my_node`, `*/*`, `**`, `roles/base`, `data/secrets`, `cookbooks/apache2`, `/users/*`, and so on. `raw_json` Chef Infra Client as JSON data. For example: ``` { "clientname": "client_name", "orgname": "org_name", "validator": false, "certificate": "-----BEGIN CERTIFICATE-----\n ... 1234567890abcdefghijklmnopq\n ... -----END CERTIFICATE-----\n", "name": "node_name" } ``` `recursive` Use to apply changes to child objects. Use `:on_change` to apply changes to child objects only if the parent object changes. Set to `true` to apply changes even if the parent object does not change. Set to `false` to prevent any changes. Default value: `:on_change`. `remove_rights` Use to remove rights. For example: ``` remove_rights :read, :users => 'jkeiser', :groups => [ 'admins', 'users' ] ``` or: ``` remove_rights [ :create, :read ], :users => [ 'jkeiser', 'adam' ] ``` or: ``` remove_rights :all, :users => [ 'jkeiser', 'adam' ] ``` `rights` Use to add rights. Syntax: `:right, :right => 'user', :groups => [ 'group', 'group']`. For example: ``` rights :read, :users => 'jkeiser', :groups => [ 'admins', 'users' ] ``` or: ``` rights [ :create, :read ], :users => [ 'jkeiser', 'adam' ] ``` or: ``` rights :all, :users => 'jkeiser' ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_acl/chef_client_config Resource ============================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_client_config.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_client_config.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_client_config** resource to create a client.rb file in the Chef Infra Client configuration directory. See the [client.rb docs](../../config_rb_client/index) for more details on options available in the client.rb configuration file. **New in Chef Infra Client 16.6.** Syntax ------ --- The full syntax for all of the properties that are available to the **chef_client_config** resource is: ``` chef_client_config 'name' do additional_config String chef_license String chef_server_url String config_directory String data_collector_server_url String data_collector_token String event_loggers Array # default value: [] exception_handlers Array # default value: [] file_backup_path String file_cache_path String file_staging_uses_destdir String formatters Array # default value: [] ftp_proxy String group String http_proxy String https_proxy String log_level Symbol log_location String, Symbol minimal_ohai true, false named_run_list String no_proxy String, Array # default value: [] node_name String ohai_disabled_plugins Array # default value: [] ohai_optional_plugins Array # default value: [] pid_file String policy_group String policy_name String policy_persist_run_list true, false report_handlers Array # default value: [] ssl_verify_mode Symbol, String start_handlers Array # default value: [] user String action Symbol # defaults to :create if not specified end ``` where: * `chef_client_config` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `additional_config`, `chef_license`, `chef_server_url`, `config_directory`, `data_collector_server_url`, `data_collector_token`, `event_loggers`, `exception_handlers`, `file_backup_path`, `file_cache_path`, `file_staging_uses_destdir`, `formatters`, `ftp_proxy`, `group`, `http_proxy`, `https_proxy`, `log_level`, `log_location`, `minimal_ohai`, `named_run_list`, `no_proxy`, `node_name`, `ohai_disabled_plugins`, `ohai_optional_plugins`, `pid_file`, `policy_group`, `policy_name`, `policy_persist_run_list`, `report_handlers`, `ssl_verify_mode`, `start_handlers`, and `user` are the properties available to this resource. Actions ------- --- The **chef_client_config** resource has the following actions: `:create` Create a client.rb config file for configuring Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a client.rb config file for configuring Chef Infra Client. Properties ---------- --- The **chef_client_config** resource has the following properties: `additional_config` **Ruby Type:** String Additional text to add at the bottom of the client.rb config. This can be used to run custom Ruby or to add less common config options `chef_license` **Ruby Type:** String **Allowed Values:** `"accept", "accept-no-persist", "accept-silent"` Accept the [Chef EULA](https://www.chef.io/end-user-license-agreement/) `chef_server_url` **Ruby Type:** String | `REQUIRED` The URL for the Chef Infra Server. `config_directory` **Ruby Type:** String | **Default Value:** ``/etc/chef/` on *nix-like systems and `C:\chef\` on Windows` The directory to store the client.rb in. `data_collector_server_url` **Ruby Type:** String The data collector URL (typically automate) to send node, converge, and compliance data. Note If possible, use Chef Infra Server to do all data collection reporting, as this removes the need to distribute tokens to individual nodes. New in Chef Infra Client 17.8 `data_collector_token` **Ruby Type:** String The data collector token to interact with the data collector server URL (Automate). Note If possible, use Chef Infra Server to do all data collection reporting, as this removes the need to distribute tokens to individual nodes. New in Chef Infra Client 17.8 `event_loggers` **Ruby Type:** Array | **Default Value:** `[]` `exception_handlers` **Ruby Type:** Array | **Default Value:** `[]` An array of hashes that contain a exception handler class and the arguments to pass to that class on initialization. The hash should include `class` and `argument` keys where `class` is a String and `argument` is an array of quoted String values. For example: `[{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]` `file_backup_path` **Ruby Type:** String The location in which backup files are stored. If this value is empty, backup files are stored in the directory of the target file `file_cache_path` **Ruby Type:** String The location in which cookbooks (and other transient data) files are stored when they are synchronized. This value can also be used in recipes to download files with the `remote_file` resource. `file_staging_uses_destdir` **Ruby Type:** String How file staging (via temporary files) is done. When `true`, temporary files are created in the directory in which files will reside. When `false`, temporary files are created under `ENV['TMP']` `formatters` **Ruby Type:** Array | **Default Value:** `[]` Client logging formatters to load. `ftp_proxy` **Ruby Type:** String The proxy server to use for FTP connections. `group` **Ruby Type:** String The group that should own the client.rb file and the configuration directory if it needs to be created. Note The configuration directory will not be created if it already exists, which allows you to further control the setup of that directory outside of this resource. `http_proxy` **Ruby Type:** String The proxy server to use for HTTP connections. `https_proxy` **Ruby Type:** String The proxy server to use for HTTPS connections. `log_level` **Ruby Type:** Symbol **Allowed Values:** `:auto, :debug, :fatal, :info, :trace, :warn` The level of logging performed by the Chef Infra Client. `log_location` **Ruby Type:** String, Symbol The location to save logs to. This can either by a path to a log file on disk `:syslog` to log to Syslog, `:win_evt` to log to the Windows Event Log, or `'STDERR'`/`'STDOUT'` to log to the *nix text streams. `minimal_ohai` **Ruby Type:** true, false Run a minimal set of Ohai plugins providing data necessary for the execution of Chef Infra Client’s built-in resources. Setting this to true will skip many large and time consuming data sets such as `cloud` or `packages`. Setting this this to true may break cookbooks that assume all Ohai data will be present. `named_run_list` **Ruby Type:** String A specific named runlist defined in the node’s applied Policyfile, which the should be used when running Chef Infra Client. `no_proxy` **Ruby Type:** String, Array | **Default Value:** `[]` A comma-separated list or an array of URLs that do not need a proxy. `node_name` **Ruby Type:** String | **Default Value:** `The `node.name` value reported by Chef Infra Client.` The name of the node. This configuration sets the `node.name` value used in cookbooks and the `client_name` value used when authenticating to a Chef Infra Server to determine what configuration to apply. Note By default this configuration uses the `node.name` value which would be set during bootstrap. Hard coding this value in the `client.rb` config avoids logic within Chef Infra Server that performs DNS lookups and may fail in the event of a DNS outage. To skip this default value and instead use the built-in Chef Infra Server logic, set this property to `nil` `ohai_disabled_plugins` **Ruby Type:** Array | **Default Value:** `[]` Ohai plugins that should be disabled in order to speed up the Chef Infra Client run and reduce the size of node data sent to Chef Infra Client `ohai_optional_plugins` **Ruby Type:** Array | **Default Value:** `[]` Optional Ohai plugins that should be enabled to provide additional Ohai data for use in cookbooks. `pid_file` **Ruby Type:** String The location in which a process identification number (pid) is saved. An executable, when started as a daemon, writes the pid to the specified file. `policy_group` **Ruby Type:** String The name of a `policy group` that exists on the Chef Infra Server. `policy_name` must also be specified when setting this property. `policy_name` **Ruby Type:** String The name of a policy, as identified by the `name` setting in a Policyfile.rb file. `policy_group` when setting this property. `policy_persist_run_list` **Ruby Type:** true, false Override run lists defined in a Policyfile with the `run_list` defined on the Chef Infra Server. New in Chef Infra Client 17.3 `report_handlers` **Ruby Type:** Array | **Default Value:** `[]` An array of hashes that contain a report handler class and the arguments to pass to that class on initialization. The hash should include `class` and `argument` keys where `class` is a String and `argument` is an array of quoted String values. For example: `[{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]` `ssl_verify_mode` **Ruby Type:** Symbol, String **Allowed Values:** `:verify_none, :verify_peer` Set the verify mode for HTTPS requests. * Use :verify_none for no validation of SSL certificates. * Use :verify_peer for validation of all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS remote_file resource URLs used in Chef Infra Client runs. This is the recommended setting. `start_handlers` **Ruby Type:** Array | **Default Value:** `[]` An array of hashes that contain a report handler class and the arguments to pass to that class on initialization. The hash should include `class` and `argument` keys where `class` is a String and `argument` is an array of quoted String values. For example: `[{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]` `user` **Ruby Type:** String The user that should own the client.rb file and the configuration directory if it needs to be created. Note The configuration directory will not be created if it already exists, which allows you to further control the setup of that directory outside of this resource. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chef_client_config** resource in recipes: **Bare minimum Chef Infra Client client.rb**: The absolute minimum configuration necessary for a node to communicate with the Chef Infra Server is the URL of the Chef Infra Server. All other configuration options either have values at the server side (Policyfiles, Roles, Environments, etc) or have default values determined at client startup. ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' end ``` **More complex Chef Infra Client client.rb**: ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' log_level :info log_location :syslog http_proxy 'proxy.example.dmz' https_proxy 'proxy.example.dmz' no_proxy %w(internal.example.dmz) end ``` **Adding additional config content to the client.rb**: This resource aims to provide common configuration options. Some configuration options are missing and some users may want to use arbitrary Ruby code within their configuration. For this we offer an `additional_config` property that can be used to add any configuration or code to the bottom of the `client.rb` file. Also keep in mind that within the configuration directory is a `client.d` directory where you can put additional `.rb` files containing configuration options. These can be created using `file` or `template` resources within your cookbooks as necessary. ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' additional_config <<~CONFIG # Extra config code to safely load a gem into the client run. # Since the config is Ruby you can run any Ruby code you want via the client.rb. # It's a great way to break things, so be careful begin require 'aws-sdk' rescue LoadError Chef::Log.warn "Failed to load aws-sdk." end CONFIG end ``` **Setup two report handlers in the client.rb**: ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' report_handlers [ { 'class' => 'ReportHandler1Class', 'arguments' => ["'FirstArgument'", "'SecondArgument'"], }, { 'class' => 'ReportHandler2Class', 'arguments' => ["'FirstArgument'", "'SecondArgument'"], }, ] end ``` **Report directly to the [Chef Automate data collector endpoint](../../automate/data_collection/index#configure-chef-infra-client-to-use-the-data-collector-endpoint-in-chef-automate).** ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' data_collector_server_url 'https://automate.example.dmz' data_collector_token 'TEST_TOKEN_TEST' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_client_config/chef_client Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_client.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_client.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_client** resource to create clients on your Chef Infra Server from within Chef Infra cookbook code. Syntax ------ --- The syntax for using the **chef_client** resource in a recipe is as follows: ``` chef_client 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_client` tells Chef Infra Client to use the `Chef::Provider::ChefClient` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the Chef Infra Client * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state Actions ------- --- The **chef_client** resource has the following actions: `:create` Default. Use to create a chef-client. `:delete` Use to delete a chef-client. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:regenerate_keys` Use to regenerate the RSA public key for a chef-client. Properties ---------- --- The **chef_client** resource has the following properties: `admin` Use to specify whether Chef Infra Client is an API client. `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a chef-client completely. When `true`, any property not specified by this resource will be reset to default property values. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of Chef Infra Client. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `output_key_format` Use to specify the format of a public key. Possible values: `pem`, `der`, or `openssh`. Default value: `openssh`. `output_key_path` Use to specify the path to the location in which a public key will be written. `raw_json` Chef Infra Client as JSON data. For example: ``` { "clientname": "client_name", "orgname": "org_name", "validator": false, "certificate": "-----BEGIN CERTIFICATE-----\n ... 1234567890abcdefghijklmnopq\n ... -----END CERTIFICATE-----\n", "name": "node_name" } ``` `source_key` Use to copy a public or private key, but apply a different `format` and `password`. Use in conjunction with `source_key_pass_phrase` and `source_key_path`. `source_key_pass_phrase` The pass phrase for the public key. Use in conjunction with `source_key` and `source_key_path`. `source_key_path` The path to the public key. Use in conjunction with `source_key` and `source_key_pass_phrase`. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `validator` Use to specify if Chef Infra Client is a chef-validator. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_client/chef_client_cron Resource =========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_client_cron.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_client_cron.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_client_cron** resource to setup the Chef Infra Client to run as a cron job. This resource will also create the specified log directory if it doesn’t already exist. **New in Chef Infra Client 16.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **chef_client_cron** resource is: ``` chef_client_cron 'name' do accept_chef_license true, false # default value: false append_log_file true, false # default value: true chef_binary_path String # default value: "/opt/chef/bin/chef-client" comment String config_directory String # default value: "/etc/chef" daemon_options Array # default value: [] day Integer, String # default value: "*" environment Hash # default value: {} hour Integer, String # default value: "*" job_name String # default value: "chef-client" log_directory String log_file_name String # default value: "client.log" mailto String minute Integer, String # default value: "0,30" month Integer, String # default value: "*" nice Integer, String splay Integer, String # default value: 300 user String # default value: "root" weekday Integer, String # default value: "*" action Symbol # defaults to :add if not specified end ``` where: * `chef_client_cron` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `append_log_file`, `chef_binary_path`, `comment`, `config_directory`, `daemon_options`, `day`, `environment`, `hour`, `job_name`, `log_directory`, `log_file_name`, `mailto`, `minute`, `month`, `nice`, `splay`, `user`, and `weekday` are the properties available to this resource. Actions ------- --- The **chef_client_cron** resource has the following actions: `:add` Add a cron job to run Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a cron job for Chef Infra Client. Properties ---------- --- The **chef_client_cron** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `append_log_file` **Ruby Type:** true, false | **Default Value:** `true` Append to the log file instead of overwriting the log file on each run. `chef_binary_path` **Ruby Type:** String | **Default Value:** `/opt/chef/bin/chef-client` The path to the chef-client binary. `comment` **Ruby Type:** String A comment to place in the cron.d file. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `day` **Ruby Type:** Integer, String | **Default Value:** `*` The day of month at which Chef Infra Client is to run (1 - 31) or a cron pattern such as ‘1,7,14,21,28’. `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. `hour` **Ruby Type:** Integer, String | **Default Value:** `*` The hour at which Chef Infra Client is to run (0 - 23) or a cron pattern such as ‘0,12’. `job_name` **Ruby Type:** String | **Default Value:** `chef-client` The name of the cron job to create. `log_directory` **Ruby Type:** String | **Default Value:** `/Library/Logs/Chef on macOS and /var/log/chef otherwise` The path of the directory to create the log file in. `log_file_name` **Ruby Type:** String | **Default Value:** `client.log` The name of the log file to use. `mailto` **Ruby Type:** String The e-mail address to e-mail any cron task failures to. `minute` **Ruby Type:** Integer, String | **Default Value:** `0,30` The minute at which Chef Infra Client is to run (0 - 59) or a cron pattern such as ‘0,30’. `month` **Ruby Type:** Integer, String | **Default Value:** `*` The month in the year on which Chef Infra Client is to run (1 - 12, jan-dec, or *). `nice` **Ruby Type:** Integer, String The process priority to run the chef-client process at. A value of -20 is the highest priority and 19 is the lowest priority. New in Chef Infra Client 16.5 `splay` **Ruby Type:** Integer, String | **Default Value:** `300` A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time. `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that Chef Infra Client runs as. `weekday` **Ruby Type:** Integer, String | **Default Value:** `*` The day of the week on which Chef Infra Client is to run (0-7, mon-sun, or *), where Sunday is both 0 and 7. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chef_client_cron** resource in recipes: **Setup Chef Infra Client to run using the default 30 minute cadence**: ``` chef_client_cron 'Run Chef Infra Client as a cron job' ``` **Run Chef Infra Client twice a day**: ``` chef_client_cron 'Run Chef Infra Client every 12 hours' do minute 0 hour '0,12' end ``` **Run Chef Infra Client with extra options passed to the client**: ``` chef_client_cron 'Run an override recipe' do daemon_options ['--override-runlist mycorp_base::default'] end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_client_cron/chef_client_scheduled_task Resource ====================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_client_scheduled_task.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_client_scheduled_task.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_client_scheduled_task** resource to setup the Chef Infra Client to run as a Windows scheduled task. This resource will also create the specified log directory if it doesn’t already exist. **New in Chef Infra Client 16.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **chef_client_scheduled_task** resource is: ``` chef_client_scheduled_task 'name' do accept_chef_license true, false # default value: false chef_binary_path String # default value: "C:/opscode/chef/bin/chef-client" config_directory String # default value: "/etc/chef" daemon_options Array # default value: [] frequency String # default value: "minute" frequency_modifier Integer, String # default value: "30 if frequency is 'minute', 1 otherwise" log_directory String # default value: "CONFIG_DIRECTORY/log" log_file_name String # default value: "client.log" password String priority Integer # default value: 7 run_on_battery true, false # default value: true splay Integer, String # default value: 300 start_date String start_time String task_name String # default value: "chef-client" use_consistent_splay true, false # default value: false user String # default value: "System" action Symbol # defaults to :add if not specified end ``` where: * `chef_client_scheduled_task` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `chef_binary_path`, `config_directory`, `daemon_options`, `frequency`, `frequency_modifier`, `log_directory`, `log_file_name`, `password`, `priority`, `run_on_battery`, `splay`, `start_date`, `start_time`, `task_name`, `use_consistent_splay`, and `user` are the properties available to this resource. Actions ------- --- The **chef_client_scheduled_task** resource has the following actions: `:add` Add a Windows Scheduled Task that runs Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows Scheduled Task that runs Chef Infra Client. Properties ---------- --- The **chef_client_scheduled_task** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `chef_binary_path` **Ruby Type:** String | **Default Value:** `C:/opscode/chef/bin/chef-client` The path to the chef-client binary. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `frequency` **Ruby Type:** String | **Default Value:** `minute` **Allowed Values:** `"daily", "hourly", "minute", "monthly", "on_idle", "on_logon", "once", "onstart"` Frequency with which to run the task. `frequency_modifier` **Ruby Type:** Integer, String | **Default Value:** `30 if frequency is 'minute', 1 otherwise` Numeric value to go with the scheduled task frequency `log_directory` **Ruby Type:** String | **Default Value:** `CONFIG_DIRECTORY/log` The path of the directory to create the log file in. `log_file_name` **Ruby Type:** String | **Default Value:** `client.log` The name of the log file to use. `password` **Ruby Type:** String The password for the user that Chef Infra Client runs as. `priority` **Ruby Type:** Integer | **Default Value:** `7` Use to set Priority Levels range from 0 to 10. New in Chef Infra Client 17.5 `run_on_battery` **Ruby Type:** true, false | **Default Value:** `true` Run the Chef Infra Client task when the system is on batteries. `splay` **Ruby Type:** Integer, String | **Default Value:** `300` A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time. `start_date` **Ruby Type:** String The start date for the task in m:d:Y format (ex: 12/17/2020). `start_time` **Ruby Type:** String The start time for the task in HH:mm format (ex: 14:00). If the frequency is minute default start time will be Time.now plus the frequency_modifier number of minutes. `task_name` **Ruby Type:** String | **Default Value:** `chef-client` The name of the scheduled task to create. `use_consistent_splay` **Ruby Type:** true, false | **Default Value:** `false` Always use the same random splay amount for each node to ensure consistent frequencies between chef-client execution. New in Chef Infra Client 17.5 `user` **Ruby Type:** String | **Default Value:** `System` The name of the user that Chef Infra Client runs as. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chef_client_scheduled_task** resource in recipes: **Setup Chef Infra Client to run using the default 30 minute cadence**: ``` chef_client_scheduled_task 'Run Chef Infra Client as a scheduled task' ``` **Run Chef Infra Client on system start**: ``` chef_client_scheduled_task 'Chef Infra Client on start' do frequency 'onstart' end ``` **Run Chef Infra Client with extra options passed to the client**: ``` chef_client_scheduled_task 'Run an override recipe' do daemon_options ['--override-runlist mycorp_base::default'] end ``` **Run Chef Infra Client daily at 01:00 am, specifying a named run-list**: ``` chef_client_scheduled_task 'Run chef-client named run-list daily' do frequency 'daily' start_time '01:00' daemon_options ['-n audit_only'] end ``` **Run Chef Infra Client with a persistent delay on every run calculated once, similar to how chef_client_cron resource works**: ``` chef_client_scheduled_task 'Run chef-client with persistent splay' do use_consistent_splay true end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_client_scheduled_task/chef_data_bag Resource ======================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_data_bag.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_data_bag.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. Use the **chef_data_bag** resource to manage data bags. Syntax ------ --- The syntax for using the **chef_data_bag** resource in a recipe is as follows: ``` chef_data_bag 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_data_bag` tells Chef Infra Client to use the `Chef::Provider::ChefDataBag` provider during a Chef Infra Client run * `name` is the name of the resource block and also the name of the data bag * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state Actions ------- --- The **chef_data_bag** resource has the following actions: `:create` Default. Use to create a data bag. `:delete` Use to delete a data bag. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_data_bag** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the data bag. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_data_bag/chef_client_systemd_timer Resource ===================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_client_systemd_timer.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_client_systemd_timer.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_client_systemd_timer** resource to setup the Chef Infra Client to run as a systemd timer. **New in Chef Infra Client 16.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **chef_client_systemd_timer** resource is: ``` chef_client_systemd_timer 'name' do accept_chef_license true, false # default value: false chef_binary_path String # default value: "/opt/chef/bin/chef-client" config_directory String # default value: "/etc/chef" cpu_quota Integer, String daemon_options Array # default value: [] delay_after_boot String # default value: "1min" description String # default value: "Chef Infra Client periodic execution" environment Hash # default value: {} interval String # default value: "30min" job_name String # default value: "chef-client" run_on_battery true, false # default value: true splay String # default value: "5min" user String # default value: "root" action Symbol # defaults to :add if not specified end ``` where: * `chef_client_systemd_timer` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `chef_binary_path`, `config_directory`, `cpu_quota`, `daemon_options`, `delay_after_boot`, `description`, `environment`, `interval`, `job_name`, `run_on_battery`, `splay`, and `user` are the properties available to this resource. Actions ------- --- The **chef_client_systemd_timer** resource has the following actions: `:add` Add a systemd timer that runs Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a systemd timer that runs Chef Infra Client. Properties ---------- --- The **chef_client_systemd_timer** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `chef_binary_path` **Ruby Type:** String | **Default Value:** `/opt/chef/bin/chef-client` The path to the chef-client binary. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `cpu_quota` **Ruby Type:** Integer, String The systemd CPUQuota to run the chef-client process with. This is a percentage value of the total CPU time available on the system. If the system has more than 1 core this may be a value greater than 100. New in Chef Infra Client 16.5 `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `delay_after_boot` **Ruby Type:** String | **Default Value:** `1min` The time to wait after booting before the interval starts. This is expressed as a systemd time span such as `300seconds`, `1hr`, or `1m`. See <https://www.freedesktop.org/software/systemd/man/systemd.time.html> for a complete list of allowed time span values. `description` **Ruby Type:** String | **Default Value:** `Chef Infra Client periodic execution` The description to add to the systemd timer. This will be displayed when running `systemctl status` for the timer. `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the systemd timer will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. `interval` **Ruby Type:** String | **Default Value:** `30min` The interval to wait between executions. This is expressed as a systemd time span such as `300seconds`, `1hr`, or `1m`. See <https://www.freedesktop.org/software/systemd/man/systemd.time.html> for a complete list of allowed time span values. `job_name` **Ruby Type:** String | **Default Value:** `chef-client` The name of the system timer to create. `run_on_battery` **Ruby Type:** true, false | **Default Value:** `true` Run the timer for Chef Infra Client if the system is on battery. `splay` **Ruby Type:** String | **Default Value:** `5min` A interval between 0 and X to add to the interval so that all chef-client commands don’t execute at the same time. This is expressed as a systemd time span such as `300seconds`, `1hr`, or `1m`. See <https://www.freedesktop.org/software/systemd/man/systemd.time.html> for a complete list of allowed time span values. `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that Chef Infra Client runs as. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chef_client_systemd_timer** resource in recipes: **Setup Chef Infra Client to run using the default 30 minute cadence**: ``` chef_client_systemd_timer 'Run Chef Infra Client as a systemd timer' ``` **Run Chef Infra Client every 1 hour**: ``` chef_client_systemd_timer 'Run Chef Infra Client every 1 hour' do interval '1hr' end ``` **Run Chef Infra Client with extra options passed to the client**: ``` chef_client_systemd_timer 'Run an override recipe' do daemon_options ['--override-runlist mycorp_base::default'] end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_client_systemd_timer/chef_client_launchd Resource ============================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_client_launchd.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_client_launchd.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_client_launchd** resource to configure the Chef Infra Client to run on a schedule on macOS systems. **New in Chef Infra Client 16.5.** Syntax ------ --- The full syntax for all of the properties that are available to the **chef_client_launchd** resource is: ``` chef_client_launchd 'name' do accept_chef_license true, false # default value: false chef_binary_path String # default value: "/opt/chef/bin/chef-client" config_directory String # default value: "/etc/chef" daemon_options Array # default value: [] environment Hash # default value: {} interval Integer, String # default value: 30 log_directory String # default value: "/Library/Logs/Chef" log_file_name String # default value: "client.log" low_priority_io true, false # default value: true nice Integer, String splay Integer, String # default value: 300 user String # default value: "root" working_directory String # default value: "/var/root" action Symbol # defaults to :enable if not specified end ``` where: * `chef_client_launchd` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `chef_binary_path`, `config_directory`, `daemon_options`, `environment`, `interval`, `log_directory`, `log_file_name`, `low_priority_io`, `nice`, `splay`, `user`, and `working_directory` are the properties available to this resource. Actions ------- --- The **chef_client_launchd** resource has the following actions: `:disable` Disable running Chef Infra Client on a schedule using launchd `:enable` Enable running Chef Infra Client on a schedule using launchd. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_client_launchd** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `chef_binary_path` **Ruby Type:** String | **Default Value:** `/opt/chef/bin/chef-client` The path to the chef-client binary. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the launchd daemon will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. `interval` **Ruby Type:** Integer, String | **Default Value:** `30` Time in minutes between Chef Infra Client executions. `log_directory` **Ruby Type:** String | **Default Value:** `/Library/Logs/Chef` The path of the directory to create the log file in. `log_file_name` **Ruby Type:** String | **Default Value:** `client.log` The name of the log file to use. `low_priority_io` **Ruby Type:** true, false | **Default Value:** `true` Run the chef-client process with low priority disk IO `nice` **Ruby Type:** Integer, String The process priority to run the chef-client process at. A value of -20 is the highest priority and 19 is the lowest priority. `splay` **Ruby Type:** Integer, String | **Default Value:** `300` A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time. `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that Chef Infra Client runs as. `working_directory` **Ruby Type:** String | **Default Value:** `/var/root` The working directory to run the Chef Infra Client from. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chef_client_launchd** resource in recipes: **Set the Chef Infra Client to run on a schedule**: ``` chef_client_launchd 'Setup the Chef Infra Client to run every 30 minutes' do interval 30 action :enable end ``` **Disable the Chef Infra Client running on a schedule**: ``` chef_client_launchd 'Prevent the Chef Infra Client from running on a schedule' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_client_launchd/chef_container Resource ======================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_container.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_container.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_container** resource to interact with container objects that exist on the Chef Infra Server. Syntax ------ --- The syntax for using the **chef_container** resource in a recipe is as follows: ``` chef_container 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_container` tells Chef Infra Client to use the `Chef::Provider::ChefContainer` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state Actions ------- --- The **chef_container** resource has the following actions: `:create` Default. `:delete` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_container** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the container. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_container/chef_group Resource ==================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_group.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_group.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_group** resource to interact with group objects that exist on the Chef server. Syntax ------ --- The syntax for using the **chef_group** resource in a recipe is as follows: ``` chef_group 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_group` tells Chef Infra Client to use the `Chef::Provider::ChefGroup` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state Actions ------- --- The **chef_group** resource has the following actions: `:create` Default. `:delete` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_group** resource has the following properties: `chef_server` The URL for the Chef server. `clients` &mldr; `complete` Use to specify if this resource defines a chef-client completely. When `true`, any property not specified by this resource will be reset to default property values. `groups` &mldr; `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `raw_json` The group as JSON data. For example: ``` { :groupname => "chef" } ``` `remove_clients` &mldr; `remove_groups` &mldr; `remove_users` &mldr; `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `users` &mldr; Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_group/chef_client_trusted_certificate Resource =========================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_client_trusted_certificate.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_client_trusted_certificate.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_client_trusted_certificate** resource to add certificates to Chef Infra Client’s trusted certificate directory. This allows the Chef Infra Client to communicate with internal encrypted resources without errors. **New in Chef Infra Client 16.5.** Syntax ------ --- The full syntax for all of the properties that are available to the **chef_client_trusted_certificate** resource is: ``` chef_client_trusted_certificate 'name' do cert_name String # default value: 'name' unless specified certificate String action Symbol # defaults to :add if not specified end ``` where: * `chef_client_trusted_certificate` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `cert_name` and `certificate` are the properties available to this resource. Actions ------- --- The **chef_client_trusted_certificate** resource has the following actions: `:add` Add a trusted certificate to Chef Infra Client’s trusted certificate directory (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a trusted certificate from Chef Infra Client’s trusted certificate directory Properties ---------- --- The **chef_client_trusted_certificate** resource has the following properties: `cert_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name to use for the certificate file on disk. If not provided the name of the resource block will be used instead. `certificate` **Ruby Type:** String | `REQUIRED` The text of the certificate file including the BEGIN/END comment lines. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chef_client_trusted_certificate** resource in recipes: **Trust a self signed certificate**: ``` chef_client_trusted_certificate 'self-signed.badssl.com' do certificate <<~CERT -----BEGIN CERTIFICATE----- MIIDeTCCAmGgAwIB<KEY> <KEY> <KEY> <KEY> <KEY> <KEY> hy<KEY> xPxTuW1CrbV8/q71FdIzSOcic<KEY>St/qbLVyt<KEY> ww9HdFxBIuGa+RuT5q0iBikusbpJHAwnnqP7i/dAcg<KEY>4<KEY> -----END CERTIFICATE----- CERT end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_client_trusted_certificate/chef_environment Resource ========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_environment.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_environment.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. Use the **chef_environment** resource to manage environments. Syntax ------ --- The syntax for using the **chef_environment** resource in a recipe is as follows: ``` chef_environment 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_environment` tells Chef Infra Client to use the `Chef::Provider::ChefEnvironment` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the environment * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state Actions ------- --- The **chef_environment** resource has the following actions: `:create` Default. Use to create an environment. `:delete` Use to delete an environment. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_environment** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines an environment completely. When `true`, any property not specified by this resource will be reset to default property values. `cookbook_versions` The cookbook versions used with the environment. Default value: `{}`. `default_attributes` A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. Default value: `{}`. `description` The description of the environment. This value populates the description field for the environment on the Chef Infra Server. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the environment. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `override_attributes` An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. Default value: `{}`. `raw_json` The environment as JSON data. For example: ``` { "name":"backend", "description":"", "cookbook_versions":{}, "json_class":"Chef::Environment", "chef_type":"environment", "default_attributes":{}, "override_attributes":{} } ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_environment/chef_data_bag_item Resource ============================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_data_bag_item.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_data_bag_item.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- A data bag is a container of related data bag items, where each individual data bag item is a JSON file. knife can load a data bag item by specifying the name of the data bag to which the item belongs and then the filename of the data bag item. The only structural requirement of a data bag item is that it must have an `id`: ``` { /* This is a supported comment style */ // This style is also supported "id": "ITEM_NAME", "key": "value" } ``` where * `key` and `value` are the `key:value` pair for each additional attribute within the data bag item * `/* ... */` and `// ...` show two ways to add comments to the data bag item Use the **chef_data_bag_item** resource to manage data bag items. Syntax ------ --- The syntax for using the **chef_data_bag_item** resource in a recipe is as follows: ``` chef_data_bag_item 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_data_bag_item` tells Chef Infra Client to use the `Chef::Provider::ChefDataBagItem` provider during a Chef Infra Client run * `name` is the name of the resource block and also the name of the data bag item * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state Actions ------- --- The **chef_data_bag_item** resource has the following actions: `:create` Default. Use to create a data bag item. `:delete` Use to delete a data bag item. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_data_bag_item** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a data bag item completely. When `true`, any property not specified by this resource will be reset to default property values. `encrypt` Use to specify whether encryption is used for a data bag item. `encryption_version` The minimum required version of data bag encryption. Possible values: `0`, `1`, `2`, and `3`. When all of the machines in an organization are running chef-client version 13.0.113 (or higher), it is recommended that this value be set to `3`. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `raw_data` Use to create a data bag from a local file from `./data_bags/bag_name/file`. `raw_json` The data bag item as JSON data. For example: ``` { "id": "adam", "real_name": "<NAME>" } ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_data_bag_item/chef_gem Resource ================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_gem.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_gem.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_gem** resource to install a gem only for the instance of Ruby that is dedicated to the chef-client. When a gem is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. The **chef_gem** resource works with all of the same properties and options as the **gem_package** resource, but does not accept the `gem_binary` property because it always uses the `CurrentGemEnvironment` under which the `chef-client` is running. In addition to performing actions similar to the **gem_package** resource, the **chef_gem** resource does the following: * Runs its actions immediately, before convergence, allowing a gem to be used in a recipe immediately after it is installed. * Runs `Gem.clear_paths` after the action, ensuring that gem is aware of changes so that it can be required immediately after it is installed. Warning The **chef_gem** and **gem_package** resources are both used to install Ruby gems. For any machine on which Chef Infra Client is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is available only to Chef Infra Client. Use the **chef_gem** resource to install gems into the instance of Ruby that is dedicated to Chef Infra Client. Use the **gem_package** resource to install all other gems (i.e. install gems system-wide). Syntax ------ --- The full syntax for all of the properties that are available to the **chef_gem** resource is: ``` chef_gem 'name' do clear_sources true, false gem_binary String include_default_source true, false options String, Hash, Array package_name String source String, Array timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `chef_gem` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `clear_sources`, `gem_binary`, `include_default_source`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **chef_gem** resource has the following actions: `:install` Default. Install a gem. If a version is specified, install the specified version of the gem. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a gem. This action typically removes the configuration files as well as the gem. `:reconfig` Reconfigure a gem. This action requires a response file. `:remove` Remove a gem. `:upgrade` Install a gem and/or ensure that a gem is the latest version. Properties ---------- --- The **chef_gem** resource has the following properties: `clear_sources` **Ruby Type:** true, false | **Default Value:** `false unless `clear_gem_sources` set to true in the `client.rb` config.` Set to `true` to download a gem from the path specified by the `source` property (and not from RubyGems). `gem_binary` **Ruby Type:** String | **Default Value:** `The `gem` binary included with Chef Infra Client.` The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by Chef Infra Client will be used. `include_default_source` **Ruby Type:** true, false Set to `false` to not include `Chef::Config[:rubygems_url]` in the sources. New in Chef Client 13.0 `options` **Ruby Type:** String, Hash, Array Options for the gem install, either a Hash or a String. When a hash is given, the options are passed to `Gem::DependencyInstaller.new`, and the gem will be installed via the gems API. When a String is given, the gem will be installed by shelling out to the gem command. Using a Hash of options with an explicit gem_binary will result in undefined behavior. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String, Array Optional. The URL, or list of URLs, at which the gem package is located. This list is added to the source configured in `Chef::Config[:rubygems_url]` (see also include_default_source) to construct the complete list of rubygems sources. Users in an ‘airgapped’ environment should set Chef::Config[:rubygems_url] to their local RubyGems mirror. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chef_gem** resource in recipes: **Compile time vs. converge time installation of gems** To install a gem while Chef Infra Client is configuring the node (the converge phase), set the `compile_time` property to `false`: ``` chef_gem 'loofah' do compile_time false action :install end ``` To install a gem while the resource collection is being built (the compile phase), set the `compile_time` property to `true`: ``` chef_gem 'loofah' do compile_time true action :install end ``` **Install MySQL gem into Chef Infra Client*** ``` apt_update build_essential 'install compilation tools' do compile_time true end chef_gem 'mysql' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_gem/chef_role Resource =================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_role.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_role.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. Use the **chef_role** resource to manage roles. Syntax ------ --- The syntax for using the **chef_role** resource in a recipe is as follows: ``` chef_role 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_role` tells Chef Infra Client to use the `Chef::Provider::ChefRole` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the role * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state Actions ------- --- The **chef_role** resource has the following actions: `:create` Default. Use to create a role. `:delete` Use to delete a role. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_role** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a role completely. When `true`, any property not specified by this resource will be reset to default property values. `default_attributes` A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. Default value: `{}`. `description` The description of the role. This value populates the description field for the role on the Chef Infra Server. `env_run_lists` The environment-specific run-list for a role. Default value: `[]`. For example: `["env_run_lists[webserver]"]` `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the role. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `override_attributes` An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. Default value: `{}`. `raw_json` The role as JSON data. For example: ``` { "name": "webserver", "chef_type": "role", "json_class": "Chef::Role", "default_attributes": {}, "description": "A webserver", "run_list": [ "recipe[apache2]" ], "override_attributes": {} } ``` `run_list` A comma-separated list of roles and/or recipes to be applied. Default value: `[]`. For example: `["recipe[default]","recipe[apache2]"]` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_role/chef_node Resource =================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_node.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_node.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. Use the **chef_node** resource to manage nodes. Syntax ------ --- The syntax for using the **chef_node** resource in a recipe is as follows: ``` chef_node 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_node` tells Chef Infra Client to use the `Chef::Provider::ChefNode` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state Actions ------- --- The **chef_node** resource has the following actions: `:create` Default. Use to create a node. `:delete` Use to delete a node. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_node** resource has the following properties: `automatic_attributes` An `automatic` attribute contains data that is identified by Ohai at the beginning of every Chef Infra Client run. An `automatic` attribute cannot be modified and always has the highest attribute precedence. Default value: `{}`. `chef_environment` The Chef Infra Server environment in which this node should exist (or does exist). `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a node completely. When `true`, any property not specified by this resource will be reset to default property values. `default_attributes` A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. Default value: `{}`. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The unique identifier of the node. `normal_attributes` A `normal` attribute is a setting that persists in the node object. A `normal` attribute has a higher attribute precedence than a `default` attribute. Default value: `{}`. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `override_attributes` An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. Default value: `{}`. `raw_json` The node as JSON data. For example: ``` { "overrides": {}, "name": "latte", "chef_type": "node", "json_class": "Chef::Node", "attributes": { "hardware_type": "laptop" }, "run_list": [ "recipe[apache2]" ], "defaults": {} } ``` `run_list` A comma-separated list of roles and/or recipes to be applied. Default value: `[]`. For example: `["recipe[default]","recipe[apache2]"]` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_node/chef_handler Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_handler.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_handler.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_handler** resource to enable handlers during a Chef Infra Client run. The resource allows arguments to be passed to Chef Infra Client, which then applies the conditions defined by the custom handler to the node attribute data collected during a Chef Infra Client run, and then processes the handler based on that data. The **chef_handler** resource is typically defined early in a node’s run-list (often being the first item). This ensures that all of the handlers will be available for the entire Chef Infra Client run. **New in Chef Infra Client 14.0.** Handler Types ------------- There are three types of handlers: | Handler | Description | | --- | --- | | exception | An exception handler is used to identify situations that have caused a Chef Infra Client run to fail. An exception handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the **chef_handler** resource to a node's run-list. An exception handler runs when the `failed?` property for the `run_status` object returns `true`. | | report | A report handler is used when a Chef Infra Client run succeeds and reports back on certain details about that Chef Infra Client run. A report handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the **chef_handler** resource to a node's run-list. A report handler runs when the `success?` property for the `run_status` object returns `true`. | | start | A start handler is used to run events at the beginning of a Chef Infra Client run. A start handler can be loaded at the start of a Chef Infra Client run by adding the start handler to the `start_handlers` setting in the client.rb file or by installing the gem that contains the start handler by using the **chef_gem** resource in a recipe in the **chef-client** cookbook. (A start handler may not be loaded using the `chef_handler` resource.) | ### Exception / Report Exception and report handlers are used to trigger certain behaviors in response to specific situations, typically identified during a Chef Infra Client run. * An exception handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run fails. * A report handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run is successful. Both types of handlers can be used to gather data about a Chef Infra Client run and can provide rich levels of data about all types of usage, which can be used later for trending and analysis across the entire organization. Exception and report handlers are made available to a Chef Infra Client run in one of the following ways: * By adding the **chef_handler** resource to a recipe, and then adding that recipe to the run-list for a node. (The **chef_handler** resource is available from the **chef_handler** cookbook.) * By adding the handler to one of the following settings in the node’s client.rb file: `exception_handlers` and/or `report_handlers` The **chef_handler** resource allows exception and report handlers to be enabled from within recipes, which can then added to the run-list for any node on which the exception or report handler should run. The **chef_handler** resource is available from the **chef_handler** cookbook. To use the **chef_handler** resource in a recipe, add code similar to the following: ``` chef_handler 'name_of_handler' do source '/path/to/handler/handler_name' action :enable end ``` For example, a handler for Growl needs to be enabled at the beginning of a Chef Infra Client run: ``` chef_gem 'chef-handler-growl' ``` and then is activated in a recipe by using the **chef_handler** resource: ``` chef_handler 'Chef::Handler::Growl' do source 'chef/handler/growl' action :enable end ``` ### Start A start handler is not loaded into a Chef Infra Client run from a recipe, but is instead listed in the client.rb file using the `start_handlers` attribute. The start handler must be installed on the node and be available to Chef Infra Client prior to the start of a Chef Infra Client run. Use the **chef-client** cookbook to install the start handler. Start handlers are made available to a Chef Infra Client run in one of the following ways: * By adding a start handler to the **chef-client** cookbook, which installs the handler on the node so that it is available to Chef Infra Client at the start of a Chef Infra Client run * By adding the handler to one of the following settings in the node’s client.rb file: `start_handlers` The **chef-client** cookbook can be configured to automatically install and configure gems that are required by a start handler. For example: ``` node.override['chef_client']['load_gems']['chef-reporting'] = { require_name: 'chef_reporting', action: :install, } node.override['chef_client']['config']['start_handlers'] = [ { class: 'Chef::Reporting::StartHandler', arguments: [], }, ] include_recipe 'chef-client::config' ``` Syntax ------ --- A **chef_handler** resource block enables handlers during a chef-client run. Two handlers—`JsonFile` and `ErrorReport`—are built into Chef: ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments :path => '/var/chef/reports' action :enable end ``` and: ``` chef_handler 'Chef::Handler::ErrorReport' do source 'chef/handler/error_report' action :enable end ``` show how to enable those handlers in a recipe. The full syntax for all of the properties that are available to the **chef_handler** resource is: ``` chef_handler 'name' do arguments Array, Hash # default value: [] class_name String # default value: 'name' unless specified source String type Hash # default value: {"report"=>true, "exception"=>true} action Symbol # defaults to :enable if not specified end ``` where: * `chef_handler` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `arguments`, `class_name`, `source`, and `type` are the properties available to this resource. Actions ------- --- The **chef_handler** resource has the following actions: `:disable` Disables the handler for the current Chef Infra Client run on the current node. `:enable` Enables the handler for the current Chef Infra Client run on the current node. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_handler** resource has the following properties: `arguments` **Ruby Type:** Array, Hash | **Default Value:** `[]` An array of arguments that are passed to the initializer for the handler class. For example: ``` arguments :key1 => 'val1' ``` or: ``` arguments [:key1 => 'val1', :key2 => 'val2'] ``` `class_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the handler class. This can be module name-spaced. `source` **Ruby Type:** String The full path to the handler file. Can also be a gem path if the handler ships as part of a Ruby gem. `type` **Ruby Type:** Hash | **Default Value:** `{"report"=>true, "exception"=>true}` The type of handler to register as, i.e. :report, :exception or both. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chef_handler** resource in recipes: **Enable the ‘MyHandler’ handler** The following example shows how to enable a fictional ‘MyHandler’ handler which is located on disk at `/etc/chef/my_handler.rb`. The handler will be configured to run with Chef Infra Client and will be passed values to the handler’s initializer method: ``` chef_handler 'MyHandler' do source '/etc/chef/my_handler.rb' # the file should already be at this path arguments path: '/var/chef/reports' action :enable end ``` **Enable handlers during the compile phase** ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' action :enable compile_time true end ``` **Handle only exceptions** ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' type exception: true action :enable end ``` **Cookbook Versions (a custom handler)** [@juliandunn](https://github.com/juliandunn) created a custom report handler that logs all of the cookbooks and cookbook versions that were used during a Chef Infra Client run, and then reports after the run is complete. cookbook_versions.rb: The following custom handler defines how cookbooks and cookbook versions that are used during a Chef Infra Client run will be compiled into a report using the `Chef::Log` class in Chef Infra Client: ``` require 'chef/log' module Chef class CookbookVersionsHandler < Chef::Handler def report cookbooks = run_context.cookbook_collection Chef::Log.info('Cookbooks and versions run: #{cookbooks.map {|x| x.name.to_s + ' ' + x.version }}') end end end ``` default.rb: The following recipe is added to the run-list for every node on which a list of cookbooks and versions will be generated as report output after every Chef Infra Client run. ``` cookbook_file '/etc/chef/cookbook_versions.rb' do source 'cookbook_versions.rb' action :create end chef_handler 'Chef::CookbookVersionsHandler' do source '/etc/chef/cookbook_versions.rb' type report: true action :enable end ``` This recipe will generate report output similar to the following: ``` [2013-11-26T03:11:06+00:00] INFO: Chef Infra Client Run complete in 0.300029878 seconds [2013-11-26T03:11:06+00:00] INFO: Running report handlers [2013-11-26T03:11:06+00:00] INFO: Cookbooks and versions run: ["cookbook_versions_handler 1.0.0"] [2013-11-26T03:11:06+00:00] INFO: Report handlers complete ``` **JsonFile Handler** The JsonFile handler is available from the `chef_handler` cookbook and can be used with exceptions and reports. It serializes run status data to a JSON file. This handler may be enabled in one of the following ways. By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how Chef Infra Client is being run: ``` require 'chef/handler/json_file' report_handlers << Chef::Handler::JsonFile.new(path: '/var/chef/reports') exception_handlers << Chef::Handler::JsonFile.new(path: '/var/chef/reports') ``` By using the `chef_handler` resource in a recipe, similar to the following: ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' action :enable end ``` After it has run, the run status data can be loaded and inspected via Interactive Ruby (IRb): ``` irb(main):002:0> require 'json' => true irb(main):003:0> require 'chef' => true irb(main):004:0> r = JSON.parse(IO.read('/var/chef/reports/chef-run-report-20110322060731.json')) => ... output truncated irb(main):005:0> r.keys => ['end_time', 'node', 'updated_resources', 'exception', 'all_resources', 'success', 'elapsed_time', 'start_time', 'backtrace'] irb(main):006:0> r['elapsed_time'] => 0.00246 ``` Register the JsonFile handler ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' action :enable end ``` **ErrorReport Handler** The ErrorReport handler is built into Chef Infra Client and can be used for both exceptions and reports. It serializes error report data to a JSON file. This handler may be enabled in one of the following ways. By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how Chef Infra Client is being run: ``` require 'chef/handler/error_report' report_handlers << Chef::Handler::ErrorReport.new exception_handlers << Chef::Handler::ErrorReport.new ``` By using the `chef_handler` resource in a recipe, similar to the following: ``` chef_handler 'Chef::Handler::ErrorReport' do source 'chef/handler/error_report' action :enable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_handler/chef_organization Resource =========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_organization.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_organization.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_organization** resource to interact with organization objects that exist on the Chef Infra Server. Syntax ------ --- The syntax for using the **chef_organization** resource in a recipe is as follows: ``` chef_organization 'name' do attribute 'value' # see attributes section below ... action :action # see actions section below end ``` where: * `chef_organization` tells Chef Infra Client to use the `Chef::Provider::ChefOrganization` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the attributes that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state Actions ------- --- The **chef_organization** resource has the following actions: `:create` Default. `:delete` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_organization** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines an organization completely. When `true`, any property not specified by this resource will be reset to default property values. `full_name` The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `Chef Software, Inc.`. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `invites` Use to specify a list of users to be invited to the organization. An invitation is sent to any user in this list who is not already a member of the organization. `members` Use to specify a list of users who MUST be members of the organization. These users will be added directly to the organization. The user who initiates this operation MUST also have permission to add users to the specified organization. `members_specified` Use to discover if a user is a member of an organization. Will return `true` if the user is a member. `name` The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `raw_json` The organization as JSON data. For example: ``` { "name": "chef", "full_name": "<NAME>, Inc", "guid": "f980d1asdfda0331235s00ff36862 ... } ``` `remove_members` Use to remove the specified users from an organization. Invitations that have not been accepted will be cancelled. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_organization/chef_sleep Resource ==================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_sleep.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_sleep.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_sleep** resource to pause (sleep) for a number of seconds during a Chef Infra Client run. Only use this resource when a command or service exits successfully but is not ready for the next step in a recipe. **New in Chef Infra Client 15.5.** Syntax ------ --- The full syntax for all of the properties that are available to the **chef_sleep** resource is: ``` chef_sleep 'name' do seconds String, Integer # default value: 'name' unless specified action Symbol # defaults to :sleep if not specified end ``` where: * `chef_sleep` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `seconds` is the property available to this resource. Actions ------- --- The **chef_sleep** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:sleep` Pause the Chef Infra Client run for a specified number of seconds. (default) Properties ---------- --- The **chef_sleep** resource has the following properties: `seconds` **Ruby Type:** String, Integer | **Default Value:** `The resource block's name` The number of seconds to sleep. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chef_sleep** resource in recipes: **Sleep for 10 seconds**: ``` chef_sleep '10' ``` **Sleep for 10 seconds with a descriptive resource name for logging**: ``` chef_sleep 'wait for the service to start' do seconds 10 end ``` **Use a notification from another resource to sleep only when necessary**: ``` service 'Service that is slow to start and reports as started' do service_name 'my_database' action :start notifies :sleep, 'chef_sleep[wait for service start]' end chef_sleep 'wait for service start' do seconds 30 action :nothing end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_sleep/chef_user Resource =================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_user.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_user.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_user** resource to manage users. Syntax ------ --- The syntax for using the **chef_user** resource in a recipe is as follows: ``` chef_user 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_user` tells Chef Infra Client to use the `Chef::Provider::ChefUser` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the user * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state Actions ------- --- The **chef_user** resource has the following actions: `:create` Default. Use to create a user. `:delete` Use to delete a user. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_user** resource has the following properties: `admin` Create a client as an admin client. This is required for any user to access Chef as an administrator. `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a user completely. When `true`, any property not specified by this resource will be reset to default property values. `email` The email address for the user. `external_authentication_uid` &mldr; `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the user. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `output_key_format` Use to specify the format of a public key. Possible values: `pem`, `der`, or `openssh`. Default value: `openssh`. `output_key_path` Use to specify the path to the location in which a public key will be written. `raw_json` The user as JSON data. For example: ``` { "name": "<NAME>" } ``` `recovery_authentication_enabled` &mldr; `source_key` Use to copy a public or private key, but apply a different `format` and `password`. Use in conjunction with `source_key_pass_phrase` and `source_key_path`. `source_key_pass_phrase` The pass phrase for the public key. Use in conjunction with `source_key` and `source_key_path`. `source_key_path` The path to the public key. Use in conjunction with `source_key` and `source_key_pass_phrase`. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_user/chocolatey_source Resource =========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chocolatey_source.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chocolatey_source.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chocolatey_source** resource to add, remove, enable, or disable Chocolatey sources. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [Chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. **New in Chef Infra Client 14.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **chocolatey_source** resource is: ``` chocolatey_source 'name' do admin_only true, false # default value: false allow_self_service true, false # default value: false bypass_proxy true, false # default value: false cert String cert_password String password String priority Integer # default value: 0 source String source_name String # default value: 'name' unless specified username String action Symbol # defaults to :add if not specified end ``` where: * `chocolatey_source` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `admin_only`, `allow_self_service`, `bypass_proxy`, `cert`, `cert_password`, `password`, `priority`, `source`, `source_name`, and `username` are the properties available to this resource. Actions ------- --- The **chocolatey_source** resource has the following actions: `:add` Adds a Chocolatey source (default) `:disable` Disables a Chocolatey source. **New in Chef Infra Client 15.1.** `:enable` Enables a Chocolatey source. **New in Chef Infra Client 15.1.** `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes a Chocolatey source. Properties ---------- --- The **chocolatey_source** resource has the following properties: `admin_only` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to set the source to be accessible to only admins. New in Chef Infra Client 15.1 `allow_self_service` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to set the source to be used for self service. New in Chef Infra Client 15.1 `bypass_proxy` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to bypass the system’s proxy settings to access the source. `cert` **Ruby Type:** String The certificate to use when authenticating against the source New in Chef Infra Client 17.7 `cert_password` **Ruby Type:** String The password for the certificate to use when authenticating against the source New in Chef Infra Client 17.7 `password` **Ruby Type:** String The password to use when authenticating against the source New in Chef Infra Client 17.7 `priority` **Ruby Type:** Integer | **Default Value:** `0` The priority level of the source. `source` **Ruby Type:** String The source URL. `source_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the source name if it differs from the resource block’s name. `username` **Ruby Type:** String The username to use when authenticating against the source New in Chef Infra Client 17.7 Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chocolatey_source** resource in recipes: **Add a Chocolatey source** ``` chocolatey_source 'MySource' do source 'http://example.com/something' action :add end ``` **Remove a Chocolatey source** ``` chocolatey_source 'MySource' do action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chocolatey_source/chef_vault_secret Resource ============================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chef_vault_secret.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chef_vault_secret.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chef_vault_secret** resource to store secrets in Chef Vault items. Where possible and relevant, this resource attempts to map behavior and functionality to the knife vault sub-commands. **New in Chef Infra Client 16.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **chef_vault_secret** resource is: ``` chef_vault_secret 'name' do admins String, Array clients String, Array data_bag String environment String id String # default value: 'name' unless specified raw_data Hash, Mash (Hash-like) # default value: {} search String # default value: "*:*" action Symbol # defaults to :create if not specified end ``` where: * `chef_vault_secret` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `admins`, `clients`, `data_bag`, `environment`, `id`, `raw_data`, and `search` are the properties available to this resource. Actions ------- --- The **chef_vault_secret** resource has the following actions: `:create` Creates the item, or updates it if it already exists. (default) `:create_if_missing` Calls the create action unless it exists. `:delete` Deletes the item and the item’s keys (‘id’_keys). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chef_vault_secret** resource has the following properties: `admins` **Ruby Type:** String, Array | `REQUIRED` A list of admin users who should have access to the item. Corresponds to the ‘admin’ option when using the chef-vault knife plugin. Can be specified as a comma separated string or an array. `clients` **Ruby Type:** String, Array A search query for the nodes' API clients that should have access to the item. `data_bag` **Ruby Type:** String | `REQUIRED` The data bag that contains the item. `environment` **Ruby Type:** String The Chef environment of the data if storing per environment values. `id` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the data bag item if it differs from the name of the resource block `raw_data` **Ruby Type:** Hash, Mash (Hash-like) | **Default Value:** `{}` The raw data, as a Ruby Hash, that will be stored in the item. `search` **Ruby Type:** String | **Default Value:** `*:*` Search query that would match the same used for the clients, gets stored as a field in the item. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chef_vault_secret** resource in recipes: **To create a ‘foo’ item in an existing ‘bar’ data bag**: ``` chef_vault_secret 'foo' do data_bag 'bar' raw_data({ 'auth' => 'baz' }) admins 'jtimberman' search '*:*' end ``` **To allow multiple admins access to an item**: ``` chef_vault_secret 'root-password' do admins 'jtimberman,paulmooring' data_bag 'secrets' raw_data({ 'auth' => 'DoNotUseThisPasswordForRoot' }) search '*:*' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chef_vault_secret/chocolatey_config Resource =========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chocolatey_config.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chocolatey_config.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chocolatey_config** resource to add or remove Chocolatey configuration keys. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [Chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. **New in Chef Infra Client 14.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **chocolatey_config** resource is: ``` chocolatey_config 'name' do config_key String # default value: 'name' unless specified value String action Symbol # defaults to :set if not specified end ``` where: * `chocolatey_config` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `config_key` and `value` are the properties available to this resource. Actions ------- --- The **chocolatey_config** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Sets a Chocolatey config value. (default) `:unset` Unsets a Chocolatey config value. Properties ---------- --- The **chocolatey_config** resource has the following properties: `config_key` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the config key name if it differs from the resource block’s name. `value` **Ruby Type:** String The value to set. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chocolatey_config** resource in recipes: **Set the Chocolatey cacheLocation config**: ``` chocolatey_config 'Set cacheLocation config' do config_key 'cacheLocation' value 'C:\temp\choco' end ``` **Unset a Chocolatey config**: ``` chocolatey_config 'BogusConfig' do action :unset end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chocolatey_config/chocolatey_package Resource ============================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chocolatey_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chocolatey_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chocolatey_package** resource to manage packages using the Chocolatey package manager on the Microsoft Windows platform. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. Warning The **chocolatey_package** resource must be specified as `chocolatey_package` and cannot be shortened to `package` in a recipe. **New in Chef Infra Client 12.7.** Syntax ------ --- The full syntax for all of the properties that are available to the **chocolatey_package** resource is: ``` chocolatey_package 'name' do list_options String options String, Array package_name String, Array password String returns Integer, Array # default value: [0, 2] source String timeout String, Integer user String version String, Array action Symbol # defaults to :install if not specified end ``` where: * `chocolatey_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `list_options`, `options`, `package_name`, `password`, `returns`, `source`, `timeout`, `user`, and `version` are the properties available to this resource. Actions ------- --- The **chocolatey_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and ensure that a package is the latest version. Properties ---------- --- The **chocolatey_package** resource has the following properties: `list_options` **Ruby Type:** String One (or more) additional list options that are passed to the command. New in Chef Infra Client 15.3 `options` **Ruby Type:** String, Array One (or more) additional options that are passed to the command. `package_name` **Ruby Type:** String, Array The name of the package. Default value: the name of the resource block. `password` **Ruby Type:** String The password to authenticate to the source. New in Chef Infra Client 15.3 `returns` **Ruby Type:** Integer, Array | **Default Value:** `[0, 2]` The exit code(s) returned by the `choco` command that indicate a successful action. See [Chocolatey Exit Codes](https://docs.chocolatey.org/en-us/choco/commands/info#exit-codes) for a complete list of exit codes used by Chocolatey. New in Chef Client 12.18 `source` **Ruby Type:** String The optional path to a package on the local file system or a reachable UNC path. Ensure that the path specified is to the **folder** containing the chocolatey package(s), not to the package itself. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `user` **Ruby Type:** String The username to authenticate feeds. New in Chef Infra Client 15.3 `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chocolatey_package** resource in recipes: **Install a Chocolatey package**: ``` chocolatey_package 'name of package' do action :install end ``` **Install a package with options with Chocolatey’s `--checksum` option**: ``` chocolatey_package 'name of package' do options '--checksum 1234567890' action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chocolatey_package/chocolatey_feature Resource ============================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [chocolatey_feature.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/chocolatey_feature.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **chocolatey_feature** resource to enable and disable Chocolatey features. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [Chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. **New in Chef Infra Client 15.1.** Syntax ------ --- The full syntax for all of the properties that are available to the **chocolatey_feature** resource is: ``` chocolatey_feature 'name' do feature_name String # default value: 'name' unless specified action Symbol # defaults to :enable if not specified end ``` where: * `chocolatey_feature` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `feature_name` is the property available to this resource. Actions ------- --- The **chocolatey_feature** resource has the following actions: `:disable` Disables a named Chocolatey feature. `:enable` Enables a named Chocolatey feature. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **chocolatey_feature** resource has the following properties: `feature_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the Chocolatey feature to enable or disable. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **chocolatey_feature** resource in recipes: **Enable the checksumFiles Chocolatey feature** ``` chocolatey_feature 'checksumFiles' do action :enable end ``` **Disable the checksumFiles Chocolatey feature** ``` chocolatey_feature 'checksumFiles' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/chocolatey_feature/cookbook_file Resource ======================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [cookbook_file.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/cookbook_file.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **cookbook_file** resource to transfer files from a sub-directory of `COOKBOOK_NAME/files/` to a specified path located on a host that is running Chef Infra Client. The file is selected according to file specificity, which allows different source files to be used based on the hostname, host platform (operating system, distro, or as appropriate), or platform version. Files that are located in the `COOKBOOK_NAME/files/default` sub-directory may be used on any platform. During a Chef Infra Client run, the checksum for each local file is calculated and then compared against the checksum for the same file as it currently exists in the cookbook on the Chef Infra Server. A file is not transferred when the checksums match. Only files that require an update are transferred from the Chef Infra Server to a node. Syntax ------ --- A **cookbook_file** resource block manages files by using files that exist within a cookbook’s `/files` directory. For example, to write the home page for an Apache website: ``` cookbook_file '/var/www/customers/public_html/index.php' do source 'index.php' owner 'web_admin' group 'web_admin' mode '0755' action :create end ``` where: * `'/var/www/customers/public_html/index.php'` is path to the file to be created * `'index.php'` is a file in the `/files` directory in a cookbook that is used to create that file (the contents of the file in the cookbook will become the contents of the file on the node) * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **cookbook_file** resource is: ``` cookbook_file 'name' do atomic_update true, false backup Integer, false # default value: 5 cookbook String force_unlink true, false # default value: false group String, Integer inherits true, false manage_symlink_source true, false mode String, Integer owner String, Integer path String # default value: 'name' unless specified rights Hash source String, Array verify String, Block action Symbol # defaults to :create if not specified end ``` where: * `cookbook_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `atomic_update`, `backup`, `cookbook`, `force_unlink`, `group`, `inherits`, `manage_symlink_source`, `mode`, `owner`, `path`, `rights`, `source`, and `verify` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **cookbook_file** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the **file** resource.) Properties ---------- --- The **cookbook_file** resource has the following properties: `atomic_update` **Ruby Type:** true, false | **Default Value:** `False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.` Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the `client.rb` file. `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `cookbook` **Ruby Type:** String | **Default Value:** `The current cookbook name` The cookbook in which a file is located (if it is not located in the current cookbook). `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `true`, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `false`, Chef will follow the symlink and will manage the permissions and content of the symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String The path to the destination at which a file is to be created. For example: `file.txt`. Microsoft Windows: A path that begins with a forward slash (`/`) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (`/`) is not recommended. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String, Array | **Default Value:** `The resource block's name` The name of the file in `COOKBOOK_NAME/files/default` or the path to a file located in `COOKBOOK_NAME/files`. The path must include the file name and its extension. This can be used to distribute specific files depending upon the platform used - see [File Specificity](#cookbook-file-specificity) for more information. `verify` **Ruby Type:** String, Block A block or a string that returns `true` or `false`. A string, when `true` is executed as a system command. A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block is `true`, Chef Infra Client will continue to update the file as appropriate. For example, this should return `true`: ``` cookbook_file '/tmp/baz' do verify { 1 == 1 } end ``` This should return `true`: ``` cookbook_file '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` This should return `true`: ``` cookbook_file '/tmp/bar' do verify { 1 == 1} end ``` And this should return `true`: ``` cookbook_file '/tmp/foo' do verify do |path| true end end ``` Whereas, this should return `false`: ``` cookbook_file '/tmp/turtle' do verify '/usr/bin/false' end ``` If a string or a block return `false`, the Chef Infra Client run will stop and an error is returned. ### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. ### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. File Specificity ---------------- A cookbook is frequently designed to work across many platforms and is often required to distribute a specific file to a specific platform. A cookbook can be designed to support the distribution of files across platforms, while ensuring that the correct file ends up on each system. The pattern for file specificity depends on two things: the lookup path and the source attribute. The first pattern that matches is used: 1. /host-$fqdn/$source 2. /$platform-$platform_version/$source 3. /$platform/$source 4. /default/$source 5. /$source Use an array with the `source` attribute to define an explicit lookup path. For example: ``` file '/conf.py' do source ['#{node.chef_environment}.py', 'conf.py'] end ``` The following example emulates the entire file specificity pattern by defining it as an explicit path: ``` file '/conf.py' do source %W( host-#{node['fqdn']}/conf.py #{node['platform']}-#{node['platform_version']}/conf.py #{node['platform']}/conf.py default/conf.py ) end ``` A cookbook may have a `/files` directory structure like this: ``` files/ host-foo.example.com ubuntu-20.04 ubuntu-20 ubuntu redhat-8.2 redhat-7.8 ... default ``` and a resource that looks something like the following: ``` cookbook_file '/usr/local/bin/apache2_module_conf_generate.pl' do source 'apache2_module_conf_generate.pl' mode '0755' owner 'root' group 'root' end ``` This resource is matched in the same order as the `/files` directory structure. For a node that is running Ubuntu 20.04, the second item would be the matching item and the location to which the file identified in the **cookbook_file** resource would be distributed: ``` host-foo.example.com/apache2_module_conf_generate.pl ubuntu-20.04/apache2_module_conf_generate.pl ubuntu-20/apache2_module_conf_generate.pl ubuntu/apache2_module_conf_generate.pl default/apache2_module_conf_generate.pl ``` If the `apache2_module_conf_generate.pl` file was located in the cookbook directory under `files/host-foo.example.com/`, the specified file(s) would only be copied to the machine with the domain name foo.example.com. **Host Notation** The naming of folders within cookbook directories must literally match the host notation used for file specificity matching. For example, if a host is named `foo.example.com`, the folder must be named `host-foo.example.com`. Examples -------- --- The following examples demonstrate various approaches for using the **cookbook_file** resource in recipes: Transfer a file ``` cookbook_file 'file.txt' do mode '0755' end ``` Handle cookbook_file and package resources in the same recipe When a **cookbook_file** resource and a **package** resource are both called from within the same recipe, use the `flush_cache` attribute to dump the in-memory Yum cache, and then use the repository immediately to ensure that the correct package is installed: ``` cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' end package 'only-in-custom-repo' do action :install flush_cache [ :before ] end ``` Install repositories from a file, trigger a command, and force the internal cache to reload The following example shows how to install new Yum repositories from a file, where the installation of the repository triggers a creation of the Yum cache that forces the internal cache for Chef Infra Client to reload: ``` execute 'create-yum-cache' do command 'yum -q makecache' action :nothing end ruby_block 'reload-internal-yum-cache' do block do Chef::Provider::Package::Yum::YumCache.instance.reload end action :nothing end cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' notifies :run, 'execute[create-yum-cache]', :immediately notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately end ``` Use a case statement The following example shows how a case statement can be used to handle a situation where an application needs to be installed on multiple platforms, but where the install directories are different paths, depending on the platform: ``` cookbook_file 'application.pm' do path case node['platform'] when 'centos','redhat' '/usr/lib/version/1.2.3/dir/application.pm' when 'arch' '/usr/share/version/core_version/dir/application.pm' else '/etc/version/dir/application.pm' end source "application-#{node['languages']['perl']['version']}.pm" owner 'root' group 'root' mode '0755' end ``` Manage dotfiles The following example shows using the **directory** and **cookbook_file** resources to manage dotfiles. The dotfiles are defined by a JSON data structure similar to: ``` "files": { ".zshrc": { "mode": '0755', "source": "dot-zshrc" }, ".bashrc": { "mode": '0755', "source": "dot-bashrc" }, ".bash_profile": { "mode": '0755', "source": "dot-bash_profile" }, } ``` and then the following resources manage the dotfiles: ``` if u.has_key?('files') u['files'].each do |filename, file_data| directory "#{home_dir}/#{File.dirname(filename)}" do recursive true mode '0755' end if file_data['subdir'] cookbook_file "#{home_dir}/#{filename}" do source "#{u['id']}/#{file_data['source']}" owner 'u['id']' group 'group_id' mode 'file_data['mode']' ignore_failure true backup 0 end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/cookbook_file/cron_access Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [cron_access.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/cron_access.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **cron_access** resource to manage cron’s cron.allow and cron.deny files. Note This resource previously shipped in the `cron` cookbook as `cron_manage`, which it can still be used as for backwards compatibility with existing Chef Infra Client releases. **New in Chef Infra Client 14.4.** Syntax ------ --- The full syntax for all of the properties that are available to the **cron_access** resource is: ``` cron_access 'name' do user String # default value: 'name' unless specified action Symbol # defaults to :allow if not specified end ``` where: * `cron_access` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `user` is the property available to this resource. Actions ------- --- The **cron_access** resource has the following actions: `:allow` Add the user to the cron.allow file. (default) `:deny` Add the user to the cron.deny file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **cron_access** resource has the following properties: `user` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the user name if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **cron_access** resource in recipes: **Add the mike user to cron.allow** ``` cron_access 'mike' ``` **Add the mike user to cron.deny** ``` cron_access 'mike' do action :deny end ``` **Specify the username with the user property** ``` cron_access 'Deny the jenkins user access to cron for security purposes' do user 'jenkins' action :deny end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/cron_access/cron Resource ============= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [cron.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/cron.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **cron** resource to manage cron entries for time-based job scheduling. Properties for a schedule will default to * if not provided. The cron resource requires access to a crontab program, typically cron. Warning The cron resource should only be used to modify an entry in a crontab file. The `cron_d` resource directly manages `cron.d` files. This resource ships in Chef Infra Client 14.4 or later and can also be found in the [cron](https://github.com/chef-cookbooks/cron) cookbook) for previous Chef Infra Client releases. Syntax ------ --- The full syntax for all of the properties that are available to the **cron** resource is: ``` cron 'name' do command String day Integer, String # default value: "*" environment Hash # default value: {} home String hour Integer, String # default value: "*" mailto String minute Integer, String # default value: "*" month Integer, String # default value: "*" path String shell String time Symbol time_out Hash # default value: {} user String # default value: "root" weekday Integer, String, Symbol # default value: "*" action Symbol # defaults to :create if not specified end ``` where: * `cron` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command`, `day`, `environment`, `home`, `hour`, `mailto`, `minute`, `month`, `path`, `shell`, `time`, `time_out`, `user`, and `weekday` are the properties available to this resource. Actions ------- --- The **cron** resource has the following actions: `:create` Create an entry in a cron table file (crontab). If an entry already exists (but does not match), update that entry to match. (default) `:delete` Delete an entry from a cron table file (crontab). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **cron** resource has the following properties: `command` **Ruby Type:** String | `REQUIRED` The command to be run, or the path to a file that contains the command to be run. `day` **Ruby Type:** Integer, String | **Default Value:** `*` The day of month at which the cron entry should run (`1 - 31`). `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `home` **Ruby Type:** String Set the `HOME` environment variable. `hour` **Ruby Type:** Integer, String | **Default Value:** `*` The hour at which the cron entry is to run (`0 - 23`). `mailto` **Ruby Type:** String Set the `MAILTO` environment variable. `minute` **Ruby Type:** Integer, String | **Default Value:** `*` The minute at which the cron entry should run (`0 - 59`). `month` **Ruby Type:** Integer, String | **Default Value:** `*` The month in the year on which a cron entry is to run (`1 - 12`, `jan-dec`, or `*`). `path` **Ruby Type:** String Set the `PATH` environment variable. `shell` **Ruby Type:** String Set the `SHELL` environment variable. `time` **Ruby Type:** Symbol **Allowed Values:** `:annually, :daily, :hourly, :midnight, :monthly, :reboot, :weekly, :yearly` A time interval. `time_out` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of timeouts in the form of `({'OPTION' => 'VALUE'})`. Accepted valid options are: * `preserve-status` (BOOL, default: ‘false’), * `foreground` (BOOL, default: ‘false’), * `kill-after` (in seconds), * `signal` (a name like ‘HUP’ or a number) New in Chef Infra Client 15.7 `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that runs the command. If the user property is changed, the original user for the crontab program continues to run until that crontab program is deleted. This property is not applicable on the AIX platform. `weekday` **Ruby Type:** Integer, String, Symbol | **Default Value:** `*` The day of the week on which this entry is to run (`0-7`, `mon-sun`, `monday-sunday`, or `*`), where Sunday is both `0` and `7`. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **cron** resource in recipes: **Run a program at a specified interval** ``` cron 'noop' do hour '5' minute '0' command '/bin/true' end ``` **Run an entry if a folder exists** ``` cron 'ganglia_tomcat_thread_max' do command "/usr/bin/gmetric -n 'tomcat threads max' -t uint32 -v '/usr/local/bin/tomcat-stat --thread-max'" only_if { ::File.exist?('/home/jboss') } end ``` **Run every Saturday, 8:00 AM** The following example shows a schedule that will run every hour at 8:00 each Saturday morning, and will then send an email to “<EMAIL>” after each run. ``` cron 'name_of_cron_entry' do minute '0' hour '8' weekday '6' mailto '<EMAIL>' action :create end ``` **Run once a week** ``` cron 'cookbooks_report' do minute '0' hour '0' weekday '1' user 'chefio' mailto '<EMAIL>' home '/srv/supermarket/shared/system' command %W{ cd /srv/supermarket/current && env RUBYLIB="/srv/supermarket/current/lib" RAILS_ASSET_ID=`git rev-parse HEAD` RAILS_ENV="#{rails_env}" bundle exec rake cookbooks_report }.join(' ') action :create end ``` **Run only in November** The following example shows a schedule that will run at 8:00 PM, every weekday (Monday through Friday), but only in November: ``` cron 'name_of_cron_entry' do minute '0' hour '20' day '*' month '11' weekday '1-5' action :create end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/cron/cron_d Resource ================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [cron_d.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/cron_d.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **cron_d** resource to manage cron job files in the `/etc/cron.d` directory. Warning Chef Infra Client also ships with the **cron** resource for managing the monolithic `/etc/crontab` file on platforms that lack cron.d support. See the [cron resource](../cron/index) for information on using that resource. **New in Chef Infra Client 14.4.** Syntax ------ --- A **cron_d** resource block manages cron.d files. For example, to get a weekly cookbook report from the Chef Supermarket: ``` cron_d 'cookbooks_report' do action :create minute '0' hour '0' weekday '1' user 'getchef' mailto '<EMAIL>' home '/srv/supermarket/shared/system' command %W{ cd /srv/supermarket/current && env RUBYLIB="/srv/supermarket/current/lib" RAILS_ASSET_ID=`git rev-parse HEAD` RAILS_ENV="#{rails_env}" bundle exec rake cookbooks_report }.join(' ') end ``` The full syntax for all of the properties that are available to the **cron_d** resource is: ``` cron_d 'name' do command String comment String cron_name String # default value: 'name' unless specified day Integer, String # default value: "*" environment Hash # default value: {} home String hour Integer, String # default value: "*" mailto String minute Integer, String # default value: "*" mode String, Integer # default value: "0600" month Integer, String # default value: "*" path String predefined_value String random_delay Integer shell String time_out Hash # default value: {} user String # default value: "root" weekday Integer, String, Symbol # default value: "*" action Symbol # defaults to :create if not specified end ``` where: * `cron_d` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command`, `comment`, `cron_name`, `day`, `environment`, `home`, `hour`, `mailto`, `minute`, `mode`, `month`, `path`, `predefined_value`, `random_delay`, `shell`, `time_out`, `user`, and `weekday` are the properties available to this resource. Actions ------- --- The **cron_d** resource has the following actions: `:create` (default) `:create_if_missing` Add a cron definition file to `/etc/cron.d`, but do not update an existing file. `:delete` Remove a cron definition file from `/etc/cron.d` if it exists. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **cron_d** resource has the following properties: `command` **Ruby Type:** String | `REQUIRED` The command to be run, or the path to a file that contains the command to be run. `comment` **Ruby Type:** String A comment to place in the cron.d file. `cron_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the cron name if it differs from the resource block’s name. `day` **Ruby Type:** Integer, String | **Default Value:** `*` The day of month at which the cron entry should run (`1 - 31`). `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `home` **Ruby Type:** String Set the `HOME` environment variable. `hour` **Ruby Type:** Integer, String | **Default Value:** `*` The hour at which the cron entry is to run (`0 - 23`). `mailto` **Ruby Type:** String Set the `MAILTO` environment variable. `minute` **Ruby Type:** Integer, String | **Default Value:** `*` The minute at which the cron entry should run (`0 - 59`). `mode` **Ruby Type:** String, Integer | **Default Value:** `0600` The octal mode of the generated crontab file. `month` **Ruby Type:** Integer, String | **Default Value:** `*` The month in the year on which a cron entry is to run (`1 - 12`, `jan-dec`, or `*`). `path` **Ruby Type:** String Set the `PATH` environment variable. `predefined_value` **Ruby Type:** String **Allowed Values:** `"@annually", "@daily", "@hourly", "@midnight", "@monthly", "@reboot", "@weekly", "@yearly"` Schedule your cron job with one of the special predefined value instead of ** * pattern. `random_delay` **Ruby Type:** Integer Set the `RANDOM_DELAY` environment variable in the cron.d file. `shell` **Ruby Type:** String Set the `SHELL` environment variable. `time_out` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of timeouts in the form of `({'OPTION' => 'VALUE'})`. Accepted valid options are: * `preserve-status` (BOOL, default: ‘false’), * `foreground` (BOOL, default: ‘false’), * `kill-after` (in seconds), * `signal` (a name like ‘HUP’ or a number) New in Chef Infra Client 15.7 `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that runs the command. `weekday` **Ruby Type:** Integer, String, Symbol | **Default Value:** `*` The day of the week on which this entry is to run (`0-7`, `mon-sun`, `monday-sunday`, or `*`), where Sunday is both `0` and `7`. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **cron_d** resource in recipes: **Run a program on the fifth hour of the day** ``` cron_d 'noop' do hour '5' minute '0' command '/bin/true' end ``` **Run an entry if a folder exists** ``` cron_d 'ganglia_tomcat_thread_max' do command "/usr/bin/gmetric -n 'tomcat threads max' -t uint32 -v '/usr/local/bin/tomcat-stat --thread-max'" only_if { ::File.exist?('/home/jboss') } end ``` **Run an entry every Saturday, 8:00 AM** ``` cron_d 'name_of_cron_entry' do minute '0' hour '8' weekday '6' mailto '<EMAIL>' command '/bin/true' action :create end ``` **Run an entry at 8:00 PM, every weekday (Monday through Friday), but only in November** ``` cron_d 'name_of_cron_entry' do minute '0' hour '20' day '*' month '11' weekday '1-5' command '/bin/true' action :create end ``` **Remove a cron job by name**: ``` cron_d 'job_to_remove' do action :delete end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/cron_d/csh Resource ============ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [csh.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/csh.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **csh** resource to execute scripts using the csh interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. Syntax ------ --- A **csh** resource block executes scripts using csh: ``` csh 'hello world' do code <<-EOH echo "Hello world!" echo "Current directory: " $cwd EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **csh** resource is: ``` csh 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `csh` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **csh** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. Properties ---------- --- The **csh** resource has the following properties: `code` **Ruby Type:** String | `REQUIRED` A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/csh/directory Resource ================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [directory.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/directory.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **directory** resource to manage a directory, which is a hierarchy of folders that comprises all of the information stored on a computer. The root directory is the top-level, under which the rest of the directory is organized. The directory resource uses the name property to specify the path to a location in a directory. Typically, permission to access that location in the directory is required. Syntax ------ --- A **directory** resource block declares a directory and the permissions needed on that directory. For example: ``` directory '/etc/apache2' do owner 'root' group 'root' mode '0755' action :create end ``` where: * `'/etc/apache2'` specifies the directory * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **directory** resource is: ``` directory 'name' do group String, Integer inherits true, false mode String, Integer owner String, Integer path String # defaults to 'name' if not specified recursive true, false rights Hash action Symbol # defaults to :create if not specified end ``` where: * `directory` is the resource. * `name` is the name of the resource block; when the `path` property is not specified, `name` is also the path to the directory, from the root * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `group`, `inherits`, `mode`, `owner`, `path`, `recursive`, and `rights` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **directory** resource has the following actions: `:create` Default. Create a directory. If a directory already exists (but does not match), update that directory to match. `:delete` Delete a directory. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **directory** resource has the following properties: `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the directory already exists, the existing mode on the directory is used. If `mode` is not specified, the directory does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'`, and then applies the umask for the system on which the directory is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the `name` of the resource block. See “Syntax” section above for more information. `recursive` **Ruby Type:** true, false | **Default Value:** `false` Create or delete parent directories recursively. For the owner, group, and mode properties, the value of this property applies only to the leaf directory. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. ### Recursive Directories The **remote_directory** resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the `recursive` attribute only applies `group`, `mode`, and `owner` attribute values to the remote directory itself and any inner directories the resource copies. A directory structure: ``` /foo /bar /baz ``` The following example shows a way create a file in the `/baz` directory: ``` remote_directory '/foo/bar/baz' do owner 'root' group 'root' mode '0755' action :create end ``` But with this example, the `group`, `mode`, and `owner` attribute values will only be applied to `/baz`. Which is fine, if that’s what you want. But most of the time, when the entire `/foo/bar/baz` directory structure is not there, you must be explicit about each directory. For example: ``` %w( /foo /foo/bar /foo/bar/baz ).each do |path| remote_directory path do owner 'root' group 'root' mode '0755' end end ``` This approach will create the correct hierarchy—`/foo`, then `/bar` in `/foo`, and then `/baz` in `/bar`—and also with the correct attribute values for `group`, `mode`, and `owner`. ### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **directory** resource in recipes: Create a directory ``` directory '/tmp/something' do owner 'root' group 'root' mode '0755' action :create end ``` Create a directory in Microsoft Windows ``` directory "C:\\tmp\\something" do rights :full_control, "DOMAIN\\User" inherits false action :create end ``` or: ``` directory 'C:\tmp\something' do rights :full_control, 'DOMAIN\User' inherits false action :create end ``` Note The difference between the two previous examples is the single- versus double-quoted strings, where if the double quotes are used, the backslash character (`\`) must be escaped using the Ruby escape character (which is a backslash). Create a directory recursively ``` %w{dir1 dir2 dir3}.each do |dir| directory "/tmp/mydirs/#{dir}" do mode '0755' owner 'root' group 'root' action :create recursive true end end ``` Delete a directory ``` directory '/tmp/something' do recursive true action :delete end ``` Set directory permissions using a variable The following example shows how read/write/execute permissions can be set using a variable named `user_home`, and then for owners and groups on any matching node: ``` user_home = "/#{node[:matching_node][:user]}" directory user_home do owner 'node[:matching_node][:user]' group 'node[:matching_node][:group]' mode '0755' action :create end ``` where `matching_node` represents a type of node. For example, if the `user_home` variable specified `{node[:nginx]...}`, a recipe might look similar to: ``` user_home = "/#{node[:nginx][:user]}" directory user_home do owner 'node[:nginx][:user]' group 'node[:nginx][:group]' mode '0755' action :create end ``` Set directory permissions for a specific type of node The following example shows how permissions can be set for the `/certificates` directory on any node that is running Nginx. In this example, permissions are being set for the `owner` and `group` properties as `root`, and then read/write permissions are granted to the root. ``` directory "#{node[:nginx][:dir]}/shared/certificates" do owner 'root' group 'root' mode '0755' recursive true end ``` Reload the configuration The following example shows how to reload the configuration of a chef-client using the **remote_file** resource to: * using an if statement to check whether the plugins on a node are the latest versions * identify the location from which Ohai plugins are stored * using the `notifies` property and a **ruby_block** resource to trigger an update (if required) and to then reload the client.rb file. ``` directory 'node[:ohai][:plugin_path]' do owner 'chef' recursive true end ruby_block 'reload_config' do block do Chef::Config.from_file('/etc/chef/client.rb') end action :nothing end if node[:ohai].key?(:plugins) node[:ohai][:plugins].each do |plugin| remote_file node[:ohai][:plugin_path] +"/#{plugin}" do source plugin owner 'chef' notifies :run, 'ruby_block[reload_config]', :immediately end end end ``` Manage dotfiles The following example shows using the **directory** and **cookbook_file** resources to manage dotfiles. The dotfiles are defined by a JSON data structure similar to: ``` "files": { ".zshrc": { "mode": '0755', "source": "dot-zshrc" }, ".bashrc": { "mode": '0755', "source": "dot-bashrc" }, ".bash_profile": { "mode": '0755', "source": "dot-bash_profile" }, } ``` and then the following resources manage the dotfiles: ``` if u.has_key?('files') u['files'].each do |filename, file_data| directory "#{home_dir}/#{File.dirname(filename)}" do recursive true mode '0755' end if file_data['subdir'] cookbook_file "#{home_dir}/#{filename}" do source "#{u['id']}/#{file_data['source']}" owner 'u['id']' group 'group_id' mode 'file_data['mode']' ignore_failure true backup 0 end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/directory/dmg_package Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [dmg_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/dmg_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **dmg_package** resource to install a package from a .dmg file. The resource will retrieve the dmg file from a remote URL, mount it using macOS' `hdidutil`, copy the application (.app directory) to the specified destination (`/Applications`), and detach the image using `hdiutil`. The dmg file will be stored in the `Chef::Config[:file_cache_path]`. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **dmg_package** resource is: ``` dmg_package 'name' do accept_eula true, false # default value: false allow_untrusted true, false # default value: false app String # default value: 'name' unless specified checksum String destination String # default value: "/Applications" dmg_name String # default value: The value passed for the application name. dmg_passphrase String file String headers Hash owner String, Integer package_id String source String type String # default value: "app" volumes_dir String # default value: The value passed for the application name. action Symbol # defaults to :install if not specified end ``` where: * `dmg_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_eula`, `allow_untrusted`, `app`, `checksum`, `destination`, `dmg_name`, `dmg_passphrase`, `file`, `headers`, `owner`, `package_id`, `source`, `type`, and `volumes_dir` are the properties available to this resource. Actions ------- --- The **dmg_package** resource has the following actions: `:install` Installs the application. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **dmg_package** resource has the following properties: `accept_eula` **Ruby Type:** true, false | **Default Value:** `false` Specify whether to accept the EULA. Certain dmg files require acceptance of EULA before mounting. `allow_untrusted` **Ruby Type:** true, false | **Default Value:** `false` Allow installation of packages that do not have trusted certificates. `app` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the application as it appears in the `/Volumes` directory if it differs from the resource block’s name. `checksum` **Ruby Type:** String The sha256 checksum of the `.dmg` file to download. `destination` **Ruby Type:** String | **Default Value:** `/Applications` The directory to copy the `.app` into. `dmg_name` **Ruby Type:** String | **Default Value:** `The value passed for the application name.` The name of the `.dmg` file if it differs from that of the app, or if the name has spaces. `dmg_passphrase` **Ruby Type:** String Specify a passphrase to be used to decrypt the `.dmg` file during the mount process. `file` **Ruby Type:** String The absolute path to the `.dmg` file on the local system. `headers` **Ruby Type:** Hash Allows custom HTTP headers (like cookies) to be set on the `remote_file` resource. `owner` **Ruby Type:** String, Integer The user that should own the package installation. `package_id` **Ruby Type:** String The package ID that is registered with `pkgutil` when a `pkg` or `mpkg` is installed. `source` **Ruby Type:** String The remote URL that is used to download the `.dmg` file, if specified. `type` **Ruby Type:** String | **Default Value:** `app` **Allowed Values:** `"app", "mpkg", "pkg"` The type of package. `volumes_dir` **Ruby Type:** String | **Default Value:** `The value passed for the application name.` The directory under `/Volumes` where the `dmg` is mounted if it differs from the name of the `.dmg` file. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **dmg_package** resource in recipes: **Install Google Chrome via the DMG package**: ``` dmg_package 'Google Chrome' do dmg_name 'googlechrome' source 'https://dl-ssl.google.com/chrome/mac/stable/GGRM/googlechrome.dmg' checksum '7daa2dc5c46d9bfb14f1d7ff4b33884325e5e63e694810adc58f14795165c91a' action :install end ``` **Install VirtualBox from the .mpkg**: ``` dmg_package 'Virtualbox' do source 'http://dlc.sun.com.edgesuite.net/virtualbox/4.0.8/VirtualBox-4.0.8-71778-OSX.dmg' type 'mpkg' end ``` **Install pgAdmin and automatically accept the EULA**: ``` dmg_package 'pgAdmin3' do source 'http://wwwmaster.postgresql.org/redir/198/h/pgadmin3/release/v1.12.3/osx/pgadmin3-1.12.3.dmg' checksum '9435f79d5b52d0febeddfad392adf82db9df159196f496c1ab139a6957242ce9' accept_eula true end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/dmg_package/dsc_resource Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [dsc_resource.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/dsc_resource.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Windows PowerShell is a task-based command-line shell and scripting language developed by Microsoft. Windows PowerShell uses a document-oriented approach for managing Microsoft Windows-based machines, similar to the approach that is used for managing Unix and Linux-based machines. Windows PowerShell is [a tool-agnostic platform](https://docs.microsoft.com/en-us/powershell/scripting/powershell-scripting) that supports using Chef for configuration management. Desired State Configuration (DSC) is a feature of Windows PowerShell that provides [a set of language extensions, cmdlets, and resources](https://docs.microsoft.com/en-us/powershell/dsc/overview) that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell. The **dsc_resource** resource allows any DSC resource to be used in a Chef recipe, as well as any custom resources that have been added to your Windows PowerShell environment. Microsoft [frequently adds new resources](https://github.com/powershell/DscResources) to the DSC resource collection. Warning Using the **dsc_resource** has the following requirements: * Windows Management Framework (WMF) 5.0 (or higher) * The **dsc_resource** resource can only use binary- or script-based resources. Composite DSC resources may not be used. This is because composite resources aren’t “real” resources from the perspective of the Local Configuration Manager (LCM). Composite resources are used by the “configuration” keyword from the `PSDesiredStateConfiguration` module, and then evaluated in that context. When using DSC to create the configuration document (the Managed Object Framework (MOF) file) from the configuration command, the composite resource is evaluated. Any individual resources from that composite resource are written into the Managed Object Framework (MOF) document. As far as the Local Configuration Manager (LCM) is concerned, there is no such thing as a composite resource. Unless that changes, the **dsc_resource** resource and/or `Invoke-DscResource` command cannot directly use them. Syntax ------ --- A **dsc_resource** resource block allows DSC resources to be used in a Chef recipe. For example, the DSC `Archive` resource: ``` Archive ExampleArchive { Ensure = "Present" Path = "C:\Users\Public\Documents\example.zip" Destination = "C:\Users\Public\Documents\ExtractionPath" } ``` and then the same **dsc_resource** with Chef: ``` dsc_resource 'example' do resource :archive property :ensure, 'Present' property :path, "C:\Users\Public\Documents\example.zip" property :destination, "C:\Users\Public\Documents\ExtractionPath" end``` ``` The full syntax for all of the properties that are available to the **dsc_resource** resource is: ``` dsc_resource 'name' do module_name String module_version String property Symbol reboot_action Symbol # default value: :nothing resource Symbol timeout Integer action Symbol # defaults to :run if not specified end ``` where: * `dsc_resource` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `property` is zero (or more) properties in the DSC resource, where each property is entered on a separate line, `:dsc_property_name` is the case-insensitive name of that property, and `"property_value"` is a Ruby value to be applied by Chef Infra Client * `module_name`, `module_version`, `property`, `reboot_action`, `resource`, and `timeout` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **dsc_resource** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Use to run the DSC configuration defined as defined in this resource. Properties ---------- --- The **dsc_resource** resource has the following properties: `module_name` **Ruby Type:** String The name of the module from which a DSC resource originates. If this property is not specified, it will be inferred. `module_version` **Ruby Type:** String The version number of the module to use. PowerShell 5.0.10018.0 (or higher) supports having multiple versions of a module installed. This should be specified along with the `module_name`. New in Chef Client 12.21 `property` **Ruby Type:** Symbol A property from a Desired State Configuration (DSC) resource. Use this property multiple times, one for each property in the Desired State Configuration (DSC) resource. The format for this property must follow `property :dsc_property_name, "property_value"` for each DSC property added to the resource block. The `:dsc_property_name` must be a symbol. Use the following Ruby types to define `property_value`: | Ruby | Windows PowerShell | | --- | --- | | `Array` | `Object[]` | | `Chef::Util::Powershell:PSCredential` | `PSCredential` | | `False` | `bool($false)` | | `Fixnum` | `Integer` | | `Float` | `Double` | | `Hash` | `Hashtable` | | `True` | `bool($true)` | These are converted into the corresponding Windows PowerShell type during a Chef Infra Client run. `reboot_action` **Ruby Type:** Symbol | **Default Value:** `:nothing` **Allowed Values:** `:nothing, :reboot_now, :request_reboot` Use to request an immediate reboot or to queue a reboot using the :reboot_now (immediate reboot) or :request_reboot (queued reboot) actions built into the reboot resource. New in Chef Client 12.6 `resource` **Ruby Type:** Symbol The name of the DSC resource. This value is case-insensitive and must be a symbol that matches the name of the DSC resource. For built-in DSC resources, use the following values: | Value | Description | | --- | --- | | `:archive` | Use to [unpack archive (.zip) files](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/archiveresource). | | `:environment` | Use to [manage system environment variables](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/environmentresource). | | `:file` | Use to [manage files and directories](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/fileresource). | | `:group` | Use to [manage local groups](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/groupresource). | | `:log` | Use to [log configuration messages](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/logresource). | | `:package` | Use to [install and manage packages](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/packageresource). | | `:registry` | Use to [manage registry keys and registry key values](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/registryresource). | | `:script` | Use to [run PowerShell script blocks](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/scriptresource). | | `:service` | Use to [manage services](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/serviceresource). | | `:user` | Use to [manage local user accounts](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/userresource). | | `:windowsfeature` | Use to [add or remove Windows features and roles](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/windowsfeatureresource). | | `:windowsoptionalfeature` | Use to configure Microsoft Windows optional features. | | `:windowsprocess` | Use to [configure Windows processes](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/windowsprocessresource). | Any DSC resource may be used in a Chef recipe. For example, the DSC Resource Kit contains resources for [configuring Active Directory components](http://www.powershellgallery.com/packages/xActiveDirectory/2.8.0.0), such as `xADDomain`, `xADDomainController`, and `xADUser`. Assuming that these resources are available to Chef Infra Client, the corresponding values for the `resource` attribute would be: `:xADDomain`, `:xADDomainController`, and `xADUser`. `timeout` **Ruby Type:** Integer The amount of time (in seconds) a command is to wait before timing out. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **dsc_resource** resource in recipes: Open a Zip file ``` dsc_resource 'example' do resource :archive property :ensure, 'Present' property :path, 'C:\Users\Public\Documents\example.zip' property :destination, 'C:\Users\Public\Documents\ExtractionPath' end ``` Manage users and groups ``` dsc_resource 'demogroupadd' do resource :group property :groupname, 'demo1' property :ensure, 'present' end dsc_resource 'useradd' do resource :user property :username, 'Foobar1' property :fullname, 'Foobar1' property :password, ps_credential('P@assword!') property :ensure, 'present' end dsc_resource 'AddFoobar1ToUsers' do resource :Group property :GroupName, 'demo1' property :MembersToInclude, ['Foobar1'] end ``` Create and register a windows service The following example creates a windows service, defines it’s execution path, and prevents windows from starting the service in case the executable is not at the defined location: ``` dsc_resource 'NAME' do resource :service property :name, 'NAME' property :startuptype, 'Disabled' property :path, 'D:\\Sites\\Site_name\file_to_run.exe' property :ensure, 'Present' property :state, 'Stopped' end ``` Create a test message queue The following example creates a file on a node (based on one that is located in a cookbook), unpacks the `MessageQueue.zip` Windows PowerShell module, and then uses the **dsc_resource** to ensure that Message Queuing (MSMQ) sub-features are installed, a test queue is created, and that permissions are set on the test queue: ``` cookbook_file 'cMessageQueue.zip' do path "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip" action :create_if_missing end windows_zipfile "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" do source "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip" action :unzip end dsc_resource 'install-sub-features' do resource :windowsfeature property :ensure, 'Present' property :name, 'msmq' property :IncludeAllSubFeature, true end dsc_resource 'create-test-queue' do resource :cPrivateMsmqQueue property :ensure, 'Present' property :name, 'Test_Queue' end dsc_resource 'set-permissions' do resource :cPrivateMsmqQueuePermissions property :ensure, 'Present' property :name, 'Test_Queue_Permissions' property :QueueNames, 'Test_Queue' property :ReadUsers, node['msmq']['read_user'] end ``` Example to show usage of module properties ``` dsc_resource 'test-cluster' do resource :xCluster module_name 'xFailOverCluster' module_version '1.6.0.0' property :name, 'TestCluster' property :staticipaddress, '10.0.0.3' property :domainadministratorcredential, ps_credential('abcd') end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/dsc_resource/freebsd_package Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [freebsd_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/freebsd_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **freebsd_package** resource to manage packages for the FreeBSD platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. Syntax ------ --- A **freebsd_package** resource block manages a package on a node, typically by installing it. The simplest use of the **freebsd_package** resource is: ``` freebsd_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **freebsd_package** resource is: ``` freebsd_package 'name' do options String package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `freebsd_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **freebsd_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. Properties ---------- --- The **freebsd_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **freebsd_package** resource in recipes: Install a package ``` freebsd_package 'name of package' do action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/freebsd_package/dpkg_package Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [dpkg_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/dpkg_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **dpkg_package** resource to manage packages for the dpkg platform. When a package is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. Syntax ------ --- A **dpkg_package** resource block manages a package on a node, typically by installing it. The simplest use of the **dpkg_package** resource is: ``` dpkg_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **dpkg_package** resource is: ``` dpkg_package 'name' do options String, Array package_name String, Array response_file String response_file_variables Hash source String, Array timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `dpkg_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `response_file`, `response_file_variables`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **dpkg_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. Properties ---------- --- The **dpkg_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `response_file` **Ruby Type:** String The direct path to the file used to pre-seed a package. `response_file_variables` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of response file variables in the form of {‘VARIABLE’ => ‘VALUE’}. `source` **Ruby Type:** String, Array The path to a package in the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Examples -------- --- The following examples demonstrate various approaches for using the **dpkg_package** resource in recipes: Install a package ``` dpkg_package 'wget_1.13.4-2ubuntu1.4_amd64.deb' do source '/foo/bar/wget_1.13.4-2ubuntu1.4_amd64.deb' action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/dpkg_package/dnf_package Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [dnf_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/dnf_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **dnf_package** resource to install, upgrade, and remove packages with DNF for Fedora and RHEL 8+. The dnf_package resource is able to resolve provides data for packages much like DNF can do when it is run from the command line. This allows a variety of options for installing packages, like minimum versions, virtual provides and library names. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. **New in Chef Infra Client 12.18.** Syntax ------ --- A **dnf_package** resource block manages a package on a node, typically by installing it. The simplest use of the **dnf_package** resource is: ``` dnf_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **dnf_package** resource is: ``` dnf_package 'name' do allow_downgrade true, false # default value: true arch String, Array flush_cache Hash # default value: {"before"=>false, "after"=>false} options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `dnf_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `arch`, `flush_cache`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **dnf_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:lock` Locks the DNF package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:unlock` Unlocks the DNF package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **dnf_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. `arch` **Ruby Type:** String, Array The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name. `flush_cache` **Ruby Type:** Hash | **Default Value:** `{"before"=>false, "after"=>false}` Flush the in-memory cache before or after a DNF operation that installs, upgrades, or removes a package. DNF automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while a Chef Infra Client run is in-progress. As an array: ``` dnf_package 'some-package' do #... flush_cache [ :before ] #... end ``` and as a Hash: ``` dnf_package 'some-package' do #... flush_cache( { :after => true } ) #... end ``` Note The `flush_cache` property does not flush the local DNF cache! Use dnf tools—`dnf clean metadata`, `dnf clean packages`, `dnf clean all`—to clean the local DNF cache. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. This property is ignored when using the `:upgrade` action. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Examples -------- --- The following examples demonstrate various approaches for using the **dnf_package** resource in recipes: Install an exact version ``` dnf_package 'netpbm = 10.35.58-8.el5' ``` Install a minimum version ``` dnf_package 'netpbm >= 10.35.58-8.el5' ``` Install a minimum version using the default action ``` dnf_package 'netpbm' ``` To install a package ``` dnf_package 'netpbm' do action :install end ``` To install a partial minimum version ``` dnf_package 'netpbm >= 10' ``` To install a specific architecture ``` dnf_package 'netpbm' do arch 'i386' end ``` or: ``` dnf_package 'netpbm.x86_64' ``` To install a specific version-release ``` dnf_package 'netpbm' do version '10.35.58-8.el5' end ``` To install a specific version (even when older than the current) ``` dnf_package 'tzdata' do version '2011b-1.el5' end ``` Handle cookbook_file and dnf_package resources in the same recipe When a **cookbook_file** resource and a **dnf_package** resource are both called from within the same recipe, use the `flush_cache` attribute to dump the in-memory DNF cache, and then use the repository immediately to ensure that the correct package is installed: ``` cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' end dnf_package 'only-in-custom-repo' do action :install flush_cache [ :before ] end ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/dnf_package/file Resource ============= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [file.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/file.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **file** resource to manage files directly on a node. Note Use the **cookbook_file** resource to copy a file from a cookbook’s `/files` directory. Use the **template** resource to create a file based on a template in a cookbook’s `/templates` directory. And use the **remote_file** resource to transfer a file to a node from a remote location. Syntax ------ --- A **file** resource block manages files that exist on nodes. For example, to write the home page for an Apache website: ``` file '/var/www/customers/public_html/index.php' do content '<html>This is a placeholder for the home page.</html>' mode '0755' owner 'web_admin' group 'web_admin' end ``` where: * `'/var/www/customers/public_html/index.php'` is path to the file and also the filename to be managed * `content` defines the contents of the file The full syntax for all of the properties that are available to the **file** resource is: ``` file 'name' do atomic_update true, false backup false, Integer checksum String content String force_unlink true, false group String, Integer inherits true, false manage_symlink_source true, false mode String, Integer owner String, Integer path String # defaults to 'name' if not specified rights Hash verify String, Block, Symbol action Symbol # defaults to :create if not specified end ``` where: * `file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `atomic_update`, `backup`, `checksum`, `content`, `force_unlink`, `group`, `inherits`, `manage_symlink_source`, `mode`, `owner`, `path`, `rights`, `sensitive`, and `verify` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **file** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. Properties ---------- --- The **file** resource has the following properties: `atomic_update` **Ruby Type:** true, false | **Default Value:** `False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.` Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the `client.rb` file. `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `checksum` **Ruby Type:** String The SHA-256 checksum of the file. Use to ensure that a specific file is used. If the checksum does not match, the file is not used. `content` **Ruby Type:** String A string that is written to the file. The contents of this property replace any previous content when this property has something other than the default value. The default behavior will not modify content. `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `false`, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `true`, Chef will follow the symlink and will manage the permissions and content of symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String The full path to the file, including the file name and its extension. For example: `/files/file.txt`. Default value: the `name` of the resource block. See “Syntax” section above for more information. Microsoft Windows: A path that begins with a forward slash (`/`) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (`/`) is not recommended. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `verify` **Ruby Type:** String, Block, Symbol Allows verification of a file'’s contents before it is created. Creates a temporary file and then allows execution of commands or Ruby code. If this code evaluates to true, the file is created. If the code evaluates to false, an error is raised. The types for this property are a block, string, or a symbol. When specified as a block, it returns `true` or `false`. When specified as a string, it is executed as a system command. It returns `true` if the command returns 0 as its exit status code and `false` if the command returns a non-zero exit status code. When using a built-in verifier symbol it returns `true` if the verifier succeeds else it returns `false`. Currently suppported verifiers are `:yaml`, `:json` and `:systemd_unit`. Note A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block returns `true`, Chef Infra Client will continue to update the file as appropriate.' For example, this should return `true`: ``` file '/tmp/baz' do verify { 1 == 1 } end ``` This should also return `true`: ``` file '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` In this example, the `%{path}` portion of this command is expanded to the temporary location where a copy of the file to be created exists. This will use Nginx’s syntax checking feature to ensure the file is a valid Nginx configuration file before writing the file. An error will be raised if the executed command returns a non-zero exit status code. This should return `true`: ``` file '/tmp/foo' do content "hello" verify do |path| open(path).read.include? "hello" end end ``` Whereas, this should return `false`: ``` file '/tmp/foo' do content "goodbye" verify do |path| open(path).read.include? "hello" end end ``` When using one of the built-in symbols(`:json`, `:yaml`, `:systemd_unit`) This should return `true`: ``` file 'foo.json' do content '{"foo": "bar"}' verify :json end ``` Whereas, this should return `false`: ``` file 'foo.yaml' do content "--- foo: 'foo-" verify :yaml end ``` If a string, block or symbol returns `false`, the Chef Infra Client run will stop and an error is raised. ### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. ### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **file** resource in recipes: Create a file ``` file '/tmp/something' do owner 'root' group 'root' mode '0755' action :create end ``` Create a file in Microsoft Windows To create a file in Microsoft Windows, be sure to add an escape character—`\`—before the backslashes in the paths: ``` file 'C:\\tmp\\something.txt' do rights :read, 'Everyone' rights :full_control, 'DOMAIN\\User' action :create end ``` Remove a file ``` file '/tmp/something' do action :delete end ``` Set file modes ``` file '/tmp/something' do mode '0755' end ``` Delete a repository using yum to scrub the cache ``` # the following code sample thanks to gaffneyc @ https://gist.github.com/918711 execute 'clean-yum-cache' do command 'yum clean all' action :nothing end file '/etc/yum.repos.d/bad.repo' do action :delete notifies :run, 'execute[clean-yum-cache]', :immediately notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately end ``` Add the value of a data bag item to a file The following example shows how to get the contents of a data bag item named `impossible_things`, create a .pem file located at `some/directory/path/`, and then use the `content` attribute to update the contents of that file with the value of the `impossible_things` data bag item: ``` private_key = data_bag_item('impossible_things', private_key_name)['private_key'] file "some/directory/path/#{private_key_name}.pem" do content private_key owner 'root' group 'group' mode '0755' end ``` Write a YAML file The following example shows how to use the `content` property to write a YAML file: ``` file "#{app['deploy_to']}/shared/config/settings.yml" do owner "app['owner']" group "app['group']" mode '0755' content app.to_yaml end ``` Write a string to a file The following example specifies a directory, and then uses the `content` property to add a string to the file created in that directory: ``` status_file = '/path/to/file/status_file' file status_file do owner 'root' group 'root' mode '0755' content 'My favourite foremost coastal Antarctic shelf, oh Larsen B!' end ``` Create a file from a copy The following example shows how to copy a file from one directory to another, locally on a node: ``` file '/root/1.txt' do content IO.read('/tmp/1.txt') action :create end ``` where the `content` attribute uses the Ruby `IO.read` method to get the contents of the `/tmp/1.txt` file. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/file/gem_package Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [gem_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/gem_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **gem_package** resource to manage gem packages that are only included in recipes. When a gem is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. Note The **gem_package** resource must be specified as `gem_package` and cannot be shortened to `package` in a recipe. Warning The **chef_gem** and **gem_package** resources are both used to install Ruby gems. For any machine on which Chef Infra Client is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is available only to Chef Infra Client. Use the **chef_gem** resource to install gems into the instance of Ruby that is dedicated to Chef Infra Client. Use the **gem_package** resource to install all other gems (i.e. install gems system-wide). Syntax ------ --- The full syntax for all of the properties that are available to the **gem_package** resource is: ``` gem_package 'name' do clear_sources true, false gem_binary String include_default_source true, false options String, Hash, Array package_name String source String, Array timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `gem_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `clear_sources`, `gem_binary`, `include_default_source`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **gem_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **gem_package** resource has the following properties: `clear_sources` **Ruby Type:** true, false | **Default Value:** `false unless `clear_gem_sources` set to true in the `client.rb` config.` Set to `true` to download a gem from the path specified by the `source` property (and not from RubyGems). `gem_binary` **Ruby Type:** String The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by Chef Infra Client will be used. `include_default_source` **Ruby Type:** true, false Set to `false` to not include `Chef::Config[:rubygems_url]` in the sources. New in Chef Client 13.0 `options` **Ruby Type:** String, Hash, Array Options for the gem install, either a Hash or a String. When a hash is given, the options are passed to `Gem::DependencyInstaller.new`, and the gem will be installed via the gems API. When a String is given, the gem will be installed by shelling out to the gem command. Using a Hash of options with an explicit gem_binary will result in undefined behavior. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String, Array Optional. The URL, or list of URLs, at which the gem package is located. This list is added to the source configured in `Chef::Config[:rubygems_url]` (see also include_default_source) to construct the complete list of rubygems sources. Users in an ‘airgapped’ environment should set Chef::Config[:rubygems_url] to their local RubyGems mirror. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **gem_package** resource in recipes: The following examples demonstrate various approaches for using the **gem_package** resource in recipes: **Install a gem file from the local file system** ``` gem_package 'loofah' do source '/tmp/loofah-2.7.0.gem' action :install end ``` **Use the `ignore_failure` common attribute** ``` gem_package 'syntax' do action :install ignore_failure true end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/gem_package/dsc_script Resource ==================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [dsc_script.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/dsc_script.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Windows PowerShell is a task-based command-line shell and scripting language developed by Microsoft. Windows PowerShell uses a document-oriented approach for managing Microsoft Windows-based machines, similar to the approach that is used for managing Unix and Linux-based machines. Windows PowerShell is [a tool-agnostic platform](https://docs.microsoft.com/en-us/powershell/scripting/powershell-scripting) that supports using Chef for configuration management. Desired State Configuration (DSC) is a feature of Windows PowerShell that provides [a set of language extensions, cmdlets, and resources](https://docs.microsoft.com/en-us/powershell/dsc/overview) that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell. Many DSC resources are comparable to built-in Chef Infra resources. For example, both DSC and Chef have **file**, **package**, and **service** resources. The **dsc_script** resource is most useful for those DSC resources that do not have a direct comparison to a resource in Chef, such as the `Archive` resource, a custom DSC resource, an existing DSC script that performs an important task, and so on. Use the **dsc_script** resource to embed the code that defines a DSC configuration directly within a Chef Infra recipe. Note Windows PowerShell 4.0 is required for using the **dsc_script** resource with Chef Infra. Note The WinRM service must be enabled. (Use `winrm quickconfig` to enable the service.) Warning The **dsc_script** resource may not be used in the same run-list with the **dsc_resource**. This is because the **dsc_script** resource requires that `RefreshMode` in the Local Configuration Manager be set to `Push`, whereas the **dsc_resource** resource requires it to be set to `Disabled`. Syntax ------ --- A **dsc_script** resource block embeds the code that defines a DSC configuration directly within a Chef recipe: ``` dsc_script 'get-dsc-resource-kit' do code <<-EOH Archive reskit { ensure = 'Present' path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" } EOH end ``` where: * the **remote_file** resource is first used to download the `DSCResourceKit620082014.zip` file. The full syntax for all of the properties that are available to the **dsc_script** resource is: ``` dsc_script 'name' do code String command String configuration_data String configuration_data_script String configuration_name String cwd String environment Hash flags Hash imports Array timeout Integer action Symbol # defaults to :run if not specified end ``` where: * `dsc_script` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `command`, `configuration_data`, `configuration_data_script`, `configuration_name`, `cwd`, `environment`, `flags`, `imports`, and `timeout` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **dsc_script** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Use to run the DSC configuration defined as defined in this resource. Properties ---------- --- The **dsc_script** resource has the following properties: `code` **Ruby Type:** String The code for the DSC configuration script. This property may not be used in conjunction with the `command` property. `command` **Ruby Type:** String The path to a valid Windows PowerShell data file that contains the DSC configuration script. This data file must be capable of running independently of Chef and must generate a valid DSC configuration. This property may not be used in conjunction with the `code` property. `configuration_data` **Ruby Type:** String The configuration data for the DSC script. The configuration data must be [a valid Windows PowerShell data file](https://docs.microsoft.com/en-us/powershell/). This property may not be used in conjunction with the `configuration_data_script` property. `configuration_data_script` **Ruby Type:** String The path to a valid Windows PowerShell data file that also contains a node called `localhost`. This property may not be used in conjunction with the `configuration_data` property. `configuration_name` **Ruby Type:** String The name of a valid Windows PowerShell cmdlet. The name may only contain letter (a-z, A-Z), number (0-9), and underscore (_) characters and should start with a letter. The name may not be null or empty. This property may not be used in conjunction with the `code` property. `cwd` **Ruby Type:** String The current working directory. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of ({‘ENV_VARIABLE’ => ‘VALUE’}). (These variables must exist for a command to be run successfully). `flags` **Ruby Type:** Hash Pass parameters to the DSC script that is specified by the `command` property. Parameters are defined as key-value pairs, where the value of each key is the parameter to pass. This property may not be used in the same recipe as the `code` property. For example: `flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' })`. `imports` **Ruby Type:** Array Warning This property **MUST** be used with the `code` attribute. Use to import DSC resources from a module. To import all resources from a module, specify only the module name: ``` imports 'module_name' ``` To import specific resources, specify the module name, and then specify the name for each resource in that module to import: ``` imports 'module_name', 'resource_name_a', 'resource_name_b', ... ``` For example, to import all resources from a module named `cRDPEnabled`: ``` imports 'cRDPEnabled' ``` To import only the `PSHOrg_cRDPEnabled` resource: ``` imports 'cRDPEnabled', 'PSHOrg_cRDPEnabled' ``` `timeout` **Ruby Type:** Integer The amount of time (in seconds) a command is to wait before timing out. ### ps_credential Helper Use the `ps_credential` helper to embed a `PSCredential` object— [a set of security credentials, such as a user name or password](https://technet.microsoft.com/en-us/magazine/ff714574.aspx) —within a script, which allows that script to be run using security credentials. For example, assuming the `CertificateID` is configured in the local configuration manager, the `SeaPower1@3` object is created and embedded within the `seapower-user` script: ``` dsc_script 'seapower-user' do code <<-EOH User AlbertAtom { UserName = 'AlbertAtom' Password = #{ps_credential('SeaPower1@3')} } EOH configuration_data <<-EOH @{ AllNodes = @( @{ NodeName = "localhost"; CertificateID = 'A8D1234559F349F7EF19104678908F701D4167' } ) } EOH end ``` Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **dsc_script** resource in recipes: Specify DSC code directly DSC data can be specified directly in a recipe: ``` dsc_script 'emacs' do code <<-EOH Environment 'texteditor' { Name = 'EDITOR' Value = 'c:\\emacs\\bin\\emacs.exe' } EOH end ``` Specify DSC code using a Windows PowerShell data file Use the `command` property to specify the path to a Windows PowerShell data file. For example, the following Windows PowerShell script defines the `DefaultEditor`: ``` Configuration 'DefaultEditor' { Environment 'texteditor' { Name = 'EDITOR' Value = 'c:\emacs\bin\emacs.exe' } } ``` Use the following recipe to specify the location of that data file: ``` dsc_script 'DefaultEditor' do command 'c:\dsc_scripts\emacs.ps1' end ``` Pass parameters to DSC configurations If a DSC script contains configuration data that takes parameters, those parameters may be passed using the `flags` property. For example, the following Windows PowerShell script takes parameters for the `EditorChoice` and `EditorFlags` settings: ``` $choices = @{'emacs' = 'c:\emacs\bin\emacs';'vi' = 'c:\vim\vim.exe';'powershell' = 'powershell_ise.exe'} Configuration 'DefaultEditor' { [CmdletBinding()] param ( $EditorChoice, $EditorFlags = '' ) Environment 'TextEditor' { Name = 'EDITOR' Value = "$($choices[$EditorChoice]) $EditorFlags" } } ``` Use the following recipe to set those parameters: ``` dsc_script 'DefaultEditor' do flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' }) command 'c:\dsc_scripts\editors.ps1' end ``` Use custom configuration data Configuration data in DSC scripts may be customized from a recipe. For example, scripts are typically customized to set the behavior for Windows PowerShell credential data types. Configuration data may be specified in one of three ways: * By using the `configuration_data` attribute * By using the `configuration_data_script` attribute * By specifying the path to a valid Windows PowerShell data file The following example shows how to specify custom configuration data using the `configuration_data` property: ``` dsc_script 'BackupUser' do configuration_data <<-EOH @{ AllNodes = @( @{ NodeName = "localhost"; PSDscAllowPlainTextPassword = $true }) } EOH code <<-EOH $user = 'backup' $password = ConvertTo-SecureString -String "YourPass$(random)" -AsPlainText -Force $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $password User $user { UserName = $user Password = $cred Description = 'Backup operator' Ensure = "Present" Disabled = $false PasswordNeverExpires = $true PasswordChangeRequired = $false } EOH end ``` The following example shows how to specify custom configuration data using the `configuration_name` property. For example, the following Windows PowerShell script defines the `vi` configuration: ``` Configuration 'emacs' { Environment 'TextEditor' { Name = 'EDITOR' Value = 'c:\emacs\bin\emacs.exe' } } Configuration 'vi' { Environment 'TextEditor' { Name = 'EDITOR' Value = 'c:\vim\bin\vim.exe' } } ``` Use the following recipe to specify that configuration: ``` dsc_script 'EDITOR' do configuration_name 'vi' command 'C:\dsc_scripts\editors.ps1' end ``` Using DSC with other Chef resources The **dsc_script** resource can be used with other resources. The following example shows how to download a file using the **remote_file** resource, and then uncompress it using the DSC `Archive` resource: ``` remote_file "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" do source 'http://gallery.technet.microsoft.com/DSC-Resource-Kit-All-c449312d/file/124481/1/DSC%20Resource%20Kit%20Wave%206%2008282014.zip' end dsc_script 'get-dsc-resource-kit' do code <<-EOH Archive reskit { ensure = 'Present' path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" } EOH end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/dsc_script/execute Resource ================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [execute.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/execute.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **execute** resource to execute a single command. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. Note Use the **script** resource to execute a script using a specific interpreter (Ruby, Python, Perl, csh, or Bash). Syntax ------ --- An **execute** resource block typically executes a single command that is unique to the environment in which a recipe will run. Some **execute** resource commands are run by themselves, but often they are run in combination with other Chef resources. For example, a single command that is run by itself: ``` execute 'apache_configtest' do command '/usr/sbin/apachectl configtest' end ``` The full syntax for all of the properties that are available to the **execute** resource is: ``` execute 'name' do command String, Array # default value: 'name' unless specified creates String cwd String default_env true, false # default value: false domain String elevated true, false # default value: false environment Hash group String, Integer input String live_stream true, false # default value: false login true, false # default value: false password String returns Integer, Array # default value: 0 timeout Integer, String, Float # default value: 3600 user String, Integer action Symbol # defaults to :run if not specified end ``` where: * `execute` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command`, `creates`, `cwd`, `default_env`, `domain`, `elevated`, `environment`, `group`, `input`, `live_stream`, `login`, `password`, `returns`, `timeout`, and `user` are the properties available to this resource. Actions ------- --- The **execute** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Run a command. (default) Properties ---------- --- The **execute** resource has the following properties: `command` **Ruby Type:** String, Array | **Default Value:** `The resource block's name` An optional property to set the command to be executed if it differs from the resource block’s name. Note Use the **execute** resource to run a single command. Use multiple **execute** resource blocks to run multiple commands. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `default_env` **Ruby Type:** true, false | **Default Value:** `false` When true this enables ENV magic to add path_sanity to the PATH and force the locale to English+UTF-8 for parsing output New in Chef Client 14.2 `domain` **Ruby Type:** String Windows only: The domain of the user specified by the user property. If not specified, the username and password specified by the `user` and `password` properties will be used to resolve that user against the domain in which the system running Chef Infra Client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. New in Chef Client 12.21 `elevated` **Ruby Type:** true, false | **Default Value:** `false` Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) from interactively blocking the process. This will cause the process to be run under a batch login instead of an interactive login. The user running chef-client needs the ‘Replace a process level token’ and ‘Adjust Memory Quotas for a process’ permissions. The user that is running the command needs the ‘Log on as a batch job’ permission. Because this requires a login, the user and password properties are required. New in Chef Client 13.3 `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `input` **Ruby Type:** String An optional property to set the input sent to the command as STDIN. New in Chef Infra Client 16.2 `live_stream` **Ruby Type:** true, false | **Default Value:** `false` Send the output of the command run by this execute resource block to the Chef Infra Client event stream. `login` **Ruby Type:** true, false | **Default Value:** `false` Use a login shell to run the commands instead of inheriting the existing execution environment. New in Chef Infra Client 17.0 `password` **Ruby Type:** String Windows only: The password of the user specified by the user property. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. New in Chef Client 12.21 `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. `domain\user` or `<EMAIL>` via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain property. On Windows only, if this property is specified, the password property must be specified. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **execute** resource in recipes: **Run a command upon notification**: ``` execute 'slapadd' do command 'slapadd < /tmp/something.ldif' creates '/var/lib/slapd/uid.bdb' action :nothing end template '/tmp/something.ldif' do source 'something.ldif' notifies :run, 'execute[slapadd]', :immediately end ``` **Run a touch file only once while running a command**: ``` execute 'upgrade script' do command 'php upgrade-application.php && touch /var/application/.upgraded' creates '/var/application/.upgraded' action :run end ``` **Run a command which requires an environment variable**: ``` execute 'slapadd' do command 'slapadd < /tmp/something.ldif' creates '/var/lib/slapd/uid.bdb' action :run environment ({'HOME' => '/home/my_home'}) end ``` **Delete a repository using yum to scrub the cache**: ``` # the following code sample thanks to gaffneyc @ https://gist.github.com/918711 execute 'clean-yum-cache' do command 'yum clean all' action :nothing end file '/etc/yum.repos.d/bad.repo' do action :delete notifies :run, 'execute[clean-yum-cache]', :immediately end ``` **Prevent restart and reconfigure if configuration is broken**: Use the `:nothing` action (common to all resources) to prevent the test from starting automatically, and then use the `subscribes` notification to run a configuration test when a change to the template is detected. ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing subscribes :run, 'template[/etc/nagios3/configures-nagios.conf]', :immediately end ``` **Notify in a specific order**: To notify multiple resources, and then have these resources run in a certain order, do something like the following. ``` execute 'foo' do command '...' notifies :create, 'template[baz]', :immediately notifies :install, 'package[bar]', :immediately notifies :run, 'execute[final]', :immediately end template 'baz' do #... notifies :run, 'execute[restart_baz]', :immediately end package 'bar' execute 'restart_baz' execute 'final' do command '...' end ``` where the sequencing will be in the same order as the resources are listed in the recipe: `execute 'foo'`, `template 'baz'`, `execute [restart_baz]`, `package 'bar'`, and `execute 'final'`. **Execute a command using a template**: The following example shows how to set up IPv4 packet forwarding using the **execute** resource to run a command named `forward_ipv4` that uses a template defined by the **template** resource. ``` execute 'forward_ipv4' do command 'echo > /proc/.../ipv4/ip_forward' action :nothing end template '/etc/file_name.conf' do source 'routing/file_name.conf.erb' notifies :run, 'execute[forward_ipv4]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[forward_ipv4]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. **Add a rule to an IP table**: The following example shows how to add a rule named `test_rule` to an IP table using the **execute** resource to run a command using a template that is defined by the **template** resource: ``` execute 'test_rule' do command "command_to_run --option value --option value --source #{node[:name_of_node][:ipsec][:local][:subnet]} -j test_rule" action :nothing end template '/etc/file_name.local' do source 'routing/file_name.local.erb' notifies :run, 'execute[test_rule]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[test_rule]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. **Stop a service, do stuff, and then restart it**: The following example shows how to use the **execute**, **service**, and **mount** resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following: * Checks to see if the Amazon EC2 node has MySQL * If the node has MySQL, stops MySQL * Installs MySQL * Mounts the node * Restarts MySQL ``` # the following code sample comes from the ``server_ec2`` # recipe in the following cookbook: # https://github.com/chef-cookbooks/mysql if (node.attribute?('ec2') && !FileTest.directory?(node['mysql']['ec2_path'])) service 'mysql' do action :stop end execute 'install-mysql' do command "mv #{node['mysql']['data_dir']}#{node['mysql']['ec2_path']}" not_if { ::File.directory?(node['mysql']['ec2_path']) } end [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir| directory dir do owner 'mysql' group 'mysql' end end mount node['mysql']['data_dir'] do device node['mysql']['ec2_path'] fstype 'none' options 'bind,rw' action [:mount, :enable] end service 'mysql' do action :start end end ``` where * the two **service** resources are used to stop, and then restart the MySQL service * the **execute** resource is used to install MySQL * the **mount** resource is used to mount the node and enable MySQL **Use the platform_family? method**: The following is an example of using the `platform_family?` method in the Recipe DSL to create a variable that can be used with other resources in the same recipe. In this example, `platform_family?` is being used to ensure that a specific binary is used for a specific platform before using the **remote_file** resource to download a file from a remote location, and then using the **execute** resource to install that file by running a command. ``` if platform_family?('rhel') pip_binary = '/usr/bin/pip' else pip_binary = '/usr/local/bin/pip' end remote_file "#{Chef::Config[:file_cache_path]}/distribute_setup.py" do source 'http://python-distribute.org/distribute_setup.py' mode '0755' not_if { ::File.exist?(pip_binary) } end execute 'install-pip' do cwd Chef::Config[:file_cache_path] command <<~EOF # command for installing Python goes here EOF not_if { ::File.exist?(pip_binary) } end ``` where a command for installing Python might look something like: ``` #{node['python']['binary']} distribute_setup.py #{::File.dirname(pip_binary)}/easy_install pip ``` **Control a service using the execute resource**: Warning This is an example of something that should NOT be done. Use the **service** resource to control a service, not the **execute** resource. Do something like this: ``` service 'tomcat' do action :start end ``` and NOT something like this: ``` execute 'start-tomcat' do command '/etc/init.d/tomcat start' action :run end ``` There is no reason to use the **execute** resource to control a service because the **service** resource exposes the `start_command` property directly, which gives a recipe full control over the command issued in a much cleaner, more direct manner. **Use the search Infra Language helper to find users**: The following example shows how to use the `search` method in the Chef Infra Language to search for users: ``` # the following code sample comes from the openvpn cookbook: search("users", "*:*") do |u| execute "generate-openvpn-#{u['id']}" do command "./pkitool #{u['id']}" cwd '/etc/openvpn/easy-rsa' end %w{ conf ovpn }.each do |ext| template "#{node['openvpn']['key_dir']}/#{u['id']}.#{ext}" do source 'client.conf.erb' variables :username => u['id'] end end end ``` where * the search data will be used to create **execute** resources * the **template** resource tells Chef Infra Client which template to use **Enable remote login for macOS**: ``` execute 'enable ssh' do command '/usr/sbin/systemsetup -setremotelogin on' not_if '/usr/sbin/systemsetup -getremotelogin | /usr/bin/grep On' action :run end ``` **Execute code immediately, based on the template resource**: By default, notifications are `:delayed`, that is they are queued up as they are triggered, and then executed at the very end of a Chef Infra Client run. To run an action immediately, use `:immediately`: ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :immediately end ``` and then Chef Infra Client would immediately run the following: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing end ``` **Sourcing a file**: The **execute** resource cannot be used to source a file (e.g. `command 'source filename'`). The following example will fail because `source` is not an executable: ``` execute 'foo' do command 'source /tmp/foo.sh' end ``` Instead, use the **script** resource or one of the **script**-based resources (**bash**, **csh**, **perl**, **python**, or **ruby**). For example: ``` bash 'foo' do code 'source /tmp/foo.sh' end ``` **Run a Knife command**: ``` execute 'create_user' do command <<~EOM knife user create #{user} --admin --password password --disable-editing --file /home/vagrant/.chef/user.pem --config /tmp/knife-admin.rb EOM end ``` **Run install command into virtual environment**: The following example shows how to install a lightweight JavaScript framework into Vagrant: ``` execute "install q and zombiejs" do cwd "/home/vagrant" user "vagrant" environment ({'HOME' => '/home/vagrant', 'USER' => 'vagrant'}) command "npm install -g q zombie should mocha coffee-script" action :run end ``` **Run a command as a named user**: The following example shows how to run `bundle install` from a Chef Infra Client run as a specific user. This will put the gem into the path of the user (`vagrant`) instead of the root user (under which the Chef Infra Client runs): ``` execute '/opt/chefdk/embedded/bin/bundle install' do cwd node['chef_workstation']['bundler_path'] user node['chef_workstation']['user'] environment ({ 'HOME' => "/home/#{node['chef_workstation']['user']}", 'USER' => node['chef_workstation']['user'] }) not_if 'bundle check' end ``` **Run a command as an alternate user**: *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] domain "domain-name" user "user" password "password" end # Passing username = 'domain-name\username'. No domain is passed execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] user "domain-name\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end ``` **Run a command with an external input file**: execute ‘md5sum’ do input File.read(**FILE**) end © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/execute/git Resource ============ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [git.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/git.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **git** resource to manage source control resources that exist in a git repository. git version 1.6.5 (or higher) is required to use all of the functionality in the git resource. Syntax ------ --- A **git** resource block manages source control resources that exist in a git repository: ``` git "#{Chef::Config[:file_cache_path]}/app_name" do repository node[:app_name][:git_repository] revision node[:app_name][:git_revision] action :sync end ``` The full syntax for all of the properties that are available to the **git** resource is: ``` git 'name' do additional_remotes Hash # default value: {} checkout_branch String depth Integer destination String # default value: 'name' unless specified enable_checkout true, false # default value: true enable_submodules true, false # default value: false environment Hash group String, Integer remote String # default value: "origin" repository String revision String # default value: "HEAD" ssh_wrapper String timeout Integer user String, Integer action Symbol # defaults to :sync if not specified end ``` where: * `git` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `additional_remotes`, `checkout_branch`, `depth`, `destination`, `enable_checkout`, `enable_submodules`, `environment`, `group`, `remote`, `repository`, `revision`, `ssh_wrapper`, `timeout`, and `user` are the properties available to this resource. Actions ------- --- The **git** resource has the following actions: `:checkout` Clone or check out the source. When a checkout is available, this provider does nothing. `:export` Export the source, excluding or removing any version control artifacts. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:sync` Default. Update the source to the specified version, or get a new clone or checkout. This action causes a hard reset of the index and working tree, discarding any uncommitted changes. Properties ---------- --- The **git** resource has the following properties: `additional_remotes` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of additional remotes that are added to the git repository configuration. `checkout_branch` **Ruby Type:** String Do a one-time checkout from git **or** use when a branch in the upstream repository is named `deploy`. To prevent the **git** resource from attempting to check out master from master, set `enable_checkout` to `false` when using the `checkout_branch` property. See `revision`. `depth` **Ruby Type:** Integer The number of past revisions to be included in the git shallow clone. Unless specified the default behavior will do a full clone. `destination` **Ruby Type:** String | **Default Value:** `The resource block's name` The location path to which the source is to be cloned, checked out, or exported. Default value: the name of the resource block. `enable_checkout` **Ruby Type:** true, false | **Default Value:** `true` Check out a repo from master. Set to `false` when using the `checkout_branch` attribute to prevent the git resource from attempting to check out `master` from `master`. `enable_submodules` **Ruby Type:** true, false | **Default Value:** `false` Perform a sub-module initialization and update. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) Note The **git** provider automatically sets the `ENV['HOME']` and `ENV['GIT_SSH']` environment variables. To override this behavior and provide different values, add `ENV['HOME']` and/or `ENV['GIT_SSH']` to the `environment` Hash. `group` **Ruby Type:** String, Integer The system group that will own the checked-out code. `remote` **Ruby Type:** String | **Default Value:** `origin` The remote repository to use when synchronizing an existing clone. `repository` **Ruby Type:** String The URI of the code repository. `revision` **Ruby Type:** String | **Default Value:** `HEAD` A branch, tag, or commit to be synchronized with git. This can be symbolic, like `HEAD` or it can be a source control management-specific revision identifier. See `checkout_branch`. The value of the `revision` attribute may change over time. From one branch to another, to a tag, to a specific SHA for a commit, and then back to a branch. The `revision` attribute may even be changed in a way where history gets rewritten. Instead of tracking a specific branch or doing a headless checkout, Chef Infra Client maintains its own branch (via the **git** resource) that does not exist in the upstream repository. Chef Infra Client is then free to forcibly check out this branch to any commit without destroying the local history of an existing branch. For example, to explicitly track an upstream repository’s master branch: ``` revision 'master' ``` Use the `git rev-parse` and `git ls-remote` commands to verify that Chef Infra Client is synchronizing commits correctly. (Chef Infra Client always runs `git ls-remote` on the upstream repository to verify the commit is made to the correct repository.) `ssh_wrapper` **Ruby Type:** String The path to the wrapper script used when running SSH with git. The `GIT_SSH` environment variable is set to this. `timeout` **Ruby Type:** Integer The amount of time (in seconds) to wait for a command to execute before timing out. When this property is specified using the **deploy** resource, the value of the `timeout` property is passed from the **deploy** resource to the **git** resource. `user` **Ruby Type:** String, Integer | **Default Value:** ``HOME` environment variable of the user running chef-client` The system user that will own the checked-out code. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **git** resource in recipes: **Use the git mirror** ``` git '/opt/my_sources/couch' do repository 'git://git.apache.org/couchdb.git' revision 'master' action :sync end ``` **Use different branches** To use different branches, depending on the environment of the node: ``` branch_name = if node.chef_environment == 'QA' 'staging' else 'master' end git '/home/user/deployment' do repository '<EMAIL>:git_site/deployment.git' revision branch_name action :sync user 'user' group 'test' end ``` Where the `branch_name` variable is set to staging or master, depending on the environment of the node. Once this is determined, the `branch_name` variable is used to set the revision for the repository. If the git status command is used after running the example above, it will return the branch name as `deploy`, as this is the default value. Run Chef Infra Client in debug mode to verify that the correct branches are being checked out: ``` sudo chef-client -l debug ``` **Install an application from git using bash** The following example shows how Bash can be used to install a plug-in for rbenv named ruby-build, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which ruby-build is located, and then runs a command. ``` git "/Users/tsmith/.chef/cache/ruby-build" do repository 'git://github.com/rbenv/ruby-build.git' revision 'master' action :sync end bash 'install_ruby_build' do cwd "/Users/tsmith/.chef/cache/ruby-build" user 'rbenv' group 'rbenv' code <<-EOH ./install.sh EOH environment 'PREFIX' => '/usr/local' end ``` **Notify a resource post-checkout** ``` git "/Users/tsmith/.chef/cache/my_app" do repository node['my_app']['git_repository'] revision node['my_app']['git_revision'] action :sync notifies :run, 'bash[compile_my_app]', :immediately end ``` **Pass in environment variables** ``` git '/opt/my_sources/couch' do repository 'git://git.apache.org/couchdb.git' revision 'master' environment 'VAR' => 'whatever' action :sync end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/git/habitat_config Resource ======================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [habitat_config.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/habitat_config.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **habitat_config** resource to apply a configuration to a Chef Habitat service. **New in Chef Infra Client 17.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **habitat_config** resource is: ``` habitat_config 'name' do config Mash (Hash-like) gateway_auth_token String remote_sup String # default value: "127.0.0.1:9632" remote_sup_http String # default value: "127.0.0.1:9631" service_group String # default value: 'name' unless specified user String action Symbol # defaults to :apply if not specified end ``` where: * `habitat_config` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `config`, `gateway_auth_token`, `remote_sup`, `remote_sup_http`, `service_group`, and `user` are the properties available to this resource. Actions ------- --- The **habitat_config** resource has the following actions: `:apply` applies the given configuration (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **habitat_config** resource has the following properties: `config` **Ruby Type:** Mash (Hash-like) | `REQUIRED` The configuration to apply as a ruby hash, for example, `{ worker_count: 2, http: { keepalive_timeout: 120 } }`. `gateway_auth_token` **Ruby Type:** String Auth token for accessing the remote supervisor’s http port. `remote_sup` **Ruby Type:** String | **Default Value:** `127.0.0.1:9632` Address to a remote supervisor’s control gateway. `remote_sup_http` **Ruby Type:** String | **Default Value:** `127.0.0.1:9631` Address for remote supervisor http port. Used to pull existing. `service_group` **Ruby Type:** String | **Default Value:** `The resource block's name` The service group to apply the configuration to. For example, `nginx.default` `user` **Ruby Type:** String Name of user key to use for encryption. Passes `--user` to `hab config apply`. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **habitat_config** resource in recipes: **Configure your nginx defaults** ``` habitat_config 'nginx.default' do config({ worker_count: 2, http: { keepalive_timeout: 120 } }) end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/habitat_config/group Resource ============== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [group.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/group.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **group** resource to manage a local group. Syntax ------ --- The full syntax for all of the properties that are available to the **group** resource is: ``` group 'name' do append true, false # default value: false comment String excluded_members String, Array # default value: [] gid String, Integer group_name String # default value: 'name' unless specified members String, Array # default value: [] non_unique true, false # default value: false system true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `group` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `append`, `comment`, `excluded_members`, `gid`, `group_name`, `members`, `non_unique`, and `system` are the properties available to this resource. Actions ------- --- The **group** resource has the following actions: `:create` Default. Create a group. If a group already exists (but does not match), update that group to match. `:manage` Manage an existing group. This action does nothing if the group does not exist. `:modify` Modify an existing group. This action raises an exception if the group does not exist. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a group. Properties ---------- --- The **group** resource has the following properties: `append` **Ruby Type:** true, false | **Default Value:** `false` How members should be appended and/or removed from a group. When true, `members` are appended and `excluded_members` are removed. When `false`, group members are reset to the value of the `members` property. `comment` **Ruby Type:** String Specifies a comment to associate with the local group. New in Chef Client 14.9 `excluded_members` **Ruby Type:** String, Array | **Default Value:** `[]` Remove users from a group. May only be used when `append` is set to `true`. `gid` **Ruby Type:** String, Integer The identifier for the group. `group_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the group. Default value: the `name` of the resource block. See “Syntax” section above for more information. `members` **Ruby Type:** String, Array | **Default Value:** `[]` Which users should be set or appended to a group. When more than one group member is identified, the list of members should be an array: `members ['user1', 'user2']`. `non_unique` **Ruby Type:** true, false | **Default Value:** `false` Allow gid duplication. May only be used with the `Groupadd` user resource provider. `system` **Ruby Type:** true, false | **Default Value:** `false` Set to `true` if the group belongs to a system group. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **group** resource in recipes: Append users to groups\n\n `ruby\n group 'www-data' do\n \ \ action :modify\n members 'maintenance'\n append true\n end\n` \n\n \ \ Add a user to group on the Windows platform\n\n `ruby\n group 'Administrators'\ \ do\n members ['domain\\foo']\n append true\n action :modify\n end\n\ \` \n" © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/group/habitat_package Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [habitat_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/habitat_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **habitat_package** to install or remove Chef Habitat packages from Habitat Builder. **New in Chef Infra Client 17.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **habitat_package** resource is: ``` habitat_package 'name' do auth_token String binlink true, false, force # default value: false bldr_url String # default value: "https://bldr.habitat.sh" channel String # default value: "stable" exclude String keep_latest String no_deps true, false # default value: false options String package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `habitat_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `auth_token`, `binlink`, `bldr_url`, `channel`, `exclude`, `keep_latest`, `no_deps`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **habitat_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:lock` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` `:remove` Remove a package. `:unlock` `:upgrade` Install a package and ensure that a package is the latest version. Properties ---------- --- The **habitat_package** resource has the following properties: `auth_token` **Ruby Type:** String Auth token for installing a package from a private organization on Habitat builder. `binlink` **Ruby Type:** true, false, force | **Default Value:** `false` If habitat should attempt to binlink the package. Acceptable values: `true`, `false`, `:force`. Will fail on binlinking if set to `true` and binary or binlink exists. `bldr_url` **Ruby Type:** String | **Default Value:** `https://bldr.habitat.sh` The habitat builder url where packages will be downloaded from. **Defaults to public Habitat Builder** `channel` **Ruby Type:** String | **Default Value:** `stable` The release channel to install your package from. `exclude` **Ruby Type:** String Identifier of one or more packages that should not be uninstalled. (ex: core/redis, core/busybox-static/1.42.2/21120102031201) `keep_latest` **Ruby Type:** String Ability to uninstall while retaining a specified version **This feature only works in Habitat 1.5.86+.** `no_deps` **Ruby Type:** true, false | **Default Value:** `false` Remove package but retain dependencies. `options` **Ruby Type:** String Pass any additional parameters to the habitat package command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **habitat_package** resource in recipes: **Install core/redis** ``` habitat_package 'core/redis' ``` **Install specific version of a package from the unstable channel** ``` habitat_package 'core/redis' do version '3.2.3' channel 'unstable' end ``` **Install a package with specific version and revision** ``` habitat_package 'core/redis' do version '3.2.3/20160920131015' end ``` **Install a package and force linking it’s binary files to the system path** ``` habitat_package 'core/nginx' do binlink :force end ``` **Install a package and link it’s binary files to the system path** ``` habitat_package 'core/nginx' do options '--binlink' end ``` **Remove package and all of it’s versions** ``` habitat_package 'core/nginx' action :remove end ``` **Remove specified version of a package** ``` habitat_package 'core/nginx/3.2.3' action :remove end ``` **Remove package but retain some versions Note: Only available as of Habitat 1.5.86** ``` habitat_package 'core/nginx' keep_latest '2' action :remove end ``` ``` **Remove package but keep dependencies** habitat_package 'core/nginx' no_deps false action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/habitat_package/habitat_install Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [habitat_install.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/habitat_install.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **habitat_install** resource to install Chef Habitat. **New in Chef Infra Client 17.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **habitat_install** resource is: ``` habitat_install 'name' do bldr_url String create_user true, false # default value: true hab_version String install_url String license String tmp_dir String action Symbol # defaults to :install if not specified end ``` where: * `habitat_install` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bldr_url`, `create_user`, `hab_version`, `install_url`, `license`, and `tmp_dir` are the properties available to this resource. Actions ------- --- The **habitat_install** resource has the following actions: `:install` Installs Habitat. Does nothing if the `hab` binary is found in the default location for the system (`/bin/hab` on Linux, `/usr/local/bin/hab` on macOS, `C:/habitat/hab.exe` on Windows) (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **habitat_install** resource has the following properties: `bldr_url` **Ruby Type:** String Optional URL to an alternate Habitat Builder. `create_user` **Ruby Type:** true, false | **Default Value:** `true` Creates the `hab` system user. `hab_version` **Ruby Type:** String Specify the version of `Habitat` you would like to install. `install_url` **Ruby Type:** String | **Default Value:** `https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh` URL to the install script, default is from the [habitat repo](https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh) . `license` **Ruby Type:** String **Allowed Values:** `"accept"` Specifies acceptance of habitat license when set to `accept`. `tmp_dir` **Ruby Type:** String Sets TMPDIR environment variable for location to place temp files. Note This is required if `/tmp` and `/var/tmp` are mounted `noexec`. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **habitat_install** resource in recipes: **Installation Without a Resource Name** ``` habitat_install ``` **Installation specifying a habitat builder URL** ``` habitat_install 'install habitat' do bldr_url 'http://localhost' end ``` **Installation specifying version and habitat builder URL** ``` habitat_install 'install habitat' do bldr_url 'http://localhost' hab_version '1.5.50' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/habitat_install/habitat_service Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [habitat_service.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/habitat_service.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **habitat_service** resource to manage Chef Habitat services. This requires that `core/hab-sup` be running as a service. See the `habitat_sup` resource documentation for more information. Note Applications may run as a specific user. Often with Habitat, the default is `hab`, or `root`. If the application requires another user, then it should be created with Chef’s `user` resource. **New in Chef Infra Client 17.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **habitat_service** resource is: ``` habitat_service 'name' do bind String, Array # default value: [] binding_mode Symbol, String # default value: :strict bldr_url String # default value: "https://bldr.habitat.sh/" channel Symbol, String # default value: :stable gateway_auth_token String health_check_interval Integer # default value: 30 remote_sup String # default value: "127.0.0.1:9632" remote_sup_http String # default value: "127.0.0.1:9631" service_group String # default value: "default" service_name String # default value: 'name' unless specified shutdown_timeout Integer # default value: 8 strategy Symbol, String # default value: :none topology Symbol, String # default value: :standalone update_condition Symbol, String # default value: :latest action Symbol # defaults to :load if not specified end ``` where: * `habitat_service` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bind`, `binding_mode`, `bldr_url`, `channel`, `gateway_auth_token`, `health_check_interval`, `remote_sup`, `remote_sup_http`, `service_group`, `service_name`, `shutdown_timeout`, `strategy`, `topology`, and `update_condition` are the properties available to this resource. Actions ------- --- The **habitat_service** resource has the following actions: `:load` (default action) runs `hab service load` to load and start the specified application service (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reload` runs the `:unload` and then `:load` actions `:restart` runs the `:stop` and then `:start` actions `:start` runs `hab service start` to start the specified application service `:stop` runs `hab service stop` to stop the specified application service `:unload` runs `hab service unload` to unload and stop the specified application service Properties ---------- --- The **habitat_service** resource has the following properties: `bind` **Ruby Type:** String, Array | **Default Value:** `[]` Passes `--bind` with the specified services to bind to the hab command. If an array of multiple service binds are specified then a `--bind` flag is added for each. `binding_mode` **Ruby Type:** Symbol, String | **Default Value:** `:strict` **Allowed Values:** `:strict, "strict", :relaxed, "relaxed"` Passes `--binding-mode` with the specified binding mode. Defaults to `:strict`. Options are `:strict` or `:relaxed` `bldr_url` **Ruby Type:** String | **Default Value:** `https://bldr.habitat.sh/` Passes `--url` with the specified Habitat Builder URL to the hab command. Depending on the type of Habitat Builder you are connecting to, this URL will look different, here are the **3** current types: - Public Habitat Builder (default) - `https://bldr.habitat.sh` - On-Prem Habitat Builder installed using the [Source Install Method](https://github.com/habitat-sh/on-prem-builder) - `https://your.bldr.url` - On-Prem Habitat Builder installed using the [Automate Installer](https://automate.chef.io/docs/on-prem-builder/) - `https://your.bldr.url/bldr/v1` `channel` **Ruby Type:** Symbol, String | **Default Value:** `:stable` Passes `--channel` with the specified channel to the hab command `gateway_auth_token` **Ruby Type:** String Auth token for accessing the remote supervisor’s http port. `health_check_interval` **Ruby Type:** Integer | **Default Value:** `30` The interval (seconds) on which to run health checks. `remote_sup` **Ruby Type:** String | **Default Value:** `127.0.0.1:9632` Address to a remote Supervisor’s Control Gateway `remote_sup_http` **Ruby Type:** String | **Default Value:** `127.0.0.1:9631` IP address and port used to communicate with the remote supervisor. If this value is invalid, the resource will update the supervisor configuration each time Chef Infra Server runs. `service_group` **Ruby Type:** String | **Default Value:** `default` Passes `--group` with the specified service group to the hab command `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the service, must be in the form of `origin/name` `shutdown_timeout` **Ruby Type:** Integer | **Default Value:** `8` The timeout in seconds allowed during shutdown. `strategy` **Ruby Type:** Symbol, String | **Default Value:** `:none` **Allowed Values:** `:none, "none", :"at-once", "at-once", :rolling, "rolling"` Passes `--strategy` with the specified update strategy to the hab command. Defaults to `:none`. Other options are `:'at-once'` and `:rolling` `topology` **Ruby Type:** Symbol, String | **Default Value:** `:standalone` **Allowed Values:** `:standalone, "standalone", :leader, "leader"` Passes `--topology` with the specified service topology to the hab command `update_condition` **Ruby Type:** Symbol, String | **Default Value:** `:latest` **Allowed Values:** `:latest, "latest", :"track-channel", "track-channel"` Passes `--update-condition` dictating when this service should updated. Defaults to `latest`. Options are `latest` or `track-channel` **_ Note This requires a minimum habitat version of 1.5.71_** - `latest`: Runs the latest package that can be found in the configured channel and local packages. - `track-channel`: Always run the package at the head of a given channel. This enables service rollback, where demoting a package from a channel will cause the package to rollback to an older version of the package. A ramification of enabling this condition is that packages that are newer than the package at the head of the channel are also uninstalled during a service rollback. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **habitat_service** resource in recipes: **Install and load nginx** ``` habitat_package 'core/nginx' habitat_service 'core/nginx' habitat_service 'core/nginx unload' do service_name 'core/nginx' action :unload end ``` **Pass the `strategy` and `topology` options to hab service commands** ``` habitat_service 'core/redis' do strategy 'rolling' topology 'standalone' end ``` **Using update_condition** ``` habitat_service 'core/redis' do strategy 'rolling' update_condition 'track-channel' topology 'standalone' end ``` **If the service has it’s own user specified that is not the `hab` user, don’t create the `hab` user on install, and instead create the application user with Chef’s `user` resource** ``` habitat_install 'install habitat' do create_user false end user 'acme-apps' do system true end habitat_service 'acme/apps' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/habitat_service/habitat_sup Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [habitat_sup.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/habitat_sup.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **habitat_sup** resource to runs a Chef Habitat supervisor for one or more Chef Habitat services. The resource is commonly used in conjunction with `habitat_service` which will manage the services loaded and started within the supervisor. **New in Chef Infra Client 17.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **habitat_sup** resource is: ``` habitat_sup 'name' do auth_token String auto_update true, false # default value: false bldr_url String event_stream_application String event_stream_cert String event_stream_environment String event_stream_site String event_stream_token String event_stream_url String gateway_auth_token String hab_channel String health_check_interval String, Integer keep_latest String launcher_version String license String limit_no_files String listen_ctl String listen_gossip String listen_http String org String # default value: "default" peer String, Array permanent_peer true, false # default value: false ring String service_version String sup_version String toml_config true, false # default value: false update_condition String action Symbol # defaults to :run if not specified end ``` where: * `habitat_sup` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `auth_token`, `auto_update`, `bldr_url`, `event_stream_application`, `event_stream_cert`, `event_stream_environment`, `event_stream_site`, `event_stream_token`, `event_stream_url`, `gateway_auth_token`, `hab_channel`, `health_check_interval`, `keep_latest`, `launcher_version`, `license`, `limit_no_files`, `listen_ctl`, `listen_gossip`, `listen_http`, `org`, `peer`, `permanent_peer`, `ring`, `service_version`, `sup_version`, `toml_config`, and `update_condition` are the properties available to this resource. Actions ------- --- The **habitat_sup** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` The `run` action handles installing Habitat using the `habitat_install` resource, ensures that the appropriate versions of the `core/hab-sup` and `core/hab-launcher` packages are installed using `habitat_package`, and then drops off the appropriate init system definitions and manages the service. (default) `:stop` Properties ---------- --- The **habitat_sup** resource has the following properties: `auth_token` **Ruby Type:** String Auth token for accessing a private organization on bldr. This value is templated into the appropriate service file. `auto_update` **Ruby Type:** true, false | **Default Value:** `false` Passes `--auto-update`. This will set the Habitat supervisor to automatically update itself any time a stable version has been released. `bldr_url` **Ruby Type:** String The Habitat Builder URL for the `habitat_package` resource, if needed. `event_stream_application` **Ruby Type:** String The name of your application that will be displayed in the Chef Automate Applications Dashboard. `event_stream_cert` **Ruby Type:** String With `Intermediary Certificates` or, Automate 2 being set to use TLS with a valid cert, you will need to provide `Habitat` with your certificate for communication with Automate to work. [Follow these steps!](https://automate.chef.io/docs/applications-setup/#share-the-tls-certificate-with-chef-habitat). `event_stream_environment` **Ruby Type:** String The application environment for the supervisor, this is for grouping in the Applications Dashboard. `event_stream_site` **Ruby Type:** String Application Dashboard label for the ‘site’ of the application - can be filtered in the dashboard. `event_stream_token` **Ruby Type:** String Chef Automate token for sending application event stream data. `event_stream_url` **Ruby Type:** String `AUTOMATE_HOSTNAME:4222` - the Chef Automate URL with port 4222 specified Note The port can be changed if needed. `gateway_auth_token` **Ruby Type:** String Auth token for accessing the supervisor’s HTTP gateway. This value is templated into the appropriate service file. `hab_channel` **Ruby Type:** String The channel to install Habitat from. Defaults to stable `health_check_interval` **Ruby Type:** String, Integer The interval (seconds) on which to run health checks. `keep_latest` **Ruby Type:** String Automatically cleans up old packages. If this flag is enabled, service startup will initiate an uninstall of all previous versions of the associated package. This also applies when a service is restarted due to an update. If a number is passed to this argument, that number of latest versions will be kept. The same logic applies to the Supervisor package `env:HAB_KEEP_LATEST_PACKAGES=1` Note This requires Habitat version `1.5.86+` `launcher_version` **Ruby Type:** String Allows you to choose which version of launcher to install. `license` **Ruby Type:** String **Allowed Values:** `"accept"` Specifies acceptance of habitat license when set to `accept`. `limit_no_files` **Ruby Type:** String allows you to set LimitNOFILE in the systemd service when used Note Linux Only. `listen_ctl` **Ruby Type:** String Only valid for `:run` action, passes `--listen-ctl` with the specified address and port, e.g., `0.0.0.0:9632`, to the hab command. `listen_gossip` **Ruby Type:** String Only valid for `:run` action, passes `--listen-gossip` with the specified address and port, e.g., `0.0.0.0:9638`, to the hab command. `listen_http` **Ruby Type:** String Only valid for `:run` action, passes `--listen-http` with the specified address and port, e.g., `0.0.0.0:9631`, to the hab command. `org` **Ruby Type:** String | **Default Value:** `default` Only valid for `:run` action, passes `--org` with the specified org name to the hab command. `peer` **Ruby Type:** String, Array Only valid for `:run` action, passes `--peer` with the specified initial peer to the hab command. `permanent_peer` **Ruby Type:** true, false | **Default Value:** `false` Only valid for `:run` action, passes `--permanent-peer` to the hab command. `ring` **Ruby Type:** String Only valid for `:run` action, passes `--ring` with the specified ring key name to the hab command. `service_version` **Ruby Type:** String Allows you to choose which version of the ***Windows Service*** to install. `sup_version` **Ruby Type:** String Allows you to choose which version of supervisor you would like to install. Note If a version is provided, it will also install that version of habitat if not previously installed. `toml_config` **Ruby Type:** true, false | **Default Value:** `false` Supports using the Supervisor toml configuration instead of passing exec parameters to the service, [reference](https://www.habitat.sh/docs/reference/#supervisor-config). `update_condition` **Ruby Type:** String Passes `--update-condition` dictating when this service should updated. Defaults to `latest`. Options are `latest` or `track-channel` **_ Note This requires a minimum habitat version of 1.5.71_** - `latest`: Runs the latest package that can be found in the configured channel and local packages. - `track-channel`: Always run what is at the head of a given channel. This enables service rollback where demoting a package from a channel will cause the package to rollback to an older version of the package. A ramification of enabling this condition is packages newer than the package at the head of the channel will be automatically uninstalled during a service rollback. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **habitat_sup** resource in recipes: **Set up with just the defaults** ``` habitat_sup 'default' ``` **Update listen ports and use Supervisor toml config** ``` habitat_sup 'test-options' do listen_http '0.0.0.0:9999' listen_gossip '0.0.0.0:9998' toml_config true end ``` **Use with an on-prem Habitat Builder. Note: Access to public builder may not be available due to your company policies** ``` habitat_sup 'default' do bldr_url 'https://bldr.example.com' end ``` **Using update_condition** ``` habitat_sup 'default' do bldr_url 'https://bldr.example.com' habitat_channel 'dev' update_condition 'track-channel' end ``` **Provide event_stream_* information** ``` habitat_sup 'default' do license 'accept' event_stream_application 'myapp' event_stream_environment 'production' event_stream_site 'MySite' event_stream_url 'automate.example.com:4222' event_stream_token 'myawesomea2clitoken=' event_stream_cert '/hab/cache/ssl/mycert.crt' end ``` **Provide specific versions** ``` habitat_sup 'default' do bldr_url 'https://bldr.example.com' sup_version '1.5.50' launcher_version '13458' service_version '0.6.0' # WINDOWS ONLY end ``` **Set latest version of packages to retain** habitat_sup ‘default’ do bldr_url ‘<https://bldr.example.com>’ sup_version ‘1.5.86’ launcher_version ‘13458’ service_version ‘0.6.0’ # WINDOWS ONLY keep_latest ‘2’ end © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/habitat_sup/habitat_user_toml Resource ============================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [habitat_user_toml.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/habitat_user_toml.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **habitat_user_toml** to template a `user.toml` for Chef Habitat services. Configurations set in the `user.toml` override the `default.toml` for a given package, which makes it an alternative to applying service group level configuration. **New in Chef Infra Client 17.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **habitat_user_toml** resource is: ``` habitat_user_toml 'name' do config Mash (Hash-like) service_name String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `habitat_user_toml` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `config` and `service_name` are the properties available to this resource. Actions ------- --- The **habitat_user_toml** resource has the following actions: `:create` (default action) Create the user.toml from the specified config. (default) `:delete` Delete the user.toml `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **habitat_user_toml** resource has the following properties: `config` **Ruby Type:** Mash (Hash-like) | `REQUIRED` Only valid for `:create` action. The configuration to apply as a ruby hash, for example, `{ worker_count: 2, http: { keepalive_timeout: 120 } }`. `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The service group to apply the configuration to, for example, `nginx.default`. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **habitat_user_toml** resource in recipes: **Configure user specific settings to nginx** ``` habitat_user_toml 'nginx' do config({ worker_count: 2, http: { keepalive_timeout: 120 } }) end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/habitat_user_toml/homebrew_cask Resource ======================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [homebrew_cask.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/homebrew_cask.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **homebrew_cask** resource to install binaries distributed via the Homebrew package manager. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **homebrew_cask** resource is: ``` homebrew_cask 'name' do cask_name String # default value: 'name' unless specified homebrew_path String # default value: "/usr/local/bin/brew" install_cask true, false # default value: true options String owner String, Integer # default value: "Calculated default username" action Symbol # defaults to :install if not specified end ``` where: * `homebrew_cask` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `cask_name`, `homebrew_path`, `install_cask`, `options`, and `owner` are the properties available to this resource. Actions ------- --- The **homebrew_cask** resource has the following actions: `:install` Install an application that is packaged as a Homebrew cask. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an application that is packaged as a Homebrew cask. Properties ---------- --- The **homebrew_cask** resource has the following properties: `cask_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the cask name if it differs from the resource block’s name. `homebrew_path` **Ruby Type:** String | **Default Value:** `/usr/local/bin/brew` The path to the homebrew binary. `install_cask` **Ruby Type:** true, false | **Default Value:** `true` Automatically install the Homebrew cask tap, if necessary. `options` **Ruby Type:** String Options to pass to the brew command during installation. `owner` **Ruby Type:** String, Integer | **Default Value:** `Calculated default username` The owner of the Homebrew installation. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/homebrew_cask/http_request Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [http_request.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/http_request.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **http_request** resource to send an HTTP request (`GET`, `PUT`, `POST`, `DELETE`, `HEAD`, or `OPTIONS`) with an arbitrary message. This resource is often useful when custom callbacks are necessary. Syntax ------ --- A **http_request** resource block sends HTTP requests with an arbitrary message. For example, send a `DELETE` request to `'http://www.chef.io/some_page?message=please_delete_me'`. ``` http_request 'please_delete_me' do url 'http://www.chef.io/some_page' action :delete end ``` The full syntax for all of the properties that are available to the **http_request** resource is: ``` http_request 'name' do headers Hash message Object # defaults to 'name' if not specified url String action Symbol # defaults to :get if not specified end ``` where: * `http_request` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `headers`, `message`, and `url` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **http_request** resource has the following actions: `:delete` Send a `DELETE` request. `:get` Default. Send a `GET` request. Changed in Chef Client 12.0 to deprecate the hard-coded query string from earlier versions. Cookbooks that rely on this string need to be updated to manually add it to the URL as it is passed to the resource. `:head` Send a `HEAD` request. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:options` Send an `OPTIONS` request. `:post` Send a `POST` request. `:put` Send a `PUT` request. Properties ---------- --- The **http_request** resource has the following properties: `headers` **Ruby Type:** Hash A Hash of custom headers. `message` **Ruby Type:** Object The message that is sent by the HTTP request. Default value: the `name` of the resource block. See “Syntax” section above for more information. `url` **Ruby Type:** String The URL to which an HTTP request is sent. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **http_request** resource in recipes: Send a GET request ``` http_request 'some_message' do url 'http://example.com/check_in' end ``` The message is sent as `http://example.com/check_in?message=some_message`. Send a POST request To send a `POST` request as JSON data, convert the message to JSON and include the correct content-type header. For example: ``` http_request 'posting data' do action :post url 'http://example.com/check_in' message ({:some => 'data'}.to_json) headers({'AUTHORIZATION' => "Basic #{ Base64.encode64('username:password')}", 'Content-Type' => 'application/data' }) end ``` Transfer a file only when the remote source changes ``` remote_file '/tmp/couch.png' do source 'http://couchdb.apache.org/img/sketch.png' action :nothing end http_request 'HEAD http://couchdb.apache.org/img/sketch.png' do message '' url 'http://couchdb.apache.org/img/sketch.png' action :head if ::File.exist?('/tmp/couch.png') headers 'If-Modified-Since' => File.mtime('/tmp/couch.png').httpdate end notifies :create, 'remote_file[/tmp/couch.png]', :immediately end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/http_request/homebrew_tap Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [homebrew_tap.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/homebrew_tap.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **homebrew_tap** resource to add additional formula repositories to the Homebrew package manager. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **homebrew_tap** resource is: ``` homebrew_tap 'name' do homebrew_path String # default value: "/usr/local/bin/brew" owner String # default value: "Calculated default username" tap_name String # default value: 'name' unless specified url String action Symbol # defaults to :tap if not specified end ``` where: * `homebrew_tap` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `homebrew_path`, `owner`, `tap_name`, and `url` are the properties available to this resource. Actions ------- --- The **homebrew_tap** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:tap` Add a Homebrew tap. (default) `:untap` Remove a Homebrew tap. Properties ---------- --- The **homebrew_tap** resource has the following properties: `homebrew_path` **Ruby Type:** String | **Default Value:** `/usr/local/bin/brew` The path to the Homebrew binary. `owner` **Ruby Type:** String | **Default Value:** `Calculated default username` The owner of the Homebrew installation. `tap_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the tap name if it differs from the resource block’s name. `url` **Ruby Type:** String The URL of the tap. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/homebrew_tap/homebrew_package Resource ========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [homebrew_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/homebrew_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **homebrew_package** resource to manage packages for the macOS platform. Note Starting with Chef Infra Client 16 the homebrew resource now accepts an array of packages for installing multiple packages at once. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. **New in Chef Infra Client 12.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **homebrew_package** resource is: ``` homebrew_package 'name' do homebrew_user String, Integer options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `homebrew_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `homebrew_user`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **homebrew_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and ensure that a package is the latest version. Properties ---------- --- The **homebrew_package** resource has the following properties: `homebrew_user` **Ruby Type:** String, Integer The name or uid of the Homebrew owner to be used by Chef Infra Client when executing a command. Chef Infra Client, by default, will attempt to execute a Homebrew command as the owner of the `/usr/local/bin/brew` executable. If that executable does not exist, Chef Infra Client will attempt to find the user by executing `which brew`. If that executable cannot be found, Chef Infra Client will print an error message: `Could not find the 'brew' executable in /usr/local/bin or anywhere on the path.`. Set this property to specify the Homebrew owner for situations where Chef Infra Client cannot automatically detect the correct owner.' `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Examples -------- --- The following examples demonstrate various approaches for using the **homebrew_package** resource in recipes: **Install a package**: ``` homebrew_package 'git' ``` **Install multiple packages at once**: ``` homebrew_package %w(git fish ruby) ``` **Specify the Homebrew user with a UUID** ``` homebrew_package 'git' do homebrew_user 1001 end ``` **Specify the Homebrew user with a string**: ``` homebrew_package 'vim' do homebrew_user 'user1' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/homebrew_package/homebrew_update Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [homebrew_update.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/homebrew_update.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **homebrew_update** resource to manage Homebrew repository updates on macOS. **New in Chef Infra Client 16.2.** Syntax ------ --- The full syntax for all of the properties that are available to the **homebrew_update** resource is: ``` homebrew_update 'name' do frequency Integer # default value: 86400 action Symbol # defaults to :periodic if not specified end ``` where: * `homebrew_update` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `frequency` is the property available to this resource. Actions ------- --- The **homebrew_update** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:periodic` Run a periodic update based on the frequency property. (default) `:update` Run an immediate update. Properties ---------- --- The **homebrew_update** resource has the following properties: `frequency` **Ruby Type:** Integer | **Default Value:** `86400` Determines how frequently (in seconds) Homebrew updates are made. Use this property when the `:periodic` action is specified. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **homebrew_update** resource in recipes: **Update the homebrew repository data at a specified interval**: ``` homebrew_update 'all platforms' do frequency 86400 action :periodic end ``` **Update the Homebrew repository at the start of a Chef Infra Client run**: ``` homebrew_update 'update' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/homebrew_update/hostname Resource ================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [hostname.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/hostname.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **hostname** resource to set the system’s hostname, configure hostname and hosts config file, and re-run the Ohai hostname plugin so the hostname will be available in subsequent cookbooks. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **hostname** resource is: ``` hostname 'name' do aliases Array compile_time true, false # default value: true domain_password String domain_user String fqdn String hostname String # default value: 'name' unless specified ipaddress String # default value: The node's IP address as determined by Ohai. windows_reboot true, false # default value: true action Symbol # defaults to :set if not specified end ``` where: * `hostname` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `aliases`, `compile_time`, `domain_password`, `domain_user`, `fqdn`, `hostname`, `ipaddress`, and `windows_reboot` are the properties available to this resource. Actions ------- --- The **hostname** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Sets the node’s hostname. (default) Properties ---------- --- The **hostname** resource has the following properties: `aliases` **Ruby Type:** Array An array of hostname aliases to use when configuring the hosts file. `compile_time` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the resource should be run at compile time. `domain_password` **Ruby Type:** String The password to accompany the domain_user parameter New in Chef Infra Client 17.2 `domain_user` **Ruby Type:** String A domain account specified in the form of DOMAIN\user used when renaming a domain-joined device New in Chef Infra Client 17.2 `fqdn` **Ruby Type:** String An optional property to set the fqdn if it differs from the resource block’s hostname. New in Chef Infra Client 17.0 `hostname` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the hostname if it differs from the resource block’s name. `ipaddress` **Ruby Type:** String | **Default Value:** `The node's IP address as determined by Ohai.` The IP address to use when configuring the hosts file. `windows_reboot` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not Windows should be reboot after changing the hostname, as this is required for the change to take effect. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **hostname** resource in recipes: **Set the hostname using the IP address, as detected by Ohai**: ``` hostname 'example' ``` **Manually specify the hostname and IP address**: ``` hostname 'statically_configured_host' do hostname 'example' ipaddress '198.51.100.2' end ``` **Change the hostname of a Windows, Non-Domain joined node**: ``` hostname 'renaming a workgroup computer' do hostname 'Foo' end ``` **Change the hostname of a Windows, Domain-joined node (new in 17.2)**: ``` hostname 'renaming a domain-joined computer' do hostname 'Foo' domain_user "Domain\Someone" domain_password 'SomePassword' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/hostname/inspec_input Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [inspec_input.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/inspec_input.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **inspec_input** resource to add an input to the Compliance Phase. **New in Chef Infra Client 17.5.** Syntax ------ --- The full syntax for all of the properties that are available to the **inspec_input** resource is: ``` inspec_input 'name' do input Hash, String # default value: 'name' unless specified source Hash, String # default value: 'name' unless specified action Symbol # defaults to :add if not specified end ``` where: * `inspec_input` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `input` and `source` are the properties available to this resource. Actions ------- --- The **inspec_input** resource has the following actions: `:add` Add an input to the compliance phase (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **inspec_input** resource has the following properties: `input` **Ruby Type:** Hash, String | **Default Value:** `The resource block's name` `source` **Ruby Type:** Hash, String | **Default Value:** `The resource block's name` Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **inspec_input** resource in recipes: **Activate the default input in the openssh cookbook’s compliance segment**: ``` inspec_input 'openssh' do action :add end ``` **Activate all inputs in the openssh cookbook’s compliance segment**: ``` inspec_input 'openssh::.*' do action :add end ``` **Add an InSpec input to the Compliance Phase from a hash**: ``` inspec_input { ssh_custom_path: '/whatever2' } ``` **Add an InSpec input to the Compliance Phase using the ‘name’ property to identify the input**: ``` inspec_input "setting my input" do source( { ssh_custom_path: '/whatever2' }) end ``` **Add an InSpec input to the Compliance Phase using a TOML, JSON, or YAML file**: ``` inspec_input "/path/to/my/input.yml" ``` **Add an InSpec input to the Compliance Phase using a TOML, JSON, or YAML file, using the ‘name’ property**: ``` inspec_input "setting my input" do source "/path/to/my/input.yml" end ``` Note that the **inspec_input** resource does not update and will not fire notifications (similar to the log resource). This is done to preserve the ability to use the resource while not causing the updated resource count to be larger than zero. Since the resource does not update the state of the managed node, this behavior is still consistent with the configuration management model. Instead, you should use events to observe configuration changes for the compliance phase. It is possible to use the `notify_group` resource to chain notifications of the two resources, but notifications are the wrong model to use, and you should use pure ruby conditionals instead. Compliance configuration should be independent of other resources and should only be conditional based on state/attributes, not other resources. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/inspec_input/ifconfig Resource ================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [ifconfig.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/ifconfig.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **ifconfig** resource to manage interfaces on Unix and Linux systems. Note This resource requires the ifconfig binary to be present on the system and may require additional packages to be installed first. On Ubuntu 18.04 or later you will need to install the `ifupdown` package, which disables the built in Netplan functionality. Warning This resource will not work with Fedora release 33 or later. Syntax ------ --- The full syntax for all of the properties that are available to the **ifconfig** resource is: ``` ifconfig 'name' do bcast String bonding_opts String bootproto String bridge String device String ethtool_opts String family String # default value: "inet" gateway String hwaddr String inet_addr String mask String master String metric String mtu String network String onboot String onparent String slave String target String # default value: 'name' unless specified vlan String action Symbol # defaults to :add if not specified end ``` where: * `ifconfig` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bcast`, `bonding_opts`, `bootproto`, `bridge`, `device`, `ethtool_opts`, `family`, `gateway`, `hwaddr`, `inet_addr`, `mask`, `master`, `metric`, `mtu`, `network`, `onboot`, `onparent`, `slave`, `target`, and `vlan` are the properties available to this resource. Actions ------- --- The **ifconfig** resource has the following actions: `:add` Run ifconfig to configure a network interface and (on some platforms) write a configuration file for that network interface. (default) `:delete` Run ifconfig to disable a network interface and (on some platforms) delete that network interface’s configuration file. `:disable` Run ifconfig to disable a network interface. `:enable` Run ifconfig to enable a network interface. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **ifconfig** resource has the following properties: `bcast` **Ruby Type:** String The broadcast address for a network interface. On some platforms this property is not set using ifconfig, but instead is added to the startup configuration file for the network interface. `bonding_opts` **Ruby Type:** String Bonding options to pass via `BONDING_OPTS` on RHEL and CentOS. For example: `mode=active-backup miimon=100`. New in Chef Client 13.4 `bootproto` **Ruby Type:** String The boot protocol used by a network interface. `bridge` **Ruby Type:** String The bridge interface this interface is a member of on Red Hat based systems. New in Chef Infra Client 16.7 `device` **Ruby Type:** String The network interface to be configured. `ethtool_opts` **Ruby Type:** String Options to be passed to ethtool(8). For example: `-A eth0 autoneg off rx off tx off`. New in Chef Client 13.4 `family` **Ruby Type:** String | **Default Value:** `inet` Networking family option for Debian-based systems; for example: `inet` or `inet6`. New in Chef Client 14.0 `gateway` **Ruby Type:** String The gateway to use for the interface. New in Chef Client 14.4 `hwaddr` **Ruby Type:** String The hardware address for the network interface. `inet_addr` **Ruby Type:** String The Internet host address for the network interface. `mask` **Ruby Type:** String The decimal representation of the network mask. For example: `255.255.255.0`. `master` **Ruby Type:** String Specifies the channel bonding interface to which the Ethernet interface is linked. New in Chef Client 13.4 `metric` **Ruby Type:** String The routing metric for the interface. `mtu` **Ruby Type:** String The maximum transmission unit (MTU) for the network interface. `network` **Ruby Type:** String The address for the network interface. `onboot` **Ruby Type:** String Bring up the network interface on boot. `onparent` **Ruby Type:** String Bring up the network interface when its parent interface is brought up. `slave` **Ruby Type:** String When set to `yes`, this device is controlled by the channel bonding interface that is specified via the `master` property. New in Chef Client 13.4 `target` **Ruby Type:** String | **Default Value:** `The resource block's name` The IP address that is to be assigned to the network interface. If not specified we’ll use the resource’s name. `vlan` **Ruby Type:** String The VLAN to assign the interface to. New in Chef Client 14.4 Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **ifconfig** resource in recipes: **Configure a network interface with a static IP** ``` ifconfig '33.33.33.80' do device 'eth1' end ``` will create the following interface configuration: ``` iface eth1 inet static address 33.33.33.80 ``` **Configure an interface to use DHCP** ``` ifconfig 'Set eth1 to DHCP' do device 'eth1' bootproto 'dhcp' end ``` will create the following interface configuration: ``` iface eth1 inet dhcp ``` **Update a static IP address with a boot protocol** ``` ifconfig "33.33.33.80" do bootproto "dhcp" device "eth1" end ``` will update the interface configuration from static to dhcp: ``` iface eth1 inet dhcp address 33.33.33.80 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/ifconfig/inspec_waiver Resource ======================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [inspec_waiver.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/inspec_waiver.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **inspec_waiver** resource to add a waiver to the Compliance Phase. **New in Chef Infra Client 17.5.** Syntax ------ --- The full syntax for all of the properties that are available to the **inspec_waiver** resource is: ``` inspec_waiver 'name' do control String # default value: 'name' unless specified expiration String justification String run_test true, false source Hash, String action Symbol # defaults to :add if not specified end ``` where: * `inspec_waiver` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `control`, `expiration`, `justification`, `run_test`, and `source` are the properties available to this resource. Actions ------- --- The **inspec_waiver** resource has the following actions: `:add` Add a waiver to the compliance phase (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **inspec_waiver** resource has the following properties: `control` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the control being waived `expiration` **Ruby Type:** String The expiration date of the waiver - provided in YYYY-MM-DD format `justification` **Ruby Type:** String Can be any text you want and might include a reason for the waiver as well as who signed off on the waiver. `run_test` **Ruby Type:** true, false If present and true, the control will run and be reported, but failures in it won’t make the overall run fail. If absent or false, the control will not be run. `source` **Ruby Type:** Hash, String Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **inspec_waiver** resource in recipes: **Activate the default waiver in the openssh cookbook’s compliance segment**: ``` inspec_waiver 'openssh' do action :add end ``` **Activate all waivers in the openssh cookbook’s compliance segment**: ``` inspec_waiver 'openssh::.*' do action :add end ``` **Add an InSpec waiver to the Compliance Phase**: ``` inspec_waiver 'Add waiver entry for control' do control 'my_inspec_control_01' run_test false justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" expiration '2022-01-01' action :add end ``` **Add an InSpec waiver to the Compliance Phase using the ‘name’ property to identify the control**: ``` inspec_waiver 'my_inspec_control_01' do justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" action :add end ``` **Add an InSpec waiver to the Compliance Phase using an arbitrary YAML, JSON, or TOML file**: ``` # files ending in .yml or .yaml that exist are parsed as YAML inspec_waiver "/path/to/my/waiver.yml" inspec_waiver "my-waiver-name" do source "/path/to/my/waiver.yml" end # files ending in .json that exist are parsed as JSON inspec_waiver "/path/to/my/waiver.json" inspec_waiver "my-waiver-name" do source "/path/to/my/waiver.json" end # files ending in .toml that exist are parsed as TOML inspec_waiver "/path/to/my/waiver.toml" inspec_waiver "my-waiver-name" do source "/path/to/my/waiver.toml" end ``` **Add an InSpec waiver to the Compliance Phase using a hash**: ``` my_hash = { "ssh-01" => { "expiration_date" => "2033-07-31", "run" => false, "justification" => "because" } } inspec_waiver "my-waiver-name" do source my_hash end ``` Note that the **inspec_waiver** resource does not update and will not fire notifications (similar to the log resource). This is done to preserve the ability to use the resource while not causing the updated resource count to be larger than zero. Since the resource does not update the state of the managed node, this behavior is still consistent with the configuration management model. Instead, you should use events to observe configuration changes for the compliance phase. It is possible to use the `notify_group` resource to chain notifications of the two resources, but notifications are the wrong model to use, and you should use pure ruby conditionals instead. Compliance configuration should be independent of other resources and should only be conditional based on state/attributes, not other resources. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/inspec_waiver/inspec_waiver_file_entry Resource ==================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [inspec_waiver_file_entry.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/inspec_waiver_file_entry.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **inspec_waiver_file_entry** resource to add or remove entries from an InSpec waiver file. This can be used in conjunction with the Compliance Phase. **New in Chef Infra Client 17.1.** Syntax ------ --- The full syntax for all of the properties that are available to the **inspec_waiver_file_entry** resource is: ``` inspec_waiver_file_entry 'name' do backup false, Integer # default value: false control String # default value: 'name' unless specified expiration String file_path String justification String run_test true, false action Symbol # defaults to :add if not specified end ``` where: * `inspec_waiver_file_entry` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `backup`, `control`, `expiration`, `file_path`, `justification`, and `run_test` are the properties available to this resource. Actions ------- --- The **inspec_waiver_file_entry** resource has the following actions: `:add` (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Properties ---------- --- The **inspec_waiver_file_entry** resource has the following properties: `backup` **Ruby Type:** false, Integer | **Default Value:** `false` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `control` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the control being added or removed to the waiver file `expiration` **Ruby Type:** String The expiration date of the given waiver - provided in YYYY-MM-DD format `file_path` **Ruby Type:** String | **Default Value:** ``/etc/chef/inspec_waivers.yml` on Linux/Unix and `C:\chef\inspec_waivers.yml` on Windows` | `REQUIRED` The path to the waiver file being modified `justification` **Ruby Type:** String Can be any text you want and might include a reason for the waiver as well as who signed off on the waiver. `run_test` **Ruby Type:** true, false If present and `true`, the control will run and be reported, but failures in it won’t make the overall run fail. If absent or `false`, the control will not be run. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **inspec_waiver_file_entry** resource in recipes: **Add an InSpec waiver entry to a given waiver file**: ``` inspec_waiver_file_entry 'Add waiver entry for control' do file_path 'C:\chef\inspec_waiver_file.yml' control 'my_inspec_control_01' run_test false justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" expiration '2022-01-01' action :add end ``` **Add an InSpec waiver entry to a given waiver file using the ‘name’ property to identify the control**: ``` inspec_waiver_file_entry 'my_inspec_control_01' do justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" action :add end ``` **Remove an InSpec waiver entry to a given waiver file**: ``` inspec_waiver_file_entry "my_inspec_control_01" do action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/inspec_waiver_file_entry/ips_package Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [ips_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/ips_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **ips_package** resource to manage packages (using Image Packaging System (IPS)) on the Solaris 11 platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. Syntax ------ --- A **ips_package** resource block manages a package on a node, typically by installing it. The simplest use of the **ips_package** resource is: ``` ips_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **ips_package** resource is: ``` ips_package 'name' do accept_license true, false # default value: false options String package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `ips_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_license`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **ips_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **ips_package** resource has the following properties: `accept_license` **Ruby Type:** true, false | **Default Value:** `false` Accept an end-user license agreement, automatically. `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **ips_package** resource in recipes: Install a package ``` ips_package 'name of package' do action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/ips_package/launchd Resource ================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [launchd.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/launchd.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **launchd** resource to manage system-wide services (daemons) and per-user services (agents) on the macOS platform. **New in Chef Infra Client 12.8.** Syntax ------ --- The full syntax for all of the properties that are available to the **launchd** resource is: ``` launchd 'name' do abandon_process_group true, false backup Integer, false cookbook String debug true, false disabled true, false # default value: false enable_globbing true, false enable_transactions true, false environment_variables Hash exit_timeout Integer group String, Integer hard_resource_limits Hash inetd_compatibility Hash init_groups true, false keep_alive true, false, Hash label String # default value: 'name' unless specified launch_events Hash launch_only_once true, false ld_group String limit_load_from_hosts Array limit_load_to_hosts Array limit_load_to_session_type Array, String low_priority_io true, false mach_services Hash mode String, Integer nice Integer on_demand true, false owner String, Integer path String plist_hash Hash process_type String program String program_arguments Array queue_directories Array root_directory String run_at_load true, false session_type String sockets Hash soft_resource_limits Array source String standard_error_path String standard_in_path String standard_out_path String start_calendar_interval Hash, Array start_interval Integer start_on_mount true, false throttle_interval Integer time_out Integer type String # default value: "daemon" username String wait_for_debugger true, false watch_paths Array working_directory String action Symbol # defaults to :create if not specified end ``` where: * `launchd` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `abandon_process_group`, `backup`, `cookbook`, `debug`, `disabled`, `enable_globbing`, `enable_transactions`, `environment_variables`, `exit_timeout`, `group`, `hard_resource_limits`, `inetd_compatibility`, `init_groups`, `keep_alive`, `label`, `launch_events`, `launch_only_once`, `ld_group`, `limit_load_from_hosts`, `limit_load_to_hosts`, `limit_load_to_session_type`, `low_priority_io`, `mach_services`, `mode`, `nice`, `on_demand`, `owner`, `path`, `plist_hash`, `process_type`, `program`, `program_arguments`, `queue_directories`, `root_directory`, `run_at_load`, `session_type`, `sockets`, `soft_resource_limits`, `source`, `standard_error_path`, `standard_in_path`, `standard_out_path`, `start_calendar_interval`, `start_interval`, `start_on_mount`, `throttle_interval`, `time_out`, `type`, `username`, `wait_for_debugger`, `watch_paths`, and `working_directory` are the properties available to this resource. Actions ------- --- The **launchd** resource has the following actions: `:create` Create a launchd property list. (default) `:create_if_missing` Create a launchd property list, if it does not already exist. `:delete` Delete a launchd property list. This will unload a daemon or agent, if loaded. `:disable` Disable a launchd property list. `:enable` Create a launchd property list, and then ensure that it is enabled. If a launchd property list already exists, but does not match, updates the property list to match, and then restarts the daemon or agent. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:restart` Restart a launchd managed daemon or agent. Properties ---------- --- The **launchd** resource has the following properties: `abandon_process_group` **Ruby Type:** true, false If a job dies, all remaining processes with the same process ID may be kept running. Set to true to kill all remaining processes. `backup` **Ruby Type:** Integer, false The number of backups to be kept in `/var/chef/backup`. Set to `false` to prevent backups from being kept. `cookbook` **Ruby Type:** String The name of the cookbook in which the source files are located. `group` **Ruby Type:** String, Integer When launchd is run as the root user, the group to run the job as. If the `username` property is specified and this property is not, this value is set to the default group for the user. `label` **Ruby Type:** String The unique identifier for the job. `mode` **Ruby Type:** Integer, String | **Default Value:** `'0755'` A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the `name` of the resource block. See “Syntax” section above for more information. `plist_hash` **Ruby Type:** Hash A Hash of key value pairs used to create the launchd property list. `session_type` **Ruby Type:** String The type of launchd plist to be created. Possible values: `system` (default) or `user`. `source` **Ruby Type:** String The path to the launchd property list. `type` **Ruby Type:** String The type of resource. Possible values: `daemon` (default), `agent`. `abandon_process_group` **Ruby Type:** true, false If a job dies, all remaining processes with the same process ID may be kept running. Set to true to kill all remaining processes. `debug` **Ruby Type:** true, false Sets the log mask to `LOG_DEBUG` for this job. `disabled` **Ruby Type:** true, false | **Default Value:** `false` Hints to `launchctl` to not submit this job to launchd. `enable_globbing` **Ruby Type:** true, false Update program arguments before invocation. `enable_transactions` **Ruby Type:** true, false Track in-progress transactions; if none, then send the `SIGKILL` signal. `environment_variables` **Ruby Type:** Hash Additional environment variables to set before running a job. `exit_timeout` **Ruby Type:** Integer The amount of time (in seconds) launchd waits before sending a `SIGKILL` signal. `hard_resource_limits` **Ruby Type:** Hash A Hash of resource limits to be imposed on a job. `inetd_compatibility` **Ruby Type:** Hash Specifies if a daemon expects to be run as if it were launched from inetd. Set to `wait => true` to pass standard input, output, and error file descriptors. Set to `wait => false` to call the accept system call on behalf of the job, and then pass standard input, output, and error file descriptors. `init_groups` **Ruby Type:** true, false Specify if `initgroups` is called before running a job. `keep_alive` **Ruby Type:** true, false, Hash Keep a job running continuously (true) or allow demand and conditions on the node to determine if the job keeps running (`false`). New in Chef Client 12.14 `launch_events` **Ruby Type:** Hash Specify higher-level event types to be used as launch-on-demand event sources. New in Chef Infra Client 15.1 `launch_only_once` **Ruby Type:** true, false Specify if a job can be run only one time. Set this value to true if a job cannot be restarted without a full machine reboot. `limit_load_from_hosts` **Ruby Type:** Array An array of hosts to which this configuration file does not apply, i.e. ‘apply this configuration file to all hosts not specified in this array’. `limit_load_to_hosts` **Ruby Type:** Array An array of hosts to which this configuration file applies. `limit_load_to_session_type` **Ruby Type:** Array, String The session type(s) to which this configuration file applies. `low_priority_io` **Ruby Type:** true, false Specify if the kernel on the node should consider this daemon to be low priority during file system I/O. `mach_services` **Ruby Type:** Hash Specify services to be registered with the bootstrap subsystem. `nice` **Ruby Type:** Integer The program scheduling priority value in the range -20 to 19. `on_demand` **Ruby Type:** true, false Keep a job alive. Only applies to macOS version 10.4 (and earlier); use `keep_alive` instead for newer versions. `process_type` **Ruby Type:** String The intended purpose of the job: `Adaptive`, `Background`, `Interactive`, or `Standard`. `program` **Ruby Type:** String The first argument of `execvp`, typically the file name associated with the file to be executed. This value must be specified if `program_arguments` is not specified, and vice-versa. `program_arguments` **Ruby Type:** Array The second argument of `execvp`. If program is not specified, this property must be specified and will be handled as if it were the first argument. `queue_directories` **Ruby Type:** Array An array of non-empty directories which, if any are modified, will cause a job to be started. `root_directory` **Ruby Type:** String `chroot` to this directory, and then run the job. `run_at_load` **Ruby Type:** true, false Launch a job once (at the time it is loaded). `sockets` **Ruby Type:** Hash A Hash of on-demand sockets that notify launchd when a job should be run. `soft_resource_limits` **Ruby Type:** Array A Hash of resource limits to be imposed on a job. `standard_error_path` **Ruby Type:** String The file to which standard error (`stderr`) is sent. `standard_in_path` **Ruby Type:** String The file to which standard input (`stdin`) is sent. `standard_out_path` **Ruby Type:** String The file to which standard output (`stdout`) is sent. `start_calendar_interval` **Ruby Type:** Hash A Hash (similar to `crontab`) that defines the calendar frequency at which a job is started. For example: `{ Minute => "0", Hour => "20", Day => "*", Weekday => "1-5", Month => "*" }` will run a job at 8:00 PM every day, Monday through Friday, every month of the year. `start_interval` **Ruby Type:** Integer The frequency (in seconds) at which a job is started. `start_on_mount` **Ruby Type:** true, false Start a job every time a file system is mounted. `throttle_interval` **Ruby Type:** Integer | **Default Value:** `10` The frequency (in seconds) at which jobs are allowed to spawn. `time_out` **Ruby Type:** Integer The amount of time (in seconds) a job may be idle before it times out. If no value is specified, the default timeout value for launchd will be used. `username` **Ruby Type:** String When launchd is run as the root user, the user to run the job as. `wait_for_debugger` **Ruby Type:** true, false Specify if launchd has a job wait for a debugger to attach before executing code. `watch_paths` **Ruby Type:** Array An array of paths which, if any are modified, will cause a job to be started. `working_directory` **Ruby Type:** String `chdir` to this directory, and then run the job. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **launchd** resource in recipes: Create a Launch Daemon from a cookbook file ``` launchd 'com.chef.every15' do source 'com.chef.every15.plist' end ``` Create a Launch Daemon using keys ``` launchd 'call.mom.weekly' do program '/Library/scripts/call_mom.sh' start_calendar_interval 'Weekday' => 7, 'Hourly' => 10 time_out 300 end ``` Remove a Launch Daemon ``` launchd 'com.chef.every15' do action :delete end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/launchd/kernel_module Resource ======================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [kernel_module.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/kernel_module.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **kernel_module** resource to manage kernel modules on Linux systems. This resource can load, unload, blacklist, disable, enable, install, and uninstall modules. **New in Chef Infra Client 14.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **kernel_module** resource is: ``` kernel_module 'name' do load_dir String # default value: "/etc/modules-load.d" modname String # default value: 'name' unless specified options Array unload_dir String # default value: "/etc/modprobe.d" action Symbol # defaults to :install if not specified end ``` where: * `kernel_module` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `load_dir`, `modname`, `options`, and `unload_dir` are the properties available to this resource. Actions ------- --- The **kernel_module** resource has the following actions: `:blacklist` Blacklist a kernel module. `:disable` Disable a kernel module. **New in Chef Infra Client 15.2.** `:enable` Enable a kernel module. Reverse :disable actions `:install` Load kernel module, and ensure it loads on reboot. (default) `:load` Load a kernel module. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:uninstall` Unload a kernel module and remove module config, so it doesn’t load on reboot. `:unload` Unload kernel module. Properties ---------- --- The **kernel_module** resource has the following properties: `load_dir` **Ruby Type:** String | **Default Value:** `/etc/modules-load.d` The directory to load modules from. `modname` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the kernel module name if it differs from the resource block’s name. `options` **Ruby Type:** Array An optional property to set options for the kernel module. New in Chef Infra Client 15.4 `unload_dir` **Ruby Type:** String | **Default Value:** `/etc/modprobe.d` The modprobe.d directory. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **kernel_module** resource in recipes: Install and load a kernel module, and ensure it loads on reboot. ``` kernel_module 'loop' ``` Install and load a kernel with a specific set of options, and ensure it loads on reboot. Consult kernel module documentation for specific options that are supported. ``` kernel_module 'loop' do options [ 'max_loop=4', 'max_part=8', ] end ``` Load a kernel module. ``` kernel_module 'loop' do action :load end ``` Unload a kernel module and remove module config, so it doesn’t load on reboot. ``` kernel_module 'loop' do action :uninstall end ``` Unload kernel module. ``` kernel_module 'loop' do action :unload end ``` Blacklist a module from loading. ``` kernel_module 'loop' do action :blacklist end ``` Disable a kernel module so that it is not installable. ``` kernel_module 'loop' do action :disable end ``` Enable a kernel module so that it is can be installed. Does not load or install. ``` kernel_module 'loop' do action :enable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/kernel_module/ksh Resource ============ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [ksh.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/ksh.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **ksh** resource to execute scripts using the Korn shell (ksh) interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. Syntax ------ --- A **ksh** resource block executes scripts using ksh: ``` ksh 'hello world' do code <<-EOH echo "Hello world!" echo "Current directory: " $cwd EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **ksh** resource is: ``` ksh 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `ksh` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **ksh** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. Properties ---------- --- The **ksh** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/ksh/link Resource ============= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [link.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/link.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **link** resource to create symbolic or hard links. A symbolic link—sometimes referred to as a soft link—is a directory entry that associates a file name with a string that contains an absolute or relative path to a file on any file system. In other words, “a file that contains a path that points to another file.” A symbolic link creates a new file with a new inode that points to the inode location of the original file. A hard link is a directory entry that associates a file with another file in the same file system. In other words, “multiple directory entries to the same file.” A hard link creates a new file that points to the same inode as the original file. On Windows, this resource can be used to create directory junction/reparse points. Syntax ------ --- A **link** resource block creates symbolic or hard links. For example, to create a hard link from `/tmp/file` to `/etc/file`: ``` link '/tmp/file' do to '/etc/file' link_type :hard end ``` Because the default value for `link_type` is symbolic, and because properties that are not specified in the resource block will be assigned their default values, the following example creates a symbolic link: ``` link '/tmp/file' do to '/etc/file' end ``` The full syntax for all of the properties that are available to the **link** resource is: ``` link 'name' do group String, Integer link_type String, Symbol # default value: :symbolic mode Integer, String owner String, Integer target_file String # default value: 'name' unless specified to String action Symbol # defaults to :create if not specified end ``` where: * `link` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `group`, `link_type`, `mode`, `owner`, `target_file`, and `to` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **link** resource has the following actions: `:create` Default. Create a link. If a link already exists (but does not match), update that link to match. `:delete` Delete a link. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **link** resource has the following properties: `group` **Ruby Type:** String, Integer A group name or ID number that identifies the group associated with a symbolic link. `link_type` **Ruby Type:** String, Symbol | **Default Value:** `:symbolic` **Allowed Values:** `:hard, :symbolic` The type of link: `:symbolic` or `:hard`. On Windows, `:symbolic` will create a junction point if the target is a directory. `mode` **Ruby Type:** Integer, String | **Default Value:** `777` If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** String, Integer The owner associated with a symbolic link. `target_file` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the target file if it differs from the resource block’s name. `to` **Ruby Type:** String The actual file to which the link is to be created. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **link** resource in recipes: Create symbolic links The following example will create a symbolic link from `/tmp/file` to `/etc/file`: ``` link '/tmp/file' do to '/etc/file' end ``` Create hard links The following example will create a hard link from `/tmp/file` to `/etc/file`: ``` link '/tmp/file' do to '/etc/file' link_type :hard end ``` Delete links The following example will delete the `/tmp/file` symbolic link and uses the `only_if` guard to run the `test -L` command, which verifies that `/tmp/file` is a symbolic link, and then only deletes `/tmp/file` if the test passes: ``` link '/tmp/file' do action :delete only_if 'test -L /tmp/file' end ``` Create multiple symbolic links The following example creates symbolic links from two files in the `/vol/webserver/cert/` directory to files located in the `/etc/ssl/certs/` directory: ``` link '/vol/webserver/cert/server.crt' do to '/etc/ssl/certs/ssl-cert-name.pem' end link '/vol/webserver/cert/server.key' do to '/etc/ssl/certs/ssl-cert-name.key' end ``` Create platform-specific symbolic links The following example shows installing a filter module on Apache. The package name is different for different platforms, and for the Red Hat Enterprise Linux family, a symbolic link is required: ``` include_recipe 'apache2::default' case node['platform_family'] when 'debian' ... when 'suse' ... when 'rhel', 'fedora' ... link '/usr/lib64/httpd/modules/mod_apreq.so' do to '/usr/lib64/httpd/modules/mod_apreq2.so' only_if 'test -f /usr/lib64/httpd/modules/mod_apreq2.so' end link '/usr/lib/httpd/modules/mod_apreq.so' do to '/usr/lib/httpd/modules/mod_apreq2.so' only_if 'test -f /usr/lib/httpd/modules/mod_apreq2.so' end end ... ``` For the complete recipe, see <https://github.com/onehealth-cookbooks/apache2/blob/68bdfba4680e70b3e90f77e40223dd535bf22c17/recipes/mod_apreq2.rb>. **Create Windows junction/reparse points** This example demonstrates how to create a directory junction/reparse point. In this example, `C:\destination` will be a junction/reparse point to the `C:\source` directory. ``` directory 'C:/source' link 'C:/destination' do link_type :symbolic to 'C:/source' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/link/msu_package Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [msu_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/msu_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **msu_package** resource to install Microsoft Update(MSU) packages on Microsoft Windows machines. **New in Chef Infra Client 12.17.** Syntax ------ --- The full syntax for all of the properties that are available to the **msu_package** resource is: ``` msu_package 'name' do checksum String options String package_name String source String timeout String, Integer # default value: 3600 action Symbol # defaults to :install if not specified end ``` where: * `msu_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `checksum`, `options`, `package_name`, `source`, and `timeout` are the properties available to this resource. Actions ------- --- The **msu_package** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **msu_package** resource has the following properties: `checksum` **Ruby Type:** String SHA-256 digest used to verify the checksum of the downloaded MSU package. `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The local file path or URL for the MSU package. `timeout` **Ruby Type:** String, Integer | **Default Value:** `3600` The amount of time (in seconds) to wait before timing out. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **msu_package** resource in recipes: Using local path in source ``` msu_package 'Install Windows 2012R2 Update KB2959977' do source 'C:\Users\xyz\AppData\Local\Temp\Windows8.1-KB2959977-x64.msu' action :install end ``` ``` msu_package 'Remove Windows 2012R2 Update KB2959977' do source 'C:\Users\xyz\AppData\Local\Temp\Windows8.1-KB2959977-x64.msu' action :remove end ``` Using URL in source ``` msu_package 'Install Windows 2012R2 Update KB2959977' do source 'https://s3.amazonaws.com/my_bucket/Windows8.1-KB2959977-x64.msu' action :install end ``` ``` msu_package 'Remove Windows 2012R2 Update KB2959977' do source 'https://s3.amazonaws.com/my_bucket/Windows8.1-KB2959977-x64.msu' action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/msu_package/macports_package Resource ========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [macports_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/macports_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **macports_package** resource to manage packages for the macOS platform using the MacPorts package management system. Syntax ------ --- A **macports_package** resource block manages a package on a node, typically by installing it. The simplest use of the **macports_package** resource is: ``` macports_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **macports_package** resource is: ``` macports_package 'name' do options String package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `macports_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **macports_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **macports_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **macports_package** resource in recipes: Install a package ``` macports_package 'name of package' do action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/macports_package/mdadm Resource ============== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [mdadm.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/mdadm.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **mdadm** resource to manage RAID devices in a Linux environment using the mdadm utility. The mdadm resource will create and assemble an array, but it will not create the config file that is used to persist the array upon reboot. If the config file is required, it must be done by specifying a template with the correct array layout, and then by using the mount provider to create a file systems table (fstab) entry. Syntax ------ --- The full syntax for all of the properties that are available to the **mdadm** resource is: ``` mdadm 'name' do bitmap String chunk Integer # default value: 16 devices Array # default value: [] layout String level Integer # default value: 1 metadata String # default value: "0.90" raid_device String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `mdadm` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bitmap`, `chunk`, `devices`, `layout`, `level`, `metadata`, and `raid_device` are the properties available to this resource. Actions ------- --- The **mdadm** resource has the following actions: `:assemble` Assemble a previously created array into an active array. `:create` Create an array with per-device superblocks. If an array already exists (but does not match), update that array to match. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:stop` Stop an active array. Properties ---------- --- The **mdadm** resource has the following properties: `bitmap` **Ruby Type:** String The path to a file in which a write-intent bitmap is stored. `chunk` **Ruby Type:** Integer | **Default Value:** `16` The chunk size. This property should not be used for a RAID 1 mirrored pair (i.e. when the `level` property is set to `1`). `devices` **Ruby Type:** Array | **Default Value:** `[]` The devices to be part of a RAID array. `layout` **Ruby Type:** String The RAID5 parity algorithm. Possible values: `left-asymmetric` (or `la`), `left-symmetric` (or ls), `right-asymmetric` (or `ra`), or `right-symmetric` (or `rs`). `level` **Ruby Type:** Integer | **Default Value:** `1` The RAID level. `metadata` **Ruby Type:** String | **Default Value:** `0.90` The superblock type for RAID metadata. `raid_device` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to specify the name of the RAID device if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **mdadm** resource in recipes: **Create and assemble a RAID 0 array** The mdadm command can be used to create RAID arrays. For example, a RAID 0 array named /dev/md0 with 10 devices would have a command similar to the following: ``` mdadm --create /dev/md0 --level=0 --raid-devices=10 /dev/s01.../dev/s10 ``` where /dev/s01 .. /dev/s10 represents 10 devices (01, 02, 03, and so on). This same command, when expressed as a recipe using the mdadm resource, would be similar to: ``` mdadm '/dev/md0' do devices [ '/dev/s01', ... '/dev/s10' ] level 0 action :create end ``` (again, where /dev/s01 .. /dev/s10 represents devices /dev/s01, /dev/s02, /dev/s03, and so on). **Create and assemble a RAID 1 array** ``` mdadm '/dev/md0' do devices [ '/dev/sda', '/dev/sdb' ] level 1 action [ :create, :assemble ] end ``` **Create and assemble a RAID 5 array** The mdadm command can be used to create RAID arrays. For example, a RAID 5 array named /dev/sd0 with 4, and a superblock type of 0.90 would be similar to: ``` mdadm '/dev/sd0' do devices [ '/dev/s1', '/dev/s2', '/dev/s3', '/dev/s4' ] level 5 metadata '0.90' chunk 32 action :create end ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/mdadm/locale Resource =============== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [locale.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/locale.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **locale** resource to set the system’s locale on Debian and Windows systems. Windows support was added in Chef Infra Client 16.0 **New in Chef Infra Client 14.5.** Syntax ------ --- The full syntax for all of the properties that are available to the **locale** resource is: ``` locale 'name' do lang String lc_env Hash # default value: {} action Symbol # defaults to :update if not specified end ``` where: * `locale` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `lang` and `lc_env` are the properties available to this resource. Actions ------- --- The **locale** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:update` Update the system’s locale. (default) Properties ---------- --- The **locale** resource has the following properties: `lang` **Ruby Type:** String Sets the default system language. `lc_env` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of LC_* env variables in the form of `({ 'LC_ENV_VARIABLE' => 'VALUE' })`. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **locale** resource in recipes: Set the lang to ‘en_US.UTF-8’ ``` locale 'set system locale' do lang 'en_US.UTF-8' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/locale/macos_userdefaults Resource ============================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [macos_userdefaults.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/macos_userdefaults.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **macos_userdefaults** resource to manage the macOS user defaults system. The properties of this resource are passed to the defaults command, and the parameters follow the convention of that command. See the defaults(1) man page for details on how the tool works. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **macos_userdefaults** resource is: ``` macos_userdefaults 'name' do domain String # default value: NSGlobalDomain: the global domain. host String, Symbol key String user String, Symbol value Integer, Float, String, true, false, Hash, Array action Symbol # defaults to :write if not specified end ``` where: * `macos_userdefaults` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `domain`, `host`, `key`, `user`, and `value` are the properties available to this resource. Actions ------- --- The **macos_userdefaults** resource has the following actions: `:delete` Delete a key from a domain. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:write` Write the value to the specified domain/key. (default) Properties ---------- --- The **macos_userdefaults** resource has the following properties: `domain` **Ruby Type:** String | **Default Value:** `NSGlobalDomain: the global domain.` The domain that the user defaults belong to. `host` **Ruby Type:** String, Symbol Set either :current, :all or a hostname to set the user default at the host level. New in Chef Infra Client 16.3 `key` **Ruby Type:** String | `REQUIRED` The preference key. `user` **Ruby Type:** String, Symbol The system user that the default will be applied to. Set :current for current user, :all for all users or pass a valid username `value` **Ruby Type:** Integer, Float, String, true, false, Hash, Array | `REQUIRED` The value of the key. Note With the `type` property set to `bool`, `String` forms of Boolean true/false values that Apple accepts in the defaults command will be coerced: 0/1, ‘TRUE’/‘FALSE,’ ‘true’/false', ‘YES’/‘NO’, or ‘yes’/‘no’. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **macos_userdefaults** resource in recipes: **Specify a global domain value** ``` macos_userdefaults 'Full keyboard access to all controls' do key 'AppleKeyboardUIMode' value 2 end ``` **Setting a value on a specific domain** ``` macos_userdefaults 'Enable macOS firewall' do domain '/Library/Preferences/com.apple.alf' key 'globalstate' value 1 end ``` **Specifying the type of a key to skip automatic type detection** ``` macos_userdefaults 'Finder expanded save dialogs' do key 'NSNavPanelExpandedStateForSaveMode' value 'TRUE' type 'bool' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/macos_userdefaults/mount Resource ============== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [mount.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/mount.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **mount** resource to manage a mounted file system. Syntax ------ --- The full syntax for all of the properties that are available to the **mount** resource is: ``` mount 'name' do device String device_type String, Symbol # default value: :device domain String dump Integer, false # default value: 0 enabled true, false # default value: false fsck_device String # default value: "-" fstype String # default value: "auto" mount_point String # default value: 'name' unless specified options Array, String # default value: ["defaults"] pass Integer, false # default value: 2 password String supports Array, Hash # default value: { remount: false } username String action Symbol # defaults to :mount if not specified end ``` where: * `mount` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `device`, `device_type`, `domain`, `dump`, `enabled`, `fsck_device`, `fstype`, `mount_point`, `options`, `pass`, `password`, `supports`, and `username` are the properties available to this resource. Actions ------- --- The **mount** resource has the following actions: `:disable` Remove an entry from the file systems table (`fstab`). `:enable` Add an entry to the file systems table (`fstab`). `:mount` Default. Mount a device. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remount` Remount a device. `:umount` Unmount a device. `:unmount` Alias for `:umount` action. Properties ---------- --- The **mount** resource has the following properties: `device` **Ruby Type:** String Required for `:umount` and `:remount` actions (for the purpose of checking the mount command output for presence). The special block device or remote node, a label, or a uuid to be mounted. `device_type` **Ruby Type:** String, Symbol | **Default Value:** `:device` **Allowed Values:** `:device, :label, :uuid` The type of device: :device, :label, or :uuid `domain` **Ruby Type:** String Windows only: Use to specify the domain in which the `username` and `password` are located. `dump` **Ruby Type:** Integer, false | **Default Value:** `0` The dump frequency (in days) used while creating a file systems table (fstab) entry. `enabled` **Ruby Type:** true, false | **Default Value:** `false` Use to specify if a mounted file system is enabled. `fsck_device` **Ruby Type:** String | **Default Value:** `-` Solaris only: The fsck device. `fstype` **Ruby Type:** String | **Default Value:** `auto` The file system type (fstype) of the device. `mount_point` **Ruby Type:** String | **Default Value:** `The resource block's name` The directory (or path) in which the device is to be mounted. Defaults to the name of the resource block if not provided. `options` **Ruby Type:** Array, String | **Default Value:** `["defaults"]` An array or comma separated list of options for the mount. `pass` **Ruby Type:** Integer, false | **Default Value:** `2` The pass number used by the file system check (fsck) command while creating a file systems table (fstab) entry. `password` **Ruby Type:** String Windows only:. Use to specify the password for username. `supports` **Ruby Type:** Array, Hash | **Default Value:** `{ remount: false }` Specify a Hash of supported mount features. `username` **Ruby Type:** String Windows only: Use to specify the user name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **mount** resource in recipes: Mount a labeled file system ``` mount '/mnt/volume1' do device 'volume1' device_type :label fstype 'xfs' options 'rw' end ``` Mount a local block drive ``` mount '/mnt/local' do device '/dev/sdb1' fstype 'ext3' end ``` Mount a non-block file system ``` mount '/mount/tmp' do pass 0 fstype 'tmpfs' device '/dev/null' options 'nr_inodes=999k,mode=755,size=500m' action [:mount, :enable] end ``` Mount and add to the file systems table ``` mount '/export/www' do device 'nas1prod:/export/web_sites' fstype 'nfs' options 'rw' action [:mount, :enable] end ``` Mount a remote file system ``` mount '/export/www' do device 'nas1prod:/export/web_sites' fstype 'nfs' options 'rw' end ``` Mount a remote folder in Microsoft Windows ``` mount 'T:' do action :mount device '\\\\hostname.example.com\\folder' end ``` Unmount a remote folder in Microsoft Windows ``` mount 'T:' do action :umount device '\\\\hostname.example.com\\D$' end ``` Stop a service, do stuff, and then restart it The following example shows how to use the **execute**, **service**, and **mount** resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following: * Checks to see if the Amazon EC2 node has MySQL * If the node has MySQL, stops MySQL * Installs MySQL * Mounts the node * Restarts MySQL ``` # the following code sample comes from the ``server_ec2`` # recipe in the following cookbook: # https://github.com/chef-cookbooks/mysql if (node.attribute?('ec2') && ! FileTest.directory?(node['mysql']['ec2_path'])) service 'mysql' do action :stop end execute 'install-mysql' do command "mv #{node['mysql']['data_dir']}#{node['mysql']['ec2_path']}" not_if do FileTest.directory?(node['mysql']['ec2_path']) end end [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir| directory dir do owner 'mysql' group 'mysql' end end mount node['mysql']['data_dir'] do device node['mysql']['ec2_path'] fstype 'none' options 'bind,rw' action [:mount, :enable] end service 'mysql' do action :start end end ``` where * the two **service** resources are used to stop, and then restart the MySQL service * the **execute** resource is used to install MySQL * the **mount** resource is used to mount the node and enable MySQL © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/mount/log Resource ============ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [log.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/log.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Syntax ------ --- A **log** resource block adds messages to the log file based on events that occur during a Chef Infra Client run: ``` log 'message' do message 'A message add to the log.' level :info end ``` The full syntax for all of the properties that are available to the **log** resource is: ``` log 'name' do level Symbol # default value: :info message String # default value: 'name' unless specified action Symbol # defaults to :write if not specified end ``` where: * `log` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `level` and `message` are the properties available to this resource. Properties ---------- --- The log resource has the following properties: `level` **Ruby Type:** Symbol | **Default Value:** `:info` The logging level for displaying this message. Options (in order of priority): `:debug`, `:info`, `:warn`, `:error`, and `:fatal`. `message` **Ruby Type:** String | **Default Value:** `The resource block's name` The message to be added to a log file. Default value: the `name` of the resource block. See “Syntax” section above for more information. Log Entries ----------- `Chef::Log` will print log entries to the default logger that is configured for the machine on which Chef Infra Client is running. (To create a log entry that is built into the resource collection, use the [log resource](index) instead of `Chef::Log`.) ### Supported Log Levels | Log Level | Syntax | | --- | --- | | Fatal | `Chef::Log.fatal('string')` | | Error | `Chef::Log.error('string')` | | Warn | `Chef::Log.warn('string')` | | Info | `Chef::Log.info('string')` | | Debug | `Chef::Log.debug('string')` | The following example shows a series of fatal `Chef::Log` entries: ``` unless node['splunk']['upgrade_enabled'] Chef::Log.fatal('The chef-splunk::upgrade recipe was added to the node,') Chef::Log.fatal('but the attribute `node["splunk"]["upgrade_enabled"]` was not set.') Chef::Log.fatal('I am bailing here so this node does not upgrade.') raise end service 'splunk_stop' do service_name 'splunk' supports status: true action :stop end if node['splunk']['is_server'] splunk_package = 'splunk' url_type = 'server' else splunk_package = 'splunkforwarder' url_type = 'forwarder' end splunk_installer splunk_package do url node['splunk']['upgrade']["#{url_type}_url"] end if node['splunk']['accept_license'] execute 'splunk-unattended-upgrade' do command "#{splunk_cmd} start --accept-license --answer-yes" end else Chef::Log.fatal('You did not accept the license (set node["splunk"]["accept_license"] to true)') Chef::Log.fatal('Splunk is stopped and cannot be restarted until the license is accepted!') raise end ``` The following example shows using multiple `Chef::Log` entry types: ``` ... begin aws = Chef::DataBagItem.load(:aws, :main) Chef::Log.info("Loaded AWS information from DataBagItem aws[#{aws['id']}]") rescue Chef::Log.fatal("Could not find the 'main' item in the 'aws' data bag") raise end ... ``` Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **log** resource in recipes: Set default logging level ``` log 'a string to log' ``` Set debug logging level ``` log 'a debug string' do level :debug end ``` Add a message to a log file ``` log 'message' do message 'This is the message that will be added to the log.' level :info end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/log/ohai_hint Resource =================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [ohai_hint.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/ohai_hint.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **ohai_hint** resource to aid in configuration detection by passing hint data to Ohai. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **ohai_hint** resource is: ``` ohai_hint 'name' do compile_time true, false # default value: true content Hash hint_name String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `ohai_hint` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `compile_time`, `content`, and `hint_name` are the properties available to this resource. Actions ------- --- The **ohai_hint** resource has the following actions: `:create` Create an Ohai hint file. (default) `:delete` Delete an Ohai hint file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **ohai_hint** resource has the following properties: `compile_time` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the resource is executed during the compile time phase. `content` **Ruby Type:** Hash Values to include in the hint file. `hint_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the hint name if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **ohai_hint** resource in recipes: **Create a hint file** ``` ohai_hint 'example' do content a: 'test_content' end ``` **Create a hint file with a name that does not match the resource name** ``` ohai_hint 'example' do hint_name 'custom' end ``` **Create a hint file that is not loaded at compile time** ``` ohai_hint 'example' do compile_time false end ``` **Delete a hint file** ``` ohai_hint 'example' do action :delete end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/ohai_hint/ohai Resource ============= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [ohai.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/ohai.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **ohai** resource to reload the Ohai configuration on a node. This allows recipes that change system attributes (like a recipe that adds a user) to refer to those attributes later on during the Chef Infra Client run. Syntax ------ --- The full syntax for all of the properties that are available to the **ohai** resource is: ``` ohai 'name' do plugin String action Symbol # defaults to :reload if not specified end ``` where: * `ohai` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `plugin` is the property available to this resource. Actions ------- --- The **ohai** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reload` Reloads the Ohai data. (default) Properties ---------- --- The **ohai** resource has the following properties: `plugin` **Ruby Type:** String Specific Ohai attribute data to reload. This property behaves similar to specifying attributes when running Ohai on the command line and takes the attribute that you wish to reload instead of the actual plugin name. For instance, you can pass `ipaddress` to reload `node['ipaddress']` even though that data comes from the `Network` plugin. If this property is not specified, Chef Infra Client will reload all plugins. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **ohai** resource in recipes: Reload All Ohai Plugins ``` ohai 'reload' do action :reload end ``` Reload A Single Ohai Plugin ``` ohai 'reload' do plugin 'ipaddress' action :reload end ``` Reload Ohai after a new user is created ``` ohai 'reload_passwd' do action :nothing plugin 'etc' end user 'daemon_user' do home '/dev/null' shell '/sbin/nologin' system true notifies :reload, 'ohai[reload_passwd]', :immediately end ruby_block 'just an example' do block do # These variables will now have the new values puts node['etc']['passwd']['daemon_user']['uid'] puts node['etc']['passwd']['daemon_user']['gid'] end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/ohai/openbsd_package Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [openbsd_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/openbsd_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **openbsd_package** resource to manage packages for the OpenBSD platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. Syntax ------ --- A **openbsd_package** resource block manages a package on a node, typically by installing it. The simplest use of the **openbsd_package** resource is: ``` openbsd_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **openbsd_package** resource is: ``` openbsd_package 'name' do options String package_name String source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `openbsd_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **openbsd_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. Properties ---------- --- The **openbsd_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **openbsd_package** resource in recipes: **Install a package** ``` openbsd_package 'name of package' do action :install end ``` **Remove a package** ``` openbsd_package 'name of package' do action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/openbsd_package/notify_group Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [notify_group.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/notify_group.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- The notify_group resource does nothing, and always fires notifications which are set on it. Use it to DRY blocks of notifications that are common to multiple resources, and provide a single target for other resources to notify. Unlike most resources, its default action is :nothing. **New in Chef Infra Client 15.8.** Syntax ------ --- The full syntax for all of the properties that are available to the **notify_group** resource is: ``` notify_group 'name' do action Symbol # defaults to :nothing if not specified end ``` where: * `notify_group` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. Actions ------- --- The **notify_group** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Properties ---------- --- This resource does not have any properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **notify_group** resource in recipes: Wire up a notification from a service resource to stop and start the service with a 60 second delay. ``` service "crude" do action [ :enable, :start ] end chef_sleep "60" do action :nothing end # Example code for a hypothetical badly behaved service that requires # 60 seconds between a stop and start in order to restart the service # (due to race conditions, bleeding connections down, resources that only # slowly unlock in the background, or other poor software behaviors that # are sometimes encountered). # notify_group "crude_stop_and_start" do notifies :stop, "service[crude]", :immediately notifies :sleep, "chef_sleep[60]", :immediately notifies :start, "service[crude]", :immediately end template "/etc/crude/crude.conf" do source "crude.conf.erb" variables node["crude"] notifies :run, "notify_group[crude_stop_and_start]", :immediately end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/notify_group/openssl_ec_private_key Resource ================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [openssl_ec_private_key.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/openssl_ec_private_key.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **openssl_ec_private_key** resource to generate an elliptic curve (EC) private key file. If a valid EC key file can be opened at the specified location, no new file will be created. If the EC key file cannot be opened, either because it does not exist or because the password to the EC key file does not match the password in the recipe, then it will be overwritten. **New in Chef Infra Client 14.4.** Syntax ------ --- The full syntax for all of the properties that are available to the **openssl_ec_private_key** resource is: ``` openssl_ec_private_key 'name' do force true, false # default value: false group String, Integer key_cipher String # default value: "des3" key_curve String # default value: "prime256v1" key_pass String mode Integer, String # default value: "0600" owner String, Integer path String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `openssl_ec_private_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `force`, `group`, `key_cipher`, `key_curve`, `key_pass`, `mode`, `owner`, and `path` are the properties available to this resource. Actions ------- --- The **openssl_ec_private_key** resource has the following actions: `:create` Generate the EC private key file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **openssl_ec_private_key** resource has the following properties: `force` **Ruby Type:** true, false | **Default Value:** `false` Force creation of the key even if the same key already exists on the node. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_cipher` **Ruby Type:** String | **Default Value:** `des3` The designed cipher to use when generating your key. Run `openssl list-cipher-algorithms` to see available options. `key_curve` **Ruby Type:** String | **Default Value:** `prime256v1` **Allowed Values:** `"prime256v1", "secp224r1", "secp256k1", "secp384r1", "secp521r1"` The desired curve of the generated key (if key_type is equal to ‘ec’). Run openssl ecparam -list_curves to see available options. `key_pass` **Ruby Type:** String The desired passphrase for the key. `mode` **Ruby Type:** Integer, String | **Default Value:** `0600` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **openssl_ec_private_key** resource in recipes: **Generate a new ec privatekey with prime256v1 key curve and default des3 cipher** ``` openssl_ec_private_key '/etc/ssl_files/eckey_prime256v1_des3.pem' do key_curve 'prime256v1' key_pass 'something' action :create end ``` **Generate a new ec private key with prime256v1 key curve and aes-128-cbc cipher** ``` openssl_ec_private_key '/etc/ssl_files/eckey_prime256v1_des3.pem' do key_curve 'prime256v1' key_cipher '<KEY>' key_pass 'something' action :create end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/openssl_ec_private_key/openssl_dhparam Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [openssl_dhparam.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/openssl_dhparam.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **openssl_dhparam** resource to generate `dhparam.pem` files. If a valid `dhparam.pem` file is found at the specified location, no new file will be created. If a file is found at the specified location but it is not a valid `dhparam.pem` file, it will be overwritten. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **openssl_dhparam** resource is: ``` openssl_dhparam 'name' do generator Integer # default value: 2 group String, Integer key_length Integer # default value: 2048 mode Integer, String # default value: "0640" owner String, Integer path String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `openssl_dhparam` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `generator`, `group`, `key_length`, `mode`, `owner`, and `path` are the properties available to this resource. Actions ------- --- The **openssl_dhparam** resource has the following actions: `:create` Create the `dhparam.pem` file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **openssl_dhparam** resource has the following properties: `generator` **Ruby Type:** Integer | **Default Value:** `2` **Allowed Values:** `2, 5` The desired Diffie-Hellmann generator. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key. `mode` **Ruby Type:** Integer, String | **Default Value:** `0640` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **openssl_dhparam** resource in recipes: **Create a dhparam file** ``` openssl_dhparam '/etc/httpd/ssl/dhparam.pem' ``` **Create a dhparam file with a specific key length** ``` openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do key_length 4096 end ``` **Create a dhparam file with specific user/group ownership** ``` openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do owner 'www-data' group 'www-data' end ``` **Manually specify the dhparam file path** ``` openssl_dhparam 'httpd_dhparam' do path '/etc/httpd/ssl/dhparam.pem' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/openssl_dhparam/openssl_ec_public_key Resource ================================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [openssl_ec_public_key.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/openssl_ec_public_key.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **openssl_ec_public_key** resource to generate elliptic curve (EC) public key files from a given EC private key. **New in Chef Infra Client 14.4.** Syntax ------ --- The full syntax for all of the properties that are available to the **openssl_ec_public_key** resource is: ``` openssl_ec_public_key 'name' do group String, Integer mode Integer, String # default value: "0640" owner String, Integer path String # default value: 'name' unless specified private_key_content String private_key_pass String private_key_path String action Symbol # defaults to :create if not specified end ``` where: * `openssl_ec_public_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `group`, `mode`, `owner`, `path`, `private_key_content`, `private_key_pass`, and `private_key_path` are the properties available to this resource. Actions ------- --- The **openssl_ec_public_key** resource has the following actions: `:create` Generate the EC public key file from a private key. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **openssl_ec_public_key** resource has the following properties: `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `mode` **Ruby Type:** Integer, String | **Default Value:** `0640` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `private_key_content` **Ruby Type:** String The content of the private key including new lines. This property is used in place of private_key_path in instances where you want to avoid having to first write the private key to disk `private_key_pass` **Ruby Type:** String The passphrase of the provided private key. `private_key_path` **Ruby Type:** String The path to the private key file. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **openssl_ec_public_key** resource in recipes: **Generate new EC public key from a private key on disk** ``` openssl_ec_public_key '/etc/ssl_files/eckey_prime256v1_des3.pub' do private_key_path '/etc/ssl_files/eckey_prime256v1_des3.pem' private_key_pass 'something' action :create end ``` **Generate new EC public key by passing in a private key** ``` openssl_ec_public_key '/etc/ssl_files/eckey_prime256v1_des3_2.pub' do private_key_content "-----BEGIN EC PRIVATE KEY----- <KEY> -----END EC PRIVATE KEY----- " action :create end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/openssl_ec_public_key/openssl_x509_crl Resource =========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [openssl_x509_crl.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/openssl_x509_crl.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **openssl_x509_crl** resource to generate PEM-formatted x509 certificate revocation list (CRL) files. **New in Chef Infra Client 14.4.** Syntax ------ --- The full syntax for all of the properties that are available to the **openssl_x509_crl** resource is: ``` openssl_x509_crl 'name' do ca_cert_file String ca_key_file String ca_key_pass String expire Integer # default value: 8 group String, Integer mode Integer, String owner String, Integer path String # default value: 'name' unless specified renewal_threshold Integer # default value: 1 revocation_reason Integer # default value: 0 serial_to_revoke Integer, String action Symbol # defaults to :create if not specified end ``` where: * `openssl_x509_crl` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ca_cert_file`, `ca_key_file`, `ca_key_pass`, `expire`, `group`, `mode`, `owner`, `path`, `renewal_threshold`, `revocation_reason`, and `serial_to_revoke` are the properties available to this resource. Actions ------- --- The **openssl_x509_crl** resource has the following actions: `:create` Create the certificate revocation list (CRL) file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **openssl_x509_crl** resource has the following properties: `ca_cert_file` **Ruby Type:** String | `REQUIRED` The path to the CA X509 Certificate on the filesystem. If the `ca_cert_file` property is specified, the `ca_key_file` property must also be specified, the CRL will be signed with them. `ca_key_file` **Ruby Type:** String | `REQUIRED` The path to the CA private key on the filesystem. If the `ca_key_file` property is specified, the `ca_cert_file` property must also be specified, the CRL will be signed with them. `ca_key_pass` **Ruby Type:** String The passphrase for CA private key’s passphrase. `expire` **Ruby Type:** Integer | **Default Value:** `8` Value representing the number of days from now through which the issued CRL will remain valid. The CRL will expire after this period. `group` **Ruby Type:** String, Integer The group permission for the CRL file. `mode` **Ruby Type:** Integer, String The permission mode of the CRL file. `owner` **Ruby Type:** String, Integer The owner permission for the CRL file. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `renewal_threshold` **Ruby Type:** Integer | **Default Value:** `1` Number of days before the expiration. It this threshold is reached, the CRL will be renewed. `revocation_reason` **Ruby Type:** Integer | **Default Value:** `0` Reason for the revocation. `serial_to_revoke` **Ruby Type:** Integer, String Serial of the X509 Certificate to revoke. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **openssl_x509_crl** resource in recipes: **Create a certificate revocation file** ``` openssl_x509_crl '/etc/ssl_test/my_ca.crl' do ca_cert_file '/etc/ssl_test/my_ca.crt' ca_key_file '/etc/ssl_test/my_ca.key' end ``` **Create a certificate revocation file for a particular serial** ``` openssl_x509_crl '/etc/ssl_test/my_ca.crl' do ca_cert_file '/etc/ssl_test/my_ca.crt' ca_key_file '/etc/ssl_test/my_ca.key' serial_to_revoke C7BCB6602A2E4251EF4E2827A228CB52BC0CEA2F end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/openssl_x509_crl/openssl_x509_certificate Resource =================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [openssl_x509_certificate.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/openssl_x509_certificate.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **openssl_x509_certificate** resource to generate signed or self-signed, PEM-formatted x509 certificates. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate. If a CA private key and certificate are provided, the certificate will be signed with them. Note This resource was renamed from openssl_x509 to openssl_x509_certificate. The legacy name will continue to function, but cookbook code should be updated for the new resource name. **New in Chef Infra Client 14.4.** Syntax ------ --- The full syntax for all of the properties that are available to the **openssl_x509_certificate** resource is: ``` openssl_x509_certificate 'name' do ca_cert_file String ca_key_file String ca_key_pass String city String common_name String country String csr_file String email String expire Integer # default value: 365 extensions Hash # default value: {} group String, Integer key_curve String # default value: "prime256v1" key_file String key_length Integer # default value: 2048 key_pass String key_type String # default value: "rsa" mode Integer, String org String org_unit String owner String, Integer path String # default value: 'name' unless specified renew_before_expiry Integer state String subject_alt_name Array # default value: [] action Symbol # defaults to :create if not specified end ``` where: * `openssl_x509_certificate` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ca_cert_file`, `ca_key_file`, `ca_key_pass`, `city`, `common_name`, `country`, `csr_file`, `email`, `expire`, `extensions`, `group`, `key_curve`, `key_file`, `key_length`, `key_pass`, `key_type`, `mode`, `org`, `org_unit`, `owner`, `path`, `renew_before_expiry`, `state`, and `subject_alt_name` are the properties available to this resource. Actions ------- --- The **openssl_x509_certificate** resource has the following actions: `:create` Generate a certificate file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **openssl_x509_certificate** resource has the following properties: `ca_cert_file` **Ruby Type:** String The path to the CA X509 Certificate on the filesystem. If the `ca_cert_file` property is specified, the `ca_key_file` property must also be specified, the certificate will be signed with them. `ca_key_file` **Ruby Type:** String The path to the CA private key on the filesystem. If the `ca_key_file` property is specified, the `ca_cert_file` property must also be specified, the certificate will be signed with them. `ca_key_pass` **Ruby Type:** String The passphrase for CA private key’s passphrase. `city` **Ruby Type:** String Value for the `L` certificate field. `common_name` **Ruby Type:** String Value for the `CN` certificate field. `country` **Ruby Type:** String Value for the `C` certificate field. `csr_file` **Ruby Type:** String The path to a X509 Certificate Request (CSR) on the filesystem. If the `csr_file` property is specified, the resource will attempt to source a CSR from this location. If no CSR file is found, the resource will generate a Self-Signed Certificate and the certificate fields must be specified (common_name at last). `email` **Ruby Type:** String Value for the `email` certificate field. `expire` **Ruby Type:** Integer | **Default Value:** `365` Value representing the number of days from now through which the issued certificate cert will remain valid. The certificate will expire after this period. `extensions` **Ruby Type:** Hash | **Default Value:** `{}` Hash of X509 Extensions entries, in format `{ 'keyUsage' => { 'values' => %w( keyEncipherment digitalSignature), 'critical' => true } }`. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_curve` **Ruby Type:** String | **Default Value:** `prime256v1` **Allowed Values:** `"prime256v1", "secp384r1", "secp521r1"` The desired curve of the generated key (if key_type is equal to ‘ec’). Run `openssl ecparam -list_curves` to see available options. `key_file` **Ruby Type:** String The path to a certificate key file on the filesystem. If the key_file property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the key_file property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key (if key_type is equal to ‘rsa’). `key_pass` **Ruby Type:** String The passphrase for an existing key’s passphrase. `key_type` **Ruby Type:** String | **Default Value:** `rsa` **Allowed Values:** `"ec", "rsa"` The desired type of the generated key. `mode` **Ruby Type:** Integer, String The permission mode applied to all files created by the resource. `org` **Ruby Type:** String Value for the `O` certificate field. `org_unit` **Ruby Type:** String Value for the `OU` certificate field. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `renew_before_expiry` **Ruby Type:** Integer The number of days before the expiry. The certificate will be automatically renewed when the value is reached. New in Chef Infra Client 15.7 `state` **Ruby Type:** String Value for the `ST` certificate field. `subject_alt_name` **Ruby Type:** Array | **Default Value:** `[]` Array of Subject Alternative Name entries, in format `DNS:example.com` or `IP:1.2.3.4`. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **openssl_x509_certificate** resource in recipes: Create a simple self-signed certificate file ``` openssl_x509_certificate '/etc/httpd/ssl/mycert.pem' do common_name 'www.f00bar.com' org 'Foo Bar' org_unit 'Lab' country 'US' end ``` Create a certificate using additional options ``` openssl_x509_certificate '/etc/ssl_files/my_signed_cert.crt' do common_name 'www.f00bar.com' ca_key_file '/etc/ssl_files/my_ca.key' ca_cert_file '/etc/ssl_files/my_ca.crt' expire 365 extensions( 'keyUsage' => { 'values' => %w( keyEncipherment digitalSignature), 'critical' => true, }, 'extendedKeyUsage' => { 'values' => %w(serverAuth), 'critical' => false, } ) subject_alt_name ['IP:127.0.0.1', 'DNS:localhost.localdomain'] end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/openssl_x509_certificate/openssl_rsa_private_key Resource =================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [openssl_rsa_private_key.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/openssl_rsa_private_key.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **openssl_rsa_private_key** resource to generate RSA private key files. If a valid RSA key file can be opened at the specified location, no new file will be created. If the RSA key file cannot be opened, either because it does not exist or because the password to the RSA key file does not match the password in the recipe, it will be overwritten. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **openssl_rsa_private_key** resource is: ``` openssl_rsa_private_key 'name' do force true, false # default value: false group String, Integer key_cipher String # default value: "des3" key_length Integer # default value: 2048 key_pass String mode Integer, String # default value: "0600" owner String, Integer path String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `openssl_rsa_private_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `force`, `group`, `key_cipher`, `key_length`, `key_pass`, `mode`, `owner`, and `path` are the properties available to this resource. Actions ------- --- The **openssl_rsa_private_key** resource has the following actions: `:create` Create the RSA private key file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **openssl_rsa_private_key** resource has the following properties: `force` **Ruby Type:** true, false | **Default Value:** `false` Force creation of the key even if the same key already exists on the node. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_cipher` **Ruby Type:** String | **Default Value:** `des3` The designed cipher to use when generating your key. Run `openssl list-cipher-algorithms` to see available options. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key. `key_pass` **Ruby Type:** String The desired passphrase for the key. `mode` **Ruby Type:** Integer, String | **Default Value:** `0600` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **openssl_rsa_private_key** resource in recipes: Generate new 2048bit key with the default des3 cipher ``` openssl_rsa_private_key '/etc/ssl_files/rsakey_des3.pem' do key_length 2048 action :create end ``` Generate new 1024bit key with the aes-128-cbc cipher ``` openssl_rsa_private_key '/etc/ssl_files/rsakey_<KEY>.pem' do key_length 1024 key_cipher '<KEY>' action :create end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/openssl_rsa_private_key/openssl_rsa_public_key Resource ================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [openssl_rsa_public_key.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/openssl_rsa_public_key.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **openssl_rsa_public_key** resource to generate RSA public key files for a given RSA private key. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **openssl_rsa_public_key** resource is: ``` openssl_rsa_public_key 'name' do group String, Integer mode Integer, String # default value: "0640" owner String, Integer path String # default value: 'name' unless specified private_key_content String private_key_pass String private_key_path String action Symbol # defaults to :create if not specified end ``` where: * `openssl_rsa_public_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `group`, `mode`, `owner`, `path`, `private_key_content`, `private_key_pass`, and `private_key_path` are the properties available to this resource. Actions ------- --- The **openssl_rsa_public_key** resource has the following actions: `:create` Create the RSA public key file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **openssl_rsa_public_key** resource has the following properties: `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `mode` **Ruby Type:** Integer, String | **Default Value:** `0640` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to the public key if it differs from the resource block’s name. `private_key_content` **Ruby Type:** String The content of the private key, including new lines. This property is used in place of private_key_path in instances where you want to avoid having to first write the private key to disk. `private_key_pass` **Ruby Type:** String The passphrase of the provided private key. `private_key_path` **Ruby Type:** String The path to the private key file. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **openssl_rsa_public_key** resource in recipes: Generate new public key from a private key on disk ``` openssl_rsa_public_key '/etc/ssl_files/rsakey_des3.pub' do private_key_path '/etc/ssl_files/rsakey_des3.pem' private_key_pass 'something' action :create end ``` Generate new public key by passing in a private key ``` openssl_rsa_public_key '/etc/ssl_files/rsakey_2.pub' do private_key_pass 'something' private_key_content "-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,5EE0AE9A5FE3342E <KEY>jq<KEY> " action :create end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/openssl_rsa_public_key/osx_profile Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [osx_profile.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/osx_profile.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **osx_profile** resource to manage configuration profiles (`.mobileconfig` files) on the macOS platform. The **osx_profile** resource installs profiles by using the uuidgen library to generate a unique `ProfileUUID`, and then using the `profiles` command to install the profile on the system. **New in Chef Infra Client 12.7.** Syntax ------ --- The full syntax for all of the properties that are available to the **osx_profile** resource is: ``` osx_profile 'name' do identifier String profile String, Hash profile_name String # default value: 'name' unless specified action Symbol # defaults to :install if not specified end ``` where: * `osx_profile` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `identifier`, `profile`, and `profile_name` are the properties available to this resource. Actions ------- --- The **osx_profile** resource has the following actions: `:install` Install the specified configuration profile. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove the specified configuration profile. Properties ---------- --- The **osx_profile** resource has the following properties: `identifier` **Ruby Type:** String Use to specify the identifier for the profile, such as `com.company.screensaver`. `profile` **Ruby Type:** String, Hash Use to specify a profile. This may be the name of a profile contained in a cookbook or a Hash that contains the contents of the profile. `profile_name` **Ruby Type:** String | **Default Value:** `The resource block's name` Use to specify the name of the profile, if different from the name of the resource block. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **osx_profile** resource in recipes: **Install a profile from a cookbook file** ``` osx_profile 'com.company.screensaver.mobileconfig' ``` **Install profile from a hash** ``` profile_hash = { 'PayloadIdentifier' => 'com.company.screensaver', 'PayloadRemovalDisallowed' => false, 'PayloadScope' => 'System', 'PayloadType' => 'Configuration', 'PayloadUUID' => '1781fbec-3325-565f-9022-8aa28135c3cc', 'PayloadOrganization' => 'Chef', 'PayloadVersion' => 1, 'PayloadDisplayName' => 'Screensaver Settings', 'PayloadContent' => [ { 'PayloadType' => 'com.apple.ManagedClient.preferences', 'PayloadVersion' => 1, 'PayloadIdentifier' => 'com.company.screensaver', 'PayloadUUID' => '73fc30e0-1e57-0131-c32d-000c2944c108', 'PayloadEnabled' => true, 'PayloadDisplayName' => 'com.apple.screensaver', 'PayloadContent' => { 'com.apple.screensaver' => { 'Forced' => [ { 'mcx_preference_settings' => { 'idleTime' => 0, }, }, ], }, }, }, ], } osx_profile 'Install screensaver profile' do profile profile_hash end ``` **Remove profile using identifier in resource name** ``` osx_profile 'com.company.screensaver' do action :remove end ``` **Remove profile by identifier and user friendly resource name** ``` osx_profile 'Remove screensaver profile' do identifier 'com.company.screensaver' action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/osx_profile/pacman_package Resource ======================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [pacman_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/pacman_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **pacman_package** resource to manage packages (using pacman) on the Arch Linux platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. Syntax ------ --- A **pacman_package** resource block manages a package on a node, typically by installing it. The simplest use of the **pacman_package** resource is: ``` pacman_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **pacman_package** resource is: ``` pacman_package 'name' do options String package_name String source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `pacman_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **pacman_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **pacman_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Examples -------- --- The following examples demonstrate various approaches for using the **pacman_package** resource in recipes: Install a package ``` pacman_package 'name of package' do action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/pacman_package/plist Resource ============== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [plist.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/plist.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **plist** resource to set config values in plist files on macOS systems. **New in Chef Infra Client 16.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **plist** resource is: ``` plist 'name' do encoding String # default value: "binary" entry String group String # default value: "wheel" mode String, Integer owner String # default value: "root" path String # default value: 'name' unless specified value true, false, String, Integer, Float, Hash action Symbol # defaults to :set if not specified end ``` where: * `plist` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `encoding`, `entry`, `group`, `mode`, `owner`, `path`, and `value` are the properties available to this resource. Actions ------- --- The **plist** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set a value in a plist file. (default) Properties ---------- --- The **plist** resource has the following properties: `encoding` **Ruby Type:** String | **Default Value:** `binary` `entry` **Ruby Type:** String `group` **Ruby Type:** String | **Default Value:** `wheel` The group of the plist file. `mode` **Ruby Type:** String, Integer The file mode of the plist file. Ex: ‘644’ `owner` **Ruby Type:** String | **Default Value:** `root` The owner of the plist file. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path on disk to the plist file. `value` **Ruby Type:** true, false, String, Integer, Float, Hash Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **plist** resource in recipes: **Show hidden files in finder**: ``` plist 'show hidden files' do path '/Users/vagrant/Library/Preferences/com.apple.finder.plist' entry 'AppleShowAllFiles' value true end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/plist/powershell_package Resource ============================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [powershell_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/powershell_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **powershell_package** resource to install and manage packages via the PowerShell Package Manager for the Microsoft Windows platform. The **powershell_package** resource requires administrative access, and a source must be configured in the PowerShell Package Manager via the [Register-PackageSource](https://docs.microsoft.com/en-us/powershell/module/packagemanagement/register-packagesource?view=powershell-5.1) command or the [powershell_package_source](../powershell_package_source/index) resource. **New in Chef Infra Client 12.16.** Syntax ------ --- A **powershell_package** resource block manages a package on a node, typically by installing it. The simplest use of the **powershell_package** resource is: ``` powershell_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The powershell_package resource has the following syntax: ``` powershell_package 'name' do options String, Array package_name String, Array skip_publisher_check true, false # default value: false source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `powershell_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `skip_publisher_check`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **powershell_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:remove` Remove a package. Properties ---------- --- The **powershell_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array The name of the package. Default value: the name of the resource block. `skip_publisher_check` **Ruby Type:** true, false | **Default Value:** `false` Skip validating module author. New in Chef Client 14.3 `source` **Ruby Type:** String Specify the source of the package. New in Chef Client 14.0 `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **powershell_package** resource in recipes: Install a specific version of a package: ``` powershell_package 'xCertificate' do action :install version '1.1.0.0' end ``` Install multiple packages: ``` powershell_package 'Install Multiple Packages' do action :install package_name %w(xCertificate xNetworking) end ``` Install a package from a custom source: ``` powershell_package 'xCertificate' do action :install source 'MyGallery' end ``` Install multiple packages, and specify package versions: ``` powershell_package 'Install Multiple Packages' do action :install package_name %w(xCertificate xNetworking) version ['2.0.0.0', '2.12.0.0'] end ``` Install multiple packages, specifying the package version for one package but not the other: ``` powershell_package 'Install Multiple Packages' do action :install package_name %w(xCertificate xNetworking) version [nil, '2.12.0.0'] end ``` In this example, the `nil` tells `powershell_package` to install the most up to date version of `xCertificate` that is available, while pinning `xNetworking` to version 2.12.0.0. Remove a package: ``` powershell_package 'xCertificate' do action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/powershell_package/openssl_x509_request Resource =============================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [openssl_x509_request.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/openssl_x509_request.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **openssl_x509_request** resource to generate PEM-formatted x509 certificates requests. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate. **New in Chef Infra Client 14.4.** Syntax ------ --- The full syntax for all of the properties that are available to the **openssl_x509_request** resource is: ``` openssl_x509_request 'name' do city String common_name String country String email String group String, Integer key_curve String # default value: "prime256v1" key_file String key_length Integer # default value: 2048 key_pass String key_type String # default value: "ec" mode Integer, String org String org_unit String owner String, Integer path String # default value: 'name' unless specified state String action Symbol # defaults to :create if not specified end ``` where: * `openssl_x509_request` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `city`, `common_name`, `country`, `email`, `group`, `key_curve`, `key_file`, `key_length`, `key_pass`, `key_type`, `mode`, `org`, `org_unit`, `owner`, `path`, and `state` are the properties available to this resource. Actions ------- --- The **openssl_x509_request** resource has the following actions: `:create` Generate a certificate request file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **openssl_x509_request** resource has the following properties: `city` **Ruby Type:** String Value for the `L` certificate field. `common_name` **Ruby Type:** String | `REQUIRED` Value for the `CN` certificate field. `country` **Ruby Type:** String Value for the `C` certificate field. `email` **Ruby Type:** String Value for the `email` certificate field. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_curve` **Ruby Type:** String | **Default Value:** `prime256v1` **Allowed Values:** `"prime256v1", "secp384r1", "secp521r1"` The desired curve of the generated key (if key_type is equal to `ec`). Run `openssl ecparam -list_curves` to see available options. `key_file` **Ruby Type:** String The path to a certificate key file on the filesystem. If the `key_file` property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the `key_file` property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key (if key_type is equal to `rsa`). `key_pass` **Ruby Type:** String The passphrase for an existing key’s passphrase. `key_type` **Ruby Type:** String | **Default Value:** `ec` **Allowed Values:** `"ec", "rsa"` The desired type of the generated key. `mode` **Ruby Type:** Integer, String The permission mode applied to all files created by the resource. `org` **Ruby Type:** String Value for the `O` certificate field. `org_unit` **Ruby Type:** String Value for the `OU` certificate field. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `state` **Ruby Type:** String Value for the `ST` certificate field. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **openssl_x509_request** resource in recipes: **Generate new EC key and CSR file** ``` openssl_x509_request '/etc/ssl_files/my_ec_request.csr' do common_name 'myecrequest.example.com' org 'Test Kitchen Example' org_unit 'Kitchens' country 'UK' end ``` **Generate a new CSR file from an existing EC key** ``` openssl_x509_request '/etc/ssl_files/my_ec_request2.csr' do common_name 'myecrequest2.example.com' org 'Test Kitchen Example' org_unit 'Kitchens' country 'UK' key_file '/etc/ssl_files/my_ec_request.key' end ``` **Generate new RSA key and CSR file** ``` openssl_x509_request '/etc/ssl_files/my_rsa_request.csr' do common_name 'myrsarequest.example.com' org 'Test Kitchen Example' org_unit 'Kitchens' country 'UK' key_type 'rsa' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/openssl_x509_request/package Resource ================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **package** resource to manage packages. When the package is installed from a local file (such as with RubyGems, dpkg, or RPM Package Manager), the file must be added to the node using the **remote_file** or **cookbook_file** resources. This resource is the base resource for several other resources used for package management on specific platforms. While it is possible to use each of these specific resources, it is recommended to use the **package** resource as often as possible. For more information about specific resources for specific platforms, see the following topics: * [apt_package](../apt_package/index) * [bff_package](../bff_package/index) * [cab_package](../cab_package/index) * [chef_gem](../chef_gem/index) * [chocolatey_package](../chocolatey_package/index) * [dmg_package](../dmg_package/index) * [dnf_package](../dnf_package/index) * [dpkg_package](../dpkg_package/index) * [freebsd_package](../freebsd_package/index) * [gem_package](../gem_package/index) * [homebrew_package](../homebrew_package/index) * [ips_package](../ips_package/index) * [macports_package](../macports_package/index) * [msu_package](../msu_package/index) * [openbsd_package](../openbsd_package/index) * [pacman_package](../pacman_package/index) * [paludis_package](../paludis_package/index) * [portage_package](../portage_package/index) * [rpm_package](../rpm_package/index) * [smartos_package](../smartos_package/index) * [snap_package](../snap_package/index) * [solaris_package](../solaris_package/index) * [windows_package](../windows_package/index) * [yum_package](../yum_package/index) * [zypper_package](../zypper_package/index) Syntax ------ --- A **package** resource block manages a package on a node, typically by installing it. The simplest use of the **package** resource is: ``` package 'httpd' ``` which will install Apache using all of the default options and the default action (`:install`). For a package that has different package names, depending on the platform, use a `case` statement within the **package**: ``` package 'Install Apache' do case node[:platform] when 'redhat', 'centos' package_name 'httpd' when 'ubuntu', 'debian' package_name 'apache2' end end ``` where: * `'redhat', 'centos'` will install Apache using the `httpd` package and `'ubuntu', 'debian'` will install it using the `apache2` package The full syntax for all of the properties that are available to the **package** resource is: ``` package 'name' do allow_downgrade true, false # Yum, RPM packages only arch String, Array # Yum packages only default_release String # Apt packages only flush_cache Array gem_binary String homebrew_user String, Integer # Homebrew packages only notifies # see description options String package_name String, Array # defaults to 'name' if not specified response_file String # Apt packages only response_file_variables Hash # Apt packages only source String subscribes # see description timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `package` tells Chef Infra Client to manage a package; Chef Infra Client will determine the correct package provider to use based on the platform running on the node * `'name'` is the name of the package * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state * `allow_downgrade`, `arch`, `default_release`, `flush_cache`, `gem_binary`, `homebrew_user`, `options`, `package_name`, `response_file`, `response_file_variables`, `source`, `recursive`, `timeout`, and `version` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Gem Package Options ------------------- The RubyGems package provider attempts to use the RubyGems API to install gems without spawning a new process, whenever possible. A gems command to install will be spawned under the following conditions: * When a `gem_binary` property is specified (as a hash, a string, or by a .gemrc file), Chef Infra Client will run that command to examine its environment settings and then again to install the gem. * When install options are specified as a string, Chef Infra Client will span a gems command with those options when installing the gem. * The Chef installer will search the `PATH` for a gem command rather than defaulting to the current gem environment. As part of `enforce_default_paths`, the `bin` directories area added to the `PATH`, which means when there are no other proceeding RubyGems, the installation will still be operated against it. ### Specify with Hash You should provide the install options as a hash if you are not using an explicit `gem_binary` parameter with the `gem_package` resource. This approach allows the provider to install the gem without needing to spawn an external gem process. The following RubyGems options are available for inclusion within a hash and are passed to the RubyGems DependencyInstaller: * `:env_shebang` * `:force` * `:format_executable` * `:ignore_dependencies` * `:prerelease` * `:security_policy` * `:wrappers` For more information about these options, see the RubyGems documentation: <https://docs.ruby-lang.org/en/2.2.0/Gem/DependencyInstaller.html>. **Example** ``` gem_package 'bundler' do options(prerelease: true, format_executable: false) end ``` ### Specify with String When using an explicit `gem_binary`, options must be passed as a string. When not using an explicit `gem_binary`, Chef Infra Client is forced to spawn a gems process to install the gems (which uses more system resources) when options are passed as a string. String options are passed verbatim to the gems command and should be specified just as if they were passed on a command line. For example, `--prerelease` for a pre-release gem. **Example** ``` gem_package 'nokogiri' do gem_binary('/opt/ree/bin/gem') options('--prerelease --no-format-executable') end ``` ### Specify with .gemrc File Options can be specified in a .gemrc file. By default the `gem_package` resource will use the Ruby interface to install gems which will ignore the .gemrc file. The `gem_package` resource can be forced to use the gems command instead (and to read the .gemrc file) by adding the `gem_binary` attribute to a code block. A template named `gemrc.erb` is located in a cookbook’s `/templates` directory: ``` :sources: - http://<%= node['gem_file']['host'] %>:<%= node['gem_file']['port'] %>/ ``` A recipe can be built that does the following: * Builds a `.gemrc` file based on a `gemrc.erb` template * Runs a `Gem.configuration` command * Installs a package using the `.gemrc` file ``` template '/root/.gemrc' do source 'gemrc.erb' action :create notifies :run, 'ruby_block[refresh_gemrc]', :immediately end ruby_block 'refresh_gemrc' do action :nothing block do Gem.configuration = Gem::ConfigFile.new [] end end gem_package 'di-ruby-lvm' do gem_binary '/opt/chef/embedded/bin/gem' action :install end ``` Actions ------- --- The **package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. (Debian platform only; for other platforms, use the `:remove` action.) `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` **yum_package** resource only. Downgrade a package to satisfy requested version requirements. `arch` **Ruby Type:** String, Array **yum_package** resource only. The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name. `default_release` **Ruby Type:** String **apt_package** resource only. The default release. For example: `stable`. `flush_cache` **Ruby Type:** Array Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Default value: `[ :before, :after ]`. The value may also be a Hash: `( { :before => true/false, :after => true/false } )`. Yum automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while the Chef Infra Client run is in-progress. As an array: ``` yum_package 'some-package' do #... flush_cache [ :before ] #... end ``` and as a Hash: ``` yum_package 'some-package' do #... flush_cache( { :after => true } ) #... end ``` Note The `flush_cache` property does not flush the local Yum cache! Use Yum tools—`yum clean headers`, `yum clean packages`, `yum clean all`—to clean the local Yum cache. `gem_binary` **Ruby Type:** String A property for the `gem_package` provider that is used to specify a gems binary. `homebrew_user` **Ruby Type:** String, Integer **homebrew_package** resource only. The name of the Homebrew owner to be used by Chef Infra Client when executing a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `options` **Ruby Type:** String One (or more) additional options that are passed to the command. `package_name` **Ruby Type:** String, Array The name of the package. Default value: the `name` of the resource block. See “Syntax” section above for more information. `response_file` **Ruby Type:** String **apt_package** and **dpkg_package** resources only. The direct path to the file used to pre-seed a package. `response_file_variables` **Ruby Type:** Hash **apt_package** and **dpkg_package** resources only. A Hash of response file variables in the form of `{"VARIABLE" => "VALUE"}`. `source` **Ruby Type:** String Optional. The path to a package in the local file system. Note The AIX platform requires `source` to be a local file system path because `installp` does not retrieve packages using HTTP or FTP. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Examples -------- --- The following examples demonstrate various approaches for using the **package** resource in recipes: Install a gems file for use in recipes ``` chef_gem 'right_aws' do action :install end require 'right_aws' ``` Install a gems file from the local file system ``` gem_package 'right_aws' do source '/tmp/right_aws-1.11.0.gem' action :install end ``` Install a package ``` package 'tar' do action :install end ``` Install a package version ``` package 'tar' do version '1.16.1-1' action :install end ``` Install a package with options ``` package 'debian-archive-keyring' do action :install options '--force-yes' end ``` Install a package with a response_file Use of a `response_file` is only supported on Debian and Ubuntu at this time. Custom resources must be written to support the use of a `response_file`, which contains debconf answers to questions normally asked by the package manager on installation. Put the file in `/files/default` of the cookbook where the package is specified and Chef Infra Client will use the **cookbook_file** resource to retrieve it. To install a package with a `response_file`: ``` package 'sun-java6-jdk' do response_file 'java.seed' end ``` Install a specified architecture using a named provider ``` yum_package 'glibc-devel' do arch 'i386' end ``` Purge a package ``` package 'tar' do action :purge end ``` Remove a package ``` package 'tar' do action :remove end ``` Upgrade a package ``` package 'tar' do action :upgrade end ``` Use the ignore_failure common attribute ``` gem_package 'syntax' do action :install ignore_failure true end ``` Avoid unnecessary string interpolation Do this: ``` package 'mysql-server' do version node['mysql']['version'] action :install end ``` and not this: ``` package 'mysql-server' do version "#{node['mysql']['version']}" action :install end ``` Install a package in a platform The following example shows how to use the **package** resource to install an application named `app` and ensure that the correct packages are installed for the correct platform: ``` package 'app_name' do action :install end case node[:platform] when 'ubuntu','debian' package 'app_name-doc' do action :install end when 'centos' package 'app_name-html' do action :install end end ``` **Install sudo, then configure /etc/sudoers/ file** The following example shows how to install sudo and then configure the `/etc/sudoers` file: ``` # the following code sample comes from the ``default`` recipe in the ``sudo`` cookbook: https://github.com/chef-cookbooks/sudo package 'sudo' do action :install end if node['authorization']['sudo']['include_sudoers_d'] directory '/etc/sudoers.d' do mode '0755' owner 'root' group 'root' action :create end cookbook_file '/etc/sudoers.d/README' do source 'README' mode '0440' owner 'root' group 'root' action :create end end template '/etc/sudoers' do source 'sudoers.erb' mode '0440' owner 'root' group platform?('freebsd') ? 'wheel' : 'root' variables( :sudoers_groups => node['authorization']['sudo']['groups'], :sudoers_users => node['authorization']['sudo']['users'], :passwordless => node['authorization']['sudo']['passwordless'] ) end ``` where * the **package** resource is used to install sudo * the `if` statement is used to ensure availability of the `/etc/sudoers.d` directory * the **template** resource tells Chef Infra Client where to find the `sudoers` template * the `variables` property is a hash that passes values to template files (that are located in the `templates/` directory for the cookbook Use a case statement to specify the platform The following example shows how to use a case statement to tell Chef Infra Client which platforms and packages to install using cURL. ``` package 'curl' case node[:platform] when 'redhat', 'centos' package 'package_1' package 'package_2' package 'package_3' when 'ubuntu', 'debian' package 'package_a' package 'package_b' package 'package_c' end end ``` where `node[:platform]` for each node is identified by Ohai during every Chef Infra Client run. For example: ``` package 'curl' case node[:platform] when 'redhat', 'centos' package 'zlib-devel' package 'openssl-devel' package 'libc6-dev' when 'ubuntu', 'debian' package 'openssl' package 'pkg-config' package 'subversion' end end ``` Use symbols to reference attributes Symbols may be used to reference attributes: ``` package 'mysql-server' do version node[:mysql][:version] action :install end ``` instead of strings: ``` package 'mysql-server' do version node['mysql']['version'] action :install end ``` Use a whitespace array to simplify a recipe The following examples show different ways of doing the same thing. The first shows a series of packages that will be upgraded: ``` package 'package-a' do action :upgrade end package 'package-b' do action :upgrade end package 'package-c' do action :upgrade end package 'package-d' do action :upgrade end ``` and the next uses a single **package** resource and a whitespace array (`%w`): ``` package %w{package-a package-b package-c package-d} do action :upgrade end ``` Specify the Homebrew user with a UUID ``` homebrew_package 'emacs' do homebrew_user 1001 end ``` Specify the Homebrew user with a string ``` homebrew_package 'vim' do homebrew_user 'user1' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/package/portage_package Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [portage_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/portage_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **portage_package** resource to manage packages for the Gentoo platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. Syntax ------ --- The full syntax for all of the properties that are available to the **portage_package** resource is: ``` portage_package 'name' do options String package_name String source String timeout String, Integer # default value: 3600 version String action Symbol # defaults to :install if not specified end ``` where: * `portage_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **portage_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **portage_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer | **Default Value:** `3600` The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **portage_package** resource in recipes: Install a package ``` portage_package 'name of package' do action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/portage_package/powershell_script Resource =========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [powershell_script.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/powershell_script.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **powershell_script** resource to execute a script using the Windows PowerShell interpreter, much like how the script and script-based resources **bash**, **csh**, **perl**, **python**, and **ruby** are used. The powershell_script is specific to the Microsoft Windows platform, but may use both the the Windows PowerShell interpreter or the PowerShell Core (pwsh) interpreter as of Chef Infra Client 16.6 and later. The powershell_script resource creates and executes a temporary file rather than running the command inline. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` conditionals to guard this resource for idempotence. Syntax ------ --- A **powershell_script** resource block executes a batch script using the Windows PowerShell interpreter. For example, writing to an interpolated path: ``` powershell_script 'write-to-interpolated-path' do code <<-EOH $stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt" $stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.") $stream.close() EOH end ``` The full syntax for all of the properties that are available to the **powershell_script** resource is: ``` powershell_script 'name' do code String command String, Array # default value: 'name' unless specified convert_boolean_return true, false # default value: false creates String cwd String domain String elevated true, false # default value: false environment Hash flags String group String, Integer input String interpreter String # default value: "powershell" live_stream true, false # default value: false password String returns Integer, Array # default value: 0 timeout Integer, String, Float # default value: 3600 user String, Integer action Symbol # defaults to :run if not specified end ``` where: * `powershell_script` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `command`, `convert_boolean_return`, `creates`, `cwd`, `domain`, `elevated`, `environment`, `flags`, `group`, `input`, `interpreter`, `live_stream`, `password`, `returns`, `timeout`, and `user` are the properties available to this resource. Actions ------- --- The **powershell_script** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run the script. Properties ---------- --- The **powershell_script** resource has the following properties: `architecture` **Ruby Type:** Symbol The architecture of the process under which a script is executed. If a value is not provided, Chef Infra Client defaults to the correct value for the architecture, as determined by Ohai. An exception is raised when anything other than `:i386` is specified for a 32-bit process. Possible values: `:i386` (for 32-bit processes) and `:x86_64` (for 64-bit processes). `code` **Ruby Type:** String | `REQUIRED` A quoted string of code to be executed. `command` **Ruby Type:** String, Array | **Default Value:** `The resource block's name` An optional property to set the command to be executed if it differs from the resource block’s name. `convert_boolean_return` **Ruby Type:** true, false | **Default Value:** `false` Return `0` if the last line of a command is evaluated to be true or to return `1` if the last line is evaluated to be false. When the `guard_interpreter` common attribute is set to `:powershell_script`, a string command will be evaluated as if this value were set to `true`. This is because the behavior of this attribute is similar to the value of the `"$?"` expression common in UNIX interpreters. For example, this: ``` powershell_script 'make_safe_backup' do guard_interpreter :powershell_script code 'cp ~/data/nodes.json ~/data/nodes.bak' not_if 'test-path ~/data/nodes.bak' end ``` is similar to: ``` bash 'make_safe_backup' do code 'cp ~/data/nodes.json ~/data/nodes.bak' not_if 'test -e ~/data/nodes.bak' end ``` `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `domain` **Ruby Type:** String The domain of the username specified by the user property. If not specified, the username and password specified by the `user` and `password` properties will be used to resolve that user against the domain in which the system running Chef Infra Client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. New in Chef Client 12.21 `elevated` **Ruby Type:** true, false | **Default Value:** `false` Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) from interactively blocking the process. This will cause the process to be run under a batch login instead of an interactive login. The user running chef-client needs the ‘Replace a process level token’ and ‘Adjust Memory Quotas for a process’ permissions. The user that is running the command needs the ‘Log on as a batch job’ permission. Because this requires a login, the user and password properties are required. New in Chef Client 13.3 `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String A string that is passed to the Windows PowerShell command. Default value (Windows PowerShell 3.0+): `-NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy Bypass, -InputFormat None`. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `guard_interpreter` **Ruby Type:** Symbol | **Default Value:** `:powershell_script` When this property is set to `:powershell_script`, the 64-bit version of the Windows PowerShell shell will be used to evaluate strings values for the `not_if` and `only_if` properties. Set this value to `:default` to use the 32-bit version of the cmd.exe shell. `input` **Ruby Type:** String An optional property to set the input sent to the command as STDIN. New in Chef Infra Client 16.2 `interpreter` **Ruby Type:** String | **Default Value:** `powershell` **Allowed Values:** `"powershell", "pwsh"` The interpreter type, `powershell` or `pwsh` (PowerShell Core) `live_stream` **Ruby Type:** true, false | **Default Value:** `false` Send the output of the command run by this execute resource block to the Chef Infra Client event stream. `password` **Ruby Type:** String The password of the user specified by the user property. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. New in Chef Client 12.21 `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. `domain\user` or `user@my.dns.domain.com` via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain property. On Windows only, if this property is specified, the password property must be specified. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **powershell_script** resource in recipes: Write to an interpolated path ``` powershell_script 'write-to-interpolated-path' do code <<-EOH $stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt" $stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.") $stream.close() EOH end ``` Change the working directory ``` powershell_script 'cwd-then-write' do cwd Chef::Config[:file_cache_path] code <<-EOH $stream = [System.IO.StreamWriter] "C:/powershell-test2.txt" $pwd = pwd $stream.WriteLine("This is the contents of: $pwd") $dirs = dir foreach ($dir in $dirs) { $stream.WriteLine($dir.fullname) } $stream.close() EOH end ``` Change the working directory in Microsoft Windows ``` powershell_script 'cwd-to-win-env-var' do cwd '%TEMP%' code <<-EOH $stream = [System.IO.StreamWriter] "./temp-write-from-chef.txt" $stream.WriteLine("chef on windows rox yo!") $stream.close() EOH end ``` Pass an environment variable to a script ``` powershell_script 'read-env-var' do cwd Chef::Config[:file_cache_path] environment ({'foo' => 'BAZ'}) code <<-EOH $stream = [System.IO.StreamWriter] "./test-read-env-var.txt" $stream.WriteLine("FOO is $env:foo") $stream.close() EOH end ``` **Evaluate for true and/or false** Use the `convert_boolean_return` attribute to raise an exception when certain conditions are met. For example, the following fragments will run successfully without error: ``` powershell_script 'false' do code '$false' end ``` and: ``` powershell_script 'true' do code '$true' end ``` whereas the following will raise an exception: ``` powershell_script 'false' do convert_boolean_return true code '$false' end ``` Use the flags attribute ``` powershell_script 'Install IIS' do code <<-EOH Import-Module ServerManager Add-WindowsFeature Web-Server EOH flags '-NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy Unrestricted, -InputFormat None, -File' guard_interpreter :powershell_script not_if '(Get-WindowsFeature -Name Web-Server).Installed' end ``` Rename computer, join domain, reboot The following example shows how to rename a computer, join a domain, and then reboot the computer: ``` reboot 'Restart Computer' do action :nothing end powershell_script 'Rename and Join Domain' do code <<-EOH ...your rename and domain join logic here... EOH not_if <<-EOH $ComputerSystem = gwmi win32_computersystem ($ComputerSystem.Name -like '#{node['some_attribute_that_has_the_new_name']}') -and $ComputerSystem.partofdomain) EOH notifies :reboot_now, 'reboot[Restart Computer]', :immediately end ``` where: * The **powershell_script** resource block renames a computer, and then joins a domain * The **reboot** resource restarts the computer * The `not_if` guard prevents the Windows PowerShell script from running when the settings in the `not_if` guard match the desired state * The `notifies` statement tells the **reboot** resource block to run if the **powershell_script** block was executed during a Chef Infra Client run Run a command as an alternate user *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] domain "domain" user "username" password "password" end # Passing username = 'domain-name\\username'. No domain is passed powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "domain-name\\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end # Work around User Access Control (UAC) powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" elevated true end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/powershell_script/perl Resource ============= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [perl.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/perl.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **perl** resource to execute scripts using the Perl interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. Syntax ------ --- A **perl** resource block executes scripts Perl: ``` perl 'hello world' do code <<-EOH print "Hello world! From Chef and Perl."; EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **perl** resource is: ``` perl 'name' do code String creates String cwd String environment Hash flags String group String, Integer notifies # see description path Array returns Integer, Array subscribes # see description timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `perl` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **perl** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. Properties ---------- --- The **perl** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/perl/paludis_package Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [paludis_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/paludis_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **paludis_package** resource to manage packages for the Paludis platform. Syntax ------ --- A **paludis_package** resource block manages a package on a node, typically by installing it. The simplest use of the **paludis_package** resource is: ``` paludis_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **paludis_package** resource is: ``` paludis_package 'name' do options String package_name String source String timeout Integer # default value: 3600 version String action Symbol # defaults to :install if not specified end ``` where: * `paludis_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **paludis_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **paludis_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer | **Default Value:** `3600` The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **paludis_package** resource in recipes: Install a package ``` paludis_package 'name of package' do action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/paludis_package/powershell_package_source Resource ==================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [powershell_package_source.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/powershell_package_source.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **powershell_package_source** resource to register a PowerShell package source and a Powershell package provider. There are two distinct objects we care about here. The first is a package source like a PowerShell repository or a NuGet Source. The second object is a provider that PowerShell uses to get to that source with, like PowerShellGet, NuGet, Chocolatey, etc. **New in Chef Infra Client 14.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **powershell_package_source** resource is: ``` powershell_package_source 'name' do new_name String password String provider_name String # default value: "NuGet" publish_location String script_publish_location String script_source_location String source_location String source_name String # default value: 'name' unless specified trusted true, false # default value: false user String action Symbol # defaults to :register if not specified end ``` where: * `powershell_package_source` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `new_name`, `password`, `provider_name`, `publish_location`, `script_publish_location`, `script_source_location`, `source_location`, `source_name`, `trusted`, and `user` are the properties available to this resource. Actions ------- --- The **powershell_package_source** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:register` Registers a PowerShell package source. (default) `:set` Updates an existing PowerShell repository or package source. `:unregister` Unregisters the PowerShell package source. Properties ---------- --- The **powershell_package_source** resource has the following properties: `new_name` **Ruby Type:** String Used to change the name of a standard package source. New in Chef Infra Client 17.6 `password` **Ruby Type:** String A password that, as part of a credential object, is used to register a repository or other package source with. New in Chef Infra Client 17.6 `provider_name` **Ruby Type:** String | **Default Value:** `NuGet` **Allowed Values:** `"NuGet", "PowerShellGet", "Programs", "chocolatey", "msi", "msu", "psl", "winget"` The package management provider for the package source. The default is `PowerShellGet`. Only change this option in specific use cases. `publish_location` **Ruby Type:** String The URL where modules will be published to. Only valid if the provider is `PowerShellGet`. `script_publish_location` **Ruby Type:** String The location where scripts will be published to for this source. Only valid if the provider is `PowerShellGet`. `script_source_location` **Ruby Type:** String The URL where scripts are located for this source. Only valid if the provider is `PowerShellGet`. `source_location` **Ruby Type:** String The URL to the location to retrieve modules from. New in Chef Infra Client 17.6 `source_name` **Ruby Type:** String | **Default Value:** `The resource block's name` A label that names your package source. `trusted` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to trust packages from this source. Used when creating a non-PowerShell repository package source. `user` **Ruby Type:** String A username that, as part of a credential object, is used to register a repository or other package source with. New in Chef Infra Client 17.6 Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **powershell_package_source** resource in recipes: **Add a new PowerShell repository that is not trusted and which requires credentials to connect to**: ``` powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted false user "<EMAIL>" password "my_password" provider_name "PSRepository" action :register end ``` **Add a new package source that uses Chocolatey as the package provider**: ``` powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted true provider_name "chocolatey" action :register end ``` **Add a new PowerShell script source that is trusted**: ``` powershell_package_source 'MyDodgyScript' do source_name "MyDodgyScript" script_source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" script_publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted true action :register end ``` **Update an existing PowerShell repository to make it trusted**: ``` powershell_package_source 'MyPSModule' do source_name "MyPSModule" trusted true action :set end ``` **Update a Nuget package source with a new name and make it trusted**: ``` powershell_package_source 'PowerShellModules -> GoldFishBowl' do source_name "PowerShellModules" new_name "GoldFishBowl" provider_name "Nuget" trusted true action :set end ``` **Update a Nuget package source with a new name when the source is secured with a username and password**: ``` powershell_package_source 'PowerShellModules -> GoldFishBowl' do source_name "PowerShellModules" new_name "GoldFishBowl" trusted true user "<EMAIL>" password "some_secret_password" action :set end ``` **Unregister a package source**: ``` powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" action :unregister end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/powershell_package_source/python Resource =============== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [python.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/python.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **python** resource to execute scripts using the Python interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. Syntax ------ --- The python resource has the following syntax: ``` python 'hello world' do code <<-EOH print "Hello world! From Chef and Python." EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **python** resource is: ``` python 'name' do code String command String # default value: 'name' unless specified creates String cwd String default_env true, false # default value: false domain String elevated true, false # default value: false environment Hash flags String group String, Integer interpreter String live_stream true, false # default value: false password String returns Integer, Array # default value: 0 sensitive true, false # default value: "True if the password property is set. False otherwise." timeout Integer, Float umask String, Integer user String, Integer action Symbol # defaults to :run if not specified end ``` where: * `python` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `command`, `creates`, `cwd`, `default_env`, `domain`, `elevated`, `environment`, `flags`, `group`, `interpreter`, `live_stream`, `password`, `returns`, `timeout`, and `user` are the properties available to this resource. Actions ------- --- The **python** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a script. Properties ---------- --- The **python** resource has the following properties: `code` **Ruby Type:** String | `REQUIRED` A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. `user` **Ruby Type:** String, Integer The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. `domain\user` or `<EMAIL>` via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain property. On Windows only, if this property is specified, the password property must be specified. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/python/reboot Resource =============== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [reboot.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/reboot.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **reboot** resource to reboot a node, a necessary step with some installations on certain platforms. This resource is supported for use on the Microsoft Windows, macOS, and Linux platforms. In using this resource via notifications, it’s important to *only* use immediate notifications. Delayed notifications produce unintuitive and probably undesired results. **New in Chef Infra Client 12.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **reboot** resource is: ``` reboot 'name' do delay_mins Integer # default value: 0 reason String # default value: "Reboot by Chef Infra Client" action Symbol # defaults to :nothing if not specified end ``` where: * `reboot` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `delay_mins` and `reason` are the properties available to this resource. Actions ------- --- The **reboot** resource has the following actions: `:cancel` Cancel a pending reboot request. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reboot_now` Reboot a node so that the Chef Infra Client may continue the installation process. `:request_reboot` Reboot a node at the end of a Chef Infra Client run. Properties ---------- --- The **reboot** resource has the following properties: `delay_mins` **Ruby Type:** Integer | **Default Value:** `0` The amount of time (in minutes) to delay a reboot request. `reason` **Ruby Type:** String | **Default Value:** `Reboot by Chef Infra Client` A string that describes the reboot action. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **reboot** resource in recipes: **Reboot a node immediately** ``` reboot 'now' do action :nothing reason 'Cannot continue Chef run without a reboot.' delay_mins 2 end execute 'foo' do command '...' notifies :reboot_now, 'reboot[now]', :immediately end ``` **Reboot a node at the end of a Chef Infra Client run** ``` reboot 'app_requires_reboot' do action :request_reboot reason 'Need to reboot when the run completes successfully.' delay_mins 5 end ``` **Cancel a reboot** ``` reboot 'cancel_reboot_request' do action :cancel reason 'Cancel a previous end-of-run reboot request.' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/reboot/registry_key Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [registry_key.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/registry_key.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **registry_key** resource to create and delete registry keys in Microsoft Windows. Note 64-bit versions of Microsoft Windows have a 32-bit compatibility layer in the registry that reflects and redirects certain keys (and their values) into specific locations (or logical views) of the registry hive. Chef Infra Client can access any reflected or redirected registry key. The machine architecture of the system on which Chef Infra Client is running is used as the default (non-redirected) location. Access to the SysWow64 location is redirected must be specified. Typically, this is only necessary to ensure compatibility with 32-bit applications that are running on a 64-bit operating system. For more information, see: [Registry Reflection](https://docs.microsoft.com/en-us/windows/win32/winprog64/registry-reflection). Syntax ------ --- A **registry_key** resource block creates and deletes registry keys in Microsoft Windows: ``` registry_key 'HKEY_LOCAL_MACHINE\\...\\System' do values [{ name: 'NewRegistryKeyValue', type: :multi_string, data: %w(foo bar baz), }] action :create end ``` Use multiple registry key entries with key values that are based on node attributes: ``` registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\name_of_registry_key' do values [{name: 'key_name', type: :string, data: 'C:\Windows\System32\file_name.bmp'}, {name: 'key_name', type: :string, data: node['node_name']['attribute']['value']}, {name: 'key_name', type: :string, data: node['node_name']['attribute']['value']} ] action :create end ``` The registry_key resource has the following syntax: ``` registry_key 'name' do architecture Symbol # default value: :machine key String # default value: 'name' unless specified recursive true, false # default value: false values action Symbol # defaults to :create if not specified end ``` where: * `registry_key` is the resource * `name` is the name of the resource block * `values` is a hash that contains at least one registry key to be created or deleted. Each registry key in the hash is grouped by brackets in which the `name:`, `type:`, and `data:` values for that registry key are specified. * `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. Warning `:multi_string` must be an array, even if there is only a single string. * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `architecture`, `key`, `recursive` and `values` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Registry Key Path Separators A Microsoft Windows registry key can be used as a string in Ruby code, such as when a registry key is used as the name of a recipe. In Ruby, when a registry key is enclosed in a double-quoted string (`" "`), the same backslash character (`\`) that is used to define the registry key path separator is also used in Ruby to define an escape character. Therefore, the registry key path separators must be escaped when they are enclosed in a double-quoted string. For example, the following registry key: ``` HKCU\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Themes ``` may be enclosed in a single-quoted string with a single backslash: ``` 'HKCU\SOFTWARE\path\to\key\Themes' ``` or may be enclosed in a double-quoted string with an extra backslash as an escape character: ``` "HKCU\\SOFTWARE\\path\\to\\key\\Themes" ``` ### Chef Infra Language Methods Six methods are present in the Chef Infra Language to help verify the registry during a Chef Infra Client run on the Microsoft Windows platform—`registry_data_exists?`, `registry_get_subkeys`, `registry_get_values`, `registry_has_subkeys?`, `registry_key_exists?`, and `registry_value_exists?`—these helpers ensure the **powershell_script** resource is idempotent. #### registry_data_exists? Use the `registry_data_exists?` method to find out if a Microsoft Windows registry key contains the specified data of the specified type under the value. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_data_exists?` method is as follows: ``` registry_data_exists?( KEY_PATH, { name: 'NAME', type: TYPE, data: DATA }, ARCHITECTURE ) ``` where: * `KEY_PATH` is the path to the registry key value. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `{ name: 'NAME', type: TYPE, data: DATA }` is a hash that contains the expected name, type, and data of the registry key value * `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. #### registry_get_subkeys Use the `registry_get_subkeys` method to get a list of registry key values that are present for a Microsoft Windows registry key. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_get_subkeys` method is as follows: ``` subkey_array = registry_get_subkeys(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This returns an array of registry key values. #### registry_get_values Use the `registry_get_values` method to get the registry key values (name, type, and data) for a Microsoft Windows registry key. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_get_values` method is as follows: ``` subkey_array = registry_get_values(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This returns an array of registry key values. #### registry_has_subkeys? Use the `registry_has_subkeys?` method to find out if a Microsoft Windows registry key has one (or more) values. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_has_subkeys?` method is as follows: ``` registry_has_subkeys?(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. #### registry_key_exists? Use the `registry_key_exists?` method to find out if a Microsoft Windows registry key exists at the specified path. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_key_exists?` method is as follows: ``` registry_key_exists?(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. (Any registry key values that are associated with this registry key are ignored.) #### registry_value_exists? Use the `registry_value_exists?` method to find out if a registry key value exists. Use `registry_data_exists?` to test for the type and data of a registry key value. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_dvalue_exists?` method is as follows: ``` registry_value_exists?( KEY_PATH, { name: 'NAME' }, ARCHITECTURE ) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `{ name: 'NAME' }` is a hash that contains the name of the registry key value; if either `type:` or `:value` are specified in the hash, they are ignored * `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. Actions ------- --- The **registry_key** resource has the following actions: `:create` Default. Create a registry key. If a registry key already exists (but does not match), update that registry key to match. `:create_if_missing` Create a registry key if it does not exist. Also, create a registry key value if it does not exist. `:delete` Delete the specified values for a registry key. `:delete_key` Delete the specified registry key and all of its subkeys. The `:delete_key` action with the `recursive` attribute will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **registry_key** resource has the following properties: `architecture` **Ruby Type:** Symbol | **Default Value:** `:machine` **Allowed Values:** `:i386, :machine, :x86_64` The architecture of the node for which keys are to be created or deleted. Possible values: `:i386` (for nodes with a 32-bit registry), `:x86_64` (for nodes with a 64-bit registry), and `:machine` (to have Chef Infra Client determine the architecture during a Chef Infra Client run). In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the `architecture` property must be set to `:i386`. The `:x86_64` value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (`:machine`) because Chef Infra Client returns an exception if `:x86_64` is used and the machine turns out to be a 32-bit machine (whereas with `:machine`, Chef Infra Client is able to access the registry key on the 32-bit machine). `key` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to the location in which a registry key is to be created or from which a registry key is to be deleted. Default value: the `name` of the resource block. See “Syntax” section above for more information. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. `recursive` **Ruby Type:** true, false | **Default Value:** `false` When creating a key, this value specifies that the required keys for the specified path are to be created. When using the `:delete_key` action in a recipe, and if the registry key has subkeys, then set the value for this property to `true`. The `:delete_key` action with the `recursive` attribute will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client. `values` **Ruby Type:** Hash, Array An array of hashes, where each Hash contains the values that are to be set under a registry key. Each Hash must contain `name:`, `type:`, and `data:` (and must contain no other key values). `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. Warning `:multi_string` must be an array, even if there is only a single string. Examples -------- --- The following examples demonstrate various approaches for using the **registry_key** resource in recipes: Create a registry key Use a double-quoted string: ``` registry_key "HKEY_LOCAL_MACHINE\\path-to-key\\Policies\\System" do values [{ name: 'EnableLUA', type: :dword, data: 0 }] action :create end ``` or a single-quoted string: ``` registry_key 'HKEY_LOCAL_MACHINE\path-to-key\Policies\System' do values [{ name: 'EnableLUA', type: :dword, data: 0 }] action :create end ``` Delete a registry key value Use a double-quoted string: ``` registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\path\\to\\key\\AU" do values [{ name: 'NoAutoRebootWithLoggedOnUsers', type: :dword, data: '' }] action :delete end ``` or a single-quoted string: ``` registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\path\to\key\AU' do values [{ name: 'NoAutoRebootWithLoggedOnUsers', type: :dword, data: '' }] action :delete end ``` Note If `data:` is not specified, you get an error: `Missing data key in RegistryKey values hash` Delete a registry key and its subkeys, recursively Use a double-quoted string: ``` registry_key "HKCU\\SOFTWARE\\Policies\\path\\to\\key\\Themes" do recursive true action :delete_key end ``` or a single-quoted string: ``` registry_key 'HKCU\SOFTWARE\Policies\path\to\key\Themes' do recursive true action :delete_key end ``` Note Be careful when using the `:delete_key` action with the `recursive` attribute. This will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client. Use re-directed keys In 64-bit versions of Microsoft Windows, `HKEY_LOCAL_MACHINE\SOFTWARE\Example` is a re-directed key. In the following examples, because `HKEY_LOCAL_MACHINE\SOFTWARE\Example` is a 32-bit key, the output will be “Found 32-bit key” if they are run on a version of Microsoft Windows that is 64-bit: ``` registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\Example" do architecture :i386 recursive true action :create end ``` or: ``` registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\Example" do architecture :x86_64 recursive true action :delete_key end ``` or: ``` ruby_block 'check 32-bit' do block do puts 'Found 32-bit key' end only_if { registry_key_exists?("HKEY_LOCAL_MACHINE\SOFTWARE\\Example", :i386) } end ``` or: ``` ruby_block 'check 64-bit' do block do puts 'Found 64-bit key' end only_if { registry_key_exists?("HKEY_LOCAL_MACHINE\\SOFTWARE\\Example", :x86_64) } end ``` Set proxy settings to be the same as those used by Chef Infra Client Use a double-quoted string: ``` proxy = URI.parse(Chef::Config[:http_proxy]) registry_key 'HKCU\Software\Microsoft\path\to\key\Internet Settings' do values [{name: 'ProxyEnable', type: :reg_dword, data: 1}, {name: 'ProxyServer', data: "#{proxy.host}:#{proxy.port}"}, {name: 'ProxyOverride', type: :reg_string, data: <local>}, ] action :create end ``` or a single-quoted string: ``` proxy = URI.parse(Chef::Config[:http_proxy]) registry_key 'HKCU\Software\Microsoft\path\to\key\Internet Settings' do values [{name: 'ProxyEnable', type: :reg_dword, data: 1}, {name: 'ProxyServer', data: "#{proxy.host}:#{proxy.port}"}, {name: 'ProxyOverride', type: :reg_string, data: <local>}, ] action :create end ``` **Set the name of a registry key to “(Default)"** Use a double-quoted string: ``` registry_key 'Set (Default) value' do key "HKLM\\Software\\Test\\Key\\Path" values [ {name: '', type: :string, data: 'test'}, ] action :create end ``` or a single-quoted string: ``` registry_key 'Set (Default) value' do key 'HKLM\Software\Test\Key\Path' values [ {name: '', type: :string, data: 'test'}, ] action :create end ``` where `name: ''` contains an empty string, which will set the name of the registry key to `(Default)`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/registry_key/rhsm_errata Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [rhsm_errata.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/rhsm_errata.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **rhsm_errata** resource to install packages associated with a given Red Hat Subscription Manager Errata ID. This is helpful if packages to mitigate a single vulnerability must be installed on your hosts. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **rhsm_errata** resource is: ``` rhsm_errata 'name' do errata_id String # default value: 'name' unless specified action Symbol # defaults to :install if not specified end ``` where: * `rhsm_errata` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `errata_id` is the property available to this resource. Actions ------- --- The **rhsm_errata** resource has the following actions: `:install` Install a package for a specific errata ID. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **rhsm_errata** resource has the following properties: `errata_id` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the errata ID if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **rhsm_errata** resource in recipes: **Install a package from an Errata ID** ``` rhsm_errata 'RHSA:2018-1234' ``` **Specify an Errata ID that differs from the resource name** ``` rhsm_errata 'errata-install' errata_id 'RHSA:2018-1234' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/rhsm_errata/rhsm_errata_level Resource ============================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [rhsm_errata_level.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/rhsm_errata_level.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **rhsm_errata_level** resource to install all packages of a specified errata level from the Red Hat Subscription Manager. For example, you can ensure that all packages associated with errata marked at a ‘Critical’ security level are installed. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **rhsm_errata_level** resource is: ``` rhsm_errata_level 'name' do errata_level String # default value: 'name' unless specified action Symbol # defaults to :install if not specified end ``` where: * `rhsm_errata_level` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `errata_level` is the property available to this resource. Actions ------- --- The **rhsm_errata_level** resource has the following actions: `:install` Install all packages of the specified errata level. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **rhsm_errata_level** resource has the following properties: `errata_level` **Ruby Type:** String | **Default Value:** `The resource block's name` **Allowed Values:** `"critical", "important", "low", "moderate"` An optional property for specifying the errata level of packages to install if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **rhsm_errata_level** resource in recipes: **Specify an errata level that differs from the resource name** ``` rhsm_errata_level 'example_install_moderate' do errata_level 'moderate' end ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/rhsm_errata_level/remote_file Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [remote_file.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/remote_file.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **remote_file** resource to transfer a file from a remote location using file specificity. This resource is similar to the **file** resource. Note Fetching files from the `files/` directory in a cookbook should be done with the **cookbook_file** resource. Syntax ------ --- A **remote_file** resource block manages files by using files that exist remotely. For example, to write the home page for an Apache website: ``` remote_file '/var/www/customers/public_html/index.html' do source 'http://somesite.com/index.html' owner 'web_admin' group 'web_admin' mode '0755' action :create end ``` where: * `'/var/www/customers/public_html/index.html'` is path to the file to be created * `'http://somesite.com/index.html'` specifies the location of the remote file, the file is downloaded from there * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **remote_file** resource is: ``` remote_file 'name' do atomic_update true, false authentication # default value: remote backup Integer, false # default value: 5 checksum String content String, nil force_unlink true, false # default value: false ftp_active_mode true, false # default value: false group String, Integer headers Hash inherits true, false manage_symlink_source true, false mode String, Integer notifies # see description owner String, Integer path String # defaults to 'name' if not specified rights Hash source String, Array subscribes # see description use_conditional_get true, false verify String, Block remote_domain String remote_password String remote_user String show_progress true, false # default value: false use_etag true, false # default value: true use_last_modified true, false # default value: true sensitive true, false # default value: false verifications Array action Symbol # defaults to :create if not specified end ``` where: * `remote_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `atomic_update`, `authentication`, `backup`, `checksum`, `content`, `force_unlink`, `ftp_active_mode`, `group`, `headers`, `http_options`, `manage_symlink_source`, `mode`, `owner`, `path`, `remote_domain`, `remote_password`, `remote_user`, `show_progress`, `ssl_verify_mode`, `use_etag`, and `use_last_modified` are the properties available to this resource. Actions ------- --- The **remote_file** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the **file** resource.) Properties ---------- --- The **remote_file** resource has the following properties: `atomic_update` **Ruby Type:** true, false | **Default Value:** `False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.` Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the `client.rb` file. `authentication` **Ruby Type:** Symbol | **Default Value:** `:remote` **Allowed Values:** `:local, :remote` `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `checksum` **Ruby Type:** String Optional, see `use_conditional_get`. The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, Chef Infra Client does not download it. `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `ftp_active_mode` **Ruby Type:** true, false | **Default Value:** `false` Whether Chef Infra Client uses active or passive FTP. Set to `true` to use active FTP. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `headers` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of custom headers. For example: ``` headers({ "Cookie" => "user=user_name; pass=p@ssw0rd!" }) ``` or: ``` headers({ "Referer" => "#{header}" }) ``` or: ``` headers( "Authorization"=>"Basic #{ Base64.encode64("#{username}:#{password}").gsub("\n", "") }" ) ``` `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `http_options` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of custom HTTP options. For example: `http_options({ http_retry_count: 0, http_retry_delay: 2 })` New in Chef Infra Client 17.5 `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `true`, the Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `false`, Chef Infra Client will follow the symlink and will manage the permissions and content of the symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The full path to the file, including the file name and its extension. Default value: the `name` of the resource block. See “Syntax” section above for more information. `remote_domain` **Ruby Type:** String **Windows only** The domain of the user specified by the `remote_user` property. By default the resource will authenticate against the domain of the remote system, or as a local account if the remote system is not joined to a domain. If the remote system is not part of a domain, it is necessary to authenticate as a local user on the remote system by setting the domain to `.`, for example: remote_domain ‘.’. The domain may also be specified as part of the `remote_user` property. New in Chef Client 13.4 `remote_password` **Ruby Type:** String **Windows only** The password of the user specified by the `remote_user` property. This property is required if `remote_user` is specified and may only be specified if `remote_user` is specified. The `sensitive` property for this resource will automatically be set to `true` if `remote_password` is specified. New in Chef Client 13.4 `remote_user` **Ruby Type:** String **Windows only** The name of a user with access to the remote file specified by the source property. The user name may optionally be specified with a domain, such as: `domain\user` or `user@my.dns.domain.com` via Universal Principal Name (UPN) format. The domain may also be set using the `remote_domain` property. Note that this property is ignored if source is not a UNC path. If this property is specified, the `remote_password` property is required. New in Chef Client 13.4 `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String, Array Required. The location of the source file. The location of the source file may be HTTP (`http://`), FTP (`ftp://`), SFTP (`sftp://`), local (`file:///`), or UNC (`\\host\share\file.tar.gz`). There are many ways to define the location of a source file. By using a path: ``` source 'http://couchdb.apache.org/img/sketch.png' ``` By using FTP: ``` source 'ftp://remote_host/path/to/img/sketch.png' ``` By using SFTP: ``` source 'sftp://username:password@remote_host:22/path/to/img/sketch.png' ``` By using a local path: ``` source 'file:///path/to/img/sketch.png' ``` By using a Microsoft Windows UNC: ``` source '\\\\path\\to\\img\\sketch.png' ``` By using a node attribute: ``` source node['nginx']['foo123']['url'] ``` By using attributes to define paths: ``` source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2" ``` By defining multiple paths for multiple locations: ``` source 'http://seapower/spring.png', 'http://seapower/has_sprung.png' ``` By defining those same multiple paths as an array: ``` source ['http://seapower/spring.png', 'http://seapower/has_sprung.png'] ``` When multiple paths are specified, Chef Infra Client will attempt to download the files in the order listed, stopping after the first successful download. `use_conditional_get` **Ruby Type:** true, false | **Default Value:** `true` Enable conditional HTTP requests by using a conditional `GET` (with the If-Modified-Since header) or an opaque identifier (ETag). To use If-Modified-Since headers, `use_last_modified` must also be set to `true`. To use ETag headers, `use_etag` must also be set to `true`. `show_progress` **Ruby Type:** true, false | **Default Value:** `false` Displays the progress of the file download. `ssl_verify_mode` **Ruby Type:** Symbol **Allowed Values:** `:verify_none, :verify_peer` Optional property to override SSL policy. If not specified, uses the SSL policy from `config.rb`. New in Chef Infra Client 16.2 `use_etag` **Ruby Type:** true, false | **Default Value:** `true` Enable ETag headers. Set to `false` to disable ETag headers. To use this setting, `use_conditional_get` must also be set to true. `use_last_modified` **Ruby Type:** true, false | **Default Value:** `true` Enable `If-Modified-Since` headers. Set to `false` to disable `If-Modified-Since` headers. To use this setting, `use_conditional_get` must also be set to `true`. `verify` **Ruby Type:** String, Block A block or a string that returns `true` or `false`. A string, when `true` is executed as a system command. A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block is `true`, Chef Infra Client will continue to update the file as appropriate. For example, this should return `true`: ``` remote_file '/tmp/baz' do verify { 1 == 1 } end ``` This should return `true`: ``` remote_file '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` This should return `true`: ``` remote_file '/tmp/bar' do verify { 1 == 1} end ``` And this should return `true`: ``` remote_file '/tmp/foo' do verify do |path| true end end ``` Whereas, this should return `false`: ``` remote_file '/tmp/turtle' do verify '/usr/bin/false' end ``` If a string or a block return `false`, the Chef Infra Client run will stop and an error is returned. ### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. ### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. ### Prevent Re-downloads To prevent Chef Infra Client from re-downloading files that are already present on a node, use one of the following attributes in a recipe: `use_conditional_get` (default) or `checksum`. * The `use_conditional_get` attribute is the default behavior of Chef Infra Client. If the remote file is located on a server that supports ETag and/or If-Modified-Since headers, Chef Infra Client will use a conditional `GET` to determine if the file has been updated. If the file has been updated, Chef Infra Client will re-download the file. * The `checksum` attribute will ask Chef Infra Client to compare the checksum for the local file to the one at the remote location. If they match, Chef Infra Client will not re-download the file. Using a local checksum for comparison requires that the local checksum be the correct checksum. The desired approach just depends on the desired workflow. For example, if a node requires a new file every day, using the checksum approach would require that the local checksum be updated and/or verified every day as well, in order to ensure that the local checksum was the correct one. Using a conditional `GET` in this scenario will greatly simplify the management required to ensure files are being updated accurately. ### Access a remote UNC path on Windows The `remote_file` resource on Windows supports accessing files from a remote SMB/CIFS share. The file name should be specified in the source property as a UNC path e.g. `\myserver\myshare\mydirectory\myfile.txt`. This allows access to the file at that path location even if the Chef Infra Client process identity does not have permission to access the file. Credentials for authenticating to the remote system can be specified using the `remote_user`, `remote_domain`, and `remote_password` properties when the user that Chef Infra Client is running does not have access to the remote file. See the “Properties” section for more details on these options. **Note**: This is primarily for accessing remote files when the user that Chef Infra Client is running as does not have sufficient access, and alternative credentials need to be specified. If the user already has access, the credentials do not need to be specified. In a case where the local system and remote system are in the same domain, the `remote_user` and `remote_password` properties often do not need to be specified, as the user may already have access to the remote file share. Examples: **Access a file from a different domain account:** ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_domain 'domain' remote_user 'username' remote_password 'password' end ``` OR ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_user 'domain\username' remote_password 'password' end ``` **Access a file using a local account on the remote machine:** ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_domain '.' remote_user 'username' remote_password 'password' end ``` OR ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_user '.\username' remote_password 'password' end ``` Examples -------- --- The following examples demonstrate various approaches for using the **remote_file** resource in recipes: **Download a file without checking the checksum**: ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' end ``` **Download a file with a checksum to validate**: ``` remote_file '/tmp/test_file' do source 'http://www.example.com/tempfiles/test_file' mode '0755' checksum '3a7dac00b1' # A SHA256 (or portion thereof) of the file. end ``` **Download a file only if it’s not already present**: ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' checksum '3a7dac00b1' # A SHA256 (or portion thereof) of the file. action :create_if_missing end ``` **Using HTTP Basic Authentication in Headers**: ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' headers('Authorization' => "Basic #{Base64.encode64("USERNAME_VALUE:PASSWORD_VALUE").delete("\n")}") checksum '3a7dac00b1' # A SHA256 (or portion thereof) of the file. action :create_if_missing end ``` **Downloading a file to the Chef file cache dir for execution**: ``` remote_file '#{Chef::Config['file_cache_path']}/install.sh' do source 'https://example.org/install.sh' action :create_if_missing end execute '#{Chef::Config['file_cache_path']}/install.sh' ``` **Specify advanced HTTP connection options including Net::HTTP (nethttp) options:** ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' http_options({ http_retry_delay: 0, http_retry_count: 0, keepalives: false, nethttp: { continue_timeout: 5, max_retries: 5, read_timeout: 5, write_timeout: 5, ssl_timeout: 5, }, }) end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/remote_file/rhsm_register Resource ======================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [rhsm_register.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/rhsm_register.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **rhsm_register** resource to register a node with the Red Hat Subscription Manager or a local Red Hat Satellite server. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **rhsm_register** resource is: ``` rhsm_register 'name' do activation_key String, Array auto_attach true, false # default value: false base_url String environment String force true, false # default value: false https_for_ca_consumer true, false # default value: false install_katello_agent true, false # default value: true organization String password String release Float, String satellite_host String server_url String service_level String system_name String username String action Symbol # defaults to :register if not specified end ``` where: * `rhsm_register` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `activation_key`, `auto_attach`, `base_url`, `environment`, `force`, `https_for_ca_consumer`, `install_katello_agent`, `organization`, `password`, `release`, `satellite_host`, `server_url`, `service_level`, `system_name`, and `username` are the properties available to this resource. Actions ------- --- The **rhsm_register** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:register` Register the node with RHSM. (default) `:unregister` Unregister the node from RHSM. Properties ---------- --- The **rhsm_register** resource has the following properties: `activation_key` **Ruby Type:** String, Array A string or array of activation keys to use when registering; you must also specify the ‘organization’ property when using this property. `auto_attach` **Ruby Type:** true, false | **Default Value:** `false` If true, RHSM will attempt to automatically attach the host to applicable subscriptions. It is generally better to use an activation key with the subscriptions pre-defined. `base_url` **Ruby Type:** String The hostname of the content delivery server to use to receive updates. Both Customer Portal Subscription Management and Subscription Asset Manager use Red Hat’s hosted content delivery services, with the URL <https://cdn.redhat.com>. Since Satellite 6 hosts its own content, the URL must be used for systems registered with Satellite 6. New in Chef Infra Client 17.8 `environment` **Ruby Type:** String The environment to use when registering; required when using the username and password properties. `force` **Ruby Type:** true, false | **Default Value:** `false` If true, the system will be registered even if it is already registered. Normally, any register operations will fail if the machine has already been registered. `https_for_ca_consumer` **Ruby Type:** true, false | **Default Value:** `false` If true, Chef Infra Client will fetch the katello-ca-consumer-latest.noarch.rpm from the satellite_host using HTTPS. New in Chef Infra Client 15.9 `install_katello_agent` **Ruby Type:** true, false | **Default Value:** `true` If true, the ‘katello-agent’ RPM will be installed. `organization` **Ruby Type:** String The organization to use when registering; required when using the ‘activation_key’ property. `password` **Ruby Type:** String The password to use when registering. This property is not applicable if using an activation key. If specified, username and environment are also required. `release` **Ruby Type:** Float, String Sets the operating system minor release to use for subscriptions for the system. Products and updates are limited to the specified minor release version. This is used only used with the `auto_attach` option. For example, `release '6.4'` will append `--release=6.4` to the register command. New in Chef Infra Client 17.8 `satellite_host` **Ruby Type:** String The FQDN of the Satellite host to register with. If this property is not specified, the host will register with Red Hat’s public RHSM service. `server_url` **Ruby Type:** String The hostname of the subscription service to use. The default is Customer Portal Subscription Management, subscription.rhn.redhat.com. If you do not use this option, the system registers with Customer Portal Subscription Management. New in Chef Infra Client 17.8 `service_level` **Ruby Type:** String Sets the service level to use for subscriptions on the registering machine. This is only used with the `auto_attach` option. New in Chef Infra Client 17.8 `system_name` **Ruby Type:** String The name of the system to register, defaults to the hostname. New in Chef Infra Client 16.5 `username` **Ruby Type:** String The username to use when registering. This property is not applicable if using an activation key. If specified, password and environment properties are also required. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **rhsm_register** resource in recipes: **Register a node with RHSM* ``` rhsm_register 'my-host' do activation_key 'ABCD1234' organization 'my_org' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/rhsm_register/rpm_package Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [rpm_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/rpm_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **rpm_package** resource to manage packages using the RPM Package Manager. Syntax ------ --- The full syntax for all of the properties that are available to the **rpm_package** resource is: ``` rpm_package 'name' do allow_downgrade true, false # default value: true options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `rpm_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **rpm_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **rpm_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **rpm_package** resource in recipes: Install a package ``` rpm_package 'name of package' do action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/rpm_package/remote_directory Resource ========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [remote_directory.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/remote_directory.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **remote_directory** resource to incrementally transfer a directory from a cookbook to a node. The directory that is copied from the cookbook should be located under `COOKBOOK_NAME/files/default/REMOTE_DIRECTORY`. The `remote_directory` resource will obey file specificity. Syntax ------ --- A **remote_directory** resource block transfers a directory from a cookbook to a node, and then assigns the permissions needed on that directory. For example: ``` remote_directory '/etc/apache2' do source 'apache2' owner 'root' group 'root' mode '0755' action :create end ``` where: * `'/etc/apache2'` specifies the directory * `source` specifies a directory in the current cookbook (use the `cookbook` property to specify a file that is in a different cookbook) * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **remote_directory** resource is: ``` remote_directory 'name' do cookbook String files_backup Integer, false # default value: 5 files_group String, Integer files_mode String, Integer # default value: 0644 on *nix systems files_owner String, Integer group String, Integer inherits true, false mode String, Integer overwrite true, false # default value: true owner String, Integer path String # default value: 'name' unless specified purge true, false recursive true, false rights Hash source String action Symbol # defaults to :create if not specified end ``` where: * `remote_directory` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `cookbook`, `files_backup`, `files_group`, `files_mode`, `files_owner`, `group`, `mode`, `overwrite`, `owner`, `path`, `purge`, `recursive`, and `source` are the properties available to this resource. Actions ------- --- The **remote_directory** resource has the following actions: `:create` Default. Create a directory and/or the contents of that directory. If a directory or its contents already exist (but does not match), update that directory or its contents to match. `:create_if_missing` Create a directory and/or the contents of that directory, but only if it does not exist. `:delete` Delete a directory, including the contents of that directory. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **remote_directory** resource has the following properties: `cookbook` **Ruby Type:** String The cookbook in which a file is located (if it is not located in the current cookbook). The default value is the current cookbook. `files_backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backup copies to keep for files in the directory. `files_group` **Ruby Type:** String, Integer Configure group permissions for files. A string or ID that identifies the group owner by group name, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available). `files_mode` **Ruby Type:** String, Integer | **Default Value:** `0644 on *nix systems` The octal mode for a file. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `files_owner` **Ruby Type:** String, Integer Configure owner permissions for files. A string or ID that identifies the group owner by user name, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `group` **Ruby Type:** Integer, String Use to configure permissions for directories. A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the directory already exists, the existing mode on the directory is used. If `mode` is not specified, the directory does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'`, and then applies the umask for the system on which the directory is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `overwrite` **Ruby Type:** true, false | **Default Value:** `true` Overwrite a file when it is different. `owner` **Ruby Type:** Integer, String Use to configure permissions for directories. A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the `name` of the resource block. See “Syntax” section above for more information. `purge` **Ruby Type:** true, false | **Default Value:** `false` Purge extra files found in the target directory. `recursive` **Ruby Type:** true, false | **Default Value:** `true` Create or delete directories recursively. Chef Infra Client must be able to create the directory structure, including parent directories (if missing), as defined in `COOKBOOK_NAME/files/default/REMOTE_DIRECTORY`. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String | **Default Value:** `The base portion of the 'path' property.` The base name of the source file (and inferred from the `path` property). For example, in the default value, ‘/some/path/’ would be ‘path’. ### Recursive Directories The **remote_directory** resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the `recursive` attribute only applies `group`, `mode`, and `owner` attribute values to the remote directory itself and any inner directories the resource copies. A directory structure: ``` /foo /bar /baz ``` The following example shows a way create a file in the `/baz` directory: ``` remote_directory '/foo/bar/baz' do owner 'root' group 'root' mode '0755' action :create end ``` But with this example, the `group`, `mode`, and `owner` attribute values will only be applied to `/baz`. Which is fine, if that’s what you want. But most of the time, when the entire `/foo/bar/baz` directory structure is not there, you must be explicit about each directory. For example: ``` %w( /foo /foo/bar /foo/bar/baz ).each do |path| remote_directory path do owner 'root' group 'root' mode '0755' end end ``` This approach will create the correct hierarchy—`/foo`, then `/bar` in `/foo`, and then `/baz` in `/bar`—and also with the correct attribute values for `group`, `mode`, and `owner`. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Recursive Directories The **remote_directory** resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the `recursive` attribute only applies `group`, `mode`, and `owner` attribute values to the remote directory itself and any inner directories the resource copies. A directory structure: ``` /foo /bar /baz ``` The following example shows a way create a file in the `/baz` directory: ``` remote_directory '/foo/bar/baz' do owner 'root' group 'root' mode '0755' action :create end ``` But with this example, the `group`, `mode`, and `owner` attribute values will only be applied to `/baz`. Which is fine, if that’s what you want. But most of the time, when the entire `/foo/bar/baz` directory structure is not there, you must be explicit about each directory. For example: ``` %w( /foo /foo/bar /foo/bar/baz ).each do |path| remote_directory path do owner 'root' group 'root' mode '0755' end end ``` This approach will create the correct hierarchy—`/foo`, then `/bar` in `/foo`, and then `/baz` in `/bar`—and also with the correct attribute values for `group`, `mode`, and `owner`. #### Example This section contains a more detailed example of how Chef Infra Client manages recursive directory structures: * A cookbook named `cumbria` that is used to build a website * A subfolder in the `/files/default` directory named `/website` * A file named `index.html`, which is the root page for the website * Directories within `/website` named `/cities`, `/places`, and `/football`, which contains pages about cities, places, and football teams * A directory named `/images`, which contains images These files are placed in the `/files/default` directory in the `cumbria` cookbook, like this: ``` cumbria /files /default /website index.html /cities carisle.html kendal.html penrith.html windermere.html /football carisle_united.html /images carisle_united.png furness_abbey.png hadrians_wall.png kendal.png /places furness_abbey.html hadrians_wall.html ``` The **remote_directory** resource can be used to build a website using these files. This website is being run on an Apache web server. The resource would be similar to the following: ``` remote_directory '/var/www/html' do files_mode '0440' files_owner 'yan' mode '0770' owner 'hamilton' source 'website' end ``` When Chef Infra Client runs, the **remote_directory** resource will tell Chef Infra Client to copy the directory tree from the cookbook to the file system using the structure defined in cookbook: ``` /var /www /html index.html /cities carisle.html kendal.html penrith.html windermere.html /football carisle_united.html /images carisle_united.png furness_abbey.png hadrians_wall.png kendal.png /places furness_abbey.html hadrians_wall.html ``` Chef Infra Client will manage the permissions of the entire directory structure below `/html`, for a total of 12 files and 4 directories. For example: ``` dr-xr-xr-x 2 root root 4096 /var/www/html dr--r----- 1 yan root 4096 /var/www/html/index.html drwxrwx--- 2 hamilton root 4096 /var/www/html/cities dr--r----- 1 yan root 4096 /var/www/html/cities/carlisle.html dr--r----- 1 yan root 4096 /var/www/html/cities/kendal.html dr--r----- 1 yan root 4096 /var/www/html/cities/penrith.html dr--r----- 1 yan root 4096 /var/www/html/cities/windermere.html drwxrwx--- 2 hamilton root 4096 /var/www/html/football dr--r----- 1 yan root 4096 /var/www/html/football/carlisle_united.html drwxrwx--- 2 hamilton root 4096 /var/www/html/images dr--r----- 1 yan root 4096 /var/www/html/images/carlisle_united/png dr--r----- 1 yan root 4096 /var/www/html/images/furness_abbey/png dr--r----- 1 yan root 4096 /var/www/html/images/hadrians_wall.png dr--r----- 1 yan root 4096 /var/www/html/images/kendal.png drwxrwx--- 2 hamilton root 4096 /var/www/html/places dr--r----- 1 yan root 4096 /var/www/html/places/furness_abbey.html dr--r----- 1 yan root 4096 /var/www/html/places/hadrians_wall.html ``` ### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. Examples -------- --- The following examples demonstrate various approaches for using the **remote_directory** resource in recipes: Recursively transfer a directory from a remote location ``` # create up to 10 backups of the files # set the files owner different from the directory remote_directory '/tmp/remote_something' do source 'something' files_backup 10 files_owner 'root' files_group 'root' files_mode '0644' owner 'nobody' group 'nobody' mode '0755' end ``` Use with the chef_handler resource The following example shows how to use the **remote_directory** resource and the **chef_handler** resource to reboot a handler named `WindowsRebootHandler`: ``` # the following code sample comes from the # ``reboot_handler`` recipe in the ``windows`` cookbook: # https://github.com/chef-cookbooks/windows remote_directory node['chef_handler']['handler_path'] do source 'handlers' recursive true action :create end chef_handler 'WindowsRebootHandler' do source "#{node['chef_handler']['handler_path']}/windows_reboot_handler.rb" arguments node['windows']['allow_pending_reboots'] supports :report => true, :exception => false action :enable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/remote_directory/route Resource ============== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [route.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/route.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **route** resource to manage the system routing table in a Linux environment. Syntax ------ --- A **route** resource block manages the system routing table in a Linux environment: ``` route '10.0.1.10/32' do gateway '10.0.0.20' device 'eth1' end ``` The full syntax for all of the properties that are available to the **route** resource is: ``` route 'name' do comment String device String gateway String metric Integer netmask String route_type Symbol, String # default value: :host target String # default value: 'name' unless specified action Symbol # defaults to :add if not specified end ``` where: * `route` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `comment`, `device`, `gateway`, `metric`, `netmask`, `route_type`, and `target` are the properties available to this resource. Actions ------- --- The **route** resource has the following actions: `:add` Default. Add a route. `:delete` Delete a route. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **route** resource has the following properties: `comment` **Ruby Type:** String Add a comment for the route. New in Chef Client 14.0 `device` **Ruby Type:** String The network interface to which the route applies. `gateway` **Ruby Type:** String The gateway for the route. `metric` **Ruby Type:** Integer The route metric value. `netmask` **Ruby Type:** String The decimal representation of the network mask. For example: `255.255.255.0`. `route_type` **Ruby Type:** Symbol, String | **Default Value:** `:host` **Allowed Values:** `:host, :net` `target` **Ruby Type:** String | **Default Value:** `The resource block's name` The IP address of the target route. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/route/rhsm_repo Resource =================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [rhsm_repo.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/rhsm_repo.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **rhsm_repo** resource to enable or disable Red Hat Subscription Manager repositories that are made available via attached subscriptions. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **rhsm_repo** resource is: ``` rhsm_repo 'name' do repo_name String # default value: 'name' unless specified action Symbol # defaults to :enable if not specified end ``` where: * `rhsm_repo` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `repo_name` is the property available to this resource. Actions ------- --- The **rhsm_repo** resource has the following actions: `:disable` Disable a RHSM repository. `:enable` Enable a RHSM repository. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **rhsm_repo** resource has the following properties: `repo_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the repository name if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **rhsm_repo** resource in recipes: **Enable an RHSM repository** ``` rhsm_repo 'rhel-7-server-extras-rpms' ``` **Disable an RHSM repository** ``` rhsm_repo 'rhel-7-server-extras-rpms' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/rhsm_repo/ruby Resource ============= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [ruby.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/ruby.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **ruby** resource to execute scripts using the Ruby interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. Syntax ------ --- A **ruby** resource block executes scripts using Ruby: ``` ruby 'hello world' do code <<-EOH puts "Hello world! From Chef and Ruby." EOH end ``` where: * `cwd` specifies the directory from which the command is run * `code` specifies the command to run The full syntax for all of the properties that are available to the **ruby** resource is: ``` ruby 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `ruby` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **ruby** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a script. Properties ---------- --- The **ruby** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/ruby/rhsm_subscription Resource =========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [rhsm_subscription.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/rhsm_subscription.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **rhsm_subscription** resource to add or remove Red Hat Subscription Manager subscriptions from your host. This can be used when a host’s activation_key does not attach all necessary subscriptions to your host. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **rhsm_subscription** resource is: ``` rhsm_subscription 'name' do pool_id String # default value: 'name' unless specified action Symbol # defaults to :attach if not specified end ``` where: * `rhsm_subscription` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `pool_id` is the property available to this resource. Actions ------- --- The **rhsm_subscription** resource has the following actions: `:attach` Attach the node to a subscription pool. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove the node from a subscription pool. Properties ---------- --- The **rhsm_subscription** resource has the following properties: `pool_id` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the Pool ID if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/rhsm_subscription/ruby_block Resource ==================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [ruby_block.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/ruby_block.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **ruby_block** resource to execute Ruby code during a Chef Infra Client run. Ruby code in the `ruby_block` resource is evaluated with other resources during convergence, whereas Ruby code outside of a `ruby_block` resource is evaluated before other resources, as the recipe is compiled. Syntax ------ --- A **ruby_block** resource block executes a block of arbitrary Ruby code. For example, to reload the client.rb file during a Chef Infra Client run: ``` ruby_block 'reload_client_config' do block do Chef::Config.from_file("/etc/chef/client.rb") end action :run end ``` The full syntax for all of the properties that are available to the **ruby_block** resource is: ``` ruby_block 'name' do block Block block_name String # defaults to 'name' if not specified action Symbol # defaults to :run if not specified end ``` where: * `ruby_block` is the resource. * `name` is the name given to the resource block. * `block` is the block of Ruby code to be executed. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `block` and `block_name` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **ruby_block** resource has the following actions: `:create` The same as `:run`. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a Ruby block. Properties ---------- --- The **ruby_block** resource has the following properties: `block` **Ruby Type:** Block A block of Ruby code. `block_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the Ruby block. Default value: the `name` of the resource block. See “Syntax” section above for more information. Examples -------- --- The following examples demonstrate various approaches for using the **ruby_block** resource in recipes: **Re-read configuration data** ``` ruby_block 'reload_client_config' do block do Chef::Config.from_file('/etc/chef/client.rb') end action :run end ``` **Run a block on a particular platform** The following example shows how an if statement can be used with the `windows?` method in the Chef Infra Language to run code specific to Microsoft Windows. The code is defined using the ruby_block resource: ``` if windows? ruby_block 'copy libmysql.dll into ruby path' do block do require 'fileutils' FileUtils.cp "#{node['mysql']['client']['lib_dir']}\\libmysql.dll", node['mysql']['client']['ruby_dir'] end not_if { ::File.exist?("#{node['mysql']['client']['ruby_dir']}\\libmysql.dll") } end end ``` **Stash a file in a data bag** The following example shows how to use the ruby_block resource to stash a BitTorrent file in a data bag so that it can be distributed to nodes in the organization. ``` ruby_block 'share the torrent file' do block do f = File.open(node['bittorrent']['torrent'],'rb') #read the .torrent file and base64 encode it enc = Base64.encode64(f.read) data = { 'id'=>bittorrent_item_id(node['bittorrent']['file']), 'seed'=>node.ipaddress, 'torrent'=>enc } item = Chef::DataBagItem.new item.data_bag('bittorrent') item.raw_data = data item.save end action :nothing subscribes :create, "bittorrent_torrent[#{node['bittorrent']['torrent']}]", :immediately end ``` **Update the /etc/hosts file** The following example shows how the ruby_block resource can be used to update the /etc/hosts file: ``` ruby_block 'edit etc hosts' do block do rc = Chef::Util::FileEdit.new('/etc/hosts') rc.search_file_replace_line(/^127\.0\.0\.1 localhost$/, '127.0.0.1 #{new_fqdn} #{new_hostname} localhost') rc.write_file end end ``` **Set environment variables** The following example shows how to use variables within a Ruby block to set environment variables using rbenv. ``` node.override[:rbenv][:root] = rbenv_root node.override[:ruby_build][:bin_path] = rbenv_binary_path ruby_block 'initialize' do block do ENV['RBENV_ROOT'] = node[:rbenv][:root] ENV['PATH'] = "#{node[:rbenv][:root]}/bin:#{node[:ruby_build][:bin_path]}:#{ENV['PATH']}" end end ``` **Call methods in a gem** The following example shows how to call methods in gems not shipped in Chef Infra Client ``` chef_gem 'mongodb' ruby_block 'config_replicaset' do block do MongoDB.configure_replicaset(node, replicaset_name, rs_nodes) end action :run end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/ruby_block/snap_package Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [snap_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/snap_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **snap_package** resource to manage snap packages on Debian and Ubuntu platforms. **New in Chef Infra Client 15.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **snap_package** resource is: ``` snap_package 'name' do channel String # default value: "stable" options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `snap_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `channel`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **snap_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:lock` Locks the apt package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:unlock` Unlocks the apt package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **snap_package** resource has the following properties: `channel` **Ruby Type:** String | **Default Value:** `stable` **Allowed Values:** `"beta", "candidate", "edge", "stable"` The default channel. For example: stable. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/snap_package/script Resource =============== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [script.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/script.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **script** resource to execute scripts using a specified interpreter, such as Bash, csh, Perl, Python, or Ruby. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. This resource is the base resource for several other resources used for scripting on specific platforms. For more information about specific resources for specific platforms, see the following topics: * [bash](../bash/index) * [csh](../csh/index) * [ksh](../ksh/index) * [perl](../perl/index) * [python](../python/index) * [ruby](../ruby/index) Changed in 12.19 to support windows alternate user identity in execute resources Syntax ------ --- A **script** resource block typically executes scripts using a specified interpreter, such as Bash, csh, Perl, Python, or Ruby: ``` script 'extract_module' do interpreter "bash" cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` where: * `interpreter` specifies the command shell to use * `cwd` specifies the directory from which the command is run * `code` specifies the command to run It is more common to use the **script**-based resource that is specific to the command shell. Chef has shell-specific resources for Bash, csh, ksh, Perl, Python, and Ruby. The same command as above, but run using the **bash** resource: ``` bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` The full syntax for all of the properties that are available to the **script** resource is: ``` script 'name' do code String creates String cwd String environment Hash flags String group String, Integer interpreter String path Array returns Integer, Array timeout Integer, Float user String password String domain String umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `script` is the resource * `name` is the name of the resource block * `cwd` is the location from which the command is run * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `interpreter`, `path`, `returns`, `timeout`, `user`, `password`, `domain` and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **script** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. Properties ---------- --- The **script** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `interpreter` **Ruby Type:** String The script interpreter to use during code execution. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String The user name of the user identity with which to launch the new process. Default value: nil. The user name may optionally be specified with a domain, i.e. domainuser or [<EMAIL>](mailto:<EMAIL>) via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified. `password` **Ruby Type:** String *Windows only*: The password of the user specified by the user property. Default value: nil. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. `domain` **Ruby Type:** String *Windows only*: The domain of the user user specified by the user property. Default value: nil. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Guard Interpreter Any resource that passes a string command may also specify the interpreter that will be used to evaluate that string command. This is done by using the `guard_interpreter` property to specify a **script**-based resource. **Attributes** The `guard_interpreter` property may be set to any of the following values: `:bash` Evaluates a string command using the **bash** resource. `:batch` Evaluates a string command using the **batch** resource. Default value (within a **batch** resource block): `:batch`. `:csh` Evaluates a string command using the **csh** resource. `:default` Default. Executes the default interpreter as identified by Chef Infra Client. `:perl` Evaluates a string command using the **perl** resource. `:powershell_script` Evaluates a string command using the **powershell_script** resource. Default value (within a **powershell_script** resource block): `:powershell_script`. `:python` Evaluates a string command using the **python** resource. `:ruby` Evaluates a string command using the **ruby** resource. **Inheritance** The `guard_interpreter` property is set to `:default` by default for the **bash**, **csh**, **perl**, **python**, and **ruby** resources. When the `guard_interpreter` property is set to `:default`, `not_if` or `only_if` guard statements **do not inherit** properties that are defined by the **script**-based resource. Warning The **batch** and **powershell_script** resources inherit properties by default. The `guard_interpreter` property is set to `:batch` or `:powershell_script` automatically when using a `not_if` or `only_if` guard statement within a **batch** or **powershell_script** resource, respectively. For example, the `not_if` guard statement in the following resource example **does not inherit** the `environment` property: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` and requires adding the `environment` property to the `not_if` guard statement so that it may use the `JAVA_HOME` path as part of its evaluation: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started', :environment => 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' end ``` To inherit properties, add the `guard_interpreter` property to the resource block and set it to the appropriate value: * `:bash` for **bash** * `:csh` for **csh** * `:perl` for **perl** * `:python` for **python** * `:ruby` for **ruby** For example, using the same example as from above, but this time adding the `guard_interpreter` property and setting it to `:bash`: ``` bash 'javatooling' do guard_interpreter :bash environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` The `not_if` statement now inherits the `environment` property and will use the `JAVA_HOME` path as part of its evaluation. **Example** For example, the following code block will ensure the command is evaluated using the default interpreter as identified by Chef Infra Client: ``` resource 'name' do guard_interpreter :default # code end ``` Examples -------- --- The following examples demonstrate various approaches for using the **script** resource in recipes: Use a named provider to run a script ``` bash 'install_something' do user 'root' cwd '/tmp' code <<-EOH wget http://www.example.com/tarball.tar.gz tar -zxf tarball.tar.gz cd tarball ./configure make make install EOH end ``` Run a script ``` script 'install_something' do interpreter 'bash' user 'root' cwd '/tmp' code <<-EOH wget http://www.example.com/tarball.tar.gz tar -zxf tarball.tar.gz cd tarball ./configure make make install EOH end ``` or something like: ``` bash 'openvpn-server-key' do environment('KEY_CN' => 'server') code <<-EOF openssl req -batch -days #{node['openvpn']['key']['expire']} \ -nodes -new -newkey rsa:#{key_size} -keyout #{key_dir}/server.key \ -out #{key_dir}/server.csr -extensions server \ -config #{key_dir}/openssl.cnf EOF not_if { File.exist?('#{key_dir}/server.crt') } end ``` where `code` contains the OpenSSL command to be run. The `not_if` property tells Chef Infra Client not to run the command if the file already exists. Install a file from a remote location using bash The following is an example of how to install the `foo123` module for Nginx. This module adds shell-style functionality to an Nginx configuration file and does the following: * Declares three variables * Gets the Nginx file from a remote location * Installs the file using Bash to the path specified by the `src_filepath` variable ``` # the following code sample is similar to the ``upload_progress_module`` # recipe in the ``nginx`` cookbook: # https://github.com/chef-cookbooks/nginx src_filename = "foo123-nginx-module-v#{ node['nginx']['foo123']['version'] }.tar.gz" src_filepath = "#{Chef::Config['file_cache_path']}/#{src_filename}" extract_path = "#{ Chef::Config['file_cache_path'] }/nginx_foo123_module/#{ node['nginx']['foo123']['checksum'] }" remote_file 'src_filepath' do source node['nginx']['foo123']['url'] checksum node['nginx']['foo123']['checksum'] owner 'root' group 'root' mode '0755' end bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` Install an application from git using bash The following example shows how Bash can be used to install a plug-in for rbenv named `ruby-build`, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which `ruby-build` is located, and then runs a command. ``` git "#{Chef::Config[:file_cache_path]}/ruby-build" do repository 'git://github.com/sstephenson/ruby-build.git' revision 'master' action :sync end bash 'install_ruby_build' do cwd "#{Chef::Config[:file_cache_path]}/ruby-build" user 'rbenv' group 'rbenv' code <<-EOH ./install.sh EOH environment 'PREFIX' => '/usr/local' end ``` To read more about `ruby-build`, see here: <https://github.com/sstephenson/ruby-build>. Store certain settings The following recipe shows how an attributes file can be used to store certain settings. An attributes file is located in the `attributes/` directory in the same cookbook as the recipe which calls the attributes file. In this example, the attributes file specifies certain settings for Python that are then used across all nodes against which this recipe will run. Python packages have versions, installation directories, URLs, and checksum files. An attributes file that exists to support this type of recipe would include settings like the following: ``` default['python']['version'] = '2.7.1' if python['install_method'] == 'package' default['python']['prefix_dir'] = '/usr' else default['python']['prefix_dir'] = '/usr/local' end default['python']['url'] = 'http://www.python.org/ftp/python' default['python']['checksum'] = '80e387...85fd61' ``` and then the methods in the recipe may refer to these values. A recipe that is used to install Python will need to do the following: * Identify each package to be installed (implied in this example, not shown) * Define variables for the package `version` and the `install_path` * Get the package from a remote location, but only if the package does not already exist on the target system * Use the **bash** resource to install the package on the node, but only when the package is not already installed ``` # the following code sample comes from the ``oc-nginx`` cookbook on |github|: https://github.com/cookbooks/oc-nginx version = node['python']['version'] install_path = "#{node['python']['prefix_dir']}/lib/python#{version.split(/(^\d+\.\d+)/)[1]}" remote_file "#{Chef::Config[:file_cache_path]}/Python-#{version}.tar.bz2" do source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2" checksum node['python']['checksum'] mode '0755' not_if { ::File.exist?(install_path) } end bash 'build-and-install-python' do cwd Chef::Config[:file_cache_path] code <<-EOF tar -jxvf Python-#{version}.tar.bz2 (cd Python-#{version} && ./configure #{configure_options}) (cd Python-#{version} && make && make install) EOF not_if { ::File.exist?(install_path) } end ``` Run a command as an alternate user *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] domain "domain-name" user "username" password "password" end # Passing username = 'domain-name\\username'. No domain is passed script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "domain-name\\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/script/service Resource ================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [service.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/service.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **service** resource to manage a service. Syntax ------ --- The full syntax for all of the properties that are available to the **service** resource is: ``` service 'name' do init_command String options Array, String parameters Hash pattern String priority Integer, String, Hash reload_command String, false restart_command String, false run_levels Array service_name String # default value: 'name' unless specified start_command String, false status_command String, false stop_command String, false supports Hash # default value: {"restart"=>nil, "reload"=>nil, "status"=>nil} timeout Integer # default value: 900 user String action Symbol # defaults to :nothing if not specified end ``` where: * `service` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `init_command`, `options`, `parameters`, `pattern`, `priority`, `reload_command`, `restart_command`, `run_levels`, `service_name`, `start_command`, `status_command`, `stop_command`, `supports`, `timeout`, and `user` are the properties available to this resource. Actions ------- --- The **service** resource has the following actions: `:disable` Disable a service. This action is equivalent to a `Disabled` startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot. `:enable` Enable a service at boot. This action is equivalent to an `Automatic` startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reload` Reload the configuration for this service. `:restart` Restart a service. `:start` Start a service, and keep it running until stopped or disabled. `:stop` Stop a service. Properties ---------- --- The **service** resource has the following properties: `init_command` **Ruby Type:** String The path to the init script that is associated with the service. Use `init_command` to prevent the need to specify overrides for the `start_command`, `stop_command`, and `restart_command` properties. When this property is not specified, Chef Infra Client will use the default init command for the service provider being used. `options` **Ruby Type:** Array, String Solaris platform only. Options to pass to the service command. See the `svcadm` manual for details of possible options. `parameters` **Ruby Type:** Hash Upstart only: A hash of parameters to pass to the service command for use in the service definition. `pattern` **Ruby Type:** String | **Default Value:** `The value provided to 'service_name' or the resource block's name` The pattern to look for in the process table. `priority` **Ruby Type:** Integer, String, Hash Debian platform only. The relative priority of the program for start and shutdown ordering. May be an integer or a Hash. An integer is used to define the start run levels; stop run levels are then 100-integer. A Hash is used to define values for specific run levels. For example, `{ 2 => [:start, 20], 3 => [:stop, 55] }` will set a priority of twenty for run level two and a priority of fifty-five for run level three. `reload_command` **Ruby Type:** String, false The command used to tell a service to reload its configuration. `restart_command` **Ruby Type:** String, false The command used to restart a service. `run_levels` **Ruby Type:** Array RHEL platforms only: Specific run_levels the service will run under. `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the service name if it differs from the resource block’s name. `start_command` **Ruby Type:** String, false The command used to start a service. `status_command` **Ruby Type:** String, false The command used to check the run status for a service. `stop_command` **Ruby Type:** String, false The command used to stop a service. `supports` **Ruby Type:** Hash | **Default Value:** `{"restart" => nil, "reload" => nil, "status" => nil}` A list of properties that controls how Chef Infra Client is to attempt to manage a service: `:restart`, `:reload`, `:status`. For `:restart`, the init script or other service provider can use a restart command; if `:restart` is not specified, Chef Infra Client attempts to stop and then start a service. For `:reload`, the init script or other service provider can use a reload command. For `:status`, the init script or other service provider can use a status command to determine if the service is running; if `:status` is not specified, Chef Infra Client attempts to match the `service_name` against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: `{ restart: false, reload: false, status: false }` for all platforms (except for the Red Hat platform family, which defaults to `{ restart: false, reload: false, status: true }`.) `timeout` **Ruby Type:** Integer | **Default Value:** `900` The amount of time (in seconds) to wait before timing out. `user` **Ruby Type:** String systemd only: A username to run the service under. New in Chef Client 12.21 Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **service** resource in recipes: Start a service ``` service 'example_service' do action :start end ``` Start a service, enable it ``` service 'example_service' do supports status: true, restart: true, reload: true action [ :enable, :start ] end ``` Use a pattern ``` service 'samba' do pattern 'smbd' action [:enable, :start] end ``` Use the :nothing common action ``` service 'memcached' do action :nothing end ``` Use the retries common attribute ``` service 'apache' do action [ :enable, :start ] retries 3 end ``` Manage a service, depending on the node platform ``` service 'example_service' do if redhat? service_name 'redhat_name' else service_name 'other_name' end supports restart: true action [ :enable, :start ] end ``` Reload a service using a template To reload a service that is based on a template, use the **template** and **service** resources together in the same recipe, similar to the following: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' end service 'apache' do action :enable subscribes :reload, 'template[/tmp/somefile]', :immediately end ``` where the `subscribes` notification is used to reload the service whenever the template is modified. Enable a service after a restart or reload ``` service 'apache' do supports restart: true, reload: true action :enable end ``` Set an IP address using variables and a template The following example shows how the **template** resource can be used in a recipe to combine settings stored in an attributes file, variables within a recipe, and a template to set the IP addresses that are used by the Nginx service. The attributes file contains the following: ``` default['nginx']['dir'] = '/etc/nginx' ``` The recipe then does the following to: * Declare two variables at the beginning of the recipe, one for the remote IP address and the other for the authorized IP address * Use the **service** resource to restart and reload the Nginx service * Load a template named `authorized_ip.erb` from the `/templates` directory that is used to set the IP address values based on the variables specified in the recipe ``` node.default['nginx']['remote_ip_var'] = 'remote_addr' node.default['nginx']['authorized_ips'] = ['127.0.0.1/32'] service 'nginx' do supports :status => true, :restart => true, :reload => true end template 'authorized_ip' do path "#{node['nginx']['dir']}/authorized_ip" source 'modules/authorized_ip.erb' owner 'root' group 'root' mode '0755' variables( :remote_ip_var => node['nginx']['remote_ip_var'], :authorized_ips => node['nginx']['authorized_ips'] ) notifies :reload, 'service[nginx]', :immediately end ``` where the `variables` property tells the template to use the variables set at the beginning of the recipe and the `source` property is used to call a template file located in the cookbook’s `/templates` directory. The template file looks similar to: ``` geo $<%= @remote_ip_var %> $authorized_ip { default no; <% @authorized_ips.each do |ip| %> <%= "#{ip} yes;" %> <% end %> } ``` Use a cron timer to manage a service The following example shows how to install the crond application using two resources and a variable: ``` # the following code sample comes from the ``cron`` cookbook: # https://github.com/chef-cookbooks/cron cron_package = case node['platform'] when 'redhat', 'centos', 'scientific', 'fedora', 'amazon' node['platform_version'].to_f >= 6.0 ? 'cronie' : 'vixie-cron' else 'cron' end package cron_package do action :install end service 'crond' do case node['platform'] when 'redhat', 'centos', 'scientific', 'fedora', 'amazon' service_name 'crond' when 'debian', 'ubuntu', 'suse' service_name 'cron' end action [:start, :enable] end ``` where * `cron_package` is a variable that is used to identify which platforms apply to which install packages * the **package** resource uses the `cron_package` variable to determine how to install the crond application on various nodes (with various platforms) * the **service** resource enables the crond application on nodes that have Red Hat, CentOS, Red Hat Enterprise Linux, Fedora, or Amazon Web Services (AWS), and the cron service on nodes that run Debian, Ubuntu, or openSUSE Restart a service, and then notify a different service The following example shows how start a service named `example_service` and immediately notify the Nginx service to restart. ``` service 'example_service' do action :start notifies :restart, 'service[nginx]', :immediately end ``` Restart one service before restarting another This example uses the `:before` notification to restart the `php-fpm` service before restarting `nginx`: ``` service 'nginx' do action :restart notifies :restart, 'service[php-fpm]', :before end ``` With the `:before` notification, the action specified for the `nginx` resource will not run until action has been taken on the notified resource (`php-fpm`). Stop a service, do stuff, and then restart it The following example shows how to use the **execute**, **service**, and **mount** resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following: * Checks to see if the Amazon EC2 node has MySQL * If the node has MySQL, stops MySQL * Installs MySQL * Mounts the node * Restarts MySQL ``` # the following code sample comes from the ``server_ec2`` # recipe in the following cookbook: # https://github.com/chef-cookbooks/mysql if (node.attribute?('ec2') && ! FileTest.directory?(node['mysql']['ec2_path'])) service 'mysql' do action :stop end execute 'install-mysql' do command "mv #{node['mysql']['data_dir']}#{node['mysql']['ec2_path']}" not_if do FileTest.directory?(node['mysql']['ec2_path']) end end [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir| directory dir do owner 'mysql' group 'mysql' end end mount node['mysql']['data_dir'] do device node['mysql']['ec2_path'] fstype 'none' options 'bind,rw' action [:mount, :enable] end service 'mysql' do action :start end end ``` where * the two **service** resources are used to stop, and then restart the MySQL service * the **execute** resource is used to install MySQL * the **mount** resource is used to mount the node and enable MySQL Control a service using the execute resource Warning This is an example of something that should NOT be done. Use the **service** resource to control a service, not the **execute** resource. Do something like this: ``` service 'tomcat' do action :start end ``` and NOT something like this: ``` execute 'start-tomcat' do command '/etc/init.d/tomcat6 start' action :run end ``` There is no reason to use the **execute** resource to control a service because the **service** resource exposes the `start_command` property directly, which gives a recipe full control over the command issued in a much cleaner, more direct manner. Enable a service on AIX using the mkitab command The **service** resource does not support using the `:enable` and `:disable` actions with resources that are managed using System Resource Controller (SRC). This is because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot. One approach for enabling or disabling services that are managed by System Resource Controller (SRC) is to use the **execute** resource to invoke `mkitab`, and then use that command to enable or disable the service. The following example shows how to install a service: ``` execute "install #{node['chef_client']['svc_name']} in SRC" do command "mkssys -s #{node['chef_client']['svc_name']} -p #{node['chef_client']['bin']} -u root -S -n 15 -f 9 -o #{node['chef_client']['log_dir']}/client.log -e #{node['chef_client']['log_dir']}/client.log -a ' -i #{node['chef_client']['interval']} -s #{node['chef_client']['splay']}'" not_if "lssrc -s #{node['chef_client']['svc_name']}" action :run end ``` and then enable it using the `mkitab` command: ``` execute "enable #{node['chef_client']['svc_name']}" do command "mkitab '#{node['chef_client']['svc_name']}:2:once:/usr/bin/startsrc -s #{node['chef_client']['svc_name']} > /dev/console 2>&1'" not_if "lsitab #{node['chef_client']['svc_name']}" end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/service/smartos_package Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [smartos_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/smartos_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **smartos_package** resource to manage packages for the SmartOS platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. Syntax ------ --- The full syntax for all of the properties that are available to the **smartos_package** resource is: ``` smartos_package 'name' do options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `smartos_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **smartos_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **smartos_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/smartos_package/solaris_package Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [solaris_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/solaris_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **solaris_package** resource to manage packages on the Solaris platform. Syntax ------ --- The full syntax for all of the properties that are available to the **solaris_package** resource is: ``` solaris_package 'name' do options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `solaris_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **solaris_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. Properties ---------- --- The **solaris_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **solaris_package** resource in recipes: Install a package ``` solaris_package 'name of package' do source '/packages_directory' action :install end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/solaris_package/ssh_known_hosts_entry Resource ================================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [ssh_known_hosts_entry.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/ssh_known_hosts_entry.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **ssh_known_hosts_entry** resource to add an entry for the specified host in /etc/ssh/ssh_known_hosts or a user’s known hosts file if specified. **New in Chef Infra Client 14.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **ssh_known_hosts_entry** resource is: ``` ssh_known_hosts_entry 'name' do file_location String # default value: "/etc/ssh/ssh_known_hosts" group String, Integer # default value: The root user's group depending on platform. hash_entries true, false # default value: false host String # default value: 'name' unless specified key String key_type String # default value: "rsa" mode String # default value: "0644" owner String, Integer # default value: "root" port Integer # default value: 22 timeout Integer # default value: 30 action Symbol # defaults to :create if not specified end ``` where: * `ssh_known_hosts_entry` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `file_location`, `group`, `hash_entries`, `host`, `key`, `key_type`, `mode`, `owner`, `port`, and `timeout` are the properties available to this resource. Actions ------- --- The **ssh_known_hosts_entry** resource has the following actions: `:create` Create an entry in the ssh_known_hosts file. (default) `:flush` Immediately flush the entries to the config file. Without this the actual writing of the file is delayed in the Chef Infra Client run so all entries can be accumulated before writing the file out. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **ssh_known_hosts_entry** resource has the following properties: `file_location` **Ruby Type:** String | **Default Value:** `/etc/ssh/ssh_known_hosts` The location of the ssh known hosts file. Change this to set a known host file for a particular user. `group` **Ruby Type:** String, Integer | **Default Value:** `The root user's group depending on platform.` The file group for the ssh_known_hosts file. `hash_entries` **Ruby Type:** true, false | **Default Value:** `false` Hash the hostname and addresses in the ssh_known_hosts file for privacy. `host` **Ruby Type:** String | **Default Value:** `The resource block's name` The host to add to the known hosts file. `key` **Ruby Type:** String An optional key for the host. If not provided this will be automatically determined. `key_type` **Ruby Type:** String | **Default Value:** `rsa` The type of key to store. `mode` **Ruby Type:** String | **Default Value:** `0644` The file mode for the ssh_known_hosts file. `owner` **Ruby Type:** String, Integer | **Default Value:** `root` The file owner for the ssh_known_hosts file. `port` **Ruby Type:** Integer | **Default Value:** `22` The server port that the ssh-keyscan command will use to gather the public key. `timeout` **Ruby Type:** Integer | **Default Value:** `30` The timeout in seconds for ssh-keyscan. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **ssh_known_hosts_entry** resource in recipes: **Add a single entry for github.com with the key auto detected** ``` ssh_known_hosts_entry 'github.com' ``` **Add a single entry with your own provided key** ``` ssh_known_hosts_entry 'github.com' do key 'node.example.com ssh-rsa ...' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/ssh_known_hosts_entry/swap_file Resource =================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [swap_file.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/swap_file.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **swap_file** resource to create or delete swap files on Linux systems, and optionally to manage the swappiness configuration for a host. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **swap_file** resource is: ``` swap_file 'name' do path String # default value: 'name' unless specified persist true, false # default value: false size Integer swappiness Integer timeout Integer # default value: 600 action Symbol # defaults to :create if not specified end ``` where: * `swap_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `path`, `persist`, `size`, `swappiness`, and `timeout` are the properties available to this resource. Actions ------- --- The **swap_file** resource has the following actions: `:create` Create a swapfile. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a swapfile and disable swap. Properties ---------- --- The **swap_file** resource has the following properties: `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path where the swap file will be created on the system if it differs from the resource block’s name. `persist` **Ruby Type:** true, false | **Default Value:** `false` Persist the swapon. `size` **Ruby Type:** Integer The size (in MBs) of the swap file. `swappiness` **Ruby Type:** Integer The swappiness value to set on the system. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Timeout for `dd` / `fallocate` commands. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **swap_file** resource in recipes: **Create a swap file** ``` swap_file '/dev/sda1' do size 1024 end ``` **Remove a swap file** ``` swap_file '/dev/sda1' do action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/swap_file/sudo Resource ============= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [sudo.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/sudo.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **sudo** resource to add or remove individual sudo entries using sudoers.d files. Sudo version 1.7.2 or newer is required to use the sudo resource, as it relies on the `#includedir` directive introduced in version 1.7.2. This resource does not enforce installation of the required sudo version. Chef-supported releases of Ubuntu, SuSE, Debian, and RHEL (6+) all support this feature. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **sudo** resource is: ``` sudo 'name' do command_aliases Array # default value: [] commands Array # default value: ["ALL"] config_prefix String # default value: "Prefix values based on the node's platform" defaults Array # default value: [] env_keep_add Array # default value: [] env_keep_subtract Array # default value: [] filename String # default value: 'name' unless specified groups String, Array # default value: [] host String # default value: "ALL" noexec true, false # default value: false nopasswd true, false # default value: false runas String # default value: "ALL" setenv true, false # default value: false template String users String, Array # default value: [] variables Hash visudo_binary String # default value: "/usr/sbin/visudo" action Symbol # defaults to :create if not specified end ``` where: * `sudo` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command_aliases`, `commands`, `config_prefix`, `defaults`, `env_keep_add`, `env_keep_subtract`, `filename`, `groups`, `host`, `noexec`, `nopasswd`, `runas`, `setenv`, `template`, `users`, `variables`, and `visudo_binary` are the properties available to this resource. Actions ------- --- The **sudo** resource has the following actions: `:create` Create a single sudoers configuration file in the `sudoers.d` directory. (default) `:delete` Remove a sudoers configuration file from the `sudoers.d` directory. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **sudo** resource has the following properties: `command_aliases` **Ruby Type:** Array | **Default Value:** `[]` Command aliases that can be used as allowed commands later in the configuration. `commands` **Ruby Type:** Array | **Default Value:** `["ALL"]` An array of full paths to commands this sudoer can execute. `config_prefix` **Ruby Type:** String | **Default Value:** `Prefix values based on the node's platform` The directory that contains the sudoers configuration file. `defaults` **Ruby Type:** Array | **Default Value:** `[]` An array of defaults for the user/group. `env_keep_add` **Ruby Type:** Array | **Default Value:** `[]` An array of strings to add to `env_keep`. `env_keep_subtract` **Ruby Type:** Array | **Default Value:** `[]` An array of strings to remove from `env_keep`. `filename` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the sudoers.d file if it differs from the name of the resource block `groups` **Ruby Type:** String, Array | **Default Value:** `[]` Group(s) to provide sudo privileges to. This property accepts either an array or a comma separated list. Leading % on group names is optional. `host` **Ruby Type:** String | **Default Value:** `ALL` The host to set in the sudo configuration. `noexec` **Ruby Type:** true, false | **Default Value:** `false` Prevent commands from shelling out. `nopasswd` **Ruby Type:** true, false | **Default Value:** `false` Allow sudo to be run without specifying a password. `runas` **Ruby Type:** String | **Default Value:** `ALL` User that the command(s) can be run as. `setenv` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not to permit preservation of the environment with `sudo -E`. `template` **Ruby Type:** String The name of the erb template in your cookbook, if you wish to supply your own template. `users` **Ruby Type:** String, Array | **Default Value:** `[]` User(s) to provide sudo privileges to. This property accepts either an array or a comma separated list. `variables` **Ruby Type:** Hash The variables to pass to the custom template. This property is ignored if not using a custom template. `visudo_binary` **Ruby Type:** String | **Default Value:** `/usr/sbin/visudo` The path to visudo for configuration verification. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **sudo** resource in recipes: **Grant a user sudo privileges for any command** ``` sudo 'admin' do user 'admin' end ``` **Grant a user and groups sudo privileges for any command** ``` sudo 'admins' do users 'bob' groups 'sysadmins, superusers' end ``` **Grant passwordless sudo privileges for specific commands** ``` sudo 'passwordless-access' do commands ['/bin/systemctl restart httpd', '/bin/systemctl restart mysql'] nopasswd true end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/sudo/subversion Resource =================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [subversion.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/subversion.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **subversion** resource to manage source control resources that exist in a Subversion repository. Warning The subversion resource has known bugs and may not work as expected. For more information see Chef GitHub issues, particularly [#4050](https://github.com/chef/chef/issues/4050) and [#4257](https://github.com/chef/chef/issues/4257). Syntax ------ --- The full syntax for all of the properties that are available to the **subversion** resource is: ``` subversion 'name' do destination String # default value: 'name' unless specified environment Hash group String, Integer repository String revision String # default value: "HEAD" svn_arguments String, false # default value: "--no-auth-cache" svn_binary String svn_info_args String, false # default value: "--no-auth-cache" svn_password String svn_username String timeout Integer user String, Integer action Symbol # defaults to :sync if not specified end ``` where: * `subversion` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `destination`, `environment`, `group`, `repository`, `revision`, `svn_arguments`, `svn_binary`, `svn_info_args`, `svn_password`, `svn_username`, `timeout`, and `user` are the properties available to this resource. Actions ------- --- The **subversion** resource has the following actions: `:checkout` Clone or check out the source. When a checkout is available, this provider does nothing. `:export` Export the source, excluding or removing any version control artifacts. `:force_export` Export the source, excluding or removing any version control artifacts and force an export of the source that is overwriting the existing copy (if it exists). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:sync` Update the source to the specified version, or get a new clone or checkout. This action causes a hard reset of the index and working tree, discarding any uncommitted changes. (default) Properties ---------- --- The **subversion** resource has the following properties: `destination` **Ruby Type:** String | **Default Value:** `The resource block's name` The location path to which the source is to be cloned, checked out, or exported. Default value: the name of the resource block. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of ({‘ENV_VARIABLE’ => ‘VALUE’}). `group` **Ruby Type:** String, Integer The system group that will own the checked-out code. `repository` **Ruby Type:** String The URI of the code repository. `revision` **Ruby Type:** String | **Default Value:** `HEAD` A branch, tag, or commit to be synchronized with git. This can be symbolic, like `HEAD` or it can be a source control management-specific revision identifier. `svn_arguments` **Ruby Type:** String, false | **Default Value:** `--no-auth-cache` The extra arguments that are passed to the Subversion command. `svn_binary` **Ruby Type:** String The location of the svn binary. `svn_info_args` **Ruby Type:** String, false | **Default Value:** `--no-auth-cache` Use when the `svn info` command is used by Chef Infra Client and arguments need to be passed. The `svn_arguments` command does not work when the `svn info` command is used. `svn_password` **Ruby Type:** String The password for a user that has access to the Subversion repository. `svn_username` **Ruby Type:** String The user name for a user that has access to the Subversion repository. `timeout` **Ruby Type:** Integer The amount of time (in seconds) to wait before timing out. `user` **Ruby Type:** String, Integer | **Default Value:** ``HOME` environment variable of the user running chef-client` The system user that will own the checked-out code. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **subversion** resource in recipes: **Get the latest version of an application** ``` subversion 'CouchDB Edge' do repository 'http://svn.apache.org/repos/asf/couchdb/trunk' revision 'HEAD' destination '/opt/my_sources/couch' action :sync end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/subversion/sysctl Resource =============== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [sysctl.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/sysctl.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **sysctl** resource to set or remove kernel parameters using the `sysctl` command line tool and configuration files in the system’s `sysctl.d` directory. Configuration files managed by this resource are named `99-chef-KEYNAME.conf`. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **sysctl** resource is: ``` sysctl 'name' do comment Array, String # default value: [] conf_dir String # default value: "/etc/sysctl.d" ignore_error true, false # default value: false key String # default value: 'name' unless specified value Array, String, Integer, Float action Symbol # defaults to :apply if not specified end ``` where: * `sysctl` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `comment`, `conf_dir`, `ignore_error`, `key`, and `value` are the properties available to this resource. Actions ------- --- The **sysctl** resource has the following actions: `:apply` Set the kernel parameter and update the `sysctl` settings. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove the kernel parameter and update the `sysctl` settings. Properties ---------- --- The **sysctl** resource has the following properties: `comment` **Ruby Type:** Array, String | **Default Value:** `[]` Comments, placed above the resource setting in the generated file. For multi-line comments, use an array of strings, one per line. New in Chef Infra Client 15.8 `conf_dir` **Ruby Type:** String | **Default Value:** `/etc/sysctl.d` The configuration directory to write the config to. `ignore_error` **Ruby Type:** true, false | **Default Value:** `false` Ignore any errors when setting the value on the command line. `key` **Ruby Type:** String | **Default Value:** `The resource block's name` The kernel parameter key in dotted format if it differs from the resource block’s name. `value` **Ruby Type:** Array, String, Integer, Float | `REQUIRED` The value to set. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **sysctl** resource in recipes: **Set vm.swappiness**: ``` sysctl 'vm.swappiness' do value 19 end ``` **Remove kernel.msgmax**: **Note**: This only removes the sysctl.d config for kernel.msgmax. The value will be set back to the kernel default value. ``` sysctl 'kernel.msgmax' do action :remove end ``` **Adding Comments to sysctl configuration files**: ``` sysctl 'vm.swappiness' do value 19 comment "define how aggressively the kernel will swap memory pages." end ``` This produces /etc/sysctl.d/99-chef-vm.swappiness.conf as follows: ``` # define how aggressively the kernel will swap memory pages. vm.swappiness = 1 ``` **Converting sysctl settings from shell scripts**: Example of existing settings: ``` fs.aio-max-nr = 1048576 net.ipv4.ip_local_port_range = 9000 65500 kernel.sem = 250 32000 100 128 ``` Converted to sysctl resources: ``` sysctl 'fs.aio-max-nr' do value '1048576' end sysctl 'net.ipv4.ip_local_port_range' do value '9000 65500' end sysctl 'kernel.sem' do value '250 32000 100 128' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/sysctl/systemd_unit Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [systemd_unit.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/systemd_unit.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **systemd_unit** resource to create, manage, and run [systemd units](https://www.freedesktop.org/software/systemd/man/systemd.html#Concepts). **New in Chef Infra Client 12.11.** Syntax ------ --- The full syntax for all of the properties that are available to the **systemd_unit** resource is: ``` systemd_unit 'name' do content String, Hash triggers_reload true, false # default value: true unit_name String # default value: 'name' unless specified user String verify true, false # default value: true action Symbol # defaults to :nothing if not specified end ``` where: * `systemd_unit` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `content`, `triggers_reload`, `unit_name`, `user`, and `verify` are the properties available to this resource. Actions ------- --- The **systemd_unit** resource has the following actions: `:create` Create a systemd unit file, if it does not already exist. `:delete` Delete a systemd unit file, if it exists. `:disable` Ensure the unit will not be started after the next system boot. `:enable` Ensure the unit will be started after the next system boot. `:mask` Ensure the unit will not start, even to satisfy dependencies. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:preset` Restore the preset ‘`enable`/`disable`’ configuration for a systemd unit. *New in Chef Infra Client 14.0.* `:reenable` Reenable a unit file. *New in Chef Infra Client 14.0.* `:reload` Reload the configuration file for a systemd unit. `:reload_or_restart` For systemd units that are services, this action reloads the configuration of the service without restarting, if possible; otherwise, it will restart the service so the new configuration is applied. `:reload_or_try_restart` For systemd units that are services, this action reloads the configuration of the service without restarting, if possible; otherwise, it will try to restart the service so the new configuration is applied. `:restart` Restart a systemd unit. `:revert` Revert to a vendor’s version of a systemd unit file. *New in Chef Infra Client 14.0.* `:start` Start a systemd unit. `:stop` Stop a running systemd unit. `:try_restart` Try to restart a systemd unit if the unit is running. `:unmask` Stop the unit from being masked and cause it to start as specified. Properties ---------- --- The **systemd_unit** resource has the following properties: `content` **Ruby Type:** String, Hash A string or hash that contains a systemd [unit file](https://www.freedesktop.org/software/systemd/man/systemd.unit.html) definition that describes the properties of systemd-managed entities, such as services, sockets, devices, and so on. In Chef Infra Client 14.4 or later, repeatable options can be implemented with an array. `triggers_reload` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether to trigger a daemon reload when creating or deleting a unit. `unit_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the unit file if it differs from the resource block’s name. New in Chef Client 13.7 `user` **Ruby Type:** String The user account that the systemd unit process is run under. The path to the unit for that user would be something like ‘/etc/systemd/user/sshd.service’. If no user account is specified, the systemd unit will run under a ‘system’ account, with the path to the unit being something like ‘/etc/systemd/system/sshd.service’. `verify` **Ruby Type:** true, false | **Default Value:** `true` Specifies if the unit will be verified before installation. Systemd can be overly strict when verifying units, so in certain cases it is preferable not to verify the unit. Unit file verification ---------------------- The unit file is verified via a `systemd-analyze verify` call before being written to disk. Be aware that the referenced commands and files need to already exist before verification. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **systemd_unit** resource in recipes: **Create systemd service unit file from a Hash** ``` systemd_unit 'etcd.service' do content({ Unit: { Description: 'Etcd', Documentation: ['https://coreos.com/etcd', 'man:etcd(1)'], After: 'network.target', }, Service: { Type: 'notify', ExecStart: '/usr/local/etcd', Restart: 'always', }, Install: { WantedBy: 'multi-user.target', } }) action [:create, :enable] end ``` **Create systemd service unit file from a String** ``` systemd_unit 'sysstat-collect.timer' do content <<~EOU [Unit] Description=Run system activity accounting tool every 10 minutes [Timer] OnCalendar=*:00/10 [Install] WantedBy=sysstat.service EOU action [:create, :enable] end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/systemd_unit/timezone Resource ================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [timezone.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/timezone.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **timezone** resource to change the system timezone on Windows, Linux, and macOS hosts. Timezones are specified in tz database format, with a complete list of available TZ values for Linux and macOS here: <https://en.wikipedia.org/wiki/List_of_tz_database_time_zones>. On Windows systems run `tzutil /l` for a complete list of valid timezones. **New in Chef Infra Client 14.6.** Syntax ------ --- The full syntax for all of the properties that are available to the **timezone** resource is: ``` timezone 'name' do timezone String # default value: 'name' unless specified action Symbol # defaults to :set if not specified end ``` where: * `timezone` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `timezone` is the property available to this resource. Actions ------- --- The **timezone** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set the system timezone. (default) Properties ---------- --- The **timezone** resource has the following properties: `timezone` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the timezone value if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **timezone** resource in recipes: **Set the timezone to UTC** ``` timezone 'UTC' ``` **Set the timezone to America/Los_Angeles with a friendly resource name on Linux/macOS** ``` timezone "Set the host's timezone to America/Los_Angeles" do timezone 'America/Los_Angeles' end ``` **Set the timezone to PST with a friendly resource name on Windows** ``` timezone "Set the host's timezone to PST" do timezone 'Pacific Standard time' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/timezone/windows_ad_join Resource ========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_ad_join.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_ad_join.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_ad_join** resource to join a Windows Active Directory domain. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_ad_join** resource is: ``` windows_ad_join 'name' do domain_name String # default value: 'name' unless specified domain_password String domain_user String new_hostname String ou_path String reboot Symbol # default value: :immediate reboot_delay Integer # default value: 0 workgroup_name String action Symbol # defaults to :join if not specified end ``` where: * `windows_ad_join` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `domain_name`, `domain_password`, `domain_user`, `new_hostname`, `ou_path`, `reboot`, `reboot_delay`, and `workgroup_name` are the properties available to this resource. Actions ------- --- The **windows_ad_join** resource has the following actions: `:join` Join the Active Directory domain. (default) `:leave` Leave an Active Directory domain and re-join a workgroup. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_ad_join** resource has the following properties: `domain_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the FQDN of the Active Directory domain to join if it differs from the resource block’s name. `domain_password` **Ruby Type:** String | `REQUIRED` The password for the domain user. Note that this resource is set to hide sensitive information by default. `domain_user` **Ruby Type:** String | `REQUIRED` The domain user that will be used to join the domain. `new_hostname` **Ruby Type:** String Specifies a new hostname for the computer in the new domain. New in Chef Client 14.5 `ou_path` **Ruby Type:** String The path to the Organizational Unit where the host will be placed. `reboot` **Ruby Type:** Symbol | **Default Value:** `:immediate` **Allowed Values:** `:delayed, :immediate, :never, :reboot_now, :request_reboot` Controls the system reboot behavior post domain joining. Reboot immediately, after the Chef Infra Client run completes, or never. Note that a reboot is necessary for changes to take effect. `reboot_delay` **Ruby Type:** Integer | **Default Value:** `0` The amount of time (in minutes) to delay a reboot request. New in Chef Infra Client 16.5 `workgroup_name` **Ruby Type:** String Specifies the name of a workgroup to which the computer is added to when it is removed from the domain. The default value is WORKGROUP. This property is only applicable to the :leave action. New in Chef Infra Client 15.4 Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_ad_join** resource in recipes: **Join a domain** ``` windows_ad_join 'ad.example.org' do domain_user 'nick' domain_password 'p@ssw0rd1' end ``` **Join a domain, as `win-workstation`** ``` windows_ad_join 'ad.example.org' do domain_user 'nick' domain_password 'p@ssw0rd1' new_hostname 'win-workstation' end ``` **Leave the current domain and re-join the `local` workgroup** ``` windows_ad_join 'Leave domain' do action :leave workgroup 'local' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_ad_join/user_ulimit Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [user_ulimit.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/user_ulimit.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **user_ulimit** resource to create individual ulimit files that are installed into the `/etc/security/limits.d/` directory. **New in Chef Infra Client 16.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **user_ulimit** resource is: ``` user_ulimit 'name' do core_hard_limit String, Integer core_limit String, Integer core_soft_limit String, Integer filehandle_hard_limit String, Integer filehandle_limit String, Integer filehandle_soft_limit String, Integer filename String memory_limit String, Integer process_hard_limit String, Integer process_limit String, Integer process_soft_limit String, Integer rtprio_hard_limit String, Integer rtprio_limit String, Integer rtprio_soft_limit String, Integer stack_hard_limit String, Integer stack_limit String, Integer stack_soft_limit String, Integer username String # default value: 'name' unless specified virt_limit String, Integer action Symbol # defaults to :create if not specified end ``` where: * `user_ulimit` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `core_hard_limit`, `core_limit`, `core_soft_limit`, `filehandle_hard_limit`, `filehandle_limit`, `filehandle_soft_limit`, `filename`, `memory_limit`, `process_hard_limit`, `process_limit`, `process_soft_limit`, `rtprio_hard_limit`, `rtprio_limit`, `rtprio_soft_limit`, `stack_hard_limit`, `stack_limit`, `stack_soft_limit`, `username`, and `virt_limit` are the properties available to this resource. Actions ------- --- The **user_ulimit** resource has the following actions: `:create` Create a ulimit configuration file. (default) `:delete` Delete an existing ulimit configuration file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **user_ulimit** resource has the following properties: `core_hard_limit` **Ruby Type:** String, Integer `core_limit` **Ruby Type:** String, Integer `core_soft_limit` **Ruby Type:** String, Integer `filehandle_hard_limit` **Ruby Type:** String, Integer `filehandle_limit` **Ruby Type:** String, Integer `filehandle_soft_limit` **Ruby Type:** String, Integer `filename` **Ruby Type:** String | **Default Value:** `lazy default` `memory_limit` **Ruby Type:** String, Integer `process_hard_limit` **Ruby Type:** String, Integer `process_limit` **Ruby Type:** String, Integer `process_soft_limit` **Ruby Type:** String, Integer `rtprio_hard_limit` **Ruby Type:** String, Integer `rtprio_limit` **Ruby Type:** String, Integer `rtprio_soft_limit` **Ruby Type:** String, Integer `stack_hard_limit` **Ruby Type:** String, Integer `stack_limit` **Ruby Type:** String, Integer `stack_soft_limit` **Ruby Type:** String, Integer `username` **Ruby Type:** String | **Default Value:** `The resource block's name` `virt_limit` **Ruby Type:** String, Integer Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **user_ulimit** resource in recipes: **Set filehandle limit for the tomcat user**: ``` user_ulimit 'tomcat' do filehandle_limit 8192 end ``` **Specify a username that differs from the name given to the resource block**: ``` user_ulimit 'Bump filehandle limits for tomcat user' do username 'tomcat' filehandle_limit 8192 end ``` **Set filehandle limit for the tomcat user with a non-default filename**: ``` user_ulimit 'tomcat' do filehandle_limit 8192 filename 'tomcat_filehandle_limits.conf' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/user_ulimit/windows_auto_run Resource =========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_auto_run.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_auto_run.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_auto_run** resource to set applications to run at login. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_auto_run** resource is: ``` windows_auto_run 'name' do args String path String program_name String # default value: 'name' unless specified root Symbol # default value: :machine action Symbol # defaults to :create if not specified end ``` where: * `windows_auto_run` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `args`, `path`, `program_name`, and `root` are the properties available to this resource. Actions ------- --- The **windows_auto_run** resource has the following actions: `:create` Create an item to be run at login. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an item that was previously configured to run at login. Properties ---------- --- The **windows_auto_run** resource has the following properties: `args` **Ruby Type:** String Any arguments to be used with the program. `path` **Ruby Type:** String The path to the program that will run at login. `program_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the program to run at login if it differs from the resource block’s name. `root` **Ruby Type:** Symbol | **Default Value:** `:machine` **Allowed Values:** `:machine, :user` The registry root key to put the entry under. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_auto_run** resource in recipes: **Run BGInfo at login** ``` windows_auto_run 'BGINFO' do program 'C:/Sysinternals/bginfo.exe' args ''C:/Sysinternals/Config.bgi' /NOLICPROMPT /TIMER:0' action :create end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_auto_run/user Resource ============= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [user.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/user.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **user** resource to add users, update existing users, remove users, and to lock/unlock user passwords. Note System attributes are collected by Ohai at the start of every Chef Infra Client run. By design, the actions available to the **user** resource are processed **after** the start of a Chef Infra Client run. This means that system attributes added or modified by the **user** resource during a Chef Infra Client run must be reloaded before they can be available to Chef Infra Client. These system attributes can be reloaded in two ways: by picking up the values at the start of the (next) Chef Infra Client run or by using the [ohai resource](../ohai/index) to reload the system attributes during the current Chef Infra Client run. Syntax ------ --- A **user** resource block manages users on a node: ``` user 'a user' do comment 'A random user' uid 1234 gid 'groupname' home '/home/random' shell '/bin/bash' password '$1$JJsvHslasdfjVEroftprNn4JHtDi' end ``` The full syntax for all of the properties that are available to the **user** resource is: ``` user 'name' do comment String force true, false # see description gid String, Integer home String iterations Integer manage_home true, false non_unique true, false password String salt String shell String system true, false uid String, Integer username String # defaults to 'name' if not specified action Symbol # defaults to :create if not specified end ``` where: * `user` is the resource * `name` is the name of the resource block * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `comment`, `force`, `gid`, `home`, `iterations`, `manage_home`, `non_unique`, `password`, `salt`, `shell`, `system`, `uid`, and `username` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **user** resource has the following actions: `:create` Default. Create a user with given properties. If a user already exists (but does not match), update that user to match. `:lock` Lock a user’s password. `:manage` Manage an existing user. This action does nothing if the user does not exist. `:modify` Modify an existing user. This action raises an exception if the user does not exist. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a user. `:unlock` Unlock a user’s password. Properties ---------- --- The **user** resource has the following properties: `comment` **Ruby Type:** String One (or more) comments about the user. `force` **Ruby Type:** true, false Force the removal of a user. May be used only with the `:remove` action. Warning Using this property may leave the system in an inconsistent state. For example, a user account will be removed even if the user is logged in. A user’s home directory will be removed, even if that directory is shared by multiple users. `gid` **Ruby Type:** String, Integer The identifier for the group. This property was previously named `group` and both continue to function. `home` **Ruby Type:** String The location of the home directory. `iterations` **Ruby Type:** Integer macOS platform only. The number of iterations for a password with a SALTED-SHA512-PBKDF2 shadow hash. `manage_home` **Ruby Type:** true, false Manage a user’s home directory. When used with the `:create` action, a user’s home directory is created based on `HOME_DIR`. If the home directory is missing, it is created unless `CREATE_HOME` in `/etc/login.defs` is set to `no`. When created, a skeleton set of files and subdirectories are included within the home directory. When used with the `:modify` action, a user’s home directory is moved to `HOME_DIR`. If the home directory is missing, it is created unless `CREATE_HOME` in `/etc/login.defs` is set to `no`. The contents of the user’s home directory are moved to the new location. `non_unique` **Ruby Type:** true, false Create a duplicate (non-unique) user account. `password` **Ruby Type:** String The password shadow hash `salt` **Ruby Type:** String A SALTED-SHA512-PBKDF2 hash. `shell` **Ruby Type:** String The login shell. `system` **Ruby Type:** true, false Create a system user. This property may be used with `useradd` as the provider to create a system user which passes the `-r` flag to `useradd`. `uid` **Ruby Type:** String, Integer The numeric user identifier. `username` **Ruby Type:** String The name of the user. Default value: the `name` of the resource block. See “Syntax” section above for more information. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **user** resource in recipes: Create a system user ``` user 'systemguy' do comment 'system guy' system true shell '/bin/false' end ``` Create a system user with a variable The following example shows how to create a system user. In this instance, the `home` value is calculated and stored in a variable called `user_home` which sets the user’s `home` attribute. ``` user_home = "/home/#{node['cookbook_name']['user']}" user node['cookbook_name']['user'] do gid node['cookbook_name']['group'] shell '/bin/bash' home user_home system true action :create end ``` Use SALTED-SHA512-PBKDF2 passwords macOS 10.8 (and higher) calculates the password shadow hash using SALTED-SHA512-PBKDF2. The length of the shadow hash value is 128 bytes, the salt value is 32 bytes, and an integer specifies the number of iterations. The following code will calculate password shadow hashes for macOS 10.8 (and higher): ``` password = 'my_awesome_password' salt = OpenSSL::Random.random_bytes(32) iterations = 25000 # Any value above 20k should be fine. shadow_hash = OpenSSL::PKCS5::pbkdf2_hmac( password, salt, iterations, 128, OpenSSL::Digest::SHA512.new ).unpack('H*').first salt_value = salt.unpack('H*').first ``` Use the calculated password shadow hash with the **user** resource: ``` user 'my_awesome_user' do password 'cbd1a....fc843' # Length: 256 salt 'bd1a....fc83' # Length: 64 iterations 25000 end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/user/windows_audit_policy Resource =============================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_audit_policy.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_audit_policy.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_audit_policy** resource to configure system level and per-user Windows advanced audit policy settings. **New in Chef Infra Client 16.2.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_audit_policy** resource is: ``` windows_audit_policy 'name' do audit_base_directories true, false audit_base_objects true, false crash_on_audit_fail true, false exclude_user String failure true, false full_privilege_auditing true, false include_user String subcategory String, Array success true, false action Symbol # defaults to :set if not specified end ``` where: * `windows_audit_policy` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `audit_base_directories`, `audit_base_objects`, `crash_on_audit_fail`, `exclude_user`, `failure`, `full_privilege_auditing`, `include_user`, `subcategory`, and `success` are the properties available to this resource. Actions ------- --- The **windows_audit_policy** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Configure an audit policy. (default) Properties ---------- --- The **windows_audit_policy** resource has the following properties: `audit_base_directories` **Ruby Type:** true, false Setting this audit policy option to true will force the system to assign a System Access Control List to named objects to enable auditing of container objects such as directories. `audit_base_objects` **Ruby Type:** true, false Setting this audit policy option to true will force the system to assign a System Access Control List to named objects to enable auditing of base objects such as mutexes. `crash_on_audit_fail` **Ruby Type:** true, false Setting this audit policy option to true will cause the system to crash if the auditing system is unable to log events. `exclude_user` **Ruby Type:** String The audit policy specified by the category or subcategory is applied per-user if specified. When a user is specified, exclude user. Include and exclude cannot be used at the same time. `failure` **Ruby Type:** true, false Specify failure auditing. By setting this property to true the resource will enable failure for the category or sub category. Success is the default and is applied if neither success nor failure are specified. `full_privilege_auditing` **Ruby Type:** true, false Setting this audit policy option to true will force the audit of all privilege changes except SeAuditPrivilege. Setting this property may cause the logs to fill up more quickly. `include_user` **Ruby Type:** String The audit policy specified by the category or subcategory is applied per-user if specified. When a user is specified, include user. Include and exclude cannot be used at the same time. `subcategory` **Ruby Type:** String, Array The audit policy subcategory, specified by GUID or name. Applied system-wide if no user is specified. `success` **Ruby Type:** true, false Specify success auditing. By setting this property to true the resource will enable success for the category or sub category. Success is the default and is applied if neither success nor failure are specified. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_audit_policy** resource in recipes: **Set Logon and Logoff policy to “Success and Failure”**: ``` windows_audit_policy "Set Audit Policy for 'Logon and Logoff' actions to 'Success and Failure'" do subcategory %w(Logon Logoff) success true failure true action :set end ``` **Set Credential Validation policy to “Success”**: ``` windows_audit_policy "Set Audit Policy for 'Credential Validation' actions to 'Success'" do subcategory 'Credential Validation' success true failure false action :set end ``` **Enable CrashOnAuditFail option**: ``` windows_audit_policy 'Enable CrashOnAuditFail option' do crash_on_audit_fail true action :set end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_audit_policy/template Resource ================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [template.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/template.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- A cookbook template is an Embedded Ruby (ERB) template that is used to dynamically generate static text files. Templates may contain Ruby expressions and statements, and are a great way to manage configuration files. Use the **template** resource to add cookbook templates to recipes; place the corresponding Embedded Ruby (ERB) template file in a cookbook’s `/templates` directory. Use the **template** resource to manage the contents of a file using an Embedded Ruby (ERB) template by transferring files from a sub-directory of `COOKBOOK_NAME/templates/` to a specified path located on a host that is running Chef Infra Client. This resource includes actions and properties from the **file** resource. Template files managed by the **template** resource follow the same file specificity rules as the **remote_file** and **file** resources. Syntax ------ --- A **template** resource block typically declares the location in which a file is to be created, the source template that will be used to create the file, and the permissions needed on that file. For example: ``` template '/etc/motd' do source 'motd.erb' owner 'root' group 'root' mode '0755' end ``` where: * `'/etc/motd'` specifies the location in which the file is created * `'motd.erb'` specifies the name of a template that exists in in the `/templates` folder of a cookbook * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **template** resource is: ``` template 'name' do atomic_update true, false backup false, Integer cookbook String force_unlink true, false group String, Integer helper(:method) Method { String } # see Helpers below helpers(module) Module # see Helpers below inherits true, false local true, false manage_symlink_source true, false mode String, Integer owner String, Integer path String # defaults to 'name' if not specified rights Hash sensitive true, false source String, Array variables Hash verify String, Block action Symbol # defaults to :create if not specified end ``` where: * `template` is the resource * `name` is the name of the resource block, typically the path to the location in which a file is created *and also* the name of the file to be managed. For example: `/var/www/html/index.html`, where `/var/www/html/` is the fully qualified path to the location and `index.html` is the name of the file * `source` is the template file that will be used to create the file on the node, for example: `index.html.erb`; the template file is located in the `/templates` directory of a cookbook * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `atomic_update`, `backup`, `cookbook`, `force_unlink`, `group`, `helper`, `helpers`, `inherits`, `local`, `manage_symlink_source`, `mode`, `owner`, `path`, `rights`, `source`, `variables`, and `verify` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **template** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the **file** resource.) Properties ---------- --- The **template** resource has the following properties: `atomic_update` **Ruby Type:** true, false Perform atomic file updates on a per-resource basis. Set to `true` for atomic file updates. Set to `false` for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the client.rb file. `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `cookbook` **Ruby Type:** String The cookbook in which a file is located (if it is not located in the current cookbook). The default value is the current cookbook. `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `helper` **Ruby Type:** Method | **Default Value:** `{}` Define a helper method inline. For example: `helper(:hello_world) { "hello world" }` or `helper(:app) { node["app"] }` or `helper(:app_conf) { |setting| node["app"][setting] }`. `helpers` **Ruby Type:** Module | **Default Value:** `[]` Define a helper module inline or in a library. For example, an inline module: `helpers do`, which is then followed by a block of Ruby code. And for a library module: `helpers(MyHelperModule)`. `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `local` **Ruby Type:** true, false | **Default Value:** `false` Load a template from a local path. By default, Chef Infra Client loads templates from a cookbook’s `/templates` directory. When this property is set to `true`, use the `source` property to specify the path to a template on the local node. `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `true`, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `false`, Chef will follow the symlink and will manage the permissions and content of the symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The full path to the file, including the file name and its extension. Microsoft Windows: A path that begins with a forward slash (`/`) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (`/`) is not recommended. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String, Array The location of a template file. By default, Chef Infra Client looks for a template file in the `/templates` directory of a cookbook. When the `local` property is set to `true`, use to specify the path to a template on the local node. This property may also be used to distribute specific files to specific platforms. See “File Specificity” below for more information. Default value: the `name` of the resource block. See “Syntax” section above for more information. `variables` **Ruby Type:** Hash A Hash of variables that are passed into a Ruby template file. The `variables` property of the **template** resource can be used to reference a partial template file by using a Hash. For example: ``` template '/file/name.txt' do variables partials: { 'partial_name_1.txt.erb' => 'message', 'partial_name_2.txt.erb' => 'message', 'partial_name_3.txt.erb' => 'message', } end ``` where each of the partial template files can then be combined using normal Ruby template patterns within a template file, such as: ``` <% @partials.each do |partial, message| %> Here is <%= partial %> <%= render partial, :variables => {:message => message} %> <% end %``` `verify` **Ruby Type:** String, Block A block or a string that returns `true` or `false`. A string, when `true` is executed as a system command. A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block is `true`, Chef Infra Client will continue to update the file as appropriate. For example, this should return `true`: ``` template '/tmp/baz' do verify { 1 == 1 } end ``` This should return `true`: ``` template '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` This should return `true`: ``` template '/tmp/bar' do verify { 1 == 1} end ``` And this should return `true`: ``` template '/tmp/foo' do verify do |path| true end end ``` Whereas, this should return `false`: ``` template '/tmp/turtle' do verify '/usr/bin/false' end ``` If a string or a block return `false`, the Chef Infra Client run will stop and an error is returned. ### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. ### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. Using Templates --------------- To use a template, two things must happen: 1. A template resource must be added to a recipe 2. An Embedded Ruby (ERB) template must be added to a cookbook For example, the following template file and template resource settings can be used to manage a configuration file named `/etc/sudoers`. Within a cookbook that uses sudo, the following resource could be added to `/recipes/default.rb`: ``` template '/etc/sudoers' do source 'sudoers.erb' mode '0440' owner 'root' group 'root' variables(sudoers_groups: node['authorization']['sudo']['groups'], sudoers_users: node['authorization']['sudo']['users']) end ``` And then create a template called `sudoers.erb` and save it to `templates/default/sudoers.erb`: ``` # # /etc/sudoers # # Generated by Chef for <%= node['fqdn'] %> # Defaults !lecture,tty_tickets,!fqdn # User privilege specification root ALL=(ALL) ALL <% @sudoers_users.each do |user| -%> <%= user %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% end -%> # Members of the sysadmin group may gain root privileges %sysadmin ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% @sudoers_groups.each do |group| -%> # Members of the group '<%= group %>' may gain root privileges <%= group %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% end -%``` And then set the default attributes in `attributes/default.rb`: ``` default['authorization']['sudo']['groups'] = %w(sysadmin wheel admin) default['authorization']['sudo']['users'] = %w(jerry greg) ``` ### File Specificity A cookbook is frequently designed to work across many platforms and is often required to distribute a specific template to a specific platform. A cookbook can be designed to support the distribution of templates across platforms, while ensuring that the correct template ends up on each system. The pattern for template specificity depends on two things: the lookup path and the source. The first pattern that matches is used: 1. `/host-$fqdn/$source` 2. `/$platform-$platform_version/$source` 3. `/$platform/$source` 4. `/default/$source` 5. `/$source` Note To specify a particular Windows version, use the [operating system version number](https://docs.microsoft.com/en-us/windows/win32/sysinfo/operating-system-version). For example, a template in `templates/windows-6.3` will be deployed on systems installed with Windows 8.1. Use an array with the `source` property to define an explicit lookup path. For example: ``` template '/test' do source ["#{node.chef_environment}.erb", 'default.erb'] end ``` The following example emulates the entire file specificity pattern by defining it as an explicit path: ``` template '/test' do source %W( host-#{node['fqdn']}/test.erb #{node['platform']}-#{node['platform_version']}/test.erb #{node['platform']}/test.erb default/test.erb ) end ``` A cookbook may have a `/templates` directory structure like this: ``` /templates/ windows-10 windows-6.3 windows default ``` and a resource that looks something like the following: ``` template 'C:\path\to\file\text_file.txt' do source 'text_file.txt' mode '0755' owner 'root' group 'root' end ``` This resource would be matched in the same order as the `/templates` directory structure. For a node named `host-node-desktop` that is running Windows 8.1, the second item would be the matching item and the location: ``` /templates windows-10/text_file.txt windows-6.3/text_file.txt windows/text_file.txt default/text_file.txt ``` ### Helpers A helper is a method or a module that can be used to extend a template. There are three approaches: * An inline helper method * An inline helper module * A cookbook library module Use the `helper` attribute in a recipe to define an inline helper method. Use the `helpers` attribute to define an inline helper module or a cookbook library module. #### Inline Methods A template helper method is always defined inline on a per-resource basis. A simple example: ``` template '/path' do helper(:hello_world) { 'hello world' } end ``` Another way to define an inline helper method is to reference a node object so that repeated calls to one (or more) cookbook attributes can be done efficiently: ``` template '/path' do helper(:app) { node['app'] } end ``` An inline helper method can also take arguments: ``` template '/path' do helper(:app_conf) { |setting| node['app'][setting] } end ``` Once declared, a template can then use the helper methods to build a file. For example: ``` Say hello: <%= hello_world %``` or: ``` node['app']['listen_port'] is: <%= app['listen_port'] %``` or: ``` node['app']['log_location'] is: <%= app_conf('log_location') %``` #### Inline Modules A template helper module can be defined inline on a per-resource basis. This approach can be useful when a template requires more complex information. For example: ``` template '/path' do helpers do def hello_world 'hello world' end def app node['app'] end def app_conf(setting) node['app']['setting'] end end end ``` where the `hello_world`, `app`, and `app_conf(setting)` methods comprise the module that extends a template. #### Library Modules A template helper module can be defined in a library. This is useful when extensions need to be reused across recipes or to make it easier to manage code that would otherwise be defined inline on a per-recipe basis. ``` template '/path/to/template.erb' do helpers(MyHelperModule) end ``` ### Host Notation The naming of folders within cookbook directories must literally match the host notation used for template specificity matching. For example, if a host is named `foo.example.com`, then the folder must be named `host-foo.example.com`. ### Partial Templates A template can be built in a way that allows it to contain references to one (or more) smaller template files. (These smaller template files are also referred to as partials.) A partial can be referenced from a template file in one of the following ways: * By using the `render` method in the template file * By using the **template** resource and the `variables` property. #### render Method Use the `render` method in a template to reference a partial template file: ``` <%= render 'partial_name.txt.erb', :option => {} %``` where `partial_name` is the name of the partial template file and `:option` is one (or more) of the following: | Option | Description | | --- | --- | | `:cookbook` | By default, a partial template file is assumed to be located in the cookbook that contains the top-level template. Use this option to specify the path to a different cookbook | | `:local` | Indicates that the name of the partial template file should be interpreted as a path to a file in the local file system or looked up in a cookbook using the normal rules for template files. Set to `true` to interpret as a path to a file in the local file system and to `false` to use the normal rules for template files | | `:source` | By default, a partial template file is identified by its file name. Use this option to specify a different name or a local path to use (instead of the name of the partial template file) | | `:variables` | A hash of `variable_name => value` that will be made available to the partial template file. When this option is used, any variables that are defined in the top-level template that are required by the partial template file must have them defined explicitly using this option | For example: ``` <%= render 'simple.txt.erb', :variables => {:user => Etc.getlogin }, :local => true %``` ### Transfer Frequency The Chef Infra Client caches a template when it is first requested. On each subsequent request for that template, the Chef Infra Client compares that request to the template located on the Chef Infra Server. If the templates are the same, no transfer occurs. ### Variables An Embedded Ruby (ERB) template allows Ruby code to be embedded inside a text file within specially formatted tags. Ruby code can be embedded using expressions and statements. An expression is delimited by `<%=` and `%>`. For example: ``` <%= "my name is #{$ruby}" %``` A statement is delimited by a modifier, such as `if`, `elsif`, and `else`. For example: ``` if false # this won't happen elsif nil # this won't either end ``` Using a Ruby expression is the most common approach for defining template variables because this is how all variables that are sent to a template are referenced. Whenever a template needs to use an `each`, `if`, or `end`, use a Ruby statement. When a template is rendered, Ruby expressions and statements are evaluated by Chef Infra Client. The variables listed in the **template** resource’s `variables` parameter and in the node object are evaluated. Chef Infra Client then passes these variables to the template, where they will be accessible as instance variables within the template. The node object can be accessed just as if it were part of a recipe, using the same syntax. For example, a simple template resource like this: ``` node['fqdn'] = 'latte' template '/tmp/foo' do source 'foo.erb' variables(x_men: 'are keen') end ``` And a simple Embedded Ruby (ERB) template like this: ``` The node <%= node[:fqdn] %> thinks the x-men <%= @x_men %``` Would render something like: ``` The node latte thinks the x-men are keen ``` Even though this is a very simple example, the full capabilities of Ruby can be used to tackle even the most complex and demanding template requirements. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **template** resource in recipes: Configure a file from a template ``` template '/tmp/config.conf' do source 'config.conf.erb' end ``` Configure a file from a local template ``` template '/tmp/config.conf' do local true source '/tmp/config.conf.erb' end ``` Configure a file using a variable map ``` template '/tmp/config.conf' do source 'config.conf.erb' variables( :config_var => node['configs']['config_var'] ) end ``` Use the not_if condition The following example shows how to use the `not_if` condition to create a file based on a template and using the presence of an attribute value on the node to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if { node['some_value'] } end ``` The following example shows how to use the `not_if` condition to create a file based on a template and then Ruby code to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if do File.exist?('/etc/passwd') end end ``` The following example shows how to use the `not_if` condition to create a file based on a template and using a Ruby block (with curly braces) to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if { File.exist?('/etc/passwd') } end ``` The following example shows how to use the `not_if` condition to create a file based on a template and using a string to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if 'test -f /etc/passwd' end ``` Use the only_if condition The following example shows how to use the `only_if` condition to create a file based on a template and using the presence of an attribute on the node to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if { node['some_value'] } end ``` The following example shows how to use the `only_if` condition to create a file based on a template, and then use Ruby to specify a condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if { ! ::File.exist?('/etc/passwd') } end ``` The following example shows how to use the `only_if` condition to create a file based on a template and using a string to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if 'test -f /etc/passwd' end ``` Use a whitespace array (%w) The following example shows how to use a Ruby whitespace array to define a list of configuration tools, and then use that list of tools within the **template** resource to ensure that all of these configuration tools are using the same RSA key: ``` %w{openssl.cnf pkitool vars Rakefile}.each do |f| template "/etc/openvpn/easy-rsa/#{f}" do source "#{f}.erb" owner 'root' group 'root' mode '0755' end end ``` Use a relative path ``` template "#{ENV['HOME']}/chef-getting-started.txt" do source 'chef-getting-started.txt.erb' mode '0755' end ``` Delay notifications ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :delayed end ``` Notify immediately By default, notifications are `:delayed`, that is they are queued up as they are triggered, and then executed at the very end of a Chef Infra Client run. To run an action immediately, use `:immediately`: ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :immediately end ``` and then Chef Infra Client would immediately run the following: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing end ``` Notify multiple resources ``` template '/etc/chef/server.rb' do source 'server.rb.erb' owner 'root' group 'root' mode '0755' notifies :restart, 'service[chef-solr]', :delayed notifies :restart, 'service[chef-solr-indexer]', :delayed notifies :restart, 'service[chef-server]', :delayed end ``` Reload a service ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' notifies :reload, 'service[apache]', :immediately end ``` Restart a service when a template is modified ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :immediately end ``` Send notifications to multiple resources To send notifications to multiple resources, just use multiple attributes. Multiple attributes will get sent to the notified resources in the order specified. ``` template '/etc/netatalk/netatalk.conf' do notifies :restart, 'service[afpd]', :immediately notifies :restart, 'service[cnid]', :immediately end service 'afpd' service 'cnid' ``` Execute a command using a template The following example shows how to set up IPv4 packet forwarding using the **execute** resource to run a command named `forward_ipv4` that uses a template defined by the **template** resource: ``` execute 'forward_ipv4' do command 'echo > /proc/.../ipv4/ip_forward' action :nothing end template '/etc/file_name.conf' do source 'routing/file_name.conf.erb' notifies :run, 'execute[forward_ipv4]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[forward_ipv4]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. Set an IP address using variables and a template The following example shows how the **template** resource can be used in a recipe to combine settings stored in an attributes file, variables within a recipe, and a template to set the IP addresses that are used by the Nginx service. The attributes file contains the following: ``` default['nginx']['dir'] = '/etc/nginx' ``` The recipe then does the following to: * Declare two variables at the beginning of the recipe, one for the remote IP address and the other for the authorized IP address * Use the **service** resource to restart and reload the Nginx service * Load a template named `authorized_ip.erb` from the `/templates` directory that is used to set the IP address values based on the variables specified in the recipe ``` node.default['nginx']['remote_ip_var'] = 'remote_addr' node.default['nginx']['authorized_ips'] = ['127.0.0.1/32'] service 'nginx' do supports :status => true, :restart => true, :reload => true end template 'authorized_ip' do path "#{node['nginx']['dir']}/authorized_ip" source 'modules/authorized_ip.erb' owner 'root' group 'root' mode '0755' variables( :remote_ip_var => node['nginx']['remote_ip_var'], :authorized_ips => node['nginx']['authorized_ips'] ) notifies :reload, 'service[nginx]', :immediately end ``` where the `variables` property tells the template to use the variables set at the beginning of the recipe and the `source` property is used to call a template file located in the cookbook’s `/templates` directory. The template file looks similar to: ``` geo $<%= @remote_ip_var %> $authorized_ip { default no; <% @authorized_ips.each do |ip| %> <%= "#{ip} yes;" %> <% end %> } ``` Add a rule to an IP table The following example shows how to add a rule named `test_rule` to an IP table using the **execute** resource to run a command using a template that is defined by the **template** resource: ``` execute 'test_rule' do command 'command_to_run --option value ... --option value --source #{node[:name_of_node][:ipsec][:local][:subnet]} -j test_rule' action :nothing end template '/etc/file_name.local' do source 'routing/file_name.local.erb' notifies :run, 'execute[test_rule]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[test_rule]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. Apply proxy settings consistently across a Chef organization The following example shows how a template can be used to apply consistent proxy settings for all nodes of the same type: ``` template "#{node['matching_node']['dir']}/sites-available/site_proxy.conf" do source 'site_proxy.matching_node.conf.erb' owner 'root' group 'root' mode '0755' variables( :ssl_certificate => "#{node['matching_node']['dir']}/shared/certificates/site_proxy.crt", :ssl_key => "#{node['matching_node']['dir']}/shared/certificates/site_proxy.key", :listen_port => node['site']['matching_node_proxy']['listen_port'], :server_name => node['site']['matching_node_proxy']['server_name'], :fqdn => node['fqdn'], :server_options => node[:site]['matching_node']['server']['options'], :proxy_options => node[:site]['matching_node']['proxy']['options'] ) end ``` where `matching_node` represents a type of node (like Nginx) and `site_proxy` represents the type of proxy being used for that type of node (like Nexus). Get template settings from a local file The **template** resource can be used to render a template based on settings contained in a local file on disk or to get the settings from a template in a cookbook. Most of the time, the settings are retrieved from a template in a cookbook. The following example shows how the **template** resource can be used to retrieve these settings from a local file. The following example is based on a few assumptions: * The environment is a Ruby on Rails application that needs render a file named `database.yml` * Information about the application—the user, their password, the server—is stored in a data bag on the Chef server * The application is already deployed to the system and that only requirement in this example is to render the `database.yml` file The application source tree looks something like: ``` myapp/ -> config/ -> database.yml.erb ``` Note There should not be a file named `database.yml` (without the `.erb`), as the `database.yml` file is what will be rendered using the **template** resource. The deployment of the app will end up in `/srv`, so the full path to this template would be something like `/srv/myapp/current/config/database.yml.erb`. The content of the template itself may look like this: ``` <%= @rails_env %>: adapter: <%= @adapter %> host: <%= @host %> database: <%= @database %> username: <%= @username %> password: <%= @password %> encoding: 'utf8' reconnect: true ``` The recipe will be similar to the following: ``` results = search(:node, "role:myapp_database_master AND chef_environment:#{node.chef_environment}") db_master = results[0] template '/srv/myapp/shared/database.yml' do source '/srv/myapp/current/config/database.yml.erb' local true variables( :rails_env => node.chef_environment, :adapter => db_master['myapp']['db_adapter'], :host => db_master['fqdn'], :database => "myapp_#{node.chef_environment}", :username => "myapp", :password => "SUPERSECRET", ) end ``` where: * the `search` method in the Chef Infra Language is used to find the first node that is the database master (of which there should only be one) * the `:adapter` variable property may also require an attribute to have been set on a role, which then determines the correct adapter The template will render similar to the following: ``` production: adapter: mysql host: domU-12-31-39-14-F1-C3.compute-1.internal database: myapp_production username: myapp password: SUPERSECRET encoding: utf8 reconnect: true ``` This example showed how to use the **template** resource to render a template based on settings contained in a local file. Some other issues that should be considered when using this type of approach include: * Should the `database.yml` file be in a `.gitignore` file? * How do developers run the application locally? * Does this work with chef-solo? Pass values from recipe to template The following example shows how pass a value to a template using the `variables` property in the **template** resource. The template file is similar to: ``` [tcpout] defaultGroup = splunk_indexers_<%= node['splunk']['receiver_port'] %> disabled=false [tcpout:splunk_indexers_<%= node['splunk']['receiver_port'] %>] server=<% @splunk_servers.map do |s| -%><%= s['ipaddress'] %>:<%= s['splunk']['receiver_port'] %> <% end.join(', ') -%> <% @outputs_conf.each_pair do |name, value| -%> <%= name %> = <%= value %> <% end -%``` The recipe then uses the `variables` attribute to find the values for `splunk_servers` and `outputs_conf`, before passing them into the template: ``` template "#{splunk_dir}/etc/system/local/outputs.conf" do source 'outputs.conf.erb' mode '0755' variables :splunk_servers => splunk_servers, :outputs_conf => node['splunk']['outputs_conf'] notifies :restart, 'service[splunk]' end ``` This example can be found in the `client.rb` recipe and the `outputs.conf.erb` template files that are located in the [chef-splunk cookbook](https://github.com/chef-cookbooks/chef-splunk/) that is maintained by Chef. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/template/windows_certificate Resource ============================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_certificate.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_certificate.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_certificate** resource to install a certificate into the Windows certificate store from a file. The resource grants read-only access to the private key for designated accounts. Due to current limitations in WinRM, installing certificates remotely may not work if the operation requires a user profile. Operations on the local machine store should still work. **New in Chef Infra Client 14.7.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_certificate** resource is: ``` windows_certificate 'name' do exportable true, false # default value: false output_path String pfx_password String private_key_acl Array source String # default value: 'name' unless specified store_name String # default value: "MY" user_store true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_certificate` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `exportable`, `output_path`, `pfx_password`, `private_key_acl`, `source`, `store_name`, and `user_store` are the properties available to this resource. Actions ------- --- The **windows_certificate** resource has the following actions: `:acl_add` Adds read-only entries to a certificate’s private key ACL. `:create` Creates or updates a certificate. (default) `:delete` Deletes a certificate. `:fetch` Fetches a certificate. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:verify` Verifies a certificate and logs the result. Properties ---------- --- The **windows_certificate** resource has the following properties: `exportable` **Ruby Type:** true, false | **Default Value:** `false` Ensure that imported pfx certificate is exportable. Please provide ‘true’ if you want the certificate to be exportable. New in Chef Infra Client 16.8 `output_path` **Ruby Type:** String A path on the node where a certificate object (PFX, PEM, CER, KEY, etc) can be exported to. New in Chef Infra Client 17.0 `pfx_password` **Ruby Type:** String The password to access the object with if it is a PFX file. `private_key_acl` **Ruby Type:** Array An array of ‘domain\account’ entries to be granted read-only access to the certificate’s private key. Not idempotent. `source` **Ruby Type:** String | **Default Value:** `The resource block's name` The source file (for `create` and `acl_add`), thumbprint (for `delete`, `export`, and `acl_add`), or subject (for `delete` or `export`) if it differs from the resource block’s name. `store_name` **Ruby Type:** String | **Default Value:** `MY` **Allowed Values:** `"AUTHROOT", "CA", "CLIENTAUTHISSUER", "DISALLOWED", "MY", "REMOTE DESKTOP", "ROOT", "SMARTCARDROOT", "TRUST", "TRUSTEDDEVICES", "TRUSTEDPEOPLE", "TRUSTEDPUBLISHER", "TrustedPublisher", "WEBHOSTING"` The certificate store to manipulate. `user_store` **Ruby Type:** true, false | **Default Value:** `false` Use the `CurrentUser` store instead of the default `LocalMachine` store. Note Prior to chef-client. 16.10 this property was ignored. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_certificate** resource in recipes: **Add PFX cert to local machine personal store and grant accounts read-only access to private key** ``` windows_certificate 'c:/test/mycert.pfx' do pfx_password 'password' private_key_acl ["acme\fred", "pc\jane"] end ``` **Add cert to trusted intermediate store** ``` windows_certificate 'c:/test/mycert.cer' do store_name 'CA' end ``` **Remove all certificates matching the subject** ``` windows_certificate 'me.acme.com' do action :delete end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_certificate/windows_dfs_folder Resource ============================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_dfs_folder.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_dfs_folder.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_dfs_folder** resource to creates a folder within DFS as many levels deep as required. **New in Chef Infra Client 15.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_dfs_folder** resource is: ``` windows_dfs_folder 'name' do description String folder_path String # default value: 'name' unless specified namespace_name String target_path String action Symbol # defaults to :create if not specified end ``` where: * `windows_dfs_folder` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `description`, `folder_path`, `namespace_name`, and `target_path` are the properties available to this resource. Actions ------- --- The **windows_dfs_folder** resource has the following actions: `:create` Creates the folder in dfs namespace. (default) `:delete` Deletes the folder in the dfs namespace. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_dfs_folder** resource has the following properties: `description` **Ruby Type:** String Description for the share. `folder_path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the path of the dfs folder if it differs from the resource block’s name. `namespace_name` **Ruby Type:** String | `REQUIRED` The namespace this should be created within. `target_path` **Ruby Type:** String The target that this path will connect you to. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_dfs_folder/windows_dfs_server Resource ============================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_dfs_server.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_dfs_server.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_dfs_server** resource to set system-wide DFS settings. **New in Chef Infra Client 15.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_dfs_server** resource is: ``` windows_dfs_server 'name' do enable_site_costed_referrals true, false # default value: false ldap_timeout_secs Integer # default value: 30 prefer_login_dc true, false # default value: false sync_interval_secs Integer # default value: 3600 use_fqdn true, false # default value: false action Symbol # defaults to :configure if not specified end ``` where: * `windows_dfs_server` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `enable_site_costed_referrals`, `ldap_timeout_secs`, `prefer_login_dc`, `sync_interval_secs`, and `use_fqdn` are the properties available to this resource. Actions ------- --- The **windows_dfs_server** resource has the following actions: `:configure` Configure DFS settings (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_dfs_server** resource has the following properties: `enable_site_costed_referrals` **Ruby Type:** true, false | **Default Value:** `false` `ldap_timeout_secs` **Ruby Type:** Integer | **Default Value:** `30` `prefer_login_dc` **Ruby Type:** true, false | **Default Value:** `false` `sync_interval_secs` **Ruby Type:** Integer | **Default Value:** `3600` `use_fqdn` **Ruby Type:** true, false | **Default Value:** `false` Indicates whether a DFS namespace server uses FQDNs in referrals. If this property is set to true, the server uses FQDNs in referrals. If this property is set to false then the server uses NetBIOS names. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_dfs_server/windows_dns_record Resource ============================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_dns_record.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_dns_record.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- The windows_dns_record resource creates a DNS record for the given domain. **New in Chef Infra Client 15.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_dns_record** resource is: ``` windows_dns_record 'name' do dns_server String # default value: "localhost" record_name String # default value: 'name' unless specified record_type String # default value: "ARecord" target String zone String action Symbol # defaults to :create if not specified end ``` where: * `windows_dns_record` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `dns_server`, `record_name`, `record_type`, `target`, and `zone` are the properties available to this resource. Actions ------- --- The **windows_dns_record** resource has the following actions: `:create` Creates and updates the DNS entry. (default) `:delete` Deletes a DNS entry. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_dns_record** resource has the following properties: `dns_server` **Ruby Type:** String | **Default Value:** `localhost` The name of the DNS server on which to create the record. New in Chef Infra Client 16.3 `record_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the dns record name if it differs from the resource block’s name. `record_type` **Ruby Type:** String | **Default Value:** `ARecord` **Allowed Values:** `"ARecord", "CNAME", "PTR"` The type of record to create, can be either ARecord, CNAME or PTR. `target` **Ruby Type:** String | `REQUIRED` The target for the record. `zone` **Ruby Type:** String | `REQUIRED` The zone to create the record in. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_dns_record/windows_dfs_namespace Resource ================================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_dfs_namespace.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_dfs_namespace.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_dfs_namespace** resource to creates a share and DFS namespace on a Windows server. **New in Chef Infra Client 15.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_dfs_namespace** resource is: ``` windows_dfs_namespace 'name' do change_users Array # default value: [] description String full_users Array # default value: ["BUILTIN\\administrators"] namespace_name String # default value: 'name' unless specified read_users Array # default value: [] root String # default value: "C:\\DFSRoots" action Symbol # defaults to :create if not specified end ``` where: * `windows_dfs_namespace` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `change_users`, `description`, `full_users`, `namespace_name`, `read_users`, and `root` are the properties available to this resource. Actions ------- --- The **windows_dfs_namespace** resource has the following actions: `:create` Creates the dfs namespace on the server. (default) `:delete` Deletes a DFS Namespace including the directory on disk. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_dfs_namespace** resource has the following properties: `change_users` **Ruby Type:** Array | **Default Value:** `[]` Determines which users should have change access to the share. `description` **Ruby Type:** String | `REQUIRED` Description of the share. `full_users` **Ruby Type:** Array | **Default Value:** `["BUILTIN\\administrators"]` Determines which users should have full access to the share. `namespace_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the dfs namespace if it differs from the resource block’s name. `read_users` **Ruby Type:** Array | **Default Value:** `[]` Determines which users should have read access to the share. `root` **Ruby Type:** String | **Default Value:** `C:\DFSRoots` The root from which to create the DFS tree. Defaults to C:\DFSRoots. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_dfs_namespace/windows_defender Resource ========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_defender.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_defender.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_defender** resource to enable or disable the Microsoft Windows Defender service. **New in Chef Infra Client 17.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_defender** resource is: ``` windows_defender 'name' do intrusion_protection_system true, false # default value: true lock_ui true, false # default value: false realtime_protection true, false # default value: true scan_archives true, false # default value: true scan_email true, false # default value: false scan_mapped_drives true, false # default value: true scan_network_files true, false # default value: false scan_removable_drives true, false # default value: false scan_scripts true, false # default value: false action Symbol # defaults to :enable if not specified end ``` where: * `windows_defender` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `intrusion_protection_system`, `lock_ui`, `realtime_protection`, `scan_archives`, `scan_email`, `scan_mapped_drives`, `scan_network_files`, `scan_removable_drives`, and `scan_scripts` are the properties available to this resource. Actions ------- --- The **windows_defender** resource has the following actions: `:disable` Disable Windows Defender. `:enable` Enable and configure Windows Defender. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_defender** resource has the following properties: `intrusion_protection_system` **Ruby Type:** true, false | **Default Value:** `true` Enable network protection against exploitation of known vulnerabilities. `lock_ui` **Ruby Type:** true, false | **Default Value:** `false` Lock the UI to prevent users from changing Windows Defender settings. `realtime_protection` **Ruby Type:** true, false | **Default Value:** `true` Enable realtime scanning of downloaded files and attachments. `scan_archives` **Ruby Type:** true, false | **Default Value:** `true` Scan file archives such as .zip or .gz archives. `scan_email` **Ruby Type:** true, false | **Default Value:** `false` Scan e-mails for malware. `scan_mapped_drives` **Ruby Type:** true, false | **Default Value:** `true` Scan files on mapped network drives. `scan_network_files` **Ruby Type:** true, false | **Default Value:** `false` Scan files on a network. `scan_removable_drives` **Ruby Type:** true, false | **Default Value:** `false` Scan content of removable drives. `scan_scripts` **Ruby Type:** true, false | **Default Value:** `false` Scan scripts in malware scans. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_defender** resource in recipes: **Configure Windows Defender AV settings**: ``` windows_defender 'Configure Defender' do realtime_protection true intrusion_protection_system true lock_ui true scan_archives true scan_scripts true scan_email true scan_removable_drives true scan_network_files false scan_mapped_drives false action :enable end ``` **Disable Windows Defender AV**: ``` windows_defender 'Disable Defender' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_defender/windows_defender_exclusion Resource ===================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_defender_exclusion.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_defender_exclusion.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_defender_exclusion** resource to exclude paths, processes, or file types from Windows Defender realtime protection scanning. **New in Chef Infra Client 17.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_defender_exclusion** resource is: ``` windows_defender_exclusion 'name' do extensions String, Array # default value: [] paths String, Array # default value: [] process_paths String, Array # default value: [] action Symbol # defaults to :add if not specified end ``` where: * `windows_defender_exclusion` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `extensions`, `paths`, and `process_paths` are the properties available to this resource. Actions ------- --- The **windows_defender_exclusion** resource has the following actions: `:add` Add an exclusion to Windows Defender. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an exclusion to Windows Defender. Properties ---------- --- The **windows_defender_exclusion** resource has the following properties: `extensions` **Ruby Type:** String, Array | **Default Value:** `[]` File extensions to exclude from scanning. `paths` **Ruby Type:** String, Array | **Default Value:** `[]` File or directory paths to exclude from scanning. `process_paths` **Ruby Type:** String, Array | **Default Value:** `[]` Paths to executables to exclude from scanning. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_defender_exclusion** resource in recipes: **Add excluded items to Windows Defender scans**: ``` windows_defender_exclusion 'Add to things to be excluded from scanning' do paths 'c:\foo\bar, d:\bar\baz' extensions 'png, foo, ppt, doc' process_paths 'c:\windows\system32' action :add end ``` **Remove excluded items from Windows Defender scans**: ``` windows_defender_exclusion 'Remove things from the list to be excluded' do process_paths 'c:\windows\system32' action :remove end ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_defender_exclusion/windows_dns_zone Resource =========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_dns_zone.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_dns_zone.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- The windows_dns_zone resource creates an Active Directory Integrated DNS Zone on the local server. **New in Chef Infra Client 15.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_dns_zone** resource is: ``` windows_dns_zone 'name' do replication_scope String # default value: "Domain" server_type String # default value: "Domain" zone_name String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `windows_dns_zone` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `replication_scope`, `server_type`, and `zone_name` are the properties available to this resource. Actions ------- --- The **windows_dns_zone** resource has the following actions: `:create` Creates and updates a DNS Zone. (default) `:delete` Deletes a DNS Zone. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_dns_zone** resource has the following properties: `replication_scope` **Ruby Type:** String | **Default Value:** `Domain` The replication scope for the zone, required if server_type set to ‘Domain’. `server_type` **Ruby Type:** String | **Default Value:** `Domain` **Allowed Values:** `"Domain", "Standalone"` The type of DNS server, Domain or Standalone. `zone_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the dns zone name if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- This resource does not have any examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_dns_zone/windows_env Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_env.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_env.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_env** resource to manage environment keys in Microsoft Windows. After an environment key is set, Microsoft Windows must be restarted before the environment key will be available to the Task Scheduler. This resource was previously called the **env** resource; its name was updated in Chef Infra Client 14.0 to reflect the fact that only Windows is supported. Existing cookbooks using `env` will continue to function, but should be updated to use the new name. Note On UNIX-based systems, the best way to manipulate environment keys is with the `ENV` variable in Ruby; however, this approach does not have the same permanent effect as using the windows_env resource. Syntax ------ --- The full syntax for all of the properties that are available to the **windows_env** resource is: ``` windows_env 'name' do delim String, false key_name String # default value: 'name' unless specified user String # default value: "<System>" value String action Symbol # defaults to :create if not specified end ``` where: * `windows_env` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `delim`, `key_name`, `user`, and `value` are the properties available to this resource. Actions ------- --- The **windows_env** resource has the following actions: `:create` Create an environment variable. If an environment variable already exists (but does not match), update that environment variable to match. (default) `:delete` Delete an environment variable. `:modify` Modify an existing environment variable. This prepends the new value to the existing value, using the delimiter specified by the `delim` property. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_env** resource has the following properties: `delim` **Ruby Type:** String, false The delimiter that is used to separate multiple values for a single key. `key_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the name of the key that is to be created, deleted, or modified if it differs from the resource block’s name. `user` **Ruby Type:** String | **Default Value:** `<System>` `value` **Ruby Type:** String | `REQUIRED` The value of the environmental variable to set. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_env** resource in recipes: **Set an environment variable**: ``` windows_env 'ComSpec' do value 'C:\Windows\system32\cmd.exe' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_env/windows_feature_dism Resource =============================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_feature_dism.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_feature_dism.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_feature_dism** resource to add, remove, or entirely delete Windows features and roles using DISM. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_feature_dism** resource is: ``` windows_feature_dism 'name' do all true, false # default value: false feature_name Array, String # default value: 'name' unless specified source String timeout Integer # default value: 600 action Symbol # defaults to :install if not specified end ``` where: * `windows_feature_dism` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `all`, `feature_name`, `source`, and `timeout` are the properties available to this resource. Actions ------- --- The **windows_feature_dism** resource has the following actions: `:delete` Remove a Windows role or feature from the image using DISM. `:install` Install a Windows role/feature using DISM. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows role or feature using DISM. Properties ---------- --- The **windows_feature_dism** resource has the following properties: `all` **Ruby Type:** true, false | **Default Value:** `false` Install all sub-features. When set to `true`, this is the equivalent of specifying the `/All` switch to `dism.exe` `feature_name` **Ruby Type:** Array, String | **Default Value:** `The resource block's name` The name of the feature(s) or role(s) to install if they differ from the resource name. `source` **Ruby Type:** String Specify a local repository for the feature install. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Specifies a timeout (in seconds) for the feature installation. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_feature_dism** resource in recipes: **Installing the TelnetClient service**: ``` windows_feature_dism "TelnetClient" ``` **Installing two features by using an array**: ``` windows_feature_dism %w(TelnetClient TFTP) ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_feature_dism/windows_feature Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_feature.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_feature.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_feature** resource to add, remove or entirely delete Windows features and roles. This resource calls the [windows_feature_dism](../windows_feature_dism/index) or [windows_feature_powershell](../windows_feature_powershell/index) resources depending on the specified installation method, and defaults to DISM, which is available on both Workstation and Server editions of Windows. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_feature** resource is: ``` windows_feature 'name' do all true, false # default value: false feature_name Array, String # default value: 'name' unless specified install_method Symbol # default value: :windows_feature_dism management_tools true, false # default value: false source String timeout Integer # default value: 600 action Symbol # defaults to :install if not specified end ``` where: * `windows_feature` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `all`, `feature_name`, `install_method`, `management_tools`, `source`, and `timeout` are the properties available to this resource. Actions ------- --- The **windows_feature** resource has the following actions: `:delete` Remove a Windows role or feature from the image. `:install` Install a Windows role or feature. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows role or feature. Properties ---------- --- The **windows_feature** resource has the following properties: `all` **Ruby Type:** true, false | **Default Value:** `false` Install all sub-features. `feature_name` **Ruby Type:** Array, String | **Default Value:** `The resource block's name` The name of the feature(s) or role(s) to install if they differ from the resource block’s name. The same feature may have different names depending on the underlying installation method being used (ie DHCPServer vs DHCP; DNS-Server-Full-Role vs DNS). `install_method` **Ruby Type:** Symbol | **Default Value:** `:windows_feature_dism` **Allowed Values:** `:windows_feature_dism, :windows_feature_powershell, :windows_feature_servermanagercmd` The underlying installation method to use for feature installation. Specify `:windows_feature_dism` for DISM or `:windows_feature_powershell` for PowerShell. `management_tools` **Ruby Type:** true, false | **Default Value:** `false` Install all applicable management tools for the roles, role services, or features (PowerShell-only). `source` **Ruby Type:** String Specify a local repository for the feature install. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Specifies a timeout (in seconds) for the feature installation. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_feature** resource in recipes: **Install the DHCP Server feature**: ``` windows_feature 'DHCPServer' do action :install end ``` **Install the .Net 3.5.1 feature using repository files on DVD**: ``` windows_feature "NetFx3" do action :install source 'd:\sources\sxs' end ``` **Remove Telnet Server and Client features**: ``` windows_feature %w(TelnetServer TelnetClient) do action :remove end ``` **Add the SMTP Server feature using the PowerShell provider**: ``` windows_feature 'smtp-server' do action :install all true install_method :windows_feature_powershell end ``` **Install multiple features using one resource with the PowerShell provider**: ``` windows_feature %w(Web-Asp-Net45 Web-Net-Ext45) do action :install install_method :windows_feature_powershell end ``` **Install the Network Policy and Access Service feature, including the management tools**: ``` windows_feature 'NPAS' do action :install management_tools true install_method :windows_feature_powershell end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_feature/windows_firewall_rule Resource ================================ Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_firewall_rule.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_firewall_rule.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_firewall_rule** resource to create, change or remove Windows firewall rules. **New in Chef Infra Client 14.7.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_firewall_rule** resource is: ``` windows_firewall_rule 'name' do description String direction Symbol, String # default value: :inbound displayname String # default value: The rule_name property value. enabled true, false # default value: true firewall_action Symbol, String # default value: :allow group String icmp_type String, Integer # default value: "Any" interface_type Symbol, String # default value: :any local_address String local_port String, Integer, Array profile Symbol, String, Array # default value: :any program String protocol String # default value: "TCP" remote_address String, Array remote_port String, Integer, Array rule_name String # default value: 'name' unless specified service String action Symbol # defaults to :create if not specified end ``` where: * `windows_firewall_rule` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `description`, `direction`, `displayname`, `enabled`, `firewall_action`, `group`, `icmp_type`, `interface_type`, `local_address`, `local_port`, `profile`, `program`, `protocol`, `remote_address`, `remote_port`, `rule_name`, and `service` are the properties available to this resource. Actions ------- --- The **windows_firewall_rule** resource has the following actions: `:create` Create a Windows firewall entry. (default) `:delete` Delete an existing Windows firewall entry. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_firewall_rule** resource has the following properties: `description` **Ruby Type:** String The description to assign to the firewall rule. `direction` **Ruby Type:** Symbol, String | **Default Value:** `:inbound` **Allowed Values:** `:inbound, :outbound` The direction of the firewall rule. Direction means either inbound or outbound traffic. `displayname` **Ruby Type:** String | **Default Value:** `The rule_name property value.` The displayname to assign to the firewall rule. New in Chef Infra Client 16.0 `enabled` **Ruby Type:** true, false | **Default Value:** `true` Whether or not to enable the firewall rule. `firewall_action` **Ruby Type:** Symbol, String | **Default Value:** `:allow` **Allowed Values:** `:allow, :block, :notconfigured` The action of the firewall rule. `group` **Ruby Type:** String Specifies that only matching firewall rules of the indicated group association are copied. New in Chef Infra Client 16.0 `icmp_type` **Ruby Type:** String, Integer | **Default Value:** `Any` Specifies the ICMP Type parameter for using a protocol starting with ICMP New in Chef Infra Client 16.0 `interface_type` **Ruby Type:** Symbol, String | **Default Value:** `:any` **Allowed Values:** `:any, :remoteaccess, :wired, :wireless` The interface type the firewall rule applies to. `local_address` **Ruby Type:** String The local address the firewall rule applies to. `local_port` **Ruby Type:** String, Integer, Array The local port the firewall rule applies to. `profile` **Ruby Type:** Symbol, String, Array | **Default Value:** `:any` The profile the firewall rule applies to. `program` **Ruby Type:** String The program the firewall rule applies to. `protocol` **Ruby Type:** String | **Default Value:** `TCP` The protocol the firewall rule applies to. `remote_address` **Ruby Type:** String, Array The remote address(es) the firewall rule applies to. `remote_port` **Ruby Type:** String, Integer, Array The remote port the firewall rule applies to. `rule_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the name of the firewall rule to assign if it differs from the resource block’s name. `service` **Ruby Type:** String The service the firewall rule applies to. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_firewall_rule** resource in recipes: **Allowing port 80 access**: ``` windows_firewall_rule 'IIS' do local_port '80' protocol 'TCP' firewall_action :allow end ``` **Configuring multiple remote-address ports on a rule**: ``` windows_firewall_rule 'MyRule' do description 'Testing out remote address arrays' enabled false local_port 1434 remote_address %w(10.17.3.101 172.7.7.53) protocol 'TCP' action :create end ``` **Allow protocol ICMPv6 with ICMP Type**: ``` windows_firewall_rule 'CoreNet-Rule' do rule_name 'CoreNet-ICMP6-LR2-In' display_name 'Core Networking - Multicast Listener Report v2 (ICMPv6-In)' local_port 'RPC' protocol 'ICMPv6' icmp_type '8' end ``` **Blocking WinRM over HTTP on a particular IP**: ``` windows_firewall_rule 'Disable WinRM over HTTP' do local_port '5985' protocol 'TCP' firewall_action :block local_address '192.168.1.1' end ``` **Deleting an existing rule** ``` windows_firewall_rule 'Remove the SSH rule' do rule_name 'ssh' action :delete end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_firewall_rule/windows_feature_powershell Resource ===================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_feature_powershell.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_feature_powershell.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_feature_powershell** resource to add, remove, or entirely delete Windows features and roles using PowerShell. This resource offers significant speed benefits over the [windows_feature_dism](../windows_feature_dism/index) resource, but requires installation of the Remote Server Administration Tools on non-server releases of Windows. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_feature_powershell** resource is: ``` windows_feature_powershell 'name' do all true, false # default value: false feature_name Array, String # default value: 'name' unless specified management_tools true, false # default value: false source String timeout Integer # default value: 600 action Symbol # defaults to :install if not specified end ``` where: * `windows_feature_powershell` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `all`, `feature_name`, `management_tools`, `source`, and `timeout` are the properties available to this resource. Actions ------- --- The **windows_feature_powershell** resource has the following actions: `:delete` Delete a Windows role or feature from the image using PowerShell. `:install` Install a Windows role or feature using PowerShell. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows role or feature using PowerShell. Properties ---------- --- The **windows_feature_powershell** resource has the following properties: `all` **Ruby Type:** true, false | **Default Value:** `false` Install all subfeatures. When set to `true`, this is the equivalent of specifying the `-InstallAllSubFeatures` switch with `Add-WindowsFeature`. `feature_name` **Ruby Type:** Array, String | **Default Value:** `The resource block's name` The name of the feature(s) or role(s) to install if they differ from the resource block’s name. `management_tools` **Ruby Type:** true, false | **Default Value:** `false` Install all applicable management tools for the roles, role services, or features. `source` **Ruby Type:** String Specify a local repository for the feature install. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Specifies a timeout (in seconds) for the feature installation. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_feature_powershell** resource in recipes: **Add the SMTP Server feature**: ``` windows_feature_powershell "smtp-server" do action :install all true end ``` **Install multiple features using one resource**: ``` windows_feature_powershell ['Web-Asp-Net45', 'Web-Net-Ext45'] do action :install end ``` **Install the Network Policy and Access Service feature**: ``` windows_feature_powershell 'NPAS' do action :install management_tools true end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_feature_powershell/windows_firewall_profile Resource =================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_firewall_profile.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_firewall_profile.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_firewall_profile** resource to enable, disable, and configure the Windows firewall. **New in Chef Infra Client 16.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_firewall_profile** resource is: ``` windows_firewall_profile 'name' do allow_inbound_rules true, false, String allow_local_firewall_rules true, false, String allow_local_ipsec_rules true, false, String allow_unicast_response true, false, String allow_user_apps true, false, String allow_user_ports true, false, String default_inbound_action String default_outbound_action String display_notification true, false, String profile String # default value: 'name' unless specified action Symbol # defaults to :enable if not specified end ``` where: * `windows_firewall_profile` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_inbound_rules`, `allow_local_firewall_rules`, `allow_local_ipsec_rules`, `allow_unicast_response`, `allow_user_apps`, `allow_user_ports`, `default_inbound_action`, `default_outbound_action`, `display_notification`, and `profile` are the properties available to this resource. Actions ------- --- The **windows_firewall_profile** resource has the following actions: `:disable` Disable a Windows Firewall profile. `:enable` Enable and optionally configure a Windows Firewall profile. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_firewall_profile** resource has the following properties: `allow_inbound_rules` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow users to set inbound firewall rules `allow_local_firewall_rules` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Merges inbound firewall rules into the policy `allow_local_ipsec_rules` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow users to manage local connection security rules `allow_unicast_response` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow unicast responses to multicast and broadcast messages `allow_user_apps` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow user applications to manage firewall `allow_user_ports` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow users to manage firewall port rules `default_inbound_action` **Ruby Type:** String **Allowed Values:** `"Allow", "Block", "NotConfigured"` Set the default policy for inbound network traffic `default_outbound_action` **Ruby Type:** String **Allowed Values:** `"Allow", "Block", "NotConfigured"` Set the default policy for outbound network traffic `display_notification` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Display a notification when firewall blocks certain activity `profile` **Ruby Type:** String | **Default Value:** `The resource block's name` **Allowed Values:** `"Domain", "Private", "Public"` Set the Windows Profile being configured Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_firewall_profile** resource in recipes: **Enable and Configure the Private Profile of the Windows Profile**: ``` windows_firewall_profile 'Private' do default_inbound_action 'Block' default_outbound_action 'Allow' allow_inbound_rules true display_notification false action :enable end ``` **Enable and Configure the Public Profile of the Windows Firewall**: ``` windows_firewall_profile 'Public' do default_inbound_action 'Block' default_outbound_action 'Allow' allow_inbound_rules false display_notification false action :enable end ``` **Disable the Domain Profile of the Windows Firewall**: ``` windows_firewall_profile 'Disable the Domain Profile of the Windows Firewall' do profile 'Domain' action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_firewall_profile/windows_package Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_package** resource to manage packages on the Microsoft Windows platform. The **windows_package** resource supports these installer formats: * Microsoft Installer Package (MSI) * Nullsoft Scriptable Install System (NSIS) * Inno Setup (inno) * Wise * InstallShield * Custom installers such as installing a non-.msi file that embeds an .msi-based installer To enable idempotence of the `:install` action or to enable the `:remove` action with no source property specified, `package_name` MUST be an exact match of the name used by the package installer. The names of installed packages Windows knows about can be found in **Add/Remove programs**, in the output of `ohai packages`, or in the `DisplayName` property in one of the following in the Windows registry: * `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall` * `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall` * `HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall` Note If there are multiple versions of a package installed with the same display name, all of those packages will be removed unless a version is provided in the **version** property or unless it can be discovered in the installer file specified by the **source** property. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. Syntax ------ --- A **windows_package** resource block manages a package on a node, typically by installing it. The simplest use of the **windows_package** resource is: ``` windows_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **windows_package** resource is: ``` windows_package 'name' do checksum String installer_type Symbol options String package_name String remote_file_attributes Hash returns String, Integer, Array source String # default value: "The resource block's name" timeout String, Integer # default value: "600 (seconds)" version String action Symbol # defaults to :install if not specified end ``` where: * `windows_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `checksum`, `installer_type`, `options`, `package_name`, `remote_file_attributes`, `returns`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **windows_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. Properties ---------- --- The **windows_package** resource has the following properties: `checksum` **Ruby Type:** String The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, Chef Infra Client does not download it. Use when a URL is specified by the `source` property. `installer_type` **Ruby Type:** Symbol **Allowed Values:** `:custom, :inno, :installshield, :msi, :nsis, :wise` A symbol that specifies the type of package. Possible values: `:custom` (such as installing a non-.msi file that embeds an .msi-based installer), `:inno` (Inno Setup), `:installshield` (InstallShield), `:msi` (Microsoft Installer Package (MSI)), `:nsis` (Nullsoft Scriptable Install System (NSIS)), `:wise` (Wise). `options` **Ruby Type:** String One (or more) additional options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `remote_file_attributes` **Ruby Type:** Hash This property allows you to define a hash of properties and their value if the source package to be installed is at a remote location. This hash will be used by the underlying **remote_file** resource which will fetch the source package. `returns` **Ruby Type:** String, Integer, Array of integers | **Default Value:** `0 (success) and 3010 (success where a reboot is necessary)` A comma-delimited list of return codes that indicate the success or failure of the package command that was run. `source` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to a package in the local file system. The location of the package may be at a URL. If the `source` property is not specified, the package name MUST be exactly the same as the display name found in **Add/Remove programs** or exactly the same as the `DisplayName` property in the appropriate registry key, which may be one of the following: ``` HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall ``` Note If there are multiple versions of a package installed with the same display name, all of those packages will be removed unless a version is provided in the `version` property or unless it can be discovered in the installer file specified by the `source` property. `timeout` **Ruby Type:** String, Integer | **Default Value:** `600 (seconds)` The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_package** resource in recipes: **Install a package**: ``` windows_package '7zip' do action :install source 'C:\7z920.msi' end ``` **Specify a URL for the source attribute**: ``` windows_package '7zip' do source 'http://www.7-zip.org/a/7z938-x64.msi' end ``` **Specify path and checksum**: ``` windows_package '7zip' do source 'http://www.7-zip.org/a/7z938-x64.msi' checksum '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3' end ``` **Modify remote_file resource attributes**: The windows_package resource may specify a package at a remote location using the remote_file_attributes property. This uses the remote_file resource to download the contents at the specified URL and passes in a Hash that modifies the properties of the remote_file resource. ``` windows_package '7zip' do source 'http://www.7-zip.org/a/7z938-x64.msi' remote_file_attributes ({ :path => 'C:\7zip.msi', :checksum => '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3' }) end ``` **Download a nsis (Nullsoft) package resource**: ``` windows_package 'Mercurial 3.6.1 (64-bit)' do source 'http://mercurial.selenic.com/release/windows/Mercurial-3.6.1-x64.exe' checksum 'febd29578cb6736163d232708b834a2ddd119aa40abc536b2c313fc5e1b5831d' end ``` **Download a custom package**: ``` windows_package 'Microsoft Visual C++ 2005 Redistributable' do source 'https://download.microsoft.com/download/6/B/B/6BB661D6-A8AE-4819-B79F-236472F6070C/vcredist_x86.exe' installer_type :custom options '/Q' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_package/windows_pagefile Resource ========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_pagefile.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_pagefile.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_pagefile** resource to configure pagefile settings on Windows. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_pagefile** resource is: ``` windows_pagefile 'name' do automatic_managed true, false initial_size Integer maximum_size Integer path String # default value: 'name' unless specified system_managed true, false action Symbol # defaults to :set if not specified end ``` where: * `windows_pagefile` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `automatic_managed`, `initial_size`, `maximum_size`, `path`, and `system_managed` are the properties available to this resource. Actions ------- --- The **windows_pagefile** resource has the following actions: `:delete` Deletes the specified pagefile. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Configures the default pagefile, creating if it doesn’t exist. (default) Properties ---------- --- The **windows_pagefile** resource has the following properties: `automatic_managed` **Ruby Type:** true, false Enable automatic management of pagefile initial and maximum size. Setting this to true ignores `initial_size` and `maximum_size` properties. `initial_size` **Ruby Type:** Integer Initial size of the pagefile in megabytes. `maximum_size` **Ruby Type:** Integer Maximum size of the pagefile in megabytes. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the pagefile name if it differs from the resource block’s name. `system_managed` **Ruby Type:** true, false Configures whether the system manages the pagefile size. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_pagefile** resource in recipes: **Set the system to manage pagefiles**: ``` windows_pagefile 'Enable automatic management of pagefiles' do automatic_managed true end ``` **Delete a pagefile**: ``` windows_pagefile 'Delete the pagefile' do path 'C' action :delete end ``` **Switch to system managed pagefiles**: ``` windows_pagefile 'Change the pagefile to System Managed' do path 'E:' system_managed true action :set end ``` **Create a pagefile with an initial and maximum size**: ``` windows_pagefile 'create the pagefile with these sizes' do path 'f:' initial_size 100 maximum_size 200 end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_pagefile/windows_printer Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_printer.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_printer.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_printer** resource to setup Windows printers. This resource will automatically install the driver specified in the `driver_name` property and will automatically create a printer port using either the `ipv4_address` property or the `port_name` property. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_printer** resource is: ``` windows_printer 'name' do comment String create_port true, false # default value: true default true, false # default value: false device_id String # default value: 'name' unless specified driver_name String ipv4_address String location String port_name String share_name String shared true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_printer` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `comment`, `create_port`, `default`, `device_id`, `driver_name`, `ipv4_address`, `location`, `port_name`, `share_name`, and `shared` are the properties available to this resource. Actions ------- --- The **windows_printer** resource has the following actions: `:create` Create a new printer and printer port, if one doesn’t already. (default) `:delete` Delete an existing printer. Note that this resource does not delete the associated printer port. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_printer** resource has the following properties: `comment` **Ruby Type:** String Optional descriptor for the printer queue. `create_port` **Ruby Type:** true, false | **Default Value:** `true` Create a printer port for the printer. Set this to false and specify the `port_name` property if using the `windows_printer_port` resource to create the port instead. New in Chef Infra Client 17.3 `default` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not this should be the system’s default printer. `device_id` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the printer queue name if it differs from the resource block’s name. Example: `HP LJ 5200 in fifth floor copy room`. `driver_name` **Ruby Type:** String | `REQUIRED` The exact name of printer driver installed on the system. `ipv4_address` **Ruby Type:** String The IPv4 address of the printer, such as `10.4.64.23` `location` **Ruby Type:** String Printer location, such as `Fifth floor copy room`. `port_name` **Ruby Type:** String | **Default Value:** `The resource block name or the ipv4_address prepended with IP_.` The port name. New in Chef Infra Client 17.3 `share_name` **Ruby Type:** String The name used to identify the shared printer. `shared` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not the printer is shared. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_printer** resource in recipes: **Create a printer**: ``` windows_printer 'HP LaserJet 5th Floor' do driver_name 'HP LaserJet 4100 Series PCL6' ipv4_address '10.4.64.38' end ``` **Delete a printer**: Note: this doesn’t delete the associated printer port. See windows_printer_port above for how to delete the port. ``` windows_printer 'HP LaserJet 5th Floor' do action :delete end ``` **Create a printer port and a printer that uses that port (new in 17.3)** ``` windows_printer_port '10.4.64.39' do port_name 'My awesome printer port' snmp_enabled true port_protocol 2 end windows_printer 'HP LaserJet 5th Floor' do driver_name 'HP LaserJet 4100 Series PCL6' port_name 'My awesome printer port' ipv4_address '10.4.64.38' create_port false end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_printer/windows_path Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_path.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_path.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_path** resource to manage the path environment variable on Microsoft Windows. **New in Chef Infra Client 13.4.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_path** resource is: ``` windows_path 'name' do path String # default value: 'name' unless specified action Symbol # defaults to :add if not specified end ``` where: * `windows_path` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `path` is the property available to this resource. Actions ------- --- The **windows_path** resource has the following actions: `:add` Add an item to the system path. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an item from the system path. Properties ---------- --- The **windows_path** resource has the following properties: `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the path value if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_path** resource in recipes: **Add Sysinternals to the system path**: ``` windows_path 'C:\Sysinternals' do action :add end ``` **Remove 7-Zip from the system path**: ``` windows_path 'C:\7-Zip' do action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_path/windows_printer_port Resource =============================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_printer_port.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_printer_port.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_printer_port** resource to create and delete TCP/IPv4 printer ports on Windows. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_printer_port** resource is: ``` windows_printer_port 'name' do ipv4_address String # default value: 'name' unless specified port_name String port_number Integer # default value: 9100 port_protocol Integer # default value: 1 snmp_enabled true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_printer_port` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ipv4_address`, `port_name`, `port_number`, `port_protocol`, and `snmp_enabled` are the properties available to this resource. Actions ------- --- The **windows_printer_port** resource has the following actions: `:create` Create or update the printer port. (default) `:delete` Delete an existing printer port. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_printer_port** resource has the following properties: `ipv4_address` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for the IPv4 address of the printer if it differs from the resource block’s name. `port_name` **Ruby Type:** String | **Default Value:** `The resource block name or the ipv4_address prepended with IP_.` The port name. `port_number` **Ruby Type:** Integer | **Default Value:** `9100` The TCP port number. `port_protocol` **Ruby Type:** Integer | **Default Value:** `1` **Allowed Values:** `1, 2` The printer port protocol: 1 (RAW) or 2 (LPR). `snmp_enabled` **Ruby Type:** true, false | **Default Value:** `false` Determines if SNMP is enabled on the port. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_printer_port** resource in recipes: **Delete a printer port** ``` windows_printer_port '10.4.64.37' do action :delete end ``` **Delete a port with a custom port_name** ``` windows_printer_port '10.4.64.38' do port_name 'My awesome port' action :delete end ``` **Create a port with more options** ``` windows_printer_port '10.4.64.39' do port_name 'My awesome port' snmp_enabled true port_protocol 2 end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_printer_port/windows_security_policy Resource ================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_security_policy.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_security_policy.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_security_policy** resource to set a security policy on the Microsoft Windows platform. **New in Chef Infra Client 16.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_security_policy** resource is: ``` windows_security_policy 'name' do secoption String # default value: 'name' unless specified secvalue String action Symbol # defaults to :set if not specified end ``` where: * `windows_security_policy` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `secoption` and `secvalue` are the properties available to this resource. Actions ------- --- The **windows_security_policy** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set the Windows security policy (default) Properties ---------- --- The **windows_security_policy** resource has the following properties: `secoption` **Ruby Type:** String | **Default Value:** `The resource block's name` | `REQUIRED` **Allowed Values:** `"AuditPolicyChange", "ClearTextPassword", "EnableAdminAccount", "EnableGuestAccount", "ForceLogoffWhenHourExpire", "LSAAnonymousNameLookup", "LockoutBadCount", "LockoutDuration", "LockoutDuration", "MaximumPasswordAge", "MinimumPasswordAge", "MinimumPasswordLength", "NewAdministratorName", "NewGuestName", "PasswordComplexity", "PasswordHistorySize", "RequireLogonToChangePassword", "ResetLockoutCount"` The name of the policy to be set on windows platform to maintain its security. `secvalue` **Ruby Type:** String | `REQUIRED` Policy value to be set for policy name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_security_policy** resource in recipes: **Set Administrator Account to Enabled**: ``` windows_security_policy 'EnableAdminAccount' do secvalue '1' action :set end ``` **Rename Administrator Account**: ``` windows_security_policy 'NewAdministratorName' do secvalue 'AwesomeChefGuy' action :set end ``` **Set Guest Account to Disabled**: ``` windows_security_policy 'EnableGuestAccount' do secvalue '0' action :set end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_security_policy/windows_shortcut Resource ========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_shortcut.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_shortcut.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_shortcut** resource to create shortcut files on Windows. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_shortcut** resource is: ``` windows_shortcut 'name' do arguments String cwd String description String iconlocation String shortcut_name String # default value: 'name' unless specified target String action Symbol # defaults to :create if not specified end ``` where: * `windows_shortcut` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `arguments`, `cwd`, `description`, `iconlocation`, `shortcut_name`, and `target` are the properties available to this resource. Actions ------- --- The **windows_shortcut** resource has the following actions: `:create` Create or modify a Windows shortcut. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_shortcut** resource has the following properties: `arguments` **Ruby Type:** String Arguments to pass to the target when the shortcut is executed. `cwd` **Ruby Type:** String Working directory to use when the target is executed. `description` **Ruby Type:** String The description of the shortcut `iconlocation` **Ruby Type:** String Icon to use for the shortcut. Accepts the format of `path, index`, where index is the icon file to use. See Microsoft’s [documentation](https://msdn.microsoft.com/en-us/library/3s9bx7at.aspx) for details `shortcut_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the shortcut name if it differs from the resource block’s name. `target` **Ruby Type:** String The destination that the shortcut links to. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_shortcut** resource in recipes: **Create a shortcut with a description**: ``` windows_shortcut 'C:\shortcut_dir.lnk' do target 'C:\original_dir' description 'Make a shortcut to C:\original_dir' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_shortcut/windows_font Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_font.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_font.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_font** resource to install font files on Windows. By default, the font is sourced from the cookbook using the resource, but a URI source can be specified as well. **New in Chef Infra Client 14.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_font** resource is: ``` windows_font 'name' do font_name String # default value: 'name' unless specified source String action Symbol # defaults to :install if not specified end ``` where: * `windows_font` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `font_name` and `source` are the properties available to this resource. Actions ------- --- The **windows_font** resource has the following actions: `:install` Install a font to the system fonts directory. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_font** resource has the following properties: `font_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the name of the font to install if it differs from the resource block’s name. `source` **Ruby Type:** String A local filesystem path or URI that is used to source the font file. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_font** resource in recipes: **Install a font from a https source**: ``` windows_font 'Custom.otf' do source 'https://example.com/Custom.otf' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_font/windows_share Resource ======================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_share.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_share.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_share** resource to create, modify and remove Windows shares. **New in Chef Infra Client 14.7.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_share** resource is: ``` windows_share 'name' do ca_timeout Integer # default value: 0 change_users Array # default value: [] concurrent_user_limit Integer # default value: 0 continuously_available true, false # default value: false description String encrypt_data true, false # default value: false full_users Array # default value: [] path String read_users Array # default value: [] scope_name String # default value: "*" share_name String # default value: 'name' unless specified temporary true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_share` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ca_timeout`, `change_users`, `concurrent_user_limit`, `continuously_available`, `description`, `encrypt_data`, `full_users`, `path`, `read_users`, `scope_name`, `share_name`, and `temporary` are the properties available to this resource. Actions ------- --- The **windows_share** resource has the following actions: `:create` Create or modify a Windows share. (default) `:delete` Delete an existing Windows share. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_share** resource has the following properties: `ca_timeout` **Ruby Type:** Integer | **Default Value:** `0` The continuous availability time-out for the share. `change_users` **Ruby Type:** Array | **Default Value:** `[]` The users that should have ‘modify’ permission on the share in domain\username format. `concurrent_user_limit` **Ruby Type:** Integer | **Default Value:** `0` The maximum number of concurrently connected users the share can accommodate. `continuously_available` **Ruby Type:** true, false | **Default Value:** `false` Indicates that the share is continuously available. `description` **Ruby Type:** String The description to be applied to the share. `encrypt_data` **Ruby Type:** true, false | **Default Value:** `false` Indicates that the share is encrypted. `full_users` **Ruby Type:** Array | **Default Value:** `[]` The users that should have ‘Full control’ permissions on the share in domain\username format. `path` **Ruby Type:** String The path of the folder to share. Required when creating. If the share already exists on a different path then it is deleted and re-created. `read_users` **Ruby Type:** Array | **Default Value:** `[]` The users that should have ‘read’ permission on the share in domain\username format. `scope_name` **Ruby Type:** String | **Default Value:** `*` The scope name of the share. `share_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the share name if it differs from the resource block’s name. `temporary` **Ruby Type:** true, false | **Default Value:** `false` The lifetime of the new SMB share. A temporary share does not persist beyond the next restart of the computer. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_share** resource in recipes: **Create a share**: ``` windows_share 'foo' do action :create path 'C:\foo' full_users ['DOMAIN_A\some_user', 'DOMAIN_B\some_other_user'] read_users ['DOMAIN_C\Domain users'] end ``` **Delete a share**: ``` windows_share 'foo' do action :delete end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_share/windows_service Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_service.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_service.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_service** resource to create, delete, or manage a service on the Microsoft Windows platform. Syntax ------ --- A **windows_service** resource block manages the state of a service on a machine that is running Microsoft Windows. For example: ``` windows_service 'BITS' do action :configure_startup startup_type :manual end ``` The full syntax for all of the properties that are available to the **windows_service** resource is: ``` windows_service 'name' do binary_path_name String delayed_start true, false # default value: false dependencies String, Array description String desired_access Integer # default value: 983551 display_name String error_control Integer # default value: 1 init_command String load_order_group String pattern String reload_command String, false restart_command String, false run_as_password String run_as_user String # default value: "LocalSystem" service_name String # default value: 'name' unless specified service_type Integer # default value: "SERVICE_WIN32_OWN_PROCESS" start_command String, false startup_type Symbol # default value: :automatic status_command String, false stop_command String, false supports Hash # default value: {"restart"=>nil, "reload"=>nil, "status"=>nil} timeout Integer action Symbol # defaults to :nothing if not specified end ``` where: * `windows_service` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `binary_path_name`, `display_name`, `desired_access`, `delayed_start`, `dependencies`, `description`, `error_control`, `init_command`, `load_order_group`, `pattern`, `reload_command`, `restart_command`, `run_as_password`, `run_as_user`, `service_name`, `service_type`, `start_command`, `startup_type`, `status_command`, `stop_command`, `supports`, and `timeout` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **windows_service** resource has the following actions: `:configure` Configure a pre-existing service. *New in Chef Client 14.0.* `:configure_startup` Configure a service based on the value of the `startup_type` property. `:create` Create the service based on the value of the `binary_path_name`, `service_name` and/or `display_name` property. *New in Chef Client 14.0.* `:delete` Delete the service based on the value of the `service_name` property. *New in Chef Client 14.0.* `:disable` Disable a service. This action is equivalent to a `Disabled` startup type on the Microsoft Windows platform. `:enable` Enable a service at boot. This action is equivalent to an `Automatic` startup type on the Microsoft Windows platform. `:nothing` Default. Do nothing with a service. `:reload` Reload the configuration for this service. This action is not supported on the Windows platform and will raise an error if used. `:restart` Restart a service. `:start` Start a service, and keep it running until stopped or disabled. `:stop` Stop a service. Properties ---------- --- The **windows_service** resource has the following properties: `binary_path_name` **Ruby Type:** String The fully qualified path to the service binary file. The path can also include arguments for an auto-start service. This is required for `:create` and `:configure` actions New in Chef Client 14.0 `delayed_start` **Ruby Type:** true, false | **Default Value:** `false` Set the startup type to delayed start. This only applies if `startup_type` is `:automatic` New in Chef Client 14.0 `dependencies` **Ruby Type:** String, Array A pointer to a double null-terminated array of null-separated names of services or load ordering groups that the system must start before this service. Specify `nil` or an empty string if the service has no dependencies. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group. New in Chef Client 14.0 `description` **Ruby Type:** String Description of the service. New in Chef Client 14.0 `desired_access` **Ruby Type:** Integer | **Default Value:** `983551` New in Chef Client 14.0 `display_name` **Ruby Type:** String The display name to be used by user interface programs to identify the service. This string has a maximum length of 256 characters. New in Chef Client 14.0 `error_control` **Ruby Type:** Integer | **Default Value:** `1` New in Chef Client 14.0 `load_order_group` **Ruby Type:** String The name of the service’s load ordering group(s). New in Chef Client 14.0 `pattern` **Ruby Type:** String | **Default Value:** `The value provided to 'service_name' or the resource block's name` The pattern to look for in the process table. `reload_command` **Ruby Type:** String, false The command used to tell a service to reload its configuration. `restart_command` **Ruby Type:** String, false The command used to restart a service. `run_as_password` **Ruby Type:** String The password for the user specified by `run_as_user`. `run_as_user` **Ruby Type:** String | **Default Value:** `localsystem` The user under which a Microsoft Windows service runs. `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the service name if it differs from the resource block’s name. `service_type` **Ruby Type:** Integer | **Default Value:** `16` New in Chef Client 14.0 `start_command` **Ruby Type:** String, false The command used to start a service. `startup_type` **Ruby Type:** Symbol | **Default Value:** `:automatic` **Allowed Values:** `:automatic, :disabled, :manual` Use to specify the startup type of the service. `status_command` **Ruby Type:** String, false The command used to check the run status for a service. `stop_command` **Ruby Type:** String, false The command used to stop a service. `supports` **Ruby Type:** Hash | **Default Value:** `{"restart"=>nil, "reload"=>nil, "status"=>nil}` A list of properties that controls how Chef Infra Client is to attempt to manage a service: `:restart`, `:reload`, `:status`. For `:restart`, the init script or other service provider can use a restart command; if `:restart` is not specified, Chef Infra Client attempts to stop and then start a service. For `:reload`, the init script or other service provider can use a reload command. For `:status`, the init script or other service provider can use a status command to determine if the service is running; if `:status` is not specified, Chef Infra Client attempts to match the `service_name` against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: `{ restart: false, reload: false, status: false }` for all platforms (except for the Red Hat platform family, which defaults to `{ restart: false, reload: false, status: true }`.) `timeout` **Ruby Type:** Integer | **Default Value:** `60` The amount of time (in seconds) to wait before timing out. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_service** resource in recipes: **Starting Services** Start a service with a `manual` startup type: ``` windows_service 'BITS' do action :configure_startup startup_type :manual end ``` **Creating Services** Create a service named chef-client: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" end ``` Create a service with `service_name` and `display_name`: ``` windows_service 'Setup chef-client as a service' do action :create display_name 'CHEF-CLIENT' service_name 'chef-client' binary_path_name "C:\opscode\chef\bin" end ``` Create a service with the `manual` startup type: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :manual end ``` Create a service with the `disabled` startup type: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :disabled end ``` Create a service with the `automatic` startup type and delayed start enabled: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :automatic delayed_start true end ``` Create a service with a description: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :automatic description "Chef client as service" end ``` **Deleting Services** Delete a service named chef-client: ``` windows_service 'chef-client' do action :delete end ``` Delete a service with the `service_name` property: ``` windows_service 'Delete chef client' do action :delete service_name 'chef-client' end ``` **Configuring Services** Change an existing service from automatic to manual startup: ``` windows_service 'chef-client' do action :configure binary_path_name "C:\opscode\chef\bin" startup_type :manual end ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_service/windows_uac Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_uac.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_uac.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- The *windows_uac* resource configures UAC on Windows hosts by setting registry keys at `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System` **New in Chef Infra Client 15.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_uac** resource is: ``` windows_uac 'name' do consent_behavior_admins Symbol # default value: :prompt_for_consent_non_windows_binaries consent_behavior_users Symbol # default value: :prompt_for_creds detect_installers true, false enable_uac true, false # default value: true prompt_on_secure_desktop true, false # default value: true require_signed_binaries true, false # default value: false action Symbol # defaults to :configure if not specified end ``` where: * `windows_uac` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `consent_behavior_admins`, `consent_behavior_users`, `detect_installers`, `enable_uac`, `prompt_on_secure_desktop`, and `require_signed_binaries` are the properties available to this resource. Actions ------- --- The **windows_uac** resource has the following actions: `:configure` Configures UAC by setting registry keys at `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System`. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_uac** resource has the following properties: `consent_behavior_admins` **Ruby Type:** Symbol | **Default Value:** `:prompt_for_consent_non_windows_binaries` **Allowed Values:** `:no_prompt, :prompt_for_consent, :prompt_for_consent_non_windows_binaries, :prompt_for_creds, :secure_prompt_for_consent, :secure_prompt_for_creds` Behavior of the elevation prompt for administrators in Admin Approval Mode. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ConsentPromptBehaviorAdmin. `consent_behavior_users` **Ruby Type:** Symbol | **Default Value:** `:prompt_for_creds` **Allowed Values:** `:auto_deny, :prompt_for_creds, :secure_prompt_for_creds` Behavior of the elevation prompt for standard users. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ConsentPromptBehaviorUser. `detect_installers` **Ruby Type:** true, false Detect application installations and prompt for elevation. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\EnableInstallerDetection. `enable_uac` **Ruby Type:** true, false | **Default Value:** `true` Enable or disable UAC Admin Approval Mode. If this is changed a system restart is required. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA. `prompt_on_secure_desktop` **Ruby Type:** true, false | **Default Value:** `true` Switch to the secure desktop when prompting for elevation. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\PromptOnSecureDesktop. `require_signed_binaries` **Ruby Type:** true, false | **Default Value:** `false` Only elevate executables that are signed and validated. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ValidateAdminCodeSignatures. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_uac** resource in recipes: **Disable UAC prompts for the admin**: ``` windows_uac 'Disable UAC prompts for the admin' do enable_uac true prompt_on_secure_desktop false consent_behavior_admins :no_prompt end ``` **Disable UAC entirely**: ``` windows_uac 'Disable UAC entirely' do enable_uac false end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_uac/windows_update_settings Resource ================================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_update_settings.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_update_settings.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_update_settings** resource to manage the various Windows Update patching options. **New in Chef Infra Client 17.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_update_settings** resource is: ``` windows_update_settings 'name' do automatic_update_option Integer, Symbol # default value: :download_and_schedule automatically_install_minor_updates true, false # default value: false block_windows_update_website true, false # default value: false custom_detection_frequency Integer # default value: 22 disable_automatic_updates true, false # default value: false disable_os_upgrades true, false # default value: false elevate_non_admins true, false # default value: true enable_detection_frequency true, false # default value: false no_reboot_with_users_logged_on true, false # default value: true scheduled_install_day String # default value: "Everyday" scheduled_install_hour Integer target_wsus_group_name String update_other_ms_products true, false # default value: true wsus_server_url String action Symbol # defaults to :set if not specified end ``` where: * `windows_update_settings` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `automatic_update_option`, `automatically_install_minor_updates`, `block_windows_update_website`, `custom_detection_frequency`, `disable_automatic_updates`, `disable_os_upgrades`, `elevate_non_admins`, `enable_detection_frequency`, `no_reboot_with_users_logged_on`, `scheduled_install_day`, `scheduled_install_hour`, `target_wsus_group_name`, `update_other_ms_products`, and `wsus_server_url` are the properties available to this resource. Actions ------- --- The **windows_update_settings** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set Windows Update settings. (default) Properties ---------- --- The **windows_update_settings** resource has the following properties: `automatic_update_option` **Ruby Type:** Integer, Symbol | **Default Value:** `:download_and_schedule` **Allowed Values:** `:download_and_notify, :download_and_schedule, :local_admin_decides, :notify` Control what to do when updates are found. This allows you to notify, automatically download and notify to install, automatically download and schedule the install, or let the local admin decide what action to take. `automatically_install_minor_updates` **Ruby Type:** true, false | **Default Value:** `false` Automatically install minor updates. `block_windows_update_website` **Ruby Type:** true, false | **Default Value:** `false` Block accessing the Windows Update website. `custom_detection_frequency` **Ruby Type:** Integer | **Default Value:** `22` If you decided to override the OS default detection frequency, specify your choice here. Valid choices are 0 - 22 `disable_automatic_updates` **Ruby Type:** true, false | **Default Value:** `false` Disable Windows Update. `disable_os_upgrades` **Ruby Type:** true, false | **Default Value:** `false` Disable OS upgrades. `elevate_non_admins` **Ruby Type:** true, false | **Default Value:** `true` Allow normal user accounts to temporarily be elevated to install patches. `enable_detection_frequency` **Ruby Type:** true, false | **Default Value:** `false` Used to override the OS default of how often to check for updates `no_reboot_with_users_logged_on` **Ruby Type:** true, false | **Default Value:** `true` Prevents the OS from rebooting while someone is on the console. `scheduled_install_day` **Ruby Type:** String | **Default Value:** `Everyday` **Allowed Values:** `"Everyday", "Friday", "Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday"` A day of the week to tell Windows when to install updates. `scheduled_install_hour` **Ruby Type:** Integer If you chose a scheduled day to install, then choose an hour on that day for you installation `target_wsus_group_name` **Ruby Type:** String Add the node to a WSUS Target Group. `update_other_ms_products` **Ruby Type:** true, false | **Default Value:** `true` Allows for other Microsoft products to get updates too `wsus_server_url` **Ruby Type:** String The URL of your WSUS server if you use one. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_update_settings** resource in recipes: **Set Windows Update settings**: ``` windows_update_settings 'Settings to Configure Windows Nodes to automatically receive updates' do disable_os_upgrades true elevate_non_admins true block_windows_update_website true automatically_install_minor_updates true scheduled_install_day 'Friday' scheduled_install_hour 18 update_other_ms_products true action :enable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_update_settings/windows_task Resource ====================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_task.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_task.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_task** resource to create, delete or run a Windows scheduled task. **New in Chef Infra Client 13.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_task** resource is: ``` windows_task 'name' do backup Integer, false # default value: 5 command String cwd String day String, Integer description String disallow_start_if_on_batteries true, false # default value: false execution_time_limit String, Integer # default value: "PT72H (72 hours in ISO8601 duration format)" force true, false # default value: false frequency Symbol frequency_modifier Integer, String # default value: 1 idle_time Integer interactive_enabled true, false # default value: false minutes_duration String, Integer minutes_interval String, Integer months String password String priority Integer # default value: 7 random_delay String, Integer run_level Symbol # default value: :limited start_day String # default value: The current date. start_time String start_when_available true, false # default value: false stop_if_going_on_batteries true, false # default value: false task_name String # default value: 'name' unless specified user String # default value: The localized SYSTEM user for the node. action Symbol # defaults to :create if not specified end ``` where: * `windows_task` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `backup`, `command`, `cwd`, `day`, `description`, `disallow_start_if_on_batteries`, `execution_time_limit`, `force`, `frequency`, `frequency_modifier`, `idle_time`, `interactive_enabled`, `minutes_duration`, `minutes_interval`, `months`, `password`, `priority`, `random_delay`, `run_level`, `start_day`, `start_time`, `start_when_available`, `stop_if_going_on_batteries`, `task_name`, and `user` are the properties available to this resource. Actions ------- --- The **windows_task** resource has the following actions: `:create` Creates a scheduled task, or updates an existing task if any property has changed. (default) `:delete` Deletes a scheduled task. `:disable` Disables a scheduled task. `:enable` Enables a scheduled task. `:end` Ends a scheduled task. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Runs a scheduled task. Properties ---------- --- The **windows_task** resource has the following properties: `backup` **Ruby Type:** Integer, false | **Default Value:** `5` Number of backups to keep of the task when modified/deleted. Set to false to disable backups. New in Chef Infra Client 17.0 `command` **Ruby Type:** String The command to be executed by the windows scheduled task. `cwd` **Ruby Type:** String The directory the task will be run from. `day` **Ruby Type:** String, Integer The day(s) on which the task runs. * Use this property when setting `frequency` to `:monthly` or `:weekly`. * Valid values with frequency `:weekly` are `MON`-`SUN` or `*`. * Valid values with frequency `:monthly` are `1-31`, `MON`-`SUN`, and `LASTDAY`. * Use `MON`-`SUN` or `LASTDAY` if you are setting `frequency_modifier` as “FIRST, SECOND, THIRD etc.” else use 1-31. * Multiple days should be comma separated. e.g `1, 2, 3` or `MON, WED, FRI`. `description` **Ruby Type:** String The task description. New in Chef Client 14.7 `disallow_start_if_on_batteries` **Ruby Type:** true, false | **Default Value:** `false` Disallow start of the task if the system is running on battery power. New in Chef Client 14.4 `execution_time_limit` **Ruby Type:** String, Integer | **Default Value:** `PT72H (72 hours in ISO8601 duration format)` The maximum time the task will run. This field accepts either seconds or an ISO8601 duration value. `force` **Ruby Type:** true, false | **Default Value:** `false` When used with create, will update the task. `frequency` **Ruby Type:** Symbol **Allowed Values:** `:daily, :hourly, :minute, :monthly, :none, :on_idle, :on_logon, :once, :onstart, :weekly` The frequency with which to run the task. Note This property is required in Chef Infra Client 14.1 or later. Note The `:once` value requires the `start_time` property to be set. `frequency_modifier` **Ruby Type:** Integer, String | **Default Value:** `1` * For frequency `:minute` valid values are 1 to 1439 * For frequency `:hourly` valid values are 1 to 23 * For frequency `:daily` valid values are 1 to 365 * For frequency `:weekly` valid values are 1 to 52 * For frequency `:monthly` valid values are `('FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST')` OR `1-12`. + e.g. If user want to run the task on `second week of the month` use `frequency_modifier` value as `SECOND`. Multiple values for weeks of the month should be comma separated e.g. `"FIRST, THIRD, LAST"`. + To run task every (n) months use values 1 to 12. `idle_time` **Ruby Type:** Integer For `:on_idle` frequency, the time (in minutes) without user activity that must pass to trigger the task, from `1` - `999`. `interactive_enabled` **Ruby Type:** true, false | **Default Value:** `false` Allow task to run interactively or non-interactively. Requires user and password to also be set. `minutes_duration` **Ruby Type:** String, Integer `minutes_interval` **Ruby Type:** String, Integer `months` **Ruby Type:** String The Months of the year on which the task runs, such as: `JAN, FEB` or `*`. Multiple months should be comma delimited. e.g. `Jan, Feb, Mar, Dec`. `password` **Ruby Type:** String The user’s password. The user property must be set if using this property. `priority` **Ruby Type:** Integer | **Default Value:** `7` Use to set Priority Levels range from 0 to 10. `random_delay` **Ruby Type:** String, Integer Delays the task up to a given time (in seconds). `run_level` **Ruby Type:** Symbol | **Default Value:** `:limited` **Allowed Values:** `:highest, :limited` Run with `:limited` or `:highest` privileges. `start_day` **Ruby Type:** String | **Default Value:** `The current date.` Specifies the first date on which the task runs in **MM/DD/YYYY** format. `start_time` **Ruby Type:** String Specifies the start time to run the task, in **HH:mm** format. `start_when_available` **Ruby Type:** true, false | **Default Value:** `false` To start the task at any time after its scheduled time has passed. New in Chef Client 14.15 `stop_if_going_on_batteries` **Ruby Type:** true, false | **Default Value:** `false` Scheduled task option when system is switching on battery. New in Chef Client 14.4 `task_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the task name if it differs from the resource block’s name. Example: `Task Name` or `/Task Name` `user` **Ruby Type:** String | **Default Value:** `The localized SYSTEM user for the node.` The user to run the task as. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_task** resource in recipes: **Create a scheduled task to run every 15 minutes as the Administrator user**: ``` windows_task 'chef-client' do user 'Administrator' password 'password' command 'chef-client' run_level :highest frequency :minute frequency_modifier 15 end ``` **Create a scheduled task to run every 2 days**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :daily frequency_modifier 2 end ``` **Create a scheduled task to run on specific days of the week**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly day 'Mon, Thu' end ``` **Create a scheduled task to run only once**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :once start_time '16:10' end ``` **Create a scheduled task to run on current day every 3 weeks and delay upto 1 min**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly frequency_modifier 3 random_delay '60' end ``` **Create a scheduled task to run weekly starting on Dec 28th 2018**: ``` windows_task 'chef-client 8' do command 'chef-client' run_level :highest frequency :weekly start_day '12/28/2018' end ``` **Create a scheduled task to run every Monday, Friday every 2 weeks**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly frequency_modifier 2 day 'Mon, Fri' end ``` **Create a scheduled task to run when computer is idle with idle duration 20 min**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :on_idle idle_time 20 end ``` **Delete a task named “old task”**: ``` windows_task 'old task' do action :delete end ``` **Enable a task named “chef-client”**: ``` windows_task 'chef-client' do action :enable end ``` **Disable a task named “ProgramDataUpdater” with TaskPath “\Microsoft\Windows\Application Experience\ProgramDataUpdater”** ``` windows_task '\Microsoft\Windows\Application Experience\ProgramDataUpdater' do action :disable end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_task/windows_user_privilege Resource ================================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_user_privilege.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_user_privilege.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- The windows_user_privilege resource allows to add and set principal (User/Group) to the specified privilege. Ref: <https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/user-rights-assignment **New in Chef Infra Client 16.0.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_user_privilege** resource is: ``` windows_user_privilege 'name' do principal String # default value: 'name' unless specified privilege Array, String users Array, String action Symbol # defaults to :add if not specified end ``` where: * `windows_user_privilege` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `principal`, `privilege`, and `users` are the properties available to this resource. Actions ------- --- The **windows_user_privilege** resource has the following actions: `:add` Add a user privilege. (default) `:clear` Clear all user privileges `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a user privilege `:set` Set the privileges that are listed in the `privilege` property for only the users listed in the `users` property. Properties ---------- --- The **windows_user_privilege** resource has the following properties: `principal` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to add the user to the given privilege. Use only with add and remove action. `privilege` **Ruby Type:** Array, String | `REQUIRED` One or more privileges to set for users. `users` **Ruby Type:** Array, String An optional property to set the privilege for given users. Use only with set action. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_user_privilege** resource in recipes: **Set the SeNetworkLogonRight Privilege for the Builtin Administrators Group and Authenticated Users**: ``` windows_user_privilege 'Network Logon Rights' do privilege 'SeNetworkLogonRight' users ['BUILTIN\Administrators', 'NT AUTHORITY\Authenticated Users'] action :set end ``` **Add the SeDenyRemoteInteractiveLogonRight Privilege to the Builtin Guests and Local Accounts User Groups**: ``` windows_user_privilege 'Remote interactive logon' do privilege 'SeDenyRemoteInteractiveLogonRight' users ['Builtin\Guests', 'NT AUTHORITY\Local Account'] action :add end ``` **Provide only the Builtin Guests and Administrator Groups with the SeCreatePageFile Privilege**: ``` windows_user_privilege 'Create Pagefile' do privilege 'SeCreatePagefilePrivilege' users ['BUILTIN\Guests', 'BUILTIN\Administrators'] action :set end ``` **Remove the SeCreatePageFile Privilege from the Builtin Guests Group**: ``` windows_user_privilege 'Create Pagefile' do privilege 'SeCreatePagefilePrivilege' users ['BUILTIN\Guests'] action :remove end ``` **Clear all users from the SeDenyNetworkLogonRight Privilege**: ``` windows_user_privilege 'Allow any user the Network Logon right' do privilege 'SeDenyNetworkLogonRight' action :clear end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_user_privilege/windows_workgroup Resource =========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_workgroup.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_workgroup.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **windows_workgroup** resource to join or change the workgroup of a Windows host. **New in Chef Infra Client 14.5.** Syntax ------ --- The full syntax for all of the properties that are available to the **windows_workgroup** resource is: ``` windows_workgroup 'name' do password String reboot Symbol # default value: :immediate user String workgroup_name String # default value: 'name' unless specified action Symbol # defaults to :join if not specified end ``` where: * `windows_workgroup` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `password`, `reboot`, `user`, and `workgroup_name` are the properties available to this resource. Actions ------- --- The **windows_workgroup** resource has the following actions: `:join` Update the workgroup. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **windows_workgroup** resource has the following properties: `password` **Ruby Type:** String The password for the local administrator user. Required if using the `user` property. `reboot` **Ruby Type:** Symbol | **Default Value:** `:immediate` **Allowed Values:** `:never, :reboot_now, :request_reboot` Controls the system reboot behavior post workgroup joining. Reboot immediately, after the Chef Infra Client run completes, or never. Note that a reboot is necessary for changes to take effect. `user` **Ruby Type:** String The local administrator user to use to change the workgroup. Required if using the `password` property. `workgroup_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the workgroup name if it differs from the resource block’s name. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_workgroup** resource in recipes: **Join a workgroup**: ``` windows_workgroup 'myworkgroup' ``` **Join a workgroup using a specific user**: ``` windows_workgroup 'myworkgroup' do user 'Administrator' password 'passw0rd' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_workgroup/yum_repository Resource ======================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [yum_repository.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/yum_repository.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **yum_repository** resource to manage a Yum repository configuration file located at `/etc/yum.repos.d/repositoryid.repo` on the local machine. This configuration file specifies which repositories to reference, how to handle cached data, etc. **New in Chef Infra Client 12.14.** Syntax ------ --- The full syntax for all of the properties that are available to the **yum_repository** resource is: ``` yum_repository 'name' do baseurl String, Array clean_metadata true, false # default value: true cost String description String # default value: "Yum Repository" enabled true, false # default value: true enablegroups true, false exclude String failovermethod String fastestmirror_enabled true, false gpgcheck true, false # default value: true gpgkey String, Array http_caching String include_config String includepkgs String keepalive true, false make_cache true, false # default value: true max_retries String, Integer metadata_expire String metalink String mirror_expire String mirrorlist String mirrorlist_expire String mode String, Integer # default value: "0644" options Hash password String priority String proxy String proxy_password String proxy_username String repo_gpgcheck true, false report_instanceid true, false reposdir String # default value: "/etc/yum.repos.d/" repositoryid String # default value: 'name' unless specified skip_if_unavailable true, false source String sslcacert String sslclientcert String sslclientkey String sslverify true, false throttle String, Integer timeout String username String action Symbol # defaults to :create if not specified end ``` where: * `yum_repository` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `baseurl`, `clean_metadata`, `cost`, `description`, `enabled`, `enablegroups`, `exclude`, `failovermethod`, `fastestmirror_enabled`, `gpgcheck`, `gpgkey`, `http_caching`, `include_config`, `includepkgs`, `keepalive`, `make_cache`, `max_retries`, `metadata_expire`, `metalink`, `mirror_expire`, `mirrorlist`, `mirrorlist_expire`, `mode`, `options`, `password`, `priority`, `proxy`, `proxy_password`, `proxy_username`, `repo_gpgcheck`, `report_instanceid`, `reposdir`, `repositoryid`, `skip_if_unavailable`, `source`, `sslcacert`, `sslclientcert`, `sslclientkey`, `sslverify`, `throttle`, `timeout`, and `username` are the properties available to this resource. Actions ------- --- The **yum_repository** resource has the following actions: `:create` Create a repository based on the properties. (default) `:delete` Remove a repository. `:makecache` Force the creation of the repository cache. This is also done automatically when a repository is updated. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. Properties ---------- --- The **yum_repository** resource has the following properties: `baseurl` **Ruby Type:** String, Array URL to the directory where the Yum repository’s `repodata` directory lives. Can be an `http://`, `https://` or a `ftp://` URLs. You can specify multiple URLs in one `baseurl` statement. `clean_metadata` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether you want to purge all of the packages downloaded from a Yum repository and held in a cache directory. `cost` **Ruby Type:** String Relative cost of accessing this repository. Useful for weighing one repo’s packages as greater/less than any other. `description` **Ruby Type:** String | **Default Value:** `Yum Repository` Descriptive name for the repository channel and maps to the ‘name’ parameter in a repository .conf. `enabled` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether or not Yum should use this repository. `enablegroups` **Ruby Type:** true, false Specifies whether Yum will allow the use of package groups for this repository. `exclude` **Ruby Type:** String List of packages to exclude from updates or installs. This should be a space separated list. Shell globs using wildcards (eg. * and ?) are allowed. `failovermethod` **Ruby Type:** String **Allowed Values:** `"priority", "roundrobin"` Method to determine how to switch to a new server if the current one fails, which can either be `roundrobin` or `priority`. `roundrobin` randomly selects a URL out of the list of URLs to start with and proceeds through each of them as it encounters a failure contacting the host. `priority` starts from the first `baseurl` listed and reads through them sequentially. `fastestmirror_enabled` **Ruby Type:** true, false Specifies whether to use the fastest mirror from a repository configuration when more than one mirror is listed in that configuration. `gpgcheck` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether or not Yum should perform a GPG signature check on the packages received from a repository. `gpgkey` **Ruby Type:** String, Array URL pointing to the ASCII-armored GPG key file for the repository. This is used if Yum needs a public key to verify a package and the required key hasn’t been imported into the RPM database. If this option is set, Yum will automatically import the key from the specified URL. Multiple URLs may be specified in the same manner as the baseurl option. If a GPG key is required to install a package from a repository, all keys specified for that repository will be installed. Multiple URLs may be specified in the same manner as the baseurl option. If a GPG key is required to install a package from a repository, all keys specified for that repository will be installed. `http_caching` **Ruby Type:** String **Allowed Values:** `"all", "none", "packages"` Determines how upstream HTTP caches are instructed to handle any HTTP downloads that Yum does. This option can take the following values: * `all` means all HTTP downloads should be cached * `packages` means only RPM package downloads should be cached, but not repository metadata downloads * `none` means no HTTP downloads should be cached. The default value of `all` is recommended unless you are experiencing caching related issues. `include_config` **Ruby Type:** String An external configuration file using the format `url://to/some/location`. `includepkgs` **Ruby Type:** String Inverse of exclude property. This is a list of packages you want to use from a repository. If this option lists only one package then that is all Yum will ever see from the repository. `keepalive` **Ruby Type:** true, false Determines whether or not HTTP/1.1 `keep-alive` should be used with this repository. `make_cache` **Ruby Type:** true, false | **Default Value:** `true` Determines whether package files downloaded by Yum stay in cache directories. By using cached data, you can carry out certain operations without a network connection. `max_retries` **Ruby Type:** String, Integer Number of times any attempt to retrieve a file should retry before returning an error. Setting this to `0` makes Yum try forever. `metadata_expire` **Ruby Type:** String Time (in seconds) after which the metadata will expire. If the current metadata downloaded is less than the value specified, then Yum will not update the metadata against the repository. If you find that Yum is not downloading information on updates as often as you would like lower the value of this option. You can also change from the default of using seconds to using days, hours or minutes by appending a `d`, `h` or `m` respectively. The default is six hours to compliment yum-updates running once per hour. It is also possible to use the word `never`, meaning that the metadata will never expire. Note When using a metalink file, the metalink must always be newer than the metadata for the repository due to the validation, so this timeout also applies to the metalink file. `metalink` **Ruby Type:** String Specifies a URL to a metalink file for the repomd.xml, a list of mirrors for the entire repository are generated by converting the mirrors for the repomd.xml file to a baseurl. `mirror_expire` **Ruby Type:** String Time (in seconds) after which the mirrorlist locally cached will expire. If the current mirrorlist is less than this many seconds old then Yum will not download another copy of the mirrorlist, it has the same extra format as metadata_expire. If you find that Yum is not downloading the mirrorlists as often as you would like lower the value of this option. You can also change from the default of using seconds to using days, hours or minutes by appending a `d`, `h` or `m` respectively. `mirrorlist` **Ruby Type:** String URL to a file containing a list of baseurls. This can be used instead of or with the baseurl option. Substitution variables, described below, can be used with this option. `mirrorlist_expire` **Ruby Type:** String Specifies the time (in seconds) after which the mirrorlist locally cached will expire. If the current mirrorlist is less than the value specified, then Yum will not download another copy of the mirrorlist. You can also change from the default of using seconds to using days, hours or minutes by appending a `d`, `h` or `m` respectively. `mode` **Ruby Type:** String, Integer | **Default Value:** `0644` Permissions mode of .repo file on disk. This is useful for scenarios where secrets are in the repo file. If this value is set to `600`, normal users will not be able to use Yum search, Yum info, etc. `options` **Ruby Type:** Hash Specifies the repository options. `password` **Ruby Type:** String Password to use with the username for basic authentication. `priority` **Ruby Type:** String Assigns a priority to a repository where the priority value is between `1` and `99` inclusive. Priorities are used to enforce ordered protection of repositories. Packages from repositories with a lower priority (higher numerical value) will never be used to upgrade packages that were installed from a repository with a higher priority (lower numerical value). The repositories with the lowest numerical priority number have the highest priority. `proxy` **Ruby Type:** String URL to the proxy server that Yum should use. `proxy_password` **Ruby Type:** String Password for this proxy. `proxy_username` **Ruby Type:** String Username to use for proxy. `repo_gpgcheck` **Ruby Type:** true, false Determines whether or not Yum should perform a GPG signature check on the repodata from this repository. `report_instanceid` **Ruby Type:** true, false Determines whether to report the instance ID when using Amazon Linux AMIs and repositories. `reposdir` **Ruby Type:** String | **Default Value:** `/etc/yum.repos.d/` The directory where the Yum repository files should be stored New in Chef Infra Client 16.9 `repositoryid` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the repository name if it differs from the resource block’s name. `skip_if_unavailable` **Ruby Type:** true, false Allow yum to continue if this repository cannot be contacted for any reason. `source` **Ruby Type:** String Use a custom template source instead of the default one. `sslcacert` **Ruby Type:** String Path to the directory containing the databases of the certificate authorities Yum should use to verify SSL certificates. `sslclientcert` **Ruby Type:** String Path to the SSL client certificate Yum should use to connect to repos/remote sites. `sslclientkey` **Ruby Type:** String Path to the SSL client key Yum should use to connect to repos/remote sites. `sslverify` **Ruby Type:** true, false Determines whether Yum will verify SSL certificates/hosts. `throttle` **Ruby Type:** String, Integer Enable bandwidth throttling for downloads. `timeout` **Ruby Type:** String Number of seconds to wait for a connection before timing out. Defaults to 30 seconds. This may be too short of a time for extremely overloaded sites. `username` **Ruby Type:** String Username to use for basic authentication to a repository. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **yum_repository** resource in recipes: **Add an internal company repository**: ``` yum_repository 'OurCo' do description 'OurCo yum repository' mirrorlist 'http://artifacts.ourco.org/mirrorlist?repo=ourco-8&arch=$basearch' gpgkey 'http://artifacts.ourco.org/pub/yum/RPM-GPG-KEY-OURCO-8' action :create end ``` **Delete a repository**: ``` yum_repository 'CentOS-Media' do action :delete end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/yum_repository/zypper_package Resource ======================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [zypper_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/zypper_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **zypper_package** resource to install, upgrade, and remove packages with Zypper for the SUSE Enterprise and openSUSE platforms. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. Syntax ------ --- The full syntax for all of the properties that are available to the **zypper_package** resource is: ``` zypper_package 'name' do allow_downgrade true, false # default value: true global_options String, Array gpg_check true, false # default value: "true" options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `zypper_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `global_options`, `gpg_check`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. Actions ------- --- The **zypper_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:lock` Locks the zypper package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:unlock` Unlocks the zypper package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. Properties ---------- --- The **zypper_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. New in Chef Client 13.6 `global_options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. For example, common zypper directives, such as `--no-recommends`. See the [zypper man page](https://en.opensuse.org/SDB:Zypper_manual_(plain)) for the full list. New in Chef Client 14.6 `gpg_check` **Ruby Type:** true, false | **Default Value:** `true` Verify the package’s GPG signature. Can also be controlled site-wide using the `zypper_check_gpg` config option. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Examples -------- --- The following examples demonstrate various approaches for using the **zypper_package** resource in recipes: **Install a package using package manager:** ``` zypper_package 'name of package' do action :install end ``` **Install a package using local file:** ``` zypper_package 'jwhois' do action :install source '/path/to/jwhois.rpm' end ``` **Install without using recommend packages as a dependency:** ``` package 'apache2' do options '--no-recommends' end ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/zypper_package/yum_package Resource ===================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [yum_package.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/yum_package.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **yum_package** resource to install, upgrade, and remove packages with Yum for the Red Hat and CentOS platforms. The yum_package resource is able to resolve `provides` data for packages much like Yum can do when it is run from the command line. This allows a variety of options for installing packages, like minimum versions, virtual provides, and library names. Note Support for using file names to install packages (as in `yum_package '/bin/sh'`) is not available because the volume of data required to parse for this is excessive. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. Syntax ------ --- The full syntax for all of the properties that are available to the **yum_package** resource is: ``` yum_package 'name' do allow_downgrade true, false # default value: true arch String, Array flush_cache Hash # default value: {"before"=>false, "after"=>false} options String, Array package_name String, Array source String timeout String, Integer version String, Array yum_binary String action Symbol # defaults to :install if not specified end ``` where: * `yum_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `arch`, `flush_cache`, `options`, `package_name`, `source`, `timeout`, `version`, and `yum_binary` are the properties available to this resource. Actions ------- --- The **yum_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:lock` Locks the yum package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:unlock` Unlocks the yum package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. This action will ignore the `version` attribute. Properties ---------- --- The **yum_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. `arch` **Ruby Type:** String, Array The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name. `flush_cache` **Ruby Type:** Hash | **Default Value:** `{"before"=>false, "after"=>false}` Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Accepts a Hash in the form: { :before => true/false, :after => true/false } or an Array in the form [ :before, :after ]. Yum automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while the Chef Infra Client run is in-progress. As an array: ``` yum_package 'some-package' do #... flush_cache [ :before ] #... end ``` and as a Hash: ``` yum_package 'some-package' do #... flush_cache( { :after => true } ) #... end ``` Note The `flush_cache` property does not flush the local Yum cache! Use Yum tools—`yum clean headers`, `yum clean packages`, `yum clean all`—to clean the local Yum cache. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array One of the following: the name of a package, the name of a package and its architecture, the name of a dependency. Default value: the `name` of the resource block. See “Syntax” section above for more information. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. This property is ignored when using the `:upgrade` action. `yum_binary` **Ruby Type:** String The path to the yum binary. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. Examples -------- --- The following examples demonstrate various approaches for using the **yum_package** resource in recipes: **Install an exact version**: ``` yum_package 'netpbm = 10.35.58-8.el8' ``` **Install a minimum version**: ``` yum_package 'netpbm >= 10.35.58-8.el8' ``` **Install a minimum version using the default action**: ``` yum_package 'netpbm' ``` **Install a version without worrying about the exact release**: ``` yum_package 'netpbm-10.35*' ``` **To install a package**: ``` yum_package 'netpbm' do action :install end ``` **To install a partial minimum version**: ``` yum_package 'netpbm >= 10' ``` **To install a specific architecture**: ``` yum_package 'netpbm' do arch 'i386' end ``` or: ``` yum_package 'netpbm.x86_64' ``` **To install a specific version-release** ``` yum_package 'netpbm' do version '10.35.58-8.el8' end ``` **Handle cookbook_file and yum_package resources in the same recipe**: When a **cookbook_file** resource and a **yum_package** resource are both called from within the same recipe, use the `flush_cache` attribute to dump the in-memory Yum cache, and then use the repository immediately to ensure that the correct package is installed: ``` cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' end yum_package 'pkg-that-is-only-in-custom-repo' do action :install flush_cache [ :before ] end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/yum_package/zypper_repository Resource =========================== Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [zypper_repository.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/zypper_repository.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](../index) --- Use the **zypper_repository** resource to create Zypper package repositories on SUSE Enterprise Linux and openSUSE systems. This resource maintains full compatibility with the **zypper_repository** resource in the existing **zypper** cookbook. **New in Chef Infra Client 13.3.** Syntax ------ --- The full syntax for all of the properties that are available to the **zypper_repository** resource is: ``` zypper_repository 'name' do autorefresh true, false # default value: true baseurl String cookbook String # default value: "The cookbook containing the resource" description String enabled true, false # default value: true gpgautoimportkeys true, false # default value: true gpgcheck true, false # default value: true gpgkey String, Array # default value: [] keeppackages true, false # default value: false mirrorlist String mode String, Integer # default value: "0644" path String priority Integer # default value: 99 refresh_cache true, false # default value: true repo_name String # default value: 'name' unless specified source String type String # default value: "NONE" action Symbol # defaults to :create if not specified end ``` where: * `zypper_repository` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `autorefresh`, `baseurl`, `cookbook`, `description`, `enabled`, `gpgautoimportkeys`, `gpgcheck`, `gpgkey`, `keeppackages`, `mirrorlist`, `mode`, `path`, `priority`, `refresh_cache`, `repo_name`, `source`, and `type` are the properties available to this resource. Actions ------- --- The **zypper_repository** resource has the following actions: `:create` Add a new Zypper repository. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:refresh` Refresh Zypper repository. `:remove` Remove a Zypper repository. Properties ---------- --- The **zypper_repository** resource has the following properties: `autorefresh` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the repository should be refreshed automatically. `baseurl` **Ruby Type:** String The base URL for the Zypper repository, such as `http://download.opensuse.org`. `cookbook` **Ruby Type:** String | **Default Value:** `The cookbook containing the resource` The cookbook to source the repository template file from. Only necessary if you’re using a custom template for the repository file. `description` **Ruby Type:** String The description of the repository that will be shown by the `zypper repos` command. `enabled` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the repository should be enabled. `gpgautoimportkeys` **Ruby Type:** true, false | **Default Value:** `true` Automatically import the specified key when setting up the repository. `gpgcheck` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not to perform a GPG signature check on the repository. `gpgkey` **Ruby Type:** String, Array | **Default Value:** `[]` The location of the repository key(s) to be imported. `keeppackages` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not packages should be saved. `mirrorlist` **Ruby Type:** String The URL of the mirror list that will be used. `mode` **Ruby Type:** String, Integer | **Default Value:** `0644` The file mode of the repository file. `path` **Ruby Type:** String The relative path from the repository’s base URL. `priority` **Ruby Type:** Integer | **Default Value:** `99` Determines the priority of the Zypper repository. `refresh_cache` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the package cache should be refreshed. `repo_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the repository name if it differs from the resource block’s name. `source` **Ruby Type:** String The name of the template for the repository file. Only necessary if you’re using a custom template for the repository file. `type` **Ruby Type:** String | **Default Value:** `NONE` Specifies the repository type. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **zypper_repository** resource in recipes: **Add the Apache repo on openSUSE Leap 15**: ``` zypper_repository 'apache' do baseurl 'http://download.opensuse.org/repositories/Apache' path '/openSUSE_Leap_15.2' type 'rpm-md' priority '100' end ``` **Remove the repo named ‘apache’**: ``` zypper_repository 'apache' do action :delete end ``` **Refresh the repo named ‘apache’**: ``` zypper_repository 'apache' do action :refresh end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/zypper_repository/Writing Ohai Custom Plugins =========================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/ohai_custom.md) You can write custom Ohai plugins to collect additional configuration attributes with Ohai to provide to Chef Infra Client during runs. Ohai plugins are written in Ruby with a plugin DSL documented below. Being written in Ruby provides access to all Ruby’s built-in functionality, as well as 3rd party gem functionality. Plugins can parse the output of any local command on the node, or they can fetch data from external APIs. Examples of plugins that users have written: - A plugin to gather node information including data center, rack, and rack position from an inventory server - A plugin to gather additional RAID array information from a controller utility - A plugin to gather hardware warranty information from a vendor API See [About Ohai](../ohai/index) for information on Ohai configuration and usage. Install Ohai Plugins -------------------- Install custom Ohai plugins by creating an `ohai` directory in your cookbook and saving your plugin code to this location. To migrate custom Ohai plugins from the deprecated ohai cookbook: 1. Create an `ohai` directory in your cookbook 2. Move your plugin into the `ohai` directory 3. Remove the outdated custom Ohai plugin installation code from your code Chef Infra Client will move the file into the correct location, load it, and return the data in the next configuration run. Chef Infra Client will provide other cookbooks that depend on the custom Ohai plugin with the correct data. Syntax ------ The syntax for an Ohai plugin is as follows: ``` Ohai.plugin(:Name) do provides 'attribute', 'attribute/subattribute' depends 'attribute', 'attribute' def shared_method # some Ruby code that defines the shared method attribute my_data end collect_data(:default) do # some Ruby code attribute my_data end collect_data(:platform...) do # some Ruby code that defines platform-specific requirements attribute my_data end end ``` where * Required. `(:Name)` is used to identify the plugin; when two plugins have the same `(:Name)`, those plugins are joined together and run as if they were a single plugin. This value must be a valid Ruby class name, starting with a capital letter and containing only alphanumeric characters * Required. `provides` is a comma-separated list of one (or more) attributes that are defined by this plugin. This attribute will become an automatic attribute (`node['attribute']`) after it is collected by Ohai at the start of a Chef Infra Client run. An attribute can also be defined using an `attribute/subattribute` pattern * `depends` is a comma-separated list of one (or more) attributes that are collected by another plugin; as long as the value is collected by another Ohai plugin, it can be used by any plugin * `shared_method` defines code that can be shared among one (or more) `collect_data` blocks; for example, instead of defining a mash for each `collect_data` block, the code can be defined as a shared method, and then called from any `collect_data` block * `collect_data` is a block of Ruby code that is called by Ohai when it runs; one (or more) `collect_data` blocks can be defined in a plugin, but only a single `collect_data` block is ever run. * `collect_data(:default)` is the code block that runs when a node’s platform is not defined by a platform-specific `collect_data` block * `collect_data(:platform)` is a platform-specific code block that is run when a match exists between the node’s platform and this `collect_data` block; only one `collect_data` block may exist for each platform; possible values: `:aix`, `:darwin`, `:freebsd`, `:linux`, `:openbsd`, `:netbsd`, `:solaris2`, `:windows`, or any other value from `RbConfig::CONFIG['host_os']` * `my_data` is string (`a string value`) or an empty mash (`{ :setting_a => 'value_a', :setting_b => 'value_b' }`). This is used to define the data that should be collected by the plugin For example, the following plugin looks up data on virtual machines hosted in Amazon EC2, Google Compute Engine, Rackspace, Eucalyptus, Linode, OpenStack, and Microsoft Azure: ``` Ohai.plugin(:Cloud) do provides 'cloud' depends 'ec2' depends 'gce' depends 'rackspace' depends 'eucalyptus' depends 'linode' depends 'openstack' depends 'azure' def create_objects cloud Mash.new cloud[:public_ips] = [] cloud[:private_ips] = [] end ... def on_gce? gce != nil end def get_gce_values cloud[:public_ipv4] = [] cloud[:local_ipv4] = [] public_ips = gce['instance']['networkInterfaces'].collect do |interface| if interface.has_key?('accessConfigs') interface['accessConfigs'].collect{|ac| ac['externalIp']} end end.flatten.compact private_ips = gce['instance']['networkInterfaces'].collect do |interface| interface['ip'] end.compact cloud[:public_ips] += public_ips cloud[:private_ips] += private_ips cloud[:public_ipv4] += public_ips cloud[:public_hostname] = nil cloud[:local_ipv4] += private_ips cloud[:local_hostname] = gce['instance']['hostname'] cloud[:provider] = 'gce' end ... # with following similar code blocks for each cloud provider ``` where * `provides` defines the `cloud` attribute, which is then turned into an object using the `create_objects` shared method, which then generates a hash based on public or private IP addresses * For Google Compute Engine the `cloud` attribute data is populated into a hash based on the IP address for the node To see the rest of the code in this plugin, go to: <https://github.com/chef/ohai/blob/main/lib/ohai/plugins/cloud.rb>. Ohai Methods ------------ The Ohai DSL is a Ruby DSL that is used to define an Ohai plugin and to ensure that Ohai collects the right data at the start of every Chef Infra Client run. The Ohai DSL is a small DSL with a single method that is specific to Ohai plugins. Because the Ohai DSL is a Ruby DSL, anything that can be done using Ruby can also be done when defining an Ohai plugin. ### collect_data The `collect_data` method is a block of Ruby code that is called by Ohai when it runs. One (or more) `collect_data` blocks can be defined in a plugin, but only a single `collect_data` block is ever run. The `collect_data` block that is run is determined by the platform on which the node is running, which is then matched up against the available `collect_data` blocks in the plugin. * A `collect_data(:default)` block is used when Ohai is not able to match the platform of the node with a `collect_data(:platform)` block in the plugin * A `collect_data(:platform)` block is required for each platform that requires non-default behavior When Ohai runs, if there isn’t a matching `collect_data` block for a platform, the `collect_data(:default)` block is used. The syntax for the `collect_data` method is: ``` collect_data(:default) do # some Ruby code end ``` or: ``` collect_data(:platform) do # some Ruby code end ``` where: * `:default` is the name of the default `collect_data` block * `:platform` is the name of a platform, such as `:aix` for AIX or `:windows` for Microsoft Windows #### Use a Mash Use a mash to store data. This is done by creating a new mash, and then setting an attribute to it. For example: ``` provides 'name_of_mash' name_of_mash Mash.new name_of_mash[:attribute] = 'value' ``` #### Examples The following examples show how to use the `collect_data` block: ``` Ohai.plugin(:Azure) do provides 'azure' collect_data do azure_metadata_from_hints = hint?('azure') if azure_metadata_from_hints Ohai::Log.debug('azure_metadata_from_hints is present.') azure Mash.new azure_metadata_from_hints.each {|k, v| azure[k] = v } else Ohai::Log.debug('No hints present for azure.') false end end end ``` or: ``` require 'ohai/mixin/ec2_metadata' extend Ohai::Mixin::Ec2Metadata Ohai.plugin do provides 'openstack' collect_data do if hint?('openstack') || hint?('hp') Ohai::Log.debug('ohai openstack') openstack Mash.new if can_metadata_connect?(EC2_METADATA_ADDR,80) Ohai::Log.debug('connecting to the OpenStack metadata service') self.fetch_metadata.each {|k, v| openstack[k] = v } case when hint?('hp') openstack['provider'] = 'hp' else openstack['provider'] = 'openstack' end else Ohai::Log.debug('unable to connect to the OpenStack metadata service') end else Ohai::Log.debug('NOT ohai openstack') end end end ``` ### require The `require` method is a standard Ruby method that can be used to list files that may be required by a platform, such as an external class library. As a best practice, even though the `require` method is often used at the top of a Ruby file, it is recommended that the use of the `require` method be used as part of the platform-specific `collect_data` block. For example, the Ruby WMI is required with Microsoft Windows: ``` collect_data(:windows) do require 'ruby-wmi' WIN32OLE.codepage = WIN32OLE::CP_UTF8 kernel Mash.new host = WMI::Win32_OperatingSystem.find(:first) kernel[:os_info] = Mash.new host.properties_.each do |p| kernel[:os_info][p.name.wmi_underscore.to_sym] = host.send(p.name) end ... end ``` Ohai will attempt to fully qualify the name of any class by prepending `Ohai::` to the loaded class. For example both: ``` require Ohai::Mixin::ShellOut ``` and: ``` require Mixin::ShellOut ``` are both understood by the Ohai in the same way: `Ohai::Mixin::ShellOut`. When a class is an external class (and therefore should not have `Ohai::` prepended), use `::` to let the Ohai know. For example: ``` ::External::Class::Library ``` #### /common Directory The `/common` directory stores code that is used across all Ohai plugins. For example, a file in the `/common` directory named `virtualization.rb` that includes code like the following: ``` module Ohai module Common module Virtualization def host?(virtualization) !virtualization.nil? && virtualization[:role].eql?('host') end def open_virtconn(system) begin require 'libvirt' require 'hpricot' rescue LoadError => e Ohai::Log.debug('Cannot load gem: #{e}.') end emu = (system.eql?('kvm') ? 'qemu' : system) virtconn = Libvirt::open_read_only('#{emu}:///system') end ... def networks(virtconn) networks = Mash.new virtconn.list_networks.each do |n| nv = virtconn.lookup_network_by_name n networks[n] = Mash.new networks[n][:xml_desc] = (nv.xml_desc.split('\n').collect {|line| line.strip}).join ['bridge_name','uuid'].each {|a| networks[n][a] = nv.send(a)} #xdoc = Hpricot networks[n][:xml_desc] end networks end ... end end end ``` can then be leveraged in a plugin by using the `require` method to require the `virtualization.rb` file and then later calling each of the methods in the required module: ``` require 'ohai/common/virtualization' Ohai.plugin(:Virtualization) do include Ohai::Common::Virtualization provides 'virtualization' %w{ capabilities domains networks storage }.each do |subattr| provides 'virtualization/#{subattr}' end collect_data(:linux) do virtualization Mash.new ... if host?(virtualization) v = open_virtconn(virtualization[:system]) virtualization[:libvirt_version] = libvirt_version(v) virtualization[:nodeinfo] = nodeinfo(v) virtualization[:uri] = uri(v) virtualization[:capabilities] = capabilities(v) virtualization[:domains] = domains(v) virtualization[:networks] = networks(v) virtualization[:storage] = storage(v) close_virtconn(v) end ``` ### Shared Methods Use shared methods to define objects for use in `collect_data` blocks, such as a data structure, a hash, or a mash. The syntax for a shared method is: ``` def a_shared_method # some Ruby code that defines the shared method end ``` The following example declares a shared `cloud` method to collect data about cloud providers based on the type of IP address and then uses the `cloud` object to collect data from different cloud providers. Create `cloud` objects based on the type of IP address: ``` def create_objects cloud Mash.new cloud[:public_ips] = Array.new cloud[:private_ips] = Array.new end ``` Use `cloud` object to collect Linode data: ``` def get_linode_values cloud[:public_ips] << linode['public_ip'] cloud[:private_ips] << linode['private_ip'] cloud[:public_ipv4] = linode['public_ipv4'] cloud[:public_hostname] = linode['public_hostname'] cloud[:local_ipv4] = linode['local_ipv4'] cloud[:local_hostname] = linode['local_hostname'] cloud[:provider] = 'linode' end ``` Use the `cloud` object to collect Azure data: ``` def get_azure_values cloud[:vm_name] = azure['vm_name'] cloud[:public_ips] << azure['public_ip'] cloud[:public_fqdn] = azure['public_fqdn'] cloud[:public_ssh_port] = azure['public_ssh_port'] if azure['public_ssh_port'] cloud[:public_winrm_port] = azure['public_winrm_port'] if azure['public_winrm_port'] cloud[:provider] = 'azure' end ``` Logging ------- Use the `Ohai::Log` class in an Ohai plugin to define log entries that are created by Ohai. The syntax for a log message is as follows: ``` Ohai::Log.log_type('message') ``` where * `log_type` can be `.debug`, `.info`, `.warn`, `.error`, or `.fatal` * `'message'` is the message that is logged. For example: ``` Ohai.plugin do provides 'openstack' collect_data do if hint?('openstack') || hint?('hp') Ohai::Log.debug('ohai openstack') openstack Mash.new if can_metadata_connect?(EC2_METADATA_ADDR,80) Ohai::Log.debug('connecting to the OpenStack metadata service') self.fetch_metadata.each {|k, v| openstack[k] = v } case when hint?('hp') openstack['provider'] = 'hp' else openstack['provider'] = 'openstack' end else Ohai::Log.debug('unable to connect to the OpenStack metadata service') end else Ohai::Log.debug('NOT ohai openstack') end end end ``` ### rescue Use the `rescue` clause to make sure that a log message is always provided. For example: ``` rescue LoadError => e Ohai::Log.debug('ip_scopes: cannot load gem, plugin disabled: #{e}') end ``` Examples -------- The following examples show different ways of building Ohai plugins. ### collect_data Blocks The following Ohai plugin uses multiple `collect_data` blocks and shared methods to define platforms: ``` Ohai.plugin(:Hostname) do provides 'domain', 'fqdn', 'hostname' def from_cmd(cmd) so = shell_out(cmd) so.stdout.split($/)[0] end def collect_domain if fqdn fqdn =~ /.+?\.(.*)/ domain $1 end end collect_data(:aix, :hpux) do hostname from_cmd('hostname -s') fqdn from_cmd('hostname') domain collect_domain end collect_data(:darwin, :netbsd, :openbsd) do hostname from_cmd('hostname -s') fqdn from_cmd('hostname') domain collect_domain end collect_data(:freebsd) do hostname from_cmd('hostname -s') fqdn from_cmd('hostname -f') domain collect_domain end collect_data(:linux) do hostname from_cmd('hostname -s') begin fqdn from_cmd('hostname --fqdn') rescue Ohai::Log.debug('hostname -f returned an error, probably no domain is set') end domain collect_domain end collect_data(:solaris2) do require 'socket' hostname from_cmd('hostname') fqdn_lookup = Socket.getaddrinfo(hostname, nil, nil, nil, nil, Socket::AI_CANONNAME).first[2] if fqdn_lookup.split('.').length > 1 # we received an fqdn fqdn fqdn_lookup else # default to assembling one h = from_cmd('hostname') d = from_cmd('domainname') fqdn '#{h}.#{d}' end domain collect_domain end collect_data(:windows) do require 'ruby-wmi' require 'socket' host = WMI::Win32_ComputerSystem.find(:first) hostname '#{host.Name}' info = Socket.gethostbyname(Socket.gethostname) if info.first =~ /.+?\.(.*)/ fqdn info.first else # host is not in dns. optionally use: # C:\WINDOWS\system32\drivers\etc\hosts fqdn Socket.gethostbyaddr(info.last).first end domain collect_domain end end ``` ### Use a mixin Library The following Ohai example shows a plugin can use a `mixin` library and also depend on another plugin: ``` require 'ohai/mixin/os' Ohai.plugin(:Os) do provides 'os', 'os_version' depends 'kernel' collect_data do os collect_os os_version kernel[:release] end end ``` ### Get Kernel Values The following Ohai example shows part of a file that gets initial kernel attribute values: ``` Ohai.plugin(:Kernel) do provides 'kernel', 'kernel/modules' def init_kernel kernel Mash.new [['uname -s', :name], ['uname -r', :release], ['uname -v', :version], ['uname -m', :machine]].each do |cmd, property| so = shell_out(cmd) kernel[property] = so.stdout.split($/)[0] end kernel end ... collect_data(:darwin) do kernel init_kernel kernel[:os] = kernel[:name] so = shell_out('sysctl -n hw.optional.x86_64') if so.stdout.split($/)[0].to_i == 1 kernel[:machine] = 'x86_64' end modules = Mash.new so = shell_out('kextstat -k -l') so.stdout.lines do |line| if line =~ /(\d+)\s+(\d+)\s+0x[0-9a-f]+\s+0x([0-9a-f]+)\s+0x[0-9a-f]+\s+([a-zA-Z0-9\.]+) \(([0-9\.]+)\)/ kext[$4] = { :version => $5, :size => $3.hex, :index => $1, :refcount => $2 } end end kernel[:modules] = modules end ... ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ohai_custom/Community Plugins ================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/plugin_community.md) This page lists plugins for Ohai plugins and Chef Infra Client handlers that are developed and maintained by the Chef community. Ohai ---- Ohai is a tool for collecting system configuration data, which it then provides to Chef Infra Client to use in cookbooks. Chef Infra Client runs Ohai at the start of every Chef Infra run to determine system state. The attributes that Ohai collects are called `automatic attributes`. Chef Infra Client uses these attributes to ensure that nodes are in the desired state after each configuration run. The types of attributes Ohai collects include but are not limited to: * Operating System * Network * Memory * Disk * CPU * Kernel * Host names * Fully qualified domain names * Virtualization * Cloud provider metadata Ohai includes required and optional plugins to detect common configuration information. Ohai has a plugin model and language to write [custom plugins](../ohai_custom/index) to collect additional system state information. The following Ohai plugins are available from the open source community: | Plugin | Description | | --- | --- | | [dell.rb](https://github.com/demonccc/chef-ohai-plugins/blob/master/dell.rb) | Adds some useful Dell server information to Ohai. For example: service tag, express service code, storage info, RAC info, and so on. To use this plugin, OMSA and SMBIOS applications need to be installed. | | [ipmi.rb](https://bitbucket.org/retr0h/ohai) | Adds a MAC address and an IP address to Ohai, where available. | | [kvm_extensions.rb](https://github.com/albertsj1/ohai-plugins/blob/master/kvm_extensions.rb) | Adds extensions for virtualization attributes to provide additional host and guest information for KVM. | | [ladvd.rb](https://github.com/demonccc/chef-ohai-plugins/blob/master/linux/ladvd.rb) | Adds ladvd information to Ohai, when it exists. | | [lxc_virtualization.rb](https://github.com/jespada/ohai-plugins/blob/master/lxc_virtualization.rb) | Adds extensions for virtualization attributes to provide host and guest information for Linux containers. | | [network_addr.rb](https://gist.github.com/1040543) | Adds extensions for network attributes with additional `ipaddrtype_iface` attributes to make it semantically easier to retrieve addresses. | | [network_ports.rb](https://github.com/agoddard/ohai-plugins/blob/master/plugins/network_ports.rb) | Adds extensions for network attributes so that Ohai can detect to which interfaces TCP and UDP ports are bound. | | [parse_host_plugin.rb](https://github.com/sbates/Chef-odds-n-ends/blob/master/ohai/parse_host_plugin.rb) | Adds the ability to parse a host name using three top-level attribute and five nested attributes. | | [r.rb](https://github.com/stevendanna/ohai-plugins/blob/master/plugins/r.rb) | Adds the ability to collect basic information about the R Project. | | [sysctl.rb](https://github.com/spheromak/cookbooks/blob/master/ohai/files/default/sysctl.rb) | Adds sysctl information to Ohai. | | [vserver.rb](https://github.com/albertsj1/ohai-plugins/blob/master/vserver.rb) | Adds extensions for virtualization attributes to allow a Linux virtual server host and guest information to be used by Ohai. | | [wtf.rb](https://github.com/cloudant/ohai_plugins/blob/master/wtf.rb) | Adds the irreverent wtfismyip.com service so that Ohai can determine a machine's external IPv4 address and geographical location. | | [xenserver.rb](https://github.com/spheromak/cookbooks/blob/master/ohai/files/default/xenserver.rb) | Adds extensions for virtualization attributes to load up Citrix XenServer host and guest information. | | [win32_software.rb](https://github.com/timops/ohai-plugins/blob/master/win32_software.rb) | Adds the ability for Ohai to use Windows Management Instrumentation (WMI) to discover useful information about software that is installed on any node that is running Microsoft Windows. | | [win32_svc.rb](https://github.com/timops/ohai-plugins/blob/master/win32_svc.rb) | Adds the ability for Ohai to query using Windows Management Instrumentation (WMI) to get information about all services that are registered on a node that is running Microsoft Windows. | Handlers -------- Use a handler to identify situations that arise during a Chef Infra Client run, and then tell Chef Infra Client how to handle these situations when they occur. The following open source handlers are available from the Chef community: | Handler | Description | | --- | --- | | [Airbrake](https://github.com/timops/ohai-plugins/blob/master/win32_svc.rb) | A handler that sends exceptions (only) to Airbrake, an application that collects data and aggregates it for review. | | [Asynchronous Resources](https://github.com/rottenbytes/chef/tree/master/async_handler) | A handler that asynchronously pushes exception and report handler data to a STOMP queue, from which data can be processed into data storage. | | [Campfire](https://github.com/ampledata/chef-handler-campfire) | A handler that collects exception and report handler data and reports it to Campfire, a web-based group chat tool. | | [Datadog](https://github.com/DataDog/chef-handler-datadog) | A handler that collects Chef Infra Client stats and sends them into a Datadog newsfeed. | | [Flowdock](https://github.com/mmarschall/chef-handler-flowdock) | A handler that collects exception and report handler data and sends it to users via the Flowdock API.. | | [Graphite](https://github.com/imeyer/chef-handler-graphite/wiki) | A handler that collects exception and report handler data and reports it to Graphite, a graphic rendering application. | | [Graylog2 GELF](https://github.com/jellybob/chef-gelf/) | A handler that provides exception and report handler status (including changes) to a Graylog2 server, so that the data can be viewed using Graylog Extended Log Format (GELF). | | [Growl](https://rubygems.org/gems/chef-handler-growl) | A handler that collects exception and report handler data and then sends it as a Growl notification. | | [HipChat](https://github.com/mojotech/hipchat/blob/master/lib/hipchat/chef.rb) | A handler that collects exception handler data and sends it to HipChat, a hosted private chat service for companies and teams. | | [IRC Snitch](https://rubygems.org/gems/chef-irc-snitch) | A handler that notifies administrators (via Internet Relay Chat (IRC)) when a Chef Infra Client run fails. | | [Journald](https://github.com/marktheunissen/chef-handler-journald) | A handler that logs an entry to the systemd journal with the Chef Infra Client run status, exception details, configurable priority, and custom details. | | [net/http](https://github.com/b1-systems/chef-handler-httpapi/) | A handler that reports the status of a Chef run to any API via net/HTTP. | | [Simple Email](https://rubygems.org/gems/chef-handler-mail) | A handler that collects exception and report handler data and then uses pony to send email reports that are based on `.erb` (Embedded Ruby ) templates. | | [SNS](http://onddo.github.io/chef-handler-sns/) | A handler that notifies exception and report handler data and sends it to a SNS topic. | | [Slack](https://github.com/rackspace-cookbooks/chef-slack_handler) | A handler to send Chef Infra Client run notifications to a Slack channel. | | [Splunk Storm](http://ampledata.org/splunk_storm_chef_handler.html) | A handler that supports exceptions and reports for Splunk Storm. | | [Syslog](https://github.com/jblaine/syslog_handler) | A handler that logs basic essential information, such as about the success or failure of a Chef Infra Client run. | | [Updated Resources](https://rubygems.org/gems/chef-handler-updated-resources) | A handler that provides a simple way to display resources that were updated during a Chef Infra Client run. | | [ZooKeeper](http://onddo.github.io/chef-handler-zookeeper/) | A Chef report handler to send Chef run notifications to ZooKeeper. | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/plugin_community/Chef Infra Server Overview ========================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/_index.md) The Chef Infra Server acts as a hub for configuration data. The Chef Infra Server stores cookbooks, the policies that are applied to nodes, and the metadata that describes each registered node that is under management by Chef Infra Client. Nodes use Chef Infra Client to ask the Chef Infra Server for configuration details, such as recipes, templates, and file distributions. Chef Infra Client then does as much of the configuration work as possible on the nodes themselves (and not on the Chef Infra Server). This scalable approach distributes the configuration effort throughout the organization. The Chef Infra Server API is written in [Erlang](http://www.erlang.org/), which is an excellent language for critical enterprise concerns like concurrency, fault-tolerance, and distributed environments. The Chef Infra Server can scale to the size of any enterprise. Note The Chef Infra Server can be configured via the `/etc/opscode/chef-server.rb` file. Whenever this file is modified, the `chef-server-ctl reconfigure` command must be run to apply the changes. See the [Chef Infra Server settings](config_rb_server/index) guide for additional information. Server Components ----------------- The following diagram shows the various components that are part of a Chef Infra Server deployment and how they relate to one another. ![Diagram of Chef Infra Server deployment] | Component | Description | | --- | --- | | Clients | The Chef Infra Server is accessed primarily by nodes that are under management by Chef, as Chef Infra Client runs occur. It is also accessed by individuals who maintain cookbooks and policy that is stored on the Chef Infra Server, typically from a workstation. And also by individual users with credentials to Chef Infra Server components, such as the Chef management console. | | Load Balancer | Nginx is an open-source HTTP and reverse proxy server that is used as the front-end load balancer for the Chef Infra Server. All requests to the Chef Infra Server API are routed through Nginx. | | Chef Manage | Chef Manage is the web interface for the Chef Infra Server, which uses the Chef Infra Server API for all communication to the Chef Infra Server. | | Chef Infra Server | Erchef is a complete rewrite of the core API for the Chef Infra Server, which allows it to be faster and more scalable than previous versions. The API itself is still compatible with the original Ruby-based Chef Infra Server, which means that cookbooks and recipes that were authored for the Ruby-based Chef Infra Server will continue to work on the Erlang-based Chef Infra Server. Chef Infra Client is still written in Ruby. Note Even though the Chef Infra Server is authored in Erlang, writing code in Erlang is NOT a requirement for using Chef Infra. | | Bookshelf | Bookshelf is used to store cookbook content—files, templates, and so on—that have been uploaded to the Chef Infra Server as part of a cookbook version. Cookbook content is stored by content checksum. If two different cookbooks or different versions of the same cookbook include the same file or template, Bookshelf will store that file only once. The cookbook content managed by Bookshelf is stored in flat files and is separated from the Chef Infra Server and search index repositories. All cookbooks are stored in a dedicated repository. | | Messages | chef-elasticsearch wraps Elastisearch and exposes its REST API for indexing and search. All messages are added to a dedicated search index repository. | | PostgreSQL | PostgreSQL is the data storage repository for the Chef Infra Server. | External Cookbooks ------------------ The following diagram highlights the specific changes that occur when cookbooks are stored at an external location, such as Amazon Simple Storage Service (S3). ![image] The following table describes the components that are different from the default configuration of the Chef Infra Server when cookbooks are stored at an external location: | Component | Description | | --- | --- | | Clients | The Chef Infra Server will provide signed URLs for cookbook requests made by the various clients (individual users, knife requests, and from the Chef Infra Client that is installed on nodes under management by Chef Infra). | | Load Balancer | The signed URLs for cookbooks are pointed here, and then routed to cookbook storage, as required. | | Chef Infra Server | Erchef is a complete rewrite of the core API for the Chef Infra Server, which allows it to be faster and more scalable than previous versions. The API itself is still compatible with the original Ruby-based Chef Infra Server, which means that cookbooks and recipes that were authored for the Ruby-based Chef Infra Server will continue to work on the Erlang-based Chef Infra Server. Chef Infra Client is still written in Ruby. Note Even though the Chef Infra Server is authored in Erlang, writing code in Erlang is NOT a requirement for using Chef Infra. | | Amazon Simple Storage Service (S3) | Bookshelf is used to store cookbook content—files, templates, and so on—that have been uploaded to the Chef Infra Server as part of a cookbook version. Cookbook content is stored by content checksum. If two different cookbooks or different versions of the same cookbook include the same file or template, Bookshelf will store that file only once. The cookbook content managed by Bookshelf is stored in flat files and is separated from the Chef Infra Server and search index repositories. This represents external cookbooks storage at Amazon Simple Storage Service (S3). | ### AWS Settings #### Required Settings To configure external cookbook storage using Amazon Simple Storage Service (S3) set the following configuration settings in the `chef-server.rb` file and run `chef-server-ctl reconfigure`: | Setting | Description | | --- | --- | | `bookshelf['access_key_id']` | The access key identifier. Default value: generated by default. Specifying this directly in the configuration file is discouraged. Please use `chef-server-ctl set-secret bookshelf access_key_id` from the [Secrets Management](../ctl_chef_server#ctl-chef-server-secrets-management) commands. | | `bookshelf['external_url']` | The full URL of the S3 bucket. | | `bookshelf['secret_access_key']` | The secret key. Default value: generated by default. Specifying this directly in the configuration file is discouraged. Please use `chef-server-ctl set-secret bookshelf secret_access_key` from the [Secrets Management](../ctl_chef_server#ctl-chef-server-secrets-management) commands. | | `opscode_erchef['s3_bucket']` | The name of the Amazon Simple Storage Service (S3) bucket. Default value: `bookshelf`. | | `bookshelf['vip']` | The virtual IP address or host name of the Amazon Simple Service (S3) API. Default value: `127.0.0.1`. | An example `chef-server.rb` configuration: ``` bookshelf['vip'] = 's3-external-1.amazonaws.com' bookshelf['external_url'] = 'https://s3-external-1.amazonaws.com' bookshelf['access_key_id'] = '<ACCESS_ID>' bookshelf['secret_access_key'] = '<ACCESS_KEY>' opscode_erchef['s3_bucket'] = '<BUCKET_NAME>' ``` #### Optional Settings The following optional settings are also available and may require modification when using an external S3 provider: | Setting | Description | | --- | --- | | `opscode_erchef['nginx_bookshelf_caching']` | Whether Nginx is used to cache cookbooks. When `:on`, Nginx serves up the cached content instead of forwarding the request. Default value: `:off`. | | `opscode_erchef['s3_parallel_ops_fanout']` | Default value: `20`. | | `opscode_erchef['s3_parallel_ops_timeout']` | Default value: `5000`. | | `opscode_erchef['s3_url_expiry_window_size']` | The frequency at which unique URLs are generated. This value may be a specific amount of time, i.e. `15m` (fifteen minutes) or a percentage of the value of `s3_url_ttl`, i.e. `10%`. Default value: `:off`. | | `opscode_erchef['s3_url_ttl']` | The amount of time (in seconds) before connections to the server expire. If node bootstraps are timing out, increase this setting. Default value: `28800`. | External PostgreSQL ------------------- The following diagram highlights the specific changes that occur when PostgreSQL is configured and managed independently of the Chef Infra Server configuration. ![image] The following table describes the components in an external PostgreSQL configuration that are different from the default configuration of the Chef Infra Server: | Component | Description | | --- | --- | | Chef Infra Server | The Chef Infra Server configuration file is updated to point to an independently configured set of servers for PostgreSQL. | | PostgreSQL | PostgreSQL is the data storage repository for the Chef Infra Server. This represents the independently configured set of servers that are running PostgreSQL and are configured to act as the data store for the Chef Infra Server. | ### PostgreSQL Settings Use the following configuration settings in the chef-server.rb file to configure external PostgreSQL for use with the Chef Infra Server: `postgresql['db_superuser']` Required when `postgresql['external']` is set to `true`. The PostgreSQL user name. This user must be granted either the `CREATE ROLE` and `CREATE DATABASE` permissions in PostgreSQL or be granted `SUPERUSER` permission. This user must also have an entry in the host-based authentication configuration file used by PostgreSQL (traditionally named `pg_hba.conf`). Default value: `'superuser_userid'`. `postgresql['db_superuser_password']` The password for the user specified by `postgresql['db_superuser']`. Required when `postgresql['external']` is set to `true`. The db_superuser_password can also be set using `chef-server-ctl set-db-superuser-password` from the [Secrets Management](../ctl_chef_server/index#ctl-chef-server-secrets-management) commands. `postgresql['external']` Required. Set to `true` to run PostgreSQL external to the Chef Infra Server. Must be set once only on a new installation of the Chef Infra Server before the first `chef-server-ctl reconfigure` command is run. If this is set after a reconfigure or set to `false`, any reconfigure of the Chef Infra Server will return an error. Default value: `false`. `postgresql['port']` Optional when `postgresql['external']` is set to `true`. The port on which the service is to listen. The port used by PostgreSQL if that port is **not** 5432. Default value: `5432`. `postgresql['vip']` Required when `postgresql['external']` is set to `true`. The virtual IP address. The host for this IP address must be online and reachable from the Chef Infra Server via the port specified by `postgresql['port']`. Set this value to the IP address or hostname for the machine on which external PostgreSQL is located when `postgresql['external']` is set to `true`. #### Optional Settings The following optional settings are required when configuring external PostgreSQL on Microsoft Azure: `bookshelf['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'bookshelf@my_postgresql.postgres.database.azure.com'`), where `username` would normally equal the value of `bookshelf['sql_user']` (default: `'bookshelf'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `bookshelf['sql_user']` Default value: `nil`. `oc_bifrost['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `oc_bifrost['sql_user']` (default: `'bifrost'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_bifrost['sql_user']`. Default value: `nil`. `oc_id['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `oc_id['sql_user']` (default: `'od_id'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_id['sql_user']`. Default value: `nil`. `opscode_erchef['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `opscode-erchef['sql_user']` (default: `'opscode_chef'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `opscode_erchef['sql_user']`. Default value: `nil`. `postgresql['db_connection_superuser']` The PostgreSQL superuser name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `postgresql['db_superuser']` with any dashes replaced by underscores. This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `postgresql['db_superuser']`. Default value: `nil`. An example `chef-server.rb` configuration for External PostgreSQL on Microsoft Azure: ``` topology 'standalone' postgresql['external'] = true postgresql['vip'] = 'my_postgresql.postgres.database.azure.com' postgresql['db_superuser'] = 'opscode_pgsql' postgresql['db_superuser_password'] = 'My_postgres_password1!' postgresql['db_connection_superuser'] = '<EMAIL>' # postgresql['sslmode']='require' # required if 'Enforce SSL connection' is enabled on Azure PostgreSQL bookshelf['sql_connection_user'] = '<EMAIL>' oc_bifrost['sql_connection_user'] = '<EMAIL>' oc_id['sql_connection_user'] = '<EMAIL>' opscode_erchef['sql_connection_user'] = '<EMAIL>' ``` Note See the list of [error messages that may be present](../errors/index#external-postgresql) when configuring the Chef Infra Server to use a remote PostgreSQL server. ### Bookshelf Settings In instances that require cookbooks to be stored within a SQL backend, such as in a high availability setup, you must set the `storage_type` to `:sql`: ``` bookshelf['storage_type'] = :sql ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/Server Users ============ [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/server_users.md) The following tasks are available for user management in Chef Infra Server: * Creating users * Editing a user’s profile * Changing a password * Recovering a password * Regenerating a private key * Viewing a user’s profile chef-server-ctl --------------- The Chef Infra Server includes a command-line utility named chef-server-ctl. This command-line tool is used to start and stop individual services, reconfigure the Chef Infra Server, run chef-pedant, and then tail Chef Infra Server log files. Use the `user-create`, `user-delete`, `user-edit`, `user-list` and `user-show` subcommands to manage users. ### org-create The `org-create` subcommand is used to create an organization. (The validation key for the organization is returned to `STDOUT` when creating an organization with this command.) **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-create ORG_NAME "ORG_FULL_NAME" (options) ``` where: * The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. * The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `"Chef Software, Inc."`. **Options** This subcommand has the following options: `-a USER_NAME`, `--association_user USER_NAME` Associate a user with an organization and add them to the `admins` and `billing_admins` security groups. `-f FILE_NAME`, `--filename FILE_NAME` Write the ORGANIZATION-validator.pem to `FILE_NAME` instead of printing it to `STDOUT`. ### org-delete The `org-delete` subcommand is used to delete an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-delete ORG_NAME ``` ### org-list The `org-list` subcommand is used to list all of the organizations currently present on the Chef Infra Server. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-list (options) ``` **Options** This subcommand has the following options: `-a`, `--all-orgs` Show all organizations. `-w`, `--with-uri` Show the corresponding URIs. ### org-show The `org-show` subcommand is used to show the details for an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-show ORG_NAME ``` ### org-user-add The `org-user-add` subcommand is used to add a user to an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-user-add ORG_NAME USER_NAME (options) ``` **Options** This subcommand has the following options: `--admin` Add the user to the `admins` group. ### org-user-remove The `org-user-remove` subcommand is used to remove a user from an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-user-remove ORG_NAME USER_NAME (options) ``` ### user-create The `user-create` subcommand is used to create a user. (The validation key for the organization may be returned to `STDOUT` when creating a user with this command.) **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-create USER_NAME FIRST_NAME [MIDDLE_NAME] LAST_NAME EMAIL 'PASSWORD' (options) ``` **Options** This subcommand has the following options: `-f FILE_NAME`, `--filename FILE_NAME` Write the USER.pem to a file instead of `STDOUT`. ### user-delete The `user-delete` subcommand is used to delete a user. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-delete USER_NAME ``` ### user-edit The `user-edit` subcommand is used to edit the details for a user. The data will be made available in the $EDITOR for editing. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-edit USER_NAME ``` ### user-list The `user-list` subcommand is used to view a list of users. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-list (options) ``` **Options** This subcommand has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### user-show The `user-show` subcommand is used to show the details for a user. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-show USER_NAME (options) ``` **Options** This subcommand has the following options: `-l`, `--with-orgs` Show all organizations. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/server_users/Chef InSpec Language ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/dsl_inspec.md) Chef InSpec is a run-time framework and rule language used to specify compliance, security, and policy requirements. It includes a collection of resources that help you write auditing controls quickly and easily. The syntax used by both open source and [Chef compliance](../../compliance/index) auditing is the same. The open source [Chef InSpec resource](../resources/index) framework is compatible with [Chef compliance](../../compliance/index). The Chef InSpec Language is a Ruby DSL for writing audit controls, which includes audit resources that you can invoke. The following sections describe the syntax and show some simple examples of using the Chef InSpec resources. Syntax ------ The following resource tests |ssh| server configuration. For example, a simple control may described as: ``` describe sshd_config do its('Port') { should cmp 22 } end ``` In various use cases like implementing IT compliance across different departments, it becomes handy to extend the control with metadata. Each control may define an additional `impact`, `title` or `desc`. An example looks like: ``` control 'sshd-8' do impact 0.6 title 'Server: Configure the service port' desc 'Always specify which port the SSH server should listen.' desc 'rationale', 'This ensures that there are no unexpected settings' # Requires Chef InSpec >=2.3.4 tag 'ssh','sshd','openssh-server' tag cce: 'CCE-27072-8' ref 'NSA-RH6-STIG - Section 3.5.2.1', url: 'https://www.nsa.gov/ia/_files/os/redhat/rhel5-guide-i731.pdf' describe sshd_config do its('Port') { should cmp 22 } end end ``` where * `'sshd-8'` is the name of the control * `impact`, `title`, and `desc` define metadata that fully describes the importance of the control, its purpose, with a succinct and complete description * `desc` when given only one argument it sets the default description. As of Chef InSpec 2.3.4, when given 2 arguments (see: `'rationale'`) it will use the first argument as a header when rendering in Automate * `impact` is a string, or numeric that measures the importance of the compliance results. Valid strings for impact are `none`, `low`, `medium`, `high`, and `critical`. The values are based off CVSS 3.0. A numeric value must be between `0.0` and `1.0`. The value ranges are: + `0.0 to <0.01` these are controls with no impact, they only provide information + `0.01 to <0.4` these are controls with low impact + `0.4 to <0.7` these are controls with medium impact + `0.7 to <0.9` these are controls with high impact + `0.9 to 1.0` these are critical controls * `tag` is optional meta-information with key or key-value pairs * `ref` is a reference to an external document * `describe` is a block that contains at least one test. A `control` block must contain at least one `describe` block, but may contain as many as required * `sshd_config` is a Chef InSpec resource. For the full list of Chef InSpec resources, see Chef InSpec resource documentation * `its('Port')` is the matcher; `{ should eq '22' }` is the test. A `describe` block must contain at least one matcher, but may contain as many as required Advanced concepts ----------------- ### Checking if at least one condition passes with `describe.one` With Chef InSpec, you can check if at least one of a collection of checks is true. For example, if you configure a setting in two different locations, then you may want to test if either configuration A or configuration B is set. Do this task with the `describe.one` block. `describe.one` defines a set of `describe` blocks where only one block needs to pass. ``` describe.one do describe ConfigurationA do its('setting_1') { should eq true } end describe ConfigurationB do its('setting_2') { should eq true } end end ``` #### `describe.one` usage notes * A `describe.one` block passes if one of its nested `describe` blocks has all assertions passing. A `describe.one` block needs an entire `describe` block to pass and not just a single assertion. * Chef InSpec will always evaluate all the tests contained within `describe.one`. It does not short-circuit upon evaluating a passing `describe` block. * Nesting a `describe.one` block inside another `describe.one` block is not supported. ### Sensitive resources In some scenarios, you may be writing checks that involve resources with sensitive content, such as a file resource. In case of failures, you may desire to suppress output. Do this task by adding the `:sensitive` flag to the resource definition: ``` describe file('/tmp/mysecretfile'), :sensitive do its('content') { should match /secret_info/ } end ``` Examples -------- The following examples show simple compliance tests using a single `control` block. ### Test System Event Log The following test shows how to audit machines running Windows 2012 R2 that password complexity is enabled: ``` control 'windows-account-102' do impact 'critical' title 'Windows Password Complexity is Enabled' desc 'Password must meet complexity requirement' describe security_policy do its('PasswordComplexity') { should cmp 1 } end end ``` ### Test if PostgreSQL passwords are empty The following test shows how to audit machines running PostgreSQL to ensure that passwords are not empty. ``` control 'postgres-7' do impact 1.0 title "Don't allow empty passwords" describe postgres_session('user', 'pass').query("SELECT * FROM pg_shadow WHERE passwd IS NULL;") do its('output') { should cmp '' } end end ``` ### Test if MySQL passwords are in ENV The following test shows how to audit machines running MySQL to ensure that passwords are not stored in `ENV`: ``` control 'mysql-3' do impact 1.0 title 'Do not store your MySQL password in your ENV' desc ' Storing credentials in your ENV may easily expose them to an attacker. Prevent this at all costs. ' describe command('env') do its('stdout') { should_not match /^MYSQL_PWD=/ } end end ``` ### Test if `/etc/ssh` is a Directory The following test shows how to audit machines to ensure that `/etc/ssh` is a directory: ``` control 'basic-1' do impact 1.0 title '/etc/ssh should be a directory' desc ' In order for OpenSSH to function correctly, its configuration path must be a folder. ' describe file('/etc/ssh') do it { should be_directory } end end ``` ### Test if Apache running The following test shows how to audit machines to ensure that Apache is enabled and running: ``` control 'apache-1' do impact 'medium' title 'Apache2 should be configured and running' describe service(apache.service) do it { should be_enabled } it { should be_running } end end ``` ### Test if insecure packages are installed The following test shows how to audit machines for insecure packages: ``` control 'cis-os-services-5.1.3' do impact 0.7 title '5.1.3 Ensure rsh client is not installed' describe package('rsh') do it { should_not be_installed } end describe package('rsh-redone-client') do it { should_not be_installed } end end ``` ### Test Windows Registry Keys The following test shows how to audit machines to ensure Safe DLL Search Mode is enabled: ``` control 'windows-base-101' do impact 1.0 title 'Safe DLL Search Mode is Enabled' desc ' @link: https://msdn.microsoft.com/en-us/library/ms682586(v=vs.85).aspx ' describe registry_key('HKLM\\System\\CurrentControlSet\\Control\\Session Manager') do it { should exist } it { should_not have_property_value('SafeDllSearchMode', :type_dword, '0') } end end ``` ### Use `only_if` to exclude a specific control This example shows how to allow skipping certain controls if conditions are not met by using `only_if`. In this example, the control will not be performed if the `redis-cli` command does not exist. A optional message can say why it was skipped. ``` control 'nutcracker-connect-redis-001' do impact 'critical' title 'Check if nutcracker can pass commands to redis' desc 'execute redis-cli set key command, to check connectivity of the service' only_if('redis is not installed.') do command('redis-cli').exist? end describe command('redis-cli SET test_inspec "HELLO"') do its('stdout') { should match /OK/ } end end ``` This example checks for if certain pip packages are installed, but only if ‘/root/.aws’ exists: ``` control 'pip-packages-installed' do title 'Check if essential pips are installed' only_if('aws-cli config not created.') do directory('/root/.aws').exist? end %w(aws-mfa PyYAML awscli).each do |aws_pip_deps| describe pip(aws_pip_deps) do it { should be_installed } end end end ``` Mixing this with other conditionals, such as checking existence of the files, can help to test different test paths using Chef InSpec. With this way, you can skip certain controls, which would 100% fail due to the way servers are prepared, but you know that the same control suites are reused later in different circumstances by different teams. Some notes about `only_if`: * `only_if` applies to the entire `control`. If the results of the `only_if` block evaluate to false, any Chef InSpec resources mentioned as part of a `describe` block will not be run. Additionally, the contents of the describe blocks will not be run. However, bare Ruby expressions and bare Chef InSpec resources (not assocated with a describe block) preceding the only_if statement will run To illustrate: ``` control "whatruns" do command("do_something") # This will ALWAYS run describe command("do_another_thing") do # This will not run command("do_yet_another_thing") # This will not run end only_if { false } command("do_something_else") # This will not run end ``` * Only one `only_if` is permitted per `control` block. If multiple `only_if` blocks are present, only the last `only_if` block will be honored * If used outside a control block, `only_if` skips all controls in the current file * To implement complex logic, use Ruby ‘or’ (`||`) and ‘and’ (`&&`) inside your `only_if` block: ``` only_if('ready for launch') do rocket_is_ready && weather_is_clear end ``` ### Additional metadata for controls The following example illustrates various ways to add tags and references to `control` ``` control 'ssh-1' do impact 1.0 title 'Allow only SSH Protocol 2' desc ' Only SSH protocol version 2 connections should be permitted. The default setting in /etc/ssh/sshd_config is correct, and can be verified by ensuring that the following line appears: Protocol 2 ' tag 'production','development' tag 'ssh','sshd','openssh-server' tag cce: 'CCE-27072-8' tag disa: 'RHEL-06-000227' tag remediation: 'stig_rhel6/recipes/sshd-config.rb' tag remediation: 'https://supermarket.chef.io/cookbooks/ssh-hardening' ref 'NSA-RH6-STIG - Section 3.5.2.1', url: 'https://www.nsa.gov/ia/_files/os/redhat/rhel5-guide-i731.pdf' ref 'http://people.redhat.com/swells/scap-security-guide/RHEL/6/output/ssg-centos6-guide-C2S.html' describe ssh_config do its('Protocol') { should cmp 2 } end end ``` Using Ruby in InSpec -------------------- The Chef InSpec Language is a Ruby based language. This allows you to be flexible with Ruby code in controls: ``` json_obj = json('/file.json') json_obj['keys'].each do |value| .. end ``` Ruby allows a lot of freedoms, but should be limited in controls so that they remain portable and easy to understand. Please see our [profile style guide](../style/index). Core and custom resources are written as regular Ruby classes which inherit from `Inspec.resource`. ### Interactive Debugging with Pry Here’s a sample Chef InSpec control that uses Ruby variables to instantiate a Chef InSpec resource once and use the content in multiple tests. ``` control 'check-perl' do impact 0.3 title 'Check perl compiled options and permissions' perl_out = command('perl -V') #require 'pry'; binding.pry; describe perl_out do its('exit_status') { should eq 0 } its('stdout') { should match /USE_64_BIT_ALL/ } its('stdout') { should match /useposix=true/ } its('stdout') { should match /-fstack-protector/ } end # extract an array of include directories perl_inc = perl_out.stdout.partition('@INC:').last.strip.split("\n") # ensure include directories are only writable by 'owner' perl_inc.each do |path| describe directory(path.strip) do it { should_not be_writable.by 'group' } it { should_not be_writable.by 'other' } end end end ``` An **advanced** but very useful Ruby tip. In the previous example, I commented out the `require 'pry'; binding.pry;` line. If you remove the `#` prefix and run the control, the execution will stop at that line and give you a `pry` shell. Use that to troubleshoot, print variables, see methods available, etc. For the above example: ``` [1] pry> perl_out.exit_status => 0 [2] pry> perl_out.stderr => "" [3] pry> ls perl_out Inspec::Plugins::Resource#methods: inspect Inspec::Resources::Cmd#methods: command exist? exit_status result stderr stdout to_s Inspec::Resource::Registry::Command#methods: inspec instance variables: @__backend_runner__ @__resource_name__ @command @result [4] pry> perl_out.stdout.partition('@INC:').last.strip.split("\n") => ["/Library/Perl/5.18/darwin-thread-multi-2level", " /Library/Perl/5.18", ...REDACTED... [5] pry> exit # or abort ``` You can use `pry` inside both the controls DSL and resources. Similarly, for dev and test, you can use `inspec shell` which is based on `pry`, for example: ``` $ inspec shell Welcome to the interactive InSpec Shell To find out how to use it, type: help inspec> command('ls ~/projects/github/inspec/docs').stdout => "README.md\nconfig.md\ndev\ndsl_inspec.md\ndsl_resource.md\nglossary.md\nhabitat.md\ninputs.md\ninspec_and_friends.md\nmatchers.md\nmigration.md\nplatforms.md\nplugin_kitchen_inspec.md\nplugins.md\nprofiles.md\nreporters.md\nresources\nshared\nshell.md\nstyle.md\nwaivers.md\n" inspec> command('ls ~/projects/github/inspec/docs').stdout.split("\n").first => "README.md" inspec> help command Name: command Description: Use the command InSpec audit resource to test an arbitrary command that is run on the system. Example: describe command('ls -al /') do it { should exist } its('stdout') { should match /bin/ } its('stderr') { should eq '' } its('exit_status') { should eq 0 } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/dsl_inspec/Server Services =============== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/server_services.md) The Chef Infra Server has a built in process supervisor, which ensures that all of the required services are in the appropriate state at any given time. The supervisor starts two processes per service. Service Subcommands ------------------- This command has a built in process supervisor that ensures all of the required services are in the appropriate state at any given time. The supervisor starts two processes per service and provides the following subcommands for managing services: `hup`, `int`, `kill`, `once`, `restart`, `service-list`, `start`, `status`, `stop`, `tail`, and `term`. ### hup The `hup` subcommand is used to send a `SIGHUP` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl hup SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### int The `int` subcommand is used to send a `SIGINT` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl int SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### kill The `kill` subcommand is used to send a `SIGKILL` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl kill SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### once The supervisor for the Chef Infra Server is configured to restart any service that fails, unless that service has been asked to change its state. The `once` subcommand is used to tell the supervisor to not attempt to restart any service that fails. This command is useful when troubleshooting configuration errors that prevent a service from starting. Run the `once` subcommand followed by the `status` subcommand to look for services in a down state and/or to identify which services are in trouble. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl once SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### restart The `restart` subcommand is used to restart all services enabled on the Chef Infra Server or to restart an individual service by specifying the name of that service in the command. Warning When running the Chef Infra Server in a high availability configuration, restarting all services may trigger failover. This subcommand has the following syntax: ``` chef-server-ctl restart SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully restarted the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` ### service-list The `service-list` subcommand is used to display a list of all available services. A service that is enabled is labeled with an asterisk (*). This subcommand has the following syntax: ``` chef-server-ctl service-list ``` ### start The `start` subcommand is used to start all services that are enabled in the Chef Infra Server. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl start SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully started the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` The supervisor for the Chef Infra Server is configured to wait seven seconds for a service to respond to a command from the supervisor. If you see output that references a timeout, it means that a signal has been sent to the process, but that the process has yet to actually comply. In general, processes that have timed out are not a big concern, unless they are failing to respond to the signals at all. If a process is not responding, use a command like the `kill` subcommand to stop the process, investigate the cause (if required), and then use the `start` subcommand to re-enable it. ### status The `status` subcommand is used to show the status of all services available to the Chef Infra Server. The results will vary based on the configuration of a given server. This subcommand has the following syntax: ``` chef-server-ctl status ``` and will return the status for all services. Status can be returned for individual services by specifying the name of the service as part of the command: ``` chef-server-ctl status SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When service status is requested, the output should be similar to: ``` run: service_name: (pid 12345) 12345s; run: log: (pid 1234) 67890s ``` where * `run:` is the state of the service (`run:` or `down:`) * `service_name:` is the name of the service for which status is returned * `(pid 12345)` is the process identifier * `12345s` is the uptime of the service, in seconds For example: ``` down: opscode-erchef: (pid 35546) 10s ``` By default, runit will restart services automatically when the services fail. Therefore, runit may report the status of a service as `run:` even when there is an issue with that service. When investigating why a particular service is not running as it should be, look for the services with the shortest uptimes. For example, the list below indicates that the **opscode-erchef** should be investigated further: ``` run: oc-id run: opscode-chef: (pid 4327) 13671s; run: log: (pid 4326) 13671s run: opscode-erchef: (pid 5383) 5s; run: log: (pid 4382) 13669s ``` #### Log Files A typical status line for a service that is running any of the Chef Infra Server front-end services is similar to the following: ``` run: name_of_service: (pid 1486) 7819s; run: log: (pid 1485) 7819s ``` where: * `run` describes the state in which the supervisor attempts to keep processes. This state is either `run` or `down`. If a service is in a `down` state, it should be stopped * `name_of_service` is the service name, for example: `opscode-erchef` * `(pid 1486) 7819s;` is the process identifier followed by the amount of time (in seconds) the service has been running * `run: log: (pid 1485) 7819s` is the log process. It is typical for a log process to have a longer run time than a service; this is because the supervisor does not need to restart the log process in order to connect the supervised process If the service is down, the status line will appear similar to the following: ``` down: opscode-erchef: 3s, normally up; run: log: (pid 1485) 8526s ``` where * `down` indicates that the service is in a down state * `3s, normally up;` indicates that the service is normally in a run state and that the supervisor would attempt to restart this service after a reboot ### stop The `stop` subcommand is used to stop all services enabled on the Chef Infra Server. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl stop SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully stopped the output should be similar to: ``` ok: down: service_name: 0s, normally up ``` For example: ``` chef-server-ctl stop ``` will return something similar to: ``` ok: down: nginx: 393s, normally up ok: down: opscode-chef: 391s, normally up ok: down: opscode-erchef: 391s, normally up ok: down: opscode-solr4: 389s, normally up ok: down: postgresql: 388s, normally up ok: down: redis_lb: 387s, normally up ``` ### tail The `tail` subcommand is used to follow all of the Chef Infra Server logs for all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl tail SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### term The `term` subcommand is used to send a `SIGTERM` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl term SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. List of Services ---------------- The following services are part of the Chef Infra Server: * bifrost * bookshelf * elasticsearch * nginx * opscode-erchef * postgresql * redis-lb ### bifrost The **oc_bifrost** service ensures that every request to view or manage objects stored on the Chef Infra Server is authorized. #### status To view the status for the service: ``` chef-server-ctl status bifrost ``` to return something like: ``` run: bifrost: (pid 1234) 123456s; run: log: (pid 5678) 789012s ``` #### start To start the service: ``` chef-server-ctl start bifrost ``` #### stop To stop the service: ``` chef-server-ctl stop bifrost ``` #### restart To restart the service: ``` chef-server-ctl restart bifrost ``` to return something like: ``` ok: run: bifrost: (pid 1234) 1234s ``` #### kill To kill the service (send a `SIGKILL` command): ``` chef-server-ctl kill bifrost ``` #### run once To run the service, but not restart it (if the service fails): ``` chef-server-ctl once bifrost ``` #### tail To follow the logs for the service: ``` chef-server-ctl tail bifrost ``` ### bookshelf The **bookshelf** service is an Amazon Simple Storage Service (S3)-compatible service that is used to store cookbooks, including all of the files—recipes, templates, and so on—that are associated with each cookbook. #### status To view the status for the service: ``` chef-server-ctl status bookshelf ``` to return something like: ``` run: bookshelf: (pid 1234) 123456s; run: log: (pid 5678) 789012s ``` #### start To start the service: ``` chef-server-ctl start bookshelf ``` #### stop To stop the service: ``` chef-server-ctl stop bookshelf ``` #### restart To restart the service: ``` chef-server-ctl restart bookshelf ``` to return something like: ``` ok: run: bookshelf: (pid 1234) 1234s ``` #### kill To kill the service (send a `SIGKILL` command): ``` chef-server-ctl kill bookshelf ``` #### run once To run the service, but not restart it (if the service fails): ``` chef-server-ctl once bookshelf ``` #### tail To follow the logs for the service: ``` chef-server-ctl tail bookshelf ``` ### Elasticsearch #### status To view the status for the service: ``` chef-server-ctl status elasticsearch ``` to return something like: ``` elasticsearch: (pid 12345) 1s; run: log: (pid 5678) 123456s ``` #### start To start the service: ``` chef-server-ctl start elasticsearch ``` to return something like: ``` ok: run: elasticsearch: (pid 5678) 0s ``` #### stop To stop the service: ``` chef-server-ctl stop elasticsearch ``` to return something like: ``` ok: down: elasticsearch: 123456s, normally up ``` #### restart To restart the service: ``` chef-server-ctl restart elasticsearch ``` to return something like: ``` ok: run: elasticsearch: (pid 56789) 1s ``` #### kill To kill the service (send a `SIGKILL` command): ``` chef-server-ctl kill elasticsearch ``` #### run once ``` chef-server-ctl once elasticsearch ``` #### tail To follow the logs for the service: ``` chef-server-ctl tail elasticsearch ``` ### nginx The **nginx** service is used to manage traffic to the Chef Infra Server, including virtual hosts for internal and external API request/response routing, external add-on request routing, and routing between front- and back-end components. #### status To view the status for the service: ``` chef-server-ctl status nginx ``` to return something like: ``` run: nginx: (pid 1234) 123456s; run: log: (pid 5678) 789012s ``` #### start To start the service: ``` chef-server-ctl start nginx ``` #### stop To stop the service: ``` chef-server-ctl stop nginx ``` #### restart To restart the service: ``` chef-server-ctl restart nginx ``` to return something like: ``` ok: run: nginx: (pid 1234) 1234s ``` #### kill To kill the service (send a `SIGKILL` command): ``` chef-server-ctl kill nginx ``` #### run once To run the service, but not restart it (if the service fails): ``` chef-server-ctl once nginx ``` #### tail To follow the logs for the service: ``` chef-server-ctl tail nginx ``` ### opscode-erchef The **opscode-erchef** service is an Erlang-based service that is used to handle Chef Infra Server API requests to the following areas within the Chef Infra Server: * Cookbooks * Data bags * Environments * Nodes * Roles * Sandboxes * Search #### status To view the status for the service: ``` chef-server-ctl status opscode-erchef ``` to return something like: ``` run: opscode-erchefs: (pid 1234) 123456s; run: log: (pid 5678) 789012s ``` #### start To start the service: ``` chef-server-ctl start opscode-erchef ``` #### stop To stop the service: ``` chef-server-ctl stop opscode-erchef ``` #### restart To restart the service: ``` chef-server-ctl restart opscode-erchef ``` to return something like: ``` ok: run: opscode-erchef: (pid 1234) 1234s ``` #### kill To kill the service (send a `SIGKILL` command): ``` chef-server-ctl kill opscode-erchef ``` #### run once To run the service, but not restart it (if the service fails): ``` chef-server-ctl once opscode-erchef ``` #### tail To follow the logs for the service: ``` chef-server-ctl tail opscode-erchef ``` ### postgresql The **postgresql** service is used to store node, object, and user data. #### status To view the status for the service: ``` chef-server-ctl status postgresql ``` to return something like: ``` run: postgresql: (pid 1234) 123456s; run: log: (pid 5678) 789012s ``` #### start To start the service: ``` chef-server-ctl start postgresql ``` #### stop To stop the service: ``` chef-server-ctl stop postgresql ``` #### restart To restart the service: ``` chef-server-ctl restart postgresql ``` to return something like: ``` ok: run: postgresql: (pid 1234) 1234s ``` #### kill To kill the service (send a `SIGKILL` command): ``` chef-server-ctl kill postgresql ``` #### run once To run the service, but not restart it (if the service fails): ``` chef-server-ctl once postgresqls ``` #### tail To follow the logs for the service: ``` chef-server-ctl tail postgresql ``` ### redis Key-value store used in conjunction with Nginx to route requests and populate request data used by the Chef Infra Server. #### status To view the status for the service: ``` chef-server-ctl status redis ``` to return something like: ``` run: redis: (pid 1234) 123456s; run: log: (pid 5678) 789012s ``` #### start To start the service: ``` chef-server-ctl start redis ``` #### stop To stop the service: ``` chef-server-ctl stop redis ``` #### restart To restart the service: ``` chef-server-ctl restart redis ``` to return something like: ``` ok: run: redis: (pid 1234) 1234s ``` #### kill To kill the service (send a `SIGKILL` command): ``` chef-server-ctl kill name_of_service ``` #### run once To run the service, but not restart it (if the service fails): ``` chef-server-ctl once redis ``` #### tail To follow the logs for the service: ``` chef-server-ctl tail name_of_service ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/server_services/Install the Chef Infra Server ============================= [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/install_server.md) There are three configuration scenarios for the Chef Infra Server: * [Standalone](#standalone) (everything on a single machine) * [High availability](#high-availability) (machines configured for front-end and back-end, allowing for failover on the back-end and load-balancing on the front-end, as required) * [Tiered](#tiered-single-backend) (machines configured for front-end and back-end, with a single back-end and load-balancing on the front-end, as required) Supported Platforms ------------------- The following table lists the commercially-supported platforms and versions for the Chef Infra Server: | Platform | Architecture | Version | | --- | --- | --- | | Amazon Linux 2 | `x86_64` | `2.x` | | CentOS | `x86_64` | `7.x`, `8.x` | | Oracle Enterprise Linux | `x86_64` | `7.x`, `8.x` | | Red Hat Enterprise Linux | `x86_64` | `7.x`, `8.x` | | SUSE Enterprise Linux Server | `x86_64` | `12.x`, `15.x` | | Ubuntu | `x86_64` | `16.04`, `18.04`, `20.04` | Prerequisites ------------- The Chef Infra Server has the following prerequisites: * An x86_64 compatible system architecture; Red Hat Enterprise Linux and CentOS may require updates prior to installation * A resolvable hostname that is specified using a FQDN or an IP address * A connection to Network Time Protocol (NTP) to prevent clock drift * If host-based firewalls (iptables, ufw, etc.) are being used, ensure that ports 80 and 443 are open. See the [firewalls](../install_server_pre/index#firewalls) section of the install prerequisites for additional details. * A local mail transfer agent that allows the Chef Infra Server to send email notifications * Using cron and the `/etc/cron.d` directory for periodic maintenance tasks * Disabling the Apache Qpid daemon on CentOS and Red Hat systems. See the [Apache Qpid](../install_server_pre/index#apache-qpid) of the prerequisite documentation for detailed steps. * Optional. A local user account under which services will run, a local user account for PostgreSQL, and a group account under which services will run. See [UIDs and GIDs](../install_server_pre/index#uids-and-gids) for more information. Note See the [expanded list of prerequisites](../install_server_pre/index) for a detailed list of software and hardware requirements. Standalone ---------- The standalone installation of Chef Infra Server creates a working installation on a single server. This installation is also useful when you are installing Chef Infra Server in a virtual machine, for proof-of-concept deployments, or as a part of a development or testing loop. To install Chef Infra Server: 1. Download the package from <https://downloads.chef.io/chef-server/>. 2. Upload the package to the machine that will run the Chef Infra Server, and then record its location on the file system. The rest of these steps assume this location is in the `/tmp` directory. 3. As a root user, install the Chef Infra Server package on the server, using the name of the package provided by Chef. For Red Hat Enterprise Linux and CentOS: ``` sudo rpm -Uvh /tmp/chef-server-core-<version>.rpm ``` For Ubuntu: ``` sudo dpkg -i /tmp/chef-server-core-<version>.deb ``` After a few minutes, the Chef Infra Server will be installed. 4. Run the following to start all of the services: ``` sudo chef-server-ctl reconfigure ``` Because the Chef Infra Server is composed of many different services that work together to create a functioning system, this step may take a few minutes to complete. 5. Run the following command to create an administrator: ``` sudo chef-server-ctl user-create USER_NAME FIRST_NAME LAST_NAME EMAIL 'PASSWORD' --filename FILE_NAME ``` An RSA private key is generated automatically. This is the user’s private key and should be saved to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. For example: ``` sudo chef-server-ctl user-create janedoe <NAME> <EMAIL> 'abc123' --filename /path/to/janedoe.pem ``` 6. Run the following command to create an organization: ``` sudo chef-server-ctl org-create short_name 'full_organization_name' --association_user user_name --filename ORGANIZATION-validator.pem ``` For example: ``` sudo chef-server-ctl org-create 4thcafe 'Fourth Cafe, Inc.' --association_user janedoe --filename /path/to/4thcafe-validator.pem ``` The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `4thcafe`. The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `'Fourth Cafe, Inc.'`. The `--association_user` option will associate the `user_name` with the `admins` security group on the Chef Infra Server. An RSA private key is generated automatically. This is the chef-validator key and should be saved to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. Update Configuration for Purchased Nodes ---------------------------------------- To use more than 25 nodes, you’ll need to change Chef Infra Server configuration for the server to recognize your purchased licenses. Edit your `/etc/opscode/chef-server.rb` file by following the process below: 1. On your Chef Infra Server, if the `chef-server.rb` file does not exist, create it. ``` sudo mkdir /etc/opscode && sudo touch /etc/opscode/chef-server.rb ``` 2. Open up the newly created `chef-server.rb` file in your favorite text editor, for example: ``` sudo vi /etc/opscode/chef-server.rb ``` 3. Paste or add the following text. Please note the placement of the single quotation (') marks. If you’re using the vi text editor, you’ll need to use the i key to insert the text. ``` license['nodes'] = N where N is the number of licensed nodes you have purchased ``` 4. Save the file. If you’re using vi, from the example above, use the esc key and then: ``` :wq ``` 5. Run `chef-server-ctl reconfigure` for the changes to be picked up by your Chef Infra Server. ``` sudo chef-server-ctl reconfigure ``` For more information on configuring your Chef Infra Server, see [chef-server.rb Settings](../config_rb_server/index) and [chef-server.rb Optional Settings](../config_rb_server_optional_settings/index). High Availability ----------------- The following links describe how to configure the Chef Infra Server for high availability. The **Backend Cluster** setup is strongly recommended for new installations: * [High Availability using Backend Cluster](../install_server_ha/index) Tiered (Single Backend) ----------------------- The following link describes how to configure the Chef Infra Server with a single backend machine and multiple frontend machines. Note that this process has been deprecated in favor of a [Backend Cluster](../install_server_ha/index) setup: * [Tiered Installation](../install_server_tiered/index) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/install_server/Chef Infra Server Prerequisites =============================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/install_server_pre.md) The following is a detailed discussion of the prerequisites for every installation of the Chef Infra Server. See [Install Chef Infra Server](../install_server/index) for installation instructions. Platforms --------- The following table lists the commercially-supported platforms and versions for the Chef Infra Server: | Platform | Architecture | Version | | --- | --- | --- | | Amazon Linux 2 | `x86_64` | `2.x` | | CentOS | `x86_64` | `7.x`, `8.x` | | Oracle Enterprise Linux | `x86_64` | `7.x`, `8.x` | | Red Hat Enterprise Linux | `x86_64` | `7.x`, `8.x` | | SUSE Enterprise Linux Server | `x86_64` | `12.x`, `15.x` | | Ubuntu | `x86_64` | `16.04`, `18.04`, `20.04` | ### Untested Platforms The following platforms are not tested by Chef Software: * Any Linux or UNIX distribution that is not listed as a Foundational platform. * Microsoft Windows * 32-bit architectures Capacity Planning ----------------- Read the [guidance around capacity planning](../index#capacity-planning) for information about how to choose the right topology for the Chef Infra Server. Hardware Requirements --------------------- All machines in a Chef Infra Server deployment have the following hardware requirements. Disk space for standalone and backend servers should scale up with the number of nodes that the servers are managing. A good rule to follow is to allocate 2 MB per node. The disk values listed below should be a good default value that you will want to modify later if/when your node count grows. Fast, redundant storage (SSD/RAID-based solution either on-prem or in a cloud environment) is preferred. **All Deployments** * 64-bit CPU architecture * CPU support for SSE4.2 extensions (Xeons starting in 2007 and Opterons in 2012) **Standalone Deployments** * 4 total cores (physical or virtual) * 8 GB of RAM or more * 5 GB of free disk space in `/opt` * 10 GB of free disk space in `/var` For a high availability deployment: **General Requirements** * Three backend servers; as many frontend servers as required * 1 x GigE NIC interface (if on premises) **Frontend Requirements** * 4 cores (physical or virtual) * 4GB RAM * 20 GB of free disk space (SSD if on premises, Premium Storage in Microsoft Azure, EBS-Optimized GP2 in AWS) **Backend Requirements** * 2 cores (physical or virtual) * 8GB RAM * 50 GB/backend server (SSD if on premises, Premium Storage in Microsoft Azure, EBS-Optimized GP2 in AWS) Warning The Chef Infra Server MUST NOT use a network file system of any type—virtual or physical—for backend storage. The Chef Infra Server database operates quickly. The behavior of operations, such as the writing of log files, will be unpredictable when run over a network file system. Software Requirements --------------------- Before installing the Chef Infra Server, ensure that each machine has the following installed and configured properly: * **Hostnames** — Ensure that all systems have properly configured hostnames. The hostname for the Chef Infra Server must be a FQDN, have fewer than 64 characters including the domain suffix, be lowercase, and resolvable. See [Hostnames, FQDNs](../../install_server_pre#hostnames) for more information * **FQDNs** — Ensure that all systems have a resolvable FQDN * **NTP** — Ensure that every server is connected to NTP; the Chef Infra Server is sensitive to clock drift * **Mail Relay** — The Chef Infra Server uses email to send notifications for various events; a local mail transfer agent should be installed and available to the Chef server * **cron** — Periodic maintenance tasks are performed using cron * **git** — git must be installed so that various internal services can confirm revisions * **Apache Qpid** — This daemon must be disabled on CentOS and Red Hat systems * **Required users** — If the environment in which the Chef Infra Server will run has restrictions on the creation of local user and group accounts, ensure that the correct users and groups exist before reconfiguring * **Firewalls and ports** — If host-based firewalls (iptables, ufw, etc.) are being used, ensure that ports 80 and 443 are open. In addition: * **Browser** — Firefox, Google Chrome, Safari, or Internet Explorer (versions 9 or better) * **Chef Infra Client communication with the Chef Infra Server** The Chef Infra Server must be able to communicate with every node that will be configured by Chef Infra Client and every workstation that will upload data to the Chef Infra ### UIDs and GIDs The installation process for the Chef Infra Server requires the use of at least two user and group identifiers (UIDs and GIDs). These are used to create the `opscode` and `opscode-pgsql` users and their default groups. Note The creation of required user and group identifiers is done **automatically** during the installation process for the Chef Infra Server; however, the following user and group accounts **may** be created in advance of installing the Chef Infra Server if specific UIDs and GIDs are preferred. The user **and** group must be created as a pair to satisfy reconfiguration requirements. * A local user account named `opscode` under which services will run * A local user account named `opscode-pgsql` that is used by PostgreSQL * A group account for each user account, one named `opscode` and the other named `opscode-pgsql` under which services will run Warning If the UID and GID of `opscode` and `opscode-pgsql` do not match on both backend Chef Infra Server machines, a high availability configuration will not run correctly. The embedded Chef Infra Server cookbooks can handle two cases: * Both `opscode` and `opscode-pgsql` user and group not found on the new server * Both `opscode` and `opscode-pgsql` user and group found on the new server Having only the group and not the corresponding users present during a chef-server-ctl reconfigure is unsupported and may lead to an error in the reconfiguration run. To determine the current range of IDs, run the following command: ``` grep -E '(UID|GID)' /etc/login.defs ``` The defaults for CentOS and Red Hat Enterprise Linux systems look like this: ``` UID_MIN 500 UID_MAX 60000 GID_MIN 500 GID_MAX 60000 ``` If the defaults have been changed for any reason, and if that change would result in less than 2 UID/GIDs being available to the `useradd` program, edit `/etc/login.defs` with changes to make at least 2 more UIDs and GIDs available for association. The currently used ID ranges for UIDs and GIDs can be found in `/etc/passwd` and `/etc/group`, respectively. If the `opscode` and `opscode-pgsql` user and group identifiers exist prior to installing the Chef Infra Server, the Chef Infra Server installation process will use the existing identifiers instead of creating them. ### Firewalls #### iptables To allow access to your Chef Infra Server on ports 80 and 443 via the iptables firewall, issue the following command with root privileges: ``` iptables -A INPUT -p tcp -m multiport --destination-ports 80,443 -j ACCEPT ``` Note that you will need to make use of a tool such as [iptables-persistent](https://packages.ubuntu.com/xenial/admin/iptables-persistent) to restore your iptables rules upon reboot. #### FirewallD On RHEL and CentOS versions 7 and above, the FirewallD firewall is enabled by default. Issue the following command with root privileges to open ports 80 and 443: ``` firewall-cmd --permanent --zone public --add-service http && firewall-cmd --permanent --zone public --add-service https && firewall-cmd --reload ``` #### UFW While UFW is installed on Ubuntu, it is not enabled by default. However, if you wish to use a UFW-based firewall on your Chef Infra Server, issue the following command with root privileges to open ports 80 and 443: ``` ufw allow proto tcp from any to any port 80,443 ``` ### Security Modules #### SELinux On CentOS and Red Hat Enterprise Linux systems, SELinux is enabled in enforcing mode by default. The Chef Infra Server does not have a profile available to run under SELinux. In order for the Chef Infra Server to run, SELinux must be disabled or set to `Permissive` mode. To determine if SELinux is installed, run the following command: ``` getenforce ``` If a response other than `"Disabled"` or `"Permissive"` is returned, SELinux must be disabled. To set SELinux to `Permissive` mode, run: ``` setenforce Permissive ``` and then check the status: ``` getenforce ``` #### AppArmor On Ubuntu systems, AppArmor is enabled in enforcing mode by default. Chef products do not have a profile available to run under AppArmor. In order for the Chef products to run, AppArmor must set to `Complaining` mode or disabled. To determine if AppArmor is installed, run the following command: ``` sudo apparmor_status ``` To install AppArmor, run the following command: ``` sudo apt-get install apparmor-utils -yes ``` If a response other than `"0 processes are in enforce mode"` or `"0 profiles are in enforce mode."` is returned, AppArmor must be set to `Complaining` mode or disabled. To set AppArmor to `Complaining` mode, run: ``` sudo aa-complain /etc/apparmor.d/* ``` Or to disable AppArmor entirely, run: ``` sudo invoke-rc.d apparmor kill sudo update-rc.d -f apparmor remove ``` and then check the status: ``` sudo apparmor_status ``` ### Apache Qpid On CentOS and Red Hat Enterprise Linux systems, the Apache Qpid daemon is installed by default. To determine if Apache Qpid is installed, run the following command: ``` rpm -qa | grep qpid ``` If Apache Qpid is installed, a response similar to the following is displayed: ``` qpid-cpp-server-0.12-6.el6.x86_64 ``` To disable Apache Qpid run: ``` service qpidd stop ``` and then: ``` chkconfig --del qpidd ``` ### cron Periodic maintenance tasks are performed on the Chef Infra Server servers via cron and the `/etc/cron.d` directory. With certain CentOS 6 configurations, an additional step is required to install crontab: ``` yum install crontabs ``` ### Enterprise Linux Updates The Chef Infra Server requires an x86_64 compatible systems architecture. When the Chef Infra Server is installed on Red Hat Enterprise Linux or CentOS, run `yum update` prior to installing the Chef Infra Server. This will ensure those platforms are fully compatible with this requirement. ### IP Addresses Unless you intend to operate the Chef Infra Server in IPv6 mode, you should disable ipv6 in the system’s `/etc/hosts` file by commenting out or removing all references to IPv6 addresses like “::1” or “fe80:db8:85a3:8d3:1319:8a2e:370:7348”. Without these changes, a Chef Infra Server install intended to run in ipv4 mode will mistakenly only start the postgres service on the ipv6 loopback address of “::1” rather than the ipv4 loopback address of 127.0.0.1. This will make further progress through an initial reconfiguration impossible. ### Hostnames The hostname for the Chef Infra Server may be specified using a FQDN or an IP address. This hostname must be resolvable, be 64 characters or less, and be lowercase. For example, a Chef Infra Server running in a production environment with a resolvable FQDN hostname can be added the DNS system. But when deploying Chef Infra Server into a testing environment, adding the hostname to the `/etc/hosts` file is enough to ensure that hostname is resolvable. * **FQDN Hostnames** When the hostname for the Chef Infra Server is a FQDN be sure to include the domain suffix. For example, something like `mychefserver.example.com` (and not something like `mychefserver`). * **IP Address Hostnames** When the Chef Infra Server is run in IPv6 mode, a hostname specified using an IP address must also be bracketed (`[ ]`) or the Chef Infra Server will not be able to recognize it as an IPv6 address. For example: ``` bookshelf['url'] "https://[2001:db8:85a3:8d3:1319:8a2e:370:7348]" ``` The `api_fqdn` setting can be added to the private-chef.rb file (it is not there by default). When added, its value should be equal to the FQDN or IP address for the service URI used by the Chef Infra Server. Then configure the same value for the `bookshelf['vip']` setting prior to installing the Chef Infra Server. For example: `api_fqdn "chef.example.com"` or `api_fqdn 123.45.67.890`. #### Configure Hostnames Use the following sections to verify the hostnames that is used by the Chef Infra Server. **To verify if a hostname is a FQDN** To verify if a hostname is a FQDN, run the following command: ``` hostname ``` If the hostname is a FQDN, it will return something like: ``` mychefserver.example.com ``` If the hostname is not a FQDN, it must be configured so that it is one. **To verify the FQDN is all lowercase** To verify if the alphabetic parts of a FQDN are all lowercase, run the following command: ``` hostname -f | grep -E '^([[:digit:]]|[[:lower:]]|\.|-|_)+$' && echo yes ``` If the hostname is all lowercase, it will return something like: ``` mychefserver.example.com yes ``` If the hostname’s alphabetic parts are not all lowercase, it must be configured so that they are. **To verify a hostname is resolvable** To verify is a hostname is resolvable, run the following command: ``` hostname -f ``` If the hostname is resolvable, it will return something like: ``` mychefserver.example.com ``` **To change a hostname** In some cases, the hostname for the Chef Infra Server needs to be updated. The process for updating a hostname varies, depending on the platform on which the Chef Infra Server will run. Refer to the manual for the platform or contact a local systems administrator for specific guidance for a specific platform. The following example shows how a hostname can be changed when running Red Hat or CentOS: ``` sudo hostname 'mychefserver.example.com' ``` and then: ``` echo "mychefserver.example.com" | sudo tee /etc/hostname ``` **To add a hostname to /etc/hosts** If a hostname is not resolvable, refer to a local systems administrator for specific guidance on how to add the hostname to the DNS system. If the Chef Infra Server is being into a testing environment, just add the hostname to `/etc/hosts`. The following example shows how a hostname can be added to `/etc/hosts` when running Red Hat or CentOS: ``` echo -e "127.0.0.2 `hostname` `hostname -s`" | sudo tee -a /etc/hosts ``` Warning The FQDN for the Chef Infra Server should be resolvable, lowercase, and should not exceed 64 characters when using OpenSSL, as OpenSSL requires the `CN` in a certificate to be no longer than 64 characters. ### Mail Relay The Chef Infra Server server uses email to send notifications for various events: * Password resets * User invitations * Failover notifications * Failed job notifications Configure a local mail transfer agent on the Chef Infra Server using the steps appropriate for the platform on which the Chef Infra Server is running. ### NTP The Chef Infra Server requires that the systems on which it is running be connected to Network Time Protocol (NTP), as the Chef Infra Server is particularly sensitive to clock drift. For Red Hat and CentOS 6: ``` yum install ntp ``` or: ``` chkconfig ntpd on ``` or: ``` service ntpd start ``` For Ubuntu: ``` apt-get install ntp ``` #### Chef Infra Client The Chef Infra Server server requires that every node that is under management by Chef also have an accurate clock that is synchronized very closely with the clock on the Chef Infra Server. If the clocks are not synchronized closely, the authentication process may fail when the clocks are out-of-sync by more than 15 minutes. A failure will trigger a `401 Unauthorized` response similar to: ``` [Tue, 01 Nov 2011 16:55:23 -0700] INFO: *** Chef 11.X.X *** [Tue, 01 Nov 2011 16:55:23 -0700] INFO: Client key /etc/chef/client.pem is not present - registering [Tue, 01 Nov 2011 16:55:24 -0700] INFO: HTTP Request Returned 401 Unauthorized: Failed to authenticate as ORGANIZATION-validator. Synchronize the clock on your host. [Tue, 01 Nov 2011 16:55:24 -0700] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out [Tue, 01 Nov 2011 16:55:24 -0700] FATAL: Net::HTTPClientException: 401 "Unauthorized" ``` In this situation, re-synchronize the system clocks with the Network Time Protocol (NTP) server, and then re-run Chef Infra Client. ### Required Accounts By default, accounts required by the Chef Infra Server are created during setup. If your environment has restrictions on the creation of local user and group accounts that will prevent these accounts from being created automatically during setup, you will need to create these accounts. #### Group Accounts The following group accounts are required: | Group Account | Description | | --- | --- | | `opscode` | The group name under which services will run. | #### User Accounts The following user accounts are required: | User Account | Description | | --- | --- | | `opscode` | The user name under which services will run. | | `opscode-pgsql` | The user name for PostgreSQL. (This is only required on the back end servers in a high availability setup.) | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/install_server_pre/Authentication ============== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/auth.md) The Chef Infra Server API handles all communication between Chef Infra Client or Chef Workstation. The Chef Infra Server API is an authenticated REST API, which means all requests require authentication and authorization. The Chef Infra tools such as `knife` and `chef-server` commands use the Chef Infra Server API for you. The authentication process ensures that Chef Infra Server only responds to requests made by trusted users or clients. Chef Infra Server uses public key encryption. You create the public and private keys when you configure [Chef Infra Client](../../config_rb_client/index) or setup [Chef Workstation](../../workstation/getting_started/index#setup-chef-credentials). * Chef Infra Server stores the public key * Chef Workstation saves the private key in `~/.chef/` * Chef Infra Client saves the private key in `/etc/chef` Both Chef Infra Client and Chef Workstation communicate with the Chef Infra Server using the Chef Infra Server API. Each time that Chef Infra Client or Chef Workstation makes a request to Chef Infra Server, they use a special group of HTTP headers and sign the rest with their private key. The Chef Infra Server then uses the public key to verify the headers and the contents. Public and Private Keys ----------------------- Every request made by Chef Infra Client to the Chef Infra Server must be an authenticated request using the Chef Infra Server API and a private key. When Chef Infra Client makes a request to the Chef Infra Server, Chef Infra Client authenticates each request using a private key located in `/etc/chef/client.pem`. ### Chef Infra Server Key Use The authentication process ensures that Chef Infra Server only responds to requests made by trusted users or clients. Chef Infra Server uses public key encryption. You create the public and private keys when you configure [Chef Infra Client](../../config_rb_client/index) or setup [Chef Workstation](../../workstation/getting_started/index#setup-chef-credentials). * Chef Infra Server stores the public key * Chef Workstation saves the private key in `~/.chef/` * Chef Infra Client saves the private key in `/etc/chef` Both Chef Infra Client and Chef Workstation communicate with the Chef Infra Server using the Chef Infra Server API. Each time that Chef Infra Client or Chef Workstation makes a request to Chef Infra Server, they use a special group of HTTP headers and sign the rest with their private key. The Chef Infra Server then uses the public key to verify the headers and the contents. #### Chef Infra Client Chef Infra Client authenticates with the Chef Infra Server using RSA public key-pairs each time a Chef Infra Client needs access to data that is stored on the Chef Infra Server. This prevents any node from accessing data that it shouldn’t and it ensures that only nodes that are properly registered with the Chef Infra Server can be managed. #### Knife RSA public key-pairs are used to authenticate knife with the Chef Infra Server every time knife attempts to access the Chef Infra Server. This ensures that each instance of knife is properly registered with the Chef Infra Server and that only trusted users can make changes to the data. Knife can also use the `knife exec` subcommand to make specific, authenticated requests to the Chef Infra Server. knife plugins can also make authenticated requests to the Chef Infra Server by leveraging the `knife exec` subcommand. #### chef-validator The private key does not yet exist the first time that Chef Infra Client runs from a new node. During the first Chef Infra Client run: 1. Chef Infra Client uses the chef-validator private key, located in `/etc/chef/validation.pem` to register with Chef Infra Server 2. Chef Infra Server assigns Chef Infra Client a private key for all future authentication requests to the Chef Infra Server 3. Chef Infra Client saves the private key on the node as `/etc/chef/client.pem` If the request to communicate with Chef Infra Server with the chef-validator key fails, then the entire first Chef Infra Client run fails. After the first completed Chef Infra Client run, delete the chef-validator private key at `/etc/chef/validation.pem` ### Chef Infra Server Key Storage Keys are stored in different locations, depending on if the location is a node or a workstation. #### Nodes Each node stores its private key locally. This private key is generated as part of the bootstrap process that initially installs Chef Infra Client on the node. The first time Chef Infra Client runs on that node, it uses the chef-validator to authenticate, but then on each subsequent run it uses the private key generated for that client by the Chef Infra Server. #### Workstations Each workstation stores its private key in the user’s `~/.chef` directory. This private key is generated by the Chef Infra Server and must be download from the server and copied to the `~/.chef` directory manually. If you require a new private key, generate it with the Chef Infra Server and copy it to the `~/.chef` directory again. The chef-repo is a directory on your workstation that stores everything you need to define your infrastructure with Chef Infra: * Cookbooks (including recipes, attributes, custom resources, libraries, and templates) * Data bags * Policyfiles The chef-repo directory should be synchronized with a version control system, such as git. All of the data in the chef-repo should be treated like source code. You’ll use the `chef` and `knife` commands to upload data to the Chef Infra Server from the chef-repo directory. Once uploaded, Chef Infra Client uses that data to manage the nodes registered with the Chef Infra Server and to ensure that it applies the right cookbooks, policyfiles, and settings to the right nodes in the right order. The .chef directory is a hidden directory that is used to store validation key files and optionally a [config.rb](../../config_rb) file. ### Chef Infra Server API Authentication #### API Requests A knife plugin is a set of one (or more) subcommands that can be added to knife to support additional functionality that is not built-in to the base set of knife subcommands. Many of the knife plugins are built by members of the Chef community and several of them are built and maintained by Chef. A knife plugin can be used to make authenticated API requests to the Chef Infra Server using the following methods: | Method | Description | | --- | --- | | `rest.delete_rest` | Use to delete an object from the Chef Infra Server. | | `rest.get_rest` | Use to get the details of an object on the Chef Infra Server. | | `rest.post_rest` | Use to add an object to the Chef Infra Server. | | `rest.put_rest` | Use to update an object on the Chef Infra Server. | For example: ``` module MyCommands class MyNodeDelete &lt; Chef::Knife #An implementation of knife node delete banner 'knife my node delete [NODE_NAME]' def run if name_args.length &lt; 1 show_usage ui.fatal('You must specify a node name.') exit 1 end nodename = name_args[0] api_endpoint = "nodes/#{nodename}" # Again, we could just call rest.delete_rest nodey = rest.get_rest(api_endpoint) ui.confirm("Do you really want to delete #{nodey}") nodey.destroy end end end ``` #### From the Web Interface The Chef Infra Server user interface uses the Chef Infra Server API to perform most operations. This ensures that authentication requests to the Chef Infra Server are authorized. This authentication process is handled automatically and is not something that users of the hosted Chef Infra Server will need to manage. For the on-premises Chef Infra Server, the authentication keys used by the web interface will need to be maintained by the individual administrators who are responsible for managing the server. #### Other Options The most common ways to interact with the Chef Infra Server using the Chef Infra Server API abstract the API from the user. That said, the Chef Infra Server API can be interacted with directly. The following sections describe a few of the ways that are available for doing that. **cURL** An API request can be made using cURL, which is a Bash shell script that requires two utilities: awk and openssl. The following example shows how an authenticated request can be made using the Chef Infra Server API and cURL: ``` #!/usr/bin/env bash _chef_dir () { # Helper function: # Recursive function that searches for chef configuration directory # It looks upward from the cwd until it hits /. If no directory is found, # ~/.chef is chosen if it exists # You could simply hard-code the path below if [ "$PWD" = "/" ]; then if [ -d ".chef" ]; then echo "/.chef" elif [ -d "$HOME/.chef" ]; then echo "$HOME/.chef" fi return fi if [ -d '.chef' ];then echo "${PWD}/.chef" else (cd ..; _chef_dir) fi } _chomp () { # helper function to remove newlines awk '{printf "%s", $0}' } chef_api_request() { # This is the meat-and-potatoes, or rice-and-vegetables, your preference really. local method path body timestamp chef_server_url client_name hashed_body hashed_path local canonical_request headers auth_headers chef_server_url="https://api.opscode.com/organizations/my_org" # '/organizations/ORG_NAME' is needed if echo $chef_server_url | grep -q "/organizations/" ; then endpoint=/organizations/${chef_server_url#*/organizations/}${2%%\?*} else endpoint=${2%%\?*} fi path=${chef_server_url}$2 client_name="chef_user" method=$1 body=$3 hashed_path=$(echo -n "$endpoint" | openssl dgst -sha1 -binary | openssl enc -base64) hashed_body=$(echo -n "$body" | openssl dgst -sha1 -binary | openssl enc -base64) timestamp=$(date -u "+%Y-%m-%dT%H:%M:%SZ") canonical_request="Method:$method\nHashed Path:$hashed_path\nX-Ops-Content-Hash:$hashed_body\nX-Ops-Timestamp:$timestamp\nX-Ops-UserId:$client_name" headers="-H X-Ops-Timestamp:$timestamp \ -H X-Ops-Userid:$client_name \ -H X-Chef-Version:0.10.4 \ -H Accept:application/json \ -H X-Ops-Content-Hash:$hashed_body \ -H X-Ops-Sign:version=1.0" auth_headers=$(printf "$canonical_request" | openssl rsautl -sign -inkey \ "$(_chef_dir)/${client_name}.pem" | openssl enc -base64 | _chomp | awk '{ll=int(length/60);i=0; \ while (i<=ll) {printf " -H X-Ops-Authorization-%s:%s", i+1, substr($0,i*60+1,60);i=i+1}}') case $method in GET) curl_command="curl $headers$auth_headers$path" $curl_command ;; *) echo "Unknown Method. I only know: GET" >&2 return 1 ;; esac } chef_api_request "$@" ``` After saving this shell script to a file named `chef_api_request`, use it similar to the following: ``` bash chef_api_request GET "/clients" ``` **PyChef** An API request can be made using PyChef, which is a Python library that meets the `Mixlib::Authentication` requirements so that it can easily interact with the Chef Infra Server. The following example shows how an authenticated request can be made using the Chef Infra Server API and PyChef: ``` from chef import autoconfigure, Node api = autoconfigure() n = Node('web1') print n['fqdn'] n['myapp']['version'] = '1.0' n.save() ``` and the following example shows how to make API calls directly: ``` from chef import autoconfigure api = autoconfigure() print api.api_request('GET', '/clients') ``` The previous examples assume that the current working directory is such that PyChef can find a valid configuration file in the same manner as Chef Infra Client or knife. For more about PyChef, see: <https://github.com/coderanger/pychef>. **Ruby** On a system with Chef Infra Client installed, use Ruby to make an authenticated request to the Chef Infra Server: ``` require 'chef/config' require 'chef/log' require 'chef/rest' chef_server_url = 'https://chefserver.com' client_name = 'clientname' signing_key_filename = '/path/to/pem/for/clientname' rest = Chef::REST.new(chef_server_url, client_name, signing_key_filename) puts rest.get_rest('/clients') ``` or: ``` require 'mixlib/cli' require 'chef' require 'chef/node' require 'chef/mixin/xml_escape' require 'json' config_file = 'c:/chef/client.rb' Chef::Config.from_file(config_file) Chef::Log.level = Chef::Config[:log_level] def Usage() puts '/etc/chef/client.rb' # The config file location, e.g. ~/home/.chef/config.rb etc config_file = gets.chomp if (!File.exist?(config_file)) puts 'config_file #{config_file} does not exist. Exiting.\n' exit end STDOUT.puts <<-EOF Choose options e.g. 1 1 Display all nodes per environment 2 Display all nodes in detail (can be slow if there a large number of nodes) 9 Exit EOF end def ExecuteUserChoice() testoption = gets.chomp case testoption when '1' Execute(method(:DisplayNodesPerEnv)) when '2' Execute(method(:DisplayNodesDetail)) when '9' puts 'exit' else puts 'Unknown option #{testoption}. Exiting\n' exit end end def DisplayNodesPerEnv() Chef::Environment.list(false).each do |envr| print 'ENVIRONMENT: ', envr[0], '\n' Chef::Node.list_by_environment(envr[0], false).each do |node_info| print '\tNODE: ', node_info[0], '\n' print '\t\tURL: ', node_info[1], '\n' end end end def DisplayNodesDetail() Chef::Node.list(true).each do |node_array| node = node_array[1] print '#{node.name}\n' print '\t#{node['fqdn']}\n' print '\t#{node['kernel']['machine']}\n' print '\t#{node['kernel']['os']}\n' print '\t#{node['platform']}\n' print '\t#{node['platform_version']}\n' print '\t#{node.chef_environment}\n' print '\t#{node.run_list.roles}\n' end end def Execute(option) begin profilestart = Time.now option.call() profileend = Time.now timeofrun = profileend - profilestart print 'Time taken = #{timeofrun}' rescue Exception => ex print 'Error calling chef API' print ex.message print ex.backtrace.join('\n') end end Usage() ExecuteUserChoice() ``` Another way Ruby can be used with the Chef Infra Server API is to get objects from the Chef Infra Server, and then interact with the returned data using Ruby methods. Whenever possible, the Chef Infra Server API will return an object of the relevant type. The returned object is then available to be called by other methods. For example, the `api.get` method can be used to return a node named `foobar`, and then `.destroy` can be used to delete that node: ``` silly_node = api.get('/nodes/foobar') silly_node.destroy ``` ### Debug Authentication Issues In some cases, Chef Infra Client may receive a 401 response to the authentication request and a 403 response to an authorization request. An authentication error error may look like the following: ``` [Wed, 05 Oct 2011 15:43:34 -0700] INFO: HTTP Request Returned 401 Unauthorized: Failed to authenticate as node_name. Ensure that your node_name and client key are correct. ``` To debug authentication problems, determine which Chef Infra Client is attempting to authenticate. This is often found in the log messages for that Chef Infra Client. Debug logging can be enabled on a Chef Infra Client using the following command: ``` chef-client -l debug ``` When debug logging is enabled, a log entry will look like the following: ``` [Wed, 05 Oct 2011 22:05:35 +0000] DEBUG: Signing the request as NODE_NAME ``` If the authentication request occurs during the initial Chef Infra Client run, the issue is most likely with the private key. If the authentication is happening on the node, there are a number of common causes: * The `client.pem` file is incorrect. This can be fixed by deleting the `client.pem` file and re-running Chef Infra Client. When Chef Infra Client re-runs, it will re-attempt to register with the Chef Infra Server and generate the correct key. * A `node_name` is different from the one used during the initial Chef Infra Client run. This can happen for a number of reasons. For example, if the client.rb file does not specify the correct node name and the host name has recently changed. This issue can be resolved by explicitly setting the node name in the client.rb file or by using the `-N` option for the Chef Infra Client executable. * The system clock has drifted from the actual time by more than 15 minutes. This can be fixed by syncing the clock with an Network Time Protocol (NTP) server. Authorization ------------- For more information about Chef Infra Server Authorization, see [Organizations and Groups](../server_orgs/index). Chef Infra Server API --------------------- For more information about using the Chef Infra Server API endpoints see [Chef Infra Server API](../api_chef_server/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/auth/Capacity Planning ================= [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/capacity_planning.md) This document provides guidance for capacity planning and how to choose the right configuration–standalone, high availability, or tiered–for the Chef Infra Server. This document provides guidance and not hard/fast rules. This is because some requests to the Chef Infra Server API are more computationally expensive than others. In general, it’s better to start small and then scale the Chef Infra Server as needed. Premature optimization can hinder more than help because it may introduce unnecessary complexity. Scaling the Chef Infra Server ----------------------------- The Chef Infra Server itself is highly scalable. A single virtual machine running the Chef Infra Server can handle requests for many thousands of nodes. As the scale increases, it’s a straightforward process to expand into a tiered front-end, back-end architecture with horizontally scaled front-ends to relieve pressure on system bottlenecks. That said, it’s best to isolate failure domains with their own Chef Infra Server, rather than trying to run every node in an infrastructure from a single central, monolithic Chef Infra Server instance/cluster. For instance, if there are West coast and East coast data centers, it is best to have one Chef Infra Server instance in each datacenter. Deploys to each Chef Infra Server can be synchronized upstream by CI software. The primary limiting bottleneck for Chef Infra Server installations is almost always input/output operations per second (IOPS) performance for the database filesystem. CCRs/min -------- The key unit of measure for scaling the Chef Infra Server is the number of Chef Infra Client runs per minute: CCRs/min. For example, 500 nodes set to check in every 30 minutes is equivalent to 16.66 CCRs/min. Typically, the Chef Infra Server does not require a high availability or tiered topology until the number of CCRs/min is higher than 333/min (approximately 10k nodes). While synthetic benchmarks should be taken with a grain of salt, as they don’t typically represent real-world performance, internal synthetic benchmarks at Chef have seen a standalone Chef Infra Server installed on a `c3.2xlarge` Amazon Web Services (AWS) instance handle more than 1,000 CCRs/min (30k nodes). Assumptions ----------- Several factors may influence server scalability. All server sizing recommendations are based on these assumptions: * Chef Infra Client runs are daemonized, and are not initiated by a cron job. Using cron to schedule runs can create “thundering herd” problems * Chef Infra Client runs are set to a default 30-minute interval with a 5-minute splay * Search and `partial_search` are utilized, but not heavily * The number of cookbooks per organization, across all versions, on the Chef Infra Server is under 500. (Multiple organizations with fewer than 500 cookbooks each, that still add up to a total of more than 500 cookbooks server-wide, is fine.) * The default maximum allowable size for a node object is 1MB, although it is rare for nodes to exceed 150KB. Though compressed, this data is replicated twice, once in Elasticsearch, and once in PostgreSQL. In practice, allowing a conservative 2MB of storage on the disk partition per node should be sufficient Host Specifications ------------------- The following sections describe the host specifications for various sizes of CCRs/min and help show when to consider moving from a standalone topology to a high availability or tiered topology. **UP TO 33 CCRs/Min (approx. 1,000 nodes):** * Chef recommends a single virtual machine instance * Start with 2 CPU cores and 8GB of RAM, which is equivalent to an Amazon EC2 `m3.large` instance * Allocate 2MB of disk space on the data partition per managed node **UP TO 167 CCRs/Min (approx. 5,000 nodes):** * Chef recommends a single virtual machine instance * Start with 4 CPU cores and 16GB of RAM, which is equivalent to an Amazon EC2 `m3.xlarge` instance **UP TO 333 CCRs/Min (Approx. 10,000 nodes):** * Chef recommends a single virtual machine instance * Start with 8 CPU cores and 32GB of RAM, which is equivalent to an Amazon EC2 `m3.2xlarge` instance **UP TO 667 CCRs/Min (Approx. 20,000 nodes):** * Chef recommends two hosts, one front-end and one back-end * The disk requirement for the front-end server is negligible * Start with 8 CPU cores and 32GB of RAM for each host, which is equivalent to an Amazon EC2 `m3.2xlarge` instance **Scaling beyond 20,000 nodes on a single cluster:** * Additional capacity can be gained by placing the front-end node behind an HTTP load balancer, and then scaling front-end nodes horizontally * Chef recommends that Chef professional services be engaged to help with capacity and architectural planning at this size © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/capacity_planning/Organizations and Groups ======================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/server/server_orgs.md) The Chef Infra Server uses role-based access control (RBAC) to restrict access to objects—nodes, environments, roles, data bags, cookbooks, and so on. This ensures that only authorized user and/or Chef Infra Client requests to the Chef Infra Server are allowed. Access to objects on the Chef Infra Server is fine-grained, allowing access to be defined by object type, object, group, user, and organization. The Chef Infra Server uses permissions to define how a user may interact with an object, after they have been authorized to do so. The Chef Infra Server uses organizations, groups, and users to define role-based access control: | Feature | Description | | --- | --- | | image | An organization is the top-level entity for role-based access control in the Chef Infra Server. Each organization contains the default groups (`admins`, `clients`, and `users`, plus `billing_admins` for the hosted Chef Infra Server), at least one user and at least one node (on which the Chef Infra Client is installed). The Chef Infra Server supports multiple organizations. The Chef Infra Server includes a single default organization that is defined during setup. Additional organizations can be created after the initial setup and configuration of the Chef Infra Server. | | image | A group is used to define access to object types and objects in the Chef Infra Server and also to assign permissions that determine what types of tasks are available to members of that group who are authorized to perform them. Groups are configured per-organization. Individual users who are members of a group will inherit the permissions assigned to the group. The Chef Infra Server includes the following default groups: `admins`, `clients`, and `users`. For users of the hosted Chef Infra Server, an additional default group is provided: `billing_admins`. | | image | A user is any non-administrator human being who will manage data that is uploaded to the Chef Infra Server from a workstation or who will log on to the Chef management console web user interface. The Chef Infra Server includes a single default user that is defined during setup and is automatically assigned to the `admins` group. | | image | A client is an actor that has permission to access the Chef Infra Server. A client is most often a node (on which the Chef Infra Client runs), but is also a workstation (on which knife runs), or some other machine that is configured to use the Chef Infra Server API. Each request to the Chef Infra Server that is made by a client uses a private key for authentication that must be authorized by the public key on the Chef Infra Server. | When a user makes a request to the Chef Infra Server using the Chef Infra Server API, permission to perform that action is determined by the following process: 1. Check if the user has permission to the object type 2. If no, recursively check if the user is a member of a security group that has permission to that object 3. If yes, allow the user to perform the action Permissions are managed using the Chef management console add-on in the Chef Infra Server web user interface. Organizations ------------- A single instance of the Chef Infra Server can support many organizations. Each organization has a unique set of groups and users. Each organization manages a unique set of nodes, on which a Chef Infra Client is installed and configured so that it may interact with a single organization on the Chef Infra Server. ![image] A user may belong to multiple organizations under the following conditions: * Role-based access control is configured per-organization * For a single user to interact with the Chef Infra Server using knife from the same chef-repo, that user may need to edit their config.rb file prior to that interaction Using multiple organizations within the Chef Infra Server ensures that the same toolset, coding patterns and practices, physical hardware, and product support effort is being applied across the entire company, even when: * Multiple product groups must be supported—each product group can have its own security requirements, schedule, and goals * Updates occur on different schedules—the nodes in one organization are managed completely independently from the nodes in another * Individual teams have competing needs for object and object types—data bags, environments, roles, and cookbooks are unique to each organization, even if they share the same name ### Permissions Permissions are used in the Chef Infra Server to define how users and groups can interact with objects on the server. Permissions are configured per-organization. #### Object Permissions The Chef Infra Server includes the following object permissions: | Permission | Description | | --- | --- | | **Delete** | Use the **Delete** permission to define which users and groups may delete an object. This permission is required for any user who uses the `knife [object] delete [object_name]` argument to interact with objects on the Chef Infra Server. | | **Grant** | Use the **Grant** permission to define which users and groups may configure permissions on an object. This permission is required for any user who configures permissions using the **Administration** tab in the Chef management console. | | **Read** | Use the **Read** permission to define which users and groups may view the details of an object. This permission is required for any user who uses the `knife [object] show [object_name]` argument to interact with objects on the Chef Infra Server. | | **Update** | Use the **Update** permission to define which users and groups may edit the details of an object. This permission is required for any user who uses the `knife [object] edit [object_name]` argument to interact with objects on the Chef Infra Server and for any Chef Infra Client to save node data to the Chef Infra Server at the conclusion of a Chef Infra Client run. | #### Global Permissions The Chef Infra Server includes the following global permissions: | Permission | Description | | --- | --- | | **Create** | Use the **Create** global permission to define which users and groups may create the following server object types: cookbooks, data bags, environments, nodes, roles, and tags. This permission is required for any user who uses the `knife [object] create` argument to interact with objects on the Chef Infra Server. | | **List** | Use the **List** global permission to define which users and groups may view the following server object types: cookbooks, data bags, environments, nodes, roles, and tags. This permission is required for any user who uses the `knife [object] list` argument to interact with objects on the Chef Infra Server. | These permissions set the default permissions for the following Chef Infra Server object types: clients, cookbooks, data bags, environments, groups, nodes, roles, and sandboxes. #### Client Key Permissions Note This is only necessary after migrating a client from one Chef Infra Server to another. Permissions must be reset for client keys after the migration. Keys should have `DELETE`, `GRANT`, `READ` and `UPDATE` permissions. Use the following code to set the correct permissions: ``` #!/usr/bin/env ruby require 'chef/knife' #previously knife.rb Chef::Config.from_file(File.join(Chef::Knife.chef_config_dir, 'knife.rb')) rest = Chef::ServerAPI.new(Chef::Config[:chef_server_url]) Chef::Node.list.each do |node| %w(read update delete grant).each do |perm| ace = rest.get("nodes/#{node[0]}/_acl")[perm] ace['actors'] << node[0] unless ace['actors'].include?(node[0]) rest.put("nodes/#{node[0]}/_acl/#{perm}", perm => ace) puts "Client \"#{node[0]}\" granted \"#{perm}\" access on node \"#{node[0]}\"" end end ``` Save it as a Ruby script—`chef_server_permissions.rb`, for example—in the `.chef/scripts` directory located in the chef-repo, and then run a knife command similar to: ``` knife exec chef_server_permissions.rb ``` #### Knife ACL The knife plugin [knife-acl](https://github.com/chef/knife-acl) provides a fine-grained approach to modifying permissions, by wrapping API calls to the `_acl` endpoint and makes such permission changes easier to manage. Warning Chef Manage is [deprecated](../../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. knife-acl and the Chef Manage browser interface are incompatible. After engaging knife-acl, you will need to discontinue using the Chef Manage browser interface from that point forward due to possible incompatibilities. Groups ------ The Chef Infra Server includes the following default groups: | Group | Description | | --- | --- | | `admins` | The `admins` group defines the list of users who have administrative rights to all objects and object types for a single organization. | | `billing_admins` | The `billing_admins` group defines the list of users who have permission to manage billing information. This permission exists only for the hosted Chef Infra Server. | | `clients` | The `clients` group defines the list of nodes on which a Chef Infra Client is installed and under management by Chef. In general, think of this permission as "all of the non-human actors---Chef Infra Client, in nearly every case---that get data from, and/or upload data to, the Chef server". Newly-created Chef Infra Client instances are added to this group automatically. | | `public_key_read_access` | The `public_key_read_access` group defines which users and clients have read permissions to key-related endpoints in the Chef Infra Server API. | | `users` | The `users` group defines the list of users who use knife and the Chef management console to interact with objects and object types. In general, think of this permission as "all of the non-admin human actors who work with data that is uploaded to and/or downloaded from the Chef server". | ### Example Default Permissions The following sections show the default permissions assigned by the Chef Infra Server to the `admins`, `billing_admins`, `clients`, and `users` groups. Note The creator of an object on the Chef Infra Server is assigned `create`, `delete`, `grant`, `read`, and `update` permission to that object. #### admins The `admins` group is assigned the following: | Group | Create | Delete | Grant | Read | Update | | --- | --- | --- | --- | --- | --- | | admins | yes | yes | yes | yes | yes | | clients | yes | yes | yes | yes | yes | | users | yes | yes | yes | yes | yes | #### billing_admins The `billing_admins` group is assigned the following: #### billing_admins The `billing_admins` group is assigned the following: | Group | Create | Delete | Read | Update | | --- | --- | --- | --- | --- | | billing_admins | no | no | yes | yes | #### clients The `clients` group is assigned the following: | Object | Create | Delete | Read | Update | | --- | --- | --- | --- | --- | | clients | no | no | no | no | | cookbooks | no | no | yes | no | | cookbook_artifacts | no | no | yes | no | | data | no | no | yes | no | | environments | no | no | yes | no | | nodes | yes | no | yes | no | | organization | no | no | yes | no | | policies | no | no | yes | no | | policy_groups | no | no | yes | no | | roles | no | no | yes | no | | sandboxes | no | no | no | no | #### public_key_read_access The `public_key_read_access` group controls which users and clients have [read permissions to the following endpoints](../../api_chef_server/index): * GET /clients/CLIENT/keys * GET /clients/CLIENT/keys/KEY * GET /users/USER/keys * GET /users/USER/keys/ By default, the `public_key_read_access` assigns all members of the `users` and `clients` group permission to these endpoints: | Group | Create | Delete | Grant | Read | Update | | --- | --- | --- | --- | --- | --- | | admins | no | no | no | no | no | | clients | yes | yes | yes | yes | yes | | users | yes | yes | yes | yes | yes | #### users The `users` group is assigned the following: #### users The `users` group is assigned the following: | Object | Create | Delete | Read | Update | | --- | --- | --- | --- | --- | | clients | no | yes | yes | no | | cookbooks | yes | yes | yes | yes | | cookbook_artifacts | yes | yes | yes | yes | | data | yes | yes | yes | yes | | environments | yes | yes | yes | yes | | nodes | yes | yes | yes | yes | | organization | no | no | yes | no | | policies | yes | yes | yes | yes | | policy_groups | yes | yes | yes | yes | | roles | yes | yes | yes | yes | | sandboxes | yes | no | no | no | ### chef-validator Every request made by Chef Infra Client to the Chef Infra Server must be an authenticated request using the Chef Infra Server API and a private key. When Chef Infra Client makes a request to the Chef Infra Server, Chef Infra Client authenticates each request using a private key located in `/etc/chef/client.pem`. The chef-validator is allowed to do the following at the start of a Chef Infra Client run. After the Chef Infra Client is registered with Chef Infra Server, that Chef Infra Client is added to the `clients` group: | Object | Create | Delete | Read | Update | | --- | --- | --- | --- | --- | | clients | yes | no | no | no | Server Admins ------------- The `server-admins` group is a global group that grants its members permission to create, read, update, and delete user accounts, with the exception of superuser accounts. The `server-admins` group is useful for users who are responsible for day-to-day administration of the Chef Infra Server, especially user management via the `knife user` subcommand. Before members can be added to the `server-admins` group, they must already have a user account on the Chef Infra Server. ### Scenario The following user accounts exist on the Chef Infra Server: `pivotal` (a superuser account), `alice`, `bob`, `carol`, and `dan`. Run the following command to view a list of users on the Chef Infra Server: ``` chef-server-ctl user-list ``` and it returns the same list of users: ``` pivotal alice bob carol dan ``` Alice is a member of the IT team whose responsibilities include day-to-day administration of the Chef Infra Server, in particular managing the user accounts on the Chef Infra Server that are used by the rest of the organization. From a workstation, Alice runs the following command: ``` knife user list -c ~/.chef/alice.rb ``` and it returns the following error: ``` ERROR: You authenticated successfully to <chef_server_url> as alice but you are not authorized for this action Response: Missing read permission ``` Alice is not a superuser and does not have permissions on other users because user accounts are global to organizations in the Chef Infra Server. Let’s add Alice to the `server-admins` group: ``` chef-server-ctl grant-server-admin-permissions alice ``` and it returns the following response: ``` User alice was added to server-admins. ``` Alice can now create, read, update, and delete user accounts on the Chef Infra Server, even for organizations to which Alice is not a member. From a workstation, Alice re-runs the following command: ``` knife user list -c ~/.chef/alice.rb ``` which now returns: ``` pivotal alice bob carol dan ``` Alice is now a server administrator and can use the following knife subcommands to manage users on the Chef Infra Server: * `knife user-create` * `knife user-delete` * `knife user-edit` * `knife user-list` * `knife user-show` For example, Alice runs the following command: ``` knife user edit carol -c ~/.chef/alice.rb ``` and the $EDITOR opens in which Alice makes changes, and then saves them. #### Superuser Accounts Superuser accounts may not be managed by users who belong to the `server-admins` group. For example, Alice attempts to delete the `pivotal` superuser account: ``` knife user delete pivotal -c ~/.chef/alice.rb ``` and the following error is returned: ``` ERROR: You authenticated successfully to <chef_server_url> as user1 but you are not authorized for this action Response: Missing read permission ``` Alice’s action is unauthorized even with membership in the `server-admins` group. ### Manage server-admins Group Membership of the `server-admins` group is managed with a set of `chef-server-ctl` subcommands: * `chef-server-ctl grant-server-admin-permissions` * `chef-server-ctl list-server-admins` * `chef-server-ctl remove-server-admin-permissions` #### Add Members The `grant-server-admin-permissions` subcommand is used to add a user to the `server-admins` group. Run the command once per user added. This subcommand has the following syntax: ``` chef-server-ctl grant-server-admin-permissions USER_NAME ``` where `USER_NAME` is the user to add to the list of server administrators. For example: ``` chef-server-ctl grant-server-admin-permissions bob ``` returns: ``` User bob was added to server-admins. This user can now list, read, and create users (even for orgs they are not members of) for this Chef Infra Server. ``` #### Remove Members The `remove-server-admin-permissions` subcommand is used to remove a user from the `server-admins` group. Run the command once per user removed. This subcommand has the following syntax: ``` chef-server-ctl remove-server-admin-permissions USER_NAME ``` where `USER_NAME` is the user to remove from the list of server administrators. For example: ``` chef-server-ctl remove-server-admin-permissions bob ``` returns: ``` User bob was removed from server-admins. This user can no longer list, read, and create users for this Chef Infra Server except for where they have default permissions (such as within an org). ``` #### List Membership The `list-server-admins` subcommand is used to return a list of users who are members of the `server-admins` group. This subcommand has the following syntax: ``` chef-server-ctl list-server-admins ``` and will return a list of users similar to: ``` pivotal alice bob carol dan ``` Manage Organizations -------------------- Use the `org-create`, `org-delete`, `org-list`, `org-show`, `org-user-add` and `org-user-remove` commands to manage organizations. ### org-create The `org-create` subcommand is used to create an organization. (The validation key for the organization is returned to `STDOUT` when creating an organization with this command.) **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-create ORG_NAME "ORG_FULL_NAME" (options) ``` where: * The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. * The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `"Chef Software, Inc."`. **Options** This subcommand has the following options: `-a USER_NAME`, `--association_user USER_NAME` Associate a user with an organization and add them to the `admins` and `billing_admins` security groups. `-f FILE_NAME`, `--filename FILE_NAME` Write the ORGANIZATION-validator.pem to `FILE_NAME` instead of printing it to `STDOUT`. ### org-delete The `org-delete` subcommand is used to delete an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-delete ORG_NAME ``` ### org-list The `org-list` subcommand is used to list all of the organizations currently present on the Chef Infra Server. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-list (options) ``` **Options** This subcommand has the following options: `-a`, `--all-orgs` Show all organizations. `-w`, `--with-uri` Show the corresponding URIs. ### org-show The `org-show` subcommand is used to show the details for an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-show ORG_NAME ``` ### org-user-add The `org-user-add` subcommand is used to add a user to an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-user-add ORG_NAME USER_NAME (options) ``` **Options** This subcommand has the following options: `--admin` Add the user to the `admins` group. ### org-user-remove The `org-user-remove` subcommand is used to remove a user from an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-user-remove ORG_NAME USER_NAME (options) ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/server_orgs/Upgrade Chef Infra Server ========================= [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/upgrades.md) Each new release of Chef Infra Server improves reliability and updates 3rd party components to ensure the security of the server. It is important to keep Chef Infra Server up to date to ensure the secure and reliable operation of Chef Infra in your organization. Warning Before upgrading a production server make sure to upgrade a test server to confirm the process. Upgrade Matrix -------------- If running a Chef Infra Server 12.17.15 or later you can upgrade directly to the latest releases of Chef Infra Server 14. If you are running a release before 12.17.15 you must perform a stepped upgrade as outlined below. | Running Version | Upgrade To Version | Requires License | Supported Version | | --- | --- | --- | --- | | 13 | 14 | Yes | Yes | | 12.17.15 | 14 | Yes | No | | 12.3.0 | 12.17.15 | No | No | | 11 | 12.3.0 | No | No | Requires License Chef Infra Server 13 and later are governed by the [Chef EULA](../../chef_license/index). You are required to accept these terms when using Chef Infra Server for the first time by entering `Yes` when prompted. Supported Release Chef Infra Server 14 and later are supported Chef Software releases. Earlier releases are not supported. For more information about supported Chef Software see the [Supported Versions](../../versions/index#supported-commercial-distributions) documentation. Release-Specific Steps ---------------------- ### Upgrading to 14.x Chef Infra Server 14.0 moved from Solr to Elasticsearch as its search index. The Chef Infra Server 14 upgrade process requires downtime for stopping the server, installing the new package, and then upgrading the server, which will include an automatic Elasticsearch reindexing operation for existing Solr users. We estimate the reindexing operation will take 2 minutes for each 1000 nodes, but the it could take more time, depending on your server hardware and the complexity of your Chef data. The Chef Infra Server 14 upgrade does not automatically reindex existing external Elasticsearch installations. #### Upgrading to 14.8 Chef Infra Server 14.8 upgrades PostgreSQL from 9.6 to 13.3. The 14.8 upgrade process requires a one-time downtime to vacuum, upgrade, and re-index the database. The entire upgrade operation takes about one minute for each 1000 nodes (1000 nodes is approximately 286MB). This process may take longer depending on your server hardware and the size of the node objects on your Chef Infra Server. Note Set the `postgresql['pg_upgrade_timeout']` attribute in [chef-server.rb](../config_rb_server_optional_settings/index) to the timeout value for the upgrade. Set this value based on the size of your data, where it take about one minute per 1,000 nodes which is approximately 286MB. ##### Database Preparation 1. Run `VACUUM FULL` on the PostgreSQL database if you don’t have automatic vacuuming set up. This process will reduce the size of the database by deleting unnecessary data and speeds up the migration. The `VACUUM FULL` operation takes around 1 to 2 minutes per gigabyte of data depending on the complexity of the data, and requires free disk space at least as large as the size of your database. ``` sudo su - opscode-pgsql /opt/opscode/embedded/bin/vacuumdb --all --full ``` You should then see output like: ``` vacuumdb: vacuuming database "bifrost" vacuumdb: vacuuming database "oc_id" vacuumdb: vacuuming database "opscode-pgsql" vacuumdb: vacuuming database "opscode_chef" vacuumdb: vacuuming database "postgres" vacuumdb: vacuuming database "template1" ``` 2. Back up the PostgreSQL database before upgrading so you can restore the full database to a previous release in the event of a failure. See [Backup and Restore](../server_backup_restore/index) for more information. ##### Upgrade Steps Follow the Chef Infra Server upgrade instructions below. Note Estimates are based on an 8-core 32 GB memory (t3.2xlarge) AWS EC2 instance with 2 organizations and 3 users having 565,000+ nodes, 13,000+ cookbooks, 29,000+ databags, 274,000+ environments, and 281,000+ roles. ### Upgrading to 12.17.15 Warning Upgrade Chef Infra Server and any add-ons to compatible versions before setting `insecure_addon_compat` to `false`. As of version 12.14, Chef Infra Server renders passwords inside of the `/etc/opscode` directory by default. If you are using Chef Infra Server without add-ons, or if you are using the latest add-ons versions, you can set `insecure_addon_compat` to `false` in `/etc/opscode/chef-server.rb. and Chef Infra Server will write all credentials to a single location. For more information on password generation, including a list of supported add-on versions, see [Chef Infra Server Credentials Management](../server_security/index#chef-infra-server-credentials-management). ### Upgrading to 12.3.0 If you are running a Chef Infra Server release before 12.3.0, please contact Chef Support for guidance on upgrading your Chef Infra Server installation. Chef Infra Server 14 Upgrade Process ------------------------------------ ### Standalone Server The Chef Infra Server 14 upgrade process requires downtime for stopping the server, installing the new package, and then upgrading the server, which will include an automatic Elasticsearch reindexing operation for existing Solr users. We estimate the reindexing operation will take 2 minutes for each 1000 nodes, but the it could take more time, depending on your server hardware and the complexity of your Chef data. 1. Run `vacuumdb` before starting the upgrade: ``` sudo su - opscode-pgsql /opt/opscode/embedded/bin/vacuumdb --all --full exit ``` You should see output like: ``` vacuumdb: vacuuming database "bifrost" vacuumdb: vacuuming database "oc_id" vacuumdb: vacuuming database "opscode-pgsql" vacuumdb: vacuuming database "opscode_chef" vacuumdb: vacuuming database "postgres" vacuumdb: vacuuming database "template1" ``` 2. Back up your Chef Infra Server data before starting the upgrade process using [chef-server-ctl-backup](../server_backup_restore/index#backup). **Make a note of where the backup is located** (The default is `/var/opt/chef-backup`). Please note that Chef Infra Server will go offline to perform the backup: ``` sudo chef-server-ctl backup ``` 3. Confirm that the Chef Infra Server services are operational: ``` chef-server-ctl reconfigure ``` 4. If you are already running 12.17.15 or greater, proceed to the next step. Otherwise consult the [upgrade matrix](#upgrade-matrix) and perform a stepped upgrade. * If you are running Chef Infra Server 12.3.0, upgrade to 12.17.15. * If you are running Chef Infra Server 11, first upgrade to 12.3.0, and then to 12.17.15.After performing the stepped upgrade to 12.17.15, continue with the next step. 5. Download the desired Chef Infra Server version from the [Chef Infra Server Downloads](https://downloads.chef.io/products/chef-server). 6. Stop the Chef Infra Server: ``` chef-server-ctl stop || chef-server-ctl kill rabbitmq ``` 7. Install the Chef Infra Server package: To install with `dpkg`: ``` dpkg -iEG /path/to/chef-server-core-VERSION.deb ``` To install with the RPM Package Manager: ``` rpm -Uvh --nopostun /path/to/chef-server-core-VERSION.rpm ``` 8. Upgrade the server and accept the Chef Software license by entering `Yes` at the prompt: ``` chef-server-ctl upgrade ``` To accept the license and upgrade in one command: ``` CHEF_LICENSE='accept' chef-server-ctl upgrade ``` 9. If the upgrade failed, see the section below on how to handle an [upgrade failure](#upgrade-failure-troubleshooting). If the upgrade was successful, start Chef Infra Server: ``` chef-server-ctl start ``` 10. [Upgrade](#upgrading-manage-add-on) any Chef Infra Server add-ons. 11. After the upgrade process is complete, test and verify that the server works. 12. Clean up the Chef Infra Server by removing the old data: ``` chef-server-ctl cleanup ``` 13. Reindex the database: ``` sudo su - opscode-pgsql /opt/opscode/embedded/bin/reindexdb --all ``` You should see output like: ``` reindexdb: reindexing database "bifrost" reindexdb: reindexing database "oc_id" reindexdb: reindexing database "opscode-pgsql" reindexdb: reindexing database "opscode_chef" reindexdb: reindexing database "postgres" reindexdb: reindexing database "template1" ``` You are now finished with the upgrade. Note Check the [post upgrade steps](#post-upgrade-steps) if you are upgrading from a version before Chef Infra Server 14.8 to a version greater than or equal to 14.8. #### Upgrade Failure Troubleshooting 1. If the upgrade failed and you have a corrupted Chef Infra Server and/or a corrupted database, **DO NOT RISK YOUR BACKUP OF THE DATABASE.** Take all steps necessary to preserve the backup, including copying it to another disk. Consult with a professional sysadmin for instructions and best practices. 2. Contact customer support. 3. Reinstall the original version of Chef Infra Server you were using before attempting the upgrade process (if you had to perform a stepped upgrade, [install your original version of Chef Infra Server](../install_server/index) before the stepped upgrade, not any versions you upgraded to in the stepped upgrade process). Again, **DO NOT RISK YOUR BACKUP OF THE DATABASE.** For example, consider using a separate disk from your backup for the new installation. 4. Consult the [restore documentation](../server_backup_restore/index) and restore the database from the path to where it was saved: ``` chef-server-ctl restore /path/to/tar/archive.tar.gz ``` ### External PostgreSQL The following External PostgreSQL upgrade steps are provided as a courtesy only. It is the responsibility of the user to upgrade and maintain any External PostgreSQL configurations. #### Upgrade Chef Infra Server 1. Log into the external PostgreSQL machine. 2. Run `vacuumdb` before starting the upgrade: ``` sudo su postgres /usr/bin/vacuumdb --all --full exit ``` 3. Log into the Chef Infra Server machine. 4. Consult the documentation on [`knife-ec-backup`](https://blog.chef.io/migrating-chef-server-knife-ec-backup-knife-tidy). Install `knife-ec-backup`, if it not already installed. A sample session follows (note that your steps could differ, depending on the versions of your software, the topology of your setup, your OS and distribution, and a range of other factors). For example: ``` apt-get update apt install ruby apt install make curl -L https://chef.io/chef/install.sh | sudo bash -s -- -P chefdk export PATH=$PATH:/root/.chefdk/gem/ruby/2.6.0/bin apt-get -y install gcc postgresql libpq-dev /opt/chefdk/embedded/bin/gem install knife-ec-backup -- --with-pg-config=/opt/opscode/embedded/postgresql/9.6/bin/pg_config ``` 5. Configure `knife` if it is not already configured. A sample session follows (again, note that your steps could differ, depending on a range of factors). For Example: ``` $ chef-server-ctl org-create 4thcafe 'Fourth Cafe, Inc.' --association_user janedoe --filename /tmp/4thcafe-validator.pem $ chef generate repo chef-repo $ cd chef-repo/ $ mkdir -p .chef $ echo '.chef' >> .gitignore $ cp /tmp/4thcafe-validator.pem .chef $ cp /home/ubuntu/janedoe.pem .chef $ cd .chef $ knife configure WARNING: No knife configuration file found. See https://docs.chef.io/config_rb/ for details. Please enter the chef server URL: [https://1.2.3.4/organizations/myorg] https://1.2.3.4/organizations/4thcafe Please enter an existing username or clientname for the API: [ubuntu] janedoe $ knife ssl fetch ``` 6. Backup the database. For Example: ``` mkdir /backup /opt/chefdk/embedded/bin/knife ec backup /backup ``` 7. If you are running Chef Infra Server version 12.17.15 or greater, proceed to the next step below. Otherwise consult the [upgrade matrix](#upgrade-matrix) and perform a stepped upgrade. If you are running a Chef Infra Server release before 12.17.15, you cannot upgrade directly to 14.8.X. You must perform a stepped upgrade first. * If you are running Chef Infra Server 12.3.0, upgrade to 12.17.15. * If you are running Chef Infra Server 11, you must first upgrade to 12.3.0, and then to 12.17.15.After performing the stepped upgrade, return here and continue with the next step below. 8. [Download](https://downloads.chef.io/tools/infra-server) the desired version of Chef Infra Server. 9. Stop the Chef Infra Server: ``` chef-server-ctl stop || chef-server-ctl kill rabbitmq ``` 10. Install the Chef Infra Server package: To install with `dpkg`: ``` dpkg -iEG /path/to/chef-server-core-VERSION.deb ``` To install with the RPM Package Manager: ``` rpm -Uvh --nopostun --force /path/to/chef-server-core-VERSION.rpm ``` 11. Upgrade Chef Infra Server and accept the Chef Software license by entering `Yes` at the prompt: ``` chef-server-ctl upgrade ``` To accept the license and upgrade in one command: ``` CHEF_LICENSE='accept' chef-server-ctl upgrade ``` 12. If the upgrade failed, see the section on [upgrade failure troubleshooting](#upgrade-failure-troubleshooting-1). If the upgrade was successful, start the Chef Infra Server services and cleanup. ``` sudo chef-server-ctl start sudo chef-server-ctl cleanup ``` You are now finished with the Chef Infra Server upgrade. Proceed directly to the **Upgrade PostgreSQL** section. #### Upgrade PostgreSQL 1. Log into the external PostgreSQL machine. 2. Update packages and install your selected PostgreSQL version. Example (Ubuntu/PostgreSQL 13.3): ``` sudo apt-get update sudo apt-get install postgresql-13 ``` 3. Check if there are any differences in the config files. Make sure to update the new config files if required. Example (PostgreSQL 13.3): ``` diff /etc/postgresql/OLD_POSTGRESQL_VERSION/main/postgresql.conf /etc/postgresql/13/main/postgresql.conf diff /etc/postgresql/OLD_POSTGRESQL_VERSION/main/pg_hba.conf /etc/postgresql/13/main/pg_hba.conf ``` 4. Stop the PostgreSQL service. ``` sudo systemctl stop postgresql.service ``` 5. Log in as the `postgres` user. ``` su postgres ``` 6. Ensure that you are in a directory where you can run the `pg_upgrade` command. Example: ``` cd /tmp ``` 7. Check clusters (notice the `--check` argument, this will not change any data). Example (PostgreSQL 13.3): ``` /usr/lib/postgresql/13/bin/pg_upgrade \ --old-datadir=/var/lib/postgresql/9.6/main \ --new-datadir=/var/lib/postgresql/13/main \ --old-bindir=/usr/lib/postgresql/9.6/bin \ --new-bindir=/usr/lib/postgresql/13/bin \ --old-options '-c config_file=/etc/postgresql/9.6/main/postgresql.conf' \ --new-options '-c config_file=/etc/postgresql/13/main/postgresql.conf' \ --check ``` 8. Migrate the data (without the `--check` argument). Example (PostgreSQL 13.3): ``` /usr/lib/postgresql/13/bin/pg_upgrade \ --old-datadir=/var/lib/postgresql/9.6/main \ --new-datadir=/var/lib/postgresql/13/main \ --old-bindir=/usr/lib/postgresql/9.6/bin \ --new-bindir=/usr/lib/postgresql/13/bin \ --old-options '-c config_file=/etc/postgresql/9.6/main/postgresql.conf' \ --new-options '-c config_file=/etc/postgresql/13/main/postgresql.conf' ``` 9. Log out of the `postgres` user. ``` exit ``` 10. Swap the ports for the old and new PostgreSQL versions. Example (PostgreSQL 13.3): ``` $ sudo vim /etc/postgresql/13/main/postgresql.conf # change "port = 5433" to "port = 5432" $ sudo vim /etc/postgresql/9.6/main/postgresql.conf # change "port = 5432" to "port = 5433" ``` 11. Start the PostgreSQL service. ``` sudo systemctl start postgresql.service ``` 12. Log in as the `postgres` user and confirm that the new PostgreSQL version is correct. Example (PostgreSQL 13.3): ``` $ sudo su - postgres $ psql -c "SELECT version();" version --------------------------------------------------------------------------------------------------------------------------------------------- PostgreSQL 13.3 (Ubuntu 13.3-1.pgdg16.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609, 64-bit (1 row) ``` 13. Run `reindexdb`. Example: ``` $ /usr/bin/reindexdb --all reindexdb: reindexing database "bifrost" reindexdb: reindexing database "oc_id" reindexdb: reindexing database "opscode_chef" reindexdb: reindexing database "postgres" reindexdb: reindexing database "template1" ``` 14. Log into the Chef Infra Server machine. 15. Check the status of Chef Infra Server. PostgreSQL should be connected. ``` $ sudo chef-server-ctl status ------------------- Internal Services ------------------- run: bookshelf: (pid 15763) 219163s; run: log: (pid 16559) 228464s run: elasticsearch: (pid 15797) 219162s; run: log: (pid 16345) 228507s run: nginx: (pid 15901) 219162s; run: log: (pid 16745) 228452s run: oc_bifrost: (pid 15909) 219161s; run: log: (pid 16237) 228519s run: oc_id: (pid 15915) 219161s; run: log: (pid 16255) 228513s run: opscode-erchef: (pid 15948) 219160s; run: log: (pid 16673) 228458s run: redis_lb: (pid 15952) 219160s; run: log: (pid 16779) 228445s ------------------- External Services ------------------- run: postgresql: connected OK to 10.0.11.0:5432 ``` #### Upgrade Failure Troubleshooting 1. If the upgrade failed and you are left with a corrupted Chef Infra Server and/or a corrupted database, **DO NOT RISK YOUR BACKUP OF THE DATABASE.** Take all steps necessary to preserve the backup, including copying it to another disk. Consult with a professional sysadmin for instructions and best practices. 2. Contact customer support. 3. Reinstall the original version of Chef Infra Server you were using before attempting the upgrade process (if you had to perform a stepped upgrade, [install your original version of Chef Infra Server](../install_server/index) before the stepped upgrade, not any versions you upgraded to in the stepped upgrade process). Again, **DO NOT RISK YOUR BACKUP OF THE DATABASE.** For example, consider using a separate disk from your backup for the new installation. 4. Consult the documentation on [knife-ec-restore](https://blog.chef.io/migrating-chef-server-knife-ec-backup-knife-tidy), and restore the database from the path where it was saved. Example: ``` /opt/chefdk/embedded/bin/knife ec restore /backup/ ``` 5. Do not continue upgrading PostgreSQL until you have an uncorrupted Chef Infra Server and an uncorrupted PostgreSQL database. ### Chef Backend Install Warning Chef Backend is [deprecated](../../versions/index#deprecated-products-and-versions) and no longer under active development. Contact your Chef account representative for information about migrating to Chef Automate HA. This document is no longer maintained. The Chef Infra Server can operate in a high availability configuration that provides automated load balancing and failover for stateful components in the system architecture. To upgrade your Chef Backend installation, see [High Availability: Upgrade to Chef Backend 2](../upgrade_server_ha_v2/index). ### Tiered Install This section describes the upgrade process from a tiered server configuration. Note These instructions are for the Chef Infra Server `tier` topology. For the latest information on setting up a highly available server cluster, see [High Availability: Backend Cluster](../install_server_ha/index). ### Tiered Upgrade Steps To upgrade to Chef Infra Server on a tiered Chef Infra Server configuration, do the following: 1. Back up the Chef Infra Server data before starting the upgrade process using [knife-ec-backup](https://github.com/chef/knife-ec-backup). 2. Confirm that the Chef Infra Server services are operational: ``` chef-server-ctl reconfigure ``` 3. Download the desired Chef Infra Server version from the [Chef Infra Server Downloads](https://downloads.chef.io/products/chef-server) page, then copy it to each server. 4. Stop all front end servers: ``` chef-server-ctl stop ``` 5. Install the Chef Infra Server package on all servers: To install with `dpkg`: ``` dpkg -i /path/to/chef-server-core-<version>.deb ``` To install with the RPM Package Manager: ``` rpm -Uvh --nopostun /path/to/chef-server-core-<version>.rpm ``` 6. Stop the back end server: ``` chef-server-ctl stop ``` 7. Upgrade the server and accept the Chef Software license by entering `Yes` at the prompt: ``` chef-server-ctl upgrade ``` To accept the license and upgrade in one command: ``` CHEF_LICENSE='accept' chef-server-ctl upgrade ``` 8. Copy the entire `/etc/opscode` directory from the back end server to all front end servers: ``` scp -r /etc/opscode <each server's IP>:/etc ``` 9. Upgrade each of the front end servers: ``` chef-server-ctl upgrade ``` 10. Run the following command on both the front end, and back end servers: ``` chef-server-ctl start ``` 11. [Upgrade](#upgrading-manage-add-on) any Chef Infra Server add-ons. 12. After the upgrade process is complete, test and verify that the server works. 13. Clean up the server by removing the old data: ``` chef-server-ctl cleanup ``` Note Check the [post upgrade steps](#post-upgrade-steps) if you are upgrading from a version before Chef Infra Server 14.8 to a version greater than or equal to 14.8. ### Upgrading Manage Add-On Chef Manage is a management console for data bags, attributes, run-lists, roles, environments, and cookbooks from a web user interface. Chef Infra Server 14 supports the Chef Manage add-on. This add-on is [deprecated](../../versions/index#deprecated-products-and-versions) and will reach [EOL](../../versions/index#end-of-life-eol-products) on December 31, 2022. After upgrading Chef Infra Server, reinstall the add-on and then reconfigure Chef Infra Server and the add-on. #### Use Downloads.chef.io The `install` subcommand downloads packages from <https://packages.chef.io> by default. For systems that are not behind a firewall (and have connectivity to <https://packages.chef.io>), these packages can be installed as described below. 1. Install add-ons Install Chef Manage with: ``` sudo chef-server-ctl install chef-manage ``` 2. Reconfigure the server ``` sudo chef-server-ctl reconfigure ``` 3. Reconfigure add-ons Reconfigure Chef Manage with: ``` sudo chef-manage-ctl reconfigure ``` Finally, accept the [Chef License](../../chef_license/index): ``` sudo chef-manage-ctl reconfigure --accept-license ``` #### Use Local Packages Use the `install` subcommand with the `--path` option to install the Chef Manage (`chef-manage`) add-on for Chef Infra Server. ``` sudo chef-server-ctl install PACKAGE_NAME --path /path/to/package/directory ``` For example: ``` sudo chef-server-ctl install chef-manage --path /root/packages ``` The `chef-server-ctl` command will install the first `chef-manage` package found in the `/root/packages` directory. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/upgrades/High Availability: Upgrade to Chef Backend 2 ============================================ [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/upgrade_server_ha_v2.md) Warning Chef Backend is [deprecated](../../versions/index#deprecated-products-and-versions) and no longer under active development. Contact your Chef account representative for information about migrating to Chef Automate HA. This document is no longer maintained. This topic describes the process of upgrading a high availability Chef Infra Server cluster. The Chef Infra Server 14 upgrade process requires downtime for stopping the server, installing the new package, and then upgrading the server, which will include an automatic Elasticsearch reindexing operation for existing Solr users. We estimate the reindexing operation will take 2 minutes for each 1000 nodes, but the it could take more time, depending on your server hardware and the complexity of your Chef data. Overview -------- These instructions cover the process of upgrading a Chef Backend cluster. Please refer to the appropriate directions for the version of Chef Backend that you are using and the version that you intend to upgrade to: Update Chef Backend ------------------- The minor version update is appropriate for all upgrades of a Chef Backend cluster within a version. For example, updating from 1.x to 1.x or 2.x to 2.x. Note The procedure assumes that the new chef-backend package has been copied to all of the nodes. ### Step 1: Block Failover We don’t want the cluster to fail over to a follower that is in the process of being updated. So we start by disabling failover: 1. Run `chef-backend-ctl set-cluster-failover off` ### Step 2: Update the followers Followers should be updated sequentially. Upgrading them simultaneously is not supported and may result in data loss. Verify the successful rejoin after each upgrade. 1. Install the new chef-backend package: RHEL and CentOS: ``` yum install PATH_TO_FILE.rpm ``` Debian and Ubuntu: ``` dpkg -i PATH_TO_FILE.deb ``` You may also want to look at the chef-ingredient cookbook to automate downloading and installing the latest package. 2. Run the upgrade command: ``` chef-backend-ctl upgrade ``` The update command will make any changes necessary to start the new service and verify that the updated node has rejoined the cluster. Repeat the previous steps in this section for each remaining follower. ### Step 3: Update the leader Unblock failover, trigger failover, block it again. ``` % chef-backend-ctl set-cluster-failover on % chef-backend-ctl upgrade --failover % chef-backend-ctl set-cluster-failover off ``` ### Step 4: Re-enable failover Allow failover again: ``` chef-backend-ctl set-cluster-failover on ``` ### Step 5: Verify the cluster is stable Check the status of the cluster: ``` chef-backend-ctl status ``` Chef Backend 1.x to 2.x Upgrade ------------------------------- Warning Upgrading from Chef Backend 1.x to Chef Backend 2.x requires full cluster downtime. 1. Identify the node with the **leader** role using the `chef-backend-ctl cluster-status` command: ``` Name IP GUID Role PG ES backend-1 192.168.33.215 dc0c6ea77a751f94037cd950e8451fa3 leader leader not_master backend-2 192.168.33.216 008782c59d3628b6bb7f43556ac0c66c follower follower not_master backend-3 192.168.33.217 1af654172b1830927a571d9a5ba7965b follower follower master ``` In this example, `backend-1` is the **leader** node, as indicated by its role in the **Role** column. 2. Install the new Chef Backend package on all nodes in the cluster: RHEL and CentOS: ``` yum install PATH_TO_FILE.rpm ``` Debian and Ubuntu: ``` dpkg -i PATH_TO_FILE.deb ``` 3. On the leader, run the following command to take the node down for the upgrade: ``` chef-backend-ctl down-for-upgrade ``` 4. Then issue the same command on the follower nodes: ``` chef-backend-ctl down-for-upgrade ``` 5. Initiate the upgrade on the follower nodes first: ``` chef-backend-ctl upgrade ``` 6. Then initiate the upgrade on the leader node: ``` chef-backend-ctl upgrade ``` 7. On any Chef Infra Server frontend nodes using the Chef Backend cluster upgraded in the previous steps, run: ``` chef-server-ctl reconfigure ``` 8. To continue the upgrades on Chef Infra Server frontend nodes using this backend cluster, see [Upgrade Frontends Associated with a Chef Backend Cluster](../install_server_ha/index#upgrading-chef-infra-server-on-the-frontend-machines). DRBD/Keepalived HA to Chef Backend 2.x -------------------------------------- DRBD configurations are no longer supported. See [End of Life Products](../../versions/index#end-of-life-eol). For a guide to migrating to Chef Backend from DRBD see the [Best Best Practices for Migrating Your Chef Server](https://blog.chef.io/2018/04/06/best-practices-for-migrating-your-chef-server/) webinar from the [Chef Blog](https://blog.chef.io/). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/upgrade_server_ha_v2/High Availability: Chef Backend =============================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/install_server_ha.md) Warning Chef Backend is [deprecated](../../versions/index#deprecated-products-and-versions) and no longer under active development. Contact your Chef account representative for information about migrating to Chef Automate HA. This document is no longer maintained. This topic introduces the underlying concepts behind the architecture of the high availability Chef Infra Server cluster. The topic then describes the setup and installation process for a high availability Chef Infra Server cluster comprised of five total nodes (two frontend and three backend). Overview -------- The Chef Infra Server can operate in a high availability configuration that provides automated load balancing and failover for stateful components in the system architecture. This type of configuration typically splits the servers into two segments: The backend cluster, and the frontend group. * The frontend group, comprised of one (or more) nodes running the Chef Infra Server. Nodes in the frontend group handle requests to the Chef Infra Server API and access to the Chef management console. Frontend group nodes should be load balanced, and may be scaled horizontally by increasing the number of nodes available to handle requests. * The backend cluster, comprised of three nodes working together, provides high availability data persistence for the frontend group. Note At this time, backend clusters can only have three nodes. ![image](https://docs.chef.io/images/server/chef_server_ha_cluster.svg) Important When doing cloud deployments, Chef HA clusters are not meant to be geographically dispersed across multiple regions or datacenters; however, in cloud providers such as AWS, you can deploy HA clusters across multiple Availability Zones within the same region. ### Key Differences From Standalone Chef Infra Server **New in Chef Infra Server 14** Starting with Chef Infra Server 14, standalone instances use Elasticsearch for internal search. Elasticsearch provides more flexible clustering options while maintaining search API compatibility with Apache Solr. Recommended Cluster Topology ---------------------------- ### Nodes * The HA backend installation requires three cluster nodes. Chef has not tested and does not support installations with other numbers of backend cluster nodes. * One or more frontend group nodes #### Hardware Requirements The following are a list of general hardware requirements for both frontend and backend servers. The important guideline you should follow are that frontend servers tend to be more CPU bound and backend servers are more disk and memory bound. Also, disk space for backend servers should scale up with the number of nodes that the servers are managing. A good rule to follow is to allocate 2 MB per node. The disk values listed below should be a good default value that you will want to modify later if/when your node count grows. * 64-bit architecture **Frontend Requirements** * 4 cores (physical or virtual) * 4GB RAM * 20 GB of free disk space (SSD if on premises, Premium Storage in Microsoft Azure, EBS-Optimized GP2 in AWS) **Backend Requirements** * 2 cores (physical or virtual) * 8GB RAM * 50 GB/backend server (SSD if on premises, Premium Storage in Microsoft Azure, EBS-Optimized GP2 in AWS) Warning The Chef Infra Server MUST NOT use a network file system of any type—virtual or physical—for backend storage. The Chef Infra Server database operates quickly. The behavior of operations, such as the writing of log files, will be unpredictable when run over a network file system. ### Network Services * A load balancer between the rest of the network, and the frontend group (Not provided). Because management console session data is stored on each node in the frontend group individually, the load balancer should be configured with sticky sessions. ### Network Port Requirements #### Inbound from load balancer to frontend group * TCP 80 (HTTP) * TCP 443 (HTTPS) #### Inbound from frontend group to backend cluster * TCP 2379 (etcd) * TCP 5432 (PostgreSQL) * TCP 7331 (leaderl) * TCP 9200-9300 (Elasticsearch) #### Peer communication, backend cluster * 2379 (etcd) * 2380 (etcd) * 5432 (PostgreSQL) * 9200-9400 (Elasticsearch) Installation ------------ These instructions assume you are using the minimum versions: * Chef Server : 12.5.0 * Chef Backend : 0.8.0 Download [Chef Infra Server](https://downloads.chef.io/chef-server/) and [Chef Backend (chef-backend)](https://downloads.chef.io/chef-backend/) if you do not have them already. Before creating the backend HA cluster and building at least one Chef Infra Server to be part of the frontend group, verify: * The user who will install and build the backend HA cluster and frontend group has root access to all nodes. * The number of backend and frontend nodes that are desired. It is required to have three backend nodes, but the number of frontend nodes may vary from a single node to a load-balanced tiered configuration. * SSH access to all boxes that will belong to the backend HA cluster from the node that will be the initial bootstrap. * A time synchronization policy is in place, such as Network Time Protocol (NTP). Drift of less than 1.5 seconds must exist across all nodes in the backend HA cluster. ### Step 1: Create Cluster The first node must be bootstrapped to initialize the cluster. The node used to bootstrap the cluster will be the cluster leader when the cluster comes online. After bootstrap completes this node is no different from any other back-end node. 1. Install the Chef Backend package on the first backend node **as root**. * Download [Chef Backend (chef-backend)](https://downloads.chef.io/chef-backend/) * In Red Hat/CentOS: `yum install PATH_TO_RPM` * In Debian/Ubuntu: `dpkg -i PATH_TO_DEB` 2. Update `/etc/chef-backend/chef-backend.rb` with the following content: ``` publish_address 'external_IP_address_of_this_box' # External ip address of this backend box ``` 3. If any of the backends or frontends are in different networks from each other then add a `postgresql.md5_auth_cidr_addresses` line to `/etc/chef-backend/chef-backend.rb` with the following content where `, "<NET-1_IN_CIDR>", ..., "<NET-N_IN_CIDR>"` is the list of all of the networks that your backends and frontends are in. See the [Configuring Frontend and Backend Members on Different Networks](#configuring-frontend-and-backend-members-on-different-networks) section for more information: ``` publish_address 'external_IP_address_of_this_box' # External ip address of this backend box postgresql.md5_auth_cidr_addresses = ["samehost", "samenet", "<NET-1_IN_CIDR>", ..., "<NET-N_IN_CIDR>"] ``` 4. Run `chef-backend-ctl create-cluster`. ### Step 2: Shared Credentials The credentials file `/etc/chef-backend/chef-backend-secrets.json` generated by bootstrapping must be shared with the other nodes. You may copy them directly, or expose them via a common mounted location. For example, to copy using ssh: ``` scp /etc/chef-backend/chef-backend-secrets.json <USER>@<IP_BE2>:/home/<USER> scp /etc/chef-backend/chef-backend-secrets.json <USER>@<IP_BE3>:/home/<USER``` Delete this file from the destination after Step 4 has been completed for each backend being joined to the cluster. ### Step 3: Install and Configure Remaining Backend Nodes For each additional node do the following in sequence (if you attempt to join nodes in parallel the cluster may fail to become available): 1. Install the Chef Backend package on the node. * Download [Chef Backend (chef-backend)](https://downloads.chef.io/chef-backend/) * In Red Hat/CentOS: `yum install PATH_TO_RPM` * In Debian/Ubuntu: `dpkg -i PATH_TO_DEB` 2. If you added a `postgresql.md5_auth_cidr_addresses` line to the leader’s `/etc/chef-backend/chef-backend.rb` in [Step 1: Create Cluster](#step-1-create-cluster) then update this node’s `/etc/chef-backend/chef-backend.rb` with the following content where `postgresql.md5_auth_cidr_addresses` is set to the same value used in the leader’s `chef-backend.rb`. If all of the backend and frontend clusters are in the same network then you don’t need to modify this node’s `/etc/chef-backend/chef-backend.rb` at all. ``` publish_address 'external_IP_address_of_this_box' # External ip address of this backend box postgresql.md5_auth_cidr_addresses = ["samehost", "samenet", "<NET-1_IN_CIDR>", ..., "<NET-N_IN_CIDR>"] ``` 3. **As root** or with sudo: ``` chef-backend-ctl join-cluster <IP_BE1> -s /home/<USER>/chef-backend-secrets.json ``` 4. Answer the prompts regarding which public IP to use. As an alternative, you may specify them on the `chef-backend join-cluster` command line. See `chef-backend-ctl join-cluster --help` for more information. If you manually added the `publish_address` line to `/etc/chef-backend/chef-backend.rb` then you will not be prompted for the public IP and you should not use the `--publish-address` option to specify the the public IP on the `chef-backend join-cluster` command line. 5. If you copied the shared `chef-backend-secrets.json` file to a user HOME directory on this host, remove it now. 6. Repeat these steps for each follower node, after which the cluster is online and available. From any node in the backend HA cluster, run the following command: ``` chef-backend-ctl status ``` should return something like: ``` Service Local Status Time in State Distributed Node Status elasticsearch running (pid 6661) 1d 5h 59m 41s state: green; nodes online: 3/3 etcd running (pid 6742) 1d 5h 59m 39s health: green; healthy nodes: 3/3 leaderl running (pid 6788) 1d 5h 59m 35s leader: 1; waiting: 0; follower: 2; total: 3 postgresql running (pid 6640) 1d 5h 59m 43s leader: 1; offline: 0; syncing: 0; synced: 2 ``` ### Step 4: Generate Chef Infra Server Configuration Log into the node from Step 1 and generate a chef-server frontend node configuration: ``` chef-backend-ctl gen-server-config <FE1-FQDN> -f chef-server.rb.FE1 scp chef-server.rb.FE1 USER@<IP_FE1>:/home/<USER``` Note `/etc/chef-backend/chef-backend-secrets.json` is *not* made available to Chef Infra Server frontend nodes. ### Step 5: Install and Configure the First Frontend On the first frontend node, assuming that the generated configuration was copied as detailed in Step 4: 1. Install the current `chef-server-core` package 2. Copy the file to `/etc/opscode` with: ``` `cp /home/<USER>/chef-server.rb.<FE1> /etc/opscode/chef-server.rb` ``` 3. **As root**, run ``` chef-server-ctl reconfigure ``` ### Step 6: Adding More Frontend Nodes For each additional frontend node you wish to add to your cluster: 1. Install the current `chef-server-core` package. 2. Generate a new `/etc/opscode/chef-server.rb` from any of the backend nodes via ``` chef-backend-ctl gen-server-config <FE_NAME-FQDN> > chef-server.rb.<FE_NAME``` 3. Copy it to `/etc/opscode` on the new frontend node. 4. From the first frontend node configured in Step 5, copy the following files from the first frontend to `/etc/opscode` on the new frontend node: * /etc/opscode/private-chef-secrets.json Note For Chef Server versions prior to 12.14, you will also need to copy the key files: * /etc/opscode/webui_priv.pem * /etc/opscode/webui_pub.pem * /etc/opscode/pivotal.pem 5. On the new frontend node run: ``` mkdir -p /var/opt/opscode/upgrades/ ``` 6. From the first frontend node, copy `/var/opt/opscode/upgrades/migration-level` to the same location on the new node. 7. On the new frontend run: ``` touch /var/opt/opscode/bootstrapped` ``` 8. On the new frontend, **as root** run: ``` chef-server-ctl reconfigure ``` ### Step 7: Configure the Server Note To restore a backup to this system, follow the [chef-server-ctl](../server_backup_restore/index) or the [knife ec](https://github.com/chef/knife-ec-backup) restore directions. 1. Run the following command to create an administrator: ``` sudo chef-server-ctl user-create USER_NAME FIRST_NAME LAST_NAME EMAIL 'PASSWORD' --filename FILE_NAME ``` An RSA private key is generated automatically. This is the user’s private key and should be saved to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. For example: ``` sudo chef-server-ctl user-create janedoe <NAME> <EMAIL> 'abc123' --filename /path/to/janedoe.pem ``` 2. Run the following command to create an organization: ``` sudo chef-server-ctl org-create short_name 'full_organization_name' --association_user user_name --filename ORGANIZATION-validator.pem ``` For example: ``` sudo chef-server-ctl org-create 4thcafe 'Fourth Cafe, Inc.' --association_user janedoe --filename /path/to/4thcafe-validator.pem ``` The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `4thcafe`. The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `'Fourth Cafe, Inc.'`. The `--association_user` option will associate the `user_name` with the `admins` security group on the Chef Infra Server. An RSA private key is generated automatically. This is the chef-validator key and should be saved to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. ### Upgrading Chef Infra Server on the Frontend Machines 1. On one frontend server, follow the [standalone upgrade process](../upgrades/index#standalone). 2. Copy `/var/opt/opscode/upgrades/migration-level` from the first upgraded frontend to `/var/opt/opscode/upgrades/migration-level` on each of the remaining frontends. 3. Once the updated file has been copied to each of the remaining frontends, perform the [standalone upgrade process](../upgrades/index#standalone) on each of the frontend servers. ### Configuring Frontend and Backend Members on Different Networks By default, PostgreSQL only allows systems on its local network to connect to the database server that runs it and the `pg_hba.conf` used by PostgreSQL controls network access to the server. The default `pg_hba.conf` has the following four entries: ``` host all all samehost md5 hostssl replication replicator samehost md5 host all all samenet md5 hostssl replication replicator samenet md5 ``` To allow other systems to connect, such as members of a frontend group that might exist on a different network, you will need to authorize that usage by adding the following line to the `/etc/chef-backend/chef-backend.rb` file on all of the backend members. ``` postgresql.md5_auth_cidr_addresses = ["samehost", "samenet", "<YOURNET IN CIDR>"] ``` After setting the `md5_auth_cidr_addresses` value and reconfiguring the server, two entries will be created in `pg_hba.conf` for each value in the `md5_auth_cidr_addresses` array. Existing values in `pg_hba.conf` will be overwritten by the values in the array, so we must also specify “samehost” and “samenet”, which will continue to allow systems on a local network to connect to PostgreSQL. For example, if a frontend host at 192.168.1.3 can reach a backend member over the network, but the backend’s local network is 192.168.2.x, you would add the following line to `/etc/chef-backend/chef-backend.rb` ``` postgresql.md5_auth_cidr_addresses = ["samehost", "samenet", "192.168.1.3/24"] ``` which would result in the following two entries being added to the `pg_hba.conf` file. ``` host all all samehost md5 hostssl replication replicator samehost md5 host all all samenet md5 hostssl replication replicator samenet md5 host all all 192.168.1.3/24 md5 hostssl replication replicator 192.168.1.3/24 md5 ``` Running `chef-backend-ctl reconfigure` on all the backends will allow that frontend to complete its connection. Important The `postgresql.md5_auth_cidr_addresses` subnet settings must be identical for all members of the backend cluster. In the case where the subnet settings of the frontend cluster are different from the subnet settings of the backend cluster, the values set on the members of the backend cluster should contain the subnet of the frontend cluster. This guarantees that all members of a cluster can still communicate with each other after a cluster change of state occurs. For example, if the frontend subnet setting is “192.168.1.0/24” and the backend subnet setting is “192.168.2.0/24”, then the `postgresql.md5_auth_cidr_addresses` subnet settings must be `postgresql.md5_auth_cidr_addresses = ["samehost", "samenet", "192.168.1.0/24", 192.168.2.0/24]` Cluster Security Considerations ------------------------------- A backend cluster is expected to run in a trusted environment. This means that untrusted users that communicate with and/or eavesdrop on services provided by the backend cluster can potentially view sensitive data. ### Communication Between Nodes PostgreSQL communication between nodes in the backend cluster is encrypted, and uses password authentication. All other communication in the backend cluster is unauthenticated and happens in the clear (without encryption). ### Communication Between Frontend Group & Backend Cluster PostgreSQL communication from nodes in the frontend group to the leader of the backend cluster uses password authentication, but communication happens in the clear (without encryption). Elasticsearch communication is unauthenticated and happens in the clear (without encryption). ### Securing Communication Because most of the peer communication between nodes in the backend cluster happens in the clear, the backend cluster is vulnerable to passive monitoring of network traffic between nodes. To help prevent an active attacker from intercepting or changing cluster data, Chef recommends using iptables or an equivalent network ACL tool to restrict access to PostgreSQL, Elasticsearch and etcd to only hosts that need access. By service role, access requirements are as follows: | Service | Access Requirements | | --- | --- | | PostgreSQL | All backend cluster members and all Chef Infra Server frontend group nodes. | | Elasticsearch | All backend cluster members and all Chef Infra Server frontend group nodes. | | etcd | All backend cluster members and all Chef Infra Server frontend group nodes. | ### Services and Secrets Communication with PostgreSQL requires password authentication. The backend cluster generates PostgreSQL users and passwords during the initial cluster-create. These passwords are present in the following files on disk: | Secret | Owner | Group | Mode | | --- | --- | --- | --- | | `/etc/chef-backend/secrets.json` | `root` | `chef_pgsql` | `0640` | | `/var/opt/chef-backend/leaderl/data/sys.config` | `chef_pgsql` | `chef_pgsql` | `0600` | | `/var/opt/chef-backend/PostgreSQL/9.5/recovery.conf` | `chef_pgsql` | `chef_pgsql` | `0600` | The following services run on each node in the backend cluster. The user account under which the service runs as listed the second column: | Service | Process Owner | | --- | --- | | `postgresql` | `chef_pgsql` | | `elasticsearch` | `chef-backend` | | `etcd` | `chef-backend` | | `leaderl` | `chef_pgsql` | | `epmd` | `chef_pgsql` (or first user launching an erlang process) | #### Chef Infra Server frontend The `chef-backend-ctl gen-server-config` command, which can be run as root from any node in the backend cluster, will automatically generate a configuration file containing the superuser database access credentials for the backend cluster PostgreSQL instance. ### Software Versions The backend HA cluster uses the Chef installer to package all of the software necessary to run the services included in the backend cluster. For a full list of the software packages included (and their versions), see the file located at `/opt/chef-backend/version-manifest.json`. Do not attempt to upgrade individual components of the Chef package. Due to the way Chef packages are built, modifying any of the individual components in the package will lead to cluster instability. If the latest version of the backend cluster is providing an out-of-date package, please bring it to the attention of Chef by filling out a ticket with [<EMAIL>](mailto:<EMAIL>@chef.io). chef-backend.rb Options ----------------------- Run `chef-backend-ctl gen-sample-backend-config` to generate the `chef-backend.rb` file. This will control most of the various feature and configuration flags going into a Chef HA backend node. A number of these options control the reliability, stability, and uptime of the backend PostgreSQL databases, the Elasticsearch index, and the leader election system. Please refrain from changing them unless you have been advised to do so. The following settings are the only settings you should modify without guidance: `fqdn` Host name of this node. `hide_sensitive` Set to `false` if you wish to print deltas of sensitive files and templates during `chef-backend-ctl reconfigure` runs. Default value: `true`. `ip_version` Set to either `'ipv4'` or `'ipv6'`. Default value: `'ipv4'`. `publish_address` Externally resolvable IP address of this back-end node. For information on all the available settings, see the [chef-backend.rb documentation](../config_rb_backend/index). chef-backend-ctl ---------------- The Chef Infra Server backend HA cluster includes a command-line utility named chef-backend-ctl. This command-line tool is used to manage the Chef Infra Server backend HA cluster, start and stop individual services, and tail Chef Infra Server log files. For more information, see the [chef-backend-ctl documentation](../ctl_chef_backend/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/install_server_ha/chef-server.rb Settings ======================= Version: Chef Infra Server 14 Chef Infra Server 13.2 [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/v14/config_rb_server.md) The `/etc/opscode/chef-server.rb` file contains all of the non-default configuration settings used by the Chef Infra Server. The default settings are built into the Chef Infra Server configuration and should only be added to the `chef-server.rb` file to apply non-default values. These configuration settings are processed when the `chef-server-ctl reconfigure` command is run. The `chef-server.rb` file is a Ruby file, which means that conditional statements can be used within it. Use Conditions -------------- Use a `case` statement to apply different values based on whether the setting exists on the front-end or back-end servers. Add code to the server configuration file similar to the following: ``` role_name = ChefServer['servers'][node['fqdn']]['role'] case role_name when 'backend' # backend-specific configuration here when 'frontend' # frontend-specific configuration here end ``` Recommended Settings -------------------- The following settings are typically added to the server configuration file (no equal sign is necessary to set the value): `api_fqdn` The FQDN for the Chef Infra Server. This setting is not in the server configuration file by default. When added, its value should be equal to the FQDN for the service URI used by the Chef Infra Server. For example: `api_fqdn "chef.example.com"`. `bootstrap` Default value: `true`. `ip_version` Use to set the IP version: `"ipv4"` or `"ipv6"`. When set to `"ipv6"`, the API listens on IPv6 and front end and back end services communicate via IPv6 when a high availability configuration is used. When configuring for IPv6 in a high availability configuration, be sure to set the netmask on the IPv6 `backend_vip` attribute. Default value: `"ipv4"`. `notification_email` Default value: `<EMAIL>`. ### NGINX SSL Protocols The following settings are often modified from the default as part of the tuning effort for the **nginx** service and to configure the Chef Infra Server to use SSL certificates: `nginx['ssl_certificate']` The SSL certificate used to verify communication over HTTPS. Default value: `nil`. `nginx['ssl_certificate_key']` The certificate key used for SSL communication. Default value: `nil`. `nginx['ssl_ciphers']` The list of supported cipher suites that are used to establish a secure connection. To favor AES256 with ECDHE forward security, drop the `RC4-SHA:RC4-MD5:RC4:RSA` prefix. For example: ``` nginx['ssl_ciphers'] = "HIGH:MEDIUM:!LOW:!kEDH: \ !aNULL:!ADH:!eNULL:!EXP: \ !SSLv2:!SEED:!CAMELLIA: \ !PSK" ``` `nginx['ssl_protocols']` The SSL protocol versions that are enabled for the Chef Infra Server API. Starting with Chef Infra Server 14.3, this value defaults to `'TLSv1.2'` for enhanced security. Previous releases defaulted to `'TLSv1 TLSv1.1 TLSv1.2'`, which allowed for less secure SSL connections. TLS 1.2 is supported on Chef Infra Client 10.16.4 and later on Linux, Unix, and macOS, and on Chef Infra Client 12.8 and later on Windows. If it is necessary to support these older end-of-life Chef Infra Client releases, set this value to `'TLSv1.1 TLSv1.2'`. ``` nginx['ssl_protocols'] = 'TLSv1.2' ``` Note See <https://www.openssl.org/docs/man1.0.2/man1/ciphers.html> for more information about the values used with the `nginx['ssl_ciphers']` and `nginx['ssl_protocols']` settings. For example, after copying the SSL certificate files to the Chef Infra Server, update the `nginx['ssl_certificate']` and `nginx['ssl_certificate_key']` settings to specify the paths to those files, and then (optionally) update the `nginx['ssl_ciphers']` and `nginx['ssl_protocols']` settings to reflect the desired level of hardness for the Chef Infra Server: ``` nginx['ssl_certificate'] = '/etc/pki/tls/private/name.of.pem' nginx['ssl_certificate_key'] = '/etc/pki/tls/private/name.of.key' nginx['ssl_ciphers'] = 'HIGH:MEDIUM:!LOW:!kEDH:!aNULL:!ADH:!eNULL:!EXP:!SSLv2:!SEED:!CAMELLIA:!PSK' nginx['ssl_protocols'] = 'TLSv1.2' ``` Optional Settings ----------------- The following settings are often used for performance tuning of the Chef Infra Server in larger installations. Note When changes are made to the chef-server.rb file the Chef Infra Server must be reconfigured by running the following command: ``` chef-server-ctl reconfigure ``` Note Review the full list of [optional settings](../config_rb_server_optional_settings/index) that can be added to the chef-server.rb file. Many of these optional settings should not be added without first consulting with Chef support. ### bookshelf The following setting is often modified from the default as part of the tuning effort for the **bookshelf** service: `bookshelf['vip']` The virtual IP address. Default value: `node['fqdn']`. Warning To [configure the server for external cookbook storage](../index#aws-settings), updates are made to settings for both the **bookshelf** and **opscode-erchef** services. ### opscode-account The following setting is often modified from the default as part of the tuning effort for the **opscode-account** service: `opscode_account['worker_processes']` The number of allowed worker processes. This value should be increased if requests made to the **opscode-account** service are timing out, but only if the front-end machines have available CPU and RAM. Default value: `4`. ### opscode-erchef The following settings are often modified from the default as part of the tuning effort for the **opscode-erchef** service: `opscode_erchef['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. If failures indicate that the **opscode-erchef** service ran out of connections, try increasing the `postgresql['max_connections']` setting. If failures persist, then increase this value (in small increments) and also increase the value for `postgresql['max_connections']`. Default value: `20`. `opscode_erchef['s3_url_ttl']` The amount of time (in seconds) before connections to the server expire. If Chef Infra Client runs are timing out, increase this setting to `3600`, and then adjust again if necessary. Default value: `900`. `opscode_erchef['strict_search_result_acls']` Use to specify that search results only return objects to which an actor (user, client, etc.) has read access, as determined by ACL settings. This affects all searches. When `true`, the performance of the Chef management console may increase because it enables the Chef management console to skip redundant ACL checks. To ensure the Chef management console is configured properly, after this setting has been applied with a `chef-server-ctl reconfigure` run `chef-manage-ctl reconfigure` to ensure the Chef management console also picks up the setting. Default value: `false`. Warning When `true`, `opscode_erchef['strict_search_result_acls']` affects all search results and any actor (user, client, etc.) that does not have read access to a search result will not be able to view it. For example, this could affect search results returned during a Chef Infra Client runs if a Chef Infra Client does not have permission to read the information. #### Data Collector The following settings are often modified from the default as part of the tuning effort for the **data_collector** **opscode-erchef** application: `data_collector['http_max_count']` The maximum worker count for the HTTP connection pool that is used by the data collector. If failures indicate that **opscode-erchef** application has run out of HTTP connections for the **data_collector** then increase this value. Default value: 100. ### postgresql The following setting is often modified from the default as part of the tuning effort for the **postgresql** service: `postgresql['max_connections']` The maximum number of allowed concurrent connections. This value should only be tuned when the `opscode_erchef['db_pool_size']` value used by the **opscode-erchef** service is modified. Default value: `350`. If there are more than two front end machines in a cluster, the `postgresql['max_connections']` setting should be increased. The increased value depends on the number of machines in the front end, but also the number of services that are running on each of these machines. * Each front end machine always runs the **oc_bifrost** and **opscode-erchef** services. * The Reporting add-on adds the **reporting** service. Each of these services requires 25 connections, above the default value. Use the following formula to help determine what the increased value should be: ``` new_value = current_value + [ (# of front end machines - 2) * (25 * # of services) ] ``` For example, if the current value is 350, there are four front end machines, and all add-ons are installed, then the formula looks like: ``` 550 = 350 + [(4 - 2) * (25 * 4)] ``` `postgresql['sslmode']` SSL encryption mode between the Chef Infra Server and PostgreSQL. Valid settings are `'disable'` and `'require'`. Default value: `'disable'`. **Note:** You are viewing documentation for an older version of Chef Infra Server. [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/v13_2/config_rb_server.md) The `/etc/opscode/chef-server.rb` file contains all of the non-default configuration settings used by the Chef Infra Server. The default settings are built into the Chef Infra Server configuration and should only be added to the `chef-server.rb` file to apply non-default values. These configuration settings are processed when the `chef-server-ctl reconfigure` command is run. The `chef-server.rb` file is a Ruby file, which means that conditional statements can be used within it. Use Conditions -------------- Use a `case` statement to apply different values based on whether the setting exists on the front-end or back-end servers. Add code to the server configuration file similar to the following: ``` role_name = ChefServer['servers'][node['fqdn']]['role'] case role_name when 'backend' # backend-specific configuration here when 'frontend' # frontend-specific configuration here end ``` Recommended Settings -------------------- The following settings are typically added to the server configuration file (no equal sign is necessary to set the value): `api_fqdn` The FQDN for the Chef Infra Server. This setting is not in the server configuration file by default. When added, its value should be equal to the FQDN for the service URI used by the Chef Infra Server. For example: `api_fqdn "chef.example.com"`. `bootstrap` Default value: `true`. `ip_version` Use to set the IP version: `"ipv4"` or `"ipv6"`. When set to `"ipv6"`, the API listens on IPv6 and front end and back end services communicate via IPv6 when a high availability configuration is used. When configuring for IPv6 in a high availability configuration, be sure to set the netmask on the IPv6 `backend_vip` attribute. Default value: `"ipv4"`. `notification_email` Default value: `<EMAIL>`. ### NGINX SSL Protocols The following settings are often modified from the default as part of the tuning effort for the **nginx** service and to configure the Chef Infra Server to use SSL certificates: `nginx['ssl_certificate']` The SSL certificate used to verify communication over HTTPS. Default value: `nil`. `nginx['ssl_certificate_key']` The certificate key used for SSL communication. Default value: `nil`. `nginx['ssl_ciphers']` The list of supported cipher suites that are used to establish a secure connection. To favor AES256 with ECDHE forward security, drop the `RC4-SHA:RC4-MD5:RC4:RSA` prefix. For example: ``` nginx['ssl_ciphers'] = "HIGH:MEDIUM:!LOW:!kEDH: \ !aNULL:!ADH:!eNULL:!EXP: \ !SSLv2:!SEED:!CAMELLIA: \ !PSK" ``` `nginx['ssl_protocols']` The SSL protocol versions that are enabled for the Chef Infra Server API. For enhanced security set this value to `'TLSv1.2'`. TLS 1.2 is supported on Chef Infra Client 10.16.4 and later on Linux, Unix, and macOS, and on Chef Infra Client 12.8 and later on Windows. If it is necessary to support these older end-of-life Chef Infra Client releases, set this value to `'TLSv1.1 TLSv1.2'`. ``` nginx['ssl_protocols'] = 'TLSv1.2' ``` Note See <https://www.openssl.org/docs/man1.0.2/man1/ciphers.html> for more information about the values used with the `nginx['ssl_ciphers']` and `nginx['ssl_protocols']` settings. For example, after copying the SSL certificate files to the Chef Infra Server, update the `nginx['ssl_certificate']` and `nginx['ssl_certificate_key']` settings to specify the paths to those files, and then (optionally) update the `nginx['ssl_ciphers']` and `nginx['ssl_protocols']` settings to reflect the desired level of hardness for the Chef Infra Server: ``` nginx['ssl_certificate'] = '/etc/pki/tls/private/name.of.pem' nginx['ssl_certificate_key'] = '/etc/pki/tls/private/name.of.key' nginx['ssl_ciphers'] = 'HIGH:MEDIUM:!LOW:!kEDH:!aNULL:!ADH:!eNULL:!EXP:!SSLv2:!SEED:!CAMELLIA:!PSK' nginx['ssl_protocols'] = 'TLSv1.2' ``` Optional Settings ----------------- The following settings are often used for performance tuning of the Chef Infra Server in larger installations. Note When changes are made to the chef-server.rb file the Chef Infra Server must be reconfigured by running the following command: ``` chef-server-ctl reconfigure ``` Note Review the full list of [optional settings](../config_rb_server_optional_settings/index) that can be added to the chef-server.rb file. Many of these optional settings should not be added without first consulting with Chef support. ### bookshelf The following setting is often modified from the default as part of the tuning effort for the **bookshelf** service: `bookshelf['vip']` The virtual IP address. Default value: `node['fqdn']`. Warning To [configure the server for external cookbook storage](../index#aws-settings), updates are made to settings for both the **bookshelf** and **opscode-erchef** services. ### opscode-account The following setting is often modified from the default as part of the tuning effort for the **opscode-account** service: `opscode_account['worker_processes']` The number of allowed worker processes. This value should be increased if requests made to the **opscode-account** service are timing out, but only if the front-end machines have available CPU and RAM. Default value: `4`. ### opscode-erchef The following settings are often modified from the default as part of the tuning effort for the **opscode-erchef** service: `opscode_erchef['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. If failures indicate that the **opscode-erchef** service ran out of connections, try increasing the `postgresql['max_connections']` setting. If failures persist, then increase this value (in small increments) and also increase the value for `postgresql['max_connections']`. Default value: `20`. `opscode_erchef['s3_url_ttl']` The amount of time (in seconds) before connections to the server expire. If Chef Infra Client runs are timing out, increase this setting to `3600`, and then adjust again if necessary. Default value: `900`. `opscode_erchef['strict_search_result_acls']` Use to specify that search results only return objects to which an actor (user, client, etc.) has read access, as determined by ACL settings. This affects all searches. When `true`, the performance of the Chef management console may increase because it enables the Chef management console to skip redundant ACL checks. To ensure the Chef management console is configured properly, after this setting has been applied with a `chef-server-ctl reconfigure` run `chef-manage-ctl reconfigure` to ensure the Chef management console also picks up the setting. Default value: `false`. Warning When `true`, `opscode_erchef['strict_search_result_acls']` affects all search results and any actor (user, client, etc.) that does not have read access to a search result will not be able to view it. For example, this could affect search results returned during a Chef Infra Client runs if a Chef Infra Client does not have permission to read the information. #### Data Collector The following settings are often modified from the default as part of the tuning effort for the **data_collector** **opscode-erchef** application: `data_collector['http_max_count']` The maximum worker count for the HTTP connection pool that is used by the data collector. If failures indicate that **opscode-erchef** application has run out of HTTP connections for the **data_collector** then increase this value. Default value: 100. ### opscode-expander The following setting is often modified from the default as part of the tuning effort for the **opscode-expander** service: `opscode_expander['nodes']` The number of allowed worker processes. The **opscode-expander** service runs on the back-end and feeds data to the **opscode-solr** service, which creates and maintains search data used by the Chef Infra Server. Additional memory may be required by these worker processes depending on the frequency and volume of Chef Infra Client runs across the organization, but only if the back-end machines have available CPU and RAM. Default value: `2`. ### opscode-solr4 The following sections describe ways of tuning the **opscode-solr4** service to improve performance around large node sizes, available memory, and update frequencies. #### Available Memory Use the following configuration setting to help ensure that Apache Solr does not run out of memory: `opscode_solr4['heap_size']` The amount of memory (in MBs) available to Apache Solr. If there is not enough memory available, search queries made by nodes to Apache Solr may fail. The amount of memory that must be available also depends on the number of nodes in the organization, the frequency of search queries, and other characteristics that are unique to each organization. In general, as the number of nodes increases, so does the amount of memory. If Apache Solr is running out of memory, the `/var/log/opscode/opscode-solr4/current` log file will contain a message similar to: ``` SEVERE: java.lang.OutOfMemoryError: Java heap space ``` The default value for `opscode_solr4['heap_size']` should work for many organizations, especially those with fewer than 25 nodes. For organizations with more than 25 nodes, set this value to 25% of system memory or `1024`, whichever is smaller. For very large configurations, increase this value to 25% of system memory or `4096`, whichever is smaller. This value should not exceed `8192`. #### Large Node Sizes The maximum field length setting for Apache Solr should be greater than any expected node object file sizes in order for them to be successfully added to the search index. If a node object file is greater than the maximum field length, the node object will be indexed up to the maximum, but the part of the file past that limit will not be indexed. If this occurs, it will seem as if nodes disappear from the search index. To ensure that large node file sizes are indexed properly, verify the following configuration settings: `nginx['client_max_body_size']` The maximum accepted body size for a client request, as indicated by the `Content-Length` request header. When the maximum accepted body size is greater than this value, a `413 Request Entity Too Large` error is returned. Default value: `250m`. and `opscode_erchef['max_request_size']` When the request body size is greater than this value, a 413 Request Entity Too Large error is returned. Default value: `2000000`. to ensure that those settings are not part of the reasons for incomplete indexing, and then update the following setting so that its value is greater than the expected node file sizes: `opscode_solr4['max_field_length']` The maximum field length (in number of tokens/terms). If a field length exceeds this value, Apache Solr may not be able to complete building the index. Default value: `100000` (increased from the Apache Solr default value of `10000`). Use the `wc` command to get the byte count of a large node object file. For example: ``` wc -c NODE_NAME.json ``` and then ensure there is a buffer beyond that value. For example, verify the size of the largest node object file: ``` wc -c nodebsp2016.json ``` which returns `154516`. Update the `opscode_solr4['max_field_length']` setting to have a value greater than the returned value. For example: `180000`. If you don’t have a node object file available then you can get an approximate size of the node data by running the following command on a node. ``` ohai | wc -c ``` #### Update Frequency At the end of every Chef Infra Client run, the node object is saved to the Chef Infra Server. From the Chef Infra Server, each node object is then added to the `SOLR` search index. This process is asynchronous. By default, node objects are committed to the search index every 60 seconds or per 1000 node objects, whichever occurs first. When data is committed to the Apache Solr index, all incoming updates are blocked. If the duration between updates is too short, it is possible for the rate at which updates are asked to occur to be faster than the rate at which objects can be actually committed. Use the following configuration setting to improve the indexing performance of node objects: `opscode_solr4['commit_interval']` The frequency (in seconds) at which node objects are added to the Apache Solr search index. Default value: `60000` (every 60 seconds). `opscode_solr4['max_commit_docs']` The frequency (in documents) at which node objects are added to the Apache Solr search index. Default value: `1000` (every 1000 documents). ### postgresql The following setting is often modified from the default as part of the tuning effort for the **postgresql** service: `postgresql['max_connections']` The maximum number of allowed concurrent connections. This value should only be tuned when the `opscode_erchef['db_pool_size']` value used by the **opscode-erchef** service is modified. Default value: `350`. If there are more than two front end machines in a cluster, the `postgresql['max_connections']` setting should be increased. The increased value depends on the number of machines in the front end, but also the number of services that are running on each of these machines. * Each front end machine always runs the **oc_bifrost** and **opscode-erchef** services. * The Reporting add-on adds the **reporting** service. Each of these services requires 25 connections, above the default value. Use the following formula to help determine what the increased value should be: ``` new_value = current_value + [ (# of front end machines - 2) * (25 * # of services) ] ``` For example, if the current value is 350, there are four front end machines, and all add-ons are installed, then the formula looks like: ``` 550 = 350 + [(4 - 2) * (25 * 4)] ``` `postgresql['sslmode']` SSL encryption mode between the Chef Infra Server and PostgreSQL. Valid settings are `'disable'` and `'require'`. Default value: `'disable'`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/config_rb_server/Tiered Installation =================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/install_server_tiered.md) This topic describes how to set up the Chef Infra Server with a single back end and multiple load-balanced frontend servers. ![image] Prerequisites ------------- Before installing the Chef Infra Server software, perform the following steps: * The backend server must be accessible from each frontend server. A virtual IP address is created and managed by the Chef Infra Server, but will also need to be added to the DNS so that all machines in the tiered configuration may access it. * Persistent data on the backend Chef Infra Server is primarily composed of cookbook files and directories. Separate disks should be dedicated entirely to storing this data prior to installing the Chef Infra Server. * Load-balancing should be used with frontend servers, along with a DNS entry for the virtual IP address used for load balancing. This virtual IP address is added to the chef-server.rb file as the `api_fqdn`. * All required ports must be open. See the Firewalls section (below) for the list of ports. All connections to and from the Chef Infra Server are accomplished via TCP. Refer to the operating system’s manual or your systems administrators for instructions on how to configure to ports, if necessary. * The hostname for the Chef Infra Server must be an FQDN, including the domain suffix, and must be resolvable by the backend and frontend servers. See [Hostnames, FQDNs](../install_server_pre/index#hostnames) for more information. * `chef-server-ctl reconfigure` will not bind the `backend_vip` to the backend server. The easiest thing to do is just define `backend_vip` as the already configured main IP address of the backend system. If you need to use an additional address, it will need to be configured and bound on the system before `chef-server-ctl reconfigure` is run. Basic Hardware Requirements --------------------------- For a tiered deployment, your backend server should support the following hardware requirements: * 64-bit architecture * 8 total cores (physical or virtual) * 16GB RAM * Fast, redundant storage (SSD/RAID-based solution) + 50 GB/backend server (SSD if on premises, Premium Storage in Microsoft Azure, EBS-Optimized GP2 in AWS) * 1 GigE NIC interface * A back-end server; all other systems will be front-end servers. Disk Configuration ------------------ Persistent data on the backend server of the Chef Infra Server is primarily composed of cookbook files and directories. Separate disks should be dedicated entirely to storing this data prior to installing the Chef Infra Server. These disks should be part of a SSD or hardware RAID-based solution that ensure redundancy and high IOPS. This configuration guide assumes that: * ~50GB of raw, unpartitioned disk space is available. Disk space should scale up with the number of nodes that the backend server is managing. A good rule to follow is to allocate 2 MB per node. * The disk space presents as a single device. For example: `/dev/sdb`. * The storage is added to a volume group named `opscode` and is presented to the Chef Infra Server by mounting on `/var/opt/opscode` before a reconfiguration The following commands properly set up disk configuration on the backend server: ``` pvcreate /dev/sdb ``` and: ``` vgcreate opscode /dev/sdb ``` and: ``` lvcreate -l 80%VG -n tiered opscode ``` ### Mount Storage Device To build and mount the storage device on the backend server, do the following: 1. Create the file system. For example, an `ext4` type named `tiered`: ``` mkfs.ext4 /dev/opscode/tiered ``` then: ``` mkdir -p /var/opt/opscode ``` and then: ``` mount /dev/opscode/tiered /var/opt/opscode ``` Backend ------- Use the following steps to set up the backend Chef Infra Server: 1. Download the packages from <https://downloads.chef.io/chef-server/>. For Red Hat and CentOS 6: ``` rpm -Uvh /tmp/chef-server-core-<version>.rpm ``` For Ubuntu: ``` dpkg -i /tmp/chef-server-core-<version>.deb ``` After a few minutes, the Chef Infra Server will be installed. 2. Create a file named chef-server.rb that is located in the `/etc/opscode/` directory. See the chef-server.rb section below for an example of the settings and values that are required. chef-server.rb -------------- The chef-server.rb file that is located in the `/etc/opscode/` directory describes the topology of the tiered configuration. On the backend server, create a file named chef-server.rb and save it in the `/etc/opscode/` directory. Add the following settings to the chef-server.rb file: 1. Define the topology type: ``` topology "tier" ``` 2. Define the backend server: ``` server "FQDN", :ipaddress => "IP_ADDRESS", :role => "backend", :bootstrap => true ``` Replace `FQDN` with the FQDN of the server and `IP_ADDRESS` with the IP address of the server. The role is a backend server is `"backend"`. 3. Define the backend virtual IP address: ``` backend_vip "FQDN", :ipaddress => "IP_ADDRESS", :device => "eth0" ``` Replace `FQDN` with the FQDN of the server. Replace `IP_ADDRESS` with the virtual IP address of the server. The `:device` parameter should be the ethernet interface to which the virtual IP address will bind. This is typically the public interface of the server. In a typical tiered install, the config here could also be just the main FQDN and IP address that are already configured for the backend. Running `chef-server-ctl reconfigure` will not bind the `backend_vip` address to an interface, this must be done on startup of the machine. 4. Define each frontend server: ``` server "FQDN", :ipaddress => "IP_ADDRESS", :role => "frontend" ``` Replace `FQDN` with the FQDN of the frontend server. Replace `IP_ADDRESS` with the IP address of the frontend server. Set `:role` to `"frontend"`. Add separate entry in the chef-server.rb file for each frontend server. 5. Define the API FQDN: ``` api_fqdn "FQDN" ``` Replace `FQDN` with the FQDN of the load balanced virtual IP address, which should be equal to the FQDN for the service URI that is used by the Chef Infra Server. 6. Reconfigure the Chef Infra Server and the Chef management console (standalone and frontend group members of a High Availabilty installation): ``` chef-server-ctl reconfigure ``` Frontend -------- For each frontend server, use the following steps to set up the Chef Infra Server: 1. Install the Chef Infra Server package. For Red Hat and CentOS 6: ``` rpm -Uvh /tmp/chef-server-core-<version>.rpm ``` For Ubuntu: ``` dpkg -i /tmp/chef-server-core-<version>.deb ``` After a few minutes, the Chef Infra Server will be installed. 2. Create the `/etc/opscode/` directory, and then copy the entire contents of the `/etc/opscode` directory from the primary backend server, including all certificates and the chef-server.rb file. 3. Reconfigure the Chef Infra Server and the Chef management console (standalone and frontend group members of a High Availabilty installation): ``` chef-server-ctl reconfigure ``` 4. Start the Chef Infra Server: ``` chef-server-ctl start ``` On a single frontend server, create an administrator and an organization: 1. Run the following command to create an administrator: ``` sudo chef-server-ctl user-create USER_NAME FIRST_NAME LAST_NAME EMAIL 'PASSWORD' --filename FILE_NAME ``` An RSA private key is generated automatically. This is the user’s private key and should be saved to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. For example: ``` sudo chef-server-ctl user-create janedoe <NAME> <EMAIL> 'abc123' --filename /path/to/janedoe.pem ``` 2. Run the following command to create an organization: ``` sudo chef-server-ctl org-create short_name 'full_organization_name' --association_user user_name --filename ORGANIZATION-validator.pem ``` For example: ``` sudo chef-server-ctl org-create 4thcafe 'Fourth Cafe, Inc.' --association_user janedoe --filename /path/to/4thcafe-validator.pem ``` The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `4thcafe`. The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `'<NAME>.'`. The `--association_user` option will associate the `user_name` with the `admins` security group on the Chef Infra Server. An RSA private key is generated automatically. This is the chef-validator key and should be saved to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. Enable Features --------------- Enable additional features of the Chef Infra Server! The packages may be downloaded directly as part of the installation process or they may be first downloaded to a local directory, and then installed. **Use Downloads** The `install` subcommand downloads packages from <https://packages.chef.io/> by default. For systems that are not behind a firewall (and have connectivity to <https://packages.chef.io/>), the Chef management console package can be installed as described below: Chef Manage Use Chef management console to manage data bags, attributes, run-lists, roles, environments, and cookbooks from a web user interface. On each front end server in the Chef Infra Server configuration, run: ``` chef-server-ctl install chef-manage ``` then: ``` chef-server-ctl reconfigure ``` and then: ``` chef-manage-ctl reconfigure ``` To accept the [Chef MLSA](../../chef_license/index): ``` sudo chef-manage-ctl reconfigure --accept-license ``` This updates the Chef Infra Server and creates the `/etc/opscode-manage/secrets.rb` file. When running the Chef management console 1.11 (or higher), copy the `secrets.rb` file in the `/etc/opscode-manage` directory on one of the frontend servers to the same directory on each of the other frontend servers, and then rerun `chef-manage-ctl reconfigure` so the copied `/etc/opscode-manage/secrets.rb` file gets used correctly. **Use Local Packages** Use the `install` subcommand with the `--path` option to install the Chef Manage (`chef-manage`) add-on for Chef Infra Server. ``` sudo chef-server-ctl install PACKAGE_NAME --path /path/to/package/directory ``` For example: ``` sudo chef-server-ctl install chef-manage --path /root/packages ``` The `chef-server-ctl` command will install the first `chef-manage` package found in the `/root/packages` directory. Reference --------- The following sections show an example chef-server.rb file and a list of the ports that are required by the Chef Infra Server. ### chef-server.rb A completed chef-server.rb configuration file for a four server tiered Chef Infra Server configuration, consisting of: | FQDN | Real IP Address | Role | | --- | --- | --- | | be1.example.com | 192.0.2.0 | backend | | fe1.example.com | 192.168.4.2 | frontend | | fe2.example.com | 192.168.4.3 | frontend | | fe3.example.com | 192.168.4.4 | frontend | | chef.example.com | | load balanced frontend VIP | | be.example.com | 192.168.4.7 | load balanced backend VIP | Looks like this: ``` topology "tier" server "be1.example.com", :ipaddress => "192.0.2.0", :role => "backend", :bootstrap => true backend_vip "be.example.com", :ipaddress => "192.168.4.7", :device => "eth0" server "fe1.example.com", :ipaddress => "192.168.4.2", :role => "frontend" server "fe2.example.com", :ipaddress => "192.168.4.3", :role => "frontend" server "fe3.example.com", :ipaddress => "192.168.4.4", :role => "frontend" api_fqdn "chef.example.com" ``` ### Firewalls All of the ports used by the Chef Infra Server are TCP ports. Refer to the operating system’s manual or site systems administrators for instructions on how to enable changes to ports, if necessary. All services must be listening on the appropriate ports. Most monitoring systems provide a means of testing whether a given port is accepting connections and service-specific tools may also be available. In addition, the generic system tool Telnet can also be used to initiate the connection: ``` telnet HOST_NAME PORT ``` A single loopback interface should be configured using the `127.0.0.1` address. This ensures that all of the services are available to the Chef Infra Server, in the event that the Chef Infra Server attempts to contact itself from within a front or back end machine. All ports should be accessible through the loopback interface of their respective hosts. #### Backend For back-end servers in a tiered Chef Infra Server installation, ensure that ports marked as external (marked as `yes` in the **External** column) are open and accessible via any firewalls that are in use: | Port | Service Name, Description | External | | --- | --- | --- | | 80, 443, 9683 | **nginx** The **nginx** service is used to manage traffic to the Chef Infra Server, including virtual hosts for internal and external API request/response routing, external add-on request routing, and routing between front- and back-end components. Note Port 9683 is used to internally load balance the **oc_bifrost** service. | yes | | 9463 | **oc_bifrost** The **oc_bifrost** service ensures that every request to view or manage objects stored on the Chef Infra Server is authorized. | | | 9200 | **elasticsearch** The **elasticsearch** service is used to create the search indexes used for searching objects like nodes, data bags, and cookbooks. (This service ensures timely search results via the Chef Infra Server API; data that is used by the Chef platform is stored in PostgreSQL.) | | | 5432 | **postgresql** The **postgresql** service is used to store node, object, and user data. | | | 16379 | **redis_lb** Key-value store used in conjunction with Nginx to route requests and populate request data used by the Chef Infra Server. | | | 4321 | **bookshelf** The **bookshelf** service is an Amazon Simple Storage Service (S3)-compatible service that is used to store cookbooks, including all of the files—recipes, templates, and so on—that are associated with each cookbook. | | | 8000 | **opscode-erchef** The **opscode-erchef** service is an Erlang-based service that is used to handle Chef Infra Server API requests to the following areas within the Chef Infra Server:* Cookbooks * Data bags * Environments * Nodes * Roles * Sandboxes * Search | | #### Frontend For front-end servers, ensure that ports marked as external (marked as `yes` in the **External** column) are open and accessible via any firewalls that are in use: | Port | Service Name, Description | External | | --- | --- | --- | | 80, 443, 9683 | **nginx** The **nginx** service is used to manage traffic to the Chef Infra Server, including virtual hosts for internal and external API request/response routing, external add-on request routing, and routing between front- and back-end components. Note Port 9683 is used to internally load balance the **oc_bifrost** service. | yes | | 9463 | **oc_bifrost** The **oc_bifrost** service ensures that every request to view or manage objects stored on the Chef Infra Server is authorized. | | | 9090 | **oc-id** The **oc-id** service enables OAuth 2.0 authentication to the Chef Infra Server by external applications, including Chef Supermarket. OAuth 2.0 uses token-based authentication, where external applications use tokens that are issued by the **oc-id** provider. No special credentials—`webui_priv.pem` or privileged keys—are stored on the external application. | | | 8000 | **opscode-erchef** The **opscode-erchef** service is an Erlang-based service that is used to handle Chef Infra Server API requests to the following areas within the Chef Infra Server:* Cookbooks * Data bags * Environments * Nodes * Roles * Sandboxes * Search | | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/install_server_tiered/chef-backend.rb Settings ======================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/config_rb_backend.md) Warning Chef Backend is [deprecated](../../versions/index#deprecated-products-and-versions) and no longer under active development. Contact your Chef account representative for information about migrating to Chef Automate HA. This document is no longer maintained. chef-backend.rb Options ----------------------- Run `chef-backend-ctl gen-sample-backend-config` to generate the `chef-backend.rb` file. This will control most of the various feature and configuration flags going into a Chef HA backend node. A number of these options control the reliability, stability, and uptime of the backend PostgreSQL databases, the Elasticsearch index, and the leader election system. Please refrain from changing them unless you have been advised to do so. The following settings are the only settings you should modify without guidance: `fqdn` Host name of this node. `hide_sensitive` Set to `false` if you wish to print deltas of sensitive files and templates during `chef-backend-ctl reconfigure` runs. Default value: `true`. `ip_version` Set to either `'ipv4'` or `'ipv6'`. Default value: `'ipv4'`. `publish_address` Externally resolvable IP address of this back-end node. ### Common ‘Runit’ Flags for Any Backend Service See <https://github.com/chef-cookbooks/runit> for details. Many of the flags are repeated across the various backend services, but they are only documented once at the top here. The same defaults are used unless specified below. `postgresql.enable` Sets up and runs the postgresql service. Default value: `true`. `postgresql.environment` A hash of environment variables with their values as content used in the service’s env directory. `postgresql.log_directory` The directory where the `svlogd` log service will run. Default value: `'/var/log/chef-backend/postgresql/<version>'`. `postgresql.log_rotation.file_maxbytes` The maximum size a log file can grow to before it is automatically rotated. Default value: `104857600` (100MB). `postgresql.log_rotation.num_to_keep` The maximum number of log files that will be retained after rotation. Default value: `10`. `etcd.enable` Sets up and runs the etcd service. Default value: `true`. `etcd.log_directory` The directory where the `svlogd` log service will run. Default value: `'/var/log/chef-backend/etcd'`. `etcd.log_rotation.file_maxbytes` The maximum size a log file can grow to before it is automatically rotated. Default value: `104857600` (100MB). `etcd.log_rotation.num_to_keep` The maximum number of log files that will be retained after rotation. Default value: `10`. `elasticsearch.enable` Sets up and runs the elasticsearch service. Default value: `true`. `elasticsearch.log_directory` The directory where the `svlogd` log service will run. Also affects `path.logs` in the Elasticsearch configuration YAML. Default value: `'/var/log/chef-backend/elasticsearch'`. `elasticsearch.log_rotation.file_maxbytes` The maximum size a log file can grow to before it is automatically rotated. Default value: `104857600` (100MB). `elasticsearch.log_rotation.num_to_keep` The maximum number of log files that will be retained after rotation. Default value: `10`. `leaderl.enable` Sets up and runs the leaderl service. Default value: `true`. `leaderl.log_directory` The directory where the `svlogd` log service will run. Default value: `'/var/log/chef-backend/leaderl'`. `leaderl.start_down` The default state of the runit service to `down` by creating `<sv_dir>/down` file. Default value: `true`. `leaderl.log_rotation.file_maxbytes` The maximum size a log file can grow to before it is automatically rotated. Default value: `104857600` (100MB). `leaderl.log_rotation.num_to_keep` The maximum number of log files that will be retained after rotation. Default value: `10`. ### PostgreSQL Settings `postgresql.db_superuser` Super user account to create. Password is in `chef-backend-secrets.json`. Default value: `'chef_pgsql'`. `postgresql.md5_auth_cidr_addresses` A list of authorized addresses from which other backend nodes can connect to perform streaming replication. `samehost` and `samenet` are special symbols to allow connections from the this node’s IP address and its subnet. You may also use `all` to match any IP address. You may specify a hostname or IP address in CIDR format (`172.20.143.89/32` for a single host, or `172.20.143.0/24` for a small network. See <https://www.postgresql.org/docs/9.5/static/auth-pg-hba-conf.html> for alternative formats. Default value: `["samehost", "samenet"]`. `postgresql.replication_user` Username used by postgres streaming replicator when accessing this node. Default value: `'replicator'`. `postgresql.username` System username that the postgres process will run as. Default value: `'chef_pgsql'`. ### PostgreSQL Settings Given to `postgresql.conf` See [PostgreSQL’s documentation](https://www.postgresql.org/docs/9.5/static/runtime-config.html) for details. Some defaults are provided: `postgresql.archive_command` Default value: `''`. `postgresql.archive_mode` Default value: `'off'`. `postgresql.archive_timeout` Default value: `0`. `postgresql.checkpoint_completion_target` Default value: `0.5`. `postgresql.checkpoint_timeout` Default value: `'5min'`. `postgresql.checkpoint_warning` Default value: `'30s'`. `postgresql.effective_cache_size` Automatically calculated based on available memory. `postgresql.hot_standby` Default value: `'on'`. `postgresql.keepalives_count` Sets `tcp_keepalives_count`. Default value: `2`. `postgresql.keepalives_idle` Sets `tcp_keepalives_idle`. Default value: `60`. `postgresql.keepalives_interval` Sets `tcp_keepalives_interval`. Default value: `15`. `postgresql.log_checkpoints` Default value: `true`. `postgresql.log_min_duration_statement` Default value: `-1`. `postgresql.max_connections` Default value: `350`. `postgresql.max_replication_slots` Default value: `12`. `postgresql.max_wal_senders` Default value: `12`. `postgresql.max_wal_size` Default value: `64`. `postgresql.min_wal_size` Default value: `5`. `postgresql.port` Default value: `5432`. `postgresql.shared_buffers` Automatically calculated based on available memory. `postgresql.wal_keep_segments` Default value: `32`. `postgresql.wal_level` Default value: `'hot_standby'`. `postgresql.wal_log_hints` Default value: `on`. `postgresql.work_mem` Default value: `'8MB'`. ### etcd Settings `etcd.client_port` Port to use for ETCD_LISTEN_CLIENT_URLS and ETCD_ADVERTISE_CLIENT_URLS. Default value: `2379`. `etcd.peer_port` Port to use for ETCD_LISTEN_PEER_URLS and ETCD_ADVERTISE_PEER_URLS. Default value: `2380`. The following settings relate to etcd’s consensus protocol. Chef Backend builds its own leader election on top of etcd’s consensus protocol. Updating these settings may be advisable if you are seeing frequent failover events as a result of spurious etcd connection timeouts. The current defaults assume a high-latency environment, such as those you might find if deploying Chef Backend to various cloud providers. `etcd.heartbeat_interval` ETCD_HEARTBEAT_INTERVAL in milliseconds. This is the frequency at which the leader will send heartbeats to followers. etcd’s documentation recommends that this is set roughly to the round-trip times between members. Default value: `500`, (`100` by default before Chef Backend 1.2). `etcd.election_timeout` ETCD_ELECTION_TIMEOUT in milliseconds. This controls how long an etcd node will wait for heartbeat before triggering an election. Per etcd’s documentation, this should be 5 to 10 times larger than the `etcd.heartbeat_interval`. Increasing `etcd.election_timeout` increases the time it will take for `etcd` to detect a failure. Default value: `5000`, (`1000` by default before Chef Backend 1.2). `etcd.snapshot_count` ETCD_SNAPSHOT_COUNT which is the number of committed transactions to trigger a snapshot to disk. Default value: `5000`. `etcd.ionice.class` etcd must be able to write to disk with minimal latency. If your cluster does not meet the [disk requirements](../install_server_ha/index#hardware-requirements), e.g. you are running Chef Backend on virtual machines with shared disks, this settings should be changed to ‘1’ (real-time scheduling) to mitigate unnecessary failovers under high latency conditions. Default value: `2`. New in Chef Backend 2.2. `etcd.ionice.level` This may be changed for further tuning to specific environments if `etcd.ionice.class` is changed, but in almost all cases it should not be modified. Default value: `0`. New in Chef Backend 2.2. Note Even though the defaults assume a high-latency environment, cloud deployments should be restricted to the same datacenter, or in AWS, in the same region. This means that geographically-dispersed cluster deployments are not supported. Multiple Availability Zones *are* supported as long as they are in the same region. See [etcd’s documentation on tunables](https://etcd.io/docs/latest/tuning/) for more information. ### Elasticsearch JVM Settings `elasticsearch.heap_size` Automatically computed by Elasticsearch based on available memory. Specify in MB if you wish to override. `elasticsearch.java_opts` Flags to directly pass to the JVM when launching Elasticsearch. If you override a heap flag here, the setting here takes precedence. `elasticsearch.new_size` Java heap’s new generation size. ### Elasticsearch Configuration See [Elasticsearch’s configuration documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/settings.html) for additional information. `elasticsearch.plugins_directory` Sets the `path.plugins` value. Default value: `'/var/opt/chef-backend/elasticsearch/plugins'`. `elasticsearch.port` Sets the `http.port` value. Default value: `9200`. `elasticsearch.scripts_directory` Sets the `path.scripts` value. Default value: `'/var/opt/chef-backend/elasticsearch/scripts'`. ### Chef HA Backend Leader Management Service Settings `leaderl.db_timeout` Socket timeout when connecting to PostgreSQL in milliseconds. Default value: `2000`. `leaderl.http_acceptors` HTTP threads that responds to monitoring and leadership status requests from HAProxy. Default value: `10`. `leaderl.http_address` The address that leaderl listens on. This address should not be `127.0.0.1`. It should be reachable from any front-end node. Default value: `'0.0.0.0'`. `leaderl.http_port` Default value: `7331`. `leaderl.leader_ttl_seconds` The number of seconds it takes the leader key to expire. Increasing this value will increase the amount of time the cluster will take to recognize a failed leader. Lowering this value may lead to frequent leadership changes and thrashing. Default value: `30`. (`10` by default before Chef Backend 1.2). `leaderl.required_active_followers` The number of followers that must be syncing via a PostgreSQL replication slot before a new leader will return 200 to /leader HTTP requests. If an existing leader fails to maintain this quorum of followers, the /leader endpoint will return 503 but active connections will still be able to complete their writes to the database. Default value: `0`. `leaderl.runsv_group` The group that sensitive password files will belong to. This is used internally for test purposes and should never be modified otherwise. Default value: `'chef_pgsql'`. `leaderl.status_internal_update_interval_seconds` How often we check for a change in the leader service’s status in seconds. Default value: `5`. `leaderl.status_post_update_interval_seconds` How often etcd is updated with the leader service’s current status in seconds. Default value: `10`. `leaderl.username` System username that the leaderl process will run as. Usually the same as `postgresql.username`. Default value: `'chef_pgsql'`. `leaderl.log_rotation.max_messages_per_second` Rate limit for the number of messages that the Erlang error_logger will output. Default value: `1000`. `leaderl.etcd_pool.ibrowse_options` Internal options to affect how requests to etcd are made (see <https://github.com/cmullaparthi/ibrowse/blob/master/doc/ibrowse.html>). `leaderl.epmd_monitor.check_interval` How often to check that leaderl is registered with the Erlang Port Mapping Daemon (epmd) in milliseconds. Default value: `60000`. ### Chef HA Backend Leader Health Status Settings `leaderl.health_check.interval_seconds` How frequently to poll the service for health status in seconds. We recommend setting this to at least 5 times the value of `leaderl.leader_ttl_seconds`. Default value: `5`, (`2` by default before version Chef Backend 1.2). `leaderl.health_check.max_bytes_behind_leader` Limit on maximum different between elected leader and current node in bytes. Default value: `52428800` (50MB). `leaderl.health_check.max_elasticsearch_failures` Number of Elasticsearch API failures allowed before health check fails. Default value: `5`. `leaderl.health_check.max_etcd_failures` Number of etcd failures allowed before health check fails. Default value: `5`. `leaderl.health_check.max_pgsql_failures` Number of PostgreSQL connection failures allowed before health check fails. Default value: `5`. `leaderl.health_check.fatal_system_checks` Whether or not system check failures (such as disk space failures) will result in the node being marked ineligible for leadership. Default value: `false`. New in Chef Backend 1.4. `leaderl.health_check.disk_paths` An array containing the paths to check for sufficient disk space. Default value: `[/var/log/chef-backend, /var/opt/chef-backend]`. New in Chef Backend 1.4. `leaderl.health_check.disk_min_space_mb` The minimum amount of disk space (in megabytes) required for a disk health check to pass. Default value: `250`. New in Chef Backend 1.4. ### Chef HA Backend Leader Connection Pool Settings See <https://github.com/seth/pooler/blob/master/README.org> for details. These are internal settings that affect the responsiveness, uptime and reliability of the backend cluster. They should not be modified unless you are advised to do so by Support. `leaderl.etcd_pool.cull_interval_seconds` Default value: `60`. `leaderl.etcd_pool.http_timeout_ms` Default value: `5000`. `leaderl.etcd_pool.init_count` Default value: `10`. `leaderl.etcd_pool.max_age_seconds` Default value: `60`. `leaderl.etcd_pool.max_connection_duration_seconds` Default value: `300`. `leaderl.etcd_pool.max_count` Default value: `10`. ### SSL Settings If `certificate` and `certificate_key` are nil, the SSL Certificate will be auto-generated using the other parameters provided. Otherwise, they are on-disk locations to user-provided certificate. `ssl.certificate` Provide this path if you have a pre-generated SSL cert. `ssl.certificate_key` Provide this path if you have a pre-generated SSL cert. `ssl.ciphers` Ordered list of allowed SSL ciphers. This will be updated based on security considerations and the version of OpenSSL being shipped. `ssl.company_name` The name of your organization. `ssl.country_name` The two-character country code. `ssl.data_dir` Where certificates will be stored. Default value: `'/var/opt/chef-backend/ssl/'`. `ssl.duration` The duration of the certificate in days. Default value: `3650` (10 years). `ssl.key_length` Default value: `2048`. `ssl.organizational_unit_name` The name of the division in your organization. chef-backend-ctl ---------------- The Chef Infra Server backend HA cluster includes a command-line utility named chef-backend-ctl. This command-line tool is used to manage the Chef Infra Server backend HA cluster, start and stop individual services, and tail Chef Infra Server log files. For more information, see the [chef-backend-ctl documentation](../ctl_chef_backend/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/config_rb_backend/Firewalls and Ports =================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/server_firewalls_and_ports.md) All of the ports used by the Chef Infra Server are TCP ports. Refer to the operating system’s manual or site systems administrators for instructions on how to enable changes to ports, if necessary. All services must be listening on the appropriate ports. Most monitoring systems provide a means of testing whether a given port is accepting connections and service-specific tools may also be available. In addition, the generic system tool Telnet can also be used to initiate the connection: ``` telnet HOST_NAME PORT ``` Note An “external” port is external from the perspective of a workstation (such as knife), a machine (Chef Infra Client), or any other user that accesses the Chef Infra Server via the Chef Infra Server API. Standalone ---------- The following sections describe the ports that are required by the Chef Infra Server in a standalone configuration: ![image] A single loopback interface should be configured using the `127.0.0.1` address. This ensures that all of the services are available to the Chef Infra Server, in the event that the Chef Infra Server attempts to contact itself from within a front or back end machine. All ports should be accessible through the loopback interface of their respective hosts. For a standalone installation, ensure that ports marked as external (marked as `yes` in the **External** column) are open and accessible via any firewalls that are in use: | Port | Service Name, Description | External | | --- | --- | --- | | 4321 | **bookshelf** The **bookshelf** service is an Amazon Simple Storage Service (S3)-compatible service that is used to store cookbooks, including all of the files—recipes, templates, and so on—that are associated with each cookbook. | no | | 80, 443, 9683 | **nginx** The **nginx** service is used to manage traffic to the Chef Infra Server, including virtual hosts for internal and external API request/response routing, external add-on request routing, and routing between front- and back-end components. Note Port 9683 is used to internally load balance the **oc_bifrost** service. | yes | | 9463 | **oc_bifrost** The **oc_bifrost** service ensures that every request to view or manage objects stored on the Chef Infra Server is authorized. | | | 9090 | **oc-id** The **oc-id** service enables OAuth 2.0 authentication to the Chef Infra Server by external applications, including Chef Supermarket. OAuth 2.0 uses token-based authentication, where external applications use tokens that are issued by the **oc-id** provider. No special credentials—`webui_priv.pem` or privileged keys—are stored on the external application. | | | 8000 | **opscode-erchef** The **opscode-erchef** service is an Erlang-based service that is used to handle Chef Infra Server API requests to the following areas within the Chef Infra Server:* Cookbooks * Data bags * Environments * Nodes * Roles * Sandboxes * Search | | | 5432 | **postgresql** The **postgresql** service is used to store node, object, and user data. | | | 9200 | **elasticsearch** The **elasticsearch** service is used to create the search indexes used for searching objects like nodes, data bags, and cookbooks. (This service ensures timely search results via the Chef Infra Server API; data that is used by the Chef platform is stored in PostgreSQL.) | | | 16379 | **redis_lb** Key-value store used in conjunction with Nginx to route requests and populate request data used by the Chef Infra Server. | | Tiered ------ The following sections describe the ports that are required by the Chef Infra Server in a tiered configuration: ![image] A single loopback interface should be configured using the `127.0.0.1` address. This ensures that all of the services are available to the Chef Infra Server, in the event that the Chef Infra Server attempts to contact itself from within a front or back end machine. All ports should be accessible through the loopback interface of their respective hosts. ### Front End For front-end servers, ensure that ports marked as external (marked as `yes` in the **External** column) are open and accessible via any firewalls that are in use: | Port | Service Name, Description | External | | --- | --- | --- | | 80, 443, 9683 | **nginx** The **nginx** service is used to manage traffic to the Chef Infra Server, including virtual hosts for internal and external API request/response routing, external add-on request routing, and routing between front- and back-end components. Note Port 9683 is used to internally load balance the **oc_bifrost** service. | yes | | 9463 | **oc_bifrost** The **oc_bifrost** service ensures that every request to view or manage objects stored on the Chef Infra Server is authorized. | | | 9090 | **oc-id** The **oc-id** service enables OAuth 2.0 authentication to the Chef Infra Server by external applications, including Chef Supermarket. OAuth 2.0 uses token-based authentication, where external applications use tokens that are issued by the **oc-id** provider. No special credentials—`webui_priv.pem` or privileged keys—are stored on the external application. | | | 8000 | **opscode-erchef** The **opscode-erchef** service is an Erlang-based service that is used to handle Chef Infra Server API requests to the following areas within the Chef Infra Server:* Cookbooks * Data bags * Environments * Nodes * Roles * Sandboxes * Search | | ### Back End For back-end servers in a tiered Chef Infra Server installation, ensure that ports marked as external (marked as `yes` in the **External** column) are open and accessible via any firewalls that are in use: | Port | Service Name, Description | External | | --- | --- | --- | | 80, 443, 9683 | **nginx** The **nginx** service is used to manage traffic to the Chef Infra Server, including virtual hosts for internal and external API request/response routing, external add-on request routing, and routing between front- and back-end components. Note Port 9683 is used to internally load balance the **oc_bifrost** service. | yes | | 9463 | **oc_bifrost** The **oc_bifrost** service ensures that every request to view or manage objects stored on the Chef Infra Server is authorized. | | | 9200 | **elasticsearch** The **elasticsearch** service is used to create the search indexes used for searching objects like nodes, data bags, and cookbooks. (This service ensures timely search results via the Chef Infra Server API; data that is used by the Chef platform is stored in PostgreSQL.) | | | 5432 | **postgresql** The **postgresql** service is used to store node, object, and user data. | | | 16379 | **redis_lb** Key-value store used in conjunction with Nginx to route requests and populate request data used by the Chef Infra Server. | | | 4321 | **bookshelf** The **bookshelf** service is an Amazon Simple Storage Service (S3)-compatible service that is used to store cookbooks, including all of the files—recipes, templates, and so on—that are associated with each cookbook. | | | 8000 | **opscode-erchef** The **opscode-erchef** service is an Erlang-based service that is used to handle Chef Infra Server API requests to the following areas within the Chef Infra Server:* Cookbooks * Data bags * Environments * Nodes * Roles * Sandboxes * Search | | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/server_firewalls_and_ports/Security ======== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/server_security.md) This guide covers the security features available in Chef Infra Server. SSL Certificates ---------------- Initial configuration of the Chef Infra Server is done automatically using a self-signed certificate to create the certificate and private key files for Nginx. This section details the process for updating a Chef Infra Server’s SSL certificate. ### Automatic Installation (recommended) The Chef Infra Server can be configured to use SSL certificates by adding the following settings to the server configuration file: | Setting | Description | | --- | --- | | `nginx['ssl_certificate']` | The SSL certificate used to verify communication over HTTPS. | | `nginx['ssl_certificate_key']` | The certificate key used for SSL communication. | and then setting their values to define the paths to the certificate and key. For example: ``` nginx['ssl_certificate'] = '/etc/pki/tls/certs/your-host.crt' nginx['ssl_certificate_key'] = '/etc/pki/tls/private/your-host.key' ``` Save the file, and then run the following command: ``` sudo chef-server-ctl reconfigure ``` For more information about the server configuration file, see [chef-server.rb](../config_rb_server/index). ### Manual Installation SSL certificates can be updated manually by placing the certificate and private key file obtained from the certifying authority in the correct files, after the initial configuration of Chef Infra Server. The locations of the certificate and private key files are: * `/var/opt/opscode/nginx/ca/FQDN.crt` * `/var/opt/opscode/nginx/ca/FQDN.key` Because the FQDN has already been configured, do the following: 1. Replace the contents of `/var/opt/opscode/nginx/ca/FQDN.crt` and `/var/opt/opscode/nginx/ca/FQDN.key` with the certifying authority’s files. 2. Reconfigure the Chef Infra Server: ``` chef-server-ctl reconfigure ``` 3. Restart the Nginx service to load the new key and certificate: ``` chef-server-ctl restart nginx ``` Warning The FQDN for the Chef Infra Server should be resolvable, lowercase, and have fewer than 64 characters including the domain suffix, when using OpenSSL, as OpenSSL requires the `CN` in a certificate to be no longer than 64 characters. ### SSL Protocols The following settings are often modified from the default as part of the tuning effort for the **nginx** service and to configure the Chef Infra Server to use SSL certificates: `nginx['ssl_certificate']` The SSL certificate used to verify communication over HTTPS. Default value: `nil`. `nginx['ssl_certificate_key']` The certificate key used for SSL communication. Default value: `nil`. `nginx['ssl_ciphers']` The list of supported cipher suites that are used to establish a secure connection. To favor AES256 with ECDHE forward security, drop the `RC4-SHA:RC4-MD5:RC4:RSA` prefix. For example: ``` nginx['ssl_ciphers'] = "HIGH:MEDIUM:!LOW:!kEDH: \ !aNULL:!ADH:!eNULL:!EXP: \ !SSLv2:!SEED:!CAMELLIA: \ !PSK" ``` `nginx['ssl_protocols']` The SSL protocol versions that are enabled for the Chef Infra Server API. For enhanced security set this value to `'TLSv1.2'`. TLS 1.2 is supported on Chef Infra Client 10.16.4 and later on Linux, Unix, and macOS, and on Chef Infra Client 12.8 and later on Windows. If it is necessary to support these older end-of-life Chef Infra Client releases, set this value to `'TLSv1.1 TLSv1.2'`. For example: ``` nginx['ssl_protocols'] = 'TLSv1.2' ``` Note See <https://www.openssl.org/docs/man1.0.2/man1/ciphers.html> for more information about the values used with the `nginx['ssl_ciphers']` and `nginx['ssl_protocols']` settings. For example, after copying the SSL certificate files to the Chef Infra Server, update the `nginx['ssl_certificate']` and `nginx['ssl_certificate_key']` settings to specify the paths to those files, and then (optionally) update the `nginx['ssl_ciphers']` and `nginx['ssl_protocols']` settings to reflect the desired level of hardness for the Chef Infra Server: ``` nginx['ssl_certificate'] = '/etc/pki/tls/private/name.of.pem' nginx['ssl_certificate_key'] = '/etc/pki/tls/private/name.of.key' nginx['ssl_ciphers'] = 'HIGH:MEDIUM:!LOW:!kEDH:!aNULL:!ADH:!eNULL:!EXP:!SSLv2:!SEED:!CAMELLIA:!PSK' nginx['ssl_protocols'] = 'TLSv1 TLSv1.1 TLSv1.2' ``` **Example: Configure SSL Keys for Nginx** The following example shows how the Chef Infra Server sets up and configures SSL certificates for Nginx. The cipher suite used by Nginx [is configurable](../config_rb_server/index#ssl-protocols) using the `ssl_protocols` and `ssl_ciphers` settings. ``` ssl_keyfile = File.join(nginx_ca_dir, "#{node['private_chef']['nginx']['server_name']}.key") ssl_crtfile = File.join(nginx_ca_dir, "#{node['private_chef']['nginx']['server_name']}.crt") ssl_signing_conf = File.join(nginx_ca_dir, "#{node['private_chef']['nginx']['server_name']}-ssl.conf") unless ::File.exist?(ssl_keyfile) && ::File.exist?(ssl_crtfile) && ::File.exist?(ssl_signing_conf) file ssl_keyfile do owner 'root' group 'root' mode '0755' content '/opt/opscode/embedded/bin/openssl genrsa 2048' not_if { ::File.exist?(ssl_keyfile) } end file ssl_signing_conf do owner 'root' group 'root' mode '0755' not_if { ::File.exist?(ssl_signing_conf) } content <<-EOH [ req ] distinguished_name = req_distinguished_name prompt = no [ req_distinguished_name ] C = #{node['private_chef']['nginx']['ssl_country_name']} ST = #{node['private_chef']['nginx']['ssl_state_name']} L = #{node['private_chef']['nginx']['ssl_locality_name']} O = #{node['private_chef']['nginx']['ssl_company_name']} OU = #{node['private_chef']['nginx']['ssl_organizational_unit_name']} CN = #{node['private_chef']['nginx']['server_name']} emailAddress = #{node['private_chef']['nginx']['ssl_email_address']} EOH end ruby_block 'create crtfile' do block do r = Chef::Resource::File.new(ssl_crtfile, run_context) r.owner 'root' r.group 'root' r.mode '0755' r.content "/opt/opscode/embedded/bin/openssl req -config '#{ssl_signing_conf}' -new -x509 -nodes -sha1 -days 3650 -key '#{ssl_keyfile}'" r.not_if { ::File.exist?(ssl_crtfile) } r.run_action(:create) end end end ``` ### Knife, Chef Infra Client Chef Infra Server 12 and later enables SSL verification by default for all requests made to the server, such as those made by knife and Chef Infra Client. The certificate that is generated during the installation of the Chef Infra Server is self-signed, which means the certificate is not signed by a trusted certificate authority (CA) recognized by Chef Infra Client. The certificate generated by the Chef Infra Server must be downloaded to any machine from which knife and/or Chef Infra Client will make requests to the Chef Infra Server. For example, without downloading the SSL certificate, the following knife command: ``` knife client list ``` responds with an error similar to: ``` ERROR: SSL Validation failure connecting to host: chef-server.example.com ... ERROR: OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 ... ``` This is by design and will occur until a verifiable certificate is added to the machine from which the request is sent. See [Chef Infra Client SSL Certificates](../../chef_client_security/index#ssl-certificates) for more information on how knife and Chef Infra Client use SSL certificates generated by the Chef Infra Server. ### Private Certificate Authority If an organization is using an internal certificate authority, then the root certificate will not appear in any `cacerts.pem` file that ships by default with operating systems and web browsers. Because of this, no currently deployed system will be able to verify certificates that are issued in this manner. To allow other systems to trust certificates from an internal certificate authority, this root certificate will need to be configured so that other systems can follow the chain of authority back to the root certificate. (An intermediate certificate is not enough because the root certificate is not already globally known.) To use an internal certificate authority, append the server–optionally, any intermediate certificate as well–and root certificates into a single `.crt` file. For example: ``` cat server.crt [intermediate.crt] root.crt >> /var/opt/opscode/nginx/ca/FQDN.crt ``` Check your combined certificate’s validity on the Chef Infra Server: ``` openssl verify -verbose -purpose sslserver -CAfile cacert.pem /var/opt/opscode/nginx/ca/FQDN.crt ``` The cacert.pem should contain only your root CA’s certificate file. This is not the usual treatment, but mimics how Chef Workstation behaves after a `knife ssl fetch` followed by a `knife ssl verify`. ### Intermediate Certificates For use with 3rd party certificate providers, for example, Verisign. To use an intermediate certificate, append both the server and intermediate certificates into a single `.crt` file. For example: ``` cat server.crt intermediate.crt >> /var/opt/opscode/nginx/ca/FQDN.crt ``` ### Verify Certificate Was Signed by Proper Key It’s possible that a certificate/key mismatch can occur during the CertificateSigningRequest (CSR) process. During a CSR, the original key for the server in question should always be used. If the output of the following commands don’t match, then it’s possible the CSR for a new key for this host was generated using a random key or a newly generated key. The symptoms of this issue will look like the following in the nginx log files: ``` nginx: [emerg] SSL_CTX_use_PrivateKey_file("/var/opt/opscode/nginx/ca/YOUR_HOSTNAME.key") failed (SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch) ``` Here’s how to tell for sure when the configured certificate doesn’t match the key ``` ## openssl x509 -in /var/opt/opscode/nginx/ca/chef-432.lxc.crt -noout -modulus | openssl sha1 (stdin)= 05b4f62e52fe7ce2351ff81d3e1060c0cdf1fa24 ## openssl rsa -in /var/opt/opscode/nginx/ca/chef-432.lxc.key -noout -modulus | openssl sha1 (stdin)= 05b4f62e52fe7ce2351ff81d3e1060c0cdf1fa24 ``` To fix this, you will need to generate a new CSR using the original key for the server, the same key that was used to produce the CSR for the previous certificates. Install that new certificates along with the original key and the mismatch error should go away. ### Regenerate Certificates SSL certificates should be regenerated periodically. This is an important part of protecting the Chef Infra Server from vulnerabilities and helps to prevent the information stored on the Chef Infra Server from being compromised. To regenerate SSL certificates: 1. Run the following command: ``` chef-server-ctl stop ``` 2. The Chef Infra Server can regenerate them. These certificates will be located in `/var/opt/opscode/nginx/ca/` and will be named after the FQDN for the Chef Infra Server. To determine the FQDN for the server, run the following command: ``` hostname -f ``` Please delete the files found in the ca directory with names like this `$FQDN.crt` and `$FQDN.key`. 3. If your organization has provided custom SSL certificates to the Chef Infra Server, the locations of that custom certificate and private key are defined in `/etc/opscode/chef-server.rb` as values for the `nginx['ssl_certificate']` and `nginx['ssl_certificate_key']` settings. Delete the files referenced in those two settings and regenerate new keys using the same authority. 4. Run the following command, Chef server-generated SSL certificates will automatically be created if necessary: ``` chef-server-ctl reconfigure ``` 5. Run the following command: ``` chef-server-ctl start ``` Chef Infra Server Credentials Management ---------------------------------------- Chef Infra Server limits where it writes service passwords and keys to disk. In the default configuration, credentials are only written to files in `/etc/opscode`. By default, Chef Infra Server still writes service credentials to multiple locations inside `/etc/opscode`. This is designed to maintain compatibility with add-ons. The `insecure_addon_compat` configuration option in `/etc/opscode/chef-server.rb`, allows you to further restrict where credentials are written. `insecure_addon_compat` can be used if you are not using add-ons, or if you are using the latest add-on versions. Setting `insecure_addon_compat` to `false` writes credentials to only one location: `/etc/opscode/private-chef-secrets.json`. User-provided secrets (such as the password for an external PostgreSQL instance) can still be set in `/etc/opscode/chef-server.rb` or via the [Secrets Management](../ctl_chef_server/index#ctl-chef-server-secrets-management) commands. These commands allow you to provide external passwords without including them in your configuration file. ### Add-on Compatibility The following table lists which add-on versions support the more restrictive `insecure_addon_compat false` setting. These versions **require** Chef Server 12.14.0 or greater: | Add-on Name | Minimum Version | | --- | --- | | Chef Backend | *all* | | Chef Manage | 2.5.0 | These newer add-ons will also write all of their secrets to `/etc/opscode/private-chef-secrets.json`. Older versions of the add-ons will still write their configuration to locations in `/etc` and `/var/opt`. ### /etc/opscode/private-chef-secrets.json `/etc/opscode/private-chef-secrets.json`’s default permissions allow only the root user to read or write the file. This file contains all of the secrets for access to the Chef server’s underlying data stores and thus access to it should be restricted to trusted users. While the file does not contain passwords in plaintext, it is not safe to share with untrusted users. The format of the secrets file allows Chef Infra Server deployments to conform to regulations that forbid the appearance of sensitive data in plain text in configuration files; however, it does not make the file meaningfully more secure. SSL Encryption Between Chef Infra Server and External PostgreSQL ---------------------------------------------------------------- Chef Infra Server can encrypt traffic between Chef Infra Server and an external PostgreSQL server over SSL. These instructions are not all-encompassing and assume some familiarity with PostgreSQL administration, configuration, and troubleshooting. Consult the [PostgreSQL documentation](https://www.postgresql.org/docs/9.6/ssl-tcp.html) for more information. The following is a typical scenario for enabling encryption between a machine running Chef Infra Server and an external machine running PostgreSQL. Both machines must be networked together and accessible to the user. 1. Run the following command on both machines to gain root access: ``` sudo -i ``` 2. Ensure that [OpenSSL](https://www.openssl.org) is installed on the PostgreSQL machine. 3. Ensure that SSL support is compiled in on PostgreSQL. This applies whether you are compiling your own source or using a pre-compiled binary. 4. Place SSL certificates in the proper directories on the PostgreSQL machine and ensure they have correct filenames, ownerships, and permissions. 5. Enable SSL on PostgreSQL by editing the `postgresql.conf` file. Set `ssl = on` and specify the paths to the SSL certificates: ``` ssl=on ssl_cert_file='/path/to/cert/file' ssl_key_file='/path/to/key/file' ``` 6. To prevent PostgreSQL from accepting non-SSL connections, edit `pg_hba.conf` on the PostgreSQL machine and change the relevant Chef Infra Server connections to `hostssl`. Here is a sample `pg_hba.conf` file with hostssl connections for Chef Infra Server (the contents of your `pg_hba.conf` will be different): ``` # "local" is for Unix domain socket connections only local all all peer # IPv4 local connections: hostssl all all 127.0.0.1/32 md5 # IPv6 local connections: hostssl all all ::1/128 md5 # nonlocal connections hostssl all all 192.168.33.100/32 md5 ``` 7. Restart PostgreSQL. This can typically be done with the following command on the PostgreSQL machine: ``` /path/to/postgresql/postgresql restart ``` 8. Edit `/etc/opscode/chef-server.rb` on the Chef Infra Server and ad the following line: ``` postgresql['sslmode'] = 'require' ``` 9. Run reconfigure on the Chef Infra Server: ``` chef-server-ctl reconfigure ``` 10. Verify that SSL is enabled and that SSL connections are up between Chef Infra Server and your running PostgreSQL instance. One way to do this is to log into the PostgreSQL database from the Chef Infra Server by running `chef-server-ctl psql` and then examine the SSL state using SQL queries. Start a psql session: ``` chef-server-ctl psql opscode_chef ``` From the psql session, enter `postgres=# show ssl;` which will show if ssl is enabled: ``` postgres=#showssl;ssl----- on(1row) ``` Then enter `postgres=# select * from pg_stat_ssl;` which will return true (`t`) in rows with SSL connections: ``` postgres=#select*frompg_stat_ssl;pid|ssl|version|cipher|bits|compression|clientdn-------+-----+---------+-----------------------------+------+-------------+---------- 16083|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16084|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16085|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16086|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16087|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16088|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16089|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16090|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16091|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16092|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16093|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16094|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16095|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16096|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16097|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16098|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16099|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16100|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16101|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16102|t|TLSv1.2|ECDHE-RSA-AES256-GCM-SHA384|256|f|16119|f|||||(21rows) ``` Key Rotation ------------ See the [chef-server-ctl key rotation commands](../ctl_chef_server/index#key-rotation) for more information about user key management. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/server_security/Backup and Restore a Standalone or Frontend install =================================================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/server_backup_restore.md) Periodic backups of Chef Infra Server data are an essential part of managing and maintaining a healthy configuration and ensuring that important data can be restored, if required. The backup takes around 4 to 5 minutes per GB of data on a t3.2xlarge AWS EC2 instance. chef-server-ctl --------------- For the majority of use cases, `chef-server-ctl backup` is the recommended way to take backups of the Chef Infra Server. Use the following commands for managing backups of Chef Infra Server data, and for restoring those backups. ### backup The `backup` subcommand is used to back up all Chef Infra Server data. This subcommand: * Requires rsync to be installed on the Chef Infra Server prior to running the command * Requires a `chef-server-ctl reconfigure` prior to running the command * Should not be run in a Chef Infra Server configuration with an external PostgreSQL database; [use knife ec backup](https://github.com/chef/knife-ec-backup) instead * Puts the initial backup in the `/var/opt/chef-backup` directory as a tar.gz file; move this backup to a new location for safe keeping **Options** This subcommand has the following options: `-y`, `--yes` Use to specify if the Chef Infra Server can go offline during tar.gz-based backups. `--pg-options` Use to specify and pass additional options PostgreSQL during backups. See the [PostgreSQL documentation](https://www.postgresql.org/docs/13/runtime-config.html) for more information. `-c`, `--config-only` Backup the Chef Infra Server configuration **without** backing up data. `-t`, `--timeout` Set the maximum amount of time in seconds to wait for shell commands (default 600). This option should be set to greater than 600 for backups taking longer than 10 minutes. `-h`, `--help` Show help message. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl backup ``` ### restore The `restore` subcommand is used to restore Chef Infra Server data from a backup that was created by the `backup` subcommand. This subcommand may also be used to add Chef Infra Server data to a newly-installed server. Do not run this command in a Chef Infra Server configuration that uses an external PostgreSQL database; [use knife ec backup](https://github.com/chef/knife-ec-backup) instead. This subcommand: * Requires rsync installed on the Chef Infra Server before running the command * Requires a `chef-server-ctl reconfigure` before running the command Ideally, the restore server will have the same FQDN as the server that you backed up. If the restore server has a different FQDN, then: 1. Replace the FQDN in the `/etc/opscode/chef-server.rb`. 2. Replace the FQDN in the `/etc/opscode/chef-server-running.json`. 3. Delete the old SSL certificate, key and `-ssl.conf` file from `/var/opt/opscode/nginx/ca`. 4. If you use a CA-issued certificate instead of a self-signed certificate, copy the CA-issued certificate and key into `/var/opt/opscode/nginx/ca`. 5. Update the `/etc/chef/client.rb` file on each client to point to the new server FQDN. 6. Run `chef-server-ctl reconfigure`. 7. Run ``chef-server-ctl restore`. **Options** This subcommand has the following options: `-c`, `--cleanse` Use to remove all existing data on the Chef Infra Server; it will be replaced by the data in the backup archive. `-d DIRECTORY`, `--staging-dir DIRECTORY` Use to specify that the path to an empty directory to be used during the restore process. This directory must have enough disk space to expand all data in the backup archive. `--pg-options` ``` : Use to specify and pass additional options PostgreSQL during backups. See the [PostgreSQL documentation](https://www.postgresql.org/docs/13/runtime-config.html) for more information. `-t`, `--timeout` : Set the maximum amount of time in seconds to wait for shell commands. Set to greater than 600 for backups that take longer than 10 minutes. Default: 600. `-h`, `--help` : Show help message. **Syntax** This subcommand has the following syntax: ```bash chef-server-ctl restore PATH_TO_BACKUP (options) ``` **Examples** ``` chef-server-ctl restore /path/to/tar/archive.tar.gz ``` Backup and restore a Chef Backend install ----------------------------------------- Warning Chef Backend is [deprecated](../../versions/index#deprecated-products-and-versions) and no longer under active development. Contact your Chef account representative for information about migrating to Chef Automate HA. This document is no longer maintained. In a disaster recovery scenario, the backup and restore processes allow you to restore a data backup into a newly built cluster. It is not intended for the recovery of an individual machine in the chef-backend cluster or for a point-in-time rollback of an existing cluster. ### Backup Restoring your data in the case of an emergency depends on having previously made backups of: * the data in your Chef Backend cluster * the configuration from your Chef server To make backups for future use in disaster scenarios: 1. On a follower chef-backend node, run `chef-backend-ctl backup` 2. On a Chef Infra Server node run: `chef-server-ctl backup --config-only` 3. Move the tar archives created in steps (1) and (2) to a long-term storage location. ### Restore To restore a Chef Backend-based Chef Infra Server cluster: 1. Restore the node and an IP address that can be used to reach the node on the first machine that you want to use in your new Chef Backend cluster. The argument to the `--publish_address` option should be the IP address for reaching the node you are restoring. ``` chef-backend-ctl restore --publish_address X.Y.Z.W /path/to/backup.tar.gz ``` 2. Join additional nodes to your Chef Backend cluster. (If you are only testing and verifying your restore process you can test against a single Chef Backend node and a single Chef Infra Server node.) ``` chef-backend-ctl join-cluster IP_OF_FIRST_NODE --publish_address IP_OF_THIS_NODE ``` 3. Restore Chef Infra Server from your backed up Infra Server configuration (See step 2 in the backup instructions above). Alternatively, you can generate new configuration for this node and reconfigure it using the steps found in [the installation instructions.](../install_server_ha/index#step-5-install-and-configure-first-frontend). ``` chef-server-ctl restore /path/to/chef-server-backup.tar.gz ``` 4. Run the `reindex` command to re-populate your search index ``` chef-server-ctl reindex --all ``` ### Verify We recommend periodically verifying your backup by restoring a single Chef Backend node, a single Chef Infra Server node, and ensuring that various knife commands and Chef Infra Client runs can successfully complete against your backup. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/server_backup_restore/Chef Backend Failure Recovery ============================= [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/backend_failure_recovery.md) Warning Chef Backend is [deprecated](../../versions/index#deprecated-products-and-versions) and no longer under active development. Contact your Chef account representative for information about migrating to Chef Automate HA. This document is no longer maintained. This document contains the recommended actions for responding to failures in your Chef Backend cluster. Note If you have concerns about applying the Chef Backend recovery process to your cluster, please consult with Support before taking the steps outlined in this guide. Assumptions ----------- All instructions currently assume a 3-node backend cluster running Chef Backend 2.1.0 or greater. The user should have SSH access with root privileges to all nodes in the cluster. Node Failures ------------- This section covers how to respond to failures that have brought the entire node down or off the network. ### Single-node Failure Temporary single-node failures require little administrator intervention to resolve. Once the administrator has addressed the failure and restarted the node, it will reconnect to the cluster and sync from the current leader. However if the failing node cannot be brought back online, it must be replaced: 1. Run `chef-backend-ctl remove-node NODE_NAME` from any working cluster member to remove the offending node (it doesn’t have to be the leader). 2. Run `chef-backend-ctl cleanse` on the offending node. This will save configuration files under the root directory by default. 3. Check to make sure `/var/opt/chef-backend` was deleted by `chef-backend-ctl cleanse`. 4. Make a directory for the configuration files: `mkdir /etc/chef-backend`. 5. Copy `/root/chef-backend-cleanse*` to `/etc/chef-backend/`. 6. Run `chef-backend-ctl join-cluster LEADER_IP --recovery` See the [installation instructions](../install_server_ha/index#step-3-install-and-configure-remaining-backend-nodes) for more details on joining nodes to the cluster. ### Two-node Failure In the case of a two-node failure in a standard three-node configuration, the cluster is no longer able to operate, as leader election requires a quorum of two nodes. This procedure assumes that the remaining node has the most up-to-date copy of the data. If that is not the case it is advised that you restore the existing node from a backup before proceeding. See the [Backup and Restore](../server_backup_restore/index#backup-and-restore-a-chef-backend-install) documentation for details. 1. On the surviving node, run the following command: ``` chef-backend-ctl create-cluster --quorum-loss-recovery ``` 2. On each of the two new nodes, install `chef-backend-ctl` and join to the cluster using: ``` chef-backend-ctl join-cluster IP_OF_LEADER -s PATH_TO_SHARED_SECRETS ``` See the [installation instructions](../install_server_ha/index#step-3-install-and-configure-remaining-backend-nodes) for more details on joining nodes to the cluster. Partitions ---------- For the purpose of this section, a **partition** refers to the loss of network connectivity between two nodes. From the perspective of other nodes in the cluster, it is impossible to tell whether a node is down or has been partitioned. However, because a partition is often characterized by the node and the software on the node still being up, this section covers some special care to take when recovering a cluster that has been partitioned at the network level. ### No Loss of Quorum If the network partition did not result in a loss of quorum, then the failed nodes in the cluster should recover on their own once connectivity is restored. ### Loss of Quorum This section covers two potential remediation options for instances where a lack of network connectivity has resulted in loss of quorum between nodes. #### Promoting a Specific Node This procedure only works currently if the administrator can take action before the network split resolves itself. 1. Resolve the network partition. As the nodes come back online, they will all move into a `waiting_for_leader` state. 2. To promote a node, run `chef-backend-ctl promote NODE_NAME_OR_IP` #### Promoting a Previous Leader If a recently deposed leader is likely the node with the most up-to-date data, you may want to reinstate its leadership. 1. To ensure that the deposed leader can come up correctly, you will need to override the safety check that prevents deposed leaders from starting PostgreSQL. On the deposed leader node that is being promoted, run the following command: ``` rm /var/opt/chef-backend/leaderl/data/no-start-pgsql ``` 2. Then restart PostgreSQL: ``` chef-backend-ctl restart postgresql ``` 3. Finally, promote the deposed leader node: ``` chef-backend-ctl promote NODE_NAME_OR_IP ``` Service Level Failures ---------------------- This section documents the expected behavior that occurs when a single service fails. This currently extends to the service’s process on the machine dying, not more complicated service failures where the process is up and taking requests but returning incorrect results. Note that the number of service-level failures that a service can sustain depends upon whether or not the failure is happening in isolation. In general an operator should assume that the cluster can sustain a failure on a single node, but a second failure is likely to cause a loss of availability if the first failure is not resolved. ### PostgreSQL The leader/follower state of PostgreSQL is managed by Leaderl. Leaderl performs health checks on PostgreSQL and fails over to a follower if the health check fails. Assuming that `etcd` and `leaderl` are running properly, two of the three nodes can have service-level PostgreSQL failures. Once the service-level problems have been resolved, the two failed nodes can be resynced from the leader node. ### Elasticsearch * Elasticsearch manages its own availability. 1 of the 3 nodes can have a service-level Elasticsearch failure without affecting the availability of the cluster. * Elasticsearch failovers are independent of PostgreSQL failovers; however, since the Chef Infra Server can only talk to a single Elasticsearch instance, if Elasticsearch fails on the leader node, Leaderl will failover (including a PostgreSQL failover) to another node. * Once the root cause of the service-level problems has been identified and solved, the failed node should be able to rejoin the cluster. ### Etcd Etcd is used by Leaderl to elect a PostgreSQL leader and store status and cluster state information. Its availability is required for Leaderl to continue functioning properly. 1 of the 3 nodes can have service-level etcd failures and the cluster should remain available. If the Etcd failure is on the current leader, a PostgreSQL failover will occur. ### Leaderl Leaderl is responsible for ensuring that leadership is assigned to a node that can resolve all requests. If Leaderl fails on the leader node, it will be unable to respond to failures in the PostgreSQL service. The other nodes in the cluster will detect Leaderl’s failure and attempt to take over as leader. However, since Leaderl on the failing node is down, PostgreSQL may still be up and accepting connections. Other Failures -------------- ### Handling nodes reporting `partially_synced: true` When a node starts to sync from a leader, Leaderl will write the following file to disk: ``` /var/opt/chef-backend/leaderl/data/unsynced ``` When the sync completes successfully the file is removed. If the sync fails, the file will remain in place, the node will be placed in a `waiting_for_leader` state, and will report as leader ineligible. The cluster will report an unhealthy status until the issue is resolved. Resolving the issue requires an understanding of what caused the sync failure. One way to determine the cause is by manually running a sync and inspecting the output: ``` chef-backend-ctl stop leaderl PSQL_INTERNAL_OK=true chef-backend-ctl pgsql-follow LEADER_IP --verbose ``` Once you’ve resolved the issue and can run the `pgsql-follow` command successfully, you can manually remove the sentinel file and restart Leaderl: ``` rm /var/opt/chef-backend/leaderl/data/unsynced chef-backend-ctl start leaderl ``` General Follower Recovery Process --------------------------------- Initial attempts to recover should follow this general pattern and use the scenarios and tools shown above to assist in the recovery steps: 1. With the cluster down, take a filesystem level backup of all backend nodes. 2. Check the health of the leader and repair if necessary. If the /var/log/chef-backend/leaderl/current logs do not show leadership changes and the `chef-backend-ctl cluster-status` shows a solid etcd/pgsql leader, then you are good to continue. **Note**: Any leadership repair process is a very dangerous step that can result in data loss. We recommend [opening a ticket with Support](https://www.chef.io/support/) to go over any cluster leadership issue. Any leadership repair process often involves removing an internal pgsql lock file that prevents promotion of what is thought as the last leader. This file is placed automatically by leaderl when it demotes a leader `/var/opt/chef-backend/leaderl/data/no-start-pgsql`. Refer to the [Promoting a Previous Leader section](#promoting-a-previous-leader) for more details. 3. If necessary, promote what is thought as the most recent leader. Refer to the [Promoting a Previous Leader section](#promoting-a-previous-leader) for more detail. 4. Sync the followers from the leader using a full basebackup because the WAL entries have likely already rotated. When the WAL entries have already rotated away, the followers will complain in the `/var/log/chef-backend/postgresql/X.Y/current` logfile about being unable to sync. Using just the –recovery flag will result in timeouts of the `chef-backend-ctl join-cluster` command. It’s impossible for a follower to sync and rejoin while in this state because it doesn’t have current enough info. Below is an example error message highlighting followers being unable to rejoin: ``` 2018-04-25_16:36:29.42242 FATAL: the database system is starting up 2018-04-25_16:36:30.90058 LOG: started streaming WAL from primary at 16F3/2D000000 on timeline 88 2018-04-25_16:36:30.90124 FATAL: could not receive data from WAL stream: ERROR: requested WAL segment 00000058000016F30000002D has already been removed 2018-04-25_16:36:30.90125 ``` In a Chef Backend High Availability deployment, the etcd service is extremely sensitive and can get into a bad state across backend nodes due to disk and/or network latency. When this happens, it is common for the cluster to be unable to automatically failover/recover. To attempt manual recovery on a follower that exhibits the symptoms previously shown, try issuing the following commands on problematic followers that will not sync. **Do this on one follower at a time.** You can check output from the `chef-backend cluster-status` command periodically to watch the state of the cluster change: ``` chef-backend-ctl stop leaderl chef-backend-ctl cluster-status PSQL_INTERNAL_OK=true chef-backend-ctl pgsql-follow --force-basebackup --verbose LAST_LEADER_IP chef-backend-ctl start ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/backend_failure_recovery/Server Tuning ============= [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/server_tuning.md) The server configuration file contains a list of all configuration options that are available for the Chef Infra Server. Some of these values should be modified for large-scale installations. Note This topic contains general information about how settings can be tuned. In many cases, this topic suggests specific values to be used for tuning. That said, every organization and configuration is different, so please don’t hesitate to contact Chef support to discuss your tuning effort so as to help ensure the right value is identified for any particular setting. Customize the Config File ------------------------- The `/etc/opscode/chef-server.rb` file contains all of the non-default configuration settings used by the Chef Infra Server. The default settings are built into the Chef Infra Server configuration and should only be added to the `chef-server.rb` file to apply non-default values. These configuration settings are processed when the `chef-server-ctl reconfigure` command is run. The `chef-server.rb` file is a Ruby file, which means that conditional statements can be used within it. ### Use Conditions Use a `case` statement to apply different values based on whether the setting exists on the front-end or back-end servers. Add code to the server configuration file similar to the following: ``` role_name = ChefServer['servers'][node['fqdn']]['role'] case role_name when 'backend' # backend-specific configuration here when 'frontend' # frontend-specific configuration here end ``` Recommended Settings -------------------- The following settings are typically added to the server configuration file (no equal sign is necessary to set the value): `api_fqdn` The FQDN for the Chef Infra Server. This setting is not in the server configuration file by default. When added, its value should be equal to the FQDN for the service URI used by the Chef Infra Server. For example: `api_fqdn "chef.example.com"`. `bootstrap` Default value: `true`. `ip_version` Use to set the IP version: `"ipv4"` or `"ipv6"`. When set to `"ipv6"`, the API listens on IPv6 and front end and back end services communicate via IPv6 when a high availability configuration is used. When configuring for IPv6 in a high availability configuration, be sure to set the netmask on the IPv6 `backend_vip` attribute. Default value: `"ipv4"`. `notification_email` Default value: `<EMAIL>`. ### SSL Protocols The following settings are often modified from the default as part of the tuning effort for the **nginx** service and to configure the Chef Infra Server to use SSL certificates: `nginx['ssl_certificate']` The SSL certificate used to verify communication over HTTPS. Default value: `nil`. `nginx['ssl_certificate_key']` The certificate key used for SSL communication. Default value: `nil`. `nginx['ssl_ciphers']` The list of supported cipher suites that are used to establish a secure connection. To favor AES256 with ECDHE forward security, drop the `RC4-SHA:RC4-MD5:RC4:RSA` prefix. For example: ``` nginx['ssl_ciphers'] = "HIGH:MEDIUM:!LOW:!kEDH: \ !aNULL:!ADH:!eNULL:!EXP: \ !SSLv2:!SEED:!CAMELLIA: \ !PSK" ``` `nginx['ssl_protocols']` The SSL protocol versions that are enabled for the Chef Infra Server API. For enhanced security set this value to `'TLSv1.2'`. TLS 1.2 is supported on Chef Infra Client 10.16.4 and later on Linux, Unix, and macOS, and on Chef Infra Client 12.8 and later on Windows. If it is necessary to support these older end-of-life Chef Infra Client releases, set this value to `'TLSv1.1 TLSv1.2'`. For example: ``` nginx['ssl_protocols'] = 'TLSv1.2' ``` Note See <https://www.openssl.org/docs/man1.0.2/man1/ciphers.html> for more information about the values used with the `nginx['ssl_ciphers']` and `nginx['ssl_protocols']` settings. For example, after copying the SSL certificate files to the Chef Infra Server, update the `nginx['ssl_certificate']` and `nginx['ssl_certificate_key']` settings to specify the paths to those files, and then (optionally) update the `nginx['ssl_ciphers']` and `nginx['ssl_protocols']` settings to reflect the desired level of hardness for the Chef Infra Server: ``` nginx['ssl_certificate'] = '/etc/pki/tls/private/name.of.pem' nginx['ssl_certificate_key'] = '/etc/pki/tls/private/name.of.key' nginx['ssl_ciphers'] = 'HIGH:MEDIUM:!LOW:!kEDH:!aNULL:!ADH:!eNULL:!EXP:!SSLv2:!SEED:!CAMELLIA:!PSK' nginx['ssl_protocols'] = 'TLSv1 TLSv1.1 TLSv1.2' ``` Optional Services Tuning ------------------------ The following settings are often used to for performance tuning of the Chef Infra Server in larger installations. Note When changes are made to the chef-server.rb file the Chef Infra Server must be reconfigured by running the following command: ``` chef-server-ctl reconfigure ``` ### bookshelf The following setting is often modified from the default as part of the tuning effort for the **bookshelf** service: `bookshelf['vip']` The virtual IP address. Default value: `node['fqdn']`. ### opscode-erchef The following settings are often modified from the default as part of the tuning effort for the **opscode-erchef** service: `opscode_erchef['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. If failures indicate that the **opscode-erchef** service ran out of connections, try increasing the `postgresql['max_connections']` setting. If failures persist, then increase this value (in small increments) and also increase the value for `postgresql['max_connections']`. Default value: `20`. `opscode_erchef['s3_url_ttl']` The amount of time (in seconds) before connections to the server expire. If Chef Infra Client runs are timing out, increase this setting to `3600`, and then adjust again if necessary. Default value: `900`. `opscode_erchef['strict_search_result_acls']` Use to specify that search results only return objects to which an actor (user, client, etc.) has read access, as determined by ACL settings. This affects all searches. When `true`, the performance of the Chef management console may increase because it enables the Chef management console to skip redundant ACL checks. To ensure the Chef management console is configured properly, after this setting has been applied with a `chef-server-ctl reconfigure` run `chef-manage-ctl reconfigure` to ensure the Chef management console also picks up the setting. Default value: `false`. Warning When `true`, `opscode_erchef['strict_search_result_acls']` affects all search results and any actor (user, client, etc.) that does not have read access to a search result will not be able to view it. For example, this could affect search results returned during a Chef Infra Client runs if a Chef Infra Client does not have permission to read the information. ### postgresql The following setting is often modified from the default as part of the tuning effort for the **postgresql** service: `postgresql['max_connections']` The maximum number of allowed concurrent connections. This value should only be tuned when the `opscode_erchef['db_pool_size']` value used by the **opscode-erchef** service is modified. Default value: `350`. If there are more than two front end machines in a cluster, the `postgresql['max_connections']` setting should be increased. The increased value depends on the number of machines in the front end, but also the number of services that are running on each of these machines. * Each front end machine always runs the **oc_bifrost** and **opscode-erchef** services. * The Reporting add-on adds the **reporting** service. Each of these services requires 25 connections, above the default value. Use the following formula to help determine what the increased value should be: ``` new_value = current_value + [ (# of front end machines - 2) * (25 * # of services) ] ``` For example, if the current value is 350, there are four front end machines, and all add-ons are installed, then the formula looks like: ``` 550 = 350 + [(4 - 2) * (25 * 4)] ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/server_tuning/chef-server.rb Optional Settings ================================ Version: Chef Infra Server 14 Chef Infra Server 13.2 [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/v14/config_rb_server_optional_settings.md) The `/etc/opscode/chef-server.rb` file contains all of the non-default configuration settings used by the Chef Infra Server. The default settings are built into the Chef Infra Server configuration and should only be added to the `chef-server.rb` file to apply non-default values. These configuration settings are processed when the `chef-server-ctl reconfigure` command is run. The `chef-server.rb` file is a Ruby file, which means that conditional statements can be used within it. Settings -------- The following sections describe the various settings that are available in the chef-server.rb file. Note When changes are made to the chef-server.rb file the Chef Infra Server must be reconfigured by running the following command: ``` chef-server-ctl reconfigure ``` ### General This configuration file has the following general settings: `addons['install']` Default value: `false`. `addons['path']` Default value: `nil`. `addons['packages']` Default value: ``` %w{chef-manage} ``` `api_version` The version of the Chef Infra Server. Default value: `'12.0.0'`. `default_orgname` The `ORG_NAME` part of the `/organizations` endpoint in Chef Infra Server. `flavor` Default value: `'cs'`. `fips` Set to `true` to run the server in FIPS compliance mode. Set to `false` to force the server to run without FIPS compliance mode. Default: The value in the kernel configuration. Note Chef Infra Server versions earlier than 14.5 configured with `nginx['enable_non_ssl'] = false` and `fips = true` require `export CSC_LB_URL=https://127.0.0.1` to run the command `chef-server-ctl reindex <options>` `insecure_addon_compat` Set to `true` to keep Chef Infra Server compatible with older add-on versions by rendering secrets and credentials to `/etc/opscode/chef-server-running.json` and other files in `/etc/opscode/`. When set to `false`, secrets are **only** written to `/etc/opscode/private-chef-secrets.json` and **not** to any other files. Default value: `true`. See [Add-on Compatibility](../server_security/index#add-on-compatibility) for the minimum add-on versions supporting `insecure_addon_compat false`. `install_path` The directory in which the Chef Infra Server is installed. Default value: `'/opt/opscode'`. `from_email` The email address from which invitations to the Chef management console are sent. Default value: `'"Opscode" <<EMAIL>>'`. `license['nodes']` The number of licensed nodes. Default value: `25`. `license['upgrade_url']` The URL to visit for more information about how to update the number of nodes licensed for an organization. Default value: `'https://www.chef.io/pricing'`. `notification_email` The email addressed to which email notifications are sent. Default value: `'<EMAIL>'`. `role` The configuration type of the Chef Infra Server. Possible values: `backend`, `frontend`, or `standalone`. Default value: `'standalone'`. `topology` The topology of the Chef Infra Server. Possible values: `manual`, `standalone`, and `tier`. Default value: `'standalone'`. ### bookshelf The **bookshelf** service is an Amazon Simple Storage Service (S3)-compatible service that is used to store cookbooks, including all of the files—recipes, templates, and so on—that are associated with each cookbook. Note To [configure the server for external cookbook storage](../index#aws-settings), updates are made to settings for both the **bookshelf** and **opscode-erchef** services. This configuration file has the following settings for `bookshelf`: `bookshelf['access_key_id']` Deprecated. Use `chef-server-ctl set-secret bookshelf access_key_id` from the [Secrets Management](../ctl_chef_server/index#secrets-management) commands. The access key identifier. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../index#aws-settings) for more information on configuring external bookshelf. Default value: **generated**. `bookshelf['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `/var/opt/opscode/bookshelf/data`. `bookshelf['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/bookshelf`. `bookshelf['enable']` Enable a service. Default value: `true`. `bookshelf['enable_request_logging']` Use to configure request logging for the bookshelf service. Default value: `false`. `bookshelf['external_url']` The base URL to which the service is to return links to API resources. Use `:host_header` to ensure the URL is derived from the host header of the incoming HTTP request. Default value: `:host_header`. `bookshelf['listen']` The IP address on which the service is to listen. Default value: `127.0.0.1`. `bookshelf['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/bookshelf`. `bookshelf['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `bookshelf['port']` The port on which the service is to listen. Default value: `4321`. `bookshelf['secret_access_key']` Deprecated. Use `chef-server-ctl set-secret bookshelf secret_access_key` from the [Secrets Management](../ctl_chef_server/index#secrets-management) commands. The secret key. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../index#aws-settings) for more information on configuring external bookshelf. Default value: **generated**. `bookshelf['storage_type']` Determines where cookbooks are stored. Default value: `:filesystem`. In instances that require cookbooks to be stored within a SQL backend, such as in a high availability setup, you must set `storage_type` to `:sql`: ``` bookshelf['storage_type'] = :sql ``` `bookshelf['stream_download']` Enable stream downloading of cookbooks. This setting (when `true`) typically results in improved cookbook download performance, especially with the memory usage of the **bookshelf** service and the behavior of load balancers and proxies in-between Chef Infra Client and the Chef Infra Server. Default value: `true`. `bookshelf['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `bookshelf['sql_user']` (default: `'bookshelf'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `bookshelf['sql_user']`. Default value: `nil`. `bookshelf['vip']` The virtual IP address. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../index#aws-settings) for more information on configuring external bookshelf. Default value: `127.0.0.1`. ### bootstrap This configuration file has the following settings for `bootstrap`: `bootstrap['enable']` Indicates whether an attempt to bootstrap the Chef Infra Server is made. Generally only enabled on systems that have bootstrap enabled via a `server` entry. Default value: `true`. ### compliance forwarding The configuration file has the following settings for forwarding `compliance` requests using the Chef Infra Server authentication system. `profiles['root_url']` If set, any properly signed requests arriving at `/organizations/ORGNAME/owners/OWNER/compliance` will be forwarded to this URL. This is expected to be a fully qualified resource, e.g. `http://compliance.example.org/owners/OWNER/compliance`. ### dark_launch This configuration file has the following settings for `dark_launch`: `dark_launch['actions']` Enable Chef actions. Default value: `true`. `dark_launch['add_type_and_bag_to_items']` Default value: `true`. `dark_launch['new_theme']` Default value: `true`. `dark_launch['private-chef']` Default value: `true`. `dark_launch['quick_start']` Default value: `false`. `dark_launch['reporting']` Enable Reporting, which performs data collection during a Chef Infra Client run. Default value: `true`. `dark_launch['sql_users']` Default value: `true`. ### data_collector This configuration file has the following settings for `data_collector`: `data_collector['root_url']` The fully qualified URL to the data collector server API. When present, it will enable the data collector in **opscode-erchef**. This also enables Chef Infra Server authenticated forwarding any properly signed requests arriving at `/organizations/ORGNAME/data-collector` to this URL with the data collector token appended. This is also target for requests authenticated and forwarded by the `/organizations/ORGNAME/data-collector` endpoint. For the forwarding to work correctly the `data_collector['token']` field must also be set. For example, if the data collector in Chef Automate is being used, the URI would look like: `http://my_automate_server.example.org/data-collector/v0/`. `data_collector['proxy']` If set to `true`, Chef Infra Server will proxy all requests sent to `/data-collector` to the configured Chef Automate `data_collector['root_url']`. Note that *this route* does not check the request signature and add the right data_collector token, but just proxies the Chef Automate endpoint **as-is**. Default value: `nil`. `data_collector['token']` Deprecated. Use `chef-server-ctl set-secret data_collector token` from the [Secrets Management](../ctl_chef_server/index#secrets-management) commands. Legacy configuration for shared data collector security token. When configured, the token will be passed as an HTTP header named `x-data-collector-token` which the server can choose to accept or reject. `data_collector['timeout']` The amount of time (in milliseconds) before a request to the data collector API times out. Default value: 30000. `data_collector['http_init_count']` The initial worker count for the HTTP connection pool that is used by the data collector. Default value: 25. `data_collector['http_max_count']` The maximum worker count for the HTTP connection pool that is used by the data collector. Default value: 100. `data_collector['http_max_age']` The maximum connection worker age (in seconds) for the HTTP connection pool that is used by the data collector. Default value: "{70, sec}". `data_collector['http_cull_interval']` The maximum cull interval (in minutes) for the HTTP connection pool that is used by the data collector. Default value: "{1, min}". `data_collector['http_max_connection_duration']` The maximum connection duration (in seconds) for the HTTP connection pool that is used by the data collector. Default value: "{70, sec}". `data_collector['ibrowse_options']` An array of comma-separated key-value pairs of ibrowse options for the HTTP connection pool that is used by the data collector. Default value: "[{connect_timeout, 10000}]". `data_collector['health_check']` A boolean that controls whether the data collector health is included in the overall health at the `_status` endpoint. When set to `true`, Chef Infra Server will report that healthy front end Chef HA cluster members have failed when the data_collector[‘root_url’] cannot be reached. As a result, the load balancer will remove those members from the load balancer pool. Default value: true`. ### estatsd This configuration file has the following settings for `estatsd`: `estatsd['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/estatsd'`. `estatsd['enable']` Enable a service. Default value: `true`. `estatsd['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/log/opscode/estatsd'`. `estatsd['port']` The port on which the service is to listen. Default value: `9466`. `estatsd['protocol']` Use to send application statistics with StatsD protocol formatting. Set this value to `statsd` to apply StatsD protocol formatting. `estatsd['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### lb / lb_internal This configuration file has the following settings for `lb`: `lb['api_fqdn']` Default value: `node['fqdn']`. `lb['ban_refresh_interval']` Default value: `600`. `lb['bookshelf']` Default value: `127.0.0.1`. `lb['cache_cookbook_files']` Default value: `false`. `lb['chef_max_version']` The maximum version of Chef Infra Client that is allowed to access the Chef Infra Server via the Chef Infra Server API. Default value: `11`. `lb['chef_min_version']` The minimum version of Chef Infra Client that is allowed to access the Chef Infra Server via the Chef Infra Server API. Default value: `10`. `lb['chef_server_webui']` Default value: `127.0.0.1`. `lb['debug']` Default value: `false`. `lb['enable']` Enable a service. Default value: `true`. `lb['erchef']` Default value: `127.0.0.1`. `lb['maint_refresh_interval']` Default value: `600`. `lb['redis_connection_pool_size']` Default value: `250`. `lb['redis_connection_timeout']` The amount of time (in milliseconds) to wait before timing out. Default value: `1000`. `lb['redis_keepalive_timeout']` The amount of time (in milliseconds) to wait before timing out. Default value: `2000`. `lb['upstream']['bookshelf']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['oc_bifrost']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['opscode_erchef']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['opscode_solr4']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['vip']` The virtual IP address. Default value: `127.0.0.1`. `lb['web_ui_fqdn']` Default value: `node['fqdn']`. `lb['xdl_defaults']['503_mode']` The default value is the recommended value. Default value: `false`. `lb['xdl_defaults']['couchdb_acls']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_association_requests']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_associations']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_containers']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_groups']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_organizations']` The default value is the recommended value. Default value: `true`. And for the internal load balancers: `lb_internal['account_port']` Default value: `9685`. `lb_internal['chef_port']` Default value: `9680`. `lb_internal['enable']` Default value: `true`. `lb_internal['oc_bifrost_port']` Default value: `9683`. `lb_internal['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### ldap Warning The following settings **MUST** be in the config file for LDAP authentication to Active Directory to work: * `base_dn` * `bind_dn` * `group_dn` * `host` If those settings are missing, you will get authentication errors and be unable to proceed. This configuration file has the following settings for `ldap`: `ldap['base_dn']` The root LDAP node under which all other nodes exist in the directory structure. For Active Directory, this is typically `cn=users` and then the domain. For example: ``` 'OU=Employees,OU=Domain users,DC=example,DC=com' ``` Default value: `nil`. `ldap['bind_dn']` The distinguished name used to bind to the LDAP server. The user the Chef Infra Server will use to perform LDAP searches. This is often the administrator or manager user. This user needs to have read access to all LDAP users that require authentication. The Chef Infra Server must do an LDAP search before any user can log in. Many Active Directory and LDAP systems do not allow an anonymous bind. If anonymous bind is allowed, leave the `bind_dn` and `bind_password` settings blank. If anonymous bind is not allowed, a user with `READ` access to the directory is required. This user must be specified as an LDAP distinguished name similar to: ``` 'CN=user,OU=Employees,OU=Domainuser,DC=example,DC=com' ``` Note If you need to escape characters in a distinguished name, such as when using Active Directory, they must be [escaped with a backslash escape character](https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx). ``` 'CN=example\\user,OU=Employees,OU=Domainuser,DC=example,DC=com' ``` Default value: `nil`. `ldap['bind_password']` Deprecated. Use `chef-server-ctl set-secret ldap bind_password` from the [Secrets Management](../../ctl_chef_server#ctl-chef-server-secrets-management) commands. Legacy configuration for the password of the binding user. The password for the user specified by `ldap['bind_dn']`. Leave this value and `ldap['bind_dn']` unset if anonymous bind is sufficient. Default value: `nil`. ``` chef-server-ctl set-secret ldap bind_password Enter ldap bind_password: (no terminal output) Re-enter ldap bind_password: (no terminal output) ``` Remove a set password via ``` chef-server-ctl remove-secret ldap bind_password ``` `ldap['group_dn']` The distinguished name for a group. When set to the distinguished name of a group, only members of that group can log in. This feature filters based on the `memberOf` attribute and only works with LDAP servers that provide such an attribute. In OpenLDAP, the `memberOf` overlay provides this attribute. For example, if the value of the `memberOf` attribute is `CN=abcxyz,OU=users,DC=company,DC=com`, then use: ``` ldap['group_dn'] = 'CN=abcxyz,OU=users,DC=company,DC=com' ``` `ldap['host']` The name (or IP address) of the LDAP server. The hostname of the LDAP or Active Directory server. Be sure the Chef Infra Server is able to resolve any host names. Default value: `ldap-server-host`. `ldap['login_attribute']` The LDAP attribute that holds the user’s login name. Use to specify the Chef Infra Server user name for an LDAP user. Default value: `sAMAccountName`. `ldap['port']` An integer that specifies the port on which the LDAP server listens. The default value is an appropriate value for most configurations. Default value: `389` or `636` when `ldap['encryption']` is set to `:simple_tls`. `ldap['ssl_enabled']` Cause the Chef Infra Server to connect to the LDAP server using SSL. Default value: `false`. Must be `false` when `ldap['tls_enabled']` is `true`. Note It’s recommended that you enable SSL for Active Directory. Note Previous versions of the Chef Infra Server used the `ldap['ssl_enabled']` setting to first enable SSL, and then the `ldap['encryption']` setting to specify the encryption type. These settings are deprecated. `ldap['system_adjective']` A descriptive name for the login system that is displayed to users in the Chef Infra Server management console. If a value like “corporate” is used, then the Chef management console user interface will display strings like “the corporate login server”, “corporate login”, or “corporate password.” Default value: `AD/LDAP`. Warning This setting is **not** used by the Chef Infra Server. It is used only by the Chef management console. `ldap['timeout']` The amount of time (in seconds) to wait before timing out. Default value: `60000`. `ldap['tls_enabled']` Enable TLS. When enabled, communication with the LDAP server is done via a secure SSL connection on a dedicated port. When `true`, `ldap['port']` is also set to `636`. Default value: `false`. Must be `false` when `ldap['ssl_enabled']` is `true`. Note Previous versions of the Chef Infra Server used the `ldap['ssl_enabled']` setting to first enable SSL, and then the `ldap['encryption']` setting to specify the encryption type. These settings are deprecated. ### nginx This configuration file has the following settings for `nginx`: `nginx['cache_max_size']` The `max_size` parameter used by the Nginx cache manager, which is part of the `proxy_cache_path` directive. When the size of file storage exceeds this value, the Nginx cache manager removes the least recently used data. Default value: `5000m`. `nginx['client_max_body_size']` The maximum accepted body size for a client request, as indicated by the `Content-Length` request header. Default value: `250m`. `nginx['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/nginx`. `nginx['enable']` Enable a service. Default value: `true`. `nginx['enable_ipv6']` Enable Internet Protocol version 6 (IPv6) addresses. Default value: `false`. `nginx['enable_non_ssl']` Allow port 80 redirects to port 443. Set to `true`, to enable SSL termination by the front-end hardware load balancers for WebUI and API endpoints. Default value: `false`. Note Chef Infra Server versions earlier than 14.5 configured with `nginx['enable_non_ssl'] = false` and `fips = true` require `export CSC_LB_URL=https://127.0.0.1` to run the command `chef-server-ctl reindex <options>` `nginx['enable_stub_status']` Enables the Nginx `stub_status` module. See `nginx['stub_status']['allow_list']`, `nginx['stub_status']['listen_host']`, `nginx['stub_status']['listen_port']`, and `nginx['stub_status']['location']`. Default value: `true`. `nginx['gzip']` Enable gzip compression. Default value: `on`. `nginx['gzip_comp_level']` The compression level used with gzip, from least amount of compression (`1`, fastest) to the most (`2`, slowest). Default value: `2`. `nginx['gzip_http_version']` Enable gzip depending on the version of the HTTP request. Default value: `1.0`. `nginx['gzip_proxied']` The type of compression used based on the request and response. Default value: `any`. `nginx['gzip_types']` Enable compression for the specified MIME-types. Default value: ``` [ 'text/plain', 'text/css', 'application/x-javascript', 'text/xml', 'application/xml', 'application/xml+rss', 'text/javascript', 'application/json' ] ``` `nginx['keepalive_timeout']` The amount of time (in seconds) to wait for requests on a HTTP keepalive connection. Default value: `65`. `nginx['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/nginx`. `nginx['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `nginx['log_x_forwarded_for']` Log $http_x_forwarded_for (“X-Forwarded-For”) instead of $remote_addr if `true`. Default value `false`. `nginx['non_ssl_port']` The port on which the WebUI and API are bound for non-SSL connections. Default value: `80`. Use `nginx['enable_non_ssl']` to enable or disable SSL redirects on this port number. Set to `false` to disable non-SSL connections. `nginx['sendfile']` Copy data between file descriptors when `sendfile()` is used. Default value: `on`. `nginx['server_name']` The FQDN for the server. Default value: `node['fqdn']`. `nginx['ssl_certificate']` The SSL certificate used to verify communication over HTTPS. Default value: `nil`. `nginx['ssl_certificate_key']` The certificate key used for SSL communication. Default value: `nil`. `nginx['ssl_ciphers']` The list of supported cipher suites that are used to establish a secure connection. To favor AES256 with ECDHE forward security, drop the `RC4-SHA:RC4-MD5:RC4:RSA` prefix. See [this link](https://www.openssl.org/docs/man1.0.2/man1/ciphers.html) for more information. For example: ``` nginx['ssl_ciphers'] = HIGH: ... :!PSK ``` `nginx['ssl_company_name']` The name of your company. Default value: `YouCorp`. `nginx['ssl_country_name']` The country in which your company is located. Default value: `US`. `nginx['ssl_email_address']` The default email address for your company. Default value: `<EMAIL>`. `nginx['ssl_locality_name']` The city in which your company is located. Default value: `Seattle`. `nginx['ssl_organizational_unit_name']` The organization or group within your company that is running the Chef Infra Server. Default value: `Operations`. `nginx['ssl_port']` Default value: `443`. `nginx['ssl_protocols']` The SSL protocol versions that are enabled for the Chef Infra Server API. Starting with Chef Infra Server 14.3, this value defaults to `'TLSv1.2'` for enhanced security. Previous releases defaulted to `'TLSv1 TLSv1.1 TLSv1.2'`, which allowed for less secure SSL connections. TLS 1.2 is supported on Chef Infra Client 10.16.4 and later on Linux, Unix, and macOS, and on Chef Infra Client 12.8 and later on Windows. If it is necessary to support these older end-of-life Chef Infra Client releases, set this value to `'TLSv1.1 TLSv1.2'`. ``` nginx['ssl_protocols'] = 'TLSv1.2' ``` Default value: `TLSv1.2`. `nginx['ssl_state_name']` The state, province, or region in which your company is located. Default value: `WA`. `nginx['strict_host_header']` Whether nginx should only respond to requests where the Host header matches one of the configured FQDNs. Default value: `false`. `nginx['stub_status']['allow_list']` The IP address on which accessing the `stub_status` endpoint is allowed. Default value: `["127.0.0.1"]`. `nginx['stub_status']['listen_host']` The host on which the Nginx `stub_status` module listens. Default value: `"127.0.0.1"`. `nginx['stub_status']['listen_port']` The port on which the Nginx `stub_status` module listens. Default value: `"9999"`. `nginx['stub_status']['location']` The name of the Nginx `stub_status` endpoint used to access data generated by the Nginx `stub_status` module. Default value: `"/nginx_status"`. `nginx['tcp_nodelay']` Enable the Nagle buffering algorithm. Default value: `on`. `nginx['tcp_nopush']` Enable TCP/IP transactions. Default value: `on`. `nginx["time_format"]` The time format of nginx `access.log`. Possible values : `"time_iso8601"` (ex: [2020-10-21T07:22:00+00:00]), `"time_local"` (ex: [07/Jun/2018:01:05:11 +0900]). Default value : `"time_iso8601"`. **New in Chef Infra Server 14.1** `nginx['url']` Default value: `https://#{node['fqdn']}`. `nginx['use_implicit_hosts']` Automatically add localhost and any local IP addresses to the configured FQDNs. Useful in combination with `nginx['strict_host_header']`. Default value: `true`. `nginx['show_welcome_page']` Determines whether or not the default nginx welcome page is shown. Default value: `true`. `nginx['worker_connections']` The maximum number of simultaneous clients. Use with `nginx['worker_processes']` to determine the maximum number of allowed clients. Default value: `10240`. `nginx['worker_processes']` The number of allowed worker processes. Use with `nginx['worker_connections']` to determine the maximum number of allowed clients. Default value: `node['cpu']['total'].to_i`. `nginx['x_forwarded_proto']` The protocol used to connect to the server. Possible values: `http` and `https`. This is the protocol used to connect to the Chef Infra Server by a Chef Infra Client or a workstation. Default value: `'https'`. `nginx['hsts_max_age']` Time duration in seconds till which the browser caches the `HSTS` information. Possible values: greater than or equal to `31536000` and less than or equal to `63072000`. Default value: `31536000` (1 year). `nginx['nginx_no_root']` Boolean, default `false`. Specifies that `nginx` processes, including the `master` process, should not run as the `root` user on a system and will instead run as `user['username']` (defaults to `opscode`). **REQUIRES** that `nginx['ssl_port']` and `nginx['non_ssl_port']` options are configured to non-privileged ports greater than `1024` or that the local system is otherwise allowed to bind to privileged ports with the user `user['username']`. **New in Chef Infra Server 14.10* ### oc_bifrost The **oc_bifrost** service ensures that every request to view or manage objects stored on the Chef Infra Server is authorized. This configuration file has the following settings for `oc_bifrost`: `oc_bifrost['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. This value should be increased if failures indicate that the **oc_bifrost** service ran out of connections. This value should be tuned in conjunction with the `postgresql['max_connections']` setting for PostgreSQL. Default value: `20`. `oc_bifrost['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/oc_bifrost`. `oc_bifrost['enable']` Enable a service. Default value: `true`. `oc_bifrost['enable_request_logging']` Use to configure request logging for the `oc_bifrost` service. Default value: `true`. `oc_bifrost['extended_perf_log']` Default value: `true`. `oc_bifrost['listen']` The IP address on which the service is to listen. Default value: `'127.0.0.1'`. `oc_bifrost['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/oc_bifrost`. `oc_bifrost['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `oc_bifrost['port']` The port on which the service is to listen. Default value: `9463`. `oc_bifrost['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `oc_bifrost['sql_user']` (default: `'bifrost'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_bifrost['sql_user']`. Default value: `nil`. `oc_bifrost['sql_password']` The password for the `sql_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_bifrost sql_password`. `oc_bifrost['sql_ro_password']` The password for the `sql_ro_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_bifrost sql_ro_password`. `oc_bifrost['sql_ro_user']` Default value: `'bifrost_ro'`. `oc_bifrost['sql_user']` The user with permission to publish data. Default value: `'bifrost'`. `oc_bifrost['superuser_id']` Default value: **generated**. `oc_bifrost['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### oc_chef_authz The **opscode-authz** service is used to handle authorization requests from oc_erchef to oc_bifrost in the Chef Infra Server. This configuration file has the following settings for `oc_chef_authz`: `oc_chef_authz['http_cull_interval']` Default value: `'{1, min}'`. `oc_chef_authz['http_init_count']` Default value: `25`. `oc_chef_authz['http_max_age']` Default value: `'{70, sec}'`. `oc_chef_authz['http_max_connection_duration']` Default value: `'{70, sec}'`. `oc_chef_authz['http_max_count']` Default value: `100`. `oc_chef_authz['ibrowse_options']` The amount of time (in milliseconds) to wait for a connection to be established. Default value: `'[{connect_timeout, 5000}]'`. `oc_chef_authz['max_connection_request_limit']` The maximum number of requests allowed per connection. Default value: `100`. ### oc-chef-pedant This configuration file has the following settings for `oc-chef-pedant`: `oc_chef_pedant['debug_org_creation']` Run tests with full output. Default value: `false`. `oc_chef_pedant['dir']` The working directory. The default value is the recommended value. Default value: ``` '/var/opt/opscode/oc-chef-pedant' ``` `oc_chef_pedant['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` '/var/log/opscode/oc-chef-pedant' ``` `oc_chef_pedant['log_http_requests']` Log HTTP requests in a file named `http-traffic.log` that is located in the path specified by `log_directory`. Default value: `true`. `oc_chef_pedant['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` ### oc-id The **oc-id** service enables OAuth 2.0 authentication to the Chef Infra Server by external applications, including Chef Supermarket. OAuth 2.0 uses token-based authentication, where external applications use tokens that are issued by the **oc-id** provider. No special credentials—`webui_priv.pem` or privileged keys—are stored on the external application. This configuration file has the following settings for `oc-id`: `oc_id['administrators']` An array of Chef Infra Server user names who may add applications to the identity service. For example, `['user1', 'user2']`. Default value: `[ ]`. `oc_id['applications']` A Hash that contains OAuth 2 application information. Default value: `{ }`. To define OAuth 2 information for Chef Supermarket, create a Hash similar to: ``` oc_id['applications'] ||= {} oc_id['applications']['supermarket'] = { 'redirect_uri' => 'https://supermarket.mycompany.com/auth/chef_oauth2/callback', } ``` `oc_id['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `'20'`. `oc_id['dir']` The working directory. The default value is the recommended value. Default value: none. `oc_id['enable']` Enable a service. Default value: `true`. `oc_id['email_from_address']` Outbound email address. Defaults to the `'from_email'` value. `oc_id['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/opt/opscode/oc_id'`. `oc_id['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `oc_id['origin']` The FQDN for the server that is sending outbound email. Defaults to the `'api_fqdn'` value, which is the FQDN for the Chef Infra Server. `oc_id['num_to_keep']` The number of log files to keep. Default value: `10`. `oc_id['port']` The port on which the service is to listen. Default value: `9090`. `oc_id['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'oc_id@my_postgresql.postgres.database.azure.com'`), where `username` would normally equal the value of `oc_id['sql_user']` (default: `'od_id'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_id['sql_user']`. Default value: `nil`. `oc_id['sql_database']` The name of the database. Default value: `oc_id`. `oc_id['sql_password']` The password for the `sql_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_id sql_password`. `oc_id['sql_user']` The user with permission to write to `sql_database`. Default value: `oc_id`. `oc_id['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### opscode-chef-mover This configuration file has the following settings for `opscode-chef-mover`: `opscode_chef_mover['bulk_fetch_batch_size']` Default value: `'5'`. `opscode_chef_mover['cache_ttl']` Default value: `'3600'`. `opscode_chef_mover['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `'5'`. `opscode_chef_mover['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: ``` '/var/opt/opscode/opscode-chef-mover/data' ``` `opscode_chef_mover['dir']` The working directory. The default value is the recommended value. Default value: ``` '/var/opt/opscode/opscode-chef-mover' ``` `opscode_chef_mover['enable']` Enable a service. Default value: `true`. `opscode_chef_mover['ibrowse_max_pipeline_size']` Default value: `1`. `opscode_chef_mover['ibrowse_max_sessions']` Default value: `256`. `opscode_chef_mover['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` '/var/log/opscode/opscode-chef-mover' ``` `opscode_chef_mover['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_chef_mover['max_cache_size']` Default value: `'10000'`. `opscode_chef_mover['solr_http_cull_interval']` Default value: `'{1, min}'`. `opscode_chef_mover['solr_http_init_count']` Default value: `25`. `opscode_chef_mover['solr_http_max_age']` Default value: `'{70, sec}'`. `opscode_chef_mover['solr_http_max_connection_duration']` Default value: `'{70, sec}'`. `opscode_chef_mover['solr_http_max_count']` Default value: `100`. `opscode_chef_mover['solr_ibrowse_options']` Default value: `'[{connect_timeout, 10000}]'`. `opscode_chef_mover['solr_timeout']` Default value: `30000`. ### opscode-erchef The **opscode-erchef** service is an Erlang-based service that is used to handle Chef Infra Server API requests to the following areas within the Chef Infra Server: * Cookbooks * Data bags * Environments * Nodes * Roles * Sandboxes * Search This configuration file has the following settings for `opscode-erchef`: `opscode_erchef["allow_email_update_only_from_manage"]` Set to `true`, users can only update their email from the Chef management console. Set to `false`, users can update their email using knife and the Chef management console. Default value : `false`. **New in Chef Infra Server 14.5** `opscode_erchef['auth_skew']` Default value: `900`. `opscode_erchef['authz_fanout']` Default value: `20`. `opscode_erchef['authz_timeout']` The amount of time (in seconds) before a request to the **oc_bifrost** service times out. Default value: `2000`. `opscode_erchef['base_resource_url']` The base URL to which the service is to return links to API resources. Use `:host_header` to ensure the URL is derived from the host header of the incoming HTTP request. Default value: `:host_header`. `opscode_erchef['bulk_fetch_batch_size']` The number of nodes that may be deserialized. Currently only applies to the `/search` endpoint in the Chef Infra Server API. The default value is the recommended value. Default value: `5`. `opscode_erchef['cache_ttl']` Default value: `3600`. `opscode_erchef['cleanup_batch_size']` Default value: `0`. `opscode_erchef['couchdb_max_conn']` Default value: `'100'`. `opscode_erchef['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `20`. `opscode_erchef['depsolver_timeout']` The amount of time (in milliseconds) to wait for cookbook dependency problems to be solved. Default value: `'5000'`. `opscode_erchef['depsolver_worker_count']` The number of Ruby processes for which cookbook dependency problems are unsolved. Use the `pgrep -fl depselector` command to verify the number of depsolver workers that are running. If you are seeing 503 service unavailable errors, increase this value. Default value: `'5'`. `opscode_erchef['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/opscode-erchef`. `opscode_erchef['enable']` Enable a service. Default value: `true`. `opscode_erchef['enable_actionlog']` Use to enable Chef actions, a premium feature of the Chef Infra Server. Default value: `false`. `opscode_erchef['enable_request_logging']` Use to configure request logging for the `opscode_erchef` service. Default value: `true`. `opscode_erchef['ibrowse_max_pipeline_size']` Default value: `1`. `opscode_erchef['ibrowse_max_sessions']` Default value: `256`. `opscode_erchef['enable_ibrowse_traces']` Use to configure ibrowse logging for the `opscode_erchef` service. Default value: `false`. `opscode_erchef["include_version_in_status"]` Set to `true` to include `server_version` as part of the `/_status` endpoint. Default value : `false`. **New in Chef Infra Server 14.1** `opscode_erchef['listen']` The IP address on which the service is to listen. Default value: `127.0.0.1`. `opscode_erchef['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/opscode-erchef`. `opscode_erchef['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_erchef['max_cache_size']` Default value: `10000`. `opscode_erchef['max_request_size']` When the request body size is greater than this value, a `413 Request Entity Too Large` error is returned. Default value: `2000000`. `opscode_erchef['nginx_bookshelf_caching']` Whether Nginx is used to cache cookbooks. When `:on`, Nginx serves up the cached content instead of forwarding the request. Default value: `:off`. `opscode_erchef['port']` The port on which the service is to listen. Default value: `8000`. `opscode_erchef['reindex_batch_size']` The number of items to fetch from the database and send to the search index at a time. Default value: `10`. `opscode_erchef['reindex_sleep_min_ms']` The minimum number of milliseconds to sleep before retrying a failed attempt to index an item. Retries are delayed a random number of miliseconds between `reindex_sleep_min_ms` and `reindex_sleep_max_ms`. Set both this and `reindex_sleep_max_ms` to 0 to retry without delay. Default value: `500` `opscode_erchef['reindex_sleep_max_ms']` The maximum number of milliseconds to sleep before retrying a failed attempt to index an item. Retries are delayed a random number of miliseconds between `reindex_sleep_min_ms` and `reindex_sleep_max_ms`. Set both this and `reindex_sleep_min_ms` to 0 to retry without delay. Default value: `2000` `opscode_erchef['reindex_item_retries']` The number of times to retry sending an object for indexing in the case of failure. Default value: `3` `opscode_erchef['root_metric_key']` Default value: `chefAPI`. `opscode_erchef['s3_bucket']` The name of the Amazon Simple Storage Service (S3) bucket. This may point at external storage locations, such as Amazon EC2. See [AWS external bookshelf settings](../index#aws-settings) for more information on configuring external bookshelf. `opscode_erchef['s3_parallel_ops_fanout']` Default value: `20`. `opscode_erchef['s3_parallel_ops_timeout']` Default value: `5000`. `opscode_erchef['s3_url_expiry_window_size']` The frequency at which unique URLs are generated. This value may be a specific amount of time, i.e. `15m` (fifteen minutes) or a percentage of the value of `s3_url_ttl`, i.e. `10%`. Default value: `:off`. `opscode_erchef['s3_url_ttl']` The amount of time (in seconds) before connections to the server expire. If node bootstraps are timing out, increase this setting. Default value: `28800`. `opscode_erchef['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `opscode-erchef['sql_user']` (default: `'opscode_chef'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `opscode_erchef['sql_user']`.Default value: `nil`. `opscode_erchef['strict_search_result_acls']` Use to specify that search results only return objects to which an actor (user, client, etc.) has read access, as determined by ACL settings. This affects all searches. When `true`, the performance of the Chef management console may increase because it enables the Chef management console to skip redundant ACL checks. To ensure the Chef management console is configured properly, after this setting has been applied with a `chef-server-ctl reconfigure` run `chef-manage-ctl reconfigure` to ensure the Chef management console also picks up the setting. Default value: `false`. Warning When `true`, `opscode_erchef['strict_search_result_acls']` affects all search results and any actor (user, client, etc.) that does not have read access to a search result will not be able to view it. For example, this could affect search results returned during a Chef Infra Client runs if a Chef Infra Client does not have permission to read the information. `opscode_erchef['udp_socket_pool_size']` Default value: `20`. `opscode_erchef['umask']` Default value: `0022`. `opscode_erchef['validation_client_name']` Default value: `chef-validator`. `opscode_erchef['vip']` The virtual IP address. Default value: `127.0.0.1`. `opscode_erchef['cbv_cache_enabled']` Enable cookbook version response caching by setting this to `true`. If you frequently see very long response times from `cookbook_versions` when under load, this is worth enabling. Enabling this makes it possible for a client to receive stale results. When a cookbook is updated in place (without incrementing the version), and the old response has not expired from the cache, the Infra Server will give the old response to the client. Subsequent client runs will receive the updated response. Default value: `false`. `opscode_erchef['cbv_cache_item_ttl']` The minimum time in milliseconds that Chef Infra Server will keep any given cookbook version response in the cache when when `cbv_cache_enabled` is enabled. Default value: `30000`. Note Be careful if increasing this number - requests for a given set of cookbook versions will be stale if the resolved cookbook versions are updated before the cache entry times out. This will not occur if you increment the version of a cookbook with every cookbook update, which is the recommended approach to updating cookbooks. ### Elasticsearch This configuration file has the following settings for `elasticsearch`: `elasticsearch['enable']` Enable a service. Default value: `true`. `elasticsearch['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/elasticsearch` `elasticsearch['data_dir']` :The paths used to store data. Default value: `/var/opt/opscode/elasticsearch/data` `elasticsearch['plugins_directory']` The default location of the plugins directory depends on which package you install. Default value: `/var/opt/opscode/elasticsearch/plugins` `elasticsearch['scripts_directory']` :The default location of the scripts directory depends on which package you install. Default value: `/var/opt/opscode/elasticsearch/scripts` `elasticsearch['temp_directory']` By default, Elasticsearch uses a private temporary directory that the startup script creates immediately below the system temporary directory. Default value: `/var/opt/opscode/elasticsearch/tmp` `elasticsearch['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/elasticsearch` `elasticsearch['log_rotation']['file_maxbytes']` The log rotation policy for this service. Log files are rotated when they exceed file_maxbytes. Default value for ‘file_maxbytes’: `104857600` `elasticsearch['log_rotation']['num_to_keep']` The log rotation policy for this service. The maximum number of log files in the rotation is defined by num_to_keep. Default value for ‘num_to_keep’: => `10` `elasticsearch['vip']` The virtual IP address for the machine on which Apache Solr is running. Default value: `127.0.0.1` `elasticsearch['listen']` The IP address for the machine on which Apache Solr is running. Default value: `127.0.0.1` `elasticsearch['port']` The port on which the service is to listen. Default value: `9200` `elasticsearch['enable_gc_log']` Enable or disable GC logging. Default value: `false` `elasticsearch['initial_cluster_join_timeout']` Default value: `90` `elasticsearch['jvm_opts']` Default values are set based on [JVM configuration options](https://github.com/elastic/elasticsearch/blob/6.8/distribution/src/config/jvm.options). Note Each item in this list will be placed as is into the java_opts config file. Entries are set in chef-server.rb as: ``` elasticsearch.jvm_opts = [ "-xoption1", "-xoption2", ... "optionN" ] ``` `elasticsearch['heap_size']` The amount of memory (in MBs) available to Elasticsearch. If there is not enough memory available, search queries made by nodes to Elasticsearch may fail. The amount of memory that must be available also depends on the number of nodes in the organization, the frequency of search queries, and other characteristics that are unique to each organization. In general, as the number of nodes increases, so does the amount of memory. The default value should work for many organizations with fewer than 25 nodes. For an organization with several hundred nodes, the amount of memory that is required often exceeds 3GB. Default value is is equivalent to 25% of the system memory or 1024 MB, whichever is greater. Note If new_size or heap_size is also specified directly in java_opts, it will be ignored in favor of the chef-server.rb values or the defaults as calculated here. Only use chef-server.rb to set heap and new sizes. Learn more about [Elasticsearch heap-size](https://www.elastic.co/guide/en/elasticsearch/reference/current/heap-size.html). It will error out if the system memory is less than 4 GB. This value is bounded between 1 GB - 28 GB. `elasticsearch['new_size']` Defaults to the larger of 1/16th the heap_size and 32 MB. Note If new_size or heap_size is also specified directly in java_opts, it will be ignored in favor of the chef-server.rb values or the defaults as calculated here. Only use chef-server.rb to set heap and new sizes. Learn more about [Elasticsearch heap-size documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/heap-size.html). ### postgresql The **postgresql** service is used to store node, object, and user data. This configuration file has the following settings for `postgresql`: `postgresql['checkpoint_completion_target']` A completion percentage that is used to determine how quickly a checkpoint should finish in relation to the completion status of the next checkpoint. For example, if the value is `0.5`, then a checkpoint attempts to finish before 50% of the next checkpoint is done. Default value: `0.5`. `postgresql['checkpoint_segments']` The maximum amount (in megabytes) between checkpoints in log file segments. Default value: `3`. `postgresql['checkpoint_timeout']` The amount of time (in minutes) between checkpoints. Default value: `5min`. `postgresql['checkpoint_warning']` The frequency (in seconds) at which messages are sent to the server log files if checkpoint segments are being filled faster than their currently configured values. Default value: `30s`. `postgresql['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `/var/opt/opscode/postgresql/#{node['private_chef']['postgresql']['version']}/data`. `postgresql['db_connection_superuser']` The PostgreSQL superuser name in `'username@hostname'` format (e.g. `'<EMAIL>@my_<EMAIL>'`), where `username` would normally equal the value of `postgresql['db_superuser']` with any dashes replaced by underscores. This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `postgresql['db_superuser']`. Default value: `nil`. `postgresql['db_superuser']` Default value: `opscode-pgsql`. If `username` is set, set `db_superuser` to the same value. `postgresql['db_superuser_password']` Password for the DB superuser. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-db-superuser-password`. `postgresql['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/postgresql/#{node['private_chef']['postgresql']['version']}`. `postgresql['effective_cache_size']` The size of the disk cache that is used for data files. Default value: 50% of available RAM. `postgresql['enable']` Enable a service. Default value: `true`. `postgresql['home']` The home directory for PostgreSQL. Default value: `/var/opt/opscode/postgresql`. `postgresql['keepalives_count']` The maximum number of keepalive proves that should be sent before dropping a connection. Default value: `2`. `postgresql['keepalives_idle']` The amount of time (in seconds) a connection must remain idle before keepalive probes will resume. Default value: `60`. `postgresql['keepalives_interval']` The amount of time (in seconds) between probes. Default value: `15`. `postgresql['listen_address']` The connection source to which PostgreSQL is to respond. Default value: `localhost`. `postgresql['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/postgresql/#{node['private_chef']['postgresql']['version']}`. `postgresql['log_min_duration_statement']` When to log a slow PostgreSQL query statement. Possible values: `-1` (disabled, do not log any statements), `0` (log every statement), or an integer greater than zero. When the integer is greater than zero, this value is the amount of time (in milliseconds) that a query statement must have run before it is logged. Default value: `-1`. `postgresql['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `postgresql['max_connections']` The maximum number of allowed concurrent connections. Default value: `350`. `postgresql['md5_auth_cidr_addresses']` Use instead of `trust_auth_cidr_addresses` to encrypt passwords using MD5 hashes. Default value: `[ '127.0.0.1/32', '::1/128' ]`. `postgresql['port']` The port on which the service is to listen. Default value: `5432`. `postgresql['shared_buffers']` The amount of memory that is dedicated to PostgreSQL for data caching. Default value: `#{(node['memory']['total'].to_i / 4) / (1024)}MB`. `postgresql['shell']` Default value: `/bin/sh`. `postgresql['shmall']` The total amount of available shared memory. Default value: `4194304`. `postgresql['shmmax']` The maximum amount of shared memory. Default value: `17179869184`. `postgresql['sslmode']` SSL encryption mode between the Chef Infra Server and PostgreSQL. Valid settings are `'disable'` and `'require'`. Default value: `'disable'`. `postgresql['trust_auth_cidr_addresses']` Use for clear-text passwords. See `md5_auth_cidr_addresses`. Default value: `'127.0.0.1/32', '::1/128'`. `postgresql['user_path']` Default value: `/opt/opscode/embedded/bin:/opt/opscode/bin:$PATH`. `postgresql['username']` The PostgreSQL account user name. Default value: `opscode-pgsql`. If setting this value, must set `db_superuser` to the same value. `postgresql['version']` The (currently) hardcoded version of PostgreSQL. Default value: `'9.2'`. `postgresql['vip']` The virtual IP address. Default value: `127.0.0.1`. `postgresql['work_mem']` The size (in megabytes) of allowed in-memory sorting. Default value: `8MB`. `postgresql['pg_upgrade_timeout']` The timeout value (in seconds) for PostgreSQL upgrade. Default value: `7200`. ### redis_lb Key-value store used in conjunction with Nginx to route requests and populate request data used by the Chef Infra Server. This configuration file has the following settings for `redis_lb`: `redis_lb['activerehashing']` Enable active rehashing. Default value: `'no'`. `redis_lb['aof_rewrite_min_size']` The minimum size of the append-only file. Only files larger than this value are rewritten. Default value: `'16mb'`. `redis_lb['aof_rewrite_percent']` The size of the current append-only file, as compared to the base size. The append-only file is rewritten when the current file exceeds the base size by this value. Default value: `'50'`. `redis_lb['appendfsync']` The frequency at which the operating system writes data on-disk, instead of waiting for more data. Possible values: `no` (don’t fsync, let operating system flush data), `always` (fsync after every write to the append-only log file), and `everysec` (fsync only once time per second). Default value: `'always'`. `redis_lb['appendonly']` Dump data asynchronously on-disk or to an append-only log file. Set to `yes` to dump data to an append-only log file. Default value: `'no'`. `redis_lb['bind']` Bind Redis to the specified IP address. Default value: `'127.0.0.1'`. `redis_lb['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `'/var/opt/opscode/redis_lb/data'`. `redis_lb['databases']` The number of databases. Default value: `'16'`. `redis_lb['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/redis_lb'`. `redis_lb['enable']` Enable a service. Default value: `true`. `redis_lb['ha']` Run the Chef Infra Server in a high availability topology. When `topology` is set to `ha`, this setting defaults to `true`. Default value: `false`. `redis_lb['keepalive']` The amount of time (in seconds) to wait for requests on a connection. Default value: `'60'`. `redis_lb['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/log/opscode/redis_lb'`. `redis_lb['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `redis_lb['loglevel']` The level of logging to be stored in a log file.. Possible values: `debug`, `notice`, `verbose`, and `warning`. Default value: `'notice'`. `redis_lb['maxmemory']` The maximum amount of memory (in bytes). Default value: `'8m'`. `redis_lb['maxmemory_policy']` The policy applied when the maximum amount of memory is reached. Possible values: `allkeys-lru` (remove keys, starting with those used least frequently), `allkeys-random` (remove keys randomly), `noeviction` (don’t expire, return an error on write operation), `volatile-lru` (remove expired keys, starting with those used least frequently), `volatile-random` (remove expired keys randomly), and `volatile-ttl` (remove keys, starting with nearest expired time). Default value: `'noeviction'`. `redis_lb['port']` The port on which the service is to listen. Default value: `'16379'`. `redis_lb['save_frequency']` Set the save frequency. Pattern: `{ "seconds" => "keys", "seconds" => "keys", "seconds" => "keys" }`. Default value: ``` { '900' => '1', '300' => '10', '60' => '1000' } ``` Which saves the database every 15 minutes if at least one key changes, every 5 minutes if at least 10 keys change, and every 60 seconds if 10000 keys change. `redis_lb['timeout']` The amount of time (in seconds) a client may be idle before timeout. Default value: `'300'`. `redis_lb['vip']` The virtual IP address. Default value: `'127.0.0.1'`. `redis_lb['password']` Legacy configuration setting for the Redis password. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret redis_lb password`. ### upgrades This configuration file has the following settings for `upgrades`: `upgrades['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/upgrades'`. ### user This configuration file has the following settings for `user`: `user['home']` The home directory for the user under which Chef Infra Server services run. Default value: `/opt/opscode/embedded`. `user['shell']` The shell for the user under which Chef Infra Server services run. Default value: `/bin/sh`. `user['username']` The user name under which Chef Infra Server services run. Default value: `opscode`. ### required_recipe `required_recipe` is a feature that allows an administrator to specify a recipe that will be run by all Chef Infra Clients that connect to it, regardless of the node’s run list. This feature is targeted at expert level practitioners who are delivering isolated configuration changes to the target systems, such as self-contained agent software. Further explanation of the feature can be found in [Chef Infra Client Development Docs](https://github.com/chef/chef/blob/main/docs/dev/design_documents/server_enforced_recipes.md). This configuration file has the following settings for `required_recipe`: `required_recipe["enable"]` Whether the feature is enabled. Default value: `false`. `required_recipe["path"]` The location of the recipe to serve. The file must be owned by the root user and group, and may not be group or world-writeable. Default value: `nil`. **Note:** You are viewing documentation for an older version of Chef Infra Server. [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/v13_2/config_rb_server_optional_settings.md) The `/etc/opscode/chef-server.rb` file contains all of the non-default configuration settings used by the Chef Infra Server. The default settings are built into the Chef Infra Server configuration and should only be added to the `chef-server.rb` file to apply non-default values. These configuration settings are processed when the `chef-server-ctl reconfigure` command is run. The `chef-server.rb` file is a Ruby file, which means that conditional statements can be used within it. Settings -------- The following sections describe the various settings that are available in the chef-server.rb file. Note When changes are made to the chef-server.rb file the Chef Infra Server must be reconfigured by running the following command: ``` chef-server-ctl reconfigure ``` ### General This configuration file has the following general settings: `addons['install']` Default value: `false`. `addons['path']` Default value: `nil`. `addons['packages']` Default value: ``` %w{chef-manage} ``` `api_version` The version of the Chef Infra Server. Default value: `'12.0.0'`. `default_orgname` The `ORG_NAME` part of the `/organizations` endpoint in Chef Infra Server. `flavor` Default value: `'cs'`. `fips` Set to `true` to run the server in FIPS compliance mode. Set to `false` to force the server to run without FIPS compliance mode. Default: The kernel configuration FIPS value. Note Chef Infra Server versions earlier than 14.5 that are configured with `nginx['enable_non_ssl'] = false` and `fips = true` require `export CSC_LB_URL=https://127.0.0.1` to run the command `chef-server-ctl reindex <options>` `insecure_addon_compat` Set to `true` to keep Chef Infra Server compatible with older add-on versions by rendering secrets and credentials to `/etc/opscode/chef-server-running.json` and other files in `/etc/opscode/`. When set to `false`, secrets are **only** written to `/etc/opscode/private-chef-secrets.json` and **not** to any other files. Default value: `true`. See [Add-on Compatibility](../server_security/index#add-on-compatibility) for the minimum add-on versions supporting `insecure_addon_compat false`. `install_path` The directory in which the Chef Infra Server is installed. Default value: `'/opt/opscode'`. `from_email` The email address from which invitations to the Chef management console are sent. Default value: `'"Opscode" <<EMAIL>>'`. `license['nodes']` The number of licensed nodes. Default value: `25`. `license['upgrade_url']` The URL to visit for more information about how to update the number of nodes licensed for an organization. Default value: `https://www.chef.io/pricing'`. `notification_email` The email addressed to which email notifications are sent. Default value: `'<EMAIL>'`. `role` The configuration type of the Chef Infra Server. Possible values: `backend`, `frontend`, or `standalone`. Default value: `'standalone'`. `topology` The topology of the Chef Infra Server. Possible values: `manual`, `standalone`, and `tier`. Default value: `'standalone'`. ### bookshelf The **bookshelf** service is an Amazon Simple Storage Service (S3)-compatible service that is used to store cookbooks, including all of the files—recipes, templates, and so on—that are associated with each cookbook. Note To [configure the server for external cookbook storage](../index#aws-settings), updates are made to settings for both the **bookshelf** and **opscode-erchef** services. This configuration file has the following settings for `bookshelf`: `bookshelf['access_key_id']` Deprecated. Use `chef-server-ctl set-secret bookshelf access_key_id` from the [Secrets Management](../ctl_chef_server/index#secrets-management) commands. The access key identifier. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../index#aws-settings) for more information on configuring external bookshelf. Default value: **generated**. `bookshelf['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `/var/opt/opscode/bookshelf/data`. `bookshelf['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/bookshelf`. `bookshelf['enable']` Enable a service. Default value: `true`. `bookshelf['enable_request_logging']` Use to configure request logging for the bookshelf service. Default value: `false`. `bookshelf['external_url']` The base URL to which the service is to return links to API resources. Use `:host_header` to ensure the URL is derived from the host header of the incoming HTTP request. Default value: `:host_header`. `bookshelf['listen']` The IP address on which the service is to listen. Default value: `127.0.0.1`. `bookshelf['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/bookshelf`. `bookshelf['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `bookshelf['port']` The port on which the service is to listen. Default value: `4321`. `bookshelf['secret_access_key']` Deprecated. Use `chef-server-ctl set-secret bookshelf secret_access_key` from the [Secrets Management](../ctl_chef_server/index#secrets-management) commands. The secret key. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../index#aws-settings) for more information on configuring external bookshelf. Default value: **generated**. `bookshelf['storage_type']` Determines where cookbooks are stored. Default value: `:filesystem`. In instances that require cookbooks to be stored within a SQL backend, such as in a high availability setup, you must set `storage_type` to `:sql`: ``` bookshelf['storage_type'] = :sql ``` `bookshelf['stream_download']` Enable stream downloading of cookbooks. This setting (when `true`) typically results in improved cookbook download performance, especially with the memory usage of the **bookshelf** service and the behavior of load balancers and proxies in-between Chef Infra Client and the Chef Infra Server. Default value: `true`. `bookshelf['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `bookshelf['sql_user']` (default: `'bookshelf'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `bookshelf['sql_user']`. Default value: `nil`. `bookshelf['vip']` The virtual IP address. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../index#aws-settings) for more information on configuring external bookshelf. Default value: `127.0.0.1`. ### bootstrap This configuration file has the following settings for `bootstrap`: `bootstrap['enable']` Indicates whether an attempt to bootstrap the Chef Infra Server is made. Generally only enabled on systems that have bootstrap enabled via a `server` entry. Default value: `true`. ### compliance forwarding The configuration file has the following settings for forwarding `compliance` requests using the chef server authentication system. `profiles['root_url']` If set, any properly signed requests arriving at `/organizations/ORGNAME/owners/OWNER/compliance` will be forwarded to this URL. This is expected to be a fully qualified resource, e.g. `http://compliance.example.org/owners/OWNER/compliance`. ### dark_launch This configuration file has the following settings for `dark_launch`: `dark_launch['actions']` Enable Chef actions. Default value: `true`. `dark_launch['add_type_and_bag_to_items']` Default value: `true`. `dark_launch['new_theme']` Default value: `true`. `dark_launch['private-chef']` Default value: `true`. `dark_launch['quick_start']` Default value: `false`. `dark_launch['reporting']` Enable Reporting, which performs data collection during a Chef Infra Client run. Default value: `true`. `dark_launch['sql_users']` Default value: `true`. ### data_collector This configuration file has the following settings for `data_collector`: `data_collector['root_url']` The fully qualified URL to the data collector server API. When present, it will enable the data collector in **opscode-erchef**. This also enables Chef Infra Server authenticated forwarding any properly signed requests arriving at `/organizations/ORGNAME/data-collector` to this URL with the data collector token appended. This is also target for requests authenticated and forwarded by the `/organizations/ORGNAME/data-collector` endpoint. For the forwarding to work correctly the `data_collector['token']` field must also be set. For example, if the data collector in Chef Automate is being used, the URI would look like: `http://my_automate_server.example.org/data-collector/v0/`. `data_collector['proxy']` If set to `true`, Chef Infra Server will proxy all requests sent to `/data-collector` to the configured Chef Automate `data_collector['root_url']`. Note that *this route* does not check the request signature and add the right data_collector token, but just proxies the Automate endpoint **as-is**. Default value: `nil`. `data_collector['token']` Deprecated. Use `chef-server-ctl set-secret data_collector token` from the [Secrets Management](../ctl_chef_server/index#secrets-management) commands. Legacy configuration for shared data collector security token. When configured, the token will be passed as an HTTP header named `x-data-collector-token` which the server can choose to accept or reject. `data_collector['timeout']` The amount of time (in milliseconds) before a request to the data collector API times out. Default value: 30000. `data_collector['http_init_count']` The initial worker count for the HTTP connection pool that is used by the data collector. Default value: 25. `data_collector['http_max_count']` The maximum worker count for the HTTP connection pool that is used by the data collector. Default value: 100. `data_collector['http_max_age']` The maximum connection worker age (in seconds) for the HTTP connection pool that is used by the data collector. Default value: "{70, sec}". `data_collector['http_cull_interval']` The maximum cull interval (in minutes) for the HTTP connection pool that is used by the data collector. Default value: "{1, min}". `data_collector['http_max_connection_duration']` The maximum connection duration (in seconds) for the HTTP connection pool that is used by the data collector. Default value: "{70, sec}". `data_collector['ibrowse_options']` An array of comma-separated key-value pairs of ibrowse options for the HTTP connection pool that is used by the data collector. Default value: "[{connect_timeout, 10000}]". `data_collector['health_check']` A boolean that controls whether the data collector health is included in the overall health at the `_status` endpoint. When set to `true`, Chef Infra Server will report that healthy front end Chef HA cluster members have failed when the data_collector[‘root_url’] cannot be reached. As a result, the load balancer will remove those members from the load balancer pool. Default value: true`. ### estatsd This configuration file has the following settings for `estatsd`: `estatsd['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/estatsd'`. `estatsd['enable']` Enable a service. Default value: `true`. `estatsd['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/log/opscode/estatsd'`. `estatsd['port']` The port on which the service is to listen. Default value: `9466`. `estatsd['protocol']` Use to send application statistics with StatsD protocol formatting. Set this value to `statsd` to apply StatsD protocol formatting. `estatsd['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### jetty This configuration file has the following settings for `jetty`: `jetty['enable']` Enable a service. Default value: `'false'`. This value should not be modified. `jetty['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` '/var/opt/opscode/opscode-solr4/jetty/logs' ``` ### lb / lb_internal This configuration file has the following settings for `lb`: `lb['api_fqdn']` Default value: `node['fqdn']`. `lb['ban_refresh_interval']` Default value: `600`. `lb['bookshelf']` Default value: `127.0.0.1`. `lb['cache_cookbook_files']` Default value: `false`. `lb['chef_max_version']` The maximum version of Chef Infra Client that is allowed to access the Chef Infra Server via the Chef Infra Server API. Default value: `11`. `lb['chef_min_version']` The minimum version of Chef Infra Client that is allowed to access the Chef Infra Server via the Chef Infra Server API. Default value: `10`. `lb['chef_server_webui']` Default value: `127.0.0.1`. `lb['debug']` Default value: `false`. `lb['enable']` Enable a service. Default value: `true`. `lb['erchef']` Default value: `127.0.0.1`. `lb['maint_refresh_interval']` Default value: `600`. `lb['redis_connection_pool_size']` Default value: `250`. `lb['redis_connection_timeout']` The amount of time (in milliseconds) to wait before timing out. Default value: `1000`. `lb['redis_keepalive_timeout']` The amount of time (in milliseconds) to wait before timing out. Default value: `2000`. `lb['upstream']['bookshelf']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['oc_bifrost']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['opscode_erchef']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['opscode_solr4']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['vip']` The virtual IP address. Default value: `127.0.0.1`. `lb['web_ui_fqdn']` Default value: `node['fqdn']`. `lb['xdl_defaults']['503_mode']` The default value is the recommended value. Default value: `false`. `lb['xdl_defaults']['couchdb_acls']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_association_requests']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_associations']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_containers']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_groups']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_organizations']` The default value is the recommended value. Default value: `true`. And for the internal load balancers: `lb_internal['account_port']` Default value: `9685`. `lb_internal['chef_port']` Default value: `9680`. `lb_internal['enable']` Default value: `true`. `lb_internal['oc_bifrost_port']` Default value: `9683`. `lb_internal['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### ldap Warning The following settings **MUST** be in the config file for LDAP authentication to Active Directory to work: * `base_dn` * `bind_dn` * `group_dn` * `host` If those settings are missing, you will get authentication errors and be unable to proceed. This configuration file has the following settings for `ldap`: `ldap['base_dn']` The root LDAP node under which all other nodes exist in the directory structure. For Active Directory, this is typically `cn=users` and then the domain. For example: ``` 'OU=Employees,OU=Domain users,DC=example,DC=com' ``` Default value: `nil`. `ldap['bind_dn']` The distinguished name used to bind to the LDAP server. The user the Chef Infra Server will use to perform LDAP searches. This is often the administrator or manager user. This user needs to have read access to all LDAP users that require authentication. The Chef Infra Server must do an LDAP search before any user can log in. Many Active Directory and LDAP systems do not allow an anonymous bind. If anonymous bind is allowed, leave the `bind_dn` and `bind_password` settings blank. If anonymous bind is not allowed, a user with `READ` access to the directory is required. This user must be specified as an LDAP distinguished name similar to: ``` 'CN=user,OU=Employees,OU=Domainuser,DC=example,DC=com' ``` Note If you need to escape characters in a distinguished name, such as when using Active Directory, they must be [escaped with a backslash escape character](https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx). ``` 'CN=example\\user,OU=Employees,OU=Domainuser,DC=example,DC=com' ``` Default value: `nil`. `ldap['bind_password']` Deprecated. Use `chef-server-ctl set-secret ldap bind_password` from the [Secrets Management](../../ctl_chef_server#ctl-chef-server-secrets-management) commands. Legacy configuration for the password of the binding user. The password for the user specified by `ldap['bind_dn']`. Leave this value and `ldap['bind_dn']` unset if anonymous bind is sufficient. Default value: `nil`. ``` chef-server-ctl set-secret ldap bind_password Enter ldap bind_password: (no terminal output) Re-enter ldap bind_password: (no terminal output) ``` Remove a set password via ``` chef-server-ctl remove-secret ldap bind_password ``` `ldap['group_dn']` The distinguished name for a group. When set to the distinguished name of a group, only members of that group can log in. This feature filters based on the `memberOf` attribute and only works with LDAP servers that provide such an attribute. In OpenLDAP, the `memberOf` overlay provides this attribute. For example, if the value of the `memberOf` attribute is `CN=abcxyz,OU=users,DC=company,DC=com`, then use: ``` ldap['group_dn'] = 'CN=abcxyz,OU=users,DC=company,DC=com' ``` `ldap['host']` The name (or IP address) of the LDAP server. The hostname of the LDAP or Active Directory server. Be sure the Chef Infra Server is able to resolve any host names. Default value: `ldap-server-host`. `ldap['login_attribute']` The LDAP attribute that holds the user’s login name. Use to specify the Chef Infra Server user name for an LDAP user. Default value: `sAMAccountName`. `ldap['port']` An integer that specifies the port on which the LDAP server listens. The default value is an appropriate value for most configurations. Default value: `389` or `636` when `ldap['encryption']` is set to `:simple_tls`. `ldap['ssl_enabled']` Cause the Chef Infra Server to connect to the LDAP server using SSL. Default value: `false`. Must be `false` when `ldap['tls_enabled']` is `true`. Note It’s recommended that you enable SSL for Active Directory. Note Previous versions of the Chef Infra Server used the `ldap['ssl_enabled']` setting to first enable SSL, and then the `ldap['encryption']` setting to specify the encryption type. These settings are deprecated. `ldap['system_adjective']` A descriptive name for the login system that is displayed to users in the Chef Infra Server management console. If a value like “corporate” is used, then the Chef management console user interface will display strings like “the corporate login server”, “corporate login”, or “corporate password.” Default value: `AD/LDAP`. Warning This setting is **not** used by the Chef Infra Server. It is used only by the Chef management console. `ldap['timeout']` The amount of time (in seconds) to wait before timing out. Default value: `60000`. `ldap['tls_enabled']` Enable TLS. When enabled, communication with the LDAP server is done via a secure SSL connection on a dedicated port. When `true`, `ldap['port']` is also set to `636`. Default value: `false`. Must be `false` when `ldap['ssl_enabled']` is `true`. Note Previous versions of the Chef Infra Server used the `ldap['ssl_enabled']` setting to first enable SSL, and then the `ldap['encryption']` setting to specify the encryption type. These settings are deprecated. ### nginx This configuration file has the following settings for `nginx`: `nginx['cache_max_size']` The `max_size` parameter used by the Nginx cache manager, which is part of the `proxy_cache_path` directive. When the size of file storage exceeds this value, the Nginx cache manager removes the least recently used data. Default value: `5000m`. `nginx['client_max_body_size']` The maximum accepted body size for a client request, as indicated by the `Content-Length` request header. Default value: `250m`. `nginx['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/nginx`. `nginx['enable']` Enable a service. Default value: `true`. `nginx['enable_ipv6']` Enable Internet Protocol version 6 (IPv6) addresses. Default value: `false`. `nginx['enable_non_ssl']` Allow port 80 redirects to port 443. When this value is set to `true`, load balancers on the front-end hardware are allowed to do SSL termination of the WebUI and API. Default value: `false`. Note Chef Infra Server versions earlier than 14.5 configured with `nginx['enable_non_ssl'] = false` and `fips = true` require `export CSC_LB_URL=https://127.0.0.1` to run the command `chef-server-ctl reindex <options>` `nginx['enable_stub_status']` Enables the Nginx `stub_status` module. See `nginx['stub_status']['allow_list']`, `nginx['stub_status']['listen_host']`, `nginx['stub_status']['listen_port']`, and `nginx['stub_status']['location']`. Default value: `true`. `nginx['gzip']` Enable gzip compression. Default value: `on`. `nginx['gzip_comp_level']` The compression level used with gzip, from least amount of compression (`1`, fastest) to the most (`2`, slowest). Default value: `2`. `nginx['gzip_http_version']` Enable gzip depending on the version of the HTTP request. Default value: `1.0`. `nginx['gzip_proxied']` The type of compression used based on the request and response. Default value: `any`. `nginx['gzip_types']` Enable compression for the specified MIME-types. Default value: ``` [ 'text/plain', 'text/css', 'application/x-javascript', 'text/xml', 'application/xml', 'application/xml+rss', 'text/javascript', 'application/json' ] ``` `nginx['keepalive_timeout']` The amount of time (in seconds) to wait for requests on a HTTP keepalive connection. Default value: `65`. `nginx['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/nginx`. `nginx['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `nginx['log_x_forwarded_for']` Log $http_x_forwarded_for (“X-Forwarded-For”) instead of $remote_addr if `true`. Default value `false`. `nginx['non_ssl_port']` The port on which the WebUI and API are bound for non-SSL connections. Default value: `80`. Use `nginx['enable_non_ssl']` to enable or disable SSL redirects on this port number. Set to `false` to disable non-SSL connections. `nginx['sendfile']` Copy data between file descriptors when `sendfile()` is used. Default value: `on`. `nginx['server_name']` The FQDN for the server. Default value: `node['fqdn']`. `nginx['ssl_certificate']` The SSL certificate used to verify communication over HTTPS. Default value: `nil`. `nginx['ssl_certificate_key']` The certificate key used for SSL communication. Default value: `nil`. `nginx['ssl_ciphers']` The list of supported cipher suites that are used to establish a secure connection. To favor AES256 with ECDHE forward security, drop the `RC4-SHA:RC4-MD5:RC4:RSA` prefix. See [this link](https://www.openssl.org/docs/man1.0.2/man1/ciphers.html) for more information. For example: ``` nginx['ssl_ciphers'] = HIGH: ... :!PSK ``` `nginx['ssl_company_name']` The name of your company. Default value: `YouCorp`. `nginx['ssl_country_name']` The country in which your company is located. Default value: `US`. `nginx['ssl_email_address']` The default email address for your company. Default value: `<EMAIL>`. `nginx['ssl_locality_name']` The city in which your company is located. Default value: `Seattle`. `nginx['ssl_organizational_unit_name']` The organization or group within your company that is running the Chef Infra Server. Default value: `Operations`. `nginx['ssl_port']` Default value: `443`. `nginx['ssl_protocols']` The SSL protocol versions that are enabled. For enhanced security set this value to `'TLSv1.2'`. TLS 1.2 is supported on Chef Infra Client 10.16.4 and later on Linux, Unix, and macOS, and on Chef Infra Client 12.8 and later on Windows. If it is necessary to support these older end-of-life Chef Infra Client releases, set this value to `'TLSv1.1 TLSv1.2'`. ``` nginx['ssl_protocols'] = 'TLSv1.2' ``` Default value: `TLSv1 TLSv1.1 TLSv1.2`. `nginx['ssl_state_name']` The state, province, or region in which your company is located. Default value: `WA`. `nginx['strict_host_header']` Whether nginx should only respond to requests where the Host header matches one of the configured FQDNs. Default value: `false`. `nginx['stub_status']['allow_list']` The IP address on which accessing the `stub_status` endpoint is allowed. Default value: `["127.0.0.1"]`. `nginx['stub_status']['listen_host']` The host on which the Nginx `stub_status` module listens. Default value: `"127.0.0.1"`. `nginx['stub_status']['listen_port']` The port on which the Nginx `stub_status` module listens. Default value: `"9999"`. `nginx['stub_status']['location']` The name of the Nginx `stub_status` endpoint used to access data generated by the Nginx `stub_status` module. Default value: `"/nginx_status"`. `nginx['tcp_nodelay']` Enable the Nagle buffering algorithm. Default value: `on`. `nginx['tcp_nopush']` Enable TCP/IP transactions. Default value: `on`. `nginx['url']` Default value: `https://#{node['fqdn']}`. `nginx['use_implicit_hosts']` Automatically add localhost and any local IP addresses to the configured FQDNs. Useful in combination with `nginx['strict_host_header']`. Default value: `true`. `nginx['show_welcome_page']` Determines whether or not the default nginx welcome page is shown. Default value: `true`. `nginx['worker_connections']` The maximum number of simultaneous clients. Use with `nginx['worker_processes']` to determine the maximum number of allowed clients. Default value: `10240`. `nginx['worker_processes']` The number of allowed worker processes. Use with `nginx['worker_connections']` to determine the maximum number of allowed clients. Default value: `node['cpu']['total'].to_i`. `nginx['x_forwarded_proto']` The protocol used to connect to the server. Possible values: `http` and `https`. This is the protocol used to connect to the Chef Infra Server by a Chef Infra Client or a workstation. Default value: `'https'`. ### oc_bifrost The **oc_bifrost** service ensures that every request to view or manage objects stored on the Chef Infra Server is authorized. This configuration file has the following settings for `oc_bifrost`: `oc_bifrost['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. This value should be increased if failures indicate that the **oc_bifrost** service ran out of connections. This value should be tuned in conjunction with the `postgresql['max_connections']` setting for PostgreSQL. Default value: `20`. `oc_bifrost['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/oc_bifrost`. `oc_bifrost['enable']` Enable a service. Default value: `true`. `oc_bifrost['enable_request_logging']` Use to configure request logging for the `oc_bifrost` service. Default value: `true`. `oc_bifrost['extended_perf_log']` Default value: `true`. `oc_bifrost['listen']` The IP address on which the service is to listen. Default value: `'127.0.0.1'`. `oc_bifrost['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/oc_bifrost`. `oc_bifrost['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `oc_bifrost['port']` The port on which the service is to listen. Default value: `9463`. `oc_bifrost['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'bifrost@my_postgresql.postgres.database.azure.com'`), where `username` would normally equal the value of `oc_bifrost['sql_user']` (default: `'bifrost'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_bifrost['sql_user']`. Default value: `nil`. `oc_bifrost['sql_password']` The password for the `sql_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_bifrost sql_password`. `oc_bifrost['sql_ro_password']` The password for the `sql_ro_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_bifrost sql_ro_password`. `oc_bifrost['sql_ro_user']` Default value: `'bifrost_ro'`. `oc_bifrost['sql_user']` The user with permission to publish data. Default value: `'bifrost'`. `oc_bifrost['superuser_id']` Default value: **generated**. `oc_bifrost['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### oc_chef_authz The **opscode-authz** service is used to handle authorization requests from oc_erchef to oc_bifrost in the Chef Infra Server. This configuration file has the following settings for `oc_chef_authz`: `oc_chef_authz['http_cull_interval']` Default value: `'{1, min}'`. `oc_chef_authz['http_init_count']` Default value: `25`. `oc_chef_authz['http_max_age']` Default value: `'{70, sec}'`. `oc_chef_authz['http_max_connection_duration']` Default value: `'{70, sec}'`. `oc_chef_authz['http_max_count']` Default value: `100`. `oc_chef_authz['ibrowse_options']` The amount of time (in milliseconds) to wait for a connection to be established. Default value: `'[{connect_timeout, 5000}]'`. ### oc-chef-pedant This configuration file has the following settings for `oc-chef-pedant`: `oc_chef_pedant['debug_org_creation']` Run tests with full output. Default value: `false`. `oc_chef_pedant['dir']` The working directory. The default value is the recommended value. Default value: ``` '/var/opt/opscode/oc-chef-pedant' ``` `oc_chef_pedant['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` '/var/log/opscode/oc-chef-pedant' ``` `oc_chef_pedant['log_http_requests']` Log HTTP requests in a file named `http-traffic.log` that is located in the path specified by `log_directory`. Default value: `true`. `oc_chef_pedant['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` ### oc-id The **oc-id** service enables OAuth 2.0 authentication to the Chef Infra Server by external applications, including Chef Supermarket. OAuth 2.0 uses token-based authentication, where external applications use tokens that are issued by the **oc-id** provider. No special credentials—`webui_priv.pem` or privileged keys—are stored on the external application. This configuration file has the following settings for `oc-id`: `oc_id['administrators']` An array of Chef Infra Server user names who may add applications to the identity service. For example, `['user1', 'user2']`. Default value: `[ ]`. `oc_id['applications']` A Hash that contains OAuth 2 application information. Default value: `{ }`. To define OAuth 2 information for Chef Supermarket, create a Hash similar to: ``` oc_id['applications'] ||= {} oc_id['applications']['supermarket'] = { 'redirect_uri' => 'https://supermarket.mycompany.com/auth/chef_oauth2/callback', } ``` `oc_id['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `'20'`. `oc_id['dir']` The working directory. The default value is the recommended value. Default value: none. `oc_id['enable']` Enable a service. Default value: `true`. `oc_id['email_from_address']` Outbound email address. Defaults to the `'from_email'` value. `oc_id['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/opt/opscode/oc_id'`. `oc_id['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `oc_id['origin']` The FQDN for the server that is sending outbound email. Defaults to the `'api_fqdn'` value, which is the FQDN for the Chef Infra Server. `oc_id['num_to_keep']` The number of log files to keep. Default value: `10`. `oc_id['port']` The port on which the service is to listen. Default value: `9090`. `oc_id['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `oc_id['sql_user']` (default: `'od_id'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_id['sql_user']`. Default value: `nil`. `oc_id['sql_database']` The name of the database. Default value: `oc_id`. `oc_id['sql_password']` The password for the `sql_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_id sql_password`. `oc_id['sql_user']` The user with permission to write to `sql_database`. Default value: `oc_id`. `oc_id['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### opscode-chef-mover This configuration file has the following settings for `opscode-chef-mover`: `opscode_chef_mover['bulk_fetch_batch_size']` Default value: `'5'`. `opscode_chef_mover['cache_ttl']` Default value: `'3600'`. `opscode_chef_mover['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `'5'`. `opscode_chef_mover['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: ``` '/var/opt/opscode/opscode-chef-mover/data' ``` `opscode_chef_mover['dir']` The working directory. The default value is the recommended value. Default value: ``` '/var/opt/opscode/opscode-chef-mover' ``` `opscode_chef_mover['enable']` Enable a service. Default value: `true`. `opscode_chef_mover['ibrowse_max_pipeline_size']` Default value: `1`. `opscode_chef_mover['ibrowse_max_sessions']` Default value: `256`. `opscode_chef_mover['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` '/var/log/opscode/opscode-chef-mover' ``` `opscode_chef_mover['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_chef_mover['max_cache_size']` Default value: `'10000'`. `opscode_chef_mover['solr_http_cull_interval']` Default value: `'{1, min}'`. `opscode_chef_mover['solr_http_init_count']` Default value: `25`. `opscode_chef_mover['solr_http_max_age']` Default value: `'{70, sec}'`. `opscode_chef_mover['solr_http_max_connection_duration']` Default value: `'{70, sec}'`. `opscode_chef_mover['solr_http_max_count']` Default value: `100`. `opscode_chef_mover['solr_ibrowse_options']` Default value: `'[{connect_timeout, 10000}]'`. `opscode_chef_mover['solr_timeout']` Default value: `30000`. ### opscode-erchef The **opscode-erchef** service is an Erlang-based service that is used to handle Chef Infra Server API requests to the following areas within the Chef Infra Server: * Cookbooks * Data bags * Environments * Nodes * Roles * Sandboxes * Search This configuration file has the following settings for `opscode-erchef`: `opscode_erchef['auth_skew']` Default value: `900`. `opscode_erchef['authz_fanout']` Default value: `20`. `opscode_erchef['authz_timeout']` The amount of time (in seconds) before a request to the **oc_bifrost** service times out. Default value: `2000`. `opscode_erchef['base_resource_url']` The base URL to which the service is to return links to API resources. Use `:host_header` to ensure the URL is derived from the host header of the incoming HTTP request. Default value: `:host_header`. `opscode_erchef['bulk_fetch_batch_size']` The number of nodes that may be deserialized. Currently only applies to the `/search` endpoint in the Chef Infra Server API. The default value is the recommended value. Default value: `5`. `opscode_erchef['cache_ttl']` Default value: `3600`. `opscode_erchef['cleanup_batch_size']` Default value: `0`. `opscode_erchef['couchdb_max_conn']` Default value: `'100'`. `opscode_erchef['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `20`. `opscode_erchef['depsolver_timeout']` The amount of time (in milliseconds) to wait for cookbook dependency problems to be solved. Default value: `'5000'`. `opscode_erchef['depsolver_worker_count']` The number of Ruby processes for which cookbook dependency problems are unsolved. Use the `pgrep -fl depselector` command to verify the number of depsolver workers that are running. If you are seeing 503 service unavailable errors, increase this value. Default value: `'5'`. `opscode_erchef['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/opscode-erchef`. `opscode_erchef['enable']` Enable a service. Default value: `true`. `opscode_erchef['enable_actionlog']` Use to enable Chef actions, a premium feature of the Chef Infra Server. Default value: `false`. `opscode_erchef['enable_request_logging']` Use to configure request logging for the `opscode_erchef` service. Default value: `true`. `opscode_erchef['ibrowse_max_pipeline_size']` Default value: `1`. `opscode_erchef['ibrowse_max_sessions']` Default value: `256`. `opscode_erchef['listen']` The IP address on which the service is to listen. Default value: `127.0.0.1`. `opscode_erchef['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/opscode-erchef`. `opscode_erchef['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_erchef['max_cache_size']` Default value: `10000`. `opscode_erchef['max_request_size']` When the request body size is greater than this value, a `413 Request Entity Too Large` error is returned. Default value: `2000000`. `opscode_erchef['nginx_bookshelf_caching']` Whether Nginx is used to cache cookbooks. When `:on`, Nginx serves up the cached content instead of forwarding the request. Default value: `:off`. `opscode_erchef['port']` The port on which the service is to listen. Default value: `8000`. `opscode_erchef['reindex_batch_size']` The number of items to fetch from the database and send to the search index at a time. Default value: `10`. `opscode_erchef['reindex_sleep_min_ms']` The minimum number of milliseconds to sleep before retrying a failed attempt to index an item. Retries are delayed a random number of miliseconds between `reindex_sleep_min_ms` and `reindex_sleep_max_ms`. Set both this and `reindex_sleep_max_ms` to 0 to retry without delay. Default value: `500` `opscode_erchef['reindex_sleep_max_ms']` The maximum number of milliseconds to sleep before retrying a failed attempt to index an item. Retries are delayed a random number of miliseconds between `reindex_sleep_min_ms` and `reindex_sleep_max_ms`. Set both this and `reindex_sleep_min_ms` to 0 to retry without delay. Default value: `2000` `opscode_erchef['reindex_item_retries']` The number of times to retry sending an object for indexing in the case of failure. Default value: `3` `opscode_erchef['root_metric_key']` Default value: `chefAPI`. `opscode_erchef['s3_bucket']` The name of the Amazon Simple Storage Service (S3) bucket. This may point at external storage locations, such as Amazon EC2. See [AWS external bookshelf settings](../index#aws-settings) for more information on configuring external bookshelf. `opscode_erchef['s3_parallel_ops_fanout']` Default value: `20`. `opscode_erchef['s3_parallel_ops_timeout']` Default value: `5000`. `opscode_erchef['s3_url_expiry_window_size']` The frequency at which unique URLs are generated. This value may be a specific amount of time, i.e. `15m` (fifteen minutes) or a percentage of the value of `s3_url_ttl`, i.e. `10%`. Default value: `:off`. `opscode_erchef['s3_url_ttl']` The amount of time (in seconds) before connections to the server expire. If node bootstraps are timing out, increase this setting. Default value: `28800`. `opscode_erchef['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `opscode-erchef['sql_user']` (default: `'opscode_chef'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `opscode_erchef['sql_user']`.Default value: `nil`. `opscode_erchef['strict_search_result_acls']` Use to specify that search results only return objects to which an actor (user, client, etc.) has read access, as determined by ACL settings. This affects all searches. When `true`, the performance of the Chef management console may increase because it enables the Chef management console to skip redundant ACL checks. To ensure the Chef management console is configured properly, after this setting has been applied with a `chef-server-ctl reconfigure` run `chef-manage-ctl reconfigure` to ensure the Chef management console also picks up the setting. Default value: `false`. Warning When `true`, `opscode_erchef['strict_search_result_acls']` affects all search results and any actor (user, client, etc.) that does not have read access to a search result will not be able to view it. For example, this could affect search results returned during a Chef Infra Client runs if a Chef Infra Client does not have permission to read the information. `opscode_erchef['udp_socket_pool_size']` Default value: `20`. `opscode_erchef['umask']` Default value: `0022`. `opscode_erchef['validation_client_name']` Default value: `chef-validator`. `opscode_erchef['vip']` The virtual IP address. Default value: `127.0.0.1`. ### opscode-expander The **opscode-expander** service is used to process data (pulled from the **rabbitmq** service’s message queue) so that it can be properly indexed by the **opscode-solr4** service. This configuration file has the following settings for `opscode-expander`: `opscode_expander['consumer_id']` The identity of the consumer to which messages are published. Default value: `default`. `opscode_expander['dir']` The working directory. The default value is the recommended value. Default value: ``` /var/opt/opscode/opscode-expander ``` `opscode_expander['enable']` Enable a service. Default value: `true`. `opscode_expander['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` /var/log/opscode/opscode-expander ``` `opscode_expander['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_expander['nodes']` The number of allowed worker processes. Default value: `2`. `opscode_expander['reindexer_log_directory']` The directory in which `opscode-expander-reindexer` logs files are located. Default value: ``` /var/log/opscode/opscode-expander-reindexer ``` ### opscode-solr4 The **opscode-solr4** service is used to create the search indexes used for searching objects like nodes, data bags, and cookbooks. (This service ensures timely search results via the Chef Infra Server API; data that is used by the Chef platform is stored in PostgreSQL.) This configuration file has the following settings for `opscode-solr4`: `opscode_solr4['auto_soft_commit']` The maximum number of documents before a soft commit is triggered. Default value: `1000`. `opscode_solr4['commit_interval']` The frequency (in seconds) at which node objects are added to the Apache Solr search index. This value should be tuned carefully. When data is committed to the Apache Solr index, all incoming updates are blocked. If the duration between updates is too short, it is possible for the rate at which updates are asked to occur to be faster than the rate at which objects can be actually committed. Default value: `60000` (every 60 seconds). `opscode_solr4['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: ``` /var/opt/opscode/opscode-solr4/data ``` `opscode_solr4['dir']` The working directory. The default value is the recommended value. Default value: ``` /var/opt/opscode/opscode-solr4 ``` `opscode_solr4['enable']` Enable a service. Default value: `true`. `opscode_solr4['heap_size']` The amount of memory (in MBs) available to Apache Solr. If there is not enough memory available, search queries made by nodes to Apache Solr may fail. The amount of memory that must be available also depends on the number of nodes in the organization, the frequency of search queries, and other characteristics that are unique to each organization. In general, as the number of nodes increases, so does the amount of memory. The default value should work for many organizations with fewer than 25 nodes. For an organization with several hundred nodes, the amount of memory that is required often exceeds 3GB. Default value: `nil`, which is equivalent to 25% of the system memory or 1024 (MB, but this setting is specified as an integer number of MB in EC11), whichever is smaller. `opscode_solr4['ip_address']` The IP address for the machine on which Apache Solr is running. Default value: `127.0.0.1`. `opscode_solr4['java_opts']` A Hash of `JAVA_OPTS` environment variables to be set. (`-XX:NewSize` is configured using the `new_size` setting.) Default value: `' '` (empty). `opscode_solr4['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` /var/log/opscode/opscode-solr4 ``` `opscode_solr4['log_gc']` Enable or disable GC logging. Default is `true`. `opscode_solr4['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_solr4['max_commit_docs']` The frequency (in documents) at which node objects are added to the Apache Solr search index. This value should be tuned carefully. When data is committed to the Apache Solr index, all incoming updates are blocked. If the duration between updates is too short, it is possible for the rate at which updates are asked to occur to be faster than the rate at which objects can be actually committed. Default value: `1000` (every 1000 documents). `opscode_solr4['max_field_length']` The maximum field length (in number of tokens/terms). If a field length exceeds this value, Apache Solr may not be able to complete building the index. Default value: `100000` (increased from the Apache Solr default value of `10000`). `opscode_solr4['max_merge_docs']` The maximum number of index segments allowed before they are merged into a single index. Default value: `2147483647`. `opscode_solr4['merge_factor']` The maximum number of document updates that can be stored in memory before being flushed and added to the current index segment. Default value: `15`. `opscode_solr4['new_size']` Configure the `-XX:NewSize` `JAVA_OPTS` environment variable. Default value: `nil`. `opscode_solr4['poll_seconds']` The frequency (in seconds) at which the secondary machine polls the primary. Default value: `20`. `opscode_solr4['port']` The port on which the service is to listen. Default value: `8983`. `opscode_solr4['ram_buffer_size']` The size (in megabytes) of the RAM buffer. When document updates exceed this amout, pending updates are flushed. Default value: `100`. `opscode_solr4['url']` Default value: `'http://localhost:8983/solr'`. `opscode_solr4['vip']` The virtual IP address. Default value: `127.0.0.1`. ### postgresql The **postgresql** service is used to store node, object, and user data. This configuration file has the following settings for `postgresql`: `postgresql['checkpoint_completion_target']` A completion percentage that is used to determine how quickly a checkpoint should finish in relation to the completion status of the next checkpoint. For example, if the value is `0.5`, then a checkpoint attempts to finish before 50% of the next checkpoint is done. Default value: `0.5`. `postgresql['checkpoint_segments']` The maximum amount (in megabytes) between checkpoints in log file segments. Default value: `3`. `postgresql['checkpoint_timeout']` The amount of time (in minutes) between checkpoints. Default value: `5min`. `postgresql['checkpoint_warning']` The frequency (in seconds) at which messages are sent to the server log files if checkpoint segments are being filled faster than their currently configured values. Default value: `30s`. `postgresql['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `/var/opt/opscode/postgresql/#{node['private_chef']['postgresql']['version']}/data`. `postgresql['db_connection_superuser']` The PostgreSQL superuser name in `'username@hostname'` format (e.g. `'opscode_pgsql@my_postgresql.postgres.database.azure.com'`), where `username` would normally equal the value of `postgresql['db_superuser']` with any dashes replaced by underscores. This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `postgresql['db_superuser']`. Default value: `nil`. `postgresql['db_superuser']` Default value: `opscode-pgsql`. If `username` is set, set `db_superuser` to the same value. `postgresql['db_superuser_password']` Password for the DB superuser. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-db-superuser-password`. `postgresql['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/postgresql/#{node['private_chef']['postgresql']['version']}`. `postgresql['effective_cache_size']` The size of the disk cache that is used for data files. Default value: 50% of available RAM. `postgresql['enable']` Enable a service. Default value: `true`. `postgresql['home']` The home directory for PostgreSQL. Default value: `/var/opt/opscode/postgresql`. `postgresql['keepalives_count']` The maximum number of keepalive proves that should be sent before dropping a connection. Default value: `2`. `postgresql['keepalives_idle']` The amount of time (in seconds) a connection must remain idle before keepalive probes will resume. Default value: `60`. `postgresql['keepalives_interval']` The amount of time (in seconds) between probes. Default value: `15`. `postgresql['listen_address']` The connection source to which PostgreSQL is to respond. Default value: `localhost`. `postgresql['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/postgresql/#{node['private_chef']['postgresql']['version']}`. `postgresql['log_min_duration_statement']` When to log a slow PostgreSQL query statement. Possible values: `-1` (disabled, do not log any statements), `0` (log every statement), or an integer greater than zero. When the integer is greater than zero, this value is the amount of time (in milliseconds) that a query statement must have run before it is logged. Default value: `-1`. `postgresql['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `postgresql['max_connections']` The maximum number of allowed concurrent connections. Default value: `350`. `postgresql['md5_auth_cidr_addresses']` Use instead of `trust_auth_cidr_addresses` to encrypt passwords using MD5 hashes. Default value: `[ '127.0.0.1/32', '::1/128' ]`. `postgresql['port']` The port on which the service is to listen. Default value: `5432`. `postgresql['shared_buffers']` The amount of memory that is dedicated to PostgreSQL for data caching. Default value: `#{(node['memory']['total'].to_i / 4) / (1024)}MB`. `postgresql['shell']` Default value: `/bin/sh`. `postgresql['shmall']` The total amount of available shared memory. Default value: `4194304`. `postgresql['shmmax']` The maximum amount of shared memory. Default value: `17179869184`. `postgresql['sslmode']` SSL encryption mode between the Chef Infra Server and PostgreSQL. Valid settings are `'disable'` and `'require'`. Default value: `'disable'`. `postgresql['trust_auth_cidr_addresses']` Use for clear-text passwords. See `md5_auth_cidr_addresses`. Default value: `'127.0.0.1/32', '::1/128'`. `postgresql['user_path']` Default value: `/opt/opscode/embedded/bin:/opt/opscode/bin:$PATH`. `postgresql['username']` The PostgreSQL account user name. Default value: `opscode-pgsql`. If setting this value, must set `db_superuser` to the same value. `postgresql['version']` The (currently) hardcoded version of PostgreSQL. Default value: `'9.2'`. `postgresql['vip']` The virtual IP address. Default value: `127.0.0.1`. `postgresql['work_mem']` The size (in megabytes) of allowed in-memory sorting. Default value: `8MB`. ### rabbitmq The **rabbitmq** service is used to provide the message queue that is used by the Chef Infra Server to get search data to Apache Solr so that it can be indexed for search. This configuration file has the following settings for `rabbitmq`: `rabbitmq['actions_exchange']` The name of the exchange to which Chef actions publishes actions data. Default value: `'actions'`. `rabbitmq['actions_password']` Legacy configuration setting for the password of the `actions_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-actions-password`. `rabbitmq['actions_user']` The user with permission to publish actions data. Default value: `'actions'`. `rabbitmq['actions_vhost']` The virtual host to which Chef actions publishes actions data. Default value: `'/analytics'`. `rabbitmq['analytics_max_length']` The maximum number of messages that can be queued before RabbitMQ automatically drops messages from the front of the queue to make room for new messages. Default value: `10000`. `rabbitmq['consumer_id']` The identity of the consumer to which messages are published. Default value: `'hotsauce'`. `rabbitmq['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `'/var/opt/opscode/rabbitmq/db'`. `rabbitmq['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/rabbitmq'`. `rabbitmq['drop_on_full_capacity']` Specify if messages will stop being sent to the RabbitMQ queue when it is at capacity. Default value: `true`. `rabbitmq['enable']` Enable a service. Default value: `true`. `rabbitmq['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/log/opscode/rabbitmq'`. `rabbitmq['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `rabbitmq['management_enabled']` Specify if the rabbitmq-management plugin is enabled. Default value: `true`. `rabbitmq['management_password']` Legacy configuration setting for rabbitmq-management plugin password. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret rabbitmq management_password`. `rabbitmq['management_port']` The rabbitmq-management plugin port. Default value: `15672`. `rabbitmq['management_user']` The rabbitmq-management plugin user. Default value: `'rabbitmgmt'`. `rabbitmq['node_ip_address']` The bind IP address for RabbitMQ. Default value: `'127.0.0.1'`. `rabbitmq['node_port']` The port on which the service is to listen. Default value: `'5672'`. `rabbitmq['nodename']` The unique identifier of the node. Default value: `'rabbit@localhost'`. `rabbitmq['password']` Legacy configuration setting for the password for the RabbitMQ user. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret rabbitmq password`. `rabbitmq['prevent_erchef_startup_on_full_capacity']` Specify if the Chef Infra Server will start when the monitored RabbitMQ queue is full. Default value: `false`. `rabbitmq['queue_at_capacity_affects_overall_status']` Specify if the `_status` endpoint in the Chef Infra Server API will fail if the monitored queue is at capacity. Default value: `false`. `rabbitmq['queue_length_monitor_enabled']` Specify if the queue length monitor is enabled. Default value: `true`. `rabbitmq['queue_length_monitor_millis']` The frequency (in milliseconds) at which the length of the RabbitMQ queue is checked. Default value: `30000`. `rabbitmq['queue_length_monitor_timeout_millis']` The timeout (in milliseconds) at which calls to the queue length monitor will stop if the Chef Infra Server is overloaded. Default value: `5000`. `rabbitmq['queue_length_monitor_queue']` The RabbitMQ queue that is observed by queue length monitor. Default value: `'alaska'`. `rabbitmq['queue_length_monitor_vhost']` The virtual host for the RabbitMQ queue that is observed by queue length monitor. Default value: `'/analytics'`. `rabbitmq['rabbit_mgmt_http_cull_interval']` The maximum cull interval (in seconds) for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `60`. `rabbitmq['rabbit_mgmt_http_init_count']` The initial worker count for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `25`. `rabbitmq['rabbit_mgmt_http_max_age']` The maximum connection worker age (in seconds) for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `70`. `rabbitmq['rabbit_mgmt_http_max_connection_duration']` The maximum connection duration (in seconds) for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `70`. `rabbitmq['rabbit_mgmt_http_max_count']` The maximum worker count for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `100`. `rabbitmq['rabbit_mgmt_ibrowse_options']` An array of comma-separated key-value pairs of ibrowse options for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `'{connect_timeout, 10000}'`. `rabbitmq['rabbit_mgmt_timeout']` The timeout for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `30000`. `rabbitmq['reindexer_vhost']` Default value: `'/reindexer'`. `rabbitmq['ssl_versions']` The SSL versions used by the rabbitmq-management plugin. (See [RabbitMQ TLS support](https://www.rabbitmq.com/ssl.html) for more information.) Default value: `['tlsv1.2', 'tlsv1.1']`. `rabbitmq['user']` Default value: `'chef'`. `rabbitmq['vhost']` Default value: `'/chef'`. `rabbitmq['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### redis_lb Key-value store used in conjunction with Nginx to route requests and populate request data used by the Chef Infra Server. This configuration file has the following settings for `redis_lb`: `redis_lb['activerehashing']` Enable active rehashing. Default value: `'no'`. `redis_lb['aof_rewrite_min_size']` The minimum size of the append-only file. Only files larger than this value are rewritten. Default value: `'16mb'`. `redis_lb['aof_rewrite_percent']` The size of the current append-only file, as compared to the base size. The append-only file is rewritten when the current file exceeds the base size by this value. Default value: `'50'`. `redis_lb['appendfsync']` The frequency at which the operating system writes data on-disk, instead of waiting for more data. Possible values: `no` (don’t fsync, let operating system flush data), `always` (fsync after every write to the append-only log file), and `everysec` (fsync only once time per second). Default value: `'always'`. `redis_lb['appendonly']` Dump data asynchronously on-disk or to an append-only log file. Set to `yes` to dump data to an append-only log file. Default value: `'no'`. `redis_lb['bind']` Bind Redis to the specified IP address. Default value: `'127.0.0.1'`. `redis_lb['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `'/var/opt/opscode/redis_lb/data'`. `redis_lb['databases']` The number of databases. Default value: `'16'`. `redis_lb['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/redis_lb'`. `redis_lb['enable']` Enable a service. Default value: `true`. `redis_lb['ha']` Run the Chef Infra Server in a high availability topology. When `topology` is set to `ha`, this setting defaults to `true`. Default value: `false`. `redis_lb['keepalive']` The amount of time (in seconds) to wait for requests on a connection. Default value: `'60'`. `redis_lb['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/log/opscode/redis_lb'`. `redis_lb['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `redis_lb['loglevel']` The level of logging to be stored in a log file.. Possible values: `debug`, `notice`, `verbose`, and `warning`. Default value: `'notice'`. `redis_lb['maxmemory']` The maximum amount of memory (in bytes). Default value: `'8m'`. `redis_lb['maxmemory_policy']` The policy applied when the maximum amount of memory is reached. Possible values: `allkeys-lru` (remove keys, starting with those used least frequently), `allkeys-random` (remove keys randomly), `noeviction` (don’t expire, return an error on write operation), `volatile-lru` (remove expired keys, starting with those used least frequently), `volatile-random` (remove expired keys randomly), and `volatile-ttl` (remove keys, starting with nearest expired time). Default value: `'noeviction'`. `redis_lb['port']` The port on which the service is to listen. Default value: `'16379'`. `redis_lb['save_frequency']` Set the save frequency. Pattern: `{ "seconds" => "keys", "seconds" => "keys", "seconds" => "keys" }`. Default value: ``` { '900' => '1', '300' => '10', '60' => '1000' } ``` Which saves the database every 15 minutes if at least one key changes, every 5 minutes if at least 10 keys change, and every 60 seconds if 10000 keys change. `redis_lb['timeout']` The amount of time (in seconds) a client may be idle before timeout. Default value: `'300'`. `redis_lb['vip']` The virtual IP address. Default value: `'127.0.0.1'`. `redis_lb['password']` Legacy configuration setting for the Redis password. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret redis_lb password`. ### upgrades This configuration file has the following settings for `upgrades`: `upgrades['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/upgrades'`. ### user This configuration file has the following settings for `user`: `user['home']` The home directory for the user under which Chef Infra Server services run. Default value: `/opt/opscode/embedded`. `user['shell']` The shell for the user under which Chef Infra Server services run. Default value: `/bin/sh`. `user['username']` The user name under which Chef Infra Server services run. Default value: `opscode`. ### required_recipe `required_recipe` is a feature that allows an administrator to specify a recipe that will be run by all Chef Infra Clients that connect to it, regardless of the node’s run list. This feature is targeted at expert level practitioners who are delivering isolated configuration changes to the target systems, such as self-contained agent software. Further explanation of the feature can be found in [Chef Infra Client Development Docs](https://github.com/chef/chef/blob/main/docs/dev/design_documents/server_enforced_recipes.md). This configuration file has the following settings for `required_recipe`: `required_recipe["enable"]` Whether the feature is enabled. Default value: `false`. `required_recipe["path"]` The location of the recipe to serve. The file must be owned by the root user and group, and may not be group or world-writeable. Default value: `nil`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/config_rb_server_optional_settings/Log Files ========= [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/server_logs.md) All logs generated by the Chef Infra Server can be found in `/var/log/opscode`. Each service enabled on the system also has a sub-directory in which service-specific logs are located, typically found in `/var/log/opscode/service_name`. View Log Files -------------- The Chef Infra Server has built-in support for easily tailing the logs that are generated. To view all the logs being generated on the Chef Infra Server, enter the following command: ``` chef-server-ctl tail ``` To view logs for a specific service: ``` chef-server-ctl tail SERVICENAME ``` where `SERVICENAME` should be replaced with the name of the service for which log files will be viewed. ### tail Log Files The `tail` subcommand is used to follow all of the Chef Infra Server logs for all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl tail SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. Another common approach to tailing the log files for a service is to use the system utility `tail`. For example: ``` tail -50f /var/log/opscode/opscode-erchef/current ``` Supervisor ---------- Supervisor logs are created and managed directly by the service supervisor, and are automatically rotated when the current log file reaches 1,000,000 bytes. 10 log files are kept. The latest supervisor log is always located in `/var/log/service_name/current` and rotated logs have a filename starting with `@` followed by a precise `tai64n` timestamp based on when the file was rotated. Supervisor logs are available for the following services: * bifrost * bookshelf * elasticsearch * nginx * opscode-erchef * postgresql * redis ### nginx, access Nginx is an important entry point for data on the Chef Infra Server, which means that debugging efforts frequently start with analyzing the **nginx** service’s `access.log` file. This log contains every HTTP request made to the front-end machine and can be very useful when investigating request rates and usage patterns. The following is an example log entry: ``` 175.185.9.6 - - [12/Jul/2013:15:56:54 +0000] "GET /organizations/exampleorg/data/firewall/nova_api HTTP/1.1" 200 "0.850" 452 "-" "Chef Client/0.10.2 (ruby-1.8.7-p302; ohai-0.6.4; x86_64-linux; +https://chef.io)" "127.0.0.1:9460" "200" "0.849" "0.10.2" "version=1.0" "some_node.example.com" "2013-07-12T15:56:40Z" "2jmj7l5rSw0yVb/vlWAYkK/YBwk=" 985 ``` where important fields in this log include: * The HTTP status code (`200`) * The IP address of the requesting client (`175.185.9.6`) * The timestamp (`[12/Jul/2013:15:56:54 +0000]`) * The total request time (`"0.850"`) * The request method (`GET`) * The request URL (`/organizations/exampleorg/data/firewall/nova_api`) ### opscode-erchef, current The **opscode-erchef** service’s `current.log` file contains a history of stack traces from major application crashes. ### opscode-erchef, erchef The **opscode-erchef** service’s `erchef.log` file contains a history of API requests that have been processed by Erchef. These logs can be rotated quickly, therefore it is generally best to sort them by date, and then find the most recently updated log file: ``` ls -lrt /var/log/opscode/opscode-erchef/erchef.log.* ``` The following is an example log entry: ``` 2013-08-06T08:54:32Z erchef@127.0.0.1 INFO org_name=srwjedoqqoypgmvafmoi; req_id=g3IAA2QAEGVyY2hlZkAx ``` where important fields in this log include: * The HTTP method (`POST`) * The HTTP path (`/organizations/srwjedoqqoypgmvafmoi/environments`) * The message (`{created,<<"_default">>}`) * The organization name (`org_name=srwjedoqqoypgmvafmoi`) * The timestamp (`2013-08-06T08:54:32Z`) * The name of the user and/or Chef Infra Client which made the request (`pivotal`) In addition, the log file may contain additional entries that detail the amounts of time spent interacting with other services: * `rdbms_time` (the time spent talking to the **postgresql** service) * `req_time` (the request time) * `solr_time` (the time spent talking to the **opscode-solr** service) Application ----------- Application logs are created by the services directly, and may require log rotation policies to be applied based on organizational goals and the platform(s) on which the services are running. ### nginx The `nginx` service creates both supervisor and administrator logs. The administrator logs contain both access and error logs for each virtual host utilized by the Chef Infra Server. Each of the following logs require external log rotation. | Logs | Description | | --- | --- | | `/var/log/opscode/nginx/access.log` | The Web UI and API HTTP access logs. | | `/var/log/opscode/nginx/error.log` | The Web UI and API HTTP error logs. | | `/var/log/opscode/nginx/internal-account.access.log` | The `opscode-account` internal load-balancer access logs. | | `/var/log/opscode/nginx/internal-account.error.log` | The `opscode-account` internal load-balancer error logs. | | `/var/log/opscode/nginx/internal-authz.access.log` | The `opscode-authz` internal load-balancer access logs. | | `/var/log/opscode/nginx/internal-authz.error.log` | The `opscode-authz` internal load-balancer error logs. | | `/var/log/opscode/nginx/internal-chef.access.log` | The `opscode-chef` and `opscode-erchef` internal load-balancer access logs. | | `/var/log/opscode/nginx/internal-chef.error.log` | The `opscode-chef` and `opscode-erchef` internal load-balancer error logs. | | `/var/log/opscode/nginx/nagios.access.log` | The `nagios` access logs. | | `/var/log/opscode/nginx/nagios.error.log` | The `nagios` error logs. | | `/var/log/opscode/nginx/rewrite-port-80.log` | The rewrite logs for traffic that uses HTTP instead of HTTPS. | To follow the logs for the service: ``` chef-server-ctl tail nginx ``` #### Read Log Files The **nginx** access log format is as follows: ``` log_format opscode '$remote_addr - $remote_user [$time_local] ' '"$request" $status "$request_time" $body_bytes_sent ' '"$http_referrer" "$http_user_agent" "$upstream_addr" ' '"$upstream_status" "$upstream_response_time" "$http_x_chef_version" ' '"$http_x_ops_sign" "$http_x_ops_userid" "$http_x_ops_timestamp" ' '"$http_x_ops_content_hash" $request_length'; ``` A sample log line: ``` 192.0.2.0 - - [17/Feb/2012:16:02:42 -0800] "GET /organizations/nginx/cookbooks HTTP/1.1" 200 "0.346" 12 "-" "Chef Knife/0.10.4 (ruby-1.9.3-p0; ohai-0.6.10; x86_64-darwin11.2.0; +http://opscode.com )" "127.0.0.1:9460" "200" "0.339" "0.10.4" "version=1.0" "adam" "2012-02-18T00:02:42Z" "2jmj7l5rSw0yVb/vlWAYkK/YBwk=" 871 ``` Field descriptions: | Field | Description | | --- | --- | | `$remote_addr` | The IP address of the client who made this request. | | `$remote_user` | The HTTP basic auth user name of this request. | | `$time_local` | The local time of the request. | | `$request` | The HTTP request. | | `$status` | The HTTP status code. | | `$request_time` | The time it took to service the request. | | `$body_bytes_sent` | The number of bytes in the HTTP response body. | | `$http_referrer` | The HTTP referrer. | | `$http_user_agent` | The user agent of the requesting client. | | `$upstream_addr` | The upstream reverse proxy used to service this request. | | `$upstream_status` | The upstream reverse proxy response status code. | | `$upstream_response_time` | The upstream reverse proxy response time. | | `$http_x_chef_version` | The version of Chef used to make this request. | | `$http_x_ops_sign` | The version of the authentication protocol. | | `$http_x_ops_userid` | The client name that was used to sign this request. | | `$http_x_ops_timestamp` | The timestamp from when this request was signed. | | `$http_x_ops_content_hash` | The hash of the contents of this request. | | `$request_length` | The length of this request. | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/server_logs/An Overview of Chef InSpec ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/_index.md) Chef InSpec is an open-source framework for testing and auditing your applications and infrastructure. Chef InSpec works by comparing the actual state of your system with the desired state that you express in easy-to-read and easy-to-write Chef InSpec code. Chef InSpec detects violations and displays findings in the form of a report, but puts you in control of remediation. Getting started with Chef InSpec -------------------------------- Below are some of the core concepts that make up Chef InSpec. ### Create a profile [Profiles](profiles/index) are the core of the Chef InSpec testing experience. Use Chef InSpec profiles to manage everything you need to run a security or compliance scan–attributes, metadata, and the tests themselves. ### Add your tests You can create tests three different ways: By composing your own tests, by including tests from the [Chef Supermarket](https://supermarket.chef.io/) or by adding tests from the [Dev-Sec Project](http://dev-sec.io/) as dependencies. You can also customize your tests–pulling in the tests from our Supermarket and change them to suit your unique needs with the easy-to-read and easy-to-write Chef InSpec language. ### Target your system Run your tests wherever your infrastructure is–locally or in the cloud. Chef InSpec is designed for platforms and treats operating systems as special cases. Chef InSpec helps you, whether you use Windows Server on your own hardware or run Linux in Docker containers in the cloud. As for the cloud, you can use Chef InSpec to target applications and services running on AWS and Azure. ### Resources Chef InSpec nearly 500 [resources](resources/index) ready use–Apache2 to ZFS pool. If you need a solution that we haven’t provided, you can write your own [custom resource](dsl_resource/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/Monitor ======= [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/server_monitor.md) Monitoring the Chef Infra Server involves two types of checks: application and system. In addition monitoring the HTTP requests that workstations and nodes are making to the Chef Infra Server and per-disk data storage volumes is recommended. Monitoring Priorities --------------------- The following sections describe the priorities for monitoring of the Chef Infra Server. In particular, running out of disk space is the primary cause of failure. ### Disks Over time, and with enough data, disks will fill up or exceed the per-disk quotas that may have been set for them and they will not be able to write data. A disk that is not able to write data will not be able to support certain components of the Chef Infra Server, such as PostgreSQL, service log files, and deleted file handles. Monitoring disk usage is the best way to ensure that disks don’t fill up or exceed their quota. Use the following commands to monitor global disk usage on a Chef Infra Server with a typical installation: ``` du -sh /var/opt/opscode ``` and: ``` du -sh /var/log/opscode ``` To keep the Chef Infra Server healthy, both `/var/opt/opscode` and `/var/log/opscode` should never exceed 80% use. In situations where disk space grows at a rapid pace, it may be preferable to shut down the Chef Infra Server and contact Chef support. The following components should be monitored for signs that disks may be rapidly filling up: * **PostgreSQL** PostgreSQL is the data store for the Chef Infra Server. * **Log files** If `/var/log/opscode` is taking up a lot of disk space, ensure that the Chef Infra Server log rotation cron job is running without errors. These errors can be found in `/var/log/messages`, `/var/log/syslog` and/or the root user’s local mail. * **Deleted file handles** Running processes with file handles associated with one (or more) deleted files will prevent the disk space being used by the deleted files from being reclaimed. Use the `sudo lsof | grep '(deleted)'` command to find all deleted file handles. Application Checks ------------------ Application-level checks should be done periodically to ensure that there is enough disk space, enough memory, and that the front-end and back-end services are communicating. ### Erlang Many components of the Chef Infra Server are written using Erlang and run on the BEAM virtual machine. One feature of Erlang and BEAM is the ability to interact with the running service using a command shell. For example: ``` cd /opt/opscode/embedded export PATH=$PATH:/opt/opscode/bin:/opt/opscode/embedded/bin bin/erl -setcookie service_name -name me@127.0.0.1 -remsh service_name@127.0.0.1 ``` where `service_name` is `bifrost` or `erchef`. This command will then open a shell that is connected to the Erchef processes: ``` Erlang R15B02 (erts-5.9.2) [source] [64-bit] ... ``` Warning Connecting to the Erlang processes should only be done when directed by Chef support services. To connect to the **oc_bifrost** service, use the following command: ``` erl -setcookie oc_bifrost -name me@127.0.0.1 -remsh oc_bifrost@127.0.0.1 ``` To connect to the **opscode-erchef** service, use the following command: ``` erl -setcookie erchef -name me@127.0.0.1 -remsh erchef@127.0.0.1 ``` To disconnect from the shell, use the following key sequence `CTRL-g`, `q`, and then `ENTER`. The output from the shell after the `CTRL-g` looks similar to: ``` (erchef@127.0.0.1)1> User switch command ``` then enter `q`, and then hit `ENTER` to exit the shell. Some commands should not be entered when interacting with a running service while using the command shell, including: * `q()` kills the Erlang node * `init:stop()` * `exit` or `exit()` does nothing #### `eper` tools As root on the Chef Infra Server, point to the bundled `eper` package of debugging tools. Replace the 2nd and 5th path entries and the `X.XX.X` value in the following path with the items that occur on the system. ``` export ERL_LIB=:/opt/{chef-server,opscode}/embedded/service/{erchef,opscode-erchef}/lib/eper-X.XX.X/ebin/ ``` Open an Erlang command shell to begin diagnosing service issues on the Chef Infra Server: ``` Eshell V5.10.4 (abort with ^G) (erchef@127.0.0.1)1``` The `dtop` tool presents a view on the Erlang virtual machine that is similar to the `linuxdagnostic` command. The period at the end of the dtop command is required for the command to take effect. ``` (erchef@127.0.0.1)1> dtop:start(). ``` To stop the `dtop` command, run: ``` (erchef@127.0.0.1)1> dtop:stop(). ``` To disconnect from the shell, use the following key sequence `CTRL-g`, `q`, and then `ENTER`. The output from the shell after the `CTRL-g` looks similar to: ``` (erchef@127.0.0.1)1> User switch command ``` then enter `q`, and then hit `ENTER` to exit the shell. ### Nginx Use Nginx to monitor for services that may be returning 504 errors. Use the following command on a front-end machine: ``` grep 'HTTP/1.1" 504' /var/log/opscode/nginx/access.log ``` and then extract the URLs and sort them by `uniq` count: ``` grep 'HTTP/1.1" 504' nginx-access.log | cut -d' ' -f8 | sort | uniq -c | sort ``` In a large installation, restricting these results to a subset of results may be necessary: ``` tail -10000 nginx-access.log | grep 'HTTP/1.1" 504' | cut -d' ' -f8 | sort | uniq -c | sort ``` ### PostgreSQL psql is the management tool for PostgreSQL. It can be used to obtain information about data stored in PostgreSQL. For more information about psql, see <http://www.postgresql.org/docs/manuals/>, and then the doc set appropriate for the version of PostgreSQL being used. To connect to the PostgreSQL database, run the following command: ``` cd /opt/opscode/embedded/service/postgresql/ export PATH=$PATH:/opt/opscode/bin:/opt/opscode/embedded/bin bin/psql -U opscode_chef ``` Warning Connecting to the PostgreSQL database should only be done when directed by Chef support services. ### Redis The **redis_lb** service located on the back end machine handles requests that are made from the Nginx service that is located on all front end machines in a Chef Infra Server cluster. In the event of a disk full condition for the Redis data store, the `dump.rdb` (the primary data store `.rdb` used by Redis) can become corrupt and saved as a zero byte file. When this occurs, after the **redis_lb** service started, it’s logs will show a statement similar to the following: ``` 2015-03-23_16:11:31.44256 [11529] 23 Mar 16:10:09.624 # Server started, Redis version 2.8.2 2015-03-23_16:11:31.44256 [11529] 23 Mar 16:10:09.624 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect. 2015-03-23_16:11:31.44257 [11529] 23 Mar 16:11:31.438 # Short read or OOM loading DB. Unrecoverable error, aborting now. ``` The `dump.rdb` file will be empty: ``` ls -al /var/opt/opscode/redis_lb/data/ total 20 drwxr-x--- 2 opscode opscode 4096 Mar 23 15:58 . drwxr-x--- 4 opscode opscode 4096 Dec 22 18:59 .. -rw-r--r-- 1 opscode opscode 0 Mar 23 15:58 dump.rdb ``` This situation is caused by a bug in Redis where saves are allowed to succeed even when the disk has been full for some time, and not just on edge cases where the disk becomes full as Redis is writing. To fix this issue, do the following: 1. Stop the **redis_lb** service: ``` chef-server-ctl stop redis_lb ``` 2. Remove the corrupt files: ``` cd /var/opt/opscode/redis_lb/data rm -fr *rdb ``` 3. Start the **redis_lb** service: ``` chef-server-ctl start redis_lb less /var/log/opscode/redis_lb/current 2015-03-23_17:05:18.82516 [28676] 23 Mar 17:05:18.825 * The server is now ready to accept connections on port 16379 ``` 4. Reconfigure the Chef Infra Server to re-populate Redis: ``` chef-server-ctl reconfigure ``` 5. Verify that Redis is re-populated, as indicated by the key `dl_default`: ``` /opt/opscode/embedded/bin/redis-cli -p 16379 keys \* 1) "dl_default" ``` System Checks ------------- System-level checks should be done for the ports and services status. ### chef-backend-ctl status The `chef-backend-ctl status` subcommand is used to check the status of services running in the [Chef Backend server topology](../install_server_ha/index). This command will verify the status of the following services on the node it is run on: * `leaderl` * `postgresql` * `etcd` * `epmd` * `elasticsearch` It will also check on the status of other nodes in the cluster, from the current node’s perspective. For example: ``` chef-backend-ctl status Service Local Status Time in State Distributed Node Status leaderl running (pid 1191) 53d 15h 11m 12s leader: 1; waiting: 0; follower: 2; total: 3 epmd running (pid 1195) 53d 15h 11m 12s status: local-only etcd running (pid 1189) 53d 15h 11m 12s health: green; healthy nodes: 3/3 postgresql running (pid 40686) 0d 12h 36m 23s leader: 1; offline: 0; syncing: 0; synced: 2 elasticsearch running (pid 47423) 0d 12h 18m 6s state: green; nodes online: 3/3 System Local Status Distributed Node Status disks /var/log/chef-backend: OK; /var/opt/chef-backend: OK health: green; healthy nodes: 3/3 ``` More information about each service can be found in the individual service logs in `/var/opt/chef-backend/`. ### opscode-authz The authz API provides a high-level view of the health of the **opscode-authz** service with a simple endpoint: `_ping`. This endpoint can be accessed using cURL and GNU Wget. For example: ``` curl http://localhost:9463/_ping ``` This command typically prints a lot of information. Use Python to use pretty-print output: ``` curl http://localhost:9463/_ping | python -mjson.tool ``` ### opscode-erchef The status API provides a high-level view of the health of the system with a simple endpoint: `_status`. This endpoint can be accessed using cURL and GNU Wget. For example: ``` curl http://localhost:8000/_status ``` which will return something similar to: ``` { "status":"pong", "upstreams":{"upstream_service":"pong","upstream_service":"fail",...}, } ``` For each of the upstream services, `pong` or `fail` is returned. The possible upstream names are: * `chef_sql` (for the **postgresql** service) * `oc_chef_authz` (for the **opscode-authz** service) If any of the status values return `fail`, this typically means the Chef Infra Server is unavailable for that service. Nodes, Workstations ------------------- If a client makes an HTTP request to the server that returns a non-specific error message, this is typically an issue with the **opscode-chef** or **opscode-erchef** services. View the full error message for these services in their respective log files. The error is most often a stacktrace from the application error. In some cases, the error message will clearly indicate a problem with another service, which can then be investigated further. For non-obvious errors, please contact Chef support services. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/server_monitor/Install and Uninstall ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/install.md) Users can choose between operating systems of MacOS, Windows, and Linux for Chef InSpec. Install Chef InSpec ------------------- You can download the latest Chef InSpec package relevant to your operating system at [our Downloads Page](https://downloads.chef.io/inspec). Alternatively, Chef InSpec can be installed via installer, script, or package manager, according to your operating system and method as listed below. ### macOS #### Homebrew Chef InSpec is available as a standalone [Homebrew](https://brew.sh/) package. Run the following command in your terminal to install Chef InSpec: ``` brew install chef/chef/inspec ``` While this command is running, you may be prompted to enter your macOS user account password for installation to complete. #### CLI You can download Chef InSpec via curl script: ``` curl https://omnitruck.chef.io/install.sh | sudo bash -s -- -P inspec ``` ### Windows #### Installer Once you downloaded the latest [Chef InSpec package](https://downloads.chef.io/inspec) relevant to your Microsoft version, double-click the `.msi` file to launch the installer and follow the prompts. #### Powershell Use the following command to install Chef InSpec via Powershell script: ``` . { iwr -useb https://omnitruck.chef.io/install.ps1 } | iex; install -project inspec ``` Once Chef InSpec is installed, run `inspec version` to verify that the installation was successful. ### Linux #### CLI The following curl script will install Chef InSpec for Ubuntu and Red Hat Enterprise Linux: ``` curl https://omnitruck.chef.io/install.sh | sudo bash -s -- -P inspec ``` If you prefer, you can use a package manager to install Chef InSpec. Once you downloaded the latest [Chef InSpec package](https://downloads.chef.io/inspec) relevant to your Linux-based platform, use the command for the respective package manager listed below. Replace the example file path with the file path leading to your downloaded package. For Ubuntu, use the following command to install Chef InSpec: ``` sudo dpkg -i /path/to/inspec.deb ``` For Red Hat Enterprise Linux, use the following command to install Chef InSpec: ``` sudo rpm -U /path-to/inspec.rpm ``` For SUSE Linux Enterprise Server, use the following command to install Chef InSpec: ``` sudo zypper install /path-to/inspec.rpm ``` Uninstall Chef InSpec --------------------- Chef InSpec can be uninstalled using the steps below that are appropriate for the method of Chef InSpec installation. ### macOS #### Homebrew Use the following *destructive* command to remove the Chef InSpec standalone Homebrew package: ``` brew cask uninstall inspec ``` #### CLI Use the following *destructive* command in your terminal to remove the Chef InSpec package: ``` sudo rm -rf /opt/inspec ``` ### Windows #### Installer Use *Add / Remove Programs* to remove Chef InSpec. ### Linux #### CLI The supported Linux-based platforms and their respective *destructive* command for their package manager are listed below. For Ubuntu, use the following *destructive* command to uninstall: ``` sudo dpkg -P inspec ``` For Red Hat Enterprise Linux, use the following *destructive* command to uninstall: ``` sudo rpm -e inspec ``` For SUSE Linux Enterprise Server, use the following *destructive* command to uninstall Chef InSpec: ``` sudo zypper remove inspec ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/install/chef-server-ctl (executable) ============================ [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/ctl_chef_server.md) The Chef Infra Server includes a command-line utility named chef-server-ctl. This command-line tool is used to start and stop individual services, reconfigure the Chef Infra Server, run chef-pedant, and then tail Chef Infra Server log files. Backup / Restore ---------------- Use the following commands to manage backups of Chef Infra Server data, and then to restore those backups. ### backup The `backup` subcommand is used to back up all Chef Infra Server data. This subcommand: * Requires rsync to be installed on the Chef Infra Server prior to running the command * Requires a `chef-server-ctl reconfigure` prior to running the command * Should not be run in a Chef Infra Server configuration with an external PostgreSQL database; [use knife ec backup](https://github.com/chef/knife-ec-backup) instead * Puts the initial backup in the `/var/opt/chef-backup` directory as a tar.gz file; move this backup to a new location for safe keeping **Options** This subcommand has the following options: `-y`, `--yes` Use to specify if the Chef Infra Server can go offline during tar.gz-based backups. `--pg-options` Use to specify and pass additional options PostgreSQL during backups. See the [PostgreSQL documentation](https://www.postgresql.org/docs/13/runtime-config.html) for more information. `-c`, `--config-only` Backup the Chef Infra Server configuration **without** backing up data. `-t`, `--timeout` Set the maximum amount of time in seconds to wait for shell commands (default 600). This option should be set to greater than 600 for backups taking longer than 10 minutes. `-h`, `--help` Show help message. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl backup ``` ### restore The `restore` subcommand is used to restore Chef Infra Server data from a backup that was created by the `backup` subcommand. This subcommand may also be used to add Chef Infra Server data to a newly-installed server. Do not run this command in a Chef Infra Server configuration that uses an external PostgreSQL database; [use knife ec backup](https://github.com/chef/knife-ec-backup) instead. This subcommand: * Requires rsync installed on the Chef Infra Server before running the command * Requires a `chef-server-ctl reconfigure` before running the command Ideally, the restore server will have the same FQDN as the server that you backed up. If the restore server has a different FQDN, then: 1. Replace the FQDN in the `/etc/opscode/chef-server.rb`. 2. Replace the FQDN in the `/etc/opscode/chef-server-running.json`. 3. Delete the old SSL certificate, key and `-ssl.conf` file from `/var/opt/opscode/nginx/ca`. 4. If you use a CA-issued certificate instead of a self-signed certificate, copy the CA-issued certificate and key into `/var/opt/opscode/nginx/ca`. 5. Update the `/etc/chef/client.rb` file on each client to point to the new server FQDN. 6. Run `chef-server-ctl reconfigure`. 7. Run ``chef-server-ctl restore`. **Options** This subcommand has the following options: `-c`, `--cleanse` Use to remove all existing data on the Chef Infra Server; it will be replaced by the data in the backup archive. `-d DIRECTORY`, `--staging-dir DIRECTORY` Use to specify that the path to an empty directory to be used during the restore process. This directory must have enough disk space to expand all data in the backup archive. `--pg-options` ``` : Use to specify and pass additional options PostgreSQL during backups. See the [PostgreSQL documentation](https://www.postgresql.org/docs/13/runtime-config.html) for more information. `-t`, `--timeout` : Set the maximum amount of time in seconds to wait for shell commands. Set to greater than 600 for backups that take longer than 10 minutes. Default: 600. `-h`, `--help` : Show help message. **Syntax** This subcommand has the following syntax: ```bash chef-server-ctl restore PATH_TO_BACKUP (options) ``` **Examples** ``` chef-server-ctl restore /path/to/tar/archive.tar.gz ``` cleanse ------- The `cleanse` subcommand is used to re-set the Chef Infra Server to the state it was in prior to the first time the `reconfigure` subcommand is run. This command will destroy all data, configuration files, and logs. The software that was put on-disk by the package installation will remain; re-run `chef-server-ctl reconfigure` to recreate the default data and configuration files. **Options** This subcommand has the following options: `--with-external` Use to specify that Chef Infra Server data on an external PostgreSQL database should be removed. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl cleanse ``` gather-logs ----------- The `gather-logs` subcommand is used to gather the Chef Infra Server log files into a tarball that contains all of the important log files and system information. This subcommand has the following syntax: ``` chef-server-ctl gather-logs ``` help ---- The `help` subcommand is used to print a list of all available chef-server-ctl commands. This subcommand has the following syntax: ``` chef-server-ctl help ``` install ------- The `install` subcommand is used to install premium features of the Chef Infra Server: Chef management console and Chef Infra Client run reporting, high availability configurations, and Chef Infra Server replication. Warning The `chef-server-ctl install` command no longer works in the 12.5 (and earlier) versions of the Chef Infra Server due to a change in how packages are downloaded from Chef. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl install name_of_addon (options) ``` where `name_of_addon` represents the command line value associated with the add-on or premium feature. **Options** This subcommand has the following options: `--path PATH` Use to specify the location of a package. This option is not required when packages are downloaded from <https://packages.chef.io/>. ### Use Downloads The `install` subcommand downloads packages from <https://packages.chef.io> by default. For systems that are not behind a firewall (and have connectivity to <https://packages.chef.io>), these packages can be installed as described below. 1. Install add-ons Install Chef Manage with: ``` sudo chef-server-ctl install chef-manage ``` 2. Reconfigure the server ``` sudo chef-server-ctl reconfigure ``` 3. Reconfigure add-ons Reconfigure Chef Manage with: ``` sudo chef-manage-ctl reconfigure ``` Finally, accept the [Chef License](../../chef_license/index): ``` sudo chef-manage-ctl reconfigure --accept-license ``` ### Use Local Packages Use the `install` subcommand with the `--path` option to install the Chef Manage (`chef-manage`) add-on for Chef Infra Server. ``` sudo chef-server-ctl install PACKAGE_NAME --path /path/to/package/directory ``` For example: ``` sudo chef-server-ctl install chef-manage --path /root/packages ``` The `chef-server-ctl` command will install the first `chef-manage` package found in the `/root/packages` directory. Key Rotation ------------ Use the following commands to manage public and private key rotation for users and clients. ### add-client-key Use the `add-client-key` subcommand to add a client key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl add-client-key ORG_NAME CLIENT_NAME [--public-key-path PATH] [--expiration-date DATE] [--key-name NAME] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `CLIENT_NAME` The name of the client that you wish to add a key for. `-e DATE` `--expiration-date DATE` An ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. For example: `2013-12-24T21:00:00Z`. If not passed, expiration will default to infinity. `-k NAME` `--key-name NAME` String defining the name of your new key for this client. If not passed, it will default to the fingerprint of the public key. `ORG_NAME` The short name for the organization to which the client belongs. `-p PATH` `--public-key-path PATH` The location to a file containing valid PKCS#1 public key to be added. If not passed, then the server will generate a new one for you and return the private key to STDOUT. ### add-user-key Use the `add-user-key` subcommand to add a user key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl add-user-key USER_NAME [--public-key-path PATH] [--expiration-date DATE] [--key-name NAME] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `-e DATE` `--expiration-date DATE` An ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. For example: `2013-12-24T21:00:00Z`. If not passed, expiration will default to infinity. `-k NAME` `--key-name NAME` String defining the name of your new key for this user. If not passed, it will default to the fingerprint of the public key. `-p PATH` `--public-key-path PATH` The location to a file containing valid PKCS#1 public key to be added. If not passed, then the server will generate a new one for you and return the private key to STDOUT. `USER_NAME` The user name for the user for which a key is added. ### delete-client-key Use the `delete-client-key` subcommand to delete a client key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl delete-client-key ORG_NAME CLIENT_NAME KEY_NAME ``` **Options** This subcommand has the following arguments: `ORG_NAME` The short name for the organization to which the client belongs. `CLIENT_NAME` The name of the client. `KEY_NAME` The unique name to be assigned to the key you wish to delete. ### delete-user-key Use the `delete-user-key` subcommand to delete a user key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl delete-user-key USER_NAME KEY_NAME ``` Warning The parameters for this subcommand must be in the order specified above. **Options** This subcommand has the following arguments: `USER_NAME` The user name. `KEY_NAME` The unique name to be assigned to the key you wish to delete. ### list-client-keys Use the `list-client-keys` subcommand to list client keys. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl list-client-keys ORG_NAME CLIENT_NAME [--verbose] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `CLIENT_NAME` The name of the client. `ORG_NAME` The short name for the organization to which the client belongs. `--verbose` Use to show the full public key strings in command output. ### list-user-keys Use the `list-user-keys` subcommand to list client keys. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl list-user-keys USER_NAME [--verbose] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `USER_NAME` The user name you wish to list keys for. `--verbose` Use to show the full public key strings in command output. **Example** To view a list of user keys (including public key output): ``` chef-server-ctl list-user-keys applejack --verbose ``` Returns: ``` 2 total key(s) found for user applejack key_name: test-key expires_at: Infinity public_key: -----BEGIN PUBLIC KEY----- <KEY> -----END PUBLIC KEY----- key_name: default expires_at: Infinity public_key: -----BEGIN PUBLIC KEY----- <KEY> ``` Secrets Management ------------------ Use the following commands to manage and rotate shared secrets and service credentials. The secrets file used for storing these is located at `/etc/opscode/private-chef-secrets.json` on your Chef Infra Server. It should be owned and readable only by `root`. ### set-secret The `set-secret` subcommand allows storing shared secrets and service credentials. Only secrets known to Chef Infra Server can be stored. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl set-secret GROUP NAME ``` There are various ways to pass the secret to this command: 1. as a third argument: ``` chef-server-ctl set-secret ldap bind_password secretpassword ``` 2. via an environment variable: ``` export LDAP.BIND_PASSWORD="secretpassword" chef-server-ctl set-secret ldap bind_password ``` 3. via an interactive prompt: ``` chef-server-ctl set-secret ldap bind_password Enter ldap bind_password: (no terminal output) Re-enter ldap bind_password: (no terminal output) ``` **Options** This subcommand has the following options: `--with-restart` If any services depend on the secret being changed, attempt to restart them after changing the secret. Added in Chef Infra Server 12.16.2. ### remove-secret The `remove-secret` subcommand allows removing a stored shared secret and service credential. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl remove-secret GROUP NAME ``` **Example** ``` chef-server-ctl remove-secret ldap bind_password ``` ### show-secret The `show-secret` subcommand allows viewing a stored shared secret and service credential. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl show-secret GROUP NAME ``` ### set-db-superuser-password The `set-db-superuser-password` subcommand allows storing the database superuser password. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl set-db-superuser-password ``` Similar to `set-secret`, the superuser password can also be provided via the environment variable `DB_PASSWORD`. ### set-actions-password The `set-actions-password` subcommand allows storing the RabbitMQ Actions password. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl set-actions-password ``` Similar to `set-secret`, the action password can also be provided via the environment variable `ACTIONS_PASSWORD`. ### oc-id-show-app The `oc-id-show-app` subcommand allows for retrieving the client ID and client secret for applications known to **oc-id**. Note that with `insecure_addon_compat` [disabled](../server_security/index#chef-infra-server-credentials-management), this data will no longer be written to `/etc/opscode/oc-id-applications/APP.json`. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl oc-id-show-app APP ``` **Example** ``` chef-server-ctl oc-id-show-app supermarket { "name": "supermarket", "uid": "0bad0f2eb04e935718e081fb71asdfec3681c81acb9968a8e1e32451d08b", "secret": "17cf1141cc971a10ce307611beda7ffadstr4f1bc98d9f9ca76b9b127879", "redirect_uri": "https://supermarket.mycompany.com/auth/chef_oauth2/callback" } ``` ### require-credential-rotation The `require-credential-rotation` subcommand takes the Chef Infra Server offline and requires a complete service credential rotation before the Chef Infra Server(s) in your cluster can restart again. Run `rotate-shared-secrets` to create a new shared secret, salt, and generate the new service credentials. Then copy the secrets file to each Chef Infra Server and run `sudo chef-server-ctl reconfigure` on each server to complete the rotation process. Note Credential rotation does not rotate the pivotal, user, or client keys, or remove any Chef Infra Server policy or cookbooks that have been uploaded. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl require-credential-rotation (options) ``` **Options** This subcommand has the following options: `-y, --yes` Bypass a prompt in the terminal and agree that you want to disable the Chef Infra Server, and require credential rotation. ### rotate-all-credentials The `rotate-all-credentials` subcommand generates new credential values for all service credentials by incrementing the credential version number and creating a new hash value. You can choose whether to copy the updated secrets file to each node in the cluster and reconfiguring or by running this subcommand on all the nodes. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl rotate-all-credentials ``` ### rotate-credentials The `rotate-credentials` subcommand generates new credential values for all credentials for a given service by incrementing the value and creating a new hash value. You can choose whether to copy the updated secrets file to each node in the cluster and reconfiguring or by running this subcommand for that specific service on all the nodes. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl rotate-credentials SERVICE_NAME ``` ### rotate-shared-secrets The `rotate-shared-secrets` subcommand creates a new shared secret and salt, in addition to generating new service credentials. It also resets the `credential_version` number for the services to 0. After you have run this subcommand, a new shared secret has been created, so you must copy the secrets file to each Chef Infra Server and run `sudo chef-server-ctl reconfigure` on them to complete the rotation process. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl rotate-shared-secrets ``` ### show-service-credentials The `show-service-credentials` subcommand shows all of the service credentials for services running on the local Chef Infra Server. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl show-service-credentials ``` ### cleanup-bifrost The `cleanup-bifrost` subcommand removes unused authorization objects from the authorization database (called bifrost). These unused objects can accumulate on long-running Chef Infra Servers as a result of failed object creation requests. For most users, the unused authorization objects do not substantially affect the performance of Chef Infra Server; however in certain situations it can be helpful to clean them up. This command is primarily intended for use by Chef support. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl cleanup-bifrost OPTIONS ``` **Options** This subcommand has the following options: `--estimate-only` Provides an estimate of the number of unused objects that will be deleted, without deleting anything. `--wait-time SECONDS` The number of seconds to wait for in-flight requests to complete. Only decrease this value if you are running the command when the Chef Infra Server is not taking requests. `--force-cleanup` Removes internal tracking tables used during the cleanup process. Manual cleanup of these tables is only required if the cleanup command is killed unexpectedly. `--batch-size` The number of orphaned authorization actors to delete at a time. Manage Organizations -------------------- Use the `org-create`, `org-delete`, `org-list`, `org-show`, `org-user-add` and `org-user-remove` commands to manage organizations. ### org-create The `org-create` subcommand is used to create an organization. (The validation key for the organization is returned to `STDOUT` when creating an organization with this command.) **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-create ORG_NAME "ORG_FULL_NAME" (options) ``` where: * The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. * The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `"Chef Software, Inc."`. **Options** This subcommand has the following options: `-a USER_NAME`, `--association_user USER_NAME` Associate a user with an organization and add them to the `admins` and `billing_admins` security groups. `-f FILE_NAME`, `--filename FILE_NAME` Write the ORGANIZATION-validator.pem to `FILE_NAME` instead of printing it to `STDOUT`. **Examples** ``` chef-server-ctl org-create prod Production ``` ``` chef-server-ctl org-create staging Staging -a chef-admin ``` ``` chef-server-ctl org-create dev Development -f /tmp/id-dev.key ``` ``` chef-server-ctl org-create dev Development --association_user grantmc ``` ### org-delete The `org-delete` subcommand is used to delete an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-delete ORG_NAME ``` **Examples** ``` chef-server-ctl org-delete infra-testing-20140909 ``` ``` chef-server-ctl org-delete pedant-testing-org ``` ### org-list The `org-list` subcommand is used to list all of the organizations currently present on the Chef Infra Server. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-list (options) ``` **Options** This subcommand has the following options: `-a`, `--all-orgs` Show all organizations. `-w`, `--with-uri` Show the corresponding URIs. ### org-show The `org-show` subcommand is used to show the details for an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-show ORG_NAME ``` ### org-user-add The `org-user-add` subcommand is used to add a user to an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-user-add ORG_NAME USER_NAME (options) ``` **Options** This subcommand has the following options: `--admin` Add the user to the `admins` group. **Examples** ``` chef-server-ctl org-user-add prod john_smith ``` ``` chef-server-ctl org-user-add preprod testmaster ``` ``` chef-server-ctl org-user-add dev grantmc --admin ``` ### org-user-remove The `org-user-remove` subcommand is used to remove a user from an organization. Warning A user who belongs to the `admins` group must be removed from the group before they may be removed from an organization. To remove a user from the `admins` group, run the following: ``` EDITOR=vi knife edit /groups/admins.json ``` make the required changes, and then save the file. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-user-remove ORG_NAME USER_NAME (options) ``` **Options** This subcommand has the following options: `--force` Force the removal of a user from the organization’s `admins` and `billing-admins` groups. **Examples** ``` chef-server-ctl org-user-remove prod john_smith ``` ``` chef-server-ctl org-user-remove prod testmaster ``` ``` chef-server-ctl org-user-remove grantmc --force ``` password -------- The `password` subcommand is used to change a user’s password. When Active Directory or LDAP is enabled, this command enables (or disables) the system recovery password for that user. For example: This subcommand has the following syntax: ``` chef-server-ctl password USERNAME ``` This subcommand has the following options: `--disable` Use this option to disable a user’s system recovery password. **Examples** For example, to change a user’s password, enter: ``` chef-server-ctl password adamjacobs ``` and then enter the password and confirm it: ``` Enter the new password: ****** Enter the new password again: ****** ``` to return: ``` Password for adamjacobs successfully set. ``` To disable a system recovery password: ``` chef-server-ctl password adamjacobs --disable ``` to return: ``` Password for adamjacobs successfully disabled for System Recovery. ``` psql ---- The `psql` subcommand is used to log into the PostgreSQL database associated with the named service. This subcommand: * Uses `psql` (the interactive terminal for PostgreSQL) * Has read-only access by default * Is the recommended way to interact with any PostgreSQL database that is part of the Chef Infra Server * Automatically handles authentication **Syntax** This subcommand has the following syntax: ``` chef-server-ctl psql SERVICE_NAME (options) ``` **Options** This subcommand has the following options: `--write` Use to enable write access to the PostgreSQL database. reconfigure ----------- The `reconfigure` subcommand is used when changes are made to the chef-server.rb file to reconfigure the server. When changes are made to the chef-server.rb file, they will not be applied to the Chef Infra Server configuration until after this command is run. This subcommand will also restart any services for which the `service_name['enabled']` setting is set to `true`. This subcommand has the following syntax: ``` chef-server-ctl reconfigure ``` reindex ------- The `reindex` subcommand is used to reload Chef Infra Server data from PostgreSQL to Elasticsearch. This subcommand has the following syntax: ``` chef-server-ctl reindex ``` Note Chef Infra Server versions earlier than 14.5 configured with `nginx['enable_non_ssl'] = false` and `fips = true` require `export CSC_LB_URL=https://127.0.0.1` to run the command `chef-server-ctl reindex <options>` **Options** This subcommand has the following options: `-a`, `--all-orgs` Use to reindex all organizations on the Chef Infra Server. This option will override any organization specified as part of the command, i.e. `chef-server-ctl reindex ORG_NAME -a` will reindex all organizations and not just the specified organization. `-d`, `--disable-api` Use to disable the Chef Infra Server API to prevent writes during reindexing. `-t`, `--with-timing` Use to print timing information for the reindex processes. `-w`, `--wait` Use to wait for the reindexing queue to clear before exiting. This option only works when run on a standalone Chef Infra Server or on a primary backend Chef server within a legacy tier. Server Admins ------------- The `server-admins` group is a global group that grants its members permission to create, read, update, and delete user accounts, with the exception of superuser accounts. The `server-admins` group is useful for users who are responsible for day-to-day administration of the Chef Infra Server, especially user management via the `knife user` subcommand. Before members can be added to the `server-admins` group, they must already have a user account on the Chef Infra Server. ### Scenario The following user accounts exist on the Chef Infra Server: `pivotal` (a superuser account), `alice`, `bob`, `carol`, and `dan`. Run the following command to view a list of users on the Chef Infra Server: ``` chef-server-ctl user-list ``` and it returns the same list of users: ``` pivotal alice bob carol dan ``` Alice is a member of the IT team whose responsibilities include day-to-day administration of the Chef Infra Server, in particular managing the user accounts on the Chef Infra Server that are used by the rest of the organization. From a workstation, Alice runs the following command: ``` knife user list -c ~/.chef/alice.rb ``` and it returns the following error: ``` ERROR: You authenticated successfully to <chef_server_url> as alice but you are not authorized for this action Response: Missing read permission ``` Alice is not a superuser and does not have permissions on other users because user accounts are global to organizations in the Chef Infra Server. Let’s add Alice to the `server-admins` group: ``` chef-server-ctl grant-server-admin-permissions alice ``` and it returns the following response: ``` User alice was added to server-admins. ``` Alice can now create, read, update, and delete user accounts on the Chef Infra Server, even for organizations to which Alice is not a member. From a workstation, Alice re-runs the following command: ``` knife user list -c ~/.chef/alice.rb ``` which now returns: ``` pivotal alice bob carol dan ``` Alice is now a server administrator and can use the following knife subcommands to manage users on the Chef Infra Server: * `knife user-create` * `knife user-delete` * `knife user-edit` * `knife user-list` * `knife user-show` For example, Alice runs the following command: ``` knife user edit carol -c ~/.chef/alice.rb ``` and the $EDITOR opens in which Alice makes changes, and then saves them. #### Superuser Accounts Superuser accounts may not be managed by users who belong to the `server-admins` group. For example, Alice attempts to delete the `pivotal` superuser account: ``` knife user delete pivotal -c ~/.chef/alice.rb ``` and the following error is returned: ``` ERROR: You authenticated successfully to <chef_server_url> as user1 but you are not authorized for this action Response: Missing read permission ``` Alice’s action is unauthorized even with membership in the `server-admins` group. ### Manage server-admins Group Membership of the `server-admins` group is managed with a set of `chef-server-ctl` subcommands: * `chef-server-ctl grant-server-admin-permissions` * `chef-server-ctl list-server-admins` * `chef-server-ctl remove-server-admin-permissions` #### Add Members The `grant-server-admin-permissions` subcommand is used to add a user to the `server-admins` group. Run the command once per user added. This subcommand has the following syntax: ``` chef-server-ctl grant-server-admin-permissions USER_NAME ``` where `USER_NAME` is the user to add to the list of server administrators. For example: ``` chef-server-ctl grant-server-admin-permissions bob ``` returns: ``` User bob was added to server-admins. This user can now list, read, and create users (even for orgs they are not members of) for this Chef Infra Server. ``` #### Remove Members The `remove-server-admin-permissions` subcommand is used to remove a user from the `server-admins` group. Run the command once per user removed. This subcommand has the following syntax: ``` chef-server-ctl remove-server-admin-permissions USER_NAME ``` where `USER_NAME` is the user to remove from the list of server administrators. For example: ``` chef-server-ctl remove-server-admin-permissions bob ``` returns: ``` User bob was removed from server-admins. This user can no longer list, read, and create users for this Chef Infra Server except for where they have default permissions (such as within an org). ``` #### List Membership The `list-server-admins` subcommand is used to return a list of users who are members of the `server-admins` group. This subcommand has the following syntax: ``` chef-server-ctl list-server-admins ``` and will return a list of users similar to: ``` pivotal alice bob carol dan ``` show-config ----------- The `show-config` subcommand is used to view the configuration that will be generated by the `reconfigure` subcommand. This command is most useful in the early stages of a deployment to ensure that everything is built properly prior to installation. This subcommand has the following syntax: ``` chef-server-ctl show-config ``` uninstall --------- The `uninstall` subcommand is used to remove the Chef Infra Server application, but without removing any of the data. This subcommand will shut down all services (including the `runit` process supervisor). This subcommand has the following syntax: ``` chef-server-ctl uninstall ``` Note To revert the `uninstall` subcommand, run the `reconfigure` subcommand (because the `start` subcommand is disabled by the `uninstall` command). upgrade ------- The `upgrade` subcommand is used to upgrade the Chef Infra Server. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl upgrade (options) ``` **Options** This subcommand has the following options: `-d DIRECTORY`, `--chef11-data-dir DIRECTORY` The directory in which Chef Infra Server 11 data is located. Default value: a temporary directory. `-e DIRECTORY`, `--chef12-data-dir DIRECTORY` The directory in which Chef Infra Server 12 data is located. Default value: a temporary directory. `-f FULL_NAME`, `--full-org-name FULL_NAME` The full name of the Chef Infra Server organization. The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `Chef Software, Inc.`. If this option is not specified, the `upgrade` command will prompt for it. `-h`, `--help` Use to show help for the `chef-server-ctl upgrade` subcommand. `-k KEY_PATH`, `--key KEY_PATH` The Chef Infra Server 11 `admin.pem` key for the API client. This is the key used to download Chef Infra Server 11 data. Default value: `/etc/chef-server/admin.pem`. `-o ORG_NAME`, `--org-name ORG_NAME` The name of the Chef Infra Server organization. The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. If this option is not specified, the `upgrade` command will prompt for it. `-s URL`, `--chef11-server-url URL` The URL for the Chef Infra Server version 11. Default value: `https://localhost`. `-t NUMBER`, `--upload-threads NUMBER` The number of threads to use when migrating cookbooks. Default value: `10`. `-u USER`, `--user` Create a client as an admin client. This is required for any user to access Chef as an administrator. `-x URL`, `--chef12-server-url URL` The URL for the Chef Infra Server, version 12. Default value: `https://localhost`. `-y`, `--yes` Use to skip confirmation prompts during the upgrade process. User Management --------------- Use the `user-create`, `user-delete`, `user-edit`, `user-list` and `user-show` subcommands to manage users. ### user-create The `user-create` subcommand is used to create a user. (The validation key for the organization may be returned to `STDOUT` when creating a user with this command.) **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-create USER_NAME FIRST_NAME [MIDDLE_NAME] LAST_NAME EMAIL 'PASSWORD' (options) ``` **Options** This subcommand has the following options: `-f FILE_NAME`, `--filename FILE_NAME` Write the USER.pem to a file instead of `STDOUT`. **Examples** ``` chef-server-ctl user-create john_smith <NAME> <EMAIL> p@s5w0rD! ``` ``` chef-server-ctl user-create jane_doe <NAME> <EMAIL> p@s5w0rD! -f /tmp/jane_doe.key ``` ``` chef-server-ctl user-create waldendude <NAME> <EMAIL> excursions ``` ### user-delete The `user-delete` subcommand is used to delete a user. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-delete USER_NAME ``` **Examples** ``` chef-server-ctl user-delete john_smith ``` ``` chef-server-ctl user-delete jane_doe ``` **Options** This subcommand has the following options: `-R`, `--remove-from-admin-groups` Removes a user who is in one or more ‘admin’ groups unless that user is the only member of the ‘admin’ group(s). ### user-edit The `user-edit` subcommand is used to edit the details for a user. The data will be made available in the $EDITOR for editing. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-edit USER_NAME ``` **Examples** ``` chef-server-ctl user-edit john_smith ``` ``` chef-server-ctl user-edit jane_doe ``` ### user-list The `user-list` subcommand is used to view a list of users. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-list (options) ``` **Options** This subcommand has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### user-show The `user-show` subcommand is used to show the details for a user. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-show USER_NAME (options) ``` **Options** This subcommand has the following options: `-l`, `--with-orgs` Show all organizations. Service Subcommands ------------------- This command has a built in process supervisor that ensures all of the required services are in the appropriate state at any given time. The supervisor starts two processes per service and provides the following subcommands for managing services: `hup`, `int`, `kill`, `once`, `restart`, `service-list`, `start`, `status`, `stop`, `tail`, and `term`. Warning The following commands are disabled when an external PostgreSQL database is configured for the Chef Infra Server: `hup`, `int`, `kill`, `once`, `restart`, `start`, `stop`, `tail`, and `term`. ### hup The `hup` subcommand is used to send a `SIGHUP` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl hup SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### int The `int` subcommand is used to send a `SIGINT` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl int SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### kill The `kill` subcommand is used to send a `SIGKILL` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl kill SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### once The supervisor for the Chef Infra Server is configured to restart any service that fails, unless that service has been asked to change its state. The `once` subcommand is used to tell the supervisor to not attempt to restart any service that fails. This command is useful when troubleshooting configuration errors that prevent a service from starting. Run the `once` subcommand followed by the `status` subcommand to look for services in a down state and/or to identify which services are in trouble. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl once SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### restart The `restart` subcommand is used to restart all services enabled on the Chef Infra Server or to restart an individual service by specifying the name of that service in the command. Warning When running the Chef Infra Server in a high availability configuration, restarting all services may trigger failover. This subcommand has the following syntax: ``` chef-server-ctl restart SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully restarted the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` ### service-list The `service-list` subcommand is used to display a list of all available services. A service that is enabled is labeled with an asterisk (*). This subcommand has the following syntax: ``` chef-server-ctl service-list ``` ### start The `start` subcommand is used to start all services that are enabled in the Chef Infra Server. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl start SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully started the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` The supervisor for the Chef Infra Server is configured to wait seven seconds for a service to respond to a command from the supervisor. If you see output that references a timeout, it means that a signal has been sent to the process, but that the process has yet to actually comply. In general, processes that have timed out are not a big concern, unless they are failing to respond to the signals at all. If a process is not responding, use a command like the `kill` subcommand to stop the process, investigate the cause (if required), and then use the `start` subcommand to re-enable it. ### status The `status` subcommand is used to show the status of all services available to the Chef Infra Server. The results will vary based on the configuration of a given server. This subcommand has the following syntax: ``` chef-server-ctl status ``` and will return the status for all services. Status can be returned for individual services by specifying the name of the service as part of the command: ``` chef-server-ctl status SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When service status is requested, the output should be similar to: ``` run: service_name: (pid 12345) 12345s; run: log: (pid 1234) 67890s ``` where * `run:` is the state of the service (`run:` or `down:`) * `service_name:` is the name of the service for which status is returned * `(pid 12345)` is the process identifier * `12345s` is the uptime of the service, in seconds For example: ``` down: opscode-erchef: (pid 35546) 10s ``` By default, runit will restart services automatically when the services fail. Therefore, runit may report the status of a service as `run:` even when there is an issue with that service. When investigating why a particular service is not running as it should be, look for the services with the shortest uptimes. For example, the list below indicates that the **opscode-erchef** should be investigated further: ``` run: oc-id run: opscode-chef: (pid 4327) 13671s; run: log: (pid 4326) 13671s run: opscode-erchef: (pid 5383) 5s; run: log: (pid 4382) 13669s ``` #### Log Files A typical status line for a service that is running any of the Chef Infra Server front-end services is similar to the following: ``` run: name_of_service: (pid 1486) 7819s; run: log: (pid 1485) 7819s ``` where: * `run` describes the state in which the supervisor attempts to keep processes. This state is either `run` or `down`. If a service is in a `down` state, it should be stopped * `name_of_service` is the service name, for example: `opscode-erchef` * `(pid 1486) 7819s;` is the process identifier followed by the amount of time (in seconds) the service has been running * `run: log: (pid 1485) 7819s` is the log process. It is typical for a log process to have a longer run time than a service; this is because the supervisor does not need to restart the log process in order to connect the supervised process If the service is down, the status line will appear similar to the following: ``` down: opscode-erchef: 3s, normally up; run: log: (pid 1485) 8526s ``` where * `down` indicates that the service is in a down state * `3s, normally up;` indicates that the service is normally in a run state and that the supervisor would attempt to restart this service after a reboot ### stop The `stop` subcommand is used to stop all services enabled on the Chef Infra Server. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl stop SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully stopped the output should be similar to: ``` ok: down: service_name: 0s, normally up ``` For example: ``` chef-server-ctl stop ``` will return something similar to: ``` ok: down: nginx: 393s, normally up ok: down: opscode-chef: 391s, normally up ok: down: opscode-erchef: 391s, normally up ok: down: opscode-solr4: 389s, normally up ok: down: postgresql: 388s, normally up ok: down: redis_lb: 387s, normally up ``` ### tail The `tail` subcommand is used to follow all of the Chef Infra Server logs for all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl tail SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### term The `term` subcommand is used to send a `SIGTERM` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl term SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/ctl_chef_server/chef-backend-ctl ================ [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/ctl_chef_backend.md) Warning Chef Backend is [deprecated](../../versions/index#deprecated-products-and-versions) and no longer under active development. Contact your Chef account representative for information about migrating to Chef Automate HA. This document is no longer maintained. The Chef Infra Server backend HA cluster includes a command-line utility named chef-backend-ctl. This command-line tool is used to manage the Chef Infra Server backend HA cluster, start and stop individual services, and tail Chef Infra Server log files. backup ------ Use the `backup` subcommand is to backup the data for a node in the backend HA cluster. This command is typically run against a follower node. Use the `--force` option to run this command against all nodes in the backend HA cluster. The backup is created as a tar.gz file and is located in `/var/opt/chef-backup/`. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl backup (options) ``` ### Options This subcommand has the following options: `--with-external` Use to specify that data on an external PostgreSQL database should be removed. ### Examples **Backup a node in the backend HA cluster** From a follower node, run the following command: ``` chef-backend-ctl backup ``` create-cluster -------------- Use the `create-cluster` subcommand to initialize the cluster state, including the PostgreSQL data store, and then bootstrap the first node in a backend HA cluster or assist in the recovery of the entire backend HA cluster. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl create-cluster (options) ``` ### Options This subcommand has the following options: `--elasticsearch-wait-time` The maximum amount of time (in seconds) to wait for Elasticsearch to start. Default value: `30`. `--etcd-wait-time` The maximum amount of time (in seconds) to wait for etcd to start. Default value: `30`. `--quorum-loss-recovery` Resets the cluster identifier in etcd to this node. If nodes in a backend HA cluster are not available, etcd may not be able to form a cluster. If etcd cannot form a cluster, rebuild the cluster. First reset the cluster identifier on an active node, rebuild the nodes that will be part of the cluster, and then rejoin the rebuilt nodes to the cluster by using the `chef-backend-ctl join-cluster` subcommand. `-y`, `--yes` Do not prompt for confirmation. ### Examples None. cleanse ------- The `cleanse` subcommand is used to re-set a machine in the Chef Infra Server backend HA cluster to the state it was in prior to the first time the `reconfigure` subcommand is run. This command will destroy all data, configuration files, and logs. The software that was put on-disk by the package installation will remain; re-run `chef-backend-ctl reconfigure` to recreate the default data and configuration files. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl cleanse ``` ### Options This subcommand has the following options: `--with-external` Use to specify that data on an external PostgreSQL database should be removed. ### Examples None. cluster-status -------------- Use the `cluster-status` subcommand to return a list of all accessible nodes, their role (leader, follower), and the status for PostgreSQL and Elasticsearch. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl cluster-status (options) ``` ### Options This subcommand has the following options: `--json` Return cluster health information as JSON. ### Examples **Return cluster health data as JSON** ``` chef-backend-ctl cluster-status --json ``` demote ------ Use the `demote` subcommand to demote the current leader in the backend HA cluster, after which a new leader is elected from the group of available followers in the backend HA cluster. This command will: * Complete with an exit code of `0` if the original leader was demoted and a new leader was elected successfully. * Return an error message and a non-zero exit code if leader election is prevented because failover has been disabled (for either the cluster or the node) or if a new leader could not be elected within the allowed time. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl demote ``` ### Examples None. force-leader ------------ Use the `force-leader` subcommand to force the node from which the command is run to become the leader in the backend HA cluster if there is not already an elected leader. This command should only be run if: * The backend cluster appears to not have an elected and available leader * All of the nodes in the backend HA cluster are believed to be in a healthy state; if one (or more) nodes are not healthy, first remove the unhealthy nodes, rebuild, and then rejoin them to the cluster This command will: * Run the `chef-backend-ctl cluster-status` subcommand to determine if a leader exists. Warning Nodes in the backend HA cluster may not be visible to each other when they are located in network partitions. This may prevent a cluster status check from discovering that a leader exists. If nodes exist on network partitions, to prevent this scenario, first run `chef-backend-ctl cluster-status`, and then verify the expected number of nodes in the backend HA cluster as healthy and `waiting_for_leader` before running this command. * Complete with an exit code of `0` if the node from which the command is run becomes the leader. * Return an error message and a non-zero exit code if a leader already exists. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl force-leader ``` ### Examples None. gather-logs ----------- Use the `gather-logs` subcommand to gather the log files for a machine in the Chef Infra Server backend HA cluster into a tarball that contains all of the important log files and system information. This subcommand has the following syntax: ``` chef-backend-ctl gather-logs ``` gen-sample-backend-config ------------------------- Use the `gen-sample-backend-config` subcommand to generate output that contains all of the backend HA cluster settings along with their default values. Use this subcommand to get the values for `publish_address` and `vip_interface` prior to bootstrapping a new node for the backend HA cluster. Warning Service-specific configuration settings—`etcd`, `elasticsearch`, `leaderl`, and `postgresql`—are generated automatically by the backend and should only be tuned under guidance from Chef. Service-specific configuration settings must be identical on all nodes in the backend HA cluster unless directed otherwise. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl gen-sample-backend-config ``` ### Example Output The following example shows the results of running the `chef-backend-ctl gen-sample-backend-config` subcommand. The settings and output will vary, depending on the configuration. The `elasticsearch`, `etcd`, `leaderl`, and `postgresql` settings are generated automatically and should not be modified: ``` fqdn = 'be1' hide_sensitive = true ip_version = 'ipv4' publish_address = '10.0.2.15' vip = '10.0.2.15' vip_interface = 'eth0' etcd.client_port = 2379 etcd.enable = true etcd.log_directory = '/var/log/chef-backend/etcd' etcd.peer_port = 2380 etcd.log_rotation.file_maxbytes = 104857600 etcd.log_rotation.num_to_keep = 10 postgresql.archive_command = '' postgresql.archive_mode = 'off' postgresql.archive_timeout = 0 postgresql.checkpoint_completion_target = 0.5 postgresql.checkpoint_timeout = '5min' postgresql.checkpoint_warning = '30s' postgresql.data_dir = '/var/opt/chef-backend/postgresql/9.5/data' postgresql.db_superuser = 'chef_pgsql' postgresql.effective_cache_size = '496MB' postgresql.enable = true postgresql.hot_standby = 'on' postgresql.keepalives_count = 2 postgresql.keepalives_idle = 60 postgresql.keepalives_interval = 15 postgresql.log_directory = '/var/log/chef-backend/postgresql/9.5' postgresql.log_min_duration_statement = -1 postgresql.max_connections = 350 postgresql.max_replication_slots = 12 postgresql.max_wal_senders = 12 postgresql.max_wal_size = 64 postgresql.md5_auth_cidr_addresses = '["samehost", "samenet"]' postgresql.min_wal_size = 5 postgresql.port = 5432 postgresql.replication_user = 'replicator' postgresql.shared_buffers = '248MB' postgresql.shmall = 4194304 postgresql.shmmax = 17179869184 postgresql.username = 'chef_pgsql' postgresql.wal_keep_segments = 32 postgresql.wal_level = 'hot_standby' postgresql.wal_log_hints = 'on' postgresql.work_mem = '8MB' postgresql.log_rotation.file_maxbytes = 104857600 postgresql.log_rotation.num_to_keep = 10 elasticsearch.data_dir = '/var/opt/chef-backend/elasticsearch/data' elasticsearch.enable = true elasticsearch.heap_size = 248 elasticsearch.java_opts = '' elasticsearch.log_directory = '/var/log/chef-backend/elasticsearch' elasticsearch.new_size = 32 elasticsearch.plugins_directory = '/var/opt/chef-backend/elasticsearch/plugins' elasticsearch.port = 9200 elasticsearch.scripts_directory = '/var/opt/chef-backend/elasticsearch/scripts' elasticsearch.temp_directory = '/var/opt/chef-backend/elasticsearch/' elasticsearch.log_rotation.file_maxbytes = 104857600 elasticsearch.log_rotation.num_to_keep = 10 leaderl.control_worker_timeout_seconds = 30 leaderl.db_timeout = 2000 leaderl.enable = true leaderl.health_check_interval_seconds = 2 leaderl.leader_ttl_seconds = 10 leaderl.log_directory = '/var/log/chef-backend/leaderl' leaderl.status_internal_update_interval_seconds = 5 leaderl.status_post_update_interval_seconds = 10 leaderl.log_rotation.file_maxbytes = 104857600 leaderl.log_rotation.max_messages_per_second = 1000 leaderl.log_rotation.num_to_keep = 10 leaderl.etcd_pool.cull_interval_seconds = 60 leaderl.etcd_pool.http_timeout_ms = 5000 leaderl.etcd_pool.ibrowse_options = '{inactivity_timeout, infinity}' leaderl.etcd_pool.init_count = 10 leaderl.etcd_pool.max_age_seconds = 60 leaderl.etcd_pool.max_connection_duration_seconds = 300 leaderl.etcd_pool.max_count = 10 ssl.certificate = nil ssl.certificate_key = nil ssl.ciphers = (a list of ciphers, not shown) ssl.company_name = 'YouCorp' ssl.country_name = 'US' ssl.data_dir = '/var/opt/chef-backend/ssl/' ssl.duration = 3650 ssl.key_length = 2048 ssl.organizational_unit_name = 'Operations' ``` gen-server-config ----------------- Use the `gen-server-config` subcommand to generate output for the `/etc/opscode/chef-server.rb` configuration file. This command may be run from any machine in the backend HA cluster, but must be run separately for each node that is part of the frontend group. This command will: * Complete with an exit code of `0` if the `chef-server.rb` file is created successfully. * Return an error message and a non-zero exit code if a node has not been bootstrapped or joined or if a FQDN is not provided. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl gen-server-config FQDN ``` ### Configure the Front End 1. On any node in the backend HA cluster, run the following command for each node in the frontend group: ``` chef-backend-ctl gen-server-config FQDN -f chef-server.rb.fqdn ``` where `FQDN` is the FQDN for the frontend machine. The generated `chef-server.rb` file will contain all of the values necessary for any frontend Chef Infra Server to connect to and bootstrap against the backend HA cluster. 2. On each frontend machine, install the `chef-server-core` package (version 12.4.0 or higher). 3. On each frontend machine, copy the generated `chef-server.rb`.fqdn to `/etc/opscode/chef-server.rb`. 4. On each frontend machine, with root permission, run the following command: ``` chef-server-ctl reconfigure ``` ### Example Output The following example shows the results of running the `chef-backend-ctl gen-server-config` subcommand. The settings and output will vary, depending on the configuration. These settings should be modified carefully: ``` fqdn "frontend1.chef-demo.com" postgresql['external'] = true postgresql['vip'] = '192.0.2.0' postgresql['db_superuser'] = 'chef_pgsql' postgresql['db_superuser_password'] = '...6810e52a01e562' opscode_solr4['external'] = true opscode_solr4['external_url'] = 'http://192.0.2.0:9200' opscode_erchef['search_provider'] = 'elasticsearch' opscode_erchef['search_queue_mode'] = 'batch' bookshelf['storage_type'] = :sql rabbitmq['enable'] = false rabbitmq['management_enabled'] = false rabbitmq['queue_length_monitor_enabled'] = false opscode_expander['enable'] = false dark_launch['actions'] = false opscode_erchef['nginx_bookshelf_caching'] = :on opscode_erchef['s3_url_expiry_window_size'] = '50%' ``` Note The `opscode_solr4`, `postgresql`, and `rabbitmq` services are disabled in this configuration file for the frontend machines when running the Chef Infra Server with a backend HA cluster. help ---- Use the `help` subcommand to print a list of all available chef-backend-ctl commands. This subcommand has the following syntax: ``` chef-backend-ctl help ``` join-cluster ------------ Use the `join-cluster` subcommand to configure a node to be a member of the backend HA cluster as a peer of the node at the specified `PEER_NODE_IP` IP address. This command will query the existing cluster to identify any necessary configuration information. If the `--publish-address` and `--vip-interface` options are not specified, and are specified in `chef-backend.rb`, the command will prompt with a list of items from which to choose. This command will return an error message and a non-zero exit code when: * The `--secrets-file-path` option is specified, a non-empty secrets file already exists at `/etc/chef-backend/secrets.json`, and the user declines to overwrite it. * The `--secrets-file-path` option is specified, but does not specify a valid file and/or the file at `/etc/chef-backend/secrets.json` is empty or does not exist. * The IP address specified by the `--publish-address` option does not exist on the node. * The interface specified by the `--vip-interface` option does not exist on the node. * Any IP address on the node is already registered in the backend HA cluster. * The node is already configured for the backend HA cluster and the `--recovery` option is not specified. * The `--recovery` option is specified, but no existing installation is found. * `--publish-address` and/or `--vip-interface` are specified, but a non-empty `chef-backend.rb` file already exists. (This command will not overwrite a `chef-backend.rb` file.) If successful, this command will generate a `chef-backend.rb` file at `/etc/chef-backend/chef-backend.rb` with the values for the `publish_address`, `vip_interface`, and `vip` added automatically. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl join-cluster PEER_NODE_IP (options) ``` where `PEER_NODE_IP` is the IP address of a peer in the cluster to be joined. ### Options This subcommand has the following options: `-i INTERFACE`, `--vip-interface INTERFACE` The network interface to which the backend VIP will bind in the event that this node becomes leader. If not provided, and if not specified in `chef-backend.rb`, this command will prompt to choose from a list of interfaces that are currently available on the node. Note This option should only be used the first time a node joins the backend HA cluster. `-p IP_ADDRESS`, `--publish-address IP_ADDRESS` The IP address that is published within the backend HA cluster. This IP address must be accessible to all nodes in the backend HA cluster. If not provided, and if not specified in `chef-backend.rb`, this command will prompt to choose from a list of IP addresses that are currently bound on the node. Note This option should only be used the first time a node joins the backend HA cluster. `--recovery` Force this node to rejoin the backend HA cluster if it has been removed via the `chef-backend-ctl remove-node` or `chef-backend-ctl bootstrap --with-quorum-recovery` commands. Note This option will run against the existing `chef-backend.rb` file, which means the `--vip-interface` and `--publish-address` options should not be specified. (They are already defined in the `chef-backend.rb` file.) `-s PATH`, `--secrets-file-path PATH` The ABSOLUTE path to the location of the `secrets.json` file on the bootstrapping node. The path should begin with a “/”. Default value: `/etc/chef-backend/secrets.json`. `-y`, `--yes` Do not prompt for confirmation. ### Examples None. promote ------- Use the `promote` subcommand to promote the named node to be leader of the backend HA cluster. This command will: * Complete with an exit code of `0` when the leader of the backend HA cluster is replaced as leader by the named node. * Return an error message and a non-zero exit code if the named node is already leader because failover has been disabled (for either the cluster or the node) or if the new leader could not be promoted within the allowed time. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl promote NODE ``` ### Examples None. reconfigure ----------- Use the `reconfigure` subcommand to reconfigure a machine in the Chef Infra Server backend HA cluster. This subcommand will also restart any services for which the `service_name['enabled']` setting is set to `true`. This subcommand has the following syntax: ``` chef-backend-ctl reconfigure ``` remove-node ----------- Use the `remove-node` subcommand to remove the named node from the backend HA cluster by removing the node’s status from etcd and deleting it from the etcd cluster. This command is useful when a node is going to be replaced or if the `join-cluster` command was unsuccessful. This command may not be run from the node that is to be removed; the node itself must be shut down physically or have all services stopped (via the the `chef-backend-ctl stop` command). If the node is still running or otherwise available to the backend HA cluster, this command will return an error message and a non-zero exist code. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl remove-node NODE_NAME ``` ### Options This subcommand has the following options: `-y`, `--yes` Do not prompt for confirmation. ### Examples None. restore ------- Use the `restore` subcommand to restore a backup created by the `chef-backend-ctl backup` subcommand. This command should be executed on the leader node in the backend HA cluster. This command will delete all existing data and replace it with the data in the backup archive. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl restore PATH (options) ``` where `PATH` is the path to a tar.gz file that was created by the `chef-backend-ctl backup` subcommand. ### Options This subcommand has the following options: `-d DIRECTORY`, `--staging-dir DIRECTORY` The path to an empty directory to be used during the restore operation. This directory must have enough available space to expand all data in the backup archive. `-y`, `--yes` Do not prompt for confirmation. ### Examples **Restore data to the backend leader** From the leader node, run the following command: ``` chef-backend-ctl restore /var/opt/chef-backup/backup_file.tgz ``` set-cluster-failover -------------------- Use the `set-cluster-failover` subcommand to enable or disable failover across the backend HA cluster. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl set-cluster-failover STATE ``` where `STATE` may be one of `on`, `off`, `true`, `false`, `enabled`, or `disabled`. set-node-failover ----------------- Use the `set-node-failover` subcommand to enable or disable failover for a node in the backend HA cluster. ### Syntax This subcommand has the following syntax: ``` chef-backend-ctl set-node-failover STATE ``` where `STATE` may be one of `on`, `off`, `true`, `false`, `enabled`, or `disabled`. show-config ----------- The `show-config` subcommand is used to view the configuration that will be generated by the `reconfigure` subcommand. This command is most useful in the early stages of a deployment to ensure that everything is built properly prior to installation. This subcommand has the following syntax: ``` chef-backend-ctl show-config ``` status ------ Use the `status` subcommand to show the status of all services available to a node in the backend HA cluster. This subcommand has the following syntax: ``` chef-backend-ctl status ``` and will return the status for all services. Status can be returned for individual services by specifying the name of the service as part of the command: ``` chef-backend-ctl status SERVICE_NAME ``` For example, full output: ``` chef-backend-ctl status ``` is similar to: ``` Service Local Status Time in State Distributed Node Status elasticsearch running (pid 6661) 1d 5h 59m 41s state: green; nodes online: 3/3 etcd running (pid 6742) 1d 5h 59m 39s health: green; healthy nodes: 3/3 leaderl running (pid 6788) 1d 5h 59m 35s leader: 1; waiting: 0; follower: 2; total: 3 postgresql running (pid 6640) 1d 5h 59m 43s leader: 1; offline: 0; syncing: 0; synced: 2 ``` which shows status for a healthy backend HA cluster. The first three columns–`Service`, `Local Status`, and `Time in State` summarize the local state. The `Distributed Node Status` column shows: * A three node cluster * All nodes healthy and online * A leader selected with two followers (for both leader/follower status for the `leaderl` service and a leader/synced state for the `postgresql` service) Simple output: ``` chef-backend-ctl status --simple ``` is similar to: ``` run: elasticsearch: (pid 6661) 106983s; run: log: (pid 6667) 106983s run: etcd: (pid 6742) 106981s; run: log: (pid 6630) 106984s run: leaderl: (pid 6788) 106976s; run: log: (pid 6739) 106982s run: postgresql: (pid 6640) 106984s; run: log: (pid 6653) 106983s ``` which shows the state of the services, process identifiers, and uptime (in seconds). Simple output is useful if one (or more) nodes in the backend HA cluster are down or in a degraded state. uninstall --------- The `uninstall` subcommand is used to remove the Chef Infra Server application from a machine in the backend HA cluster, but without removing any of the data. This subcommand will shut down all services (including the `runit` process supervisor). This subcommand has the following syntax: ``` chef-backend-ctl uninstall ``` Note To revert the `uninstall` subcommand, run the `reconfigure` subcommand (because the `start` subcommand is disabled by the `uninstall` command). Service Subcommands ------------------- This command has a built in process supervisor that ensures all of the required services are in the appropriate state at any given time. The supervisor starts two processes per service and provides the following subcommands for managing services: `hup`, `int`, `kill`, `once`, `restart`, `service-list`, `start`, `status`, `stop`, `tail`, and `term`. Warning The following commands are disabled when an external PostgreSQL database is configured for the Chef Infra Server: `hup`, `int`, `kill`, `once`, `restart`, `service-list`, `start`, `stop`, `tail`, and `term`. ### hup Use the `hup` subcommand to send a `SIGHUP` to all services on a machine in the Chef Infra Server backend HA cluster. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-backend-ctl hup SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### int Use the `int` subcommand to send a `SIGINT` to all services on a machine in the Chef Infra Server backend HA cluster. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-backend-ctl int SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### kill Use the `kill` subcommand to send a `SIGKILL` to all services on a machine in the Chef Infra Server backend HA cluster. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-backend-ctl kill SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### once The supervisor for a machine in the Chef Infra Server backend HA cluster is configured to restart any service that fails, unless that service has been asked to change its state. The `once` subcommand is used to tell the supervisor to not attempt to restart any service that fails. This command is useful when troubleshooting configuration errors that prevent a service from starting. Run the `once` subcommand followed by the `status` subcommand to look for services in a down state and/or to identify which services are in trouble. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-backend-ctl once SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### restart Use the `restart` subcommand to restart all services enabled on a machine in the Chef Infra Server backend HA cluster, or to restart an individual service by specifying the name of that service in the command. Warning When running the Chef Infra Server in a high availability configuration, restarting all services may trigger failover. This subcommand has the following syntax: ``` chef-backend-ctl restart SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully restarted the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` ### service-list Use the `service-list` subcommand to display a list of all available services on a machine in the Chef Infra Server backend HA cluster. A service that is enabled is labeled with an asterisk (*). This subcommand has the following syntax: ``` chef-backend-ctl service-list ``` ### start Use the `start` subcommand to start all services that are enabled on a machine in the Chef Infra Server backend HA cluster. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-backend-ctl start SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully started the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` The supervisor for a machine in the Chef Infra Server backend HA cluster is configured to wait seven seconds for a service to respond to a command from the supervisor. If you see output that references a timeout, it means that a signal has been sent to the process, but that the process has yet to actually comply. In general, processes that have timed out are not a big concern, unless they are failing to respond to the signals at all. If a process is not responding, use a command like the `kill` subcommand to stop the process, investigate the cause (if required), and then use the `start` subcommand to re-enable it. ### stop Use the `stop` subcommand to stop all services enabled on the Chef Infra Server backend HA cluster. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-backend-ctl stop SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully stopped the output should be similar to: ``` ok: diwb: service_name: 0s, normally up ``` For example: ``` chef-backend-ctl stop ``` will return something similar to: ``` ok: down: etcd: 393s, normally up ok: down: postgresql: 388s, normally up ``` ### tail Use the `tail` subcommand to follow all of the logs for all services on a machine in the Chef Infra Server backend HA cluster. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-backend-ctl tail SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### term Use the `term` subcommand to send a `SIGTERM` to all services on a machine in the Chef Infra Server backend HA cluster. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-backend-ctl term SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/ctl_chef_backend/Chef InSpec and Friends ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/inspec_and_friends.md) This page looks at projects that are similar to Chef InSpec to explain how they relate to each other. RSpec ----- RSpec is an awesome framework that is widely used by software engineers to test Ruby code. It enables test-driven development (TDD) and helps developers to write better code every day. Chef InSpec is built on top of RSpec and uses it as the underlying foundation to execute tests. It uses the key strengths of RSpec, easily execute tests and a DSL to write tests, but extends the functionality for use as compliance audits. Chef InSpec ships with custom audit resources that make it easy to write audit checks and with the ability to run those checks on remote servers. These audit resources provided know the differences between operating systems and help you abstract from the local operating system, similar to other resources you might use in your Chef recipes. A complete Chef InSpec rule looks like: ``` control "sshd-11" do impact 1.0 title "Server: Set protocol version to SSHv2" desc "Set the SSH protocol version to 2. Don't use legacy insecure SSHv1 connections anymore." tag security: "level-1" tag "openssh-server" ref "Server Security Guide v.1.0", url: "http://..." describe sshd_config do its('Protocol') { should eq('2') } end end ``` That said, Chef InSpec is not RSpec. Some key differences: * In InSpec, `describe` blocks should not be nested; instead use `control` blocks to describe a higher-level grouping of tests. * The RSpec `shared_example` construct is not supported. Instead, create a simple custom resource that executes repetitious tasks. * Chef InSpec is aimed at compliance practitioners and infrastructure testers, so our focus is providing a few, well-supported, easy-to-use [universal matchers](../matchers/index), such as `cmp`. In contrast, RSpec is a tool designed for software engineers. It thus supports a very large range of matchers, to enable testing of software engineering constructs such as exceptions, Object Oriented Programming relationships, and so on. * While Chef InSpec uses parts of the RSpec project and codebase, it is a separate project from InSpec. Rspec’s release schedule and feature set are beyond the control of the Chef InSpec team. While it is possible to use many of the RSpec core features within Chef InSpec profiles, Chef InSpec can only guarantee that the features described in the [InSpec documentation](../index) will function correctly. Some RSpec core functionality may be removed in future versions of Chef InSpec as needed to ensure stability in the Chef InSpec project. Serverspec ---------- Serverspec is the first extension of RSpec that enabled users to run RSpec tests on servers to verify deployed artifacts. It was created in March 2013 by <NAME> and has been widely adopted. It is also one of the core test frameworks within test-kitchen and has been widely used within the Chef ecosystem. Chef InSpec takes lessons learned implementing and using Serverspec and builds on them to make auditing and compliance easier. Lessons learned from Serverspec include: * IT, compliance, and security professional require metadata beyond what Serverspec offers, such as criticality, to fully describe controls. * Setting up and running the same tests across multiple machines must be easy. * It must be easy to locate, debug, and extend operating system-dependent code. * It must be easy to extend the language and create custom resources. * It must run multiple tests simultaneously. * Support for Windows is a first-class requirement. * A command line interface (CLI) is required for faster iteration of test code. You can also watch this [podcast](http://foodfightshow.org/2016/02/inspec.html) to find out more on the relationship between Chef InSpec and Serverspec. ### How is Chef InSpec different from Serverspec One of the key differences is that Chef InSpec targets more user groups. It is optimized for DevOps, Security, and Compliance professionals. Additional metadata, such as impact, title, and description, make it easier to fully describe the controls which makes it easier to share the controls with other departments. This enables Security departments to prioritize rules. DevOps teams use this information to focus on the most critical issues to remediate. ``` control "sshd-11" do impact 1.0 title "Server: Set protocol version to SSHv2" desc "Set the SSH protocol version to 2. Don't use legacy insecure SSHv1 connections anymore." tag security: "level-1" tag "openssh-server" ref "Server Security Guide v.1.0" url: "http://..." describe sshd_config do its('Protocol') { should cmp 2 } end end ``` **Why not fork Serverspec?** Chef InSpec started as an extension of Serverspec. As the extension grew, it became clear that a new library was required. Creating and maintaining a fork was not practical so a new project was born. **Will Chef InSpec only work on machines managed by Chef?** No, Chef InSpec can be used on any machine. It does not matter if that machine was configured by Chef Infra or configured lovingly by the hands of your local System Administrator. **Is Chef InSpec a replacement of Serverspec?** Chef InSpec is intended to be a drop-in replacement of Serverspec. Popular Serverspec resources have been ported to InSpec. It changed some behavior as documented in our migration guide. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/inspec_and_friends/Chef InSpec Troubleshooting =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/troubleshooting.md) Undefined Local Variable or Method Error for Cloud Resource ----------------------------------------------------------- This error is a result of invoking a resource from one of the cloud resource packs without initializing an InSpec profile with that resource pack (AWS, Azure, or GCP) as a dependency. InSpec profiles that use **any cloud resource** must have the resource pack defined as a dependency. See the relevant resource pack readme for instructions: * [inspec-aws README](https://github.com/inspec/inspec-aws#use-the-resources) * [inspec-azure README](https://github.com/inspec/inspec-azure#use-the-resources) * [inspec-gcp README](https://github.com/inspec/inspec-gcp#use-the-resources) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/troubleshooting/Chef InSpec Glossary ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/glossary.md) This document should help you become familiar with some of the terminology used by the Chef InSpec project. There are two ways to use it: * A [text glossary](#text-glossary). Learn the meaning of a word you have encountered. * A [visual glossary](#visual-glossary). Look at examples and see how the parts are labelled. You can then use the text glossary to read details of each concept. Visual Glossary --------------- ### Motivating Example Suppose we are interested in auditing cars. Let’s suppose we have two Chef InSpec resources for auditing: `cars`, which searches for and filters groups of cars, and `car`, which performs detailed auditing of a single car. ### Basic Syntax Let’s look at some simple examples. ### Singular Resource Example ``` describe car(owner: '<NAME>') do it { should exist } its('license_plate') { should cmp 'MOONMAN' } it { should be_classy } it { should_not have_check_engine_light_on } end ``` #### describe car(owner: ‘<NAME>’) do *car* is a [resource](#resource). Since we are talking about only one car, it is a [singular resource](#singular-resource). #### describe car(*owner: ‘<NAME>’*) *owner* is a [resource parameter](#resource-parameter) and *‘<NAME>’* is a resource parameter value. #### *it { should exist }* Each line within the resource block beginning with `it` or `its` is a [test](#test). Use [it](#it) to access [resource-specific matchers](#resource-specific-matcher), and use [its](#its) to access [properties](#property) of the [resource](#resource), which are in turn used with [universal matchers](#universal-matcher). #### its('*license_plate*') { should cmp ‘MOONMAN’ } *license_plate* is a [property](#property) belonging to the [resource](#resource). Properties expose testable information about the resource. Some properties are numbers, some (like this one) are text, some are lists, and some are more complex objects. Properties are always used with [universal matchers](#universal-matcher). #### its(‘license_plate’) { should *cmp* ‘MOONMAN’ } *cmp* is a [universal matcher](#universal-matcher). `cmp` is a very flexible, loosely typed equality operator; here it checks to see if the license plate text is the same as the text ‘MOONMAN’. Notice that the test operates on the license plate text (the property value) and not on the resource. You can find the full list of supported universal matchers on the [Universal Matcher page](../matchers/index). #### its(‘license_plate’) { should cmp *‘MOONMAN’* } *‘MOONMAN’* is an [expected result](#expected-result). Some matchers take an expected result; others do not. #### it { should *be_classy* } *be_classy* is a [resource-specific matcher](#resource-specific-matcher). It returns a yes-or-no value, based on whether Tony’s car is classy or not. (It is. Tony is a classy guy.) #### it { *should_not* have_check_engine_light_on } *should_not* indicates this is a negated test. So, this test passes if the matcher says “no”. ### Plural Resource Example ``` describe cars.where(color: /^b/) do it { should exist } its('manufacturers') { should include 'Cadillac' } its('count') { should be >= 10 } end ``` #### describe *cars*.where(color: /^b/) do *cars* is a [resource](#resource). Since we are potentially talking about many cars, it is a [plural resource](#plural-resource). #### describe cars.*where(color: /^b/)* do *where(color: /^b/)* is a [filter statement](#filter-statement). Without a filter statement, `cars` simply selects all the cars in the world. #### describe cars.where(*color: /^b/*) do *color* is a [filter criterion](#filter-criteria) along with its filter value, */^b/*. Here, the criterion expresses that we want to select all cars whose colors begin with the letter ‘b’ - blue, brown, burgundy, etc. #### *it { should exist }* Each line within the resource block beginning with `it` or `its` is a [test](#test). Use [it](#it) to access [resource-specific matchers](#resource-specific-matcher), and use [its](#its) to access [properties](#property) of the [resource](#resource), which are in turn used with [universal matchers](#universal-matcher). With plural resources, `exist` has a special meaning: did the filter match anything? #### its('*manufacturers*') { should include ‘Cadillac’ } *manufacturers* is a [property](#property) of the [resource](#resource). Properties expose testable information about the resource. On plural resources, properties are almost always names in the plural, and almost always return a list of values. Here, the test returns a list of the car manufacturer names. Some list properties are de-duplicated; for example, you might have 10 cars, but if they are all Subarus and Cadillacs, it returns only two entries in the `manufacturers` property. Be sure to check the documentation for your resource. #### its(‘manufacturers’) { should *include* ‘Cadillac’ } *include* is a [universal matcher](#universal-matcher). `include` works with lists, and checks to see if an expected result is present. Here, it checks to see if the list of manufacturers contains an entry with the text ‘Cadillac’. Notice it operates on the manufacturers list (the property value) and not on the resource. You can find the full list of supported universal matchers on the [Universal Matcher page](../matchers/index). #### its(‘manufacturers’) { should include ‘*Cadillac*’ } *‘Cadillac’* is an [expected result](#expected-result). Some matchers take an expected result; others do not. #### its(‘count’) { should *be >=* 10 } *be >=* is an [operator matcher](#operator-matcher). It allows you to perform numeric comparisons. All plural resources have a `count` property. Text Glossary ------------- ### Attribute Deprecated name for [input](#input). ### Control ### Control Block The *`control`* keyword is used to declare a *`control block`*. Here, the word ‘control’ means a ‘regulatory control, recommendation, or requirement’ - not a software engineering construct. A `control block` has a name (which usually refers to the assigned ID of the regulatory recommendation it implements), metadata such as descriptions, references, and tags, and finally groups together related [describe blocks](#describe-block) to implement the checks. ### Core Resource A [resource](#resource) that is included with InSpec; you are not required to install additional [plugins](#plugin) or depend on a [resource pack](#resource-pack) to use the resource. ### Custom Resource A [resource](#resource) that is *not* included with InSpec. It may be a resource of your own creation, or one you obtain by depending on a [resource pack](#resource-pack). ### Describe ### Describe Block The *`describe`* keyword is used with a *`describe block`* to refer to a Chef InSpec resource. You use the `describe` keyword along with the name of a [resource](#resource) to enclose related [tests](#test) that apply to the resource. Multiple describe blocks are usually grouped together in a [control](#control), but you can also use them outside of a control. ``` control 'Rule 1.1 - Color restrictions' do # Count only blue cars describe cars.where(color: 'blue') do its('count') { should eq 20 } end end ``` ### DSL *DSL* is an acronym for *Domain Specific Language*. It refers to the language extensions Chef InSpec provides to make authoring resources and controls easier. While Chef InSpec control files are use Ruby, the *Control DSL* makes it easy to write controls without knowledge of Ruby by providing DSL keywords such as [describe](#describe), [control](#control), [it](#it) and [its](#its). See the [Chef InSpec Language page](../dsl_inspec/index) for details about keywords available to control authors. For [custom resource](#custom-resource) authors, an additional DSL is available - see the [Resource Language page](../dsl_resource/index). ### Expected Result When using a [matcher](#matcher), the *`expected result`* is the value the matcher will compare against the [property](#property) being accessed. In this example, the [`cmp`](../matchers/index#cmp) matcher is being used to compare the `color` property to the expected result ‘black’. ``` describe car(owner: '<NAME>') do its('color') { should cmp 'black' } end ``` ### Filter Statement When using a [plural resource](#plural-resource), a *`filter statement`* is used to select individual test subjects using [filter criteria](#filter-criteria). A filter statement almost always is indicated by the keyword `where`, and may be repeated using method chaining. A filter statement may use method call syntax (which allows basic criteria operations, such as equality, regex matching, and ruby `===` comparison) or block syntax (which allows arbitrary code). In this example, `where(...)` is the filter statement. ``` # Count only blue cars describe cars.where(color: 'blue') do its('count') { should eq 20 } end ``` ### Filter Criterion ### Filter Criteria When using a [plural resource](#plural-resource), a *`filter criterion`* is used to select individual test subjects within a [filter statement](#filter-statement). You may use multiple *`filter criteria`* in a single filter statement. When method-call syntax is used with the filter statement, you provide filter criteria as a Hash, with filter criteria names as keys, and conditions as the Hash values. You may provide test, true/false, or numbers, in which case the comparison is equality; or you may provide a regular expression, in which case a match is performed. Here, `(color: blue)` is a single filter criterion being used with a filter statement in method-call syntax. ``` # Count only blue cars describe cars.where(color: 'blue') do its('count') { should eq 20 } end ``` When block-method syntax is used with the filter statement, you provide a block. The block may contain arbitrary code, and each filter criteria will be available as an accessor. The block will be evaluated once per row, and each block that evaluates to a truthy value will pass the filter. Here, `{ engine_cylinders >= 6 }` is a block-syntax filter statement referring to one filter criterion. ``` # Vroom! describe cars.where { engine_cylinders >= 6 } do its('city_mpg_ratings') { should_not include '4-star' } end ``` ### Input An *`input`* is a value that Chef InSpec can source from a number of providers, including from the command line, profile metadata, or within the control file DSL itself. You can use this feature either to change a [profile’s](#profile) behavior by passing different attribute files or to store secrets that should not be directly present in a profile. Inputs were formerly known as `attributes`. Chef InSpec inputs are unrelated to Chef Infra attributes. The CLI syntax for inputs is documented under the [`inspec exec`](../cli/index#exec) command. Inputs are documented in detail in the [input documentation](../inputs/index). ### It Within a [describe block](#describe), *`it`* declares an individual [test](#test) directly against the [resource](#resource) (as opposed to testing against one of the resource’s [properties](#property), as [its](#its) does). Though it is possible to use [universal matchers](#universal-matcher) with `it`, it is much more typical to use [resource-specific matchers](#resource-specific-matchers). `it` may be used with `should`, or negated using `should_not`. Here, `it { should ... }` declares a test, calling the `classy?` matcher on <NAME>’s car. ``` describe car(owner: '<NAME>') do it { should be_classy } end ``` ### Its Within a [describe block](#describe), *`its`* declares an individual [test](#test) against a property of the [resource](#resource) (as opposed to testing directly against the resource itself, as [it](#it) does). You must use [universal matchers](#universal-matcher) with `its`; you cannot use [resource-specific matchers](#resource-specific-matchers). `its` may be used with `should`, or negated using `should_not`. The property to access is passed as a single string argument to `its`. As an advanced usage, if the property has methods you are interested in, you can call them using ‘`.`’ within the string; even more advanced calling patterns are possible - see [the rspec-its documentation](https://github.com/rspec/rspec-its#usage). Here, `its('fuzzy_dice') { should ... }` declares a test, testing against the `fuzzy_dice` property of <NAME>’s car. Let’s assume - Tony being Tony - that `fuzzy_dice` will return an Array. ``` describe car(owner: '<NAME>') do its('fuzzy_dice') { should_not be_empty } its('fuzzy_dice.count') { should be >= 2 } its('fuzzy_dice.first.fuzziness') { should cmp 'outlandishly so' } end ``` ### Matcher A *`matcher`* performs the actual assertions against [resources](#resource) or the [properties](#property) of resources. Matchers always return a true/false value. Matchers fall into two camps: * [resource-specific matchers](#resource-specific-matchers), which operate directly on the resource, are used with [it](#it), and tend to be highly customized to the auditing needs of the resource * [universal matchers](#universal-matchers), which operate on the properties of the resource, are used with [its](#its), and tend to be very generic, operating on text, numbers, and lists Some matchers accept parameters, called [expected results](#expected-results). For information on how RSpec matchers are related o Chef InSpec matchers, see [Chef InSpec and RSpec](../inspec_and_friends/index#rspec). Here, `be_classy` is a resource-specific matcher operating directly on the `car`, while `cmp` is a universal matcher operating on the `manufacturer` property. ``` describe car(owner: '<NAME>') do it { should be_classy } its('manufacturer') { should cmp 'Cadillac' } end ``` ### Operator Matcher An operator matcher allows you to use operators to compare numerical [expected results](#expected-result) against a [property](#property). All plural resources have a `count` property. For example: ``` describe cars do its('count') { should be >= 10 } end ``` Operators include: * `==` * `>=` * `<=` * `>` * `<` ### plural resource A *`plural resource`* is a [resource](#resource) that specializes in performing searches and represents multiple occurrences of the resource on the [target](#target) platform. Plural resources are used to audit counts, inspect group properties, and have the unique ability to enforce negative tests (“nothing like this should exist”) often required by compliance standards. Plural resources are not intended to perform in-depth auditing of an individual; use [singular resources](#singular-resource) for that. Plural resources nearly always have a name that ends in ’s': `processes`, `aws_security_groups`, `cars`. Plural resources generally do not have [resource-specific matchers](#resource-specific-matcher). If they have properties, they are almost always list properties, meaning that they return a list of values, which may or may not be de-duplicated. Plural resources support [filter statements](#filter-statement). See the [resource documentation](../resources/index) for details regarding which [filter criteria](#filter-criteria) are supported on each resource. Here, `cars` is a plural resource. ``` describe cars.where(color: 'blue') do its('count') { should eq 20 } its('license_plates') { should include 'AUTOAZUL' } # License plates are unique, should have 20 its('license_plates.count') { should cmp 20 } # Manufacturers are de-duplicated its('manufacturers') { should include 'Subaru' } its('manufacturers.count') { should be < 10 } end ``` ### Profile A *`profile`* is a set of related [controls](#control) in a distributable form. You might have a locally-developed profile that your organization uses to define baseline security on all machines, or you might use a pre-defined profile that implements the requirements of a specific compliance standard. For full details about the capabilities of a profile, see the [profile documentation](../profiles/index). Profiles may be distributed locally as a directory tree, as a tarball or zipfile at a URL, as a git repo, and several other ways. Profiles contain metadata, including versioning, and can setup dependency relationships with other profiles. Aside from controls, profiles can also contain [custom resources](#custom-resource). If the profile contains only custom resources and no controls, we call it a [resource pack](#resource-pack). ### Property A fact about a [resource](#resource). Typically, you use the [its](#its) keyword to access the property and write a [test](#test) within a [describe block](#describe-block), and then use a [universal matcher](#universal-matcher) to make assertions about the value of the property. Each resource has different properties. See the [resource documentation](../resources/index) for details. Here, `manufacturer` is a property of the `car` resource. ``` describe car(owner: '<NAME>') do its('manufacturer') { should cmp 'Cadillac' } end ``` ### Reporter An output format for the `inspec exec` command line. Several reporters are available, including JSON and JUnit; see the [inspec exec documentation](../cli/index#exec). ### Resource A *`resource`* represents a category of things on the [target](#target) you wish to examine. For example, to check for the existence and permissions of a file, you would use the [`file`](../resources/file/index) resource. Chef InSpec offers dozens of different resources, from the highly specialized (such as `aws_security_group`, which examines firewall rules in AWS) to the very general (such as `command`, which runs a command and lets you examine its output). Resources are generally categorized as either [singular](#singular-resource) or [plural](#plural-resource), though there are some irregular resources that cannot be cleanly considered one or the other. Resources are used within a [describe block](#describe-block) to perform [tests](#test). Here, `car` is a resource. ``` describe car(owner: '<NAME>') do it { should be_classy } end ``` ### Resource Pack A *resource pack* is a type of [profile](#profile) that is used to distribute [custom resources](#custom-resource). This specialized type of profile contains no [controls](#control), but it does contain a `libraries` directory within which Ruby files define custom resources. ### Resource Parameter *`resource parameters`* are information passed to the resource when they are declared. Typically, resource parameters provide identifying information or connectivity information. Resource parameters are not the same as a [filter statement](#filter-statement). Resource parameters vary from resource to resource; refer to the [resource documentation](../resources/index) for details. Here, `owner: '<NAME>'` is a resource parameter. ``` describe car(owner: '<NAME>') do it { should be_classy } end ``` ### Resource-Specific Matcher A [matcher](#matcher) that operates directly on the [resource](#resource), as opposed to operating on a property as a [universal matcher](#universal-matcher) does. Resource-specific matchers often provide highly customized behavior. Check the [resource documentation](#/inspec/resources/) to discover which resource-specific matchers are available for your resource. For example, the hypothetical `car` resource defines a `classy?` method, which is exposed as the `be_classy` matcher in Chef InSpec tests. ``` describe car(owner: '<NAME>') do it { should be_classy } end ``` ### Singular Resource A [resource](#resource) intended to uniquely identify a single object on the [target](#target). Singular resources specialize in providing richer auditing capabilities via resource-specific matchers. Compare to [plural resources](#plural-resource). ### Target The *`target`* is the OS or API on which Chef InSpec is performing audits. In Chef InSpec 1.x, this was always an operating system target (a bare metal machine, VM, or container). In Chef InSpec 2.x and later, this can be an OS target, or an API target, including cloud providers such as AWS. Chef InSpec is agentless, meaning that the Chef InSpec code and profiles remain on your workstation, and the target is remotely interrogated without installing anything. ### Test A *`test`* is an individual assertion about the state of the [resource](#resource) or one of its [properties](#property). All tests begin with the keyword [it](#it) or [its](#its). Tests are grouped within a [describe block](#describe-block). ### Universal Matcher A *universal matcher* is a [matcher](#matcher) that can be used on the [properties](#property) of any type of [resource](#resource). For example, you can use the `cmp` matcher to check the value of properties without having to worry about Ruby type-casting. Universal matchers are almost always used with the [its](#its) keyword. Universal matchers are documented on the [Universal Matchers](../matchers/index) page. Here, we access the ‘color’ property, then use the `cmp` universal matcher to compare the property to the ‘black’ [expected result](#expected-result). ``` describe car(owner: '<NAME>') do its('color') { should cmp 'black' } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/glossary/Using Chef InSpec on Cloud Platforms ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/platforms.md) As of Chef InSpec 2.0, we have expanded our platform support beyond individual machines and now include support for select AWS and Azure resources. Using InSpec, you can use several Chef InSpec resources to audit properties of your cloud infrastructure - for example, an Amazon Web Services S3 bucket. AWS Platform Support in InSpec ------------------------------ ### Setting up AWS credentials for InSpec Chef InSpec uses the standard AWS authentication mechanisms. Typically, you will create an IAM user specifically for auditing activities. 1. Create an IAM user in the AWS console, with your choice of username. Check the box marked “Programmatic Access.” 2. On the Permissions screen, choose Direct Attach. Select the AWS-managed IAM Profile named “ReadOnlyAccess.” If you wish to restrict the user further, you may do so; see individual Chef InSpec resources to identify which permissions are required. 3. After generating the key, record the Access Key ID and Secret Key. #### Using Environment Variables to provide credentials You may provide the credentials to Chef InSpec by setting the following environment variables: `AWS_REGION`, `AWS_ACCESS_KEY_ID`, and `AWS_SECRET_ACCESS_KEY`. You may also use `AWS_PROFILE`, or if you are using MFA, `AWS_SESSION_TOKEN`. See the [AWS Command Line Interface Docs](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html) for details. Once you have your environment variables set, you can verify your credentials by running: ``` $ inspec detect -t aws:// == Platform Details Name: aws Families: cloud, api Release: aws-sdk-v2.10.125 ``` #### Using the Chef InSpec target option to provide credentials on AWS Look for a file in your home directory named `~/.aws/credentials`. If it does not exist, create it. Choose a name for your profile; here, we’re using the name ‘auditing’. Add your credentials as a new profile, in INI format: ``` [auditing] aws_access_key_id = AKIA.... aws_secret_access_key = <KEY> ``` You may now run Chef InSpec using the `--target` / `-t` option, using the format `-t aws://region/profile`. For example, to connect to the Ohio region using a profile named ‘auditing’, use `-t aws://us-east-2/auditing`. To verify your credentials, run ``` $ inspec detect -t aws:// == Platform Details Name: aws Families: cloud, api Release: aws-sdk-v2.10.125 ``` Azure Platform Support in InSpec -------------------------------- ### Setting up Azure credentials for InSpec To use Chef InSpec Azure resources, you will need to create a Service Principal Name (SPN) for auditing an Azure subscription. This can be done on the command line or from the Azure Portal: * [Azure CLI](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal-cli) * [PowerShell](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal) * [Azure Portal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) The information from the SPN can be specified either in the file `~/.azure/credentials`, as environment variables, or by using Chef InSpec target URIs. #### Setting up the Azure Credentials File By default, Chef InSpec is configured to look at `~/.azure/credentials`, and it should contain: ``` [<SUBSCRIPTION_ID>] client_id = "<CLIENT_ID>" client_secret = "<CLIENT_SECRET>" tenant_id = "<TENANT_ID>" ``` Note In the Azure web portal, these values are labeled differently: * The client_id is referred to as the ‘Application ID’ * The client_secret is referred to as the ‘Key (Password Type)’ * The tenant_id is referred to as the ‘Directory ID’ With the credentials are in place, you may now execute InSpec: ``` inspec exec my-inspec-profile -t azure:// ``` #### Using Environment variables to provide credentials You may also set the Azure credentials via environment variables: * `AZURE_SUBSCRIPTION_ID` * `AZURE_CLIENT_ID` * `AZURE_CLIENT_SECRET` * `AZURE_TENANT_ID` For example: ``` AZURE_SUBSCRIPTION_ID="2fbdbb02-df2e-11e6-bf01-fe55135034f3" \ AZURE_CLIENT_ID="58dc4f6c-df2e-11e6-bf01-fe55135034f3" \ AZURE_CLIENT_SECRET="<KEY>" \ AZURE_TENANT_ID="6<KEY>2<KEY>" inspec exec my-profile -t azure:// ``` #### Using the Chef InSpec target option to provide credentials on Azure If you have created a `~/.azure/credentials` file as above, you may also use the Chef InSpec command line `--target` / `-t` option to select a subscription ID. For example: ``` inspec exec my-profile -t azure://2fbdbb02-df2e-11e6-bf01-fe55135034f3 ``` GCP Platform Support in InSpec ------------------------------ ### Setting up GCP credentials for InSpec To use Chef InSpec GCP resources, you will need to install and configure the Google Cloud SDK. Instructions for this pre-requisite can be found in the [Google CLoud SDK documentation](https://cloud.google.com/sdk/docs/). Be sure that your InSpec installation is the latest version. The minimal required InSpec version is 3.0.25. ### Create an InSpec profile that makes use of `inspec-gcp`. With a version of InSpec above 4.0.0, it is possible to create a profile with the following command: ``` $ inspec init profile --platform gcp my-profile Create new profile at /Users/me/my-profile * Creating directory libraries * Creating file README.md * Creating directory controls * Creating file controls/example.rb * Creating file inspec.yml * Creating file inputs.yml * Creating file libraries/.gitkeep ``` Assuming the `inputs.yml` file contains your GCP project ID, this sample profile can then be executed using the following command: ``` inspec exec my-profile --input-file=my-profile/inputs.yml -t gcp:// ``` #### Setting up the GCP Credentials File While InSpec can use user accounts for authentication, [Google Cloud documentation](https://cloud.google.com/docs/authentication/) recommends using service accounts. Following GCP best practices, first create a service account with the scopes appropriate for your needs. See [these instructions](https://cloud.google.com/docs/authentication/getting-started) on creating a service account. Then, download the credential JSON file, e.g. `project-credentials.json`, to your workspace and run the following command to activate your service account: ``` gcloud auth activate-service-account --key-file project-credentials.json ``` #### Using Environment variables to provide credentials You may also set the GCP credentials json file via the `GOOGLE_APPLICATION_CREDENTIALS` environment variable. ``` export GOOGLE_APPLICATION_CREDENTIALS='/Users/me/.config/gcloud/myproject-1-feb7993e8660.json' ``` Once you have your environment variables set, you can verify your credentials by running: ``` $ inspec detect -t gcp:// == Platform Details Name: gcp Families: cloud, api Release: google-cloud-v ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/platforms/InSpec CLI ========== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/cli.md) Use the InSpec CLI to run tests and audits against targets using local, SSH, WinRM, or Docker connections. archive ------- Archive a profile to tar.gz (default) or zip. ### Syntax This subcommand has the following syntax: ``` inspec archive PATH ``` ### Options This subcommand has the following additional options: * `--airgap`, `--no-airgap` Fallback to using local archives if fetching fails. * `--ignore-errors`, `--no-ignore-errors` Ignore profile warnings. * `-o`, `--output=OUTPUT` Save the archive to a path. * `--overwrite`, `--no-overwrite` Overwrite existing archive. * `--profiles-path=PROFILES_PATH` Folder which contains referenced profiles. * `--tar`, `--no-tar` Generates a tar.gz archive. * `--vendor-cache=VENDOR_CACHE` Use the given path for caching dependencies, (default: `~/.inspec/cache`). * `--zip`, `--no-zip` Generates a zip archive. automate -------- Communicate with Chef Automate. ### Syntax This subcommand has the following syntax: ``` inspec automate SUBCOMMAND ``` check ----- Verify the metadata in the inspec.yml file, verify that control blocks have the correct fields (title, description, impact) defined, that all controls have visible tests, and that controls are not using deprecated InSpec DSL code. ### Syntax This subcommand has the following syntax: ``` inspec check PATH ``` ### Options This subcommand has the following additional options: * `--format=FORMAT` The output format to use. Valid values: `json` and `doc`. Default value: `doc`. * `--profiles-path=PROFILES_PATH` Folder which contains referenced profiles. * `--vendor-cache=VENDOR_CACHE` Use the given path for caching dependencies, (default: `~/.inspec/cache`). detect ------ Detect the target OS. ### Syntax This subcommand has the following syntax: ``` inspec detect ``` ### Options This subcommand has the following additional options: * `-b`, `--backend=BACKEND` Choose a backend: local, ssh, winrm, docker. * `--bastion-host=BASTION_HOST` Specifies the bastion host if applicable. * `--bastion-port=BASTION_PORT` Specifies the bastion port if applicable. * `--bastion-user=BASTION_USER` Specifies the bastion user if applicable. * `--config=CONFIG` Read configuration from JSON file (`-` reads from stdin). * `--docker-url` Provides path to Docker API endpoint (Docker). * `--enable-password=ENABLE_PASSWORD` Password for enable mode on Cisco IOS devices. * `--format=FORMAT` * `--host=HOST` Specify a remote host which is tested. * `--insecure`, `--no-insecure` Disable SSL verification on select targets. * `-i`, `--key-files=one two three` Login key or certificate file for a remote scan. * `--password=PASSWORD` Login password for a remote scan, if required. * `--path=PATH` Login path to use when connecting to the target (WinRM). * `-p`, `--port=N` Specify the login port for a remote scan. * `--proxy-command=PROXY_COMMAND` Specifies the command to use to connect to the server. * `--self-signed`, `--no-self-signed` Allow remote scans with self-signed certificates (WinRM). * `--shell`, `--no-shell` Run scans in a subshell. Only activates on Unix. * `--shell-command=SHELL_COMMAND` Specify a particular shell to use. * `--shell-options=SHELL_OPTIONS` Additional shell options. * `--ssl`, `--no-ssl` Use SSL for transport layer encryption (WinRM). * `--sudo`, `--no-sudo` Run scans with sudo. Only activates on Unix and non-root user. * `--sudo-command=SUDO_COMMAND` Alternate command for sudo. * `--sudo-options=SUDO_OPTIONS` Additional sudo options for a remote scan. * `--sudo-password=SUDO_PASSWORD` Specify a sudo password, if it is required. * `-t`, `--target=TARGET` Simple targeting option using URIs, e.g. ssh://user:pass@host:port. * `--target-id=TARGET_ID` Provide a ID which will be included on reports. * `--user=USER` The login user for a remote scan. * `--winrm-basic-auth-only`, `--no-winrm-basic-auth-only` Whether to use basic authentication, defaults to false (WinRM). * `--winrm-disable-sspi`, `--no-winrm-disable-sspi` Whether to use disable sspi authentication, defaults to false (WinRM). * `--winrm-transport=WINRM_TRANSPORT` Specify which transport to use, defaults to negotiate (WinRM). * `--winrm-shell-type=WINRM_SHELL_TYPE` Specify which shell type to use (powershell,elevated or cmd), defaults to powershell (WinRM). env --- Output shell-appropriate completion configuration. ### Syntax This subcommand has the following syntax: ``` inspec env ``` exec ---- Run all test files at the specified locations. The subcommand loads the given profiles, fetches their dependencies if needed, then connects to the target and executes any controls contained in the profiles. One or more reporters are used to generate the output. ``` exit codes: 0 normal exit, all tests passed 1 usage or general error 2 error in plugin system 3 fatal deprecation encountered 100 normal exit, at least one test failed 101 normal exit, at least one test skipped but none failed 172 chef license not accepted ``` Below are some examples of using `exec` with different test locations: Chef Automate: ``` inspec automate login inspec exec compliance://username/linux-baseline ``` `inspec compliance` is a backwards compatible alias for `inspec automate` and works the same way: ``` inspec compliance login ``` Chef Supermarket: ``` inspec exec supermarket://username/linux-baseline inspec exec supermarket://username/linux-baseline --supermarket_url="https://privatesupermarket.example.com" ``` Local profile (executes all tests in `controls/`): ``` inspec exec /path/to/profile ``` Local single test (doesn’t allow inputs or custom resources): ``` inspec exec /path/to/a_test.rb ``` Git via SSH: ``` inspec exec git@github.com:dev-sec/linux-baseline.git ``` Git via HTTPS (.git suffix is required): ``` inspec exec https://github.com/dev-sec/linux-baseline.git ``` Private Git via HTTPS (.git suffix is required): ``` inspec exec https://api_token@github.com/dev-sec/linux-baseline.git ``` Private Git via HTTPS and cached credentials (.git suffix is required): ``` git config credential.helper cache git ls-remote https://github.com/dev-sec/linux-baseline.git inspec exec https://github.com/dev-sec/linux-baseline.git ``` Web-hosted file (also supports .zip): ``` inspec exec https://webserver/linux-baseline.tar.gz ``` Web-hosted file with basic authentication (supports .zip): ``` inspec exec https://username:password@webserver/linux-baseline.tar.gz ``` ### Syntax This subcommand has the following syntax: ``` inspec exec LOCATIONS ``` ### Options This subcommand has the following additional options: * `--attrs=one two three` Legacy name for –input-file - deprecated. * `-b`, `--backend=BACKEND` Choose a backend: local, ssh, winrm, docker. * `--backend-cache`, `--no-backend-cache` Allow caching for backend command output. (default: true). * `--bastion-host=BASTION_HOST` Specifies the bastion host if applicable. * `--bastion-port=BASTION_PORT` Specifies the bastion port if applicable. * `--bastion-user=BASTION_USER` Specifies the bastion user if applicable. * `--command-timeout=SECONDS` Maximum seconds to allow a command to run. * `--config=CONFIG` Read configuration from JSON file (`-` reads from stdin). * `--controls=one two three` A list of control names to run, or a list of /regexes/ to match against control names. Ignore all other tests. * `--create-lockfile`, `--no-create-lockfile` Write out a lockfile based on this execution (unless one already exists). * `--distinct-exit`, `--no-distinct-exit` Exit with code 101 if any tests fail, and 100 if any are skipped (default). If disabled, exit 0 on skips and 1 for failures. * `--docker-url` Provides path to Docker API endpoint (Docker). Defaults to unix:///var/run/docker.sock on Unix systems and tcp://localhost:2375 on Windows. * `--enable-password=ENABLE_PASSWORD` Password for enable mode on Cisco IOS devices. * `--filter-empty-profiles`, `--no-filter-empty-profiles` Filter empty profiles (profiles without controls) from the report. * `--filter-waived-controls` Do not execute waived controls in InSpec at all. Must use with –waiver-file. Ignores `run` setting of waiver file. * `--host=HOST` Specify a remote host which is tested. * `--input=name1=value1 name2=value2` Specify one or more inputs directly on the command line, as –input NAME=VALUE. Accepts single-quoted YAML and JSON structures. * `--input-file=one two three` Load one or more input files, a YAML file with values for the profile to use. * `--insecure`, `--no-insecure` Disable SSL verification on select targets. * `-i`, `--key-files=one two three` Login key or certificate file for a remote scan. * `--password=PASSWORD` Login password for a remote scan, if required. * `--path=PATH` Login path to use when connecting to the target (WinRM). * `-p`, `--port=N` Specify the login port for a remote scan. * `--profiles-path=PROFILES_PATH` Folder which contains referenced profiles. * `--proxy-command=PROXY_COMMAND` Specifies the command to use to connect to the server. * `--reporter=one two:/output/file/path` Enable one or more output reporters: cli, documentation, html, progress, json, json-min, json-rspec, junit, yaml. * `--reporter-backtrace-inclusion`, `--no-reporter-backtrace-inclusion` Include a code backtrace in report data (default: true). * `--reporter-include-source` Include full source code of controls in the CLI report. * `--reporter-message-truncation=REPORTER_MESSAGE_TRUNCATION` Number of characters to truncate failure messages in report data to (default: no truncation). * `--self-signed`, `--no-self-signed` Allow remote scans with self-signed certificates (WinRM). * `--shell`, `--no-shell` Run scans in a subshell. Only activates on Unix. * `--shell-command=SHELL_COMMAND` Specify a particular shell to use. * `--shell-options=SHELL_OPTIONS` Additional shell options. * `--show-progress`, `--no-show-progress` Show progress while executing tests. * `--silence-deprecations=all|GROUP GROUP...` Suppress deprecation warnings. See install_dir/etc/deprecations.json for list of GROUPs or use ‘all’. * `--ssh-config-file=one two three` A list of paths to the SSH configuration file, for example: `~/.ssh/config` or `/etc/ssh/ssh_config`. * `--ssl`, `--no-ssl` Use SSL for transport layer encryption (WinRM). * `--sudo`, `--no-sudo` Run scans with sudo. Only activates on Unix and non-root user. * `--sudo-command=SUDO_COMMAND` Alternate command for sudo. * `--sudo-options=SUDO_OPTIONS` Additional sudo options for a remote scan. * `--sudo-password=SUDO_PASSWORD` Specify a sudo password, if it is required. * `-t`, `--target=TARGET` Simple targeting option using URIs, e.g. ssh://user:pass@host:port. * `--target-id=TARGET_ID` Provide a ID which will be included on reports. * `--tags=one two three` A list of tags or a list of regular expressions that match tags. `exec` will run controls referenced by the listed or matching tags. * `--user=USER` The login user for a remote scan. * `--vendor-cache=VENDOR_CACHE` Use the given path for caching dependencies. (default: `~/.inspec/cache`). * `--waiver-file=one two three` Load one or more waiver files. * `--winrm-basic-auth-only`, `--no-winrm-basic-auth-only` Whether to use basic authentication, defaults to false (WinRM). * `--winrm-disable-sspi`, `--no-winrm-disable-sspi` Whether to use disable sspi authentication, defaults to false (WinRM). * `--winrm-transport=WINRM_TRANSPORT` Specify which transport to use, defaults to negotiate (WinRM). habitat ------- Create a Chef Habitat package. ### Syntax This subcommand has the following syntax: ``` inspec habitat SUBCOMMAND ``` help ---- Describe available commands or one specific command. ### Syntax This subcommand has the following syntax: ``` inspec help [COMMAND] ``` init ---- Scaffold a new project. ### Syntax This subcommand has the following syntax: ``` inspec init TEMPLATE ``` json ---- Read all tests in path and generate a json summary. ### Syntax This subcommand has the following syntax: ``` inspec json PATH ``` ### Options This subcommand has the following additional options: * `--controls=one two three` A list of controls to include. Ignore all other tests. * `-o`, `--output=OUTPUT` Save the created profile to a path. * `--profiles-path=PROFILES_PATH` Folder which contains referenced profiles. * `--tags=one two three` A list of tags that reference certain controls. Other controls are ignored. * `--vendor-cache=VENDOR_CACHE` Use the given path for caching dependencies. (default: `~/.inspec/cache`). nothing ------- Does nothing. ### Syntax This subcommand has the following syntax: ``` inspec nothing ``` plugin ------ Install and manage [Chef InSpec plugins](../plugins/index). ### Syntax This subcommand has the following syntax: ``` inspec plugin SUBCOMMAND ``` schema ------ Print the json schema. ### Syntax This subcommand has the following syntax: ``` inspec schema NAME ``` shell ----- Open an interactive debugging shell. ### Syntax This subcommand has the following syntax: ``` inspec shell ``` ### Options This subcommand has the following additional options: * `-b`, `--backend=BACKEND` Choose a backend: local, ssh, winrm, docker. * `--bastion-host=BASTION_HOST` Specifies the bastion host if applicable. * `--bastion-port=BASTION_PORT` Specifies the bastion port if applicable. * `--bastion-user=BASTION_USER` Specifies the bastion user if applicable. * `-c`, `--command=COMMAND` A single command string to run instead of launching the shell. * `--command-timeout=SECONDS` Maximum seconds to allow a command to run. * `--config=CONFIG` Read configuration from JSON file (`-` reads from stdin). * `--depends=one two three` A space-delimited list of local folders containing profiles whose libraries and resources will be loaded into the new shell. * `--distinct-exit`, `--no-distinct-exit` Exit with code 100 if any tests fail, and 101 if any are skipped but none failed (default). If disabled, exit 0 on skips and 1 for failures. * `--docker-url` Provides path to Docker API endpoint (Docker). Defaults to unix:///var/run/docker.sock on Unix systems and tcp://localhost:2375 on Windows. * `--enable-password=ENABLE_PASSWORD` Password for enable mode on Cisco IOS devices. * `--host=HOST` Specify a remote host which is tested. * `--insecure`, `--no-insecure` Disable SSL verification on select targets. * `--inspect`, `--no-inspect` Use verbose/debugging output for resources. * `-i`, `--key-files=one two three` Login key or certificate file for a remote scan. * `--password=PASSWORD` Login password for a remote scan, if required. * `--path=PATH` Login path to use when connecting to the target (WinRM). * `-p`, `--port=N` Specify the login port for a remote scan. * `--proxy-command=PROXY_COMMAND` Specifies the command to use to connect to the server. * `--reporter=one two:/output/file/path` Enable one or more output reporters: cli, documentation, html, progress, json, json-min, json-rspec, junit. * `--self-signed`, `--no-self-signed` Allow remote scans with self-signed certificates (WinRM). * `--shell`, `--no-shell` Run scans in a subshell. Only activates on Unix. * `--shell-command=SHELL_COMMAND` Specify a particular shell to use. * `--shell-options=SHELL_OPTIONS` Additional shell options. * `--ssh-config-file=one two three` A list of paths to the SSH configuration file, for example: `~/.ssh/config` or `/etc/ssh/ssh_config`. * `--ssl`, `--no-ssl` Use SSL for transport layer encryption (WinRM). * `--sudo`, `--no-sudo` Run scans with sudo. Only activates on Unix and non-root user. * `--sudo-command=SUDO_COMMAND` Alternate command for sudo. * `--sudo-options=SUDO_OPTIONS` Additional sudo options for a remote scan. * `--sudo-password=SUDO_PASSWORD` Specify a sudo password, if it is required. * `-t`, `--target=TARGET` Simple targeting option using URIs, e.g. ssh://user:pass@host:port. * `--target-id=TARGET_ID` Provide a ID which will be included on reports. * `--user=USER` The login user for a remote scan. * `--winrm-basic-auth-only`, `--no-winrm-basic-auth-only` Whether to use basic authentication, defaults to false (WinRM). * `--winrm-disable-sspi`, `--no-winrm-disable-sspi` Whether to use disable sspi authentication, defaults to false (WinRM). * `--winrm-transport=WINRM_TRANSPORT` Specify which transport to use, defaults to negotiate (WinRM). supermarket ----------- Supermarket commands. ### Syntax This subcommand has the following syntax: ``` inspec supermarket SUBCOMMAND ... ``` ### Options This subcommand has additional options: * `--supermarket_url` Specify the URL of a private Chef Supermarket. vendor ------ Download all dependencies and generate a lockfile in a `vendor` directory. ### Syntax This subcommand has the following syntax: ``` inspec vendor PATH ``` ### Options This subcommand has additional options: * `--overwrite`, `--no-overwrite` Overwrite existing vendored dependencies and lockfile. version ------- Prints the version of this tool. ### Syntax This subcommand has the following syntax: ``` inspec version ``` ### Options This subcommand has the following additional options: * `--format=FORMAT` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/cli/Chef InSpec Universal Matchers Reference ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/matchers.md) Chef InSpec uses matchers to help compare resource values to expectations. The following matchers are available: You may also use any matcher provided by [RSpec::Expectations](https://relishapp.com/rspec/rspec-expectations/docs), but those matchers are outside of InSpec’s [scope of support](../inspec_and_friends/index#rspec). The following InSpec-supported universal matchers are available: * [`be`](#be) - make numeric comparisons * [`be_in`](#be_in) - look for the property value in a list * [`cmp`](#cmp) - general-use equality (try this first) * [`eq`](#eq) - type-specific equality * [`include`](#include) - look for an expected value in a list-valued property * [`match`](#match) - look for patterns in text using regular expressions See [Explore Chef InSpec resources](https://learn.chef.io/modules/explore-inspec-resources#/) on Learn Chef Rally to learn more about InSpec’s built-in matchers. be -- This matcher can be followed by many different comparison operators. Always make sure to use numbers, not strings, for these comparisons. ``` describe file('/proc/cpuinfo') do its('size') { should be >= 10 } its('size') { should be < 1000 } end ``` cmp --- Unlike `eq`, `cmp` is a matcher for less-restrictive comparisons. It will try to fit the actual value to the type you are comparing it to. This is meant to relieve the user from having to write type-casts and resolutions. ``` describe sshd_config do its('Protocol') { should cmp 2 } end describe passwd.uid(0) do its('users') { should cmp 'root' } end ``` `cmp` behaves in the following way: * Compare strings to numbers ``` describe sshd_config do # Only `'2'` works its('Protocol') { should eq '2' } # Both of these work its('Protocol') { should cmp '2' } its('Protocol') { should cmp 2 } end ``` * String comparisons are not case-sensitive ``` describe auditd_conf do its('log_format') { should cmp 'raw' } its('log_format') { should cmp 'RAW' } end ``` * Recognize versions embedded in strings ``` describe package('curl') do its('version') { should cmp > '7.35.0-1ubuntu2.10' } end ``` * Compare arrays with only one entry to a value ``` describe passwd.uids(0) do its('users') { should cmp 'root' } its('users') { should cmp ['root'] } end ``` * Single-value arrays of strings may also be compared to a regex ``` describe auditd_conf do its('log_format') { should cmp /raw/i } end ``` * Improved printing of octal comparisons ``` describe file('/proc/cpuinfo') do its('mode') { should cmp '0345' } end expected: 0345 got: 0444 ``` eq -- Test for exact equality of two values. ``` describe sshd_config do its('RSAAuthentication') { should_not eq 'no' } its('Protocol') { should eq '2' } end ``` `eq` fails if types don’t match. Please keep this in mind, when comparing configuration entries that are numbers: ``` its('Port') { should eq '22' } # ok its('Port') { should eq 22 } # fails: '2' != 2 (string vs int) ``` For less restrictive comparisons, please use `cmp`. include ------- Verifies if a value is included in a list. ``` describe passwd do its('users') { should include 'my_user' } end ``` be_in ------ Verifies that an item is included in a list. ``` describe resource do its('item') { should be_in LIST } end ``` match ----- Check if a string matches a regular expression. ``` describe sshd_config do its('Ciphers') { should_not match /cbc/ } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/matchers/About Chef InSpec Profiles ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/profiles.md) Chef InSpec supports the creation of complex test and compliance profiles, which organize controls to support dependency management and code reuse. Each profile is a standalone structure with its own distribution and execution flow. Profile Structure ----------------- A profile should have the following structure: ``` examples/profile├── README.md├── controls│ ├── example.rb│ └── control_etc.rb├── libraries│ └── extension.rb|── files│ └── extras.conf└── inspec.yml ``` where: * `inspec.yml` includes the profile description (required) * `controls` is the directory in which all tests are located (required) * `libraries` is the directory in which all Chef InSpec resource extensions are located (optional) * `files` is the directory with additional files that a profile can access (optional) * `README.md` should be used to explain the profile, its scope, and usage See a complete example profile in the Chef InSpec open source repository: [Example Chef InSpec Profile](https://github.com/chef/inspec/tree/main/examples/profile) Also check out [Explore Chef InSpec resources](https://learn.chef.io/modules/explore-inspec-resources#/) on Learn Chef Rally to learn more about how profiles are structured with hands-on-examples. inspec.yml ---------- Each profile must have an `inspec.yml` file that defines the following information: * Use `name` to specify a unique name for the profile. Required. * Use `title` to specify a human-readable name for the profile. * Use `maintainer` to specify the profile maintainer. * Use `copyright` to specify the copyright holder. * Use `copyright_email` to specify support contact information for the profile, typically an email address. * Use `license` to specify the license for the profile. * Use `summary` to specify a one line summary for the profile. * Use `description` to specify a multiple line description of the profile. * Use `version` to specify the profile version. * Use `inspec_version` to place SemVer constraints on the version of Chef InSpec that the profile can run under. * Use `supports` to specify a list of supported platform targets. * Use `depends` to define a list of profiles on which this profile depends. * Use `inputs` to define a list of inputs you can use in your controls. `name` is required; all other profile settings are optional. For example: ``` name:sshtitle:Basic SSHmaintainer:Chef Software, Inc.copyright:Chef Software, Inc.copyright_email:<EMAIL>olicense:Proprietary, All rights reservedsummary:Verify that SSH Server and SSH Client are configured securelyversion:1.0.0supports:- platform-family:linuxdepends:- name:profilepath:../path/to/profileinspec_version:"~> 2.1" ``` The `inspec.yml` also supports embedded ERB in the file. For example: ``` name:dummytitle:InSpec Profilemaintainer:The Authorscopyright:The Authorscopyright_email:<EMAIL>license:Apache-2.0summary:An InSpec Compliance Profileversion:0.1.0depends:- name:inheriturl:"https://artifactory.com/artifactory/example-repo-local/inspec/0.4.1.tar.gz"username:<%= ENV['USERNAME'] %>password:<%= ENV['API_KEY'] %> ``` Verify Profiles --------------- Use the `inspec check` command to verify the implementation of a profile: ``` inspec check examples/profile ``` Platform Support ---------------- Use the `supports` setting in the `inspec.yml` file to specify one (or more) platforms for which a profile is targeting. The list of supported platforms may contain the following: * Use `platform-family` to restrict to a specific platform family. * Use `platform-name` to restrict on a specific platform name. `platform-name` supports asterisk (`*`) wildcard use. * Use `release` to restrict to a specific platform version, and use together with `platform-name`. `release` supports asterisk (`*`) wildcard use. * Use `platform` to restrict on either platform-name or platform-family. For compatibility we support `os-name` and `os-family`. We recommend all users to change `os-name` to `platform-name` and `os-family` to `platform-family`. With Chef InSpec 2.0, we introduced new families to help distinguish the cloud platforms. The new families can restrict the platform family to `os`, `aws`, `azure` or `gcp`. For example, to target anything running Debian Linux, use: ``` name:sshsupports:- platform-name:debian ``` To target only Ubuntu version 20.04, use: ``` name:sshsupports:- platform-name:ubunturelease:20.04 ``` To target the entire release of Ubuntu version 20.x, use: ``` name:sshsupports:- platform-name:ubunturelease:20.* ``` To target the Red Hat and derivative platforms such as CentOS and Oracle Linux, use: ``` name:sshsupports:- platform-family:redhat ``` To target the entire Windows 2019 platform family, including Datacenter and Core Servers, use: ``` name:sshsupports:- platform-name:windows_server_2019* ``` To target anything running on Amazon AWS, use: ``` name:sshsupports:- platform:aws ``` To target all of these examples in a single `inspec.yml` file, use: ``` name:sshsupports:- platform-name:debian- platform-name:ubunturelease:20.04- platform-family:redhat- platform:aws ``` Profile Dependencies -------------------- A Chef InSpec profile can bring in the controls and custom resources from another Chef InSpec profile. Additionally, when inheriting the controls of another profile, a profile can skip or even modify those included controls. For hands-on examples, check out [Create a custom Chef InSpec profile](https://learn.chef.io/modules/create-a-custom-profile#/) on Learn Chef Rally. ### Defining the Dependencies Before a profile can use controls from another profile, the to-be-included profile needs to be specified in the including profile’s `inspec.yml` file in the `depends` section. For each profile to be included, a location for the profile from where to be fetched and a name for the profile should be included. For example: ``` depends:- name:linux-baselineurl:https://github.com/dev-sec/linux-baseline/archive/master.tar.gz- name:ssh-baselineurl:https://github.com/dev-sec/ssh-baseline/archive/master.tar.gz ``` Chef InSpec supports a number of dependency sources. #### path The `path` setting defines a profile that is located on disk. This setting is typically used during development of profiles and when debugging profiles. ``` depends:- name:my-profilepath:/absolute/path- name:anotherpath:../relative/path ``` #### url The `url` setting specifies a profile that is located at an HTTP- or HTTPS-based URL. The profile must be accessible via a HTTP GET operation and must be a valid profile archive (zip, tar, or tar.gz format). ``` depends:- name:my-profileurl:https://my.domain/path/to/profile.tgz- name:profile-via-giturl:https://github.com/myusername/myprofile-repo/archive/master.tar.gz ``` `url` also supports basic authentication. ``` depends:- name:my-profileurl:https://my.domain/path/to/profile.tgzusername:userpassword:password ``` #### git A `git` setting specifies a profile that is located in a git repository, with optional settings for branch, tag, commit, version, and relative_path. The source location is translated into a URL upon resolution. This type of dependency supports version constraints via semantic versioning as git tags. ``` depends:- name:git-profilegit:http://url/to/repobranch:desired_branchtag:desired_versioncommit:pinned_commitversion:semver_via_tagsrelative_path:relative/optional/path/to/profile ``` #### supermarket A `supermarket` setting specifies a profile that is located in a cookbook hosted on Chef Supermarket. The source location is translated into a URL upon resolution. For example: ``` depends:- name:supermarket-profilesupermarket:supermarket-username/supermarket-profile ``` Available Supermarket profiles can be listed with `inspec supermarket profiles`. #### compliance A `compliance` setting specifies a profile that is located on the Chef Automate or Chef Compliance server. For example: ``` depends:- name:linuxcompliance:base/linux ``` Vendoring Dependencies ---------------------- When you execute a local profile, the `inspec.yml` file will be read in order to source any profile dependencies. It will then cache the dependencies locally and generate an `inspec.lock` file. If you add or update dependencies in `inspec.yml`, dependencies may be re-vendored and the lockfile updated with `inspec vendor --overwrite` Using Controls from an Included Profile --------------------------------------- Once defined in the `inspec.yml`, controls from the included profiles can be used! Let’s look at some examples. ### Including All Controls from a Profile With the `include_controls` command in a profile, all controls from the named profile will be executed every time the including profile is executed. ![Include Controls] In the example above, every time `my-app-profile` is executed, all the controls from `my-baseline` are also executed. Therefore, the following controls would be executed: * myapp-1 * myapp-2 * myapp-3 * baseline-1 * baseline-2 This is a great reminder that having a good naming convention for your controls is helpful to avoid confusion when including controls from other profiles! ### Skipping a Control from a Profile What if one of the controls from the included profile does not apply to your environment? Luckily, it is not necessary to maintain a slightly-modified copy of the included profile just to delete a control. The `skip_control` command tells Chef InSpec to not run a particular control. ![Include Controls with Skip] In the above example, all controls from `my-app-profile` and `my-baseline` profile will be executed every time `my-app-profile` is executed **except** for control `baseline-2` from the `my-baseline` profile. ### Modifying a Control Let’s say a particular control from an included profile should still be run, but the impact isn’t appropriate? Perhaps the test should still run, but if it fails, it should be treated as low severity instead of high severity? When a control is included, it can also be modified! ![Include Controls with Modification] In the above example, all controls from `my-baseline` are executed along with all the controls from the including profile, `my-app-profile`. However, should control `baseline-1` fail, it will be raised with an impact of `0.5` instead of the originally-intended impact of `1.0`. ### Selectively Including Controls from a Profile If there are only a handful of controls that should be executed from an included profile, it’s not necessarily to skip all the unneeded controls, or worse, copy/paste those controls bit-for-bit into your profile. Instead, use the `require_controls` command. ![Require Controls] Whenever `my-app-profile` is executed, in addition to its own controls, it will run only the controls specified in the `require_controls` block. In the case, the following controls would be executed: * myapp-1 * myapp-2 * myapp-3 * baseline-2 * baseline-4 Controls `baseline-1`, `baseline-3`, and `baseline-5` would not be run, just as if they were manually skipped. This method of including specific controls ensures only the controls specified are executed; if new controls are added to a later version of `my-baseline`, they would not be run. And, just the way its possible to modify controls when using `include_controls`, controls can be modified as well. ![Require Controls with Modification] As with the prior example, only `baseline-2` and `baseline-4` are executed, but if `baseline-2` fails, it will report with an impact of `0.5` instead of the originally-intended `1.0` impact. Using Resources from an Included Profile ---------------------------------------- By default, all of the custom resources from a listed dependency are available for use in your profile. If two of your dependencies provide a resource with the same name, you can use the `require_resource` DSL function to disambiguate the two: ``` require_resource(profile: 'my_dep', resource:'my_res',as:'my_res2') ``` This will allow you to reference the resource `my_res` from the profile `my_dep` using the name `my_res2`. Profile Inputs -------------- Our documentation regarding [Inputs](../inputs/index) is now on a dedicated page. Profile files ------------- A Chef InSpec profile may contain additional files that can be accessed during tests. A profile file enables you to separate the logic of your tests from the data your tests check for, for example, the list of ports you require to be open. To access these files, they must be stored in the `files` directory at the root of a profile. They are accessed by their name relative to this folder with `inspec.profile.file(...)`. Here is an example for reading and testing a list of ports. The folder structure is: ``` examples/profile├── controls│ ├── example.rb│── files│ └── services.yml└── inspec.yml ``` With `services.yml` containing: ``` - service_name:httpd-alphaport:80- service_name:httpd-betaport:8080 ``` The tests in `example.rb` can now access this file: ``` my_services = yaml(content: inspec.profile.file('services.yml')).params my_services.each do |s| describe service(s['service_name']) do it { should be_running } end describe port(s['port']) do it { should be_listening } end end ``` For a more complete example that uses a profile file, see [Explore Chef InSpec resources](https://learn.chef.io/modules/explore-inspec-resources#/) on Learn Chef Rally. “should” vs. “expect” syntax ---------------------------- Users familiar with the RSpec testing framework may know that there are two ways to write test statements: `should` and `expect`. The RSpec community decided that `expect` is the preferred syntax. However, Chef InSpec recommends the `should` syntax as it tends to read more easily to those users who are not as technical. Chef InSpec will continue to support both methods of writing tests. Consider this `file` test: ``` describe file('/tmp/test.txt') do it { should be_file } end ``` This can be re-written with `expect` syntax ``` describe file('/tmp/test.txt') do it 'should be a file' do expect(subject).to(be_file) end end ``` The output of both of the above examples looks like this: ``` File /tmp/test.txt ✔ should be a file ``` In addition, you can make use of the `subject` keyword to further control your output if you choose: ``` describe 'test file' do subject { file('/tmp/test.txt') } it 'should be a file' do expect(subject).to(be_file) end end ``` &mldr; which will render the following output: ``` test file ✔ should be a file ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/profiles/Chef InSpec Reporters ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/reporters.md) Introduced in Chef InSpec 1.51.6 A `reporter` is a facility for formatting and delivering the results of a Chef InSpec auditing run. Chef InSpec allows you to output your test results to one or more reporters. Configure the reporter(s) using either the `--reporter` option or as part of the general config file using the `--config` (or `--json-config`, prior to v3.6) option. While you can configure multiple reporters to write to different files, only one reporter can output to the screen(stdout). Syntax ------ You can specify one or more reporters using the `--reporter` cli flag. You can also specify a output by appending a path separated by a colon. Output json to screen. ``` inspec exec example_profile --reporter json # or explicitly specifying output to STDOUT: inspec exec example_profile --reporter json:- ``` Output yaml to screen ``` inspec exec example_profile --reporter yaml # or inspec exec example_profile --reporter yaml:- ``` Output cli to screen and write json to a file. ``` inspec exec example_profile --reporter cli json:/tmp/output.json ``` Output nothing to screen and write junit and html to a file. ``` inspec exec example_profile --reporter junit2:/tmp/junit.xml html:www/index.html ``` Output json to screen and write to a file. Write junit to a file. ``` inspec exec example_profile --reporter json junit2:/tmp/junit.xml | tee out.json ``` If you wish to pass the profiles directly after specifying the reporters you will need to use the end of options flag `--`. ``` inspec exec --reporter json junit2:/tmp/junit.xml -- profile1 profile2 ``` If you are using the cli option `--config`, you can also set reporters. Output cli to screen. ``` { "reporter": { "cli" : { "stdout" : true } } } ``` Output cli to screen and write json to a file. ``` { "reporter": { "cli" : { "stdout" : true }, "json" : { "file" : "/tmp/output.json", "stdout" : false } } } ``` Reporter Options ---------------- The following are CLI options that may be used to modify reporter behavior. Many of these options allow you to limit the size of the report, because some reporters (such as the json-automate reporter) have a limit on the total size of the report that can be processed. `--diff`, `--no-diff` Include a `diff` comparison of textual differences in failed test output (default: `true`). Use `--no-diff` to limit the size of the report output when tests contain large amounts of text output. `--filter-empty-profiles` Remove empty profiles (those containing zero controls, such as resource packs) from the output of the reporter. `--reporter-backtrace-inclusion`, `--no-reporter-backtrace-inclusion` Include a code backtrace in report data (default: `true`). The `--no-reporter-backtrace-inclusion` option may be used to limit report size when large code stack traces are present in the output. `--reporter-include-source` (CLI reporter only) Include full source code of controls in the report. `--reporter-message-truncation=N` Number of characters to truncate failure messages in report data (default: no truncation). This may be used to limit the size of reports when failure messages are exceptionally large. Supported Reporters ------------------- The following are the current supported reporters: ### cli This is the basic text base report. It includes details about which tests passed and failed and includes an overall summary at the end. ### json This reporter includes all information about the profiles and test results in standard JSON format. You may optionally pass through arbitrary structured JSON data by setting a JSON configuration with the `--config` parameter. For example: ``` { "reporter": { "json": { "stdout": true, "passthrough": { "a": 1, "b": false } } } } ``` ### json-min This reporter is a redacted version of the json and only includes test results. ### yaml This reporter includes all information about the profiles and test results in standard yaml format. ### documentation This reporter is a very minimal text base report. It shows you which tests passed by name and has a small summary at the end. ### junit2 This reporter outputs the standard JUnit spec in XML format and is recommended for all new users of JUnit. #### junit This legacy reporter outputs nonstandard JUnit XML and is provided only for backwards compatibility. ### progress This reporter is very condensed and gives you a `.`(pass), `f`(fail), or `*`(skip) character per test and a small summary at the end. ### json-rspec This reporter includes all information from the rspec runner. Unlike the json reporter this includes rspec specific details. ### html This reporter is the legacy RSpec HTML reporter, which is retained for backwards compatibility. The report generated is not aware of profiles or controls, and only contains unsorted test information. Most users should migrate to the `html2` reporter for more complete data. ### html2 This reporter is an improved HTML reporter that contains full data about the structure of the profile, controls, and tests. The generated report renders HTML code for viewing your tests in a browser. The `html2` reporter requires no configuration to function. However, two options–`alternate_css_file` and `alternate_js_file`–are available for customization. The options are set in the JSON-formatted configuration file that Chef InSpec consumes. For details, see [our configuration file documentation](../config/index). For example: ``` { "version": "1.2", "plugins": { "inspec-reporter-html2": { "alternate_js_file":"/var/www/js/my-javascript.js", "alternate_css_file":"/var/www/css/my-style.css" } } } ``` #### alternate_css_file Specifies the full path to the location of a CSS file that will be read and inlined into the HTML report. The default CSS will not be included. #### alternate_js_file Specifies the full path to the location of a JavaScript file that will be read and inlined into the HTML report. The default JavaScript will not be included. The JavaScript file should implement at least a `pageLoaded()` function, which will be called by the `onload` event of the HTML `body` element. Automate Reporter ----------------- The `automate` reporter type is a special reporter which will send its results over the network to [Chef Automate](../../automate/index). To use this reporter you must pass in the correct configuration via a json config `--config`. Example config: ``` { "reporter": { "automate" : { "stdout" : false, "url" : "https://YOUR_A2_URL/data-collector/v0/", "token" : "YOUR_A2_ADMIN_TOKEN", "insecure" : true, "node_name" : "inspec_test_node", "environment" : "prod" } } } ``` ### Mandatory fields #### stdout This will either suppress or show the automate report in the CLI screen on completion #### url This is your Automate 2 url. Append `data-collector/v0/` at the end. #### token This is your Automate 2 token. You can generate this token by navigating to the admin tab of A2 and then api keys. ### Optional fields #### insecure This will disable or enable the ssl check when accessing the Automate 2 instance. #### node_name This will be the node name which shows up in Automate. #### node_uuid This will be the node UUID which shows up in Chef Automate. Use a single static UUID per node for all your reports. You must specify a `node_uuid` in the Chef InSpec configuration file if running Chef InSpec outside of an audit cookbook or another environment where a `chef_guid` or `node_uuid` is already known to Chef InSpec. #### environment This will set the environment metadata for Automate. JSON-Automate Reporter ---------------------- The `json-automate` reporter is a special reporter that prepares the data format used by the Automate reporter. `json-automate` does not communicate on the network; rather it simply produces the JSON report format that Automate would be consuming. Notably, the report is based on the `json` reporter, with the following modifications: * Controls that appear in child profiles are de-duplicated by ID, merging up into the parent profile. * Child profiles are deleted, flattening the report. The `json-automate` reporter is primarily used for internal needs, but some users may find it useful if they want a JSON based reporter that merges controls. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/reporters/InSpec Configuration File ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/config.md) This documents the Chef InSpec configuration file format introduced in version 3.5 of InSpec and extended in later versions. Config File Location -------------------- By default, Chef InSpec looks for a config file in `~/.inspec/config.json`. Chef InSpec does not need a configuration file to run. You may also specify the location using `--config`. For example, to run the shell using a config file in `/etc/inspec`, use `inspec shell --config /etc/inspec/config.json`. Config File Format Versions --------------------------- Config files must contain a top-level key, `version`, which indicates the file format. This allows us to add new fields without breaking old installations. Version 1.1 ----------- ### Complete Example ``` { "version": "1.1", "cli_options":{ "color": "true" }, "credentials": { "ssh": { "my-target": { "host":"somewhere.there.com", "user":"bob" } } }, "reporter": { "automate" : { "stdout" : false, "url" : "https://YOUR_A2_URL/data-collector/v0/", "token" : "YOUR_A2_API_TOKEN", "insecure" : true, "node_name" : "inspec_test_node", "environment" : "prod" } } } ``` version Should have the value ‘1.1’. cli_options Any long-form command line option, without the leading dashes. credentials Train-transport-specific options. Store the options keyed first by transport name, then by a name you’ll use later on. The combination of transport name and your chosen name can be used in the `--target` option to `inspec exec`, as `--target transport-name://connection-name`. For example, if the config file contains: ``` { "credentials": { "winrm": { "myconn": { "user": "Administrator", "host": "prod01.east.example.com", "disable_sspi": true, "connection_retries": 10 } } } } ``` Then use `-t winrm://myconn` to connect to the host, with the given extra options. Each Train transport offers a variety of options. By using the credential set facility, you are able to easily set options that are not accessible via the Train URI. You may have as many credential sets in the config file as you require. If you use a target URI and the portion after the `://` cannot be matched to credential set name, Chef InSpec will send the URI to Train to be parsed as a Train URI. Thus, you can still do `ssh://someuser@myhost.com`. You can use a credential set, and then override individual options using command line options. Credential sets are intended to work hand-in-hand with the underlying credentials storage facility of the transport. For example, if you have a `~/.ssh/config` file specifying that the sally-key.pem file should be used with the host `somehost.com`, and you have a credential set that specifies that host, then when Train tries to connect to that host, the SSH library will automatically use the SSH config file to use the indicated key. ### reporter You may also set output (reporter) options in the config file. See the [Reporters Page](../reporters/index) for details. Version 1.2 ----------- Version 1.2 adds a top-level field, “plugins”. ### plugins Use the `plugins` top-level configuration field to provide configuration settings to plugins that you use with Chef InSpec. Refer to the documentation of the plugin you are using for details regarding what settings are available. To use this new feature, add a new top-level key in your config file named `plugins`. Then create a sub-key named for each plugin you wish to configure. Each plugin will have a key-value are that it may use as it sees fit - Chef InSpec does not specify the structure. Here is an example, using contrived plugins: ``` { "version":"1.2", "plugins": { "inspec-training-wheels": { "diameter": "4 inches" }, "inspec-input-secrets": { "security-tokens: [ "123456789". "<KEY>" ] } } } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/config/All Infra Resources =================== This reference describes each of the resources available to Chef Infra Client, including a list of actions, properties, and usage examples. Common Functionality -------------------- The properties and actions in this section apply to all resources. ### Actions The following actions may be used with any resource: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. #### Examples The following examples show how to use common actions in a recipe. **Use the :nothing action** ``` service 'memcached' do action :nothing end ``` ### Properties The following properties are common to every resource: `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Examples The following examples show how to use common properties in a recipe. **Use the ignore_failure common property** ``` gem_package 'syntax' do action :install ignore_failure true end ``` **Use the retries and retry_delay common properties** ``` service 'apache' do action [ :enable, :start ] retries 3 retry_delay 5 end ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. #### Properties The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Arguments The following arguments can be used with the `not_if` or `only_if` guard properties: `:user` Specify the user that a command will run as. For example: ``` not_if 'grep adam /etc/passwd', user: 'adam' ``` `:group` Specify the group that a command will run as. For example: ``` not_if 'grep adam /etc/passwd', group: 'adam' ``` `:environment` Specify a Hash of environment variables to be set. For example: ``` not_if 'grep adam /etc/passwd', environment: { 'HOME' => '/home/adam', } ``` `:cwd` Set the current working directory before running a command. For example: ``` not_if 'grep adam passwd', cwd: '/etc' ``` `:timeout` Set a timeout for a command. For example: ``` not_if 'sleep 10000', timeout: 10 ``` #### not_if Examples The following examples show how to use `not_if` as a condition in a recipe: **Create a file, but not if an attribute has a specific value** The following example shows how to use the `not_if` condition to create a file based on a template and using the presence of an attribute value on the node to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if { node['some_value'] } end ``` **Create a file with a Ruby block, but not if “/etc/passwd” exists** The following example shows how to use the `not_if` condition to create a file based on a template and then Ruby code to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if do ::File.exist?('/etc/passwd') end end ``` **Create a file with Ruby block that has curly braces, but not if “/etc/passwd” exists** The following example shows how to use the `not_if` condition to create a file based on a template and using a Ruby block (with curly braces) to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if { ::File.exist?('/etc/passwd') } end ``` **Create a file using a string, but not if “/etc/passwd” exists** The following example shows how to use the `not_if` condition to create a file based on a template and using a string to specify the condition: ``` template '/etc/some_config' do mode '0640' source 'some_config.erb' not_if 'some_app --check-config' end ``` #### only_if Examples The following examples show how to use `only_if` as a condition in a recipe: **Create a file, but only if an attribute has a specific value** The following example shows how to use the `only_if` condition to create a file based on a template and using the presence of an attribute on the node to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if { node['some_value'] } end ``` **Create a file with a Ruby block, but only if “/etc/passwd” does not exist** The following example shows how to use the `only_if` condition to create a file based on a template, and then use Ruby to specify a condition: ``` template '/etc/some_app/some_config' do mode '0640' source 'some_config.erb' only_if { ::File.exist?('/etc/some_app/') } end ``` **Create a file using a string, but only if “/etc/passwd” exists** The following example shows how to use the `only_if` condition to create a file based on a template and using a string to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if 'test -f /etc/passwd' end ``` ### Guard Interpreters Any resource that passes a string command may also specify the interpreter that will be used to evaluate that string command. This is done by using the `guard_interpreter` property to specify a **script**-based resource. #### Attributes The `guard_interpreter` property may be set to any of the following values: `:bash` Evaluates a string command using the **bash** resource. `:batch` Evaluates a string command using the **batch** resource. Default value (within a **batch** resource block): `:batch`. `:csh` Evaluates a string command using the **csh** resource. `:default` Default. Executes the default interpreter as identified by Chef Infra Client. `:perl` Evaluates a string command using the **perl** resource. `:powershell_script` Evaluates a string command using the **powershell_script** resource. Default value (within a **powershell_script** resource block): `:powershell_script`. `:python` Evaluates a string command using the **python** resource. `:ruby` Evaluates a string command using the **ruby** resource. #### Inheritance The `guard_interpreter` property is set to `:default` by default for the **bash**, **csh**, **perl**, **python**, and **ruby** resources. When the `guard_interpreter` property is set to `:default`, `not_if` or `only_if` guard statements **do not inherit** properties that are defined by the **script**-based resource. Warning The **batch** and **powershell_script** resources inherit properties by default. The `guard_interpreter` property is set to `:batch` or `:powershell_script` automatically when using a `not_if` or `only_if` guard statement within a **batch** or **powershell_script** resource, respectively. For example, the `not_if` guard statement in the following resource example **does not inherit** the `environment` property: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` and requires adding the `environment` property to the `not_if` guard statement so that it may use the `JAVA_HOME` path as part of its evaluation: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started', :environment => 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' end ``` To inherit properties, add the `guard_interpreter` property to the resource block and set it to the appropriate value: * `:bash` for **bash** * `:csh` for **csh** * `:perl` for **perl** * `:python` for **python** * `:ruby` for **ruby** For example, using the same example as from above, but this time adding the `guard_interpreter` property and setting it to `:bash`: ``` bash 'javatooling' do guard_interpreter :bash environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` The `not_if` statement now inherits the `environment` property and will use the `JAVA_HOME` path as part of its evaluation. #### Examples For example, the following code block will ensure the command is evaluated using the default interpreter as identified by Chef Infra Client: ``` resource 'name' do guard_interpreter :default # code end ``` ### Lazy Evaluation In some cases, the value for a property cannot be known until the execution phase of a Chef Infra Client run. In this situation, using lazy evaluation of property values can be helpful. Instead of a property being assigned a value, it may instead be assigned a code block. The syntax for using lazy evaluation is as follows: ``` property_name lazy { code_block } ``` where `lazy` is used to tell Chef Infra Client to evaluate the contents of the code block later on in the resource evaluation process (instead of immediately) and `{ code_block }` is arbitrary Ruby code that provides the value. For example, a resource that is **not** doing lazy evaluation: ``` template 'template_name' do # some properties path '/foo/bar' end ``` and a resource block that is doing lazy evaluation: ``` template 'template_name' do # some properties path lazy { ' some Ruby code ' } end ``` In the previous examples, the first resource uses the value `/foo/bar` and the second resource uses the value provided by the code block, as long as the contents of that code block are a valid resource property. The following example shows how to use lazy evaluation with template variables: ``` template '/tmp/canvey_island.txt' do source 'canvey_island.txt.erb' variables( lazy do { canvey_island: node.run_state['sea_power'] } end ) end ``` ### Notifications A notification is a property on a resource that listens to other resources in the resource collection and then takes actions based on the notification type (`notifies` or `subscribes`). #### Timers A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. #### Notifies A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` ##### Examples The following examples show how to use the `notifies` notification in a recipe. **Delay notifications** ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :delayed end ``` **Notify immediately** By default, notifications are `:delayed`, that is they are queued up as they are triggered, and then executed at the very end of a Chef Infra Client run. To run an action immediately, use `:immediately`: ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :immediately end ``` and then Chef Infra Client would immediately run the following: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing end ``` **Notify multiple resources** ``` template '/etc/chef/server.rb' do source 'server.rb.erb' owner 'root' group 'root' mode '0755' notifies :restart, 'service[chef-elasticsearch]', :delayed notifies :restart, 'service[chef-server]', :delayed end ``` **Notify in a specific order** To notify multiple resources, and then have these resources run in a certain order, do something like the following: ``` execute 'foo' do command '...' notifies :create, 'template[baz]', :immediately notifies :install, 'package[bar]', :immediately notifies :run, 'execute[final]', :immediately end template 'baz' do ... notifies :run, 'execute[restart_baz]', :immediately end package 'bar' execute 'restart_baz' execute 'final' do command '...' end ``` where the sequencing will be in the same order as the resources are listed in the recipe: `execute 'foo'`, `template 'baz'`, `execute [restart_baz]`, `package 'bar'`, and `execute 'final'`. **Reload a service** ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' notifies :reload, 'service[apache]', :immediately end ``` **Restart a service when a template is modified** ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :immediately end ``` **Send notifications to multiple resources** To send notifications to multiple resources, just use multiple attributes. Multiple attributes will get sent to the notified resources in the order specified. ``` template '/etc/netatalk/netatalk.conf' do notifies :restart, 'service[afpd]', :immediately notifies :restart, 'service[cnid]', :immediately end service 'afpd' service 'cnid' ``` **Execute a command using a template** The following example shows how to set up IPv4 packet forwarding using the **execute** resource to run a command named `forward_ipv4` that uses a template defined by the **template** resource: ``` execute 'forward_ipv4' do command 'echo > /proc/.../ipv4/ip_forward' action :nothing end template '/etc/file_name.conf' do source 'routing/file_name.conf.erb' notifies :run, 'execute[forward_ipv4]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[forward_ipv4]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. **Restart a service, and then notify a different service** The following example shows how start a service named `example_service` and immediately notify the Nginx service to restart. ``` service 'example_service' do action :start notifies :restart, 'service[nginx]', :immediately end ``` **Restart one service before restarting another** This example uses the `:before` notification to restart the `php-fpm` service before restarting `nginx`: ``` service 'nginx' do action :restart notifies :restart, 'service[php-fpm]', :before end ``` With the `:before` notification, the action specified for the `nginx` resource will not run until action has been taken on the notified resource (`php-fpm`). **Notify when a remote source changes** ``` remote_file '/tmp/couch.png' do source 'http://couchdb.apache.org/img/sketch.png' action :nothing end http_request 'HEAD http://couchdb.apache.org/img/sketch.png' do message '' url 'http://couchdb.apache.org/img/sketch.png' action :head if ::File.exist?('/tmp/couch.png') headers 'If-Modified-Since' => File.mtime('/tmp/couch.png').httpdate end notifies :create, 'remote_file[/tmp/couch.png]', :immediately end ``` #### Subscribes A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ##### Examples The following examples show how to use the `subscribes` notification in a recipe. **Prevent restart and reconfigure if configuration is broken** Use the `:nothing` action (common to all resources) to prevent the test from starting automatically, and then use the `subscribes` notification to run a configuration test when a change to the template is detected: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing subscribes :run, 'template[/etc/nagios3/configures-nagios.conf]', :immediately end ``` **Reload a service using a template** To reload a service that is based on a template, use the **template** and **service** resources together in the same recipe, similar to the following: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' end service 'apache' do action :enable subscribes :reload, 'template[/tmp/somefile]', :immediately end ``` where the `subscribes` notification is used to reload the service whenever the template is modified. **Stash a file in a data bag** The following example shows how to use the **ruby_block** resource to stash a BitTorrent file in a data bag so that it can be distributed to nodes in the organization. ``` # the following code sample comes from the ``seed`` recipe # in the following cookbook: https://github.com/mattray/bittorrent-cookbook ruby_block 'share the torrent file' do block do f = File.open(node['bittorrent']['torrent'], 'rb') #read the .torrent file and base64 encode it enc = Base64.encode64(f.read) data = { 'id' => bittorrent_item_id(node['bittorrent']['file']), 'seed' => node['ipaddress'], 'torrent' => enc, } item = Chef::DataBagItem.new item.data_bag('bittorrent') item.raw_data = data item.save end action :nothing subscribes :create, "bittorrent_torrent[#{node['bittorrent']['torrent']}]", :immediately end ``` ### Relative Paths The following relative paths can be used with any resource: `#{ENV['HOME']}` Use to return the `~` path in Linux and macOS or the `%HOMEPATH%` in Microsoft Windows. #### Examples ``` template "#{ENV['HOME']}/chef-getting-started.txt" do source 'chef-getting-started.txt.erb' mode '0755' end ``` ### Run in Compile Phase Chef Infra Client processes recipes in two phases: 1. First, each resource in the node object is identified and a resource collection is built. All recipes are loaded in a specific order, and then the actions specified within each of them are identified. This is also referred to as the “compile phase”. 2. Next, Chef Infra Client configures the system based on the order of the resources in the resource collection. Each resource then examines the node and performs the necessary steps to complete the action. This is also referred to as the “execution phase”. Typically, actions are processed during the execution phase of a Chef Infra Client run. However, sometimes it is necessary to run an action during the compile phase. For example, a resource can be configured to install a package during the compile phase to ensure that application is available to other resources during the execution phase. Note Use the **chef_gem** resource to install gems that are needed by Chef Infra Client during the execution phase. #### run_action Use `.run_action(:some_action)` at the end of a resource block to run the specified action during the compile phase. For example: ``` build_essential 'Install compilers' do action :nothing end.run_action(:install) ``` where `action` is set to `:nothing` to ensure the `run_action` is run during the compile phase and not later during the execution phase. This can be simplified by using the `compile_time` flag in Chef Infra Client 16 and later versions: ``` build_essential 'Install compilers' do compile_time true end ``` That flag both forces the resource to run at compile time and sets the converge action to `:nothing`. The following examples show when (and when not) to use `run_action`. **Using Custom Resources preferred to forcing to compile time** Compile time execution is often used to install gems before requiring them in recipe code. This is a poor pattern since gems may depend on native gems which may require installing compilers at compile time. ``` build_essential 'Install compilers' do compile_time true end chef_gem 'aws-dsk' do compile_time true end require 'aws-sdk' ``` A better strategy is to move the code, which requires the gem, into a custom resource. Since all the actions of custom resources run at converge time, this defers requiring the gem until later in the overall Chef Infra Client execution. Unified mode can also be used in the resource to eliminate compile/converge mode issues entirely: ``` unified_mode true action :run do build_essential 'Install compilers' chef_gem 'aws-sdk' require 'aws-sdk' end ``` **Download and parse a configuration file** A common use case is to download a configuration file, parse it, and then use the values in templates and to control other configuration. An important distinction to make is that the downloaded configuration file only exists in a temporary state to be used by the Chef Infra Client. It will not be used directly by the system or applications that are managed by the Chef Infra Client. To download and parse a JSON file and render it in a template, it makes sense to download the file during compile time: ``` # the remote_file is being downloaded to a temporary file remote_file "#{Chef::Config[:file_cache_path]}/users.json" do source "https://jsonplaceholder.typicode.com/users" compile_time true end # this parsing needs to happen after the remote_file is downloaded, but will # be executed at compile time. array = JSON.parse(IO.read("#{Chef::Config[:file_cache_path]}/users.json") # the `array.last["phone"]` expression here will also be evaluated at compile # time and must be lazied via wrapping the expresssion in `lazy {}` file "/tmp/phone_number.txt" do content array.last["phone"] end ``` This is considerably cleaner than the alternative of lazy evaluating both the parsing of the JSON and the rendering of the data into the file template, which will happen if the `remote_file` resource is not run at compile time: ``` # the execution of this is now deferred remote_file "#{Chef::Config[:file_cache_path]}/users.json" do source "https://jsonplaceholder.typicode.com/users" end # it is necessary due to lexical scoping issues to create this variable here array = nil # the parsing of the JSON is now deferred due to the ruby_block ruby_block "parse JSON" do block do array = JSON.parse(IO.read("#{Chef::Config[:file_cache_path]}/users.json") end end # the argument to the content property must now also be deferred file "/tmp/phone_number.txt" do content lazy { array.last["phone"] } end ``` This is an example of code that overuses deferred execution, uses more “lazy” evaluation, and is considerably harder to understand and write correctly. **Notifications will not work** Resources that are executed during the compile phase cannot notify other resources. For example: ``` execute 'ifconfig' package 'vim-enhanced' do compile_time true notifies :run, 'execute[ifconfig]', :immediately end ``` A better approach in this type of situation is to install the package before the resource collection is built to ensure that it is available to other resources later on. The best approach to this problem is to use `unified mode` which eliminates the compile time and converge time distinction, while allowing notifications to work correctly. **Resources that are forced to compile time by default** The `ohai_hint` and `hostname` resources run at compile time by default. This is due to the fact that later resources may consume the node attributes which are set by those resources leading to excessive use of `lazy` in subsequent resources (and similar issues to the `remote_file` example above). The `chef_gem` resource used to execute at compile time by default, but now we recommend that users move code that executes at compile time to custom resources. ### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. ### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. Resources --------- The following resources are built into the Chef Infra Client: alternatives resource --------------------- [alternatives resource page](alternatives/index) --- Use the **alternatives** resource to configure command alternatives in Linux using the alternatives or update-alternatives packages. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **alternatives** resource is: ``` alternatives 'name' do link String # default value: "/usr/bin/LINK_NAME" link_name String # default value: 'name' unless specified path String priority String, Integer action Symbol # defaults to :install if not specified end ``` where: * `alternatives` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `link`, `link_name`, `path`, and `priority` are the properties available to this resource. ### Actions --- The **alternatives** resource has the following actions: `:auto` Set an alternative up in automatic mode with the highest priority automatically selected. `:install` Install an alternative on the system including symlinks. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:refresh` Refresh alternatives. `:remove` Remove an alternative and all associated links. `:set` Set the symlink for an alternative. ### Properties --- The **alternatives** resource has the following properties: `link` **Ruby Type:** String | **Default Value:** `/usr/bin/LINK_NAME` The path to the alternatives link. `link_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the link to create. This will be the command you type on the command line such as `ruby` or `gcc`. `path` **Ruby Type:** String The absolute path to the original application binary such as `/usr/bin/ruby27`. `priority` **Ruby Type:** String, Integer The priority of the alternative. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **alternatives** resource in recipes: **Install an alternative**: ``` alternatives 'python install 2' do link_name 'python' path '/usr/bin/python2.7' priority 100 action :install end ``` **Set an alternative**: ``` alternatives 'python set version 3' do link_name 'python' path '/usr/bin/python3' action :set end ``` **Set the automatic alternative state**: ``` alternatives 'python auto' do link_name 'python' action :auto end ``` **Refresh an alternative**: ``` alternatives 'python refresh' do link_name 'python' action :refresh end ``` **Remove an alternative**: ``` alternatives 'python remove' do link_name 'python' path '/usr/bin/python3' action :remove end ``` apt_package resource --------------------- [apt_package resource page](apt_package/index) --- Use the **apt_package** resource to manage packages on Debian, Ubuntu, and other platforms that use the APT package system. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **apt_package** resource block manages a package on a node, typically by installing it. The simplest use of the **apt_package** resource is: `apt_package 'package_name'` which will install the named package using all of the default options and the default action of `:install`. The full syntax for all of the properties that are available to the **apt_package** resource is: ``` apt_package 'name' do default_release String options String, Array overwrite_config_files true, false # default value: false package_name String, Array response_file String response_file_variables Hash # default value: {} timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `apt_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `default_release`, `options`, `overwrite_config_files`, `package_name`, `response_file`, `response_file_variables`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **apt_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:lock` Locks the apt package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:unlock` Unlocks the apt package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **apt_package** resource has the following properties: `default_release` **Ruby Type:** String The default release. For example: `stable`. `options` **Ruby Type:** String, Array One (or more) additional options that are passed to the command. For example, common apt-get directives, such as `--no-install-recommends`. See the [apt-get man page](http://manpages.ubuntu.com/manpages/jammy/en/man8/apt-get.8.html) for the full list. `overwrite_config_files` **Ruby Type:** true, false | **Default Value:** `false` Overwrite existing configuration files with those supplied by the package, if prompted by APT. New in Chef Client 14.0 `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `response_file` **Ruby Type:** String The direct path to the file used to pre-seed a package. `response_file_variables` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of response file variables in the form of {‘VARIABLE’ => ‘VALUE’}. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **apt_package** resource in recipes: **Install a package using package manager**: ``` apt_package 'name of package' do action :install end ``` **Install a package without specifying the default action**: ``` apt_package 'name of package' ``` **Install multiple packages at once**: ``` apt_package %w(package1 package2 package3) ``` **Install without using recommend packages as a dependency**: ``` package 'apache2' do options '--no-install-recommends' end ``` apt_preference resource ------------------------ [apt_preference resource page](apt_preference/index) --- Use the **apt_preference** resource to create APT [preference files](https://wiki.debian.org/AptPreferences). Preference files are used to control which package versions and sources are prioritized during installation. **New in Chef Infra Client 13.3.** ### Syntax --- The full syntax for all of the properties that are available to the **apt_preference** resource is: ``` apt_preference 'name' do glob String package_name String # default value: 'name' unless specified pin String pin_priority String, Integer action Symbol # defaults to :add if not specified end ``` where: * `apt_preference` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `glob`, `package_name`, `pin`, and `pin_priority` are the properties available to this resource. ### Actions --- The **apt_preference** resource has the following actions: `:add` Creates a preferences file under `/etc/apt/preferences.d`. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes the preferences file, thus unpinning the package. ### Properties --- The **apt_preference** resource has the following properties: `glob` **Ruby Type:** String Pin by a `glob()` expression or with a regular expression surrounded by `/`. `package_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the package name if it differs from the resource block’s name. `pin` **Ruby Type:** String | `REQUIRED` The package version or repository to pin. `pin_priority` **Ruby Type:** String, Integer | `REQUIRED` Sets the Pin-Priority for a package. See <https://wiki.debian.org/AptPreferences> for more details. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **apt_preference** resource in recipes: **Pin libmysqlclient16 to a version 5.1.49-3**: ``` apt_preference 'libmysqlclient16' do pin 'version 5.1.49-3' pin_priority '700' end ``` Note: The `pin_priority` of `700` ensures that this version will be preferred over any other available versions. **Unpin a libmysqlclient16**: ``` apt_preference 'libmysqlclient16' do action :remove end ``` **Pin all packages to prefer the packages.dotdeb.org repository**: ``` apt_preference 'dotdeb' do glob '*' pin 'origin packages.dotdeb.org' pin_priority '700' end ``` apt_repository resource ------------------------ [apt_repository resource page](apt_repository/index) --- Use the **apt_repository** resource to specify additional APT repositories. Adding a new repository will update the APT package cache immediately. **New in Chef Infra Client 12.9.** ### Syntax --- The full syntax for all of the properties that are available to the **apt_repository** resource is: ``` apt_repository 'name' do arch String, false cache_rebuild true, false # default value: true components Array # default value: `main` if using a PPA repository. cookbook String, false deb_src true, false # default value: false distribution String, false # default value: The LSB codename of the node such as 'focal'. key String, Array, false # default value: [] key_proxy String, false keyserver String, false # default value: "keyserver.ubuntu.com" repo_name String # default value: 'name' unless specified trusted true, false # default value: false uri String action Symbol # defaults to :add if not specified end ``` where: * `apt_repository` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `arch`, `cache_rebuild`, `components`, `cookbook`, `deb_src`, `distribution`, `key`, `key_proxy`, `keyserver`, `repo_name`, `trusted`, and `uri` are the properties available to this resource. ### Actions --- The **apt_repository** resource has the following actions: `:add` Creates a repository file at `/etc/apt/sources.list.d/` and builds the repository listing. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes the repository listing. ### Properties --- The **apt_repository** resource has the following properties: `arch` **Ruby Type:** String, false Constrain packages to a particular CPU architecture such as `i386` or `amd64`. `cache_rebuild` **Ruby Type:** true, false | **Default Value:** `true` Determines whether to rebuild the APT package cache. `components` **Ruby Type:** Array | **Default Value:** ``main` if using a PPA repository.` Package groupings, such as ‘main’ and ‘stable’. `cookbook` **Ruby Type:** String, false If key should be a cookbook_file, specify a cookbook where the key is located for files/default. Default value is nil, so it will use the cookbook where the resource is used. `deb_src` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not to add the repository as a source repo as well. `distribution` **Ruby Type:** String, false | **Default Value:** `The LSB codename of the node such as 'focal'.` Usually a distribution’s codename, such as `xenial`, `bionic`, or `focal`. `key` **Ruby Type:** String, Array, false | **Default Value:** `[]` If a keyserver is provided, this is assumed to be the fingerprint; otherwise it can be either the URI of GPG key for the repo, or a cookbook_file. `key_proxy` **Ruby Type:** String, false If set, a specified proxy is passed to GPG via `http-proxy=`. `keyserver` **Ruby Type:** String, false | **Default Value:** `keyserver.ubuntu.com` The GPG keyserver where the key for the repo should be retrieved. `repo_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the repository name if it differs from the resource block’s name. The value of this setting must not contain spaces. New in Chef Client 14.1 `trusted` **Ruby Type:** true, false | **Default Value:** `false` Determines whether you should treat all packages from this repository as authenticated regardless of signature. `uri` **Ruby Type:** String The base of the Debian distribution. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **apt_repository** resource in recipes: **Add repository with basic settings**: ``` apt_repository 'nginx' do uri 'http://nginx.org/packages/ubuntu/' components ['nginx'] end ``` **Enable Ubuntu multiverse repositories**: ``` apt_repository 'security-ubuntu-multiverse' do uri 'http://security.ubuntu.com/ubuntu' distribution 'xenial-security' components ['multiverse'] deb_src true end ``` **Add the Nginx PPA, autodetect the key and repository url**: ``` apt_repository 'nginx-php' do uri 'ppa:nginx/stable' end ``` **Add the JuJu PPA, grab the key from the Ubuntu keyserver, and add source repo**: ``` apt_repository 'juju' do uri 'ppa:juju/stable' components ['main'] distribution 'xenial' key 'C8068B11' action :add deb_src true end ``` **Add repository that requires multiple keys to authenticate packages**: ``` apt_repository 'rundeck' do uri 'https://dl.bintray.com/rundeck/rundeck-deb' distribution '/' key ['379CE192D401AB61', 'http://rundeck.org/keys/BUILD-GPG-KEY-Rundeck.org.key'] keyserver 'keyserver.ubuntu.com' action :add end ``` **Add the Cloudera Repo of CDH4 packages for Ubuntu 16.04 on AMD64**: ``` apt_repository 'cloudera' do uri 'http://archive.cloudera.com/cdh4/ubuntu/xenial/amd64/cdh' arch 'amd64' distribution 'xenial-cdh4' components ['contrib'] key 'http://archive.cloudera.com/debian/archive.key' end ``` **Remove a repository from the list**: ``` apt_repository 'zenoss' do action :remove end ``` apt_update resource -------------------- [apt_update resource page](apt_update/index) --- Use the **apt_update** resource to manage APT repository updates on Debian and Ubuntu platforms. **New in Chef Infra Client 12.7.** ### Syntax --- The full syntax for all of the properties that are available to the **apt_update** resource is: ``` apt_update 'name' do frequency Integer # default value: 86400 action Symbol # defaults to :periodic if not specified end ``` where: * `apt_update` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `frequency` is the property available to this resource. ### Nameless This resource can be **nameless**. Add the resource itself to your recipe to get the default behavior: ``` apt_update ``` will behave the same as: ``` apt_update 'update' ``` ### Actions --- The **apt_update** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:periodic` Update the Apt repository at the interval specified by the `frequency` property. (default) `:update` Update the Apt repository at the start of a Chef Infra Client run. ### Properties --- The **apt_update** resource has the following properties: `frequency` **Ruby Type:** Integer | **Default Value:** `86400` Determines how frequently (in seconds) APT repository updates are made. Use this property when the `:periodic` action is specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **apt_update** resource in recipes: **Update the Apt repository at a specified interval**: ``` apt_update 'all platforms' do frequency 86400 action :periodic end ``` **Update the Apt repository at the start of a Chef Infra Client run**: ``` apt_update 'update' ``` archive_file resource ---------------------- [archive_file resource page](archive_file/index) --- Use the **archive_file** resource to extract archive files to disk. This resource uses the libarchive library to extract multiple archive formats including tar, gzip, bzip, and zip formats. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **archive_file** resource is: ``` archive_file 'name' do destination String group String mode String, Integer # default value: "'755'" options Array, Symbol overwrite true, false, auto # default value: false owner String path String # default value: 'name' unless specified strip_components Integer # default value: 0 action Symbol # defaults to :extract if not specified end ``` where: * `archive_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `destination`, `group`, `mode`, `options`, `overwrite`, `owner`, `path`, and `strip_components` are the properties available to this resource. ### Actions --- The **archive_file** resource has the following actions: `:extract` Extract and archive file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **archive_file** resource has the following properties: `destination` **Ruby Type:** String | `REQUIRED` The file path to extract the archive file to. `group` **Ruby Type:** String The group of the extracted files. `mode` **Ruby Type:** String, Integer | **Default Value:** `'755'` The mode of the extracted files. Integer values are deprecated as octal values (ex. 0755) would not be interpreted correctly. `options` **Ruby Type:** Array, Symbol | **Default Value:** `lazy default` An array of symbols representing extraction flags. Example: `:no_overwrite` to prevent overwriting files on disk. By default, this properly sets `:time` which preserves the modification timestamps of files in the archive when writing them to disk. `overwrite` **Ruby Type:** true, false, auto | **Default Value:** `false` Should the resource overwrite the destination file contents if they already exist? If set to `:auto` the date stamp of files within the archive will be compared to those on disk and disk contents will be overwritten if they differ. This may cause unintended consequences if disk date stamps are changed between runs, which will result in the files being overwritten during each client run. Make sure to properly test any change to this property. `owner` **Ruby Type:** String The owner of the extracted files. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the file path to the archive to extract if it differs from the resource block’s name. `strip_components` **Ruby Type:** Integer | **Default Value:** `0` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. This behaves similarly to tar’s –strip-components command line argument. New in Chef Infra Client 17.5 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **archive_file** resource in recipes: **Extract a zip file to a specified directory**: ``` archive_file 'Precompiled.zip' do path '/tmp/Precompiled.zip' destination '/srv/files' end ``` **Set specific permissions on the extracted files**: ``` archive_file 'Precompiled.zip' do owner 'tsmith' group 'staff' mode '700' path '/tmp/Precompiled.zip' destination '/srv/files' end ``` bash resource ------------- [bash resource page](bash/index) --- Use the **bash** resource to execute scripts using the Bash interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **bash** resource block executes scripts using Bash: ``` bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` where: * `cwd` specifies the directory from which the command is run * `code` specifies the command to run The full syntax for all of the properties that are available to the **bash** resource is: ``` bash 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `bash` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **bash** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a script. ### Properties --- The **bash** resource has the following properties: `code` **Ruby Type:** String | `REQUIRED` A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **bash** resource in recipes: Use a named provider to run a script ``` bash 'install_something' do user 'root' cwd '/tmp' code <<-EOH wget http://www.example.com/tarball.tar.gz tar -zxf tarball.tar.gz cd tarball ./configure make make install EOH end ``` Install a file from a remote location using bash The following is an example of how to install the `foo123` module for Nginx. This module adds shell-style functionality to an Nginx configuration file and does the following: * Declares three variables * Gets the Nginx file from a remote location * Installs the file using Bash to the path specified by the `src_filepath` variable ``` # the following code sample is similar to the ``upload_progress_module`` # recipe in the ``nginx`` cookbook: # https://github.com/chef-cookbooks/nginx src_filename = "foo123-nginx-module-v#{ node['nginx']['foo123']['version'] }.tar.gz" src_filepath = "#{Chef::Config['file_cache_path']}/#{src_filename}" extract_path = "#{ Chef::Config['file_cache_path'] }/nginx_foo123_module/#{ node['nginx']['foo123']['checksum'] }" remote_file 'src_filepath' do source node['nginx']['foo123']['url'] checksum node['nginx']['foo123']['checksum'] owner 'root' group 'root' mode '0755' end bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` Install an application from git using bash The following example shows how Bash can be used to install a plug-in for rbenv named `ruby-build`, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which `ruby-build` is located, and then runs a command. ``` git "#{Chef::Config[:file_cache_path]}/ruby-build" do repository 'git://github.com/sstephenson/ruby-build.git' revision 'master' action :sync end bash 'install_ruby_build' do cwd "#{Chef::Config[:file_cache_path]}/ruby-build" user 'rbenv' group 'rbenv' code <<-EOH ./install.sh EOH environment 'PREFIX' => '/usr/local' end ``` To read more about `ruby-build`, see here: <https://github.com/sstephenson/ruby-build>. Store certain settings The following recipe shows how an attributes file can be used to store certain settings. An attributes file is located in the `attributes/` directory in the same cookbook as the recipe which calls the attributes file. In this example, the attributes file specifies certain settings for Python that are then used across all nodes against which this recipe will run. Python packages have versions, installation directories, URLs, and checksum files. An attributes file that exists to support this type of recipe would include settings like the following: ``` default['python']['version'] = '2.7.1' if python['install_method'] == 'package' default['python']['prefix_dir'] = '/usr' else default['python']['prefix_dir'] = '/usr/local' end default['python']['url'] = 'http://www.python.org/ftp/python' default['python']['checksum'] = '80e387...85fd61' ``` and then the methods in the recipe may refer to these values. A recipe that is used to install Python will need to do the following: * Identify each package to be installed (implied in this example, not shown) * Define variables for the package `version` and the `install_path` * Get the package from a remote location, but only if the package does not already exist on the target system * Use the **bash** resource to install the package on the node, but only when the package is not already installed ``` # the following code sample comes from the ``oc-nginx`` cookbook on |github|: https://github.com/cookbooks/oc-nginx version = node['python']['version'] install_path = "#{node['python']['prefix_dir']}/lib/python#{version.split(/(^\d+\.\d+)/)[1]}" remote_file "#{Chef::Config[:file_cache_path]}/Python-#{version}.tar.bz2" do source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2" checksum node['python']['checksum'] mode '0755' not_if { ::File.exist?(install_path) } end bash 'build-and-install-python' do cwd Chef::Config[:file_cache_path] code <<-EOF tar -jxvf Python-#{version}.tar.bz2 (cd Python-#{version} && ./configure #{configure_options}) (cd Python-#{version} && make && make install) EOF not_if { ::File.exist?(install_path) } end ``` batch resource -------------- [batch resource page](batch/index) --- Use the **batch** resource to execute a batch script using the cmd.exe interpreter on Windows. The batch resource creates and executes a temporary file (similar to how the script resource behaves), rather than running the command inline. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **batch** resource block executes a batch script using the cmd.exe interpreter: ``` batch 'echo some env vars' do code <<-EOH echo %TEMP% echo %SYSTEMDRIVE% echo %PATH% echo %WINDIR% EOH end ``` The full syntax for all of the properties that are available to the **batch** resource is: ``` batch 'name' do architecture Symbol code String command String, Array creates String cwd String flags String group String, Integer guard_interpreter Symbol interpreter String returns Integer, Array timeout Integer, Float user String password String domain String action Symbol # defaults to :run if not specified end ``` where: * `batch` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `architecture`, `code`, `command`, `creates`, `cwd`, `flags`, `group`, `guard_interpreter`, `interpreter`, `returns`, `timeout`, `user`, `password` and `domain` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **batch** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Run a batch file. ### Properties --- The **batch** resource has the following properties: `architecture` **Ruby Type:** Symbol The architecture of the process under which a script is executed. If a value is not provided, Chef Infra Client defaults to the correct value for the architecture, as determined by Ohai. An exception is raised when anything other than `:i386` is specified for a 32-bit process. Possible values: `:i386` (for 32-bit processes) and `:x86_64` (for 64-bit processes). `code` **Ruby Type:** String | `REQUIRED` A quoted string of code to be executed. `command` **Ruby Type:** String, Array The name of the command to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `guard_interpreter` **Ruby Type:** Symbol | **Default Value:** `:batch` When this property is set to `:batch`, the 64-bit version of the cmd.exe shell will be used to evaluate strings values for the `not_if` and `only_if` properties. Set this value to `:default` to use the 32-bit version of the cmd.exe shell. `interpreter` **Ruby Type:** String The script interpreter to use during code execution. Changing the default value of this property is not supported. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. domainuser or [<EMAIL>](mailto:<EMAIL>.domain.com) via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified. `password` **Ruby Type:** String *Windows only*: The password of the user specified by the user property. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. `domain` **Ruby Type:** String *Windows only*: The domain of the user user specified by the user property. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef Infra Client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **batch** resource in recipes: Unzip a file, and then move it To run a batch file that unzips and then moves Ruby, do something like: ``` batch 'unzip_and_move_ruby' do code <<-EOH 7z.exe x #{Chef::Config[:file_cache_path]}/ruby-1.8.7-p352-i386-mingw32.7z -oC:\\source -r -y xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y EOH end batch 'echo some env vars' do code <<-EOH echo %TEMP% echo %SYSTEMDRIVE% echo %PATH% echo %WINDIR% EOH end ``` or: ``` batch 'unzip_and_move_ruby' do code <<-EOH 7z.exe x #{Chef::Config[:file_cache_path]}/ruby-1.8.7-p352-i386-mingw32.7z -oC:\\source -r -y xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y EOH end batch 'echo some env vars' do code 'echo %TEMP%\\necho %SYSTEMDRIVE%\\necho %PATH%\\necho %WINDIR%' end ``` Run a command as an alternate user *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] domain "domain" user "username" password "password" end # Passing username = 'domain-name\\username'. No domain is passed batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "domain-name\\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end ``` bff_package resource --------------------- [bff_package resource page](bff_package/index) --- Use the **bff_package** resource to manage packages for the AIX platform using the installp utility. When a package is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. Note A Backup File Format (BFF) package may not have a `.bff` file extension. Chef Infra Client will still identify the correct provider to use based on the platform, regardless of the file extension. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- The full syntax for all of the properties that are available to the **bff_package** resource is: ``` bff_package 'name' do options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `bff_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **bff_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. ### Properties --- The **bff_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String Required. The path to a package in the local file system. The AIX platform requires `source` to be a local file system path because `installp` does not retrieve packages using HTTP or FTP. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **bff_package** resource in recipes: The **bff_package** resource is the default package provider on the AIX platform. The base **package** resource may be used, and then when the platform is AIX, Chef Infra Client will identify the correct package provider. The following examples show how to install part of the IBM XL C/C++ compiler. **Installing using the base package resource** ``` package 'xlccmp.13.1.0' do source '/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0' action :install end ``` **Installing using the bff_package resource** ``` bff_package 'xlccmp.13.1.0' do source '/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0' action :install end ``` breakpoint resource ------------------- [breakpoint resource page](breakpoint/index) --- Use the **breakpoint** resource to add breakpoints to recipes. Run the chef-shell in Chef Infra Client mode, and then use those breakpoints to debug recipes. Breakpoints are ignored by the chef-client during an actual chef-client run. That said, breakpoints are typically used to debug recipes only when running them in a non-production environment, after which they are removed from those recipes before the parent cookbook is uploaded to the Chef server. **New in Chef Infra Client 12.0.** ### Syntax --- The full syntax for all of the properties that are available to the **breakpoint** resource is: ``` breakpoint 'name' do action Symbol # defaults to :break if not specified end ``` where: * `breakpoint` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. ### Actions --- The **breakpoint** resource has the following actions: `:break` Add a breakpoint for use with chef-shell (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- This resource does not have any properties. ### Debug Recipes with chef-shell chef-shell is a recipe debugging tool that allows the use of breakpoints within recipes. chef-shell runs as an Interactive Ruby (IRb) session. chef-shell supports both recipe and attribute file syntax, as well as interactive debugging features. #### Modes chef-shell is tool that is run using an Interactive Ruby (IRb) session. chef-shell currently supports recipe and attribute file syntax, as well as interactive debugging features. chef-shell has three run modes: | Mode | Description | | --- | --- | | Standalone | Default. No cookbooks are loaded, and the run-list is empty. | | Solo | chef-shell acts as a Chef Solo Client. It attempts to load the chef-solo configuration file at `~/.chef/config.rb` and any JSON attributes passed. If the JSON attributes set a run-list, it will be honored. Cookbooks will be loaded in the same way that chef-solo loads them. chef-solo mode is activated with the `-s` or `--solo` command line option, and JSON attributes are specified in the same way as for chef-solo, with `-j /path/to/chef-solo.json`. | | Client | chef-shell acts as a Chef Infra Client. During startup, it reads the Chef Infra Client configuration file from `~/.chef/client.rb` and contacts the Chef Infra Server to get the node's run_list, attributes, and cookbooks. Chef Infra Client mode is activated with the `-z` or `--client` options. You can also specify the configuration file with `-c CONFIG` and the server URL with `-S SERVER_URL`. | #### Configure chef-shell determines which configuration file to load based on the following: 1. If a configuration file is specified using the `-c` option, chef-shell will use the specified configuration file 2. If a NAMED_CONF is given, chef-shell will load ~/.chef/NAMED_CONF/chef_shell.rb 3. If no NAMED_CONF is given chef-shell will load ~/.chef/chef_shell.rb if it exists 4. If no chef_shell.rb can be found, chef-shell falls back to load: * /etc/chef/client.rb if -z option is given. * /etc/chef/solo.rb if –solo-legacy-mode option is given. * .chef/config.rb if -s option is given. * .chef/knife.rb if -s option is given. ##### chef-shell.rb The chef-shell.rb file can be used to configure chef-shell in the same way as the client.rb file is used to configure Chef Infra Client. For example, to configure chef-shell to authenticate to the Chef Infra Server, copy the `node_name`, `client_key`, and `chef_server_url` settings from the config.rb file: ``` node_name 'your-knife-clientname' client_key File.expand_path('~/.chef/my-client.pem') chef_server_url 'https://api.opscode.com/organizations/myorg' ``` and then add them to the chef-shell.rb file. Other configuration possibilities include disabling Ohai plugins (which will speed up the chef-shell boot process) or including arbitrary Ruby code in the chef-shell.rb file. ##### Run as a Chef Infra Client By default, chef-shell loads in standalone mode and does not connect to the Chef Infra Server. The chef-shell can be run as a Chef Infra Client to verify functionality that is only available when Chef Infra Client connects to the Chef Infra Server, such as search functionality or accessing data stored in data bags. chef-shell can use the same credentials as knife when connecting to a Chef Infra Server. Make sure that the settings in chef-shell.rb are the same as those in config.rb, and then use the `-z` option as part of the command. For example: ``` chef-shell -z ``` #### Manage When chef-shell is configured to access a Chef Infra Server, chef-shell can list, show, search for and edit cookbooks, clients, nodes, roles, environments, policyfiles, and data bags. The syntax for managing objects on the Chef Infra Server is as follows: ``` chef-shell -z named_configuration ``` Where: * `named_configuration` is an existing configuration file in `~/.chef/named_configuration/chef_shell.rb`, such as `production`, `staging`, or `test`. Once in chef-shell, commands can be run against objects as follows: ``` chef (preprod) > items.command ``` Where: * `items` is the type of item to search for: `cookbooks`, `clients`, `nodes`, `roles`, `environments` or a data bag. * `command` is the command: `list`, `show`, `find`, or `edit`. For example, to list all of the nodes in a configuration named “preprod”, enter: ``` chef (preprod) > nodes.list ``` Which will return something similar to: ``` => [node[i-f09a939b], node[i-049a936f], node[i-eaaaa581], node[i-9154b1fb], node[i-6a213101], node[i-c2687aa9], node[i-7abeaa11], node[i-4eb8ac25], node[i-9a2030f1], node[i-a06875cb], node[i-145f457f], node[i-e032398b], node[i-dc8c98b7], node[i-6afdf401], node[i-f49b119c], node[i-5abfab31], node[i-78b8ac13], node[i-d99678b3], node[i-02322269], node[i-feb4a695], node[i-9e2232f5], node[i-6e213105], node[i-cdde3ba7], node[i-e8bfb083], node[i-743c2c1f], node[i-2eaca345], node[i-aa7f74c1], node[i-72fdf419], node[i-140e1e7f], node[i-f9d43193], node[i-bd2dc8d7], node[i-8e7f70e5], node[i-78f2e213], node[i-962232fd], node[i-4c322227], node[i-922232f9], node[i-c02728ab], node[i-f06c7b9b]] ``` The `list` command can take a code block, which will applied (but not saved), to each object that is returned from the server. For example: ``` chef (preprod) > nodes.list {|n| puts "#{n.name}: #{n.run_list}" } ``` will return something similar to: ``` => i-f09a939b: role[lb], role[preprod], recipe[aws] i-049a936f: role[lb], role[preprod], recipe[aws] i-9154b1fb: recipe[erlang], role[base], role[couchdb], role[preprod], i-6a213101: role[chef], role[preprod] # more... ``` The `show` command can be used to display a specific node. For example: ``` chef (preprod) > load_balancer = nodes.show('i-f09a939b') ``` will return something similar to: ``` => node[i-f09a939b] ``` Or: ``` chef (preprod) > load_balancer.ec2.public_hostname ``` will return something similar to: ``` => "ec2-111-22-333-44.compute-1.amazonaws.com" ``` The `find` command can be used to search the Chef Infra Server from the chef-shell. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') ``` You can also format the results with a code block. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } and nil ``` will return something similar to: ``` => ["ami-f8927a91", "ami-f8927a91", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1" # and more... ``` Or: ``` chef (preprod) > amis = nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } chef (preprod) > puts amis.uniq.sort ``` will return something similar to: ``` => ami-4b4ba522 ami-a89870c1 ami-eef61587 ami-f8927a91 ``` #### Use Breakpoints chef-shell allows the current position in a run-list to be manipulated during a Chef Infra Client run. Add breakpoints to a recipe to take advantage of this functionality. ##### Step Through Run-list To explore how using the **breakpoint** to manually step through a Chef Infra Client run, create a simple recipe in chef-shell: ``` chef > recipe_mode chef:recipe > echo off chef:recipe > file "/tmp/before-breakpoint" chef:recipe > breakpoint "foo" chef:recipe > file "/tmp/after-breakpoint" ``` and then run Chef Infra Client: ``` chef:recipe > run_chef [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:17:49 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint ``` Chef Infra Client ran the first resource before the breakpoint (`file[/tmp/before-breakpoint]`), but then stopped after execution. Chef Infra Client attempted to name the breakpoint after its position in the source file, but Chef Infra Client was confused because the resource was entered interactively. From here, chef-shell can resume the interrupted Chef Infra Client run: ``` chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:27:08 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` A quick view of the `/tmp` directory shows that the following files were created: ``` after-breakpoint before-breakpoint ``` You can rewind and step through a Chef Infra Client run: ``` chef:recipe > Chef::Log.level = :debug # debug logging won't turn on automatically in this case => :debug chef:recipe > chef_run.rewind => 0 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File => 1 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint => 2 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File => 3 ``` From the output, the rewound run-list is shown, but when the resources are executed again, they will repeat their checks for the existence of files. If they exist, Chef Infra Client will skip creating them. If the files are deleted, then: ``` chef:recipe > ls("/tmp").grep(/breakpoint/).each {|f| rm "/tmp/#{f}" } => ["after-breakpoint", "before-breakpoint"] ``` Rewind, and then resume your Chef Infra Client run to get the expected results: ``` chef:recipe > chef_run.rewind chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:48:56 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:49:20 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` ##### Debug Existing Recipe chef-shell can be used to debug existing recipes. The recipe first needs to be added to a run-list for the node, so that it is cached when starting chef-shell and then used for debugging. chef-shell will report which recipes are being cached when it is started: ``` loading configuration: none (standalone session) Session type: standalone Loading.............done. Welcome to the chef-shell 15.8.23 For usage see https://docs.chef.io/chef_shell.html run `help' for help, `exit' or ^D to quit. chef (15.8.23)``` To just load one recipe from the run-list, go into the recipe and use the `include_recipe` command. For example: ``` chef > recipe_mode chef:recipe > include_recipe "getting-started" => [#< Chef::Recipe:0x10256f9e8 @cookbook_name="getting-started", ... output truncated ... ``` To load all of the recipes from a run-list, use code similar to the following: ``` node.run_list.expand(node.chef_environment).recipes.each do |r| include_recipe r end ``` After the recipes that are to be debugged have been loaded, use the `run_chef` command to run them. ##### Advanced Debugging In chef-shell, it is possible to get verbose debugging using the tracing feature in Interactive Ruby (IRb). chef-shell provides a shortcut for turning tracing on and off. For example: ``` chef > tracing on tracing is on => nil chef ``` and: ``` chef > tracing off #0:(irb):2:Object:-: tracing off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:109:Shell::Extensions::ObjectCoreExtensions:>: def off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:110:Shell::Extensions::ObjectCoreExtensions:-: :off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:111:Shell::Extensions::ObjectCoreExtensions:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:272:main:>: def tracing(on_or_off) #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:273:main:-: conf.use_tracer = on_or_off.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:162:Shell::Extensions::Symbol:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:163:Shell::Extensions::Symbol:-: to_s.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:149:Shell::Extensions::String:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:150:Shell::Extensions::String:-: case self #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:154:Shell::Extensions::String:-: false #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:158:Shell::Extensions::String:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:164:Shell::Extensions::Symbol:<: end tracing is off => nil chef ``` #### Debug Examples The following examples show how to use chef-shell. ##### "Hello World" This example shows how to run chef-shell in standalone mode. (For chef-solo or Chef Infra Client modes, you would need to run chef-shell using the `-s` or `-z` command line options, and then take into consideration the necessary configuration settings.) When Chef Infra Client is installed using RubyGems or a package manager, chef-shell should already be installed. When Chef Infra Client is run from a git clone, it will be located in `chef/bin/chef shell`. To start chef-shell, just run it without any options. You’ll see the loading message, then the banner, and then the chef-shell prompt: ``` bin/chef-shell loading configuration: none (standalone session) Session type: standalone Loading.............done. Welcome to the chef-shell 15.8.23 For usage see https://docs.chef.io/chef_shell.html run `help' for help, `exit' or ^D to quit. chef (15.8.23)``` (Use the help command to print a list of supported commands.) Use the recipe_mode command to switch to recipe context: ``` chef > recipe_mode chef:recipe_mode ``` Typing is evaluated in the same context as recipes. Create a file resource: ``` chef:recipe_mode > file "/tmp/ohai2u_shef" => #< Chef::Resource::File:0x1b691ac @enclosing_provider=nil, @resource_name=:file, @before=nil, @supports={}, @backup=5, @allowed_actions=[:nothing, :create, :delete, :touch, :create_if_missing], @only_if=nil, @noop=nil, @collection=#< Chef::ResourceCollection:0x1b9926c @insert_after_idx=nil, @resources_by_name={"file[/tmp/ohai2u_shef]"=>0}, @resources=[#< Chef::Resource::File:0x1b691ac ...>]>, @updated=false, @provider=nil, @node=< Chef::Node:0xdeeaae @name="eigenstate.local">, @recipe_name=nil, @not_if=nil, @name="/tmp/ohai2u_shef", @action="create", @path="/tmp/ohai2u_shef", @source_line="/Users/username/ruby/chef/chef/(irb#1) line 1", @params={}, @actions={}, @cookbook_name=nil, @ignore_failure=false``` (The previous example was formatted for presentation.) At this point, chef-shell has created the resource and put it in the run-list, but not yet created the file. To initiate a Chef Infra Client run, use the `run_chef` command: ``` chef:recipe_mode > run_chef [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: Processing file[/tmp/ohai2u_shef] [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File [Fri, 15 Jan 2020 10:42:47 -0800] INFO: Creating file[/tmp/ohai2u_shef] at /tmp/ohai2u_shef => true ``` chef-shell can also switch to the same context as attribute files. Set an attribute with the following syntax: ``` chef:recipe_mode > attributes_mode chef:attributes > default[:hello] = "ohai2u-again" => "ohai2u-again" chef:attributes ``` Switch back to recipe_mode context and use the attributes: ``` chef:attributes > recipe_mode => :attributes chef:recipe_mode > file "/tmp/#{node.hello}" ``` Now, run Chef Infra Client again: ``` chef:recipe_mode > run_chef [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u_shef] [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u-again] [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u-again] using Chef::Provider::File [Fri, 15 Jan 2020 10:53:22 -0800] INFO: Creating file[/tmp/ohai2u-again] at /tmp/ohai2u-again => true chef:recipe_mode ``` Because the first resource (`file[/tmp/ohai2u_shef]`) is still in the run-list, it gets executed again. And because that file already exists, Chef Infra Client doesn’t attempt to re-create it. Finally, the files were created using the `ls` method: ``` chef:recipe_mode > ls("/tmp").grep(/ohai/) => ["ohai2u-again", "ohai2u_shef"] Shell Tutorial ``` ##### Get Specific Nodes To get a list of nodes using a recipe named `postfix` use `search(:node,"recipe:postfix")`. To get a list of nodes using a sub-recipe named `delivery`, use chef-shell. For example: ``` search(:node, 'recipes:postfix\:\:delivery') ``` Note Single (' ‘) vs. double (" “) is important. This is because a backslash () needs to be included in the string, instead of having Ruby interpret it as an escape. ### Examples --- The following examples demonstrate various approaches for using the **breakpoint** resource in recipes: **A recipe without a breakpoint** ``` yum_key node['yum']['elrepo']['key'] do url node['yum']['elrepo']['key_url'] action :add end yum_repository 'elrepo' do description 'ELRepo.org Community Enterprise Linux Extras Repository' key node['yum']['elrepo']['key'] mirrorlist node['yum']['elrepo']['url'] includepkgs node['yum']['elrepo']['includepkgs'] exclude node['yum']['elrepo']['exclude'] action :create end ``` **The same recipe with breakpoints** In the following example, the name of each breakpoint is an arbitrary string. ``` breakpoint "before yum_key node['yum']['repo_name']['key']" do action :break end yum_key node['yum']['repo_name']['key'] do url node['yum']['repo_name']['key_url'] action :add end breakpoint "after yum_key node['yum']['repo_name']['key']" do action :break end breakpoint "before yum_repository 'repo_name'" do action :break end yum_repository 'repo_name' do description 'description' key node['yum']['repo_name']['key'] mirrorlist node['yum']['repo_name']['url'] includepkgs node['yum']['repo_name']['includepkgs'] exclude node['yum']['repo_name']['exclude'] action :create end breakpoint "after yum_repository 'repo_name'" do action :break end ``` In the previous examples, the names are used to indicate if the breakpoint is before or after a resource and also to specify which resource it is before or after. build_essential resource ------------------------- [build_essential resource page](build_essential/index) --- Use the **build_essential** resource to install the packages required for compiling C software from source. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **build_essential** resource is: ``` build_essential 'name' do raise_if_unsupported true, false # default value: false action Symbol # defaults to :install if not specified end ``` where: * `build_essential` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `raise_if_unsupported` is the property available to this resource. ### Nameless This resource can be **nameless**. Add the resource itself to your recipe to get the default behavior: ``` build_essential ``` will behave the same as: ``` build_essential 'install tools' ``` ### Actions --- The **build_essential** resource has the following actions: `:install` Install build essential packages. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:upgrade` Upgrade the Xcode CLI Tools on macOS hosts. **New in Chef Infra Client 16** ### Properties --- The **build_essential** resource has the following properties: `raise_if_unsupported` **Ruby Type:** true, false | **Default Value:** `false` Raise a hard error on platforms where this resource is unsupported. New in Chef Infra Client 15.5 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **build_essential** resource in recipes: **Install compilation packages**: ``` build_essential ``` **Install compilation packages during the compilation phase**: ``` build_essential 'Install compilation tools' do compile_time true end ``` **Upgrade compilation packages on macOS systems**: ``` build_essential 'Install compilation tools' do action :upgrade end ``` cab_package resource --------------------- [cab_package resource page](cab_package/index) --- Use the **cab_package** resource to install or remove Microsoft Windows cabinet (.cab) packages. **New in Chef Infra Client 12.15.** ### Syntax --- The full syntax for all of the properties that are available to the **cab_package** resource is: ``` cab_package 'name' do options String, Array package_name String source String # default value: The package name. timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `cab_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **cab_package** resource has the following actions: `:install` Installs the cabinet package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes the cabinet package. ### Properties --- The **cab_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String | **Default Value:** `The package name.` The local file path or URL for the CAB package. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **cab_package** resource in recipes: **Using local path in source** ``` cab_package 'Install .NET 3.5 sp1 via KB958488' do source 'C:\Users\xyz\AppData\Local\Temp\Windows6.1-KB958488-x64.cab' action :install end cab_package 'Remove .NET 3.5 sp1 via KB958488' do source 'C:\Users\xyz\AppData\Local\Temp\Windows6.1-KB958488-x64.cab' action :remove end ``` **Using URL in source** ``` cab_package 'Install .NET 3.5 sp1 via KB958488' do source 'https://s3.amazonaws.com/my_bucket/Windows6.1-KB958488-x64.cab' action :install end cab_package 'Remove .NET 3.5 sp1 via KB958488' do source 'https://s3.amazonaws.com/my_bucket/Temp\Windows6.1-KB958488-x64.cab' action :remove end ``` chef_acl resource ------------------ [chef_acl resource page](chef_acl/index) --- Use the **chef_acl** resource to interact with access control lists (ACLs) that exist on the Chef Infra Server. ### Syntax --- The syntax for using the **chef_acl** resource in a recipe is as follows: ``` chef_acl 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_acl` tells Chef Infra Client to use the `Chef::Provider::ChefAcl` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `path` property is not specified as part of a recipe, `name` is also the name of the Chef Infra Client. * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_acl** resource has the following actions: `:create` Default. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_acl** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a chef-client completely. When `true`, any property not specified by this resource will be reset to default property values. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `path` A path to a directory in the chef-repo against which the ACL is applied. For example: `nodes`, `nodes/*`, `nodes/my_node`, `*/*`, `**`, `roles/base`, `data/secrets`, `cookbooks/apache2`, `/users/*`, and so on. `raw_json` Chef Infra Client as JSON data. For example: ``` { "clientname": "client_name", "orgname": "org_name", "validator": false, "certificate": "-----BEGIN CERTIFICATE-----\n ... 1234567890abcdefghijklmnopq\n ... -----END CERTIFICATE-----\n", "name": "node_name" } ``` `recursive` Use to apply changes to child objects. Use `:on_change` to apply changes to child objects only if the parent object changes. Set to `true` to apply changes even if the parent object does not change. Set to `false` to prevent any changes. Default value: `:on_change`. `remove_rights` Use to remove rights. For example: ``` remove_rights :read, :users => 'jkeiser', :groups => [ 'admins', 'users' ] ``` or: ``` remove_rights [ :create, :read ], :users => [ 'jkeiser', 'adam' ] ``` or: ``` remove_rights :all, :users => [ 'jkeiser', 'adam' ] ``` `rights` Use to add rights. Syntax: `:right, :right => 'user', :groups => [ 'group', 'group']`. For example: ``` rights :read, :users => 'jkeiser', :groups => [ 'admins', 'users' ] ``` or: ``` rights [ :create, :read ], :users => [ 'jkeiser', 'adam' ] ``` or: ``` rights :all, :users => 'jkeiser' ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_client resource --------------------- [chef_client resource page](chef_client/index) --- Use the **chef_client** resource to create clients on your Chef Infra Server from within Chef Infra cookbook code. ### Syntax --- The syntax for using the **chef_client** resource in a recipe is as follows: ``` chef_client 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_client` tells Chef Infra Client to use the `Chef::Provider::ChefClient` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the Chef Infra Client * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_client** resource has the following actions: `:create` Default. Use to create a chef-client. `:delete` Use to delete a chef-client. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:regenerate_keys` Use to regenerate the RSA public key for a chef-client. ### Properties --- The **chef_client** resource has the following properties: `admin` Use to specify whether Chef Infra Client is an API client. `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a chef-client completely. When `true`, any property not specified by this resource will be reset to default property values. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of Chef Infra Client. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `output_key_format` Use to specify the format of a public key. Possible values: `pem`, `der`, or `openssh`. Default value: `openssh`. `output_key_path` Use to specify the path to the location in which a public key will be written. `raw_json` Chef Infra Client as JSON data. For example: ``` { "clientname": "client_name", "orgname": "org_name", "validator": false, "certificate": "-----BEGIN CERTIFICATE-----\n ... 1234567890abcdefghijklmnopq\n ... -----END CERTIFICATE-----\n", "name": "node_name" } ``` `source_key` Use to copy a public or private key, but apply a different `format` and `password`. Use in conjunction with `source_key_pass_phrase` and `source_key_path`. `source_key_pass_phrase` The pass phrase for the public key. Use in conjunction with `source_key` and `source_key_path`. `source_key_path` The path to the public key. Use in conjunction with `source_key` and `source_key_pass_phrase`. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `validator` Use to specify if Chef Infra Client is a chef-validator. ### Examples --- This resource does not have any examples. chef_client_config resource ----------------------------- [chef_client_config resource page](chef_client_config/index) --- Use the **chef_client_config** resource to create a client.rb file in the Chef Infra Client configuration directory. See the [client.rb docs](../config_rb_client/index) for more details on options available in the client.rb configuration file. **New in Chef Infra Client 16.6.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_config** resource is: ``` chef_client_config 'name' do additional_config String chef_license String chef_server_url String config_directory String data_collector_server_url String data_collector_token String event_loggers Array # default value: [] exception_handlers Array # default value: [] file_backup_path String file_cache_path String file_staging_uses_destdir String formatters Array # default value: [] ftp_proxy String group String http_proxy String https_proxy String log_level Symbol log_location String, Symbol minimal_ohai true, false named_run_list String no_proxy String, Array # default value: [] node_name String ohai_disabled_plugins Array # default value: [] ohai_optional_plugins Array # default value: [] pid_file String policy_group String policy_name String policy_persist_run_list true, false report_handlers Array # default value: [] ssl_verify_mode Symbol, String start_handlers Array # default value: [] user String action Symbol # defaults to :create if not specified end ``` where: * `chef_client_config` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `additional_config`, `chef_license`, `chef_server_url`, `config_directory`, `data_collector_server_url`, `data_collector_token`, `event_loggers`, `exception_handlers`, `file_backup_path`, `file_cache_path`, `file_staging_uses_destdir`, `formatters`, `ftp_proxy`, `group`, `http_proxy`, `https_proxy`, `log_level`, `log_location`, `minimal_ohai`, `named_run_list`, `no_proxy`, `node_name`, `ohai_disabled_plugins`, `ohai_optional_plugins`, `pid_file`, `policy_group`, `policy_name`, `policy_persist_run_list`, `report_handlers`, `ssl_verify_mode`, `start_handlers`, and `user` are the properties available to this resource. ### Actions --- The **chef_client_config** resource has the following actions: `:create` Create a client.rb config file for configuring Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a client.rb config file for configuring Chef Infra Client. ### Properties --- The **chef_client_config** resource has the following properties: `additional_config` **Ruby Type:** String Additional text to add at the bottom of the client.rb config. This can be used to run custom Ruby or to add less common config options `chef_license` **Ruby Type:** String **Allowed Values:** `"accept", "accept-no-persist", "accept-silent"` Accept the [Chef EULA](https://www.chef.io/end-user-license-agreement/) `chef_server_url` **Ruby Type:** String | `REQUIRED` The URL for the Chef Infra Server. `config_directory` **Ruby Type:** String | **Default Value:** ``/etc/chef/` on *nix-like systems and `C:\chef\` on Windows` The directory to store the client.rb in. `data_collector_server_url` **Ruby Type:** String The data collector URL (typically automate) to send node, converge, and compliance data. Note If possible, use Chef Infra Server to do all data collection reporting, as this removes the need to distribute tokens to individual nodes. New in Chef Infra Client 17.8 `data_collector_token` **Ruby Type:** String The data collector token to interact with the data collector server URL (Automate). Note If possible, use Chef Infra Server to do all data collection reporting, as this removes the need to distribute tokens to individual nodes. New in Chef Infra Client 17.8 `event_loggers` **Ruby Type:** Array | **Default Value:** `[]` `exception_handlers` **Ruby Type:** Array | **Default Value:** `[]` An array of hashes that contain a exception handler class and the arguments to pass to that class on initialization. The hash should include `class` and `argument` keys where `class` is a String and `argument` is an array of quoted String values. For example: `[{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]` `file_backup_path` **Ruby Type:** String The location in which backup files are stored. If this value is empty, backup files are stored in the directory of the target file `file_cache_path` **Ruby Type:** String The location in which cookbooks (and other transient data) files are stored when they are synchronized. This value can also be used in recipes to download files with the `remote_file` resource. `file_staging_uses_destdir` **Ruby Type:** String How file staging (via temporary files) is done. When `true`, temporary files are created in the directory in which files will reside. When `false`, temporary files are created under `ENV['TMP']` `formatters` **Ruby Type:** Array | **Default Value:** `[]` Client logging formatters to load. `ftp_proxy` **Ruby Type:** String The proxy server to use for FTP connections. `group` **Ruby Type:** String The group that should own the client.rb file and the configuration directory if it needs to be created. Note The configuration directory will not be created if it already exists, which allows you to further control the setup of that directory outside of this resource. `http_proxy` **Ruby Type:** String The proxy server to use for HTTP connections. `https_proxy` **Ruby Type:** String The proxy server to use for HTTPS connections. `log_level` **Ruby Type:** Symbol **Allowed Values:** `:auto, :debug, :fatal, :info, :trace, :warn` The level of logging performed by the Chef Infra Client. `log_location` **Ruby Type:** String, Symbol The location to save logs to. This can either by a path to a log file on disk `:syslog` to log to Syslog, `:win_evt` to log to the Windows Event Log, or `'STDERR'`/`'STDOUT'` to log to the *nix text streams. `minimal_ohai` **Ruby Type:** true, false Run a minimal set of Ohai plugins providing data necessary for the execution of Chef Infra Client’s built-in resources. Setting this to true will skip many large and time consuming data sets such as `cloud` or `packages`. Setting this this to true may break cookbooks that assume all Ohai data will be present. `named_run_list` **Ruby Type:** String A specific named runlist defined in the node’s applied Policyfile, which the should be used when running Chef Infra Client. `no_proxy` **Ruby Type:** String, Array | **Default Value:** `[]` A comma-separated list or an array of URLs that do not need a proxy. `node_name` **Ruby Type:** String | **Default Value:** `The `node.name` value reported by Chef Infra Client.` The name of the node. This configuration sets the `node.name` value used in cookbooks and the `client_name` value used when authenticating to a Chef Infra Server to determine what configuration to apply. Note By default this configuration uses the `node.name` value which would be set during bootstrap. Hard coding this value in the `client.rb` config avoids logic within Chef Infra Server that performs DNS lookups and may fail in the event of a DNS outage. To skip this default value and instead use the built-in Chef Infra Server logic, set this property to `nil` `ohai_disabled_plugins` **Ruby Type:** Array | **Default Value:** `[]` Ohai plugins that should be disabled in order to speed up the Chef Infra Client run and reduce the size of node data sent to Chef Infra Client `ohai_optional_plugins` **Ruby Type:** Array | **Default Value:** `[]` Optional Ohai plugins that should be enabled to provide additional Ohai data for use in cookbooks. `pid_file` **Ruby Type:** String The location in which a process identification number (pid) is saved. An executable, when started as a daemon, writes the pid to the specified file. `policy_group` **Ruby Type:** String The name of a `policy group` that exists on the Chef Infra Server. `policy_name` must also be specified when setting this property. `policy_name` **Ruby Type:** String The name of a policy, as identified by the `name` setting in a Policyfile.rb file. `policy_group` when setting this property. `policy_persist_run_list` **Ruby Type:** true, false Override run lists defined in a Policyfile with the `run_list` defined on the Chef Infra Server. New in Chef Infra Client 17.3 `report_handlers` **Ruby Type:** Array | **Default Value:** `[]` An array of hashes that contain a report handler class and the arguments to pass to that class on initialization. The hash should include `class` and `argument` keys where `class` is a String and `argument` is an array of quoted String values. For example: `[{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]` `ssl_verify_mode` **Ruby Type:** Symbol, String **Allowed Values:** `:verify_none, :verify_peer` Set the verify mode for HTTPS requests. * Use :verify_none for no validation of SSL certificates. * Use :verify_peer for validation of all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS remote_file resource URLs used in Chef Infra Client runs. This is the recommended setting. `start_handlers` **Ruby Type:** Array | **Default Value:** `[]` An array of hashes that contain a report handler class and the arguments to pass to that class on initialization. The hash should include `class` and `argument` keys where `class` is a String and `argument` is an array of quoted String values. For example: `[{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]` `user` **Ruby Type:** String The user that should own the client.rb file and the configuration directory if it needs to be created. Note The configuration directory will not be created if it already exists, which allows you to further control the setup of that directory outside of this resource. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_config** resource in recipes: **Bare minimum Chef Infra Client client.rb**: The absolute minimum configuration necessary for a node to communicate with the Chef Infra Server is the URL of the Chef Infra Server. All other configuration options either have values at the server side (Policyfiles, Roles, Environments, etc) or have default values determined at client startup. ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' end ``` **More complex Chef Infra Client client.rb**: ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' log_level :info log_location :syslog http_proxy 'proxy.example.dmz' https_proxy 'proxy.example.dmz' no_proxy %w(internal.example.dmz) end ``` **Adding additional config content to the client.rb**: This resource aims to provide common configuration options. Some configuration options are missing and some users may want to use arbitrary Ruby code within their configuration. For this we offer an `additional_config` property that can be used to add any configuration or code to the bottom of the `client.rb` file. Also keep in mind that within the configuration directory is a `client.d` directory where you can put additional `.rb` files containing configuration options. These can be created using `file` or `template` resources within your cookbooks as necessary. ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' additional_config <<~CONFIG # Extra config code to safely load a gem into the client run. # Since the config is Ruby you can run any Ruby code you want via the client.rb. # It's a great way to break things, so be careful begin require 'aws-sdk' rescue LoadError Chef::Log.warn "Failed to load aws-sdk." end CONFIG end ``` **Setup two report handlers in the client.rb**: ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' report_handlers [ { 'class' => 'ReportHandler1Class', 'arguments' => ["'FirstArgument'", "'SecondArgument'"], }, { 'class' => 'ReportHandler2Class', 'arguments' => ["'FirstArgument'", "'SecondArgument'"], }, ] end ``` **Report directly to the [Chef Automate data collector endpoint](../automate/data_collection/index#configure-chef-infra-client-to-use-the-data-collector-endpoint-in-chef-automate).** ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' data_collector_server_url 'https://automate.example.dmz' data_collector_token 'TEST_TOKEN_TEST' end ``` chef_client_cron resource --------------------------- [chef_client_cron resource page](chef_client_cron/index) --- Use the **chef_client_cron** resource to setup the Chef Infra Client to run as a cron job. This resource will also create the specified log directory if it doesn’t already exist. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_cron** resource is: ``` chef_client_cron 'name' do accept_chef_license true, false # default value: false append_log_file true, false # default value: true chef_binary_path String # default value: "/opt/chef/bin/chef-client" comment String config_directory String # default value: "/etc/chef" daemon_options Array # default value: [] day Integer, String # default value: "*" environment Hash # default value: {} hour Integer, String # default value: "*" job_name String # default value: "chef-client" log_directory String log_file_name String # default value: "client.log" mailto String minute Integer, String # default value: "0,30" month Integer, String # default value: "*" nice Integer, String splay Integer, String # default value: 300 user String # default value: "root" weekday Integer, String # default value: "*" action Symbol # defaults to :add if not specified end ``` where: * `chef_client_cron` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `append_log_file`, `chef_binary_path`, `comment`, `config_directory`, `daemon_options`, `day`, `environment`, `hour`, `job_name`, `log_directory`, `log_file_name`, `mailto`, `minute`, `month`, `nice`, `splay`, `user`, and `weekday` are the properties available to this resource. ### Actions --- The **chef_client_cron** resource has the following actions: `:add` Add a cron job to run Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a cron job for Chef Infra Client. ### Properties --- The **chef_client_cron** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `append_log_file` **Ruby Type:** true, false | **Default Value:** `true` Append to the log file instead of overwriting the log file on each run. `chef_binary_path` **Ruby Type:** String | **Default Value:** `/opt/chef/bin/chef-client` The path to the chef-client binary. `comment` **Ruby Type:** String A comment to place in the cron.d file. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `day` **Ruby Type:** Integer, String | **Default Value:** `*` The day of month at which Chef Infra Client is to run (1 - 31) or a cron pattern such as ‘1,7,14,21,28’. `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. `hour` **Ruby Type:** Integer, String | **Default Value:** `*` The hour at which Chef Infra Client is to run (0 - 23) or a cron pattern such as ‘0,12’. `job_name` **Ruby Type:** String | **Default Value:** `chef-client` The name of the cron job to create. `log_directory` **Ruby Type:** String | **Default Value:** `/Library/Logs/Chef on macOS and /var/log/chef otherwise` The path of the directory to create the log file in. `log_file_name` **Ruby Type:** String | **Default Value:** `client.log` The name of the log file to use. `mailto` **Ruby Type:** String The e-mail address to e-mail any cron task failures to. `minute` **Ruby Type:** Integer, String | **Default Value:** `0,30` The minute at which Chef Infra Client is to run (0 - 59) or a cron pattern such as ‘0,30’. `month` **Ruby Type:** Integer, String | **Default Value:** `*` The month in the year on which Chef Infra Client is to run (1 - 12, jan-dec, or *). `nice` **Ruby Type:** Integer, String The process priority to run the chef-client process at. A value of -20 is the highest priority and 19 is the lowest priority. New in Chef Infra Client 16.5 `splay` **Ruby Type:** Integer, String | **Default Value:** `300` A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time. `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that Chef Infra Client runs as. `weekday` **Ruby Type:** Integer, String | **Default Value:** `*` The day of the week on which Chef Infra Client is to run (0-7, mon-sun, or *), where Sunday is both 0 and 7. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_cron** resource in recipes: **Setup Chef Infra Client to run using the default 30 minute cadence**: ``` chef_client_cron 'Run Chef Infra Client as a cron job' ``` **Run Chef Infra Client twice a day**: ``` chef_client_cron 'Run Chef Infra Client every 12 hours' do minute 0 hour '0,12' end ``` **Run Chef Infra Client with extra options passed to the client**: ``` chef_client_cron 'Run an override recipe' do daemon_options ['--override-runlist mycorp_base::default'] end ``` chef_client_launchd resource ------------------------------ [chef_client_launchd resource page](chef_client_launchd/index) --- Use the **chef_client_launchd** resource to configure the Chef Infra Client to run on a schedule on macOS systems. **New in Chef Infra Client 16.5.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_launchd** resource is: ``` chef_client_launchd 'name' do accept_chef_license true, false # default value: false chef_binary_path String # default value: "/opt/chef/bin/chef-client" config_directory String # default value: "/etc/chef" daemon_options Array # default value: [] environment Hash # default value: {} interval Integer, String # default value: 30 log_directory String # default value: "/Library/Logs/Chef" log_file_name String # default value: "client.log" low_priority_io true, false # default value: true nice Integer, String splay Integer, String # default value: 300 user String # default value: "root" working_directory String # default value: "/var/root" action Symbol # defaults to :enable if not specified end ``` where: * `chef_client_launchd` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `chef_binary_path`, `config_directory`, `daemon_options`, `environment`, `interval`, `log_directory`, `log_file_name`, `low_priority_io`, `nice`, `splay`, `user`, and `working_directory` are the properties available to this resource. ### Actions --- The **chef_client_launchd** resource has the following actions: `:disable` Disable running Chef Infra Client on a schedule using launchd `:enable` Enable running Chef Infra Client on a schedule using launchd. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_client_launchd** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `chef_binary_path` **Ruby Type:** String | **Default Value:** `/opt/chef/bin/chef-client` The path to the chef-client binary. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the launchd daemon will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. `interval` **Ruby Type:** Integer, String | **Default Value:** `30` Time in minutes between Chef Infra Client executions. `log_directory` **Ruby Type:** String | **Default Value:** `/Library/Logs/Chef` The path of the directory to create the log file in. `log_file_name` **Ruby Type:** String | **Default Value:** `client.log` The name of the log file to use. `low_priority_io` **Ruby Type:** true, false | **Default Value:** `true` Run the chef-client process with low priority disk IO `nice` **Ruby Type:** Integer, String The process priority to run the chef-client process at. A value of -20 is the highest priority and 19 is the lowest priority. `splay` **Ruby Type:** Integer, String | **Default Value:** `300` A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time. `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that Chef Infra Client runs as. `working_directory` **Ruby Type:** String | **Default Value:** `/var/root` The working directory to run the Chef Infra Client from. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_launchd** resource in recipes: **Set the Chef Infra Client to run on a schedule**: ``` chef_client_launchd 'Setup the Chef Infra Client to run every 30 minutes' do interval 30 action :enable end ``` **Disable the Chef Infra Client running on a schedule**: ``` chef_client_launchd 'Prevent the Chef Infra Client from running on a schedule' do action :disable end ``` chef_client_scheduled_task resource -------------------------------------- [chef_client_scheduled_task resource page](chef_client_scheduled_task/index) --- Use the **chef_client_scheduled_task** resource to setup the Chef Infra Client to run as a Windows scheduled task. This resource will also create the specified log directory if it doesn’t already exist. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_scheduled_task** resource is: ``` chef_client_scheduled_task 'name' do accept_chef_license true, false # default value: false chef_binary_path String # default value: "C:/opscode/chef/bin/chef-client" config_directory String # default value: "/etc/chef" daemon_options Array # default value: [] frequency String # default value: "minute" frequency_modifier Integer, String # default value: "30 if frequency is 'minute', 1 otherwise" log_directory String # default value: "CONFIG_DIRECTORY/log" log_file_name String # default value: "client.log" password String priority Integer # default value: 7 run_on_battery true, false # default value: true splay Integer, String # default value: 300 start_date String start_time String task_name String # default value: "chef-client" use_consistent_splay true, false # default value: false user String # default value: "System" action Symbol # defaults to :add if not specified end ``` where: * `chef_client_scheduled_task` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `chef_binary_path`, `config_directory`, `daemon_options`, `frequency`, `frequency_modifier`, `log_directory`, `log_file_name`, `password`, `priority`, `run_on_battery`, `splay`, `start_date`, `start_time`, `task_name`, `use_consistent_splay`, and `user` are the properties available to this resource. ### Actions --- The **chef_client_scheduled_task** resource has the following actions: `:add` Add a Windows Scheduled Task that runs Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows Scheduled Task that runs Chef Infra Client. ### Properties --- The **chef_client_scheduled_task** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `chef_binary_path` **Ruby Type:** String | **Default Value:** `C:/opscode/chef/bin/chef-client` The path to the chef-client binary. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `frequency` **Ruby Type:** String | **Default Value:** `minute` **Allowed Values:** `"daily", "hourly", "minute", "monthly", "on_idle", "on_logon", "once", "onstart"` Frequency with which to run the task. `frequency_modifier` **Ruby Type:** Integer, String | **Default Value:** `30 if frequency is 'minute', 1 otherwise` Numeric value to go with the scheduled task frequency `log_directory` **Ruby Type:** String | **Default Value:** `CONFIG_DIRECTORY/log` The path of the directory to create the log file in. `log_file_name` **Ruby Type:** String | **Default Value:** `client.log` The name of the log file to use. `password` **Ruby Type:** String The password for the user that Chef Infra Client runs as. `priority` **Ruby Type:** Integer | **Default Value:** `7` Use to set Priority Levels range from 0 to 10. New in Chef Infra Client 17.5 `run_on_battery` **Ruby Type:** true, false | **Default Value:** `true` Run the Chef Infra Client task when the system is on batteries. `splay` **Ruby Type:** Integer, String | **Default Value:** `300` A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time. `start_date` **Ruby Type:** String The start date for the task in m:d:Y format (ex: 12/17/2020). `start_time` **Ruby Type:** String The start time for the task in HH:mm format (ex: 14:00). If the frequency is minute default start time will be Time.now plus the frequency_modifier number of minutes. `task_name` **Ruby Type:** String | **Default Value:** `chef-client` The name of the scheduled task to create. `use_consistent_splay` **Ruby Type:** true, false | **Default Value:** `false` Always use the same random splay amount for each node to ensure consistent frequencies between chef-client execution. New in Chef Infra Client 17.5 `user` **Ruby Type:** String | **Default Value:** `System` The name of the user that Chef Infra Client runs as. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_scheduled_task** resource in recipes: **Setup Chef Infra Client to run using the default 30 minute cadence**: ``` chef_client_scheduled_task 'Run Chef Infra Client as a scheduled task' ``` **Run Chef Infra Client on system start**: ``` chef_client_scheduled_task 'Chef Infra Client on start' do frequency 'onstart' end ``` **Run Chef Infra Client with extra options passed to the client**: ``` chef_client_scheduled_task 'Run an override recipe' do daemon_options ['--override-runlist mycorp_base::default'] end ``` **Run Chef Infra Client daily at 01:00 am, specifying a named run-list**: ``` chef_client_scheduled_task 'Run chef-client named run-list daily' do frequency 'daily' start_time '01:00' daemon_options ['-n audit_only'] end ``` **Run Chef Infra Client with a persistent delay on every run calculated once, similar to how chef_client_cron resource works**: ``` chef_client_scheduled_task 'Run chef-client with persistent splay' do use_consistent_splay true end ``` chef_client_systemd_timer resource ------------------------------------- [chef_client_systemd_timer resource page](chef_client_systemd_timer/index) --- Use the **chef_client_systemd_timer** resource to setup the Chef Infra Client to run as a systemd timer. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_systemd_timer** resource is: ``` chef_client_systemd_timer 'name' do accept_chef_license true, false # default value: false chef_binary_path String # default value: "/opt/chef/bin/chef-client" config_directory String # default value: "/etc/chef" cpu_quota Integer, String daemon_options Array # default value: [] delay_after_boot String # default value: "1min" description String # default value: "Chef Infra Client periodic execution" environment Hash # default value: {} interval String # default value: "30min" job_name String # default value: "chef-client" run_on_battery true, false # default value: true splay String # default value: "5min" user String # default value: "root" action Symbol # defaults to :add if not specified end ``` where: * `chef_client_systemd_timer` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `chef_binary_path`, `config_directory`, `cpu_quota`, `daemon_options`, `delay_after_boot`, `description`, `environment`, `interval`, `job_name`, `run_on_battery`, `splay`, and `user` are the properties available to this resource. ### Actions --- The **chef_client_systemd_timer** resource has the following actions: `:add` Add a systemd timer that runs Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a systemd timer that runs Chef Infra Client. ### Properties --- The **chef_client_systemd_timer** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `chef_binary_path` **Ruby Type:** String | **Default Value:** `/opt/chef/bin/chef-client` The path to the chef-client binary. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `cpu_quota` **Ruby Type:** Integer, String The systemd CPUQuota to run the chef-client process with. This is a percentage value of the total CPU time available on the system. If the system has more than 1 core this may be a value greater than 100. New in Chef Infra Client 16.5 `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `delay_after_boot` **Ruby Type:** String | **Default Value:** `1min` The time to wait after booting before the interval starts. This is expressed as a systemd time span such as `300seconds`, `1hr`, or `1m`. See <https://www.freedesktop.org/software/systemd/man/systemd.time.html> for a complete list of allowed time span values. `description` **Ruby Type:** String | **Default Value:** `Chef Infra Client periodic execution` The description to add to the systemd timer. This will be displayed when running `systemctl status` for the timer. `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the systemd timer will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. `interval` **Ruby Type:** String | **Default Value:** `30min` The interval to wait between executions. This is expressed as a systemd time span such as `300seconds`, `1hr`, or `1m`. See <https://www.freedesktop.org/software/systemd/man/systemd.time.html> for a complete list of allowed time span values. `job_name` **Ruby Type:** String | **Default Value:** `chef-client` The name of the system timer to create. `run_on_battery` **Ruby Type:** true, false | **Default Value:** `true` Run the timer for Chef Infra Client if the system is on battery. `splay` **Ruby Type:** String | **Default Value:** `5min` A interval between 0 and X to add to the interval so that all chef-client commands don’t execute at the same time. This is expressed as a systemd time span such as `300seconds`, `1hr`, or `1m`. See <https://www.freedesktop.org/software/systemd/man/systemd.time.html> for a complete list of allowed time span values. `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that Chef Infra Client runs as. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_systemd_timer** resource in recipes: **Setup Chef Infra Client to run using the default 30 minute cadence**: ``` chef_client_systemd_timer 'Run Chef Infra Client as a systemd timer' ``` **Run Chef Infra Client every 1 hour**: ``` chef_client_systemd_timer 'Run Chef Infra Client every 1 hour' do interval '1hr' end ``` **Run Chef Infra Client with extra options passed to the client**: ``` chef_client_systemd_timer 'Run an override recipe' do daemon_options ['--override-runlist mycorp_base::default'] end ``` chef_client_trusted_certificate resource ------------------------------------------- [chef_client_trusted_certificate resource page](chef_client_trusted_certificate/index) --- Use the **chef_client_trusted_certificate** resource to add certificates to Chef Infra Client’s trusted certificate directory. This allows the Chef Infra Client to communicate with internal encrypted resources without errors. **New in Chef Infra Client 16.5.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_trusted_certificate** resource is: ``` chef_client_trusted_certificate 'name' do cert_name String # default value: 'name' unless specified certificate String action Symbol # defaults to :add if not specified end ``` where: * `chef_client_trusted_certificate` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `cert_name` and `certificate` are the properties available to this resource. ### Actions --- The **chef_client_trusted_certificate** resource has the following actions: `:add` Add a trusted certificate to Chef Infra Client’s trusted certificate directory (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a trusted certificate from Chef Infra Client’s trusted certificate directory ### Properties --- The **chef_client_trusted_certificate** resource has the following properties: `cert_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name to use for the certificate file on disk. If not provided the name of the resource block will be used instead. `certificate` **Ruby Type:** String | `REQUIRED` The text of the certificate file including the BEGIN/END comment lines. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_trusted_certificate** resource in recipes: **Trust a self signed certificate**: ``` chef_client_trusted_certificate 'self-signed.badssl.com' do certificate <<~CERT -----BEGIN CERTIFICATE----- MIIDeTCCAmGgAwIBAgIJAPziuikCTox4MA0GCSqGSIb3DQEBCwUAMGIxCzAJBgNV BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNp c2NvMQ8wDQYDVQQKDAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTAeFw0x OTEwMDkyMzQxNTJaFw0yMTEwMDgyMzQxNTJaMGIxCzAJBgNVBAYTAlVTMRMwEQYD VQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQ8wDQYDVQQK DAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTCCASIwDQYJKoZIhvcNAQEB BQADggEPADCCAQoCggEBAMIE7PiM7gTCs9hQ1XBYzJMY61yoaEmwIrX5lZ6xKyx2 PmzAS2BMTOqytMAPgLaw+XLJhgL5XEFdEyt/ccRLvOmULlA3pmccYYz2QULFRtMW hyefdOsKnRFSJiFzbIRMeVXk0WvoBj1IFVKtsyjbqv9u/<KEY> -----END CERTIFICATE----- CERT end ``` chef_container resource ------------------------ [chef_container resource page](chef_container/index) --- Use the **chef_container** resource to interact with container objects that exist on the Chef Infra Server. ### Syntax --- The syntax for using the **chef_container** resource in a recipe is as follows: ``` chef_container 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_container` tells Chef Infra Client to use the `Chef::Provider::ChefContainer` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_container** resource has the following actions: `:create` Default. `:delete` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_container** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the container. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_data_bag resource ------------------------ [chef_data_bag resource page](chef_data_bag/index) --- Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. Use the **chef_data_bag** resource to manage data bags. ### Syntax --- The syntax for using the **chef_data_bag** resource in a recipe is as follows: ``` chef_data_bag 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_data_bag` tells Chef Infra Client to use the `Chef::Provider::ChefDataBag` provider during a Chef Infra Client run * `name` is the name of the resource block and also the name of the data bag * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_data_bag** resource has the following actions: `:create` Default. Use to create a data bag. `:delete` Use to delete a data bag. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_data_bag** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the data bag. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_data_bag_item resource ------------------------------ [chef_data_bag_item resource page](chef_data_bag_item/index) --- A data bag is a container of related data bag items, where each individual data bag item is a JSON file. knife can load a data bag item by specifying the name of the data bag to which the item belongs and then the filename of the data bag item. The only structural requirement of a data bag item is that it must have an `id`: ``` { /* This is a supported comment style */ // This style is also supported "id": "ITEM_NAME", "key": "value" } ``` where * `key` and `value` are the `key:value` pair for each additional attribute within the data bag item * `/* ... */` and `// ...` show two ways to add comments to the data bag item Use the **chef_data_bag_item** resource to manage data bag items. ### Syntax --- The syntax for using the **chef_data_bag_item** resource in a recipe is as follows: ``` chef_data_bag_item 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_data_bag_item` tells Chef Infra Client to use the `Chef::Provider::ChefDataBagItem` provider during a Chef Infra Client run * `name` is the name of the resource block and also the name of the data bag item * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_data_bag_item** resource has the following actions: `:create` Default. Use to create a data bag item. `:delete` Use to delete a data bag item. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_data_bag_item** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a data bag item completely. When `true`, any property not specified by this resource will be reset to default property values. `encrypt` Use to specify whether encryption is used for a data bag item. `encryption_version` The minimum required version of data bag encryption. Possible values: `0`, `1`, `2`, and `3`. When all of the machines in an organization are running chef-client version 13.0.113 (or higher), it is recommended that this value be set to `3`. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `raw_data` Use to create a data bag from a local file from `./data_bags/bag_name/file`. `raw_json` The data bag item as JSON data. For example: ``` { "id": "adam", "real_name": "<NAME>" } ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_environment resource -------------------------- [chef_environment resource page](chef_environment/index) --- An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. Use the **chef_environment** resource to manage environments. ### Syntax --- The syntax for using the **chef_environment** resource in a recipe is as follows: ``` chef_environment 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_environment` tells Chef Infra Client to use the `Chef::Provider::ChefEnvironment` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the environment * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_environment** resource has the following actions: `:create` Default. Use to create an environment. `:delete` Use to delete an environment. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_environment** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines an environment completely. When `true`, any property not specified by this resource will be reset to default property values. `cookbook_versions` The cookbook versions used with the environment. Default value: `{}`. `default_attributes` A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. Default value: `{}`. `description` The description of the environment. This value populates the description field for the environment on the Chef Infra Server. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the environment. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `override_attributes` An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. Default value: `{}`. `raw_json` The environment as JSON data. For example: ``` { "name":"backend", "description":"", "cookbook_versions":{}, "json_class":"Chef::Environment", "chef_type":"environment", "default_attributes":{}, "override_attributes":{} } ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_gem resource ------------------ [chef_gem resource page](chef_gem/index) --- Use the **chef_gem** resource to install a gem only for the instance of Ruby that is dedicated to the chef-client. When a gem is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. The **chef_gem** resource works with all of the same properties and options as the **gem_package** resource, but does not accept the `gem_binary` property because it always uses the `CurrentGemEnvironment` under which the `chef-client` is running. In addition to performing actions similar to the **gem_package** resource, the **chef_gem** resource does the following: * Runs its actions immediately, before convergence, allowing a gem to be used in a recipe immediately after it is installed. * Runs `Gem.clear_paths` after the action, ensuring that gem is aware of changes so that it can be required immediately after it is installed. Warning The **chef_gem** and **gem_package** resources are both used to install Ruby gems. For any machine on which Chef Infra Client is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is available only to Chef Infra Client. Use the **chef_gem** resource to install gems into the instance of Ruby that is dedicated to Chef Infra Client. Use the **gem_package** resource to install all other gems (i.e. install gems system-wide). ### Syntax --- The full syntax for all of the properties that are available to the **chef_gem** resource is: ``` chef_gem 'name' do clear_sources true, false gem_binary String include_default_source true, false options String, Hash, Array package_name String source String, Array timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `chef_gem` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `clear_sources`, `gem_binary`, `include_default_source`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **chef_gem** resource has the following actions: `:install` Default. Install a gem. If a version is specified, install the specified version of the gem. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a gem. This action typically removes the configuration files as well as the gem. `:reconfig` Reconfigure a gem. This action requires a response file. `:remove` Remove a gem. `:upgrade` Install a gem and/or ensure that a gem is the latest version. ### Properties --- The **chef_gem** resource has the following properties: `clear_sources` **Ruby Type:** true, false | **Default Value:** `false unless `clear_gem_sources` set to true in the `client.rb` config.` Set to `true` to download a gem from the path specified by the `source` property (and not from RubyGems). `gem_binary` **Ruby Type:** String | **Default Value:** `The `gem` binary included with Chef Infra Client.` The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by Chef Infra Client will be used. `include_default_source` **Ruby Type:** true, false Set to `false` to not include `Chef::Config[:rubygems_url]` in the sources. New in Chef Client 13.0 `options` **Ruby Type:** String, Hash, Array Options for the gem install, either a Hash or a String. When a hash is given, the options are passed to `Gem::DependencyInstaller.new`, and the gem will be installed via the gems API. When a String is given, the gem will be installed by shelling out to the gem command. Using a Hash of options with an explicit gem_binary will result in undefined behavior. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String, Array Optional. The URL, or list of URLs, at which the gem package is located. This list is added to the source configured in `Chef::Config[:rubygems_url]` (see also include_default_source) to construct the complete list of rubygems sources. Users in an ‘airgapped’ environment should set Chef::Config[:rubygems_url] to their local RubyGems mirror. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_gem** resource in recipes: **Compile time vs. converge time installation of gems** To install a gem while Chef Infra Client is configuring the node (the converge phase), set the `compile_time` property to `false`: ``` chef_gem 'loofah' do compile_time false action :install end ``` To install a gem while the resource collection is being built (the compile phase), set the `compile_time` property to `true`: ``` chef_gem 'loofah' do compile_time true action :install end ``` **Install MySQL gem into Chef Infra Client*** ``` apt_update build_essential 'install compilation tools' do compile_time true end chef_gem 'mysql' ``` chef_group resource -------------------- [chef_group resource page](chef_group/index) --- Use the **chef_group** resource to interact with group objects that exist on the Chef server. ### Syntax --- The syntax for using the **chef_group** resource in a recipe is as follows: ``` chef_group 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_group` tells Chef Infra Client to use the `Chef::Provider::ChefGroup` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_group** resource has the following actions: `:create` Default. `:delete` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_group** resource has the following properties: `chef_server` The URL for the Chef server. `clients` &mldr; `complete` Use to specify if this resource defines a chef-client completely. When `true`, any property not specified by this resource will be reset to default property values. `groups` &mldr; `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `raw_json` The group as JSON data. For example: ``` { :groupname => "chef" } ``` `remove_clients` &mldr; `remove_groups` &mldr; `remove_users` &mldr; `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `users` &mldr; ### Examples --- This resource does not have any examples. chef_handler resource ---------------------- [chef_handler resource page](chef_handler/index) --- Use the **chef_handler** resource to enable handlers during a Chef Infra Client run. The resource allows arguments to be passed to Chef Infra Client, which then applies the conditions defined by the custom handler to the node attribute data collected during a Chef Infra Client run, and then processes the handler based on that data. The **chef_handler** resource is typically defined early in a node’s run-list (often being the first item). This ensures that all of the handlers will be available for the entire Chef Infra Client run. **New in Chef Infra Client 14.0.** ### Handler Types There are three types of handlers: | Handler | Description | | --- | --- | | exception | An exception handler is used to identify situations that have caused a Chef Infra Client run to fail. An exception handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the **chef_handler** resource to a node's run-list. An exception handler runs when the `failed?` property for the `run_status` object returns `true`. | | report | A report handler is used when a Chef Infra Client run succeeds and reports back on certain details about that Chef Infra Client run. A report handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the **chef_handler** resource to a node's run-list. A report handler runs when the `success?` property for the `run_status` object returns `true`. | | start | A start handler is used to run events at the beginning of a Chef Infra Client run. A start handler can be loaded at the start of a Chef Infra Client run by adding the start handler to the `start_handlers` setting in the client.rb file or by installing the gem that contains the start handler by using the **chef_gem** resource in a recipe in the **chef-client** cookbook. (A start handler may not be loaded using the `chef_handler` resource.) | #### Exception / Report Exception and report handlers are used to trigger certain behaviors in response to specific situations, typically identified during a Chef Infra Client run. * An exception handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run fails. * A report handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run is successful. Both types of handlers can be used to gather data about a Chef Infra Client run and can provide rich levels of data about all types of usage, which can be used later for trending and analysis across the entire organization. Exception and report handlers are made available to a Chef Infra Client run in one of the following ways: * By adding the **chef_handler** resource to a recipe, and then adding that recipe to the run-list for a node. (The **chef_handler** resource is available from the **chef_handler** cookbook.) * By adding the handler to one of the following settings in the node’s client.rb file: `exception_handlers` and/or `report_handlers` The **chef_handler** resource allows exception and report handlers to be enabled from within recipes, which can then added to the run-list for any node on which the exception or report handler should run. The **chef_handler** resource is available from the **chef_handler** cookbook. To use the **chef_handler** resource in a recipe, add code similar to the following: ``` chef_handler 'name_of_handler' do source '/path/to/handler/handler_name' action :enable end ``` For example, a handler for Growl needs to be enabled at the beginning of a Chef Infra Client run: ``` chef_gem 'chef-handler-growl' ``` and then is activated in a recipe by using the **chef_handler** resource: ``` chef_handler 'Chef::Handler::Growl' do source 'chef/handler/growl' action :enable end ``` #### Start A start handler is not loaded into a Chef Infra Client run from a recipe, but is instead listed in the client.rb file using the `start_handlers` attribute. The start handler must be installed on the node and be available to Chef Infra Client prior to the start of a Chef Infra Client run. Use the **chef-client** cookbook to install the start handler. Start handlers are made available to a Chef Infra Client run in one of the following ways: * By adding a start handler to the **chef-client** cookbook, which installs the handler on the node so that it is available to Chef Infra Client at the start of a Chef Infra Client run * By adding the handler to one of the following settings in the node’s client.rb file: `start_handlers` The **chef-client** cookbook can be configured to automatically install and configure gems that are required by a start handler. For example: ``` node.override['chef_client']['load_gems']['chef-reporting'] = { require_name: 'chef_reporting', action: :install, } node.override['chef_client']['config']['start_handlers'] = [ { class: 'Chef::Reporting::StartHandler', arguments: [], }, ] include_recipe 'chef-client::config' ``` ### Syntax --- A **chef_handler** resource block enables handlers during a chef-client run. Two handlers—`JsonFile` and `ErrorReport`—are built into Chef: ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments :path => '/var/chef/reports' action :enable end ``` and: ``` chef_handler 'Chef::Handler::ErrorReport' do source 'chef/handler/error_report' action :enable end ``` show how to enable those handlers in a recipe. The full syntax for all of the properties that are available to the **chef_handler** resource is: ``` chef_handler 'name' do arguments Array, Hash # default value: [] class_name String # default value: 'name' unless specified source String type Hash # default value: {"report"=>true, "exception"=>true} action Symbol # defaults to :enable if not specified end ``` where: * `chef_handler` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `arguments`, `class_name`, `source`, and `type` are the properties available to this resource. ### Actions --- The **chef_handler** resource has the following actions: `:disable` Disables the handler for the current Chef Infra Client run on the current node. `:enable` Enables the handler for the current Chef Infra Client run on the current node. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_handler** resource has the following properties: `arguments` **Ruby Type:** Array, Hash | **Default Value:** `[]` An array of arguments that are passed to the initializer for the handler class. For example: ``` arguments :key1 => 'val1' ``` or: ``` arguments [:key1 => 'val1', :key2 => 'val2'] ``` `class_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the handler class. This can be module name-spaced. `source` **Ruby Type:** String The full path to the handler file. Can also be a gem path if the handler ships as part of a Ruby gem. `type` **Ruby Type:** Hash | **Default Value:** `{"report"=>true, "exception"=>true}` The type of handler to register as, i.e. :report, :exception or both. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_handler** resource in recipes: **Enable the ‘MyHandler’ handler** The following example shows how to enable a fictional ‘MyHandler’ handler which is located on disk at `/etc/chef/my_handler.rb`. The handler will be configured to run with Chef Infra Client and will be passed values to the handler’s initializer method: ``` chef_handler 'MyHandler' do source '/etc/chef/my_handler.rb' # the file should already be at this path arguments path: '/var/chef/reports' action :enable end ``` **Enable handlers during the compile phase** ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' action :enable compile_time true end ``` **Handle only exceptions** ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' type exception: true action :enable end ``` **Cookbook Versions (a custom handler)** [@juliandunn](https://github.com/juliandunn) created a custom report handler that logs all of the cookbooks and cookbook versions that were used during a Chef Infra Client run, and then reports after the run is complete. cookbook_versions.rb: The following custom handler defines how cookbooks and cookbook versions that are used during a Chef Infra Client run will be compiled into a report using the `Chef::Log` class in Chef Infra Client: ``` require 'chef/log' module Chef class CookbookVersionsHandler < Chef::Handler def report cookbooks = run_context.cookbook_collection Chef::Log.info('Cookbooks and versions run: #{cookbooks.map {|x| x.name.to_s + ' ' + x.version }}') end end end ``` default.rb: The following recipe is added to the run-list for every node on which a list of cookbooks and versions will be generated as report output after every Chef Infra Client run. ``` cookbook_file '/etc/chef/cookbook_versions.rb' do source 'cookbook_versions.rb' action :create end chef_handler 'Chef::CookbookVersionsHandler' do source '/etc/chef/cookbook_versions.rb' type report: true action :enable end ``` This recipe will generate report output similar to the following: ``` [2013-11-26T03:11:06+00:00] INFO: Chef Infra Client Run complete in 0.300029878 seconds [2013-11-26T03:11:06+00:00] INFO: Running report handlers [2013-11-26T03:11:06+00:00] INFO: Cookbooks and versions run: ["cookbook_versions_handler 1.0.0"] [2013-11-26T03:11:06+00:00] INFO: Report handlers complete ``` **JsonFile Handler** The JsonFile handler is available from the `chef_handler` cookbook and can be used with exceptions and reports. It serializes run status data to a JSON file. This handler may be enabled in one of the following ways. By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how Chef Infra Client is being run: ``` require 'chef/handler/json_file' report_handlers << Chef::Handler::JsonFile.new(path: '/var/chef/reports') exception_handlers << Chef::Handler::JsonFile.new(path: '/var/chef/reports') ``` By using the `chef_handler` resource in a recipe, similar to the following: ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' action :enable end ``` After it has run, the run status data can be loaded and inspected via Interactive Ruby (IRb): ``` irb(main):002:0> require 'json' => true irb(main):003:0> require 'chef' => true irb(main):004:0> r = JSON.parse(IO.read('/var/chef/reports/chef-run-report-20110322060731.json')) => ... output truncated irb(main):005:0> r.keys => ['end_time', 'node', 'updated_resources', 'exception', 'all_resources', 'success', 'elapsed_time', 'start_time', 'backtrace'] irb(main):006:0> r['elapsed_time'] => 0.00246 ``` Register the JsonFile handler ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' action :enable end ``` **ErrorReport Handler** The ErrorReport handler is built into Chef Infra Client and can be used for both exceptions and reports. It serializes error report data to a JSON file. This handler may be enabled in one of the following ways. By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how Chef Infra Client is being run: ``` require 'chef/handler/error_report' report_handlers << Chef::Handler::ErrorReport.new exception_handlers << Chef::Handler::ErrorReport.new ``` By using the `chef_handler` resource in a recipe, similar to the following: ``` chef_handler 'Chef::Handler::ErrorReport' do source 'chef/handler/error_report' action :enable end ``` chef_node resource ------------------- [chef_node resource page](chef_node/index) --- A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. Use the **chef_node** resource to manage nodes. ### Syntax --- The syntax for using the **chef_node** resource in a recipe is as follows: ``` chef_node 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_node` tells Chef Infra Client to use the `Chef::Provider::ChefNode` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_node** resource has the following actions: `:create` Default. Use to create a node. `:delete` Use to delete a node. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_node** resource has the following properties: `automatic_attributes` An `automatic` attribute contains data that is identified by Ohai at the beginning of every Chef Infra Client run. An `automatic` attribute cannot be modified and always has the highest attribute precedence. Default value: `{}`. `chef_environment` The Chef Infra Server environment in which this node should exist (or does exist). `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a node completely. When `true`, any property not specified by this resource will be reset to default property values. `default_attributes` A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. Default value: `{}`. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The unique identifier of the node. `normal_attributes` A `normal` attribute is a setting that persists in the node object. A `normal` attribute has a higher attribute precedence than a `default` attribute. Default value: `{}`. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `override_attributes` An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. Default value: `{}`. `raw_json` The node as JSON data. For example: ``` { "overrides": {}, "name": "latte", "chef_type": "node", "json_class": "Chef::Node", "attributes": { "hardware_type": "laptop" }, "run_list": [ "recipe[apache2]" ], "defaults": {} } ``` `run_list` A comma-separated list of roles and/or recipes to be applied. Default value: `[]`. For example: `["recipe[default]","recipe[apache2]"]` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_organization resource --------------------------- [chef_organization resource page](chef_organization/index) --- Use the **chef_organization** resource to interact with organization objects that exist on the Chef Infra Server. ### Syntax --- The syntax for using the **chef_organization** resource in a recipe is as follows: ``` chef_organization 'name' do attribute 'value' # see attributes section below ... action :action # see actions section below end ``` where: * `chef_organization` tells Chef Infra Client to use the `Chef::Provider::ChefOrganization` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the attributes that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_organization** resource has the following actions: `:create` Default. `:delete` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_organization** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines an organization completely. When `true`, any property not specified by this resource will be reset to default property values. `full_name` The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `Chef Software, Inc.`. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `invites` Use to specify a list of users to be invited to the organization. An invitation is sent to any user in this list who is not already a member of the organization. `members` Use to specify a list of users who MUST be members of the organization. These users will be added directly to the organization. The user who initiates this operation MUST also have permission to add users to the specified organization. `members_specified` Use to discover if a user is a member of an organization. Will return `true` if the user is a member. `name` The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `raw_json` The organization as JSON data. For example: ``` { "name": "chef", "full_name": "<NAME>", "guid": "f980d1asdfda0331235s00ff36862 ... } ``` `remove_members` Use to remove the specified users from an organization. Invitations that have not been accepted will be cancelled. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_role resource ------------------- [chef_role resource page](chef_role/index) --- A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. Use the **chef_role** resource to manage roles. ### Syntax --- The syntax for using the **chef_role** resource in a recipe is as follows: ``` chef_role 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_role` tells Chef Infra Client to use the `Chef::Provider::ChefRole` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the role * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_role** resource has the following actions: `:create` Default. Use to create a role. `:delete` Use to delete a role. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_role** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a role completely. When `true`, any property not specified by this resource will be reset to default property values. `default_attributes` A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. Default value: `{}`. `description` The description of the role. This value populates the description field for the role on the Chef Infra Server. `env_run_lists` The environment-specific run-list for a role. Default value: `[]`. For example: `["env_run_lists[webserver]"]` `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the role. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `override_attributes` An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. Default value: `{}`. `raw_json` The role as JSON data. For example: ``` { "name": "webserver", "chef_type": "role", "json_class": "Chef::Role", "default_attributes": {}, "description": "A webserver", "run_list": [ "recipe[apache2]" ], "override_attributes": {} } ``` `run_list` A comma-separated list of roles and/or recipes to be applied. Default value: `[]`. For example: `["recipe[default]","recipe[apache2]"]` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_sleep resource -------------------- [chef_sleep resource page](chef_sleep/index) --- Use the **chef_sleep** resource to pause (sleep) for a number of seconds during a Chef Infra Client run. Only use this resource when a command or service exits successfully but is not ready for the next step in a recipe. **New in Chef Infra Client 15.5.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_sleep** resource is: ``` chef_sleep 'name' do seconds String, Integer # default value: 'name' unless specified action Symbol # defaults to :sleep if not specified end ``` where: * `chef_sleep` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `seconds` is the property available to this resource. ### Actions --- The **chef_sleep** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:sleep` Pause the Chef Infra Client run for a specified number of seconds. (default) ### Properties --- The **chef_sleep** resource has the following properties: `seconds` **Ruby Type:** String, Integer | **Default Value:** `The resource block's name` The number of seconds to sleep. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_sleep** resource in recipes: **Sleep for 10 seconds**: ``` chef_sleep '10' ``` **Sleep for 10 seconds with a descriptive resource name for logging**: ``` chef_sleep 'wait for the service to start' do seconds 10 end ``` **Use a notification from another resource to sleep only when necessary**: ``` service 'Service that is slow to start and reports as started' do service_name 'my_database' action :start notifies :sleep, 'chef_sleep[wait for service start]' end chef_sleep 'wait for service start' do seconds 30 action :nothing end ``` chef_user resource ------------------- [chef_user resource page](chef_user/index) --- Use the **chef_user** resource to manage users. ### Syntax --- The syntax for using the **chef_user** resource in a recipe is as follows: ``` chef_user 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_user` tells Chef Infra Client to use the `Chef::Provider::ChefUser` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the user * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_user** resource has the following actions: `:create` Default. Use to create a user. `:delete` Use to delete a user. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_user** resource has the following properties: `admin` Create a client as an admin client. This is required for any user to access Chef as an administrator. `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a user completely. When `true`, any property not specified by this resource will be reset to default property values. `email` The email address for the user. `external_authentication_uid` &mldr; `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the user. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `output_key_format` Use to specify the format of a public key. Possible values: `pem`, `der`, or `openssh`. Default value: `openssh`. `output_key_path` Use to specify the path to the location in which a public key will be written. `raw_json` The user as JSON data. For example: ``` { "name": "<NAME>" } ``` `recovery_authentication_enabled` &mldr; `source_key` Use to copy a public or private key, but apply a different `format` and `password`. Use in conjunction with `source_key_pass_phrase` and `source_key_path`. `source_key_pass_phrase` The pass phrase for the public key. Use in conjunction with `source_key` and `source_key_path`. `source_key_path` The path to the public key. Use in conjunction with `source_key` and `source_key_pass_phrase`. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_vault_secret resource ---------------------------- [chef_vault_secret resource page](chef_vault_secret/index) --- Use the **chef_vault_secret** resource to store secrets in Chef Vault items. Where possible and relevant, this resource attempts to map behavior and functionality to the knife vault sub-commands. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_vault_secret** resource is: ``` chef_vault_secret 'name' do admins String, Array clients String, Array data_bag String environment String id String # default value: 'name' unless specified raw_data Hash, Mash (Hash-like) # default value: {} search String # default value: "*:*" action Symbol # defaults to :create if not specified end ``` where: * `chef_vault_secret` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `admins`, `clients`, `data_bag`, `environment`, `id`, `raw_data`, and `search` are the properties available to this resource. ### Actions --- The **chef_vault_secret** resource has the following actions: `:create` Creates the item, or updates it if it already exists. (default) `:create_if_missing` Calls the create action unless it exists. `:delete` Deletes the item and the item’s keys (‘id’_keys). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_vault_secret** resource has the following properties: `admins` **Ruby Type:** String, Array | `REQUIRED` A list of admin users who should have access to the item. Corresponds to the ‘admin’ option when using the chef-vault knife plugin. Can be specified as a comma separated string or an array. `clients` **Ruby Type:** String, Array A search query for the nodes' API clients that should have access to the item. `data_bag` **Ruby Type:** String | `REQUIRED` The data bag that contains the item. `environment` **Ruby Type:** String The Chef environment of the data if storing per environment values. `id` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the data bag item if it differs from the name of the resource block `raw_data` **Ruby Type:** Hash, Mash (Hash-like) | **Default Value:** `{}` The raw data, as a Ruby Hash, that will be stored in the item. `search` **Ruby Type:** String | **Default Value:** `*:*` Search query that would match the same used for the clients, gets stored as a field in the item. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_vault_secret** resource in recipes: **To create a ‘foo’ item in an existing ‘bar’ data bag**: ``` chef_vault_secret 'foo' do data_bag 'bar' raw_data({ 'auth' => 'baz' }) admins 'jtimberman' search '*:*' end ``` **To allow multiple admins access to an item**: ``` chef_vault_secret 'root-password' do admins 'jtimberman,paulmooring' data_bag 'secrets' raw_data({ 'auth' => 'DoNotUseThisPasswordForRoot' }) search '*:*' end ``` chocolatey_config resource --------------------------- [chocolatey_config resource page](chocolatey_config/index) --- Use the **chocolatey_config** resource to add or remove Chocolatey configuration keys. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [Chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. **New in Chef Infra Client 14.3.** ### Syntax --- The full syntax for all of the properties that are available to the **chocolatey_config** resource is: ``` chocolatey_config 'name' do config_key String # default value: 'name' unless specified value String action Symbol # defaults to :set if not specified end ``` where: * `chocolatey_config` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `config_key` and `value` are the properties available to this resource. ### Actions --- The **chocolatey_config** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Sets a Chocolatey config value. (default) `:unset` Unsets a Chocolatey config value. ### Properties --- The **chocolatey_config** resource has the following properties: `config_key` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the config key name if it differs from the resource block’s name. `value` **Ruby Type:** String The value to set. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chocolatey_config** resource in recipes: **Set the Chocolatey cacheLocation config**: ``` chocolatey_config 'Set cacheLocation config' do config_key 'cacheLocation' value 'C:\temp\choco' end ``` **Unset a Chocolatey config**: ``` chocolatey_config 'BogusConfig' do action :unset end ``` chocolatey_feature resource ---------------------------- [chocolatey_feature resource page](chocolatey_feature/index) --- Use the **chocolatey_feature** resource to enable and disable Chocolatey features. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [Chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. **New in Chef Infra Client 15.1.** ### Syntax --- The full syntax for all of the properties that are available to the **chocolatey_feature** resource is: ``` chocolatey_feature 'name' do feature_name String # default value: 'name' unless specified action Symbol # defaults to :enable if not specified end ``` where: * `chocolatey_feature` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `feature_name` is the property available to this resource. ### Actions --- The **chocolatey_feature** resource has the following actions: `:disable` Disables a named Chocolatey feature. `:enable` Enables a named Chocolatey feature. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chocolatey_feature** resource has the following properties: `feature_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the Chocolatey feature to enable or disable. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chocolatey_feature** resource in recipes: **Enable the checksumFiles Chocolatey feature** ``` chocolatey_feature 'checksumFiles' do action :enable end ``` **Disable the checksumFiles Chocolatey feature** ``` chocolatey_feature 'checksumFiles' do action :disable end ``` chocolatey_package resource ---------------------------- [chocolatey_package resource page](chocolatey_package/index) --- Use the **chocolatey_package** resource to manage packages using the Chocolatey package manager on the Microsoft Windows platform. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. Warning The **chocolatey_package** resource must be specified as `chocolatey_package` and cannot be shortened to `package` in a recipe. **New in Chef Infra Client 12.7.** ### Syntax --- The full syntax for all of the properties that are available to the **chocolatey_package** resource is: ``` chocolatey_package 'name' do list_options String options String, Array package_name String, Array password String returns Integer, Array # default value: [0, 2] source String timeout String, Integer user String version String, Array action Symbol # defaults to :install if not specified end ``` where: * `chocolatey_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `list_options`, `options`, `package_name`, `password`, `returns`, `source`, `timeout`, `user`, and `version` are the properties available to this resource. ### Actions --- The **chocolatey_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and ensure that a package is the latest version. ### Properties --- The **chocolatey_package** resource has the following properties: `list_options` **Ruby Type:** String One (or more) additional list options that are passed to the command. New in Chef Infra Client 15.3 `options` **Ruby Type:** String, Array One (or more) additional options that are passed to the command. `package_name` **Ruby Type:** String, Array The name of the package. Default value: the name of the resource block. `password` **Ruby Type:** String The password to authenticate to the source. New in Chef Infra Client 15.3 `returns` **Ruby Type:** Integer, Array | **Default Value:** `[0, 2]` The exit code(s) returned by the `choco` command that indicate a successful action. See [Chocolatey Exit Codes](https://docs.chocolatey.org/en-us/choco/commands/info#exit-codes) for a complete list of exit codes used by Chocolatey. New in Chef Client 12.18 `source` **Ruby Type:** String The optional path to a package on the local file system or a reachable UNC path. Ensure that the path specified is to the **folder** containing the chocolatey package(s), not to the package itself. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `user` **Ruby Type:** String The username to authenticate feeds. New in Chef Infra Client 15.3 `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chocolatey_package** resource in recipes: **Install a Chocolatey package**: ``` chocolatey_package 'name of package' do action :install end ``` **Install a package with options with Chocolatey’s `--checksum` option**: ``` chocolatey_package 'name of package' do options '--checksum 1234567890' action :install end ``` chocolatey_source resource --------------------------- [chocolatey_source resource page](chocolatey_source/index) --- Use the **chocolatey_source** resource to add, remove, enable, or disable Chocolatey sources. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [Chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. **New in Chef Infra Client 14.3.** ### Syntax --- The full syntax for all of the properties that are available to the **chocolatey_source** resource is: ``` chocolatey_source 'name' do admin_only true, false # default value: false allow_self_service true, false # default value: false bypass_proxy true, false # default value: false cert String cert_password String password String priority Integer # default value: 0 source String source_name String # default value: 'name' unless specified username String action Symbol # defaults to :add if not specified end ``` where: * `chocolatey_source` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `admin_only`, `allow_self_service`, `bypass_proxy`, `cert`, `cert_password`, `password`, `priority`, `source`, `source_name`, and `username` are the properties available to this resource. ### Actions --- The **chocolatey_source** resource has the following actions: `:add` Adds a Chocolatey source (default) `:disable` Disables a Chocolatey source. **New in Chef Infra Client 15.1.** `:enable` Enables a Chocolatey source. **New in Chef Infra Client 15.1.** `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes a Chocolatey source. ### Properties --- The **chocolatey_source** resource has the following properties: `admin_only` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to set the source to be accessible to only admins. New in Chef Infra Client 15.1 `allow_self_service` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to set the source to be used for self service. New in Chef Infra Client 15.1 `bypass_proxy` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to bypass the system’s proxy settings to access the source. `cert` **Ruby Type:** String The certificate to use when authenticating against the source New in Chef Infra Client 17.7 `cert_password` **Ruby Type:** String The password for the certificate to use when authenticating against the source New in Chef Infra Client 17.7 `password` **Ruby Type:** String The password to use when authenticating against the source New in Chef Infra Client 17.7 `priority` **Ruby Type:** Integer | **Default Value:** `0` The priority level of the source. `source` **Ruby Type:** String The source URL. `source_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the source name if it differs from the resource block’s name. `username` **Ruby Type:** String The username to use when authenticating against the source New in Chef Infra Client 17.7 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chocolatey_source** resource in recipes: **Add a Chocolatey source** ``` chocolatey_source 'MySource' do source 'http://example.com/something' action :add end ``` **Remove a Chocolatey source** ``` chocolatey_source 'MySource' do action :remove end ``` cookbook_file resource ----------------------- [cookbook_file resource page](cookbook_file/index) --- Use the **cookbook_file** resource to transfer files from a sub-directory of `COOKBOOK_NAME/files/` to a specified path located on a host that is running Chef Infra Client. The file is selected according to file specificity, which allows different source files to be used based on the hostname, host platform (operating system, distro, or as appropriate), or platform version. Files that are located in the `COOKBOOK_NAME/files/default` sub-directory may be used on any platform. During a Chef Infra Client run, the checksum for each local file is calculated and then compared against the checksum for the same file as it currently exists in the cookbook on the Chef Infra Server. A file is not transferred when the checksums match. Only files that require an update are transferred from the Chef Infra Server to a node. ### Syntax --- A **cookbook_file** resource block manages files by using files that exist within a cookbook’s `/files` directory. For example, to write the home page for an Apache website: ``` cookbook_file '/var/www/customers/public_html/index.php' do source 'index.php' owner 'web_admin' group 'web_admin' mode '0755' action :create end ``` where: * `'/var/www/customers/public_html/index.php'` is path to the file to be created * `'index.php'` is a file in the `/files` directory in a cookbook that is used to create that file (the contents of the file in the cookbook will become the contents of the file on the node) * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **cookbook_file** resource is: ``` cookbook_file 'name' do atomic_update true, false backup Integer, false # default value: 5 cookbook String force_unlink true, false # default value: false group String, Integer inherits true, false manage_symlink_source true, false mode String, Integer owner String, Integer path String # default value: 'name' unless specified rights Hash source String, Array verify String, Block action Symbol # defaults to :create if not specified end ``` where: * `cookbook_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `atomic_update`, `backup`, `cookbook`, `force_unlink`, `group`, `inherits`, `manage_symlink_source`, `mode`, `owner`, `path`, `rights`, `source`, and `verify` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **cookbook_file** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the **file** resource.) ### Properties --- The **cookbook_file** resource has the following properties: `atomic_update` **Ruby Type:** true, false | **Default Value:** `False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.` Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the `client.rb` file. `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `cookbook` **Ruby Type:** String | **Default Value:** `The current cookbook name` The cookbook in which a file is located (if it is not located in the current cookbook). `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `true`, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `false`, Chef will follow the symlink and will manage the permissions and content of the symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String The path to the destination at which a file is to be created. For example: `file.txt`. Microsoft Windows: A path that begins with a forward slash (`/`) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (`/`) is not recommended. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String, Array | **Default Value:** `The resource block's name` The name of the file in `COOKBOOK_NAME/files/default` or the path to a file located in `COOKBOOK_NAME/files`. The path must include the file name and its extension. This can be used to distribute specific files depending upon the platform used - see [File Specificity](#cookbook-file-specificity) for more information. `verify` **Ruby Type:** String, Block A block or a string that returns `true` or `false`. A string, when `true` is executed as a system command. A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block is `true`, Chef Infra Client will continue to update the file as appropriate. For example, this should return `true`: ``` cookbook_file '/tmp/baz' do verify { 1 == 1 } end ``` This should return `true`: ``` cookbook_file '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` This should return `true`: ``` cookbook_file '/tmp/bar' do verify { 1 == 1} end ``` And this should return `true`: ``` cookbook_file '/tmp/foo' do verify do |path| true end end ``` Whereas, this should return `false`: ``` cookbook_file '/tmp/turtle' do verify '/usr/bin/false' end ``` If a string or a block return `false`, the Chef Infra Client run will stop and an error is returned. #### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(<NAME>) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### File Specificity A cookbook is frequently designed to work across many platforms and is often required to distribute a specific file to a specific platform. A cookbook can be designed to support the distribution of files across platforms, while ensuring that the correct file ends up on each system. The pattern for file specificity depends on two things: the lookup path and the source attribute. The first pattern that matches is used: 1. /host-$fqdn/$source 2. /$platform-$platform_version/$source 3. /$platform/$source 4. /default/$source 5. /$source Use an array with the `source` attribute to define an explicit lookup path. For example: ``` file '/conf.py' do source ['#{node.chef_environment}.py', 'conf.py'] end ``` The following example emulates the entire file specificity pattern by defining it as an explicit path: ``` file '/conf.py' do source %W( host-#{node['fqdn']}/conf.py #{node['platform']}-#{node['platform_version']}/conf.py #{node['platform']}/conf.py default/conf.py ) end ``` A cookbook may have a `/files` directory structure like this: ``` files/ host-foo.example.com ubuntu-20.04 ubuntu-20 ubuntu redhat-8.2 redhat-7.8 ... default ``` and a resource that looks something like the following: ``` cookbook_file '/usr/local/bin/apache2_module_conf_generate.pl' do source 'apache2_module_conf_generate.pl' mode '0755' owner 'root' group 'root' end ``` This resource is matched in the same order as the `/files` directory structure. For a node that is running Ubuntu 20.04, the second item would be the matching item and the location to which the file identified in the **cookbook_file** resource would be distributed: ``` host-foo.example.com/apache2_module_conf_generate.pl ubuntu-20.04/apache2_module_conf_generate.pl ubuntu-20/apache2_module_conf_generate.pl ubuntu/apache2_module_conf_generate.pl default/apache2_module_conf_generate.pl ``` If the `apache2_module_conf_generate.pl` file was located in the cookbook directory under `files/host-foo.example.com/`, the specified file(s) would only be copied to the machine with the domain name foo.example.com. **Host Notation** The naming of folders within cookbook directories must literally match the host notation used for file specificity matching. For example, if a host is named `foo.example.com`, the folder must be named `host-foo.example.com`. ### Examples --- The following examples demonstrate various approaches for using the **cookbook_file** resource in recipes: Transfer a file ``` cookbook_file 'file.txt' do mode '0755' end ``` Handle cookbook_file and package resources in the same recipe When a **cookbook_file** resource and a **package** resource are both called from within the same recipe, use the `flush_cache` attribute to dump the in-memory Yum cache, and then use the repository immediately to ensure that the correct package is installed: ``` cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' end package 'only-in-custom-repo' do action :install flush_cache [ :before ] end ``` Install repositories from a file, trigger a command, and force the internal cache to reload The following example shows how to install new Yum repositories from a file, where the installation of the repository triggers a creation of the Yum cache that forces the internal cache for Chef Infra Client to reload: ``` execute 'create-yum-cache' do command 'yum -q makecache' action :nothing end ruby_block 'reload-internal-yum-cache' do block do Chef::Provider::Package::Yum::YumCache.instance.reload end action :nothing end cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' notifies :run, 'execute[create-yum-cache]', :immediately notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately end ``` Use a case statement The following example shows how a case statement can be used to handle a situation where an application needs to be installed on multiple platforms, but where the install directories are different paths, depending on the platform: ``` cookbook_file 'application.pm' do path case node['platform'] when 'centos','redhat' '/usr/lib/version/1.2.3/dir/application.pm' when 'arch' '/usr/share/version/core_version/dir/application.pm' else '/etc/version/dir/application.pm' end source "application-#{node['languages']['perl']['version']}.pm" owner 'root' group 'root' mode '0755' end ``` Manage dotfiles The following example shows using the **directory** and **cookbook_file** resources to manage dotfiles. The dotfiles are defined by a JSON data structure similar to: ``` "files": { ".zshrc": { "mode": '0755', "source": "dot-zshrc" }, ".bashrc": { "mode": '0755', "source": "dot-bashrc" }, ".bash_profile": { "mode": '0755', "source": "dot-bash_profile" }, } ``` and then the following resources manage the dotfiles: ``` if u.has_key?('files') u['files'].each do |filename, file_data| directory "#{home_dir}/#{File.dirname(filename)}" do recursive true mode '0755' end if file_data['subdir'] cookbook_file "#{home_dir}/#{filename}" do source "#{u['id']}/#{file_data['source']}" owner 'u['id']' group 'group_id' mode 'file_data['mode']' ignore_failure true backup 0 end end ``` cron resource ------------- [cron resource page](cron/index) --- Use the **cron** resource to manage cron entries for time-based job scheduling. Properties for a schedule will default to * if not provided. The cron resource requires access to a crontab program, typically cron. Warning The cron resource should only be used to modify an entry in a crontab file. The `cron_d` resource directly manages `cron.d` files. This resource ships in Chef Infra Client 14.4 or later and can also be found in the [cron](https://github.com/chef-cookbooks/cron) cookbook) for previous Chef Infra Client releases. ### Syntax --- The full syntax for all of the properties that are available to the **cron** resource is: ``` cron 'name' do command String day Integer, String # default value: "*" environment Hash # default value: {} home String hour Integer, String # default value: "*" mailto String minute Integer, String # default value: "*" month Integer, String # default value: "*" path String shell String time Symbol time_out Hash # default value: {} user String # default value: "root" weekday Integer, String, Symbol # default value: "*" action Symbol # defaults to :create if not specified end ``` where: * `cron` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command`, `day`, `environment`, `home`, `hour`, `mailto`, `minute`, `month`, `path`, `shell`, `time`, `time_out`, `user`, and `weekday` are the properties available to this resource. ### Actions --- The **cron** resource has the following actions: `:create` Create an entry in a cron table file (crontab). If an entry already exists (but does not match), update that entry to match. (default) `:delete` Delete an entry from a cron table file (crontab). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **cron** resource has the following properties: `command` **Ruby Type:** String | `REQUIRED` The command to be run, or the path to a file that contains the command to be run. `day` **Ruby Type:** Integer, String | **Default Value:** `*` The day of month at which the cron entry should run (`1 - 31`). `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `home` **Ruby Type:** String Set the `HOME` environment variable. `hour` **Ruby Type:** Integer, String | **Default Value:** `*` The hour at which the cron entry is to run (`0 - 23`). `mailto` **Ruby Type:** String Set the `MAILTO` environment variable. `minute` **Ruby Type:** Integer, String | **Default Value:** `*` The minute at which the cron entry should run (`0 - 59`). `month` **Ruby Type:** Integer, String | **Default Value:** `*` The month in the year on which a cron entry is to run (`1 - 12`, `jan-dec`, or `*`). `path` **Ruby Type:** String Set the `PATH` environment variable. `shell` **Ruby Type:** String Set the `SHELL` environment variable. `time` **Ruby Type:** Symbol **Allowed Values:** `:annually, :daily, :hourly, :midnight, :monthly, :reboot, :weekly, :yearly` A time interval. `time_out` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of timeouts in the form of `({'OPTION' => 'VALUE'})`. Accepted valid options are: * `preserve-status` (BOOL, default: ‘false’), * `foreground` (BOOL, default: ‘false’), * `kill-after` (in seconds), * `signal` (a name like ‘HUP’ or a number) New in Chef Infra Client 15.7 `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that runs the command. If the user property is changed, the original user for the crontab program continues to run until that crontab program is deleted. This property is not applicable on the AIX platform. `weekday` **Ruby Type:** Integer, String, Symbol | **Default Value:** `*` The day of the week on which this entry is to run (`0-7`, `mon-sun`, `monday-sunday`, or `*`), where Sunday is both `0` and `7`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **cron** resource in recipes: **Run a program at a specified interval** ``` cron 'noop' do hour '5' minute '0' command '/bin/true' end ``` **Run an entry if a folder exists** ``` cron 'ganglia_tomcat_thread_max' do command "/usr/bin/gmetric -n 'tomcat threads max' -t uint32 -v '/usr/local/bin/tomcat-stat --thread-max'" only_if { ::File.exist?('/home/jboss') } end ``` **Run every Saturday, 8:00 AM** The following example shows a schedule that will run every hour at 8:00 each Saturday morning, and will then send an email to “<EMAIL>” after each run. ``` cron 'name_of_cron_entry' do minute '0' hour '8' weekday '6' mailto '<EMAIL>' action :create end ``` **Run once a week** ``` cron 'cookbooks_report' do minute '0' hour '0' weekday '1' user 'chefio' mailto '<EMAIL>' home '/srv/supermarket/shared/system' command %W{ cd /srv/supermarket/current && env RUBYLIB="/srv/supermarket/current/lib" RAILS_ASSET_ID=`git rev-parse HEAD` RAILS_ENV="#{rails_env}" bundle exec rake cookbooks_report }.join(' ') action :create end ``` **Run only in November** The following example shows a schedule that will run at 8:00 PM, every weekday (Monday through Friday), but only in November: ``` cron 'name_of_cron_entry' do minute '0' hour '20' day '*' month '11' weekday '1-5' action :create end ``` cron_access resource --------------------- [cron_access resource page](cron_access/index) --- Use the **cron_access** resource to manage cron’s cron.allow and cron.deny files. Note This resource previously shipped in the `cron` cookbook as `cron_manage`, which it can still be used as for backwards compatibility with existing Chef Infra Client releases. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **cron_access** resource is: ``` cron_access 'name' do user String # default value: 'name' unless specified action Symbol # defaults to :allow if not specified end ``` where: * `cron_access` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `user` is the property available to this resource. ### Actions --- The **cron_access** resource has the following actions: `:allow` Add the user to the cron.allow file. (default) `:deny` Add the user to the cron.deny file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **cron_access** resource has the following properties: `user` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the user name if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **cron_access** resource in recipes: **Add the mike user to cron.allow** ``` cron_access 'mike' ``` **Add the mike user to cron.deny** ``` cron_access 'mike' do action :deny end ``` **Specify the username with the user property** ``` cron_access 'Deny the jenkins user access to cron for security purposes' do user 'jenkins' action :deny end ``` cron_d resource ---------------- [cron_d resource page](cron_d/index) --- Use the **cron_d** resource to manage cron job files in the `/etc/cron.d` directory. Warning Chef Infra Client also ships with the **cron** resource for managing the monolithic `/etc/crontab` file on platforms that lack cron.d support. See the [cron resource](cron/index) for information on using that resource. **New in Chef Infra Client 14.4.** ### Syntax --- A **cron_d** resource block manages cron.d files. For example, to get a weekly cookbook report from the Chef Supermarket: ``` cron_d 'cookbooks_report' do action :create minute '0' hour '0' weekday '1' user 'getchef' mailto '<EMAIL>' home '/srv/supermarket/shared/system' command %W{ cd /srv/supermarket/current && env RUBYLIB="/srv/supermarket/current/lib" RAILS_ASSET_ID=`git rev-parse HEAD` RAILS_ENV="#{rails_env}" bundle exec rake cookbooks_report }.join(' ') end ``` The full syntax for all of the properties that are available to the **cron_d** resource is: ``` cron_d 'name' do command String comment String cron_name String # default value: 'name' unless specified day Integer, String # default value: "*" environment Hash # default value: {} home String hour Integer, String # default value: "*" mailto String minute Integer, String # default value: "*" mode String, Integer # default value: "0600" month Integer, String # default value: "*" path String predefined_value String random_delay Integer shell String time_out Hash # default value: {} user String # default value: "root" weekday Integer, String, Symbol # default value: "*" action Symbol # defaults to :create if not specified end ``` where: * `cron_d` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command`, `comment`, `cron_name`, `day`, `environment`, `home`, `hour`, `mailto`, `minute`, `mode`, `month`, `path`, `predefined_value`, `random_delay`, `shell`, `time_out`, `user`, and `weekday` are the properties available to this resource. ### Actions --- The **cron_d** resource has the following actions: `:create` (default) `:create_if_missing` Add a cron definition file to `/etc/cron.d`, but do not update an existing file. `:delete` Remove a cron definition file from `/etc/cron.d` if it exists. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **cron_d** resource has the following properties: `command` **Ruby Type:** String | `REQUIRED` The command to be run, or the path to a file that contains the command to be run. `comment` **Ruby Type:** String A comment to place in the cron.d file. `cron_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the cron name if it differs from the resource block’s name. `day` **Ruby Type:** Integer, String | **Default Value:** `*` The day of month at which the cron entry should run (`1 - 31`). `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `home` **Ruby Type:** String Set the `HOME` environment variable. `hour` **Ruby Type:** Integer, String | **Default Value:** `*` The hour at which the cron entry is to run (`0 - 23`). `mailto` **Ruby Type:** String Set the `MAILTO` environment variable. `minute` **Ruby Type:** Integer, String | **Default Value:** `*` The minute at which the cron entry should run (`0 - 59`). `mode` **Ruby Type:** String, Integer | **Default Value:** `0600` The octal mode of the generated crontab file. `month` **Ruby Type:** Integer, String | **Default Value:** `*` The month in the year on which a cron entry is to run (`1 - 12`, `jan-dec`, or `*`). `path` **Ruby Type:** String Set the `PATH` environment variable. `predefined_value` **Ruby Type:** String **Allowed Values:** `"@annually", "@daily", "@hourly", "@midnight", "@monthly", "@reboot", "@weekly", "@yearly"` Schedule your cron job with one of the special predefined value instead of ** * pattern. `random_delay` **Ruby Type:** Integer Set the `RANDOM_DELAY` environment variable in the cron.d file. `shell` **Ruby Type:** String Set the `SHELL` environment variable. `time_out` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of timeouts in the form of `({'OPTION' => 'VALUE'})`. Accepted valid options are: * `preserve-status` (BOOL, default: ‘false’), * `foreground` (BOOL, default: ‘false’), * `kill-after` (in seconds), * `signal` (a name like ‘HUP’ or a number) New in Chef Infra Client 15.7 `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that runs the command. `weekday` **Ruby Type:** Integer, String, Symbol | **Default Value:** `*` The day of the week on which this entry is to run (`0-7`, `mon-sun`, `monday-sunday`, or `*`), where Sunday is both `0` and `7`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **cron_d** resource in recipes: **Run a program on the fifth hour of the day** ``` cron_d 'noop' do hour '5' minute '0' command '/bin/true' end ``` **Run an entry if a folder exists** ``` cron_d 'ganglia_tomcat_thread_max' do command "/usr/bin/gmetric -n 'tomcat threads max' -t uint32 -v '/usr/local/bin/tomcat-stat --thread-max'" only_if { ::File.exist?('/home/jboss') } end ``` **Run an entry every Saturday, 8:00 AM** ``` cron_d 'name_of_cron_entry' do minute '0' hour '8' weekday '6' mailto '<EMAIL>' command '/bin/true' action :create end ``` **Run an entry at 8:00 PM, every weekday (Monday through Friday), but only in November** ``` cron_d 'name_of_cron_entry' do minute '0' hour '20' day '*' month '11' weekday '1-5' command '/bin/true' action :create end ``` **Remove a cron job by name**: ``` cron_d 'job_to_remove' do action :delete end ``` csh resource ------------ [csh resource page](csh/index) --- Use the **csh** resource to execute scripts using the csh interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **csh** resource block executes scripts using csh: ``` csh 'hello world' do code <<-EOH echo "Hello world!" echo "Current directory: " $cwd EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **csh** resource is: ``` csh 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `csh` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **csh** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. ### Properties --- The **csh** resource has the following properties: `code` **Ruby Type:** String | `REQUIRED` A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. directory resource ------------------ [directory resource page](directory/index) --- Use the **directory** resource to manage a directory, which is a hierarchy of folders that comprises all of the information stored on a computer. The root directory is the top-level, under which the rest of the directory is organized. The directory resource uses the name property to specify the path to a location in a directory. Typically, permission to access that location in the directory is required. ### Syntax --- A **directory** resource block declares a directory and the permissions needed on that directory. For example: ``` directory '/etc/apache2' do owner 'root' group 'root' mode '0755' action :create end ``` where: * `'/etc/apache2'` specifies the directory * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **directory** resource is: ``` directory 'name' do group String, Integer inherits true, false mode String, Integer owner String, Integer path String # defaults to 'name' if not specified recursive true, false rights Hash action Symbol # defaults to :create if not specified end ``` where: * `directory` is the resource. * `name` is the name of the resource block; when the `path` property is not specified, `name` is also the path to the directory, from the root * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `group`, `inherits`, `mode`, `owner`, `path`, `recursive`, and `rights` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **directory** resource has the following actions: `:create` Default. Create a directory. If a directory already exists (but does not match), update that directory to match. `:delete` Delete a directory. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **directory** resource has the following properties: `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the directory already exists, the existing mode on the directory is used. If `mode` is not specified, the directory does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'`, and then applies the umask for the system on which the directory is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the `name` of the resource block. See “Syntax” section above for more information. `recursive` **Ruby Type:** true, false | **Default Value:** `false` Create or delete parent directories recursively. For the owner, group, and mode properties, the value of this property applies only to the leaf directory. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. #### Recursive Directories The **remote_directory** resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the `recursive` attribute only applies `group`, `mode`, and `owner` attribute values to the remote directory itself and any inner directories the resource copies. A directory structure: ``` /foo /bar /baz ``` The following example shows a way create a file in the `/baz` directory: ``` remote_directory '/foo/bar/baz' do owner 'root' group 'root' mode '0755' action :create end ``` But with this example, the `group`, `mode`, and `owner` attribute values will only be applied to `/baz`. Which is fine, if that’s what you want. But most of the time, when the entire `/foo/bar/baz` directory structure is not there, you must be explicit about each directory. For example: ``` %w( /foo /foo/bar /foo/bar/baz ).each do |path| remote_directory path do owner 'root' group 'root' mode '0755' end end ``` This approach will create the correct hierarchy—`/foo`, then `/bar` in `/foo`, and then `/baz` in `/bar`—and also with the correct attribute values for `group`, `mode`, and `owner`. #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **directory** resource in recipes: Create a directory ``` directory '/tmp/something' do owner 'root' group 'root' mode '0755' action :create end ``` Create a directory in Microsoft Windows ``` directory "C:\\tmp\\something" do rights :full_control, "DOMAIN\\User" inherits false action :create end ``` or: ``` directory 'C:\tmp\something' do rights :full_control, 'DOMAIN\User' inherits false action :create end ``` Note The difference between the two previous examples is the single- versus double-quoted strings, where if the double quotes are used, the backslash character (`\`) must be escaped using the Ruby escape character (which is a backslash). Create a directory recursively ``` %w{dir1 dir2 dir3}.each do |dir| directory "/tmp/mydirs/#{dir}" do mode '0755' owner 'root' group 'root' action :create recursive true end end ``` Delete a directory ``` directory '/tmp/something' do recursive true action :delete end ``` Set directory permissions using a variable The following example shows how read/write/execute permissions can be set using a variable named `user_home`, and then for owners and groups on any matching node: ``` user_home = "/#{node[:matching_node][:user]}" directory user_home do owner 'node[:matching_node][:user]' group 'node[:matching_node][:group]' mode '0755' action :create end ``` where `matching_node` represents a type of node. For example, if the `user_home` variable specified `{node[:nginx]...}`, a recipe might look similar to: ``` user_home = "/#{node[:nginx][:user]}" directory user_home do owner 'node[:nginx][:user]' group 'node[:nginx][:group]' mode '0755' action :create end ``` Set directory permissions for a specific type of node The following example shows how permissions can be set for the `/certificates` directory on any node that is running Nginx. In this example, permissions are being set for the `owner` and `group` properties as `root`, and then read/write permissions are granted to the root. ``` directory "#{node[:nginx][:dir]}/shared/certificates" do owner 'root' group 'root' mode '0755' recursive true end ``` Reload the configuration The following example shows how to reload the configuration of a chef-client using the **remote_file** resource to: * using an if statement to check whether the plugins on a node are the latest versions * identify the location from which Ohai plugins are stored * using the `notifies` property and a **ruby_block** resource to trigger an update (if required) and to then reload the client.rb file. ``` directory 'node[:ohai][:plugin_path]' do owner 'chef' recursive true end ruby_block 'reload_config' do block do Chef::Config.from_file('/etc/chef/client.rb') end action :nothing end if node[:ohai].key?(:plugins) node[:ohai][:plugins].each do |plugin| remote_file node[:ohai][:plugin_path] +"/#{plugin}" do source plugin owner 'chef' notifies :run, 'ruby_block[reload_config]', :immediately end end end ``` Manage dotfiles The following example shows using the **directory** and **cookbook_file** resources to manage dotfiles. The dotfiles are defined by a JSON data structure similar to: ``` "files": { ".zshrc": { "mode": '0755', "source": "dot-zshrc" }, ".bashrc": { "mode": '0755', "source": "dot-bashrc" }, ".bash_profile": { "mode": '0755', "source": "dot-bash_profile" }, } ``` and then the following resources manage the dotfiles: ``` if u.has_key?('files') u['files'].each do |filename, file_data| directory "#{home_dir}/#{File.dirname(filename)}" do recursive true mode '0755' end if file_data['subdir'] cookbook_file "#{home_dir}/#{filename}" do source "#{u['id']}/#{file_data['source']}" owner 'u['id']' group 'group_id' mode 'file_data['mode']' ignore_failure true backup 0 end end ``` dmg_package resource --------------------- [dmg_package resource page](dmg_package/index) --- Use the **dmg_package** resource to install a package from a .dmg file. The resource will retrieve the dmg file from a remote URL, mount it using macOS' `hdidutil`, copy the application (.app directory) to the specified destination (`/Applications`), and detach the image using `hdiutil`. The dmg file will be stored in the `Chef::Config[:file_cache_path]`. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **dmg_package** resource is: ``` dmg_package 'name' do accept_eula true, false # default value: false allow_untrusted true, false # default value: false app String # default value: 'name' unless specified checksum String destination String # default value: "/Applications" dmg_name String # default value: The value passed for the application name. dmg_passphrase String file String headers Hash owner String, Integer package_id String source String type String # default value: "app" volumes_dir String # default value: The value passed for the application name. action Symbol # defaults to :install if not specified end ``` where: * `dmg_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_eula`, `allow_untrusted`, `app`, `checksum`, `destination`, `dmg_name`, `dmg_passphrase`, `file`, `headers`, `owner`, `package_id`, `source`, `type`, and `volumes_dir` are the properties available to this resource. ### Actions --- The **dmg_package** resource has the following actions: `:install` Installs the application. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **dmg_package** resource has the following properties: `accept_eula` **Ruby Type:** true, false | **Default Value:** `false` Specify whether to accept the EULA. Certain dmg files require acceptance of EULA before mounting. `allow_untrusted` **Ruby Type:** true, false | **Default Value:** `false` Allow installation of packages that do not have trusted certificates. `app` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the application as it appears in the `/Volumes` directory if it differs from the resource block’s name. `checksum` **Ruby Type:** String The sha256 checksum of the `.dmg` file to download. `destination` **Ruby Type:** String | **Default Value:** `/Applications` The directory to copy the `.app` into. `dmg_name` **Ruby Type:** String | **Default Value:** `The value passed for the application name.` The name of the `.dmg` file if it differs from that of the app, or if the name has spaces. `dmg_passphrase` **Ruby Type:** String Specify a passphrase to be used to decrypt the `.dmg` file during the mount process. `file` **Ruby Type:** String The absolute path to the `.dmg` file on the local system. `headers` **Ruby Type:** Hash Allows custom HTTP headers (like cookies) to be set on the `remote_file` resource. `owner` **Ruby Type:** String, Integer The user that should own the package installation. `package_id` **Ruby Type:** String The package ID that is registered with `pkgutil` when a `pkg` or `mpkg` is installed. `source` **Ruby Type:** String The remote URL that is used to download the `.dmg` file, if specified. `type` **Ruby Type:** String | **Default Value:** `app` **Allowed Values:** `"app", "mpkg", "pkg"` The type of package. `volumes_dir` **Ruby Type:** String | **Default Value:** `The value passed for the application name.` The directory under `/Volumes` where the `dmg` is mounted if it differs from the name of the `.dmg` file. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **dmg_package** resource in recipes: **Install Google Chrome via the DMG package**: ``` dmg_package 'Google Chrome' do dmg_name 'googlechrome' source 'https://dl-ssl.google.com/chrome/mac/stable/GGRM/googlechrome.dmg' checksum '7daa2dc5c46d9bfb14f1d7ff4b33884325e5e63e694810adc58f14795165c91a' action :install end ``` **Install VirtualBox from the .mpkg**: ``` dmg_package 'Virtualbox' do source 'http://dlc.sun.com.edgesuite.net/virtualbox/4.0.8/VirtualBox-4.0.8-71778-OSX.dmg' type 'mpkg' end ``` **Install pgAdmin and automatically accept the EULA**: ``` dmg_package 'pgAdmin3' do source 'http://wwwmaster.postgresql.org/redir/198/h/pgadmin3/release/v1.12.3/osx/pgadmin3-1.12.3.dmg' checksum '9435f79d5b52d0febeddfad392adf82db9df159196f496c1ab139a6957242ce9' accept_eula true end ``` dnf_package resource --------------------- [dnf_package resource page](dnf_package/index) --- Use the **dnf_package** resource to install, upgrade, and remove packages with DNF for Fedora and RHEL 8+. The dnf_package resource is able to resolve provides data for packages much like DNF can do when it is run from the command line. This allows a variety of options for installing packages, like minimum versions, virtual provides and library names. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. **New in Chef Infra Client 12.18.** ### Syntax --- A **dnf_package** resource block manages a package on a node, typically by installing it. The simplest use of the **dnf_package** resource is: ``` dnf_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **dnf_package** resource is: ``` dnf_package 'name' do allow_downgrade true, false # default value: true arch String, Array flush_cache Hash # default value: {"before"=>false, "after"=>false} options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `dnf_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `arch`, `flush_cache`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **dnf_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:lock` Locks the DNF package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:unlock` Unlocks the DNF package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **dnf_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. `arch` **Ruby Type:** String, Array The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name. `flush_cache` **Ruby Type:** Hash | **Default Value:** `{"before"=>false, "after"=>false}` Flush the in-memory cache before or after a DNF operation that installs, upgrades, or removes a package. DNF automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while a Chef Infra Client run is in-progress. As an array: ``` dnf_package 'some-package' do #... flush_cache [ :before ] #... end ``` and as a Hash: ``` dnf_package 'some-package' do #... flush_cache( { :after => true } ) #... end ``` Note The `flush_cache` property does not flush the local DNF cache! Use dnf tools—`dnf clean metadata`, `dnf clean packages`, `dnf clean all`—to clean the local DNF cache. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. This property is ignored when using the `:upgrade` action. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **dnf_package** resource in recipes: Install an exact version ``` dnf_package 'netpbm = 10.35.58-8.el5' ``` Install a minimum version ``` dnf_package 'netpbm >= 10.35.58-8.el5' ``` Install a minimum version using the default action ``` dnf_package 'netpbm' ``` To install a package ``` dnf_package 'netpbm' do action :install end ``` To install a partial minimum version ``` dnf_package 'netpbm >= 10' ``` To install a specific architecture ``` dnf_package 'netpbm' do arch 'i386' end ``` or: ``` dnf_package 'netpbm.x86_64' ``` To install a specific version-release ``` dnf_package 'netpbm' do version '10.35.58-8.el5' end ``` To install a specific version (even when older than the current) ``` dnf_package 'tzdata' do version '2011b-1.el5' end ``` Handle cookbook_file and dnf_package resources in the same recipe When a **cookbook_file** resource and a **dnf_package** resource are both called from within the same recipe, use the `flush_cache` attribute to dump the in-memory DNF cache, and then use the repository immediately to ensure that the correct package is installed: ``` cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' end dnf_package 'only-in-custom-repo' do action :install flush_cache [ :before ] end ``` dpkg_package resource ---------------------- [dpkg_package resource page](dpkg_package/index) --- Use the **dpkg_package** resource to manage packages for the dpkg platform. When a package is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. ### Syntax --- A **dpkg_package** resource block manages a package on a node, typically by installing it. The simplest use of the **dpkg_package** resource is: ``` dpkg_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **dpkg_package** resource is: ``` dpkg_package 'name' do options String, Array package_name String, Array response_file String response_file_variables Hash source String, Array timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `dpkg_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `response_file`, `response_file_variables`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **dpkg_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. ### Properties --- The **dpkg_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `response_file` **Ruby Type:** String The direct path to the file used to pre-seed a package. `response_file_variables` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of response file variables in the form of {‘VARIABLE’ => ‘VALUE’}. `source` **Ruby Type:** String, Array The path to a package in the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **dpkg_package** resource in recipes: Install a package ``` dpkg_package 'wget_1.13.4-2ubuntu1.4_amd64.deb' do source '/foo/bar/wget_1.13.4-2ubuntu1.4_amd64.deb' action :install end ``` dsc_resource resource ---------------------- [dsc_resource resource page](dsc_resource/index) --- Windows PowerShell is a task-based command-line shell and scripting language developed by Microsoft. Windows PowerShell uses a document-oriented approach for managing Microsoft Windows-based machines, similar to the approach that is used for managing Unix and Linux-based machines. Windows PowerShell is [a tool-agnostic platform](https://docs.microsoft.com/en-us/powershell/scripting/powershell-scripting) that supports using Chef for configuration management. Desired State Configuration (DSC) is a feature of Windows PowerShell that provides [a set of language extensions, cmdlets, and resources](https://docs.microsoft.com/en-us/powershell/dsc/overview) that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell. The **dsc_resource** resource allows any DSC resource to be used in a Chef recipe, as well as any custom resources that have been added to your Windows PowerShell environment. Microsoft [frequently adds new resources](https://github.com/powershell/DscResources) to the DSC resource collection. Warning Using the **dsc_resource** has the following requirements: * Windows Management Framework (WMF) 5.0 (or higher) * The **dsc_resource** resource can only use binary- or script-based resources. Composite DSC resources may not be used. This is because composite resources aren’t “real” resources from the perspective of the Local Configuration Manager (LCM). Composite resources are used by the “configuration” keyword from the `PSDesiredStateConfiguration` module, and then evaluated in that context. When using DSC to create the configuration document (the Managed Object Framework (MOF) file) from the configuration command, the composite resource is evaluated. Any individual resources from that composite resource are written into the Managed Object Framework (MOF) document. As far as the Local Configuration Manager (LCM) is concerned, there is no such thing as a composite resource. Unless that changes, the **dsc_resource** resource and/or `Invoke-DscResource` command cannot directly use them. ### Syntax --- A **dsc_resource** resource block allows DSC resources to be used in a Chef recipe. For example, the DSC `Archive` resource: ``` Archive ExampleArchive { Ensure = "Present" Path = "C:\Users\Public\Documents\example.zip" Destination = "C:\Users\Public\Documents\ExtractionPath" } ``` and then the same **dsc_resource** with Chef: ``` dsc_resource 'example' do resource :archive property :ensure, 'Present' property :path, "C:\Users\Public\Documents\example.zip" property :destination, "C:\Users\Public\Documents\ExtractionPath" end``` ``` The full syntax for all of the properties that are available to the **dsc_resource** resource is: ``` dsc_resource 'name' do module_name String module_version String property Symbol reboot_action Symbol # default value: :nothing resource Symbol timeout Integer action Symbol # defaults to :run if not specified end ``` where: * `dsc_resource` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `property` is zero (or more) properties in the DSC resource, where each property is entered on a separate line, `:dsc_property_name` is the case-insensitive name of that property, and `"property_value"` is a Ruby value to be applied by Chef Infra Client * `module_name`, `module_version`, `property`, `reboot_action`, `resource`, and `timeout` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **dsc_resource** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Use to run the DSC configuration defined as defined in this resource. ### Properties --- The **dsc_resource** resource has the following properties: `module_name` **Ruby Type:** String The name of the module from which a DSC resource originates. If this property is not specified, it will be inferred. `module_version` **Ruby Type:** String The version number of the module to use. PowerShell 5.0.10018.0 (or higher) supports having multiple versions of a module installed. This should be specified along with the `module_name`. New in Chef Client 12.21 `property` **Ruby Type:** Symbol A property from a Desired State Configuration (DSC) resource. Use this property multiple times, one for each property in the Desired State Configuration (DSC) resource. The format for this property must follow `property :dsc_property_name, "property_value"` for each DSC property added to the resource block. The `:dsc_property_name` must be a symbol. Use the following Ruby types to define `property_value`: | Ruby | Windows PowerShell | | --- | --- | | `Array` | `Object[]` | | `Chef::Util::Powershell:PSCredential` | `PSCredential` | | `False` | `bool($false)` | | `Fixnum` | `Integer` | | `Float` | `Double` | | `Hash` | `Hashtable` | | `True` | `bool($true)` | These are converted into the corresponding Windows PowerShell type during a Chef Infra Client run. `reboot_action` **Ruby Type:** Symbol | **Default Value:** `:nothing` **Allowed Values:** `:nothing, :reboot_now, :request_reboot` Use to request an immediate reboot or to queue a reboot using the :reboot_now (immediate reboot) or :request_reboot (queued reboot) actions built into the reboot resource. New in Chef Client 12.6 `resource` **Ruby Type:** Symbol The name of the DSC resource. This value is case-insensitive and must be a symbol that matches the name of the DSC resource. For built-in DSC resources, use the following values: | Value | Description | | --- | --- | | `:archive` | Use to [unpack archive (.zip) files](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/archiveresource). | | `:environment` | Use to [manage system environment variables](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/environmentresource). | | `:file` | Use to [manage files and directories](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/fileresource). | | `:group` | Use to [manage local groups](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/groupresource). | | `:log` | Use to [log configuration messages](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/logresource). | | `:package` | Use to [install and manage packages](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/packageresource). | | `:registry` | Use to [manage registry keys and registry key values](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/registryresource). | | `:script` | Use to [run PowerShell script blocks](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/scriptresource). | | `:service` | Use to [manage services](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/serviceresource). | | `:user` | Use to [manage local user accounts](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/userresource). | | `:windowsfeature` | Use to [add or remove Windows features and roles](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/windowsfeatureresource). | | `:windowsoptionalfeature` | Use to configure Microsoft Windows optional features. | | `:windowsprocess` | Use to [configure Windows processes](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/windowsprocessresource). | Any DSC resource may be used in a Chef recipe. For example, the DSC Resource Kit contains resources for [configuring Active Directory components](http://www.powershellgallery.com/packages/xActiveDirectory/2.8.0.0), such as `xADDomain`, `xADDomainController`, and `xADUser`. Assuming that these resources are available to Chef Infra Client, the corresponding values for the `resource` attribute would be: `:xADDomain`, `:xADDomainController`, and `xADUser`. `timeout` **Ruby Type:** Integer The amount of time (in seconds) a command is to wait before timing out. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **dsc_resource** resource in recipes: Open a Zip file ``` dsc_resource 'example' do resource :archive property :ensure, 'Present' property :path, 'C:\Users\Public\Documents\example.zip' property :destination, 'C:\Users\Public\Documents\ExtractionPath' end ``` Manage users and groups ``` dsc_resource 'demogroupadd' do resource :group property :groupname, 'demo1' property :ensure, 'present' end dsc_resource 'useradd' do resource :user property :username, 'Foobar1' property :fullname, 'Foobar1' property :password, ps_credential('P@assword!') property :ensure, 'present' end dsc_resource 'AddFoobar1ToUsers' do resource :Group property :GroupName, 'demo1' property :MembersToInclude, ['Foobar1'] end ``` Create and register a windows service The following example creates a windows service, defines it’s execution path, and prevents windows from starting the service in case the executable is not at the defined location: ``` dsc_resource 'NAME' do resource :service property :name, 'NAME' property :startuptype, 'Disabled' property :path, 'D:\\Sites\\Site_name\file_to_run.exe' property :ensure, 'Present' property :state, 'Stopped' end ``` Create a test message queue The following example creates a file on a node (based on one that is located in a cookbook), unpacks the `MessageQueue.zip` Windows PowerShell module, and then uses the **dsc_resource** to ensure that Message Queuing (MSMQ) sub-features are installed, a test queue is created, and that permissions are set on the test queue: ``` cookbook_file 'cMessageQueue.zip' do path "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip" action :create_if_missing end windows_zipfile "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" do source "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip" action :unzip end dsc_resource 'install-sub-features' do resource :windowsfeature property :ensure, 'Present' property :name, 'msmq' property :IncludeAllSubFeature, true end dsc_resource 'create-test-queue' do resource :cPrivateMsmqQueue property :ensure, 'Present' property :name, 'Test_Queue' end dsc_resource 'set-permissions' do resource :cPrivateMsmqQueuePermissions property :ensure, 'Present' property :name, 'Test_Queue_Permissions' property :QueueNames, 'Test_Queue' property :ReadUsers, node['msmq']['read_user'] end ``` Example to show usage of module properties ``` dsc_resource 'test-cluster' do resource :xCluster module_name 'xFailOverCluster' module_version '1.6.0.0' property :name, 'TestCluster' property :staticipaddress, '10.0.0.3' property :domainadministratorcredential, ps_credential('abcd') end ``` dsc_script resource -------------------- [dsc_script resource page](dsc_script/index) --- Windows PowerShell is a task-based command-line shell and scripting language developed by Microsoft. Windows PowerShell uses a document-oriented approach for managing Microsoft Windows-based machines, similar to the approach that is used for managing Unix and Linux-based machines. Windows PowerShell is [a tool-agnostic platform](https://docs.microsoft.com/en-us/powershell/scripting/powershell-scripting) that supports using Chef for configuration management. Desired State Configuration (DSC) is a feature of Windows PowerShell that provides [a set of language extensions, cmdlets, and resources](https://docs.microsoft.com/en-us/powershell/dsc/overview) that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell. Many DSC resources are comparable to built-in Chef Infra resources. For example, both DSC and Chef have **file**, **package**, and **service** resources. The **dsc_script** resource is most useful for those DSC resources that do not have a direct comparison to a resource in Chef, such as the `Archive` resource, a custom DSC resource, an existing DSC script that performs an important task, and so on. Use the **dsc_script** resource to embed the code that defines a DSC configuration directly within a Chef Infra recipe. Note Windows PowerShell 4.0 is required for using the **dsc_script** resource with Chef Infra. Note The WinRM service must be enabled. (Use `winrm quickconfig` to enable the service.) Warning The **dsc_script** resource may not be used in the same run-list with the **dsc_resource**. This is because the **dsc_script** resource requires that `RefreshMode` in the Local Configuration Manager be set to `Push`, whereas the **dsc_resource** resource requires it to be set to `Disabled`. ### Syntax --- A **dsc_script** resource block embeds the code that defines a DSC configuration directly within a Chef recipe: ``` dsc_script 'get-dsc-resource-kit' do code <<-EOH Archive reskit { ensure = 'Present' path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" } EOH end ``` where: * the **remote_file** resource is first used to download the `DSCResourceKit620082014.zip` file. The full syntax for all of the properties that are available to the **dsc_script** resource is: ``` dsc_script 'name' do code String command String configuration_data String configuration_data_script String configuration_name String cwd String environment Hash flags Hash imports Array timeout Integer action Symbol # defaults to :run if not specified end ``` where: * `dsc_script` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `command`, `configuration_data`, `configuration_data_script`, `configuration_name`, `cwd`, `environment`, `flags`, `imports`, and `timeout` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **dsc_script** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Use to run the DSC configuration defined as defined in this resource. ### Properties --- The **dsc_script** resource has the following properties: `code` **Ruby Type:** String The code for the DSC configuration script. This property may not be used in conjunction with the `command` property. `command` **Ruby Type:** String The path to a valid Windows PowerShell data file that contains the DSC configuration script. This data file must be capable of running independently of Chef and must generate a valid DSC configuration. This property may not be used in conjunction with the `code` property. `configuration_data` **Ruby Type:** String The configuration data for the DSC script. The configuration data must be [a valid Windows PowerShell data file](https://docs.microsoft.com/en-us/powershell/). This property may not be used in conjunction with the `configuration_data_script` property. `configuration_data_script` **Ruby Type:** String The path to a valid Windows PowerShell data file that also contains a node called `localhost`. This property may not be used in conjunction with the `configuration_data` property. `configuration_name` **Ruby Type:** String The name of a valid Windows PowerShell cmdlet. The name may only contain letter (a-z, A-Z), number (0-9), and underscore (_) characters and should start with a letter. The name may not be null or empty. This property may not be used in conjunction with the `code` property. `cwd` **Ruby Type:** String The current working directory. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of ({‘ENV_VARIABLE’ => ‘VALUE’}). (These variables must exist for a command to be run successfully). `flags` **Ruby Type:** Hash Pass parameters to the DSC script that is specified by the `command` property. Parameters are defined as key-value pairs, where the value of each key is the parameter to pass. This property may not be used in the same recipe as the `code` property. For example: `flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' })`. `imports` **Ruby Type:** Array Warning This property **MUST** be used with the `code` attribute. Use to import DSC resources from a module. To import all resources from a module, specify only the module name: ``` imports 'module_name' ``` To import specific resources, specify the module name, and then specify the name for each resource in that module to import: ``` imports 'module_name', 'resource_name_a', 'resource_name_b', ... ``` For example, to import all resources from a module named `cRDPEnabled`: ``` imports 'cRDPEnabled' ``` To import only the `PSHOrg_cRDPEnabled` resource: ``` imports 'cRDPEnabled', 'PSHOrg_cRDPEnabled' ``` `timeout` **Ruby Type:** Integer The amount of time (in seconds) a command is to wait before timing out. #### ps_credential Helper Use the `ps_credential` helper to embed a `PSCredential` object— [a set of security credentials, such as a user name or password](https://technet.microsoft.com/en-us/magazine/ff714574.aspx) —within a script, which allows that script to be run using security credentials. For example, assuming the `CertificateID` is configured in the local configuration manager, the `SeaPower1@3` object is created and embedded within the `seapower-user` script: ``` dsc_script 'seapower-user' do code <<-EOH User AlbertAtom { UserName = 'AlbertAtom' Password = #{ps_credential('SeaPower1@3')} } EOH configuration_data <<-EOH @{ AllNodes = @( @{ NodeName = "localhost"; CertificateID = 'A8D1234559F349F7EF19104678908F701D4167' } ) } EOH end ``` ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **dsc_script** resource in recipes: Specify DSC code directly DSC data can be specified directly in a recipe: ``` dsc_script 'emacs' do code <<-EOH Environment 'texteditor' { Name = 'EDITOR' Value = 'c:\\emacs\\bin\\emacs.exe' } EOH end ``` Specify DSC code using a Windows PowerShell data file Use the `command` property to specify the path to a Windows PowerShell data file. For example, the following Windows PowerShell script defines the `DefaultEditor`: ``` Configuration 'DefaultEditor' { Environment 'texteditor' { Name = 'EDITOR' Value = 'c:\emacs\bin\emacs.exe' } } ``` Use the following recipe to specify the location of that data file: ``` dsc_script 'DefaultEditor' do command 'c:\dsc_scripts\emacs.ps1' end ``` Pass parameters to DSC configurations If a DSC script contains configuration data that takes parameters, those parameters may be passed using the `flags` property. For example, the following Windows PowerShell script takes parameters for the `EditorChoice` and `EditorFlags` settings: ``` $choices = @{'emacs' = 'c:\emacs\bin\emacs';'vi' = 'c:\vim\vim.exe';'powershell' = 'powershell_ise.exe'} Configuration 'DefaultEditor' { [CmdletBinding()] param ( $EditorChoice, $EditorFlags = '' ) Environment 'TextEditor' { Name = 'EDITOR' Value = "$($choices[$EditorChoice]) $EditorFlags" } } ``` Use the following recipe to set those parameters: ``` dsc_script 'DefaultEditor' do flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' }) command 'c:\dsc_scripts\editors.ps1' end ``` Use custom configuration data Configuration data in DSC scripts may be customized from a recipe. For example, scripts are typically customized to set the behavior for Windows PowerShell credential data types. Configuration data may be specified in one of three ways: * By using the `configuration_data` attribute * By using the `configuration_data_script` attribute * By specifying the path to a valid Windows PowerShell data file The following example shows how to specify custom configuration data using the `configuration_data` property: ``` dsc_script 'BackupUser' do configuration_data <<-EOH @{ AllNodes = @( @{ NodeName = "localhost"; PSDscAllowPlainTextPassword = $true }) } EOH code <<-EOH $user = 'backup' $password = ConvertTo-SecureString -String "YourPass$(random)" -AsPlainText -Force $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $password User $user { UserName = $user Password = $cred Description = 'Backup operator' Ensure = "Present" Disabled = $false PasswordNeverExpires = $true PasswordChangeRequired = $false } EOH end ``` The following example shows how to specify custom configuration data using the `configuration_name` property. For example, the following Windows PowerShell script defines the `vi` configuration: ``` Configuration 'emacs' { Environment 'TextEditor' { Name = 'EDITOR' Value = 'c:\emacs\bin\emacs.exe' } } Configuration 'vi' { Environment 'TextEditor' { Name = 'EDITOR' Value = 'c:\vim\bin\vim.exe' } } ``` Use the following recipe to specify that configuration: ``` dsc_script 'EDITOR' do configuration_name 'vi' command 'C:\dsc_scripts\editors.ps1' end ``` Using DSC with other Chef resources The **dsc_script** resource can be used with other resources. The following example shows how to download a file using the **remote_file** resource, and then uncompress it using the DSC `Archive` resource: ``` remote_file "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" do source 'http://gallery.technet.microsoft.com/DSC-Resource-Kit-All-c449312d/file/124481/1/DSC%20Resource%20Kit%20Wave%206%2008282014.zip' end dsc_script 'get-dsc-resource-kit' do code <<-EOH Archive reskit { ensure = 'Present' path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" } EOH end ``` execute resource ---------------- [execute resource page](execute/index) --- Use the **execute** resource to execute a single command. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. Note Use the **script** resource to execute a script using a specific interpreter (Ruby, Python, Perl, csh, or Bash). ### Syntax --- An **execute** resource block typically executes a single command that is unique to the environment in which a recipe will run. Some **execute** resource commands are run by themselves, but often they are run in combination with other Chef resources. For example, a single command that is run by itself: ``` execute 'apache_configtest' do command '/usr/sbin/apachectl configtest' end ``` The full syntax for all of the properties that are available to the **execute** resource is: ``` execute 'name' do command String, Array # default value: 'name' unless specified creates String cwd String default_env true, false # default value: false domain String elevated true, false # default value: false environment Hash group String, Integer input String live_stream true, false # default value: false login true, false # default value: false password String returns Integer, Array # default value: 0 timeout Integer, String, Float # default value: 3600 user String, Integer action Symbol # defaults to :run if not specified end ``` where: * `execute` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command`, `creates`, `cwd`, `default_env`, `domain`, `elevated`, `environment`, `group`, `input`, `live_stream`, `login`, `password`, `returns`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **execute** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Run a command. (default) ### Properties --- The **execute** resource has the following properties: `command` **Ruby Type:** String, Array | **Default Value:** `The resource block's name` An optional property to set the command to be executed if it differs from the resource block’s name. Note Use the **execute** resource to run a single command. Use multiple **execute** resource blocks to run multiple commands. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `default_env` **Ruby Type:** true, false | **Default Value:** `false` When true this enables ENV magic to add path_sanity to the PATH and force the locale to English+UTF-8 for parsing output New in Chef Client 14.2 `domain` **Ruby Type:** String Windows only: The domain of the user specified by the user property. If not specified, the username and password specified by the `user` and `password` properties will be used to resolve that user against the domain in which the system running Chef Infra Client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. New in Chef Client 12.21 `elevated` **Ruby Type:** true, false | **Default Value:** `false` Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) from interactively blocking the process. This will cause the process to be run under a batch login instead of an interactive login. The user running chef-client needs the ‘Replace a process level token’ and ‘Adjust Memory Quotas for a process’ permissions. The user that is running the command needs the ‘Log on as a batch job’ permission. Because this requires a login, the user and password properties are required. New in Chef Client 13.3 `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `input` **Ruby Type:** String An optional property to set the input sent to the command as STDIN. New in Chef Infra Client 16.2 `live_stream` **Ruby Type:** true, false | **Default Value:** `false` Send the output of the command run by this execute resource block to the Chef Infra Client event stream. `login` **Ruby Type:** true, false | **Default Value:** `false` Use a login shell to run the commands instead of inheriting the existing execution environment. New in Chef Infra Client 17.0 `password` **Ruby Type:** String Windows only: The password of the user specified by the user property. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. New in Chef Client 12.21 `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. `domain\user` or `<EMAIL>` via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain property. On Windows only, if this property is specified, the password property must be specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **execute** resource in recipes: **Run a command upon notification**: ``` execute 'slapadd' do command 'slapadd < /tmp/something.ldif' creates '/var/lib/slapd/uid.bdb' action :nothing end template '/tmp/something.ldif' do source 'something.ldif' notifies :run, 'execute[slapadd]', :immediately end ``` **Run a touch file only once while running a command**: ``` execute 'upgrade script' do command 'php upgrade-application.php && touch /var/application/.upgraded' creates '/var/application/.upgraded' action :run end ``` **Run a command which requires an environment variable**: ``` execute 'slapadd' do command 'slapadd < /tmp/something.ldif' creates '/var/lib/slapd/uid.bdb' action :run environment ({'HOME' => '/home/my_home'}) end ``` **Delete a repository using yum to scrub the cache**: ``` # the following code sample thanks to gaffneyc @ https://gist.github.com/918711 execute 'clean-yum-cache' do command 'yum clean all' action :nothing end file '/etc/yum.repos.d/bad.repo' do action :delete notifies :run, 'execute[clean-yum-cache]', :immediately end ``` **Prevent restart and reconfigure if configuration is broken**: Use the `:nothing` action (common to all resources) to prevent the test from starting automatically, and then use the `subscribes` notification to run a configuration test when a change to the template is detected. ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing subscribes :run, 'template[/etc/nagios3/configures-nagios.conf]', :immediately end ``` **Notify in a specific order**: To notify multiple resources, and then have these resources run in a certain order, do something like the following. ``` execute 'foo' do command '...' notifies :create, 'template[baz]', :immediately notifies :install, 'package[bar]', :immediately notifies :run, 'execute[final]', :immediately end template 'baz' do #... notifies :run, 'execute[restart_baz]', :immediately end package 'bar' execute 'restart_baz' execute 'final' do command '...' end ``` where the sequencing will be in the same order as the resources are listed in the recipe: `execute 'foo'`, `template 'baz'`, `execute [restart_baz]`, `package 'bar'`, and `execute 'final'`. **Execute a command using a template**: The following example shows how to set up IPv4 packet forwarding using the **execute** resource to run a command named `forward_ipv4` that uses a template defined by the **template** resource. ``` execute 'forward_ipv4' do command 'echo > /proc/.../ipv4/ip_forward' action :nothing end template '/etc/file_name.conf' do source 'routing/file_name.conf.erb' notifies :run, 'execute[forward_ipv4]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[forward_ipv4]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. **Add a rule to an IP table**: The following example shows how to add a rule named `test_rule` to an IP table using the **execute** resource to run a command using a template that is defined by the **template** resource: ``` execute 'test_rule' do command "command_to_run --option value --option value --source #{node[:name_of_node][:ipsec][:local][:subnet]} -j test_rule" action :nothing end template '/etc/file_name.local' do source 'routing/file_name.local.erb' notifies :run, 'execute[test_rule]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[test_rule]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. **Stop a service, do stuff, and then restart it**: The following example shows how to use the **execute**, **service**, and **mount** resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following: * Checks to see if the Amazon EC2 node has MySQL * If the node has MySQL, stops MySQL * Installs MySQL * Mounts the node * Restarts MySQL ``` # the following code sample comes from the ``server_ec2`` # recipe in the following cookbook: # https://github.com/chef-cookbooks/mysql if (node.attribute?('ec2') && !FileTest.directory?(node['mysql']['ec2_path'])) service 'mysql' do action :stop end execute 'install-mysql' do command "mv #{node['mysql']['data_dir']}#{node['mysql']['ec2_path']}" not_if { ::File.directory?(node['mysql']['ec2_path']) } end [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir| directory dir do owner 'mysql' group 'mysql' end end mount node['mysql']['data_dir'] do device node['mysql']['ec2_path'] fstype 'none' options 'bind,rw' action [:mount, :enable] end service 'mysql' do action :start end end ``` where * the two **service** resources are used to stop, and then restart the MySQL service * the **execute** resource is used to install MySQL * the **mount** resource is used to mount the node and enable MySQL **Use the platform_family? method**: The following is an example of using the `platform_family?` method in the Recipe DSL to create a variable that can be used with other resources in the same recipe. In this example, `platform_family?` is being used to ensure that a specific binary is used for a specific platform before using the **remote_file** resource to download a file from a remote location, and then using the **execute** resource to install that file by running a command. ``` if platform_family?('rhel') pip_binary = '/usr/bin/pip' else pip_binary = '/usr/local/bin/pip' end remote_file "#{Chef::Config[:file_cache_path]}/distribute_setup.py" do source 'http://python-distribute.org/distribute_setup.py' mode '0755' not_if { ::File.exist?(pip_binary) } end execute 'install-pip' do cwd Chef::Config[:file_cache_path] command <<~EOF # command for installing Python goes here EOF not_if { ::File.exist?(pip_binary) } end ``` where a command for installing Python might look something like: ``` #{node['python']['binary']} distribute_setup.py #{::File.dirname(pip_binary)}/easy_install pip ``` **Control a service using the execute resource**: Warning This is an example of something that should NOT be done. Use the **service** resource to control a service, not the **execute** resource. Do something like this: ``` service 'tomcat' do action :start end ``` and NOT something like this: ``` execute 'start-tomcat' do command '/etc/init.d/tomcat start' action :run end ``` There is no reason to use the **execute** resource to control a service because the **service** resource exposes the `start_command` property directly, which gives a recipe full control over the command issued in a much cleaner, more direct manner. **Use the search Infra Language helper to find users**: The following example shows how to use the `search` method in the Chef Infra Language to search for users: ``` # the following code sample comes from the openvpn cookbook: search("users", "*:*") do |u| execute "generate-openvpn-#{u['id']}" do command "./pkitool #{u['id']}" cwd '/etc/openvpn/easy-rsa' end %w{ conf ovpn }.each do |ext| template "#{node['openvpn']['key_dir']}/#{u['id']}.#{ext}" do source 'client.conf.erb' variables :username => u['id'] end end end ``` where * the search data will be used to create **execute** resources * the **template** resource tells Chef Infra Client which template to use **Enable remote login for macOS**: ``` execute 'enable ssh' do command '/usr/sbin/systemsetup -setremotelogin on' not_if '/usr/sbin/systemsetup -getremotelogin | /usr/bin/grep On' action :run end ``` **Execute code immediately, based on the template resource**: By default, notifications are `:delayed`, that is they are queued up as they are triggered, and then executed at the very end of a Chef Infra Client run. To run an action immediately, use `:immediately`: ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :immediately end ``` and then Chef Infra Client would immediately run the following: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing end ``` **Sourcing a file**: The **execute** resource cannot be used to source a file (e.g. `command 'source filename'`). The following example will fail because `source` is not an executable: ``` execute 'foo' do command 'source /tmp/foo.sh' end ``` Instead, use the **script** resource or one of the **script**-based resources (**bash**, **csh**, **perl**, **python**, or **ruby**). For example: ``` bash 'foo' do code 'source /tmp/foo.sh' end ``` **Run a Knife command**: ``` execute 'create_user' do command <<~EOM knife user create #{user} --admin --password password --disable-editing --file /home/vagrant/.chef/user.pem --config /tmp/knife-admin.rb EOM end ``` **Run install command into virtual environment**: The following example shows how to install a lightweight JavaScript framework into Vagrant: ``` execute "install q and zombiejs" do cwd "/home/vagrant" user "vagrant" environment ({'HOME' => '/home/vagrant', 'USER' => 'vagrant'}) command "npm install -g q zombie should mocha coffee-script" action :run end ``` **Run a command as a named user**: The following example shows how to run `bundle install` from a Chef Infra Client run as a specific user. This will put the gem into the path of the user (`vagrant`) instead of the root user (under which the Chef Infra Client runs): ``` execute '/opt/chefdk/embedded/bin/bundle install' do cwd node['chef_workstation']['bundler_path'] user node['chef_workstation']['user'] environment ({ 'HOME' => "/home/#{node['chef_workstation']['user']}", 'USER' => node['chef_workstation']['user'] }) not_if 'bundle check' end ``` **Run a command as an alternate user**: *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] domain "domain-name" user "user" password "password" end # Passing username = 'domain-name\username'. No domain is passed execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] user "domain-name\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end ``` **Run a command with an external input file**: execute ‘md5sum’ do input File.read(**FILE**) end file resource ------------- [file resource page](file/index) --- Use the **file** resource to manage files directly on a node. Note Use the **cookbook_file** resource to copy a file from a cookbook’s `/files` directory. Use the **template** resource to create a file based on a template in a cookbook’s `/templates` directory. And use the **remote_file** resource to transfer a file to a node from a remote location. ### Syntax --- A **file** resource block manages files that exist on nodes. For example, to write the home page for an Apache website: ``` file '/var/www/customers/public_html/index.php' do content '<html>This is a placeholder for the home page.</html>' mode '0755' owner 'web_admin' group 'web_admin' end ``` where: * `'/var/www/customers/public_html/index.php'` is path to the file and also the filename to be managed * `content` defines the contents of the file The full syntax for all of the properties that are available to the **file** resource is: ``` file 'name' do atomic_update true, false backup false, Integer checksum String content String force_unlink true, false group String, Integer inherits true, false manage_symlink_source true, false mode String, Integer owner String, Integer path String # defaults to 'name' if not specified rights Hash verify String, Block, Symbol action Symbol # defaults to :create if not specified end ``` where: * `file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `atomic_update`, `backup`, `checksum`, `content`, `force_unlink`, `group`, `inherits`, `manage_symlink_source`, `mode`, `owner`, `path`, `rights`, `sensitive`, and `verify` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **file** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. ### Properties --- The **file** resource has the following properties: `atomic_update` **Ruby Type:** true, false | **Default Value:** `False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.` Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the `client.rb` file. `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `checksum` **Ruby Type:** String The SHA-256 checksum of the file. Use to ensure that a specific file is used. If the checksum does not match, the file is not used. `content` **Ruby Type:** String A string that is written to the file. The contents of this property replace any previous content when this property has something other than the default value. The default behavior will not modify content. `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `false`, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `true`, Chef will follow the symlink and will manage the permissions and content of symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String The full path to the file, including the file name and its extension. For example: `/files/file.txt`. Default value: the `name` of the resource block. See “Syntax” section above for more information. Microsoft Windows: A path that begins with a forward slash (`/`) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (`/`) is not recommended. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `verify` **Ruby Type:** String, Block, Symbol Allows verification of a file'’s contents before it is created. Creates a temporary file and then allows execution of commands or Ruby code. If this code evaluates to true, the file is created. If the code evaluates to false, an error is raised. The types for this property are a block, string, or a symbol. When specified as a block, it returns `true` or `false`. When specified as a string, it is executed as a system command. It returns `true` if the command returns 0 as its exit status code and `false` if the command returns a non-zero exit status code. When using a built-in verifier symbol it returns `true` if the verifier succeeds else it returns `false`. Currently suppported verifiers are `:yaml`, `:json` and `:systemd_unit`. Note A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block returns `true`, Chef Infra Client will continue to update the file as appropriate.' For example, this should return `true`: ``` file '/tmp/baz' do verify { 1 == 1 } end ``` This should also return `true`: ``` file '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` In this example, the `%{path}` portion of this command is expanded to the temporary location where a copy of the file to be created exists. This will use Nginx’s syntax checking feature to ensure the file is a valid Nginx configuration file before writing the file. An error will be raised if the executed command returns a non-zero exit status code. This should return `true`: ``` file '/tmp/foo' do content "hello" verify do |path| open(path).read.include? "hello" end end ``` Whereas, this should return `false`: ``` file '/tmp/foo' do content "goodbye" verify do |path| open(path).read.include? "hello" end end ``` When using one of the built-in symbols(`:json`, `:yaml`, `:systemd_unit`) This should return `true`: ``` file 'foo.json' do content '{"foo": "bar"}' verify :json end ``` Whereas, this should return `false`: ``` file 'foo.yaml' do content "--- foo: 'foo-" verify :yaml end ``` If a string, block or symbol returns `false`, the Chef Infra Client run will stop and an error is raised. #### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **file** resource in recipes: Create a file ``` file '/tmp/something' do owner 'root' group 'root' mode '0755' action :create end ``` Create a file in Microsoft Windows To create a file in Microsoft Windows, be sure to add an escape character—`\`—before the backslashes in the paths: ``` file 'C:\\tmp\\something.txt' do rights :read, 'Everyone' rights :full_control, 'DOMAIN\\User' action :create end ``` Remove a file ``` file '/tmp/something' do action :delete end ``` Set file modes ``` file '/tmp/something' do mode '0755' end ``` Delete a repository using yum to scrub the cache ``` # the following code sample thanks to gaffneyc @ https://gist.github.com/918711 execute 'clean-yum-cache' do command 'yum clean all' action :nothing end file '/etc/yum.repos.d/bad.repo' do action :delete notifies :run, 'execute[clean-yum-cache]', :immediately notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately end ``` Add the value of a data bag item to a file The following example shows how to get the contents of a data bag item named `impossible_things`, create a .pem file located at `some/directory/path/`, and then use the `content` attribute to update the contents of that file with the value of the `impossible_things` data bag item: ``` private_key = data_bag_item('impossible_things', private_key_name)['private_key'] file "some/directory/path/#{private_key_name}.pem" do content private_key owner 'root' group 'group' mode '0755' end ``` Write a YAML file The following example shows how to use the `content` property to write a YAML file: ``` file "#{app['deploy_to']}/shared/config/settings.yml" do owner "app['owner']" group "app['group']" mode '0755' content app.to_yaml end ``` Write a string to a file The following example specifies a directory, and then uses the `content` property to add a string to the file created in that directory: ``` status_file = '/path/to/file/status_file' file status_file do owner 'root' group 'root' mode '0755' content 'My favourite foremost coastal Antarctic shelf, oh Larsen B!' end ``` Create a file from a copy The following example shows how to copy a file from one directory to another, locally on a node: ``` file '/root/1.txt' do content IO.read('/tmp/1.txt') action :create end ``` where the `content` attribute uses the Ruby `IO.read` method to get the contents of the `/tmp/1.txt` file. freebsd_package resource ------------------------- [freebsd_package resource page](freebsd_package/index) --- Use the **freebsd_package** resource to manage packages for the FreeBSD platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **freebsd_package** resource block manages a package on a node, typically by installing it. The simplest use of the **freebsd_package** resource is: ``` freebsd_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **freebsd_package** resource is: ``` freebsd_package 'name' do options String package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `freebsd_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **freebsd_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. ### Properties --- The **freebsd_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **freebsd_package** resource in recipes: Install a package ``` freebsd_package 'name of package' do action :install end ``` gem_package resource --------------------- [gem_package resource page](gem_package/index) --- Use the **gem_package** resource to manage gem packages that are only included in recipes. When a gem is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. Note The **gem_package** resource must be specified as `gem_package` and cannot be shortened to `package` in a recipe. Warning The **chef_gem** and **gem_package** resources are both used to install Ruby gems. For any machine on which Chef Infra Client is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is available only to Chef Infra Client. Use the **chef_gem** resource to install gems into the instance of Ruby that is dedicated to Chef Infra Client. Use the **gem_package** resource to install all other gems (i.e. install gems system-wide). ### Syntax --- The full syntax for all of the properties that are available to the **gem_package** resource is: ``` gem_package 'name' do clear_sources true, false gem_binary String include_default_source true, false options String, Hash, Array package_name String source String, Array timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `gem_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `clear_sources`, `gem_binary`, `include_default_source`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **gem_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **gem_package** resource has the following properties: `clear_sources` **Ruby Type:** true, false | **Default Value:** `false unless `clear_gem_sources` set to true in the `client.rb` config.` Set to `true` to download a gem from the path specified by the `source` property (and not from RubyGems). `gem_binary` **Ruby Type:** String The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by Chef Infra Client will be used. `include_default_source` **Ruby Type:** true, false Set to `false` to not include `Chef::Config[:rubygems_url]` in the sources. New in Chef Client 13.0 `options` **Ruby Type:** String, Hash, Array Options for the gem install, either a Hash or a String. When a hash is given, the options are passed to `Gem::DependencyInstaller.new`, and the gem will be installed via the gems API. When a String is given, the gem will be installed by shelling out to the gem command. Using a Hash of options with an explicit gem_binary will result in undefined behavior. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String, Array Optional. The URL, or list of URLs, at which the gem package is located. This list is added to the source configured in `Chef::Config[:rubygems_url]` (see also include_default_source) to construct the complete list of rubygems sources. Users in an ‘airgapped’ environment should set Chef::Config[:rubygems_url] to their local RubyGems mirror. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **gem_package** resource in recipes: The following examples demonstrate various approaches for using the **gem_package** resource in recipes: **Install a gem file from the local file system** ``` gem_package 'loofah' do source '/tmp/loofah-2.7.0.gem' action :install end ``` **Use the `ignore_failure` common attribute** ``` gem_package 'syntax' do action :install ignore_failure true end ``` git resource ------------ [git resource page](git/index) --- Use the **git** resource to manage source control resources that exist in a git repository. git version 1.6.5 (or higher) is required to use all of the functionality in the git resource. ### Syntax --- A **git** resource block manages source control resources that exist in a git repository: ``` git "#{Chef::Config[:file_cache_path]}/app_name" do repository node[:app_name][:git_repository] revision node[:app_name][:git_revision] action :sync end ``` The full syntax for all of the properties that are available to the **git** resource is: ``` git 'name' do additional_remotes Hash # default value: {} checkout_branch String depth Integer destination String # default value: 'name' unless specified enable_checkout true, false # default value: true enable_submodules true, false # default value: false environment Hash group String, Integer remote String # default value: "origin" repository String revision String # default value: "HEAD" ssh_wrapper String timeout Integer user String, Integer action Symbol # defaults to :sync if not specified end ``` where: * `git` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `additional_remotes`, `checkout_branch`, `depth`, `destination`, `enable_checkout`, `enable_submodules`, `environment`, `group`, `remote`, `repository`, `revision`, `ssh_wrapper`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **git** resource has the following actions: `:checkout` Clone or check out the source. When a checkout is available, this provider does nothing. `:export` Export the source, excluding or removing any version control artifacts. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:sync` Default. Update the source to the specified version, or get a new clone or checkout. This action causes a hard reset of the index and working tree, discarding any uncommitted changes. ### Properties --- The **git** resource has the following properties: `additional_remotes` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of additional remotes that are added to the git repository configuration. `checkout_branch` **Ruby Type:** String Do a one-time checkout from git **or** use when a branch in the upstream repository is named `deploy`. To prevent the **git** resource from attempting to check out master from master, set `enable_checkout` to `false` when using the `checkout_branch` property. See `revision`. `depth` **Ruby Type:** Integer The number of past revisions to be included in the git shallow clone. Unless specified the default behavior will do a full clone. `destination` **Ruby Type:** String | **Default Value:** `The resource block's name` The location path to which the source is to be cloned, checked out, or exported. Default value: the name of the resource block. `enable_checkout` **Ruby Type:** true, false | **Default Value:** `true` Check out a repo from master. Set to `false` when using the `checkout_branch` attribute to prevent the git resource from attempting to check out `master` from `master`. `enable_submodules` **Ruby Type:** true, false | **Default Value:** `false` Perform a sub-module initialization and update. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) Note The **git** provider automatically sets the `ENV['HOME']` and `ENV['GIT_SSH']` environment variables. To override this behavior and provide different values, add `ENV['HOME']` and/or `ENV['GIT_SSH']` to the `environment` Hash. `group` **Ruby Type:** String, Integer The system group that will own the checked-out code. `remote` **Ruby Type:** String | **Default Value:** `origin` The remote repository to use when synchronizing an existing clone. `repository` **Ruby Type:** String The URI of the code repository. `revision` **Ruby Type:** String | **Default Value:** `HEAD` A branch, tag, or commit to be synchronized with git. This can be symbolic, like `HEAD` or it can be a source control management-specific revision identifier. See `checkout_branch`. The value of the `revision` attribute may change over time. From one branch to another, to a tag, to a specific SHA for a commit, and then back to a branch. The `revision` attribute may even be changed in a way where history gets rewritten. Instead of tracking a specific branch or doing a headless checkout, Chef Infra Client maintains its own branch (via the **git** resource) that does not exist in the upstream repository. Chef Infra Client is then free to forcibly check out this branch to any commit without destroying the local history of an existing branch. For example, to explicitly track an upstream repository’s master branch: ``` revision 'master' ``` Use the `git rev-parse` and `git ls-remote` commands to verify that Chef Infra Client is synchronizing commits correctly. (Chef Infra Client always runs `git ls-remote` on the upstream repository to verify the commit is made to the correct repository.) `ssh_wrapper` **Ruby Type:** String The path to the wrapper script used when running SSH with git. The `GIT_SSH` environment variable is set to this. `timeout` **Ruby Type:** Integer The amount of time (in seconds) to wait for a command to execute before timing out. When this property is specified using the **deploy** resource, the value of the `timeout` property is passed from the **deploy** resource to the **git** resource. `user` **Ruby Type:** String, Integer | **Default Value:** ``HOME` environment variable of the user running chef-client` The system user that will own the checked-out code. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **git** resource in recipes: **Use the git mirror** ``` git '/opt/my_sources/couch' do repository 'git://git.apache.org/couchdb.git' revision 'master' action :sync end ``` **Use different branches** To use different branches, depending on the environment of the node: ``` branch_name = if node.chef_environment == 'QA' 'staging' else 'master' end git '/home/user/deployment' do repository '<EMAIL>:git_site/deployment.git' revision branch_name action :sync user 'user' group 'test' end ``` Where the `branch_name` variable is set to staging or master, depending on the environment of the node. Once this is determined, the `branch_name` variable is used to set the revision for the repository. If the git status command is used after running the example above, it will return the branch name as `deploy`, as this is the default value. Run Chef Infra Client in debug mode to verify that the correct branches are being checked out: ``` sudo chef-client -l debug ``` **Install an application from git using bash** The following example shows how Bash can be used to install a plug-in for rbenv named ruby-build, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which ruby-build is located, and then runs a command. ``` git "/Users/tsmith/.chef/cache/ruby-build" do repository 'git://github.com/rbenv/ruby-build.git' revision 'master' action :sync end bash 'install_ruby_build' do cwd "/Users/tsmith/.chef/cache/ruby-build" user 'rbenv' group 'rbenv' code <<-EOH ./install.sh EOH environment 'PREFIX' => '/usr/local' end ``` **Notify a resource post-checkout** ``` git "/Users/tsmith/.chef/cache/my_app" do repository node['my_app']['git_repository'] revision node['my_app']['git_revision'] action :sync notifies :run, 'bash[compile_my_app]', :immediately end ``` **Pass in environment variables** ``` git '/opt/my_sources/couch' do repository 'git://git.apache.org/couchdb.git' revision 'master' environment 'VAR' => 'whatever' action :sync end ``` group resource -------------- [group resource page](group/index) --- Use the **group** resource to manage a local group. ### Syntax --- The full syntax for all of the properties that are available to the **group** resource is: ``` group 'name' do append true, false # default value: false comment String excluded_members String, Array # default value: [] gid String, Integer group_name String # default value: 'name' unless specified members String, Array # default value: [] non_unique true, false # default value: false system true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `group` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `append`, `comment`, `excluded_members`, `gid`, `group_name`, `members`, `non_unique`, and `system` are the properties available to this resource. ### Actions --- The **group** resource has the following actions: `:create` Default. Create a group. If a group already exists (but does not match), update that group to match. `:manage` Manage an existing group. This action does nothing if the group does not exist. `:modify` Modify an existing group. This action raises an exception if the group does not exist. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a group. ### Properties --- The **group** resource has the following properties: `append` **Ruby Type:** true, false | **Default Value:** `false` How members should be appended and/or removed from a group. When true, `members` are appended and `excluded_members` are removed. When `false`, group members are reset to the value of the `members` property. `comment` **Ruby Type:** String Specifies a comment to associate with the local group. New in Chef Client 14.9 `excluded_members` **Ruby Type:** String, Array | **Default Value:** `[]` Remove users from a group. May only be used when `append` is set to `true`. `gid` **Ruby Type:** String, Integer The identifier for the group. `group_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the group. Default value: the `name` of the resource block. See “Syntax” section above for more information. `members` **Ruby Type:** String, Array | **Default Value:** `[]` Which users should be set or appended to a group. When more than one group member is identified, the list of members should be an array: `members ['user1', 'user2']`. `non_unique` **Ruby Type:** true, false | **Default Value:** `false` Allow gid duplication. May only be used with the `Groupadd` user resource provider. `system` **Ruby Type:** true, false | **Default Value:** `false` Set to `true` if the group belongs to a system group. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **group** resource in recipes: Append users to groups\n\n `ruby\n group 'www-data' do\n \ \ action :modify\n members 'maintenance'\n append true\n end\n` \n\n \ \ Add a user to group on the Windows platform\n\n `ruby\n group 'Administrators'\ \ do\n members ['domain\\foo']\n append true\n action :modify\n end\n\ \` \n" habitat_config resource ------------------------ [habitat_config resource page](habitat_config/index) --- Use the **habitat_config** resource to apply a configuration to a Chef Habitat service. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_config** resource is: ``` habitat_config 'name' do config Mash (Hash-like) gateway_auth_token String remote_sup String # default value: "127.0.0.1:9632" remote_sup_http String # default value: "127.0.0.1:9631" service_group String # default value: 'name' unless specified user String action Symbol # defaults to :apply if not specified end ``` where: * `habitat_config` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `config`, `gateway_auth_token`, `remote_sup`, `remote_sup_http`, `service_group`, and `user` are the properties available to this resource. ### Actions --- The **habitat_config** resource has the following actions: `:apply` applies the given configuration (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **habitat_config** resource has the following properties: `config` **Ruby Type:** Mash (Hash-like) | `REQUIRED` The configuration to apply as a ruby hash, for example, `{ worker_count: 2, http: { keepalive_timeout: 120 } }`. `gateway_auth_token` **Ruby Type:** String Auth token for accessing the remote supervisor’s http port. `remote_sup` **Ruby Type:** String | **Default Value:** `127.0.0.1:9632` Address to a remote supervisor’s control gateway. `remote_sup_http` **Ruby Type:** String | **Default Value:** `127.0.0.1:9631` Address for remote supervisor http port. Used to pull existing. `service_group` **Ruby Type:** String | **Default Value:** `The resource block's name` The service group to apply the configuration to. For example, `nginx.default` `user` **Ruby Type:** String Name of user key to use for encryption. Passes `--user` to `hab config apply`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_config** resource in recipes: **Configure your nginx defaults** ``` habitat_config 'nginx.default' do config({ worker_count: 2, http: { keepalive_timeout: 120 } }) end ``` habitat_install resource ------------------------- [habitat_install resource page](habitat_install/index) --- Use the **habitat_install** resource to install Chef Habitat. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_install** resource is: ``` habitat_install 'name' do bldr_url String create_user true, false # default value: true hab_version String install_url String license String tmp_dir String action Symbol # defaults to :install if not specified end ``` where: * `habitat_install` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bldr_url`, `create_user`, `hab_version`, `install_url`, `license`, and `tmp_dir` are the properties available to this resource. ### Actions --- The **habitat_install** resource has the following actions: `:install` Installs Habitat. Does nothing if the `hab` binary is found in the default location for the system (`/bin/hab` on Linux, `/usr/local/bin/hab` on macOS, `C:/habitat/hab.exe` on Windows) (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **habitat_install** resource has the following properties: `bldr_url` **Ruby Type:** String Optional URL to an alternate Habitat Builder. `create_user` **Ruby Type:** true, false | **Default Value:** `true` Creates the `hab` system user. `hab_version` **Ruby Type:** String Specify the version of `Habitat` you would like to install. `install_url` **Ruby Type:** String | **Default Value:** `https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh` URL to the install script, default is from the [habitat repo](https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh) . `license` **Ruby Type:** String **Allowed Values:** `"accept"` Specifies acceptance of habitat license when set to `accept`. `tmp_dir` **Ruby Type:** String Sets TMPDIR environment variable for location to place temp files. Note This is required if `/tmp` and `/var/tmp` are mounted `noexec`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_install** resource in recipes: **Installation Without a Resource Name** ``` habitat_install ``` **Installation specifying a habitat builder URL** ``` habitat_install 'install habitat' do bldr_url 'http://localhost' end ``` **Installation specifying version and habitat builder URL** ``` habitat_install 'install habitat' do bldr_url 'http://localhost' hab_version '1.5.50' end ``` habitat_package resource ------------------------- [habitat_package resource page](habitat_package/index) --- Use the **habitat_package** to install or remove Chef Habitat packages from Habitat Builder. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_package** resource is: ``` habitat_package 'name' do auth_token String binlink true, false, force # default value: false bldr_url String # default value: "https://bldr.habitat.sh" channel String # default value: "stable" exclude String keep_latest String no_deps true, false # default value: false options String package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `habitat_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `auth_token`, `binlink`, `bldr_url`, `channel`, `exclude`, `keep_latest`, `no_deps`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **habitat_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:lock` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` `:remove` Remove a package. `:unlock` `:upgrade` Install a package and ensure that a package is the latest version. ### Properties --- The **habitat_package** resource has the following properties: `auth_token` **Ruby Type:** String Auth token for installing a package from a private organization on Habitat builder. `binlink` **Ruby Type:** true, false, force | **Default Value:** `false` If habitat should attempt to binlink the package. Acceptable values: `true`, `false`, `:force`. Will fail on binlinking if set to `true` and binary or binlink exists. `bldr_url` **Ruby Type:** String | **Default Value:** `https://bldr.habitat.sh` The habitat builder url where packages will be downloaded from. **Defaults to public Habitat Builder** `channel` **Ruby Type:** String | **Default Value:** `stable` The release channel to install your package from. `exclude` **Ruby Type:** String Identifier of one or more packages that should not be uninstalled. (ex: core/redis, core/busybox-static/1.42.2/21120102031201) `keep_latest` **Ruby Type:** String Ability to uninstall while retaining a specified version **This feature only works in Habitat 1.5.86+.** `no_deps` **Ruby Type:** true, false | **Default Value:** `false` Remove package but retain dependencies. `options` **Ruby Type:** String Pass any additional parameters to the habitat package command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_package** resource in recipes: **Install core/redis** ``` habitat_package 'core/redis' ``` **Install specific version of a package from the unstable channel** ``` habitat_package 'core/redis' do version '3.2.3' channel 'unstable' end ``` **Install a package with specific version and revision** ``` habitat_package 'core/redis' do version '3.2.3/20160920131015' end ``` **Install a package and force linking it’s binary files to the system path** ``` habitat_package 'core/nginx' do binlink :force end ``` **Install a package and link it’s binary files to the system path** ``` habitat_package 'core/nginx' do options '--binlink' end ``` **Remove package and all of it’s versions** ``` habitat_package 'core/nginx' action :remove end ``` **Remove specified version of a package** ``` habitat_package 'core/nginx/3.2.3' action :remove end ``` **Remove package but retain some versions Note: Only available as of Habitat 1.5.86** ``` habitat_package 'core/nginx' keep_latest '2' action :remove end ``` ``` **Remove package but keep dependencies** habitat_package 'core/nginx' no_deps false action :remove end ``` habitat_service resource ------------------------- [habitat_service resource page](habitat_service/index) --- Use the **habitat_service** resource to manage Chef Habitat services. This requires that `core/hab-sup` be running as a service. See the `habitat_sup` resource documentation for more information. Note Applications may run as a specific user. Often with Habitat, the default is `hab`, or `root`. If the application requires another user, then it should be created with Chef’s `user` resource. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_service** resource is: ``` habitat_service 'name' do bind String, Array # default value: [] binding_mode Symbol, String # default value: :strict bldr_url String # default value: "https://bldr.habitat.sh/" channel Symbol, String # default value: :stable gateway_auth_token String health_check_interval Integer # default value: 30 remote_sup String # default value: "127.0.0.1:9632" remote_sup_http String # default value: "127.0.0.1:9631" service_group String # default value: "default" service_name String # default value: 'name' unless specified shutdown_timeout Integer # default value: 8 strategy Symbol, String # default value: :none topology Symbol, String # default value: :standalone update_condition Symbol, String # default value: :latest action Symbol # defaults to :load if not specified end ``` where: * `habitat_service` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bind`, `binding_mode`, `bldr_url`, `channel`, `gateway_auth_token`, `health_check_interval`, `remote_sup`, `remote_sup_http`, `service_group`, `service_name`, `shutdown_timeout`, `strategy`, `topology`, and `update_condition` are the properties available to this resource. ### Actions --- The **habitat_service** resource has the following actions: `:load` (default action) runs `hab service load` to load and start the specified application service (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reload` runs the `:unload` and then `:load` actions `:restart` runs the `:stop` and then `:start` actions `:start` runs `hab service start` to start the specified application service `:stop` runs `hab service stop` to stop the specified application service `:unload` runs `hab service unload` to unload and stop the specified application service ### Properties --- The **habitat_service** resource has the following properties: `bind` **Ruby Type:** String, Array | **Default Value:** `[]` Passes `--bind` with the specified services to bind to the hab command. If an array of multiple service binds are specified then a `--bind` flag is added for each. `binding_mode` **Ruby Type:** Symbol, String | **Default Value:** `:strict` **Allowed Values:** `:strict, "strict", :relaxed, "relaxed"` Passes `--binding-mode` with the specified binding mode. Defaults to `:strict`. Options are `:strict` or `:relaxed` `bldr_url` **Ruby Type:** String | **Default Value:** `https://bldr.habitat.sh/` Passes `--url` with the specified Habitat Builder URL to the hab command. Depending on the type of Habitat Builder you are connecting to, this URL will look different, here are the **3** current types: - Public Habitat Builder (default) - `https://bldr.habitat.sh` - On-Prem Habitat Builder installed using the [Source Install Method](https://github.com/habitat-sh/on-prem-builder) - `https://your.bldr.url` - On-Prem Habitat Builder installed using the [Automate Installer](https://automate.chef.io/docs/on-prem-builder/) - `https://your.bldr.url/bldr/v1` `channel` **Ruby Type:** Symbol, String | **Default Value:** `:stable` Passes `--channel` with the specified channel to the hab command `gateway_auth_token` **Ruby Type:** String Auth token for accessing the remote supervisor’s http port. `health_check_interval` **Ruby Type:** Integer | **Default Value:** `30` The interval (seconds) on which to run health checks. `remote_sup` **Ruby Type:** String | **Default Value:** `127.0.0.1:9632` Address to a remote Supervisor’s Control Gateway `remote_sup_http` **Ruby Type:** String | **Default Value:** `127.0.0.1:9631` IP address and port used to communicate with the remote supervisor. If this value is invalid, the resource will update the supervisor configuration each time Chef Infra Server runs. `service_group` **Ruby Type:** String | **Default Value:** `default` Passes `--group` with the specified service group to the hab command `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the service, must be in the form of `origin/name` `shutdown_timeout` **Ruby Type:** Integer | **Default Value:** `8` The timeout in seconds allowed during shutdown. `strategy` **Ruby Type:** Symbol, String | **Default Value:** `:none` **Allowed Values:** `:none, "none", :"at-once", "at-once", :rolling, "rolling"` Passes `--strategy` with the specified update strategy to the hab command. Defaults to `:none`. Other options are `:'at-once'` and `:rolling` `topology` **Ruby Type:** Symbol, String | **Default Value:** `:standalone` **Allowed Values:** `:standalone, "standalone", :leader, "leader"` Passes `--topology` with the specified service topology to the hab command `update_condition` **Ruby Type:** Symbol, String | **Default Value:** `:latest` **Allowed Values:** `:latest, "latest", :"track-channel", "track-channel"` Passes `--update-condition` dictating when this service should updated. Defaults to `latest`. Options are `latest` or `track-channel` **_ Note This requires a minimum habitat version of 1.5.71_** - `latest`: Runs the latest package that can be found in the configured channel and local packages. - `track-channel`: Always run the package at the head of a given channel. This enables service rollback, where demoting a package from a channel will cause the package to rollback to an older version of the package. A ramification of enabling this condition is that packages that are newer than the package at the head of the channel are also uninstalled during a service rollback. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_service** resource in recipes: **Install and load nginx** ``` habitat_package 'core/nginx' habitat_service 'core/nginx' habitat_service 'core/nginx unload' do service_name 'core/nginx' action :unload end ``` **Pass the `strategy` and `topology` options to hab service commands** ``` habitat_service 'core/redis' do strategy 'rolling' topology 'standalone' end ``` **Using update_condition** ``` habitat_service 'core/redis' do strategy 'rolling' update_condition 'track-channel' topology 'standalone' end ``` **If the service has it’s own user specified that is not the `hab` user, don’t create the `hab` user on install, and instead create the application user with Chef’s `user` resource** ``` habitat_install 'install habitat' do create_user false end user 'acme-apps' do system true end habitat_service 'acme/apps' ``` habitat_sup resource --------------------- [habitat_sup resource page](habitat_sup/index) --- Use the **habitat_sup** resource to runs a Chef Habitat supervisor for one or more Chef Habitat services. The resource is commonly used in conjunction with `habitat_service` which will manage the services loaded and started within the supervisor. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_sup** resource is: ``` habitat_sup 'name' do auth_token String auto_update true, false # default value: false bldr_url String event_stream_application String event_stream_cert String event_stream_environment String event_stream_site String event_stream_token String event_stream_url String gateway_auth_token String hab_channel String health_check_interval String, Integer keep_latest String launcher_version String license String limit_no_files String listen_ctl String listen_gossip String listen_http String org String # default value: "default" peer String, Array permanent_peer true, false # default value: false ring String service_version String sup_version String toml_config true, false # default value: false update_condition String action Symbol # defaults to :run if not specified end ``` where: * `habitat_sup` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `auth_token`, `auto_update`, `bldr_url`, `event_stream_application`, `event_stream_cert`, `event_stream_environment`, `event_stream_site`, `event_stream_token`, `event_stream_url`, `gateway_auth_token`, `hab_channel`, `health_check_interval`, `keep_latest`, `launcher_version`, `license`, `limit_no_files`, `listen_ctl`, `listen_gossip`, `listen_http`, `org`, `peer`, `permanent_peer`, `ring`, `service_version`, `sup_version`, `toml_config`, and `update_condition` are the properties available to this resource. ### Actions --- The **habitat_sup** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` The `run` action handles installing Habitat using the `habitat_install` resource, ensures that the appropriate versions of the `core/hab-sup` and `core/hab-launcher` packages are installed using `habitat_package`, and then drops off the appropriate init system definitions and manages the service. (default) `:stop` ### Properties --- The **habitat_sup** resource has the following properties: `auth_token` **Ruby Type:** String Auth token for accessing a private organization on bldr. This value is templated into the appropriate service file. `auto_update` **Ruby Type:** true, false | **Default Value:** `false` Passes `--auto-update`. This will set the Habitat supervisor to automatically update itself any time a stable version has been released. `bldr_url` **Ruby Type:** String The Habitat Builder URL for the `habitat_package` resource, if needed. `event_stream_application` **Ruby Type:** String The name of your application that will be displayed in the Chef Automate Applications Dashboard. `event_stream_cert` **Ruby Type:** String With `Intermediary Certificates` or, Automate 2 being set to use TLS with a valid cert, you will need to provide `Habitat` with your certificate for communication with Automate to work. [Follow these steps!](https://automate.chef.io/docs/applications-setup/#share-the-tls-certificate-with-chef-habitat). `event_stream_environment` **Ruby Type:** String The application environment for the supervisor, this is for grouping in the Applications Dashboard. `event_stream_site` **Ruby Type:** String Application Dashboard label for the ‘site’ of the application - can be filtered in the dashboard. `event_stream_token` **Ruby Type:** String Chef Automate token for sending application event stream data. `event_stream_url` **Ruby Type:** String `AUTOMATE_HOSTNAME:4222` - the Chef Automate URL with port 4222 specified Note The port can be changed if needed. `gateway_auth_token` **Ruby Type:** String Auth token for accessing the supervisor’s HTTP gateway. This value is templated into the appropriate service file. `hab_channel` **Ruby Type:** String The channel to install Habitat from. Defaults to stable `health_check_interval` **Ruby Type:** String, Integer The interval (seconds) on which to run health checks. `keep_latest` **Ruby Type:** String Automatically cleans up old packages. If this flag is enabled, service startup will initiate an uninstall of all previous versions of the associated package. This also applies when a service is restarted due to an update. If a number is passed to this argument, that number of latest versions will be kept. The same logic applies to the Supervisor package `env:HAB_KEEP_LATEST_PACKAGES=1` Note This requires Habitat version `1.5.86+` `launcher_version` **Ruby Type:** String Allows you to choose which version of launcher to install. `license` **Ruby Type:** String **Allowed Values:** `"accept"` Specifies acceptance of habitat license when set to `accept`. `limit_no_files` **Ruby Type:** String allows you to set LimitNOFILE in the systemd service when used Note Linux Only. `listen_ctl` **Ruby Type:** String Only valid for `:run` action, passes `--listen-ctl` with the specified address and port, e.g., `0.0.0.0:9632`, to the hab command. `listen_gossip` **Ruby Type:** String Only valid for `:run` action, passes `--listen-gossip` with the specified address and port, e.g., `0.0.0.0:9638`, to the hab command. `listen_http` **Ruby Type:** String Only valid for `:run` action, passes `--listen-http` with the specified address and port, e.g., `0.0.0.0:9631`, to the hab command. `org` **Ruby Type:** String | **Default Value:** `default` Only valid for `:run` action, passes `--org` with the specified org name to the hab command. `peer` **Ruby Type:** String, Array Only valid for `:run` action, passes `--peer` with the specified initial peer to the hab command. `permanent_peer` **Ruby Type:** true, false | **Default Value:** `false` Only valid for `:run` action, passes `--permanent-peer` to the hab command. `ring` **Ruby Type:** String Only valid for `:run` action, passes `--ring` with the specified ring key name to the hab command. `service_version` **Ruby Type:** String Allows you to choose which version of the ***Windows Service*** to install. `sup_version` **Ruby Type:** String Allows you to choose which version of supervisor you would like to install. Note If a version is provided, it will also install that version of habitat if not previously installed. `toml_config` **Ruby Type:** true, false | **Default Value:** `false` Supports using the Supervisor toml configuration instead of passing exec parameters to the service, [reference](https://www.habitat.sh/docs/reference/#supervisor-config). `update_condition` **Ruby Type:** String Passes `--update-condition` dictating when this service should updated. Defaults to `latest`. Options are `latest` or `track-channel` **_ Note This requires a minimum habitat version of 1.5.71_** - `latest`: Runs the latest package that can be found in the configured channel and local packages. - `track-channel`: Always run what is at the head of a given channel. This enables service rollback where demoting a package from a channel will cause the package to rollback to an older version of the package. A ramification of enabling this condition is packages newer than the package at the head of the channel will be automatically uninstalled during a service rollback. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_sup** resource in recipes: **Set up with just the defaults** ``` habitat_sup 'default' ``` **Update listen ports and use Supervisor toml config** ``` habitat_sup 'test-options' do listen_http '0.0.0.0:9999' listen_gossip '0.0.0.0:9998' toml_config true end ``` **Use with an on-prem Habitat Builder. Note: Access to public builder may not be available due to your company policies** ``` habitat_sup 'default' do bldr_url 'https://bldr.example.com' end ``` **Using update_condition** ``` habitat_sup 'default' do bldr_url 'https://bldr.example.com' habitat_channel 'dev' update_condition 'track-channel' end ``` **Provide event_stream_* information** ``` habitat_sup 'default' do license 'accept' event_stream_application 'myapp' event_stream_environment 'production' event_stream_site 'MySite' event_stream_url 'automate.example.com:4222' event_stream_token 'myawesomea2clitoken=' event_stream_cert '/hab/cache/ssl/mycert.crt' end ``` **Provide specific versions** ``` habitat_sup 'default' do bldr_url 'https://bldr.example.com' sup_version '1.5.50' launcher_version '13458' service_version '0.6.0' # WINDOWS ONLY end ``` **Set latest version of packages to retain** habitat_sup ‘default’ do bldr_url ‘<https://bldr.example.com>’ sup_version ‘1.5.86’ launcher_version ‘13458’ service_version ‘0.6.0’ # WINDOWS ONLY keep_latest ‘2’ end habitat_user_toml resource ---------------------------- [habitat_user_toml resource page](habitat_user_toml/index) --- Use the **habitat_user_toml** to template a `user.toml` for Chef Habitat services. Configurations set in the `user.toml` override the `default.toml` for a given package, which makes it an alternative to applying service group level configuration. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_user_toml** resource is: ``` habitat_user_toml 'name' do config Mash (Hash-like) service_name String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `habitat_user_toml` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `config` and `service_name` are the properties available to this resource. ### Actions --- The **habitat_user_toml** resource has the following actions: `:create` (default action) Create the user.toml from the specified config. (default) `:delete` Delete the user.toml `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **habitat_user_toml** resource has the following properties: `config` **Ruby Type:** Mash (Hash-like) | `REQUIRED` Only valid for `:create` action. The configuration to apply as a ruby hash, for example, `{ worker_count: 2, http: { keepalive_timeout: 120 } }`. `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The service group to apply the configuration to, for example, `nginx.default`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_user_toml** resource in recipes: **Configure user specific settings to nginx** ``` habitat_user_toml 'nginx' do config({ worker_count: 2, http: { keepalive_timeout: 120 } }) end ``` homebrew_cask resource ----------------------- [homebrew_cask resource page](homebrew_cask/index) --- Use the **homebrew_cask** resource to install binaries distributed via the Homebrew package manager. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **homebrew_cask** resource is: ``` homebrew_cask 'name' do cask_name String # default value: 'name' unless specified homebrew_path String # default value: "/usr/local/bin/brew" install_cask true, false # default value: true options String owner String, Integer # default value: "Calculated default username" action Symbol # defaults to :install if not specified end ``` where: * `homebrew_cask` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `cask_name`, `homebrew_path`, `install_cask`, `options`, and `owner` are the properties available to this resource. ### Actions --- The **homebrew_cask** resource has the following actions: `:install` Install an application that is packaged as a Homebrew cask. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an application that is packaged as a Homebrew cask. ### Properties --- The **homebrew_cask** resource has the following properties: `cask_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the cask name if it differs from the resource block’s name. `homebrew_path` **Ruby Type:** String | **Default Value:** `/usr/local/bin/brew` The path to the homebrew binary. `install_cask` **Ruby Type:** true, false | **Default Value:** `true` Automatically install the Homebrew cask tap, if necessary. `options` **Ruby Type:** String Options to pass to the brew command during installation. `owner` **Ruby Type:** String, Integer | **Default Value:** `Calculated default username` The owner of the Homebrew installation. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. homebrew_package resource -------------------------- [homebrew_package resource page](homebrew_package/index) --- Use the **homebrew_package** resource to manage packages for the macOS platform. Note Starting with Chef Infra Client 16 the homebrew resource now accepts an array of packages for installing multiple packages at once. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. **New in Chef Infra Client 12.0.** ### Syntax --- The full syntax for all of the properties that are available to the **homebrew_package** resource is: ``` homebrew_package 'name' do homebrew_user String, Integer options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `homebrew_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `homebrew_user`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **homebrew_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and ensure that a package is the latest version. ### Properties --- The **homebrew_package** resource has the following properties: `homebrew_user` **Ruby Type:** String, Integer The name or uid of the Homebrew owner to be used by Chef Infra Client when executing a command. Chef Infra Client, by default, will attempt to execute a Homebrew command as the owner of the `/usr/local/bin/brew` executable. If that executable does not exist, Chef Infra Client will attempt to find the user by executing `which brew`. If that executable cannot be found, Chef Infra Client will print an error message: `Could not find the 'brew' executable in /usr/local/bin or anywhere on the path.`. Set this property to specify the Homebrew owner for situations where Chef Infra Client cannot automatically detect the correct owner.' `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **homebrew_package** resource in recipes: **Install a package**: ``` homebrew_package 'git' ``` **Install multiple packages at once**: ``` homebrew_package %w(git fish ruby) ``` **Specify the Homebrew user with a UUID** ``` homebrew_package 'git' do homebrew_user 1001 end ``` **Specify the Homebrew user with a string**: ``` homebrew_package 'vim' do homebrew_user 'user1' end ``` homebrew_tap resource ---------------------- [homebrew_tap resource page](homebrew_tap/index) --- Use the **homebrew_tap** resource to add additional formula repositories to the Homebrew package manager. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **homebrew_tap** resource is: ``` homebrew_tap 'name' do homebrew_path String # default value: "/usr/local/bin/brew" owner String # default value: "Calculated default username" tap_name String # default value: 'name' unless specified url String action Symbol # defaults to :tap if not specified end ``` where: * `homebrew_tap` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `homebrew_path`, `owner`, `tap_name`, and `url` are the properties available to this resource. ### Actions --- The **homebrew_tap** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:tap` Add a Homebrew tap. (default) `:untap` Remove a Homebrew tap. ### Properties --- The **homebrew_tap** resource has the following properties: `homebrew_path` **Ruby Type:** String | **Default Value:** `/usr/local/bin/brew` The path to the Homebrew binary. `owner` **Ruby Type:** String | **Default Value:** `Calculated default username` The owner of the Homebrew installation. `tap_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the tap name if it differs from the resource block’s name. `url` **Ruby Type:** String The URL of the tap. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. homebrew_update resource ------------------------- [homebrew_update resource page](homebrew_update/index) --- Use the **homebrew_update** resource to manage Homebrew repository updates on macOS. **New in Chef Infra Client 16.2.** ### Syntax --- The full syntax for all of the properties that are available to the **homebrew_update** resource is: ``` homebrew_update 'name' do frequency Integer # default value: 86400 action Symbol # defaults to :periodic if not specified end ``` where: * `homebrew_update` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `frequency` is the property available to this resource. ### Actions --- The **homebrew_update** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:periodic` Run a periodic update based on the frequency property. (default) `:update` Run an immediate update. ### Properties --- The **homebrew_update** resource has the following properties: `frequency` **Ruby Type:** Integer | **Default Value:** `86400` Determines how frequently (in seconds) Homebrew updates are made. Use this property when the `:periodic` action is specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **homebrew_update** resource in recipes: **Update the homebrew repository data at a specified interval**: ``` homebrew_update 'all platforms' do frequency 86400 action :periodic end ``` **Update the Homebrew repository at the start of a Chef Infra Client run**: ``` homebrew_update 'update' ``` hostname resource ----------------- [hostname resource page](hostname/index) --- Use the **hostname** resource to set the system’s hostname, configure hostname and hosts config file, and re-run the Ohai hostname plugin so the hostname will be available in subsequent cookbooks. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **hostname** resource is: ``` hostname 'name' do aliases Array compile_time true, false # default value: true domain_password String domain_user String fqdn String hostname String # default value: 'name' unless specified ipaddress String # default value: The node's IP address as determined by Ohai. windows_reboot true, false # default value: true action Symbol # defaults to :set if not specified end ``` where: * `hostname` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `aliases`, `compile_time`, `domain_password`, `domain_user`, `fqdn`, `hostname`, `ipaddress`, and `windows_reboot` are the properties available to this resource. ### Actions --- The **hostname** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Sets the node’s hostname. (default) ### Properties --- The **hostname** resource has the following properties: `aliases` **Ruby Type:** Array An array of hostname aliases to use when configuring the hosts file. `compile_time` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the resource should be run at compile time. `domain_password` **Ruby Type:** String The password to accompany the domain_user parameter New in Chef Infra Client 17.2 `domain_user` **Ruby Type:** String A domain account specified in the form of DOMAIN\user used when renaming a domain-joined device New in Chef Infra Client 17.2 `fqdn` **Ruby Type:** String An optional property to set the fqdn if it differs from the resource block’s hostname. New in Chef Infra Client 17.0 `hostname` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the hostname if it differs from the resource block’s name. `ipaddress` **Ruby Type:** String | **Default Value:** `The node's IP address as determined by Ohai.` The IP address to use when configuring the hosts file. `windows_reboot` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not Windows should be reboot after changing the hostname, as this is required for the change to take effect. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **hostname** resource in recipes: **Set the hostname using the IP address, as detected by Ohai**: ``` hostname 'example' ``` **Manually specify the hostname and IP address**: ``` hostname 'statically_configured_host' do hostname 'example' ipaddress '198.51.100.2' end ``` **Change the hostname of a Windows, Non-Domain joined node**: ``` hostname 'renaming a workgroup computer' do hostname 'Foo' end ``` **Change the hostname of a Windows, Domain-joined node (new in 17.2)**: ``` hostname 'renaming a domain-joined computer' do hostname 'Foo' domain_user "Domain\Someone" domain_password 'SomePassword' end ``` http_request resource ---------------------- [http_request resource page](http_request/index) --- Use the **http_request** resource to send an HTTP request (`GET`, `PUT`, `POST`, `DELETE`, `HEAD`, or `OPTIONS`) with an arbitrary message. This resource is often useful when custom callbacks are necessary. ### Syntax --- A **http_request** resource block sends HTTP requests with an arbitrary message. For example, send a `DELETE` request to `'http://www.chef.io/some_page?message=please_delete_me'`. ``` http_request 'please_delete_me' do url 'http://www.chef.io/some_page' action :delete end ``` The full syntax for all of the properties that are available to the **http_request** resource is: ``` http_request 'name' do headers Hash message Object # defaults to 'name' if not specified url String action Symbol # defaults to :get if not specified end ``` where: * `http_request` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `headers`, `message`, and `url` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **http_request** resource has the following actions: `:delete` Send a `DELETE` request. `:get` Default. Send a `GET` request. Changed in Chef Client 12.0 to deprecate the hard-coded query string from earlier versions. Cookbooks that rely on this string need to be updated to manually add it to the URL as it is passed to the resource. `:head` Send a `HEAD` request. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:options` Send an `OPTIONS` request. `:post` Send a `POST` request. `:put` Send a `PUT` request. ### Properties --- The **http_request** resource has the following properties: `headers` **Ruby Type:** Hash A Hash of custom headers. `message` **Ruby Type:** Object The message that is sent by the HTTP request. Default value: the `name` of the resource block. See “Syntax” section above for more information. `url` **Ruby Type:** String The URL to which an HTTP request is sent. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **http_request** resource in recipes: Send a GET request ``` http_request 'some_message' do url 'http://example.com/check_in' end ``` The message is sent as `http://example.com/check_in?message=some_message`. Send a POST request To send a `POST` request as JSON data, convert the message to JSON and include the correct content-type header. For example: ``` http_request 'posting data' do action :post url 'http://example.com/check_in' message ({:some => 'data'}.to_json) headers({'AUTHORIZATION' => "Basic #{ Base64.encode64('username:password')}", 'Content-Type' => 'application/data' }) end ``` Transfer a file only when the remote source changes ``` remote_file '/tmp/couch.png' do source 'http://couchdb.apache.org/img/sketch.png' action :nothing end http_request 'HEAD http://couchdb.apache.org/img/sketch.png' do message '' url 'http://couchdb.apache.org/img/sketch.png' action :head if ::File.exist?('/tmp/couch.png') headers 'If-Modified-Since' => File.mtime('/tmp/couch.png').httpdate end notifies :create, 'remote_file[/tmp/couch.png]', :immediately end ``` ifconfig resource ----------------- [ifconfig resource page](ifconfig/index) --- Use the **ifconfig** resource to manage interfaces on Unix and Linux systems. Note This resource requires the ifconfig binary to be present on the system and may require additional packages to be installed first. On Ubuntu 18.04 or later you will need to install the `ifupdown` package, which disables the built in Netplan functionality. Warning This resource will not work with Fedora release 33 or later. ### Syntax --- The full syntax for all of the properties that are available to the **ifconfig** resource is: ``` ifconfig 'name' do bcast String bonding_opts String bootproto String bridge String device String ethtool_opts String family String # default value: "inet" gateway String hwaddr String inet_addr String mask String master String metric String mtu String network String onboot String onparent String slave String target String # default value: 'name' unless specified vlan String action Symbol # defaults to :add if not specified end ``` where: * `ifconfig` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bcast`, `bonding_opts`, `bootproto`, `bridge`, `device`, `ethtool_opts`, `family`, `gateway`, `hwaddr`, `inet_addr`, `mask`, `master`, `metric`, `mtu`, `network`, `onboot`, `onparent`, `slave`, `target`, and `vlan` are the properties available to this resource. ### Actions --- The **ifconfig** resource has the following actions: `:add` Run ifconfig to configure a network interface and (on some platforms) write a configuration file for that network interface. (default) `:delete` Run ifconfig to disable a network interface and (on some platforms) delete that network interface’s configuration file. `:disable` Run ifconfig to disable a network interface. `:enable` Run ifconfig to enable a network interface. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **ifconfig** resource has the following properties: `bcast` **Ruby Type:** String The broadcast address for a network interface. On some platforms this property is not set using ifconfig, but instead is added to the startup configuration file for the network interface. `bonding_opts` **Ruby Type:** String Bonding options to pass via `BONDING_OPTS` on RHEL and CentOS. For example: `mode=active-backup miimon=100`. New in Chef Client 13.4 `bootproto` **Ruby Type:** String The boot protocol used by a network interface. `bridge` **Ruby Type:** String The bridge interface this interface is a member of on Red Hat based systems. New in Chef Infra Client 16.7 `device` **Ruby Type:** String The network interface to be configured. `ethtool_opts` **Ruby Type:** String Options to be passed to ethtool(8). For example: `-A eth0 autoneg off rx off tx off`. New in Chef Client 13.4 `family` **Ruby Type:** String | **Default Value:** `inet` Networking family option for Debian-based systems; for example: `inet` or `inet6`. New in Chef Client 14.0 `gateway` **Ruby Type:** String The gateway to use for the interface. New in Chef Client 14.4 `hwaddr` **Ruby Type:** String The hardware address for the network interface. `inet_addr` **Ruby Type:** String The Internet host address for the network interface. `mask` **Ruby Type:** String The decimal representation of the network mask. For example: `255.255.255.0`. `master` **Ruby Type:** String Specifies the channel bonding interface to which the Ethernet interface is linked. New in Chef Client 13.4 `metric` **Ruby Type:** String The routing metric for the interface. `mtu` **Ruby Type:** String The maximum transmission unit (MTU) for the network interface. `network` **Ruby Type:** String The address for the network interface. `onboot` **Ruby Type:** String Bring up the network interface on boot. `onparent` **Ruby Type:** String Bring up the network interface when its parent interface is brought up. `slave` **Ruby Type:** String When set to `yes`, this device is controlled by the channel bonding interface that is specified via the `master` property. New in Chef Client 13.4 `target` **Ruby Type:** String | **Default Value:** `The resource block's name` The IP address that is to be assigned to the network interface. If not specified we’ll use the resource’s name. `vlan` **Ruby Type:** String The VLAN to assign the interface to. New in Chef Client 14.4 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **ifconfig** resource in recipes: **Configure a network interface with a static IP** ``` ifconfig '33.33.33.80' do device 'eth1' end ``` will create the following interface configuration: ``` iface eth1 inet static address 33.33.33.80 ``` **Configure an interface to use DHCP** ``` ifconfig 'Set eth1 to DHCP' do device 'eth1' bootproto 'dhcp' end ``` will create the following interface configuration: ``` iface eth1 inet dhcp ``` **Update a static IP address with a boot protocol** ``` ifconfig "33.33.33.80" do bootproto "dhcp" device "eth1" end ``` will update the interface configuration from static to dhcp: ``` iface eth1 inet dhcp address 33.33.33.80 ``` inspec_input resource ---------------------- [inspec_input resource page](inspec_input/index) --- Use the **inspec_input** resource to add an input to the Compliance Phase. **New in Chef Infra Client 17.5.** ### Syntax --- The full syntax for all of the properties that are available to the **inspec_input** resource is: ``` inspec_input 'name' do input Hash, String # default value: 'name' unless specified source Hash, String # default value: 'name' unless specified action Symbol # defaults to :add if not specified end ``` where: * `inspec_input` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `input` and `source` are the properties available to this resource. ### Actions --- The **inspec_input** resource has the following actions: `:add` Add an input to the compliance phase (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **inspec_input** resource has the following properties: `input` **Ruby Type:** Hash, String | **Default Value:** `The resource block's name` `source` **Ruby Type:** Hash, String | **Default Value:** `The resource block's name` ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **inspec_input** resource in recipes: **Activate the default input in the openssh cookbook’s compliance segment**: ``` inspec_input 'openssh' do action :add end ``` **Activate all inputs in the openssh cookbook’s compliance segment**: ``` inspec_input 'openssh::.*' do action :add end ``` **Add an InSpec input to the Compliance Phase from a hash**: ``` inspec_input { ssh_custom_path: '/whatever2' } ``` **Add an InSpec input to the Compliance Phase using the ‘name’ property to identify the input**: ``` inspec_input "setting my input" do source( { ssh_custom_path: '/whatever2' }) end ``` **Add an InSpec input to the Compliance Phase using a TOML, JSON, or YAML file**: ``` inspec_input "/path/to/my/input.yml" ``` **Add an InSpec input to the Compliance Phase using a TOML, JSON, or YAML file, using the ‘name’ property**: ``` inspec_input "setting my input" do source "/path/to/my/input.yml" end ``` Note that the **inspec_input** resource does not update and will not fire notifications (similar to the log resource). This is done to preserve the ability to use the resource while not causing the updated resource count to be larger than zero. Since the resource does not update the state of the managed node, this behavior is still consistent with the configuration management model. Instead, you should use events to observe configuration changes for the compliance phase. It is possible to use the `notify_group` resource to chain notifications of the two resources, but notifications are the wrong model to use, and you should use pure ruby conditionals instead. Compliance configuration should be independent of other resources and should only be conditional based on state/attributes, not other resources. inspec_waiver resource ----------------------- [inspec_waiver resource page](inspec_waiver/index) --- Use the **inspec_waiver** resource to add a waiver to the Compliance Phase. **New in Chef Infra Client 17.5.** ### Syntax --- The full syntax for all of the properties that are available to the **inspec_waiver** resource is: ``` inspec_waiver 'name' do control String # default value: 'name' unless specified expiration String justification String run_test true, false source Hash, String action Symbol # defaults to :add if not specified end ``` where: * `inspec_waiver` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `control`, `expiration`, `justification`, `run_test`, and `source` are the properties available to this resource. ### Actions --- The **inspec_waiver** resource has the following actions: `:add` Add a waiver to the compliance phase (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **inspec_waiver** resource has the following properties: `control` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the control being waived `expiration` **Ruby Type:** String The expiration date of the waiver - provided in YYYY-MM-DD format `justification` **Ruby Type:** String Can be any text you want and might include a reason for the waiver as well as who signed off on the waiver. `run_test` **Ruby Type:** true, false If present and true, the control will run and be reported, but failures in it won’t make the overall run fail. If absent or false, the control will not be run. `source` **Ruby Type:** Hash, String ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **inspec_waiver** resource in recipes: **Activate the default waiver in the openssh cookbook’s compliance segment**: ``` inspec_waiver 'openssh' do action :add end ``` **Activate all waivers in the openssh cookbook’s compliance segment**: ``` inspec_waiver 'openssh::.*' do action :add end ``` **Add an InSpec waiver to the Compliance Phase**: ``` inspec_waiver 'Add waiver entry for control' do control 'my_inspec_control_01' run_test false justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" expiration '2022-01-01' action :add end ``` **Add an InSpec waiver to the Compliance Phase using the ‘name’ property to identify the control**: ``` inspec_waiver 'my_inspec_control_01' do justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" action :add end ``` **Add an InSpec waiver to the Compliance Phase using an arbitrary YAML, JSON, or TOML file**: ``` # files ending in .yml or .yaml that exist are parsed as YAML inspec_waiver "/path/to/my/waiver.yml" inspec_waiver "my-waiver-name" do source "/path/to/my/waiver.yml" end # files ending in .json that exist are parsed as JSON inspec_waiver "/path/to/my/waiver.json" inspec_waiver "my-waiver-name" do source "/path/to/my/waiver.json" end # files ending in .toml that exist are parsed as TOML inspec_waiver "/path/to/my/waiver.toml" inspec_waiver "my-waiver-name" do source "/path/to/my/waiver.toml" end ``` **Add an InSpec waiver to the Compliance Phase using a hash**: ``` my_hash = { "ssh-01" => { "expiration_date" => "2033-07-31", "run" => false, "justification" => "because" } } inspec_waiver "my-waiver-name" do source my_hash end ``` Note that the **inspec_waiver** resource does not update and will not fire notifications (similar to the log resource). This is done to preserve the ability to use the resource while not causing the updated resource count to be larger than zero. Since the resource does not update the state of the managed node, this behavior is still consistent with the configuration management model. Instead, you should use events to observe configuration changes for the compliance phase. It is possible to use the `notify_group` resource to chain notifications of the two resources, but notifications are the wrong model to use, and you should use pure ruby conditionals instead. Compliance configuration should be independent of other resources and should only be conditional based on state/attributes, not other resources. inspec_waiver_file_entry resource ------------------------------------ [inspec_waiver_file_entry resource page](inspec_waiver_file_entry/index) --- Use the **inspec_waiver_file_entry** resource to add or remove entries from an InSpec waiver file. This can be used in conjunction with the Compliance Phase. **New in Chef Infra Client 17.1.** ### Syntax --- The full syntax for all of the properties that are available to the **inspec_waiver_file_entry** resource is: ``` inspec_waiver_file_entry 'name' do backup false, Integer # default value: false control String # default value: 'name' unless specified expiration String file_path String justification String run_test true, false action Symbol # defaults to :add if not specified end ``` where: * `inspec_waiver_file_entry` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `backup`, `control`, `expiration`, `file_path`, `justification`, and `run_test` are the properties available to this resource. ### Actions --- The **inspec_waiver_file_entry** resource has the following actions: `:add` (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` ### Properties --- The **inspec_waiver_file_entry** resource has the following properties: `backup` **Ruby Type:** false, Integer | **Default Value:** `false` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `control` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the control being added or removed to the waiver file `expiration` **Ruby Type:** String The expiration date of the given waiver - provided in YYYY-MM-DD format `file_path` **Ruby Type:** String | **Default Value:** ``/etc/chef/inspec_waivers.yml` on Linux/Unix and `C:\chef\inspec_waivers.yml` on Windows` | `REQUIRED` The path to the waiver file being modified `justification` **Ruby Type:** String Can be any text you want and might include a reason for the waiver as well as who signed off on the waiver. `run_test` **Ruby Type:** true, false If present and `true`, the control will run and be reported, but failures in it won’t make the overall run fail. If absent or `false`, the control will not be run. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **inspec_waiver_file_entry** resource in recipes: **Add an InSpec waiver entry to a given waiver file**: ``` inspec_waiver_file_entry 'Add waiver entry for control' do file_path 'C:\chef\inspec_waiver_file.yml' control 'my_inspec_control_01' run_test false justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" expiration '2022-01-01' action :add end ``` **Add an InSpec waiver entry to a given waiver file using the ‘name’ property to identify the control**: ``` inspec_waiver_file_entry 'my_inspec_control_01' do justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" action :add end ``` **Remove an InSpec waiver entry to a given waiver file**: ``` inspec_waiver_file_entry "my_inspec_control_01" do action :remove end ``` ips_package resource --------------------- [ips_package resource page](ips_package/index) --- Use the **ips_package** resource to manage packages (using Image Packaging System (IPS)) on the Solaris 11 platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **ips_package** resource block manages a package on a node, typically by installing it. The simplest use of the **ips_package** resource is: ``` ips_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **ips_package** resource is: ``` ips_package 'name' do accept_license true, false # default value: false options String package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `ips_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_license`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **ips_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **ips_package** resource has the following properties: `accept_license` **Ruby Type:** true, false | **Default Value:** `false` Accept an end-user license agreement, automatically. `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **ips_package** resource in recipes: Install a package ``` ips_package 'name of package' do action :install end ``` kernel_module resource ----------------------- [kernel_module resource page](kernel_module/index) --- Use the **kernel_module** resource to manage kernel modules on Linux systems. This resource can load, unload, blacklist, disable, enable, install, and uninstall modules. **New in Chef Infra Client 14.3.** ### Syntax --- The full syntax for all of the properties that are available to the **kernel_module** resource is: ``` kernel_module 'name' do load_dir String # default value: "/etc/modules-load.d" modname String # default value: 'name' unless specified options Array unload_dir String # default value: "/etc/modprobe.d" action Symbol # defaults to :install if not specified end ``` where: * `kernel_module` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `load_dir`, `modname`, `options`, and `unload_dir` are the properties available to this resource. ### Actions --- The **kernel_module** resource has the following actions: `:blacklist` Blacklist a kernel module. `:disable` Disable a kernel module. **New in Chef Infra Client 15.2.** `:enable` Enable a kernel module. Reverse :disable actions `:install` Load kernel module, and ensure it loads on reboot. (default) `:load` Load a kernel module. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:uninstall` Unload a kernel module and remove module config, so it doesn’t load on reboot. `:unload` Unload kernel module. ### Properties --- The **kernel_module** resource has the following properties: `load_dir` **Ruby Type:** String | **Default Value:** `/etc/modules-load.d` The directory to load modules from. `modname` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the kernel module name if it differs from the resource block’s name. `options` **Ruby Type:** Array An optional property to set options for the kernel module. New in Chef Infra Client 15.4 `unload_dir` **Ruby Type:** String | **Default Value:** `/etc/modprobe.d` The modprobe.d directory. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **kernel_module** resource in recipes: Install and load a kernel module, and ensure it loads on reboot. ``` kernel_module 'loop' ``` Install and load a kernel with a specific set of options, and ensure it loads on reboot. Consult kernel module documentation for specific options that are supported. ``` kernel_module 'loop' do options [ 'max_loop=4', 'max_part=8', ] end ``` Load a kernel module. ``` kernel_module 'loop' do action :load end ``` Unload a kernel module and remove module config, so it doesn’t load on reboot. ``` kernel_module 'loop' do action :uninstall end ``` Unload kernel module. ``` kernel_module 'loop' do action :unload end ``` Blacklist a module from loading. ``` kernel_module 'loop' do action :blacklist end ``` Disable a kernel module so that it is not installable. ``` kernel_module 'loop' do action :disable end ``` Enable a kernel module so that it is can be installed. Does not load or install. ``` kernel_module 'loop' do action :enable end ``` ksh resource ------------ [ksh resource page](ksh/index) --- Use the **ksh** resource to execute scripts using the Korn shell (ksh) interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **ksh** resource block executes scripts using ksh: ``` ksh 'hello world' do code <<-EOH echo "Hello world!" echo "Current directory: " $cwd EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **ksh** resource is: ``` ksh 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `ksh` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **ksh** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. ### Properties --- The **ksh** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. launchd resource ---------------- [launchd resource page](launchd/index) --- Use the **launchd** resource to manage system-wide services (daemons) and per-user services (agents) on the macOS platform. **New in Chef Infra Client 12.8.** ### Syntax --- The full syntax for all of the properties that are available to the **launchd** resource is: ``` launchd 'name' do abandon_process_group true, false backup Integer, false cookbook String debug true, false disabled true, false # default value: false enable_globbing true, false enable_transactions true, false environment_variables Hash exit_timeout Integer group String, Integer hard_resource_limits Hash inetd_compatibility Hash init_groups true, false keep_alive true, false, Hash label String # default value: 'name' unless specified launch_events Hash launch_only_once true, false ld_group String limit_load_from_hosts Array limit_load_to_hosts Array limit_load_to_session_type Array, String low_priority_io true, false mach_services Hash mode String, Integer nice Integer on_demand true, false owner String, Integer path String plist_hash Hash process_type String program String program_arguments Array queue_directories Array root_directory String run_at_load true, false session_type String sockets Hash soft_resource_limits Array source String standard_error_path String standard_in_path String standard_out_path String start_calendar_interval Hash, Array start_interval Integer start_on_mount true, false throttle_interval Integer time_out Integer type String # default value: "daemon" username String wait_for_debugger true, false watch_paths Array working_directory String action Symbol # defaults to :create if not specified end ``` where: * `launchd` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `abandon_process_group`, `backup`, `cookbook`, `debug`, `disabled`, `enable_globbing`, `enable_transactions`, `environment_variables`, `exit_timeout`, `group`, `hard_resource_limits`, `inetd_compatibility`, `init_groups`, `keep_alive`, `label`, `launch_events`, `launch_only_once`, `ld_group`, `limit_load_from_hosts`, `limit_load_to_hosts`, `limit_load_to_session_type`, `low_priority_io`, `mach_services`, `mode`, `nice`, `on_demand`, `owner`, `path`, `plist_hash`, `process_type`, `program`, `program_arguments`, `queue_directories`, `root_directory`, `run_at_load`, `session_type`, `sockets`, `soft_resource_limits`, `source`, `standard_error_path`, `standard_in_path`, `standard_out_path`, `start_calendar_interval`, `start_interval`, `start_on_mount`, `throttle_interval`, `time_out`, `type`, `username`, `wait_for_debugger`, `watch_paths`, and `working_directory` are the properties available to this resource. ### Actions --- The **launchd** resource has the following actions: `:create` Create a launchd property list. (default) `:create_if_missing` Create a launchd property list, if it does not already exist. `:delete` Delete a launchd property list. This will unload a daemon or agent, if loaded. `:disable` Disable a launchd property list. `:enable` Create a launchd property list, and then ensure that it is enabled. If a launchd property list already exists, but does not match, updates the property list to match, and then restarts the daemon or agent. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:restart` Restart a launchd managed daemon or agent. ### Properties --- The **launchd** resource has the following properties: `abandon_process_group` **Ruby Type:** true, false If a job dies, all remaining processes with the same process ID may be kept running. Set to true to kill all remaining processes. `backup` **Ruby Type:** Integer, false The number of backups to be kept in `/var/chef/backup`. Set to `false` to prevent backups from being kept. `cookbook` **Ruby Type:** String The name of the cookbook in which the source files are located. `group` **Ruby Type:** String, Integer When launchd is run as the root user, the group to run the job as. If the `username` property is specified and this property is not, this value is set to the default group for the user. `label` **Ruby Type:** String The unique identifier for the job. `mode` **Ruby Type:** Integer, String | **Default Value:** `'0755'` A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the `name` of the resource block. See “Syntax” section above for more information. `plist_hash` **Ruby Type:** Hash A Hash of key value pairs used to create the launchd property list. `session_type` **Ruby Type:** String The type of launchd plist to be created. Possible values: `system` (default) or `user`. `source` **Ruby Type:** String The path to the launchd property list. `type` **Ruby Type:** String The type of resource. Possible values: `daemon` (default), `agent`. `abandon_process_group` **Ruby Type:** true, false If a job dies, all remaining processes with the same process ID may be kept running. Set to true to kill all remaining processes. `debug` **Ruby Type:** true, false Sets the log mask to `LOG_DEBUG` for this job. `disabled` **Ruby Type:** true, false | **Default Value:** `false` Hints to `launchctl` to not submit this job to launchd. `enable_globbing` **Ruby Type:** true, false Update program arguments before invocation. `enable_transactions` **Ruby Type:** true, false Track in-progress transactions; if none, then send the `SIGKILL` signal. `environment_variables` **Ruby Type:** Hash Additional environment variables to set before running a job. `exit_timeout` **Ruby Type:** Integer The amount of time (in seconds) launchd waits before sending a `SIGKILL` signal. `hard_resource_limits` **Ruby Type:** Hash A Hash of resource limits to be imposed on a job. `inetd_compatibility` **Ruby Type:** Hash Specifies if a daemon expects to be run as if it were launched from inetd. Set to `wait => true` to pass standard input, output, and error file descriptors. Set to `wait => false` to call the accept system call on behalf of the job, and then pass standard input, output, and error file descriptors. `init_groups` **Ruby Type:** true, false Specify if `initgroups` is called before running a job. `keep_alive` **Ruby Type:** true, false, Hash Keep a job running continuously (true) or allow demand and conditions on the node to determine if the job keeps running (`false`). New in Chef Client 12.14 `launch_events` **Ruby Type:** Hash Specify higher-level event types to be used as launch-on-demand event sources. New in Chef Infra Client 15.1 `launch_only_once` **Ruby Type:** true, false Specify if a job can be run only one time. Set this value to true if a job cannot be restarted without a full machine reboot. `limit_load_from_hosts` **Ruby Type:** Array An array of hosts to which this configuration file does not apply, i.e. ‘apply this configuration file to all hosts not specified in this array’. `limit_load_to_hosts` **Ruby Type:** Array An array of hosts to which this configuration file applies. `limit_load_to_session_type` **Ruby Type:** Array, String The session type(s) to which this configuration file applies. `low_priority_io` **Ruby Type:** true, false Specify if the kernel on the node should consider this daemon to be low priority during file system I/O. `mach_services` **Ruby Type:** Hash Specify services to be registered with the bootstrap subsystem. `nice` **Ruby Type:** Integer The program scheduling priority value in the range -20 to 19. `on_demand` **Ruby Type:** true, false Keep a job alive. Only applies to macOS version 10.4 (and earlier); use `keep_alive` instead for newer versions. `process_type` **Ruby Type:** String The intended purpose of the job: `Adaptive`, `Background`, `Interactive`, or `Standard`. `program` **Ruby Type:** String The first argument of `execvp`, typically the file name associated with the file to be executed. This value must be specified if `program_arguments` is not specified, and vice-versa. `program_arguments` **Ruby Type:** Array The second argument of `execvp`. If program is not specified, this property must be specified and will be handled as if it were the first argument. `queue_directories` **Ruby Type:** Array An array of non-empty directories which, if any are modified, will cause a job to be started. `root_directory` **Ruby Type:** String `chroot` to this directory, and then run the job. `run_at_load` **Ruby Type:** true, false Launch a job once (at the time it is loaded). `sockets` **Ruby Type:** Hash A Hash of on-demand sockets that notify launchd when a job should be run. `soft_resource_limits` **Ruby Type:** Array A Hash of resource limits to be imposed on a job. `standard_error_path` **Ruby Type:** String The file to which standard error (`stderr`) is sent. `standard_in_path` **Ruby Type:** String The file to which standard input (`stdin`) is sent. `standard_out_path` **Ruby Type:** String The file to which standard output (`stdout`) is sent. `start_calendar_interval` **Ruby Type:** Hash A Hash (similar to `crontab`) that defines the calendar frequency at which a job is started. For example: `{ Minute => "0", Hour => "20", Day => "*", Weekday => "1-5", Month => "*" }` will run a job at 8:00 PM every day, Monday through Friday, every month of the year. `start_interval` **Ruby Type:** Integer The frequency (in seconds) at which a job is started. `start_on_mount` **Ruby Type:** true, false Start a job every time a file system is mounted. `throttle_interval` **Ruby Type:** Integer | **Default Value:** `10` The frequency (in seconds) at which jobs are allowed to spawn. `time_out` **Ruby Type:** Integer The amount of time (in seconds) a job may be idle before it times out. If no value is specified, the default timeout value for launchd will be used. `username` **Ruby Type:** String When launchd is run as the root user, the user to run the job as. `wait_for_debugger` **Ruby Type:** true, false Specify if launchd has a job wait for a debugger to attach before executing code. `watch_paths` **Ruby Type:** Array An array of paths which, if any are modified, will cause a job to be started. `working_directory` **Ruby Type:** String `chdir` to this directory, and then run the job. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **launchd** resource in recipes: Create a Launch Daemon from a cookbook file ``` launchd 'com.chef.every15' do source 'com.chef.every15.plist' end ``` Create a Launch Daemon using keys ``` launchd 'call.mom.weekly' do program '/Library/scripts/call_mom.sh' start_calendar_interval 'Weekday' => 7, 'Hourly' => 10 time_out 300 end ``` Remove a Launch Daemon ``` launchd 'com.chef.every15' do action :delete end ``` link resource ------------- [link resource page](link/index) --- Use the **link** resource to create symbolic or hard links. A symbolic link—sometimes referred to as a soft link—is a directory entry that associates a file name with a string that contains an absolute or relative path to a file on any file system. In other words, “a file that contains a path that points to another file.” A symbolic link creates a new file with a new inode that points to the inode location of the original file. A hard link is a directory entry that associates a file with another file in the same file system. In other words, “multiple directory entries to the same file.” A hard link creates a new file that points to the same inode as the original file. On Windows, this resource can be used to create directory junction/reparse points. ### Syntax --- A **link** resource block creates symbolic or hard links. For example, to create a hard link from `/tmp/file` to `/etc/file`: ``` link '/tmp/file' do to '/etc/file' link_type :hard end ``` Because the default value for `link_type` is symbolic, and because properties that are not specified in the resource block will be assigned their default values, the following example creates a symbolic link: ``` link '/tmp/file' do to '/etc/file' end ``` The full syntax for all of the properties that are available to the **link** resource is: ``` link 'name' do group String, Integer link_type String, Symbol # default value: :symbolic mode Integer, String owner String, Integer target_file String # default value: 'name' unless specified to String action Symbol # defaults to :create if not specified end ``` where: * `link` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `group`, `link_type`, `mode`, `owner`, `target_file`, and `to` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **link** resource has the following actions: `:create` Default. Create a link. If a link already exists (but does not match), update that link to match. `:delete` Delete a link. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **link** resource has the following properties: `group` **Ruby Type:** String, Integer A group name or ID number that identifies the group associated with a symbolic link. `link_type` **Ruby Type:** String, Symbol | **Default Value:** `:symbolic` **Allowed Values:** `:hard, :symbolic` The type of link: `:symbolic` or `:hard`. On Windows, `:symbolic` will create a junction point if the target is a directory. `mode` **Ruby Type:** Integer, String | **Default Value:** `777` If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** String, Integer The owner associated with a symbolic link. `target_file` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the target file if it differs from the resource block’s name. `to` **Ruby Type:** String The actual file to which the link is to be created. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **link** resource in recipes: Create symbolic links The following example will create a symbolic link from `/tmp/file` to `/etc/file`: ``` link '/tmp/file' do to '/etc/file' end ``` Create hard links The following example will create a hard link from `/tmp/file` to `/etc/file`: ``` link '/tmp/file' do to '/etc/file' link_type :hard end ``` Delete links The following example will delete the `/tmp/file` symbolic link and uses the `only_if` guard to run the `test -L` command, which verifies that `/tmp/file` is a symbolic link, and then only deletes `/tmp/file` if the test passes: ``` link '/tmp/file' do action :delete only_if 'test -L /tmp/file' end ``` Create multiple symbolic links The following example creates symbolic links from two files in the `/vol/webserver/cert/` directory to files located in the `/etc/ssl/certs/` directory: ``` link '/vol/webserver/cert/server.crt' do to '/etc/ssl/certs/ssl-cert-name.pem' end link '/vol/webserver/cert/server.key' do to '/etc/ssl/certs/ssl-cert-name.key' end ``` Create platform-specific symbolic links The following example shows installing a filter module on Apache. The package name is different for different platforms, and for the Red Hat Enterprise Linux family, a symbolic link is required: ``` include_recipe 'apache2::default' case node['platform_family'] when 'debian' ... when 'suse' ... when 'rhel', 'fedora' ... link '/usr/lib64/httpd/modules/mod_apreq.so' do to '/usr/lib64/httpd/modules/mod_apreq2.so' only_if 'test -f /usr/lib64/httpd/modules/mod_apreq2.so' end link '/usr/lib/httpd/modules/mod_apreq.so' do to '/usr/lib/httpd/modules/mod_apreq2.so' only_if 'test -f /usr/lib/httpd/modules/mod_apreq2.so' end end ... ``` For the complete recipe, see <https://github.com/onehealth-cookbooks/apache2/blob/68bdfba4680e70b3e90f77e40223dd535bf22c17/recipes/mod_apreq2.rb>. **Create Windows junction/reparse points** This example demonstrates how to create a directory junction/reparse point. In this example, `C:\destination` will be a junction/reparse point to the `C:\source` directory. ``` directory 'C:/source' link 'C:/destination' do link_type :symbolic to 'C:/source' end ``` locale resource --------------- [locale resource page](locale/index) --- Use the **locale** resource to set the system’s locale on Debian and Windows systems. Windows support was added in Chef Infra Client 16.0 **New in Chef Infra Client 14.5.** ### Syntax --- The full syntax for all of the properties that are available to the **locale** resource is: ``` locale 'name' do lang String lc_env Hash # default value: {} action Symbol # defaults to :update if not specified end ``` where: * `locale` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `lang` and `lc_env` are the properties available to this resource. ### Actions --- The **locale** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:update` Update the system’s locale. (default) ### Properties --- The **locale** resource has the following properties: `lang` **Ruby Type:** String Sets the default system language. `lc_env` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of LC_* env variables in the form of `({ 'LC_ENV_VARIABLE' => 'VALUE' })`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **locale** resource in recipes: Set the lang to ‘en_US.UTF-8’ ``` locale 'set system locale' do lang 'en_US.UTF-8' end ``` log resource ------------ [log resource page](log/index) --- ### Syntax --- A **log** resource block adds messages to the log file based on events that occur during a Chef Infra Client run: ``` log 'message' do message 'A message add to the log.' level :info end ``` The full syntax for all of the properties that are available to the **log** resource is: ``` log 'name' do level Symbol # default value: :info message String # default value: 'name' unless specified action Symbol # defaults to :write if not specified end ``` where: * `log` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `level` and `message` are the properties available to this resource. ### Properties --- The log resource has the following properties: `level` **Ruby Type:** Symbol | **Default Value:** `:info` The logging level for displaying this message. Options (in order of priority): `:debug`, `:info`, `:warn`, `:error`, and `:fatal`. `message` **Ruby Type:** String | **Default Value:** `The resource block's name` The message to be added to a log file. Default value: the `name` of the resource block. See “Syntax” section above for more information. ### Log Entries `Chef::Log` will print log entries to the default logger that is configured for the machine on which Chef Infra Client is running. (To create a log entry that is built into the resource collection, use the [log resource](log/index) instead of `Chef::Log`.) ### Supported Log Levels | Log Level | Syntax | | --- | --- | | Fatal | `Chef::Log.fatal('string')` | | Error | `Chef::Log.error('string')` | | Warn | `Chef::Log.warn('string')` | | Info | `Chef::Log.info('string')` | | Debug | `Chef::Log.debug('string')` | The following example shows a series of fatal `Chef::Log` entries: ``` unless node['splunk']['upgrade_enabled'] Chef::Log.fatal('The chef-splunk::upgrade recipe was added to the node,') Chef::Log.fatal('but the attribute `node["splunk"]["upgrade_enabled"]` was not set.') Chef::Log.fatal('I am bailing here so this node does not upgrade.') raise end service 'splunk_stop' do service_name 'splunk' supports status: true action :stop end if node['splunk']['is_server'] splunk_package = 'splunk' url_type = 'server' else splunk_package = 'splunkforwarder' url_type = 'forwarder' end splunk_installer splunk_package do url node['splunk']['upgrade']["#{url_type}_url"] end if node['splunk']['accept_license'] execute 'splunk-unattended-upgrade' do command "#{splunk_cmd} start --accept-license --answer-yes" end else Chef::Log.fatal('You did not accept the license (set node["splunk"]["accept_license"] to true)') Chef::Log.fatal('Splunk is stopped and cannot be restarted until the license is accepted!') raise end ``` The following example shows using multiple `Chef::Log` entry types: ``` ... begin aws = Chef::DataBagItem.load(:aws, :main) Chef::Log.info("Loaded AWS information from DataBagItem aws[#{aws['id']}]") rescue Chef::Log.fatal("Could not find the 'main' item in the 'aws' data bag") raise end ... ``` ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **log** resource in recipes: Set default logging level ``` log 'a string to log' ``` Set debug logging level ``` log 'a debug string' do level :debug end ``` Add a message to a log file ``` log 'message' do message 'This is the message that will be added to the log.' level :info end ``` macos_userdefaults resource ---------------------------- [macos_userdefaults resource page](macos_userdefaults/index) --- Use the **macos_userdefaults** resource to manage the macOS user defaults system. The properties of this resource are passed to the defaults command, and the parameters follow the convention of that command. See the defaults(1) man page for details on how the tool works. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **macos_userdefaults** resource is: ``` macos_userdefaults 'name' do domain String # default value: NSGlobalDomain: the global domain. host String, Symbol key String user String, Symbol value Integer, Float, String, true, false, Hash, Array action Symbol # defaults to :write if not specified end ``` where: * `macos_userdefaults` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `domain`, `host`, `key`, `user`, and `value` are the properties available to this resource. ### Actions --- The **macos_userdefaults** resource has the following actions: `:delete` Delete a key from a domain. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:write` Write the value to the specified domain/key. (default) ### Properties --- The **macos_userdefaults** resource has the following properties: `domain` **Ruby Type:** String | **Default Value:** `NSGlobalDomain: the global domain.` The domain that the user defaults belong to. `host` **Ruby Type:** String, Symbol Set either :current, :all or a hostname to set the user default at the host level. New in Chef Infra Client 16.3 `key` **Ruby Type:** String | `REQUIRED` The preference key. `user` **Ruby Type:** String, Symbol The system user that the default will be applied to. Set :current for current user, :all for all users or pass a valid username `value` **Ruby Type:** Integer, Float, String, true, false, Hash, Array | `REQUIRED` The value of the key. Note With the `type` property set to `bool`, `String` forms of Boolean true/false values that Apple accepts in the defaults command will be coerced: 0/1, ‘TRUE’/‘FALSE,’ ‘true’/false', ‘YES’/‘NO’, or ‘yes’/‘no’. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macos_userdefaults** resource in recipes: **Specify a global domain value** ``` macos_userdefaults 'Full keyboard access to all controls' do key 'AppleKeyboardUIMode' value 2 end ``` **Setting a value on a specific domain** ``` macos_userdefaults 'Enable macOS firewall' do domain '/Library/Preferences/com.apple.alf' key 'globalstate' value 1 end ``` **Specifying the type of a key to skip automatic type detection** ``` macos_userdefaults 'Finder expanded save dialogs' do key 'NSNavPanelExpandedStateForSaveMode' value 'TRUE' type 'bool' end ``` macports_package resource -------------------------- [macports_package resource page](macports_package/index) --- Use the **macports_package** resource to manage packages for the macOS platform using the MacPorts package management system. ### Syntax --- A **macports_package** resource block manages a package on a node, typically by installing it. The simplest use of the **macports_package** resource is: ``` macports_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **macports_package** resource is: ``` macports_package 'name' do options String package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `macports_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **macports_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **macports_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macports_package** resource in recipes: Install a package ``` macports_package 'name of package' do action :install end ``` mdadm resource -------------- [mdadm resource page](mdadm/index) --- Use the **mdadm** resource to manage RAID devices in a Linux environment using the mdadm utility. The mdadm resource will create and assemble an array, but it will not create the config file that is used to persist the array upon reboot. If the config file is required, it must be done by specifying a template with the correct array layout, and then by using the mount provider to create a file systems table (fstab) entry. ### Syntax --- The full syntax for all of the properties that are available to the **mdadm** resource is: ``` mdadm 'name' do bitmap String chunk Integer # default value: 16 devices Array # default value: [] layout String level Integer # default value: 1 metadata String # default value: "0.90" raid_device String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `mdadm` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bitmap`, `chunk`, `devices`, `layout`, `level`, `metadata`, and `raid_device` are the properties available to this resource. ### Actions --- The **mdadm** resource has the following actions: `:assemble` Assemble a previously created array into an active array. `:create` Create an array with per-device superblocks. If an array already exists (but does not match), update that array to match. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:stop` Stop an active array. ### Properties --- The **mdadm** resource has the following properties: `bitmap` **Ruby Type:** String The path to a file in which a write-intent bitmap is stored. `chunk` **Ruby Type:** Integer | **Default Value:** `16` The chunk size. This property should not be used for a RAID 1 mirrored pair (i.e. when the `level` property is set to `1`). `devices` **Ruby Type:** Array | **Default Value:** `[]` The devices to be part of a RAID array. `layout` **Ruby Type:** String The RAID5 parity algorithm. Possible values: `left-asymmetric` (or `la`), `left-symmetric` (or ls), `right-asymmetric` (or `ra`), or `right-symmetric` (or `rs`). `level` **Ruby Type:** Integer | **Default Value:** `1` The RAID level. `metadata` **Ruby Type:** String | **Default Value:** `0.90` The superblock type for RAID metadata. `raid_device` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to specify the name of the RAID device if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **mdadm** resource in recipes: **Create and assemble a RAID 0 array** The mdadm command can be used to create RAID arrays. For example, a RAID 0 array named /dev/md0 with 10 devices would have a command similar to the following: ``` mdadm --create /dev/md0 --level=0 --raid-devices=10 /dev/s01.../dev/s10 ``` where /dev/s01 .. /dev/s10 represents 10 devices (01, 02, 03, and so on). This same command, when expressed as a recipe using the mdadm resource, would be similar to: ``` mdadm '/dev/md0' do devices [ '/dev/s01', ... '/dev/s10' ] level 0 action :create end ``` (again, where /dev/s01 .. /dev/s10 represents devices /dev/s01, /dev/s02, /dev/s03, and so on). **Create and assemble a RAID 1 array** ``` mdadm '/dev/md0' do devices [ '/dev/sda', '/dev/sdb' ] level 1 action [ :create, :assemble ] end ``` **Create and assemble a RAID 5 array** The mdadm command can be used to create RAID arrays. For example, a RAID 5 array named /dev/sd0 with 4, and a superblock type of 0.90 would be similar to: ``` mdadm '/dev/sd0' do devices [ '/dev/s1', '/dev/s2', '/dev/s3', '/dev/s4' ] level 5 metadata '0.90' chunk 32 action :create end ``` mount resource -------------- [mount resource page](mount/index) --- Use the **mount** resource to manage a mounted file system. ### Syntax --- The full syntax for all of the properties that are available to the **mount** resource is: ``` mount 'name' do device String device_type String, Symbol # default value: :device domain String dump Integer, false # default value: 0 enabled true, false # default value: false fsck_device String # default value: "-" fstype String # default value: "auto" mount_point String # default value: 'name' unless specified options Array, String # default value: ["defaults"] pass Integer, false # default value: 2 password String supports Array, Hash # default value: { remount: false } username String action Symbol # defaults to :mount if not specified end ``` where: * `mount` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `device`, `device_type`, `domain`, `dump`, `enabled`, `fsck_device`, `fstype`, `mount_point`, `options`, `pass`, `password`, `supports`, and `username` are the properties available to this resource. ### Actions --- The **mount** resource has the following actions: `:disable` Remove an entry from the file systems table (`fstab`). `:enable` Add an entry to the file systems table (`fstab`). `:mount` Default. Mount a device. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remount` Remount a device. `:umount` Unmount a device. `:unmount` Alias for `:umount` action. ### Properties --- The **mount** resource has the following properties: `device` **Ruby Type:** String Required for `:umount` and `:remount` actions (for the purpose of checking the mount command output for presence). The special block device or remote node, a label, or a uuid to be mounted. `device_type` **Ruby Type:** String, Symbol | **Default Value:** `:device` **Allowed Values:** `:device, :label, :uuid` The type of device: :device, :label, or :uuid `domain` **Ruby Type:** String Windows only: Use to specify the domain in which the `username` and `password` are located. `dump` **Ruby Type:** Integer, false | **Default Value:** `0` The dump frequency (in days) used while creating a file systems table (fstab) entry. `enabled` **Ruby Type:** true, false | **Default Value:** `false` Use to specify if a mounted file system is enabled. `fsck_device` **Ruby Type:** String | **Default Value:** `-` Solaris only: The fsck device. `fstype` **Ruby Type:** String | **Default Value:** `auto` The file system type (fstype) of the device. `mount_point` **Ruby Type:** String | **Default Value:** `The resource block's name` The directory (or path) in which the device is to be mounted. Defaults to the name of the resource block if not provided. `options` **Ruby Type:** Array, String | **Default Value:** `["defaults"]` An array or comma separated list of options for the mount. `pass` **Ruby Type:** Integer, false | **Default Value:** `2` The pass number used by the file system check (fsck) command while creating a file systems table (fstab) entry. `password` **Ruby Type:** String Windows only:. Use to specify the password for username. `supports` **Ruby Type:** Array, Hash | **Default Value:** `{ remount: false }` Specify a Hash of supported mount features. `username` **Ruby Type:** String Windows only: Use to specify the user name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **mount** resource in recipes: Mount a labeled file system ``` mount '/mnt/volume1' do device 'volume1' device_type :label fstype 'xfs' options 'rw' end ``` Mount a local block drive ``` mount '/mnt/local' do device '/dev/sdb1' fstype 'ext3' end ``` Mount a non-block file system ``` mount '/mount/tmp' do pass 0 fstype 'tmpfs' device '/dev/null' options 'nr_inodes=999k,mode=755,size=500m' action [:mount, :enable] end ``` Mount and add to the file systems table ``` mount '/export/www' do device 'nas1prod:/export/web_sites' fstype 'nfs' options 'rw' action [:mount, :enable] end ``` Mount a remote file system ``` mount '/export/www' do device 'nas1prod:/export/web_sites' fstype 'nfs' options 'rw' end ``` Mount a remote folder in Microsoft Windows ``` mount 'T:' do action :mount device '\\\\hostname.example.com\\folder' end ``` Unmount a remote folder in Microsoft Windows ``` mount 'T:' do action :umount device '\\\\hostname.example.com\\D$' end ``` Stop a service, do stuff, and then restart it The following example shows how to use the **execute**, **service**, and **mount** resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following: * Checks to see if the Amazon EC2 node has MySQL * If the node has MySQL, stops MySQL * Installs MySQL * Mounts the node * Restarts MySQL ``` # the following code sample comes from the ``server_ec2`` # recipe in the following cookbook: # https://github.com/chef-cookbooks/mysql if (node.attribute?('ec2') && ! FileTest.directory?(node['mysql']['ec2_path'])) service 'mysql' do action :stop end execute 'install-mysql' do command "mv #{node['mysql']['data_dir']}#{node['mysql']['ec2_path']}" not_if do FileTest.directory?(node['mysql']['ec2_path']) end end [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir| directory dir do owner 'mysql' group 'mysql' end end mount node['mysql']['data_dir'] do device node['mysql']['ec2_path'] fstype 'none' options 'bind,rw' action [:mount, :enable] end service 'mysql' do action :start end end ``` where * the two **service** resources are used to stop, and then restart the MySQL service * the **execute** resource is used to install MySQL * the **mount** resource is used to mount the node and enable MySQL msu_package resource --------------------- [msu_package resource page](msu_package/index) --- Use the **msu_package** resource to install Microsoft Update(MSU) packages on Microsoft Windows machines. **New in Chef Infra Client 12.17.** ### Syntax --- The full syntax for all of the properties that are available to the **msu_package** resource is: ``` msu_package 'name' do checksum String options String package_name String source String timeout String, Integer # default value: 3600 action Symbol # defaults to :install if not specified end ``` where: * `msu_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `checksum`, `options`, `package_name`, `source`, and `timeout` are the properties available to this resource. ### Actions --- The **msu_package** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **msu_package** resource has the following properties: `checksum` **Ruby Type:** String SHA-256 digest used to verify the checksum of the downloaded MSU package. `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The local file path or URL for the MSU package. `timeout` **Ruby Type:** String, Integer | **Default Value:** `3600` The amount of time (in seconds) to wait before timing out. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **msu_package** resource in recipes: Using local path in source ``` msu_package 'Install Windows 2012R2 Update KB2959977' do source 'C:\Users\xyz\AppData\Local\Temp\Windows8.1-KB2959977-x64.msu' action :install end ``` ``` msu_package 'Remove Windows 2012R2 Update KB2959977' do source 'C:\Users\xyz\AppData\Local\Temp\Windows8.1-KB2959977-x64.msu' action :remove end ``` Using URL in source ``` msu_package 'Install Windows 2012R2 Update KB2959977' do source 'https://s3.amazonaws.com/my_bucket/Windows8.1-KB2959977-x64.msu' action :install end ``` ``` msu_package 'Remove Windows 2012R2 Update KB2959977' do source 'https://s3.amazonaws.com/my_bucket/Windows8.1-KB2959977-x64.msu' action :remove end ``` notify_group resource ---------------------- [notify_group resource page](notify_group/index) --- The notify_group resource does nothing, and always fires notifications which are set on it. Use it to DRY blocks of notifications that are common to multiple resources, and provide a single target for other resources to notify. Unlike most resources, its default action is :nothing. **New in Chef Infra Client 15.8.** ### Syntax --- The full syntax for all of the properties that are available to the **notify_group** resource is: ``` notify_group 'name' do action Symbol # defaults to :nothing if not specified end ``` where: * `notify_group` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. ### Actions --- The **notify_group** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` ### Properties --- This resource does not have any properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **notify_group** resource in recipes: Wire up a notification from a service resource to stop and start the service with a 60 second delay. ``` service "crude" do action [ :enable, :start ] end chef_sleep "60" do action :nothing end # Example code for a hypothetical badly behaved service that requires # 60 seconds between a stop and start in order to restart the service # (due to race conditions, bleeding connections down, resources that only # slowly unlock in the background, or other poor software behaviors that # are sometimes encountered). # notify_group "crude_stop_and_start" do notifies :stop, "service[crude]", :immediately notifies :sleep, "chef_sleep[60]", :immediately notifies :start, "service[crude]", :immediately end template "/etc/crude/crude.conf" do source "crude.conf.erb" variables node["crude"] notifies :run, "notify_group[crude_stop_and_start]", :immediately end ``` ohai resource ------------- [ohai resource page](ohai/index) --- Use the **ohai** resource to reload the Ohai configuration on a node. This allows recipes that change system attributes (like a recipe that adds a user) to refer to those attributes later on during the Chef Infra Client run. ### Syntax --- The full syntax for all of the properties that are available to the **ohai** resource is: ``` ohai 'name' do plugin String action Symbol # defaults to :reload if not specified end ``` where: * `ohai` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `plugin` is the property available to this resource. ### Actions --- The **ohai** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reload` Reloads the Ohai data. (default) ### Properties --- The **ohai** resource has the following properties: `plugin` **Ruby Type:** String Specific Ohai attribute data to reload. This property behaves similar to specifying attributes when running Ohai on the command line and takes the attribute that you wish to reload instead of the actual plugin name. For instance, you can pass `ipaddress` to reload `node['ipaddress']` even though that data comes from the `Network` plugin. If this property is not specified, Chef Infra Client will reload all plugins. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **ohai** resource in recipes: Reload All Ohai Plugins ``` ohai 'reload' do action :reload end ``` Reload A Single Ohai Plugin ``` ohai 'reload' do plugin 'ipaddress' action :reload end ``` Reload Ohai after a new user is created ``` ohai 'reload_passwd' do action :nothing plugin 'etc' end user 'daemon_user' do home '/dev/null' shell '/sbin/nologin' system true notifies :reload, 'ohai[reload_passwd]', :immediately end ruby_block 'just an example' do block do # These variables will now have the new values puts node['etc']['passwd']['daemon_user']['uid'] puts node['etc']['passwd']['daemon_user']['gid'] end end ``` ohai_hint resource ------------------- [ohai_hint resource page](ohai_hint/index) --- Use the **ohai_hint** resource to aid in configuration detection by passing hint data to Ohai. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **ohai_hint** resource is: ``` ohai_hint 'name' do compile_time true, false # default value: true content Hash hint_name String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `ohai_hint` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `compile_time`, `content`, and `hint_name` are the properties available to this resource. ### Actions --- The **ohai_hint** resource has the following actions: `:create` Create an Ohai hint file. (default) `:delete` Delete an Ohai hint file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **ohai_hint** resource has the following properties: `compile_time` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the resource is executed during the compile time phase. `content` **Ruby Type:** Hash Values to include in the hint file. `hint_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the hint name if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **ohai_hint** resource in recipes: **Create a hint file** ``` ohai_hint 'example' do content a: 'test_content' end ``` **Create a hint file with a name that does not match the resource name** ``` ohai_hint 'example' do hint_name 'custom' end ``` **Create a hint file that is not loaded at compile time** ``` ohai_hint 'example' do compile_time false end ``` **Delete a hint file** ``` ohai_hint 'example' do action :delete end ``` openbsd_package resource ------------------------- [openbsd_package resource page](openbsd_package/index) --- Use the **openbsd_package** resource to manage packages for the OpenBSD platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **openbsd_package** resource block manages a package on a node, typically by installing it. The simplest use of the **openbsd_package** resource is: ``` openbsd_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **openbsd_package** resource is: ``` openbsd_package 'name' do options String package_name String source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `openbsd_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **openbsd_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. ### Properties --- The **openbsd_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openbsd_package** resource in recipes: **Install a package** ``` openbsd_package 'name of package' do action :install end ``` **Remove a package** ``` openbsd_package 'name of package' do action :remove end ``` openssl_dhparam resource ------------------------- [openssl_dhparam resource page](openssl_dhparam/index) --- Use the **openssl_dhparam** resource to generate `dhparam.pem` files. If a valid `dhparam.pem` file is found at the specified location, no new file will be created. If a file is found at the specified location but it is not a valid `dhparam.pem` file, it will be overwritten. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_dhparam** resource is: ``` openssl_dhparam 'name' do generator Integer # default value: 2 group String, Integer key_length Integer # default value: 2048 mode Integer, String # default value: "0640" owner String, Integer path String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `openssl_dhparam` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `generator`, `group`, `key_length`, `mode`, `owner`, and `path` are the properties available to this resource. ### Actions --- The **openssl_dhparam** resource has the following actions: `:create` Create the `dhparam.pem` file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_dhparam** resource has the following properties: `generator` **Ruby Type:** Integer | **Default Value:** `2` **Allowed Values:** `2, 5` The desired Diffie-Hellmann generator. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key. `mode` **Ruby Type:** Integer, String | **Default Value:** `0640` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_dhparam** resource in recipes: **Create a dhparam file** ``` openssl_dhparam '/etc/httpd/ssl/dhparam.pem' ``` **Create a dhparam file with a specific key length** ``` openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do key_length 4096 end ``` **Create a dhparam file with specific user/group ownership** ``` openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do owner 'www-data' group 'www-data' end ``` **Manually specify the dhparam file path** ``` openssl_dhparam 'httpd_dhparam' do path '/etc/httpd/ssl/dhparam.pem' end ``` openssl_ec_private_key resource ---------------------------------- [openssl_ec_private_key resource page](openssl_ec_private_key/index) --- Use the **openssl_ec_private_key** resource to generate an elliptic curve (EC) private key file. If a valid EC key file can be opened at the specified location, no new file will be created. If the EC key file cannot be opened, either because it does not exist or because the password to the EC key file does not match the password in the recipe, then it will be overwritten. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_ec_private_key** resource is: ``` openssl_ec_private_key 'name' do force true, false # default value: false group String, Integer key_cipher String # default value: "des3" key_curve String # default value: "prime256v1" key_pass String mode Integer, String # default value: "0600" owner String, Integer path String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `openssl_ec_private_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `force`, `group`, `key_cipher`, `key_curve`, `key_pass`, `mode`, `owner`, and `path` are the properties available to this resource. ### Actions --- The **openssl_ec_private_key** resource has the following actions: `:create` Generate the EC private key file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_ec_private_key** resource has the following properties: `force` **Ruby Type:** true, false | **Default Value:** `false` Force creation of the key even if the same key already exists on the node. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_cipher` **Ruby Type:** String | **Default Value:** `des3` The designed cipher to use when generating your key. Run `openssl list-cipher-algorithms` to see available options. `key_curve` **Ruby Type:** String | **Default Value:** `prime256v1` **Allowed Values:** `"prime256v1", "secp224r1", "secp256k1", "secp384r1", "secp521r1"` The desired curve of the generated key (if key_type is equal to ‘ec’). Run openssl ecparam -list_curves to see available options. `key_pass` **Ruby Type:** String The desired passphrase for the key. `mode` **Ruby Type:** Integer, String | **Default Value:** `0600` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_ec_private_key** resource in recipes: **Generate a new ec privatekey with prime256v1 key curve and default des3 cipher** ``` openssl_ec_private_key '/etc/ssl_files/eckey_prime256v1_des3.pem' do key_curve 'prime256v1' key_pass 'something' action :create end ``` **Generate a new ec private key with prime256v1 key curve and aes-128-cbc cipher** ``` openssl_ec_private_key '/etc/ssl_files/eckey_prime256v1_des3.pem' do key_curve 'prime256v1' key_cipher '<KEY>' key_pass 'something' action :create end ``` openssl_ec_public_key resource --------------------------------- [openssl_ec_public_key resource page](openssl_ec_public_key/index) --- Use the **openssl_ec_public_key** resource to generate elliptic curve (EC) public key files from a given EC private key. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_ec_public_key** resource is: ``` openssl_ec_public_key 'name' do group String, Integer mode Integer, String # default value: "0640" owner String, Integer path String # default value: 'name' unless specified private_key_content String private_key_pass String private_key_path String action Symbol # defaults to :create if not specified end ``` where: * `openssl_ec_public_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `group`, `mode`, `owner`, `path`, `private_key_content`, `private_key_pass`, and `private_key_path` are the properties available to this resource. ### Actions --- The **openssl_ec_public_key** resource has the following actions: `:create` Generate the EC public key file from a private key. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_ec_public_key** resource has the following properties: `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `mode` **Ruby Type:** Integer, String | **Default Value:** `0640` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `private_key_content` **Ruby Type:** String The content of the private key including new lines. This property is used in place of private_key_path in instances where you want to avoid having to first write the private key to disk `private_key_pass` **Ruby Type:** String The passphrase of the provided private key. `private_key_path` **Ruby Type:** String The path to the private key file. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_ec_public_key** resource in recipes: **Generate new EC public key from a private key on disk** ``` openssl_ec_public_key '/etc/ssl_files/eckey_prime256v1_des3.pub' do private_key_path '/etc/ssl_files/eckey_prime256v1_des3.pem' private_key_pass 'something' action :create end ``` **Generate new EC public key by passing in a private key** ``` openssl_ec_public_key '/etc/ssl_files/eckey_prime256v1_des3_2.pub' do private_key_content "-----BEGIN EC PRIVATE KEY----- <KEY> -----END EC PRIVATE KEY----- " action :create end ``` openssl_rsa_private_key resource ----------------------------------- [openssl_rsa_private_key resource page](openssl_rsa_private_key/index) --- Use the **openssl_rsa_private_key** resource to generate RSA private key files. If a valid RSA key file can be opened at the specified location, no new file will be created. If the RSA key file cannot be opened, either because it does not exist or because the password to the RSA key file does not match the password in the recipe, it will be overwritten. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_rsa_private_key** resource is: ``` openssl_rsa_private_key 'name' do force true, false # default value: false group String, Integer key_cipher String # default value: "des3" key_length Integer # default value: 2048 key_pass String mode Integer, String # default value: "0600" owner String, Integer path String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `openssl_rsa_private_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `force`, `group`, `key_cipher`, `key_length`, `key_pass`, `mode`, `owner`, and `path` are the properties available to this resource. ### Actions --- The **openssl_rsa_private_key** resource has the following actions: `:create` Create the RSA private key file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_rsa_private_key** resource has the following properties: `force` **Ruby Type:** true, false | **Default Value:** `false` Force creation of the key even if the same key already exists on the node. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_cipher` **Ruby Type:** String | **Default Value:** `des3` The designed cipher to use when generating your key. Run `openssl list-cipher-algorithms` to see available options. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key. `key_pass` **Ruby Type:** String The desired passphrase for the key. `mode` **Ruby Type:** Integer, String | **Default Value:** `0600` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_rsa_private_key** resource in recipes: Generate new 2048bit key with the default des3 cipher ``` openssl_rsa_private_key '/etc/ssl_files/rsakey_des3.pem' do key_length 2048 action :create end ``` Generate new 1024bit key with the aes-128-cbc cipher ``` openssl_rsa_private_key '/etc/ssl_files/rsakey_aes128cbc.pem' do key_length 1024 key_cipher '<KEY>' action :create end ``` openssl_rsa_public_key resource ---------------------------------- [openssl_rsa_public_key resource page](openssl_rsa_public_key/index) --- Use the **openssl_rsa_public_key** resource to generate RSA public key files for a given RSA private key. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_rsa_public_key** resource is: ``` openssl_rsa_public_key 'name' do group String, Integer mode Integer, String # default value: "0640" owner String, Integer path String # default value: 'name' unless specified private_key_content String private_key_pass String private_key_path String action Symbol # defaults to :create if not specified end ``` where: * `openssl_rsa_public_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `group`, `mode`, `owner`, `path`, `private_key_content`, `private_key_pass`, and `private_key_path` are the properties available to this resource. ### Actions --- The **openssl_rsa_public_key** resource has the following actions: `:create` Create the RSA public key file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_rsa_public_key** resource has the following properties: `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `mode` **Ruby Type:** Integer, String | **Default Value:** `0640` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to the public key if it differs from the resource block’s name. `private_key_content` **Ruby Type:** String The content of the private key, including new lines. This property is used in place of private_key_path in instances where you want to avoid having to first write the private key to disk. `private_key_pass` **Ruby Type:** String The passphrase of the provided private key. `private_key_path` **Ruby Type:** String The path to the private key file. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_rsa_public_key** resource in recipes: Generate new public key from a private key on disk ``` openssl_rsa_public_key '/etc/ssl_files/rsakey_des3.pub' do private_key_path '/etc/ssl_files/rsakey_des3.pem' private_key_pass 'something' action :create end ``` Generate new public key by passing in a private key ``` openssl_rsa_public_key '/etc/ssl_files/rsakey_2.pub' do private_key_pass 'something' private_key_content "-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,5EE0AE9A5FE3342E <KEY> " action :create end ``` openssl_x509_certificate resource ----------------------------------- [openssl_x509_certificate resource page](openssl_x509_certificate/index) --- Use the **openssl_x509_certificate** resource to generate signed or self-signed, PEM-formatted x509 certificates. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate. If a CA private key and certificate are provided, the certificate will be signed with them. Note This resource was renamed from openssl_x509 to openssl_x509_certificate. The legacy name will continue to function, but cookbook code should be updated for the new resource name. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_x509_certificate** resource is: ``` openssl_x509_certificate 'name' do ca_cert_file String ca_key_file String ca_key_pass String city String common_name String country String csr_file String email String expire Integer # default value: 365 extensions Hash # default value: {} group String, Integer key_curve String # default value: "prime256v1" key_file String key_length Integer # default value: 2048 key_pass String key_type String # default value: "rsa" mode Integer, String org String org_unit String owner String, Integer path String # default value: 'name' unless specified renew_before_expiry Integer state String subject_alt_name Array # default value: [] action Symbol # defaults to :create if not specified end ``` where: * `openssl_x509_certificate` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ca_cert_file`, `ca_key_file`, `ca_key_pass`, `city`, `common_name`, `country`, `csr_file`, `email`, `expire`, `extensions`, `group`, `key_curve`, `key_file`, `key_length`, `key_pass`, `key_type`, `mode`, `org`, `org_unit`, `owner`, `path`, `renew_before_expiry`, `state`, and `subject_alt_name` are the properties available to this resource. ### Actions --- The **openssl_x509_certificate** resource has the following actions: `:create` Generate a certificate file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_x509_certificate** resource has the following properties: `ca_cert_file` **Ruby Type:** String The path to the CA X509 Certificate on the filesystem. If the `ca_cert_file` property is specified, the `ca_key_file` property must also be specified, the certificate will be signed with them. `ca_key_file` **Ruby Type:** String The path to the CA private key on the filesystem. If the `ca_key_file` property is specified, the `ca_cert_file` property must also be specified, the certificate will be signed with them. `ca_key_pass` **Ruby Type:** String The passphrase for CA private key’s passphrase. `city` **Ruby Type:** String Value for the `L` certificate field. `common_name` **Ruby Type:** String Value for the `CN` certificate field. `country` **Ruby Type:** String Value for the `C` certificate field. `csr_file` **Ruby Type:** String The path to a X509 Certificate Request (CSR) on the filesystem. If the `csr_file` property is specified, the resource will attempt to source a CSR from this location. If no CSR file is found, the resource will generate a Self-Signed Certificate and the certificate fields must be specified (common_name at last). `email` **Ruby Type:** String Value for the `email` certificate field. `expire` **Ruby Type:** Integer | **Default Value:** `365` Value representing the number of days from now through which the issued certificate cert will remain valid. The certificate will expire after this period. `extensions` **Ruby Type:** Hash | **Default Value:** `{}` Hash of X509 Extensions entries, in format `{ 'keyUsage' => { 'values' => %w( keyEncipherment digitalSignature), 'critical' => true } }`. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_curve` **Ruby Type:** String | **Default Value:** `prime256v1` **Allowed Values:** `"prime256v1", "secp384r1", "secp521r1"` The desired curve of the generated key (if key_type is equal to ‘ec’). Run `openssl ecparam -list_curves` to see available options. `key_file` **Ruby Type:** String The path to a certificate key file on the filesystem. If the key_file property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the key_file property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key (if key_type is equal to ‘rsa’). `key_pass` **Ruby Type:** String The passphrase for an existing key’s passphrase. `key_type` **Ruby Type:** String | **Default Value:** `rsa` **Allowed Values:** `"ec", "rsa"` The desired type of the generated key. `mode` **Ruby Type:** Integer, String The permission mode applied to all files created by the resource. `org` **Ruby Type:** String Value for the `O` certificate field. `org_unit` **Ruby Type:** String Value for the `OU` certificate field. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `renew_before_expiry` **Ruby Type:** Integer The number of days before the expiry. The certificate will be automatically renewed when the value is reached. New in Chef Infra Client 15.7 `state` **Ruby Type:** String Value for the `ST` certificate field. `subject_alt_name` **Ruby Type:** Array | **Default Value:** `[]` Array of Subject Alternative Name entries, in format `DNS:example.com` or `IP:1.2.3.4`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_x509_certificate** resource in recipes: Create a simple self-signed certificate file ``` openssl_x509_certificate '/etc/httpd/ssl/mycert.pem' do common_name 'www.f00bar.com' org 'Foo Bar' org_unit 'Lab' country 'US' end ``` Create a certificate using additional options ``` openssl_x509_certificate '/etc/ssl_files/my_signed_cert.crt' do common_name 'www.f00bar.com' ca_key_file '/etc/ssl_files/my_ca.key' ca_cert_file '/etc/ssl_files/my_ca.crt' expire 365 extensions( 'keyUsage' => { 'values' => %w( keyEncipherment digitalSignature), 'critical' => true, }, 'extendedKeyUsage' => { 'values' => %w(serverAuth), 'critical' => false, } ) subject_alt_name ['IP:127.0.0.1', 'DNS:localhost.localdomain'] end ``` openssl_x509_crl resource --------------------------- [openssl_x509_crl resource page](openssl_x509_crl/index) --- Use the **openssl_x509_crl** resource to generate PEM-formatted x509 certificate revocation list (CRL) files. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_x509_crl** resource is: ``` openssl_x509_crl 'name' do ca_cert_file String ca_key_file String ca_key_pass String expire Integer # default value: 8 group String, Integer mode Integer, String owner String, Integer path String # default value: 'name' unless specified renewal_threshold Integer # default value: 1 revocation_reason Integer # default value: 0 serial_to_revoke Integer, String action Symbol # defaults to :create if not specified end ``` where: * `openssl_x509_crl` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ca_cert_file`, `ca_key_file`, `ca_key_pass`, `expire`, `group`, `mode`, `owner`, `path`, `renewal_threshold`, `revocation_reason`, and `serial_to_revoke` are the properties available to this resource. ### Actions --- The **openssl_x509_crl** resource has the following actions: `:create` Create the certificate revocation list (CRL) file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_x509_crl** resource has the following properties: `ca_cert_file` **Ruby Type:** String | `REQUIRED` The path to the CA X509 Certificate on the filesystem. If the `ca_cert_file` property is specified, the `ca_key_file` property must also be specified, the CRL will be signed with them. `ca_key_file` **Ruby Type:** String | `REQUIRED` The path to the CA private key on the filesystem. If the `ca_key_file` property is specified, the `ca_cert_file` property must also be specified, the CRL will be signed with them. `ca_key_pass` **Ruby Type:** String The passphrase for CA private key’s passphrase. `expire` **Ruby Type:** Integer | **Default Value:** `8` Value representing the number of days from now through which the issued CRL will remain valid. The CRL will expire after this period. `group` **Ruby Type:** String, Integer The group permission for the CRL file. `mode` **Ruby Type:** Integer, String The permission mode of the CRL file. `owner` **Ruby Type:** String, Integer The owner permission for the CRL file. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `renewal_threshold` **Ruby Type:** Integer | **Default Value:** `1` Number of days before the expiration. It this threshold is reached, the CRL will be renewed. `revocation_reason` **Ruby Type:** Integer | **Default Value:** `0` Reason for the revocation. `serial_to_revoke` **Ruby Type:** Integer, String Serial of the X509 Certificate to revoke. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_x509_crl** resource in recipes: **Create a certificate revocation file** ``` openssl_x509_crl '/etc/ssl_test/my_ca.crl' do ca_cert_file '/etc/ssl_test/my_ca.crt' ca_key_file '/etc/ssl_test/my_ca.key' end ``` **Create a certificate revocation file for a particular serial** ``` openssl_x509_crl '/etc/ssl_test/my_ca.crl' do ca_cert_file '/etc/ssl_test/my_ca.crt' ca_key_file '/etc/ssl_test/my_ca.key' serial_to_revoke C7BCB6602A2E4251EF4E2827A228CB52BC0CEA2F end ``` openssl_x509_request resource ------------------------------- [openssl_x509_request resource page](openssl_x509_request/index) --- Use the **openssl_x509_request** resource to generate PEM-formatted x509 certificates requests. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_x509_request** resource is: ``` openssl_x509_request 'name' do city String common_name String country String email String group String, Integer key_curve String # default value: "prime256v1" key_file String key_length Integer # default value: 2048 key_pass String key_type String # default value: "ec" mode Integer, String org String org_unit String owner String, Integer path String # default value: 'name' unless specified state String action Symbol # defaults to :create if not specified end ``` where: * `openssl_x509_request` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `city`, `common_name`, `country`, `email`, `group`, `key_curve`, `key_file`, `key_length`, `key_pass`, `key_type`, `mode`, `org`, `org_unit`, `owner`, `path`, and `state` are the properties available to this resource. ### Actions --- The **openssl_x509_request** resource has the following actions: `:create` Generate a certificate request file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_x509_request** resource has the following properties: `city` **Ruby Type:** String Value for the `L` certificate field. `common_name` **Ruby Type:** String | `REQUIRED` Value for the `CN` certificate field. `country` **Ruby Type:** String Value for the `C` certificate field. `email` **Ruby Type:** String Value for the `email` certificate field. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_curve` **Ruby Type:** String | **Default Value:** `prime256v1` **Allowed Values:** `"prime256v1", "secp384r1", "secp521r1"` The desired curve of the generated key (if key_type is equal to `ec`). Run `openssl ecparam -list_curves` to see available options. `key_file` **Ruby Type:** String The path to a certificate key file on the filesystem. If the `key_file` property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the `key_file` property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key (if key_type is equal to `rsa`). `key_pass` **Ruby Type:** String The passphrase for an existing key’s passphrase. `key_type` **Ruby Type:** String | **Default Value:** `ec` **Allowed Values:** `"ec", "rsa"` The desired type of the generated key. `mode` **Ruby Type:** Integer, String The permission mode applied to all files created by the resource. `org` **Ruby Type:** String Value for the `O` certificate field. `org_unit` **Ruby Type:** String Value for the `OU` certificate field. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `state` **Ruby Type:** String Value for the `ST` certificate field. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_x509_request** resource in recipes: **Generate new EC key and CSR file** ``` openssl_x509_request '/etc/ssl_files/my_ec_request.csr' do common_name 'myecrequest.example.com' org 'Test Kitchen Example' org_unit 'Kitchens' country 'UK' end ``` **Generate a new CSR file from an existing EC key** ``` openssl_x509_request '/etc/ssl_files/my_ec_request2.csr' do common_name 'myecrequest2.example.com' org 'Test Kitchen Example' org_unit 'Kitchens' country 'UK' key_file '/etc/ssl_files/my_ec_request.key' end ``` **Generate new RSA key and CSR file** ``` openssl_x509_request '/etc/ssl_files/my_rsa_request.csr' do common_name 'myrsarequest.example.com' org 'Test Kitchen Example' org_unit 'Kitchens' country 'UK' key_type 'rsa' end ``` osx_profile resource --------------------- [osx_profile resource page](osx_profile/index) --- Use the **osx_profile** resource to manage configuration profiles (`.mobileconfig` files) on the macOS platform. The **osx_profile** resource installs profiles by using the uuidgen library to generate a unique `ProfileUUID`, and then using the `profiles` command to install the profile on the system. **New in Chef Infra Client 12.7.** ### Syntax --- The full syntax for all of the properties that are available to the **osx_profile** resource is: ``` osx_profile 'name' do identifier String profile String, Hash profile_name String # default value: 'name' unless specified action Symbol # defaults to :install if not specified end ``` where: * `osx_profile` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `identifier`, `profile`, and `profile_name` are the properties available to this resource. ### Actions --- The **osx_profile** resource has the following actions: `:install` Install the specified configuration profile. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove the specified configuration profile. ### Properties --- The **osx_profile** resource has the following properties: `identifier` **Ruby Type:** String Use to specify the identifier for the profile, such as `com.company.screensaver`. `profile` **Ruby Type:** String, Hash Use to specify a profile. This may be the name of a profile contained in a cookbook or a Hash that contains the contents of the profile. `profile_name` **Ruby Type:** String | **Default Value:** `The resource block's name` Use to specify the name of the profile, if different from the name of the resource block. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **osx_profile** resource in recipes: **Install a profile from a cookbook file** ``` osx_profile 'com.company.screensaver.mobileconfig' ``` **Install profile from a hash** ``` profile_hash = { 'PayloadIdentifier' => 'com.company.screensaver', 'PayloadRemovalDisallowed' => false, 'PayloadScope' => 'System', 'PayloadType' => 'Configuration', 'PayloadUUID' => '1781fbec-3325-565f-9022-8aa28135c3cc', 'PayloadOrganization' => 'Chef', 'PayloadVersion' => 1, 'PayloadDisplayName' => 'Screensaver Settings', 'PayloadContent' => [ { 'PayloadType' => 'com.apple.ManagedClient.preferences', 'PayloadVersion' => 1, 'PayloadIdentifier' => 'com.company.screensaver', 'PayloadUUID' => '73fc30e0-1e57-0131-c32d-000c2944c108', 'PayloadEnabled' => true, 'PayloadDisplayName' => 'com.apple.screensaver', 'PayloadContent' => { 'com.apple.screensaver' => { 'Forced' => [ { 'mcx_preference_settings' => { 'idleTime' => 0, }, }, ], }, }, }, ], } osx_profile 'Install screensaver profile' do profile profile_hash end ``` **Remove profile using identifier in resource name** ``` osx_profile 'com.company.screensaver' do action :remove end ``` **Remove profile by identifier and user friendly resource name** ``` osx_profile 'Remove screensaver profile' do identifier 'com.company.screensaver' action :remove end ``` package resource ---------------- [package resource page](package/index) --- Use the **package** resource to manage packages. When the package is installed from a local file (such as with RubyGems, dpkg, or RPM Package Manager), the file must be added to the node using the **remote_file** or **cookbook_file** resources. This resource is the base resource for several other resources used for package management on specific platforms. While it is possible to use each of these specific resources, it is recommended to use the **package** resource as often as possible. For more information about specific resources for specific platforms, see the following topics: * [apt_package](apt_package/index) * [bff_package](bff_package/index) * [cab_package](cab_package/index) * [chef_gem](chef_gem/index) * [chocolatey_package](chocolatey_package/index) * [dmg_package](dmg_package/index) * [dnf_package](dnf_package/index) * [dpkg_package](dpkg_package/index) * [freebsd_package](freebsd_package/index) * [gem_package](gem_package/index) * [homebrew_package](homebrew_package/index) * [ips_package](ips_package/index) * [macports_package](macports_package/index) * [msu_package](msu_package/index) * [openbsd_package](openbsd_package/index) * [pacman_package](pacman_package/index) * [paludis_package](paludis_package/index) * [portage_package](portage_package/index) * [rpm_package](rpm_package/index) * [smartos_package](smartos_package/index) * [snap_package](snap_package/index) * [solaris_package](solaris_package/index) * [windows_package](windows_package/index) * [yum_package](yum_package/index) * [zypper_package](zypper_package/index) ### Syntax --- A **package** resource block manages a package on a node, typically by installing it. The simplest use of the **package** resource is: ``` package 'httpd' ``` which will install Apache using all of the default options and the default action (`:install`). For a package that has different package names, depending on the platform, use a `case` statement within the **package**: ``` package 'Install Apache' do case node[:platform] when 'redhat', 'centos' package_name 'httpd' when 'ubuntu', 'debian' package_name 'apache2' end end ``` where: * `'redhat', 'centos'` will install Apache using the `httpd` package and `'ubuntu', 'debian'` will install it using the `apache2` package The full syntax for all of the properties that are available to the **package** resource is: ``` package 'name' do allow_downgrade true, false # Yum, RPM packages only arch String, Array # Yum packages only default_release String # Apt packages only flush_cache Array gem_binary String homebrew_user String, Integer # Homebrew packages only notifies # see description options String package_name String, Array # defaults to 'name' if not specified response_file String # Apt packages only response_file_variables Hash # Apt packages only source String subscribes # see description timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `package` tells Chef Infra Client to manage a package; Chef Infra Client will determine the correct package provider to use based on the platform running on the node * `'name'` is the name of the package * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state * `allow_downgrade`, `arch`, `default_release`, `flush_cache`, `gem_binary`, `homebrew_user`, `options`, `package_name`, `response_file`, `response_file_variables`, `source`, `recursive`, `timeout`, and `version` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Gem Package Options The RubyGems package provider attempts to use the RubyGems API to install gems without spawning a new process, whenever possible. A gems command to install will be spawned under the following conditions: * When a `gem_binary` property is specified (as a hash, a string, or by a .gemrc file), Chef Infra Client will run that command to examine its environment settings and then again to install the gem. * When install options are specified as a string, Chef Infra Client will span a gems command with those options when installing the gem. * The Chef installer will search the `PATH` for a gem command rather than defaulting to the current gem environment. As part of `enforce_default_paths`, the `bin` directories area added to the `PATH`, which means when there are no other proceeding RubyGems, the installation will still be operated against it. #### Specify with Hash You should provide the install options as a hash if you are not using an explicit `gem_binary` parameter with the `gem_package` resource. This approach allows the provider to install the gem without needing to spawn an external gem process. The following RubyGems options are available for inclusion within a hash and are passed to the RubyGems DependencyInstaller: * `:env_shebang` * `:force` * `:format_executable` * `:ignore_dependencies` * `:prerelease` * `:security_policy` * `:wrappers` For more information about these options, see the RubyGems documentation: <https://docs.ruby-lang.org/en/2.2.0/Gem/DependencyInstaller.html>. **Example** ``` gem_package 'bundler' do options(prerelease: true, format_executable: false) end ``` #### Specify with String When using an explicit `gem_binary`, options must be passed as a string. When not using an explicit `gem_binary`, Chef Infra Client is forced to spawn a gems process to install the gems (which uses more system resources) when options are passed as a string. String options are passed verbatim to the gems command and should be specified just as if they were passed on a command line. For example, `--prerelease` for a pre-release gem. **Example** ``` gem_package 'nokogiri' do gem_binary('/opt/ree/bin/gem') options('--prerelease --no-format-executable') end ``` #### Specify with .gemrc File Options can be specified in a .gemrc file. By default the `gem_package` resource will use the Ruby interface to install gems which will ignore the .gemrc file. The `gem_package` resource can be forced to use the gems command instead (and to read the .gemrc file) by adding the `gem_binary` attribute to a code block. A template named `gemrc.erb` is located in a cookbook’s `/templates` directory: ``` :sources: - http://<%= node['gem_file']['host'] %>:<%= node['gem_file']['port'] %>/ ``` A recipe can be built that does the following: * Builds a `.gemrc` file based on a `gemrc.erb` template * Runs a `Gem.configuration` command * Installs a package using the `.gemrc` file ``` template '/root/.gemrc' do source 'gemrc.erb' action :create notifies :run, 'ruby_block[refresh_gemrc]', :immediately end ruby_block 'refresh_gemrc' do action :nothing block do Gem.configuration = Gem::ConfigFile.new [] end end gem_package 'di-ruby-lvm' do gem_binary '/opt/chef/embedded/bin/gem' action :install end ``` ### Actions --- The **package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. (Debian platform only; for other platforms, use the `:remove` action.) `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` **yum_package** resource only. Downgrade a package to satisfy requested version requirements. `arch` **Ruby Type:** String, Array **yum_package** resource only. The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name. `default_release` **Ruby Type:** String **apt_package** resource only. The default release. For example: `stable`. `flush_cache` **Ruby Type:** Array Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Default value: `[ :before, :after ]`. The value may also be a Hash: `( { :before => true/false, :after => true/false } )`. Yum automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while the Chef Infra Client run is in-progress. As an array: ``` yum_package 'some-package' do #... flush_cache [ :before ] #... end ``` and as a Hash: ``` yum_package 'some-package' do #... flush_cache( { :after => true } ) #... end ``` Note The `flush_cache` property does not flush the local Yum cache! Use Yum tools—`yum clean headers`, `yum clean packages`, `yum clean all`—to clean the local Yum cache. `gem_binary` **Ruby Type:** String A property for the `gem_package` provider that is used to specify a gems binary. `homebrew_user` **Ruby Type:** String, Integer **homebrew_package** resource only. The name of the Homebrew owner to be used by Chef Infra Client when executing a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `options` **Ruby Type:** String One (or more) additional options that are passed to the command. `package_name` **Ruby Type:** String, Array The name of the package. Default value: the `name` of the resource block. See “Syntax” section above for more information. `response_file` **Ruby Type:** String **apt_package** and **dpkg_package** resources only. The direct path to the file used to pre-seed a package. `response_file_variables` **Ruby Type:** Hash **apt_package** and **dpkg_package** resources only. A Hash of response file variables in the form of `{"VARIABLE" => "VALUE"}`. `source` **Ruby Type:** String Optional. The path to a package in the local file system. Note The AIX platform requires `source` to be a local file system path because `installp` does not retrieve packages using HTTP or FTP. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **package** resource in recipes: Install a gems file for use in recipes ``` chef_gem 'right_aws' do action :install end require 'right_aws' ``` Install a gems file from the local file system ``` gem_package 'right_aws' do source '/tmp/right_aws-1.11.0.gem' action :install end ``` Install a package ``` package 'tar' do action :install end ``` Install a package version ``` package 'tar' do version '1.16.1-1' action :install end ``` Install a package with options ``` package 'debian-archive-keyring' do action :install options '--force-yes' end ``` Install a package with a response_file Use of a `response_file` is only supported on Debian and Ubuntu at this time. Custom resources must be written to support the use of a `response_file`, which contains debconf answers to questions normally asked by the package manager on installation. Put the file in `/files/default` of the cookbook where the package is specified and Chef Infra Client will use the **cookbook_file** resource to retrieve it. To install a package with a `response_file`: ``` package 'sun-java6-jdk' do response_file 'java.seed' end ``` Install a specified architecture using a named provider ``` yum_package 'glibc-devel' do arch 'i386' end ``` Purge a package ``` package 'tar' do action :purge end ``` Remove a package ``` package 'tar' do action :remove end ``` Upgrade a package ``` package 'tar' do action :upgrade end ``` Use the ignore_failure common attribute ``` gem_package 'syntax' do action :install ignore_failure true end ``` Avoid unnecessary string interpolation Do this: ``` package 'mysql-server' do version node['mysql']['version'] action :install end ``` and not this: ``` package 'mysql-server' do version "#{node['mysql']['version']}" action :install end ``` Install a package in a platform The following example shows how to use the **package** resource to install an application named `app` and ensure that the correct packages are installed for the correct platform: ``` package 'app_name' do action :install end case node[:platform] when 'ubuntu','debian' package 'app_name-doc' do action :install end when 'centos' package 'app_name-html' do action :install end end ``` **Install sudo, then configure /etc/sudoers/ file** The following example shows how to install sudo and then configure the `/etc/sudoers` file: ``` # the following code sample comes from the ``default`` recipe in the ``sudo`` cookbook: https://github.com/chef-cookbooks/sudo package 'sudo' do action :install end if node['authorization']['sudo']['include_sudoers_d'] directory '/etc/sudoers.d' do mode '0755' owner 'root' group 'root' action :create end cookbook_file '/etc/sudoers.d/README' do source 'README' mode '0440' owner 'root' group 'root' action :create end end template '/etc/sudoers' do source 'sudoers.erb' mode '0440' owner 'root' group platform?('freebsd') ? 'wheel' : 'root' variables( :sudoers_groups => node['authorization']['sudo']['groups'], :sudoers_users => node['authorization']['sudo']['users'], :passwordless => node['authorization']['sudo']['passwordless'] ) end ``` where * the **package** resource is used to install sudo * the `if` statement is used to ensure availability of the `/etc/sudoers.d` directory * the **template** resource tells Chef Infra Client where to find the `sudoers` template * the `variables` property is a hash that passes values to template files (that are located in the `templates/` directory for the cookbook Use a case statement to specify the platform The following example shows how to use a case statement to tell Chef Infra Client which platforms and packages to install using cURL. ``` package 'curl' case node[:platform] when 'redhat', 'centos' package 'package_1' package 'package_2' package 'package_3' when 'ubuntu', 'debian' package 'package_a' package 'package_b' package 'package_c' end end ``` where `node[:platform]` for each node is identified by Ohai during every Chef Infra Client run. For example: ``` package 'curl' case node[:platform] when 'redhat', 'centos' package 'zlib-devel' package 'openssl-devel' package 'libc6-dev' when 'ubuntu', 'debian' package 'openssl' package 'pkg-config' package 'subversion' end end ``` Use symbols to reference attributes Symbols may be used to reference attributes: ``` package 'mysql-server' do version node[:mysql][:version] action :install end ``` instead of strings: ``` package 'mysql-server' do version node['mysql']['version'] action :install end ``` Use a whitespace array to simplify a recipe The following examples show different ways of doing the same thing. The first shows a series of packages that will be upgraded: ``` package 'package-a' do action :upgrade end package 'package-b' do action :upgrade end package 'package-c' do action :upgrade end package 'package-d' do action :upgrade end ``` and the next uses a single **package** resource and a whitespace array (`%w`): ``` package %w{package-a package-b package-c package-d} do action :upgrade end ``` Specify the Homebrew user with a UUID ``` homebrew_package 'emacs' do homebrew_user 1001 end ``` Specify the Homebrew user with a string ``` homebrew_package 'vim' do homebrew_user 'user1' end ``` pacman_package resource ------------------------ [pacman_package resource page](pacman_package/index) --- Use the **pacman_package** resource to manage packages (using pacman) on the Arch Linux platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **pacman_package** resource block manages a package on a node, typically by installing it. The simplest use of the **pacman_package** resource is: ``` pacman_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **pacman_package** resource is: ``` pacman_package 'name' do options String package_name String source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `pacman_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **pacman_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **pacman_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **pacman_package** resource in recipes: Install a package ``` pacman_package 'name of package' do action :install end ``` paludis_package resource ------------------------- [paludis_package resource page](paludis_package/index) --- Use the **paludis_package** resource to manage packages for the Paludis platform. ### Syntax --- A **paludis_package** resource block manages a package on a node, typically by installing it. The simplest use of the **paludis_package** resource is: ``` paludis_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **paludis_package** resource is: ``` paludis_package 'name' do options String package_name String source String timeout Integer # default value: 3600 version String action Symbol # defaults to :install if not specified end ``` where: * `paludis_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **paludis_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **paludis_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer | **Default Value:** `3600` The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **paludis_package** resource in recipes: Install a package ``` paludis_package 'name of package' do action :install end ``` perl resource ------------- [perl resource page](perl/index) --- Use the **perl** resource to execute scripts using the Perl interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **perl** resource block executes scripts Perl: ``` perl 'hello world' do code <<-EOH print "Hello world! From Chef and Perl."; EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **perl** resource is: ``` perl 'name' do code String creates String cwd String environment Hash flags String group String, Integer notifies # see description path Array returns Integer, Array subscribes # see description timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `perl` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **perl** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. ### Properties --- The **perl** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. plist resource -------------- [plist resource page](plist/index) --- Use the **plist** resource to set config values in plist files on macOS systems. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **plist** resource is: ``` plist 'name' do encoding String # default value: "binary" entry String group String # default value: "wheel" mode String, Integer owner String # default value: "root" path String # default value: 'name' unless specified value true, false, String, Integer, Float, Hash action Symbol # defaults to :set if not specified end ``` where: * `plist` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `encoding`, `entry`, `group`, `mode`, `owner`, `path`, and `value` are the properties available to this resource. ### Actions --- The **plist** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set a value in a plist file. (default) ### Properties --- The **plist** resource has the following properties: `encoding` **Ruby Type:** String | **Default Value:** `binary` `entry` **Ruby Type:** String `group` **Ruby Type:** String | **Default Value:** `wheel` The group of the plist file. `mode` **Ruby Type:** String, Integer The file mode of the plist file. Ex: ‘644’ `owner` **Ruby Type:** String | **Default Value:** `root` The owner of the plist file. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path on disk to the plist file. `value` **Ruby Type:** true, false, String, Integer, Float, Hash ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **plist** resource in recipes: **Show hidden files in finder**: ``` plist 'show hidden files' do path '/Users/vagrant/Library/Preferences/com.apple.finder.plist' entry 'AppleShowAllFiles' value true end ``` portage_package resource ------------------------- [portage_package resource page](portage_package/index) --- Use the **portage_package** resource to manage packages for the Gentoo platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- The full syntax for all of the properties that are available to the **portage_package** resource is: ``` portage_package 'name' do options String package_name String source String timeout String, Integer # default value: 3600 version String action Symbol # defaults to :install if not specified end ``` where: * `portage_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **portage_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **portage_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer | **Default Value:** `3600` The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **portage_package** resource in recipes: Install a package ``` portage_package 'name of package' do action :install end ``` powershell_package resource ---------------------------- [powershell_package resource page](powershell_package/index) --- Use the **powershell_package** resource to install and manage packages via the PowerShell Package Manager for the Microsoft Windows platform. The **powershell_package** resource requires administrative access, and a source must be configured in the PowerShell Package Manager via the [Register-PackageSource](https://docs.microsoft.com/en-us/powershell/module/packagemanagement/register-packagesource?view=powershell-5.1) command or the [powershell_package_source](powershell_package_source/index) resource. **New in Chef Infra Client 12.16.** ### Syntax --- A **powershell_package** resource block manages a package on a node, typically by installing it. The simplest use of the **powershell_package** resource is: ``` powershell_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The powershell_package resource has the following syntax: ``` powershell_package 'name' do options String, Array package_name String, Array skip_publisher_check true, false # default value: false source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `powershell_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `skip_publisher_check`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **powershell_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:remove` Remove a package. ### Properties --- The **powershell_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array The name of the package. Default value: the name of the resource block. `skip_publisher_check` **Ruby Type:** true, false | **Default Value:** `false` Skip validating module author. New in Chef Client 14.3 `source` **Ruby Type:** String Specify the source of the package. New in Chef Client 14.0 `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **powershell_package** resource in recipes: Install a specific version of a package: ``` powershell_package 'xCertificate' do action :install version '1.1.0.0' end ``` Install multiple packages: ``` powershell_package 'Install Multiple Packages' do action :install package_name %w(xCertificate xNetworking) end ``` Install a package from a custom source: ``` powershell_package 'xCertificate' do action :install source 'MyGallery' end ``` Install multiple packages, and specify package versions: ``` powershell_package 'Install Multiple Packages' do action :install package_name %w(xCertificate xNetworking) version ['2.0.0.0', '2.12.0.0'] end ``` Install multiple packages, specifying the package version for one package but not the other: ``` powershell_package 'Install Multiple Packages' do action :install package_name %w(xCertificate xNetworking) version [nil, '2.12.0.0'] end ``` In this example, the `nil` tells `powershell_package` to install the most up to date version of `xCertificate` that is available, while pinning `xNetworking` to version 2.12.0.0. Remove a package: ``` powershell_package 'xCertificate' do action :remove end ``` powershell_package_source resource ------------------------------------ [powershell_package_source resource page](powershell_package_source/index) --- Use the **powershell_package_source** resource to register a PowerShell package source and a Powershell package provider. There are two distinct objects we care about here. The first is a package source like a PowerShell repository or a NuGet Source. The second object is a provider that PowerShell uses to get to that source with, like PowerShellGet, NuGet, Chocolatey, etc. **New in Chef Infra Client 14.3.** ### Syntax --- The full syntax for all of the properties that are available to the **powershell_package_source** resource is: ``` powershell_package_source 'name' do new_name String password String provider_name String # default value: "NuGet" publish_location String script_publish_location String script_source_location String source_location String source_name String # default value: 'name' unless specified trusted true, false # default value: false user String action Symbol # defaults to :register if not specified end ``` where: * `powershell_package_source` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `new_name`, `password`, `provider_name`, `publish_location`, `script_publish_location`, `script_source_location`, `source_location`, `source_name`, `trusted`, and `user` are the properties available to this resource. ### Actions --- The **powershell_package_source** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:register` Registers a PowerShell package source. (default) `:set` Updates an existing PowerShell repository or package source. `:unregister` Unregisters the PowerShell package source. ### Properties --- The **powershell_package_source** resource has the following properties: `new_name` **Ruby Type:** String Used to change the name of a standard package source. New in Chef Infra Client 17.6 `password` **Ruby Type:** String A password that, as part of a credential object, is used to register a repository or other package source with. New in Chef Infra Client 17.6 `provider_name` **Ruby Type:** String | **Default Value:** `NuGet` **Allowed Values:** `"NuGet", "PowerShellGet", "Programs", "chocolatey", "msi", "msu", "psl", "winget"` The package management provider for the package source. The default is `PowerShellGet`. Only change this option in specific use cases. `publish_location` **Ruby Type:** String The URL where modules will be published to. Only valid if the provider is `PowerShellGet`. `script_publish_location` **Ruby Type:** String The location where scripts will be published to for this source. Only valid if the provider is `PowerShellGet`. `script_source_location` **Ruby Type:** String The URL where scripts are located for this source. Only valid if the provider is `PowerShellGet`. `source_location` **Ruby Type:** String The URL to the location to retrieve modules from. New in Chef Infra Client 17.6 `source_name` **Ruby Type:** String | **Default Value:** `The resource block's name` A label that names your package source. `trusted` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to trust packages from this source. Used when creating a non-PowerShell repository package source. `user` **Ruby Type:** String A username that, as part of a credential object, is used to register a repository or other package source with. New in Chef Infra Client 17.6 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **powershell_package_source** resource in recipes: **Add a new PowerShell repository that is not trusted and which requires credentials to connect to**: ``` powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted false user "<EMAIL>" password "my_password" provider_name "PSRepository" action :register end ``` **Add a new package source that uses Chocolatey as the package provider**: ``` powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted true provider_name "chocolatey" action :register end ``` **Add a new PowerShell script source that is trusted**: ``` powershell_package_source 'MyDodgyScript' do source_name "MyDodgyScript" script_source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" script_publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted true action :register end ``` **Update an existing PowerShell repository to make it trusted**: ``` powershell_package_source 'MyPSModule' do source_name "MyPSModule" trusted true action :set end ``` **Update a Nuget package source with a new name and make it trusted**: ``` powershell_package_source 'PowerShellModules -> GoldFishBowl' do source_name "PowerShellModules" new_name "GoldFishBowl" provider_name "Nuget" trusted true action :set end ``` **Update a Nuget package source with a new name when the source is secured with a username and password**: ``` powershell_package_source 'PowerShellModules -> GoldFishBowl' do source_name "PowerShellModules" new_name "GoldFishBowl" trusted true user "<EMAIL>" password "some_secret_password" action :set end ``` **Unregister a package source**: ``` powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" action :unregister end ``` powershell_script resource --------------------------- [powershell_script resource page](powershell_script/index) --- Use the **powershell_script** resource to execute a script using the Windows PowerShell interpreter, much like how the script and script-based resources **bash**, **csh**, **perl**, **python**, and **ruby** are used. The powershell_script is specific to the Microsoft Windows platform, but may use both the the Windows PowerShell interpreter or the PowerShell Core (pwsh) interpreter as of Chef Infra Client 16.6 and later. The powershell_script resource creates and executes a temporary file rather than running the command inline. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` conditionals to guard this resource for idempotence. ### Syntax --- A **powershell_script** resource block executes a batch script using the Windows PowerShell interpreter. For example, writing to an interpolated path: ``` powershell_script 'write-to-interpolated-path' do code <<-EOH $stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt" $stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.") $stream.close() EOH end ``` The full syntax for all of the properties that are available to the **powershell_script** resource is: ``` powershell_script 'name' do code String command String, Array # default value: 'name' unless specified convert_boolean_return true, false # default value: false creates String cwd String domain String elevated true, false # default value: false environment Hash flags String group String, Integer input String interpreter String # default value: "powershell" live_stream true, false # default value: false password String returns Integer, Array # default value: 0 timeout Integer, String, Float # default value: 3600 user String, Integer action Symbol # defaults to :run if not specified end ``` where: * `powershell_script` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `command`, `convert_boolean_return`, `creates`, `cwd`, `domain`, `elevated`, `environment`, `flags`, `group`, `input`, `interpreter`, `live_stream`, `password`, `returns`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **powershell_script** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run the script. ### Properties --- The **powershell_script** resource has the following properties: `architecture` **Ruby Type:** Symbol The architecture of the process under which a script is executed. If a value is not provided, Chef Infra Client defaults to the correct value for the architecture, as determined by Ohai. An exception is raised when anything other than `:i386` is specified for a 32-bit process. Possible values: `:i386` (for 32-bit processes) and `:x86_64` (for 64-bit processes). `code` **Ruby Type:** String | `REQUIRED` A quoted string of code to be executed. `command` **Ruby Type:** String, Array | **Default Value:** `The resource block's name` An optional property to set the command to be executed if it differs from the resource block’s name. `convert_boolean_return` **Ruby Type:** true, false | **Default Value:** `false` Return `0` if the last line of a command is evaluated to be true or to return `1` if the last line is evaluated to be false. When the `guard_interpreter` common attribute is set to `:powershell_script`, a string command will be evaluated as if this value were set to `true`. This is because the behavior of this attribute is similar to the value of the `"$?"` expression common in UNIX interpreters. For example, this: ``` powershell_script 'make_safe_backup' do guard_interpreter :powershell_script code 'cp ~/data/nodes.json ~/data/nodes.bak' not_if 'test-path ~/data/nodes.bak' end ``` is similar to: ``` bash 'make_safe_backup' do code 'cp ~/data/nodes.json ~/data/nodes.bak' not_if 'test -e ~/data/nodes.bak' end ``` `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `domain` **Ruby Type:** String The domain of the username specified by the user property. If not specified, the username and password specified by the `user` and `password` properties will be used to resolve that user against the domain in which the system running Chef Infra Client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. New in Chef Client 12.21 `elevated` **Ruby Type:** true, false | **Default Value:** `false` Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) from interactively blocking the process. This will cause the process to be run under a batch login instead of an interactive login. The user running chef-client needs the ‘Replace a process level token’ and ‘Adjust Memory Quotas for a process’ permissions. The user that is running the command needs the ‘Log on as a batch job’ permission. Because this requires a login, the user and password properties are required. New in Chef Client 13.3 `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String A string that is passed to the Windows PowerShell command. Default value (Windows PowerShell 3.0+): `-NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy Bypass, -InputFormat None`. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `guard_interpreter` **Ruby Type:** Symbol | **Default Value:** `:powershell_script` When this property is set to `:powershell_script`, the 64-bit version of the Windows PowerShell shell will be used to evaluate strings values for the `not_if` and `only_if` properties. Set this value to `:default` to use the 32-bit version of the cmd.exe shell. `input` **Ruby Type:** String An optional property to set the input sent to the command as STDIN. New in Chef Infra Client 16.2 `interpreter` **Ruby Type:** String | **Default Value:** `powershell` **Allowed Values:** `"powershell", "pwsh"` The interpreter type, `powershell` or `pwsh` (PowerShell Core) `live_stream` **Ruby Type:** true, false | **Default Value:** `false` Send the output of the command run by this execute resource block to the Chef Infra Client event stream. `password` **Ruby Type:** String The password of the user specified by the user property. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. New in Chef Client 12.21 `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. `domain\user` or `<EMAIL>@my.dns.domain.com` via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain property. On Windows only, if this property is specified, the password property must be specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **powershell_script** resource in recipes: Write to an interpolated path ``` powershell_script 'write-to-interpolated-path' do code <<-EOH $stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt" $stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.") $stream.close() EOH end ``` Change the working directory ``` powershell_script 'cwd-then-write' do cwd Chef::Config[:file_cache_path] code <<-EOH $stream = [System.IO.StreamWriter] "C:/powershell-test2.txt" $pwd = pwd $stream.WriteLine("This is the contents of: $pwd") $dirs = dir foreach ($dir in $dirs) { $stream.WriteLine($dir.fullname) } $stream.close() EOH end ``` Change the working directory in Microsoft Windows ``` powershell_script 'cwd-to-win-env-var' do cwd '%TEMP%' code <<-EOH $stream = [System.IO.StreamWriter] "./temp-write-from-chef.txt" $stream.WriteLine("chef on windows rox yo!") $stream.close() EOH end ``` Pass an environment variable to a script ``` powershell_script 'read-env-var' do cwd Chef::Config[:file_cache_path] environment ({'foo' => 'BAZ'}) code <<-EOH $stream = [System.IO.StreamWriter] "./test-read-env-var.txt" $stream.WriteLine("FOO is $env:foo") $stream.close() EOH end ``` **Evaluate for true and/or false** Use the `convert_boolean_return` attribute to raise an exception when certain conditions are met. For example, the following fragments will run successfully without error: ``` powershell_script 'false' do code '$false' end ``` and: ``` powershell_script 'true' do code '$true' end ``` whereas the following will raise an exception: ``` powershell_script 'false' do convert_boolean_return true code '$false' end ``` Use the flags attribute ``` powershell_script 'Install IIS' do code <<-EOH Import-Module ServerManager Add-WindowsFeature Web-Server EOH flags '-NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy Unrestricted, -InputFormat None, -File' guard_interpreter :powershell_script not_if '(Get-WindowsFeature -Name Web-Server).Installed' end ``` Rename computer, join domain, reboot The following example shows how to rename a computer, join a domain, and then reboot the computer: ``` reboot 'Restart Computer' do action :nothing end powershell_script 'Rename and Join Domain' do code <<-EOH ...your rename and domain join logic here... EOH not_if <<-EOH $ComputerSystem = gwmi win32_computersystem ($ComputerSystem.Name -like '#{node['some_attribute_that_has_the_new_name']}') -and $ComputerSystem.partofdomain) EOH notifies :reboot_now, 'reboot[Restart Computer]', :immediately end ``` where: * The **powershell_script** resource block renames a computer, and then joins a domain * The **reboot** resource restarts the computer * The `not_if` guard prevents the Windows PowerShell script from running when the settings in the `not_if` guard match the desired state * The `notifies` statement tells the **reboot** resource block to run if the **powershell_script** block was executed during a Chef Infra Client run Run a command as an alternate user *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] domain "domain" user "username" password "password" end # Passing username = 'domain-name\\username'. No domain is passed powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "domain-name\\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end # Work around User Access Control (UAC) powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" elevated true end ``` python resource --------------- [python resource page](python/index) --- Use the **python** resource to execute scripts using the Python interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- The python resource has the following syntax: ``` python 'hello world' do code <<-EOH print "Hello world! From Chef and Python." EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **python** resource is: ``` python 'name' do code String command String # default value: 'name' unless specified creates String cwd String default_env true, false # default value: false domain String elevated true, false # default value: false environment Hash flags String group String, Integer interpreter String live_stream true, false # default value: false password String returns Integer, Array # default value: 0 sensitive true, false # default value: "True if the password property is set. False otherwise." timeout Integer, Float umask String, Integer user String, Integer action Symbol # defaults to :run if not specified end ``` where: * `python` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `command`, `creates`, `cwd`, `default_env`, `domain`, `elevated`, `environment`, `flags`, `group`, `interpreter`, `live_stream`, `password`, `returns`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **python** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a script. ### Properties --- The **python** resource has the following properties: `code` **Ruby Type:** String | `REQUIRED` A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. `user` **Ruby Type:** String, Integer The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. `domain\user` or `<EMAIL>@my.dns.domain.com` via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain property. On Windows only, if this property is specified, the password property must be specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. reboot resource --------------- [reboot resource page](reboot/index) --- Use the **reboot** resource to reboot a node, a necessary step with some installations on certain platforms. This resource is supported for use on the Microsoft Windows, macOS, and Linux platforms. In using this resource via notifications, it’s important to *only* use immediate notifications. Delayed notifications produce unintuitive and probably undesired results. **New in Chef Infra Client 12.0.** ### Syntax --- The full syntax for all of the properties that are available to the **reboot** resource is: ``` reboot 'name' do delay_mins Integer # default value: 0 reason String # default value: "Reboot by Chef Infra Client" action Symbol # defaults to :nothing if not specified end ``` where: * `reboot` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `delay_mins` and `reason` are the properties available to this resource. ### Actions --- The **reboot** resource has the following actions: `:cancel` Cancel a pending reboot request. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reboot_now` Reboot a node so that the Chef Infra Client may continue the installation process. `:request_reboot` Reboot a node at the end of a Chef Infra Client run. ### Properties --- The **reboot** resource has the following properties: `delay_mins` **Ruby Type:** Integer | **Default Value:** `0` The amount of time (in minutes) to delay a reboot request. `reason` **Ruby Type:** String | **Default Value:** `Reboot by Chef Infra Client` A string that describes the reboot action. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **reboot** resource in recipes: **Reboot a node immediately** ``` reboot 'now' do action :nothing reason 'Cannot continue Chef run without a reboot.' delay_mins 2 end execute 'foo' do command '...' notifies :reboot_now, 'reboot[now]', :immediately end ``` **Reboot a node at the end of a Chef Infra Client run** ``` reboot 'app_requires_reboot' do action :request_reboot reason 'Need to reboot when the run completes successfully.' delay_mins 5 end ``` **Cancel a reboot** ``` reboot 'cancel_reboot_request' do action :cancel reason 'Cancel a previous end-of-run reboot request.' end ``` registry_key resource ---------------------- [registry_key resource page](registry_key/index) --- Use the **registry_key** resource to create and delete registry keys in Microsoft Windows. Note 64-bit versions of Microsoft Windows have a 32-bit compatibility layer in the registry that reflects and redirects certain keys (and their values) into specific locations (or logical views) of the registry hive. Chef Infra Client can access any reflected or redirected registry key. The machine architecture of the system on which Chef Infra Client is running is used as the default (non-redirected) location. Access to the SysWow64 location is redirected must be specified. Typically, this is only necessary to ensure compatibility with 32-bit applications that are running on a 64-bit operating system. For more information, see: [Registry Reflection](https://docs.microsoft.com/en-us/windows/win32/winprog64/registry-reflection). ### Syntax --- A **registry_key** resource block creates and deletes registry keys in Microsoft Windows: ``` registry_key 'HKEY_LOCAL_MACHINE\\...\\System' do values [{ name: 'NewRegistryKeyValue', type: :multi_string, data: %w(foo bar baz), }] action :create end ``` Use multiple registry key entries with key values that are based on node attributes: ``` registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\name_of_registry_key' do values [{name: 'key_name', type: :string, data: 'C:\Windows\System32\file_name.bmp'}, {name: 'key_name', type: :string, data: node['node_name']['attribute']['value']}, {name: 'key_name', type: :string, data: node['node_name']['attribute']['value']} ] action :create end ``` The registry_key resource has the following syntax: ``` registry_key 'name' do architecture Symbol # default value: :machine key String # default value: 'name' unless specified recursive true, false # default value: false values action Symbol # defaults to :create if not specified end ``` where: * `registry_key` is the resource * `name` is the name of the resource block * `values` is a hash that contains at least one registry key to be created or deleted. Each registry key in the hash is grouped by brackets in which the `name:`, `type:`, and `data:` values for that registry key are specified. * `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. Warning `:multi_string` must be an array, even if there is only a single string. * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `architecture`, `key`, `recursive` and `values` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. #### Registry Key Path Separators A Microsoft Windows registry key can be used as a string in Ruby code, such as when a registry key is used as the name of a recipe. In Ruby, when a registry key is enclosed in a double-quoted string (`" "`), the same backslash character (`\`) that is used to define the registry key path separator is also used in Ruby to define an escape character. Therefore, the registry key path separators must be escaped when they are enclosed in a double-quoted string. For example, the following registry key: ``` HKCU\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Themes ``` may be enclosed in a single-quoted string with a single backslash: ``` 'HKCU\SOFTWARE\path\to\key\Themes' ``` or may be enclosed in a double-quoted string with an extra backslash as an escape character: ``` "HKCU\\SOFTWARE\\path\\to\\key\\Themes" ``` #### Chef Infra Language Methods Six methods are present in the Chef Infra Language to help verify the registry during a Chef Infra Client run on the Microsoft Windows platform—`registry_data_exists?`, `registry_get_subkeys`, `registry_get_values`, `registry_has_subkeys?`, `registry_key_exists?`, and `registry_value_exists?`—these helpers ensure the **powershell_script** resource is idempotent. ##### registry_data_exists? Use the `registry_data_exists?` method to find out if a Microsoft Windows registry key contains the specified data of the specified type under the value. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_data_exists?` method is as follows: ``` registry_data_exists?( KEY_PATH, { name: 'NAME', type: TYPE, data: DATA }, ARCHITECTURE ) ``` where: * `KEY_PATH` is the path to the registry key value. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `{ name: 'NAME', type: TYPE, data: DATA }` is a hash that contains the expected name, type, and data of the registry key value * `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. ##### registry_get_subkeys Use the `registry_get_subkeys` method to get a list of registry key values that are present for a Microsoft Windows registry key. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_get_subkeys` method is as follows: ``` subkey_array = registry_get_subkeys(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This returns an array of registry key values. ##### registry_get_values Use the `registry_get_values` method to get the registry key values (name, type, and data) for a Microsoft Windows registry key. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_get_values` method is as follows: ``` subkey_array = registry_get_values(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This returns an array of registry key values. ##### registry_has_subkeys? Use the `registry_has_subkeys?` method to find out if a Microsoft Windows registry key has one (or more) values. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_has_subkeys?` method is as follows: ``` registry_has_subkeys?(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. ##### registry_key_exists? Use the `registry_key_exists?` method to find out if a Microsoft Windows registry key exists at the specified path. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_key_exists?` method is as follows: ``` registry_key_exists?(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. (Any registry key values that are associated with this registry key are ignored.) ##### registry_value_exists? Use the `registry_value_exists?` method to find out if a registry key value exists. Use `registry_data_exists?` to test for the type and data of a registry key value. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_dvalue_exists?` method is as follows: ``` registry_value_exists?( KEY_PATH, { name: 'NAME' }, ARCHITECTURE ) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `{ name: 'NAME' }` is a hash that contains the name of the registry key value; if either `type:` or `:value` are specified in the hash, they are ignored * `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. ### Actions --- The **registry_key** resource has the following actions: `:create` Default. Create a registry key. If a registry key already exists (but does not match), update that registry key to match. `:create_if_missing` Create a registry key if it does not exist. Also, create a registry key value if it does not exist. `:delete` Delete the specified values for a registry key. `:delete_key` Delete the specified registry key and all of its subkeys. The `:delete_key` action with the `recursive` attribute will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **registry_key** resource has the following properties: `architecture` **Ruby Type:** Symbol | **Default Value:** `:machine` **Allowed Values:** `:i386, :machine, :x86_64` The architecture of the node for which keys are to be created or deleted. Possible values: `:i386` (for nodes with a 32-bit registry), `:x86_64` (for nodes with a 64-bit registry), and `:machine` (to have Chef Infra Client determine the architecture during a Chef Infra Client run). In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the `architecture` property must be set to `:i386`. The `:x86_64` value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (`:machine`) because Chef Infra Client returns an exception if `:x86_64` is used and the machine turns out to be a 32-bit machine (whereas with `:machine`, Chef Infra Client is able to access the registry key on the 32-bit machine). `key` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to the location in which a registry key is to be created or from which a registry key is to be deleted. Default value: the `name` of the resource block. See “Syntax” section above for more information. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. `recursive` **Ruby Type:** true, false | **Default Value:** `false` When creating a key, this value specifies that the required keys for the specified path are to be created. When using the `:delete_key` action in a recipe, and if the registry key has subkeys, then set the value for this property to `true`. The `:delete_key` action with the `recursive` attribute will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client. `values` **Ruby Type:** Hash, Array An array of hashes, where each Hash contains the values that are to be set under a registry key. Each Hash must contain `name:`, `type:`, and `data:` (and must contain no other key values). `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. Warning `:multi_string` must be an array, even if there is only a single string. ### Examples --- The following examples demonstrate various approaches for using the **registry_key** resource in recipes: Create a registry key Use a double-quoted string: ``` registry_key "HKEY_LOCAL_MACHINE\\path-to-key\\Policies\\System" do values [{ name: 'EnableLUA', type: :dword, data: 0 }] action :create end ``` or a single-quoted string: ``` registry_key 'HKEY_LOCAL_MACHINE\path-to-key\Policies\System' do values [{ name: 'EnableLUA', type: :dword, data: 0 }] action :create end ``` Delete a registry key value Use a double-quoted string: ``` registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\path\\to\\key\\AU" do values [{ name: 'NoAutoRebootWithLoggedOnUsers', type: :dword, data: '' }] action :delete end ``` or a single-quoted string: ``` registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\path\to\key\AU' do values [{ name: 'NoAutoRebootWithLoggedOnUsers', type: :dword, data: '' }] action :delete end ``` Note If `data:` is not specified, you get an error: `Missing data key in RegistryKey values hash` Delete a registry key and its subkeys, recursively Use a double-quoted string: ``` registry_key "HKCU\\SOFTWARE\\Policies\\path\\to\\key\\Themes" do recursive true action :delete_key end ``` or a single-quoted string: ``` registry_key 'HKCU\SOFTWARE\Policies\path\to\key\Themes' do recursive true action :delete_key end ``` Note Be careful when using the `:delete_key` action with the `recursive` attribute. This will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client. Use re-directed keys In 64-bit versions of Microsoft Windows, `HKEY_LOCAL_MACHINE\SOFTWARE\Example` is a re-directed key. In the following examples, because `HKEY_LOCAL_MACHINE\SOFTWARE\Example` is a 32-bit key, the output will be “Found 32-bit key” if they are run on a version of Microsoft Windows that is 64-bit: ``` registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\Example" do architecture :i386 recursive true action :create end ``` or: ``` registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\Example" do architecture :x86_64 recursive true action :delete_key end ``` or: ``` ruby_block 'check 32-bit' do block do puts 'Found 32-bit key' end only_if { registry_key_exists?("HKEY_LOCAL_MACHINE\SOFTWARE\\Example", :i386) } end ``` or: ``` ruby_block 'check 64-bit' do block do puts 'Found 64-bit key' end only_if { registry_key_exists?("HKEY_LOCAL_MACHINE\\SOFTWARE\\Example", :x86_64) } end ``` Set proxy settings to be the same as those used by Chef Infra Client Use a double-quoted string: ``` proxy = URI.parse(Chef::Config[:http_proxy]) registry_key 'HKCU\Software\Microsoft\path\to\key\Internet Settings' do values [{name: 'ProxyEnable', type: :reg_dword, data: 1}, {name: 'ProxyServer', data: "#{proxy.host}:#{proxy.port}"}, {name: 'ProxyOverride', type: :reg_string, data: <local>}, ] action :create end ``` or a single-quoted string: ``` proxy = URI.parse(Chef::Config[:http_proxy]) registry_key 'HKCU\Software\Microsoft\path\to\key\Internet Settings' do values [{name: 'ProxyEnable', type: :reg_dword, data: 1}, {name: 'ProxyServer', data: "#{proxy.host}:#{proxy.port}"}, {name: 'ProxyOverride', type: :reg_string, data: <local>}, ] action :create end ``` **Set the name of a registry key to “(Default)"** Use a double-quoted string: ``` registry_key 'Set (Default) value' do key "HKLM\\Software\\Test\\Key\\Path" values [ {name: '', type: :string, data: 'test'}, ] action :create end ``` or a single-quoted string: ``` registry_key 'Set (Default) value' do key 'HKLM\Software\Test\Key\Path' values [ {name: '', type: :string, data: 'test'}, ] action :create end ``` where `name: ''` contains an empty string, which will set the name of the registry key to `(Default)`. remote_directory resource -------------------------- [remote_directory resource page](remote_directory/index) --- Use the **remote_directory** resource to incrementally transfer a directory from a cookbook to a node. The directory that is copied from the cookbook should be located under `COOKBOOK_NAME/files/default/REMOTE_DIRECTORY`. The `remote_directory` resource will obey file specificity. ### Syntax --- A **remote_directory** resource block transfers a directory from a cookbook to a node, and then assigns the permissions needed on that directory. For example: ``` remote_directory '/etc/apache2' do source 'apache2' owner 'root' group 'root' mode '0755' action :create end ``` where: * `'/etc/apache2'` specifies the directory * `source` specifies a directory in the current cookbook (use the `cookbook` property to specify a file that is in a different cookbook) * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **remote_directory** resource is: ``` remote_directory 'name' do cookbook String files_backup Integer, false # default value: 5 files_group String, Integer files_mode String, Integer # default value: 0644 on *nix systems files_owner String, Integer group String, Integer inherits true, false mode String, Integer overwrite true, false # default value: true owner String, Integer path String # default value: 'name' unless specified purge true, false recursive true, false rights Hash source String action Symbol # defaults to :create if not specified end ``` where: * `remote_directory` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `cookbook`, `files_backup`, `files_group`, `files_mode`, `files_owner`, `group`, `mode`, `overwrite`, `owner`, `path`, `purge`, `recursive`, and `source` are the properties available to this resource. ### Actions --- The **remote_directory** resource has the following actions: `:create` Default. Create a directory and/or the contents of that directory. If a directory or its contents already exist (but does not match), update that directory or its contents to match. `:create_if_missing` Create a directory and/or the contents of that directory, but only if it does not exist. `:delete` Delete a directory, including the contents of that directory. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **remote_directory** resource has the following properties: `cookbook` **Ruby Type:** String The cookbook in which a file is located (if it is not located in the current cookbook). The default value is the current cookbook. `files_backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backup copies to keep for files in the directory. `files_group` **Ruby Type:** String, Integer Configure group permissions for files. A string or ID that identifies the group owner by group name, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available). `files_mode` **Ruby Type:** String, Integer | **Default Value:** `0644 on *nix systems` The octal mode for a file. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `files_owner` **Ruby Type:** String, Integer Configure owner permissions for files. A string or ID that identifies the group owner by user name, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `group` **Ruby Type:** Integer, String Use to configure permissions for directories. A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the directory already exists, the existing mode on the directory is used. If `mode` is not specified, the directory does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'`, and then applies the umask for the system on which the directory is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `overwrite` **Ruby Type:** true, false | **Default Value:** `true` Overwrite a file when it is different. `owner` **Ruby Type:** Integer, String Use to configure permissions for directories. A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the `name` of the resource block. See “Syntax” section above for more information. `purge` **Ruby Type:** true, false | **Default Value:** `false` Purge extra files found in the target directory. `recursive` **Ruby Type:** true, false | **Default Value:** `true` Create or delete directories recursively. Chef Infra Client must be able to create the directory structure, including parent directories (if missing), as defined in `COOKBOOK_NAME/files/default/REMOTE_DIRECTORY`. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String | **Default Value:** `The base portion of the 'path' property.` The base name of the source file (and inferred from the `path` property). For example, in the default value, ‘/some/path/’ would be ‘path’. #### Recursive Directories The **remote_directory** resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the `recursive` attribute only applies `group`, `mode`, and `owner` attribute values to the remote directory itself and any inner directories the resource copies. A directory structure: ``` /foo /bar /baz ``` The following example shows a way create a file in the `/baz` directory: ``` remote_directory '/foo/bar/baz' do owner 'root' group 'root' mode '0755' action :create end ``` But with this example, the `group`, `mode`, and `owner` attribute values will only be applied to `/baz`. Which is fine, if that’s what you want. But most of the time, when the entire `/foo/bar/baz` directory structure is not there, you must be explicit about each directory. For example: ``` %w( /foo /foo/bar /foo/bar/baz ).each do |path| remote_directory path do owner 'root' group 'root' mode '0755' end end ``` This approach will create the correct hierarchy—`/foo`, then `/bar` in `/foo`, and then `/baz` in `/bar`—and also with the correct attribute values for `group`, `mode`, and `owner`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Recursive Directories The **remote_directory** resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the `recursive` attribute only applies `group`, `mode`, and `owner` attribute values to the remote directory itself and any inner directories the resource copies. A directory structure: ``` /foo /bar /baz ``` The following example shows a way create a file in the `/baz` directory: ``` remote_directory '/foo/bar/baz' do owner 'root' group 'root' mode '0755' action :create end ``` But with this example, the `group`, `mode`, and `owner` attribute values will only be applied to `/baz`. Which is fine, if that’s what you want. But most of the time, when the entire `/foo/bar/baz` directory structure is not there, you must be explicit about each directory. For example: ``` %w( /foo /foo/bar /foo/bar/baz ).each do |path| remote_directory path do owner 'root' group 'root' mode '0755' end end ``` This approach will create the correct hierarchy—`/foo`, then `/bar` in `/foo`, and then `/baz` in `/bar`—and also with the correct attribute values for `group`, `mode`, and `owner`. ##### Example This section contains a more detailed example of how Chef Infra Client manages recursive directory structures: * A cookbook named `cumbria` that is used to build a website * A subfolder in the `/files/default` directory named `/website` * A file named `index.html`, which is the root page for the website * Directories within `/website` named `/cities`, `/places`, and `/football`, which contains pages about cities, places, and football teams * A directory named `/images`, which contains images These files are placed in the `/files/default` directory in the `cumbria` cookbook, like this: ``` cumbria /files /default /website index.html /cities carisle.html kendal.html penrith.html windermere.html /football carisle_united.html /images carisle_united.png furness_abbey.png hadrians_wall.png kendal.png /places furness_abbey.html hadrians_wall.html ``` The **remote_directory** resource can be used to build a website using these files. This website is being run on an Apache web server. The resource would be similar to the following: ``` remote_directory '/var/www/html' do files_mode '0440' files_owner 'yan' mode '0770' owner 'hamilton' source 'website' end ``` When Chef Infra Client runs, the **remote_directory** resource will tell Chef Infra Client to copy the directory tree from the cookbook to the file system using the structure defined in cookbook: ``` /var /www /html index.html /cities carisle.html kendal.html penrith.html windermere.html /football carisle_united.html /images carisle_united.png furness_abbey.png hadrians_wall.png kendal.png /places furness_abbey.html hadrians_wall.html ``` Chef Infra Client will manage the permissions of the entire directory structure below `/html`, for a total of 12 files and 4 directories. For example: ``` dr-xr-xr-x 2 root root 4096 /var/www/html dr--r----- 1 yan root 4096 /var/www/html/index.html drwxrwx--- 2 hamilton root 4096 /var/www/html/cities dr--r----- 1 yan root 4096 /var/www/html/cities/carlisle.html dr--r----- 1 yan root 4096 /var/www/html/cities/kendal.html dr--r----- 1 yan root 4096 /var/www/html/cities/penrith.html dr--r----- 1 yan root 4096 /var/www/html/cities/windermere.html drwxrwx--- 2 hamilton root 4096 /var/www/html/football dr--r----- 1 yan root 4096 /var/www/html/football/carlisle_united.html drwxrwx--- 2 hamilton root 4096 /var/www/html/images dr--r----- 1 yan root 4096 /var/www/html/images/carlisle_united/png dr--r----- 1 yan root 4096 /var/www/html/images/furness_abbey/png dr--r----- 1 yan root 4096 /var/www/html/images/hadrians_wall.png dr--r----- 1 yan root 4096 /var/www/html/images/kendal.png drwxrwx--- 2 hamilton root 4096 /var/www/html/places dr--r----- 1 yan root 4096 /var/www/html/places/furness_abbey.html dr--r----- 1 yan root 4096 /var/www/html/places/hadrians_wall.html ``` #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. ### Examples --- The following examples demonstrate various approaches for using the **remote_directory** resource in recipes: Recursively transfer a directory from a remote location ``` # create up to 10 backups of the files # set the files owner different from the directory remote_directory '/tmp/remote_something' do source 'something' files_backup 10 files_owner 'root' files_group 'root' files_mode '0644' owner 'nobody' group 'nobody' mode '0755' end ``` Use with the chef_handler resource The following example shows how to use the **remote_directory** resource and the **chef_handler** resource to reboot a handler named `WindowsRebootHandler`: ``` # the following code sample comes from the # ``reboot_handler`` recipe in the ``windows`` cookbook: # https://github.com/chef-cookbooks/windows remote_directory node['chef_handler']['handler_path'] do source 'handlers' recursive true action :create end chef_handler 'WindowsRebootHandler' do source "#{node['chef_handler']['handler_path']}/windows_reboot_handler.rb" arguments node['windows']['allow_pending_reboots'] supports :report => true, :exception => false action :enable end ``` remote_file resource --------------------- [remote_file resource page](remote_file/index) --- Use the **remote_file** resource to transfer a file from a remote location using file specificity. This resource is similar to the **file** resource. Note Fetching files from the `files/` directory in a cookbook should be done with the **cookbook_file** resource. ### Syntax --- A **remote_file** resource block manages files by using files that exist remotely. For example, to write the home page for an Apache website: ``` remote_file '/var/www/customers/public_html/index.html' do source 'http://somesite.com/index.html' owner 'web_admin' group 'web_admin' mode '0755' action :create end ``` where: * `'/var/www/customers/public_html/index.html'` is path to the file to be created * `'http://somesite.com/index.html'` specifies the location of the remote file, the file is downloaded from there * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **remote_file** resource is: ``` remote_file 'name' do atomic_update true, false authentication # default value: remote backup Integer, false # default value: 5 checksum String content String, nil force_unlink true, false # default value: false ftp_active_mode true, false # default value: false group String, Integer headers Hash inherits true, false manage_symlink_source true, false mode String, Integer notifies # see description owner String, Integer path String # defaults to 'name' if not specified rights Hash source String, Array subscribes # see description use_conditional_get true, false verify String, Block remote_domain String remote_password String remote_user String show_progress true, false # default value: false use_etag true, false # default value: true use_last_modified true, false # default value: true sensitive true, false # default value: false verifications Array action Symbol # defaults to :create if not specified end ``` where: * `remote_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `atomic_update`, `authentication`, `backup`, `checksum`, `content`, `force_unlink`, `ftp_active_mode`, `group`, `headers`, `http_options`, `manage_symlink_source`, `mode`, `owner`, `path`, `remote_domain`, `remote_password`, `remote_user`, `show_progress`, `ssl_verify_mode`, `use_etag`, and `use_last_modified` are the properties available to this resource. ### Actions --- The **remote_file** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the **file** resource.) ### Properties --- The **remote_file** resource has the following properties: `atomic_update` **Ruby Type:** true, false | **Default Value:** `False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.` Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the `client.rb` file. `authentication` **Ruby Type:** Symbol | **Default Value:** `:remote` **Allowed Values:** `:local, :remote` `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `checksum` **Ruby Type:** String Optional, see `use_conditional_get`. The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, Chef Infra Client does not download it. `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `ftp_active_mode` **Ruby Type:** true, false | **Default Value:** `false` Whether Chef Infra Client uses active or passive FTP. Set to `true` to use active FTP. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `headers` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of custom headers. For example: ``` headers({ "Cookie" => "user=user_name; pass=p@ssw0rd!" }) ``` or: ``` headers({ "Referer" => "#{header}" }) ``` or: ``` headers( "Authorization"=>"Basic #{ Base64.encode64("#{username}:#{password}").gsub("\n", "") }" ) ``` `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `http_options` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of custom HTTP options. For example: `http_options({ http_retry_count: 0, http_retry_delay: 2 })` New in Chef Infra Client 17.5 `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `true`, the Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `false`, Chef Infra Client will follow the symlink and will manage the permissions and content of the symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The full path to the file, including the file name and its extension. Default value: the `name` of the resource block. See “Syntax” section above for more information. `remote_domain` **Ruby Type:** String **Windows only** The domain of the user specified by the `remote_user` property. By default the resource will authenticate against the domain of the remote system, or as a local account if the remote system is not joined to a domain. If the remote system is not part of a domain, it is necessary to authenticate as a local user on the remote system by setting the domain to `.`, for example: remote_domain ‘.’. The domain may also be specified as part of the `remote_user` property. New in Chef Client 13.4 `remote_password` **Ruby Type:** String **Windows only** The password of the user specified by the `remote_user` property. This property is required if `remote_user` is specified and may only be specified if `remote_user` is specified. The `sensitive` property for this resource will automatically be set to `true` if `remote_password` is specified. New in Chef Client 13.4 `remote_user` **Ruby Type:** String **Windows only** The name of a user with access to the remote file specified by the source property. The user name may optionally be specified with a domain, such as: `domain\user` or `user@my.dns.domain.com` via Universal Principal Name (UPN) format. The domain may also be set using the `remote_domain` property. Note that this property is ignored if source is not a UNC path. If this property is specified, the `remote_password` property is required. New in Chef Client 13.4 `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String, Array Required. The location of the source file. The location of the source file may be HTTP (`http://`), FTP (`ftp://`), SFTP (`sftp://`), local (`file:///`), or UNC (`\\host\share\file.tar.gz`). There are many ways to define the location of a source file. By using a path: ``` source 'http://couchdb.apache.org/img/sketch.png' ``` By using FTP: ``` source 'ftp://remote_host/path/to/img/sketch.png' ``` By using SFTP: ``` source 'sftp://username:password@remote_host:22/path/to/img/sketch.png' ``` By using a local path: ``` source 'file:///path/to/img/sketch.png' ``` By using a Microsoft Windows UNC: ``` source '\\\\path\\to\\img\\sketch.png' ``` By using a node attribute: ``` source node['nginx']['foo123']['url'] ``` By using attributes to define paths: ``` source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2" ``` By defining multiple paths for multiple locations: ``` source 'http://seapower/spring.png', 'http://seapower/has_sprung.png' ``` By defining those same multiple paths as an array: ``` source ['http://seapower/spring.png', 'http://seapower/has_sprung.png'] ``` When multiple paths are specified, Chef Infra Client will attempt to download the files in the order listed, stopping after the first successful download. `use_conditional_get` **Ruby Type:** true, false | **Default Value:** `true` Enable conditional HTTP requests by using a conditional `GET` (with the If-Modified-Since header) or an opaque identifier (ETag). To use If-Modified-Since headers, `use_last_modified` must also be set to `true`. To use ETag headers, `use_etag` must also be set to `true`. `show_progress` **Ruby Type:** true, false | **Default Value:** `false` Displays the progress of the file download. `ssl_verify_mode` **Ruby Type:** Symbol **Allowed Values:** `:verify_none, :verify_peer` Optional property to override SSL policy. If not specified, uses the SSL policy from `config.rb`. New in Chef Infra Client 16.2 `use_etag` **Ruby Type:** true, false | **Default Value:** `true` Enable ETag headers. Set to `false` to disable ETag headers. To use this setting, `use_conditional_get` must also be set to true. `use_last_modified` **Ruby Type:** true, false | **Default Value:** `true` Enable `If-Modified-Since` headers. Set to `false` to disable `If-Modified-Since` headers. To use this setting, `use_conditional_get` must also be set to `true`. `verify` **Ruby Type:** String, Block A block or a string that returns `true` or `false`. A string, when `true` is executed as a system command. A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block is `true`, Chef Infra Client will continue to update the file as appropriate. For example, this should return `true`: ``` remote_file '/tmp/baz' do verify { 1 == 1 } end ``` This should return `true`: ``` remote_file '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` This should return `true`: ``` remote_file '/tmp/bar' do verify { 1 == 1} end ``` And this should return `true`: ``` remote_file '/tmp/foo' do verify do |path| true end end ``` Whereas, this should return `false`: ``` remote_file '/tmp/turtle' do verify '/usr/bin/false' end ``` If a string or a block return `false`, the Chef Infra Client run will stop and an error is returned. #### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. #### Prevent Re-downloads To prevent Chef Infra Client from re-downloading files that are already present on a node, use one of the following attributes in a recipe: `use_conditional_get` (default) or `checksum`. * The `use_conditional_get` attribute is the default behavior of Chef Infra Client. If the remote file is located on a server that supports ETag and/or If-Modified-Since headers, Chef Infra Client will use a conditional `GET` to determine if the file has been updated. If the file has been updated, Chef Infra Client will re-download the file. * The `checksum` attribute will ask Chef Infra Client to compare the checksum for the local file to the one at the remote location. If they match, Chef Infra Client will not re-download the file. Using a local checksum for comparison requires that the local checksum be the correct checksum. The desired approach just depends on the desired workflow. For example, if a node requires a new file every day, using the checksum approach would require that the local checksum be updated and/or verified every day as well, in order to ensure that the local checksum was the correct one. Using a conditional `GET` in this scenario will greatly simplify the management required to ensure files are being updated accurately. #### Access a remote UNC path on Windows The `remote_file` resource on Windows supports accessing files from a remote SMB/CIFS share. The file name should be specified in the source property as a UNC path e.g. `\myserver\myshare\mydirectory\myfile.txt`. This allows access to the file at that path location even if the Chef Infra Client process identity does not have permission to access the file. Credentials for authenticating to the remote system can be specified using the `remote_user`, `remote_domain`, and `remote_password` properties when the user that Chef Infra Client is running does not have access to the remote file. See the “Properties” section for more details on these options. **Note**: This is primarily for accessing remote files when the user that Chef Infra Client is running as does not have sufficient access, and alternative credentials need to be specified. If the user already has access, the credentials do not need to be specified. In a case where the local system and remote system are in the same domain, the `remote_user` and `remote_password` properties often do not need to be specified, as the user may already have access to the remote file share. Examples: **Access a file from a different domain account:** ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_domain 'domain' remote_user 'username' remote_password 'password' end ``` OR ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_user 'domain\username' remote_password 'password' end ``` **Access a file using a local account on the remote machine:** ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_domain '.' remote_user 'username' remote_password 'password' end ``` OR ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_user '.\username' remote_password 'password' end ``` ### Examples --- The following examples demonstrate various approaches for using the **remote_file** resource in recipes: **Download a file without checking the checksum**: ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' end ``` **Download a file with a checksum to validate**: ``` remote_file '/tmp/test_file' do source 'http://www.example.com/tempfiles/test_file' mode '0755' checksum '3a7dac00b1' # A SHA256 (or portion thereof) of the file. end ``` **Download a file only if it’s not already present**: ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' checksum '3a7dac00b1' # A SHA256 (or portion thereof) of the file. action :create_if_missing end ``` **Using HTTP Basic Authentication in Headers**: ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' headers('Authorization' => "Basic #{Base64.encode64("USERNAME_VALUE:PASSWORD_VALUE").delete("\n")}") checksum '3a7dac00b1' # A SHA256 (or portion thereof) of the file. action :create_if_missing end ``` **Downloading a file to the Chef file cache dir for execution**: ``` remote_file '#{Chef::Config['file_cache_path']}/install.sh' do source 'https://example.org/install.sh' action :create_if_missing end execute '#{Chef::Config['file_cache_path']}/install.sh' ``` **Specify advanced HTTP connection options including Net::HTTP (nethttp) options:** ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' http_options({ http_retry_delay: 0, http_retry_count: 0, keepalives: false, nethttp: { continue_timeout: 5, max_retries: 5, read_timeout: 5, write_timeout: 5, ssl_timeout: 5, }, }) end ``` rhsm_errata resource --------------------- [rhsm_errata resource page](rhsm_errata/index) --- Use the **rhsm_errata** resource to install packages associated with a given Red Hat Subscription Manager Errata ID. This is helpful if packages to mitigate a single vulnerability must be installed on your hosts. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **rhsm_errata** resource is: ``` rhsm_errata 'name' do errata_id String # default value: 'name' unless specified action Symbol # defaults to :install if not specified end ``` where: * `rhsm_errata` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `errata_id` is the property available to this resource. ### Actions --- The **rhsm_errata** resource has the following actions: `:install` Install a package for a specific errata ID. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **rhsm_errata** resource has the following properties: `errata_id` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the errata ID if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **rhsm_errata** resource in recipes: **Install a package from an Errata ID** ``` rhsm_errata 'RHSA:2018-1234' ``` **Specify an Errata ID that differs from the resource name** ``` rhsm_errata 'errata-install' errata_id 'RHSA:2018-1234' end ``` rhsm_errata_level resource ---------------------------- [rhsm_errata_level resource page](rhsm_errata_level/index) --- Use the **rhsm_errata_level** resource to install all packages of a specified errata level from the Red Hat Subscription Manager. For example, you can ensure that all packages associated with errata marked at a ‘Critical’ security level are installed. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **rhsm_errata_level** resource is: ``` rhsm_errata_level 'name' do errata_level String # default value: 'name' unless specified action Symbol # defaults to :install if not specified end ``` where: * `rhsm_errata_level` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `errata_level` is the property available to this resource. ### Actions --- The **rhsm_errata_level** resource has the following actions: `:install` Install all packages of the specified errata level. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **rhsm_errata_level** resource has the following properties: `errata_level` **Ruby Type:** String | **Default Value:** `The resource block's name` **Allowed Values:** `"critical", "important", "low", "moderate"` An optional property for specifying the errata level of packages to install if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **rhsm_errata_level** resource in recipes: **Specify an errata level that differs from the resource name** ``` rhsm_errata_level 'example_install_moderate' do errata_level 'moderate' end ``` rhsm_register resource ----------------------- [rhsm_register resource page](rhsm_register/index) --- Use the **rhsm_register** resource to register a node with the Red Hat Subscription Manager or a local Red Hat Satellite server. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **rhsm_register** resource is: ``` rhsm_register 'name' do activation_key String, Array auto_attach true, false # default value: false base_url String environment String force true, false # default value: false https_for_ca_consumer true, false # default value: false install_katello_agent true, false # default value: true organization String password String release Float, String satellite_host String server_url String service_level String system_name String username String action Symbol # defaults to :register if not specified end ``` where: * `rhsm_register` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `activation_key`, `auto_attach`, `base_url`, `environment`, `force`, `https_for_ca_consumer`, `install_katello_agent`, `organization`, `password`, `release`, `satellite_host`, `server_url`, `service_level`, `system_name`, and `username` are the properties available to this resource. ### Actions --- The **rhsm_register** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:register` Register the node with RHSM. (default) `:unregister` Unregister the node from RHSM. ### Properties --- The **rhsm_register** resource has the following properties: `activation_key` **Ruby Type:** String, Array A string or array of activation keys to use when registering; you must also specify the ‘organization’ property when using this property. `auto_attach` **Ruby Type:** true, false | **Default Value:** `false` If true, RHSM will attempt to automatically attach the host to applicable subscriptions. It is generally better to use an activation key with the subscriptions pre-defined. `base_url` **Ruby Type:** String The hostname of the content delivery server to use to receive updates. Both Customer Portal Subscription Management and Subscription Asset Manager use Red Hat’s hosted content delivery services, with the URL <https://cdn.redhat.com>. Since Satellite 6 hosts its own content, the URL must be used for systems registered with Satellite 6. New in Chef Infra Client 17.8 `environment` **Ruby Type:** String The environment to use when registering; required when using the username and password properties. `force` **Ruby Type:** true, false | **Default Value:** `false` If true, the system will be registered even if it is already registered. Normally, any register operations will fail if the machine has already been registered. `https_for_ca_consumer` **Ruby Type:** true, false | **Default Value:** `false` If true, Chef Infra Client will fetch the katello-ca-consumer-latest.noarch.rpm from the satellite_host using HTTPS. New in Chef Infra Client 15.9 `install_katello_agent` **Ruby Type:** true, false | **Default Value:** `true` If true, the ‘katello-agent’ RPM will be installed. `organization` **Ruby Type:** String The organization to use when registering; required when using the ‘activation_key’ property. `password` **Ruby Type:** String The password to use when registering. This property is not applicable if using an activation key. If specified, username and environment are also required. `release` **Ruby Type:** Float, String Sets the operating system minor release to use for subscriptions for the system. Products and updates are limited to the specified minor release version. This is used only used with the `auto_attach` option. For example, `release '6.4'` will append `--release=6.4` to the register command. New in Chef Infra Client 17.8 `satellite_host` **Ruby Type:** String The FQDN of the Satellite host to register with. If this property is not specified, the host will register with Red Hat’s public RHSM service. `server_url` **Ruby Type:** String The hostname of the subscription service to use. The default is Customer Portal Subscription Management, subscription.rhn.redhat.com. If you do not use this option, the system registers with Customer Portal Subscription Management. New in Chef Infra Client 17.8 `service_level` **Ruby Type:** String Sets the service level to use for subscriptions on the registering machine. This is only used with the `auto_attach` option. New in Chef Infra Client 17.8 `system_name` **Ruby Type:** String The name of the system to register, defaults to the hostname. New in Chef Infra Client 16.5 `username` **Ruby Type:** String The username to use when registering. This property is not applicable if using an activation key. If specified, password and environment properties are also required. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **rhsm_register** resource in recipes: **Register a node with RHSM* ``` rhsm_register 'my-host' do activation_key 'ABCD1234' organization 'my_org' end ``` rhsm_repo resource ------------------- [rhsm_repo resource page](rhsm_repo/index) --- Use the **rhsm_repo** resource to enable or disable Red Hat Subscription Manager repositories that are made available via attached subscriptions. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **rhsm_repo** resource is: ``` rhsm_repo 'name' do repo_name String # default value: 'name' unless specified action Symbol # defaults to :enable if not specified end ``` where: * `rhsm_repo` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `repo_name` is the property available to this resource. ### Actions --- The **rhsm_repo** resource has the following actions: `:disable` Disable a RHSM repository. `:enable` Enable a RHSM repository. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **rhsm_repo** resource has the following properties: `repo_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the repository name if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **rhsm_repo** resource in recipes: **Enable an RHSM repository** ``` rhsm_repo 'rhel-7-server-extras-rpms' ``` **Disable an RHSM repository** ``` rhsm_repo 'rhel-7-server-extras-rpms' do action :disable end ``` rhsm_subscription resource --------------------------- [rhsm_subscription resource page](rhsm_subscription/index) --- Use the **rhsm_subscription** resource to add or remove Red Hat Subscription Manager subscriptions from your host. This can be used when a host’s activation_key does not attach all necessary subscriptions to your host. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **rhsm_subscription** resource is: ``` rhsm_subscription 'name' do pool_id String # default value: 'name' unless specified action Symbol # defaults to :attach if not specified end ``` where: * `rhsm_subscription` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `pool_id` is the property available to this resource. ### Actions --- The **rhsm_subscription** resource has the following actions: `:attach` Attach the node to a subscription pool. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove the node from a subscription pool. ### Properties --- The **rhsm_subscription** resource has the following properties: `pool_id` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the Pool ID if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. route resource -------------- [route resource page](route/index) --- Use the **route** resource to manage the system routing table in a Linux environment. ### Syntax --- A **route** resource block manages the system routing table in a Linux environment: ``` route '10.0.1.10/32' do gateway '10.0.0.20' device 'eth1' end ``` The full syntax for all of the properties that are available to the **route** resource is: ``` route 'name' do comment String device String gateway String metric Integer netmask String route_type Symbol, String # default value: :host target String # default value: 'name' unless specified action Symbol # defaults to :add if not specified end ``` where: * `route` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `comment`, `device`, `gateway`, `metric`, `netmask`, `route_type`, and `target` are the properties available to this resource. ### Actions --- The **route** resource has the following actions: `:add` Default. Add a route. `:delete` Delete a route. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **route** resource has the following properties: `comment` **Ruby Type:** String Add a comment for the route. New in Chef Client 14.0 `device` **Ruby Type:** String The network interface to which the route applies. `gateway` **Ruby Type:** String The gateway for the route. `metric` **Ruby Type:** Integer The route metric value. `netmask` **Ruby Type:** String The decimal representation of the network mask. For example: `255.255.255.0`. `route_type` **Ruby Type:** Symbol, String | **Default Value:** `:host` **Allowed Values:** `:host, :net` `target` **Ruby Type:** String | **Default Value:** `The resource block's name` The IP address of the target route. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. rpm_package resource --------------------- [rpm_package resource page](rpm_package/index) --- Use the **rpm_package** resource to manage packages using the RPM Package Manager. ### Syntax --- The full syntax for all of the properties that are available to the **rpm_package** resource is: ``` rpm_package 'name' do allow_downgrade true, false # default value: true options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `rpm_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **rpm_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **rpm_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **rpm_package** resource in recipes: Install a package ``` rpm_package 'name of package' do action :install end ``` ruby resource ------------- [ruby resource page](ruby/index) --- Use the **ruby** resource to execute scripts using the Ruby interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **ruby** resource block executes scripts using Ruby: ``` ruby 'hello world' do code <<-EOH puts "Hello world! From Chef and Ruby." EOH end ``` where: * `cwd` specifies the directory from which the command is run * `code` specifies the command to run The full syntax for all of the properties that are available to the **ruby** resource is: ``` ruby 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `ruby` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **ruby** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a script. ### Properties --- The **ruby** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. ruby_block resource -------------------- [ruby_block resource page](ruby_block/index) --- Use the **ruby_block** resource to execute Ruby code during a Chef Infra Client run. Ruby code in the `ruby_block` resource is evaluated with other resources during convergence, whereas Ruby code outside of a `ruby_block` resource is evaluated before other resources, as the recipe is compiled. ### Syntax --- A **ruby_block** resource block executes a block of arbitrary Ruby code. For example, to reload the client.rb file during a Chef Infra Client run: ``` ruby_block 'reload_client_config' do block do Chef::Config.from_file("/etc/chef/client.rb") end action :run end ``` The full syntax for all of the properties that are available to the **ruby_block** resource is: ``` ruby_block 'name' do block Block block_name String # defaults to 'name' if not specified action Symbol # defaults to :run if not specified end ``` where: * `ruby_block` is the resource. * `name` is the name given to the resource block. * `block` is the block of Ruby code to be executed. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `block` and `block_name` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **ruby_block** resource has the following actions: `:create` The same as `:run`. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a Ruby block. ### Properties --- The **ruby_block** resource has the following properties: `block` **Ruby Type:** Block A block of Ruby code. `block_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the Ruby block. Default value: the `name` of the resource block. See “Syntax” section above for more information. ### Examples --- The following examples demonstrate various approaches for using the **ruby_block** resource in recipes: **Re-read configuration data** ``` ruby_block 'reload_client_config' do block do Chef::Config.from_file('/etc/chef/client.rb') end action :run end ``` **Run a block on a particular platform** The following example shows how an if statement can be used with the `windows?` method in the Chef Infra Language to run code specific to Microsoft Windows. The code is defined using the ruby_block resource: ``` if windows? ruby_block 'copy libmysql.dll into ruby path' do block do require 'fileutils' FileUtils.cp "#{node['mysql']['client']['lib_dir']}\\libmysql.dll", node['mysql']['client']['ruby_dir'] end not_if { ::File.exist?("#{node['mysql']['client']['ruby_dir']}\\libmysql.dll") } end end ``` **Stash a file in a data bag** The following example shows how to use the ruby_block resource to stash a BitTorrent file in a data bag so that it can be distributed to nodes in the organization. ``` ruby_block 'share the torrent file' do block do f = File.open(node['bittorrent']['torrent'],'rb') #read the .torrent file and base64 encode it enc = Base64.encode64(f.read) data = { 'id'=>bittorrent_item_id(node['bittorrent']['file']), 'seed'=>node.ipaddress, 'torrent'=>enc } item = Chef::DataBagItem.new item.data_bag('bittorrent') item.raw_data = data item.save end action :nothing subscribes :create, "bittorrent_torrent[#{node['bittorrent']['torrent']}]", :immediately end ``` **Update the /etc/hosts file** The following example shows how the ruby_block resource can be used to update the /etc/hosts file: ``` ruby_block 'edit etc hosts' do block do rc = Chef::Util::FileEdit.new('/etc/hosts') rc.search_file_replace_line(/^127\.0\.0\.1 localhost$/, '127.0.0.1 #{new_fqdn} #{new_hostname} localhost') rc.write_file end end ``` **Set environment variables** The following example shows how to use variables within a Ruby block to set environment variables using rbenv. ``` node.override[:rbenv][:root] = rbenv_root node.override[:ruby_build][:bin_path] = rbenv_binary_path ruby_block 'initialize' do block do ENV['RBENV_ROOT'] = node[:rbenv][:root] ENV['PATH'] = "#{node[:rbenv][:root]}/bin:#{node[:ruby_build][:bin_path]}:#{ENV['PATH']}" end end ``` **Call methods in a gem** The following example shows how to call methods in gems not shipped in Chef Infra Client ``` chef_gem 'mongodb' ruby_block 'config_replicaset' do block do MongoDB.configure_replicaset(node, replicaset_name, rs_nodes) end action :run end ``` script resource --------------- [script resource page](script/index) --- Use the **script** resource to execute scripts using a specified interpreter, such as Bash, csh, Perl, Python, or Ruby. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. This resource is the base resource for several other resources used for scripting on specific platforms. For more information about specific resources for specific platforms, see the following topics: * [bash](bash/index) * [csh](csh/index) * [ksh](ksh/index) * [perl](perl/index) * [python](python/index) * [ruby](ruby/index) Changed in 12.19 to support windows alternate user identity in execute resources ### Syntax --- A **script** resource block typically executes scripts using a specified interpreter, such as Bash, csh, Perl, Python, or Ruby: ``` script 'extract_module' do interpreter "bash" cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` where: * `interpreter` specifies the command shell to use * `cwd` specifies the directory from which the command is run * `code` specifies the command to run It is more common to use the **script**-based resource that is specific to the command shell. Chef has shell-specific resources for Bash, csh, ksh, Perl, Python, and Ruby. The same command as above, but run using the **bash** resource: ``` bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` The full syntax for all of the properties that are available to the **script** resource is: ``` script 'name' do code String creates String cwd String environment Hash flags String group String, Integer interpreter String path Array returns Integer, Array timeout Integer, Float user String password String domain String umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `script` is the resource * `name` is the name of the resource block * `cwd` is the location from which the command is run * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `interpreter`, `path`, `returns`, `timeout`, `user`, `password`, `domain` and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **script** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. ### Properties --- The **script** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `interpreter` **Ruby Type:** String The script interpreter to use during code execution. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String The user name of the user identity with which to launch the new process. Default value: nil. The user name may optionally be specified with a domain, i.e. domainuser or [<EMAIL>](mailto:<EMAIL>) via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified. `password` **Ruby Type:** String *Windows only*: The password of the user specified by the user property. Default value: nil. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. `domain` **Ruby Type:** String *Windows only*: The domain of the user user specified by the user property. Default value: nil. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Guard Interpreter Any resource that passes a string command may also specify the interpreter that will be used to evaluate that string command. This is done by using the `guard_interpreter` property to specify a **script**-based resource. **Attributes** The `guard_interpreter` property may be set to any of the following values: `:bash` Evaluates a string command using the **bash** resource. `:batch` Evaluates a string command using the **batch** resource. Default value (within a **batch** resource block): `:batch`. `:csh` Evaluates a string command using the **csh** resource. `:default` Default. Executes the default interpreter as identified by Chef Infra Client. `:perl` Evaluates a string command using the **perl** resource. `:powershell_script` Evaluates a string command using the **powershell_script** resource. Default value (within a **powershell_script** resource block): `:powershell_script`. `:python` Evaluates a string command using the **python** resource. `:ruby` Evaluates a string command using the **ruby** resource. **Inheritance** The `guard_interpreter` property is set to `:default` by default for the **bash**, **csh**, **perl**, **python**, and **ruby** resources. When the `guard_interpreter` property is set to `:default`, `not_if` or `only_if` guard statements **do not inherit** properties that are defined by the **script**-based resource. Warning The **batch** and **powershell_script** resources inherit properties by default. The `guard_interpreter` property is set to `:batch` or `:powershell_script` automatically when using a `not_if` or `only_if` guard statement within a **batch** or **powershell_script** resource, respectively. For example, the `not_if` guard statement in the following resource example **does not inherit** the `environment` property: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` and requires adding the `environment` property to the `not_if` guard statement so that it may use the `JAVA_HOME` path as part of its evaluation: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started', :environment => 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' end ``` To inherit properties, add the `guard_interpreter` property to the resource block and set it to the appropriate value: * `:bash` for **bash** * `:csh` for **csh** * `:perl` for **perl** * `:python` for **python** * `:ruby` for **ruby** For example, using the same example as from above, but this time adding the `guard_interpreter` property and setting it to `:bash`: ``` bash 'javatooling' do guard_interpreter :bash environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` The `not_if` statement now inherits the `environment` property and will use the `JAVA_HOME` path as part of its evaluation. **Example** For example, the following code block will ensure the command is evaluated using the default interpreter as identified by Chef Infra Client: ``` resource 'name' do guard_interpreter :default # code end ``` ### Examples --- The following examples demonstrate various approaches for using the **script** resource in recipes: Use a named provider to run a script ``` bash 'install_something' do user 'root' cwd '/tmp' code <<-EOH wget http://www.example.com/tarball.tar.gz tar -zxf tarball.tar.gz cd tarball ./configure make make install EOH end ``` Run a script ``` script 'install_something' do interpreter 'bash' user 'root' cwd '/tmp' code <<-EOH wget http://www.example.com/tarball.tar.gz tar -zxf tarball.tar.gz cd tarball ./configure make make install EOH end ``` or something like: ``` bash 'openvpn-server-key' do environment('KEY_CN' => 'server') code <<-EOF openssl req -batch -days #{node['openvpn']['key']['expire']} \ -nodes -new -newkey rsa:#{key_size} -keyout #{key_dir}/server.key \ -out #{key_dir}/server.csr -extensions server \ -config #{key_dir}/openssl.cnf EOF not_if { File.exist?('#{key_dir}/server.crt') } end ``` where `code` contains the OpenSSL command to be run. The `not_if` property tells Chef Infra Client not to run the command if the file already exists. Install a file from a remote location using bash The following is an example of how to install the `foo123` module for Nginx. This module adds shell-style functionality to an Nginx configuration file and does the following: * Declares three variables * Gets the Nginx file from a remote location * Installs the file using Bash to the path specified by the `src_filepath` variable ``` # the following code sample is similar to the ``upload_progress_module`` # recipe in the ``nginx`` cookbook: # https://github.com/chef-cookbooks/nginx src_filename = "foo123-nginx-module-v#{ node['nginx']['foo123']['version'] }.tar.gz" src_filepath = "#{Chef::Config['file_cache_path']}/#{src_filename}" extract_path = "#{ Chef::Config['file_cache_path'] }/nginx_foo123_module/#{ node['nginx']['foo123']['checksum'] }" remote_file 'src_filepath' do source node['nginx']['foo123']['url'] checksum node['nginx']['foo123']['checksum'] owner 'root' group 'root' mode '0755' end bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` Install an application from git using bash The following example shows how Bash can be used to install a plug-in for rbenv named `ruby-build`, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which `ruby-build` is located, and then runs a command. ``` git "#{Chef::Config[:file_cache_path]}/ruby-build" do repository 'git://github.com/sstephenson/ruby-build.git' revision 'master' action :sync end bash 'install_ruby_build' do cwd "#{Chef::Config[:file_cache_path]}/ruby-build" user 'rbenv' group 'rbenv' code <<-EOH ./install.sh EOH environment 'PREFIX' => '/usr/local' end ``` To read more about `ruby-build`, see here: <https://github.com/sstephenson/ruby-build>. Store certain settings The following recipe shows how an attributes file can be used to store certain settings. An attributes file is located in the `attributes/` directory in the same cookbook as the recipe which calls the attributes file. In this example, the attributes file specifies certain settings for Python that are then used across all nodes against which this recipe will run. Python packages have versions, installation directories, URLs, and checksum files. An attributes file that exists to support this type of recipe would include settings like the following: ``` default['python']['version'] = '2.7.1' if python['install_method'] == 'package' default['python']['prefix_dir'] = '/usr' else default['python']['prefix_dir'] = '/usr/local' end default['python']['url'] = 'http://www.python.org/ftp/python' default['python']['checksum'] = '80e387...85fd61' ``` and then the methods in the recipe may refer to these values. A recipe that is used to install Python will need to do the following: * Identify each package to be installed (implied in this example, not shown) * Define variables for the package `version` and the `install_path` * Get the package from a remote location, but only if the package does not already exist on the target system * Use the **bash** resource to install the package on the node, but only when the package is not already installed ``` # the following code sample comes from the ``oc-nginx`` cookbook on |github|: https://github.com/cookbooks/oc-nginx version = node['python']['version'] install_path = "#{node['python']['prefix_dir']}/lib/python#{version.split(/(^\d+\.\d+)/)[1]}" remote_file "#{Chef::Config[:file_cache_path]}/Python-#{version}.tar.bz2" do source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2" checksum node['python']['checksum'] mode '0755' not_if { ::File.exist?(install_path) } end bash 'build-and-install-python' do cwd Chef::Config[:file_cache_path] code <<-EOF tar -jxvf Python-#{version}.tar.bz2 (cd Python-#{version} && ./configure #{configure_options}) (cd Python-#{version} && make && make install) EOF not_if { ::File.exist?(install_path) } end ``` Run a command as an alternate user *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] domain "domain-name" user "username" password "password" end # Passing username = 'domain-name\\username'. No domain is passed script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "domain-name\\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end ``` service resource ---------------- [service resource page](service/index) --- Use the **service** resource to manage a service. ### Syntax --- The full syntax for all of the properties that are available to the **service** resource is: ``` service 'name' do init_command String options Array, String parameters Hash pattern String priority Integer, String, Hash reload_command String, false restart_command String, false run_levels Array service_name String # default value: 'name' unless specified start_command String, false status_command String, false stop_command String, false supports Hash # default value: {"restart"=>nil, "reload"=>nil, "status"=>nil} timeout Integer # default value: 900 user String action Symbol # defaults to :nothing if not specified end ``` where: * `service` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `init_command`, `options`, `parameters`, `pattern`, `priority`, `reload_command`, `restart_command`, `run_levels`, `service_name`, `start_command`, `status_command`, `stop_command`, `supports`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **service** resource has the following actions: `:disable` Disable a service. This action is equivalent to a `Disabled` startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot. `:enable` Enable a service at boot. This action is equivalent to an `Automatic` startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reload` Reload the configuration for this service. `:restart` Restart a service. `:start` Start a service, and keep it running until stopped or disabled. `:stop` Stop a service. ### Properties --- The **service** resource has the following properties: `init_command` **Ruby Type:** String The path to the init script that is associated with the service. Use `init_command` to prevent the need to specify overrides for the `start_command`, `stop_command`, and `restart_command` properties. When this property is not specified, Chef Infra Client will use the default init command for the service provider being used. `options` **Ruby Type:** Array, String Solaris platform only. Options to pass to the service command. See the `svcadm` manual for details of possible options. `parameters` **Ruby Type:** Hash Upstart only: A hash of parameters to pass to the service command for use in the service definition. `pattern` **Ruby Type:** String | **Default Value:** `The value provided to 'service_name' or the resource block's name` The pattern to look for in the process table. `priority` **Ruby Type:** Integer, String, Hash Debian platform only. The relative priority of the program for start and shutdown ordering. May be an integer or a Hash. An integer is used to define the start run levels; stop run levels are then 100-integer. A Hash is used to define values for specific run levels. For example, `{ 2 => [:start, 20], 3 => [:stop, 55] }` will set a priority of twenty for run level two and a priority of fifty-five for run level three. `reload_command` **Ruby Type:** String, false The command used to tell a service to reload its configuration. `restart_command` **Ruby Type:** String, false The command used to restart a service. `run_levels` **Ruby Type:** Array RHEL platforms only: Specific run_levels the service will run under. `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the service name if it differs from the resource block’s name. `start_command` **Ruby Type:** String, false The command used to start a service. `status_command` **Ruby Type:** String, false The command used to check the run status for a service. `stop_command` **Ruby Type:** String, false The command used to stop a service. `supports` **Ruby Type:** Hash | **Default Value:** `{"restart" => nil, "reload" => nil, "status" => nil}` A list of properties that controls how Chef Infra Client is to attempt to manage a service: `:restart`, `:reload`, `:status`. For `:restart`, the init script or other service provider can use a restart command; if `:restart` is not specified, Chef Infra Client attempts to stop and then start a service. For `:reload`, the init script or other service provider can use a reload command. For `:status`, the init script or other service provider can use a status command to determine if the service is running; if `:status` is not specified, Chef Infra Client attempts to match the `service_name` against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: `{ restart: false, reload: false, status: false }` for all platforms (except for the Red Hat platform family, which defaults to `{ restart: false, reload: false, status: true }`.) `timeout` **Ruby Type:** Integer | **Default Value:** `900` The amount of time (in seconds) to wait before timing out. `user` **Ruby Type:** String systemd only: A username to run the service under. New in Chef Client 12.21 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **service** resource in recipes: Start a service ``` service 'example_service' do action :start end ``` Start a service, enable it ``` service 'example_service' do supports status: true, restart: true, reload: true action [ :enable, :start ] end ``` Use a pattern ``` service 'samba' do pattern 'smbd' action [:enable, :start] end ``` Use the :nothing common action ``` service 'memcached' do action :nothing end ``` Use the retries common attribute ``` service 'apache' do action [ :enable, :start ] retries 3 end ``` Manage a service, depending on the node platform ``` service 'example_service' do if redhat? service_name 'redhat_name' else service_name 'other_name' end supports restart: true action [ :enable, :start ] end ``` Reload a service using a template To reload a service that is based on a template, use the **template** and **service** resources together in the same recipe, similar to the following: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' end service 'apache' do action :enable subscribes :reload, 'template[/tmp/somefile]', :immediately end ``` where the `subscribes` notification is used to reload the service whenever the template is modified. Enable a service after a restart or reload ``` service 'apache' do supports restart: true, reload: true action :enable end ``` Set an IP address using variables and a template The following example shows how the **template** resource can be used in a recipe to combine settings stored in an attributes file, variables within a recipe, and a template to set the IP addresses that are used by the Nginx service. The attributes file contains the following: ``` default['nginx']['dir'] = '/etc/nginx' ``` The recipe then does the following to: * Declare two variables at the beginning of the recipe, one for the remote IP address and the other for the authorized IP address * Use the **service** resource to restart and reload the Nginx service * Load a template named `authorized_ip.erb` from the `/templates` directory that is used to set the IP address values based on the variables specified in the recipe ``` node.default['nginx']['remote_ip_var'] = 'remote_addr' node.default['nginx']['authorized_ips'] = ['127.0.0.1/32'] service 'nginx' do supports :status => true, :restart => true, :reload => true end template 'authorized_ip' do path "#{node['nginx']['dir']}/authorized_ip" source 'modules/authorized_ip.erb' owner 'root' group 'root' mode '0755' variables( :remote_ip_var => node['nginx']['remote_ip_var'], :authorized_ips => node['nginx']['authorized_ips'] ) notifies :reload, 'service[nginx]', :immediately end ``` where the `variables` property tells the template to use the variables set at the beginning of the recipe and the `source` property is used to call a template file located in the cookbook’s `/templates` directory. The template file looks similar to: ``` geo $<%= @remote_ip_var %> $authorized_ip { default no; <% @authorized_ips.each do |ip| %> <%= "#{ip} yes;" %> <% end %> } ``` Use a cron timer to manage a service The following example shows how to install the crond application using two resources and a variable: ``` # the following code sample comes from the ``cron`` cookbook: # https://github.com/chef-cookbooks/cron cron_package = case node['platform'] when 'redhat', 'centos', 'scientific', 'fedora', 'amazon' node['platform_version'].to_f >= 6.0 ? 'cronie' : 'vixie-cron' else 'cron' end package cron_package do action :install end service 'crond' do case node['platform'] when 'redhat', 'centos', 'scientific', 'fedora', 'amazon' service_name 'crond' when 'debian', 'ubuntu', 'suse' service_name 'cron' end action [:start, :enable] end ``` where * `cron_package` is a variable that is used to identify which platforms apply to which install packages * the **package** resource uses the `cron_package` variable to determine how to install the crond application on various nodes (with various platforms) * the **service** resource enables the crond application on nodes that have Red Hat, CentOS, Red Hat Enterprise Linux, Fedora, or Amazon Web Services (AWS), and the cron service on nodes that run Debian, Ubuntu, or openSUSE Restart a service, and then notify a different service The following example shows how start a service named `example_service` and immediately notify the Nginx service to restart. ``` service 'example_service' do action :start notifies :restart, 'service[nginx]', :immediately end ``` Restart one service before restarting another This example uses the `:before` notification to restart the `php-fpm` service before restarting `nginx`: ``` service 'nginx' do action :restart notifies :restart, 'service[php-fpm]', :before end ``` With the `:before` notification, the action specified for the `nginx` resource will not run until action has been taken on the notified resource (`php-fpm`). Stop a service, do stuff, and then restart it The following example shows how to use the **execute**, **service**, and **mount** resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following: * Checks to see if the Amazon EC2 node has MySQL * If the node has MySQL, stops MySQL * Installs MySQL * Mounts the node * Restarts MySQL ``` # the following code sample comes from the ``server_ec2`` # recipe in the following cookbook: # https://github.com/chef-cookbooks/mysql if (node.attribute?('ec2') && ! FileTest.directory?(node['mysql']['ec2_path'])) service 'mysql' do action :stop end execute 'install-mysql' do command "mv #{node['mysql']['data_dir']}#{node['mysql']['ec2_path']}" not_if do FileTest.directory?(node['mysql']['ec2_path']) end end [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir| directory dir do owner 'mysql' group 'mysql' end end mount node['mysql']['data_dir'] do device node['mysql']['ec2_path'] fstype 'none' options 'bind,rw' action [:mount, :enable] end service 'mysql' do action :start end end ``` where * the two **service** resources are used to stop, and then restart the MySQL service * the **execute** resource is used to install MySQL * the **mount** resource is used to mount the node and enable MySQL Control a service using the execute resource Warning This is an example of something that should NOT be done. Use the **service** resource to control a service, not the **execute** resource. Do something like this: ``` service 'tomcat' do action :start end ``` and NOT something like this: ``` execute 'start-tomcat' do command '/etc/init.d/tomcat6 start' action :run end ``` There is no reason to use the **execute** resource to control a service because the **service** resource exposes the `start_command` property directly, which gives a recipe full control over the command issued in a much cleaner, more direct manner. Enable a service on AIX using the mkitab command The **service** resource does not support using the `:enable` and `:disable` actions with resources that are managed using System Resource Controller (SRC). This is because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot. One approach for enabling or disabling services that are managed by System Resource Controller (SRC) is to use the **execute** resource to invoke `mkitab`, and then use that command to enable or disable the service. The following example shows how to install a service: ``` execute "install #{node['chef_client']['svc_name']} in SRC" do command "mkssys -s #{node['chef_client']['svc_name']} -p #{node['chef_client']['bin']} -u root -S -n 15 -f 9 -o #{node['chef_client']['log_dir']}/client.log -e #{node['chef_client']['log_dir']}/client.log -a ' -i #{node['chef_client']['interval']} -s #{node['chef_client']['splay']}'" not_if "lssrc -s #{node['chef_client']['svc_name']}" action :run end ``` and then enable it using the `mkitab` command: ``` execute "enable #{node['chef_client']['svc_name']}" do command "mkitab '#{node['chef_client']['svc_name']}:2:once:/usr/bin/startsrc -s #{node['chef_client']['svc_name']} > /dev/console 2>&1'" not_if "lsitab #{node['chef_client']['svc_name']}" end ``` smartos_package resource ------------------------- [smartos_package resource page](smartos_package/index) --- Use the **smartos_package** resource to manage packages for the SmartOS platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- The full syntax for all of the properties that are available to the **smartos_package** resource is: ``` smartos_package 'name' do options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `smartos_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **smartos_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **smartos_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. snap_package resource ---------------------- [snap_package resource page](snap_package/index) --- Use the **snap_package** resource to manage snap packages on Debian and Ubuntu platforms. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **snap_package** resource is: ``` snap_package 'name' do channel String # default value: "stable" options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `snap_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `channel`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **snap_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:lock` Locks the apt package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:unlock` Unlocks the apt package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **snap_package** resource has the following properties: `channel` **Ruby Type:** String | **Default Value:** `stable` **Allowed Values:** `"beta", "candidate", "edge", "stable"` The default channel. For example: stable. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- This resource does not have any examples. solaris_package resource ------------------------- [solaris_package resource page](solaris_package/index) --- Use the **solaris_package** resource to manage packages on the Solaris platform. ### Syntax --- The full syntax for all of the properties that are available to the **solaris_package** resource is: ``` solaris_package 'name' do options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `solaris_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **solaris_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. ### Properties --- The **solaris_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **solaris_package** resource in recipes: Install a package ``` solaris_package 'name of package' do source '/packages_directory' action :install end ``` ssh_known_hosts_entry resource --------------------------------- [ssh_known_hosts_entry resource page](ssh_known_hosts_entry/index) --- Use the **ssh_known_hosts_entry** resource to add an entry for the specified host in /etc/ssh/ssh_known_hosts or a user’s known hosts file if specified. **New in Chef Infra Client 14.3.** ### Syntax --- The full syntax for all of the properties that are available to the **ssh_known_hosts_entry** resource is: ``` ssh_known_hosts_entry 'name' do file_location String # default value: "/etc/ssh/ssh_known_hosts" group String, Integer # default value: The root user's group depending on platform. hash_entries true, false # default value: false host String # default value: 'name' unless specified key String key_type String # default value: "rsa" mode String # default value: "0644" owner String, Integer # default value: "root" port Integer # default value: 22 timeout Integer # default value: 30 action Symbol # defaults to :create if not specified end ``` where: * `ssh_known_hosts_entry` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `file_location`, `group`, `hash_entries`, `host`, `key`, `key_type`, `mode`, `owner`, `port`, and `timeout` are the properties available to this resource. ### Actions --- The **ssh_known_hosts_entry** resource has the following actions: `:create` Create an entry in the ssh_known_hosts file. (default) `:flush` Immediately flush the entries to the config file. Without this the actual writing of the file is delayed in the Chef Infra Client run so all entries can be accumulated before writing the file out. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **ssh_known_hosts_entry** resource has the following properties: `file_location` **Ruby Type:** String | **Default Value:** `/etc/ssh/ssh_known_hosts` The location of the ssh known hosts file. Change this to set a known host file for a particular user. `group` **Ruby Type:** String, Integer | **Default Value:** `The root user's group depending on platform.` The file group for the ssh_known_hosts file. `hash_entries` **Ruby Type:** true, false | **Default Value:** `false` Hash the hostname and addresses in the ssh_known_hosts file for privacy. `host` **Ruby Type:** String | **Default Value:** `The resource block's name` The host to add to the known hosts file. `key` **Ruby Type:** String An optional key for the host. If not provided this will be automatically determined. `key_type` **Ruby Type:** String | **Default Value:** `rsa` The type of key to store. `mode` **Ruby Type:** String | **Default Value:** `0644` The file mode for the ssh_known_hosts file. `owner` **Ruby Type:** String, Integer | **Default Value:** `root` The file owner for the ssh_known_hosts file. `port` **Ruby Type:** Integer | **Default Value:** `22` The server port that the ssh-keyscan command will use to gather the public key. `timeout` **Ruby Type:** Integer | **Default Value:** `30` The timeout in seconds for ssh-keyscan. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **ssh_known_hosts_entry** resource in recipes: **Add a single entry for github.com with the key auto detected** ``` ssh_known_hosts_entry 'github.com' ``` **Add a single entry with your own provided key** ``` ssh_known_hosts_entry 'github.com' do key 'node.example.com ssh-rsa ...' end ``` subversion resource ------------------- [subversion resource page](subversion/index) --- Use the **subversion** resource to manage source control resources that exist in a Subversion repository. Warning The subversion resource has known bugs and may not work as expected. For more information see Chef GitHub issues, particularly [#4050](https://github.com/chef/chef/issues/4050) and [#4257](https://github.com/chef/chef/issues/4257). ### Syntax --- The full syntax for all of the properties that are available to the **subversion** resource is: ``` subversion 'name' do destination String # default value: 'name' unless specified environment Hash group String, Integer repository String revision String # default value: "HEAD" svn_arguments String, false # default value: "--no-auth-cache" svn_binary String svn_info_args String, false # default value: "--no-auth-cache" svn_password String svn_username String timeout Integer user String, Integer action Symbol # defaults to :sync if not specified end ``` where: * `subversion` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `destination`, `environment`, `group`, `repository`, `revision`, `svn_arguments`, `svn_binary`, `svn_info_args`, `svn_password`, `svn_username`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **subversion** resource has the following actions: `:checkout` Clone or check out the source. When a checkout is available, this provider does nothing. `:export` Export the source, excluding or removing any version control artifacts. `:force_export` Export the source, excluding or removing any version control artifacts and force an export of the source that is overwriting the existing copy (if it exists). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:sync` Update the source to the specified version, or get a new clone or checkout. This action causes a hard reset of the index and working tree, discarding any uncommitted changes. (default) ### Properties --- The **subversion** resource has the following properties: `destination` **Ruby Type:** String | **Default Value:** `The resource block's name` The location path to which the source is to be cloned, checked out, or exported. Default value: the name of the resource block. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of ({‘ENV_VARIABLE’ => ‘VALUE’}). `group` **Ruby Type:** String, Integer The system group that will own the checked-out code. `repository` **Ruby Type:** String The URI of the code repository. `revision` **Ruby Type:** String | **Default Value:** `HEAD` A branch, tag, or commit to be synchronized with git. This can be symbolic, like `HEAD` or it can be a source control management-specific revision identifier. `svn_arguments` **Ruby Type:** String, false | **Default Value:** `--no-auth-cache` The extra arguments that are passed to the Subversion command. `svn_binary` **Ruby Type:** String The location of the svn binary. `svn_info_args` **Ruby Type:** String, false | **Default Value:** `--no-auth-cache` Use when the `svn info` command is used by Chef Infra Client and arguments need to be passed. The `svn_arguments` command does not work when the `svn info` command is used. `svn_password` **Ruby Type:** String The password for a user that has access to the Subversion repository. `svn_username` **Ruby Type:** String The user name for a user that has access to the Subversion repository. `timeout` **Ruby Type:** Integer The amount of time (in seconds) to wait before timing out. `user` **Ruby Type:** String, Integer | **Default Value:** ``HOME` environment variable of the user running chef-client` The system user that will own the checked-out code. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **subversion** resource in recipes: **Get the latest version of an application** ``` subversion 'CouchDB Edge' do repository 'http://svn.apache.org/repos/asf/couchdb/trunk' revision 'HEAD' destination '/opt/my_sources/couch' action :sync end ``` sudo resource ------------- [sudo resource page](sudo/index) --- Use the **sudo** resource to add or remove individual sudo entries using sudoers.d files. Sudo version 1.7.2 or newer is required to use the sudo resource, as it relies on the `#includedir` directive introduced in version 1.7.2. This resource does not enforce installation of the required sudo version. Chef-supported releases of Ubuntu, SuSE, Debian, and RHEL (6+) all support this feature. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **sudo** resource is: ``` sudo 'name' do command_aliases Array # default value: [] commands Array # default value: ["ALL"] config_prefix String # default value: "Prefix values based on the node's platform" defaults Array # default value: [] env_keep_add Array # default value: [] env_keep_subtract Array # default value: [] filename String # default value: 'name' unless specified groups String, Array # default value: [] host String # default value: "ALL" noexec true, false # default value: false nopasswd true, false # default value: false runas String # default value: "ALL" setenv true, false # default value: false template String users String, Array # default value: [] variables Hash visudo_binary String # default value: "/usr/sbin/visudo" action Symbol # defaults to :create if not specified end ``` where: * `sudo` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command_aliases`, `commands`, `config_prefix`, `defaults`, `env_keep_add`, `env_keep_subtract`, `filename`, `groups`, `host`, `noexec`, `nopasswd`, `runas`, `setenv`, `template`, `users`, `variables`, and `visudo_binary` are the properties available to this resource. ### Actions --- The **sudo** resource has the following actions: `:create` Create a single sudoers configuration file in the `sudoers.d` directory. (default) `:delete` Remove a sudoers configuration file from the `sudoers.d` directory. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **sudo** resource has the following properties: `command_aliases` **Ruby Type:** Array | **Default Value:** `[]` Command aliases that can be used as allowed commands later in the configuration. `commands` **Ruby Type:** Array | **Default Value:** `["ALL"]` An array of full paths to commands this sudoer can execute. `config_prefix` **Ruby Type:** String | **Default Value:** `Prefix values based on the node's platform` The directory that contains the sudoers configuration file. `defaults` **Ruby Type:** Array | **Default Value:** `[]` An array of defaults for the user/group. `env_keep_add` **Ruby Type:** Array | **Default Value:** `[]` An array of strings to add to `env_keep`. `env_keep_subtract` **Ruby Type:** Array | **Default Value:** `[]` An array of strings to remove from `env_keep`. `filename` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the sudoers.d file if it differs from the name of the resource block `groups` **Ruby Type:** String, Array | **Default Value:** `[]` Group(s) to provide sudo privileges to. This property accepts either an array or a comma separated list. Leading % on group names is optional. `host` **Ruby Type:** String | **Default Value:** `ALL` The host to set in the sudo configuration. `noexec` **Ruby Type:** true, false | **Default Value:** `false` Prevent commands from shelling out. `nopasswd` **Ruby Type:** true, false | **Default Value:** `false` Allow sudo to be run without specifying a password. `runas` **Ruby Type:** String | **Default Value:** `ALL` User that the command(s) can be run as. `setenv` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not to permit preservation of the environment with `sudo -E`. `template` **Ruby Type:** String The name of the erb template in your cookbook, if you wish to supply your own template. `users` **Ruby Type:** String, Array | **Default Value:** `[]` User(s) to provide sudo privileges to. This property accepts either an array or a comma separated list. `variables` **Ruby Type:** Hash The variables to pass to the custom template. This property is ignored if not using a custom template. `visudo_binary` **Ruby Type:** String | **Default Value:** `/usr/sbin/visudo` The path to visudo for configuration verification. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **sudo** resource in recipes: **Grant a user sudo privileges for any command** ``` sudo 'admin' do user 'admin' end ``` **Grant a user and groups sudo privileges for any command** ``` sudo 'admins' do users 'bob' groups 'sysadmins, superusers' end ``` **Grant passwordless sudo privileges for specific commands** ``` sudo 'passwordless-access' do commands ['/bin/systemctl restart httpd', '/bin/systemctl restart mysql'] nopasswd true end ``` swap_file resource ------------------- [swap_file resource page](swap_file/index) --- Use the **swap_file** resource to create or delete swap files on Linux systems, and optionally to manage the swappiness configuration for a host. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **swap_file** resource is: ``` swap_file 'name' do path String # default value: 'name' unless specified persist true, false # default value: false size Integer swappiness Integer timeout Integer # default value: 600 action Symbol # defaults to :create if not specified end ``` where: * `swap_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `path`, `persist`, `size`, `swappiness`, and `timeout` are the properties available to this resource. ### Actions --- The **swap_file** resource has the following actions: `:create` Create a swapfile. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a swapfile and disable swap. ### Properties --- The **swap_file** resource has the following properties: `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path where the swap file will be created on the system if it differs from the resource block’s name. `persist` **Ruby Type:** true, false | **Default Value:** `false` Persist the swapon. `size` **Ruby Type:** Integer The size (in MBs) of the swap file. `swappiness` **Ruby Type:** Integer The swappiness value to set on the system. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Timeout for `dd` / `fallocate` commands. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **swap_file** resource in recipes: **Create a swap file** ``` swap_file '/dev/sda1' do size 1024 end ``` **Remove a swap file** ``` swap_file '/dev/sda1' do action :remove end ``` sysctl resource --------------- [sysctl resource page](sysctl/index) --- Use the **sysctl** resource to set or remove kernel parameters using the `sysctl` command line tool and configuration files in the system’s `sysctl.d` directory. Configuration files managed by this resource are named `99-chef-KEYNAME.conf`. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **sysctl** resource is: ``` sysctl 'name' do comment Array, String # default value: [] conf_dir String # default value: "/etc/sysctl.d" ignore_error true, false # default value: false key String # default value: 'name' unless specified value Array, String, Integer, Float action Symbol # defaults to :apply if not specified end ``` where: * `sysctl` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `comment`, `conf_dir`, `ignore_error`, `key`, and `value` are the properties available to this resource. ### Actions --- The **sysctl** resource has the following actions: `:apply` Set the kernel parameter and update the `sysctl` settings. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove the kernel parameter and update the `sysctl` settings. ### Properties --- The **sysctl** resource has the following properties: `comment` **Ruby Type:** Array, String | **Default Value:** `[]` Comments, placed above the resource setting in the generated file. For multi-line comments, use an array of strings, one per line. New in Chef Infra Client 15.8 `conf_dir` **Ruby Type:** String | **Default Value:** `/etc/sysctl.d` The configuration directory to write the config to. `ignore_error` **Ruby Type:** true, false | **Default Value:** `false` Ignore any errors when setting the value on the command line. `key` **Ruby Type:** String | **Default Value:** `The resource block's name` The kernel parameter key in dotted format if it differs from the resource block’s name. `value` **Ruby Type:** Array, String, Integer, Float | `REQUIRED` The value to set. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **sysctl** resource in recipes: **Set vm.swappiness**: ``` sysctl 'vm.swappiness' do value 19 end ``` **Remove kernel.msgmax**: **Note**: This only removes the sysctl.d config for kernel.msgmax. The value will be set back to the kernel default value. ``` sysctl 'kernel.msgmax' do action :remove end ``` **Adding Comments to sysctl configuration files**: ``` sysctl 'vm.swappiness' do value 19 comment "define how aggressively the kernel will swap memory pages." end ``` This produces /etc/sysctl.d/99-chef-vm.swappiness.conf as follows: ``` # define how aggressively the kernel will swap memory pages. vm.swappiness = 1 ``` **Converting sysctl settings from shell scripts**: Example of existing settings: ``` fs.aio-max-nr = 1048576 net.ipv4.ip_local_port_range = 9000 65500 kernel.sem = 250 32000 100 128 ``` Converted to sysctl resources: ``` sysctl 'fs.aio-max-nr' do value '1048576' end sysctl 'net.ipv4.ip_local_port_range' do value '9000 65500' end sysctl 'kernel.sem' do value '250 32000 100 128' end ``` systemd_unit resource ---------------------- [systemd_unit resource page](systemd_unit/index) --- Use the **systemd_unit** resource to create, manage, and run [systemd units](https://www.freedesktop.org/software/systemd/man/systemd.html#Concepts). **New in Chef Infra Client 12.11.** ### Syntax --- The full syntax for all of the properties that are available to the **systemd_unit** resource is: ``` systemd_unit 'name' do content String, Hash triggers_reload true, false # default value: true unit_name String # default value: 'name' unless specified user String verify true, false # default value: true action Symbol # defaults to :nothing if not specified end ``` where: * `systemd_unit` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `content`, `triggers_reload`, `unit_name`, `user`, and `verify` are the properties available to this resource. ### Actions --- The **systemd_unit** resource has the following actions: `:create` Create a systemd unit file, if it does not already exist. `:delete` Delete a systemd unit file, if it exists. `:disable` Ensure the unit will not be started after the next system boot. `:enable` Ensure the unit will be started after the next system boot. `:mask` Ensure the unit will not start, even to satisfy dependencies. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:preset` Restore the preset ‘`enable`/`disable`’ configuration for a systemd unit. *New in Chef Infra Client 14.0.* `:reenable` Reenable a unit file. *New in Chef Infra Client 14.0.* `:reload` Reload the configuration file for a systemd unit. `:reload_or_restart` For systemd units that are services, this action reloads the configuration of the service without restarting, if possible; otherwise, it will restart the service so the new configuration is applied. `:reload_or_try_restart` For systemd units that are services, this action reloads the configuration of the service without restarting, if possible; otherwise, it will try to restart the service so the new configuration is applied. `:restart` Restart a systemd unit. `:revert` Revert to a vendor’s version of a systemd unit file. *New in Chef Infra Client 14.0.* `:start` Start a systemd unit. `:stop` Stop a running systemd unit. `:try_restart` Try to restart a systemd unit if the unit is running. `:unmask` Stop the unit from being masked and cause it to start as specified. ### Properties --- The **systemd_unit** resource has the following properties: `content` **Ruby Type:** String, Hash A string or hash that contains a systemd [unit file](https://www.freedesktop.org/software/systemd/man/systemd.unit.html) definition that describes the properties of systemd-managed entities, such as services, sockets, devices, and so on. In Chef Infra Client 14.4 or later, repeatable options can be implemented with an array. `triggers_reload` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether to trigger a daemon reload when creating or deleting a unit. `unit_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the unit file if it differs from the resource block’s name. New in Chef Client 13.7 `user` **Ruby Type:** String The user account that the systemd unit process is run under. The path to the unit for that user would be something like ‘/etc/systemd/user/sshd.service’. If no user account is specified, the systemd unit will run under a ‘system’ account, with the path to the unit being something like ‘/etc/systemd/system/sshd.service’. `verify` **Ruby Type:** true, false | **Default Value:** `true` Specifies if the unit will be verified before installation. Systemd can be overly strict when verifying units, so in certain cases it is preferable not to verify the unit. ### Unit file verification The unit file is verified via a `systemd-analyze verify` call before being written to disk. Be aware that the referenced commands and files need to already exist before verification. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **systemd_unit** resource in recipes: **Create systemd service unit file from a Hash** ``` systemd_unit 'etcd.service' do content({ Unit: { Description: 'Etcd', Documentation: ['https://coreos.com/etcd', 'man:etcd(1)'], After: 'network.target', }, Service: { Type: 'notify', ExecStart: '/usr/local/etcd', Restart: 'always', }, Install: { WantedBy: 'multi-user.target', } }) action [:create, :enable] end ``` **Create systemd service unit file from a String** ``` systemd_unit 'sysstat-collect.timer' do content <<~EOU [Unit] Description=Run system activity accounting tool every 10 minutes [Timer] OnCalendar=*:00/10 [Install] WantedBy=sysstat.service EOU action [:create, :enable] end ``` template resource ----------------- [template resource page](template/index) --- A cookbook template is an Embedded Ruby (ERB) template that is used to dynamically generate static text files. Templates may contain Ruby expressions and statements, and are a great way to manage configuration files. Use the **template** resource to add cookbook templates to recipes; place the corresponding Embedded Ruby (ERB) template file in a cookbook’s `/templates` directory. Use the **template** resource to manage the contents of a file using an Embedded Ruby (ERB) template by transferring files from a sub-directory of `COOKBOOK_NAME/templates/` to a specified path located on a host that is running Chef Infra Client. This resource includes actions and properties from the **file** resource. Template files managed by the **template** resource follow the same file specificity rules as the **remote_file** and **file** resources. ### Syntax --- A **template** resource block typically declares the location in which a file is to be created, the source template that will be used to create the file, and the permissions needed on that file. For example: ``` template '/etc/motd' do source 'motd.erb' owner 'root' group 'root' mode '0755' end ``` where: * `'/etc/motd'` specifies the location in which the file is created * `'motd.erb'` specifies the name of a template that exists in in the `/templates` folder of a cookbook * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **template** resource is: ``` template 'name' do atomic_update true, false backup false, Integer cookbook String force_unlink true, false group String, Integer helper(:method) Method { String } # see Helpers below helpers(module) Module # see Helpers below inherits true, false local true, false manage_symlink_source true, false mode String, Integer owner String, Integer path String # defaults to 'name' if not specified rights Hash sensitive true, false source String, Array variables Hash verify String, Block action Symbol # defaults to :create if not specified end ``` where: * `template` is the resource * `name` is the name of the resource block, typically the path to the location in which a file is created *and also* the name of the file to be managed. For example: `/var/www/html/index.html`, where `/var/www/html/` is the fully qualified path to the location and `index.html` is the name of the file * `source` is the template file that will be used to create the file on the node, for example: `index.html.erb`; the template file is located in the `/templates` directory of a cookbook * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `atomic_update`, `backup`, `cookbook`, `force_unlink`, `group`, `helper`, `helpers`, `inherits`, `local`, `manage_symlink_source`, `mode`, `owner`, `path`, `rights`, `source`, `variables`, and `verify` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **template** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the **file** resource.) ### Properties --- The **template** resource has the following properties: `atomic_update` **Ruby Type:** true, false Perform atomic file updates on a per-resource basis. Set to `true` for atomic file updates. Set to `false` for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the client.rb file. `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `cookbook` **Ruby Type:** String The cookbook in which a file is located (if it is not located in the current cookbook). The default value is the current cookbook. `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `helper` **Ruby Type:** Method | **Default Value:** `{}` Define a helper method inline. For example: `helper(:hello_world) { "hello world" }` or `helper(:app) { node["app"] }` or `helper(:app_conf) { |setting| node["app"][setting] }`. `helpers` **Ruby Type:** Module | **Default Value:** `[]` Define a helper module inline or in a library. For example, an inline module: `helpers do`, which is then followed by a block of Ruby code. And for a library module: `helpers(MyHelperModule)`. `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `local` **Ruby Type:** true, false | **Default Value:** `false` Load a template from a local path. By default, Chef Infra Client loads templates from a cookbook’s `/templates` directory. When this property is set to `true`, use the `source` property to specify the path to a template on the local node. `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `true`, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `false`, Chef will follow the symlink and will manage the permissions and content of the symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The full path to the file, including the file name and its extension. Microsoft Windows: A path that begins with a forward slash (`/`) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (`/`) is not recommended. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String, Array The location of a template file. By default, Chef Infra Client looks for a template file in the `/templates` directory of a cookbook. When the `local` property is set to `true`, use to specify the path to a template on the local node. This property may also be used to distribute specific files to specific platforms. See “File Specificity” below for more information. Default value: the `name` of the resource block. See “Syntax” section above for more information. `variables` **Ruby Type:** Hash A Hash of variables that are passed into a Ruby template file. The `variables` property of the **template** resource can be used to reference a partial template file by using a Hash. For example: ``` template '/file/name.txt' do variables partials: { 'partial_name_1.txt.erb' => 'message', 'partial_name_2.txt.erb' => 'message', 'partial_name_3.txt.erb' => 'message', } end ``` where each of the partial template files can then be combined using normal Ruby template patterns within a template file, such as: ``` <% @partials.each do |partial, message| %> Here is <%= partial %> <%= render partial, :variables => {:message => message} %> <% end %``` `verify` **Ruby Type:** String, Block A block or a string that returns `true` or `false`. A string, when `true` is executed as a system command. A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block is `true`, Chef Infra Client will continue to update the file as appropriate. For example, this should return `true`: ``` template '/tmp/baz' do verify { 1 == 1 } end ``` This should return `true`: ``` template '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` This should return `true`: ``` template '/tmp/bar' do verify { 1 == 1} end ``` And this should return `true`: ``` template '/tmp/foo' do verify do |path| true end end ``` Whereas, this should return `false`: ``` template '/tmp/turtle' do verify '/usr/bin/false' end ``` If a string or a block return `false`, the Chef Infra Client run will stop and an error is returned. #### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. ### Using Templates To use a template, two things must happen: 1. A template resource must be added to a recipe 2. An Embedded Ruby (ERB) template must be added to a cookbook For example, the following template file and template resource settings can be used to manage a configuration file named `/etc/sudoers`. Within a cookbook that uses sudo, the following resource could be added to `/recipes/default.rb`: ``` template '/etc/sudoers' do source 'sudoers.erb' mode '0440' owner 'root' group 'root' variables(sudoers_groups: node['authorization']['sudo']['groups'], sudoers_users: node['authorization']['sudo']['users']) end ``` And then create a template called `sudoers.erb` and save it to `templates/default/sudoers.erb`: ``` # # /etc/sudoers # # Generated by Chef for <%= node['fqdn'] %> # Defaults !lecture,tty_tickets,!fqdn # User privilege specification root ALL=(ALL) ALL <% @sudoers_users.each do |user| -%> <%= user %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% end -%> # Members of the sysadmin group may gain root privileges %sysadmin ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% @sudoers_groups.each do |group| -%> # Members of the group '<%= group %>' may gain root privileges <%= group %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% end -%``` And then set the default attributes in `attributes/default.rb`: ``` default['authorization']['sudo']['groups'] = %w(sysadmin wheel admin) default['authorization']['sudo']['users'] = %w(jerry greg) ``` #### File Specificity A cookbook is frequently designed to work across many platforms and is often required to distribute a specific template to a specific platform. A cookbook can be designed to support the distribution of templates across platforms, while ensuring that the correct template ends up on each system. The pattern for template specificity depends on two things: the lookup path and the source. The first pattern that matches is used: 1. `/host-$fqdn/$source` 2. `/$platform-$platform_version/$source` 3. `/$platform/$source` 4. `/default/$source` 5. `/$source` Note To specify a particular Windows version, use the [operating system version number](https://docs.microsoft.com/en-us/windows/win32/sysinfo/operating-system-version). For example, a template in `templates/windows-6.3` will be deployed on systems installed with Windows 8.1. Use an array with the `source` property to define an explicit lookup path. For example: ``` template '/test' do source ["#{node.chef_environment}.erb", 'default.erb'] end ``` The following example emulates the entire file specificity pattern by defining it as an explicit path: ``` template '/test' do source %W( host-#{node['fqdn']}/test.erb #{node['platform']}-#{node['platform_version']}/test.erb #{node['platform']}/test.erb default/test.erb ) end ``` A cookbook may have a `/templates` directory structure like this: ``` /templates/ windows-10 windows-6.3 windows default ``` and a resource that looks something like the following: ``` template 'C:\path\to\file\text_file.txt' do source 'text_file.txt' mode '0755' owner 'root' group 'root' end ``` This resource would be matched in the same order as the `/templates` directory structure. For a node named `host-node-desktop` that is running Windows 8.1, the second item would be the matching item and the location: ``` /templates windows-10/text_file.txt windows-6.3/text_file.txt windows/text_file.txt default/text_file.txt ``` #### Helpers A helper is a method or a module that can be used to extend a template. There are three approaches: * An inline helper method * An inline helper module * A cookbook library module Use the `helper` attribute in a recipe to define an inline helper method. Use the `helpers` attribute to define an inline helper module or a cookbook library module. ##### Inline Methods A template helper method is always defined inline on a per-resource basis. A simple example: ``` template '/path' do helper(:hello_world) { 'hello world' } end ``` Another way to define an inline helper method is to reference a node object so that repeated calls to one (or more) cookbook attributes can be done efficiently: ``` template '/path' do helper(:app) { node['app'] } end ``` An inline helper method can also take arguments: ``` template '/path' do helper(:app_conf) { |setting| node['app'][setting] } end ``` Once declared, a template can then use the helper methods to build a file. For example: ``` Say hello: <%= hello_world %``` or: ``` node['app']['listen_port'] is: <%= app['listen_port'] %``` or: ``` node['app']['log_location'] is: <%= app_conf('log_location') %``` ##### Inline Modules A template helper module can be defined inline on a per-resource basis. This approach can be useful when a template requires more complex information. For example: ``` template '/path' do helpers do def hello_world 'hello world' end def app node['app'] end def app_conf(setting) node['app']['setting'] end end end ``` where the `hello_world`, `app`, and `app_conf(setting)` methods comprise the module that extends a template. ##### Library Modules A template helper module can be defined in a library. This is useful when extensions need to be reused across recipes or to make it easier to manage code that would otherwise be defined inline on a per-recipe basis. ``` template '/path/to/template.erb' do helpers(MyHelperModule) end ``` #### Host Notation The naming of folders within cookbook directories must literally match the host notation used for template specificity matching. For example, if a host is named `foo.example.com`, then the folder must be named `host-foo.example.com`. #### Partial Templates A template can be built in a way that allows it to contain references to one (or more) smaller template files. (These smaller template files are also referred to as partials.) A partial can be referenced from a template file in one of the following ways: * By using the `render` method in the template file * By using the **template** resource and the `variables` property. ##### render Method Use the `render` method in a template to reference a partial template file: ``` <%= render 'partial_name.txt.erb', :option => {} %``` where `partial_name` is the name of the partial template file and `:option` is one (or more) of the following: | Option | Description | | --- | --- | | `:cookbook` | By default, a partial template file is assumed to be located in the cookbook that contains the top-level template. Use this option to specify the path to a different cookbook | | `:local` | Indicates that the name of the partial template file should be interpreted as a path to a file in the local file system or looked up in a cookbook using the normal rules for template files. Set to `true` to interpret as a path to a file in the local file system and to `false` to use the normal rules for template files | | `:source` | By default, a partial template file is identified by its file name. Use this option to specify a different name or a local path to use (instead of the name of the partial template file) | | `:variables` | A hash of `variable_name => value` that will be made available to the partial template file. When this option is used, any variables that are defined in the top-level template that are required by the partial template file must have them defined explicitly using this option | For example: ``` <%= render 'simple.txt.erb', :variables => {:user => Etc.getlogin }, :local => true %``` #### Transfer Frequency The Chef Infra Client caches a template when it is first requested. On each subsequent request for that template, the Chef Infra Client compares that request to the template located on the Chef Infra Server. If the templates are the same, no transfer occurs. #### Variables An Embedded Ruby (ERB) template allows Ruby code to be embedded inside a text file within specially formatted tags. Ruby code can be embedded using expressions and statements. An expression is delimited by `<%=` and `%>`. For example: ``` <%= "my name is #{$ruby}" %``` A statement is delimited by a modifier, such as `if`, `elsif`, and `else`. For example: ``` if false # this won't happen elsif nil # this won't either end ``` Using a Ruby expression is the most common approach for defining template variables because this is how all variables that are sent to a template are referenced. Whenever a template needs to use an `each`, `if`, or `end`, use a Ruby statement. When a template is rendered, Ruby expressions and statements are evaluated by Chef Infra Client. The variables listed in the **template** resource’s `variables` parameter and in the node object are evaluated. Chef Infra Client then passes these variables to the template, where they will be accessible as instance variables within the template. The node object can be accessed just as if it were part of a recipe, using the same syntax. For example, a simple template resource like this: ``` node['fqdn'] = 'latte' template '/tmp/foo' do source 'foo.erb' variables(x_men: 'are keen') end ``` And a simple Embedded Ruby (ERB) template like this: ``` The node <%= node[:fqdn] %> thinks the x-men <%= @x_men %``` Would render something like: ``` The node latte thinks the x-men are keen ``` Even though this is a very simple example, the full capabilities of Ruby can be used to tackle even the most complex and demanding template requirements. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **template** resource in recipes: Configure a file from a template ``` template '/tmp/config.conf' do source 'config.conf.erb' end ``` Configure a file from a local template ``` template '/tmp/config.conf' do local true source '/tmp/config.conf.erb' end ``` Configure a file using a variable map ``` template '/tmp/config.conf' do source 'config.conf.erb' variables( :config_var => node['configs']['config_var'] ) end ``` Use the not_if condition The following example shows how to use the `not_if` condition to create a file based on a template and using the presence of an attribute value on the node to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if { node['some_value'] } end ``` The following example shows how to use the `not_if` condition to create a file based on a template and then Ruby code to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if do File.exist?('/etc/passwd') end end ``` The following example shows how to use the `not_if` condition to create a file based on a template and using a Ruby block (with curly braces) to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if { File.exist?('/etc/passwd') } end ``` The following example shows how to use the `not_if` condition to create a file based on a template and using a string to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if 'test -f /etc/passwd' end ``` Use the only_if condition The following example shows how to use the `only_if` condition to create a file based on a template and using the presence of an attribute on the node to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if { node['some_value'] } end ``` The following example shows how to use the `only_if` condition to create a file based on a template, and then use Ruby to specify a condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if { ! ::File.exist?('/etc/passwd') } end ``` The following example shows how to use the `only_if` condition to create a file based on a template and using a string to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if 'test -f /etc/passwd' end ``` Use a whitespace array (%w) The following example shows how to use a Ruby whitespace array to define a list of configuration tools, and then use that list of tools within the **template** resource to ensure that all of these configuration tools are using the same RSA key: ``` %w{openssl.cnf pkitool vars Rakefile}.each do |f| template "/etc/openvpn/easy-rsa/#{f}" do source "#{f}.erb" owner 'root' group 'root' mode '0755' end end ``` Use a relative path ``` template "#{ENV['HOME']}/chef-getting-started.txt" do source 'chef-getting-started.txt.erb' mode '0755' end ``` Delay notifications ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :delayed end ``` Notify immediately By default, notifications are `:delayed`, that is they are queued up as they are triggered, and then executed at the very end of a Chef Infra Client run. To run an action immediately, use `:immediately`: ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :immediately end ``` and then Chef Infra Client would immediately run the following: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing end ``` Notify multiple resources ``` template '/etc/chef/server.rb' do source 'server.rb.erb' owner 'root' group 'root' mode '0755' notifies :restart, 'service[chef-solr]', :delayed notifies :restart, 'service[chef-solr-indexer]', :delayed notifies :restart, 'service[chef-server]', :delayed end ``` Reload a service ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' notifies :reload, 'service[apache]', :immediately end ``` Restart a service when a template is modified ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :immediately end ``` Send notifications to multiple resources To send notifications to multiple resources, just use multiple attributes. Multiple attributes will get sent to the notified resources in the order specified. ``` template '/etc/netatalk/netatalk.conf' do notifies :restart, 'service[afpd]', :immediately notifies :restart, 'service[cnid]', :immediately end service 'afpd' service 'cnid' ``` Execute a command using a template The following example shows how to set up IPv4 packet forwarding using the **execute** resource to run a command named `forward_ipv4` that uses a template defined by the **template** resource: ``` execute 'forward_ipv4' do command 'echo > /proc/.../ipv4/ip_forward' action :nothing end template '/etc/file_name.conf' do source 'routing/file_name.conf.erb' notifies :run, 'execute[forward_ipv4]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[forward_ipv4]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. Set an IP address using variables and a template The following example shows how the **template** resource can be used in a recipe to combine settings stored in an attributes file, variables within a recipe, and a template to set the IP addresses that are used by the Nginx service. The attributes file contains the following: ``` default['nginx']['dir'] = '/etc/nginx' ``` The recipe then does the following to: * Declare two variables at the beginning of the recipe, one for the remote IP address and the other for the authorized IP address * Use the **service** resource to restart and reload the Nginx service * Load a template named `authorized_ip.erb` from the `/templates` directory that is used to set the IP address values based on the variables specified in the recipe ``` node.default['nginx']['remote_ip_var'] = 'remote_addr' node.default['nginx']['authorized_ips'] = ['127.0.0.1/32'] service 'nginx' do supports :status => true, :restart => true, :reload => true end template 'authorized_ip' do path "#{node['nginx']['dir']}/authorized_ip" source 'modules/authorized_ip.erb' owner 'root' group 'root' mode '0755' variables( :remote_ip_var => node['nginx']['remote_ip_var'], :authorized_ips => node['nginx']['authorized_ips'] ) notifies :reload, 'service[nginx]', :immediately end ``` where the `variables` property tells the template to use the variables set at the beginning of the recipe and the `source` property is used to call a template file located in the cookbook’s `/templates` directory. The template file looks similar to: ``` geo $<%= @remote_ip_var %> $authorized_ip { default no; <% @authorized_ips.each do |ip| %> <%= "#{ip} yes;" %> <% end %> } ``` Add a rule to an IP table The following example shows how to add a rule named `test_rule` to an IP table using the **execute** resource to run a command using a template that is defined by the **template** resource: ``` execute 'test_rule' do command 'command_to_run --option value ... --option value --source #{node[:name_of_node][:ipsec][:local][:subnet]} -j test_rule' action :nothing end template '/etc/file_name.local' do source 'routing/file_name.local.erb' notifies :run, 'execute[test_rule]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[test_rule]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. Apply proxy settings consistently across a Chef organization The following example shows how a template can be used to apply consistent proxy settings for all nodes of the same type: ``` template "#{node['matching_node']['dir']}/sites-available/site_proxy.conf" do source 'site_proxy.matching_node.conf.erb' owner 'root' group 'root' mode '0755' variables( :ssl_certificate => "#{node['matching_node']['dir']}/shared/certificates/site_proxy.crt", :ssl_key => "#{node['matching_node']['dir']}/shared/certificates/site_proxy.key", :listen_port => node['site']['matching_node_proxy']['listen_port'], :server_name => node['site']['matching_node_proxy']['server_name'], :fqdn => node['fqdn'], :server_options => node[:site]['matching_node']['server']['options'], :proxy_options => node[:site]['matching_node']['proxy']['options'] ) end ``` where `matching_node` represents a type of node (like Nginx) and `site_proxy` represents the type of proxy being used for that type of node (like Nexus). Get template settings from a local file The **template** resource can be used to render a template based on settings contained in a local file on disk or to get the settings from a template in a cookbook. Most of the time, the settings are retrieved from a template in a cookbook. The following example shows how the **template** resource can be used to retrieve these settings from a local file. The following example is based on a few assumptions: * The environment is a Ruby on Rails application that needs render a file named `database.yml` * Information about the application—the user, their password, the server—is stored in a data bag on the Chef server * The application is already deployed to the system and that only requirement in this example is to render the `database.yml` file The application source tree looks something like: ``` myapp/ -> config/ -> database.yml.erb ``` Note There should not be a file named `database.yml` (without the `.erb`), as the `database.yml` file is what will be rendered using the **template** resource. The deployment of the app will end up in `/srv`, so the full path to this template would be something like `/srv/myapp/current/config/database.yml.erb`. The content of the template itself may look like this: ``` <%= @rails_env %>: adapter: <%= @adapter %> host: <%= @host %> database: <%= @database %> username: <%= @username %> password: <%= @password %> encoding: 'utf8' reconnect: true ``` The recipe will be similar to the following: ``` results = search(:node, "role:myapp_database_master AND chef_environment:#{node.chef_environment}") db_master = results[0] template '/srv/myapp/shared/database.yml' do source '/srv/myapp/current/config/database.yml.erb' local true variables( :rails_env => node.chef_environment, :adapter => db_master['myapp']['db_adapter'], :host => db_master['fqdn'], :database => "myapp_#{node.chef_environment}", :username => "myapp", :password => "SUPERSECRET", ) end ``` where: * the `search` method in the Chef Infra Language is used to find the first node that is the database master (of which there should only be one) * the `:adapter` variable property may also require an attribute to have been set on a role, which then determines the correct adapter The template will render similar to the following: ``` production: adapter: mysql host: domU-12-31-39-14-F1-C3.compute-1.internal database: myapp_production username: myapp password: SUPERSECRET encoding: utf8 reconnect: true ``` This example showed how to use the **template** resource to render a template based on settings contained in a local file. Some other issues that should be considered when using this type of approach include: * Should the `database.yml` file be in a `.gitignore` file? * How do developers run the application locally? * Does this work with chef-solo? Pass values from recipe to template The following example shows how pass a value to a template using the `variables` property in the **template** resource. The template file is similar to: ``` [tcpout] defaultGroup = splunk_indexers_<%= node['splunk']['receiver_port'] %> disabled=false [tcpout:splunk_indexers_<%= node['splunk']['receiver_port'] %>] server=<% @splunk_servers.map do |s| -%><%= s['ipaddress'] %>:<%= s['splunk']['receiver_port'] %> <% end.join(', ') -%> <% @outputs_conf.each_pair do |name, value| -%> <%= name %> = <%= value %> <% end -%``` The recipe then uses the `variables` attribute to find the values for `splunk_servers` and `outputs_conf`, before passing them into the template: ``` template "#{splunk_dir}/etc/system/local/outputs.conf" do source 'outputs.conf.erb' mode '0755' variables :splunk_servers => splunk_servers, :outputs_conf => node['splunk']['outputs_conf'] notifies :restart, 'service[splunk]' end ``` This example can be found in the `client.rb` recipe and the `outputs.conf.erb` template files that are located in the [chef-splunk cookbook](https://github.com/chef-cookbooks/chef-splunk/) that is maintained by Chef. timezone resource ----------------- [timezone resource page](timezone/index) --- Use the **timezone** resource to change the system timezone on Windows, Linux, and macOS hosts. Timezones are specified in tz database format, with a complete list of available TZ values for Linux and macOS here: <https://en.wikipedia.org/wiki/List_of_tz_database_time_zones>. On Windows systems run `tzutil /l` for a complete list of valid timezones. **New in Chef Infra Client 14.6.** ### Syntax --- The full syntax for all of the properties that are available to the **timezone** resource is: ``` timezone 'name' do timezone String # default value: 'name' unless specified action Symbol # defaults to :set if not specified end ``` where: * `timezone` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `timezone` is the property available to this resource. ### Actions --- The **timezone** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set the system timezone. (default) ### Properties --- The **timezone** resource has the following properties: `timezone` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the timezone value if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **timezone** resource in recipes: **Set the timezone to UTC** ``` timezone 'UTC' ``` **Set the timezone to America/Los_Angeles with a friendly resource name on Linux/macOS** ``` timezone "Set the host's timezone to America/Los_Angeles" do timezone 'America/Los_Angeles' end ``` **Set the timezone to PST with a friendly resource name on Windows** ``` timezone "Set the host's timezone to PST" do timezone 'Pacific Standard time' end ``` user resource ------------- [user resource page](user/index) --- Use the **user** resource to add users, update existing users, remove users, and to lock/unlock user passwords. Note System attributes are collected by Ohai at the start of every Chef Infra Client run. By design, the actions available to the **user** resource are processed **after** the start of a Chef Infra Client run. This means that system attributes added or modified by the **user** resource during a Chef Infra Client run must be reloaded before they can be available to Chef Infra Client. These system attributes can be reloaded in two ways: by picking up the values at the start of the (next) Chef Infra Client run or by using the [ohai resource](ohai/index) to reload the system attributes during the current Chef Infra Client run. ### Syntax --- A **user** resource block manages users on a node: ``` user 'a user' do comment 'A random user' uid 1234 gid 'groupname' home '/home/random' shell '/bin/bash' password '$1$JJsvHslasdfjVEroftprNn4JHtDi' end ``` The full syntax for all of the properties that are available to the **user** resource is: ``` user 'name' do comment String force true, false # see description gid String, Integer home String iterations Integer manage_home true, false non_unique true, false password String salt String shell String system true, false uid String, Integer username String # defaults to 'name' if not specified action Symbol # defaults to :create if not specified end ``` where: * `user` is the resource * `name` is the name of the resource block * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `comment`, `force`, `gid`, `home`, `iterations`, `manage_home`, `non_unique`, `password`, `salt`, `shell`, `system`, `uid`, and `username` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **user** resource has the following actions: `:create` Default. Create a user with given properties. If a user already exists (but does not match), update that user to match. `:lock` Lock a user’s password. `:manage` Manage an existing user. This action does nothing if the user does not exist. `:modify` Modify an existing user. This action raises an exception if the user does not exist. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a user. `:unlock` Unlock a user’s password. ### Properties --- The **user** resource has the following properties: `comment` **Ruby Type:** String One (or more) comments about the user. `force` **Ruby Type:** true, false Force the removal of a user. May be used only with the `:remove` action. Warning Using this property may leave the system in an inconsistent state. For example, a user account will be removed even if the user is logged in. A user’s home directory will be removed, even if that directory is shared by multiple users. `gid` **Ruby Type:** String, Integer The identifier for the group. This property was previously named `group` and both continue to function. `home` **Ruby Type:** String The location of the home directory. `iterations` **Ruby Type:** Integer macOS platform only. The number of iterations for a password with a SALTED-SHA512-PBKDF2 shadow hash. `manage_home` **Ruby Type:** true, false Manage a user’s home directory. When used with the `:create` action, a user’s home directory is created based on `HOME_DIR`. If the home directory is missing, it is created unless `CREATE_HOME` in `/etc/login.defs` is set to `no`. When created, a skeleton set of files and subdirectories are included within the home directory. When used with the `:modify` action, a user’s home directory is moved to `HOME_DIR`. If the home directory is missing, it is created unless `CREATE_HOME` in `/etc/login.defs` is set to `no`. The contents of the user’s home directory are moved to the new location. `non_unique` **Ruby Type:** true, false Create a duplicate (non-unique) user account. `password` **Ruby Type:** String The password shadow hash `salt` **Ruby Type:** String A SALTED-SHA512-PBKDF2 hash. `shell` **Ruby Type:** String The login shell. `system` **Ruby Type:** true, false Create a system user. This property may be used with `useradd` as the provider to create a system user which passes the `-r` flag to `useradd`. `uid` **Ruby Type:** String, Integer The numeric user identifier. `username` **Ruby Type:** String The name of the user. Default value: the `name` of the resource block. See “Syntax” section above for more information. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **user** resource in recipes: Create a system user ``` user 'systemguy' do comment 'system guy' system true shell '/bin/false' end ``` Create a system user with a variable The following example shows how to create a system user. In this instance, the `home` value is calculated and stored in a variable called `user_home` which sets the user’s `home` attribute. ``` user_home = "/home/#{node['cookbook_name']['user']}" user node['cookbook_name']['user'] do gid node['cookbook_name']['group'] shell '/bin/bash' home user_home system true action :create end ``` Use SALTED-SHA512-PBKDF2 passwords macOS 10.8 (and higher) calculates the password shadow hash using SALTED-SHA512-PBKDF2. The length of the shadow hash value is 128 bytes, the salt value is 32 bytes, and an integer specifies the number of iterations. The following code will calculate password shadow hashes for macOS 10.8 (and higher): ``` password = 'my_awesome_password' salt = OpenSSL::Random.random_bytes(32) iterations = 25000 # Any value above 20k should be fine. shadow_hash = OpenSSL::PKCS5::pbkdf2_hmac( password, salt, iterations, 128, OpenSSL::Digest::SHA512.new ).unpack('H*').first salt_value = salt.unpack('H*').first ``` Use the calculated password shadow hash with the **user** resource: ``` user 'my_awesome_user' do password 'cbd1a....fc843' # Length: 256 salt 'bd1a....fc83' # Length: 64 iterations 25000 end ``` user_ulimit resource --------------------- [user_ulimit resource page](user_ulimit/index) --- Use the **user_ulimit** resource to create individual ulimit files that are installed into the `/etc/security/limits.d/` directory. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **user_ulimit** resource is: ``` user_ulimit 'name' do core_hard_limit String, Integer core_limit String, Integer core_soft_limit String, Integer filehandle_hard_limit String, Integer filehandle_limit String, Integer filehandle_soft_limit String, Integer filename String memory_limit String, Integer process_hard_limit String, Integer process_limit String, Integer process_soft_limit String, Integer rtprio_hard_limit String, Integer rtprio_limit String, Integer rtprio_soft_limit String, Integer stack_hard_limit String, Integer stack_limit String, Integer stack_soft_limit String, Integer username String # default value: 'name' unless specified virt_limit String, Integer action Symbol # defaults to :create if not specified end ``` where: * `user_ulimit` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `core_hard_limit`, `core_limit`, `core_soft_limit`, `filehandle_hard_limit`, `filehandle_limit`, `filehandle_soft_limit`, `filename`, `memory_limit`, `process_hard_limit`, `process_limit`, `process_soft_limit`, `rtprio_hard_limit`, `rtprio_limit`, `rtprio_soft_limit`, `stack_hard_limit`, `stack_limit`, `stack_soft_limit`, `username`, and `virt_limit` are the properties available to this resource. ### Actions --- The **user_ulimit** resource has the following actions: `:create` Create a ulimit configuration file. (default) `:delete` Delete an existing ulimit configuration file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **user_ulimit** resource has the following properties: `core_hard_limit` **Ruby Type:** String, Integer `core_limit` **Ruby Type:** String, Integer `core_soft_limit` **Ruby Type:** String, Integer `filehandle_hard_limit` **Ruby Type:** String, Integer `filehandle_limit` **Ruby Type:** String, Integer `filehandle_soft_limit` **Ruby Type:** String, Integer `filename` **Ruby Type:** String | **Default Value:** `lazy default` `memory_limit` **Ruby Type:** String, Integer `process_hard_limit` **Ruby Type:** String, Integer `process_limit` **Ruby Type:** String, Integer `process_soft_limit` **Ruby Type:** String, Integer `rtprio_hard_limit` **Ruby Type:** String, Integer `rtprio_limit` **Ruby Type:** String, Integer `rtprio_soft_limit` **Ruby Type:** String, Integer `stack_hard_limit` **Ruby Type:** String, Integer `stack_limit` **Ruby Type:** String, Integer `stack_soft_limit` **Ruby Type:** String, Integer `username` **Ruby Type:** String | **Default Value:** `The resource block's name` `virt_limit` **Ruby Type:** String, Integer ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **user_ulimit** resource in recipes: **Set filehandle limit for the tomcat user**: ``` user_ulimit 'tomcat' do filehandle_limit 8192 end ``` **Specify a username that differs from the name given to the resource block**: ``` user_ulimit 'Bump filehandle limits for tomcat user' do username 'tomcat' filehandle_limit 8192 end ``` **Set filehandle limit for the tomcat user with a non-default filename**: ``` user_ulimit 'tomcat' do filehandle_limit 8192 filename 'tomcat_filehandle_limits.conf' end ``` windows_ad_join resource -------------------------- [windows_ad_join resource page](windows_ad_join/index) --- Use the **windows_ad_join** resource to join a Windows Active Directory domain. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_ad_join** resource is: ``` windows_ad_join 'name' do domain_name String # default value: 'name' unless specified domain_password String domain_user String new_hostname String ou_path String reboot Symbol # default value: :immediate reboot_delay Integer # default value: 0 workgroup_name String action Symbol # defaults to :join if not specified end ``` where: * `windows_ad_join` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `domain_name`, `domain_password`, `domain_user`, `new_hostname`, `ou_path`, `reboot`, `reboot_delay`, and `workgroup_name` are the properties available to this resource. ### Actions --- The **windows_ad_join** resource has the following actions: `:join` Join the Active Directory domain. (default) `:leave` Leave an Active Directory domain and re-join a workgroup. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_ad_join** resource has the following properties: `domain_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the FQDN of the Active Directory domain to join if it differs from the resource block’s name. `domain_password` **Ruby Type:** String | `REQUIRED` The password for the domain user. Note that this resource is set to hide sensitive information by default. `domain_user` **Ruby Type:** String | `REQUIRED` The domain user that will be used to join the domain. `new_hostname` **Ruby Type:** String Specifies a new hostname for the computer in the new domain. New in Chef Client 14.5 `ou_path` **Ruby Type:** String The path to the Organizational Unit where the host will be placed. `reboot` **Ruby Type:** Symbol | **Default Value:** `:immediate` **Allowed Values:** `:delayed, :immediate, :never, :reboot_now, :request_reboot` Controls the system reboot behavior post domain joining. Reboot immediately, after the Chef Infra Client run completes, or never. Note that a reboot is necessary for changes to take effect. `reboot_delay` **Ruby Type:** Integer | **Default Value:** `0` The amount of time (in minutes) to delay a reboot request. New in Chef Infra Client 16.5 `workgroup_name` **Ruby Type:** String Specifies the name of a workgroup to which the computer is added to when it is removed from the domain. The default value is WORKGROUP. This property is only applicable to the :leave action. New in Chef Infra Client 15.4 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_ad_join** resource in recipes: **Join a domain** ``` windows_ad_join 'ad.example.org' do domain_user 'nick' domain_password 'p@ssw0rd1' end ``` **Join a domain, as `win-workstation`** ``` windows_ad_join 'ad.example.org' do domain_user 'nick' domain_password 'p@ssw0rd1' new_hostname 'win-workstation' end ``` **Leave the current domain and re-join the `local` workgroup** ``` windows_ad_join 'Leave domain' do action :leave workgroup 'local' end ``` windows_audit_policy resource ------------------------------- [windows_audit_policy resource page](windows_audit_policy/index) --- Use the **windows_audit_policy** resource to configure system level and per-user Windows advanced audit policy settings. **New in Chef Infra Client 16.2.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_audit_policy** resource is: ``` windows_audit_policy 'name' do audit_base_directories true, false audit_base_objects true, false crash_on_audit_fail true, false exclude_user String failure true, false full_privilege_auditing true, false include_user String subcategory String, Array success true, false action Symbol # defaults to :set if not specified end ``` where: * `windows_audit_policy` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `audit_base_directories`, `audit_base_objects`, `crash_on_audit_fail`, `exclude_user`, `failure`, `full_privilege_auditing`, `include_user`, `subcategory`, and `success` are the properties available to this resource. ### Actions --- The **windows_audit_policy** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Configure an audit policy. (default) ### Properties --- The **windows_audit_policy** resource has the following properties: `audit_base_directories` **Ruby Type:** true, false Setting this audit policy option to true will force the system to assign a System Access Control List to named objects to enable auditing of container objects such as directories. `audit_base_objects` **Ruby Type:** true, false Setting this audit policy option to true will force the system to assign a System Access Control List to named objects to enable auditing of base objects such as mutexes. `crash_on_audit_fail` **Ruby Type:** true, false Setting this audit policy option to true will cause the system to crash if the auditing system is unable to log events. `exclude_user` **Ruby Type:** String The audit policy specified by the category or subcategory is applied per-user if specified. When a user is specified, exclude user. Include and exclude cannot be used at the same time. `failure` **Ruby Type:** true, false Specify failure auditing. By setting this property to true the resource will enable failure for the category or sub category. Success is the default and is applied if neither success nor failure are specified. `full_privilege_auditing` **Ruby Type:** true, false Setting this audit policy option to true will force the audit of all privilege changes except SeAuditPrivilege. Setting this property may cause the logs to fill up more quickly. `include_user` **Ruby Type:** String The audit policy specified by the category or subcategory is applied per-user if specified. When a user is specified, include user. Include and exclude cannot be used at the same time. `subcategory` **Ruby Type:** String, Array The audit policy subcategory, specified by GUID or name. Applied system-wide if no user is specified. `success` **Ruby Type:** true, false Specify success auditing. By setting this property to true the resource will enable success for the category or sub category. Success is the default and is applied if neither success nor failure are specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_audit_policy** resource in recipes: **Set Logon and Logoff policy to “Success and Failure”**: ``` windows_audit_policy "Set Audit Policy for 'Logon and Logoff' actions to 'Success and Failure'" do subcategory %w(Logon Logoff) success true failure true action :set end ``` **Set Credential Validation policy to “Success”**: ``` windows_audit_policy "Set Audit Policy for 'Credential Validation' actions to 'Success'" do subcategory 'Credential Validation' success true failure false action :set end ``` **Enable CrashOnAuditFail option**: ``` windows_audit_policy 'Enable CrashOnAuditFail option' do crash_on_audit_fail true action :set end ``` windows_auto_run resource --------------------------- [windows_auto_run resource page](windows_auto_run/index) --- Use the **windows_auto_run** resource to set applications to run at login. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_auto_run** resource is: ``` windows_auto_run 'name' do args String path String program_name String # default value: 'name' unless specified root Symbol # default value: :machine action Symbol # defaults to :create if not specified end ``` where: * `windows_auto_run` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `args`, `path`, `program_name`, and `root` are the properties available to this resource. ### Actions --- The **windows_auto_run** resource has the following actions: `:create` Create an item to be run at login. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an item that was previously configured to run at login. ### Properties --- The **windows_auto_run** resource has the following properties: `args` **Ruby Type:** String Any arguments to be used with the program. `path` **Ruby Type:** String The path to the program that will run at login. `program_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the program to run at login if it differs from the resource block’s name. `root` **Ruby Type:** Symbol | **Default Value:** `:machine` **Allowed Values:** `:machine, :user` The registry root key to put the entry under. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_auto_run** resource in recipes: **Run BGInfo at login** ``` windows_auto_run 'BGINFO' do program 'C:/Sysinternals/bginfo.exe' args ''C:/Sysinternals/Config.bgi' /NOLICPROMPT /TIMER:0' action :create end ``` windows_certificate resource ----------------------------- [windows_certificate resource page](windows_certificate/index) --- Use the **windows_certificate** resource to install a certificate into the Windows certificate store from a file. The resource grants read-only access to the private key for designated accounts. Due to current limitations in WinRM, installing certificates remotely may not work if the operation requires a user profile. Operations on the local machine store should still work. **New in Chef Infra Client 14.7.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_certificate** resource is: ``` windows_certificate 'name' do exportable true, false # default value: false output_path String pfx_password String private_key_acl Array source String # default value: 'name' unless specified store_name String # default value: "MY" user_store true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_certificate` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `exportable`, `output_path`, `pfx_password`, `private_key_acl`, `source`, `store_name`, and `user_store` are the properties available to this resource. ### Actions --- The **windows_certificate** resource has the following actions: `:acl_add` Adds read-only entries to a certificate’s private key ACL. `:create` Creates or updates a certificate. (default) `:delete` Deletes a certificate. `:fetch` Fetches a certificate. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:verify` Verifies a certificate and logs the result. ### Properties --- The **windows_certificate** resource has the following properties: `exportable` **Ruby Type:** true, false | **Default Value:** `false` Ensure that imported pfx certificate is exportable. Please provide ‘true’ if you want the certificate to be exportable. New in Chef Infra Client 16.8 `output_path` **Ruby Type:** String A path on the node where a certificate object (PFX, PEM, CER, KEY, etc) can be exported to. New in Chef Infra Client 17.0 `pfx_password` **Ruby Type:** String The password to access the object with if it is a PFX file. `private_key_acl` **Ruby Type:** Array An array of ‘domain\account’ entries to be granted read-only access to the certificate’s private key. Not idempotent. `source` **Ruby Type:** String | **Default Value:** `The resource block's name` The source file (for `create` and `acl_add`), thumbprint (for `delete`, `export`, and `acl_add`), or subject (for `delete` or `export`) if it differs from the resource block’s name. `store_name` **Ruby Type:** String | **Default Value:** `MY` **Allowed Values:** `"AUTHROOT", "CA", "CLIENTAUTHISSUER", "DISALLOWED", "MY", "REMOTE DESKTOP", "ROOT", "SMARTCARDROOT", "TRUST", "TRUSTEDDEVICES", "TRUSTEDPEOPLE", "TRUSTEDPUBLISHER", "TrustedPublisher", "WEBHOSTING"` The certificate store to manipulate. `user_store` **Ruby Type:** true, false | **Default Value:** `false` Use the `CurrentUser` store instead of the default `LocalMachine` store. Note Prior to chef-client. 16.10 this property was ignored. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_certificate** resource in recipes: **Add PFX cert to local machine personal store and grant accounts read-only access to private key** ``` windows_certificate 'c:/test/mycert.pfx' do pfx_password 'password' private_key_acl ["acme\fred", "pc\jane"] end ``` **Add cert to trusted intermediate store** ``` windows_certificate 'c:/test/mycert.cer' do store_name 'CA' end ``` **Remove all certificates matching the subject** ``` windows_certificate 'me.acme.com' do action :delete end ``` windows_defender resource -------------------------- [windows_defender resource page](windows_defender/index) --- Use the **windows_defender** resource to enable or disable the Microsoft Windows Defender service. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_defender** resource is: ``` windows_defender 'name' do intrusion_protection_system true, false # default value: true lock_ui true, false # default value: false realtime_protection true, false # default value: true scan_archives true, false # default value: true scan_email true, false # default value: false scan_mapped_drives true, false # default value: true scan_network_files true, false # default value: false scan_removable_drives true, false # default value: false scan_scripts true, false # default value: false action Symbol # defaults to :enable if not specified end ``` where: * `windows_defender` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `intrusion_protection_system`, `lock_ui`, `realtime_protection`, `scan_archives`, `scan_email`, `scan_mapped_drives`, `scan_network_files`, `scan_removable_drives`, and `scan_scripts` are the properties available to this resource. ### Actions --- The **windows_defender** resource has the following actions: `:disable` Disable Windows Defender. `:enable` Enable and configure Windows Defender. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_defender** resource has the following properties: `intrusion_protection_system` **Ruby Type:** true, false | **Default Value:** `true` Enable network protection against exploitation of known vulnerabilities. `lock_ui` **Ruby Type:** true, false | **Default Value:** `false` Lock the UI to prevent users from changing Windows Defender settings. `realtime_protection` **Ruby Type:** true, false | **Default Value:** `true` Enable realtime scanning of downloaded files and attachments. `scan_archives` **Ruby Type:** true, false | **Default Value:** `true` Scan file archives such as .zip or .gz archives. `scan_email` **Ruby Type:** true, false | **Default Value:** `false` Scan e-mails for malware. `scan_mapped_drives` **Ruby Type:** true, false | **Default Value:** `true` Scan files on mapped network drives. `scan_network_files` **Ruby Type:** true, false | **Default Value:** `false` Scan files on a network. `scan_removable_drives` **Ruby Type:** true, false | **Default Value:** `false` Scan content of removable drives. `scan_scripts` **Ruby Type:** true, false | **Default Value:** `false` Scan scripts in malware scans. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_defender** resource in recipes: **Configure Windows Defender AV settings**: ``` windows_defender 'Configure Defender' do realtime_protection true intrusion_protection_system true lock_ui true scan_archives true scan_scripts true scan_email true scan_removable_drives true scan_network_files false scan_mapped_drives false action :enable end ``` **Disable Windows Defender AV**: ``` windows_defender 'Disable Defender' do action :disable end ``` windows_defender_exclusion resource ------------------------------------- [windows_defender_exclusion resource page](windows_defender_exclusion/index) --- Use the **windows_defender_exclusion** resource to exclude paths, processes, or file types from Windows Defender realtime protection scanning. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_defender_exclusion** resource is: ``` windows_defender_exclusion 'name' do extensions String, Array # default value: [] paths String, Array # default value: [] process_paths String, Array # default value: [] action Symbol # defaults to :add if not specified end ``` where: * `windows_defender_exclusion` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `extensions`, `paths`, and `process_paths` are the properties available to this resource. ### Actions --- The **windows_defender_exclusion** resource has the following actions: `:add` Add an exclusion to Windows Defender. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an exclusion to Windows Defender. ### Properties --- The **windows_defender_exclusion** resource has the following properties: `extensions` **Ruby Type:** String, Array | **Default Value:** `[]` File extensions to exclude from scanning. `paths` **Ruby Type:** String, Array | **Default Value:** `[]` File or directory paths to exclude from scanning. `process_paths` **Ruby Type:** String, Array | **Default Value:** `[]` Paths to executables to exclude from scanning. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_defender_exclusion** resource in recipes: **Add excluded items to Windows Defender scans**: ``` windows_defender_exclusion 'Add to things to be excluded from scanning' do paths 'c:\foo\bar, d:\bar\baz' extensions 'png, foo, ppt, doc' process_paths 'c:\windows\system32' action :add end ``` **Remove excluded items from Windows Defender scans**: ``` windows_defender_exclusion 'Remove things from the list to be excluded' do process_paths 'c:\windows\system32' action :remove end ``` windows_dfs_folder resource ----------------------------- [windows_dfs_folder resource page](windows_dfs_folder/index) --- Use the **windows_dfs_folder** resource to creates a folder within DFS as many levels deep as required. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_dfs_folder** resource is: ``` windows_dfs_folder 'name' do description String folder_path String # default value: 'name' unless specified namespace_name String target_path String action Symbol # defaults to :create if not specified end ``` where: * `windows_dfs_folder` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `description`, `folder_path`, `namespace_name`, and `target_path` are the properties available to this resource. ### Actions --- The **windows_dfs_folder** resource has the following actions: `:create` Creates the folder in dfs namespace. (default) `:delete` Deletes the folder in the dfs namespace. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_dfs_folder** resource has the following properties: `description` **Ruby Type:** String Description for the share. `folder_path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the path of the dfs folder if it differs from the resource block’s name. `namespace_name` **Ruby Type:** String | `REQUIRED` The namespace this should be created within. `target_path` **Ruby Type:** String The target that this path will connect you to. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. windows_dfs_namespace resource -------------------------------- [windows_dfs_namespace resource page](windows_dfs_namespace/index) --- Use the **windows_dfs_namespace** resource to creates a share and DFS namespace on a Windows server. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_dfs_namespace** resource is: ``` windows_dfs_namespace 'name' do change_users Array # default value: [] description String full_users Array # default value: ["BUILTIN\\administrators"] namespace_name String # default value: 'name' unless specified read_users Array # default value: [] root String # default value: "C:\\DFSRoots" action Symbol # defaults to :create if not specified end ``` where: * `windows_dfs_namespace` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `change_users`, `description`, `full_users`, `namespace_name`, `read_users`, and `root` are the properties available to this resource. ### Actions --- The **windows_dfs_namespace** resource has the following actions: `:create` Creates the dfs namespace on the server. (default) `:delete` Deletes a DFS Namespace including the directory on disk. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_dfs_namespace** resource has the following properties: `change_users` **Ruby Type:** Array | **Default Value:** `[]` Determines which users should have change access to the share. `description` **Ruby Type:** String | `REQUIRED` Description of the share. `full_users` **Ruby Type:** Array | **Default Value:** `["BUILTIN\\administrators"]` Determines which users should have full access to the share. `namespace_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the dfs namespace if it differs from the resource block’s name. `read_users` **Ruby Type:** Array | **Default Value:** `[]` Determines which users should have read access to the share. `root` **Ruby Type:** String | **Default Value:** `C:\DFSRoots` The root from which to create the DFS tree. Defaults to C:\DFSRoots. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. windows_dfs_server resource ----------------------------- [windows_dfs_server resource page](windows_dfs_server/index) --- Use the **windows_dfs_server** resource to set system-wide DFS settings. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_dfs_server** resource is: ``` windows_dfs_server 'name' do enable_site_costed_referrals true, false # default value: false ldap_timeout_secs Integer # default value: 30 prefer_login_dc true, false # default value: false sync_interval_secs Integer # default value: 3600 use_fqdn true, false # default value: false action Symbol # defaults to :configure if not specified end ``` where: * `windows_dfs_server` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `enable_site_costed_referrals`, `ldap_timeout_secs`, `prefer_login_dc`, `sync_interval_secs`, and `use_fqdn` are the properties available to this resource. ### Actions --- The **windows_dfs_server** resource has the following actions: `:configure` Configure DFS settings (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_dfs_server** resource has the following properties: `enable_site_costed_referrals` **Ruby Type:** true, false | **Default Value:** `false` `ldap_timeout_secs` **Ruby Type:** Integer | **Default Value:** `30` `prefer_login_dc` **Ruby Type:** true, false | **Default Value:** `false` `sync_interval_secs` **Ruby Type:** Integer | **Default Value:** `3600` `use_fqdn` **Ruby Type:** true, false | **Default Value:** `false` Indicates whether a DFS namespace server uses FQDNs in referrals. If this property is set to true, the server uses FQDNs in referrals. If this property is set to false then the server uses NetBIOS names. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. windows_dns_record resource ----------------------------- [windows_dns_record resource page](windows_dns_record/index) --- The windows_dns_record resource creates a DNS record for the given domain. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_dns_record** resource is: ``` windows_dns_record 'name' do dns_server String # default value: "localhost" record_name String # default value: 'name' unless specified record_type String # default value: "ARecord" target String zone String action Symbol # defaults to :create if not specified end ``` where: * `windows_dns_record` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `dns_server`, `record_name`, `record_type`, `target`, and `zone` are the properties available to this resource. ### Actions --- The **windows_dns_record** resource has the following actions: `:create` Creates and updates the DNS entry. (default) `:delete` Deletes a DNS entry. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_dns_record** resource has the following properties: `dns_server` **Ruby Type:** String | **Default Value:** `localhost` The name of the DNS server on which to create the record. New in Chef Infra Client 16.3 `record_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the dns record name if it differs from the resource block’s name. `record_type` **Ruby Type:** String | **Default Value:** `ARecord` **Allowed Values:** `"ARecord", "CNAME", "PTR"` The type of record to create, can be either ARecord, CNAME or PTR. `target` **Ruby Type:** String | `REQUIRED` The target for the record. `zone` **Ruby Type:** String | `REQUIRED` The zone to create the record in. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. windows_dns_zone resource --------------------------- [windows_dns_zone resource page](windows_dns_zone/index) --- The windows_dns_zone resource creates an Active Directory Integrated DNS Zone on the local server. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_dns_zone** resource is: ``` windows_dns_zone 'name' do replication_scope String # default value: "Domain" server_type String # default value: "Domain" zone_name String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `windows_dns_zone` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `replication_scope`, `server_type`, and `zone_name` are the properties available to this resource. ### Actions --- The **windows_dns_zone** resource has the following actions: `:create` Creates and updates a DNS Zone. (default) `:delete` Deletes a DNS Zone. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_dns_zone** resource has the following properties: `replication_scope` **Ruby Type:** String | **Default Value:** `Domain` The replication scope for the zone, required if server_type set to ‘Domain’. `server_type` **Ruby Type:** String | **Default Value:** `Domain` **Allowed Values:** `"Domain", "Standalone"` The type of DNS server, Domain or Standalone. `zone_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the dns zone name if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. windows_env resource --------------------- [windows_env resource page](windows_env/index) --- Use the **windows_env** resource to manage environment keys in Microsoft Windows. After an environment key is set, Microsoft Windows must be restarted before the environment key will be available to the Task Scheduler. This resource was previously called the **env** resource; its name was updated in Chef Infra Client 14.0 to reflect the fact that only Windows is supported. Existing cookbooks using `env` will continue to function, but should be updated to use the new name. Note On UNIX-based systems, the best way to manipulate environment keys is with the `ENV` variable in Ruby; however, this approach does not have the same permanent effect as using the windows_env resource. ### Syntax --- The full syntax for all of the properties that are available to the **windows_env** resource is: ``` windows_env 'name' do delim String, false key_name String # default value: 'name' unless specified user String # default value: "<System>" value String action Symbol # defaults to :create if not specified end ``` where: * `windows_env` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `delim`, `key_name`, `user`, and `value` are the properties available to this resource. ### Actions --- The **windows_env** resource has the following actions: `:create` Create an environment variable. If an environment variable already exists (but does not match), update that environment variable to match. (default) `:delete` Delete an environment variable. `:modify` Modify an existing environment variable. This prepends the new value to the existing value, using the delimiter specified by the `delim` property. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_env** resource has the following properties: `delim` **Ruby Type:** String, false The delimiter that is used to separate multiple values for a single key. `key_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the name of the key that is to be created, deleted, or modified if it differs from the resource block’s name. `user` **Ruby Type:** String | **Default Value:** `<System>` `value` **Ruby Type:** String | `REQUIRED` The value of the environmental variable to set. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_env** resource in recipes: **Set an environment variable**: ``` windows_env 'ComSpec' do value 'C:\Windows\system32\cmd.exe' end ``` windows_feature resource ------------------------- [windows_feature resource page](windows_feature/index) --- Use the **windows_feature** resource to add, remove or entirely delete Windows features and roles. This resource calls the [windows_feature_dism](windows_feature_dism/index) or [windows_feature_powershell](windows_feature_powershell/index) resources depending on the specified installation method, and defaults to DISM, which is available on both Workstation and Server editions of Windows. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_feature** resource is: ``` windows_feature 'name' do all true, false # default value: false feature_name Array, String # default value: 'name' unless specified install_method Symbol # default value: :windows_feature_dism management_tools true, false # default value: false source String timeout Integer # default value: 600 action Symbol # defaults to :install if not specified end ``` where: * `windows_feature` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `all`, `feature_name`, `install_method`, `management_tools`, `source`, and `timeout` are the properties available to this resource. ### Actions --- The **windows_feature** resource has the following actions: `:delete` Remove a Windows role or feature from the image. `:install` Install a Windows role or feature. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows role or feature. ### Properties --- The **windows_feature** resource has the following properties: `all` **Ruby Type:** true, false | **Default Value:** `false` Install all sub-features. `feature_name` **Ruby Type:** Array, String | **Default Value:** `The resource block's name` The name of the feature(s) or role(s) to install if they differ from the resource block’s name. The same feature may have different names depending on the underlying installation method being used (ie DHCPServer vs DHCP; DNS-Server-Full-Role vs DNS). `install_method` **Ruby Type:** Symbol | **Default Value:** `:windows_feature_dism` **Allowed Values:** `:windows_feature_dism, :windows_feature_powershell, :windows_feature_servermanagercmd` The underlying installation method to use for feature installation. Specify `:windows_feature_dism` for DISM or `:windows_feature_powershell` for PowerShell. `management_tools` **Ruby Type:** true, false | **Default Value:** `false` Install all applicable management tools for the roles, role services, or features (PowerShell-only). `source` **Ruby Type:** String Specify a local repository for the feature install. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Specifies a timeout (in seconds) for the feature installation. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_feature** resource in recipes: **Install the DHCP Server feature**: ``` windows_feature 'DHCPServer' do action :install end ``` **Install the .Net 3.5.1 feature using repository files on DVD**: ``` windows_feature "NetFx3" do action :install source 'd:\sources\sxs' end ``` **Remove Telnet Server and Client features**: ``` windows_feature %w(TelnetServer TelnetClient) do action :remove end ``` **Add the SMTP Server feature using the PowerShell provider**: ``` windows_feature 'smtp-server' do action :install all true install_method :windows_feature_powershell end ``` **Install multiple features using one resource with the PowerShell provider**: ``` windows_feature %w(Web-Asp-Net45 Web-Net-Ext45) do action :install install_method :windows_feature_powershell end ``` **Install the Network Policy and Access Service feature, including the management tools**: ``` windows_feature 'NPAS' do action :install management_tools true install_method :windows_feature_powershell end ``` windows_feature_dism resource ------------------------------- [windows_feature_dism resource page](windows_feature_dism/index) --- Use the **windows_feature_dism** resource to add, remove, or entirely delete Windows features and roles using DISM. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_feature_dism** resource is: ``` windows_feature_dism 'name' do all true, false # default value: false feature_name Array, String # default value: 'name' unless specified source String timeout Integer # default value: 600 action Symbol # defaults to :install if not specified end ``` where: * `windows_feature_dism` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `all`, `feature_name`, `source`, and `timeout` are the properties available to this resource. ### Actions --- The **windows_feature_dism** resource has the following actions: `:delete` Remove a Windows role or feature from the image using DISM. `:install` Install a Windows role/feature using DISM. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows role or feature using DISM. ### Properties --- The **windows_feature_dism** resource has the following properties: `all` **Ruby Type:** true, false | **Default Value:** `false` Install all sub-features. When set to `true`, this is the equivalent of specifying the `/All` switch to `dism.exe` `feature_name` **Ruby Type:** Array, String | **Default Value:** `The resource block's name` The name of the feature(s) or role(s) to install if they differ from the resource name. `source` **Ruby Type:** String Specify a local repository for the feature install. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Specifies a timeout (in seconds) for the feature installation. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_feature_dism** resource in recipes: **Installing the TelnetClient service**: ``` windows_feature_dism "TelnetClient" ``` **Installing two features by using an array**: ``` windows_feature_dism %w(TelnetClient TFTP) ``` windows_feature_powershell resource ------------------------------------- [windows_feature_powershell resource page](windows_feature_powershell/index) --- Use the **windows_feature_powershell** resource to add, remove, or entirely delete Windows features and roles using PowerShell. This resource offers significant speed benefits over the [windows_feature_dism](windows_feature_dism/index) resource, but requires installation of the Remote Server Administration Tools on non-server releases of Windows. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_feature_powershell** resource is: ``` windows_feature_powershell 'name' do all true, false # default value: false feature_name Array, String # default value: 'name' unless specified management_tools true, false # default value: false source String timeout Integer # default value: 600 action Symbol # defaults to :install if not specified end ``` where: * `windows_feature_powershell` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `all`, `feature_name`, `management_tools`, `source`, and `timeout` are the properties available to this resource. ### Actions --- The **windows_feature_powershell** resource has the following actions: `:delete` Delete a Windows role or feature from the image using PowerShell. `:install` Install a Windows role or feature using PowerShell. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows role or feature using PowerShell. ### Properties --- The **windows_feature_powershell** resource has the following properties: `all` **Ruby Type:** true, false | **Default Value:** `false` Install all subfeatures. When set to `true`, this is the equivalent of specifying the `-InstallAllSubFeatures` switch with `Add-WindowsFeature`. `feature_name` **Ruby Type:** Array, String | **Default Value:** `The resource block's name` The name of the feature(s) or role(s) to install if they differ from the resource block’s name. `management_tools` **Ruby Type:** true, false | **Default Value:** `false` Install all applicable management tools for the roles, role services, or features. `source` **Ruby Type:** String Specify a local repository for the feature install. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Specifies a timeout (in seconds) for the feature installation. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_feature_powershell** resource in recipes: **Add the SMTP Server feature**: ``` windows_feature_powershell "smtp-server" do action :install all true end ``` **Install multiple features using one resource**: ``` windows_feature_powershell ['Web-Asp-Net45', 'Web-Net-Ext45'] do action :install end ``` **Install the Network Policy and Access Service feature**: ``` windows_feature_powershell 'NPAS' do action :install management_tools true end ``` windows_firewall_profile resource ----------------------------------- [windows_firewall_profile resource page](windows_firewall_profile/index) --- Use the **windows_firewall_profile** resource to enable, disable, and configure the Windows firewall. **New in Chef Infra Client 16.3.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_firewall_profile** resource is: ``` windows_firewall_profile 'name' do allow_inbound_rules true, false, String allow_local_firewall_rules true, false, String allow_local_ipsec_rules true, false, String allow_unicast_response true, false, String allow_user_apps true, false, String allow_user_ports true, false, String default_inbound_action String default_outbound_action String display_notification true, false, String profile String # default value: 'name' unless specified action Symbol # defaults to :enable if not specified end ``` where: * `windows_firewall_profile` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_inbound_rules`, `allow_local_firewall_rules`, `allow_local_ipsec_rules`, `allow_unicast_response`, `allow_user_apps`, `allow_user_ports`, `default_inbound_action`, `default_outbound_action`, `display_notification`, and `profile` are the properties available to this resource. ### Actions --- The **windows_firewall_profile** resource has the following actions: `:disable` Disable a Windows Firewall profile. `:enable` Enable and optionally configure a Windows Firewall profile. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_firewall_profile** resource has the following properties: `allow_inbound_rules` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow users to set inbound firewall rules `allow_local_firewall_rules` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Merges inbound firewall rules into the policy `allow_local_ipsec_rules` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow users to manage local connection security rules `allow_unicast_response` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow unicast responses to multicast and broadcast messages `allow_user_apps` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow user applications to manage firewall `allow_user_ports` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow users to manage firewall port rules `default_inbound_action` **Ruby Type:** String **Allowed Values:** `"Allow", "Block", "NotConfigured"` Set the default policy for inbound network traffic `default_outbound_action` **Ruby Type:** String **Allowed Values:** `"Allow", "Block", "NotConfigured"` Set the default policy for outbound network traffic `display_notification` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Display a notification when firewall blocks certain activity `profile` **Ruby Type:** String | **Default Value:** `The resource block's name` **Allowed Values:** `"Domain", "Private", "Public"` Set the Windows Profile being configured ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_firewall_profile** resource in recipes: **Enable and Configure the Private Profile of the Windows Profile**: ``` windows_firewall_profile 'Private' do default_inbound_action 'Block' default_outbound_action 'Allow' allow_inbound_rules true display_notification false action :enable end ``` **Enable and Configure the Public Profile of the Windows Firewall**: ``` windows_firewall_profile 'Public' do default_inbound_action 'Block' default_outbound_action 'Allow' allow_inbound_rules false display_notification false action :enable end ``` **Disable the Domain Profile of the Windows Firewall**: ``` windows_firewall_profile 'Disable the Domain Profile of the Windows Firewall' do profile 'Domain' action :disable end ``` windows_firewall_rule resource -------------------------------- [windows_firewall_rule resource page](windows_firewall_rule/index) --- Use the **windows_firewall_rule** resource to create, change or remove Windows firewall rules. **New in Chef Infra Client 14.7.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_firewall_rule** resource is: ``` windows_firewall_rule 'name' do description String direction Symbol, String # default value: :inbound displayname String # default value: The rule_name property value. enabled true, false # default value: true firewall_action Symbol, String # default value: :allow group String icmp_type String, Integer # default value: "Any" interface_type Symbol, String # default value: :any local_address String local_port String, Integer, Array profile Symbol, String, Array # default value: :any program String protocol String # default value: "TCP" remote_address String, Array remote_port String, Integer, Array rule_name String # default value: 'name' unless specified service String action Symbol # defaults to :create if not specified end ``` where: * `windows_firewall_rule` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `description`, `direction`, `displayname`, `enabled`, `firewall_action`, `group`, `icmp_type`, `interface_type`, `local_address`, `local_port`, `profile`, `program`, `protocol`, `remote_address`, `remote_port`, `rule_name`, and `service` are the properties available to this resource. ### Actions --- The **windows_firewall_rule** resource has the following actions: `:create` Create a Windows firewall entry. (default) `:delete` Delete an existing Windows firewall entry. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_firewall_rule** resource has the following properties: `description` **Ruby Type:** String The description to assign to the firewall rule. `direction` **Ruby Type:** Symbol, String | **Default Value:** `:inbound` **Allowed Values:** `:inbound, :outbound` The direction of the firewall rule. Direction means either inbound or outbound traffic. `displayname` **Ruby Type:** String | **Default Value:** `The rule_name property value.` The displayname to assign to the firewall rule. New in Chef Infra Client 16.0 `enabled` **Ruby Type:** true, false | **Default Value:** `true` Whether or not to enable the firewall rule. `firewall_action` **Ruby Type:** Symbol, String | **Default Value:** `:allow` **Allowed Values:** `:allow, :block, :notconfigured` The action of the firewall rule. `group` **Ruby Type:** String Specifies that only matching firewall rules of the indicated group association are copied. New in Chef Infra Client 16.0 `icmp_type` **Ruby Type:** String, Integer | **Default Value:** `Any` Specifies the ICMP Type parameter for using a protocol starting with ICMP New in Chef Infra Client 16.0 `interface_type` **Ruby Type:** Symbol, String | **Default Value:** `:any` **Allowed Values:** `:any, :remoteaccess, :wired, :wireless` The interface type the firewall rule applies to. `local_address` **Ruby Type:** String The local address the firewall rule applies to. `local_port` **Ruby Type:** String, Integer, Array The local port the firewall rule applies to. `profile` **Ruby Type:** Symbol, String, Array | **Default Value:** `:any` The profile the firewall rule applies to. `program` **Ruby Type:** String The program the firewall rule applies to. `protocol` **Ruby Type:** String | **Default Value:** `TCP` The protocol the firewall rule applies to. `remote_address` **Ruby Type:** String, Array The remote address(es) the firewall rule applies to. `remote_port` **Ruby Type:** String, Integer, Array The remote port the firewall rule applies to. `rule_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the name of the firewall rule to assign if it differs from the resource block’s name. `service` **Ruby Type:** String The service the firewall rule applies to. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_firewall_rule** resource in recipes: **Allowing port 80 access**: ``` windows_firewall_rule 'IIS' do local_port '80' protocol 'TCP' firewall_action :allow end ``` **Configuring multiple remote-address ports on a rule**: ``` windows_firewall_rule 'MyRule' do description 'Testing out remote address arrays' enabled false local_port 1434 remote_address %w(10.17.3.101 172.7.7.53) protocol 'TCP' action :create end ``` **Allow protocol ICMPv6 with ICMP Type**: ``` windows_firewall_rule 'CoreNet-Rule' do rule_name 'CoreNet-ICMP6-LR2-In' display_name 'Core Networking - Multicast Listener Report v2 (ICMPv6-In)' local_port 'RPC' protocol 'ICMPv6' icmp_type '8' end ``` **Blocking WinRM over HTTP on a particular IP**: ``` windows_firewall_rule 'Disable WinRM over HTTP' do local_port '5985' protocol 'TCP' firewall_action :block local_address '192.168.1.1' end ``` **Deleting an existing rule** ``` windows_firewall_rule 'Remove the SSH rule' do rule_name 'ssh' action :delete end ``` windows_font resource ---------------------- [windows_font resource page](windows_font/index) --- Use the **windows_font** resource to install font files on Windows. By default, the font is sourced from the cookbook using the resource, but a URI source can be specified as well. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_font** resource is: ``` windows_font 'name' do font_name String # default value: 'name' unless specified source String action Symbol # defaults to :install if not specified end ``` where: * `windows_font` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `font_name` and `source` are the properties available to this resource. ### Actions --- The **windows_font** resource has the following actions: `:install` Install a font to the system fonts directory. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_font** resource has the following properties: `font_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the name of the font to install if it differs from the resource block’s name. `source` **Ruby Type:** String A local filesystem path or URI that is used to source the font file. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_font** resource in recipes: **Install a font from a https source**: ``` windows_font 'Custom.otf' do source 'https://example.com/Custom.otf' end ``` windows_package resource ------------------------- [windows_package resource page](windows_package/index) --- Use the **windows_package** resource to manage packages on the Microsoft Windows platform. The **windows_package** resource supports these installer formats: * Microsoft Installer Package (MSI) * Nullsoft Scriptable Install System (NSIS) * Inno Setup (inno) * Wise * InstallShield * Custom installers such as installing a non-.msi file that embeds an .msi-based installer To enable idempotence of the `:install` action or to enable the `:remove` action with no source property specified, `package_name` MUST be an exact match of the name used by the package installer. The names of installed packages Windows knows about can be found in **Add/Remove programs**, in the output of `ohai packages`, or in the `DisplayName` property in one of the following in the Windows registry: * `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall` * `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall` * `HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall` Note If there are multiple versions of a package installed with the same display name, all of those packages will be removed unless a version is provided in the **version** property or unless it can be discovered in the installer file specified by the **source** property. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **windows_package** resource block manages a package on a node, typically by installing it. The simplest use of the **windows_package** resource is: ``` windows_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **windows_package** resource is: ``` windows_package 'name' do checksum String installer_type Symbol options String package_name String remote_file_attributes Hash returns String, Integer, Array source String # default value: "The resource block's name" timeout String, Integer # default value: "600 (seconds)" version String action Symbol # defaults to :install if not specified end ``` where: * `windows_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `checksum`, `installer_type`, `options`, `package_name`, `remote_file_attributes`, `returns`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **windows_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. ### Properties --- The **windows_package** resource has the following properties: `checksum` **Ruby Type:** String The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, Chef Infra Client does not download it. Use when a URL is specified by the `source` property. `installer_type` **Ruby Type:** Symbol **Allowed Values:** `:custom, :inno, :installshield, :msi, :nsis, :wise` A symbol that specifies the type of package. Possible values: `:custom` (such as installing a non-.msi file that embeds an .msi-based installer), `:inno` (Inno Setup), `:installshield` (InstallShield), `:msi` (Microsoft Installer Package (MSI)), `:nsis` (Nullsoft Scriptable Install System (NSIS)), `:wise` (Wise). `options` **Ruby Type:** String One (or more) additional options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `remote_file_attributes` **Ruby Type:** Hash This property allows you to define a hash of properties and their value if the source package to be installed is at a remote location. This hash will be used by the underlying **remote_file** resource which will fetch the source package. `returns` **Ruby Type:** String, Integer, Array of integers | **Default Value:** `0 (success) and 3010 (success where a reboot is necessary)` A comma-delimited list of return codes that indicate the success or failure of the package command that was run. `source` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to a package in the local file system. The location of the package may be at a URL. If the `source` property is not specified, the package name MUST be exactly the same as the display name found in **Add/Remove programs** or exactly the same as the `DisplayName` property in the appropriate registry key, which may be one of the following: ``` HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall ``` Note If there are multiple versions of a package installed with the same display name, all of those packages will be removed unless a version is provided in the `version` property or unless it can be discovered in the installer file specified by the `source` property. `timeout` **Ruby Type:** String, Integer | **Default Value:** `600 (seconds)` The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_package** resource in recipes: **Install a package**: ``` windows_package '7zip' do action :install source 'C:\7z920.msi' end ``` **Specify a URL for the source attribute**: ``` windows_package '7zip' do source 'http://www.7-zip.org/a/7z938-x64.msi' end ``` **Specify path and checksum**: ``` windows_package '7zip' do source 'http://www.7-zip.org/a/7z938-x64.msi' checksum '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3' end ``` **Modify remote_file resource attributes**: The windows_package resource may specify a package at a remote location using the remote_file_attributes property. This uses the remote_file resource to download the contents at the specified URL and passes in a Hash that modifies the properties of the remote_file resource. ``` windows_package '7zip' do source 'http://www.7-zip.org/a/7z938-x64.msi' remote_file_attributes ({ :path => 'C:\7zip.msi', :checksum => '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3' }) end ``` **Download a nsis (Nullsoft) package resource**: ``` windows_package 'Mercurial 3.6.1 (64-bit)' do source 'http://mercurial.selenic.com/release/windows/Mercurial-3.6.1-x64.exe' checksum 'febd29578cb6736163d232708b834a2ddd119aa40abc536b2c313fc5e1b5831d' end ``` **Download a custom package**: ``` windows_package 'Microsoft Visual C++ 2005 Redistributable' do source 'https://download.microsoft.com/download/6/B/B/6BB661D6-A8AE-4819-B79F-236472F6070C/vcredist_x86.exe' installer_type :custom options '/Q' end ``` windows_pagefile resource -------------------------- [windows_pagefile resource page](windows_pagefile/index) --- Use the **windows_pagefile** resource to configure pagefile settings on Windows. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_pagefile** resource is: ``` windows_pagefile 'name' do automatic_managed true, false initial_size Integer maximum_size Integer path String # default value: 'name' unless specified system_managed true, false action Symbol # defaults to :set if not specified end ``` where: * `windows_pagefile` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `automatic_managed`, `initial_size`, `maximum_size`, `path`, and `system_managed` are the properties available to this resource. ### Actions --- The **windows_pagefile** resource has the following actions: `:delete` Deletes the specified pagefile. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Configures the default pagefile, creating if it doesn’t exist. (default) ### Properties --- The **windows_pagefile** resource has the following properties: `automatic_managed` **Ruby Type:** true, false Enable automatic management of pagefile initial and maximum size. Setting this to true ignores `initial_size` and `maximum_size` properties. `initial_size` **Ruby Type:** Integer Initial size of the pagefile in megabytes. `maximum_size` **Ruby Type:** Integer Maximum size of the pagefile in megabytes. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the pagefile name if it differs from the resource block’s name. `system_managed` **Ruby Type:** true, false Configures whether the system manages the pagefile size. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_pagefile** resource in recipes: **Set the system to manage pagefiles**: ``` windows_pagefile 'Enable automatic management of pagefiles' do automatic_managed true end ``` **Delete a pagefile**: ``` windows_pagefile 'Delete the pagefile' do path 'C' action :delete end ``` **Switch to system managed pagefiles**: ``` windows_pagefile 'Change the pagefile to System Managed' do path 'E:' system_managed true action :set end ``` **Create a pagefile with an initial and maximum size**: ``` windows_pagefile 'create the pagefile with these sizes' do path 'f:' initial_size 100 maximum_size 200 end ``` windows_path resource ---------------------- [windows_path resource page](windows_path/index) --- Use the **windows_path** resource to manage the path environment variable on Microsoft Windows. **New in Chef Infra Client 13.4.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_path** resource is: ``` windows_path 'name' do path String # default value: 'name' unless specified action Symbol # defaults to :add if not specified end ``` where: * `windows_path` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `path` is the property available to this resource. ### Actions --- The **windows_path** resource has the following actions: `:add` Add an item to the system path. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an item from the system path. ### Properties --- The **windows_path** resource has the following properties: `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the path value if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_path** resource in recipes: **Add Sysinternals to the system path**: ``` windows_path 'C:\Sysinternals' do action :add end ``` **Remove 7-Zip from the system path**: ``` windows_path 'C:\7-Zip' do action :remove end ``` windows_printer resource ------------------------- [windows_printer resource page](windows_printer/index) --- Use the **windows_printer** resource to setup Windows printers. This resource will automatically install the driver specified in the `driver_name` property and will automatically create a printer port using either the `ipv4_address` property or the `port_name` property. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_printer** resource is: ``` windows_printer 'name' do comment String create_port true, false # default value: true default true, false # default value: false device_id String # default value: 'name' unless specified driver_name String ipv4_address String location String port_name String share_name String shared true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_printer` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `comment`, `create_port`, `default`, `device_id`, `driver_name`, `ipv4_address`, `location`, `port_name`, `share_name`, and `shared` are the properties available to this resource. ### Actions --- The **windows_printer** resource has the following actions: `:create` Create a new printer and printer port, if one doesn’t already. (default) `:delete` Delete an existing printer. Note that this resource does not delete the associated printer port. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_printer** resource has the following properties: `comment` **Ruby Type:** String Optional descriptor for the printer queue. `create_port` **Ruby Type:** true, false | **Default Value:** `true` Create a printer port for the printer. Set this to false and specify the `port_name` property if using the `windows_printer_port` resource to create the port instead. New in Chef Infra Client 17.3 `default` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not this should be the system’s default printer. `device_id` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the printer queue name if it differs from the resource block’s name. Example: `HP LJ 5200 in fifth floor copy room`. `driver_name` **Ruby Type:** String | `REQUIRED` The exact name of printer driver installed on the system. `ipv4_address` **Ruby Type:** String The IPv4 address of the printer, such as `10.4.64.23` `location` **Ruby Type:** String Printer location, such as `Fifth floor copy room`. `port_name` **Ruby Type:** String | **Default Value:** `The resource block name or the ipv4_address prepended with IP_.` The port name. New in Chef Infra Client 17.3 `share_name` **Ruby Type:** String The name used to identify the shared printer. `shared` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not the printer is shared. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_printer** resource in recipes: **Create a printer**: ``` windows_printer 'HP LaserJet 5th Floor' do driver_name 'HP LaserJet 4100 Series PCL6' ipv4_address '10.4.64.38' end ``` **Delete a printer**: Note: this doesn’t delete the associated printer port. See windows_printer_port above for how to delete the port. ``` windows_printer 'HP LaserJet 5th Floor' do action :delete end ``` **Create a printer port and a printer that uses that port (new in 17.3)** ``` windows_printer_port '10.4.64.39' do port_name 'My awesome printer port' snmp_enabled true port_protocol 2 end windows_printer 'HP LaserJet 5th Floor' do driver_name 'HP LaserJet 4100 Series PCL6' port_name 'My awesome printer port' ipv4_address '10.4.64.38' create_port false end ``` windows_printer_port resource ------------------------------- [windows_printer_port resource page](windows_printer_port/index) --- Use the **windows_printer_port** resource to create and delete TCP/IPv4 printer ports on Windows. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_printer_port** resource is: ``` windows_printer_port 'name' do ipv4_address String # default value: 'name' unless specified port_name String port_number Integer # default value: 9100 port_protocol Integer # default value: 1 snmp_enabled true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_printer_port` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ipv4_address`, `port_name`, `port_number`, `port_protocol`, and `snmp_enabled` are the properties available to this resource. ### Actions --- The **windows_printer_port** resource has the following actions: `:create` Create or update the printer port. (default) `:delete` Delete an existing printer port. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_printer_port** resource has the following properties: `ipv4_address` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for the IPv4 address of the printer if it differs from the resource block’s name. `port_name` **Ruby Type:** String | **Default Value:** `The resource block name or the ipv4_address prepended with IP_.` The port name. `port_number` **Ruby Type:** Integer | **Default Value:** `9100` The TCP port number. `port_protocol` **Ruby Type:** Integer | **Default Value:** `1` **Allowed Values:** `1, 2` The printer port protocol: 1 (RAW) or 2 (LPR). `snmp_enabled` **Ruby Type:** true, false | **Default Value:** `false` Determines if SNMP is enabled on the port. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_printer_port** resource in recipes: **Delete a printer port** ``` windows_printer_port '10.4.64.37' do action :delete end ``` **Delete a port with a custom port_name** ``` windows_printer_port '10.4.64.38' do port_name 'My awesome port' action :delete end ``` **Create a port with more options** ``` windows_printer_port '10.4.64.39' do port_name 'My awesome port' snmp_enabled true port_protocol 2 end ``` windows_security_policy resource ---------------------------------- [windows_security_policy resource page](windows_security_policy/index) --- Use the **windows_security_policy** resource to set a security policy on the Microsoft Windows platform. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_security_policy** resource is: ``` windows_security_policy 'name' do secoption String # default value: 'name' unless specified secvalue String action Symbol # defaults to :set if not specified end ``` where: * `windows_security_policy` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `secoption` and `secvalue` are the properties available to this resource. ### Actions --- The **windows_security_policy** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set the Windows security policy (default) ### Properties --- The **windows_security_policy** resource has the following properties: `secoption` **Ruby Type:** String | **Default Value:** `The resource block's name` | `REQUIRED` **Allowed Values:** `"AuditPolicyChange", "ClearTextPassword", "EnableAdminAccount", "EnableGuestAccount", "ForceLogoffWhenHourExpire", "LSAAnonymousNameLookup", "LockoutBadCount", "LockoutDuration", "LockoutDuration", "MaximumPasswordAge", "MinimumPasswordAge", "MinimumPasswordLength", "NewAdministratorName", "NewGuestName", "PasswordComplexity", "PasswordHistorySize", "RequireLogonToChangePassword", "ResetLockoutCount"` The name of the policy to be set on windows platform to maintain its security. `secvalue` **Ruby Type:** String | `REQUIRED` Policy value to be set for policy name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_security_policy** resource in recipes: **Set Administrator Account to Enabled**: ``` windows_security_policy 'EnableAdminAccount' do secvalue '1' action :set end ``` **Rename Administrator Account**: ``` windows_security_policy 'NewAdministratorName' do secvalue 'AwesomeChefGuy' action :set end ``` **Set Guest Account to Disabled**: ``` windows_security_policy 'EnableGuestAccount' do secvalue '0' action :set end ``` windows_service resource ------------------------- [windows_service resource page](windows_service/index) --- Use the **windows_service** resource to create, delete, or manage a service on the Microsoft Windows platform. ### Syntax --- A **windows_service** resource block manages the state of a service on a machine that is running Microsoft Windows. For example: ``` windows_service 'BITS' do action :configure_startup startup_type :manual end ``` The full syntax for all of the properties that are available to the **windows_service** resource is: ``` windows_service 'name' do binary_path_name String delayed_start true, false # default value: false dependencies String, Array description String desired_access Integer # default value: 983551 display_name String error_control Integer # default value: 1 init_command String load_order_group String pattern String reload_command String, false restart_command String, false run_as_password String run_as_user String # default value: "LocalSystem" service_name String # default value: 'name' unless specified service_type Integer # default value: "SERVICE_WIN32_OWN_PROCESS" start_command String, false startup_type Symbol # default value: :automatic status_command String, false stop_command String, false supports Hash # default value: {"restart"=>nil, "reload"=>nil, "status"=>nil} timeout Integer action Symbol # defaults to :nothing if not specified end ``` where: * `windows_service` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `binary_path_name`, `display_name`, `desired_access`, `delayed_start`, `dependencies`, `description`, `error_control`, `init_command`, `load_order_group`, `pattern`, `reload_command`, `restart_command`, `run_as_password`, `run_as_user`, `service_name`, `service_type`, `start_command`, `startup_type`, `status_command`, `stop_command`, `supports`, and `timeout` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **windows_service** resource has the following actions: `:configure` Configure a pre-existing service. *New in Chef Client 14.0.* `:configure_startup` Configure a service based on the value of the `startup_type` property. `:create` Create the service based on the value of the `binary_path_name`, `service_name` and/or `display_name` property. *New in Chef Client 14.0.* `:delete` Delete the service based on the value of the `service_name` property. *New in Chef Client 14.0.* `:disable` Disable a service. This action is equivalent to a `Disabled` startup type on the Microsoft Windows platform. `:enable` Enable a service at boot. This action is equivalent to an `Automatic` startup type on the Microsoft Windows platform. `:nothing` Default. Do nothing with a service. `:reload` Reload the configuration for this service. This action is not supported on the Windows platform and will raise an error if used. `:restart` Restart a service. `:start` Start a service, and keep it running until stopped or disabled. `:stop` Stop a service. ### Properties --- The **windows_service** resource has the following properties: `binary_path_name` **Ruby Type:** String The fully qualified path to the service binary file. The path can also include arguments for an auto-start service. This is required for `:create` and `:configure` actions New in Chef Client 14.0 `delayed_start` **Ruby Type:** true, false | **Default Value:** `false` Set the startup type to delayed start. This only applies if `startup_type` is `:automatic` New in Chef Client 14.0 `dependencies` **Ruby Type:** String, Array A pointer to a double null-terminated array of null-separated names of services or load ordering groups that the system must start before this service. Specify `nil` or an empty string if the service has no dependencies. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group. New in Chef Client 14.0 `description` **Ruby Type:** String Description of the service. New in Chef Client 14.0 `desired_access` **Ruby Type:** Integer | **Default Value:** `983551` New in Chef Client 14.0 `display_name` **Ruby Type:** String The display name to be used by user interface programs to identify the service. This string has a maximum length of 256 characters. New in Chef Client 14.0 `error_control` **Ruby Type:** Integer | **Default Value:** `1` New in Chef Client 14.0 `load_order_group` **Ruby Type:** String The name of the service’s load ordering group(s). New in Chef Client 14.0 `pattern` **Ruby Type:** String | **Default Value:** `The value provided to 'service_name' or the resource block's name` The pattern to look for in the process table. `reload_command` **Ruby Type:** String, false The command used to tell a service to reload its configuration. `restart_command` **Ruby Type:** String, false The command used to restart a service. `run_as_password` **Ruby Type:** String The password for the user specified by `run_as_user`. `run_as_user` **Ruby Type:** String | **Default Value:** `localsystem` The user under which a Microsoft Windows service runs. `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the service name if it differs from the resource block’s name. `service_type` **Ruby Type:** Integer | **Default Value:** `16` New in Chef Client 14.0 `start_command` **Ruby Type:** String, false The command used to start a service. `startup_type` **Ruby Type:** Symbol | **Default Value:** `:automatic` **Allowed Values:** `:automatic, :disabled, :manual` Use to specify the startup type of the service. `status_command` **Ruby Type:** String, false The command used to check the run status for a service. `stop_command` **Ruby Type:** String, false The command used to stop a service. `supports` **Ruby Type:** Hash | **Default Value:** `{"restart"=>nil, "reload"=>nil, "status"=>nil}` A list of properties that controls how Chef Infra Client is to attempt to manage a service: `:restart`, `:reload`, `:status`. For `:restart`, the init script or other service provider can use a restart command; if `:restart` is not specified, Chef Infra Client attempts to stop and then start a service. For `:reload`, the init script or other service provider can use a reload command. For `:status`, the init script or other service provider can use a status command to determine if the service is running; if `:status` is not specified, Chef Infra Client attempts to match the `service_name` against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: `{ restart: false, reload: false, status: false }` for all platforms (except for the Red Hat platform family, which defaults to `{ restart: false, reload: false, status: true }`.) `timeout` **Ruby Type:** Integer | **Default Value:** `60` The amount of time (in seconds) to wait before timing out. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_service** resource in recipes: **Starting Services** Start a service with a `manual` startup type: ``` windows_service 'BITS' do action :configure_startup startup_type :manual end ``` **Creating Services** Create a service named chef-client: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" end ``` Create a service with `service_name` and `display_name`: ``` windows_service 'Setup chef-client as a service' do action :create display_name 'CHEF-CLIENT' service_name 'chef-client' binary_path_name "C:\opscode\chef\bin" end ``` Create a service with the `manual` startup type: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :manual end ``` Create a service with the `disabled` startup type: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :disabled end ``` Create a service with the `automatic` startup type and delayed start enabled: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :automatic delayed_start true end ``` Create a service with a description: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :automatic description "Chef client as service" end ``` **Deleting Services** Delete a service named chef-client: ``` windows_service 'chef-client' do action :delete end ``` Delete a service with the `service_name` property: ``` windows_service 'Delete chef client' do action :delete service_name 'chef-client' end ``` **Configuring Services** Change an existing service from automatic to manual startup: ``` windows_service 'chef-client' do action :configure binary_path_name "C:\opscode\chef\bin" startup_type :manual end ``` windows_share resource ----------------------- [windows_share resource page](windows_share/index) --- Use the **windows_share** resource to create, modify and remove Windows shares. **New in Chef Infra Client 14.7.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_share** resource is: ``` windows_share 'name' do ca_timeout Integer # default value: 0 change_users Array # default value: [] concurrent_user_limit Integer # default value: 0 continuously_available true, false # default value: false description String encrypt_data true, false # default value: false full_users Array # default value: [] path String read_users Array # default value: [] scope_name String # default value: "*" share_name String # default value: 'name' unless specified temporary true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_share` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ca_timeout`, `change_users`, `concurrent_user_limit`, `continuously_available`, `description`, `encrypt_data`, `full_users`, `path`, `read_users`, `scope_name`, `share_name`, and `temporary` are the properties available to this resource. ### Actions --- The **windows_share** resource has the following actions: `:create` Create or modify a Windows share. (default) `:delete` Delete an existing Windows share. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_share** resource has the following properties: `ca_timeout` **Ruby Type:** Integer | **Default Value:** `0` The continuous availability time-out for the share. `change_users` **Ruby Type:** Array | **Default Value:** `[]` The users that should have ‘modify’ permission on the share in domain\username format. `concurrent_user_limit` **Ruby Type:** Integer | **Default Value:** `0` The maximum number of concurrently connected users the share can accommodate. `continuously_available` **Ruby Type:** true, false | **Default Value:** `false` Indicates that the share is continuously available. `description` **Ruby Type:** String The description to be applied to the share. `encrypt_data` **Ruby Type:** true, false | **Default Value:** `false` Indicates that the share is encrypted. `full_users` **Ruby Type:** Array | **Default Value:** `[]` The users that should have ‘Full control’ permissions on the share in domain\username format. `path` **Ruby Type:** String The path of the folder to share. Required when creating. If the share already exists on a different path then it is deleted and re-created. `read_users` **Ruby Type:** Array | **Default Value:** `[]` The users that should have ‘read’ permission on the share in domain\username format. `scope_name` **Ruby Type:** String | **Default Value:** `*` The scope name of the share. `share_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the share name if it differs from the resource block’s name. `temporary` **Ruby Type:** true, false | **Default Value:** `false` The lifetime of the new SMB share. A temporary share does not persist beyond the next restart of the computer. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_share** resource in recipes: **Create a share**: ``` windows_share 'foo' do action :create path 'C:\foo' full_users ['DOMAIN_A\some_user', 'DOMAIN_B\some_other_user'] read_users ['DOMAIN_C\Domain users'] end ``` **Delete a share**: ``` windows_share 'foo' do action :delete end ``` windows_shortcut resource -------------------------- [windows_shortcut resource page](windows_shortcut/index) --- Use the **windows_shortcut** resource to create shortcut files on Windows. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_shortcut** resource is: ``` windows_shortcut 'name' do arguments String cwd String description String iconlocation String shortcut_name String # default value: 'name' unless specified target String action Symbol # defaults to :create if not specified end ``` where: * `windows_shortcut` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `arguments`, `cwd`, `description`, `iconlocation`, `shortcut_name`, and `target` are the properties available to this resource. ### Actions --- The **windows_shortcut** resource has the following actions: `:create` Create or modify a Windows shortcut. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_shortcut** resource has the following properties: `arguments` **Ruby Type:** String Arguments to pass to the target when the shortcut is executed. `cwd` **Ruby Type:** String Working directory to use when the target is executed. `description` **Ruby Type:** String The description of the shortcut `iconlocation` **Ruby Type:** String Icon to use for the shortcut. Accepts the format of `path, index`, where index is the icon file to use. See Microsoft’s [documentation](https://msdn.microsoft.com/en-us/library/3s9bx7at.aspx) for details `shortcut_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the shortcut name if it differs from the resource block’s name. `target` **Ruby Type:** String The destination that the shortcut links to. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_shortcut** resource in recipes: **Create a shortcut with a description**: ``` windows_shortcut 'C:\shortcut_dir.lnk' do target 'C:\original_dir' description 'Make a shortcut to C:\original_dir' end ``` windows_task resource ---------------------- [windows_task resource page](windows_task/index) --- Use the **windows_task** resource to create, delete or run a Windows scheduled task. **New in Chef Infra Client 13.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_task** resource is: ``` windows_task 'name' do backup Integer, false # default value: 5 command String cwd String day String, Integer description String disallow_start_if_on_batteries true, false # default value: false execution_time_limit String, Integer # default value: "PT72H (72 hours in ISO8601 duration format)" force true, false # default value: false frequency Symbol frequency_modifier Integer, String # default value: 1 idle_time Integer interactive_enabled true, false # default value: false minutes_duration String, Integer minutes_interval String, Integer months String password String priority Integer # default value: 7 random_delay String, Integer run_level Symbol # default value: :limited start_day String # default value: The current date. start_time String start_when_available true, false # default value: false stop_if_going_on_batteries true, false # default value: false task_name String # default value: 'name' unless specified user String # default value: The localized SYSTEM user for the node. action Symbol # defaults to :create if not specified end ``` where: * `windows_task` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `backup`, `command`, `cwd`, `day`, `description`, `disallow_start_if_on_batteries`, `execution_time_limit`, `force`, `frequency`, `frequency_modifier`, `idle_time`, `interactive_enabled`, `minutes_duration`, `minutes_interval`, `months`, `password`, `priority`, `random_delay`, `run_level`, `start_day`, `start_time`, `start_when_available`, `stop_if_going_on_batteries`, `task_name`, and `user` are the properties available to this resource. ### Actions --- The **windows_task** resource has the following actions: `:create` Creates a scheduled task, or updates an existing task if any property has changed. (default) `:delete` Deletes a scheduled task. `:disable` Disables a scheduled task. `:enable` Enables a scheduled task. `:end` Ends a scheduled task. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Runs a scheduled task. ### Properties --- The **windows_task** resource has the following properties: `backup` **Ruby Type:** Integer, false | **Default Value:** `5` Number of backups to keep of the task when modified/deleted. Set to false to disable backups. New in Chef Infra Client 17.0 `command` **Ruby Type:** String The command to be executed by the windows scheduled task. `cwd` **Ruby Type:** String The directory the task will be run from. `day` **Ruby Type:** String, Integer The day(s) on which the task runs. * Use this property when setting `frequency` to `:monthly` or `:weekly`. * Valid values with frequency `:weekly` are `MON`-`SUN` or `*`. * Valid values with frequency `:monthly` are `1-31`, `MON`-`SUN`, and `LASTDAY`. * Use `MON`-`SUN` or `LASTDAY` if you are setting `frequency_modifier` as “FIRST, SECOND, THIRD etc.” else use 1-31. * Multiple days should be comma separated. e.g `1, 2, 3` or `MON, WED, FRI`. `description` **Ruby Type:** String The task description. New in Chef Client 14.7 `disallow_start_if_on_batteries` **Ruby Type:** true, false | **Default Value:** `false` Disallow start of the task if the system is running on battery power. New in Chef Client 14.4 `execution_time_limit` **Ruby Type:** String, Integer | **Default Value:** `PT72H (72 hours in ISO8601 duration format)` The maximum time the task will run. This field accepts either seconds or an ISO8601 duration value. `force` **Ruby Type:** true, false | **Default Value:** `false` When used with create, will update the task. `frequency` **Ruby Type:** Symbol **Allowed Values:** `:daily, :hourly, :minute, :monthly, :none, :on_idle, :on_logon, :once, :onstart, :weekly` The frequency with which to run the task. Note This property is required in Chef Infra Client 14.1 or later. Note The `:once` value requires the `start_time` property to be set. `frequency_modifier` **Ruby Type:** Integer, String | **Default Value:** `1` * For frequency `:minute` valid values are 1 to 1439 * For frequency `:hourly` valid values are 1 to 23 * For frequency `:daily` valid values are 1 to 365 * For frequency `:weekly` valid values are 1 to 52 * For frequency `:monthly` valid values are `('FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST')` OR `1-12`. + e.g. If user want to run the task on `second week of the month` use `frequency_modifier` value as `SECOND`. Multiple values for weeks of the month should be comma separated e.g. `"FIRST, THIRD, LAST"`. + To run task every (n) months use values 1 to 12. `idle_time` **Ruby Type:** Integer For `:on_idle` frequency, the time (in minutes) without user activity that must pass to trigger the task, from `1` - `999`. `interactive_enabled` **Ruby Type:** true, false | **Default Value:** `false` Allow task to run interactively or non-interactively. Requires user and password to also be set. `minutes_duration` **Ruby Type:** String, Integer `minutes_interval` **Ruby Type:** String, Integer `months` **Ruby Type:** String The Months of the year on which the task runs, such as: `JAN, FEB` or `*`. Multiple months should be comma delimited. e.g. `Jan, Feb, Mar, Dec`. `password` **Ruby Type:** String The user’s password. The user property must be set if using this property. `priority` **Ruby Type:** Integer | **Default Value:** `7` Use to set Priority Levels range from 0 to 10. `random_delay` **Ruby Type:** String, Integer Delays the task up to a given time (in seconds). `run_level` **Ruby Type:** Symbol | **Default Value:** `:limited` **Allowed Values:** `:highest, :limited` Run with `:limited` or `:highest` privileges. `start_day` **Ruby Type:** String | **Default Value:** `The current date.` Specifies the first date on which the task runs in **MM/DD/YYYY** format. `start_time` **Ruby Type:** String Specifies the start time to run the task, in **HH:mm** format. `start_when_available` **Ruby Type:** true, false | **Default Value:** `false` To start the task at any time after its scheduled time has passed. New in Chef Client 14.15 `stop_if_going_on_batteries` **Ruby Type:** true, false | **Default Value:** `false` Scheduled task option when system is switching on battery. New in Chef Client 14.4 `task_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the task name if it differs from the resource block’s name. Example: `Task Name` or `/Task Name` `user` **Ruby Type:** String | **Default Value:** `The localized SYSTEM user for the node.` The user to run the task as. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_task** resource in recipes: **Create a scheduled task to run every 15 minutes as the Administrator user**: ``` windows_task 'chef-client' do user 'Administrator' password 'password' command 'chef-client' run_level :highest frequency :minute frequency_modifier 15 end ``` **Create a scheduled task to run every 2 days**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :daily frequency_modifier 2 end ``` **Create a scheduled task to run on specific days of the week**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly day 'Mon, Thu' end ``` **Create a scheduled task to run only once**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :once start_time '16:10' end ``` **Create a scheduled task to run on current day every 3 weeks and delay upto 1 min**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly frequency_modifier 3 random_delay '60' end ``` **Create a scheduled task to run weekly starting on Dec 28th 2018**: ``` windows_task 'chef-client 8' do command 'chef-client' run_level :highest frequency :weekly start_day '12/28/2018' end ``` **Create a scheduled task to run every Monday, Friday every 2 weeks**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly frequency_modifier 2 day 'Mon, Fri' end ``` **Create a scheduled task to run when computer is idle with idle duration 20 min**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :on_idle idle_time 20 end ``` **Delete a task named “old task”**: ``` windows_task 'old task' do action :delete end ``` **Enable a task named “chef-client”**: ``` windows_task 'chef-client' do action :enable end ``` **Disable a task named “ProgramDataUpdater” with TaskPath “\Microsoft\Windows\Application Experience\ProgramDataUpdater”** ``` windows_task '\Microsoft\Windows\Application Experience\ProgramDataUpdater' do action :disable end ``` windows_uac resource --------------------- [windows_uac resource page](windows_uac/index) --- The *windows_uac* resource configures UAC on Windows hosts by setting registry keys at `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System` **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_uac** resource is: ``` windows_uac 'name' do consent_behavior_admins Symbol # default value: :prompt_for_consent_non_windows_binaries consent_behavior_users Symbol # default value: :prompt_for_creds detect_installers true, false enable_uac true, false # default value: true prompt_on_secure_desktop true, false # default value: true require_signed_binaries true, false # default value: false action Symbol # defaults to :configure if not specified end ``` where: * `windows_uac` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `consent_behavior_admins`, `consent_behavior_users`, `detect_installers`, `enable_uac`, `prompt_on_secure_desktop`, and `require_signed_binaries` are the properties available to this resource. ### Actions --- The **windows_uac** resource has the following actions: `:configure` Configures UAC by setting registry keys at `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System`. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_uac** resource has the following properties: `consent_behavior_admins` **Ruby Type:** Symbol | **Default Value:** `:prompt_for_consent_non_windows_binaries` **Allowed Values:** `:no_prompt, :prompt_for_consent, :prompt_for_consent_non_windows_binaries, :prompt_for_creds, :secure_prompt_for_consent, :secure_prompt_for_creds` Behavior of the elevation prompt for administrators in Admin Approval Mode. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ConsentPromptBehaviorAdmin. `consent_behavior_users` **Ruby Type:** Symbol | **Default Value:** `:prompt_for_creds` **Allowed Values:** `:auto_deny, :prompt_for_creds, :secure_prompt_for_creds` Behavior of the elevation prompt for standard users. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ConsentPromptBehaviorUser. `detect_installers` **Ruby Type:** true, false Detect application installations and prompt for elevation. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\EnableInstallerDetection. `enable_uac` **Ruby Type:** true, false | **Default Value:** `true` Enable or disable UAC Admin Approval Mode. If this is changed a system restart is required. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA. `prompt_on_secure_desktop` **Ruby Type:** true, false | **Default Value:** `true` Switch to the secure desktop when prompting for elevation. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\PromptOnSecureDesktop. `require_signed_binaries` **Ruby Type:** true, false | **Default Value:** `false` Only elevate executables that are signed and validated. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ValidateAdminCodeSignatures. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_uac** resource in recipes: **Disable UAC prompts for the admin**: ``` windows_uac 'Disable UAC prompts for the admin' do enable_uac true prompt_on_secure_desktop false consent_behavior_admins :no_prompt end ``` **Disable UAC entirely**: ``` windows_uac 'Disable UAC entirely' do enable_uac false end ``` windows_update_settings resource ---------------------------------- [windows_update_settings resource page](windows_update_settings/index) --- Use the **windows_update_settings** resource to manage the various Windows Update patching options. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_update_settings** resource is: ``` windows_update_settings 'name' do automatic_update_option Integer, Symbol # default value: :download_and_schedule automatically_install_minor_updates true, false # default value: false block_windows_update_website true, false # default value: false custom_detection_frequency Integer # default value: 22 disable_automatic_updates true, false # default value: false disable_os_upgrades true, false # default value: false elevate_non_admins true, false # default value: true enable_detection_frequency true, false # default value: false no_reboot_with_users_logged_on true, false # default value: true scheduled_install_day String # default value: "Everyday" scheduled_install_hour Integer target_wsus_group_name String update_other_ms_products true, false # default value: true wsus_server_url String action Symbol # defaults to :set if not specified end ``` where: * `windows_update_settings` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `automatic_update_option`, `automatically_install_minor_updates`, `block_windows_update_website`, `custom_detection_frequency`, `disable_automatic_updates`, `disable_os_upgrades`, `elevate_non_admins`, `enable_detection_frequency`, `no_reboot_with_users_logged_on`, `scheduled_install_day`, `scheduled_install_hour`, `target_wsus_group_name`, `update_other_ms_products`, and `wsus_server_url` are the properties available to this resource. ### Actions --- The **windows_update_settings** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set Windows Update settings. (default) ### Properties --- The **windows_update_settings** resource has the following properties: `automatic_update_option` **Ruby Type:** Integer, Symbol | **Default Value:** `:download_and_schedule` **Allowed Values:** `:download_and_notify, :download_and_schedule, :local_admin_decides, :notify` Control what to do when updates are found. This allows you to notify, automatically download and notify to install, automatically download and schedule the install, or let the local admin decide what action to take. `automatically_install_minor_updates` **Ruby Type:** true, false | **Default Value:** `false` Automatically install minor updates. `block_windows_update_website` **Ruby Type:** true, false | **Default Value:** `false` Block accessing the Windows Update website. `custom_detection_frequency` **Ruby Type:** Integer | **Default Value:** `22` If you decided to override the OS default detection frequency, specify your choice here. Valid choices are 0 - 22 `disable_automatic_updates` **Ruby Type:** true, false | **Default Value:** `false` Disable Windows Update. `disable_os_upgrades` **Ruby Type:** true, false | **Default Value:** `false` Disable OS upgrades. `elevate_non_admins` **Ruby Type:** true, false | **Default Value:** `true` Allow normal user accounts to temporarily be elevated to install patches. `enable_detection_frequency` **Ruby Type:** true, false | **Default Value:** `false` Used to override the OS default of how often to check for updates `no_reboot_with_users_logged_on` **Ruby Type:** true, false | **Default Value:** `true` Prevents the OS from rebooting while someone is on the console. `scheduled_install_day` **Ruby Type:** String | **Default Value:** `Everyday` **Allowed Values:** `"Everyday", "Friday", "Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday"` A day of the week to tell Windows when to install updates. `scheduled_install_hour` **Ruby Type:** Integer If you chose a scheduled day to install, then choose an hour on that day for you installation `target_wsus_group_name` **Ruby Type:** String Add the node to a WSUS Target Group. `update_other_ms_products` **Ruby Type:** true, false | **Default Value:** `true` Allows for other Microsoft products to get updates too `wsus_server_url` **Ruby Type:** String The URL of your WSUS server if you use one. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_update_settings** resource in recipes: **Set Windows Update settings**: ``` windows_update_settings 'Settings to Configure Windows Nodes to automatically receive updates' do disable_os_upgrades true elevate_non_admins true block_windows_update_website true automatically_install_minor_updates true scheduled_install_day 'Friday' scheduled_install_hour 18 update_other_ms_products true action :enable end ``` windows_user_privilege resource --------------------------------- [windows_user_privilege resource page](windows_user_privilege/index) --- The windows_user_privilege resource allows to add and set principal (User/Group) to the specified privilege. Ref: <https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/user-rights-assignment **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_user_privilege** resource is: ``` windows_user_privilege 'name' do principal String # default value: 'name' unless specified privilege Array, String users Array, String action Symbol # defaults to :add if not specified end ``` where: * `windows_user_privilege` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `principal`, `privilege`, and `users` are the properties available to this resource. ### Actions --- The **windows_user_privilege** resource has the following actions: `:add` Add a user privilege. (default) `:clear` Clear all user privileges `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a user privilege `:set` Set the privileges that are listed in the `privilege` property for only the users listed in the `users` property. ### Properties --- The **windows_user_privilege** resource has the following properties: `principal` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to add the user to the given privilege. Use only with add and remove action. `privilege` **Ruby Type:** Array, String | `REQUIRED` One or more privileges to set for users. `users` **Ruby Type:** Array, String An optional property to set the privilege for given users. Use only with set action. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_user_privilege** resource in recipes: **Set the SeNetworkLogonRight Privilege for the Builtin Administrators Group and Authenticated Users**: ``` windows_user_privilege 'Network Logon Rights' do privilege 'SeNetworkLogonRight' users ['BUILTIN\Administrators', 'NT AUTHORITY\Authenticated Users'] action :set end ``` **Add the SeDenyRemoteInteractiveLogonRight Privilege to the Builtin Guests and Local Accounts User Groups**: ``` windows_user_privilege 'Remote interactive logon' do privilege 'SeDenyRemoteInteractiveLogonRight' users ['Builtin\Guests', 'NT AUTHORITY\Local Account'] action :add end ``` **Provide only the Builtin Guests and Administrator Groups with the SeCreatePageFile Privilege**: ``` windows_user_privilege 'Create Pagefile' do privilege 'SeCreatePagefilePrivilege' users ['BUILTIN\Guests', 'BUILTIN\Administrators'] action :set end ``` **Remove the SeCreatePageFile Privilege from the Builtin Guests Group**: ``` windows_user_privilege 'Create Pagefile' do privilege 'SeCreatePagefilePrivilege' users ['BUILTIN\Guests'] action :remove end ``` **Clear all users from the SeDenyNetworkLogonRight Privilege**: ``` windows_user_privilege 'Allow any user the Network Logon right' do privilege 'SeDenyNetworkLogonRight' action :clear end ``` windows_workgroup resource --------------------------- [windows_workgroup resource page](windows_workgroup/index) --- Use the **windows_workgroup** resource to join or change the workgroup of a Windows host. **New in Chef Infra Client 14.5.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_workgroup** resource is: ``` windows_workgroup 'name' do password String reboot Symbol # default value: :immediate user String workgroup_name String # default value: 'name' unless specified action Symbol # defaults to :join if not specified end ``` where: * `windows_workgroup` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `password`, `reboot`, `user`, and `workgroup_name` are the properties available to this resource. ### Actions --- The **windows_workgroup** resource has the following actions: `:join` Update the workgroup. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_workgroup** resource has the following properties: `password` **Ruby Type:** String The password for the local administrator user. Required if using the `user` property. `reboot` **Ruby Type:** Symbol | **Default Value:** `:immediate` **Allowed Values:** `:never, :reboot_now, :request_reboot` Controls the system reboot behavior post workgroup joining. Reboot immediately, after the Chef Infra Client run completes, or never. Note that a reboot is necessary for changes to take effect. `user` **Ruby Type:** String The local administrator user to use to change the workgroup. Required if using the `password` property. `workgroup_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the workgroup name if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_workgroup** resource in recipes: **Join a workgroup**: ``` windows_workgroup 'myworkgroup' ``` **Join a workgroup using a specific user**: ``` windows_workgroup 'myworkgroup' do user 'Administrator' password 'passw0rd' end ``` yum_package resource --------------------- [yum_package resource page](yum_package/index) --- Use the **yum_package** resource to install, upgrade, and remove packages with Yum for the Red Hat and CentOS platforms. The yum_package resource is able to resolve `provides` data for packages much like Yum can do when it is run from the command line. This allows a variety of options for installing packages, like minimum versions, virtual provides, and library names. Note Support for using file names to install packages (as in `yum_package '/bin/sh'`) is not available because the volume of data required to parse for this is excessive. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- The full syntax for all of the properties that are available to the **yum_package** resource is: ``` yum_package 'name' do allow_downgrade true, false # default value: true arch String, Array flush_cache Hash # default value: {"before"=>false, "after"=>false} options String, Array package_name String, Array source String timeout String, Integer version String, Array yum_binary String action Symbol # defaults to :install if not specified end ``` where: * `yum_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `arch`, `flush_cache`, `options`, `package_name`, `source`, `timeout`, `version`, and `yum_binary` are the properties available to this resource. ### Actions --- The **yum_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:lock` Locks the yum package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:unlock` Unlocks the yum package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. This action will ignore the `version` attribute. ### Properties --- The **yum_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. `arch` **Ruby Type:** String, Array The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name. `flush_cache` **Ruby Type:** Hash | **Default Value:** `{"before"=>false, "after"=>false}` Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Accepts a Hash in the form: { :before => true/false, :after => true/false } or an Array in the form [ :before, :after ]. Yum automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while the Chef Infra Client run is in-progress. As an array: ``` yum_package 'some-package' do #... flush_cache [ :before ] #... end ``` and as a Hash: ``` yum_package 'some-package' do #... flush_cache( { :after => true } ) #... end ``` Note The `flush_cache` property does not flush the local Yum cache! Use Yum tools—`yum clean headers`, `yum clean packages`, `yum clean all`—to clean the local Yum cache. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array One of the following: the name of a package, the name of a package and its architecture, the name of a dependency. Default value: the `name` of the resource block. See “Syntax” section above for more information. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. This property is ignored when using the `:upgrade` action. `yum_binary` **Ruby Type:** String The path to the yum binary. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **yum_package** resource in recipes: **Install an exact version**: ``` yum_package 'netpbm = 10.35.58-8.el8' ``` **Install a minimum version**: ``` yum_package 'netpbm >= 10.35.58-8.el8' ``` **Install a minimum version using the default action**: ``` yum_package 'netpbm' ``` **Install a version without worrying about the exact release**: ``` yum_package 'netpbm-10.35*' ``` **To install a package**: ``` yum_package 'netpbm' do action :install end ``` **To install a partial minimum version**: ``` yum_package 'netpbm >= 10' ``` **To install a specific architecture**: ``` yum_package 'netpbm' do arch 'i386' end ``` or: ``` yum_package 'netpbm.x86_64' ``` **To install a specific version-release** ``` yum_package 'netpbm' do version '10.35.58-8.el8' end ``` **Handle cookbook_file and yum_package resources in the same recipe**: When a **cookbook_file** resource and a **yum_package** resource are both called from within the same recipe, use the `flush_cache` attribute to dump the in-memory Yum cache, and then use the repository immediately to ensure that the correct package is installed: ``` cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' end yum_package 'pkg-that-is-only-in-custom-repo' do action :install flush_cache [ :before ] end ``` yum_repository resource ------------------------ [yum_repository resource page](yum_repository/index) --- Use the **yum_repository** resource to manage a Yum repository configuration file located at `/etc/yum.repos.d/repositoryid.repo` on the local machine. This configuration file specifies which repositories to reference, how to handle cached data, etc. **New in Chef Infra Client 12.14.** ### Syntax --- The full syntax for all of the properties that are available to the **yum_repository** resource is: ``` yum_repository 'name' do baseurl String, Array clean_metadata true, false # default value: true cost String description String # default value: "Yum Repository" enabled true, false # default value: true enablegroups true, false exclude String failovermethod String fastestmirror_enabled true, false gpgcheck true, false # default value: true gpgkey String, Array http_caching String include_config String includepkgs String keepalive true, false make_cache true, false # default value: true max_retries String, Integer metadata_expire String metalink String mirror_expire String mirrorlist String mirrorlist_expire String mode String, Integer # default value: "0644" options Hash password String priority String proxy String proxy_password String proxy_username String repo_gpgcheck true, false report_instanceid true, false reposdir String # default value: "/etc/yum.repos.d/" repositoryid String # default value: 'name' unless specified skip_if_unavailable true, false source String sslcacert String sslclientcert String sslclientkey String sslverify true, false throttle String, Integer timeout String username String action Symbol # defaults to :create if not specified end ``` where: * `yum_repository` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `baseurl`, `clean_metadata`, `cost`, `description`, `enabled`, `enablegroups`, `exclude`, `failovermethod`, `fastestmirror_enabled`, `gpgcheck`, `gpgkey`, `http_caching`, `include_config`, `includepkgs`, `keepalive`, `make_cache`, `max_retries`, `metadata_expire`, `metalink`, `mirror_expire`, `mirrorlist`, `mirrorlist_expire`, `mode`, `options`, `password`, `priority`, `proxy`, `proxy_password`, `proxy_username`, `repo_gpgcheck`, `report_instanceid`, `reposdir`, `repositoryid`, `skip_if_unavailable`, `source`, `sslcacert`, `sslclientcert`, `sslclientkey`, `sslverify`, `throttle`, `timeout`, and `username` are the properties available to this resource. ### Actions --- The **yum_repository** resource has the following actions: `:create` Create a repository based on the properties. (default) `:delete` Remove a repository. `:makecache` Force the creation of the repository cache. This is also done automatically when a repository is updated. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **yum_repository** resource has the following properties: `baseurl` **Ruby Type:** String, Array URL to the directory where the Yum repository’s `repodata` directory lives. Can be an `http://`, `https://` or a `ftp://` URLs. You can specify multiple URLs in one `baseurl` statement. `clean_metadata` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether you want to purge all of the packages downloaded from a Yum repository and held in a cache directory. `cost` **Ruby Type:** String Relative cost of accessing this repository. Useful for weighing one repo’s packages as greater/less than any other. `description` **Ruby Type:** String | **Default Value:** `Yum Repository` Descriptive name for the repository channel and maps to the ‘name’ parameter in a repository .conf. `enabled` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether or not Yum should use this repository. `enablegroups` **Ruby Type:** true, false Specifies whether Yum will allow the use of package groups for this repository. `exclude` **Ruby Type:** String List of packages to exclude from updates or installs. This should be a space separated list. Shell globs using wildcards (eg. * and ?) are allowed. `failovermethod` **Ruby Type:** String **Allowed Values:** `"priority", "roundrobin"` Method to determine how to switch to a new server if the current one fails, which can either be `roundrobin` or `priority`. `roundrobin` randomly selects a URL out of the list of URLs to start with and proceeds through each of them as it encounters a failure contacting the host. `priority` starts from the first `baseurl` listed and reads through them sequentially. `fastestmirror_enabled` **Ruby Type:** true, false Specifies whether to use the fastest mirror from a repository configuration when more than one mirror is listed in that configuration. `gpgcheck` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether or not Yum should perform a GPG signature check on the packages received from a repository. `gpgkey` **Ruby Type:** String, Array URL pointing to the ASCII-armored GPG key file for the repository. This is used if Yum needs a public key to verify a package and the required key hasn’t been imported into the RPM database. If this option is set, Yum will automatically import the key from the specified URL. Multiple URLs may be specified in the same manner as the baseurl option. If a GPG key is required to install a package from a repository, all keys specified for that repository will be installed. Multiple URLs may be specified in the same manner as the baseurl option. If a GPG key is required to install a package from a repository, all keys specified for that repository will be installed. `http_caching` **Ruby Type:** String **Allowed Values:** `"all", "none", "packages"` Determines how upstream HTTP caches are instructed to handle any HTTP downloads that Yum does. This option can take the following values: * `all` means all HTTP downloads should be cached * `packages` means only RPM package downloads should be cached, but not repository metadata downloads * `none` means no HTTP downloads should be cached. The default value of `all` is recommended unless you are experiencing caching related issues. `include_config` **Ruby Type:** String An external configuration file using the format `url://to/some/location`. `includepkgs` **Ruby Type:** String Inverse of exclude property. This is a list of packages you want to use from a repository. If this option lists only one package then that is all Yum will ever see from the repository. `keepalive` **Ruby Type:** true, false Determines whether or not HTTP/1.1 `keep-alive` should be used with this repository. `make_cache` **Ruby Type:** true, false | **Default Value:** `true` Determines whether package files downloaded by Yum stay in cache directories. By using cached data, you can carry out certain operations without a network connection. `max_retries` **Ruby Type:** String, Integer Number of times any attempt to retrieve a file should retry before returning an error. Setting this to `0` makes Yum try forever. `metadata_expire` **Ruby Type:** String Time (in seconds) after which the metadata will expire. If the current metadata downloaded is less than the value specified, then Yum will not update the metadata against the repository. If you find that Yum is not downloading information on updates as often as you would like lower the value of this option. You can also change from the default of using seconds to using days, hours or minutes by appending a `d`, `h` or `m` respectively. The default is six hours to compliment yum-updates running once per hour. It is also possible to use the word `never`, meaning that the metadata will never expire. Note When using a metalink file, the metalink must always be newer than the metadata for the repository due to the validation, so this timeout also applies to the metalink file. `metalink` **Ruby Type:** String Specifies a URL to a metalink file for the repomd.xml, a list of mirrors for the entire repository are generated by converting the mirrors for the repomd.xml file to a baseurl. `mirror_expire` **Ruby Type:** String Time (in seconds) after which the mirrorlist locally cached will expire. If the current mirrorlist is less than this many seconds old then Yum will not download another copy of the mirrorlist, it has the same extra format as metadata_expire. If you find that Yum is not downloading the mirrorlists as often as you would like lower the value of this option. You can also change from the default of using seconds to using days, hours or minutes by appending a `d`, `h` or `m` respectively. `mirrorlist` **Ruby Type:** String URL to a file containing a list of baseurls. This can be used instead of or with the baseurl option. Substitution variables, described below, can be used with this option. `mirrorlist_expire` **Ruby Type:** String Specifies the time (in seconds) after which the mirrorlist locally cached will expire. If the current mirrorlist is less than the value specified, then Yum will not download another copy of the mirrorlist. You can also change from the default of using seconds to using days, hours or minutes by appending a `d`, `h` or `m` respectively. `mode` **Ruby Type:** String, Integer | **Default Value:** `0644` Permissions mode of .repo file on disk. This is useful for scenarios where secrets are in the repo file. If this value is set to `600`, normal users will not be able to use Yum search, Yum info, etc. `options` **Ruby Type:** Hash Specifies the repository options. `password` **Ruby Type:** String Password to use with the username for basic authentication. `priority` **Ruby Type:** String Assigns a priority to a repository where the priority value is between `1` and `99` inclusive. Priorities are used to enforce ordered protection of repositories. Packages from repositories with a lower priority (higher numerical value) will never be used to upgrade packages that were installed from a repository with a higher priority (lower numerical value). The repositories with the lowest numerical priority number have the highest priority. `proxy` **Ruby Type:** String URL to the proxy server that Yum should use. `proxy_password` **Ruby Type:** String Password for this proxy. `proxy_username` **Ruby Type:** String Username to use for proxy. `repo_gpgcheck` **Ruby Type:** true, false Determines whether or not Yum should perform a GPG signature check on the repodata from this repository. `report_instanceid` **Ruby Type:** true, false Determines whether to report the instance ID when using Amazon Linux AMIs and repositories. `reposdir` **Ruby Type:** String | **Default Value:** `/etc/yum.repos.d/` The directory where the Yum repository files should be stored New in Chef Infra Client 16.9 `repositoryid` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the repository name if it differs from the resource block’s name. `skip_if_unavailable` **Ruby Type:** true, false Allow yum to continue if this repository cannot be contacted for any reason. `source` **Ruby Type:** String Use a custom template source instead of the default one. `sslcacert` **Ruby Type:** String Path to the directory containing the databases of the certificate authorities Yum should use to verify SSL certificates. `sslclientcert` **Ruby Type:** String Path to the SSL client certificate Yum should use to connect to repos/remote sites. `sslclientkey` **Ruby Type:** String Path to the SSL client key Yum should use to connect to repos/remote sites. `sslverify` **Ruby Type:** true, false Determines whether Yum will verify SSL certificates/hosts. `throttle` **Ruby Type:** String, Integer Enable bandwidth throttling for downloads. `timeout` **Ruby Type:** String Number of seconds to wait for a connection before timing out. Defaults to 30 seconds. This may be too short of a time for extremely overloaded sites. `username` **Ruby Type:** String Username to use for basic authentication to a repository. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **yum_repository** resource in recipes: **Add an internal company repository**: ``` yum_repository 'OurCo' do description 'OurCo yum repository' mirrorlist 'http://artifacts.ourco.org/mirrorlist?repo=ourco-8&arch=$basearch' gpgkey 'http://artifacts.ourco.org/<KEY>' action :create end ``` **Delete a repository**: ``` yum_repository 'CentOS-Media' do action :delete end ``` zypper_package resource ------------------------ [zypper_package resource page](zypper_package/index) --- Use the **zypper_package** resource to install, upgrade, and remove packages with Zypper for the SUSE Enterprise and openSUSE platforms. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- The full syntax for all of the properties that are available to the **zypper_package** resource is: ``` zypper_package 'name' do allow_downgrade true, false # default value: true global_options String, Array gpg_check true, false # default value: "true" options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `zypper_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `global_options`, `gpg_check`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **zypper_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:lock` Locks the zypper package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:unlock` Unlocks the zypper package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **zypper_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. New in Chef Client 13.6 `global_options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. For example, common zypper directives, such as `--no-recommends`. See the [zypper man page](https://en.opensuse.org/SDB:Zypper_manual_(plain)) for the full list. New in Chef Client 14.6 `gpg_check` **Ruby Type:** true, false | **Default Value:** `true` Verify the package’s GPG signature. Can also be controlled site-wide using the `zypper_check_gpg` config option. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **zypper_package** resource in recipes: **Install a package using package manager:** ``` zypper_package 'name of package' do action :install end ``` **Install a package using local file:** ``` zypper_package 'jwhois' do action :install source '/path/to/jwhois.rpm' end ``` **Install without using recommend packages as a dependency:** ``` package 'apache2' do options '--no-recommends' end ``` zypper_repository resource --------------------------- [zypper_repository resource page](zypper_repository/index) --- Use the **zypper_repository** resource to create Zypper package repositories on SUSE Enterprise Linux and openSUSE systems. This resource maintains full compatibility with the **zypper_repository** resource in the existing **zypper** cookbook. **New in Chef Infra Client 13.3.** ### Syntax --- The full syntax for all of the properties that are available to the **zypper_repository** resource is: ``` zypper_repository 'name' do autorefresh true, false # default value: true baseurl String cookbook String # default value: "The cookbook containing the resource" description String enabled true, false # default value: true gpgautoimportkeys true, false # default value: true gpgcheck true, false # default value: true gpgkey String, Array # default value: [] keeppackages true, false # default value: false mirrorlist String mode String, Integer # default value: "0644" path String priority Integer # default value: 99 refresh_cache true, false # default value: true repo_name String # default value: 'name' unless specified source String type String # default value: "NONE" action Symbol # defaults to :create if not specified end ``` where: * `zypper_repository` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `autorefresh`, `baseurl`, `cookbook`, `description`, `enabled`, `gpgautoimportkeys`, `gpgcheck`, `gpgkey`, `keeppackages`, `mirrorlist`, `mode`, `path`, `priority`, `refresh_cache`, `repo_name`, `source`, and `type` are the properties available to this resource. ### Actions --- The **zypper_repository** resource has the following actions: `:create` Add a new Zypper repository. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:refresh` Refresh Zypper repository. `:remove` Remove a Zypper repository. ### Properties --- The **zypper_repository** resource has the following properties: `autorefresh` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the repository should be refreshed automatically. `baseurl` **Ruby Type:** String The base URL for the Zypper repository, such as `http://download.opensuse.org`. `cookbook` **Ruby Type:** String | **Default Value:** `The cookbook containing the resource` The cookbook to source the repository template file from. Only necessary if you’re using a custom template for the repository file. `description` **Ruby Type:** String The description of the repository that will be shown by the `zypper repos` command. `enabled` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the repository should be enabled. `gpgautoimportkeys` **Ruby Type:** true, false | **Default Value:** `true` Automatically import the specified key when setting up the repository. `gpgcheck` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not to perform a GPG signature check on the repository. `gpgkey` **Ruby Type:** String, Array | **Default Value:** `[]` The location of the repository key(s) to be imported. `keeppackages` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not packages should be saved. `mirrorlist` **Ruby Type:** String The URL of the mirror list that will be used. `mode` **Ruby Type:** String, Integer | **Default Value:** `0644` The file mode of the repository file. `path` **Ruby Type:** String The relative path from the repository’s base URL. `priority` **Ruby Type:** Integer | **Default Value:** `99` Determines the priority of the Zypper repository. `refresh_cache` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the package cache should be refreshed. `repo_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the repository name if it differs from the resource block’s name. `source` **Ruby Type:** String The name of the template for the repository file. Only necessary if you’re using a custom template for the repository file. `type` **Ruby Type:** String | **Default Value:** `NONE` Specifies the repository type. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **zypper_repository** resource in recipes: **Add the Apache repo on openSUSE Leap 15**: ``` zypper_repository 'apache' do baseurl 'http://download.opensuse.org/repositories/Apache' path '/openSUSE_Leap_15.2' type 'rpm-md' priority '100' end ``` **Remove the repo named ‘apache’**: ``` zypper_repository 'apache' do action :delete end ``` **Refresh the repo named ‘apache’**: ``` zypper_repository 'apache' do action :refresh end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/About Chef InSpec and Train Plugins =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/plugins.md) What are Chef InSpec Plugins? ----------------------------- Chef InSpec Plugins are optional software components that extend the capabilities of InSpec. For example, [`inspec-iggy`](https://github.com/inspec/inspec-iggy) is a Plugin project that aims to generate Chef InSpec controls from infrastructure-as-code files. Plugins are distributed as RubyGems, and Chef InSpec manages their installation. Chef InSpec Plugins always begin with the prefix ‘inspec-’. What are Train Plugins? ----------------------- Train Plugins allow Chef InSpec to speak to new kinds of targets (typically new remote targets or APIs, but you could treat the local system in a new way if you wished to). For example, if you wanted to audit a Kubernetes cluster, you might want a transport that can talk to the supervisor API. You would develop a Train Plugin for that, and install it using the Chef InSpec command line. Train Plugins always begin with the prefix ‘train-’. What can plugins do? -------------------- Currently, each plugin can offer one or more of these capabilities: * define new output formats (“reporters”) * input sources * define a new command-line-interface (CLI) command suite (`inspec` plugins) * connectivity to new types of hosts or cloud providers (`train` plugins) * DSL extensions at the file, control, describe block, or test level * DSL extensions for custom resources How do I find out which plugins are available? ---------------------------------------------- The Chef InSpec CLI can tell you which plugins are available: ``` inspec plugin search inspec- ``` How do I install and manage plugins? ------------------------------------ The Chef InSpec command line now offers a new subcommand just for managing plugins. You can install a plugin by running: ``` inspec plugin install inspec-some-plugin inspec plugin install train-some-plugin ``` For more details on what the `plugin` command can do, run `inspec plugin help`. How do I use a different Gem server? ------------------------------------ You can specify an alternate source by passing the base of your Gem repository to the `--source` parameter: ``` inspec plugin search --source https://my.private.server inspec-private inspec plugin install --source https://my.private.server inspec-private-plugin ``` How do I write a plugin? ------------------------ ### Chef InSpec Plugins For details on how to author a Chef InSpec Plugin, see the [developer documentation](https://github.com/inspec/inspec/blob/main/dev-docs/plugins.md) ### Train Plugins For details on how to author a Train Plugin, see the [developer documentation](https://github.com/inspec/train/blob/main/docs/plugins.md) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/plugins/Chef InSpec Inputs ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/inputs.md) What are Inputs? ---------------- Inputs are the “knobs” you can use to customize the behavior of Chef InSpec profiles. If a profile supports inputs, you can set the inputs in a variety of ways, allowing flexibility. Profiles that include other profiles can set inputs in the included profile, enabling a multi-layered approach to configuring profiles. ### A Simple Example Suppose you have a profile named `rock_critic`. In its profile metadata file (inspec.yml): ``` # Optionally declare inputs in the profile metadata# This lets you set up things like type checking, etc.inputs:- name:amplifier_max_volumedescription:How loud the amplifiers can gotype:numeric# More options, including value: and priority: are possible here ``` In the profile’s control code: ``` # Set a default value for an input. This is optional. input('amplifier_max_volume', value: 10) control 'Big Rock Show' do describe input('amplifier_max_volume') do # This line reads the value of the input it { should cmp 11 } # The UK'S LOUDEST BAND end end ``` When the above profile is executed by using `inspec exec rock_critic`, you would see something like: ``` × Big Rock Show: 10 × 10 is expected to cmp == 11 expected: 11 got: 10 (compared using `cmp` matcher) Profile Summary: 0 successful controls, 1 control failure, 0 controls skipped ``` That result clearly won’t do. Let’s override the input’s default value. We can now run that profile with `inspec exec rock_critic --input amplifier_max_volume=11`: ``` ✔ Big Rock Show: 11 ✔ 11 is expected to cmp == 11 Profile Summary: 1 successful control, 0 control failures, 0 controls skipped ``` ### Which profiles support inputs? The best way for a profile to indicate it supports inputs is to list them in the metadata file, `inspec.yml`. Any profile that has an `inputs` (or the deprecated `attributes`) section in its `inspec.yml` metadata file is [configuring](#configuring-inputs-in-profile-metadata) inputs. That said, any profile that uses the DSL keyword `input()` (or the deprecated `attribute()`) in the control source code supports inputs. These profiles are *reading* (and possibly setting) input values and using them to make decisions. ### How can I set Inputs? As installed (without specialized plugins), Chef InSpec supports several ways of setting inputs: * Inline in control code, using `input('input_name', value: 42)`. * In profile `inspec.yml` metadata files * Using the CLI option `--input name1=value1 name2=value2...` to read directly from the command line * Using the CLI option `--input-file somefile.yaml` to read inputs from files * In kitchen-inspec, using the `verifier/inputs` settings In addition, Chef InSpec supports Input Plugins, which can provide optional integrations to specific key-value stores. ### How does Input precedence work? #### Simple Precedence Briefly: inline DSL < metadata < ( cli-input-file or kitchen-inspec ) < cli –input In addition, for inherited profiles: dependent profile metadata < wrapper profile metadata This precedence lets you override input values on the command line, as well as override child profile inline values from the parent profile. This description matches the general behavior of InSpec v3, while also making some edge cases easier to reason. #### The Details of Input Precedence Whenever an input provider sets a value on an input, a *priority value* is assigned to the operation. Over the life of the input, multiple assignments with varying priority values may occur. When the input is evaluated, the current value is determined by finding the setting event with the highest priority. Note that this approach does not rely on execution order, nor does it rely on multiple named precedence levels. Each setting operation is preserved and this allows the user to [debug](#debugging-inputs-with-the-event-log) the history of the input values. Some input providers allow you to set a priority when you set the value. For example, to set a priority of 50 in a metadata file, use: ``` inputs:- name:very_important_inputvalue:12priority:50 ``` To set a priority in DSL, use: ``` input('also_important', value: 42, priority: 45) ``` As packaged, Chef InSpec uses the following priority values: | Input Provider | Priority | May change priority | | --- | --- | --- | | Inline DSL | 20 | Yes | | Metadata | 30 | Yes | | Metadata in a wrapper cookbook | 35 | Yes | | CLI `--input-file` option | 40 | No | | inspec-kitchen `inputs:` section | 40 | No | | CLI `--input` option | 50 | No | ### What happened to “Attributes”? When originally introduced, the Input facility was named *Attributes*. This name was problematic, because: * The Chef Infra tool uses the same word to describe its parameterization system. * Chef Infra attributes have a completely different and much more complex precedence system. * This caused confusion about passing Chef Infra attributes into InSpec when using Audit Cookbook and kitchen-inspec. Based on these concerns, InSpec attributes have been renamed to InSpec inputs in Chef InSpec v4. Support for using the DSL keyword `attribute()`, the metadata field `attributes:`, and the corresponding kitchen-inspec and audit cookbook values are anticipated to continue through Chef InSpec v5. Working with Inputs in Control Code ----------------------------------- ### Input Scope Inputs are available throughout the InSpec profile DSL. You can use them anywhere. ``` # some_controls.rb input('outer_input', value: 1) # here control 'control-1' do input('control_dsl_input', value: 2) # here too describe some_resource do input('test_dsl_input', value: 3) # even here it { should cmp input('expectation_dsl_input') } # and yes here too end end ``` ### Setting Inputs in Control DSL When you write `input('some_name', value: 'some_value')`, you are *setting* an input value in the DSL. Because the `value:` option is present, a new value will be set. You may also pass any other option listed in the [input option reference](#input-options-reference). ### Reading Inputs in Control DSL When you call `input('some_name')`, with or without additional options, the value of the input will be resolved and returned. Note that this process may involve sourcing the value from another provider, using the value set in DSL, or overriding the value provided in the same call. ``` # You can use the value in a Ruby variable some_var = input('some_input_name') # Or more directly in a resource parameter describe file(input('important_path')) do it { should exist } end # Or as the resource itself (this could be a string, here) describe input('some_setting') do it { should cmp 'correct_value' } end # Or as the expected value describe file('/etc/httpd/httpd.conf') do its('owner') { should_not cmp input('webserver_user') } end ``` The value returned can be used anywhere a Ruby value is used. Configuring Inputs in Profile Metadata -------------------------------------- Each Chef InSpec profile has a metadata file at the top level named `inspec.yml`. In that file, you may add a section for inputs. You may define inputs there, clearly setting options including values, type checking, and whether the input is required. ``` name:my_profileinputs:- name:webserver_user # Name is the only required field- name:favorite_fruitvalue:banana # You can set a value; priority is 30 for metadata- name:meaning_of_lifetype:Numericvalue:42required:truepriority:70sensitive:true ``` All [input options](#input-options-reference) are supported in metadata files. There are two major advantages to defining inputs in profile metadata: 1. The inputs and their configuration are listed explicitly in simple YAML in one place - a consumer of your profile does not need to read through the control code to find the inputs. 2. You can set inputs in other profiles that you depend on using profile inheritance. ### Using inputs with Profile inheritance When your profile relies on another profile using the `depends` key in the metadata file, you can set — that is, override — the value of the input in the dependent profile by including the `profile` option and naming the dependent profile. ``` # child inspec.ymlname:childinputs:- name:favorite_foodvalue:pizza ``` ``` # wrapper inspec.ymlname:wrapperdepends:- name:childpath:../childinputs:- name:favorite_foodvalue:broccoliprofile:child # <----- REQUIRED to override the value in InSpec 4 ``` In Chef InSpec 4+, every input is namespaced. For example, you could have an input named `wrapper/favorite_food` and one named `child/favorite_food`. If no explicit profile option is set within the `wrapper` profile metadata file, then `wrapper` is assumed to be the profile. Setting Input values using `--input-file` ----------------------------------------- You may also provide inputs and values via YAML files on the command line. The format can be seen below: ``` an_input:a_valueanother_input:another_value ``` CLI-input-file-set inputs have a priority of 40. As of Chef InSpec 4.3.2, this mechanism has the following limitations: 1. No [input options](#input-options-reference) may be set - only the name and value. 2. Because the CLI is outside the scope of any individual profile and the inputs don’t take options, the inputs are clumsily copied into every profile, effectively making the CLI mechanism global. Setting Input values using `--input` ------------------------------------ You may also provide inputs and values directly on the command line: ``` inspec exec my_profile --input input_name=input_value ``` To set multiple inputs, say: ``` inspec exec my_profile --input input_name1=input_value1 name2=value2 ``` If a CLI input value resembles a number, it will be converted to an Integer or Float. Scientific notation is not currently recognized. ``` inspec exec my_profile --input amplifier_volume=-11inspec exec my_profile --input water_depth=11.5 ``` You may set inputs with complex values, such as arrays and hashes using either YAML or JSON syntax. Just be sure to protect the string from the shell using single quotes. ``` inspec exec my_profile --input alphabet='[a,b,c]'inspec exec my_profile --input fruits='{a: apples, b: bananas, c: cantelopes}'inspec exec my_profile --input json_fruit='{"a": "apples", "g": ["grape01", "grape02"] }' ``` Do not repeat the `--input` flag; that will override the previous setting. CLI-set inputs have a priority of 50. As of Chef InSpec 4.12, this mechanism has the following limitations: 1. No [input options](#input-options-reference) may be set - only the name and value. 2. Because the CLI is outside the scope of any individual profile and the inputs don’t take options, the inputs are clumsily copied into every profile, effectively making the CLI mechanism global. Setting Input values using Plugins ---------------------------------- Inputs can also be set by custom input plugins, which retrieve values from external sources like secret stores or databases. Please check [RubyGems.org](https://rubygems.org/) for available InSpec input plugins. ### Disabling Caching for Inputs Especially with plugins, it can be desirable to re-evaluate inputs every time and not cache them. By default, an existing input value is reused which can lead to problems if the retrieved values are expected to change. An example for this is using `kitchen-inspec` with input plugins to connect to a Vault server for password retrieval. To disable input caching, you can disable the cache from your Ruby code: ``` Inspec::InputRegistry.instance.cache_inputs = false ``` Input Options Reference ----------------------- ### Name Required `String`. This option identifies the input. Allowed in: All. When used in DSL and Metadata, the name is unique within the current profile. When used in CLI input files, and kitchen-inspec, the input is copied across all profiles using the same name. ### Description Optional `String`. Human-meaningful explanation of the input. Allowed in: DSL, Metadata ### Value Optional, any Ruby or YAML type. This is the value that will be available when you read the input. See the [Reading Inputs](#reading-inputs-in-control-dsl) section for more information. Allowed in: All ### Type Optional, `String`. This value must be one of `String`, `Numeric`, `Regexp`, `Array`, `Hash`, `Boolean`, or `Any`. If provided, the value of the input will be checked to see if it is of the corresponding type. Note that `Regexp` indicates that the input value itself should be a regular expression, not that it should match any particular regular expression. Allowed in: DSL, Metadata ### Required Optional, `true` or `false`. If `true`, a control using the input will be failed if it [reads](#reading-inputs-in-control-dsl) the value when none has been set. Allowed in: DSL, Metadata ### Priority Optional, `Integer`, 0-100. Higher values make this assignment have higher precedence. This is an advanced feature. Allowed in: DSL, Metadata ### Profile Optional, `String`. Allows you to set an input in another profile from your profile. Allowed in: DSL, Metadata ### Sensitive Optional, `true` or `false`. If `true`, the value of the input will be used normally during the `exec` run, but the value will be obscured as “***” in the “inputs” or “attributes” section of any [Reporter](../reporters/index) that explicitly lists inputs (the `json` reporter is one such reporter). Note that this will not obscure input values that are used as test results. Allowed in: Metadata ### Pattern Optional, `Regexp`. This feature validates the input by matching it with the provided regular expression. Allowed in: DSL, Metadata Advanced Topics --------------- ### Debugging Inputs with the Event Log If it is difficult to determine why a particular value is being used, you can use the Event Log to determine what is happening. First, use the `input_object()` DSL method. This method is like `input()` in that it looks up an input, but instead of evaluating the current value, it returns the underlying `Inspec::Input` object. ``` puts input_object('troublesome_input').diagnostic_string # Or require 'pp' pp input_object('troublesome_input').events ``` `diagnostic_string` assembles the Event Log into a printable log message for convenience. The Event Log contains entries for every time that the value changed, as well as one for when the input was first created. When possible, stack probing is used to determine file and line numbers. Most importantly, you will see priority numbers; remember that highest priority wins; order only matters to break a tie. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/inputs/Chef InSpec Profile Style Guide =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/style.md) This is a set of recommended Chef InSpec rules you should use when writing controls. Control Files ------------- ### Place control files in `controls/` and end them with `.rb` Most syntax highlighters will render Chef InSpec files correctly across a wide list of tools. Avoid: * `controls/ssh_config` * `controls/ssh/config.rb` Use: * `controls/ssh_config.rb` * `controls/ssh_config.rb` ### Avoid `controls`/`control` in your control filenames Using `controls` in the filename creates unnecessary clutter when reading it. Keep the names short and concise. Avoid: * `controls/ssh_controls.rb` Use: * `controls/ssh.rb` Code Style ---------- ### Avoid unnecessary parentheses in matchers Adding additional parentheses is not required and provides more readability if it is not used: Avoid: * `it { should eq(value) }` Use: * `it { should eq value }` The exception are matchers that require additional arguments or named arguments. Controls -------- ### Avoid wrapping controls in conditional statements This will create dynamic profiles whose controls depend on the execution. The problem here is that we cannot render the profile or provide its information before scanning a system. We want to be able to inform users of the contents of their profiles before they run them. It is valid to skip controls that are not necessary for a system, as long as you do it via `only_if` conditions. Ruby’s internal conditionals will hide parts of the profile to static analysis and should thus be avoided. Avoid: ``` if package('..').installed? control "package-test1" do .. end end ``` Use: ``` control "package-test1" do only_if { package('..').installed? } end ``` Avoid: ``` case inspec.platform.name when /centos/ include_controls 'centos-profile' ... ``` Instead use the `supports` attribute in the `inspec.yml` of the profile you want to include: ``` supports: - platform-name: centos ``` Now whenever you run the base profile you can just `include_controls 'centos-profile'`. It will only run the included profiles is the platform matches the supported platform. ### Avoid dynamic elements in the control IDs Control IDs are used to map test results to the tests and profiles. Dynamic control IDs make it impossible to map results back, since the identifier which connects tests and results may change in the process. Avoid: ``` control "test-file-#{name}" do .. end ``` Use: ``` control "test-all-files" do .. end ``` Sometimes you may create controls from a static list of elements. If this list stays the same no matter what system is scanned, it may be ok to do so and use it as a generator for static controls. ### Avoid Ruby system calls Ruby code is executed on the system that runs InSpec. This allows Chef InSpec to work without Ruby and RubyGems being required on remote targets (servers or containers). System calls are often used to interact with the local OS or remote endpoints from a local installation. Chef InSpec tests, however, are designed to be universally executable on all types of runtimes, including local and remote execution. We want to give users the ability to take an OS profile and execute it remotely or locally. ### Avoid shelling out Avoid: * ``ls`` * `system("ls")` * `IO.popen("ls")` Use: * `command("ls")` or `powershell("Get-ChildItem")` Ruby’s command executors will only run locally. Imagine a test like this: ``` describe `whoami` do it { should cmp "bob\n" } end ``` If you run this test on your local system and happen to be using Bob’s account it will succeed. But if you were to run it against `--target alice@remote-host.com` it will still report that the user is bob instead of alice. Instead, do this: ``` describe command('whoami') do its('stdout') { should cmp "bob\n" } end ``` If the profile is pointed to a remote endpoint using the `command` resource will run it on the remote OS. ### Avoid Ruby IO on files Similar to the command interactions these files will only be read locally with Ruby’s internal calls. If you run this test against a remote target it won’t read the file from the remote endpoint, but from the local OS instead. Use the `file` resource to read files on the target system. Avoid: * `File.new("filename").read` * `File.read("filename")` * `IO.read("filename")` Use: * `file("filename")` In general, try to avoid Ruby’s IO calls from within Chef InSpec controls and use Chef InSpec resources instead. ### Avoid Ruby gem dependencies in controls In addition to avoiding system-level gems and modules you should also limit the use of external dependencies to resource packs or plugins. Gems need to be resolved, installed, vendored, and protected from conflicts. We aim to avoid exposing this complexity to users of InSpec, to make it a great tool even if you are not a developer. Plugins should declare gem dependencies in their gemspec, and then rely on the plugin installation facility to install and manage dependencies. ### Avoid debugging calls (in production) One of the best way to develop and explore tests is the interactive debugging shell `pry` (see [Interactive Debugging with Pry] (/inspec/dsl_inspec/#interactive-debugging-with-pry) at the end of this page). However, after you finish your profile make sure you have no interactive statements included anymore. Sometimes interactive calls are hidden behind conditionals (`if` statements) that are harder to reach. These calls can easily cause trouble when an automated profiles runs into an interactive `pry` call that stops the execution and waits for user input. Avoid: * `binding.pry` in production profiles Use: * Use debugging calls during development only Also you may find it helpful to use the Chef InSpec logging interface: ``` Inspec::Log.info('Hi') ``` #### 9. Favor `cmp` over `eq` The `cmp` matcher handles type conversions, case insensitive comparisons, converting strings to versions (e.g. ‘7.35.0-1ubuntu2.10’), and many other troublesome things. Unless you want an exact match (if so use the `eq` matcher) then the `cmp` matcher should be used. For example, this: ``` describe passwd.uids(0) do its('users') { should cmp 'root' } end ``` is preferred over: ``` describe passwd.uids(0) do its('users') { should eq ['root'] } end ``` See the [`cmp` matcher documentation](../matchers/index#cmp) for more examples. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/style/Resource DSL ============ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/dsl_resource.md) Chef InSpec provides a mechanism for defining custom resources. These become available with their respective names and provide easy functionality to profiles. Resource location ----------------- Resources may be added to profiles in the libraries folder: ``` $ tree examples/profile examples/profile ... ├── libraries │   └── example_config.rb ``` Resource structure ------------------ The smallest possible resource takes this form: ``` class Tiny < Inspec.resource(1) name 'tiny' end ``` Resources are written as a regular Ruby class which inherits from Inspec.resource. The number (1) specifies the version this resource plugin targets. As Chef InSpec evolves, this interface may change and may require a higher version. The following attributes can be configured: * name - Identifier of the resource (required) * desc - Description of the resource (optional) * example - Example usage of the resource (optional) * supports - (Chef InSpec 2.0+) Platform restrictions of the resource (optional) The following methods are available to the resource: * inspec - Contains a registry of all other resources to interact with the operating system or target in general. * skip_resource - A resource may call this method to indicate that requirements aren’t met. All tests that use this resource will be marked as skipped. The following example shows a full resource using attributes and methods to provide simple access to a configuration file: ``` class ExampleConfig < Inspec.resource(1) name 'example_config' # Restrict to only run on the below platforms (if none were given, all OS's supported) supports platform_family: 'fedora' supports platform: 'centos', release: '6.9' # Supports `*` for wildcard matcher in the release supports platform: 'centos', release: '7.*' desc ' Resource description ... ' example ' describe example_config do its("signal") { should eq "on" } end ' # Load the configuration file on initialization def initialize(path = nil) @path = path || '/etc/example.conf' @params = SimpleConfig.new( read_content ) end # Expose all parameters of the configuration file. def method_missing(name) @params[name] end private def read_content f = inspec.file(@path) # Test if the path exist and that it's a file if f.file? # Retrieve the file's contents f.content else # If the file doesn't exist, skip all tests that use example_config raise Inspec::Exceptions::ResourceSkipped, "Can't read config at #{@path}" end end end ``` For a full example, see our [example resource](https://github.com/chef/inspec/blob/main/examples/profile/libraries/example_config.rb). Lazy Loading ------------ Prior to InSpec v4.16, resources were pre-loaded for every invocation of `inspec`. This was a heavy and unnecessary burden on the system and exacerbated startup times (especially on Windows). As of InSpec v4.16, resources are lazily loaded into the `inspec` process upon use. This greatly speeds up the initial startup costs of the `inspec` process and only loads what you need to use. For example, `inspec --version` no longer runs for 10 seconds!. ### Overriding Core Resources Lazy loading does change the way the resource registry is handled in ways that might break some assumptions. Specifically, `inspec.<resource>` isn’t pre-populated with the core resources that InSpec ships with. If you make a local/custom resource of the same name, referring to the core resource via `inspec.<resource>` will not resolve to the core resource. As such, overriding core resources is not recommended best practice. If you really do need to do this, it is easiest to make a local resource with a new name and refer to the core resource directly. Otherwise, you need to ensure that the core resource you want is registered (via `require "inspec/resource/<name>"`) *before* your profile is run to ensure it is eagerly loaded and in the global resource registry. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/dsl_resource/Chef InSpec Shell ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/shell.md) The Chef InSpec interactive shell is a pry based REPL that can be used to quickly run Chef InSpec controls and tests without having to write it to a file. Its functionality is similar to [chef-shell](../../chef_shell/index) as it provides a way to exercise the Chef InSpec Language, its resources, tests, and plugins without having to create a profile or write a test file. See <http://pryrepl.org/> for an introduction to what pry is and what it can do. See [Explore Chef InSpec resources](https://learn.chef.io/modules/explore-inspec-resources#/) on Learn Chef Rally for a hands-on example that uses Chef InSpec shell. Launching the shell ------------------- If you are using Chef InSpec from a platform-specific package (rpm, msi, etc.) or from a Chef prepared shell in Chef Workstation, you can directly launch Chef InSpec shell against your local machine using the following. See [https://docs.chef.io/install_dk.html#set-system-ruby](../../install_dk#set-system-ruby) for details. ``` inspec shell inspec help shell # This will describe inspec shell usage ``` If you wish to connect to a remote machine (called a target within InSpec), you can use the `-t` flag. We support connecting using SSH, WinRM and docker. If no target is provided, we implicitly support the “local” target - i.e. tests running on the current machine running InSpec. For an SSH connection, use `-i` for specifying SSH key files, and the `--sudo*` commands for requesting a privilege escalation after logging in. For a WinRM connection, use `--path` to change the login path, `--ssl` to use SSL for transport layer encryption. ``` inspec shell -t ssh://root@192.168.64.2:11022 # Login to remote machine using ssh as root. inspec shell -t ssh://user@hostname:1234 -i /path/to/user_key # Login to hostname on port 1234 as user using given ssh key. inspec shell -t winrm://UserName:Password@windowsmachine:1234 # Login to windowsmachine over WinRM as UserName. inspec shell -t winrm://windowsmachine --user 'UserName@domain' --password 'Secret123!' # Login to windowsmachine as <EMAIL>. inspec shell -t docker://container_id # Login to a Docker container. ``` Resource Packs -------------- Use resource packs to share custom resources with other Chef InSpec users. A resource pack is a Chef InSpec profile that contains only custom resources and no other controls or tests. For example, the profile in [`examples/profile`](https://github.com/chef/inspec/tree/main/examples/profile) in the Chef InSpec GitHub repository defines an [`example_config` resource](https://github.com/chef/inspec/blob/main/examples/profile/controls/example.rb). To use these resources within the Chef InSpec shell, you will need to download and specify them as a dependency. Once you have local access to the profile, you can use the `example_config` custom resource provided in the `examples/profile` GitHub repo in your local environment : ``` inspec shell --depends examples/profile ``` Once inside the shell your resource will be available: ``` inspec> example_config ``` Using Ruby in Chef InSpec shell ------------------------------- Since Chef InSpec shell is pry based, you may treat the shell as an interactive Ruby session. You may write Ruby expressions and evaluate them. Source high-lighting, automatic indentation and command history (using the up and down arrow keys) are available to make your experience more delightful. You can exit the shell using `exit`. ``` $ inspec shell Welcome to the interactive InSpec Shell To find out how to use it, type: help inspec> 1 + 2 => 3 inspec> exit ``` Using Chef InSpec Language in Chef InSpec shell ----------------------------------------------- Chef InSpec shell will automatically evaluate the result of every command as if it were a test file. If you type in a Ruby command that is not an Chef InSpec control or test, the shell will evaluate it as if it were a regular ruby command. Bare Chef InSpec resources are instantiated and their help text is presented. You may also access the resource contents or other matchers that they define. Run `help <resource>` to get more help on using a particular resource or see the Chef InSpec resources documentation online. ``` $ inspec shell Welcome to the interactive InSpec Shell To find out how to use it, type: help inspec> file('/Users/myuser').directory? => true inspec> os_env('HOME') => Environment variable HOME inspec> os_env('HOME').content => /Users/myuser inspec> exit ``` Chef InSpec tests are immediately executed. ``` inspec> describe file('/Users') # Empty test. Summary: 0 successful, 0 failures, 0 skipped inspec> describe file('/Users') do # Test with one check. inspec> it { should exist } inspec> end ✔ File /Users should exist Summary: 1 successful, 0 failures, 0 skipped ``` All tests in a control are immediately executed as well. If a control is redefined in the shell, the old control’s tests are destroyed and replaced with the redefinition and the control is re-run. ``` inspec> control 'my_control' do inspec> describe os_env('HOME') do inspec> its('content') { should eq '/Users/myuser' } inspec> end inspec> end ✔ my_control: Environment variable HOME content should eq "/Users/myuser" Summary: 1 successful, 0 failures, 0 skipped ``` Syntax errors are illegal tests are also detected and reported. ``` inspec> control 'foo' do inspec> thisisnonsense inspec> end NameError: undefined local variable or method `thisisnonsense' for #<#<Class:0x007fd63b571f98>:0x007fd639825cc8> from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-expectations-3.5.0/lib/rspec/matchers.rb:967:in `method_missing' inspec> control 'foo' do inspec> describe file('wut') do inspec> its('thismakesnosense') { should cmp 'fail' } inspec> end inspec> end ✖ foo: File wut thismakesnosense (undefined method `thismakesnosense' for File wut:Inspec::Resource::Registry::File) Summary: 0 successful, 1 failures, 0 skipped ``` Running a single Chef InSpec command ------------------------------------ If you wish to run a single Chef InSpec command and fetch its results, you may use the `-c` flag. This is similar to using `bash -c`. ``` $ inspec shell -c 'describe file("/Users/myuser") do it { should exist } end' Target: local:// ✔ File /Users/myuser should exist Summary: 1 successful, 0 failures, 0 skipped ``` ``` $ inspec shell --format json -c 'describe file("/Users/test") do it { should exist } end' { "version": "1.49.2", "controls": [{ "status": "passed", "code_desc": "File /Users/test should exist", "run_time": 0.002374, "start_time": "2018-01-06 18:32:38 -0500" }], "other_checks": [], "profiles": [{ "name": "inspec-shell", "supports": [], "controls": [{ "title": null, "desc": null, "impact": 0.5, "refs": [], "tags": {}, "code": "", "source_location": { "ref": "/usr/local/lib/ruby/gems/2.4.0/gems/inspec-1.49.2/lib/inspec/control_eval_context.rb", "line": 89 }, "id": "(generated from (eval):1 7b6f82c2cc5e4205b3e2c97c8e855f2d)", "results": [{ "status": "passed", "code_desc": "File /Users/test should exist", "run_time": 0.002374, "start_time": "2018-01-06 18:32:38 -0500" }] }], "groups": [{ "title": null, "controls": ["(generated from (eval):1 7b6f82c2cc5e4205b3e2c97c8e855f2d)"], "id": "unknown" }], "attributes": [], "sha256": "29c070a90b7e3521babf618215573284a790d92907783d5b2c138f411bfd2e74" }], "platform": { "name": "mac_os_x", "release": "17.3.0" }, "statistics": { "duration": 0.003171 } } ``` Running Chef InSpec Shell With Inputs ------------------------------------- With InSpec [profiles that support inputs](../inputs/index#which-profiles-support-inputs), you can set inputs using the InSpec `shell` command. This allows you to work more consistently with InSpec profiles when switching between the `shell` and `exec` commands. For more details on inputs, see the [inputs reference](../inputs/index). ### Set Inputs with Command-line Options The `shell` command accepts one or more inputs in the command line as single-quoted YAML or JSON structures. ``` $ inspec shell --input=input_name=input_value Welcome to the interactive InSpec Shell To find out how to use it, type: help inspec> control 'my_control' do inspec> describe input('input_name') do inspec> it { should cmp 'input_value' } inspec> end inspec> end Profile: inspec-shell ✔ my_control: input_value ✔ input_value is expected to cmp == "input_value" Profile Summary: 1 successful control, 0 control failures, 0 controls skipped Test Summary: 1 successful, 0 failures, 0 skipped inspec> exit ``` ### Set Inputs with YAML File You can also save inputs and values to one or more YAML files and pass them to `shell` in the command line. For example: ``` input_name:input_valueanother_input:another_value ``` ``` inspec shell --input-file=<path``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/shell/About kitchen-inspec ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/plugin_kitchen_inspec.md) Use Chef InSpec as a Kitchen verifier with `kitchen-inspec`. Add the Chef InSpec verifier to the `.kitchen.yml` file: ``` verifier: name: inspec ``` Use a compliance profile from the Chef Compliance server: ``` suites: - name: compliance run_list: - recipe[ssh-hardening::default] verifier: inspec_tests: - compliance://base/ssh ``` and then run the following command: ``` inspec automate login https://compliance.test --user admin --insecure --token '' ``` where `--insecure` is required when using self-signed certificates. `inspec compliance` is a backwards compatible alias for `inspec automate` and works the same way: ``` inspec compliance login https://compliance.test --user admin --insecure --token '' ``` Use a compliance profile from the Chef Supermarket: ``` suites: - name: supermarket run_list: - recipe[ssh-hardening::default] verifier: inspec_tests: - supermarket://dev-sec/ssh-baseline ``` Use Chef InSpec tests from the local file system: ``` suites: - name: local run_list: - recipe[my_cookbook::default] verifier: inspec_tests: - test/integration/default ``` Check out [Detect and correct with Test Kitchen](https://learn.chef.io/modules/detect-correct-kitchen#/) on Learn Chef Rally for a hands-on look at how to use Test Kitchen to run Chef InSpec profiles. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/plugin_kitchen_inspec/Chef InSpec Migration Guide =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/migration.md) How is Chef InSpec different from Serverspec -------------------------------------------- We’ve written a complete blog post about that topic: [The Road to InSpec](https://blog.chef.io/2015/11/04/the-road-to-inspec/) Is Chef InSpec suitable for infrastructure testing? --------------------------------------------------- Chef InSpec is a framework that allows you to run infrastructure testing as well as compliance testing. The compliance features are always optional and provide customers a way to use Chef InSpec for both use-cases. To ensure we build the best infrastructure testing, we migrate our cookbooks [chef-cookbooks](https://github.com/chef-cookbooks) to InSpec. Which Serverspec resources are available in InSpec? --------------------------------------------------- The following resources are available in InSpec: | Serverspec | Chef InSpec | | --- | --- | | [`bond`](http://serverspec.org/resource_types.html#bond) | [`bond`](../resources/bond/index) | | [`bridge`](http://serverspec.org/resource_types.html#bridge) | [`bridge`](../resources/bridge/index) | | [`command`](http://serverspec.org/resource_types.html#command) | [`command`](../resources/command/index) | | [`cron`](http://serverspec.org/resource_types.html#cron) | [`crontab`](../resources/crontab/index) | | [`docker_container`](http://serverspec.org/resource_types.html#docker_container) | [`docker_container`](../resources/docker_container/index) | | [`docker_image`](http://serverspec.org/resource_types.html#docker_image) | [`docker_image`](../resources/docker_image/index) | | [`file`](http://serverspec.org/resource_types.html#file) | [`file`](../resources/file/index) | | [`group`](http://serverspec.org/resource_types.html#group) | [`group`](../resources/group/index) | | [`host`](http://serverspec.org/resource_types.html#host) | [`host`](../resources/host/index) | | [`interface`](http://serverspec.org/resource_types.html#interface) | [`interface`](../resources/interface/index) | | [`iis_website`](http://serverspec.org/resource_types.html#iis_website) | [`iis_site`](../resources/iis_site/index) | | [`iis_app_pool`](http://serverspec.org/resource_types.html#iis_app_pool) | [`iis_app`](../resources/iis_app/index) | | [`iptables`](http://serverspec.org/resource_types.html#iptables) | [`iptables`](../resources/iptables/index) | | [`kernel_module`](http://serverspec.org/resource_types.html#kernel_module) | [`kernel_module`](../resources/kernel_module/index) | | [`linux_kernel_parameter`](http://serverspec.org/resource_types.html#linux_kernel_parameter) | [`kernel_parameter`](../resources/kernel_parameter/index) | | [`mysql_config`](http://serverspec.org/resource_types.html#mysql_config) | [`mysql_conf`](../resources/mysql_conf/index) | | [`package`](http://serverspec.org/resource_types.html#package) | [`package`](../resources/package/index) | | [`port`](http://serverspec.org/resource_types.html#port) | [`port`](../resources/port/index) | | [`ppa`](http://serverspec.org/resource_types.html#ppa) | [`apt`](../resources/apt/index) | | [`process`](http://serverspec.org/resource_types.html#process) | [`processes`](../resources/processes/index) | | [`service`](http://serverspec.org/resource_types.html#service) | [`service`](../resources/service/index) | | [`user`](http://serverspec.org/resource_types.html#user) | [`user`](../resources/user/index) | | [`windows_feature`](http://serverspec.org/resource_types.html#windows_feature) | [`windows_feature`](../resources/windows_feature/index) | | [`windows_registry_key`](http://serverspec.org/resource_types.html#windows_registry_key) | [`registry_key`](../resources/registry_key/index) | | [`x509_certificate`](http://serverspec.org/resource_types.html#x509_certificate) | [`x509_certificate`](../resources/x509_certificate/index) | | [`yumrepo`](http://serverspec.org/resource_types.html#yumrepo) | [`yum`](../resources/yum/index) | | [`zfs`](http://serverspec.org/resource_types.html#zfs) | [`zfs_pool`](../resources/zfs_pool/index) | Some Serverspec resources are not available yet. We will implement those resources based on user feedback. If you need a resource that is not available in InSpec, please open an [Github issue](https://github.com/chef/inspec/issues). The list of resources that are not available in InSpec: * [`cgroup`](http://serverspec.org/resource_types.html#cgroup) * [`default_gateway`](http://serverspec.org/resource_types.html#default_gateway) * [`ip6tables`](http://serverspec.org/resource_types.html#ip6tables) * [`ipfilter`](http://serverspec.org/resource_types.html#ipfilter) * [`ipnat`](http://serverspec.org/resource_types.html#ipnat) * [`linux_audit_system`](http://serverspec.org/resource_types.html#linux_audit_system) * [`lxc`](http://serverspec.org/resource_types.html#lxc) * [`mail_alias`](http://serverspec.org/resource_types.html#mail_alias) * [`php_config`](http://serverspec.org/resource_types.html#php_config) * [`routing_table`](http://serverspec.org/resource_types.html#routing_table) * [`selinux`](http://serverspec.org/resource_types.html#selinux) * [`selinux_module`](http://serverspec.org/resource_types.html#selinux_module) * [`x509_private_key`](http://serverspec.org/resource_types.html#x509_private_key) In addition Chef InSpec provides additional [resources](../resources/index) that are not available in Serverspec: * [`apache_conf`](../resources/apache_conf/index) * [`apt`](../resources/apt/index) * [`audit_policy`](../resources/audit_policy/index) * [`auditd_conf`](../resources/auditd_conf/index) * [`bash`](../resources/bash/index) * [`csv`](../resources/csv/index) * [`shadow`](../resources/shadow/index) * [`gem`](../resources/gem/index) * [`grub_conf`](../resources/grub_conf/index) * [`inetd_conf`](../resources/inetd_conf/index) * [`ini`](../resources/ini/index) * [`json`](../resources/json/index) * [`npm`](../resources/npm/index) * [`ntp_conf`](../resources/ntp_conf/index) * [`oneget`](../resources/oneget/index) * [`pip`](../resources/pip/index) * [`powershell`](../resources/powershell/index) * [`security_policy`](../resources/security_policy/index) * [`ssh_config`](../resources/ssh_config/index) * [`sshd_config`](../resources/sshd_config/index) * [`sys_info`](../resources/sys_info/index) How do I migrate my Serverspec tests to InSpec ---------------------------------------------- For most cases, the migration to Chef InSpec is pretty straight forward. First, replace the current verifier in `kitchen.yml` configuration with: ``` verifier:name:inspec ``` Second, rename the directory `test/integration/default/serverspec` to `test/integration/default/inspec` Third, remove the Serverspec-specific code from the test files. ``` require 'serverspec' # Required by serverspec set :backend, :exec ``` Chef InSpec is now configured with Test-Kitchen: ``` kitchen verify package-install-centos-72 -----> Starting Kitchen (v1.14.2) -----> Verifying <package-install-centos-72>... Detected alternative framework tests for `inspec` Loaded Target: ssh://vagrant@127.0.0.1:2200 PHP has ✔ php ✔ the pear.php.net channel ✔ the pecl.php.net channel Test Summary: 3 successful, 0 failures, 0 skipped Finished verifying <package-install-centos-72> (0m0.40s). -----> Kitchen is finished. (0m3.31s) ``` Some real-world migrations are available: * [docker](https://github.com/chef-cookbooks/docker) * [nginx](https://github.com/chef-cookbooks/chef_nginx/pull/5/files) * [mysql](https://github.com/chef-cookbooks/mysql/pull/430/files) * [php](https://github.com/chef-cookbooks/php/pull/189/files) Some general recommendations: * use test-kitchen 1.14+ * in case of errors, increase the log level `kitchen verify package-install-centos-72 -l debug` Do I still need the backend configuration? ------------------------------------------ Chef InSpec does not attach backend information to test files. All tests are defined independently of any backend. Therefore a Serverspec test file: ``` require 'serverspec' # Required by serverspec set :backend, :exec describe 'PHP' do it 'has php' do expect(command('php -v').exit_status).to eq(0) end it 'has the pear.php.net channel' do expect(command('pear list-channels').stdout).to include('pear.php.net') end it 'has the pecl.php.net channel' do expect(command('pear list-channels').stdout).to include('pecl.php.net') end end ``` will become the following Chef InSpec test file: ``` describe 'PHP' do it 'has php' do expect(command('php -v').exit_status).to eq(0) end it 'has the pear.php.net channel' do expect(command('pear list-channels').stdout).to include('pear.php.net') end it 'has the pecl.php.net channel' do expect(command('pear list-channels').stdout).to include('pecl.php.net') end end ``` As you can see, the Chef InSpec test files just focuses on tests and tries to avoid all clutter. Nested describe blocks ---------------------- Serverspec and RSpec allow you to define nested describe blocks. We did a survey and found out that most users use nested describe blocks only to improve their output report. We believe the code structure should not change to improve the output of a report. Nevertheless we understand that nested describe blocks help you to structure test code. A sample code block looks like: ``` describe 'chef-server-directories' do describe file('/etc/opscode') do it { should be_directory } it { should be_owned_by 'root' } end describe file('/etc/opscode-analytics') do it { should be_directory } it { should be_owned_by 'opscode' } it { should be_grouped_into 'opscode' } end describe file('/var/log/opscode') do it { should be_directory } it { should be_owned_by 'opscode' } it { should be_grouped_into 'opscode' } end describe file('/var/opt/opscode') do it { should be_directory } it { should be_owned_by 'root' } end end ``` In Chef InSpec you would split up groups into files. ``` tests ├── server-directories.rb ├── other-tests.rb └── further-tests.rb ``` Each file can have a top-level description of its content: ``` title "Chef Server Directories" describe file('/etc/opscode') do it { should be_directory } it { should be_owned_by 'root' } end describe file('/etc/opscode-analytics') do it { should be_directory } it { should be_owned_by 'opscode' } it { should be_grouped_into 'opscode' } end describe file('/var/log/opscode') do it { should be_directory } it { should be_owned_by 'opscode' } it { should be_grouped_into 'opscode' } end describe file('/var/opt/opscode') do it { should be_directory } it { should be_owned_by 'root' } end ``` Are you supporting the `expect` syntax? --------------------------------------- Of course. We still prefer the `should` syntax for UX reasons. We did surveys with various types of customers like devops engineers, auditors, managers. All participants who preferred the `expect` syntax have been Ruby experts. All non-Ruby developers found it easier to understand the `should` syntax. ### `should` syntax with InSpec ``` describe command('php -v') do its('exit_status') { should eq 0 } end describe command('pear list-channels') do its('stdout') { should include('pear.php.net')} end describe command('pear list-channels') do its('stdout') { should include('pecl.php.net')} end ``` ### `expect` syntax with InSpec ``` describe 'PHP' do it 'has php' do expect(command('php -v').exit_status).to eq(0) end it 'has the pear.php.net channel' do expect(command('pear list-channels').stdout).to include('pear.php.net') end it 'has the pecl.php.net channel' do expect(command('pear list-channels').stdout).to include('pecl.php.net') end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/migration/Chef InSpec Integration with Chef Habitat ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/habitat.md) Chef InSpec provides an easy method to create an executable Chef Habitat package for a Chef InSpec profile. When run via the Chef Habitat Supervisor, the package will run Chef InSpec with your profile and write out its findings to the supervisor log. This provides the ability to ship your compliance controls alongside your Chef Habitat-packaged application and continuously run InSpec, providing you *Continuous Compliance.* What is Chef Habitat -------------------- Chef Habitat by Chef Software is our new Application Automation tool that aims to make it easy, safe, and fast to build, deploy, and manage applications. From build dependencies, runtime dependencies, dynamic configuration, and service discovery (just to name a few), Chef Habitat packages the automation with the application instead of relying on an underlying platform. To learn more about Chef Habitat and try our demos and tutorials, visit <https://www.habitat.sh>. Using the Chef Habitat Integration ---------------------------------- After creating a Chef Habitat package for a Chef InSpec profile (see CLI commands below) and uploading the package to a Chef Habitat Depot or manually distributing to a host, start the Chef Habitat Supervisor with your package: ``` hab start effortless/audit-baseline ``` The Chef Habitat Supervisor will install Chef InSpec and execute your profile in a loop. The loop is controlled by two variables: the `interval` and the `splay`. The `interval` is a set time you want InSpec to run and its default is `1800` seconds. The `splay` is a randomly generated sleep time that prevents a thundering herd problem, or resource starvation scenario, when sending your report to an external server like Chef Automate. The default for the `splay` is also `1800` seconds. Alternatively, the `splay_first_run` can be set to wait a random period of time between 0 and the number set for the `splay_first_run` before running InSpec when your Habitat package is started or updated. The default of the `splay_first_run` is `0` seconds. ``` HAB_INSPEC_PROFILE_FRONTEND1="interval = 60" hab start effortless/audit-baseline ``` The Chef Habitat Supervisor will display output like this: ``` hab start effortless/audit-baseline ∵ Missing package for core/hab-sup/0.17.0 » Installing core/hab-sup/0.17.0 ↓ Downloading core/hab-sup/0.17.0/20170214235450 1.68 MB / 1.68 MB - [=========================================================================] 100.00 % 7.43 MB/s ... more Chef Habitat output here ... hab-sup(MN): Starting effortless/audit-baseline/0.1.0/20170328173005 hab-sup(CS): effortless/audit-baseline/0.1.0/20170328173005 is not installed ↓ Downloading adamleff-20160617201047 public origin key 79 B / 79 B | [===============================================================================] 100.00 % 2.64 MB/s ☑ Cached adamleff-20160617201047 public origin key ↓ Downloading chef/inspec/1.17.0/20170321214949 16.93 MB / 16.93 MB / [======================================================================] 100.00 % 10.49 MB/s ... more Chef Habitat output here ... ★ Install of effortless/audit-baseline/0.1.0/20170328173005 complete with 9 new packages installed. hab-sup(MR): Butterfly Member ID d9bd761e18c144469d755b1b97406eb2 hab-sup(MR): Starting butterfly on 0.0.0.0:9638 hab-sup(MR): Starting http-gateway on 0.0.0.0:9631 inspec-profile-frontend1.default(SR): Initializing inspec-profile-frontend1.default(SV): Starting process as user=hab, group=hab inspec-profile-frontend1.default(O): Executing InSpec effortless/audit-baseline inspec-profile-frontend1.default(O): InSpec run completed successfully. inspec-profile-frontend1.default(O): sleeping for 2134 seconds ``` The above sample output shows the supervisor starting, downloading the necessary dependencies for the supervisor and the Chef InSpec profile, and then shows the supervisor running Chef InSpec successfully. Chef InSpec will write a JSON file in the `${svc_var_path}/inspec_results` directory containing the results of the last Chef InSpec run. For example, for the `effortless/audit-baseline` package, the Chef InSpec results will be at: ``` /hab/svc/inspec-profile-frontend1/var/inspec_results/inspec-profile-frontend1.json ``` Chef InSpec Chef Habitat CLI Commands ------------------------------------- ### inspec habitat profile create Create a Chef Habitat package for a Chef InSpec profile. Chef InSpec will validate the profile, fetch and vendor any dependencies (if necessary), and build the Chef Habitat package with a dependency on the latest InSpec. The resulting package will be saved to the current working directory. The package can then be manually uploaded to a Chef Habitat Depot or manually distributed to a host and installed via `hab pkg install`. The package file will be named: ``` HABITAT_ORIGIN-inspec-profile-PROFILE_NAME-PROFILE_VERSION-BUILD_ID-x86_64-linux.hart ``` For example: ``` adamleff-inspec-profile-frontend1-0.1.0-20170328173005-x86_64-linux.hart ``` #### Syntax ``` inspec habitat profile create PROFILE_DIRECTORY ``` #### Example ``` inspec habitat profile create ~/profiles/frontend1 ``` #### Example Output ``` $ habitat profile create ~/profiles/frontend1 [2017-03-28T13:29:32-04:00] INFO: Creating a Habitat artifact for profile: /Users/aleff/profiles/frontend1 [2017-03-28T13:29:32-04:00] INFO: Checking to see if Habitat is installed... [2017-03-28T13:29:32-04:00] INFO: Copying profile contents to the work directory... [2017-03-28T13:29:32-04:00] INFO: Generating Habitat plan at /var/folders/<KEY>T/inspec-habitat-exporter20170328-4932-kg2ltd/habitat/plan.sh... [2017-03-28T13:29:32-04:00] INFO: Generating a Habitat run hook at /var/folders/v5/z54gb76j2rs3wrn65hmtyf1r0000gp/T/inspec-habitat-exporter20170328-4932-kg2ltd/habitat/hooks/run... [2017-03-28T13:29:32-04:00] INFO: Generating Habitat's default.toml configuration... [2017-03-28T13:29:32-04:00] INFO: Building our Habitat artifact... hab-studio: Destroying Studio at /hab/studios/src (default) hab-studio: Creating Studio at /hab/studios/src (default) hab-studio: Importing adamleff secret origin key » Importing origin key from standard input ★ Imported secret origin key adamleff-20160617201047. » Installing core/hab-backline ↓ Downloading core/hab-backline/0.19.0/20170311034116 2.17 KB / 2.17 KB / [=========================================================================] 100.00 % 4.33 MB/s ... more Chef Habitat output here... [2017-03-28T13:30:18-04:00] INFO: Copying artifact to /Users/aleff... ``` ### inspec habitat profile setup Create a Chef Habitat directory that includes a plan file in a profile directory. This is the same process that is used by `inspec habitat profile create` - but this adds the generated Chef Habitat directory and file to your system so that you can commit them to source control. If you commit these files to GitHub, you can connect that plan to the [Chef Habitat Builder Service](https://www.habitat.sh/docs/using-builder/). #### Syntax ``` inspec habitat profile setup PROFILE_DIRECTORY ``` #### Example ``` inspec habitat profile setup ~/profiles/frontend1 ``` #### Example Output ``` [2018-10-31T23:45:59+00:00] INFO: Setting up profile at /home/nell/profiles/frontend1/ for Habitat... [2018-10-31T23:45:59+00:00] INFO: Checking to see if the profile is valid... [2018-10-31T23:45:59+00:00] INFO: Profile is valid. [2018-10-31T23:45:59+00:00] INFO: Profile's dependencies are already vendored, skipping vendor process. [2018-10-31T23:45:59+00:00] INFO: Generating Habitat plan at /home/nell/profiles/frontend1/habitat/plan.sh... ``` ### inspec habitat profile upload Create and then upload a Chef Habitat package for a Chef InSpec profile. Like the `inspec habitat profile create` command, Chef InSpec will validate the profile, fetch and vendor any dependencies (if necessary), and build the Chef Habitat package with a dependency on the latest InSpec. However, instead of saving the package locally to the workstation, Chef InSpec will upload it to the depot defined in the `HAB_DEPOT` environment variable. If `HAB_DEPOT` is not defined, the package will be uploaded to the public Chef Habitat depot at <https://app.habitat.sh>. #### Syntax ``` inspec habitat profile upload PROFILE_DIRECTORY ``` #### Example ``` inspec habitat profile upload ~/profiles/frontend1 ``` #### Example Output ``` [2017-03-28T13:29:32-04:00] INFO: Creating a Habitat artifact for profile: /Users/aleff/profiles/frontend1 [2017-03-28T13:29:32-04:00] INFO: Checking to see if Habitat is installed... [2017-03-28T13:29:32-04:00] INFO: Copying profile contents to the work directory... [2017-03-28T13:29:32-04:00] INFO: Generating Habitat plan at /var/folders/v5/z54gb76j2rs3wrn65hmtyf1r0000gp/T/inspec-habitat-exporter20170328-4932-kg2ltd/habitat/plan.sh... [2017-03-28T13:29:32-04:00] INFO: Generating a Habitat run hook at /var/folders/v5/z54gb76j2rs3wrn65hmtyf1r0000gp/T/inspec-habitat-exporter20170328-4932-kg2ltd/habitat/hooks/run... [2017-03-28T13:29:32-04:00] INFO: Generating Habitat's default.toml configuration... [2017-03-28T13:29:32-04:00] INFO: Building our Habitat artifact... hab-studio: Destroying Studio at /hab/studios/src (default) hab-studio: Creating Studio at /hab/studios/src (default) hab-studio: Importing adamleff secret origin key » Importing origin key from standard input ★ Imported secret origin key adamleff-20160617201047. » Installing core/hab-backline ↓ Downloading core/hab-backline/0.19.0/20170311034116 2.17 KB / 2.17 KB / [=========================================================================] 100.00 % 4.33 MB/s ... more Chef Habitat output here... [2017-03-28T13:30:18-04:00] INFO: Uploading the Habitat artifact to our Depot... [2017-03-28T13:30:23-04:00] INFO: Upload complete! ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/habitat/Waivers ======= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/waivers.md) Waivers is a mechanism to mark controls as “waived” for various reasons, and to control the running and/or reporting of those controls. It uses a YAML input file that identifies: 1. which controls are waived 2. a description of why it is waived 3. (optionally) whether they should be skipped from running 4. (optionally) an expiration date for the waiver Usage ----- To use waivers, you must have a correctly formatted input file and invoke `inspec exec` with `--waiver-file [path]`. ``` inspec exec path/to/profile --waiver-file waivers.yaml ``` File Format ----------- Waiver files are [input files](../inputs/index) with a specific format: ``` control_id:expiration_date:YYYY-MM-DDrun:falsejustification:"reason for waiving this control" ``` * `expiration_date` is optional. Absence means the waiver is permanent. * `run` is optional. If absent or true, the control will run and be reported, but failures in it won’t make the overall run fail. If present and false, the control will not be run. You may use any of yes, no, true or false. To avoid confusion, it is good practice to explicitly specify whether the control should run. * `justification` can be any text you want and might include a reason as well as who signed off on the waiver. ### Examples: ``` waiver_control_1_2_3:expiration_date:2019-10-15justification:Not needed until Q3. @secteamxccdf_org.cisecurity.benchmarks_rule_1.1.1.4_Ensure_mounting_of_hfs_filesystems_is_disabled:expiration_date:2020-03-01justification:"This might be a bug in the test. @qateam"run:false ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/waivers/aide_conf resource =================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aide_conf.md) Use the `aide_conf` Chef InSpec audit resource to test the rules established for the file integrity tool AIDE. Controlled by the aide.conf file typically at /etc/aide.conf. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.37.6 of InSpec. Syntax ------ An `aide_conf` resource block can be used to determine if the selection lines contain one (or more) directories whose files should be added to the aide database: ``` describe aide_conf('path') do its('selection_lines') { should include '/sbin' } end ``` where * `'selection_lines'` refers to all selection lines found in the aide.conf file * `('path')` is the non-default path to the `aide.conf` file (optional) * `should include 'value'` is the value that is expected Use the where clause to match a selection_line to one rule or a particular set of rules found in the aide.conf file: ``` describe aide_conf.where { selection_line == '/bin' } do its('rules.flatten') { should include 'r' } end describe aide_conf.where { selection_line == '/sbin' } do its('rules') { should include ['p', 'i', 'l', 'n', 'u', 'g', 'sha512'] } end ``` Properties ---------- ### `rules` The `rules` property returns the list of rules set in the `aide.conf` file. ``` its('rules') { should include ['r', 'sha512'] } ``` ### `all_have_rule` The `all_have_rule` property returns the all selected lines from `aide.conf` file e.g. ‘p’, ‘i’ etc. ``` aide_conf.all_have_rule('sha512') ``` ### `selection_lines` The `selection_lines` property returns the list of lines from `aide.conf` file. ``` its('selection_lines') { should include '/sbin' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if all selection lines contain the `xattr` rule ``` describe aide_conf.all_have_rule('xattr') do it { should eq true } end ``` ### Test whether selection line for /bin contains a particular rule ``` describe aide_conf.where { selection_line == '/bin' } do its('rules.flatten') { should include 'r' } end ``` ### Test whether the selection line for `/sbin` consists of a particular set of rules ``` describe aide_conf.where { selection_line == '/sbin' } do its('rules') { should include ['r', 'sha512'] } end ``` ### The usage of all_have_rule will return whether or not all selection lines in audit.conf contain a particular rule: ``` describe aide_conf.all_have_rule('sha512') do it { should eq true } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aide_conf/InSpec Resources Reference ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/_index.md) The following list of InSpec resources are available. OS -- * [cassandradb_conf resource](cassandradb_conf/index) * [cassandradb_session resource](cassandradb_session/index) * [command resource](command/index) * [csv resource](csv/index) * [directory resource](directory/index) * [file resource](file/index) * [gem resource](gem/index) * [group resource](group/index) * [groups resource](groups/index) * [host resource](host/index) * [ibmdb2_conf resource](ibmdb2_conf/index) * [ibmdb2_session resource](ibmdb2_session/index) * [ini resource](ini/index) * [interface resource](interface/index) * [interfaces resource](interfaces/index) * [json resource](json/index) * [key_rsa resource](key_rsa/index) * [mongodb_conf resource](mongodb_conf/index) * [mongodb_session resource](mongodb_session/index) * [mssql_sys_conf resource](mssql_sys_conf/index) * [mysql_conf resource](mysql_conf/index) * [mysql_session resource](mysql_session/index) * [npm resource](npm/index) * [opa_api resource](opa_api/index) * [opa_cli resource](opa_cli/index) * [oracledb_conf resource](oracledb_conf/index) * [oracledb_listener_conf resource](oracledb_listener_conf/index) * [oracledb_session resource](oracledb_session/index) * [os resource](os/index) * [os_env resource](os_env/index) * [package resource](package/index) * [parse_config resource](parse_config/index) * [parse_config_file resource](parse_config_file/index) * [pip resource](pip/index) * [port resource](port/index) * [postfix_conf resource](postfix_conf/index) * [postgres_conf resource](postgres_conf/index) * [postgres_session resource](postgres_session/index) * [processes resource](processes/index) * [service resource](service/index) * [ssl resource](ssl/index) * [sybase_conf resource](sybase_conf/index) * [sybase_session resource](sybase_session/index) * [sys_info resource](sys_info/index) * [toml resource](toml/index) * [user resource](user/index) * [users resource](users/index) * [x509_certificate resource](x509_certificate/index) * [xml resource](xml/index) * [yaml resource](yaml/index) ### Linux The following resources work on Linux operating systems. * [aide_conf resource](aide_conf/index) * [apache resource](apache/index) * [apache_conf resource](apache_conf/index) * [apt resource](apt/index) * [audit_policy resource](audit_policy/index) * [auditd resource](auditd/index) * [auditd_conf resource](auditd_conf/index) * [bash resource](bash/index) * [bond resource](bond/index) * [bridge resource](bridge/index) * [bsd_service resource](bsd_service/index) * [chrony_conf resource](chrony_conf/index) * [cpan resource](cpan/index) * [cran resource](cran/index) * [crontab resource](crontab/index) * [dh_params resource](dh_params/index) * [docker resource](docker/index) * [docker_container resource](docker_container/index) * [docker_image resource](docker_image/index) * [docker_plugin resource](docker_plugin/index) * [docker_service resource](docker_service/index) * [elasticsearch resource](elasticsearch/index) * [etc_fstab resource](etc_fstab/index) * [etc_group resource](etc_group/index) * [etc_hosts resource](etc_hosts/index) * [etc_hosts_allow resource](etc_hosts_allow/index) * [etc_hosts_deny resource](etc_hosts_deny/index) * [filesystem resource](filesystem/index) * [firewalld resource](firewalld/index) * [grub_conf resource](grub_conf/index) * [http resource](http/index) * [inetd_conf resource](inetd_conf/index) * [ip6tables resource](ip6tables/index) * [iptables resource](iptables/index) * [kernel_module resource](kernel_module/index) * [kernel_parameter resource](kernel_parameter/index) * [launchd_service resource](launchd_service/index) * [limits_conf resource](limits_conf/index) * [login_defs resource](login_defs/index) * [mount resource](mount/index) * [nginx resource](nginx/index) * [nginx_conf resource](nginx_conf/index) * [ntp_conf resource](ntp_conf/index) * [packages resource](packages/index) * [passwd resource](passwd/index) * [postgres_hba_conf resource](postgres_hba_conf/index) * [postgres_ident_conf resource](postgres_ident_conf/index) * [rabbitmq_config resource](rabbitmq_config/index) * [runit_service resource](runit_service/index) * [selinux resource](selinux/index) * [shadow resource](shadow/index) * [ssh_config resource](ssh_config/index) * [sshd_config resource](sshd_config/index) * [systemd_service resource](systemd_service/index) * [sysv_service resource](sysv_service/index) * [upstart_service resource](upstart_service/index) * [virtualization resource](virtualization/index) * [xinetd_conf resource](xinetd_conf/index) * [yum resource](yum/index) * [zfs_dataset resource](zfs_dataset/index) * [zfs_pool resource](zfs_pool/index) ### Windows The following resources work on Windows operating systems. * [chocolatey_package resource](chocolatey_package/index) * [iis_app resource](iis_app/index) * [iis_site resource](iis_site/index) * [mssql_session resource](mssql_session/index) * [oneget resource](oneget/index) * [powershell resource](powershell/index) * [registry_key resource](registry_key/index) * [security_identifier resource](security_identifier/index) * [security_policy resource](security_policy/index) * [vbscript resource](vbscript/index) * [windows_feature resource](windows_feature/index) * [windows_firewall resource](windows_firewall/index) * [windows_firewall_rule resource](windows_firewall_rule/index) * [windows_hotfix resource](windows_hotfix/index) * [windows_task resource](windows_task/index) * [wmi resource](wmi/index) AWS --- * [aws_alb resource](aws_alb/index) * [aws_albs resource](aws_albs/index) * [aws_auto_scaling_group resource](aws_auto_scaling_group/index) * [aws_auto_scaling_groups resource](aws_auto_scaling_groups/index) * [aws_cloudformation_stack resource](aws_cloudformation_stack/index) * [aws_cloudtrail_trail resource](aws_cloudtrail_trail/index) * [aws_cloudtrail_trails resource](aws_cloudtrail_trails/index) * [aws_cloudwatch_alarm resource](aws_cloudwatch_alarm/index) * [aws_cloudwatch_log_group resource](aws_cloudwatch_log_group/index) * [aws_cloudwatch_log_metric_filter resource](aws_cloudwatch_log_metric_filter/index) * [aws_config_delivery_channel resource](aws_config_delivery_channel/index) * [aws_config_recorder resource](aws_config_recorder/index) * [aws_db_subnet_group resource](aws_db_subnet_group/index) * [aws_db_subnet_groups resource](aws_db_subnet_groups/index) * [aws_dhcp_options resource](aws_dhcp_options/index) * [aws_dynamodb_table resource](aws_dynamodb_table/index) * [aws_ebs_volume resource](aws_ebs_volume/index) * [aws_ebs_volumes resource](aws_ebs_volumes/index) * [aws_ec2_instance resource](aws_ec2_instance/index) * [aws_ec2_instances resource](aws_ec2_instances/index) * [aws_ecr resource](aws_ecr/index) * [aws_ecr_image resource](aws_ecr_image/index) * [aws_ecr_images resource](aws_ecr_images/index) * [aws_ecr_repositories resource](aws_ecr_repositories/index) * [aws_ecr_repository resource](aws_ecr_repository/index) * [aws_ecs_cluster resource](aws_ecs_cluster/index) * [aws_ecs_clusters resource](aws_ecs_clusters/index) * [aws_efs_file_system resource](aws_efs_file_system/index) * [aws_efs_file_systems resource](aws_efs_file_systems/index) * [aws_eks_cluster resource](aws_eks_cluster/index) * [aws_eks_clusters resource](aws_eks_clusters/index) * [aws_elasticache_cluster resource](aws_elasticache_cluster/index) * [aws_elasticache_cluster_node resource](aws_elasticache_cluster_node/index) * [aws_elasticache_clusters resource](aws_elasticache_clusters/index) * [aws_elb resource](aws_elb/index) * [aws_elbs resource](aws_elbs/index) * [aws_flow_log resource](aws_flow_log/index) * [aws_hosted_zone resource](aws_hosted_zone/index) * [aws_hosted_zones resource](aws_hosted_zones/index) * [aws_iam_access_key resource](aws_iam_access_key/index) * [aws_iam_access_keys resource](aws_iam_access_keys/index) * [aws_iam_account_alias resource](aws_iam_account_alias/index) * [aws_iam_group resource](aws_iam_group/index) * [aws_iam_groups resource](aws_iam_groups/index) * [aws_iam_inline_policy resource](aws_iam_inline_policy/index) * [aws_iam_password_policy resource](aws_iam_password_policy/index) * [aws_iam_policies resource](aws_iam_policies/index) * [aws_iam_policy resource](aws_iam_policy/index) * [aws_iam_role resource](aws_iam_role/index) * [aws_iam_roles resource](aws_iam_roles/index) * [aws_iam_root_user resource](aws_iam_root_user/index) * [aws_iam_saml_provider resource](aws_iam_saml_provider/index) * [aws_iam_saml_providers resource](aws_iam_saml_providers/index) * [aws_iam_user resource](aws_iam_user/index) * [aws_iam_users resource](aws_iam_users/index) * [aws_internet_gateway resource](aws_internet_gateway/index) * [aws_internet_gateways resource](aws_internet_gateways/index) * [aws_kms_key resource](aws_kms_key/index) * [aws_kms_keys resource](aws_kms_keys/index) * [aws_lambda resource](aws_lambda/index) * [aws_lambdas resource](aws_lambdas/index) * [aws_launch_configuration resource](aws_launch_configuration/index) * [aws_nat_gateway resource](aws_nat_gateway/index) * [aws_nat_gateways resource](aws_nat_gateways/index) * [aws_organizations_member resource](aws_organizations_member/index) * [aws_rds_cluster resource](aws_rds_cluster/index) * [aws_rds_clusters resource](aws_rds_clusters/index) * [aws_rds_instance resource](aws_rds_instance/index) * [aws_rds_instances resource](aws_rds_instances/index) * [aws_region resource](aws_region/index) * [aws_regions resource](aws_regions/index) * [aws_route_table resource](aws_route_table/index) * [aws_route_tables resource](aws_route_tables/index) * [aws_s3_bucket resource](aws_s3_bucket/index) * [aws_s3_bucket_object resource](aws_s3_bucket_object/index) * [aws_s3_buckets resource](aws_s3_buckets/index) * [aws_security_group resource](aws_security_group/index) * [aws_security_groups resource](aws_security_groups/index) * [aws_sns_subscription resource](aws_sns_subscription/index) * [aws_sns_topic resource](aws_sns_topic/index) * [aws_sns_topics resource](aws_sns_topics/index) * [aws_sqs_queue resource](aws_sqs_queue/index) * [aws_sqs_queues](aws_sqs_queues/index) * [aws_ssm_parameter resource](aws_ssm_parameter/index) * [aws_ssm_parameters resource](aws_ssm_parameters/index) * [aws_sts_caller_identity resource](aws_sts_caller_identity/index) * [aws_subnet resource](aws_subnet/index) * [aws_subnets resource](aws_subnets/index) * [aws_transit_gateway resource](aws_transit_gateway/index) * [aws_vpc resource](aws_vpc/index) * [aws_vpcs resource](aws_vpcs/index) Azure ----- * [azure_generic_resource resource](azure_generic_resource/index) * [azure_resource_group resource](azure_resource_group/index) * [azure_virtual_machine resource](azure_virtual_machine/index) * [azure_virtual_machine_data_disk resource](azure_virtual_machine_data_disk/index) * [azurerm_ad_user resource](azurerm_ad_user/index) * [azurerm_ad_users resource](azurerm_ad_users/index) * [azurerm_aks_cluster resource](azurerm_aks_cluster/index) * [azurerm_aks_clusters resource](azurerm_aks_clusters/index) * [azurerm_cosmosdb_database_account resource](azurerm_cosmosdb_database_account/index) * [azurerm_event_hub_authorization_rule resource](azurerm_event_hub_authorization_rule/index) * [azurerm_event_hub_event_hub resource](azurerm_event_hub_event_hub/index) * [azurerm_event_hub_namespace resource](azurerm_event_hub_namespace/index) * [azurerm_iothub resource](azurerm_iothub/index) * [azurerm_iothub_event_hub_consumer_group resource](azurerm_iothub_event_hub_consumer_group/index) * [azurerm_iothub_event_hub_consumer_groups resource](azurerm_iothub_event_hub_consumer_groups/index) * [azurerm_key_vault resource](azurerm_key_vault/index) * [azurerm_key_vault_key resource](azurerm_key_vault_key/index) * [azurerm_key_vault_keys resource](azurerm_key_vault_keys/index) * [azurerm_key_vault_secret resource](azurerm_key_vault_secret/index) * [azurerm_key_vault_secrets resource](azurerm_key_vault_secrets/index) * [azurerm_key_vaults resource](azurerm_key_vaults/index) * [azurerm_load_balancer resource](azurerm_load_balancer/index) * [azurerm_load_balancers resource](azurerm_load_balancers/index) * [azurerm_locks resource](azurerm_locks/index) * [azurerm_management_group resource](azurerm_management_group/index) * [azurerm_management_groups resource](azurerm_management_groups/index) * [azurerm_monitor_activity_log_alert resource](azurerm_monitor_activity_log_alert/index) * [azurerm_monitor_activity_log_alerts resource](azurerm_monitor_activity_log_alerts/index) * [azurerm_monitor_log_profile resource](azurerm_monitor_log_profile/index) * [azurerm_monitor_log_profiles resource](azurerm_monitor_log_profiles/index) * [azurerm_mysql_database resource](azurerm_mysql_database/index) * [azurerm_mysql_databases resource](azurerm_mysql_databases/index) * [azurerm_mysql_server resource](azurerm_mysql_server/index) * [azurerm_mysql_servers resource](azurerm_mysql_servers/index) * [azurerm_network_interface resource](azurerm_network_interface/index) * [azurerm_network_interfaces resource](azurerm_network_interfaces/index) * [azurerm_network_security_group resource](azurerm_network_security_group/index) * [azurerm_network_security_groups resource](azurerm_network_security_groups/index) * [azurerm_network_watcher resource](azurerm_network_watcher/index) * [azurerm_network_watchers resource](azurerm_network_watchers/index) * [azurerm_postgresql_database resource](azurerm_postgresql_database/index) * [azurerm_postgresql_databases resource](azurerm_postgresql_databases/index) * [azurerm_postgresql_server resource](azurerm_postgresql_server/index) * [azurerm_postgresql_servers resource](azurerm_postgresql_servers/index) * [azurerm_resource_groups resource](azurerm_resource_groups/index) * [azurerm_role_definition resource](azurerm_role_definition/index) * [azurerm_role_definitions resource](azurerm_role_definitions/index) * [azurerm_security_center_policies resource](azurerm_security_center_policies/index) * [azurerm_security_center_policy resource](azurerm_security_center_policy/index) * [azurerm_sql_database resource](azurerm_sql_database/index) * [azurerm_sql_databases resource](azurerm_sql_databases/index) * [azurerm_sql_server resource](azurerm_sql_server/index) * [azurerm_sql_servers resource](azurerm_sql_servers/index) * [azurerm_storage_account_blob_container resource](azurerm_storage_account_blob_container/index) * [azurerm_storage_account_blob_containers resource](azurerm_storage_account_blob_containers/index) * [azurerm_subnet resource](azurerm_subnet/index) * [azurerm_subnets resource](azurerm_subnets/index) * [azurerm_subscription resource](azurerm_subscription/index) * [azurerm_virtual_machine resource](azurerm_virtual_machine/index) * [azurerm_virtual_machine_disk resource](azurerm_virtual_machine_disk/index) * [azurerm_virtual_machine_disks resource](azurerm_virtual_machine_disks/index) * [azurerm_virtual_machines resource](azurerm_virtual_machines/index) * [azurerm_virtual_network resource](azurerm_virtual_network/index) * [azurerm_virtual_networks resource](azurerm_virtual_networks/index) * [azurerm_webapp resource](azurerm_webapp/index) * [azurerm_webapps resource](azurerm_webapps/index) GCP --- * [google_access_context_manager_access_policies resource](google_access_context_manager_access_policies/index) * [google_access_context_manager_access_policy resource](google_access_context_manager_access_policy/index) * [google_access_context_manager_service_perimeter resource](google_access_context_manager_service_perimeter/index) * [google_access_context_manager_service_perimeters resource](google_access_context_manager_service_perimeters/index) * [google_appengine_standard_app_version resource](google_appengine_standard_app_version/index) * [google_appengine_standard_app_versions resource](google_appengine_standard_app_versions/index) * [google_bigquery_dataset resource](google_bigquery_dataset/index) * [google_bigquery_datasets resource](google_bigquery_datasets/index) * [google_bigquery_table resource](google_bigquery_table/index) * [google_bigquery_tables resource](google_bigquery_tables/index) * [google_billing_project_billing_info resource](google_billing_project_billing_info/index) * [google_cloud_scheduler_job resource](google_cloud_scheduler_job/index) * [google_cloud_scheduler_jobs resource](google_cloud_scheduler_jobs/index) * [google_cloudbuild_trigger resource](google_cloudbuild_trigger/index) * [google_cloudbuild_triggers resource](google_cloudbuild_triggers/index) * [google_cloudfunctions_cloud_function resource](google_cloudfunctions_cloud_function/index) * [google_cloudfunctions_cloud_functions resource](google_cloudfunctions_cloud_functions/index) * [google_compute_address resource](google_compute_address/index) * [google_compute_addresses resource](google_compute_addresses/index) * [google_compute_autoscaler resource](google_compute_autoscaler/index) * [google_compute_autoscalers resource](google_compute_autoscalers/index) * [google_compute_backend_bucket resource](google_compute_backend_bucket/index) * [google_compute_backend_buckets resource](google_compute_backend_buckets/index) * [google_compute_backend_service resource](google_compute_backend_service/index) * [google_compute_backend_services resource](google_compute_backend_services/index) * [google_compute_disk resource](google_compute_disk/index) * [google_compute_disks resource](google_compute_disks/index) * [google_compute_firewall resource](google_compute_firewall/index) * [google_compute_firewalls resource](google_compute_firewalls/index) * [google_compute_forwarding_rule resource](google_compute_forwarding_rule/index) * [google_compute_forwarding_rules resource](google_compute_forwarding_rules/index) * [google_compute_global_address resource](google_compute_global_address/index) * [google_compute_global_addresses resource](google_compute_global_addresses/index) * [google_compute_global_forwarding_rule resource](google_compute_global_forwarding_rule/index) * [google_compute_global_forwarding_rules resource](google_compute_global_forwarding_rules/index) * [google_compute_health_check resource](google_compute_health_check/index) * [google_compute_health_checks resource](google_compute_health_checks/index) * [google_compute_http_health_check resource](google_compute_http_health_check/index) * [google_compute_http_health_checks resource](google_compute_http_health_checks/index) * [google_compute_https_health_check resource](google_compute_https_health_check/index) * [google_compute_https_health_checks resource](google_compute_https_health_checks/index) * [google_compute_image resource](google_compute_image/index) * [google_compute_instance resource](google_compute_instance/index) * [google_compute_instance_group resource](google_compute_instance_group/index) * [google_compute_instance_group_manager resource](google_compute_instance_group_manager/index) * [google_compute_instance_group_managers resource](google_compute_instance_group_managers/index) * [google_compute_instance_groups resource](google_compute_instance_groups/index) * [google_compute_instance_template resource](google_compute_instance_template/index) * [google_compute_instance_templates resource](google_compute_instance_templates/index) * [google_compute_instances resource](google_compute_instances/index) * [google_compute_network resource](google_compute_network/index) * [google_compute_network_endpoint_group resource](google_compute_network_endpoint_group/index) * [google_compute_network_endpoint_groups resource](google_compute_network_endpoint_groups/index) * [google_compute_networks resource](google_compute_networks/index) * [google_compute_node_group resource](google_compute_node_group/index) * [google_compute_node_groups resource](google_compute_node_groups/index) * [google_compute_node_template resource](google_compute_node_template/index) * [google_compute_node_templates resource](google_compute_node_templates/index) * [google_compute_project_info resource](google_compute_project_info/index) * [google_compute_region resource](google_compute_region/index) * [google_compute_region_backend_service resource](google_compute_region_backend_service/index) * [google_compute_region_backend_services resource](google_compute_region_backend_services/index) * [google_compute_region_instance_group_manager resource](google_compute_region_instance_group_manager/index) * [google_compute_region_instance_group_managers resource](google_compute_region_instance_group_managers/index) * [google_compute_regional_disk resource](google_compute_regional_disk/index) * [google_compute_regions resource](google_compute_regions/index) * [google_compute_route resource](google_compute_route/index) * [google_compute_router resource](google_compute_router/index) * [google_compute_router_nat resource](google_compute_router_nat/index) * [google_compute_router_nats resource](google_compute_router_nats/index) * [google_compute_routers resource](google_compute_routers/index) * [google_compute_routes resource](google_compute_routes/index) * [google_compute_security_policies resource](google_compute_security_policies/index) * [google_compute_security_policy resource](google_compute_security_policy/index) * [google_compute_snapshot resource](google_compute_snapshot/index) * [google_compute_snapshots resource](google_compute_snapshots/index) * [google_compute_ssl_certificate resource](google_compute_ssl_certificate/index) * [google_compute_ssl_certificates resource](google_compute_ssl_certificates/index) * [google_compute_ssl_policies resource](google_compute_ssl_policies/index) * [google_compute_ssl_policy resource](google_compute_ssl_policy/index) * [google_compute_subnetwork resource](google_compute_subnetwork/index) * [google_compute_subnetwork_iam_binding resource](google_compute_subnetwork_iam_binding/index) * [google_compute_subnetwork_iam_policy resource](google_compute_subnetwork_iam_policy/index) * [google_compute_subnetworks resource](google_compute_subnetworks/index) * [google_compute_target_http_proxies resource](google_compute_target_http_proxies/index) * [google_compute_target_http_proxy resource](google_compute_target_http_proxy/index) * [google_compute_target_https_proxies resource](google_compute_target_https_proxies/index) * [google_compute_target_https_proxy resource](google_compute_target_https_proxy/index) * [google_compute_target_pool resource](google_compute_target_pool/index) * [google_compute_target_pools resource](google_compute_target_pools/index) * [google_compute_target_tcp_proxies resource](google_compute_target_tcp_proxies/index) * [google_compute_target_tcp_proxy resource](google_compute_target_tcp_proxy/index) * [google_compute_url_map resource](google_compute_url_map/index) * [google_compute_url_maps resource](google_compute_url_maps/index) * [google_compute_vpn_tunnel resource](google_compute_vpn_tunnel/index) * [google_compute_vpn_tunnels resource](google_compute_vpn_tunnels/index) * [google_compute_zone resource](google_compute_zone/index) * [google_compute_zones resource](google_compute_zones/index) * [google_container_cluster resource](google_container_cluster/index) * [google_container_clusters resource](google_container_clusters/index) * [google_container_node_pool resource](google_container_node_pool/index) * [google_container_node_pools resource](google_container_node_pools/index) * [google_container_regional_cluster resource](google_container_regional_cluster/index) * [google_container_regional_clusters resource](google_container_regional_clusters/index) * [google_container_regional_node_pool resource](google_container_regional_node_pool/index) * [google_container_regional_node_pools resource](google_container_regional_node_pools/index) * [google_dataproc_cluster resource](google_dataproc_cluster/index) * [google_dataproc_clusters resource](google_dataproc_clusters/index) * [google_dns_managed_zone resource](google_dns_managed_zone/index) * [google_dns_managed_zones resource](google_dns_managed_zones/index) * [google_dns_resource_record_set resource](google_dns_resource_record_set/index) * [google_dns_resource_record_sets resource](google_dns_resource_record_sets/index) * [google_filestore_instance resource](google_filestore_instance/index) * [google_filestore_instances resource](google_filestore_instances/index) * [google_iam_custom_role resource](google_iam_custom_role/index) * [google_iam_custom_roles resource](google_iam_custom_roles/index) * [google_iam_organization_custom_role resource](google_iam_organization_custom_role/index) * [google_iam_organization_custom_roles resource](google_iam_organization_custom_roles/index) * [google_iam_service_account resource](google_iam_service_account/index) * [google_iam_service_account_key resource](google_iam_service_account_key/index) * [google_iam_service_account_keys resource](google_iam_service_account_keys/index) * [google_iam_service_accounts resource](google_iam_service_accounts/index) * [google_kms_crypto_key resource](google_kms_crypto_key/index) * [google_kms_crypto_key_iam_binding resource](google_kms_crypto_key_iam_binding/index) * [google_kms_crypto_key_iam_bindings resource](google_kms_crypto_key_iam_bindings/index) * [google_kms_crypto_key_iam_policy resource](google_kms_crypto_key_iam_policy/index) * [google_kms_crypto_keys resource](google_kms_crypto_keys/index) * [google_kms_key_ring resource](google_kms_key_ring/index) * [google_kms_key_ring_iam_binding resource](google_kms_key_ring_iam_binding/index) * [google_kms_key_ring_iam_bindings resource](google_kms_key_ring_iam_bindings/index) * [google_kms_key_ring_iam_policy resource](google_kms_key_ring_iam_policy/index) * [google_kms_key_rings resource](google_kms_key_rings/index) * [google_logging_folder_exclusion resource](google_logging_folder_exclusion/index) * [google_logging_folder_exclusions resource](google_logging_folder_exclusions/index) * [google_logging_folder_log_sink resource](google_logging_folder_log_sink/index) * [google_logging_folder_log_sinks resource](google_logging_folder_log_sinks/index) * [google_logging_organization_log_sink resource](google_logging_organization_log_sink/index) * [google_logging_organization_log_sinks resource](google_logging_organization_log_sinks/index) * [google_logging_project_exclusion resource](google_logging_project_exclusion/index) * [google_logging_project_exclusions resource](google_logging_project_exclusions/index) * [google_logging_project_sink resource](google_logging_project_sink/index) * [google_logging_project_sinks resource](google_logging_project_sinks/index) * [google_ml_engine_model resource](google_ml_engine_model/index) * [google_ml_engine_models resource](google_ml_engine_models/index) * [google_organization resource](google_organization/index) * [google_organization_iam_binding resource](google_organization_iam_binding/index) * [google_organization_iam_policy resource](google_organization_iam_policy/index) * [google_organization_policy resource](google_organization_policy/index) * [google_organizations resource](google_organizations/index) * [google_project resource](google_project/index) * [google_project_alert_policies resource](google_project_alert_policies/index) * [google_project_alert_policy resource](google_project_alert_policy/index) * [google_project_alert_policy_condition resource](google_project_alert_policy_condition/index) * [google_project_iam_binding resource](google_project_iam_binding/index) * [google_project_iam_bindings resource](google_project_iam_bindings/index) * [google_project_iam_custom_role resource](google_project_iam_custom_role/index) * [google_project_iam_custom_roles resource](google_project_iam_custom_roles/index) * [google_project_iam_policy resource](google_project_iam_policy/index) * [google_project_logging_audit_config resource](google_project_logging_audit_config/index) * [google_project_metric resource](google_project_metric/index) * [google_project_metrics resource](google_project_metrics/index) * [google_project_service resource](google_project_service/index) * [google_project_services resource](google_project_services/index) * [google_projects resource](google_projects/index) * [google_pubsub_subscription resource](google_pubsub_subscription/index) * [google_pubsub_subscription_iam_binding resource](google_pubsub_subscription_iam_binding/index) * [google_pubsub_subscription_iam_policy resource](google_pubsub_subscription_iam_policy/index) * [google_pubsub_subscriptions resource](google_pubsub_subscriptions/index) * [google_pubsub_topic resource](google_pubsub_topic/index) * [google_pubsub_topic_iam_binding resource](google_pubsub_topic_iam_binding/index) * [google_pubsub_topic_iam_policy resource](google_pubsub_topic_iam_policy/index) * [google_pubsub_topics resource](google_pubsub_topics/index) * [google_redis_instance resource](google_redis_instance/index) * [google_redis_instances resource](google_redis_instances/index) * [google_resourcemanager_folder resource](google_resourcemanager_folder/index) * [google_resourcemanager_folder_iam_binding resource](google_resourcemanager_folder_iam_binding/index) * [google_resourcemanager_folder_iam_policy resource](google_resourcemanager_folder_iam_policy/index) * [google_resourcemanager_folders resource](google_resourcemanager_folders/index) * [google_resourcemanager_organization_policy resource](google_resourcemanager_organization_policy/index) * [google_resourcemanager_project_iam_binding resource](google_resourcemanager_project_iam_binding/index) * [google_resourcemanager_project_iam_policy resource](google_resourcemanager_project_iam_policy/index) * [google_runtime_config_config resource](google_runtime_config_config/index) * [google_runtime_config_config_iam_binding resource](google_runtime_config_config_iam_binding/index) * [google_runtime_config_config_iam_policy resource](google_runtime_config_config_iam_policy/index) * [google_runtime_config_configs resource](google_runtime_config_configs/index) * [google_runtime_config_variable resource](google_runtime_config_variable/index) * [google_runtime_config_variables resource](google_runtime_config_variables/index) * [google_service_account resource](google_service_account/index) * [google_service_account_key resource](google_service_account_key/index) * [google_service_account_keys resource](google_service_account_keys/index) * [google_service_accounts resource](google_service_accounts/index) * [google_sourcerepo_repositories resource](google_sourcerepo_repositories/index) * [google_sourcerepo_repository resource](google_sourcerepo_repository/index) * [google_spanner_database resource](google_spanner_database/index) * [google_spanner_databases resource](google_spanner_databases/index) * [google_spanner_instance resource](google_spanner_instance/index) * [google_spanner_instance_iam_binding resource](google_spanner_instance_iam_binding/index) * [google_spanner_instance_iam_policy resource](google_spanner_instance_iam_policy/index) * [google_spanner_instances resource](google_spanner_instances/index) * [google_sql_database_instance resource](google_sql_database_instance/index) * [google_sql_database_instances resource](google_sql_database_instances/index) * [google_sql_user resource](google_sql_user/index) * [google_sql_users resource](google_sql_users/index) * [google_storage_bucket resource](google_storage_bucket/index) * [google_storage_bucket_acl resource](google_storage_bucket_acl/index) * [google_storage_bucket_iam_binding resource](google_storage_bucket_iam_binding/index) * [google_storage_bucket_iam_bindings resource](google_storage_bucket_iam_bindings/index) * [google_storage_bucket_iam_policy resource](google_storage_bucket_iam_policy/index) * [google_storage_bucket_object resource](google_storage_bucket_object/index) * [google_storage_bucket_objects resource](google_storage_bucket_objects/index) * [google_storage_buckets resource](google_storage_buckets/index) * [google_storage_default_object_acl resource](google_storage_default_object_acl/index) * [google_storage_object_acl resource](google_storage_object_acl/index) * [google_user resource](google_user/index) * [google_users resource](google_users/index) Habitat ------- * [habitat_package resource](habitat_package/index) * [habitat_packages resource](habitat_packages/index) * [habitat_service resource](habitat_service/index) * [habitat_services resource](habitat_services/index) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/Chef Infra Server API ===================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/api_chef_server.md) The Chef Infra Server API is a REST API that provides access to objects on the Chef Infra Server, including nodes, environments, roles, users, organizations, cookbooks (and cookbook versions), and is used to manage an API client list and the associated RSA public key-pairs. Requirements ------------ The Chef Infra Server API has the following requirements: * The `Accept` header must be set to `application/json`. * For `PUT` and `POST` requests, the `Content-Type` header must be set to `application/json`. * The `X-Chef-Version` header must be set to the version of the Chef Infra Server API that is being used. * A request must be signed by adding authentication headers. ‘Mixlib::Authentication’ may be used to sign requests. * A request must be well-formatted. The easiest way to ensure a well-formatted request is to use the `Chef::ServerAPI` library. Authentication Headers ---------------------- Authentication to the Chef Infra Server requires a specific set of HTTP headers signed using a private key that is associated with the client making the request. The request is authorized if the Chef Infra Server can verify the signature using the public key. Only authorized actions are allowed. Note Most authentication requests made to the Chef Infra Server are abstracted from the user. Such as when using knife or the Chef Infra Server user interface. In some cases, such as when using the `knife exec` subcommand, the authentication requests need to be made more explicitly, but still in a way that does not require authentication headers. In a few cases, such as when using arbitrary Ruby code, a Chef Infra Server API client, or cURL, it may be necessary to include the full authentication header as part of the request to the Chef Infra Server. ### Required Headers The following authentication headers are required: | Feature | Description | | --- | --- | | `Accept` | The format in which response data from the Chef Infra Server is provided. This header must be set to `application/json`. | | `Content-Type` | The format in which data is sent to the Chef Infra Server. This header is required for `PUT` and `POST` requests and must be set to `application/json`. | | `Host` | The host name (and port number) to which a request is sent. (Port number `80` does not need to be specified.) For example: `api.chef.io` (which is the same as `api.chef.io:80`) or `api.chef.io:443`. | | `Method` | The method from the request. | | `Path` | Omit for Authentication Version 1. Specify for Authentication Version 1.3 | | `X-Chef-Version` | The version of the Chef Infra Client executable from which a request is made. This header ensures that responses are in the correct format. For example: `12.0.2` or `11.16.x`. | | `X-Ops-Authorization-N` | One (or more) 60 character segments that comprise the canonical header. A canonical header is signed with the private key used by the client machine from which the request is sent, and is also encoded using Base64. If more than one segment is required, each should be named sequentially, e.g. `X-Ops-Authorization-1`, `X-Ops-Authorization-2`, `X-Ops-Authorization-N`, where `N` represents the integer used by the last header that is part of the request. | | `X-Ops-Content-Hash` | For API Version 1. The result of the SHA-1 hash of the request body encoded using Base64. Base64 encoding should have line breaks every 60 characters. For API Version 1.3. The result of the SHA-256 hash of the request body encoded using Base64. Base64 encoding should have line breaks every 60 characters. | | `X-Ops-Server-API-Version` | Use `X-Ops-Server-API-Version` to specify the version of the Chef Infra Server API. For example: `X-Ops-Server-API-Version: 1`. `X-Ops-Server-API-Version: 0` is supported for use with Chef Infra Server version 12, but will be deprecated as part of the next major release. | | `X-Ops-Sign` | Set this header to the following value: `algorithm=sha1,version=1.0` or `version=1.3`. | | `X-Ops-Timestamp` | The timestamp, in ISO-8601 format and with UTC indicated by a trailing `Z` and separated by the character `T`. For example: `2013-03-10T14:14:44Z`. | | `X-Ops-UserId` | The name of the API client whose private key will be used to create the authorization header. | Note Use `X-Ops-Server-API-Info` to identify the version of the Chef Infra Server API. #### Canonical Header Format 1.0 using SHA-1 The signed headers are encrypted using the OpenSSL RSA_private_encrypt method and encoded in Base64. The signed headers are used to create one or more X-Ops-Authorization-N headers of 60 character segments. The canonical header should be created by concatenating the following headers, encrypting and encoding: ``` Method:HTTP_METHOD Hashed Path:HASHED_PATH X-Ops-Content-Hash:HASHED_BODY X-Ops-Timestamp:TIME X-Ops-UserId:USERID ``` where: * `HTTP_METHOD` is the method used in the API request (`GET`, `POST`, and so on) * `HASHED_PATH` is the path of the request: `/organizations/NAME/name_of_endpoint`. The `HASHED_PATH` must be hashed using SHA-1 and encoded using Base64, must not have repeated forward slashes (`/`), must not end in a forward slash (unless the path is `/`), and must not include a query string. * `X-Ops-Content-Hash` is the Base64 encoded SHA256 hash of the json body of the request. * `X-Ops-Timestamp` UTC time in RFC3339 format. * `X-Ops-UserId` is the plain text client or user name. The Chef Infra Server decrypts this header and ensures its content matches the content of the non-encrypted headers that were in the request. The timestamp of the message is checked to ensure the request was received within a reasonable amount of time. One approach generating the signed headers is to use [mixlib-authentication](https://github.com/chef/mixlib-authentication), which is a class-based header signing authentication object similar to the one used by Chef Infra Client. ##### Example The following example shows an authentication request: ``` GET /organizations/NAME/nodes HTTP/1.1 Accept: application/json Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3 Host: api.chef.io:443 User-Agent: Chef Knife/12.0.2 (ruby-2.1.1-p320; ohai-8.0.0; x86_64-darwin12.0.2; +http://chef.io) X-Chef-Version: 12.0.2 X-Ops-Authorization-1: BE3NnBritishaf3ifuwLSPCCYasdfXaRN5oZb4c6hbW0aefI X-Ops-Authorization-2: sL4j1qtEZzi/2WeF67UuytdsdfgbOc5CjgECQwqrym9gCUON X-Ops-Authorization-3: yf0p7PrLRCNasdfaHhQ2LWSea+kTcu0dkasdfvaTghfCDC57 X-Ops-Authorization-4: 155i+ZlthfasfasdffukusbIUGBKUYFjhbvcds3k0i0gqs+V X-Ops-Authorization-5: /sLcR7JjQky7sdafIHNfsBQrISktNPower1236hbFIayFBx3 X-Ops-Authorization-6: nodilAGMb166@haC/fttwlWQ2N1LasdqqGomRedtyhSqXA== X-Ops-Content-Hash: 2jmj7l5rfasfgSw0ygaVb/vlWAghYkK/YBwk= X-Ops-Server-API-Info: 1 X-Ops-Sign: algorithm=sha1;version=1.0; X-Ops-Userid: user_id X-Ops-Timestamp: 2014-12-12T17:13:28Z ``` #### Canonical Header Format 1.3 using SHA-256 Chef Infra Server versions 12.4.0 and above support signing protocol version 1.3, which adds support for SHA-256 algorithms. It can be enabled on Chef Infra Client via the `client.rb` file: ``` authentication_protocol_version = '1.3' ``` And for Chef’s knife CLI via `config.rb`: ``` knife[:authentication_protocol_version] = '1.3' ``` To create the signed headers for direct use. Gather the following headers in the order listed, convert the signature headers to a concatenated string, sign and Base64 encode the result. The concatenation of signature headers is signed using the client RSA private key, with SHA-256 hashing and PKCS1v15 padding. Chop the Base64 encoded value into 60 character chunks and create X-Ops-Authorization-N headers with the chunks. ``` Method:HTTP_METHOD Path:PATH X-Ops-Content-Hash:HASHED_BODY X-Ops-Sign X-Ops-Timestamp:TIME X-Ops-UserId:USERID X-Ops-Server-API-Version ``` where: * `HTTP_METHOD` is the method used in the API request (`GET`, `POST`, &mldr;) * `PATH` is the path of the request: `/organizations/NAME/name_of_endpoint`. The value must not have repeated forward slashes (`/`), must not end in a forward slash (unless the path is `/`), and must not include a query string. * `X-Ops-Content-Hash` is the Base64 encoded SHA256 hash of the json body of the request. * `X-Ops-Sign` has the value “version=1.3”. * `X-Ops-Timestamp` UTC time in RFC3339 format. * `X-Ops-UserId` is the plain text client or user name. * `X-Ops-Server-API-Version` is the numeric value of the Chef Infra Server API. ##### Example The following example shows an authentication request: ``` GET /organizations/NAME/nodes HTTP/1.1 Accept: application/json Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3 Host: api.chef.io:443 Method: GET Path: /organizations/NAME/nodes User-Agent: Chef Knife/12.0.2 (ruby-2.1.1-p320; ohai-8.0.0; x86_64-darwin12.0.2; +http://chef.io) X-Chef-Version: 14.0.0 X-Ops-Content-Hash: 2jmj7l5rfasfgSw0ygaVb/vlWAghYkK/YBwk= X-Ops-Authorization-1: BE3NnBritishaf3ifuwLSPCCYasdfXaRN5oZb4c6hbW0aefI X-Ops-Authorization-2: sL4j1qtEZzi/2WeF67UuytdsdfgbOc5CjgECQwqrym9gCUON X-Ops-Authorization-3: yf0p7PrLRCNasdfaHhQ2LWSea+kTcu0dkasdfvaTghfCDC57 X-Ops-Authorization-4: 155i+ZlthfasfasdffukusbIUGBKUYFjhbvcds3k0i0gqs+V X-Ops-Authorization-5: /sLcR7JjQky7sdafIHNfsBQrISktNPower1236hbFIayFBx3 X-Ops-Authorization-6: nodilAGMb166@haC/fttwlWQ2N1LasdqqGomRedtyhSqXA== X-Ops-Server-API-Info: 1 X-Ops-Sign: version=1.3; X-Ops-Timestamp: 2014-12-12T17:13:28Z X-Ops-Userid: user_id ``` ### Knife API Requests A knife plugin is a set of one (or more) subcommands that can be added to knife to support additional functionality that is not built-in to the base set of knife subcommands. Many of the knife plugins are built by members of the Chef community and several of them are built and maintained by Chef. A knife plugin can be used to make authenticated API requests to the Chef Infra Server using the following methods: | Method | Description | | --- | --- | | `rest.delete_rest` | Use to delete an object from the Chef Infra Server. | | `rest.get_rest` | Use to get the details of an object on the Chef Infra Server. | | `rest.post_rest` | Use to add an object to the Chef Infra Server. | | `rest.put_rest` | Use to update an object on the Chef Infra Server. | For example: ``` module MyCommands class MyNodeDelete &lt; Chef::Knife #An implementation of knife node delete banner 'knife my node delete [NODE_NAME]' def run if name_args.length &lt; 1 show_usage ui.fatal('You must specify a node name.') exit 1 end nodename = name_args[0] api_endpoint = "nodes/#{nodename}" # Again, we could just call rest.delete_rest nodey = rest.get_rest(api_endpoint) ui.confirm("Do you really want to delete #{nodey}") nodey.destroy end end end ``` Global Endpoints ---------------- A global endpoint may be used to access all of the organizations on the Chef Infra Server. ### /authenticate_user The `/authenticate_user` endpoint has the following methods: `POST`. #### POST The `POST` method is used to authenticate a user. This endpoint is used by the Chef Identity Service to authenticate users of Chef Supermarket to the Chef Infra Server. This method has no parameters. **Request** ``` POST /authenticate_user ``` with a request body similar to: ``` { "username" : "grantmc", "password" : "p@ssw0rd" } ``` **Response** This method has no response body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, password, and that the correct key was used to sign the request. | ### /license Note This endpoint is used for information purposes only and to trigger a notification in the Chef management console about the number of licenses owned vs. the number of licenses that should be owned. No other action is taken and the functionality and behavior of the Chef Infra Server and any added component does not change. The `/license` endpoint has the following methods: `GET`. #### GET The `GET` method is used to get license information for the Chef Infra Server. This method has no parameters. **Request** ``` GET /license ``` This method has no request body. **Response** The response is similar to: ``` { "limit_exceeded": false, "node_license": 25, "node_count": 12, "upgrade_url": "https://www.chef.io/pricing" } ``` When `node_count` is greater than `node_license`, then `limit_exceeded` is `true` and the Chef management console will display a notification about this status. The way to resolve this is to visit the upgrade URL, add the appropriate number of licenses, and then update the configuration settings appropriately. The chef-server.rb file contains settings that can be used to edit the number of nodes that are under license: | Setting | Description | | --- | --- | | `license['nodes']` | The number of licensed nodes. Default value: `25`. | | `license['upgrade_url']` | The URL to visit for more information about how to update the number of nodes licensed for an organization. Default value: `"https://www.chef.io/pricing"`. | **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | ### /organizations The Chef Infra Server may contain multiple organizations. The `/organizations` endpoint has the following methods: `GET` and `POST`. Warning This endpoint may only be accessed by the `pivotal` user, which is created as part of the installation process for the Chef Infra Server. (See the “Query for Users and Orgs” example below for an example of how to access this endpoint with the `pivotal` user.) #### GET The `GET` method is used to get a list of organizations on the Chef Infra Server. **Request** ``` GET /organizations ``` **Response** The response is similar to: ``` { "org_name1": https://url/for/org_name1", "org_name2": https://url/for/org_name2" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create an organization on the Chef Infra Server. This method has no parameters. **Request** ``` POST /organizations ``` with a request body similar to: ``` { "name": "org_name1", "full_name": "Org_name1 Full Name" } ``` where: * `name` must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. * `full_name` must begin with a non-white space character and must be between 1 and 1023 characters. For example: `Chef Software, Inc.`. Note An organization isn’t usable until a user that belongs to the `admins` group is associated with the organization. **Response** The response is similar to: ``` { "clientname": "org_name1-validator", "private_key": "-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAx2uyX ...", "uri": "https://url/for/org_name1" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The request was successful. The organization was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The organization already exists. | ### /organizations/NAME An organization is a single instance of a Chef Infra Server, including all of the nodes that are managed by that Chef Infra Server and each of the workstations that will run knife and access the Chef Infra Server using the Chef Infra Server API. The `/organizations/NAME` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete an organization. This method has no parameters. **Request** ``` DELETE /organizations/NAME ``` **Response** The response is similar to: ``` { "name": "chef", "full_name": "Chef Software, Inc.", "guid": "f980d1asdfda0331235s00ff36862" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### GET The `GET` method is used to get the details for the named organization. This method has no parameters. **Request** ``` GET /organizations/NAME ``` **Response** The response is similar to: ``` { "name": "chef", "full_name": "<NAME>, Inc.", "guid": "f980d1asdfda0331235s00ff36862" ... } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### PUT The `PUT` method is used to update an organization definition. This method has no parameters. **Request** ``` PUT /organizations/NAME ``` with a request body similar to: ``` { "name": "chef", "full_name": "<NAME>, Inc." } ``` **Response** The response is similar to: ``` { "name": "chef", "full_name": "<NAME>, Inc.", "guid": "f980d1asdfda0331235s00ff36862" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `410` | Gone. Unable to update private key. | ### /_stats Use the `/_stats` endpoint to display statistics about connection pool usage inside Erchef, Postgresql, and the Erlang VM. The `_stats` endpoint uses Basic Authorization instead of the X-Ops-Authorization scheme usually used to connect to the Chef Infra Server. The default user used to query the `_stats` endpoint is `statsuser`. The password for the `statsuser` is available as the `opscode_erchef::stats_password` from the `chef-server-ctl show-service-credentials` command. The `/_stats` endpoint has the following method: `GET`. #### GET The `GET` method is used to get the statistics. This method has the following parameters: | Parameter | Description | | --- | --- | | `format=json` | Return results as JSON. | | `format=text` | Return results as text. | **Request** ``` GET /_stats ``` This method has no parameters. This method has no request body. The `/_stats` endpoint does not require authentication headers. **Response** The response body is similar to: ``` [ { "name": "erlang_vm_time_correction", "type": "UNTYPED", "help": "1 if time correction is enabled, otherwise 0.", "metrics": [ { "value": "1" } ] }, { "name": "erlang_vm_thread_pool_size", "type": "GAUGE", "help": "The number of async threads in the async thread pool used for asynchronous driver calls.", "metrics": [ { "value": "5" } ] }, ... { "name": "pg_stat_seq_scan", "type": "COUNTER", "help": "Number of sequential scans initiated on all tables", "metrics": [ { "value": "22147" } ] } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. | | `401` | Unauthorized. The user or password is not valid. | | `406` | Not Acceptable. An invalid format was requested. | ### /_status Use the `/_status` endpoint to check the status of communications between the front and back end servers. This endpoint is located at `/_status` on the front end servers. The `/_status` endpoint does not require authentication headers. #### GET The `GET` method is used to get the Chef Infra Server status details. **Request** ``` GET /_status ``` This method has no parameters. This method has no request body. **Response** The response will return something like the following: ``` { "status": "pong", "upstreams": { "service_name": "pong", "service_name": "pong", ... } "keygen": { "keys": 10, .... } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | All communications are OK. | | `500` | One (or more) services are down. For example: ``` { "status":"fail", "upstreams": { "service_name": "fail", "service_name": "pong", ... } } ``` | ### /users A user is an individual account that is created to allow access to the Chef Infra Server. For example: * A hosted Chef Infra Server account * The user that operates the workstation from which a Chef Infra Server will be managed The `/users` endpoint has the following methods: `GET` and `POST`. Warning This endpoint may only be accessed by the `pivotal` user, which is created as part of the installation process for the Chef Infra Server. (See the “Query for Users and Orgs” example below for an example of how to access this endpoint with the `pivotal` user.) Note This documentation for the `/users` endpoint is for version 1 of the Chef Infra Server API. Version 0 of the API has some differences in the request body and in the results. #### GET The `GET` method is used to get a list of users on the Chef Infra Server. This method has the following parameters: | Parameter | Description | | --- | --- | | `email=<EMAIL>` | Filter the users returned based on their email id. | | `external_authentication_uid=<EMAIL>` | Filter the users returned based on their external login id. | | `verbose=true` | Returns a user list with "email", "first_name", "last_name" fields. If this flag is set the email and external_authentication_uid parameters are ignored. | **Request** ``` GET /users ``` **Response** The response is similar to: ``` { "user1": "https://chef.example/users/user1", "user2": "https://chef.example/users/user2" } ``` The verbose response is similar to: ``` { "janechef": { "email": "<EMAIL>", "first_name": "jane", "last_name": "chef_user" }, "yaelsmith": { "email": "<EMAIL>", "first_name": "yeal", "last_name": "smith" } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | **Optional Filtering** Filtering on `/users` can be done with the `external_authentication_uid`. This is to support SAML authentication. As an example, to retrieve users whos `external_authentication_uid` is `<EMAIL>`, you would do the following: ``` GET /users?external_authentication_uid=jane%40doe.com ``` #### POST The `POST` method is used to create a user on the Chef Infra Server. This method has no parameters. **Request** ``` POST /users ``` with a request body similar to: ``` { "username": "robert-forster", "display_name": "robert", "email": "<EMAIL>", "first_name": "robert", "last_name": "forster", "middle_name": "", "password": "yeahpass", "create_key": true, "public_key": "-----<KEY>" } ``` where: * `username` must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores. For example: `chef`. `username` is required to be present and have a valid value. A valid username is a dot separated list of elements matching `a-z0-9!#$%&'*+/=?^_`{|}~-`. * `display_name` is required to be present. * `email` is required to be present and have a valid value. The email validation doesn’t allow for all unicode characters. * Either `external_authentication_uid` or `password` are required to be present and have a value. * During the POST, the `public_key` value will be broken out and resubmitted to the keys portion of the API in the latest Chef Infra Server versions. * Only one of the keys, `create_key` or `public_key`, may be specified. If `create_key` is specified, a default private key is generated and returned. **Response** The response is similar to: ``` { "uri": "https://chef.example/users/robert-forster", "chef_key": { "name": "default", "public_key": "-----BEGIN RSA PUBLIC KEY...", "expiration_date": "infinity", "uri": "https://chef.example/users/robert-forster/keys/default", "private_key": "-----BEGIN RSA PRIVATE KEY..." } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The user was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /users/NAME The `/users/USER_NAME` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. Note This documentation for the `/users/NAME` endpoint is for version 1 of the Chef Infra Server API. Version 0 of the API has some differences in the request body and in the results. #### DELETE The `DELETE` method is used to delete a user. This method has no parameters. **Request** ``` DELETE /users/USER_NAME ``` **Response** The response is similar to: ``` { } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return the details for a user. This method has no parameters. **Request** ``` GET /users/USER_NAME ``` **Response** The response is similar to: ``` { "username": "robert-forster", "display_name": "robert", "email": "<EMAIL>", "first_name": "robert", "last_name": "forster" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update a specific user. If values are not specified for the `PUT` method, the Chef Infra Server will use the existing values rather than assign default values. Note `PUT` supports renames. If `PUT /users/foo` is requested with `{ "username: "bar""}`, then it will rename `foo` to `bar` and all of the content previously associated with `foo` will be associated with `bar`. Note As of 12.1.0, the `"public_key"`, `"private_key"`, and `"create_key"` parameters in PUT requests to clients/users will cause a 400 response. This method has no parameters. **Request** ``` PUT /users/NAME ``` with a request body similar to: ``` { "username": "grant.mclennan", "display_name": "<NAME>", "email": "<EMAIL>", "first_name": "Grant", "last_name": "McLennan", "middle_name": "james", "public_key" : "-------- BEGIN PUBLIC KEY ----and a valid key here" } ``` **Response** The response is similar to: ``` { "uri": "https://chef.example/users/grant.mclennan", "chef_key": { "name": "default", "public_key": "-----BEGIN RSA PUBLIC KEY...", "expiration_date": "infinity", "uri": "https://chef.example/users/rober-forster/keys/default", "private_key": "" } } ``` If a new private key was generated, both the private and public keys are returned. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `201` | Created. The object was created. (This response code is only returned when the user is renamed.) | | `400` | Invalid. Invalid or missing values. Otherwise malformed request. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `409` | Conflict. This response code is only returned when a user is renamed, but a user already exists with that name. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /users/USER/keys/ The `/users/USER/keys` endpoint has the following methods: `GET` and `POST`. User keys are public RSA keys in the SSL `.pem` file format and are used for authentication. The Chef Infra Server does not save private keys for users. #### GET The `GET` method is used to retrieve all of the named user’s key identifiers, associated URIs, and expiry states. This method has no parameters. **Request** ``` GET /users/USER/keys/ ``` **Response** The response is similar to: ``` [ { "name" : "default", "uri" : "https://chef.example/users/USER/keys/default", "expired" : false }, { "name" : "key1", "uri" : "https://chef.example/users/USER/keys/key1", "expired" : false } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST The `POST` method is used to add a key for the specified user. This method has no parameters. **Request** ``` POST /users/USER/keys/ ``` with a request body similar to: ``` { "name" : "key1", "public_key" : "-------- BEGIN PUBLIC KEY ----and a valid key here", "expiration_date" : "infinity" } ``` **Response** The response is similar to: ``` { "name" : "key1", "uri" : "https://chapi_chef_server.mdef.example/users/user1/keys/key1", "expired": false } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The object was created. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /users/USER/keys/KEY The `/users/USER/keys/KEY` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete the specified key for the specified user. This method has no parameters. **Request** ``` DELETE /users/USER/keys/KEY ``` **Response** The response returns the information about the deleted key and is similar to: ``` { "name" : "default", "public_key" : "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date" : "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return details for a specific key for a specific user. This method has no parameters. **Request** ``` GET /users/USER/keys/KEY ``` **Response** The response is similar to: ``` { "name" : "default", "public_key" : "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date" : "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update one or more properties for a specific key for a specific user. This method has no parameters. **Request** ``` PUT /users/USER/keys/KEY ``` with a request body similar to: ``` { "name" : "new_key_name", "public_key" : "-------- BEGIN PUBLIC KEY ----and a valid key here", "expiration_date" : "2020-12-31T00:00:00Z" } ``` **Response** The response contains the updated information for the key, and is similar to: ``` { "name" : "new_key_name", "public_key" : "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date" : "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `201` | Created. The object was created. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | Organization Endpoints ---------------------- Each organization-specific authentication request must include `/organizations/NAME` as part of the name for the endpoint. For example, the full endpoint for getting a list of roles: ``` GET /organizations/NAME/roles ``` where `ORG_NAME` is the name of the organization. ### /association_requests Users may be invited to join organizations via the web user interface in the Chef management console or via the `POST` endpoint in the Chef Infra Server API. The `/association_requests` endpoint has the following methods: `DELETE`, `GET`, and `POST`. #### DELETE The `DELETE` method is used to delete a pending invitation. This method has no parameters. **Request** ``` DELETE /organizations/NAME/association_requests/ID ``` This method has no request body. **Response** The response is similar to: ``` { "id": "79b9382ab70e962907cee1747f9969a4", "orgname": "testorg", "username" "janedoe" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to get a list of pending invitations. This method has no parameters. **Request** ``` GET /organizations/NAME/association_requests ``` This method has no request body. **Response** The response returns a dictionary similar to: ``` [ { "id": "79b9382ab70e962907cee1747f9969a4", "username": "marygupta" }, { "id": "24t1432uf33x799382abb7096g8190b5", "username": "johnirving" } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create an invitation. This method has no parameters. **Request** ``` { "user": "billysmith" } POST /organizations/NAME/association_requests ``` **Response** The response is similar to: ``` { "uri": "https://chef.example/organizations/test/association_requests/79b9382ab70e962907cee1747f9969a4", "organization_user": { "username": "authorizeduser" }, "organization": { "name": "test" }, "user": { "email": "<EMAIL>", "first_name": "sally" } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. An invitation was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The invited user does not exist. | | `409` | Conflict. The object already exists. | ### /clients Use the `/clients` endpoint to manage clients and their associated RSA key-pairs. The `/clients` endpoint has the following methods: `GET` and `POST`. Note The clients should be managed using knife as opposed to the Chef Infra Server API. The interactions between clients, nodes and acls are tricky. #### GET The `GET` method is used to return a client list on the Chef Infra Server, including clients for nodes that have been registered with the Chef Infra Server, the chef-validator clients, and the chef-server-webui clients for the entire organization. This method has no parameters. **Request** ``` GET /organizations/NAME/clients ``` This method has no request body. **Response** The response is similar to: ``` { "org1-validator" : "https://chef.example/orgaizations/org1/clients/org1-validator", "client1" : "https://chef.example/orgaizations/org1/clients/client1" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create a new API client. Note As of 12.1.0, the `"admin"` parameter is no longer supported in client/user creation and support. If used in the `POST` or `PUT` of a client or user, the `"admin"` parameter is ignored. This method has no parameters. **Request** ``` POST /organizations/NAME/clients ``` with a request body similar to: ``` { "name": "name_of_API_client", "clientname": "name_of_API_client", "validator": true, "create_key": true } ``` where `name_of_API_client` is the name of the API client to be created and `admin` indicates whether the API client will be run as an admin API client. Either name or clientname needs to be specified. **Response** The response is similar to: ``` { "uri": "https://chef.example/orgaizations/org1/clients/client1", "chef_key": { "name": "default", "expiration_date": "infinity", "private_key": "-----BEGIN RSA PRIVATE KEY----- ...", "public_key": "-----BEGIN PUBLIC KEY----- ... ", "uri": "https://chef.example/orgaizations/org1/clients/client1/keys/default" } ``` Store the private key in a safe place. It will be required later (along with the client name) to access the Chef Infra Server when using the Chef Infra Server API. **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The client was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /clients/NAME The `/clients/NAME` endpoint is used to manage a specific client. This endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to remove a specific client. This method has no parameters. **Request** ``` DELETE /organizations/NAME/clients/NAME ``` This method has no request body. **Response** The response has no body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return a specific API client. This method has no parameters. **Request** ``` GET /organizations/NAME/clients/NAME ``` This method has no request body. **Response** The response is similar to: ``` { "name": "user1", "clientname": "user1", "orgname": "test", "json_class": "Chef::ApiClient", "chef_type": "client", "validator": "false" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update a specific client. If values are not specified for the `PUT` method, the Chef Infra Server will use the existing values rather than assign default values. Note `PUT` supports renames. If `PUT /client/foo` is requested with `{ "name: "bar""}`, then it will rename `foo` to `bar` and all of the content previously associated with `foo` will be associated with `bar`. Note As of 12.1.0, the `"admin"` parameter is no longer supported in client/user creation and support. If used in the `POST` or `PUT` of a client or user, then it is ignored. Note As of 12.1.0, including `"public_key"`, `"private_key"`, or `"create_key"` in PUT requests to clients/users will cause a 400 response. Note `"name"` and `"clientname"` are not independent values. Making a PUT request with different values will return a 400 error. Either name may be specified to set both values. **Request** ``` PUT /organizations/NAME/clients/NAME ``` with a request body similar to: ``` { "name": "monkeypants", "validator": false } ``` **Response** The response is similar to: ``` { "name": "monkeypants", "clientname": "monkeypants", "validator": true, "json_class":"Chef::ApiClient", "chef_type":"client" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `201` | Created. The client was updated. (This response code is only returned when the client is renamed.) | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `409` | Conflict. This response code is only returned when a client is renamed, but a client already exists with the new name. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /clients/CLIENT/keys/ The `/clients/CLIENT/keys` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to retrieve all of the named client’s key identifiers, associated URIs, and expiry states. This method has no parameters. **Request** ``` GET /organizations/NAME/clients/CLIENT/keys ``` This method has no request body. **Response** The response is similar to: ``` [ { "name": "default", "uri": "https://chef.example/organizations/example/clients/client1/keys/default", "expired": false }, { "name": "key1", "uri": "https://chef.example/organizations/example/clients/client1/keys/key1", "expired": true } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST The `POST` method is used to add a key for the specified client. This method has no parameters. **Request** ``` POST /organizations/NAME/clients/CLIENT/keys ``` with a request body similar to: ``` { "name": "key1", "public_key": "-------- BEGIN PUBLIC KEY ----and a valid key here", "expiration_date": "infinity" } ``` **Response** The response is similar to: ``` { "uri": "https://chef.example/organizations/example/clients/client1/keys/key1" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The object was created. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /clients/CLIENT/keys/KEY The `/clients/CLIENT/keys/KEY` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete the specified key for the specified client. This method has no parameters. **Request** ``` DELETE /organizations/NAME/clients/CLIENT/keys/KEY ``` This method has no request body. **Response** The response returns the information about the deleted key and is similar to: ``` { "name": "default", "public_key": "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date": "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return details for a specific key for a specific client. This method has no parameters. **Request** ``` GET /organizations/NAME/clients/CLIENT/keys/KEY ``` This method has no request body. **Response** The response is similar to: ``` { "name" : "default", "public_key" : "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date" : "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update one or more properties for a specific key for a specific client. This method has no parameters. **Request** ``` PUT /organizations/NAME/clients/CLIENT/keys/KEY ``` with a request body similar to: ``` { "name": "new_key_name", "public_key": "-------- BEGIN PUBLIC KEY ----and a valid key here", "expiration_date": "2020-12-31T00:00:00Z" } ``` **Response** The response contains the updated information for the key and is similar to: ``` { "name": "new_key_name", "public_key": "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date": "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `201` | Created. The object was created. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /containers The `/containers` endpoint has the following methods: `GET`, `POST`. #### GET The `GET` method is used to get a list of containers. Note: The `/containers` endpoint is not useful outside of the Chef Infra Server code. This method has no parameters. **Request** ``` GET /organizations/NAME/containers ``` This method does not use a request body. **Response** The response is similar to: ``` { "clients": "https://chef.example/organizations/example/containers/clients", "containers": "https://chef.example/organizations/example/containers/containers", "cookbooks": "https://chef.example/organizations/example/containers/cookbooks", "data": "https://chef.example/organizations/example/containers/data", "environments": "https://chef.example/organizations/example/containers/environments", "groups": "https://chef.example/organizations/example/containers/groups", "nodes": "https://chef.example/organizations/example/containers/nodes", "roles": "https://chef.example/organizations/example/containers/roles", "sandboxes": "https://chef.example/organizations/example/containers/sandboxes" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST The `POST` method is used to create a container. Note: Using the `POST` method of the `/containers` endpoint may have unexpected effects and is likely to break your system. Use of this method is not supported. This method has no parameters. **Request** ``` POST /organizations/NAME ``` This method has a request body similar to: ``` { "containername": "mycontainer", "containerpath": "mycontainer" } ``` **Response** The response is similar to: ``` { "uri"": "https://chef.example/organizations/test/containers/mycontainer" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /containers/NAME #### DELETE The `DELETE` method is used to remove a container. The `/containers/Name` endpoint has the following methods: `DELETE`, `GET`. Note: Using the `DELETE` method of the `/containers/NAME` endpoint may have unexpected effects and is likely to break your system. Use of this method is not supported. This method has no parameters. **Request** ``` DELETE /organizations/NAME/containers/NAME ``` This method does not use a request body. **Response** The response does not return response body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to get a container. This method has no parameters. **Request** ``` GET /organizations/NAME/containers/NAME ``` This method does not use a request body. **Response** The response is similar to: ``` { "containername"": "mycontainer", "containerpath"": "mycontainer" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /cookbook_artifacts Cookbook artifacts are specific versions of cookbooks that were specified by a Policyfile applied to a node. The `/organization/NAME/cookbook_artifacts` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a hash of all cookbook artifacts and their versions. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbook_artifacts ``` This method has no request body. **Response** The response is similar to: ``` { "oc-influxdb": { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/oc-influxdb", "versions": [ { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/oc-influxdb/9634a5d998b02ff069761f6e1309a41572d0f858", "identifier": "9634a5d998b02ff069761f6e1309a41572d0f858" }, { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/oc-influxdb/d774c9bb079f21b64c34275ecd4b371e0cae71a1", "identifier": "d774c9bb079f21b64c34275ecd4b371e0cae71a1" } ] }, "rabbitmq": { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq", "versions": [ { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq/58035a5b41c005f3b5b98f22ccaed1a0d6161e22", "identifier": "58035a5b41c005f3b5b98f22ccaed1a0d6161e22" }, { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq/5c08f92cc01f94ee37d382c32023b137ee343a1e", "identifier": "5c08f92cc01f94ee37d382c32023b137ee343a1e" } ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | ### /cookbook_artifacts/NAME This endpoint lists versions of a named cookbook artifact. The `/organization/NAME/cookbook_artifacts/NAME` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a hash of a single cookbook artifact and its versions. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbook_artifacts/NAME ``` This method has no request body. **Response** The response is similar to: ``` { "rabbitmq": { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq", "versions": [ { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq/0bd7539be0434e3355aff8ecccf4543ecf5c4be2", "identifier": "0bd7539be0434e3355aff8ecccf4543ecf5c4be2" }, { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq/0e1016d364685b87456c648136da04a2559821ec", "identifier": "0e1016d364685b87456c648136da04a2559821ec" } ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /cookbook_artifacts/NAME/ID The `/organization/NAME/cookbook_artifacts/NAME/ID` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete a single cookbook artifact version. This method has no parameters. **Request** ``` DELETE /organizations/NAME/cookbook_artifacts/NAME/ID ``` This method has no request body. **Response** The response contains the record of the deleted resource and is similar to: ``` { "version": "5.7.7", "name": "rabbitmq", "identifier": "f3cf8ea7d8bfc59e35ec541946e3e82cd4b73e74", "frozen?": false, "chef_type": "cookbook_version", "attributes": [ { "name": "default.rb", "path": "attributes/default.rb", "checksum": "e5a530cca3898d8bd07604435dc5156e", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-e5a530cca3898d8bd07604435dc5156e" } ], "definitions": [ ], "files": [ ], "libraries": [ { "name": "matchers.rb", "path": "libraries/matchers.rb", "checksum": "24c3f44c4d1d62300a56051f0069f639", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-24c3f44c4d1d62300a56051f0069f639" }, { "name": "helpers.rb", "path": "libraries/helpers.rb", "checksum": "df65c4a7259fcb30c6f3f1305ebf7502", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-df65c4a7259fcb30c6f3f1305ebf7502" }, { "name": "default.rb", "path": "libraries/default.rb", "checksum": "94292faac84ba797e720501700b30f74", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-94292faac84ba797e720501700b30f74" } ], "providers": [ { "name": "user.rb", "path": "providers/user.rb", "checksum": "c31c9cc749f21962c825f983a6679d94", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-c31c9cc749f21962c825f983a6679d94" }, { "name": "policy.rb", "path": "providers/policy.rb", "checksum": "746c8a3f248f5bbfa51f5d2ba60b6315", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-746c8a3f248f5bbfa51f5d2ba60b6315" } ], "recipes": [ { "name": "default.rb", "path": "recipes/default.rb", "checksum": "99a9b404ff6038d6ac55a90ca68c347a", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-99a9b404ff6038d6ac55a90ca68c347a" }, { "name": "cluster.rb", "path": "recipes/cluster.rb", "checksum": "fc0a86c1f858c9d37e11282efc9fe329", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-fc0a86c1f858c9d37e11282efc9fe329" } ], "resources": [ { "name": "cluster.rb", "path": "resources/cluster.rb", "checksum": "85e74276e19bfdad581dce4f5c59f94a", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-85e74276e19bfdad581dce4f5c59f94a" } ], "root_files": [ { "name": "metadata.rb", "path": "metadata.rb", "checksum": "36b395e758138a4295d1e3f9b3df5da9", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-36b395e758138a4295d1e3f9b3df5da9" }, { "name": "README.md", "path": "README.md", "checksum": "99873670f0994642f5e6baade52c8020", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-99873670f0994642f5e6baade52c8020" } ], "templates": [ { "name": "default.rabbitmq-server.erb", "path": "templates/default/default.rabbitmq-server.erb", "checksum": "077855f4dc37f7fb708976134d8b2551", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-077855f4dc37f7fb708976134d8b2551" }, { "name": "90forceyes.erb", "path": "templates/default/90forceyes.erb", "checksum": "73cc571097cf77c74b4e7b5b680020c9", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-73cc571097cf77c74b4e7b5b680020c9" } ], "metadata": { "name": "rabbitmq", "description": "Installs and configures RabbitMQ server", "long_description": "", "maintainer": "Chef Software, Inc. and contributors", "maintainer_email": "<EMAIL>", "license": "Apache-2.0", "platforms": { "amazon": ">= 2.0", "centos": ">= 7.0", "debian": ">= 8.0", "opensuse": ">= 0.0.0", "opensuseleap": ">= 0.0.0", "oracle": ">= 0.0.0", "redhat": ">= 0.0.0", "scientific": ">= 0.0.0", "smartos": ">= 0.0.0", "suse": ">= 0.0.0", "ubuntu": ">= 14.04" }, "dependencies": { "erlang": ">= 0.0.0", "yum-epel": ">= 0.0.0", "yum-erlang_solutions": ">= 0.0.0", "dpkg_autostart": ">= 0.0.0", "logrotate": ">= 0.0.0" }, "providing": { "rabbitmq::cluster": ">= 0.0.0", "rabbitmq::community_plugins": ">= 0.0.0", "rabbitmq": ">= 0.0.0", "rabbitmq::erlang_package": ">= 0.0.0", "rabbitmq::esl_erlang_package": ">= 0.0.0", "rabbitmq::management_ui": ">= 0.0.0", "rabbitmq::mgmt_console": ">= 0.0.0", "rabbitmq::plugin_management": ">= 0.0.0", "rabbitmq::plugins": ">= 0.0.0", "rabbitmq::policies": ">= 0.0.0", "rabbitmq::policy_management": ">= 0.0.0", "rabbitmq::systemd_limits": ">= 0.0.0", "rabbitmq::user_management": ">= 0.0.0", "rabbitmq::users": ">= 0.0.0", "rabbitmq::vhosts": ">= 0.0.0", "rabbitmq::virtualhost_management": ">= 0.0.0" }, "recipes": { "rabbitmq": "Install and configure RabbitMQ", "rabbitmq::systemd_limits": "Sets up kernel limits (e.g. nofile) for RabbitMQ via systemd", "rabbitmq::cluster": "Set up RabbitMQ clustering.", "rabbitmq::management_ui": "Sets up RabbitMQ management plugin/UI", "rabbitmq::mgmt_console": "Deprecated, alias for rabbitmq::management_ui", "rabbitmq::plugins": "Manage plugins with node attributes", "rabbitmq::plugin_management": "Deprecated, alias for rabbitmq::plugins", "rabbitmq::vhosts": "Manage virtual hosts with node attributes", "rabbitmq::virtualhost_management": "Deprecated, alias for rabbitmq::vhosts", "rabbitmq::users": "Manage users with node attributes", "rabbitmq::user_management": "Deprecated, alias for rabbitmq::users", "rabbitmq::policies": "Manage policies with node attributes", "rabbitmq::policy_management": "Deprecated, alias for rabbitmq::policies", "rabbitmq::erlang_package": "Provisions Erlang via Team RabbitMQ packages", "rabbitmq::esl_erlang_package": "Alias for erlang::esl", "rabbitmq::community_plugins": "" }, "version": "5.7.7", "source_url": "https://github.com/rabbitmq/chef-cookbook", "issues_url": "https://github.com/rabbitmq/chef-cookbook/issues", "privacy": false, "chef_versions": [ ], "ohai_versions": [ ], "gems": [ ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return a single cookbook artifact version. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbook_artifacts/NAME/ID ``` This method has no request body. **Response** The response is similar to: ``` { "version": "5.7.7", "name": "rabbitmq", "identifier": "f3cf8ea7d8bfc59e35ec541946e3e82cd4b73e74", "frozen?": false, "chef_type": "cookbook_version", "attributes": [ { "name": "default.rb", "path": "attributes/default.rb", "checksum": "e5a530cca3898d8bd07604435dc5156e", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-e5a530cca3898d8bd07604435dc5156e" } ], "definitions": [ ], "files": [ ], "libraries": [ { "name": "matchers.rb", "path": "libraries/matchers.rb", "checksum": "24c3f44c4d1d62300a56051f0069f639", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-24c3f44c4d1d62300a56051f0069f639" }, { "name": "helpers.rb", "path": "libraries/helpers.rb", "checksum": "df65c4a7259fcb30c6f3f1305ebf7502", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-df65c4a7259fcb30c6f3f1305ebf7502" }, { "name": "default.rb", "path": "libraries/default.rb", "checksum": "94292faac84ba797e720501700b30f74", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-94292faac84ba797e720501700b30f74" } ], "providers": [ { "name": "user.rb", "path": "providers/user.rb", "checksum": "c31c9cc749f21962c825f983a6679d94", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-c31c9cc749f21962c825f983a6679d94" }, { "name": "policy.rb", "path": "providers/policy.rb", "checksum": "746c8a3f248f5bbfa51f5d2ba60b6315", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-746c8a3f248f5bbfa51f5d2ba60b6315" } ], "recipes": [ { "name": "default.rb", "path": "recipes/default.rb", "checksum": "99a9b404ff6038d6ac55a90ca68c347a", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-99a9b404ff6038d6ac55a90ca68c347a" }, { "name": "cluster.rb", "path": "recipes/cluster.rb", "checksum": "fc0a86c1f858c9d37e11282efc9fe329", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-fc0a86c1f858c9d37e11282efc9fe329" } ], "resources": [ { "name": "cluster.rb", "path": "resources/cluster.rb", "checksum": "85e74276e19bfdad581dce4f5c59f94a", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-85e74276e19bfdad581dce4f5c59f94a" } ], "root_files": [ { "name": "metadata.rb", "path": "metadata.rb", "checksum": "36b395e758138a4295d1e3f9b3df5da9", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-36b395e758138a4295d1e3f9b3df5da9" }, { "name": "README.md", "path": "README.md", "checksum": "99873670f0994642f5e6baade52c8020", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-99873670f0994642f5e6baade52c8020" } ], "templates": [ { "name": "default.rabbitmq-server.erb", "path": "templates/default/default.rabbitmq-server.erb", "checksum": "077855f4dc37f7fb708976134d8b2551", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-077855f4dc37f7fb708976134d8b2551" }, { "name": "90forceyes.erb", "path": "templates/default/90forceyes.erb", "checksum": "73cc571097cf77c74b4e7b5b680020c9", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-73cc571097cf77c74b4e7b5b680020c9" } ], "metadata": { "name": "rabbitmq", "description": "Installs and configures RabbitMQ server", "long_description": "", "maintainer": "Chef Software, Inc. and contributors", "maintainer_email": "<EMAIL>", "license": "Apache-2.0", "platforms": { "amazon": ">= 2.0", "centos": ">= 7.0", "debian": ">= 8.0", "opensuse": ">= 0.0.0", "opensuseleap": ">= 0.0.0", "oracle": ">= 0.0.0", "redhat": ">= 0.0.0", "scientific": ">= 0.0.0", "smartos": ">= 0.0.0", "suse": ">= 0.0.0", "ubuntu": ">= 14.04" }, "dependencies": { "erlang": ">= 0.0.0", "yum-epel": ">= 0.0.0", "yum-erlang_solutions": ">= 0.0.0", "dpkg_autostart": ">= 0.0.0", "logrotate": ">= 0.0.0" }, "providing": { "rabbitmq::cluster": ">= 0.0.0", "rabbitmq::community_plugins": ">= 0.0.0", "rabbitmq": ">= 0.0.0", "rabbitmq::erlang_package": ">= 0.0.0", "rabbitmq::esl_erlang_package": ">= 0.0.0", "rabbitmq::management_ui": ">= 0.0.0", "rabbitmq::mgmt_console": ">= 0.0.0", "rabbitmq::plugin_management": ">= 0.0.0", "rabbitmq::plugins": ">= 0.0.0", "rabbitmq::policies": ">= 0.0.0", "rabbitmq::policy_management": ">= 0.0.0", "rabbitmq::systemd_limits": ">= 0.0.0", "rabbitmq::user_management": ">= 0.0.0", "rabbitmq::users": ">= 0.0.0", "rabbitmq::vhosts": ">= 0.0.0", "rabbitmq::virtualhost_management": ">= 0.0.0" }, "recipes": { "rabbitmq": "Install and configure RabbitMQ", "rabbitmq::systemd_limits": "Sets up kernel limits (e.g. nofile) for RabbitMQ via systemd", "rabbitmq::cluster": "Set up RabbitMQ clustering.", "rabbitmq::management_ui": "Sets up RabbitMQ management plugin/UI", "rabbitmq::mgmt_console": "Deprecated, alias for rabbitmq::management_ui", "rabbitmq::plugins": "Manage plugins with node attributes", "rabbitmq::plugin_management": "Deprecated, alias for rabbitmq::plugins", "rabbitmq::vhosts": "Manage virtual hosts with node attributes", "rabbitmq::virtualhost_management": "Deprecated, alias for rabbitmq::vhosts", "rabbitmq::users": "Manage users with node attributes", "rabbitmq::user_management": "Deprecated, alias for rabbitmq::users", "rabbitmq::policies": "Manage policies with node attributes", "rabbitmq::policy_management": "Deprecated, alias for rabbitmq::policies", "rabbitmq::erlang_package": "Provisions Erlang via Team RabbitMQ packages", "rabbitmq::esl_erlang_package": "Alias for erlang::esl", "rabbitmq::community_plugins": "" }, "version": "5.7.7", "source_url": "https://github.com/rabbitmq/chef-cookbook", "issues_url": "https://github.com/rabbitmq/chef-cookbook/issues", "privacy": false, "chef_versions": [ ], "ohai_versions": [ ], "gems": [ ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to create or update a single cookbook artifact version. This method has no parameters. **Request** ``` PUT /organizations/NAME/cookbook_artifacts/NAME/ID ``` The request body is similar to: ``` { "definitions": [ { "name": "unicorn_config.rb", "checksum": "c92b659171552e896074caa58dada0c2", "path": "definitions/unicorn_config.rb", "specificity": "default" } ], "attributes": [], "files": [], "providers": [], "metadata": { "dependencies": {"ruby": [], "rubygems": []}, "name": "unicorn", "maintainer_email": "<EMAIL>", "attributes": {}, "license": "Apache 2.0", "suggestions": {}, "platforms": {}, "maintainer": "Chef Software, Inc.", "long_description": "= LICENSE AND AUTHOR:\\n\\nAuthor:: <NAME>...", "recommendations": {}, "version": "0.1.2", "conflicting": {}, "recipes": {"unicorn": "Installs unicorn rubygem"}, "groupings": {}, "replacing": {}, "description": "Installs/Configures unicorn", "providing": {} }, "libraries": [], "templates": [ { "name": "unicorn.rb.erb", "checksum": "36a1cc1b225708db96d48026c3f624b2", "path": "templates/default/unicorn.rb.erb", "specificity": "default" } ], "resources": [], "name": "unicorn", "identifier": "ba0dadcbca26710a521e0e3160cc5e20", "recipes": [ { "name": "default.rb", "checksum": "ba0dadcbca26710a521e0e3160cc5e20", "path": "recipes/default.rb", "specificity": "default" } ], "root_files": [ { "name": "README.rdoc", "checksum": "d18c630c8a68ffa4852d13214d0525a6", "path": "README.rdoc", "specificity": "default" }, { "name": "metadata.rb", "checksum": "967087a09f48f234028d3aa27a094882", "path": "metadata.rb", "specificity": "default" }, { "name": "metadata.json", "checksum": "45b27c78955f6a738d2d42d88056c57c", "path": "metadata.json", "specificity": "default" } ], "chef_type": "cookbook_artifact_version" } ``` where the `checksum` values must have already been uploaded to the Chef Infra Server using the sandbox endpoint. Once a file with a particular checksum has been uploaded by the user, redundant uploads are not necessary. Unused `checksum` values will be garbage collected. **Response** This method has no response body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /cookbooks A cookbook is the fundamental unit of configuration and policy distribution in Chef Infra. A cookbook defines a scenario and contains everything that is required to support that scenario: * Recipes that specify which Chef Infra built-in resources to use, as well as the order in which they are to be applied * Attribute values, which allow environment-based configurations such as `dev` or `prodution`. * Custom Resources for extending Chef Infra beyond the built-in resources. * Files and Templates for distributing information to systems. * Custom Ohai Plugins for extending system configuration collection beyond the Ohai defaults. * The `metadata.rb` file, which describes the cookbook itself and any dependencies it may have. When a cookbook is uploaded, only files that are new or updated will be included. This approach minimizes the amount of storage and time that is required during the modify-upload-test cycle. To keep track of which files have already been uploaded, Chef Infra Client uses a checksum and assigns a checksum to each file. These checksums are used in the cookbook version manifest, alongside the same records that store the file description (name, specificity, and so on), as well as the checksum and the URL from which the file’s contents can be retrieved. The `/cookbooks` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a hash of all cookbooks and cookbook versions. This method has the following parameters: | Parameter | Description | | --- | --- | | `num_versions=n` | The number of cookbook versions to include in the response, where `n` is the number of cookbook versions. For example: `num_versions=3` returns the three latest versions, in descending order (newest to oldest). Use `num_versions=all` to return all cookbook versions. If `num_versions` is not specified, a single cookbook version is returned. `0` is an invalid input (an empty array for the versions of each cookbook is returned). | **Request** ``` GET /organizations/NAME/cookbooks ``` **Response** The response is similar to: ``` { "apache2": { "url": "https://localhost/cookbooks/apache2", "versions": [ {"url": "https://localhost/cookbooks/apache2/5.1.0", "version": "5.1.0"}, {"url": "https://localhost/cookbooks/apache2/4.2.0", "version": "4.2.0"} ] }, "nginx": { "url": "https://localhost/cookbooks/nginx", "versions": [ {"url": "https://localhost/cookbooks/nginx/1.0.0", "version": "1.0.0"}, {"url": "https://localhost/cookbooks/nginx/0.3.0", "version": "0.3.0"} ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | ### /cookbooks/_latest The `/cookbooks/_latest` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a list of the most recent cookbook versions. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbooks/_latest ``` **Response** For example, if cookbooks `foo` and `bar` both exist on the Chef Infra Server and both with versions `0.1.0` and `0.2.0`, the response is similar to: ``` { "foo": "https://localhost/cookbooks/foo/0.2.0", "bar": "https://localhost/cookbooks/bar/0.2.0" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /cookbooks/_recipes The `/cookbooks/_recipes` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return the names of all recipes in the most recent cookbook versions. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbooks/_recipes ``` **Response** The response is similar to: ``` { } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /cookbooks/NAME The `/cookbooks/NAME` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a hash that contains a key-value pair that corresponds to the specified cookbook, with a URL for the cookbook and for each version of the cookbook. **Request** ``` GET /organizations/NAME/cookbooks/NAME ``` **Response** The response is similar to: ``` { "apache2": { "url": "https://localhost/cookbooks/apache2", "versions": [ {"url": "https://localhost/cookbooks/apache2/5.1.0", "version": "5.1.0"}, {"url": "https://localhost/cookbooks/apache2/4.2.0", "version": "4.2.0"} ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /cookbooks/NAME/version A cookbook version represents a set of functionality that is different from the cookbook on which it is based. A version may exist for many reasons, such as ensuring the correct use of a third-party component, updating a bug fix, or adding an improvement. A cookbook version is defined using syntax and operators, may be associated with environments, cookbook metadata, and/or run-lists, and may be frozen (to prevent unwanted updates from being made). A cookbook version is maintained just like a cookbook, with regard to source control, uploading it to the Chef Infra Server, and how Chef Infra Client applies that cookbook when configuring nodes. The `/cookbooks/NAME/VERSION` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete a cookbook version. This method has no parameters. **Request** ``` DELETE /organizations/NAME/cookbooks/NAME/VERSION ``` **Response** This method has no response body. Unused `checksum` values will be garbage collected. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return a description of a cookbook, including its metadata and links to component files. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbooks/NAME/VERSION ``` where `VERSION` can be `_latest` in order to float to head. **Response** The response is similar to: ``` { "cookbook_name": "getting-started", "files": [ ], "chef_type": "cookbook_version", "definitions": [ ], "libraries": [ ], "attributes": [ { "url": "https://domain.com/org_name/(...rest of URL)", "path": "attributes/default.rb", "specificity": "default", "name": "default.rb", "checksum": "fa0fc4abf3f6787fdsaasadfrc5c35de667c" } ], "recipes": [ { "url": "https://domain.com/org_name/(...rest of URL)", "path": "recipes/default.rb", "specificity": "default", "name": "default.rb", "checksum": "7e79b1ace7728fdsadfsdaf857e60fc69" } ], "providers": [ ], "resources": [ ], "templates": [ { "url": "https://domain.com/org_name/(...rest of URL)", "path": "templates/default/chef-getting-started.txt.erb", "specificity": "default", "name": "chef-getting-started.txt.erb", "checksum": "a29d6f2545sdffds1f140c3a78b1fe" } ], "root_files": [ { "url": "https://domain.com/org_name/(...rest of URL)", "path": ".DS_Store", "specificity": "default", "name": ".DS_Store", "checksum": "c107b500aafd12asdffdsdf5c2a7d6" }, { "url": "https://domain.com/org_name/(...rest of URL)", "path": "metadata.json", "specificity": "default", "name": "metadata.json", "checksum": "20f09570e54dasdf0f3ae01e6401c90f" }, { "url": "https://domain.com/org_name/(...rest of URL)", "path": "metadata.rb", "specificity": "default", "name": "metadata.rb", "checksum": "71027aefasd487fdsa4cb6994b66ed" }, { "url": "https://domain.com/org_name/(...rest of URL)", "path": "README.rdoc", "specificity": "default", "name": "README.rdoc", "checksum": "8b9275e56fee974easdfasdfbb729" } ], "name": "getting-started-0.4.0", "frozen?": false, "version": "0.4.0", "json_class": "Chef::CookbookVersion", "metadata": { "maintainer": "Maintainer", "attributes": { }, "suggestions": { }, "recipes": { "getting-started": "" }, "dependencies": { }, "platforms": { }, "groupings": { }, "recommendations": { }, "name": "getting-started", "description": "description", "version": "0.4.0", "maintainer_email": "<EMAIL>", "long_description": "= DESCRIPTION:\n\nThis cookbook is used to do some things.\n\n", "providing": { "getting-started": ">= 0.0.0" }, "replacing": { }, "conflicting": { }, "license": "Apache 2.0" } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to create or update a cookbook version. This method has no parameters. **Request** ``` PUT /organizations/NAME/cookbooks/NAME/VERSION ``` with a request body similar to: ``` { "definitions": [ { "name": "unicorn_config.rb", "checksum": "c92b659171552e896074caa58dada0c2", "path": "definitions/unicorn_config.rb", "specificity": "default" } ], "name": "unicorn-0.1.2", "attributes": [], "files": [], "json_class": "Chef::CookbookVersion", "providers": [], "metadata": { "dependencies": {"ruby": [], "rubygems": []}, "name": "unicorn", "maintainer_email": "<EMAIL>", "attributes": {}, "license": "Apache 2.0", "suggestions": {}, "platforms": {}, "maintainer": "Chef Software, Inc.", "long_description": "= LICENSE AND AUTHOR:\n\nAuthor:: <NAME>...", "recommendations": {}, "version": "0.1.2", "conflicting": {}, "recipes": {"unicorn": "Installs unicorn rubygem"}, "groupings": {}, "replacing": {}, "description": "Installs/Configures unicorn", "providing": {} }, "libraries": [], "templates": [ { "name": "unicorn.rb.erb", "checksum": "36a1cc1b225708db96d48026c3f624b2", "path": "templates/default/unicorn.rb.erb", "specificity": "default" } ], "resources": [], "cookbook_name": "unicorn", "version": "0.1.2", "recipes": [ { "name": "default.rb", "checksum": "ba0dadcbca26710a521e0e3160cc5e20", "path": "recipes/default.rb", "specificity": "default" } ], "root_files": [ { "name": "README.rdoc", "checksum": "d18c630c8a68ffa4852d13214d0525a6", "path": "README.rdoc", "specificity": "default" }, { "name": "metadata.rb", "checksum": "967087a09f48f234028d3aa27a094882", "path": "metadata.rb", "specificity": "default" }, { "name": "metadata.json", "checksum": "45b27c78955f6a738d2d42d88056c57c", "path": "metadata.json", "specificity": "default" } ], "chef_type": "cookbook_version" } ``` where the `checksum` values must have already been uploaded to the Chef Infra Server using the sandbox endpoint. Once a file with a particular checksum has been uploaded by the user, redundant uploads are not necessary. Unused `checksum` values will be garbage collected. **Response** This method has no response body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /data Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. The `/data` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to return a list of all data bags on the Chef Infra Server. This method has no parameters. **Request** ``` GET /organizations/NAME/data ``` **Response** The response is similar to: ``` { "users": "https://chef.example/organizations/NAME/data/users", "applications": "https://chef.example/organizations/NAME/data/applications" } ``` shown as a list of key-value pairs, where (in the example above) `users` and `applications` are the names of data bags and `https://chef.example/organizations/NAME/data/foo` is the path to the data bag. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create a new data bag on the Chef Infra Server. This method has no parameters. **Request** ``` POST /organizations/NAME/data ``` with a request body that contains the key-value pair for the data bag and is similar to: ``` { "name": "users" } ``` where (in the example above) `name` is the key and “users” is the value. **Response** The response is similar to: ``` { "uri": "https://organizations/NAME/data/users", } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The object was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. A databag with that name already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /data/NAME The `/data/NAME` endpoint is used to view and update data for a specific data bag. This endpoint has the following methods: `DELETE`, `GET`, and `POST`. #### DELETE The `DELETE` method is used to delete a data bag. This method has no parameters. **Request** ``` DELETE /organizations/NAME/data/NAME ``` This method has no request body. **Response** The response is similar to: ``` { "name": "users", "json_class": "Chef::DataBag", "chef_type": "data_bag" } ``` where the key-value pairs represent the last state of the data bag item. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return a hash of all entries in the specified data bag. This method has no parameters. **Request** ``` GET /organizations/NAME/data/NAME ``` **Response** The response is similar to: ``` { "adam": "https://chef.example/organizations/NAME/data/users/adam" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST The `POST` method is used to create a new data bag item. This method has no parameters. **Request** ``` POST /organizations/NAME/data/NAME ``` with a request body similar to: ``` { "id": "adam", "real_name": "<NAME>" } ``` where `id` is required. **Response** This method has no response body. **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The item was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /data/NAME/ITEM A data bag is a container of related data bag items, where each individual data bag item is a JSON file. knife can load a data bag item by specifying the name of the data bag to which the item belongs and then the filename of the data bag item. The only structural requirement of a data bag item is that it must have an `id`: ``` { /* This is a supported comment style */ // This style is also supported "id": "ITEM_NAME", "key": "value" } ``` where * `key` and `value` are the `key:value` pair for each additional attribute within the data bag item * `/* ... */` and `// ...` show two ways to add comments to the data bag item The `/data/NAME/ITEM` endpoint allows the key-value pairs within a data bag item to be viewed and managed. This endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete a key-value pair in a data bag item. This method has no parameters. **Request** ``` DELETE /organizations/NAME/data/NAME/ITEM ``` **Response** The response is similar to: ``` { } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to view all of the key-value pairs in a data bag item. This method has no parameters. **Request** ``` GET /organizations/NAME/data/NAME/ITEM ``` **Response** The response is similar to: ``` { "real_name": "<NAME>", "id": "adam" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to replace the contents of a data bag item with the contents of this request. This method has no parameters. **Request** ``` PUT /organizations/NAME/data/NAME/ITEM ``` with a request body similar to: ``` { "real_name": "<NAME>", "id": "adam" } ``` where `id` is required. **Response** The response is similar to: ``` { } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /environments An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. The `/environments` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to return a data structure that contains a link to each available environment. This method has no parameters. **Request** ``` GET /organizations/NAME/environments ``` **Response** The response is similar to: ``` { "_default": "https://api.chef.io/organizations/org_name/environments/_default", "webserver": "https://api.chef.io/organizations/org_name/environments/webserver" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create a new environment. This method has no parameters. **Request** ``` POST /organizations/NAME/environments ``` with a request body similar to: ``` { "name": "dev", "default_attributes": {}, "json_class": "Chef::Environment", "description": "", "cookbook_versions": {}, "chef_type": "environment" } ``` **Response** The response is similar to: ``` { "uri": "https://localhost/environments/dev" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The object was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /environments/_default The `/environments/_default` endpoint has the following methods: `GET`. #### GET The `GET` method is used to get information about the `_default` environment on the Chef Infra Server. This method has no parameters. **Request** ``` GET /organizations/NAME/environments/_default ``` **Response** The response is similar to: ``` { "name": "_default", "description": "The default Chef environment", "json_class": "Chef::Environment", "chef_type": "environment", "default_attributes": { }, "override_attributes": { }, "cookbook_versions": { } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /environments/NAME The `/environments/NAME` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete an environment. This method has no parameters. **Request** ``` DELETE /organizations/NAME/environments/NAME ``` **Response** The response will return the JSON for the environment that was deleted, similar to: ``` { "name":"backend", "description":"", "cookbook_versions":{}, "json_class":"Chef::Environment", "chef_type":"environment", "default_attributes":{}, "override_attributes":{} } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return the details for an environment as JSON. This method has no parameters. **Request** ``` GET /organizations/NAME/environments/NAME ``` **Response** The response is similar to: ``` { "name": "_default", "description": "The default Chef environment", "json_class": "Chef::Environment", "chef_type": "environment", "default_attributes": { } "override_attributes": { }, "cookbook_versions": { }, } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update the details of an environment on the Chef Infra Server. This method has no parameters. **Request** ``` PUT /organizations/NAME/environments/NAME ``` with a request body that contains the updated JSON for the environment and is similar to: ``` { "name": "dev", "attributes": {}, "json_class": "Chef::Environment", "description": "The Dev Environment", "cookbook_versions": {}, "chef_type": "environment" } ``` **Response** The response will return the updated environment. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /environments/NAME/cookbooks/NAME The `/environments/NAME/cookbooks/NAME` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a hash of key-value pairs for the requested cookbook. This method has the following parameters: | Parameter | Description | | --- | --- | | `num_versions=n` | The number of cookbook versions to include in the response, where `n` is the number of cookbook versions. For example: `num_versions=3` returns the three latest versions, in descending order (newest to oldest). Use `num_versions=all` to return all cookbook versions. If `num_versions` is not specified, a single cookbook version is returned. `0` is an invalid input (an empty array for the versions of each cookbook is returned). | **Request** ``` GET /organizations/NAME/environments/NAME/cookbooks/NAME ``` where the first instance of `NAME` is the name of the environment, and the second instance is the name of the cookbook. **Response** The response is similar to: ``` { "apache2": { "url": "https://localhost/cookbooks/apache2", "versions": [ {"url": "https://localhost/cookbooks/apache2/5.1.0", "version": "5.1.0"}, {"url": "https://localhost/cookbooks/apache2/4.2.0", "version": "4.2.0"} ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /environments/NAME/cookbook_versions The `/environments/NAME/cookbook_versions` endpoint has the following methods: `POST`. #### POST The `POST` method is used to return a hash of the cookbooks and cookbook versions (including all dependencies) that are required by the `run_list` array. Version constraints may be specified using the `@` symbol after the cookbook name as a delimiter. Version constraints may also be present when the `cookbook_versions` attributes is specified for an environment or when dependencies are specified by a cookbook. This method has no parameters. **Request** ``` POST /organizations/NAME/environments/NAME/cookbook_versions ``` with a request body similar to: ``` { "run_list": [ "zed@0.0.1", "bar", "mysql", "gem", "nginx@0.99.2", "cron", "foo" ] } ``` where `@x.x.x` represents a constraint for a cookbook version. **Response** The response will return a list of cookbooks that are required by the `run_list` array contained in the request. The cookbooks that are returned are often the latest versions of each cookbook. Depending on any constraints present in the request or on dependencies a cookbook may have for specific cookbook versions, a request may not always return the latest cookbook version for each cookbook. The response is similar to: ``` { "cookbook_name": { "recipes": [ { "name": "default.rb", "path": "recipes/default.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "recipe_name.rb", "path": "recipes/recipe_name.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { ... } ], "definitions": [ ], "libraries": [ ], "attributes": [ ], "files": [ ], "templates": [ { "name": "template_name.erb", "path": "templates/default/template_name.erb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { ... } ], "resources": [ ], "providers": [ ], "root_files": [ { "name": "metadata.rb", "path": "metadata.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" } ], "cookbook_name": "cookbook_name-1.0.2", "metadata": { "name": "cookbook_name", "description": "description", "long_description": "", "maintainer": "maintainer", "maintainer_email": "<EMAIL>", "license": "license", "platforms": { }, "dependencies": { "cookbook_name": ">= 0.0.0", "cookbook_name": ">= 1.2.3", ... "cookbook_name": ">= 0.1.0" }, "recommendations": { }, "suggestions": { }, "conflicting": { }, "providing": { "cookbook_name": ">= 0.0.0", "cookbook_name::recipe_name": ">= 0.0.0", "cookbook_name::recipe_name": ">= 1.2.3", "cookbook_name::recipe_name": ">= 0.1.0" }, "replacing": { }, "attributes": { }, "groupings": { }, "recipes": { "cookbook_name": "description", "cookbook_name::recipe_name": "", ... "cookbook_name::recipe_name": "" }, "version": "0.0.0" }, "version": "0.0.0", "name": "cookbook_name-1.0.2", "frozen?": false, "chef_type": "cookbook_version", "json_class": "Chef::CookbookVersion" }, "cookbook_name": { "recipes": [ { "name": "default.rb", "path": "recipes/default.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, ], "definitions": [ ], "libraries": [ { "name": "library_file.rb", "path": "libraries/library_file.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" } ], "attributes": [ { "name": "default.rb", "path": "attributes/default.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" } ], "files": [ ], "templates": [ ], "resources": [ ], "providers": [ ], "root_files": [ { "name": ".gitignore", "path": ".gitignore", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": ".kitchen.yml", "path": ".kitchen.yml", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "CHANGELOG.md", "path": "CHANGELOG.md", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "CONTRIBUTING", "path": "CONTRIBUTING", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "LICENSE", "path": "LICENSE", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "metadata.json", "path": "metadata.json", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "metadata.rb", "path": "metadata.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "README.md", "path": "README.md", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, ], "chef_type": "cookbook_version", "name": "cookbook_name-1.0.2", "cookbook_name": "cookbook_name", "version": "1.0.2", "metadata": { "name": "cookbook_name", "description": "description", "long_description": "", "maintainer": "maintainer", "maintainer_email": "<EMAIL>", "license": "license", "platforms": { }, "dependencies": { }, "recommendations": { }, "suggestions": { }, "conflicting": { }, "providing": { }, "replacing": { }, "attributes": { }, "groupings": { }, "recipes": { }, "version": "1.0.2" }, "frozen?": true, "json_class": "Chef::CookbookVersion" }, "cookbook_name": { ... } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `412` | Not allowed. A set of cookbooks and/or cookbook versions could not be found that met all of the requirements of the run-list. A cookbook in the run-list may not exist. A dependency may be present for a cookbook that does not exist. A constraint on a cookbook made by a run-list, environment, or cookbook version, may not match an available cookbook version. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /environments/NAME/cookbooks The `/environments/NAME/cookbooks` endpoint has the following methods: `GET`. #### GET The `GET` method is used to get a list of cookbooks and cookbook versions that are available to the specified environment. This method has the following parameters: | Parameter | Description | | --- | --- | | `num_versions=n` | The number of cookbook versions to include in the response, where `n` is the number of cookbook versions. For example: `num_versions=3` returns the three latest versions, in descending order (newest to oldest). Use `num_versions=all` to return all cookbook versions. If `num_versions` is not specified, a single cookbook version is returned. `0` is an invalid input (an empty array for the versions of each cookbook is returned). | **Request** ``` GET /organizations/NAME/environments/NAME/cookbooks ``` **Response** The response is similar to: ``` { "apache2": { "url": "https://localhost/cookbooks/apache2", "versions": [ {"url": "https://localhost/cookbooks/apache2/5.1.0", "version": "5.1.0"}, {"url": "https://localhost/cookbooks/apache2/4.2.0", "version": "4.2.0"} ] }, "nginx": { "url": "https://localhost/cookbooks/nginx", "versions": [ {"url": "https://localhost/cookbooks/nginx/1.0.0", "version": "1.0.0"}, {"url": "https://localhost/cookbooks/nginx/0.3.0", "version": "0.3.0"} ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /environments/NAME/nodes The `/environments/NAME/nodes` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a list of nodes in a given environment. This method has no parameters. **Request** ``` GET /organizations/NAME/environments/NAME/nodes ``` **Response** The response is similar to: ``` { "blah": "https://api.chef.io/org/org_name/nodes/_default", "boxer": "https://api.chef.io/org/org_name/nodes/frontend", "blarrrrgh": "https://api.chef.io/org/org_name/nodes/backend" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /environments/NAME/recipes The `/environments/NAME/recipes` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a list of recipes available to a given environment. This method has no parameters. **Request** ``` GET /organizations/NAME/environments/NAME/recipes ``` where the first instance of `NAME` is the name of the environment, and the second instance is the name of the recipe. **Response** The response is similar to: ``` [ "ant", "apache2", "apache2::mod_auth_openid", "apache2::mod_authnz_ldap", "apt", "aws", "capistrano", "chef", "chef::bootstrap_client", "chef-client::config", "chef-client", ... ] ``` The list of recipes will be the default recipes for a given cookbook. If an environment has multiple versions of a cookbook that matches its constraints, only the recipes from the latest version of that cookbook will be reported. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /environments/NAME/roles/NAME The `/environments/NAME/roles/NAME` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return the `run_list` attribute of the role (when the name of the environment is `_default`) or to return `env_run_lists[environment_name]` (for non-default environments). Note The behavior of this endpoint is identical to `GET /roles/NAME/environments/NAME`; it is recommended (but not required) that `GET /roles/NAME/environments/NAME` be used instead of this endpoint. This method has no parameters. **Request** ``` GET /organizations/NAME/environments/NAME/roles/NAME ``` where the first instance of `NAME` is the name of the environment, and the second instance is the name of the role. **Response** The response is similar to: ``` { "run_list": [ "recipe[recipe_name]", "role[role_name]", "recipe[recipe_name]", "role[role_name]", "recipe[recipe_name]", "role[role_name]" ] } ``` Chef Infra Client will pick up the `_default` run-list if `env_run_list[environment_name]` is null or nonexistent. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /groups The `/groups` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to get a list of groups on the Chef Infra Server for a single organization. This method has no parameters. **Request** ``` GET /organizations/NAME/groups ``` **Response** The response is similar to: ``` { "33a5c28a8efe11e195005fsaes25400298d3f": "https://url/for/group1", "admins": "https://url/for/groups/admins", "billing-admins": "https://url/for/billing-admins", "clients": "https://url/for/clients", "developers": "https://url/for/developers", "users": "https://url/for/groups/users" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST The `POST` method is used to create a group on the Chef Infra Server for a single organization. **Request** ``` POST /organizations/NAME/groups ``` with a request body similar to: ``` { "name": "group1", "groupname": "group1", "orgname": "test", "actors": [] "clients": ["mynode"], "groups": ["admins"], "users": ["betina"] } ``` **Response** The response is similar to: ``` { "uri": "https://chef.example/organizations/test/groups/group1", } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The group was created. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `409` | Conflict. The requested group already exists. | ### /groups/GROUP_NAME The `/groups/GROUP_NAME` endpoint has the following methods: `DELETE`, `GET` and `PUT`. #### DELETE The `DELETE` method is used to remove a group from a single organization. This method has no parameters. **Request** ``` DELETE /organizations/NAME/groups/GROUP_NAME ``` without a request body. **Response** The response is similar to: ``` { } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The group was deleted. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to get lists of users and other groups that belong to a group. This method has no parameters. **Request** ``` GET /organizations/NAME/groups/GROUP_NAME ``` **Response** The response is similar to: ``` { "actors": [ "pivotal", "grantmc" ], "users": [ "pivotal", "grantmc" ], "clients": [ ], "groups": [ "000000000000ad94b5ddde157c070f0c" ], "orgname": "inbetweens", "name": "admins", "groupname": "admins" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update a group on a single organization. Updating the clients, groups and users memberships replaces the definitions for the group. `GET` the group and merge changes to create the desired member lists. This method has no parameters. **Request** ``` PUT /organizations/NAME/groups/GROUP_NAME ``` with a request body similar to: ``` { "name": "group1", "groupname": "groupnew", "actors": { "clients": ["mynode","addme"], "groups": ["admins"], "users": ["betina"] } } ``` **Response** The response is similar to: ``` { "name": "group1", "groupname": "groupnew", "orgname": "test", "actors": { "clients": ["mynode","addme"], "groups": ["admins"], "users": ["betina"] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The group was updated. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /nodes A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. The `/nodes` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to return a hash of URIs for nodes on the Chef Infra Server. This method has no parameters. **Request** ``` GET /organizations/NAME/nodes ``` **Response** The response is similar to: ``` { "latte": "https://localhost/nodes/latte" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create a new node. This method has no parameters. **Request** ``` POST /organizations/NAME/nodes ``` with a request body similar to: ``` { "name": "latte", "chef_type": "node", "json_class": "Chef::Node", "attributes": { "hardware_type": "laptop" }, "overrides": {}, "defaults": {}, "run_list": [ "recipe[unicorn]" ] } ``` where `name` is the name of the node. Other attributes are optional. The order of the `run_list` attribute matters. **Response** The response is similar to: ``` { "uri": "https://localhost/nodes/latte" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The object was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /nodes/NAME The `/nodes/NAME` endpoint has the following methods: `DELETE`, `GET`, `HEAD` and `PUT`. #### DELETE The `DELETE` method is used to delete a node. This method has no parameters. **Request** ``` DELETE /organizations/NAME/nodes/NAME ``` **Response** The response will return the last known state of the node, similar to: ``` { "overrides": {}, "name": "latte", "chef_type": "node", "json_class": "Chef::Node", "attributes": { "hardware_type": "laptop" }, "run_list": [ "recipe[apache2]" ], "defaults": {} } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return the details of a node as JSON. This method has no parameters. **Request** ``` GET /organizations/NAME/nodes/NAME ``` **Response** The response is similar to: ``` { "name": "node_name", "chef_environment": "_default", "run_list": [ "recipe[recipe_name]" ] "json_class": "Chef::Node", "chef_type": "node", "automatic": { ... }, "normal": { "tags": [ ] }, "default": { }, "override": { } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### HEAD The `HEAD` method is used to check the existence of a node. This method has no parameters. **Request** ``` HEAD /organizations/NAME/nodes/NAME ``` **Response** The method does not return a body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update a node. This method has no parameters. **Request** ``` PUT /organizations/NAME/nodes/NAME ``` with a request body similar to: ``` { "overrides": {}, "name": "latte", "chef_type": "node", "json_class": "Chef::Node", "attributes": { "hardware_type": "laptop" }, "run_list": [ 'recipe[cookbook_name::recipe_name], role[role_name]' ], "defaults": {} } ``` **Response** The response will return the updated node. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /policies The `/policies` endpoint has the following methods: `GET`. #### GET The `GET` method is used to get a list of policies (including policy revisions) from the Chef Infra Server. This method has no parameters. **Request** ``` GET /organizations/NAME/policies ``` **Response** The response groups policies by name and revision and is similar to: ``` { "aar": { "uri": "https://chef.example/organizations/org1/policies/aar", "revisions": { "37f9b658cdd1d9319bac8920581723efcc2014304b5f3827ee0779e10ffbdcc9": { }, "95040c199302c85c9ccf1bcc6746968b820b1fa25d92477ea2ec5386cd58b9c5": { }, "d81e80ae9bb9778e8c4b7652d29b11d2111e763a840d0cadb34b46a8b2ca4347": { } } }, "jenkins": { "uri": "https://chef.example/organizations/org1/policies/jenkins", "revisions": { "613f803bdd035d574df7fa6da525b38df45a74ca82b38b79655efed8a189e073": { }, "6fe753184c8946052d3231bb4212116df28d89a3a5f7ae52832ad408419dd5eb": { }, "cc1a0801e75df1d1ea5b0d2c71ba7d31c539423b81478f65e6388b9ee415ad87": { } } } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | ### /policy_groups The `/policy_groups` endpoint has the following methods: `GET`. Each node has a 1:many relationship with policy settings stored on the Chef Infra Server. This relationship is based on the policy group to which the node is associated, and then the policy settings assigned to that group: * A policy is typically named after the functional role ahost performs, such as “application server”, “chat server”, “load balancer”, and so on * A policy group defines a set of hosts in a deployed units, typically mapped to organizational requirements such as “dev”, “test”, “staging”, and “production”, but can also be mapped to more detailed requirements as needed ### /principals/NAME The `/principals/NAME` endpoint has the following methods: `GET`. #### GET The `GET` method is used to get a list of public keys for clients and users in order to ensure that enough information is present for authorized requests. This method has no parameters. **Request** ``` GET /organizations/NAME/principals/NAME ``` **Response** For a user or client, the type value will vary. The response body returns an array of principals which allows for a client with the same name as a user. The response for a user or client is similar to: ``` { "Principals: [ { "name": "normal_user", "type": "user", "public_key": "-----BEGIN PUBLIC KEY-----...", "authz_id": "eca5fdd45a8b4bacc04bbc6e37a340bes", "org_member":false } ] } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `404` | Not found. The requested object does not exist. | ### /required_recipe The `/required_recipe` endpoint has the following method: `GET`. #### GET Use the `GET` method to view a recipe specified by a Chef Infra Server administrator as part of the Chef Infra Server configuration. This recipe will be run by all Chef Infra Clients that connect to the Chef Infra Server. The `required_recipe` feature is aimed at expert level practitioners delivering isolated configuration changes to target systems. The returned text is the content of a single recipe file. This method has no parameters. **Request** ``` GET /organizations/NAME/required_recipe ``` This method has no request body. **Response** The response is returned in plain text, not in JSON format. The response is similar to: ``` "# My required recipe file '/tmp/build' package 'secret_sauce' " ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. Required recipe is enabled, a path to a recipe is defined, and a recipe exists at the path location. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not Found. The required recipe function is not enabled. | ### /roles A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. The `/roles` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to get a list of roles along with their associated URIs. This method has no parameters. **Request** ``` GET /organizations/NAME/roles ``` **Response** The response is similar to: ``` { "webserver": "https://chef.example/organizations/org1/roles/webserver" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create a new role on the Chef Infra Server. This method has no parameters. **Request** ``` POST /organizations/NAME/roles ``` with a request body similar to: ``` { "name": "webserver", "default_attributes": {}, "description": "A webserver", "env_run_lists": { "testenv": { "recipe[pegasus]" } }, "run_list": [ "recipe[unicorn]", "recipe[apache2]" ], "override_attributes": {} } ``` **Response** The response is similar to: ``` { "uri": "https://chef.example/organizations/org1/roles/webserver" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The request was successful. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /roles/NAME The `/roles/NAME` endpoint has the following methods: `GET`, `DELETE`, and `PUT`. #### DELETE The `DELETE` method is used to delete a role on the Chef Infra Server. This method has no parameters. **Request** ``` DELETE /organizations/NAME/roles/NAME ``` **Response** The response is similar to: ``` { "name": "webserver", "chef_type": "role", "json_class": "Chef::Role", "default_attributes": {}, "description": "A webserver", "env_run_lists": { "env1": { "recipe[foo1]" } }, "run_list": [ "recipe[apache2]" ], "override_attributes": {} } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return the details for a role as JSON. This method has no parameters. **Request** ``` GET /organizations/NAME/roles/NAME ``` **Response** The response is similar to: ``` { "name": "webserver", "chef_type": "role", "json_class": "Chef::Role", "default_attributes": {}, "description": "A webserver", "env_run_lists": {}, "run_list": [ "recipe[unicorn]", "recipe[apache2]" ], "override_attributes": {} } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update a role on the Chef Infra Server. This method has no parameters. **Request** ``` PUT /organizations/NAME/roles/NAME ``` with a request body similar to: ``` { "name": "webserver", "default_attributes": {}, "description": "A webserver", "env_run_lists": {}, "default_attributes": {}, "run_list": [ "recipe[apache2]" ], "override_attributes": {} } ``` **Response** The response will return the JSON for the updated role. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /roles/NAME/environments The `/roles/NAME/environments` endpoint has the following method: `GET`. #### GET The `GET` method returns a list of the environments that have environment-specific run-lists in the given role as JSON data. This method has no parameters. **Request** ``` GET /organizations/NAME/roles/NAME/environments ``` **Response** The response is similar to: ``` ["_default","production","qa"] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /roles/NAME/environments/NAME The `/roles/NAME/environments/NAME` endpoint has the following method: `GET`. #### GET The `GET` method returns the environment-specific run-list (`env_run_lists[environment_name]`) for a role. This method has no parameters. **Request** ``` GET /organizations/NAME/roles/NAME/environments/NAME ``` where the first `NAME` is the name of the role and the second is the name of the environment. **Response** The response is similar to: ``` {"run_list":["recipe[foo]"]} ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /sandboxes A sandbox is used to commit files so they only need to be updated one time, as opposed to every time a cookbook is uploaded. The `/sandboxes` endpoint has the following methods: `POST`. #### POST The `POST` method is used to create a new sandbox. This method accepts a list of checksums as input and returns the URLs against which to `PUT` files that need to be uploaded. This method has no parameters. **Request** ``` POST /organizations/NAME/sandboxes ``` with a request body similar to: ``` {"checksums": { "385ea5490c86570c7de71070bce9384a":null, "f6f73175e979bd90af6184ec277f760c":null, "2e03dd7e5b2e6c8eab1cf41ac61396d5":null } } ``` **Response** The response is similar to: ``` {"uri": "https://api.chef.io/organizations/testorg/sandboxes/eff7b6f8b3ef44c6867216662d5eeb5f", "checksums": {"385ea5490c86570c7de71070bce9384a": {"url": "https://s3.amazonaws.com/opscode-platform-production-data/organization-(...)", "needs_upload":true}, "f6f73175e979bd90af6184ec277f760c"=> {"url": "https://s3.amazonaws.com/opscode-platform-production-data/organization-(...)", "needs_upload":true}, "2e03dd7e5b2e6c8eab1cf41ac61396d5": {"url": "https://s3.amazonaws.com/opscode-platform-production-data/organization-(...)", "needs_upload":true} }, "sandbox_id"=>"eff7b6f8b3ef44c6867216662d5eeb5f" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. A hash that maps each checksum to a hash that contains a boolean `needs_upload` field and a URL if `needs_upload` is set to `true`. | | `400` | Bad request. The object has already been committed or one (or more) of the objects were not properly uploaded. The payload does not contain a well-formed `checksums` parameter that is a hash containing a key for each checksum. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /sandboxes/ID Each sandbox has a unique identifier. The `/sandboxes/ID` endpoint has the following methods: `PUT`. #### PUT The `PUT` method is used to commit files that are in a sandbox to their final location so that changes to cookbooks will not require re-uploading the same data. This method has no parameters. **Request** ``` PUT /organizations/NAME/sandboxes/ID ``` with a request body similar to: ``` {"is_completed":true} ``` **Response** The response is similar to: ``` { "guid": guid, "name": guid, "checksums": {"385ea5490c86570c7de71070bce9384a": {"url": "https://s3.amazonaws.com/opscode-platform-production-data/organization-(...)", "needs_upload":true} }, "create_time": <get an example of time format>, "is_completed": true } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /search Search indexes allow queries to be made for any type of data that is indexed by the Chef Infra Server, including data bags (and data bag items), environments, nodes, and roles. A defined query syntax is used to support search patterns like exact, wildcard, range, and fuzzy. A search is a full-text query that can be done from several locations, including from within a recipe, by using the `search` subcommand in knife, the `search` method in the Chef Infra Language, the search box in the Chef management console, and by using the `/search` or `/search/INDEX` endpoints in the Chef Infra Server API. The search engine is based on Elasticsearch and is run from the Chef Infra Server. The `/search` endpoint allows nodes, roles, data bags, environments to be searched. This endpoint has the following methods: `GET`. Note At the end of every Chef Infra Client run, the node object is saved to the Chef Infra Server. From the Chef Infra Server, each node object is then added to the Apache Solr search index. This process is asynchronous. By default, node objects are committed to the search index every 60 seconds or per 1000 node objects, whichever occurs first. Note This endpoint does not have any ACL restrictions, which means it may be used by any user or client that is able to make the request to the Chef Infra Server. #### GET The `GET` method is used to return a data structure that contains links to each available search index. By default, the `role`, `node`, `client`, and `data bag` indexes will always be available (where the `data bag` index is the name of the data bag on the Chef Infra Server). Search indexes may lag behind the most current data at any given time. If a situation occurs where data needs to be written and then immediately searched, an artificial delay (of at least 10 seconds) is recommended. This method has no parameters. **Request** ``` GET /organizations/NAME/search ``` This method has no request body. **Response** The response is similar to: ``` { "node": "https://chef.example/organizations/org1/search/node", "role": "https://chef.example/organizations/org1/search/role", "client": "https://chef.example/organizations/org1/search/client", "users": "https://chef.example/organizations/org1/search/users" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | ### /search/INDEX Use the `/search/INDEX` endpoint to access the search indexes on the Chef Infra Server. The `/search/INDEX` endpoint has the following methods: `GET` and `POST`. A search query is comprised of two parts: the key and the search pattern. A search query has the following syntax: ``` key:search_pattern ``` where `key` is a field name that is found in the JSON description of an indexable object on the Chef Infra Server (a role, node, client, environment, or data bag) and `search_pattern` defines what will be searched for, using one of the following search patterns: exact, wildcard, range, or fuzzy matching. Both `key` and `search_pattern` are case-sensitive; `key` has limited support for multiple character wildcard matching using an asterisk ("*") (and as long as it is not the first character). #### GET The `GET` method is used to return all of the data that matches the query in the `GET` request. This method has the following parameters: | Parameter | Description | | --- | --- | | `q` | The search query used to identify a list of items on a Chef Infra Server. This option uses the same syntax as the `knife search` subcommand. | | `rows` | The number of rows to be returned. | | `start` | The row at which return results begin. | **Request** ``` GET /organizations/NAME/search/INDEX ``` **Response** The response contains the total number of rows that match the request and for a node index search is similar to: ``` { "total": 1, "start": 0, "rows": [ { "automatic": {"hardware_type": "laptop"}, "chef_environment": "_default", "chef_type": "node", "default": {} "json_class": "Chef::Node", "name": "latte", "normal": {}, "override": {"hardware_type": "laptop"}, "run_list": ["recipe[unicorn]"] } ] } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST A partial search query allows a search query to be made against specific attribute keys that are stored on the Chef Infra Server. A partial search query can search the same set of objects on the Chef Infra Server as a full search query, including specifying an object index and providing a query that can be matched to the relevant index. While a full search query will return an array of objects that match (each object containing a full set of attributes for the node), a partial search query will return only the values for the attributes that match. One primary benefit of using a partial search query is that it requires less memory and network bandwidth while Chef Infra Client processes the search results. The attributes to be returned by the partial search are specified in the request JSON body. This method has the following parameters: | Parameter | Description | | --- | --- | | `q` | The search query used to identify a list of items on a Chef Infra Server. This option uses the same syntax as the `search` subcommand. | | `rows` | The number of rows to be returned. | | `start` | The row at which return results begin. | **Request** ``` POST /organizations/NAME/search ``` with a request body similar to: ``` { "name": [ "name" ], "ip": [ "ipaddress" ], "kernel_version": [ "kernel", "version" ] } ``` **Response** The response is similar to: ``` { "total":1, "start":0, "rows": [ { "url": "https://chef.example/organization/org1/nodes/latte", "data": { "name": "latte", "ip": "123.4.5.6789", "kernel_version": {"linux": "1.2.3"} } } ] } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /universe Use the `/universe` endpoint to retrieve the known collection of cookbooks, and then use it with Berkshelf and Chef Supermarket. The `/universe` endpoint has the following methods: `GET`. #### GET The `GET` method is used to retrieve the universe data. This method has no parameters. This method has no request body. **Request** ``` GET /universe ``` **Response** The response will return a json hash, with the name of each cookbook as a top-level key. Each cookbook will list each version, along with its location information and dependencies: ``` { "ffmpeg": { "0.1.0": { "location_path": "http://supermarket.chef.io/api/v1/cookbooks/ffmpeg/0.1.0/download", "location_type": "supermarket", "dependencies": { "git": ">= 0.0.0", "build-essential": ">= 0.0.0", "libvpx": "~> 0.1.1", "x264": "~> 0.1.1" } }, "0.1.1": { "location_path": "http://supermarket.chef.io/api/v1/cookbooks/ffmpeg/0.1.1/download", "location_type": "supermarket", "dependencies": { "git": ">= 0.0.0", "build-essential": ">= 0.0.0", "libvpx": "~> 0.1.1", "x264": "~> 0.1.1" } } }, "pssh": { "0.1.0": { "location_path": "http://supermarket.chef.io/api/v1/cookbooks/pssh.1.0/download", "location_type": "supermarket", "dependencies": {} } } } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. One (or more) cookbooks and associated cookbook version information was returned. | ### /updated_since The `/updated_since` endpoint ensures that replica instances of the Chef Infra Server are able to synchronize with the primary Chef Infra Server. `/updated_since` was part of the Chef Replication product. Chef Replication is no longer available as a product and the `/updated_since` endpoint is also deprecated. The expectation for almost all chef users is that use of the endpoint will return an http status of 404. The `/organizations/NAME/updated_since` endpoint has the following methods: `GET`. Warning This update is available after Chef replication is installed on the Chef Infra Server. #### GET The `GET` method is used to return the details of an organization as JSON. **Request** ``` GET /organizations/NAME/updated_since?seq=NUM ``` where `NUM` is the largest integer previously returned as an identifier. **Response** The response will return an array of paths for objects that have been created, updated, or deleted since `NUM`, similar to: ``` [ { "action": "create", "id": 1, "path": "/roles/foo" }, { "action": "create", "id": 2, "path": "/roles/foo2" }, { "action": "create", "id": 3, "path": "/roles/foo3" }, { "action": "update", "id": 4, "path": "/roles/foo3" } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist or the function is not implemented. | ### /users A user may be associated with an organization. The `/users` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to return an array of usernames for users associated with an organization. This method has no parameters. **Request** ``` GET /organizations/NAME/users ``` This method has no request body. **Response** The response is similar to: ``` [ { "user": { "username": "paperlatte" } } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to associate a user with an organization immediately. Superuser only. This method has no parameters. **Request** ``` POST /organizations/NAME/users ``` with a request body similar to: ``` { "username": "paperlatte", } ``` where `username` is the name of the user to be associated. **Response** No response block is returned. **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The user was associated with the organization. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The user is already associated. | ### /users/NAME The `/users/NAME` endpoint has the following methods: `DELETE`, `GET`. #### DELETE The `DELETE` method is used to delete a user association with an organization. This method has no parameters. **Request** ``` DELETE /organizations/NAME/users/NAME ``` **Response** The response will return the end state of the user, similar to: ``` { "username": "paperlatte" "email": "latte", "display_name": "<NAME>", "first_name": "Paper", "last_name": "Latte", "public_key": "-----BEGIN PUBLIC KEY----- ... " } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. The user association was removed. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return the details of a user as JSON. This method has no parameters. **Request** ``` GET /organizations/NAME/users/NAME ``` **Response** The response is similar to: ``` { "username": "paperlatte" "email": "latte", "display_name": "<NAME>", "first_name": "Paper", "last_name": "Latte", "public_key": "-----BEGIN PUBLIC KEY----- ... " } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | Examples -------- The following sections show examples of using the Chef Infra Server API. ### Query for Users and Orgs The following example shows how to query the Chef Infra Server API for a listing of organizations and users. The `/organizations` and `/users` endpoints may only be accessed by the `pivotal` user, which is a user account that is created by Chef during the installation of the Chef Infra Server. Run the following from a `.chef` directory that contains a `pivotal.rb` file: ``` require 'chef' require 'chef/server_api' Chef::Config.from_file('.chef/pivotal.rb') rest = Chef::ServerAPI.new(Chef::Config[:chef_server_url]) orgs = rest.get('/organizations') puts "\n=== Listing of organizations" orgs.each do |org| puts org end puts "\n=== Listing of Users" users = rest.get('/users') users.each do |user| puts user end ``` An example of a `.chef/pivotal.rb` file is shown below: ``` current_dir = File.dirname(__FILE__) node_name 'pivotal' chef_server_url 'https://192.0.2.0:443' chef_server_root 'https://192.0.2.0:443' client_key "#{current_dir}/pivotal.pem" ``` Note The `pivotal.pem` file must exist in the specified location and the IP addresses must be correct for the Chef Infra Server. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server/api_chef_server/auditd resource =============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/auditd.md) Use the `auditd` Chef InSpec audit resource to test the rules for logging that exist on the system. The audit.rules file is typically located under /etc/audit/ and contains the list of rules that define what is captured in log files. These rules are output using the auditctl -l command. This resource supports versions of `audit` >= 2.3. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.38.8 of InSpec. Syntax ------ An `auditd` resource block declares one (or more) rules to be tested, and then what that rule should do: ``` describe auditd do its('lines') { should include %r(-w /etc/ssh/sshd_config) } end ``` or test that multiple individual rules are defined: ``` describe auditd do its('lines') { should include %r(-a always,exit -F arch=.* -S init_module,delete_module -F key=modules) } its('lines') { should include %r(-a always,exit -F arch=.* -S chmod,fchmod,fchmodat -F auid>=1000 -F auid!=-1 -F key=.+) } end ``` where each test must declare one (or more) rules to be tested. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if a rule contains a matching element that is identified by a regular expression For `audit` >= 2.3: ``` describe auditd do its('lines') { should include %r(-a always,exit -F arch=.* -S chown.* -F auid>=1000 -F auid!=-1 -F key=perm_mod) } end ``` ### Query the audit daemon status ``` describe auditd.status('backlog') do it { should cmp 0 } end ``` ### Query properties of rules targeting specific syscalls or files - uniq is used to handle multiple rules for the same syscall with redundant field values ``` describe auditd.syscall('open') do its('action.uniq') { should eq ['always'] } its('list.uniq') { should eq ['exit'] } end describe auditd.file('/etc/sudoers') do its('permissions') { should include ['x'] } end ``` The where accessor can be used to filter on fields. For example: ``` describe auditd.syscall('chown').where { arch == "b32" } do its('action') { should eq ['always'] } its('list') { should eq ['exit'] } its('exit') { should include ['-EACCES'] } its('exit') { should include ['-EPERM'] } end ``` The key filter may be useful in evaluating rules with particular key values: ``` describe auditd.where { key == "privileged" } do its('permissions') { should include ['x'] } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/auditd/apache_conf resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/apache_conf.md) Use the `apache_conf` Chef InSpec audit resource to test the configuration settings for Apache. This file is typically located under `/etc/apache2` on the Debian and Ubuntu platforms and under `/etc/httpd` on the Fedora, CentOS, RedHat Enterprise Linux, and ArchLinux platforms. The configuration settings may vary significantly from platform to platform. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Requirements `ServerRoot` must be included in an Apache configuration file. If not present, the included configurations will not be accessible to the resource. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `apache_conf` Chef InSpec audit resource block declares configuration settings that should be tested: ``` describe apache_conf('path') do its('setting_name') { should eq 'value' } end ``` where * `'setting_name'` is a configuration setting defined in the Apache configuration file * `('path')` is the non-default path to the Apache configuration file * `{ should eq 'value' }` is the value that is expected Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test for blocking .htaccess files on CentOS ``` describe apache_conf do its('AllowOverride') { should cmp 'None' } end ``` ### Test ports for SSL ``` describe apache_conf do its('Listen') { should cmp '443' } end ``` ### Test multiple ports are listening ``` describe apache_conf do its('Listen') { should =~ [ '80', '443' ] } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). This Chef InSpec audit resource matches any service that is listed in the Apache configuration file: ``` its('PidFile') { should_not eq '/var/run/httpd.pid' } ``` or: ``` its('Timeout') { should cmp '300' } ``` For example: ``` describe apache_conf do its('MaxClients') { should cmp '100' } its('Listen') { should cmp '443' } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/apache_conf/apache resource =============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/apache.md) Warning This resource is deprecated and should not be used. It was removed in Chef InSpec 4.0. The documentation below is preserved as a reference. Replacement functionality is available in the [`apache_conf`](../apache_conf/index) resource. Use the `apache` Chef InSpec audit resource to test the state of the Apache server on Linux/Unix systems. Availability ------------ ### Installation This resource was distributed along with Chef InSpec itself. ### Version This resource first became available in v1.51.15 of InSpec and was removed in version 4.0. Syntax ------ An `apache` Chef InSpec audit resource block declares settings that should be tested: ``` describe apache do its('setting_name') { should cmp 'value' } end ``` where * `'setting_name'` is description of the Apache configuration file * `{ should cmp 'value' }` is the value that is expected Properties ---------- * `service`, `conf_dir`, `conf_path`, `user` Property Examples ----------------- The following examples show how to use this Chef InSpec audit resource. ### Test the service name. ``` describe apache do its ('service') { should cmp 'apache2' } end ``` ### Test the configuration location ``` describe apache do its ('conf_dir') { should cmp '/etc/apache2' } end ``` ### Test the path of the configuration file ``` describe apache do its ('conf_path') { should cmp '/etc/apache2/apache2.conf' } end ``` ### Test the apache user ``` describe apache do its ('user') { should cmp 'www-data' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/apache/apt resource ============ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/apt.md) Use the `apt` Chef InSpec audit resource to verify Apt repositories on the Debian and Ubuntu platforms, and also PPA repositories on the Ubuntu platform. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `apt` resource block tests the contents of Apt and PPA repositories: ``` describe apt('path') do it { should exist } it { should be_enabled } end ``` where * `apt('path')` must specify an Apt or PPA repository * `('path')` may be an `http://` address, a `ppa:` address, or a short `repo-name/ppa` address * `exist` and `be_enabled` are a valid matchers for this resource Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if apt repository exists and is enabled ``` describe apt('http://ppa.launchpad.net/juju/stable/ubuntu') do it { should exist } it { should be_enabled } end ``` ### Verify that a PPA repository exists and is enabled ``` describe apt('ppa:nginx/stable') do it { should exist } it { should be_enabled } end ``` ### Verify that a repository is not present ``` describe apt('ubuntu-wine/ppa') do it { should_not exist } it { should_not be_enabled } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if a repository is enabled on the system: ``` it { should be_enabled } ``` ### exist The `exist` matcher tests if a repository exists on the system: ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/apt/audit_policy resource ====================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/audit_policy.md) Use the `audit_policy` Chef InSpec audit resource to test auditing policies on the Windows platform. An auditing policy is a category of security-related events to be audited. Auditing is disabled by default and may be enabled for categories like account management, logon events, policy changes, process tracking, privilege use, system events, or object access. For each enabled auditing category property, the auditing level may be set to `No Auditing`, `Not Specified`, `Success`, `Success and Failure`, or `Failure`. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `audit_policy` resource block declares a parameter that belongs to an audit policy category or subcategory: ``` describe audit_policy do its('parameter') { should eq 'value' } end ``` where * `'parameter'` must specify a parameter * `'value'` must be one of `No Auditing`, `Not Specified`, `Success`, `Success and Failure`, or `Failure` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test that a parameter is not set to “No Auditing” ``` describe audit_policy do its('Other Account Logon Events') { should_not eq 'No Auditing' } end ``` ### Test that a parameter is set to “Success” ``` describe audit_policy do its('User Account Management') { should eq 'Success' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/audit_policy/auditd_conf resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/auditd_conf.md) Use the `auditd_conf` Chef InSpec audit resource to test the configuration settings for the audit daemon. This file is typically located under `/etc/audit/auditd.conf'` on Unix and Linux platforms. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `auditd_conf` resource block declares configuration settings that should be tested: ``` describe auditd_conf('path') do its('keyword') { should cmp 'value' } end ``` where * `'keyword'` is a configuration setting defined in the `auditd.conf` configuration file * `('path')` is the non-default path to the `auditd.conf` configuration file * `{ should cmp 'value' }` is the value that is expected Properties ---------- This matcher will match any property listed in the `auditd.conf` configuration file. Property names and expected values are case-insensitive: * `admin_space_left`, `admin_space_left_action`, `action_mail_acct`, `conf_path`, `content`, `disk_error_action`, `disk_full_action`, `flush`, `freq`, `log_file`, `log_format`, `max_log_file`, `max_log_file_action`, `num_logs`, `params`, `space_left`, `space_left_action` Property Examples ----------------- The following examples show how to use this Chef InSpec audit resource. ### Test the auditd.conf file ``` describe auditd_conf do its('log_file') { should cmp '/full/path/to/file' } its('log_format') { should cmp 'raw' } its('flush') { should cmp 'none' } its('freq') { should cmp 1 } its('num_logs') { should cmp 0 } its('max_log_file') { should cmp 6 } its('max_log_file_action') { should cmp 'email' } its('space_left') { should cmp 2 } its('action_mail_acct') { should cmp 'root' } its('space_left_action') { should cmp 'email' } its('admin_space_left') { should cmp 1 } its('admin_space_left_action') { should cmp 'halt' } its('disk_full_action') { should cmp 'halt' } its('disk_error_action') { should cmp 'halt' } end describe file(auditd_conf.conf_path) do its('group') { should cmp 'root' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### `cmp` The `cmp` matcher compares values across types. ``` its('freq') { should cmp 1 } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/auditd_conf/bash resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/bash.md) Use the `bash` Chef InSpec audit resource to test an arbitrary command that is run on the system using a Bash script. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `command` resource block declares a command to be run, one (or more) expected outputs, and the location to which that output is sent: ``` describe bash('command') do it { should exist } its('property') { should eq 'expected value' } end ``` where * `'command'` must specify a command to be run * `'property'` is one of `exit_status`, `stderr`, or `stdout` * `'expected value'` tests the output of the command run on the system versus the expected output stated in the test For example: ``` describe bash('ls -al /') do its('stdout') { should match /bin/ } its('stderr') { should eq '' } its('exit_status') { should eq 0 } end ``` Properties ---------- ### exit_status The `exit_status` property returns the exit status for the command. ``` its('exit_status') { should eq 0 } ``` ### stderr The `stderr` property returns results of the command as returned in standard error (stderr). ``` its('stderr') { should eq '' } ``` ### stdout The `stdout` property returns the results of the command as returned in standard output (stdout). ``` its('stdout') { should match /bin/ } ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist If an absolute path is provided, the `exist` matcher tests if the command exists on the filesystem at the specified location. Otherwise, the `exist` matcher tests if the command is found in the PATH. ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/bash/bond resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/bond.md) Use the `bond` Chef InSpec audit resource to test a logical, bonded network interface (i.e. “two or more network interfaces aggregated into a single, logical network interface”). On Linux platforms, any value in the `/proc/net/bonding` directory may be tested. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `bond` resource block declares a bonded network interface, and then specifies the properties of that bonded network interface to be tested: ``` describe bond('name') do it { should exist } end ``` where * `'name'` is the name of the bonded network interface * `{ should exist }` is a valid matcher for this resource Properties ---------- ### content The `content` property returns the contents in the file that defines the bonded network interface. The values of the `content` property are arbitrary. ``` its('content') { should match('value') } ``` ### interfaces The `interfaces` property tests if the named secondary interfaces are available. ``` its('interfaces') { should eq ['eth0', 'eth1', ...] } ``` ### mode The `mode` property returns the Bonding Mode. ``` its('mode') { should eq 'IEEE 802.3ad Dynamic link aggregation' } ``` ### params The `params` property returns arbitrary parameters for the bonded network interface. ``` its('params') { should eq 'value' } ``` Examples -------- ### Test if eth0 is a secondary interface for bond0 ``` describe bond('bond0') do it { should exist } it { should have_interface 'eth0' } end ``` ### Test parameters for bond0 ``` describe bond('bond0') do its('mode') { should eq 'IEEE 802.3ad Dynamic link aggregation' } its('params') { should have_key 'Transmit Hash Policy' } its('params') { should include 'Transmit Hash Policy' => 'layer3+4 (1)' } its('params') { should have_key 'MII Status' } its('params') { should include 'MII Status' => 'up' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `exist` matcher tests if the bonded network interface is available: ``` it { should exist } ``` ### have_interface The `have_interface` matcher tests if the bonded network interface has one (or more) secondary interfaces: ``` it { should have_interface } ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/bond/cassandradb_session resource ============================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/cassandradb_session.md) Use the `cassandradb_session` Chef InSpec audit resource to test Cassandra Query Language (CQL) commands run against a Cassandra database. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. Syntax ------ A `cassandradb_session` resource block declares the username, password, host, and port to use for the session, and then the command to be run: ``` describe cassandradb_session(user: 'USERNAME', password: 'PASSWORD', host: 'localhost', port: 9042).query('QUERY') do its('value') { should eq('EXPECTED') } end ``` where * `cassandradb_session` declares a username, password, host and port to run the query. * `query('QUERY')` contains the query to be run. * `its('value') { should eq('expected') }` compares the results of the query against the expected result in the test. ### Optional Parameters The `cassandradb_session` InSpec resource accepts `user`, `password`, `host`, and `port` parameters. In Particular: #### `user` Default value: `cassandra`. #### `password` Default value: `cassandra`. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test for matching values using a Cassandra query ``` cql = cassandradb_session(user: 'MY_USER', password: 'PASSWORD', host: 'localhost', port: 9042) describe cql.query("SELECT cluster_name FROM system.local") do its('output') { should match /Test Cluster/ } end ``` ### Test for matching values using a Cassandra query from a sample database ``` cql = cassandradb_session(user: 'MY_USER', password: 'PASSWORD', host: 'localhost', port: 9042) describe cql.query("use SAMPLEDB; SELECT name FROM SAMPLETABLE") do its('output') { should match /Test Name/ } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/cassandradb_session/bridge resource =============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/bridge.md) Use the `bridge` Chef InSpec audit resource to test basic network bridge properties, such as `name`, if an interface is defined, and the associations for any defined interface. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `bridge` resource block declares the bridge to be tested and what interface it should be associated with: ``` describe bridge('br0') do it { should exist } it { should have_interface 'eth0' } end ``` * On Linux platforms, any value in the `/sys/class/net/{interface}/bridge` directory may be tested * On the Windows platform, the `Get-NetAdapter` cmdlet is associated with the `Get-NetAdapterBinding` cmdlet and returns the `ComponentID ms_bridge` value as a JSON object Properties ---------- ### interfaces The `interfaces` property returns the named interfaces. ``` its('interfaces') { should include('foo') } ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `exist` matcher tests if the network bridge is available: ``` it { should exist } ``` ### have_interface The `have_interface` matcher tests if the named interface is defined for the network bridge: ``` it { should have_interface 'eth0' } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/bridge/chocolatey_package resource ============================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/chocolatey_package.md) Use the `chocolatey_package` Chef InSpec audit resource to test if the named [Chocolatey](https://chocolatey.org/) package and/or package version is installed on the system. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v2.1.30 of InSpec. Syntax ------ A `chocolatey_package` resource block declares the name of a Chocolatey package to be tested: ``` describe chocolatey_package('name') do it { should be_installed } end ``` where * `('name')` must specify the (case-sensitive) name of a package, such as `'nssm'` * `be_installed` is a valid matcher for this resource Examples -------- The following examples show how to use this Chef InSpec audit resource ### Test if NSSM version 2.1.0 is installed ``` describe chocolatey_package('nssm') do it { should be_installed } its('version') { should eq '2.1.0' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers). ### be_installed The `be_installed` matcher tests if the named package is installed at all. ``` it { should be_installed } ``` ### version The `version` matcher tests if the named package version is on the system: ``` its('version') { should eq '2.1.0' } ``` You can also use the `cmp OPERATOR` matcher to perform comparisons using the version attribute: ``` its('version') { should cmp >= '1.93.4-13debug84' } ``` `cmp` understands version numbers using Gem::Version, and can use the operators `==, <, <=, >=, and >`. It will compare versions by each segment, not as a string - so ‘7.4’ is smaller than ‘7.30’, for example. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/chocolatey_package/bsd_service resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/bsd_service.md) Use the `bsd_service` Chef InSpec audit resource to test a service using a Berkeley OS-style `init` on the FreeBSD platform. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `bsd_service` resource block declares the name of a service and then one (or more) matchers to test the state of the service: ``` describe bsd_service('service_name') do it { should be_installed } it { should be_enabled } it { should be_running } end ``` where * `('service_name')` must specify a service name * `be_installed`, `be_enabled`, and `be_running` are the different [matchers](#matchers) for this resource. Parameters ---------- ### Path The path to the service manager’s control may be specified for situations where the path isn’t available in the current `PATH`. For example: ``` describe bsd_service('service_name', '/path/to/control') do it { should be_enabled } it { should be_installed } it { should be_running } end ``` Properties ---------- All properties available to the [`service`](../service/index) resource may be used. Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if the named service is enabled: ``` it { should be_enabled } ``` ### be_installed The `be_installed` matcher tests if the named service is installed: ``` it { should be_installed } ``` ### be_running The `be_running` matcher tests if the named service is running: ``` it { should be_running } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/bsd_service/cassandradb_conf resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/cassandradb_conf.md) Use the `cassandradb_conf` Chef InSpec audit resource to test the configuration of a Cassandra database, which is typically located at `$CASSANDRA_HOME/cassandra.yaml` or `$CASSANDRA_HOME\conf\cassandra.yaml` depending upon the platform. Installation ------------ This resource is distributed along with Chef InSpec itself. You can use it automatically. Requirements ------------ * The value of the `CASSANDRA_HOME` environment variable must be set in the system. Syntax ------ A `cassandradb_conf` resource block fetches configurations in the `cassandra.yaml` file, and then compares them with the value stated in the test: ``` describe cassandradb_conf do its('config item') { should eq 'value' } end ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test parameters set within the configuration file ``` describe cassandradb_conf do its('listen_address') { should eq 'localhost' } its('num_tokens') { should eq 16 } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/cassandradb_conf/chrony_conf resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/chrony_conf.md) Use the `chrony_conf` Chef InSpec audit resource to test the synchronization settings defined in the `chrony.conf` file. This file is typically located at `/etc/chrony.conf`. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. Syntax ------ An `chrony_conf` resource block declares the synchronization settings that should be tested: ``` describe chrony_conf('PATH') do its('setting_name') { should eq 'VALUE' } end ``` where: * `'setting_name'` is a synchronization setting defined in the `chrony.conf` file. * `('path')` is the non-default path to the `chrony.conf` file (default path is `/etc/chrony.conf`). * `{ should eq 'value' }` is the value that is expected. Examples -------- The following examples show how to use this Chef InSpec audit resource. This resource matches any service listed in the `chrony.conf` file. ### Test for clock drift against named servers ``` describe chrony_conf do its('driftfile') { should cmp '/var/lib/chrony/drift' } its('server') do should cmp [ '0.ubuntu.pool.ntp.org', '1.ubuntu.pool.ntp.org', '2.ubuntu.pool.ntp.org' ] end end ``` ### Test that an NTP server exists and a specific subnet is specified from which NTP clients are accessible ``` describe chrony_conf do its('server') { should_not eq nil } its('allow') { should include '192.168.0.0/16'} end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/chrony_conf/cran resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/cran.md) Use the `cran` Chef InSpec audit resource to test R modules that are installed from CRAN package repository. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.43.5 of InSpec. Syntax ------ A `cran` resource block declares a package and (optionally) a package version: ``` describe cran('package_name') do it { should be_installed } end ``` where * `'package_name'` is the name of the package, such as `'DBI'` * `be_installed` tests to see if the package described above is installed Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if DBI is installed on the system ``` describe cran('DBI') do it { should be_installed } end ``` ### Test if DBI 0.5.1 is installed on the system ``` describe cran('DBI') do it { should be_installed } its('version') { should eq '0.5.1' } end ``` Property Examples ----------------- ### version The `version` property tests if the named package version is on the system: ``` its('version') { should eq '1.2.3' } ``` Matchers -------- This Chef InSpec audit resource has the following matchers: ### be_installed The `be_installed` matcher tests if the named package is installed on the system: ``` it { should be_installed } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/cran/cpan resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/cpan.md) Use the `cpan` Chef InSpec audit resource to test Perl modules that are installed by system packages or the CPAN installer. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.43.5 of InSpec. Syntax ------ A `cpan` resource block declares a package and (optionally) a package version: ``` describe cpan('package_name') do it { should be_installed } end ``` where * `'package_name'` is the name of the package, such as `'DBD::Pg'` * `be_installed` tests to see if the package described above is installed Resource Parameters ------------------- This resource uses package names and perl library paths as resource parameters. Resource Parameter Examples --------------------------- ### Test if DBD::Pg is installed on the system ``` describe cpan('DBD:Pg') do it { should be_installed } end ``` ### Test if DBD::Pg 3.7.0 is installed on the system ``` describe cpan('DBD::Pg') do it { should be_installed } its('version') { should eq '3.7.0' } end ``` ### Test if DBD::Pg is installed within a custom PERL5LIB path on the system Hint: You can pass multiple paths separated with a colon `/path/to/perl5/lib:/usr/share/perl5/vendor_perl/lib/perl5` ``` describe cpan('DBD::Pg', '/home/jdoe/perl5/lib/perl5') do it { should be_installed } end ``` Property Examples ----------------- The following examples show how to use this Chef InSpec audit resource. ### version The `version` property tests if the named package version is on the system: ``` its('version') { should eq '1.2.3' } ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_installed The `be_installed` matcher tests if the named package is installed on the system: ``` it { should be_installed } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/cpan/command resource ================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/command.md) Use the `command` Chef InSpec audit resource to test an arbitrary command that is run on the system. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `command` resource block declares a command to be run, one (or more) expected values, and the location to which that output is sent: ``` describe command('command') do it { should exist } its('property') { should eq 'value' } end ``` where * `'command'` must specify a command to be run * `'property'` is one of `exit_status`, `stderr`, or `stdout` * `'output'` tests the output of the command run on the system versus the output value stated in the test Property Examples ----------------- The following examples show how to use this Chef InSpec audit resource. ### exit_status The `exit_status` property tests the exit status for the command: ``` its('exit_status') { should eq 123 } ``` ### stderr The `stderr` property tests results of the command as returned in standard error (stderr): ``` its('stderr') { should eq 'error' } ``` ### stdout The `stdout` property tests results of the command as returned in standard output (stdout). The following example shows matching output using a regular expression: ``` describe command('echo 1') do its('stdout') { should match (/[0-9]/) } end ``` ### Test standard output (stdout) ``` describe command('echo hello') do its('stdout') { should eq "hello\n" } its('stderr') { should eq '' } its('exit_status') { should eq 0 } end ``` ### Test standard error (stderr) ``` describe command('>&2 echo error') do its('stdout') { should eq '' } its('stderr') { should eq "error\n" } its('exit_status') { should eq 0 } end ``` ### Test an exit status code ``` describe command('exit 123') do its('stdout') { should eq '' } its('stderr') { should eq '' } its('exit_status') { should eq 123 } end ``` ### Test if the command shell exists ``` describe command('/bin/sh').exist? do it { should eq true } end ``` ### Test for a command that should not exist ``` describe command('this is not existing').exist? do it { should eq false } end ``` ### Test for PostgreSQL database running a RC, development, or beta release ``` describe command('psql -V') do its('stdout') { should eq '/RC/' } its('stdout') { should_not eq '/DEVEL/' } its('stdout') { should_not eq '/BETA/' } end ``` ### Verify NTP The following example shows how to use the `file` audit resource to verify if the `ntp.conf` and `leap-seconds` files are present, and then the `command` resource to verify if NTP is installed and running: ``` describe file('/etc/ntp.conf') do it { should be_file } end describe file('/etc/ntp.leapseconds') do it { should be_file } end describe command('pgrep ntp') do its('exit_status') { should eq 0 } end ``` ### Verify WiX Wix includes several tools – such as `candle` (preprocesses and compiles source files into object files), `light` (links and binds object files to an installer database), and `heat` (harvests files from various input formats). The following example uses a whitespace array and the `file` audit resource to verify if these three tools are present: ``` %w( candle.exe heat.exe light.exe ).each do |utility| describe file("C:/wix/##{utility}") do it { should be_file } end end ``` ### Timing Out Long-Running Commands On target platforms that support the feature, the command resource takes an optional `timeout:` parameter which specifies how long the command may run in seconds before erroring out and failing the control. ``` describe command("find / -owner badguy", timeout: 300) do its("stdout") { should be_empty } end ``` This example would run the `find` command for up to 300 seconds, then give up and fail the control if it exceeded that time. On supported target platforms, the default timeout is 3600 seconds (one hour). Aside from setting the value on a per-resource basis, you may also use the `--command-timeout` CLI option to globally set a command timeout. The CLI option takes precedence over any per-resource `timeout:` options. Currently supported target platforms include: * Local Unix-like OSes, including macOS * SSH targets * Windows targets via WinRM Any target platforms not listed are not supported at this time. On unsupported platforms, the timeout value is ignored and the command will run indefinitely. ### Redacting Sensitive Commands By default the command that is ran is shown in the Chef InSpec output. This can be problematic if the command contains sensitive arguments such as a password. These sensitive parts can be redacted by passing in `redact_regex` and a regular expression to redact. Optionally, you can use 2 capture groups to fine tune what is redacted. The following examples show how to use `redact_regex`: ``` # Example without capture groups describe command('myapp -p secretpassword -d no_redact', redact_regex: /-p .* -d/) do its('exit_status') { should cmp 0 } end # Result (no capture groups used) Command: `myapp REDACTED no_redact` ✔ exit_status should cmp == 0 # Example with capture groups # Each set of parenthesis is a capture group. # Anything in the two capture groups will not be 'REDACTED' describe command('myapp -p secretpassword -d no_redact', redact_regex: /(-p ).*( -d)/) do its('exit_status') { should cmp 0 } end # Result (capture groups used) Command: `myapp -p REDACTED -d no_redact` ✔ exit_status should cmp == 0 ``` For more info/help on regular expressions, we recommend [RegExr](https://regexr.com/) Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `exist` matcher tests if a command may be run on the system: ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/command/crontab resource ================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/crontab.md) Use the `crontab` Chef InSpec audit resource to test the crontab entries for a particular user on the system. It recognizes special time strings (@yearly, @weekly, etc). Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.15.0 of InSpec. Syntax ------ A `crontab` resource block declares a user (which defaults to the current user) and the details to be tested, such as the schedule elements for each crontab entry or the exact commands themselves: ``` describe crontab do its('commands') { should include '/some/scheduled/task.sh' } end ``` Note The `include` matcher in this context specifies the entire list of commands that the crontab should include and not a particular substring that should be included by a command. The `include` matcher always matches a complete command invocation, including options and arguments. The path to the system crontab can also be supplied via: ``` describe crontab(path: '/etc/cron.d/some_crontab') do its('commands') { should include '/path/to/some/script' } end ``` Note that only the path or the user (and not both) should be supplied as arguments to the resource. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test that root’s crontab has a particular command ``` describe crontab('root') do its('commands') { should include '/path/to/some/script -option arg' } end ``` ### Test that myuser’s crontab entry for command ‘/home/myuser/build.sh’ runs every minute ``` describe crontab('myuser').commands('/home/myuser/build.sh') do its('hours') { should cmp '*' } its('minutes') { should cmp '*' } end ``` ### Test that the logged-in user’s crontab has no tasks set to run on every hour and every minute ``` describe crontab.where({'hour' => '*', 'minute' => '*'}) do its('entries.length') { should cmp '0' } end ``` ### Test that the logged-in user’s crontab contains a single command that matches a pattern ``` describe crontab.where { command =~ /a partial command string/ } do its('entries.length') { should cmp 1 } end ``` ### Test a special time string (i.e., @yearly /root/annual_report.sh) ``` describe crontab.commands('/root/annual_report.sh') do its('hours') { should cmp '0' } its('minutes') { should cmp '0' } its('days') { should cmp '1' } its('months') { should cmp '1' } end ``` ### Test @reboot case ``` describe crontab.commands('/root/reboot.sh') do its('hours') { should cmp '-1' } its('minutes') { should cmp '-1' } end ``` Property Examples ----------------- ### Test a special time string ``` describe crontab do its('minutes') { should cmp '0' } its('hours') { should cmp '0' } its('days') { should cmp '1' } its('weekdays') { should cmp '1' } its('user') { should include 'username'} its('commands') { should include '/some/scheduled/task.sh' } end ``` Chef InSpec will automatically interpret crontab-supported special time strings. For example, a crontab entry set to run `@yearly` can be tested as if the entry was manually configured to run on January 1, 12 AM. Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/crontab/csv resource ============ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/csv.md) Use the `csv` Chef InSpec audit resource to test configuration data in a CSV file. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `csv` resource block declares the configuration data to be tested: ``` describe csv('file', true) do its('name') { should cmp 'foo' } end ``` Test `csv` file without headers ``` describe csv('file', false).params do its([0]) { should cmp 'name' } end ``` where * `'file'` is the path to a CSV file * `true` or `false` tests a CSV file with or without headers. Default value: `true`. * `name` is a configuration setting in a CSV file * `should eq 'foo'` tests a value of `name` as read from a CSV file versus the value declared in the test * `params` is the method for fetching data from a CSV file without headers. * `[0]` is the array element position. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test a CSV file without headers ``` describe csv('some_file.csv', false).params do its([0]) { should eq ["name"] } end ``` ### Test a CSV file ``` describe csv('some_file.csv') do its('setting') { should eq 1 } end ``` Property Examples ----------------- ### name The `name` property tests the value of `name` as read from a CSV file compared to the value declared in the test. ``` its('name') { should cmp 'foo' } ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/csv/directory resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/directory.md) Use the `directory` Chef InSpec audit resource to test if the file type is a directory. This is equivalent to using the [`file` resource](../file/index) and the `be_directory` matcher, but provides a simpler and more direct way to test directories. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `directory` resource block declares the location of the directory to be tested, and then one (or more) matchers. ``` describe directory('path') do its('property') { should cmp 'value' } end ``` Properties ---------- All of the properties available to [`file`](../file/index) may be used with `directory`. Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/directory/docker resource =============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/docker.md) Use the `docker` Chef InSpec audit resource to test configuration data for the Docker daemon. It is a very comprehensive resource. See also: [docker_container](../docker_container/index) and [docker_image](../docker_image/index), too. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.21.0 of InSpec. Syntax ------ A `docker` resource block declares allows you to write test for many containers: ``` describe docker.containers do its('images') { should_not include 'u12:latest' } end ``` or: ``` describe docker.containers.where { names == 'flamboyant_colden' } do it { should be_running } end ``` where * `.where()` may specify a specific item and value, to which the resource parameters are compared * `commands`, `ids`, `images`, `labels`, `local_volumes`, `mounts`, `names`, `networks`, `ports`, `sizes` and `status` are valid parameters for `containers` The `docker` resource block also declares allows you to write test for many images: ``` describe docker.images do its('repositories') { should_not include 'inssecure_image' } end ``` or if you want to query specific images: ``` describe docker.images.where { repository == 'ubuntu' && tag == '12.04' } do it { should_not exist } end ``` where * `.where()` may specify a specific filter and expected value, against which parameters are compared Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Return all running containers ``` docker.containers.running?.ids.each do |id| describe docker.object(id) do its('State.Health.Status') { should eq 'healthy' } end end ``` ### Verify a Docker Server and Client version ``` describe docker.version do its('Server.Version') { should cmp >= '1.12'} its('Client.Version') { should cmp >= '1.12'} end ``` ### Iterate over all containers to verify host configuration ``` docker.containers.ids.each do |id| # call Docker inspect for a specific container id describe docker.object(id) do its(%w(HostConfig Privileged)) { should cmp false } its(%w(HostConfig Privileged)) { should_not cmp true } end end ``` ### Iterate over all images to verify the container was built without ADD instruction ``` docker.images.ids.each do |id| describe command("docker history #{id}| grep 'ADD'") do its('stdout') { should eq '' } end end ``` ### Verify that health-checks are enabled for a container ``` describe docker.object('71b5df59442b') do its(%w(Config Healthcheck)) { should_not eq nil } end ``` How to run the DevSec Docker baseline profile --------------------------------------------- There are two ways to run the `docker-baseline` profile to test Docker via the `docker` resource. Clone the profile: ``` git clone https://github.com/dev-sec/cis-docker-benchmark.git ``` and then run: ``` inspec exec cis-docker-benchmark ``` Or execute the profile directly via URL: ``` inspec exec https://github.com/dev-sec/cis-docker-benchmark ``` Resource Parameters ------------------- * `commands`, `ids`, `images`, `labels`, `local_volumes`, `mounts`, `names`, `networks`, `ports`, `sizes` and `status` are valid parameters for `containers` Resource Parameter Examples --------------------------- ### containers `containers` returns information about containers as returned by [docker ps -a](https://docs.docker.com/engine/reference/commandline/ps/). ``` describe docker.containers do its('ids') { should include 'sha:71b5df59...442b' } its('commands') { should_not include '/bin/sh' } its('images') { should_not include 'u12:latest' } its('ports') { should include '0.0.0.0:1234->1234/tcp' } its('labels') { should include 'License=GPLv2' } end ``` ### object(‘id’) `object` returns low-level information about Docker objects. It is calling [docker inspect](https://docs.docker.com/engine/reference/commandline/info/) under the hood. ``` describe docker.object(id) do its('Configuration.Path') { should eq 'value' } end ``` ### images `images` returns information about a Docker image as returned by [docker images](https://docs.docker.com/engine/reference/commandline/images/). ``` describe docker.images do its('ids') { should include 'sha:12b5df59...442b' } its('repositories') { should_not include 'my_image' } its('tags') { should_not include 'unwanted_tag' } its('sizes') { should_not include '1.41 GB' } end ``` ### plugins `plugins` returns information about Docker plugins as returned by [docker plugin ls](https://docs.docker.com/engine/reference/commandline/plugin/). ``` describe docker.plugins do its('names') { should include ['store/weaveworks/net-plugin', 'docker4x/cloudstor'] } its('ids') { should cmp ['6ea8176de74b', '771d3ee7c7ea'] } its('versions') { should cmp ['2.3.0', '18.03.1-ce-aws1'] } its('enabled') { should cmp [true, false] } end ``` ### info `info` returns the parsed result of [docker info](https://docs.docker.com/engine/reference/commandline/info/) ``` describe docker.info do its('Configuration.Path') { should eq 'value' } end ``` ### version `info` returns the parsed result of [docker version](https://docs.docker.com/engine/reference/commandline/version/) ``` describe docker.version do its('Server.Version') { should cmp >= '1.12'} its('Client.Version') { should cmp >= '1.12'} end ``` Properties ---------- * `id` * `image` * `repo` * `tag` * `ports` * `command` Property Examples ----------------- ### id ``` describe docker_container(name: 'an-echo-server') do its('id') { should_not eq '' } end ``` ### image ``` describe docker_container(name: 'an-echo-server') do its('image') { should eq 'busybox:latest' } end ``` ### repo ``` describe docker_container(name: 'an-echo-server') do its('repo') { should eq 'busybox' } end ``` ### tag ``` describe docker_container(name: 'an-echo-server') do its('tag') { should eq 'latest' } end ``` ### ports ``` describe docker_container(name: 'an-echo-server') do its('ports') { should eq '0.0.0.0:1234->1234/tcp' } end ``` ### command ``` describe docker_container(name: 'an-echo-server') do its('command') { should eq 'nc -ll -p 1234 -e /bin/cat' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/docker/docker_plugin resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/docker_plugin.md) Use the `docker_plugin` Chef InSpec audit resource to verify a Docker plugin. Syntax ------ A `docker_plugin` resource block declares the plugin: ``` describe docker_plugin('rexray/ebs') do it { should exist } its('id') { should_not eq '0ac30b93ad40' } its('version') { should eq '0.11.1' } it { should be_enabled } end ``` Resource Parameter Examples --------------------------- The resource allows you to pass in an plugin id: ``` describe docker_plugin(id: plugin_id) do it { should be_enabled } end ``` Properties ---------- ### id The `id` property returns the full plugin id: ``` its('id') { should eq '0ac30b93ad40' } ``` ### version The `version` property tests the value of plugin version: ``` its('version') { should eq '0.11.0' } ``` Examples -------- ### Test a Docker plugin ``` describe docker_plugin('rexray/ebs') do it { should exist } its('id') { should_not eq '0ac30b93ad40' } its('version') { should eq '0.11.1' } it { should be_enabled } end ``` Matchers -------- For a full list of available matchers, please visit our [Universal Matchers](../../matchers/index). ### exist The `exist` matcher tests if the plugin is available on the node: ``` describe docker_plugin('rexray/ebs') do it { should exist } end ``` ### enabled The `be_enabled` matches tests if the plugin is enabled © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/docker_plugin/dh_params resource =================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/dh_params.md) Use the `dh_params` Chef InSpec audit resource to test Diffie-Hellman (DH) parameters. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.19.0 of InSpec. Syntax ------ A `dh_params` resource block declares a parameter file to be tested. ``` describe dh_params('/path/to/file.dh_pem') do it { should be_dh_params } it { should be_valid } its('generator') { should eq 2 } its('modulus') { should eq '00:91:a0:15:89:e5:bc:38:93:12:02:fc:...' } its('prime_length') { should eq 2048 } its('pem') { should eq '-----BEGIN DH PARAMETERS...' } its('text') { should eq 'PKCS#3 DH Parameters: (2048 bit)...' } end ``` Properties ---------- ### generator (Integer) The `generator` property returns generator used for the Diffie-Hellman operation. ``` its('generator') { should eq 2 } ``` ### modulus (String) The `modulus` property returns the prime modulus used for the Diffie-Hellman operation. ``` its('modulus') { should eq '00:91:a0:15:89:e5:bc:38:93:12:02:fc:...' } ``` ### prime_length (Integer) The `prime_length` property returns the length of prime modulus used for the Diffie-Hellman operation. ``` its('prime_length') { should eq 2048 } ``` ### pem (String) The `pem` property returns the pem formatted value of DH parameters. ``` its('pem') { should eq '-----BEGIN DH PARAMETERS...' } ``` ### text (String) The `text` property returns the value of DH parameters in text format. ``` its('text') { should eq 'PKCS#3 DH Parameters: (2048 bit)...' } ``` Examples -------- ### Test generator used for the Diffie-Hellman operation: ``` describe dh_params('/path/to/file.dh_pem') do its('generator') { should eq 2 } end ``` ### Test prime modulus used for the Diffie-Hellman operation: ``` describe dh_params('/path/to/file.dh_pem') do its('modulus') { should eq '00:91:a0:15:89:e5:bc:38:93:12:02:fc:...' } end ``` ### Test example using multi-line string: ``` describe dh_params('/path/to/file.dh_pem') do its('modulus') do # regex removes all whitespace should eq <<-EOF.gsub(/[[:space:]]+/, '') 00:91:a0:15:89:e5:bc:38:93:12:02:fc:91:a2:85: f7:f7:29:63:2e:d3:4e:7a:86:f7:ee:84:fe:42:d0: 48:bc:9c:91:d5:54:f8:78:1d:c0:41:78:a2:c4:ac: 1a:24:8b:9d:88:55:98:0b:ac:a7:23:eb:c2:aa:2b: 2e:a9:f9:af:d4:8e:4e:11:bc:7f:35:a2:ac:da:3a: ef:f0:25:6c:9a:a4:fd:00:28:76:86:2c:57:87:67: 30:5d:b1:d6:5b:22:8f:72:a1:ea:de:8b:ef:9e:33: 1a:40:92:68:85:02:54:02:09:fa:c0:60:c1:3c:4e: 28:26:db:ed:25:8e:38:21:56:40:dc:c0:c0:66:1f: 2b:32:c3:b4:78:a9:26:94:ea:f7:41:28:b2:f5:5b: 01:38:0c:46:09:85:26:4d:69:12:8d:95:0f:35:e2: e6:4e:47:3a:86:dd:8a:b2:fe:45:15:27:d8:59:c2: 3c:f4:62:ff:5f:74:e9:77:92:50:47:36:2b:05:57: 60:ee:7b:a1:60:cc:1c:7a:2b:77:18:8a:37:f7:c7: 31:3e:15:cb:15:7f:7b:66:96:fb:c6:be:7d:d6:03: 5e:0d:60:75:2b:5b:62:2a:a3:37:b6:34:f9:fe:96: 4c:f6:c5:e3:a1:52:af:01:c1:4f:c7:42:a0:be:ed: cd:13 EOF end end ``` ### Test length of prime modulus used for the Diffie-Hellman operation: ``` describe dh_params('/path/to/file.dh_pem') do its('prime_length') { should eq 2048 } end ``` ### Test `pem` output of DH parameters: ``` describe dh_params('/path/to/file.dh_pem') do its('pem') { should eq '-----BEGIN DH PARAMETERS...' } end ``` ### Test example using multi-line string: ``` describe dh_params('/path/to/file.dh_pem') do its('pem') do # regex removes all leading spaces should eq <<-EOF.gsub(/^[[:blank:]]+/, '') -----BEGIN DH PARAMETERS----- MIIBCAKCAQEAkaAVieW8OJMSAvyRooX39yljLtNOeob37oT+QtBIvJyR1VT4eB3A QXiixKwaJIudiFWYC6ynI+vCqisuqfmv1I5OEbx/NaKs2jrv8CVsmqT9ACh2hixX h2cwXbHWWyKPcqHq3ovvnjMaQJJohQJUAgn6wGDBPE4oJtvtJY44IVZA3MDAZh8r MsO0eKkmlOr3QSiy9VsBOAxGCYUmTWkSjZUPNeLmTkc6ht2Ksv5FFSfYWcI89GL/ X3Tpd5JQRzYrBVdg7nuhYMwceit3GIo398cxPhXLFX97Zpb7xr591gNeDWB1K1ti KqM3tjT5/pZM9sXjoVKvAcFPx0Kgvu3NEwIBAg== -----END DH PARAMETERS----- EOF end end ``` ### Test via `openssl dhparam` command: ``` $ openssl dhparam -in /path/to/file.dh_pem -----BEGIN DH PARAMETERS----- MIIBCAKCAQEAkaAVieW8OJMSAvyRooX39yljLtNOeob37oT+QtBIvJyR1VT4eB3A QXiixKwaJIudiFWYC6ynI+vCqisuqfmv1I5OEbx/NaKs2jrv8CVsmqT9ACh2hixX h2cwXbHWWyKPcqHq3ovvnjMaQJJohQJUAgn6wGDBPE4oJtvtJY44IVZA3MDAZh8r MsO0eKkmlOr3QSiy<KEY>TWkS<KEY>GL/ X3Tpd5JQRzYrBVdg7nuhYMwceit3GIo398cxPhXLFX97Zpb7xr591gNeDWB1K1ti KqM3tjT5/pZM9sXjoVKvAcFPx0Kgvu3NEwIBAg== -----END DH PARAMETERS----- ``` ### Test human-readable text output of DH parameters: ``` describe dh_params('/path/to/file.dh_pem') do its('text') { should eq 'PKCS#3 DH Parameters: (2048 bit)...' } end ``` ### Test example using multi-line string: ``` describe dh_params('/path/to/file.dh_pem') do its('text') do # regex removes 2 leading spaces should eq <<-EOF.gsub(/^[[:blank:]]{2}/, '') PKCS#3 DH Parameters: (2048 bit) prime: 00:91:a0:15:89:e5:bc:38:93:12:02:fc:91:a2:85: f7:f7:29:63:2e:d3:4e:7a:86:f7:ee:84:fe:42:d0: 48:bc:9c:91:d5:54:f8:78:1d:c0:41:78:a2:c4:ac: 1a:24:8b:9d:88:55:98:0b:ac:a7:23:eb:c2:aa:2b: 2e:a9:f9:af:d4:8e:4e:11:bc:7f:35:a2:ac:da:3a: ef:f0:25:6c:9a:a4:fd:00:28:76:86:2c:57:87:67: 30:5d:b1:d6:5b:22:8f:72:a1:ea:de:8b:ef:9e:33: 1a:40:92:68:85:02:54:02:09:fa:c0:60:c1:3c:4e: 28:26:db:ed:25:8e:38:21:56:40:dc:c0:c0:66:1f: 2b:32:c3:b4:78:a9:26:94:ea:f7:41:28:b2:f5:5b: 01:38:0c:46:09:85:26:4d:69:12:8d:95:0f:35:e2: e6:4e:47:3a:86:dd:8a:b2:fe:45:15:27:d8:59:c2: 3c:f4:62:ff:5f:74:e9:77:92:50:47:36:2b:05:57: 60:ee:7b:a1:60:cc:1c:7a:2b:77:18:8a:37:f7:c7: 31:3e:15:cb:15:7f:7b:66:96:fb:c6:be:7d:d6:03: 5e:0d:60:75:2b:5b:62:2a:a3:37:b6:34:f9:fe:96: 4c:f6:c5:e3:a1:52:af:01:c1:4f:c7:42:a0:be:ed: cd:13 generator: 2 (0x2) EOF end end ``` ### Test via `openssl dhparam` command: ``` $ openssl dhparam -in /path/to/file.dh_pem -noout -text PKCS#3 DH Parameters: (2048 bit) prime: 00:91:a0:15:89:e5:bc:38:93:12:02:fc:91:a2:85: f7:f7:29:63:2e:d3:4e:7a:86:f7:ee:84:fe:42:d0: 48:bc:9c:91:d5:54:f8:78:1d:c0:41:78:a2:c4:ac: 1a:24:8b:9d:88:55:98:0b:ac:a7:23:eb:c2:aa:2b: 2e:a9:f9:af:d4:8e:4e:11:bc:7f:35:a2:ac:da:3a: ef:f0:25:6c:9a:a4:fd:00:28:76:86:2c:57:87:67: 30:5d:b1:d6:5b:22:8f:72:a1:ea:de:8b:ef:9e:33: 1a:40:92:68:85:02:54:02:09:fa:c0:60:c1:3c:4e: 28:26:db:ed:25:8e:38:21:56:40:dc:c0:c0:66:1f: 2b:32:c3:b4:78:a9:26:94:ea:f7:41:28:b2:f5:5b: 01:38:0c:46:09:85:26:4d:69:12:8d:95:0f:35:e2: e6:4e:47:3a:86:dd:8a:b2:fe:45:15:27:d8:59:c2: 3c:f4:62:ff:5f:74:e9:77:92:50:47:36:2b:05:57: 60:ee:7b:a1:60:cc:1c:7a:2b:77:18:8a:37:f7:c7: 31:3e:15:cb:15:7f:7b:66:96:fb:c6:be:7d:d6:03: 5e:0d:60:75:2b:5b:62:2a:a3:37:b6:34:f9:fe:96: 4c:f6:c5:e3:a1:52:af:01:c1:4f:c7:42:a0:be:ed: cd:13 generator: 2 (0x2) ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_valid Verify whether DH parameters are valid: ``` describe dh_params('/path/to/file.dh_pem') do it { should be_valid } end ``` ### be_dh_params ``` describe dh_params('/path/to/file.dh_pem') do it { should be_dh_params} end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/dh_params/docker_image resource ====================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/docker_image.md) Use the `docker_image` Chef InSpec audit resource to verify a Docker image. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.21.0 of InSpec. Syntax ------ A `docker_image` resource block declares the image: ``` describe docker_image('alpine:latest') do it { should exist } its('id') { should eq 'sha256:4a415e...a526' } its('repo') { should eq 'alpine' } its('tag') { should eq 'latest' } end ``` Resource Parameter Examples --------------------------- The resource allows you to pass in an image id: ``` describe docker_image(id: alpine_id) do ... end ``` If the tag is missing for an image, `latest` is assumed as default: ``` describe docker_image('alpine') do ... end ``` You can also pass in repository and tag as separate values ``` describe docker_image(repo: 'alpine', tag: 'latest') do ... end ``` Property Examples ----------------- ### id The `id` property returns the full image id: ``` its('id') { should eq 'sha256:4a415e3663882fbc554ee830889c68a33b3585503892cc718a4698e91ef2a526' } ``` ### image The `image` property tests the value of the image. It is a combination of `repository/tag`: ``` its('image') { should eq 'alpine:latest' } ``` ### repo The `repo` property tests the value of the repository name: ``` its('repo') { should eq 'alpine' } ``` ### tag The `tag` property tests the value of image tag: ``` its('tag') { should eq 'latest' } ``` ### Test a Docker Image ``` describe docker_image('alpine:latest') do it { should exist } its('id') { should eq 'sha256:4a415e...a526' } its('image') { should eq 'alpine:latest' } its('repo') { should eq 'alpine' } its('tag') { should eq 'latest' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `exist` matcher tests if the image is available on the node: ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/docker_image/docker_container resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/docker_container.md) Use the `docker_container` Chef InSpec audit resource to test a Docker container. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.21.0 of InSpec. Syntax ------ A `docker_container` resource block declares the configuration data to be tested: ``` describe docker_container('container') do it { should exist } it { should be_running } its('id') { should_not eq '' } its('image') { should eq 'busybox:latest' } its('repo') { should eq 'busybox' } its('tag') { should eq 'latest' } its('ports') { should eq [] } its('command') { should eq 'nc -ll -p 1234 -e /bin/cat' } end ``` Resource Parameter Examples --------------------------- ### name The container name can also be passed with the `name` resource parameter: ``` describe docker_container(name: 'an-echo-server') do it { should exist } it { should be_running } end ``` ### id Alternatively, you can pass in the container id: ``` describe docker_container(id: '71b5df59442b') do it { should exist } it { should be_running } end ``` Property Examples ----------------- The following examples show how to use this Chef InSpec resource. ### id The `id` property tests the container id: ``` its('id') { should eq 'sha:71b5df59...442b' } ``` ### repo The `repo` property tests the value of the image repository: ``` its('repo') { should eq 'busybox' } ``` ### tag The `tag` property tests the value of the image tag: ``` its('tag') { should eq 'latest' } ``` ### ports The `ports` property tests the value the Docker ports: ``` its('ports') { should eq '0.0.0.0:1234->1234/tcp' } ``` ### command The `command` property tests the value of the container run command: ``` its('command') { should eq 'nc -ll -p 1234 -e /bin/cat' } ``` ### Verify a running container: ``` describe docker_container('an-echo-server') do it { should exist } it { should be_running } its('id') { should_not eq '' } its('image') { should eq 'busybox:latest' } its('repo') { should eq 'busybox' } its('tag') { should eq 'latest' } its('ports') { should eq [] } its('command') { should eq 'nc -ll -p 1234 -e /bin/cat' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/docker_container/docker_service resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/docker_service.md) Use the `docker_service` Chef InSpec audit resource to verify a docker swarm service. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.51.0 of InSpec. Syntax ------ A `docker_service` resource block declares the service by name: ``` describe docker_service('foo') do it { should exist } its('id') { should eq '2ghswegspre1' } its('repo') { should eq 'alpine' } its('tag') { should eq 'latest' } end ``` Resource Parameter Examples --------------------------- The resource allows you to pass in a service id: ``` describe docker_service(id: '2ghswegspre1') do ... end ``` You can also pass in the fully-qualified image: ``` describe docker_service(image: 'localhost:5000/alpine:latest') do ... end ``` Property Examples ----------------- The following examples show how to use Chef InSpec `docker_service` resource. ### id The `id` property returns the service id: ``` its('id') { should eq '2ghswegspre1' } ``` ### image The `image` property is a combination of `repository:tag` it tests the value of the image: ``` its('image') { should eq 'alpine:latest' } ``` ### mode The `mode` property tests the value of the service mode: ``` its('mode') { should eq 'replicated' } ``` ### name The `name` property tests the value of the service name: ``` its('name') { should eq 'foo' } ``` ### ports The `ports` property tests the value of the service’s published ports: ``` its('ports') { should include '*:8000->8000/tcp' } ``` ### repo The `repo` property tests the value of the repository name: ``` its('repo') { should eq 'alpine' } ``` ### replicas The `replicas` property tests the value of the service’s replica count: ``` its('replicas') { should eq '3/3' } ``` ### tag The `tag` property tests the value of image tag: ``` its('tag') { should eq 'latest' } ``` ### Test a docker service ``` describe docker_service('foo') do it { should exist } its('id') { should eq '2ghswegspre1' } its('repo') { should eq 'alpine' } its('tag') { should eq 'latest' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `exist` matcher tests if the image is available on the node: ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/docker_service/elasticsearch resource ====================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/elasticsearch.md) Use the `elasticsearch` resource to test the status of a node against a running Elasticsearch cluster. Chef InSpec retrieves the node list from the cluster node URL provided (defaults to `http://localhost:9200`) and provides the ability to query a variety of settings and statuses. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.43.5 of InSpec. Syntax ------ ``` describe elasticsearch do its('property') { should cmp 'value' } end ``` Supported Resource Parameters ----------------------------- The `elasticsearch` resource accepts several optional resource parameters: `url` the top-level URL of an Elasticsearch node in the cluster. If your Elasticsearch installation is not served out of the top-level directory at the host, be sure to specify the full URL; for example: `http://my-load-balancer/elasticsearch`. Default: `http://localhost:9200` `username` a username to use to log in with HTTP-Basic authentication. If `username` is provided, a `password` must also be provided. `password` a password to use to log in with HTTP-Basic authentication. If `password` is provided, a `username` must also be provided. `ssl_verify` if `false`, SSL certificate validation will be disabled. Default: `true` In addition, the `elasticsearch` resource allows for filtering the nodes returned by property before executing the tests: ``` describe elasticsearch.where { node_name == 'one-off-node' } do its('version') { should eq '1.2.3' } end describe elasticsearch.where { process.mlockall == false } do its('count') { should cmp 0 } end ``` To simply check if nodes exist that match the criteria, use the `exist` matcher: ``` describe elasticsearch.where { cluster_name == 'my_cluster' } do it { should exist } end ``` Properties ---------- The following are the different properties of the resource: Since the `elasticsearch` resource is meant for use on a cluster, each property will return an array of the values for each node that matches any provided search criteria. Using InSpec’s `cmp` matcher helps avoid issues when comparing values when there is only a single match (i.e. when the cluster only contains a single node or the `where` filter criteria provided only returns a single node). ### build_hash The `build hash` property returns the build hash for each of the nodes. ``` its('build_hash') { should cmp 'b2f0c09' } ``` ### cluster_name The `cluster_name` property returns the cluster names of each of the nodes. ``` its('cluster_name') { should cmp 'my_cluster' } ``` ### host The `host` property returns the hostname of each of the nodes. This may return an IP address if the node is improperly performing DNS resolution or has no hostname set. ``` its('host') { should cmp 'my.hostname.mycompany.biz' } ``` ### http The `http` property returns a hash of HTTP-related settings for each of the nodes. In this example, the `first` method is used to grab only the first node’s HTTP-related info and is a way of removing the item from the Array if only one node is being queried. ``` its('http.first.max_content_length_in_bytes') { should cmp 123456 } ``` ### ingest The `ingest` property returns ingest-related settings and capabilities, such as available processors. ``` its('ingest.first.processors.count') { should be >= 1 } ``` ### ip The `ip` property returns the IP address of each of the nodes. ``` its('ip') { should cmp '192.168.1.100' } ``` ### jvm The `jvm` property returns Java Virtual Machine related parameters for each of the nodes. ``` its('jvm.first.version') { should cmp '1.8.0_141' } ``` ### module_list The `module_list` property returns a list of enabled modules for each node in the cluster. ``` its('module_list.first') { should include 'my_module' } ``` ### modules The `modules` property returns detailed information about each enabled module for each node in the cluster. ``` its('modules.first') { should include 'lang-groovy' } ``` ### node_name The `node_name` property returns the node name for each node in the cluster. ``` its('node_name') { should cmp 'node1' } ``` ### node_id The `node_id` property returns the node IDs of each of the nodes in the cluster. ``` its('node_id') { should include 'my_node_id' } ``` ### os The `os` property returns OS-related information about each node in the cluster. ``` its('os.first.arch') { should cmp 'amd64' } ``` ### plugin_list The `plugin_list` property returns a list of enabled plugins for each node in the cluster. For more additional information about each plugin, use the `plugins` property. ``` its('plugin_list.first') { should include 'my_plugin' } ``` ### plugins The `plugins` property returns detailed information about each enabled plugin for each node in the cluster. ``` its('plugins.first') { should include 'my_plugin' } ``` ### process The `process` property returns process information for each node in the cluster, such as the process ID. ``` its('process.first.mlockall') { should cmp true } ``` ### roles The `roles` property returns the role for each of the nodes in the cluster. ``` its('roles') { should include 'master' } ``` ### settings The `settings` property returns all the configuration settings for each node in the cluster. These settings usually include those set in the elasticsearch.yml as well as those set via `-Des.` or `-E` flags at startup. Use the `inspec shell` to explore the various setting keys that are available. ``` its('settings.first.path.home') { should cmp '/usr/share/elasticsearch' } ``` ### total_indexing_buffer The `total_indexing_buffer` property returns the total indexing buffer for each node in the cluster. ``` its('total_indexing_buffer') { should cmp 123456 } ``` ### transport The `transport` property returns transport-related settings for each node in the cluster, such as the bound and published addresses. ``` its('transport.first.bound_address') { should cmp '1.2.3.4:9200' } ``` ### transport_address The `transport_address` property returns the bound transport address for each node in the cluster. ``` its('transport_address') { should cmp '1.2.3.4:9200' } ``` ### version The `version` property returns the version of Elasticsearch running on each node of the cluster. ``` its('version') { should cmp '5.5.2' } ``` Examples -------- ### Test to verify the specific module. Uses additional Ruby to find a specific module and assert a value. For a succinct list of the names of each of the modules enabled, use the `module_list` property. ``` modules = elasticsearch.modules.first lang_groovy_module = modules.find { |mod| mod.name == 'lang-groovy' } describe 'lang-groovy module version' do subject { lang_groovy_module } its('version') { should cmp '5.5.2' } end ``` ### Tests to verify the specific plugin. Uses additional Ruby to find a specific plugin and assert a value. For a succinct list of the names of each of the plugins enabled, use the `plugin_list` property. ``` plugins = elasticsearch.plugins.first my_plugin = plugins.find { |plugin| plugin.name == 'my_plugin' } describe 'my_plugin plugin version' do subject { my_plugin } its('version') { should cmp '1.2.3' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/elasticsearch/etc_group resource =================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/etc_group.md) Use the `etc_group` Chef InSpec audit resource to test groups that are defined on Linux and Unix platforms. The `/etc/group` file stores details about each group: group name, password, group identifier, along with a comma-separated list of users that belong to the group. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `etc_group` resource block declares a collection of properties to be tested: ``` describe etc_group('path') do its('property') { should eq 'some_value' } end ``` or: ``` describe etc_group.where(item: 'value', item: 'value') do its('gids') { should_not contain_duplicates } its('groups') { should include 'user_name' } its('users') { should include 'user_name' } end ``` where * `('path')` is the non-default path to the `\etc\group` file * `.where()` filters for a specific item and value, to which the parameter are compared * `.where` filter may be one or more of: + `name: 'name'`, `group_name: 'group_name'`, `password: 'password'`, `gid: 'gid'`, `group_id: 'gid'`, `users: 'user_name'`, `members: 'member_name'` Properties ---------- ### gids The `gids` property returns the list of gids from `/etc/group` file. ``` its('gids') { should include 'gid' } ``` ### groups The `groups` property returns the list of groups from `/etc/group` file. ``` its('groups') { should include 'my_group' } ``` ### users The `users` property returns the list of users from `/etc/group` file. ``` its('users') { should include 'my_user' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test group identifiers (GIDs) for duplicates ``` describe etc_group do its('gids') { should_not contain_duplicates } end ``` ### Test all groups to see if a specific user belongs to one (or more) groups ``` describe etc_group do its('groups') { should include 'my_group' } end ``` ### Test all groups for a specific user name ``` describe etc_group do its('users') { should include 'my_user' } end ``` ### Filter a list of groups for a specific user ``` describe etc_group.where(name: 'my_group') do its('users') { should include 'my_user' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/etc_group/etc_hosts_allow resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/etc_hosts_allow.md) Use the `etc_hosts_allow` Chef InSpec audit resource to test rules defined for accepting daemon and client traffic in the `'/etc/hosts.allow'` file. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.39.1 of InSpec. Syntax ------ An etc/hosts.allow rule specifies one or more daemons mapped to one or more clients, with zero or more options for accepting traffic when found. Use the where clause to match a property to one or more rules in the `hosts.allow` file. ``` describe etc_hosts_allow.where { daemon == 'value' } do its ('client_list') { should include ['values'] } its ('options') { should include ['values'] }p end ``` Use the optional constructor parameter to give an alternative path to `hosts.allow` file. ``` describe etc_hosts_allow(hosts_path).where { daemon == 'value' } do its ('client_list') { should include ['values'] } its ('options') { should include ['values'] } end ``` where * `daemon` is a filter that will be allowed to pass traffic in. * `client_list`, `options` are the valid resource properties that test the list of clients who will be allowed to pass traffic in, and a list of tasks that are to be done with the rule when traffic is found respectively. Properties ---------- ### daemon The `daemon` property returns a string containing the daemon that is allowed in the rule. ``` describe etc_hosts_allow.where { client_list == ['127.0.1.154', '[:fff:fAb0::]'] } do its('daemon') { should eq ['vsftpd', 'sshd'] } end ``` ### client_list The `client_list` property returns a 2d string array where each entry contains the clients specified for the rule. ``` describe etc_hosts_allow.where { daemon == 'sshd' } do its('client_list') { should include ['192.168.0.0/16', '[abcd::0000:1234]'] } end ``` ### options The `options` property returns a 2d string array where each entry contains any options specified for the rule. ``` describe etc_hosts_allow.where { daemon == 'sshd' } do its('options') { should include ['deny', 'echo "REJECTED"'] } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/etc_hosts_allow/etc_hosts_deny resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/etc_hosts_deny.md) Use the `etc_hosts_deny` Chef InSpec audit resource to test rules for rejecting daemon and client traffic defined in /etc/hosts.deny. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.39.1 of InSpec. Syntax ------ An `etc_hosts_deny` rule specifies one or more daemons mapped to one or more clients, with zero or more options for rejecting traffic when found. Use the where clause to match a property to one or more rules in the hosts.deny file: ``` describe etc_hosts_deny.where { daemon == 'value' } do its ('client_list') { should include ['values'] } its ('options') { should include ['values'] } end ``` Use the optional constructor parameter to give an alternative path to hosts.deny: ``` describe etc_hosts_deny(hosts_path).where { daemon == 'value' } do its ('client_list') { should include ['values'] } its ('options') { should include ['values'] } end ``` where * `daemon` is a daemon that will be rejected to pass traffic in. * `client_list` is a list of clients that will be rejected to pass traffic in. * `options` is a list of tasks that are to be done with the rule when traffic is found. Properties ---------- ### daemon The `daemon` property returns a string containing the daemon that is allowed in the rule. ``` describe etc_hosts_deny.where { client_list == ['127.0.1.154', '[:fff:fAb0::]'] } do its('daemon') { should eq ['vsftpd', 'sshd'] } end ``` ### client_list The `client_list` property returns a 2d string array where each entry contains the clients specified for the rule. ``` describe etc_hosts_deny.where { daemon == 'sshd' } do its('client_list') { should include ['192.168.0.0/16', '[abcd::0000:1234]'] } end ``` ### options The `options` property returns a 2d string array where each entry contains any options specified for the rule. ``` describe etc_hosts_deny.where { daemon == 'sshd' } do its('options') { should include ['deny', 'echo "REJECTED"'] } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/etc_hosts_deny/etc_hosts resource =================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/etc_hosts.md) Use the `etc_hosts` Chef InSpec audit resource to test rules set to match IP addresses with hostnames. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.37.6 of InSpec. Syntax ------ An etc/hosts rule specifies an IP address and what its hostname is along with optional aliases it can have. Syntax ------ Use the `.where` clause to match a property to one or more rules in the hosts file: ``` describe etc_hosts.where { ip_address == 'value' } do its('primary_name') { should cmp 'hostname' } its('all_host_names') { should cmp 'list' } end ``` Use the optional resource parameter to give an alternative path to the hosts file: ``` describe etc_hosts('path/to/hosts').where { ip_address == 'value' } do its('primary_name') { should cmp 'hostname' } its('all_host_names') { should cmp 'list' } end ``` where * `ip_address` is the IP address of the hostname in either ipv4 or ipv6 format. * `primary_name` is the name associated with the IP address. * `all_host_names` is a list including the primary_name as the first entry followed by any alias names the host has. Properties ---------- ### ip_address The `ip_address` property returns a string array of ip addresses specified in the etc/hosts file. ``` its('ip_address') { should cmp '127.0.1.154' } ``` ### primary_name The `primary_name` property returns a string array of primary_names specified in the etc/hosts file. ``` its('primary_name') { should cmp 'localhost' } ``` ### all_host_names The `all_host_names` property returns a two-dimensional string array where each entry has the primary_name first followed by any aliases. ``` its('all_host_names') { should cmp 'list' } ``` Examples -------- ### Test the IP address of the given primary name ‘localhost’. ``` describe etc_hosts.where { primary_name == 'localhost' } do its('ip_address') { should cmp '127.0.1.154' } end ``` ### Test the primay name for where ip address is ‘::1’ ``` describe etc_hosts.where { ip_address == '::1' } do its('primary_name') { should cmp 'localhost' } end ``` ### Test the list of primary names and their aliases for the given IP address. ``` describe etc_hosts.where { ip_address == '127.0.1.154' } do its('all_host_names') { should eq [['localhost', 'localhost.localdomain', 'localhost4', 'localhost4.localdomain4'], ['localhost', 'localhost.localdomain', 'localhost6', 'localhost6.localdomain6']] } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/etc_hosts/etc_fstab resource =================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/etc_fstab.md) Use the `etc_fstab` Chef InSpec audit resource to test information about all partitions and storage devices on a Linux system. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.37.6 of InSpec. Syntax ------ An etc_fstab rule specifies a device name, its mount point, its mount type, the options it mounted with, its dump options and the files system options should be checked. Use the where clause to match a property to one or more rules in the fstab file: ``` describe etc_fstab.where { device_name == 'value' } do its('mount_point') { should cmp 'hostname' } its('file_system_type') { should cmp 'list' } its('mount_options') { should cmp 'list' } its('dump_options') { should cmp 'list' } its('file_system_options') { should cmp 'list' } end ``` Use the optional constructor parameter to give an alternative path to fstab file: ``` describe etc_fstab(hosts_path).where { device_name == 'value' } do its('mount_point') { should cmp 'hostname' } its('file_system_type') { should cmp 'list' } its('mount_options') { should cmp 'list' } its('dump_options') { should cmp 'list' } its('file_system_options') { should cmp 'list ' } end ``` Properties ---------- ### device_name The `device_name` property returns a string array including the device names mounted on the system. ``` describe etc_fstab.where { mount_point == '/mnt/sr0' } do its('device_name') { should cmp '/dev/sr0' } end ``` ### mount_point The `mount_point` property returns a string array including the path of directories at which filesystems are configured to be mounted. ``` describe etc_fstab.where { device_name == '/dev/sr0' } do its('mount_point') { should cmp '/mnt/sr0' } end ``` ### file_system_type The `file_system_type` property returns a string array including each device or partitions file system type. ``` describe etc_fstab.where { device_name == '/dev/sr0' } do its('file_system_type') { should cmp 'iso9660' } end ``` ### mount_options The `mount_options` property returns a two dimensional array of each partition’s mount options. ``` describe etc_fstab.where { mount_point == '/' } do its('mount_options') { should eq [['defaults', 'x-systemd.device-timeout=0']] } end ``` ### dump_options The `dump_options` property returns an integer array of each partitions dump option. This is a number used by dump to decide if a file system should be backed up. ``` describe etc_fstab.where { device_name == '/dev/sr0' } do its('dump_options') { should cmp 0 } end ``` ### file_system_options The `file_system_options` property returns an integer array of each partitions file system option. This is a number that specifies the order in which the file system should be checked. ``` describe etc_fstab.where { device_name == '/dev/sr0' } do its('file_system_options') { should cmp 0 } end ``` Examples -------- ### Check all partitions that have a type of ‘nfs’ ``` nfs_systems = etc_fstab.nfs_file_systems.entries nfs_systems.each do |partition| describe partition do its('mount_options') { should include 'nosuid' } end end ``` ### Check the partition mounted at /home contains ‘nosuid’ in its mount_options ``` describe etc_fstab do its('home_mount_options') { should include 'nosuid' } end ``` ### Check if a partition is mounted at a point ``` describe etc_fstab.where { mount_point == '/home' } do it { should be_configured } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/etc_fstab/firewalld resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/firewalld.md) Use the `firewalld` Chef InSpec audit resource to test that firewalld is configured to allow and deny access to specific hosts, services and ports on a system. A firewalld has a number of zones that can be configured to allow and deny access to specific hosts, services, and ports. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.40.0 of InSpec. Syntax ------ ``` describe firewalld do it { should be_running } its('default_zone') { should eq 'public' } it { should have_service_enabled_in_zone('ssh', 'public') } it { should have_rule_enabled('family=ipv4 source address=192.168.0.14 accept', 'public') } end ``` Use the where clause to test open interfaces, sources, and services that are in active zones. ``` describe firewalld.where { zone == 'public' } do its('interfaces') { should cmp ['enp0s3', 'eno2'] } its('sources') { should cmp ['192.168.1.0/24', '192.168.1.2'] } its('services') { should cmp ['ssh', 'icmp'] } end ``` Properties ---------- ### `interfaces` The `interfaces` property is used in conjunction with the where class to display open interfaces in an active zone. ``` describe firewalld.where { zone == 'public' } do its('interfaces') { should cmp ['enp0s3', 'eno2'] } end ``` ### `sources` The `sources` property is used in conjunction with the where class to display open sources in an active zone. ``` describe firewalld.where { zone == 'public' } do its('sources') { should cmp ['192.168.1.0/24', '192.168.1.2'] } end ``` ### `services` The `services` property is used in conjunction with the where class to display open services in an active zone. ``` describe firewalld.where { zone == 'public' } do its('services') { should cmp ['ssh', 'icmp'] } end ``` ### `default_zone` The `default_zone` property displays the default active zone to be used. ``` its('default_zone') { should eq 'public' } ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### `be_installed` The `be_installed` matcher tests if the firewalld service is installed: ``` it { should be_installed } ``` ### `be_running` The `be_running` matcher tests if the firewalld service is running: ``` it { should be_running } ``` ### `have_zone` `have_zone` returns true or false if the zone is set on firewalld. It does not mean the zone is active. ``` it { should have_zone('public') } ``` ### `have_service_enabled_in_zone` `have_service_enabled_in_zone` returns true or false if the service is allowed in the specified zone. ``` it { should have_service_enabled_in_zone('ssh', 'public') } ``` ### `have_port_enabled_in_zone` `have_port_enabled_in_zone` returns true or false if the port is allowed in the specified zone. ``` it { should have_port_enabled_in_zone('22/tcp', 'public') } ``` ### `have_rule_enabled` `have_rule_enabled` returns true or false if the rich-rule has been specified in the zone. ``` it { should have_rule_enabled('family=ipv4 source address=192.168.0.14 accept', 'public') } ``` It is not necessary to add the “rule” string, and you can start with the optional flags that are used in firewalld and end with the action © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/firewalld/gem resource ============ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/gem.md) Use the `gem` Chef InSpec audit resource to test if a global Gem package is installed. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `gem` resource block declares a package and (optionally) a package version: ``` describe gem('gem_package_name', 'gem_binary') do it { should be_installed } end ``` where * `('gem_package_name')` must specify a Gem package, such as `'rubocop'` * `('gem_binary')` can specify the path to a non-default gem binary, defaults to `'gem'` * `be_installed` is a valid matcher for this resource Properties ---------- ### `version (String)` The `version` property returns a string of the default version on the system: ``` its('version') { should eq '0.33.0' } ``` ### `versions` The `versions` property returns an array of strings of all the versions of the gem installed on the system: ``` its('versions') { should include /0.33/ } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Verify that a gem package is installed, with a specific version ``` describe gem('rubocop') do it { should be_installed } its('version') { should eq '1.22.0' } end ``` ### Verify that a particular version is installed when there are multiple versions installed ``` describe gem('rubocop') do it { should be_installed } its('versions') { should include /1.21.0/ } its('versions.count') { should_not be > 3 } end ``` ### Verify that a gem package is not installed ``` describe gem('rubocop') do it { should_not be_installed } end ``` ### Verify that a gem package is installed in an omnibus environment ``` describe gem('pry', '/opt/ruby-3.0.2/embedded/bin/gem') do it { should be_installed } end ``` ### Verify that a gem package is installed in a chef omnibus environment ``` describe gem('chef-sugar', :chef) do it { should be_installed } end ``` ### Verify that a gem package is installed in a chef-server omnibus environment ``` describe gem('knife-backup', :chef_server) do it { should be_installed } end ``` Properties ---------- ### version (String) The `version` property returns a string of the default version on the system: ``` its('version') { should eq '1.22.0' } ``` ### versions The `versions` property returns an array of strings of all the versions of the gem installed on the system: ``` its('versions') { should include /1.22/ } ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_installed The `be_installed` matcher tests if the named Gem package is installed: ``` it { should be_installed } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/gem/filesystem resource =================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/filesystem.md) Use the `filesystem` Chef InSpec resource to audit filesystem disk space usage. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.51.0 of InSpec. The `free_kb`, `size_kb`, and `type` properties became available in v3.6 of InSpec. ### Note Versions of this resource in Chef InSpec prior to 3.5.x offered a property `size`, which returned a value in GB when on Windows and a value in KB on Linux, though it was documented to always return KB. All new code should use `size_kb` which is unit-stable. The property `size` will remain available in Chef InSpec v3 and 4, but will be deprecated in the future. Syntax ------ A `filesystem` resource block declares tests for disk space in a partition: ``` describe filesystem('/') do its('size_kb') { should be >= 32 * 1024 * 1024} its('free_kb') { should be >= 50 * 1024 } its('percent_free') { should be >= 20 } its('type') { should cmp 'ext4' } end ``` where * `filesystem('/')` states that the resource will look at the root (/) partition. * `size_kb` is the total partition size and is measured in kilobytes (KB). * `free_kb` is the available space on the partition and is measured in kilobytes (KB). * `percent_free` is the percentage of available free space, and ranges from 0 to 100. Properties ---------- size_kb (Integer) ------------------ The `size_kb` property returns the total partition size in kb. ``` its('size_kb') { should be >= 32000 } ``` free_kb (Integer) ------------------ The `free_kb` property returns the size of available space on the partition in kb. ``` its('size_kb') { should be >= 32000 } ``` percent_free (Integrer) ------------------------ The `percent_free` property returns the available free space on the partition, ranges from 0 to 100. ``` its('percent_free') { should be >= 20 } ``` type (String) ------------- The `type` property returns the type of the file system. ``` its('type') { should cmp 'NTFS' } ``` Examples -------- ### Test if the root partition is greater than 32000 KB ``` describe filesystem('/') do its('size_kb') { should be >= 32000 } end ``` ### Test that the root partition has more than 5GB free ``` describe filesystem('/') do its('free_kb') { should be >= 5000000 } end ``` ### Test if the C:\ partition is NTFS Note that Windows filesystems (drives) are referred to without any slashes: ``` describe filesystem('c:') do its('type') { should cmp 'NTFS' } end ``` ### Test if the /var partition has sufficient free space ``` describe filesystem('/var') do its('percent_free') { should be >= 20 } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/filesystem/file resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/file.md) Use the `file` Chef InSpec audit resource to test all system file types, including files, directories, symbolic links, named pipes, sockets, character devices, block devices, and doors. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `file` resource block declares the location of the file type to be tested, the expected file type (if required), and one (or more) resource properties. ``` describe file('path') do it { should PROPERTY 'value' } end ``` where * `('path')` is the name of the file and/or the path to the file. * `PROPERTY` is a valid resource property for this resource' * `'value'` is the value to be tested. Properties ---------- ### General Properties * `content` * `size` * `basename` * `path` * `owner` * `group` * `type` ### Unix/Linux Properties * `symlink` * `mode` * `link_path` * `shallow_link_path` * `mtime` * `size` * `selinux_label` * `md5sum` * `sha256sum` * `path` * `source` * `source_path` * `uid` * `gid` ### Windows Properties * `file_version` * `product_version` Resource Property Examples -------------------------- ### content The `content` property tests if contents in the file match the value specified in a regular expression. The values of the `content` property are arbitrary and depend on the file type being tested and also the type of information that is expected to be in that file: ``` its('content') { should match REGEX } ``` The following complete example tests the `pg_hba.conf` file in PostgreSQL for MD5 requirements. The tests look at all `host` and `local` settings in that file, and then compare the MD5 checksums against the values in the test: ``` describe file('/etc/postgresql/9.1/main/pg_hba.conf') do its('content') { should match(%r{local\s.*?all\s.*?all\s.*?md5}) } its('content') { should match(%r{host\s.*?all\s.*?all\s.*?127.0.0.1\/32\s.*?md5}) } its('content') { should match(%r{host\s.*?all\s.*?all\s.*?::1\/128\s.*?md5}) } end ``` ### file_version The `file_version` property tests if a Windows file’s version matches the specified value. The difference between a file’s “file version” and “product version” is that the file version is the version number of the file itself, whereas the product version is the version number associated with the application from which that file originates: ``` its('file_version') { should eq '1.2.3' } ``` ### group The `group` property tests if the group to which a file belongs matches the specified value. ``` its('group') { should eq 'admins' } ``` The following examples show how to use this Chef InSpec audit resource. ### link_path The `link_path` property tests if the file exists at the specified path. If the file is a symlink, Chef InSpec will resolve the symlink recursively and return the ultimate linked file. ``` its('link_path') { should eq '/some/path/to/file' } ``` ### shallow_link_path The `shallow_link_path` property returns the path that the file refers to, only resolving it once (that is, it performs a readlink operation). If the file is not a symlink, nil is returned. ``` its('shallow_link_path') { should eq '/some/path/to/file' } ``` ### md5sum The `md5sum` property tests if the MD5 checksum for a file matches the specified value. ``` its('md5sum') { should eq '3329x3hf9130gjs9jlasf2305mx91s4j' } ``` ### mode The `mode` property tests if the mode assigned to the file matches the specified value. ``` its('mode') { should cmp '0644' } ``` Chef InSpec [octal](https://en.wikipedia.org/wiki/Leading_zero#0_as_a_prefix) values begin the numeric mode specification with zero. For example, write: ``` { should cmp '0644' } ``` not ``` { should cmp '644' } ``` or write: ``` { should cmp '01775' } ``` not ``` { should cmp '1775' } ``` Without the zero prefix for the octal value, Chef InSpec will interpret it as the *decimal* value 644, which is octal 1024 or `-----w-r-T`, and any test for a file that is `-rw-r--r--` will fail. Note: see the [`be_more_permissive_than(mode)`](#be_more_permissive_than?(mode)) matcher for upper and lower bounds on file mode. ### mtime The `mtime` property tests if the file modification time for the file matches the specified value. The mtime, where supported, is returned as the number of seconds since the epoch. ``` describe file('/') do its('mtime') { should <= Time.now.to_i } its('mtime') { should >= Time.now.to_i - 1000 } end ``` ### owner The `owner` property tests if the owner of the file matches the specified value. ``` its('owner') { should eq 'root' } ``` ### product_version The `product_version` property tests if a Windows file’s product version matches the specified value. The difference between a file’s “file version” and “product version” is that the file version is the version number of the file itself, whereas the product version is the version number associated with the application from which that file originates. ``` its('product_version') { should eq '2.3.4' } ``` ### selinux_label The `selinux_label` property tests if the SELinux label for a file matches the specified value. ``` its('selinux_label') { should eq 'system_u:system_r:httpd_t:s0' } ``` ### sha256sum The `sha256sum` property tests if the SHA-256 checksum for a file matches the specified value. ``` its('sha256sum') { should eq 'b837ch38lh19bb8eaopl8jvxwd2e4g58jn9lkho1w3ed9jbkeicalplaad9k0pjn' } ``` ### size The `size` property tests if a file’s size matches, is greater than, or is less than the specified value. For example, equal: ``` its('size') { should eq 32375 } ``` Greater than: ``` its('size') { should > 64 } ``` Less than: ``` its('size') { should < 10240 } ``` ### type The `type` property tests for the file type. The available types are: `file` the object is a file `directory` the object is a directory `link` the object is a symbolic link `pipe` the object is a named pipe `socket` the object is a socket `character_device` the object is a character device `block_device` the object is a block device `door` the object is a door device The `type` method usually returns the type as a Ruby “symbol”. We recommend using the `cmp` matcher to match either by symbol or string. For example: ``` its('type') { should eq :file } its('type') { should cmp 'file' } ``` or: ``` its('type') { should eq :socket } its('type') { should cmp 'socket' } ``` ### Test the contents of a file for MD5 requirements ``` describe file('/etc/postgresql/9.1/main/pg_hba.conf') do its('content') { should match /local\s.*?all\s.*?all\s.*?md5/ } its('content') { should match %r{/host\s.*?all\s.*?all\s.*?127.0.0.1\/32\s.*?md5/} } its('content') { should match %r{/host\s.*?all\s.*?all\s.*?::1\/128\s.*?md5/} } end ``` ### Test if a file exists ``` describe file('/tmp') do it { should exist } end ``` ### Test that a file does not exist ``` describe file('/tmpest') do it { should_not exist } end ``` ### Test if a path is a directory ``` describe file('/tmp') do its('type') { should eq :directory } it { should be_directory } end ``` ### Test if a path is a file and not a directory ``` describe file('/proc/version') do its('type') { should cmp 'file' } it { should be_file } it { should_not be_directory } end ``` ### Test if a file is a symbolic link ``` describe file('/dev/stdout') do its('type') { should cmp 'symlink' } it { should be_symlink } it { should_not be_file } it { should_not be_directory } end ``` ### Test if a file is a character device ``` describe file('/dev/zero') do its('type') { should cmp 'character' } it { should be_character_device } it { should_not be_file } it { should_not be_directory } end ``` ### Test if a file is a block device ``` describe file('/dev/zero') do its('type') { should cmp 'block' } it { should be_character_device } it { should_not be_file } it { should_not be_directory } end ``` ### Test the mode for a file ``` describe file('/dev') do its('mode') { should cmp '00755' } end ``` ### Test the owner of a file ``` describe file('/root') do its('owner') { should eq 'root' } end ``` ### Test if a file is owned by the root user ``` describe file('/dev') do it { should be_owned_by 'root' } end ``` ### Test the mtime for a file ``` describe file('/') do its('mtime') { should <= Time.now.to_i } its('mtime') { should >= Time.now.to_i - 1000 } end ``` ### Test that a file’s size is between 64 and 10240 ``` describe file('/') do its('size') { should be > 64 } its('size') { should be < 10240 } end ``` ### Test that a file’s size is zero ``` describe file('/proc/cpuinfo') do its('size') { should be 0 } end ``` ### Test an MD5 checksum ``` require 'digest' cpuinfo = file('/proc/cpuinfo').content md5sum = Digest::MD5.hexdigest(cpuinfo) describe file('/proc/cpuinfo') do its('md5sum') { should eq md5sum } end ``` ### Test an SHA-256 checksum ``` require 'digest' cpuinfo = file('/proc/cpuinfo').content sha256sum = Digest::SHA256.hexdigest(cpuinfo) describe file('/proc/cpuinfo') do its('sha256sum') { should eq sha256sum } end ``` ### Verify NTP The following example shows how to use the `file` audit resource to verify if the `ntp.conf` and `leap-seconds` files are present, and then the `command` resource to verify if NTP is installed and running: ``` describe file('/etc/ntp.conf') do it { should be_file } end describe file('/etc/ntp.leapseconds') do it { should be_file } end describe command('pgrep ntp') do its('exit_status') { should eq 0 } end ``` ### Test parameters of symlinked file If you need to test the parameters of the target file for a symlink, you can use the `link_path` (recursive resolution) or `shallow_link_path` (direct link) method for the `file` resource. For example, for the following symlink: ``` lrwxrwxrwx. 1 root root 11 03-10 17:56 /dev/virtio-ports/com.redhat.rhevm.vdsm -> ../vport2p1 ``` &mldr; you can write controls for both the link and the target. ``` describe file('/dev/virtio-ports/com.redhat.rhevm.vdsm') do it { should be_symlink } end virito_port_vdsm = file('/dev/virtio-ports/com.redhat.rhevm.vdsm').link_path describe file(virito_port_vdsm) do it { should exist } it { should be_character_device } it { should be_owned_by 'ovirtagent' } it { should be_grouped_into 'ovirtagent' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_allowed The `be_allowed` matcher tests if the file contains a certain permission set, such as `execute` or `write` in Unix and [`full-control` or `modify` in Windows](https://www.codeproject.com/Reference/871338/AccessControl-FileSystemRights-Permissions-Table). ``` it { should be_allowed('read') } ``` Just like with `be_executable` and other permissions, one can check for the permission with respect to the specific user or group. ``` it { should be_allowed('full-control', by_user: 'MyComputerName\Administrator') } ``` OR ``` it { should be_allowed('write', by: 'root') } ``` ### be_block_device The `be_block_device` matcher tests if the file exists as a block device, such as `/dev/disk0` or `/dev/disk0s9`: ``` it { should be_block_device } ``` ### be_character_device The `be_character_device` matcher tests if the file exists as a character device (that corresponds to a block device), such as `/dev/rdisk0` or `/dev/rdisk0s9`: ``` it { should be_character_device } ``` ### be_directory The `be_directory` matcher tests if the file exists as a directory, such as `/etc/passwd`, `/etc/shadow`, or `/var/log/httpd`: ``` it { should be_directory } ``` ### be_executable The `be_executable` matcher tests if the file exists as an executable: ``` it { should be_executable } ``` The `be_executable` matcher may also test if the file is executable by a specific owner, group, or user. For example, a group: ``` it { should be_executable.by('group') } ``` an owner: ``` it { should be_executable.by('owner') } ``` any user other than the owner or members of the file’s group: ``` it { should be_executable.by('others') } ``` a user: ``` it { should be_executable.by_user('user') } ``` ### be_file The `be_file` matcher tests if the file exists as a file. This can be useful with configuration files like `/etc/passwd` where there typically is not an associated file extension—`passwd.txt`: ``` it { should be_file } ``` ### be_grouped_into The `be_grouped_into` matcher tests if the file exists as part of the named group: ``` it { should be_grouped_into 'group' } ``` ### be_linked_to The `be_linked_to` matcher tests if the file is linked to the named target: ``` it { should be_linked_to '/etc/target-file' } ``` ### be_owned_by The `be_owned_by` matcher tests if the file is owned by the named user, such as `root`: ``` it { should be_owned_by 'root' } ``` ### be_pipe The `be_pipe` matcher tests if the file exists as first-in, first-out special file (`.fifo`) that is typically used to define a named pipe, such as `/var/log/nginx/access.log.fifo`: ``` it { should be_pipe } ``` ### be_readable The `be_readable` matcher tests if the file is readable: ``` it { should be_readable } ``` The `be_readable` matcher may also test if the file is readable by a specific owner, group, or user. For example, a group: ``` it { should be_readable.by('group') } ``` an owner: ``` it { should be_readable.by('owner') } ``` any user other than the owner or members of the file’s group: ``` it { should be_readable.by('others') } ``` a user: ``` it { should be_readable.by_user('user') } ``` ### be_setgid The `be_setgid` matcher tests if the ‘setgid’ permission is set on the file or directory. On executable files, this causes the process to be started owned by the group that owns the file, rather than the primary group of the invocating user. This can result in escalation of privilege. On Linux, when setgid is set on directories, setgid causes newly created files and directories to be owned by the group that owns the setgid parent directory; additionally, newly created subdirectories will have the setgid bit set. To use this matcher: ``` it { should be_setgid } ``` ### be_socket The `be_socket` matcher tests if the file exists as socket (`.sock`), such as `/var/run/php-fpm.sock`: ``` it { should be_socket } ``` ### be_sticky The `be_sticky` matcher tests if the ‘sticky bit’ permission is set on the directory. On directories, this restricts file deletion to the owner of the file, even if the permission of the parent directory would normally permit deletion by others. This is commonly used on /tmp filesystems. To use this matcher: ``` it { should be_sticky } ``` ### be_setuid The `be_setuid` matcher tests if the ‘setuid’ permission is set on the file. On executable files, this causes the process to be started owned by the user that owns the file, rather than invocating user. This can result in escalation of privilege. To use this matcher: ``` it { should be_setuid } ``` ### be_symlink The `be_symlink` matcher tests if the file exists as a symbolic, or soft link that contains an absolute or relative path reference to another file: ``` it { should be_symlink } ``` ### be_version The `be_version` matcher tests the version of the file: ``` it { should be_version '1.2.3' } ``` ### be_writable The `be_writable` matcher tests if the file is writable: ``` it { should be_writable } ``` The `be_writable` matcher may also test if the file is writable by a specific owner, group, or user. For example, a group: ``` it { should be_writable.by('group') } ``` an owner: ``` it { should be_writable.by('owner') } ``` any user other than the owner or members of the file’s group: ``` it { should be_writable.by('others') } ``` a user: ``` it { should be_writable.by_user('user') } ``` ### exist The `exist` matcher tests if the named file exists: ``` it { should exist } ``` ### have_mode The `have_mode` matcher tests if a file has a mode assigned to it: ``` it { should have_mode } ``` ### `be_more_permissive_than(mode)` `be_more_permissive_than(mode)` takes the maximum desired mode - in `octal format` (‘0644’ or ‘0777’) - of your file as a `String` and returns a `Boolean`. It will return `true` if your file has a mode with greater permissions than specified. ``` describe file('/etc/passwd') do it { should_not be_more_permissive_than('0644') } it { should be_more_permissive_than('0000') } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/file/group resource ============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/group.md) Use the `group` Chef InSpec audit resource to test a single group on the system. The `group` resource uses the following system groups: * On **non-Windows** systems the group resource tests a local group defined in the`/etc/group` file. * On **Windows** systems the group resource tests a local group defined by Local Users and Groups. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `group` resource block declares a group, and then the details to be tested, such as if the group is a local group, the group identifier, or if the group exists: ``` describe group('group_name') do it { should exist } its('gid') { should eq 0 } end ``` where * `'group_name'` must specify the name of a group to be tested on the system * `exist` and `'gid'` are valid matchers for this resource Properties ---------- ### gid The `gid` property returns the named group identifier: ``` its('gid') { should eq 1234 } ``` ### members The `members` property returns the members that belong to the group: ``` its('members') { should include 'root' } ``` where `members` returns: * an array of group members for **Windows Platform**. Example: `["member1", "member2"]` * a CSV formatted string of group members for **Non-Windows Platforms**. Example: `"member1,member2"` ### members_array The `members_array` property returns the members that belong to a group just like the `members` property, but the value returned by this property is always an array of group members. ``` its('members_array') { should include 'root' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the group identifier for the root group ``` describe group('root') do it { should exist } its('gid') { should eq 0 } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_local The `be_local` matcher tests if the group is a local group: ``` it { should be_local } ``` ### exist The `exist` matcher tests if the named group exists: ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/group/grub_conf resource =================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/grub_conf.md) Grub is a boot loader on the Linux platform used to load and then transfer control to an operating system kernel, after which that kernel initializes the rest of the operating system. Use the `grub_conf` Chef InSpec audit resource to test boot loader configuration settings that are defined in the `grub.conf` configuration file. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `grub_conf` resource block declares a list of settings in a `grub.conf` file: ``` describe grub_conf('path', 'kernel') do its('setting') { should eq 'value' } end ``` or: ``` describe grub_conf('path') do its('default') { should eq '0' } # its('setting') { should eq 'value' } end ``` where * `'service_name'` is a service listed in the `grub.conf` file * `'path'` is the path to the `grub.conf` file * `'kernel'` specifies the default kernel (by using `'default'`) or a specific kernel; `'default'` defines the position in the list of kernels at which the default kernel is defined, i.e. `should eq '0'` for the first kernel listed or `'path', 'default'` to use the default kernel as specified in the `grub.conf` file * `'value'` is the value that is expected Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test a grub.conf file A Grub configuration file located at `/etc/grub.conf` is similar to the following: ``` # grub.conf generated by anaconda # # Note: You do not need to rerun grub after making changes to this file # NOTICE: You have a /boot partition. This means that # all kernel and initrd paths are relative to /boot/, eg. # root (hd0,0) # kernel /vmlinuz-version ro root=/dev/hda6 # initrd /initrd-version.img #boot=/dev/hda default=0 timeout=10 splashimage=(hd0,0)/grub/splash.xpm.gz title Red Hat Enterprise Linux ES (2.6.32-573.7.1.el6.x86_64) root (hd0,0) kernel /vmlinuz-2.6.32-573.7.1.el6.x86_64 ro root=/dev/hda6 initrd /initrd-2.6.32-573.7.1.el6.x86_64.img title Red Hat Enterprise Linux ES (2.6.32-358.14.1.el6.x86_64) root (hd0,0) kernel /vmlinuz-2.6.32-358.14.1.el6.x86_64 ro root=/dev/hda6 ramdisk_size=400000 initrd /initrd-2.6.32-358.14.1.el6.x86_64.img ``` This file defines two versions of RedHat Enterprise Linux, with version `2.6.32-573.7.1.el6.x86_64` specified as the default. The following test verifies the kernel, ensures that kernel is the default kernel, its initial RAM disk (`initrd`), and the timeout: ``` describe grub_conf('/etc/grub.conf', 'default') do its('kernel') { should include '/vmlinuz-2.6.32-573.7.1.el6.x86_64' } its('initrd') { should include '/initrd-2.6.32-573.7.1.el6.x86_64.img' } its('default') { should_not eq '1' } its('timeout') { should eq '10' } end ``` The following test verifies the `ramdisk_size` for the non-default kernel: ``` describe grub_conf('/etc/grub.conf', 'Red Hat Enterprise Linux ES (2.6.32-358.14.1.el6.x86_64)') do its('kernel') { should include 'ramdisk_size=400000' } end ``` ### Test a configuration file and boot configuration ``` describe grub_conf('/etc/grub.conf', 'default') do its('kernel') { should include '/vmlinuz-2.6.32-573.7.1.el6.x86_64' } its('initrd') { should include '/initramfs-2.6.32-573.el6.x86_64.img=1' } its('default') { should_not eq '1' } its('timeout') { should eq '5' } end ``` ### Test a specific kernel ``` grub_conf('/etc/grub.conf', 'CentOS (2.6.32-573.12.1.el6.x86_64)') do its('kernel') { should include 'audit=1' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/grub_conf/groups resource =============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/groups.md) Use the `groups` Chef InSpec audit resource to test multiple groups on the system. The `groups` resource uses the following system groups: * On **non-Windows** systems the group resource tests local groups defined in the`/etc/group` file. * On **Windows** systems the group resource tests local groups defined by Local Users and Groups. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `groups` resource block uses `where` to filter entries from the systems groups. If `where` is omitted, all entries are selected. ``` describe groups do its('names') { should eq ['wheel', 'daemon', 'sys', 'adm'] } its('names') { should include 'wheel' } end describe groups.where { members =~ /root/ } do its('names') { should eq ['wheel', 'daemon', 'sys', 'adm'] } end ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the group identifier for the wheel group ``` describe groups.where { name == 'wheel' } do it { should exist } its('members') { should include 'root' } end ``` Properties ---------- ### gids The `gids` property tests the named group identifier: ``` its('gids') { should eq 1234 } ``` ### names The `names` property tests the name field on a Windows group: its(‘names’) { should include ‘Power Users’ } ### domains The `domains` property tests the domain on a Windows group: its(‘domains’) { should include ‘WIN-CIV7VMLVHLD’ } ### members The `members` property tests the members that belong to a group: ``` its('members') { should include 'root' } its('members') { should include 'Administrator' } ``` where `members` returns: * an array of group members for **Windows Platform**. Example: `["member1", "member2"]` * a single element array that contains a CSV string of group members for **Non-Windows Platforms**. Example: `["member1,member2"]` ### members_array The `members_array` property tests the group members just like the `members` property, but the value returned by this property is always an array of group members. ``` its('members_array') { should include 'root' } its('members_array') { should include 'Administrator' } ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `exist` matcher tests if the named user exists: ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/groups/http resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/http.md) Use the `http` Chef InSpec audit resource to test an http endpoint. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.10.0 of InSpec. Syntax ------ An `http` resource block declares the configuration settings to be tested: ``` describe http('url', auth: {user: 'user', pass: 'test'}, params: {params}, method: 'method', headers: {headers}, data: data, open_timeout: 60, read_timeout: 60, ssl_verify: true, max_redirects: 3) do its('status') { should eq number } its('body') { should eq 'body' } its('headers.name') { should eq 'header' } end ``` where * `('url')` is the url to test * `auth: { user: 'user', pass: 'test' }` may be specified for basic auth request * `{params}` may be specified for http request parameters * `'method'` may be specified for http request method (default to ‘GET’) * `{headers}` may be specified for http request headers * `data` may be specified for http request body * `open_timeout` may be specified for a timeout for opening connections (default to 60) * `read_timeout` may be specified for a timeout for reading connections (default to 60) * `ssl_verify` may be specified to enable or disable verification of SSL certificates (default to `true`) * `max_redirects` may be specified to control how many HTTP Redirects to follow (defaults to `0`) Example ------- The following examples show how to use this Chef InSpec audit resource. An `http` resource block declares the configuration settings to be tested: ### Simple http test For example, a service is listening on default http port can be tested like this: ``` describe http('http://localhost') do its('status') { should cmp 200 } end ``` ### Complex http test ``` describe http('http://localhost:8080/ping', auth: {user: 'user', pass: 'test'}, params: {format: 'html'}, method: 'POST', headers: {'Content-Type' => 'application/json'}, data: { a":"1", "b":"five" } ) do its('status') { should cmp 200 } its('body') { should cmp 'pong' } its('headers.Content-Type') { should cmp 'text/html' } end ``` Local vs. Remote ---------------- Beginning with Chef InSpec 1.41, you can enable the ability to have the HTTP test execute on the remote target: Parameters ---------- Parameter Examples ------------------ ### url `('url')` is the url to test. ``` describe http('http://localhost:8080/ping') do ... end ``` ### auth `auth: { user: 'user', pass: 'test' }` may be specified for basic auth request. ``` describe http('http://localhost:8080/ping', auth: {user: 'user', pass: 'test'}) do ... end ``` ### params `{params}` may be specified for http request parameters. ``` describe http('http://localhost:8080/ping', params: {format: 'html'}) do ... end ``` ### method `'method'` may be specified for http request method (default to ‘GET’). ``` describe http('http://localhost:8080/ping', method: 'POST') do ... end ``` ### headers `{headers}` may be specified for http request headers. ``` describe http('http://localhost:8080/ping', headers: {'Content-Type' => 'application/json'}) do ... end ``` ### data `data` may be specified for http request body. When working with remote Windows target use single quotes around data that you are passing for e.g. `data: '{ "a" : "1", "b" : "five" }'` ``` describe http('http://localhost:8080/ping', data: { "a":"1", "b":"five" } ) do ... end ``` ### open_timeout `open_timeout` may be specified for a timeout for opening connections (default to 60). ``` describe http('http://localhost:8080/ping', open_timeout: '90') do ... end ``` ### read_timeout `read_timeout` may be specified for a timeout for reading connections (default to 60). ``` describe http('http://localhost:8080/ping', read_timeout: '90') do ... end ``` ### ssl_verify `ssl_verify` may be specified to enable or disable verification of SSL certificates (default to `true`). ``` describe http('http://localhost:8080/ping', ssl_verify: true) do ... end ``` ### max_redirects `max_redirects` may be specified to control how many HTTP Redirects to follow (default to 0). ``` describe http('http://localhost:8080/ping', max_redirects: 3) do ... end ``` ### proxy Specify a `proxy` to test by passing in the proxy URI or a hash of the proxy URI, a username, and password. Specify `disable` to ignore a proxy set as an environment variable. You can include the username and password in the `proxy` parameter: ``` describe http('http://localhost:8080/ping', proxy: "http://username:password@www.example.com:3128") do ... end ``` The `proxy` parameter also accepts proxy options in hash format: ``` describe http('http://localhost:8080/ping', proxy: { uri: 'http://www.example.com:3128', user: 'username', password: 'proxypassword'}) do ... end ``` Use `disable` to ignore the proxy set in the environment variable: ``` describe http('http://localhost:8080/ping', proxy: 'disable') do ... end ``` Note Windows remote targets do not accept username and password values in a string; use the hash format instead. Note Special characters in the URI must be converted to their UTF-8 equivalent when passed in to the `proxy` parameter as a string. For example, the string `http://username:bar@123@www.example.com:3128` must be passed in as `http://username:bar%40123@www.example.com:3128` instead. Special characters may be passed into the hash format without conversion to UTF-8 characters. Properties ---------- ### body The `body` property tests body content of http response: ``` its('body') { should eq 'hello\n' } ``` ### headers The `headers` property returns an hash of all http headers: ``` its('headers') { should eq {} } ``` Individual headers can be tested via: ``` its('headers.Content-Type') { should cmp 'text/html' } ``` ### http_method The `http_method` property returns the http method of the http request. ``` its('http_method') { should eq 'GET'} ``` ### status The `status` property tests status of the http response: ``` its('status') { should eq 200 } ``` Example ------- The following examples show how to use this Chef InSpec audit resource. An `http` resource block declares the configuration settings to be tested: ### Simple http test For example, a service is listening on default http port can be tested like this: ``` describe http('http://localhost') do its('status') { should cmp 200 } end ``` ### Complex http test ``` describe http('http://localhost:8080/ping', auth: {user: 'user', pass: 'test'}, params: {format: 'html'}, method: 'POST', headers: {'Content-Type' => 'application/json'}, data: '{"data":{"a":"1","b":"five"}}') do its('status') { should cmp 200 } its('body') { should cmp 'pong' } its('headers.Content-Type') { should cmp 'text/html' } end ``` Local vs. Remote ---------------- Beginning with Chef InSpec 1.41, you can enable the ability to have the HTTP test execute on the remote target: ``` describe http('http://www.example.com', enable_remote_worker: true) do its('body') { should cmp 'awesome' } end ``` In Chef InSpec 2.0, the HTTP test will automatically execute remotely whenever Chef InSpec is testing a remote node. Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/http/ibmdb2_session resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/ibmdb2_session.md) Use the `ibmdb2_session` Chef InSpec audit resource to test SQL commands run against an IBM Db2 database. Make sure you are using the IBM Db2 database instance user credentials to run the InSpec test. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. Syntax ------ A `ibmdb2_session` resource block declares the db2_executable_file_path, db_instance and db_name to use for the session, and then the query to be run: ``` describe ibmdb2_session(db2_executable_file_path: "/opt/ibm/db2/V11.5/bin/db2", db_instance: "db2inst1", db_name: "sample").query("select rolename from syscat.roleauth") do its("output") { should match(/SYSTS_MGR/) } end ``` Windows ``` describe ibmdb2_session(db_name: "sample").query("select rolename from syscat.roleauth") do its("output") { should match(/SYSTS_MGR/) } end ``` where * `ibmdb2_session` declares a db2_executable_file_path, db_instance and db_name to connect. * `db2_executable_file_path` is the path of the db2 binary file. For Windows this is not required. * `db_instance` is the name of the database instance. For Windows this is not required. * `db_name` is the name of the database to query on. * `query('QUERY')` contains the query to be run. * `its('output') { should eq(/expected-result/) }` compares the results of the query against the expected result in the test. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test for matching role name ``` describe ibmdb2_session(db2_executable_file_path: "/opt/ibm/db2/V11.5/bin/db2", db_instance: "db2inst1", db_name: "sample").query("select rolename from syscat.roleauth") do its("output") { should match(/SYSTS_MGR/) } end ``` ### Test for matching database ``` describe ibmdb2_session(db2_executable_file_path: "/opt/ibm/db2/V11.5/bin/db2", db_instance: "db2inst1", db_name: "sample").query("list database directory") do its("output") { should match(/SAMPLE/) } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/ibmdb2_session/ibmdb2_conf resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/ibmdb2_conf.md) Use the `ibmdb2_conf` Chef InSpec audit resource to test the configuration settings. Make sure you are using the IBM Db2 database instance user credentials to run the InSpec test. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. Syntax ------ A `ibmdb2_conf` resource block declares db2_executable_file_path, db_instance to connect and then runs command to get the configuration values and compares it to the value stated in the test: ``` describe ibmdb2_conf(db2_executable_file_path: "/opt/ibm/db2/V11.5/bin/db2", db_instance: "db2inst1") do its("output") { should_not be_empty } its("output") { should include("Audit buffer size (4KB) (AUDIT_BUF_SZ) = 0")} end ``` Windows ``` describe ibmdb2_conf do its("output") { should_not be_empty } its("output") { should include("Audit buffer size (4KB) (AUDIT_BUF_SZ) = 0")} end ``` where * `ibmdb2_session` declares a db2_executable_file_path, db_instance and db_name to connect. * `db2_executable_file_path` is the path of the db2 binary file. For Windows this is not required. * `db_instance` is the name of the database instance. For Windows this is not required. * `its("output") { should include("expected_settings")}` compares the results of the output against the expected result in the test. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the audit buffer size configuration settings of IBM Db2 database ``` describe ibmdb2_conf(db2_executable_file_path: "/opt/ibm/db2/V11.5/bin/db2", db_instance: "db2inst1") do its("output") { should_not be_empty } its("output") { should include("Audit buffer size (4KB) (AUDIT_BUF_SZ) = 1000")} end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/ibmdb2_conf/inetd_conf resource ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/inetd_conf.md) Use the `inetd_conf` Chef InSpec audit resource to test if a service is listed in the `inetd.conf` file on Linux and Unix platforms. inetd—the Internet service daemon—listens on dedicated ports, and then loads the appropriate program based on a request. The `inetd.conf` file is typically located at `/etc/inetd.conf` and contains a list of Internet services associated to the ports on which that service will listen. Only enabled services may handle a request; only services that are required by the system should be enabled. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `inetd_conf` resource block declares the list of services that are enabled in the `inetd.conf` file: ``` describe inetd_conf('path') do its('service_name') { should eq 'value' } end ``` where * `'service_name'` is a service listed in the `inetd.conf` file * `('path')` is the non-default path to the `inetd.conf` file * `should eq 'value'` is the value that is expected Properties ---------- This resource supports any of the properties listed as services in the `inetd.conf` file. You may want to ensure that specific services do not listen via `inetd.conf`. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Basic tests for inetd_conf services: ``` its('shell') { should eq nil } ``` or: ``` its('netstat') { should eq nil } ``` or: ``` its('systat') { should eq nil } ``` For example: ``` describe inetd_conf do its('shell') { should eq nil } its('login') { should eq nil } its('exec') { should eq nil } end ``` ### Verify that FTP is disabled The contents if the `inetd.conf` file contain the following: ``` #ftp stream tcp nowait root /usr/sbin/tcpd in.ftpd -l -a #telnet stream tcp nowait root /usr/sbin/tcpd in.telnetd ``` and the following test is defined: ``` describe inetd_conf do its('ftp') { should eq nil } its('telnet') { should eq nil } end ``` Because both the `ftp` and `telnet` Internet services are commented out (`#`), both services are disabled. Consequently, both tests will return `true`. However, if the `inetd.conf` file is set as follows: ``` ftp stream tcp nowait root /usr/sbin/tcpd in.ftpd -l -a #telnet stream tcp nowait root /usr/sbin/tcpd in.telnetd ``` then the same test will return `false` for `ftp` and the entire test will fail. ### Test if telnet is installed ``` describe package('telnetd') do it { should_not be_installed } end describe inetd_conf do its('telnet') { should eq nil } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/inetd_conf/host resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/host.md) Use the `host` Chef InSpec audit resource to test the name used to refer to a specific host and its availability, including the Internet protocols and ports over which that host name should be available. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `host` resource block declares a host name, and then (depending on what is to be tested) a port and/or a protocol: ``` describe host('example.com', port: 80, protocol: 'tcp') do it { should be_reachable } it { should be_resolvable } its('ipaddress') { should include '12.34.56.78' } end ``` where * `host()` must specify a host name and may specify a port number and/or a protocol * `'example.com'` is the host name * `port:` is the port number * `protocol:` is the Internet protocol: TCP (`protocol: 'tcp'`), UDP (`protocol: 'udp'` or ICMP (`protocol: 'icmp'`)) Properties ---------- ### ipaddress The `ipaddress` property returns the ipaddress of the host. ``` its('ipaddress') { should include '93.184.216.34' } ``` ### connection The `connection` property returns the connection string. ``` its('connection') { should match /connection refused/ } ``` ### `protocol` The `protocol` property returns the protocol that given host is using. ``` its('protocol') { should eq 'tcp' } ``` ### `socket`property returns the socket for the given host. ``` its('socket') { should match /STATUS_OK/ } ``` Examples -------- ### Verify that host name is resolvable to specific IP address. ``` describe host('example.com') do its('ipaddress') { should include '93.184.216.34' } end ``` ### Verify host name is reachable over a specific protocol and port number ``` describe host('example.com', port: 80, protocol: 'tcp') do it { should be_reachable } end ``` ### Verify that a specific IP address can be resolved ``` describe host('example.com') do it { should be_resolvable } its('ipaddress') { should include '93.184.216.34' } end ``` ### Review the connection setup and socket contents when checking reachability ``` describe host('example.com', port: 12345, protocol: 'tcp') do it { should be_reachable } its('connection') { should_not match /connection refused/ } its('socket') { should match /STATUS_OK/ } end ``` Matchers -------- This Chef InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_reachable The `be_reachable` matcher tests if the host name is available: ``` it { should be_reachable } ``` ### be_resolvable The `be_resolvable` matcher tests for host name resolution, i.e. “resolvable to an IP address”: ``` it { should be_resolvable } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/host/iis_app resource ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/iis_app.md) Use the `iis_app` Chef InSpec audit resource to test the state of IIS on Windows Server 2012 (and later). Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.28.0 of InSpec. Syntax ------ An `iis_app` resource block declares details about the named site: ``` describe iis_app('application_path', 'site_name') do it { should exist } it { should have_application_pool('application_pool') } it { should have_protocol('protocol') } it { should have_site_name('site') } it { should have_physical_path('physical_path') } it { should have_path('application_path') } end ``` where * `'application_path'` is the path to the application, such as `'/myapp'` * `have_application_pool`, `have_protocol`, `have_site_name`, `have_physical_path` and `have_path` are the different [matchers](#matchers) for this resource. For example: ``` describe iis_app('/myapp', 'Default Web Site') do it { should exist } it { should have_application_pool('MyAppPool') } it { should have_protocol('http') } it { should have_site_name('Default Web Site') } it { should have_physical_path('C:\\inetpub\\wwwroot\\myapp') } it { should have_path('\\My Application') } end ``` Properties ---------- ### application pool `application_pool` property returns the name of the application pool in which the site’s root application is run, such as `DefaultAppPool`. ``` its('application_pool') { should eq 'root' } ``` ### path `path` property returns the path to the application. ``` its('path') { should eq '\my_app' } ``` ### physical_path `physical_path` property returns the physical path of the application, such as `'C:\\inetpub\\wwwroot\\myapp'`. ``` its('phyiscal_path') { should eq 'C:\\inetpub\\wwwroot\\myapp' } ``` ### protocols `protocols` property returns an array of protocols i.e. the binding for the site, such as `'http'`. A site may have multiple bindings. ``` its('protocols') { should include 'http' } ``` ### site_name `site_name` property returns the name of the site, such as `'Default Web Site'` ``` its('site_name') { should eq 'Default Web Site' } ``` Examples -------- ### Test a default IIS web application ``` describe iis_app('Default Web Site') do it { should exist } it { should be_running } it { should have_app_pool('DefaultAppPool') } it { should have_binding('http *:80:') } it { should have_path('%SystemDrive%\\inetpub\\wwwroot') } end ``` ### Test if IIS service is running ``` describe service('W3SVC') do it { should be_installed } it { should be_running } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `exist` matcher tests if the site exists: ``` it { should exist } ``` ### have_application_pool The `have_application_pool` matcher tests if the named application pool exists for the web application: ``` it { should have_application_pool('DefaultAppPool') } ``` ### have_protocol The `have_protocol` matcher tests if the specified protocol exists for the web application: ``` it { should have_protocol('http') } ``` or: ``` it { should have_protocol('https') } ``` A web application may have multiple bindings; use a `have_protocol` matcher for each unique web application binding to be tested. ##### Protocol Attributes The `have_protocol` matcher can also test attributes that are defined for a web application enabledProtocols. ``` it { should have_protocol('http') } ``` For example, testing a site that doesn’t have https enabled: ``` it { should_not have_protocol('https') } it { should have_protocol('http') } ``` Testing a web application with https enabled and http enabled: ``` it { should have_protocol('https') } it { should have_protocol('http') } ``` ### have_physical_path The `have_physical_path` matcher tests if the named path is defined for the web application: ``` it { should have_physical_path('C:\\inetpub\\wwwroot') } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/iis_app/ini resource ============ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/ini.md) Use the `ini` Chef InSpec audit resource to test settings in an INI file. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `ini` resource block declares the configuration settings to be tested: ``` describe ini('path') do its('setting_name') { should eq 'value' } end ``` where * `'setting_name'` is a setting key defined in the INI file * `('path')` is the path to the INI file * `{ should eq 'value' }` is the value that is expected For example: ``` describe ini('path/to/ini_file.ini') do its('port') { should eq '143' } its('server') { should eq '192.0.2.62' } end ``` Settings inside of sections, such as the following: ``` [section_name] setting_name = 123 ``` &mldr; can be retrieved by prefixing the setting_name with the section. ``` its('section_name.setting_name') { should cmp 123 } ``` In the event a section or setting name has a period in it, the alternate syntax can be used: ``` its(['section.with.a.dot.in.it', 'setting.name.with.dots']) { should cmp 'lotsadots' } ``` Properties ---------- This resource supports any of the settings listed in an INI file as properties. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test SMTP settings in a PHP INI file For example, a PHP INI file located at contains the following settings: ``` [mail function] SMTP = smtp.gmail.com smtp_port = 465 ``` and can be tested like this: ``` describe ini('/etc/php5/apache2/php.ini') do its('mail function.smtp_port') { should eq('465') } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/ini/iis_site resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/iis_site.md) Use the `iis_site` Chef InSpec audit resource to test the state of IIS on Windows Server 2012 (and later). Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `iis_site` resource block declares details about the named site: ``` describe iis_site('site_name') do it { should exist } it { should be_running } it { should have_app_pool('app_pool_name') } it { should have_binding('binding_details') } it { should have_path('path_to_site') } end ``` where * `'site_name'` is the name of the site, such as `'Default Web Site'` * `('app_pool_name')` is the name of the application pool in which the site’s root application is run, such as `'DefaultAppPool'` * `('binding_details')` is a binding for the site, such as `'net.pipe *'`. A site may have multiple bindings; therefore, use a `have_binding` matcher for each site binding to be tested * `('path_to_site')` is the path to the site, such as `'C:\\inetpub\\wwwroot'` For example: ``` describe iis_site('Default Web Site') do it { should exist } it { should be_running } it { should have_app_pool('DefaultAppPool') } it { should have_binding('https :443:www.contoso.com sslFlags=0') } it { should have_binding('net.pipe *') } it { should have_path('C:\\inetpub\\wwwroot') } end ``` Properties ---------- app_pool, bindings, path, state Property Examples ----------------- The following examples show how to use this Chef InSpec audit resource. ### Test a default IIS site ``` describe iis_site('Default Web Site') do it { should exist } it { should be_running } it { should have_app_pool('DefaultAppPool') } it { should have_binding('http *:80:') } it { should have_path('%SystemDrive%\\inetpub\\wwwroot') } end ``` ### Test if IIS service is running ``` describe service('W3SVC') do it { should be_installed } it { should be_running } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_running The `be_running` matcher tests if the site is running: ``` it { should be_running } ``` ### exist The `exist` matcher tests if the site exists: ``` it { should exist } ``` ### have_app_pool The `have_app_pool` matcher tests if the named application pool exists for the site: ``` it { should have_app_pool('DefaultAppPool') } ``` For example, testing if a site’s application pool inherits the settings of the parent application pool: ``` it { should have_app_pool('/') } ``` ### have_binding The `have_binding` matcher tests if the specified binding exists for the site: ``` it { should have_binding('http :80:*') } ``` or: ``` it { should have_binding('net.pipe *') } ``` A site may have multiple bindings; use a `have_binding` matcher for each unique site binding to be tested. ##### Binding Attributes The `have_binding` matcher can also test attributes that are defined for a site binding. For example, the `sslFlags` attribute defines if SSL is enabled, and (when enabled) what level of SSL is applied to the site. Testing a site with SSL disabled: ``` it { should have_binding('https :443:www.contoso.com sslFlags=0') } ``` Testing a site with SSL enabled: ``` it { should have_binding('https :443:www.contoso.com sslFlags=Ssl') } ``` Testing a site with certificate mapping authentication enabled: ``` it { should have_binding('https :443:www.contoso.com sslFlags=SslMapCert') } ``` Testing a site with 128-bit SSL enabled: ``` it { should have_binding('https :443:www.contoso.com sslFlags=Ssl128') } ``` ### have_path The `have_path` matcher tests if the named path is defined for the site: ``` it { should have_path('C:\\inetpub\\wwwroot') } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/iis_site/interface resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/interface.md) Use the `interface` Chef InSpec audit resource to test basic network adapter properties, such as name, status, IP addresses, and link speed (in MB/sec). * On Linux platforms, `/sys/class/net/#{iface}` is used as source * On the Windows platform, the `Get-NetAdapter` cmdlet is used as source * On BSD and MacOS platforms, the `ifconfig` command is used as source. Link speed may not be available. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of Chef InSpec. Syntax ------ An `interface` resource block declares network interface properties to be tested: ``` describe interface('eth0') do it { should be_up } its('speed') { should eq 1000 } its('name') { should eq eth0 } its('ipv4_addresses') { should include '10.0.0.5' } end ``` Properties ---------- ### ipv4_address Returns the first `ipv4_addresses` entry as a String. Note: this property is incompatible with ServerSpec, which returns the value including the CIDR range, such as ‘10.0.0.5/32’. ``` its('ipv4_address') { should eq '10.0.0.5' } ``` ### ipv4_addresses The `ipv4_addresses` property returns an Array of IPv4 addresses as Strings. You may then test if the specified address exists on the named network interface: ``` its('ipv4_addresses') { should include '127.0.0.1' } ``` ### ipv4_addresses_netmask The `ipv4_addresses_netmask` property returns an Array of Strings with each containing the IPv4 address, a slash, and the netmask. You may then test if the specified address and netmask exists on the named network interface: ``` its('ipv4_addresses_netmask') { should include '127.0.0.1/255.0.0.0' } ``` ### ipv6_address Returns the first `ipv6_address` entry. Note: this property is incompatible with ServerSpec, which returns the value including the CIDR range. ``` its('ipv6_address') { should eq '2089:98b::faeb' } ``` ### ipv6_addresses The `ipv6_addresses` property returns an Array of Strings and tests if the specified address exists on the named network interface: ``` its('ipv6_addresses') { should include '::1' } ``` ### ipv4_cidrs The `ipv4_cidrs` property returns an Array of Strings and tests if the specified address and netmask combination exists on the named network interface: ``` its('ipv4_cidrs') { should include '127.0.0.1/8' } ``` ### ipv6_cidrs The `ipv6_cidrs` property returns an Array of Strings and tests if the specified address and netmask combination exists on the named network interface: ``` its('ipv6_cidrs') { should include '::1/128' } ``` ### name The `name` property returns the name of the interface: ``` its('name') { should eq 'eth0' } ``` ### speed The `speed` property tests the speed of the network interface, in MB/sec. Note: On BSD and MacOS platforms, this value may be nil, because it difficult to obtain reliably. ``` its('speed') { should eq 1000 } ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_up The `be_up` matcher tests if the network interface is available: ``` it { should be_up } ``` ### exist The `exist` matcher tests if the network interface exists: ``` it { should exist } ``` ### have_an_ipv4_address The `have_an_ipv4_address` matcher tests if the network interface has any IPv4 addresses assigned: ``` it { should have_an_ipv4_address } ``` ### have_an_ipv6_address The `have_an_ipv6_address` matcher tests if the network interface has any IPv6 addresses assigned: ``` it { should have_an_ipv6_address } ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/interface/interfaces resource =================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/interfaces.md) Use the `interfaces` Chef InSpec audit resource to test the properties of multiple network interfaces on the system. Syntax ------ An `interfaces` resource block may take no arguments, in which case it will list all interfaces: ``` describe interfaces do its('names') { should include 'eth0' } end ``` An `interfaces` resource block may take a where clause, filtering on a Filter Criterion: ``` # All eth- interfaces describe interfaces.where(name: /^eth\d+/) its('names') { should include 'eth0' } end ``` Like any Chef InSpec resource, you may also use it for data lookup instead of testing: ``` # We are an IPv6 shop interfaces.where(name: /^eth/).names do |name| describe interface(name) do it { should have_ipv6_address } end end # Obtain the machine's main IP address my_ip = interfaces.ipv4_address ``` Filter Criteria --------------- ### name String. The name of an interface. Properties ---------- ### count The `count` property returns an Integer describing how many interfaces matched. its(“count”) { should eq 6 } ### ipv4_address Attempts to guess the “first” “real” IPv4 address on any interface. Looks for interfaces that are up and have IPv4 addresses assigned, then tries to filter out loopback, management (10/8) and local (192.168/16) IP addresses, returning the best of of those that it can; you may still get nil, or a loopback address. Note that if the machine is behind NAT this will not be the external IP address; use the `http` resource to query an IP lookup service for that. its(‘ipv4_address’) { should_not eq ‘127.0.0.1’ } ### names The `names` property returns an Array of Strings representing the names of the interfaces. its(“names”) { should include “eth0” } Matchers -------- For a full list of available universal matchers, please visit our [matchers page](../../matchers/index). ### exist The `exist` matcher tests true if at least one interface exists on the system. This is almost always the case. ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/interfaces/ip6tables resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/ip6tables.md) Use the `ip6tables` Chef InSpec audit resource to test rules that are defined in `ip6tables`, which maintains tables of IP packet filtering rules for IPv6. There may be more than one table. Each table contains one (or more) chains (both built-in and custom). A chain is a list of rules that match packets. When the rule matches, the rule defines what target to assign to the packet. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v4.6.9 of InSpec. Syntax ------ A `ip6tables` resource block declares tests for rules in IP tables: ``` describe ip6tables(rule:'name', table:'name', chain: 'name') do it { should have_rule('RULE') } end ``` where * `ip6tables()` may specify any combination of `rule`, `table`, or `chain` * `rule:'name'` is the name of a rule that matches a set of packets * `table:'name'` is the packet matching table against which the test is run * `chain: 'name'` is the name of a user-defined chain or one of `ACCEPT`, `DROP`, `QUEUE`, or `RETURN` * `have_rule('RULE')` tests that rule in the ip6tables list. This must match the entire line taken from `ip6tables -S CHAIN`. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if the INPUT chain is in default ACCEPT mode ``` describe ip6tables do it { should have_rule('-P INPUT ACCEPT') } end ``` ### Test if the INPUT chain from the mangle table is in ACCEPT mode ``` describe ip6tables(table:'mangle', chain: 'INPUT') do it { should have_rule('-P INPUT ACCEPT') } end ``` ### Test if there is a rule allowing Postgres (5432/TCP) traffic ``` describe ip6tables do it { should have_rule('-A INPUT -p tcp -m tcp -m multiport --dports 5432 -m comment --comment "postgres" -j ACCEPT') } end ``` Note that the rule specification must exactly match what’s in the output of `ip6tables -S INPUT`, which will depend on how you’ve built your rules. Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### have_rule The `have_rule` matcher tests the named rule against the information in the `ip6tables` file: ``` it { should have_rule('RULE') } ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/ip6tables/iptables resource ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/iptables.md) Use the `iptables` Chef InSpec audit resource to test rules that are defined in `iptables`, which maintains tables of IP packet filtering rules. There may be more than one table. Each table contains one (or more) chains (both built-in and custom). A chain is a list of rules that match packets. When the rule matches, the rule defines what target to assign to the packet. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `iptables` resource block declares tests for rules in IP tables: ``` describe iptables(rule:'name', table:'name', chain: 'name') do it { should have_rule('RULE') } end ``` where * `iptables()` may specify any combination of `rule`, `table`, or `chain` * `rule:'name'` is the name of a rule that matches a set of packets * `table:'name'` is the packet matching table against which the test is run * `chain: 'name'` is the name of a user-defined chain or one of `ACCEPT`, `DROP`, `QUEUE`, or `RETURN` * `have_rule('RULE')` tests that rule in the iptables list. This must match the entire line taken from `iptables -S CHAIN`. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if the INPUT chain is in default ACCEPT mode ``` describe iptables do it { should have_rule('-P INPUT ACCEPT') } end ``` ### Test if the INPUT chain from the mangle table is in ACCEPT mode ``` describe iptables(table:'mangle', chain: 'INPUT') do it { should have_rule('-P INPUT ACCEPT') } end ``` ### Test if there is a rule allowing Postgres (5432/TCP) traffic ``` describe iptables do it { should have_rule('-A INPUT -p tcp -m tcp -m multiport --dports 5432 -m comment --comment "postgres" -j ACCEPT') } end ``` Note that the rule specification must exactly match what’s in the output of `iptables -S INPUT`, which will depend on how you’ve built your rules. Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### have_rule The `have_rule` matcher tests the named rule against the information in the `iptables` file: ``` it { should have_rule('RULE') } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/iptables/json resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/json.md) Use the `json` Chef InSpec audit resource to test data in a JSON file. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `json` resource block declares the data to be tested. Assume the following JSON file: ``` { "name" : "hello", "meta" : { "creator" : "<NAME>" }, "array": [ "zero", "one" ] } ``` This file can be queried using: ``` describe json('/path/to/name.json') do its('name') { should eq 'hello' } its(['meta','creator']) { should eq '<NAME>' } its(['array', 1]) { should eq 'one' } end ``` where * `name` is a configuration setting in a JSON file * `should eq 'foo'` tests a value of `name` as read from a JSON file versus the value declared in the test The `json` resource can also be used with JSON formatted output from a command. Using the same JSON as the previous example, it can be queried using: ``` describe json({ command: 'retrieve_data.py --json'}) do its('name') { should eq 'hello' } its(['meta','creator']) { should eq '<NAME>' } its(['array', 1]) { should eq 'one' } end ``` Finally, content can be passed directly to the resource: ``` describe json({ content: '{\"item1\": { \"status\": \"available\" } }' }) do its(['item1', 'status']) { should cmp 'available' } end ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### name The `name` matcher tests the value of the filename as read from a JSON file versus the value declared in the test: ``` its('name') { should eq '/tmp/example.json' } ``` ### Test a cookbook version in a policyfile.lock.json file ``` describe json('policyfile.lock.json') do its(['cookbook_locks', 'omnibus', 'version']) { should eq('2.2.0') } end ``` ### Test JSON output from an HTTP API Our example API has a `/health` endpoint, which looks like this: ``` { "service": { "port": 3000, "status": "ok" } } ``` Example test: ``` describe json(content: http('http://localhost:3000/health').body) do its(['service', 'port']) { should eq 3000 } its(['service', 'status']) { should eq 'ok' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/json/launchd_service resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/launchd_service.md) Use the `launchd_service` Chef InSpec audit resource to test a service using Launchd. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `launchd_service` resource block declares the name of a service and then one (or more) matchers to test the state of the service: ``` describe launchd_service('service_name') do it { should be_installed } it { should be_enabled } it { should be_running } end ``` where * `('service_name')` must specify a service name * `be_installed`, `be_enabled`, and `be_running` are valid matchers for this resource; all matchers available to the `service` resource may be used The path to the service manager’s control may be specified for situations where the path isn’t available in the current `PATH`. For example: ``` describe launchd_service('service_name', '/path/to/control') do it { should be_enabled } it { should be_installed } it { should be_running } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if the named service is enabled: ``` it { should be_enabled } ``` ### be_installed The `be_installed` matcher tests if the named service is installed: ``` it { should be_installed } ``` ### be_running The `be_running` matcher tests if the named service is running: ``` it { should be_running } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/launchd_service/key_rsa resource ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/key_rsa.md) Use the `key_rsa` Chef InSpec audit resource to test RSA public/private keypairs. This resource is mainly useful when used in conjunction with the x509_certificate resource but it can also be used for checking SSH keys. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.18.0 of InSpec. Syntax ------ An `key_rsa` resource block declares a `key file` to be tested. ``` describe key_rsa('mycertificate.key') do it { should be_private } it { should be_public } its('public_key') { should match "-----BEGIN PUBLIC KEY-----\n3597459df9f3982" } its('key_length') { should eq 2048 } end ``` You can use an optional passphrase with `key_rsa` ``` describe key_rsa('mycertificate.key', 'passphrase') do it { should be_private } end ``` Properties ---------- ### public_key (String) The `public_key` property returns the public part of the RSA key pair ``` describe key_rsa('/etc/pki/www.mywebsite.com.key') do its('public_key') { should match "-----BEGIN PUBLIC KEY-----\n3597459df9f3982......" } end ``` ### private_key (String) The `private_key` property returns the private key or the RSA key pair. ``` describe key_rsa('/etc/pki/www.mywebsite.com.key') do its('private_key') { should match "-----BEGIN RSA PRIVATE KEY-----\<KEY>......" } end ``` ### key_length The `key_length` property allows testing the number of bits in the key pair. ``` describe key_rsa('/etc/pki/www.mywebsite.com.key') do its('key_length') { should eq 2048 } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### public? To verify if a key is public use the following: ``` describe key_rsa('/etc/pki/www.mywebsite.com.key') do it { should be_public } end ``` ### private? This property verifies that the key includes a private key: ``` describe key_rsa('/etc/pki/www.mywebsite.com.key') do it { should be_private } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/key_rsa/kernel_module resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/kernel_module.md) Use the `kernel_module` Chef InSpec audit resource to test kernel modules on Linux platforms. These parameters are located under `/lib/modules`. Any submodule may be tested using this resource. The `kernel_module` resource can also verify if a kernel module is `blacklisted` or if a module is disabled via a fake install using the `bin_true` or `bin_false` method. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `kernel_module` resource block declares a module name, and then tests if that module is a loaded kernel module, if it is enabled, disabled or if it is blacklisted: ``` describe kernel_module('module_name') do it { should be_loaded } it { should_not be_disabled } it { should_not be_blacklisted } end ``` where * `'module_name'` must specify a kernel module, such as `'bridge'` * `{ should be_loaded }` tests if the module is a loaded kernel module * `{ should be_blacklisted }` tests if the module is blacklisted or if the module is disabled via a fake install using /bin/false or /bin/true * `{ should be_disabled }` tests if the module is disabled via a fake install using /bin/false or /bin/true Examples -------- The following examples show how to use this Chef InSpec audit resource. ### version The `version` property tests if the kernel module on the system has the correct version: ``` its('version') { should eq '3.2.2' } ``` ### Test a kernel module’s ‘version’ ``` describe kernel_module('bridge') do it { should be_loaded } its('version') { should cmp >= '2.2.2' } end ``` ### Test if a kernel module is loaded, not disabled, and not blacklisted ``` describe kernel_module('video') do it { should be_loaded } it { should_not be_disabled } it { should_not be_blacklisted } end ``` ### Check if a kernel module is blacklisted ``` describe kernel_module('floppy') do it { should be_blacklisted } end ``` ### Check if a kernel module is *not* blacklisted and is loaded ``` describe kernel_module('video') do it { should_not be_blacklisted } it { should be_loaded } end ``` ### Check if a kernel module is disabled via ‘bin_false’ ``` describe kernel_module('sstfb') do it { should_not be_loaded } it { should be_disabled } end ``` ### Check if a kernel module is ‘blacklisted’/‘disabled’ via ‘bin_true’ ``` describe kernel_module('nvidiafb') do it { should_not be_loaded } it { should be_blacklisted } end ``` ### Check if a kernel module is not loaded ``` describe kernel_module('dhcp') do it { should_not be_loaded } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_blacklisted The `be_blacklisted` matcher tests if the kernel module is a blacklisted module: ``` it { should be_blacklisted } ``` ### be_disabled The `be_disabled` matcher tests if the kernel module is disabled: ``` it { should be_disabled } ``` ### be_loaded The `be_loaded` matcher tests if the kernel module is loaded: ``` it { should be_loaded } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/kernel_module/mongodb_conf resource ====================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/mongodb_conf.md) Use the `mongodb_conf` Chef InSpec audit resource to test the contents of the configuration file for MongoDB, typically located at `/etc/mongod.conf` or `C:\Program Files\MongoDB\Server\<version>\bin\mongod.cfg`, depending on the platform. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. Syntax ------ A `mongodb_conf` resource block declares one (or more) settings in the `mongodb.conf` file, and then compares the setting in the configuration file to the value stated in the test: ``` describe mongodb_conf('path') do its('setting') { should eq 'value' } end ``` where * `'setting'` specifies a setting in the `mongodb.conf` file * `('path')` is the non-default path to the `mongodb.conf` file (optional) * `should eq 'value'` is the value that is expected Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the key management configuration options ``` describe mongodb_conf do its(["security", "enableEncryption"]) { should eq true } end ``` ### Test the port on which MongoDB listens ``` describe mongodb_conf do its(["net", "port"]) { should eq 27017 } end ``` ### Test the security configuration options ``` describe mongodb_conf do its(["security", "authorization"]) { should eq "enabled" } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/mongodb_conf/mssql_session resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/mssql_session.md) Use the `mssql_session` Chef InSpec audit resource to test SQL commands run against a Microsoft SQL database. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.24.0 of InSpec. Syntax ------ A `mssql_session` resource block declares the username and password to use for the session, and then the command to be run: ``` describe mssql_session(user: 'username', password: 'password').query('QUERY').row(0).column('result') do its('value') { should eq('') } end ``` where * `mssql_session` declares a username and password with permission to run the query. Omitting the username or password parameters results in the use of Windows authentication as the user Chef InSpec is executing as. You may also optionally pass a host and instance name. If omitted, they will default to host: localhost and the default instance. * `query('QUERY')` contains the query to be run * `its('value') { should eq('') }` compares the results of the query against the expected result in the test Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test for matching databases ``` sql = mssql_session(user: 'my_user', password: 'password') describe sql.query("SELECT SERVERPROPERTY('ProductVersion') as result").row(0).column('result') do its("value") { should cmp > '12.00.4457' } end ``` ### Test using Windows authentication ``` sql = mssql_session describe sql.query("SELECT SERVERPROPERTY('ProductVersion') as result").row(0).column('result') do its("value") { should cmp > '12.00.4457' } end ``` ### Test a specific host and instance ``` sql = mssql_session(user: 'my_user', password: 'password', host: 'mssqlserver', instance: 'foo') describe sql.query("SELECT SERVERPROPERTY('ProductVersion') as result").row(0).column('result') do its("value") { should cmp > '12.00.4457' } end ``` ### Test a specific database ``` sql = mssql_session(user: 'my_user', password: 'password', db_name: 'test') describe sql.query("SELECT Name AS result FROM Product WHERE ProductID == 1").row(0).column('result') do its("value") { should eq 'foo' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/mssql_session/limits_conf resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/limits_conf.md) Use the `limits_conf` Chef InSpec audit resource to test configuration settings in the `/etc/security/limits.conf` file. The `limits.conf` defines limits for processes (by user and/or group names) and helps ensure that the system running those processes remains stable. Each process may be assigned a hard or soft limit. * Soft limits are maintained by the shell and defines the number of file handles (or open files) available to the user or group after login * Hard limits are maintained by the kernel and defines the maximum number of allowed file handles Entries in the `limits.conf` file are similar to: ``` grantmc soft nofile 4096 grantmc hard nofile 63536 ^^^^^^^^^ ^^^^ ^^^^^^ ^^^^^ domain type item value ``` Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `limits_conf` resource block declares a domain to be tested, along with associated type, item, and value: ``` describe limits_conf('path') do its('domain') { should include ['type', 'item', 'value'] } its('domain') { should eq ['type', 'item', 'value'] } end ``` where * `('path')` is the non-default path to the `inetd.conf` file * `'domain'` is a user or group name, such as `grantmc` * `'type'` is either `hard` or `soft` * `'item'` is the item for which limits are defined, such as `core`, `nofile`, `stack`, `nproc`, `priority`, or `maxlogins` * `'value'` is the value associated with the `item` Properties ---------- ### domain The `domain` property tests the domain in the `limits.conf` file, along with associated type, item, and value: ``` its('domain') { should include ['type', 'item', 'value'] } ``` For example: ``` its('grantmc') { should include ['hard', 'nofile', '63536'] } ``` ### Test limits ``` describe limits_conf('path') do its('*') { should include ['soft', 'core', '0'], ['hard', 'rss', '10000'] } its('ftp') { should eq ['hard', 'nproc', '0'] } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/limits_conf/login_defs resource ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/login_defs.md) Use the `login_defs` Chef InSpec audit resource to test configuration settings in the `/etc/login.defs` file. The `logins.defs` file defines site-specific configuration for the shadow password suite on Linux and Unix platforms, such as password expiration ranges, minimum/maximum values for automatic selection of user and group identifiers, or the method with which passwords are encrypted. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `login_defs` resource block declares the `login.defs` configuration data to be tested: ``` describe login_defs do its('name') { should include('foo') } end ``` where * `name` is a configuration setting in `login.defs` * `{ should include('foo') }` tests the value of `name` as read from `login.defs` versus the value declared in the test Properties ---------- This resource supports the properties found in the `login.defs` configuration settings. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### name The `name` matcher tests the value of `name` as read from `login.defs` versus the value declared in the test: ``` its('name') { should eq 'foo' } ``` ### Test password expiration settings ``` describe login_defs do its('PASS_MAX_DAYS') { should eq '180' } its('PASS_MIN_DAYS') { should eq '1' } its('PASS_MIN_LEN') { should eq '15' } its('PASS_WARN_AGE') { should eq '30' } end ``` ### Test the encryption method ``` describe login_defs do its('ENCRYPT_METHOD') { should eq 'SHA512' } end ``` ### Test umask setting ``` describe login_defs do its('UMASK') { should eq '077' } its('PASS_MAX_DAYS') { should eq '90' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/login_defs/kernel_parameter resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/kernel_parameter.md) Use the `kernel_parameter` Chef InSpec audit resource to test kernel parameters on Linux platforms. These parameters are located under `/proc/cmdline`. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `kernel_parameter` resource block declares a parameter and then a value to be tested: ``` describe kernel_parameter('path.to.parameter') do its('value') { should eq 0 } end ``` where * `'kernel.parameter'` must specify a kernel parameter, such as `'net.ipv4.conf.all.forwarding'` * `{ should eq 0 }` states the value to be tested Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if global forwarding is enabled for an IPv4 address ``` describe kernel_parameter('net.ipv4.conf.all.forwarding') do its('value') { should eq 1 } end ``` ### Test if global forwarding is disabled for an IPv6 address ``` describe kernel_parameter('net.ipv6.conf.all.forwarding') do its('value') { should eq 0 } end ``` ### Test if an IPv6 address accepts redirects ``` describe kernel_parameter('net.ipv6.conf.interface.accept_redirects') do its('value') { should cmp 'true' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/kernel_parameter/mongodb_session resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/mongodb_session.md) Use the `mongodb_session` Chef InSpec audit resource to run MongoDB command against a MongoDB Database. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. Syntax ------ A `mongodb_session` resource block declares the `user`, `password`, and `database` to use for the session and then the command to be run: describe mongodb_session(user: “username”, password: “password”, database: “test”).query(key: value) do its(“params”) { should match(/expected-result/) } end where * `mongodb_session` declares a user, password, and database, connecting locally, with permission to run the query. * `query` contains the query to be run. * `its("params") { should eq(/expected-result/) }` compares the results of the query against the expected result in the test ### Optional Parameters The `mongodb_session` InSpec resource accepts `user`, `password`, `host`, `port`, `auth_source`, `auth_mech`, `ssl`, `ssl_cert`, `ssl_ca_cert`, and `auth_mech_properties` parameters. In Particular: #### `host` The server host IP address. Default value: `127.0.0.1`. #### `port` The server port. Default value: `27017`. #### `auth_mech` The authentication mechanism. The available options are: `:scram`, `:scram256`, `:mongodb_x509`, and `:aws`. Default value: `:scram`. See the MongoDB documentation on [Ruby driver authentication](https://docs.mongodb.com/ruby-driver/current/reference/authentication/) for more information. #### `auth_source` The database where the user’s authentication credentials are stored. The default value is the database name that is passed as a parameter to the resource. #### `ssl` Whether to use the SSL security protocol or not. Set to `true` to use SSL transport, default value: `false`. See the MongoDB documentation on [Ruby Driver authentication](https://docs.mongodb.com/ruby-driver/current/reference/authentication/#client-certificate-x-509) for more information. #### ‘ssl_cert’ Path to the SSL certificate file. #### `ssl_ca_cert` Path to the SSL Certificate Authority (CA) certificate file. #### `ssl_key` Path to SSL key file. #### `auth_mech_properties` A hash of the authentication mechanism properties. This option is generally used with the AWS authentication mechanism. See the MongoDB documentation on [Ruby Driver authentication using AWS](https://docs.mongodb.com/ruby-driver/current/reference/authentication/#aws) for more information. ### MongoDB Query Reference Documentation This resource uses the [MongoDB Ruby Driver](https://docs.mongodb.com/ruby-driver/current/reference/authentication/) to fetch the data. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the roles information using the `rolesInfo` command in MongoDB ``` describe mongodb_session(user: "foo", password: "bar", database: "test").query(rolesInfo: "dbAdmin").params["roles"].first do its(["role"]) { should eq "dbAdmin" } end ``` ### Test the MongoDB user role ``` describe mongodb_session(user: "foo", password: "bar", database: "test").query(usersInfo: "foo").params["users"].first["roles"].first do its(["role"]) { should eq "readWrite" } end ``` ### Test the database parameters ``` describe mongodb_session(user: "foo", password: "bar", database: "test").query(rolesInfo: "dbAdmin") do its("params") { should_not be_empty } its("params") { should include "roles" } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### params The `params` contains all the query data. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/mongodb_session/mount resource ============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/mount.md) Use the `mount` Chef InSpec audit resource to test the mount points on FreeBSD and Linux systems. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `mount` resource block declares the synchronization settings that should be tested: ``` describe mount('path') do it { should MATCHER 'value' } end ``` where * `('path')` is the path to the mounted directory * `MATCHER` is a valid matcher for this resource * `'value'` is the value to be tested Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test a the mount point on ‘/’ ``` describe mount('/') do it { should be_mounted } its('device') { should eq '/dev/mapper/VolGroup-lv_root' } its('type') { should eq 'ext4' } its('options') { should eq ['rw', 'mode=620'] } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_mounted The `be_mounted` matcher tests if the file is accessible from the file system: ``` it { should be_mounted } ``` ### device The `device` matcher tests the device from the `fstab` table: ``` its('device') { should eq '/dev/mapper/VolGroup-lv_root' } ``` ### options The `options` matcher tests the mount options for the file system from the `fstab` table: ``` its('options') { should eq ['rw', 'mode=620'] } ``` ### type The `type` matcher tests the file system type: ``` its('type') { should eq 'ext4' } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/mount/mssql_sys_conf resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/mssql_sys_conf.md) Use the `mssql_sys_conf` Chef InSpec audit resource to test the configuration of a Microsoft SQL Server database. Installation ------------ This resource is distributed along with Chef InSpec itself. You can use it automatically. Requirements ------------ You must have database access. Syntax ------ A `mssql_sys_conf` resource block declares the configuration item, user, and password to test. ``` describe mssql_sys_conf("CONFIGURATION ITEM TO TEST", user: 'USER', password: 'PASSWORD') do its("value_in_use") { should cmp "EXPECTED_VALUE" } its("value_configured") { should cmp "EXPECTED_VALUE" } end ``` where: * `mssql_sys_conf` declares a configuration item, `user`, and `password` with permission to use `sys.configurations`. * `its('value_in_use') { should cmp 'EXPECTED_VALUE' }` compares the current running value of the configuration item against an expected value. * `its('value_configured') { should cmp 'EXPECTED_VALUE' }` compares the saved value of the configuration item against an expected value. ### Optional Parameters `mssql_sys_conf` is based on the `mssql_session` resource and accepts all the parameters that `mssql_session` accepts. #### `username` The user name. Default value: `SA`. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test parameters set within the database view ``` describe mssql_sys_conf("clr_enabled", user: 'USER', password: 'PASSWORD') do its("value_in_use") { should cmp "0" } its("value_configured") { should cmp "0" } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/mssql_sys_conf/nginx resource ============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/nginx.md) Use the `nginx` Chef InSpec audit resource to test the fields and validity of nginx. Nginx resource extracts and exposes data reported by the command ‘nginx -V’ Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.37.6 of InSpec. Syntax ------ An `nginx` Chef InSpec audit resource block extracts configuration settings that should be tested: ``` describe nginx do its('attribute') { should eq 'value' } end describe nginx('path to nginx') do its('attribute') { should eq 'value' } end ``` where * `'attribute'` is a configuration parsed from result of the command ‘nginx -V’ * `'value'` is the value that is expected of the attribute Properties ---------- * `compiler_info`, `error_log_path`, `http_client_body_temp_path`, `http_fastcgi_temp_path`, `http_log_path`, `http_proxy_temp_path`, `http_scgi_temp_path`, `http_uwsgi_temp_path`, `lock_path`, `modules`, `modules_path`, `openssl_version`, `prefix`, `sbin_path`, `service`, `support_info`, `version` Property Examples ----------------- ### version(String) `version` returns a string of the version of the running nginx instance ``` describe nginx do its('version') { should eq '1.12.0' } end ``` ### modules(String) `modules` returns a array modules in the running nginx instance ``` describe nginx do its('modules') { should include 'my_module' } end ``` ### openssl_version(Hash) `openssl_version` returns a hash with ‘version’ and ‘date’ as keys ``` describe nginx do its('openssl_version.date') { should eq '11 Feb 2013' } end ``` ### compiler_info(Hash) `compiler_info` returns a hash with ‘compiler’ , version' and ‘date’ as keys ``` describe nginx do its('compiler_info.compiler') { should eq 'gcc' } end ``` ### support_info(String) `support_info` returns a string containing supported protocols ``` describe nginx do its('support_info') { should match /TLS/ } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/nginx/mysql_session resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/mysql_session.md) Use the `mysql_session` Chef InSpec audit resource to test SQL commands run against a MySQL database. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `mysql_session` resource block declares the username and password to use for the session, and then the command to be run: ``` describe mysql_session('username', 'password').query('QUERY') do its('output') { should match(/expected-result/) } end ``` where * `mysql_session` declares a username and password, connecting locally, with permission to run the query * `query('QUERY')` contains the query to be run * `its('output') { should eq(/expected-result/) }` compares the results of the query against the expected result in the test Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test for matching databases ``` sql = mysql_session('my_user','password') describe sql.query('show databases like \'test\';') do its('output') { should_not match(/test/) } end ``` ### Alternate Connection: Different Host ``` sql = mysql_session('my_user','password','db.example.com') ``` ### Alternate Connection: Different Port ``` sql = mysql_session('my_user','password','localhost',3307) ``` ### Alternate Connection: Using a socket ``` sql = mysql_session('my_user','password', nil, nil, '/var/lib/mysql-default/mysqld.sock') ``` ### Test for a successful query ``` describe mysql_session('my_user','password').query('show tables in existing_database;') do its('exit_status') { should eq(0) } end ``` ### Test for a failing query ``` describe mysql_session('my_user','password').query('show tables in non_existent_database;') do its('exit_status') { should_not eq(0) } end ``` ### Test for specific error message ``` describe mysql_session('my_user','password').query('show tables in non_existent_database;') do its('stderr') { should match(/Unknown database/) } end ``` Matchers -------- This Chef InSpec audit resource builds a [command](../command) object and returns the the result object. For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/mysql_session/mysql_conf resource ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/mysql_conf.md) Use the `mysql_conf` Chef InSpec audit resource to test the contents of the configuration file for MySQL, typically located at `/etc/mysql/my.cnf` or `/etc/my.cnf`. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `mysql_conf` resource block declares one (or more) settings in the `my.cnf` file, and then compares the setting in the configuration file to the value stated in the test: ``` describe mysql_conf('path') do its('setting') { should eq 'value' } end # Test a parameter set within the [mysqld] section describe mysql_conf do its('mysqld.port') { should cmp 3306 } end # Test a parameter set within the [mariadb] section using array notation describe mysql_conf do its(['mariadb', 'max-connections']) { should_not be_nil } end ``` where * `'setting'` specifies a setting in the `my.cnf` file, such as `max_connections` + when checking a setting within sections, such as `[mysqld]`, the section name must be included * `('path')` is the non-default path to the `my.cnf` file * `should eq 'value'` is the value that is expected Properties ---------- This resource supports any settings listed in a `my.cnf` file as properties. For example, `max_connections`. ``` its('max_connections') { should eq '505' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the maximum number of allowed connections ``` describe mysql_conf do its('max_connections') { should eq '505' } its('max_user_connections') { should eq '500' } end ``` ### Test slow query logging** ``` describe mysql_conf do its('slow_query_log_file') { should eq 'hostname_slow.log' } its('slow_query_log') { should eq '0' } its('log_queries_not_using_indexes') { should eq '1' } its('long_query_time') { should eq '0.5' } its('min_examined_row_limit') { should eq '100' } end ``` ### Test the port and socket on which MySQL listens ``` describe mysql_conf do its('port') { should eq '3306' } its('socket') { should eq '/var/run/mysqld/mysql.sock' } end ``` ### Test connection and thread variables ``` describe mysql_conf do its('port') { should eq '3306' } its('socket') { should eq '/var/run/mysqld/mysql.sock' } its('max_allowed_packet') { should eq '12M' } its('default_storage_engine') { should eq 'InnoDB' } its('character_set_server') { should eq 'utf8' } its('collation_server') { should eq 'utf8_general_ci' } its('max_connections') { should eq '505' } its('max_user_connections') { should eq '500' } its('thread_cache_size') { should eq '505' } end ``` ### Test the safe-user-create parameter ``` describe mysql_conf.params('mysqld') do its('safe-user-create') { should eq('1') } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/mysql_conf/npm resource ============ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/npm.md) Use the `npm` Chef InSpec audit resource to test if a global NPM package is installed. NPM is the the package manager for [Node.js packages](https://docs.npmjs.com), such as Bower and StatsD. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `npm` resource block declares a package and (optionally) a package version: ``` describe npm('npm_package_name') do it { should be_installed } end ``` where * `('npm_package_name')` must specify an NPM package, such as `'bower'` or `'statsd'` * `be_installed` is a valid matcher for this resource You can also specify additional options: ``` describe npm('npm_package_name', path: '/path/to/project') do it { should be_installed } end ``` The `path` specifies a folder, that contains a `node_modules` subdirectory. It emulates running `npm` inside the specified folder. This way you can inspect local NPM installations as well as global ones. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Verify that bower is installed, with a specific version ``` describe npm('bower') do it { should be_installed } its('version') { should eq '1.4.1' } end ``` ### Verify that statsd is not installed ``` describe npm('statsd') do it { should_not be_installed } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_installed The `be_installed` matcher tests if the named Gem package and package version (if specified) is installed: ``` it { should be_installed } ``` ### version The `version` matcher tests if the named package version is on the system: ``` its('version') { should eq '1.2.3' } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/npm/nginx_conf resource ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/nginx_conf.md) Use the `nginx_conf` Chef InSpec resource to test configuration data for the NGINX server located at `/etc/nginx/nginx.conf` on Linux and Unix platforms. **Stability: Experimental** Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.37.6 of InSpec. Syntax ------ An `nginx_conf` resource block declares the client NGINX configuration data to be tested: ``` describe nginx_conf.params['pid'].flatten do it { should cmp 'logs/nginx.pid' } end ``` where * `nginx_conf` is the resource to reference your NGINX configuration * `params` accesses all its parameters * `params['pid']` selects the `pid` entry from the global NGINX configuration * `{ should cmp 'logs/nginx.pid' }` tests if the PID is set to `logs/nginx.pid` (via `cmp` matcher) Parameters can be accessed either via `params` or via the `its` syntax: ``` describe nginx_conf do its('pid') { should cmp 'logs/nginx.pid' } end ``` The `its` syntax allows for a more descriptive block and is available in the `nginx_conf`, `nginx_conf.http.entries`, and `nginx_conf.http.servers` resources. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Find a specific server ``` servers = nginx_conf.servers domain2 = servers.find { |s| s.params['server_name'].flatten.include? 'domain2.com' } describe 'No server serves domain2' do subject { domain2 } it { should be_nil } end ``` ### Test a raw parameter ``` describe nginx_conf.params['worker_processes'].flatten do it { should cmp 5 } end # Or when using `its` syntax describe nginx_conf do its('worker_processes') { should cmp 5 } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### http Retrieves all `http` entries in the configuration file. ``` nginx_conf.http => nginx_conf /etc/nginx/nginx.conf, http entries ``` It provides further access to all individual entries, servers, and locations. ``` nginx_conf.http.entries => [nginx_conf /etc/nginx/nginx.conf, http entry ...] nginx_conf.http.servers => [nginx_conf /etc/nginx/nginx.conf, server entry ...] nginx_conf.http.locations => [nginx_conf /etc/nginx/nginx.conf, location entry ...] ``` You can access each of these from the array and inspect it further (see below). ### servers Retrieve all `servers` entries in the configuration: ``` # all servers across all configs aggregated: nginx_conf.servers => [nginx_conf /etc/nginx/nginx.conf, server entry ...] # servers that belong to a specific http entry: nginx_conf.http.entries[0].servers => [nginx_conf /etc/nginx/nginx.conf, server entry ...] ``` Servers provide access to all their locations, parent http entry, and raw parameters: ``` server = nginx_conf.servers[0] server.locations => [nginx_conf /etc/nginx/nginx.conf, location entry ...] server.parent => nginx_conf /etc/nginx/nginx.conf, http entry server.params => {"listen"=>[["85"]], "server_name"=>[["domain1.com", "www.domain1.com"]], "root"=>[["html"]], "location"=>[{"_"=>["~", "\\.php$"], "fastcgi_pass"=>[["127.0.0.1:1025"]]}]} ``` ### locations Retrieve all `location` entries in the configuration: ``` # all locations across all configs aggregated: nginx_conf.locations => [nginx_conf /etc/nginx/nginx.conf, location entry ...] # locations of a http entry aggregated: nginx_conf.http.entries[0].locations => [nginx_conf /etc/nginx/nginx.conf, location entry ...] # locations of a specific server: nginx_conf.servers[0].locations => [nginx_conf /etc/nginx/nginx.conf, location entry ...] ``` Locations provide access to their parent server entry and raw parameters: ``` location = nginx_conf.locations[0] location.parent => nginx_conf /etc/nginx/nginx.conf, server entry location.params => {"_"=>["~", "\\.php$"], "fastcgi_pass"=>[["127.0.0.1:1025"]]} ``` ### configuration file path If the NGINX configuration file is not located at the default path, `/etc/nginx/nginx.conf`, the path can specified as the first parameter of the describe block: ``` describe nginx_conf('/opt/nginx/nginx.conf').params['pid'] do it { should cmp 'logs/nginx.pid' } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/nginx_conf/oracledb_conf resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/oracledb_conf.md) Use the `oracledb_conf` Chef InSpec audit resource to test the Oracle system parameters. Installation ------------ This resource is distributed along with Chef InSpec itself. You can use it automatically. Requirements ------------ You must have access to a database user with `DBA` role. Syntax ------ A `oracledb_conf` resource block declares user and password to use. It fetches system parameters which are defined in the `V$SYSTEM_PARAMETER` database view, and then compares those parameters to the values stated in the test: ``` describe oracledb_conf(user: 'USER', password: 'PASSWORD') do its("config item") { should cmp "value" } end ``` ### Optional Parameters `oracledb_conf` is based on `oracledb_session`, and accepts all parameters that `oracledb_session` accepts. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test parameters set within the database view ``` describe oracledb_conf(user: 'USER', password: 'PASSWORD') do its("audit_sys_operations") { should cmp "true" } its("sql92_security") { should cmp "true" } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/oracledb_conf/ntp_conf resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/ntp_conf.md) Use the `ntp_conf` Chef InSpec audit resource to test the synchronization settings defined in the `ntp.conf` file. This file is typically located at `/etc/ntp.conf`. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `ntp_conf` resource block declares the synchronization settings that should be tested: ``` describe ntp_conf('path') do its('setting_name') { should eq 'value' } end ``` where * `'setting_name'` is a synchronization setting defined in the `ntp.conf` file * `('path')` is the non-default path to the `ntp.conf` file * `{ should eq 'value' }` is the value that is expected Properties ---------- This resource supports any of the settings listed in an `ntp.conf` file as properties. Examples -------- The following examples show how to use this Chef InSpec audit resource ``` describe ntp_conf do its('server') { should_not eq nil } its('restrict') { should include '-4 default kod notrap nomodify nopeer noquery'} end ``` ### Test for clock drift against named servers ``` describe ntp_conf do its('driftfile') { should eq '/var/lib/ntp/ntp.drift' } its('server') do should eq [ '0.ubuntu.pool.ntp.org', '1.ubuntu.pool.ntp.org', '2.ubuntu.pool.ntp.org' ] end end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/ntp_conf/oneget resource =============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/oneget.md) Use the `oneget` Chef InSpec audit resource to test if the named package and/or package version is installed on the system. This resource uses Oneget, which is `part of the Windows Management Framework 5.0 and Windows 10 <https://github.com/OneGet/oneget>`. This resource uses the `Get-Package` cmdlet to return all of the package names in the Oneget repository. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `oneget` resource block declares a package and (optionally) a package version: ``` describe oneget('name') do it { should be_installed } end ``` where * `('name')` must specify the name of a package, such as `'VLC'` * `be_installed` is a valid matcher for this resource Properties ---------- ### version The `version` property tests if the named package version is on the system: ``` its('version') { should eq '1.2.3' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if VLC is installed ``` describe oneget('VLC') do it { should be_installed } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_installed The `be_installed` matcher tests if the named package is installed on the system: ``` it { should be_installed } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/oneget/opa_cli resource ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/opa_cli.md) Use the `opa_cli` Chef InSpec audit resource to query Open Policy Agent (OPA) using an OPA policy file, a data file, and a query. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. Syntax ------ An `opa_cli` resource block declares OPA policy configurations that can be tested. ``` describe opa_cli(policy: "example.rego", data: "input.json", query: "data.example.allow") do its(["result"]) { should eq "value" } end ``` where * `data` specifies the json formatted input data or file path. * `policy` the path to policy file. * `query` specifies the query to be run. * `its(["result"]) { should eq "value" }` compares the results of the query against the expected result in the test parameters ---------- The `opa_cli` resource InSpec resource accepts `policy`, `data`, `query`, and `opa_executable_path` as parameters. ### `policy` *(required)* The path to the OPA policy file. ### `data` *(required)* An OPA query as a JSON data file or a string in JSON format. ### `query` *(required)* The query to be evaluated against policy and input data. ### `opa_executable_path` This is the full path to the OPA binary or EXE file used for running the OPA CLI or OPA commands. By default it will consider that the path is added in PATH variable. Properties ---------- ### result The `result` property checks whether the resource query returns an empty result. ``` its('result') { should be nil } ``` ### allow The `allow` property checks if specific input matches the policy defined in OPA. This matcher will not work if `allow` is not defined in the policy file. ``` its('allow') { should eq 'value' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource: ``` describe opa_cli(query: "data.example.allow", policy: "example.rego", data: "input.json", opa_executable_path: "./opa") do its("result") { shoule_not be nil } its(["result", 0, "expressions", 0, "value"]) { should eq true } its("allow") { should eq "true" } end ``` The above example shows how the `allow` value can be fetched in two ways. Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/opa_cli/oracledb_session resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/oracledb_session.md) Use the `oracledb_session` Chef InSpec audit resource to test SQL commands run against a Oracle database. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `oracledb_session` resource block declares the username and password to use for the session with an optional service to connect to, and then the command to be run: ``` describe oracledb_session(user: 'username', password: 'password', service: 'ORCL.localdomain').query('QUERY').row(0).column('result') do its('value') { should eq('') } end ``` where * `oracledb_session` declares a username and password with permission to run the query (required), and an optional parameters for host (default: `localhost`), SID (default: `nil`, which uses the default SID, and path to the sqlplus binary (default: `sqlplus`). * it is possible to run queries as sysdba/sysoper by using `as_db_role option`, see examples * SQLcl can be used in place of sqlplus. Use the `sqlcl_bin` option to set the sqlcl binary path instead of `sqlplus_bin`. * `query('QUERY')` contains the query to be run * `its('value') { should eq('') }` compares the results of the query against the expected result in the test oracledb_session(&mldr;).query method Properties ------------------------------------------------- * rows the query result as array of hashes * row(number) selected row from query result, where number is just a row number in the query result * column(name) array with values from selected column Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test for matching databases ``` sql = oracledb_session(user: 'my_user', pass: 'password') describe sql.query('SELECT NAME AS VALUE FROM v$database;').row(0).column('value') do its('value') { should cmp 'ORCL' } end ``` ### Test for matching databases with custom host, SID and sqlplus binary location ``` sql = oracledb_session(user: 'my_user', pass: 'password', host: 'oraclehost', sid: 'mysid', sqlplus_bin: '/u01/app/oracle/product/12.1.0/dbhome_1/bin/sqlplus') describe sql.query('SELECT NAME FROM v$database;').row(0).column('name') do its('value') { should cmp 'ORCL' } end ``` ### Test for table contains a specified value in any row for the given column name ``` sql = oracledb_session(user: 'my_user', pass: 'password', service: 'MYSID') describe sql.query('SELECT * FROM my_table;').column('my_column') do it { should include 'my_value' } end ``` ### Test tablespace exists as sysdba ``` The check will change user (with su) to specified user and run 'sqlplus / as sysdba' (sysoper, sysasm) sql = oracledb_session(as_os_user: 'oracle', as_db_role: 'sysdba', service: 'MYSID') describe sql.query('SELECT tablespace_name AS name FROM dba_tablespaces;').column('name') do it { should include 'MYTABLESPACE' } end NOTE: option `as_os_user` available only on unix-like systems and not supported on Windows. Also this option requires that you are running inspec as `root` or with `--sudo` ``` ### Test number of rows in the query result ``` sql = oracledb_session(user: 'my_user', pass: 'password') describe sql.query('SELECT * FROM my_table;').rows do its('count') { should eq 20 } end ``` ### Use data out of (remote) DB query to build other tests ``` sql = oracledb_session(user: 'my_user', pass: 'password', host: 'my.remote.db', service: 'MYSID') sql.query('SELECT * FROM files;').rows.each do |file_row| describe file(file_row['path']) do its('owner') { should eq file_row['owner']} end end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/oracledb_session/opa_api resource ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/opa_api.md) Use the `opa_api` Chef InSpec audit resource to query Open Policy Agent (OPA) using the OPA URL and data. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. Syntax ------ An `opa_api` resource block declares OPA policy configurations that can be tested. ``` describe opa_api(url: "localhost:8181/v1/data/example/violation", data: "input.json") do its(["result"]) { should eq 'value' } end ``` where * `'url'` specifies the url of the OPA server on which OPA is running. * `'data'` specifies the json formatted data or json file. * `its(["returned_result"]) { should eq 'expected_result' }` compares the results of the query against the expected result in the test. parameters ---------- The `opa_api` resource InSpec resource requires a `url` and `data` as a JSON file or a string in JSON format. ### `url` *(required)* The URL of the OPA API server. ### `data` *(required)* An OPA query as a JSON data file or a string in JSON format. Properties ---------- ### result The `result` property checks whether the resource query returns an empty result. ``` its('result') { should be nil } ``` ### allow The `allow` property checks if a specific input matches the policy defined in OPA. This matcher will not work if `allow` is not defined in the policy file. ``` its('allow') { should eq 'value' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ``` describe opa_api(url: "localhost:8181/v1/data/example/allow", data: "input.json") do its("result") { shoule_not be nil } its(["result"]) { should eq true } its("allow") { should eq "true" } end ``` The above example shows how the `allow` value can be fetched in two ways. Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/opa_api/os_env resource ================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/os_env.md) Use the `os_env` Chef InSpec audit resource to test the environment variables for the platform on which the system is running. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `os_env` resource block declares an environment variable, and then declares its value: ``` describe os_env('VARIABLE') do its('property') { should eq 1 } end ``` where * `('VARIABLE')` must specify an environment variable, such as `PATH` * `matcher` is a valid matcher for this resource Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the PATH environment variable ``` describe os_env('PATH') do its('split') { should_not include('') } its('split') { should_not include('.') } end ``` ### Test the Path environment variable by specifying the target Environment (Windows) On windows a User’s environment variable may obscure the local machine (system) environment variable. The correct environment variable may be tested as follows: ``` describe os_env('PATH', 'target') do its('split') { should_not include('') } its('split') { should_not include('.') } end ``` where * `'target'` may be either `system` or `user` ### Test Chef Habitat environment variables Chef Habitat uses the `os_env` resource to test environment variables. The environment variables are first defined in a whitespace array, after which each environment variable is tested: ``` hab_env_vars = %w(HAB_AUTH_TOKEN HAB_CACHE_KEY_PATH HAB_DEPOT_URL HAB_ORG HAB_ORIGIN HAB_ORIGIN_KEYS HAB_RING HAB_RING_KEY HAB_STUDIOS_HOME HAB_STUDIO_ROOT HAB_USER) hab_env_vars.each do |e| describe os_env(e) do its('content') { should eq nil } end end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### content The `content` matcher return the value of the environment variable: ``` its('content') { should eq '/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin' } ``` ### split The `split` matcher splits the value of the environment variable with the `:` deliminator (use the `;` deliminator if Windows): ``` its('split') { should include ('/usr/bin') } ``` Note: the `split` matcher returns an array including `""` for cases where there is a trailing colon (`:`), such as `dir1::dir2:` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/os_env/oracledb_listener_conf resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/oracledb_listener_conf.md) Use the `oracledb_listener_conf` Chef InSpec audit resource to test the listeners settings of Oracle DB, typically located at `$ORACLE_HOME/network/admin/listener.ora` or `$ORACLE_HOME\network\admin\listener.ora` depending upon the platform. Installation ------------ This resource is distributed along with Chef InSpec itself. You can use it automatically. Requirements ------------ * You must have sufficient permission to access listener settings defined in `listener.ora` file. * Value for environment variable `ORACLE_HOME` should be set in the system. Syntax ------ A `oracledb_listener_conf` resource block fetches listeners settings in the `listener.ora` file, and then compares them with the value stated in the test: ``` describe oracledb_listener_conf do its('config item') { should eq 'value' } end ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test parameters set within the listener file ``` describe oracledb_listener_conf do its('DEFAULT_SERVICE_LISTENER') { should eq 'XE' } its('EM_EXPRESS_PORT') { should eq '5500' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/oracledb_listener_conf/packages resource ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/packages.md) Use the `packages` Chef InSpec audit resource to test the properties of multiple packages on the system. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.51.15 of InSpec. Syntax ------ A `packages` resource block declares a regular expression search to select packages ``` describe packages(/name/) do its('statuses') { should cmp 'installed' } end ``` Properties ---------- ### statuses The `statuses` property tests if packages are installed on the system: ``` its('statuses') { should cmp 'installed' } ``` ### versions The `versions` property tests the versions of the packages installed on the system ``` its('versions') { should cmp '3.4.0.2-4.el7' } ``` ### architectures The `architectures` property tests the architecture of packages installed on the system ``` its('architectures') { should include 'i686' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Verify that no `xserver` packages are installed ``` describe packages(/xserver/) do its('statuses') { should_not cmp 'installed' } end ``` ### Verify all `openssl` packages match a certain version ``` describe packages(/openssl/) do its('versions') { should cmp '1.0.1e-42.el7' } end ``` ### Verify that both the `i686` and `x86_64` versions of `libgcc` are installed ``` describe packages(/libgcc/) do its('architectures') { should include 'x86_64' } its('architectures') { should include 'i686' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/packages/os resource =========== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/os.md) Use the `os` Chef InSpec audit resource to test the platform on which the system is running. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `os` resource block declares the platform to be tested. The platform may specified via matcher or control block name. For example, using a matcher: ``` describe os.family do it { should eq 'platform_family_name' } end ``` * `'platform_family_name'` (a string) is one of `aix`, `bsd`, `darwin`, `debian`, `hpux`, `linux`, `redhat`, `solaris`, `suse`, `unix`, or `windows` The parameters available to `os` are: * `:name` - the operating system name, such as `centos` * `:family` - the operating system family, such as `redhat` * `:release` - the version of the operating system, such as `7.3.1611` * `:arch` - the architecture of the operating system, such as `x86_64` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test for RedHat ``` describe os.family do it { should eq 'redhat' } end ``` ### Test for Ubuntu ``` describe os.family do it { should eq 'debian' } end ``` ### Test for Microsoft Windows ``` describe os.family do it { should eq 'windows' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### os.family? Helpers The `os` audit resource includes a collection of helpers that enable more granular testing of platforms, platform names, architectures, and releases. Use any of the following platform-specific helpers to test for specific platforms: * `aix?` * `bsd?` (including Darwin, FreeBSD, NetBSD, and OpenBSD) * `darwin?` * `debian?` * `hpux?` * `linux?` (including Alpine Linux, Amazon Linux, ArchLinux, CoreOS, Exherbo, Fedora, Gentoo, and Slackware) * `redhat?` (including CentOS) * `solaris?` (including Nexenta Core, OmniOS, Open Indiana, Solaris Open, and SmartOS) * `suse?` * `unix?` * `windows?` For example, to test for Darwin use: ``` describe os.bsd? do it { should eq true } end ``` To test for Windows use: ``` describe os.windows? do it { should eq true } end ``` and to test for Redhat use: ``` describe os.redhat? do it { should eq true } end ``` Use the following helpers to test for operating system names, releases, and architectures: ``` describe os.name do it { should eq 'foo' } end describe os.release do it { should eq 'foo' } end describe os.arch do it { should eq 'foo' } end ``` ### os.family names Use `os.family` to enable more granular testing of platforms, platform names, architectures, and releases. Use any of the following platform-specific names to test for specific platforms: * `aix` * `bsd` For platforms that are part of the Berkeley OS family `darwin`, `freebsd`, `netbsd`, and `openbsd`. * `debian` * `hpux` * `linux`. For platforms that are part of the Linux family `alpine`, `amazon`, `arch`, `coreos`, `exherbo`, `fedora`, `gentoo`, and `slackware`. * `redhat`. For platforms that are part of the Redhat family `centos`. * `solaris`. For platforms that are part of the Solaris family `nexentacore`, `omnios`, `openindiana`, `opensolaris`, and `smartos`. * `suse` * `unix` * `windows` For example, both of the following tests should have the same result: ``` if os.family == 'debian' describe port(69) do its('processes') { should include 'in.tftpd' } end elsif os.family == 'redhat' describe port(69) do its('processes') { should include 'xinetd' } end end if os.debian? describe port(69) do its('processes') { should include 'in.tftpd' } end elsif os.redhat? describe port(69) do its('processes') { should include 'xinetd' } end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/os/package resource ================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/package.md) Use the `package` Chef InSpec audit resource to test if the named package and/or package version is installed on the system. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `package` resource block declares a package and (optionally) a package version: ``` describe package('name') do it { should be_installed } end ``` where * `('name')` must specify the name of a package, such as `'nginx'` * `be_installed` is a valid matcher for this resource Properties ---------- ### version The `version` property tests if the named package version is on the system: ``` its('version') { should eq '1.2.3' } ``` You can also use the `cmp` matcher to perform comparisons using the version attribute: ``` its('version') { should cmp >= '7.35.0-1ubuntu3.10' } ``` `cmp` understands version numbers using Gem::Version, and can use the operators `==, <, <=, >=, and >`. It will compare versions by each segment, not as a string - so ‘7.4’ is smaller than ‘7.30’, for example. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if NGINX version 1.9.5 is installed ``` describe package('nginx') do it { should be_installed } its('version') { should eq '1.9.5' } end ``` ### Test that a package is not installed ``` describe package('some_package') do it { should_not be_installed } end ``` ### Test that telnet is not installed ``` describe package('telnetd') do it { should_not be_installed } end describe inetd_conf do its('telnet') { should eq nil } end ``` ### Test if ClamAV (an antivirus engine) is installed and running ``` describe package('clamav') do it { should be_installed } its('version') { should eq '0.98.7' } end describe service('clamd') do it { should be_enabled } it { should be_installed } it { should be_running } end ``` ### Verify if a package is installed according to my rpm database ``` describe package('some_package', rpm_dbpath: '/var/lib/my_rpmdb') do it { should be_installed } end ``` ### Verify if Memcached is installed, enabled, and running Memcached is an in-memory key-value store that helps improve the performance of database-driven websites and can be installed, maintained, and tested using the `memcached` cookbook (maintained by Chef). The following example is from the `memcached` cookbook and shows how to use a combination of the `package`, `service`, and `port` Chef InSpec audit resources to test if Memcached is installed, enabled, and running: ``` describe package('memcached') do it { should be_installed } end describe service('memcached') do it { should be_installed } it { should be_enabled } it { should be_running } end describe port(11_211) do it { should be_listening } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_held The `be_held` matcher tests if the named package is “held”. On dpkg platforms, a “held” package will not be upgraded to a later version. ``` it { should be_held } ``` ### be_installed The `be_installed` matcher tests if the named package is installed on the system: ``` it { should be_installed } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/package/parse_config resource ====================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/parse_config.md) Use the `parse_config` Chef InSpec audit resource to test arbitrary configuration files. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `parse_config` resource block declares the location of the configuration setting to be tested, and then what value is to be tested. Because this resource relies on arbitrary configuration files, the test itself is often arbitrary and relies on custom Ruby code: ``` output = command('some-command').stdout describe parse_config(output, { data_config_option: value } ) do its('setting') { should eq 1 } end ``` or: ``` audit = command('/sbin/auditctl -l').stdout options = { assignment_regex: /^\s*([^:]*?)\s*:\s*(.*?)\s*$/, multiple_values: true } describe parse_config(audit, options) do its('setting') { should eq 1 } end ``` where each test * Must declare the location of the configuration file to be tested * Must declare one (or more) settings to be tested * May run a command to `stdout`, and then run the test against that output * May use options to define how configuration data is to be parsed Options ------- This resource supports multiple options to parse configuration data. Use the options in an `options` block stated outside of (and immediately before) the actual test. For example: ``` options = { assignment_regex: /^\s*([^:]*?)\s*:\s*(.*?)\s*$/, multiple_values: true } output = command('some-command').stdout describe parse_config(output, options) do its('setting') { should eq 1 } end ``` ### assignment_regex Use `assignment_regex` to test a key value using a regular expression: ``` 'key = value' ``` may be tested using the following regular expression, which determines assignment from key to value: ``` assignment_regex: /^\s*([^=]*?)\s*=\s*(.*?)\s*$/ ``` ### comment_char Use `comment_char` to test for comments in a configuration file: ``` comment_char: '#' ``` ### key_values Use `key_values` to test how many values a key contains: ``` key = a b c ``` contains three values. To test that value to ensure it only contains one, use: ``` key_values: 1 ``` ### multiple_values Use `multiple_values` if the source file uses the same key multiple times. All values will be aggregated in an array: ``` # # file structure: # key = a # key = b # key2 = c params['key'] = ['a', 'b'] params['key2'] = ['c'] ``` To use plain key value mapping, use `multiple_values: false`: ``` # # file structure: # key = a # key = b # key2 = c params['key'] = 'b' params['key2'] = 'c' ``` ### standalone_comments Use `standalone_comments` to parse comments as a line, otherwise inline comments are allowed: ``` 'key = value # comment' params['key'] = 'value # comment' ``` Use `standalone_comments: false`, to parse the following: ``` 'key = value # comment' params['key'] = 'value' ``` Examples -------- This resource is based on the `parse_config_file` resource. See the [`parse_config_file`](../parse_config_file) resource for examples. Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/parse_config/port resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/port.md) Use the `port` Chef InSpec audit resource to test basic port properties, such as port, process, if it’s listening. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `port` resource block declares a port, and then depending on what needs to be tested, a process, protocol, process identifier, and its state (is it listening?): ``` describe port(514) do it { should be_listening } its('processes') {should include 'syslog'} end ``` where the `processes` returns the processes listening on port 514. A filter may specify an attribute: ``` describe port.where { protocol =~ /tcp/ && port > 22 && port < 80 } do it { should_not be_listening } end ``` where * `.where{}` specifies a block in which one (or more) attributes—`port`, `address`, `protocol`, `process`, `pid`, or `listening?`—-scope the test to ports that match those attributes For example, to test if the SSH daemon is available on a Linux machine via the default port (22): ``` describe port(22) do its('processes') { should include 'sshd' } its('protocols') { should include 'tcp' } its('addresses') { should include '0.0.0.0' } end ``` Properties ---------- ### address The `addresses` property tests if the specified address is associated with a port: ``` its('addresses') { should include '0.0.0.0' } ``` ### be_listening The `be_listening` property tests if the port is listening for traffic: ``` it { should be_listening } ``` ### pids The `pids` property tests the process identifiers (PIDs): ``` its('pids') { should cmp 27808 } ``` ### processes The `processes` property tests if the named process is running on the system: ``` its('processes') { should cmp 'syslog' } ``` ### protocols The `protocols` property tests the Internet protocol: ICMP (`'icmp'`), TCP (`'tcp'` or `'tcp6'`), or UDP (`'udp'` or `'udp6'`): ``` its('protocols') { should include 'tcp' } ``` or for the IPv6 protocol: ``` its('protocols') { should include 'tcp6' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test port 80, listening with the TCP protocol ``` describe port(80) do it { should be_listening } its('protocols') { should cmp 'tcp' } end ``` ### Test port 80, on a specific address A specific port address may be checked using either of the following examples: ``` describe port(80) do it { should be_listening } its('addresses') {should include '0.0.0.0'} end ``` or: ``` describe port('0.0.0.0', 80) do it { should be_listening } end ``` ### Test port 80, listening with TCP version IPv6 protocol ``` describe port(80) do it { should be_listening } its('protocols') { should cmp 'tcp6' } end ``` ### Test that only secure ports accept requests ``` describe port(80) do it { should_not be_listening } end describe port(443) do it { should be_listening } its('protocols') { should cmp 'tcp' } end ``` ### Verify port 65432 is not listening ``` describe port(22) do it { should be_listening } its('protocols') { should include('tcp') } its('protocols') { should_not include('udp') } end describe port(65432) do it { should_not be_listening } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/port/passwd resource =============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/passwd.md) Use the `passwd` Chef InSpec audit resource to test the contents of `/etc/passwd`, which contains the following information for users that may log into the system and/or as users that own running processes. The format for `/etc/passwd` includes: * A username * The password for that user (on newer systems passwords should be stored in `/etc/shadow` ) * The user identifier (UID) assigned to that user * The group identifier (GID) assigned to that user * Additional information about that user * That user’s home directory * That user’s default command shell These entries are defined as a colon-delimited row in the file, one row per user: ``` root:x:1234:5678:additional_info:/home/dir/:/bin/bash ``` Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `passwd` resource block declares one (or more) users and associated user information to be tested: ``` describe passwd do its('users') { should_not include 'forbidden_user' } end describe passwd.uids(filter) do its('users') { should cmp 'root' } its('count') { should eq 1 } end ``` where * `homes`, `gids`, `passwords`, `shells`, `uids`, and `users` are valid accessors for `passwd` * `filter` one (or more) arguments, for example: `passwd.users(/name/)` used to define filtering * `filter` may take any of the following arguments: `count` (retrieves the number of entries), `lines` (provides raw `passwd` lines), and `params` (returns an array of maps for all entries) Properties ---------- ### gids The `gids` property tests if the group indentifiers in the test match group identifiers in `/etc/passwd`: ``` its('gids') { should include 1234 } its('gids') { should cmp 0 } ``` ### homes The `homes` property tests the absolute path to a user’s home directory: ``` its('home') { should eq '/' } ``` ### length The `length` property tests the length of a password that appears in `/etc/passwd`: ``` its('length') { should be <= 32 } ``` This matcher is best used in conjunction with filters. For example: ``` describe passwd.users('highlander') do its('length') { should_not be < 16 } end ``` ### passwords The `passwords` property tests if passwords are * Encrypted * Have direct logins disabled, as indicated by an asterisk (`*`) * In the `/etc/shadow` file, as indicated by the letter x (`x`) For example: ``` its('passwords') { should eq ['x'] } its('passwords') { should cmp '*' } ``` ### shells The `shells` property tests the absolute path of a shell (or command) to which a user has access: ``` its('shells') { should_not include 'user' } ``` or to find all users with the nologin shell: ``` describe passwd.shells(/nologin/) do its('users') { should_not include 'my_login_user' } end ``` ### uids The `uids` property tests if the user identifiers in the test match user identifiers in `/etc/passwd`: ``` its('uids') { should eq ['1234', '1235'] } ``` or: ``` describe passwd.uids(0) do its('users') { should cmp 'root' } its('count') { should eq 1 } end ``` ### users The `users` property tests if the user names in the test match user names in `/etc/passwd`: ``` its('users') { should eq ['root', 'www-data'] } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test usernames and UIDs ``` describe passwd do its('users') { should eq ['root', 'www-data'] } its('uids') { should eq [0, 33] } end ``` ### Select one user and test for multiple occurrences ``` describe passwd.uids(0) do its('users') { should cmp 'root' } its('count') { should eq 1 } end describe passwd.where { user == 'www-data' } do its('uids') { should cmp 33 } its('count') { should eq 1 } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/passwd/pip resource ============ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/pip.md) Use the `pip` Chef InSpec audit resource to test packages that are installed using the Python PIP installer. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `pip` resource block declares a package and (optionally) a package version: ``` describe pip('package_name') do it { should be_installed } end ``` where * `'package_name'` is the name of the package, such as `'Jinja2'` * `be_installed` tests to see if the package described above is installed Properties ---------- ### version The `version` property tests if the named package version is on the system: ``` its('version') { should eq '1.2.3' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if Jinja2 is installed on the system ``` describe pip('Jinja2') do it { should be_installed } end ``` ### Test if Jinja2 2.8 is installed on the system ``` describe pip('Jinja2') do it { should be_installed } its('version') { should eq '2.8' } end ``` ### Test packages installed into a non-default location (e.g. virtualenv) by passing a custom path to pip executable ``` describe pip('Jinja2', '/path/to/bin/pip') do it { should be_installed } its('version') { should eq '2.8' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_installed The `be_installed` matcher tests if the named package is installed on the system: ``` it { should be_installed } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/pip/parse_config_file resource ============================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/parse_config_file.md) Use the `parse_config_file` Chef InSpec audit resource to test arbitrary configuration files. It works in the same way as `parse_config`. Instead of using a command output, this resource works with files. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `parse_config_file` Chef InSpec audit resource block declares the location of the configuration file to be tested, and then which settings in that file are to be tested. ``` describe parse_config_file('/path/to/file', { data_config_option: value } ) do its('setting') { should eq 1 } end ``` or: ``` options = { assignment_regex: /^\s*([^:]*?)\s*:\s*(.*?)\s*$/, multiple_values: true } describe parse_config_file('path/to/file', options) do its('setting') { should eq 1 } end ``` where each test * Must declare the location of the configuration file to be tested * Must declare one (or more) settings to be tested * May run a command to `stdout`, and then run the test against that output * May use options to define how configuration data is to be parsed ### Option Names Containing Periods A possible behavior may occur when attempting to access option names containing periods with `its()`. There are two ways to work around it: * Access the option by using the `params` attribute of the returned resource object * Since 4.24.5, `its` can be used by passing the option name in a single-element array. See the `parse config file` examples. Options ------- This resource supports multiple options to parse configuration data. Use the options in an `options` block stated outside of (and immediately before) the actual test. For example: ``` options = { assignment_regex: /^\s*([^:]*?)\s*:\s*(.*?)\s*$/, multiple_values: true } describe parse_config_file('path/to/file', options) do its('setting') { should eq 1 } end ``` ### assignment_regex Use `assignment_regex` to test a key value using a regular expression: ``` 'key = value' ``` may be tested using the following regular expression, which determines assignment from key to value: ``` assignment_regex: /^\s*([^=]*?)\s*=\s*(.*?)\s*$/ ``` ### comment_char Use `comment_char` to test for comments in a configuration file: ``` comment_char: '#' ``` ### key_values Use `key_values` to test how many values a key contains: ``` key = a b c ``` contains three values. To test that value to ensure it only contains one, use: ``` key_values: 1 ``` ### multiple_values Use `multiple_values` if the source file uses the same key multiple times. All values will be aggregated in an array: ``` # # file structure: # key = a # key = b # key2 = c params['key'] = ['a', 'b'] params['key2'] = ['c'] ``` To use plain key value mapping, use `multiple_values: false`: ``` # # file structure: # key = a # key = b # key2 = c params['key'] = 'b' params['key2'] = 'c' ``` ### standalone_comments Use `standalone_comments` to parse comments as a line, otherwise inline comments are allowed: ``` 'key = value # comment' params['key'] = 'value # comment' ``` Use `standalone_comments: false`, to parse the following: ``` 'key = value # comment' params['key'] = 'value' ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test A Configuration Setting ``` describe parse_config_file('/path/to/file.conf') do its('PARAM_X') { should eq 'Y' } end ``` ### Use Options And Then Test A Configuration Setting ``` describe parse_config_file('/path/to/file.conf', { multiple_values: true }) do its('PARAM_X') { should include 'Y' } end ``` ### Test A File With An INI File Structure `yum.conf` is one example of an INI file structure type. ``` describe parse_config_file('/path/to/yum.conf') do its('main') { should include('gpgcheck' => '1') } end ``` ### Test A Configuration Setting Containing Periods ``` describe parse_config_file('/etc/sysctl.conf') do its(['kernel.domainname']) { should eq 'example.com' } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/parse_config_file/postgres_hba_conf resource ============================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/postgres_hba_conf.md) Use the `postgres_hba_conf` Chef InSpec audit resource to test the client authentication data defined in the pg_hba.conf file. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.31.0 of InSpec. Syntax ------ An `postgres_hba_conf` Chef InSpec audit resource block declares client authentication data that should be tested: ``` describe postgres_hba_conf.where { type == 'local' } do its('auth_method') { should eq ['peer'] } end ``` where * `'attribute'` is a attribute in the pg hba configuration file * `'filter_value'` is the value that is to be filtered for * `'value'` is the value that is to be matched expected Properties ---------- ### address([String]) `address` returns a an array of strings that matches the where condition of the filter table ``` describe postgres_hba_conf.where { type == 'local' } do its('address') { should cmp 'value' } end ``` ### auth_method([String]) `auth_method` returns a an array of strings that matches the where condition of the filter table ``` describe postgres_hba_conf.where { type == 'local' } do its('auth_method') { should cmp 'value' } end ``` ### database([String]) `database` returns a an array of strings that matches the where condition of the filter table ``` describe postgres_hba_conf.where { type == 'local' } do its('database') { should cmp 'value' } end ``` ### type([String]) `type` returns a an array of strings that matches the where condition of the filter table ``` describe postgres_hba_conf.where { database == 'acme_test_db' } do its('type') { should cmp 'value' } end ``` ### user([String]) `user` returns a an array of strings that matches the where condition of the filter table ``` describe postgres_hba_conf.where { database == 'acme_test_db' } do its('user') { should cmp 'value' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/postgres_hba_conf/postgres_conf resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/postgres_conf.md) Use the `postgres_conf` Chef InSpec audit resource to test the contents of the configuration file for PostgreSQL, typically located at `/etc/postgresql/<version>/main/postgresql.conf` or `/var/lib/postgres/data/postgresql.conf`, depending on the platform. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `postgres_conf` resource block declares one (or more) settings in the `postgresql.conf` file, and then compares the setting in the configuration file to the value stated in the test: ``` describe postgres_conf('path') do its('setting') { should eq 'value' } end ``` where * `'setting'` specifies a setting in the `postgresql.conf` file * `('path')` is the non-default path to the `postgresql.conf` file (optional) * `should eq 'value'` is the value that is expected Properties ---------- This resource supports any of the settings listed in an postgresql.conf file as properties for e.g. max_connections ``` its('max_connections') { should eq '5' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the maximum number of allowed client connections ``` describe postgres_conf do its('max_connections') { should eq '5' } end ``` ### Test system logging ``` describe postgres_conf do its('logging_collector') { should eq 'on' } its('log_connections') { should eq 'on' } its('log_disconnections') { should eq 'on' } its('log_duration') { should eq 'on' } its('log_hostname') { should eq 'on' } its('log_line_prefix') { should eq '%t %u %d %h' } its(['pgaudit.log_parameter']) { should cmp 'on' } end ``` ### Test the port on which PostgreSQL listens ``` describe postgres_conf do its('port') { should eq '5432' } end ``` ### Test the Unix socket settings ``` describe postgres_conf do its('unix_socket_directories') { should eq '.s.PGSQL.5432' } its('unix_socket_group') { should eq nil } its('unix_socket_permissions') { should eq '0770' } end ``` where `unix_socket_group` is set to the PostgreSQL default setting (the group to which the server user belongs). Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/postgres_conf/postgres_session resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/postgres_session.md) Use the `postgres_session` Chef InSpec audit resource to test SQL commands run against a PostgreSQL database. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `postgres_session` resource block declares the username and password to use for the session, and then the command to be run: ``` # Create a PostgreSQL session: sql = postgres_session('username', 'password', 'host', 'port', 'socketpath') # default values: # username: 'postgres' # host: 'localhost' # port: 5432 # socketpath (optional): nil # Run an SQL query with an optional database to execute sql.query('sql_query', ['database_name'])` ``` A full example is: ``` sql = postgres_session('username', 'password', 'host', 'port', 'socketpath') describe sql.query('SELECT * FROM pg_shadow WHERE passwd IS NULL;') do its('output') { should eq '' } end ``` where * `its('output') { should eq '' }` compares the results of the query against the expected result in the test * `socketpath` is an optional parameter. Use `socketpath` to establish a socket connection with Postgres by specifying one of the Postgres Unix domain socket paths. Only supported on Unix-based platforms. Properties ---------- ### output The `output` property tests the results of the query: ``` its('output') { should eq(/^0/) } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the PostgreSQL shadow password ``` sql = postgres_session('my_user', 'password', '192.168.1.2', 5432) describe sql.query('SELECT * FROM pg_shadow WHERE passwd IS NULL;', ['testdb']) do its('output') { should eq('') } end ``` ### Test for risky database entries ``` describe postgres_session('my_user', 'password').query('SELECT count (*) FROM pg_language WHERE lanpltrusted = \'f\' AND lanname!=\'internal\' AND lanname!=\'c\';', ['postgres']) do its('output') { should eq '0' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/postgres_session/postfix_conf resource ====================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/postfix_conf.md) Use the `postfix_conf` Chef InSpec audit resource to test the main configuration of the Postfix Mail Transfer Agent. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version Syntax ------ A `postfix_conf` resource block declares the configuration settings to be tested: ``` describe postfix_conf do its('setting_name') { should cmp 'value' } end ``` where * `'setting_name'` is a setting key defined in main.cf * `{ should cmp 'value' }` is the value to be expected When using `postfix_conf` with a custom configuration directory, the following syntax can be used: ``` describe postfix_conf('path') do ... end ``` where * `'path'` is the path to your Postfix configuration (ex. ‘/etc/my/postfix/path/main.cf’) Properties ---------- This resource supports any of the settings listed in the main.cf file as properties. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test basic Postfix configuration settings in the main.cf file For example, the following Postfix configuration: ``` /etc/postfix/main.cf: myorigin = $myhostname myhostname = host.local.domain mynetworks = 127.0.0.0/8 ``` can be tested like this: ``` describe postfix_conf do its('myorigin') { should cmp '$myhostname' } its('myhostname') { should cmp 'host.local.domain' } its('mynetworks') { should cmp '127.0.0.0/8' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/postfix_conf/postgres_ident_conf resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/postgres_ident_conf.md) Use the `postgres_ident_conf` Chef InSpec audit resource to test the client authentication data defined in the pg_ident.conf file. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.31.0 of InSpec. Syntax ------ An `postgres_ident_conf` Chef InSpec audit resource block declares client authentication data that should be tested: ``` describe postgres_ident_conf.where { pg_username == 'filter_value' } do its('attribute') { should eq ['value'] } end ``` where * `'attribute'` is a attribute in the pg ident configuration file * `'filter_value'` is the value that is to be filtered for * `'value'` is the value that is to be matched expected Properties ---------- ### map_name([String]) `map_name` returns a an array of strings that matches the where condition of the filter table ``` describe postgres_ident_conf.where { pg_username == 'name' } do its('map_name') { should eq ['value'] } end ``` ### pg_username([String]) `pg_username` returns a an array of strings that matches the where condition of the filter table ``` describe postgres_ident_conf.where { pg_username == 'name' } do its('pg_username') { should eq ['value'] } end ``` ### system_username([String]) `system_username` returns a an array of strings that matches the where condition of the filter table ``` describe postgres_ident_conf.where { pg_username == 'name' } do its('system_username') { should eq ['value'] } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/postgres_ident_conf/rabbitmq_config resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/rabbitmq_config.md) Use the `rabbitmq_config` Chef InSpec audit resource to test configuration data for the RabbitMQ daemon located at `/etc/rabbitmq/rabbitmq.config` on Linux and Unix platforms. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.20.0 of InSpec. Syntax ------ A `rabbitmq_config` resource block declares the RabbitMQ configuration data to be tested: ``` describe rabbitmq_config.params('rabbit', 'ssl_listeners') do it { should cmp 5671 } end ``` where * `params` is the list of parameters configured in the RabbitMQ config file * `{ should cmp 5671 }` tests the value of `rabbit.ssl_listeners` as read from `rabbitmq.config` versus the value declared in the test Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the list of TCP listeners ``` describe rabbitmq_config.params('rabbit', 'tcp_listeners') do it { should eq [5672] } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/rabbitmq_config/registry_key resource ====================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/registry_key.md) Use the `registry_key` Chef InSpec audit resource to test key values in the Windows registry. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `registry_key` resource block declares the item in the Windows registry, the path to a setting under that item, and then one (or more) name/value pairs to be tested. Use a registry key name and path: ``` describe registry_key('Task Scheduler','HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Schedule') do its('Start') { should eq 2 } end ``` Use only a registry key path: ``` describe registry_key('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Schedule') do its('Start') { should eq 2 } end ``` Or use a Ruby Hash: ``` describe registry_key({ name: 'Task Scheduler', hive: 'HKEY_LOCAL_MACHINE', key: '\SYSTEM\CurrentControlSet\services\Schedule' }) do its('Start') { should eq 2 } end ``` ### Registry Key Path Separators A Windows registry key can be used as a string in Ruby code, such as when a registry key is used as the name of a recipe. In Ruby, when a registry key is enclosed in a double-quoted string (`" "`), the same backslash character (`\`) that is used to define the registry key path separator is also used in Ruby to define an escape character. Therefore, the registry key path separators must be escaped when they are enclosed in a double-quoted string. For example, the following registry key: ``` HKCU\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Themes ``` may be enclosed in a single-quoted string with a single backslash: ``` 'HKCU\SOFTWARE\path\to\key\Themes' ``` or may be enclosed in a double-quoted string with an extra backslash as an escape character: ``` "HKCU\\SOFTWARE\\path\\to\\key\\Themes" ``` **Warning**: Please make sure that you use backslashes instead of forward slashes. Forward slashes will not work for registry keys. ``` # The following will not work: # describe registry_key('HKLM/SOFTWARE/Microsoft/NET Framework Setup/NDP/v4/Full/1033') do # its('Release') { should eq 378675 } # end # You should use: describe registry_key('HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\1033') do its('Release') { should eq 378675 } end ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the start time for the Schedule service ``` describe registry_key('Task Scheduler','HKEY_LOCAL_MACHINE\...\Schedule') do its('Start') { should eq 2 } end ``` where `'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Schedule'` is the full path to the setting. ### Use a regular expression in responses ``` describe registry_key({ hive: 'HKEY_LOCAL_MACHINE', key: 'SOFTWARE\Microsoft\Windows NT\CurrentVersion' }) do its('ProductName') { should match /^[a-zA-Z0-9\(\)\s]*2012\s[rR]2[a-zA-Z0-9\(\)\s]*$/ } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### children The `children` matcher return all of the child items of a registry key. A regular expression may be used to filter child items: ``` describe registry_key('Key Name', '\path\to\key').children(regex) ... end ``` For example, to get all child items for a registry key: ``` describe registry_key('Task Scheduler','HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet').children do it { should_not eq [] } end ``` The following example shows how find a property that may exist against multiple registry keys, and then test that property for every registry key in which that property is located: ``` describe registry_key({ hive: 'HKEY_USERS' }).children(/^S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]{3,}\\Software\\Policies\\Microsoft\\Windows\\Installer/).each { |key| describe registry_key(key) do its('AlwaysInstallElevated') { should eq 'value' } end } ``` ### exist The `exist` matcher tests if the registry key is present: ``` it { should exist } ``` ### have_property The `have_property` matcher tests if a property exists for a registry key: ``` it { should have_property 'value' } ``` ### have_property_value The `have_property_value` matcher tests if a property value exists for a registry key: ``` it { should have_property_value 'value' } ``` ### have_value The `have_value` matcher tests if a value exists for a registry key: ``` it { should have_value 'value' } ``` ### name The `name` matcher tests the value for the specified registry setting: ``` its('name') { should eq 'value' } ``` **Warning**: Any name with a dot will not work as expected: `its(‘explorer.exe’) { should eq ‘test’ }`. For details, see <https://github.com/inspec/inspec/issues/1281``` # instead of: # its('explorer.exe') { should eq 'test' } # either use have_property_value... it { should have_property_value('explorer.exe', :string, 'test') } # ...or provide the name in an array its(['explorer.exe']) { should eq 'test' } ``` The latter workaround may be preferable because upon failure, Chef InSpec will present the expected and actual values: ``` inspec> describe registry_key('HKEY_USERS\S-1-5-20\Software\Policies\Microsoft\Windows\Control Panel\Desktop') do inspec> its(["SCRNSAVE.EXE"]) { should eq "FlyingToasters.scr" } inspec> end Profile: inspec-shell Version: (not specified) Registry Key HKEY_USERS\S-1-5-20\Software\Policies\Microsoft\Windows\Control Panel\Desktop × ["SCRNSAVE.EXE"] should eq "FlyingToasters.scr" expected: "FlyingToasters.scr" got: "scrnsave.scr" (compared using ==) Test Summary: 0 successful, 1 failure, 0 skipped ``` `have_property_value` only presents a false assertion: ``` Registry Key HKEY_USERS\S-1-5-20\Software\Policies\Microsoft\Windows\Control Panel\Desktop × should have property value "SCRNSAVE.EXE", "FlyingToasters.scr" expected #has_property_value?("SCRNSAVE.EXE", "FlyingToasters.scr") to return true, got false ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/registry_key/runit_service resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/runit_service.md) Use the `runit_service` Chef InSpec audit resource to test a service using runit. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `runit_service` resource block declares the name of a service and then one (or more) matchers to test the state of the service: ``` describe runit_service('service_name') do it { should be_installed } it { should be_enabled } it { should be_running } end ``` where * `('service_name')` must specify a service name * `be_installed`, `be_enabled`, and `be_running` are valid matchers for this resource; all matchers available to the `service` resource may be used The path to the service manager’s control may be specified for situations where the path isn’t available in the current `PATH`. For example: ``` describe runit_service('service_name', '/path/to/control') do it { should be_enabled } it { should be_installed } it { should be_running } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if the named service is enabled: ``` it { should be_enabled } ``` ### be_installed The `be_installed` matcher tests if the named service is installed: ``` it { should be_installed } ``` ### be_running The `be_running` matcher tests if the named service is running: ``` it { should be_running } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/runit_service/powershell resource =================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/powershell.md) Use the `powershell` Chef InSpec audit resource to test a Powershell script on the Windows platform. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `powershell` resource block declares a Powershell script to be tested, and then compares the output of that command to the matcher in the test: ``` script = <<-EOH # a PowerShell script EOH describe powershell(script) do its('property') { should eq 'output' } end ``` where * `'script'` must specify a Powershell script to be run * `'matcher'` is one of `exit_status`, `stderr`, or `stdout` * `'output'` tests the output of the command run on the system versus the output value stated in the test Properties ---------- ### exit_status The `exit_status` property tests the exit status for the command: ``` its('exit_status') { should eq 123 } ``` ### stderr The `stderr` property tests results of the command as returned in standard error (stderr): ``` its('stderr') { should eq 'error' } ``` ### stdout The `stdout` property tests results of the command as returned in standard output (stdout): ``` its('stdout') { should eq '/^1$/' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Get all groups of Administrator user ``` script = <<-EOH # find user $user = Get-WmiObject Win32_UserAccount -filter "Name = 'Administrator'" # get related groups $groups = $user.GetRelated('Win32_Group') | Select-Object -Property Caption, Domain, Name, LocalAccount, SID, SIDType, Status $groups | ConvertTo-Json EOH describe powershell(script) do its('stdout') { should_not eq '' } end ``` ### Write-Output ‘hello’ The following Powershell script: ``` script = <<-EOH Write-Output 'hello' EOH ``` can be tested in the following ways. For a newline: ``` describe powershell(script) do its('stdout') { should eq "hello\r\n" } its('stderr') { should eq '' } end ``` Removing whitespace `\r\n` from `stdout`: ``` describe powershell(script) do its('strip') { should eq "hello" } end ``` No newline: ``` describe powershell("'hello' | Write-Host -NoNewLine") do its('stdout') { should eq 'hello' } its('stderr') { should eq '' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/powershell/processes resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/processes.md) Use the `processes` Chef InSpec audit resource to test properties for programs that are running on the system. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `processes` resource block declares the name of the process to be tested, and then declares one (or more) property/value pairs: ``` describe processes('process_name') do its('property_name') { should eq ['property_value'] } end ``` where * `processes('process_name')` specifies the name of a process to check. If this is a string, it will be converted to a Regexp. For more specificity, pass a Regexp directly. If left blank, all processes will be returned. * `property_name` may be used to test user (`its('users')`) and state properties (`its('states')`) Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if the list length for the mysqld process is 1 ``` describe processes('mysqld') do its('list.length') { should eq 1 } end ``` ### Test if the process is owned by a specific user ``` describe processes('init') do its('users') { should eq ['root'] } end describe processes('winlogon') do its('users') { should cmp "NT AUTHORITY\\SYSTEM" } end ``` ### Test if a high-priority process is running ``` describe processes('linux_process') do its('states') { should eq ['R<'] } end describe processes('windows_process') do its('labels') { should cmp "High" } end ``` ### Test if a process exists on the system ``` describe processes('some_process') do it { should exist } end ``` ### Test for a process using a specific Regexp If the process name is too common for a string to uniquely find it, you may use a regexp. Inclusion of whitespace characters may be needed. ``` describe processes(Regexp.new("/usr/local/bin/swap -d")) do its('list.length') { should eq 1 } end ``` ### Notes for auditing Windows systems Sometimes with system properties there isn’t a direct comparison between different operating systems. Most of the `property_name`’s do align between the different OS’s. There are however some exception’s, for example, within linux `states` offers multiple properties. Windows doesn’t have direct comparison that is a single property so instead `states` is mapped to the property of `Responding`, This is a boolean true/false flag to help determine if the process is hung. Below is a mapping table to help you understand what property the unix field maps to the windows `Get-Process` Property | *unix ps field* | *windows PowerShell Property* | | --- | --- | | labels | PriorityClass | | pids | Id | | cpus | CPU | | mem | PM | | vsz | VirtualMemorySize | | rss | NPM | | tty | SessionId | | states | Responding | | start | StartTime | | time | TotalProcessorTime | | users | UserName | | commands | Path | Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### property_name The `property_name` matcher tests the named property for the specified value: ``` its('property_name') { should eq ['property_value'] } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/processes/security_identifier resource ============================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/security_identifier.md) Use the `security_identifier` Chef InSpec resource to test the [Security Identifier (SID)](https://docs.microsoft.com/en-us/windows/desktop/secauthz/security-identifiers) for user and group trustees on Windows. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. Resource Parameters ------------------- A `security_identifier` resource should specify the name and type of the trustee to test the SID for: ``` describe security_identifier(group: 'Everyone') do its('sid') { should eq 'S-1-1-0' } end ``` where * `group:` specifies that `'Everyone'` should be a group. `user:` can be used to specify a user account. ** It is necessary to declare the type of the trustee because Windows allows users, groups and other entities to share names. If you really need to not specify the type, `unspecified:` can be used. This will attempt to match the name to a group and then a useraccount. This may take longer to execute and comes with the risk of Chef InSpec matching the name to an unintended trustee. Examples -------- The following examples show how to use this Chef InSpec resource. ### Verify that the Admnistrator user has a SID ``` describe security_identifier(user: 'Administrator') do it { should exist } end ``` ### Verify that a SID is the expected value ``` describe security_identifier(group: 'Everyone') do its('sid') { should eq 'S-1-1-0' } end ``` ### Use in conjunction with the security_policy resource to specify the trustee to test for in the audit policy ``` describe security_policy do its("SeRemoteInteractiveLogonRight") { should_not include security_identifier(group: 'Guests') } end ``` Properties ---------- ### sid ``` describe security_identifier(group: 'Everyone') do its('sid') { should eq 'S-1-1-0' } end ``` Matchers -------- This Chef InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist For this resource, `exist` is true if a Security Identifier (SID) exists on the target host for the specified trustee. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/security_identifier/selinux resource ================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/selinux.md) Use the `selinux` Chef InSpec audit resource to test the configuration data of the SELinux policy, SELinux modules and SELinux booleans. The `selinux` resource extracts and exposes data reported by the `sestatus`, `semodule -lfull`, and `semanage boolean -l -n` command. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v4.35.1 of InSpec. Syntax ------ The `selinux` Chef InSpec resource block tests the state and mode of SELinux policy. ``` describe selinux do it { should be_installed } it { should_not be_disabled } it { should be_enforcing } it { should_not be_permissive } end ``` The `selinux` resource block also allows you to write tests for multiple modules: ``` describe selinux.modules.where("zebra") do it { should exist } it { should be_installed } it { should be_enabled } end ``` or: ``` describe selinux.modules.where(status: "installed") do it { should exist } its('count') { should cmp 404 } end ``` where: * `.where()` specifies the parameter and expected value. * `name`, `status`, `state`, and `priority` are valid parameters. The `selinux` resource block also allows you to write tests for multiple booleans: ``` describe selinux.booleans.where(name: "httpd_enable_homedirs") do it { should_not be_on } end ``` or: ``` describe selinux.booleans.where(name: "xend_run_blktap", state: "on") do it { should exist } its('defaults') { should cmp "on" } end ``` * `.where()` specifies the parameter and expected value. * `name`, `state`, and `default` are valid parameters for `booleans`. Examples -------- The following examples show how to use this Chef InSpec selinux resource. ### Test if SELinux is installed and enabled ``` describe selinux do it { should be_installed } it { should_not be_disabled } end ``` ### Test if SELinux is enabled and running in enforcing mode ``` describe selinux do it { should_not be_disabled } it { should be_enforcing } end ``` ### Test the selinux policy type ``` describe selinux do its('policy') { should eq "targeted"} end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_installed The `be_installed` matcher tests if the SElinux policy or SElinux modules are installed on the system: ``` it { should be_installed } ``` ### be_disabled The `be_disabled` matcher tests if the SELinux is disabled on the system: ``` it { should be_disabled } ``` ### be_enforcing The `be_enforcing` matcher tests if the SELinux mode is set to enforcing: ``` it { should be_enforcing } ``` ### be_permissive The `be_permissive` matcher tests if the SELinux mode is set to permissive: ``` it { should be_permissive } ``` ### be_on The `be_on` matcher tests if the SELinux boolean is on: ``` it { should be_on } ``` ### be_enabled The `be_enabled` matcher tests if the SElinux module is enabled: ``` it { should be_enabled } ``` Resource Parameters ------------------- * `names`, `status`, `states`, and `priorities` are valid parameters for SELinux policy modules. * `names`, `status`, `states`, and `defaults` are valid parameters for SELinux `booleans`. Resource Parameter Examples --------------------------- ### modules `modules` returns information about SELinux modules using the [semodule -lfull](https://man7.org/linux/man-pages/man8/semodule.8.html) command. Note: The `semodule -l` command [does not provide version information](https://access.redhat.com/solutions/2760071) for newer versions of Linux-based systems like RHEL8 and Centos8, so we do not support that option. ``` describe selinux.modules do its("names") { should include "zebra" } its("status") { should include "installed" } its("states") { should include "enabled" } its("priorities") { should include "100" } end ``` ### booleans `booleans` returns information about SELinux booleans using the [semanage boolean -l -n](https://man7.org/linux/man-pages/man8/semanage-boolean.8.html) command. ``` describe selinux.booleans do its("names") { should include "httpd_enable_homedirs" } its("states") { should include "on" } its("states") { should include "off" } its("defaults") { should include "on" } its("defaults") { should include "off" } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/selinux/security_policy resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/security_policy.md) Use the `security_policy` Chef InSpec audit resource to test security policies on the Windows platform. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `security_policy` resource block declares the name of a security policy and the value to be tested: ``` describe security_policy do its('policy_name') { should eq 'value' } end describe security_policy(translate_sid: true) do its('policy_name') { should include 'sid_name' } end ``` where * `'policy_name'` must specify a security policy * `{ should eq 'value' }` tests the value of `policy_name` against the value declared in the test * `translate_sid` converts the security identifier (SID) into a human readable SID name if `true`. Default value is `false`. Properties ---------- This resource supports any of the security policy name as properties for e.g. `SeNetworkLogonRigth`, `SeRemoteInteractiveLogonRight` etc. ``` its('SeNetworkLogonRight') { should eq '*S-1-5-11' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Verify that only the Administrators group has remote access ``` describe security_policy do its('SeRemoteInteractiveLogonRight') { should eq '*S-1-5-32-544' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/security_policy/shadow resource =============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/shadow.md) Use the `shadow` Chef InSpec audit resource to test the contents of `/etc/shadow`, which contains password details that are readable only by the `root` user. `shadow` is a [plural resource](../../glossary/index#plural_resource). Like all plural resources, it functions by performing searches across multiple entries in the shadow file. The format for `/etc/shadow` includes: * A username * The hashed password for that user * The last date a password was changed, as the number of days since Jan 1, 1970 * The minimum number of days a password must exist before it may be changed * The maximum number of days after which a password must be changed * The number of days a user is warned about an expiring password * The number of days a user must be inactive before the user account is disabled * The date on which a user account was disabled, as the number of days since Jan 1, 1970 These entries are defined as a colon-delimited row in the file, one row per user: ``` dannos:Gb7crrO5CDF.:10063:0:99999:7::: ``` The `shadow` resource understands this format, allows you to search on the fields, and exposes the selected users' properties. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Resource Parameters ------------------- The `shadow` resource takes one optional parameter: the path to the shadow file. If omitted, `/etc/shadow` is assumed. ``` # Expect a file to exist at the default location and have 32 users describe shadow do its('count') { should eq 32 } end # Use a custom location describe shadow('/etc/my-custom-place/shadow') do its('count') { should eq 32 } end ``` Examples -------- A `shadow` resource block uses `where` to filter entries from the shadow file. If `where` is omitted, all entries are selected. ``` # Select all users. Among them, there should not be a user with the name 'forbidden_user'. describe shadow do its('users') { should_not include 'forbidden_user' } end # Ensure there is only one user named 'root' (Select all with name 'root', then count them). describe shadow.where(user: 'root') do its('count') { should eq 1 } end ``` Use `where` to match any of the supported [filter criteria](#filter_criteria). `where` has a method form for simple equality and a block form for more complex queries. ``` # Method form, simple # Select just the root user (direct equality) describe shadow.where(user: 'root') do its ('count') { should eq 1 } end # Method form, with a regex # Select all users whose names begin with smb describe shadow.where(user: /^smb/) do its ('count') { should eq 2 } end # Block form # Select users whose passwords have expired describe shadow.where { expiry_date > 0 } do # This test directly asserts that there should be 0 such users its('count') { should eq 0 } # But if the count test fails, this test outputs the users that are causing the failure. its('users') { should be_empty } end ``` Use `where` with [expect syntax](../../profiles/index#should-vs-expect-syntax) to show all users (that aren’t disabled or locked) without SHA512 hashed passwords. ``` # Users with password fields that are not *, !, or don't begin with $6$ bad_users = inspec.shadow.where { password !~ /^[*!]$|^\$6\$.*/ }.users describe 'Password hashes in /etc/shadow' do it 'should only contain SHA512 hashes' do message = "Users without SHA512 hashes: #{bad_users.join(', ')}" expect(bad_users).to be_empty, message end end ``` Properties ---------- As a [plural resource](../../glossary/index#plural_resource), all of `shadow`’s properties return lists (that is, Ruby Arrays). `include` and `be_empty` are two useful matchers when working with lists. You can also perform manipulation of the lists, such as calling `uniq`, `sort`, `count`, `first`, `last`, `min`, and `max`. ### users A list of strings, representing the usernames matched by the filter. ``` describe shadow its('users') { should include 'root' } end ``` ### passwords A list of strings, representing the encrypted password strings for entries matched by the `where` filter. Each string may not be an encrypted password, but rather a `*` or similar which indicates that direct logins are not allowed. Different operating systems use different flags here (such as `*LK*` to indicate the account is locked). ``` # Use uniq to remove duplicates, then determine # if the only password left on the list is '*' describe shadow.where(user: /adm$/) do its('passwords.uniq.first') { should cmp '*' } its('passwords.uniq.count') { should eq 1 } end ``` ### last_changes A list of integers, indicating the number of days since Jan 1, 1970 since the password for each matching entry was changed. ``` # Ensure all entries have changed their password in the last 90 days. (Probably want a filter on that) describe shadow do its('last_changes.min') { should be < Date.today - 90 - Date.new(1970,1,1) } end ``` ### min_days A list of integers reflecting the minimum number of days a password must exist, before it may be changed, for the users that matched the filter. ``` # min_days seems crazy today; make sure it is zero for everyone describe shadow do its('min_days.uniq') { should eq [0] } end ``` ### max_days A list of integers reflecting the maximum number of days after which the password must be changed for each user matching the filter. ``` # Make sure there is no policy allowing longer than 90 days describe shadow do its('max_days.max') { should be < 90 } end ``` ### warn_days A list of integers reflecting the number of days a user is warned about an expiring password for each user matching the filter. ``` # Ensure everyone gets the same 7-day policy describe shadow do its('warn_days.uniq.count') { should eq 1 } its('warn_days.uniq.first') { should eq 7 } end ``` ### inactive_days A list of integers reflecting the number of days a user must be inactive before the user account is disabled for each user matching the filter. ``` # Ensure everyone except admins has an stale policy of no more than 14 days describe shadow.where { user !~ /adm$/ } do its('inactive_days.max') { should be <= 14 } end ``` ### expiry_dates A list of integers reflecting the number of days since Jan 1, 1970 that a user account has been disabled, for each user matching the filter. Value is `nil` if the account has not expired. ``` # No one should have an expired account. describe shadow do its('expiry_dates.compact') { should be_empty } end ``` ### count The `count` property tests the number of records that the filter matched. ``` # Should probably only have one root user describe shadow.user('root') do its('count') { should eq 1 } end ``` Filter Criteria --------------- You may use any of these filter criteria with the `where` function. They are named after the columns in the shadow file. Each has a related list [property](#properties). ### user The string username of a user. Always present. Not required to be unique. ``` # Expect all users whose name ends in adm to have a disabled password via the '*' flag describe shadow.where(user: /adm$/) do its('password.uniq') { should eq ['*'] } end ``` ### password The encrypted password strings, or an account status string. Each string may not be an encrypted password, but rather a `*` or similar which indicates that direct logins are not allowed. Different operating systems use other flags here (such as `*LK*` to indicate the account is locked). ``` # Find 'locked' accounts and ensure 'nobody' is on the list describe shadow.where(password: '*LK*') do its('users') { should include 'nobody' } end ``` ### last_change An integer reflecting the number of days since Jan 1, 1970 since the user’s password was changed. ``` # Find users who have not changed their password within 90 days describe shadow.where { last_change > Date.today - 90 - Date.new(1970,1,1) } do its('users') { should be_empty } end ``` ### min_days An integer reflecting the minimum number of days a user is required to wait before changing their password again. ``` # Find users who have a nonzero wait time describe shadow.where { min_days > 0 } do its('users') { should be_empty } end ``` ### max_days An integer reflecting the maximum number of days a user may go without changing their password. ``` # All users should have a 30-day policy describe shadow.where { max_days != 30 } do its('users') { should be_empty } end ``` ### warn_days An integer reflecting the number of days before a password expiration that a user receives an alert. ``` # All users should have a 7-day warning policy describe shadow.where { warn_days != 7 } do its('users') { should be_empty } end ``` ### inactive_days An integer reflecting the number of days that must pass before a user who has not logged in will be disabled. ``` # Ensure everyone has a stale policy of no more than 14 days. describe shadow.where { inactive_days.nil? || inactive_days > 14 } do its('users') { should be_empty } end ``` ### expiry_date An integer reflecting the number of days since Jan 1, 1970 on which the user was disabled. The `expiry_date` criterion is `nil` for enabled users. ``` # Ensure no one is disabled due to a old password describe shadow.where { !expiry_date.nil? } do its('users') { should be_empty } end # Ensure no one is disabled for more than 14 days describe shadow.where { !expiry_date.nil? && expiry_date - Date.new(1970,1,1) > 14} do its('users') { should be_empty } end ``` Matchers -------- This resource has no resource-specific matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/shadow/sshd_config resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/sshd_config.md) Use the `sshd_config` Chef InSpec audit resource to test configuration data for the OpenSSH daemon located at `/etc/ssh/sshd_config` on Linux and Unix platforms. sshd—the OpenSSH daemon—listens on dedicated ports, starts a daemon for each incoming connection, and then handles encryption, authentication, key exchanges, command execution, and data exchanges. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `sshd_config` resource block declares the OpenSSH daemon configuration data to be tested: ``` describe sshd_config('path') do its('name') { should include('foo') } end ``` where * `name` is a configuration setting in `sshd_config` * `('path')` is the non-default `/path/to/sshd_config` * `{ should include('foo') }` tests the value of `name` as read from `sshd_config` versus the value declared in the test Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test which variables may be sent to the server ``` describe sshd_config do its('AcceptEnv') { should include('CI_ENABLE_COVERAGE') } end ``` ### Test for IPv6-only addresses ``` describe sshd_config do its('AddressFamily') { should cmp 'inet6' } end ``` ### Test the Protocol setting ``` describe sshd_config do its('Protocol') { should cmp 2 } end ``` ### Test for approved, strong ciphers ``` describe sshd_config do its('Ciphers') { should cmp('<EMAIL>,aes256-ctr,aes192-ctr,aes128-ctr') } end ``` ### Test SSH protocols ``` describe sshd_config do its('Port') { should cmp 22 } its('UsePAM') { should eq 'yes' } its('ListenAddress') { should eq nil } its('HostKey') do should eq [ '/etc/ssh/ssh_host_rsa_key', '/etc/ssh/ssh_host_dsa_key', '/etc/ssh/ssh_host_ecdsa_key', ] end end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### name The `name` matcher tests the value of `name` as read from `sshd_config` versus the value declared in the test: ``` its('name') { should cmp 'foo' } ``` or: ``` its('name') {should include('bar') } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/sshd_config/service resource ================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/service.md) Use the `service` Chef InSpec audit resource to test if the named service is installed, running and/or enabled. Under some circumstances, it may be necessary to specify the service manager by using one of the following service manager-specific resources: `bsd_service`, `launchd_service`, `runit_service`, `systemd_service`, `sysv_service`, or `upstart_service`. These resources are based on the `service` resource. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `service` resource block declares the name of a service and then one (or more) matchers to test the state of the service: ``` describe service('service_name') do it { should be_installed } it { should be_enabled } it { should be_running } end ``` where * `('service_name')` must specify a service name * `be_installed`, `be_enabled`, and `be_running` are valid matchers for this resource Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if the postgresql service is both running and enabled ``` describe service('postgresql') do it { should be_enabled } it { should be_running } end ``` ### Test if the mysql service is both running and enabled ``` describe service('mysqld') do it { should be_enabled } it { should be_running } end ``` ### Test if ClamAV (an antivirus engine) is installed and running ``` describe package('clamav') do it { should be_installed } its('version') { should eq '0.98.7' } end describe service('clamd') do it { should_not be_enabled } it { should_not be_installed } it { should_not be_running } end ``` ### Test Unix System V run levels On targets that are using SystemV services, the existing run levels can also be checked: ``` describe service('sshd').runlevels do its('keys') { should include(2) } end describe service('sshd').runlevels(2,4) do it { should be_enabled } end ``` ### Override the service manager Under some circumstances, it may be required to override the logic in place to select the right service manager. For example, to check a service managed by Upstart: ``` describe upstart_service('service') do it { should_not be_enabled } it { should be_installed } it { should be_running } end ``` This is also possible with `systemd_service`, `runit_service`, `sysv_service`, `bsd_service`, and `launchd_service`. Provide the control command when it is not to be found at the default location. For example, if the `sv` command for services managed by runit is not in the `PATH`: ``` describe runit_service('service', '/opt/chef/embedded/sbin/sv') do it { should be_enabled } it { should be_installed } it { should be_running } end ``` ### Verify that IIS is running ``` describe service('W3SVC') do it { should be_installed } it { should be_running } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if the named service is enabled: ``` it { should be_enabled } ``` ### be_installed The `be_installed` matcher tests if the named service is installed: ``` it { should be_installed } ``` ### be_running The `be_running` matcher tests if the named service is running: ``` it { should be_running } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/service/ssh_config resource ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/ssh_config.md) Use the `ssh_config` Chef InSpec audit resource to test OpenSSH client configuration data located at `/etc/ssh/ssh_config` on Linux and Unix platforms. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `ssh_config` resource block declares the client OpenSSH configuration data to be tested: ``` describe ssh_config('path') do its('name') { should include('foo') } end ``` where * `name` is a configuration setting in `ssh_config` * `('path')` is the non-default `/path/to/ssh_config` * `{ should include('foo') }` tests the value of `name` as read from `ssh_config` versus the value declared in the test Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test SSH configuration settings ``` describe ssh_config do its('cipher') { should contain '3des' } its('port') { should eq '22' } its('hostname') { should include('example.com') } end ``` ### Test which variables from the local environment are sent to the server ``` only_if do command('sshd').exist? or command('ssh').exists? end describe ssh_config do its('SendEnv') { should include('CI_ENABLE_COVERAGE') } end ``` ### Test SSH configuration ``` describe ssh_config do its('Host') { should eq '*' } its('Tunnel') { should eq nil } its('SendEnv') { should eq 'LANG LC_*' } its('HashKnownHosts') { should eq 'yes' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### name The `name` matcher tests the value of `name` as read from `ssh_config` versus the value declared in the test: ``` its('name') { should eq 'foo' } ``` or: ``` its('name') { should include('bar') } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/ssh_config/ssl resource ============ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/ssl.md) Use the `ssl` Chef InSpec audit resource to test SSL settings for the named port. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `ssl` resource block declares an SSL port, and then other properties of the test like cipher and/or protocol: ``` describe ssl(port: #) do it { should be_enabled } end ``` or: ``` describe ssl(port: #).filter('value') do it { should be_enabled } end ``` where * `ssl(port: #)` is the port number, such as `ssl(port: 443)` * `filter` may take any of the following arguments: `ciphers`, `protocols`, and `handshake` Properties ---------- ### ciphers The `ciphers` property tests the named cipher: ``` its('ciphers') { should_not eq '/rc4/i' } ``` or: ``` describe ssl(port: 443).ciphers(/rc4/i) do it { should_not be_enabled } end ``` ### protocols The `protocols` property tests what protocol versions (SSLv3, TLSv1.1, etc) are enabled: ``` its('protocols') { should eq 'ssl2' } ``` or: ``` describe ssl(port: 443).protocols('ssl2') do it { should_not be_enabled } end ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Run the ssl-baseline example profile The following shows how to use the `ssl` Chef InSpec audit resource to find all TCP ports on the system, including IPv4 and IPv6. (This is a partial example based on the `ssl_text.rb` file in the `ssl-baseline` profile on GitHub.) ``` ... control 'tls1.2' do title 'Run TLS 1.2 whenever SSL is active on a port' impact 0.5 sslports.each do |socket| proc_desc = "on node == #{command('hostname').stdout.strip} running #{socket.process.inspect} (#{socket.pid})" describe ssl(port: socket.port).protocols('tls1.2') do it(proc_desc) { should be_enabled } it { should be_enabled } end end end ... control 'rc4' do title 'Disable RC4 ciphers from all exposed SSL/TLS ports and versions.' impact 0.5 sslports.each do |socket| proc_desc = "on node == #{command('hostname').stdout.strip} running #{socket.process.inspect} (#{socket.pid})" describe ssl(port: socket.port).ciphers(/rc4/i) do it(proc_desc) { should_not be_enabled } it { should_not be_enabled } end end end ``` There are two ways to run the `ssl-baseline` example profile to test SSL via the `ssl` resource. Clone the profile: ``` $ git clone https://github.com/dev-sec/ssl-baseline ``` and then run: ``` $ inspec exec ssl-baseline ``` Or execute the profile directly via URL: ``` $ inspec exec https://github.com/dev-sec/ssl-baseline ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if SSL is enabled: ``` it { should be_enabled } ``` ### ciphers The `ciphers` matcher tests the named cipher: ``` its('ciphers') { should_not eq '/rc4/i' } ``` or: ``` describe ssl(port: 443).ciphers(/rc4/i) do it { should_not be_enabled } end ``` ### protocols The `protocols` matcher tests what protocol versions (SSLv3, TLSv1.1, etc) are enabled: ``` its('protocols') { should eq 'ssl2' } ``` or: ``` describe ssl(port: 443).protocols('ssl2') do it { should_not be_enabled } end ``` Supported protocols: * `ssl2` * `ssl3` * `tls1.0` * `tls1.1` * `tls1.2` * `tls1.3` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/ssl/sys_info resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/sys_info.md) Use the `sys_info` Chef InSpec audit resource to test for operating system properties for the named host, and then returns that info as standard output. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `sys_info` resource block declares the hostname to be tested: ``` describe sys_info do its('hostname') { should eq 'value' } end ``` Properties ---------- ### hostname The `hostname` property tests the host for which standard output is returned: ``` its('hostname') { should eq 'value' } ``` ### fqdn The `fqdn` property tests the ‘fully qualified domain name’ of the system: ``` its('fqdn') { should eq 'value' } ``` ### domain The `domain` property tests the name of the DNS domain: ``` its('domain') { should eq 'value' } ``` ### ip-address The `ip-address` property tests all network addresses of the host: ``` its('ip-address') { should eq 'value' } ``` ### short The `short` property tests the host name cut at the first dot: ``` its('short') { should eq 'value' } ``` ### manufacturer The `manufacturer` property tests the host for which standard output is returned: ``` its('manufacturer') { should eq 'ACME Corp.' } ``` ### model The `model` property tests the host for which standard output is returned: ``` its('model') { should eq 'Flux Capacitor' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Get system information for example.com ``` describe sys_info do its('hostname') { should eq 'example.com' } end ``` ### Compare content to hostname ``` describe file('/path/to/some/file') do its('content') { should match sys_info.hostname } end ``` Options can be passed as arguments to hostname as well. ``` describe file('/path/to/some/file') do its('content') { should match sys_info.hostname('full') } end ``` Currently supported arguments to `hostname` on Linux platforms are ‘full’|‘f’|‘fqdn’|‘long’, ‘domain’|’d', ‘ip_address’|‘i’, and ‘short’|’s'. Mac currently supports ‘full’|‘f’|‘fqdn’|‘long’ and ‘short’|’s' Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/sys_info/systemd_service resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/systemd_service.md) Use the `systemd_service` Chef InSpec audit resource to test a service using SystemD. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `systemd_service` resource block declares the name of a service and then one (or more) matchers to test the state of the service: ``` describe systemd_service('service_name') do it { should be_installed } it { should be_enabled } it { should be_running } end ``` where * `('service_name')` must specify a service name * `be_installed`, `be_enabled`, and `be_running` are valid matchers for this resource; all matchers available to the `service` resource may be used The path to the service manager’s control may be specified for situations where the path isn’t available in the current `PATH`. For example: ``` describe systemd_service('service_name', '/path/to/control') do it { should be_enabled } it { should be_installed } it { should be_running } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if the named service is enabled: ``` it { should be_enabled } ``` ### be_installed The `be_installed` matcher tests if the named service is installed: ``` it { should be_installed } ``` ### be_running The `be_running` matcher tests if the named service is running: ``` it { should be_running } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/systemd_service/sybase_session resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/sybase_session.md) Use the `sybase_session` Chef InSpec audit resource to test the SQL commands run against an SAP Adaptive Server Enterprise (ASE) database. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Requirements The `isql` command line tool must be installed on the target system. Syntax ------ A `sybase_session` resource block declares the server, database, username and password to use for the session, and then the command to be run: ``` describe sybase_session(database: 'pubs2', server: 'SYBASE', username: 'USERNAME', password: 'PASSWORD').query('QUERY').row(0).column('RESULT') do its('value') { should eq('EXPECTED') } end ``` where * `sybase_session` declares a server, database, username, and password with permission to run the query. * `query('QUERY')` contains the query to be run. * `its('value') { should eq('expected') }` compares the results of the query against the expected result in the test. ### Optional Parameters #### bin You may use the `bin` parameter to specify the path to the `isql` cli tool. ``` describe sybase_session(database: 'pubs2', server: 'SYBASE', username: 'USERNAME', password: 'PASSWORD', bin: '/opt/sap/OCS-16_0/bin/isql', ).query('QUERY').row(0).column('RESULT') do its('value') { should eq('EXPECTED') } end ``` #### sybase_home You may use the `sybase_home` parameter to specify the path to the sybase installation. ``` describe sybase_session(database: 'pubs2', server: 'SYBASE', username: 'USERNAME', password: 'PASSWORD', sybase_home: '/opt/sap', ).query('QUERY').row(0).column('RESULT') do its('value') { should eq('EXPECTED') } end ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test for matching values in the pubs2 sample database ``` sql = sybase_session(database: 'pubs2', server: 'SYBASE', username: 'MY_USER', password: 'PASSWORD') describe sql.query("SELECT au_lname FROM authors").row(0).column('AU_LNAME') do its("value") { should eq 'BENNET' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/sybase_session/sysv_service resource ====================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/sysv_service.md) Use the `sysv_service` Chef InSpec audit resource to test a service using SystemV. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `sysv_service` resource block declares the name of a service and then one (or more) matchers to test the state of the service: ``` describe sysv_service('service_name') do it { should be_installed } it { should be_enabled } it { should be_running } end ``` where * `('service_name')` must specify a service name * `be_installed`, `be_enabled`, and `be_running` are valid matchers for this resource; all matchers available to the `service` resource may be used The path to the service manager’s control may be specified for situations where the path isn’t available in the current `PATH`. For example: ``` describe sysv_service('service_name', '/path/to/control') do it { should be_enabled } it { should be_installed } it { should be_running } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if the named service is enabled: ``` it { should be_enabled } ``` ### be_installed The `be_installed` matcher tests if the named service is installed: ``` it { should be_installed } ``` ### be_running The `be_running` matcher tests if the named service is running: ``` it { should be_running } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/sysv_service/sybase_conf resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/sybase_conf.md) Use the `sybase_conf` Chef InSpec audit resource to test the configuration of an SAP Adaptive Server Enterprise (ASE) database. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Requirements The `isql` command line tool must be installed on the target system. You must have access to a database user that has access to the `sa` role on the `master` database. Syntax ------ A `sybase_conf` resource block declares the configuration item name, server, and password to use. ``` describe sybase_session('config item', server: 'SYBASE', password: 'PASSWORD') do its('run_value') { should cmp 'EXPECTED' } its('config_value') { should cmp 'EXPECTED' } end ``` where * `sybase_conf` declares a configuration item, server, and password with permission to run `sp_configure`. * `its('run_value') { should cmp 'expected' }` compares the current running value of the configuration item against an expected value. * `its('config_value') { should cmp 'expected' }` compares the saved value of the configuration item against an expected value. ### Optional Parameters The `sybase_conf` resource is based on the `sybase_session` resource and accepts all parameters that `sybase_session` accepts, including optional parameters `username`, `database`, `sybase_home`, and `bin`. In particular: #### `database` Defaults to `master`. #### `username` Defaults to `sa`. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test for max memory configuration ``` describe sybase_session('max memory', server: 'SYBASE', password: 'PASSWORD') do its('run_value') { should cmp 180224 } its('config_value') { should cmp 180224 } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/sybase_conf/toml resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/toml.md) Use the `toml` Chef InSpec audit resource to test settings in a TOML file. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `toml` resource block declares the configuration settings to be tested: ``` describe toml('path') do its('setting_name') { should eq 'value' } end ``` where: * `'setting_name'` is a setting key defined in the TOML file. * `('path')` is the path to the TOML file. * `{ should eq 'value' }` is the value that is expected. Properties ---------- This resource supports any of the settings listed in a TOML file as properties. Examples -------- In the examples below, the `example.toml` file contains the following data: ``` port = 8080 fruits = ["apple", "banana", "cantaloupe"] [section] key1 = "value1" ``` **Verify the port number:** ``` describe toml('path/to/example.toml') do its('port') { should eq 8080 } end ``` **Verify the value of an array using brackets:** ``` describe toml('path/to/example.toml') do its(['fruits', 0]) { should eq 'apple' } end ``` **Verify the value of a key in a table using brackets:** ``` describe toml('path/to/example.toml') do its(['section', 'key1']) { should cmp 'value1' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/toml/upstart_service resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/upstart_service.md) Use the `upstart_service` Chef InSpec audit resource to test a service using Upstart. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `upstart_service` resource block declares the name of a service and then one (or more) matchers to test the state of the service: ``` describe upstart_service('service_name') do it { should be_installed } it { should be_enabled } it { should be_running } end ``` where * `('service_name')` must specify a service name * `be_installed`, `be_enabled`, and `be_running` are valid matchers for this resource; all matchers available to the `service` resource may be used The path to the service manager’s control may be specified for situations where the path isn’t available in the current `PATH`. For example: ``` describe upstart_service('service_name', '/path/to/control') do it { should be_enabled } it { should be_installed } it { should be_running } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if the named service is enabled: ``` it { should be_enabled } ``` ### be_installed The `be_installed` matcher tests if the named service is installed: ``` it { should be_installed } ``` ### be_running The `be_running` matcher tests if the named service is running: ``` it { should be_running } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/upstart_service/user resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/user.md) Use the `user` Chef InSpec audit resource to test user profiles for a single, known/expected local user, including the groups to which that user belongs, the frequency of required password changes, and the directory paths to home and shell. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `user` resource block declares a user name, and then one (or more) matchers: ``` describe user('root') do it { should exist } its('uid') { should eq 1234 } its('gid') { should eq 1234 } its('group') { should eq 'root' } its('groups') { should eq ['root', 'other']} its('home') { should eq '/root' } its('shell') { should eq '/bin/bash' } its('mindays') { should eq 0 } its('maxdays') { should eq 90 } its('warndays') { should eq 8 } its('passwordage') { should eq 355 } its('maxbadpasswords') { should eq nil } // Only valid on Windows OS its('badpasswordattempts') { should eq 0 } its('lastlogin') { should eq nil } // Only valid on Windows OS end ``` where * `('root')` is the user to be tested * `it { should exist }` tests if the user exists * `gid`, `group`, `groups`, `home`, `maxdays`, `mindays`, `shell`, `uid`, `warndays`´, `passwordage`, `maxbadpasswords`, `badpasswordattempts` and `lastlogin` are valid matchers for this resource Properties ---------- ### gid The `gid` property tests the group identifier: ``` its('gid') { should eq 1234 } ``` where `1234` represents the user identifier. The `gid` option is only available on Linux and will return `nil` for Windows os. ### group The `group` property tests the group to which the user belongs: ``` its('group') { should eq 'root' } ``` where `root` represents the group. The `group` option is only available on Linux and will return `nil` for Windows os. ### groups The `groups` property tests two (or more) groups to which the user belongs: ``` its('groups') { should eq ['root', 'other'] } ``` ### home The `home` property tests the home directory path for the user: ``` its('home') { should eq '/root' } ``` ### maxdays The `maxdays` property tests the maximum number of days between password changes: ``` its('maxdays') { should eq 99 } ``` where `99` represents the maximum number of days. ### mindays The `mindays` property tests the minimum number of days between password changes: ``` its('mindays') { should eq 0 } ``` where `0` represents the maximum number of days. ### shell The `shell` property tests the path to the default shell for the user: ``` its('shell') { should eq '/bin/bash' } ``` ### uid The `uid` property tests the user identifier: ``` its('uid') { should eq 1234 } ``` where `1234` represents the user identifier. ### warndays The `warndays` property tests the number of days a user is warned before a password must be changed: ``` its('warndays') { should eq 5 } ``` where `5` represents the number of days a user is warned. ### passwordage The `passwordage` property tests the number of days a user changed its password: ``` its('passwordage') { should_be <= 365 } ``` where `365` represents the number of days since the last password change. ### maxbadpasswords The `maxbadpasswords` property tests the count of max badpassword settings for a specific user. ``` its('maxbadpasswords') { should eq 7 } ``` where `7` is the count of maximum bad password attempts. ### badpasswordattempts The `badpasswordattempts` property tests the count of bad password attempts for a user. ``` its('badpasswordattempts') { should eq 0 } ``` where `0` is the count of bad passwords for a user. On Linux based operating systems it relies on `lastb` and for Windows it uses information stored for the user object. These settings will be reset to `0` depending on your operating system configuration. ### lastlogin The `lastlogin` property tests the last login date for a specific user. ``` its('lastlogin') { should eq nil } ``` The `nil` value means this user has never logged in. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Verify available users for the MySQL server ``` describe user('root') do it { should exist } its('uid') { should eq 0 } its('groups') { should eq ['root'] } end describe user('mysql') do it { should_not exist } end ``` ### Test users on multiple platforms The `nginx` user is typically `www-data`, but on CentOS it’s `nginx`. The following example shows how to test for the `nginx` user with a single test, but accounting for all platforms: ``` web_user = 'www-data' web_user = 'nginx' if os[:family] == 'centos' describe user(web_user) do it { should exist } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `exist` matcher tests if the named user exists: ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/user/users resource ============== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/users.md) Use the `users` Chef InSpec audit resource to look up all local users available on the system, and then test specific properties of those users. This resource does not return information about users that may be located on other systems, such as LDAP or Active Directory. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `users` resource block declares a user name, and then one (or more) matchers: ``` describe users.where(uid: 0).entries do it { should eq ['root'] } its('uids') { should eq [1234] } its('gids') { should eq [1234] } end ``` where * `gid`, `group`, `groups`, `home`, `maxdays`, `mindays`, `shell`, `uid`, `warndays`, `passwordage`, `maxbadpasswords` and `badpasswordattempts` are valid matchers for this resource * `where(uid: 0).entries` represents a filter that runs the test only against matching users For example: ``` describe users.where { username =~ /.*/ } do it { should exist } end ``` or: ``` describe users.where { uid =~ /^S-1-5-[0-9-]+-501$/ } do it { should exist } end ``` Properties ---------- ### gid The `gid` property tests the group identifier: ``` its('gid') { should eq 1234 } } ``` where `1234` represents the user identifier. ### group The `group` property tests the group to which the user belongs: ``` its('group') { should eq 'root' } ``` where `root` represents the group. ### groups The `groups` property tests two (or more) groups to which the user belongs: ``` its('groups') { should eq ['root', 'other']} ``` ### home The `home` property tests the home directory path for the user: ``` its('home') { should eq '/root' } ``` ### maxdays The `maxdays` property tests the maximum number of days between password changes: ``` its('maxdays') { should eq 99 } ``` where `99` represents the maximum number of days. ### mindays The `mindays` property tests the minimum number of days between password changes: ``` its('mindays') { should eq 0 } ``` where `0` represents the maximum number of days. ### shell The `shell` property tests the path to the default shell for the user: ``` its('shells') { should eq ['/bin/bash'] } ``` ### uid The `uid` property tests the user identifier: ``` its('uid') { should eq 1234 } } ``` where `1234` represents the user identifier. ### warndays The `warndays` property tests the number of days a user is warned before a password must be changed: ``` its('warndays') { should eq 5 } ``` where `5` represents the number of days a user is warned. ### passwordage The `passwordage` property tests the number of days a user changed its password: ``` its('passwordage') { should_be <= 365 } ``` where `365` represents the number of days since the last password change. ### maxbadpasswords The `maxbadpasswords` property tests the count of max badpassword settings for a specific user. ``` its('maxbadpasswords') { should eq 7 } ``` where `7` is the count of maximum bad password attempts. ### badpasswordattempts The `badpasswordattempts` property tests the count of bad password attempts for a user. ``` its('badpasswordattempts') { should eq 0 } ``` where `0` is the count of bad passwords for a user. On Linux based operating systems it relies on `lastb` and for Windows it uses information stored for the user object. These settings will be resetted to `0` depending on your operating system configuration. Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Use a regular expression to find users: ``` describe users.where { uid =~ /S\-1\-5\-21\-\d+\-\d+\-\d+\-500/ } do it { should exist } end ``` ### Test that only allowed users exist: ``` allowed_users = %w(user1 user2 user3) users.where { uid > 1000 && uid < 65534 }.usernames.sort.each do |u| describe user(u) do if allowed_users.include?(u) it { should exist } else it { should_not exist } end end end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `exist` matcher tests if the named user exists: ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/users/virtualization resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/virtualization.md) Use the `virtualization` Chef InSpec audit resource to test the virtualization platform on which the system is running. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.28.0 of InSpec. Syntax ------ An `virtualization` resource block declares the virtualization platform that should be tested: ``` describe virtualization do its('system') { should MATCHER 'value' } end ``` where * `('system')` is the name of the system information of the virtualization platform (e.g. docker, lxc, vbox, kvm, etc) * `MATCHER` is a valid matcher for this resource * `'value'` is the value to be tested Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test for Docker ``` describe virtualization do its('system') { should eq 'docker' } end ``` ### Test for VirtualBox ``` describe virtualization do its('system') { should eq 'vbox' } its('role') { should eq 'guest' } end ``` ### Detect the virtualization platform ``` if virtualization.system == 'vbox' describe package('name') do it { should be_installed } end end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### virtualization.virtual_system? Helper This helper returns, if any of the supported virtualization platforms was detected and the machine under test is a guest. You can use this in a `only_if { virtual_system? }` clause to execute test only on virtualized systems. ### virtualization.physical_system? Helper If no virtualization platform is detected, this will return `true`. For unsupported virtualization platforms this can result in false posititves. ### virtualization.system names The resource supports the following virtualization platforms: On Linux machines: * `docker` (`guest` role only) * `hyper-v` (`guest` role only) * `kvm` * `linux vserver` * `lxc` / `lxd` * `openstack` (`host` role only) * `openvz` * `parallels` (`guest` role only) * `virtualbox` * `vmware` (`guest` role only) * `xen` On Windows machines (`guest` role only) * `hyper-v` * `kvm` * `vmware` * `virtualbox` * `xen` ### virtualization.role Can be either * `guest` * `host` Please see the documentation on `virtualization.system` to check supported roles per platform. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/virtualization/vbscript resource ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/vbscript.md) Use the `vbscript` Chef InSpec audit resource to test a VBScript on the Windows platform. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `vbscript` resource block tests the output of a VBScript on the Windows platform: ``` describe vbscript('script contents') do its('stdout') { should eq 'output' } end ``` where * `'script_name'` is the name of the VBScript to test * `('output')` is the expected output of the VBScript Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test a VBScript A VBScript file similar to: ``` script = <<-EOH WScript.Echo "hello" EOH ``` may be tested for multiple lines: ``` describe vbscript(script) do its('stdout') { should eq "hello\r\n" } end ``` and tested for whitespace removal from standard output: ``` describe vbscript(script) do its('strip') { should eq "hello" } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/vbscript/windows_feature resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/windows_feature.md) Use the `windows_feature` Chef InSpec audit resource to test features on Windows via the `Get-WindowsFeature` cmdlet. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `windows_feature` resource block declares the name of the Windows feature, tests if that feature is installed, and then returns information about that feature: ``` describe windows_feature('feature_name') do it { should be_installed } end ``` where * `('feature_name')` must specify a Windows feature name, such as `DHCP Server` or `IIS-Webserver` * `be_installed` is a valid matcher for this resource Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test the DHCP feature (Attempts PowerShell then DISM) ``` describe windows_feature('DHCP') do it{ should be_installed } end ``` ### Test the IIS-WebServer feature using DISM ``` describe windows_feature('IIS-WebServer', DISM) do it{ should be_installed } end ``` ### Test the NetFx3 feature using DISM ``` describe windows_feature('NetFx3', :dism) do it{ should be_installed } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_installed The `be_installed` matcher tests if the named Windows feature is installed: ``` it { should be_installed } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/windows_feature/windows_firewall resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/windows_firewall.md) Use the `windows_firewall` Chef InSpec audit resource to test if a firewall profile is correctly configured on a Windows system. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. Syntax ------ A `windows_firewall` resource block specifies which profile to validate: ``` describe windows_firewall('name') do it { should be_enabled } end ``` where * `('name')` must specify the name of a firewall profile, such as `'Public'`, `'Private'` or `'Domain'` * `be_enabled` is a valid matcher for this resource Examples -------- The following example shows how to use this Chef InSpec audit resource. ### Test if the firewall has the appropriate amount of rules and default Accept ``` describe windows_firewall('Public') do it { should be_enabled } it { should have_default_inbound_allowed } its('num_rules') { should eq 219 } end ``` Properties ---------- The resource compiles the following list of firewall profile properties: * `description` * `default_inbound_action` * `default_outbound_action` * `allow_inbound_rules` * `allow_local_firewall_rules` * `allow_local_ipsec_rules` * `allow_user_apps` * `allow_user_ports` * `allow_unicast_response_to_multicast` * `notify_on_listen` * `enable_stealth_mode_for_ipsec` * `log_max_size_kilobytes` * `log_allowed` * `log_blocked` * `log_ignored` * `num_rules` Each of these properties can be used in two distinct ways: ``` its('default_inbound_action') { should cmp 'Allow' } ``` or via matcher: ``` it { should have_default_inbound_action 'Allow' } ``` Shortcuts are defined for: * `have_default_inbound_allow?` * `have_default_outbound_allow?` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if the Profile is enabled: ``` it { should be_enabled } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/windows_firewall/windows_firewall_rule resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/windows_firewall_rule.md) Use the `windows_firewall_rule` Chef InSpec audit resource to test if a firewall rule is correctly configured on a Windows system. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. Syntax ------ A `windows_firewall_rule` resource block specifies which rule to validate: ``` describe windows_firewall_rule('name') do it { should be_enabled } end ``` where * `('name')` must specify the name of a firewall rule, which is not the firewall rule’s display name * `be_enabled` is a valid matcher for this resource Examples -------- The following example shows how to use this Chef InSpec audit resource. ### Test If the Firewall Contains a Rule for Outbound HTTPS ``` describe windows_firewall_rule('HTTPS Out') do it { should be_enabled } it { should be_allowed } it { should be_outbound } it { should be_tcp } its('remote_port') { should eq 443 } end ``` Properties ---------- The resource compiles the following list of firewall rule properties: * `description` * `displayname` * `group` * `local_address` * `local_port` * `remote_address` * `remote_port` * `direction` * `protocol` * `icmp_type` * `action` * `profile` * `program` * `service` * `interface_type` Each of these properties can be used in two distinct ways: ``` its('remote_address') { should cmp '192.0.2.42' } ``` or via matcher: ``` it { should have_remote_address '192.0.2.42' } ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `be_enabled` matcher tests if the rule does exist: ``` it { should exist } ``` ### be_enabled The `be_enabled` matcher tests if the rule is enabled: ``` it { should be_enabled } ``` ### be_allowed The `be_allowed` matcher tests if the rule is allowing traffic: ``` it { should be_allowed } ``` ### be_inbound The `be_inbound` matcher tests if the rule is an inbound rule: ``` it { should be_inbound } ``` ### be_outbound The `be_outbound` matcher tests if the rule is an outbound rule: ``` it { should be_outbound } ``` ### be_tcp The `be_tcp` matcher tests if the rule is for the TCP protocol: ``` it { should be_tcp } ``` ### be_ucp The `be_ucp` matcher tests if the rule is for the DCP protocol: ``` it { should be_dcp } ``` ### be_icmp The `be_icmp` matcher tests if the rule is for any ICMP protocol: ``` it { should be_icmp } ``` ### be_icmpv4 The `be_icmpv4` matcher tests if the rule is for the ICMPv4 protocol: ``` it { should be_icmpv4 } ``` ### be_icmpv6 The `be_icmpv6` matcher tests if the rule is for any ICMPv6 protocol: ``` it { should be_icmpv6 } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/windows_firewall_rule/windows_hotfix resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/windows_hotfix.md) Use the `windows_hotfix` Chef InSpec audit resource to test if the hotfix has been installed on a Windows system. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.39.1 of InSpec. Syntax ------ A `windows_hotfix` resource block declares a hotfix to validate: ``` describe windows_hotfix('name') do it { should be_installed } end ``` where * `('name')` must specify the name of a hotfix, such as `'KB4012213'` * `be_installed` is a valid matcher for this resource Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if KB4012213 is installed ``` describe windows_hotfix('KB4012213') do it { should be_installed } end ``` ### Test that a hotfix is not installed ``` describe windows_hotfix('KB9999999') do it { should_not be_installed } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_installed The `be_installed` matcher tests if the named hotfix is installed on the system: ``` it { should be_installed } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/windows_hotfix/wmi resource ============ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/wmi.md) Use the `wmi` Chef InSpec audit resource to test WMI settings on the Windows platform. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `wmi` resource block tests WMI settings on the Windows platform: ``` describe wmi({ class: 'class_name', namespace: 'path\\to\\setting', filter: 'filter', query: 'query' }) do its('setting_name') { should eq '' } end ``` where * `class`, `namespace`, `filter`, and `query` comprise a Ruby Hash of the WMI object * `('class')` is the WMI class to which the setting belongs, such as `win32_service` * `('namespace')` is path to that object, such as `root\\cimv2` * Use `('filter')` fine-tune the information defined by the WMI class, such as to find a specific service (`filter: "name like '%winrm%'")`, to find a specific setting (`filter: 'KeyName = \'MinimumPasswordAge\' And precedence=1'`), and so on * Use `('query')` to run a query that returns data to be tested, such as `"SELECT Setting FROM RSOP_SecuritySettingBoolean WHERE KeyName='LSAAnonymousNameLookup' AND Precedence=1"` * `('setting_name')` is a setting in the WMI object to be tested, and then `should eq ''` is the expected value for that setting For example, both of the following tests will verify if WinRM is present on the target node. The first tests if WinRM belongs to the list of services running under the `win32_service` class: ``` describe wmi({class: 'win32_service'}) do its('DisplayName') { should include 'Windows Remote Management (WS-Management)'} end ``` and the second uses a filter in the Ruby Hash to first identify WinRM, and then perform additional tests: ``` describe wmi({ class: 'win32_service', filter: "name like '%winrm%'" }) do its('Status') { should cmp 'ok' } its('State') { should cmp 'Running' } its('ExitCode') { should cmp 0 } its('DisplayName') { should eq 'Windows Remote Management (WS-Management)'} end ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test a password expiration policy ``` describe wmi({ class: 'RSOP_SecuritySettingNumeric', namespace: 'root\\rsop\\computer', filter: 'KeyName = \'MinimumPasswordAge\' And precedence=1' }) do its('Setting') { should eq 1 } end ``` ### Test if an anonymous user can query the Local Security Authority (LSA) ``` describe wmi({ namespace: 'root\\rsop\\computer', query: "SELECT Setting FROM RSOP_SecuritySettingBoolean WHERE KeyName='LSAAnonymousNameLookup' AND Precedence=1" }) do its('Setting') { should eq false } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/wmi/windows_task resource ====================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/windows_task.md) Use the `windows_task` Chef InSpec audit resource to test a scheduled tasks configuration on a Windows platform. Microsoft and application vendors use scheduled tasks to perform a variety of system maintenance tasks but system administrators can schedule their own. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.10.0 of InSpec. Syntax ------ A `windows_task` resource block declares the name of the task (as its full path) and tests its configuration: ``` describe windows_task('task name uri') do its('parameter') { should eq 'value' } it { should be_enabled } end ``` where * `'parameter'` must be a valid parameter defined within this resource ie `logon_mode`, `last_result`, `task_to_run`, `run_as_user` * `'value'` will be used to compare the value gather from your chosen parameter * `'be_enabled'` is an example of a valid matcher that checks the state of a task, other examples are `exist` or `be_disabled` Examples -------- The following examples show how to use this Chef InSpec resource. ### Tests that a task is enabled ``` describe windows_task('\Microsoft\Windows\Time Synchronization\SynchronizeTime') do it { should be_enabled } end ``` ### Tests that a task is disabled ``` describe windows_task('\Microsoft\Windows\AppID\PolicyConverter') do it { should be_disabled } end ``` ### Tests the configuration parameters of a task ``` describe windows_task('\Microsoft\Windows\AppID\PolicyConverter') do its('logon_mode') { should eq 'Interactive/Background' } its('last_result') { should eq '1' } its('task_to_run') { should cmp '%Windir%\system32\appidpolicyconverter.exe' } its('run_as_user') { should eq 'LOCAL SERVICE' } end ``` ### Tests that a task is defined ``` describe windows_task('\Microsoft\Windows\Defrag\ScheduledDefrag') do it { should exist } end ``` Gathering Tasknames ------------------- Rather then use the GUI you can use the `schtasks.exe` to output a full list of tasks available on the system `schtasks /query /FO list` rather than use the `list` output you can use `CSV` if it is easier. Please make sure you use the full TaskName (include the prefix `\`) within your control ``` C:\>schtasks /query /FO list ... Folder: \Microsoft\Windows\Diagnosis HostName: XPS15 TaskName: \Microsoft\Windows\Diagnosis\Scheduled Next Run Time: N/A Status: Ready Logon Mode: Interactive/Background ... ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/windows_task/x509_certificate resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/x509_certificate.md) Use the `x509_certificate` Chef InSpec audit resource to test the fields and validity of an x.509 certificate. X.509 certificates use public/private key pairs to sign and encrypt documents or communications over a network. They may also be used for authentication. Examples include SSL certificates, S/MIME certificates and VPN authentication certificates. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.18.0 of InSpec. Syntax ------ An `x509_certificate` resource block declares a certificate `key file` to be tested. ``` describe x509_certificate('mycertificate.pem') do its('validity_in_days') { should be > 30 } end ``` The `filepath` property can also be used. ``` describe x509_certificate(filepath: 'mycertificate.pem') do its('validity_in_days') { should be > 30 } end ``` The resource also supports passing in the certificate content. ``` cert_content = file('certificate.pem').content describe x509_certificate(content: cert_content) do its('validity_in_days') { should be > 30 } end ``` If both `content` and `filepath` is given, the value passed in `content` is used. Properties ---------- ### subject.XX `subject` property makes it easier to access individual subject elements. ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do its('subject.CN') { should eq "www.mywebsite.com" } end ``` ### subject_dn (String) The `subject_dn` string returns the distinguished name of the subject field. It contains several fields separated by forward slashes. The field identifiers are the same ones used by OpenSSL to generate CSR’s and certs. Use `subject.XX` instead to access the parsed version. e.g. `/C=US/L=Seattle/O=Chef Software Inc/OU=Chefs/CN=<NAME>` ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do its('subject_dn') { should match "CN=www.mywebsite.com" } end ``` ### issuer.XX `issuer` makes it easier to access individual issuer elements. ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do its('issuer.CN') { should eq "Acme Trust CA" } end ``` ### issuer_dn (String) The `issuer_dn` is the distinguished name from a CA (certificate authority) during the certificate signing process. It describes which authority is guaranteeing the identity of our certificate. e.g. `/C=US/L=Seattle/CN=Acme Trust CA/emailAddress=<EMAIL>` ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do its('issuer_cn') { should match "CN=Acme Trust CA" } end ``` ### public_key (String) The `public_key` property returns a base64 encoded public key in PEM format. ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do its('public_key') { should match "-----BEGIN PUBLIC KEY-----\nblah blah blah..." } end ``` ### key_length (Integer) The `key_length` property calculates the number of bits in the public key. More bits increase security, but at the cost of speed and in extreme cases, compatibility. ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do its('key_length') { should be 2048 } end ``` ### signature_algorithm (String) The `signature_algorithm` property describes which hash function was used by the CA to sign the certificate. ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do its('signature_algorithm') { should be 'sha256WithRSAEncryption' } end ``` ### validity_in_days (Float) The `validity_in_days` property can be used to check that certificates are not in danger of expiring soon. ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do its('validity_in_days') { should be > 30 } end ``` ### not_before and not_after (Time) The `not_before` and `not_after` properties expose the start and end dates of certificate validity. They are exposed as ruby Time class so that date arithmetic can be easily performed. ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do its('not_before') { should be <= Time.utc.now } its('not_after') { should be >= Time.utc.now } end ``` ### serial (Integer) The `serial` property exposes the serial number of the certificate. The serial number is set by the CA during the signing process and should be unique within that CA. ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do its('serial') { should eq 9623283588743302433 } end ``` ### version (Integer) The `version` property exposes the certificate version. ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do its('version') { should eq 2 } end ``` ### extensions (Hash) The `extensions` hash property is mainly used to determine what the certificate can be used for. ``` describe x509_certificate('/etc/pki/www.mywebsite.com.pem') do # Check what extension categories we have its('extensions') { should include 'keyUsage' } its('extensions') { should include 'extendedKeyUsage' } its('extensions') { should include 'subjectAltName' } # Check examples of basic 'keyUsage' its('extensions.keyUsage') { should include 'Digital Signature' } its('extensions.keyUsage') { should include 'Non Repudiation' } its('extensions.keyUsage') { should include 'Data Encipherment' } # Check examples of newer 'extendedKeyUsage' its('extensions.extendedKeyUsage') { should include 'TLS Web Server Authentication' } its('extensions.extendedKeyUsage') { should include 'Code Signing' } # Check examples of 'subjectAltName' its('extensions.subjectAltName') { should include 'email:<EMAIL>' } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/x509_certificate/xinetd_conf resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/xinetd_conf.md) Use the `xinetd_conf` Chef InSpec audit resource to test services under `/etc/xinet.d` on Linux and Unix platforms. xinetd—the extended Internet service daemon—listens on all ports, and then loads the appropriate program based on a request. The `xinetd.conf` file is typically located at `/etc/xinetd.conf` and contains a list of Internet services associated to the ports on which that service will listen. Only enabled services may handle a request; only services that are required by the system should be enabled. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ An `xinetd_conf` resource block declares settings found in a `xinetd.conf` file for the named service: ``` describe xinetd_conf.services('service_name') do it { should be_enabled } # or be_disabled its('setting') { should eq 'value' } end ``` where * `'service_name'` is a service located under `/etc/xinet.d` * `('setting')` is a setting in the `xinetd.conf` file * `should eq 'value'` is the value that is expected Properties ---------- ### ids The `ids` property tests if the named service is located under `/etc/xinet.d`: ``` its('ids') { should include 'service_name' } ``` For example: ``` its('ids') { should include 'chargen-stream chargen-dgram'} ``` ### services The `services` property tests if the named service is listed under `/etc/xinet.d`: ``` its('services') { should include 'service_name' } ``` ### socket_types The `socket_types` property tests if a service listed under `/etc/xinet.d` is configured to use the named socket type. Use `socket` if the socket type is `dgram`, `raw`, or `stream`: ``` its('socket_types') { should eq 'socket' } ``` For a UDP-based service: ``` its('socket_types') { should eq 'dgram' } ``` For a raw socket (such as a service using a non-standard protocol or a service that requires direct access to IP): ``` its('socket_types') { should eq 'raw' } ``` For a TCP-based service: ``` its('socket_types') { should eq 'stream' } ``` ### types The `types` property tests the service type: ``` its('type') { should eq 'TYPE' } ``` where `'TYPE'` is `INTERNAL` (for a service provided by xinetd), `RPC` (for a service based on remote procedure call), or `UNLISTED` (for services not under `/etc/services` or `/etc/rpc`). ### wait The `wait` property tests how a service handles incoming connections. For UDP (`dgram`) socket types, the `wait` property should test for `yes`: ``` its('socket_types') { should eq 'dgram' } its('wait') { should eq 'yes' } ``` For TCP (`stream`) socket types, the `wait` property should test for `no`: ``` its('socket_types') { should eq 'stream' } its('wait') { should eq 'no' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test a socket_type The network socket type: `dgram` (a datagram-based service), `raw` (a service that requires direct access to an IP address), `stream` (a stream-based service), or `seqpacket` (a service that requires a sequenced packet). ``` describe xinetd_conf.services('service_name') do its('socket_types') { should include 'dgram' } end ``` ### Test a service type The type of service: `INTERNAL` (a service provided by xinetd), `RPC` (an RPC-based service), `TCPMUX` (a service that is started on a well-known TCPMUX port), or `UNLISTED` (a service that is not listed in a standard system file location). ``` describe xinetd_conf.services('service_name') do its('type') { should include 'RPC' } end ``` ### Test the telnet service For example, a `telnet` file under `/etc/xinet.d` contains the following settings: ``` service telnet { disable = yes flags = REUSE socket_type = stream wait = no user = root server = /usr/sbin/in.telnetd log_on_failure += USERID } ``` Some examples of tests that can be run against that file include: ``` describe xinetd_conf.services('telnet') do it { should be_disabled } end ``` and ``` describe xinetd_conf.services('telnet') do its('socket_type') { should include 'stream' } end ``` and ``` describe xinetd_conf.services('telnet') do its('wait') { should eq 'no' } end ``` All three settings can be tested in the same block as well: ``` describe xinetd_conf.services('telnet') do it { should be_disabled } its('socket_type') { should include 'stream' } its('wait') { should eq 'no' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if a service listed under `/etc/xinet.d` is enabled: ``` it { should be_enabled } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/xinetd_conf/yaml resource ============= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/yaml.md) Use the `yaml` Chef InSpec audit resource to test configuration data in a Yaml file. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `yaml` resource block declares the configuration data to be tested. Assume the following Yaml file: ``` name: foo array: - zero - one ``` This file can be queried using: ``` describe yaml('filename.yml') do its('name') { should eq 'foo' } its(['array', 1]) { should eq 'one' } end ``` where * `name` is a configuration setting in a Yaml file * `should eq 'foo'` tests a value of `name` as read from a Yaml file versus the value declared in the test Like the `json` resource, the `yaml` resource can read a file, run a command, or accept content inline: ``` describe yaml('config.yaml') do its(['driver', 'name']) { should eq 'vagrant' } end describe yaml({ command: 'retrieve_data.py --yaml' }) do its('state') { should eq 'open' } end describe yaml({ content: "\"key1: value1\nkey2: value2\"" }) do its('key2') { should cmp 'value2' } end ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test a kitchen.yml file driver ``` describe yaml('.kitchen.yaml') do its(['driver','name']) { should eq('vagrant') } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### name The `name` matcher tests the value of `name` as read from a Yaml file versus the value declared in the test: ``` its('name') { should eq 'foo' } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/yaml/xml resource ============ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/xml.md) Use the `xml` Chef InSpec audit resource to test data in an XML file. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.37.6 of InSpec. Syntax ------ An `xml` resource block declares the data to be tested. Assume the following XML file: ``` <root> <name>hello</name> <meta> <creator><NAME></creator> </meta> <array> <element>one</element> <element>two</element> </array> <array> <element value="one"></element> <element value="two"></element> </array> </root``` This file can be queried for elements using: ``` describe xml('/path/to/name.xml') do its('root/name') { should eq ['hello'] } its('root/meta/creator') { should eq ['<NAME>'] } its('root/array[2]/element') { should eq ['two'] } end ``` This file can be queried for attributes using: ``` describe xml('/path/to/name.xml') do its('root/array[2]/element/@value') { should eq ['one', 'two'] } its('root/array[2]/element/attribute::value') { should eq ['one', 'two'] } its('root/array[2]/element[2]/attribute::value') { should eq ['two'] } its('count(//*)') { should eq [42] } its('boolean(root/array[2]/element[2]/@valid)') { should eq [false] } end ``` where * `root/name` and `root/array[2]/element/@value` is an XPath expression * `should eq ['foo']` tests a value of `root/name` as read from an XML file versus the value declared in the test In the above example, you see the use of `@` and `attribute::` which are both methods of fetching attributes. In the event the path contains an element which contains periods, the alternate syntax can be used: ``` its(['root/name.with.a.period']) { should cmp 'so_many_dots' } ``` Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test an AppPool’s presence in an applicationHost.config file or the default site under applicationHost.sites ``` describe xml('applicationHost.config') do # using the alternate syntax as described above because of the . in the key name its(['configuration/system.applicationHost/applicationPools/add@name']) { should contain('my_pool') } end describe xml('applicationHost.sites') do its('site[@name="Default Web Site"]/application/virtualDirectory/@path') { should eq ['/'] } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### name The `name` matcher tests the value of `name` as read from a JSON file versus the value declared in the test: ``` its('name') { should eq 'foo' } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/xml/aws_alb resource ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_alb.md) Use the `aws_alb` InSpec audit resource to test properties of a single AWS Application Load Balancer (ALB). Syntax ------ Ensure that an `aws_alb` exists ``` describe aws_alb('arn:aws:elasticloadbalancing') do it { should exist } end describe aws_alb(load_balancer_arn: 'arn:aws:elasticloadbalancing') do it { should exist } end ``` Parameters ---------- ### load_balancer_arn *(required)* This resource accepts a single parameter, the ALB Arn which uniquely identifies the ALB. This can be passed either as a string or as a `load_balancer_arn: 'value'` key-value entry in a hash. See also the [AWS documentation on Elastic Load Balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference). Properties ---------- | Property | Description | | --- | --- | | load_balancer_name | The name of the load balancer. | | load_balancer_addresses | A collection of the load balancer addresses. | | canonical_hosted_zone_id | The ID of the Amazon Route 53 hosted zone for the load balancer. | | dns_name | The DNS name of the load balancer. | | availability_zones | The Availability Zones for the load balancer. | | security_groups | The security groups for the load balancer. Valid only for load balancers in a VPC. | | scheme | The type of load balancer. Valid only for load balancers in a VPC. | | state | The state of the load balancer. | | subnets | A collection of the subnet ids. | | type | The type of the load balancer. | | vpc_id | The ID of the VPC for the load balancer. | | zone_names | A collection of the names of the availability zones. | | listeners | A collection of the listeners for the load balancer. | | ssl_policies | A list of the SSL Policies configured for the listeners of the load balancer. | | external_ports | A list of the ports configured for the listeners of the load balancer. | | protocols | A list of the protocols configured for the listeners of the load balancer. | Examples -------- ### Test that an ALB has its availability zones configured correctly ``` describe aws_alb('arn::alb') do its('zone_names.count') { should be > 1 } its('zone_names') { should include 'us-east-2a' } its('zone_names') { should include 'us-east-2b' } end ``` Matchers -------- This InSpec audit resource has no special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_alb('AnExistingALB') do it { should exist } end describe aws_alb('ANonExistentALB') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `elasticloadbalancing:DescribeLoadBalancers` action set to Allow. You can find detailed documentation at [Authentication and Access Control for Your Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/load-balancer-authentication-access-control.html) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_alb/yum resource ============ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/yum.md) Use the `yum` Chef InSpec audit resource to test packages in the Yum repository. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `yum` resource block declares a package repo, tests if the package repository is present, and if it that package repository is a valid package source (i.e. “is enabled”): ``` describe yum.repo('name') do it { should exist } it { should be_enabled } end ``` where * `repo('name')` is the (optional) name of a package repo, using either a full identifier (`'updates/7/x86_64'`) or a short identifier (`'updates'`) Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test if the yum repo exists ``` describe yum do its('repos') { should exist } end ``` ### Test if the ‘base/7/x86_64’ repo exists and is enabled ``` describe yum do its('repos') { should include 'base/7/x86_64' } its('epel') { should exist } its('epel') { should be_enabled } end ``` ### Test if a specific yum repo exists ``` describe yum.repo('epel') do it { should exist } it { should be_enabled } end ``` ### Test a particular repository configuration, such as its Base URL ``` describe yum.repo('mycompany-artifacts') do it { should exist } it { should be_enabled } its('baseurl') { should include 'mycompany.biz' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_enabled The `be_enabled` matcher tests if the package repository is a valid package source: ``` it { should be_enabled } ``` ### exist The `exist` matcher tests if the package repository exists: ``` it { should exist } ``` ### repo(‘name’) The `repo('name')` matcher names a specific package repository: ``` describe yum.repo('epel') do ... end ``` ### repos The `repos` matcher tests if a named repo, using either a full identifier (`'updates/7/x86_64'`) or a short identifier (`'updates'`), is included in the Yum repo: ``` its('repos') { should include 'some_repo' } ``` ### shortname The `shortname` matcher names a specific package repository’s group identifier. For example, if a repository’s group name is “Directory Server”, the corresponding group identifier is typically “directory-server”: ``` describe yum.repo('Directory Server') do its('shortname') { should eq 'directory-server' } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/yum/zfs_dataset resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/zfs_dataset.md) Use the `zfs_dataset` Chef InSpec audit resource to test the ZFS datasets on FreeBSD & Linux (Check [OS Family Details](../os/index#osfamily-helpers) for more details). Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.16.0 of InSpec. Syntax ------ A `zfs_dataset` resource block declares the ZFS dataset properties that should be tested: ``` describe zfs_dataset('dataset') do it { should MATCHER 'value' } end ``` where * `('dataset')` is the name of the ZFS dataset (eg: `'tank/tmp'`) * `MATCHER` is a valid matcher for this resource * `'value'` is the value to be tested Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test a dataset of ‘tank/tmp’ ``` describe zfs_dataset('tank/tmp') do it { should be_mounted } its('atime') { should eq 'on' } its('compression') { should eq 'lz4' } its('exec') { should eq 'off' } its('readonly') { should eq 'off' } its('setuid') { should eq 'off' } end ``` Matchers -------- This Chef InSpec audit resource has the matchers listed below, in addition to dynamically exposing all ZFS dataset properties available (see: `man zfs` for the list of supported properties). For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_mounted The `be_mounted` matcher tests if the dataset is accessible from the file system: ``` it { should be_mounted } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/zfs_dataset/aws_auto_scaling_group resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_auto_scaling_group.md) Use the `aws_auto_scaling_group` InSpec audit resource to test properties of a single AWS Auto Scaling group. Syntax ------ Ensure that an auto scaling group exists and has the correct scale sizes ``` describe aws_auto_scaling_group('MyAutoScalingGroup') do it { should exist } its('min_size') { should be 1} its('max_size') { should be 4} end ``` You may also use hash syntax to pass the auto scaling group name ``` describe aws_auto_scaling_group(name: 'MyAutoScalingGroup') do it { should exist } end ``` Parameters ---------- ### name *(required)* This resource accepts a single parameter, the Auto Scaling Group Name which uniquely identifies the auto scaling group. This can be passed either as a string or as a `name: 'value'` key-value entry in a hash. See also the [AWS documentation on Auto Scaling Group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html). Properties ---------- | Property | Description | | --- | --- | | min_size | An integer indicating the minimum number of instances in the auto scaling group | | maximum_size | An integer indicating the maximum number of instances in the auto scaling group | | desired_capacity | An integer indicating the desired number of instances in the auto scaling group | | launch_configuration_name | The name of the auto scaling launch configuration associated with the auto scaling group | | vpc_zone_identifier | An array of strings corresponding to the subnet IDs associated with the auto scaling group | | tags | An hash with each key-value pair corresponding to a tag associated with the entity | Examples -------- ### Ensure that an auto scaling group has the correct desired capacity ``` describe aws_auto_scaling_group('MyAutoScalingGroup') do it { should exist } its('desired_capacity') { should be 2 } end ``` ### Ensure that an auto scaling group has the correct Launch Configuration name and VPC identifier ``` describe aws_auto_scaling_group('MyAutoScalingGroup') do it { should exist } its('launch_configuration_name') { should eq 'MyLaunchConfiguration'} its('vpc_zone_identifier') { should include 'subnet-1234'} end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_auto_scaling_group('AnExistingASG') do it { should exist } end describe aws_auto_scaling_group('ANonExistentASG') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `autoscaling:Describe*` actions with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon Auto Scaling Groups](https://docs.aws.amazon.com/autoscaling/ec2/userguide/control-access-using-iam.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_auto_scaling_group/zfs_pool resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/zfs_pool.md) Use the `zfs_pool` Chef InSpec audit resource to test the ZFS pools on FreeBSD & Linux (Centos, RHEL, Ubuntu, CloudLinux, Debian) systems. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.16.0 of InSpec. Syntax ------ A `zfs_pool` resource block declares the ZFS pool properties that should be tested: ``` describe zfs_pool('pool') do it { should MATCHER 'value' } end ``` where: * `('pool')` is the name of the ZFS pool (eg: `'tank'`) * `MATCHER` is a valid matcher for this resource * `'value'` is the value to be tested Properties ---------- This Chef InSpec audit resource dynamically exposes all ZFS pool properties available (see: `man zpool` for the list of supported properties). Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test a pool of ‘tank’ ``` describe zfs_pool('tank') do its('autoexpand') { should eq 'off' } its('failmode') { should eq 'continue' } its('feature@lz4_compress') { should eq 'active' } its('health') { should eq 'ONLINE' } its('listsnapshots') { should eq 'off' } its('readonly') { should eq 'off' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/zfs_pool/aws_cloudformation_stack resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_cloudformation_stack.md) Use the `aws_cloudformation_stack` InSpec audit resource to test properties of a single AWS Cloud Formation Stack. Syntax ------ Ensure that an `aws_cloudformation_stack` exists ``` describe aws_cloudformation_stack('stack-name') do it { should exist } end describe aws_cloudformation_stack(stack_name: 'stack-name') do it { should exist } end ``` Parameters ---------- ### stack_name *(required)* This resource accepts a single parameter, the CloudFormation Stack name which uniquely identifies the stack. This can be passed either as a string or as a `stack_name: 'value'` key-value entry in a hash. See also the [AWS documentation on Cloud Formation](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/Welcome.html). Properties ---------- | Property | Description | | --- | --- | | stack_id | Unique identifier of the stack. | | stack_name | The name associated with the stack. | | change_set_id | The unique ID of the change set. | | description | A user-defined description associated with the stack. | | parameters | A list of Parameter structures. | | creation_time | The time at which the stack was created. | | deletion_time | The time the stack was deleted. | | last_updated_time | The time the stack was last updated. | | rollback_configuration | The rollback triggers for AWS CloudFormation to monitor during stack creation and updating operations, and for the specified monitoring period afterwards. | | stack_status | Current status of the stack. | | stack_status_reason | Success/failure message associated with the stack status. | | drift_information | Information on whether a stack’s actual configuration differs, or has drifted, from it’s expected configuration, as defined in the stack template and any values specified as template parameters. | | disable_rollback | Boolean to enable or disable rollback on stack creation failures: | | notification_arns | SNS topic ARNs to which stack related events are published. | | timeout_in_minutes | The amount of time within which stack creation should complete. | | capabilities | The capabilities allowed in the stack. | | outputs | A list of output structures. | | role_arn | The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role that is associated with the stack. | | tags | A list of Tags that specify information about the stack. | | enable_termination_protection | Whether termination protection is enabled for the stack. | | parent_id | For nested stacks–stacks created as resources for another stack–the stack ID of the direct parent of this stack. | | root_id | For nested stacks–stacks created as resources for another stack–the stack ID of the the top-level stack to which the nested stack ultimately belongs. | Examples -------- ### Test that a CloudFormation Stack has its stack_status configured correctly ``` describe aws_cloudformation_stack('stack_name') do its ('stack_status') { should eq 'CREATE_COMPLETE' } end ``` Matchers -------- This InSpec audit resource has no special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_cloudformation_stack('AnExistingStack') do it { should exist } end describe aws_cloudformation_stack('ANonExistentStack') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `cloudformation:DescribeStacks` action set to Allow. You can find detailed documentation at [Authentication and Access Control for CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_cloudformation_stack/aws_albs resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_albs.md) Use the `aws_albs` InSpec audit resource to test the configuration of a collection of Application Load Balancers. Syntax ------ Ensure that an `aws_albs` exists ``` describe aws_albs do its('load_balancer_arns') { should include 'arn:aws:elasticloadbalancing' } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on Elastic Load Balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference). Properties ---------- | Property | Description | | --- | --- | | load_balancer_names | The names of the load balancers. | | load_balancer_addresses | A collection of the load balancers addresses. | | canonical_hosted_zone_ids | The IDs of the Amazon Route 53 hosted zone for the load balancers. | | dns_names | The DNS names of the load balancers. | | availability_zones | The Availability Zones for the load balancers. | | security_groups | The security groups for the load balancers. Valid only for load balancers in a VPC. | | schemes | The types of load balancers. Valid only for load balancers in a VPC. | | states | The states of the load balancers. | | subnets | A collection of the subnet ids. | | types | The types of the load balancers. | | vpc_ids | The IDs of the VPCs for the load balancers. | | zone_names | A collection of the names of the availability zones. | Examples -------- ### Test that an ALB has its availability zones configured correctly ``` describe aws_alb('arn::alb') do its('zone_names.count') { should be > 1 } its('zone_names') { should include 'us-east-2a' } its('zone_names') { should include 'us-east-2b' } end ``` Matchers -------- This InSpec audit resource has no special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_albs do it { should exist } its('availability_zones') { should_not include 'us-east-1a'} end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `elasticloadbalancing:DescribeLoadBalancers` action set to Allow. You can find detailed documentation at [Authentication and Access Control for Your Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/load-balancer-authentication-access-control.html) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_albs/aws_cloudtrail_trails resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_cloudtrail_trails.md) Use the `aws_cloudtrail_trails` InSpec audit resource to test properties of a collection of AWS CloudTrail Trails. Syntax ------ An `aws_cloudtrail_trails` resource block returns all CloudTrail Trails and allows the testing of those trails. ``` describe aws_cloudtrail_trails do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on Auto Scaling Group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html). Properties ---------- | Property | Description | | --- | --- | | trail_arns | Specifies the ARNs of the trails. | | names | The names of the trails. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Ensure a CloudTrail with a specific name exists ``` describe aws_cloudtrail_trails do its('names') { should include('trail-1') } end ``` ### Ensure a CloudTrail with a specific arn exists ``` describe aws_cloudtrail_trails do its('trail_arns') { should include('arn:aws:cloudtrail:us-east-1::trail/trail-1') } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_cloudtrail_trails do it { should exist } end describe aws_cloudtrail_trails do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `cloudtrail:DescribeTrails` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for AWS CloudTrail](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awscloudtrail.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_cloudtrail_trails/aws_auto_scaling_groups resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_auto_scaling_groups.md) Use the `aws_auto_scaling_groups` InSpec audit resource to test the properties of a collection of AWS Auto Scaling Groups. Syntax ------ An `aws_auto_scaling_groups` resource block returns all Auto Scaling Groups and allows the testing of those ASGs. ``` describe aws_auto_scaling_groups do its('names') { should include 'group-name' } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on Auto Scaling Group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html). Properties ---------- | Property | Description | | --- | --- | | min_sizes | An integer indicating the minimum number of instances in the auto scaling group | | max_sizes | An integer indicating the maximum number of instances in the auto scaling group | | desired_capacities | An integer indicating the desired number of instances in the auto scaling group | | launch_configuration_names | The name of the auto scaling launch configuration associated with the auto scaling group | | vpc_zone_identifiers | An array of strings corresponding to the subnet IDs associated with the auto scaling group | | health_check_types | The service to use for the health checks. The valid values are EC2 and ELB. | | tags | A hash of key-value pairs corresponding to the tags associated with the entity. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Ensure there are no groups with incorrect vpc_zone_identifiers. ``` describe aws_auto_scaling_groups do it { should exist } its('vpc_zone_identifiers') { should_not include 'UNDESIRED-ZONE'} end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_auto_scaling_groups.where( <property>: <value>) do it { should exist } end describe aws_auto_scaling_groups.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `autoscaling:Describe*` actions with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon Auto Scaling Groups](https://docs.aws.amazon.com/autoscaling/ec2/userguide/control-access-using-iam.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_auto_scaling_groups/aws_cloudtrail_trail resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_cloudtrail_trail.md) Use the `aws_cloudtrail_trail` InSpec audit resource to test properties of a single AWS CloudTrail. Syntax ------ An `aws_cloudtrail_trail` resource block identifies a trail by `trail_name`. ``` # Find a trail by name describe aws_cloudtrail_trail('trail-name') do it { should exist } end # Hash syntax for trail name describe aws_cloudtrail_trail(trail_name: 'trail-name') do it { should exist } end ``` Parameters ---------- ### trail_name *(required)* This resource expects a single parameter, the CloudTrail Name which uniquely identifies it. This can be passed either as a string or as a `trail_name: 'value'` key-value entry in a hash. See also the [AWS documentation on CloudTrail](https://docs.aws.amazon.com/cloudtrail/index.html#lang/en_us). Properties ---------- | Property | Description | | --- | --- | | trail_arn | Specifies the ARN of the trail. | | trail_name | Name of the trail. | | home_region | The region in which the trail was created. | | s3_bucket_name | Name of the Amazon S3 bucket into which CloudTrail delivers your trail files. | | cloud_watch_logs_role_arn | Specifies the role for the CloudWatch Logs endpoint to assume to write to a user’s log group. | | cloud_watch_logs_log_group_arn | Specifies an Amazon Resource Name (ARN), a unique identifier that represents the log group to which CloudTrail logs will be delivered. | | kms_key_id | Specifies the KMS key ID that encrypts the logs delivered by CloudTrail. | Examples -------- ### Test that the specified trail does exist ``` describe aws_cloudtrail_trail('my-cloudtrail') do it { should exist } end describe aws_cloudtrail_trail(trail_name: 'my-cloudtrail') do it { should exist } end ``` ### Check the KMS key used to encrypt ``` describe aws_cloudtrail_trail('my-cloudtrail') do its('kms_key_id') { should eq "my-kms-key" } end ``` ### Check the Home Region is correct ``` describe aws_cloudtrail_trail('my-cloudtrail') do its('home_region') { should eq 'us-east-1' } end ``` ### Test that the specified trail is a multi-region trail ``` describe aws_cloudtrail_trail('my-cloudtrail') do it { should be_multi_region_trail } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` # Verify that at least one CloudTrail Trail exists. describe aws_cloudtrail_trail('my-cloudtrail') do it { should exist } end ``` ### be_multi_region_trail The test will pass if the identified trail is a multi-region trail. ``` describe aws_cloudtrail_trail('my-cloudtrail') do it { should be_multi_region_trail } end ``` ### be_encrypted The test will pass if the logs delivered by the identified trail are encrypted. ``` describe aws_cloudtrail_trail('my-cloudtrail') do it { should be_encrypted } end ``` ### be_log_file_validation_enabled The test will pass if the identified trail has log file integrity validation is enabled. ``` describe aws_cloudtrail_trail('my-cloudtrail') do it { should be_log_file_validation_enabled } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `cloudtrail:DescribeTrails` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for AWS CloudTrail](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awscloudtrail.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_cloudtrail_trail/aws_cloudwatch_alarm resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_cloudwatch_alarm.md) Use the `aws_cloudwatch_alarm` InSpec audit resource to test properties of a single CloudWatch Alarm. **If more than one Alarm matches, an error will be raised.** Syntax ------ ### Ensure an Alarm exists. ``` aws_cloudwatch_alarm(metric_name: 'my-metric-name', metric_namespace: 'my-metric-namespace') do it { should exist } end ``` Parameters ---------- ### metric_name *(required)* The metric name used by this alarm. This must be passed as a `metric_name: 'value'` key-value entry in a hash. ### metric_namespace *(required)* The metric namespace used by this alarm. This must be passed as a `metric_namespace: 'value'` key-value entry in a hash. ### dimensions *(optional)* The dimensions associated with this alarm. This must be passed as an array of hashes `dimensions: [{key:'value'}]` . Properties ---------- | Property | Description | | --- | --- | | alarm_actions | The actions to execute when this alarm transitions to the ALARM state from any other state. Each action is specified as an Amazon Resource Name (ARN). | | alarm_name | The name of the alarm. | | metric_name | The name of the metric. | | metric_namespace | The namespace of the metric. | Examples -------- ### Ensure an Alarm has at least one alarm action ``` describe aws_cloudwatch_alarm(metric_name: 'my-metric-name', metric_namespace: 'my-metric-namespace') do its('alarm_actions') { should_not be_empty } end ``` ### Ensure an Alarm with Dimensions exists ``` describe aws_cloudwatch_alarm(metric_name: 'my-metric-name', metric_namespace: 'my-metric-namespace', dimensions: [{key: 'value'}]) do it { should exist } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_cloudwatch_alarm(metric_name: 'good-metric', metric_namespace: 'my-metric-namespace') do it { should exist } end describe aws_cloudwatch_alarm(metric_name: 'bed-metric', metric_namespace: 'my-metric-namespace') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `cloudwatch:DescribeAlarmsForMetric` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon CloudWatch](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncloudwatch.html). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_cloudwatch_alarm/aws_cloudwatch_log_metric_filter resource ============================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_cloudwatch_log_metric_filter.md) Use the `aws_cloudwatch_log_metric_filter` InSpec audit resource to search for and test properties of individual AWS Cloudwatch Log Metric Filters. Syntax ------ ``` describe aws_cloudwatch_log_metric_filter(filter_name: 'my-filter', log_group_name: 'my-log-group') do it { should exist } end describe aws_cloudwatch_log_metric_filter(log_group_name: 'my-log-group', pattern: 'my-filter') do it { should exist } end ``` Parameters ---------- **Note**: *While all parameters are optional, at least one must be provided. In practice, the more parameters you provide the narrower a result you will return.* ### filter_name *(optional)* The name of the Log Metric Filter. Expected in a hash as `filter_name: 'value'`. ### log_group_name *(optional)* The log group of the filter. Expected in a hash as `log_group_name: 'value'`. ### pattern *(optional)* A pattern by which to narrow down the result-set, if you expect multiple results. Expected in a hash as `pattern: 'value'`. See also the [AWS documentation on CloudWatch](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncloudwatch.html). Properties ---------- | Property | Description | | --- | --- | | filter_name | The name of the metric filter. | | log_group_name | The name of the log group. | | metric_name | The name of the metric. | | metric_namespace | The namespace of the metric. | | pattern | A symbolic description of how CloudWatch Logs should interpret the data in each log event. For example, a log event may contain timestamps, IP addresses, strings, and so on. You use the filter pattern to specify what to look for in the log event message. | Examples -------- ### Ensure a Filter exists ``` describe aws_cloudwatch_log_metric_filter(filter_name: 'my-filter', log_group_name: 'my-log-group') do it { should exist } end ``` ### Ensure a Filter exists for a specific pattern ``` describe aws_cloudwatch_log_metric_filter(pattern: '"ERROR" - "Exiting"') do it { should exist } end ``` ### Check the name of a Filter ``` describe aws_cloudwatch_log_metric_filter(log_group_name: 'app-log-group', pattern: 'KERBLEWIE') do its('filter_name') { should eq 'kaboom_lmf' } end ``` ### Check the Log Group name of a Filter ``` describe aws_cloudwatch_log_metric_filter(filter_name: 'error-watcher') do its('log_group_name') { should eq 'app-log-group' } end ``` ### Check a filter has the correct pattern ``` describe aws_cloudwatch_log_metric_filter(filter_name: 'error-watcher', log_group_name: 'app-log-group') do its('pattern') { should cmp 'ERROR' } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_cloudwatch_log_metric_filter(log_group_name: 'my-log-group') do it { should exist } end describe aws_cloudwatch_log_metric_filter(log_group_name: 'i-dont-exist') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `cloudwatch:DescribeAlarmsForMetric` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon CloudWatch](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncloudwatch.html). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_cloudwatch_log_metric_filter/aws_config_delivery_channel resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_config_delivery_channel.md) The AWS Config service can monitor and record changes to your AWS resource configurations. A Delivery Channel can record the changes to an S3 Bucket, an SNS or both. Use the `aws_config_delivery_channel` InSpec audit resource to examine how the AWS Config service delivers those change notifications. One delivery channel is allowed per region per AWS account, and the delivery channel is required to use AWS Config. Syntax ------ ``` describe aws_config_delivery_channel('my_channel') do it { should exist } end describe aws_config_delivery_channel(channel_name: 'my-channel') do it { should exist } end ``` Since you may only have one Delivery Channel per region, and InSpec connections are per-region, you may also omit the `channel_name` to obtain the one Delivery Channel (if any) that exists: ``` describe aws_config_delivery_channel do it { should exist } end ``` Parameters ---------- ### channel_name *(optional)* This resource can be passed a single parameter, the Channel Name. This can be passed either as a string or as a `channel_name: 'value'` key-value entry in a hash. See also the [AWS documentation on Delivery Channels](https://docs.aws.amazon.com/config/latest/developerguide/manage-delivery-channel.html). Properties ---------- | Property | Description | | --- | --- | | channel_name | The name of the delivery channel. By default, AWS Config assigns the name “default” when creating the delivery channel. | | s3_bucket_name | The name of the Amazon S3 bucket to which AWS Config delivers configuration snapshots and configuration history files. | | s3_key_prefix | The prefix for the specified Amazon S3 bucket. | | sns_topic_arn | The Amazon Resource Name (ARN) of the Amazon SNS topic to which AWS Config sends notifications about configuration changes. | | delivery_frequency_in_hours | Specifies how often the AWS Config sends configuration changes to the s3 bucket in the delivery channel. | Examples -------- ### Test how frequently the channel writes configuration changes to the s3 bucket ``` describe aws_config_delivery_channel(channel_name: 'my-recorder') do its('delivery_frequency_in_hours') { should be > 3 } end ``` ### Ensure configuration change notifications are being delivered to the correct bucket and key ``` describe aws_config_delivery_channel(channel_name: 'my_channel') its('s3_bucket_name') { should eq 'my_bucket' } its('s3_key_prefix') { should eq 'logs/' } end ``` Matchers -------- ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_config_delivery_channel('my_channel') do it { should exist } end describe aws_config_delivery_channel('my-nonexistent-channel') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `config:DescribeDeliveryChannels` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for AWS Config](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awsconfig.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_config_delivery_channel/aws_cloudwatch_log_group resource ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_cloudwatch_log_group.md) Use the `aws_cloudwatch_log_group` InSpec audit resource to test properties of a single AWS CloudWatch Log Group. Syntax ------ Ensure that an `aws_cloudwatch_log_group` exists ``` describe aws_cloudwatch_log_group('my_log_group') do it { should exist } end describe aws_cloudwatch_log_group(log_group_name: 'my_log_group') do it { should exist } end ``` Parameters ---------- ### log_group_name *(required)* This resource accepts a single parameter, the log group name which uniquely identifies the CloudWatch Log Group. This can be passed either as a string or as a `log_group_name: 'value'` key-value entry in a hash. See also the [AWS documentation on CloudWatch Logs](https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogGroups.html). Properties ---------- | Property | Description | | --- | --- | | retention_in_days | The number of days to retain the log events in the specified log group | | kms_key_id | The Amazon Resource Name (ARN) of the CMK to use when encrypting log data | | tags | The tags for the log group. | ### Test tags on the CloudWatch Log Group ``` describe aws_cloudwatch_log_group('my_log_group') do its('tags') { should include(:Environment => 'env-name', :Name => 'my_log_group')} end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `logs:DescribeLogGroups` and `logs:ListTagsLogGroup` actions with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon CloudWatch Logs](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncloudwatchlogs.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_cloudwatch_log_group/aws_db_subnet_groups resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_db_subnet_groups.md) Use the `aws_db_subnet_groups` InSpec audit resource to test properties of a collection of AWS RDS subnet groups. RDS gives you access to the capabilities of a MySQL, MariaDB, PostgreSQL, Microsoft SQL Server, Oracle, or Amazon Aurora database server. Syntax ------ Ensure you have exactly 3 subnet groups ``` describe aws_db_subnet_groups do its('db_subnet_group_names.count') { should cmp 3 } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on RDS](https://docs.aws.amazon.com/rds/?id=docs_gateway). Properties ---------- | Property | Description | | --- | --- | | db_subnet_group_names | The name of the DB subnet group. | | db_subnet_group_descriptions | Provides the description of the DB subnet group. | | vpc_ids | Provides the VPC ID of the DB subnet group. | | subnet_group_status | Provides the status of the DB subnet group. | | subnets | Contains a list of Subnet elements. | | db_subnet_group_arns | The Amazon Resource Name for the DB subnet group. | For a comprehensive list of properties available, see [the API reference documentation](https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DBSubnetGroup.html) Examples -------- ### Ensure DB Subnet Group Name of a subnet group exists ``` describe aws_db_subnet_groups do its('db_subnet_group_names') { should include 'subnet-group-name' } end ``` Matchers -------- For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_db_subnet_groups.where( <property>: <value> ) do it { should exist } end describe aws_db_subnet_groups.where( <property>: <value> ) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `rds:DescribeDBSubnetGroups` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon RDS](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonrds.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_db_subnet_groups/aws_config_recorder resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_config_recorder.md) Use the `aws_config_recorder` InSpec audit resource to test properties of your AWS Config Service. The AWS Config service can monitor and record changes to your AWS resource configurations. The Aws Config Recorder is used to detect changes in resource configurations and capture these changes as configuration items. As of April 2018, you are only permitted one configuration recorder per region. Syntax ------ Ensure that an auto scaling group exists and has the correct scale sizes ``` describe aws_config_recorder('my-recorder') do it { should exist } end ``` You may also use hash syntax to pass the recorder name ``` describe aws_config_recorder(recorder_name: 'my-recorder') do it { should exist } end ``` Since you may only have one recorder per region, and InSpec connections are per-region, you may also omit the recorder name to obtain the one recorder (if any) that exists: ``` describe aws_config_recorder do it { should exist } end ``` Parameters ---------- ### recorder_name *(optional)* This resource accepts a single parameter, the Configuration Recorder Name. This can be passed either as a string or as a `recorder_name: 'value'` key-value entry in a hash. See also the [AWS documentation on Configuration](https://docs.aws.amazon.com/config/latest/developerguide/aws-config-landing-page.html). Properties ---------- | Property | Description | | --- | --- | | recorder_name | The name of the recorder. By default, AWS Config automatically assigns the name “default” when creating the configuration recorder. You cannot change the assigned name. | | role_arn | Amazon Resource Name (ARN) of the IAM role used to describe the AWS resources associated with the account. | | resource_types | A comma-separated list that specifies the types of AWS resources for which AWS Config records configuration changes (i.e. AWS::EC2::Instance) | Examples -------- ### Test if the recorder is active and recording ``` describe aws_config_recorder do it { should be_recording } end ``` ### Ensure the role_arn is correct for the recorder The role is used to grant permissions to S3 Buckets, SNS topics and to get configuration details for supported AWS resources. ``` describe aws_config_recorder do its('role_arn') { should eq 'arn:aws:iam::721741954427:role/My_Recorder' } end ``` ### Test the recorder is monitoring changes to the correct resources. ``` describe aws_config_recorder do its('resource_types') { should include 'AWS::EC2::CustomerGateway' } its('resource_types') { should include 'AWS::EC2::EIP' } end ``` Matchers -------- ### be_recording Ensure the recorder is active ``` it { should be_recording } ``` ### be_recording_all_resource_types Indicates if the ConfigurationRecorder will record changes for all resources, regardless of type. If this is true, resource_types is ignored. ``` it { should be_recording_all_resource_types } ``` ### be_recording_all_global_types Indicates whether the ConfigurationRecorder will record changes for global resource types (such as [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal)s). ``` it { should be_recording_all_global_types } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `config:DescribeConfigurationRecorders` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for AWS Config](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awsconfig.html). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_config_recorder/aws_db_subnet_group resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_db_subnet_group.md) Use the `aws_db_subnet_group` InSpec audit resource to test properties of a db subnet group. Syntax ------ An `aws_db_subnet_group` resource block uses the parameter to select a subnet group. ``` describe aws_db_subnet_group(db_subnet_group_name: 'subnet-group-name-12345') do it { should exist } end ``` Parameters ---------- ### db_subnet_group_name *(required)* This resource accepts a single parameter, the DB Subnet Group Name. This can be passed either as a string or as a `aws_db_subnet_group: 'value'` key-value entry in a hash. See also the [AWS documentation on DB Subnet Groups](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.WorkingWithRDSInstanceinaVPC.html#USER_VPC.Subnets). Properties ---------- | Property | Description | | --- | --- | | db_subnet_group_name | The name of the DB subnet group. | | db_subnet_group_description | Provides the description of the DB subnet group. | | vpc_id | Provides the VPC ID of the DB subnet group. | | subnet_group_status | Provides the status of the DB subnet group. | | subnets | Contains a list of Subnet elements. | | db_subnet_group_arn | The Amazon Resource Name for the DB subnet group. | For a comprehensive list of properties available, see [the API reference documentation](https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DBSubnetGroup.html) Examples -------- ### Check DB Subnet Group Name of a subnet group ``` describe aws_db_subnet_group(db_subnet_group_name: 'subnet-group-name-12345') do its('db_subnet_group_name') { should eq 'subnet-group-name-12345' } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_db_subnet_group(db_subnet_group_name: 'subnet-group-name-12345') do it { should exist } end describe aws_rds_cluster(db_cluster_identifier: 'subnet-group-name-6789') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `rds:DescribeDBSubnetGroup` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keysfor Amazon RDS](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonrds.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_db_subnet_group/aws_dynamodb_table resource ============================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_dynamodb_table.md) Use the `aws_dynamodb_table` InSpec audit resource to test properties of a single DynamoDb Table. Syntax ------ ### Ensure an DynamoDb Table exists. ``` describe aws_dynamodb_table(table_name: 'table-name') do it { should exist } end ``` Parameters ---------- ### table_name *(required)* The table name used by this DynamoDb Table. This must be passed as a `table_name: 'value'` key-value entry in a hash. Properties ---------- | Property | Description | | --- | --- | | table_name | The name of the DynamoDb Table. | | table_status | The status of the DynamoDb Table. | | table_arn | The Amazon Resource Names of the DynamoDb Table. | | creation_date | The date the DynamoDb Table was created. eg. `01/01/2019` | | number_of_decreases_today | The number of provisioned throughput decreases for this table during this UTC calendar day. | | write_capacity_units | The maximum number of writes consumed per second before DynamoDb returns a ThrottlingException. | | read_capacity_units | The maximum number of strongly consistent reads consumed per second before DynamoDb returns a ThrottlingException. | | item_count | The number of entries in the DynamoDb Table. | | attributes | An array of attributes that describe the key schema for the table and indexes. This is returned as a hash. Each entry is composed of: `attribute_name` - The name of this key attribute. `attribute_type` - The datatype of the attribute : `B` - Boolean, `N` - Number, `S` - string | | key_schema | Specifies the attributes that make up the primary key for a table or an index. This is returned as a hash. The attributes in KeySchema must also be defined in the Attributes array. Each element in the KeySchemaElement array is composed of: `attribute_name` - The name of this key attribute. `key_type` - The role that the key attribute will assume: `HASH` - partition key, `RANGE` - sort key | | global_secondary_indexes | A list of global secondary indexes if there is any referenced on the selected table. | Examples -------- ### Ensure DynamoDb Table status is active ``` describe aws_dynamodb_table(table_name: 'table-name') do its('table_status') { should eq 'ACTIVE' } end ``` ### Ensure DynamoDb Table has an attribute ``` describe aws_dynamodb_table(table_name: 'table-name') do its('attributes') { should_not be_empty } its('attributes') { should include({:attribute_name =>'table_field', :attribute_type =>'N'}) } end ``` ### Ensure DynamoDb Table has a key_schema ``` describe aws_dynamodb_table(table_name: 'table-name') do its('key_schema') { should_not be_empty } its('key_schema') { should include({:attribute_name =>'table_field', :key_type =>'HASH'}) } end ``` ### Ensure DynamoDb Table has the correct global secondary indexes set ``` aws_dynamodb_table(table_name: 'table-name').global_secondary_indexes.each do |global_sec_idx| describe global_sec_idx do its('index_name') { should eq 'TitleIndex' } its('index_status') { should eq 'ACTIVE' } its('key_schema') { should include({:attribute_name =>'Title', :key_type =>'HASH'}) } its('provisioned_throughput.write_capacity_units') { should cmp 10 } its('provisioned_throughput.read_capacity_units') { should cmp 10 } its('projection.projection_type') { should eq 'INCLUDE' } end end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_dynamodb_table(table_name: 'table-name') do it { should exist } end describe aws_dynamodb_table(table_name: 'table-name') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `DynamoDB::DescribeTable` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon Dynamodb](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazondynamodb.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_dynamodb_table/aws_dhcp_options resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_dhcp_options.md) Use the `aws_dhcp_options` InSpec audit resource to test properties of a single AWS DHCP Options. Syntax ------ Ensure that an `aws_dhcp_options` exists ``` describe aws_dhcp_options('dopt-0123456789abcdefg') do it { should exist } end describe aws_dhcp_options(dhcp_options_id: 'dopt-0123456789abcdefg') do it { should exist } end ``` Parameters ---------- ### dhcp_options_id *(required)* This resource accepts a single parameter, the DHCP Options ID which uniquely identifies the DHCP Options. This can be passed either as a string or as a `dhcp_options_id: 'value'` key-value entry in a hash. See also the [AWS documentation on EC2](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeDhcpOptions.html). Properties ---------- | Property | Description | | --- | --- | | dhcp_configurations | The list of dhcp configurations | | domain_name_servers | The list of domain name servers in the dhcp configuration | | ntp_servers | The list of ntp servers in the dhcp configuration | | tags | The tags of the DHCP Options. | ### Test tags on the DHCP Options ``` describe aws_dhcp_options('dopt-0123456789abcdefg') do its('tags') { should include(:Environment => 'env-name', :Name => 'dhcp-options-name')} end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeDhcpOptions` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_dhcp_options/aws_ebs_volume resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ebs_volume.md) Use the `aws_ebs_volume` InSpec audit resource to test properties of a single AWS EBS volume. Syntax ------ Ensure an EBS exists ``` describe aws_ebs_volume('vol-01a2349e94458a507') do it { should exist } end ``` You may also use hash syntax to pass the EBS volume name ``` describe aws_ebs_volume(name: 'data-vol') do it { should exist } end ``` Parameters ---------- This resource accepts a single parameter, either the EBS Volume name or id. At least one must be provided. ### volume_id *(required if `name` not provided)* The EBS Volume ID which uniquely identifies the volume. This can be passed as either a string or an `volume_id: 'value'` key-value entry in a hash. ### name *(required if `volume_id` not provided)* The EBS Volume Name which uniquely identifies the volume. This must be passed as a `name: 'value'` key-value entry in a hash. See also the [AWS documentation on EBS](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html). Properties ---------- | Property | Description | | --- | --- | | availability_zone | The Availability Zone for the volume. | | encrypted | Indicates whether the volume will be encrypted. | | iops | The number of I/O operations per second (IOPS) that the volume supports. | | kms_key_id | The full ARN of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the volume. | | size | The size of the volume, in GiBs. | | snapshot_id | The snapshot from which the volume was created, if applicable. | | status | The volume state. | | volume_type | The volume type. | Examples -------- ### Test that an EBS Volume does not exist ``` describe aws_ebs_volume(name: 'data_vol') do it { should_not exist } end ``` ### Test that an EBS Volume is encrypted ``` describe aws_ebs_volume(name: 'secure_data_vol') do it { should be_encrypted } end ``` ### Test that an EBS Volume the correct size ``` describe aws_ebs_volume(name: 'data_vol') do its('size') { should cmp 32 } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_ebs_volume(name: 'data_vol') do it { should exist } end describe aws_ebs_volume(name: 'data_vol') do it { should_not exist } end ``` ### be_encrypted The `be_encrypted` matcher tests if the described EBS Volume is encrypted. ``` it { should be_encrypted } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeVolumes`, and `iam:GetInstanceProfile` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ebs_volume/aws_ebs_volumes resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ebs_volumes.md) Use the `aws_ebs_volumes` InSpec audit resource to test properties of a collection of AWS EBS volumes. EBS volumes are persistent block storage volumes for use with Amazon EC2 instances in the AWS Cloud. Syntax ------ Ensure you have exactly 3 volumes ``` describe aws_ebs_volumes do its('volume_ids.count') { should cmp 3 } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on EBS](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html). Properties ---------- | Property | Description | | --- | --- | | volume_ids | The unique IDs of the EBS Volumes returned. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Ensure a specific volume exists ``` describe aws_ebs_volumes do its('volume_ids') { should include 'vol-12345678' } end ``` ### Use the InSpec resource to request the IDs of all EBS volumes, then test in-depth using `aws_ebs_volume` to ensure all volumes are encrypted and have a sensible size. ``` aws_ebs_volumes.volume_ids.each do |volume_id| describe aws_ebs_volume(volume_id) do it { should be_encrypted } its('size') { should be > 10 } its('iops') { should cmp 100 } end end ``` Matchers -------- For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_ebs_volumes do it { should exist } end describe aws_ebs_volumes do it { should_not exist } end ``` Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeVolumes`, and `iam:GetInstanceProfile` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ebs_volumes/aws_ec2_instances resource ============================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ec2_instances.md) Use the `aws_ec2_instances` InSpec audit resource to test properties of some or all AWS EC2 instances. To audit a single EC2 instance, use `aws_ec2_instance` (singular). Syntax ------ An `aws_ec2_instances` resource block collects a group of EC2 Instances and then tests that group. ``` describe aws_ec2_instances it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. Properties ---------- | Property | Description | | --- | --- | | instance_ids | The ID of the EC2 instance. The field name is `instance_id`. | | names | The value of the `Name` tag if applied to the instance. The filed name is `name`. | | vpc_ids | The VPC with which the EC2 instance is associated. The field name is `vpc_id`. | | subnet_ids | The subnet with which the EC2 instance is associated. The field name is `subnet_id`. | | instance_types | The type of instance, for example m5.large. The field name is `instance_type`. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | | tags | A hash, with each key-value pair corresponding to an EC2 instance tag, e.g, `{"Name"=>"Testing Box", "Environment"=>"Dev"}`. This property is available in InSpec AWS resource pack version **[1.12.0](https://github.com/inspec/inspec-aws/releases/tag/v1.12.0)** onwards. The field name is `tags`. | | iam_profiles | The IAM instance profile associated with the instance. The `role` property of the `aws_ec2_instance` singular resource can be used to check the attached IAM role on the profile. The field name is `iam_profile`. | Examples -------- ### Ensure you have exactly 3 instances ``` describe aws_ec2_instances do its('instance_ids.count') { should cmp 3 } end ``` ### Use this InSpec resource to request the IDs of all EC2 instances, then test in-depth using `aws_ec2_instance`. ``` aws_ec2_instances.instance_ids.each do |instance_id| describe aws_ec2_instance(instance_id) do it { should_not have_roles } its('key_name') { should cmp 'admin-ssh-key' } its('image_id') { should eq 'ami-27a58d5c' } end end ``` ### Filter EC2 instances with their `Environment` tags* equal to `Dev`, then test in-depth using `aws_ec2_instance`. ``` aws_ec2_instances.where(tags: {"Environment" => "Dev"}).instance_ids.each do |id| describe aws_ec2_instance(id) do it { should be_stopped } end end ``` *Note that the filter won’t return the EC2 instances with multiple tags. In this case use regex: `/{"Environment"=>"Dev"}/` ### Filter EC2 instances with a `stop-at-10-pm` tag regardless of its value, then test in-depth using `aws_ec2_instance`. ``` aws_ec2_instances.where(tags: /"stop-at-10-pm"=>/).instance_ids.each do |id| describe aws_ec2_instance(id) do it { should be_stopped } end end ``` ### Filter EC2 instances with their `name` equal to `Test Box`, then check their role using `aws_ec2_instance`. ``` aws_ec2_instances.where(name: "Test Box").instance_ids.each do |id| describe aws_ec2_instance(id) do its('role) { should eq "test-role" } end end ``` Matchers -------- For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. The field names described in the [properties table](#properties) should be used for the `<property>` in the `where` clause. Use `should_not` to test the entity should not exist. ``` describe aws_ec2_instances.where( <property>: <value>) do it { should exist } end describe aws_ec2_instances.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeInstances`, and `iam:GetInstanceProfile` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ec2_instances/aws_ecr_image resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ecr_image.md) Use the `aws_ecr_image` InSpec audit resource to test the properties of a single image in an AWS Elastic Container Registry (ECR) repository. This resource is available in InSpec AWS resource pack version **[1.11.0](https://github.com/inspec/inspec-aws/releases/tag/v1.11.0)** onwards. Syntax ------ An `aws_ecr_image` resource block declares the tests for a single image in an AWS ECR repository by repository name and image identifier. ``` describe aws_ecr_image(repository_name: 'my-repo', image_tag: 'latest') do it { should exist } end ``` Parameters ---------- The repository name and the image identifier (either `image_tag` or `image_digest`) must be provided. The ID of the registry is optional. ### repository_name *(required)* The name of the ECR repository must satisfy the following constraints: * Regex pattern `(?:[a-z0-9]+(?:[._-][a-z0-9]+)*/)*[a-z0-9]+(?:[._-][a-z0-9]+)*`. * Minimum 2 and maximum of 256 characters long. ### image_tag *(required if `image_digest` not provided)* The tag used for the image. It can not be longer than 300 characters. ### image_digest *(required if `image_tag` not provided)* The `sha256` digest of the image manifest. It must satisfy this regex pattern: `[a-zA-Z0-9-_+.]+:[a-fA-F0-9]+`. ### registry_id *(optional)* The 12-digit ID of the AWS Elastic Container Registry. If not provided, the [default](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_DescribeRepositories.html) registry is assumed. Properties ---------- | Property | Description | | --- | --- | | repository_name | The name of the repository. | | registry_id | The AWS account ID associated with the registry that contains the repository. | | tags | The list of tags associated with this image. | | vulnerability_severity_counts | The image vulnerability counts, sorted by severity, e.g. `{:high=>1}`. | | vulnerabilities | A list of hashes with each key-value pair corresponding to an image [scan findings](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_ImageScanFinding.html). E.g. `{:name=>"CVE-2019-14697", :uri=>"https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-14697", :severity=>"HIGH", :package_version=>"1.1.18-r3", :package_name=>"musl", :CVSS2_VECTOR=>"AV:N/AC:L/Au:N/C:P/I:P/A:P", :CVSS2_SCORE=>"7.5"}` | | cve_ids | The list of [CVE IDs](https://cve.mitre.org/cve/identifiers/) of the vulnerabilities in the image. | | highest_vulnerability_severity | The [CVSS v2](https://www.first.org/cvss/v2/guide) score of the most severe vulnerability in the image. | There are also additional properties available. For a comprehensive list, see [the API reference documentation](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_ImageDetail.html) Examples -------- ### Test the scan status of an image ``` describe aws_ecr_image(repository_name: 'my-repo', image_tag: 'latest') do its('image_scan_status.status') { should eq 'COMPLETE' } end ``` ### Test that an image has a certain tag ``` describe aws_ecr_image(repository_name: 'my-repo', image_digest: 'sha256:687fba9b76554c8dea4c40fed4144011f29b8e1d5db5f2fc976c64ed31894967') do its('tags') { should include('latest') } end ``` ### Test that an image does not contain the [Heartbleed](https://heartbleed.com/) vulnerability ``` describe aws_ecr_image(repository_name: 'my-repo', image_tag: 'latest') do its('cve_ids') { should_not include('CVE-2014-0160') } end ``` ### Test that an image does not contain a vulnerability more severe than CVSS v2 score 8 ``` describe aws_ecr_image(repository_name: 'my-repo', image_tag: 'latest') do its('highest_vulnerability_severity') { should be <= 8 } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist ``` describe aws_ecr_image(repository_name: 'my-repo', image_tag: 'latest') do it { should exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ecr:DescribeImages` and `ecr:DescribeImageScanFindings` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_Operations.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ecr_image/aws_ecr_images resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ecr_images.md) Use the `aws_ecr_images` InSpec audit resource to test the properties of all images in an AWS Elastic Container Registry (ECR) repository. This resource is available in InSpec AWS resource pack version **[1.11.0](https://github.com/inspec/inspec-aws/releases/tag/v1.11.0)** onwards. Syntax ------ An `aws_ecr_images` resource block declares the tests for all images in an AWS ECR repository by the repository name. ``` describe aws_ecr_images(repository_name: 'my-repo') do it { should exist } end ``` Parameters ---------- The repository name must be provided. The ID of the registry is optional. ### repository_name *(required)* The name of the ECR repository must satisfy the following constraints: * Regex pattern `(?:[a-z0-9]+(?:[._-][a-z0-9]+)*/)*[a-z0-9]+(?:[._-][a-z0-9]+)*`. * Minimum 2 and maximum of 256 characters long. ### registry_id *(optional)* The 12-digit ID of the AWS Elastic Container Registry. If not provided, the [default](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_DescribeRepositories.html) registry is assumed. Properties ---------- | Property | Description | | --- | --- | | digests | The sha256 digest of the image manifest. The field name is `digest`. | | size_in_bytes | The size, in bytes, of the image in the repository. | | tags | The list of tags associated with an image. The field name is `tags`. | | vulnerability_severity_counts | The image vulnerability counts, sorted by severity. | | vulnerability_scan_status | The current state of the scan. It returns an [image scan status object](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_ImageScanStatus.html). | | pushed_at_dates | The date and time at which an image was pushed to the repository. The field name is `pushed_at_date`. | Examples -------- ### Ensure that there are exactly 3 images ``` describe aws_ecr_images(repository_name: 'my-repo') do its('count') { should cmp 3 } end ``` ### Use this InSpec resource to request the digests of all images, then test in-depth using `aws_ecr_image`. ``` aws_ecr_images(repository_name: 'my-repo').digests.each do |image_digest| describe aws_ecr_image(repository_name: 'my-repo', image_digest: image_digest) do its('tags') { should include('latest') } end end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_ecr_images(repository_name: 'my-repo').where( <property>: <value>) do it { should exist } end describe aws_ecr_images(repository_name: 'my-repo').where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ecr:DescribeImages` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_Operations.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ecr_images/aws_ec2_instance resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ec2_instance.md) Use the `aws_ec2_instance` InSpec audit resource to test properties of a single AWS EC2 instance. Syntax ------ An `aws_ec2_instance` resource block declares the tests for a single AWS EC2 instance by either name or instance id. ``` describe aws_ec2_instance('i-01a2349e94458a507') do it { should exist } end describe aws_ec2_instance(name: 'my-instance') do it { should exist } end ``` Parameters ---------- One of either the EC2 instance’s ID or name must be be provided. ### instance_id *(required if `name` not provided)* The ID of the EC2 instance. This is in the format of `i-` followed by 8 or 17 hexadecimal characters. This can be passed either as a string or as an `instance_id: 'value'` key-value entry in a hash. ### name *(required if `instance_id` not provided)* If you have a `Name` tag applied to the EC2 instance, this can be used to lookup the instance. This must be passed as a `name: 'value'` key-value entry in a hash. Properties ---------- | Property | Description | | --- | --- | | state | The current state of the EC2 Instance, for example ‘running’. | | image_id | The id of the AMI used to launch the instance. | | role | The IAM role attached to the instance. | | launch_time | The time the instance was launched. | | availability_zone | The availability zone of the instance. | | security_groups | A hash containing the security group ids and names associated with the instance. | | security_group_ids | The security group ids associated with the instance. | | ebs_volumes | A hash containing the names and ids of any EBS volumes associated with the instance. | | tags | A list of hashes with each key-value pair corresponding to an EC2 instance tag, e.g, `[{:key=>"Name", :value=>"Testing Box"}, {:key=>"Environment", :value=>"Dev"}]` | | tags_hash | A hash, with each key-value pair corresponding to an EC2 instance tag, e.g, `{"Name"=>"Testing Box", "Environment"=>"Dev"}`. This property is available in InSpec AWS resource pack version **[1.12.0](https://github.com/inspec/inspec-aws/releases/tag/v1.12.0)** onwards. | There are also additional properties available. For a comprehensive list, see [the API reference documentation](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Instance.html) Examples -------- ### Test that an EC2 instance is running ``` describe aws_ec2_instance(name: 'prod-database') do it { should be_running } end ``` ### Test that an EC2 instance is using the correct AMI ``` describe aws_ec2_instance(name: 'my-instance') do its('image_id') { should eq 'ami-27a58d5c' } end ``` ### Test that an EC2 instance has the correct tag ``` describe aws_ec2_instance('i-090c29e4f4c165b74') do its('tags') { should include(key: 'Contact', value: 'Gilfoyle') } end ``` ### Test that an EC2 instance has the correct tag (using the `tags_hash` property) ``` describe aws_ec2_instance('i-090c29e4f4c165b74') do its('tags_hash') { should include('Contact' => 'Gilfoyle') } its('tags_hash') { should include('Contact') } # Regardless of the value end ``` ### Test that an EC2 instance has no roles ``` describe aws_ec2_instance('i-090c29e4f4c165b74') do it { should_not have_roles } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` it { should exist } it { should_not exist } ``` ### has_roles Test if the EC2 instance has any roles associated with it. Use `should_not` to test the entity does not have roles. ``` it { should have_roles } it { should_not have_roles } ``` ### be_pending The `be_pending` matcher tests if the described EC2 instance state is `pending`. This indicates that an instance is provisioning. This state should be temporary. ``` it { should be_pending } ``` ### be_running The `be_running` matcher tests if the described EC2 instance state is `running`. This indicates the instance is fully operational from AWS’s perspective. ``` it { should be_running } ``` ### be_shutting_down The `be_shutting_down` matcher tests if the described EC2 instance state is `shutting-down`. This indicates the instance has received a termination command and is in the process of being permanently halted and de-provisioned. This state should be temporary. ``` it { should be_shutting_down } ``` ### be_stopped The `be_stopped` matcher tests if the described EC2 instance state is `stopped`. This indicates that the instance is suspended and may be started again. ``` it { should be_stopped } ``` ### be_stopping The `be_stopping` matcher tests if the described EC2 instance state is `stopping`. This indicates that an AWS stop command has been issued, which will suspend the instance in an OS-unaware manner. This state should be temporary. ``` it { should be_stopping } ``` ### be_terminated The `be_terminated` matcher tests if the described EC2 instance state is `terminated`. This indicates the instance is permanently halted and will be removed from the instance listing in a short period. This state should be temporary. ``` it { should be_terminated } ``` ### be_unknown The `be_unknown` matcher tests if the described EC2 instance state is `unknown`. This indicates an error condition in the AWS management system. This state should be temporary. ``` it { should be_unknown } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeInstances`, and `iam:GetInstanceProfile` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ec2_instance/aws_ecr resource ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ecr.md) Warning This resource is deprecated. Please use one of the following resources instead. * `aws_ecr_image` * `aws_ecr_images` * `aws_ecr_repository` * `aws_ecr_repositories` Use the `aws_ecr` InSpec audit resource to test properties of a single AWS Elastic Container Registry. Syntax ------ An `aws_ecr` resource block declares the tests for a single AWS ECR by repository name. ``` describe aws_ecr(repository_name: aws_ecr_name) do it { should exist } its ('repository_name') { should eq aws_ecr_name } end ``` Parameters ---------- The ECR repository_name must be provided. ### repository_name *(required)* The name of the repository This can be passed either as a string or as an `repository_name: 'value'` key-value entry in a hash. Properties ---------- | Property | Description | | --- | --- | | registry_id | The AWS account ID associated with the registry | | repository_arn | The Amazon Resource Name of the repository | | repository_name | The name of the repository | | repository_uri | The uri of the repository | | image_tags | The tags associated with the image | | image_digest | A sha256 hash of the image | | image_size_in_bytes | The size of the image in bytes. | | image_pushed_at | The datetime as a string when the image was uploaded. ‘yyyy-mm-dd hh:mm:ss tz’ | | image_uploaded_date | The date as a string when the image was uploaded. ‘yyyy-mm-dd’ | Examples -------- ### Test that an ECR has the correct image properties ``` describe aws_ecr(repository_name: aws_ecr_name).images do its ('image_tags') { should include 'latest'} its ('image_digest') { should eq 'sha256:6dce4a9c1635c4c9b6a2b645e6613fa0238182fe13929808ee2258370d0f3497'} its ('image_size_in_bytes') { should eq 764234} its ('image_uploaded_date') { should eq '2019-06-11'} its ('image_pushed_at') { should eq '2019-06-11 15:08:29 +0100'} end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` it { should exist } it { should_not exist } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ecr:DescribeRepositories` and `ecr:DescribeImages` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon ECR](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonelasticcontainerregistry.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ecr/aws_ecr_repositories resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ecr_repositories.md) Use the `aws_ecr_repositories` InSpec audit resource to test the properties of all repositories in an AWS Elastic Container Registry (ECR). This resource is available in InSpec AWS resource pack version **[1.11.0](https://github.com/inspec/inspec-aws/releases/tag/v1.11.0)** onwards. Syntax ------ An `aws_ecr_repositories` resource block declares the tests for all AWS ECR repositories in the default registry unless the registry ID is provided. ``` describe aws_ecr_repositories do it { should exist } end ``` Repositories in a non-default registry can be tested by supplying the registry ID if the AWS user has necessary permissions on it. ``` describe aws_ecr_repositories(registry_id: '123456789012') do it { should exist } end ``` Parameters ---------- The registry id is optional. ### registry_id *(optional)* The 12-digit ID of the AWS Elastic Container Registry. If not provided, the [default](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_DescribeRepositories.html) registry is assumed. Properties ---------- | Property | Description | | --- | --- | | arns | The Amazon Resource Name (ARN) that identifies the repository. | | names | The name of the repository. | | uris | The URI for the repository. | | created_at_dates | The date and time, in JavaScript date format, when the repository was created. | | image_tag_mutability_status | The tag mutability setting for the repository. | | image_scanning_on_push_status | The setting that determines whether images are scanned after being pushed to a repository. | Examples -------- ### Ensure that there are exactly 3 repositories in the default registry ``` describe aws_ecr_repositories do its("count") { should cmp 3 } end ``` ### Use this InSpec resource to request the names of all repositories, then test in-depth using `aws_ecr_repository`. ``` aws_ecr_repositories.names.each do |repository_name| describe aws_ecr_repository(repository_name) do its('image_tag_mutability') { should eq 'MUTABLE' } end end ``` Matchers -------- For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_ecr_repositories.where( <property>: <value>) do it { should exist } end describe aws_ecr_repositories.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ecr:DescribeRepositories` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_Operations.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ecr_repositories/aws_efs_file_system resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_efs_file_system.md) Use the `aws_efs_file_system` InSpec audit resource to test the properties of a single AWS EFS file system. This resource is added to InSpec AWS resource pack in version **[1.10.0](https://github.com/inspec/inspec-aws/releases/tag/v1.10.0)** and it is available with InSpec **[4.18.108](https://github.com/inspec/inspec/releases/tag/v4.18.108)** and later versions. Syntax ------ An `aws_efs_file_system` resource block declares the tests for a single AWS EFS file system by either file system id or creation token. ``` describe aws_efs_file_system(file_system_id: 'fs-12345678') do it { should be_encrypted } its('size_in_bytes.value') { should cmp 6144 } end describe aws_efs_file_system(creation_token: 'my-token') do its('encrypted') { should cmp true } its('throughput_mode') { should eq 'bursting' } end ``` The value of the `file_system_id` can be provided as a string. ``` describe aws_efs_file_system('fs-12345678') do it { should exist } end ``` Parameters ---------- Either the EFS file system id or creation token must be provided. ### file_system_id *(required if `creation_token` not provided)* The ID of the EFS file system. This is in the format of `fs-` followed by 8 or 17 hexadecimal characters. This can be passed either as a string or as a `file_system_id: 'value'` key-value entry in a hash. ### creation_token *(required if `file_system_id` not provided)* The creation token is automatically assigned by AWS if not provided by the user at creation. This is a string with minimum 1 and maximum 64-character long. This must be passed as a `creation_token: 'value'` key-value entry in a hash. Properties ---------- | Property | Description | | --- | --- | | creation_token | The value of the creation token. | | file_system_id | The id of the file system which is auto-assigned by the AWS. | | encrypted | Indicates whether the file system is encrypted or not. | | life_cycle_state | The lifecycle phase of the file system, e.g. ‘creating’. | | owner_id | The AWS account that created the file system. | | performance_mode | The performance mode of the file system, e.g. ‘maxIO’. | | throughput_mode | The throughput mode for a file system, e.g. ‘bursting’. | | tags | An hash with each key-value pair corresponding to a tag associated with the entity. | There are also additional properties available. For a comprehensive list, see [the API reference documentation](https://docs.aws.amazon.com/efs/latest/ug/API_FileSystemDescription.html) Examples -------- ### Test that an EFS file system is available ``` describe aws_efs_file_system("fs-12345678") do its("life_cycle_state") { should eq 'available' } end ``` ### Test that an EFS file system is in ‘maxIO’ performance mode ``` describe aws_efs_file_system(creation_token: "My Token") do its("performance_mode") { should eq "maxIO" } end ``` ### Test that an EFS file system has a certain tag ``` describe aws_efs_file_system(creation_token: "My Token") do its("tags") { should include("companyName" => "My Company") } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist ``` describe aws_efs_file_system(file_system_id: "fs-12345678") do it { should exist } end ``` ### be_encrypted ``` describe aws_efs_file_system(creation_token: "My Token") do it { should be_encrypted } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `elasticfilesystem:DescribeFileSystems` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EFS](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonelasticfilesystem.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_efs_file_system/aws_ecs_cluster resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ecs_cluster.md) Use the `aws_ecs_cluster` InSpec audit resource to test properties of a single AWS ECS Cluster. Syntax ------ An `aws_ecs_cluster` resource block declares the tests for a single AWS ECS Cluster by cluster name. ``` describe aws_ecs_cluser(cluster_name: 'cluster-8') do it { should exist } end ``` Parameters ---------- If no parameters are passed, the resource will attempt to retrieve the `default` ECS Cluster. ### cluster_name *(optional)* This resource accepts a single parameter, the Cluster Name. This can be passed either as a string or as a `cluster_name: 'value'` key-value entry in a hash. See also the [AWS documentation on ECS Clusters](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_clusters.html). Properties ---------- | Property | Description | | --- | --- | | cluster_arn | The Amazon Resource Name (ARN) that identifies the cluster. | | cluster_name | A user-generated string that you use to identify your cluster. | | status | The status of the cluster. | | running_tasks_count | The number of tasks in the cluster that are in the RUNNING state. | | pending_tasks_count | The number of tasks in the cluster that are in the PENDING state. | | active_services_count | The number of services that are running on the cluster in an ACTIVE state. | | registered_container_instances_count | The number of container instances registered into the cluster. This includes container instances in both ACTIVE and DRAINING status. | | statistics | Additional information about your clusters that are separated by launch type. | Examples -------- ### Test that an ECS Cluster does not exist ``` describe aws_ecs_cluster(cluster_name: 'invalid-cluster') do it { should_not exist } end ``` ### Test that an ECS Cluster is active ``` describe aws_ecs_cluster('cluster-8') do its ('status') { should eq 'ACTIVE' } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_ecs_cluster('cluster-8') do it { should exist } end describe aws_ecs_cluster('cluster-9') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeClusters` action set to allow. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ecs_cluster/aws_ecr_repository resource ============================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ecr_repository.md) Use the `aws_ecr_repository` InSpec audit resource to test the properties of a single AWS Elastic Container Registry (ECR) repository. This resource is available in InSpec AWS resource pack version **[1.11.0](https://github.com/inspec/inspec-aws/releases/tag/v1.11.0)** onwards. Syntax ------ An `aws_ecr_repository` resource block declares the tests for a single AWS ECR repository by repository name. ``` describe aws_ecr_repository(repository_name: 'my-repo') do it { should exist } end ``` The value of the `repository_name` can be provided as a string. ``` describe aws_ecr_repository('my-repo') do it { should exist } end ``` Parameters ---------- The repository name must be provided. The registry id is optional. ### repository_name *(required)* The name of the ECR repository must satisfy the following constraints: * Regex pattern `(?:[a-z0-9]+(?:[._-][a-z0-9]+)*/)*[a-z0-9]+(?:[._-][a-z0-9]+)*`. * Minimum 2 and maximum of 256 characters long. This can be passed either as a string or as a `repository_name: 'value'` key-value entry in a hash. ### registry_id *(optional)* The 12-digit ID of the AWS Elastic Container Registry. If not provided, the [default](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_DescribeRepositories.html) registry is assumed. Properties ---------- | Property | Description | | --- | --- | | repository_name | The name of the repository. | | image_tag_mutability | The tag mutability settings for the repository. Valid values are `MUTABLE` or `IMMUTABLE`. | | registry_id | The AWS account ID associated with the registry that contains the repository. | | tags | An hash with each key-value pair corresponding to a tag associated with the entity. | There are also additional properties available. For a comprehensive list, see [the API reference documentation](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_Repository.html) Examples -------- ### Test that image tags are `IMMUTABLE` in an ECR repository ``` describe aws_ecr_repository('my-repo') do its('image_tag_mutability') { should eq 'IMMUTABLE' } end ``` ### Test that images are scanned for vulnerabilities at a push to repository ``` describe aws_ecr_repository(repository_name: 'my-repo') do its('image_scanning_configuration.scan_on_push') { should eq true} end ``` ### Test that an ECR repository has a certain tag ``` describe aws_ecr_repository('my-repo') do its('tags') { should include('environment' => 'dev') } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist ``` describe aws_ecr_repository(repository_name: 'my-repo') do it { should exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ecr:DescribeRepositories` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_Operations.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ecr_repository/aws_ecs_clusters resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ecs_clusters.md) Use the `aws_ecs_clusters` InSpec audit resource to test properties of some or all AWS ECS Clusters. Syntax ------ An `aws_ecs_clusters` resource block returns all ECS Clusters and allows the testing of that group of Clusters. ``` describe aws_ecs_clusters do its('cluster_names') { should include 'cluster-root' } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on ECS Clusters](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_clusters.html). Properties ---------- | Property | Description | | --- | --- | | cluster_arn | The Amazon Resource Name (ARN) that identifies the cluster. | | cluster_name | A user-generated string that you use to identify your cluster. | | status | The status of the cluster. | | running_tasks_count | The number of tasks in the cluster that are in the RUNNING state. | | pending_tasks_count | The number of tasks in the cluster that are in the PENDING state. | | active_services_count | The number of services that are running on the cluster in an ACTIVE state. | | registered_container_instances_count | The number of container instances registered into the cluster. This includes container instances in both ACTIVE and DRAINING status. | | statistics | Additional information about your clusters that are separated by launch type. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Ensure there are no Clusters in an undesired state. ``` describe aws_ecs_clusters do it { should exist } its('statuses') { should_not include 'UNDESIRED-STATUS'} its('cluster_names') { should include 'SQL-cluster' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_ecs_clusters.where( <property>: <value>) do it { should exist } end describe aws_ecs_clusters.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ecs:ListClusters` & `ecs:DescribeClusters` action set to allow. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ecs_clusters/aws_efs_file_systems resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_efs_file_systems.md) Use the `aws_efs_file_systems` InSpec audit resource to test the properties of some or all AWS EFS file systems. To audit a single EFS file system, use `aws_efs_file_ststem` (singular). This resource is added to InSpec AWS resource pack in version **[1.10.0](https://github.com/inspec/inspec-aws/releases/tag/v1.10.0)** and it is available with InSpec **[4.18.108](https://github.com/inspec/inspec/releases/tag/v4.18.108)** and later versions. Syntax ------ An `aws_efs_file_systems` resource block collects a group of EFS file system descriptions and then tests that group. ``` describe aws_efs_file_systems it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. Properties ---------- | Property | Description | | --- | --- | | tags | The list of tags that the EFS file system has. | | names | The value of the `Name` (case sensitive) tag if it is defined. | | file_system_ids | The ID of the EFS file system. | | creation_tokens | The creation token that the EFS file system is associated. | | owner_ids | The owner id of the EFS file system. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | | creation_times | The creation time of the EFS file system | | performance_modes | The performance mode of the EFS file system, e.g. ‘maxIO’. | | encryption_status | This indicates whether the EFS file system is encrypted or not. | | throughput_modes | The throughput mode of the EFS file system. | | kms_key_ids | The ID of an AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the encrypted EFS file system. | | size_in_bytes | The latest known metered size (in bytes) of data stored in the file system, in its `value` field. | | life_cycle_states | The life cycle phase of the EFS file system, e.g. ‘deleting’. | Examples -------- ### Ensure you have exactly 3 file systems ``` describe aws_efs_file_systems do its("entries.count") { should cmp 3 } end ``` ### Use this InSpec resource to request the IDs of all EFS file systems, then test in-depth using `aws_efs_file_system`. ``` aws_efs_file_systems.file_system_ids.each do |file_system_id| describe aws_efs_file_system(file_system_id) do its("tags") { should include("companyName" => "My Company Name") } it { should be_encrypted } its("throughput_mode") { should eq "bursting" } its("performance_mode") { should eq "generalPurpose" } end end ``` Matchers -------- For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_efs_file_systems.where( <property>: <value>) do it { should exist } end describe aws_efs_file_systems.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `elasticfilesystem:DescribeFileSystems` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EFS](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonelasticfilesystem.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_efs_file_systems/aws_eks_cluster resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_eks_cluster.md) Use the `aws_eks_cluster` InSpec audit resource to test properties of a single AWS Elastic Container Service for Kubernetes. Syntax ------ An `aws_eks_cluster` resource block declares the tests for a single EKS Cluster by Cluster name. ``` describe aws_eks_cluster('my-eks') do it { should exist } end describe aws_eks_cluster(cluster_name: 'my-eks') do it { should exist } end ``` Parameters ---------- ### cluster_name *(required)* This resource requires a single parameter, the EKS Cluster Name. This can be passed either as a string or as a `cluster_name: 'value'` key-value entry in a hash. See also the [AWS documentation on EKS Clusters](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html). Properties ---------- | Property | Description | | --- | --- | | arn | The Amazon Resource Name (ARN) of the cluster. | | name | The name of the cluster. | | endpoint | The endpoint for your Kubernetes API server. | | status | The current status of the cluster. | | version | The Kubernetes server version for the cluster. | | certificate_authority | The certificate-authority-data for your cluster. | | subnets_count | The number of subnets associated with your cluster. | | subnet_ids | The subnets associated with your cluster. | | security_groups_count | The count of security groups associated with your cluster. | | security_group_ids | The security groups associated with the cross-account elastic network interfaces that are used to allow communication between your worker nodes and the Kubernetes control plane. | | role_arn | The Amazon Resource Name (ARN) of the IAM role that provides permissions for the Kubernetes control plane to make calls to AWS API operations on your behalf. | | vpc_id | The VPC associated with your cluster. | | created_at | The Unix epoch timestamp in seconds for when the cluster was created. | | creating | Boolean indicating whether or not the state of the cluster is CREATING. | | active | Boolean indicating whether or not the state of the cluster is ACTIVE. | | failed | Boolean indicating whether or not the state of the cluster is FAILED. | | deleting | Boolean indicating whether or not the state of the cluster is DELETING. | | tags | Cluster tags | Examples -------- ### Test that an EKS Cluster has at least 2 subnets ``` describe aws_eks_cluster('my-cluster') do its('subnets_count') { should be > 1 } end ``` ### Ensure a Cluster has the correct status. ``` describe aws_eks_cluster(cluster_name: 'my-eks') do its('status') { should eq 'ACTIVE' } end ``` ### Ensure that the EKS Cluster is on the correct VPC ``` describe aws_eks_cluster('my-cluster') do its('vpc_id') { should eq 'vpc-12345678' } end ``` ### Ensure the EKS Cluster is using the correct IAM Role. ``` describe aws_eks_cluster('my-cluster') do its('role_arn') { should cmp 'rn:aws:iam::012345678910:role/eks-service-role-AWSServiceRoleForAmazonEKS-J7ONKE3BQ4PI' } end ``` ### Integrate with other resources Use a combination of InSpec AWS resources to ensure your EKS Cluster does not use the Default VPC. ``` # Find the default Security Group for our VPC cluster_vpc = aws_eks_cluster(cluster_name: 'my-cluster').vpc_id default_sg = aws_security_group(group_name: 'default', vpc_id: cluster_vpc) # Ensure we are not using the default Security Group describe aws_eks_cluster(cluster_name: 'my-cluster') do its('security_group_ids') { should_not include default_security_group.group_id } end ``` Matchers -------- This InSpec audit resource has no special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_eks_cluster('AnExistingCluster') do it { should exist } end describe aws_eks_cluster('ANonExistentCluster') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `eks:DescribeCluster` action set to Allow. You can find detailed documentation at [Amazon EKS IAM Policies, Roles, and Permissions](https://docs.aws.amazon.com/eks/latest/userguide/IAM_policies.html) The documentation for EKS actions is at [Policy Structure](https://docs.aws.amazon.com/eks/latest/userguide/iam-policy-structure.html#UsingWithEKS_Actions) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_eks_cluster/aws_eks_clusters resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_eks_clusters.md) Use the `aws_eks_clusters` resource to test the configuration of a collection of AWS Elastic Container Service for Kubernetes. Syntax ------ ``` describe aws_eks_clusters do its('names.count') { should cmp 10 } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on EKS Clusters](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html). Properties ---------- | Property | Description | | --- | --- | | arn | The Amazon Resource Name (ARN) of the cluster. | | name | The name of the cluster. | | endpoint | The endpoint for your Kubernetes API server. | | status | The current status of the cluster. | | version | The Kubernetes server version for the cluster. | | certificate_authority | The certificate-authority-data for your cluster. | | subnets_count | The number of subnets associated with your cluster. | | subnet_ids | The subnets associated with your cluster. | | security_groups_count | The count of security groups associated with your cluster. | | security_group_ids | The security groups associated with the cross-account elastic network interfaces that are used to allow communication between your worker nodes and the Kubernetes control plane. | | role_arn | The Amazon Resource Name (ARN) of the IAM role that provides permissions for the Kubernetes control plane to make calls to AWS API operations on your behalf. | | vpc_id | The VPC associated with your cluster. | | created_at | The Unix epoch timestamp in seconds for when the cluster was created. | | creating | Boolean indicating whether or not the state of the cluster is CREATING. | | active | Boolean indicating whether or not the state of the cluster is ACTIVE. | | failed | Boolean indicating whether or not the state of the cluster is FAILED. | | deleting | Boolean indicating whether or not the state of the cluster is DELETING. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Allow at most 100 EKS Clusters on the account ``` describe aws_eks_clusters do its('entries.count') { should be <= 100} end ``` ### Ensure a specific Cluster exists, by name ``` describe aws_eks_clusters do its('names') { should include('cluster-1') } end ``` ### Ensure no Clusters are in a failed state ``` describe aws_eks_clusters.where( failed: true ) do it { should_not exist ) end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_eks_clusters.where( <property>: <value>) do it { should exist } end describe aws_eks_clusters.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `eks:DescribeCluster` action with Effect set to Allow. You can find detailed documentation at [Amazon EKS IAM Policies, Roles, and Permissions](https://docs.aws.amazon.com/eks/latest/userguide/IAM_policies.html) The documentation for EKS actions is at [Policy Structure](https://docs.aws.amazon.com/eks/latest/userguide/iam-policy-structure.html#UsingWithEKS_Actions) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_eks_clusters/aws_elasticache_cluster resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_elasticache_cluster.md) Use the `aws_elasticache_cluster` InSpec audit resource to test the properties of a single AWS ElastiCache cluster. Syntax ------ An `aws_elasticache_cluster` resource block declares the tests for a single AWS ElastiCache cluster by `cache_cluster_id`. ``` describe aws_elasticache_cluster(cache_cluster_id: 'my-cluster-123') do it { should exist } end ``` The value of the `cache_cluster_id` can be provided as a string. ``` describe aws_elasticache_cluster('my-cluster-123') do its('engine') { should cmp 'redis' } end ``` Parameters ---------- The ElastiCache cluster ID must be provided. ### cache_cluster_id *(required)* The ID of the ElastiCache cluster: * contains between 1 and 50 alphanumeric characters or hyphens, * should start with a letter, * cannot end with a hyphen or contain two consecutive hyphens. It can be passed either as a string or as a `cache_cluster_id: 'value'` key-value entry in a hash. Properties ---------- | Property | Description | | --- | --- | | cache_cluster_id | The user-supplied identifier of the cluster. This identifier is a unique key that identifies a cluster. | | engine | The name of the cache engine, e.g. `redis`. | | node_ids | The id list of all cluster nodes. | | ports | A hash of the node ID and port number pairs. | | status | The current state of the cluster, e.g. `creating`, `available`. | | encrypted_at_rest | Indicates whether the content is encrypted at rest or not. | | encrypted_at_transit | Indicates whether the content is encrypted at transit or not. | There are also additional properties available. For a comprehensive list, see [the API reference documentation](https://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_CacheCluster.html). Examples -------- ### Test that an ElastiCache cluster is available ``` describe aws_elasticache_cluster("my-cluster-123") do its("status") { should eq 'available' } end ``` ### Test that an Elasticache cluster engine is listening on port `11211` ``` describe aws_elasticache_cluster(cache_cluster_id: "my-cluster-123") do its("port") { should cmp 11211 } end ``` ### Test that an Elasticache cluster’s engine version is `1.5.16` ``` describe aws_elasticache_cluster(cache_cluster_id: "my-cluster-123") do its("engine_version") { should cmp 1.5.16 } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist ``` describe aws_elasticache_cluster(cache_cluster_id: "my-cluster-123") do it { should exist } end ``` ### be_encrypted_at_rest ``` describe aws_elasticache_cluster(cache_cluster_id: "my-cluster-123") do it { should be_encrypted_at_rest } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `elasticache:DescribeCacheClusters` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon ElastiCache](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonelasticache.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_elasticache_cluster/aws_elasticache_clusters resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_elasticache_clusters.md) Use the `aws_elasticache_clusters` InSpec audit resource to test the properties of all AWS ElastiCache clusters. To audit a single ElastiCache cluster, use `aws_elasticache_cluster` (singular). Syntax ------ An `aws_elasticache_clusters` resource block collects a group of ElastiCache cluster descriptions and then tests that group. ``` describe aws_elasticache_clusters it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. Properties ---------- | Property | Description | | --- | --- | | ids | The user-supplied identifier of the cluster. This identifier is a unique key that identifies a cluster. | | node_types | The name of the compute and memory capacity node type for the cluster, e.g. `cache.m5.large`. | | engines | The name of the cache engine, e.g. `redis`. | | status | The current state of the cluster, e.g. `creating`, `available`. | | zones | The name of the availability zone in which the cluster is located or “Multiple” if the cache nodes are located in different availability zones. | | subnet_group_names | The name of the cache subnet group. | | encrypted_at_rest | Indicates whether the content is encrypted at rest or not. | | encrypted_at_transit | Indicates whether the content is encrypted at transit or not. | Examples -------- ### Ensure that exactly 3 ElastiCache clusters exist ``` describe aws_elasticache_clusters do its("entries.count") { should cmp 3 } end ``` ### Use this InSpec resource to request the IDs of all ElastiCache clusters, then test in-depth using `aws_elasticache_cluster` and `aws_elasticache_cluster_node`. ``` aws_elasticache_clusters.ids.each do |id| aws_elasticache_cluster(id).node_ids.each do |node_id| describe aws_elasticache_cluster_node(cache_cluster_id: id, node_id: node_id) do it { should exist } end end end ``` Matchers -------- For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_elasticache_clusters.where( <property>: <value>) do it { should exist } end describe aws_elasticache_clusters.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `elasticache:DescribeCacheClusters` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon ElastiCache](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonelasticache.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_elasticache_clusters/aws_elasticache_cluster_node resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_elasticache_cluster_node.md) Use the `aws_elasticache_cluster_node` InSpec audit resource to test the properties of a single AWS ElastiCache cluster node. Syntax ------ An `aws_elasticache_cluster_node` resource block declares the tests for a single AWS ElastiCache cluster node by `cache_cluster_id` and `node_id`. ``` describe aws_elasticache_cluster_node(cache_cluster_id: 'my-cluster-123', node_id: '0001') do it { should exist } end ``` Parameters ---------- The ElastiCache cluster ID and node ID must be provided. ### cache_cluster_id *(required)* The ID of the ElastiCache cluster: * contains between 1 and 50 alphanumeric characters or hyphens, * should start with a letter, * cannot end with a hyphen or contain two consecutive hyphens. It can be passed either as a string or as a `cache_cluster_id: 'value'` key-value entry in a hash. ### node_id *(required)* The ID of the node must be a string containing 4 digits. It can be passed as a `node_id: 'value'` key-value entry in a hash. Properties ---------- | Property | Description | | --- | --- | | id | The cache node identifier, e.g. `0001`. | | port | The port number that the cache engine is listening on. | | address | The DNS hostname of the cache node. | | status | The current state of the cache node. One of the following values: `available`, `creating`, `rebooting`, or `deleting`. | | create_time | The date and time when the cache node was created. | There are also additional properties available. For a comprehensive list, see [the API reference documentation](https://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_CacheNode.html). Examples -------- ### Test that an ElastiCache cluster node is available ``` describe aws_elasticache_cluster_node(cache_cluster_id: "my-cluster-123", node_id: "0001") do its("status") { should eq 'available' } end ``` ### Test that an Elasticache cluster engine is listening on port `11211` ``` describe aws_elasticache_cluster_node(cache_cluster_id: "my-cluster-123", node_id: "0001") do its("port") { should cmp 11211 } end ``` ### Test that an Elasticache cluster node’s customer availability zone is `us-east-2b` ``` describe aws_elasticache_cluster_node(cache_cluster_id: "my-cluster-123", node_id: "0001") do its("customer_availability_zone") { should cmp "us-east-2b" } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist ``` describe aws_elasticache_cluster_node(cache_cluster_id: "my-cluster-123", node_id: "0001") do it { should exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `elasticache:DescribeCacheClusters` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon ElastiCache](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonelasticache.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_elasticache_cluster_node/aws_elb resource ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_elb.md) Use the `aws_elb` InSpec audit resource to test properties of a single AWS Elastic Load Balancer (ELB). Syntax ------ An `aws_elb` resource block declares the tests for a single AWS ELB by ELB name. AWS ELB Names are unique per region. ``` describe aws_elb('my-elb') do it { should exist } end describe aws_elb(load_balancer_name: 'my-elb') do it { should exist } end ``` Parameters ---------- ### load_balancer_name *(required)* This resource accepts a single parameter, the ELB Name which uniquely identifies the ELB. This can be passed either as a string or as a `load_balancer_name: 'value'` key-value entry in a hash. See also the [AWS documentation on Elastic Load Balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference). Properties ---------- | Property | Description | | --- | --- | | load_balancer_name | The name of the load balancer. | | dns_name | The DNS name of the load balancer. | | availability_zones | The Availability Zones for the load balancer. | | instance_ids | An array containing all instance ids associated with the ELB. | | external_ports | An array of the external ports exposed on the ELB. | | internal_ports | An array of the internal ports exposed on the ELB. | | security_group_ids | The security groups for the load balancer. Valid only for load balancers in a VPC. | | vpc_id | The ID of the VPC for the load balancer. | | subnet_ids | The IDs of the subnets for the load balancer. | | listeners | A collection of the listeners for the load balancer. | | ssl_policies | A collection of the SSL Policies configured in-use for the load balancer (and their policy attributes). | | protocols | A list of the protocols configured for the listeners of the load balancer. | Examples -------- ### Test that an ELB has its availability zones configured correctly ``` describe aws_elb('prod_web_app_elb') do its('availability_zones.count') { should be > 1 } its('availability_zones') { should include 'us-east-2a' } its('availability_zones') { should include 'us-east-2b' } end ``` ### Ensure an ELB has the correct number of EC2 Instances associated with it ``` describe aws_elb('prod_web_app_elb') do its('instance_ids.count') { should cmp 3 } end ``` ### Ensure the correct DNS is set ``` describe aws_elb('prod_web_app_elb') do its('dns_name') { should cmp 'your-fqdn.com' } end ``` ### Ensure we only expose port 80, both to the public and internal ``` describe aws_elb('prod_web_app_elb') do its('external_ports.count') { should cmp 1 } its('external_ports') { should include 80 } its('internal_ports.count') { should cmp 1 } its('internal_ports') { should include 80 } end ``` ### Ensure the correct EC2 Instances are associated ``` describe aws_elb('prod_web_app_elb') do its('instance_ids') { should include 'i-12345678' } end ``` Matchers -------- This InSpec audit resource has no special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_elb('AnExistingELB') do it { should exist } end describe aws_elb('ANonExistentELB') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `elasticloadbalancing:DescribeLoadBalancers` action set to Allow. You can find detailed documentation at [Authentication and Access Control for Your Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/load-balancer-authentication-access-control.html) © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_elb/aws_flow_log resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_flow_log.md) Use the `aws_flow_log` InSpec audit resource to test properties of a single Flow Log. Syntax ------ ``` describe aws_flow_log(flow_log_id: 'fl-9c718cf5') do it { should exist } end ``` Parameters ---------- This resource requires at least one of the following parameters to be provided: `flow_log_id`, `subnet_id`, `vpc_id`. ### flow_log_id *(required if no other parameters provided)* The Flow Log ID which uniquely identifies the Flow Log. This can be passed either as a string or as a `flow_log_id: 'value'` key-value entry in a hash. ### subnet_id *(required if no other parameters provided)* The subnet associated with the Flow Log, if applicable. This must be passed as a `subnet_id: 'value'` key-value entry in a hash. ### vpc_id *(required if no other parameters provided)* The VPC associated with the Flow Log, if applicable. This must be passed as a `vpc_id: 'value'` key-value entry in a hash. See also the [AWS documentation on Flow Logs](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html). Properties ---------- | Property | Description | | --- | --- | | flow_log_id | The ID of the Flow Log. | | log_group_name | The name of the associated log group. | | resource_id | The ID of the assosiated resource, e.g. VPC, Subnet or Network Interface. | Examples -------- ### Search for a flow log by the associated subnet id ``` describe aws_flow_log(subnet_id: 'subnet-c6a4319c') do it { should exist } end ``` ### Search for a flow log by the associated VPC id ``` describe aws_flow_log(vpc_id: 'vpc-96cabaef') do it { should exist } end ``` ### Ensure the correct Flow Log is associated with a Subnet ``` describe aws_flow_log(subnet_id: 'subnet-c6a4319c') do its('flow_log_id') { should cmp 'fl-9c718cf5' } end ``` ### Ensure the Flow Log is associated with the correct resource type ``` describe aws_flow_log('fl-9c718cf5') do its('resource_type') { should cmp 'subnet' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_flow_log('AnExistingFlowLog') do it { should exist } end describe aws_flow_log('ANonExistentFlowLog') do it { should_not exist } end ``` ### be_attached_to_eni Indicates that the Flow Log is attached to a ENI resource. ``` describe aws_flow_log('fl-9c718cf5') do it { should be_attached_to_eni } end ``` ### be_attached_to_subnet Indicates that the Flow Log is attached to a subnet resource. ``` describe aws_flow_log('fl-9c718cf5') do it { should be_attached_to_subnet } end ``` ### be_attached_to_vpc Indicates that the Flow Log is attached to a vpc resource. ``` describe aws_flow_log('fl-9c718cf5') do it { should be_attached_to_vpc } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeFlowLogs` actions with Effect set to Allow. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_flow_log/aws_elbs resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_elbs.md) Use the `aws_elbs` InSpec audit resource to test the configuration of a collection of AWS Elastic Load Balancers. Syntax ------ ``` describe aws_elbs do its('load_balancer_names') { should include 'elb-name' } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on Elastic Load Balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference). Properties ---------- | Property | Description | | --- | --- | | load_balancer_names | The name of the load balancer. | | dns_names | The DNS name of the load balancer. | | availability_zones | The Availability Zones for the load balancer. | | instance_ids | An array containing all instance ids associated with the ELB. | | external_ports | An array of the external ports exposed on the ELB. | | internal_ports | An array of the internal ports exposed on the ELB. | | security_group_ids | The security groups for the load balancer. Valid only for load balancers in a VPC. | | vpc_ids | The ID of the VPC for the load balancer. | | subnet_id s | The IDs of the subnets for the load balancer. | Examples -------- ### Ensure there are no Load Balancers with an undesired zone. ``` describe aws_elbs do it { should exist } its('availability_zones') { should_not include 'us-east-1a'} end ``` ### Ensure all ELBs expose only port 80 ``` aws_elbs.each do |elb| describe elb do its('external_ports.count') { should cmp 1 } its('external_ports') { should include 80 } its('internal_ports.count') { should cmp 1 } its('internal_ports') { should include 80 } end end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_elbs.where( <property>: <value>) do it { should exist } end describe aws_elbs.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `elasticloadbalancing:DescribeLoadBalancers` action set to Allow. You can find detailed documentation at [Authentication and Access Control for Your Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/load-balancer-authentication-access-control.html) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_elbs/aws_hosted_zones resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_hosted_zones.md) Use the `aws_hosted_zones` resource to test the hosted zones configuration. Syntax ------ ``` describe aws_hosted_zones do its('names') { should include ("carry-on.films.com") } end ``` Parameters ---------- This resource does not expect any parameters. Properties ---------- | Property | Description | | --- | --- | | name | The name of the hosted zone. | | id | It’s id. | Examples -------- ### Ensure a specific hosted zone exists ``` describe aws_hosted_zones do its('names') { should include ("carry-on.films.com") } end ``` Matchers -------- This InSpec audit resource uses the following special matcher. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### should The control will pass if the describe passes all tests. Use `should` to validate if a specific hosted zone exists ``` describe aws_hosted_zones do its('names') { should include ("carry-on.films.com") } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `route53:ListHostedZones` action with Effect set to Allow. You can find detailed documentation at [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/r53-api-permissions-ref.html) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_hosted_zones/aws_hosted_zone resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_hosted_zone.md) Use the `aws_hosted_zone` resource to test a specific hosted zone configuration. Syntax ------ ``` describe aws_hosted_zone('zone-name') do it { should exist } its ('name_servers.count') { should eq 4 } its ('private_zone') { should be false } its ('record_names') { should include 'sid-james.carry-on.films.com' } end ``` Parameters ---------- This resource takes one parameter, the name of the hosted zone to validate. Properties ---------- | Property | Description | | --- | --- | | name | The name of the hosted zone. | | id | It’s id. | | name_servers | List of the associated name servers | | private_zone | If the hosted zone if private or public | | record_count | Number of associated records | | records | The associated records, flattens the list, so each rule will have multiple records for each type | Examples -------- ### Ensure a specific hosted zone exists ``` describe aws_hosted_zone('zone-name') do it { should exist } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe passes all tests. Use `exist` to validate the hosted zone exists ``` describe aws_hosted_zone('zone-name') do it { should exist } end ``` Use `should_not` to test the entity should not exist. ``` describe aws_hosted_zone('zone-name') do it { should_not exist } end ``` ### should The control will pass if the describe passes all tests. Use `should` to validate the hosted zone if public or private, the number of name servers is correct or that a specific record exists e.g. ``` describe aws_hosted_zone('zone-name') do it { should exist } its ('name_servers.count') { should eq 4 } its ('private_zone') { should be false } its ('record_names') { should include 'sid-james.carry-on.films.com' } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `route53:ListHostedZones` action with Effect set to Allow. You can find detailed documentation at [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/r53-api-permissions-ref.html) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_hosted_zone/aws_iam_access_key resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_access_key.md) Use the `aws_iam_access_key` InSpec audit resource to test properties of a single AWS IAM Access Key. Syntax ------ An `aws_iam_access_key` resource allows the testing of a single AWS IAM Access Key. ``` describe aws_iam_access_key(access_key_id: 'AKIA1111111111111111') do it { should exist } end ``` Parameters ---------- This resources requires either an `access_key_id` or the IAM `username` associated with the Access Key. ### access_key_id *(required if `username` not provided.)* The Access Key ID which uniquely identifies the Key. Begins with the characters “AKIA”. This can be passed either as a string or as a `access_key_id: 'value'` key-value entry in a hash. ### username *(required if `access_key_id` not provided.)* The IAM Username which is associated with the Access Key. This can be passed either as a string or as a `username: 'value'` key-value entry in a hash. See also the [AWS documentation on IAM Access Keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html). Properties ---------- | Property | Description | | --- | --- | | access_key_id | The ID of the Access Key. | | username | The IAM Username which is associated with the Access Key. | | status | The status of the Access Key, e.g. “Active”. | | create_date | The creation date of the Access Key. | Examples -------- The following examples show how to use this InSpec audit resource. ### Test that an IAM Access Key has been used in the last 90 days ``` describe aws_iam_access_key(access_key_id: 'AKIA1111111111111111') do it { should exist } its('last_used_date') { should be > Time.now - 90 * 86400 } end ``` ### Test that an IAM Access Key for a specific user exists ``` describe aws_iam_access_key(username: 'psmith', id: 'AKIA1111111111111111') do it { should exist } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` it { should exist } it { should_not exist } ``` ### active The `active` matcher tests if the described IAM Access Key has a status of Active. ``` it { should be_active } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the following permissions action set to allow: `iam:ListAccessKeys` `iam:GetAccessKeyLastUsed` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_access_key/aws_iam_access_keys resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_access_keys.md) Use the `aws_iam_access_keys` InSpec audit resource to test properties of some or all AWS IAM Access Keys. Syntax ------ An `aws_iam_access_keys` resource block returns all IAM Access Keys and allows the testing of that group of Access Keys. ``` describe aws_iam_access_keys do it { should exist } its('access_key_ids') { should include 'AKIA1111111111111111' } end ``` Parameters ---------- This resources accepts a single optional parameter, a Username for which to retrieve all Access Keys. If not provided, all Access Keys for all Users will be retrieved. ### username *(optional)* The IAM Username for which to retrieve the Access Keys. This can be passed either as a string or as a `username: 'value'` key-value entry in a hash. See also the [AWS documentation on IAM Access Keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html). Properties ---------- | Property | Description | | --- | --- | | access_key_id | The ID of the Access Key. | | username | The IAM Username which is associated with the Access Key. | | active | Indicates if the status of the Key is Active. | | inactive | Indicates if the status of the Key is Inactive. | | ever_used | Indicates if the Key has ever been used. | | never_used | Indicates if the Key has never been used. | | create_date | The creation date of the Access Key. | | created_days_ago | How many days ago the Access Key was created. | | created_hours_ago | How many hours ago the Access Key was created. | | created_with_user | Boolean indicating if the Access Key was created with a User. | | last_used_date | The date the Access Key was last used. | | last_used_hours_ago | How many hours ago the Key was last used. | | last_used_days_ago | How many days ago the Key was last used. | | user_created_date | The date on which the associated User was created. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Test all Active keys ``` describe aws_iam_access_keys.where(active: true) do its('access_key_ids') { should include 'AKIA1111111111111111' } end ``` ### Ensure a User has no Access Keys ``` describe aws_iam_access_keys.where(username: 'untrusted-account') do it { should_not exist } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` it { should exist } it { should_not exist } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the following permissions set to Allow: `iam:GetUser` `iam:GetAccessKeyLastUsed` `iam:ListUsers` `iam:ListAccessKeys` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_access_keys/aws_iam_account_alias resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_account_alias.md) Use the `aws_iam_account_alias` InSpec audit resource to test properties of the AWS IAM account alias. Syntax ------ An `aws_iam_account_alias` resource block may be used to perform tests on details of the AWS account alias. ``` describe aws_iam_account_alias do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on Account Aliases](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html). Properties ---------- | Property | Description | | --- | --- | | alias | String containing the Alias of the account. | Examples -------- ### Check that the account alias has not be set ``` describe aws_iam_account_alias do it { should_not exist } end ``` ### Test if the account alias starts with expected prefix ``` describe aws_iam_account_alias do it { should exist } its('alias') { should match /^chef-/ } end ``` Matchers -------- ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_iam_account_alias do it { should exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `iam:ListAccountAliases` action with Effect set to Allow. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_account_alias/aws_iam_group resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_group.md) Use the `aws_iam_group` InSpec audit resource to test properties of a single IAM group. Syntax ------ An `aws_iam_group` resource block identifies a group by group name. ``` describe aws_iam_group('mygroup') do it { should exist } end # Hash syntax for group name describe aws_iam_group(group_name: 'mygroup') do it { should exist } end ``` Parameters ---------- ### group_name *(required)* This resource accepts a single parameter, the Group Name which uniquely identifies the IAM Group. This can be passed either as a string or as a `group_name: 'value'` key-value entry in a hash. See also the [AWS documentation on IAM Groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html). Properties ---------- | Property | Description | | --- | --- | | group_name | The group name. | | group_id | The group ID. | | arn | The Amazon Resource Name of the group. | | users | Array of users associated with the group. | Examples -------- ### Ensure group contains a certain user ``` describe aws_iam_group('admin-group') do its('users') { should include 'deployment-service-account')} end ``` Matchers -------- ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_iam_group('AnExistingGroup') do it { should exist } end describe aws_iam_group('ANonExistentGroup') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `iam:GetGroup` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_group/aws_iam_groups resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_groups.md) Use the `aws_iam_groups` InSpec audit resource to test properties of a collection of IAM groups. Syntax ------ An `aws_iam_groups` resource block identifies a group by group name. ``` describe aws_iam_groups('mygroup') do it { should exist } end # Hash syntax for group name describe aws_iam_groups(group_name: 'mygroup') do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on IAM Groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html). Properties ---------- | Property | Description | | --- | --- | | group_names | The group name. | | group_ids | The group ID. | | arns | The Amazon Resource Name of the group. | | users | Array of users associated with the group. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Ensure group contains a certain user ``` describe aws_iam_groups do it { should exist } its('group_names') { should include 'prod-access-group' } end ``` Matchers -------- ### exist The control will pass if a group with the given group name exists. ``` describe aws_iam_groups do it { should exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `iam:ListGroup` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_groups/aws_iam_inline_policy resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_inline_policy.md) Use the `aws_iam_inline_policy` InSpec audit resource to test properties of a single inline AWS IAM Policy embedded with IAM User, IAM Group or IAM Role. For managed policies, use the `aws_iam_policy` resource. Syntax ------ An `aws_iam_inline_policy` resource block identifies an inline policy by policy name and user/group/role by name ``` # Find an inline policy by name and role name describe aws_iam_inline_policy(role_name: 'role-x', policy_name: 'policy-1') do it { should exist } end # Find an inline policy by name and group name describe aws_iam_inline_policy(group_name: 'group-x', policy_name: 'policy-1') do it { should exist } end # Find an inline policy by name and user name describe aws_iam_inline_policy(user_name: 'user-a', policy_name: 'policy-1') do it { should exist } end ``` Parameters ---------- This resource requires `policy_name` and one of the `role_name`, `group_name` or `user_name` to be provided. See AWS Documentation on inline policies for more details * [get-role-policy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-role-policy.html) * [get-group-policy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-group-policy.html) * [get-user-policy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-user-policy.html) Properties ---------- | Property | Description | | --- | --- | | policy | Returns the default version of the policy document after decoding as a Ruby hash. This hash contains the policy statements and is useful for performing checks that cannot be expressed using higher-level matchers like `have_statement`. | | statement_count | Returns the number of statements present in the `policy`. | Examples -------- ### Test that a policy does exist ``` describe aws_iam_inline_policy(role_name: 'role-x', policy_name: 'policy-1') do it { should exist } end ``` ### Examine the policy statements ``` describe aws_iam_inline_policy(role_name: 'role-x', policy_name: 'policy-1') do # Verify that there is at least one statement allowing access to S3 it { should have_statement(Action: 's3:PutObject', Effect: 'allow') } # have_statement does not expand wildcards. If you want to verify # they are absent, an explicit check is required. it { should_not have_statement(Action: 's3:*') } # You can also check NotAction it { should_not have_statement(NotAction: 'iam:*') } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` it { should exist } it { should_not exist } ``` ### have_statement Examines the list of statements contained in the policy and passes if at least one of the statements matches. This matcher does *not* interpret the policy in a request authorization context, as AWS does when a request processed. Rather, `have_statement` examines the literal contents of the IAM policy, and reports on what is present (or absent, when used with `should_not`). `have_statement` accepts the following criteria to search for matching statements. If any statement matches all the criteria, the test is successful. All criteria may be used as Titlecase (as in the AWS examples) or lowercase, string or symbol. * `Action` - Expresses the requested operation. Acceptable literal values are any AWS operation name, including the ‘*’ wildcard character. `Action` may also use a list of AWS operation names. * `Effect` - Expresses if the operation is permitted. Acceptable values are ‘Deny’ and ‘Allow’. * `Sid` - A user-provided string identifier for the statement. * `Resource` - Expresses the operation’s target. Acceptable values are ARNs, including the ‘*’ wildcard. `Resource` may also use a list of ARN values. Please note the following about the behavior of `have_statement`: * `Action`, `Sid`, and `Resource` allow using a regular expression as the search critera instead of a string literal. * it does not support wildcard expansion; to check for a wildcard value, check for it explicitly. For example, if the policy includes a statement with `"Action": "s3:*"` and the test checks for `Action: "s3:PutObject"`, the test *will not match*. You must write an additional test checking for the wildcard case. * it supports searching list values. For example, if a statement contains a list of 3 resources, and a `have_statement` test specifes *one* of those resources, it will match. * `Action` and `Resource` allow using a list of string literals or regular expressions in a test, in which case *all* must match on the *same* statement for the test to match. Order is ignored. * it does not support the `[Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal)` or `Conditional` key, or any of `NotAction`, `Not[Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal)`, or `NotResource`. Examples: ``` # Verify there is no full-admin statement describe aws_iam_inline_policy(role_name: 'role-x', policy_name: 'policy-1') do it { should_not have_statement('Effect' => 'Allow', 'Resource' => '*', 'Action' => '*')} end # Symbols and lowercase also allowed as criteria describe aws_iam_inline_policy(role_name: 'role-x', policy_name: 'policy-1') do # All 4 the same it { should_not have_statement('Effect' => 'Allow', 'Resource' => '*', 'Action' => '*')} it { should_not have_statement('effect' => 'Allow', 'resource' => '*', 'action' => '*')} it { should_not have_statement(Effect: 'Allow', Resource: '*', Action: '*')} it { should_not have_statement(effect: 'Allow', resource: '*', action: '*')} end # Verify bob is allowed to manage things on S3 buckets that start with bobs-stuff describe aws_iam_inline_policy(role_name: 'role-x', policy_name: 'policy-1') do it { should have_statement(Effect: 'Allow', # Using the AWS wildcard - this must match exactly Resource: 'arn:aws:s3:::bobs-stuff*', # Specify a list of actions - all must match, no others, order isn't important Action: ['s3:PutObject', 's3:GetObject', 's3:DeleteObject'])} # Bob would make new buckets constantly if we let him. it { should_not have_statement(Effect: 'Allow', Action: 's3:CreateBucket')} it { should_not have_statement(Effect: 'Allow', Action: 's3:*')} it { should_not have_statement(Effect: 'Allow', Action: '*')} # An alternative to checking for wildcards is to specify the # statements you expect, then restrict statement count its('statement_count') { should cmp 1 } end # Use regular expressions to examine the policy describe aws_iam_inline_policy(role_name: 'role-x', policy_name: 'policy-1') do # Check to see if anything mentions RDS at all. # This catches `rds:CreateDBinstance` and `rds:*`, but would not catch '*'. it { should_not have_statement(Action: /^rds:.+$/)} # This policy should refer to both sally and kim's s3 buckets. # This will only match if there is a statement that refers to both resources. it { should have_statement(Resource: [/arn:aws:s3.+:sally/, /arn:aws:s3.+:kim/]) } # The following also matches on a statement mentioning only one of them it { should have_statement(Resource: /arn:aws:s3.+:(sally|kim)/) } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `iam:GetUserPolicy`, `iam:GetRolePolicy`, and `iam:GetGroupPolicy` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_inline_policy/aws_iam_password_policy resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_password_policy.md) Use the `aws_iam_password_policy` InSpec audit resource to test properties of an AWS IAM Password Policy. Syntax ------ An `aws_iam_password_policy` resource block declares the tests for an AWS IAM Password Policy. ``` describe aws_iam_password_policy do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on Auto Scaling Group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html). Properties ---------- | Property | Description | | --- | --- | | minimum_password_length | The minimum character count of the password policy. | | max_password_age_in_days | Integer representing in days how long a password may last before expiring. | | number_of_passwords_to_remember | Number of previous passwords to remember. | Examples -------- ### Test that a Password Policy meets your company’s requirements. ``` describe aws_iam_password_policy do it { should require_uppercase_characters } it { should require_lowercase_characters } it { should require_numbers } its('minimum_password_length') { should be > 8 } end ``` ### Test that users can change their own passwords ``` describe aws_iam_password_policy do it { should allow_users_to_change_password } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist ``` it { should exist } ``` ### prevent_password_reuse ``` it { should prevent_password_reuse } ``` ### expire_passwords ``` it { should expire_passwords } ``` ### require_numbers ``` it { should require_numbers } ``` ### require_symbols ``` it { should require_symbols } ``` ### require_lowercase_characters ``` it { should require_lowercase_characters } ``` ### require_uppercase_characters ``` it { should require_uppercase_characters} ``` ### allow_users_to_change_passwords ``` it { should allow_users_to_change_password } ``` All matchers can use the inverse `should_not` predicate. AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the following permissions action set to allow: `iam:GetAccountPasswordPolicy` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_password_policy/aws_iam_policies resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_policies.md) Use the `aws_iam_policies` InSpec audit resource to test properties of a collection of AWS IAM Policies. Syntax ------ `aws_iam_policies` Resource returns a collection of IAM Policies and allows testing of that collection. ``` describe aws_iam_policies do its('policy_names') { should include('test-policy-1') } end ``` Parameters ---------- ### only_attached *(optional)* This resource allows filtering by only_attached. When `OnlyAttached` is `true`, the returned list contains only the policies that are attached to an IAM user, group, or role. When `OnlyAttached` is `false`, or when the parameter is not included, all policies are returned. ### scope *(optional)* This resource allows filtering by scope. To list only AWS managed policies, set `Scope` to `AWS`. To list only the customer managed policies in your AWS account, set `Scope` to `Local`. If scope is not supplied `ALL` policies are returned. See also the [AWS documentation on IAM Policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html). Properties ---------- | Property | Description | | --- | --- | | arns | The ARN identifier of the specified policy. | | policy_ids | The policy ids. | | policy_names | The policy names. | | attachment_counts | The count of attached entities for each policy. | | attached_groups | The list of group names of the groups attached to each policy. | | attached_roles | The list of role names of the roles attached to each policy. | | attached_users | The list of usernames of the users attached to each policy. | | default_version_ids | The ‘default_version_id’ value of each policy. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Ensure a policy exists ``` describe aws_iam_policies do its('policy_names') { should include('test-policy-1') } end ``` ### Allow at most 100 IAM Policies on the account ``` describe aws_iam_policies do its('entries.count') { should be <= 100} end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_iam_policies.where( <property>: <value>) do it { should exist } end describe aws_iam_policies.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `iam:ListPolicies` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_policies/aws_iam_role resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_role.md) Use the `aws_iam_role` InSpec audit resource to test properties of an AWS IAM Role. Syntax ------ An `aws_iam_role` resource block declares the tests for a single AWS IAM Role by Role Name. ``` describe aws_iam_role(role_name: 'my-role') do it { should exist } end ``` Parameters ---------- ### role_name *(required)* This resource accepts a single parameter, the Role Name which uniquely identifies the Role. This can be passed either as a string or as a `role_name: 'value'` key-value entry in a hash. See also the [AWS documentation on IAM Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html). Properties ---------- | Property | Description | | --- | --- | | path | The path to the role. | | role_name | The name of the role. | | role_id | The id of the role. | | arn | The Amazon Resource Name (ARN) specifying the role. | | create_date | The date and time, in ISO 8601 date-time format , when the role was created. | | assume_role_policy_document | The policy that grants an entity permission to assume the role. | | description | The description of the role. | | max_session_duration | The maximum session duration (in seconds) for the specified role. Anyone who uses the AWS CLI, or API to assume the role can specify the duration using the optional DurationSeconds API parameter or duration-seconds CLI parameter. | | permissions_boundary_type | The permissions boundary usage type that indicates what type of IAM resource is used as the permissions boundary for an entity. This data type can only have a value of Policy . | | permissions_boundary_arn | The ARN of the policy used to set the permissions boundary for the user or role. | | inline_policies | A list of inline policy names associated with the described role. | | attached_policies_name | A list of attached policy names associated with the described role. | | attached_policies_arn | A list of attached policy ARNs associated with the described role. | Examples -------- ### Test that an IAM Role exists ``` describe aws_iam_role(role_name: aws_iam_role_name) do it { should exist } its('role_name') { should eq aws_iam_role_name } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_iam_role('AnExistingRole') do it { should exist } end describe aws_iam_role('ANonExistentRole') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the following permissions action set to allow: `iam:GetRole` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_role/aws_iam_policy resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_policy.md) Use the `aws_iam_policy` InSpec audit resource to test properties of a single managed AWS IAM Policy. Syntax ------ An `aws_iam_policy` resource block identifies a policy by policy name or arn ``` # Find a policy by name describe aws_iam_policy('AWSSupportAccess') do it { should exist } end # Hash syntax for policy name describe aws_iam_policy(policy_name: 'AWSSupportAccess') do it { should exist } end ``` Parameters ---------- This resource requires either the `policy_name` or the `policy_arn` to be provided. ### policy_name *(required if `policy_arn` not provided)* The Policy Name which uniquely identifies the Policy. This must be passed as a `policy_name: 'value'` key-value entry in a hash. ### policy_arn *(required if `policy_name` not provided)* The Policy ARN which uniquely identifies the Policy. This must be passed as a `policy_arn: 'value'` key-value entry in a hash. See also the [AWS documentation on IAM Policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html). Properties ---------- | Property | Description | | --- | --- | | arn | The ARN identifier of the specified policy. | | attachment_count | The count of attached entities for the specified policy. | | attached_groups | The list of group names of the groups attached to the policy. | | attached_roles | The list of role names of the roles attached to the policy. | | attached_users | The list of usernames of the users attached to the policy. | | default_version_id | The ‘default_version_id’ value of the specified policy. | | policy | Returns the default version of the policy document after decoding as a Ruby hash. This hash contains the policy statements and is useful for performing checks that cannot be expressed using higher-level matchers like `have_statement`. | | statement_count | Returns the number of statements present in the `policy`. | Examples -------- ### Test that a policy does exist ``` describe aws_iam_policy('AWSSupportAccess') do it { should exist } end ``` ### Test that a policy is attached to at least one entity ``` describe aws_iam_policy('AWSSupportAccess') do it { should be_attached } end ``` ### Examine the policy statements ``` describe aws_iam_policy('my-policy') do # Verify that there is at least one statement allowing access to S3 it { should have_statement(Action: 's3:PutObject', Effect: 'allow') } # have_statement does not expand wildcards. If you want to verify # they are absent, an explicit check is required. it { should_not have_statement(Action: 's3:*') } # You can also check NotAction it { should_not have_statement(NotAction: 'iam:*') } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` it { should exist } it { should_not exist } ``` ### be_attached The test will pass if the identified policy is attached to at least one IAM user, group, or role. ``` describe aws_iam_policy('AWSSupportAccess') do it { should be_attached } end ``` ### be_attached_to_group(GROUPNAME) The test will pass if the identified policy attached the specified group. ``` describe aws_iam_policy('AWSSupportAccess') do it { should be_attached_to_group(GROUPNAME) } end ``` ### be_attached_to_user(USERNAME) The test will pass if the identified policy attached the specified user. ``` describe aws_iam_policy('AWSSupportAccess') do it { should be_attached_to_user(USERNAME) } end ``` ### be_attached_to_role(ROLENAME) The test will pass if the identified policy attached the specified role. ``` describe aws_iam_policy('AWSSupportAccess') do it { should be_attached_to_role(ROLENAME) } end ``` ### have_statement Examines the list of statements contained in the policy and passes if at least one of the statements matches. This matcher does *not* interpret the policy in a request authorization context, as AWS does when a request processed. Rather, `have_statement` examines the literal contents of the IAM policy, and reports on what is present (or absent, when used with `should_not`). `have_statement` accepts the following criteria to search for matching statements. If any statement matches all the criteria, the test is successful. All criteria may be used as Titlecase (as in the AWS examples) or lowercase, string or symbol. * `Action` - Expresses the requested operation. Acceptable literal values are any AWS operation name, including the ‘*’ wildcard character. `Action` may also use a list of AWS operation names. * `Effect` - Expresses if the operation is permitted. Acceptable values are ‘Deny’ and ‘Allow’. * `Sid` - A user-provided string identifier for the statement. * `Resource` - Expresses the operation’s target. Acceptable values are ARNs, including the ‘*’ wildcard. `Resource` may also use a list of ARN values. Please note the following about the behavior of `have_statement`: * `Action`, `Sid`, and `Resource` allow using a regular expression as the search critera instead of a string literal. * It does not support wildcard expansion; to check for a wildcard value, check for it explicitly. For example, if the policy includes a statement with `"Action": "s3:*"` and the test checks for `Action: "s3:PutObject"`, the test *will not match*. You must write an additional test checking for the wildcard case. * It supports searching list values. For example, if a statement contains a list of 3 resources, and a `have_statement` test specifes *one* of those resources, it will match. * `Action` and `Resource` allow using a list of string literals or regular expressions in a test, in which case *all* must match on the *same* statement for the test to match. Order is ignored. * It does not support the [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html), [NotPrincipal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html) or [Condition](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html). Examples: ``` # Verify there is no full-admin statement describe aws_iam_policy('kryptonite') do it { should_not have_statement('Effect' => 'Allow', 'Resource' => '*', 'Action' => '*')} end # Symbols and lowercase also allowed as criteria describe aws_iam_policy('kryptonite') do # All 4 the same it { should_not have_statement('Effect' => 'Allow', 'Resource' => '*', 'Action' => '*')} it { should_not have_statement('effect' => 'Allow', 'resource' => '*', 'action' => '*')} it { should_not have_statement(Effect: 'Allow', Resource: '*', Action: '*')} it { should_not have_statement(effect: 'Allow', resource: '*', action: '*')} end # Verify bob is allowed to manage things on S3 buckets that start with bobs-stuff describe aws_iam_policy('bob-is-a-packrat') do it { should have_statement(Effect: 'Allow', # Using the AWS wildcard - this must match exactly Resource: 'arn:aws:s3:::bobs-stuff*', # Specify a list of actions - all must match, no others, order isn't important Action: ['s3:PutObject', 's3:GetObject', 's3:DeleteObject'])} # Bob would make new buckets constantly if we let him. it { should_not have_statement(Effect: 'Allow', Action: 's3:CreateBucket')} it { should_not have_statement(Effect: 'Allow', Action: 's3:*')} it { should_not have_statement(Effect: 'Allow', Action: '*')} # An alternative to checking for wildcards is to specify the # statements you expect, then restrict statement count its('statement_count') { should cmp 1 } end # Use regular expressions to examine the policy describe aws_iam_policy('regex-demo') do # Check to see if anything mentions RDS at all. # This catches `rds:CreateDBinstance` and `rds:*`, but would not catch '*'. it { should_not have_statement(Action: /^rds:.+$/)} # This policy should refer to both sally and kim's s3 buckets. # This will only match if there is a statement that refers to both resources. it { should have_statement(Resource: [/arn:aws:s3.+:sally/, /arn:aws:s3.+:kim/]) } # The following also matches on a statement mentioning only one of them it { should have_statement(Resource: /arn:aws:s3.+:(sally|kim)/) } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `iam:GetPolicy`, `iam:ListPolicy`, and `iam:ListEntitiesForPolicy` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_policy/aws_iam_roles resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_roles.md) Use the `aws_iam_roles` InSpec audit resource to test properties of a collection of AWS IAM Roles. Syntax ------ An `aws_iam_roles` resource block returns all IAM Roles and allows the testing of that group of Roles. ``` describe aws_iam_roles do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on IAM Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html). Properties ---------- | Property | Description | | --- | --- | | paths | The path to the role. | | role_names | The name of the role. | | role_ids | The id of the role. | | arns | The Amazon Resource Name (ARN) specifying the role. | | create_date | The date and time, in ISO 8601 date-time format , when the role was created. | | assume_role_policy_document | The policy that grants an entity permission to assume the role. | | description | The description of the role. | | max_session_duration | The maximum session duration (in seconds) for the specified role. Anyone who uses the AWS CLI, or API to assume the role can specify the duration using the optional DurationSeconds API parameter or duration-seconds CLI parameter. | | permissions_boundary_type | The permissions boundary usage type that indicates what type of IAM resource is used as the permissions boundary for an entity. This data type can only have a value of Policy . | | permissions_boundary_arn | The ARN of the policy used to set the permissions boundary for the user or role. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Ensure the Role ‘RDS-RW’ exists. ``` describe aws_iam_roles do its('role_names') { should include 'RDS-RW' } end ``` ### Ensure no Roles have `max_session_duration` greater or equal to 2hrs. ``` describe aws_iam_roles.where{ max_session_duration >= (60*120) } do it { should_not exist } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `exists` matcher tests if the filtered IAM User(s) exists. ``` describe aws_iam_roles.where( <property>: <param>) do it { should exist } end ``` You may also use `it { should_not exist }`. AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the following permissions set to Allow: `iam:ListRoles` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_roles/aws_iam_saml_providers resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_saml_providers.md) Use the `aws_iam_saml_providers` InSpec audit resource to test properties of some or all AWS IAM SAML Providers. Syntax ------ An `aws_iam_saml_providers` resource block returns all IAM SAML Providers and allows the testing of that group of Providers. ``` describe aws_iam_saml_providers do it { should exist } end ``` Parameters ---------- ### saml_provider_arn *(required)* This resource accepts a single parameter, the ARN of the SAML Provider. This can be passed either as a string or as a `saml_provider_arn: 'value'` key-value entry in a hash. Properties ---------- | Property | Description | | --- | --- | | provider_arns | The ARNs of the returned providers. | | valid_untils | The expiration date and time for the SAML provider. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Ensure we have at least one provider currently valid ``` describe.one do aws_iam_saml_providers.provider_arns.each do |provider_arn| describe aws_iam_saml_provider(provider_arn) do it { should exist } its('arn') { should match("arn:aws:iam::.*:saml-provider\/FANCY") } its('valid_until') { should be > Time.now + 90 * 86400 } end end end ``` ### Ensure we have one and only one SAML provider ``` describe aws_iam_saml_providers do its('entries.count') { should cmp 1 } end ``` ### Ensure we have at least one provider that matches ``` describe aws_iam_saml_providers.where{ arn =~ /arn:aws:iam::.*:saml-provider\/FANCY/ } do it { should exist } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exists The `exists` matcher tests if the filtered IAM SAML Provider(s) exists. ``` describe aws_iam_saml_providers.where( <property>: <param>) do it { should exist } end ``` You may also use `it { should_not exist }`. AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the following permissions set to Allow: `iam:ListSamlProviders` `iam:GetSamlProvider` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_saml_providers/aws_iam_root_user resource ============================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_root_user.md) Use the `aws_iam_root_user` InSpec audit resource to test properties of an AWS IAM Root User. Syntax ------ An `aws_iam_root_user` resource block declares the tests for a single AWS IAM Root User by user name. ``` describe aws_iam_root_user do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on Root Users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html). Properties ---------- | Property | Description | | --- | --- | | summary_account | A hash containing a summary of the Root User’s account. Properties within this hash can be accessed and tested against. Please see the [API Documentation](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccountSummary.html) for details on the available properties. | | virtual_devices | A list of the virtual MFA devices in the AWS account. | Examples -------- ### Test that an IAM Root User has MFA enabled ``` describe aws_iam_root_user do it { should have_mfa_enabled } end ``` ### Test that an IAM Root User does not have an access key ``` describe aws_iam_root_user do it { should_not have_access_key } end ``` ### Test the IAM Root User has virtual MFA enabled ``` describe aws_iam_root_user do it { should have_virtual_mfa_enabled } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_iam_root_user do it { should exist } end ``` ### have_mfa_enabled ``` it { should have_mfa_enabled } ``` ### have_virtual_mfa_enabled ``` it { should have_virtual_mfa_enabled } ``` ### have_access_key ``` it { should have_access_key } ``` ### have_hardware_mfa_enabled ``` it { should have_hardware_mfa_enabled } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the following permissions action set to allow: `iam:GetAccountSummary` `iam:ListVirtualMFADevices` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_root_user/aws_iam_saml_provider resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_saml_provider.md) Use the `aws_iam_saml_provider` InSpec audit resource to test properties of an AWS IAM SAML Provider. Syntax ------ An `aws_iam_saml_provider` resource block declares the tests for a single AWS IAM SAML Provider by Provider ARN. ``` describe aws_iam_saml_provider('arn:aws:iam::123456789012:saml-provider/FANCY') do it { should exist } end ``` Parameters ---------- ### saml_provider_arn *(required)* This resource accepts a single parameter, the ARN of the SAML Provider. This can be passed either as a string or as a `saml_provider_arn: 'value'` key-value entry in a hash. Properties ---------- | Property | Description | | --- | --- | | provider | The provider. | | arn | The arn of the provider. | | saml_metadata_document | Metadata document associated with the saml provider. | | valid_until | The expiration date and time for the SAML provider. | | create_date | The date and time, in ISO 8601 date-time format , when the role was created. | Examples -------- #### Ensure we have at least one provider currently valid ``` describe aws_iam_saml_provider("arn:aws:iam::123456789012:saml-provider/FANCY") do it { should exist } its("arn") { should match("arn:aws:iam::.*:saml-provider\/FANCY") } its("valid_until") { should be > Time.now + 90 * 86400 } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exists The `exists` matcher tests if the filtered IAM SAML Provider(s) exists. ``` describe aws_iam_saml_provider('arn:aws:iam::123456789012:saml-provider/FANCY') do it { should exist } end ``` You may also use `it { should_not exist }`. AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the following permissions set to Allow: `iam:GetSamlProvider` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_saml_provider/aws_internet_gateway resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_internet_gateway.md) Use the `aws_internet_gateway` InSpec audit resource to test the properties of a single AWS internet gateway. Syntax ------ An `aws_internet_gateway` resource block declares the tests for a single AWS internet gateway by id or name. ``` describe aws_internet_gateway(id: 'igw-abc0123456789deff') do it { should exist } end describe aws_internet_gateway(name: 'my-igw') do it { should exist } end ``` Parameters ---------- Either the id or the name must be provided. ### id *(required if `name` not provided)* The value of the `internet_gateway_id` assigned by the AWS after the resource has been created. This should be in the format of `igw-` followed by 8 or 17 hexadecimal characters and passed as an `id: 'value'` key-value entry in a hash. ### name *(required if `id` not provided)* If a `Name` tag is applied to the internet gateway, this can be used to lookup the resource. This must be passed as a `name: 'value'` key-value entry in a hash. If there are multiple internet gateways with the same name, this resource will raise an error. Properties ---------- | Property | Description | | --- | --- | | id | The ID of the internet gateway. | | name | The value of the `Name` tag. It is `nil` if not defined. | | vpc_id | The ID of the attached VPC. It is `nil` if the resource is in a `detached` state. | | tags | A hash, with each key-value pair corresponding to an internet gateway tag. | | attached? | Indicates whether the internet gateway is **attached** to a VPC or not (`true` or `false`). | | detached? | Indicates whether the internet gateway is in a **detached** state or not (`true` or `false`). | | owner_id | The ID of the AWS account that owns the internet gateway. | There are also additional properties available. For a comprehensive list, see [the API reference documentation](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InternetGateway.html) Examples -------- ### Test that the internet gateway is attached ``` describe aws_internet_gateway(name: 'my-igw') do it { should be_attached } end ``` ### Test that the ID of the attached VPC is `vpc-1234567890abcdef1` ``` describe aws_internet_gateway(id: 'igw-abc0123456789deff') do its('vpc_id') { should eq `vpc-1234567890abcdef1` } end ``` ### Test that the internet gateway has a certain tag ``` describe aws_internet_gateway(name: 'my-igw') do its('tags') { should include('environment' => 'dev') } its('tags') { should include('shutdown-at-10-pm') } # Regardless of the value end ``` Matchers -------- This InSpec audit resource has the following special matcher. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist ``` describe aws_internet_gateway(name: 'my-igw') do it { should exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeInternetGateways` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_internet_gateway/aws_iam_user resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_user.md) Use the `aws_iam_user` InSpec audit resource to test properties of a single AWS IAM User. Syntax ------ An `aws_iam_user` resource block declares the tests for a single AWS IAM User by user name. ``` describe aws_iam_user(user_name: 'psmith') do it { should exist } end ``` Parameters ---------- ### user_name *(required)* This resource accepts a single parameter, the User’s username which uniquely identifies the User. This can be passed either as a string or as a `user_name: 'value'` key-value entry in a hash. See also the [AWS documentation on IAM Users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html). Properties ---------- | Property | Description | | --- | --- | | username | The user’s username. | | user_id | The user’s ID. | | user_arn | The Amazon Resource Name of the user. | | access_keys | An array of hashes each containing metadata about the user’s Access Keys. | | inline_policy_names | The names of policies directly attached to the user. | | attached_policy_names | The name of standalone IAM policies which are attached to the user. | | attached_policy_arns | The arns of the standalone IAM policies which are attached to the user. | * has_mfa_enabled * has_console_password Examples -------- The following examples show how to use this InSpec audit resource. ### Test that an IAM user does not exist ``` describe aws_iam_user(user_name: 'invalid-user') do it { should_not exist } end ``` ### Test that an IAM user has MFA enabled ``` describe aws_iam_user('psmith') do it { should exist } it { should have_mfa_enabled } end ``` ### Ensure a User has no Access Keys or Inline Policies ``` describe aws_iam_user('psmith') do it { should exist } its('access_keys') { should be_empty } its('inline_policy_names') { should be_empty } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` it { should exist } ``` ### has_mfa_enabled This will check if the requested User has Multi Factor Authentication enabled. ``` it { should have_mfa_enabled } ``` #### has_console_password This will ensure the User has a console password set. ``` it { should have_console_password } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the following permissions action set to allow: `iam:GetUser` `iam:GetLoginProfile` `iam:ListMFADevices` `iam:ListAccessKeys` `iam:ListUserPolicies` `iam:ListAttachedUserPolicies` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_user/aws_iam_users resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_iam_users.md) Use the `aws_iam_users` InSpec audit resource to test properties of some or all AWS IAM Users. Syntax ------ An `aws_iam_users` resource block returns all IAM Users and allows the testing of that group of Users. ``` describe aws_iam_users do its('usernames') { should include 'payroll-admin' } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on IAM Users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html). Properties ---------- | Property | Description | | --- | --- | | usernames | The usernames of the returned Users. | | user_arns | The Amazon Resource Names of the returned Users. | | user_ids | The IDs of the returned Users. | | access_keys | Array of Access Keys belonging to each User. | | has_attached_policies | Whether or not the User has IAM Policies attached. | | attached_policy_names | The names (if any) of the IAM Policies attached to the User. | | attached_policy_arns | The Amazon Resource Names (if any) of the IAM Policies attached to the User. | | has_console_password | Whether or not the User has a console password set. | | has_inline_policies | Boolean indicating whether or not the User has policies set directly on them. | | inline_policy_names | The names of the policies (if any) which are directly on the User. | | has_mfa_enabled | Boolean indicating whether the User has MFA enabled or not. | | password_ever_used? | Whether the user has even used their console password. | | password_last_used_days_ago | How long ago, in days, since the user last used their console password. Returns `-1` if the password has never been used. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Ensure there are no Users who do not have MFA enabled. ``` describe aws_iam_users.where( has_mfa_enabled: false) do it { should_not exist } end ``` ### Ensure there are no Users with inline policies ``` describe aws_iam_users.where(has_inline_policies: true) do its('usernames') { should be_empty } end ``` ### Ensure there are no Users with attached policies ``` describe aws_iam_users.where(has_attached_policies: true) do its('usernames') { should be_empty } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_iam_users.where( <property>: <value>) do it { should exist } end describe aws_iam_users.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the following permissions set to Allow: `iam:GetLoginProfile` `iam:ListUsers` `iam:ListMFADevices` `iam:ListAccessKeys` `iam:ListUserPolicies` `iam:ListAttachedUserPolicies` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_iam_users/aws_kms_key resource ====================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_kms_key.md) Use the `aws_kms_key` InSpec audit resource to test properties of a single AWS KMS Key. AWS Key Management Service (AWS KMS) is a managed service that makes it easy for you to create and control the encryption keys used to encrypt your data. AWS KMS lets you create master keys that can never be exported from the service and which can be used to encrypt and decrypt data based on policies you define. Each AWS KMS Key is uniquely identified by its key_id or arn. Syntax ------ An aws_kms_key resource block identifies a key by key_arn or the key id. ``` # Find a kms key by arn describe aws_kms_key('arn:aws:kms:us-east-1::key/4321dcba-21io-23de-85he-ab0987654321') do it { should exist } end # Find a kms key by just the id describe aws_kms_key('4321dcba-21io-23de-85he-ab0987654321') do it { should exist } end # Hash syntax for key arn describe aws_kms_key(key_id: 'arn:aws:kms:us-east-1::key/4321dcba-21io-23de-85he-ab0987654321') do it { should exist } end ``` Parameters ---------- ### alias *(required if `key_id` not specified)* This resource accepts searching for a KMS Key by it’s Alias. This can be passed as a `alias: 'alias/value'` key-value entry in a hash. This will then use the `target_key_id` from the Alias to search for the KMS Key. ### key_id *(required if `alias` not specified)* This resource accepts searching for a KMS Key by the KMS Key ID which can represent both the actual Key ID or the ARN of the Key. This can be passed either as a string or as a `key_id: 'value'` key-value entry in a hash. See also the [AWS documentation on KS Keys](https://docs.aws.amazon.com/kms/latest/developerguide/getting-started.html). Properties ---------- | Property | Description | | --- | --- | | key_id | The globally unique identifier for the key. | | arn | The ARN identifier of the specified key. | | creation_date | Specifies the date and time when the key was created. | | created_days_ago | Specifies the number of days since the key was created. | | key_state | Specifies the state of the key one of “Enabled”, “Disabled”, “PendingDeletion”, “PendingImport”. To just check if the key is enabled or not, use the `be_enabled` matcher. | | description | The description of the key. | | deletion_time | Specifies the date and time after which AWS KMS deletes the key. This value is present only when KeyState is PendingDeletion, otherwise this value is nil. | | invalidation_time | Provides the date and time until the key is not valid. Once the key is not valid, AWS KMS deletes the key and it becomes unusable. This value will be null unless the keys Origin is EXTERNAL and its matcher have_key_expiration is set to true. | Examples -------- ### Test that the specified key does exist ``` describe aws_kms_key('arn:aws:kms:us-east-1::key/4321dcba-21io-23de-85he-ab0987654321') do it { should exist } end ``` ### Test that the specified key is enabled ``` describe aws_kms_key('arn:aws:kms:us-east-1::key/4321dcba-21io-23de-85he-ab0987654321') do it { should be_enabled } end ``` ### Test that the specified key is rotation enabled ``` describe aws_kms_key('arn:aws:kms:us-east-1::key/4321dcba-21io-23de-85he-ab0987654321') do it { should have_rotation_enabled } end ``` ### Makes sure that the key was created at least 10 days ago ``` describe aws_kms_key('arn:aws:kms:us-east-1::key/4321dcba-21io-23de-85he-ab0987654321') do its('creation_date') { should be < Time.now - 10 * 86400 } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers (such as `exist`) please visit our [matchers page](../../matchers/index). Use `should_not` to test the entity should not exist in all cases. ### exist The control will pass if the describe returns at least one result. ``` it { should exist } it { should_not exist } ``` ### be_enabled The test will pass if the specified key’s key_state is set to enabled. ``` it { should be_enabled } ``` ### be_external Provides whether the source of the key’s key material is external or not. If it is not external than it was created by AWS KMS. When it is external, the key material was imported from an existing key management infrastructure or the key lacks key material. ``` it { should be_external } ``` ### be_managed_by_aws Provides whether or not the key manager is from AWS. If it is not managed by AWS, it is managed by the customer. ``` it { should be_managed_by_aws } ``` ### have_key_expiration Specifies whether the key’s key material expires. This value is null unless the keys Origin is External. ``` it { should have_key_expiration } ``` ### have_rotation_enabled The test will pass if automatic rotation of the key material is enabled for the specified key. ``` it { should have_rotation_enabled } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `kms:DescribeKey`, and `kms:GetKeyRotationStatus` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for AWS Key Management Service](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awskeymanagementservice.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_kms_key/aws_lambda resource ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_lambda.md) Use the `aws_lambda` resource to test a specific lambda. Syntax ------ ``` describe aws_lambda do it { should exist} its ('handler') { should eq 'main.on_event'} its ('version') { should eq '$LATEST' } its ('runtime') { should eq 'python3.7' } end ``` Parameters ---------- This resource expects the name of the function. Properties ---------- All properties as defined by the [Aws::lambda::Types::GetFunctionResponse](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/Lambda/Types/GetFunctionResponse.html) Examples -------- ### tests that all lambdas with a particular tag is correctly deployed ``` describe aws_lambda('my_new_lambda') do it { should exist} its ('handler') { should eq 'main.on_event'} its ('version') { should eq '$LATEST' } its ('runtime') { should eq 'python3.7' } end ``` Matchers -------- This InSpec audit resource uses the standard matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `lambda:GetFunction` action with Effect set to Allow. You can find detailed documentation at [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/lambda-api-permissions-ref.html) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_lambda/aws_lambdas resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_lambdas.md) Use the `aws_lambdas` resource to test the collection of lambdas deployed into an account. Syntax ------ ``` describe aws_lambdas do its('count') { should eq 20 } end ``` Parameters ---------- This resource does not expect any parameters. Properties ---------- | Property | Description | | --- | --- | | names | The names of the lambda deployed. | | tags | The tags of the lambda deployed. | Examples -------- ### tests that all lambdas with a particular tag is correctly deployed ``` lambdas = aws_lambdas() describe lambdas do its ('count') { should eq 33} end lambdas.tags.each_with_index { | tag, i | if tag!= {} and tag.include? 'Application' and tag['Application']=='test') lambda_name = lambdas.names[i] describe aws_lambda(lambda_name) do it { should exist} its ('handler') { should eq 'main.on_event'} its ('version') { should eq '$LATEST' } its ('runtime') { should eq 'python3.7' } end end } ``` Matchers -------- This InSpec audit resource uses the standard matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `lambda:ListFunctions` action with Effect set to Allow. You can find detailed documentation at [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/lambda-api-permissions-ref.html) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_lambdas/aws_internet_gateways resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_internet_gateways.md) Use the `aws_internet_gateways` InSpec audit resource to test the properties of all AWS internet gateways owned by the AWS account. Syntax ------ An `aws_internet_gateways` resource block collects all of the internet gateways and then tests that group. ``` describe aws_internet_gateways do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. Properties ---------- | Property | Description | | --- | --- | | ids | The ID of the internet gateway. The field name is `id`. | | names | The value of the `Name` tag. It is `nil` if not defined. The field name is `name`. | | vpc_ids | The ID of the attached VPC. It is `nil` if the resource is in a `detached` state. The field name is `vpc_id`. | | tags | A hash, with each key-value pair corresponding to an internet gateway tag. The field name is `tags`. | | attachment_states | Indicates whether the internet gateway is attached to a VPC (`attached` or `detached`). The field name is `attachment_state`. | | owner_ids | The ID of the AWS account that owns the internet gateway. The field name is `owner_id`. | Examples -------- ### Test that there are exactly 3 internet gateways ``` describe aws_internet_gateway do its('count') { should cmp 3 } end ``` ### Use this InSpec resource to request the ids of all internet gateways, then test in-depth using `aws_internet_gateway`. ``` aws_internet_gateways.ids.each do |id| describe aws_internet_gateway(id: id) do it { should be_attached } end end ``` Matchers -------- For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. The field names described in the [properties table](#properties) should be used for the `<property>` in the `where` clause. Use `should_not` to test the entity should not exist. ``` describe aws_internet_gateways.where( <property>: <value>) do it { should exist } end describe aws_internet_gateways.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeInternetGateways` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_internet_gateways/aws_kms_keys resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_kms_keys.md) Use the `aws_kms_keys` InSpec audit resource to test properties of some or all AWS KMS Keys. AWS Key Management Service (KMS) is a managed service that makes creating and controlling your encryption keys for your data easier. KMS uses Hardware Security Modules (HSMs) to protect the security of your keys. AWS Key Management Service is integrated with several other AWS services to help you protect the data you store with these services. Syntax ------ An `aws_kms_keys` resource block uses an optional filter to select a group of KMS Keys and then tests that group. ``` # Verify the number of KMS keys in the AWS account describe aws_kms_keys do its('entries.count') { should cmp 10 } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on KS Keys](https://docs.aws.amazon.com/kms/latest/developerguide/getting-started.html). Properties ---------- | Property | Description | | --- | --- | | key_ids | The IDs of the returned keys. | | key_arns | The Amazon Resource Names of the returned keys. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- The following examples show how to use this InSpec audit resource. ### Ensure a Key exists ``` describe aws_kms_keys do its('key_ids') { should include '<KEY>'} end ``` ### Allow at most 100 KMS Keys on the account ``` describe aws_kms_keys do its('entries.count') { should be <= 100} end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_kms_keys do it { should exist } end describe aws_kms_keys.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `kms:ListKeys` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for AWS Key Management Service](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awskeymanagementservice.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_kms_keys/aws_launch_configuration resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_launch_configuration.md) Use the `aws_launch_configuration` InSpec audit resource to test properties of a single AWS Launch Configuration. Syntax ------ ``` # Ensure that a launch configuration exists and has the correct key name describe aws_launch_configuration('my-config') do it { should exist } its('key_name') { should be 'my-key-name' } end # You may also use hash syntax to pass the launch configuration name describe aws_launch_configuration(launch_configuration_name: 'my-config') do it { should exist } end ``` Parameters ---------- ### launch_configuration_name *(required)* This resource expects a single parameter, the `launch_configuration_name` which uniquely identifies the of a Launch Configuration. See also the [AWS documentation on Launch Configurations](https://docs.aws.amazon.com/autoscaling/ec2/userguide/LaunchConfiguration.html). Properties ---------- | Property | Description | | --- | --- | | arn | An string indicating the ARN of the launch configuration | | image_id | An string indicating the AMI of the launch configuration | | instance_type | A string indicating the instance type of the launch configuration | | iam_instance_profile | A string indicating the IAM profile for the launch configuration | | key_name | A string indicating the AWS key pair for the launch configuration | | security_groups | An array of strings of the security group IDs associated with the launch configuration | | associate_public_ip_address | A boolean indicating if the launch configuration is configured to set a public IP address | | user_data | A string containing the user data configured for the launch configuration | | ebs_optimized | A boolean indicating if the launch configuration is optimized for Amazon EBS | | instance_monitoring | A string indicating if instance monitoring is set to `detailed` or `basic` | | spot_price | A floating point number indicating the spot price configured | Examples -------- ### Ensure a Launch Config is using the correct AMI ``` describe aws_launch_configuration('my-config') do its('image_id') { should eq 'ami-012345'} end ``` ### Test the instance type used in a Launch Config ``` describe aws_launch_configuration('my-config') do its('instance_type') { should eq 't3.micro'} end ``` ### Ensure a Launch Config is associated with the right IAM Profile ``` describe aws_launch_configuration('my-config') do its('iam_instance_profile') { should eq 'iam-profile' } end ``` ### Ensure the Launch Config does not set a public IP ``` describe aws_launch_configuration('my-config') do its('associate_public_ip_address') { should be false } end ``` ### Ensure the correct UserData is set on launched instances ``` describe aws_launch_configuration('my-config') do its('user_data') { should include 'user-data' } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_launch_configuration('AnExistingLC') do it { should exist } end describe aws_launch_configuration('ANonExistentLC') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `autoscaling:Describe*` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon Auto Scaling Groups and launch configurations](https://docs.aws.amazon.com/autoscaling/ec2/userguide/control-access-using-iam.html). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_launch_configuration/aws_nat_gateway resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_nat_gateway.md) Use the `aws_nat_gateway` InSpec audit resource to test the properties of a single AWS NAT gateway. Syntax ------ An `aws_nat_gateway` resource block declares the tests for a single AWS NAT gateway by id, name, vpc_id or subnet_id. ``` describe aws_nat_gateway(id: 'nat-abc0123456789deff') do it { should exist } end describe aws_nat_gateway(name: 'my-nat-gateway') do it { should exist } end ``` Multiple parameters can be provided for better granularity. ``` describe aws_nat_gateway(vpc_id: 'vpc-abc01234', subnet_id: 'subnet-6789deff') do it { should exist } end ``` Parameters ---------- At least one of the following parameters must be provided. * id * name * subnet_id * vpc_id ### id The value of the `nat_gateway_id` assigned by the AWS after the resource has been created. This should be in the format of `nat-` followed by 8 or 17 hexadecimal characters and passed as an `id: 'value'` key-value entry in a hash. ### name If a `Name` tag is applied to the NAT gateway, this can be used to lookup the resource. This must be passed as a `name: 'value'` key-value entry in a hash. If there are multiple NAT gateways with the same name, this resource will raise an error. ### subnet_id The ID of the subnet in which the NAT gateway is placed. This should be in the format of `subnet-` followed by 8 or 17 hexadecimal characters and passed as an `subnet_id: 'value'` key-value entry in a hash. ### vpc_id The ID of the VPC in which the NAT gateway is located. This should be in the format of `vpc-` followed by 8 or 17 hexadecimal characters and passed as an `vpc_id: 'value'` key-value entry in a hash. Properties ---------- | Property | Description | | --- | --- | | id | The ID of the NAT gateway. | | name | The value of the `Name` tag. It is `nil` if not defined. | | vpc_id | The ID of the VPC in which the NAT gateway is located. | | subnet_id | The ID of the subnet in which the NAT gateway is placed. | | tags | A hash, with each key-value pair corresponding to a NAT gateway tag. | | nat_gateway_address_set | A hash of [NatGatewayAddress object](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_NatGatewayAddress.html) that gives information about the IP addresses and network interface associated with the NAT gateway. | | state | The sate of the NAT gateway. Valid values are: `pending`, `failed`, `available`, `deleting` and `deleted`. | There are also additional properties available. For a comprehensive list, see [the API reference documentation](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_NatGateway.html) Examples -------- ### Test that the NAT gateway is in `available` state ``` describe aws_nat_gateway(name: 'my-nat-gateway') do its('state') { should eq 'available' } end ``` ### Test that the ID of the VPC is `vpc-1234567890abcdef1` ``` describe aws_nat_gateway(id: 'nat-abc0123456789deff') do its('vpc_id') { should eq `vpc-1234567890abcdef1` } end ``` ### Test that the NAT gateway has a certain tag ``` describe aws_nat_gateway(name: 'my-nat-gateway') do its('tags') { should include('environment' => 'dev') } its('tags') { should include('delete-at-10-pm') } # Regardless of the value end ``` ### Test that the private IP address is `10.0.1.68` ``` describe aws_nat_gateway(vpc_id: 'vpc-abc01234', subnet_id: 'subnet-12345678') do its('nat_gateway_address_set') { should include(:private_ip => '10.0.1.68') } end ``` For more examples, please check the [integration tests](https://github.com/inspec/inspec-aws/blob/main/test/integration/verify/controls/aws_nat_gateway.rb). Matchers -------- This InSpec audit resource has the following special matcher. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist ``` describe aws_nat_gateway(name: 'my-nat-gateway') do it { should exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeNatGateways` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_nat_gateway/aws_rds_cluster resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_rds_cluster.md) Use the `aws_rds_cluster` InSpec audit resource to test detailed properties of an individual RDS cluster. RDS gives you access to the capabilities of a MySQL, MariaDB, PostgreSQL, Microsoft SQL Server, Oracle, or Amazon Aurora database server. Syntax ------ An `aws_rds_cluster` resource block uses resource parameters to search for an RDS cluster, and then tests that RDS cluster. If no RDS clusters match, no error is raised, but the `exists` matcher will return `false` and all properties will be `nil`. If more than one RDS cluster matches (due to vague search parameters), an error is raised. ``` describe aws_rds_cluster('test-cluster-id') do it { should exist } end # Can also use hash syntax describe aws_rds_cluster(db_cluster_identifier: 'test-cluster-id') do it { should exist } end ``` Parameters ---------- ### db_cluster_identifier *(required)* This resource accepts a single parameter, the user-supplied cluster identifier. This parameter isn’t case-sensitive. This can be passed either as a string or as a `db_cluster_identifier: 'value'` key-value entry in a hash. See also the [AWS documentation on RDS cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.html). Properties ---------- For a comprehensive list of properties available to test on an RDS cluster see the [AWS Response Object](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/RDS/DBCluster.html). Examples -------- ### Test the engine used with an RDS cluster ``` describe aws_rds_cluster(db_cluster_identifier: 'awsrds123') do its('engine') { should eq 'mysql' } its('engine_version') { should eq '5.6.37' } end ``` ### Test the storage allocated to an RDS cluster ``` describe aws_rds_cluster(db_cluster_identifier: 'awsrds123') do its('storage_encrypted') { should eq true } its('allocated_storage') { should eq 10 } end ``` ### Test the cluster status and master username ``` describe aws_rds_cluster(db_cluster_identifier: 'awsrds123') do its('master_username') { should eq 'db-maintain' } its('status') { should eq 'available' } end ``` ### Test the maximum and minumum capacity of a serverless RDS cluster ``` describe aws_rds_cluster(db_cluster_identifier: 'awsrds123') do its('scaling_configuration_info.min_capacity') { should eq 2 } its('scaling_configuration_info.max_capacity') { should eq 64 } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_rds_cluster(db_cluster_identifier: 'AnExistingRDS') do it { should exist } end describe aws_rds_cluster(db_cluster_identifier: 'ANonExistentRDS') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `rds:DescribeDBclusters` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon RDS](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonrds.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_rds_cluster/aws_organizations_member resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_organizations_member.md) Use the `aws_organizations_member` InSpec audit resource to test the current AWS Account being used within an organization. Syntax ------ An `aws_organizations_member` resource block tests if the current AWS Account is the Master Account. The `master` matcher will return `true` or `false` accordingly. You may also verify that the `master_account_id` and `master_account_arn` properties match known values. If the current AWS Account ***is*** the Master Account, you may also access properties of that account. ``` describe aws_organizations_member do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. Note This resource must target AWS Region `us-east-1`. If another region is specified in your configuration, it will be overwritten at runtime. Properties ---------- | Property | Description | | --- | --- | | master_account_id | The ID of the AWS Organizations Master Account | | master_account_arn | The ARN of the AWS Organizations Master Account | ***If the current Account is the Master Account, the following properties are also available:*** | Property | Description | | --- | --- | | account_id | The ID of the current Account. | | account_arn | The ARN of the current Account. | | account_name | The Name of the current Account. | | account_email | The Email address associated with the current Account. | Examples -------- ### Ensure you are a child account with a certain ID for the top level account. ``` describe aws_organizations_member do it { should_not be_master } its('master_account_id') { should cmp '56845218745' } end ``` ### Ensure you are the top level account, with the right name and email associated. ``` describe aws_organizations_member do it { should be_master } its('account_name') { should eq 'MyAWSMasterAccount' } its('account_email') { should eq '<EMAIL>' } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_master The `be_master` matcher tests if the account is a ‘master’ AWS Account. ``` it { should_not be_master } ``` ### exist The control will pass if the describe returns at least one result. ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_organizations_member/aws_nat_gateways resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_nat_gateways.md) Use the `aws_nat_gateways` InSpec audit resource to test the properties of all AWS NAT gateways owned by the AWS account. Syntax ------ An `aws_nat_gateways` resource block collects all of the NAT gateways and then tests that group. ``` describe aws_nat_gateways do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. Properties ---------- | Property | Description | | --- | --- | | ids | The ID of the NAT gateway. The field name is `id`. | | names | The value of the `Name` tag. It is `nil` if not defined. The field name is `name`. | | vpc_ids | The ID of the VPC in which the NAT gateway is located. The field name is `vpc_id`. | | subnet_ids | The ID of the subnet in which the NAT gateway is placed. The field name is `subnet_id`. | | tags | A hash, with each key-value pair corresponding to a NAT gateway tag. The field name is `tags`. | | states | The sate of the NAT gateway. Valid values are: `pending`, `failed`, `available`, `deleting` and `deleted`. The field name is `state`. | Examples -------- ### Test that there are exactly 3 NAT Gateways ``` describe aws_nat_gateways do its('count') { should cmp 3 } end ``` ### Request The IDs of all NAT Gateways Use this InSpec resource to request the ids of all NAT gateways, then test in-depth using `aws_nat_gateway` InSpec singular AWS resource. ``` aws_nat_gateways.ids.each do |id| describe aws_nat_gateway(id: id) do its('state') { should eq 'available' } end end ``` For more examples, please check the [integration tests](https://github.com/inspec/inspec-aws/blob/main/test/integration/verify/controls/aws_nat_gateways.rb). Matchers -------- For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). #### exist The control will pass if the describe returns at least one result. The field names described in the [properties table](#properties) should be used for the `<property>` in the `where` clause. Use `should_not` to test the entity should not exist. ``` describe aws_nat_gateways.where( <property>: <value>) do it { should exist } end describe aws_nat_gateways.where( <property>: <value>) do it { should_not exist } end ``` Please see [here](https://github.com/inspec/inspec/blob/main/docs/dev/filtertable-usage.md) for more information on how to use filter table. AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeNatGateways` action set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_nat_gateways/aws_rds_clusters resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_rds_clusters.md) Use the `aws_rds_clusters` InSpec audit resource to test properties of a collection of AWS RDS clusters. RDS gives you access to the capabilities of a MySQL, MariaDB, PostgreSQL, Microsoft SQL Server, Oracle, or Amazon Aurora database server. Syntax ------ Ensure you have exactly 3 clusters ``` describe aws_rds_clusters do its('db_cluster_identifiers.count') { should cmp 3 } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on RDS](https://docs.aws.amazon.com/rds/?id=docs_gateway). Properties ---------- | Property | Description | | --- | --- | | cluster_identifier | The unique IDs of the RDS clusters returned. | | database_name | The name of the database associated with each RDS cluster. | | cluster_members | The RDS instances attached to each RDS cluster. | | engine | The name of the database engine used by each cluster. | | engine_version | The version of the database engine used by each cluster. | | status | The current status of each cluster. | | allocated_storage | The storage allocated to each cluster. | | storage_encrypted | Returns T/F whether the cluster is encrypted or not. | | availability_zones | A list of availability zones of the RDS clusters returned. | | multi_az | Returns T/F depending on whether multiple availability zones are used in the cluster. | | arn | The unique Amazon resource name of the RDS clusters. | Examples -------- ### Ensure a specific cluster exists ``` describe aws_rds_clusters do its('db_cluster_identifier') { should include 'cluster-12345678' } end ``` ### Test That All RDS Clusters Are Encrypted by ID Use the InSpec resource to request the IDs of all RDS clusters, then test in-depth using `aws_rds_cluster` to ensure all clusters are encrypted and have a sensible size. ``` aws_rds_clusters.cluster_identifier.each do |cluster_identifier| describe aws_rds_cluster(cluster_identifier) do it { should have_encrypted_storage } end end ``` Matchers -------- For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_rds_clusters do it { should exist } end describe aws_rds_clusters do it { should_not exist } end ``` Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:Describeclusters`, and `iam:GetInstanceProfile` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_rds_clusters/aws_rds_instance resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_rds_instance.md) Use the `aws_rds_instance` InSpec audit resource to test detailed properties of an individual RDS instance. RDS gives you access to the capabilities of a MySQL, MariaDB, PostgreSQL, Microsoft SQL Server, Oracle, or Amazon Aurora database server. Syntax ------ An `aws_rds_instance` resource block uses resource parameters to search for an RDS instance, and then tests that RDS instance. If no RDS instances match, no error is raised, but the `exists` matcher will return `false` and all properties will be `nil`. If more than one RDS instance matches (due to vague search parameters), an error is raised. ``` describe aws_rds_instance('test-instance-id') do it { should exist } end # Can also use hash syntax describe aws_rds_instance(db_instance_identifier: 'test-instance-id') do it { should exist } end ``` Parameters ---------- ### db_instance_identifier *(required)* This resource accepts a single parameter, the user-supplied instance identifier. This parameter isn’t case-sensitive. This can be passed either as a string or as a `db_instance_identifier: 'value'` key-value entry in a hash. See also the [AWS documentation on RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.html). Properties ---------- For a comprehensive list of properties available to test on an RDS Instance see the [AWS Response Object](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/RDS/Types/DBInstance.html) Examples -------- ### Test the engine used with an RDS instance ``` describe aws_rds_instance(db_instance_identifier: 'awsrds123') do its ('engine') { should eq 'mysql' } its ('engine_version') { should eq '5.6.37' } end ``` ### Test the storage allocated to an RDS instance ``` describe aws_rds_instance(db_instance_identifier: 'awsrds123') do its ('storage_type') { should eq 'gp2' } its ('allocated_storage') { should eq 10 } end ``` ### Test the instance type and master username ``` describe aws_rds_instance(db_instance_identifier: 'awsrds123') do its ('master_username') { should eq 'db-maintain' } its ('db_instance_class') { should eq 'db.t3.micro' } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_rds_instance(db_instance_identifier: 'AnExistingRDS') do it { should exist } end describe aws_rds_instance(db_instance_identifier: 'ANonExistentRDS') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `rds:DescribeDBInstances` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon RDS](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonrds.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_rds_instance/aws_rds_instances resource ============================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_rds_instances.md) Use the `aws_rds_instances` InSpec audit resource to test properties of a collection of AWS RDS instances. RDS gives you access to the capabilities of a MySQL, MariaDB, PostgreSQL, Microsoft SQL Server, Oracle, or Amazon Aurora database server. RDS instances are compute instances used by the RDS service. Syntax ------ Ensure you have exactly 3 instances ``` describe aws_rds_instances do its('db_instance_identifiers.count') { should cmp 3 } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on RDS](https://docs.aws.amazon.com/rds/?id=docs_gateway). Properties ---------- | Property | Description | | --- | --- | | db_instance_identifiers | The unique IDs of the RDS Instances returned. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Ensure a specific instance exists ``` describe aws_rds_instances do its('db_instance_identifiers') { should include 'rds-12345678' } end ``` ### Test That All Rds Instances Are Encrypted by Id Use the InSpec resource to request the IDs of all RDS instances, then test in-depth using `aws_rds_instance` to ensure all instances are encrypted and have a sensible size. ``` aws_rds_instances.db_instance_identifiers.each do |db_instance_identifier| describe aws_rds_instance(db_instance_identifier) do it { should be_encrypted } end end ``` Matchers -------- For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_rds_instances do it { should exist } end describe aws_rds_instances do it { should_not exist } end ``` Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeInstances`, and `iam:GetInstanceProfile` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html), and [Actions, Resources, and Condition Keys for Identity And Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_rds_instances/aws_regions resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_regions.md) Use the `aws_regions` InSpec audit resource to test properties of some or all AWS regions in bulk. Note that this resource lists all AWS regions that are currently available to the caller. Syntax ------ An `aws_regions` resource block uses an optional filter to select a group of regions and then tests that group. ``` describe aws_regions.where { region_name: 'us-not-there-1' } do it { should_not exist } end ``` Parameters ---------- ### name *(required)* This resource does not expect any parameters. See also the [AWS documentation on Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html). Properties ---------- | Property | Description | | --- | --- | | region_names | The Names of the regions. | | endpoints | The resolved endpoints of the regions. | Examples -------- The following examples show how to use this InSpec audit resource. ### Check for a Particular Region ``` describe aws_regions do its('region_names') { should include 'eu-west-2' } end ``` ### Check an endpoint exists ``` describe aws_regions do its('endpoints') { should include 'ec2.eu-west-2.amazonaws.com' } end ``` ### Use the regions resource to check single regions in more detail ``` aws_regions.region_names.each do |aws_region_name| describe aws_region(region_name: aws_region_name) do it { should exist } end end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. ``` it { should exist } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeVpcs` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_regions/aws_region resource ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_region.md) Use the `aws_region` InSpec audit resource to test properties of a single AWS region. Syntax ------ An `aws_region` resource block identifies an AWS region by ID. If no region is provided, the current default is used. ``` describe aws_region('eu-west-2') do it { should exist } end describe aws_region(region_name: 'us-east-1') do it { should exist } end ``` Parameters ---------- ### region_name *(optional)* This resource accepts a single parameter, the region_name. This can be passed either as a string or as a `region_name: 'value'` key-value entry in a hash. See also the [AWS documentation on Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html). Properties ---------- | Property | Description | | --- | --- | | region_name | The Name of the region. | | endpoint | The resolved endpoint of the region. | Examples -------- ### Test whether a region exists ``` describe aws_region('region-not-real') do it { should_not exist } end ``` ### Test the Region Endpoint ``` describe aws_region(region_name: 'eu-west-2') do its('endpoint') { should eq 'ec2.eu-west-2.amazonaws.com' } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. ``` it { should exist } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeRegions` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_region/aws_route_table resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_route_table.md) Use the `aws_route_table` InSpec audit resource to test properties of a single Route Table. A route table contains a set of rules, called routes, that are used to determine where network traffic is directed. Syntax ------ This resource expects a single parameter that uniquely identifies the Route Table. You may pass it as a string, or as the value in a hash: ``` describe aws_route_table('rtb-123abcde') do it { should exist } end describe aws_route_table(route_table_id: 'rtb-123abcde') do it { should exist } end ``` Parameters ---------- ### route_table_id *(required)* This resource accepts a single parameter, the route_table_id. This can be passed either as a string or as a `route_table_id: 'value'` key-value entry in a hash. See also the [AWS documentation on Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html). Properties ---------- | Property | Description | | --- | --- | | route_table_id | The ID of the route table. | | owner_id | The ID of the AWS account that owns the route table. | | vpc_id | The ID of the VPC. | | routes | The routes in the route table. | | associations | The associations between the route table and one or more subnets. | | propagating_vgws | Any virtual private gateway (VGW) propagating routes. | | tags | Any tags assigned to the route table. | Examples -------- ### Confirm that the route table has expected VPC identifier ``` describe aws_route_table(route_table_id: 'rtb-123abcde') do its('vpc_id') { should eq 'vpc-01625e36123456789' } end ``` ### Confirm that the route table has expected owner identifier ``` describe aws_route_table(route_table_id: 'rtb-123abcde') do its('owner_id') { should eq '123456789012' } end ``` ### Ensure the expected number of routes is present ``` describe aws_route_table(route_table_id: 'rtb-123abcde') do its('routes.count') { should eq 2 } end ``` ### Ensure the expected number of associations is present ``` describe aws_route_table(route_table_id: 'rtb-123abcde') do its('associations.count') { should eq 1 } end ``` ### Ensure there are no virtual private gateway (VGW) propagating routes ``` describe aws_route_table(route_table_id: 'rtb-123abcde') do its('propagating_vgws') { should be_empty } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_route_table('should-be-there') do it { should exist } end describe aws_route_table('should-not-be-there') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeRouteTables` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_route_table/aws_route_tables resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_route_tables.md) Use the `aws_route_tables` InSpec audit resource to test properties of all or a group of Route Tables. A Route Table contains a set of rules, called routes, that are used to determine where network traffic is directed. Syntax ------ Ensure that there is at least one route table ``` describe aws_route_tables do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html). Properties ---------- | Property | Description | | --- | --- | | route_table_ids | The route table IDs | | vpc_ids | The VPC IDs | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Confirm that a route table exists ``` describe aws_route_tables do its('vpc_ids') { should include 'vpc-01625e36123456789' } end ``` ### Confirm a Route Table exists. ``` describe aws_route_tables do its('route_table_ids') { should include 'rtb-12345678' } end ``` Matchers -------- ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` it { should exist } it { should_not exist } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeRouteTables` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_route_tables/aws_s3_bucket resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_s3_bucket.md) Use the `aws_s3_bucket` InSpec audit resource to test properties of a single AWS bucket. Syntax ------ An `aws_s3_bucket` resource block declares a bucket by name, and then lists tests to be performed. ``` describe aws_s3_bucket(bucket_name: 'test_bucket') do it { should exist } it { should_not be_public } end describe aws_s3_bucket('test_bucket') do it { should exist } end ``` Parameters ---------- ### bucket_name *(required)* This resource accepts a single parameter, the S3 Bucket Name which uniquely identifies the bucket. This can be passed either as a string or as a `bucket_name: 'value'` key-value entry in a hash. See also the [AWS documentation on S3 Buckets](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html). Properties ---------- | Property | Description | | --- | --- | | region | The region of the bucket. Region is overridden based on the location returned from S3 | | bucket_acl | An array of AWS Grants detailing permission grants on the bucket. | | bucket_policy | The IAM policy document controlling access to the bucket. | | bucket_lifecycle_rules | The lifecycle policy rules that define actions S3 will take for all objects (or a subset of objects) in their lifetime. | | tags | An hash with each key-value pair corresponding to a tag associated with the entity | Examples -------- ### Test the bucket-level ACL ``` describe aws_s3_bucket('test_bucket') do its('bucket_acl.count') { should eq 1 } end ``` ### Check if a bucket has a bucket policy ``` describe aws_s3_bucket('test_bucket') do its('bucket_policy') { should be_empty } end ``` ### Check if a bucket appears to be exposed to the public ``` describe aws_s3_bucket('test_bucket') do it { should_not be_public } end ``` ### Check if the correct region is set ``` describe aws_s3_bucket('test_bucket') do its('region') { should eq 'us-east-1' } end ``` ### Check bucket’s ACL for correct grants ``` bucket_acl = aws_s3_bucket('my-bucket').bucket_acl # Look for grants to "AllUsers" (that is, the public) all_users_grants = bucket_acl.select do |g| g.grantee.type == 'Group' && g.grantee.uri =~ /AllUsers/ end # Look for grants to "AuthenticatedUsers" (that is, any authenticated AWS user - nearly public) auth_grants = bucket_acl.select do |g| g.grantee.type == 'Group' && g.grantee.uri =~ /AuthenticatedUsers/ end ``` ### Test all buckets ``` aws_s3_buckets.bucket_names.each do |bucket_name| describe aws_s3_bucket(bucket_name) do it { should have_default_encryption_enabled } end end ``` ### Test buckets in a specific region ``` aws_s3_buckets.bucket_names.each do |bucket_name| if aws_s3_bucket(bucket_name: bucket_name).region == region describe aws_s3_bucket(bucket_name) do it { should have_default_encryption_enabled } end end end ``` ### Check if a bucket has a bucket policy that requires requests to use HTTPS ``` describe aws_s3_bucket('test_bucket') do it { should have_secure_transport_enabled } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_public The `be_public` matcher tests if the bucket has potentially insecure access controls. This high-level matcher detects several insecure conditions, which may be enhanced in the future. Currently, the matcher reports an insecure bucket if any of the following conditions are met: 1. A bucket ACL grant exists for the ‘AllUsers’ group 2. A bucket ACL grant exists for the ‘AuthenticatedUsers’ group 3. A bucket policy has an effect ‘Allow’ and principal ‘*’ Note: This resource does not detect insecure object ACLs. ``` it { should_not be_public } ``` ### have_access_logging_enabled The `have_access_logging_enabled` matcher tests if access logging is enabled for the s3 bucket. ``` it { should have_access_logging_enabled } ``` ### have_default_encryption_enabled The `have_default_encryption_enabled` matcher tests if default encryption is enabled for the s3 bucket. ``` it { should have_default_encryption_enabled } ``` ### have_versioning_enabled The `have_versioning_enabled` matcher tests if versioning is enabled for the s3 bucket. it { should have_versioning_enabled } ### have_secure_transport_enabled The `have_secure_transport_enabled` matcher tests if a bucket policy that explicitly denies requests via HTTP is enabled for the s3 bucket. it { should have_secure_transport_enabled } AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `s3:GetBucketAcl`, `s3:GetBucketLocation`, `s3:GetBucketLogging`, `s3:GetBucketPolicy`, and `s3:GetEncryptionConfiguration` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon S3](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazons3.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_s3_bucket/aws_s3_buckets resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_s3_buckets.md) Use the `aws_s3_buckets` InSpec audit resource to list all buckets in a single account. Syntax ------ An `aws_s3_buckets` resource block takes no arguments ``` describe aws_s3_buckets do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on S3 Buckets](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html). Properties ---------- | Property | Description | | --- | --- | | bucket_names | An Array of bucket names. | | tags | An hash with each key-value pair corresponding to a tag associated with the entity | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Examine what buckets have been created. ``` describe aws_s3_buckets do its('bucket_names') { should eq ['my_bucket'] } # OR its('bucket_names') { should include 'my_bucket' } end ``` ### Check the tags on buckets ``` describe aws_s3_buckets.where( bucket_names: 'my-bucket' ) do its('tags') { should include(:Environment => 'env-name', :Name => 'bucket-name')} end ``` Matchers -------- ### exists The control will pass if the resource contains at least one bucket. ``` # Test if there are any buckets describe aws_s3_buckets it { should exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `s3:ListAllMyBuckets` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon S3](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazons3.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_s3_buckets/aws_s3_bucket_object resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_s3_bucket_object.md) Use the `aws_s3_bucket_object` InSpec audit resource to test properties of a single AWS bucket object. Each S3 Object has a ‘key’ which can be thought of as the name of the S3 Object which uniquely identifies it. Syntax ------ An `aws_s3_bucket_object` resource block declares a bucket and an object key by name, and then lists tests to be performed. ``` describe aws_s3_bucket_object(bucket_name: 'test_bucket', key: 'test_object_key') do it { should exist } it { should_not be_public } end ``` Parameters ---------- ### bucket_name *(required)* The S3 Bucket Name which uniquely identifies the bucket. This must be passed as a `bucket_name: 'value'` key-value entry in a hash. ### key *(required)* The S3 Bucket Key which uniquely identifies the bucket object. This must be passed as a `key: 'value'` key-value entry in a hash. See also the [AWS documentation on S3 Buckets](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html). Properties ---------- | Property | Description | | --- | --- | | bucket_name | The name of the bucket. | | key | The key within the bucket. | | content_length | Size of the body in bytes. | | content_type | A standard MIME type describing the format of the object data. | | object_acl | An array of AWS Grants detailing permission grants on the bucket object. | There are also additional properties available. For a comprehensive list, see [the API reference documentation](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html). Examples -------- ### Test an object’s object-level ACL ``` describe aws_s3_bucket_object(bucket_name: 'test_bucket', key: 'test_key') do its('object_acl.count') { should eq 1 } end ``` ### Test an object’s size in bytes is less than `100000` ``` describe aws_s3_bucket_object(bucket_name: 'test_bucket', key: 'test_key') do its('content_length') { should be < 1_000_000 } end ``` ### Test an object’s type is “image/jpeg” ``` describe aws_s3_bucket_object(bucket_name: 'test_bucket', key: 'test_key') do its('content_type') { should eq "image/jpeg" } end ``` ### Check to see if a object appears to be exposed to the public ``` describe aws_s3_bucket_object(bucket_name: 'test_bucket', key: 'test_key') do it { should_not be_public } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers (such as `exist`) please visit our [matchers page](../../matchers/index). ### be_public The `be_public` matcher tests if the object has potentially insecure access controls. This high-level matcher detects several insecure conditions, which may be enhanced in the future. Currently, the matcher reports an insecure object if any of the following conditions are met: 1. A object ACL grant exists for the ‘AllUsers’ group 2. A object ACL grant exists for the ‘AuthenticatedUsers’ group Note This resource does not detect insecure bucket ACLs. ``` it { should_not be_public } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `s3:GetObject`, and `s3:GetObjectAcl` actions set to allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon S3](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazons3.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_s3_bucket_object/aws_security_groups resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_security_groups.md) Use the `aws_security_groups` InSpec audit resource to test properties of some or all security groups. Security groups are a networking construct that contain ingress and egress rules for network communications. Security groups may be attached to EC2 instances, as well as certain other AWS resources. Along with Network Access Control Lists, Security Groups are one of the two main mechanisms of enforcing network-level security. Syntax ------ An `aws_security_groups` resource block uses an optional filter to select a group of security groups and then tests that group. ``` describe aws_security_groups do its('entries.count') { should be > 1 } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on Security Groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html). Properties ---------- | Property | Description | | --- | --- | | group_ids | The name of the auto scaling launch configuration associated with the auto scaling group | | group_names | An integer indicating the maximum number of instances in the auto scaling group | | vpc_ids | An integer indicating the desired number of instances in the auto scaling group | | tags | An integer indicating the minimum number of instances in the auto scaling group | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- The following examples show how to use this InSpec audit resource. ### Look for a particular security group in just one VPC ``` describe aws_security_groups.where( vpc_id: 'vpc-12345678') do its('group_ids') { should include('sg-abcdef12')} end ``` ### Examine the default security group in all VPCs ``` describe aws_security_groups.where( group_name: 'default') do it { should exist } end ``` ### Allow at most 100 security groups on the account ``` describe aws_security_groups do its('entries.count') { should be <= 100} end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` # You will always have at least one SG, the VPC default SG describe aws_security_groups it { should exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeSecurityGroups` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_security_groups/aws_sns_subscription resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_sns_subscription.md) [[edit on GitHub]](https://github.com/inspec/inspec/blob/main/docs-chef-io/content/aws_sns_subscription.md) Use the `aws_sns_subscription` InSpec audit resource to test detailed properties of a AWS SNS Subscription. Syntax ------ An `aws_sns_subscription` resource block uses resource parameters to search for a SNS Subscription, and then tests that subscriptions properties. If no Subscriptions match, no error is raised, but the `exists` matcher will return `false` and all properties will be `nil`. ``` describe aws_sns_subscription('arn:aws:sns:us-east-1::test-topic-01:b214aff5-a2c7-438f-a753-8494493f2ff6') do it { should exist } end ``` Parameters ---------- ### subscription_arn *(required)* This resource accepts a single parameter, the subscription_arn. This can be passed either as a string or as a `subscription_arn: 'value'` key-value entry in a hash. See also the [AWS documentation on SNS](https://docs.aws.amazon.com/sns/latest/dg/sns-getting-started.html). Properties ---------- | Property | Description | | --- | --- | | arn | An integer indicating the minimum number of instances in the auto scaling group | | owner | An integer indicating the maximum number of instances in the auto scaling group | | raw_message_delivery | An integer indicating the desired number of instances in the auto scaling group | | topic_arn | The name of the auto scaling launch configuration associated with the auto scaling group | | protocol | An array of strings corresponding to the subnet IDs associated with the auto scaling group | | confirmation_was_authenticated | An hash with each key-value pair corresponding to a tag associated with the entity | Examples -------- ### Inspect the endpoint ``` describe aws_sns_subscription(subscription_arn: 'arn:aws:sns:us-east-1::test-topic-01:b214aff5-a2c7-438f-a753-8494493f2ff6' ) do # If protocol is 'sms', this should be a phone number: its('endpoint') { should cmp '+16105551234' } # If protocol is 'email' or 'email-json', endpoint should be an email address its('endpoint') { should cmp '<EMAIL>' } # If protocol is 'http', endpoint should be a URL beginning with 'https://' its('endpoint') { should cmp 'https://www.exampleurl.com' } # If the protocol is 'lambda', its endpoint should be the ARN of a AWS Lambda function its('endpoint') { should cmp 'rn:aws:lambda:us-east-1:account-id:function:myfunction' } end ``` ### Inspect the owners ID ``` describe aws_sns_subscription(subscription_arn: 'arn:aws:sns:us-east-1::test-topic-01:b214aff5-a2c7-438f-a753-8494493f2ff6' ) do its('owner') { should cmp '12345678' } end ``` ### Inspect the endpoint ``` describe aws_sns_subscription(subscription_arn: 'arn:aws:sns:us-east-1::test-topic-01:b214aff5-a2c7-438f-a753-8494493f2ff6' ) do its('protocol') { should cmp 'sqs' } end ``` Matchers -------- ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` it { should exist } it { should_not exist } ``` ### be_confirmation_authenticated Provides whether or not the subscription confirmation request was authenticated. ``` describe aws_sns_subscription(subscription_arn: 'arn:aws:sns:us-east-1::NOGOOD:b214aff5-a2c7-438f-a753-8494493f2ff6') it { should be_confirmation_authenticated } end ``` ### have_raw_message_delivery Provides whether or not the original message is passed as is, not formatted as a json or yaml. ``` describe aws_sns_subscription(subscription_arn: 'arn:aws:sns:us-east-1::NOGOOD:b214aff5-a2c7-438f-a753-8494493f2ff6') it { should have_raw_message_delivery } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `sns:GetSubscriptionAttributes` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon SNS](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonsns.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_sns_subscription/aws_security_group resource ============================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_security_group.md) Use the `aws_security_group` InSpec audit resource to test detailed properties of an individual Security Group (SG). SGs are a networking construct which contain ingress and egress rules for network communications. SGs may be attached to EC2 instances, as well as certain other AWS resources. Along with Network Access Control Lists, SGs are one of the two main mechanisms of enforcing network-level security. Limitations ----------- While this resource provides facilities for searching inbound and outbound rules on a variety of criteria, there is currently no support for performing matches based on: * References to VPC peers or other AWS services (that is, no support for searches based on ‘prefix lists’). Syntax ------ ``` describe aws_security_group('sg-12345678') do it { should exist } end # May also use hash syntax describe aws_security_group(group_id: 'sg-12345678') do it { should exist } end # Ensure you have a Security Group with a specific name. Names are # unique within a VPC but not across VPCs. # Using only Group returns an error if multiple SGs match. describe aws_security_group(group_name: 'my-group') do it { should exist } end # Add vpc_id to ensure uniqueness. describe aws_security_group(group_name: 'my-group', vpc_id: 'vpc-12345678') do it { should exist } end ``` Parameters ---------- You must provide at least one parameter; `group_id`, `group_name` or `vpc_id` ### group_id *(required if no other parameter provided)* The Security Group ID which uniquely identifies the SG. This can be passed either as a string or as a `group_id: 'value'` key-value entry in a hash. ### group_name *(required if no other parameter provided)* The Security Group name. This can be passed either as a string or as a `group_name: 'value'` key-value entry in a hash. ### vpc_id *(required if no other parameter provided)* The ID of the VPC associated with the SG. This can be passed either as a string or as a `vpc_id: 'value'` key-value entry in a hash. See also the [AWS documentation on Security Groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html). Properties ---------- | Property | Description | | --- | --- | | description | A String reflecting the human-meaningful description that was given to the SG at creation time. | | group_id | Provides the Security Group ID. | | group_name | A String reflecting the name that was given to the SG at creation time. | | inbound_rules | A list of the rules that the Security Group applies to incoming network traffic. | | inbound_rules_count | A Number totalling the number of individual rules defined - It is a sum of the combinations of port, protocol, IPv4 rules, IPv6 rules and security group rules. | | outbound_rules | A list of the rules that the Security Group applies to outgoing network traffic initiated by the AWS resource in the Security Group. | | outbound_rules_count | A Number totalling the number of individual rules defined - It is a sum of the combinations of port, protocol, IPv4 rules, IPv6 rules and security group rules. | | vpc_id | A String in the format `vpc-` followed by 8 hexadecimal characters reflecting VPC that contains the Security Group. | | tags | The tags of the security group. | Examples -------- ### Test outbound rules ``` describe aws_security_group(group_name: isolated_servers) do its('outbound_rules.last') { should_not include(ip_ranges:['0.0.0.0/0']) } end ``` ### Test a rule that allows All Traffic ``` describe aws_security_group(group_name: my_group) do it { should allow_in(ipv4_range: ["10.1.2.0/24", "10.3.2.0/24"], protocol: 'all') } end ``` ### Ensure a SG only allows SSH from a specific range ``` describe aws_security_group(group_name: linux_servers) do it { should allow_in(port: 22, ipv4_range: '10.5.0.0/16') } it { should_not allow_in(port: 22, ipv4_range: '0.0.0.0/0') } end ``` ### Ensure that the careful_updates Security Group may only initiate contact with specific IPs. ``` describe aws_security_group(group_name: 'careful_updates') do # If you have two rules, with one CIDR each: [ '10.7.23.12/32', '10.8.23.12/32' ].each do |allowed_destination| # This doesn't care about which ports are enabled it { should allow_out(ipv4_range: allowed_destination) } end # If you have one rule with two CIDRs: it { should allow_out(ipv4_range: [ '10.7.23.12/32', '10.8.23.12/32' ]) } # Expect exactly three rules. its('outbound_rules.count') { should cmp 3 } end ``` ### Ensure that the canary_deployments Security Group only allows access from one specific security group id on port 443. ``` describe aws_security_group(group_name: 'canary_deployments') do it { should allow_in_only(port: 443, security_group: "sg-33334444") } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of additional available matchers, please visit our [Universal Matchers page](../../matchers/index). ### allow The `allow` series of matchers includes: * allow_in * allow_out * allow_in_only * allow_out_only The `allow` series of matchers enable you to perform queries about what network traffic would be permitted through the Security Group rule set. `allow_in` and `allow_in_exactly` examine inbound rules, and `allow_out` and `allow_out_exactly` examine outbound rules. `allow_in` and `allow_out` examine if at least one rule that matches the criteria exists. `allow_in` and `allow_out` also perform inexact (ie, range-based or subset-based) matching on ports and IP addresses ranges, allowing you to specify a candidate port or IP address and determine if it is covered by a rule. `allow_in_only` and `allow_out_only` examines if exactly one rule exists (but see `position`, below), and if it matches the criteria (this is useful for ensuring no unexpected rules have been added). Additionally, `allow_in_only` and `allow_out_only` do *not* perform inexact matching; you must specify exactly the port range or IP address(es) you wish to match. ### Matchers search criteria The matchers accept a key-value list of search criteria. For a rule to match, it must match all provided criteria. `from_port` Determines if a rule exists whose port range begins at the specified number. The word `from_` does *not* relate to inbound/outbound directionality; it relates to the port range (“counting *from*"). `from_port` is an exact criterion; so if the rule allows 1000-2000 and you specify a `from_port` of 1001, it does not match. `ipv4_range` Specifies an IPv4 address or subnet as a CIDR, or a list of them, to be checked as a permissible origin (for `allow_in`) or destination (for `allow_out`) for traffic. Each AWS Security Group rule may have multiple allowed source IP ranges. `ipv6_range` Specifies an IPv6 address or subnet as a CIDR, or a list of them, to be checked as a permissible origin (for `allow_in`) or destination (for `allow_out`) for traffic. Each AWS Security Group rule may have multiple allowed source IP ranges. `port` Determines if a particular TCP/IP port is reachable. `allow_in` and `allow_out` examine whether the specified port is included in the port range of a rule, while `allow_in`. You may specify the port as a string (`'22'`) or as a number. `position` A one-based index into the list of rules. If provided, this restricts the evaluation to the rule at that position. You may also use the special values `:first` and `:last`. `position` may also be used to enable `allow_in_only` and `allow_out_only` to work with multi-rule Security Groups. `protocol` Specifies the IP protocol. `tcp`, `udp`, and `icmp` are some typical values. The string `"-1"` or `any` is used to indicate any protocol. `to_port` Determines if a rule exists whose port range ends at the specified number. The word `to_` does *not* relate to inbound/outbound directionality; it relates to the port range (“counting *to*"). `to_port` is an exact criterion; so if the rule allows 1000-2000 and you specify a `to_port` of 1999, it does not match. `security_group` Specifies a security-group id, to be checked as permissible origin (for `allow_in`) or destination (for `allow_out`) for traffic. Each AWS Security Group rule may have multiple allowed source or destination security groups. ``` describe aws_security_group(group_name: 'mixed-functionality-group') do # Allow RDP from defined range it { should allow_in(port: 3389, ipv4_range: '10.5.0.0/16') } it { should allow_in(port: 3389, ipv6_range: '2001:db8::/122') } # Allow SSH from two ranges it { should allow_in(port: 22, ipv4_range: ['10.5.0.0/16', '10.2.3.0/24']) } # Check Bacula port range it { should allow_in(from_port: 9101, to_port: 9103, ipv4_range: '10.6.7.0/24') } # Assuming the AWS SG allows 9001-9003, use inexact matching to check 9002 it { should allow_in(port: 9002) } # Assuming the AWS SG allows 10.2.1.0/24, use inexact matching to check 10.2.1.33/32 it { should allow_in(ipv4_range: '10.2.1.33/32') } # Ensure the 3rd outbound rule is TCP-based it { should allow_in(protocol: 'tcp', position: 3') } # Do not allow unrestricted IPv4 access. it { should_not allow_in(ipv4_range: '0.0.0.0/0') } # Allow unrestricted access from security-group. it { should allow_in(security_group: 'sg-11112222') } end ``` Suppose you have a Group that should allow SSH and RDP from the admin network, 10.5.0.0/16. The resource has 2 rules to allow this, and you want to ensure no others have been added. ``` describe aws_security_group(group_name: 'admin-group') do # Allow RDP from a defined range and nothing else # The SG must have this rule in position 1 and it must match this exactly it { should allow_in_only(port: 3389, ipv4_range: '10.5.0.0/16', position: 1) } # Specify position 2 for the SSH rule. Without `position`, # allow_in_only only allows one rule, total. it { should allow_in_only(port: 22, ipv4_range: '10.5.0.0/16', position: 2) } # Because this is an _only matcher, this fails - _only matchers # use exact IP matching. it { should allow_in_only(port: 3389, ipv4_range: '10.5.1.34/32', position: 1) } end ``` ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` it { should exist } it { should_not exist } ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeSecurityGroups` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_security_group/aws_sns_topic resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_sns_topic.md) Use the `aws_sns_topic` InSpec audit resource to test properties of a single AWS Simple Notification Service Topic. SNS topics are channels for related events. AWS resources place events in the SNS topic, while other AWS resources subscribe to receive notifications when new events occur. Syntax ------ ``` describe aws_sns_topic('arn:aws:sns:*::my-topic-name') do it { should exist } end # You may also use has syntax to pass the ARN describe aws_sns_topic(arn: 'arn:aws:sns:*::my-topic-name') do it { should exist } end ``` Parameters ---------- ### arn *(required)* This resource accepts a single parameter, the ARN of the SNS Topic. This can be passed either as a string or as a `arn: 'value'` key-value entry in a hash. See also the [AWS documentation on SNS](https://docs.aws.amazon.com/sns/latest/dg/sns-getting-started.html). Properties ---------- | Property | Description | | --- | --- | | confirmed_subscription_count | An integer indicating the number of currently active subscriptions. | Examples -------- ### Make sure something is subscribed to the topic ``` describe aws_sns_topic('arn:aws:sns:*::my-topic-name') do its('confirmed_subscription_count') { should_not be_zero} end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_sns_topic('arn:aws:sns:*::good-news') do it { should exist } end describe aws_sns_topic('arn:aws:sns:*::bad-news') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `sns:GetTopicAttributes` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon SNS](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonsns.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_sns_topic/aws_sqs_queue resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_sqs_queue.md) Use the `aws_sqs_queue` InSpec audit resource to test properties of a single AWS Simple Queue Service queue. Syntax ------ ``` describe aws_sqs_queue(queue_url: 'https://sqs.ap-southeast-2.amazonaws.com/1212121/MyQueue') do it { should exist } end ``` Parameters ---------- ### queue_url *(required)* This resource accepts a single parameter, the SQS Queue URL. This can be passed either as a string or as a `queue_url: 'value'` key-value entry in a hash. See also the [AWS documentation on SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html). Properties ---------- | Property | Description | | --- | --- | | arn | The ARN of the SQS Queue. | | is_fifo_queue | A boolean value indicating if this queue is a FIFO queue | | visibility_timeout | An integer indicating the visibility timeout of the message in seconds | | maximum_message_size | An integer indicating the maximum message size in bytes | | message_retention_period | An integer indicating the maximum retention period for a message in seconds | | delay_seconds | An integer indicating the delay in seconds for the queue | | receive_message_wait_timeout_seconds | An integer indicating the number of seconds an attempt to receive a message will wait before returning | | content_based_deduplication | A boolean value indicating if content based dedcuplication is enabled or not | | redrive_policy | A string indicating the redrive policy | Examples -------- ### Ensure that a queue exists and has a visibility timeout of 300 seconds ``` describe aws_sqs_queue('https://sqs.ap-southeast-2.amazonaws.com/1212121/MyQueue') do it { should exist } its('visibility_timeout') { should be 300 } end ``` ### Ensure maximum message size is set ``` describe aws_sqs_queue('https://sqs.ap-southeast-2.amazonaws.com/1212121/MyQueue') do its('maximum_message_size') { should be 262144 } # 256 KB end ``` ### Test the delay time ``` describe aws_sqs_queue('https://sqs.ap-southeast-2.amazonaws.com/1212121/MyQueue') do its('delay_seconds') { should be 0 } end ``` ### Ensure messages are retained for 4 days ``` describe aws_sqs_queue('https://sqs.ap-southeast-2.amazonaws.com/1212121/MyQueue') do its('message_retention_period') { should be 345600 } # 4 days end ``` ### Check if queue is fifo ``` describe aws_sqs_queue('https://sqs.ap-southeast-2.amazonaws.com/1212121/MyQueue') do its('is_fifo_queue') { should be false } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_sqs_queue('https://sqs.ap-southeast-2.amazonaws.com/1212121/MyQueue') do it { should exist } end describe aws_sqs_queue('https://sqs.ap-southeast-2.amazonaws.com/1212121/MyQueueWhichDoesntExist') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `sqs:GetQueueAttributes` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-using-identity-based-policies.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_sqs_queue/aws_ssm_parameter resource ============================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ssm_parameter.md) Use the `aws_ssm_parameter` InSpec audit resource to test properties of a ssm parameter. Syntax ------ An `aws_ssm_parameter` resource block uses the parameter to select a ssm parameter. ``` describe aws_ssm_parameter(name: 'ssm-parameter-name-1234') do it { should exist } end ``` Parameters ---------- ### name *(required)* This resource accepts a single parameter, the SSM Parameter Name. This can be passed either as a string or as a `aws_ssm_parameter: 'value'` key-value entry in a hash. ### with_decryption *(optional)* This decrypts the value associated with the ssm parameter. This must be passed as a string `with_decryption: "true"`. See also the [AWS documentation on SSM Parameters](https://docs.aws.amazon.com/systems-manager/latest/userguide/integration-ps-secretsmanager.html). Properties ---------- | Property | Description | | --- | --- | | arn | Provides the Amazon Resource Name (ARN) of the parameter. | | data_type | Provides the data type of the parameter. | | last_modified_date | Provides the date the parameter was last changed or updated and the parameter version was created. | | name | Provides the name of the parameter. | | selector | Provides the version number or label used to retrieve the parameter value. | | source_result | Applies to parameters that reference information in other AWS services. | | type | Provides the type of the parameter. | | value | Provides the value of the parameter. | | version | Provides the version of the parameter. | For a comprehensive list of properties available, see [the API reference documentation](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_Parameter.html) Examples -------- ### Check the Name of a SSM Parameter ``` describe aws_ssm_parameter(name: 'ssm_parameter-name-1234') do its('name') { should eq 'ssm_parameter-name-1234' } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_ssm_parameter(name: 'ssm_parameter-name-1234') do it { should exist } end describe aws_ssm_parameter(name: 'ssm_parameter-name-6789') do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ssm:GetParameter` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon Systems Manager](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awssystemsmanager.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ssm_parameter/aws_sns_topics resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_sns_topics.md) Use the `aws_sns_topics` InSpec audit resource to test all or a group of the SNS Topic ARNs in an account. User the ‘aws_sns_topic’ InSpec audit resource to test a single SNS Topic in an account. Syntax ------ ``` # Get all SNS Topic arns describe aws_sns_topics do its('topic_arns') { should include 'arn:aws:sns:us-east-1:333344445555:MyTopic' } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on SNS](https://docs.aws.amazon.com/sns/latest/dg/sns-getting-started.html). Properties ---------- | Property | Description | | --- | --- | | topic_arns | The ARNs of the SNS Topics. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- The following examples show how to use this InSpec audit resource. ### Ensure a Topic exists ``` describe aws_sns_topics do its('topic_arns') { should include 'arn:aws:sns:us-east-1:333344445555:MyTopic' } end ``` Matchers -------- ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_sns_topics do it { should exist } end describe aws_sns_topics do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `sns:ListTopics` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon SNS](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonsns.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_sns_topics/aws_sqs_queues ================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_sqs_queues.md) Use the `aws_sqs_queues` InSpec audit resource to test properties of some or all AWS Simple Queue Service queues. Syntax ------ ``` describe aws_sqs_queues() do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html). Properties ---------- | Property | Description | | --- | --- | | arns | The ARNs of the SQS Queues. | | is_fifo_queues | A boolean value indicating if queues are FIFO queues | | visibility_timeouts | An integer indicating the visibility timeout of the message in seconds | | maximum_message_sizes | An integer indicating the maximum message size in bytes | | message_retention_periods | An integer indicating the maximum retention period for a message in seconds | | delay_seconds | An integer indicating the delay in seconds for the queues | | receive_message_wait_timeout_seconds | An integer indicating the number of seconds an attempt to receive a message will wait before returning | | content_based_deduplications | A boolean value indicating if content based deduplication is enabled or not | Examples -------- ### Ensure that a queue exists and has a visibility timeout of 300 seconds ``` describe aws_sqs_queues.where(queue_url: 'https://sqs.ap-southeast-2.amazonaws.com/1212121/MyQueue') do it { should exist } its('visibility_timeout') { should be 300 } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_sqs_queues() do it { should exist } end describe aws_sqs_queues() do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `sqs:GetQueueAttributes` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-using-identity-based-policies.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_sqs_queues/aws_ssm_parameters resource ============================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_ssm_parameters.md) Use the `aws_ssm_parameters` InSpec audit resource to test properties of a collection of AWS SSM parameters. Syntax ------ Ensure you have exactly 3 SSM Parameters ``` describe aws_ssm_parameters do its('names.count') { should cmp 3 } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on SSM](https://docs.aws.amazon.com/systems-manager/?id=docs_gateway). Properties ---------- | Property | Description | | --- | --- | | names | Provides the name of the parameter. | | types | Provides the type of the parameter. | | key_ids | Provides the key id of the parameter. | | last_modified_dates | Provides the date the parameter was last changed or updated and the parameter version was created. | | last_modified_users | Provides the user that last changed or updated the parameter. | | descriptions | Provides the description of the parameter. | | versions | Provides the version of the parameter. | | tiers | Provides the tier of the parameter. | For a comprehensive list of properties available, see [the API reference documentation](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_Parameter.html) Examples -------- ### Ensure Name of a SSM Parameter exists ``` describe aws_ssm_parameters do its('names') { should include 'ssm-parameter-name' } end ``` Matchers -------- For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_ssm_parameters.where( <property>: <value> ) do it { should exist } end describe aws_ssm_parameters.where( <property>: <value> ) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ssm:DescribeParameters` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon Systems Manager](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awssystemsmanager.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_ssm_parameters/aws_subnet resource ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_subnet.md) Use the `aws_subnet` InSpec audit resource to test properties of a vpc subnet. Syntax ------ An `aws_subnet` resource block uses the parameter to select a VPC and a subnet in the VPC. ``` describe aws_subnet(subnet_id: 'subnet-1234567') do it { should exist } end ``` Parameters ---------- ### subnet_id *(required)* This resource accepts a single parameter, the Subnet ID. This can be passed either as a string or as a `subnet_id: 'value'` key-value entry in a hash. See also the [AWS documentation on Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html). Properties ---------- | Property | Description | | --- | --- | | subnet_id | Provides the ID of the Subnet. | | vpc_id | Provides the ID of the VPC the subnet is in. | | availability_zone | Provides the Availability Zone of the subnet. | | cidr_block | Provides the block of ip addresses specified to the subnet. | | available_ip_address_count | Provides the number of available IPv4 addresses on the subnet. | Examples -------- ### Check availability zone of a subnet ``` describe aws_subnet(subnet_id: 'subnet-12345678') do its('availability_zone') { should eq 'us-east-1c' } end ``` ### Check the number of available IP addresses ``` describe aws_subnet(subnet_id: 'subnet-12345678') do its('available_ip_address_count') { should eq 251 } end ``` ### Test the block of ip addresses specified to the subnet ``` describe aws_subnet(subnet_id: 'subnet-12345678') do its('cidr_block') { should eq '10.0.1.0/24' } end ``` ### Ensure the subnet is in the right VPC ``` describe aws_subnet(subnet_id: 'subnet-12345678') do its('vpc_id') { should eq 'vpc-12345678' } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### assigning_ipv_6_address_on_creation Detects if the network interface on the subnet accepts IPv6 addresses. ``` describe aws_subnet(subnet_id: 'subnet-12345678') do it { should be_assigning_ipv_6_address_on_creation } end ``` ### available Provides the current state of the subnet. ``` describe aws_subnet(subnet_id: 'subnet-12345678') do it { should be_available } end ``` ### default_for_az Detects if the subnet is the default subnet for the Availability Zone. ``` describe aws_subnet(subnet_id: 'subnet-12345678') do it { should be_default_for_az } end ``` ### mapping_public_ip_on_launch Provides the VPC ID for the subnet. ``` describe aws_subnet(subnet_id: 'subnet-12345678') do it { should be_mapping_public_ip_on_launch } end ``` ### exist The `exist` matcher indicates that a subnet exists for the specified vpc. ``` describe aws_subnet(subnet_id: 'subnet-12345678') do it { should exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeSubnets` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_subnet/aws_subnets resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_subnets.md) Use the `aws_subnets` InSpec audit resource to test properties of some or all subnets. Subnets are networks within a VPC that can have their own block of IP address’s and ACL’s. VPCs span across all availability zones in AWS, while a subnet in a VPC can only span a single availability zone. Separating IP addresses allows for protection if there is a failure in one availability zone. Syntax ------ An `aws_subnets` resource block uses an optional filter to select a group of subnets and then tests that group. ``` # Test all subnets within a single vpc describe aws_subnets.where(vpc_id: 'vpc-12345678') do its('subnet_ids') { should include 'subnet-12345678' } its('subnet_ids') { should include 'subnet-98765432' } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html). Properties ---------- | Property | Description | | --- | --- | | subnet_ids | The name of the auto scaling launch configuration associated with the auto scaling group | | vpc_ids | An integer indicating the maximum number of instances in the auto scaling group | | cidr_blocks | An integer indicating the minimum number of instances in the auto scaling group | | availability_zone | The availability zone this subnet is part of. | | map_public_ip_on_launch | A boolean indicating if a public IP is automatically mapped to instances launched in this subnet. | | states | An array of strings corresponding to the subnet IDs associated with the auto scaling group | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Look for all subnets within a vpc ``` describe aws_subnets.where( vpc_id: 'vpc-12345678') do its('subnet_ids') { should include 'subnet-12345678' } its('subnet_ids') { should include 'subnet-98765432' } end ``` ### Examine a specific subnet ``` describe aws_subnets.where(subnet_id: 'subnet-12345678') do its('cidr_blocks') { should eq ['10.0.1.0/24'] } end ``` ### Examine a specific vpcs Subnet IDs ``` describe aws_subnets.where( vpc_id: 'vpc-12345678') do its('states') { should_not include 'pending' } end ``` ### Examine a specific subnets VPC IDS ``` describe aws_subnets.where( subnet_id: 'subnet-12345678') do its('vpc_ids') { should include 'vpc-12345678' } end ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../../matchers/index). exist ----- The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_subnets.where( <property>: <value>) do it { should exist } end describe aws_subnets.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeSubnets` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_subnets/aws_sts_caller_identity resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_sts_caller_identity.md) Use the `aws_sts_caller_identity` InSpec audit resource to test properties of AWS IAM identity whose credentials are used in the current InSpec scan. Syntax ------ An `aws_sts_caller_identity` resource block may be used to perform tests on details of the AWS credentials being used in the current InSpec scan. You can also test if the credentials belong to a GovCloud account or not. ``` describe aws_sts_caller_identity do it { should exist } end ``` Parameters ---------- ### name *(required)* This resource does not expect any parameters. Properties ---------- | Property | Description | | --- | --- | | arn | The ARN of the IAM Identity | Examples -------- ### Check that the credentials used to run the scan is correct ``` describe aws_sts_caller_identity do its("arn") { should match "arn:aws:iam::.*:user/service-account-inspec" } end ``` ### Test if the account belongs to GovCloud ``` describe aws_sts_caller_identity do it { should be_govcloud } end ``` ### Skip a test if we are using GovCloud ``` if aws_sts_caller_identity.govcloud? describe 'Skipping Root User MFA check as we are on GovCloud' do skip end else describe aws_iam_root_user do it { should have_mfa_enabled } end end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_govcloud The `be_govcloud` matcher tests if the account is a ‘GovCloud’ AWS Account. ``` describe aws_sts_caller_identity do it { should_not be_govcloud } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_sts_caller_identity/aws_vpcs resource ================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_vpcs.md) Use the `aws_vpcs` InSpec audit resource to test properties of some or all AWS Virtual Private Clouds (VPCs). Each VPC is uniquely identified by its VPC ID. In addition, each VPC has a non-unique CIDR IP Address range (such as 10.0.0.0/16) which it manages. Every AWS account has at least one VPC, the “default” VPC, in every region. Syntax ------ An `aws_vpcs` resource block uses an optional filter to select a group of VPCs and then tests that group. ``` # Since you always have at least one VPC, this will always pass. describe aws_vpcs do it { should exist } end ``` Parameters ---------- This resource does not expect any parameters. See also the [AWS documentation on VPCs](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html). Properties ---------- | Property | Description | | --- | --- | | cidr_blocks | The cidr_blocks property provides a list of the CIDR blocks that the matched VPCs serve as strings. | | dhcp_options_ids | The dhcp_option_set_ids property provides a de-duplicated list of the DHCP Option Set IDs that the matched VPCs use when assigning IPs to resources. | | vpc_ids | The vpc_ids property provides a list of the IDs of the matched VPCs. | | tags | A hash of key-value pairs corresponding to the tags associated with the entity. | | entries | Provides access to the raw results of the query, which can be treated as an array of hashes. | Examples -------- ### Ensure all VPCs use the same DHCP option set ``` describe aws_vpcs.where { dhcp_options_id != 'dopt-12345678' } do it { should_not exist } end ``` ### Check for a Particular VPC ID ``` describe aws_vpcs do its('vpc_ids') { should include 'vpc-12345678' } end ``` ### Use the VPC IDs to Get a List of Default Security Groups ``` aws_vpcs.vpc_ids.each do |vpc_id| describe aws_security_group(vpc_id: vpc_id, group_name: 'default') do it { should_not allow_in(port: 22) } end end ``` ### We shun the 10.0.0.0/8 space ``` describe aws_vpcs.where { cidr_block.start_with?('10') } do it { should_not exist } end ``` ### Check tags ``` describe aws_vpc do its('tags') { should include(:Environment => 'env-name', :Name => 'vpc-name')} end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exist The control will pass if the describe returns at least one result. Use `should_not` to test the entity should not exist. ``` describe aws_vpcs do it { should exist } end describe aws_vpcs.where( <property>: <value>) do it { should_not exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeVpcs` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_vpcs/aws_vpc resource ================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_vpc.md) Use the `aws_vpc` InSpec audit resource to test properties of a single AWS Virtual Private Cloud (VPC). Each VPC is uniquely identified by its VPC ID. In addition, each VPC has a non-unique CIDR IP Address range (such as 10.0.0.0/16) which it manages. Every AWS account has at least one VPC, the “default” VPC, in every region. Syntax ------ An `aws_vpc` resource block identifies a VPC by id. If no VPC ID is provided, the default VPC is used. ``` # Find the default VPC describe aws_vpc do it { should exist } end # Find a VPC by ID describe aws_vpc('vpc-12345678987654321') do it { should exist } end # Hash syntax for ID describe aws_vpc(vpc_id: 'vpc-12345678') do it { should exist } end ``` Parameters ---------- If no parameter is provided, the subscription’s default VPC will be returned. ### vpc_id *(optional)* This resource accepts a single parameter, the VPC ID. This can be passed either as a string or as a `vpc_id: 'value'` key-value entry in a hash. See also the [AWS documentation on VPCs](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html). Properties ---------- | Property | Description | | --- | --- | | cidr_block | The IPv4 address range that is managed by the VPC. | | dhcp_options_id | The ID of the set of DHCP options associated with the VPC (or `default` if the default options are associated with the VPC). | | instance_tenancy | The allowed tenancy of instances launched into the VPC. | | state | The state of the VPC (`pending` | | vpc_id | The ID of the VPC. | | tags | The tags of the VPC. | Examples -------- The following examples show how to use this InSpec audit resource. ### Test the CIDR of a named VPC ``` describe aws_vpc('vpc-87654321') do its('cidr_block') { should cmp '10.0.0.0/16' } end ``` ### Test the state of the VPC ``` describe aws_vpc do its ('state') { should eq 'available' } # or equivalently it { should be_available } end ``` ### Test the allowed tenancy of instances launched into the VPC ``` describe aws_vpc do its ('instance_tenancy') { should eq 'default' } end ``` ### Test tags on the VPC ``` describe aws_vpc do its('tags') { should include(:Environment => 'env-name', :Name => 'vpc-name')} end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### be_default The test will pass if the identified VPC is the default VPC for the region. ``` describe aws_vpc('vpc-87654321') do it { should be_default } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeVpcs` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_vpc/aws_transit_gateway resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/aws_transit_gateway.md) Use the `aws_transit_gateway` InSpec audit resource to test properties of a transit gateway. Syntax ------ An `aws_transit_gateway` resource block uses the parameter to select a transit gateway. ``` describe aws_transit_gateway(transit_gateway_id: 'tgw-1234567') do it { should exist } end ``` Parameters ---------- ### transit_gateway_id *(required)* This resource accepts a single parameter, the Transit Gateway ID. This can be passed either as a string or as a `transit_gateway_id: 'value'` key-value entry in a hash. See also the [AWS documentation on Transit Gateways](https://docs.aws.amazon.com/vpc/latest/tgw/). Properties ---------- | Property | Description | | --- | --- | | transit_gateway_id | Provides the ID of the Transit Gateway. | | transit_gateway_arn | Provides the ARN of the Transit Gateway. | | transit_gateway_owner_id | Provides the id of the owner of the Transit Gateway. | | default_route_table_id | Provides the id of the default route table of the Transit Gateway. | | propagation_default_route_table_id | Provides the propagation default route table id for the Transit gateway | | dns_support | Provides the status of dns support for the Transit Gateway | | vpn_ecmp_support | Provides the status of vpn ecmp support for the Transit Gateway | Examples -------- ### Check the owner id zone of the Transit Gateway ``` describe aws_transit_gateway(transit_gateway_id: 'tgw-0e231ae7f5e5e7bd5') do its('transit_gateway_owner_id') { should eq 'owner_id' } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### exist The `exist` matcher indicates that a transit gateway exists. ``` describe aws_transit_gateway(transit_gateway_id: 'tgw-0e231ae7f5e5e7bd5') do it { should exist } end ``` AWS Permissions --------------- Your [Principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) will need the `ec2:DescribeTransitGateways` action with Effect set to Allow. You can find detailed documentation at [Actions, Resources, and Condition Keys for Amazon EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html). © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/aws_transit_gateway/azure_generic_resource resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azure_generic_resource.md) Warning This resource is deprecated and should not be used. It will be removed in Chef InSpec 5.0. Instead of using any of the demonstration Azure resources included with Chef InSpec, use the [`inspec-azure`](https://github.com/inspec/inspec-azure) resource pack, which offers rich functionality and specific resources to fit many common use cases. Use the `azure_generic_resource` Chef InSpec audit resource to test any valid Azure Resource. This is very useful if you need to test something that we do not yet have a specific Chef InSpec resource for. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v2.0.16 of InSpec. Syntax ------ ``` describe azure_generic_resource(group_name: 'MyResourceGroup', name: 'MyResource') do its('property') { should eq 'value' } end ``` where: * `MyResourceGroup` is the name of the resource group that contains the Azure Resource to be validated * `MyResource` is the name of the resource that needs to be checked * `property` This generic resource dynamically creates the properties on the fly based on the type of resource that has been targeted. * `value` is the expected output from the chosen property Parameters ---------- * `group_name` * `name` * `apiversion` * `type` The options that can be passed to the resource are as follows. ### `group_name` (required) Use this parameter to define the Azure Resource Group to be tested. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure') do ... end ``` ### `name` Use this parameter to define the name of the Azure resource to test. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Windows-Internal-VM') do ... end ``` ### `apiversion` The API Version to use when querying the resource. Defaults to the latest version for the resource. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Windows-Internal-VM', apiversion: '2.0') do ... end ``` ### `type` Use this parameter to define the type of resources to test. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Windows-Internal-VM', apiversion: '2.0', type: 'Microsoft.Compute/virtualMachines') do ... end ``` These options can also be set using the environment variables: * `AZURE_RESOURCE_GROUP_NAME` * `AZURE_RESOURCE_NAME` * `AZURE_RESOURCE_TYPE` * `AZURE_RESOURCE_API_VERSION` When the options have been set as well as the environment variables, the environment variables take priority. ### Parameter Example ``` describe azure_generic_resource(group_name: 'Inspec-Azure', name: 'Linux-Internal-VM', apiversion: '2.0') do its('location') { should eq 'westeurope' } end ``` Properties ---------- The properties that can be tested are entirely dependent on the Azure Resource that is under scrutiny. That means the properties vary. The best way to see what is available please use the [Azure Resources Portal](https://resources.azure.com) to select the resource you are interested in and see what can be tested. This resource allows you to test *any* valid Azure Resource. The trade off for this is that the language to check each item is not as natural as it would be for a native Chef InSpec resource. Property Examples ----------------- The following examples show how to use some of the Chef InSpec audit properties: ### Tests the virtual machine’s location ``` its('location') { should cmp 'westeurope' } ``` ### Tests for the presence of a specified address prefix ``` its('properties.addressSpace.addressPrefixes') { should include '10.1.1.0/24' } ``` ### Tests that virtual machine was created from the correct disk ``` its('properties.creationData.createOption') { should eq 'FromImage' } ``` ### Tests that the image is Ubuntu ``` its('properties.creationData.imageReference.id') { should match 'Canonical' } its('properties.creationData.imageReference.id') { should match 'UbuntuServer' } its('properties.creationData.imageReference.id') { should match '16.04.0-LTS' } ``` ### Tests the disk size ``` its('properties.diskSizeGB') { should be > 25 } ``` ### Tests the disk state ``` its('properties.diskState') { should cmp 'Attached' } ``` ### Tests that there are no custom DNS settings ``` its('properties.dnsSettings.dnsServers.count') { should eq 0 } its('properties.dnsSettings.appliedDnsServers.count') { should eq 0 } ``` ### Tests that the NIC is connected to the correct machine ``` its('properties.virtualMachine.id') { should match 'Linux-External-VM' } ``` ### Tests that the blob and file services are enabled ``` its('properties.encryption.services.blob.enabled') { should be true } its('properties.encryption.services.file.enabled') { should be true } its('properties.encryption.keySource') { should cmp 'Microsoft.Storage' } ``` ### Test the hardware profile ``` its('properties.hardwareProfile.vmSize') { should cmp 'Standard_DS2_v2' } ``` ### Test the network interfaces ``` its('properties.networkProfile.networkInterfaces.count') { should eq 1 } ``` ### Test the authentication and OS type ``` its('properties.osProfile.computerName') { should eq 'linux-external-1' } its('properties.osProfile.adminUsername') { should eq 'azure' } its('properties.osProfile.linuxConfiguration.disablePasswordAuthentication') { should be true } ``` ### Test that the tags are properly set ``` it { should have_tags } its('tag_count') { should be 1 } its('tags') { should include 'Description' } its('Description_tag') { should match 'Externally facing' } ``` Matchers -------- This Chef InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). References ---------- Please see the integration tests for in depth examples of how this resource can be used. [Chef InSpec Integration Tests for Azure Generic Resources](https://github.com/chef/inspec/tree/main/test/integration/azure/verify/controls) © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azure_generic_resource/azure_resource_group resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azure_resource_group.md) Use the `azure_resource_group_resource_count` Chef InSpec audit resource to check the number of Azure resources in a resource group. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v2.0.16 of InSpec. Syntax ------ The name of the resource group is specified as a parameter on the resource: ``` describe azure_resource_group(name: 'MyResourceGroup') do its('property') { should eq 'value' } end ``` where * `MyResourceGroup` is the name of the resource group being interrogated * `property` is one a resource property * `value` is the expected output from the matcher Examples -------- The following examples show how to use this Chef InSpec audit resource: ### Ensure the Resource Group has the correct number of resources ``` describe azure_resource_group_resource_count(name: 'InSpec-Azure') do its('total') { should eq 7} end ``` ### Ensure that the Resource Group contains the correct resources ``` describe azure_resource_group_resource_count(name: 'InSpec-Azure') do its('total') { should eq 7 } its('vm_count') { should eq 2 } its('nic_count') { should eq 2 } its('public_ip_count') { should eq 1 } its('sa_count') { should eq 1 } its('vnet_count') { should eq 1 } end ``` Parameters ---------- * `group_name` * `name` ### `group_name` (required) Use this parameter to define the Azure Resource Group to be tested. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure') do ... end ``` ### `name` Use this parameter to define the name of the Azure resource to test. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Windows-Internal-VM') do ... end ``` If both `group_name` and `name` is set then `name` takes priority These options can also be set using the environment variables: * `AZURE_RESOURCE_GROUP_NAME` * `AZURE_RESOURCE_NAME` When the options have been set as well as the environment variables, the environment variables take priority. ### Parameter Example ``` describe azure_generic_resource(group_name: 'InSpec-Azure', name: 'Linux-Internal-VM') do its('location') { should eq 'westeurope' } end ``` Properties ---------- * `name` * `location` * `id` * `provisioning_state` * `subscription_id` * `total` * `nic_count` * `vm_count` * `extension_count` * `vnet_count` * `sa_count` * `public_ip_count` * `managed_disk_image_count` * `managed_disk_count` * `tag_count` ### name Tests the name of the resource group. ``` its('name') { should cmp 'InSpec-Azure' } ``` ### location Tests where in Azure the resource group is located. ``` its('location') { should cmp 'westeurope' } ``` ### id Tests the full qualified ID of the resource group. This takes the format: `/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP_NAME>`. ``` its('id') { should cmp 'FQDN' } ``` ### provisioning_state Tests the provisioning state of the resource group. ``` its('provisioning_state') { should cmp 'Succeeded' } ``` ### total Tests the total number of resources in the resource group. ``` its('total') { should eq 13 } ``` ### nic_count Tests the number of network interface cards in the resource group. ``` it { should have_nics } its('nic_count') { should eq 3 } ``` ### vm_count Tests the number of virtual machines in the resource group. ``` its('vm_count') { should eq 5 } ``` ### vnet_count Tests the number of virtual networks in the resource group. ``` its('vnet_count') { should eq 5 } ``` ### sa_count Tests the number of storage accounts in the resource group. ``` its('sa_count') { should eq 5 } ``` ### public_ip_count Tests the number of Public IP Addresses in the resource group. ``` its('public_ip_count') { should eq 5 } ``` ### managed_disk_image_count Tests the number of managed disk images that are in the resource group. Managed disks are created from disk images and then attached to the machines. Generally, the images are created from a base image or a custom image (e.g., Packer) ``` its('managed_disk_image_count') { should eq 5 } ``` ### managed_disk_count Tests the number of managed disks in the resource group. If a resource group contains one virtual machine with an OS disk and 2 data disks that are all Managed Disks, then the count would be 3. ``` its('managed_disk_count') { should eq 3 } ``` Matchers -------- This resource has a number of special matchers that provide a simple way to test if a specific Azure Resource type exists in the resource group. For a full list of available matchers, please visit our [matchers page](../../matchers/index). ### have_nics Use this matcher to test if network interfaces exist. ``` it { should have_nics } ``` ### have_vms Use this matcher to test that virtual machines exist. ``` it { should have_vms } ``` ### have_extensions Use this matcher to test for virtual machine extensions. ``` it { should have_extensions } ``` ### have_nsgs Use this matcher to test that network security groups exist. ``` it { should have_nsgs } ``` ### have_vnets Use this matcher to test that virtual networks exist. ``` it { should have_vnets } ``` ### have_managed_disks Use this matcher to test that managed disks exist. ``` it { should have_managed_disks } ``` ### have_managed_disk_images Use this matcher to test that managed disk images exist. ``` it { should have_managed_disk_images } ``` ### have_sas Use this matcher to test that storage accounts exist. ``` it { should have_sas } ``` ### have_public_ips Use this matcher to test that public ips exist. ``` it { should have_public_ips } ``` Tags ---- It is possible to test the tags that have been assigned to the resource. There are some properties for checking that a resource has tags, that it has the correct number of tags, and that the correct tags are assigned. ### have_tags This is a simple test to see if the machine has tags assigned to it or not. ``` it { should have_tags } ``` ### tag_count Returns the number of tags that are assigned to the resource ``` its ('tag_count') { should eq 2 } ``` ### tags It is possible to check if a specific tag has been set on the resource. ``` its('tags') { should include 'owner' } ``` ### xxx_tag To get the value of the tag, some properties are created from the tags themselves. For example, if the following tag is set on a resource: * owner: <NAME> Then a property is available called `Owner_tag`. ``` its('owner_tag') { should cmp '<NAME>' } ``` Note: The tag name is case sensitive which makes the test case sensitive. E.g. `owner_tag` does not equal `Owner_tag`. References ---------- For more information on Azure Ruby SDK resources, see: * [Azure Ruby SDK - Resources](https://github.com/Azure/azure-sdk-for-ruby/tree/main/management/azure_mgmt_resources) * [Resource Group](https://github.com/chef/inspec/blob/fc990346f2438690f0ac36a9f6606e61574a79b8/test/azure/verify/controls/resource_group.rb) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azure_resource_group/azure_virtual_machine_data_disk resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azure_virtual_machine_data_disk.md) Use this resource to ensure that a specific data disk attached to a machine has been created properly. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v2.0.16 of InSpec. Syntax ------ The name of the resource group and machine are required to use this resource. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'MyVM') do its('property') { should eq 'value' } end ``` where: * `MyVm` is the name of the virtual machine as seen in Azure. (It is **not** the hostname of the machine) * `InSpec-Azure` is the name of the resource group that the machine is in. * `property` is a resource property * `value` is the expected output from the matcher Examples -------- The following examples show to use this Chef InSpec audit resource. ### Check that the first data disk is of the correct size ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Linux-Internal-VM').where(number: 1) do its('size') { should cmp >= 15 } end ``` Resource Parameters ------------------- * `group_name` * `name` * `apiversion` Parameter Examples ------------------ The options that can be passed to the resource are as follows. ### `group_name` (required) Use this parameter to define the Azure Resource Group to be tested. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure') do ... end ``` ### name Use this parameter to define the name of the Azure resource to test. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Windows-Internal-VM') do ... end ``` ### apiversion The API Version to use when querying the resource. Defaults to the latest version for the resource. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Windows-Internal-VM', apiversion: '2.0') do ... end ``` These options can also be set using the environment variables: * `AZURE_RESOURCE_GROUP_NAME` * `AZURE_RESOURCE_NAME` * `AZURE_RESOURCE_API_VERSION` When the options have been set as well as the environment variables, the environment variables take priority. Filter Criteria --------------- * `number` * `disk` Filter Examples --------------- ### disk The zero based index of the disk attached to the machine. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Windows-Internal-VM').where(disk: 0) end ``` ### number The ‘1’ based index of the disk attached to the machine. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Windows-Internal-VM').where(number: 1) end ``` Properties ---------- * `count`, `disk`, `number`, `name`, `size`, `lun`, `caching`, `create_option`, `is_managed_disk?`, `vhd_uri`, `storage_account_name`, `storage_account_type`, `id`, `subscription_id`, `resource_group` Property Examples ----------------- ### count Returns the number of data disks attached to the machine ``` its('count') { should eq 1 } ``` ### name Returns a string of the name of the disk. ``` its('name') { should cmp 'linux-external-datadisk-1' } ``` ### size Returns an integer of size of this disk in GB. ``` its('size') { should cmp >= 15 } ``` ### lun The disk number as reported by Azure. Has a zero-based index value. ``` its('lun') { should cmp 0 } ``` ### caching String stating the caching that has been set on the disk. ``` its('caching') { should cmp 'none' } ``` ### create_option How the disk was created. Typically for data disks, this will be the string value ‘Empty’. ``` its('create_option') { should cmp 'Empty' } ``` ### is_managed_disk? Boolean stating if the disk is a managed disk or not. If it is not a managed disk then it is one that is stored in a Storage Account. ``` its('is_managed_disk?') { should cmp 'false' } ``` ### vhd_uri If this is *not* a managed disk, then the `vhd_uri` will be the full URI to the disk in the storage account. ``` its('vhd_uri') { should cmp 'https://primary_storage.blob.core.windows.net/container_name/vm_name.vhd' } ``` ### storage_account_name If this is *not* a managed disk this will be the storage account name in which the disk is stored. This derived from the `vhd_uri`. ``` its('storage_account_name') { should cmp 'primary_storage' } ``` ### storage_account_type If this is a managed disk this is the storage account type, e.g. `Standard_LRS`. ``` its('storage_account_type') { should cmp 'Standard_LRS' } ``` ### id If this is a managed disk then this is the fully qualified id for the disk in Azure. ``` its('id') { should cmp '/subscriptions/1234abcd-e567-890f-g123-456h78i9jkl0/resourceGroups/InSpec-Azure' } ``` ### subscription_id If this is a managed disk, this returns the subscription id of where the disk is stored. This is derived from the `id`. ``` its('subscription_id') { should cmp '1234abcd-e567-890f-g123-456h78i9jkl0' } ``` ### resource_group If this is a managed disk, this returns the resource group in which the disk is stored. This is derived from the `id`. ``` its('resource_group') { should cmp 'InSpec-Azure' } ``` ## Matchers This Chef InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [matchers page](../../matchers/index). The following properties are applied to the virtual machine itself and not specific disks. ### have_data_disks Returns a boolean denoting if any data disks are attached to the machine. ``` it { should have_data_disks } ``` ### have_managed_disks Returns a boolean stating if the machine has Managed Disks for data disks. ``` it { should have_managed_disks } ``` References ---------- * [Azure Ruby SDK - Compute](https://github.com/Azure/azure-sdk-for-ruby/tree/main/management/azure_mgmt_compute) * [Linux Internal Data Disks](https://github.com/chef/inspec/blob/main/test/azure/verify/controls/virtual_machine_linux_external_vm_datadisk.rb) * [Windows Internal Data Disk](https://github.com/chef/inspec/blob/main/test/azure/verify/controls/virtual_machine_windows_internal_vm_datadisk.rb) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azure_virtual_machine_data_disk/azurerm_ad_user resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_ad_user.md) Use the `azurerm_ad_user` InSpec audit resource to test properties of an Azure Active Directory user within a Tenant. Azure REST API version ---------------------- This resource interacts with version `1.6` of the Azure Graph API. For more information see the [official Azure documentation](https://msdn.microsoft.com/Library/Azure/Ad/Graph/api/users-operations#GetAUser). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.1.0 of the inspec-azure resource pack. Syntax ------ The `user_id` must be given as a parameter. ``` describe azurerm_ad_user(user_id: 'someUserId') do it { should exist } end ``` Examples -------- If an Active Directory user account is referenced with a valid ID ``` describe azurerm_ad_user(user_id: 'someValidId') it { should exist } end ``` If an Active Directory user account is referenced with an invalid ID ``` describe azurerm_ad_user(user_id: 'someInvalidId') it { should_not exist } end ``` Parameters ---------- * `user_id` Parameter Examples ------------------ `user_id` is a required parameter. ``` describe azurerm_ad_user(user_id: 'MyUserId') do ... end ``` Attributes ---------- * `object_id` * `account_enabled` * `city` * `country` * `department` * `displayName` * `facsimile_telephone_number` * `given_name` * `job_title` * `mail` * `mail_nickname` * `mobile` * `password_policies` * `password_profile` * `postal_code` * `state` * `street_address` * `surname` * `telephone_number` * `usage_location` * `user_principal_name` * `user_type` ### object_id The user’s object ID. ### account_enabled Whether the account is enabled. ### city The user’s city. ### country The user’s country. ### department The user’s department. ### displayName The display name of the user. ### facsimile_telephone_number the user’s facsimile (fax) number. ### given_name the given name for the user. ### job_title the user’s job title. ### mail the primary email address of the user. ### mail_nickname The mail alias for the user. ### mobile The user’s mobile (cell) phone number. ### password_policies The password policies for the user. ### password_profile The password profile for the user. ### postal_code The user’s postal (ZIP) code. ### state The user’s state. ### street_address The user’s street address. ### surname The user’s surname (family name or last name). ### telephone_number The user’s telephone number. ### usage_location A two letter country code (ISO standard 3166). Required for users that will be assigned licenses due to legal requirement to check for availability of services in countries. Examples include: “US”, “JP”, and “GB”. ### user_principal_name The principal name of the user. ### user_type A string value that can be used to classify user types in your directory, such as ‘Member’ and ‘Guest’. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). Given the example response in their documentation: ``` ... "preferredLanguage": "en-US", "provisionedPlans": [ { "capabilityStatus": "Enabled", "provisioningStatus": "Success", "service": "exchange" }, ... ``` We may access `provisioningStatus` with: ``` its('provisionedPlants.first.provisioningStatus') { should eq "Success" } ``` The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_ad_user(user_id: 'someUserId') do it { should exist } end ``` Azure Permissions ----------------- The Client/Active Directory Application you have configured InSpec Azure to use (`AZURE_CLIENT_ID`) must have permissions to read User data from the Azure Graph RBAC API. Please refer to the [Microsoft Documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-integrating-applications#updating-an-application) for information on how to grant these permissions to your application. Note: An Azure Admin must grant your application these permissions. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_ad_user/azurerm_aks_cluster resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_aks_cluster.md) Use the `azurerm_aks_cluster` InSpec audit resource to test properties of an Azure AKS Cluster. Azure REST API version ---------------------- This resource interacts with version `2018-03-31` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/aks/managedclusters/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_aks_cluster` resource block identifies an AKS Cluster by name and Resource Group. ``` describe azurerm_aks_cluster(resource_group: 'example', name: 'ClusterName') do ... end ``` Examples -------- ### Test that an example Resource Group has the specified AKS Cluster ``` describe azurerm_aks_cluster(resource_group: 'example', name: 'ClusterName') do it { should exist } end ``` ### Test that a specified AKS cluster was successfully provisioned ``` describe azurerm_network_security_group(resource_group: 'example', name: 'ClusterName') do its('properties.provisioningState') { should cmp 'Succeeded' } end ``` ### Test that a specified AKS cluster the correct number of nodes in pool ``` describe azurerm_network_security_group(resource_group: 'example', name: 'ClusterName') do its('properties.agentPoolProfiles.first.count') { should cmp 5 } end ``` Parameters ---------- * `name` * `resource_group` Parameter Examples ------------------ The Resource Group as well as the AKS Cluster name. ``` describe azurerm_aks_cluster(resource_group: 'example', name: 'ClusterName') do it { should exist } end ``` Attributes ---------- All of the attributes are available via dot notation. This is an example of the currently available attributes. ``` control 'azurerm_aks_cluster' do describe azurerm_aks_cluster(resource_group: 'example', name: 'ClusterName') do it { should exist } its('properties.provisioningState') { should cmp 'Succeeded' } its('properties.kubernetesVersion') { should cmp '1.11.3' } its('properties.dnsPrefix') { should cmp 'ClusterName' } its('properties.fqdn') { should cmp 'ClusterName' } its('properties.agentPoolProfiles.first.name') { should cmp 'agentpool' } its('properties.agentPoolProfiles.first.count') { should cmp 3 } its('properties.agentPoolProfiles.first.vmSize') { should cmp 'Standard_DS2_V2' } its('properties.agentPoolProfiles.first.storageProfile') { should cmp 'ManagedDisks' } its('properties.agentPoolProfiles.first.maxPods') { should cmp 110 } its('properties.agentPoolProfiles.first.osType') { should cmp 'Linux' } end end ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'ClusterName' to always exist describe azurerm_aks_cluster(resource_group: 'example', name: 'ClusterName') do it { should exist } end # If we expect 'ClusterName' to never exist describe azurerm_aks_cluster(resource_group: 'example', name: 'ClusterName') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_aks_cluster/azure_virtual_machine resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azure_virtual_machine.md) Use the `azure_virtual_machine` Chef InSpec audit resource to ensure that a Virtual Machine has been provisioned correctly. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v2.0.16 of InSpec. Syntax ------ The name of the machine and the resource group are required as properties to the resource. ``` describe azure_virtual_machine(group_name: 'MyResourceGroup', name: 'MyVM') do its('property') { should eq 'value' } end ``` where * `MyVm` is the name of the virtual machine as seen in Azure; it is **not** the hostname of the machine * `MyResourceGroup` is the name of the machine’s resource group * `property` is one of the resource properties * `value` is the expected output from the matcher Examples -------- The following examples show to use this Chef InSpec audit resource. ### Check that the first data disk is of the correct size ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Linux-Internal-VM').where(number: 1) do its('size') { should cmp >= 15 } end ``` Parameters ---------- * `group_name` * `name` * `apiversion` The options that can be passed to the resource are as follows. ### `group_name` (required) Use this parameter to define the Azure Resource Group to be tested. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure') do ... end ``` ### `name` Use this parameter to define the name of the Azure resource to test. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Windows-Internal-VM') do ... end ``` ### `apiversion` The API Version to use when querying the resource. Defaults to the latest version for the resource. ``` describe azure_virtual_machine_data_disk(group_name: 'InSpec-Azure', name: 'Windows-Internal-VM', apiversion: '2.0') do ... end ``` These options can also be set using the environment variables: * `AZURE_RESOURCE_GROUP_NAME` * `AZURE_RESOURCE_NAME` * `AZURE_RESOURCE_API_VERSION` When the options have been set as well as the environment variables, the environment variables take priority. Properties ---------- * `type`, `location`, `name`, `publisher`, `offer`, `sku`, `os_type`, `os_disk_name`, `have_managed_osdisk`, `caching`, `create_option`, `disk_size_gb`, `have_data_disks`, `data_disk_count` , `storage_account_type`, `vm_size`, `computer_name`, `admin_username`, `have_nics`, `nic_count`, `connected_nics`, `have_password_authentication`, `password_authentication?`, `have_custom_data`, `custom_data?`, `have_ssh_keys`, `ssh_keys?`, `ssh_key_count`, `ssh_keys`, `have_boot_diagnostics`, `boot_diagnostics_storage_uri` Property Examples ----------------- This Chef InSpec audit resource has the following properties that can be tested: ### type The Azure Resource type. For a virtual machine this will always return `Microsoft.Compute/virtualMachines` ``` its('type') { should cmp 'Microsoft.Compute/virtualMachines' } ``` ### location Where the machine is located ``` its('location') { should eq 'westeurope' } ``` ### name Name of the Virtual Machine in Azure. Be aware that this is not the computer name or hostname, rather the name of the machine when seen in the Azure Portal. ``` its('name') { should cmp 'InSpec-Azure' } ``` ### publisher The publisher of this machine’s build image. `nil` if the machine was created from a custom image. ``` its('publisher') { should cmp 'MicrosoftWindowsServer' } ``` ### offer The offer from the publisher of the build image. `nil` if the machine was created from a custom image. ``` its('offer') { should cmp 'WindowsServer' } ``` ### sku The item from the publisher that was used to create the image. `nil` if the machine was created from a custom image. ``` its('sku') { should cmp '2016-Datacenter' } ``` ### os_type Test that returns the classification in Azure of the operating system type. Usually either `Linux` or `Windows`. ``` its('os_type') { should cmp 'Windows' } ``` ### os_disk_name Return the name of the operating system disk attached to the machine. ``` its('os_disk_name') { should cmp 'Windows-Internal-OSDisk-MD' } ``` ### caching Returns the type of caching that has been set on the operating system disk. ``` its('caching') { should cmp 'ReadWrite' } ``` ### create_option When the operating system disk is created, how it was created is set as a property. This property returns how the disk was created. ``` its('create_option') { should cmp 'FromImage' } ``` ### disk_size_gb Returns the size of the operating system disk. ``` its('disk_size_gb') { should be >= 30 } ``` ### data_disk_count Return the number of data disks that are attached to the machine ### storage_account_type This provides the storage account type for a machine that is using managed disks for the operating system disk. ``` its('storage_account_type') { should cmp 'Standard_LRS' } ``` ### vm_size The size of the machine in Azure ``` its('vm_size') { should eq 'Standard_DS2_v2' } ``` ### computer_name The name of the machine. This is what was assigned to the machine during deployment and is what *should* be returned by the `hostname` command. ``` its('computer_name') { should cmp 'win-internal-1' } ``` ### admin_username The admin username that was assigned to the machine NOTE: Azure does not allow the use of `Administrator` as the admin username on a Windows machine ``` its('admin_username') { should cmp 'azure' } ``` ### nic_count The number of network interface cards that have been attached to the machine ``` its('nic_count') { should eq 1 } ``` ### connected_nics This returns an array of the NIC ids that are connected to the machine. This means that it possible to check that the machine has the correct NIC(s) attached and thus on the correct subnet. ``` its('connected_nics') { should include /Inspec-NIC-1/ } ``` Note the use of the regular expression here. This is because the NIC id is a long string that contains the subscription id, resource group, machine id as well as other things. By using the regular expression the NIC can be checked without breaking this string up. It also means that other tests can be performed. An example of the id string is `/subscriptions/1e0b427a-d58b-494e-ae4f-ee558463ebbf/resourceGroups/Inspec-Azure/providers/Microsoft.Network/networkInterfaces/Inspec-NIC-1` ### password_authentication? Boolean to state of password authentication is enabled or not for the admin user. ``` its('password_authentication?') { should be false } ``` This only applies to Linux machines and will always return `true` on Windows. ### custom_data Boolean to state if the machine has custom data or not ``` its('custom_data') { should be true } ``` ### ssh_keys? Boolean to state of the machine is accessible using SSH keys ``` its('ssh_keys?') { should be true } ``` ### ssh_key_count Returns how many SSH keys have been applied to the machine. This only applies to Linux machines and will always return `0` on Windows. ``` its('ssh_key_count') { should eq '0' } ``` ### ssh_keys Returns an array of the keys that are assigned to the machine. This checks if the correct keys are assigned. Most SSH public keys have a signature at the end of them that can be tested. For example: ``` its('ssh_keys') { should include /azure@inspec.local/ } ``` ### boot_diagnostics_storage_uri If boot diagnostics are enabled for the machine they will be saved in a storage account. This method returns the URI for the storage account. ``` its('boot_diagnostics_storage_uri') { should match 'ghjgjhgjg' } ``` Matchers -------- There are a number of built in comparison operators that are available to test the result with an expected value. For information on all that are available please refer to the [Chef InSpec Matchers Reference](../../matchers/index) page. ### boot_diagnostics? Boolean test to see if boot diagnostics have been enabled on the machine ``` it { should have_boot_diagnostics } ``` ### have_custom_data Returns a boolean stating if the machine has custom data assigned to it. ``` it { should have_custom_data } ``` ### have_data_disks Denotes if the machine has data disks attached to it or not. ``` it { should have_data_disks } ``` ### have_managed_osdisk Determine if the operating system disk is a Managed Disks or not. This test can be used in the following way: ``` it { should have_managed_osdisk } ``` ### have_nics Returns a boolean to state if the machine has NICs connected or not. This can be used in the following way: ``` it { should have_nics } ``` ### have_password_authentication Returns a boolean to denote if the machine is accessible using a password. ``` it { should have_password_authentication } ``` ### have_ssh_keys Boolean to state if the machine has SSH keys assigned to it ``` it { should have_ssh_keys } ``` For a Windows machine this will always be false. Tags ---- It is possible to test the tags that have been assigned to the resource. There are a number of properties that can be called to check that it has tags, that it has the correct number and that the correct ones are assigned. ### have_tags This is a simple test to see if the machine has tags assigned to it or not. ``` it { should have_tags } ``` ### tag_count Returns the number of tags that are assigned to the resource ``` its ('tag_count') { should eq 2 } ``` ### tags It is possible to check if a specific tag has been set on the resource. ``` its('tags') { should include 'Owner' } ``` ### xxx_tag To get the value of the tag, a number of tests have been created from the tags that are set. For example, if the following tag is set on a resource: * owner: <NAME> Then a test is available called `Owner_tag`. ``` its('owner_tag') { should cmp '<NAME>' } ``` Note: The tag name is case sensitive which makes the test case sensitive. E.g. `owner_tag` does not equal `Owner_tag`. References ---------- * [Azure Ruby SDK - Resources](https://github.com/Azure/azure-sdk-for-ruby/tree/main/management/azure_mgmt_resources) * [Virtual Machine External VM](https://github.com/chef/inspec/blob/fc990346f2438690f0ac36a9f6606e61574a79b8/test/azure/verify/controls/virtual_machine_external_vm.rb) * [Virtual Machine Internal VM](https://github.com/chef/inspec/blob/fc990346f2438690f0ac36a9f6606e61574a79b8/test/azure/verify/controls/virtual_machine_internal_vm.rb) © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azure_virtual_machine/azurerm_ad_users resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_ad_users.md) Use the `azurerm_ad_users` InSpec audit resource to test properties of some or all Azure Active Directory users within a Tenant. Azure REST API version ---------------------- This resource interacts with version `1.6` of the Azure Graph API. For more information see the [official Azure documentation](https://msdn.microsoft.com/Library/Azure/Ad/Graph/api/users-operations#GetUsers). I don’t see a way to select the version of the API in the Azure documents. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.1.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_ad_users` resource block returns all Azure Active Directory user accounts for the contained within the configured Tenant and then tests that group group of users. ``` describe azurerm_ad_users do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check Users are present ``` describe azurerm_ad_users do it { should exist } end ``` ### Ensure there are no Guest accounts active ``` describe azurerm_ad_users.guest_accounts it { should_not exist } end ``` Filter Criteria --------------- * `names` ### names Filters the results to include only those Users that match the given name. This is a string value. ``` describe azurerm_ad_users.where{ displayName.eql?('<NAME>') } do it { should exist } end ``` Properties ---------- * `object_ids` * `display_names` * `mails` * `user_types` ### object_ids The azureIds property provides a list of all User’s Azure IDs. ``` its('azure_ids') { should include '44211066-f292-4546-8ced-2ab0e0911f44' } ``` ### display_names The displayNames property provides a list of all the User display names. ``` its('display_names') { should include 'Azure Admin Account' } ``` ### mails The mails property provides a list of all the User email addresses, where present. ``` its('mails') { should include '<EMAIL>' } ``` ### user_types The userTypes property provides a list of all User Types for all users. ``` its('user_types') { should include 'Member' } ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_ad_users do it { should exist } end ``` Azure Permissions ----------------- The Client/Active Directory Application you have configured InSpec Azure to use (`AZURE_CLIENT_ID`) must have permissions to read User data from the Azure Graph RBAC API. Please refer to the [Microsoft Documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-integrating-applications#updating-an-application) for information on how to grant these permissions to your application. Note: An Azure Admin must grant your application these permissions. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_ad_users/azurerm_aks_clusters resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_aks_clusters.md) Use the `azurerm_aks_clusters` InSpec audit resource to enumerate AKS Clusters. Azure REST API version ---------------------- This resource interacts with version `2018-03-31` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/aks/managedclusters/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_aks_clusters` resource block identifies AKS Clusters by Resource Group. ``` describe azurerm_aks_clusters(resource_group: 'ExampleGroup') do ... end ``` Examples -------- ### Test that an example Resource Group has the named AKS Cluster ``` describe azurerm_aks_clusters(resource_group: 'ExampleGroup') do its('names') { should include('ClusterName') } end ``` Properties ---------- * `names` ### names The name of the AKS Cluster ``` its('names') { should include('ClusterName') } ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'ExampleGroup' Resource Group to have AKS Clusters describe azurerm_aks_clusters(resource_group: 'ExampleGroup') do it { should exist } end # If we expect 'EmptyExampleGroup' Resource Group to not have AKS Clusters describe azurerm_aks_clusters(resource_group: 'EmptyExampleGroup') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_aks_clusters/azurerm_event_hub_namespace resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_event_hub_namespace.md) Use the `azurerm_event_hub_namespace` InSpec audit resource to test properties and configuration of an Azure Event Hub Namespace within a Resource Group. Azure REST API version ---------------------- This resource interacts with version `2017-04-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/eventhub/namespaces/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.11.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` and `namespace_name` must be given as a parameter. ``` describe azurerm_event_hub_namespace(resource_group: 'my-rg', namespace_name 'my-event-hub-ns') do it { should exist } end ``` Examples -------- If an Event Hub Namespace is referenced with a valid `Resource Group` and `Namespace Name` ``` describe azurerm_event_hub_namespace(resource_group: 'my-rg', namespace_name: 'my-event-hub-ns') do it { should exist } end ``` If an Event Hub Namespace is referenced with an invalid `Resource Group` or `Namespace Name` ``` describe azurerm_event_hub_namespace(resource_group: 'invalid-rg', namespace_name: 'i-dont-exist') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the Event Hub Namespace belongs. * `namespace_name` - The unique name of the Event Hub Namespace. Attributes ---------- * `id` * `name` * `sku` * `location` * `properties` * `tags` * `type` ### id Azure resource ID. ### name Event Hub Namespace name, e.g. `my-event-hub-ns`. ### sku SKU properties for the Event Hub Namespace. Such as sku name, billing tier and capacity. ### location Resource location, e.g. `eastus`. ### properties A collection of additional configuration properties related to the Event Hub Namespace, e.g. `isAutoInflateEnabled,maximumThroughputUnits,kafkaEnabled`. ### tags Resource tags applied to the Event Hub Namespace. ### type The type of Resource, typically `Microsoft.EventHub/Namespaces`. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_event_hub_namespace(resource_group: 'my-rg', namespace_name: 'my-event-hub-ns') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_event_hub_namespace/azurerm_cosmosdb_database_account resource ============================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_cosmosdb_database_account.md) Use the `azurerm_cosmosdb_database_account` InSpec audit resource to test properties and configuration of an Azure CosmosDb Database Account within a Resource Group. Azure REST API version ---------------------- This resource interacts with version `2015-04-08` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/cosmos-db-resource-provider/databaseaccounts/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.11.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` and `cosmosdb_database_account` must be given as a parameter. ``` describe azurerm_cosmosdb_database_account(resource_group: 'my-rg', cosmosdb_database_account 'my-cosmos-db') do it { should exist } end ``` Examples -------- If an CosmosDb Database Account is referenced with a valid `Resource Group` and `CosmosDb Database Account` ``` describe azurerm_cosmosdb_database_account(resource_group: 'my-rg', cosmosdb_database_account 'my-cosmos-db') do it { should exist } end ``` If an CosmosDb Database Account is referenced with an invalid `Resource Group` and `CosmosDb Database Account` ``` describe azurerm_cosmosdb_database_account(resource_group: 'my-rg', cosmosdb_database_account 'fake-cosmos-db') do it { should not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the CosmosDb Database Account belongs. * `cosmosdb_database_account` - The unique name of the CosmosDb Database Account. Attributes ---------- * `id` * `name` * `location` * `type` * `kind` * `tags` * `properties` ### id Azure resource ID. ### name CosmosDb Database Account name, e.g. `my-cosmosdb-account`. ### location Resource location, e.g. `eastus`. ### type The type of Resource, typically `Microsoft.DocumentDB/databaseAccounts`. ### kind Indicates the type of database account, e.g. `GlobalDocumentDB`, `MongoDB` ### tags Resource tags applied to the ComsosDb Account. ### properties A collection of additional configuration properties related to the CosmosDb Database Account, e.g. `Capability, ConsistencyPolicy, DatabaseAccountKind`. For a full list of properties please take a look at the [Azure documentation](https://docs.microsoft.com/en-us/rest/api/cosmos-db-resource-provider/databaseaccounts/get#definitions) ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_cosmosdb_database_account(resource_group: 'my-rg', cosmosdb_database_account 'my-cosmos-db') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_cosmosdb_database_account/azurerm_event_hub_event_hub resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_event_hub_event_hub.md) Use the `azurerm_event_hub_event_hub` InSpec audit resource to test properties and configuration of an Azure Event Hub Event Hub within a Resource Group. Azure REST API version ---------------------- This resource interacts with version `2017-04-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/eventhub/eventhubs/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.11.0 of the inspec-azure resource pack. Syntax ------ The `resource_group`, `namespace_name` and `event_hub_name` must be given as a parameter. ``` describe azurerm_event_hub_event_hub(resource_group: 'my-rg', namespace_name 'my-event-hub-ns', event_hub_name 'myeventhub') do it { should exist } end ``` Examples -------- If an Event Hub Event Hub is referenced with a valid `Resource Group`, `Namespace Name` and `Event Hub Name` ``` describe azurerm_event_hub_event_hub(resource_group: 'my-rg', namespace_name: 'my-event-hub-ns', event_hub_name 'myeventhub') do it { should exist } end ``` If a Event Hub Event Hub is referenced with an invalid `Resource Group`, `Namespace Name` and `Event Hub Name` ``` describe azurerm_event_hub_event_hub(resource_group: 'invalid-rg', namespace_name: 'i-dont-exist', event_hub_name 'i-dont-exist') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the Event Hub Event Hub belongs. * `namespace_name` - The unique name of the Event Hub Namespace. * `event_hub_name` - The unique name of the Event Hub Name. Attributes ---------- * `id` * `name` * `type` * `properties` ### id Azure resource ID. ### name Event Hub name, e.g. `myeventhub`. ### type The type of Resource, typically `Microsoft.EventHub/Namespaces/EventHubs`. ### properties A collection of additional configuration properties related to the Event Hub Event Hub, e.g. `messageRetentionInDays, partitionCount, status`. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_event_hub_event_hub(resource_group: 'my-rg', namespace_name: 'my-event-hub-ns', event_hub_name: 'myeventhub') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_event_hub_event_hub/azurerm_event_hub_authorization_rule resource ================================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_event_hub_authorization_rule.md) Use the `azurerm_event_hub_authorization_rule` InSpec audit resource to test properties and configuration of an Azure Event Hub Authorization Rule within a Resource Group. Azure REST API version ---------------------- This resource interacts with version `2017-04-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/eventhub/namespaces/getauthorizationrule). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.11.0 of the inspec-azure resource pack. Syntax ------ The `resource_group`, `namespace_name`, `event_hub_name` and `authorization_rule_name` must be given as a parameter. ``` describe azurerm_event_hub_authorization_rule(resource_group: 'my-rg', namespace_name 'my-event-hub-ns', event_hub_name: 'myeventhub', authorization_rule_name: 'my-auth-rule') do it { should exist } end ``` Examples -------- If an Event Hub Authorization Rule is referenced with a valid `Resource Group`, `Namespace Name`, `Event Hub Name` and `Authorization Rule Name` ``` describe azurerm_event_hub_authorization_rule(resource_group: 'my-rg', namespace_name: 'my-event-hub-ns', event_hub_endpoint: 'myeventhub', authorization_rule: 'my-auth-rule') do it { should exist } end ``` If a Event Hub Authorization Rule is referenced with an invalid `Resource Group`, `Namespace Name`, `Event Hub Name` or `Authorization Rule Name` ``` describe azurerm_event_hub_namespace(resource_group: 'invalid-rg', namespace_name: 'i-dont-exist', event_hub_endpoint: 'fakeendpoint', authorization_rule: 'fake-auth-rule') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the Event Hub Namespace belongs. * `namespace_name` - The unique name of the Event Hub Namespace. * `event_hub_name` - The unique name of the Event Hub Name. * `authorization_rule_name` - The unique name of the Event Hub Authorization Rule. Attributes ---------- * `id` * `name` * `properties.rights` * `type` ### id Azure resource ID. ### name Event Hub Authorization Rule name, e.g. `my-auth-rule`. ### properties A collection of additional configuration properties related to the Event Hub Authorization Rule, eg. `rights` ### type The type of Resource, typically `Microsoft.EventHub/Namespaces/EventHubs/AuthorizationRules`. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_event_hub_authorization_rule(resource_group: 'my-rg', namespace_name 'my-event-hub-ns', event_hub_name: 'myeventhub', authorization_rule_name: 'my-auth-rule') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_event_hub_authorization_rule/azurerm_key_vault resource ============================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_key_vault.md) Use the `azurerm_key_vault` InSpec audit resource to test properties and configuration of an Azure Key Vault. Azure REST API version ---------------------- This resource interacts with version `2016-10-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/keyvault/vaults/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.2.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` and `vault_name` must be given as a parameter. ``` describe azurerm_key_vault(resource_group: 'inspec-resource-group', vault_name: 'vault-101') do it { should exist } its('name') { should eq('vault-101') } end ``` Examples -------- If a Key Vault is referenced with a valid `Resource Group` and `Vault Name` ``` describe azurerm_key_vault(resource_group: 'my-rg', vault_name: 'vault-101') do it { should exist } end ``` If a Key Vault is referenced with an invalid `Resource Group` or `Vault Name` ``` describe azurerm_key_vault(resource_group: 'invalid-rg', vault_name: 'vault-null') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the Key Vault belongs. * `vault_name` - The unique name of the Key Vault. Attributes ---------- * `id` * `name` * `location` * `type` * `tags` * `properties` ### id Azure resource ID. ### name Key Vault name, e.g. `vault-101`. ### location Resource location, e.g. `eastus`. ### type The type of Resource, typically `Microsoft.KeyVault/vaults`. ### tags Resource tags applied to the Key Vault. ### properties A collection of additional configuration properties related to the Key Vault, e.g. `vaultUri`. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_key_vault(resource_group: 'my-rg', vault_name: 'vault-101') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_key_vault/azurerm_iothub resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_iothub.md) Use the `azurerm_iothub` InSpec audit resource to test properties and configuration of an Azure Event Hub Namespace within a Resource Group. Azure REST API version ---------------------- This resource interacts with version `2018-04-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/iothub/iothubresource/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.11.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` and `resource_name` must be given as a parameter. ``` describe azurerm_iothub(resource_group: 'my-rg', resource_name 'my-iot-hub') do it { should exist } end ``` Examples -------- If an IoT Hub is referenced with a valid `Resource Group` and `Resource Name` ``` describe azurerm_iothub(resource_group: 'my-rg', resource_name 'my-iot-hub') do it { should exist } end ``` If an IoT Hub is referenced with an invalid `Resource Group` or `Resource Name` ``` describe azurerm_iothub(resource_group: 'invalid-rg', resource_name: 'i-dont-exist') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the IoT Hub belongs. * `resource_name` - The unique name of the IoT Hub. Attributes ---------- * `id` * `name` * `type` * `location` * `tags` * `etag` * `properties` * `sku` ### id Azure resource ID. ### name IoT Hub name, e.g. `my-iot-hub`. ### type The type of Resource, typically `Microsoft.Devices/IotHubs`. ### location Resource location, e.g. `eastus`. ### properties A collection of additional configuration properties related to the IoT Hub, e.g. `eventHubEndpoints,routing,messagingEndpoints`. For a full list of properties please take a look at the [Azure documentation](https://docs.microsoft.com/en-us/rest/api/iothub/iothubresource/get#definitions) ### tags Resource tags applied to the IoT Hub. ### etag The etag applied to the IoT Hub. ### sku SKU properties for the IoT Hub. Such as sku name, billing tier and capacity. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_iothub(resource_group: 'my-rg', resource_name 'my-iot-hub') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_iothub/azurerm_iothub_event_hub_consumer_group resource ===================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_iothub_event_hub_consumer_group.md) Use the `azurerm_iothub_event_hub_consumer_group` InSpec audit resource to test properties and configuration of an Azure IoT Hub Event Hub Consumer Group within a Resource Group. Azure REST API version ---------------------- This resource interacts with version `2018-04-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/iothub/iothubresource/geteventhubconsumergroup). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.11.0 of the inspec-azure resource pack. Syntax ------ The `resource_group`, `resource_name`, `event_hub_endpoint` and `consumer_group` must be given as a parameter. ``` describe azurerm_iothub_event_hub_consumer_group(resource_group: 'my-rg', resource_name 'my-iot-hub', event_hub_endpoint: 'myeventhub', consumer_group: 'my-consumer-group') do it { should exist } end ``` Examples -------- If an IoT Hub Event Hub Consumer Group is referenced with a valid `Resource Group`, `Resource Name`, `Event Hub Endpoint` and `Consumer Group` ``` describe azurerm_iothub_event_hub_consumer_group(resource_group: 'my-rg', resource_name 'my-iot-hub', event_hub_endpoint: 'myeventhub', consumer_group: 'my-consumer-group') do it { should exist } end ``` If an IoT Hub Event Hub Consumer Group is referenced with an invalid `Resource Group`, `Resource Name`, `Event Hub Endpoint` or `Consumer Group` ``` describe azurerm_iothub_event_hub_consumer_group(resource_group: 'invalid-rg', resource_name: 'invalid-resource', event_hub_endpoint: 'invalideventhub', consumer_group: 'invalid-consumer-group') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the IoT Hub belongs. * `resource_name` - The unique name of the IoT Hub. * `event_hub_endpoint` - The unique name of the IoT Hub Endpoint * `consumer_group` - The unique name of the IoI Hub Endpoint consumer group Attributes ---------- * `id` * `name` * `type` * `etag` * `properties` ### id Azure resource ID. ### name The Event Hub-compatible consumer group identifier, e.g. `my-consumer-group`. ### type The type of Resource, typically `Microsoft.Devices/IotHubs/EventHubEndpoints/ConsumerGroups`. ### properties A collection of additional configuration properties related to the IoT Hub Consumer Group, e.g. `created`. ### etag The etag applied to the IoT Hub Consumer Group. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_iothub_event_hub_consumer_group(resource_group: 'my-rg', resource_name 'my-iot-hub', event_hub_endpoint: 'myeventhub', consumer_group: 'my-consumer-group') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_iothub_event_hub_consumer_group/azurerm_key_vault_key resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_key_vault_key.md) Use the `azurerm_key_vault_key` InSpec audit resource to test properties and configuration of an Azure Key within a Vault. Azure REST API version ---------------------- This resource interacts with version `2016-10-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/keyvault/getkey/getkey). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.3.0 of the inspec-azure resource pack. Syntax ------ The `vault_name` and `key_name` must be given as a parameter. You may also specify a `key_version` - if no version is specified, the most recent version of the key will be used. ``` describe azurerm_key_vault_key('vault-101', 'secret-key') do its('key.kid') { should_not be_nil } its('attributes.enabled') { should eq true } end ``` Examples -------- If a Key Vault Key is referenced with a valid `Vault Name`, `Key Name` and `Key Version` ``` describe azurerm_key_vault_key('vault-101', 'secret-key', '7df9bf2c3b4347bab213ebe233f0e350') do it { should exist } its('key.kid') { should_not be_nil } its('attributes.enabled') { should eq true } end ``` If a Key Vault Key is referenced with an invalid `Vault Name` or `Key Name` ``` describe azurerm_key_vault_key('vault-101', 'incorrect-key') do it { should_not exist } end ``` Parameters ---------- * `vault_name` - The name of the Key Vault. * `key_name` - The name of the Key. * `key_version` (Optional) - The version of a Key, e.g. `7df9bf2c3b4347bab213ebe233f0e350`. Attributes ---------- * `attributes` * `key` * `managed` * `tags` ### attributes The key management attributes. ### key The JSON web key. ### managed True if the key’s lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. ### tags Resource tags applied to the Key. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_key_vault_key('vault-101', 'secret-key') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. Your Azure Key Vault should also have this Service Principal listed in it’s Access Policy with both `keys/get` and `keys/list` permissions. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_key_vault_key/azurerm_key_vault_keys resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_key_vault_keys.md) Use the `azurerm_key_vault_keys` InSpec audit resource to test properties and configuration of Azure Keys within Vaults. Azure REST API version ---------------------- This resource interacts with version `2016-10-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/keyvault/getkeys/getkeys). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.3.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_key_vault_keys` resource block returns all Keys within a Vault. ``` describe azurerm_key_vault_keys('my-vault') do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check Keys within a Vault ``` azurerm_key_vault_keys('my-vault').entries.each do |key| describe key do its('kid') { should_not be nil } its('attributes.enabled') { should eq true } end end ``` Filter Criteria --------------- All fields described in [Attributes](#attributes) can be used to filter. Below is an example using `managed`. ### managed Filters the results to include only those Keys which are not managed by the Vault. This is a boolean value. ``` describe azurerm_key_vault_keys('my-vault').where{ managed.eql?(false) } do it { should_not exist } end ``` Attributes ---------- * `attributes` * `kid` * `managed` * `tags` ### attributes The key management attributes. ### kid Key identifier. ### managed True if the key’s lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. ### tags Resource tags applied to the Key. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_key_vault_keys('my-vault') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. Your Azure Key Vault should also have this Service Principal listed in it’s Access Policy with `keys/list` permissions. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_key_vault_keys/azurerm_iothub_event_hub_consumer_groups resource ====================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_iothub_event_hub_consumer_groups.md) Use the `azurerm_iothub_event_hub_consumer_groups` InSpec audit resource to test properties and configuration of an Azure IoT Hub Event Hub Consumer Groups within a Resource Group. Azure REST API version ---------------------- This resource interacts with version `2018-04-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/iothub/iothubresource/geteventhubconsumergroup). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.11.0 of the inspec-azure resource pack. Syntax ------ The `resource_group`, `resource_name` and `event_hub_endpoint` must be given as a parameter. ``` describe azurerm_iothub_event_hub_consumer_groups(resource_group: 'my-rg', resource_name 'my-iot-hub', event_hub_endpoint: 'myeventhub') do its('names') { should include "my-consumer-group"} its('types') { should include 'Microsoft.Devices/IotHubs/EventHubEndpoints/ConsumerGroups' } end ``` Examples -------- If a IoT Hub Event Hub Consumer Groups is referenced with a valid `Resource Group`, `Resource Name` and `Event Hub Endpoint` ``` describe azurerm_iothub_event_hub_consumer_groups(resource_group: 'my-rg', resource_name 'my-iot-hub', event_hub_endpoint: 'myeventhub') do it { should exist } end ``` If a IoT Hub Event Hub Consumer Groups is referenced with an invalid `Resource Group`, `Resource Name` or `Event Hub Endpoint` ``` describe azurerm_iothub_event_hub_consumer_groups(resource_group: 'invalid-rg', resource_name: 'invalid-resource', event_hub_endpoint: 'invalideventhub') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the IoT Hub belongs. * `resource_name` - The unique name of the IoT Hub. * `event_hub_endpoint` - The unique name of the IoT Hub Endpoint Attributes ---------- * `ids` * `names` * `types` * `etag` * `properties` ### ids The Azure resource IDs. ### names The Event Hub-compatible consumer group names identifier. its(‘types’) { should include(`my-consumer-group-a`, `my-consumer-group-b`) } ### types The types of the Resources, typically `Microsoft.Devices/IotHubs/EventHubEndpoints/ConsumerGroups`. its(‘types’) { should include(`Microsoft.Devices/IotHubs/EventHubEndpoints/ConsumerGroups`) } ### properties A collection of additional configuration properties related to the IoT Hub Consumer Group, e.g. `created`. ### etags The etag applied to the IoT Hub Consumer Group. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_iothub_event_hub_consumer_group(resource_group: 'my-rg', resource_name 'my-iot-hub', event_hub_endpoint: 'myeventhub') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_iothub_event_hub_consumer_groups/azurerm_key_vault_secret resource ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_key_vault_secret.md) Use the `azurerm_key_vault_secret` InSpec audit resource to test properties and configuration of an Azure Secret within a Vault. Azure REST API version ---------------------- This resource interacts with version `2016-10-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/keyvault/getsecret/getsecret). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.3.0 of the inspec-azure resource pack. Syntax ------ The `vault_name` and `secret_name` must be given as a parameter. You may also specify a `secret_version` - if no version is specified, the most recent version of the secret will be used. ``` describe azurerm_key_vault_secret('vault-101', 'secret-101') do it { should exist } its('value') { should_not be_nil } end ``` Examples -------- If a Key Vault Secret is referenced with a valid `Vault Name`, `Secret Name` and `Secret Version` ``` describe azurerm_key_vault_secret('vault-101', 'secret-101', '7df9bf2c3b4347bab213ebe233f0e350') do its('value') { should_not be_nil } end ``` If a Key Vault Secret is referenced with an invalid `Vault Name` or `Secret Name` ``` describe azurerm_key_vault_secret('vault-101', 'incorrect-secret') do it { should_not exist } end ``` Parameters ---------- * `vault_name` - The name of the Key Vault. * `secret_name` - The name of the Key. * `secret_version` (Optional) - The version of a Key, e.g. `7df9bf2c3b4347bab213ebe233f0e350`. Attributes ---------- * `id` * `value` * `attributes` * `kid` * `content_type` * `managed` * `tags` ### id The secret id. ### value The secret value. ### attributes The secret management attributes. ### kid If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV certificate. ### content_type The content type of the secret. ### managed True if the secret’s lifetime is managed by key vault. If this is a secret backing a certificate, then managed will be true. ### tags Resource tags applied to the Secret. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_key_vault_secret('vault-101', 'secret') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. Your Azure Key Vault should also have this Service Principal listed in it’s Access Policy with both `secret/get` and `secret/list` permissions. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_key_vault_secret/azurerm_key_vaults resource ============================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_key_vaults.md) Use the `azurerm_key_vaults` InSpec audit resource to test properties and configuration of Azure Key Vaults. Azure REST API version ---------------------- This resource interacts with version `2016-10-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/keyvault/vaults/listbyresourcegroup). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.2.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_key_vaults` resource block returns all Azure Key Vaults within a Resource Group. ``` describe azurerm_key_vaults(resource_group: 'my-rg') do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check Key Vaults are present ``` describe azurerm_key_vaults(resource_group: 'my-rg') do it { should exist } its('names') { should include 'vault-101' } end ``` Filter Criteria --------------- ### names Filters the results to include only those vaults which match the given name. This is a string value. ``` describe azurerm_key_vaults(resource_group: 'my-rg').where{ name.eql?('vault-101') } do it { should exist } end ``` ### location Filters the results to include only those vaults which reside in a given location. This is a string value. ``` describe azurerm_key_vaults(resource_group: 'my-rg').where{ location.eql?('eastus') } do it { should exist } end ``` Attributes ---------- * `id` * `name` * `location` * `type` * `tags` * `properties` ### ids Azure resource ID. ### names Key Vault name, e.g. `vault-101`. ``` its('names') { should include 'vault-101' } ``` ### locations Resource location, e.g. `eastus`. ``` its('locations') { should_not include 'eastus' } ``` ### type The type of Resource, typically `Microsoft.KeyVault/vaults`. ### tag Resource tags applied to the Key Vault. ### properties A collection of additional configuration properties related to the Key Vault, e.g. `vaultUri`. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_key_vaults(resource_group: 'my-rg') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_key_vaults/azurerm_management_group resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_management_group.md) Use the `azurerm_management_group` InSpec audit resource to test properties related to a management group. Azure REST API version ---------------------- This resource interacts with version `2018-03-01-preview` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/resources/managementgroups/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ The `group_id` must be given as a parameter. ``` describe azurerm_management_group(group_id: 'MyGroupId') do ... end ``` Optionally, you may use the `expand`, `recurse` and/or `filter` parameters. ``` describe azurerm_management_group(group_id: 'MyGroupId', expand: 'children', recurse: true) do ... end describe azurerm_management_group(group_id: 'MyGroupId', expand: 'children', recurse: true, filter: 'children.childType ne Subscription') do ... end ``` Examples -------- describe azurerm_management_group(group_id: ‘20000000-0000-0000-0000-000000000000’, expand: ‘children’, recurse: true) do it { should exist } its(‘id’) { should eq ‘/providers/Microsoft.Management/managementGroups/20000000-0000-0000-0000-000000000000’ } its(‘type’) { should eq ‘/providers/Microsoft.Management/managementGroups’ } its(‘name’) { should eq ‘20000000-0000-0000-0000-000000000000’ } its(‘display_name’) { should eq ‘Management Group Display Name One’ } its(‘tenant_id’) { should eq ‘56700000-0000-0000-0000-000000000000’ } its(‘parent_name’) { should eq ‘10000000-0000-0000-0000-000000000000’ } its(‘parent_id’) { should eq ‘/providers/Microsoft.Management/managementGroups/10000000-0000-0000-0000-000000000000’ } its(‘parent_display_name’) { should eq ‘Tenant Root Group’ } its(‘children_display_names’) { should include(‘Management Group Display Name Child’) } its(‘children_ids’) { should include('/providers/Microsoft.Management/managementGroups/40000000-0000-0000-0000-000000000000') } its(‘children_names’) { should include(‘40000000-0000-0000-0000-000000000000’) } its(‘children_types’) { should include('/providers/Microsoft.Management/managementGroups') } end describe azurerm_management_group(group_id: ‘40000000-0000-0000-0000-000000000000’, expand: ‘children’, recurse: true) do it { should exist } its(‘id’) { should eq ‘/providers/Microsoft.Management/managementGroups/40000000-0000-0000-0000-000000000000’ } its(‘type’) { should eq ‘/providers/Microsoft.Management/managementGroups’ } its(‘name’) { should eq ‘40000000-0000-0000-0000-000000000000’ } its(‘display_name’) { should eq ‘Management Group Display Name Child’ } its(‘tenant_id’) { should eq ‘56700000-0000-0000-0000-000000000000’ } its(‘parent_name’) { should eq ‘20000000-0000-0000-0000-000000000000’ } its(‘parent_id’) { should eq ‘/providers/Microsoft.Management/managementGroups/20000000-0000-0000-0000-000000000000’ } its(‘parent_display_name’) { should eq ‘Management Group Display Name One’ } its(‘children_display_names’) { should eq [] } its(‘children_ids’) { should eq [] } its(‘children_names’) { should eq [] } its(‘children_types’) { should eq [] } end Parameters ---------- * `group_id` * `expand` * `recurse` * `filter` Parameter Examples ------------------ ### group_id (required) Defines the group id of the management group that you wish to test. ``` describe azurerm_management_group(group_id: 'MyGroupId') do ... end ``` ### expand (optional) Query string parameter allows clients to request inclusion of children so that you can test them. ``` describe azurerm_management_group(group_id: 'MyGroupId', expand: 'children') do ... end ``` ### recurse (optional) Setting this to true allows clients to request inclusion of entire hierarchy in the response payload. Note that `expand: 'children'` must be passed up if `recurse` is set to `true`. ``` describe azurerm_management_group(group_id: 'MyGroupId', expand: 'children', recurse: true) do ... end ``` ### filter (optional) A filter which allows the exclusion of subscriptions from results (i.e. `filter: 'children.childType ne Subscription'`) ``` describe azurerm_management_group(group_id: 'MyGroupId', expand: 'children', recurse: true, filter: 'children.childType ne Subscription') do ... end ``` Attributes ---------- * `id` * `type` * `name` * `tenant_id` * `parent_name` * `parent_id` * `parent_display_name` * `children_display_names` * `children_ids` * `children_names` * `children_roles` * `children_types` ### id The management group id. ``` its('id') { should eq('/providers/Microsoft.Management/managementGroups/MyGroupId') } ``` id will be in format: ``` '/providers/Microsoft.Management/managementGroups/<GROUP_ID>' ``` ### type The management group type. ``` its('type') { should eq('/providers/Microsoft.Management/managementGroups') } ``` ### name The management group name. ``` its('name') { should eq('MyGroupName') } ``` ### tenant_id The management groups tenant id. ``` its('tenant_id') { should eq('00000000-0000-0000-0000-000000000000') } ``` ### parent_name The management group parent name. ``` its('parent_name') { should eq('MyGroupsParentName') } ``` ### parent_id The management group parent id ``` its('parent_id') { should eq('/providers/Microsoft.Management/managementGroups/MyGroupsParentId') } ``` parent_id will be in format: ``` '/providers/Microsoft.Management/managementGroups/<GROUP_ID>' ``` ### parent_display_name The management groups parent display name ``` its('parent_display_name') { should eq('My Groups Parent Display Name!') } ``` ### children_display_names The management group children display names. ``` its('children_display_names') { should include('I am a child of the group!') } ``` ### children_ids The management group children ids. ``` its('children_ids') { should include('/providers/Microsoft.Management/managementGroups/a-child-name') } ``` ### children_names The management group children names. ``` its('children_names') { should include('a-child-name') } ``` ### children_roles The management group children roles. ``` its('children_roles') { should include('/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635') } ``` ### children_types The management group ``` its('children_types') { should include('') } ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` # If a management group is found it will exist describe azurerm_management_group(groupd_id: 'MyGroupId') do it { should exist } end # management groups that aren't found will not exist describe azurerm_management_group(groupd_id: 'DoesNotExist') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the Tenant Root Group or the specific management group(s) you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_management_group/azurerm_load_balancer resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_load_balancer.md) Use the `azurerm_load_balancer` InSpec audit resource to test properties and configuration of an Azure Load Balancer. Azure REST API version ---------------------- This resource interacts with version `2018-11-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/load-balancer/loadbalancers/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.7.2 of the inspec-azure resource pack. Syntax ------ The `resource_group` and `loadbalancer_name` must be given as a parameter. ``` describe azurerm_load_balancer(resource_group: 'inspec-resource-group-9', loadbalancer_name: 'example_lb') do it { should exist } end ``` Examples -------- If a Load Balancer is referenced with a valid `Resource Group` and `Load balancer Name` ``` describe azurerm_load_balancer(resource_group: 'my-rg', loadbalancer_name: 'lb-1') do it { should exist } end ``` If a Load Balancer is referenced with an invalid `Resource Group` or `Load balancer Name` ``` describe azurerm_load_balancer(resource_group: 'invalid-rg', loadbalancer_name: 'i-dont-exist') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the Load Balancer belongs. * `loadbalancer_name` - The unique name of the Load balancer. Attributes ---------- * `id` * `name` * `sku` * `location` * `properties` * `tags` * `type` ### id Azure resource ID. ### name Load Balancer name, e.g. `lb-1`. ### sku SKU of load balancer. This is billing information related properties of a load balancer. ### location Resource location, e.g. `eastus`. ### properties A collection of additional configuration properties related to the Load balancer, e.g. `loadBalancingRules`. ### tags Resource tags applied to the Load balancer. ### type The type of Resource, typically `Microsoft.Network/loadBalancers`. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_load_balancer(resource_group: 'my-rg', loadbalancer_name: 'lb-1') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_load_balancer/azurerm_load_balancers resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_load_balancers.md) Use the `azurerm_load_balancers` InSpec audit resource to test properties and configuration of Azure Load Balancers. Azure REST API version ---------------------- This resource interacts with version `2018-11-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/load-balancer/loadbalancers/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.7.2 of the inspec-azure resource pack. Syntax ------ An `azurerm_load_balancers` resource block returns all Azure Load Balancers, either within a Resource Group (if provided), or within an entire Subscription. ``` describe azurerm_load_balancer do ... end ``` or ``` describe azurerm_load_balancers(resource_group: 'my-rg') do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check Load balancers are present ``` describe azurerm_load_balancers do it { should exist } its('names') { should include 'my-lb' } end ``` Filter Criteria --------------- ### names Filters the results to include only those load balancers which match the given name. This is a string value. ``` describe azurerm_load_balancers.where{ name.eql?('production-lb-5') } do it { should exist } end ``` ### location Filters the results to include only those load balancers which reside in a given location. This is a string value. ``` describe azurerm_load_balancers.where{ location.eql?('eastus') } do it { should exist } end ``` Attributes ---------- * `id` * `name` * `sku` * `location` * `properties` * `tags` * `type` ### ids Azure resource ID. ### names Load balancer name, e.g. `my-lb`. ``` its('names') { should include 'my-lb' } ``` ### SKU SKU of load balancer. This is metadata used for the Azure portal experience. ### locations Resource location, e.g. `eastus`. ``` its('locations') { should_not include 'eastus' } ``` ### properties A collection of additional configuration properties related to the Load Balancer, e.g. `loadBalancingRules`. ### tag Resource tags applied to the Load balancer. ### type The type of Resource, typically `Microsoft.Network/loadBalancers`. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_load_balancers do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_load_balancers/azurerm_key_vault_secrets resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_key_vault_secrets.md) Use the `azurerm_key_vault_secrets` InSpec audit resource to test properties and configuration of Azure Secrets within Vaults. Azure REST API version ---------------------- This resource interacts with version `2016-10-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/keyvault/getsecrets/getsecrets). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: -name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.3.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_key_vault_secrets` resource block returns all Secrets within a Vault. ``` describe azurerm_key_vault_secrets('my-vault') do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check Keys within a Vault ``` azurerm_key_vault_secrets('my-vault').entries.each do |secret| describe secret do its('id') { should_not be nil } its('attributes.exp') { should_not be_nil } end end ``` Filter Criteria --------------- All fields described in [Attributes](#attributes) can be used to filter. Below is an example using `managed`. ### managed Filters the results to include only those Secrets which are not managed by the Vault. This is a boolean value. ``` describe azurerm_key_vault_secrets('my-vault').where{ managed.eql?(false) } do it { should_not exist } end ``` Attributes ---------- * `id` * `attributes` * `contentType` * `managed` * `tags` ### id Secret identifier. ### attributes The secret management attributes. ### contentType Type of the secret value such as a password. ### managed True if the secret’s lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. ### tags Resource tags applied to the Key. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_key_vault_secrets('my-vault') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. Your Azure Key Vault should also have this Service Principal listed in it’s Access Policy with `secrets/list` permissions. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_key_vault_secrets/azurerm_management_groups resource ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_management_groups.md) Use the `azurerm_management_groups` InSpec audit resource to test properties related to management groups. Azure REST API version ---------------------- This resource interacts with version `2018-03-01-preview` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/resources/managementgroups/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ ``` describe azurerm_management_groups do ... end ``` Examples -------- ### Check Attributes of All Management Groups ``` describe azurerm_management_groups do its('ids') { should include "/providers/Microsoft.Management/managementGroups/mg_id" } its('names') { should include "parent_mg" } its('types') { should include '/providers/Microsoft.Management/managementGroups' } end ``` ### Filter Results to Inspect the Properties of Specific Management Group ``` describe azurerm_management_groups.where(name: 'mg_parent').entries.first do its('properties') { should have_attributes(:tenantId => tenant_id, :displayName => parent_dn)} end ``` Parameters ---------- N/A Attributes ---------- * `ids` * `types` * `names` * `properties` ### ids The management group ids. ### types The management group types. ### names The management group names. ### properties Additional properties relating to management groups. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has no special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_management_groups(name: 'my-mg') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `Contributor` or `Management Group Contributor` role on the Tenant Root Group or the specific management group(s) you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_management_groups/azurerm_locks resource ======================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_locks.md) Use the `azurerm_locks` InSpec audit resource to test properties of some or all Azure Resource Locks. Azure REST API version ---------------------- This resource interacts with version `2016-09-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/resources/managementlocks/listatresourcelevel). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.3.8 of the inspec-azure resource pack. Syntax ------ An `azurerm_locks` resource block returns all Locks on a given Resource. ``` describe azurerm_locks(resource_group: 'rg', resource_name: 'my-vm', resource_type: 'Microsoft.Compute/virtualMachines') do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Ensure a Lock exists ``` describe azurerm_locks(resource_group: 'my-rg', resource_name: 'my-vm', resource_type: 'Microsoft.Compute/virtualMachines') do it { should exist } end ``` Filter Criteria --------------- * `ids` * `names` * `properties` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_locks/azurerm_monitor_activity_log_alert resource =============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_monitor_activity_log_alert.md) Use the `azurerm_monitor_activity_log_alert` InSpec audit resource to test properties of an Azure Monitor Activity Log Alert. Azure REST API version ---------------------- This resource interacts with version `2017-04-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/monitor/activitylogalerts/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_monitor_activity_log_alert` resource block identifies an Activity Log Alert by name and resource group. ``` describe azurerm_monitor_activity_log_alert(resource_group: 'example', name: 'AlertName') do ... end ``` Examples -------- ### Test that an example resource has an Activity Log Alert ``` describe azurerm_monitor_activity_log_alert(resource_group: 'example', name: 'AlertName') do it { should exist } end ``` ### Test an example resource has an Activity Log Alert with the correct operation ``` describe azurerm_monitor_activity_log_alert(resource_group: 'example', name: 'AlertName') do its('operations') { should include 'Microsoft.Authorization/policyAssignments/write' } end ``` Parameters ---------- * `name` * `resource_group` Parameter Examples ------------------ The resource group as well as the Activity Log Alert name. ``` describe azurerm_monitor_activity_log_alert(resource_group: 'example', name: 'AlertName') do its('operations') { should include 'Microsoft.Authorization/policyAssignments/write' } end ``` Attributes ---------- For more information on these attributes see [Azure REST API documentation](https://docs.microsoft.com/en-us/rest/api/monitor/activitylogalerts/get#activitylogalertresource). * `id` * `name` * `operations` * `properties` * `conditions` ### id The Activity Log Alert’s id. ``` its('id') { should eq(id) } ``` ### name The Activity Log Alert’s name. ``` its('name') { should eq(name) } ``` ### operations The operations collection can be checked for the presence or absence of a given operation string. ``` its('operations') { should include 'Microsoft.Authorization/policyAssignments/write' } ``` ### properties.actions A list of actions that are executed when the condition is met. ### properties.description Description of this alert. ``` its('properties.description') { should eq 'Alert description' } ``` ### properties.enabled Indicates if this alert is enabled or not (`true`|`false`). ``` its('properties.enabled') { should be_true } ``` ### properties.scopes List of resources this alert applies to. There must be at least one item in this list. ``` its('properties.scopes') { should include 'subscriptions/SUBSCRIPTION_ID' } ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'AlertName' to always exist describe azurerm_monitor_activity_log_alert(resource_group: 'example', name: 'AlertName') do it { should exist } end # If we expect 'OtherAlertName' to never exist describe azurerm_monitor_activity_log_alert(resource_group: 'example', name: 'OtherAlertName') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_monitor_activity_log_alert/azurerm_monitor_activity_log_alerts resource ================================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_monitor_activity_log_alerts.md) Use the `azurerm_monitor_activity_log_alerts` InSpec audit resource to verify that an Activity Log Alert exists. Azure REST API version ---------------------- This resource interacts with version `2017-04-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/monitor/activitylogalerts/listbysubscriptionid). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_monitor_activity_log_alerts` resource block identifies Activity Log Alerts by name. ``` describe azurerm_monitor_activity_log_alerts do ... end ``` Examples -------- ### Test that an example resource has an Activity Log Alert ``` describe azurerm_monitor_activity_log_alerts do its('names') { should include('ExampleLogAlert') } end ``` Attributes ---------- * `names` ### names The name of the Activity Log Alert ``` its('names') { should include('ExampleLogAlert') } ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'ExampleLogAlert' to exist describe azurerm_monitor_activity_log_alerts do it { should exist } end # If we do not expect 'ExampleLogAlert' to exist describe azurerm_monitor_activity_log_alerts do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_monitor_activity_log_alerts/azurerm_monitor_log_profile resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_monitor_log_profile.md) Use the `azurerm_monitor_log_profile` InSpec audit resource to test properties of an Azure Monitor Log Profile. Azure REST API version ---------------------- This resource interacts with version `2016-03-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/monitor/logprofiles/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_monitor_log_profile` resource block identifies a Log Profile by name. ``` describe azurerm_monitor_log_profile(name: 'default') do ... end ``` Examples -------- ### Test that a Log Profile exists ``` describe azurerm_monitor_log_profile(name: 'default') do it { should exist } end ``` ### Test that Log Profile retention is enabled ``` describe azurerm_monitor_log_profile(name: 'default') do its('retention_enabled') { should be true } end ``` Parameters ---------- * `name` Parameter Examples ------------------ The name of the Log Profile. ``` describe azurerm_monitor_log_profile(name: 'default') do it { should exist } end ``` Attributes ---------- * `retention_enabled` * `retention_days` ### retention_enabled Determine if retention is enabled ``` its('retention_enabled') { should be true } ``` ### retention_days Determine number of days retention is enabled for ``` its('retention_days') { should eq(365) } ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'default' to exist describe azurerm_monitor_log_profile(name: 'default') do it { should exist } end # If we expect 'default' to not exist describe azurerm_monitor_log_profile(name: 'default') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_monitor_log_profile/azurerm_monitor_log_profiles resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_monitor_log_profiles.md) Use the `azurerm_monitor_log_profiles` InSpec audit resource to verify that a Log Profile exists. Azure REST API version ---------------------- This resource interacts with version `2016-03-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/monitor/logprofiles/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_monitor_log_profiles` resource block identifies a Log Profile by name. ``` describe azurerm_monitor_log_profiles do ... end ``` Examples -------- ### Test that an example resource has a Log Profile ``` describe azurerm_monitor_log_profiles do its('names') { should include('ExampleProfile') } end ``` Attributes ---------- * `names` ### names The name of the Log Profile ``` its('names') { should include('ExampleProfile') } ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'ExampleProfile' to exist describe azurerm_monitor_log_profiles do its('names') { should include('ExampleProfile') } end # If we expect 'ExampleProfile' to not exist describe azurerm_monitor_log_profiles do its('names') { should_not include('ExampleProfile') } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_monitor_log_profiles/azurerm_mysql_database resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_mysql_database.md) Use the `azurerm_mysql_database` InSpec audit resource to test properties and configuration of an Azure MySQL Database on a MySQL Server. Azure REST API version ---------------------- This resource interacts with version `2017-12-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/mysql/databases/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.6.0 of the inspec-azure resource pack. Syntax ------ The `resource_group`, `server_name` and `database_name` must be given as a parameter. ``` describe azurerm_mysql_database(resource_group: 'inspec-rg', server_name: 'customer_server', database_name: 'order-db') do it { should exist } end ``` Examples -------- If a MySQL Database is referenced with a valid `Resource Group`, `Server Name` and `Database name` ``` describe azurerm_mysql_database(resource_group: 'inspec-rg', server_name: 'customer_server', database_name: 'order-db') do it { should exist } its('name') { should be 'order-db' } end ``` If a MySQL Database is referenced with an invalid `Resource Group`, `Server Name` or `Database Name` ``` describe azurerm_mysql_database(resource_group: 'inspec-rg', server_name: 'customer_server', database_name: 'invalid-db-name') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the MySQL Server belongs. * `server_name` - The unique name of the MySQL Server. * `database_name` - The unique name of the MySQL Database. Attributes ---------- * `id` * `name` * `type` * `properties` ### id Azure resource ID. ### name SQL Server name, e.g. `customer-database`. ### type The type of Resource, typically `Microsoft.DBforMySQL/servers/databases`. ### properties A collection of additional configuration properties related to the MySQL Database, e.g. `collation`. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_mysql_database(resource_group: 'my-rg', server_name: 'server-name-1', database_name: 'customer-db') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_mysql_database/azurerm_mysql_server resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_mysql_server.md) Use the `azurerm_mysql_server` InSpec audit resource to test properties and configuration of an Azure MySQL Server. Azure REST API version ---------------------- This resource interacts with version `2017-12-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/mysql/databases/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.6.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` and `server_name` must be given as a parameter. ``` describe azurerm_mysql_server(resource_group: 'inspec-resource-group-9', server_name: 'example_server') do it { should exist } end ``` Examples -------- If a SQL Server is referenced with a valid `Resource Group` and `Server Name` ``` describe azurerm_sql_server(resource_group: 'my-rg', server_name: 'sql-server-1') do it { should exist } end ``` If a SQL Server is referenced with an invalid `Resource Group` or `Server Name` ``` describe azurerm_sql_server(resource_group: 'invalid-rg', server_name: 'i-dont-exist') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the SQL Server belongs. * `server_name` - The unique name of the SQL Server. Attributes ---------- * `id` * `name` * `sku` * `location` * `properties` * `tags` * `type` ### id Azure resource ID. ### name MySQL Server name, e.g. `my-sql-server`. ### sku SKU of mysql server. This is billing information related properties of a server. ### location Resource location, e.g. `eastus`. ### properties A collection of additional configuration properties related to the MySQL Server, e.g. `administratorLogin`. ### tags Resource tags applied to the MySQL Server. ### type The type of Resource, typically `Microsoft.DBforMySQL/servers`. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_mysql_server(resource_group: 'my-rg', server_name: 'server-name-1') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_mysql_server/azurerm_mysql_servers resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_mysql_servers.md) Use the `azurerm_mysql_servers` InSpec audit resource to test properties and configuration of multiple Azure MySQL Servers. Azure REST API version ---------------------- This resource interacts with version `2017-12-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/mysql/servers/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.6.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_mysql_servers` resource block returns all Azure MySQL Servers, either within a Resource Group (if provided), or within an entire Subscription. ``` describe azurerm_mysql_servers do ... end ``` or ``` describe azurerm_mysql_servers(resource_group: 'my-rg') do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check SQL Servers are present ``` describe azurerm_mysql_servers do it { should exist } its('names') { should include 'my-server-name' } end ``` Filter Criteria --------------- ### names Filters the results to include only those servers which match the given name. This is a string value. ``` describe azurerm_mysql_servers.where{ name.eql?('production-server-5') } do it { should exist } end ``` ### location Filters the results to include only those servers which reside in a given location. This is a string value. ``` describe azurerm_mysql_servers.where{ location.eql?('eastus') } do it { should exist } end ``` Attributes ---------- * `id` * `name` * `sku` * `location` * `properties` * `tags` * `type` ### ids Azure resource ID. ### names SQL Server name, e.g. `my-sql-server`. ``` its('names') { should include 'my-sql-database' } ``` ### sku SKU of mysql server. This is billing information related properties of a server. ### locations Resource location, e.g. `eastus`. ``` its('locations') { should_not include 'eastus' } ``` ### properties A collection of additional configuration properties related to the MySQL Server, e.g. `administratorLogin`. ### tag Resource tags applied to the MySQL Server. ### type The type of Resource, typically `Microsoft.DBforMySQL/servers`. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_mysql_servers do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_mysql_servers/azurerm_mysql_databases resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_mysql_databases.md) Use the `azurerm_mysql_databases` InSpec audit resource to test properties and configuration of Azure MySQL Databases. Azure REST API version ---------------------- This resource interacts with version `2017-12-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/mysql/databases/listbyserver). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.6.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_mysql_databases` resource block returns all MySQL Databases on a MySQL Server, within a Rsource Group. ``` describe azurerm_mysql_databases(resource_group: ..., server_name: ...) do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check MySQL Databases are present ``` describe azurerm_mysql_databases(resource_group: 'resource-group-1', server_name: 'production') do it { should exist } its('names') { should include 'my-database-name' } end ``` Filter Criteria --------------- * `azure_mysql_databases` resources are filterable on all available properties. Below are some examples. ### names Filters the results to include only those databases that match the given name. This is a string value. ``` describe azurerm_mysql_databases(resource_group: 'rg', server_name: 'server').where{ name.eql?('production-database') } do it { should exist } end ``` ### location Filters the results to include only those resource groups that reside in a given location. This is a string value. ``` describe azurerm_mysql_databases(resource_group: 'rg', server_name: 'server').where{ location.eql?('eastus') } do it { should exist } end ``` Attributes ---------- * `id` * `name` * `type` * `properties` ### ids Azure resource ID. ### names SQL Database name, e.g. `my-sql-database`. ``` its('names') { should include 'my-sql-database' } ``` ### type The type of Resource, typically `Microsoft.Sql/servers/databases`. ### properties A collection of additional configuration properties related to the MySQL Database, e.g. `collation`. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_mysql_databases do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_mysql_databases/azurerm_network_interface resource ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_network_interface.md) Use the `azurerm_network_interface` InSpec audit resource to test properties and configuration of Azure Network Interface. Azure REST API version ---------------------- This resource interacts with version `2018-11-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/virtualnetwork/networkinterface(preview)/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.7.2 of the inspec-azure resource pack. Syntax ------ The `resource_group` and `name` must be given as a parameter. ``` describe azurerm_network_interface(resource_group: 'inspec-resource-group-9',name: 'example-nic-name') do it { should exist } end ``` Examples -------- If a Network Interface is referenced with a valid `Resource Group` and `Name` ``` describe azurerm_network_interface(resource_group: 'my-rg', name: 'name-nic') do it { should exist } end ``` If a Network Interface is referenced with an invalid `Resource Group` or `Name` ``` describe azurerm_network_interface(resource_group: 'invalid-rg', name: 'i-dont-exist') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the Network Interface belongs. * `name` - The unique name of the Network interface. Attributes ---------- * `id` * `name` * `location` * `properties` * `tags` * `type` * `private_ip` * `public_ip` ### id Azure resource ID. ### name Network interface name, e.g. `vm-nic`. ### location Resource location, e.g. `eastus`. ### properties A collection of additional configuration properties related to the Network interface, e.g. `ipConfigurations`. ### tags Resource tags applied to the Network Interface. ### type The type of Resource, typically `Microsoft.Network/networkInterfaces`. ### private_ip The Network interface private IP. ### public_ip The Network interface public IP. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_network_interface(resource_group: 'my-rg', name: 'nic-name-1') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_network_interface/azurerm_network_interfaces resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_network_interfaces.md) Use the `azurerm_network_interfaces` InSpec audit resource to test properties and configuration of Azure Network interfaces. Azure REST API version ---------------------- This resource interacts with version `2018-11-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/virtualnetwork/networkinterface(preview)/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.7.2 of the inspec-azure resource pack. Syntax ------ An `azurerm_network_interfaces` resource block returns all Azure Network Interfaces, either within a Resource Group (if provided), or within an entire Subscription. ``` describe azurerm_network_interfaces do ... end ``` or ``` describe azurerm_network_interfaces(resource_group: 'my-rg') do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check Network interfaces are present ``` describe azurerm_network_interfaces do it { should exist } its('names') { should include 'my-network-interface-name' } end ``` Filter Criteria --------------- ### names Filters the results to include only those network interfaces which match the given name. This is a string value. ``` describe azurerm_network_interfaces.where{ name.eql?('network-interface-5') } do it { should exist } end ``` ### location Filters the results to include only those servers which reside in a given location. This is a string value. ``` describe azurerm_network_interfaces.where{ location.eql?('eastus') } do it { should exist } end ``` Attributes ---------- * `id` * `name` * `location` * `properties` * `tags` * `type` ### ids Azure resource ID. ### names Network interface name, e.g. `nic-name`. ``` its('names') { should include 'nic-name' } ``` ### locations Resource location, e.g. `eastus`. ``` its('locations') { should_not include 'eastus' } ``` ### properties A collection of additional configuration properties related to the Network interface, e.g. `ipConfigurations`. ### tag Resource tags applied to the Network interface. ### type The type of Resource, typically `Microsoft.Network/networkInterfaces`. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_network_interfaces do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_network_interfaces/azurerm_network_security_group resource ========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_network_security_group.md) Use the `azurerm_network_security_group` InSpec audit resource to test properties of an Azure Network Security Group. Azure REST API version ---------------------- This resource interacts with version `2018-02-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/virtualnetwork/networksecuritygroups/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_network_security_group` resource block identifies a Network Security Group by name and Resource Group. ``` describe azurerm_network_security_group(resource_group: 'example', name: 'GroupName') do ... end ``` Examples -------- ### Test that an example Resource Group has the specified Network Security Group ``` describe azurerm_network_security_group(resource_group: 'example', name: 'GroupName') do it { should exist } end ``` ### Test that an example Resource Group has a Network Security Group that allows SSH from the internet ``` describe azurerm_network_security_group(resource_group: 'example', name: 'GroupName') do it { should allow_ssh_from_internet } end ``` Parameters ---------- * `name` * `resource_group` Parameter Examples ------------------ The Resource Group as well as the Network Security Group name. ``` describe azurerm_network_security_group(resource_group: 'example', name: 'GroupName') do it { should allow_rdp_from_internet } end ``` Attributes ---------- * `security_rules` * `default_security_rules` * `allow_ssh_from_internet` * `allow_rdp_from_internet` * `properties` ### security_rules The security_rules property contains the set of Security Rules. ``` its('security_rules') { should_not be_empty } ``` ### default_security_rules The default_security_rules property contains the set of Default Security Rules. ``` its('default_security_rules') { should_not be_empty } ``` ### allow_ssh_from_internet The allow_ssh_from_internet property contains a boolean value determined by analyzing the Security Rules and Default Security Rules for unrestricted SSH access. ``` it { should_not allow_ssh_from_internet } ``` ### allow_rdp_from_internet The allow_rdp_from_internet property contains a boolean value determined by analyzing the Security Rules and Default Security Rules for unrestricted RDP access. ``` it { should_not allow_rdp_from_internet } ``` ### allow\port_from_internet The allow_port_from_internet property contains a boolean value determined by analyzing the Security Rules and Default Security Rules for unrestricted access to a specified port. ``` it { should_not allow_port_from_internet('443') } ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'GroupName' to always exist describe azurerm_network_security_group(resource_group: 'example', name: 'GroupName') do it { should exist } end # If we expect 'EmptyGroupName' to never exist describe azurerm_network_security_group(resource_group: 'example', name: 'EmptyGroupName') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_network_security_group/azurerm_postgresql_database resource ====================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_postgresql_database.md) Use the `azurerm_postgresql_database` InSpec audit resource to test properties and configuration of an Azure PostgreSQL Database on a PostgreSQL Server. Azure REST API version ---------------------- This resource interacts with version `2017-12-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/postgresql/databases/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.7.0 of the inspec-azure resource pack. Syntax ------ The `resource_group`, `server_name` and `database_name` must be given as a parameter. ``` describe azurerm_postgresql_database(resource_group: 'inspec-rg', server_name: 'customer_server', database_name: 'order-db') do it { should exist } end ``` Examples -------- If a PostgreSQL Database is referenced with a valid `Resource Group`, `Server Name` and `Database name` ``` describe azurerm_postgresql_database(resource_group: 'inspec-rg', server_name: 'customer_server', database_name: 'order-db') do it { should exist } its('name') { should be 'order-db' } end ``` If a PostgreSQL Database is referenced with an invalid `Resource Group`, `Server Name` or `Database Name` ``` describe azurerm_postgresql_database(resource_group: 'inspec-rg', server_name: 'customer_server', database_name: 'invalid-db-name') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the PostgreSQL Server belongs. * `server_name` - The unique name of the PostgreSQL Server. * `database_name` - The unique name of the PostgreSQL Database. Attributes ---------- * `id` * `name` * `type` * `properties` ### id Azure resource ID. ### name SQL Server name, e.g. `customer-database`. ### type The type of Resource, typically `Microsoft.DBforPostgreSQL/servers/databases`. ### properties A collection of additional configuration properties related to the PostgreSQL Database, e.g. `collation`. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_postgresql_database(resource_group: 'my-rg', server_name: 'server-name-1', database_name: 'customer-db') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_postgresql_database/azurerm_network_security_groups resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_network_security_groups.md) Use the `azurerm_network_security_groups` InSpec audit resource to enumerate Network Security Groups. Azure REST API version ---------------------- This resource interacts with version `2018-02-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/virtualnetwork/networksecuritygroups/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_network_security_groups` resource block identifies Network Security Groups by Resource Group. ``` describe azurerm_network_security_groups(resource_group: 'ExampleGroup') do ... end ``` Examples -------- ### Test that an example Resource Group has the named Network Security Group ``` describe azurerm_network_security_groups(resource_group: 'ExampleGroup') do its('names') { should include('ExampleNetworkSecurityGroup') } end ``` Attributes ---------- * `names` ### names The name of the Network Security Group ``` its('names') { should include('ExampleNetworkSecurityGroup') } ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'ExampleGroup' Resource Group to have Network Security Groups describe azurerm_network_security_groups(resource_group: 'ExampleGroup') do it { should exist } end # If we expect 'EmptyExampleGroup' Resource Group to not have Network Security Groups describe azurerm_network_security_groups(resource_group: 'EmptyExampleGroup') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_network_security_groups/azurerm_network_watchers resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_network_watchers.md) Use the `azurerm_network_watchers` InSpec audit resource to verify that a Network Watcher exists. Azure REST API version ---------------------- This resource interacts with version `2018-02-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/network-watcher/networkwatchers/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_network_watchers` resource block identifies Network Watchers by Resource Group. ``` describe azurerm_network_watchers(resource_group: 'example_group') do ... end ``` Examples -------- ### Test that an example Resource Group has the named Network Watcher ``` describe azurerm_network_watchers(resource_group: 'example_group') do its('names') { should include('ExampleNetworkWatcher') } end ``` Attributes ---------- * `names` ### names The name of the Network Watcher ``` its('names') { should include('ExampleNetworkWatcher') } ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'ExampleGroup' Resource Group to have Network Watchers describe azurerm_network_watchers(resource_group: 'ExampleGroup') do it { should exist } end # If we expect 'MissingExampleGroup' Resource Group to not have Network Watchers describe azurerm_network_watchers(resource_group: 'MissingExampleGroup') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_network_watchers/azurerm_network_watcher resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_network_watcher.md) Use the `azurerm_network_watcher` InSpec audit resource to test properties of an Azure Network Watcher. Azure REST API version ---------------------- This resource interacts with version `2018-02-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/network-watcher/networkwatchers/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_network_watcher` resource block identifies a Network Watcher by name and resource group. ``` describe azurerm_network_watcher(resource_group: 'example', name: 'WatcherName') do ... end ``` Examples -------- ### Test that an example Resource Group has the specified Network Watcher ``` describe azurerm_network_watcher(resource_group: 'example', name: 'WatcherName') do it { should exist } end ``` ### Test that an example Resource Group has a Network Watcher with the Provisioning State value ‘Succeeded’ ``` describe azurerm_network_watcher(resource_group: 'example', name: 'WatcherName') do its('provisioning_state') { should eq 'Succeeded' } end ``` Parameters ---------- * `name` * `resource_group` Parameter Examples ------------------ The Resource Group as well as the Network Watcher name. ``` describe azurerm_network_watcher(resource_group: 'example', name: 'WatcherName') do its('provisioning_state') { should eq 'Succeeded' } end ``` Attributes ---------- * `provisioning_state` ### provisioning_state The provisioning_state field can be checked for the value of the Provisioning State. ``` its('provisioning_state') { should eq 'Succeeded' } ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'WatcherName' to always exist describe azurerm_network_watcher(resource_group: 'example', name: 'WatcherName') do it { should exist } end # If we expect 'WatcherNotFound' to never exist describe azurerm_network_watcher(resource_group: 'example', name: 'WatcherNotFound') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_network_watcher/azurerm_postgresql_databases resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_postgresql_databases.md) Use the `azurerm_postgresql_databases` InSpec audit resource to test properties and configuration of Azure PostgreSQL Databases. Azure REST API version ---------------------- This resource interacts with version `2017-12-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/postgresql/databases/listbyserver). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.7.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_postgresql_databases` resource block returns all Databases on a PostgreSQL Server, within a Resource Group. ``` describe azurerm_postgresql_databases(resource_group: ..., server_name: ...) do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check PostgreSQL Databases are present ``` describe azurerm_postgresql_databases(resource_group: 'resource-group-1', server_name: 'production') do it { should exist } its('names') { should include 'my-database-name' } end ``` Filter Criteria --------------- * `azure_postgresql_databases` resources are filterable on all available properties. Below are some examples. ### names Filters the results to include only those databases that match the given name. This is a string value. ``` describe azurerm_postgresql_databases(resource_group: 'rg', server_name: 'server').where{ name.eql?('production-database') } do it { should exist } end ``` Attributes ---------- * `id` * `name` * `type` * `properties` ### ids Azure resource ID. ### names SQL Database name, e.g. `my-sql-database`. ``` its('names') { should include 'my-sql-database' } ``` ### type The type of Resource, typically `Microsoft.Sql/servers/databases`. ### properties A collection of additional configuration properties related to the PostgreSQL Database. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_postgresql_databases do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_postgresql_databases/azurerm_postgresql_server resource ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_postgresql_server.md) Use the `azurerm_postgresql_server` InSpec audit resource to test properties and configuration of an Azure PostgreSQL Server. Azure REST API version ---------------------- This resource interacts with version `2017-12-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/postgresql/databases/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.7.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` and `server_name` must be given as a parameter. ``` describe azurerm_postgresql_server(resource_group: 'inspec-resource-group-9', server_name: 'example_server') do it { should exist } end ``` Examples -------- If a PostgreSQL Server is referenced with a valid `Resource Group` and `Server Name` ``` describe azurerm_postgresql_server(resource_group: 'my-rg', server_name: 'sql-server-1') do it { should exist } end ``` If a PostgreSQL Server is referenced with an invalid `Resource Group` or `Server Name` ``` describe azurerm_postgresql_server(resource_group: 'invalid-rg', server_name: 'i-dont-exist') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the SQL Server belongs. * `server_name` - The unique name of the SQL Server. Attributes ---------- * `id` * `name` * `sku` * `location` * `properties` * `type` ### id Azure resource ID. ### name Server name, e.g. `my-sql-server`. ### sku SKU of server. This is billing information related properties of a server. ### location Resource location, e.g. `eastus`. ### properties A collection of additional configuration properties related to the PostgreSQL Server, e.g. `administratorLogin`. ### type The type of Resource, typically `Microsoft.DBforPostgreSQL/servers`. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_postgresql_server(resource_group: 'my-rg', server_name: 'server-name-1') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_postgresql_server/azurerm_role_definitions resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_role_definitions.md) Use the `azurerm_role_definitions` InSpec audit resource to test properties of some or all Azure Role Definitions. Azure REST API version ---------------------- This resource interacts with version `2015-07-01` of the Azure Graph API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/authorization/roledefinitions/list#roledefinition). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.3.7 of the inspec-azure resource pack. Syntax ------ An `azurerm_role_definitions` resource block returns all Role definitions within a subscription and allows testing of them. ``` describe azurerm_role_definitions do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check a role has the correct permissions are present ``` describe azurerm_role_definitions.where{name.eql?('Custom-Admin')} do its ('properties.first.permissions.first') { should have_attributes(actions: ['*']) } end ``` ### Check a role does not have certain permissions ``` describe azurerm_role_definitions do its ('properties.first.permissions.first') { should have_attributes(notActions: [ 'Microsoft.Authorization/*/Delete', 'Microsoft.Authorization/*/Write', 'Microsoft.Authorization/elevateAccess/Action', 'Microsoft.Blueprint/blueprintAssignments/write', 'Microsoft.Blueprint/blueprintAssignments/delete' ]) } end ``` Filter Criteria --------------- ### names Filters the results to include only those resource groups that match the given name. This is a string value. ``` describe azurerm_role_definitions.where{name.eql?('Custom-Admin') } do it { should exist } end ``` Properties ---------- * `ids` * `names` * `properties` ### ids The Object IDs of the Roles. ### names The names of the Roles. For a built-in role this will be an Azure generated UUID. For a CustomRole this will be the name you specified on creation. ### properties Additional properties available for the Roles. May be accessed with dot notation in controls. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_role_definitions do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_role_definitions/azurerm_postgresql_servers resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_postgresql_servers.md) Use the `azurerm_postgresql_servers` InSpec audit resource to test properties and configuration of multiple Azure PostgreSQL Servers. Azure REST API version ---------------------- This resource interacts with version `2017-12-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/postgresql/servers/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.7.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_postgresql_servers` resource block returns all Azure PostgreSQL Servers, either within a Resource Group (if provided), or within an entire Subscription. ``` describe azurerm_postgresql_servers do ... end ``` or ``` describe azurerm_postgresql_servers(resource_group: 'my-rg') do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check SQL Servers are present ``` describe azurerm_postgresql_servers do it { should exist } its('names') { should include 'my-server-name' } end ``` Filter Criteria --------------- ### names Filters the results to include only those servers which match the given name. This is a string value. ``` describe azurerm_postgresql_servers.where{ name.eql?('production-server-5') } do it { should exist } end ``` ### location Filters the results to include only those servers which reside in a given location. This is a string value. ``` describe azurerm_postgresql_servers.where{ location.eql?('eastus') } do it { should exist } end ``` Attributes ---------- * `id` * `name` * `sku` * `location` * `properties` * `type` ### ids Azure resource ID. ### names SQL Server name, e.g. `my-sql-server`. ``` its('names') { should include 'my-sql-database' } ``` ### sku SKU of the server. This is billing information related properties of a server. ### locations Resource location, e.g. `eastus`. ``` its('locations') { should_not include 'eastus' } ``` ### properties A collection of additional configuration properties related to the PostgreSQL Server, e.g. `administratorLogin`. ### type The type of Resource, typically `Microsoft.DBforPostgreSQL/servers`. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_postgresql_servers do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_postgresql_servers/azurerm_resource_groups resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_resource_groups.md) Use the `azurerm_resource_groups` InSpec audit resource to test properties of some or all Azure Resource Groups A Resource Group is a grouping of Azure resources. This allows you to issue a common command on a group of resources. Azure REST API version ---------------------- This resource interacts with version `2018-02-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.0.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_resource_groups` resource block uses an optional filter to select a group of Resource Groups and then tests that group. ``` describe azurerm_resource_groups do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check for a Resource Group ``` describe azurerm_resource_groups do its('names') { should include 'MyResourceGroup' } end ``` ### Insist that your resource group exists ``` describe azurerm_resource_groups.where(name: 'MyResourceGroup') it { should exist } end ``` ### Use names to get all Virtual Machines in Azure ``` azurerm_resource_groups.names.each do |resource_group| describe azurerm_virtual_machines(resource_group: resource_group, name: 'MyVmName') do its('monitoring_agent_installed') { should be true } end end ``` Filter Criteria --------------- * `names` ### names Filters the results to include only those resource groups that match the given name. This is a string value. ``` describe azurerm_resource_groups.where { name.start_with?('InSpec') } do it { should exist } end ``` Attributes ---------- * `ids` * `names` * `tags` ### names The ids property provides a list of all the Resource Group ids. ``` its('ids') { should include 'MyResourceGroupID' } ``` The names property provides a list of all the Resource Group names. ``` its('names') { should include 'MyResourceGroup' } ``` The tags property provides a list of all the Resource Group tags. ``` its('tags') { should include '{MyResourceGroupTag=""}' } ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_resource_groups do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_resource_groups/azurerm_role_definition resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_role_definition.md) Use the `azurerm_role_definition` InSpec audit resource to test properties of an Azure Role Definition. Azure REST API version ---------------------- This resource interacts with version `2015-07-01` of the Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/authorization/roledefinitions/get#roledefinition). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.3.7 of the inspec-azure resource pack. Syntax ------ The `name` of the Role must be given as a parameter. For built-in roles, such as `Owner` or `Contributor`, this role name takes the form of a UUID. For `CustomRole`’s which you have added to your subscription yourself, the Name field will be what you choose on creation of the Role. ``` describe azurerm_role_definition(name: 'some-custom-role-name') do ... end ``` Examples -------- Ensure a given role has a specific permission ``` describe azurerm_role_definition(name: 'policy-reader-only') it { should exist } its('permissions_allowed') { should include 'Microsoft.Authorization/policyassignments/read'} its('permissions_allowed') { should_not include 'Microsoft.Authorization/policyassignments/write'} its('permissions_allowed') { should_not include '*'} end ``` Attributes ---------- * `id` * `name` * `role_name` * `type` * `role_type` * `assignable_scopes` * `permissions_allowed` * `permissions_not_allowed` ### id The object ID of the Role ### name The name of the Role. For a built-in role this will be an Azure generated UUID. For a CustomRole this will be the name you specified on creation. ### role_name The human readable name of the Role. ### type The type of the object, e.g. `Microsoft.Authorization/roleDefinitions` ### role_type `BuiltInRole` or `CustomRole` ### assignable_scopes Role Assignable scopes. ### permissions_allowed Provider permissions granted with this role. ### permissions_not_allowed Provider permissions blocked with this role. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). Given the example response in their documentation: The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_role_definition(name: 'some-role') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_role_definition/azurerm_security_center_policies resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_security_center_policies.md) Use the `azurerm_security_center_policies` InSpec audit resource to test properties of some or all Azure Security Center Policies. Security Center Policies are defined for each Resource Group. A Security Center Policy called `default` also exists for every subscription. Azure REST API version ---------------------- This resource interacts with version `2015-06-01-Preview` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/previous-versions/azure/reference/mt704061(v%3dazure.100)). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.0.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_security_center_policies` resource block uses an optional filter to select a group of Security Center Policies and confirm that the expected groups exist. ``` describe azurerm_security_center_policies do ... end ``` Examples -------- ### Check for a Security Center Policy ``` describe azurerm_security_center_policies do its('names') { should include 'default' } end ``` ### Assert default Security Center Policy exists ``` describe azurerm_security_center_policies.where(name: 'default') it { should exist } end ``` Filter Criteria --------------- * `names` ### names Filters the results to include only those Security Center Policies that match the given name. This is a string value. ``` # default should always exist describe azurerm_security_center_policies.where(name: 'default') it { should exist } end ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` # default should always exist describe azurerm_security_center_policies.where(name: 'default') it { should exist } end # this security center policy should not exist describe azurerm_security_center_policies.where(name: 'DoesNotExist') it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_security_center_policies/azurerm_sql_servers resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_sql_servers.md) Use the `azurerm_sql_servers` InSpec audit resource to test properties and configuration of Azure SQL Servers. Azure REST API version ---------------------- This resource interacts with version `2018-06-01-preview` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/sql/servers/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.2.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_sql_servers` resource block returns all Azure SQL Servers, either within a Resource Group (if provided), or within an entire Subscription. ``` describe azurerm_sql_servers do ... end ``` or ``` describe azurerm_sql_servers(resource_group: 'my-rg') do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check SQL Servers are present ``` describe azurerm_sql_servers do it { should exist } its('names') { should include 'my-server-name' } end ``` Filter Criteria --------------- ### names Filters the results to include only those servers which match the given name. This is a string value. ``` describe azurerm_sql_servers.where{ name.eql?('production-server-5') } do it { should exist } end ``` ### location Filters the results to include only those servers which reside in a given location. This is a string value. ``` describe azurerm_sql_servers.where{ location.eql?('eastus') } do it { should exist } end ``` Attributes ---------- * `id` * `name` * `kind` * `location` * `properties` * `tags` * `type` ### ids Azure resource ID. ### names SQL Server name, e.g. `my-sql-server`. ``` its('names') { should include 'my-sql-database' } ``` ### kinds Kind of sql server. This is metadata used for the Azure portal experience. ### locations Resource location, e.g. `eastus`. ``` its('locations') { should_not include 'eastus' } ``` ### properties A collection of additional configuration properties related to the SQL Server, e.g. `administratorLogin`. ### tag Resource tags applied to the SQL Server. ### type The type of Resource, typically `Microsoft.Sql/servers`. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_sql_servers do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_sql_servers/azurerm_security_center_policy resource ========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_security_center_policy.md) Use the `azurerm_security_center_policy` InSpec audit resource to test properties of the `default` Security Center Policy. Azure currently only supports looking up the `default` policy via their Rest API. If you attempt to look up a different Security Policy you will receive an error. An Azure Security Center Policy defines a set of controls recommended for resources within this subscription. These settings will generate alerts if something is found to violate the recommendations. This resource allows you to inspect what alerts you have configured for your account. Azure REST API Version ---------------------- This resource interacts with version `2015-06-01-Preview` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/previous-versions/azure/reference/mt704062%28v%3dazure.100%29). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.0.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_security_center_policy` resource block identifies a Security Center Policy by name. In the current Rest API you may only lookup a `default` policy. If no policy is given the default one will be used. ``` describe azurerm_security_center_policy(name: 'default') do ... end ``` Examples -------- ### Assert that the default Security Center Policy exists ``` describe azurerm_security_center_policy(name: 'default') do it { should exist } end ``` ### Assert that the default Security Center Policy has log collection enabled ``` describe azurerm_security_center_policy(name: 'default') do its('log_collection') { should eq('On') } end ``` ### A non default policy may not be searched ``` describe azurerm_security_center_policy(name: 'NonDefaultPolicy') do it { should_not exist } end ``` Parameters ---------- * `name` Parameter Examples ------------------ The name of the Security Center Policy. It must be `default`. If no name is given then it will search for the `default` Security Center Policy (Optional). ``` describe azurerm_security_center_policy(name: 'default') do its('log_collection') { should eq('On') } end ``` Attributes ---------- * `id` * `name` * `log_collection` * `patch` * `baseline` * `anti_malware` * `disk_encryption` * `network_security_groups` * `web_application_firewall` * `next_generation_firewall` * `vulnerability_assessment` * `storage_encryption` * `just_in_time_network_access` * `app_whitelisting` * `sql_auditing` * `sql_transparent_data_encryption` * `notifications_enabled`, * `send_security_email_to_admin` * `contact_emails` * `contact_phone` * `pricing_tier` ### id The id of the Security Center Policy. ``` its('id') { should eq('/subscriptions/<SUBSCRIPTION_ID>/providers/Microsoft.Security/policies/default') } ``` ### name The name of the Security Center Policy. ``` its('name') { should eq('default') } ``` ### log_collection Log collection indicates if the monitoring agent will collect security data (`On`|`Off`). ``` its('log_collection') { should eq('On') } ``` ### pricing_tier Cost/Feature Model under which the subscription is operating (`Standard`|`Free`). ``` its('pricing_tier') { should eq('Standard') } ``` ### patch Patch indicates if system updates should be enabled for virtual machines (`On`|`Off`). ``` its('patch') { should eq('On') } ``` ### baseline Baseline indicates if OS vulnerabilities recommendations for virtual machines are enabled (`On`|`Off`). ``` its('baseline') { should eq('On') } ``` ### anti_malware Anti-Malware indicates if endpoint protection recommendations for virtual machines are enabled (`On`|`Off`). ``` its('anti_malware') { should eq('On') } ``` ### disk_encryption Disk Encryption indicates if recommendations for virtual machines are enabled (`On`|`Off`). ``` its('disk_encryption') { should eq('On') } ``` ### network_security_groups Network security groups indicates if recommendations for virtual machines are enabled (`On`|`Off`). ``` its('network_security_groups') { should eq('On') } ``` ### web_application_firewall Web application firewall indicates if recommendations for virtual machines are enabled (`On`|`Off`). ``` its('web_application_firewall') { should eq('On') } ``` ### next_generation_firewall Next generation firewall indicates if recommendations for virtual machines are enabled (`On`|`Off`). ``` its('next_generation_firewall') { should eq('On') } ``` ### vulnerability_assessment Vulnerability assessment indicates if recommendations for virtual machines are enabled (`On`|`Off`). ``` its('vulnerability_assessment') { should eq('On') } ``` ### storage_encryption Storage Encryption indicates if new data in Azure Blobs and Files will be encrypted by default (`On`|`Off`). ``` its('storage_encryption') { should eq('On') } ``` ### just_in_time_network_access Just in time network access indicates if recommendations for virtual machines are enabled (`On`|`Off`). ``` its('just_in_time_network_access') { should eq('On') } ``` ### app_whitelisting App whitelisting indicates if adaptive application controls are enabled (`On`|`Off`). ``` its('app_whitelisting') { should eq('On') } ``` ### sql_auditing SQL auditing indicates if auditing and threat detection recommendations are enabled (`On`|`Off`). ``` its('sql_auditing') { should eq('On') } ``` ### sql_transparent_data_encryption SQL transparent data encryption indicates if recommendations are enabled (`On`|`Off`). ``` its('sql_transparent_data_encryption') { should eq('On') } ``` ### notifications_enabled Notifications enabled indicates if security alerts are emailed to the security contact (`true`|`false`). ``` its('notifications_enabled') { should eq(true) } ``` ### send_security_email_to_admin Send security email to admin indicates if the subscription admin will receive security alerts (`true`|`false`). ``` its('send_security_email_to_admin') { should eq(true) } ``` ### contact_emails Contact emails contains a list of security email addresses. ``` its('contact_emails') { should include('<EMAIL>') } ``` ### contact_phone Contact phone contains the security contact phone number. ``` its('contact_phone') { should eq('1-111-111-1111') } ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # default should always exist describe azurerm_security_center_policy(name: 'default') do it { should exist } end # this security center policy should not exist describe azurerm_security_center_policy(name: 'DoesNotExist') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_security_center_policy/azurerm_sql_databases resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_sql_databases.md) Use the `azurerm_sql_databases` InSpec audit resource to test properties and configuration of Azure SQL Databases. Azure REST API version ---------------------- This resource interacts with version `2017-10-01-preview` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/sql/databases/listbyserver). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.2.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_sql_databases` resource block returns all SQL Databases on a SQL Server, within a Rsource Group. ``` describe azurerm_sql_databases(resource_group: ..., server_name: ...) do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check SQL Databases are present ``` describe azurerm_sql_databases(resource_group: 'resource-group-1', server_name: 'production') do it { should exist } its('names') { should include 'my-database-name' } end ``` Filter Criteria --------------- * `azure_sql_databases` resources are filterable on all available properties. Below are some examples. ### names Filters the results to include only those databases that match the given name. This is a string value. ``` describe azurerm_sql_databases(resource_group: 'rg', server_name: 'server').where{ name.eql?('production-database') } do it { should exist } end ``` ### location Filters the results to include only those resource groups that reside ina given location. This is a string value. ``` describe azurerm_sql_databases(resource_group: 'rg', server_name: 'server').where{ location.eql?('eastus') } do it { should exist } end ``` Attributes ---------- * `id` * `name` * `kind` * `location` * `type` * `sku` * `properties` ### ids Azure resource ID. ### names SQL Database name, e.g. `my-sql-database`. ``` its('names') { should include 'my-sql-database' } ``` ### kinds Kind of sql database. This is metadata used for the Azure portal experience. ### locations Resource location, e.g. `eastus`. ``` its('locations') { should_not include 'eastus' } ``` ### type The type of Resource, typically `Microsoft.Sql/servers/databases`. ### sku The name and tier of the SKU. ### properties A collection of additional configuration properties related to the SQL Database, e.g. `collation`. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_sql_databases do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_sql_databases/azurerm_sql_database resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_sql_database.md) Use the `azurerm_sql_database` InSpec audit resource to test properties and configuration of an Azure SQL Database on a SQL Server. Azure REST API version ---------------------- This resource interacts with version `2017-10-01-preview` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/sql/databases/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.2.0 of the inspec-azure resource pack. Syntax ------ The `resource_group`, `server_name` and `database_name` must be given as a parameter. ``` describe azurerm_sql_database(resource_group: 'inspec-rg', server_name: 'customer_server', database_name: 'order-db') do it { should exist } end ``` Examples -------- If a SQL Database is referenced with a valid `Resource Group`, `Server Name` and `Database name` ``` describe azurerm_sql_database(resource_group: 'inspec-rg', server_name: 'customer_server', database_name: 'order-db') do it { should exist } its('name') { should be 'order-db'} end ``` If a SQL Database is referenced with an invalid `Resource Group`, `Server Name` or `Database Name` ``` describe azurerm_sql_database(resource_group: 'inspec-rg', server_name: 'customer_server', database_name: 'invalid-db-name') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the SQL Server belongs. * `server_name` - The unique name of the SQL Server. * `database_name` - The unique name of the SQL Database. Attributes ---------- * `id` * `name` * `kind` * `location` * `type` * `sku` * `properties` ### id Azure resource ID. ### name SQL Server name, e.g. `customer-database`. ### kind Kind of sql database. This is metadata used for the Azure portal experience. ### location Resource location, e.g. `eastus`. ### type The type of Resource, typically `Microsoft.Sql/servers/databases`. ### sku The name and tier of the SKU. ### properties A collection of additional configuration properties related to the SQL Database, e.g. `collation`. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_sql_database(resource_group: 'my-rg', server_name: 'server-name-1', database_name: 'customer-db') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_sql_database/azurerm_sql_server resource ============================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_sql_server.md) Use the `azurerm_sql_server` InSpec audit resource to test properties and configuration of an Azure SQL Server within a Resource Group. Azure REST API version ---------------------- This resource interacts with version `2018-06-01-preview` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/sql/servers/get#server). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.2.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` and `server_name` must be given as a parameter. ``` describe azurerm_sql_server(resource_group: 'inspec-resource-group-9', server_name: 'example_server') do it { should exist } end ``` Examples -------- If a SQL Server is referenced with a valid `Resource Group` and `Server Name` ``` describe azurerm_sql_server(resource_group: 'my-rg', server_name: 'sql-server-1') do it { should exist } end ``` If a SQL Server is referenced with an invalid `Resource Group` or `Server Name` ``` describe azurerm_sql_server(resource_group: 'invalid-rg', server_name: 'i-dont-exist') do it { should_not exist } end ``` Parameters ---------- * `resource_group` - The resource Group to which the SQL Server belongs. * `server_name` - The unique name of the SQL Server. Attributes ---------- * `id` * `name` * `kind` * `location` * `properties` * `tags` * `type` ### id Azure resource ID. ### name SQL Server name, e.g. `my-sql-server`. ### kind Kind of sql server. This is metadata used for the Azure portal experience. ### location Resource location, e.g. `eastus`. ### properties A collection of additional configuration properties related to the SQL Server, e.g. `administratorLogin`. ### tags Resource tags applied to the SQL Server. ### type The type of Resource, typically `Microsoft.Sql/servers`. ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_sql_server(resource_group: 'my-rg', server_name: 'server-name-1') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_sql_server/azurerm_storage_account_blob_containers resource ==================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_storage_account_blob_containers.md) Use the `azurerm_storage_account_blob_containers` InSpec audit resource to test properties and configuration of Blob Containers within an Azure Storage Account. Azure REST API version ---------------------- This resource interacts with version `2018-07-01` of the Azure Management API. For more information see the [Official Azure Documentation](https://docs.microsoft.com/en-us/rest/api/storagerp/blobcontainers/blobcontainers_list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.3.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_storage_account_blob_containers` block returns all Blob Containers within a given Azure Storage Account. The `resource_group` and `storage_account_name` must be given as parameters. ``` describe azurerm_storage_account_blob_containers(resource_group: 'rg', storage_account_name: 'production') do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Ensure that a Blob Container exists ``` describe azurerm_storage_account_blob_containers(resource_group: 'rg', storage_account_name: 'sa') do its('names') { should include('my_blob_container') } end ``` Filter Criteria --------------- * `ids` * `names` * `etags` ### names Filters the results to include only those containers which match the given name. This is a string value. ``` describe azurerm_storage_account_blob_containers(resource_group: 'rg', storage_account_name: 'sa') do its('names') { should include('my_blob_container') } end ``` Attributes ---------- * `ids` * `names` * `etags` ### ids Azure resource ID. ### names Blob Container name, e.g. `my-blob-container`. ``` its('names') { should include 'my-blob-container' } ``` ### etags The etag of the Resource, e.g. `\"0x8D592D74CC20EBA\"`. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_storage_account_blob_containers do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_storage_account_blob_containers/azurerm_storage_account_blob_container resource =================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_storage_account_blob_container.md) Use the `azurerm_storage_account_blob_container` InSpec audit resource to test properties related to a Blob Container in an Azure Storage Account. Azure REST API version ---------------------- This resource interacts with version `2018-07-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/storagerp/blobcontainers/blobcontainers_get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.3.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_storage_account_blob_container` block returns the requested Blob Container within an Azure Storage Account. The `resource_group`, `storage_account_name` and `blob_container_name` must be given as parameters. ``` describe azurerm_storage_account_blob_container(resource_group: 'rg', storage_account_name: 'production', blob_container_name: 'logs') do ... ... end ``` Examples -------- ### Ensure that the Blob Container exists ``` describe azurerm_storage_account_blob_container(resource_group: 'rg', storage_account_name: 'default', blob_container_name: 'logs') do it { should exist } its('name') { should eq('logs') } end ``` ### Ensure that the Blob Container is private ``` describe azurerm_storage_account_blob_container(resource_group: 'rg', storage_account_name: 'production', blob_container_name: 'logs') do its('properties') { should have_attributes(publicAccess: 'None') } end ``` Parameters ---------- * `resource_group` * `storage_account_name` * `blob_container_name` Attributes ---------- * `id` * `name` * `etag` * `properties` * `type` ### id Fully qualified resource ID for the resource, e.g. ``` /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} ``` ### name The name of the resource ### etag Resource Etag, e.g. ``` \"0x8D592D74CC20EBA\" ``` ### properties Additional properties relating to the Blob Container, e.g. ``` its('properties') { should have_attributes(publicAccess: 'None') } ``` ### type The resource type, e.g. ``` Microsoft.Storage/storageAccounts/blobServices/containers ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_storage_account_blob_container(resource_group: 'rg', storage_account_name: 'production', blob_container_name: 'logs') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_storage_account_blob_container/azurerm_subnet resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_subnet.md) Use the `azurerm_subnet` InSpec audit resource to test properties related to a subnet for a given virtual network. Azure REST API version ---------------------- This resource interacts with version `2018-02-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/virtualnetwork/subnets/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.2.0 of the inspec-azure resource pack. Syntax ------ The `resource_group`, virtual network `vnet`, and subnet ‘name’ must be given as parameters. Since subnet must be in the context of a virtual network, this parameter had to be included. ``` describe azurerm_subnet(resource_group: 'MyResourceGroup', vnet: 'MyVnetName', name: 'MySubnetName') do ... end ``` Examples -------- ### Ensure That the Subnet Exists for a given Virtual Network ``` describe azurerm_subnet(resource_group: 'MyResourceGroup', vnet: 'MyVnetName', name: 'MySubnetName') do it { should exist } end ``` ### Ensure That the Subnets Address Prefix Is Configured as Expected ``` describe azurerm_subnet(resource_group: 'MyResourceGroup', vnet: 'MyVnetName', name: 'MySubnetName') do its('address_prefix') { should eq [192.168.0.0/24] } end ``` ### Ensure That the Subnet Is Attached to the Right Network Security Group ``` describe azurerm_subnet(resource_group: 'MyResourceGroup', vnet: 'MyVnetName', name: 'MySubnetName') do its('nsg') { should eq 'NetworkSecurityGroupName'} end ``` Parameters ---------- * `resource_group` * `vnet` * `name` Parameter Examples ------------------ ### resource_group (required) Defines the resource group of the subnet that you wish to test resides in. ``` describe azurerm_subnet(resource_group: 'MyResourceGroup', vnet: 'MyVnetName', name: 'MySubnetName') do ... end ``` ### vnet (required) Defines the virtual network that the subnet that you wish to test is a part of. ``` describe azurerm_subnet(resource_group: 'MyResourceGroup', vnet: 'MyVnetName', name: 'MySubnetName') do ... end ``` ### name (required) Defines the name of the subnet that you wish to test. ``` describe azurerm_subnet(resource_group: 'MyResourceGroup', vnet: 'MyVnetName', name: 'MySubnetName') do ... end ``` Attributes ---------- * `id` * `name` * `type` * `address_prefix` * `nsg` ### id The subnet’s id. ``` its('id') { should eq(id) } ``` Id will be in format: ``` '/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/Inspec-Azure-mmclane/providers/Microsoft.Network/virtualNetworks/Inspec-VNet/subnets/Inspec-Subnet' ``` ### name The subnets’s name. ``` its('name') { should eq('MySubnetName') } ``` ### type The virtual network’s resource type. ``` its('type') { should eq 'Microsoft.Network/virtualNetworks/subnets' } ``` ### address_prefix The address prefix for the subnet. ``` its('address_prefix') { should eq "x.x.x.x/x" } ``` ### nsg The network security group attached to the subnet. ``` its('nsg') { should eq 'MyNetworkSecurityGroupName' } ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` # If a subnet is found it will exist describe azurerm_subnet(resource_group: 'MyResourceGroup', vnet: 'MyVnetName', name: 'MySubnetName') do it { should exist } end # subnets that aren't found will not exist describe azurerm_subnet(resource_group: 'MyResourceGroup', vnet: 'MyVnetName', name: 'DoesNotExist') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_subnet/azurerm_subscription resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_subscription.md) Use the `azurerm_subscription` InSpec audit resource to test properties related to the current subscription subscription. Azure REST API version ---------------------- This resource interacts with version `2019-10-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/resources/subscriptions/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.7.0 of the inspec-azure resource pack. Syntax ------ The resource will retrieve the current subscription which InSpec is using, which is specified in your environment/service principal. ``` describe azurerm_subscription do ... end ``` Examples -------- ### Ensure a Location Is Available in a Subscription ``` describe azurerm_subscription do its('name') { should eq 'subscription name' } its('locations') { should include 'eastus' } end ``` Parameters ---------- No parameters required. Attributes ---------- * `id` * `name` * `locations` ### id The subscription’s unique id. e.g. ‘1ea4649e-0132-4f1c-8b68-9f9b2147281c’ ### name The subscriptions’s display name. ``` its('name') { should eq('subscription name') } ``` ### locations An array of locations available in this subscription. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_subscription do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_subscription/azurerm_virtual_machine resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_virtual_machine.md) Use the `azurerm_virtual_machine` InSpec audit resource to test properties related to a virtual machine. Azure REST API version ---------------------- This resource interacts with version `2017-12-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/compute/virtualmachines/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.0.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` and virtual machine `name` must be given as parameters. ``` describe azurerm_virtual_machine(resource_group: 'MyResourceGroup', name: 'MyVmName') do ... end ``` Examples -------- ### Ensure That the Virtual Machine Has the Expected Data Disks ``` describe azurerm_virtual_machine(resource_group: 'MyResourceGroup', name: 'MyVmName') do its('data_disks') { should include 'DataDisk1' } its('data_disks') { should include 'DataDisk2' } end ``` ### Ensure That the Virtual Machine Has the Expected Monitoring Agent Installed ``` describe azurerm_virtual_machine(resource_group: 'MyResourceGroup', name: 'MyVmName') do it { should have_monitoring_agent_installed } end ``` Parameters ---------- * `resource_group` * `name` Parameter Examples ------------------ ### resource_group (required) Defines the resource group that the virtual machine that you wish to test resides in. ``` describe azurerm_virtual_machine(resource_group: 'MyResourceGroup', name: 'MyVmName') do ... end ``` ### name (required) Defines the name of the virtual machine that you wish to test. ``` describe azurerm_virtual_machine(resource_group: 'MyResourceGroup', name: 'MyVmName') do ... end ``` Attributes ---------- * `id` * `name` * `location` * `properties` * `resources` * `tags` * `type` * `zones` * `installed_extensions_types` * `installed_extensions_names` * `monitoring_agent_installed` * `os_disk_name` * `data_disk_names` ### id The virtual machine’s id. ``` its('id') { should eq(id) } ``` Id will be in format: ``` '/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/virtualMachines/MyVirtualMachine' ``` ### name The virtual machine’s name. ``` its('name') { should eq('MyVmName') } ``` ### location The virtual machine’s location. ``` its('location') { should eq('East US') } ``` ### tags The virtual machine’s tags. ``` its('tags') { should eq({ 'key' => 'value' }) } ``` ### type The virtual machine’s resource type. ``` its('type') { should eq('Microsoft.Compute/virtualMachines') } ``` ### zones The virtual machine’s availability zones. ``` its('zones') should include('zone1', 'zone2') ``` ### os_disk_name The virtual machine’s operating system disk name. ``` its('os_disk_name') { should eq('OsDiskName') } ``` ### data_disk_names The virtual machine’s data disk names. ``` its('data_disk_names') { should include('DataDisk1') } ``` ### installed_extensions_types List of all installed extensions' types for the virtual machine. ``` its('installed_extensions_types') { should eq(['ExtensionType']) } ``` ### installed_extensions_names List of all installed extensions' names for the virtual machine. ``` its('installed_extensions_names') { should eq(['ExtensionName']) } ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` # If a virtual machine is found it will exist describe azurerm_virtual_machine(resource_group: 'MyResourceGroup', name: 'MyVmName') do it { should exist } end # virtual machines that aren't found will not exist describe azurerm_virtual_machine(resource_group: 'MyResourceGroup', name: 'DoesNotExist') do it { should_not exist } end ``` ### have_only_approved_extensions ``` # Check if a virtual machine has only approved extensions. If an extension # is used that's not in the list then the check will fail. describe azurerm_virtual_machine(resource_group: 'MyResourceGroup', name: 'MyVmName') do it { should have_only_approved_extensions(['ApprovedExtension', 'OtherApprovedExtensions']) } end ``` ### have_monitoring_agent_installed ``` # Will be true if the MicrosoftMonitoringAgent is installed (Windows only) describe azurerm_virtual_machine(resource_group: 'MyResourceGroup', name: 'MyVmName') do it { should have_monitoring_agent_installed } end ``` ### have_endpoint_protection_installed ``` # Will be true if any of the given extensions are installed. describe azurerm_virtual_machine(resource_group: 'MyResourceGroup', name: 'MyVmName') do it { should have_endpoint_protection_installed(['Extension1', 'Extension2']) } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_virtual_machine/azurerm_subnets resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_subnets.md) Use the `azurerm_subnets` InSpec audit resource to test properties related to subnets for a resource group. Azure REST API version ---------------------- This resource interacts with version `2018-02-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/virtualnetwork/subnets/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.2.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` and ‘vnet’ must be given as a parameter. ``` describe azurerm_subnets(resource_group: 'MyResourceGroup', vnet: 'MyVnetName') do ... end ``` Examples -------- ``` # Exists if any subnetss exist for a given virtual network in the resource group describe azurerm_subnets(resource_group: 'MyResourceGroup', vnet: 'MyVnetName') do it { should exist } end ``` Parameters ---------- * `resource_group` * ‘vnet’ ### Parameter Examples ### resource_group (required) Defines the resource group of the subnet that you wish to test resides in. ``` describe azurerm_subnets(resource_group: 'MyResourceGroup', vnet: 'MyVnetName') do ... end ``` ### vnet (required) Defines the virtual network that the subnet that you wish to test is a part of. ``` describe azurerm_subnets(resource_group: 'MyResourceGroup', vnet: 'MyVnetName') do ... end ``` ### name Filters the results to only those that match the given name. ``` # Insist that MySubnet exists describe azurerm_subnets(resource_group: 'MyResourceGroup', vnet: 'MyVnetName') do .where(name: 'MySubnet') do it { should exist } end ``` Attributes ---------- * `names` ### names Gives a list of all the subnet names in the virtual network. ``` its('names') { should include('SubnetName1', 'SubnetName2') } ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` # Should not exist if no subnets are in the virtual network describe azurerm_subnets(resource_group: 'MyResourceGroup', vnet: 'MyVnetName') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_subnets/azurerm_virtual_machines resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_virtual_machines.md) Use the `azurerm_virtual_machines` InSpec audit resource to test properties related to virtual machines for a resource group. Azure REST API version ---------------------- This resource interacts with version `2017-12-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/compute/virtualmachines/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.0.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` must be given as a parameter. ``` describe azurerm_virtual_machines(resource_group: 'MyResourceGroup') do ... end ``` Examples -------- ``` # Exists if any virtual machines exist in the resource group describe azurerm_virtual_machines(resource_group: 'MyResourceGroup') do it { should exist } end # Filters based on platform describe azurerm_virtual_machines(resource_group: 'MyResourceGroup').where(platform: 'windows') do it { should exist } end ``` Parameters ---------- * `resource_group` ### Parameter Examples #### resource_group (required) ``` describe azurerm_virtual_machines(resource_group: 'MyResourceGroup') do ... end ``` Filter Criteria --------------- * `platform` * `name` * `os_disk` ### platform Filters the results to only include those that match the given platform. Valid choices are `linux` and `windows`. ``` # Insist that you have at least one windows virtual machine describe azurerm_virtual_machines(resource_group: 'MyResourceGroup').where(platform: 'windows') do it { should exist } end ``` ### name Filters the result to only those that match the given name. ``` # Insist that you have at least one virtual machine that starts with 'MyVm' describe azurerm_virtual_machines(resource_group: 'MyResourceGroup').where { name.start_with?('WindowsVm') } do it { should exist } end ``` Attributes ---------- * `os_disks` * `data_disks` * `vm_names` ### os_disks Gives a list of OS disk names for all the virtual machines in the resource group. ``` its('os_disks.sort') { should eq ['MyDisk1', 'MyDisk2'] } ``` ### data_disks Gives a list of data disks for all the virtual machines in the resource group. ``` its('os_disks.sort') { should eq [['MyDisk1'], ['MyDisk2']] } ``` Note that it returns an array of arrays. You may flatten them for testing: ``` its('os_disks.flatten.sort') { should eq ['MyDisk1', 'MyDisk2'] } ``` ### vm_names Gives a list of all the virtual machine names in the resource group. ``` its('vm_names') { should include('MyVm1', 'MyVm2') } ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` # Should not exist if no virtual machines are in the resource group describe azurerm_virtual_machines(resource_group: 'MyResourceGroup') do it { should_not exist } end # Should exist if the filter returns a single virtual machine describe azurerm_virtual_machines(resource_group: 'MyResourceGroup').where(platform: 'windows') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_virtual_machines/azurerm_virtual_machine_disk resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_virtual_machine_disk.md) Use the `azurerm_virtual_machine_disk` InSpec audit resource to test properties related to a virtual machine’s disk. This resource will only support managed disks. If your disk is not managed it will not `exist` to the matcher. Azure REST API version ---------------------- This resource interacts with version `2017-03-30` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/compute/disks/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.0.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` and `name` must be given as parameters. ``` describe azurerm_virtual_machine_disk(resource_group: 'MyResourceGroup', name: 'MyDiskName') do ... end ``` Examples -------- ``` # If a disk is found it will exist describe azurerm_virtual_machine_disk(resource_group: 'MyResourceGroup', name: 'MyDiskName') do it { should exist } end # Check if encryption is enabled describe azurerm_virtual_machine_disk(resource_group: 'MyResourceGroup', name: 'MyDiskName') do its('encryption_enabled') { should be true } end ``` Parameters ---------- * `resource_group`, `name` Parameter Examples ------------------ ``` # resource_group and name are required parameters describe azurerm_virtual_machine_disk(resource_group: 'MyGroup', name: 'MyDiskName') do ... end ``` Attributes ---------- * `id` * `name` * `managedBy` * `sku` * `properties` * `type` * `location` * `tags` * `encryption_enabled` ### id The disk’s unique identifier. ``` its('id') { should eq(id) } ``` Id will be in the format: ``` /subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/myManagedDisk ``` ### name The disk’s name. ``` its('name') { should eq('MyDiskName') } ``` ### managedBy The resource managing the disk if it is attached to a virtual machine. ``` its('managedBy') { should eq(ResourceId) } ``` ResourceId will be in the format: ``` /subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/myManagedDisk ``` ### sku The disk’s sku name (`Standard_LRS`|`StandardSSD_LRS`|`Premium_LRS`). ``` its('sku.name') { should eq('Standard_LRS') } ``` ### properties The disk’s properties. This is a hash of key/value pairs. ### type The disk’s type. Will always be `Microsoft.Compute/disks`. ``` its('type') { should eq('Microsoft.Compute/disks') } ``` ### location The disk’s location. Will be the region where the disk resides. ``` its('location') { should eq('West US') } ``` ### tags The disk’s tags. Will be a hash of key/value pairs. ``` its('tags') { should eq({ 'department' => 'IT' }) ``` ### encryption_enabled If the disk is encrypted or not (`true`|`false`). ``` its('encryption_enabled') { should be true } ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` describe azurerm_virtual_machine_disk(resource_group: 'MyResourceGroup', name: 'MyDiskName') do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_virtual_machine_disk/azurerm_virtual_machine_disks resource ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_virtual_machine_disks.md) Use the `azurerm_virtual_machine_disks` InSpec audit resource to test properties of some or all Azure Disks within a subscription. Azure REST API version ---------------------- This resource interacts with version `2019-03-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/compute/disks/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.8.0 of the inspec-azure resource pack. Syntax ------ An `azurerm_virtual_machine_disks` resource block returns all Azure Disks in a subscription. ``` describe azurerm_virtual_machine_disks do ... end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Check a Disk exists ``` describe azurerm_virtual_machine_disks do it('names') { should include 'app-server-disk' } end ``` ### Ensure there are no detached disks ``` describe azurerm_virtual_machine_disks.where { attached == true } do it { should_not exist } end ``` Filter Criteria --------------- * `ids` * `names` * `properties` * `tags` * `locations` * `attached` * `resource_groups` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the filter returns at least one result. Use `should_not` if you expect zero matches. ``` describe azurerm_virtual_machine_disks.where { <filter> == <criteria> } do it { should exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_virtual_machine_disks/azurerm_virtual_networks resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_virtual_networks.md) Use the `azurerm_virtual_networks` InSpec audit resource to test properties related to virtual networks for a resource group. Azure REST API version ---------------------- This resource interacts with version `2018-02-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/virtualnetwork/virtualnetworks/list). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.1.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` must be given as a parameter. ``` describe azurerm_virtual_networks(resource_group: 'MyResourceGroup') do ... end ``` Examples -------- ``` # Exists if any virtual networks exist in the resource group describe azurerm_virtual_networks(resource_group: 'MyResourceGroup') do it { should exist } end ``` Parameters ---------- * `resource_group` ### Parameter Examples ### resource_group (required) ``` describe azurerm_virtual_networks(resource_group: 'MyResourceGroup') do ... end ``` ### name Filters the results to only those that match the given name. ``` # Insist that MyVnetName exists describe azurerm_virtual_networks(resource_group: 'MyResourceGroup') .where(name: 'MyVnetName') do it { should exist } end # Insist that you have at least one virtual network that starts with 'prefix' describe azurerm_virtual_networks(resource_group: 'MyResourceGroup').where { name.start_with?('prefix') } do it { should exist } end ``` Attributes ---------- * `names` ### names Gives a list of all the virtual network names in the resource group. ``` its('names') { should include('VnetName1', 'VnetName2') } ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` # Should not exist if no virtual networks are in the resource group describe azurerm_virtual_networks(resource_group: 'MyResourceGroup') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_virtual_networks/azurerm_virtual_network resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_virtual_network.md) Use the `azurerm_virtual_network` InSpec audit resource to test properties related to a virtual network. Azure REST API version ---------------------- This resource interacts with version `2018-02-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/virtualnetwork/virtualnetworks/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: - name: inspec-azure git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). ### Version This resource first became available in 1.1.0 of the inspec-azure resource pack. Syntax ------ The `resource_group` and virtual network `name` must be given as parameters. ``` describe azurerm_virtual_network(resource_group: 'MyResourceGroup', name: 'MyVnetName') do ... end ``` Examples -------- ### Ensure That the Virtual Network Exists in the East US Region ``` describe azurerm_virtual_network(resource_group: resource_group, name: 'MyVnetName') do it { should exist } its('location') { should eq 'East US' } end ``` ### Ensure That the Virtual Network’s Dns Servers Are Configured as Expected ``` describe azurerm_virtual_network(resource_group: resource_group, name: 'MyVnetName') do its('dns_servers') { should eq ["192.168.0.6"] } end ``` ### Ensure That the Virtual Network’s Address Space Is Configured as Expected ``` describe azurerm_virtual_network(resource_group: resource_group, name: 'MyVnetName') do its('address_space') { should eq ["192.168.0.0/24"] } end ``` Parameters ---------- * `resource_group` * `name` Parameter Examples ------------------ ### resource_group (required) Defines the resource group that the virtual network that you wish to test resides in. ``` describe azurerm_virtual_network(resource_group: 'MyResourceGroup', name: 'MyVnetName') do ... end ``` ### name (required) Defines the name of the virtual network that you wish to test. ``` describe azurerm_virtual_network(resource_group: 'MyResourceGroup', name: 'MyVnetName') do ... end ``` Attributes ---------- * `id` * `name` * `location` * `tags` * `type` * `subnets` * `address_space` * `dns_servers` * `vnet_peerings` * `enable_ddos_protection` * `enable_vm_protection` ### id The virtual network’s id. ``` its('id') { should eq(id) } ``` Id will be in format: ``` '/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/Inspec-Azure-mmclane/providers/Microsoft.Network/virtualNetworks/MyVnetName' ``` ### name The virtual network’s name. ``` its('name') { should eq('MyVnetName') } ``` ### location The virtual network’s location. ``` its('location') { should eq('East US') } ``` ### type The virtual network’s resource type. ``` its('type') { should eq 'Microsoft.Network/virtualNetworks' } ``` ### tags The virtual network’s tags. ``` its('tags') { should eq({ 'key' => 'value' }) } ``` ### subnets The list of subnet names that are attached to this virtual network. ``` its('subnets') { should eq ["MySubnetName"] } ``` ### address_space The list of address spaces used by the virtual network. ``` its('address_space') { should eq ["x.x.x.x/x"] } ``` ### dns_servers The list of DNS servers configured for the virtual network. The virtual network returns these IP addresses when virtual machines makes a DHCP request. ``` its('dns_servers') { should eq ["x.x.x.x", "x.x.x.x"] } ``` ### vnet_peerings A mapping of names and the virtual network ids of the virtual network peerings. ``` its('vnet_peerings') { should eq "MyVnetPeeringConnection"=>"PeeringConnectionID"} ``` ### enable_ddos_protection Boolean value showing if Azure DDoS standard protection is enabled on the virtual network. ``` its('enable_ddos_protection') { should eq true } ``` ### enable_vm_protection Boolean value showing if the virtual network has VM protection enabled. ``` its('enable_vm_protection') { should eq false } ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists ``` # If a virtual network is found it will exist describe azurerm_virtual_network(resource_group: 'MyResourceGroup', name: 'MyVnetName') do it { should exist } end # virtual networks that aren't found will not exist describe azurerm_virtual_network(resource_group: 'MyResourceGroup', name: 'DoesNotExist') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_virtual_network/azurerm_webapp resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_webapp.md) Use the `azurerm_webapp` InSpec audit resource to test properties of an Azure Webapp. Azure REST API version ---------------------- This resource interacts with version `2016-08-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/appservice/webapps/get). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_webapp` resource block identifies an AppService Webapp by name and Resource Group. ``` describe azurerm_appservice_webapp(resource_group: 'example', name: 'webapp name') do ... end ``` Examples -------- ### Test and Verify That Resource Group Has Specified Webapp Test that an example Resource Group has the specified Webapp and verify it’s authentication settings are enabled. Verify HTTP 2.0 is enabled. ``` describe azurerm_webapp(resource_group: 'example', name: 'webapp_name') do it { should exist } its('auth_settings.properties') { should have_attributes(enabled: false) } its('configuration.properties') { should have_attributes(http20Enabled: true) } end ``` ### Test Webapp to Ensure It’s Using the Latest Supported Version Of .Net ``` describe azurerm_webapp(resource_group: resource_group, name: wa_name) do it { should be_using_latest('aspnet') } end ``` ### Test Webapp to Ensure It’s Using the Latest Supported Version of Python ``` describe azurerm_webapp(resource_group: resource_group, name: wa_name) do it { should be_using_latest('python') } end ``` Parameters ---------- * `name` * `resource_group` Parameter Examples ------------------ The Resource Group as well as the Webapp name. ``` describe azurerm_webapp(resource_group: 'example', name: 'webapp_name') do it { should exist } end describe azurerm_webapp(resource_group: 'example', name: 'webapp_name').auth_settings do its('properties') { should have_attributes(enabled: true) } end ``` Attributes ---------- * `id` * `name` * `location` * `properties` * `identity` * `auth_settings` * `configuration` All of the attributes are avialable via dot notation. This is an example of the currently available attributes. ``` control 'azurerm_webapp' do describe azurerm_webapp(resource_group: 'example', name: 'webapp_name') do it { should exist } its('properties.enabled') { should cmp true } its('properties.clientCertEnabled') { should cmp true } its('properties.enabledHostNames') { should cmp 'webapp_name.azurewebsites.net' } its('properties.httpsOnly') { should cmp true } end end ``` ### Other Attributes There are additional attributes that may be accessed that we have not documented. Please take a look at the [Azure documentation](#azure-rest-api-version). Any attribute in the response may be accessed with the key names separated by dots (`.`). The API may not always return keys that do not have any associated data. There may be cases where the deeply nested property may not have the desired attribute along your call chain. If you find yourself writing tests against properties that may be nil, fork this resource pack and add an accessor to the resource. Within that accessor you’ll be able to guard against nil keys. Pull requests are always welcome. Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### using_latest?(stack) Asserts whether the deployed Azure WebApp is using the latest supported version of the given language/stack. Supported stacks (i.e. python, java, php, node) can be found in the `properties` section of WebApp Configuration [documentation](https://docs.microsoft.com/en-us/rest/api/appservice/webapps/getconfiguration#siteconfigresource). ``` it { should be_using_latest('php') } it { should be_using_latest('java') } it { should be_using_latest('python') } it { should be_using_latest('aspnet') } it { should be_using_latest('dotnetcore') } ``` ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'webapp_name' to have a Managed Service Identity describe azurerm_webapp(resource_group: 'example', name: 'webapp_name') do it { should have_identity } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_webapp/google_access_context_manager_access_policy resource ========================================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_access_context_manager_access_policy.md) Syntax ------ A `google_access_context_manager_access_policy` is used to test a Google AccessPolicy resource Examples -------- ``` describe.one do google_access_context_manager_access_policies(org_id: '190694428152').names.each do |policy_name| describe google_access_context_manager_access_policy(name: policy_name) do it { should exist } its('title') { should cmp 'policytitle' } its('parent') { should match '190694428152' } end end end ``` Properties ---------- Properties that can be accessed from the `google_access_context_manager_access_policy` resource: `name` Resource name of the AccessPolicy. Format: accessPolicies/{policy_id} `create_time` Time the AccessPolicy was created in UTC. `update_time` Time the AccessPolicy was updated in UTC. `parent` The parent of this AccessPolicy in the Cloud Resource Hierarchy. Format: organizations/{organization_id} `title` Human readable title. Does not affect behavior. GCP Permissions --------------- © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_access_context_manager_access_policy/google_access_context_manager_service_perimeter resource ============================================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_access_context_manager_service_perimeter.md) Syntax ------ A `google_access_context_manager_service_perimeter` is used to test a Google ServicePerimeter resource Examples -------- ``` describe.one do google_access_context_manager_access_policies(org_id: '190694428152').names.each do |policy_name| describe google_access_context_manager_service_perimeter(policy_name: policy_name, name: 'restrict_all') do it { should exist } its('title') { should cmp 'restrict_all' } its('status.restricted_services') { should include 'storage.googleapis.com' } end end end ``` Properties ---------- Properties that can be accessed from the `google_access_context_manager_service_perimeter` resource: `title` Human readable title. Must be unique within the Policy. `description` Description of the ServicePerimeter and its use. Does not affect behavior. `create_time` Time the AccessPolicy was created in UTC. `update_time` Time the AccessPolicy was updated in UTC. `perimeter_type` Specifies the type of the Perimeter. There are two types: regular and bridge. Regular Service Perimeter contains resources, access levels, and restricted services. Every resource can be in at most ONE regular Service Perimeter. In addition to being in a regular service perimeter, a resource can also be in zero or more perimeter bridges. A perimeter bridge only contains resources. Cross project operations are permitted if all effected resources share some perimeter (whether bridge or regular). Perimeter Bridge does not contain access levels or services: those are governed entirely by the regular perimeter that resource is in. Perimeter Bridges are typically useful when building more complex topologies with many independent perimeters that need to share some data with a common perimeter, but should not be able to share data among themselves. Possible values: * PERIMETER_TYPE_REGULAR * PERIMETER_TYPE_BRIDGE `status` ServicePerimeter configuration. Specifies sets of resources, restricted services and access levels that determine perimeter content and boundaries. `resources` A list of GCP resources that are inside of the service perimeter. Currently only projects are allowed. Format: projects/{project_number} `access_levels` A list of AccessLevel resource names that allow resources within the ServicePerimeter to be accessed from the internet. AccessLevels listed must be in the same policy as this ServicePerimeter. Referencing a nonexistent AccessLevel is a syntax error. If no AccessLevel names are listed, resources within the perimeter can only be accessed via GCP calls with request origins within the perimeter. For Service Perimeter Bridge, must be empty. Format: accessPolicies/{policy_id}/accessLevels/{access_level_name} `restricted_services` GCP services that are subject to the Service Perimeter restrictions. Must contain a list of services. For example, if `storage.googleapis.com` is specified, access to the storage buckets inside the perimeter must meet the perimeter’s access restrictions. `vpc_accessible_services` Specifies how APIs are allowed to communicate within the Service Perimeter. `enable_restriction` Whether to restrict API calls within the Service Perimeter to the list of APIs specified in ‘allowedServices’. `allowed_services` The list of APIs usable within the Service Perimeter. Must be empty unless `enableRestriction` is True. `spec` Proposed (or dry run) ServicePerimeter configuration. This configuration allows to specify and test ServicePerimeter configuration without enforcing actual access restrictions. Only allowed to be set when the `useExplicitDryRunSpec` flag is set. `resources` A list of GCP resources that are inside of the service perimeter. Currently only projects are allowed. Format: projects/{project_number} `access_levels` A list of AccessLevel resource names that allow resources within the ServicePerimeter to be accessed from the internet. AccessLevels listed must be in the same policy as this ServicePerimeter. Referencing a nonexistent AccessLevel is a syntax error. If no AccessLevel names are listed, resources within the perimeter can only be accessed via GCP calls with request origins within the perimeter. For Service Perimeter Bridge, must be empty. Format: accessPolicies/{policy_id}/accessLevels/{access_level_name} `restricted_services` GCP services that are subject to the Service Perimeter restrictions. Must contain a list of services. For example, if `storage.googleapis.com` is specified, access to the storage buckets inside the perimeter must meet the perimeter’s access restrictions. `vpc_accessible_services` Specifies how APIs are allowed to communicate within the Service Perimeter. `enable_restriction` Whether to restrict API calls within the Service Perimeter to the list of APIs specified in ‘allowedServices’. `allowed_services` The list of APIs usable within the Service Perimeter. Must be empty unless `enableRestriction` is True. `use_explicit_dry_run_spec` Use explicit dry run spec flag. Ordinarily, a dry-run spec implicitly exists for all Service Perimeters, and that spec is identical to the status for those Service Perimeters. When this flag is set, it inhibits the generation of the implicit spec, thereby allowing the user to explicitly provide a configuration (“spec”) to use in a dry-run version of the Service Perimeter. This allows the user to test changes to the enforced config (“status”) without actually enforcing them. This testing is done through analyzing the differences between currently enforced and suggested restrictions. useExplicitDryRunSpec must bet set to True if any of the fields in the spec are set to non-default values. `parent` The AccessPolicy this ServicePerimeter lives in. Format: accessPolicies/{policy_id} `name` Resource name for the ServicePerimeter. The short*name component must begin with a letter and only include alphanumeric and ‘*’. Format: accessPolicies/{policy_id}/servicePerimeters/{short_name} GCP Permissions --------------- © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_access_context_manager_service_perimeter/google_appengine_standard_app_version resource ================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_appengine_standard_app_version.md) Syntax ------ A `google_appengine_standard_app_version` is used to test a Google StandardAppVersion resource Examples -------- ``` describe google_appengine_standard_app_version(project: 'chef-gcp-inspec', location: 'europe-west2', version_id: 'v2', service: 'default') do it { should exist } its('version_id') { should eq 'v2' } its('runtime') { should eq 'nodejs10' } end ``` Properties ---------- Properties that can be accessed from the `google_appengine_standard_app_version` resource: `name` Full path to the Version resource in the API. Example, “v1”. `version_id` Relative name of the version within the service. For example, `v1`. Version names can contain only lowercase letters, numbers, or hyphens. Reserved names,“default”, “latest”, and any name with the prefix “ah-”. `runtime` Desired runtime. Example python27. `threadsafe` Whether multiple requests can be dispatched to this version at once. `instance_class` Instance class that is used to run this version. Valid values are AutomaticScaling: F1, F2, F4, F4_1G BasicScaling or ManualScaling: B1, B2, B4, B4_1G, B8 Defaults to F1 for AutomaticScaling and B2 for ManualScaling and BasicScaling. If no scaling is specified, AutomaticScaling is chosen. `automatic_scaling` Automatic scaling is based on request rate, response latencies, and other application metrics. `max_concurrent_requests` Number of concurrent requests an automatic scaling instance can accept before the scheduler spawns a new instance. Defaults to a runtime-specific value. `max_idle_instances` Maximum number of idle instances that should be maintained for this version. `max_pending_latency` Maximum amount of time that a request should wait in the pending queue before starting a new instance to handle it. A duration in seconds with up to nine fractional digits, terminated by ’s'. Example: “3.5s”. `min_idle_instances` Minimum number of idle instances that should be maintained for this version. Only applicable for the default version of a service. `min_pending_latency` Minimum amount of time a request should wait in the pending queue before starting a new instance to handle it. A duration in seconds with up to nine fractional digits, terminated by ’s'. Example: “3.5s”. `standard_scheduler_settings` Scheduler settings for standard environment. `target_cpu_utilization` Target CPU utilization ratio to maintain when scaling. Should be a value in the range [0.50, 0.95], zero, or a negative value. `target_throughput_utilization` Target throughput utilization ratio to maintain when scaling. Should be a value in the range [0.50, 0.95], zero, or a negative value. `min_instances` Minimum number of instances to run for this version. Set to zero to disable minInstances configuration. `max_instances` Maximum number of instances to run for this version. Set to zero to disable maxInstances configuration. `basic_scaling` Basic scaling creates instances when your application receives requests. Each instance will be shut down when the application becomes idle. Basic scaling is ideal for work that is intermittent or driven by user activity. `idle_timeout` Duration of time after the last request that an instance must wait before the instance is shut down. A duration in seconds with up to nine fractional digits, terminated by ’s'. Example: “3.5s”. Defaults to 900s. `max_instances` Maximum number of instances to create for this version. Must be in the range [1.0, 200.0]. `manual_scaling` A service with manual scaling runs continuously, allowing you to perform complex initialization and rely on the state of its memory over time. `instances` Number of instances to assign to the service at the start. **Note:** When managing the number of instances at runtime through the App Engine Admin API or the (now deprecated) Python 2 Modules API set_num_instances() you must use `lifecycle.ignore_changes = ["manual_scaling"[0].instances]` to prevent drift detection. GCP Permissions --------------- Ensure the [App Engine Admin API](https://console.cloud.google.com/apis/library/appengine.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_appengine_standard_app_version/google_access_context_manager_access_policies resource =========================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_access_context_manager_access_policies.md) Syntax ------ A `google_access_context_manager_access_policies` is used to test a Google AccessPolicy resource Examples -------- ``` describe google_access_context_manager_access_policies(org_id: '190694428152') do its('count') { should be >= 1 } its('titles') { should include 'policytitle' } end ``` Properties ---------- Properties that can be accessed from the `google_access_context_manager_access_policies` resource: See the [google_access_context_manager_access_policy](../google_access_context_manager_access_policy/index#properties) resource for more information. `names` an array of `google_access_context_manager_access_policy` name `create_times` an array of `google_access_context_manager_access_policy` create_time `update_times` an array of `google_access_context_manager_access_policy` update_time `parents` an array of `google_access_context_manager_access_policy` parent `titles` an array of `google_access_context_manager_access_policy` title Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_access_context_manager_access_policies/google_access_context_manager_service_perimeters resource ============================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_access_context_manager_service_perimeters.md) Syntax ------ A `google_access_context_manager_service_perimeters` is used to test a Google ServicePerimeter resource Examples -------- ``` describe.one do google_access_context_manager_access_policies(org_id: '190694428152').names.each do |policy_name| describe google_access_context_manager_service_perimeters(policy_name: policy_name) do its('names') { should include 'restrict_all' } its('titles') { should include 'restrict_all' } end end end ``` Properties ---------- Properties that can be accessed from the `google_access_context_manager_service_perimeters` resource: See the [google_access_context_manager_service_perimeter](../google_access_context_manager_service_perimeter/index#properties) resource for more information. `titles` an array of `google_access_context_manager_service_perimeter` title `descriptions` an array of `google_access_context_manager_service_perimeter` description `create_times` an array of `google_access_context_manager_service_perimeter` create_time `update_times` an array of `google_access_context_manager_service_perimeter` update_time `perimeter_types` an array of `google_access_context_manager_service_perimeter` perimeter_type `statuses` an array of `google_access_context_manager_service_perimeter` status `specs` an array of `google_access_context_manager_service_perimeter` spec `use_explicit_dry_run_specs` an array of `google_access_context_manager_service_perimeter` use_explicit_dry_run_spec `parents` an array of `google_access_context_manager_service_perimeter` parent `names` an array of `google_access_context_manager_service_perimeter` name Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_access_context_manager_service_perimeters/google_appengine_standard_app_versions resource =================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_appengine_standard_app_versions.md) Syntax ------ A `google_appengine_standard_app_versions` is used to test a Google StandardAppVersion resource Examples -------- ``` describe google_appengine_standard_app_versions(project: 'chef-gcp-inspec', location: 'europe-west2',service: 'default') do its('runtimes') { should include 'nodejs10' } end ``` Properties ---------- Properties that can be accessed from the `google_appengine_standard_app_versions` resource: See the [google_appengine_standard_app_version](../google_appengine_standard_app_version/index#properties) resource for more information. `names` an array of `google_appengine_standard_app_version` name `version_ids` an array of `google_appengine_standard_app_version` version_id `runtimes` an array of `google_appengine_standard_app_version` runtime `threadsaves` an array of `google_appengine_standard_app_version` threadsafe `instance_classes` an array of `google_appengine_standard_app_version` instance_class `automatic_scalings` an array of `google_appengine_standard_app_version` automatic_scaling `basic_scalings` an array of `google_appengine_standard_app_version` basic_scaling `manual_scalings` an array of `google_appengine_standard_app_version` manual_scaling Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [App Engine Admin API](https://console.cloud.google.com/apis/library/appengine.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_appengine_standard_app_versions/google_bigquery_dataset resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_bigquery_dataset.md) Syntax ------ A `google_bigquery_dataset` is used to test a Google Dataset resource Examples -------- ``` describe google_bigquery_dataset(project: 'chef-gcp-inspec', name: 'inspec_gcp_dataset') do it { should exist } its('friendly_name') { should eq 'A BigQuery dataset test' } its('location') { should eq 'EU' } its('description') { should eq 'Test BigQuery dataset description' } its('name') { should eq 'inspec_gcp_dataset' } its('default_table_expiration_ms') { should cmp '3600000' } end describe.one do google_bigquery_dataset(project: 'chef-gcp-inspec', name: 'inspec_gcp_dataset').access.each do |dataset_access| describe dataset_access do its('role') { should eq 'WRITER' } its('special_group') { should eq 'projectWriters' } end end end describe google_bigquery_dataset(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_bigquery_dataset` resource: `access` An array of objects that define dataset access for one or more entities. `domain` A domain to grant access to. Any users signed in with the domain specified will be granted the specified access `group_by_email` An email address of a Google Group to grant access to. `role` Describes the rights granted to the user specified by the other member of the access object. Primitive, Predefined and custom roles are supported. Predefined roles that have equivalent primitive roles are swapped by the API to their Primitive counterparts. See [official docs](https://cloud.google.com/bigquery/docs/access-control). `special_group` A special group to grant access to. Possible values include: * `projectOwners`: Owners of the enclosing project. * `projectReaders`: Readers of the enclosing project. * `projectWriters`: Writers of the enclosing project. * `allAuthenticatedUsers`: All authenticated BigQuery users. `user_by_email` An email address of a user to grant access to. For example: [<EMAIL>](mailto:<EMAIL>) `iam_member` Some other type of member that appears in the IAM Policy but isn’t a user, group, domain, or special group. For example: `allUsers` `view` A view from a different dataset to grant access to. Queries executed against that view will have read access to tables in this dataset. The role field is not required when this field is set. If that view is updated by any user, access to the view needs to be granted again via an update operation. `dataset_id` The ID of the dataset containing this table. `project_id` The ID of the project containing this table. `table_id` The ID of the table. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 1,024 characters. `creation_time` The time when this dataset was created, in milliseconds since the epoch. `dataset_reference` A reference that identifies the dataset. `dataset_id` A unique ID for this dataset, without the project name. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 1,024 characters. `project_id` The ID of the project containing this dataset. `default_table_expiration_ms` The default lifetime of all tables in the dataset, in milliseconds. The minimum value is 3600000 milliseconds (one hour). Once this property is set, all newly-created tables in the dataset will have an `expirationTime` property set to the creation time plus the value in this property, and changing the value will only affect new tables, not existing ones. When the `expirationTime` for a given table is reached, that table will be deleted automatically. If a table’s `expirationTime` is modified or removed before the table expires, or if you provide an explicit `expirationTime` when creating a table, that value takes precedence over the default expiration time indicated by this property. `default_partition_expiration_ms` The default partition expiration for all partitioned tables in the dataset, in milliseconds. Once this property is set, all newly-created partitioned tables in the dataset will have an `expirationMs` property in the `timePartitioning` settings set to this value, and changing the value will only affect new tables, not existing ones. The storage in a partition will have an expiration time of its partition time plus this value. Setting this property overrides the use of `defaultTableExpirationMs` for partitioned tables: only one of `defaultTableExpirationMs` and `defaultPartitionExpirationMs` will be used for any new partitioned table. If you provide an explicit `timePartitioning.expirationMs` when creating or updating a partitioned table, that value takes precedence over the default partition expiration time indicated by this property. `description` A user-friendly description of the dataset `etag` A hash of the resource. `friendly_name` A descriptive name for the dataset `id` The fully-qualified unique name of the dataset in the format projectId:datasetId. The dataset name without the project name is given in the datasetId field `labels` The labels associated with this dataset. You can use these to organize and group your datasets `last_modified_time` The date when this dataset or any of its tables was last modified, in milliseconds since the epoch. `location` The geographic location where the dataset should reside. See [official docs](https://cloud.google.com/bigquery/docs/dataset-locations). There are two types of locations, regional or multi-regional. A regional location is a specific geographic place, such as Tokyo, and a multi-regional location is a large geographic area, such as the United States, that contains at least two geographic places. Possible regional values include: `asia-east1`, `asia-northeast1`, `asia-southeast1`, `australia-southeast1`, `europe-north1`, `europe-west2` and `us-east4`. Possible multi-regional values: `EU` and `US`. The default value is multi-regional location `US`. Changing this forces a new resource to be created. `default_encryption_configuration` The default encryption key for all tables in the dataset. Once this property is set, all newly-created partitioned tables in the dataset will have encryption key set to this value, unless table creation request (or query) overrides the key. `kms_key_name` Describes the Cloud KMS encryption key that will be used to protect destination BigQuery table. The BigQuery Service Account associated with your project requires access to this encryption key. GCP Permissions --------------- Ensure the [BigQuery API](https://console.cloud.google.com/apis/library/bigquery-json.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_bigquery_dataset/google_bigquery_table resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_bigquery_table.md) Syntax ------ A `google_bigquery_table` is used to test a Google Table resource Examples -------- ``` describe google_bigquery_table(project: 'chef-gcp-inspec', dataset: 'inspec_gcp_dataset', name: 'inspec_gcp_bigquery_table') do it { should exist } its('expiration_time') { should cmp '1738882264000' } its('time_partitioning.type') { should eq 'DAY' } its('description') { should eq 'A BigQuery table' } end describe google_bigquery_table(project: 'chef-gcp-inspec', dataset: 'inspec_gcp_dataset', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_bigquery_table` resource: `table_reference` Reference describing the ID of this table `dataset_id` The ID of the dataset containing this table `project_id` The ID of the project containing this table `table_id` The ID of the the table `clustering` One or more fields on which data should be clustered. Only top-level, non-repeated, simple-type fields are supported. When you cluster a table using multiple columns, the order of columns you specify is important. The order of the specified columns determines the sort order of the data. `creation_time` The time when this dataset was created, in milliseconds since the epoch. `description` A user-friendly description of the dataset `friendly_name` A descriptive name for this table `id` An opaque ID uniquely identifying the table. `labels` The labels associated with this dataset. You can use these to organize and group your datasets `last_modified_time` The time when this table was last modified, in milliseconds since the epoch. `location` The geographic location where the table resides. This value is inherited from the dataset. `name` Name of the table `num_bytes` The size of this table in bytes, excluding any data in the streaming buffer. `num_long_term_bytes` The number of bytes in the table that are considered “long-term storage”. `num_rows` The number of rows of data in this table, excluding any data in the streaming buffer. `require_partition_filter` If set to true, queries over this table require a partition filter that can be used for partition elimination to be specified. `type` Describes the table type Possible values: * TABLE * VIEW * EXTERNAL `view` The view definition. `use_legacy_sql` Specifies whether to use BigQuery’s legacy SQL for this view `user_defined_function_resources` Describes user-defined function resources used in the query. `inline_code` An inline resource that contains code for a user-defined function (UDF). Providing a inline code resource is equivalent to providing a URI for a file containing the same code. `resource_uri` A code resource to load from a Google Cloud Storage URI (gs://bucket/path). `time_partitioning` If specified, configures time-based partitioning for this table. `expiration_ms` Number of milliseconds for which to keep the storage for a partition. `field` If not set, the table is partitioned by pseudo column, referenced via either ‘_PARTITIONTIME’ as TIMESTAMP type, or ‘_PARTITIONDATE’ as DATE type. If field is specified, the table is instead partitioned by this field. The field must be a top-level TIMESTAMP or DATE field. Its mode must be NULLABLE or REQUIRED. `type` The only type supported is DAY, which will generate one partition per day. Possible values: * DAY `streaming_buffer` Contains information regarding this table’s streaming buffer, if one is present. This field will be absent if the table is not being streamed to or if there is no data in the streaming buffer. `estimated_bytes` A lower-bound estimate of the number of bytes currently in the streaming buffer. `estimated_rows` A lower-bound estimate of the number of rows currently in the streaming buffer. `oldest_entry_time` Contains the timestamp of the oldest entry in the streaming buffer, in milliseconds since the epoch, if the streaming buffer is available. `schema` Describes the schema of this table `fields` Describes the fields in a table. `description` The field description. The maximum length is 1,024 characters. `fields` Describes the nested schema fields if the type property is set to RECORD. `mode` The field mode Possible values: * NULLABLE * REQUIRED * REPEATED `name` The field name `type` The field data type Possible values: * STRING * BYTES * INTEGER * FLOAT * TIMESTAMP * DATE * TIME * DATETIME * RECORD `encryption_configuration` Custom encryption configuration `kms_key_name` Describes the Cloud KMS encryption key that will be used to protect destination BigQuery table. The BigQuery Service Account associated with your project requires access to this encryption key. `expiration_time` The time when this table expires, in milliseconds since the epoch. If not present, the table will persist indefinitely. `external_data_configuration` Describes the data format, location, and other properties of a table stored outside of BigQuery. By defining these properties, the data source can then be queried as if it were a standard BigQuery table. `autodetect` Try to detect schema and format options automatically. Any option specified explicitly will be honored. `compression` The compression type of the data source Possible values: * GZIP * NONE `ignore_unknown_values` Indicates if BigQuery should allow extra values that are not represented in the table schema `max_bad_records` The maximum number of bad records that BigQuery can ignore when reading data `source_format` The data format Possible values: * CSV * GOOGLE_SHEETS * NEWLINE_DELIMITED_JSON * AVRO * DATASTORE_BACKUP * BIGTABLE `source_uris` The fully-qualified URIs that point to your data in Google Cloud. For Google Cloud Storage URIs: Each URI can contain one ‘*’ wildcard character and it must come after the ‘bucket’ name. Size limits related to load jobs apply to external data sources. For Google Cloud Bigtable URIs: Exactly one URI can be specified and it has be a fully specified and valid HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore backups, exactly one URI can be specified. Also, the ‘*’ wildcard character is not allowed. `schema` The schema for the data. Schema is required for CSV and JSON formats `fields` Describes the fields in a table. `description` The field description `fields` Describes the nested schema fields if the type property is set to RECORD `mode` Field mode. Possible values: * NULLABLE * REQUIRED * REPEATED `name` Field name `type` Field data type Possible values: * STRING * BYTES * INTEGER * FLOAT * TIMESTAMP * DATE * TIME * DATETIME * RECORD `google_sheets_options` Additional options if sourceFormat is set to GOOGLE_SHEETS. `skip_leading_rows` The number of rows at the top of a Google Sheet that BigQuery will skip when reading the data. `csv_options` Additional properties to set if sourceFormat is set to CSV. `allow_jagged_rows` Indicates if BigQuery should accept rows that are missing trailing optional columns `allow_quoted_newlines` Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file `encoding` The character encoding of the data Possible values: * UTF-8 * ISO-8859-1 `field_delimiter` The separator for fields in a CSV file `quote` The value that is used to quote data sections in a CSV file `skip_leading_rows` The number of rows at the top of a CSV file that BigQuery will skip when reading the data. `bigtable_options` Additional options if sourceFormat is set to BIGTABLE. `ignore_unspecified_column_families` If field is true, then the column families that are not specified in columnFamilies list are not exposed in the table schema `read_rowkey_as_string` If field is true, then the rowkey column families will be read and converted to string. `column_families` List of column families to expose in the table schema along with their types. `columns` Lists of columns that should be exposed as individual fields as opposed to a list of (column name, value) pairs. `encoding` The encoding of the values when the type is not STRING Possible values: * TEXT * BINARY `field_name` If the qualifier is not a valid BigQuery field identifier, a valid identifier must be provided as the column field name and is used as field name in queries. `only_read_latest` If this is set, only the latest version of value in this column are exposed `qualifier_string` Qualifier of the column `type` The type to convert the value in cells of this column Possible values: * BYTES * STRING * INTEGER * FLOAT * BOOLEAN `encoding` The encoding of the values when the type is not STRING Possible values: * TEXT * BINARY `family_id` Identifier of the column family. `only_read_latest` If this is set only the latest version of value are exposed for all columns in this column family `type` The type to convert the value in cells of this column family Possible values: * BYTES * STRING * INTEGER * FLOAT * BOOLEAN `dataset` Name of the dataset GCP Permissions --------------- Ensure the [BigQuery API](https://console.cloud.google.com/apis/library/bigquery-json.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_bigquery_table/google_billing_project_billing_info resource ================================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_billing_project_billing_info.md) Syntax ------ A `google_billing_project_billing_info` is used to test a Google ProjectBillingInfo resource Examples -------- ``` describe google_billing_project_billing_info(project_id: 'chef-gcp-inspec') do it { should exist } its('billing_account_name') { should eq 'billingAccounts/<KEY>' } its('billing_enabled') { should eq true } end ``` Properties ---------- Properties that can be accessed from the `google_billing_project_billing_info` resource: `project_id` The project id to retrieve billing info for. `billing_account_name` The resource name of the billing account associated with the project, if any. For example, `billingAccounts/ <KEY>`. `billing_enabled` True if the project is associated with an open billing account, to which usage on the project is charged. False if the project is associated with a closed billing account, or no billing account at all, and therefore cannot use paid services. GCP Permissions --------------- © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_billing_project_billing_info/google_cloud_scheduler_job resource ====================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_cloud_scheduler_job.md) Syntax ------ A `google_cloud_scheduler_job` is used to test a Google Job resource Examples -------- ``` describe google_cloud_scheduler_job(project: 'chef-gcp-inspec', region: us-central1, name: 'job-name') do it { should exist } its('description') { should cmp 'A description' } its('schedule') { should cmp '*/8 * * * *' } its('time_zone') { should cmp 'America/New_York' } its('http_target.http_method') { should cmp 'POST' } its('http_target.uri') { should cmp 'https://example.com/ping' } end ``` Properties ---------- Properties that can be accessed from the `google_cloud_scheduler_job` resource: `name` The name of the job. `description` A human-readable description for the job. This string must not contain more than 500 characters. `schedule` Describes the schedule on which the job will be executed. `time_zone` Specifies the time zone to be used in interpreting schedule. The value of this field must be a time zone name from the tz database. `attempt_deadline` The deadline for job attempts. If the request handler does not respond by this deadline then the request is cancelled and the attempt is marked as a DEADLINE_EXCEEDED failure. The failed attempt can be viewed in execution logs. Cloud Scheduler will retry the job according to the RetryConfig. The allowed duration for this deadline is: For HTTP targets, between 15 seconds and 30 minutes, for App Engine HTTP targets, between 15 seconds and 24 hours. A duration in seconds with up to nine fractional digits, terminated by ’s'. Example: “3.5s” `retry_config` By default, if a job does not complete successfully, meaning that an acknowledgement is not received from the handler, then it will be retried with exponential backoff according to the settings `retry_count` The number of attempts that the system will make to run a job using the exponential backoff procedure described by maxDoublings. Values greater than 5 and negative values are not allowed. `max_retry_duration` The time limit for retrying a failed job, measured from time when an execution was first attempted. If specified with retryCount, the job will be retried until both limits are reached. A duration in seconds with up to nine fractional digits, terminated by ’s'. `min_backoff_duration` The minimum amount of time to wait before retrying a job after it fails. A duration in seconds with up to nine fractional digits, terminated by ’s'. `max_backoff_duration` The maximum amount of time to wait before retrying a job after it fails. A duration in seconds with up to nine fractional digits, terminated by ’s'. `max_doublings` The time between retries will double maxDoublings times. A job’s retry interval starts at minBackoffDuration, then doubles maxDoublings times, then increases linearly, and finally retries retries at intervals of maxBackoffDuration up to retryCount times. `pubsub_target` Pub/Sub target If the job providers a Pub/Sub target the cron will publish a message to the provided topic `topic_name` The full resource name for the Cloud Pub/Sub topic to which messages will be published when a job is delivered. Note The topic name must be in the same format as required by PubSub’s PublishRequest.name, e.g. `projects/my-project/topics/my-topic`. `data` The message payload for PubsubMessage. Pubsub message must contain either non-empty data, or at least one attribute. `attributes` Attributes for PubsubMessage. Pubsub message must contain either non-empty data, or at least one attribute. `app_engine_http_target` App Engine HTTP target. If the job providers a App Engine HTTP target the cron will send a request to the service instance `http_method` Which HTTP method to use for the request. `app_engine_routing` App Engine Routing setting for the job. `service` App service. By default, the job is sent to the service which is the default service when the job is attempted. `version` App version. By default, the job is sent to the version which is the default version when the job is attempted. `instance` App instance. By default, the job is sent to an instance which is available when the job is attempted. `relative_uri` The relative URI. The relative URL must begin with “/” and must be a valid HTTP relative URL. It can contain a path, query string arguments, and # fragments. If the relative URL is empty, then the root path “/” will be used. No spaces are allowed, and the maximum length allowed is 2083 characters `body` HTTP request body. A request body is allowed only if the HTTP method is POST or PUT. It will result in invalid argument error to set a body on a job with an incompatible HttpMethod. `headers` HTTP request headers. This map contains the header field names and values. Headers can be set when the job is created. `http_target` HTTP target. If the job providers a http_target the cron will send a request to the targeted url `uri` The full URI path that the request will be sent to. `http_method` Which HTTP method to use for the request. `body` HTTP request body. A request body is allowed only if the HTTP method is POST, PUT, or PATCH. It is an error to set body on a job with an incompatible HttpMethod. `headers` This map contains the header field names and values. Repeated headers are not supported, but a header value can contain commas. `oauth_token` Contains information needed for generating an OAuth token. This type of authorization should be used when sending requests to a GCP endpoint. `service_account_email` Service account email to be used for generating OAuth token. The service account must be within the same project as the job. `scope` OAuth scope to be used for generating OAuth access token. If not specified, “[https://www.googleapis.com/auth/cloud-platform"](https://www.googleapis.com/auth/cloud-platform%22) will be used. `oidc_token` Contains information needed for generating an OpenID Connect token. This type of authorization should be used when sending requests to third party endpoints or Cloud Run. `service_account_email` Service account email to be used for generating OAuth token. The service account must be within the same project as the job. `audience` Audience to be used when generating OIDC token. If not specified, the URI specified in target will be used. `region` Region where the scheduler job resides GCP Permissions --------------- © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_cloud_scheduler_job/google_bigquery_datasets resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_bigquery_datasets.md) Syntax ------ A `google_bigquery_datasets` is used to test a Google Dataset resource Examples -------- ``` describe google_bigquery_datasets(project: 'chef-gcp-inspec') do its('count') { should be >= 1 } its('friendly_names') { should include 'A BigQuery dataset test' } its('locations') { should include 'EU' } end google_bigquery_datasets(project: 'chef-gcp-inspec').ids.each do |name| google_bigquery_dataset(project: 'chef-gcp-inspec', name: name.split(':').last).access.each do |access| describe access do # No bigquery dataset should allow access to allUsers its('iam_member') { should_not cmp 'allUsers' } end end end ``` Properties ---------- Properties that can be accessed from the `google_bigquery_datasets` resource: See the [google_bigquery_dataset](../google_bigquery_dataset/index#properties) resource for more information. `dataset_references` an array of `google_bigquery_dataset` dataset_reference `default_partition_expiration_ms` an array of `google_bigquery_dataset` default_partition_expiration_ms `etags` an array of `google_bigquery_dataset` etag `friendly_names` an array of `google_bigquery_dataset` friendly_name `ids` an array of `google_bigquery_dataset` id `labels` an array of `google_bigquery_dataset` labels `locations` an array of `google_bigquery_dataset` location `default_encryption_configurations` an array of `google_bigquery_dataset` default_encryption_configuration Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [BigQuery API](https://console.cloud.google.com/apis/library/bigquery-json.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_bigquery_datasets/google_bigquery_tables resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_bigquery_tables.md) Syntax ------ A `google_bigquery_tables` is used to test a Google Table resource Examples -------- ``` describe.one do google_bigquery_tables(project: 'chef-gcp-inspec', dataset: 'inspec_gcp_dataset').table_references.each do |table_reference| describe google_bigquery_table(project: 'chef-gcp-inspec', dataset: 'inspec_gcp_dataset', name: table_reference.table_id) do its('expiration_time') { should cmp '1738882264000' } its('description') { should eq 'A BigQuery table' } end end end ``` Properties ---------- Properties that can be accessed from the `google_bigquery_tables` resource: See the [google_bigquery_table](../google_bigquery_table/index#properties) resource for more information. `table_references` an array of `google_bigquery_table` table_reference `clusterings` an array of `google_bigquery_table` clustering `creation_times` an array of `google_bigquery_table` creation_time `friendly_names` an array of `google_bigquery_table` friendly_name `ids` an array of `google_bigquery_table` id `labels` an array of `google_bigquery_table` labels `last_modified_times` an array of `google_bigquery_table` last_modified_time `locations` an array of `google_bigquery_table` location `num_bytes` an array of `google_bigquery_table` num_bytes `num_long_term_bytes` an array of `google_bigquery_table` num_long_term_bytes `num_rows` an array of `google_bigquery_table` num_rows `require_partition_filters` an array of `google_bigquery_table` require_partition_filter `types` an array of `google_bigquery_table` type `views` an array of `google_bigquery_table` view `time_partitionings` an array of `google_bigquery_table` time_partitioning `streaming_buffers` an array of `google_bigquery_table` streaming_buffer `schemas` an array of `google_bigquery_table` schema `encryption_configurations` an array of `google_bigquery_table` encryption_configuration `expiration_times` an array of `google_bigquery_table` expiration_time `external_data_configurations` an array of `google_bigquery_table` external_data_configuration `datasets` an array of `google_bigquery_table` dataset Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [BigQuery API](https://console.cloud.google.com/apis/library/bigquery-json.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_bigquery_tables/google_cloud_scheduler_jobs resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_cloud_scheduler_jobs.md) Syntax ------ A `google_cloud_scheduler_jobs` is used to test a Google Job resource Examples -------- ``` google_cloud_scheduler_jobs(project: 'chef-gcp-inspec', region: ).names.each do |name| describe google_cloud_scheduler_job(project: 'chef-gcp-inspec', region: us-central1, name: name) do it { should exist } its('description') { should cmp 'A description' } its('schedule') { should cmp '*/8 * * * *' } its('time_zone') { should cmp 'America/New_York' } its('http_target.http_method') { should cmp 'POST' } its('http_target.uri') { should cmp 'https://example.com/ping' } end end ``` Properties ---------- Properties that can be accessed from the `google_cloud_scheduler_jobs` resource: See the [google_cloud_scheduler_job](../google_cloud_scheduler_job/index#properties) resource for more information. `names` an array of `google_cloud_scheduler_job` name `descriptions` an array of `google_cloud_scheduler_job` description `schedules` an array of `google_cloud_scheduler_job` schedule `time_zones` an array of `google_cloud_scheduler_job` time_zone `attempt_deadlines` an array of `google_cloud_scheduler_job` attempt_deadline `retry_configs` an array of `google_cloud_scheduler_job` retry_config `pubsub_targets` an array of `google_cloud_scheduler_job` pubsub_target `app_engine_http_targets` an array of `google_cloud_scheduler_job` app_engine_http_target `http_targets` an array of `google_cloud_scheduler_job` http_target `regions` an array of `google_cloud_scheduler_job` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_cloud_scheduler_jobs/google_cloudbuild_triggers resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_cloudbuild_triggers.md) Syntax ------ A `google_cloudbuild_triggers` is used to test a Google Trigger resource Examples -------- ``` describe google_cloudbuild_triggers(project: 'chef-gcp-inspec') do its('count') { should eq 1 } end google_cloudbuild_triggers(project: 'chef-gcp-inspec').ids.each do |id| describe google_cloudbuild_trigger(project: 'chef-gcp-inspec', id: id) do its('filename') { should eq 'cloudbuild.yaml' } its('trigger_template.branch_name') { should eq 'trigger-branch' } its('trigger_template.repo_name') { should eq 'trigger-repo' } its('trigger_template.project_id') { should eq 'trigger-project' } end end ``` Properties ---------- Properties that can be accessed from the `google_cloudbuild_triggers` resource: See the [google_cloudbuild_trigger](../google_cloudbuild_trigger/index#properties) resource for more information. `ids` an array of `google_cloudbuild_trigger` id `names` an array of `google_cloudbuild_trigger` name `descriptions` an array of `google_cloudbuild_trigger` description `disableds` an array of `google_cloudbuild_trigger` disabled `create_times` an array of `google_cloudbuild_trigger` create_time `substitutions` an array of `google_cloudbuild_trigger` substitutions `filenames` an array of `google_cloudbuild_trigger` filename `ignored_files` an array of `google_cloudbuild_trigger` ignored_files `included_files` an array of `google_cloudbuild_trigger` included_files `trigger_templates` an array of `google_cloudbuild_trigger` trigger_template `githubs` (Beta only) an array of `google_cloudbuild_trigger` github `builds` an array of `google_cloudbuild_trigger` build Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Build API](https://console.cloud.google.com/apis/library/cloudbuild.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_cloudbuild_triggers/google_cloudbuild_trigger resource ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_cloudbuild_trigger.md) Syntax ------ A `google_cloudbuild_trigger` is used to test a Google Trigger resource Examples -------- ``` describe google_cloudbuild_triggers(project: 'chef-gcp-inspec') do its('count') { should eq 1 } end google_cloudbuild_triggers(project: 'chef-gcp-inspec').ids.each do |id| describe google_cloudbuild_trigger(project: 'chef-gcp-inspec', id: id) do its('filename') { should eq 'cloudbuild.yaml' } its('trigger_template.branch_name') { should eq 'trigger-branch' } its('trigger_template.repo_name') { should eq 'trigger-repo' } its('trigger_template.project_id') { should eq 'trigger-project' } end end ``` Properties ---------- Properties that can be accessed from the `google_cloudbuild_trigger` resource: `id` The unique identifier for the trigger. `name` Name of the trigger. Must be unique within the project. `description` Human-readable description of the trigger. `disabled` Whether the trigger is disabled or not. If true, the trigger will never result in a build. `create_time` Time when the trigger was created. `substitutions` Substitutions data for Build resource. `filename` Path, from the source root, to a file whose contents is used for the template. Either a filename or build template must be provided. `ignored_files` ignoredFiles and includedFiles are file glob matches using <https://golang.org/pkg/path/filepath/#Match> extended with support for `**`. If ignoredFiles and changed files are both empty, then they are not used to determine whether or not to trigger a build. If ignoredFiles is not empty, then we ignore any files that match any of the ignored_file globs. If the change has no files that are outside of the ignoredFiles globs, then we do not trigger a build. `included_files` ignoredFiles and includedFiles are file glob matches using <https://golang.org/pkg/path/filepath/#Match> extended with support for `**`. If any of the files altered in the commit pass the ignoredFiles filter and includedFiles is empty, then as far as this filter is concerned, we should trigger the build. If any of the files altered in the commit pass the ignoredFiles filter and includedFiles is not empty, then we make sure that at least one of those files matches a includedFiles glob. If not, then we do not trigger a build. `trigger_template` Template describing the types of source changes to trigger a build. Branch and tag names in trigger templates are interpreted as regular expressions. Any branch or tag change that matches that regular expression will trigger a build. `project_id` ID of the project that owns the Cloud Source Repository. If omitted, the project ID requesting the build is assumed. `repo_name` Name of the Cloud Source Repository. If omitted, the name “default” is assumed. `dir` Directory, relative to the source root, in which to run the build. This must be a relative path. If a step’s dir is specified and is an absolute path, this value is ignored for that step’s execution. `branch_name` Name of the branch to build. Exactly one a of branch name, tag, or commit SHA must be provided. This field is a regular expression. `tag_name` Name of the tag to build. Exactly one of a branch name, tag, or commit SHA must be provided. This field is a regular expression. `commit_sha` Explicit commit SHA to build. Exactly one of a branch name, tag, or commit SHA must be provided. `github` (Beta only) Describes the configuration of a trigger that creates a build whenever a GitHub event is received. `owner` Owner of the repository. For example: The owner for <https://github.com/googlecloudplatform/cloud-builders> is “googlecloudplatform”. `name` Name of the repository. For example: The name for <https://github.com/googlecloudplatform/cloud-builders> is “cloud-builders”. `pull_request` filter to match changes in pull requests. Specify only one of pullRequest or push. `branch` Regex of branches to match. `comment_control` Whether to block builds on a “/gcbrun” comment from a repository owner or collaborator. Possible values: * COMMENTS_DISABLED * COMMENTS_ENABLED `push` filter to match changes in refs, like branches or tags. Specify only one of pullRequest or push. `branch` Regex of branches to match. Specify only one of branch or tag. `tag` Regex of tags to match. Specify only one of branch or tag. `build` Contents of the build template. Either a filename or build template must be provided. `tags` Tags for annotation of a Build. These are not docker tags. `images` A list of images to be pushed upon the successful completion of all build steps. The images are pushed using the builder service account’s credentials. The digests of the pushed images will be stored in the Build resource’s results field. If any of the images fail to be pushed, the build status is marked FAILURE. `timeout` Amount of time that this build should be allowed to run, to second granularity. If this amount of time elapses, work on the build will cease and the build status will be TIMEOUT. This timeout must be equal to or greater than the sum of the timeouts for build steps within the build. The expected format is the number of seconds followed by s. Default time is ten minutes (600s). `steps` The operations to be performed on the workspace. `name` The name of the container image that will run this particular build step. If the image is available in the host’s Docker daemon’s cache, it will be run directly. If not, the host will attempt to pull the image first, using the builder service account’s credentials if necessary. The Docker daemon’s cache will already have the latest versions of all of the officially supported build steps (<https://github.com/GoogleCloudPlatform/cloud-builders)>. The Docker daemon will also have cached many of the layers for some popular images, like “ubuntu”, “debian”, but they will be refreshed at the time you attempt to use them. If you built an image in a previous build step, it will be stored in the host’s Docker daemon’s cache and is available to use as the name for a later build step. `args` A list of arguments that will be presented to the step when it is started. If the image used to run the step’s container has an entrypoint, the args are used as arguments to that entrypoint. If the image does not define an entrypoint, the first element in args is used as the entrypoint, and the remainder will be used as arguments. `env` A list of environment variable definitions to be used when running a step. The elements are of the form “KEY=VALUE” for the environment variable “KEY” being given the value “VALUE”. `id` Unique identifier for this build step, used in `wait_for` to reference this build step as a dependency. `entrypoint` Entrypoint to be used instead of the build step image’s default entrypoint. If unset, the image’s default entrypoint is used `dir` Working directory to use when running this step’s container. If this value is a relative path, it is relative to the build’s working directory. If this value is absolute, it may be outside the build’s working directory, in which case the contents of the path may not be persisted across build step executions, unless a `volume` for that path is specified. If the build specifies a `RepoSource` with `dir` and a step with a `dir`, which specifies an absolute path, the `RepoSource` `dir` is ignored for the step’s execution. `secret_env` A list of environment variables which are encrypted using a Cloud Key Management Service crypto key. These values must be specified in the build’s `Secret`. `timeout` Time limit for executing this build step. If not defined, the step has no time limit and will be allowed to continue to run until either it completes or the build itself times out. `timing` Output only. Stores timing information for executing this build step. `volumes` List of volumes to mount into the build step. Each volume is created as an empty volume prior to execution of the build step. Upon completion of the build, volumes and their contents are discarded. Using a named volume in only one step is not valid as it is indicative of a build request with an incorrect configuration. `name` Name of the volume to mount. Volume names must be unique per build step and must be valid names for Docker volumes. Each named volume must be used by at least two build steps. `path` Path at which to mount the volume. Paths must be absolute and cannot conflict with other volume paths on the same build step or with certain reserved volume paths. `wait_for` The ID(s) of the step(s) that this build step depends on. This build step will not start until all the build steps in `wait_for` have completed successfully. If `wait_for` is empty, this build step will start when all previous build steps in the `Build.Steps` list have completed successfully. GCP Permissions --------------- Ensure the [Cloud Build API](https://console.cloud.google.com/apis/library/cloudbuild.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_cloudbuild_trigger/google_cloudfunctions_cloud_function resource ================================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_cloudfunctions_cloud_function.md) Syntax ------ A `google_cloudfunctions_cloud_function` is used to test a Google CloudFunction resource Examples -------- ``` describe google_cloudfunctions_cloud_function(project: 'chef-gcp-inspec', location: 'europe-west1', name: 'inspec-gcp-function') do it { should exist } its('description') { should eq 'A description of the function' } its('available_memory_mb') { should eq '128' } its('https_trigger.url') { should match /\/inspec-gcp-function$/ } its('entry_point') { should eq 'hello' } its('environment_variables') { should include('MY_ENV_VAR' => 'val1') } end describe google_cloudfunctions_cloud_function(project: 'chef-gcp-inspec', location: 'europe-west1', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_cloudfunctions_cloud_function` resource: `name` A user-defined name of the function. Function names must be unique globally and match pattern `projects/*/locations/*/functions/*`. `description` User-provided description of a function. `status` Status of the function deployment. Possible values: * CLOUD_FUNCTION_STATUS_UNSPECIFIED * ACTIVE * OFFLINE * DEPLOY_IN_PROGRESS * DELETE_IN_PROGRESS * UNKNOWN `entry_point` The name of the function (as defined in source code) that will be executed. Defaults to the resource name suffix, if not specified. For backward compatibility, if function with given name is not found, then the system will try to use function named “function”. For Node.js this is name of a function exported by the module specified in source_location. `runtime` The runtime in which the function is going to run. If empty, defaults to Node.js 6. `timeout` The function execution timeout. Execution is considered failed and can be terminated if the function is not completed at the end of the timeout period. Defaults to 60 seconds. `available_memory_mb` The amount of memory in MB available for a function. `service_account_email` The email of the service account for this function. `update_time` The last update timestamp of a Cloud Function `version_id` The version identifier of the Cloud Function. Each deployment attempt results in a new version of a function being created. `labels` A set of key/value label pairs associated with this Cloud Function. `environment_variables` Environment variables that shall be available during function execution. `source_archive_url` The Google Cloud Storage URL, starting with gs://, pointing to the zip archive which contains the function. `source_upload_url` The Google Cloud Storage signed URL used for source uploading. `source_repository` The source repository where a function is hosted. `url` The URL pointing to the hosted repository where the function is defined `deployed_url` The URL pointing to the hosted repository where the function were defined at the time of deployment. `https_trigger` An HTTPS endpoint type of source that can be triggered via URL. `url` The deployed url for the function. `event_trigger` An HTTPS endpoint type of source that can be triggered via URL. `event_type` The type of event to observe. For example: `providers/cloud.storage/eventTypes/object.change` and `providers/cloud.pubsub/eventTypes/topic.publish`. `resource` The resource(s) from which to observe events, for example, `projects/_/buckets/myBucket.` `service` The hostname of the service that should be observed. `location` The location of this cloud function. GCP Permissions --------------- Ensure the [Cloud Functions API](https://console.cloud.google.com/apis/library/cloudfunctions.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_cloudfunctions_cloud_function/google_cloudfunctions_cloud_functions resource ================================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_cloudfunctions_cloud_functions.md) Syntax ------ A `google_cloudfunctions_cloud_functions` is used to test a Google CloudFunction resource Examples -------- ``` describe google_cloudfunctions_cloud_functions(project: 'chef-gcp-inspec', location: 'europe-west1') do its('descriptions') { should include 'A description of the function' } its('entry_points') { should include 'hello' } end ``` Properties ---------- Properties that can be accessed from the `google_cloudfunctions_cloud_functions` resource: See the [google_cloudfunctions_cloud_function](../google_cloudfunctions_cloud_function/index#properties) resource for more information. `names` an array of `google_cloudfunctions_cloud_function` name `descriptions` an array of `google_cloudfunctions_cloud_function` description `statuses` an array of `google_cloudfunctions_cloud_function` status `entry_points` an array of `google_cloudfunctions_cloud_function` entry_point `runtimes` an array of `google_cloudfunctions_cloud_function` runtime `timeouts` an array of `google_cloudfunctions_cloud_function` timeout `available_memory_mbs` an array of `google_cloudfunctions_cloud_function` available_memory_mb `service_account_emails` an array of `google_cloudfunctions_cloud_function` service_account_email `update_times` an array of `google_cloudfunctions_cloud_function` update_time `version_ids` an array of `google_cloudfunctions_cloud_function` version_id `labels` an array of `google_cloudfunctions_cloud_function` labels `environment_variables` an array of `google_cloudfunctions_cloud_function` environment_variables `source_archive_urls` an array of `google_cloudfunctions_cloud_function` source_archive_url `source_upload_urls` an array of `google_cloudfunctions_cloud_function` source_upload_url `source_repositories` an array of `google_cloudfunctions_cloud_function` source_repository `https_triggers` an array of `google_cloudfunctions_cloud_function` https_trigger `event_triggers` an array of `google_cloudfunctions_cloud_function` event_trigger `locations` an array of `google_cloudfunctions_cloud_function` location Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Functions API](https://console.cloud.google.com/apis/library/cloudfunctions.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_cloudfunctions_cloud_functions/google_compute_address resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_address.md) Syntax ------ A `google_compute_address` is used to test a Google Address resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_address(project: 'chef-gcp-inspec', location: 'europe-west2', name: 'inspec-gcp-global-address') do it { should exist } its('address') { should eq '10.2.0.3' } its('address_type') { should eq 'INTERNAL' } its('user_count') { should eq 0 } end describe google_compute_address(project: 'chef-gcp-inspec', location: 'europe-west2', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP compute address IP exists ``` describe google_compute_address(project: 'chef-inspec-gcp', location: 'europe-west2', name: 'compute-address') do its('address_ip_exists') { should be true } end ``` ### Test that a GCP compute address is in a particular status ``` describe google_compute_address(project: 'chef-inspec-gcp', location: 'europe-west2', name: 'compute-address') do its('status') { should eq "IN_USE" } end ``` ### Test that a GCP compute address IP has the expected number of users ``` describe google_compute_address(project: 'chef-inspec-gcp', location: 'europe-west2', name: 'compute-address') do its('user_count') { should eq 1 } end ``` ### Test that the first user of a GCP compute address has the expected resource name ``` describe google_compute_address(project: 'chef-inspec-gcp', location: 'europe-west2', name: 'compute-address') do its('user_resource_name') { should eq "gcp_ext_vm_name" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_address` resource: `address` The static external IP address represented by this resource. Only IPv4 is supported. An address may only be specified for INTERNAL address types. The IP address must be inside the specified subnetwork, if any. `address_type` The type of address to reserve. Possible values: * INTERNAL * EXTERNAL `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. `id` The unique identifier for the resource. `name` Name of the resource. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `purpose` The purpose of this resource, which can be one of the following values: - GCE_ENDPOINT for addresses that are used by VM instances, alias IP ranges, internal load balancers, and similar resources. This should only be set when using an Internal address. Possible values: * GCE_ENDPOINT `network_tier` The networking tier used for configuring this address. If this field is not specified, it is assumed to be PREMIUM. Possible values: * PREMIUM * STANDARD `subnetwork` The URL of the subnetwork in which to reserve the address. If an IP address is specified, it must be within the subnetwork’s IP range. This field can only be used with INTERNAL type with GCE_ENDPOINT/DNS_RESOLVER purposes. `users` The URLs of the resources that are using this address. `labels` (Beta only) Labels to apply to this address. A list of key->value pairs. `label_fingerprint` (Beta only) The fingerprint used for optimistic locking of this resource. Used internally during updates. `status` The status of the address, which can be one of RESERVING, RESERVED, or IN_USE. An address that is RESERVING is currently in the process of being reserved. A RESERVED address is currently reserved and available to use. An IN_USE address is currently being used by another resource and is not available. Possible values: * RESERVING * RESERVED * IN_USE `region` URL of the region where the regional address resides. This field is not applicable to global addresses. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_address/google_compute_addresses resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_addresses.md) Syntax ------ A `google_compute_addresses` is used to test a Google Address resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_addresses(project: 'chef-gcp-inspec', location: 'europe-west2') do its('addresses') { should include '10.2.0.3' } its('names') { should include 'inspec-gcp-global-address' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_addresses` resource: See the [google_compute_address](../google_compute_address/index#properties) resource for more information. `addresses` an array of `google_compute_address` address `address_types` an array of `google_compute_address` address_type `creation_timestamps` an array of `google_compute_address` creation_timestamp `descriptions` an array of `google_compute_address` description `ids` an array of `google_compute_address` id `names` an array of `google_compute_address` name `purposes` an array of `google_compute_address` purpose `network_tiers` an array of `google_compute_address` network_tier `subnetworks` an array of `google_compute_address` subnetwork `users` an array of `google_compute_address` users `labels` (Beta only) an array of `google_compute_address` labels `label_fingerprints` (Beta only) an array of `google_compute_address` label_fingerprint `statuses` an array of `google_compute_address` status `regions` an array of `google_compute_address` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_addresses/google_compute_autoscalers resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_autoscalers.md) Syntax ------ A `google_compute_autoscalers` is used to test a Google Autoscaler resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` autoscalers = google_compute_autoscalers(project: 'chef-gcp-inspec', zone: 'zone') describe.one do autoscalers.autoscaling_policies.each do |autoscaling_policy| describe autoscaling_policy do its('max_num_replicas') { should eq '5' } its('min_num_replicas') { should eq '1' } its('cool_down_period_sec') { should eq '60' } its('cpu_utilization.utilization_target') { should eq '0.5' } end end end ``` Properties ---------- Properties that can be accessed from the `google_compute_autoscalers` resource: See the [google_compute_autoscaler](../google_compute_autoscaler/index#properties) resource for more information. `ids` an array of `google_compute_autoscaler` id `creation_timestamps` an array of `google_compute_autoscaler` creation_timestamp `names` an array of `google_compute_autoscaler` name `descriptions` an array of `google_compute_autoscaler` description `autoscaling_policies` an array of `google_compute_autoscaler` autoscaling_policy `targets` an array of `google_compute_autoscaler` target `zones` an array of `google_compute_autoscaler` zone Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_autoscalers/google_compute_backend_buckets resource ========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_backend_buckets.md) Syntax ------ A `google_compute_backend_buckets` is used to test a Google BackendBucket resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_backend_buckets(project: 'chef-gcp-inspec', name: 'inspec-gcp-backend-bucket') do its('descriptions') { should include 'Backend bucket example' } its('bucket_names') { should include 'gcp-inspec-storage-bucket' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_backend_buckets` resource: See the [google_compute_backend_bucket](../google_compute_backend_bucket/index#properties) resource for more information. `bucket_names` an array of `google_compute_backend_bucket` bucket_name `cdn_policies` an array of `google_compute_backend_bucket` cdn_policy `creation_timestamps` an array of `google_compute_backend_bucket` creation_timestamp `descriptions` an array of `google_compute_backend_bucket` description `enable_cdns` an array of `google_compute_backend_bucket` enable_cdn `ids` an array of `google_compute_backend_bucket` id `names` an array of `google_compute_backend_bucket` name Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_backend_buckets/google_compute_autoscaler resource ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_autoscaler.md) Syntax ------ A `google_compute_autoscaler` is used to test a Google Autoscaler resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_autoscaler(project: 'chef-gcp-inspec', zone: 'zone', name: 'inspec-gcp-autoscaler') do it { should exist } its('target') { should match /\/inspec-gcp-igm$/ } its('autoscaling_policy.max_num_replicas') { should eq '5' } its('autoscaling_policy.min_num_replicas') { should eq '1' } its('autoscaling_policy.cool_down_period_sec') { should eq '60' } its('autoscaling_policy.cpu_utilization.utilization_target') { should eq '0.5' } end describe google_compute_autoscaler(project: 'chef-gcp-inspec', zone: 'zone', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_autoscaler` resource: `id` Unique identifier for the resource. `creation_timestamp` Creation timestamp in RFC3339 text format. `name` Name of the resource. The name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `description` An optional description of this resource. `autoscaling_policy` The configuration parameters for the autoscaling algorithm. You can define one or more of the policies for an autoscaler: cpuUtilization, customMetricUtilizations, and loadBalancingUtilization. If none of these are specified, the default will be to autoscale based on cpuUtilization to 0.6 or 60%. `min_num_replicas` The minimum number of replicas that the autoscaler can scale down to. This cannot be less than 0. If not provided, autoscaler will choose a default value depending on maximum number of instances allowed. `max_num_replicas` The maximum number of instances that the autoscaler can scale up to. This is required when creating or updating an autoscaler. The maximum number of replicas should not be lower than minimal number of replicas. `cool_down_period_sec` The number of seconds that the autoscaler should wait before it starts collecting information from a new instance. This prevents the autoscaler from collecting information when the instance is initializing, during which the collected usage would not be reliable. The default time autoscaler waits is 60 seconds. Virtual machine initialization times might vary because of numerous factors. We recommend that you test how long an instance may take to initialize. To do this, create an instance and time the startup process. `cpu_utilization` Defines the CPU utilization policy that allows the autoscaler to scale based on the average CPU utilization of a managed instance group. `utilization_target` The target CPU utilization that the autoscaler should maintain. Must be a float value in the range (0, 1]. If not specified, the default is 0.6. If the CPU level is below the target utilization, the autoscaler scales down the number of instances until it reaches the minimum number of instances you specified or until the average CPU of your instances reaches the target utilization. If the average CPU is above the target utilization, the autoscaler scales up until it reaches the maximum number of instances you specified or until the average utilization reaches the target utilization. `custom_metric_utilizations` Configuration parameters of autoscaling based on a custom metric. `metric` The identifier (type) of the Stackdriver Monitoring metric. The metric cannot have negative values. The metric must have a value type of INT64 or DOUBLE. `single_instance_assignment` (Beta only) If scaling is based on a per-group metric value that represents the total amount of work to be done or resource usage, set this value to an amount assigned for a single instance of the scaled group. The autoscaler will keep the number of instances proportional to the value of this metric, the metric itself should not change value due to group resizing. For example, a good metric to use with the target is `pubsub.googleapis.com/subscription/num_undelivered_messages` or a custom metric exporting the total number of requests coming to your instances. A bad example would be a metric exporting an average or median latency, since this value can’t include a chunk assignable to a single instance, it could be better used with utilization_target instead. `utilization_target` The target value of the metric that autoscaler should maintain. This must be a positive value. A utilization metric scales number of virtual machines handling requests to increase or decrease proportionally to the metric. For example, a good metric to use as a utilizationTarget is [www.googleapis.com/compute/instance/network/received_bytes_count](http://www.googleapis.com/compute/instance/network/received_bytes_count). The autoscaler will work to keep this value constant for each of the instances. `utilization_target_type` Defines how target utilization value is expressed for a Stackdriver Monitoring metric. Possible values: * GAUGE * DELTA_PER_SECOND * DELTA_PER_MINUTE `filter` (Beta only) A filter string to be used as the filter string for a Stackdriver Monitoring TimeSeries.list API call. This filter is used to select a specific TimeSeries for the purpose of autoscaling and to determine whether the metric is exporting per-instance or per-group data. You can only use the AND operator for joining selectors. You can only use direct equality comparison operator (=) without any functions for each selector. You can specify the metric in both the filter string and in the metric field. However, if specified in both places, the metric must be identical. The monitored resource type determines what kind of values are expected for the metric. If it is a gce_instance, the autoscaler expects the metric to include a separate TimeSeries for each instance in a group. In such a case, you cannot filter on resource labels. If the resource type is any other value, the autoscaler expects this metric to contain values that apply to the entire autoscaled instance group and resource label filtering can be performed to point autoscaler at the correct TimeSeries to scale upon. This is called a per-group metric for the purpose of autoscaling. If not specified, the type defaults to gce_instance. You should provide a filter that is selective enough to pick just one TimeSeries for the autoscaled group or for each of the instances (if you are using gce_instance resource type). If multiple TimeSeries are returned upon the query execution, the autoscaler will sum their respective values to obtain its scaling value. `load_balancing_utilization` Configuration parameters of autoscaling based on a load balancer. `utilization_target` Fraction of backend capacity utilization (set in HTTP(s) load balancing configuration) that autoscaler should maintain. Must be a positive float value. If not defined, the default is 0.8. `target` URL of the managed instance group that this autoscaler will scale. `zone` URL of the zone where the instance group resides. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_autoscaler/google_compute_backend_service resource ========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_backend_service.md) Syntax ------ A `google_compute_backend_service` is used to test a Google BackendService resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_backend_service(project: 'chef-gcp-inspec', name: 'inspec-gcp-backend-service') do it { should exist } its('description') { should eq 'A description' } its('port_name') { should eq 'http' } its('protocol') { should eq 'HTTP' } its('timeout_sec') { should eq '10' } its('enable_cdn') { should eq 'true' } end describe google_compute_backend_service(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_backend_service` resource: `affinity_cookie_ttl_sec` Lifetime of cookies in seconds if session_affinity is GENERATED_COOKIE. If set to 0, the cookie is non-persistent and lasts only until the end of the browser session (or equivalent). The maximum allowed value for TTL is one day. When the load balancing scheme is INTERNAL, this field is not used. `backends` The set of backends that serve this BackendService. `balancing_mode` Specifies the balancing mode for this backend. For global HTTP(S) or TCP/SSL load balancing, the default is UTILIZATION. Valid values are UTILIZATION, RATE (for HTTP(S)) and CONNECTION (for TCP/SSL). Possible values: * UTILIZATION * RATE * CONNECTION `capacity_scaler` A multiplier applied to the group’s maximum servicing capacity (based on UTILIZATION, RATE or CONNECTION). Default value is 1, which means the group will serve up to 100% of its configured capacity (depending on balancingMode). A setting of 0 means the group is completely drained, offering 0% of its available Capacity. Valid range is [0.0,1.0]. `description` An optional description of this resource. Provide this property when you create the resource. `group` The fully-qualified URL of an Instance Group or Network Endpoint Group resource. In case of instance group this defines the list of instances that serve traffic. Member virtual machine instances from each instance group must live in the same zone as the instance group itself. No two backends in a backend service are allowed to use same Instance Group resource. For Network Endpoint Groups this defines list of endpoints. All endpoints of Network Endpoint Group must be hosted on instances located in the same zone as the Network Endpoint Group. Backend services cannot mix Instance Group and Network Endpoint Group backends. Note that you must specify an Instance Group or Network Endpoint Group resource using the fully-qualified URL, rather than a partial URL. `max_connections` The max number of simultaneous connections for the group. Can be used with either CONNECTION or UTILIZATION balancing modes. For CONNECTION mode, either maxConnections or one of maxConnectionsPerInstance or maxConnectionsPerEndpoint, as appropriate for group type, must be set. `max_connections_per_instance` The max number of simultaneous connections that a single backend instance can handle. This is used to calculate the capacity of the group. Can be used in either CONNECTION or UTILIZATION balancing modes. For CONNECTION mode, either maxConnections or maxConnectionsPerInstance must be set. `max_connections_per_endpoint` The max number of simultaneous connections that a single backend network endpoint can handle. This is used to calculate the capacity of the group. Can be used in either CONNECTION or UTILIZATION balancing modes. For CONNECTION mode, either maxConnections or maxConnectionsPerEndpoint must be set. `max_rate` The max requests per second (RPS) of the group. Can be used with either RATE or UTILIZATION balancing modes, but required if RATE mode. For RATE mode, either maxRate or one of maxRatePerInstance or maxRatePerEndpoint, as appropriate for group type, must be set. `max_rate_per_instance` The max requests per second (RPS) that a single backend instance can handle. This is used to calculate the capacity of the group. Can be used in either balancing mode. For RATE mode, either maxRate or maxRatePerInstance must be set. `max_rate_per_endpoint` The max requests per second (RPS) that a single backend network endpoint can handle. This is used to calculate the capacity of the group. Can be used in either balancing mode. For RATE mode, either maxRate or maxRatePerEndpoint must be set. `max_utilization` Used when balancingMode is UTILIZATION. This ratio defines the CPU utilization target for the group. The default is 0.8. Valid range is [0.0, 1.0]. `circuit_breakers` Settings controlling the volume of connections to a backend service. This field is applicable only when the load_balancing_scheme is set to INTERNAL_SELF_MANAGED. `connect_timeout` (Beta only) The timeout for new network connections to hosts. `seconds` Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive. `nanos` Span of time that’s a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0 seconds field and a positive nanos field. Must be from 0 to 999,999,999 inclusive. `max_requests_per_connection` Maximum requests for a single backend connection. This parameter is respected by both the HTTP/1.1 and HTTP/2 implementations. If not specified, there is no limit. Setting this parameter to 1 will effectively disable keep alive. `max_connections` The maximum number of connections to the backend cluster. Defaults to 1024. `max_pending_requests` The maximum number of pending requests to the backend cluster. Defaults to 1024. `max_requests` The maximum number of parallel requests to the backend cluster. Defaults to 1024. `max_retries` The maximum number of parallel retries to the backend cluster. Defaults to 3. `consistent_hash` Consistent Hash -based load balancing can be used to provide soft session affinity based on HTTP headers, cookies or other properties. This load balancing policy is applicable only for HTTP connections. The affinity to a particular destination host will be lost when one or more hosts are added/removed from the destination service. This field specifies parameters that control consistent hashing. This field only applies if the load_balancing_scheme is set to INTERNAL_SELF_MANAGED. This field is only applicable when locality_lb_policy is set to MAGLEV or RING_HASH. `http_cookie` Hash is based on HTTP Cookie. This field describes a HTTP cookie that will be used as the hash key for the consistent hash load balancer. If the cookie is not present, it will be generated. This field is applicable if the sessionAffinity is set to HTTP_COOKIE. `ttl` Lifetime of the cookie. `seconds` Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive. `nanos` Span of time that’s a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0 seconds field and a positive nanos field. Must be from 0 to 999,999,999 inclusive. `name` Name of the cookie. `path` Path to set for the cookie. `http_header_name` The hash based on the value of the specified header field. This field is applicable if the sessionAffinity is set to HEADER_FIELD. `minimum_ring_size` The minimum number of virtual nodes to use for the hash ring. Larger ring sizes result in more granular load distributions. If the number of hosts in the load balancing pool is larger than the ring size, each host will be assigned a single virtual node. Defaults to 1024. `cdn_policy` Cloud CDN configuration for this BackendService. `cache_key_policy` The CacheKeyPolicy for this CdnPolicy. `include_host` If true requests to different hosts will be cached separately. `include_protocol` If true, http and https requests will be cached separately. `include_query_string` If true, include query string parameters in the cache key according to query_string_whitelist and query_string_blacklist. If neither is set, the entire query string will be included. If false, the query string will be excluded from the cache key entirely. `query_string_blacklist` Names of query string parameters to exclude in cache keys. All other parameters will be included. Either specify query_string_whitelist or query_string_blacklist, not both. ‘&’ and ‘=’ will be percent encoded and not treated as delimiters. `query_string_whitelist` Names of query string parameters to include in cache keys. All other parameters will be excluded. Either specify query_string_whitelist or query_string_blacklist, not both. ‘&’ and ‘=’ will be percent encoded and not treated as delimiters. `signed_url_cache_max_age_sec` Maximum number of seconds the response to a signed URL request will be considered fresh, defaults to 1hr (3600s). After this time period, the response will be revalidated before being served. When serving responses to signed URL requests, Cloud CDN will internally behave as though all responses from this backend had a “Cache-Control: public, max-age=[TTL]” header, regardless of any existing Cache-Control header. The actual headers served in responses will not be altered. `connection_draining` Settings for connection draining `draining_timeout_sec` Time for which instance will be drained (not accept new connections, but still work to finish started). `creation_timestamp` Creation timestamp in RFC3339 text format. `custom_request_headers` Headers that the HTTP/S load balancer should add to proxied requests. `fingerprint` Fingerprint of this resource. A hash of the contents stored in this object. This field is used in optimistic locking. `description` An optional description of this resource. `enable_cdn` If true, enable Cloud CDN for this BackendService. `health_checks` The set of URLs to the HttpHealthCheck or HttpsHealthCheck resource for health checking this BackendService. Currently at most one health check can be specified, and a health check is required. For internal load balancing, a URL to a HealthCheck resource must be specified instead. `id` The unique identifier for the resource. `iap` Settings for enabling Cloud Identity Aware Proxy `enabled` Enables IAP. `oauth2_client_id` OAuth2 Client ID for IAP `oauth2_client_secret` OAuth2 Client Secret for IAP `oauth2_client_secret_sha256` OAuth2 Client Secret SHA-256 for IAP `load_balancing_scheme` Indicates whether the backend service will be used with internal or external load balancing. A backend service created for one type of load balancing cannot be used with the other. Possible values: * EXTERNAL * INTERNAL_SELF_MANAGED `locality_lb_policy` The load balancing algorithm used within the scope of the locality. The possible values are - ROUND_ROBIN - This is a simple policy in which each healthy backend is selected in round robin order. LEAST_REQUEST - An O(1) algorithm which selects two random healthy hosts and picks the host which has fewer active requests. RING_HASH - The ring/modulo hash load balancer implements consistent hashing to backends. The algorithm has the property that the addition/removal of a host from a set of N hosts only affects 1/N of the requests. RANDOM - The load balancer selects a random healthy host. ORIGINAL_DESTINATION - Backend host is selected based on the client connection metadata, i.e., connections are opened to the same address as the destination address of the incoming connection before the connection was redirected to the load balancer. MAGLEV - used as a drop in replacement for the ring hash load balancer. Maglev is not as stable as ring hash but has faster table lookup build times and host selection times. For more information about Maglev, refer to <https://ai.google/research/pubs/pub44824> This field is applicable only when the load_balancing_scheme is set to INTERNAL_SELF_MANAGED. Possible values: * ROUND_ROBIN * LEAST_REQUEST * RING_HASH * RANDOM * ORIGINAL_DESTINATION * MAGLEV `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `outlier_detection` Settings controlling eviction of unhealthy hosts from the load balancing pool. This field is applicable only when the load_balancing_scheme is set to INTERNAL_SELF_MANAGED. `base_ejection_time` The base time that a host is ejected for. The real time is equal to the base time multiplied by the number of times the host has been ejected. Defaults to 30000ms or 30s. `seconds` Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive. `nanos` Span of time that’s a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0 `seconds` field and a positive `nanos` field. Must be from 0 to 999,999,999 inclusive. `consecutive_errors` Number of errors before a host is ejected from the connection pool. When the backend host is accessed over HTTP, a 5xx return code qualifies as an error. Defaults to 5. `consecutive_gateway_failure` The number of consecutive gateway failures (502, 503, 504 status or connection errors that are mapped to one of those status codes) before a consecutive gateway failure ejection occurs. Defaults to 5. `enforcing_consecutive_errors` The percentage chance that a host will be actually ejected when an outlier status is detected through consecutive 5xx. This setting can be used to disable ejection or to ramp it up slowly. Defaults to 100. `enforcing_consecutive_gateway_failure` The percentage chance that a host will be actually ejected when an outlier status is detected through consecutive gateway failures. This setting can be used to disable ejection or to ramp it up slowly. Defaults to 0. `enforcing_success_rate` The percentage chance that a host will be actually ejected when an outlier status is detected through success rate statistics. This setting can be used to disable ejection or to ramp it up slowly. Defaults to 100. `interval` Time interval between ejection sweep analysis. This can result in both new ejections as well as hosts being returned to service. Defaults to 10 seconds. `seconds` Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive. `nanos` Span of time that’s a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0 `seconds` field and a positive `nanos` field. Must be from 0 to 999,999,999 inclusive. `max_ejection_percent` Maximum percentage of hosts in the load balancing pool for the backend service that can be ejected. Defaults to 10%. `success_rate_minimum_hosts` The number of hosts in a cluster that must have enough request volume to detect success rate outliers. If the number of hosts is less than this setting, outlier detection via success rate statistics is not performed for any host in the cluster. Defaults to 5. `success_rate_request_volume` The minimum number of total requests that must be collected in one interval (as defined by the interval duration above) to include this host in success rate based outlier detection. If the volume is lower than this setting, outlier detection via success rate statistics is not performed for that host. Defaults to 100. `success_rate_stdev_factor` This factor is used to determine the ejection threshold for success rate outlier ejection. The ejection threshold is the difference between the mean success rate, and the product of this factor and the standard deviation of the mean success rate: mean - (stdev * success_rate_stdev_factor). This factor is divided by a thousand to get a double. That is, if the desired factor is 1.9, the runtime value should be 1900. Defaults to 1900. `port_name` Name of backend port. The same name should appear in the instance groups referenced by this service. Required when the load balancing scheme is EXTERNAL. `protocol` The protocol this BackendService uses to communicate with backends. The default is HTTP. **NOTE**: HTTP2 is only valid for beta HTTP/2 load balancer types and may result in errors if used with the GA API. Possible values: * HTTP * HTTPS * HTTP2 * TCP * SSL `security_policy` The security policy associated with this backend service. `session_affinity` Type of session affinity to use. The default is NONE. Session affinity is not applicable if the protocol is UDP. Possible values: * NONE * CLIENT_IP * CLIENT_IP_PORT_PROTO * CLIENT_IP_PROTO * GENERATED_COOKIE * HEADER_FIELD * HTTP_COOKIE `timeout_sec` How many seconds to wait for the backend before considering it a failed request. Default is 30 seconds. Valid range is [1, 86400]. `log_config` This field denotes the logging options for the load balancer traffic served by this backend service. If logging is enabled, logs will be exported to Stackdriver. `enable` Whether to enable logging for the load balancer traffic served by this backend service. `sample_rate` This field can only be specified if logging is enabled for this backend service. The value of the field must be in [0, 1]. This configures the sampling rate of requests to the load balancer where 1.0 means all logged requests are reported and 0.0 means no logged requests are reported. The default value is 1.0. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_backend_service/azurerm_webapps resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/azurerm_webapps.md) Use the `azurerm_webapps` InSpec audit resource to enumerate Webapps. Azure REST API version ---------------------- This resource interacts with version `2016-08-01` of the Azure Management API. For more information see the [official Azure documentation](https://docs.microsoft.com/en-us/rest/api/appservice/webapps/listbyresourcegroup). At the moment, there doesn’t appear to be a way to select the version of the Azure API docs. If you notice a newer version being referenced in the official documentation please open an issue or submit a pull request using the updated version. Availability ------------ ### Installation This resource is available in the `inspec-azure` [resource pack](../../glossary/index#resource-pack). To use it, add the following to your `inspec.yml` in your top-level profile: ``` depends: inspec-azure: git: https://github.com/inspec/inspec-azure.git ``` You’ll also need to setup your Azure credentials; see the resource pack [README](https://github.com/inspec/inspec-azure#inspec-for-azure). Syntax ------ An `azurerm_webapps` resource block identifies Webapps by Resource Group. ``` describe azurerm_webapps(resource_group: 'ExampleGroup') do ... end ``` Examples -------- ### Test that an example Resource Group has the named Webapps ``` describe azurerm_webapps(resource_group: 'ExampleGroup') do its('names') { should include('webapp_name') } end ``` Properties ---------- * `names` ### names The name of the Webapp ``` its('names') { should include('webapp_name') } ``` Matchers -------- This InSpec audit resource has the following special matchers. For a full list of available matchers, please visit our [Universal Matchers page](../../matchers/index). ### exists The control will pass if the resource returns a result. Use `should_not` if you expect zero matches. ``` # If we expect 'ExampleGroup' Resource Group to have Webapps describe azurerm_webapps(resource_group: 'ExampleGroup') do it { should exist } end # If we expect 'EmptyExampleGroup' Resource Group to not have Webapps describe azurerm_webapps(resource_group: 'EmptyExampleGroup') do it { should_not exist } end ``` Azure Permissions ----------------- Your [Service Principal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal) must be setup with a `contributor` role on the subscription you wish to test. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/azurerm_webapps/google_compute_backend_bucket resource ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_backend_bucket.md) Syntax ------ A `google_compute_backend_bucket` is used to test a Google BackendBucket resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_backend_bucket(project: 'chef-gcp-inspec', name: 'inspec-gcp-backend-bucket') do it { should exist } its('description') { should eq 'Backend bucket example' } its('enable_cdn') { should be 'true' } its('bucket_name') { should eq 'gcp-inspec-storage-bucket' } end describe google_compute_backend_bucket(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_backend_bucket` resource: `bucket_name` Cloud Storage bucket name. `cdn_policy` Cloud CDN configuration for this Backend Bucket. `signed_url_cache_max_age_sec` Maximum number of seconds the response to a signed URL request will be considered fresh. After this time period, the response will be revalidated before being served. When serving responses to signed URL requests, Cloud CDN will internally behave as though all responses from this backend had a “Cache-Control: public, max-age=[TTL]” header, regardless of any existing Cache-Control header. The actual headers served in responses will not be altered. `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional textual description of the resource; provided by the client when the resource is created. `enable_cdn` If true, enable Cloud CDN for this BackendBucket. `id` Unique identifier for the resource. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_backend_bucket/google_compute_backend_services resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_backend_services.md) Syntax ------ A `google_compute_backend_services` is used to test a Google BackendService resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_backend_services(project: 'chef-gcp-inspec') do its('count') { should be >= 1 } its('names') { should include 'inspec-gcp-backend-service' } its('port_names') { should include 'http' } its('protocols') { should include 'HTTP' } its('timeout_secs') { should include '10' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_backend_services` resource: See the [google_compute_backend_service](../google_compute_backend_service/index#properties) resource for more information. `affinity_cookie_ttl_secs` an array of `google_compute_backend_service` affinity_cookie_ttl_sec `backends` an array of `google_compute_backend_service` backends `circuit_breakers` an array of `google_compute_backend_service` circuit_breakers `consistent_hashes` an array of `google_compute_backend_service` consistent_hash `cdn_policies` an array of `google_compute_backend_service` cdn_policy `connection_drainings` an array of `google_compute_backend_service` connection_draining `creation_timestamps` an array of `google_compute_backend_service` creation_timestamp `custom_request_headers` an array of `google_compute_backend_service` custom_request_headers `fingerprints` an array of `google_compute_backend_service` fingerprint `descriptions` an array of `google_compute_backend_service` description `enable_cdns` an array of `google_compute_backend_service` enable_cdn `health_checks` an array of `google_compute_backend_service` health_checks `ids` an array of `google_compute_backend_service` id `iaps` an array of `google_compute_backend_service` iap `load_balancing_schemes` an array of `google_compute_backend_service` load_balancing_scheme `locality_lb_policies` an array of `google_compute_backend_service` locality_lb_policy `names` an array of `google_compute_backend_service` name `outlier_detections` an array of `google_compute_backend_service` outlier_detection `port_names` an array of `google_compute_backend_service` port_name `protocols` an array of `google_compute_backend_service` protocol `security_policies` an array of `google_compute_backend_service` security_policy `session_affinities` an array of `google_compute_backend_service` session_affinity `timeout_secs` an array of `google_compute_backend_service` timeout_sec `log_configs` an array of `google_compute_backend_service` log_config Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_backend_services/google_compute_disks resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_disks.md) Syntax ------ A `google_compute_disks` is used to test a Google Disk resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` most_recent_image = google_compute_image(project: 'debian-cloud', name: 'debian-10-buster-v20191014') describe google_compute_disks(project: 'chef-gcp-inspec', zone: 'zone') do it { should exist } its('names') { should include 'inspec-snapshot-disk' } its('source_images') { should include most_recent_image.self_link } end ``` Properties ---------- Properties that can be accessed from the `google_compute_disks` resource: See the [google_compute_disk](../google_compute_disk/index#properties) resource for more information. `label_fingerprints` an array of `google_compute_disk` label_fingerprint `creation_timestamps` an array of `google_compute_disk` creation_timestamp `descriptions` an array of `google_compute_disk` description `ids` an array of `google_compute_disk` id `last_attach_timestamps` an array of `google_compute_disk` last_attach_timestamp `last_detach_timestamps` an array of `google_compute_disk` last_detach_timestamp `labels` an array of `google_compute_disk` labels `licenses` an array of `google_compute_disk` licenses `names` an array of `google_compute_disk` name `size_gbs` an array of `google_compute_disk` size_gb `users` an array of `google_compute_disk` users `physical_block_size_bytes` an array of `google_compute_disk` physical_block_size_bytes `types` an array of `google_compute_disk` type `source_images` an array of `google_compute_disk` source_image `resource_policies` (Beta only) an array of `google_compute_disk` resource_policies `zones` an array of `google_compute_disk` zone `source_image_encryption_keys` an array of `google_compute_disk` source_image_encryption_key `source_image_ids` an array of `google_compute_disk` source_image_id `disk_encryption_keys` an array of `google_compute_disk` disk_encryption_key `source_snapshots` an array of `google_compute_disk` source_snapshot `source_snapshot_encryption_keys` an array of `google_compute_disk` source_snapshot_encryption_key `source_snapshot_ids` an array of `google_compute_disk` source_snapshot_id Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_disks/google_compute_forwarding_rule resource ========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_forwarding_rule.md) Syntax ------ A `google_compute_forwarding_rule` is used to test a Google ForwardingRule resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_forwarding_rule(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'udp-forwarding-rule') do it { should exist } its('region') { should match 'europe-west2' } its('creation_timestamp') { should be > Time.now - 365*60*60*24*10 } its('load_balancing_scheme') { should match 'EXTERNAL' } its('port_range') { should match "500-500" } its('ip_protocol') { should match "UDP" } end describe google_compute_forwarding_rule(project: 'chef-gcp-inspec', region: 'europe-west2', name: "nonexistent") do it { should_not exist } end ``` ### Test that a GCP compute forwarding_rule exists ``` describe google_compute_forwarding_rule(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-forwarding_rule') do it { should exist } end ``` ### Test when a GCP compute forwarding_rule was created ``` describe google_compute_forwarding_rule(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-forwarding_rule') do its('creation_timestamp_date') { should be > Time.now - 365*60*60*24*10 } end ``` ### Test for an expected forwarding_rule identifier ``` describe google_compute_forwarding_rule(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-forwarding_rule') do its('id') { should eq 12345567789 } end ``` ### Test that a forwarding_rule load_balancing_scheme is as expected ``` describe google_compute_forwarding_rule(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-forwarding_rule') do its('load_balancing_scheme') { should eq "INTERNAL" } end ``` ### Test that a forwarding_rule IP address is as expected ``` describe google_compute_forwarding_rule(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-forwarding_rule') do its('ip_address') { should eq "10.0.0.1" } end ``` ### Test that a forwarding_rule is associated with the expected network ``` describe google_compute_forwarding_rule(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-forwarding_rule') do its('network') { should match "gcp_network_name" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_forwarding_rule` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `is_mirroring_collector` (Beta only) Indicates whether or not this load balancer can be used as a collector for packet mirroring. To prevent mirroring loops, instances behind this load balancer will not have their traffic mirrored even if a PacketMirroring rule applies to them. This can only be set to true for load balancers that have their loadBalancingScheme set to INTERNAL. `description` An optional description of this resource. Provide this property when you create the resource. `id` The unique identifier for the resource. `ip_address` The IP address that this forwarding rule is serving on behalf of. Addresses are restricted based on the forwarding rule’s load balancing scheme (EXTERNAL or INTERNAL) and scope (global or regional). When the load balancing scheme is EXTERNAL, for global forwarding rules, the address must be a global IP, and for regional forwarding rules, the address must live in the same region as the forwarding rule. If this field is empty, an ephemeral IPv4 address from the same scope (global or regional) will be assigned. A regional forwarding rule supports IPv4 only. A global forwarding rule supports either IPv4 or IPv6. When the load balancing scheme is INTERNAL, this can only be an RFC 1918 IP address belonging to the network/subnet configured for the forwarding rule. By default, if this field is empty, an ephemeral internal IP address will be automatically allocated from the IP range of the subnet or network configured for this forwarding rule. An address can be specified either by a literal IP address or a URL reference to an existing Address resource. The following examples are all valid: * 100.1.2.3 * <https://www.googleapis.com/compute/v1/projects/project/regions/> * region/addresses/address * projects/project/regions/region/addresses/address * regions/region/addresses/address * global/addresses/address * address `ip_protocol` The IP protocol to which this rule applies. When the load balancing scheme is INTERNAL, only TCP and UDP are valid. Possible values: * TCP * UDP * ESP * AH * SCTP * ICMP `backend_service` A BackendService to receive the matched traffic. This is used only for INTERNAL load balancing. `load_balancing_scheme` This signifies what the ForwardingRule will be used for and can be EXTERNAL, INTERNAL, or INTERNAL_MANAGED. EXTERNAL is used for Classic Cloud VPN gateways, protocol forwarding to VMs from an external IP address, and HTTP(S), SSL Proxy, TCP Proxy, and Network TCP/UDP load balancers. INTERNAL is used for protocol forwarding to VMs from an internal IP address, and internal TCP/UDP load balancers. INTERNAL_MANAGED is used for internal HTTP(S) load balancers. Possible values: * EXTERNAL * INTERNAL * INTERNAL_MANAGED `name` Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `network` For internal load balancing, this field identifies the network that the load balanced IP should belong to for this Forwarding Rule. If this field is not specified, the default network will be used. This field is only used for INTERNAL load balancing. `port_range` This field is used along with the target field for TargetHttpProxy, TargetHttpsProxy, TargetSslProxy, TargetTcpProxy, TargetVpnGateway, TargetPool, TargetInstance. Applicable only when IPProtocol is TCP, UDP, or SCTP, only packets addressed to ports in the specified range will be forwarded to target. Forwarding rules with the same `[IPAddress, IPProtocol]` pair must have disjoint port ranges. Some types of forwarding target have constraints on the acceptable ports: * TargetHttpProxy: 80, 8080 * TargetHttpsProxy: 443 * TargetTcpProxy: 25, 43, 110, 143, 195, 443, 465, 587, 700, 993, 995, 1883, 5222 * TargetSslProxy: 25, 43, 110, 143, 195, 443, 465, 587, 700, 993, 995, 1883, 5222 * TargetVpnGateway: 500, 4500 `ports` This field is used along with the backend_service field for internal load balancing. When the load balancing scheme is INTERNAL, a single port or a comma separated list of ports can be configured. Only packets addressed to these ports will be forwarded to the backends configured with this forwarding rule. You may specify a maximum of up to 5 ports. `subnetwork` The subnetwork that the load balanced IP should belong to for this Forwarding Rule. This field is only used for INTERNAL load balancing. If the network specified is in auto subnet mode, this field is optional. However, if the network is in custom subnet mode, a subnetwork must be specified. `target` The URL of the target resource to receive the matched traffic. The target must live in the same region as the forwarding rule. The forwarded traffic must be of a type appropriate to the target object. `allow_global_access` If true, clients can access ILB from all regions. Otherwise only allows from the local region the ILB is located at. `labels` (Beta only) Labels to apply to this forwarding rule. A list of key->value pairs. `label_fingerprint` (Beta only) The fingerprint used for optimistic locking of this resource. Used internally during updates. `all_ports` For internal TCP/UDP load balancing (i.e. load balancing scheme is INTERNAL and protocol is TCP/UDP), set this to true to allow packets addressed to any ports to be forwarded to the backends configured with this forwarding rule. Used with backend service. Cannot be set if port or portRange are set. `network_tier` The networking tier used for configuring this address. If this field is not specified, it is assumed to be PREMIUM. Possible values: * PREMIUM * STANDARD `service_label` An optional prefix to the service name for this Forwarding Rule. If specified, will be the first label of the fully qualified service name. The label must be 1-63 characters long, and comply with RFC1035. Specifically, the label must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. This field is only used for INTERNAL load balancing. `service_name` The internal fully qualified service name for this Forwarding Rule. This field is only used for INTERNAL load balancing. `region` A reference to the region where the regional forwarding rule resides. This field is not applicable to global forwarding rules. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_forwarding_rule/google_compute_disk resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_disk.md) Syntax ------ A `google_compute_disk` is used to test a Google Disk resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` most_recent_image = google_compute_image(project: 'debian-cloud', name: 'debian-10-buster-v20191014') describe google_compute_disk(project: 'chef-gcp-inspec', name: 'inspec-snapshot-disk', zone: 'zone') do it { should exist } # Test that the image is the most recent image for the family its('source_image') { should match most_recent_image.self_link } its('type') { should match 'pd-standard' } end describe.one do google_compute_disk(project: 'chef-gcp-inspec', name: 'inspec-snapshot-disk', zone: 'zone').labels.each_pair do |key, value| describe key do it { should cmp "environment" } end end end describe google_compute_disk(project: 'chef-gcp-inspec', name: 'nonexistent', zone: 'zone') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_disk` resource: `label_fingerprint` The fingerprint used for optimistic locking of this resource. Used internally during updates. `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. Provide this property when you create the resource. `id` The unique identifier for the resource. `last_attach_timestamp` Last attach timestamp in RFC3339 text format. `last_detach_timestamp` Last detach timestamp in RFC3339 text format. `labels` Labels to apply to this disk. A list of key->value pairs. `licenses` Any applicable publicly visible licenses. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `size_gb` Size of the persistent disk, specified in GB. You can specify this field when creating a persistent disk using the sourceImage or sourceSnapshot parameter, or specify it alone to create an empty persistent disk. If you specify this field along with sourceImage or sourceSnapshot, the value of sizeGb must not be less than the size of the sourceImage or the size of the snapshot. `users` Links to the users of the disk (attached instances) in form: project/zones/zone/instances/instance `physical_block_size_bytes` Physical block size of the persistent disk, in bytes. If not present in a request, a default value is used. Currently supported sizes are 4096 and 16384, other sizes may be added in the future. If an unsupported value is requested, the error message will list the supported values for the caller’s project. `type` URL of the disk type resource describing which disk type to use to create the disk. Provide this when creating the disk. `source_image` The source image used to create this disk. If the source image is deleted, this field will not be set. To create a disk with one of the public operating system images, specify the image by its family name. For example, specify family/debian-8 to use the latest Debian 8 image: projects/debian-cloud/global/images/family/debian-8 Alternatively, use a specific version of a public operating system image: projects/debian-cloud/global/images/debian-8-jessie-vYYYYMMDD To create a disk with a private image that you created, specify the image name in the following format: global/images/my-private-image You can also specify a private image by its image family, which returns the latest version of the image in that family. Replace the image name with family/family-name: global/images/family/my-private-family `resource_policies` (Beta only) Resource policies applied to this disk for automatic snapshot creations. `zone` A reference to the zone where the disk resides. `source_image_encryption_key` The customer-supplied encryption key of the source image. Required if the source image is protected by a customer-supplied encryption key. `raw_key` Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. `sha256` The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. `kms_key_name` The name of the encryption key that is stored in Google Cloud KMS. `source_image_id` The ID value of the image used to create this disk. This value identifies the exact image that was used to create this persistent disk. For example, if you created the persistent disk from an image that was later deleted and recreated under the same name, the source image ID would identify the exact version of the image that was used. `disk_encryption_key` Encrypts the disk using a customer-supplied encryption key. After you encrypt a disk with a customer-supplied key, you must provide the same key if you use the disk later (e.g. to create a disk snapshot or an image, or to attach the disk to a virtual machine). Customer-supplied encryption keys do not protect access to metadata of the disk. If you do not provide an encryption key when creating the disk, then the disk will be encrypted using an automatically generated key and you do not need to provide a key to use the disk later. `raw_key` Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. `sha256` The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. `kms_key_name` The name of the encryption key that is stored in Google Cloud KMS. Your project’s Compute Engine System service account (`service-{{PROJECT_NUMBER}}<EMAIL>`) must have `roles/cloudkms.cryptoKeyEncrypterDecrypter` to use this feature. `source_snapshot` The source snapshot used to create this disk. You can provide this as a partial or full URL to the resource. If the snapshot is in another project than this disk, you must supply a full URL. For example, the following are valid values: * `https://www.googleapis.com/compute/v1/projects/project/global/snapshots/snapshot` * `projects/project/global/snapshots/snapshot` * `global/snapshots/snapshot` `source_snapshot_encryption_key` The customer-supplied encryption key of the source snapshot. Required if the source snapshot is protected by a customer-supplied encryption key. `raw_key` Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. `kms_key_name` The name of the encryption key that is stored in Google Cloud KMS. `sha256` The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. `source_snapshot_id` The unique ID of the snapshot used to create this disk. This value identifies the exact snapshot that was used to create this persistent disk. For example, if you created the persistent disk from a snapshot that was later deleted and recreated under the same name, the source snapshot ID would identify the exact version of the snapshot that was used. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_disk/google_compute_firewall resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_firewall.md) Syntax ------ A `google_compute_firewall` is used to test a Google Firewall resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_firewall(project: 'chef-gcp-inspec', name: 'inspec-gcp-firewall') do its('direction') { should cmp 'INGRESS' } its('log_config_enabled?') { should be true } its('source_tags') { should include 'some-tag' } end ``` ### Test that a GCP compute firewall allows SSH access on port 22 ``` describe google_compute_firewall(project: 'chef-inspec-gcp', name: 'firewall-rule') do its('allowed_ssh?') { should be true } end ``` ### Test that a GCP compute firewall does not allow HTTP access on port 80 ``` describe google_compute_firewall(project: 'chef-inspec-gcp', name: 'firewall-rule') do its('allowed_http?') { should be false } end ``` ### Test that a GCP compute firewall allows HTTPS access on port 443 ``` describe google_compute_firewall(project: 'chef-inspec-gcp', name: 'firewall-rule') do its('allowed_https?') { should be true } end ``` ### Test the direction of a GCP compute firewall e.g. “INGRESS” or “EGRESS” ``` describe google_compute_firewall(project: 'chef-inspec-gcp', name: 'firewall-rule') do its('direction') { should eq "INGRESS" } end ``` ### Test the source IP range list for the GCP compute firewall is not open to the world ``` describe google_compute_firewall(project: 'chef-inspec-gcp', name: 'firewall-rule') do its('source_ranges') { should_not eq ["0.0.0.0/0"] } # or using helpers its('direction') { should eq "INGRESS" } it { should_not allow_ip_ranges ["0.0.0.0/0"] } end ``` ### Test whether or not a port/protocol is defined for a given firewall rule ``` describe google_compute_firewall(project: 'chef-inspec-gcp', name: 'firewall-rule') do # similar to the http / ssh helpers above it { should_not allow_port_protocol("22", "tcp") } it { should allow_port_protocol("80", "tcp") } end ``` ### Test whether firewall rule allows ingress/egress for specified tags ``` describe google_compute_firewall(project: 'chef-inspec-gcp', name: 'firewall-rule') do its('direction') { should eq "INGRESS" } it { should allow_source_tags ["allow-gcp-tag"] } it { should allow_target_tags ["allow-gcp-other-tag"] } # stricter it { should allow_source_tags_only ["allow-gcp-tag"] } it { should allow_target_tags_only ["allow-gcp-other-tag"] } end ``` Properties ---------- Properties that can be accessed from the `google_compute_firewall` resource: `allowed` The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-range tuple that describes a permitted connection. `ip_protocol` The IP protocol to which this rule applies. The protocol type is required when creating a firewall rule. This value can either be one of the following well known protocol strings (tcp, udp, icmp, esp, ah, sctp, ipip), or the IP protocol number. `ports` An optional list of ports to which this rule applies. This field is only applicable for UDP or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule applies to connections through any port. Example inputs include: [“22”], [“80”,“443”], and [“12345-12349”]. `creation_timestamp` Creation timestamp in RFC3339 text format. `denied` The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-range tuple that describes a denied connection. `ip_protocol` The IP protocol to which this rule applies. The protocol type is required when creating a firewall rule. This value can either be one of the following well known protocol strings (tcp, udp, icmp, esp, ah, sctp, ipip), or the IP protocol number. `ports` An optional list of ports to which this rule applies. This field is only applicable for UDP or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule applies to connections through any port. Example inputs include: [“22”], [“80”,“443”], and [“12345-12349”]. `description` An optional description of this resource. Provide this property when you create the resource. `destination_ranges` If destination ranges are specified, the firewall will apply only to traffic that has destination IP address in these ranges. These ranges must be expressed in CIDR format. Only IPv4 is supported. `direction` Direction of traffic to which this firewall applies; default is INGRESS. Note: For INGRESS traffic, it is NOT supported to specify destinationRanges; For EGRESS traffic, it is NOT supported to specify sourceRanges OR sourceTags. Possible values: * INGRESS * EGRESS `disabled` Denotes whether the firewall rule is disabled, i.e not applied to the network it is associated with. When set to true, the firewall rule is not enforced and the network behaves as if it did not exist. If this is unspecified, the firewall rule will be enabled. `log_config` This field denotes whether to enable logging for a particular firewall rule. If logging is enabled, logs will be exported to Stackdriver. `enable_logging` This field denotes whether to enable logging for a particular firewall rule. If logging is enabled, logs will be exported to Stackdriver. `id` The unique identifier for the resource. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `network` URL of the network resource for this firewall rule. If not specified when creating a firewall rule, the default network is used: global/networks/default If you choose to specify this property, you can specify the network as a full or partial URL. For example, the following are all valid URLs: <https://www.googleapis.com/compute/v1/projects/myproject/global/> networks/my-network projects/myproject/global/networks/my-network global/networks/default `priority` Priority for this rule. This is an integer between 0 and 65535, both inclusive. When not specified, the value assumed is 1000. Relative priorities determine precedence of conflicting rules. Lower value of priority implies higher precedence (eg, a rule with priority 0 has higher precedence than a rule with priority 1). DENY rules take precedence over ALLOW rules having equal priority. `source_ranges` If source ranges are specified, the firewall will apply only to traffic that has source IP address in these ranges. These ranges must be expressed in CIDR format. One or both of sourceRanges and sourceTags may be set. If both properties are set, the firewall will apply to traffic that has source IP address within sourceRanges OR the source IP that belongs to a tag listed in the sourceTags property. The connection does not need to match both properties for the firewall to apply. Only IPv4 is supported. `source_service_accounts` If source service accounts are specified, the firewall will apply only to traffic originating from an instance with a service account in this list. Source service accounts cannot be used to control traffic to an instance’s external IP address because service accounts are associated with an instance, not an IP address. sourceRanges can be set at the same time as sourceServiceAccounts. If both are set, the firewall will apply to traffic that has source IP address within sourceRanges OR the source IP belongs to an instance with service account listed in sourceServiceAccount. The connection does not need to match both properties for the firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or targetTags. `source_tags` If source tags are specified, the firewall will apply only to traffic with source IP that belongs to a tag listed in source tags. Source tags cannot be used to control traffic to an instance’s external IP address. Because tags are associated with an instance, not an IP address. One or both of sourceRanges and sourceTags may be set. If both properties are set, the firewall will apply to traffic that has source IP address within sourceRanges OR the source IP that belongs to a tag listed in the sourceTags property. The connection does not need to match both properties for the firewall to apply. `target_service_accounts` A list of service accounts indicating sets of instances located in the network that may make network connections as specified in allowed. targetServiceAccounts cannot be used at the same time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are specified, the firewall rule applies to all instances on the specified network. `target_tags` A list of instance tags indicating sets of instances located in the network that may make network connections as specified in allowed. If no targetTags are specified, the firewall rule applies to all instances on the specified network. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_firewall/google_compute_firewalls resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_firewalls.md) Syntax ------ A `google_compute_firewalls` is used to test a Google Firewall resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_firewalls(project: 'chef-gcp-inspec') do its('count') { should be >= 1 } its('firewall_names') { should include 'inspec-gcp-firewall' } its('firewall_directions') { should include 'INGRESS' } end ``` ### Test that there are no more than a specified number of firewalls available for the project ``` describe google_compute_firewalls(project: 'chef-inspec-gcp') do its('count') { should be <= 100} end ``` ### Test that an expected firewall is available for the project ``` describe google_compute_firewalls(project: 'chef-inspec-gcp') do its('firewall_names') { should include "my-app-firewall-rule" } end ``` ### Test that a particular named rule does not exist ``` describe google_compute_firewalls(project: 'chef-inspec-gcp') do its('firewall_names') { should_not include "default-allow-ssh" } end ``` ### Test there are no firewalls for the “INGRESS” direction ``` describe google_compute_firewalls(project: 'chef-inspec-gcp').where(firewall_direction: 'INGRESS') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_firewalls` resource: See the [google_compute_firewall](../google_compute_firewall/index#properties) resource for more information. `alloweds` an array of `google_compute_firewall` allowed `creation_timestamps` an array of `google_compute_firewall` creation_timestamp `denieds` an array of `google_compute_firewall` denied `descriptions` an array of `google_compute_firewall` description `destination_ranges` an array of `google_compute_firewall` destination_ranges `firewall_directions` an array of `google_compute_firewall` direction `disableds` an array of `google_compute_firewall` disabled `log_configs` an array of `google_compute_firewall` log_config `firewall_ids` an array of `google_compute_firewall` id `firewall_names` an array of `google_compute_firewall` name `networks` an array of `google_compute_firewall` network `priorities` an array of `google_compute_firewall` priority `source_ranges` an array of `google_compute_firewall` source_ranges `source_service_accounts` an array of `google_compute_firewall` source_service_accounts `source_tags` an array of `google_compute_firewall` source_tags `target_service_accounts` an array of `google_compute_firewall` target_service_accounts `target_tags` an array of `google_compute_firewall` target_tags Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_firewalls/google_compute_global_address resource ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_global_address.md) Syntax ------ A `google_compute_global_address` is used to test a Google GlobalAddress resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_global_address(project: 'chef-gcp-inspec', name: 'inspec-gcp-global-address') do it { should exist } its('ip_version') { should eq 'IPV6' } end describe google_compute_global_address(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_global_address` resource: `address` The static external IP address represented by this resource. `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. `id` The unique identifier for the resource. This identifier is defined by the server. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `labels` (Beta only) Labels to apply to this address. A list of key->value pairs. `label_fingerprint` (Beta only) The fingerprint used for optimistic locking of this resource. Used internally during updates. `ip_version` The IP Version that will be used by this address. The default value is `IPV4`. Possible values: * IPV4 * IPV6 `region` A reference to the region where the regional address resides. `prefix_length` The prefix length of the IP range. If not present, it means the address field is a single IP address. This field is not applicable to addresses with addressType=EXTERNAL. `address_type` The type of the address to reserve. _ EXTERNAL indicates public/external single IP address. _ INTERNAL indicates internal IP ranges belonging to some network. Possible values: * EXTERNAL * INTERNAL `purpose` The purpose of the resource. For global internal addresses it can be _ VPC_PEERING - for peer networks This should only be set when using an Internal address. Possible values: * VPC_PEERING `network` The URL of the network in which to reserve the IP range. The IP range must be in RFC1918 space. The network cannot be deleted if there are any reserved IP ranges referring to it. This should only be set when using an Internal address. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_global_address/google_compute_global_addresses resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_global_addresses.md) Syntax ------ A `google_compute_global_addresses` is used to test a Google GlobalAddress resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_global_addresses(project: 'chef-gcp-inspec', name: 'inspec-gcp-global-address') do its('count') { should be >= 1 } its('names') { should include 'inspec-gcp-global-address' } its('ip_versions') { should include 'IPV6' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_global_addresses` resource: See the [google_compute_global_address](../google_compute_global_address/index#properties) resource for more information. `addresses` an array of `google_compute_global_address` address `creation_timestamps` an array of `google_compute_global_address` creation_timestamp `descriptions` an array of `google_compute_global_address` description `ids` an array of `google_compute_global_address` id `names` an array of `google_compute_global_address` name `labels` (Beta only) an array of `google_compute_global_address` labels `label_fingerprints` (Beta only) an array of `google_compute_global_address` label_fingerprint `ip_versions` an array of `google_compute_global_address` ip_version `regions` an array of `google_compute_global_address` region `prefix_lengths` an array of `google_compute_global_address` prefix_length `address_types` an array of `google_compute_global_address` address_type `purposes` an array of `google_compute_global_address` purpose `networks` an array of `google_compute_global_address` network Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_global_addresses/google_compute_global_forwarding_rule resource ================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_global_forwarding_rule.md) Syntax ------ A `google_compute_global_forwarding_rule` is used to test a Google GlobalForwardingRule resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_global_forwarding_rule(project: 'chef-gcp-inspec', name: 'inspec-gcp-global-forwarding-rule') do it { should exist } its('port_range') { should eq '80-80' } its('target') { should match /\/inspec-gcp-http-proxy$/ } end describe google_compute_global_forwarding_rule(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_global_forwarding_rule` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. Provide this property when you create the resource. `id` The unique identifier for the resource. `ip_address` The IP address that this forwarding rule is serving on behalf of. Addresses are restricted based on the forwarding rule’s load balancing scheme (external or internal) and scope (global or regional). The address must be a global IP for external global forwarding rules. If this field is empty, an ephemeral IPv4 address from the same scope (global) is chosen. Global forwarding rules supports either IPv4 or IPv6. When the load balancing scheme is INTERNAL_SELF_MANAGED, this must be a URL reference to an existing Address resource (internal regional static IP address), with a purpose of GCE_END_POINT and addressType of INTERNAL. An address can be specified either by a literal IP address or a URL reference to an existing Address resource. The following examples are all valid: * 100.1.2.3 * <https://www.googleapis.com/compute/v1/projects/project/regions/> * region/addresses/address * projects/project/regions/region/addresses/address * regions/region/addresses/address * global/addresses/address * address `ip_protocol` The IP protocol to which this rule applies. When the load balancing scheme is INTERNAL_SELF_MANAGED, only TCP is valid. Possible values: * TCP * UDP * ESP * AH * SCTP * ICMP `ip_version` The IP Version that will be used by this global forwarding rule. Possible values: * IPV4 * IPV6 `labels` (Beta only) Labels to apply to this forwarding rule. A list of key->value pairs. `label_fingerprint` (Beta only) The fingerprint used for optimistic locking of this resource. Used internally during updates. `load_balancing_scheme` This signifies what the GlobalForwardingRule will be used for. The value of INTERNAL_SELF_MANAGED means that this will be used for Internal Global HTTP(S) LB. The value of EXTERNAL means that this will be used for External Global Load Balancing (HTTP(S) LB, External TCP/UDP LB, SSL Proxy) NOTE: Currently global forwarding rules cannot be used for INTERNAL load balancing. Possible values: * EXTERNAL * INTERNAL_SELF_MANAGED `metadata_filters` Opaque filter criteria used by Loadbalancer to restrict routing configuration to a limited set xDS compliant clients. In their xDS requests to Loadbalancer, xDS clients present node metadata. If a match takes place, the relevant routing configuration is made available to those proxies. For each metadataFilter in this list, if its filterMatchCriteria is set to MATCH_ANY, at least one of the filterLabels must match the corresponding label provided in the metadata. If its filterMatchCriteria is set to MATCH_ALL, then all of its filterLabels must match with corresponding labels in the provided metadata. metadataFilters specified here can be overridden by those specified in the UrlMap that this ForwardingRule references. metadataFilters only applies to Loadbalancers that have their loadBalancingScheme set to INTERNAL_SELF_MANAGED. `filter_match_criteria` Specifies how individual filterLabel matches within the list of filterLabels contribute towards the overall metadataFilter match. MATCH_ANY - At least one of the filterLabels must have a matching label in the provided metadata. MATCH_ALL - All filterLabels must have matching labels in the provided metadata. Possible values: * MATCH_ANY * MATCH_ALL `filter_labels` The list of label value pairs that must match labels in the provided metadata based on filterMatchCriteria This list must not be empty and can have at the most 64 entries. `name` Name of the metadata label. The length must be between 1 and 1024 characters, inclusive. `value` The value that the label must match. The value has a maximum length of 1024 characters. `name` Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `network` This field is not used for external load balancing. For INTERNAL_SELF_MANAGED load balancing, this field identifies the network that the load balanced IP should belong to for this global forwarding rule. If this field is not specified, the default network will be used. `port_range` This field is used along with the target field for TargetHttpProxy, TargetHttpsProxy, TargetSslProxy, TargetTcpProxy, TargetVpnGateway, TargetPool, TargetInstance. Applicable only when IPProtocol is TCP, UDP, or SCTP, only packets addressed to ports in the specified range will be forwarded to target. Forwarding rules with the same `[IPAddress, IPProtocol]` pair must have disjoint port ranges. Some types of forwarding target have constraints on the acceptable ports: * TargetHttpProxy: 80, 8080 * TargetHttpsProxy: 443 * TargetTcpProxy: 25, 43, 110, 143, 195, 443, 465, 587, 700, 993, 995, 1883, 5222 * TargetSslProxy: 25, 43, 110, 143, 195, 443, 465, 587, 700, 993, 995, 1883, 5222 * TargetVpnGateway: 500, 4500 `target` The URL of the target resource to receive the matched traffic. The forwarded traffic must be of a type appropriate to the target object. For INTERNAL_SELF_MANAGED load balancing, only HTTP and HTTPS targets are valid. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_global_forwarding_rule/google_compute_forwarding_rules resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_forwarding_rules.md) Syntax ------ A `google_compute_forwarding_rules` is used to test a Google ForwardingRule resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_forwarding_rules(project: 'chef-gcp-inspec', region: 'europe-west2') do its('forwarding_rule_names') { should include 'udp-forwarding-rule' } end ``` ### Test that there are no more than a specified number of forwarding_rules available for the project and region ``` describe google_compute_forwarding_rules(project: 'chef-inspec-gcp', region: 'europe-west2') do its('count') { should be <= 100} end ``` ### Test that an expected forwarding_rule identifier is present in the project and region ``` describe google_compute_forwarding_rules(project: 'chef-inspec-gcp', region: 'europe-west2') do its('forwarding_rule_ids') { should include 12345678975432 } end ``` ### Test that an expected forwarding_rule name is available for the project and region ``` describe google_compute_forwarding_rules(project: 'chef-inspec-gcp', region: 'europe-west2') do its('forwarding_rule_names') { should include "forwarding_rule-name" } end ``` ### Test that an expected forwarding_rule network name is not present for the project and region ``` describe google_compute_forwarding_rules(project: 'chef-inspec-gcp', region: 'europe-west2') do its('forwarding_rule_networks') { should not include "network-name" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_forwarding_rules` resource: See the [google_compute_forwarding_rule](../google_compute_forwarding_rule/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_forwarding_rule` creation_timestamp `is_mirroring_collectors` (Beta only) an array of `google_compute_forwarding_rule` is_mirroring_collector `descriptions` an array of `google_compute_forwarding_rule` description `forwarding_rule_ids` an array of `google_compute_forwarding_rule` id `ip_addresses` an array of `google_compute_forwarding_rule` ip_address `ip_protocols` an array of `google_compute_forwarding_rule` ip_protocol `backend_services` an array of `google_compute_forwarding_rule` backend_service `forwarding_rule_load_balancing_schemes` an array of `google_compute_forwarding_rule` load_balancing_scheme `forwarding_rule_names` an array of `google_compute_forwarding_rule` name `forwarding_rule_networks` an array of `google_compute_forwarding_rule` network `port_ranges` an array of `google_compute_forwarding_rule` port_range `ports` an array of `google_compute_forwarding_rule` ports `subnetworks` an array of `google_compute_forwarding_rule` subnetwork `targets` an array of `google_compute_forwarding_rule` target `allow_global_accesses` an array of `google_compute_forwarding_rule` allow_global_access `labels` (Beta only) an array of `google_compute_forwarding_rule` labels `label_fingerprints` (Beta only) an array of `google_compute_forwarding_rule` label_fingerprint `all_ports` an array of `google_compute_forwarding_rule` all_ports `network_tiers` an array of `google_compute_forwarding_rule` network_tier `service_labels` an array of `google_compute_forwarding_rule` service_label `service_names` an array of `google_compute_forwarding_rule` service_name `regions` an array of `google_compute_forwarding_rule` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_forwarding_rules/google_compute_global_forwarding_rules resource =================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_global_forwarding_rules.md) Syntax ------ A `google_compute_global_forwarding_rules` is used to test a Google GlobalForwardingRule resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_global_forwarding_rules(project: 'chef-gcp-inspec') do its('count') { should be >= 1 } its('port_ranges') { should include '80-80' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_global_forwarding_rules` resource: See the [google_compute_global_forwarding_rule](../google_compute_global_forwarding_rule/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_global_forwarding_rule` creation_timestamp `descriptions` an array of `google_compute_global_forwarding_rule` description `ids` an array of `google_compute_global_forwarding_rule` id `ip_addresses` an array of `google_compute_global_forwarding_rule` ip_address `ip_protocols` an array of `google_compute_global_forwarding_rule` ip_protocol `ip_versions` an array of `google_compute_global_forwarding_rule` ip_version `labels` (Beta only) an array of `google_compute_global_forwarding_rule` labels `label_fingerprints` (Beta only) an array of `google_compute_global_forwarding_rule` label_fingerprint `load_balancing_schemes` an array of `google_compute_global_forwarding_rule` load_balancing_scheme `metadata_filters` an array of `google_compute_global_forwarding_rule` metadata_filters `names` an array of `google_compute_global_forwarding_rule` name `networks` an array of `google_compute_global_forwarding_rule` network `port_ranges` an array of `google_compute_global_forwarding_rule` port_range `targets` an array of `google_compute_global_forwarding_rule` target Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_global_forwarding_rules/google_compute_health_check resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_health_check.md) Syntax ------ A `google_compute_health_check` is used to test a Google HealthCheck resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_health_check(project: 'chef-gcp-inspec', name: 'inspec-gcp-health-check') do it { should exist } its('timeout_sec') { should eq '10' } its('tcp_health_check.port') { should eq '80' } end describe google_compute_health_check(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_health_check` resource: `check_interval_sec` How often (in seconds) to send a health check. The default value is 5 seconds. `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. Provide this property when you create the resource. `healthy_threshold` A so-far unhealthy instance will be marked healthy after this many consecutive successes. The default value is 2. `id` The unique identifier for the resource. This identifier is defined by the server. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `timeout_sec` How long (in seconds) to wait before claiming failure. The default value is 5 seconds. It is invalid for timeoutSec to have greater value than checkIntervalSec. `unhealthy_threshold` A so-far healthy instance will be marked unhealthy after this many consecutive failures. The default value is 2. `type` Specifies the type of the healthCheck, either TCP, SSL, HTTP or HTTPS. If not specified, the default is TCP. Exactly one of the protocol-specific health check field must be specified, which must match type field. Possible values: * TCP * SSL * HTTP * HTTPS * HTTP2 `http_health_check` A nested object resource `host` The value of the host header in the HTTP health check request. If left empty (default value), the public IP on behalf of which this health check is performed will be used. `request_path` The request path of the HTTP health check request. The default value is /. `response` The bytes to match against the beginning of the response data. If left empty (the default value), any response will indicate health. The response data can only be ASCII. `port` The TCP port number for the HTTP health check request. The default value is 80. `port_name` Port name as defined in InstanceGroup#NamedPort#name. If both port and port_name are defined, port takes precedence. `proxy_header` Specifies the type of proxy header to append before sending data to the backend. Possible values: * NONE * PROXY_V1 `port_specification` Specifies how port is selected for health checking, can be one of the following values: `USE_FIXED_PORT` The port number in `port` is used for health checking. `USE_NAMED_PORT` The `portName` is used for health checking. `USE_SERVING_PORT` For NetworkEndpointGroup, the port specified for each network endpoint is used for health checking. For other backends, the port or named port specified in the Backend Service is used for health checking. If not specified, HTTP health check follows behavior specified in `port` and `portName` fields. `https_health_check` A nested object resource `host` The value of the host header in the HTTPS health check request. If left empty (default value), the public IP on behalf of which this health check is performed will be used. `request_path` The request path of the HTTPS health check request. The default value is /. `response` The bytes to match against the beginning of the response data. If left empty (the default value), any response will indicate health. The response data can only be ASCII. `port` The TCP port number for the HTTPS health check request. The default value is 443. `port_name` Port name as defined in InstanceGroup#NamedPort#name. If both port and port_name are defined, port takes precedence. `proxy_header` Specifies the type of proxy header to append before sending data to the backend. Possible values: * NONE * PROXY_V1 `port_specification` Specifies how port is selected for health checking, can be one of the following values: `USE_FIXED_PORT` The port number in `port` is used for health checking. `USE_NAMED_PORT` The `portName` is used for health checking. `USE_SERVING_PORT` For NetworkEndpointGroup, the port specified for each network endpoint is used for health checking. For other backends, the port or named port specified in the Backend Service is used for health checking. If not specified, HTTPS health check follows behavior specified in `port` and `portName` fields. `tcp_health_check` A nested object resource `request` The application data to send once the TCP connection has been established (default value is empty). If both request and response are empty, the connection establishment alone will indicate health. The request data can only be ASCII. `response` The bytes to match against the beginning of the response data. If left empty (the default value), any response will indicate health. The response data can only be ASCII. `port` The TCP port number for the TCP health check request. The default value is 443. `port_name` Port name as defined in InstanceGroup#NamedPort#name. If both port and port_name are defined, port takes precedence. `proxy_header` Specifies the type of proxy header to append before sending data to the backend. Possible values: * NONE * PROXY_V1 `port_specification` Specifies how port is selected for health checking, can be one of the following values: `USE_FIXED_PORT` The port number in `port` is used for health checking. `USE_NAMED_PORT` The `portName` is used for health checking. `USE_SERVING_PORT` For NetworkEndpointGroup, the port specified for each network endpoint is used for health checking. For other backends, the port or named port specified in the Backend Service is used for health checking. If not specified, TCP health check follows behavior specified in `port` and `portName` fields. `ssl_health_check` A nested object resource `request` The application data to send once the SSL connection has been established (default value is empty). If both request and response are empty, the connection establishment alone will indicate health. The request data can only be ASCII. `response` The bytes to match against the beginning of the response data. If left empty (the default value), any response will indicate health. The response data can only be ASCII. `port` The TCP port number for the SSL health check request. The default value is 443. `port_name` Port name as defined in InstanceGroup#NamedPort#name. If both port and port_name are defined, port takes precedence. `proxy_header` Specifies the type of proxy header to append before sending data to the backend. Possible values: * NONE * PROXY_V1 `port_specification` Specifies how port is selected for health checking, can be one of the following values: `USE_FIXED_PORT` The port number in `port` is used for health checking. `USE_NAMED_PORT` The `portName` is used for health checking. `USE_SERVING_PORT` For NetworkEndpointGroup, the port specified for each network endpoint is used for health checking. For other backends, the port or named port specified in the Backend Service is used for health checking. If not specified, SSL health check follows behavior specified in `port` and `portName` fields. `http2_health_check` A nested object resource `host` The value of the host header in the HTTP2 health check request. If left empty (default value), the public IP on behalf of which this health check is performed will be used. `request_path` The request path of the HTTP2 health check request. The default value is /. `response` The bytes to match against the beginning of the response data. If left empty (the default value), any response will indicate health. The response data can only be ASCII. `port` The TCP port number for the HTTP2 health check request. The default value is 443. `port_name` Port name as defined in InstanceGroup#NamedPort#name. If both port and port_name are defined, port takes precedence. `proxy_header` Specifies the type of proxy header to append before sending data to the backend. Possible values: * NONE * PROXY_V1 `port_specification` Specifies how port is selected for health checking, can be one of the following values: `USE_FIXED_PORT` The port number in `port` is used for health checking. `USE_NAMED_PORT` The `portName` is used for health checking. `USE_SERVING_PORT` For NetworkEndpointGroup, the port specified for each network endpoint is used for health checking. For other backends, the port or named port specified in the Backend Service is used for health checking. If not specified, HTTP2 health check follows behavior specified in `port` and `portName` fields. `log_config` (Beta only) Configure logging on this health check. `enable` : Indicates whether or not to export logs. This is false by default, which means no health check logging will be done. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_health_check/google_compute_http_health_check resource ============================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_http_health_check.md) Syntax ------ A `google_compute_http_health_check` is used to test a Google HttpHealthCheck resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_http_health_check(project: 'chef-gcp-inspec', name: 'inspec-gcp-http-health-check') do it { should exist } its('timeout_sec') { should eq '20' } its('request_path') { should eq '/health_check' } its('check_interval_sec') { should eq '20' } end describe google_compute_http_health_check(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_http_health_check` resource: `check_interval_sec` How often (in seconds) to send a health check. The default value is 5 seconds. `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. Provide this property when you create the resource. `healthy_threshold` A so-far unhealthy instance will be marked healthy after this many consecutive successes. The default value is 2. `host` The value of the host header in the HTTP health check request. If left empty (default value), the public IP on behalf of which this health check is performed will be used. `id` The unique identifier for the resource. This identifier is defined by the server. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `port` The TCP port number for the HTTP health check request. The default value is 80. `request_path` The request path of the HTTP health check request. The default value is /. `timeout_sec` How long (in seconds) to wait before claiming failure. The default value is 5 seconds. It is invalid for timeoutSec to have greater value than checkIntervalSec. `unhealthy_threshold` A so-far healthy instance will be marked unhealthy after this many consecutive failures. The default value is 2. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_http_health_check/google_compute_http_health_checks resource ============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_http_health_checks.md) Syntax ------ A `google_compute_http_health_checks` is used to test a Google HttpHealthCheck resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_http_health_checks(project: 'chef-gcp-inspec') do its('names') { should include 'inspec-gcp-http-health-check' } its('timeout_secs') { should include '20' } its('check_interval_secs') { should include '20' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_http_health_checks` resource: See the [google_compute_http_health_check](../google_compute_http_health_check/index#properties) resource for more information. `check_interval_secs` an array of `google_compute_http_health_check` check_interval_sec `creation_timestamps` an array of `google_compute_http_health_check` creation_timestamp `descriptions` an array of `google_compute_http_health_check` description `healthy_thresholds` an array of `google_compute_http_health_check` healthy_threshold `hosts` an array of `google_compute_http_health_check` host `ids` an array of `google_compute_http_health_check` id `names` an array of `google_compute_http_health_check` name `ports` an array of `google_compute_http_health_check` port `request_paths` an array of `google_compute_http_health_check` request_path `timeout_secs` an array of `google_compute_http_health_check` timeout_sec `unhealthy_thresholds` an array of `google_compute_http_health_check` unhealthy_threshold Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_http_health_checks/google_compute_health_checks resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_health_checks.md) Syntax ------ A `google_compute_health_checks` is used to test a Google HealthCheck resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_health_checks(project: 'chef-gcp-inspec') do its('names') { should include 'inspec-gcp-health-check' } its('timeout_secs') { should include '10' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_health_checks` resource: See the [google_compute_health_check](../google_compute_health_check/index#properties) resource for more information. `check_interval_secs` an array of `google_compute_health_check` check_interval_sec `creation_timestamps` an array of `google_compute_health_check` creation_timestamp `descriptions` an array of `google_compute_health_check` description `healthy_thresholds` an array of `google_compute_health_check` healthy_threshold `ids` an array of `google_compute_health_check` id `names` an array of `google_compute_health_check` name `timeout_secs` an array of `google_compute_health_check` timeout_sec `unhealthy_thresholds` an array of `google_compute_health_check` unhealthy_threshold `types` an array of `google_compute_health_check` type `http_health_checks` an array of `google_compute_health_check` http_health_check `https_health_checks` an array of `google_compute_health_check` https_health_check `tcp_health_checks` an array of `google_compute_health_check` tcp_health_check `ssl_health_checks` an array of `google_compute_health_check` ssl_health_check `http2_health_checks` an array of `google_compute_health_check` http2_health_check `log_configs` (Beta only) an array of `google_compute_health_check` log_config Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_health_checks/google_compute_https_health_checks resource =============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_https_health_checks.md) Syntax ------ A `google_compute_https_health_checks` is used to test a Google HttpsHealthCheck resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_https_health_checks(project: 'chef-gcp-inspec') do its('names') { should include 'inspec-gcp-https-health-check' } its('timeout_secs') { should include '15' } its('check_interval_secs') { should include '15' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_https_health_checks` resource: See the [google_compute_https_health_check](../google_compute_https_health_check/index#properties) resource for more information. `check_interval_secs` an array of `google_compute_https_health_check` check_interval_sec `creation_timestamps` an array of `google_compute_https_health_check` creation_timestamp `descriptions` an array of `google_compute_https_health_check` description `healthy_thresholds` an array of `google_compute_https_health_check` healthy_threshold `hosts` an array of `google_compute_https_health_check` host `ids` an array of `google_compute_https_health_check` id `names` an array of `google_compute_https_health_check` name `ports` an array of `google_compute_https_health_check` port `request_paths` an array of `google_compute_https_health_check` request_path `timeout_secs` an array of `google_compute_https_health_check` timeout_sec `unhealthy_thresholds` an array of `google_compute_https_health_check` unhealthy_threshold Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_https_health_checks/google_compute_image resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_image.md) Syntax ------ A `google_compute_image` is used to test a Google Image resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_image(project: 'chef-gcp-inspec', name: 'inspec-image') do it { should exist } its('disk_size_gb') { should cmp 3 } end describe google_compute_image(project: 'chef-gcp-inspec', name: 'notfound') do it { should_not exist } end ``` ### Test that a GCP compute image is in a particular status e.g. “READY” means available for use ``` describe google_compute_image(project: 'chef-inspec-gcp', location: 'europe-west2', name: 'compute-address') do its('status') { should eq "READY" } end ``` ### Test that a GCP compute image has the expected family ``` describe google_compute_image(project: 'chef-inspec-gcp', name: 'ubuntu') do its('family') { should match "ubuntu" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_image` resource: `archive_size_bytes` Size of the image tar.gz archive stored in Google Cloud Storage (in bytes). `creation_timestamp` Creation timestamp in RFC3339 text format. `deprecated` The deprecation status associated with this image. `deleted` An optional RFC3339 timestamp on or after which the state of this resource is intended to change to DELETED. This is only informational and the status will not change unless the client explicitly changes it. `deprecated` An optional RFC3339 timestamp on or after which the state of this resource is intended to change to DEPRECATED. This is only informational and the status will not change unless the client explicitly changes it. `obsolete` An optional RFC3339 timestamp on or after which the state of this resource is intended to change to OBSOLETE. This is only informational and the status will not change unless the client explicitly changes it. `replacement` The URL of the suggested replacement for a deprecated resource. The suggested replacement resource must be the same kind of resource as the deprecated resource. `state` The deprecation state of this resource. This can be DEPRECATED, OBSOLETE, or DELETED. Operations which create a new resource using a DEPRECATED resource will return successfully, but with a warning indicating the deprecated resource and recommending its replacement. Operations which use OBSOLETE or DELETED resources will be rejected and result in an error. Possible values: * DEPRECATED * OBSOLETE * DELETED `description` An optional description of this resource. Provide this property when you create the resource. `disk_size_gb` Size of the image when restored onto a persistent disk (in GB). `family` The name of the image family to which this image belongs. You can create disks by specifying an image family instead of a specific image name. The image family always returns its latest image that is not deprecated. The name of the image family must comply with RFC1035. `guest_os_features` A list of features to enable on the guest operating system. Applicable only for bootable images. `type` The type of supported feature. Read [Enabling guest operating system features](https://cloud.google.com/compute/docs/images/create-delete-deprecate-private-images#guest-os-features) to see a list of available options. Possible values: * MULTI_IP_SUBNET * SECURE_BOOT * UEFI_COMPATIBLE * VIRTIO_SCSI_MULTIQUEUE * WINDOWS `id` The unique identifier for the resource. This identifier is defined by the server. `image_encryption_key` Encrypts the image using a customer-supplied encryption key. After you encrypt an image with a customer-supplied key, you must provide the same key if you use the image later (e.g. to create a disk from the image) `raw_key` Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. `sha256` The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. `kms_key_name` (Beta only) The name of the encryption key that is stored in Google Cloud KMS. `labels` Labels to apply to this Image. `label_fingerprint` The fingerprint used for optimistic locking of this resource. Used internally during updates. `licenses` Any applicable license URI. `name` Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `raw_disk` The parameters of the raw disk image. `container_type` The format used to encode and transmit the block device, which should be TAR. This is just a container and transmission format and not a runtime format. Provided by the client when the disk image is created. Possible values: * TAR `sha1_checksum` An optional SHA1 checksum of the disk image before unpackaging. This is provided by the client when the disk image is created. `source` The full Google Cloud Storage URL where disk storage is stored You must provide either this property or the sourceDisk property but not both. `source_disk` The source disk to create this image based on. You must provide either this property or the rawDisk.source property but not both to create an image. `source_disk_encryption_key` The customer-supplied encryption key of the source disk. Required if the source disk is protected by a customer-supplied encryption key. `raw_key` Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. `sha256` The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. `kms_key_name` (Beta only) The name of the encryption key that is stored in Google Cloud KMS. `source_disk_id` The ID value of the disk used to create this image. This value may be used to determine whether the image was taken from the current or a previous instance of a given disk name. `source_type` The type of the image used to create this disk. The default and only value is RAW Possible values: * RAW `self_link` The self link of the image `status` The status of the image. Either `READY` `PENDING` or `FAILED`. Possible values: * READY * PENDING * FAILED GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_image/google_compute_https_health_check resource ============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_https_health_check.md) Syntax ------ A `google_compute_https_health_check` is used to test a Google HttpsHealthCheck resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_https_health_check(project: 'chef-gcp-inspec', name: 'inspec-gcp-https-health-check') do it { should exist } its('timeout_sec') { should eq '15' } its('request_path') { should eq '/https_health_check' } its('check_interval_sec') { should eq '15' } its('unhealthy_threshold') { should eq '3' } end describe google_compute_https_health_check(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_https_health_check` resource: `check_interval_sec` How often (in seconds) to send a health check. The default value is 5 seconds. `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. Provide this property when you create the resource. `healthy_threshold` A so-far unhealthy instance will be marked healthy after this many consecutive successes. The default value is 2. `host` The value of the host header in the HTTPS health check request. If left empty (default value), the public IP on behalf of which this health check is performed will be used. `id` The unique identifier for the resource. This identifier is defined by the server. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `port` The TCP port number for the HTTPS health check request. The default value is 80. `request_path` The request path of the HTTPS health check request. The default value is /. `timeout_sec` How long (in seconds) to wait before claiming failure. The default value is 5 seconds. It is invalid for timeoutSec to have greater value than checkIntervalSec. `unhealthy_threshold` A so-far healthy instance will be marked unhealthy after this many consecutive failures. The default value is 2. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_https_health_check/google_compute_instance_group resource ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_instance_group.md) Syntax ------ A `google_compute_instance_group` is used to test a Google InstanceGroup resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_instance_group(project: 'chef-gcp-inspec', zone: 'zone', name: 'inspec-instance-group') do it { should exist } its('description') { should cmp 'My instance group for testing' } its('named_ports.count') { should cmp 1 } its('named_ports.first.name') { should cmp 'https' } its('named_ports.first.port') { should cmp '8080' } end describe google_compute_instance_group(project: 'chef-gcp-inspec', zone: 'zone', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP compute instance group has the expected size ``` describe google_compute_instance_group(project: 'chef-inspec-gcp', zone: 'europe-west2-a', name: 'gcp-inspec-test') do its('size') { should eq 2 } end ``` ### Test that a GCP compute instance group has a port with supplied name and value ``` describe google_compute_instance_group(project: 'chef-inspec-gcp', zone: 'europe-west2-a', name: 'gcp-inspec-test') do its('port_name') { should eq "http" } its('port_value') { should eq 80 } end ``` Properties ---------- Properties that can be accessed from the `google_compute_instance_group` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. Provide this property when you create the resource. `id` A unique identifier for this instance group. `name` The name of the instance group. The name must be 1-63 characters long, and comply with RFC1035. `named_ports` Assigns a name to a port number. For example: {name: “http”, port: 80}. This allows the system to reference ports by the assigned name instead of a port number. Named ports can also contain multiple ports. For example: [{name: “http”, port: 80},{name: “http”, port: 8080}] Named ports apply to all instances in this instance group. `name` The name for this named port. The name must be 1-63 characters long, and comply with RFC1035. `port` The port number, which can be a value between 1 and 65535. `network` The network to which all instances in the instance group belong. `region` The region where the instance group is located (for regional resources). `subnetwork` The subnetwork to which all instances in the instance group belong. `zone` A reference to the zone where the instance group resides. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_instance_group/google_compute_instance_group_manager resource ================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_instance_group_manager.md) Syntax ------ A `google_compute_instance_group_manager` is used to test a Google InstanceGroupManager resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_instance_group_manager(project: 'chef-gcp-inspec', zone: 'zone', name: 'inspec-gcp-igm') do it { should exist } its('base_instance_name') { should eq 'igm' } its('named_ports.count') { should cmp 1 } its('named_ports.first.name') { should eq 'port' } its('named_ports.first.port') { should eq '80' } end describe google_compute_instance_group_manager(project: 'chef-gcp-inspec', zone: 'zone', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_instance_group_manager` resource: `base_instance_name` The base instance name to use for instances in this group. The value must be 1-58 characters long. Instances are named by appending a hyphen and a random four-character string to the base instance name. The base instance name must comply with RFC1035. `creation_timestamp` The creation timestamp for this managed instance group in RFC3339 text format. `current_actions` The list of instance actions and the number of instances in this managed instance group that are scheduled for each of those actions. `abandoning` The total number of instances in the managed instance group that are scheduled to be abandoned. Abandoning an instance removes it from the managed instance group without deleting it. `creating` The number of instances in the managed instance group that are scheduled to be created or are currently being created. If the group fails to create any of these instances, it tries again until it creates the instance successfully. If you have disabled creation retries, this field will not be populated; instead, the creatingWithoutRetries field will be populated. `creating_without_retries` The number of instances that the managed instance group will attempt to create. The group attempts to create each instance only once. If the group fails to create any of these instances, it decreases the group’s targetSize value accordingly. `deleting` The number of instances in the managed instance group that are scheduled to be deleted or are currently being deleted. `none` The number of instances in the managed instance group that are running and have no scheduled actions. `recreating` The number of instances in the managed instance group that are scheduled to be recreated or are currently being being recreated. Recreating an instance deletes the existing root persistent disk and creates a new disk from the image that is defined in the instance template. `refreshing` The number of instances in the managed instance group that are being reconfigured with properties that do not require a restart or a recreate action. For example, setting or removing target pools for the instance. `restarting` The number of instances in the managed instance group that are scheduled to be restarted or are currently being restarted. `description` An optional description of this resource. Provide this property when you create the resource. `id` A unique identifier for this resource `instance_group` The instance group being managed `instance_template` The instance template that is specified for this managed instance group. The group uses this template to create all new instances in the managed instance group. `name` The name of the managed instance group. The name must be 1-63 characters long, and comply with RFC1035. `named_ports` Named ports configured for the Instance Groups complementary to this Instance Group Manager. `name` The name for this named port. The name must be 1-63 characters long, and comply with RFC1035. `port` The port number, which can be a value between 1 and 65535. `region` The region this managed instance group resides (for regional resources). `target_pools` TargetPool resources to which instances in the instanceGroup field are added. The target pools automatically apply to all of the instances in the managed instance group. `target_size` The target number of running instances for this managed instance group. Deleting or abandoning instances reduces this number. Resizing the group changes this number. `zone` The zone the managed instance group resides. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_instance_group_manager/google_compute_instance resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_instance.md) Syntax ------ A `google_compute_instance` is used to test a Google Instance resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_instance(project: 'chef-gcp-inspec', zone: 'zone', name: 'inspec-instance') do it { should exist } its('machine_type') { should match 'n1-standard-1' } its('tags.items') { should include 'foo' } its('tags.items') { should include 'bar' } its('tag_count') { should cmp 2 } its('service_account_scopes') { should include 'https://www.googleapis.com/auth/compute.readonly' } its('metadata_keys') { should include '123' } its('metadata_values') { should include 'asdf' } end describe google_compute_instance(project: 'chef-gcp-inspec', zone: 'zone', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP compute instance does not exist ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone: 'us-east1-b', name: 'inspec-test-vm-not-there') do it { should_not exist } end ``` ### Test that a GCP compute instance is in the expected state ([explore possible states here](https://cloud.google.com/compute/docs/instances/checking-instance-status)) ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone: 'us-east1-b', name: 'inspec-test-vm') do its('status') { should eq 'RUNNING' } end ``` ### Test that a GCP compute instance is the expected size ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone: 'us-east1-b', name: 'inspec-test-vm') do its('machine_type') { should match "f1-micro" } end ``` ### Test that a GCP compute instance has the expected CPU platform ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone: 'us-east1-b', name: 'inspec-test-vm') do its('cpu_platform') { should match "Intel" } end ``` ### Test that a GCP compute instance has the expected number of attached disks ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone: 'us-east1-b', name: 'inspec-test-vm') do its('disk_count'){should eq 2} end ``` ### Test that a GCP compute instance has the expected number of attached network interfaces ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone: 'us-east1-b', name: 'inspec-test-vm') do its('network_interfaces_count'){should eq 1} end ``` ### Test that a GCP compute instance has the expected number of tags ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone: 'us-east1-b', name: 'inspec-test-vm') do its('tag_count'){should eq 1} end ``` ### Test that a GCP compute instance has a single public IP address ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone: 'us-east1-b', name: 'inspec-test-vm') do its('first_network_interface_nat_ip_exists'){ should be true } its('first_network_interface_name'){ should eq "external-nat" } its('first_network_interface_type'){ should eq "one_to_one_nat" } end ``` ### Test that a particular compute instance label key is present ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone: 'us-east1-b', name: 'inspec-test-vm') do its('labels_keys') { should include 'my_favourite_label' } end ``` ### Test that a particular compute instance label value is matching regexp ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone:'us-east1-b', name:'inspec-test-vm').label_value_by_key('business-area') do it { should match '^(marketing|research)$' } end ``` ### Test that a particular compute instance metadata key is present ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone:'us-east1-b', name:'inspec-test-vm') do its('metadata_keys') { should include 'patching-type' } end ``` ### Test that a particular compute instance metadata value is matching regexp ``` describe google_compute_instance(project: 'chef-inspec-gcp', zone:'us-east1-b', name:'inspec-test-vm').metadata_value_by_key('patching-window') do it { should match '^\d{1}-\d{2}$' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_instance` resource: `can_ip_forward` Allows this instance to send and receive packets with non-matching destination or source IPs. This is required if you plan to use this instance to forward routes. `cpu_platform` The CPU platform used by this instance. `creation_timestamp` Creation timestamp in RFC3339 text format. `deletion_protection` Whether the resource should be protected against deletion. `disks` An array of disks that are associated with the instances that are created from this template. `auto_delete` Specifies whether the disk will be auto-deleted when the instance is deleted (but not when the disk is detached from the instance). Tip: Disks should be set to autoDelete=true so that leftover disks are not left behind on machine deletion. `boot` Indicates that this is a boot disk. The virtual machine will use the first partition of the disk for its root filesystem. `device_name` Specifies a unique device name of your choice that is reflected into the /dev/disk/by-id/google-* tree of a Linux operating system running within the instance. This name can be used to reference the device for mounting, resizing, and so on, from within the instance. `disk_encryption_key` Encrypts or decrypts a disk using a customer-supplied encryption key. `raw_key` Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. `rsa_encrypted_key` Specifies an RFC 4648 base64 encoded, RSA-wrapped 2048-bit customer-supplied encryption key to either encrypt or decrypt this resource. `sha256` The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. `index` Assigns a zero-based index to this disk, where 0 is reserved for the boot disk. For example, if you have many disks attached to an instance, each disk would have a unique index number. If not specified, the server will choose an appropriate value. `initialize_params` Specifies the parameters for a new disk that will be created alongside the new instance. Use initialization parameters to create boot disks or local SSDs attached to the new instance. `disk_name` Specifies the disk name. If not specified, the default is to use the name of the instance. `disk_size_gb` Specifies the size of the disk in base-2 GB. `disk_type` Reference to a disk type. Specifies the disk type to use to create the instance. If not specified, the default is pd-standard. `source_image` The source image to create this disk. When creating a new instance, one of initializeParams.sourceImage or disks.source is required. To create a disk with one of the public operating system images, specify the image by its family name. `source_image_encryption_key` The customer-supplied encryption key of the source image. Required if the source image is protected by a customer-supplied encryption key. Instance templates do not store customer-supplied encryption keys, so you cannot create disks for instances in a managed instance group if the source images are encrypted with your own keys. `raw_key` Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. `sha256` The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. `interface` Specifies the disk interface to use for attaching this disk, which is either SCSI or NVME. The default is SCSI. Persistent disks must always use SCSI and the request will fail if you attempt to attach a persistent disk in any other format than SCSI. Possible values: * SCSI * NVME `mode` The mode in which to attach this disk, either READ_WRITE or READ_ONLY. If not specified, the default is to attach the disk in READ_WRITE mode. Possible values: * READ_WRITE * READ_ONLY `source` Reference to a disk. When creating a new instance, one of initializeParams.sourceImage or disks.source is required. If desired, you can also attach existing non-root persistent disks using this property. This field is only applicable for persistent disks. `type` Specifies the type of the disk, either SCRATCH or PERSISTENT. If not specified, the default is PERSISTENT. Possible values: * SCRATCH * PERSISTENT `licenses` Any applicable publicly visible licenses. `guest_accelerators` List of the type and count of accelerator cards attached to the instance `accelerator_count` : The number of the guest accelerator cards exposed to this instance. `accelerator_type` : Full or partial URL of the accelerator type resource to expose to this instance. `hostname` The hostname of the instance to be created. The specified hostname must be RFC1035 compliant. If hostname is not specified, the default hostname is [INSTANCE_NAME].c.[PROJECT_ID].internal when using the global DNS, and [INSTANCE_NAME].[ZONE].c.[PROJECT_ID].internal when using zonal DNS. `id` The unique identifier for the resource. This identifier is defined by the server. `label_fingerprint` The fingerprint used for optimistic locking of this resource. Used internally during updates. `labels` Labels to apply to this instance. A list of key->value pairs. `metadata` The metadata key/value pairs to assign to instances that are created from this template. These pairs can consist of custom metadata or predefined keys. `machine_type` A reference to a machine type which defines VM kind. `min_cpu_platform` Specifies a minimum CPU platform for the VM instance. Applicable values are the friendly names of CPU platforms `name` The name of the resource, provided by the client when initially creating the resource. The resource name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `network_interfaces` An array of configurations for this interface. This specifies how this interface is configured to interact with other network services, such as connecting to the internet. Only one network interface is supported per instance. `access_configs` : An array of configurations for this interface. Currently, only one access config, ONE_TO_ONE_NAT, is supported. If there are no accessConfigs specified, then this instance will have no external internet access. ``` `name` : The name of this access configuration. The default and recommended name is External NAT but you can use any arbitrary string you would like. For example, My external IP or Network Access. `nat_ip` : Reference to an address. An external IP address associated with this instance. Specify an unused static external IP address available to the project or leave this field undefined to use an IP from a shared ephemeral IP address pool. If you specify a static external IP address, it must live in the same region as the zone of the instance. `type` : The type of configuration. The default and only option is ONE_TO_ONE_NAT. Possible values: - ONE_TO_ONE_NAT `set_public_ptr` : Specifies whether a public DNS PTR record should be created to map the external IP address of the instance to a DNS domain name. `public_ptr_domain_name` : The DNS domain name for the public PTR record. You can set this field only if the setPublicPtr field is enabled. `network_tier` : This signifies the networking tier used for configuring this access configuration. If an AccessConfig is specified without a valid external IP address, an ephemeral IP will be created with this networkTier. If an AccessConfig with a valid external IP address is specified, it must match that of the networkTier associated with the Address resource owning that IP. Possible values: - PREMIUM - STANDARD ``` `alias_ip_ranges` : An array of alias IP ranges for this network interface. Can only be specified for network interfaces on subnet-mode networks. ``` `ip_cidr_range` : The IP CIDR range represented by this alias IP range. This IP CIDR range must belong to the specified subnetwork and cannot contain IP addresses reserved by system or used by other network interfaces. This range may be a single IP address (e.g. 10.2.3.4), a netmask (e.g. /24) or a CIDR format string (e.g. 10.1.2.0/24). `subnetwork_range_name` : Optional subnetwork secondary range name specifying the secondary range from which to allocate the IP CIDR range for this alias IP range. If left unspecified, the primary range of the subnetwork will be used. ``` `name` : The name of the network interface, generated by the server. For network devices, these are eth0, eth1, etc `network` : Specifies the title of an existing network. When creating an instance, if neither the network nor the subnetwork is specified, the default network global/networks/default is used; if the network is not specified but the subnetwork is specified, the network is inferred. `network_ip` : An IPv4 internal network address to assign to the instance for this network interface. If not specified by the user, an unused internal IP is assigned by the system. `subnetwork` : Reference to a VPC network. If the network resource is in legacy mode, do not provide this property. If the network is in auto subnet mode, providing the subnetwork is optional. If the network is in custom subnet mode, then this field should be specified. `scheduling` Sets the scheduling options for this instance. `automatic_restart` : Specifies whether the instance should be automatically restarted if it is terminated by Compute Engine (not terminated by a user). You can only set the automatic restart option for standard instances. Preemptible instances cannot be automatically restarted. `on_host_maintenance` : Defines the maintenance behavior for this instance. For standard instances, the default behavior is MIGRATE. For preemptible instances, the default and only possible behavior is TERMINATE. For more information, see Setting Instance Scheduling Options. `preemptible` : Defines whether the instance is preemptible. This can only be set during instance creation, it cannot be set or changed after the instance has been created. `service_accounts` A list of service accounts, with their specified scopes, authorized for this instance. Only one service account per VM instance is supported. `email` : Email address of the service account. `scopes` : The list of scopes to be made available for this service account. `shielded_instance_config` Configuration for various parameters related to shielded instances. `enable_secure_boot` : Defines whether the instance has Secure Boot enabled. `enable_vtpm` : Defines whether the instance has the vTPM enabled `enable_integrity_monitoring` : Defines whether the instance has integrity monitoring enabled. `status` The status of the instance. One of the following values: PROVISIONING, STAGING, RUNNING, STOPPING, SUSPENDING, SUSPENDED, and TERMINATED. As a user, use RUNNING to keep a machine “on” and TERMINATED to turn a machine off Possible values: * PROVISIONING * STAGING * RUNNING * STOPPING * SUSPENDING * SUSPENDED * TERMINATED `status_message` An optional, human-readable explanation of the status. `tags` A list of tags to apply to this instance. Tags are used to identify valid sources or targets for network firewalls and are specified by the client during instance creation. The tags can be later modified by the setTags method. Each tag within the list must comply with RFC1035. `fingerprint` Specifies a fingerprint for this request, which is essentially a hash of the metadata’s contents and used for optimistic locking. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update metadata. You must always provide an up-to-date fingerprint hash in order to update or change metadata. `items` An array of tags. Each tag must be 1-63 characters long, and comply with RFC1035. `zone` A reference to the zone where the machine resides. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_instance/google_compute_instance_group_managers resource =================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_instance_group_managers.md) Syntax ------ A `google_compute_instance_group_managers` is used to test a Google InstanceGroupManager resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_instance_group_managers(project: 'chef-gcp-inspec', zone: 'zone') do its('base_instance_names') { should include 'igm' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_instance_group_managers` resource: See the [google_compute_instance_group_manager](../google_compute_instance_group_manager/index#properties) resource for more information. `base_instance_names` an array of `google_compute_instance_group_manager` base_instance_name `creation_timestamps` an array of `google_compute_instance_group_manager` creation_timestamp `current_actions` an array of `google_compute_instance_group_manager` current_actions `descriptions` an array of `google_compute_instance_group_manager` description `ids` an array of `google_compute_instance_group_manager` id `instance_groups` an array of `google_compute_instance_group_manager` instance_group `instance_templates` an array of `google_compute_instance_group_manager` instance_template `names` an array of `google_compute_instance_group_manager` name `named_ports` an array of `google_compute_instance_group_manager` named_ports `regions` an array of `google_compute_instance_group_manager` region `target_pools` an array of `google_compute_instance_group_manager` target_pools `target_sizes` an array of `google_compute_instance_group_manager` target_size `zones` an array of `google_compute_instance_group_manager` zone Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_instance_group_managers/google_compute_instance_groups resource ========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_instance_groups.md) Syntax ------ A `google_compute_instance_groups` is used to test a Google InstanceGroup resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_instance_groups(project: 'chef-gcp-inspec', zone: 'zone') do its('instance_group_names') { should include 'inspec-instance-group' } end ``` ### Test that there are no more than a specified number of instance groups available for the project ``` describe google_compute_instance_groups(project: 'chef-inspec-gcp') do its('count') { should be <= 100} end ``` ### Test that an expected instance_group is available for the project ``` describe google_compute_instance_groups(project: 'chef-inspec-gcp', zone: 'europe-west2-a') do its('instance_group_names') { should include "my-instance-group-name" } end ``` ### Test that a subset of all instance_groups matching “mig*” have size greater than zero ``` google_compute_instance_groups(project: 'chef-inspec-gcp', zone: 'europe-west2-a').where(instance_group_name: /^mig/).instance_group_names.each do |instance_group_name| describe google_compute_instance_group(project: 'chef-inspec-gcp', zone: 'europe-west2-a', name: instance_group_name) do it { should exist } its('size') { should be > 0 } end end ``` Properties ---------- Properties that can be accessed from the `google_compute_instance_groups` resource: See the [google_compute_instance_group](../google_compute_instance_group/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_instance_group` creation_timestamp `descriptions` an array of `google_compute_instance_group` description `instance_group_ids` an array of `google_compute_instance_group` id `instance_group_names` an array of `google_compute_instance_group` name `named_ports` an array of `google_compute_instance_group` named_ports `networks` an array of `google_compute_instance_group` network `regions` an array of `google_compute_instance_group` region `subnetworks` an array of `google_compute_instance_group` subnetwork `zones` an array of `google_compute_instance_group` zone Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_instance_groups/google_compute_instance_template resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_instance_template.md) Syntax ------ A `google_compute_instance_template` is used to test a Google InstanceTemplate resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_instance_template(project: 'chef-gcp-inspec', name: 'inspec-gcp-instance-template') do it { should exist } its('description') { should eq 'A description of the instance template' } its('properties.description') { should eq 'A description of the instance itself' } its('properties.machine_type') { should eq 'f1-micro' } its('properties.tags.items') { should include 'foo' } its('properties.disks.count') { should eq 1 } its('properties.disks.first.auto_delete') { should eq 'true' } its('properties.disks.first.boot') { should eq 'true' } its('properties.network_interfaces.count') { should eq 1 } its('properties.service_accounts.count') { should eq 1 } end describe google_compute_instance_template(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_instance_template` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. Provide this property when you create the resource. `id` The unique identifier for the resource. This identifier is defined by the server. `name` Name of the resource. The name is 1-63 characters long and complies with RFC1035. `properties` The instance properties for this instance template. `can_ip_forward` Enables instances created based on this template to send packets with source IP addresses other than their own and receive packets with destination IP addresses other than their own. If these instances will be used as an IP gateway or it will be set as the next-hop in a Route resource, specify true. If unsure, leave this set to false. `description` An optional text description for the instances that are created from this instance template. `disks` An array of disks that are associated with the instances that are created from this template. `licenses` Any applicable license URI. `auto_delete` Specifies whether the disk will be auto-deleted when the instance is deleted (but not when the disk is detached from the instance). Tip: Disks should be set to autoDelete=true so that leftover disks are not left behind on machine deletion. `boot` Indicates that this is a boot disk. The virtual machine will use the first partition of the disk for its root filesystem. `device_name` Specifies a unique device name of your choice that is reflected into the /dev/disk/by-id/google-* tree of a Linux operating system running within the instance. This name can be used to reference the device for mounting, resizing, and so on, from within the instance. `disk_encryption_key` Encrypts or decrypts a disk using a customer-supplied encryption key. `raw_key` Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. `rsa_encrypted_key` Specifies an RFC 4648 base64 encoded, RSA-wrapped 2048-bit customer-supplied encryption key to either encrypt or decrypt this resource. `sha256` The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. `index` Assigns a zero-based index to this disk, where 0 is reserved for the boot disk. For example, if you have many disks attached to an instance, each disk would have a unique index number. If not specified, the server will choose an appropriate value. `initialize_params` Specifies the parameters for a new disk that will be created alongside the new instance. Use initialization parameters to create boot disks or local SSDs attached to the new instance. `disk_name` Specifies the disk name. If not specified, the default is to use the name of the instance. `disk_size_gb` Specifies the size of the disk in base-2 GB. `disk_type` Reference to a disk type. Specifies the disk type to use to create the instance. If not specified, the default is pd-standard. `source_image` The source image to create this disk. When creating a new instance, one of initializeParams.sourceImage or disks.source is required. To create a disk with one of the public operating system images, specify the image by its family name. `source_image_encryption_key` The customer-supplied encryption key of the source image. Required if the source image is protected by a customer-supplied encryption key. Instance templates do not store customer-supplied encryption keys, so you cannot create disks for instances in a managed instance group if the source images are encrypted with your own keys. `raw_key` Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. `sha256` The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. `interface` Specifies the disk interface to use for attaching this disk, which is either SCSI or NVME. The default is SCSI. Persistent disks must always use SCSI and the request will fail if you attempt to attach a persistent disk in any other format than SCSI. Possible values: * SCSI * NVME `mode` The mode in which to attach this disk, either READ_WRITE or READ_ONLY. If not specified, the default is to attach the disk in READ_WRITE mode. Possible values: * READ_WRITE * READ_ONLY `source` Reference to a disk. When creating a new instance, one of initializeParams.sourceImage or disks.source is required. If desired, you can also attach existing non-root persistent disks using this property. This field is only applicable for persistent disks. Note that for InstanceTemplate, specify the disk name, not the URL for the disk. `type` Specifies the type of the disk, either SCRATCH or PERSISTENT. If not specified, the default is PERSISTENT. Possible values: * SCRATCH * PERSISTENT `labels` Labels to apply to this address. A list of key->value pairs. `machine_type` The machine type to use in the VM instance template. `min_cpu_platform` Specifies a minimum CPU platform for the VM instance. Applicable values are the friendly names of CPU platforms `metadata` The metadata key/value pairs to assign to instances that are created from this template. These pairs can consist of custom metadata or predefined keys. `guest_accelerators` List of the type and count of accelerator cards attached to the instance `accelerator_count` The number of the guest accelerator cards exposed to this instance. `accelerator_type` Full or partial URL of the accelerator type resource to expose to this instance. `network_interfaces` An array of configurations for this interface. This specifies how this interface is configured to interact with other network services, such as connecting to the internet. Only one network interface is supported per instance. `access_configs` An array of configurations for this interface. Currently, only one access config, ONE_TO_ONE_NAT, is supported. If there are no accessConfigs specified, then this instance will have no external internet access. `name` The name of this access configuration. The default and recommended name is External NAT but you can use any arbitrary string you would like. For example, My external IP or Network Access. `nat_ip` Reference to an address. An external IP address associated with this instance. Specify an unused static external IP address available to the project or leave this field undefined to use an IP from a shared ephemeral IP address pool. If you specify a static external IP address, it must live in the same region as the zone of the instance. `type` The type of configuration. The default and only option is ONE_TO_ONE_NAT. Possible values: * ONE_TO_ONE_NAT `set_public_ptr` Specifies whether a public DNS PTR record should be created to map the external IP address of the instance to a DNS domain name. `public_ptr_domain_name` The DNS domain name for the public PTR record. You can set this field only if the setPublicPtr field is enabled. `network_tier` This signifies the networking tier used for configuring this access configuration. If an AccessConfig is specified without a valid external IP address, an ephemeral IP will be created with this networkTier. If an AccessConfig with a valid external IP address is specified, it must match that of the networkTier associated with the Address resource owning that IP. Possible values: * PREMIUM * STANDARD `alias_ip_ranges` An array of alias IP ranges for this network interface. Can only be specified for network interfaces on subnet-mode networks. `ip_cidr_range` The IP CIDR range represented by this alias IP range. This IP CIDR range must belong to the specified subnetwork and cannot contain IP addresses reserved by system or used by other network interfaces. This range may be a single IP address (e.g. 10.2.3.4), a netmask (e.g. /24) or a CIDR format string (e.g. 10.1.2.0/24). `subnetwork_range_name` Optional subnetwork secondary range name specifying the secondary range from which to allocate the IP CIDR range for this alias IP range. If left unspecified, the primary range of the subnetwork will be used. `name` The name of the network interface, generated by the server. For network devices, these are eth0, eth1, etc `network` Specifies the title of an existing network. When creating an instance, if neither the network nor the subnetwork is specified, the default network global/networks/default is used; if the network is not specified but the subnetwork is specified, the network is inferred. `network_ip` An IPv4 internal network address to assign to the instance for this network interface. If not specified by the user, an unused internal IP is assigned by the system. `subnetwork` Reference to a VPC network. If the network resource is in legacy mode, do not provide this property. If the network is in auto subnet mode, providing the subnetwork is optional. If the network is in custom subnet mode, then this field should be specified. `scheduling` Sets the scheduling options for this instance. `automatic_restart` Specifies whether the instance should be automatically restarted if it is terminated by Compute Engine (not terminated by a user). You can only set the automatic restart option for standard instances. Preemptible instances cannot be automatically restarted. `on_host_maintenance` Defines the maintenance behavior for this instance. For standard instances, the default behavior is MIGRATE. For preemptible instances, the default and only possible behavior is TERMINATE. For more information, see Setting Instance Scheduling Options. `preemptible` Defines whether the instance is preemptible. This can only be set during instance creation, it cannot be set or changed after the instance has been created. `service_accounts` A list of service accounts, with their specified scopes, authorized for this instance. Only one service account per VM instance is supported. `email` Email address of the service account. `scopes` The list of scopes to be made available for this service account. `tags` A list of tags to apply to this instance. Tags are used to identify valid sources or targets for network firewalls and are specified by the client during instance creation. The tags can be later modified by the setTags method. Each tag within the list must comply with RFC1035. `fingerprint` Specifies a fingerprint for this request, which is essentially a hash of the metadata’s contents and used for optimistic locking. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update metadata. You must always provide an up-to-date fingerprint hash in order to update or change metadata. `items` An array of tags. Each tag must be 1-63 characters long, and comply with RFC1035. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_instance_template/google_compute_instance_templates resource ============================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_instance_templates.md) Syntax ------ A `google_compute_instance_templates` is used to test a Google InstanceTemplate resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_instance_templates(project: 'chef-gcp-inspec') do its('names') { should include 'inspec-gcp-instance-template' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_instance_templates` resource: See the [google_compute_instance_template](../google_compute_instance_template/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_instance_template` creation_timestamp `descriptions` an array of `google_compute_instance_template` description `ids` an array of `google_compute_instance_template` id `names` an array of `google_compute_instance_template` name `properties` an array of `google_compute_instance_template` properties Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_instance_templates/google_compute_network_endpoint_group resource ================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_network_endpoint_group.md) Syntax ------ A `google_compute_network_endpoint_group` is used to test a Google NetworkEndpointGroup resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_network_endpoint_group(project: 'chef-gcp-inspec', zone: 'zone', name: 'inspec-gcp-endpoint-group') do it { should exist } its('default_port') { should cmp '90' } end describe google_compute_network_endpoint_group(project: 'chef-gcp-inspec', zone: 'zone', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_network_endpoint_group` resource: `id` The unique identifier for the resource. `name` Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `description` An optional description of this resource. Provide this property when you create the resource. `network_endpoint_type` Type of network endpoints in this network endpoint group. Possible values: * GCE_VM_IP_PORT `size` Number of network endpoints in the network endpoint group. `network` The network to which all network endpoints in the NEG belong. Uses “default” project network if unspecified. `subnetwork` Optional subnetwork to which all network endpoints in the NEG belong. `default_port` The default port used if the port number is not specified in the network endpoint. `zone` Zone where the network endpoint group is located. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_network_endpoint_group/google_compute_network resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_network.md) Syntax ------ A `google_compute_network` is used to test a Google Network resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_network(project: 'chef-gcp-inspec', name: 'inspec-network') do it { should exist } its('routing_config.routing_mode') { should cmp 'REGIONAL' } end describe google_compute_network(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP compute network exists ``` describe google_compute_network(project: 'chef-inspec-gcp', name: 'gcp-inspec-network') do it { should exist } end ``` ### Test when a GCP compute network was created ``` describe google_compute_network(project: 'chef-inspec-gcp', name: 'gcp-inspec-network') do its('creation_timestamp_date') { should be > Time.now - 365*60*60*24*10 } end ``` ### Test for an expected network identifier ``` describe google_compute_network(project: 'chef-inspec-gcp', name: 'gcp-inspec-network') do its('id') { should eq 12345567789 } end ``` ### Test whether a single attached subnetwork name is correct ``` describe google_compute_network(project: 'chef-inspec-gcp', name: 'gcp-inspec-network') do its ('subnetworks.count') { should eq 1 } its ('subnetworks.first') { should match "subnetwork-name"} end ``` ### Test whether the network is configured to automatically create subnetworks or not ``` describe google_compute_network(project: 'chef-inspec-gcp', name: 'gcp-inspec-network') do its ('auto_create_subnetworks'){ should be false } end ``` ### Check the network routing configuration routing mode ``` describe google_compute_network(project: 'chef-inspec-gcp', name: 'gcp-inspec-network') do its ('routing_config.routing_mode') { should eq "REGIONAL" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_network` resource: `description` An optional description of this resource. The resource must be recreated to modify this field. `gateway_ipv4` The gateway address for default routing out of the network. This value is selected by GCP. `id` The unique identifier for the resource. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `subnetworks` Server-defined fully-qualified URLs for all subnetworks in this network. `auto_create_subnetworks` When set to `true`, the network is created in “auto subnet mode” and it will create a subnet for each region automatically across the `10.128.0.0/9` address range. When set to `false`, the network is created in “custom subnet mode” so the user can explicitly connect subnetwork resources. `creation_timestamp` Creation timestamp in RFC3339 text format. `routing_config` The network-level routing configuration for this network. Used by Cloud Router to determine what type of network-wide routing behavior to enforce. `routing_mode` The network-wide routing mode to use. If set to `REGIONAL`, this network’s cloud routers will only advertise routes with subnetworks of this network in the same region as the router. If set to `GLOBAL`, this network’s cloud routers will advertise routes with all subnetworks of this network, across regions. Possible values: * REGIONAL * GLOBAL GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_network/google_compute_networks resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_networks.md) Syntax ------ A `google_compute_networks` is used to test a Google Network resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_networks(project: 'chef-gcp-inspec') do its('network_names') { should include 'inspec-network' } end ``` ### Test that there are no more than a specified number of networks available for the project ``` describe google_compute_networks(project: 'chef-inspec-gcp') do its('count') { should be <= 100} end ``` ### Test that an expected network identifier is present in the project ``` describe google_compute_networks(project: 'chef-inspec-gcp') do its('network_ids') { should include 12345678975432 } end ``` ### Test that an expected network name is available for the project ``` describe google_compute_networks(project: 'chef-inspec-gcp') do its('network_names') { should include "network-name" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_networks` resource: See the [google_compute_network](../google_compute_network/index#properties) resource for more information. `descriptions` an array of `google_compute_network` description `gateway_ipv4s` an array of `google_compute_network` gateway_ipv4 `network_ids` an array of `google_compute_network` id `network_names` an array of `google_compute_network` name `subnetworks` an array of `google_compute_network` subnetworks `auto_create_subnetworks` an array of `google_compute_network` auto_create_subnetworks `creation_timestamps` an array of `google_compute_network` creation_timestamp `routing_configs` an array of `google_compute_network` routing_config Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_networks/google_compute_instances resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_instances.md) Syntax ------ A `google_compute_instances` is used to test a Google Instance resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_instances(project: 'chef-gcp-inspec', zone: 'zone') do its('instance_names') { should include 'inspec-instance' } end ``` ### Test that there are no more than a specified number of instances in the project and zone ``` describe google_compute_instances(project: 'chef-inspec-gcp', zone: 'europe-west2-a') do its('count') { should be <= 100} end ``` ### Test the exact number of instances in the project and zone ``` describe google_compute_instances(project: 'chef-inspec-gcp', zone: 'europe-west2-a') do its('instance_ids.count') { should cmp 9 } end ``` ### Test that an instance with a particular name exists in the project and zone ``` describe google_compute_instances(project: 'chef-inspec-gcp', zone: 'europe-west2-a') do its('instance_names') { should include "my-favorite-instance" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_instances` resource: See the [google_compute_instance](../google_compute_instance/index#properties) resource for more information. `can_ip_forwards` an array of `google_compute_instance` can_ip_forward `cpu_platforms` an array of `google_compute_instance` cpu_platform `creation_timestamps` an array of `google_compute_instance` creation_timestamp `deletion_protections` an array of `google_compute_instance` deletion_protection `disks` an array of `google_compute_instance` disks `guest_accelerators` an array of `google_compute_instance` guest_accelerators `hostnames` an array of `google_compute_instance` hostname `instance_ids` an array of `google_compute_instance` id `label_fingerprints` an array of `google_compute_instance` label_fingerprint `labels` an array of `google_compute_instance` labels `metadata` an array of `google_compute_instance` metadata `machine_types` an array of `google_compute_instance` machine_type `min_cpu_platforms` an array of `google_compute_instance` min_cpu_platform `instance_names` an array of `google_compute_instance` name `network_interfaces` an array of `google_compute_instance` network_interfaces `schedulings` an array of `google_compute_instance` scheduling `service_accounts` an array of `google_compute_instance` service_accounts `shielded_instance_configs` an array of `google_compute_instance` shielded_instance_config `statuses` an array of `google_compute_instance` status `status_messages` an array of `google_compute_instance` status_message `tags` an array of `google_compute_instance` tags `zones` an array of `google_compute_instance` zone Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_instances/google_compute_network_endpoint_groups resource =================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_network_endpoint_groups.md) Syntax ------ A `google_compute_network_endpoint_groups` is used to test a Google NetworkEndpointGroup resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_network_endpoint_groups(project: 'chef-gcp-inspec', zone: 'zone') do its('default_ports') { should include '90' } its('names') { should include 'inspec-gcp-endpoint-group' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_network_endpoint_groups` resource: See the [google_compute_network_endpoint_group](../google_compute_network_endpoint_group/index#properties) resource for more information. `ids` an array of `google_compute_network_endpoint_group` id `names` an array of `google_compute_network_endpoint_group` name `descriptions` an array of `google_compute_network_endpoint_group` description `network_endpoint_types` an array of `google_compute_network_endpoint_group` network_endpoint_type `sizes` an array of `google_compute_network_endpoint_group` size `networks` an array of `google_compute_network_endpoint_group` network `subnetworks` an array of `google_compute_network_endpoint_group` subnetwork `default_ports` an array of `google_compute_network_endpoint_group` default_port `zones` an array of `google_compute_network_endpoint_group` zone Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_network_endpoint_groups/google_compute_node_template resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_node_template.md) Syntax ------ A `google_compute_node_template` is used to test a Google NodeTemplate resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_node_template(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'inspec-node-template') do it { should exist } its('node_affinity_labels') { should include('key' => 'value') } end describe google_compute_node_template(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_node_template` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional textual description of the resource. `name` Name of the resource. `node_affinity_labels` Labels to use for node affinity, which will be used in instance scheduling. `node_type` Node type to use for nodes group that are created from this template. Only one of nodeTypeFlexibility and nodeType can be specified. `node_type_flexibility` Flexible properties for the desired node type. Node groups that use this node template will create nodes of a type that matches these properties. Only one of nodeTypeFlexibility and nodeType can be specified. `cpus` Number of virtual CPUs to use. `memory` Physical memory available to the node, defined in MB. `local_ssd` Use local SSD `server_binding` (Beta only) The server binding policy for nodes using this template. Determines where the nodes should restart following a maintenance event. `type` Type of server binding policy. If `RESTART_NODE_ON_ANY_SERVER`, nodes using this template will restart on any physical server following a maintenance event. If `RESTART_NODE_ON_MINIMAL_SERVER`, nodes using this template will restart on the same physical server following a maintenance event, instead of being live migrated to or restarted on a new physical server. This option may be useful if you are using software licenses tied to the underlying server characteristics such as physical sockets or cores, to avoid the need for additional licenses when maintenance occurs. However, VMs on such nodes will experience outages while maintenance is applied. Possible values: * RESTART_NODE_ON_ANY_SERVER * RESTART_NODE_ON_MINIMAL_SERVERS `region` Region where nodes using the node template will be created GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_node_template/google_compute_node_templates resource ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_node_templates.md) Syntax ------ A `google_compute_node_templates` is used to test a Google NodeTemplate resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_node_templates(project: 'chef-gcp-inspec', region: 'europe-west2') do its('names') { should include 'inspec-node-template' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_node_templates` resource: See the [google_compute_node_template](../google_compute_node_template/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_node_template` creation_timestamp `descriptions` an array of `google_compute_node_template` description `names` an array of `google_compute_node_template` name `node_affinity_labels` an array of `google_compute_node_template` node_affinity_labels `node_types` an array of `google_compute_node_template` node_type `node_type_flexibilities` an array of `google_compute_node_template` node_type_flexibility `server_bindings` (Beta only) an array of `google_compute_node_template` server_binding `regions` an array of `google_compute_node_template` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_node_templates/google_compute_node_groups resource ====================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_node_groups.md) Syntax ------ A `google_compute_node_groups` is used to test a Google NodeGroup resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_node_groups(project: 'chef-gcp-inspec', zone: 'zone') do it { should exist } its('descriptions') { should include 'A description of the node group' } its('sizes') { should include '0' } its('names') { should include 'inspec-node-group' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_node_groups` resource: See the [google_compute_node_group](../google_compute_node_group/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_node_group` creation_timestamp `descriptions` an array of `google_compute_node_group` description `names` an array of `google_compute_node_group` name `node_templates` an array of `google_compute_node_group` node_template `sizes` an array of `google_compute_node_group` size `autoscaling_policies` (Beta only) an array of `google_compute_node_group` autoscaling_policy `zones` an array of `google_compute_node_group` zone Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_node_groups/google_compute_project_info resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_project_info.md) Syntax ------ A `google_compute_project_info` is used to test a Google ProjectInfo resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_project_info(project: 'chef-gcp-inspec') do it { should exist } its('default_service_account') { should match "developer.gserviceaccount.com" } end ``` ### Test that GCP compute project information exists ``` describe google_compute_project_info(project: 'chef-inspec-gcp') do it { should exist } end ``` ### Test that GCP compute project default service account is as expected ``` describe google_compute_project_info(project: 'chef-inspec-gcp') do its('default_service_account') { should eq '12345-compute@developer.gserviceaccount.com' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_project_info` resource: `name` The name of this project `common_instance_metadata` Metadata shared for all instances in this project `items` Array of key/values `key` Key of the metadata key/value pair `value` Value of the metadata key/value pair `enabled_features` Restricted features enabled for use on this project `default_service_account` Default service account used by VMs in this project `xpn_project_status` The role this project has in a shared VPC configuration. `default_network_tier` The default network tier used for configuring resources in this project `quotas` Quotas applied to this project `metric` Name of the quota metric `limit` Quota limit for this metric `usage` Current usage of this metric `owner` Owning resource. This is the resource on which this quota is applied. `creation_timestamp` Creation timestamp in RFC3339 text format. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_project_info/google_compute_node_group resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_node_group.md) Syntax ------ A `google_compute_node_group` is used to test a Google NodeGroup resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_node_group(project: 'chef-gcp-inspec', zone: 'zone', name: 'inspec-node-group') do it { should exist } its('description') { should cmp 'A description of the node group' } its('size') { should cmp '0' } end describe google_compute_node_group(project: 'chef-gcp-inspec', zone: 'zone', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_node_group` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional textual description of the resource. `name` Name of the resource. `node_template` The URL of the node template to which this node group belongs. `size` The total number of nodes in the node group. `autoscaling_policy` (Beta only) If you use sole-tenant nodes for your workloads, you can use the node group autoscaler to automatically manage the sizes of your node groups. `mode` The autoscaling mode. Set to one of the following: - OFF: Disables the autoscaler. - ON: Enables scaling in and scaling out. - ONLY_SCALE_OUT: Enables only scaling out. You must use this mode if your node groups are configured to restart their hosted VMs on minimal servers. Possible values: * OFF * ON * ONLY_SCALE_OUT `min_nodes` Minimum size of the node group. Must be less than or equal to max-nodes. The default value is 0. `max_nodes` Maximum size of the node group. Set to a value less than or equal to 100 and greater than or equal to min-nodes. `zone` Zone where this node group is located GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_node_group/google_compute_region_backend_service resource ================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_region_backend_service.md) Syntax ------ A `google_compute_region_backend_service` is used to test a Google RegionBackendService resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_region_backend_service(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'inspec-gcp-region-backend-service') do it { should exist } its('description') { should eq 'A regional description' } its('protocol') { should eq 'TCP' } its('timeout_sec') { should eq '15' } end describe google_compute_region_backend_service(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_region_backend_service` resource: `affinity_cookie_ttl_sec` Lifetime of cookies in seconds if session_affinity is GENERATED_COOKIE. If set to 0, the cookie is non-persistent and lasts only until the end of the browser session (or equivalent). The maximum allowed value for TTL is one day. When the load balancing scheme is INTERNAL, this field is not used. `backends` The set of backends that serve this RegionBackendService. `balancing_mode` Specifies the balancing mode for this backend. Possible values: * UTILIZATION * RATE * CONNECTION `capacity_scaler` A multiplier applied to the group’s maximum servicing capacity (based on UTILIZATION, RATE or CONNECTION). ~>**NOTE**: This field cannot be set for INTERNAL region backend services (default loadBalancingScheme), but is required for non-INTERNAL backend service. The total capacity_scaler for all backends must be non-zero. A setting of 0 means the group is completely drained, offering 0% of its available Capacity. Valid range is [0.0,1.0]. `description` An optional description of this resource. Provide this property when you create the resource. `failover` This field designates whether this is a failover backend. More than one failover backend can be configured for a given RegionBackendService. `group` The fully-qualified URL of an Instance Group or Network Endpoint Group resource. In case of instance group this defines the list of instances that serve traffic. Member virtual machine instances from each instance group must live in the same zone as the instance group itself. No two backends in a backend service are allowed to use same Instance Group resource. For Network Endpoint Groups this defines list of endpoints. All endpoints of Network Endpoint Group must be hosted on instances located in the same zone as the Network Endpoint Group. Backend services cannot mix Instance Group and Network Endpoint Group backends. When the `load_balancing_scheme` is INTERNAL, only instance groups are supported. Note that you must specify an Instance Group or Network Endpoint Group resource using the fully-qualified URL, rather than a partial URL. `max_connections` The max number of simultaneous connections for the group. Can be used with either CONNECTION or UTILIZATION balancing modes. Cannot be set for INTERNAL backend services. For CONNECTION mode, either maxConnections or one of maxConnectionsPerInstance or maxConnectionsPerEndpoint, as appropriate for group type, must be set. `max_connections_per_instance` The max number of simultaneous connections that a single backend instance can handle. Cannot be set for INTERNAL backend services. This is used to calculate the capacity of the group. Can be used in either CONNECTION or UTILIZATION balancing modes. For CONNECTION mode, either maxConnections or maxConnectionsPerInstance must be set. `max_connections_per_endpoint` The max number of simultaneous connections that a single backend network endpoint can handle. Cannot be set for INTERNAL backend services. This is used to calculate the capacity of the group. Can be used in either CONNECTION or UTILIZATION balancing modes. For CONNECTION mode, either maxConnections or maxConnectionsPerEndpoint must be set. `max_rate` The max requests per second (RPS) of the group. Cannot be set for INTERNAL backend services. Can be used with either RATE or UTILIZATION balancing modes, but required if RATE mode. Either maxRate or one of maxRatePerInstance or maxRatePerEndpoint, as appropriate for group type, must be set. `max_rate_per_instance` The max requests per second (RPS) that a single backend instance can handle. This is used to calculate the capacity of the group. Can be used in either balancing mode. For RATE mode, either maxRate or maxRatePerInstance must be set. Cannot be set for INTERNAL backend services. `max_rate_per_endpoint` The max requests per second (RPS) that a single backend network endpoint can handle. This is used to calculate the capacity of the group. Can be used in either balancing mode. For RATE mode, either maxRate or maxRatePerEndpoint must be set. Cannot be set for INTERNAL backend services. `max_utilization` Used when balancingMode is UTILIZATION. This ratio defines the CPU utilization target for the group. Valid range is [0.0, 1.0]. Cannot be set for INTERNAL backend services. `circuit_breakers` Settings controlling the volume of connections to a backend service. This field is applicable only when the `load_balancing_scheme` is set to INTERNAL_MANAGED and the `protocol` is set to HTTP, HTTPS, or HTTP2. `connect_timeout` (Beta only) The timeout for new network connections to hosts. `seconds` Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive. `nanos` Span of time that’s a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0 seconds field and a positive nanos field. Must be from 0 to 999,999,999 inclusive. `max_requests_per_connection` Maximum requests for a single backend connection. This parameter is respected by both the HTTP/1.1 and HTTP/2 implementations. If not specified, there is no limit. Setting this parameter to 1 will effectively disable keep alive. `max_connections` The maximum number of connections to the backend cluster. Defaults to 1024. `max_pending_requests` The maximum number of pending requests to the backend cluster. Defaults to 1024. `max_requests` The maximum number of parallel requests to the backend cluster. Defaults to 1024. `max_retries` The maximum number of parallel retries to the backend cluster. Defaults to 3. `consistent_hash` Consistent Hash-based load balancing can be used to provide soft session affinity based on HTTP headers, cookies or other properties. This load balancing policy is applicable only for HTTP connections. The affinity to a particular destination host will be lost when one or more hosts are added/removed from the destination service. This field specifies parameters that control consistent hashing. This field only applies when all of the following are true: `load_balancing_scheme` is set to INTERNAL_MANAGED, `protocol` is set to HTTP, HTTPS, or HTTP2, and `locality_lb_policy` is set to MAGLEV or RING_HASH `http_cookie` Hash is based on HTTP Cookie. This field describes a HTTP cookie that will be used as the hash key for the consistent hash load balancer. If the cookie is not present, it will be generated. This field is applicable if the sessionAffinity is set to HTTP_COOKIE. `ttl` Lifetime of the cookie. `seconds` Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive. `nanos` Span of time that’s a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0 seconds field and a positive nanos field. Must be from 0 to 999,999,999 inclusive. `name` Name of the cookie. `path` Path to set for the cookie. `http_header_name` The hash based on the value of the specified header field. This field is applicable if the sessionAffinity is set to HEADER_FIELD. `minimum_ring_size` The minimum number of virtual nodes to use for the hash ring. Larger ring sizes result in more granular load distributions. If the number of hosts in the load balancing pool is larger than the ring size, each host will be assigned a single virtual node. Defaults to 1024. `connection_draining` Settings for connection draining `draining_timeout_sec` Time for which instance will be drained (not accept new connections, but still work to finish started). `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. `failover_policy` Policy for failovers. `disable_connection_drain_on_failover` On failover or failback, this field indicates whether connection drain will be honored. Setting this to true has the following effect: connections to the old active pool are not drained. Connections to the new active pool use the timeout of 10 min (currently fixed). Setting to false has the following effect: both old and new connections will have a drain timeout of 10 min. This can be set to true only if the protocol is TCP. The default is false. `drop_traffic_if_unhealthy` This option is used only when no healthy VMs are detected in the primary and backup instance groups. When set to true, traffic is dropped. When set to false, new connections are sent across all VMs in the primary group. The default is false. `failover_ratio` The value of the field must be in [0, 1]. If the ratio of the healthy VMs in the primary backend is at or below this number, traffic arriving at the load-balanced IP will be directed to the failover backend. In case where ‘failoverRatio’ is not set or all the VMs in the backup backend are unhealthy, the traffic will be directed back to the primary backend in the “force” mode, where traffic will be spread to the healthy VMs with the best effort, or to all VMs when no VM is healthy. This field is only used with l4 load balancing. `fingerprint` Fingerprint of this resource. A hash of the contents stored in this object. This field is used in optimistic locking. `health_checks` The set of URLs to HealthCheck resources for health checking this RegionBackendService. Currently at most one health check can be specified, and a health check is required. `id` The unique identifier for the resource. `load_balancing_scheme` Indicates what kind of load balancing this regional backend service will be used for. A backend service created for one type of load balancing cannot be used with the other(s). Possible values: * INTERNAL * INTERNAL_MANAGED `locality_lb_policy` The load balancing algorithm used within the scope of the locality. The possible values are: ROUND*ROBIN This is a simple policy in which each healthy backend is selected in round robin order. LEAST_REQUEST An O(1) algorithm which selects two random healthy hosts and picks the host which has fewer active requests. RING_HASH The ring/modulo hash load balancer implements consistent hashing to backends. The algorithm has the property that the addition/removal of a host from a set of N hosts only affects 1/N of the requests. RANDOM The load balancer selects a random healthy host. ORIGINAL_DESTINATION Backend host is selected based on the client connection metadata, i.e., connections are opened to the same address as the destination address of the incoming connection before the connection was redirected to the load balancer. MAGLEV used as a drop in replacement for the ring hash load balancer. Maglev is not as stable as ring hash but has faster table lookup build times and host selection times. For more information about Maglev, refer to <https://ai.google/research/pubs/pub44824>. This field is applicable only when the `load_balancing_scheme` is set to INTERNAL_MANAGED and the `protocol` is set to HTTP, HTTPS, or HTTP2. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `outlier_detection` Settings controlling eviction of unhealthy hosts from the load balancing pool. This field is applicable only when the `load_balancing_scheme` is set to INTERNAL_MANAGED and the `protocol` is set to HTTP, HTTPS, or HTTP2. `base_ejection_time` The base time that a host is ejected for. The real time is equal to the base time multiplied by the number of times the host has been ejected. Defaults to 30000ms or 30s. `seconds` Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive. `nanos` Span of time that’s a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0 `seconds` field and a positive `nanos` field. Must be from 0 to 999,999,999 inclusive. `consecutive_errors` Number of errors before a host is ejected from the connection pool. When the backend host is accessed over HTTP, a 5xx return code qualifies as an error. Defaults to 5. `consecutive_gateway_failure` The number of consecutive gateway failures (502, 503, 504 status or connection errors that are mapped to one of those status codes) before a consecutive gateway failure ejection occurs. Defaults to 5. `enforcing_consecutive_errors` The percentage chance that a host will be actually ejected when an outlier status is detected through consecutive 5xx. This setting can be used to disable ejection or to ramp it up slowly. Defaults to 100. `enforcing_consecutive_gateway_failure` The percentage chance that a host will be actually ejected when an outlier status is detected through consecutive gateway failures. This setting can be used to disable ejection or to ramp it up slowly. Defaults to 0. `enforcing_success_rate` The percentage chance that a host will be actually ejected when an outlier status is detected through success rate statistics. This setting can be used to disable ejection or to ramp it up slowly. Defaults to 100. `interval` Time interval between ejection sweep analysis. This can result in both new ejections as well as hosts being returned to service. Defaults to 10 seconds. `seconds` Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive. `nanos` Span of time that’s a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0 `seconds` field and a positive `nanos` field. Must be from 0 to 999,999,999 inclusive. `max_ejection_percent` Maximum percentage of hosts in the load balancing pool for the backend service that can be ejected. Defaults to 10%. `success_rate_minimum_hosts` The number of hosts in a cluster that must have enough request volume to detect success rate outliers. If the number of hosts is less than this setting, outlier detection via success rate statistics is not performed for any host in the cluster. Defaults to 5. `success_rate_request_volume` The minimum number of total requests that must be collected in one interval (as defined by the interval duration above) to include this host in success rate based outlier detection. If the volume is lower than this setting, outlier detection via success rate statistics is not performed for that host. Defaults to 100. `success_rate_stdev_factor` This factor is used to determine the ejection threshold for success rate outlier ejection. The ejection threshold is the difference between the mean success rate, and the product of this factor and the standard deviation of the mean success rate: mean - (stdev * success_rate_stdev_factor). This factor is divided by a thousand to get a double. That is, if the desired factor is 1.9, the runtime value should be 1900. Defaults to 1900. `port_name` A named port on a backend instance group representing the port for communication to the backend VMs in that group. Required when the loadBalancingScheme is EXTERNAL, INTERNAL_MANAGED, or INTERNAL_SELF_MANAGED and the backends are instance groups. The named port must be defined on each backend instance group. This parameter has no meaning if the backends are NEGs. API sets a default of “http” if not given. Must be omitted when the loadBalancingScheme is INTERNAL (Internal TCP/UDP Load Balancing). `protocol` The protocol this RegionBackendService uses to communicate with backends. The default is HTTP. **NOTE**: HTTP2 is only valid for beta HTTP/2 load balancer types and may result in errors if used with the GA API. Possible values: * HTTP * HTTPS * HTTP2 * SSL * TCP * UDP `session_affinity` Type of session affinity to use. The default is NONE. Session affinity is not applicable if the protocol is UDP. Possible values: * NONE * CLIENT * IP * CLIENT*IP_PORT_PROTO * CLIENT*IP_PROTO * GENERATED*COOKIE * HEADER_FIELD * HTTP_COOKIE `timeout_sec` How many seconds to wait for the backend before considering it a failed request. Default is 30 seconds. Valid range is [1, 86400]. `log_config` This field denotes the logging options for the load balancer traffic served by this backend service. If logging is enabled, logs will be exported to Stackdriver. `enable` Whether to enable logging for the load balancer traffic served by this backend service. `sample_rate` This field can only be specified if logging is enabled for this backend service. The value of the field must be in [0, 1]. This configures the sampling rate of requests to the load balancer where 1.0 means all logged requests are reported and 0.0 means no logged requests are reported. The default value is 1.0. `network` The URL of the network to which this backend service belongs. This field can only be specified when the load balancing scheme is set to INTERNAL. `region` A reference to the region where the regional backend service resides. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_region_backend_service/google_compute_region_backend_services resource =================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_region_backend_services.md) Syntax ------ A `google_compute_region_backend_services` is used to test a Google RegionBackendService resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_region_backend_services(project: 'chef-gcp-inspec', region: 'europe-west2') do its('count') { should be >= 1 } its('names') { should include 'inspec-gcp-region-backend-service' } its('protocols') { should include 'TCP' } its('timeout_secs') { should include '15' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_region_backend_services` resource: See the [google_compute_region_backend_service](../google_compute_region_backend_service/index#properties) resource for more information. `affinity_cookie_ttl_secs` an array of `google_compute_region_backend_service` affinity_cookie_ttl_sec `backends` an array of `google_compute_region_backend_service` backends `circuit_breakers` an array of `google_compute_region_backend_service` circuit_breakers `consistent_hashes` an array of `google_compute_region_backend_service` consistent_hash `connection_drainings` an array of `google_compute_region_backend_service` connection_draining `creation_timestamps` an array of `google_compute_region_backend_service` creation_timestamp `descriptions` an array of `google_compute_region_backend_service` description `failover_policies` an array of `google_compute_region_backend_service` failover_policy `fingerprints` an array of `google_compute_region_backend_service` fingerprint `health_checks` an array of `google_compute_region_backend_service` health_checks `ids` an array of `google_compute_region_backend_service` id `load_balancing_schemes` an array of `google_compute_region_backend_service` load_balancing_scheme `locality_lb_policies` an array of `google_compute_region_backend_service` locality_lb_policy `names` an array of `google_compute_region_backend_service` name `outlier_detections` an array of `google_compute_region_backend_service` outlier_detection `port_names` an array of `google_compute_region_backend_service` port_name `protocols` an array of `google_compute_region_backend_service` protocol `session_affinities` an array of `google_compute_region_backend_service` session_affinity `timeout_secs` an array of `google_compute_region_backend_service` timeout_sec `log_configs` an array of `google_compute_region_backend_service` log_config `networks` an array of `google_compute_region_backend_service` network `regions` an array of `google_compute_region_backend_service` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_region_backend_services/google_compute_region resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_region.md) Syntax ------ A `google_compute_region` is used to test a Google Region resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_region(project: 'chef-gcp-inspec', name: 'europe-west2') do it { should exist } it { should be_up } its('zone_names') { should include "#{gcp_location}-a" } end describe google_compute_region(project: 'chef-gcp-inspec', name: 'notthere') do it { should_not exist } end ``` ### Test that a GCP compute region exists ``` describe google_compute_region(project: 'chef-inspec-gcp', region: 'europe-west2') do it { should exist } end ``` ### Test that a GCP compute region is in the expected state ``` describe google_compute_region(project: 'chef-inspec-gcp', region: 'europe-west2') do its('status') { should eq 'UP' } # or equivalently it { should be_up } end ``` ### Test a GCP compute region identifier ``` describe google_compute_region(project: 'chef-inspec-gcp', region: "asia-east1") do its('id') { should eq "1220" } end ``` ### Check that a region is associated with the expected zone fully qualified name ``` describe google_compute_region(project: 'chef-inspec-gcp', region: "asia-east1") do its('zones') { should include "https://www.googleapis.com/compute/v1/projects/spaterson-project/zones/asia-east1-a" } end ``` ### Check that a region is associated with the expected zone short name ``` describe google_compute_region(project: 'chef-inspec-gcp', region: "asia-east1") do its('zone_names') { should include "asia-east1-a" } end ``` The `zone_names` property is also useful for subsequently looping over associated `google_compute_zone` resources. For example: ``` google_compute_region(project: 'chef-inspec-gcp', region: "asia-east1").zone_names.each do |zone_name| describe google_compute_zone(project: 'chef-inspec-gcp', name: zone_name) do it { should be_up } end end ``` Properties ---------- Properties that can be accessed from the `google_compute_region` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `deprecated` The deprecation state of this resource. `deleted` An optional RFC3339 timestamp on or after which the deprecation state of this resource will be changed to DELETED. `deprecated` An optional RFC3339 timestamp on or after which the deprecation state of this resource will be changed to DEPRECATED. `obsolete` An optional RFC3339 timestamp on or after which the deprecation state of this resource will be changed to OBSOLETE. `replacement` The URL of the suggested replacement for a deprecated resource. The suggested replacement resource must be the same kind of resource as the deprecated resource. `state` The deprecation state of this resource. This can be DEPRECATED, OBSOLETE, or DELETED. Operations which create a new resource using a DEPRECATED resource will return successfully, but with a warning indicating the deprecated resource and recommending its replacement. Operations which use OBSOLETE or DELETED resources will be rejected and result in an error. Possible values: * DEPRECATED * OBSOLETE * DELETED `description` An optional description of this resource. `id` The unique identifier for the resource. `name` Name of the resource. `quotas` Quotas assigned to this region. `metric` Name of the quota metric. `limit` Quota limit for this metric. `usage` Current usage of this metric. `owner` Owning resource. This is the resource on which this quota is applied. `status` Status of the region, either UP or DOWN. Possible values: * UP * DOWN `zones` List of zones within the region GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_region/google_compute_region_instance_group_managers resource =========================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_region_instance_group_managers.md) Syntax ------ A `google_compute_region_instance_group_managers` is used to test a Google RegionInstanceGroupManager resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_region_instance_group_managers(project: 'chef-gcp-inspec', region: 'europe-west2') do its('instance_group_manager_names') { should include 'inspec-rigm' } its('base_instance_names') { should include 'rigm1' } end ``` ### Test that there are no more than a specified number of instance groups available for the project ``` describe google_compute_region_instance_group_managers(project: 'chef-inspec-gcp', region: 'europe-west2') do its('count') { should be <= 100} end ``` ### Test that an expected instance_group is available for the project ``` describe google_compute_region_instance_group_managers(project: 'chef-inspec-gcp', region: 'europe-west2') do its('instance_group_names') { should include "my-instance-group-name" } end ``` ### Test that a subset of all instance_groups matching “mig*” have size greater than zero ``` google_compute_region_instance_group_managers(project: 'chef-inspec-gcp', region: 'europe-west2').where(instance_group_name: /^mig/).instance_group_names.each do |instance_group_name| describe google_compute_instance_group(project: 'chef-inspec-gcp', region: 'europe-west2', name: instance_group_name) do it { should exist } its('target_size') { should be > 0 } end end ``` Properties ---------- Properties that can be accessed from the `google_compute_region_instance_group_managers` resource: See the [google_compute_region_instance_group_manager](../google_compute_region_instance_group_manager/index#properties) resource for more information. `base_instance_names` an array of `google_compute_region_instance_group_manager` base_instance_name `creation_timestamps` an array of `google_compute_region_instance_group_manager` creation_timestamp `current_actions` an array of `google_compute_region_instance_group_manager` current_actions `descriptions` an array of `google_compute_region_instance_group_manager` description `instance_group_manager_ids` an array of `google_compute_region_instance_group_manager` id `instance_groups` an array of `google_compute_region_instance_group_manager` instance_group `instance_templates` an array of `google_compute_region_instance_group_manager` instance_template `instance_group_manager_names` an array of `google_compute_region_instance_group_manager` name `named_ports` an array of `google_compute_region_instance_group_manager` named_ports `target_pools` an array of `google_compute_region_instance_group_manager` target_pools `target_sizes` an array of `google_compute_region_instance_group_manager` target_size `auto_healing_policies` an array of `google_compute_region_instance_group_manager` auto_healing_policies `regions` an array of `google_compute_region_instance_group_manager` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_region_instance_group_managers/google_compute_regional_disk resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_regional_disk.md) Syntax ------ A `google_compute_regional_disk` is used to test a Google Regional Disk resource Examples -------- ``` describe google_compute_regional_disk(project: 'chef-gcp-inspec', name: 'my_disk', region: 'region') do it { should exist } its('type') { should match 'pd-standard' } end describe.one do google_compute_regional_disk(project: 'chef-gcp-inspec', name: 'my_disk', region: 'region').labels.each_pair do |key, value| describe key do it { should cmp "environment" } end end end describe google_compute_regional_disk(project: 'chef-gcp-inspec', name: 'nonexistent', region: 'region') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_regional_disk` resource: `label_fingerprint` The fingerprint used for optimistic locking of this resource. Used internally during updates. `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. Provide this property when you create the resource. `id` The unique identifier for the resource. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `size_gb` Size of the persistent disk, specified in GB. You can specify this field when creating a persistent disk using the sourceImage or sourceSnapshot parameter, or specify it alone to create an empty persistent disk. If you specify this field along with sourceImage or sourceSnapshot, the value of sizeGb must not be less than the size of the sourceImage or the size of the snapshot. `physical_block_size_bytes` Physical block size of the persistent disk, in bytes. If not present in a request, a default value is used. Currently supported sizes are 4096 and 16384, other sizes may be added in the future. If an unsupported value is requested, the error message will list the supported values for the caller’s project. `type` URL of the disk type resource describing which disk type to use to create the disk. Provide this when creating the disk. `region` A reference to the region where the disk resides. `replica_zones` A reference to the zones where the disk resides. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_regional_disk/google_compute_region_instance_group_manager resource ========================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_region_instance_group_manager.md) Syntax ------ A `google_compute_region_instance_group_manager` is used to test a Google RegionInstanceGroupManager resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_region_instance_group_manager(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'inspec-rigm') do it { should exist } its('base_instance_name') { should eq 'rigm1' } its('target_size') { should eq '1' } its('named_ports.first.name') { should eq 'https' } its('named_ports.first.port') { should eq '8888' } its('auto_healing_policies.first.initial_delay_sec') { should eq '300' } end describe google_compute_region_instance_group_manager(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP compute region instance group manager has the expected size ``` describe google_compute_region_instance_group_manager(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-test') do its('target_size') { should eq 2 } end ``` ### Test that a GCP compute region instance group manager has a port with supplied name and value ``` describe google_compute_region_instance_group_manager(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-test') do its('named_ports') { should include "http" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_region_instance_group_manager` resource: `base_instance_name` The base instance name to use for instances in this group. The value must be 1-58 characters long. Instances are named by appending a hyphen and a random four-character string to the base instance name. The base instance name must comply with RFC1035. `creation_timestamp` The creation timestamp for this managed instance group in RFC3339 text format. `current_actions` The list of instance actions and the number of instances in this managed instance group that are scheduled for each of those actions. `abandoning` : The total number of instances in the managed instance group that are scheduled to be abandoned. Abandoning an instance removes it from the managed instance group without deleting it. `creating` : The number of instances in the managed instance group that are scheduled to be created or are currently being created. If the group fails to create any of these instances, it tries again until it creates the instance successfully. If you have disabled creation retries, this field will not be populated; instead, the creatingWithoutRetries field will be populated. `creating_without_retries` : The number of instances that the managed instance group will attempt to create. The group attempts to create each instance only once. If the group fails to create any of these instances, it decreases the group’s targetSize value accordingly. `deleting` : The number of instances in the managed instance group that are scheduled to be deleted or are currently being deleted. `none` : The number of instances in the managed instance group that are running and have no scheduled actions. `recreating` : The number of instances in the managed instance group that are scheduled to be recreated or are currently being being recreated. Recreating an instance deletes the existing root persistent disk and creates a new disk from the image that is defined in the instance template. `refreshing` : The number of instances in the managed instance group that are being reconfigured with properties that do not require a restart or a recreate action. For example, setting or removing target pools for the instance. `restarting` : The number of instances in the managed instance group that are scheduled to be restarted or are currently being restarted. `description` An optional description of this resource. Provide this property when you create the resource. `id` A unique identifier for this resource `instance_group` The instance group being managed `instance_template` The instance template that is specified for this managed instance group. The group uses this template to create all new instances in the managed instance group. `name` The name of the managed instance group. The name must be 1-63 characters long, and comply with RFC1035. `named_ports` Named ports configured for the Instance Groups complementary to this Instance Group Manager. `name` : The name for this named port. The name must be 1-63 characters long, and comply with RFC1035. `port` : The port number, which can be a value between 1 and 65535. `target_pools` TargetPool resources to which instances in the instanceGroup field are added. The target pools automatically apply to all of the instances in the managed instance group. `target_size` The target number of running instances for this managed instance group. Deleting or abandoning instances reduces this number. Resizing the group changes this number. `auto_healing_policies` The autohealing policy for this managed instance group `health_check` : The URL for the health check that signals autohealing. `initial_delay_sec` : The number of seconds that the managed instance group waits before it applies autohealing policies to new instances or recently recreated instances `region` The region the managed instance group resides. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_region_instance_group_manager/google_compute_route resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_route.md) Syntax ------ A `google_compute_route` is used to test a Google Route resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_route(project: 'chef-gcp-inspec', name: 'inspec-gcp-route') do it { should exist } its('dest_range') { should eq '15.0.0.0/24' } its('network') { should match /\/gcp-inspec-network$/ } its('next_hop_ip') { should eq '10.2.0.1' } its('priority') { should eq '100' } end describe google_compute_route(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_route` resource: `dest_range` The destination range of outgoing packets that this route applies to. Only IPv4 is supported. `description` An optional description of this resource. Provide this property when you create the resource. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `network` The network that this route applies to. `priority` The priority of this route. Priority is used to break ties in cases where there is more than one matching route of equal prefix length. In the case of two routes with equal prefix length, the one with the lowest-numbered priority value wins. Default value is 1000. Valid range is 0 through 65535. `tags` A list of instance tags to which this route applies. `next_hop_gateway` URL to a gateway that should handle matching packets. Currently, you can only specify the internet gateway, using a full or partial valid URL: _ <https://www.googleapis.com/compute/v1/projects/project/> global/gateways/default-internet-gateway _ projects/project/global/gateways/default-internet-gateway * global/gateways/default-internet-gateway `next_hop_instance` URL to an instance that should handle matching packets. You can specify this as a full or partial URL. For example: _ <https://www.googleapis.com/compute/v1/projects/project/zones/zone/> instances/instance _ projects/project/zones/zone/instances/instance * zones/zone/instances/instance `next_hop_ip` Network IP address of an instance that should handle matching packets. `next_hop_vpn_tunnel` URL to a VpnTunnel that should handle matching packets. `next_hop_network` URL to a Network that should handle matching packets. `next_hop_ilb` The URL to a forwarding rule of type loadBalancingScheme=INTERNAL that should handle matching packets. You can only specify the forwarding rule as a partial or full URL. For example, the following are all valid URLs: <https://www.googleapis.com/compute/v1/projects/project/regions/region/forwardingRules/forwardingRule> regions/region/forwardingRules/forwardingRule Note that this can only be used when the destinationRange is a public (non-RFC 1918) IP CIDR range. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_route/google_compute_router_nat resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_router_nat.md) Syntax ------ A `google_compute_router_nat` is used to test a Google RouterNat resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_router_nat(project: 'chef-gcp-inspec', region: 'europe-west2', router: 'inspec-gcp-router', name: 'inspec-router-nat') do it { should exist } its('nat_ip_allocate_option') { should cmp 'AUTO_ONLY' } its('source_subnetwork_ip_ranges_to_nat') { should cmp 'ALL_SUBNETWORKS_ALL_IP_RANGES' } its('min_ports_per_vm') { should cmp '2' } its('log_config.enable') { should cmp 'true' } its('log_config.filter') { should cmp 'ERRORS_ONLY' } end describe google_compute_router(project: 'chef-gcp-inspec', region: 'europe-west2', router: 'nonexistent', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_router_nat` resource: `name` Name of the NAT service. The name must be 1-63 characters long and comply with RFC1035. `nat_ip_allocate_option` How external IPs should be allocated for this NAT. Valid values are `AUTO_ONLY` for only allowing NAT IPs allocated by Google Cloud Platform, or `MANUAL_ONLY` for only user-allocated NAT IP addresses. Possible values: * MANUAL_ONLY * AUTO_ONLY `nat_ips` Self-links of NAT IPs. Only valid if natIpAllocateOption is set to MANUAL_ONLY. `drain_nat_ips` A list of URLs of the IP resources to be drained. These IPs must be valid static external IPs that have been assigned to the NAT. `source_subnetwork_ip_ranges_to_nat` How NAT should be configured per Subnetwork. If `ALL_SUBNETWORKS_ALL_IP_RANGES`, all of the IP ranges in every Subnetwork are allowed to Nat. If `ALL_SUBNETWORKS_ALL_PRIMARY_IP_RANGES`, all of the primary IP ranges in every Subnetwork are allowed to Nat. `LIST_OF_SUBNETWORKS`: A list of Subnetworks are allowed to Nat (specified in the field subnetwork below). Note that if this field contains ALL_SUBNETWORKS_ALL_IP_RANGES or ALL_SUBNETWORKS_ALL_PRIMARY_IP_RANGES, then there should not be any other RouterNat section in any Router for this network in this region. Possible values: * ALL_SUBNETWORKS_ALL_IP_RANGES * ALL_SUBNETWORKS_ALL_PRIMARY_IP_RANGES * LIST_OF_SUBNETWORKS `subnetwork` One or more subnetwork NAT configurations. Only used if `source_subnetwork_ip_ranges_to_nat` is set to `LIST_OF_SUBNETWORKS` `name` Self-link of subnetwork to NAT `source_ip_ranges_to_nat` List of options for which source IPs in the subnetwork should have NAT enabled. Supported values include: * `ALL_IP_RANGES` * `LIST_OF_SECONDARY_IP_RANGES` * `PRIMARY_IP_RANGE` `secondary_ip_range_names` List of the secondary ranges of the subnetwork that are allowed to use NAT. This can be populated only if `LIST_OF_SECONDARY_IP_RANGES` is one of the values in sourceIpRangesToNat `min_ports_per_vm` Minimum number of ports allocated to a VM from this NAT. `udp_idle_timeout_sec` Timeout (in seconds) for UDP connections. Defaults to 30s if not set. `icmp_idle_timeout_sec` Timeout (in seconds) for ICMP connections. Defaults to 30s if not set. `tcp_established_idle_timeout_sec` Timeout (in seconds) for TCP established connections. Defaults to 1200s if not set. `tcp_transitory_idle_timeout_sec` Timeout (in seconds) for TCP transitory connections. Defaults to 30s if not set. `log_config` Configuration for logging on NAT `enable` Indicates whether or not to export logs. `filter` Specifies the desired filtering of logs on this NAT. Possible values: * ERRORS_ONLY * TRANSLATIONS_ONLY * ALL `router` The name of the Cloud Router in which this NAT will be configured. `region` Region where the router and NAT reside. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_router_nat/google_compute_regions resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_regions.md) Syntax ------ A `google_compute_regions` is used to test a Google Region resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_regions(project: 'chef-gcp-inspec') do its('count') { should be >= 1 } its('region_names') { should include "#{gcp_location}" } its('region_statuses') { should_not include "DOWN" } its('region_ids') { should include "1290" } end ``` ### Use this InSpec resource to enumerate IDs then test in-depth using `google_compute_region` ``` google_compute_regions(project: 'chef-inspec-gcp').region_names.each do |region_name| describe google_compute_region(project: 'chef-inspec-gcp', region: region_name) do it { should be_up } end end ``` ### Test that there are more than a specified number of regions available for the project ``` describe google_compute_regions(project: 'chef-inspec-gcp') do its('count') { should be >= 10} end ``` ### Test that an expected region is available for the project ``` describe google_compute_regions(project: 'chef-inspec-gcp') do its('region_names') { should include 'europe-west2' } end ``` ### Test whether any regions are in status “DOWN” ``` describe google_compute_regions(project: 'chef-inspec-gcp') do its('region_statuses') { should_not include "DOWN" } end ``` ### Test that a subset of all regions matching “europe*” are “UP” ``` google_compute_regions(project: gcp_project_id).where(region_name: /^europe/).region_names.each do |region_name| describe google_compute_region(project: 'chef-inspec-gcp', region: region_name) do it { should be_up } end end ``` Properties ---------- Properties that can be accessed from the `google_compute_regions` resource: See the [google_compute_region](../google_compute_region/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_region` creation_timestamp `deprecateds` an array of `google_compute_region` deprecated `descriptions` an array of `google_compute_region` description `region_ids` an array of `google_compute_region` id `region_names` an array of `google_compute_region` name `quotas` an array of `google_compute_region` quotas `region_statuses` an array of `google_compute_region` status `zones` an array of `google_compute_region` zones Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_regions/google_compute_router resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_router.md) Syntax ------ A `google_compute_router` is used to test a Google Router resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_router(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'inspec-gcp-router') do it { should exist } its('bgp.asn') { should eq '64514' } its('bgp.advertise_mode') { should eq 'CUSTOM' } its('bgp.advertised_groups') { should include 'ALL_SUBNETS' } its('bgp.advertised_ip_ranges.count') { should eq 2 } its('bgp.advertised_ip_ranges.first.range') { should eq '1.2.3.4' } its('bgp.advertised_ip_ranges.last.range') { should eq '1.2.3.4' } its('network') { should match /\/gcp-inspec-network$/ } end describe google_compute_router(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_router` resource: `id` The unique identifier for the resource. `creation_timestamp` Creation timestamp in RFC3339 text format. `name` Name of the resource. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `description` An optional description of this resource. `network` A reference to the network to which this router belongs. `bgp` BGP information specific to this router. `asn` Local BGP Autonomous System Number (ASN). Must be an RFC6996 private ASN, either 16-bit or 32-bit. The value will be fixed for this router resource. All VPN tunnels that link to this router will have the same local ASN. `advertise_mode` User-specified flag to indicate which mode to use for advertisement. Possible values: * DEFAULT * CUSTOM `advertised_groups` User-specified list of prefix groups to advertise in custom mode. This field can only be populated if advertiseMode is CUSTOM and is advertised to all peers of the router. These groups will be advertised in addition to any specified prefixes. Leave this field blank to advertise no custom groups. This enum field has the one valid value: ALL_SUBNETS `advertised_ip_ranges` User-specified list of individual IP ranges to advertise in custom mode. This field can only be populated if advertiseMode is CUSTOM and is advertised to all peers of the router. These IP ranges will be advertised in addition to any specified groups. Leave this field blank to advertise no custom IP ranges. `range` The IP range to advertise. The value must be a CIDR-formatted string. `description` User-specified description for the IP range. `region` Region where the router resides. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_router/google_compute_router_nats resource ====================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_router_nats.md) Syntax ------ A `google_compute_router_nats` is used to test a Google RouterNat resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_router_nats(project: 'chef-gcp-inspec', region: 'europe-west2', router: 'inspec-gcp-router') do its('names') { should include 'inspec-router-nat' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_router_nats` resource: See the [google_compute_router_nat](../google_compute_router_nat/index#properties) resource for more information. `names` an array of `google_compute_router_nat` name `nat_ip_allocate_options` an array of `google_compute_router_nat` nat_ip_allocate_option `nat_ips` an array of `google_compute_router_nat` nat_ips `drain_nat_ips` an array of `google_compute_router_nat` drain_nat_ips `source_subnetwork_ip_ranges_to_nats` an array of `google_compute_router_nat` source_subnetwork_ip_ranges_to_nat `subnetworks` an array of `google_compute_router_nat` subnetwork `min_ports_per_vms` an array of `google_compute_router_nat` min_ports_per_vm `udp_idle_timeout_secs` an array of `google_compute_router_nat` udp_idle_timeout_sec `icmp_idle_timeout_secs` an array of `google_compute_router_nat` icmp_idle_timeout_sec `tcp_established_idle_timeout_secs` an array of `google_compute_router_nat` tcp_established_idle_timeout_sec `tcp_transitory_idle_timeout_secs` an array of `google_compute_router_nat` tcp_transitory_idle_timeout_sec `log_configs` an array of `google_compute_router_nat` log_config `routers` an array of `google_compute_router_nat` router `regions` an array of `google_compute_router_nat` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_router_nats/google_compute_routes resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_routes.md) Syntax ------ A `google_compute_routes` is used to test a Google Route resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_routes(project: 'chef-gcp-inspec') do its('count') { should be >= 1 } its('dest_ranges') { should include '15.0.0.0/24' } its('next_hop_ips') { should include '10.2.0.1' } its('priorities') { should include '100' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_routes` resource: See the [google_compute_route](../google_compute_route/index#properties) resource for more information. `dest_ranges` an array of `google_compute_route` dest_range `descriptions` an array of `google_compute_route` description `names` an array of `google_compute_route` name `networks` an array of `google_compute_route` network `priorities` an array of `google_compute_route` priority `tags` an array of `google_compute_route` tags `next_hop_gateways` an array of `google_compute_route` next_hop_gateway `next_hop_instances` an array of `google_compute_route` next_hop_instance `next_hop_ips` an array of `google_compute_route` next_hop_ip `next_hop_vpn_tunnels` an array of `google_compute_route` next_hop_vpn_tunnel `next_hop_networks` an array of `google_compute_route` next_hop_network `next_hop_ilbs` an array of `google_compute_route` next_hop_ilb Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_routes/google_compute_routers resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_routers.md) Syntax ------ A `google_compute_routers` is used to test a Google Router resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_routers(project: 'chef-gcp-inspec', region: 'europe-west2') do its('names') { should include 'inspec-gcp-router' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_routers` resource: See the [google_compute_router](../google_compute_router/index#properties) resource for more information. `ids` an array of `google_compute_router` id `creation_timestamps` an array of `google_compute_router` creation_timestamp `names` an array of `google_compute_router` name `descriptions` an array of `google_compute_router` description `networks` an array of `google_compute_router` network `bgps` an array of `google_compute_router` bgp `regions` an array of `google_compute_router` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_routers/google_compute_security_policy resource ========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_security_policy.md) Syntax ------ A `google_compute_security_policy` is used to test a Google SecurityPolicy resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_security_policy(project: 'chef-gcp-inspec', name: 'sec-policy') do it { should exist } its('rules.size') { should cmp 2 } its('rules.first.priority') { should cmp '1000' } its('rules.first.match.config.src_ip_ranges.first') { should cmp '9.9.9.0/24' } end describe google_compute_security_policy(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_security_policy` resource: `name` Name of the security policy. `id` The unique identifier for the resource. `rules` A list of rules that belong to this policy. There must always be a default rule (rule with priority 2147483647 and match “*"). If no rules are provided when creating a security policy, a default rule with action “allow” will be added. `description` A description of the rule. `priority` An integer indicating the priority of a rule in the list. The priority must be a positive value between 0 and 2147483647. Rules are evaluated from highest to lowest priority where 0 is the highest priority and 2147483647 is the lowest prority. `action` The Action to preform when the client connection triggers the rule. Can currently be either “allow” or “deny()” where valid values for status are 403, 404, and 502. `preview` If set to true, the specified action is not enforced. `match` A match condition that incoming traffic is evaluated against. If it evaluates to true, the corresponding ‘action’ is enforced. `description` : A description of the rule. `expr` : User defined CEVAL expression. A CEVAL expression is used to specify match criteria such as origin.ip, source.region_code and contents in the request header. ``` `expression` : Textual representation of an expression in Common Expression Language syntax. `title` : Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs which allow to enter the expression. `description` : Optional. Description of the expression. This is a longer text which describes the expression, e.g. when hovered over it in a UI. `location` : Optional. String indicating the location of the expression for error reporting, e.g. a file name and a position in the file. ``` `versioned_expr` : Preconfigured versioned expression. If this field is specified, config must also be specified. Available preconfigured expressions along with their requirements are: `SRC_IPS_V1` - must specify the corresponding srcIpRange field in config. `config` : The configuration options available when specifying versionedExpr. This field must be specified if versionedExpr is specified and cannot be specified if versionedExpr is not specified. ``` `src_ip_ranges` : CIDR IP address range. ``` GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_security_policy/google_compute_security_policies resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_security_policies.md) Syntax ------ A `google_compute_security_policies` is used to test a Google SecurityPolicy resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_security_policies(project: 'chef-gcp-inspec') do its('count') { should be >= 1 } its('names') { should include 'sec-policy' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_security_policies` resource: See the [google_compute_security_policy](../google_compute_security_policy/index#properties) resource for more information. `names` an array of `google_compute_security_policy` name `ids` an array of `google_compute_security_policy` id `rules` an array of `google_compute_security_policy` rules Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_security_policies/google_compute_snapshot resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_snapshot.md) Syntax ------ A `google_compute_snapshot` is used to test a Google Snapshot resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_snapshot(project: 'chef-gcp-inspec', name: 'inspec-gcp-disk-snapshot') do it { should exist } its('source_disk') { should match 'inspec-snapshot-disk' } end describe google_compute_snapshot(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_snapshot` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `id` The unique identifier for the resource. `disk_size_gb` Size of the snapshot, specified in GB. `name` Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `description` An optional description of this resource. `storage_bytes` A size of the the storage used by the snapshot. As snapshots share storage, this number is expected to change with snapshot creation/deletion. `licenses` A list of public visible licenses that apply to this snapshot. This can be because the original image had licenses attached (such as a Windows image). snapshotEncryptionKey nested object Encrypts the snapshot using a customer-supplied encryption key. `labels` Labels to apply to this Snapshot. `label_fingerprint` The fingerprint used for optimistic locking of this resource. Used internally during updates. `source_disk` A reference to the disk used to create this snapshot. `zone` A reference to the zone where the disk is hosted. `snapshot_encryption_key` The customer -supplied encryption key of the snapshot. Required if the source snapshot is protected by a customer-supplied encryption key. `raw_key` Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. `sha256` The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. `kms_key_name` The name of the encryption key that is stored in Google Cloud KMS. `source_disk_encryption_key` The customer -supplied encryption key of the source snapshot. Required if the source snapshot is protected by a customer-supplied encryption key. `raw_key` Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. `kms_key_name` The name of the encryption key that is stored in Google Cloud KMS. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_snapshot/google_compute_snapshots resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_snapshots.md) Syntax ------ A `google_compute_snapshots` is used to test a Google Snapshot resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_snapshots(project: 'chef-gcp-inspec') do its('count') { should be >= 1 } end describe.one do google_compute_snapshots(project: 'chef-gcp-inspec').names do |snapshot_name| describe google_compute_snapshot(project: 'chef-gcp-inspec', name: snapshot_name) do its('source_disk') { should match 'inspec-snapshot-disk' } end end end ``` Properties ---------- Properties that can be accessed from the `google_compute_snapshots` resource: See the [google_compute_snapshot](../google_compute_snapshot/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_snapshot` creation_timestamp `ids` an array of `google_compute_snapshot` id `disk_size_gbs` an array of `google_compute_snapshot` disk_size_gb `names` an array of `google_compute_snapshot` name `descriptions` an array of `google_compute_snapshot` description `storage_bytes` an array of `google_compute_snapshot` storage_bytes `licenses` an array of `google_compute_snapshot` licenses `labels` an array of `google_compute_snapshot` labels `label_fingerprints` an array of `google_compute_snapshot` label_fingerprint `source_disks` an array of `google_compute_snapshot` source_disk `zones` an array of `google_compute_snapshot` zone `snapshot_encryption_keys` an array of `google_compute_snapshot` snapshot_encryption_key `source_disk_encryption_keys` an array of `google_compute_snapshot` source_disk_encryption_key Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_snapshots/google_compute_ssl_certificate resource ========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_ssl_certificate.md) Syntax ------ A `google_compute_ssl_certificate` is used to test a Google SslCertificate resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_ssl_certificate(project: 'chef-gcp-inspec', name: 'inspec-gcp-ssl-certificate') do it { should exist } its('description') { should eq 'A fake ssl certificate (DO NOT USE)' } its('certificate') { should eq '-----BEGIN CERTIFICATE----- <KEY> -----END CERTIFICATE----- ' } end describe google_compute_ssl_certificate(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_ssl_certificate` resource: `certificate` The certificate in PEM format. The certificate chain must be no greater than 5 certs long. The chain must include at least one intermediate cert. `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. `id` The unique identifier for the resource. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `private_key` The write-only private key in PEM format. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_ssl_certificate/google_compute_ssl_policies resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_ssl_policies.md) Syntax ------ A `google_compute_ssl_policies` is used to test a Google SslPolicy resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_ssl_policies(project: 'chef-gcp-inspec') do it { should exist } its('names') { should include 'inspec-gcp-ssl-policy' } its('profiles') { should include 'CUSTOM' } its('count') { should eq 1 } end google_compute_ssl_policies(project: 'chef-gcp-inspec').names.each do |policy_name| describe google_compute_ssl_policy(project: 'chef-gcp-inspec', name: policy_name) do its('min_tls_version') { should eq 'TLS_1_2' } end end ``` Properties ---------- Properties that can be accessed from the `google_compute_ssl_policies` resource: See the [google_compute_ssl_policy](../google_compute_ssl_policy/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_ssl_policy` creation_timestamp `descriptions` an array of `google_compute_ssl_policy` description `ids` an array of `google_compute_ssl_policy` id `names` an array of `google_compute_ssl_policy` name `profiles` an array of `google_compute_ssl_policy` profile `min_tls_versions` an array of `google_compute_ssl_policy` min_tls_version `enabled_features` an array of `google_compute_ssl_policy` enabled_features `custom_features` an array of `google_compute_ssl_policy` custom_features `fingerprints` an array of `google_compute_ssl_policy` fingerprint `warnings` an array of `google_compute_ssl_policy` warnings Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_ssl_policies/google_compute_ssl_certificates resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_ssl_certificates.md) Syntax ------ A `google_compute_ssl_certificates` is used to test a Google SslCertificate resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_ssl_certificates(project: 'chef-gcp-inspec') do its('names') { should include 'inspec-gcp-ssl-certificate' } its('descriptions') { should include 'A fake ssl certificate (DO NOT USE)' } its('certificates') { should include '-----BEGIN CERTIFICATE----- MIICqjCCAk+gAwIBAgIJAIuJ+0352Kq4MAoGCCqGSM49BAMCMIGwMQswCQYDVQQG EwJVUzETMBEGA1UECAwKV2FzaGlu<KEY>UJxp+M6a+nGMX+UJR3YgAiEAvvl39QRVAiv84hdoCuyON0lJ zqGNhIPGq2ULqXKK8BY= -----END CERTIFICATE----- ' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_ssl_certificates` resource: See the [google_compute_ssl_certificate](../google_compute_ssl_certificate/index#properties) resource for more information. `certificates` an array of `google_compute_ssl_certificate` certificate `creation_timestamps` an array of `google_compute_ssl_certificate` creation_timestamp `descriptions` an array of `google_compute_ssl_certificate` description `ids` an array of `google_compute_ssl_certificate` id `names` an array of `google_compute_ssl_certificate` name `private_keys` an array of `google_compute_ssl_certificate` private_key Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_ssl_certificates/google_compute_subnetwork_iam_binding resource ================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_subnetwork_iam_binding.md) Syntax ------ A `google_compute_subnetwork_iam_binding` is used to test a Google Subnetwork Iam Bindings Examples -------- ``` describe google_compute_subnetwork_iam_binding(project: "project", region: "region", name: "name", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_subnetwork_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_subnetwork_iam_binding/google_compute_ssl_policy resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_ssl_policy.md) Syntax ------ A `google_compute_ssl_policy` is used to test a Google SslPolicy resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_ssl_policy(project: 'chef-gcp-inspec', name: 'inspec-gcp-ssl-policy') do it { should exist } its('min_tls_version') { should eq 'TLS_1_2' } its('profile') { should eq 'CUSTOM' } its('custom_features') { should include 'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384' } its('custom_features') { should include 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384' } end describe google_compute_ssl_policy(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_ssl_policy` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. `id` The unique identifier for the resource. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `profile` Profile specifies the set of SSL features that can be used by the load balancer when negotiating SSL with clients. If using `CUSTOM`, the set of SSL features to enable must be specified in the `customFeatures` field. Possible values: * COMPATIBLE * MODERN * RESTRICTED * CUSTOM `min_tls_version` The minimum version of SSL protocol that can be used by the clients to establish a connection with the load balancer. Possible values: * TLS_1_0 * TLS_1_1 * TLS_1_2 `enabled_features` The list of features enabled in the SSL policy. `custom_features` A list of features enabled when the selected profile is CUSTOM. The method returns the set of features that can be specified in this list. This field must be empty if the profile is not CUSTOM. `fingerprint` Fingerprint of this resource. A hash of the contents stored in this object. This field is used in optimistic locking. `warnings` If potential misconfigurations are detected for this SSL policy, this field will be populated with warning messages. `code` A warning code, if applicable. `message` A human-readable description of the warning code. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_ssl_policy/google_compute_subnetwork_iam_policy resource ================================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_subnetwork_iam_policy.md) Syntax ------ A `google_compute_subnetwork_iam_policy` is used to test a Google Subnetwork Iam Policy resource Examples -------- ``` describe google_compute_subnetwork_iam_policy(project: "project", region: "region", name: "name") do it { should exist } end google_compute_subnetwork_iam_policy(project: "project", region: "region", name: "name").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` Properties ---------- Properties that can be accessed from the `google_compute_subnetwork_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` : The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` : Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_subnetwork_iam_policy/google_compute_subnetwork resource ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_subnetwork.md) Syntax ------ A `google_compute_subnetwork` is used to test a Google Subnetwork resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_subnetwork(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'inspec-subnet') do it { should exist } its('ip_cidr_range') { should eq '10.2.0.0/16' } its('log_config.enable') { should be true } its('log_config.flow_sampling') { should cmp '0.5' } its('log_config.aggregation_interval') { should cmp 'INTERVAL_10_MIN' } its('log_config.metadata') { should include 'INCLUDE_ALL_METADATA' } end describe google_compute_subnetwork(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP compute subnetwork exists ``` describe google_compute_subnetwork(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-subnetwork') do it { should exist } end ``` ### Test when a GCP compute subnetwork was created ``` describe google_compute_subnetwork(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-subnetwork') do its('creation_timestamp') { should be > Time.now - 365*60*60*24*10 } end ``` ### Test for an expected subnetwork identifier ``` describe google_compute_subnetwork(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-subnetwork') do its('id') { should eq 12345567789 } end ``` ### Test that a subnetwork gateway address is as expected ``` describe google_compute_subnetwork(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-subnetwork') do its('gateway_address') { should eq "10.2.0.1" } end ``` ### Test that a subnetwork IP CIDR range is as expected ``` describe google_compute_subnetwork(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-subnetwork') do its('ip_cidr_range') { should eq "10.2.0.0/29" } end ``` ### Test that a subnetwork is associated with the expected network ``` describe google_compute_subnetwork(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-subnetwork') do its('network') { should match "gcp_network_name" } end ``` ### Test whether VMs in this subnet can access Google services without assigning external IP addresses through Private Google Access ``` describe google_compute_subnetwork(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-subnetwork') do its('private_ip_google_access') { should be false } end ``` Properties ---------- Properties that can be accessed from the `google_compute_subnetwork` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. Provide this property when you create the resource. This field can be set only at resource creation time. `gateway_address` The gateway address for default routes to reach destination addresses outside this subnetwork. `id` The unique identifier for the resource. `ip_cidr_range` The range of internal addresses that are owned by this subnetwork. Provide this property when you create the subnetwork. For example, 10.0.0.0/8 or 192.168.0.0/16. Ranges must be unique and non-overlapping within a network. Only IPv4 is supported. `name` The name of the resource, provided by the client when initially creating the resource. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `network` The network this subnet belongs to. Only networks that are in the distributed mode can have subnetworks. `purpose` (Beta only) The purpose of the resource. This field can be either PRIVATE or INTERNAL_HTTPS_LOAD_BALANCER. A subnetwork with purpose set to INTERNAL_HTTPS_LOAD_BALANCER is a user-created subnetwork that is reserved for Internal HTTP(S) Load Balancing. If unspecified, the purpose defaults to PRIVATE. If set to INTERNAL_HTTPS_LOAD_BALANCER you must also set the role. Possible values: * INTERNAL_HTTPS_LOAD_BALANCER * PRIVATE `role` (Beta only) The role of subnetwork. Currently, this field is only used when purpose = INTERNAL_HTTPS_LOAD_BALANCER. The value can be set to ACTIVE or BACKUP. An ACTIVE subnetwork is one that is currently being used for Internal HTTP(S) Load Balancing. A BACKUP subnetwork is one that is ready to be promoted to ACTIVE or is currently draining. Possible values: * ACTIVE * BACKUP `secondary_ip_ranges` An array of configurations for secondary IP ranges for VM instances contained in this subnetwork. The primary IP of such VM must belong to the primary ipCidrRange of the subnetwork. The alias IPs may belong to either primary or secondary ranges. `range_name` The name associated with this subnetwork secondary range, used when adding an alias IP range to a VM instance. The name must be 1-63 characters long, and comply with RFC1035. The name must be unique within the subnetwork. `ip_cidr_range` The range of IP addresses belonging to this subnetwork secondary range. Provide this property when you create the subnetwork. Ranges must be unique and non-overlapping with all primary and secondary IP ranges within a network. Only IPv4 is supported. `private_ip_google_access` When enabled, VMs in this subnetwork without external IP addresses can access Google APIs and services by using Private Google Access. `region` URL of the GCP region for this subnetwork. `log_config` Denotes the logging options for the subnetwork flow logs. If logging is enabled logs will be exported to Stackdriver. This field cannot be set if the `purpose` of this subnetwork is `INTERNAL_HTTPS_LOAD_BALANCER` `enable` If logging is enabled for this subnetwork `aggregation_interval` Can only be specified if VPC flow logging for this subnetwork is enabled. Toggles the aggregation interval for collecting flow logs. Increasing the interval time will reduce the amount of generated flow logs for long lasting connections. Default is an interval of 5 seconds per connection. Possible values: * INTERVAL_5_SEC * INTERVAL_30_SEC * INTERVAL_1_MIN * INTERVAL_5_MIN * INTERVAL_10_MIN * INTERVAL_15_MIN `flow_sampling` Can only be specified if VPC flow logging for this subnetwork is enabled. The value of the field must be in [0, 1. Set the sampling rate of VPC flow logs within the subnetwork where 1.0 means all collected logs are reported and 0.0 means no logs are reported. Default is 0.5 which means half of all collected logs are reported. `metadata` Can only be specified if VPC flow logging for this subnetwork is enabled. Configures whether metadata fields should be added to the reported VPC flow logs. Possible values: * EXCLUDE_ALL_METADATA * INCLUDE_ALL_METADATA GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_subnetwork/google_compute_target_http_proxy resource ============================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_target_http_proxy.md) Syntax ------ A `google_compute_target_http_proxy` is used to test a Google TargetHttpProxy resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_target_http_proxy(project: 'chef-gcp-inspec', name: 'inspec-gcp-http-proxy') do it { should exist } its('description') { should eq 'A HTTP proxy' } its('url_map') { should match /\/inspec-gcp-url-map$/ } end describe google_compute_target_http_proxy(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_target_http_proxy` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. `id` The unique identifier for the resource. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `url_map` A reference to the UrlMap resource that defines the mapping from URL to the BackendService. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_target_http_proxy/google_compute_subnetworks resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_subnetworks.md) Syntax ------ A `google_compute_subnetworks` is used to test a Google Subnetwork resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_subnetworks(project: 'chef-gcp-inspec', region: 'europe-west2') do its('ip_cidr_ranges') { should include '10.2.0.0/16' } its('subnetwork_names') { should include 'inspec-subnet' } end ``` ### Test that there are no more than a specified number of subnetworks available for the project and region ``` describe google_compute_subnetworks(project: 'chef-inspec-gcp', region: 'europe-west2') do its('count') { should be <= 100} end ``` ### Test that an expected subnetwork identifier is present in the project and region ``` describe google_compute_subnetworks(project: 'chef-inspec-gcp', region: 'europe-west2') do its('subnetwork_ids') { should include 12345678975432 } end ``` ### Test that an expected subnetwork name is available for the project and region ``` describe google_compute_subnetworks(project: 'chef-inspec-gcp', region: 'europe-west2') do its('subnetwork_names') { should include "subnetwork-name" } end ``` ### Test that an expected subnetwork network name is not present for the project and region ``` describe google_compute_subnetworks(project: 'chef-inspec-gcp', region: 'europe-west2') do its('subnetwork_networks') { should not include "network-name" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_subnetworks` resource: See the [google_compute_subnetwork](../google_compute_subnetwork/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_subnetwork` creation_timestamp `descriptions` an array of `google_compute_subnetwork` description `gateway_addresses` an array of `google_compute_subnetwork` gateway_address `subnetwork_ids` an array of `google_compute_subnetwork` id `ip_cidr_ranges` an array of `google_compute_subnetwork` ip_cidr_range `subnetwork_names` an array of `google_compute_subnetwork` name `networks` an array of `google_compute_subnetwork` network `purposes` (Beta only) an array of `google_compute_subnetwork` purpose `roles` (Beta only) an array of `google_compute_subnetwork` role `secondary_ip_ranges` an array of `google_compute_subnetwork` secondary_ip_ranges `private_ip_google_accesses` an array of `google_compute_subnetwork` private_ip_google_access `regions` an array of `google_compute_subnetwork` region `log_configs` an array of `google_compute_subnetwork` log_config Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_subnetworks/google_compute_target_http_proxies resource =============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_target_http_proxies.md) Syntax ------ A `google_compute_target_http_proxies` is used to test a Google TargetHttpProxy resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_target_http_proxies(project: 'chef-gcp-inspec') do its('names') { should include 'inspec-gcp-http-proxy' } its('descriptions') { should include 'A HTTP proxy' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_target_http_proxies` resource: See the [google_compute_target_http_proxy](../google_compute_target_http_proxy/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_target_http_proxy` creation_timestamp `descriptions` an array of `google_compute_target_http_proxy` description `ids` an array of `google_compute_target_http_proxy` id `names` an array of `google_compute_target_http_proxy` name `url_maps` an array of `google_compute_target_http_proxy` url_map Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_target_http_proxies/google_compute_target_https_proxies resource ================================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_target_https_proxies.md) Syntax ------ A `google_compute_target_https_proxies` is used to test a Google TargetHttpsProxy resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_target_https_proxies(project: 'chef-gcp-inspec') do its('names') { should include 'inspec-gcp-https-proxy' } its('descriptions') { should include 'A HTTPS target proxy' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_target_https_proxies` resource: See the [google_compute_target_https_proxy](../google_compute_target_https_proxy/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_target_https_proxy` creation_timestamp `descriptions` an array of `google_compute_target_https_proxy` description `ids` an array of `google_compute_target_https_proxy` id `names` an array of `google_compute_target_https_proxy` name `quic_overrides` an array of `google_compute_target_https_proxy` quic_override `ssl_certificates` an array of `google_compute_target_https_proxy` ssl_certificates `ssl_policies` an array of `google_compute_target_https_proxy` ssl_policy `url_maps` an array of `google_compute_target_https_proxy` url_map Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_target_https_proxies/google_compute_target_pools resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_target_pools.md) Syntax ------ A `google_compute_target_pools` is used to test a Google TargetPool resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_target_pools(project: 'chef-gcp-inspec', region: 'europe-west2') do its('names') { should include 'inspec-gcp-target-pool' } its('session_affinities') { should include 'CLIENT_IP' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_target_pools` resource: See the [google_compute_target_pool](../google_compute_target_pool/index#properties) resource for more information. `backup_pools` an array of `google_compute_target_pool` backup_pool `creation_timestamps` an array of `google_compute_target_pool` creation_timestamp `descriptions` an array of `google_compute_target_pool` description `failover_ratios` an array of `google_compute_target_pool` failover_ratio `health_checks` an array of `google_compute_target_pool` health_check `ids` an array of `google_compute_target_pool` id `instances` an array of `google_compute_target_pool` instances `names` an array of `google_compute_target_pool` name `session_affinities` an array of `google_compute_target_pool` session_affinity `regions` an array of `google_compute_target_pool` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_target_pools/google_compute_target_https_proxy resource ============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_target_https_proxy.md) Syntax ------ A `google_compute_target_https_proxy` is used to test a Google TargetHttpsProxy resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_target_https_proxy(project: 'chef-gcp-inspec', name: 'inspec-gcp-https-proxy') do it { should exist } its('url_map') { should match /\/inspec-gcp-url-map$/ } its('description') { should eq 'A HTTPS target proxy' } end describe google_compute_target_https_proxy(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_target_https_proxy` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. `id` The unique identifier for the resource. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `quic_override` Specifies the QUIC override policy for this resource. This determines whether the load balancer will attempt to negotiate QUIC with clients or not. Can specify one of NONE, ENABLE, or DISABLE. If NONE is specified, uses the QUIC policy with no user overrides, which is equivalent to DISABLE. Possible values: * NONE * ENABLE * DISABLE `ssl_certificates` A list of SslCertificate resources that are used to authenticate connections between users and the load balancer. At least one SSL certificate must be specified. `ssl_policy` A reference to the SslPolicy resource that will be associated with the TargetHttpsProxy resource. If not set, the TargetHttpsProxy resource will not have any SSL policy configured. `url_map` A reference to the UrlMap resource that defines the mapping from URL to the BackendService. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_target_https_proxy/google_compute_target_pool resource ====================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_target_pool.md) Syntax ------ A `google_compute_target_pool` is used to test a Google TargetPool resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_target_pool(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'inspec-gcp-target-pool') do it { should exist } its('session_affinity') { should eq 'CLIENT_IP' } it { should has_target_instance('gcp_ext_vm_name', 'zone') } end describe google_compute_target_pool(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_target_pool` resource: `backup_pool` This field is applicable only when the containing target pool is serving a forwarding rule as the primary pool, and its failoverRatio field is properly set to a value between [0, 1]. backupPool and failoverRatio together define the fallback behavior of the primary target pool: if the ratio of the healthy instances in the primary pool is at or below failoverRatio, traffic arriving at the load-balanced IP will be directed to the backup pool. In case where failoverRatio and backupPool are not set, or all the instances in the backup pool are unhealthy, the traffic will be directed back to the primary pool in the “force” mode, where traffic will be spread to the healthy instances with the best effort, or to all instances when no instance is healthy. `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. `failover_ratio` This field is applicable only when the containing target pool is serving a forwarding rule as the primary pool (i.e., not as a backup pool to some other target pool). The value of the field must be in [0, 1]. If set, backupPool must also be set. They together define the fallback behavior of the primary target pool: if the ratio of the healthy instances in the primary pool is at or below this number, traffic arriving at the load-balanced IP will be directed to the backup pool. In case where failoverRatio is not set or all the instances in the backup pool are unhealthy, the traffic will be directed back to the primary pool in the “force” mode, where traffic will be spread to the healthy instances with the best effort, or to all instances when no instance is healthy. `health_check` A reference to a HttpHealthCheck resource. A member instance in this pool is considered healthy if and only if the health checks pass. If not specified it means all member instances will be considered healthy at all times. `id` The unique identifier for the resource. `instances` A list of virtual machine instances serving this pool. They must live in zones contained in the same region as this pool. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `session_affinity` Session affinity option. Must be one of these values: - NONE: Connections from the same client IP may go to any instance in the pool. - CLIENT_IP: Connections from the same client IP will go to the same instance in the pool while that instance remains healthy. - CLIENT_IP_PROTO: Connections from the same client IP with the same IP protocol will go to the same instance in the pool while that instance remains healthy. Possible values: * NONE * CLIENT_IP * CLIENT_IP_PROTO `region` The region where the target pool resides. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_target_pool/google_compute_target_tcp_proxies resource ============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_target_tcp_proxies.md) Syntax ------ A `google_compute_target_tcp_proxies` is used to test a Google TargetTcpProxy resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_target_tcp_proxies(project: 'chef-gcp-inspec') do its('names') { should include 'inspec-gcp-target-tcp-proxy' } its('proxy_headers') { should include 'NONE' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_target_tcp_proxies` resource: See the [google_compute_target_tcp_proxy](../google_compute_target_tcp_proxy/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_target_tcp_proxy` creation_timestamp `descriptions` an array of `google_compute_target_tcp_proxy` description `ids` an array of `google_compute_target_tcp_proxy` id `names` an array of `google_compute_target_tcp_proxy` name `proxy_headers` an array of `google_compute_target_tcp_proxy` proxy_header `services` an array of `google_compute_target_tcp_proxy` service Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_target_tcp_proxies/google_compute_vpn_tunnel resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_vpn_tunnel.md) Syntax ------ A `google_compute_vpn_tunnel` is used to test a Google VpnTunnel resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_vpn_tunnel(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'inspec-vpn-tunnel') do it { should exist } its('peer_ip') { should eq '15.0.0.120' } end describe google_compute_vpn_tunnel(project: 'chef-gcp-inspec', region: 'europe-west2', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP compute vpn_tunnel exists ``` describe google_compute_vpn_tunnel(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-vpn-tunnel') do it { should exist } end ``` ### Test when a GCP compute vpn_tunnel was created ``` describe google_compute_vpn_tunnel(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-vpn-tunnel') do its('creation_timestamp_date') { should be > Time.now - 365*60*60*24*10 } end ``` ### Test for an expected vpn_tunnel identifier ``` describe google_compute_vpn_tunnel(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-vpn-tunnel') do its('id') { should eq 12345567789 } end ``` ### Test that a vpn_tunnel peer address is as expected ``` describe google_compute_vpn_tunnel(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-vpn-tunnel') do its('peer_ip') { should eq "123.123.123.123" } end ``` ### Test that a vpn_tunnel status is as expected ``` describe google_compute_vpn_tunnel(project: 'chef-inspec-gcp', region: 'europe-west2', name: 'gcp-inspec-vpn_tunnel') do its('status') { should eq "ESTABLISHED" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_vpn_tunnel` resource: `id` The unique identifier for the resource. This identifier is defined by the server. `creation_timestamp` Creation timestamp in RFC3339 text format. `name` Name of the resource. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `description` An optional description of this resource. `target_vpn_gateway` URL of the Target VPN gateway with which this VPN tunnel is associated. `vpn_gateway` (Beta only) URL of the VPN gateway with which this VPN tunnel is associated. This must be used if a High Availability VPN gateway resource is created. `vpn_gateway_interface` (Beta only) The interface ID of the VPN gateway with which this VPN tunnel is associated. `peer_external_gateway` (Beta only) URL of the peer side external VPN gateway to which this VPN tunnel is connected. `peer_external_gateway_interface` (Beta only) The interface ID of the external VPN gateway to which this VPN tunnel is connected. `peer_gcp_gateway` (Beta only) URL of the peer side HA GCP VPN gateway to which this VPN tunnel is connected. If provided, the VPN tunnel will automatically use the same vpn_gateway_interface ID in the peer GCP VPN gateway. `router` URL of router resource to be used for dynamic routing. `peer_ip` IP address of the peer VPN gateway. Only IPv4 is supported. `shared_secret` Shared secret used to set the secure session between the Cloud VPN gateway and the peer VPN gateway. `shared_secret_hash` Hash of the shared secret. `ike_version` IKE protocol version to use when establishing the VPN tunnel with peer VPN gateway. Acceptable IKE versions are 1 or 2. Default version is 2. `local_traffic_selector` Local traffic selector to use when establishing the VPN tunnel with peer VPN gateway. The value should be a CIDR formatted string, for example `192.168.0.0/16`. The ranges should be disjoint. Only IPv4 is supported. `remote_traffic_selector` Remote traffic selector to use when establishing the VPN tunnel with peer VPN gateway. The value should be a CIDR formatted string, for example `192.168.0.0/16`. The ranges should be disjoint. Only IPv4 is supported. `labels` (Beta only) Labels to apply to this VpnTunnel. `label_fingerprint` (Beta only) The fingerprint used for optimistic locking of this resource. Used internally during updates. `region` The region where the tunnel is located. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_vpn_tunnel/google_compute_target_tcp_proxy resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_target_tcp_proxy.md) Syntax ------ A `google_compute_target_tcp_proxy` is used to test a Google TargetTcpProxy resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_target_tcp_proxy(project: 'chef-gcp-inspec', name: 'inspec-gcp-target-tcp-proxy') do it { should exist } its('proxy_header') { should eq 'NONE' } its('service') { should match /\/gcp-inspec-tcp-backend-service$/ } end describe google_compute_target_tcp_proxy(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_target_tcp_proxy` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `description` An optional description of this resource. `id` The unique identifier for the resource. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `proxy_header` Specifies the type of proxy header to append before sending data to the backend. Possible values: * NONE * PROXY_V1 `service` A reference to the BackendService resource. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_target_tcp_proxy/google_compute_url_map resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_url_map.md) Syntax ------ A `google_compute_url_map` is used to test a Google UrlMap resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_url_map(project: 'chef-gcp-inspec', name: 'inspec-gcp-url-map') do it { should exist } its('description') { should eq 'URL map description' } its('default_service') { should match /\/inspec-gcp-backend-service$/ } its('host_rules.count') { should eq 1 } its('host_rules.first.hosts') { should include 'site.com' } its('path_matchers.count') { should eq 1 } its('path_matchers.first.default_service') { should match /\/inspec-gcp-backend-service$/ } its('tests.count') { should eq 1 } its('tests.first.host') { should eq 'test.com' } its('tests.first.path') { should eq '/home' } end describe google_compute_url_map(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_compute_url_map` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `default_service` The full or partial URL of the defaultService resource to which traffic is directed if none of the hostRules match. If defaultRouteAction is additionally specified, advanced routing actions like URL Rewrites, etc. take effect prior to sending the request to the backend. However, if defaultService is specified, defaultRouteAction cannot contain any weightedBackendServices. Conversely, if routeAction specifies any weightedBackendServices, service must not be specified. Only one of defaultService, defaultUrlRedirect or defaultRouteAction.weightedBackendService must be set. `description` An optional description of this resource. Provide this property when you create the resource. `id` The unique identifier for the resource. `fingerprint` Fingerprint of this resource. A hash of the contents stored in this object. This field is used in optimistic locking. `header_action` Specifies changes to request and response headers that need to take effect for the selected backendService. The headerAction specified here take effect after headerAction specified under pathMatcher. `request_headers_to_add` Headers to add to a matching request prior to forwarding the request to the backendService. `header_name` : The name of the header. `header_value` : The value of the header to add. `replace` : If false, headerValue is appended to any values that already exist for the header. If true, headerValue is set for the header, discarding any values that were set for that header. `request_headers_to_remove` A list of header names for headers that need to be removed from the request prior to forwarding the request to the backendService. `response_headers_to_add` Headers to add the response prior to sending the response back to the client. `header_name` : The name of the header. `header_value` : The value of the header to add. `replace` : If false, headerValue is appended to any values that already exist for the header. If true, headerValue is set for the header, discarding any values that were set for that header. `response_headers_to_remove` A list of header names for headers that need to be removed from the response prior to sending the response back to the client. `host_rules` The list of HostRules to use against the URL. `description` An optional description of this resource. Provide this property when you create the resource. `hosts` The list of host patterns to match. They must be valid hostnames, except _ will match any string of ([a-z0-9-.]_). In that case, * must be the first character and must be followed in the pattern by either - or .. `path_matcher` The name of the PathMatcher to use to match the path portion of the URL if the hostRule matches the URL’s host portion. `name` Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. `path_matchers` The list of named PathMatchers to use against the URL. `default_service` The full or partial URL to the BackendService resource. This will be used if none of the pathRules or routeRules defined by this PathMatcher are matched. For example, the following are all valid URLs to a BackendService resource: - <https://www.googleapis.com/compute/v1/projects/project/global/backendServices/backendService> - compute/v1/projects/project/global/backendServices/backendService - global/backendServices/backendService If defaultRouteAction is additionally specified, advanced routing actions like URL Rewrites, etc. take effect prior to sending the request to the backend. However, if defaultService is specified, defaultRouteAction cannot contain any weightedBackendServices. Conversely, if defaultRouteAction specifies any weightedBackendServices, defaultService must not be specified. Only one of defaultService, defaultUrlRedirect or defaultRouteAction.weightedBackendService must be set. Authorization requires one or more of the following Google IAM permissions on the specified resource defaultService: - compute.backendBuckets.use - compute.backendServices.use `description` An optional description of this resource. Provide this property when you create the resource. `header_action` Specifies changes to request and response headers that need to take effect for the selected backendService. HeaderAction specified here are applied after the matching HttpRouteRule HeaderAction and before the HeaderAction in the UrlMap `request_headers_to_add` : Headers to add to a matching request prior to forwarding the request to the backendService. ``` `header_name` : The name of the header. `header_value` : The value of the header to add. `replace` : If false, headerValue is appended to any values that already exist for the header. If true, headerValue is set for the header, discarding any values that were set for that header. ``` `request_headers_to_remove` : A list of header names for headers that need to be removed from the request prior to forwarding the request to the backendService. `response_headers_to_add` : Headers to add the response prior to sending the response back to the client. ``` `header_name` : The name of the header. `header_value` : The value of the header to add. `replace` : If false, headerValue is appended to any values that already exist for the header. If true, headerValue is set for the header, discarding any values that were set for that header. ``` `response_headers_to_remove` : A list of header names for headers that need to be removed from the response prior to sending the response back to the client. `name` The name to which this PathMatcher is referred by the HostRule. `default_url_redirect` When none of the specified hostRules match, the request is redirected to a URL specified by defaultUrlRedirect. If defaultUrlRedirect is specified, defaultService or defaultRouteAction must not be set. `host_redirect` : The host that will be used in the redirect response instead of the one that was supplied in the request. The value must be between 1 and 255 characters. `https_redirect` : If set to true, the URL scheme in the redirected request is set to https. If set to false, the URL scheme of the redirected request will remain the same as that of the request. This must only be set for UrlMaps used in TargetHttpProxys. Setting this true for TargetHttpsProxy is not permitted. The default is set to false. `path_redirect` : The path that will be used in the redirect response instead of the one that was supplied in the request. pathRedirect cannot be supplied together with prefixRedirect. Supply one alone or neither. If neither is supplied, the path of the original request will be used for the redirect. The value must be between 1 and 1024 characters. `prefix_redirect` : The prefix that replaces the prefixMatch specified in the HttpRouteRuleMatch, retaining the remaining portion of the URL before redirecting the request. prefixRedirect cannot be supplied together with pathRedirect. Supply one alone or neither. If neither is supplied, the path of the original request will be used for the redirect. The value must be between 1 and 1024 characters. `redirect_response_code` : The HTTP Status code to use for this RedirectAction. Supported values are: ``` Supported values are: - MOVED_PERMANENTLY_DEFAULT, which is the default value and corresponds to 301. - FOUND, which corresponds to 302. - SEE_OTHER which corresponds to 303. - TEMPORARY_REDIRECT, which corresponds to 307. In this case, the request method will be retained. - PERMANENT_REDIRECT, which corresponds to 308. In this case, the request method will be retained. ``` `strip_query` : If set to true, any accompanying query portion of the original URL is removed prior to redirecting the request. If set to false, the query portion of the original URL is retained. `tests` The list of expected URL mapping tests. Request to update this UrlMap will succeed only if all of the test cases pass. You can specify a maximum of 100 tests per UrlMap. `description` : Description of this test case. `host` : Host portion of the URL. `path` : Path portion of the URL. `service` : Expected BackendService resource the given URL should be mapped to. `default_url_redirect` When none of the specified hostRules match, the request is redirected to a URL specified by defaultUrlRedirect. If defaultUrlRedirect is specified, defaultService or defaultRouteAction must not be set. `host_redirect` The host that will be used in the redirect response instead of the one that was supplied in the request. The value must be between 1 and 255 characters. `https_redirect` If set to true, the URL scheme in the redirected request is set to https. If set to false, the URL scheme of the redirected request will remain the same as that of the request. This must only be set for UrlMaps used in TargetHttpProxys. Setting this true for TargetHttpsProxy is not permitted. The default is set to false. `path_redirect` The path that will be used in the redirect response instead of the one that was supplied in the request. pathRedirect cannot be supplied together with prefixRedirect. Supply one alone or neither. If neither is supplied, the path of the original request will be used for the redirect. The value must be between 1 and 1024 characters. `prefix_redirect` The prefix that replaces the prefixMatch specified in the HttpRouteRuleMatch, retaining the remaining portion of the URL before redirecting the request. prefixRedirect cannot be supplied together with pathRedirect. Supply one alone or neither. If neither is supplied, the path of the original request will be used for the redirect. The value must be between 1 and 1024 characters. `redirect_response_code` The HTTP Status code to use for this RedirectAction. Supported values are: * MOVED_PERMANENTLY_DEFAULT, which is the default value and corresponds to 301. * FOUND, which corresponds to 302. * SEE_OTHER which corresponds to 303. * TEMPORARY_REDIRECT, which corresponds to 307. In this case, the request method will be retained. * PERMANENT_REDIRECT, which corresponds to 308. In this case, the request method will be retained. `strip_query` If set to true, any accompanying query portion of the original URL is removed prior to redirecting the request. If set to false, the query portion of the original URL is retained. The default is set to false. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_url_map/google_compute_url_maps resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_url_maps.md) Syntax ------ A `google_compute_url_maps` is used to test a Google UrlMap resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_url_maps(project: 'chef-gcp-inspec') do its('names') { should include 'inspec-gcp-url-map' } end ``` Properties ---------- Properties that can be accessed from the `google_compute_url_maps` resource: See the [google_compute_url_map](../google_compute_url_map/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_url_map` creation_timestamp `default_services` an array of `google_compute_url_map` default_service `descriptions` an array of `google_compute_url_map` description `ids` an array of `google_compute_url_map` id `fingerprints` an array of `google_compute_url_map` fingerprint `header_actions` an array of `google_compute_url_map` header_action `host_rules` an array of `google_compute_url_map` host_rules `names` an array of `google_compute_url_map` name `path_matchers` an array of `google_compute_url_map` path_matchers `tests` an array of `google_compute_url_map` tests `default_url_redirects` an array of `google_compute_url_map` default_url_redirect Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_url_maps/google_compute_vpn_tunnels resource ====================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_vpn_tunnels.md) Syntax ------ A `google_compute_vpn_tunnels` is used to test a Google VpnTunnel resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_vpn_tunnels(project: 'chef-gcp-inspec', region: 'europe-west2') do its('vpn_tunnel_names') { should include 'inspec-vpn-tunnel' } its('peer_ips') { should include '15.0.0.120' } end ``` ### Test that there are no more than a specified number of vpn_tunnels available for the project and region ``` describe google_compute_vpn_tunnels(project: 'chef-inspec-gcp', region: 'europe-west2') do its('count') { should be <= 100} end ``` ### Test that an expected vpn_tunnel name is available for the project and region ``` describe google_compute_vpn_tunnels(project: 'chef-inspec-gcp', region: 'europe-west2') do its('vpn_tunnel_names') { should include "vpn_tunnel-name" } end ``` ### Test that an expected vpn_tunnel target_vpn_gateways name is not present for the project and region ``` describe google_compute_vpn_tunnels(project: 'chef-inspec-gcp', region: 'europe-west2') do its('vpn_tunnel_target_vpn_gateways') { should not include "gateway-name" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_vpn_tunnels` resource: See the [google_compute_vpn_tunnel](../google_compute_vpn_tunnel/index#properties) resource for more information. `ids` an array of `google_compute_vpn_tunnel` id `creation_timestamps` an array of `google_compute_vpn_tunnel` creation_timestamp `vpn_tunnel_names` an array of `google_compute_vpn_tunnel` name `descriptions` an array of `google_compute_vpn_tunnel` description `target_vpn_gateways` an array of `google_compute_vpn_tunnel` target_vpn_gateway `vpn_gateways` (Beta only) an array of `google_compute_vpn_tunnel` vpn_gateway `vpn_gateway_interfaces` (Beta only) an array of `google_compute_vpn_tunnel` vpn_gateway_interface `peer_external_gateways` (Beta only) an array of `google_compute_vpn_tunnel` peer_external_gateway `peer_external_gateway_interfaces` (Beta only) an array of `google_compute_vpn_tunnel` peer_external_gateway_interface `peer_gcp_gateways` (Beta only) an array of `google_compute_vpn_tunnel` peer_gcp_gateway `routers` an array of `google_compute_vpn_tunnel` router `peer_ips` an array of `google_compute_vpn_tunnel` peer_ip `shared_secrets` an array of `google_compute_vpn_tunnel` shared_secret `shared_secret_hashes` an array of `google_compute_vpn_tunnel` shared_secret_hash `ike_versions` an array of `google_compute_vpn_tunnel` ike_version `local_traffic_selectors` an array of `google_compute_vpn_tunnel` local_traffic_selector `remote_traffic_selectors` an array of `google_compute_vpn_tunnel` remote_traffic_selector `labels` (Beta only) an array of `google_compute_vpn_tunnel` labels `label_fingerprints` (Beta only) an array of `google_compute_vpn_tunnel` label_fingerprint `regions` an array of `google_compute_vpn_tunnel` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_vpn_tunnels/google_compute_zones resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_zones.md) Syntax ------ A `google_compute_zones` is used to test a Google Zone resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` google_compute_zones(project: 'chef-gcp-inspec').zone_names.each do |zone_name| describe google_compute_zone(project: 'chef-gcp-inspec', name: zone_name) do it { should exist } it { should be_up } end end ``` ### Test that there are no more than a specified number of zones available for the project ``` describe google_compute_zones(project: 'chef-inspec-gcp') do its('count') { should be <= 100} end ``` ### Test the exact number of zones in the project ``` describe google_compute_zones(project: 'chef-inspec-gcp') do its('zone_ids.count') { should cmp 9 } end ``` ### Test that an expected zone is available for the project ``` describe google_compute_zones(project: 'chef-inspec-gcp') do its('zone_names') { should include "us-east1-b" } end ``` ### Test whether any zones are in status “DOWN” ``` describe google_compute_zones(project: 'chef-inspec-gcp') do its('zone_statuses') { should_not include "DOWN" } end ``` ### Test that a subset of all zones matching “us*” are “UP” ``` google_compute_zones(project: 'chef-inspec-gcp').where(zone_name: /^us/).zone_names.each do |zone_name| describe google_compute_zone(project: 'chef-inspec-gcp', zone: zone_name) do it { should exist } its('status') { should eq 'UP' } end end ``` Properties ---------- Properties that can be accessed from the `google_compute_zones` resource: See the [google_compute_zone](../google_compute_zone/index#properties) resource for more information. `creation_timestamps` an array of `google_compute_zone` creation_timestamp `deprecateds` an array of `google_compute_zone` deprecated `descriptions` an array of `google_compute_zone` description `zone_ids` an array of `google_compute_zone` id `zone_names` an array of `google_compute_zone` name `regions` an array of `google_compute_zone` region `zone_statuses` an array of `google_compute_zone` status `available_cpu_platforms` an array of `google_compute_zone` available_cpu_platforms Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_zones/google_container_cluster resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_container_cluster.md) Syntax ------ A `google_container_cluster` is used to test a Google Cluster resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_container_cluster(project: 'chef-gcp-inspec', location: 'europe-west2-a', name: 'gcp-inspec-kube-cluster') do it { should exist } its('locations.sort'){ should cmp [ 'europe-west2-a', 'europe-west2-b', 'europe-west2-c' ].sort } its('master_auth.username') { should eq 'gcp-inspec-kube-admin' } end describe google_container_cluster(project: 'chef-gcp-inspec', location: 'europe-west2-a', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP container cluster is in a particular state e.g. “RUNNING” ``` describe google_container_cluster(project: 'chef-inspec-gcp', location: 'europe-west2-a', name: 'inspec-gcp-kube-cluster') do its('status') { should eq 'RUNNING' } end ``` ### Test that a GCP container cluster has the expected kube master user/password ``` describe google_container_cluster(project: 'chef-inspec-gcp', location: 'europe-west2-a', name: 'inspec-gcp-kube-cluster') do its('master_auth.username'){ should eq "user_name"} its('master_auth.password'){ should eq "choose_something_strong"} end ``` ### Test that the locations where the GCP container cluster is running match those expected ``` describe google_container_cluster(project: 'chef-inspec-gcp', location: 'europe-west2-a', name: 'inspec-gcp-kube-cluster') do its('locations.sort'){should cmp ["europe-west2-a", "europe-west2-b", "europe-west2-c"].sort} end ``` ### Test GCP container cluster network and subnetwork settings ``` describe google_container_cluster(project: 'chef-inspec-gcp', location: 'europe-west2-a', name: 'inspec-gcp-kube-cluster') do its('network'){should eq "default"} its('subnetwork'){should eq "default"} end ``` ### Test GCP container cluster node pool configuration settings ``` describe google_container_cluster(project: 'chef-inspec-gcp', location: 'europe-west2-a', name: 'inspec-gcp-kube-cluster') do its('node_config.disk_size_gb'){should eq 100} its('node_config.image_type'){should eq "COS"} its('node_config.machine_type'){should eq "n1-standard-1"} its('node_ipv4_cidr_size'){should eq 24} its('node_pools.count'){should eq 1} end ``` Properties ---------- Properties that can be accessed from the `google_container_cluster` resource: `name` The name of this cluster. The name must be unique within this project and location, and can be up to 40 characters. Must be Lowercase letters, numbers, and hyphens only. Must start with a letter. Must end with a number or a letter. `description` An optional description of this cluster. `initial_node_count` The number of nodes to create in this cluster. You must ensure that your Compute Engine resource quota is sufficient for this number of instances. You must also have available firewall and routes quota. For requests, this field should only be used in lieu of a “nodePool” object, since this configuration (along with the “nodeConfig”) will be used to create a “NodePool” object with an auto-generated name. Do not use this and a nodePool at the same time. This field has been deprecated. Please use nodePool.initial_node_count instead. `node_config` Parameters used in creating the cluster’s nodes. For requests, this field should only be used in lieu of a “nodePool” object, since this configuration (along with the “initialNodeCount”) will be used to create a “NodePool” object with an auto-generated name. Do not use this and a nodePool at the same time. For responses, this field will be populated with the node configuration of the first node pool. If unspecified, the defaults are used. `machine_type` The name of a Google Compute Engine machine type (e.g. n1-standard-1). If unspecified, the default machine type is n1-standard-1. `disk_size_gb` Size of the disk attached to each node, specified in GB. The smallest allowed disk size is 10GB. If unspecified, the default disk size is 100GB. `oauth_scopes` The set of Google API scopes to be made available on all of the node VMs under the “default” service account. The following scopes are recommended, but not required, and by default are not included: <https://www.googleapis.com/auth/compute> is required for mounting persistent storage on your nodes. <https://www.googleapis.com/auth/devstorage.read_only> is required for communicating with gcr.io (the Google Container Registry). If unspecified, no scopes are added, unless Cloud Logging or Cloud Monitoring are enabled, in which case their required scopes will be added. `service_account` The Google Cloud Platform Service Account to be used by the node VMs. If no Service Account is specified, the “default” service account is used. `metadata` The metadata key/value pairs assigned to instances in the cluster. Keys must conform to the regexp [a-zA-Z0-9-_]+ and be less than 128 bytes in length. These are reflected as part of a URL in the metadata server. Additionally, to avoid ambiguity, keys must not conflict with any other metadata keys for the project or be one of the four reserved keys: “instance-template”, “kube-env”, “startup-script”, and “user-data” Values are free-form strings, and only have meaning as interpreted by the image running in the instance. The only restriction placed on them is that each value’s size must be less than or equal to 32 KB. The total size of all keys and values must be less than 512 KB. An object containing a list of “key”: value pairs. Example: { “name”: “wrench”, “mass”: “1.3kg”, “count”: “3” }. `image_type` The image type to use for this node. Note that for a given image type, the latest version of it will be used. `labels` The map of Kubernetes labels (key/value pairs) to be applied to each node. These will added in addition to any default label(s) that Kubernetes may apply to the node. In case of conflict in label keys, the applied set may differ depending on the Kubernetes version – it’s best to assume the behavior is undefined and conflicts should be avoided. For more information, including usage and the valid values, see: <http://kubernetes.io/v1.1/docs/user-guide/labels.html> An object containing a list of “key”: value pairs. Example: { “name”: “wrench”, “mass”: “1.3kg”, “count”: “3” }. `local_ssd_count` The number of local SSD disks to be attached to the node. The limit for this value is dependant upon the maximum number of disks available on a machine per zone. See: <https://cloud.google.com/compute/docs/disks/local-ssd#local_ssd_limits> for more information. `tags` The list of instance tags applied to all nodes. Tags are used to identify valid sources or targets for network firewalls and are specified by the client during cluster or node pool creation. Each tag within the list must comply with RFC1035. `preemptible` Whether the nodes are created as preemptible VM instances. See: <https://cloud.google.com/compute/docs/instances/preemptible> for more information about preemptible VM instances. `accelerators` A list of hardware accelerators to be attached to each node. See <https://cloud.google.com/compute/docs/gpus> for more information about support for GPUs. `accelerator_count` The number of accelerator cards exposed to an instance. `accelerator_type` The accelerator type resource name `disk_type` Type of the disk attached to each node (e.g. ‘pd-standard’ or ‘pd-ssd’) If unspecified, the default disk type is ‘pd-standard’ `min_cpu_platform` Minimum CPU platform to be used by this instance. The instance may be scheduled on the specified or newer CPU platform. `taints` List of kubernetes taints to be applied to each node. For more information, including usage and the valid values, see: <https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/> `key` Key for taint `value` Value for taint `effect` Effect for taint Possible values: * EFFECT_UNSPECIFIED * NO_SCHEDULE * PREFER_NO_SCHEDULE * NO_EXECUTE `master_auth` The authentication information for accessing the master endpoint. `username` The username to use for HTTP basic authentication to the master endpoint. `password` The password to use for HTTP basic authentication to the master endpoint. Because the master endpoint is open to the Internet, you should create a strong password with a minimum of 16 characters. `client_certificate_config` Configuration for client certificate authentication on the cluster. For clusters before v1.12, if no configuration is specified, a client certificate is issued. `issue_client_certificate` Issue a client certificate. `cluster_ca_certificate` Base64-encoded public certificate that is the root of trust for the cluster. `client_certificate` Base64-encoded public certificate used by clients to authenticate to the cluster endpoint. `client_key` Base64-encoded private key used by clients to authenticate to the cluster endpoint. `logging_service` The logging service the cluster should use to write logs. Currently available options: logging.googleapis.com - the Google Cloud Logging service. none - no logs will be exported from the cluster. if left as an empty string,logging.googleapis.com will be used. Possible values: * logging.googleapis.com * none `monitoring_service` The monitoring service the cluster should use to write metrics. Currently available options: monitoring.googleapis.com - the Google Cloud Monitoring service. none - no metrics will be exported from the cluster. if left as an empty string, monitoring.googleapis.com will be used. Possible values: * monitoring.googleapis.com * none `network` The name of the Google Compute Engine network to which the cluster is connected. If left unspecified, the default network will be used. `private_cluster_config` Configuration for a private cluster. `enable_private_nodes` Whether nodes have internal IP addresses only. If enabled, all nodes are given only RFC 1918 private addresses and communicate with the master via private networking. `enable_private_endpoint` Whether the master’s internal IP address is used as the cluster endpoint. `master_ipv4_cidr_block` The IP range in CIDR notation to use for the hosted master network. This range will be used for assigning internal IP addresses to the master or set of masters, as well as the ILB VIP. This range must not overlap with any other ranges in use within the cluster’s network. `private_endpoint` The internal IP address of this cluster’s master endpoint. `public_endpoint` The external IP address of this cluster’s master endpoint. `cluster_ipv4_cidr` The IP address range of the container pods in this cluster, in CIDR notation (e.g. 10.96.0.0/14). Leave blank to have one automatically chosen or specify a /14 block in 10.0.0.0/8. `enable_tpu` (Optional) Whether to enable Cloud TPU resources in this cluster. See the official documentation - <https://cloud.google.com/tpu/docs/kubernetes-engine-setup> `tpu_ipv4_cidr_block` The IP address range of the Cloud TPUs in this cluster, in [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation (e.g. `1.2.3.4/29`). `addons_config` Configurations for the various addons available to run in the cluster. `http_load_balancing` Configuration for the HTTP (L7) load balancing controller addon, which makes it easy to set up HTTP load balancers for services in a cluster. `disabled` Whether the HTTP Load Balancing controller is enabled in the cluster. When enabled, it runs a small pod in the cluster that manages the load balancers. `horizontal_pod_autoscaling` Configuration for the horizontal pod autoscaling feature, which increases or decreases the number of replica pods a replication controller has based on the resource usage of the existing pods. `disabled` Whether the Horizontal Pod Autoscaling feature is enabled in the cluster. When enabled, it ensures that a Heapster pod is running in the cluster, which is also used by the Cloud Monitoring service. `kubernetes_dashboard` Configuration for the Kubernetes Dashboard. This addon is deprecated, and will be disabled in 1.15. It is recommended to use the Cloud Console to manage and monitor your Kubernetes clusters, workloads and applications. `disabled` Whether the Kubernetes Dashboard is enabled for this cluster. `network_policy_config` Configuration for NetworkPolicy. This only tracks whether the addon is enabled or not on the Master, it does not track whether network policy is enabled for the nodes. `disabled` Whether NetworkPolicy is enabled for this cluster. `subnetwork` The name of the Google Compute Engine subnetwork to which the cluster is connected. `locations` The list of Google Compute Engine zones in which the cluster’s nodes should be located. `resource_labels` The resource labels for the cluster to use to annotate any related Google Compute Engine resources. `label_fingerprint` The fingerprint of the set of labels for this cluster. `legacy_abac` Configuration for the legacy ABAC authorization mode. `enabled` Whether the ABAC authorizer is enabled for this cluster. When enabled, identities in the system, including service accounts, nodes, and controllers, will have statically granted permissions beyond those provided by the RBAC configuration or IAM. `network_policy` Configuration options for the NetworkPolicy feature. `provider` The selected network policy provider. Possible values: * PROVIDER_UNSPECIFIED * CALICO `enabled` Whether network policy is enabled on the cluster. `default_max_pods_constraint` The default constraint on the maximum number of pods that can be run simultaneously on a node in the node pool of this cluster. Only honored if cluster created with IP Alias support. `max_pods_per_node` Constraint enforced on the max num of pods per node. `ip_allocation_policy` Configuration for controlling how IPs are allocated in the cluster `use_ip_aliases` Whether alias IPs will be used for pod IPs in the cluster `create_subnetwork` Whether a new subnetwork will be created automatically for the cluster `subnetwork_name` A custom subnetwork name to be used if createSubnetwork is true. If this field is empty, then an automatic name will be chosen for the new subnetwork. `cluster_secondary_range_name` The name of the secondary range to be used for the cluster CIDR block. The secondary range will be used for pod IP addresses. This must be an existing secondary range associated with the cluster subnetwork `services_secondary_range_name` The name of the secondary range to be used as for the services CIDR block. The secondary range will be used for service ClusterIPs. This must be an existing secondary range associated with the cluster subnetwork. `cluster_ipv4_cidr_block` The IP address range for the cluster pod IPs. If this field is set, then cluster.cluster_ipv4_cidr must be left blank. This field is only applicable when useIpAliases is true. Set to blank to have a range chosen with the default size. Set to /netmask (e.g. /14) to have a range chosen with a specific netmask. `node_ipv4_cidr_block` The IP address range of the instance IPs in this cluster. This is applicable only if createSubnetwork is true. Set to blank to have a range chosen with the default size. Set to /netmask (e.g. /14) to have a range chosen with a specific netmask. `services_ipv4_cidr_block` The IP address range of the services IPs in this cluster. If blank, a range will be automatically chosen with the default size. This field is only applicable when useIpAliases is true. Set to blank to have a range chosen with the default size. Set to /netmask (e.g. /14) to have a range chosen with a specific netmask. `tpu_ipv4_cidr_block` The IP address range of the Cloud TPUs in this cluster. If unspecified, a range will be automatically chosen with the default size. This field is only applicable when useIpAliases is true. If unspecified, the range will use the default size. Set to /netmask (e.g. /14) to have a range chosen with a specific netmask. `endpoint` The IP address of this cluster’s master endpoint. The endpoint can be accessed from the internet at https://username:password@endpoint/ See the masterAuth property of this resource for username and password information. `initial_cluster_version` The software version of the master endpoint and kubelets used in the cluster when it was first created. The version can be upgraded over time. `current_master_version` The current software version of the master endpoint. `current_node_version` The current version of the node software components. If they are currently at multiple versions because they’re in the process of being upgraded, this reflects the minimum version of all nodes. `create_time` The time the cluster was created, in RFC3339 text format. `status` The current status of this cluster. Possible values: * STATUS_UNSPECIFIED * PROVISIONING * RUNNING * RECONCILING * STOPPING * ERROR * DEGRADED `status_message` Additional information about the current status of this cluster, if available. `node_ipv4_cidr_size` The size of the address space on each node for hosting containers. This is provisioned from within the container_ipv4_cidr range. `services_ipv4_cidr` The IP address range of the Kubernetes services in this cluster, in CIDR notation (e.g. 1.2.3.4/29). Service addresses are typically put in the last /16 from the container CIDR. `current_node_count` The number of nodes currently in the cluster. `expire_time` The time the cluster will be automatically deleted in RFC3339 text format. `conditions` Which conditions caused the current cluster state. `code` Machine-friendly representation of the condition `message` Human-friendly representation of the condition `master_authorized_networks_config` Configuration for controlling how IPs are allocated in the cluster `enabled` Whether or not master authorized networks is enabled. `cidr_blocks` Define up to 50 external networks that could access Kubernetes master through HTTPS. `display_name` Optional field used to identify cidr blocks `cidr_block` Block specified in CIDR notation `node_pools` Node pools belonging to this cluster `name` Name of the node pool `pod_security_policy_config` (Beta only) Configuration for the PodSecurityPolicy feature. `enabled` If enabled, pods must be valid under a PodSecurityPolicy to be created. `binary_authorization` Configuration for the BinaryAuthorization feature. `enabled` If enabled, all container images will be validated by Binary Authorization. `location` The location where the cluster is deployed GCP Permissions --------------- Ensure the [Kubernetes Engine API](https://console.cloud.google.com/apis/library/container.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_container_cluster/google_compute_zone resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_compute_zone.md) Syntax ------ A `google_compute_zone` is used to test a Google Zone resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_compute_zone(project: 'chef-gcp-inspec', name: "us-central1-a") do it { should exist } it { should be_up } end ``` ### Test that a GCP compute zone exists ``` describe google_compute_zone(project: 'chef-inspec-gcp', zone: 'us-east1-b') do it { should exist } end ``` ### Test that a GCP compute zone is in the expected state ``` describe google_compute_zone(project: 'chef-inspec-gcp', zone: 'us-east1-b') do its('status') { should eq 'UP' } # or equivalently it { should be_up } end ``` ### Test that a GCP compute zone has an expected CPU platform ``` describe google_compute_zone(project: 'chef-inspec-gcp', zone: 'us-east1-b') do its('available_cpu_platforms') { should include "Intel Skylake" } end ``` Properties ---------- Properties that can be accessed from the `google_compute_zone` resource: `creation_timestamp` Creation timestamp in RFC3339 text format. `deprecated` The deprecation status associated with this machine type. `deleted` An optional RFC3339 timestamp on or after which the state of this resource is intended to change to DELETED. This is only informational and the status will not change unless the client explicitly changes it. `deprecated` An optional RFC3339 timestamp on or after which the state of this resource is intended to change to DEPRECATED. This is only informational and the status will not change unless the client explicitly changes it. `obsolete` An optional RFC3339 timestamp on or after which the state of this resource is intended to change to OBSOLETE. This is only informational and the status will not change unless the client explicitly changes it. `replacement` The URL of the suggested replacement for a deprecated resource. The suggested replacement resource must be the same kind of resource as the deprecated resource. `state` The deprecation state of this resource. This can be DEPRECATED, OBSOLETE, or DELETED. Operations which create a new resource using a DEPRECATED resource will return successfully, but with a warning indicating the deprecated resource and recommending its replacement. Operations which use OBSOLETE or DELETED resources will be rejected and result in an error. Possible values: * DEPRECATED * OBSOLETE * DELETED `description` An optional textual description of the resource. `id` The unique identifier for the resource. `name` Name of the resource. `region` The region where the zone is located. `status` The status of the zone. Possible values: * UP * DOWN `available_cpu_platforms` The available CPU platforms in this zone GCP Permissions --------------- Ensure the [Compute Engine API](https://console.cloud.google.com/apis/library/compute.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_compute_zone/google_container_clusters resource ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_container_clusters.md) Syntax ------ A `google_container_clusters` is used to test a Google Cluster resource. Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource. Examples -------- ``` describe google_container_clusters(project: 'chef-gcp-inspec', location: 'europe-west2-a') do its('cluster_names') { should include 'gcp-inspec-kube-cluster' } end ``` ### Test that there are no more than a specified number of clusters available for the project in a particular zone ``` describe google_container_clusters(project: 'chef-inspec-gcp', location: 'europe-west2-a') do its('count') { should be <= 5} end ``` ### Test that an expected cluster is available for the project ``` describe google_container_clusters(project: 'chef-inspec-gcp', location: 'europe-west2-a') do its('cluster_names') { should include "my-cluster" } end ``` ### Test whether any clusters are in status “STOPPING” ``` describe google_container_clusters(project: 'chef-inspec-gcp', location: 'europe-west2-a') do its('cluster_statuses') { should_not include "STOPPING" } end ``` ### Test that a subset of all clusters matching “kube*” are “RUNNING” ``` google_container_clusters(project: gcp_project_id).where(cluster_name: /^kube/).cluster_names.each do |cluster_name| describe google_container_cluster(project: 'chef-inspec-gcp', location: 'europe-west2-a', name: cluster_name) do it { should exist } its('status') { should eq 'RUNNING' } end end ``` Properties ---------- Properties that can be accessed from the `google_container_clusters` resource: See the [google_container_cluster](../google_container_cluster/index#properties) resource for more information. `cluster_names` an array of `google_container_cluster` name `descriptions` an array of `google_container_cluster` description `initial_node_counts` an array of `google_container_cluster` initial_node_count `node_configs` an array of `google_container_cluster` node_config `master_auths` an array of `google_container_cluster` master_auth `logging_services` an array of `google_container_cluster` logging_service `monitoring_services` an array of `google_container_cluster` monitoring_service `cluster_networks` an array of `google_container_cluster` network `private_cluster_configs` an array of `google_container_cluster` private_cluster_config `cluster_ipv4_cidrs` an array of `google_container_cluster` cluster_ipv4_cidr `enable_tpus` an array of `google_container_cluster` enable_tpu `tpu_ipv4_cidr_blocks` an array of `google_container_cluster` tpu_ipv4_cidr_block `addons_configs` an array of `google_container_cluster` addons_config `subnetworks` an array of `google_container_cluster` subnetwork `locations` an array of `google_container_cluster` locations `resource_labels` an array of `google_container_cluster` resource_labels `label_fingerprints` an array of `google_container_cluster` label_fingerprint `legacy_abacs` an array of `google_container_cluster` legacy_abac `network_policies` an array of `google_container_cluster` network_policy `default_max_pods_constraints` an array of `google_container_cluster` default_max_pods_constraint `ip_allocation_policies` an array of `google_container_cluster` ip_allocation_policy `endpoints` an array of `google_container_cluster` endpoint `initial_cluster_versions` an array of `google_container_cluster` initial_cluster_version `current_master_versions` an array of `google_container_cluster` current_master_version `current_node_versions` an array of `google_container_cluster` current_node_version `create_times` an array of `google_container_cluster` create_time `cluster_statuses` an array of `google_container_cluster` status `status_messages` an array of `google_container_cluster` status_message `node_ipv4_cidr_sizes` an array of `google_container_cluster` node_ipv4_cidr_size `services_ipv4_cidrs` an array of `google_container_cluster` services_ipv4_cidr `current_node_counts` an array of `google_container_cluster` current_node_count `expire_times` an array of `google_container_cluster` expire_time `conditions` an array of `google_container_cluster` conditions `master_authorized_networks_configs` an array of `google_container_cluster` master_authorized_networks_config `node_pools` an array of `google_container_cluster` node_pools `pod_security_policy_configs` (Beta only) an array of `google_container_cluster` pod_security_policy_config `binary_authorizations` an array of `google_container_cluster` binary_authorization `locations` an array of `google_container_cluster` location Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Kubernetes Engine API](https://console.cloud.google.com/apis/library/container.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_container_clusters/google_container_node_pools resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_container_node_pools.md) Syntax ------ A `google_container_node_pools` is used to test a Google NodePool resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_container_node_pools(project: 'chef-gcp-inspec', location: 'europe-west2-a', cluster_name: 'gcp-inspec-kube-cluster') do its('initial_node_counts') { should include '1'} end ``` ### Test that there are no more than a specified number of node pools available for the project ``` describe google_container_node_pools(project: 'chef-inspec-gcp') do its('count') { should be <= 10} end ``` ### Test that an expected node pool is available for the project ``` describe google_container_node_pools(project: 'chef-inspec-gcp') do its('node_pool_names') { should include "us-east1-b" } end ``` ### Test that a subset of all node pools matching “mypool*” are “UP” ``` google_container_node_pools(project: 'chef-inspec-gcp', location: 'europe-west2-a', cluster_name: 'inspec-gcp-cluster').where(node_pool_name: /^mypool/).node_pool_names.each do |node_pool_name| describe google_container_node_pool(project: 'chef-inspec-gcp', location: 'europe-west2-a', cluster_name: 'inspec-gcp-cluster', nodepool_name: node_pool_name) do it { should exist } its('status') { should eq 'RUNNING' } end end ``` Properties ---------- Properties that can be accessed from the `google_container_node_pools` resource: See the [google_container_node_pool](../google_container_node_pool/index#properties) resource for more information. `node_pool_names` an array of `google_container_node_pool` name `configs` an array of `google_container_node_pool` config `initial_node_counts` an array of `google_container_node_pool` initial_node_count `node_pool_statuses` an array of `google_container_node_pool` status `status_messages` an array of `google_container_node_pool` status_message `versions` an array of `google_container_node_pool` version `autoscalings` an array of `google_container_node_pool` autoscaling `managements` an array of `google_container_node_pool` management `max_pods_constraints` an array of `google_container_node_pool` max_pods_constraint `conditions` an array of `google_container_node_pool` conditions `pod_ipv4_cidr_sizes` an array of `google_container_node_pool` pod_ipv4_cidr_size `clusters` an array of `google_container_node_pool` cluster `locations` an array of `google_container_node_pool` location Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Kubernetes Engine API](https://console.cloud.google.com/apis/library/container.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_container_node_pools/google_container_node_pool resource ====================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_container_node_pool.md) Syntax ------ A `google_container_node_pool` is used to test a Google NodePool resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_container_node_pool(project: 'chef-gcp-inspec', location: 'europe-west2-a', cluster_name: 'gcp-inspec-kube-cluster', nodepool_name: 'inspec-gcp-regional-node-pool') do it { should exist } its('initial_node_count') { should eq '1'} end describe google_container_node_pool(project: 'chef-gcp-inspec', location: 'europe-west2-a', cluster_name: 'gcp-inspec-kube-cluster', nodepool_name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP container node pool is in a particular state e.g. “RUNNING” ``` describe google_container_node_pool(project: 'chef-inspec-gcp', locations: 'europe-west2-a', cluster_name: 'inspec-gcp-kube-cluster', nodepool_name: 'inspec-gcp-kube-node-pool') do its('status') { should eq 'RUNNING' } end ``` ### Test GCP container node pool disk size in GB is as expected ``` describe google_container_node_pool(project: 'chef-inspec-gcp', locations: 'europe-west2-a', cluster_name: 'inspec-gcp-kube-cluster', nodepool_name: 'inspec-gcp-kube-node-pool') do its('config.disk_size_gb'){should eq 100} end ``` ### Test GCP container node pool machine type is as expected ``` describe google_container_node_pool(project: 'chef-inspec-gcp', locations: 'europe-west2-a', cluster_name: 'inspec-gcp-kube-cluster', nodepool_name: 'inspec-gcp-kube-node-pool') do its('config.machine_type'){should eq "n1-standard-1"} end ``` ### Test GCP container node pool node image type is as expected ``` describe google_container_node_pool(project: 'chef-inspec-gcp', locations: 'europe-west2-a', cluster_name: 'inspec-gcp-kube-cluster', nodepool_name: 'inspec-gcp-kube-node-pool') do its('config.image_type'){should eq "COS"} end ``` ### Test GCP container node pool initial node count is as expected ``` describe google_container_node_pool(project: 'chef-inspec-gcp', locations: 'europe-west2-a', cluster_name: 'inspec-gcp-kube-cluster', nodepool_name: 'inspec-gcp-kube-node-pool') do its('initial_node_count'){should eq 3} end ``` Properties ---------- Properties that can be accessed from the `google_container_node_pool` resource: `name` The name of the node pool. `config` The node configuration of the pool. * `machine_type` : The name of a Google Compute Engine machine type (e.g. n1-standard-1). If unspecified, the default machine type is n1-standard-1. * `disk_size_gb` : Size of the disk attached to each node, specified in GB. The smallest allowed disk size is 10GB. If unspecified, the default disk size is 100GB. * `oauth_scopes` : The set of Google API scopes to be made available on all of the node VMs under the “default” service account. The following scopes are recommended, but not required, and by default are not included: <https://www.googleapis.com/auth/compute> is required for mounting persistent storage on your nodes. <https://www.googleapis.com/auth/devstorage.read_only> is required for communicating with gcr.io (the Google Container Registry). If unspecified, no scopes are added, unless Cloud Logging or Cloud Monitoring are enabled, in which case their required scopes will be added. * `service_account` : The Google Cloud Platform Service Account to be used by the node VMs. If no Service Account is specified, the “default” service account is used. * `metadata` : The metadata key/value pairs assigned to instances in the cluster. Keys must conform to the regexp [a-zA-Z0-9-_]+ and be less than 128 bytes in length. These are reflected as part of a URL in the metadata server. Additionally, to avoid ambiguity, keys must not conflict with any other metadata keys for the project or be one of the four reserved keys: “instance-template”, “kube-env”, “startup-script”, and “user-data” Values are free-form strings, and only have meaning as interpreted by the image running in the instance. The only restriction placed on them is that each value’s size must be less than or equal to 32 KB. The total size of all keys and values must be less than 512 KB. An object containing a list of “key”: value pairs. Example: { “name”: “wrench”, “mass”: “1.3kg”, “count”: “3” }. * `image_type` : The image type to use for this node. Note that for a given image type, the latest version of it will be used. * `labels` : The map of Kubernetes labels (key/value pairs) to be applied to each node. These will added in addition to any default label(s) that Kubernetes may apply to the node. In case of conflict in label keys, the applied set may differ depending on the Kubernetes version – it’s best to assume the behavior is undefined and conflicts should be avoided. For more information, including usage and the valid values, see: <http://kubernetes.io/v1.1/docs/user-guide/labels.html> An object containing a list of “key”: value pairs. Example: { “name”: “wrench”, “mass”: “1.3kg”, “count”: “3” }. * `local_ssd_count` : The number of local SSD disks to be attached to the node. The limit for this value is dependant upon the maximum number of disks available on a machine per zone. See: <https://cloud.google.com/compute/docs/disks/local-ssd#local_ssd_limits> for more information. * `tags` : The list of instance tags applied to all nodes. Tags are used to identify valid sources or targets for network firewalls and are specified by the client during cluster or node pool creation. Each tag within the list must comply with RFC1035. * `preemptible` : Whether the nodes are created as preemptible VM instances. See: <https://cloud.google.com/compute/docs/instances/preemptible> for more information about preemptible VM instances. * `accelerators` : A list of hardware accelerators to be attached to each node + `accelerator_count` : The number of the accelerator cards exposed to an instance. + `accelerator_type` : The accelerator type resource name * `disk_type` : Type of the disk attached to each node (e.g. ‘pd-standard’ or ‘pd-ssd’) If unspecified, the default disk type is ‘pd-standard’ * `min_cpu_platform` : Minimum CPU platform to be used by this instance. The instance may be scheduled on the specified or newer CPU platform * `taints` : List of kubernetes taints to be applied to each node. + `key` : Key for taint + `value` : Value for taint + `effect` : Effect for taint `initial_node_count` The initial node count for the pool. You must ensure that your Compute Engine resource quota is sufficient for this number of instances. You must also have available firewall and routes quota. `status` Status of nodes in this pool instance `status_message` Additional information about the current status of this node pool instance `version` The version of the Kubernetes of this node. `autoscaling` Autoscaler configuration for this NodePool. Autoscaler is enabled only if a valid configuration is present. * `enabled` : Is autoscaling enabled for this node pool. * `min_node_count` : Minimum number of nodes in the NodePool. Must be >= 1 and <= maxNodeCount. * `max_node_count` : Maximum number of nodes in the NodePool. Must be >= minNodeCount. There has to enough quota to scale up the cluster. `management` Management configuration for this NodePool. * `auto_upgrade` : A flag that specifies whether node auto-upgrade is enabled for the node pool. If enabled, node auto-upgrade helps keep the nodes in your node pool up to date with the latest release version of Kubernetes. * `auto_repair` : A flag that specifies whether the node auto-repair is enabled for the node pool. If enabled, the nodes in this node pool will be monitored and, if they fail health checks too many times, an automatic repair action will be triggered. * `upgrade_options` : Specifies the Auto Upgrade knobs for the node pool. + `auto_upgrade_start_time` : This field is set when upgrades are about to commence with the approximate start time for the upgrades, in RFC3339 text format. + `description` : This field is set when upgrades are about to commence with the description of the upgrade. `max_pods_constraint` The constraint on the maximum number of pods that can be run simultaneously on a node in the node pool. * `max_pods_per_node` : Constraint enforced on the max num of pods per node. `conditions` Which conditions caused the current node pool state. * `code` : Machine-friendly representation of the condition. Possible values: + UNKNOWN + GCE_STOCKOUT + GKE_SERVICE_ACCOUNT_DELETED + GCE_QUOTA_EXCEEDED + SET_BY_OPERATOR `pod_ipv4_cidr_size` The pod CIDR block size per node in this node pool. `cluster` The cluster this node pool belongs to. `location` The location where the node pool is deployed GCP Permissions --------------- Ensure the [Kubernetes Engine API](https://console.cloud.google.com/apis/library/container.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_container_node_pool/google_container_regional_cluster resource ============================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_container_regional_cluster.md) Syntax ------ A `google_container_regional_cluster` is used to test a Google RegionalCluster resource Examples -------- ``` describe google_container_regional_cluster(project: 'chef-gcp-inspec', location: 'europe-west2', name: 'inspec-gcp-regional-cluster') do it { should exist } its('initial_node_count') { should eq '1'} its('location') { should eq 'europe-west2'} end describe google_container_regional_cluster(project: 'chef-gcp-inspec', location: 'europe-west2', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_container_regional_cluster` resource: `name` The name of this cluster. The name must be unique within this project and location, and can be up to 40 characters. Must be Lowercase letters, numbers, and hyphens only. Must start with a letter. Must end with a number or a letter. `description` An optional description of this cluster. `initial_node_count` The number of nodes to create in this cluster. You must ensure that your Compute Engine resource quota is sufficient for this number of instances. You must also have available firewall and routes quota. For requests, this field should only be used in lieu of a “nodePool” object, since this configuration (along with the “nodeConfig”) will be used to create a “NodePool” object with an auto-generated name. Do not use this and a nodePool at the same time. This field has been deprecated. Please use nodePool.initial_node_count instead. `node_config` Parameters used in creating the cluster’s nodes. For requests, this field should only be used in lieu of a “nodePool” object, since this configuration (along with the “initialNodeCount”) will be used to create a “NodePool” object with an auto-generated name. Do not use this and a nodePool at the same time. For responses, this field will be populated with the node configuration of the first node pool. If unspecified, the defaults are used. `machine_type` The name of a Google Compute Engine machine type (e.g. n1-standard-1). If unspecified, the default machine type is n1-standard-1. `disk_size_gb` Size of the disk attached to each node, specified in GB. The smallest allowed disk size is 10GB. If unspecified, the default disk size is 100GB. `oauth_scopes` The set of Google API scopes to be made available on all of the node VMs under the “default” service account. The following scopes are recommended, but not required, and by default are not included: <https://www.googleapis.com/auth/compute> is required for mounting persistent storage on your nodes. <https://www.googleapis.com/auth/devstorage.read_only> is required for communicating with gcr.io (the Google Container Registry). If unspecified, no scopes are added, unless Cloud Logging or Cloud Monitoring are enabled, in which case their required scopes will be added. `service_account` The Google Cloud Platform Service Account to be used by the node VMs. If no Service Account is specified, the “default” service account is used. `metadata` The metadata key/value pairs assigned to instances in the cluster. Keys must conform to the regexp [a-zA-Z0-9-_]+ and be less than 128 bytes in length. These are reflected as part of a URL in the metadata server. Additionally, to avoid ambiguity, keys must not conflict with any other metadata keys for the project or be one of the four reserved keys: “instance-template”, “kube-env”, “startup-script”, and “user-data” Values are free-form strings, and only have meaning as interpreted by the image running in the instance. The only restriction placed on them is that each value’s size must be less than or equal to 32 KB. The total size of all keys and values must be less than 512 KB. An object containing a list of “key”: value pairs. Example: { “name”: “wrench”, “mass”: “1.3kg”, “count”: “3” }. `image_type` The image type to use for this node. Note that for a given image type, the latest version of it will be used. `labels` The map of Kubernetes labels (key/value pairs) to be applied to each node. These will added in addition to any default label(s) that Kubernetes may apply to the node. In case of conflict in label keys, the applied set may differ depending on the Kubernetes version – it’s best to assume the behavior is undefined and conflicts should be avoided. For more information, including usage and the valid values, see: <http://kubernetes.io/v1.1/docs/user-guide/labels.html> An object containing a list of “key”: value pairs. Example: { “name”: “wrench”, “mass”: “1.3kg”, “count”: “3” }. `local_ssd_count` The number of local SSD disks to be attached to the node. The limit for this value is dependant upon the maximum number of disks available on a machine per zone. See: <https://cloud.google.com/compute/docs/disks/local-ssd#local_ssd_limits> for more information. `tags` The list of instance tags applied to all nodes. Tags are used to identify valid sources or targets for network firewalls and are specified by the client during cluster or node pool creation. Each tag within the list must comply with RFC1035. `preemptible` Whether the nodes are created as preemptible VM instances. See: <https://cloud.google.com/compute/docs/instances/preemptible> for more information about preemptible VM instances. `accelerators` A list of hardware accelerators to be attached to each node. See <https://cloud.google.com/compute/docs/gpus> for more information about support for GPUs. `accelerator_count` The number of accelerator cards exposed to an instance. `accelerator_type` The accelerator type resource name `disk_type` Type of the disk attached to each node (e.g. ‘pd-standard’ or ‘pd-ssd’) If unspecified, the default disk type is ‘pd-standard’ `min_cpu_platform` Minimum CPU platform to be used by this instance. The instance may be scheduled on the specified or newer CPU platform. `taints` List of kubernetes taints to be applied to each node. For more information, including usage and the valid values, see: <https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/> `key` Key for taint `value` Value for taint `effect` Effect for taint `master_auth` The authentication information for accessing the master endpoint. `username` The username to use for HTTP basic authentication to the master endpoint. `password` The password to use for HTTP basic authentication to the master endpoint. Because the master endpoint is open to the Internet, you should create a strong password with a minimum of 16 characters. `client_certificate_config` Configuration for client certificate authentication on the cluster. For clusters before v1.12, if no configuration is specified, a client certificate is issued. `issue_client_certificate` Issue a client certificate. `cluster_ca_certificate` Base64-encoded public certificate that is the root of trust for the cluster. `client_certificate` Base64-encoded public certificate used by clients to authenticate to the cluster endpoint. `client_key` Base64-encoded private key used by clients to authenticate to the cluster endpoint. `logging_service` The logging service the cluster should use to write logs. Currently available options: logging.googleapis.com - the Google Cloud Logging service. none - no logs will be exported from the cluster. if left as an empty string,logging.googleapis.com will be used. `monitoring_service` The monitoring service the cluster should use to write metrics. Currently available options: monitoring.googleapis.com - the Google Cloud Monitoring service. none - no metrics will be exported from the cluster. if left as an empty string, monitoring.googleapis.com will be used. `network` The name of the Google Compute Engine network to which the cluster is connected. If left unspecified, the default network will be used. `private_cluster_config` Configuration for a private cluster. `enable_private_nodes` Whether nodes have internal IP addresses only. If enabled, all nodes are given only RFC 1918 private addresses and communicate with the master via private networking. `enable_private_endpoint` Whether the master’s internal IP address is used as the cluster endpoint. `master_ipv4_cidr_block` The IP range in CIDR notation to use for the hosted master network. This range will be used for assigning internal IP addresses to the master or set of masters, as well as the ILB VIP. This range must not overlap with any other ranges in use within the cluster’s network. `private_endpoint` The internal IP address of this cluster’s master endpoint. `public_endpoint` The external IP address of this cluster’s master endpoint. `cluster_ipv4_cidr` The IP address range of the container pods in this cluster, in CIDR notation (e.g. 10.96.0.0/14). Leave blank to have one automatically chosen or specify a /14 block in 10.0.0.0/8. `enable_tpu` (Optional) Whether to enable Cloud TPU resources in this cluster. See the official documentation - <https://cloud.google.com/tpu/docs/kubernetes-engine-setup> `tpu_ipv4_cidr_block` The IP address range of the Cloud TPUs in this cluster, in [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation (e.g. `1.2.3.4/29`). `addons_config` Configurations for the various addons available to run in the cluster. `http_load_balancing` Configuration for the HTTP (L7) load balancing controller addon, which makes it easy to set up HTTP load balancers for services in a cluster. `disabled` Whether the HTTP Load Balancing controller is enabled in the cluster. When enabled, it runs a small pod in the cluster that manages the load balancers. `horizontal_pod_autoscaling` Configuration for the horizontal pod autoscaling feature, which increases or decreases the number of replica pods a replication controller has based on the resource usage of the existing pods. `disabled` Whether the Horizontal Pod Autoscaling feature is enabled in the cluster. When enabled, it ensures that a Heapster pod is running in the cluster, which is also used by the Cloud Monitoring service. `kubernetes_dashboard` Configuration for the Kubernetes Dashboard. This addon is deprecated, and will be disabled in 1.15. It is recommended to use the Cloud Console to manage and monitor your Kubernetes clusters, workloads and applications. `disabled` Whether the Kubernetes Dashboard is enabled for this cluster. `network_policy_config` Configuration for NetworkPolicy. This only tracks whether the addon is enabled or not on the Master, it does not track whether network policy is enabled for the nodes. `disabled` Whether NetworkPolicy is enabled for this cluster. `subnetwork` The name of the Google Compute Engine subnetwork to which the cluster is connected. `locations` The list of Google Compute Engine zones in which the cluster’s nodes should be located. `resource_labels` The resource labels for the cluster to use to annotate any related Google Compute Engine resources. `label_fingerprint` The fingerprint of the set of labels for this cluster. `legacy_abac` Configuration for the legacy ABAC authorization mode. `enabled` Whether the ABAC authorizer is enabled for this cluster. When enabled, identities in the system, including service accounts, nodes, and controllers, will have statically granted permissions beyond those provided by the RBAC configuration or IAM. `network_policy` Configuration options for the NetworkPolicy feature. `provider` The selected network policy provider. `enabled` Whether network policy is enabled on the cluster. `default_max_pods_constraint` The default constraint on the maximum number of pods that can be run simultaneously on a node in the node pool of this cluster. Only honored if cluster created with IP Alias support. `max_pods_per_node` Constraint enforced on the max num of pods per node. `ip_allocation_policy` Configuration for controlling how IPs are allocated in the cluster `use_ip_aliases` Whether alias IPs will be used for pod IPs in the cluster `create_subnetwork` Whether a new subnetwork will be created automatically for the cluster `subnetwork_name` A custom subnetwork name to be used if createSubnetwork is true. If this field is empty, then an automatic name will be chosen for the new subnetwork. `cluster_secondary_range_name` The name of the secondary range to be used for the cluster CIDR block. The secondary range will be used for pod IP addresses. This must be an existing secondary range associated with the cluster subnetwork `services_secondary_range_name` The name of the secondary range to be used as for the services CIDR block. The secondary range will be used for service ClusterIPs. This must be an existing secondary range associated with the cluster subnetwork. `cluster_ipv4_cidr_block` The IP address range for the cluster pod IPs. If this field is set, then cluster.cluster_ipv4_cidr must be left blank. This field is only applicable when useIpAliases is true. Set to blank to have a range chosen with the default size. Set to /netmask (e.g. /14) to have a range chosen with a specific netmask. `node_ipv4_cidr_block` The IP address range of the instance IPs in this cluster. This is applicable only if createSubnetwork is true. Set to blank to have a range chosen with the default size. Set to /netmask (e.g. /14) to have a range chosen with a specific netmask. `services_ipv4_cidr_block` The IP address range of the services IPs in this cluster. If blank, a range will be automatically chosen with the default size. This field is only applicable when useIpAliases is true. Set to blank to have a range chosen with the default size. Set to /netmask (e.g. /14) to have a range chosen with a specific netmask. `tpu_ipv4_cidr_block` The IP address range of the Cloud TPUs in this cluster. If unspecified, a range will be automatically chosen with the default size. This field is only applicable when useIpAliases is true. If unspecified, the range will use the default size. Set to /netmask (e.g. /14) to have a range chosen with a specific netmask. `endpoint` The IP address of this cluster’s master endpoint. The endpoint can be accessed from the internet at https://username:password@endpoint/ See the masterAuth property of this resource for username and password information. `initial_cluster_version` The software version of the master endpoint and kubelets used in the cluster when it was first created. The version can be upgraded over time. `current_master_version` The current software version of the master endpoint. `current_node_version` The current version of the node software components. If they are currently at multiple versions because they’re in the process of being upgraded, this reflects the minimum version of all nodes. `create_time` The time the cluster was created, in RFC3339 text format. `status` The current status of this cluster. `status_message` Additional information about the current status of this cluster, if available. `node_ipv4_cidr_size` The size of the address space on each node for hosting containers. This is provisioned from within the container_ipv4_cidr range. `services_ipv4_cidr` The IP address range of the Kubernetes services in this cluster, in CIDR notation (e.g. 1.2.3.4/29). Service addresses are typically put in the last /16 from the container CIDR. `current_node_count` The number of nodes currently in the cluster. `expire_time` The time the cluster will be automatically deleted in RFC3339 text format. `conditions` Which conditions caused the current cluster state. `code` Machine-friendly representation of the condition `message` Human-friendly representation of the condition `master_authorized_networks_config` Configuration for controlling how IPs are allocated in the cluster `enabled` Whether or not master authorized networks is enabled. `cidr_blocks` Define up to 50 external networks that could access Kubernetes master through HTTPS. `display_name` Optional field used to identify cidr blocks `cidr_block` Block specified in CIDR notation `location` The location where the cluster is deployed GCP Permissions --------------- Ensure the [Kubernetes Engine API](https://console.cloud.google.com/apis/library/container.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_container_regional_cluster/google_container_regional_node_pool resource ================================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_container_regional_node_pool.md) Syntax ------ A `google_container_regional_node_pool` is used to test a Google RegionalNodePool resource Examples -------- ``` describe google_container_regional_node_pool(project: 'chef-gcp-inspec', location: 'europe-west2', cluster: 'inspec-gcp-regional-cluster', name: 'inspec-gcp-regional-node-pool') do it { should exist } its('initial_node_count') { should eq '1'} end describe google_container_regional_node_pool(project: 'chef-gcp-inspec', location: 'europe-west2', cluster: 'inspec-gcp-regional-cluster', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_container_regional_node_pool` resource: `name` The name of the node pool. `config` The node configuration of the pool. `machine_type` The name of a Google Compute Engine machine type (e.g. n1-standard-1). If unspecified, the default machine type is n1-standard-1. `disk_size_gb` Size of the disk attached to each node, specified in GB. The smallest allowed disk size is 10GB. If unspecified, the default disk size is 100GB. `oauth_scopes` The set of Google API scopes to be made available on all of the node VMs under the “default” service account. The following scopes are recommended, but not required, and by default are not included: <https://www.googleapis.com/auth/compute> is required for mounting persistent storage on your nodes. <https://www.googleapis.com/auth/devstorage.read_only> is required for communicating with gcr.io (the Google Container Registry). If unspecified, no scopes are added, unless Cloud Logging or Cloud Monitoring are enabled, in which case their required scopes will be added. `service_account` The Google Cloud Platform Service Account to be used by the node VMs. If no Service Account is specified, the “default” service account is used. `metadata` The metadata key/value pairs assigned to instances in the cluster. Keys must conform to the regexp [a-zA-Z0-9-_]+ and be less than 128 bytes in length. These are reflected as part of a URL in the metadata server. Additionally, to avoid ambiguity, keys must not conflict with any other metadata keys for the project or be one of the four reserved keys: “instance-template”, “kube-env”, “startup-script”, and “user-data” Values are free-form strings, and only have meaning as interpreted by the image running in the instance. The only restriction placed on them is that each value’s size must be less than or equal to 32 KB. The total size of all keys and values must be less than 512 KB. An object containing a list of “key”: value pairs. Example: { “name”: “wrench”, “mass”: “1.3kg”, “count”: “3” }. `image_type` The image type to use for this node. Note that for a given image type, the latest version of it will be used. `labels` The map of Kubernetes labels (key/value pairs) to be applied to each node. These will added in addition to any default label(s) that Kubernetes may apply to the node. In case of conflict in label keys, the applied set may differ depending on the Kubernetes version – it’s best to assume the behavior is undefined and conflicts should be avoided. For more information, including usage and the valid values, see: <http://kubernetes.io/v1.1/docs/user-guide/labels.html> An object containing a list of “key”: value pairs. Example: { “name”: “wrench”, “mass”: “1.3kg”, “count”: “3” }. `local_ssd_count` The number of local SSD disks to be attached to the node. The limit for this value is dependant upon the maximum number of disks available on a machine per zone. See: <https://cloud.google.com/compute/docs/disks/local-ssd#local_ssd_limits> for more information. `tags` The list of instance tags applied to all nodes. Tags are used to identify valid sources or targets for network firewalls and are specified by the client during cluster or node pool creation. Each tag within the list must comply with RFC1035. `preemptible` Whether the nodes are created as preemptible VM instances. See: <https://cloud.google.com/compute/docs/instances/preemptible> for more information about preemptible VM instances. `accelerators` A list of hardware accelerators to be attached to each node `accelerator_count` The number of the accelerator cards exposed to an instance. `accelerator_type` The accelerator type resource name `disk_type` Type of the disk attached to each node (e.g. ‘pd-standard’ or ‘pd-ssd’) If unspecified, the default disk type is ‘pd-standard’ `min_cpu_platform` Minimum CPU platform to be used by this instance. The instance may be scheduled on the specified or newer CPU platform `taints` List of kubernetes taints to be applied to each node. `key` Key for taint `value` Value for taint `effect` Effect for taint `initial_node_count` The initial node count for the pool. You must ensure that your Compute Engine resource quota is sufficient for this number of instances. You must also have available firewall and routes quota. `status` Status of nodes in this pool instance `status_message` Additional information about the current status of this node pool instance `version` The version of the Kubernetes of this node. `autoscaling` Autoscaler configuration for this NodePool. Autoscaler is enabled only if a valid configuration is present. `enabled` Is autoscaling enabled for this node pool. `min_node_count` Minimum number of nodes in the NodePool. Must be >= 1 and <= maxNodeCount. `max_node_count` Maximum number of nodes in the NodePool. Must be >= minNodeCount. There has to enough quota to scale up the cluster. `management` Management configuration for this NodePool. `auto_upgrade` A flag that specifies whether node auto-upgrade is enabled for the node pool. If enabled, node auto-upgrade helps keep the nodes in your node pool up to date with the latest release version of Kubernetes. `auto_repair` A flag that specifies whether the node auto-repair is enabled for the node pool. If enabled, the nodes in this node pool will be monitored and, if they fail health checks too many times, an automatic repair action will be triggered. `upgrade_options` Specifies the Auto Upgrade knobs for the node pool. `auto_upgrade_start_time` This field is set when upgrades are about to commence with the approximate start time for the upgrades, in RFC3339 text format. `description` This field is set when upgrades are about to commence with the description of the upgrade. `max_pods_constraint` The constraint on the maximum number of pods that can be run simultaneously on a node in the node pool. `max_pods_per_node` : Constraint enforced on the max num of pods per node. `conditions` Which conditions caused the current node pool state. `code` Machine-friendly representation of the condition `pod_ipv4_cidr_size` The pod CIDR block size per node in this node pool. `cluster` The cluster this node pool belongs to. `location` The location where the node pool is deployed GCP Permissions --------------- Ensure the [Kubernetes Engine API](https://console.cloud.google.com/apis/library/container.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_container_regional_node_pool/google_container_regional_clusters resource ============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_container_regional_clusters.md) Syntax ------ A `google_container_regional_clusters` is used to test a Google RegionalCluster resource Examples -------- ``` describe google_container_regional_clusters(project: 'chef-gcp-inspec', location: 'europe-west2') do its('count') { should be >= 1 } its('names') { should include 'inspec-gcp-regional-cluster' } its('initial_node_counts') { should include '1'} end ``` Properties ---------- Properties that can be accessed from the `google_container_regional_clusters` resource: See the [google_container_regional_cluster](../google_container_regional_cluster/index#properties) resource for more information. `names` an array of `google_container_regional_cluster` name `descriptions` an array of `google_container_regional_cluster` description `initial_node_counts` an array of `google_container_regional_cluster` initial_node_count `node_configs` an array of `google_container_regional_cluster` node_config `master_auths` an array of `google_container_regional_cluster` master_auth `logging_services` an array of `google_container_regional_cluster` logging_service `monitoring_services` an array of `google_container_regional_cluster` monitoring_service `networks` an array of `google_container_regional_cluster` network `private_cluster_configs` an array of `google_container_regional_cluster` private_cluster_config `cluster_ipv4_cidrs` an array of `google_container_regional_cluster` cluster_ipv4_cidr `enable_tpus` an array of `google_container_regional_cluster` enable_tpu `tpu_ipv4_cidr_blocks` an array of `google_container_regional_cluster` tpu_ipv4_cidr_block `addons_configs` an array of `google_container_regional_cluster` addons_config `subnetworks` an array of `google_container_regional_cluster` subnetwork `locations` an array of `google_container_regional_cluster` locations `resource_labels` an array of `google_container_regional_cluster` resource_labels `label_fingerprints` an array of `google_container_regional_cluster` label_fingerprint `legacy_abacs` an array of `google_container_regional_cluster` legacy_abac `network_policies` an array of `google_container_regional_cluster` network_policy `default_max_pods_constraints` an array of `google_container_regional_cluster` default_max_pods_constraint `ip_allocation_policies` an array of `google_container_regional_cluster` ip_allocation_policy `endpoints` an array of `google_container_regional_cluster` endpoint `initial_cluster_versions` an array of `google_container_regional_cluster` initial_cluster_version `current_master_versions` an array of `google_container_regional_cluster` current_master_version `current_node_versions` an array of `google_container_regional_cluster` current_node_version `create_times` an array of `google_container_regional_cluster` create_time `statuses` an array of `google_container_regional_cluster` status `status_messages` an array of `google_container_regional_cluster` status_message `node_ipv4_cidr_sizes` an array of `google_container_regional_cluster` node_ipv4_cidr_size `services_ipv4_cidrs` an array of `google_container_regional_cluster` services_ipv4_cidr `current_node_counts` an array of `google_container_regional_cluster` current_node_count `expire_times` an array of `google_container_regional_cluster` expire_time `conditions` an array of `google_container_regional_cluster` conditions `master_authorized_networks_configs` an array of `google_container_regional_cluster` master_authorized_networks_config `locations` an array of `google_container_regional_cluster` location Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Kubernetes Engine API](https://console.cloud.google.com/apis/library/container.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_container_regional_clusters/google_container_regional_node_pools resource ================================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_container_regional_node_pools.md) Syntax ------ A `google_container_regional_node_pools` is used to test a Google RegionalNodePool resource Examples -------- ``` describe google_container_regional_node_pools(project: 'chef-gcp-inspec', location: 'europe-west2', cluster: 'inspec-gcp-regional-cluster') do its('initial_node_counts') { should include '1'} end ``` Properties ---------- Properties that can be accessed from the `google_container_regional_node_pools` resource: See the [google_container_regional_node_pool](../google_container_regional_node_pool/index#properties) resource for more information. `names` an array of `google_container_regional_node_pool` name `configs` an array of `google_container_regional_node_pool` config `initial_node_counts` an array of `google_container_regional_node_pool` initial_node_count `statuses` an array of `google_container_regional_node_pool` status `status_messages` an array of `google_container_regional_node_pool` status_message `versions` an array of `google_container_regional_node_pool` version `autoscalings` an array of `google_container_regional_node_pool` autoscaling `managements` an array of `google_container_regional_node_pool` management `max_pods_constraints` an array of `google_container_regional_node_pool` max_pods_constraint `conditions` an array of `google_container_regional_node_pool` conditions `pod_ipv4_cidr_sizes` an array of `google_container_regional_node_pool` pod_ipv4_cidr_size `clusters` an array of `google_container_regional_node_pool` cluster `locations` an array of `google_container_regional_node_pool` location Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Kubernetes Engine API](https://console.cloud.google.com/apis/library/container.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_container_regional_node_pools/google_dataproc_cluster resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_dataproc_cluster.md) Syntax ------ A `google_dataproc_cluster` is used to test a Google Cluster resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_dataproc_cluster(project: 'chef-gcp-inspec', region: 'europe-west2', cluster_name: 'inspec-dataproc-cluster') do it { should exist } its('labels') { should include('label' => 'value') } its('config.master_config.num_instances') { should cmp '1' } its('config.worker_config.num_instances') { should cmp '2' } its('config.master_config.machine_type_uri') { should match 'n1-standard-1' } its('config.worker_config.machine_type_uri') { should match 'n1-standard-1' } its('config.software_config.properties') { should include('dataproc:dataproc.allow.zero.workers' => 'true') } end describe google_dataproc_cluster(project: 'chef-gcp-inspec', region: 'europe-west2', cluster_name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_dataproc_cluster` resource: `cluster_name` The name of the cluster, unique within the project and region. `labels` Labels to apply to this cluster. A list of key->value pairs. `config` Configuration for the cluster `config_bucket` The Cloud Storage staging bucket used to stage files, such as Hadoop jars, between client machines and the cluster. `gce_cluster_config` Common config settings for resources of Google Compute Engine cluster instances, applicable to all instances in the cluster. `zone_uri` The zone where the Compute Engine cluster will be located `network_uri` The Compute Engine network to be used for machine communications `subnetwork_uri` The Compute Engine subnetwork to be used for machine communications `internal_ip_only` If true, all instances int he cluster will only have internal IP addresses `service_account_scopes` The URIs of service account scopes to be included in Compute Engine instances The following base set of scopes is always included: <https://www.googleapis.com/auth/cloud.useraccounts.readonly> <https://www.googleapis.com/auth/devstorage.read_write> <https://www.googleapis.com/auth/logging.write> `tags` The Compute Engine tags to add to all instances `metadata` The map of metadata entries to add to all instances `master_config` The config settings for Compute Engine resources in an instance group, such as a master or worker group. `num_instances` The number of VM instances in the instance group. For master instance groups, must be set to 1. `instance_names` The list of instance names. `image_uri` The Compute Engine image resource used for cluster instances. `machine_type_uri` The Compute Engine machine type used for cluster instances `disk_config` Disk option config settings `boot_disk_type` Type of the boot disk. Valid values are “pd-ssd” or “pd-standard” `boot_disk_size_gb` Size in GB of the boot disk. `num_local_ssds` Number of attached SSDs, from 0 to 4. `is_preemptible` Specifies if this instance group contains preemptible instances. `managed_group_config` The config for Compute Engine Instance Group Manager that manages this group. This is only used for preemptible instance groups. `instance_template_name` The name of the Instance Template used for the Managed Instance Group. `instance_group_manager_name` The name of the Instance Group Manager for this group `worker_config` The config settings for Compute Engine resources in an instance group, such as a master or worker group. `num_instances` The number of VM instances in the instance group. For master instance groups, must be set to 1. `instance_names` The list of instance names. `image_uri` The Compute Engine image resource used for cluster instances. `machine_type_uri` The Compute Engine machine type used for cluster instances `disk_config` Disk option config settings `boot_disk_type` Type of the boot disk. Valid values are “pd-ssd” or “pd-standard” `boot_disk_size_gb` Size in GB of the boot disk. `num_local_ssds` Number of attached SSDs, from 0 to 4. `is_preemptible` Specifies if this instance group contains preemptible instances. `managed_group_config` The config for Compute Engine Instance Group Manager that manages this group. This is only used for preemptible instance groups. `instance_template_name` The name of the Instance Template used for the Managed Instance Group. `instance_group_manager_name` The name of the Instance Group Manager for this group `secondary_worker_config` The config settings for Compute Engine resources in an instance group, such as a master or worker group. `num_instances` The number of VM instances in the instance group. For master instance groups, must be set to 1. `instance_names` The list of instance names. `image_uri` The Compute Engine image resource used for cluster instances. `machine_type_uri` The Compute Engine machine type used for cluster instances `disk_config` Disk option config settings `boot_disk_type` Type of the boot disk. Valid values are “pd-ssd” or “pd-standard” `boot_disk_size_gb` Size in GB of the boot disk. `num_local_ssds` Number of attached SSDs, from 0 to 4. `is_preemptible` Specifies if this instance group contains preemptible instances. `managed_group_config` The config for Compute Engine Instance Group Manager that manages this group. This is only used for preemptible instance groups. `instance_template_name` The name of the Instance Template used for the Managed Instance Group. `instance_group_manager_name` The name of the Instance Group Manager for this group `software_config` Specifies the selection and config of software inside the cluster `image_version` The version of software inside the cluster. It must be one of the supported Cloud Dataproc Versions, such as “1.2” (including a subminor version, such as “1.2.29”), or the “preview” version. `properties` The properties to set on daemon config files. Property keys are specified in the prefix:property format, for example `core:hadoop.tmp.dir` `optional_components` The set of optional components to activate on the cluster. Possible values: * COMPONENT_UNSPECIFIED * ANACONDA * HBASE * RANGER * SOLR * HIVE_WEBHCAT * JUPYTER * ZEPPELIN `initialization_actions` Specifies an executable to run on a fully configured node and a timeout period for executable completion. `executable_file` Cloud Storage URI of the executable file `execution_timeout` Amount of time executable has to complete `encryption_config` Encryption settings for the cluster. `gce_pd_kms_key_name` The Cloud KMS key name to use for PD disk encyption for all instances in the cluster. `security_config` Kerberos config holder. `kerberos_config` Kerberos related configuration. `enable_kerberos` Flag to indicate whether to Kerberize the cluster. `rootprincipal_password_uri` The cloud Storage URI of a KMS encrypted file containing the root principal password. `kms_key_uri` The uri of the KMS key used to encrypt various sensitive files. `keystore_uri` The Cloud Storage URI of the keystore file used for SSL encryption. `truststore_uri` The Cloud Storage URI of a KMS encrypted file containing the password to the user provided keystore. `key_password_uri` The Cloud Storage URI of a KMS encrypted file containing the password to the user provided key. `truststore_password_uri` The Cloud Storage URI of a KMS encrypted file containing the password to the user provided truststore. `cross_realm_trust_realm` The remote realm the Dataproc on-cluster KDC will trust, should the user enable cross realm trust. `cross_realm_trust_admin_server` The admin server (IP or hostname) for the remote trusted realm in a cross realm trust relationship. `cross_realm_trust_shared_password_uri` The Cloud Storage URI of a KMS encrypted file containing the shared password between the on-cluster Kerberos realm and the remote trusted realm, in a cross realm trust relationship. `kdc_db_key_uri` The Cloud Storage URI of a KMS encrypted file containing the master key of the KDC database. `tgt_lifetime_hours` The lifetime of the ticket granting ticket, in hours. `realm` The name of the on-cluster Kerberos realm. `region` The region in which the cluster and associated nodes will be created in. GCP Permissions --------------- Ensure the [Cloud Dataproc API](https://console.cloud.google.com/apis/library/dataproc.googleapis.com) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_dataproc_cluster/google_dns_managed_zone resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_dns_managed_zone.md) Syntax ------ A `google_dns_managed_zone` is used to test a Google ManagedZone resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_dns_managed_zone(project: 'chef-gcp-inspec', zone: 'example-zone') do it { should exist } its('dns_name') { should cmp 'dns-zone-name.com.' } its('description') { should cmp 'example description' } its('zone_signing_key_algorithm') { should cmp 'rsasha256' } its('key_signing_key_algorithm') { should cmp 'rsasha512' } end describe google_dns_managed_zone(project: 'chef-gcp-inspec', zone: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP compute zone exists ``` describe google_dns_managed_zone(project: 'chef-inspec-gcp', zone: 'zone-name') do it { should exist } end ``` ### Test that a GCP DNS managed zone has the expected DNS name ``` describe google_dns_managed_zone(project: 'chef-inspec-gcp', zone: 'zone-name') do its('dns_name') { should match 'mydomain.com' } end ``` ### Test that a GCP DNS managed zone has expected name server ``` describe google_dns_managed_zone(project: 'chef-inspec-gcp', zone: 'zone-name') do its('name_servers') { should include 'ns-cloud-d1.googledomains.com.' } end ``` Properties ---------- Properties that can be accessed from the `google_dns_managed_zone` resource: `description` A mutable string of at most 1024 characters associated with this resource for the user’s convenience. Has no effect on the managed zone’s function. `dns_name` The DNS name of this managed zone, for instance “example.com.”. `dnssec_config` DNSSEC configuration `kind` Identifies what kind of resource this is `non_existence` Specifies the mechanism used to provide authenticated denial-of-existence responses. non_existence can only be updated when the state is `off`. Possible values: * nsec * nsec3 `state` Specifies whether DNSSEC is enabled, and what mode it is in Possible values: * off * on * transfer `default_key_specs` Specifies parameters that will be used for generating initial DnsKeys for this ManagedZone. If you provide a spec for keySigning or zoneSigning, you must also provide one for the other. default_key_specs can only be updated when the state is `off`. `algorithm` String mnemonic specifying the DNSSEC algorithm of this key Possible values: * ecdsap256sha256 * ecdsap384sha384 * rsasha1 * rsasha256 * rsasha512 `key_length` Length of the keys in bits `key_type` Specifies whether this is a key signing key (KSK) or a zone signing key (ZSK). Key signing keys have the Secure Entry Point flag set and, when active, will only be used to sign resource record sets of type DNSKEY. Zone signing keys do not have the Secure Entry Point flag set and will be used to sign all other types of resource record sets. Possible values: * keySigning * zoneSigning `kind` Identifies what kind of resource this is `id` Unique identifier for the resource; defined by the server. `name` User assigned name for this resource. Must be unique within the project. `name_servers` Delegate your managed_zone to these virtual name servers; defined by the server `name_server_set` Optionally specifies the NameServerSet for this ManagedZone. A NameServerSet is a set of DNS name servers that all host the same ManagedZones. Most users will leave this field unset. `creation_time` The time that this resource was created on the server. This is in RFC3339 text format. `labels` A set of key/value label pairs to assign to this ManagedZone. `visibility` The zone’s visibility: public zones are exposed to the Internet, while private zones are visible only to Virtual Private Cloud resources. Possible values: * private * public `private_visibility_config` For privately visible zones, the set of Virtual Private Cloud resources that the zone is visible from. `networks` The list of VPC networks that can see this zone. `network_url` The fully qualified URL of the VPC network to bind to. This should be formatted like `https://www.googleapis.com/compute/v1/projects/{project}/global/networks/{network}` `forwarding_config` (Beta only) The presence for this field indicates that outbound forwarding is enabled for this zone. The value of this field contains the set of destinations to forward to. `target_name_servers` List of target name servers to forward to. Cloud DNS will select the best available name server if more than one target is given. `ipv4_address` IPv4 address of a target name server. `forwarding_path` Forwarding path for this TargetNameServer. If unset or `default` Cloud DNS will make forwarding decision based on address ranges, i.e. RFC1918 addresses go to the VPC, Non-RFC1918 addresses go to the Internet. When set to `private`, Cloud DNS will always send queries through VPC for this target Possible values: * default * private `peering_config` (Beta only) The presence of this field indicates that DNS Peering is enabled for this zone. The value of this field contains the network to peer with. `target_network` The network with which to peer. `network_url` The fully qualified URL of the VPC network to forward queries to. This should be formatted like `https://www.googleapis.com/compute/v1/projects/{project}/global/networks/{network}` `reverse_lookup` (Beta only) Specifies if this is a managed reverse lookup zone. If true, Cloud DNS will resolve reverse lookup queries using automatically configured records for VPC resources. This only applies to networks listed under `private_visibility_config`. `service_directory_config` (Beta only) The presence of this field indicates that this zone is backed by Service Directory. The value of this field contains information related to the namespace associated with the zone. `namespace` The namespace associated with the zone. `namespace_url` The fully qualified URL of the service directory namespace that should be associated with the zone. Ignored for `public` visibility zones. GCP Permissions --------------- Ensure the [Google Cloud DNS API](https://console.cloud.google.com/apis/library/dns.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_dns_managed_zone/google_dataproc_clusters resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_dataproc_clusters.md) Syntax ------ A `google_dataproc_clusters` is used to test a Google Cluster resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_dataproc_clusters(project: 'chef-gcp-inspec', region: 'europe-west2') do its('count') { should be >= 1 } its('cluster_names') { should include 'inspec-dataproc-cluster' } end ``` Properties ---------- Properties that can be accessed from the `google_dataproc_clusters` resource: See the [google_dataproc_cluster](../google_dataproc_cluster/index#properties) resource for more information. `cluster_names` an array of `google_dataproc_cluster` cluster_name `labels` an array of `google_dataproc_cluster` labels `configs` an array of `google_dataproc_cluster` config `regions` an array of `google_dataproc_cluster` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Dataproc API](https://console.cloud.google.com/apis/library/dataproc.googleapis.com) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_dataproc_clusters/google_dns_resource_record_sets resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_dns_resource_record_sets.md) Syntax ------ A `google_dns_resource_record_sets` is used to test a Google ResourceRecordSet resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_dns_resource_record_sets(project: 'chef-gcp-inspec', name: 'backend.my.domain.com.', managed_zone: 'inspec-gcp-managed-zone') do its('count') { should eq 3 } its('types') { should include 'A' } its('ttls') { should include '300' } its('targets.flatten') { should include '8.8.8.8' } its('targets.flatten') { should include '8.8.4.4' } end ``` Properties ---------- Properties that can be accessed from the `google_dns_resource_record_sets` resource: See the [google_dns_resource_record_set](../google_dns_resource_record_set/index#properties) resource for more information. `names` an array of `google_dns_resource_record_set` name `types` an array of `google_dns_resource_record_set` type `ttls` an array of `google_dns_resource_record_set` ttl `targets` an array of `google_dns_resource_record_set` target `managed_zones` an array of `google_dns_resource_record_set` managed_zone Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Google Cloud DNS API](https://console.cloud.google.com/apis/library/dns.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_dns_resource_record_sets/google_dns_managed_zones resource ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_dns_managed_zones.md) Syntax ------ A `google_dns_managed_zones` is used to test a Google ManagedZone resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_dns_managed_zones(project: 'chef-gcp-inspec') do it { should exist } its('zone_names') { should include 'example-zone' } its('zone_dns_names') { should include 'dns-zone-name.com.' } end ``` ### Test that there are no more than a specified number of zones available for the project ``` describe google_dns_managed_zones(project: 'chef-inspec-gcp') do its('count') { should be <= 100} end ``` ### Test that an expected, named managed zone is available for the project ``` describe google_dns_managed_zones(project: 'chef-inspec-gcp') do its('zone_names') { should include "zone-name" } end ``` ### Test that a subset of all zones matching “myzone*” exist ``` google_dns_managed_zones(project: 'chef-inspec-gcp').where(zone_name: /^myzone/).zone_names.each do |zone_name| describe google_dns_managed_zone(project: 'chef-inspec-gcp', zone: zone_name) do it { should exist } end end ``` Properties ---------- Properties that can be accessed from the `google_dns_managed_zones` resource: See the [google_dns_managed_zone](../google_dns_managed_zone/index#properties) resource for more information. `descriptions` an array of `google_dns_managed_zone` description `zone_dns_names` an array of `google_dns_managed_zone` dns_name `dnssec_configs` an array of `google_dns_managed_zone` dnssec_config `zone_ids` an array of `google_dns_managed_zone` id `zone_names` an array of `google_dns_managed_zone` name `name_servers` an array of `google_dns_managed_zone` name_servers `name_server_sets` an array of `google_dns_managed_zone` name_server_set `creation_times` an array of `google_dns_managed_zone` creation_time `labels` an array of `google_dns_managed_zone` labels `visibilities` an array of `google_dns_managed_zone` visibility `private_visibility_configs` an array of `google_dns_managed_zone` private_visibility_config `forwarding_configs` (Beta only) an array of `google_dns_managed_zone` forwarding_config `peering_configs` (Beta only) an array of `google_dns_managed_zone` peering_config `reverse_lookups` (Beta only) an array of `google_dns_managed_zone` reverse_lookup `service_directory_configs` (Beta only) an array of `google_dns_managed_zone` service_directory_config Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Google Cloud DNS API](https://console.cloud.google.com/apis/library/dns.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_dns_managed_zones/google_dns_resource_record_set resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_dns_resource_record_set.md) Syntax ------ A `google_dns_resource_record_set` is used to test a Google ResourceRecordSet resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_dns_resource_record_set(project: 'chef-gcp-inspec', name: 'backend.my.domain.com.', type: 'A', managed_zone: 'inspec-gcp-managed-zone') do it { should exist } its('type') { should eq 'A' } its('ttl') { should eq '300' } its('target') { should include '8.8.8.8' } its('target') { should include '8.8.4.4' } end ``` Properties ---------- Properties that can be accessed from the `google_dns_resource_record_set` resource: `name` For example, `www.example.com`. `type` One of valid DNS resource types. Possible values: * A * AAAA * CAA * CNAME * MX * NAPTR * NS * PTR * SOA * SPF * SRV * TLSA * TXT `ttl` Number of seconds that this ResourceRecordSet can be cached by resolvers. `target` As defined in RFC 1035 (section 5) and RFC 1034 (section 3.6.1) `managed_zone` Identifies the managed zone addressed by this request. GCP Permissions --------------- Ensure the [Google Cloud DNS API](https://console.cloud.google.com/apis/library/dns.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_dns_resource_record_set/google_filestore_instances resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_filestore_instances.md) Syntax ------ A `google_filestore_instances` is used to test a Google Instance resource Examples -------- ``` describe google_filestore_instances(project: 'chef-gcp-inspec', zone: 'us-central1-b') do its('tiers') { should include 'PREMIUM' } end ``` Properties ---------- Properties that can be accessed from the `google_filestore_instances` resource: See the [google_filestore_instance](../google_filestore_instance/index#properties) resource for more information. `names` an array of `google_filestore_instance` name `descriptions` an array of `google_filestore_instance` description `create_times` an array of `google_filestore_instance` create_time `tiers` an array of `google_filestore_instance` tier `labels` an array of `google_filestore_instance` labels `file_shares` an array of `google_filestore_instance` file_shares `networks` an array of `google_filestore_instance` networks `etags` an array of `google_filestore_instance` etag `zones` an array of `google_filestore_instance` zone Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_filestore_instances/google_filestore_instance resource ==================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_filestore_instance.md) Syntax ------ A `google_filestore_instance` is used to test a Google Instance resource Examples -------- ``` describe google_filestore_instance(project: 'chef-gcp-inspec', zone: 'us-central1-b', name: 'inspecgcp') do it { should exist } its('tier') { should cmp 'PREMIUM' } its('file_shares.count') { should cmp 1 } its('file_shares.first.capacity_gb') { should cmp '2660' } its('file_shares.first.name') { should cmp 'inspecgcp' } its('networks.count') { should cmp 1 } its('networks.first.network') { should cmp 'default' } its('networks.first.modes') { should include 'MODE_IPV4' } end describe google_filestore_instance(project: 'chef-gcp-inspec', zone: 'us-central1-b', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_filestore_instance` resource: `name` The resource name of the instance. `description` A description of the instance. `create_time` Creation timestamp in RFC3339 text format. `tier` The service tier of the instance. Possible values: * TIER_UNSPECIFIED * STANDARD * PREMIUM `labels` Resource labels to represent user-provided metadata. `file_shares` File system shares on the instance. For this version, only a single file share is supported. `name` The name of the fileshare (16 characters or less) `capacity_gb` File share capacity in GiB. This must be at least 1024 GiB for the standard tier, or 2560 GiB for the premium tier. `networks` VPC networks to which the instance is connected. For this version, only a single network is supported. `network` The name of the GCE VPC network to which the instance is connected. `modes` IP versions for which the instance has IP addresses assigned. `reserved_ip_range` A /29 CIDR block that identifies the range of IP addresses reserved for this instance. `ip_addresses` A list of IPv4 or IPv6 addresses. `etag` Server-specified ETag for the instance resource to prevent simultaneous updates from overwriting each other. `zone` The name of the Filestore zone of the instance. GCP Permissions --------------- © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_filestore_instance/google_iam_organization_custom_role resource ================================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_iam_organization_custom_role.md) Syntax ------ A `google_iam_organization_custom_role` is used to test a Google OrganizationCustomRole resource Examples -------- ``` describe google_iam_organization_custom_role(org_id: '12345', name: 'org-role') do it { should exist } its('stage') { should eq 'GA' } its('included_permissions') { should eq ["iam.roles.list"] } end describe google_iam_organization_custom_role(org_id: '12345', name: 'org-role', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_iam_organization_custom_role` resource: `name` The name of the role. `title` A human-readable title for the role. Typically this is limited to 100 UTF-8 bytes. `description` Human-readable description for the role `included_permissions` Names of permissions this role grants when bound in an IAM policy. `stage` The current launch stage of the role. Possible values: * ALPHA * BETA * GA * DEPRECATED * DISABLED * EAP `deleted` The current deleted state of the role GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_iam_organization_custom_role/google_iam_organization_custom_roles resource ================================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_iam_organization_custom_roles.md) Syntax ------ A `google_iam_organization_custom_roles` is used to test a Google OrganizationCustomRole resource Examples -------- ``` describe google_iam_organization_custom_roles(org_id: '190694428152') do its('names') { should include "organizations/123456/roles/role-id" } end ``` Properties ---------- Properties that can be accessed from the `google_iam_organization_custom_roles` resource: See the [google_iam_organization_custom_role](../google_iam_organization_custom_role/index#properties) resource for more information. `names` an array of `google_iam_organization_custom_role` name `titles` an array of `google_iam_organization_custom_role` title `descriptions` an array of `google_iam_organization_custom_role` description `included_permissions` an array of `google_iam_organization_custom_role` included_permissions `stages` an array of `google_iam_organization_custom_role` stage `deleteds` an array of `google_iam_organization_custom_role` deleted Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_iam_organization_custom_roles/google_iam_custom_roles resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_iam_custom_roles.md) Syntax ------ A `google_iam_custom_roles` is used to test a Google CustomRole resource Examples -------- ``` describe google_iam_custom_roles(project: 'chef-gcp-inspec') do its('names') { should include "projects/project-id/roles/role-id" } end ``` Properties ---------- Properties that can be accessed from the `google_iam_custom_roles` resource: See the [google_iam_custom_role](../google_iam_custom_role/index#properties) resource for more information. `names` an array of `google_iam_custom_role` name `titles` an array of `google_iam_custom_role` title `descriptions` an array of `google_iam_custom_role` description `included_permissions` an array of `google_iam_custom_role` included_permissions `stages` an array of `google_iam_custom_role` stage `deleteds` an array of `google_iam_custom_role` deleted Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_iam_custom_roles/google_iam_service_account resource ====================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_iam_service_account.md) Syntax ------ A `google_iam_service_account` is used to test a Google ServiceAccount resource Examples -------- ``` describe google_iam_service_account(project: 'chef-gcp-inspec', name: "<EMAIL>") do it { should exist } its('display_name') { should cmp '' } end describe google_iam_service_account(project: 'chef-gcp-inspec', name: "<EMAIL>") do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_iam_service_account` resource: `name` The name of the service account. `project_id` Id of the project that owns the service account. `unique_id` Unique and stable id of the service account `email` Email address of the service account. `display_name` User specified description of service account. `oauth2_client_id` OAuth2 client id for the service account. GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_iam_service_account/google_iam_service_account_keys resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_iam_service_account_keys.md) Syntax ------ A `google_iam_service_account_keys` is used to test a Google ServiceAccountKey resource Examples -------- ``` describe google_iam_service_account_keys(project: 'chef-gcp-inspec', service_account: "display-name@project-id.iam.gserviceaccount.com") do its('count') { should be <= 1000 } end ``` Properties ---------- Properties that can be accessed from the `google_iam_service_account_keys` resource: See the [google_iam_service_account_key](../google_iam_service_account_key/index#properties) resource for more information. `key_names` an array of `google_iam_service_account_key` name `private_key_types` an array of `google_iam_service_account_key` private_key_type `key_algorithms` an array of `google_iam_service_account_key` key_algorithm `private_key_data` an array of `google_iam_service_account_key` private_key_data `public_key_data` an array of `google_iam_service_account_key` public_key_data `valid_after_times` an array of `google_iam_service_account_key` valid_after_time `valid_before_times` an array of `google_iam_service_account_key` valid_before_time `key_types` an array of `google_iam_service_account_key` key_type `service_accounts` an array of `google_iam_service_account_key` service_account `paths` an array of `google_iam_service_account_key` path Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_iam_service_account_keys/google_iam_custom_role resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_iam_custom_role.md) Syntax ------ A `google_iam_custom_role` is used to test a Google CustomRole resource Examples -------- ``` describe google_iam_custom_role(project: 'chef-gcp-inspec', name: 'admin-role') do it { should exist } its('stage') { should eq 'GA' } its('included_permissions') { should eq ["iam.roles.list"] } end describe google_iam_custom_role(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_iam_custom_role` resource: `name` The name of the role. `title` A human-readable title for the role. Typically this is limited to 100 UTF-8 bytes. `description` Human-readable description for the role `included_permissions` Names of permissions this role grants when bound in an IAM policy. `stage` The current launch stage of the role. `deleted` The current deleted state of the role GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_iam_custom_role/google_iam_service_account_key resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_iam_service_account_key.md) Syntax ------ A `google_iam_service_account_key` is used to test a Google ServiceAccountKey resource Examples -------- ``` google_iam_service_account_keys(project: 'chef-gcp-inspec', service_account: "<EMAIL>.iam.gserviceaccount.com").key_names.each do |sa_key_name| describe end ``` Properties ---------- Properties that can be accessed from the `google_iam_service_account_key` resource: `name` The name of the key. `private_key_type` Output format for the service account key. `key_algorithm` Specifies the algorithm for the key. `private_key_data` Private key data. Base-64 encoded. `public_key_data` Public key data. Base-64 encoded. `valid_after_time` Key can only be used after this time. `valid_before_time` Key can only be used before this time. `key_type` Specifies the type of the key. Possible values include: * KEY_TYPE_UNSPECIFIED * USER_MANAGED * SYSTEM_MANAGED `service_account` The name of the serviceAccount. `path` The full name of the file that will hold the service account private key. The management of this file will depend on the value of sync_file parameter. File path must be absolute. GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_iam_service_account_key/google_kms_crypto_key_iam_bindings resource ================================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_kms_crypto_key_iam_bindings.md) **This resource is deprecated. Please use google_kms_crypto_key_iam_policy instead** Use the `google_kms_crypto_key_iam_bindings` InSpec audit resource to test properties of all, or a filtered group of, GCP KMS Crypto Key IAM Bindings. Syntax ------ A `google_kms_crypto_key_iam_bindings` resource block collects GCP KMS Crypto Key IAM Bindings then tests that group. ``` describe google_kms_crypto_key_iam_bindings(crypto_key_url: 'projects/project/locations/europe-west2/keyRings/key-ring/cryptoKeys/key-name') do it { should exist } end ``` Use this InSpec resource to enumerate roles then test in-depth using `google_kms_key_ring_iam_binding`. ``` google_kms_crypto_key_iam_bindings(crypto_key_url: 'projects/project/locations/europe-west2/keyRings/key-ring/cryptoKeys/key-name').iam_binding_roles.each do |iam_binding_role| describe google_kms_crypto_key_iam_binding(crypto_key_url: 'projects/project/locations/europe-west2/keyRings/key-ring/cryptoKeys/key-name', role: "roles/owner") do it { should exist } its('members') {should include 'user:<EMAIL>' } end end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Test that there are no more than a specified number of IAM bindings roles available for the crypto key ``` describe google_kms_crypto_key_iam_bindings(crypto_key_url: 'projects/project/locations/europe-west2/keyRings/key-ring/cryptoKeys/key-name') do its('count') { should be <= 100} end ``` ### Test that an expected IAM binding is available for the crypto key ``` describe google_kms_crypto_key_iam_bindings(crypto_key_url: 'projects/project/locations/europe-west2/keyRings/key-ring/cryptoKeys/key-name') do its('iam_binding_roles') { should include "roles/storage.admin" } end ``` ### Test that a particular role does not exist using filtering of the plural resource ``` describe google_kms_crypto_key_iam_bindings(crypto_key_url: 'projects/project/locations/europe-west2/keyRings/key-ring/cryptoKeys/key-name').where(iam_binding_role: "roles/iam.securityReviewer") do it { should_not exist } end ``` Filter Criteria --------------- This resource supports the following filter criteria: `iam_binding_role`. This may be used with `where`, as a block or as a method. Properties ---------- * `iam_binding_roles` - an array of google_kms_crypto_key_iam_binding role strings e.g. `["roles/compute.admin", "roles/owner"]` GCP Permissions --------------- Ensure the [Cloud Key Management Service (KMS) API](https://console.cloud.google.com/apis/library/cloudkms.googleapis.com/) is enabled for the project where the resource is located.s © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_kms_crypto_key_iam_bindings/google_kms_crypto_key_iam_binding resource =============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_kms_crypto_key_iam_binding.md) Syntax ------ A `google_kms_crypto_key_iam_binding` is used to test a Google CryptoKey Iam Bindings Examples -------- ``` describe google_kms_crypto_key_iam_binding(project: "project", location: "location", key_ring_name: "key_ring_name", crypto_key_name: "crypto_key_name", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` Properties ---------- Properties that can be accessed from the `google_kms_crypto_key_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. GCP Permissions --------------- Ensure the [Cloud Key Management Service (KMS) API](https://console.cloud.google.com/apis/library/cloudkms.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_kms_crypto_key_iam_binding/google_kms_crypto_key resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_kms_crypto_key.md) Syntax ------ A `google_kms_crypto_key` is used to test a Google CryptoKey resource Examples -------- ``` describe google_kms_crypto_key(project: 'chef-gcp-inspec', location: 'europe-west2', key_ring_name: 'kms-key-ring', name: 'kms-key') do it { should exist } its('crypto_key_name') { should cmp 'kms-key' } its('primary_state') { should eq "ENABLED" } its('purpose') { should eq "ENCRYPT_DECRYPT" } its('next_rotation_time') { should be > Time.now - 100000 } its('create_time') { should be > Time.now - 365*60*60*24*10 } end describe google_kms_crypto_key(project: 'chef-gcp-inspec', location: 'europe-west2', key_ring_name: 'kms-key-ring', name: "nonexistent") do it { should_not exist } end ``` ### Test that a GCP KMS crypto key was created recently ``` describe google_kms_crypto_key(project: 'chef-inspec-gcp', location: 'us-east1', key_ring_name: 'key-ring', name: 'crypto-key') do its('create_time_date') { should be > Time.now - 365*60*60*24*10 } end ``` ### Test when the next rotation time for a GCP KMS crypto key is scheduled ``` describe google_kms_crypto_key(project: 'chef-inspec-gcp', location: 'us-east1', key_ring_name: 'key-ring', name: 'crypto-key') do its('next_rotation_time_date') { should be > Time.now - 100000 } end ``` ### Check that the crypto key purpose is as expected ``` describe google_kms_crypto_key(project: 'chef-inspec-gcp', location: 'us-east1', key_ring_name: 'key-ring', name: 'crypto-key') do its('purpose') { should eq "ENCRYPT_DECRYPT" } end ``` ### Check that the crypto key primary is in “ENABLED” state ``` describe google_kms_crypto_key(project: 'chef-inspec-gcp', location: 'us-east1', key_ring_name: 'key-ring', name: 'crypto-key') do its('primary_state') { should eq "ENABLED" } end ``` Properties ---------- Properties that can be accessed from the `google_kms_crypto_key` resource: `crypto_key_name` The resource name for the CryptoKey. `create_time` The time that this resource was created on the server. This is in RFC3339 text format. `labels` Labels with user-defined metadata to apply to this resource. `purpose` The immutable purpose of this CryptoKey. See the [purpose reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys#CryptoKeyPurpose) for possible inputs. Possible values: * ENCRYPT_DECRYPT * ASYMMETRIC_SIGN * ASYMMETRIC_DECRYPT `rotation_period` Every time this period passes, generate a new CryptoKeyVersion and set it as the primary. The first rotation will take place after the specified period. The rotation period has the format of a decimal number with up to 9 fractional digits, followed by the letter `s` (seconds). It must be greater than a day (ie, 86400). `version_template` A template describing settings for new crypto key versions. `algorithm` The algorithm to use when creating a version based on this template. See the [algorithm reference](https://cloud.google.com/kms/docs/reference/rest/v1/CryptoKeyVersionAlgorithm) for possible inputs. `protection_level` The protection level to use when creating a version based on this template. Possible values: * SOFTWARE * HSM `next_rotation_time` The time when KMS will create a new version of this Crypto Key. `key_ring` The KeyRing that this key belongs to. Format: `'projects/{{project}}/locations/{{location}}/keyRings/{{keyRing}}'`. GCP Permissions --------------- Ensure the [Cloud Key Management Service (KMS) API](https://console.cloud.google.com/apis/library/cloudkms.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_kms_crypto_key/google_iam_service_accounts resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_iam_service_accounts.md) Syntax ------ A `google_iam_service_accounts` is used to test a Google ServiceAccount resource Examples -------- ``` describe google_iam_service_accounts(project: 'chef-gcp-inspec', name: "<EMAIL>") do its('service_account_emails') { should include "<EMAIL>" } its('count') { should be <= 1000 } end ``` Properties ---------- Properties that can be accessed from the `google_iam_service_accounts` resource: See the [google_iam_service_account](../google_iam_service_account/index#properties) resource for more information. `service_account_names` an array of `google_iam_service_account` name `project_ids` an array of `google_iam_service_account` project_id `service_account_ids` an array of `google_iam_service_account` unique_id `service_account_emails` an array of `google_iam_service_account` email `service_account_display_names` an array of `google_iam_service_account` display_name `oauth2_client_ids` an array of `google_iam_service_account` oauth2_client_id Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_iam_service_accounts/google_kms_crypto_key_iam_policy resource ============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_kms_crypto_key_iam_policy.md) Syntax ------ A `google_kms_crypto_key_iam_policy` is used to test a Google CryptoKey Iam Policy resource Examples -------- ``` describe google_kms_crypto_key_iam_policy(project: "project", location: "location", key_ring_name: "key_ring_name", crypto_key_name: "crypto_key_name") do it { should exist } end google_kms_crypto_key_iam_policy(project: "project", location: "location", key_ring_name: "key_ring_name", crypto_key_name: "crypto_key_name").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` Properties ---------- Properties that can be accessed from the `google_kms_crypto_key_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Cloud Key Management Service (KMS) API](https://console.cloud.google.com/apis/library/cloudkms.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_kms_crypto_key_iam_policy/google_kms_crypto_keys resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_kms_crypto_keys.md) Syntax ------ A `google_kms_crypto_keys` is used to test a Google CryptoKey resource Examples -------- ``` describe google_kms_crypto_keys(project: 'chef-gcp-inspec', location: 'europe-west2', key_ring_name: 'kms-key-ring') do its('count') { should be >= 1 } its('crypto_key_names') { should include 'kms-key' } end ``` ### Test that there are no more than a specified number of keys in the key ring ``` describe google_kms_crypto_keys(project: 'chef-inspec-gcp', location: 'us-east1', key_ring_name: 'key-ring') do its('count') { should be <= 100} end ``` ### Test that an expected key name is present in the key ring ``` describe google_kms_crypto_keys(project: 'chef-inspec-gcp', location: 'us-east1', key_ring_name: 'key-ring') do its('crypto_key_names') { should include "my-crypto-key-name" } end ``` Properties ---------- Properties that can be accessed from the `google_kms_crypto_keys` resource: See the [google_kms_crypto_key](../google_kms_crypto_key/index#properties) resource for more information. `crypto_key_names` an array of `google_kms_crypto_key` crypto_key_name `create_times` an array of `google_kms_crypto_key` create_time `labels` an array of `google_kms_crypto_key` labels `purposes` an array of `google_kms_crypto_key` purpose `rotation_periods` an array of `google_kms_crypto_key` rotation_period `version_templates` an array of `google_kms_crypto_key` version_template `next_rotation_times` an array of `google_kms_crypto_key` next_rotation_time `key_rings` an array of `google_kms_crypto_key` key_ring Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Key Management Service (KMS) API](https://console.cloud.google.com/apis/library/cloudkms.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_kms_crypto_keys/google_kms_key_ring_iam_binding resource ============================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_kms_key_ring_iam_binding.md) Syntax ------ A `google_kms_key_ring_iam_binding` is used to test a Google KeyRing Iam Bindings Examples -------- ``` describe google_kms_key_ring_iam_binding(project: "project", location: "location", key_ring_name: "key_ring_name", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` Properties ---------- Properties that can be accessed from the `google_kms_key_ring_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. GCP Permissions --------------- Ensure the [Cloud Key Management Service (KMS) API](https://console.cloud.google.com/apis/library/cloudkms.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_kms_key_ring_iam_binding/google_kms_key_ring resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_kms_key_ring.md) Syntax ------ A `google_kms_key_ring` is used to test a Google KeyRing resource Examples -------- ``` describe google_kms_key_ring(project: 'chef-gcp-inspec', location: 'europe-west2', name: 'kms-key-ring') do it { should exist } its('create_time') { should be > Time.now - 365*60*60*24*10 } its('key_ring_name'){ should eq 'kms-key-ring' } its('key_ring_url'){ should match 'kms-key-ring' } end describe google_kms_key_ring(project: 'chef-gcp-inspec', location: 'europe-west2', name: "nonexistent") do it { should_not exist } end ``` ### Test that a GCP kms key ring exists ``` describe google_kms_key_ring(project: 'chef-inspec-gcp', location: 'us-east1', name: 'key-ring-name') do it { should exist } end ``` ### Test that a GCP kms key ring is in the expected state For any existing key ring, below should definitely be true! ``` describe google_kms_key_ring(project: 'chef-inspec-gcp', location: 'us-east1', name: 'key-ring-name') do its('create_time_date') { should be > Time.now - 365*60*60*24*50 } end ``` Properties ---------- Properties that can be accessed from the `google_kms_key_ring` resource: `create_time` The time that this resource was created on the server. This is in RFC3339 text format. `key_ring_url` The full resource name for the KeyRing `location` The location for the KeyRing. A full list of valid locations can be found by running `gcloud kms locations list`. GCP Permissions --------------- Ensure the [Cloud Key Management Service (KMS) API](https://console.cloud.google.com/apis/library/cloudkms.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_kms_key_ring/google_kms_key_ring_iam_bindings resource ============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_kms_key_ring_iam_bindings.md) **This resource is deprecated. Please use `google_kms_key_ring_iam_policy` instead** Use the `google_kms_key_ring_iam_bindings` InSpec audit resource to test properties of all, or a filtered group of, GCP KMS key ring IAM bindings. Syntax ------ A `google_kms_key_ring_iam_bindings` resource block collects GCP KMS key ring IAM bindings then tests that group. ``` describe google_kms_key_ring_iam_bindings(key_ring_url: 'projects/project/locations/europe-west2/keyRings/key-ring') do it { should exist } end ``` Use this InSpec resource to enumerate roles then test in-depth using `google_kms_key_ring_iam_binding`. ``` google_kms_key_ring_iam_bindings(key_ring_url: 'projects/project/locations/europe-west2/keyRings/key-ring').iam_binding_roles.each do |iam_binding_role| describe google_kms_key_ring_iam_binding(key_ring_url: 'projects/project/locations/europe-west2/keyRings/key-ring', role: "roles/owner") do it { should exist } its('members') {should include 'user:<EMAIL>' } end end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Test that there are no more than a specified number of IAM bindings roles available for the key ring ``` describe google_kms_key_ring_iam_bindings(key_ring_url: 'projects/project/locations/europe-west2/keyRings/key-ring') do its('count') { should be <= 100} end ``` ### Test that an expected IAM binding is available for the key ring ``` describe google_kms_key_ring_iam_bindings(key_ring_url: 'projects/project/locations/europe-west2/keyRings/key-ring') do its('iam_binding_roles') { should include "roles/storage.admin" } end ``` ### Test that a particular role does not exist using filtering of the plural resource ``` describe google_kms_key_ring_iam_bindings(key_ring_url: 'projects/project/locations/europe-west2/keyRings/key-ring').where(iam_binding_role: "roles/iam.securityReviewer") do it { should_not exist } end ``` Filter Criteria --------------- This resource supports the following filter criteria: `iam_binding_role`. This may be used with `where`, as a block or as a method. Properties ---------- * `iam_binding_roles` - an array of google_kms_key_ring_iam_binding role strings e.g. `["roles/compute.admin", "roles/owner"]` GCP Permissions --------------- Ensure the [Cloud Key Management Service (KMS) API](https://console.cloud.google.com/apis/library/cloudkms.googleapis.com/) is enabled for the project where the resource is located.s © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_kms_key_ring_iam_bindings/google_kms_key_ring_iam_policy resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_kms_key_ring_iam_policy.md) Syntax ------ A `google_kms_key_ring_iam_policy` is used to test a Google KeyRing Iam Policy resource Examples -------- ``` describe google_kms_key_ring_iam_policy(project: "project", location: "location", key_ring_name: "key_ring_name") do it { should exist } end google_kms_key_ring_iam_policy(project: "project", location: "location", key_ring_name: "key_ring_name").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` Properties ---------- Properties that can be accessed from the `google_kms_key_ring_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Cloud Key Management Service (KMS) API](https://console.cloud.google.com/apis/library/cloudkms.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_kms_key_ring_iam_policy/google_kms_key_rings resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_kms_key_rings.md) Syntax ------ A `google_kms_key_rings` is used to test a Google KeyRing resource Examples -------- ``` describe google_kms_key_rings(project: 'chef-gcp-inspec', location: 'europe-west2') do its('key_ring_names'){ should include 'kms-key-ring' } end describe.one do google_kms_key_rings(project: 'chef-gcp-inspec', location: 'europe-west2').key_ring_urls do |url| describe url do it { should match 'kms-key-ring' } end end end ``` ### Test that there are no more than a specified number of kms_key_rings available for the project ``` describe google_kms_key_rings(project: 'chef-inspec-gcp', location: 'us-east1') do its('count') { should be <= 200} end ``` ### Test that an expected kms_key_ring is available for the project ``` describe google_kms_key_rings(project: 'chef-inspec-gcp', location: 'us-east1') do its('key_ring_names') { should include "a-named-key" } end ``` ### Test that all KMS key rings were created in the past year ``` describe google_kms_key_rings(project: gcp_project_id, location: 'us-east1').key_ring_names.each do |key_ring_name| describe google_kms_key_ring(project: 'chef-inspec-gcp', location: 'us-east1', 'name: key_ring_name) do it { should exist } its('create_time_date') { should be > Time.now - 365*60*60*24 } end end ``` Properties ---------- Properties that can be accessed from the `google_kms_key_rings` resource: See the [google_kms_key_ring](../google_kms_key_ring/index#properties) resource for more information. `create_times` an array of `google_kms_key_ring` create_time `key_ring_urls` an array of `google_kms_key_ring` key_ring_url `locations` an array of `google_kms_key_ring` location Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Key Management Service (KMS) API](https://console.cloud.google.com/apis/library/cloudkms.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_kms_key_rings/google_logging_folder_exclusion resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_logging_folder_exclusion.md) Syntax ------ A `google_logging_folder_exclusion` is used to test a Google FolderExclusion resource Examples -------- ``` # Getting folder exclusions is complicated due to the name being generated by the server. # This can be drastically simplified if you have the name when writing the test describe.one do google_resourcemanager_folders(parent: 'organizations/12345').names.each do |folder_name| # name on a folder is in the form `folders/12345` google_logging_folder_exclusions(folder: folder_name.split('/')[1]).names.each do |exclusion_name| describe google_logging_folder_exclusion(folder: folder_name.split('/')[1], name: exclusion_name) do its('name'){ should cmp 'inspec-folder-exclusion' } its('description'){ should cmp 'My folder exclusion description' } its('filter'){ should cmp 'resource.type = gce_instance AND severity <= DEBUG' } end end end end ``` Properties ---------- Properties that can be accessed from the `google_logging_folder_exclusion` resource: `folder` Id of the folder that this exclusion applies to. `name` Name of the exclusion, specified by the server during create. `description` A user provided description of this exclusion. `filter` An advanced logs filter. The only exported log entries are those that are in the resource owning the sink and that match the filter. `disabled` If set to true then this exclusion is disabled and it does not exclude any log entries. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_logging_folder_exclusion/google_logging_folder_log_sink resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_logging_folder_log_sink.md) Syntax ------ A `google_logging_folder_log_sink` is used to test a Google FolderLogSink resource Examples -------- ``` # Getting folder sinks is complicated due to the name being generated by the server. # This can be drastically simplified if you have the folder name when writing the test describe.one do google_resourcemanager_folders(parent: 'organizations/12345').names.each do |folder_name| # name on a folder is in the form `folders/12345` describe google_logging_folder_log_sink(folder: folder_name.split('/')[1], name: 'inspec-gcp-folder-sink') do it { should exist } its('filter') { should cmp 'resource.type = gce_instance AND severity >= ERROR' } end end end ``` Properties ---------- Properties that can be accessed from the `google_logging_folder_log_sink` resource: `folder` Id of the folder that this sink belongs to `name` Name of the log sink. `filter` An advanced logs filter. The only exported log entries are those that are in the resource owning the sink and that match the filter. `destination` The export destination. `writer_identity` An IAM identity—a service account or group—under which Logging writes the exported log entries to the sink’s destination. This field is set by sinks.create and sinks.update based on the value of uniqueWriterIdentity in those methods. `include_children` If the field is false, the default, only the logs owned by the sink’s parent resource are available for export. If the field is true, then logs from all the projects, folders, and billing accounts contained in the sink’s parent resource are also available for export. Whether a particular log entry from the children is exported depends on the sink’s filter expression. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_logging_folder_log_sink/google_logging_folder_exclusions resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_logging_folder_exclusions.md) Syntax ------ A `google_logging_folder_exclusions` is used to test a Google FolderExclusion resource Examples -------- ``` # Getting folder exclusions is complicated due to the name being generated by the server. # This can be drastically simplified if you have the name when writing the test describe.one do google_resourcemanager_folders(parent: 'organizations/12345').names.each do |name| # name on a folder is in the form `folders/12345` describe google_logging_folder_exclusions(folder: name.split('/')[1]) do its('names'){ should include 'inspec-folder-exclusion' } its('descriptions'){ should include 'My folder exclusion description' } its('filters'){ should include 'resource.type = gce_instance AND severity <= DEBUG' } end end end ``` Properties ---------- Properties that can be accessed from the `google_logging_folder_exclusions` resource: See the [google_logging_folder_exclusion](../google_logging_folder_exclusion/index#properties) resource for more information. `folders` an array of `google_logging_folder_exclusion` folder `names` an array of `google_logging_folder_exclusion` name `descriptions` an array of `google_logging_folder_exclusion` description `filters` an array of `google_logging_folder_exclusion` filter `disableds` an array of `google_logging_folder_exclusion` disabled Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_logging_folder_exclusions/google_logging_folder_log_sinks resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_logging_folder_log_sinks.md) Syntax ------ A `google_logging_folder_log_sinks` is used to test a Google FolderLogSink resource Examples -------- ``` # Getting folder sinks is complicated due to the name being generated by the server. # This can be drastically simplified if you have the folder name when writing the test describe.one do google_resourcemanager_folders(parent: 'organizations/12345').names.each do |folder_name| # name on a folder is in the form `folders/12345` describe google_logging_folder_log_sinks(folder: folder_name.split('/')[1]) do its('names') { should include 'inspec-gcp-folder-sink' } its('filters') { should include 'resource.type = gce_instance AND severity >= ERROR' } end end end ``` Properties ---------- Properties that can be accessed from the `google_logging_folder_log_sinks` resource: See the [google_logging_folder_log_sink](../google_logging_folder_log_sink/index#properties) resource for more information. `folders` an array of `google_logging_folder_log_sink` folder `names` an array of `google_logging_folder_log_sink` name `filters` an array of `google_logging_folder_log_sink` filter `destinations` an array of `google_logging_folder_log_sink` destination `writer_identities` an array of `google_logging_folder_log_sink` writer_identity `include_children` an array of `google_logging_folder_log_sink` include_children Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_logging_folder_log_sinks/google_logging_project_exclusion resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_logging_project_exclusion.md) Syntax ------ A `google_logging_project_exclusion` is used to test a Google ProjectExclusion resource Examples -------- ``` describe google_logging_project_exclusion(project: 'chef-gcp-inspec', name: 'inspec-project-exclusion') do it { should exist } its('description'){ should cmp 'My project exclusion description' } its('filter'){ should cmp 'resource.type = gce_instance AND severity <= DEBUG' } end describe google_logging_project_exclusion(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP project logging exclusion name is as expected ``` describe google_logging_project_exclusion(project: 'chef-inspec-gcp', exclusion: 'exclusion-name-abcd') do its('name') { should eq 'exclusion-name-abcd' } end ``` ### Test that a GCP project logging exclusion filter is set correctly ``` describe google_logging_project_exclusion(project: 'chef-inspec-gcp', exclusion: 'exclusion-name-abcd') do its('filter') { should eq 'resource.type = gce_instance AND severity <= DEBUG' } end ``` ### Test that a GCP project logging exclusion description is as expected ``` describe google_logging_project_exclusion(project: 'chef-inspec-gcp', exclusion: 'exclusion-name-abcd') do its('description') { should eq 'Exclude GCE instance debug logs' } end ``` Properties ---------- Properties that can be accessed from the `google_logging_project_exclusion` resource: `project` Id of the project that this exclusion applies to. `name` Name of the exclusion, specified by the server during create. `description` A user provided description of this exclusion. `filter` An advanced logs filter. The only exported log entries are those that are in the resource owning the sink and that match the filter. `disabled` If set to true then this exclusion is disabled and it does not exclude any log entries. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_logging_project_exclusion/google_logging_organization_log_sinks resource ================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_logging_organization_log_sinks.md) Syntax ------ A `google_logging_organization_log_sinks` is used to test a Google OrganizationLogSink resource Examples -------- ``` describe google_logging_organization_log_sinks(organization: '190694428152') do its('names') { should include 'inspec-gcp-org-sink' } end ``` Properties ---------- Properties that can be accessed from the `google_logging_organization_log_sinks` resource: See the [google_logging_organization_log_sink](../google_logging_organization_log_sink/index#properties) resource for more information. `organizations` an array of `google_logging_organization_log_sink` organization `names` an array of `google_logging_organization_log_sink` name `filters` an array of `google_logging_organization_log_sink` filter `destinations` an array of `google_logging_organization_log_sink` destination `writer_identities` an array of `google_logging_organization_log_sink` writer_identity `include_children` an array of `google_logging_organization_log_sink` include_children Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_logging_organization_log_sinks/google_logging_project_exclusions resource ============================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_logging_project_exclusions.md) Syntax ------ A `google_logging_project_exclusions` is used to test a Google ProjectExclusion resource Examples -------- ``` describe google_logging_project_exclusions(project: 'chef-gcp-inspec') do its('names'){ should include 'inspec-folder-exclusion' } end ``` Properties ---------- Properties that can be accessed from the `google_logging_project_exclusions` resource: See the [google_logging_project_exclusion](../google_logging_project_exclusion/index#properties) resource for more information. `projects` an array of `google_logging_project_exclusion` project `names` an array of `google_logging_project_exclusion` name `descriptions` an array of `google_logging_project_exclusion` description `filters` an array of `google_logging_project_exclusion` filter `disableds` an array of `google_logging_project_exclusion` disabled Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_logging_project_exclusions/google_logging_project_sink resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_logging_project_sink.md) Syntax ------ A `google_logging_project_sink` is used to test a Google ProjectSink resource Examples -------- ``` describe google_logging_project_sink(project: 'chef-gcp-inspec', name: 'inspec-gcp-org-sink') do it { should exist } its('filter') { should cmp 'resource.type = gce_instance AND severity = DEBUG' } end describe google_logging_project_sink(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP project logging sink destination is correct ``` describe google_logging_project_sink(project: 'chef-inspec-gcp', sink: 'sink-name-abcd') do its('destination') { should eq 'storage.googleapis.com/gcp-inspec-logging-bucket' } end ``` ### Test that a GCP project logging sink filter is correct ``` describe google_logging_project_sink(project: 'chef-inspec-gcp', sink: 'sink-name-abcd') do its('filter') { should eq "resource.type = gce_instance AND resource.labels.instance_id = \"12345678910123123\"" } end ``` ### Test a GCP project logging sink output version format ``` describe google_logging_project_sink(project: 'chef-inspec-gcp', sink: 'sink-name-abcd') do its('output_version_format') { should eq "V2" } end ``` ### Test a GCP project logging sink writer identity is as expected ``` describe google_logging_project_sink(project: 'chef-inspec-gcp', sink: 'sink-name-abcd') do its('writer_identity') { should eq "serviceAccount:my-logging-service-account.iam.gserviceaccount.com" } end ``` Properties ---------- Properties that can be accessed from the `google_logging_project_sink` resource: `project` Id of the project that this sink belongs to. `name` Name of the log sink. `filter` An advanced logs filter. The only exported log entries are those that are in the resource owning the sink and that match the filter. `destination` The export destination. `writer_identity` An IAM identity—a service account or group—under which Logging writes the exported log entries to the sink’s destination. This field is set by sinks.create and sinks.update based on the value of uniqueWriterIdentity in those methods. `include_children` If the field is false, the default, only the logs owned by the sink’s parent resource are available for export. If the field is true, then logs from all the projects, folders, and billing accounts contained in the sink’s parent resource are also available for export. Whether a particular log entry from the children is exported depends on the sink’s filter expression. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_logging_project_sink/google_logging_organization_log_sink resource ================================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_logging_organization_log_sink.md) Syntax ------ A `google_logging_organization_log_sink` is used to test a Google OrganizationLogSink resource Examples -------- ``` describe google_logging_organization_log_sink(organization: '190694428152', name: 'inspec-gcp-org-sink') do it { should exist } its('filter') { should cmp 'resource.type = gce_instance' } end describe google_logging_organization_log_sink(organization: '190694428152', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_logging_organization_log_sink` resource: `organization` Id of the organization that this sink belongs to. `name` Name of the log sink. `filter` An advanced logs filter. The only exported log entries are those that are in the resource owning the sink and that match the filter. `destination` The export destination. `writer_identity` An IAM identity—a service account or group—under which Logging writes the exported log entries to the sink’s destination. This field is set by sinks.create and sinks.update based on the value of uniqueWriterIdentity in those methods. `include_children` If the field is false, the default, only the logs owned by the sink’s parent resource are available for export. If the field is true, then logs from all the projects, folders, and billing accounts contained in the sink’s parent resource are also available for export. Whether a particular log entry from the children is exported depends on the sink’s filter expression. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_logging_organization_log_sink/google_ml_engine_model resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_ml_engine_model.md) Syntax ------ A `google_ml_engine_model` is used to test a Google Model resource Examples -------- ``` describe google_ml_engine_model(project: 'chef-gcp-inspec', name: 'ml_model') do it { should exist } its('description') { should cmp 'My awesome ML model' } its('regions') { should include 'us-central1' } its('online_prediction_logging') { should cmp 'true' } its('online_prediction_console_logging') { should cmp 'true' } end describe google_ml_engine_model(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_ml_engine_model` resource: `name` The name specified for the model. `description` The description specified for the model when it was created. `default_version` The default version of the model. This version will be used to handle prediction requests that do not specify a version. `name` The name specified for the version when it was created. `regions` The list of regions where the model is going to be deployed. Currently only one region per model is supported `online_prediction_logging` If true, online prediction access logs are sent to StackDriver Logging. `online_prediction_console_logging` If true, online prediction nodes send stderr and stdout streams to Stackdriver Logging `labels` One or more labels that you can add, to organize your models. GCP Permissions --------------- Ensure the [Cloud ML](https://console.cloud.google.com/apis/library/ml.googleapis.com) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_ml_engine_model/google_ml_engine_models resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_ml_engine_models.md) Syntax ------ A `google_ml_engine_models` is used to test a Google Model resource Examples -------- ``` describe google_ml_engine_models(project: 'chef-gcp-inspec') do its('descriptions') { should include 'My awesome ML model' } its('online_prediction_loggings') { should include 'true' } its('online_prediction_console_loggings') { should include 'true' } end ``` Properties ---------- Properties that can be accessed from the `google_ml_engine_models` resource: See the [google_ml_engine_model](../google_ml_engine_model/index#properties) resource for more information. `names` an array of `google_ml_engine_model` name `descriptions` an array of `google_ml_engine_model` description `default_versions` an array of `google_ml_engine_model` default_version `regions` an array of `google_ml_engine_model` regions `online_prediction_loggings` an array of `google_ml_engine_model` online_prediction_logging `online_prediction_console_loggings` an array of `google_ml_engine_model` online_prediction_console_logging `labels` an array of `google_ml_engine_model` labels Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud ML](https://console.cloud.google.com/apis/library/ml.googleapis.com) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_ml_engine_models/google_organization_iam_binding resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_organization_iam_binding.md) Syntax ------ A `google_organization_iam_binding` is used to test a Google Organization Iam Bindings Examples -------- ``` describe google_organization_iam_binding(name: "name", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` Properties ---------- Properties that can be accessed from the `google_organization_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_organization_iam_binding/google_logging_project_sinks resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_logging_project_sinks.md) Syntax ------ A `google_logging_project_sinks` is used to test a Google ProjectSink resource Examples -------- ``` describe google_logging_project_sinks(project: 'chef-gcp-inspec') do its('names') { should include 'inspec-gcp-org-sink' } end ``` ### Test that there are no more than a specified number of sinks available for the project ``` describe google_logging_project_sinks(project: 'chef-inspec-gcp') do its('count') { should be <= 100} end ``` ### Test that an expected sink name is available for the project ``` describe google_logging_project_sinks(project: 'chef-inspec-gcp') do its('sink_names') { should include "my-sink" } end ``` ### Test that an expected sink destination is available for the project ``` describe google_logging_project_sinks(project: 'chef-inspec-gcp') do its('sink_destinations') { should include "storage.googleapis.com/a-logging-bucket" } end ``` ### Test that a subset of all sinks matching “project*” have a particular writer identity ``` google_logging_project_sinks(project: 'chef-inspec-gcp').where(sink_name: /project/).sink_names.each do |sink_name| describe google_logging_project_sink(project: 'chef-inspec-gcp', sink: sink_name) do its('writer_identity') { should eq "serviceAccount:my-logging-service-account.iam.gserviceaccount.com" } end end ``` Properties ---------- Properties that can be accessed from the `google_logging_project_sinks` resource: See the [google_logging_project_sink](../google_logging_project_sink/index#properties) resource for more information. `projects` an array of `google_logging_project_sink` project `names` an array of `google_logging_project_sink` name `filters` an array of `google_logging_project_sink` filter `destinations` an array of `google_logging_project_sink` destination `writer_identities` an array of `google_logging_project_sink` writer_identity `include_children` an array of `google_logging_project_sink` include_children Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_logging_project_sinks/google_organization resource ============================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_organization.md) Syntax ------ A `google_organization` is used to test a Google Organization resource Examples -------- ``` describe google_organization(name: "organizations/123456") do its('name') { should eq "organizations/123456" } its('lifecycle_state') { should cmp 'ACTIVE' } end ``` ### Test that a GCP organization has the expected name ``` describe google_organization(name: 'organizations/1234') do its('name') { should eq 'organizations/1234' } end ``` ### Test that a GCP organization has the expected lifecycle state e.g. “ACTIVE” ``` describe google_organization(display_name: 'google.com') do its('lifecycle_state') { should eq "ACTIVE" } end ``` Properties ---------- Properties that can be accessed from the `google_organization` resource: `name` The resource name of the organization. This is the organization’s relative path in the API. Its format is “organizations/[organizationId]”. For example, “organizations/1234”. `display_name` A human-readable string that refers to the Organization in the GCP Console UI. This string is set by the server and cannot be changed. The string will be set to the primary domain (for example, “google.com”) of the G Suite customer that owns the organization. `lifecycle_state` The lifecycle state of the folder. Updates to the lifecycleState must be performed via folders.delete and folders.undelete. Possible values: * LIFECYCLE_STATE_UNSPECIFIED * ACTIVE * DELETE_REQUESTED `creation_time` Timestamp when the Organization was created. Assigned by the server. `owner` The entity that owns the Organization `directory_customer_id` The G Suite customer id used in the Directory API GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_organization/google_organizations resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_organizations.md) Syntax ------ A `google_organizations` is used to test a Google Organization resource Examples -------- ``` describe google_organizations do its('names') { should include "organizations/123456" } end ``` ### Test that there are no more than a specified number of organizations available ``` describe google_organizations do its('count') { should be <= 100} end ``` ### Test that an expected organization name is available ``` describe google_organizations do its('names') { should include "organization/1234" } end ``` ### Test that an expected organization display name is available ``` describe google_organizations do its('display_names') { should include "google.com" } end ``` ### Test that all organizations are ACTIVE ``` describe google_organizations do its('lifecycle_state'){ should eq 'ACTIVE' } end ``` ### Test that a particular subset of ACTIVE organizations with display name ‘goog*’ exist ``` google_organizations.where(display_name: /^goog/, lifecycle_state: 'ACTIVE').names.each do |name| describe google_organization(name: name) do it { should exist } end end ``` Properties ---------- Properties that can be accessed from the `google_organizations` resource: See the [google_organization](../google_organization/index#properties) resource for more information. `names` an array of `google_organization` name `display_names` an array of `google_organization` display_name `lifecycle_states` an array of `google_organization` lifecycle_state `creation_times` an array of `google_organization` creation_time `owners` an array of `google_organization` owner Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_organizations/google_project_alert_policies resource ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_alert_policies.md) Syntax ------ A `google_project_alert_policies` is used to test a Google AlertPolicy resource Examples -------- ``` describe google_project_alert_policies(project: 'chef-gcp-inspec') do it { should exist } its('policy_display_names') { should include 'Display'} its('combiners') { should include 'OR'} end ``` ### Test that there are no more than a specified number of project alert policies available for the project ``` describe google_project_alert_policies(project: 'chef-inspec-gcp') do its('count') { should be <= 100} end ``` ### Test that an expected policy name is available for the project ``` describe google_project_alert_policies(project: 'chef-inspec-gcp') do its('policy_names') { should include 'projects/spaterson-project/alertPolicies/9271751234503117449' } end ``` ### Test whether any expected policy display name is available for the project ``` describe google_project_alert_policies(project: 'chef-inspec-gcp') do its('policy_display_names') { should_not include 'banned policy' } end ``` ### Ensure no existing policies are inactive ``` describe google_project_alert_policies(project: 'chef-inspec-gcp') do its('policy_enabled_states') { should_not include false } end ``` Properties ---------- Properties that can be accessed from the `google_project_alert_policies` resource: See the [google_project_alert_policy](../google_project_alert_policy/index#properties) resource for more information. `policy_names` an array of `google_project_alert_policy` name `policy_display_names` an array of `google_project_alert_policy` display_name `combiners` an array of `google_project_alert_policy` combiner `creation_records` an array of `google_project_alert_policy` creation_record `policy_enabled_states` an array of `google_project_alert_policy` enabled `conditions` an array of `google_project_alert_policy` conditions `notification_channels` an array of `google_project_alert_policy` notification_channels `user_labels` an array of `google_project_alert_policy` user_labels `documentations` an array of `google_project_alert_policy` documentation Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Stackdriver Monitoring API](https://console.cloud.google.com/apis/library/monitoring.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_alert_policies/google_organization_iam_policy resource ========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_organization_iam_policy.md) Syntax ------ A `google_organization_iam_policy` is used to test a Google Organization Iam Policy resource Examples -------- ``` describe google_organization_iam_policy(name: "name") do it { should exist } end google_organization_iam_policy(name: "name").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` Properties ---------- Properties that can be accessed from the `google_organization_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_organization_iam_policy/google_organization_policy resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_organization_policy.md) Use the `google_organization_policy` InSpec audit resource to test constraints set on a GCP organization. Syntax ------ Google organization policies can restrict certain GCP services. For more information see <https://cloud.google.com/resource-manager/docs/organization-policy/understanding-constraints A `google_organization_policy` resource block declares the tests for a single GCP organization constraint identified by the pair of the `name` of the organization and the `constraint`: ``` describe google_organization_policy(name: 'organizations/123456', constraint: 'constraints/compute.disableGuestAttributesAccess') do it { should exist } its('boolean_policy.enforced') { should be true } end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Test that a GCP organization has a specific constraint enforced ``` describe google_organization_policy(name: 'organizations/123456', constraint: 'constraints/compute.disableGuestAttributesAccess') do it { should exist } its('boolean_policy.enforced') { should be true } end ``` ### Test that a GCP organization has certain values allowed for a list constraint ``` describe google_organization_policy(name: 'organizations/123456', constraint: 'constraints/someListConstraint') do it { should exist } its('list_policy.allowed_values') { should include 'included_val' } its('list_policy.allowed_values') { should_not include 'excluded' } its('list_policy.denied_values') { should include 'denied' } end ``` Properties ---------- `update_time` The time stamp this policy was last updated. `boolean_policy` Only available for constraints that are boolean policies. `enforced` Boolean for if this policy is enforced. `list_policy` Available for list policies. `allowed_values` List of values allowed at this resource. `denied_values` List of values denied at this resource. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_organization_policy/google_project resource ======================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project.md) Syntax ------ A `google_project` is used to test a Google Project resource Examples -------- ``` describe google_project(project: 'chef-gcp-inspec') do it { should exist } its('project_id') { should cmp 'chef-gcp-inspec' } its('lifecycle_state') { should cmp 'ACTIVE' } end ``` ### Test that a GCP project has the expected project number ``` describe google_project(project: 'chef-inspec-gcp') do its('project_number') { should eq 12345678 } end ``` ### Test that a GCP project has the expected lifecycle state e.g. “ACTIVE” ``` describe google_project(project: 'chef-inspec-gcp') do its('lifecycle_state') { should eq "ACTIVE" } end ``` ### Validate that a GCP project has some arbitrary label with expected content (for example defined by regexp ) ``` describe google_project(project: 'chef-inspec-gcp').label_value_by_key('season') do it {should match '^(winter|spring|summer|autumn)$' } end ``` Properties ---------- Properties that can be accessed from the `google_project` resource: `number` Number uniquely identifying the project. `lifecycle_state` The Project lifecycle state. Possible values: * LIFECYCLE_STATE_UNSPECIFIED * ACTIVE * DELETE_REQUESTED * DELETE_IN_PROGRESS `name` The user-assigned display name of the Project. It must be 4 to 30 characters. Allowed characters are: lowercase and uppercase letters, numbers, hyphen, single-quote, double-quote, space, and exclamation point. `create_time` Time of creation `labels` The labels associated with this Project. Label keys must be between 1 and 63 characters long and must conform to the following regular expression: `[a-z]([-a-z0-9]*[a-z0-9])?`. Label values must be between 0 and 63 characters long and must conform to the regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`. No more than 256 labels can be associated with a given resource. Clients should store labels in a representation such as JSON that does not depend on specific characters being disallowed `parent` A parent organization `type` Must be organization. `id` Id of the organization `project_id` The unique, user-assigned ID of the Project. It must be 6 to 30 lowercase letters, digits, or hyphens. It must start with a letter. Trailing hyphens are prohibited. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project/google_project_iam_binding resource ====================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_iam_binding.md) Syntax ------ A `google_project_iam_binding` is used to test a Google Project Iam Bindings Examples -------- ``` describe google_project_iam_binding(project: "project", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` This resource supports [IAM conditions](https://cloud.google.com/iam/docs/conditions-overview). Specifying a `condition` in the constructor matches only bindings with that condition. `condition` has three possible fields, `title`, `expression` and `description`. If any of these fields are unspecified they will not be matched. ``` describe google_project_iam_binding(project: "project", role: "roles/browser", condition: { title: "my title" }) do it { should exist } its('members.count'){ should cmp 1 } its('members') { should include 'user:<EMAIL>' } its('condition.title') {should cmp 'my title' } its('condition.expression') { should cmp "request.time < timestamp('2020-10-01T00:00:00.000Z')" } end ``` Properties ---------- Properties that can be accessed from the `google_project_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `condition` Contains information about when this binding is to be applied. `expression` Textual representation of an expression in Common Expression Language syntax. `title` An optional title for the expression, i.e. a short string describing its purpose. `description` An optional description of the expression. This is a longer text which describes the expression. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_iam_binding/google_project_alert_policy_condition resource ================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_alert_policy_condition.md) Use the `google_project_alert_policy_condition` InSpec audit resource to test properties of a single GCP project alert policy condition. Syntax ------ A `google_project_alert_policy_condition` resource block declares the tests for a single GCP project alert policy condition by name and filter. ``` describe google_project_alert_policy_condition(name: 'projects/spaterson-project/alertPolicies/9271751234503117449', filter 'project=\"spaterson-project\"') do it { should exist } end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Test that a GCP project alert policy condition has a particular threshold value ``` describe google_project_alert_policy_condition(name: 'projects/spaterson-project/alertPolicies/9271751234503117449', filter 'project=\"spaterson-project\"') do its('condition_threshold_value'){ should eq 0.001 } end ``` ### Test that a GCP project alert policy condition has a particular aggregation alignment period ``` describe google_project_alert_policy_condition(name: 'projects/spaterson-project/alertPolicies/9271751234503117449', filter 'project=\"spaterson-project\"') do its('aggregation_alignment_period'){ should eq '60s' } end ``` Properties ---------- * `condition_threshold_value`, `aggregation_alignment_period`, `aggregation_per_series_aligner`, `aggregation_cross_series_reducer` GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/api/logging.googleapis.com/) is enabled for the project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_alert_policy_condition/google_project_alert_policy resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_alert_policy.md) Syntax ------ A `google_project_alert_policy` is used to test a Google AlertPolicy resource Examples -------- ``` describe.one do google_project_alert_policies(project: 'chef-gcp-inspec').policy_names.each do |policy_name| describe google_project_alert_policy(project: 'chef-gcp-inspec', name: policy_name.split('/').last) do it { should exist } its('display_name') { should cmp 'Display'} its('combiner') { should cmp 'OR'} it { should be_enabled } end end end ``` ### Test that a GCP alert policy is enabled describe google_project_alert_policy(policy: ‘spaterson’, name: ‘9271751234503117449’) do it { should be_enabled } end ### Test that a GCP compute alert policy display name is correct describe google_project_alert_policy(policy: ‘spaterson-project’, name: ‘9271751234503117449’) do its(‘display_name’) { should eq ‘policy name’ } end Properties ---------- Properties that can be accessed from the `google_project_alert_policy` resource: `name` The unique resource name for this policy. Its syntax is: projects/[PROJECT_ID]/alertPolicies/[ALERT_POLICY_ID] `display_name` A short name or phrase used to identify the policy in dashboards, notifications, and incidents. To avoid confusion, don’t use the same display name for multiple policies in the same project. The name is limited to 512 Unicode characters. `combiner` How to combine the results of multiple conditions to determine if an incident should be opened. Possible values: * AND * OR * AND_WITH_MATCHING_RESOURCE `creation_record` A read-only record of the creation of the alerting policy. If provided in a call to create or update, this field will be ignored. `mutate_time` When the change occurred. `mutated_by` The email address of the user making the change. `enabled` Whether or not the policy is enabled. The default is true. `conditions` A list of conditions for the policy. The conditions are combined by AND or OR according to the combiner field. If the combined conditions evaluate to true, then an incident is created. A policy can have from one to six conditions. `condition_absent` A condition that checks that a time series continues to receive new data points. `aggregations` Specifies the alignment of data points in individual time series as well as how to combine the retrieved time series together (such as when aggregating multiple streams on each resource to a single stream for each resource or when aggregating streams across all members of a group of resources). Multiple aggregations are applied in the order specified. `per_series_aligner` The approach to be used to align individual time series. Not all alignment functions may be applied to all time series, depending on the metric type and value type of the original time series. Alignment may change the metric type or the value type of the time series.Time series data must be aligned in order to perform cross- time series reduction. If crossSeriesReducer is specified, then perSeriesAligner must be specified and not equal ALIGN_NONE and alignmentPeriod must be specified; otherwise, an error is returned. Possible values: * ALIGN_NONE * ALIGN_DELTA * ALIGN_RATE * ALIGN_INTERPOLATE * ALIGN_NEXT_OLDER * ALIGN_MIN * ALIGN_MAX * ALIGN_MEAN * ALIGN_COUNT * ALIGN_SUM * ALIGN_STDDEV * ALIGN_COUNT_TRUE * ALIGN_COUNT_FALSE * ALIGN_FRACTION_TRUE * ALIGN_PERCENTILE_99 * ALIGN_PERCENTILE_95 * ALIGN_PERCENTILE_50 * ALIGN_PERCENTILE_05 * ALIGN_PERCENT_CHANGE `group_by_fields` The set of fields to preserve when crossSeriesReducer is specified. The groupByFields determine how the time series are partitioned into subsets prior to applying the aggregation function. Each subset contains time series that have the same value for each of the grouping fields. Each individual time series is a member of exactly one subset. The crossSeriesReducer is applied to each subset of time series. It is not possible to reduce across different resource types, so this field implicitly contains resource.type. Fields not specified in groupByFields are aggregated away. If groupByFields is not specified and all the time series have the same resource type, then the time series are aggregated into a single output time series. If crossSeriesReducer is not defined, this field is ignored. `alignment_period` The alignment period for per-time series alignment. If present, alignmentPeriod must be at least 60 seconds. After per-time series alignment, each time series will contain data points only on the period boundaries. If perSeriesAligner is not specified or equals ALIGN_NONE, then this field is ignored. If perSeriesAligner is specified and does not equal ALIGN_NONE, then this field must be defined; otherwise an error is returned. `cross_series_reducer` The approach to be used to combine time series. Not all reducer functions may be applied to all time series, depending on the metric type and the value type of the original time series. Reduction may change the metric type of value type of the time series.Time series data must be aligned in order to perform cross- time series reduction. If crossSeriesReducer is specified, then perSeriesAligner must be specified and not equal ALIGN_NONE and alignmentPeriod must be specified; otherwise, an error is returned. Possible values: * REDUCE_NONE * REDUCE_MEAN * REDUCE_MIN * REDUCE_MAX * REDUCE_SUM * REDUCE_STDDEV * REDUCE_COUNT * REDUCE_COUNT_TRUE * REDUCE_COUNT_FALSE * REDUCE_FRACTION_TRUE * REDUCE_PERCENTILE_99 * REDUCE_PERCENTILE_95 * REDUCE_PERCENTILE_50 * REDUCE_PERCENTILE_05 `trigger` The number/percent of time series for which the comparison must hold in order for the condition to trigger. If unspecified, then the condition will trigger if the comparison is true for any of the time series that have been identified by filter and aggregations. `percent` The percentage of time series that must fail the predicate for the condition to be triggered. `count` The absolute number of time series that must fail the predicate for the condition to be triggered. `duration` The amount of time that a time series must fail to report new data to be considered failing. Currently, only values that are a multiple of a minute–e.g. 60s, 120s, or 300s –are supported. `filter` A filter that identifies which time series should be compared with the threshold.The filter is similar to the one that is specified in the MetricService.ListTimeSeries request (that call is useful to verify the time series that will be retrieved / processed) and must specify the metric type and optionally may contain restrictions on resource type, resource labels, and metric labels. This field may not exceed 2048 Unicode characters in length. `name` The unique resource name for this condition. Its syntax is: projects/[PROJECT_ID]/alertPolicies/[POLICY_ID]/conditions/[CONDITION_ID] [CONDITION_ID] is assigned by Stackdriver Monitoring when the condition is created as part of a new or updated alerting policy. `condition_threshold` A condition that compares a time series against a threshold. `threshold_value` A value against which to compare the time series. `denominator_filter` A filter that identifies a time series that should be used as the denominator of a ratio that will be compared with the threshold. If a denominator_filter is specified, the time series specified by the filter field will be used as the numerator.The filter is similar to the one that is specified in the MetricService.ListTimeSeries request (that call is useful to verify the time series that will be retrieved / processed) and must specify the metric type and optionally may contain restrictions on resource type, resource labels, and metric labels. This field may not exceed 2048 Unicode characters in length. `denominator_aggregations` Specifies the alignment of data points in individual time series selected by denominatorFilter as well as how to combine the retrieved time series together (such as when aggregating multiple streams on each resource to a single stream for each resource or when aggregating streams across all members of a group of resources).When computing ratios, the aggregations and denominator_aggregations fields must use the same alignment period and produce time series that have the same periodicity and labels.This field is similar to the one in the MetricService.ListTimeSeries request. It is advisable to use the ListTimeSeries method when debugging this field. `per_series_aligner` The approach to be used to align individual time series. Not all alignment functions may be applied to all time series, depending on the metric type and value type of the original time series. Alignment may change the metric type or the value type of the time series.Time series data must be aligned in order to perform cross- time series reduction. If crossSeriesReducer is specified, then perSeriesAligner must be specified and not equal ALIGN_NONE and alignmentPeriod must be specified; otherwise, an error is returned. Possible values: * ALIGN_NONE * ALIGN_DELTA * ALIGN_RATE * ALIGN_INTERPOLATE * ALIGN_NEXT_OLDER * ALIGN_MIN * ALIGN_MAX * ALIGN_MEAN * ALIGN_COUNT * ALIGN_SUM * ALIGN_STDDEV * ALIGN_COUNT_TRUE * ALIGN_COUNT_FALSE * ALIGN_FRACTION_TRUE * ALIGN_PERCENTILE_99 * ALIGN_PERCENTILE_95 * ALIGN_PERCENTILE_50 * ALIGN_PERCENTILE_05 * ALIGN_PERCENT_CHANGE `group_by_fields` The set of fields to preserve when crossSeriesReducer is specified. The groupByFields determine how the time series are partitioned into subsets prior to applying the aggregation function. Each subset contains time series that have the same value for each of the grouping fields. Each individual time series is a member of exactly one subset. The crossSeriesReducer is applied to each subset of time series. It is not possible to reduce across different resource types, so this field implicitly contains resource.type. Fields not specified in groupByFields are aggregated away. If groupByFields is not specified and all the time series have the same resource type, then the time series are aggregated into a single output time series. If crossSeriesReducer is not defined, this field is ignored. `alignment_period` The alignment period for per-time series alignment. If present, alignmentPeriod must be at least 60 seconds. After per-time series alignment, each time series will contain data points only on the period boundaries. If perSeriesAligner is not specified or equals ALIGN_NONE, then this field is ignored. If perSeriesAligner is specified and does not equal ALIGN_NONE, then this field must be defined; otherwise an error is returned. `cross_series_reducer` The approach to be used to combine time series. Not all reducer functions may be applied to all time series, depending on the metric type and the value type of the original time series. Reduction may change the metric type of value type of the time series.Time series data must be aligned in order to perform cross- time series reduction. If crossSeriesReducer is specified, then perSeriesAligner must be specified and not equal ALIGN_NONE and alignmentPeriod must be specified; otherwise, an error is returned. Possible values: * REDUCE_NONE * REDUCE_MEAN * REDUCE_MIN * REDUCE_MAX * REDUCE_SUM * REDUCE_STDDEV * REDUCE_COUNT * REDUCE_COUNT_TRUE * REDUCE_COUNT_FALSE * REDUCE_FRACTION_TRUE * REDUCE_PERCENTILE_99 * REDUCE_PERCENTILE_95 * REDUCE_PERCENTILE_50 * REDUCE_PERCENTILE_05 `duration` The amount of time that a time series must violate the threshold to be considered failing. Currently, only values that are a multiple of a minute–e.g., 0, 60, 120, or 300 seconds–are supported. If an invalid value is given, an error will be returned. When choosing a duration, it is useful to keep in mind the frequency of the underlying time series data (which may also be affected by any alignments specified in the aggregations field); a good duration is long enough so that a single outlier does not generate spurious alerts, but short enough that unhealthy states are detected and alerted on quickly. `comparison` The comparison to apply between the time series (indicated by filter and aggregation) and the threshold (indicated by threshold_value). The comparison is applied on each time series, with the time series on the left-hand side and the threshold on the right-hand side. Only COMPARISON_LT and COMPARISON_GT are supported currently. Possible values: * COMPARISON_GT * COMPARISON_GE * COMPARISON_LT * COMPARISON_LE * COMPARISON_EQ * COMPARISON_NE `trigger` The number/percent of time series for which the comparison must hold in order for the condition to trigger. If unspecified, then the condition will trigger if the comparison is true for any of the time series that have been identified by filter and aggregations, or by the ratio, if denominator_filter and denominator_aggregations are specified. `percent` The percentage of time series that must fail the predicate for the condition to be triggered. `count` The absolute number of time series that must fail the predicate for the condition to be triggered. `aggregations` Specifies the alignment of data points in individual time series as well as how to combine the retrieved time series together (such as when aggregating multiple streams on each resource to a single stream for each resource or when aggregating streams across all members of a group of resources). Multiple aggregations are applied in the order specified.This field is similar to the one in the MetricService.ListTimeSeries request. It is advisable to use the ListTimeSeries method when debugging this field. `per_series_aligner` The approach to be used to align individual time series. Not all alignment functions may be applied to all time series, depending on the metric type and value type of the original time series. Alignment may change the metric type or the value type of the time series.Time series data must be aligned in order to perform cross- time series reduction. If crossSeriesReducer is specified, then perSeriesAligner must be specified and not equal ALIGN_NONE and alignmentPeriod must be specified; otherwise, an error is returned. Possible values: * ALIGN_NONE * ALIGN_DELTA * ALIGN_RATE * ALIGN_INTERPOLATE * ALIGN_NEXT_OLDER * ALIGN_MIN * ALIGN_MAX * ALIGN_MEAN * ALIGN_COUNT * ALIGN_SUM * ALIGN_STDDEV * ALIGN_COUNT_TRUE * ALIGN_COUNT_FALSE * ALIGN_FRACTION_TRUE * ALIGN_PERCENTILE_99 * ALIGN_PERCENTILE_95 * ALIGN_PERCENTILE_50 * ALIGN_PERCENTILE_05 * ALIGN_PERCENT_CHANGE `group_by_fields` The set of fields to preserve when crossSeriesReducer is specified. The groupByFields determine how the time series are partitioned into subsets prior to applying the aggregation function. Each subset contains time series that have the same value for each of the grouping fields. Each individual time series is a member of exactly one subset. The crossSeriesReducer is applied to each subset of time series. It is not possible to reduce across different resource types, so this field implicitly contains resource.type. Fields not specified in groupByFields are aggregated away. If groupByFields is not specified and all the time series have the same resource type, then the time series are aggregated into a single output time series. If crossSeriesReducer is not defined, this field is ignored. `alignment_period` The alignment period for per-time series alignment. If present, alignmentPeriod must be at least 60 seconds. After per-time series alignment, each time series will contain data points only on the period boundaries. If perSeriesAligner is not specified or equals ALIGN_NONE, then this field is ignored. If perSeriesAligner is specified and does not equal ALIGN_NONE, then this field must be defined; otherwise an error is returned. `cross_series_reducer` The approach to be used to combine time series. Not all reducer functions may be applied to all time series, depending on the metric type and the value type of the original time series. Reduction may change the metric type of value type of the time series.Time series data must be aligned in order to perform cross- time series reduction. If crossSeriesReducer is specified, then perSeriesAligner must be specified and not equal ALIGN_NONE and alignmentPeriod must be specified; otherwise, an error is returned. Possible values: * REDUCE_NONE * REDUCE_MEAN * REDUCE_MIN * REDUCE_MAX * REDUCE_SUM * REDUCE_STDDEV * REDUCE_COUNT * REDUCE_COUNT_TRUE * REDUCE_COUNT_FALSE * REDUCE_FRACTION_TRUE * REDUCE_PERCENTILE_99 * REDUCE_PERCENTILE_95 * REDUCE_PERCENTILE_50 * REDUCE_PERCENTILE_05 `filter` A filter that identifies which time series should be compared with the threshold.The filter is similar to the one that is specified in the MetricService.ListTimeSeries request (that call is useful to verify the time series that will be retrieved / processed) and must specify the metric type and optionally may contain restrictions on resource type, resource labels, and metric labels. This field may not exceed 2048 Unicode characters in length. `display_name` A short name or phrase used to identify the condition in dashboards, notifications, and incidents. To avoid confusion, don’t use the same display name for multiple conditions in the same policy. `notification_channels` Identifies the notification channels to which notifications should be sent when incidents are opened or closed or when new violations occur on an already opened incident. Each element of this array corresponds to the name field in each of the NotificationChannel objects that are returned from the notificationChannels.list method. The syntax of the entries in this field is `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]` `user_labels` This field is intended to be used for organizing and identifying the AlertPolicy objects.The field can contain up to 64 entries. Each key and value is limited to 63 Unicode characters or 128 bytes, whichever is smaller. Labels and values can contain only lowercase letters, numerals, underscores, and dashes. Keys must begin with a letter. `documentation` A short name or phrase used to identify the policy in dashboards, notifications, and incidents. To avoid confusion, don’t use the same display name for multiple policies in the same project. The name is limited to 512 Unicode characters. `content` The text of the documentation, interpreted according to mimeType. The content may not exceed 8,192 Unicode characters and may not exceed more than 10,240 bytes when encoded in UTF-8 format, whichever is smaller. `mime_type` The format of the content field. Presently, only the value “text/markdown” is supported. GCP Permissions --------------- Ensure the [Stackdriver Monitoring API](https://console.cloud.google.com/apis/library/monitoring.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_alert_policy/google_project_iam_bindings resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_iam_bindings.md) **This resource is deprecated. Please use `google_project_iam_policy` instead** Use the `google_project_iam_bindings` InSpec audit resource to test properties of all, or a filtered group of, GCP project IAM bindings. Syntax ------ A `google_project_iam_bindings` resource block collects GCP project IAM bindings then tests that group. ``` describe google_project_iam_bindings(project: 'chef-inspec-gcp') do it { should exist } end ``` Use this InSpec resource to enumerate roles then test in-depth using `google_project_iam_binding`. ``` google_project_iam_bindings(project: 'chef-inspec-gcp').iam_binding_roles.each do |iam_binding_role| describe google_project_iam_binding(project: 'chef-inspec-gcp', role: iam_binding_role) do it { should exist } its('members') {should include 'user:<EMAIL>' } end end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Test that there are no more than a specified number of IAM bindings roles available for the project ``` describe google_project_iam_bindings(project: 'chef-inspec-gcp') do its('count') { should be <= 100} end ``` ### Test that an expected role is available for the project ``` describe google_project_iam_bindings(project: 'chef-inspec-gcp') do its('iam_binding_roles') { should include "roles/storage.admin" } end ``` ### Test that a particular role does not exist using filtering of the plural resource ``` describe google_project_iam_bindings(project: 'chef-inspec-gcp').where(iam_binding_role: "roles/iam.securityReviewer") do it { should_not exist } end ``` Filter Criteria --------------- This resource supports the following filter criteria: `iam_binding_role`. This may be used with `where`, as a block or as a method. Properties ---------- * `iam_binding_roles` - an array of google_project_iam_binding role strings e.g. `["roles/compute.admin", "roles/owner"]` GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_iam_bindings/google_project_iam_custom_roles resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_iam_custom_roles.md) Syntax ------ A `google_project_iam_custom_roles` is used to test a Google CustomRole resource Examples -------- ``` describe google_project_iam_custom_roles(project: 'chef-gcp-inspec') do its('names') { should include "projects/project-id/roles/role-id" } end ``` Properties ---------- Properties that can be accessed from the `google_project_iam_custom_roles` resource: See the [google_project_iam_custom_role](../google_project_iam_custom_role/index#properties) resource for more information. `names` an array of `google_project_iam_custom_role` name `titles` an array of `google_project_iam_custom_role` title `descriptions` an array of `google_project_iam_custom_role` description `included_permissions` an array of `google_project_iam_custom_role` included_permissions `stages` an array of `google_project_iam_custom_role` stage `deleteds` an array of `google_project_iam_custom_role` deleted Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_iam_custom_roles/google_project_services resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_services.md) Syntax ------ A `google_project_services` is used to test a Google Service resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe.one do google_project_services(project: 'chef-gcp-inspec').names.each do |name| describe name do it { should match 'maps-android-backend.googleapis.com' } end end end ``` Properties ---------- Properties that can be accessed from the `google_project_services` resource: See the [google_project_service](../google_project_service/index#properties) resource for more information. `names` an array of `google_project_service` name `parents` an array of `google_project_service` parent `states` an array of `google_project_service` state `disable_dependent_services` an array of `google_project_service` disable_dependent_services `configs` an array of `google_project_service` config Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Service Usage API](https://console.cloud.google.com/apis/library/serviceusage.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_services/google_project_iam_custom_role resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_iam_custom_role.md) Syntax ------ A `google_project_iam_custom_role` is used to test a Google CustomRole resource Examples -------- ``` describe google_project_iam_custom_role(project: 'chef-gcp-inspec', name: 'admin-role') do it { should exist } its('stage') { should eq 'GA' } its('included_permissions') { should eq ["iam.roles.list"] } end describe google_project_iam_custom_role(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP project IAM custom role has the expected stage in the launch lifecycle ``` describe google_project_iam_custom_role(project: 'chef-inspec-gcp', name: 'chef-inspec-gcp-role-abcd') do its('stage') { should eq "GA" } end ``` ### Test that a GCP project IAM custom role has the expected included permissions ``` describe google_project_iam_custom_role(project: 'chef-inspec-gcp', name: 'chef-inspec-gcp-role-abcd') do its('included_permissions') { should eq ["iam.roles.list"] } end ``` Properties ---------- Properties that can be accessed from the `google_project_iam_custom_role` resource: `name` The name of the role. `title` A human-readable title for the role. Typically this is limited to 100 UTF-8 bytes. `description` Human-readable description for the role `included_permissions` Names of permissions this role grants when bound in an IAM policy. `stage` The current launch stage of the role. Possible values: * ALPHA * BETA * GA * DEPRECATED * DISABLED * EAP `deleted` The current deleted state of the role GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_iam_custom_role/google_project_service resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_service.md) Syntax ------ A `google_project_service` is used to test a Google Service resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_project_service(project: 'chef-gcp-inspec', name: 'maps-android-backend.googleapis.com') do it { should exist } its('state') { should cmp "ENABLED" } end ``` Properties ---------- Properties that can be accessed from the `google_project_service` resource: `name` The resource name of the service `parent` The name of the parent of this service. For example ‘projects/123’ `state` Whether or not the service has been enabled for use by the consumer. Possible values: * STATE_UNSPECIFIED * DISABLED * ENABLED `disable_dependent_services` Indicates if dependent services should also be disabled. Can only be turned on if service is disabled. `config` The service configuration of the available service. `name` The DNS address at which this service is available. `title` The product title for this service `apis` The list of API interfaces exported by this service. `name` Name of the API `version` The version of the API GCP Permissions --------------- Ensure the [Service Usage API](https://console.cloud.google.com/apis/library/serviceusage.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_service/google_project_metric resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_metric.md) Syntax ------ A `google_project_metric` is used to test a Google Metric resource Examples -------- ``` describe google_project_metric(project: 'chef-gcp-inspec', name: 'some/metric') do it { should exist } its('filter') { should cmp 'resource.type=gae_app AND severity>=ERROR' } its('metric_descriptor.metric_kind') { should cmp 'DELTA' } its('metric_descriptor.value_type') { should cmp 'INT64' } end describe google_project_metric(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` ### Test that a GCP project metric exists ``` describe google_project_metric(project: 'chef-inspec-gcp', metric: 'metric_name') do it { should exist } end ``` ### Test that a GCP compute zone has an expected CPU platform ``` describe google_project_metric(project: 'chef-inspec-gcp', metric: 'metric_name') do its('filter') { should eq "(protoPayload.serviceName=\"cloudresourcemanager.googleapis.com\")" } end ``` Properties ---------- Properties that can be accessed from the `google_project_metric` resource: `name` The client-assigned metric identifier. Examples - “error*count”, “nginx/requests”. Metric identifiers are limited to 100 characters and can include only the following characters A-Z, a-z, 0-9, and the special characters *-.,+!*',()%/. The forward-slash character (/) denotes a hierarchy of name pieces, and it cannot be the first character of the name. `description` A description of this metric, which is used in documentation. The maximum length of the description is 8000 characters. `filter` An advanced logs filter (<https://cloud.google.com/logging/docs/view/advanced-filters>) which is used to match log entries. `metric_descriptor` The metric descriptor associated with the logs-based metric. `unit` The unit in which the metric value is reported. It is only applicable if the valueType is `INT64`, `DOUBLE`, or `DISTRIBUTION`. The supported units are a subset of [The Unified Code for Units of Measure](http://unitsofmeasure.org/ucum.html) standard `value_type` Whether the measurement is an integer, a floating-point number, etc. Some combinations of metricKind and valueType might not be supported. For counter metrics, set this to INT64. Possible values: * BOOL * INT64 * DOUBLE * STRING * DISTRIBUTION * MONEY `metric_kind` Whether the metric records instantaneous values, changes to a value, etc. Some combinations of metricKind and valueType might not be supported. For counter metrics, set this to DELTA. Possible values: * DELTA * GAUGE * CUMULATIVE `labels` The set of labels that can be used to describe a specific instance of this metric type. For example, the appengine.googleapis.com/http/server/response_latencies metric type has a label for the HTTP response code, response_code, so you can look at latencies for successful responses or just for responses that failed. `key` The label key. `description` A human-readable description for the label. `value_type` The type of data that can be assigned to the label. Possible values: * BOOL * INT64 * STRING `display_name` A concise name for the metric, which can be displayed in user interfaces. Use sentence case without an ending period, for example “Request count”. This field is optional but it is recommended to be set for any metrics associated with user-visible concepts, such as Quota. `type` The metric type, including its DNS name prefix. The type is not URL-encoded. All user-defined metric types have the DNS name `custom.googleapis.com` or `external.googleapis.com`. `label_extractors` A map from a label key string to an extractor expression which is used to extract data from a log entry field and assign as the label value. Each label key specified in the LabelDescriptor must have an associated extractor expression in this map. The syntax of the extractor expression is the same as for the valueExtractor field. `value_extractor` A valueExtractor is required when using a distribution logs-based metric to extract the values to record from a log entry. Two functions are supported for value extraction - EXTRACT(field) or REGEXP_EXTRACT(field, regex). The argument are 1. field - The name of the log entry field from which the value is to be extracted. 2. regex - A regular expression using the Google RE2 syntax (<https://github.com/google/re2/wiki/Syntax>) with a single capture group to extract data from the specified log entry field. The value of the field is converted to a string before applying the regex. It is an error to specify a regex that does not include exactly one capture group. `bucket_options` The bucketOptions are required when the logs-based metric is using a DISTRIBUTION value type and it describes the bucket boundaries used to create a histogram of the extracted values. `linear_buckets` Specifies a linear sequence of buckets that all have the same width (except overflow and underflow). Each bucket represents a constant absolute uncertainty on the specific value in the bucket. `num_finite_buckets` Must be greater than 0. `width` Must be greater than 0. `offset` Lower bound of the first bucket. `exponential_buckets` Specifies an exponential sequence of buckets that have a width that is proportional to the value of the lower bound. Each bucket represents a constant relative uncertainty on a specific value in the bucket. `num_finite_buckets` Must be greater than 0. `growth_factor` Must be greater than 1. `scale` Must be greater than 0. `explicit_buckets` Specifies a set of buckets with arbitrary widths. `bounds` The values must be monotonically increasing. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_metric/google_project_metrics resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_metrics.md) Syntax ------ A `google_project_metrics` is used to test a Google Metric resource Examples -------- ``` describe google_project_metrics(project: 'chef-gcp-inspec') do it { should exist } its('metric_filters') { should include 'resource.type=gae_app AND severity>=ERROR' } its('metric_names') { should include 'some/metric' } end describe.one do google_project_metrics(project: 'chef-gcp-inspec').metric_types.each do |metric_type| describe metric_type do it { should match 'some/metric' } end end end ``` ### Test that there are no more than a specified number of metrics available for the project ``` describe google_project_metrics(project: 'chef-inspec-gcp') do its('count') { should be <= 100} end ``` ### Test that an expected metric name is available for the project ``` describe google_project_metrics(project: 'chef-inspec-gcp') do its('metric_names') { should include "metric-name" } end ``` ### Test that a subset of all metrics with name matching “*project*” have a particular writer identity ``` google_project_metrics(project: 'chef-inspec-gcp').where(metric_name: /project/).metric_names.each do |metric_name| describe google_project_metric(project: 'chef-inspec-gcp', metric: metric_name) do its('filter') { should eq "(protoPayload.serviceName=\"cloudresourcemanager.googleapis.com\")" } end end ``` Properties ---------- Properties that can be accessed from the `google_project_metrics` resource: See the [google_project_metric](../google_project_metric/index#properties) resource for more information. `metric_names` an array of `google_project_metric` name `descriptions` an array of `google_project_metric` description `metric_filters` an array of `google_project_metric` filter `metric_descriptors` an array of `google_project_metric` metric_descriptor `label_extractors` an array of `google_project_metric` label_extractors `value_extractors` an array of `google_project_metric` value_extractor `bucket_options` an array of `google_project_metric` bucket_options Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Stackdriver Logging API](https://console.cloud.google.com/apis/library/logging.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_metrics/google_project_logging_audit_config resource ================================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_logging_audit_config.md) Use the `google_compute_zone` InSpec audit resource to test properties of a single GCP compute zone. Syntax ------ A `google_project_logging_audit_config` resource block declares the tests for a single GCP zone by project and name. ``` describe google_project_logging_audit_config(project: 'chef-inspec-gcp') do it { should exist } end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Test that a GCP project logging audit configuration has a default type defined ``` describe google_project_logging_audit_config(project: 'chef-inspec-gcp') do its('default_types') { should include 'ADMIN_READ' } end ``` ### Test that a GCP project logging audit configuration has default exempted members ``` describe google_compute_zone(project: 'chef-inspec-gcp', zone: 'us-east1-b') do it { should_not have_default_exempted_members } end ``` Properties ---------- * `default_types`, `default_exempted_members` GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_logging_audit_config/google_projects resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_projects.md) Syntax ------ A `google_projects` is used to test a Google Project resource Examples -------- ``` describe google_projects() do its('count') { should be >= 1 } its('project_ids') { should include 'chef-gcp-inspec' } its('lifecycle_states') { should include 'ACTIVE' } end ``` ### Test that there are no more than a specified number of projects available for the project ``` describe google_projects do its('count') { should be <= 100} end ``` ### Test that an expected named project is available ``` describe google_projects do its('project_names'){ should include "GCP Project Name" } end ``` ### Test that an expected project identifier is available ``` describe google_projects do its('project_ids'){ should include "gcp_project_id" } end ``` ### Test that an expected project number is available ``` describe google_projects do its('project_numbers'){ should include 1122334455 } end ``` ### Test that a particular subset of projects with id ‘prod*’ are in ACTIVE lifecycle state ``` google_projects.where(project_id: /^prod/).project_ids.each do |gcp_project_id| describe google_project(project: gcp_project_id) do it { should exist } its('lifecycle_state') { should eq "ACTIVE" } end end ``` ### Test that a particular subset of ACTIVE projects with id ‘prod*’ exist ``` google_projects.where(project_id: /^prod/, lifecycle_state: 'ACTIVE').project_ids.each do |gcp_project_id| describe google_project(project: gcp_project_id) do it { should exist } end end ``` Properties ---------- Properties that can be accessed from the `google_projects` resource: See the [google_project](../google_project/index#properties) resource for more information. `project_numbers` an array of `google_project` number `lifecycle_states` an array of `google_project` lifecycle_state `project_names` an array of `google_project` name `create_times` an array of `google_project` create_time `labels` an array of `google_project` labels `parents` an array of `google_project` parent `project_ids` an array of `google_project` project_id Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_projects/google_project_iam_policy resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_project_iam_policy.md) Syntax ------ A `google_project_iam_policy` is used to test a Google Project Iam Policy resource Examples -------- ``` describe google_project_iam_policy(project: "project") do it { should exist } end google_project_iam_policy(project: "project").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` This resource supports [IAM conditions](https://cloud.google.com/iam/docs/conditions-overview). Properties ---------- Properties that can be accessed from the `google_project_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `condition` Contains information about when this binding is to be applied. `expression` Textual representation of an expression in Common Expression Language syntax. `title` An optional title for the expression, i.e. a short string describing its purpose. `description` An optional description of the expression. This is a longer text which describes the expression. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_project_iam_policy/google_pubsub_subscription_iam_binding resource =================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_pubsub_subscription_iam_binding.md) Syntax ------ A `google_pubsub_subscription_iam_binding` is used to test a Google Subscription Iam Bindings Examples -------- ``` describe google_pubsub_subscription_iam_binding(project: "project", name: "name", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` Properties ---------- Properties that can be accessed from the `google_pubsub_subscription_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. GCP Permissions --------------- Ensure the [Cloud Pub/Sub API](https://console.cloud.google.com/apis/library/pubsub.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_pubsub_subscription_iam_binding/google_pubsub_subscription resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_pubsub_subscription.md) Syntax ------ A `google_pubsub_subscription` is used to test a Google Subscription resource Examples -------- ``` describe google_pubsub_subscription(project: 'chef-gcp-inspec', name: 'inspec-gcp-subscription') do it { should exist } end describe google_pubsub_subscription(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_pubsub_subscription` resource: `name` Name of the subscription. `topic` A reference to a Topic resource. `labels` A set of key/value label pairs to assign to this Subscription. `push_config` If push delivery is used with this subscription, this field is used to configure it. An empty pushConfig signifies that the subscriber will pull and ack messages using API methods. `oidc_token` If specified, Pub/Sub will generate and attach an OIDC JWT token as an Authorization header in the HTTP request for every pushed message. `service_account_email` Service account email to be used for generating the OIDC token. The caller (for subscriptions.create, subscriptions.patch, and subscriptions.modifyPushConfig RPCs) must have the iam.serviceAccounts.actAs permission for the service account. `audience` Audience to be used when generating OIDC token. The audience claim identifies the recipients that the JWT is intended for. The audience value is a single case-sensitive string. Having multiple values (array) for the audience field is not supported. More info about the OIDC JWT token audience here: <https://tools.ietf.org/html/rfc7519#section-4.1.3> Note: if not specified, the Push endpoint URL will be used. `push_endpoint` A URL locating the endpoint to which messages should be pushed. For example, a Webhook endpoint might use “[https://example.com/push"](https://example.com/push%22). `attributes` Endpoint configuration attributes. Every endpoint has a set of API supported attributes that can be used to control different aspects of the message delivery. The currently supported attribute is x-goog-version, which you can use to change the format of the pushed message. This attribute indicates the version of the data expected by the endpoint. This controls the shape of the pushed message (i.e., its fields and metadata). The endpoint version is based on the version of the Pub/Sub API. If not present during the subscriptions.create call, it will default to the version of the API used to make such call. If not present during a subscriptions.modifyPushConfig call, its value will not be changed. subscriptions.get calls will always return a valid version, even if the subscription was created without this attribute. The possible values for this attribute are: - v1beta1: uses the push format defined in the v1beta1 Pub/Sub API. - v1 or v1beta2: uses the push format defined in the v1 Pub/Sub API. `ack_deadline_seconds` This value is the maximum time after a subscriber receives a message before the subscriber should acknowledge the message. After message delivery but before the ack deadline expires and before the message is acknowledged, it is an outstanding message and will not be delivered again during that time (on a best-effort basis). For pull subscriptions, this value is used as the initial value for the ack deadline. To override this value for a given message, call subscriptions.modifyAckDeadline with the corresponding ackId if using pull. The minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds (10 minutes). If this parameter is 0, a default value of 10 seconds is used. For push delivery, this value is also used to set the request timeout for the call to the push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message. `message_retention_duration` How long to retain unacknowledged messages in the subscription’s backlog, from the moment a message is published. If retainAckedMessages is true, then this also configures the retention of acknowledged messages, and thus configures how far back in time a subscriptions.seek can be done. Defaults to 7 days. Cannot be more than 7 days (`"604800s"`) or less than 10 minutes (`"600s"`). A duration in seconds with up to nine fractional digits, terminated by ’s'. Example: `"600.5s"`. `retain_acked_messages` Indicates whether to retain acknowledged messages. If `true`, then messages are not expunged from the subscription’s backlog, even if they are acknowledged, until they fall out of the messageRetentionDuration window. `expiration_policy` A policy that specifies the conditions for this subscription’s expiration. A subscription is considered active as long as any connected subscriber is successfully consuming messages from the subscription or is issuing operations on the subscription. If expirationPolicy is not set, a default policy with ttl of 31 days will be used. If it is set but ttl is “”, the resource never expires. The minimum allowed value for expirationPolicy.ttl is 1 day. `ttl` Specifies the “time-to-live” duration for an associated resource. The resource expires if it is not active for a period of ttl. If ttl is not set, the associated resource never expires. A duration in seconds with up to nine fractional digits, terminated by ’s'. Example - “3.5s”. `dead_letter_policy` A policy that specifies the conditions for dead lettering messages in this subscription. If dead_letter_policy is not set, dead lettering is disabled. The Cloud Pub/Sub service account associated with this subscriptions’s parent project (i.e., [<EMAIL>](mailto:service-%7Bproject_<EMAIL>)) must have permission to Acknowledge() messages on this subscription. `dead_letter_topic` The name of the topic to which dead letter messages should be published. Format is `projects/{project}/topics/{topic}`. The Cloud Pub/Sub service\naccount associated with the enclosing subscription’s parent project (i.e., [<EMAIL>](mailto:<EMAIL>)) must have permission to Publish() to this topic. The operation will fail if the topic does not exist. Users should ensure that there is a subscription attached to this topic since messages published to a topic with no subscriptions are lost. `max_delivery_attempts` The maximum number of delivery attempts for any message. The value must be between 5 and 100. The number of delivery attempts is defined as 1 + (the sum of number of NACKs and number of times the acknowledgement deadline has been exceeded for the message). A NACK is any call to ModifyAckDeadline with a 0 deadline. Note that client libraries may automatically extend ack_deadlines. This field will be honored on a best effort basis. If this parameter is 0, a default value of 5 is used. GCP Permissions --------------- Ensure the [Cloud Pub/Sub API](https://console.cloud.google.com/apis/library/pubsub.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_pubsub_subscription/google_pubsub_subscriptions resource ====================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_pubsub_subscriptions.md) Syntax ------ A `google_pubsub_subscriptions` is used to test a Google Subscription resource Examples -------- ``` describe google_pubsub_subscriptions(project: 'chef-gcp-inspec') do its('count') { should be >= 1 } end google_pubsub_subscriptions(project: 'chef-gcp-inspec').names.each do |subscription_name| describe google_pubsub_subscription(project: 'chef-gcp-inspec', name: subscription_name) do it { should exist } end end ``` Properties ---------- Properties that can be accessed from the `google_pubsub_subscriptions` resource: See the [google_pubsub_subscription](../google_pubsub_subscription/index#properties) resource for more information. `names` an array of `google_pubsub_subscription` name `topics` an array of `google_pubsub_subscription` topic `labels` an array of `google_pubsub_subscription` labels `push_configs` an array of `google_pubsub_subscription` push_config `ack_deadline_seconds` an array of `google_pubsub_subscription` ack_deadline_seconds `message_retention_durations` an array of `google_pubsub_subscription` message_retention_duration `retain_acked_messages` an array of `google_pubsub_subscription` retain_acked_messages `expiration_policies` an array of `google_pubsub_subscription` expiration_policy `dead_letter_policies` an array of `google_pubsub_subscription` dead_letter_policy Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Pub/Sub API](https://console.cloud.google.com/apis/library/pubsub.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_pubsub_subscriptions/google_pubsub_subscription_iam_policy resource ================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_pubsub_subscription_iam_policy.md) Syntax ------ A `google_pubsub_subscription_iam_policy` is used to test a Google Subscription Iam Policy resource Examples -------- ``` describe google_pubsub_subscription_iam_policy(project: "project", name: "name") do it { should exist } end google_pubsub_subscription_iam_policy(project: "project", name: "name").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` Properties ---------- Properties that can be accessed from the `google_pubsub_subscription_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Cloud Pub/Sub API](https://console.cloud.google.com/apis/library/pubsub.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_pubsub_subscription_iam_policy/google_pubsub_topic resource ============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_pubsub_topic.md) Syntax ------ A `google_pubsub_topic` is used to test a Google Topic resource Examples -------- ``` describe google_pubsub_topic(project: 'chef-gcp-inspec', name: 'inspec-gcp-topic') do it { should exist } end describe google_pubsub_topic(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_pubsub_topic` resource: `name` Name of the topic. `kms_key_name` The resource name of the Cloud KMS CryptoKey to be used to protect access to messages published on this topic. Your project’s PubSub service account (`<EMAIL>-{{PROJECT_<EMAIL>`) must have `roles/cloudkms.cryptoKeyEncrypterDecrypter` to use this feature. The expected format is `projects/*/locations/*/keyRings/*/cryptoKeys/*` `labels` A set of key/value label pairs to assign to this Topic. `message_storage_policy` Policy constraining the set of Google Cloud Platform regions where messages published to the topic may be stored. If not present, then no constraints are in effect. `allowed_persistence_regions` A list of IDs of GCP regions where messages that are published to the topic may be persisted in storage. Messages published by publishers running in non-allowed GCP regions (or running outside of GCP altogether) will be routed for storage in one of the allowed regions. An empty list means that no regions are allowed, and is not a valid configuration. GCP Permissions --------------- Ensure the [Cloud Pub/Sub API](https://console.cloud.google.com/apis/library/pubsub.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_pubsub_topic/google_pubsub_topic_iam_policy resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_pubsub_topic_iam_policy.md) Syntax ------ A `google_pubsub_topic_iam_policy` is used to test a Google Topic Iam Policy resource Examples -------- ``` describe google_pubsub_topic_iam_policy(project: "project", name: "name") do it { should exist } end google_pubsub_topic_iam_policy(project: "project", name: "name").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` Properties ---------- Properties that can be accessed from the `google_pubsub_topic_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Cloud Pub/Sub API](https://console.cloud.google.com/apis/library/pubsub.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_pubsub_topic_iam_policy/google_pubsub_topic_iam_binding resource ============================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_pubsub_topic_iam_binding.md) Syntax ------ A `google_pubsub_topic_iam_binding` is used to test a Google Topic Iam Bindings Examples -------- ``` describe google_pubsub_topic_iam_binding(project: "project", name: "name", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` Properties ---------- Properties that can be accessed from the `google_pubsub_topic_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. GCP Permissions --------------- Ensure the [Cloud Pub/Sub API](https://console.cloud.google.com/apis/library/pubsub.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_pubsub_topic_iam_binding/google_redis_instance resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_redis_instance.md) Syntax ------ A `google_redis_instance` is used to test a Google Instance resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_redis_instance(project: 'chef-gcp-inspec', region: 'us-central1', name: 'my-redis-cache') do it { should exist } its('tier') { should cmp 'STANDARD_HA' } its('memory_size_gb') { should cmp '1' } its('alternative_location_id') { should cmp 'us-central1-f' } its('redis_version') { should cmp 'REDIS_3_2' } its('display_name') { should cmp 'InSpec test instance' } its('reserved_ip_range') { should cmp '192.168.0.0/29' } its('labels') { should include('key' => 'value') } end describe google_redis_instance(project: 'chef-gcp-inspec', region: 'us-central1', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_redis_instance` resource: `alternative_location_id` Only applicable to STANDARD_HA tier which protects the instance against zonal failures by provisioning it across two zones. If provided, it must be a different zone from the one provided in [locationId]. `authorized_network` The full name of the Google Compute Engine network to which the instance is connected. If left unspecified, the default network will be used. `connect_mode` The connection mode of the Redis instance. Possible values: * DIRECT_PEERING * PRIVATE_SERVICE_ACCESS `create_time` The time the instance was created in RFC3339 UTC"Zulu" format, accurate to nanoseconds. `current_location_id` The current zone where the Redis endpoint is placed. For Basic Tier instances, this will always be the same as the [locationId] provided by the user at creation time. For Standard Tier instances, this can be either [locationId] or [alternativeLocationId] and can change after a failover event. `display_name` An arbitrary and optional user-provided name for the instance. `host` Hostname or IP address of the exposed Redis endpoint used by clients to connect to the service. `labels` Resource labels to represent user provided metadata. `redis_configs` Redis configuration parameters, according to <http://redis.io/topics/config>. Please check Memorystore documentation for the list of supported parameters: <https://cloud.google.com/memorystore/docs/redis/reference/rest/v1/projects.locations.instances#Instance.FIELDS.redis_configs> `location_id` The zone where the instance will be provisioned. If not provided, the service will choose a zone for the instance. For STANDARD_HA tier, instances will be created across two zones for protection against zonal failures. If [alternativeLocationId] is also provided, it must be different from [locationId]. `name` The ID of the instance or a fully qualified identifier for the instance. `memory_size_gb` Redis memory size in GiB. `port` The port number of the exposed Redis endpoint. `redis_version` The version of Redis software. If not provided, latest supported version will be used. Currently, the supported values are: - REDIS_4_0 for Redis 4.0 compatibility - REDIS_3_2 for Redis 3.2 compatibility `reserved_ip_range` The CIDR range of internal addresses that are reserved for this instance. If not provided, the service will choose an unused /29 block, for example, 10.0.0.0/29 or 192.168.0.0/29. Ranges must be unique and non-overlapping with existing subnets in an authorized network. `tier` The service tier of the instance. Must be one of these values: - BASIC: standalone instance - STANDARD_HA: highly available primary/replica instances Possible values: * BASIC * STANDARD_HA `region` The name of the Redis region of the instance. GCP Permissions --------------- © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_redis_instance/google_redis_instances resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_redis_instances.md) Syntax ------ A `google_redis_instances` is used to test a Google Instance resource Beta Resource ------------- This resource has beta fields available. To retrieve these fields, include `beta: true` in the constructor for the resource Examples -------- ``` describe google_redis_instances(project: 'chef-gcp-inspec', region: 'us-central1') do its('tiers') { should include 'STANDARD_HA' } its('memory_size_gbs') { should include '1' } its('alternative_location_ids') { should include 'us-central1-f' } its('redis_versions') { should include 'REDIS_3_2' } its('display_names') { should include 'InSpec test instance' } its('reserved_ip_ranges') { should include '192.168.0.0/29' } end ``` Properties ---------- Properties that can be accessed from the `google_redis_instances` resource: See the [google_redis_instance](../google_redis_instance/index#properties) resource for more information. `alternative_location_ids` an array of `google_redis_instance` alternative_location_id `authorized_networks` an array of `google_redis_instance` authorized_network `connect_modes` an array of `google_redis_instance` connect_mode `create_times` an array of `google_redis_instance` create_time `current_location_ids` an array of `google_redis_instance` current_location_id `display_names` an array of `google_redis_instance` display_name `hosts` an array of `google_redis_instance` host `labels` an array of `google_redis_instance` labels `redis_configs` an array of `google_redis_instance` redis_configs `location_ids` an array of `google_redis_instance` location_id `names` an array of `google_redis_instance` name `memory_size_gbs` an array of `google_redis_instance` memory_size_gb `ports` an array of `google_redis_instance` port `redis_versions` an array of `google_redis_instance` redis_version `reserved_ip_ranges` an array of `google_redis_instance` reserved_ip_range `tiers` an array of `google_redis_instance` tier `regions` an array of `google_redis_instance` region Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_redis_instances/google_pubsub_topics resource =============================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_pubsub_topics.md) Syntax ------ A `google_pubsub_topics` is used to test a Google Topic resource Examples -------- ``` describe google_pubsub_topics(project: 'chef-gcp-inspec') do it { should exist } its('names') { should include 'inspec-gcp-topic' } its('count') { should be >=1 } end describe.one do google_pubsub_topics(project: 'chef-gcp-inspec').names.each do |topic_name| describe google_pubsub_topic(project: 'chef-gcp-inspec', name: topic_name) do it { should exist } end end end ``` Properties ---------- Properties that can be accessed from the `google_pubsub_topics` resource: See the [google_pubsub_topic](../google_pubsub_topic/index#properties) resource for more information. `names` an array of `google_pubsub_topic` name `kms_key_names` an array of `google_pubsub_topic` kms_key_name `labels` an array of `google_pubsub_topic` labels `message_storage_policies` an array of `google_pubsub_topic` message_storage_policy Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Pub/Sub API](https://console.cloud.google.com/apis/library/pubsub.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_pubsub_topics/google_resourcemanager_folder_iam_policy resource ===================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_resourcemanager_folder_iam_policy.md) Syntax ------ A `google_resourcemanager_folder_iam_policy` is used to test a Google Folder Iam Policy resource Examples -------- ``` describe google_resourcemanager_folder_iam_policy(name: "name") do it { should exist } end google_resourcemanager_folder_iam_policy(name: "name").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` Properties ---------- Properties that can be accessed from the `google_resourcemanager_folder_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_resourcemanager_folder_iam_policy/google_resourcemanager_folders resource ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_resourcemanager_folders.md) Syntax ------ A `google_resourcemanager_folders` is used to test a Google Folder resource Examples -------- ``` describe.one do google_resourcemanager_folders(parent: 'organizations/12345').display_names.each do |display_name| describe display_name do it { should eq 'inspec-gcp-folder' } end end end ``` Properties ---------- Properties that can be accessed from the `google_resourcemanager_folders` resource: See the [google_resourcemanager_folder](../google_resourcemanager_folder/index#properties) resource for more information. `names` an array of `google_resourcemanager_folder` name `lifecycle_states` an array of `google_resourcemanager_folder` lifecycle_state `create_times` an array of `google_resourcemanager_folder` create_time `parents` an array of `google_resourcemanager_folder` parent `display_names` an array of `google_resourcemanager_folder` display_name Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_resourcemanager_folders/google_resourcemanager_folder resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_resourcemanager_folder.md) Syntax ------ A `google_resourcemanager_folder` is used to test a Google Folder resource Examples -------- ``` describe.one do google_resourcemanager_folders(parent: 'organizations/12345').names.each do |name| describe google_resourcemanager_folder(name: name) do it { should exist } its('display_name') { should eq 'inspec-gcp-folder' } end end end ``` Properties ---------- Properties that can be accessed from the `google_resourcemanager_folder` resource: `name` The resource name of the Folder. Its format is folders/{folder_id}, for example: “folders/1234”. `lifecycle_state` The lifecycle state of the folder. Updates to the lifecycleState must be performed via folders.delete and folders.undelete. Possible values: * LIFECYCLE_STATE_UNSPECIFIED * ACTIVE * DELETE_REQUESTED `create_time` Time of creation `parent` The Folder’s parent’s resource name. Updates to the folder’s parent must be performed via folders.move. `display_name` The folder’s display name. A folder’s display name must be unique amongst its siblings, e.g. no two folders with the same parent can share the same display name. The display name must start and end with a letter or digit, may contain letters, digits, spaces, hyphens and underscores and can be no longer than 30 characters. This is captured by the regular expression: `[\p{L}\p{N}]([\p{L}\p{N}_- ]{0,28}[\p{L}\p{N}])?`. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_resourcemanager_folder/google_resourcemanager_folder_iam_binding resource ====================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_resourcemanager_folder_iam_binding.md) Syntax ------ A `google_resourcemanager_folder_iam_binding` is used to test a Google Folder Iam Bindings Examples -------- ``` describe google_resourcemanager_folder_iam_binding(name: "name", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` Properties ---------- Properties that can be accessed from the `google_resourcemanager_folder_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_resourcemanager_folder_iam_binding/google_resourcemanager_organization_policy resource ====================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_resourcemanager_organization_policy.md) Syntax ------ A `google_resourcemanager_organization_policy` is used to test organization policy constraints. More information can be found here [Organization Policy Constraints](https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints) Examples -------- ``` describe google_resourcemanager_organization_policy(organization_name: "organizations/123456789", constraint: "constraints/compute.disableSerialPortAccess") do it { should exist } its('constraint') { should eq 'constraints/compute.disableSerialPortAccess' } its('boolean_policy.enforced') { should be true } end ``` Properties ---------- Properties that can be accessed from the `google_resourcemanager_organization_policy` resource: `version` The version of the policy. `constraint` The name of the constraint the policy is configuring. `update_time` The time stamp the policy was previously updated. `list_policy` List of values either allowed or disallowed `allowed_values` List of values allowed `denied_values` List of values denied `boolean_policy` Used to specify how a boolean policy will behave `enforced` If true then the policy is enforced. If false then any configuration is acceptable GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_resourcemanager_organization_policy/google_runtime_config_config resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_runtime_config_config.md) Syntax ------ A `google_runtime_config_config` is used to test a Google Config resource Examples -------- ``` describe google_runtime_config_config(project: 'chef-gcp-inspec', name: 'inspec-gcp-runtime-config') do it { should exist } its('description') { should cmp 'My runtime configurations' } end describe google_runtime_config_config(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_runtime_config_config` resource: `description` The description to associate with the runtime config. `name` The name of the runtime config. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_runtime_config_config/google_resourcemanager_project_iam_policy resource ====================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_resourcemanager_project_iam_policy.md) Syntax ------ A `google_resourcemanager_project_iam_policy` is used to test a Google Project Iam Policy resource Examples -------- ``` describe google_resourcemanager_project_iam_policy(project_id: "projectId") do it { should exist } end google_resourcemanager_project_iam_policy(project_id: "projectId").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` Properties ---------- Properties that can be accessed from the `google_resourcemanager_project_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_resourcemanager_project_iam_policy/google_runtime_config_config_iam_binding resource ====================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_runtime_config_config_iam_binding.md) Syntax ------ A `google_runtime_config_config_iam_binding` is used to test a Google Config Iam Bindings Examples -------- ``` describe google_runtime_config_config_iam_binding(project: "project", name: "name", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` Properties ---------- Properties that can be accessed from the `google_runtime_config_config_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_runtime_config_config_iam_binding/google_resourcemanager_project_iam_binding resource ======================================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_resourcemanager_project_iam_binding.md) Syntax ------ A `google_resourcemanager_project_iam_binding` is used to test a Google Project Iam Bindings Examples -------- ``` describe google_resourcemanager_project_iam_binding(project_id: "projectId", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` Properties ---------- Properties that can be accessed from the `google_resourcemanager_project_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_resourcemanager_project_iam_binding/google_runtime_config_configs resource ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_runtime_config_configs.md) Syntax ------ A `google_runtime_config_configs` is used to test a Google Config resource Examples -------- ``` describe google_runtime_config_configs(project: 'chef-gcp-inspec') do its('descriptions') { should include 'My runtime configurations' } end ``` Properties ---------- Properties that can be accessed from the `google_runtime_config_configs` resource: See the [google_runtime_config_config](../google_runtime_config_config/index#properties) resource for more information. `descriptions` an array of `google_runtime_config_config` description `names` an array of `google_runtime_config_config` name Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_runtime_config_configs/google_runtime_config_config_iam_policy resource ===================================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_runtime_config_config_iam_policy.md) Syntax ------ A `google_runtime_config_config_iam_policy` is used to test a Google Config IAM Policy resource Examples -------- ``` describe google_runtime_config_config_iam_policy(project: "project", name: "name") do it { should exist } end google_runtime_config_config_iam_policy(project: "project", name: "name").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` Properties ---------- Properties that can be accessed from the `google_runtime_config_config_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_runtime_config_config_iam_policy/google_runtime_config_variables resource =========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_runtime_config_variables.md) Syntax ------ A `google_runtime_config_variables` is used to test a Google Variable resource Examples -------- ``` describe google_runtime_config_variables(project: 'chef-gcp-inspec', config: 'inspec-gcp-runtime-config') do its('texts') { should include 'example.com' } end ``` Properties ---------- Properties that can be accessed from the `google_runtime_config_variables` resource: See the [google_runtime_config_variable](../google_runtime_config_variable/index#properties) resource for more information. `values` an array of `google_runtime_config_variable` value `texts` an array of `google_runtime_config_variable` text `names` an array of `google_runtime_config_variable` name `configs` an array of `google_runtime_config_variable` config Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_runtime_config_variables/google_spanner_database resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_spanner_database.md) Syntax ------ A `google_spanner_database` is used to test a Google Database resource Examples -------- ``` describe google_spanner_database(project: 'chef-gcp-inspec', instance: 'spinstance', name: 'spdatabase') do it { should exist } its('name') { should match 'spdatabase' } end ``` Properties ---------- Properties that can be accessed from the `google_spanner_database` resource: `name` A unique identifier for the database, which cannot be changed after the instance is created. Values are of the form [a-z][-a-z0-9]*[a-z0-9]. `instance` The instance to create the database on. GCP Permissions --------------- Ensure the [Cloud Spanner API](https://console.cloud.google.com/apis/library/spanner.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_spanner_database/google_service_account_keys resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_service_account_keys.md) Syntax ------ A `google_service_account_keys` is used to test a Google ServiceAccountKey resource Examples -------- ``` describe google_service_account_keys(project: 'chef-gcp-inspec', service_account: "display-name@project-id.iam.gserviceaccount.com") do its('count') { should be <= 1000 } its('key_types') { should_not include 'USER_MANAGED' } end ``` ### Test that there are no more than a specified number of keys for the service account ``` describe google_service_account_keys(project: 'sample-project', service_account: 'sample-<EMAIL>.iam.<EMAIL>.com') do its('count') { should be <= 1000} end ``` ### Test that a service account with expected name is available ``` describe google_service_account_keys(project: 'sample-project', service_account: 'sample-<EMAIL>@sample-project.iam.gserviceaccount.com') do its('key_names'){ should include "projects/sample-project/serviceAccounts/test-sa@sample-project.iam.g<EMAIL>account.com/keys/<KEY>" } end ``` Properties ---------- Properties that can be accessed from the `google_service_account_keys` resource: See the [google_service_account_key](../google_service_account_key/index#properties) resource for more information. `key_names` an array of `google_service_account_key` name `private_key_types` an array of `google_service_account_key` private_key_type `key_algorithms` an array of `google_service_account_key` key_algorithm `private_key_data` an array of `google_service_account_key` private_key_data `public_key_data` an array of `google_service_account_key` public_key_data `valid_after_times` an array of `google_service_account_key` valid_after_time `valid_before_times` an array of `google_service_account_key` valid_before_time `key_types` an array of `google_service_account_key` key_type `service_accounts` an array of `google_service_account_key` service_account `paths` an array of `google_service_account_key` path Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_service_account_keys/google_service_account resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_service_account.md) Syntax ------ A `google_service_account` is used to test a Google ServiceAccount resource Examples -------- ``` describe google_service_account(project: 'chef-gcp-inspec', name: "<EMAIL>") do it { should exist } its('display_name') { should cmp '' } end describe google_service_account(project: 'chef-gcp-inspec', name: "<EMAIL>") do it { should_not exist } end ``` ### Test that a GCP project IAM service account has the expected unique identifier ``` describe google_service_account(project: 'sample-project', name: '<EMAIL>@sample-<EMAIL>.iam.<EMAIL>') do its('unique_id') { should eq 12345678 } end ``` ### Test that a GCP project IAM service account has the expected oauth2 client identifier ``` describe google_service_account(project: 'sample-project', name: '<EMAIL>') do its('oauth2_client_id') { should eq 12345678 } end ``` ### Test that a GCP project IAM service account does not have user managed keys ``` describe google_service_account_keys(project: 'chef-gcp-inspec', service_account: "<EMAIL>") do its('key_types') { should_not include 'USER_MANAGED' } end ``` Properties ---------- Properties that can be accessed from the `google_service_account` resource: `name` The name of the service account. `project_id` Id of the project that owns the service account. `unique_id` Unique and stable id of the service account `email` Email address of the service account. `display_name` User specified description of service account. `oauth2_client_id` OAuth2 client id for the service account. GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_service_account/google_service_account_key resource ====================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_service_account_key.md) Syntax ------ A `google_service_account_key` is used to test a Google ServiceAccountKey resource Examples -------- ``` google_service_account_keys(project: 'chef-gcp-inspec', service_account: "<EMAIL>").key_names.each do |sa_key_name| describe google_service_account_key(project: 'chef-gcp-inspec', service_account: "<EMAIL>", name: sa_key_name.split('/').last) do it { should exist } its('key_type') { should_not cmp 'USER_MANAGED' } end end ``` ### Test that a GCP project IAM service account key has the expected key algorithm ``` describe google_service_account_key(name: "projects/sample-project/serviceAccounts/test-sa@sample-project.iam.gserviceaccount.com/keys/<KEY>" ) do its('key_algorithm') { should eq "KEY_ALG_RSA_2048" } end ``` Properties ---------- Properties that can be accessed from the `google_service_account_key` resource: `name` The name of the key. `private_key_type` Output format for the service account key. Possible values: * TYPE_UNSPECIFIED * TYPE_PKCS12_FILE * TYPE_GOOGLE_CREDENTIALS_FILE `key_algorithm` Specifies the algorithm for the key. Possible values: * KEY_ALG_UNSPECIFIED * KEY_ALG_RSA_1024 * KEY_ALG_RSA_2048 `private_key_data` Private key data. Base-64 encoded. `public_key_data` Public key data. Base-64 encoded. `valid_after_time` Key can only be used after this time. `valid_before_time` Key can only be used before this time. `key_type` Specifies the type of the key. Possible values: * KEY_TYPE_UNSPECIFIED * USER_MANAGED * SYSTEM_MANAGED `service_account` The name of the serviceAccount. `path` The full name of the file that will hold the service account private key. The management of this file will depend on the value of sync_file parameter. File path must be absolute. GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_service_account_key/google_sourcerepo_repository resource ======================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_sourcerepo_repository.md) Syntax ------ A `google_sourcerepo_repository` is used to test a Google Repository resource Examples -------- ``` describe google_sourcerepo_repository(project: 'chef-gcp-inspec', name: 'inspec-gcp-repository') do it { should exist } end describe google_sourcerepo_repository(project: 'chef-gcp-inspec', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_sourcerepo_repository` resource: `name` Resource name of the repository, of the form projects/{{project}}/repos/{{repo}}. The repo name may contain slashes. E.g., projects/myproject/repos/name/with/slash `url` URL to clone the repository from Google Cloud Source Repositories. `size` The disk usage of the repo, in bytes. `pubsub_configs` How this repository publishes a change in the repository through Cloud Pub/Sub. Keyed by the topic names. GCP Permissions --------------- Ensure the [Cloud Source Repositories API](https://console.cloud.google.com/apis/library/sourcerepo.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_sourcerepo_repository/google_runtime_config_variable resource ========================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_runtime_config_variable.md) Syntax ------ A `google_runtime_config_variable` is used to test a Google Variable resource Examples -------- ``` describe google_runtime_config_variable(project: 'chef-gcp-inspec', config: 'inspec-gcp-runtime-config', name: 'prod-variables/hostname') do it { should exist } its('text') { should cmp 'example.com' } end describe google_runtime_config_variable(project: 'chef-gcp-inspec', config: 'inspec-gcp-runtime-config', name: 'nonexistent') do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_runtime_config_variable` resource: `value` The binary value of the variable. Either this or `text` can be set. `text` The string value of the variable. Either this or `value` can be set. `name` The name of the variable resource. `config` The name of the runtime config that this variable belongs to. GCP Permissions --------------- Ensure the [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_runtime_config_variable/google_sourcerepo_repositories resource ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_sourcerepo_repositories.md) Syntax ------ A `google_sourcerepo_repositories` is used to test a Google Repository resource Examples -------- ``` repo_name = 'inspec-gcp-repository' describe.one do google_sourcerepo_repositories(project: 'chef-gcp-inspec').names.each do |name| describe name do it { should match /\/repos\/#{repo_name}$/ } end end end ``` Properties ---------- Properties that can be accessed from the `google_sourcerepo_repositories` resource: See the [google_sourcerepo_repository](../google_sourcerepo_repository/index#properties) resource for more information. `names` an array of `google_sourcerepo_repository` name `urls` an array of `google_sourcerepo_repository` url `sizes` an array of `google_sourcerepo_repository` size `pubsub_configs` an array of `google_sourcerepo_repository` pubsub_configs Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Source Repositories API](https://console.cloud.google.com/apis/library/sourcerepo.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_sourcerepo_repositories/google_service_accounts resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_service_accounts.md) Syntax ------ A `google_service_accounts` is used to test a Google ServiceAccount resource Examples -------- ``` describe google_service_accounts(project: 'chef-gcp-inspec', name: "<EMAIL>") do its('service_account_emails') { should include "<EMAIL>" } its('count') { should be <= 1000 } end ``` ### Test that there are no more than a specified number of service accounts for the project ``` describe google_service_accounts(project: 'chef-inspec-gcp') do its('count') { should be <= 1000} end ``` ### Test that an expected service account display name is available ``` describe google_service_accounts(project: 'chef-inspec-gcp') do its('service_account_display_names'){ should include "gcp_sa_name" } end ``` ### Test that an expected service account unique identifier is available ``` describe google_service_accounts(project: 'chef-inspec-gcp') do its('service_account_ids'){ should include 12345678 } end ``` ### Test that a service account with expected name is available ``` describe google_service_accounts(project: 'dummy-project') do its('service_account_names'){ should include "projects/dummy-project/serviceAccounts/dummy-acct@dummy-project.iam.gserviceaccount.com" } end ``` ### Use filtering to retrieve a particular service account ``` google_service_accounts(project: 'chef-inspec-gcp').where(service_account_display_names: /^dummyaccount/).service_account_names.each do |sa_name| describe google_service_account(name: sa_name) do it { should exist } end end ``` Properties ---------- Properties that can be accessed from the `google_service_accounts` resource: See the [google_service_account](../google_service_account/index#properties) resource for more information. `service_account_names` an array of `google_service_account` name `project_ids` an array of `google_service_account` project_id `service_account_ids` an array of `google_service_account` unique_id `service_account_emails` an array of `google_service_account` email `service_account_display_names` an array of `google_service_account` display_name `oauth2_client_ids` an array of `google_service_account` oauth2_client_id Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Identity and Access Management (IAM) API](https://console.cloud.google.com/apis/library/iam.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_service_accounts/google_spanner_instance resource ================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_spanner_instance.md) Syntax ------ A `google_spanner_instance` is used to test a Google Instance resource Examples -------- ``` describe google_spanner_instance(project: 'chef-gcp-inspec', name: 'spinstance', config: 'regional-us-east1') do it { should exist } its('config') { should match 'regional-us-east1' } its('name') { should match 'spinstance' } its('display_name') { should eq 'inspectest' } its('node_count') { should eq '1' } its('labels') { should include('env' => 'test') } end ``` Properties ---------- Properties that can be accessed from the `google_spanner_instance` resource: `name` A unique identifier for the instance, which cannot be changed after the instance is created. The name must be between 6 and 30 characters in length. `config` The name of the instance’s configuration (similar but not quite the same as a region) which defines defines the geographic placement and replication of your databases in this instance. It determines where your data is stored. Values are typically of the form `regional-europe-west1` , `us-central` etc. In order to obtain a valid list please consult the [Configuration section of the docs](https://cloud.google.com/spanner/docs/instances). `display_name` The descriptive name for this instance as it appears in UIs. Must be unique per project and between 4 and 30 characters in length. `node_count` The number of nodes allocated to this instance. `labels` An object containing a list of `"key": "value"` pairs. Example: { “name”: “wrench”, “mass”: “1.3kg”, “count”: “3” }. GCP Permissions --------------- Ensure the [Cloud Spanner API](https://console.cloud.google.com/apis/library/spanner.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_spanner_instance/google_spanner_databases resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_spanner_databases.md) Syntax ------ A `google_spanner_databases` is used to test a Google Database resource Examples -------- ``` describe.one do google_spanner_databases(project: 'chef-gcp-inspec', instance: 'spinstance').names.each do |name| describe name do it { should match 'spdatabase' } end end end ``` Properties ---------- Properties that can be accessed from the `google_spanner_databases` resource: See the [google_spanner_database](../google_spanner_database/index#properties) resource for more information. `names` an array of `google_spanner_database` name `instances` an array of `google_spanner_database` instance Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Spanner API](https://console.cloud.google.com/apis/library/spanner.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_spanner_databases/google_spanner_instance_iam_binding resource ================================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_spanner_instance_iam_binding.md) Syntax ------ A `google_spanner_instance_iam_binding` is used to test a Google Instance Iam Bindings Examples -------- ``` describe google_spanner_instance_iam_binding(project: "project", name: "name", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` Properties ---------- Properties that can be accessed from the `google_spanner_instance_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. GCP Permissions --------------- Ensure the [Cloud Spanner API](https://console.cloud.google.com/apis/library/spanner.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_spanner_instance_iam_binding/google_spanner_instance_iam_policy resource =============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_spanner_instance_iam_policy.md) Syntax ------ A `google_spanner_instance_iam_policy` is used to test a Google Instance Iam Policy resource Examples -------- ``` describe google_spanner_instance_iam_policy(project: "project", name: "name") do it { should exist } end google_spanner_instance_iam_policy(project: "project", name: "name").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` Properties ---------- Properties that can be accessed from the `google_spanner_instance_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Cloud Spanner API](https://console.cloud.google.com/apis/library/spanner.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_spanner_instance_iam_policy/google_spanner_instances resource =================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_spanner_instances.md) Syntax ------ A `google_spanner_instances` is used to test a Google Instance resource Examples -------- ``` describe.one do google_spanner_instances(project: 'chef-gcp-inspec', config: 'regional-us-east1').configs.each do |config| describe config do it { should match 'regional-us-east1' } end end end ``` Properties ---------- Properties that can be accessed from the `google_spanner_instances` resource: See the [google_spanner_instance](../google_spanner_instance/index#properties) resource for more information. `names` an array of `google_spanner_instance` name `configs` an array of `google_spanner_instance` config `display_names` an array of `google_spanner_instance` display_name `node_counts` an array of `google_spanner_instance` node_count `labels` an array of `google_spanner_instance` labels Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud Spanner API](https://console.cloud.google.com/apis/library/spanner.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_spanner_instances/google_sql_user resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_sql_user.md) Syntax ------ A `google_sql_user` is used to test a Google User resource Examples -------- ``` describe google_sql_user(project: 'chef-gcp-inspec', database: 'my-database', name: 'user-name', host: "example.com") do it { should exist } its('name') { should cmp 'user-name' } its('instance') { should cmp 'my-database' } end describe google_sql_user(project: 'chef-gcp-inspec', database: 'my-database', name: "nonexistent", host: "example.com") do it { should_not exist } end ``` Properties ---------- Properties that can be accessed from the `google_sql_user` resource: `host` The host name from which the user can connect. For insert operations, host defaults to an empty string. For update operations, host is specified as part of the request URL. The host name cannot be updated after insertion. `name` The name of the user in the Cloud SQL instance. `instance` The name of the Cloud SQL instance. This does not include the project ID. `password` The password for the user. GCP Permissions --------------- Ensure the [Cloud SQL Admin API](https://console.cloud.google.com/apis/library/sqladmin.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_sql_user/google_sql_database_instance resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_sql_database_instance.md) Syntax ------ A `google_sql_database_instance` is used to test a Google DatabaseInstance resource Examples -------- ``` describe google_sql_database_instance(project: 'chef-gcp-inspec', database: 'my-database') do it { should exist } its('state') { should eq 'RUNNABLE' } its('backend_type') { should eq 'SECOND_GEN' } its('database_version') { should eq 'MYSQL_5_7' } end ``` ### Test that a GCP Cloud SQL Database instance is in the expected state ``` describe google_sql_database_instance(project: 'chef-inspec-gcp', database: 'my-database') do its('state') { should eq 'RUNNABLE' } end ``` ### Test that a GCP Cloud SQL Database instance generation type ``` describe google_sql_database_instance(project: 'chef-inspec-gcp', database: 'my-database') do its('backend_type') { should eq "SECOND_GEN" } end ``` ### Test that a GCP Cloud SQL Database instance connection name is as expected ``` describe google_sql_database_instance(project: 'spaterson-project', database: 'gcp-inspec-db-instance') do its('connection_name') { should eq "spaterson-project:europe-west2:gcp-inspec-db-instance" } end ``` ### Confirm that a GCP Cloud SQL Database instance has the correct version ``` describe google_sql_database_instance(project: 'spaterson-project', database: 'gcp-inspec-db-instance') do its('database_version') { should eq "MYSQL_5_7" } end ``` ### Confirm that a GCP Cloud SQL Database instance is running in the desired region and zone ``` describe google_sql_database_instance(project: 'spaterson-project', database: 'gcp-inspec-db-instance') do its('gce_zone') { should eq "europe-west2-a" } its('region') { should eq "europe-west2" } end ``` Properties ---------- Properties that can be accessed from the `google_sql_database_instance` resource: `backend_type` Possible values: * FIRST_GEN: First Generation instance. MySQL only. * SECOND_GEN: Second Generation instance or PostgreSQL instance. * EXTERNAL: A database server that is not managed by Google. `connection_name` Connection name of the Cloud SQL instance used in connection strings. `database_version` The database engine type and version. For First Generation instances, can be MYSQL_5_5, or MYSQL_5_6. For Second Generation instances, can be MYSQL_5_6 or MYSQL_5_7. Defaults to MYSQL_5_6. PostgreSQL instances: POSTGRES_9_6 The databaseVersion property can not be changed after instance creation. Possible values: * MYSQL_5_5 * MYSQL_5_6 * MYSQL_5_7 * POSTGRES_9_6 `failover_replica` The name and status of the failover replica. This property is applicable only to Second Generation instances. `available` The availability status of the failover replica. A false status indicates that the failover replica is out of sync. The master can only failover to the failover replica when the status is true. `name` The name of the failover replica. If specified at instance creation, a failover replica is created for the instance. The name doesn’t include the project ID. This property is applicable only to Second Generation instances. `instance_type` The instance type. This can be one of the following. _ CLOUD_SQL_INSTANCE: A Cloud SQL instance that is not replicating from a master. _ ON_PREMISES_INSTANCE: An instance running on the customer’s premises. _ READ_REPLICA_INSTANCE: A Cloud SQL instance configured as a read-replica. Possible values: * CLOUD_SQL_INSTANCE * ON_PREMISES_INSTANCE * READ_REPLICA_INSTANCE `ip_addresses` The assigned IP addresses for the instance. `ip_address` The IP address assigned. `time_to_retire` The due time for this IP to be retired in RFC 3339 format, for example 2012-11-15T16:19:00.094Z. This field is only available when the IP is scheduled to be retired. `type` The type of this IP address. A PRIMARY address is an address that can accept incoming connections. An OUTGOING address is the source address of connections originating from the instance, if supported. Possible values: * PRIMARY * OUTGOING `ipv6_address` The IPv6 address assigned to the instance. This property is applicable only to First Generation instances. `master_instance_name` The name of the instance which will act as master in the replication setup. `max_disk_size` The maximum disk size of the instance in bytes. `name` Name of the Cloud SQL instance. This does not include the project ID. `region` The geographical region. Defaults to us-central or us-central1 depending on the instance type (First Generation or Second Generation/PostgreSQL). `replica_configuration` Configuration specific to failover replicas and read replicas. `failover_target` Specifies if the replica is the failover target. If the field is set to true the replica will be designated as a failover replica. In case the master instance fails, the replica instance will be promoted as the new master instance. Only one replica can be specified as failover target, and the replica has to be in different zone with the master instance. `mysql_replica_configuration` MySQL specific configuration when replicating from a MySQL on-premises master. Replication configuration information such as the username, password, certificates, and keys are not stored in the instance metadata. The configuration information is used only to set up the replication connection and is stored by MySQL in a file named master.info in the data directory. `ca_certificate` PEM representation of the trusted CA’s x509 certificate. `client_certificate` PEM representation of the slave’s x509 certificate `client_key` PEM representation of the slave’s private key. The corresponding public key is encoded in the client’s certificate. `connect_retry_interval` Seconds to wait between connect retries. MySQL’s default is 60 seconds. `dump_file_path` Path to a SQL dump file in Google Cloud Storage from which the slave instance is to be created. The URI is in the form gs://bucketName/fileName. Compressed gzip files (.gz) are also supported. Dumps should have the binlog coordinates from which replication should begin. This can be accomplished by setting –master-data to 1 when using mysqldump. `master_heartbeat_period` Interval in milliseconds between replication heartbeats. `password` The password for the replication connection. `ssl_cipher` A list of permissible ciphers to use for SSL encryption. `username` The username for the replication connection. `verify_server_certificate` Whether or not to check the master’s Common Name value in the certificate that it sends during the SSL handshake. `replica_names` The replicas of the instance. `service_account_email_address` The service account email address assigned to the instance. This property is applicable only to Second Generation instances. `settings` The user settings. `database_flags` The database flags passed to the instance at startup `name` The name of the flag. These flags are passed at instance startup, so include both server options and system variables for MySQL. Flags should be specified with underscores, not hyphens. `value` The value of the flag. Booleans should be set to on for true and off for false. This field must be omitted if the flag doesn’t take a value. `ip_configuration` The settings for IP Management. This allows to enable or disable the instance IP and manage which external networks can connect to the instance. The IPv4 address cannot be disabled for Second Generation instances. `ipv4_enabled` Whether the instance should be assigned an IP address or not. `authorized_networks` The list of external networks that are allowed to connect to the instance using the IP. In CIDR notation, also known as ‘slash’ notation (e.g. 192.168.100.0/24). `expiration_time` The time when this access control entry expires in RFC 3339 format, for example 2012-11-15T16:19:00.094Z. `name` An optional label to identify this entry. `value` The whitelisted value for the access control list. For example, to grant access to a client from an external IP (IPv4 or IPv6) address or subnet, use that address or subnet here. `require_ssl` Whether the mysqld should default to ‘REQUIRE X509’ for users connecting over IP. `tier` The tier or machine type for this instance, for example db-n1-standard-1. For MySQL instances, this field determines whether the instance is Second Generation (recommended) or First Generation. `availability_type` The availabilityType define if your postgres instance is run zonal or regional. Possible values: * ZONAL * REGIONAL `backup_configuration` The daily backup configuration for the instance. `enabled` Enable Autobackup for your instance. `binary_log_enabled` Whether binary log is enabled. If backup configuration is disabled, binary log must be disabled as well. MySQL only. `start_time` Define the backup start time in UTC (HH:MM) `settings_version` The version of instance settings. This is a required field for update method to make sure concurrent updates are handled properly. During update, use the most recent settingsVersion value for this instance and do not try to update this value. `user_labels` User-provided labels, represented as a dictionary where each label is a single key value pair. `gce_zone` The Compute Engine zone that the instance is currently serving from. This value could be different from the zone that was specified when the instance was created if the instance has failed over to its secondary zone. `state` The current serving state of the database instance. Possible values: * SQL_INSTANCE_STATE_UNSPECIFIED * RUNNABLE * SUSPENDED * PENDING_DELETE * PENDING_CREATE * MAINTENANCE * FAILED GCP Permissions --------------- Ensure the [Cloud SQL Admin API](https://console.cloud.google.com/apis/library/sqladmin.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_sql_database_instance/google_sql_database_instances resource ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_sql_database_instances.md) Syntax ------ A `google_sql_database_instances` is used to test a Google DatabaseInstance resource Examples -------- ``` describe google_sql_database_instances(project: 'chef-gcp-inspec') do its('instance_states') { should include 'RUNNABLE' } its('instance_names') { should include 'my-database' } end ``` ### Test that there are no more than a specified number of zones available for the project ``` describe google_sql_database_instances(project: 'chef-inspec-gcp') do its('count') { should be <= 100} end ``` ### Test that a database instance exists in the expected zone ``` describe google_sql_database_instances(project: 'chef-inspec-gcp') do its('instance_zones') { should include "us-east1-b" } end ``` ### Test that a database instance exists in the expected region ``` describe google_sql_database_instances(project: 'chef-inspec-gcp') do its('instance_regions') { should include "us-east1" } end ``` ### Confirm that at least one database instance is in “RUNNABLE” state ``` describe google_sql_database_instances(project: 'chef-inspec-gcp') do its('instance_states') { should include "RUNNABLE" } end ``` ### Test that a subset of all database instances matching “*mysqldb*” are all version “MYSQL_5_7” ``` google_sql_database_instances(project: 'chef-inspec-gcp').where(instance_name: /mysqldb/).instance_names.each do |instance_name| describe google_sql_database_instance(project: 'chef-inspec-gcp', database: instance_name) do it { should exist } its('database_version') { should eq "MYSQL_5_7" } end end ``` Properties ---------- Properties that can be accessed from the `google_sql_database_instances` resource: See the [google_sql_database_instance](../google_sql_database_instance/index#properties) resource for more information. `backend_types` an array of `google_sql_database_instance` backend_type `connection_names` an array of `google_sql_database_instance` connection_name `instance_versions` an array of `google_sql_database_instance` database_version `failover_replicas` an array of `google_sql_database_instance` failover_replica `instance_types` an array of `google_sql_database_instance` instance_type `ip_addresses` an array of `google_sql_database_instance` ip_addresses `ipv6_addresses` an array of `google_sql_database_instance` ipv6_address `master_instance_names` an array of `google_sql_database_instance` master_instance_name `max_disk_sizes` an array of `google_sql_database_instance` max_disk_size `instance_names` an array of `google_sql_database_instance` name `instance_regions` an array of `google_sql_database_instance` region `replica_configurations` an array of `google_sql_database_instance` replica_configuration `settings` an array of `google_sql_database_instance` settings `instance_zones` an array of `google_sql_database_instance` gce_zone `instance_states` an array of `google_sql_database_instance` state Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud SQL Admin API](https://console.cloud.google.com/apis/library/sqladmin.googleapis.com/) is enabled for the current project. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_sql_database_instances/google_storage_bucket resource ================================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_storage_bucket.md) Syntax ------ A `google_storage_bucket` is used to test a Google Bucket resource Examples -------- ``` describe google_storage_bucket(name: bucket-name) do it { should exist } its('location') { should cmp 'europe-west2'.upcase } its('storage_class') { should eq "STANDARD" } its('labels') { should include("key" => "value") } its('retention_policy.retention_period') { should cmp 1000 } end describe google_storage_bucket(name: "nonexistent") do it { should_not exist } end ``` ### Test that a GCP storage bucket is in the expected location ``` describe google_storage_bucket(name: 'chef-inspec-gcp-storage-bucket-abcd') do its('location') { should eq "EUROPE-WEST2" } end ``` ### Test that a GCP storage bucket has the expected project number ``` describe google_storage_bucket(name: 'chef-inspec-gcp-storage-bucket-abcd') do its('project_number') {should eq 12345678 } end ``` ### Test that a GCP storage bucket has the expected storage class ``` describe google_storage_bucket(name: 'chef-inspec-gcp-storage-bucket-abcd') do its('storage_class') { should eq 'STANDARD' } end ``` Properties ---------- Properties that can be accessed from the `google_storage_bucket` resource: `acl` Access controls on the bucket. `bucket` The name of the bucket. `domain` The domain associated with the entity. `email` The email address associated with the entity. `entity` The entity holding the permission, in one of the following forms: user-userId user-email group-groupId group-email domain-domain project-team-projectId allUsers allAuthenticatedUsers Examples: The user [<EMAIL>](mailto:liz<EMAIL>) would be [<EMAIL>](mailto:<EMAIL>). The group [<EMAIL>](mailto:<EMAIL>) would be [<EMAIL>](mailto:<EMAIL>). To refer to all members of the Google Apps for Business domain example.com, the entity would be domain-example.com. `entity_id` The ID for the entity `id` The ID of the access-control entry. `project_team` The project team associated with the entity `project_number` The project team associated with the entity `team` The team. Possible values: * editors * owners * viewers `role` The access permission for the entity. Possible values: * OWNER * READER * WRITER `cors` The bucket’s Cross-Origin Resource Sharing (CORS) configuration. `max_age_seconds` : The value, in seconds, to return in the Access-Control-Max-Age header used in preflight responses. `method` : The list of HTTP methods on which to include CORS response headers, (GET, OPTIONS, POST, etc) Note: “*” is permitted in the list of methods, and means “any method”. `origin` : The list of Origins eligible to receive CORS response headers. Note: “*” is permitted in the list of origins, and means “any Origin”. `response_header` : The list of HTTP headers other than the simple response headers to give permission for the user-agent to share across domains. `default_event_based_hold` Whether or not to automatically apply an eventBasedHold to new objects added to the bucket. `default_object_acl` Default access controls to apply to new objects when no ACL is provided. `bucket` The name of the bucket. `domain` The domain associated with the entity. `email` The email address associated with the entity. `entity` The entity holding the permission, in one of the following forms: * user-{{userId}} * user-{{email}} (such as “[<EMAIL>](mailto:<EMAIL>)”) * group-{{groupId}} * group-{{email}} (such as “[<EMAIL>](mailto:<EMAIL>)”) * domain-{{domain}} (such as “domain-example.com”) * project-team-{{projectId}} * allUsers * allAuthenticatedUsers `entity_id` The ID for the entity `generation` The content generation of the object, if applied to an object. `id` The ID of the access-control entry. `object` The name of the object, if applied to an object. `project_team` The project team associated with the entity `project_number` The project team associated with the entity `team` The team. Possible values: * editors * owners * viewers `role` The access permission for the entity. Possible values: * OWNER * READER `id` The ID of the bucket. For buckets, the id and name properties are the same. `lifecycle` The bucket’s lifecycle configuration. See <https://developers.google.com/storage/docs/lifecycle> for more information. `rule` A lifecycle management rule, which is made of an action to take and the condition(s) under which the action will be taken. `action` The action to take. `storage_class` Target storage class. Required iff the type of the action is SetStorageClass. `type` Type of the action. Currently, only Delete and SetStorageClass are supported. Possible values: * Delete * SetStorageClass `condition` The condition(s) under which the action will be taken. `age_days` Age of an object (in days). This condition is satisfied when an object reaches the specified age. `created_before` A date in RFC 3339 format with only the date part (for instance, “2013-01-15”). This condition is satisfied when an object is created before midnight of the specified date in UTC. `is_live` Relevant only for versioned objects. If the value is true, this condition matches live objects; if the value is false, it matches archived objects. `matches_storage_class` Objects having any of the storage classes specified by this condition will be matched. Values include MULTI_REGIONAL, REGIONAL, NEARLINE, COLDLINE, STANDARD, ARCHIVE, and DURABLE_REDUCED_AVAILABILITY. `num_newer_versions` Relevant only for versioned objects. If the value is N, this condition is satisfied when there are at least N versions (including the live version) newer than this version of the object. `location` The location of the bucket. Object data for objects in the bucket resides in physical storage within this region. Defaults to US. See the developer’s guide for the authoritative list. `logging` The bucket’s logging configuration, which defines the destination bucket and optional name prefix for the current bucket’s logs. `log_bucket` The destination bucket where the current bucket’s logs should be placed. `log_object_prefix` A prefix for log object names. `metageneration` The metadata generation of this bucket. `name` The name of the bucket `owner` The owner of the bucket. This is always the project team’s owner group. `entity` The entity, in the form project-owner-projectId. `entity_id` The ID for the entity. `project_number` The project number of the project the bucket belongs to. `storage_class` The bucket’s default storage class, used whenever no storageClass is specified for a newly-created object. This defines how objects in the bucket are stored and determines the SLA and the cost of storage. Values include MULTI_REGIONAL, REGIONAL, STANDARD, NEARLINE, COLDLINE, ARCHIVE, and DURABLE_REDUCED_AVAILABILITY. If this value is not specified when the bucket is created, it will default to STANDARD. For more information, see storage classes. Possible values: * MULTI_REGIONAL * REGIONAL * STANDARD * NEARLINE * COLDLINE * ARCHIVE * DURABLE_REDUCED_AVAILABILITY `time_created` The creation time of the bucket in RFC 3339 format. `updated` The modification time of the bucket in RFC 3339 format. `versioning` The bucket’s versioning configuration. `enabled` While set to true, versioning is fully enabled for this bucket. `website` The bucket’s website configuration, controlling how the service behaves when accessing bucket contents as a website. See the Static Website Examples for more information. `main_page_suffix` If the requested object path is missing, the service will ensure the path has a trailing ‘/’, append this suffix, and attempt to retrieve the resulting object. This allows the creation of index.html objects to represent directory pages. `not_found_page` If the requested object path is missing, and any mainPageSuffix object is missing, if applicable, the service will return the named object from this bucket as the content for a 404 Not Found result. `labels` Labels applied to this bucket. A list of key->value pairs. `encryption` Encryption configuration for the bucket `default_kms_key_name` A Cloud KMS key that will be used to encrypt objects inserted into this bucket, if no encryption method is specified. `retention_policy` Retention policy for the bucket `effective_time` The time from which the retention policy was effective `is_locked` If the retention policy is locked. If true, the retention policy cannot be removed and the period cannot be reduced. `retention_period` The period of time, in seconds, that objects in the bucket must be retained and cannot be deleted, overwritten, or made noncurrent. `project` A valid API project identifier. `predefined_default_object_acl` Apply a predefined set of default object access controls to this bucket. Acceptable values are: - “authenticatedRead”: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. - “bucketOwnerFullControl”: Object owner gets OWNER access, and project team owners get OWNER access. - “bucketOwnerRead”: Object owner gets OWNER access, and project team owners get READER access. - “private”: Object owner gets OWNER access. - “projectPrivate”: Object owner gets OWNER access, and project team members get access according to their roles. - “publicRead”: Object owner gets OWNER access, and allUsers get READER access. Possible values: * authenticatedRead * bucketOwnerFullControl * bucketOwnerRead * private * projectPrivate * publicRead GCP Permissions --------------- Ensure the [Google Cloud Storage](https://console.cloud.google.com/apis/library/storage-component.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_storage_bucket/google_storage_bucket_acl resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_storage_bucket_acl.md) Syntax ------ A `google_storage_bucket_acl` is used to test a Google BucketACL resource Examples -------- ``` describe google_storage_bucket_acl(bucket: 'storage-bucket-name', entity: user-email) do it { should exist } its('role') { should cmp "OWNER" } its('bucket') { should eq 'storage-bucket-name' } its('email') { should include entity-email.com } end describe google_storage_bucket_acl(bucket: 'storage-bucket-name', entity: "allUsers") do it { should_not exist } end ``` ### Test that a GCP storage bucket ACL exists ``` describe google_storage_bucket_acl(bucket: 'bucket-buvsjjcndqz', entity: '<EMAIL>') do it { should exist } end ``` ### Test that a GCP storage bucket ACL has the expected role (READER, WRITER or OWNER) ``` describe google_storage_bucket_acl(bucket: 'bucket-buvsjjcndqz', entity: '<EMAIL>') do its('role') { should eq 'OWNER' } end ``` Properties ---------- Properties that can be accessed from the `google_storage_bucket_acl` resource: `domain` The domain associated with the entity. `email` The email address associated with the entity. `entity` The entity holding the permission, in one of the following forms: user-userId user-email group-groupId group-email domain-domain project-team-projectId allUsers allAuthenticatedUsers Examples: The user [<EMAIL>](mailto:<EMAIL>) would be [<EMAIL>](mailto:<EMAIL>). The group [<EMAIL>](mailto:<EMAIL>) would be [<EMAIL>](mailto:<EMAIL>). To refer to all members of the Google Apps for Business domain example.com, the entity would be domain-example.com. `entity_id` The ID for the entity `id` The ID of the access-control entry. `project_team` The project team associated with the entity `project_number` The project team associated with the entity `team` The team. Possible values: * editors * owners * viewers `role` The access permission for the entity. Possible values: * OWNER * READER * WRITER GCP Permissions --------------- Ensure the [Google Cloud Storage](https://console.cloud.google.com/apis/library/storage-component.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_storage_bucket_acl/google_sql_users resource =========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_sql_users.md) Syntax ------ A `google_sql_users` is used to test a Google User resource Examples -------- ``` describe google_sql_users(project: 'chef-gcp-inspec', database: 'my-database') do its('user_names') { should include 'user-name' } end ``` ### Test that there are no more than a specified number of users available for the project ``` describe google_sql_users(project: 'chef-inspec-gcp', database: 'database-instance') do its('count') { should be <= 100} end ``` ### Test that an expected user is available for the project ``` describe google_sql_users(project: 'chef-inspec-gcp') do its('user_names') { should include "us-east1-b" } end ``` ### Test whether any users are in status “DOWN” ``` describe google_sql_users(project: 'chef-inspec-gcp') do its('user_statuses') { should_not include "DOWN" } end ``` ### Test users exist for all database instances in a project ``` google_sql_database_instances(project: 'chef-inspec-gcp').instance_names.each do |instance_name| describe google_sql_users(project: 'chef-inspec-gcp', database: instance_name) do it { should exist } end end ``` Properties ---------- Properties that can be accessed from the `google_sql_users` resource: See the [google_sql_user](../google_sql_user/index#properties) resource for more information. `user_hosts` an array of `google_sql_user` host `user_names` an array of `google_sql_user` name `user_instances` an array of `google_sql_user` instance `passwords` an array of `google_sql_user` password Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Cloud SQL Admin API](https://console.cloud.google.com/apis/library/sqladmin.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_sql_users/google_storage_bucket_iam_policy resource ============================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_storage_bucket_iam_policy.md) Syntax ------ A `google_storage_bucket_iam_policy` is used to test a Google Bucket Iam Policy resource Examples -------- ``` describe google_storage_bucket_iam_policy(bucket: "bucket") do it { should exist } end google_storage_bucket_iam_policy(bucket: "bucket").bindings.each do |binding| describe binding do its('role') { should eq 'roles/editor'} its('members') { should include 'user:<EMAIL>'} end end ``` Properties ---------- Properties that can be accessed from the `google_storage_bucket_iam_policy` resource: `iam_binding_roles` The list of roles that exist on the policy. `bindings` Associates a list of members to a role. `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. `audit_configs` Specifies cloud audit logging configuration for this policy. `service` Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. `audit_log_configs` The configuration for logging of each type of permission. `log_type` The log type that this config enables. For example, ADMIN_READ, DATA_WRITE or DATA_READ `exempted_members` Specifies the identities that do not cause logging for this type of permission. GCP Permissions --------------- Ensure the [Google Cloud Storage](https://console.cloud.google.com/apis/library/storage-component.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_storage_bucket_iam_policy/google_storage_bucket_iam_bindings resource =============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_storage_bucket_iam_bindings.md) **This resource is deprecated. Please use `google_storage_bucket_iam_policy` instead** Use the `google_storage_bucket_iam_bindings` InSpec audit resource to test properties of all, or a filtered group of, GCP storage bucket IAM bindings. Syntax ------ A `google_storage_bucket_iam_bindings` resource block collects GCP storage bucket IAM bindings then tests that group. ``` describe google_storage_bucket_iam_bindings(bucket: 'bucket-buvsjjcndqz') do it { should exist } end ``` Use this InSpec resource to enumerate roles then test in-depth using `google_project_iam_binding`. ``` google_storage_bucket_iam_bindings(bucket: 'bucket-buvsjjcndqz').iam_binding_roles.each do |iam_binding_role| describe google_storage_bucket_iam_binding(bucket: 'bucket-buvsjjcndqz', role: iam_binding_role) do it { should exist } its('members') {should include 'user:<EMAIL>' } end end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Test that there are no more than a specified number of IAM bindings roles available for the bucket ``` describe google_storage_bucket_iam_bindings(bucket: 'bucket-buvsjjcndqz') do its('count') { should be <= 100} end ``` ### Test that an expected role is available for the bucket ``` describe google_storage_bucket_iam_bindings(bucket: 'bucket-buvsjjcndqz') do its('iam_binding_roles') { should include "roles/storage.admin" } end ``` ### Test that a particular role does not exist using filtering of the plural resource ``` describe google_storage_bucket_iam_bindings(bucket: 'bucket-buvsjjcndqz').where(iam_binding_role: "roles/iam.securityReviewer") do it { should_not exist } end ``` Filter Criteria --------------- This resource supports the following filter criteria: `iam_binding_role`. This may be used with `where`, as a block or as a method. Properties ---------- * `iam_binding_roles` - an array of google_storage_bucket_iam_binding role strings e.g. `["roles/storage.admin", "roles/owner"]` GCP Permissions --------------- Ensure the [Google Cloud Storage API](https://console.cloud.google.com/apis/api/storage-component.googleapis.com/) is enabled. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_storage_bucket_iam_bindings/google_storage_bucket_iam_binding resource ============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_storage_bucket_iam_binding.md) Syntax ------ A `google_storage_bucket_iam_binding` is used to test a Google Bucket Iam Bindings Examples -------- ``` describe google_storage_bucket_iam_binding(bucket: "bucket", role: "roles/editor") do it { should exist } its('members') { should include 'user:<EMAIL>' } end ``` Properties ---------- Properties that can be accessed from the `google_storage_bucket_iam_binding` resource: `role` Role that is assigned to members. For example, roles/viewer, roles/editor, or roles/owner. `members` Specifies the identities requesting access for a Cloud Platform resource. GCP Permissions --------------- Ensure the [Google Cloud Storage](https://console.cloud.google.com/apis/library/storage-component.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_storage_bucket_iam_binding/google_storage_buckets resource ================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_storage_buckets.md) Syntax ------ A `google_storage_buckets` is used to test a Google Bucket resource Examples -------- ``` describe google_storage_buckets(project: 'chef-gcp-inspec') do its('bucket_names') { should include bucket-name } end ``` ### Test that there are no more than a specified number of storage buckets for the project ``` describe google_storage_buckets(project: 'chef-inspec-gcp') do its('count') { should be <= 100} end ``` ### Test that an expected named bucket is available ``` describe google_storage_buckets do its('bucket_names'){ should include "my_expected_bucket" } end ``` ### Test that all buckets belong to the expected project number ``` google_storage_buckets(project: 'chef-inspec-gcp').bucket_names.each do |bucket_name| describe google_storage_bucket(name: bucket_name) do it { should exist } its('project_number'){ should eq 1122334455 } end end ``` Properties ---------- Properties that can be accessed from the `google_storage_buckets` resource: See the [google_storage_bucket](../google_storage_bucket/index#properties) resource for more information. `acls` an array of `google_storage_bucket` acl `cors` an array of `google_storage_bucket` cors `default_event_based_holds` an array of `google_storage_bucket` default_event_based_hold `default_object_acls` an array of `google_storage_bucket` default_object_acl `bucket_ids` an array of `google_storage_bucket` id `lifecycles` an array of `google_storage_bucket` lifecycle `bucket_locations` an array of `google_storage_bucket` location `loggings` an array of `google_storage_bucket` logging `metagenerations` an array of `google_storage_bucket` metageneration `bucket_names` an array of `google_storage_bucket` name `owners` an array of `google_storage_bucket` owner `bucket_project_numbers` an array of `google_storage_bucket` project_number `storage_classes` an array of `google_storage_bucket` storage_class `time_createds` an array of `google_storage_bucket` time_created `updateds` an array of `google_storage_bucket` updated `versionings` an array of `google_storage_bucket` versioning `websites` an array of `google_storage_bucket` website `labels` an array of `google_storage_bucket` labels `encryptions` an array of `google_storage_bucket` encryption `retention_policies` an array of `google_storage_bucket` retention_policy `projects` an array of `google_storage_bucket` project `predefined_default_object_acls` an array of `google_storage_bucket` predefined_default_object_acl Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Google Cloud Storage](https://console.cloud.google.com/apis/library/storage-component.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_storage_buckets/google_storage_bucket_object resource ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_storage_bucket_object.md) Syntax ------ A `google_storage_bucket_object` is used to test a Google BucketObject resource Examples -------- ``` describe google_storage_bucket_object(bucket: 'bucket-with-object', object: 'image1') do it { should exist } its('size.to_i') { should be > 0 } its('time_created') { should be > Time.now - 60*60*24*10 } its('time_updated') { should be > Time.now - 60*60*24*10 } end describe google_storage_bucket_object(bucket: 'bucket-with-object', object: "nonexistent") do it { should_not exist } end ``` ### Test that a GCP compute zone exists ``` describe google_storage_bucket_object(bucket: 'bucket-buvsjjcndqz', object: 'bucket-object-pmxbiikq') do it { should exist } end ``` ### Test that a GCP storage bucket object has non-zero size ``` describe google_storage_bucket_object(bucket: 'bucket-buvsjjcndqz', object: 'bucket-object-pmxbiikq') do its('size') { should be > 0 } end ``` ### Test that a GCP storage bucket object has the expected content type ``` describe google_storage_bucket_object(bucket: 'bucket-buvsjjcndqz', object: 'bucket-object-pmxbiikq') do its('content_type') { should eq "text/plain; charset=utf-8" } end ``` ### Test that a GCP storage bucket object was created within a certain time period ``` describe google_storage_bucket_object(bucket: 'bucket-buvsjjcndqz', object: 'bucket-object-pmxbiikq') do its('time_created_date') { should be > Time.now - 365*60*60*24*10 } end ``` ### Test that a GCP storage bucket object was last updated within a certain time period ``` describe google_storage_bucket_object(bucket: 'bucket-buvsjjcndqz', object: 'bucket-object-pmxbiikq') do its('time_updated') { should be > Time.now - 365*60*60*24*10 } end ``` Properties ---------- Properties that can be accessed from the `google_storage_bucket_object` resource: `bucket` The name of the bucket. `object` The name of the object. `content_type` The Content-Type of the object data. See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types> for more information on possible Content-Types `crc32c` CRC32c checksum. `etag` The object entity tag. `generation` The content generation of this object. Used for object versioning. `id` The ID of the object, including the bucket name, object name, and generation number. `md5_hash` MD5 hash of the data; encoded using base64. `media_link` Media download link. `metageneration` The version of the metadata for this object at this generation. Used for preconditions and for detecting changes in metadata. A metageneration number is only meaningful in the context of a particular generation of a particular object. `name` The name of the object. `size` Content-Length of the data in bytes. `storage_class` Storage class of the object. `time_created` The time this object was created. `time_deleted` The time this object was deleted. Returned if and only if this version of the object is no longer a live version, but remains in the bucket as a noncurrent version. `time_storage_class_updated` The time at which the object’s storage class was last changed. `time_updated` The modification time of the object metadata. GCP Permissions --------------- Ensure the [Google Cloud Storage](https://console.cloud.google.com/apis/library/storage-component.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_storage_bucket_object/google_storage_default_object_acl resource ============================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_storage_default_object_acl.md) Syntax ------ A `google_storage_default_object_acl` is used to test a Google DefaultObjectACL resource Examples -------- ``` describe google_storage_default_object_acl(bucket: 'gcp-inspec-storage-bucket', entity: user-email) do it { should exist } its('role') { should cmp "OWNER" } its('bucket') { should eq 'gcp-inspec-storage-bucket' } its('email') { should include entity-email.com } end describe google_storage_default_object_acl(bucket: 'gcp-inspec-storage-bucket', entity: "allUsers") do it { should_not exist } end ``` ### Test that a GCP storage bucket ACL exists ``` describe google_storage_default_object_acl(bucket: 'bucket-buvsjjcndqz', entity: 'user-object-<EMAIL>') do it { should exist } end ``` ### Test that a GCP storage default object ACL has the expected role (READER, WRITER or OWNER) ``` describe google_storage_default_object_acl(bucket: 'bucket-buvsjjcndqz', entity: '<EMAIL>') do its('role') { should eq 'OWNER' } end ``` Properties ---------- Properties that can be accessed from the `google_storage_default_object_acl` resource: `domain` The domain associated with the entity. `email` The email address associated with the entity. `entity` The entity holding the permission, in one of the following forms: _ user-{{userId}} _ user-{{email}} (such as “[<EMAIL>](mailto:<EMAIL>)”) _ group-{{groupId}} _ group-{{email}} (such as “[<EMAIL>](mailto:<EMAIL>)”) _ domain-{{domain}} (such as “domain-example.com”) _ project-team-{{projectId}} _ allUsers _ allAuthenticatedUsers `entity_id` The ID for the entity `generation` The content generation of the object, if applied to an object. `id` The ID of the access-control entry. `object` The name of the object, if applied to an object. `project_team` The project team associated with the entity `project_number` The project team associated with the entity `team` The team. Possible values: * editors * owners * viewers `role` The access permission for the entity. Possible values: * OWNER * READER GCP Permissions --------------- Ensure the [Google Cloud Storage](https://console.cloud.google.com/apis/library/storage-component.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_storage_default_object_acl/google_storage_bucket_objects resource ========================================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_storage_bucket_objects.md) Syntax ------ A `google_storage_bucket_objects` is used to test a Google BucketObject resource Examples -------- ``` describe google_storage_bucket_objects(bucket: 'bucket-with-object') do its('object_names') { should include 'image1' } its('count') { should be <= 10 } end ``` ### Test that there are no more than a specified number of storage buckets for the project ``` describe google_storage_bucket_objects(bucket: 'bucket-name') do its('count') { should be <= 100 } end ``` ### Test that an expected named bucket is available ``` describe google_storage_bucket_objects(bucket: 'bucket-name') do its('object_buckets'){ should include 'my_expected_bucket' } end ``` ### Test that an expected named bucket is available ``` describe google_storage_bucket_objects(bucket: 'bucket-name') do its('object_names'){ should include 'my_expected_object' } end ``` ### Test a filtered group of bucket objects created within the last 24hrs ``` describe google_storage_bucket_objects(bucket: 'bucket-name').where(object_created_time > Time.now - 60*60*24) do it { should exist } end ``` Properties ---------- Properties that can be accessed from the `google_storage_bucket_objects` resource: See the [google_storage_bucket_object](../google_storage_bucket_object/index#properties) resource for more information. `object_buckets` an array of `google_storage_bucket_object` bucket `objects` an array of `google_storage_bucket_object` object `content_types` an array of `google_storage_bucket_object` content_type `crc32cs` an array of `google_storage_bucket_object` crc32c `etags` an array of `google_storage_bucket_object` etag `generations` an array of `google_storage_bucket_object` generation `ids` an array of `google_storage_bucket_object` id `md5_hashes` an array of `google_storage_bucket_object` md5_hash `media_links` an array of `google_storage_bucket_object` media_link `metagenerations` an array of `google_storage_bucket_object` metageneration `object_names` an array of `google_storage_bucket_object` name `sizes` an array of `google_storage_bucket_object` size `storage_classes` an array of `google_storage_bucket_object` storage_class `object_created_times` an array of `google_storage_bucket_object` time_created `time_deleteds` an array of `google_storage_bucket_object` time_deleted `time_storage_class_updateds` an array of `google_storage_bucket_object` time_storage_class_updated `time_updateds` an array of `google_storage_bucket_object` time_updated Filter Criteria --------------- This resource supports all of the above properties as filter criteria, which can be used with `where` as a block or a method. GCP Permissions --------------- Ensure the [Google Cloud Storage](https://console.cloud.google.com/apis/library/storage-component.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_storage_bucket_objects/google_storage_object_acl resource ===================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_storage_object_acl.md) Syntax ------ A `google_storage_object_acl` is used to test a Google ObjectACL resource Examples -------- ``` describe google_storage_object_acl(bucket: 'bucket-with-object', object: 'image1', entity: user-email) do it { should exist } its('role') { should cmp "OWNER" } its('bucket') { should eq 'bucket-with-object' } its('email') { should include entity-email.com } end describe google_storage_object_acl(bucket: 'bucket-with-object', object: 'image1', entity: "allUsers") do it { should_not exist } end ``` ### Test that a GCP storage bucket ACL exists ``` describe google_storage_object_acl(bucket: 'bucket-buvsjjcndqz', object: 'bucket-object-pmxbiikq', entity: '<EMAIL>') do it { should exist } end ``` ### Test that a GCP storage object ACL has the expected role (READER, WRITER or OWNER) ``` describe google_storage_object_acl(bucket: 'bucket-buvsjjcndqz', object: 'bucket-object-pmxbiikq', entity: '<EMAIL>') do its('role') { should eq 'OWNER' } end ``` Properties ---------- Properties that can be accessed from the `google_storage_object_acl` resource: `domain` The domain associated with the entity. `email` The email address associated with the entity. `entity` The entity holding the permission, in one of the following forms: _ user-{{userId}} _ user-{{email}} (such as “[<EMAIL>](mailto:<EMAIL>)”) _ group-{{groupId}} _ group-{{email}} (such as “[<EMAIL>](mailto:<EMAIL>)”) _ domain-{{domain}} (such as “domain-example.com”) _ project-team-{{projectId}} _ allUsers _ allAuthenticatedUsers `entity_id` The ID for the entity `generation` The content generation of the object, if applied to an object. `id` The ID of the access-control entry. `object` The name of the object, if applied to an object. `project_team` The project team associated with the entity `project_number` The project team associated with the entity `team` The team. Possible values: * editors * owners * viewers `role` The access permission for the entity. Possible values: * OWNER * READER GCP Permissions --------------- Ensure the [Google Cloud Storage](https://console.cloud.google.com/apis/library/storage-component.googleapis.com/) is enabled for the current project. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_storage_object_acl/google_users resource ====================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_users.md) Use the `google_users` InSpec audit resource to test properties of all, or a filtered group of, GCP users. Syntax ------ A `google_users` resource block collects GCP users for the specified customer. As documented [here](https://developers.google.com/admin-sdk/directory/v1/reference/users/list), this defaults to the `my_customer` alias to represent your account’s `customerId`. ``` describe google_users(customer: 'my_customer') do it { should exist } end ``` The `domain` argument can optionally be provided to get fields from only one domain. Either the customer or the domain parameter must be provided. ``` describe google_users(domain: 'my_domain.com') do it { should exist } end ``` Use this InSpec resource to enumerate IDs then test in-depth using `google_user`. ``` google_users(customer: 'my_customer').user_ids.each do |user_id| describe google_user(user_key: user_id) do it { should exist } it { should_not be_suspended } end end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Test that there are no more than a specified number of users available for the project ``` describe google_users(customer: 'my_customer') do its('count') { should be <= 100} end ``` ### Test that an expected user is available for the project ``` describe google_users(customer: 'my_customer') do its('user_names') { should include "<NAME>" } end ``` ### Test that a subset of all users with name matching “Batman” exists ``` google_users(customer: 'my_customer').where(user_full_name: /Batman/).user_ids.each do |user_id| describe google_user(user_key: user_id) do it { should exist } end end ``` Filter Criteria --------------- This resource supports the following filter criteria: `user_id`; `user_full_name` and `user_email`. Any of these may be used with `where`, as a block or as a method. Properties ---------- * `user_ids` - an array of google_user identifier integers * `user_full_names` - an array of google_user full name strings * `user_emails`- an array of google_user primary email address strings GCP Permissions --------------- Ensure the G Suite Admin SDK [Directory API](https://developers.google.com/admin-sdk/directory/) is enabled and you have sufficient privileges to list users. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_users/google_user resource ===================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/google_user.md) Use the `google_user` InSpec audit resource to test properties of a single GCP user. Syntax ------ A `google_user` resource block declares the tests for a single GCP user by principal email address or immutable ID. ``` describe google_user(user_key: 'principal_email_address@domain.com') do it { should exist } end ``` Examples -------- The following examples show how to use this InSpec audit resource. ### Test that a GCP user with specified ID exists ``` describe google_user(user_key: '110491234567894702010') do it { should exist } end ``` ### Test that a GCP user has expected full name ``` describe google_user(user_key: '110491234567894702010') do its('name.full_name') { should eq "<NAME>." } end ``` ### Test that a GCP user has MFA enabled ``` describe google_user(user_key: 'theodore_ted_logan@excellentadventure.com') do it { should have_mfa_enabled } end ``` ### Test that a GCP user is suspended or not ``` describe google_user(user_key: 'theodore_ted_logan@excellentadventure.com') do it { should_not be_suspended } end ``` Properties ---------- * `agreed_to_terms`, `archived`, `change_password_at_next_login`, `creation_time`, `customer_id`, `emails`, `etag`, `id`, `include_in_global_address_list`, `ip_whitelisted`, `is_admin`, `is_delegated_admin`, `is_enforced_in2_sv`, `is_enrolled_in2_sv`, `is_mailbox_setup`, `kind`, `last_login_time`, `name`, `non_editable_aliases`, `org_unit_path`, `primary_email`, `suspended` GCP Permissions --------------- Ensure the G Suite Admin SDK [Directory API](https://developers.google.com/admin-sdk/directory/) is enabled and you have sufficient privileges to list users. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/google_user/habitat_package resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/habitat_package.md) Use the `habitat_package` InSpec audit resource to test properties of a single Habitat package. Availability ------------ ### Status: EXPERIMENTAL This resource, like all of the inspec-habitat resource pack, is in the early stages of research and development. Functionality may be defective, incomplete, or be withdrawn in the future. If you are interested in helping this project mature, please join the conversation or contribute code at the [inspec-habitat project](https://github.com/inspec/inspec-habitat). ### Connecting to Habitat To configure `inspec` to be able to communicate with Chef Habitat, be sure [to follow the instructions](https://github.com/inspec/inspec-habitat#configuring-inspec-to-reach-habitat) regarding configuring the connection options. This will prevent ‘unsupported platform’ errors. Examples -------- ### Check for core/httpd package ``` describe habitat_package(origin: 'core', name: 'httpd') do it { should exist } its('version') { should eq '2.4.35'} its('release') { should eq '20190307151146'} end ``` Limitations ----------- ### API versus CLI access Habitat exposes certain data via the CLI, and other data via the HTTP Gateway API. This resource is **only** available using CLI credentials. If you use the API interface without the CLI, instances of this resource will behave as if the sought-after package was not found. ### Behavior when not found If the package is not found, then this resource behaves as follows: * `it { should exist }` will be a failing test. Check this test if you are unsure if the resource will exist; it is guaranteed to be reliable in the future. * `name`, `origin`, `version`, and `release` will continue to return their values as set in the resource parameters. This allows output messaging to refer to the missing package clearly. * `identifier` will return as much information as it can assemble from `name`, `origin`, `version`, and `release`. * All other single-value properties will return `nil`. * All array- and hash-valued properties will return empty objects. * All matchers will return `false`. ### Behavior when multiple packages match A system can have multiple versions of the same-named package installed (or even multiple releases of the same version of the same named package). For this reason, if you under-specify the resource parameters, you may match with multiple packages. Under these conditions, this resource will throw an `ArgumentError` exception, and the resource test will be recorded as a failure. To avoid this possibility, fully specify the resource parameters, including `version` and `release`. To list all installed versions and releases of a named package, use the plural resource `habitat_packages`. Availability ------------ ### Installation This resource is in the `inspec-habitat` resource pack. You can use the resource by setting an InSpec profile dependency on this resource pack. See [inspec-habitat instructions](https://github.com/inspec/inspec-habitat#installation) ### Version This resource was first available in version 0.1.0 of the resource pack. Resource Parameters ------------------- Use [resource parameters](../../glossary/index#resource-parameter) to identify the particular package you wish to test. `habitat_package` can accept a single resource parameter, a `String` package identifier; or it can accept a `Hash` of identifier components. ### As a single `String` Using this approach, you pass the package identifier as a single `String`. It should consist of `<origin>/<name>/<version>/<release>`, though `version` and `release` are optional. ``` describe habitat_package('core/httpd') do it { should exist } end ``` ### Using individual identifier components as a `Hash` This approach can make it easier to write resource tests that use InSpec inputs or Ruby variables. #### origin `String`. The name of the `origin` (distribution facility) that provides the package. ``` # Most common origin is 'core', publicly distributed packages created by Chef describe habitat_package(origin: 'core', name: 'httpd') do it { should exist } end # Your company might run a private origin describe habitat_package(origin: 'mycorp', name: 'secret-sauce') do it { should exist } end ``` #### name `String`. The name (unique within the namespace of the origin) of the package. This may match more than one package; see [Behavior when multiple packages match](#behavior-when-multiple-packages-match). ``` describe habitat_package(origin: 'core', name: 'httpd') do it { should exist } end ``` #### release `String`, a 14-digit timestamp of the form ‘YYYMMDDHHmmSS’. The release number of the package as determined by the packager of the software. If you provide this, you must also provide the version; with all four components, the match is guarenteed to be unique. ``` describe habitat_package(origin: 'core', name: 'httpd', version: '2.3.5', release: '20190307151146') do it { should exist } end ``` #### version `String`, typically of the form `1.2.3` but formats vary. The version of the package as determined by the author of the software. This may match more than one package, because multiple releases of the same version may be co-installed; see [Behavior when multiple packages match](#behavior-when-multiple-packages-match). ``` describe habitat_package(origin: 'core', name: 'httpd', version: '2.3.5') do it { should exist } end ``` Properties ---------- Use [properties](../../glossary/index#property) to create tests that compare an expected value to the actual value. ### identifier `String`. The origin, name, version (if known) and release (if known) concatenated with `/`, to create the package identifier. ``` describe habitat_package(origin: 'core', name: 'httpd') do its('identifier') { should eq 'core/httpd/2.4.35/20190307151146' } end ``` ### name `String`. The name of the package, as passed in via the resource parameter. Always available, even if the resource was not found. See also [origin](#origin) and [version](#version). ``` describe habitat_package(origin: 'core', name: 'httpd') do its('name') { should cmp 'httpd' } end ``` ### origin `String`. The origin name of the package, as passed in via the resource parameter. Always available, even if the resource was not found. See also [name](#name) and [version](#version). ``` describe habitat_package(origin: 'core', name: 'httpd') do its('origin') { should cmp 'core' } end ``` ### pkg_id `String`. The full package identifier of the package, in the form `origin/name/version/release`. See also [name](#name) and [version](#version). ``` describe habitat_package(origin: 'core', name: 'httpd') do its('pkg_id') { should cmp 'core/httpd/2.4.35/20190307151146' } end ``` ### release `String`. The release number of the package, as assigned by the packager. These values are always strings, but are 14-digit timestamps. See also [version](#version). ``` describe habitat_package(origin: 'core', name: 'httpd') do its('release') { should be >= '20190307151146' } end ``` ### version `String`. The version of the package, as assigned by the maintainer of the package project. While many versions are of the 3-digit form, there is no set rule, and exceptions are common. See also [release](#release). ``` describe habitat_package(origin: 'core', name: 'httpd') do its('version') { should be >= '2.2' } end ``` Matchers -------- Use [matchers](../../glossary/index#matcher) to create tests that test a true or false question. InSpec includes a number of [universal matchers](../../matchers/index). See below for matchers specific to this resource. This resource does not provide any resource-specific matchers. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/habitat_package/habitat_service resource ========================= [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/habitat_service.md) Use the `habitat_service` InSpec audit resource to test properties of a single Habitat service. Availability ------------ ### Status: EXPERIMENTAL This resource, like all of the inspec-habitat resource pack, is in the early stages of research and development. Functionality may be defective, incomplete, or be withdrawn in the future. If you are interested in helping this project mature, please join the conversation or contribute code at the [inspec-habitat project](https://github.com/inspec/inspec-habitat). ### Connecting to Habitat To configure `inspec` to be able to communicate with Chef Habitat, be sure [to follow the instructions](https://github.com/inspec/inspec-habitat#configuring-inspec-to-reach-habitat) regarding configuring the connection options. This will prevent ‘unsupported platform’ errors. Examples -------- ### Check for core/httpd service ``` describe habitat_service(origin: 'core', name: 'httpd') do it { should exist } its('version') { should eq '2.4.35'} its('topology') { should eq 'standalone' } its('update_strategy') { should eq 'none' } end ``` Limitations ----------- ### API versus CLI access Habitat exposes certain data via the CLI, and other data via the HTTP Gateway API. To enjoy the full functionality of this resource, use a set of credentials that includes the API. Limited data is available by CLI. See the [train-habitat](https://github.com/inspec/train-habitat) documentation for more details. If you use the CLI interface without the API, unavailable properties will behave as if the resource was not found (see below). ### Behavior when not found If the service is not found, then this resource behaves as follows: * `it { should exist }` will be a failing test. Check this test if you are unsure if the resource will exist; it is guaranteed to be reliable in the future. * `name` and `origin` will continue to return their values as set in the resource parameters. This allows output messaging to refer to the missing service clearly. * All other single-value properties will return nil. * All array and hash-valued properties will return empty objects. * All matchers will return false. Availability ------------ ### Installation This resource is in the `inspec-habitat` resource pack. You can use the resource by setting an InSpec profile dependency on the resource pack. See [inspec-habitat instructions](https://github.com/inspec/inspec-habitat#installation) ### Version This resource was first available in version 0.1.0 of the resource pack. Resource Parameters ------------------- Use [resource parameters](../../glossary/index#resource-parameter) to identify the particular service you wish to test. ### origin Required string. The name of the `origin` (distribution facility) of the package that provides the service. ``` # Most common origin is 'core', publicly distributed packages created by Chef describe habitat_service(origin: 'core', name: 'httpd') do it { should exist } end # Your company might run a private origin describe habitat_service(origin: 'mycorp', name: 'secret-sauce') do it { should exist } end ``` ### name Required string. The name (unique within the namespace of the origin) of the package that provides the service. ``` describe habitat_service(origin: 'core', name: 'httpd') do it { should exist } end ``` Properties ---------- Use [properties](../../glossary/index#property) to create tests that compare an expected value to the actual value. ### dependency_names Array of strings. A list of the packages that this service depends on, in the form of `dep_origin/dep_name`. This property does not contain version information; see `dependency_ids` for that. Requires API connection; not available via CLI. ``` describe habitat_service(origin: 'core', name: 'httpd') do its('dependency_names') { should include 'core/pcre' } its('dependency_names') { should_not include 'core/nginx' } end ``` ### dependency_ids Array of strings. A list of the packages that this service depends on, in the form of `dep_origin/dep_name/1.2.3/20190325123456`. This value may be difficult to compare, because the version identifier (`1.2.3`, the third component) may be formatted in any way the maintainer of the project chooses; they need not be of the form `1.2.3`. Requires API connection; not available via CLI. ``` describe habitat_service(origin: 'core', name: 'httpd') do # Suppose this version was unwanted, for example its('dependency_names') { should_not include 'core/pcre/8.42/20190115012526' } end ``` ### name The name of the service, as passed in via the resource parameter. Always available, even if the resource was not found. See also [origin](#origin) and [version](#version). ``` describe habitat_service(origin: 'core', name: 'httpd') do its('name') { should cmp 'httpd' } end ``` ### origin The origin name of the service, as passed in via the resource parameter. Always available, even if the resource was not found. See also [name](#name) and [version](#version). ``` describe habitat_service(origin: 'core', name: 'httpd') do its('origin') { should cmp 'core' } end ``` ### pkg_id String. The full package identifier of the package that supports the service, in the form `origin/name/version/release`. See also [name](#name) and [version](#version). ``` describe habitat_service(origin: 'core', name: 'httpd') do its('pkg_id') { should cmp 'core/httpd/2.4.35/20190307151146' } end ``` ### release String. The release number of the package that supports the service, as assigned by the packager. These values are always strings, but are 14-digit timestamps. See also [version](#version). ``` describe habitat_service(origin: 'core', name: 'httpd') do its('release') { should be >= '20190307151146' } end ``` ### version The version of the package that supports the service, as assigned by the maintainer of the package project. While many versions are of the 3-digit form, there is no set rule, and exceptions are common. See also [release](#release). ``` describe habitat_service(origin: 'core', name: 'httpd') do its('version') { should be >= '2.2' } end ``` Matchers -------- Use [matchers](../../glossary/index#matcher) to create tests that test a true or false question. InSpec includes a number of [universal matchers](../../matchers/index). See below for matchers specific to this resource. ### have_standalone_topology This matcher returns `true` if the service is configured in a [`standalone`](https://www.habitat.sh/docs/using-habitat/#standalone) topology. ``` describe habitat_service(origin: 'core', name: 'httpd') do it { should have_standalone_topology } end ``` ### have_leader_follower_topology This matcher returns `true` if the service is configured in a [`leader-follower`](https://www.habitat.sh/docs/using-habitat/#leader-follower-topology) topology. ``` describe habitat_service(origin: 'core', name: 'httpd') do it { should have_leader_follower_topology } end ``` ### be_updated_by_none This matcher returns `true` if the update strategy for the service is [`none`](https://www.habitat.sh/docs/using-habitat/#none-strategy). Requires API connection; not available via CLI. ``` describe habitat_service(origin: 'core', name: 'postgresql') do it { should be_updated_by_none } end ``` ### be_updated_by_rolling This matcher returns `true` if the update strategy for the service is [`rolling`](https://www.habitat.sh/docs/using-habitat/#rolling-strategy). Requires API connection; not available via CLI. ``` describe habitat_service(origin: 'core', name: 'postgresql') do it { should be_updated_by_rolling } end ``` ### be_updated_at_once This matcher returns `true` if the update strategy for the service is [`at once`](https://www.habitat.sh/docs/using-habitat/#at-once-strategy). Requires API connection; not available via CLI. ``` describe habitat_service(origin: 'core', name: 'nginx') do it { should be_updated_at_once } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/habitat_service/habitat_packages resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/habitat_packages.md) Use the `habitat_package` (singular) InSpec audit resource to perform in-depth auditing of a single package. Use the `habitat_packages` (plural) InSpec audit resource to list Habitat packages, and perform bulk operations. Availability ------------ ### Status: EXPERIMENTAL This resource, like all of the inspec-habitat resource pack, is in the early stages of research and development. Functionality may be defective, incomplete, or be withdrawn in the future. If you are interested in helping this project mature, please join the conversation or contribute code at the [inspec-habitat project](https://github.com/inspec/inspec-habitat). ### Connecting to Habitat To configure `inspec` to be able to communicate with Chef Habitat, be sure [to follow the instructions](https://github.com/inspec/inspec-habitat#configuring-inspec-to-reach-habitat) regarding configuring the connection options. This will prevent ‘unsupported platform’ errors. Examples -------- ### Ensure httpd and memcached are installed ``` describe habitat_packages do its('names') { should include 'httpd' } its('names') { should include 'memcached' } end ``` ### Ensure all packages were updated since January 1, 2018 ``` describe habitat_packages.where { release <= '20180101000000' } do it { should_not exist } end ``` ### Search for packages, then examine them in detail using `habitat_package` ``` # Use the plural resource as a data lookup (not as a test)... habitat_packages.where { origin != 'core' }.habitat_package_params.each do |params| # ... then use the singular resource to do in-depth testing describe habitat_package(params) do # ... end end ``` Limitations ----------- ### API versus CLI access Habitat exposes certain data via the CLI, and other data via the HTTP Gateway API. This resource is not available via the API; you must provide CLI credentials to use the resource. See the [train-habitat](https://github.com/inspec/train-habitat) documentation for more details. If you use this resource without the CLI, this resource will always return zero matches. Availability ------------ ### Installation This resource is in the `inspec-habitat` resource pack. You can use this resource by setting an InSpec profile dependency on the resource pack. See [inspec-habitat instructions](https://github.com/inspec/inspec-habitat#installation). ### Version This resource was first available in version 0.1.0 of the resource pack. Resource Parameters ------------------- [Resource parameters](../../glossary/index#resource-parameter) are arguments passed to the resource in the control code. This resource does not accept resource parameters, which is typical for plural resources. Filter Criteria --------------- [Filter criteria](../../glossary/index#filter-criteria) are used to select which packages you wish to examine. If no filter criteria are used, all packages are selected. ### name String. The (unqualified) name of the package under consideration. ``` # No packages named *ftp* permitted describe habitat_packages.where(name: /ftp/) do it { should_not exist } end ``` ### origin String. The name of the origin that created the package under consideration. ``` # Examine only packages released by Chef describe habitat_packages.where(origin: 'bad-origin') do it { should_not exist } end ``` ### release String. A 14-digit timestamp, in the format `YYYYMMDDHHMmmSS`. The timestamp reflects the time at which the package backing the package was released. These strings are sortable and comparable. ``` # Examine packages older than Jan 1 2018 describe habitat_packages.where { release < '20180101000000' } do it { should_not exist } end # Examine packages older than 1 year describe habitat_packages.where { Date.parse(release[0..7]) < Date.today - 365 } do it { should_not exist } end # Another way describe habitat_packages.where { release < (Date.today - 365).strftime('%Y%m%d000000') } do it { should_not exist } end ``` Properties ---------- Use [properties](../../glossary/index#property) to create tests that compare an expected value to the actual value. ### count Number. The count of packages that matched the filter criteria. ``` # Expect 12 total describe habitat_packages do its(count) { should cmp 12 } end ``` ### habitat_package_params `Array` of `Hash`es. Returns a list of a set of options that can be passed directly to `habitat_package` (singular) to load an individual package for in-depth analysis. ``` # Use the plural resource as a data lookup (not as a test)... habitat_packages.where { origin != 'core' }.habitat_package_params.each do |params| # ... then use the singular resource to do in-depth testing describe habitat_package(params) do its('release') { should_not be < '201904090000' } end end ``` ### names Array of strings. The unqualified name of the package, such as ‘httpd’. This list is de-duplicated, though a name is almost always unique anyway. ``` describe habitat_packages do its('names') { should include 'httpd' } its('names') { should include 'memcached' } its('names') { should_not include 'telnetd' } end ``` ### origins Array of strings. The names of the origins that created the matched packages. This list is de-duplicated. ``` # Only allow core and mycorp-packaged packages describe habitat_packages do its('origins') { should include 'core' } its('origins') { should include 'mycorp' } # Advanced usage - count an array-valued property its('origins', 'count') { should cmp 2 } end ``` ### releases Array of strings. Each string is a 14-digit timestamp, in the format `YYYYMMDDHHMmmSS`. The timestamp reflects the time at which the package backing the package was released. These strings are sortable and comparable. This list is de-duplicated. ``` # We had a bad Monday describe habitat_packages do its('releases') { should_not include '20180325000000' } end ``` Matchers -------- Use [matchers](../../glossary/index#matcher) to create tests that test a true or false question. InSpec includes a number of [universal matchers](../../matchers/index). This resource does not define any resource-specific matchers. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/habitat_packages/About Chef Workstation ====================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/_index.md) Start your infrastructure automation quickly and easily with [Chef Workstation](index). Chef Workstation gives you everything you need to get started with Chef - ad hoc remote execution, remote scanning, configuration tasks, cookbook creation tools as well as robust dependency and testing software - all in one easy-to-install package. Chef Workstation includes: * Chef Infra Client * Chef InSpec * Chef Habitat * chef and knife command line tools * Testing tools such as Test Kitchen and Cookstyle * Everything else needed to author cookbooks and upload them to the Chef Infra Server Chef Workstation replaces ChefDK, combining all the existing features with new features, such as ad-hoc task support and the new Chef Workstation desktop application. Getting Started --------------- Chef Infra is a systems and cloud infrastructure automation framework that makes it easy to deploy servers and applications to any physical, virtual, or cloud location, no matter the size of the infrastructure. Each organization is comprised of one (or more) Chef Workstation installations, a single server, and every node that will be configured and maintained by Chef Infra Client. Cookbooks (and recipes) are used to tell Chef Infra Client how each node in your organization should be configured. Chef Infra Client—which is installed on every node—does the actual configuration. * [An Overview of Chef Infra](../chef_overview/index) * [Install Chef Workstation](install_workstation/index) ### Cookbook Development Workflow Chef Infra defines a common workflow for cookbook development: 1. Create a skeleton cookbook by running `chef generate cookbook MY_COOKBOOK_NAME`. This generates a cookbook with a single recipe and testing configuration for Test Kitchen with Chef InSpec. 2. Write cookbook recipes or resources and lint and debug them with Cookstyle and Test Kitchen. Making your own cookbooks is an iterative process where you develop, test, find and fix bugs, and then develop and test some more. A text editor—Visual Studio Code, Atom, vim, or any other preferred text editor—is the only tool that you need to author your cookbooks. 3. Test in acceptance. Test your work in an environment that matches your production environment as closely as possible. 4. Deploy your cookbooks to the production environment, but only after they pass all the acceptance tests and are verified to work in the desired manner. Tools ----- Chef Workstation packages all the tools necessary to be successful with Chef Infra and InSpec. These tools are combined into packages for common operating systems and include all the dependencies you need to get started. The most important tools included in Chef Workstation are: | Tool | Description | | --- | --- | | Chef CLI | A workflow tool for Chef Infra. | | knife | A tool for managing systems on the Chef Infra Server. | | Chef Infra Client | The Chef Infra agent. | | Chef InSpec | A compliance as code tool that can also be used for testing Chef Infra cookbooks. | | Cookstyle | A linting tool that helps you write better Chef Infra cookbooks by detecting and automatically correcting style, syntax, and logic mistakes in your code. | | Test Kitchen | An integration testing framework tool that tests cookbooks across platforms and various cloud provider / hypervisors. | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/habitat_services resource ========================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/habitat_services.md) Use the `habitat_service` (singular) InSpec audit resource to perform in-depth auditing of a single service. Use the `habitat_services` (plural) InSpec audit resource to list Habitat services, and perform bulk operations. Availability ------------ ### Status: EXPERIMENTAL This resource, like all of the inspec-habitat resource pack, is in the early stages of research and development. Functionality may be defective, incomplete, or be withdrawn in the future. If you are interested in helping this project mature, please join the conversation or contribute code at the [inspec-habitat project](https://github.com/inspec/inspec-habitat). ### Connecting to Habitat To configure `inspec` to be able to communicate with Chef Habitat, be sure [to follow the instructions](https://github.com/inspec/inspec-habitat#configuring-inspec-to-reach-habitat) regarding configuring the connection options. This will prevent ‘unsupported platform’ errors. Examples -------- ### Ensure there are 2 services, with the expected names ``` describe habitat_services do its('count') { should cmp 2 } its('names') { should include 'httpd' } its('names') { should include 'memcached' } end ``` ### Ensure all running services were updated since January 1, 2018 ``` describe habitat_services.where { release <= '20180101000000' } do it { should_not exist } end ``` ### Ensure gcc is not a dependency of any service ``` # One way - list all services, insist none have a dependency on gcc describe habitat_services do its('dependency_names') { should_not include 'core/gcc' } end # Another way - list all services with a dependency on gcc, insist there are none describe habitat_services.where { dependency_names.include?('core/gcc') } do it { should_not exist } end ``` ### Search for services, then examine them in detail using `habitat_service` ``` # Use the plural resource as a data lookup (not as a test)... habitat_services.where { origin != 'core' }.habitat_service_params.each do |params| # ... then use the singular resource to do in-depth testing describe habitat_service(params) do its('release') { should_not be_standalone } end end ``` Limitations ----------- ### API versus CLI access Habitat exposes certain data via the CLI, and other data via the HTTP Gateway API. To enjoy the full functionality of this resource, use a set of credentials that includes the API. Limited data is available by CLI. See the [train-habitat](https://github.com/inspec/train-habitat) documentation for more details. If you use the CLI interface without the API, unavailable properties will return empty arrays or `nil`, and unavailable filter criteria will never match. See each property and filter criteria for details. Availability ------------ ### Installation This resource is in the `inspec-habitat` resource pack. You can use the resource by setting an InSpec profile dependency on the resource pack. See [inspec-habitat instructions](https://github.com/inspec/inspec-habitat#installation). ### Version This resource was first available in version 0.1.0 of the resource pack. Resource Parameters ------------------- [Resource parameters](../../glossary/index#resource-parameter) are arguments passed to the resource in the control code. This resource does not accept resource parameters, which is typical for plural resources. Filter Criteria --------------- [Filter criteria](../../glossary/index#filter-criteria) are used to select which services you wish to examine. If no filter criteria are used, all services are selected. ### dependency_names An array of strings in the form `origin/name`. Each string is the qualified name of a dependency of a service that is being filtered. Requires API connection; not available (never matches) via CLI. ``` describe habitat_services.where { dependency_names.include?('core/gcc') } do it { should_not exist } end ``` ### name String. The (unqualified) name of the service under consideration. ``` # No services named *ftp* permitted describe habitat_services.where(name: /ftp/) do it { should_not exist } end ``` ### origin String. The name of the origin that created the package that backs the service under consideration. ``` # Examine only services released by Chef describe habitat_services.where(origin: 'chef') do its('topologies') { should_not include 'standalone' } end ``` ### release String. A 14-digit timestamp, in the format `YYYYMMDDHHMmmSS`. The timestamp reflects the time at which the package backing the service was released. These strings are sortable and comparable. ``` # Examine packages older than Jan 1 2018 describe habitat_services.where { release < '20180101000000' } do its('update_strategies' ) { should_not include 'none' } end # Examine packages older than 1 year describe habitat_services.where { Date.parse(release[0..7]) < Date.today - 365 } do its('update_strategies' ) { should_not include 'none' } end # Another way describe habitat_services.where { release < (Date.today - 365).strftime('%Y%m%d000000') } do its('update_strategies' ) { should_not include 'none' } end ``` ### topology String reflecting the topology of the service. Values include `standalone` and `leader` (for leader-follower). See [the Habitat docs](https://www.habitat.sh/docs/using-habitat/#topologies) for implications of these values. ``` # HA or the highway describe habitat_services.where(topology: 'standalone') do it { should_not exist } end ``` ### update_strategy String reflecting how the software package backing the service should be updated. Values include `none`, `rolling`, and `at-once`. See [the Habitat docs](https://www.habitat.sh/docs/using-habitat/#using-updates) for implications of these values. Requires API connection; not available (never matches) via CLI. ``` # No YOLO describe habitat_services.where(update_strategy: 'at-once') do it { should_not exist } end ``` Properties ---------- Use [properties](../../glossary/index#property) to create tests that compare an expected to value to the actual value. ### count Number. The count of services that matched the filter criteria. ``` # Expect 12 total describe habitat_services do its(count) { should cmp 12 } end describe habitat_services.where(update_strategy: 'at-once') do it { should_not exist } its(count) { should cmp 0 } # Same as `should_not exist` end ``` ### dependency_names Array of strings in the form `origin/name`. Each string is the qualified name of a dependency of a service that was selected by the filter criteria. This list is de-duplicated. Requires API connection; not available (always an empty array) via CLI. ``` describe habitat_services do its('dependency_names') { should_not include 'core/gcc' } end ``` ### habitat_service_params Hash. Returns a set of options that can be passed directly to `habitat_service` (singular) to load an individual service for in-depth analysis. ``` # Use the plural resource as a data lookup (not as a test)... habitat_services.where { origin != 'core' }.habitat_service_params.each do |params| # ... then use the singular resource to do in-depth testing describe habitat_service(params) do its('release') { should_not be_standalone } end end ``` ### names Array of strings. The unqualified name of the service, such as ‘httpd’. This list is de-duplicated, though a name is almost always unique anyway. ``` describe habitat_services do its('names') { should include 'httpd' } its('names') { should include 'memcached' } its('names') { should_not include 'telnetd' } end ``` ### origins Array of strings. The names of the origins that created the packages that backs the services that were matched. This list is de-duplicated. ``` # Only allow core and mycorp-packaged services describe habitat_services do its('origins') { should include 'core' } its('origins') { should include 'mycorp' } # Advanced usage - count an array-valued property its('origins', 'count') { should cmp 2 } end ``` ### releases Array of strings. Each string is a 14-digit timestamp, in the format `YYYYMMDDHHMmmSS`. The timestamp reflects the time at which the package backing the service was released. These strings are sortable and comparable. This list is de-duplicated. ``` # We had a bad Monday describe habitat_services do its('releases') { should_not include '20180325000000' } end ``` ### topologies Array of strings reflecting the topology of the matched services. Values include `standalone` and `leader` (for leader-follower). See [the Habitat docs](https://www.habitat.sh/docs/using-habitat/#topologies) for implications of these values. This list is de-duplicated. ``` describe habitat_services do its('topologies') { should_not include 'standalone' } end ``` ### update_strategies Array of strings reflecting how the software package backing the services that matched the filter should be updated. Values include `none`, `rolling`, and `at-once`. See [the Habitat docs](https://www.habitat.sh/docs/using-habitat/#using-updates) for implications of these values. This list is de-duplicated. Requires API connection; not available (never matches) via CLI. ``` # No YOLO describe habitat_services do its('update_strategies') { should_not include 'at-once' } end ``` Matchers -------- Use [matchers](../../glossary/index#matcher) to create tests that test a true or false question. InSpec includes a number of [universal matchers](../../matchers/index). This resource does not define any resource-specific matchers. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/habitat_services/Setup Chef Workstation ====================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/getting_started.md) This guide walks your through the four parts to set up Chef Workstation on your computer. * [Configure Ruby Environment](#configure-ruby-environment) * [Set up your chef-repo](#setup-your-chef-repo) for storing your cookbooks * [Setup Chef Credentials](#setup-chef-credentials) * [Verify Client-to-Server Communication](#Verify%20Client-to-Server%20Communication) Prerequisites ------------- 1. [Download and install Chef Workstation](../install_workstation/index) 2. A running instance of [Chef Infra Server](../../server/install_server/index) or [Hosted Chef Server](https://manage.chef.io/signup). 3. Unless using Chef Manage or Hosted Chef, the `CLIENT.PEM` file supplied by your Chef administrator. Configure Ruby Environment -------------------------- For many users, Ruby is primarily used for developing Chef policy (for example, cookbooks, Policyfiles, and Chef InSpec profiles). If that’s true for you, then we recommend using the Chef Workstation Ruby as your default system Ruby. If you use Ruby for software development, you’ll want to skip this step. Note These instructions are intended for macOS and Linux users. On Windows, Chef Workstation includes a desktop shortcut to a PowerShell prompt already configured for use. 1. Determine your default shell by running: ``` echo $SHELL ``` This will give you the path to your default shell such as `/bin/zsh` for the Zsh shell. 2. Add the Workstation initialization content to the appropriate shell rc file: For Bash shells run: ``` echo 'eval "$(chef shell-init bash)"' >> ~/.bashrc ``` For Zsh shells run: ``` echo 'eval "$(chef shell-init zsh)"' >> ~/.zshrc ``` For Fish shells run: ``` echo 'eval (chef shell-init fish)' >> ~/.config/fish/config.fish ``` 3. Open a new shell window and run: ``` which ruby ``` The command should return `/opt/chef-workstation/embedded/bin/ruby`. Setup Your Chef Repo -------------------- If you’re setting up Chef for the very first time **in your organization**, then you will need a Chef Infra repository for saving your cookbooks and other work. The chef-repo is a directory on your workstation that stores everything you need to define your infrastructure with Chef Infra: * Cookbooks (including recipes, attributes, custom resources, libraries, and templates) * Data bags * Policyfiles The chef-repo directory should be synchronized with a version control system, such as git. All of the data in the chef-repo should be treated like source code. You’ll use the `chef` and `knife` commands to upload data to the Chef Infra Server from the chef-repo directory. Once uploaded, Chef Infra Client uses that data to manage the nodes registered with the Chef Infra Server and to ensure that it applies the right cookbooks, policyfiles, and settings to the right nodes in the right order. Use the [chef generate repo](../ctl_chef/index#chef-generate-repo) command to create your Chef Infra repository. For example, to create a repository called `chef-repo`: ``` chef generate repo chef-repo ``` Setup Chef Credentials ---------------------- The first time you run the Chef Workstation app, it creates a `.chef` directory in your user directory. The `.chef` directory is where you will store your Chef Workstation configuration and your client keys. If you’re setting up Chef Workstation **as a Chef Infra Server administrator**, then you will need to manage users with the [Chef Infra Server CLI](../../server/ctl_chef_server/index#user-management) or the Manage UI. When you create a new user, a user-specific RSA client key will be generated, which you then need to share securely with that user. If you’re setting up Chef Workstation **as a Chef user**, then you will need to setup your unique client private key that corresponds to a client on the Chef Infra Server that your server administrator creates for you. The client private key is an RSA private key in the `.pem` format. ### Configure Your User Credentials File Your `.chef` directory contains a `credentials` file used to communicate with the Chef Infra Server. You can generate this file by running `knife configure` and following the prompts. The `knife configure` command requires the following values: * `Chef Server URL`: the full URL to your Chef Infra Server including the org * `Client Name`: the client name your server administrator created for you Your Chef administrator should provide this information. For Hosted Chef or Chef Manage, you can find this information in the Starter Kit file. Download the file on the Manage site by navigating to the Administration tab and selecting Starter Kit. (**Manage > Administration > Starter Kit > Download Starter Kit**) Find the `.chef/config.rb` file in the Starter Kit. It should look like: ``` current_dir = File.dirname(__FILE__) log_level :info log_location STDOUT node_name "hshefu" client_key "#{current_dir}/hshefu.pem" chef_server_url "https://api.chef.io/organizations/4thcafe-web-team" cookbook_path ["#{current_dir}/../cookbooks"] ``` Use the `chef_server_url` and `node_name` values from this file when running `knife configure`. ### Setup Your Client Private Key All communication between Chef Workstation and the Chef Infra Server is authenticated using an RSA public/private key pair. This pair is generated on the Chef Infra Server and the private key must be copied to your local Chef Workstation installation for communication to function. The steps for downloading or generating these files vary depending on how you interact with Chef Infra Server. Select the option that best describes how you interact with the server: * [Chef Infra Server / Automate](#infra_and_automate_keys) * [Hosted Chef / Manage](#hosted-keys) Your Chef administrator will provide you with your client.pem file. Copy this file to the `~/.chef` directory. On macOS and Linux systems this looks something like: ``` cp ~/Downloads/MY_NAME.pem ~/.chef/ ``` On Windows systems this will look something like this: ``` Copy-Item -Path C:\Users\MY_NAME\Downloads\MY_NAME.pem -Destination C:\Users\MY_NAME\.chef\ ``` The client key file is located in the Starter Kit at `.chef/MY_NAME.pem`. Copy the .pem file to the `~/.chef` directory. On macOS and Linux systems this looks something like: ``` cp ~/Downloads/chef-repo/.chef/MY_NAME.pem ~/.chef/ ``` On Windows systems this will look something like this: ``` Copy-Item -Path C:\Users\MY_NAME\Downloads\chef-repo\.chef\MY_NAME.pem -Destination C:\Users\MY_NAME\.chef\ ``` Verify Client-to-Server Communication ------------------------------------- To verify that Chef Workstation can connect to the Chef Infra Server: Run the following command on the command line: ``` knife client list ``` Which should return a list of clients similar to: ``` chef_machine registered_node ``` ### Fetch Self Signed Certificates If the Chef Infra Server you’re configured to use has a self signed certificate, you’ll use the `knife ssl fetch` subcommand to download the the Chef Infra Server TLS/SSL certificate and save it in your `.chef/trusted_certs`. Chef Infra verifies the security of all requests made to the server from tools such a knife and Chef Infra Client. The certificate that is generated during the installation of the Chef Infra Server is self-signed, which means there isn’t a signing certificate authority (CA) to verify. In addition, this certificate must be downloaded to any machine from which knife and/or Chef Infra Client will make requests to the Chef Infra Server. Use the `knife ssl fetch` subcommand to pull the SSL certificate down from the Chef Infra Server: ``` knife ssl fetch ``` See [SSL Certificates](../../chef_client_security/index#ssl-certificates) for more information about how knife and Chef Infra Client use SSL certificates generated by the Chef Infra Server. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/getting_started/Install Chef Workstation ======================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/install_workstation.md) Start your infrastructure automation quickly and easily with [Chef Workstation](../index). Chef Workstation gives you everything you need to get started with Chef - ad hoc remote execution, remote scanning, configuration tasks, cookbook creation tools as well as robust dependency and testing software - all in one easy-to-install package. Chef Workstation includes: * Chef Infra Client * Chef InSpec * Chef Habitat * chef and knife command line tools * Testing tools such as Test Kitchen and Cookstyle * Everything else needed to author cookbooks and upload them to the Chef Infra Server Supported Platforms ------------------- Supported Host Operating Systems: | Platform | Version | | --- | --- | | Amazon Linux | 2 | | Apple macOS | 10.15, 11, 12 | | Microsoft Windows | 10, 11, Server 2012, Server 2012 R2, Server 2016, Server 2019, Server 2022 | | Red Hat Enterprise Linux / CentOS | 7.x, 8.x | | Ubuntu | 16.04, 18.04, 20.04 | | Debian | 9, 10, 11 | System Requirements ------------------- Minimum system requirements: * RAM: 4GB * Disk: 8GB * Additional memory and storage space may be necessary to take advantage of Chef Workstation tools such as Test Kitchen which creates and manages virtualized test environments. Additional Chef Workstation App Requirements: * On Linux you must have a graphical window manager running with support for system tray icons. For some distributions you may also need to install additional libraries. After you install the Chef Workstation package from the terminal, the post-install message will tell you which, if any, additional libraries are required to run the Chef Workstation App. Installation ------------ The Chef Workstation installer must run as a privileged user. Chef Workstation installs to `/opt/chef-workstation/` on macOS / Linux and `C:\opscode\chef-workstation\` on Windows. These file locations help avoid interference between these components and other applications that may be running on the target machine. ### macOS Install 1. Visit the [Chef Workstation downloads page](https://www.chef.io/downloads/tools/workstation?os=mac_os_x) and select the appropriate package for your macOS version. Select on the **Download** button. 2. Follow the steps to accept the license and install Chef Workstation. Alternately, install Chef Workstation using the [Homebrew](https://brew.sh/) package manager: `brew install --cask chef-workstation` ### Windows Install 1. Visit the [Chef Workstation downloads page](https://www.chef.io/downloads/tools/workstation?os=windows) and select the appropriate package for your Windows version. Click on the **Download** button. 2. Follow the steps to accept the license and install Chef Workstation. You will have the option to change your install location; by default the installer uses the `C:\opscode\chef-workstation\` directory. 3. **Optional:** Set the default shell. On Microsoft Windows it is strongly recommended to use Windows PowerShell instead of `cmd.exe`. Alternately, install Chef Workstation using the [Chocolatey](https://chocolatey.org/) package manager: `choco install chef-workstation` #### Headless Unattended Install “Headless” systems are configured to operate without a monitor (the “head”) keyboard, and mouse. They are usually administered remotely using protocols such as SSH or WinRM. Chef Workstation can be installed on a headless system using the `msiexec` command and flags to skip the installation of the Chef Workstation Application, which requires a GUI. Run the following command in Windows PowerShell or `cmd.exe`, replacing `MsiPath` with the path of the downloaded Chef Workstation installer. ``` msiexec /q /i MsiPath ADDLOCAL=ALL REMOVE=ChefWSApp ``` #### Spaces and Directories Directories that are used by Chef products on Windows cannot have spaces. For example, `C:\Users\User Name` will not work, but `C:\Users\UserName` will. Chef commands may fail if used against a directory with a space in its name. #### Top-level Directory Names Windows will throw errors when path name lengths are too long. For this reason, it’s often helpful to use a very short top-level directory, much like what is done in UNIX and Linux. For example, Chef uses `/opt/` to install Chef Workstation on macOS. A similar approach can be done on Microsoft Windows, by creating a top-level directory with a short name. For example: `C:\chef`. ### Linux 1. Visit the [Chef Workstation downloads page](https://www.chef.io/downloads/tools/workstation) and download the appropriate package for your distribution: * Red Hat Enterprise Linux ``` wget https://packages.chef.io/files/stable/chef-workstation/21.10.640/el/8/chef-workstation-21.10.640-1.el8.x86_64.rpm ``` * Debian/Ubuntu ``` wget https://packages.chef.io/files/stable/chef-workstation/21.10.640/ubuntu/20.04/chef-workstation_21.10.640-1_amd64.deb ``` 2. Use your distribution’s package manager to install Chef Workstation: * Red Hat Enterprise Linux: ``` yum localinstall chef-workstation-21.10.640-1.el8.x86_64.rpm ``` * Debian/Ubuntu: ``` dpkg -i chef-workstation_21.10.640-1_amd64.deb ``` Verify the Installation ----------------------- To verify the installation, run: ``` chef -v ``` Which returns the versions of all installed Chef tools: ``` Chef Workstation version: 21.10.640 Chef Infra Client version: 17.6.18 Chef InSpec version: 4.46.13 Chef CLI version: 5.4.2 Chef Habitat version: 1.6.351 Test Kitchen version: 3.1.0 Cookstyle version: 7.25.6 ``` Upgrading --------- To upgrade from ChefDK or an earlier release of Chef Workstation, follow the instructions provided under [Installing](index). Uninstalling ------------ ### Mac Uninstall Run `uninstall_chef_workstation` in your terminal. ### Windows Uninstall Use **Add / Remove Programs** to remove Chef Workstation. ### Linux Uninstall Ubuntu, Debian, and related: ``` sudo dpkg -P chef-workstation ``` Red Hat, CentOS, and related: ``` sudo yum remove chef-workstation ``` Next Steps ---------- Now that you’ve installed Chef Workstation, proceed to the [Setup](../getting_started/index) guide to configure your Chef Workstation installation. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/install_workstation/Troubleshooting =============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/troubleshooting.md) Chef Workstation Logs --------------------- Chef Workstation logs are stored in `~/.chef-workstation/logs`. Uninstall instructions ---------------------- Follow the steps provided under [Uninstalling](../install_workstation/index#uninstalling). Common Error Codes ------------------ ### CHEFINT001 ``` CHEFINT001 An remote error has occurred: Your SSH Agent has no keys added, and you have not specified a password or a key file. ``` This error now appears as CHEFTRN007. If you’re running an older version of chef-run it will appear as CHEFINT001 with the message above. Follow the steps detailed under CHEFTRN007 below to resolve. ### CHEFTRN007 `No authentication methods available` This error occurs when there are no available ssh authentication methods to provide to the server. chef-run requires a password, a key file, or a `.ssh/config` host entry containing a KeyFile. Information about each option is below. #### resolve via chef-run flags Use `--password` to provide the password required to authenticate to the host: ``` chef-run --password $PASSWORD myhost.example.com --password ``` Alternatively, explicitly provide an identity file using ‘–identity-file’: ``` chef-run --identity-file /path/to/your/ssh/key ``` #### resolve by adding key(s) to ssh-agent ``` ## ensure ssh-agent is running. This may report it is already started: $ ssh-agent ## Add your key file(s): $ ssh-add Identity added: /home/timmy/.ssh/id_rsa (/home/timmy/.ssh/id_rsa) ``` ### resolve by adding a host entry to ~/.ssh/config Add an entry for this host to your .ssh/config: ``` host example.com IdentityFile /path/to/valid/key ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/troubleshooting/Configure Chef Workstation ========================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/config.md) Configuration ============= Chef Workstation App and `chef-run` configuration is managed in `config.toml`. Chef Workstation will create `config.toml` the first time you use `chef-run`, if one does not already exist. To configure other tools, see their respective pages found in the toolbar under Chef Workstation Tools. Default location ---------------- Chef Workstation looks for the `config.toml` in a default location. ### Windows * Powershell: `$env:USERPROFILE\.chef-workstation\config.toml` * cmd.exe: `%USERPROFILE%\.chef-workstation\config.toml` ### Linux and Mac `/home/$USER/.chef-workstation/config.toml` Settings -------- ### Telemetry Configure telemetry behaviors for Chef Workstation components. #### Example ``` [telemetry] enable = true dev = false ``` #### enable Description When `true`, anonymous usage data and bug reports are sent to Chef. See Chef’s [Privacy Statement](../privacy/index) for the type and usage of gathered data. Value `true`, `false` Default `true` Used by `chef-run` `CHEF_TELEMETRY_OPT_OUT` When set to any value, `chef-run` will not capture or send telemetry data. #### dev Description When set to any value, `chef-run` will not capture or send telemetry data. Only set this if you have access to Chef’s internal QA environment - otherwise the telemetry data will not be successfully captured by Chef. If you have access to Chef’s internal QA environment, if `dev` and `enable` are both `true`, anonymous data is reported to Chef’s QA environment. Values `true`, `false` Default `false` Used by `chef-run`, `Chef Workstation App` ### Log Control logging level and location. #### Example ``` [log] level = "debug" location = "C:\Users\username\chef-workstation.log" ``` #### level Description Determines what messages are logged from locally-run Chef Workstation commands to the to the local log file. Values `"debug"`, `"warn"`, `"info"`, `"error"`, `"fatal"` Default `"warn"` Used by `chef-run` #### location Description The location of the local Chef Workstation log file. Values Value must be a valid, writable file path. Default `"$USERHOME/.chef-workstation/logs/default.log" Used by `chef-run` ### Cache Configure caching options. #### Example ``` [cache] path = "/home/users/username/.cache/chef-workstation" ``` #### path Description The base path used to store cached cookbooks and downloads. Default `$USERHOME/.chef-workstation/cache` Values This must reference a valid, writable directory. Used by `chef-run` ### Connection Control default connection behaviors. #### Example ``` [connection] default_protocol = "winrm" default_user = "username" ``` #### default_protocol Description Default protocol for connecting to target hosts. Values `"ssh"`, `"winrm"` Default `"ssh"` Used by `chef-run` CLI flag `--protocol PROTO` #### default_user Description Default username for target host authentication. Values A username that exists on the target hosts. Default `root` (Linux), `administrator` (Windows) Used by `chef-run` CLI flag `--user USERNAME` ### Connection.winrm Control connection behaviors for the WinRM protocol. #### Example ``` [connection.winrm] ssl = true ssl_verify = false ``` #### ssl Description Enable SSL for WinRM session encryption Values `true`, `false` Default `false` Used by `chef-run` CLI flag `--[no]-ssl` #### ssl_verify Description :Intended for use in testing environments that use self-signed certificates on Windows nodes. Default `true` Values `true`, `false` Used by `chef-run` CLI flag –ssl-[no]-verify ### Chef Configure remote Chef running on instances. #### Example ``` [chef] trusted_certs_dir = "/home/username/mytrustedcerts" cookbook_repo_paths = [ "/home/username/cookbooks", "/var/chef/cookbooks" ] ``` #### trusted_certs_dir Description Describes where to find Chef’s trusted certificates. Used to ensure trusted certs are provided to the `chef-client` run on target nodes. Values A directory containing the trusted certificates for use in the Chef ecosystem. Default Look first for `.chef/config.rb` and use that value if provided; otherwise `"/opt/chef-workstation/embedded/ssl/certs/"` Used by `chef-run` #### cookbook_repo_paths Description Path or paths to use for cookbook resolution. When multiple cookbook paths are provided and a cookbook exists in more than one of them, the cookbook found in the last-most directory will be used. Considering the example, when resolving cookbook `mycb`: if `mycb` existed in both `/home/username/cookbooks` and `/var/chef/cookbooks`, `mycb` in `/var/chef/cookbooks` will be used. Values A string referencing a valid cookbook path, or an array of such strings. See example for syntax. Default `cookbook_path` value from `.chef/config.rb`, otherwise not found Used by `chef-run` CLI flag `--cookbook-repo-paths PATH1,PATH2,..PATHn` ### Updates Control the behavior of automatic update checking for Chef Workstation. #### Example ``` [updates] enable = true channel = "current" ``` #### enable Description Enable update checking for Chef Workstation updates. Values `true`, `false` Default `true` Used by Chef Workstation App #### channel Description Set the update channel to use when checking for Chef Workstation updates. `"stable"` is the recommended value. Switch to `"current"` is not guaranteed to be stable, and should only be used if you are comfortable with the risks associated. Values `"stable"`, `"current"` Default `"stable"` Used by Chef Workstation App ### Data_collector Configure reporting of `chef-client` runs triggered via `chef-run`. #### Example ``` [data_collector] url = "https://1.1.1.1/data-collector/v0/" token = "ABCDEF0123456789" ``` #### url Description URL of an Automate [data collection](../../automate/data_collection/index) endpoint. This URL is provided to the target host, allowing them to report in to Automate when `chef-run` is used to converge the targets. A valid token generated by automate is required. Values A valid automate data collector endpoint. Default not set. Used by `chef-run` #### token Description An Automate [API token](../../automate/api_tokens/index#creating-api-tokens), used on target host to authenticate to the `url` provided. Values A valid token generated by Automate. Default not set. Used by `chef-run` ### Dev These options are intended for development and troubleshooting of Chef Workstation tools. Their usage is not supported and is subject to change. #### Example ``` [dev] spinner = false ``` #### spinner Description Use animated spinners and progress indicators in the terminal output. Values `true`, `false` Default `true` Used by `chef-run` ### Features Enable and disable experimental features for Chef Workstation. #### Example ``` [features] example = true ``` Description List of experimental features. Boolean. Default: none. Enable the feature with `feature = true` and disable with `feature = false`. `example = true` enables one feature, which is the `example` feature. You can also enable or disable any feature from the command line using an environment variable. For example, setting `CHEF_FEAT_EXAMPLE=true` from the command line enables the `example` feature for the duration of your terminal session. Values `name = true`, `name = false` Used by The entire Chef Workstation ecosystem. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/config/Privacy and Telemetry ===================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/privacy.md) In order to continually improve Chef Workstation, we collect information to help us identify bugs and understand how people interact with Chef Workstation. What We Collect --------------- We capture: * A unique installation-id that isn’t connected to user data. This helps us track the number of active Chef Workstation installations without needing to perform IP-based tracking. * The Chef-specific commands you execute, but **none** of the arguments you pass. * Your host operating system and version. * A SHA256 sum of any hostname that you’re connecting to via `chef-run`. * How you connect to a remote host via `chef-run`, either WinRM or SSH. * Target operating system of any hosts connected to via `chef-run`. How We Use Your Data -------------------- We use this data to track Chef Workstation usage patterns, identify bugs, and iterate development based real aggregated feedback. Only Chef Software, Inc employees have access to your data. We will never sell, re-sell, or use your data in a malicious manner. Opting out ---------- * To stop the capture of telemetry data from a single session, set the environment variable `CHEF_TELEMETRY_OPT_OUT` to any value before running `chef-run`, for example: ``` CHEF_TELEMETRY_OPT_OUT=1 chef-run -h ``` * Disable telemetry entirely by adding the following to `$HOME/.chef-workstation/config.toml`: ``` [telemetry] enabled=false ``` See Your Data ------------- You can view the analytics we collect before it is sent. Find—and remove—your data in the `HOME/.chef-workstation/telemetry/` folder. We save the data from a current `chef-run` in the telemetry folder and collect it at the start of the next `chef-run`. When telemetry is disabled, we won’t collect your previously stored analytics. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/privacy/chef-run (executable) ===================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/chef_run.md) chef-run is a tool to execute ad-hoc tasks on one or more target nodes using Chef Infra Client. To start with, familiarize yourself with `chef-run`’s arguments and flags by running `chef-run -h`. Apply a Resource to a Single Node over SSH ------------------------------------------ In its simplest form, `chef-run` targets a single machine and execute a single resource on that machine: ``` chef-run ssh://my_user@host1:2222 directory /tmp/foo --identity-file ~/.ssh/id_rsa ``` SSH is the default protocol. When using SSH, `chef-run` attempts to read defaults from your `~/.ssh/config` file. Given the following SSH configuration: ``` Host host1 IdentityFile /Users/me/.ssh/id_rsa User my_user Port 2222 ``` You could specify the `chef-run` command as: ``` chef-run host1 directory /tmp/foo ``` To use password authentication instead of an identity file, specify the password as part of the connection information or by using the command line flag: ``` chef-run my_user:a_password@host1:2222 directory /tmp/foo chef-run my_user@host1:2222 directory /tmp/foo --password a_password ``` Applying a Resource to a Single Node over WinRM ----------------------------------------------- To target WinRM you must specify the `winrm` protocol as part of the connection information: ``` chef-run 'winrm://my_user:my_p4ssword!@host' directory /tmp/foo ``` WinRM connections only support password authentication. Provide username and password as shown in the example, or via the `--user` and `--password` flags. HTTPS connections are supported by providing the `--ssl` flag. `chef-run` over WinRM does not support certificate-based authentication to target hosts. Specifying resource properties and actions ------------------------------------------ You can specify all the Chef Infra [resources](../../resources/index) in the command line. Enter the `chef-run` command first, followed by the resource type in the second place, and the resource name in the third place. For example: ``` chef-run host1 group awesome_group ``` This command specifies the `group` resource with a name of `awesome_group`. To specify properties and actions, use a `key=value` syntax: ``` chef-run host1 group awesome_group gid=1001 chef-run host1 user super_person gid=1001 'password=complex=p@ssword!!' chef-run host1 user super_person action=remove ``` See the documentation for each resource to see available properties available to customize. As shown in the previous example, you can quote the `key=value` pair if the value contains a character that would be interpreted by the shell. Running a Recipe ---------------- To run a full recipe, specify a recipe using its path: ``` chef-run host1 /path/to/recipe.rb chef-run host1 recipe.rb ``` If your recipe is in a cookbook you can also specify that cookbook: ``` chef-run host1 /cookbooks/my_cookbook/recipes/default.rb chef-run host1 /cookbooks/my_cookbook ``` If you specify the path to the cookbook `chef-run` will execute the default recipe from the cookbook on the target node. `chef-run` also supports looking up your cookbook in a local cookbook repository. Assuming you have your cookbook repository at `/cookbooks`, run: ``` cd /cookbooks chef-run host1 my_cookbook chef-run host1 my_cookbook::non_default_recipe ``` `::recipe_name` tells `chef-run` to run a recipe other than the default. `chef-run` reads your local Chef Workstation configuration file `~/.chef-workstation/config.toml` and Chef configuration file `~/.chef/config.rb`. It looks for cookbooks in the paths specified in both files. The configuration value is an array and looks something like this: For `~/.chef-workstation/config.toml`: ``` [chef] cookbook_repo_paths = [ "/path/1", "/path/b" ] ``` and for `~/.chef/config.rb`: ``` cookbook_path ['/path/1', '/path/b'] ``` If you run `chef-run host1 my_cookbook` and the current directory does not have a cookbook named `my_cookbook`, then `chef-run` searches the configured paths, with those configured in `~/.chef-workstation/config.toml` taking priority over those in `~/.chef/config.rb`. To specify the search paths as command line arguments instead of using a configuration file, use: ``` chef-run host1 my_cookbook --cookbook-repo-paths '/path/1,/path/b' ``` Configuring Cookbook Dependencies and Sources --------------------------------------------- When converging a target node `chef-run` creates a Policyfile bundle that includes the cookbook specified. If the cookbook you specified has its own [`Policyfile.rb`](../../config_rb_policyfile/index) that will be respected. In your `metadata.rb` file: ``` name "really_complicated" ... depends "pretty_simple" ``` In your `Policyfile.rb` file: ``` name "really_complicated" default_source :supermarket default_source :chef_repo, "../" run_list "really_complicated::first" cookbook "pretty_simple" ``` In your `recipes/first.rb` ``` log "lets include some stuff" include_recipe "pretty_simple::second" ``` Running `chef-run host1 really_complicated::first` collects all the `really_complicated` cookbook dependencies (`pretty_simple`) first, in preparation for converging the target node. When running on that node the `first` recipe finds its local dependency on the `pretty_simple` cookbook and then runs its `second` recipe. You can specify different cookbook sources in `Policyfile.rb`, including a private supermarket. See the [Policyfile documentation](../../config_rb_policyfile/index) for examples. Connecting to Automate 2 ------------------------ You can configure remote nodes managed with `chef-run` to send run information to Automate. First, [generate an auth token](../../automate/api_tokens/index#creating-api-tokens). Next, add the token to [config.toml](../config/index#data_collector), specifying the appropriate [url](../../automate/data_collection/index) and [token](../../automate/api_tokens/index#creating-api-tokens) for the automate server: ``` [data_collector] url="https://127.0.0.1/data-collector/v0/" token="abc123=" ``` Target nodes need network access to port 443 of the Automate instance for sending `chef-client` run information. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/chef_run/About Berkshelf =============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/berkshelf.md) Berkshelf is a dependency manager for Chef cookbooks. With it, you can easily depend on community cookbooks and have them safely included in your workflow. You can also ensure that your CI systems reproducibly select the same cookbook versions, and can upload and bundle cookbook dependencies without needing a locally maintained copy. Berkshelf is included in Chef Workstation. Note For new users, we strongly recommend using [Policyfiles](../../policyfile/index) rather than Berkshelf. Policyfiles provide more predictability, since dependencies are only resolved once, and a much improved way of promoting cookbooks from dev to testing, and then to production. Quick Start ----------- Run `chef generate cookbook -b` or `--berks` to create a Berksfile in the root of the cookbook. The Berksfile will be placed alongside the cookbook’s metadata.rb file. As usual, add your cookbook’s dependencies to the metadata.rb file: ``` name 'my_first_cookbook' version '0.1.0' depends 'apt', '~> 5.0' ``` The default `Berksfile` will contain the following: ``` source 'https://supermarket.chef.io' metadata ``` Now, when you run `berks install`, the apt cookbook will be downloaded from Supermarket into the cache: ``` berks install Resolving cookbook dependencies... Fetching 'my_first_cookbook' from source at . Fetching cookbook index from https://supermarket.chef.io... Installing apt (5.0.0) Using my_first_cookbook (0.1.0) from source at . Installing compat_resource (12.16.2) ``` In this example, the `compat_resource` cookbook is also installed since it’s a dependency of the `apt` cookbook. Running the install command also creates a `Berksfile.lock`, which represents exactly which cookbook versions Berkshelf installed. This file ensures that someone else can check the cookbook out of git and get exactly the same dependencies as you. You can now upload all cookbooks to your Chef Infra Server with `berks upload`: ``` berks upload Uploaded apt (5.0.0) to: 'https://api.chef.io:443/organizations/example' Uploaded compat_resource (12.16.2) to: 'https://api.chef.io:443/organizations/example' Uploaded my_first_cookbook (0.1.0) to: 'https://api.chef.io:443/organizations/example' ``` The Berksfile ------------- A Berksfile describes the set of sources and dependencies needed to use a cookbook. It is used in conjunction with the `berks` command. ### Syntax A Berksfile is a Ruby file, in which sources, dependencies, and options may be specified. Berksfiles are modeled closely on Bundler’s Gemfile. The syntax is as follows: ``` source "https://supermarket.chef.io" metadata cookbook "NAME" [, "VERSION_CONSTRAINT"] [, SOURCE_OPTIONS] ``` #### Source Keyword A source defines where Berkshelf should look for cookbooks. Sources are processed in the order that they are defined in, and processing stops as soon as a suitable cookbook is found. Locations include a private or public [Supermarket](../../supermarket/index), Chef Infra Server, or local Chef repository. By default, a Berksfile has a source for Chef’s public Supermarket: ``` source "https://supermarket.chef.io" ``` To add a private Supermarket, which will be preferred: ``` source "https://supermarket.example.com" source "https://supermarket.chef.io" ``` To add a Chef Infra Server: ``` source "https://supermarket.chef.io" source :chef_server ``` To add a local Chef repository: ``` source "https://supermarket.chef.io" source chef_repo: ".." ``` The location and authentication details for the Chef Infra Server will be taken from the user’s `config.rb` by default. To add multiple Chef Infra Servers: ``` source "https://supermarket.chef.io" source chef_server: "https://mychefserver.example.com/organizations/one", client_name: "one-client", client_key: "/path/to/one-client.pem" source chef_server: "https://mychefserver.example.com/organizations/two", client_name: "two-client", client_key: "/path/to/two-client.pem" ``` To use an [Artifactory server](https://www.jfrog.com/confluence/display/RTF/Chef+Cookbook+Repositories) as a source: ``` source artifactory: "https://artifactory.example.com/api/chef/nameofrepo", api_key: "<KEY>" ``` If the `api_key` option is not given, it will use the value of the `$ARTIFACTORY_API_KEY` environment variable by default. #### Metadata Keyword The `metadata` keyword causes Berkshelf to process the local cookbook metadata. This ensures that the dependencies of the cookbook are resolved by Berkshelf. Using the `metadata` keyword requires that the Berksfile be placed in the root of the cookbook, next to `metadata.rb`. #### Cookbook Keyword The `cookbook` keyword allows the user to define where a cookbook is installed from, or to set additional version constraints. It can also be used to install additional cookbooks, for example to use during testing. The format of a `cookbook` stanza is as follows: ``` cookbook "NAME" [, "VERSION_CONSTRAINT"] [, SOURCE_OPTIONS] ``` The simplest form is: ``` cookbook "library-cookbook" ``` This ensures that a cookbook named `library-cookbook` is installed by berkshelf. Version constraints are the second parameter: ``` cookbook "library-cookbook", "~> 0.1.1" ``` These are identical to the version constraints in a [cookbook metadata file](../../config_rb_metadata/index#cookbook-version-constraints). Source options are used to specify the location to acquire a cookbook from, or to place a cookbook in a group. By default, cookbooks are acquired from the default sources, but it’s possible to override this on a case by case basis. Often this is used to get a development cookbook from Git, or to use another cookbook in a monolithic cookbook repository. **Path Location** The path location enables Berkshelf to use a cookbook located on the same system. It does not cache the target cookbook, ensuring that the latest version is always used. The target must be a single cookbook with a `metadata.rb`. ``` cookbook "library-cookbook", "~> 0.1.1", path: "../library-cookbook" ``` **Git Location** The git location enables Berkshelf to use acquire a cookbook from a git repository. ``` cookbook "library-cookbook", "~> 0.1.1", git: "https://github.com/example/library-cookbook.git" ``` The user can specify a git branch or a tag (the options are synonymous) using an optional argument: ``` cookbook "library-cookbook", "~> 0.1.1", git: "https://github.com/example/library-cookbook.git", branch: "smartos-dev" cookbook "library-cookbook", "~> 0.1.1", git: "https://github.com/example/library-cookbook.git", tag: "1.2.3" ``` The user can also specify a revision: ``` cookbook "library-cookbook", "~> 0.1.1", git: "https://github.com/example/library-cookbook.git", ref: "eef7e65806e7ff3bdbe148e27c447ef4a8bc3881" ``` If a git repository contains many cookbooks, the user can specify the path to the desired cookbook using the `rel` option: ``` cookbook "library-cookbook", "~> 0.1.1", git: "https://github.com/example/cookbook-repo.git", rel: "library-cookbook" ``` **GitHub Location** If a cookbook is in GitHub, you can use the `github:` shorthand to refer to it: ``` cookbook "library-cookbook", "~> 0.1.1", github: "example/library-cookbook" ``` Any other git options are valid for a GitHub location. #### Groups Adding cookbooks to a group is useful should you wish to exclude certain cookbooks from upload or vendoring. Groups can be defined via blocks: ``` group :test do cookbook "test-cookbook", path: "test/fixtures/test" end ``` Groups can also be specified inline: ``` cookbook "test-cookbook", path: "test/fixtures/test", group: :test ``` To exclude a group when using `berks`, use the `--except` flag: ``` berks install --except test ``` #### Solver Keyword It is possible to configure which engine to use for the [solve](https://github.com/berkshelf/solve) dependency resolution system. By default, the solver selection depends on your environment. When the `dep_selector` gem is installed, as in the case of Chef Workstation, the `gecode` solver is used. Otherwise, the `ruby` solver is utilized by default. The `gecode` solver matches the engine used by the Chef Infra Server, so will more closely reflect the behavior of the Chef Infra Server in selecting cookbooks: ``` solver :gecode ``` The `ruby` solver can give better results in some situations, notably when Berkshelf times out when trying to build a dependency set. ``` solver :ruby ``` Berkshelf CLI ------------- The Berkshelf CLI is the interface to Berkshelf. ### Common Options `-c PATH`, `--config PATH` The path to the Berkshelf configuration file. `-d`, `--debug` Use to print debug information. Default value: `false`. `-F JSON`, `--format JSON` Use to specify the output format to be used. Default value: `human` Possible values: `base`, `human`, `json`, and `null`. `-q`, `--quiet` Use to silence all informational output. Default value: `false`. ### berks apply Use `berks apply` to apply Berksfile version locks to the named environment on the Chef Infra Server. #### Syntax This subcommand has the following syntax: ``` berks apply ENVIRONMENT (options) ``` #### Options This command has the following options: `-b LOCK_FILE_PATH`, `--lockfile LOCK_FILE_PATH` The path to the Berksfile lock file from which Berksfile version locks are applied. `-f JSON_FILE_PATH`, `--envfile PATH` The path to an environment file (in JSON format) to which Berksfile version locks are applied. `--ssl-verify` Use to enable (`true`) or disable (`false`) SSL verification when applying Berksfile version locks to an environment. ### berks contingent Use `berks contingent` to list all cookbooks in a Berksfile that depend on the named cookbook. #### Syntax This subcommand has the following syntax: ``` berks contingent COOKBOOK (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile in which the cookbook is located. ### berks cookbook Use `berks cookbook` to create a skeleton for a new cookbook. Warning This command is deprecated. Please use `chef generate cookbook` instead. ### berks info Use `berks info` to display the name, author, copyright, and dependency information for the named cookbook. #### Syntax This subcommand has the following syntax: ``` berks info COOKBOOK (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile in which the cookbook is located. ### berks init Use `berks init` to initialize Berkshelf to the specified directory. Warning This command is deprecated. Please use `chef generate cookbook` instead. ### berks install Use `berks install` to install cookbooks into the cache. This command generates the Berkshelf lock file that ensures consistency. #### Syntax This subcommand has the following syntax: ``` berks install (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile in which the cookbook is located. `-e [GROUP, GROUP, ...]`, `--except [GROUP, GROUP, ...]` An array of cookbook groups that will not be listed. `-o [GROUP, GROUP, ...]`, `--only [GROUP, GROUP, ...]` An array of cookbook groups to be listed. When this option is used, cookbooks that exist in groups not listed will not be listed. ### berks list Use `berks list` to list cookbooks and their dependencies. #### Syntax This subcommand has the following syntax: ``` berks list (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile in which the cookbook is located. `-e [GROUP, GROUP, ...]`, `--except [GROUP, GROUP, ...]` An array of cookbook groups that will not be listed. `-o [GROUP, GROUP, ...]`, `--only [GROUP, GROUP, ...]` An array of cookbook groups to be listed. When this option is used, cookbooks that exist in groups not listed will not be listed. ### berks outdated Use `berks outdated` to list dependencies for the named cookbook, and then check if there are new versions available for version constraints that may exist. #### Syntax This subcommand has the following syntax: ``` berks outdated COOKBOOK (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile in which the cookbook is located. `-e [GROUP, GROUP, ...]`, `--except [GROUP, GROUP, ...]` An array of cookbook groups that will not be checked for version constraints. `-o [GROUP, GROUP, ...]`, `--only [GROUP, GROUP, ...]` An array of cookbook groups to be checked for version constraints. When this option is used, cookbooks that exist in groups not listed will not be checked for version constraints. ### berks package Use `berks package` to vendor, and then archive the dependencies of a Berksfile. #### Syntax This subcommand has the following syntax: ``` berks package PATH (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile to be vendored, and then archived. `-e [GROUP, GROUP, ...]`, `--except [GROUP, GROUP, ...]` An array of cookbook groups that will not be vendored, and then archived. `-o [GROUP, GROUP, ...]`, `--only [GROUP, GROUP, ...]` An array of cookbook groups to be vendored, and then archived. When this option is used, cookbooks that exist in groups not listed will not be vendored or archived. ### berks search Use `berks search` to search the remote source for cookbooks that match the search query. The query itself will match partial cookbook names. #### Syntax This subcommand has the following syntax: ``` berks search QUERY (options) ``` #### Options This command has the following options: `--source URL` The URL at which remote cookbooks are located. Default value: `https://supermarket.chef.io`. ### berks show Use `berks show` to show the path to the named cookbook. #### Syntax This subcommand has the following syntax: ``` berks show COOKBOOK (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile in which the named cookbook is defined. ### berks update Use `berks update` to update the named cookbook or cookbooks (and any dependencies). #### Syntax This subcommand has the following syntax: ``` berks update COOKBOOK (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile in which the named cookbook is defined. `-e [GROUP, GROUP, ...]`, `--except [GROUP, GROUP, ...]` An array of cookbook groups that will not be updated. `-o [GROUP, GROUP, ...]`, `--only [GROUP, GROUP, ...]` An array of cookbook groups to be updated. When this option is used, cookbooks that exist in groups not listed will not be updated. ### berks upload Use `berks upload` to upload the named cookbook to the Chef Infra Server. #### Syntax This subcommand has the following syntax: ``` berks upload COOKBOOK (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile in which the named cookbook is defined. `-e [GROUP, GROUP, ...]`, `--except [GROUP, GROUP, ...]` An array of cookbook groups that will not be uploaded. `--force` Use to upload any named cookbook even if that cookbook exists on the Chef Infra Server and is frozen. `--halt-on-frozen` Use to exit the command with a non-zero exit code if this version of a cookbook already exists on the Chef Infra Server. `-o [GROUP, GROUP, ...]`, `--only [GROUP, GROUP, ...]` An array of cookbook groups to be uploaded. When this option is used, cookbooks that exist in groups not listed will not be uploaded. `--no-freeze` A frozen cookbook requires changes to that cookbook to be submitted as a new version of that cookbook. Use this option to prevent this cookbook from being frozen. Default value: `false` (i.e. “frozen”). `--ssl-verify` Use to enable (`true`) or disable (`false`) SSL verification when uploading cookbooks to the Chef Infra Server. `-s`, `--skip-syntax-check` Use to skip Ruby syntax checking when uploading a cookbook to the Chef Infra Server. Default value: `false`. ### berks vendor Use `berks vendor` to vendor groups of cookbooks (as specified by group name) into a directory. #### Syntax This subcommand has the following syntax: ``` berks vendor PATH (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile from which cookbooks will be vendored. `--delete` Use to clean the directory in which vendored cookbooks will be placed prior to executing this command. `-e [GROUP, GROUP, ...]`, `--except [GROUP, GROUP, ...]` An array of cookbook groups that will not be vendored. `-o [GROUP, GROUP, ...]`, `--only [GROUP, GROUP, ...]` An array of cookbook groups to be vendored. When this option is used, cookbooks that exist in groups not listed will not be vendored. ### berks verify Use `berks verify` to perform a validation of the contents of resolved cookbooks. #### Syntax This subcommand has the following syntax: ``` berks verify (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile from which resolved cookbooks are validated. ### berks version Use `berks version` to display the version of Berkshelf. ### berks viz Use `berks viz` to generate a dependency graph image file. #### Syntax This subcommand has the following syntax: ``` berks viz (options) ``` #### Options This command has the following options: `-b PATH`, `--berksfile PATH` The path to the Berksfile for which the dependency graph is built. `-o NAME`, `--outfile NAME` The name of the file to which output is saved. Default value: `graph.png`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/berkshelf/chef (executable) ================= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/ctl_chef.md) The chef executable is a command-line tool that does the following: * Generates repositories, cookbooks, recipes, attributes, templates, and custom resources. * Installs gems into the Chef development environment’s Ruby installation. chef capture ------------ Use the `chef capture` subcommand to capture a node’s state as a local [chef-repo](../../chef_repo/index). Use the generated repository if you need to converge a node locally. ### Syntax This subcommand has the following syntax: ``` chef capture NODE-NAME [options] ``` ### Options `-c`, `--credentials` Credentials file (default $HOME/.chef/credentials). `-d`, `--with-data-bags` Download all data bags as part of node capture. `-h`, `--help` Show help for the command. `-k`, `--client-key` Chef Infra Server API client key. `-n`, `--client-name` Chef Infra Server API client name. `-o`, `--ssl-no-verify` Do not verify SSL when connecting to Chef Infra Server (default: verify). `-p`, `--profile` Profile to use from credentials file (default “default”). `-s`, `--chef-server-url` Chef Infra Server URL. ### Examples **Capture a node** To capture a node in a local repository, run a command similar to: ``` chef capture test-server ``` This will return something similar to: ``` - Setting up local repository - Capturing node object 'test-server' - Capturing policy data... - Capturing cookbook artifacts... - Writing kitchen configuration... Repository has been created in './node-test-server-repo'. Next, locate version-controlled copies of the cookbooks. This is important so that you can track changes to the cookbooks as you edit them. You may have one or more existing paths where you have checked out cookbooks. If not, now is a good time to open a separate terminal and clone or check out the cookbooks. If all cookbooks are not available in the same base location, you will have a chance to provide additional locations. Press Enter to Continue: You're ready to begin! Start with 'cd ./node-test-server-repo; kitchen converge'. As you identify issues, you can modify cookbooks in their original checkout locations or in the repository's cookbooks directory and they will be picked up on subsequent runs of 'kitchen converge'. ``` See the [Upgrade Lab](../upgrade_lab/index#create-an-upgrade-environment-with-chef-capture) documentation for additional information on upgrading Chef Infra Client. chef env -------- Use the `chef env` subcommand to configure the environment for Chef Workstation. ### Syntax This subcommand has the following syntax: ``` chef env ``` ### Options This command does not have any specific options. ### Examples None. chef exec --------- Use the `chef exec` subcommand to run arbitrary shell commands with the `PATH` environment variable and the `GEM_HOME` and `GEM_PATH` Ruby environment variables pointed at Chef Workstation. ### Syntax This subcommand has the following syntax: ``` chef exec SYSTEM_COMMAND (options) ``` ### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef gem -------- The `chef gem` subcommand is a wrapper around the `gem` command in RubyGems and is used by Chef to install RubyGems into Chef Workstation development environment. All knife plugins, drivers for Kitchen, and other Ruby applications that are not packaged within Chef Workstation will be installed to the `.Chef Workstation` path in the home directory: `~/.Chef Workstation/gem/ruby/ver.si.on/bin` (where `ver.si.on` is the version of Ruby that is packaged within Chef Workstation). ### Syntax This subcommand has the following syntax: ``` chef gem GEM_COMMAND GEM_OPTIONS (options) ``` ### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples **Show an existing gem in Chef Workstation** To show a gem, run a command similar to: ``` chef gem list cookstyle ``` to return something similar to: ``` *** LOCAL GEMS *** cookstyle (5.20.0) ``` **List all local gems** To list all of the installed gems on your development environment, use the `list` command without any arguments: ``` chef gem list ``` **Search for local gems** The `list` command can also be used to search for locally installed gems. For example, to list all of the gems with `knife` in their title: ``` chef gem list knife ``` which returns the following output: ``` *** LOCAL GEMS *** knife-opc (0.3.2) knife-windows (1.9.0) ``` **Search remote gems** Use the `search` command to search for remote gems available for installation: ``` chef gem search kitchen ``` to return something similar to: ``` *** REMOTE GEMS *** chefkitchen_cli (0.0.1) gst-kitchen (0.9.0) guard-kitchen (0.0.2) jackal-kitchen (0.1.2) jackal-kitchen-slack (0.1.2) kitchen (0.0.3) ``` **Install a gem** To install a gem, run a command similar to: ``` chef gem install knife-config ``` to return something similar to: ``` Successfully installed knife-config-1.1.0 1 gem installed ``` **Uninstall a gem** To uninstall a gem from Chef Workstation environment: ``` chef gem uninstall knife-config ``` to return something similar to: ``` Successfully uninstalled knife-config-1.1.0 ``` **View the contents of a gem** To view the contents of a gem, run a command similar to: ``` chef gem content knife-config ``` to return something similar to: ``` /Users/user/.chefdk/gem/ruby/2.1.0/gems/knife-config-1.1.0/LICENSE /Users/user/.chefdk/gem/ruby/2.1.0/gems/knife-config-1.1.0/README.md /Users/user/.chefdk/gem/ruby/2.1.0/gems/knife-config-1.1.0/lib/chef/knife/config.rb /Users/user/.chefdk/gem/ruby/2.1.0/gems/knife-config-1.1.0/lib/knife-config.rb ``` chef generate attribute ----------------------- Use the `chef generate attribute` subcommand to generate an attribute file in the `/attributes` directory. ### Syntax This subcommand has the following syntax: ``` chef generate attribute COOKBOOK_PATH NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples **Create an attribute** To generate an attribute, run a command similar to: ``` chef generate attribute /path/to/cookbook FOO ``` will return something similar to: ``` Recipe: code_generator::attribute * directory[/Users/grantmc/chef-repo/cookbooks/chef-repo/attributes] action create - create new directory /Users/grantmc/chef-repo/cookbooks/chef-repo/attributes * template[/Users/grantmc/chef-repo/cookbooks/chef-repo/attributes/FOO.rb] action create - create new file /Users/grantmc/chef-repo/cookbooks/chef-repo/attributes/FOO.rb ``` chef generate cookbook ---------------------- Use the `chef generate cookbook` subcommand to generate a cookbook. Note Cookbook and custom resource names should contain only alphanumeric characters. A hyphen (`-`) is a valid character and may be used in cookbook and custom resource names, but it is discouraged. Chef Infra Client will return an error if a hyphen is not converted to an underscore (`_`) when referencing from a recipe the name of a custom resource in which a hyphen is located. ### Syntax This subcommand has the following syntax: ``` chef generate cookbook COOKBOOK_PATH/COOKBOOK_NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-b`, `--berks` Create a Berksfile in the cookbook. Default: disabled. Optional. Use to create a berksfile by overriding default creation of a Policyfile. `-C COPYRIGHT`, `--copyright COPYRIGHT` Specify the copyright holder for copyright notices in generated files. Default value: `The Authors` `-d`, `--delivery` Generate a delivery config file and build cookbook inside the new cookbook. Default value: disabled. This option is disabled. It has no effect and exists only for compatibility with past releases `-m EMAIL`, `--email EMAIL` Specify the email address of the author. Default value: `<EMAIL>`. `-a KEY=VALUE`, `--generator-arg KEY=VALUE` Sets a property named `KEY` to the given `VALUE` on the generator context object in the generator cookbook. This allows custom generator cookbooks to accept optional user input on the command line. `-I LICENSE`, `--license LICENSE` Sets the license. Valid values are `all_rights`, `apache2`, `mit`, `gplv2`, or `gplv3`. Default value: `all_rights`. `-P`, `--policy` Create a Policyfile in the cookbook instead of a Berksfile. Default: enabled. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples **Create a cookbook** To generate a cookbook, run a command similar to: ``` chef generate cookbook chefdocs ``` will return something similar to: ``` Recipe: code_generator::cookbook * directory[/Users/grantmc/chefdocs] action create - create new directory /Users/grantmc/chefdocs * template[/Users/grantmc/chefdocs/metadata.rb] action create - create new file /Users/grantmc/chefdocs/metadata.rb * template[/Users/grantmc/chefdocs/README.md] action create - create new file /Users/grantmc/chefdocs/README.md * cookbook_file[/Users/grantmc/chefdocs/chefignore] action create - create new file /Users/grantmc/chefdocs/chefignore * cookbook_file[/Users/grantmc/chefdocs/Berksfile] action create - create new file /Users/grantmc/chefdocs/Berksfile * template[/Users/grantmc/chefdocs/kitchen.yml] action create - create new file /Users/grantmc/chefdocs/kitchen.yml * directory[/Users/grantmc/chefdocs/recipes] action create - create new directory /Users/grantmc/chefdocs/recipes * template[/Users/grantmc/chefdocs/recipes/default.rb] action create - create new file /Users/grantmc/chefdocs/recipes/default.rb * execute[initialize-git] action run - execute git init . * cookbook_file[/Users/grantmc/chefdocs/.gitignore] action create - create new file /Users/grantmc/chefdocs/.gitignore ``` and which creates a directory structure similar to: ``` /chefdocs /.git .gitignore kitchen.yml Berksfile chefignore metadata.rb README.md /recipes default.rb ``` **Create a cookbook using a custom skeleton cookbook** If a custom skeleton cookbook is located on a macOS desktop (and in this example, the `chef_generator` cookbook is simply a copy of the same cookbook that ships in Chef Workstation), the following command will use the skeleton cookbook at the custom location to generate a cookbook into the repository from which the `chef` command is run: ``` chef generate cookbook --generator-cookbook ~/Desktop testcookbook ``` Note The `code_generator` cookbook itself is not specified as part of the path. will return something similar to: ``` Compiling Cookbooks... Recipe: code_generator::cookbook * directory[/Users/grantmc/Desktop/chef-repo/test-cookbook] action create - create new directory /Users/grantmc/Desktop/chef-repo/test-cookbook * template[/Users/grantmc/Desktop/chef-repo/test-cookbook/metadata.rb] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/metadata.rb * template[/Users/grantmc/Desktop/chef-repo/test-cookbook/README.md] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/README.md * cookbook_file[/Users/grantmc/Desktop/chef-repo/test-cookbook/chefignore] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/chefignore * cookbook_file[/Users/grantmc/Desktop/chef-repo/test-cookbook/Berksfile] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/Berksfile * template[/Users/grantmc/Desktop/chef-repo/test-cookbook/kitchen.yml] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/kitchen.yml * directory[/Users/grantmc/Desktop/chef-repo/test-cookbook/recipes] action create - create new directory /Users/grantmc/Desktop/chef-repo/test-cookbook/recipes * template[/Users/grantmc/Desktop/chef-repo/test-cookbook/recipes/default.rb] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/recipes/default.rb ``` chef generate build-cookbook ---------------------------- Use the `chef generate build-cookbook` subcommand to generate a delivery configuration file and build cookbook. ### Syntax This subcommand has the following syntax: ``` chef generate build-cookbook COOKBOOK_PATH/COOKBOOK_NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-C COPYRIGHT`, `--copyright COPYRIGHT` Specify the copyright holder for copyright notices in generated files. Default value: `The Authors` `-m EMAIL`, `--email EMAIL` Specify the email address of the author. Default value: `<EMAIL>`. `-a KEY=VALUE`, `--generator-arg KEY=VALUE` Sets a property named `KEY` to the given `VALUE` on the generator context object in the generator cookbook. This allows custom generator cookbooks to accept optional user input on the command line. `-I LICENSE`, `--license LICENSE` Sets the license. Valid values are `all_rights`, `apache2`, `mit`, `gplv2`, or `gplv3`. Default value: `all_rights`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef generate file ------------------ Use the `chef generate file` subcommand to generate a file in the `/files` directory. ### Syntax This subcommand has the following syntax: ``` chef generate file COOKBOOK_PATH NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-h`, `--help` Show help for the command. `-s SOURCE_FILE`, `--source SOURCE_FILE` Copy the contents from a source file. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef generate resource ---------------------- Use the `chef generate resource` subcommand to generate a custom resource in the `/resources` directory. Note Cookbook and custom resource names should contain only alphanumeric characters. A hyphen (`-`) is a valid character and may be used in cookbook and custom resource names, but it is discouraged. Chef Infra Client will return an error if a hyphen is not converted to an underscore (`_`) when referencing from a recipe the name of a custom resource in which a hyphen is located. ### Syntax This subcommand has the following syntax: ``` chef generate resource COOKBOOK_PATH NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef generate recipe -------------------- Use the `chef generate recipe` subcommand to generate a recipe in the `/recipes` directory. ### Syntax This subcommand has the following syntax: ``` chef generate recipe COOKBOOK_PATH NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef generate repo ------------------ Use the `chef generate repo` subcommand to create a chef-repo. By default, the repo is a cookbook repo with options available to support generating a cookbook that supports Policyfile. ### Syntax This subcommand has the following syntax: ``` chef generate repo REPO_NAME (options) ``` ### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-p`, `--policy-only` Create a repository that does not store cookbook files, only Policyfile files. `-P`, `--policy` Use Policyfile instead of Berkshelf. `-r`, `--roles` Create directories for `/roles` and `/environments` instead of creating directories for Policyfile. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef generate template ---------------------- Use the `chef generate template` subcommand to generate a template in the `/templates` directory. ### Syntax This subcommand has the following syntax: ``` chef generate template COOKBOOK_PATH NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-h`, `--help` Show help for the command. `-s SOURCE_FILE`, `--source SOURCE_FILE` Copy the contents from a source file. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef report cookbooks --------------------- Use the `chef report cookbooks` subcommand to generate a cookbook-oriented report for your Chef Infra environment. This report provides details about upgrade compatibility errors and node cookbook usage. ### Syntax This subcommand has the following syntax: ``` chef report cookbooks [options] ``` ### Options This subcommand has the following options: `-a`, `--anonymize` Replace cookbook and node names with hash values to protect the sensitive information. `-c`, `--credentials string` Credentials file (default $HOME/.chef/credentials). `-f`, `--format` Output format: txt is human readable, csv is machine readable (default “txt”). `-F`, `--node-filter` Search filter to apply to nodes. `-h`, `--help` Show help for the command. `-k`, `--client-key` Chef Infra Server API client key. `-n`, `--client-name` Chef Infra Server API client name. `-o`, `--ssl-no-verify` Do not verify SSL when connecting to Chef Infra Server (default: verify). `-p`, `--profile` Profile to use from credentials file (default “default”). `-s`, `--chef-server-url` Chef Infra Server URL. `-u`, `--only-unused` Generate a report that only includes cookbooks that are not included in any node’s runlist. `-V`, `--verify-upgrade` Verify the upgrade compatibility of every cookbook. `-w`, `--workers` Maximum number of parallel workers at once (default 50). ### Examples **Generate a report** To generate a cookbook oriented report, run a command similar to: ``` chef report cookbooks ``` will return something similar to: ``` Finding available cookbooks... (5 found) Analyzing cookbooks... 5 / 5 [----------------------------------------------------------------------------------------------------------------] 100.00% 13 p/s -- REPORT SUMMARY -- Cookbook Version Policy Group Policy Nodes Affected -----------+---------+--------------+--------+----------------- apt 2.7.0 2 Go 0.1.0 3 java 0.3.0 4 java Production K8s 1 K8s Production K8s 1 Cookbooks report saved to .chef-workstation/reports/cookbooks-20200722120938.txt ``` More details of this summary report can be viewed in the text file, the location for which is given at the end of the summary. See the [Upgrade Lab](../upgrade_lab/index#chef-report-cookbooks) documentation for additional information on upgrading Chef Infra Client. chef report nodes ----------------- Use the `chef report nodes` subcommand to generate a nodes-oriented report for your chef environment. This report provides details about nodes, applied policies and the cookbooks used during the most recent chef-client run. ### Syntax This subcommand has the following syntax: ``` chef report nodes [options] ``` ### Options This subcommand has the following options: `-a`, `--anonymize` Replace cookbook and node names with hash values to protect sensitive information. `-c`, `--credentials string` Credentials file (default $HOME/.chef/credentials). `-f`, `--format` Output format: txt is human readable, csv is machine readable (default “txt”). `-F`, `--node-filter` Search filter to apply to nodes. `-h`, `--help` Show help for the command. `-k`, `--client-key` Chef Infra Server API client key. `-n`, `--client-name` Chef Infra Server API client name. `-o`, `--ssl-no-verify` Do not verify SSL when connecting to Chef Infra Server (default: verify). `-p`, `--profile` Profile to use from credentials file (default “default”). `-s`, `--chef-server-url` Chef Infra Server URL. ### Examples **Generate a report** To generate a nodes oriented report, run a command similar to: ``` chef report nodes ``` will return something similar to: ``` Analyzing nodes... -- REPORT SUMMARY -- Node Name Chef Version Operating System Number Cookbooks ---------------------+--------------+------------------+------------------- dev-server-backend 16.1.16 redhat v8.2 3 dev-server-web 16.1.16 redhat v8.2 1 production-server 16.1.16 redhat v8.2 2 staging-server 16.1.16 redhat v8.2 4 test-server 16.1.16 redhat v8.2 3 Nodes report saved to .chef-workstation/reports/nodes-20200722130502.txt ``` More details of this summary report can be viewed in the text file, the location for which is given at the end of the summary. [Upgrade Lab](../upgrade_lab) provides further details on how this command can be used in Chef Infra Client upgrade process. chef shell-init --------------- Use the `chef shell-init` subcommand to set the Ruby included in Chef Workstation as the system Ruby. Chef Workstation is designed to allow the isolation of applications used by Chef Workstation from other Ruby development tools that may be present on the workstation. This supports Bash, fish, Windows PowerShell (posh), and zsh. bash zsh fish PowerShell (posh) ### Syntax This subcommand has the following syntax: ``` chef shell-init SHELL_NAME (options) ``` ### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples **Set PowerShell** You can use the `chef shell-init` command with Windows PowerShell to add the appropriate variables to your environment. To try it in your current session: ``` chef shell-init powershell | Invoke-Expression ``` To enable it permanently: ``` "chef shell-init powershell | Invoke-Expression" >> $PROFILE ``` **Set the execution policy on new machines** On new Windows machines, PowerShell scripts will not work until an administrator runs the following command: ``` Set-ExecutionPolicy RemoteSigned ``` **Create a $PROFILE on new machines** On new Windows machines, commands cannot be appended to `$PROFILE` if the folder does not exist, or if there is a new user profile. This will result in an error similar to the following: ``` PS C:\Users\Stuart> "chef shell-init powershell | Invoke-Expression" >> $PROFILE out-file : Could not find a part of the path 'C:\Users\Stuart\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'. At line:1 char:1 + "chef shell-init powershell | Invoke-Expression" >> $PROFILE + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OpenError: (:) [Out-File], DirectoryNotFoundException + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand ``` In this situation, run the following `chef shell-init` command instead: ``` if(Test-Path $PROFILE){ chef shell-init powershell | Add-Content $PROFILE } else { New-Item -Force -ItemType File $PROFILE; chef shell-init powershell | Add-Content $PROFILE } ``` Policyfile Commands ------------------- The following commands are built into the `chef` executable and support the use of Policyfile files. ### chef clean-policy-cookbooks Use the `chef clean-policy-cookbooks` subcommand to delete cookbooks that are not used by Policyfile files. Cookbooks are considered unused when they are not referenced by any policy revisions on the Chef Infra Server. Note Cookbooks that are referenced by orphaned policy revisions are not removed. Use `chef clean-policy-revisions` to remove orphaned policies. #### Syntax This subcommand has the following syntax: ``` chef clean-policy-cookbooks (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef clean-policy-revisions Use the `chef clean-policy-revisions` subcommand to delete orphaned policy revisions to Policyfile files from the Chef Infra Server. An orphaned policy revision is not associated to any policy group and therefore is not in active use by any node. Use `chef show-policy --orphans` to view a list of orphaned policy revisions. #### Syntax This subcommand has the following syntax: ``` chef clean-policy-revisions (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef delete-policy Use the `chef delete-policy` subcommand to delete all revisions of the named policy that exist on the Chef Infra Server. (The state of the policy revision is backed up locally and may be restored using the `chef undelete` subcommand.) #### Syntax This subcommand has the following syntax: ``` chef delete-policy POLICY_NAME (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef delete-policy-group Use the `chef delete-policy-group` subcommand to delete the named policy group from the Chef Infra Server. Any policy revision associated with that policy group is not deleted. (The state of the policy group is backed up locally and may be restored using the `chef undelete` subcommand.) #### Syntax This subcommand has the following syntax: ``` chef delete-policy-group POLICY_GROUP (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef diff Use the `chef diff` subcommand to display an itemized comparison of two revisions of a `Policyfile.lock.json` file. #### Syntax This subcommand has the following syntax: ``` chef diff POLICY_FILE --head | --git POLICY_GROUP | POLICY_GROUP...POLICY_GROUP (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-g GIT_REF`, `--git GIT_REF` Compare the specified git reference against the current revision of a `Policyfile.lock.json` file or against another git reference. `-h`, `--help` Show help for the command. `--head` A shortcut for `chef diff --git HEAD`. When a git-specific flag is not provided, the on-disk `Policyfile.lock.json` file is compared to one on the Chef Infra Server or (if a `Policyfile.lock.json` file is not present on-disk) two `Policyfile.lock.json` files in the specified policy group on the Chef Infra Server are compared. `--[no-]pager` Use `--pager` to enable paged output for a `Policyfile.lock.json` file. Default value: `--pager`. `-v`, `--version` The Chef Infra Client version. #### Examples **Compare current lock to latest commit on latest branch** ``` chef diff --git HEAD ``` **Compare current lock with latest commit on master branch** ``` chef diff --git master ``` **Compare current lock to specified revision** ``` chef diff --git v1.0.0 ``` **Compare lock on master branch to lock on revision** ``` chef diff --git master...dev ``` **Compare lock for version with latest commit on master branch** ``` chef diff --git v1.0.0...master ``` **Compare current lock with latest lock for policy group** ``` chef diff staging ``` **Compare locks for two policy groups** ``` chef diff production...staging ``` ### chef export Use the `chef export` subcommand to create a chef-zero-compatible chef-repo that contains the cookbooks described by a `Policyfile.lock.json` file. After a chef-zero-compatible chef-repo is copied to a node, the policy can be applied locally on that machine by running `chef-client -z` (local mode). #### Syntax This subcommand has the following syntax: ``` chef export POLICY_FILE DIRECTORY (options) ``` #### Options This subcommand has the following options: `-a`, `--archive` Export an archive as a tarball, instead as a directory. Default value: `false`. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-f`, `--force` Remove the contents of the destination directory if that directory is not empty. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef generate policyfile Use the `chef generate policyfile` subcommand to generate a file to be used with Policyfile. #### Syntax This subcommand has the following syntax: ``` chef generate policyfile POLICY_NAME (options) ``` #### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef install Use the `chef install` subcommand to evaluate a policy file and find a compatible set of cookbooks, build a run-list, cache it locally, and then emit a `Policyfile.lock.json` file that describes the locked policy set. The `Policyfile.lock.json` file may be used to install the locked policy set to other machines and may be pushed to a policy group on the Chef Infra Server to apply that policy to a group of nodes that are under management by Chef. #### Syntax This subcommand has the following syntax: ``` chef install POLICY_FILE (options) ``` #### Options This subcommand has the following options: `-D`, `--debug` Enable stack traces and other debug output. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Policyfile.lock.json When the `chef install` command is run, Chef Workstation caches any necessary cookbooks and emits a `Policyfile.lock.json` file that describes: * The versions of cookbooks in use * A Hash of cookbook content * The source for all cookbooks A `Policyfile.lock.json` file is associated with a specific policy group, i.e. is associated with one (or more) nodes that use the same revision of a given policy. A `Policyfile.lock.json` file is similar to: ``` { "revision_id": "288ed244f8db8bff3caf58147e840bbe079f76e0", "name": "jenkins", "run_list": [ "recipe[java::default]", "recipe[jenkins::master]", "recipe[policyfile_demo::default]" ], "cookbook_locks": { "policyfile_demo": { "version": "0.1.0", "identifier": "f04cc40faf628253fe7d9566d66a1733fb1afbe9", "dotted_decimal_identifier": "67638399371010690.23642238397896298.25512023620585", "source": "cookbooks/policyfile_demo", "cache_key": null, "scm_info": null, "source_options": { "path": "cookbooks/policyfile_demo" } }, "java": { "version": "1.24.0", "identifier": "4c24ae46a6633e424925c24e683e0f43786236a3", "dotted_decimal_identifier": "21432429158228798.18657774985439294.16782456927907", "cache_key": "java-1.24.0-supermarket.chef.io", "origin": "https://supermarket.chef.io/api/v1/cookbooks/java/versions/1.24.0/download", "source_options": { "artifactserver": "https://supermarket.chef.io/api/v1/cookbooks/java/versions/1.24.0/download", "version": "1.24.0" } ``` #### Examples None. ### chef push Use the `chef push` subcommand to upload an existing `Policyfile.lock.json` file to the Chef Infra Server, along with all of the cookbooks that are contained in the file. The `Policyfile.lock.json` file will be applied to the specified policy group, which is a set of nodes that share the same run-list and cookbooks. #### Syntax This subcommand has the following syntax: ``` chef push POLICY_GROUP POLICY_FILE (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef push-archive The `chef push-archive` subcommand is used to publish a policy archive file to the Chef Infra Server. (A policy archive is created using the `chef export` subcommand.) The policy archive is assigned to the specified policy group, which is a set of nodes that share the same run-list and cookbooks. #### Syntax This subcommand has the following syntax: ``` chef push-archive POLICY_GROUP ARCHIVE_FILE (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef show-policy Use the `chef show-policy` subcommand to display revisions for every `Policyfile.rb` file that is on the Chef Infra Server. By default, only active policy revisions are shown. When both a policy and policy group are specified, the contents of the active `Policyfile.lock.json` file for the policy group is returned. #### Syntax This subcommand has the following syntax: ``` chef show-policy POLICY_NAME POLICY_GROUP (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-o`, `--orphans` Show policy revisions that are not currently assigned to any policy group. `--[no-]pager` Use `--pager` to enable paged output for a `Policyfile.lock.json` file. Default value: `--pager`. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef undelete Use the `chef undelete` subcommand to recover a deleted policy or policy group. This command: * Does not detect conflicts. If a deleted item has been recreated, running this command will overwrite it * Does not include cookbooks that may be referenced by policy files; cookbooks that are cleaned after running this command may not be fully restorable to their previous state * Does not store access control data #### Syntax This subcommand has the following syntax: ``` chef undelete (options) ``` When run with no arguments, returns a list of available operations. #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. `-h`, `--help` Show help for the command. `-i ID`, `--id ID` Undo the delete operation specified by `ID`. `-l`, `--last` Undo the most recent delete operation. `--list` Default. Return a list of available operations. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef update Use the `chef update` subcommand to read the `Policyfile.rb` file, and then apply any changes. This will resolve dependencies and will create a `Policyfile.lock.json` file. The locked policy will reflect any changes to the run-list and will pull in any cookbook updates that are compatible with any version constraints defined in the `Policyfile.rb` file. #### Syntax This subcommand has the following syntax: ``` chef update POLICY_FILE (options) ``` #### Options This subcommand has the following options: `-a`, `--attributes` Update attributes. Default value: `false`. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/ctl_chef/chef-shell (executable) ======================= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/chef_shell.md) chef-shell is a recipe debugging tool that allows the use of breakpoints within recipes. chef-shell runs as an Interactive Ruby (IRb) session. chef-shell supports both recipe and attribute file syntax, as well as interactive debugging features. The chef-shell executable is run as a command-line tool. Modes ----- chef-shell is tool that is run using an Interactive Ruby (IRb) session. chef-shell currently supports recipe and attribute file syntax, as well as interactive debugging features. chef-shell has three run modes: | Mode | Description | | --- | --- | | Standalone | Default. No cookbooks are loaded, and the run-list is empty. | | Solo | chef-shell acts as a Chef Solo Client. It attempts to load the chef-solo configuration file at `~/.chef/config.rb` and any JSON attributes passed. If the JSON attributes set a run-list, it will be honored. Cookbooks will be loaded in the same way that chef-solo loads them. chef-solo mode is activated with the `-s` or `--solo` command line option, and JSON attributes are specified in the same way as for chef-solo, with `-j /path/to/chef-solo.json`. | | Client | chef-shell acts as a Chef Infra Client. During startup, it reads the Chef Infra Client configuration file from `~/.chef/client.rb` and contacts the Chef Infra Server to get the node's run_list, attributes, and cookbooks. Chef Infra Client mode is activated with the `-z` or `--client` options. You can also specify the configuration file with `-c CONFIG` and the server URL with `-S SERVER_URL`. | Options ------- This command has the following syntax: ``` chef-shell OPTION VALUE OPTION VALUE ... ``` This command has the following options: `-a`, `--standalone` Run chef-shell in standalone mode. `-c CONFIG`, `--config CONFIG` The configuration file to use. `-h`, `--help` Show help for the command. `-j PATH`, `--json-attributes PATH` The path to a file that contains JSON data. Use this option to define a `run_list` object. For example, a JSON file similar to: ``` "run_list": [ "recipe[base]", "recipe[foo]", "recipe[bar]", "role[webserver]" ], ``` may be used by running `chef-shell -j path/to/file.json`. In certain situations this option may be used to update `normal` attributes. Warning Any other attribute type that is contained in this JSON file will be treated as a `normal` attribute. Setting attributes at other precedence levels is not possible. For example, attempting to update `override` attributes using the `-j` option: ``` { "name": "dev-99", "description": "Install some stuff", "override_attributes": { "apptastic": { "enable_apptastic": "false", "apptastic_tier_name": "dev-99.bomb.com" } } } ``` will result in a node object similar to: ``` { "name": "maybe-dev-99", "normal": { "name": "dev-99", "description": "Install some stuff", "override_attributes": { "apptastic": { "enable_apptastic": "false", "apptastic_tier_name": "dev-99.bomb.com" } } } } ``` `-l LEVEL`, `--log-level LEVEL` The level of logging to be stored in a log file. `-o RUN_LIST_ITEM`, `--override-runlist RUN_LIST_ITEM` Replace the current run-list with the specified items. Only applicable when also using `solo` or `server` modes. `-s`, `--solo` Run chef-shell in chef-solo mode. `-S CHEF_SERVER_URL`, `--server CHEF_SERVER_URL` The URL for the Chef Infra Server. `-v`, `--version` The Chef Infra Client version. `-z`, `--client` Run chef-shell in Chef Infra Client mode. Configure --------- chef-shell determines which configuration file to load based on the following: 1. If a configuration file is specified using the `-c` option, chef-shell will use the specified configuration file 2. If a NAMED_CONF is given, chef-shell will load ~/.chef/NAMED_CONF/chef_shell.rb 3. If no NAMED_CONF is given chef-shell will load ~/.chef/chef_shell.rb if it exists 4. If no chef_shell.rb can be found, chef-shell falls back to load: * /etc/chef/client.rb if -z option is given. * /etc/chef/solo.rb if –solo-legacy-mode option is given. * .chef/config.rb if -s option is given. * .chef/knife.rb if -s option is given. ### chef-shell.rb The chef-shell.rb file can be used to configure chef-shell in the same way as the client.rb file is used to configure Chef Infra Client. For example, to configure chef-shell to authenticate to the Chef Infra Server, copy the `node_name`, `client_key`, and `chef_server_url` settings from the config.rb file: ``` node_name 'your-knife-clientname' client_key File.expand_path('~/.chef/my-client.pem') chef_server_url 'https://api.opscode.com/organizations/myorg' ``` and then add them to the chef-shell.rb file. Other configuration possibilities include disabling Ohai plugins (which will speed up the chef-shell boot process) or including arbitrary Ruby code in the chef-shell.rb file. ### Run as a Chef Infra Client By default, chef-shell loads in standalone mode and does not connect to the Chef Infra Server. The chef-shell can be run as a Chef Infra Client to verify functionality that is only available when Chef Infra Client connects to the Chef Infra Server, such as search functionality or accessing data stored in data bags. chef-shell can use the same credentials as knife when connecting to a Chef Infra Server. Make sure that the settings in chef-shell.rb are the same as those in config.rb, and then use the `-z` option as part of the command. For example: ``` chef-shell -z ``` Debugging Cookbooks ------------------- chef-shell allows the current position in a run-list to be manipulated during a Chef Infra Client run. Add breakpoints to a recipe to take advantage of this functionality. ### Step Through Run-list To explore how using the **breakpoint** to manually step through a Chef Infra Client run, create a simple recipe in chef-shell: ``` chef > recipe_mode chef:recipe > echo off chef:recipe > file "/tmp/before-breakpoint" chef:recipe > breakpoint "foo" chef:recipe > file "/tmp/after-breakpoint" ``` and then run Chef Infra Client: ``` chef:recipe > run_chef [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:17:49 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint ``` Chef Infra Client ran the first resource before the breakpoint (`file[/tmp/before-breakpoint]`), but then stopped after execution. Chef Infra Client attempted to name the breakpoint after its position in the source file, but Chef Infra Client was confused because the resource was entered interactively. From here, chef-shell can resume the interrupted Chef Infra Client run: ``` chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:27:08 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` A quick view of the `/tmp` directory shows that the following files were created: ``` after-breakpoint before-breakpoint ``` You can rewind and step through a Chef Infra Client run: ``` chef:recipe > Chef::Log.level = :debug # debug logging won't turn on automatically in this case => :debug chef:recipe > chef_run.rewind => 0 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File => 1 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint => 2 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File => 3 ``` From the output, the rewound run-list is shown, but when the resources are executed again, they will repeat their checks for the existence of files. If they exist, Chef Infra Client will skip creating them. If the files are deleted, then: ``` chef:recipe > ls("/tmp").grep(/breakpoint/).each {|f| rm "/tmp/#{f}" } => ["after-breakpoint", "before-breakpoint"] ``` Rewind, and then resume your Chef Infra Client run to get the expected results: ``` chef:recipe > chef_run.rewind chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:48:56 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:49:20 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` ### Debug Existing Recipe chef-shell can be used to debug existing recipes. The recipe first needs to be added to a run-list for the node, so that it is cached when starting chef-shell and then used for debugging. chef-shell will report which recipes are being cached when it is started: ``` loading configuration: none (standalone session) Session type: standalone Loading.............done. Welcome to the chef-shell 15.8.23 For usage see https://docs.chef.io/chef_shell.html run `help' for help, `exit' or ^D to quit. chef (15.8.23)``` To just load one recipe from the run-list, go into the recipe and use the `include_recipe` command. For example: ``` chef > recipe_mode chef:recipe > include_recipe "getting-started" => [#< Chef::Recipe:0x10256f9e8 @cookbook_name="getting-started", ... output truncated ... ``` To load all of the recipes from a run-list, use code similar to the following: ``` node.run_list.expand(node.chef_environment).recipes.each do |r| include_recipe r end ``` After the recipes that are to be debugged have been loaded, use the `run_chef` command to run them. ### Advanced Debugging In chef-shell, it is possible to get verbose debugging using the tracing feature in Interactive Ruby (IRb). chef-shell provides a shortcut for turning tracing on and off. For example: ``` chef > tracing on tracing is on => nil chef ``` and: ``` chef > tracing off #0:(irb):2:Object:-: tracing off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:109:Shell::Extensions::ObjectCoreExtensions:>: def off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:110:Shell::Extensions::ObjectCoreExtensions:-: :off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:111:Shell::Extensions::ObjectCoreExtensions:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:272:main:>: def tracing(on_or_off) #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:273:main:-: conf.use_tracer = on_or_off.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:162:Shell::Extensions::Symbol:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:163:Shell::Extensions::Symbol:-: to_s.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:149:Shell::Extensions::String:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:150:Shell::Extensions::String:-: case self #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:154:Shell::Extensions::String:-: false #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:158:Shell::Extensions::String:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:164:Shell::Extensions::Symbol:<: end tracing is off => nil chef ``` Manipulating Chef Infra Server Data ----------------------------------- When chef-shell is configured to access a Chef Infra Server, chef-shell can list, show, search for and edit cookbooks, clients, nodes, roles, environments, policyfiles, and data bags. The syntax for managing objects on the Chef Infra Server is as follows: ``` chef-shell -z named_configuration ``` Where: * `named_configuration` is an existing configuration file in `~/.chef/named_configuration/chef_shell.rb`, such as `production`, `staging`, or `test`. Once in chef-shell, commands can be run against objects as follows: ``` chef (preprod) > items.command ``` Where: * `items` is the type of item to search for: `cookbooks`, `clients`, `nodes`, `roles`, `environments` or a data bag. * `command` is the command: `list`, `show`, `find`, or `edit`. For example, to list all of the nodes in a configuration named “preprod”, enter: ``` chef (preprod) > nodes.list ``` Which will return something similar to: ``` => [node[i-f09a939b], node[i-049a936f], node[i-eaaaa581], node[i-9154b1fb], node[i-6a213101], node[i-c2687aa9], node[i-7abeaa11], node[i-4eb8ac25], node[i-9a2030f1], node[i-a06875cb], node[i-145f457f], node[i-e032398b], node[i-dc8c98b7], node[i-6afdf401], node[i-f49b119c], node[i-5abfab31], node[i-78b8ac13], node[i-d99678b3], node[i-02322269], node[i-feb4a695], node[i-9e2232f5], node[i-6e213105], node[i-cdde3ba7], node[i-e8bfb083], node[i-743c2c1f], node[i-2eaca345], node[i-aa7f74c1], node[i-72fdf419], node[i-140e1e7f], node[i-f9d43193], node[i-bd2dc8d7], node[i-8e7f70e5], node[i-78f2e213], node[i-962232fd], node[i-4c322227], node[i-922232f9], node[i-c02728ab], node[i-f06c7b9b]] ``` The `list` command can take a code block, which will applied (but not saved), to each object that is returned from the server. For example: ``` chef (preprod) > nodes.list {|n| puts "#{n.name}: #{n.run_list}" } ``` will return something similar to: ``` => i-f09a939b: role[lb], role[preprod], recipe[aws] i-049a936f: role[lb], role[preprod], recipe[aws] i-9154b1fb: recipe[erlang], role[base], role[couchdb], role[preprod], i-6a213101: role[chef], role[preprod] # more... ``` The `show` command can be used to display a specific node. For example: ``` chef (preprod) > load_balancer = nodes.show('i-f09a939b') ``` will return something similar to: ``` => node[i-f09a939b] ``` Or: ``` chef (preprod) > load_balancer.ec2.public_hostname ``` will return something similar to: ``` => "ec2-111-22-333-44.compute-1.amazonaws.com" ``` The `find` command can be used to search the Chef Infra Server from the chef-shell. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') ``` You can also format the results with a code block. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } and nil ``` will return something similar to: ``` => ["ami-f8927a91", "ami-f8927a91", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1" # and more... ``` Or: ``` chef (preprod) > amis = nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } chef (preprod) > puts amis.uniq.sort ``` will return something similar to: ``` => ami-4b4ba522 ami-a89870c1 ami-eef61587 ami-f8927a91 ``` Examples -------- The following examples show how to use chef-shell. ### “Hello World” This example shows how to run chef-shell in standalone mode. (For chef-solo or Chef Infra Client modes, you would need to run chef-shell using the `-s` or `-z` command line options, and then take into consideration the necessary configuration settings.) When Chef Infra Client is installed using RubyGems or a package manager, chef-shell should already be installed. When Chef Infra Client is run from a git clone, it will be located in `chef/bin/chef shell`. To start chef-shell, just run it without any options. You’ll see the loading message, then the banner, and then the chef-shell prompt: ``` bin/chef-shell loading configuration: none (standalone session) Session type: standalone Loading.............done. Welcome to the chef-shell 15.8.23 For usage see https://docs.chef.io/chef_shell.html run `help' for help, `exit' or ^D to quit. chef (15.8.23)``` (Use the help command to print a list of supported commands.) Use the recipe_mode command to switch to recipe context: ``` chef > recipe_mode chef:recipe_mode ``` Typing is evaluated in the same context as recipes. Create a file resource: ``` chef:recipe_mode > file "/tmp/ohai2u_shef" => #< Chef::Resource::File:0x1b691ac @enclosing_provider=nil, @resource_name=:file, @before=nil, @supports={}, @backup=5, @allowed_actions=[:nothing, :create, :delete, :touch, :create_if_missing], @only_if=nil, @noop=nil, @collection=#< Chef::ResourceCollection:0x1b9926c @insert_after_idx=nil, @resources_by_name={"file[/tmp/ohai2u_shef]"=>0}, @resources=[#< Chef::Resource::File:0x1b691ac ...>]>, @updated=false, @provider=nil, @node=< Chef::Node:0xdeeaae @name="eigenstate.local">, @recipe_name=nil, @not_if=nil, @name="/tmp/ohai2u_shef", @action="create", @path="/tmp/ohai2u_shef", @source_line="/Users/username/ruby/chef/chef/(irb#1) line 1", @params={}, @actions={}, @cookbook_name=nil, @ignore_failure=false``` (The previous example was formatted for presentation.) At this point, chef-shell has created the resource and put it in the run-list, but not yet created the file. To initiate a Chef Infra Client run, use the `run_chef` command: ``` chef:recipe_mode > run_chef [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: Processing file[/tmp/ohai2u_shef] [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File [Fri, 15 Jan 2020 10:42:47 -0800] INFO: Creating file[/tmp/ohai2u_shef] at /tmp/ohai2u_shef => true ``` chef-shell can also switch to the same context as attribute files. Set an attribute with the following syntax: ``` chef:recipe_mode > attributes_mode chef:attributes > default[:hello] = "ohai2u-again" => "ohai2u-again" chef:attributes ``` Switch back to recipe_mode context and use the attributes: ``` chef:attributes > recipe_mode => :attributes chef:recipe_mode > file "/tmp/#{node.hello}" ``` Now, run Chef Infra Client again: ``` chef:recipe_mode > run_chef [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u_shef] [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u-again] [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u-again] using Chef::Provider::File [Fri, 15 Jan 2020 10:53:22 -0800] INFO: Creating file[/tmp/ohai2u-again] at /tmp/ohai2u-again => true chef:recipe_mode ``` Because the first resource (`file[/tmp/ohai2u_shef]`) is still in the run-list, it gets executed again. And because that file already exists, Chef Infra Client doesn’t attempt to re-create it. Finally, the files were created using the `ls` method: ``` chef:recipe_mode > ls("/tmp").grep(/ohai/) => ["ohai2u-again", "ohai2u_shef"] Shell Tutorial ``` ### Get Specific Nodes To get a list of nodes using a recipe named `postfix` use `search(:node,"recipe:postfix")`. To get a list of nodes using a sub-recipe named `delivery`, use chef-shell. For example: ``` search(:node, 'recipes:postfix\:\:delivery') ``` Note Single (' ‘) vs. double (" “) is important. This is because a backslash () needs to be included in the string, instead of having Ruby interpret it as an escape. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/chef_shell/Chef Workstation App ==================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/chef-workstation-app.md) About Chef Workstation App ========================== The Chef Workstation App (CWA) is an early-release desktop application that provides additional services for Chef Workstation: * Update checking and notifications * Chef Workstation version information Additional features and integrations will be rolled out in future updates. Running the Chef Workstation App -------------------------------- ### Windows Launch Chef Workstation App from the Chef Workstation folder in the Start menu. ### Linux Start Chef Workstation App by running the command `chef-workstation-app`. #### Notes 1. Chef Workstation App requires a running display manager with support for system tray icons. 2. On some distributions you may need to install additional libraries. The post-install message shown when you install the Chef Workstation package from the terminal will tell you which – if any – additional libraries are required to run Chef Workstation App. ### Mac Start `Chef Workstation App` from your Applications folder. Disabling Automatic Update Checks --------------------------------- To disable CWA’s automatic update checking, add or modify the `enable` setting under `updates` in [config.toml](../config/index#updates): ``` [updates] enable=false ``` Setting Update Channel ---------------------- To set the channel used for update checking, bring up the CWA tray app menu (Windows/Linux) or the application menu (Mac) and select “About Chef Workstation”. Select the “Channel” button and choose your preferred channel. This will trigger an immediate update check. ``` [updates] channel="current" ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/chef-workstation-app/Chef Vault ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/chef_vault.md) `chef-vault` is a Ruby Gem that is included in Chef Workstation and Chef Infra Client. Chef Vault lets you encrypt a data bag item using asymmetric keys. When you provide Chef Vault with a list of public keys from your nodes, only the nodes with public keys entered on this list can decrypt the data bag item contents. Chef Vault is included in Chef Workstation and Chef Infra Client by way of the `chef-vault` Ruby Gem. `chef-vault` uses the `knife vault` subcommand. Note Chef Vault does not currently support alternate keying mechanisms like GPG and Amazon KMS. Warning To use Chef Vault, Chef Infra Client must be configured to use public/private key pairs. Chef Vault is incompatible with the practice of using Chef Infra Client with a private key, such as `client.pem`, and a certificate set as its public identity in the Chef Infra Server database. To update existing nodes to use `chef-vault`, first re-register your Chef Infra Client nodes with the Chef Infra Server which will generate public/private key pairs, and then install Chef Vault on each node. If Chef Vault is used with a Chef Infra Client instance that has a private key, such as `client.pem`, and a certificate set as its public identity in the Chef Infra Server database, Chef Vault will generate the following error: ``` ## OpenSSL::PKey::RSAError Neither PUB key nor PRIV key:: nested asn1 error ``` ### Configuring config.rb for Chef Vault To set ‘client’ as the default mode, add the following line to the config.rb file. ``` knife[:vault_mode] = 'client' ``` To set the default list of admins for creating and updating vaults, add the following line to the config.rb file. ``` knife[:vault_admins] = [ 'example-alice', 'example-bob', 'example-carol' ] ``` (These values can be overridden on the command line by using `-A`) ### Syntax ``` knife vault SUBCOMMAND VAULT ITEM VALUES ``` where: * `vault` names the location for storing the encrypted item. * `item` names the item stored in the vault. * `values` contains the data that will be encrypted and stored in the vault. ### Vault Commands ``` knife vault create VAULT ITEM VALUES (options) knife vault delete VAULT ITEM (options) knife vault download VAULT ITEM PATH (options) knife vault edit VAULT ITEM (options) knife vault isvault VAULT ITEM (options) knife vault itemtype VAULT ITEM (options) knife vault list (options) knife vault refresh VAULT ITEM knife vault remove VAULT ITEM VALUES (options) knife vault rotate all keys knife vault rotate keys VAULT ITEM (options) knife vault show VAULT [ITEM] [VALUES] (options) knife vault update VAULT ITEM VALUES (options) ``` ### Vault Common Options `-A`, `--admins ADMINS` Chef users to be added as admins `-s`, `--server-url URL` Chef Infra Server URL `--chef-zero-host HOST` Host to start chef-zero on `--chef-zero-port PORT` Port (or port range) to start chef-zero on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works. `-k`, `--key KEY` API Client Key `-C`, `--clients CLIENTS` Chef clients to be added as clients `--[no-]color` Use colored output, defaults to enabled `-c`, `--config CONFIG` The configuration file to use `--config-option OPTION=VALUE` Override a single configuration option `--defaults` Accept default values for all questions `-d`, –disable-editing Do not open EDITOR, just accept the data as is `-e`, `--editor EDITOR` Set the editor to use for interactive commands `-E`, `--environment ENVIRONMENT` Set the Chef environment (except for in searches, where this will be flagrantly ignored) `--file FILE` File to be added to vault item as file-content `--[no-]fips` Enable or disable fips mode `-F`, `--format FORMAT` Which format to use for output `-J`, `--json FILE` File containing JSON data to encrypt `-K`, `--keys-mode KEYS_MODE` Mode in which to save vault keys `--[no-]listen` Whether a local mode (-z) server binds to a port `-z`, `--local-mode` Point knife commands at local repository instead of server `-u`, `--user USER` API Client Username `--print-after` Show the data after a destructive operation `-S`, `--search SEARCH` Chef SOLR search for clients `-M`, `--mode MODE` Chef mode to run in. Default Value: `solo` `-V`, `--verbose` More verbose output. Use twice for max verbosity `-v`, `--version` Show chef version `-y`, `--yes` Say yes to all prompts for confirmation `-h`, `--help` Show this message ### Example Commands ### `create` Create a vault called passwords and put an item called root in it with the given values for username and password encrypted for clients role:webserver, client1 & client2 and admins admin1 & admin2 ``` knife vault create passwords root '{"username": "root", "password": "mypassword"}' -S "role:webserver" -C "client1,client2" -A "admin1,admin2" ``` Create a vault called passwords and put an item called root in it with the given values for username and password encrypted for clients role:webserver and admins admin1 & admin2 ``` knife vault create passwords root '{"username": "root", "password": "mypassword"}' -S "role:webserver" -A "admin1,admin2" ``` Create a vault called passwords and put an item called root in it with the given values for username and password encrypted for clients role:webserver, client1 & client2 ``` knife vault create passwords root '{"username": "root", "password": "mypassword"}' -S "role:webserver" -C "client1,client2" ``` Create a vault called passwords and put an item called root in it with the given values for username and password encrypted for clients role:webserver ``` knife vault create passwords root '{"username": "root", "password": "mypassword"}' -S "role:webserver" ``` Create a vault called passwords and put an item called root in it with the given values for username and password encrypted for clients client1 & client2 ``` knife vault create passwords root '{"username": "root", "password": "mypassword"}' -C "client1,client2" ``` Create a vault called passwords and put an item called root in it with the given values for username and password encrypted for admins admin1 & admin2 ``` knife vault create passwords root '{"username": "root", "password": "mypassword"}' -A "admin1,admin2" ``` Create a vault called passwords and put an item called root in it encrypted for admins admin1 & admin2. *Leaving the data off the command-line will open an editor to fill out the data* ``` knife vault create passwords root -A "admin1,admin2" ``` Note A JSON file can be used in place of specifying the values on the command line, see global options below for details ### `update` Update the values in username and password in the vault passwords and item root. Will overwrite existing values if values already exist! ``` knife vault update passwords root '{"username": "root", "password": "mypassword"}' ``` Update the values in username and password in the vault passwords and item root and add role:webserver, client1 & client2 to the encrypted clients and admin1 & admin2 to the encrypted admins. Will overwrite existing values if values already exist! ``` knife vault update passwords root '{"username": "root", "password": "mypassword"}' -S "role:webserver" -C "client1,client2" -A "admin1,admin2" ``` Update the values in username and password in the vault passwords and item root and add role:webserver to the encrypted clients and admin1 & admin2 to the encrypted admins. Will overwrite existing values if values already exist! ``` knife vault update passwords root '{"username": "root", "password": "mypassword"}' -S "role:webserver" -A "admin1,admin2" ``` Update the values in username and password in the vault passwords and item root and add role:webserver to the encrypted clients. Will overwrite existing values if values already exist! ``` knife vault update passwords root '{"username": "root", "password": "mypassword"}' -S "role:webserver" ``` Update the values in username and password in the vault passwords and item root and add client1 & client2 to the encrypted clients. Will overwrite existing values if values already exist! ``` knife vault update passwords root '{"username": "root", "password": "mypassword"}' -C "client1,client2" ``` Update the values in username and password in the vault passwords and item root and add admin1 & admin2 to the encrypted admins. Will overwrite existing values if values already exist! ``` knife vault update passwords root '{"username": "root", "password": "mypassword"}' -A "admin1,admin2" ``` Add role:webserver to encrypted clients for the vault passwords and item root. ``` knife vault update passwords root -S "role:webserver" ``` Add client1 & client2 to encrypted clients for the vault passwords and item root. ``` knife vault update passwords root -C "client1,client2" ``` Add admin1 & admin2 to encrypted admins for the vault passwords and item root. ``` knife vault update passwords root -A "admin1,admin2" ``` Add admin1 & admin2 to encrypted admins and role:webserver, client1 & client2 to encrypted clients for the vault passwords and item root. ``` knife vault update passwords root -S "role:webserver" -C "client1,client2" -A "admin1,admin2" ``` Add admin1 & admin2 to encrypted admins and role:webserver to encrypted clients for the vault passwords and item root. ``` knife vault update passwords root -S "role:webserver" -A "admin1,admin2" ``` Add admin1 & admin2 to encrypted admins and client1 & client2 to encrypted clients for the vault passwords and item root. ``` knife vault update passwords root -C "client1,client2" -A "admin1,admin2" ``` ..Note:: A JSON file can be used in place of specifying the values on the command line, see global options below for details ### `remove` Remove the values in username and password from the vault passwords and item root. ``` knife vault remove passwords root '{"username": "root", "password": "mypassword"}' ``` Remove the values in username and password from the vault passwords and item root and remove role:webserver, client1 & client2 from the encrypted clients and admin1 & admin2 from the encrypted admins. ``` knife vault remove passwords root '{"username": "root", "password": "mypassword"}' -S "role:webserver" -C "client1,client2" -A "admin1,admin2" ``` Remove the values in username and password from the vault passwords and item root and remove role:webserver from the encrypted clients and admin1 & admin2 from the encrypted admins. ``` knife vault remove passwords root '{"username": "root", "password": "mypassword"}' -S "role:webserver" -A "admin1,admin2" ``` Remove the values in username and password from the vault passwords and item root and remove client1 & client2 from the encrypted clients and admin1 & admin2 from the encrypted admins. ``` knife vault remove passwords root '{"username": "root", "password": "mypassword"}' -C "client1,client2" -A "admin1,admin2" ``` Remove the values in username and password from the vault passwords and item root and remove role:webserver from the encrypted clients. ``` knife vault remove passwords root '{"username": "root", "password": "mypassword"}' -S "role:webserver" ``` Remove the values in username and password from the vault passwords and item root and remove client1 & client2 from the encrypted clients. ``` knife vault remove passwords root '{"username": "root", "password": "mypassword"}' -C "client1,client2" ``` Remove the values in username and password from the vault passwords and item root and remove admin1 & admin2 from the encrypted admins. ``` knife vault remove passwords root '{"username": "root", "password": "mypassword"}' -A "admin1,admin2" ``` Remove admin1 & admin2 from encrypted admins and role:webserver, client1 & client2 from encrypted clients for the vault passwords and item root. ``` knife vault remove passwords root -S "role:webserver" -C "client1,client2" -A "admin1,admin2" ``` Remove admin1 & admin2 from encrypted admins and role:webserver from encrypted clients for the vault passwords and item root. ``` knife vault remove passwords root -S "role:webserver" -A "admin1,admin2" ``` Remove role:webserver from encrypted clients for the vault passwords and item root. ``` knife vault remove passwords root -S "role:webserver" ``` Remove client1 & client2 from encrypted clients for the vault passwords and item root. ``` knife vault remove passwords root -C "client1,client2" ``` Remove admin1 & admin2 from encrypted admins for the vault passwords and item root. ``` knife vault remove passwords root -A "admin1,admin2" ``` ### `delete` Delete the item root from the vault passwords ``` knife vault delete passwords root ``` ### `show` Show the items in a vault. ``` knife vault show passwords ``` Show the entire root item in the passwords vault and print in JSON format. ``` knife vault show passwords root -Fjson ``` Show the entire root item in the passwords vault and print in JSON format, including the search query, clients, and admins. ``` knife vault show passwords root -Fjson -p all ``` Show the username and password for the item root in the vault passwords. ``` knife vault show passwords root "username, password" ``` Show the contents for the item user_pem in the vault certs. ``` knife vault show certs user_pem "contents" ``` ### `edit` Decrypt the entire root item in the passwords vault and open it in json format in your $EDITOR. Writing and exiting out the editor will save and encrypt the vault item. ``` knife vault edit passwords root ``` ### `download` Decrypt and download an encrypted file to the specified path. ``` knife vault download certs user_pem ~/downloaded_user_pem ``` ### `rotate keys` Rotate the shared key for the vault passwords and item root. The shared key is that which is used for the chef encrypted data bag item. ``` knife vault rotate keys passwords root ``` To remove clients which have been deleted from Chef but not from the vault, add the `--clean-unknown-clients` switch: ``` knife vault rotate keys passwords root --clean-unknown-clients ``` ### `rotate all keys` Rotate the shared key for all vaults and items. The shared key is that which is used for the chef encrypted data bag item. ``` knife vault rotate all keys ``` Removes clients which have been deleted from Chef but not from the vault. ``` knife vault rotate keys passwords root --clean-unknown-clients ``` ### `refresh` This command reads the search_query in the vault item, performs the search, and reapplies the results. ``` knife vault refresh VAULT ITEM ``` To remove clients which have been deleted from Chef but not from the vault, add the `--clean-unknown-clients` switch: ``` knife vault refresh passwords root --clean-unknown-clients ``` ### `isvault` This command checks if the given item is a vault or not, and exit with a status of 0 if it is and 1 if it is not. ``` knife vault isvault VAULT ITEM ``` ### `itemtype` This command outputs the type of the data bag item: normal, encrypted or vault ``` knife vault itemtype VAULT ITEM ``` ### Global Options | Short Command | Long Command | Description | Default | Valid Values | Sub-Commands | | --- | --- | --- | --- | --- | --- | | `-M`, `MODE` | `--mode MODE` | Chef mode to run in. Can be set in config.rb | `solo` | `solo`, `client` | all | | `-S` `SEARCH` | `--search SEARCH` | Chef Infra Server SOLR Search Of Nodes | none | none | `create`, `remove` , `update` | | `-A` `ADMINS` | `--admins ADMINS` | Chef clients or users to be vault admins, can be comma list | none | none | `create`, `remove` , `update` | | `-J` `FILE` | `--json FILE` | JSON file to be used for values, will be merged with VALUES if VALUES is passed | none | none | `create`, `update` | | `--file` `FILE` | none | File that `chef-vault` should encrypt. It adds “file-content” & “file-name” keys to the vault item | none | none | `create`, `update` | | `-p` `DATA` | `--print DATA` | Print extra vault data | none | `search`, `clients`, `admins`, `all` | `show` | | `-F` `FORMAT` | `--format FORMAT` | Format for decrypted output | summary | `summary`, `json`, `yaml`, `pp` | `show` | | –clean-unknown-clients | none | Remove unknown clients during key rotation | none | none | `refresh`, `remove`, `rotate` | Options for knife bootstrap --------------------------- Use the following options with a validatorless bootstrap to specify items that are stored in Chef Vault: `--bootstrap-vault-file VAULT_FILE` The path to a JSON file that contains a list of vaults and items to be updated. `--bootstrap-vault-item VAULT_ITEM` A single vault and item to update as `vault:item`. `--bootstrap-vault-json VAULT_JSON` A JSON string that contains a list of vaults and items to be updated. –bootstrap-vault-json ‘{ “vault1”: [“item1”, “item2”], “vault2”: “item2” }’ ### Using Chef Vault in recipes To use this gem in a recipe to decrypt data you must first install the gem via a chef_gem resource. Once the gem is installed, `require` the gem and then you can create a new instance of Chef Vault. Chef Vault 1.0 style decryption is supported, however it has been deprecated and Chef Vault 2.0 decryption should be used instead ### Example Code ``` chef_gem 'chef-vault' do compile_time true if respond_to?(:compile_time) end # require 'chef-vault' # item = ChefVault::Item.load("passwords", "root") item["password"] ``` Note that in this case, the gem needs to be installed at compile time because the require statement is at the top-level of the recipe. If you move the require of `chef-vault` and the call to `::load` to library or provider code, you can install the gem in the converge phase instead. ### Specifying an alternate node name or client key path Normally, the value of `Chef::Config[:node_name]` is used to find the per-node encrypted secret in the keys data bag item, and the value of Chef::Config[:client_key] is used to locate the private key to decrypt this secret. These can be overridden by passing a hash with the keys `:node_name` or `:client_key_path` to `ChefVault::Item.load`: ``` item = ChefVault::Item.load( 'passwords', 'root', node_name: 'service_foo', client_key_path: '/secure/place/service_foo.pem' ) item['password'] ``` The above example assumes that you have transferred `/secure/place/service_foo.pem` to your system via a secure channel. This usage allows you to decrypt a vault using a key shared among several nodes, which can be helpful when working in cloud environments or other configurations where nodes are created dynamically. ### chef_vault_item helper The [chef-vault cookbook](https://supermarket.chef.io/cookbooks/chef-vault/) contains a recipe to install the `chef-vault` gem and a helper method `chef_vault_item` which makes it easier to test cookbooks that use Chef Vault using Test Kitchen. ### Determining if Item is a Vault Chef Vault provides a helper method to determine if a data bag item is a vault, which can be helpful if you produce a recipe for community consumption and want to support both normal data bags and vaults: ``` if ChefVault::Item.vault?('passwords', 'root') item = ChefVault::Item.load('passwords', 'root') else item = Chef::DataBagItem.load('passwords', 'root') end ``` This functionality is also available from the command line as `knife vault isvault VAULT ITEM`. ### Determining Data Bag Item Type Chef Vault provides a helper method to determine the type of a data bag item. It returns one of the symbols :normal, :encrypted or :vault ``` case ChefVault::Item.data_bag_item_type('passwords', 'root') when :normal ... when :encrypted ... when :vault end ``` This functionality is also available from the command line as `knife vault itemtype VAULT ITEM`. ### Stand Alone Usage The `chef-vault` gem can be used as a stand-alone binary to decrypt values stored in Chef. It requires that Chef is installed on the system and that you have a valid `config.rb`. This is useful if you want to mix Chef Vault into non-Chef recipe code, for example some other script where you want to protect a password. It does still require that the data bag has been encrypted for the user’s or client’s pem and pushed to the Chef Infra Server. It mixes Chef into the gem and uses it to go grab the data bag. Use `chef-vault --help` to see all all available options ### Example usage (password) ``` chef-vault -v passwords -i root -a password -k /etc/chef/config.rb ``` ### Testing To stub vault items in ChefSpec, use the [chef-vault-testfixture](https://rubygems.org/gems/chef-vault-testfixtures) gem. To fall back to unencrypted JSON files in Test Kitchen, use the `chef_vault_item` helper in the aforementioned chef-vault cookbook. More Information ---------------- For more information about `chef-vault`: * [<NAME>’s blog post](https://blog.chef.io/2016/01/21/chef-vault-what-is-it-and-what-can-it-do-for-you/) * [<NAME>’s blog post](https://www.chef.io/blog/2013/09/19/managing-secrets-with-chef-vault/) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/chef_vault/config.rb ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/config_rb.md) Warning The `config.rb` file is a replacement for the `knife.rb` file. The `config.rb` file has identical settings and behavior to the `knife.rb` file. Chef Infra Client looks first for the presence of the `config.rb` file and if it is not found, then looks for the `knife.rb` file. A `config.rb` file is used to specify configuration details for knife. A `config.rb` file: * Is loaded every time the knife executable is run * Is not created by default * Is located by default at `~/.chef/config.rb` (macOS and Linux platforms) or `c:\Users\username\.chef\config.rb` (Microsoft Windows platform), use the `--config` option from the command line to change this location * Will override the default configuration when a `config.rb` file exists at the default path or the path specified by the `--config` option Note When running Microsoft Windows, the `config.rb` file is located at `%HOMEDRIVE%:%HOMEPATH%\.chef` (e.g. `c:\Users\<username>\.chef`). Settings -------- This configuration file has the following settings: `bootstrap_template` The path to a template file to be used during a bootstrap operation. `chef_server_url` The URL for the Chef Infra Server. For example: ``` chef_server_url 'https://localhost/organizations/ORG_NAME' ``` Note If changes need to be made to any global end points like user or user keys, use [`knife exec`](../knife_exec/index) with the `--server-url` flag to set `chef_server_url` to `https://localhost/`. `chef_zero.enabled` Enable chef-zero. This setting requires `local_mode` to be set to `true`. Default value: `false`. For example: ``` chef_zero.enabled true ``` `chef_zero[:port]` The port on which chef-zero is to listen. Default value: `8889`. For example: ``` chef_zero[:port] 8889 ``` `client_d_dir` A directory that contains additional configuration scripts to load for Chef Infra Client. `client_key` The location of the file that contains the client key, as an absolute path. Default value: `/etc/chef/client.pem`. For example: ``` client_key '/etc/chef/client.pem' ``` `cookbook_copyright` The name of the copyright holder. This option places a copyright notice that contains the name of the copyright holder in each of the pre-created files. If this option is not specified, a copyright name of “COMPANY_NAME” is used instead; it can easily be modified later. `cookbook_email` The email address for the individual who maintains the cookbook. This option places an email address in each of the pre-created files. If not specified, an email name of “YOUR_EMAIL” is used instead; this can easily be modified later. `cookbook_license` The type of license under which a cookbook is distributed: `apachev2`, `gplv2`, `gplv3`, `mit`, or `none` (default). This option places the appropriate license notice in the pre-created files: `Apache v2.0` (for `apachev2`), `GPL v2` (for `gplv2`), `GPL v3` (for `gplv3`), `MIT` (for `mit`), or `license 'Proprietary - All Rights Reserved` (for `none`). Be aware of the licenses for files inside of a cookbook and be sure to follow any restrictions they describe. `cookbook_path` The Chef Infra Client sub-directory for storing cookbooks. This value can be a string or an array of file system locations, processed in the specified order. The last cookbook is considered to override local modifications. For example: ``` cookbook_path [ '/var/chef/cookbooks', '/var/chef/site-cookbooks' ] ``` `data_bag_encrypt_version` The minimum required version of data bag encryption. Possible values: `1` or `2`. When all of the machines in an organization are running Chef Client 11.6 (or higher), it is recommended that this value be set to `2`. For example: ``` data_bag_encrypt_version 2 ``` `fips` Allows OpenSSL to enforce FIPS-validated security during a Chef Infra Client run. Set to `true` to enable FIPS-validated security. The following operating systems are supported: * Red Hat Enterprise Linux * Oracle Enterprise Linux * CentOS * Windows `local_mode` Run Chef Infra Client in local mode. This allows all commands that work against the Chef Infra Server to also work against the local chef-repo. For example: ``` local_mode true ``` `node_name` The name of the node. This may be a username with permission to authenticate to the Chef Infra Server or it may be the name of the machine from which knife is run. For example: ``` node_name 'user_name' ``` or: ``` node_name 'machine_name' ``` `no_proxy` A comma-separated list of URLs that do not need a proxy. Default value: `nil`. For example: ``` no_proxy 'localhost, 10.0.1.35, *.example.com, *.dev.example.com' ``` `ssh_agent_signing` **New in 14.2** Use `ssh-agent` to authenticate. When using this option, specify the location of the public key in `client_key`. Default value: `false`. Ensure the public key is in PKCS#1 format. You can convert an OpenSSH public key using `ssh-keygen`. For example: ``` ssh-keygen -f key.pub -e -m pem > key.pem ``` `ssh_timeout` The amount of time (in seconds) to wait for an SSH connection time out. `ssl_verify_mode` Set the verify mode for HTTPS requests. * Use `:verify_none` to do no validation of SSL certificates. * Use `:verify_peer` to do validation of all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS **remote_file** resource URLs used in a Chef Infra Client run. This is the recommended setting. Depending on how OpenSSL is configured, the `ssl_ca_path` may need to be specified. Default value: `:verify_peer`. `tmux_split` Split the Tmux window. Default value: `false`. `validation_client_name` The name of the chef-validator key that is used by Chef Infra Client to access the Chef Infra Server during the initial Chef Infra Client run when not using validatorless bootstrapping. For example: ``` validation_client_name 'chef-validator' ``` `validation_key` The location of the file that contains the key used when a Chef Infra Client is registered with a Chef Infra Server. A validation key is signed using the `validation_client_name` for authentication. Default value: `/etc/chef/validation.pem`. For example: ``` validation_key '/etc/chef/validation.pem' ``` `verify_api_cert` Verify the SSL certificate on the Chef Infra Server. When `true`, Chef Infra Client always verifies the SSL certificate. When `false`. Chef Infra Client uses the value of `ssl_verify_mode` to determine if the SSL certificate requires verification. Default value: `false`. `versioned_cookbooks` Append cookbook versions to cookbooks. Set to `false` to hide cookbook versions: `cookbooks/apache`. Set to `true` to show cookbook versions: `cookbooks/apache-1.0.0` and/or `cookbooks/apache-1.0.1`. When this setting is `true`, `knife download` downloads ALL cookbook versions, which can be useful if a full-fidelity backup of data on the Chef Infra Server is required. For example: ``` versioned_cookbooks true ``` `config_log_level` Sets the default value of `log_level` in the client.rb file of the node being bootstrapped. Possible values are `:debug`, `:info`, `:warn`, `:error` and `:fatal`. For example: ``` config_log_level :debug ``` `config_log_location` Sets the default value of `log_location` in the client.rb file of the node being bootstrapped. Possible values are `/path/to/log_location`, `STDOUT`, `STDERR`, `:win_evt` and `:syslog`. For example: ``` config_log_location "/path/to/log_location" # Please make sure that the path exists ``` ### Proxy Settings In certain situations the proxy used by the Chef Infra Server requires authentication. In this situation, three settings must be added to the configuration file. Which settings to add depends on the protocol used to access the Chef Infra Server: HTTP or HTTPS. If the Chef Infra Server is configured to use HTTP, add the following settings: `http_proxy` The proxy server for HTTP connections. Default value: `nil`. For example: ``` http_proxy 'http://proxy.example.com:3128' ``` `http_proxy_user` The user name for the proxy server when the proxy server is using an HTTP connection. Default value: `nil`. `http_proxy_pass` The password for the proxy server when the proxy server is using an HTTP connection. Default value: `nil`. #### HTTPS Proxy Settings (such as the hosted Chef Infra Server) `https_proxy` The proxy server for HTTPS connections. (The hosted Chef Infra Server uses an HTTPS connection.) Default value: `nil`. `https_proxy_user` The user name for the proxy server when the proxy server is using an HTTPS connection. Default value: `nil`. `https_proxy_pass` The password for the proxy server when the proxy server is using an HTTPS connection. Default value: `nil`. #### Settings for No-proxy URLs `no_proxy` A comma-separated list of URLs that do not need a proxy. Default value: `nil`. .d Directories -------------- Chef Infra Client supports reading multiple configuration files by putting them inside a `.d` configuration directory. For example: `/etc/chef/client.d`. All files that end in `.rb` in the `.d` directory are loaded; other non-`.rb` files are ignored. `.d` directories may exist in any location where the `client.rb`, `config.rb`, or `solo.rb` files are present, such as: * `/etc/chef/client.d` * `/etc/chef/config.d` * `~/chef/solo.d` (There is no support for a `knife.d` directory; use `config.d` instead.) For example, when using knife, the following configuration files would be loaded: * `~/.chef/config.rb` * `~/.chef/config.d/company_settings.rb` * `~/.chef/config.d/ec2_configuration.rb` * `~/.chef/config.d/old_settings.rb.bak` The `old_settings.rb.bak` file is ignored because it’s not a configuration file. The `config.rb`, `company_settings.rb`, and `ec2_configuration` files are merged together as if they are a single configuration file. Note If multiple configuration files exists in a `.d` directory, ensure that the same setting has the same value in all files. Optional Settings ----------------- In addition to the default settings in a `config.rb` file, there are other subcommand-specific settings that can be added: 1. A value passed via the command-line 2. A value contained in the `config.rb` file 3. The default value A value passed via the command line overrides a value in the `config.rb` file; a value in a `config.rb` file overrides a default value. Before adding any settings to the `config.rb` file: * Verify the settings by reviewing the documentation for the knife subcommands and/or knife plugins * Verify the use case(s) your organization has for adding them Also note that: * Custom plugins can be configured to use the same settings as the core knife subcommands * Many of these settings are used by more than one subcommand and/or plugin * Some of the settings are included only because knife checks for a value in the `config.rb` file To add settings to the `config.rb` file, use the following syntax: ``` knife[:setting_name] = value ``` where `value` may require quotation marks (' ‘) if that value is a string. For example: ``` knife[:ssh_port] = 22 knife[:bootstrap_template] = 'ubuntu14.04-gems' knife[:bootstrap_version] = '' knife[:bootstrap_proxy] = '' ``` ### Frequently Used Some of the optional `config.rb` settings are used often, such as the template file used in a bootstrap operation. The frequency of use of any option varies from organization to organization, so even though the following settings are often added to a `config.rb` file, they may not be the right settings to add for every organization: `knife[:bootstrap_proxy]` The proxy server for the node that is the target of a bootstrap operation. `knife[:bootstrap_template]` The path to a template file to be used during a bootstrap operation. `knife[:bootstrap_version]` The version of Chef Infra Client to install. `knife[:editor]` The $EDITOR that is used for all interactive commands. `knife[:ssh_gateway]` The SSH tunnel or gateway that is used to run a bootstrap action on a machine that is not accessible from the workstation. Adding this setting can be helpful when a user cannot SSH directly into a host. `knife[:ssh_port]` The SSH port. ### Additional SSH Settings Other SSH-related settings that are sometimes helpful when added to the `config.rb` file: `knife[:forward_agent]` Enable SSH agent forwarding. `knife[:ssh_attribute]` The attribute used when opening an SSH connection. `knife[:ssh_password]` The SSH password. This can be used to pass the password directly on the command line. If this option is not specified (and a password is required) knife prompts for the password. `knife[:ssh_user]` The SSH user name. ### Data Bag Settings Some organizations choose to have all data bags use the same secret and secret file, rather than have a unique secret and secret file for each data bag. To use the same secret and secret file for all data bags, add the following to `config.rb`: `knife[:secret]` The encryption key that is used for values contained within a data bag item. `knife[:secret_file]` The path to the file that contains the encryption key. ### Ohai Settings (Not Recommended) Some settings are better left to Ohai, which gets the value at the start of a Chef Infra Client run: `knife[:server_name]` Same as `node_name`. Recommended configuration is to allow Ohai to collect this value during each Chef Infra Client run. `node_name` Same as `knife[:server_name]`. Recommended configuration is to allow Ohai to collect this value during each Chef Infra Client run. Warning Review the full list of [optional settings](../config_rb_optional_settings/index) that can be added to the `config.rb` file. Many of these optional settings should not be added to the `config.rb` file. The reasons for not adding them can vary. For example, using `--yes` as a default in the `config.rb` file causes knife to always assume that “Y” is the response to any prompt, which may lead to undesirable outcomes. Other settings, such as `--hide-healthy`(used only with the `knife status` subcommand) or `--bare-directories` (used only with the `knife list` subcommand) probably aren’t used often enough (and in the same exact way) to justify adding them to the `config.rb` file. In general, if the optional settings are not listed on the main config.rb[topic](index), then add settings only after careful consideration. Do not use optional settings in a production environment until after the setting’s performance has been validated in a safe testing environment. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/config_rb/ChefSpec ======== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/chefspec.md) Use ChefSpec to simulate the convergence of resources on a node: * Is an extension of RSpec, a behavior-driven development (BDD) framework for Ruby * Is the fastest way to test resources and recipes ChefSpec is a framework that tests resources and recipes as part of a simulated Chef Infra Client run. ChefSpec tests execute very quickly. When used as part of the cookbook authoring workflow, ChefSpec tests are often the first indicator of problems that may exist within a cookbook. Run ChefSpec ------------ ChefSpec is packaged as part of Chef Workstation. To run ChefSpec: ``` chef exec rspec ``` Unit Tests ---------- RSpec is a behavior-driven development (BDD) framework that uses a natural language domain-specific language (DSL) to quickly describe scenarios in which systems are being tested. RSpec allows a scenario to be set up, and then executed. The results are compared to a set of defined expectations. ChefSpec is built on the RSpec DSL. ### Syntax The syntax of RSpec-based tests should follow the natural language descriptions of RSpec itself. The tests themselves should create an English-like sentence: “The sum of one plus one equals two, and not three.” For example: ``` describe '1 plus 1' do it 'equals 2' do a = 1 b = 1 sum = a + b expect(sum).to eq(2) expect(sum).not_to eq(3) end end ``` where: * `describe` creates the testing scenario: `1 plus 1` * `it` is a block that defines a list of parameters to test, along with parameters that define the expected outcome * `describe` and `it` should have human readable descriptions: “one plus one equals two” * `a`, `b`, and `sum` define the testing scenario: `a` equals one, `b` equals one, the `sum` of one plus equals two * `expect()` defines the expectation: the sum of one plus one equals two—`expect(sum).to eq(2)`—and does not equal three–`expect(sum).not_to eq(3)` * `.to` tests the results of the test for true; `.not_to` tests the result of the test for false; a test passes when the results of the test are true #### context RSpec-based tests may contain `context` blocks. Use `context` blocks within `describe` blocks to define “tests within tests”. Each `context` block is tested individually. All `context` blocks within a `describe` block must be true for the test to pass. For example: ``` describe 'math' do context 'when adding 1 + 1' do it 'equals 2' do expect(sum).to eq(2) end end context 'when adding 2 + 2' do it 'equals 4' do expect(sum).to eq(4) end end end ``` where each `context` block describes a different testing scenario: “The sum of one plus one to equal two, and also the sum of two plus two to equal four.” A `context` block is useful to handle platform-specific scenarios. For example, “When on platform A, test for foo; when on platform B, test for bar.” For example: ``` describe 'cookbook_name::recipe_name' do context 'when on Debian' do it 'equals 2' do a = 1 b = 1 sum = a + b expect(sum).to eq(2) end end context 'when on Ubuntu' do it 'equals 2' do expect(1 + 1).to eq(2) end end context 'when on Windows' do it 'equals 3' do expect(1 + 2).to eq(3) end end end ``` #### let RSpec-based tests may contain `let` statements within a `context` block. Use `let` statements to create a symbol, assign it a value, and then use it elsewhere in the `context` block. For example: ``` describe 'Math' do context 'when adding 1 + 1' do let(:sum) { 1 + 1 } it 'equals 2' do expect(sum).to eq(2) end end context 'when adding 2 + 2' do let(:sum) do 2 + 2 end it 'equals 4' do expect(sum).to eq(4) end end end ``` where: * The first `let` statement creates the `:sum` symbol, and then assigns it the value of one plus one. The `expect` statement later in the test uses `sum` to test that one plus one equals two * The second `let` statement creates the `:sum` symbol, and then assigns it the value of two plus two. The `expect` statement later in the test uses `sum` to test that two plus two equals four ### Require ChefSpec A ChefSpec unit test must contain the following statement at the top of the test file: ``` require 'chefspec' ``` Examples -------- The ChefSpec repo on github has [an impressive collection of examples](https://github.com/sethvargo/chefspec/tree/main/examples). For all of the core Chef Infra Client resources, for guards, attributes, multiple actions, and so on. Take a look at those examples and use them as a starting point for building your own unit tests. Some of them are included below, for reference here. ### file Resource **Recipe** ``` file '/tmp/explicit_action' do action :delete end file '/tmp/with_attributes' do user 'user' group 'group' backup false action :delete end file 'specifying the identity attribute' do path '/tmp/identity_attribute' action :delete end ``` **Unit Test** ``` require 'chefspec' describe 'file::delete' do let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '20.04').converge(described_recipe) } it 'deletes a file with an explicit action' do expect(chef_run).to delete_file('/tmp/explicit_action') expect(chef_run).to_not delete_file('/tmp/not_explicit_action') end it 'deletes a file with attributes' do expect(chef_run).to delete_file('/tmp/with_attributes').with(backup: false) expect(chef_run).to_not delete_file('/tmp/with_attributes').with(backup: true) end it 'deletes a file when specifying the identity attribute' do expect(chef_run).to delete_file('/tmp/identity_attribute') end end ``` ### template Resource **Recipe** ``` template '/tmp/default_action' template '/tmp/explicit_action' do action :create end template '/tmp/with_attributes' do user 'user' group 'group' backup false end template 'specifying the identity attribute' do path '/tmp/identity_attribute' end ``` **Unit Test** ``` require 'chefspec' describe 'template::create' do let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '20.04').converge(described_recipe) } it 'creates a template with the default action' do expect(chef_run).to create_template('/tmp/default_action') expect(chef_run).to_not create_template('/tmp/not_default_action') end it 'creates a template with an explicit action' do expect(chef_run).to create_template('/tmp/explicit_action') end it 'creates a template with attributes' do expect(chef_run).to create_template('/tmp/with_attributes').with( user: 'user', group: 'group', backup: false, ) expect(chef_run).to_not create_template('/tmp/with_attributes').with( user: 'bacon', group: 'fat', backup: true, ) end it 'creates a template when specifying the identity attribute' do expect(chef_run).to create_template('/tmp/identity_attribute') end end ``` ### package Resource **Recipe** ``` package 'explicit_action' do action :remove end package 'with_attributes' do version '1.0.0' action :remove end package 'specifying the identity attribute' do package_name 'identity_attribute' action :remove end ``` **Unit Test** ``` require 'chefspec' describe 'package::remove' do let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '20.04').converge(described_recipe) } it 'removes a package with an explicit action' do expect(chef_run).to remove_package('explicit_action') expect(chef_run).to_not remove_package('not_explicit_action') end it 'removes a package with attributes' do expect(chef_run).to remove_package('with_attributes').with(version: '1.0.0') expect(chef_run).to_not remove_package('with_attributes').with(version: '1.2.3') end it 'removes a package when specifying the identity attribute' do expect(chef_run).to remove_package('identity_attribute') end end ``` ### chef_gem Resource **Recipe** ``` chef_gem 'default_action' chef_gem 'explicit_action' do action :install end chef_gem 'with_attributes' do version '1.0.0' end chef_gem 'specifying the identity attribute' do package_name 'identity_attribute' end ``` **Unit Test** ``` require 'chefspec' describe 'chef_gem::install' do let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '20.04').converge(described_recipe) } it 'installs a chef_gem with the default action' do expect(chef_run).to install_chef_gem('default_action') expect(chef_run).to_not install_chef_gem('not_default_action') end it 'installs a chef_gem with an explicit action' do expect(chef_run).to install_chef_gem('explicit_action') end it 'installs a chef_gem with attributes' do expect(chef_run).to install_chef_gem('with_attributes').with(version: '1.0.0') expect(chef_run).to_not install_chef_gem('with_attributes').with(version: '1.2.3') end it 'installs a chef_gem when specifying the identity attribute' do expect(chef_run).to install_chef_gem('identity_attribute') end end ``` ### directory Resource **Recipe** ``` directory '/tmp/default_action' directory '/tmp/explicit_action' do action :create end directory '/tmp/with_attributes' do user 'user' group 'group' end directory 'specifying the identity attribute' do path '/tmp/identity_attribute' end ``` **Unit Test** ``` require 'chefspec' describe 'directory::create' do let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '20.04').converge(described_recipe) } it 'creates a directory with the default action' do expect(chef_run).to create_directory('/tmp/default_action') expect(chef_run).to_not create_directory('/tmp/not_default_action') end it 'creates a directory with an explicit action' do expect(chef_run).to create_directory('/tmp/explicit_action') end it 'creates a directory with attributes' do expect(chef_run).to create_directory('/tmp/with_attributes').with( user: 'user', group: 'group', ) expect(chef_run).to_not create_directory('/tmp/with_attributes').with( user: 'bacon', group: 'fat', ) end it 'creates a directory when specifying the identity attribute' do expect(chef_run).to create_directory('/tmp/identity_attribute') end end ``` ### Guards **Recipe** ``` service 'true_guard' do action :start only_if { 1 == 1 } end service 'false_guard' do action :start not_if { 1 == 1 } end service 'action_nothing_guard' do action :nothing end ``` **Unit Test** ``` require 'chefspec' describe 'guards::default' do let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '20.04').converge(described_recipe) } it 'includes resource that have guards that evaluate to true' do expect(chef_run).to start_service('true_guard') end it 'excludes resources that have guards evaluated to false' do expect(chef_run).to_not start_service('false_guard') end it 'excludes resource that have action :nothing' do expect(chef_run).to_not start_service('action_nothing_guard') end end ``` ### include_recipe Method **Recipe** ``` include_recipe 'include_recipe::other' ``` **Unit Test** ``` require 'chefspec' describe 'include_recipe::default' do let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '20.04').converge(described_recipe) } it 'includes the `other` recipe' do expect(chef_run).to include_recipe('include_recipe::other') end it 'does not include the `not` recipe' do expect(chef_run).to_not include_recipe('include_recipe::not') end end ``` ### Multiple Actions **Recipe** ``` service 'resource' do action :start end service 'resource' do action :nothing end ``` **Unit Test** ``` require 'chefspec' describe 'multiple_actions::sequential' do let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '20.04', log_level: :fatal).converge(described_recipe) } it 'executes both actions' do expect(chef_run).to start_service('resource') end it 'does not match other actions' do expect(chef_run).to_not disable_service('resource') end end ``` For more information &mldr; --------------------------- For more information about ChefSpec: * [ChefSpec GitHub Repo](https://github.com/chefspec/chefspec) © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/chefspec/Cookstyle ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/cookstyle/_index.md) Cookstyle is a code linting tool that helps you write better Chef Infra cookbooks by detecting and automatically correcting style, syntax, and logic mistakes in your code. Cookstyle is powered by the RuboCop linting engine. RuboCop ships with over three-hundred rules, or cops, designed to detect common Ruby coding mistakes and enforce a common coding style. We’ve customized Cookstyle with a subset of those cops that we believe are perfectly tailored for cookbook development. We also ship Chef-specific cops that catch common cookbook coding mistakes, cleanup portions of code that are no longer necessary, and detect deprecations that prevent cookbooks from running on the latest releases of Chef Infra Client. Cookstyle increases code quality by: * Enforcing style conventions and best practices. * Helping every member of a team author similarly structured code. * Maintaining uniformity in the source code. * Setting expectations for fellow (and future) project contributors. * Detecting deprecated code that creates errors after upgrading to a newer Chef Infra Client release. * Detecting common Chef Infra mistakes that cause code to fail or behave incorrectly. Cookstyle vs. Rubocop --------------------- Cookstyle is more stable than Rubocop and is customized for Chef Cookbook code. This means that linting Cookbooks with Cookstyle will be more consistent and less likely to produce CI test failures. ### Tailored cops Cookbook development differs from traditional Ruby software development, so we maintain a tailored set of built-in cops from Rubocop. Cops that are not useful for cookbook development are disabled and occasionally we change the configuration of a rule to enforce a different behavior. We’ve also extended the base RuboCop package with a set of our own Chef Infra-specific cops. These cops are only found in Cookstyle and will help you to write more reliable and future-proof cookbooks. ### New cops New cops are continuously added to Rubocop. New cops can make existing codebases fail CI tests and force authors to constantly update their code. With Cookstyle, we update the RuboCop engine for bug and performance fixes, but we only change the set of cops that will fail tests once a year during Chef Infra’s major release in April. All new cops are introduced at RuboCop’s “refactor” alert level, meaning they will alert to the screen as you run Cookstyle, but they won’t fail a build. This stability means you are free to upgrade releases of Cookstyle without being forced to update your infrastructure code. Run Cookstyle ------------- Cookstyle is run from the command line, typically against a single cookbook and all of the Ruby files contained within it: ``` cookstyle /path/to/cookbook ``` Cookstyle may also be run from the root of an individual cookbook directory: ``` cookstyle . ``` Cookstyle returns a list, via standard output, that shows the results of the evaluation: ``` Inspecting 8 files CWCWCCCC Offences: cookbooks/apache/attributes/default.rb:1:1: C: Missing utf-8 encoding comment. default["apache"]["indexfile"] = "index1.html" ^ cookbooks/apache/attributes/default.rb:1:9: C: Prefer single-quoted strings when you don't need string interpolation or special symbols. default["apache"]["indexfile"] = "index1.html" ^^^^^^^^ cookbooks/apache/attributes/default.rb:1:19: C: Prefer single-quoted strings when you don't need string interpolation or special symbols. default["apache"]["indexfile"] = "index1.html" ^^^^^^^^^^^ ``` ### Output Cookstyle output: * States the number of files found and examined. For example: `Inspecting 8 files` * Lists the results of those files as a series of symbols. For example: `CWCWCCCC` * For each symbol, states the file name, line number, character number, type of issue or error, describes the issue or error, and specifies the location in the source code at which the issue or error is located A Cookstyle evaluation has the following syntax: ``` FILENAME:LINE_NUMBER:CHARACTER_NUMBER: TYPE_OF_ERROR: MESSAGE SOURCE CODE ^^^^^^^^^^^ ``` For example: ``` cookbooks/apache/attributes/default.rb:1:9: C: Prefer single-quoted strings when you don't need string interpolation or special symbols. default["apache"]["indexfile"] = "index1.html" ^^^^^^^^ ``` #### Symbols The following symbols appear in the standard output and are used to indicate the result of an evaluation: | Symbol | Description | | --- | --- | | `.` | The file does not have any issues. | | `C` | The file has an issue with convention. | | `E` | The file contains an error. | | `F` | The file contains a fatal error. | | `W` | The file contains a warning. | | `R` | The file contains code that should be refactored. | Autocorrecting Cookstyle Warnings --------------------------------- Many of the Cookstyle Cops include the ability to autocorrect violations. To autocorrect code run the following from the cookbook directory: ``` cookstyle -a . ``` Take particular care after running this command to ensure the autocorrection logic resulted in appropriate cookbook code. .rubocop.yml ------------ Use a .rubocop.yml file in a cookbook to override the default settings in Cookstyle for enabled and disabled rules. Only enabled rules—either in the `enabled.yml` file in Cookstyle itself or rules that are specifically enabled in a cookbook’s .rubocop.yml file—will be used during the evaluation. Any rule that becomes unhelpful should be disabled in the .rubocop.yml file. Each cookbook has its own .rubocop.yml file, which means that each cookbook may have its own set of enabled, disabled, and custom rules. That said, it’s more common for all cookbooks to have the same set of enabled, disabled, and custom rules. When RuboCop is run against a cookbook, the full set of enabled and disabled rules (as defined the `enabled.yml` and `disabled.yml` files in Cookstyle itself) are loaded first, and are then compared against the settings in the cookbook’s .rubocop.yml file. Custom rules should be specified in the .rubocop.yml file. The state of rules—enabled or disabled—in a .rubocop.yml file take precedence over the state of rules defined in the `enabled.yml` and `disabled.yml` files. ### Syntax A .rubocop.yml file has the following syntax: ``` NAME_OF_RULE:Description:'a description of a rule'Enabled :(true or false)KEY:VALUE ``` where * `NAME_OF_RULE` is the name of a rule * `Description` is the string that prints as part of the standard output that describes the rule if it is triggered during the evaluation * `Enabled` enables a rule (`true`) or disables a rule (`false`); for non-custom rules, this value will override the settings in the `enabled.yml` and `disabled.yml` files in Cookstyle * `KEY: VALUE` adds additional details for a rule, if necessary. For example, `Max: 200` sets the line length to 200 characters for the `LineLength` rule ### .rubocop_todo.yml Use a .rubocop_todo.yml file to capture the current state of all evaluations, and then write them to a file. This allows evaluations to reviewed one at a time. Disable any evaluations that are unhelpful, and then address the ones that are. To generate the .rubocop_todo.yml file, run the following command: ``` cookstyle --auto-gen-config ``` Note Rename this file to .rubocop.yml to adopt this evaluation state as the standard. Include this file in the .rubocop.yml file by adding `inherit_from: .rubocop_todo.yml` to the top of the .rubocop.yml file. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/Cookstyle Cops List =================== Chef/Correctness ---------------- * [BlockGuardWithOnlyString](../chef_correctness_blockguardwithonlystring/index) * [ChefApplicationFatal](../chef_correctness_chefapplicationfatal/index) * [ConditionalRubyShellout](../chef_correctness_conditionalrubyshellout/index) * [CookbookUsesNodeSave](../chef_correctness_cookbookusesnodesave/index) * [DnfPackageAllowDowngrades](../chef_correctness_dnfpackageallowdowngrades/index) * [IncorrectLibraryInjection](../chef_correctness_incorrectlibraryinjection/index) * [InvalidCookbookName](../chef_correctness_invalidcookbookname/index) * [InvalidDefaultAction](../chef_correctness_invaliddefaultaction/index) * [InvalidNotificationResource](../chef_correctness_invalidnotificationresource/index) * [InvalidNotificationTiming](../chef_correctness_invalidnotificationtiming/index) * [InvalidPlatformFamilyHelper](../chef_correctness_invalidplatformfamilyhelper/index) * [InvalidPlatformFamilyInCase](../chef_correctness_invalidplatformfamilyincase/index) * [InvalidPlatformHelper](../chef_correctness_invalidplatformhelper/index) * [InvalidPlatformInCase](../chef_correctness_invalidplatformincase/index) * [InvalidPlatformMetadata](../chef_correctness_invalidplatformmetadata/index) * [InvalidPlatformValueForPlatformFamilyHelper](../chef_correctness_invalidplatformvalueforplatformfamilyhelper/index) * [InvalidPlatformValueForPlatformHelper](../chef_correctness_invalidplatformvalueforplatformhelper/index) * [InvalidVersionMetadata](../chef_correctness_invalidversionmetadata/index) * [LazyEvalNodeAttributeDefaults](../chef_correctness_lazyevalnodeattributedefaults/index) * [LazyInResourceGuard](../chef_correctness_lazyinresourceguard/index) * [MacosUserdefaultsInvalidType](../chef_correctness_macosuserdefaultsinvalidtype/index) * [MalformedPlatformValueForPlatformHelper](../chef_correctness_malformedplatformvalueforplatformhelper/index) * [MetadataMalformedDepends](../chef_correctness_metadatamalformeddepends/index) * [MetadataMissingName](../chef_correctness_metadatamissingname/index) * [MetadataMissingVersion](../chef_correctness_metadatamissingversion/index) * [NodeNormal](../chef_correctness_nodenormal/index) * [NodeNormalUnless](../chef_correctness_nodenormalunless/index) * [NotifiesActionNotSymbol](../chef_correctness_notifiesactionnotsymbol/index) * [OctalModeAsString](../chef_correctness_octalmodeasstring/index) * [OpenSSLPasswordHelpers](../chef_correctness_opensslpasswordhelpers/index) * [PowershellFileExists](../chef_correctness_powershellfileexists/index) * [PowershellScriptDeleteFile](../chef_correctness_powershellscriptdeletefile/index) * [PropertyWithoutType](../chef_correctness_propertywithouttype/index) * [ResourceSetsInternalProperties](../chef_correctness_resourcesetsinternalproperties/index) * [ResourceSetsNameProperty](../chef_correctness_resourcesetsnameproperty/index) * [ResourceWithNoneAction](../chef_correctness_resourcewithnoneaction/index) * [ScopedFileExist](../chef_correctness_scopedfileexist/index) * [ServiceResource](../chef_correctness_serviceresource/index) * [SupportsMustBeFloat](../chef_correctness_supportsmustbefloat/index) * [TmpPath](../chef_correctness_tmppath/index) Chef/Deprecations ----------------- * [ChefDKGenerators](../chef_deprecations_chefdkgenerators/index) * [Cheffile](../chef_deprecations_cheffile/index) * [ChefHandlerRecipe](../chef_deprecations_chefhandlerrecipe/index) * [ChefHandlerUsesSupports](../chef_deprecations_chefhandlerusessupports/index) * [ChefRewind](../chef_deprecations_chefrewind/index) * [ChefShellout](../chef_deprecations_chefshellout/index) * [ChefSpecCoverageReport](../chef_deprecations_chefspeccoveragereport/index) * [ChefSpecLegacyRunner](../chef_deprecations_chefspeclegacyrunner/index) * [ChefSugarHelpers](../chef_deprecations_chefsugarhelpers/index) * [ChefWindowsPlatformHelper](../chef_deprecations_chefwindowsplatformhelper/index) * [ChocolateyPackageUninstallAction](../chef_deprecations_chocolateypackageuninstallaction/index) * [CookbookDependsOnCompatResource](../chef_deprecations_cookbookdependsoncompatresource/index) * [CookbookDependsOnPartialSearch](../chef_deprecations_cookbookdependsonpartialsearch/index) * [CookbookDependsOnPoise](../chef_deprecations_cookbookdependsonpoise/index) * [CookbooksDependsOnSelf](../chef_deprecations_cookbooksdependsonself/index) * [DependsOnChefNginxCookbook](../chef_deprecations_dependsonchefnginxcookbook/index) * [DependsOnChefReportingCookbook](../chef_deprecations_dependsonchefreportingcookbook/index) * [DependsOnOmnibusUpdaterCookbook](../chef_deprecations_dependsonomnibusupdatercookbook/index) * [DeprecatedChefSpecPlatform](../chef_deprecations_deprecatedchefspecplatform/index) * [DeprecatedPlatformMethods](../chef_deprecations_deprecatedplatformmethods/index) * [DeprecatedShelloutMethods](../chef_deprecations_deprecatedshelloutmethods/index) * [DeprecatedSudoActions](../chef_deprecations_deprecatedsudoactions/index) * [DeprecatedWindowsVersionCheck](../chef_deprecations_deprecatedwindowsversioncheck/index) * [DeprecatedYumRepositoryActions](../chef_deprecations_deprecatedyumrepositoryactions/index) * [DeprecatedYumRepositoryProperties](../chef_deprecations_deprecatedyumrepositoryproperties/index) * [EasyInstallResource](../chef_deprecations_easyinstallresource/index) * [EOLAuditModeUsage](../chef_deprecations_eolauditmodeusage/index) * [EpicFail](../chef_deprecations_epicfail/index) * [ErlCallResource](../chef_deprecations_erlcallresource/index) * [ExecutePathProperty](../chef_deprecations_executepathproperty/index) * [ExecuteRelativeCreatesWithoutCwd](../chef_deprecations_executerelativecreateswithoutcwd/index) * [FoodcriticTesting](../chef_deprecations_foodcritictesting/index) * [HWRPWithoutProvides](../chef_deprecations_hwrpwithoutprovides/index) * [HWRPWithoutUnifiedTrue](../chef_deprecations_hwrpwithoutunifiedtrue/index) * [IncludingXMLRubyRecipe](../chef_deprecations_includingxmlrubyrecipe/index) * [IncludingYumDNFCompatRecipe](../chef_deprecations_includingyumdnfcompatrecipe/index) * [LaunchdDeprecatedHashProperty](../chef_deprecations_launchddeprecatedhashproperty/index) * [LegacyNotifySyntax](../chef_deprecations_legacynotifysyntax/index) * [LegacyYumCookbookRecipes](../chef_deprecations_legacyyumcookbookrecipes/index) * [LibrarianChefSpec](../chef_deprecations_librarianchefspec/index) * [LocaleDeprecatedLcAllProperty](../chef_deprecations_localedeprecatedlcallproperty/index) * [LogResourceNotifications](../chef_deprecations_logresourcenotifications/index) * [MacosUserdefaultsGlobalProperty](../chef_deprecations_macosuserdefaultsglobalproperty/index) * [NamePropertyWithDefaultValue](../chef_deprecations_namepropertywithdefaultvalue/index) * [NodeDeepFetch](../chef_deprecations_nodedeepfetch/index) * [NodeMethodsInsteadofAttributes](../chef_deprecations_nodemethodsinsteadofattributes/index) * [NodeSet](../chef_deprecations_nodeset/index) * [NodeSetUnless](../chef_deprecations_nodesetunless/index) * [NodeSetWithoutLevel](../chef_deprecations_nodesetwithoutlevel/index) * [PartialSearchClassUsage](../chef_deprecations_partialsearchclassusage/index) * [PartialSearchHelperUsage](../chef_deprecations_partialsearchhelperusage/index) * [PoiseArchiveUsage](../chef_deprecations_poisearchiveusage/index) * [PolicyfileCommunitySource](../chef_deprecations_policyfilecommunitysource/index) * [PowershellCookbookHelpers](../chef_deprecations_powershellcookbookhelpers/index) * [RequireRecipe](../chef_deprecations_requirerecipe/index) * [ResourceInheritsFromCompatResource](../chef_deprecations_resourceinheritsfromcompatresource/index) * [ResourceOverridesProvidesMethod](../chef_deprecations_resourceoverridesprovidesmethod/index) * [ResourceUsesDslNameMethod](../chef_deprecations_resourceusesdslnamemethod/index) * [ResourceUsesOnlyResourceName](../chef_deprecations_resourceusesonlyresourcename/index) * [ResourceUsesProviderBaseMethod](../chef_deprecations_resourceusesproviderbasemethod/index) * [ResourceUsesUpdatedMethod](../chef_deprecations_resourceusesupdatedmethod/index) * [ResourceWithoutUnifiedTrue](../chef_deprecations_resourcewithoutunifiedtrue/index) * [Ruby27KeywordArgumentWarnings](../chef_deprecations_ruby27keywordargumentwarnings/index) * [RubyBlockCreateAction](../chef_deprecations_rubyblockcreateaction/index) * [SearchUsesPositionalParameters](../chef_deprecations_searchusespositionalparameters/index) * [UseAutomaticResourceName](../chef_deprecations_useautomaticresourcename/index) * [UseInlineResourcesDefined](../chef_deprecations_useinlineresourcesdefined/index) * [UserDeprecatedSupportsProperty](../chef_deprecations_userdeprecatedsupportsproperty/index) * [UsesChefRESTHelpers](../chef_deprecations_useschefresthelpers/index) * [UsesDeprecatedMixins](../chef_deprecations_usesdeprecatedmixins/index) * [UsesRunCommandHelper](../chef_deprecations_usesruncommandhelper/index) * [UseYamlDump](../chef_deprecations_useyamldump/index) * [VerifyPropertyUsesFileExpansion](../chef_deprecations_verifypropertyusesfileexpansion/index) * [WindowsFeatureServermanagercmd](../chef_deprecations_windowsfeatureservermanagercmd/index) * [WindowsPackageInstallerTypeString](../chef_deprecations_windowspackageinstallertypestring/index) * [WindowsTaskChangeAction](../chef_deprecations_windowstaskchangeaction/index) * [WindowsVersionHelpers](../chef_deprecations_windowsversionhelpers/index) Chef/Effortless --------------- * [Berksfile](../chef_effortless_berksfile/index) * [ChefVaultUsed](../chef_effortless_chefvaultused/index) * [CookbookUsesDatabags](../chef_effortless_cookbookusesdatabags/index) * [CookbookUsesEnvironments](../chef_effortless_cookbookusesenvironments/index) * [CookbookUsesPolicygroups](../chef_effortless_cookbookusespolicygroups/index) * [CookbookUsesRoles](../chef_effortless_cookbookusesroles/index) * [CookbookUsesSearch](../chef_effortless_cookbookusessearch/index) * [DependsChefVault](../chef_effortless_dependschefvault/index) * [SearchForEnvironmentsOrRoles](../chef_effortless_searchforenvironmentsorroles/index) Chef/Modernize -------------- * [ActionMethodInResource](../chef_modernize_actionmethodinresource/index) * [AllowedActionsFromInitialize](../chef_modernize_allowedactionsfrominitialize/index) * [ChefGemNokogiri](../chef_modernize_chefgemnokogiri/index) * [ClassEvalActionClass](../chef_modernize_classevalactionclass/index) * [ConditionalUsingTest](../chef_modernize_conditionalusingtest/index) * [CronDFileOrTemplate](../chef_modernize_crondfileortemplate/index) * [CronManageResource](../chef_modernize_cronmanageresource/index) * [CustomResourceWithAttributes](../chef_modernize_customresourcewithattributes/index) * [DatabagHelpers](../chef_modernize_databaghelpers/index) * [DeclareActionClass](../chef_modernize_declareactionclass/index) * [DefaultActionFromInitialize](../chef_modernize_defaultactionfrominitialize/index) * [DefinesChefSpecMatchers](../chef_modernize_defineschefspecmatchers/index) * [Definitions](../chef_modernize_definitions/index) * [DependsOnChefVaultCookbook](../chef_modernize_dependsonchefvaultcookbook/index) * [DependsOnChocolateyCookbooks](../chef_modernize_dependsonchocolateycookbooks/index) * [DependsOnKernelModuleCookbook](../chef_modernize_dependsonkernelmodulecookbook/index) * [DependsOnLocaleCookbook](../chef_modernize_dependsonlocalecookbook/index) * [DependsOnOpensslCookbook](../chef_modernize_dependsonopensslcookbook/index) * [DependsOnTimezoneLwrpCookbook](../chef_modernize_dependsontimezonelwrpcookbook/index) * [DependsOnWindowsFirewallCookbook](../chef_modernize_dependsonwindowsfirewallcookbook/index) * [DependsOnZypperCookbook](../chef_modernize_dependsonzyppercookbook/index) * [DslIncludeInResource](../chef_modernize_dslincludeinresource/index) * [EmptyResourceInitializeMethod](../chef_modernize_emptyresourceinitializemethod/index) * [ExecuteAptUpdate](../chef_modernize_executeaptupdate/index) * [ExecuteScExe](../chef_modernize_executescexe/index) * [ExecuteSleep](../chef_modernize_executesleep/index) * [ExecuteSysctl](../chef_modernize_executesysctl/index) * [ExecuteTzUtil](../chef_modernize_executetzutil/index) * [FoodcriticComments](../chef_modernize_foodcriticcomments/index) * [IfProvidesDefaultAction](../chef_modernize_ifprovidesdefaultaction/index) * [IncludingAptDefaultRecipe](../chef_modernize_includingaptdefaultrecipe/index) * [IncludingMixinShelloutInResources](../chef_modernize_includingmixinshelloutinresources/index) * [IncludingOhaiDefaultRecipe](../chef_modernize_includingohaidefaultrecipe/index) * [IncludingWindowsDefaultRecipe](../chef_modernize_includingwindowsdefaultrecipe/index) * [LegacyBerksfileSource](../chef_modernize_legacyberksfilesource/index) * [LibarchiveFileResource](../chef_modernize_libarchivefileresource/index) * [MacOsXUserdefaults](../chef_modernize_macosxuserdefaults/index) * [MinitestHandlerUsage](../chef_modernize_minitesthandlerusage/index) * [NodeInitPackage](../chef_modernize_nodeinitpackage/index) * [NodeRolesInclude](../chef_modernize_noderolesinclude/index) * [OpensslRsaKeyResource](../chef_modernize_opensslrsakeyresource/index) * [OpensslX509Resource](../chef_modernize_opensslx509resource/index) * [OsxConfigProfileResource](../chef_modernize_osxconfigprofileresource/index) * [PowerShellGuardInterpreter](../chef_modernize_powershellguardinterpreter/index) * [PowershellInstallPackage](../chef_modernize_powershellinstallpackage/index) * [PowershellInstallWindowsFeature](../chef_modernize_powershellinstallwindowsfeature/index) * [PowershellScriptExpandArchive](../chef_modernize_powershellscriptexpandarchive/index) * [PropertyWithNameAttribute](../chef_modernize_propertywithnameattribute/index) * [ProvidesFromInitialize](../chef_modernize_providesfrominitialize/index) * [ResourceForcingCompileTime](../chef_modernize_resourceforcingcompiletime/index) * [ResourceNameFromInitialize](../chef_modernize_resourcenamefrominitialize/index) * [RespondToCompileTime](../chef_modernize_respondtocompiletime/index) * [RespondToInMetadata](../chef_modernize_respondtoinmetadata/index) * [RespondToProvides](../chef_modernize_respondtoprovides/index) * [RespondToResourceName](../chef_modernize_respondtoresourcename/index) * [SetOrReturnInResources](../chef_modernize_setorreturninresources/index) * [SevenZipArchiveResource](../chef_modernize_sevenziparchiveresource/index) * [ShellOutHelper](../chef_modernize_shellouthelper/index) * [ShellOutToChocolatey](../chef_modernize_shellouttochocolatey/index) * [SimplifyAptPpaSetup](../chef_modernize_simplifyaptppasetup/index) * [SysctlParamResource](../chef_modernize_sysctlparamresource/index) * [UnnecessaryDependsChef14](../chef_modernize_unnecessarydependschef14/index) * [UnnecessaryDependsChef15](../chef_modernize_unnecessarydependschef15/index) * [UnnecessaryMixlibShelloutRequire](../chef_modernize_unnecessarymixlibshelloutrequire/index) * [UseBuildEssentialResource](../chef_modernize_usebuildessentialresource/index) * [UseChefLanguageCloudHelpers](../chef_modernize_usecheflanguagecloudhelpers/index) * [UseChefLanguageEnvHelpers](../chef_modernize_usecheflanguageenvhelpers/index) * [UseChefLanguageSystemdHelper](../chef_modernize_usecheflanguagesystemdhelper/index) * [UseMultipackageInstalls](../chef_modernize_usemultipackageinstalls/index) * [UseRequireRelative](../chef_modernize_userequirerelative/index) * [UsesZypperRepo](../chef_modernize_useszypperrepo/index) * [WhyRunSupportedTrue](../chef_modernize_whyrunsupportedtrue/index) * [WindowsRegistryUAC](../chef_modernize_windowsregistryuac/index) * [WindowsScResource](../chef_modernize_windowsscresource/index) * [WindowsZipfileUsage](../chef_modernize_windowszipfileusage/index) * [ZipfileResource](../chef_modernize_zipfileresource/index) Chef/RedundantCode ------------------ * [AptRepositoryDistributionDefault](../chef_redundantcode_aptrepositorydistributiondefault/index) * [AptRepositoryNotifiesAptUpdate](../chef_redundantcode_aptrepositorynotifiesaptupdate/index) * [AttributeMetadata](../chef_redundantcode_attributemetadata/index) * [ConflictsMetadata](../chef_redundantcode_conflictsmetadata/index) * [CustomResourceWithAllowedActions](../chef_redundantcode_customresourcewithallowedactions/index) * [DoubleCompileTime](../chef_redundantcode_doublecompiletime/index) * [GroupingMetadata](../chef_redundantcode_groupingmetadata/index) * [LongDescriptionMetadata](../chef_redundantcode_longdescriptionmetadata/index) * [MultiplePlatformChecks](../chef_redundantcode_multipleplatformchecks/index) * [NamePropertyIsRequired](../chef_redundantcode_namepropertyisrequired/index) * [OhaiAttributeToString](../chef_redundantcode_ohaiattributetostring/index) * [PropertySplatRegex](../chef_redundantcode_propertysplatregex/index) * [PropertyWithRequiredAndDefault](../chef_redundantcode_propertywithrequiredanddefault/index) * [ProvidesMetadata](../chef_redundantcode_providesmetadata/index) * [RecipeMetadata](../chef_redundantcode_recipemetadata/index) * [ReplacesMetadata](../chef_redundantcode_replacesmetadata/index) * [ResourceWithNothingAction](../chef_redundantcode_resourcewithnothingaction/index) * [SensitivePropertyInResource](../chef_redundantcode_sensitivepropertyinresource/index) * [StringPropertyWithNilDefault](../chef_redundantcode_stringpropertywithnildefault/index) * [SuggestsMetadata](../chef_redundantcode_suggestsmetadata/index) * [UnnecessaryDesiredState](../chef_redundantcode_unnecessarydesiredstate/index) * [UnnecessaryNameProperty](../chef_redundantcode_unnecessarynameproperty/index) * [UseCreateIfMissing](../chef_redundantcode_usecreateifmissing/index) Chef/Security ------------- * [SshPrivateKey](../chef_security_sshprivatekey/index) Chef/Sharing ------------ * [DefaultMetadataMaintainer](../chef_sharing_defaultmetadatamaintainer/index) * [EmptyMetadataField](../chef_sharing_emptymetadatafield/index) * [IncludePropertyDescriptions](../chef_sharing_includepropertydescriptions/index) * [IncludeResourceDescriptions](../chef_sharing_includeresourcedescriptions/index) * [IncludeResourceExamples](../chef_sharing_includeresourceexamples/index) * [InsecureCookbookURL](../chef_sharing_insecurecookbookurl/index) * [InvalidLicenseString](../chef_sharing_invalidlicensestring/index) Chef/Style ---------- * [AttributeKeys](../chef_style_attributekeys/index) * [ChefWhaaat](../chef_style_chefwhaaat/index) * [CommentFormat](../chef_style_commentformat/index) * [CommentSentenceSpacing](../chef_style_commentsentencespacing/index) * [CopyrightCommentFormat](../chef_style_copyrightcommentformat/index) * [DefaultCopyrightComments](../chef_style_defaultcopyrightcomments/index) * [FileMode](../chef_style_filemode/index) * [ImmediateNotificationTiming](../chef_style_immediatenotificationtiming/index) * [IncludeRecipeWithParentheses](../chef_style_includerecipewithparentheses/index) * [NegatingOnlyIf](../chef_style_negatingonlyif/index) * [OverlyComplexSupportsDependsMetadata](../chef_style_overlycomplexsupportsdependsmetadata/index) * [SimplifyPlatformMajorVersionCheck](../chef_style_simplifyplatformmajorversioncheck/index) * [TrueClassFalseClassResourceProperties](../chef_style_trueclassfalseclassresourceproperties/index) * [UnnecessaryOSCheck](../chef_style_unnecessaryoscheck/index) * [UnnecessaryPlatformCaseStatement](../chef_style_unnecessaryplatformcasestatement/index) * [UsePlatformHelpers](../chef_style_useplatformhelpers/index) InSpec/Deprecations ------------------- * [AttributeDefault](../inspec_deprecations_attributedefault/index) * [AttributeHelper](../inspec_deprecations_attributehelper/index) × [Cookstyle Cops List](#cookstyle-cops-list) * [Chef/Correctness](#chefcorrectness) * [Chef/Deprecations](#chefdeprecations) * [Chef/Effortless](#chefeffortless) * [Chef/Modernize](#chefmodernize) * [Chef/RedundantCode](#chefredundantcode) * [Chef/Security](#chefsecurity) * [Chef/Sharing](#chefsharing) * [Chef/Style](#chefstyle) * [InSpec/Deprecations](#inspecdeprecations) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/cops/config.rb Optional Settings =========================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/config_rb_optional_settings.md) In addition to the default settings in a knife config.rb file, there are other subcommand-specific settings that can be added. When a subcommand is run, knife will use: 1. A value passed via the command-line 2. A value contained in the config.rb file 3. The default value A value passed via the command line will override a value in the config.rb file; a value in a config.rb file will override a default value. Warning Many optional settings should not be added to the config.rb file. The reasons for not adding them can vary. For example, using `--yes` as a default in the config.rb file will cause knife to always assume that “Y” is the response to any prompt, which may lead to undesirable outcomes. Other settings, such as `--hide-by-mins` (used only with the `knife status` subcommand) or `--bare-directories` (used only with the `knife list` subcommand) probably aren’t used often enough (and in the same exact way) to justify adding them to the config.rb file. In general, if the optional settings are not listed on [the main config.rb topic](../config_rb/index), then add settings only after careful consideration. Do not use optional settings in a production environment until after the setting’s performance has been validated in a safe testing environment. The following list describes all of the optional settings that can be added to the configuration file: `knife[:admin]` Create a client as an admin client. `knife[:admin_client_key]` `knife[:admin_client_name]` `knife[:after]` Add a run-list item after the specified run-list item. `knife[:all]` Indicates that all environments, cookbooks, cookbook versions, metadata, and/or data bags will be uploaded, deleted, generated, or tested. The context depends on which knife subcommand and argument is used. `knife[:all_versions]` Return all available versions for every cookbook. `knife[:attribute]` The attribute (or attributes) to show. `knife[:attribute_from_cli]` `knife[:authentication_protocol_version]` Sets the authentication protocol that is used to communicate with Chef Infra Server. For example, specify protocol version 1.3 to enable support for SHA-256 algorithms: ``` knife[:authentication_protocol_version] = '1.3' ``` Note that authentication protocol 1.3 is only supported on Chef Server versions 12.4.0 and above. `knife[:bare_directories]` Prevent a directory’s children from showing when a directory matches a pattern. `knife[:before]` `knife[:bootstrap_curl_options]` Arbitrary options to be added to the bootstrap command when using cURL. This option may not be used in the same command with `--bootstrap-install-command`. `knife[:bootstrap_install_command]` Execute a custom installation command sequence for Chef Infra Client. This option may not be used in the same command with `--bootstrap-curl-options`, `--bootstrap-install-sh`, or `--bootstrap-wget-options`. `knife[:bootstrap_no_proxy]` A URL or IP address that specifies a location that should not be proxied. `knife[:bootstrap_proxy]` The proxy server for the node that is the target of a bootstrap operation. `knife[:bootstrap_template]` The path to a template file to be used during a bootstrap operation. `knife[:bootstrap_vault_file]` The path to a JSON file that contains a list of vaults and items to be updated. `knife[:bootstrap_vault_item]` A single vault and item to update as `vault:item`. `knife[:bootstrap_vault_json]` A JSON string that contains a list of vaults and items to be updated. `knife[:bootstrap_version]` The version of the Chef Infra Client to install. `knife[:bootstrap_wget_options]` Arbitrary options to be added to the bootstrap command when using GNU Wget. This option may not be used in the same command with `--bootstrap-install-command`. `knife[:both]` Delete both local and remote copies of an object. `knife[:chef_node_name]` `knife[:chef_repo_path]` The path to the chef-repo. `knife[:chef_server_url]` `knife[:chef_zero_host]` Override the host on which chef-zero listens. `knife[:chef_zero_post]` The port on which chef-zero listens. `knife[:client_key]` `knife[:color]` `knife[:concurrency]` The number of allowed concurrent connections. `knife[:config_file]` The configuration file to use. `knife[:cookbook_copyright]` `knife[:cookbook_email]` `knife[:cookbook_license]` `knife[:cookbook_path]` `knife[:delete_validators]` `knife[:depends]` Ensure that when a cookbook has a dependency on one (or more) cookbooks, those cookbooks are also uploaded. `knife[:description]` The description for an environment and/or a role. `knife[:diff]` `knife[:diff_filter]` Select only files that have been added (`A`), deleted (`D`), modified (`M`), and/or have had their type changed (`T`). Any combination of filter characters may be used, including no filter characters. Use `*` to select all paths if a file matches other criteria in the comparison. `knife[:disable_editing]` Prevent the $EDITOR from being opened and accept data as-is. `knife[:distro]` `knife[:download_directory]` The directory in which cookbooks are located. `knife[:dry_run]` Take no action and only print out results. `knife[:editor]` The $EDITOR that is used for all interactive commands. `knife[:encrypt]` `knife[:env_run_list]` `knife[:environment]` The name of the environment. `knife[:exec]` A string of code that to be executed. `knife[:file]` Save a private key to the specified file name. `knife[:filter_result]` `knife[:first_boot_attributes]` `knife[:flat]` Show a list of file names. Set to `false` to view `ls`-like output. `knife[:force]` Overwrite an existing directory. `knife[:format]` `knife[:forward_agent]` Enable SSH agent forwarding. `knife[:fqdn]` FQDN `knife[:freeze]` Require changes to a cookbook be included as a new version. Only the `--force` option can override this setting. `knife[:help]` `knife[:hide_healthy]` Hide nodes on which a Chef Infra Client run has occurred within the previous hour. `knife[:hints]` An Ohai hint to be set on the target node. `knife[:host_key_verify]` Use `--no-host-key-verify` to disable host key verification. `knife[:id_only]` `knife[:identity_file]` The SSH identity file used for authentication. Key-based authentication is recommended. `knife[:initial]` Create a API client, typically an administrator client on a freshly-installed Chef Infra Server. `knife[:input]` The name of a file to be used with the `PUT` or a `POST` request. `knife[:latest]` Download the most recent version of a cookbook. `knife[:local]` Return only the contents of the local directory. `knife[:local_mode]` `knife[:log_level]` `knife[:log_location]` `knife[:manual]` Define a search query as a space-separated list of servers. `knife[:max_arguments_per_command]` `knife[:max_command_line]` `knife[:method]` The request method: `DELETE`, `GET`, `POST`, or `PUT`. `knife[:mismatch]` `knife[:name_only]` Show only the names of modified files. `knife[:name_status]` Show only the names of files with a status of `Added`, `Deleted`, `Modified`, or `Type Changed`. `knife[:no_deps]` Ensure that all cookbooks to which the installed cookbook has a dependency are not installed. `knife[:node_name]` The unique identifier of the node. This may be a username with permission to authenticate to the Chef Infra Server or it may be the name of the machine from which knife is run. For example: ``` node_name 'user_name' ``` or: ``` node_name 'machine_name' ``` `knife[:null_separator]` `knife[:on_error]` `knife[:one_column]` Show only one column of results. `knife[:patterns]` `knife[:platform]` The platform for which a cookbook is designed. `knife[:platform_version]` The version of the platform. `knife[:pretty]` Use `--no-pretty` to disable pretty-print output for JSON. `knife[:print_after]` Show data after a destructive operation. `knife[:proxy_auth]` Enable proxy authentication to the Chef Infra Server web user interface. `knife[:purge]` Entirely remove a cookbook (or cookbook version) from the Chef Infra Server. Use this action carefully because only one copy of any single file is stored on the Chef Infra Server. Consequently, purging a cookbook disables any other cookbook that references one or more files from the cookbook that has been purged. `knife[:query]` `knife[:readme_format]` The document format of the readme file: `md` (markdown) and `rdoc` (Ruby docs). `knife[:recurse]` Use `--recurse` to delete directories recursively. `knife[:recursive]` `knife[:remote]` `knife[:replace_all]` `knife[:replace_first]` `knife[:repo_mode]` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. `knife[:repository]` The path to the chef-repo. `knife[:rows]` `knife[:run_list]` A comma-separated list of roles and/or recipes to be applied. `knife[:script_path]` A colon-separated path at which Ruby scripts are located. `knife[:secret]` The encryption key that is used for values contained within a data bag item. `knife[:secret_file]` The path to the file that contains the encryption key. `knife[:server_name]` Same as node_name. Recommended configuration is to allow Ohai to collect this value during each Chef Infra Client run. `knife[:ssh_attribute]` The attribute used when opening an SSH connection. `knife[:ssh_gateway]` The SSH tunnel or gateway that is used to run a bootstrap action on a machine that is not accessible from the workstation. `knife[:ssh_password]` The SSH password. This can be used to pass the password directly on the command line. If this option is not specified (and a password is required) knife prompts for the password. `knife[:ssh_password_ng]` `knife[:ssh_port]` The SSH port. `knife[:ssh_user]` The SSH user name. `knife[:start]` `knife[:supermarket_site]` The URL at which the Chef Supermarket is located. Default value: <https://supermarket.chef.io>. `knife[:template_file]` `knife[:trailing_slashes]` `knife[:tree]` Show dependencies in a visual tree structure (including duplicates, if they exist). `knife[:use current_branch]` Ensure that the current branch is used. `knife[:use_sudo]` Execute a bootstrap operation with sudo. `knife[:use_sudo_password]` `knife[:user]` and/or `knife[:user_home]` The user name used by knife to sign requests made by the API client to the Chef Infra Server. Authentication fails if the user name does not match the private key. `knife[:user_key]` Save a public key to the specified file name. `knife[:user_password]` The user password. `knife[:validation_client_name]` `knife[:validation_key]` `knife[:validator]` `knife[:verbose_commands]` `knife[:verbosity]` `knife[:with_uri]` `knife[:yes]` Respond to all confirmation prompts with “Yes”. By Subcommand ------------- The following sections show the optional settings for the config.rb file, sorted by subcommand. ### bootstrap The following `knife bootstrap` settings can be added to the config.rb file: `knife[:bootstrap_curl_options]` Adds the `--bootstrap-curl-options` option. `knife[:bootstrap_install_command]` Adds the `--bootstrap-install-command` option. `knife[:bootstrap_no_proxy]` Adds the `--bootstrap-no-proxy` option. `knife[:bootstrap_proxy]` Adds the `--bootstrap-proxy` option. `knife[:bootstrap_template]` Adds the the `--bootstrap-template` option. `knife[:bootstrap_url]` Adds the the `--bootstrap-url` option. `knife[:bootstrap_vault_item]` Adds the the `--bootstrap-vault-item` option. `knife[:bootstrap_version]` Adds the the `--bootstrap-version` option. `knife[:bootstrap_wget_options]` Adds the the `--bootstrap-wget-options` option. `knife[:run_list]` Adds the the `--run-list` option. `knife[:template_file]` Adds the the `--bootstrap-template` option. `knife[:use_sudo]` Adds the the `--sudo` option. Note The `knife bootstrap` subcommand relies on a number of SSH-related settings that are handled by the `knife ssh` subcommand. ### client create The following `knife client create` settings can be added to the config.rb file: `knife[:file]` Adds the the `--file` option. ### client reregister The following `knife client reregister` settings can be added to the config.rb file: `knife[:file]` Adds the the `--file` option. ### configure The following `knife configure` settings can be added to the config.rb file: `knife[:admin_client_name]` The name of the admin client that is passed as part of the command itself. `knife[:config_file]` Adds the the `--config` option. `knife[:disable_editing]` Adds the the `--disable-editing` option. `knife[:file]` Adds the the `--file` option. `knife[:initial]` Adds the the `--initial` option. `knife[:repository]` Adds the the `--repository` option. `knife[:user_home]` Adds the the `--user` option. `knife[:user_password]` Adds the the `--password` option. `knife[:yes]` Adds the the `--yes` option. ### cookbook bulk delete The following `knife cookbook bulk delete` settings can be added to the config.rb file: `knife[:purge]` Adds the the `--purge` option. `knife[:yes]` Adds the the `--yes` option. ### cookbook create The following `knife cookbook create` settings can be added to the config.rb file: `knife[:readme_format]` Adds the the `--readme-format` option. ### cookbook delete The following `knife cookbook delete` settings can be added to the config.rb file: `knife[:all]` Adds the the `--all` option. `knife[:print_after]` Adds the the `--print-after` option. `knife[:purge]` Adds the the `--purge` option. ### cookbook download The following `knife cookbook download` settings can be added to the config.rb file: `knife[:download_directory]` Adds the the `--dir` option. `knife[:force]` Adds the the `--force` option. `knife[:latest]` Adds the the `--latest` option. ### cookbook list The following `knife cookbook list` settings can be added to the config.rb file: `knife[:all]` Adds the the `--all` option. `knife[:environment]` Adds the the `--environment` option. ### cookbook metadata The following `knife cookbook metadata` settings can be added to the config.rb file: `knife[:all]` Adds the the `--all` option. ### cookbook show The following `knife cookbook show` settings can be added to the config.rb file: `knife[:fqdn]` Adds the the `--fqdn` option. `knife[:platform]` Adds the the `--platform` option. `knife[:platform_version]` Adds the the `--platform-version` option. ### cookbook upload The following `knife cookbook upload` settings can be added to the config.rb file: `knife[:all]` Adds the the `--all` option. `knife[:depends]` Adds the the `--include-dependencies` option. `knife[:environment]` Adds the the `--environment` option. `knife[:force]` Adds the the `--force` option. `knife[:freeze]` Adds the the `--freeze` option. ### supermarket download The following `knife supermarket download` settings can be added to the config.rb file: `knife[:file]` Adds the the `--file` option. `knife[:force]` Adds the the `--force` option. `knife[:supermarket_site]` The URL at which the Chef Supermarket is located. Default value: <https://supermarket.chef.io>. ### supermarket install The following `knife supermarket install` settings can be added to the config.rb file: `knife[:cookbook_path]` Adds the the `--cookbook-path` option. `knife[:file]` Adds the the `--file` option. `knife[:no_deps]` Adds the the `--skip-dependencies` option. `knife[:use_current_branch]` Adds the the `--use-current-branch` option. `knife[:supermarket_site]` The URL at which the Chef Supermarket is located. Default value: <https://supermarket.chef.io>. ### supermarket share The following `knife supermarket share` settings can be added to the config.rb file: `knife[:cookbook_path]` Adds the the `--cookbook-path` option. `knife[:supermarket_site]` The URL at which the Chef Supermarket is located. Default value: <https://supermarket.chef.io>. ### data bag create The following `knife data bag create` settings can be added to the config.rb file: `knife[:secret]` Adds the the `--secret` option. `knife[:secret_file]` Adds the the `--secret-file` option. ### data bag edit The following `knife data bag edit` settings can be added to the config.rb file: `knife[:print_after]` Adds the the `--print-after` option. `knife[:secret]` Adds the the `--secret` option. `knife[:secret_file]` Adds the the `--secret-file` option. ### data bag from file The following `knife data bag from file` settings can be added to the config.rb file: `knife[:all]` Adds the the `--all` option. `knife[:secret]` Adds the the `--secret` option. `knife[:secret_file]` Adds the the `--secret-file` option. ### data bag show The following `knife data bag show` settings can be added to the config.rb file: `knife[:secret]` Adds the the `--secret` option. `knife[:secret_file]` Adds the the `--secret-file` option. ### delete The following `knife delete` settings can be added to the config.rb file: `knife[:chef_repo_path]` Adds the the `--chef-repo-path` option. `knife[:concurrency]` Adds the the `--concurrency` option. `knife[:recurse]` Adds the the `--recurse` option. `knife[:repo_mode]` Adds the the `--repo-mode` option. ### deps The following `knife deps` settings can be added to the config.rb file: `knife[:chef_repo_path]` Adds the the `--chef-repo-path` option. `knife[:concurrency]` Adds the the `--concurrency` option. `knife[:recurse]` Adds the the `--recurse` option. `knife[:remote]` Adds the the `--remote` option. `knife[:repo_mode]` Adds the the `--repo-mode` option. `knife[:tree]` Adds the the `--tree` option. ### diff The following `knife diff` settings can be added to the config.rb file: `knife[:chef_repo_path]` Adds the the `--chef-repo-path` option. `knife[:concurrency]` Adds the the `--concurrency` option. `knife[:name_only]` Adds the the `--name-only` option. `knife[:name_status]` Adds the the `--name-status` option. `knife[:recurse]` Adds the the `--recurse` option. `knife[:repo_mode]` Adds the the `--repo-mode` option. ### download The following `knife download` settings can be added to the config.rb file: `knife[:chef_repo_path]` Adds the the `--chef-repo-path` option. `knife[:concurrency]` Adds the the `--concurrency` option. `knife[:recurse]` Adds the the `--recurse` option. `knife[:repo_mode]` Adds the the `--repo-mode` option. ### edit The following `knife edit` settings can be added to the config.rb file: `knife[:chef_repo_path]` Adds the the `--chef-repo-path` option. `knife[:concurrency]` Adds the the `--concurrency` option. `knife[:disable_editing]` Adds the the `--disable-editing` option. `knife[:editor]` Adds the the `--editor` option. `knife[:local]` Adds the the `--local` option. `knife[:repo_mode]` Adds the the `--repo-mode` option. ### environment create The following `knife environment create` settings can be added to the `config.rb` file: `knife[:description]` Adds the the `--description` option. ### environment from file The following `knife environment from file` settings can be added to the config.rb file: `knife[:all]` Adds the the `--all` option. `knife[:print_after]` Adds the the `--print-after` option. ### exec The following `knife exec` settings can be added to the config.rb file: `knife[:exec]` Adds the the `--exec` option. `knife[:script_path]` Adds the the `--script-path` option. ### list The following `knife list` settings can be added to the config.rb file: `knife[:bare_directories]` Adds the the `-d` option. `knife[:chef_repo_path]` Adds the the `--chef-repo-path` option. `knife[:concurrency]` Adds the the `--concurrency` option. `knife[:recursive]` Adds the the `-R` option. `knife[:repo_mode]` Adds the the `--repo-mode` option. ### node from file The following `knife node from file` settings can be added to the config.rb file: `knife[:print_after]` Adds the the `--print-after` option. ### node list The following `knife node list` settings can be added to the config.rb file: `knife[:environment]` Adds the the `--environment` option. ### node run list add The following `knife node run list add` settings can be added to the config.rb file: `knife[:after]` Adds the the `--after` option. `knife[:run_list]` The run-list that is passed as part of the command itself. ### node run list remove The following `knife node run list remove` settings can be added to the config.rb file: `knife[:run_list]` The run-list that is passed as part of the command itself. ### raw The following `knife raw` settings can be added to the config.rb file: `knife[:chef_repo_path]` Adds the the `--chef-repo-path` option. `knife[:concurrency]` Adds the the `--concurrency` option. `knife[:input]` Adds the the `--input` option. `knife[:method]` Adds the the `--method` option. `knife[:pretty]` Adds the the `--[no-]pretty` option. `knife[:repo_mode]` Adds the the `--repo-mode` option. ### role create The following `knife role create` settings can be added to the config.rb file: `knife[:description]` Adds the the `--description` option. ### role from file The following `knife role from file` settings can be added to the config.rb file: `knife[:print_after]` Adds the the `--print-after` option. ### role show The following `knife role show` settings can be added to the config.rb file: `knife[:environment]` Adds the the `--environment` option. ### ssh The following `knife ssh` settings can be added to the config.rb file: `knife[:concurrency]` Adds the the `--concurrency` option. `knife[:identity_file]` Adds the the `--identity-file` option. `knife[:host_key_verify]` Adds the the `--[no-]host-key-verify` option. `knife[:manual]` Adds the the `--manual-list` option. `knife[:ssh_attribute]` Adds the the `--attribute` option. `knife[:ssh_gateway]` Adds the the `--ssh-gateway` option. `knife[:ssh_password]` Adds the the `--ssh-password` option. `knife[:ssh_port]` Adds the the `--ssh-port` option. `knife[:ssh_user]` Adds the the `--ssh-user` option. ### status The following `knife status` settings can be added to the config.rb file: `knife[:hide_by_mins]` Adds the the `--hide-by-mins` option. `knife[:run_list]` Adds the the `--run-list` option. `knife[:sort_reverse]` Adds the the `--sort-reverse` option. ### upload The following `knife upload` settings can be added to the config.rb file: `knife[:chef_repo_path]` Adds the the `--chef-repo-path` option. `knife[:concurrency]` Adds the the `--concurrency` option. `knife[:recurse]` Adds the the `--recurse` option. `knife[:repo_mode]` Adds the the `--repo-mode` option. ### user create The following `knife user create` settings can be added to the config.rb file: `knife[:file]` Adds the the `--file` option. `knife[:user_key]` Adds the the `--user-key` option. `knife[:user_password]` Adds the the `--password` option. ### user reregister The following `knife user reregister` settings can be added to the config.rb file: `knife[:file]` Adds the the `--file` option. ### xargs The following `knife delete` settings can be added to the config.rb file: `knife[:chef_repo_path]` Adds the the `--chef-repo-path` option. `knife[:concurrency]` Adds the the `--concurrency` option. `knife[:diff]` Adds the the `--diff` option. `knife[:dry_run]` Adds the the `--dry-run` option. `knife[:force]` Adds the the `--force` option. `knife[:local]` Adds the the `--local` option. `knife[:max_arguments_per_command]` Adds the the `--max-args` option. `knife[:max_command_line]` Adds the the `--max-chars` option. `knife[:null_separator]` Adds the the `-0` option. `knife[:patterns]` Adds the the `--pattern` option. `knife[:replace_all]` Adds the the `--replace` option. `knife[:replace_first]` Adds the the `--replace-first` option. `knife[:repo_mode]` Adds the the `--repo-mode` option. `knife[:verbose_commands]` Adds the the `-t` option. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/config_rb_optional_settings/Test Kitchen ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/kitchen.md) Use [Test Kitchen](https://kitchen.ci/) to automatically test cookbooks across any combination of platforms and test suites: * Test suites are defined in a kitchen.yml file. See the [configuration](../config_yml_kitchen/index) documentation for options and syntax information. * Supports cookbook testing across many cloud providers and virtualization technologies. * Uses a comprehensive set of operating system base images from Chef’s [Bento](https://github.com/chef/bento) project. The key concepts in Test Kitchen are: * A platform is the operating system or target environment on which a cookbook is to be tested * A suite is the Chef Infra Client configuration, a Policyfile or run-list, and (optionally) node attributes * An instance is the combination of a specific platform and a specific suite, with each instance being assigned an auto-generated name * A driver is the lifecycle that implements the actions associated with a specific instance—create the instance, do what is needed to converge on that instance (such as installing Chef Infra Client, uploading cookbooks, starting a Chef Infra Client run, and so on), setup anything else needed for testing, verify one (or more) suites post-converge, and then destroy that instance * A provisioner is the component on which the Chef Infra Client code will be run, either using chef-zero or chef-solo via the `chef_zero` and `chef_solo` provisioners, respectively Bento ----- [Bento](https://github.com/chef/bento) is a Chef Software project that produces base testing VirtualBox, Parallels, and VMware boxes for multiple operating systems for use with Test Kitchen. By default, Test Kitchen uses the base images provided by Bento although custom images may also be built using HashiCorp Packer. Drivers ------- Test Kitchen uses a driver plugin architecture to enable Test Kitchen to test instances on cloud providers such as Amazon EC2, Google Compute Engine, and Microsoft Azure. You can also test on multiple local hypervisors, such as VMware, Hyper-V, or VirtualBox. Note Chef Workstation includes many common Test Kitchen drivers. Most drivers have driver-specific configuration settings that must be added to the kitchen.yml file before Test Kitchen will be able to use that platform during cookbook testing. For information about these driver-specific settings, please refer to the driver-specific documentation. Some popular drivers: | Driver Plugin | Description | | --- | --- | | [kitchen-azurerm](https://github.com/test-kitchen/kitchen-azurerm) | A driver for Microsoft Azure. | | [kitchen-cloudstack](https://github.com/test-kitchen/kitchen-cloudstack) | A driver for CloudStack. | | [kitchen-digitalocean](https://github.com/test-kitchen/kitchen-digitalocean) | A driver for DigitalOcean. This driver ships in Chef Workstation. | | [kitchen-dokken](https://github.com/test-kitchen/kitchen-dokken) | A driver for Docker. This driver ships in Chef Workstation. | | [kitchen-dsc](https://github.com/test-kitchen/kitchen-dsc) | A driver for Windows PowerShell Desired State Configuration (DSC). | | [kitchen-ec2](https://github.com/test-kitchen/kitchen-ec2) | A driver for Amazon EC2. This driver ships in Chef Workstation. | | [kitchen-google](https://github.com/test-kitchen/kitchen-google) | A driver for Google Compute Engine. This driver ships in Chef Workstation | | [kitchen-hyperv](https://github.com/test-kitchen/kitchen-hyperv) | A driver for Microsoft Hyper-V Server. This driver ships in Chef Workstation. | | [kitchen-openstack](https://github.com/test-kitchen/kitchen-openstack) | A driver for OpenStack. This driver ships in Chef Workstation. | | [kitchen-rackspace](https://github.com/test-kitchen/kitchen-rackspace) | A driver for Rackspace. | | [kitchen-vagrant](https://github.com/test-kitchen/kitchen-vagrant) | A driver for HashiCorp Vagrant. This driver ships in Chef Workstation. | Validation with InSpec ---------------------- Test Kitchen will create a VM or cloud instance, install Chef Infra Client to that system, and converge Chef Infra Client with your local cookbook. Once this is complete, you will want to perform automated validation against the infrastructure you have built to validate its configuration. Test Kitchen allows you to run InSpec tests against your converged cookbook for easy local validation of your infrastructure. kitchen (executable) -------------------- kitchen is the command-line tool for Test Kitchen, an integration testing tool maintained by Chef Software. Test Kitchen runs tests against any combination of platforms using any combination of test suites. Each test, however, is done against a specific instance, which is comprised of a single platform and a single set of testing criteria. This allows each test to be run in isolation, ensuring that different behaviors within the same codebase can be tested thoroughly before those changes are committed to production. Note Any Test Kitchen subcommand that does not specify an instance will be applied to all instances. Note For more information about the `kitchen` command line tool, see [kitchen](../ctl_kitchen/index). kitchen.yml ----------- Use a kitchen.yml file to define what is required to run Test Kitchen, including drivers, provisioners, platforms, and test suites. Note For more information about the kitchen.yml file, see [kitchen.yml](../config_yml_kitchen/index). ### Syntax The basic structure of a kitchen.yml file is as follows: ``` driver:name:driver_nameprovisioner:name:provisioner_nameverifier:name:verifier_nametransport:name:transport_nameplatforms:- name:platform-versiondriver:name:driver_name- name:platform-versionsuites:- name:suite_namerun_list:- recipe[cookbook_name::recipe_name]attributes:{foo:"bar"}excludes:- platform-version- name:suite_namedriver:name:driver_namerun_list:- recipe[cookbook_name::recipe_name]attributes:{foo:"bar"}includes:- platform-version ``` where: * `driver_name` is the name of a driver that will be used to create platform instances used during cookbook testing. This is the default driver used for all platforms and suites **unless** a platform or suite specifies a `driver` to override the default driver for that platform or suite; a driver specified for a suite will override a driver set for a platform * `provisioner_name` specifies how Chef Infra Client will be simulated during testing. `chef_zero` and `chef_solo` are the most common provisioners used for testing cookbooks * `verifier_name` specifies which application to use when running tests, such as `inspec` * `transport_name` specifies which transport to use when executing commands remotely on the test instance. `winrm` is the default transport on Windows. The `ssh` transport is the default on all other operating systems. * `platform-version` is the name of a platform on which Test Kitchen will perform cookbook testing, for example, `ubuntu-20.04` or `centos-7`; depending on the platform, additional driver details—for example, instance names and URLs used with cloud platforms like OpenStack or Amazon EC2—may be required * `platforms` may define Chef Infra Server attributes that are common to the collection of test suites * `suites` is a collection of test suites, with each `suite_name` grouping defining an aspect of a cookbook to be tested. Each `suite_name` must specify a run-list, for example: ``` run_list: - recipe[cookbook_name::default] - recipe[cookbook_name::recipe_name] ``` * Each `suite_name` grouping may specify `attributes` as a Hash: `{ foo: "bar" }` * A `suite_name` grouping may use `excludes` and `includes` to exclude/include one (or more) platforms. For example: ``` excludes: - platform-version - platform-version # for additional platforms ``` For example, a very simple kitchen.yml file: ``` driver:name:vagrantprovisioner:name:chef_zeroplatforms:- name:ubuntu-20.04- name:centos-8- name:debian-10suites:- name:defaultrun_list:- recipe[apache::httpd]excludes:- debian-10 ``` This file uses HashiCorp Vagrant as the driver, which requires no additional configuration because it’s the default driver used by Test Kitchen, chef-zero as the provisioner, and a single (default) test suite that runs on Ubuntu 20.04, and CentOS 7. ### Work with Proxies The environment variables `http_proxy`, `https_proxy`, and `ftp_proxy` are honored by Test Kitchen for proxies. The client.rb file is read to look for proxy configuration settings. If `http_proxy`, `https_proxy`, and `ftp_proxy` are specified in the client.rb file, Chef Infra Client will configure the `ENV` variable based on these (and related) settings. For example: ``` http_proxy 'http://proxy.example.org:8080' http_proxy_user 'myself' http_proxy_pass 'Password1' ``` will be set to: ``` ENV['http_proxy'] = 'http://myself:Password1@proxy.example.org:8080' ``` Test Kitchen also supports `http_proxy` and `https_proxy` in the `kitchen.yml` file. You can set them manually or have them read from your local environment variables: ``` driver:name:vagrantprovisioner:name:chef_zero# Set proxy settings manually, orhttp_proxy:'http://user:password@server:port'https_proxy:'http://user:password@server:port'# Read from local environment variableshttp_proxy:<%= ENV['http_proxy'] %>https_proxy:<%= ENV['https_proxy'] %> ``` This will not set the proxy environment variables for applications other than Chef. The Vagrant plugin, [vagrant-proxyconf](http://tmatilai.github.io/vagrant-proxyconf/), can be used to set the proxy environment variables for applications inside the VM. For more information &mldr; --------------------------- For more information about test-driven development and Test Kitchen: * [kitchen.ci](https://kitchen.ci/) * [Getting Started with Test Kitchen](https://kitchen.ci/docs/getting-started/introduction/) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/kitchen/kitchen-vagrant =============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/plugin_kitchen_vagrant.md) The `kitchen-vagrant` driver for Kitchen generates a single Vagrantfile for each instance of Kitchen in a sandboxed directory. The `kitchen-vagrant` driver supports VirtualBox and VMware Fusion, requires Vagrant 1.1.0 (or higher), and is the default driver for Test Kitchen. The following attributes are used to configure `kitchen-vagrant` for Chef: | Attribute | Description | | --- | --- | | `box` | Required. Use to specify the box on which Vagrant will run. Default value: computed from the platform name of the instance. | | `box_check_update` | Use to check for box updates. Default value: `false`. | | `box_url` | Use to specify the URL at which the configured box is located. Default value: computed from the platform name of the instance, but only when the Vagrant provider is VirtualBox- or VMware-based. | | `communicator` | Use to override the `config.vm.communicator` setting in Vagrant. For example, when a base box is a Microsoft Windows operating system that does not have SSH installed and enabled, Vagrant will not be able to boot without a custom Vagrant file. Default value: `nil` (assumes SSH is available). | | `customize` | A hash of key-value pairs that define customizations that should be made to the Vagrant virtual machine. For example: `customize: memory: 1024 cpuexecutioncap: 50`. | | `guest` | Use to specify the `config.vm.guest` setting in the default Vagrantfile. | | `gui` | Use to enable the graphical user interface for the defined platform. This is passed to the `config.vm.provider` setting in Vagrant, but only when the Vagrant provider is VirtualBox- or VMware-based. | | `network` | Use to specify an array of network customizations to be applied to the virtual machine. Default value: `[]`. For example: `network: - ["forwarded_port", {guest: 80, host: 8080}] - ["private_network", {ip: "192.168.33.33"}]`. | | `pre_create_command` | Use to run a command immediately prior to `vagrant up --no-provisioner`. | | `provider` | Use to specify the Vagrant provider. This value must match a provider name in Vagrant. | | `provision` | Use to provision Vagrant when the instance is created. This is useful if the operating system needs customization during provisioning. Default value: `false`. | | `ssh_key` | Use to specify the private key file used for SSH authentication. | | `synced_folders` | Use to specify a collection of synchronized folders on each Vagrant instance. Source paths are relative to the Kitchen root path. Default value: `[]`. For example: `synced_folders: - ["data/%{instance_name}", "/opt/instance_data"] - ["/host_path", "/vm_path", "create: true, type: :nfs"]`. | | `vagrantfile_erb` | Use to specify an alternate Vagrant Embedded Ruby (ERB) template to be used by this driver. | | `vagrantfiles` | An array of paths to one (or more) Vagrant files to be merged with the default Vagrant file. The paths may be absolute or relative to the kitchen.yml file. | | `vm_hostname` | Use to specify the internal hostname for the instance. This is not required when connecting to a Vagrant virtual machine. Set this to `false` to prevent this value from being rendered in the default Vagrantfile. Default value: computed from the platform name of the instance. | The `kitchen-vagrant` driver can predict the box name for Vagrant and the download URL that have been published by Chef. For example: ``` platforms: - name: ubuntu-18.04 - name: ubuntu-20.04 - name: centos-7 - name: centos-8 - name: debian-10 ``` which will generate a configuration file similar to: ``` platforms: - name: ubuntu-18.04 driver: box: bento/ubuntu-18.04 - name: ubuntu-20.04 driver: box: bento/ubuntu-20.04 # ... ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/plugin_kitchen_vagrant/Setting up Knife ================ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_setup.md) knife is a command-line tool that provides an interface between a local chef-repo and the Chef Infra Server. The knife command line tool must be configured to communicate with the Chef Infra Server as well as any other infrastructure within your organization. To configure knife to communicate with Chef Infra Server for the first time run `knife configure` to create a Chef Infra credentials file at `~/.chef/credentials`. Previous Chef Infra setups recommended setting up knife with a `config.rb` file. Configuring knife with `config.rb` is still valid, but only for working with a single Chef Infra Server with a single Chef Infra Server organization. ``` mkdir ~/.chef touch ~/.chef/config.rb ``` ``` New-Item -Path "c:\" -Name ".chef" -ItemType "directory" New-Item -ItemType "file" -Path "c:\.chef\config.rb" ``` The config.rb configuration can include arbitrary Ruby code to extend configuration beyond static values. This can be used to load environmental variables from the workstation. This makes it possible to write a single config.rb file that can be used by all users within your organization. This single file can also be checked into your chef-repo, allowing users to load different config.rb files based on which chef-repo they execute the commands from. This can be especially useful when each chef-repo points to a different chef server or organization. Example config.rb: ``` current_dir = File.dirname(__FILE__) user = ENV['CHEF_USER'] || ENV['USER'] node_name user client_key "#{ENV['HOME']}/chef-repo/.chef/#{user}.pem" chef_server_url "https://api.opscode.com/organizations/#{ENV['ORGNAME']}" syntax_check_cache_path "#{ENV['HOME']}/chef-repo/.chef/syntax_check_cache" cookbook_path ["#{current_dir}/../cookbooks"] cookbook_copyright "Your Company, Inc." cookbook_license "Apache-2.0" cookbook_email "<EMAIL>" # Amazon AWS knife[:aws_access_key_id] = ENV['AWS_ACCESS_KEY_ID'] knife[:aws_secret_access_key] = ENV['AWS_SECRET_ACCESS_KEY'] ``` **Profile Support since Chef 13.7** Knife profiles make switching knife between Chef Infra Servers or between organizations on the same Chef Infra Server easier. Knife profiles are an alternative to `config.rb`–you cannot use both. Set up knife profiles by adding them to the `.chef/credentials` file in your home directory on your workstation. The `credentials` file is TOML formatted. Each profile is listed as a separate ‘table’ name of your choice, and is followed by `key = value` pairs. The keys correspond to any setting permitted in the [config.rb](../config_rb/index) file. File paths, such as `client_key` or `validator_key`, are relative to `~/.chef` unless you provide absolute path. Identify clients with `client_name` (preferred) or `node_name`. Store credentials for use with target mode (`chef-client --target switch.example.org`) as a separate profile in the credentials file. Use the DNS name of the target as the profile name and surrounded by single quotes when the name contains a period. For example: `['switch.example.org']`. Keys that are valid configuration options get passed to train, such as `port`. ``` # Example .chef/credentials file [default] client_name = "barney" client_key = "barney_rubble.pem" chef_server_url = "https://api.chef.io/organizations/bedrock" # a 'config context' such as knife can be is configured as a separate table [default.knife] ssh_user = 'ubuntu' # this would have been knife[:ssh_user] in your config.rb aws_profile = 'engineering' use_sudo = true # a client_key may also be specified inline as in this example [dev] client_name = "admin" client_key = """ -----BEGIN RSA PRIVATE KEY----- <KEY> ...ABC123= -----END RSA PRIVATE KEY----- """ validator_key = "test-validator.pem" chef_server_url = "https://api.chef-server.dev/organizations/test" ['web.preprod'] client_name = "brubble" client_key = "preprod-brubble.pem" chef_server_url = "https://preprod.chef-server.dev/organizations/preprod" ['switch.example.org'] user = "cisco" password = "cisco" enable_password = "cisco" ``` There are four ways to select which profile to use and are listed in priority order: 1. Pass the `--profile` option to knife, e.g. `knife node list --profile dev`. 2. Set the profile name in the `CHEF_PROFILE` environment variable. 3. Write the profile name to the `~/.chef/context` file. 4. Otherwise, knife uses the ‘default’ profile. Knife Config ------------ **knife config support since Chef 14.4** Use the `knife config` command to manage your knife profiles. List your profiles with the `knife config list-profiles` command. For example: ``` knife config list-profiles ``` Returns something like: ``` ## Profile Client Key Server default barney ~/.chef/barney_rubble.pem https://api.chef.io/organizations/bedrock dev admin ~/.chef/admin.pem https://api.chef-server.dev/organizations/test web.preprod brubble ~/.chef/preprod-brubble.pem https://preprod.chef-server.dev/organizations/preprod switch.example.org btm ~/.chef/btm.pem https://localhost:443 ``` The line that begins with the asterisk is the currently selected profile. To change the current profile, run the `knife config use-profile NAME` command, which will write the profile name to the `~/.chef/context` file. Running `knife config get-profile` prints out the name of the currently selected profile. If you need to troubleshoot any settings, you can verify the value that knife is using with the `knife config get KEY` command, for example: ``` knife config get chef_server_url Loading from credentials file /home/barney/.chef/credentials chef_server_url: https://api.chef-server.dev/organizations/test ``` config.rb Configuration File ---------------------------- The `config.rb` file contains settings for the knife command-line tool and any installed knife plugins. See the [config.rb documentation](../config_rb/index) for a complete list of configuration options. ### Load Path Priority The config.rb file loads every time the knife command is invoked using the following load order: * From a specified location given the `--config` flag * From a specified location given the `$KNIFE_HOME` environment variable, if set * From a `config.rb` file within the current working directory, e.g., `./config.rb` * From a `config.rb` file within a `.chef` directory in the current working directory, e.g., `./.chef/config.rb` * From a `config.rb` file within a `.chef` directory located one directory above the current working directory, e.g., `../.chef/config.rb` * From `~/.chef/config.rb` (macOS and Linux platforms) or `c:\Users\<username>\.chef` (Microsoft Windows platform) Note On Microsoft Windows, the `config.rb` file is located at: `%HOMEDRIVE%:%HOMEPATH%\.chef` (e.g. `c:\Users\<username>\.chef`). In a script for Microsoft Windows, use: `%USERPROFILE%\chef-repo\.chef`. ### config.rb Configuration Within a Chef Repository Use knife configure command to generate your initial `config.rb` file in your home directory. See [knife configure](../knife_configure/index) for details. Setting Your Text Editor ------------------------ Some knife commands, such as `knife data bag edit`, require that information be edited as JSON data using a text editor. For example, the following command: ``` knife data bag edit admins admin_name ``` opens up the text editor with data similar to: ``` { "id": "admin_name" } ``` Then make changes to that file: ``` { "id": "<NAME>." "description": "I am passing the time by letting time pass over me ..." } ``` The type of text editor that is used by knife can be configured by adding an entry to your config.rb file, or by setting an `EDITOR` environment variable. For example, to configure knife to open the `vim` text editor, add the following to your config.rb file: ``` knife[:editor] = "/usr/bin/vim" ``` When a Microsoft Windows file path is enclosed in a double-quoted string (" “), the same backslash character (`\`) that is used to define the file path separator is also used in Ruby to define an escape character. The config.rb file is a Ruby file; therefore, file path separators must be escaped. In addition, spaces in the file path must be replaced with `~1` so that the length of each section within the file path is not more than 8 characters. For example, if EditPad Pro is the text editor of choice and is located at the following path: ``` C:\\Program Files (x86)\EditPad Pro\EditPad.exe ``` the setting in the config.rb file would be similar to: ``` knife[:editor] = "C:\\Progra~1\\EditPa~1\\EditPad.exe" ``` One approach to working around the double- vs. single-quote issue is to put the single-quotes outside of the double-quotes. For example, for Notepad++: ``` knife[:editor] = '"C:\Program Files (x86)\Notepad++\notepad++.exe" -nosession -multiInst' ``` for Sublime Text: ``` knife[:editor] = '"C:\Program Files\Sublime Text 2\sublime_text.exe" --wait' ``` for TextPad: ``` knife[:editor] = '"C:\Program Files (x86)\TextPad 7\TextPad.exe"' ``` and for vim: ``` knife[:editor] = '"C:\Program Files (x86)\vim\vim74\gvim.exe"' ``` ### Using Quotes The text editor command cannot include spaces that are not properly wrapped in quotes. The command can be entered with double quotes (” “) or single quotes (' ‘), but this should be done consistently as shown in the examples above. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_setup/kitchen (executable) ==================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/ctl_kitchen.md) kitchen is the command-line tool for Test Kitchen, an integration testing tool maintained by Chef Software. Test Kitchen runs tests against any combination of platforms using any combination of test suites. Each test, however, is done against a specific instance, which is comprised of a single platform and a single set of testing criteria. This allows each test to be run in isolation, ensuring that different behaviors within the same codebase can be tested thoroughly before those changes are committed to production. Note Any Test Kitchen subcommand that does not specify an instance will be applied to all instances. Note This topic details functionality that is packaged with Chef Workstation. See <https://kitchen.ci/docs/getting-started/introduction/> for more information about Test Kitchen. Fuzzy Matching -------------- Fuzzy matching can be used with all commands because kitchen uses regular expressions to search. For example, a fully qualified name: ``` kitchen list client-ubuntu-1804 --bare ``` will return something similar to: ``` client-ubuntu-1804 ``` A partial name: ``` kitchen list ubuntu --bare ``` will return something similar to: ``` client-ubuntu-1804 server-ubuntu-1804 ``` A short string: ``` kitchen list ub --bare ``` will return something similar to: ``` client-ubuntu-1804 server-ubuntu-1804 ``` An integer: ``` kitchen list 4 --bare ``` will return something similar to: ``` client-ubuntu-1804 server-ubuntu-1804 ``` A single-quoted Ruby regular expression: ``` kitchen list '^cli.*-65$' --bare ``` will return something similar to: ``` client-centos-65 ``` kitchen converge ---------------- Use the `converge` subcommand to converge one (or more) instances. Instances are based on the list of platforms in the kitchen.yml file. This process will install Chef Infra Client on an instance using the Chef installer, upload cookbook files and minimal configuration to the instance, and then start a Chef Infra Client run using the run-list and attributes specified in the kitchen.yml file. Test Kitchen will skip unnecessary steps. For example, if Chef Infra Client is already installed to the instance, Test Kitchen will not re-install Chef Infra Client. That said, Test Kitchen will always upload the cookbook files and minimal configuration. This ensures that cookbook testing is being done correctly. The following exit codes are used by Test Kitchen: * `0` means the operation was successful * Any non-zero value means at least one part of the operation was unsuccessful In general, use the `test` subcommand to verify the end-to-end quality of a cookbook. Use the `converge` and `verify` subcommands during the normal the day-to-day development of a cookbook. ### Syntax This subcommand has the following syntax: ``` kitchen converge PLATFORMS (options) ``` ### Options This subcommand has the following options: `-c`, `--concurrency` The number of allowed concurrent connections. Default: `9999` (all instances, effectively). `-l`, `--log-level` The level of logging to be stored in a log file. Options (in order of priority): `debug`, `info`, `warn`, `error`, and `fatal`. Default: `info`. `PLATFORMS` Run Test Kitchen against one or more platforms listed in the kitchen.yml file. Use `all` to run Test Kitchen against all platforms. Use a Ruby regular expression to glob two or more platforms into a single run. For example, if a kitchen.yml file contains the following: ``` - name: centos-7 - name: centos-8 - name: fedora-latest - name: ubuntu-1604 - name: ubuntu-1804 ``` then a regular expression like `(04|7)` would run Test Kitchen against `centos-7`, `ubuntu-1604`, and `ubuntu-1804`. A regular expression like `(ubuntu)` would run Test Kitchen against `ubuntu-1604` and `ubuntu-1804`. A regular expression like `(fedora)` would run Test Kitchen against only `fedora-latest`. Default: `all`. ### Examples **Converge the default CentOS instance** To converge the default CentOS instance, run the following: ``` kitchen converge default-centos-7 ``` Chef Infra Client is downloaded the first time this command is run. The output of the command is similar to: ``` -----> Starting Kitchen (v1.4.2) -----> Converging <default-centos-7>... Preparing files for transfer Preparing cookbooks from project directory Removing non-cookbook files before transfer Preparing nodes -----> Installing Chef Omnibus (true) downloading https://www.chef.io/chef/install.sh to file /tmp/install.sh ... Downloading Chef ... Installing Chef ... Thank you for installing Chef! Transferring files to <default-centos-7> [2014-06-27T18:41:04+00:00] INFO: Forking chef instance to converge... Starting Chef Client, version 12.4.1 [2014-06-27T18:45:18+00:00] INFO: *** Chef 12.4.1 *** [2014-06-27T18:45:18+00:00] INFO: Chef-client pid: 3226 [2014-06-27T18:45:25+00:00] INFO: Setting the run_list to ["recipe[chef-repo::default]"] from CLI options [2014-06-27T18:45:25+00:00] INFO: Run List is [recipe[chef-repo::default]] [2014-06-27T18:45:25+00:00] INFO: Run List expands to [chef-repo::default] [2014-06-27T18:45:25+00:00] INFO: Starting Chef Run for default-centos-7 [2014-06-27T18:45:25+00:00] INFO: Running start handlers [2014-06-27T18:42:40+00:00] INFO: Start handlers complete. Compiling Cookbooks... Converging 1 resources Recipe: chef-repo::default * file[/root/test.txt] action create... INFO: Processing file[/root/test.txt] action create (chef-repo::default line 10) [2014-06-27T18:42:40+00:00] INFO: file[/root/test.txt] created file /root/test.txt - create new file /root/test.txt... INFO: file[/root/test.txt] updated file contents /root/test.txt - update content in file /root/test.txt from none to d9c88f --- /root/test.txt 2014-06-27 18:42:40.695889276 +0000 +++ /tmp/.test.txt20140627-2810-1xdx98p 2014-06-27 18:42:40.695889276 +0000 @@ -1 +1,2 @@ +This file created by Chef! - restore selinux security context [2014-06-27T18:42:40+00:00] INFO: Chef Run complete in 0.168252291 seconds Running handlers: [2014-06-27T18:42:40+00:00] INFO: Running report handlers Running handlers complete [2014-06-27T18:42:40+00:00] INFO: Report handlers complete Chef Client finished, 1/1 resources updated in 7.152725504 seconds Finished converging <default-centos-7> (0m8.43s). -----> Kitchen is finished. (0m15.96s) ``` **Converge the default Ubuntu instance** To converge the default Ubuntu instance, run the following: ``` kitchen converge default-ubuntu-1804 ``` Chef Infra Client is downloaded the first time this command is run. The output of the command is similar to: ``` -----> Starting Kitchen (v1.4.2) -----> Converging <default-ubuntu-1804>... Preparing files for transfer Preparing cookbooks from project directory Removing non-cookbook files before transfer Preparing nodes -----> Installing Chef Omnibus (true) downloading https://www.chef.io/chef/install.sh to file /tmp/install.sh ... Downloading Chef ... Installing Chef ... Thank you for installing Chef! Transferring files to <default-ubuntu-1804> [2014-06-27T18:48:01+00:00] INFO: Forking chef instance to converge... Starting Chef Client, version 12.4.1 [2014-06-27T18:48:01+00:00] INFO: *** Chef 12.4.1 *** [2014-06-27T18:48:01+00:00] INFO: Chef-client pid: 1246 [2014-06-27T18:48:03+00:00] INFO: Setting the run_list to ["recipe[chef-repo::default]"] from CLI options [2014-06-27T18:48:03+00:00] INFO: Run List is [recipe[chef-repo::default]] [2014-06-27T18:48:03+00:00] INFO: Run List expands to [chef-repo::default] [2014-06-27T18:48:03+00:00] INFO: Starting Chef Run for default-ubuntu-1804 [2014-06-27T18:48:03+00:00] INFO: Running start handlers [2014-06-27T18:48:03+00:00] INFO: Start handlers complete. Compiling Cookbooks... Converging 1 resources Recipe: chef-repo::default * file[/home/vagrant/test.txt] action create... INFO: Processing file[/home/vagrant/test.txt] action create (chef-repo::default line 10) [2014-06-27T18:48:03+00:00] INFO: file[/home/vagrant/test.txt] created file /home/vagrant/test.txt - create new file /home/vagrant/test.txt... INFO: file[/home/vagrant/test.txt] updated file contents /home/vagrant/test.txt - update content in file /home/vagrant/test.txt from none to d9c88f --- /home/vagrant/test.txt 2014-06-27 18:48:03.233096345 +0000 +++ /tmp/.test.txt20140627-1246-178u9dg 2014-06-27 18:48:03.233096345 +0000 @@ -1 +1,2 @@ +This file created by Chef! [2014-06-27T18:48:03+00:00] INFO: Chef Run complete in 0.015439954 seconds Running handlers: [2014-06-27T18:48:03+00:00] INFO: Running report handlers Running handlers complete [2014-06-27T18:48:03+00:00] INFO: Report handlers complete Chef Client finished, 1/1 resources updated in 1.955915841 seconds Finished converging <default-ubuntu-1804> (0m15.67s). -----> Kitchen is finished. (0m15.96s) ``` kitchen create -------------- Use the `create` subcommand to create one (or more) instances. Instances are based on the list of platforms and suites in the kitchen.yml file. ### Syntax This subcommand has the following syntax: ``` kitchen create PLATFORMS (options) ``` ### Options This subcommand has the following options: `-c`, `--concurrency` The number of allowed concurrent connections. Default: `9999` (all instances, effectively). `-l`, `--log-level` The level of logging to be stored in a log file. Options (in order of priority): `debug`, `info`, `warn`, `error`, and `fatal`. Default: `info`. `PLATFORMS` Run Test Kitchen against one or more platforms listed in the kitchen.yml file. Use `all` to run Test Kitchen against all platforms. Use a Ruby regular expression to glob two or more platforms into a single run. For example, if a kitchen.yml file contains the following: ``` - name: centos-7 - name: centos-8 - name: fedora-latest - name: ubuntu-1604 - name: ubuntu-1804 ``` then a regular expression like `(04|7)` would run Test Kitchen against `centos-7`, `ubuntu-1604`, and `ubuntu-1804`. A regular expression like `(ubuntu)` would run Test Kitchen against `ubuntu-1604` and `ubuntu-1804`. A regular expression like `(fedora)` would run Test Kitchen against only `fedora-latest`. Default: `all`. ### Examples **Create the default CentOS instance** To create the default CentOS instance, run the following: ``` kitchen create default-centos-7 ``` CentOS is downloaded the first time this command is run, after which Vagrant is started. (This may take a few minutes.) The output of the command is similar to: ``` -----> Starting Kitchen (v1.4.2) -----> Creating <default-centos-7>... Bringing machine 'default' up with 'virtualbox' provider... ==> default: Box 'opscode-centos-7' could not be found. Attempting to find and install... default: Box Provider: virtualbox default: Box Version: >= 0 ==> default: Adding box 'opscode-centos-7' (v0) for provider: virtualbox default: Downloading: https://opscode-vm-bento.s3.amazonaws.com/vagrant/virtualbox/opscode_centos-6.5_chef-provisionerless.box ==> default: Successfully added box 'opscode-centos-7' (v0) for 'virtualbox'! ==> default: Importing base box 'opscode-centos-7'... ==> default: Matching MAC address for NAT networking... ==> default: Setting the name of the VM: default-centos-7_default_1403650129063_53517 ==> default: Clearing any previously set network interfaces... ==> default: Preparing network interfaces based on configuration... default: Adapter 1: nat ==> default: Forwarding ports... default: 22 => 2222 (adapter 1) ==> default: Booting VM... ==> default: Waiting for machine to boot. This may take a few minutes... default: SSH address: 127.0.0.1:2222 default: SSH username: vagrant default: SSH auth method: private key default: Warning: Connection timeout. Retrying... ==> default: Machine booted and ready! ==> default: Checking for guest additions in VM... ==> default: Setting hostname... ==> default: Machine not provisioning because `--no-provision` is specified. Vagrant instance <default-centos-7> created. Finished creating <default-centos-7> (4m0.59s). -----> Kitchen is finished. (11m29.76s) ``` **Create the default Ubuntu instance** To create the default Ubuntu instance, run the following: ``` kitchen create default-ubuntu-1804 ``` Ubuntu is downloaded the first time this command is run, after which Vagrant is started. (This may take a few minutes.) The output of the command is similar to: ``` -----> Starting Kitchen (v1.4.2) -----> Creating <default-ubuntu-1804>... Bringing machine 'default' up with 'virtualbox' provider... ==> default: Box 'opscode-ubuntu-12.04' could not be found. Attempting to find and install... default: Box Provider: virtualbox default: Box Version: >= 0 ==> default: Adding box 'opscode-ubuntu-12.04' (v0) for provider: virtualbox default: Downloading: https://opscode-vm-bento.s3.amazonaws.com/vagrant/virtualbox/opscode_ubuntu-12.04_chef-provisionerless.box ==> default: Successfully added box 'opscode-ubuntu-12.04' (v0) for 'virtualbox'! ==> default: Importing base box 'opscode-ubuntu-12.04'... ==> default: Matching MAC address for NAT networking... ==> default: Setting the name of the VM: default-ubuntu-1804_default_1403651715173_54200 ==> default: Fixed port collision for 22 => 2222. Now on port 2200. ==> default: Clearing any previously set network interfaces... ==> default: Preparing network interfaces based on configuration... default: Adapter 1: nat ==> default: Forwarding ports... default: 22 => 2200 (adapter 1) ==> default: Booting VM... ==> default: Waiting for machine to boot. This may take a few minutes... default: SSH username: vagrant default: SSH auth method: private key default: Warning: Connection timeout. Retrying... ==> default: Machine booted and ready! ==> default: Checking for guest additions in VM... ==> default: Setting hostname... ==> default: Machine not provisioning because `--no-provision` is specified. Vagrant instance <default-ubuntu-1804> created. Finished creating <default-ubuntu-1804> (4m1.59s). -----> Kitchen is finished. (10m58.24s) ``` kitchen destroy --------------- Use the `destroy` subcommand to delete one (or more) instances. Instances are based on the list of platforms and suites in the kitchen.yml file. ### Syntax This subcommand has the following syntax: ``` kitchen destroy PLATFORMS (options) ``` ### Options This subcommand has the following options: `-c`, `--concurrency` The number of allowed concurrent connections. Default: `9999` (all instances, effectively). `-l`, `--log-level` The level of logging to be stored in a log file. Options (in order of priority): `debug`, `info`, `warn`, `error`, and `fatal`. Default: `info`. `PLATFORMS` Run Test Kitchen against one or more platforms listed in the kitchen.yml file. Use `all` to run Test Kitchen against all platforms. Use a Ruby regular expression to glob two or more platforms into a single run. For example, if a kitchen.yml file contains the following: ``` - name: centos-7 - name: centos-8 - name: fedora-latest - name: ubuntu-1604 - name: ubuntu-1804 ``` then a regular expression like `(04|7)` would run Test Kitchen against `centos-7`, `ubuntu-1604`, and `ubuntu-1804`. A regular expression like `(ubuntu)` would run Test Kitchen against `ubuntu-1604` and `ubuntu-1804`. A regular expression like `(fedora)` would run Test Kitchen against only `fedora-latest`. Default: `all`. ### Examples None. kitchen diagnose ---------------- Use the `diagnose` subcommand to show a computed diagnostic configuration for one (or more) instances. This subcommand will make all implicit configuration settings explicit because it echoes back all of the configuration data as YAML. ### Syntax This subcommand has the following syntax: ``` kitchen diagnose PLATFORMS (options) ``` ### Options This subcommand has the following options: `--all` Include all diagnostics. Default: `false`. `--instances` Include instance diagnostics. Default: `true`. `-l`, `--log-level` The level of logging to be stored in a log file. Options (in order of priority): `debug`, `info`, `warn`, `error`, and `fatal`. Default: `info`. `--loader` Include data loader diagnostics. Default: `false`. `PLATFORMS` Run Test Kitchen against one or more platforms listed in the kitchen.yml file. Use `all` to run Test Kitchen against all platforms. Use a Ruby regular expression to glob two or more platforms into a single run. For example, if a kitchen.yml file contains the following: ``` - name: centos-7 - name: centos-8 - name: fedora-latest - name: ubuntu-1604 - name: ubuntu-1804 ``` then a regular expression like `(04|7)` would run Test Kitchen against `centos-7`, `ubuntu-1604`, and `ubuntu-1804`. A regular expression like `(ubuntu)` would run Test Kitchen against `ubuntu-1604` and `ubuntu-1804`. A regular expression like `(fedora)` would run Test Kitchen against only `fedora-latest`. Default: `all`. ### Examples **Diagnose an instance** Use the `--loader` option to include diagnostic data in the output: ``` loader:combined_config:filename:raw_data:driver:name:vagrantsocket:tcp://192.0.2.0:1234provisioner:#... ``` or: ``` ---loader:global_config:filename:"/Users/username/.kitchen/config.yml"raw_data:#...project_config:filename:"/Users/username/Projects/sandbox/path/to/kitchen.yml"raw_data:#...local_config: ``` **Diagnose an instance using –instances option** Use the `--instances` option to track instances, which are based on the list of platforms and suites in the kitchen.yml file: ``` ---instancesdefault-ubuntu-1804busser:root_path:/tmp/busserruby_bindir:/opt/chef/embedded/binsudo:true ``` **Diagnose an instance using –loader option** This command returns data as YAML: ``` ---timestamp:2014-04-15 18:59:58.460470000Zkitchen-version:1.2.2.devinstances:default-ubuntu-1804# ...default-centos-8# ... ``` When Test Kitchen is being used to test cookbooks, Test Kitchen will track state data: ``` ---instances:default-ubuntu-1804state_file:hostname:192.0.2.0last_action:createport:'22'ssh_key:"/Users/username/path/to/key"username:vagrantdefault-centos-65# ... ``` and will track information that was given to a driver: ``` ---instances:default-ubuntu-1804driver:box:opscode-ubuntu-18.04box_url:https://URL/path/to/filename.boxkitchen_root:"/Users/username/Projects/sandbox/" ``` and will track information about provisioners: ``` ---instances:default-ubuntu-1804provisioner:attributes:{}chef_omnibus_url:https://www.chef.io/chef/install.shclients_path:name:chef_zero ``` kitchen driver create --------------------- Use the `driver create` subcommand to create a new Test Kitchen driver in the RubyGems project. ### Syntax This subcommand has the following syntax: ``` kitchen driver create NAME ``` ### Options This subcommand has the following options: `-l`, `--license` The license for the RubyGems file. Possible values: `apachev2`, `lgplv3`, `mit`, and `reserved`. Default: `apachev2`. ### Examples None. kitchen exec ------------ Use the `exec` subcommand to execute a command on a remote instance. ### Syntax This subcommand has the following syntax: ``` kitchen exec PLATFORMS (options) ``` ### Options This subcommand has the following options: `-c REMOTE_COMMAND` Use to specify a remote command to be run via SSH. `PLATFORMS` Run Test Kitchen against one or more platforms listed in the kitchen.yml file. Use `all` to run Test Kitchen against all platforms. Use a Ruby regular expression to glob two or more platforms into a single run. For example, if a kitchen.yml file contains the following: ``` - name: centos-7 - name: centos-8 - name: fedora-latest - name: ubuntu-1604 - name: ubuntu-1804 ``` then a regular expression like `(04|7)` would run Test Kitchen against `centos-7`, `ubuntu-1604`, and `ubuntu-1804`. A regular expression like `(ubuntu)` would run Test Kitchen against `ubuntu-1604` and `ubuntu-1804`. A regular expression like `(fedora)` would run Test Kitchen against only `fedora-latest`. Default: `all`. ### Examples None. kitchen init ------------ Use the `init` subcommand to create an initial Test Kitchen environment, including: * Creating a kitchen.yml file * Appending Test Kitchen to the RubyGems file, .gitignore, and .thor * Creating the `test/integration/default` directory ### Syntax This subcommand has the following syntax: ``` kitchen init ``` ### Options This subcommand has the following options: `--create_gemfile` Create a RubyGems file, if one does not already exist. Default: `false`. `-D`, `--driver` Add one (or more) Test Kitchen drivers to a RubyGems file. Default: `kitchen-vagrant`. `-l`, `--log-level` The level of logging to be stored in a log file. Options (in order of priority): `debug`, `info`, `warn`, `error`, and `fatal`. Default: `info`. `-P`, `--provisioner` The default provisioner that is used by Test Kitchen. `PLATFORMS` Run Test Kitchen against one or more platforms listed in the kitchen.yml file. Use `all` to run Test Kitchen against all platforms. Use a Ruby regular expression to glob two or more platforms into a single run. For example, if a kitchen.yml file contains the following: ``` - name: centos-7 - name: centos-8 - name: fedora-latest - name: ubuntu-1604 - name: ubuntu-1804 ``` then a regular expression like `(04|7)` would run Test Kitchen against `centos-7`, `ubuntu-1604`, and `ubuntu-1804`. A regular expression like `(ubuntu)` would run Test Kitchen against `ubuntu-1604` and `ubuntu-1804`. A regular expression like `(fedora)` would run Test Kitchen against only `fedora-latest`. Default: `all`. ### Examples **Create the Test Kitchen environment** ``` kitchen init --driver=kitchen-vagrant ``` will return something similar to: ``` create kitchen.yml create test/integration/default create .gitignore append .gitignore append .gitignore run gem install kitchen-vagrant from "." Fetching: kitchen-vagrant-0.12.0.gem (100%) Successfully installed kitchen-vagrant-0.12.0 1 gem installed ``` kitchen list ------------ Use the `list` subcommand to view the list of instances. Instances are based on the list of platforms in the kitchen.yml file. Test Kitchen will auto-name instances by combining a suite name with a platform name. For example, if a suite is named `default` and a platform is named `ubuntu-18.04`, then the instance would be `default-ubuntu-1804`. This ensures that Test Kitchen instances have safe DNS and hostname records. ### Syntax This subcommand has the following syntax: ``` kitchen list PLATFORMS (options) ``` ### Options This subcommand has the following options: `-b`, `--bare` Print the name of each instance, one instance per line. Default: `false`. `-l`, `--log-level` The level of logging to be stored in a log file. Options (in order of priority): `debug`, `info`, `warn`, `error`, and `fatal`. Default: `info`. `PLATFORMS` Run Test Kitchen against one or more platforms listed in the kitchen.yml file. Use `all` to run Test Kitchen against all platforms. Use a Ruby regular expression to glob two or more platforms into a single run. For example, if a kitchen.yml file contains the following: ``` - name: centos-7 - name: centos-8 - name: fedora-latest - name: ubuntu-1604 - name: ubuntu-1804 ``` then a regular expression like `(04|7)` would run Test Kitchen against `centos-7`, `ubuntu-1604`, and `ubuntu-1804`. A regular expression like `(ubuntu)` would run Test Kitchen against `ubuntu-1604` and `ubuntu-1804`. A regular expression like `(fedora)` would run Test Kitchen against only `fedora-latest`. Default: `all`. ### Examples **View a list of Test Kitchen instances** To view the list of Test Kitchen instances: ``` kitchen list ``` A list will be returned, similar to: ``` Instance Driver Provisioner Last Action default-ubuntu-18.04 vagrant chef_zero created default-centos-8 vagrant chef_zero created ``` or: ``` Instance Driver Provisioner Last Action default-ubuntu-18.04 vagrant chef_zero converged default-centos-8 vagrant chef_zero created ``` or: ``` Instance Driver Provisioner Last Action default-ubuntu-18.04 vagrant chef_zero verified default-centos-8 vagrant chef_zero created ``` or: ``` Instance Driver Provisioner Last Action default-ubuntu-18.04 vagrant chef_zero created default-centos-8 vagrant chef_zero <not created``` or if there are multiple suites defined, such as `default` and `test`: ``` Instance Driver Provisioner Last Action default-ubuntu-18.04 vagrant chef_zero <not created> default-centos-8 vagrant chef_zero <not created> test-ubuntu-18.04 vagrant chef_zero <not created> test-centos-8 vagrant chef_zero <not created``` kitchen login ------------- Use the `login` subcommand to log in to a single instance. Instances are based on the list of platforms and suites in the kitchen.yml file. After logging in successfully, the instance can be interacted with just like any other virtual machine, including adding or removing packages, starting or stopping services, and so on. It’s a sandbox. Make any change necessary to help improve the coverage for cookbook testing. ### Syntax This subcommand has the following syntax: ``` kitchen login PLATFORM (options) ``` ### Options This subcommand has the following options: `-l`, `--log-level` The level of logging to be stored in a log file. Options (in order of priority): `debug`, `info`, `warn`, `error`, and `fatal`. Default: `info`. `PLATFORMS` Run Test Kitchen against one or more platforms listed in the kitchen.yml file. Use `all` to run Test Kitchen against all platforms. Use a Ruby regular expression to glob two or more platforms into a single run. For example, if a kitchen.yml file contains the following: ``` - name: centos-7 - name: centos-8 - name: fedora-latest - name: ubuntu-1604 - name: ubuntu-1804 ``` then a regular expression like `(04|7)` would run Test Kitchen against `centos-7`, `ubuntu-1604`, and `ubuntu-1804`. A regular expression like `(ubuntu)` would run Test Kitchen against `ubuntu-1604` and `ubuntu-1804`. A regular expression like `(fedora)` would run Test Kitchen against only `fedora-latest`. Default: `all`. ### Examples To login to the default Ubuntu instance, run the following: ``` kitchen login default-ubuntu-1804 ``` to return something similar to: ``` Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-51-generic x86_64) Last login: Wed Jul 3 18:21:09 2019 from 10.0.2.2 vagrant@default-ubuntu-1804:~$ ``` kitchen setup ------------- Use the `setup` subcommand to set up one (or more) instances. Instances are based on the list of platforms in the kitchen.yml file. ### Syntax This subcommand has the following syntax: ``` kitchen setup PLATFORMS (options) ``` ### Options This subcommand has the following options: `-c`, `--concurrency` The number of allowed concurrent connections. Default: `9999` (all instances, effectively). `-l`, `--log-level` The level of logging to be stored in a log file. Options (in order of priority): `debug`, `info`, `warn`, `error`, and `fatal`. Default: `info`. `PLATFORMS` Run Test Kitchen against one or more platforms listed in the kitchen.yml file. Use `all` to run Test Kitchen against all platforms. Use a Ruby regular expression to glob two or more platforms into a single run. For example, if a kitchen.yml file contains the following: ``` - name: centos-7 - name: centos-8 - name: fedora-latest - name: ubuntu-1604 - name: ubuntu-1804 ``` then a regular expression like `(04|7)` would run Test Kitchen against `centos-7`, `ubuntu-1604`, and `ubuntu-1804`. A regular expression like `(ubuntu)` would run Test Kitchen against `ubuntu-1604` and `ubuntu-1804`. A regular expression like `(fedora)` would run Test Kitchen against only `fedora-latest`. Default: `all`. ### Examples None. kitchen test ------------ Use the `test` subcommand to test one (or more) verified instances. Instances are based on the list of platforms and suites in the kitchen.yml file. This subcommand will create a new instance (cleaning up a previous instance, if necessary), converge that instance, set up the test harness, verify the instance using that test harness, and then destroy the instance. In general, use the `test` subcommand to verify the end-to-end quality of a cookbook. Use the `converge` and `verify` subcommands during the normal day-to-day development of a cookbook. ### Syntax This subcommand has the following syntax: ``` kitchen test PLATFORMS (options) ``` ### Options This subcommand has the following options: `--auto-init` Invoke the `init` command if kitchen.yml is missing. Default: `false`. `-c NUMBER`, `--concurrency NUMBER` The number of allowed concurrent connections. Use this option to limit the number of instances that are tested concurrently. For example, `--concurrency 6` will set this limit to six concurrent instances. Default: `9999` (all instances, effectively). `-d`, `--destroy` The destroy strategy used at the conclusion of a Test Kitchen run. Possible values: `always` (always destroy instances), `never` (never destroy instances), or `passing` (only destroy instances that passed). Default: `passing`. `-l`, `--log-level` The level of logging to be stored in a log file. Options (in order of priority): `debug`, `info`, `warn`, `error`, and `fatal`. Default: `info`. `PLATFORMS` Run Test Kitchen against one or more platforms listed in the kitchen.yml file. Use `all` to run Test Kitchen against all platforms. Use a Ruby regular expression to glob two or more platforms into a single run. For example, if a kitchen.yml file contains the following: ``` - name: centos-7 - name: centos-8 - name: fedora-latest - name: ubuntu-1604 - name: ubuntu-1804 ``` then a regular expression like `(04|7)` would run Test Kitchen against `centos-7`, `ubuntu-1604`, and `ubuntu-1804`. A regular expression like `(ubuntu)` would run Test Kitchen against `ubuntu-1604` and `ubuntu-1804`. A regular expression like `(fedora)` would run Test Kitchen against only `fedora-latest`. Default: `all`. ### Examples **Test the default Ubuntu instance** To test the default Ubuntu instance, run the following: ``` kitchen test default-ubuntu-1804 ``` to return something similar to: ``` -----> Starting Kitchen (v2.2.5) -----> Cleaning up any prior instances of <default-ubuntu-1804> -----> Destroying <default-ubuntu-1804>... ... Finished destroying <config-ubuntu-1804> (0m4.92s). -----> Testing <default-ubuntu-1804> -----> Creating <default-ubuntu-1804>... Bringing machine 'default' up with 'virtualbox' provider... ... Vagrant instance <default-ubuntu-1804> created. Finished creating <default-ubuntu-1804> (0m34.01s). -----> Converging <default-ubuntu-1804>... ... -----> Installing Chef install only if missing package Downloading https://omnitruck.chef.io/install.sh to file /tmp/install.sh ... Installing chef ... Setting up chef (15.1.36-1) ... Thank you for installing Chef Infra Client! For help getting started visit https://learn.chef.io ... Starting Chef Infra Client, version 15.1.36 ... Converging 2 resources Recipe: git::default * package[git] action install[date/time] INFO: Processing package[git] action install (git::default line 10) - install version 1:2.3.4.5-6 of package git * log[log_description] action write[date/time] INFO: Processing log[log_description] action write (git::default line 5) ... Chef Infra Client finished finished, 2 resources updated Finished converging <default-ubuntu-1804> (0m45.17s). -----> Setting up <default-ubuntu-1804>... Finished setting up <default-ubuntu-1804> (0m0.00s). -----> Verifying <default-ubuntu-1804>... ... Package: `git` ✓ should exist Test Summary: 1 successful, 0 failures, 0 skipped Finished verifying <default-ubuntu-1804> (0m1.25s). -----> Destroying <default-ubuntu-1804>... ... Finished destroying <default-ubuntu-1804> (0m4.68s). Finished testing <default-ubuntu-1804> (0m57.80s). ``` **Test an instance using –concurrency option** Use the `--concurrency` option to control the number of instances that are tested concurrently on the local workstation. The default setting is to test all instances, but the practical setting depends on the capabilities of the local machine itself. The following examples will limit the number of instances to four: ``` kitchen test --concurrency=4 ``` or: ``` kitchen test --concurrency 4 ``` or: ``` kitchen test -c=4 ``` or: ``` kitchen test -c 4 ``` kitchen verify -------------- Use the `verify` subcommand to verify one (or more) instances. Instances are based on the list of platforms and suites in the kitchen.yml file. In general, use the `test` subcommand to verify the end-to-end quality of a cookbook. Use the `converge` and `verify` subcommands during the normal day-to-day development of a cookbook. ### Syntax This subcommand has the following syntax: ``` kitchen verify PLATFORMS (options) ``` ### Options This subcommand has the following options: `-c`, `--concurrency` The number of allowed concurrent connections. Default: `9999` (all instances, effectively). `-l`, `--log-level` The level of logging to be stored in a log file. Options (in order of priority): `debug`, `info`, `warn`, `error`, and `fatal`. Default: `info`. `PLATFORMS` Run Test Kitchen against one or more platforms listed in the kitchen.yml file. Use `all` to run Test Kitchen against all platforms. Use a Ruby regular expression to glob two or more platforms into a single run. For example, if a kitchen.yml file contains the following: ``` - name: centos-7 - name: centos-8 - name: fedora-latest - name: ubuntu-1604 - name: ubuntu-1804 ``` then a regular expression like `(04|7)` would run Test Kitchen against `centos-7`, `ubuntu-1604`, and `ubuntu-1804`. A regular expression like `(ubuntu)` would run Test Kitchen against `ubuntu-1604` and `ubuntu-1804`. A regular expression like `(fedora)` would run Test Kitchen against only `fedora-latest`. Default: `all`. ### Examples **Verify the default Ubuntu instance** To verify the default Ubuntu instance, run the following: ``` kitchen verify default-ubuntu-18.04 ``` to return something similar to: ``` -----> Starting Kitchen (v2.2.5) -----> Setting up <default-ubuntu-18.04> Fetching: <name of test tool> (100%) Successfully installed <name of test tool> # gems installed -----> Setting up <name of test tool> ... -----> Running <name of test tool> test suite ✓ <test result2 tests, 0 failures Finished verifying <default-ubuntu-18.04> (2m1.12s). -----> Kitchen is finished. (2m3.45s) echo $? 0 ``` or: ``` -----> Starting Kitchen (v2.2.5) -----> Setting up <default-ubuntu-18.04> Fetching: <name of test tool> (100%) Successfully installed <name of test tool> # gems installed -----> Setting up <name of test tool> ... -----> Running <name of test tool> test suite - <test result2 tests, 1 failures ... exit code was 1 echo $? 10 ``` kitchen version --------------- Use the `version` subcommand to print the version of Kitchen. ### Syntax This subcommand has the following syntax: ``` kitchen version ``` ### Options This subcommand does not have any options. ### Examples **Verify the version of Test Kitchen** To view the version of Test Kitchen: ``` kitchen version ``` will return something similar to: ``` Test Kitchen version 2.2.5 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/ctl_kitchen/kitchen.yml =========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/config_yml_kitchen.md) Use [Test Kitchen](https://kitchen.ci/) to automatically test cookbook data across any combination of platforms and test suites: * Defined in a kitchen.yml file * Uses a driver plugin architecture * Supports cookbook testing across many cloud providers and virtualization technologies * Supports all common testing frameworks that are used by the Ruby community * Uses a comprehensive set of base images provided by [Bento](https://github.com/chef/bento) Use a kitchen.yml file to define what is required to run Test Kitchen, including drivers, provisioners, platforms, and test suites. Note This topic details functionality that is packaged with Chef Workstation. See <https://kitchen.ci/docs/getting-started/introduction/> for more information about Test Kitchen. Syntax ------ The basic structure of a kitchen.yml file is as follows: ``` driver:name:driver_nameprovisioner:name:provisioner_nameverifier:name:verifier_nametransport:name:transport_nameplatforms:- name:platform-versiondriver:name:driver_name- name:platform-versionsuites:- name:suite_namerun_list:- recipe[cookbook_name::recipe_name]attributes:{foo:"bar"}excludes:- platform-version- name:suite_namedriver:name:driver_namerun_list:- recipe[cookbook_name::recipe_name]attributes:{foo:"bar"}includes:- platform-version ``` where: * `driver_name` is the name of a driver that will be used to create platform instances used during cookbook testing. This is the default driver used for all platforms and suites **unless** a platform or suite specifies a `driver` to override the default driver for that platform or suite; a driver specified for a suite will override a driver set for a platform * `provisioner_name` specifies how Chef Infra Client will be simulated during testing. `chef_zero` and `chef_solo` are the most common provisioners used for testing cookbooks * `verifier_name` specifies which application to use when running tests, such as `inspec` * `transport_name` specifies which transport to use when executing commands remotely on the test instance. `winrm` is the default transport on Windows. The `ssh` transport is the default on all other operating systems. * `platform-version` is the name of a platform on which Test Kitchen will perform cookbook testing, for example, `ubuntu-20.04` or `centos-7`; depending on the platform, additional driver details—for example, instance names and URLs used with cloud platforms like OpenStack or Amazon EC2—may be required * `platforms` may define Chef Infra Server attributes that are common to the collection of test suites * `suites` is a collection of test suites, with each `suite_name` grouping defining an aspect of a cookbook to be tested. Each `suite_name` must specify a run-list, for example: ``` run_list: - recipe[cookbook_name::default] - recipe[cookbook_name::recipe_name] ``` * Each `suite_name` grouping may specify `attributes` as a Hash: `{ foo: "bar" }` * A `suite_name` grouping may use `excludes` and `includes` to exclude/include one (or more) platforms. For example: ``` excludes: - platform-version - platform-version # for additional platforms ``` For example, a very simple kitchen.yml file: ``` driver:name:vagrantprovisioner:name:chef_zeroplatforms:- name:ubuntu-20.04- name:centos-8- name:debian-10suites:- name:defaultrun_list:- recipe[apache::httpd]excludes:- debian-10 ``` This file uses HashiCorp Vagrant as the driver, which requires no additional configuration because it’s the default driver used by Test Kitchen, chef-zero as the provisioner, and a single (default) test suite that runs on Ubuntu 20.04, and CentOS 7. Provisioner Settings -------------------- Test Kitchen can configure the chef-zero provisioner with the following Chef-specific settings: | Setting | Description | | --- | --- | | `attributes` | Chef attributes for use in the suite | | `chef_client_path` | Chef Infra Client provisioner only. | | `chef_metadata_url` | **This will be deprecated in a future version.** | | `chef_omnibus_install_options` | Use to specify the package to be installed. Possible values: `-P chef` (for Chef Infra Client) and `-P chef-workstation` (for the Chef Infra Client that is packaged as part of Chef Workstation). Use `-n` to specify the nightly build. For example: `-P chef-workstation` or `-n -P chef-workstation`. **This will be deprecated in a future version.** See the `product_name`, `product_version`, and `channel` settings instead. | | `chef_omnibus_root` | Default value: `/etc/opt` for UNIX and Linux, `$env:systemdrive\\opscode\\chef` on Microsoft Windows. | | `chef_omnibus_url` | The URL for an `install.sh` script that will install Chef Infra Client on the machine under test. Default value: `https://omnitruck.chef.io/install.sh`. **This will be deprecated in a future version.** | | `chef_solo_path` | chef-solo provisioner only. | | `chef_zero_host` | Chef Infra Client provisioner only. | | `chef_zero_port` | Chef Infra Client provisioner only. The port on which chef-zero is to listen. | | `client_rb` | Chef Infra Client provisioner only. A list of client.rb file settings. For example: ``` client_rb: log_level: :warn ``` | | `clients_path` | The relative path to the directory in which client data is located. This data must be defined as JSON. | | `cookbook_files_glob` | A file glob (pattern) that matches files considered to be part of the cookbook. (Typically, this value does not need to be modified from the default.) | | `data_path` | Use to specify the path from which non-cookbook files are copied to a Kitchen instance. | | `data_bags_path` | The relative path to a directory in which data bags and data bag items are defined. This data must be structured as if it were in the chef-repo. | | `deprecations_as_errors` | Set to true to treat deprecation warning messages as error messages. | | `driver` | Use to specify a driver for a platform. This will override the default driver. | | `enforce_idempotency` | Use with `multiple_converge` > 1. Set to `true` to force test-kitchen to fail if last converge has any updated resources. | | `encrypted_data_bag_secret_key_path` | The path to an RSA key file that is used to decrypt encrypted data bag items. | | `environments_path` | The relative path to the directory in which environment data is located. This data must be defined as JSON. | | `http_proxy` | The proxy server for HTTP connections. | | `https_proxy` | The proxy server for HTTPS connections. | | `no_proxy` | The comma-separated exception list of host patterns to exclude from proxying. | | `install_msi_url` | An alternate URL for a Windows MSI package that will install Chef Infra Client on the machine under test. **This will be deprecated in a future version.** Use the `download_url` setting instead. | | `json_attributes` | Chef Infra Client provisioner only. | | `log_file` | | | `multiple_converge` | Number of times to converge the node. Defaults to 1. | | `nodes_path` | The relative path to the directory in which node data is located. This data must be defined as JSON. | | `require_chef_omnibus` | Use to install the latest version of Chef Infra Client on a node. Set to `true` to install the latest version, `false` to not install Chef Infra Client (assumes the box already has it installed), or a version specifier like `15.3.12` to install a particular version, or simply `15` to install the latest 15.x package. When set to `true` or a version number, the `chef_omnibus_url` may be used to specify the URL of the `install.sh` that installs the specified version of Chef Infra Client. Default value: `true`. **This will be deprecated in a future version.** See the `product_version` and `install_strategy` settings. | | `roles_path` | The relative path to the directory in which role data is located. This data must be defined as JSON. | | `root_path` | The directory in which Kitchen will stage all content on the target node. This directory should be large enough to store all the content and must be writable. (Typically, this value does not need to be modified from the default value.) Default value: `/tmp/kitchen`. | | `ruby_bindir` | Chef Infra Client provisioner only. | | `run_list` | | | `solo_rb` | chef-solo provisioner only. | | `retry_on_exit_code` | Takes an array of exit codes to indicate that kitchen should retry the converge command. Default value: `[35, 213]`. | | `max_retries` | Number of times to retry the converge before passing along the failed status. Defaults value: 1. | | `wait_for_retry` | Number of seconds to wait between converge attempts. Default value: 30. | These settings may be added to the `provisioner` section of the kitchen.yml file when the provisioner is chef-zero or chef-solo. ### New Provisioner Settings | New Setting | Description | Default | Replaces | | --- | --- | --- | --- | | `product_name` | `chef` or `chef-workstation`. This setting must be specified in order to use the new settings. Using this setting overrides Test Kitchen's default behavior based on the `require_chef_omnibus` setting. | | `chef_omnibus_install_options` | | `product_version` | Product version number. Supports partial version numbers. | `latest` | `require_chef_omnibus` | | `channel` | Artifact repository name. `stable`, `current` or `unstable`. | `stable` | `chef_omnibus_install_options` | | `install_strategy` | Product install strategy. `once` (Don't install if any product installation detected), `always` or `skip`. | `once` | `require_chef_omnibus` | | `download_url` | Direct package URL. Supports all platforms. | | `install_msi_url` | | `checksum` | Optional setting when using `download_url`. Validates SHA256 checksum after download. | | | | `platform` | Override platform. | <auto detected> | | | `platform_version` | Override platform platform. | <auto detected> | | | `architecture` | Override platform architecture. | <auto detected> | | | `always_update_cookbooks` | Updates the policyfile.lock.json when changes are made to the cookbook. Supports `true` or `false` | <auto detected> | | Transport Settings ------------------ Kitchen can configure a transport with the following settings for either `ssh` or `winrm` transports: | Setting | Description | | --- | --- | | `connection_retries` | Maximum number of times to retry after a failed attempt to open a connection. The default is 5. | | `connection_retry_sleep` | Number of seconds to wait until attempting to make another connection after a failure. | | `max_wait_until_ready` | Maximum number of attempts to determine if the test instance is ready to accept commands. This defaults to 600. | | `password` | The password used for authenticating to the test instance. | | `port` | The port used to connect to the test instance. This defaults to `22` for the `ssh` transport and `5985` or `5986` for `winrm` using `http` or `https` respectively. | | `username` | The username used for authenticating to the test instance. This defaults to `administrator` for the `winrm` transport and `root` for the `ssh` transport. Some drivers may change this default. | These settings may be added to the `transport` section of the kitchen.yml file when the transport is SSH: | Setting | Description | | --- | --- | | `compression` | Wether or not to use compression. The default is `false`. | | `compression_level` | The default is 6 if `compression` is `true`. | | `connection_timeout` | Defaults to 15. | | `keepalive` | Defaults to `true`. | | `keepalive_interval` | Defaults to 60. | | `max_ssh_sessions` | Maximum number of parallel ssh sessions. | | `ssh_key` | Path to an ssh key identity file. | These settings may be added to the `transport` section of the kitchen.yml file when the transport is WinRM: | Setting | Description | | --- | --- | | `elevated` | When `true`, all commands are executed via a scheduled task. This may eliminate access denied errors related to double hop authentication, interacting with windows updates and installing some MSIs such as sql server and .net runtimes. Defaults to `false`. | | `elevated_password` | The password used by the identity running the scheduled task. This may be `null` in the case of service accounts. Defaults to `password`. | | `elevated_username` | The identity that the task runs under. This may also be set to service accounts such as `System`. This defaults to `username`. | | `rdp_port` | Port used making `rdp` connections for `kitchen login` commands. Defaults to 3389. | | `winrm_transport` | The transport type used by winrm as explained [here](https://github.com/WinRb/WinRM). The default is `negotiate`. `ssl` and `plaintext` are also acceptable values. | ### Work with Proxies The environment variables `http_proxy`, `https_proxy`, and `ftp_proxy` are honored by Test Kitchen for proxies. The client.rb file is read to look for proxy configuration settings. If `http_proxy`, `https_proxy`, and `ftp_proxy` are specified in the client.rb file, Chef Infra Client will configure the `ENV` variable based on these (and related) settings. For example: ``` http_proxy 'http://proxy.example.org:8080' http_proxy_user 'myself' http_proxy_pass 'Password1' ``` will be set to: ``` ENV['http_proxy'] = 'http://myself:Password1@proxy.example.org:8080' ``` Test Kitchen also supports `http_proxy` and `https_proxy` in the `kitchen.yml` file. You can set them manually or have them read from your local environment variables: ``` driver:name:vagrantprovisioner:name:chef_zero# Set proxy settings manually, orhttp_proxy:'http://user:password@server:port'https_proxy:'http://user:password@server:port'# Read from local environment variableshttp_proxy:<%= ENV['http_proxy'] %>https_proxy:<%= ENV['https_proxy'] %> ``` This will not set the proxy environment variables for applications other than Chef. The Vagrant plugin, [vagrant-proxyconf](http://tmatilai.github.io/vagrant-proxyconf/), can be used to set the proxy environment variables for applications inside the VM. Chef Infra Client Settings -------------------------- A kitchen.yml file may define Chef Infra Client-specific settings, such as whether to require the Chef installer or the URL from which Chef Infra Client is downloaded, or to override settings in the client.rb file: ``` provisioner:name:chef_zero *or* chef_solorequire_chef_omnibus:truechef_omnibus_url:https://www.chef.io/chef/install.sh...suites:- name:configrun_list:...attributes:chef_client:load_gems:chef-handler-updated-resources:require_name:"chef/handler/updated_resources"config:log_level:":debug"ssl_verify_mode:":verify_peer"start_handlers:[{class:"SimpleReport::UpdatedResources", arguments:[]}]report_handlers:[{class:"SimpleReport::UpdatedResources", arguments:[]}]exception_handlers:[{class:"SimpleReport::UpdatedResources", arguments:[]}]ohai:disabled_plugins:["passwd"] ``` where: * `require_chef_omnibus` is used to ensure that the Chef installer will be used to install Chef Infra Client to all platform instances; `require_chef_omnibus` may also be set to `latest`, which means the newest version of Chef Infra Client for that platform will be used for cookbook testing * `chef_omnibus_url` is used to specify the URL from which Chef Infra Client is downloaded * All of the `attributes` for the `config` test suite contain specific client.rb settings for use with this test suite Driver Settings --------------- Driver-specific configuration settings may be required. Use a block similar to: ``` driver:name:driver_nameoptional_settings:values ``` Specific `optional_settings: values` may be specified. ### Bento [Bento](https://github.com/chef/bento) is a Chef Software project that produces base testing VirtualBox, Parallels, and VMware boxes for multiple operating systems for use with Test Kitchen. By default, Test Kitchen uses the base images provided by Bento although custom images may also be built using HashiCorp Packer. ### Drivers Test Kitchen uses a driver plugin architecture to enable Test Kitchen to test instances on cloud providers such as Amazon EC2, Google Compute Engine, and Microsoft Azure. You can also test on multiple local hypervisors, such as VMware, Hyper-V, or VirtualBox. Note Chef Workstation includes many common Test Kitchen drivers. Most drivers have driver-specific configuration settings that must be added to the kitchen.yml file before Test Kitchen will be able to use that platform during cookbook testing. For information about these driver-specific settings, please refer to the driver-specific documentation. Some popular drivers: | Driver Plugin | Description | | --- | --- | | [kitchen-azurerm](https://github.com/test-kitchen/kitchen-azurerm) | A driver for Microsoft Azure. | | [kitchen-cloudstack](https://github.com/test-kitchen/kitchen-cloudstack) | A driver for CloudStack. | | [kitchen-digitalocean](https://github.com/test-kitchen/kitchen-digitalocean) | A driver for DigitalOcean. This driver ships in Chef Workstation. | | [kitchen-dokken](https://github.com/test-kitchen/kitchen-dokken) | A driver for Docker. This driver ships in Chef Workstation. | | [kitchen-dsc](https://github.com/test-kitchen/kitchen-dsc) | A driver for Windows PowerShell Desired State Configuration (DSC). | | [kitchen-ec2](https://github.com/test-kitchen/kitchen-ec2) | A driver for Amazon EC2. This driver ships in Chef Workstation. | | [kitchen-google](https://github.com/test-kitchen/kitchen-google) | A driver for Google Compute Engine. This driver ships in Chef Workstation | | [kitchen-hyperv](https://github.com/test-kitchen/kitchen-hyperv) | A driver for Microsoft Hyper-V Server. This driver ships in Chef Workstation. | | [kitchen-openstack](https://github.com/test-kitchen/kitchen-openstack) | A driver for OpenStack. This driver ships in Chef Workstation. | | [kitchen-rackspace](https://github.com/test-kitchen/kitchen-rackspace) | A driver for Rackspace. | | [kitchen-vagrant](https://github.com/test-kitchen/kitchen-vagrant) | A driver for HashiCorp Vagrant. This driver ships in Chef Workstation. | ### kitchen-vagrant The `kitchen-vagrant` driver for Kitchen generates a single Vagrantfile for each instance of Kitchen in a sandboxed directory. The `kitchen-vagrant` driver supports VirtualBox and VMware Fusion, requires Vagrant 1.1.0 (or higher), and is the default driver for Test Kitchen. The following attributes are used to configure `kitchen-vagrant` for Chef: | Attribute | Description | | --- | --- | | `box` | Required. Use to specify the box on which Vagrant will run. Default value: computed from the platform name of the instance. | | `box_check_update` | Use to check for box updates. Default value: `false`. | | `box_url` | Use to specify the URL at which the configured box is located. Default value: computed from the platform name of the instance, but only when the Vagrant provider is VirtualBox- or VMware-based. | | `communicator` | Use to override the `config.vm.communicator` setting in Vagrant. For example, when a base box is a Microsoft Windows operating system that does not have SSH installed and enabled, Vagrant will not be able to boot without a custom Vagrant file. Default value: `nil` (assumes SSH is available). | | `customize` | A hash of key-value pairs that define customizations that should be made to the Vagrant virtual machine. For example: `customize: memory: 1024 cpuexecutioncap: 50`. | | `guest` | Use to specify the `config.vm.guest` setting in the default Vagrantfile. | | `gui` | Use to enable the graphical user interface for the defined platform. This is passed to the `config.vm.provider` setting in Vagrant, but only when the Vagrant provider is VirtualBox- or VMware-based. | | `network` | Use to specify an array of network customizations to be applied to the virtual machine. Default value: `[]`. For example: `network: - ["forwarded_port", {guest: 80, host: 8080}] - ["private_network", {ip: "192.168.33.33"}]`. | | `pre_create_command` | Use to run a command immediately prior to `vagrant up --no-provisioner`. | | `provider` | Use to specify the Vagrant provider. This value must match a provider name in Vagrant. | | `provision` | Use to provision Vagrant when the instance is created. This is useful if the operating system needs customization during provisioning. Default value: `false`. | | `ssh_key` | Use to specify the private key file used for SSH authentication. | | `synced_folders` | Use to specify a collection of synchronized folders on each Vagrant instance. Source paths are relative to the Kitchen root path. Default value: `[]`. For example: `synced_folders: - ["data/%{instance_name}", "/opt/instance_data"] - ["/host_path", "/vm_path", "create: true, type: :nfs"]`. | | `vagrantfile_erb` | Use to specify an alternate Vagrant Embedded Ruby (ERB) template to be used by this driver. | | `vagrantfiles` | An array of paths to one (or more) Vagrant files to be merged with the default Vagrant file. The paths may be absolute or relative to the kitchen.yml file. | | `vm_hostname` | Use to specify the internal hostname for the instance. This is not required when connecting to a Vagrant virtual machine. Set this to `false` to prevent this value from being rendered in the default Vagrantfile. Default value: computed from the platform name of the instance. | The `kitchen-vagrant` driver can predict the box name for Vagrant and the download URL that have been published by Chef. For example: ``` platforms: - name: ubuntu-18.04 - name: ubuntu-20.04 - name: centos-7 - name: centos-8 - name: debian-10 ``` which will generate a configuration file similar to: ``` platforms: - name: ubuntu-18.04 driver: box: bento/ubuntu-18.04 - name: ubuntu-20.04 driver: box: bento/ubuntu-20.04 # ... ``` Examples -------- The following examples show actual kitchen.yml files used in Chef-maintained cookbooks. ### Chef, Chef Workstation The following example shows the provisioner settings needed to install Chef Workstation, and then use the version of Chef that is embedded in Chef Workstation to converge the node. To install the latest version of Chef Workstation: ``` provisioner:...chef_omnibus_install_options:-P chef-workstationchef_omnibus_root:/opt/chef-workstation ``` and to install a specific version of Chef Workstation: ``` provisioner:...chef_omnibus_install_options:-P chef-workstationchef_omnibus_root:/opt/chef-workstationrequire_chef_omnibus:0.9 ``` ### Microsoft Windows Platform The following example shows platform settings for the Microsoft Windows platform: ``` platforms:- name:eval-win2012r2-standardos_type:windowstransport:name:winrmelevated:true ``` If `name` begins with `win` then the `os_type` defaults to `windows`. The `winrm` transport is the default on Windows operating systems. Here `elevated` is true which runs windows commands via a scheduled task to imitate a local user. ### Chef Infra Client Cookbook The following kitchen.yml file is part of the `chef-client` cookbook and ensures Chef Infra Client is configured correctly. ``` driver:name:vagrantprovisioner:name:chef_zeroplatforms:- name:centos-8- name:fedora-latest- name:ubuntu-1804- name:ubuntu-2004suites:- name:service_initrun_list:- recipe[minitest-handler]- recipe[chef-client::config]- recipe[chef-client_test::service_init]- recipe[chef-client::init_service]attributes:{}- name:service_runitrun_list:- recipe[minitest-handler]- recipe[runit]- recipe[chef-client_test::service_runit]- recipe[chef-client::runit_service]attributes:{}- name:service_upstartrun_list:- recipe[minitest-handler]- recipe[chef-client_test::service_upstart]- recipe[chef-client::upstart_service]excludes:["centos-5.9"]attributes:{}- name:cronrun_list:- recipe[minitest-handler]- recipe[chef-client::cron]attributes:{}- name:delete_validationrun_list:- recipe[chef-client::delete_validation]attributes:{} ``` ### chef-splunk Cookbook The following kitchen.yml file is part of the `chef-splunk` cookbook and is used to help ensure the installation of the Splunk client and server is done correctly. ``` driver:name:vagrantcustomize:memory:1024provisioner:name:chef_zeroplatforms:- name:ubuntu-18.04- name:ubuntu-20.04- name:centos-7- name:centos-8suites:- name:clientrun_list:- recipe[chef-splunk::default]- recipe[test::default]attributes:dev_mode:truesplunk:accept_license:true- name:serverrun_list:- recipe[chef-splunk::default]attributes:dev_mode:truesplunk:is_server:trueaccept_license:truessl_options:enable_ssl:true ``` ### yum Cookbook The following kitchen.yml file is part of the `yum` cookbook: ``` driver:name:vagrantprovisioner:name:chef_zeroplatforms:- name:centos-7- name:centos-8- name:fedora-latestsuites:- name:defaultrun_list:- recipe[yum::default]- recipe[yum_test::test_repo] ``` ### Platform Attributes The following kitchen.yml file sets up a simple tiered configuration of the Chef Infra Server, including two front-end servers, a single back-end server, and two add-ons (Chef Push Jobs and Chef management console). The `platforms` block uses an `attributes` section to define Chef server-specific attributes that are used by all three test suites: ``` driver:name:vagrantprovisioner:name:chef_zeroplatforms:- name:ubuntu-18.04attributes:chef-server:api_fqdn:backend.chef-server.combackend:fqdn:backend.chef-server.comipaddress:123.456.789.0frontends:frontend1.chef-server.com:123.456.789.0frontend2.chef-server.com:123.456.789.0urls:private_chef:http://123.456.789.0/path/to/private-chef_11.1.4-1_amd64.debmanage:http://123.456.789.0/path/to/opscode-manage_1.3.1-1_amd64.debpush_jobs:http://123.456.789.0/path/to/opscode-push-jobs-server_1.1.1-1_amd64.debsuites:- name:frontend1driver:vm_hostname:frontend1.chef-server.comnetwork:- ["private_network",{ip:"123.456.789.0"}]customize:memory:2048cpus:2run_list:- recipe[chef-server::configfile]- recipe[chef-server::ntp]- recipe[chef-server::server]- recipe[chef-server::frontend]- name:frontend2driver:vm_hostname:frontend2.chef-server.comnetwork:- ["private_network",{ip:"123.456.789.0"}]customize:memory:2048cpus:2run_list:- recipe[chef-server::configfile]- recipe[chef-server::ntp]- recipe[chef-server::server]- recipe[chef-server::frontend]- name:backenddriver:vm_hostname:backend.chef-server.comnetwork:- ["private_network",{ip:"123.456.789.0"}]customize:memory:8192cpus:4run_list:- recipe[chef-server::configfile]- recipe[chef-server::ntp]- recipe[chef-server::server]- recipe[chef-server::backend] ``` ### Kitchen Converge On System Reboot Test-Kitchen can handle reboots (when initiated from Chef Infra Client) by setting `retry_on_exit_code`, `max_retries` and `wait_for_retry` attributes on the provisioner in `kitchen.yml` file as follows : ``` provisioner:name:chef_zeroretry_on_exit_code:- 35# 35 is the exit code signaling that the node is rebooting- 1max_retries:1client_rb:exit_status::enabled# Opt-in to the standardized exit codesclient_fork:false# Forked instances don't return the real exit code ``` **One note on Linux nodes**: The shutdown command blocks (as opposed to the Windows variant which registers the reboot and returns right away), so once the timeout period passes, Chef Infra Client and the node are in a race to see who can exit/shutdown first - so you may or may not get the exit code out of Linux instances. In that case, you can add `1` to the `retry_on_exit_code` array and that should catch both cases. Please refer [YAML documentation](https://symfony.com/doc/current/components/yaml/yaml_format.html#collections) to set `retry_on_exit_code` attribute. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/config_yml_kitchen/About Knife =========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife.md) knife is a command-line tool that provides an interface between a local chef-repo and the Chef Infra Server. knife helps users to manage: * Nodes * Cookbooks and recipes * Roles, Environments, and Data Bags * Resources within various cloud environments * The installation of Chef Infra Client onto nodes * Searching of indexed data on the Chef Infra Server The Knife Quick Reference provides an all-in-one quick reference of knife commands. You can view the [overview](https://github.com/chef/quick-reference/blob/main/qr_knife_web.png) or download the [source files](https://github.com/chef/quick-reference). | Topic | Description | | --- | --- | | [Setting up Knife](../../knife_setup/index) | Configure knife to interact with your organization's Chef Infra Server and infrastructure. | | [Knife Common Options](../../knife_options/index) | Common options that are available for all knife subcommands. | | [config.rb](../../config_rb/index) | Common options for the `config.rb` (knife.rb) file | | [config.rb Optional Settings](../../config_rb_optional_settings/index) | Additional options for your `config.rb` file | Knife Subcommands ----------------- knife includes a collection of built in subcommands that work together to provide all of the functionality required to take specific actions against any object in an organization, including cookbooks, nodes, roles, data bags, environments, and users. ### Knife Command Syntax All knife subcommands have the following syntax: ``` knife subcommand [ARGUMENT] (options) ``` Each subcommand has its own set of arguments and options. Note All syntax examples in this document show variables in ALL_CAPS. For example `-u PORT_LIST` (where PORT_LIST is a comma-separated list of local and public UDP ports) or `-F FORMAT` (where FORMAT determines the output format, either `summary`, `text`, `json`, `yaml`, or `pp`). These variables often require specific values that are unique to each organization. ### Built-in Subcommands | Subcommand | Description | | --- | --- | | [knife_bootstrap](../../knife_bootstrap/index) | Use the `knife bootstrap` subcommand to run a bootstrap operation that installs Chef Infra Client on the target system. The bootstrap operation must specify the IP address or FQDN of the target system. | | [knife_client](../../knife_client/index) | Use the `knife client` subcommand to manage an API client list and their associated RSA public key-pairs. This allows authentication requests to be made to the Chef Infra Server by any entity that uses the Chef Infra Server API, such as Chef Infra Client and knife. | | [knife configure](../../knife_configure/index) | Use the `knife configure` subcommand to create the [client.rb](/config_rb_client/) and credential files so that they can be distributed to workstations and nodes. | | [knife cookbook](../../knife_cookbook/index) | Use the `knife cookbook` subcommand to interact with cookbooks that are located on the Chef Infra Server or the local chef-repo. | | [knife data bag](../../knife_data_bag/index) | Use the `knife data bag` subcommand to manage arbitrary stores of globally available JSON data. | | [knife delete](../../knife_delete/index) | Use the `knife delete` subcommand to delete an object from a Chef Infra Server. This subcommand works similar to `knife cookbook delete`, `knife data bag delete`, `knife environment delete`, `knife node delete`, and `knife role delete`, but with a single verb (and a single action). | | [knife deps](../../knife_deps/index) | Use the `knife deps` subcommand to identify dependencies for a node, role, or cookbook. | | [knife diff](../../knife_diff/index) | Use the `knife diff` subcommand to compare the differences between files and directories on the Chef Infra Server and in the chef-repo. For example, to compare files on the Chef Infra Server prior to uploading or downloading files using the `knife download` and `knife upload` subcommands, or to ensure that certain files in multiple production environments are the same. This subcommand is similar to the `git diff` command that can be used to diff what is in the chef-repo with what is synced to a git repository. | | [knife download](../../knife_download/index) | Use the `knife download` subcommand to download roles, cookbooks, environments, nodes, and data bags from the Chef Infra Server to the current working directory. It can be used to back up data on the Chef Infra Server, inspect the state of one or more files, or to extract out-of-process changes users may have made to files on the Chef Infra Server, such as if a user made a change that bypassed version source control. This subcommand is often used in conjunction with `knife diff`, which can be used to see exactly what changes will be downloaded, and then `knife upload`, which does the opposite of `knife download`. | | [knife edit](../../knife_edit/index) | Use the `knife edit` subcommand to edit objects on the Chef Infra Server. This subcommand works similar to `knife cookbook edit`, `knife data bag edit`, `knife environment edit`, `knife node edit`, and `knife role edit`, but with a single verb (and a single action). | | [knife environment](../../knife_environment/index) | Use the `knife environment` subcommand to manage environments within a single organization on the Chef Infra Server. | | [knife exec](../../knife_exec/index) | Use the `knife exec` subcommand to execute Ruby scripts in the context of a fully configured Chef Infra Client. Use this subcommand to run scripts that will only access Chef Infra Server one time (or otherwise very infrequently) or any time that an operation does not warrant full usage of the knife subcommand library. | | [knife list](../../knife_list/index) | Use the `knife list` subcommand to view a list of objects on the Chef Infra Server. This subcommand works similar to `knife cookbook list`, `knife data bag list`, `knife environment list`, `knife node list`, and `knife role list`, but with a single verb (and a single action). | | [knife node](../../knife_node/index) | Use the `knife node` subcommand to manage the nodes that exist on a Chef Infra Server. | | [knife raw](../../knife_raw/index) | Use the `knife raw` subcommand to send a REST request to an endpoint in the Chef Infra Server API. | | [knife recipe list](../../knife_recipe_list/index) | Use the `knife recipe list` subcommand to view all of the recipes that are on a Chef Infra Server. A regular expression can be used to limit the results to recipes that match a specific pattern. The regular expression must be within quotes and not be surrounded by forward slashes (/). | | [knife role](../../knife_role/index) | Use the `knife role` subcommand to manage the roles that are associated with one or more nodes on a Chef Infra Server. | | [knife search](../../knife_search/index) | Use the `knife search` subcommand to run a search query for information that is indexed on a Chef Infra Server. | | [knife serve](../../knife_serve/index) | Use the `knife serve` subcommand to run a persistent chef-zero against the local chef-repo. (chef-zero is a lightweight Chef Infra Server that runs in-memory on the local machine.) This is the same as running the Chef Infra Client executable with the `--local-mode` option. The `chef_repo_path` is located automatically and the Chef Infra Server will bind to the first available port between `8889` and `9999`. `knife serve` will print the URL for the local Chef Infra Server, so that it may be added to the config.rb file. | | [knife show](../../knife_show/index) | Use the `knife show` subcommand to view the details of one (or more) objects on the Chef Infra Server. This subcommand works similar to `knife cookbook show`, `knife data bag show`, `knife environment show`, `knife node show`, and `knife role show`, but with a single verb (and a single action). | | [knife ssh](../../knife_ssh/index) | Use the `knife ssh` subcommand to invoke SSH commands (in parallel) on a subset of nodes within an organization, based on the results of a [search query](/chef_search/) made to the Chef Infra Server. | | [knife ssl check](../../knife_ssl_check/index) | Use the `knife ssl check` subcommand to verify the SSL configuration for the Chef Infra Server or a location specified by a URL or URI. Invalid certificates will not be used by OpenSSL. When this command is run, the certificate files (`*.crt` and/or `*.pem`) that are located in the `/.chef/trusted_certs` directory are checked to see if they have valid X.509 certificate properties. A warning is returned when certificates do not have valid X.509 certificate properties or if the `/.chef/trusted_certs` directory does not contain any certificates. Warning When verification of a remote server’s SSL certificate is disabled, Chef Infra Client will issue a warning similar to “SSL validation of HTTPS requests is disabled. HTTPS connections are still encrypted, but Chef Infra Client is not able to detect forged replies or man-in-the-middle attacks.” To configure SSL for Chef Infra Client, set `ssl_verify_mode` to `:verify_peer` (recommended) **or** `verify_api_cert` to `true` in the client.rb file. | | [knife ssl fetch](../../knife_ssl_fetch/index) | Use the `knife ssl fetch` subcommand to copy SSL certificates from an HTTPS server to the `trusted_certs_dir` directory that is used by knife and Chef Infra Client to store trusted SSL certificates. When these certificates match the hostname of the remote server, running `knife ssl fetch` is the only step required to verify a remote server that is accessed by either knife or Chef Infra Client. Warning It is the user’s responsibility to verify the authenticity of every SSL certificate before downloading it to the `/.chef/trusted_certs` directory. knife will use any certificate in that directory as if it is a 100% trusted and authentic SSL certificate. knife will not be able to determine if any certificate in this directory has been tampered with, is forged, malicious, or otherwise harmful. Therefore it is essential that users take the proper steps before downloading certificates into this directory. | | [knife status](../../knife_status/index) | Use the `knife status` subcommand to display a brief summary of the nodes on a Chef Infra Server, including the time of the most recent successful Chef Infra Client run. | | [knife tag](../../knife_tag/index) | Use the `knife tag` subcommand to apply tags to nodes on a Chef Infra Server. | | [knife supermarket](../../knife_supermarket/index) | Use the `knife supermarket` subcommand to interact with cookbooks that are available in the [Chef Supermarket](https://supermarket.chef.io/). A user account is required for any community actions that write data to this site. The following arguments do not require a user account: `download`, `search`, `install`, and `list`. | | [knife upload](../../knife_upload/index) | Use the `knife upload` subcommand to upload data to the Chef Infra Server from the current working directory in the chef-repo. The following types of data may be uploaded with this subcommand: * Cookbooks * Data bags * Roles stored as JSON data * Environments stored as JSON data (Roles and environments stored as Ruby data will not be uploaded.) This subcommand is often used in conjunction with `knife diff`, which can be used to see exactly what changes will be uploaded, and then `knife download`, which does the opposite of `knife upload`. | | [knife user](../../knife_user/index) | Use the `knife user` subcommand to manage the list of users and their associated RSA public key-pairs. | | [knife xargs](../../knife_xargs/index) | Use the `knife xargs` subcommand to take patterns from standard input, download as JSON, run a command against the downloaded JSON, and then upload any changes. | ### Verb Subcommands knife includes a set of subcommands that are built around common verbs: `delete`, `deps`, `diff`, `download`, `edit`, `list`, `show`, `upload`, `xargs`. These subcommands allow knife to issue commands that interact with any object stored in the chef-repo or stored on the Chef Infra Server. Some important principles behind this group of subcommands includes: * A command that works with each object in the chef-repo. The subcommands specify the desired action (the “verb”), and then directory in which that object resides (`clients`, `cookbooks/`, `data_bags/`, `environments/`, `nodes`, `roles/`, and `users`). For example: `download cookbooks/` * A command that works with certain objects in the Chef Infra Server, including `acls`, `groups`, and `containers` * Uses the Chef Infra Server as if it were a file system, allowing the chef-repo on the Chef Infra Server to behave like a mirror of the chef-repo on the workstation. The Chef Infra Server will have the same objects as the local chef-repo. To make changes to the files on the Chef Infra Server, just download files from the Chef Infra Server or upload files from the chef-repo * The context from which a command is run matters. For example, when working in the `roles/` directory, knife will know what is being worked with. Enter `knife show base.json` and knife will return the base role from the Chef Infra Server. From the chef-repo root, enter `knife show roles/base.json` to get the same result * Parallel requests can be made to the Chef Infra Server and are configurable on a per-command basis ### Wildcard Search A wildcard matching pattern can be used for substring matches that replace zero (or more) characters. There are two types of wildcard patterns: * A question mark ("?") can be used to replace exactly one character (as long as that character is not the first character) * An asterisk ("*") can be used to replace any number of characters (including zero) Wildcard patterns must be escaped (using a backslash) so that the wildcard itself can reach the Chef Infra Server. If they are not escaped, the wildcard is expanded into the actual filenames and knife will not know the wildcard was intended to be used. For example, if the Chef Infra Server has data bags named `aardvarks`, `anagrams`, and `arp_tables`, but the local file system only has `aardvarks` and `anagrams`, escaping vs. not escaping the wildcard pattern will yield different results: ``` knife list data_bags/a\* ``` asks the Chef Infra Server for everything starting with the letter “a” and will return: ``` aardvarks/ anagrams/ arp_tables/ ``` But, the following: ``` knife list data_bags/a* ``` will return: ``` aardvarks/ anagrams/ ``` Which is the same as entering: ``` knife list data_bags/aardvarks data_bags/anagrams ``` to return: ``` aardvarks/ anagrams/ ``` Knife Plug-ins -------------- Knife functionality can be extended with plugins, which work the same as built-in subcommands (including common options). Knife plugins have been written to interact with common cloud providers, to simplify common Chef tasks, and to aid in Chef workflows. ### Plugin Installation Knife plugins ship as RubyGems and are installed into the Chef Workstation installation using the `chef` command: ``` chef gem install PLUGIN_NAME ``` Post installation you will also need to rehash the list of knife commands by running: ``` knife rehash ``` ### Chef Maintained Knife Plugins Chef maintains the following plugins which ship with Chef Workstation: * `knife-acl` * `knife-azure` * `knife-ec2` * `knife-google` * `knife-lpar` * `knife-opc` * `knife-openstack` * `knife-rackspace` * `knife-reporting` * `knife-vcenter` * `knife-windows` ### Community Knife Plugins Knife plugins written by Chef community members can be found on Supermarket under [Knife Plugins](https://supermarket.chef.io/tools?type=knife_plugin). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife/Knife Common Options ==================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_options.md) The following options can be run with all knife subcommands and plug-ins: `-c CONFIG_FILE`, `--config CONFIG_FILE` The configuration file to use. For example, when knife is run from a node that is configured to be managed by the Chef Infra Server, this option is used to allow knife to use the same credentials as Chef Infra Client looks when communicating with the Chef Infra Server. `--chef-zero-host HOST` The host to start Chef Infra Zero on. Chef Infra Zero is a lightweight, in-memory Chef Infra Server. `--chef-zero-port PORT` The port (or port range) to start chef-zero on. Port ranges l `1000,1010` or `8889-9999` will try all given ports until one works. `-d`, `--disable-editing` Prevent the $EDITOR from being opened and accept data as-is. `--defaults` Cause knife to use the default value instead of asking a user to provide one. `-e EDITOR`, `--editor EDITOR` The $EDITOR that is used for all interactive commands. `-E ENVIRONMENT`, `--environment ENVIRONMENT` The name of the environment. When this option is added to a command, the command will run only against the named environment. This option is ignored during search queries made using the `knife search` subcommand. `-F FORMAT`, `--format FORMAT` The output format: `summary` (default), `text`, `json`, `yaml`, `pp`. `-h`, `--help` Show help for the command. `-k KEY`, `--key KEY` The USER.pem file that knife uses to sign requests made by the API client to the Chef Infra Server. `--[no-]color` View colored output. `--[no-]fips` Allows OpenSSL to enforce FIPS-validated security during a C Infra Client run. `--print-after` Show data after a destructive operation. `-s URL`, `--server-url URL` The URL for the Chef Infra Server. `-u USER`, `--user USER` The user name used by knife to sign requests made by the API client to the Chef Infra Server. Authentication fails if the user name does not match the private key. `-v`, `--version` The Chef Infra Client version. `-V`, `--verbose` Set for more verbose outputs. Use `-VV` for much more verbose outputs. Use `-VVV` for maximum verbosity, which may provide more information than is actually helpful. `-y`, `--yes` Respond to all confirmation prompts with “Yes”. `-z`, `--local-mode` Run Chef Infra Client looks in local mode. This allows all commands that work against the Chef Infra Server to also work against the local chef-repo. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_options/Knife Azurerm ============= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_azurerm.md) Knife Azure Overview -------------------- Microsoft Azure is a cloud hosting platform from Microsoft that provides virtual machines for Linux and Windows Server, cloud and database services, and more. Use the `knife azure` subcommand to manage API-driven cloud servers hosted by Microsoft Azure. Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. `knife-azure` version 4.0 and later no longer support the legacy `knife azure` commands that utilized the now deprecated Azure ASM APIs. ### Configuration The `knife azurem` requires setting up a service principal for authentication and permissioning. For setting up a service principal from the command line, see [Create service principal with PowerShell / Azure CLI 2.0](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal). Note When creating your user following the example in the Microsoft documentation, change -o Reader to -o Contributor, otherwise you will not be able to spin up or delete machines. After creating the service principal, you will have the values: * client id (GUID) * client secret(string) * tenant id (GUID). Put the following in your knife.rb ``` knife[:azure_tenant_id] # found via: tenantId=$(azure account show -s <subscriptionId> --json | jq -r '.[0].tenantId') knife[:azure_subscription_id] # found via: <subscriptionId> knife[:azure_client_id] # appId=$(azure ad app show --search <principleappcreated> --json | jq -r '.[0].appId') knife[:azure_client_secret] # password you set at the beginning ``` Microsoft Azure encourages the use of Azure CLI 2.0. If you are still using [azure-xplat-cli](https://github.com/Azure/azure-xplat-cli) _then run `azure login` and skip creating the service principal. ### Knife Azurerm Commands #### server create Use the `server create` argument to provision a new server in Azure and then perform a Chef bootstrap. **Syntax** This argument has the following syntax: ``` knife azurerm server create (options) ``` **Options** This argument has the following options: `-a`, `--azure-storage-account NAME` Required for advanced server-create option. A name for the storage account that is unique within Windows Azure. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. This name is the DNS prefix name and can be used to access blobs, queues, and tables in the storage account. For example: <http://ServiceName.blob.core.windows.net/mycontainer/ `--azure-availability-set NAME` Name of availability set to add virtual machine into. `--azure-extension-client-config CLIENT_PATH` Path to a client.rb file for use by the bootstrapped node. `--azure-image-os-type OSTYPE` Specifies the image OS Type for which server needs to be created. Accepted values: `ubuntu`, `centos`, `rhel`, `debian`, `windows`. `--azure-image-reference-offer OFFER` Specifies the offer of the image used to create the virtual machine. eg. CentOS, UbuntuServer, WindowsServer. `--azure-image-reference-publisher PUBLISHER_NAME` Specifies the publisher of the image used to create the virtual machine. eg. OpenLogic Canonical, MicrosoftWindowsServer. `--azure-image-reference-sku SKU` Specifies the SKU of the image used to create the virtual machine. `--azure-image-reference-version VERSION` Specifies the version of the image used to create the virtual machine. Default: ‘latest’. `--azure-resource-group-name RESOURCE_GROUP_NAME` The Resource Group name. `--azure-storage-account-type TYPE` One of the following account types (case-sensitive): `Standard_LRS` (Standard Locally-redundant storage); `Standard_ZRS` (Standard Zone-redundant storage); `Standard_GRS` (Standard Geo-redundant storage); `Standard_RAGRS` (Standard Read access geo-redundant storage); `Premium_LRS` (Premium Locally-redundant storage). `--azure-vm-name NAME` Required. Specifies the name for the virtual machine. The name must be unique within the ResourceGroup. Maximum length: 15 characters. `--azure-vm-size SIZE` Size of virtual machine. Values: `ExtraSmall`, `Small`, `Medium`, `Large`, `ExtraLarge`. `--azure-vnet-name VNET_NAME` Specifies the virtual network name. This may be the name of an existing vnet present under the given resource group or this may be the name of a new vnet to be added in the given resource group. If not specified then azure-vm-name will be taken as the default name for vnet name as well. Along with this option, the `azure-vnet-subnet-name` option can also be specified or skipped. `--azure-vnet-subnet-name VNET_SUBNET_NAME` Specifies the virtual network subnet name. Must be specified only with `azure-vnet-name` option. This may be the name of an existing subnet present under the given virtual network or this may be the name of a new subnet to be added virtual network. If not specified then `azure-vm-name` will be taken as name for subnet name as well. Note: `GatewaySubnet` cannot be used as the name for the `--azure-vnet-subnet-name` option. `--bootstrap-proxy PROXY_URL` The proxy server for the node being bootstrapped. `--bootstrap-version VERSION` The version of Chef to install. `-c`, `--config CONFIG` The configuration file to use. `--cert-passphrase PASSWORD` SSL Certificate Password. `--cert-path PATH` SSL Certificate Path. `--chef-daemon-interval INTERVAL` It specifies the frequency (in minutes) at which the chef-service runs. Pass 0 if you don’t want the chef-service to be installed on the target machine. `--chef-zero-host HOST` Host for starting chef-zero. `--chef-zero-port PORT` Port (or port range) to start chef-zero on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works. `--[no-]color` Use colored output. Default: `enabled` `--config-option OPTION=VALUE` Override a single configuration option. `-d`, `--disable-editing` Accept the data without opening the editor. `--daemon DAEMON` Configures the Chef Infra Client service for unattended execution. Requires `--bootstrap-protocol` to be `cloud-api` and the node platform to be `Windows`. Options: ‘none’ or ‘service’ or ‘task’. ‘none’ - Currently prevents the Chef Infra Client service from being configured as a service. ‘service’ - Configures Chef Infra Client to run automatically in the background as a service. ‘task’ - Configures Chef Infra Client to run automatically in the background as a scheduled task. `--defaults` Accept default values for all questions `-e`, `--editor EDITOR` Set the editor to use for interactive commands `-E`, `--environment ENVIRONMENT` Set the Chef environment (except for in searches, where this will be flagrantly ignored) `--extended-logs` It shows chef convergence logs in detail. `-F`, `--format FORMAT` Which format to use for output `--[no-]fips` Enable fips mode `-h`, `--help` Show this message `-j`, `--json-attributes JSON` A JSON string to be added to the first run of Chef Infra Client `--[no-]listen` Whether a local mode (-z) server binds to a port `-k`, `--key KEY` API Client Key `-m LOCATION`, `--azure-service-location` Required if not using an Affinity Group. Specifies the geographic location - the name of the data center location that is valid for your subscription. Eg: westus, eastus, eastasia, southeastasia, northeurope, westeurope `-N`, `--node-name NAME` The Chef node name for your new node `-o DISKNAME`, `--azure-os-disk-name` Specifies the friendly name of the disk containing the guest OS image in the image repository. `--node-ssl-verify-mode [peer|none]` Whether or not to verify the SSL cert for all HTTPS requests. `--[no-]node-verify-api-cert` Verify the SSL cert for HTTPS requests to the Chef Infra Server API. `--ohai-hints HINT_OPTIONS` Hint option names to be set in Ohai configuration the target node. Values: `vm_name`, `public_fqdn` and platform. User can pass any comma separated combination of these values like `vm_name,public_fqdn`. Default: `default` which corresponds to supported values list mentioned here. `--print-after` Show the data after a destructive operation `--profile PROFILE` The credentials profile to select `-r`, `--run-list RUN_LIST` Comma separated list of roles/recipes to apply `-s`, `--secret` The secret key to use to encrypt data bag item values. Can also be defaulted in your config with the key ‘secret’ `--secret-file SECRET_FILE` A file containing the secret key to use to encrypt data bag item values. Can also be defaulted in your config with the key ‘secret_file’ `--server-count COUNT` Number of servers to create with same configuration. Maximum: 5. Default: 1. `--server-url URL` Chef Infra Server URL `--ssh-password PASSWORD` The ssh password `--ssh-port PORT` The ssh port. Default: 22. `--ssh-public-key FILENAME` It is the ssh-rsa public key path. Specify either `ssh-password` or `ssh-public-key`. `--ssh-user USERNAME` The ssh username `-t`, `--tcp-endpoints PORT_LIST` Comma-separated list of TCP ports to open e.g. ‘80,433’ `--thumbprint THUMBPRINT` The thumbprint of the ssl certificate `-u`, `--user USER` API Client Username `-v`, `--version` Show Chef version `-V`, `--verbose` More verbose output. Use twice for max verbosity. `-P`, `--winrm-password PASSWORD` The WinRM password `-x`, `--winrm-user USERNAME` The WinRM username `-y`, `--yes` Say yes to all prompts for confirmation `-z`, `--local-mode` Point knife commands at local repository instead of server knife azurerm server delete SERVER [SERVER] (options) #### server delete Use the `server delete` argument to delete existing ARM servers configured in the Azure account. **Syntax** This argument has the following syntax: ``` knife azurerm server delete (options) ``` **Options** This argument has the following options: `-c`, `--config CONFIG` The configuration file to use. `--chef-zero-host HOST` Host for starting chef-zero. `--chef-zero-port PORT` Port (or port range) to start chef-zero on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works. `--[no-]color` Use colored output, defaults to enabled. `--config-option OPTION=VALUE` Override a single configuration option. `-d`, `--disable-editing` Accept the data without opening the editor. `--defaults` Accept default values for all questions. `--delete-resource-group` Deletes corresponding resource group along with VirtualMachine. `-e`, `--editor EDITOR` Set the editor to use for interactive commands. `-E`, `--environment ENVIRONMENT` Set the Chef environment, except for use in searching. `-F`, `--format FORMAT` Which format to use for output. `--[no-]fips` Enable fips mode. `-h`, `--help` Show the help message `-k`, `--key KEY` API Client Key. `--[no-]listen` Whether a local mode (-z) server binds to a port. `-N`, `--node-name NAME` The unique identifier of the node and client to delete, if it differs from the server name. Only has meaning when used with the ‘–purge’ option. `--print-after` Show the data after a destructive operation. `--profile PROFILE` The credentials profile to select. `-P`, `--purge` Destroy corresponding node and client on the ChefServer, in addition to destroying the Windows Azure node itself. Assumes node and client have the same name as the server (if not, add the ‘–node-name’ option). `-r RESOURCE_GROUP_NAME`, `--azure-resource-group-name` The Resource Group name. `-s`, `--server-url URL` Chef Infra Server URL. `-u`, `--user USER` API Client Username `-v`, `--version` Show chef version `-V`, `--verbose` More verbose output. Use twice for maximum verbosity. `-y`, `--yes` Say yes to all prompts for confirmation. `-z`, `--local-mode` Point knife commands at local repository instead of at the server. #### server list Use the `server list` argument to output a list of all ARM servers–including those not managed by the Chef server—in the Azure account. **Syntax** This argument has the following syntax: ``` knife azurerm server list (options) ``` **Options** This argument has the following options: `-c`, `--config CONFIG` The configuration file to use. `--chef-zero-host HOST` Host for starting chef-zero. `--chef-zero-port PORT` Port (or port range) to start chef-zero on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works. `--[no-]color` Use colored output, defaults to enabled. `--config-option OPTION=VALUE` Override a single configuration option. `-d`, `--disable-editing` Accept the data without opening the editor. `--defaults` Accept default values for all questions. `-e`, `--editor EDITOR` Set the editor to use for interactive commands. `-E`, `--environment ENVIRONMENT` Set the Chef environment, except for use in searching. `-F`, `--format FORMAT` Which format to use for output. `--[no-]fips` Enable fips mode. `-h`, `--help` Show the help message `-k`, `--key KEY` API Client Key. `--[no-]listen` Whether a local mode (-z) server binds to a port. `--print-after` Show the data after a destructive operation. `--profile PROFILE` The credentials profile to select. `-r RESOURCE_GROUP_NAME`, `--azure-resource-group-name` The Resource Group name. `-s`, `--server-url URL` Chef Infra Server URL. `-u`, `--user USER` API Client Username `-v`, `--version` Show chef version `-V`, `--verbose` More verbose output. Use twice for maximum verbosity. `-y`, `--yes` Say yes to all prompts for confirmation. `-z`, `--local-mode` Point knife commands at local repository instead of at the server. #### server show Use the `server show` argument to output the details of an ARM server in the Azure account. **Syntax** This argument has the following syntax: ``` knife azurerm server show (options) ``` **Options** This argument has the following options: `-c`, `--config CONFIG` The configuration file to use. `--chef-zero-host HOST` Host for starting chef-zero. `--chef-zero-port PORT` Port (or port range) to start chef-zero on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works. `--[no-]color` Use colored output, defaults to enabled. `--config-option OPTION=VALUE` Override a single configuration option. `-d`, `--disable-editing` Accept the data without opening the editor. `--defaults` Accept default values for all questions. `-e`, `--editor EDITOR` Set the editor to use for interactive commands. `-E`, `--environment ENVIRONMENT` Set the Chef environment, except for use in searching. `-F`, `--format FORMAT` Which format to use for output. `--[no-]fips` Enable fips mode. `-h`, `--help` Show the help message `-k`, `--key KEY` API Client Key. `--[no-]listen` Whether a local mode (-z) server binds to a port. `--print-after` Show the data after a destructive operation. `--profile PROFILE` The credentials profile to select. `-r RESOURCE_GROUP_NAME`, `--azure-resource-group-name` The Resource Group name. `-s`, `--server-url URL` Chef Infra Server URL. `-u`, `--user USER` API Client Username `-v`, `--version` Show chef version `-V`, `--verbose` More verbose output. Use twice for maximum verbosity. `-y`, `--yes` Say yes to all prompts for confirmation. `-z`, `--local-mode` Point knife commands at local repository instead of at the server. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_azurerm/knife configure =============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_configure.md) Use the `knife configure` subcommand to create the [client.rb](../../config_rb_client/index) and credential files so that they can be distributed to workstations and nodes. Syntax ------ This subcommand has the following syntax when creating a credentials file: ``` knife configure (options) ``` and the following syntax when creating a client.rb file: ``` knife configure client DIRECTORY ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options for use when configuring a config.rb file: `--admin-client-name NAME` The name of the client, typically the name of the admin client. `--admin-client-key PATH` The path to the private key used by the client, typically a file named `admin.pem`. `-i`, `--initial` Create a API client, typically an administrator client on a freshly-installed Chef Infra Server. `-r REPO`, `--repository REPO` The path to the chef-repo. `--validation-client-name NAME` The name of the validation client, typically a client named chef-validator. `--validation-key PATH` The path to the validation key used by the client, typically a file named chef-validator.pem. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Configure credentials file** ``` knife configure ``` **Configure client.rb** ``` knife configure client '/directory' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_configure/knife cookbook ============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_cookbook.md) A cookbook is the fundamental unit of configuration and policy distribution in Chef Infra. A cookbook defines a scenario and contains everything that is required to support that scenario: * Recipes that specify which Chef Infra built-in resources to use, as well as the order in which they are to be applied * Attribute values, which allow environment-based configurations such as `dev` or `prodution`. * Custom Resources for extending Chef Infra beyond the built-in resources. * Files and Templates for distributing information to systems. * Custom Ohai Plugins for extending system configuration collection beyond the Ohai defaults. * The `metadata.rb` file, which describes the cookbook itself and any dependencies it may have. Use the `knife cookbook` subcommand to interact with cookbooks that are located on the Chef Infra Server or the local chef-repo. Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. bulk delete ----------- Use the `bulk delete` argument to delete cookbook files that match a pattern defined by a regular expression. The regular expression must be within quotes and not be surrounded by forward slashes (/). ### Syntax This argument has the following syntax: ``` knife cookbook bulk delete REGEX (options) ``` ### Options This argument has the following options: `-p`, `--purge` Entirely remove a cookbook (or cookbook version) from the Chef Infra Server. Use this action carefully because only one copy of any single file is stored on the Chef Infra Server. Consequently, purging a cookbook disables any other cookbook that references one or more files from the cookbook that has been purged. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Bulk delete many cookbooks** Use a regular expression to define the pattern used to bulk delete cookbooks: ``` knife cookbook bulk delete "^[0-9]{3}$" -p ``` delete ------ Use the `delete` argument to delete a specified cookbook or cookbook version on the Chef Infra Server (and not locally). ### Syntax This argument has the following syntax: ``` knife cookbook delete COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `-a`, `--all` Delete all cookbooks (and cookbook versions). `COOKBOOK_VERSION` The version of a cookbook to be deleted. If a cookbook has only one version, this option does not need to be specified. If a cookbook has more than one version and this option is not specified, knife prompts for a version. `-p`, `--purge` Entirely remove a cookbook (or cookbook version) from the Chef Infra Server. Use this action carefully because only one copy of any single file is stored on the Chef Infra Server. Consequently, purging a cookbook disables any other cookbook that references one or more files from the cookbook that has been purged. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Delete a cookbook** ``` knife cookbook delete cookbook_name version ``` For example: ``` knife cookbook delete smartmon 0.8 ``` Type `Y` to confirm a deletion. download -------- Use the `download` argument to download a cookbook from the Chef Infra Server to the current working directory. ### Syntax This argument has the following syntax: ``` knife cookbook download COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `-d DOWNLOAD_DIRECTORY`, `--dir DOWNLOAD_DIRECTORY` The directory in which cookbooks are located. `-f`, `--force` Overwrite an existing directory. `-N`, `--latest` Download the most recent version of a cookbook. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Download a cookbook** To download a cookbook named `smartmon`, enter: ``` knife cookbook download smartmon ``` list ---- Use the `list` argument to view a list of cookbooks that are currently available on the Chef Infra Server. The list will contain only the most recent version for each cookbook by default. ### Syntax This argument has the following syntax: ``` knife cookbook list (options) ``` ### Options This argument has the following options: `-a`, `--all` Return all available versions for every cookbook. `-w`, `--with-uri` Show the corresponding URIs. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **View a list of cookbooks** To view a list of cookbooks: ``` knife cookbook list ``` metadata -------- Use the `metadata` argument to generate the metadata for one or more cookbooks. ### Syntax This argument has the following syntax: ``` knife cookbook metadata (options) ``` ### Options This argument has the following options: `-a`, `--all` Generate metadata for all cookbooks. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Generate metadata** ``` knife cookbook metadata -a ``` metadata from file ------------------ Use the `metadata from file` argument to load the metadata for a cookbook from a file. ### Syntax This argument has the following syntax: ``` knife cookbook metadata from file FILE ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **View metadata** ``` knife cookbook metadata from file /path/to/file ``` show ---- Use the `show` argument to view information about a cookbook, parts of a cookbook (attributes, definitions, files, libraries, providers, recipes, resources, and templates), or a file that is associated with a cookbook (including attributes such as checksum or specificity). ### Syntax This argument has the following syntax: ``` knife cookbook show COOKBOOK_NAME [COOKBOOK_VERSION] [PART...] [FILE_NAME] (options) ``` ### Options This argument has the following options: `COOKBOOK_VERSION` The version of a cookbook to be shown. If a cookbook has only one version, this option does not need to be specified. If a cookbook has more than one version and this option is not specified, a list of cookbook versions is returned. `-f FQDN`, `--fqdn FQDN` The FQDN of the host. `FILE_NAME` The name of a file that is associated with a cookbook. `-p PLATFORM`, `--platform PLATFORM` The platform for which a cookbook is designed. `PART` The part of the cookbook to show: `attributes`, `definitions`, `files`, `libraries`, `providers`, `recipes`, `resources`, or `templates`. More than one part can be specified. `-V PLATFORM_VERSION`, `--platform-version PLATFORM_VERSION` The version of the platform. `-w`, `--with-uri` Show the corresponding URIs. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Show cookbook data** To get the list of available versions of a cookbook named `getting-started`, enter: ``` knife cookbook show getting-started ``` to return something like: ``` getting-started 0.3.0 0.2.0 ``` **Show cookbook versions** To show a list of data about a cookbook using the name of the cookbook and the version, enter: ``` knife cookbook show getting-started 0.3.0 ``` to return something like: ``` attributes: checksum: fa0fc4abf3f6787aeb5c3c5c35de667c name: default.rb path: attributes/default.rb specificity: default url: https://somelongurlhere.com chef_type: cookbook_version cookbook_name: getting-started definitions: [] files: [] frozen?: false json_class: Chef::CookbookVersion libraries: [] ``` **Show a cookbook version** To only view data about templates, enter: ``` knife cookbook show getting-started 0.3.0 templates ``` to return something like: ``` checksum: a29d6f254577b830091f140c3a78b1fe name: chef-getting-started.txt.erb path: templates/default/chef-getting-started.txt.erb specificity: default url: https://someurlhere.com ``` **Show cookbook data as JSON** To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife cookbook show devops -F json ``` Other formats available include `text`, `yaml`, and `pp`. test ---- Use the `test` argument to test a cookbook for syntax errors. This argument uses Ruby syntax checking to verify every file in a cookbook that ends in .rb and Embedded Ruby (ERB). This argument will respect chefignore files when determining which cookbooks to test for syntax errors. Warning This feature is deprecated in favor of [Cookstyle](../cookstyle/index) and [ChefSpec](../chefspec/index) ### Syntax This argument has the following syntax: ``` knife cookbook test COOKBOOK_NAME (options) ``` ### Options This argument has the following options: `-a`, `--all` Test all cookbooks. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Test a cookbook** ``` knife cookbook test cookbook_name ``` upload ------ Use the `upload` argument to upload one or more cookbooks (and any files that are associated with those cookbooks) from a local repository to the Chef Infra Server. Only files that do not already exist on the Chef Infra Server will be uploaded. Note Use a chefignore file to prevent the upload of specific files and file types, such as temporary files or files placed in folders by version control systems. The chefignore file must be located in the root of the cookbook repository and must use rules similar to filename globbing (as defined by the Ruby `File.fnmatch` syntax). Note Empty directories are not uploaded to the Chef Infra Server. To upload an empty directory, create a “dot” file—e.g. `.keep`—in that directory to ensure that the directory itself is not empty. ### Syntax This argument has the following syntax: ``` knife cookbook upload [COOKBOOK_NAME...] (options) ``` ### Options This argument has the following options: `-a`, `--all` Upload all cookbooks. `--concurrency` The number of allowed concurrent connections. Default: `10`. `-d`, `--include-dependencies` Ensure that when a cookbook has a dependency on one (or more) cookbooks, those cookbooks are also uploaded. `-E ENVIRONMENT`, `--environment ENVIRONMENT` Use to set the environment version dependency to the cookbook version being uploaded. `--force` Update a cookbook even if the `--freeze` flag has been set. `--freeze` Require changes to a cookbook be included as a new version. Only the `--force` option can override this setting. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Upload a cookbook** ``` knife cookbook upload cookbook_name ``` **Freeze a cookbook** To upload a cookbook, and then prevent other users from being able to make changes to it, enter: ``` knife cookbook upload redis --freeze ``` to return something like: ``` Uploading redis... Upload completed ``` If a cookbook is frozen and the `--force` option is not specified, knife will return an error message similar to the following: ``` Uploading redis... ERROR: Version 0.1.6 of cookbook redis is frozen. Use --force to override. ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_cookbook/knife client ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_client.md) Use the `knife client` subcommand to manage an API client list and their associated RSA public key-pairs. This allows authentication requests to be made to the Chef Infra Server by any entity that uses the Chef Infra Server API, such as Chef Infra Client and knife. Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. bulk delete ----------- Use the `bulk delete` argument to delete any API client that matches a pattern defined by a regular expression. The regular expression must be within quotes and not be surrounded by forward slashes (`/`). ### Syntax This argument has the following syntax: ``` knife client bulk delete REGEX ``` ### Options This argument has the following options: `-D`, `--delete-validators` Force the deletion of the client when it is also a chef-validator. ### Examples None. create ------ Use the `create` argument to create a new API client. This process will generate an RSA key pair for the named API client. The public key will be stored on the Chef Infra Server and the private key will be displayed on `STDOUT` or written to a named file. . For Chef Infra Client, the private key should be copied to the system as `/etc/chef/client.pem`. . For knife, the private key is typically copied to `~/.chef/client_name.pem` and referenced in the config.rb configuration file. ### Syntax This argument has the following syntax: ``` knife client create CLIENT_NAME (options) ``` ### Options This argument has the following options: `-f FILE`, `--file FILE` Save a private key to the specified file name. `-k`, `--prevent-keygen` Create a user without a public key. This key may be managed later by using the `knife user key` subcommands. Note This option is valid only with Chef Infra Server API, version 1.0, which was released with Chef Server 12.1. If this option or the `--user-key` option are not passed in the command, the Chef Infra Server will create a user with a public key named `default` and will return the private key. For the Chef Server versions earlier than 12.1, this option will not work; a public key is always generated unless `--user-key` is passed in the command. `-p FILE`, `--public-key FILE` The path to a file that contains the public key. This option may not be passed in the same command with `--prevent-keygen`. When using Chef a default key is generated if this option is not passed in the command. For Chef Server version 12.x, see the `--prevent-keygen` option. `--validator` Create the client as the chef-validator. Default value: `true`. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create an admin client** To create a Chef Infra Client that can access the Chef Infra Server API as an administrator—sometimes referred to as an “API Chef Infra Client”—with the name “exampleorg” and save its private key to a file, enter: ``` knife client create exampleorg -a -f "/etc/chef/client.pem" ``` delete ------ Use the `delete` argument to delete a registered API client. If using Chef Client 12.17 or later, you can delete multiple clients using this subcommand. ### Syntax This argument has the following syntax: ``` knife client delete CLIENT_NAME ``` ### Options This argument has the following options: `-D`, `--delete-validators` Force the deletion of the client when it is also a chef-validator. ### Examples The following examples show how to use this knife subcommand: **Delete a client** To delete a client with the name “client_foo”, enter: ``` knife client delete client_foo ``` Type `Y` to confirm a deletion. edit ---- Use the `edit` argument to edit the details of a registered API client. When this argument is run, knife will open $EDITOR to enable editing of the `admin` attribute. (None of the other attributes should be changed using this argument.) When finished, knife will update the Chef Infra Server with those changes. ### Syntax This argument has the following syntax: ``` knife client edit CLIENT_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Edit a client** To edit a client with the name “exampleorg”, enter: ``` knife client edit exampleorg ``` key create ---------- Use the `key create` argument to create a public key. ### Syntax This argument has the following syntax: ``` knife client key create CLIENT_NAME (options) ``` ### Options This argument has the following options: `-e DATE`, `--expiration-date DATE` The expiration date for the public key, specified as an ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. If this option is not specified, the public key will not have an expiration date. For example: `2013-12-24T21:00:00Z`. `-f FILE`, `--file FILE` Save a private key to the specified file name. If the `--public-key` option is not specified the Chef Infra Server will generate a private key. `-k NAME`, `--key-name NAME` The name of the public key. `-p FILE_NAME`, `--public-key FILE_NAME` The path to a file that contains the public key. If this option is not specified, and only if `--key-name` is specified, the Chef Infra Server will generate a public/private key pair. ### Examples None. key delete ---------- Use the `key delete` argument to delete a public key. ### Syntax This argument has the following syntax: ``` knife client key delete CLIENT_NAME KEY_NAME ``` ### Examples None. key edit -------- Use the `key edit` argument to modify or rename a public key. ### Syntax This argument has the following syntax: ``` knife client key edit CLIENT_NAME KEY_NAME (options) ``` ### Options This argument has the following options: `-c`, `--create-key` Generate a new public/private key pair and replace an existing public key with the newly-generated public key. To replace the public key with an existing public key, use `--public-key` instead. `-e DATE`, `--expiration-date DATE` The expiration date for the public key, specified as an ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. If this option is not specified, the public key will not have an expiration date. For example: `2013-12-24T21:00:00Z`. `-f FILE`, `--file FILE` Save a private key to the specified file name. If the `--public-key` option is not specified the Chef Infra Server will generate a private key. `-k NAME`, `--key-name NAME` The name of the public key. `-p FILE_NAME`, `--public-key FILE_NAME` The path to a file that contains the public key. If this option is not specified, and only if `--key-name` is specified, the Chef Infra Server will generate a public/private key pair. ### Examples None. key list -------- Use the `key list` argument to view a list of public keys for the named client. ### Syntax This argument has the following syntax: ``` knife client key list CLIENT_NAME (options) ``` ### Options This argument has the following options: `-e`, `--only-expired` Show a list of public keys that have expired. `-n`, `--only-non-expired` Show a list of public keys that have not expired. `-w`, `--with-details` Show a list of public keys, including URIs and expiration status. ### Examples None. key show -------- Use the `key show` argument to view details for a specific public key. ### Syntax This argument has the following syntax: ``` knife client key show CLIENT_NAME KEY_NAME ``` ### Examples None. list ---- Use the `list` argument to view a list of registered API client. ### Syntax This argument has the following syntax: ``` knife client list (options) ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### Examples The following examples show how to use this knife subcommand: **View a list of clients** To verify the API client list for the Chef Infra Server, enter: ``` knife client list ``` to return something similar to: ``` exampleorg i-12345678 rs-123456 ``` To verify that an API client can authenticate to the Chef Infra Server correctly, try getting a list of clients using `-u` and `-k` options to specify its name and private key: ``` knife client list -u ORGNAME -k .chef/ORGNAME.pem ``` reregister ---------- Use the `reregister` argument to regenerate an RSA key pair for an API client. The public key will be stored on the Chef Infra Server and the private key will be displayed on `STDOUT` or written to a named file. Note Running this argument will invalidate the previous RSA key pair, making it unusable during authentication to the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife client reregister CLIENT_NAME (options) ``` ### Options This argument has the following options: `-f FILE_NAME`, `--file FILE_NAME` Save a private key to the specified file name. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Re-register a client** To re-register the RSA key pair for a client named “testclient” and save it to a file named “rsa_key”, enter: ``` knife client reregister testclient -f rsa_key ``` show ---- Use the `show` argument to show the details of an API client. ### Syntax This argument has the following syntax: ``` knife client show CLIENT_NAME (options) ``` ### Options This argument has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. ### Examples The following examples show how to use this knife subcommand: **Show clients** To view a client named “testclient”, enter: ``` knife client show testclient ``` to return something like: ``` admin: false chef_type: client json_class: Chef::ApiClient name: testclient public_key: ``` To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife client show devops -F json ``` Other formats available include `text`, `yaml`, and `pp`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_client/knife bootstrap =============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_bootstrap.md) A node is any physical, virtual, or cloud device that is configured and maintained by an instance of Chef Infra Client. Bootstrapping installs Chef Infra Client on a target system so that it can run as a client and sets the node up to communicate with a Chef Infra Server. There are two ways to do this: * Run the `knife bootstrap` command from a workstation. * Perform an unattended install to bootstrap from the node itself, without requiring SSH or WinRM connectivity. Use the `knife bootstrap` subcommand to run a bootstrap operation that installs Chef Infra Client on the target system. The bootstrap operation must specify the IP address or FQDN of the target system. **Considerations:** * Knife will copy the contents of the `~/.chef/client.d` directory on your local workstation to the `client.d` directory on the device being bootstrapped with the `knife bootstrap` command. You can also set the `client_d_dir` option in the `config.rb` file to point to an arbitrary directory instead of `~/.chef/client.d`, and the contents of that directory will be copied to the device being bootstrapped. All config files inside the `client.d` directory will get copied into the `/etc/chef/client.d` directory on the system being bootstrapped. * SSL certificates from an on-premises Chef Infra Server can be copied to the `/trusted_certs_dir` directory on your local workstation automatically by running [knife ssl fetch](../knife_ssl_fetch/index). These certificates are used during `knife` operations to communicate with the Chef Infra Server. * By default, `knife bootstrap` will attempt to use `ssh` to connect to the target node. Use the `-o` to specify a different protocol, such as `winrm` for windows nodes. Syntax ------ This subcommand has the following syntax: ``` knife bootstrap FQDN_or_IP_ADDRESS (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. ### General Connection Options `-U USERNAME`, `--connection-user USERNAME` Authenticate to the target host with this user account. `-P PASSWORD`, `--connection-password PASSWORD` Authenticate to the target host with this password." `-p PORT`, `--connection-port PORT` The port on the target node to connect to." `-o PROTOCOL`, `--connection-protocol PROTOCOL` The protocol to use to connect to the target node. Options are `ssh` or `winrm`. `ssh` is default. `-W SECONDS`, `--max-wait SECONDS` The maximum time to wait for the initial connection to be established. `--session-timeout SECONDS` The number of seconds to wait for each connection operation to be acknowledged while running bootstrap. ### WinRM Connection Options `--winrm-ssl-peer-fingerprint FINGERPRINT` SSL certificate fingerprint expected from the target. `-f CA_TRUST_PATH`, `--ca-trust-file CA_TRUST_PATH` The Certificate Authority (CA) trust file used for SSL transport `--winrm-no-verify-cert` Do not verify the SSL certificate of the target node for WinRM. `--winrm-ssl` Use SSL in the WinRM connection. `-w AUTH-METHOD`, `--winrm-auth-method AUTH-METHOD` The WinRM authentication method to use. `--winrm-basic-auth-only` For WinRM basic authentication when using the ‘ssl’ auth method. `-R KERBEROS_REALM`, `--kerberos-realm KERBEROS_REALM` The Kerberos realm used for authentication. `-S KERBEROS_SERVICE`, `--kerberos-service KERBEROS_SERVICE` The Kerberos service used for authentication. ### SSH Connection Options `-G GATEWAY`, `--ssh-gateway GATEWAY` The SSH tunnel or gateway that is used to run a bootstrap action on a machine that is not accessible from the workstation. `--ssh-gateway-identity SSH_GATEWAY_IDENTITY` The SSH identity file used for gateway authentication. `-A`, `--ssh-forward-agent` Enable SSH agent forwarding. `-i IDENTITY_FILE`, `--ssh-identity-file IDENTITY_FILE` The SSH identity file used for authentication. Key-based authentication is recommended. `ssh_verify_host_key`, `--ssh-verify-host-key VALUE` Verify host key. Default is ‘always’ ### Chef Installation Options `--bootstrap-version VERSION` The version of Chef Infra Client to install. `--bootstrap-install-command COMMAND` Execute a custom installation command sequence for Chef Infra Client. This option may not be used in the same command with `--bootstrap-curl-options` or `--bootstrap-wget-options`. `--bootstrap-curl-options OPTIONS` Arbitrary options to be added to the bootstrap command when using cURL. This option may not be used in the same command with `--bootstrap-install-command`. `--bootstrap-wget-options OPTIONS` Arbitrary options to be added to the bootstrap command when using GNU Wget. This option may not be used in the same command with `--bootstrap-install-command`. `--bootstrap-preinstall-command COMMANDS` Custom commands to run before installing Chef Infra Client `--bootstrap-url URL` The URL to a custom installation script. `-m URL`, `--msi-url URL` Location of the Chef Infra Client MSI. The default templates will prefer to download from this location. The MSI will be downloaded from chef.io if not provided. `--sudo` Execute a bootstrap operation with sudo. `--sudo-preserve-home` Use to preserve the non-root user’s `HOME` environment. `--use-sudo-password` Perform a bootstrap operation with sudo; specify the password with the `-P` (or `--ssh-password`) option. `-t TEMPLATE`, `--bootstrap-template TEMPLATE` The bootstrap template to use. This may be the name of a bootstrap template—`chef-full` for example—or it may be the full path to an Embedded Ruby (ERB) template that defines a custom bootstrap. Default value: `chef-full`, which installs Chef Infra Client using the Chef Infra installer on all supported platforms. ### Proxy Options `--bootstrap-no-proxy NO_PROXY_URL_or_IP` A URL or IP address that specifies a location that should not be proxied during the bootstrap. `--bootstrap-proxy PROXY_URL` The proxy server for the node that is the target of a bootstrap operation. `--bootstrap-proxy-pass PROXY_PASS` The proxy authentication password for the node being bootstrapped. `--bootstrap-proxy-user PROXY_USER` The proxy authentication username for the node being bootstrapped. ### Node Options `-N NAME`, `--node-name NAME` The unique identifier of the node. Note This option is required for a validatorless bootstrap. `-E ENVIRONMENT`, `--environment ENVIRONMENT` The name of the environment to be applied. `-r RUN_LIST`, `--run-list RUN_LIST` A comma-separated list of roles and/or recipes to be applied. `--secret SECRET` The encryption key that is used for values contained within a data bag item. `--secret-file FILE` The path to the file that contains the encryption key. `--hint HINT_NAME[=HINT_FILE]` An Ohai hint to be set on the bootstrap target. See the [Ohai](../../ohai/index#hints) documentation for more information. `HINT_FILE` is the name of the JSON file. `HINT_NAME` is the name of a hint in a JSON file. Use multiple `--hint` options to specify multiple hints. `-j JSON_ATTRIBS`, `--json-attributes JSON_ATTRIBS` A JSON string that is added to the first run of a Chef Infra Client. `--json-attribute-file FILE` A JSON file to be added to the first run of Chef Infra Client. `--[no-]fips` Allows OpenSSL to enforce FIPS-validated security during Chef Infra Client runs. `--policy-group POLICY_GROUP` The name of a policy group that exists on the Chef Infra Server. `--policy-name POLICY_NAME` The name of a policy, as identified by the name setting in a Policyfile.rb file. ### chef-vault Options `--bootstrap-vault-file VAULT_FILE` The path to a JSON file that contains a list of vaults and items to be updated. `--bootstrap-vault-item VAULT_ITEM` A single vault and item to update as `vault:item`. `--bootstrap-vault-json VAULT_JSON` A JSON string that contains a list of vaults and items to be updated. –bootstrap-vault-json ‘{ “vault1”: [“item1”, “item2”], “vault2”: “item2” }’ ### Key Verification Options `--[no-]host-key-verify` Use `--no-host-key-verify` to disable host key verification. Default setting: `--host-key-verify`. `--[no-]node-verify-api-cert` Verify the SSL certificate on the Chef Infra Server. When `true`, Chef Infra Client always verifies the SSL certificate. When `false`, Chef Infra Client uses the value of `ssl_verify_mode` to determine if the SSL certificate requires verification. If this option is not specified, the setting for `verify_api_cert` in the configuration file is applied. `--node-ssl-verify-mode MODE` Set the verify mode for HTTPS requests. Options: `none` or `peer`. Use `none` to do no validation of SSL certificates. Use `peer` to do validation of all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS **remote_file** resource URLs used in a Chef Infra Client run. This is the recommended setting. ### Debug Options `-V -V` Run the initial Chef Infra Client run at the `debug` log-level (e.g. `chef-client -l debug`). `-V -V -V` Run the initial Chef Infra Client run at the `trace` log-level (e.g. `chef-client -l trace`). Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Validatorless Bootstrap The ORGANIZATION-validator.pem is typically added to the .chef directory on the workstation. When a node is bootstrapped from that workstation, the ORGANIZATION-validator.pem is used to authenticate the newly-created node to the Chef Infra Server during the initial Chef Infra Client run. It is possible to bootstrap a node using the USER.pem file instead of the ORGANIZATION-validator.pem file. This is known as a “validatorless bootstrap”. To create a node via the USER.pem file, simply delete the ORGANIZATION-validator.pem file on the workstation. For example: ``` rm -f /home/lamont/.chef/myorg-validator.pem ``` and then make the following changes in the config.rb file: * Remove the `validation_client_name` setting * Edit the `validation_key` setting to be something that isn’t a path to an existent ORGANIZATION-validator.pem file. For example: `/nonexist`. As long as a USER.pem is also present on the workstation from which the validatorless bootstrap operation will be initiated, the bootstrap operation will run and will use the USER.pem file instead of the ORGANIZATION-validator.pem file. When running a validatorless `knife bootstrap` operation, the output is similar to: ``` desktop% knife bootstrap 10.1.1.1 -N foo01.acme.org \ -E dev -r 'role[base]' -j '{ "foo": "bar" }' \ --ssh-user vagrant --sudo Node foo01.acme.org exists, overwrite it? (Y/N) Client foo01.acme.org exists, overwrite it? (Y/N) Creating new client for foo01.acme.org Creating new node for foo01.acme.org Connecting to 10.1.1.1 10.1.1.1 Starting first Chef Client run... [....etc...] ``` Note The `--node-name` option is required for a validatorless bootstrap. ### FIPS Mode Federal Information Processing Standards (FIPS) is a United States government computer security standard that specifies security requirements for cryptography. The current version of the standard is FIPS 140-2. Chef Infra Client can be configured to allow OpenSSL to enforce FIPS-validated security during a Chef Infra Client run. This will disable cryptography that is explicitly disallowed in FIPS-validated software, including certain ciphers and hashing algorithms. Any attempt to use any disallowed cryptography will cause Chef Infra Client to throw an exception during a Chef Infra Client run. Note Chef uses MD5 hashes to uniquely identify files that are stored on the Chef Infra Server. MD5 is used only to generate a unique hash identifier and is not used for any cryptographic purpose. Notes about FIPS: * May be enabled for nodes running on Microsoft Windows and Enterprise Linux platforms * Should only be enabled for environments that require FIPS 140-2 compliance **Bootstrap a node using FIPS** ``` knife bootstrap 192.0.2.0 -P vanilla -x root -r 'recipe[apt],recipe[xfs],recipe[vim]' --fips ``` which shows something similar to: ``` OpenSSL FIPS 140 mode enabled ... 192.0.2.0 Chef Infra Client finished, 12/12 resources updated in 78.942455583 seconds ``` Custom Templates ---------------- The default `chef-full` template uses the Chef installer. For most bootstrap operations, regardless of the platform on which the target node is running, using the `chef-full` distribution is the best approach for installing Chef Infra Client on a target node. In some situations, a custom template may be required. For example, the default bootstrap operation relies on an Internet connection to get the distribution to the target node. If a target node cannot access the Internet, then a custom template can be used to define a specific location for the distribution so that the target node may access it during the bootstrap operation. The example below will show you how to create a bootstrap template that uses a custom artifact store for Chef packages and installation scripts, as well as a RubyGem mirror: 1. A custom bootstrap template file must be located in a `bootstrap/` directory, which is typically located within the `~/.chef/` directory on the local workstation. Navigate to the `.chef` directory, and create a `bootstrap` directory within it: ``` mkdir bootstrap ``` 2. Move to the `bootstrap` directory and create a blank template file; this example will use `template.erb` for the template name: ``` touch template.erb ``` 3. Still in the `bootstrap` directory, issue the following command to copy the `chef-full` configuration to your new template: ``` find /opt/chef-workstation/embedded/lib/ruby -type f -name chef-full.erb -exec cat {} \; > template.erb ``` This command searches for the `chef-full` template file under `/opt/chef-workstation/embedded/lib/ruby`, and then outputs the contents of the file to `template.erb`. If you used a different template file name, be sure to replace `template.erb` with the template file you created during the last step. 4. Update `template.erb` to replace `omnitruck.chef.io` with the URL of an `install.sh` script on your artifact store: ``` install_sh="<%= knife_config[:bootstrap_url] ? knife_config[:bootstrap_url] : "http://packages.example.com/install.sh" %>" ``` 5. Still in your text editor, locate the following line near the bottom of your `template.erb` file: ``` cat > /etc/chef/client.rb <<'EOP' <%= config_content %> EOP ``` Beneath it, add the following, replacing `gems.example.com` with the URL of your gem mirror: ``` cat >> /etc/chef/client.rb <<'EOP' rubygems_url "http://gems.example.com" EOP ``` This appends the appropriate `rubygems_url` setting to the `/etc/chef/client.rb` file that is created during bootstrap, which ensures that your nodes use your internal gem mirror. ### Bootstrap a Custom Template You can use the `--bootstrap-template` option with the `knife bootstrap` subcommand to specify the name of your bootstrap template file: ``` knife bootstrap 123.456.7.8 -x username -P password --sudo --bootstrap-template "template" ``` Alternatively, you can use the `knife[:bootstrap_template]` option within `config.rb` to specify the template that `knife bootstrap` will use by default when bootstrapping a node. It should point to your custom template within the `bootstrap` directory: ``` knife[:bootstrap_template] = "#{current_dir}/bootstrap/template.erb" ``` Examples -------- The following examples show how to use this knife subcommand: **Bootstrap a node** ``` knife bootstrap 192.0.2.0 -P vanilla -x root -r 'recipe[apt],recipe[xfs],recipe[vim]' ``` which shows something similar to: ``` ... 192.0.2.0 Chef Infra Client finished, 12/12 resources updated in 78.942455583 seconds ``` Use `knife node show` to verify: ``` knife node show debian-buster.int.domain.org ``` which returns something similar to: ``` Node Name: debian-buster.int.domain.org Environment: _default FQDN: debian-buster.int.domain.org IP: 192.0.2.0 Run List: recipe[apt], recipe[xfs], recipe[vim] Roles: Recipes: apt, xfs, vim, apt::default, xfs::default, vim::default Platform: debian 10.0 Tags: ``` **Use an SSH password** ``` knife bootstrap 192.0.2.0 -x username -P PASSWORD --sudo ``` **Use a file that contains a private key** ``` knife bootstrap 192.0.2.0 -x username -i ~/.ssh/id_rsa --sudo ``` **Specify options when using cURL** ``` knife bootstrap --bootstrap-curl-options "--proxy http://myproxy.com:8080" ``` **Specify options when using GNU Wget** ``` knife bootstrap --bootstrap-wget-options "-e use_proxy=yes -e http://myproxy.com:8080" ``` **Specify a custom installation command sequence** ``` knife bootstrap --bootstrap-install-command "curl -l http://mycustomserver.com/custom_install_chef_script.sh | sudo bash -s --" ``` **Bootstrap a Windows node via WinRM using a run list and environment** ``` knife bootstrap -o winrm 123.456.7.8 -U username -P 'PASSWORD' --node-name NODE_NAME --run-list 'recipe[cookbook]' -E ENV_NAME ``` **Bootstrap a Windows node via WinRM using a policyfile and policy group** ``` knife bootstrap -o winrm 123.456.7.8 -U username -P 'PASSWORD' --node-name NODE_NAME --policy-name PF_NAME --policy-group PG_NAME ``` **Bootstrap Windows node with shorthand syntax** ``` knife bootstrap winrm://username:PASSWORD@123.456.7.8 --run-list 'recipe[cookbook]' -E ENV_NAME ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_bootstrap/knife cookbook site =================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_cookbook_site.md) The Supermarket API is used to provide access to cookbooks, tools, and users on the [Chef Supermarket](https://supermarket.chef.io). All of the cookbooks, tools, and users on the Supermarket are accessible through a RESTful API by accessing `supermarket.chef.io/api/v1/` via the supported endpoints. In most cases, knife is the best way to interact with the Supermarket; however in some cases, direct use of the Supermarket API is necessary. Use the `knife cookbook site` subcommand to interact with cookbooks that are available in the [Chef Supermarket](https://supermarket.chef.io/). A user account is required for any community actions that write data to this site. The following arguments do not require a user account: `download`, `search`, `install`, and `list`. Warning `knife cookbook site` has been deprecated in favor of the [knife supermarket](../knife_supermarket/index) command. Warning Please consider managing community cookbooks using the version of Berkshelf that ships with Chef Workstation. For more information about Chef Workstation, see [About Chef Workstation](../index). Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. Private Supermarket ------------------- To use the `knife cookbook site` command with a private Supermarket installation, you must first add the URL of your Supermarket to your `config.rb` file: ``` knife[:supermarket_site] = 'https://supermarket.example.com' ``` If this value is not specified, knife will use `https://supermarket.chef.io` by default. download -------- Use the `download` argument to download a cookbook from the community website. A cookbook will be downloaded as a tar.gz archive and placed in the current working directory. If a cookbook (or cookbook version) has been deprecated and the `--force` option is not used, knife will alert the user that the cookbook is deprecated and then will provide the name of the most recent non-deprecated version of that cookbook. ### Syntax This argument has the following syntax: ``` knife cookbook site download COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `COOKBOOK_VERSION` The version of a cookbook to be downloaded. If a cookbook has only one version, this option does not need to be specified. If a cookbook has more than one version and this option is not specified, the most recent version of the cookbook is downloaded. `-f FILE`, `--file FILE` The file to which a cookbook download is written. `--force` Overwrite an existing directory. `-m SUPERMARKET_SITE`, `--supermarket-site SUPERMARKET_SITE` The URL at which the Chef Supermarket is located. Default value: <https://supermarket.chef.io>. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Download a cookbook** To download the cookbook `getting-started`, enter: ``` knife cookbook site download getting-started ``` to return something like: ``` Downloading getting-started from the cookbooks site at version 1.2.3 to /Users/grantmc/chef-support/getting-started-1.2.3.tar.gz Cookbook saved: /Users/grantmc/chef-support/getting-started-1.2.3.tar.gz ``` install ------- Use the `install` argument to install a cookbook that has been downloaded from the community site to a local git repository . This action uses the git version control system in conjunction with the the [Chef Supermarket](https://supermarket.chef.io/cookbooks) site to install community-contributed cookbooks to the local chef-repo. Using this argument does the following: 1. A new “pristine copy” branch is created in git for tracking the upstream. 2. All existing versions of a cookbook are removed from the branch. 3. The cookbook is downloaded from the [Chef Supermarket](https://supermarket.chef.io/cookbooks) in the tar.gz format. 4. The downloaded cookbook is untarred and its contents are committed to git and a tag is created. 5. The “pristine copy” branch is merged into the master branch. This process allows the upstream cookbook in the master branch to be modified while letting git maintain changes as a separate patch. When an updated upstream version becomes available, those changes can be merged while maintaining any local modifications. ### Syntax This argument has the following syntax: ``` knife cookbook site install COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `-b`, `--use-current-branch` Ensure that the current branch is used. `-B BRANCH`, `--branch BRANCH` The name of the default branch. This defaults to the master branch. `COOKBOOK_VERSION` The version of the cookbook to be installed. If a version is not specified, the most recent version of the cookbook is installed. `-D`, `--skip-dependencies` Ensure that all cookbooks to which the installed cookbook has a dependency are not installed. `-m SUPERMARKET_SITE`, `--supermarket-site SUPERMARKET_SITE` The URL at which the Chef Supermarket is located. Default value: <https://supermarket.chef.io>. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Install a cookbook** To install the cookbook `getting-started`, enter: ``` knife cookbook site install getting-started ``` to return something like: ``` Installing getting-started to /Users/grantmc/chef-support/.chef/../cookbooks Checking out the master branch. Creating pristine copy branch chef-vendor-getting-started Downloading getting-started from the cookbooks site at version 1.2.3 to /Users/grantmc/chef-support/.chef/../cookbooks/getting-started.tar.gz Cookbook saved: /Users/grantmc/chef-support/.chef/../cookbooks/getting-started.tar.gz Removing pre-existing version. Uncompressing getting-started version /Users/grantmc/chef-support/.chef/../cookbooks. removing downloaded tarball 1 files updated, committing changes Creating tag cookbook-site-imported-getting-started-1.2.3 Checking out the master branch. Updating 4d44b5b..b4c32f2 Fast-forward cookbooks/getting-started/README.rdoc | 4 +++ cookbooks/getting-started/attributes/default.rb | 1 + cookbooks/getting-started/metadata.json | 29 ++++++++++++++++++++ cookbooks/getting-started/metadata.rb | 6 ++++ cookbooks/getting-started/recipes/default.rb | 23 +++++++++++++++ .../templates/default/chef-getting-started.txt.erb | 5 +++ 6 files changed, 68 insertions(+), 0 deletions(-) create mode 100644 cookbooks/getting-started/README.rdoc create mode 100644 cookbooks/getting-started/attributes/default.rb create mode 100644 cookbooks/getting-started/metadata.json create mode 100644 cookbooks/getting-started/metadata.rb create mode 100644 cookbooks/getting-started/recipes/default.rb create mode 100644 cookbooks/getting-started/templates/default/chef-getting-started.txt.erb Cookbook getting-started version 1.2.3 successfully installed ``` list ---- Use the `list` argument to view a list of cookbooks that are currently available at the [Chef Supermarket](https://supermarket.chef.io/cookbooks). ### Syntax This argument has the following syntax: ``` knife cookbook site list ``` ### Options This argument has the following options: `-m SUPERMARKET_SITE`, `--supermarket-site SUPERMARKET_SITE` The URL at which the Chef Supermarket is located. Default value: <https://supermarket.chef.io>. `-w`, `--with-uri` Show the corresponding URIs. ### Examples The following examples show how to use this knife subcommand: **View a list of cookbooks** To view a list of cookbooks at the [Chef Supermarket](https://supermarket.chef.io/cookbooks) server, enter: ``` knife cookbook site list ``` to return a list similar to: ``` 1password homesick rabbitmq 7-zip hostname rabbitmq-management AmazonEC2Tag hosts rabbitmq_chef R hosts-awareness rackspaceknife accounts htop radiant ack-grep hudson rails activemq icinga rails_enterprise ad id3lib redis-package ad-likewise iftop redis2 ant iis redmine [...truncated...] ``` search ------ Use the `search` argument to search for a cookbook at the [Chef Supermarket](https://supermarket.chef.io/cookbooks). A search query is used to return a list of cookbooks at the [Chef Supermarket](https://supermarket.chef.io/cookbooks) and uses the same syntax as the `knife search` subcommand. ### Syntax This argument has the following syntax: ``` knife cookbook site search SEARCH_QUERY (options) ``` ### Options This argument has the following options: `-m SUPERMARKET_SITE`, `--supermarket-site SUPERMARKET_SITE` The URL at which the Chef Supermarket is located. Default value: <https://supermarket.chef.io>. ### Examples The following examples show how to use this knife subcommand: **Search for cookbooks** To search for all of the cookbooks that can be used with Apache, enter: ``` knife cookbook site search 'apache*' ``` to return something like: ``` apache2: cookbook: https://supermarket.chef.io/api/v1/cookbooks/apache2 cookbook_description: Installs and configures apache2 cookbook_maintainer: sous-chefs cookbook_name: apache2 apache_hadoop: cookbook: https://supermarket.chef.io/api/v1/cookbooks/apache_hadoop cookbook_description: Installs/Configures the Apache Hadoop distribution cookbook_maintainer: dowlingj cookbook_name: apache_hadoop apache_kafka: cookbook: https://supermarket.chef.io/api/v1/cookbooks/apache_kafka cookbook_description: Installs/Configures Apache Kafka >= 0.7.0 cookbook_maintainer: mathyourlife cookbook_name: apache_kafka [...truncated...] ``` share ----- Use the `share` argument to add a cookbook to the [Chef Supermarket](https://supermarket.chef.io/cookbooks). This action will require a user account and a certificate for [Chef Supermarket](https://supermarket.chef.io/). By default, knife will use the user name and API key that is identified in the configuration file used during the upload; otherwise these values must be specified on the command line or in an alternate configuration file. If a cookbook already exists on the [Chef Supermarket](https://supermarket.chef.io/cookbooks), then only an owner or maintainer of that cookbook can make updates. ### Syntax This argument has the following syntax: ``` knife cookbook site share COOKBOOK_NAME CATEGORY (options) ``` ### Options This argument has the following options: `CATEGORY` The cookbook category: `"Databases"`, `"Web Servers"`, `"Process Management"`, `"Monitoring & Trending"`, `"Programming Languages"`, `"Package Management"`, `"Applications"`, `"Networking"`, `"Operating Systems & Virtualization"`, `"Utilities"`, or `"Other"`. `-m SUPERMARKET_SITE`, `--supermarket-site SUPERMARKET_SITE` The URL at which the Chef Supermarket is located. Default value: <https://supermarket.chef.io>. `-n`, `--dry-run` Take no action and only print out results. Default: `false`. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Share a cookbook** To share a cookbook named `apache2`: ``` knife cookbook site share "apache2" "Web Servers" ``` show ---- Use the `show` argument to view information about a cookbook on the [Chef Supermarket](https://supermarket.chef.io/cookbooks). ### Syntax This argument has the following syntax: ``` knife cookbook site show COOKBOOK_NAME [COOKBOOK_VERSION] ``` ### Options This argument has the following options: `COOKBOOK_VERSION` The version of a cookbook to be shown. If a cookbook has only one version, this option does not need to be specified. If a cookbook has more than one version and this option is not specified, a list of cookbook versions is returned. `-m SUPERMARKET_SITE`, `--supermarket-site SUPERMARKET_SITE` The URL at which the Chef Supermarket is located. Default value: <https://supermarket.chef.io>. ### Examples The following examples show how to use this knife subcommand: **Show cookbook data** To show the details for a cookbook named `haproxy`: ``` knife cookbook site show haproxy ``` to return something like: ``` average_rating: category: Other created_at: 2009-10-25T23:51:07.000Z deprecated: false description: Installs and configures haproxy external_url: https://github.com/sous-chefs/haproxy issues_url: https://github.com/sous-chefs/haproxy/issues latest_version: https://supermarket.chef.io/api/v1/cookbooks/haproxy/versions/6.2.3 maintainer: sous-chefs metrics: collaborators: 3 downloads: total: 29114892 versions: 0.7.0: 1258890 0.8.0: 1258804 [...truncated...] followers: 139 name: haproxy source_url: https://github.com/sous-chefs/haproxy up_for_adoption: updated_at: 2018-08-08T20:09:52.334Z versions: https://supermarket.chef.io/api/v1/cookbooks/haproxy/versions/6.2.3 https://supermarket.chef.io/api/v1/cookbooks/haproxy/versions/6.2.2 [...truncated...] ``` **Show cookbook data as JSON** To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife cookbook site show devops -F json ``` Other formats available include `text`, `yaml`, and `pp`. unshare ------- Use the `unshare` argument to stop the sharing of a cookbook at the [Chef Supermarket](https://supermarket.chef.io/cookbooks). Only the maintainer of a cookbook may perform this action. Note Unsharing a cookbook will break a cookbook that has set a dependency on that cookbook or cookbook version. ### Syntax This argument has the following syntax: ``` knife cookbook site unshare COOKBOOK_NAME/versions/VERSION ``` ### Options This argument has the following options: `-m SUPERMARKET_SITE`, `--supermarket-site SUPERMARKET_SITE` The URL at which the Chef Supermarket is located. Default value: <https://supermarket.chef.io>. ### Examples The following examples show how to use this knife subcommand: **Unshare a cookbook** To unshare a cookbook named `getting-started`, enter: ``` knife cookbook site unshare "getting-started" ``` **Unshare a cookbook version** To unshare cookbook version `0.10.0` for the `getting-started` cookbook, enter: ``` knife cookbook site unshare "getting-started/versions/0.10.0" ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_cookbook_site/knife data bag ============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_data_bag.md) Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. A data bag item may be encrypted using [shared secret encryption](https://en.wikipedia.org/wiki/Symmetric-key_algorithm). This allows each data bag item to store confidential information (such as a database password) or to be managed in a source control system (without plain-text data appearing in revision history). Each data bag item may be encrypted individually; if a data bag contains multiple encrypted data bag items, these data bag items are not required to share the same encryption keys. Note Because the contents of encrypted data bag items are not visible to the Chef Infra Server, search queries against data bags with encrypted items will not return any results. Use the `knife data bag` subcommand to manage arbitrary stores of globally available JSON data. Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. create ------ Use the `create` argument to add a data bag to the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife data bag create DATA_BAG_NAME [DATA_BAG_ITEM] (options) ``` ### Options This argument has the following options: `DATA_BAG_ITEM` The name of a specific item within a data bag. `DATA_BAG_NAME` may not be `client`, `environment`, `node` or `role`, as these are reserved words for [knife search](../knife_search/index). `--secret SECRET` The encryption key that is used for values contained within a data bag item. If `secret` is not specified, Chef Infra Client looks for a secret at the path specified by the `encrypted_data_bag_secret` setting in the client.rb file. For encrypted data bag items, use **either** `--secret` or `--secret-file`, not both. `--secret-file FILE` The path to the file that contains the encryption key. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create a data bag** To create a data bag named “admins”, enter: ``` knife data bag create admins ``` to return: ``` Created data_bag[admins] ``` delete ------ Use the `delete` argument to delete a data bag or a data bag item from a Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife data bag delete DATA_BAG_NAME [DATA_BAG_ITEM] (options) ``` ### Options This argument has the following options: `DATA_BAG_ITEM` The name of a specific item within a data bag. ### Examples The following examples show how to use this knife subcommand: **Delete a data bag** ``` knife data bag delete data_bag_name ``` **Delete a data bag item** To delete an item named “charlie”, enter: ``` knife data bag delete admins charlie ``` Type `Y` to confirm a deletion. edit ---- Use the `edit` argument to edit the data contained in a data bag. If encryption is being used, the data bag will be decrypted, the data will be made available in the $EDITOR, and then encrypted again before saving it to the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife data bag edit DATA_BAG_NAME [DATA_BAG_ITEM] (options) ``` ### Options This argument has the following options: `DATA_BAG_ITEM` The name of a specific item within a data bag. `--secret SECRET` The encryption key that is used for values contained within a data bag item. If `secret` is not specified, Chef Infra Client looks for a secret at the path specified by the `encrypted_data_bag_secret` setting in the client.rb file. `--secret-file FILE` The path to the file that contains the encryption key. Note For encrypted data bag items, use *either* `--secret` or `--secret-file`, not both. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Edit a data bag** To edit the contents of a data bag, enter: ``` knife data bag edit dogs tibetanspaniel ``` where `dogs` is the name of the data bag and `tibetanspaniel` is the name of the data bag item. This will return something similar to the following in the knife editor: ``` { "name":"data_bag_item_dogs_tibetanspaniel", "json_class":"Chef::DataBagItem", "chef_type":"data_bag_item", "data_bag":"dogs", "raw_data": { "description":"small dog that likes to sit in windows", "id":"tibetanspaniel" } } ``` Make the necessary changes to the key-value pairs under `raw_data` and save them. **Edit a data bag item** To edit an item named “charlie” that is contained in a data bag named “admins”, enter: ``` knife data bag edit admins charlie ``` to open the $EDITOR. Once opened, you can update the data before saving it to the Chef Infra Server. For example, by changing: ``` { "id": "charlie" } ``` to: ``` { "id": "charlie", "uid": 1005, "gid": "ops", "shell": "/bin/zsh", "comment": "Crazy Charlie" } ``` from file --------- Use the `from file` argument to: * Add a data bag item to a data bag * Update the contents of an existing data bag item The data bag itself must already exist on the Chef Infra Server and must be specified as part of the command. The contents of the data bag item are specified using a JSON file. This JSON file may be located at a relative or absolute path; its location must be specified as part of the command. The JSON file that defines the contents of the data bag item must at least contain the name of the data bag item—`"id": "name"`. ### Syntax This argument has the following syntax: ``` knife data bag from file DATA_BAG_NAME_or_PATH JSON_FILE ``` ### Options This argument has the following options: `-a`, `--all` Upload all data bags found at the specified path. `--secret SECRET` The encryption key that is used for values contained within a data bag item. If `secret` is not specified, Chef Infra Client looks for a secret at the path specified by the `encrypted_data_bag_secret` setting in the client.rb file. `--secret-file FILE` The path to the file that contains the encryption key. Note For encrypted data bag items, use *either* `--secret` or `--secret-file`, not both. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create a data bag from a file** To create a data bag on the Chef Infra Server from a file: ``` knife data bag from file "path to JSON file" ``` **Create an encrypted data bag from a file** To create a data bag named “devops_data” that contains encrypted data, enter: ``` knife data bag from file devops_data --secret-file "path to decryption file" ``` **Create an encrypted data bag for use with Chef Infra Client local mode** To generate an encrypted data bag item in a JSON file for use when Chef Infra Client is run in local mode (via the `--local-mode` option), enter: ``` knife data bag from file my_data_bag /path/to/data_bag_item.json -z --secret-file /path/to/encrypted_data_bag_secret ``` this will create an encrypted JSON file in: ``` data_bags/my_data_bag/data_bag_item.json ``` list ---- Use the `list` argument to view a list of data bags that are currently available on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife data bag list ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### Examples The following examples show how to use this knife subcommand: **View a list of data bags** ``` knife data bag list ``` show ---- Use the `show` argument to view the contents of a data bag. ### Syntax This argument has the following syntax: ``` knife data bag show DATA_BAG_NAME (options) ``` ### Options This argument has the following options: `DATA_BAG_ITEM` The name of a specific item within a data bag. `--secret SECRET` The encryption key that is used for values contained within a data bag item. If `secret` is not specified, Chef Infra Client looks for a secret at the path specified by the `encrypted_data_bag_secret` setting in the client.rb file. `--secret-file FILE` The path to the file that contains the encryption key. Note For encrypted data bag items, use *either* `--secret` or `--secret-file`, not both. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Show a data bag** ``` knife data bag show admins ``` to return something like: ``` charlie ``` **Show a data bag item** To show the contents of a specific item within data bag, enter: ``` knife data bag show admins charlie ``` to return: ``` comment: Crazy Charlie gid: ops id: charlie shell: /bin/zsh uid: 1005 ``` **Show a data bag, encrypted** To show the contents of a data bag named `passwords` with an item that contains encrypted data named `mysql`, enter: ``` knife data bag show passwords mysql ``` to return: ``` { "id": "mysql", "pass": "trywgFA6R70NO28PNhMpGhEvKBZuxouemnbnAUQsUyo=\n", "user": "e/p+8WJYVHY9fHcEgAAReg==\n" } ``` **Show a data bag, decrypted** To show the decrypted contents of the same data bag, enter: ``` knife data bag show --secret-file /path/to/decryption/file passwords mysql ``` to return: ``` { "id": "mysql", "pass": "thesecret123", "user": "fred" } ``` **Show a data bag as JSON** To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife data bag show admins -F json ``` Other formats available include `text`, `yaml`, and `pp`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_data_bag/knife delete ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_delete.md) Use the `knife delete` subcommand to delete an object from a Chef Infra Server. This subcommand works similar to `knife cookbook delete`, `knife data bag delete`, `knife environment delete`, `knife node delete`, and `knife role delete`, but with a single verb (and a single action). Syntax ------ This subcommand has the following syntax: ``` knife delete [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--both` Delete both local and remote copies of an object. Default: `false`. `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--local` Delete only the local copy of an object. A remote copy will not be deleted. Default: `false`. `-r`, `--[no-]recurse` Use `--recurse` to delete directories recursively. Default: `--no-recurse`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- None. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_delete/knife deps ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_deps.md) Use the `knife deps` subcommand to identify dependencies for a node, role, or cookbook. Syntax ------ This subcommand has the following syntax: ``` knife deps (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--[no-]recurse` Use `--recurse` to list dependencies recursively. This option can only be used when `--tree` is set to `true`. Default: `--no-recurse`. `--remote` Determine dependencies from objects located on the Chef Infra Server instead of in the local chef-repo. Default: `false`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. `--tree` Show dependencies in a visual tree structure (including duplicates, if they exist). Default: `false`. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Find dependencies for a node** ``` knife deps nodes/node_name.json ``` **Find dependencies for a role** ``` knife deps roles/role_name.json ``` **Find dependencies for a cookbook** ``` knife deps cookbooks/cookbook_name.json ``` **Find dependencies for an environment** ``` knife deps environments/environment_name.json ``` **Find dependencies for a combination of nodes, roles, and so on** To find the dependencies for a combination of nodes, cookbooks, roles, and/or environments: ``` knife deps cookbooks/git.json cookbooks/github.json roles/base.json environments/desert.json nodes/mynode.json ``` **Use a wildcard** A wildcard can be used to return all of the child nodes. For example, all of the environments: ``` knife deps environments/*.json ``` **Return as tree** Use the `--tree` option to view the results with structure: ``` knife deps roles/webserver.json ``` to return something like: ``` roles/webserver.json roles/base.json cookbooks/github cookbooks/git cookbooks/users cookbooks/apache2 ``` **Pass knife deps output to knife upload** The output of `knife deps` can be passed to `knife upload`: ``` knife upload `knife deps nodes/*.json ``` **Pass knife deps output to knife xargs** The output of `knife deps` can be passed to `knife xargs`: ``` knife deps nodes/*.json | xargs knife upload ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_deps/knife diff ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_diff.md) Use the `knife diff` subcommand to compare the differences between files and directories on the Chef Infra Server and in the chef-repo. For example, to compare files on the Chef Infra Server prior to uploading or downloading files using the `knife download` and `knife upload` subcommands, or to ensure that certain files in multiple production environments are the same. This subcommand is similar to the `git diff` command that can be used to diff what is in the chef-repo with what is synced to a git repository. Syntax ------ This subcommand has the following syntax: ``` knife diff [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--cookbook-version VERSION` The version of a cookbook to download. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--diff-filter=[(A|D|M|T)...[*]]` Select only files that have been added (`A`), deleted (`D`), modified (`M`), and/or have had their type changed (`T`). Any combination of filter characters may be used, including no filter characters. Use `*` to select all paths if a file matches other criteria in the comparison. Default value: `nil`. `--name-only` Show only the names of modified files. `--name-status` Show only the names of files with a status of `Added`, `Deleted`, `Modified`, or `Type Changed`. `--no-recurse` Use `--no-recurse` to disable listing a directory recursively. Default: `--recurse`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Compare files that contain JSON data** To compare the `base.json` role to a `webserver.json` role, enter: ``` knife diff roles/base.json roles/webserver.json ``` **Compare the chef-repo and the server** To compare the differences between the local chef-repo and the files that are on the Chef Infra Server, enter: ``` knife diff ``` **Compare, then return results** To diff a node named `node-lb` and then only return files that have been added, deleted, modified, or changed, enter: ``` knife diff --name-status node-lb ``` to return something like: ``` node-lb/recipes/eip.rb node-lb/recipes/heartbeat-int.rb node-lb/templates/default/corpsite.conf.erb node-lb/files/default/wildcard.node.com.crt node-lb/files/default/wildcard.node.com.crt-2009 node-lb/files/default/wildcard.node.com.key node-lb/.gitignore node-lb/Rakefile ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_diff/knife edit ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_edit.md) Use the `knife edit` subcommand to edit objects on the Chef Infra Server. This subcommand works similar to `knife cookbook edit`, `knife data bag edit`, `knife environment edit`, `knife node edit`, and `knife role edit`, but with a single verb (and a single action). Syntax ------ This subcommand has the following syntax: ``` knife edit (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--local` Show files in the local chef-repo instead of a remote location. Default: `false`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Remove a user from /groups/admins.json** A user who belongs to the `admins` group must be removed from the group before they may be removed from an organization. To remove a user from the `admins` group, run the following: ``` EDITOR=vi knife edit /groups/admins.json ``` make the required changes, and then save the file. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_edit/knife download ============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_download.md) Use the `knife download` subcommand to download roles, cookbooks, environments, nodes, and data bags from the Chef Infra Server to the current working directory. It can be used to back up data on the Chef Infra Server, inspect the state of one or more files, or to extract out-of-process changes users may have made to files on the Chef Infra Server, such as if a user made a change that bypassed version source control. This subcommand is often used in conjunction with `knife diff`, which can be used to see exactly what changes will be downloaded, and then `knife upload`, which does the opposite of `knife download`. Syntax ------ This subcommand has the following syntax: ``` knife download [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--cookbook-version VERSION` The version of a cookbook to download. `-n`, `--dry-run` Take no action and only print out results. Default: `false`. `--[no-]diff` Download only new and modified files. Set to `false` to download all files. Default: `--diff`. `--[no-]force` Use `--force` to download files even when the file on the hard drive is identical to the object on the server (role, cookbook, etc.). By default, files are compared to see if they have equivalent content, and local files are only overwritten if they are different. Default: `--no-force`. `--[no-]purge` Use `--purge` to delete local files and directories that do not exist on the Chef Infra Server. By default, if a role, cookbook, etc. does not exist on the Chef Infra Server, the local file for said role is left alone and NOT deleted. Default: `--no-purge`. `--[no-]recurse` Use `--no-recurse` to disable downloading a directory recursively. Default: `--recurse`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Download the entire chef-repo** To download the entire chef-repo from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download / ``` **Download the /cookbooks directory** To download the `cookbooks/` directory from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download cookbooks ``` or from anywhere in the chef-repo, enter: ``` knife download /cookbooks ``` **Download the /environments directory** To download the `environments/` directory from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download environments ``` or from anywhere in the chef-repo, enter: ``` knife download /environments ``` **Download an environment** To download an environment named “production” from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download environments/production.json ``` or from the `environments/` directory, enter: ``` knife download production.json ``` **Download the /roles directory** To download the `roles/` directory from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download roles ``` or from anywhere in the chef-repo, enter: ``` knife download /roles ``` **Download cookbooks and roles** To download all cookbooks that start with “apache” and belong to the “webserver” role, browse to the top level of the chef-repo and enter: ``` knife download cookbooks/apache\* roles/webserver.json ``` **Download data bags** To download all data bags from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download data_bags ``` or from anywhere in the chef-repo, enter: ``` knife download /data_bags ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_download/knife exec ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_exec.md) Use the `knife exec` subcommand to execute Ruby scripts in the context of a fully configured Chef Infra Client. Use this subcommand to run scripts that will only access Chef Infra Server one time (or otherwise very infrequently) or any time that an operation does not warrant full usage of the knife subcommand library. Authenticated API Requests -------------------------- The `knife exec` subcommand can be used to make authenticated API requests to the Chef Infra Server using the following methods: | Method | Description | | --- | --- | | `api.delete` | Use to delete an object from the Chef Infra Server. | | `api.get` | Use to get the details of an object on the Chef Infra Server. | | `api.post` | Use to add an object to the Chef Infra Server. | | `api.put` | Use to update an object on the Chef Infra Server. | These methods are used with the `-E` option, which executes that string locally on the workstation using chef-shell. These methods have the following syntax: ``` knife exec -E 'api.method(/endpoint)' ``` where: * `api.method` is the corresponding authentication method — `api.delete`, `api.get`, `api.post`, or `api.put` * `/endpoint` is an endpoint in the Chef Infra Server API For example, to get the data for a node named “Example_Node”: ``` knife exec -E 'puts api.get("/nodes/Example_Node")' ``` and to ensure that the output is visible in the console, add the `puts` in front of the API authorization request: ``` knife exec -E 'puts api.get("/nodes/Example_Node")' ``` where `puts` is the shorter version of the `$stdout.puts` predefined variable in Ruby. The following example shows how to add a client named “IBM305RAMAC” and the `/clients` endpoint, and then return the private key for that user in the console: ``` client_desc = { "name" => "IBM305RAMAC", "admin" => false } new_client = api.post("/clients", client_desc) puts new_client["private_key"] ``` Ruby Scripts ------------ For Ruby scripts that will be run using the `exec` subcommand, note the following: * The Ruby script must be located on the system from which knife is run (and not be located on any of the systems that knife will be managing). * Shell commands will be run from a management workstation. For example, something like `%x[ls -lash /opt/only-on-a-node]` would give you the directory listing for the “opt/only-on-a-node” directory or a “No such file or directory” error if the file does not already exist locally. * When the chef-shell DSL is available, the Chef Infra Client DSL will not be (unless the management workstation is also a Chef Infra Client). Without the Chef Infra Client DSL, a bash block cannot be used to run bash commands. Syntax ------ This subcommand has the following syntax: ``` knife exec SCRIPT (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-E CODE`, `--exec CODE` A string of code to be executed. `-p PATH:PATH`, `--script-path PATH:PATH` A colon-separated path at which Ruby scripts are located. Use to override the default location for scripts. When this option is not specified, knife will look for scripts located in `chef-repo/.chef/scripts` directory. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Run Ruby scripts** There are three ways to use `knife exec` to run Ruby script files. For example: ``` knife exec /path/to/script_file ``` or: ``` knife exec -E 'RUBY CODE' ``` or: ``` knife exec RUBY CODE ^D ``` **Chef Knife status** To check the status of knife using a Ruby script named `status.rb` (which looks like): ``` printf "%-5s %-12s %-8s %s\n", "Check In", "Name", "Ruby", "Recipes" nodes.all do |n| checkin = Time.at(n['ohai_time']).strftime("%F %R") rubyver = n['languages']['ruby']['version'] recipes = n.run_list.expand(_default).recipes.join(", ") printf "%-20s %-12s %-8s %s\n", checkin, n.name, rubyver, recipes end ``` and is located in a directory named `scripts/`, enter: ``` knife exec scripts/status.rb ``` **List available free memory** To show the available free memory for all nodes, enter: ``` knife exec -E 'nodes.all {|n| puts "#{n.name} has #{n.memory.total} free memory"}' ``` **List available search indexes** To list all of the available search indexes, enter: ``` knife exec -E 'puts api.get("search").keys' ``` **Operations on Users and User Keys** To change any global end points like user or user keys, use the `--server-url` flag: ``` knife exec -E 'api.delete("/users/myuser/keys/user33")' --server-url https:// ``` **Query for multiple attributes** To query a node for multiple attributes using a Ruby script named `search_attributes.rb` (which looks like): ``` % cat scripts/search_attributes.rb query = ARGV[2] attributes = ARGV[3].split(",") puts "Your query: #{query}" puts "Your attributes: #{attributes.join(" ")}" results = {} search(:node, query) do |n| results[n.name] = {} attributes.each {|a| results[n.name][a] = n[a]} end puts results exit 0 ``` enter: ``` % knife exec scripts/search_attributes.rb "hostname:test_system" ipaddress,fqdn ``` to return something like: ``` Your query: hostname:test_system Your attributes: ipaddress fqdn {"test_system.example.com"=>{"ipaddress"=>"10.1.1.200", "fqdn"=>"test_system.example.com"}} ``` **Find shadow cookbooks** To find all of the locations in which cookbooks exist that may shadow each other, create a file called `shadow-check.rb` that contains the following Ruby code: ``` config = Chef::Config cookbook_loader = begin Chef::Cookbook::FileVendor.on_create { |manifest| Chef::Cookbook::FileSystemFileVendor.new(manifest, config[:cookbook_path]) } Chef::CookbookLoader.new(config[:cookbook_path]) end ui = Chef::Knife::UI.new($stdout, $stderr, $stdin, {}) cookbook_loader.load_cookbooks if cookbook_loader.merged_cookbooks.empty? ui.msg "cookbooks ok" else ui.warn "* " * 40 ui.warn(<<-WARNING) The cookbooks: #{cookbook_loader.merged_cookbooks.join(', ')} exist in multiple places in your cookbook_path. A composite version of these cookbooks has been compiled for uploading. #{ui.color('IMPORTANT:', :red, :bold)} In a future version of Chef, this behavior will be removed and you will no longer be able to have the same version of a cookbook in multiple places in your cookbook_path. WARNING ui.warn "The affected cookbooks are located:" ui.output ui.format_for_display(cookbook_loader.merged_cookbook_paths) ui.warn "* " * 40 end ``` Put this file in the directory of your choice. Run the following command: ``` knife exec shadow-check.rb ``` and be sure to edit `shadow-check.rb` so that it defines the path to that file correctly. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_exec/knife list ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_list.md) Use the `knife list` subcommand to view a list of objects on the Chef Infra Server. This subcommand works similar to `knife cookbook list`, `knife data bag list`, `knife environment list`, `knife node list`, and `knife role list`, but with a single verb (and a single action). Syntax ------ This subcommand has the following syntax: ``` knife list [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-1` Show only one column of results. Default: `false`. `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `-d` Prevent a directory’s children from showing when a directory matches a pattern. Default value: `false`. `-f`, `--flat` Show a list of file names. Set to `false` to view `ls`-like output. Default: `false`. `--local` Return only the contents of the local directory. Default: `false`. `-p` Show directories with trailing slashes (/). Default: `false`. `-R` List directories recursively. Default: `false`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **List roles** For example, to view a list of roles on the Chef Infra Server: ``` knife list roles/ ``` **List roles and environments** To view a list of roles and environments on the Chef Infra Server: ``` knife list roles/ environments/ ``` **List everything** To view a list of absolutely everything on the Chef Infra Server: ``` knife list -R / ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_list/knife node ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_node.md) A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. Use the `knife node` subcommand to manage the nodes that exist on a Chef Infra Server. Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. bulk delete ----------- Use the `bulk delete` argument to delete one or more nodes that match a pattern defined by a regular expression. The regular expression must be within quotes and not be surrounded by forward slashes (/). ### Syntax This argument has the following syntax: ``` knife node bulk delete REGEX ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Bulk delete nodes** Use a regular expression to define the pattern used to bulk delete nodes: ``` knife node bulk delete "^[0-9]{3}$" ``` Type `Y` to confirm a deletion. create ------ Use the `create` argument to add a node to the Chef Infra Server. Node data is stored as JSON on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife node create NODE_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Create a node** To add a node named `node1`, enter: ``` knife node create node1 ``` In the $EDITOR enter the node data in JSON: ``` { "normal": { }, "name": "foobar", "override": { }, "default": { }, "json_class": "Chef::Node", "automatic": { }, "run_list": [ "recipe[zsh]", "role[webserver]" ], "chef_type": "node" } ``` When finished, save it. delete ------ Use the `delete` argument to delete a node from the Chef Infra Server. If using Chef Client 12.17 or later, you can delete multiple nodes using this subcommand. Note Deleting a node will not delete any corresponding API clients. ### Syntax This argument has the following syntax: ``` knife node delete NODE_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Delete a node** To delete a node named `node1`, enter: ``` knife node delete node1 ``` edit ---- Use the `edit` argument to edit the details of a node on a Chef Infra Server. Node data is stored as JSON on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife node edit NODE_NAME (options) ``` ### Options This argument has the following options: `-a`, `--all` Display a node in the $EDITOR. By default, attributes that are default, override, or automatic, are not shown. ### Examples The following examples show how to use this knife subcommand: **Edit a node** To edit the data for a node named `node1`, enter: ``` knife node edit node1 -a ``` Update the role data in JSON: ``` { "normal": { }, "name": "node1", "override": { }, "default": { }, "json_class": "Chef::Node", "automatic": { }, "run_list": [ "recipe[devops]", "role[webserver]" ], "chef_type": "node" } ``` When finished, save it. environment set --------------- Use the `environment set` argument to set the environment for a node without editing the node object. ### Syntax This argument has the following syntax: ``` knife node environment_set NODE_NAME ENVIRONMENT_NAME (options) ``` ### Options This command does not have any specific options. ### Examples None. from file --------- Use the `from file` argument to create a node using existing node data as a template. ### Syntax This argument has the following syntax: ``` knife node from file FILE ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Create a node using a JSON file** To add a node using data contained in a JSON file: ``` knife node from file "PATH_TO_JSON_FILE" ``` list ---- Use the `list` argument to view all of the nodes that exist on a Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife node list (options) ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **View a list of nodes** To verify the list of nodes that are registered with the Chef Infra Server, enter: ``` knife node list ``` to return something similar to: ``` i-12345678 rs-123456 ``` policy set ---------- Use the `policy set` argument to set the policy group and policy name for a node. ### Syntax This argument has the following syntax: ``` knife node policy set NODE POLICY_GROUP POLICY_NAME ``` ### Examples Set the policy group and policy name for a node named `test-node`: ``` knife node policy set test-node 'test-group' 'test-name' ``` run_list add ------------- A run-list defines all of the information necessary for Chef to configure a node into the desired state. A run-list is: * An ordered list of roles and/or recipes that are run in the exact order defined in the run-list; if a recipe appears more than once in the run-list, Chef Infra Client will not run it twice * Always specific to the node on which it runs; nodes may have a run-list that is identical to the run-list used by other nodes * Stored as part of the node object on the Chef server * Maintained using knife and then uploaded from the workstation to the Chef Infra Server, or maintained using Chef Automate Use the `run_list add` argument to add run-list items (roles or recipes) to a node. A run-list must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: ``` "role[NAME]" ``` or ``` "recipe[COOKBOOK::RECIPE]" ``` Use a comma to separate roles and recipes when adding more than one item the run-list: ``` "recipe[COOKBOOK::RECIPE],COOKBOOK::RECIPE,role[NAME]" ``` ### Syntax This argument has the following syntax: ``` knife node run_list add NODE_NAME RUN_LIST_ITEM (options) ``` Warning When running knife in Microsoft Windows, a string may be interpreted as a wildcard pattern when quotes are not present in the command. The number of quotes to use depends on the shell from which the command is being run. When running knife from the command prompt, a string should be surrounded by single quotes (`' '`). For example: ``` knife node run_list set test-node 'recipe[iptables]' ``` When running knife from Windows PowerShell, a string should be surrounded by triple single quotes (`''' '''`). For example: ``` knife node run_list set test-node '''recipe[iptables]''' ``` Note The Chef Client 12.4 release adds an optional feature to the Microsoft Installer Package (MSI) for Chef. This feature enables the ability to pass quoted strings from the Windows PowerShell command line without the need for triple single quotes (`''' '''`). This feature installs a Windows PowerShell module (typically in `C:\opscode\chef\modules`) that is also appended to the `PSModulePath` environment variable. This feature is not enabled by default. To activate this feature, run the following command from within Windows PowerShell: ``` Import-Module chef ``` or add `Import-Module chef` to the profile for Windows PowerShell located at: ``` ~\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 ``` This module exports cmdlets that have the same name as the command-line tools—chef-client, knife—that are built into Chef. For example: ``` knife exec -E 'puts ARGV' """&s0meth1ng""" ``` is now: ``` knife exec -E 'puts ARGV' '&s0meth1ng' ``` and: ``` knife node run_list set test-node '''role[ssssssomething]''' ``` is now: ``` knife node run_list set test-node 'role[ssssssomething]' ``` To remove this feature, run the following command from within Windows PowerShell: ``` Remove-Module chef ``` ### Options This argument has the following options: `-a ITEM`, `--after ITEM` Add a run-list item after the specified run-list item. `-b ITEM`, `--before ITEM` Add a run-list item before the specified run-list item. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Add a role** To add a role to a run-list, enter: ``` knife node run_list add NODE_NAME 'role[ROLE_NAME]' ``` **Add roles and recipes** To add roles and recipes to a run-list, enter: ``` knife node run_list add NODE_NAME 'recipe[COOKBOOK::RECIPE_NAME],recipe[COOKBOOK::RECIPE_NAME],role[ROLE_NAME]' ``` **Add a recipe with a FQDN** To add a recipe to a run-list using the fully qualified format, enter: ``` knife node run_list add NODE_NAME 'recipe[COOKBOOK::RECIPE_NAME]' ``` **Add a recipe with a cookbook** To add a recipe to a run-list using the cookbook format, enter: ``` knife node run_list add NODE_NAME 'COOKBOOK::RECIPE_NAME' ``` **Add the default recipe** To add the default recipe of a cookbook to a run-list, enter: ``` knife node run_list add NODE_NAME 'COOKBOOK' ``` run_list remove ---------------- Use the `run_list remove` argument to remove run-list items (roles or recipes) from a node. A recipe must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: `'role[ROLE_NAME]'` or `'recipe[COOKBOOK::RECIPE_NAME]'`. Use a comma to separate roles and recipes when removing more than one, like this: `'recipe[COOKBOOK::RECIPE_NAME],COOKBOOK::RECIPE_NAME,role[ROLE_NAME]'`. ### Syntax This argument has the following syntax: ``` knife node run_list remove NODE_NAME RUN_LIST_ITEM ``` ### Options This command does not have any specific options. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Remove a role** To remove a role from a run-list, enter: ``` knife node run_list remove NODE_NAME 'role[ROLE_NAME]' ``` **Remove a run-list** To remove a recipe from a run-list using the fully qualified format, enter: ``` knife node run_list remove NODE_NAME 'recipe[COOKBOOK::RECIPE_NAME]' ``` run_list set ------------- Use the `run_list set` argument to set the run-list for a node. A recipe must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: `"role[ROLE_NAME]"` or `"recipe[COOKBOOK::RECIPE_NAME]"`. Use a comma to separate roles and recipes when setting more than one, like this: `"recipe[COOKBOOK::RECIPE_NAME],COOKBOOK::RECIPE_NAME,role[ROLE_NAME]"`. ### Syntax This argument has the following syntax: ``` knife node run_list set NODE_NAME RUN_LIST_ITEM ``` Warning When running knife in Microsoft Windows, a string may be interpreted as a wildcard pattern when quotes are not present in the command. The number of quotes to use depends on the shell from which the command is being run. When running knife from the command prompt, a string should be surrounded by single quotes (`' '`). For example: ``` knife node run_list set test-node 'recipe[iptables]' ``` When running knife from Windows PowerShell, a string should be surrounded by triple single quotes (`''' '''`). For example: ``` knife node run_list set test-node '''recipe[iptables]''' ``` Note The Chef Client 12.4 release adds an optional feature to the Microsoft Installer Package (MSI) for Chef. This feature enables the ability to pass quoted strings from the Windows PowerShell command line without the need for triple single quotes (`''' '''`). This feature installs a Windows PowerShell module (typically in `C:\opscode\chef\modules`) that is also appended to the `PSModulePath` environment variable. This feature is not enabled by default. To activate this feature, run the following command from within Windows PowerShell: ``` Import-Module chef ``` or add `Import-Module chef` to the profile for Windows PowerShell located at: ``` ~\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 ``` This module exports cmdlets that have the same name as the command-line tools—chef-client, knife—that are built into Chef. For example: ``` knife exec -E 'puts ARGV' """&s0meth1ng""" ``` is now: ``` knife exec -E 'puts ARGV' '&s0meth1ng' ``` and: ``` knife node run_list set test-node '''role[ssssssomething]''' ``` is now: ``` knife node run_list set test-node 'role[ssssssomething]' ``` To remove this feature, run the following command from within Windows PowerShell: ``` Remove-Module chef ``` ### Options This command does not have any specific options. ### Examples None. show ---- Use the `show` argument to display information about a node. ### Syntax This argument has the following syntax: ``` knife node show NODE_NAME (options) ``` ### Options This argument has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. `-F json`, `--format=json` Display output as JSON. `-l`, `--long` Display all attributes in the output. `-m`, `--medium` Display normal attributes in the output. `-r`, `--run-list` Show only the run-list. ### Examples The following examples show how to use this knife subcommand: **Show all data about nodes** To view all data for a node named `build`, enter: ``` knife node show build ``` to return: ``` Node Name: build Environment: _default FQDN: IP: Run List: Roles: Recipes: Platform: ``` **Show basic information about nodes** To show basic information about a node, truncated and nicely formatted: ``` knife node show NODE_NAME ``` **Show all data about nodes, truncated** To show all information about a node, nicely formatted: ``` knife node show -l NODE_NAME ``` **Show attributes** To list a single node attribute: ``` knife node show NODE_NAME -a ATTRIBUTE_NAME ``` where `ATTRIBUTE_NAME` is something like `kernel` or `platform`. To list a nested attribute: ``` knife node show NODE_NAME -a ATTRIBUTE_NAME.NESTED_ATTRIBUTE_NAME ``` where `ATTRIBUTE_NAME` is something like `kernel` and `NESTED_ATTRIBUTE_NAME` is something like `machine`. **Show the FQDN** To view the FQDN for a node named `i-12345678`, enter: ``` knife node show i-12345678 -a fqdn ``` to return: ``` fqdn: ip-10-251-75-20.ec2.internal ``` **Show a run-list** To view the run-list for a node named `dev`, enter: ``` knife node show dev -r ``` **Show as JSON data** To view information in JSON format, use the `-F` common option; use a command like this for a node named `devops`: ``` knife node show devops -F json ``` Other formats available include `text`, `yaml`, and `pp`. **Show as raw JSON data** To view node information in raw JSON, use the `-l` or `--long` option: ``` knife node show -l -F json NODE_NAME ``` and/or: ``` knife node show -l --format=json NODE_NAME ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_node/knife opc ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/plugin_knife_opc.md) The `knife opc` subcommand is used to manage organizations and users in Chef Server 12. Note Administrator permissions are required to add, remove, or edit users. To manage organizations, or change a user’s assignment to an organization, the pivotal key is required. Rather than using the knife-opc plugin commands below, which are an implementation detail, use the equivalent “user-” and “org-” subcommands directly on the Chef Infra Server. Those wrappered subcommands already have the needed permissions applied and access to sensitive commands will then be centralized. [See chef-server-ctl for details](../../ctl_chef_server/index). Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. config.rb Configuration [plugin_knife_opc-knife-rb-configuration] =================================================================== Unlike other knife subcommands the subcommands in the knife-opc plugin make API calls against the root of your Chef Infra Server installation’s API endpoint. Typically the `chef_server_url` for your Chef Infra Server installation may look like this: ``` chef_server_url 'https://chef.yourdomain.com/organizations/ORG_NAME' ``` To configure knife-opc, set the `chef_server_root` option to the root of your Chef Infra Server installation: ``` chef_server_root 'https://chef.yourdomain.com/' ``` If your `chef_server_url` configuration ends with `/organizations/ORG_NAME` (as shown above), this setting will default to `https://chef.yourdomain.com/`. Note On Chef Server 12, the majority of the commands provided by this plugin can be accessed via `chef-server-ctl` wrapper commands. [See chef-server-ctl for details](../../ctl_chef_server/index). opc user list [plugin_knife_opc-opc-user-list] ================================================ Show a list of all users in your Chef Infra Server installation. ### Syntax This argument has the following syntax: ``` knife opc user list (options) ``` ### Options This argument has the following options: `-w`, `--with-uri` Show corresponding URIs. ### Example ``` knife opc user list alice pivotal knife opc user list -w alice: https://chef-server.fqdn/users/alice pivotal: https://chef-server.fqdn/users/pivotal ``` opc user show ------------- Shows the details of a user in your Chef Infra Server installation. ### Syntax This argument has the following syntax: ``` knife opc user show USER_NAME (options) ``` ### Options This argument has the following options: `-l`, `--with-orgs` Show the organizations of which the user is a member. ### Example ``` knife opc user show alice -l display_name: <NAME> email: <EMAIL> first_name: Alice last_name: Schmidt middle_name: organizations: acme public_key: -----BEGIN PUBLIC KEY----- [...] -----END PUBLIC KEY----- username: alice ``` opc user create [plugin_knife_opc-opc-user-create] ==================================================== Creates a new user in your Chef Infra Server installation. The user’s private key will be returned in response. ### Syntax This argument has the following syntax: ``` knife opc user create USER_NAME FIRST_NAME [MIDDLE_NAME] LAST_NAME EMAIL PASSWORD (options) ``` ### Options This argument has the following options: `-f FILENAME`, `--filename FILENAME` Write private key to `FILENAME` rather than `STDOUT`. ### Example ``` knife opc user create arno arno schmidt <EMAIL> password -----BEGIN RSA PRIVATE KEY----- [...] -----END RSA PRIVATE KEY----- ``` opc user delete --------------- Deletes the given OPC user. ### Syntax This argument has the following syntax: ``` knife opc user delete USER_NAME [-d] [-R] ``` ### Options This argument has the following options: `-d`, `--no-disassociate-user` Don’t disassociate the user first. `-R`, `--remove-from-admin-groups` If the user is a member of any org admin groups, attempt to remove from those groups. Ignored if `--no-disassociate-user` is set. ### Example ``` knife opc user delete arno Do you want to delete the user arno? (Y/N) Y Checking organization memberships... Deleting user arno. ``` opc user edit ------------- Will open `$EDITOR` to edit a user. When finished editing, knife will update the given Chef Infra Server user. ### Syntax This argument has the following syntax: ``` knife opc user edit USER_NAME ``` Example [plugin_knife_opc-opc-user-password] ---------------------------------------------- ``` EDITOR=ed knife opc user edit arno 639 1,%p { "username": "arno", "email": "<EMAIL>", "display_name": "<NAME>", "first_name": "arno", "last_name": "schmidt", "middle_name": "", "public_key": "-----BEGIN PUBLIC KEY-----\n[...]\n-----END PUBLIC KEY-----\n\n" } /email/s/chef.io/opscode.com/p "email": "<EMAIL>", wq 643 Saved arno. knife opc user show arno display_name: <NAME> email: <EMAIL> first_name: arno last_name: schmidt middle_name: public_key: -----BEGIN PUBLIC KEY----- [...] -----END PUBLIC KEY----- username: arno ``` opc user password ----------------- Command for managing password and authentication for a user. ### Syntax This argument has the following syntax: ``` knife opc user password USER_NAME [PASSWORD | --enable_external_auth] ``` The last argument should either be a string to use as password or `--enable_external_auth` instead of a password to enable external authentication for this user. ### Example ``` knife opc user password arno newpassword {"username"=>"arno", "email"=>"<EMAIL>", "display_name"=>"<NAME>", "first_name"=>"arno", "last_name"=>"schmidt", "middle_name"=>"", "public_key"=>"-----BEGIN PUBLIC KEY-----\n[...]\n-----END PUBLIC KEY-----\n\n", "password"=>"newpassword", "recovery_authentication_enabled"=>true} Authentication info updated for arno. ``` opc org list [plugin_knife_opc-opc-org-list] ============================================== Show a list of all organizations in your Chef Infra Server installation. ### Syntax This argument has the following syntax: ``` knife opc org list (options) ``` ### Options This argument has the following options: `-w`, `--with-uri` Show corresponding URIs. `-a`, `--all-orgs` Display auto-generated hidden orgs. ### Example ``` knife opc org list -w -a acme: https://chef-server.fqdn/organizations/acme ``` opc org show [plugin_knife_opc-opc-org-show] ============================================== Shows the details of an organization in your Chef Infra Server installation. ### Syntax This argument has the following syntax: ``` knife opc org show ORG_NAME ``` ### Example ``` knife opc org show acme full_name: Acme guid: cc9f9d0d4f6e7e35272e327e22e7affc name: acme ``` opc org create [plugin_knife_opc-opc-org-create] ================================================== Creates a new Chef Infra Server organization. The private key for the organization’s validator client is returned. ### Syntax This argument has the following syntax: ``` knife opc org create ORG_NAME ORG_FULL_NAME (options) ``` ### Options This argument has the following options: `-f FILENAME`, `--filename FILENAME` Write private key to `FILENAME` rather than `STDOUT`. `-a USER_NAME`, `--association_user USER_NAME` Associate `USER_NAME` with the organization after creation. ### Example ``` knife opc org create acme2 "The Other Acme" -a arno -----BEGIN RSA PRIVATE KEY----- [...] -----BEGIN RSA PRIVATE KEY----- ``` opc org delete [plugin_knife_opc-opc-org-delete] ================================================== Deletes the given Chef Infra Server organization. ### Syntax This argument has the following syntax: ``` knife opc org delete ORG_NAME ``` ### Example ``` knife opc org delete acme2 Do you want to delete the organization acme2? (Y/N) Y full_name: The Other Acme guid: 2adec1140cf777a15d82d9099304da71 name: acme2 ``` opc org user add ---------------- Adds a user to an organization. Requires that the named organization and user both exist. ### Syntax This argument has the following syntax: ``` knife opc org user add ORG_NAME USER_NAME ``` ### Example ``` knife opc org user add acme2 alice ``` opc org user remove =================== Removes a user from an organization. Requires that the named organization and user both exist, and that the user is currently associated with the organization. ### Syntax This argument has the following syntax: ``` knife opc org user remove ORG_NAME USER_NAME ``` ### Example ``` knife opc org user remove acme2 alice ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/plugin_knife_opc/knife raw ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_raw.md) Use the `knife raw` subcommand to send a REST request to an endpoint in the Chef Infra Server API. Syntax ------ This subcommand has the following syntax: ``` knife raw REQUEST_PATH (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-i FILE`, `--input FILE` The name of a file to be used with the `PUT` or a `POST` request. `--[no-]pretty` Use `--no-pretty` to disable pretty-print output for JSON. Default: `--pretty`. `-m METHOD`, `--method METHOD` The request method: `DELETE`, `GET`, `POST`, or `PUT`. Default value: `GET`. `--proxy-auth` Enable proxy authentication to the Chef Infra Server web user interface. Default value: `false`. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **View a client** To view information about a client: ``` knife raw /clients/<client_name``` **View a node** To view information about a node: ``` knife raw /nodes/<node_name``` **Delete a data bag** To delete a data bag, enter a command similar to: ``` knife raw -m DELETE /data/foo ``` to return something similar to: ``` { "name":"foo", "json_class":"Chef::DataBag", "chef_type":"data_bag" } ``` **Delete a role** To delete a role, enter a command similar to: ``` knife raw -m DELETE /roles/role-foo.json ``` to return something similar to: ``` { "name":"role-foo", "json_class":"Chef::Role", "chef_type":"role" } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_raw/knife environment ================= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_environment.md) An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. Use the `knife environment` subcommand to manage environments within a single organization on the Chef Infra Server. Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. compare ------- Use the `compare` argument to compare the cookbook version constraints that are set on one (or more) environments. ### Syntax This argument has the following syntax: ``` knife environment compare [ENVIRONMENT_NAME...] (options) ``` ### Options This argument has the following options: `-a`, `--all` Upload all environments found at the specified path. `-m`, `--mismatch` Show only matching versions. ### Examples The following examples show how to use this knife subcommand: **Compare cookbook versions in a single environment** To compare cookbook versions for a single environment: ``` knife environment compare development ``` to return something similar to: ``` development apache 2.3.1 windows 4.1.2 ``` **Compare cookbook versions for multiple environments** To compare cookbook versions for multiple environments: ``` knife environment compare development staging ``` to return something similar to: ``` development staging apache 2.3.1 1.2.2 windows 4.1.2 1.0.0 postgresql 1.0.0 1.0.0 ``` **Compare cookbook versions for all environments** To compare all cookbook versions for all environments: ``` knife environment compare --all ``` to return something similar to: ``` staging development ulimit latest latest redisio latest latest journly latest latest aws latest latest test latest latest unicorn latest latest sensu latest latest runit latest latest templater latest latest powershell latest latest openssl latest latest rbenv latest latest rabbitmq latest latest postgresql latest latest mysql latest latest ohai latest latest git latest latest erlang latest latest ssh_known_hosts latest latest nginx latest latest database latest latest yum latest latest xfs latest latest apt latest latest dmg latest latest chef_handler latest latest windows 1.0.0 4.1.2 ``` create ------ Use the `create` argument to add an environment object to the Chef Infra Server. When this argument is run, knife will open $EDITOR to enable editing of the `ENVIRONMENT` description field (unless a description is specified as part of the command). When finished, knife will add the environment to the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife environment create ENVIRONMENT_NAME -d --description ENVIRONMENT_DESCRIPTION ``` ### Options This argument has the following options: `--description DESCRIPTION` The description of the environment. This value populates the description field for the environment on the Chef Infra Server. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create an environment** To create an environment named `dev` with a description of `The development environment.`: ``` knife environment create dev -d --description "The development environment." ``` delete ------ Use the `delete` argument to delete an environment from a Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife environment delete ENVIRONMENT_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Delete an environment** To delete an environment named `dev`, enter: ``` knife environment delete dev ``` Type `Y` to confirm a deletion. edit ---- Use the `edit` argument to edit the attributes of an environment. When this argument is run, knife will open $EDITOR to enable editing of `ENVIRONMENT` attributes. When finished, knife will update the Chef Infra Server with those changes. ### Syntax This argument has the following syntax: ``` knife environment edit ENVIRONMENT_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Edit an environment** To edit an environment named `devops`, enter: ``` knife environment edit devops ``` from file --------- Use the `from file` argument to add or update an environment using a JSON or Ruby DSL description. ### Syntax This argument has the following syntax: ``` knife environment from file FILE (options) ``` ### Options This argument has the following options: `-a`, `--all` Upload all environments found at the specified path. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create an environment from a JSON file** To add an environment using data contained in a JSON file: ``` knife environment from file "path to JSON file" ``` list ---- Use the `list` argument to list all of the environments that are currently available on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife environment list -w ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### Examples The following examples show how to use this knife subcommand: **View a list of environments** To view a list of environments: ``` knife environment list -w ``` show ---- Use the `show` argument to display information about the specified environment. ### Syntax This argument has the following syntax: ``` knife environment show ENVIRONMENT_NAME ``` ### Options This argument has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. ### Examples The following examples show how to use this knife subcommand: **Show environments** To view information about the `dev` environment enter: ``` knife environment show dev ``` to return: ``` % knife environment show dev chef_type: environment cookbook_versions: default_attributes: description: json_class: Chef::Environment name: dev override_attributes: \\ \\ \\ \\ ``` **Show environments as JSON** To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife environment show devops -F json ``` Other formats available include `text`, `yaml`, and `pp`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_environment/knife org ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_org.md) The `knife org` subcommand is used to manage organizations and users in Chef Infra Server. Note The recommended best practice is to use the Chef Infra Server `user-` and `org-` commands to manage organizations and users instead of this subcommand. The Chef Infra Server command line tool already has the permissions that you need to manage organizations and users. Using Chef Infra Server commands centralizes the access and application of sensitive commands, which is important for system security and security audits. See the [chef-server-ctl](../../ctl_chef_server/index) documentation for more information. Required Permissions -------------------- * Administrator permissions are required to add, remove, or edit users. * The pivotal key is required to manage organizations, or change a user’s assignment to an organization. The knife [common options](../knife_options/index) are available to this (and all) knife subcommands and plugins. config.rb Setup --------------- Unlike other knife subcommands the subcommands in the `knife-org` plugin make API calls to the root of your Chef Infra Server API endpoints. The `chef_server_url` for your Chef Infra Server installation typically looks like this: ``` chef_server_url 'https://chef.yourdomain.com/organizations/ORG_NAME' ``` To configure knife-opc, set the `chef_server_root` option to the root of your Chef Infra Server installation: ``` chef_server_root 'https://chef.yourdomain.com/' ``` If your `chef_server_url` configuration ends with `/organizations/ORG_NAME` (as shown above), this setting defaults to `https://chef.yourdomain.com/`. Note User subcommands or options are added under `knife user`. See the [knife user](../knife_user/index) documentation for more information. org create ---------- Creates a new Chef Infra Server organization. The private key for the organization’s validator client is returned. ### Syntax This argument has the following syntax: ``` knife org create ORG_NAME ORG_FULL_NAME (options) ``` ### Options This argument has the following options: `-f FILENAME`, `--filename FILENAME` Write private key to `FILENAME` rather than `STDOUT`. `-a USER_NAME`, `--association_user USER_NAME` Associate `USER_NAME` with the organization after creation. ### Example ``` knife org create acme2 "The Other Acme" -a arno -----BEGIN RSA PRIVATE KEY----- [...] -----BEGIN RSA PRIVATE KEY----- ``` org list -------- Show a list of all organizations in your Chef Infra Server installation. ### Syntax This argument has the following syntax: ``` knife org list (options) ``` ### Options This argument has the following options: `-w`, `--with-uri` Show corresponding URIs. `-a`, `--all-orgs` Display auto-generated hidden orgs. ### Example ``` knife org list -w -a acme: https://chef-server.fqdn/organizations/acme ``` org show -------- Shows the details of an organization in your Chef Infra Server installation. ### Syntax This argument has the following syntax: ``` knife org show ORG_NAME ``` ### Example ``` knife org show acme full_name: Acme guid: cc9f9d0d4f6e7e35272e327e22e7affc name: acme ``` org edit -------- Edits the given Chef Infra Server organization. ### Syntax This argument has the following syntax: ``` knife org edit ORG_NAME ``` ### Example ``` knife org edit Acme -e nano {"name"=>"Acme", "full_name"=>"<NAME>", "guid"=>"dea05074c4566f81d9d3228f4ad9bcd3"} Saved Acme. ``` org delete ---------- Deletes the given Chef Infra Server organization. ### Syntax This argument has the following syntax: ``` knife org delete ORG_NAME ``` ### Example ``` knife org delete acme2 Do you want to delete the organization acme2? (Y/N) Y full_name: The Other Acme guid: 2adec1140cf777a15d82d9099304da71 name: acme2 ``` org user add ------------ Adds a user to an organization. Requires that the named organization and user both exist. ### Syntax This argument has the following syntax: ``` knife org user add ORG_NAME USER_NAME ``` ### Options This argument has the following options: `-a`, `--admin` Add user to admin group. ### Example ``` knife org user add acme2 alice ``` org user remove --------------- Removes a user from an organization. Requires that the named organization and user both exist, and that the user is currently associated with the organization. ### Syntax This argument has the following syntax: ``` knife org user remove ORG_NAME USER_NAME ``` ### Options This argument has the following options: `-f`, `--force` Force removal of user from the organization’s admins and billing-admins group. ### Example ``` knife org user remove acme2 alice ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_org/knife show ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_show.md) Use the `knife show` subcommand to view the details of one (or more) objects on the Chef Infra Server. This subcommand works similar to `knife cookbook show`, `knife data bag show`, `knife environment show`, `knife node show`, and `knife role show`, but with a single verb (and a single action). Syntax ------ This subcommand has the following syntax: ``` knife show [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--local` Show local files instead of remote files. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. `-S SEPARATOR`, `--field-separator SEPARATOR` Character separator used to delineate nesting in –attribute filters. For example, to use a colon as the delimiter, specify `-S:` in your `knife node show` subcommand. Default is `.` Examples -------- The following examples show how to use this knife subcommand: **Show all cookbooks** To show all cookbooks in the `cookbooks/` directory: ``` knife show cookbooks/ ``` or, (if already in the `cookbooks/` directory in the local chef-repo): ``` knife show ``` **Show roles and environments** ``` knife show roles/ environments/ ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_show/knife recipe list ================= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_recipe_list.md) Use the `knife recipe list` subcommand to view all of the recipes that are on a Chef Infra Server. A regular expression can be used to limit the results to recipes that match a specific pattern. The regular expression must be within quotes and not be surrounded by forward slashes (/). Syntax ------ This subcommand has the following syntax: ``` knife recipe list REGEX ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This command does not have any specific options. Examples -------- The following examples show how to use this knife subcommand: **View a list of recipes** To view a list of recipes: ``` knife recipe list 'couchdb::*' ``` to return: ``` couchdb::main_monitors couchdb::master couchdb::default couchdb::org_cleanup ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_recipe_list/knife search ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_search.md) Search indexes allow queries to be made for any type of data that is indexed by the Chef Infra Server, including data bags (and data bag items), environments, nodes, and roles. A defined query syntax is used to support search patterns like exact, wildcard, range, and fuzzy. A search is a full-text query that can be done from several locations, including from within a recipe, by using the `search` subcommand in knife, the `search` method in the Chef Infra Language, the search box in the Chef management console, and by using the `/search` or `/search/INDEX` endpoints in the Chef Infra Server API. The search engine is based on Elasticsearch and is run from the Chef Infra Server. Use the `knife search` subcommand to run a search query for information that is indexed on a Chef Infra Server. Syntax ------ This subcommand has the following syntax: ``` knife search INDEX SEARCH_QUERY ``` where `INDEX` is one of `client`, `environment`, `node`, `role`, or the name of a data bag and `SEARCH_QUERY` is the search query syntax for the query that will be executed. `INDEX` is implied if omitted, and will default to `node`. For example: ``` knife search '*:*' -i ``` will return something similar to: ``` 8 items found centos-62-dev opensuse-15 ubuntu-1804-orgtest ubuntu-1804-ohai-test ubuntu-1804-ifcfg-test ohai-test win2k19-dev ``` and is the same search as: ``` knife search node '*:*' -i ``` If the `SEARCH_QUERY` does not contain a colon character (`:`), then the default query pattern is `tags:*#{@query}* OR roles:*#{@query}* OR fqdn:*#{@query}* OR addresses:*#{@query}*`, which means the following two search queries are effectively the same: ``` knife search ubuntu ``` or: ``` knife search node "tags:*ubuntu* OR roles:*ubuntu* OR fqdn:*ubuntu* (etc.)" ``` ### Query Syntax A search query is comprised of two parts: the key and the search pattern. A search query has the following syntax: ``` key:search_pattern ``` where `key` is a field name that is found in the JSON description of an indexable object on the Chef Infra Server (a role, node, client, environment, or data bag) and `search_pattern` defines what will be searched for, using one of the following search patterns: exact, wildcard, range, or fuzzy matching. Both `key` and `search_pattern` are case-sensitive; `key` has limited support for multiple character wildcard matching using an asterisk ("*") (and as long as it is not the first character). ### Keys A field name/description pair is available in the JSON object. Use the field name when searching for this information in the JSON object. Any field that exists in any JSON description for any role, node, Chef Infra Client, environment, or data bag can be searched. To search for the available fields for a particular object, use the `show` argument with any of the following knife subcommands: `knife client`, `knife data bag`, `knife environment`, `knife node`, or `knife role`. For example: `knife data bag show`. #### Nested Fields A nested field appears deeper in the JSON data structure. For example, information about a network interface might be several layers deep: `node['network']['interfaces']['en1']`. When nested fields are present in a JSON structure, Chef Infra Client will extract those nested fields to the top-level, flattening them into compound fields that support wildcard search patterns. By combining wildcards with range-matching patterns and wildcard queries, it is possible to perform very powerful searches, such as using the vendor part of the MAC address to find every node that has a network card made by the specified vendor. Consider the following snippet of JSON data: ``` {"network": [ //snipped... "interfaces", {"en1": { "number": "1", "flags": [ "UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST" ], "addresses": { "fe80::fa1e:dfff:fed8:63a2": { "scope": "Link", "prefixlen": "64", "family": "inet6" }, "f8:1e:df:d8:63:a2": { "family": "lladdr" }, "192.0.2.0": { "netmask": "255.255.255.0", "broadcast": "192.168.0.255", "family": "inet" } }, "mtu": "1500", "media": { "supported": { "autoselect": { "options": [ ] } }, "selected": { "autoselect": { "options": [ ] } } }, "type": "en", "status": "active", "encapsulation": "Ethernet" }, //snipped... ``` Before this data is indexed on the Chef Infra Server, the nested fields are extracted into the top level, similar to: ``` "broadcast" => "192.168.0.255", "flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"] "mtu" => "1500" ``` which allows searches like the following to find data that is present in this node: ``` node "broadcast:192.168.0.*" ``` or: ``` node "mtu:1500" ``` or: ``` node "flags:UP" ``` This data is also flattened into various compound fields, which follow the same pattern as the JSON hierarchy and use underscores (`_`) to separate the levels of data, similar to: ``` # ...snip... "network_interfaces_en1_addresses_192.0.2.0_broadcast" => "192.168.0.255", "network_interfaces_en1_addresses_fe80::fa1e:tldr_family" => "inet6", "network_interfaces_en1_addresses" => ["fe80::fa1e:tldr","f8:1e:df:tldr","192.0.2.0"] # ...snip... ``` which allows searches like the following to find data that is present in this node: ``` node "network_interfaces_en1_addresses:192.0.2.0" ``` This flattened data structure also supports using wildcard compound fields, which allow searches to omit levels within the JSON data structure that are not important to the search query. In the following example, an asterisk (`*`) is used to show where the wildcard can exist when searching for a nested field: ``` "network_interfaces_*_flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"] "network_interfaces_*_addresses" => ["fe80::fa1e:dfff:fed8:63a2", "192.0.2.0", "f8:1e:df:d8:63:a2"] "network_interfaces_en0_media_*" => ["autoselect", "none", "1000baseT", "10baseT/UTP", "100baseTX"] "network_interfaces_en1_*" => ["1", "UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST", "fe80::fa1e:dfff:fed8:63a2", "f8:1e:df:d8:63:a2", "192.0.2.0", "1500", "supported", "selected", "en", "active", "Ethernet"] ``` For each of the wildcard examples above, the possible values are shown contained within the brackets. When running a search query, the query syntax for wildcards is to simply omit the name of the node (while preserving the underscores), similar to: ``` network_interfaces__flags ``` This query will search within the `flags` node, within the JSON structure, for each of `UP`, `BROADCAST`, `SMART`, `RUNNING`, `SIMPLEX`, and `MULTICAST`. #### Examples To see the available keys for a node, enter the following (for a node named `staging`): ``` knife node show staging -Fj | less ``` to return a full JSON description of the node and to view the available keys with which any search query can be based. To use a question mark (`?`) to replace a single character in a wildcard search, enter the following: ``` knife search node 'platfor?:ubuntu' ``` To use an asterisk (`*`) to replace zero (or more) characters in a wildcard search, enter the following: ``` knife search node 'platfo*:ubuntu' ``` To find all IP address that are on the same network, enter the following: ``` knife search node 'ipaddress:192.168*' ``` where `192.168*` is the network address for which the search will be run. To use a range search to find IP addresses within a subnet, enter the following: ``` knife search node 'ipaddress:[192.168.0.* TO 192.0.2.*]' ``` where `192.168.0.* TO 192.0.2.*` defines the subnet range. ### About Patterns A search pattern is a way to fine-tune search results by returning anything that matches some type of incomplete search query. There are four types of search patterns that can be used when searching the search indexes on the Chef Infra Server: exact, wildcard, range, and fuzzy. #### Exact Matching An exact matching search pattern is used to search for a key with a name that exactly matches a search query. If the name of the key contains spaces, quotes must be used in the search pattern to ensure the search query finds the key. The entire query must also be contained within quotes, so as to prevent it from being interpreted by Ruby or a command shell. The best way to ensure that quotes are used consistently is to quote the entire query using single quotes (' ‘) and a search pattern with double quotes (" “). To search in a specific data bag for a specific data bag item, enter the following: ``` knife search admins 'id:charlie' ``` where `admins` is the name of the data bag and `charlie` is the name of the data bag item. Something similar to the following will be returned: ``` 1 items found _rev: 1-39ff4099f2510f477b4c26bef81f75b9 chef_type: data_bag_item comment: Charlie the Unicorn data_bag: admins gid: ops id: charlie shell: /bin/zsh uid: 1005 ``` To search in a specific data bag using a string to find any matching data bag item, enter the following: ``` knife search admins 'comment:"<NAME>"' ``` where `admins` is the name of the data bag and `<NAME>` is the string that will be used during the search. Something similar to the following will be returned: ``` 1 items found _rev: 1-39ff4099f2510f477b4c26bef81f75b9 chef_type: data_bag_item comment: <NAME> data_bag: admins gid: ops id: charlie shell: /bin/zsh uid: 1005 ``` #### Wildcard Matching A wildcard matching search pattern is used to query for substring matches that replace zero (or more) characters in the search pattern with anything that could match the replaced character. There are two types of wildcard searches: * A question mark (`?`) can be used to replace exactly one character (as long as that character is not the first character in the search pattern) * An asterisk (`*`) can be used to replace any number of characters (including zero) To search for any node that contains the specified key, enter the following: ``` knife search node 'foo:*' ``` where `foo` is the name of the node. To search for a node using a partial name, enter one of the following: ``` knife search node 'name:app*' ``` or: ``` knife search node 'name:app1*.example.com' ``` or: ``` knife search node 'name:app?.example.com' ``` or: ``` knife search node 'name:app1.example.???' ``` to return `app1.example.com` (and any other node that matches any of the string searches above). #### Range Matching A range matching search pattern is used to query for values that are within a range defined by upper and lower boundaries. A range matching search pattern can be inclusive or exclusive of the boundaries. Use square brackets ("[ ]") to denote inclusive boundaries and curly braces ("{ }") to denote exclusive boundaries and with the following syntax: ``` boundary TO boundary ``` where `TO` is required (and must be capitalized). A data bag named `sample` contains four data bag items: `abc`, `bar`, `baz`, and `quz`. All of the items in-between `bar` and `foo`, inclusive, can be searched for using an inclusive search pattern. To search using an inclusive range, enter the following: ``` knife search sample "id:[bar TO foo]" ``` where square brackets (`[ ]`) are used to define the range. A data bag named `sample` contains four data bag items: `abc`, `bar`, `baz`, and `quz`. All of the items that are exclusive to `bar` and `foo` can be searched for using an exclusive search pattern. To search using an exclusive range, enter the following: ``` knife search sample "id:{bar TO foo}" ``` where curly braces (`{ }`) are used to define the range. #### Fuzzy Matching A fuzzy matching search pattern is used to search based on the proximity of two strings of characters. An (optional) integer may be used as part of the search query to more closely define the proximity. A fuzzy matching search pattern has the following syntax: ``` "search_query"~edit_distance ``` where `search_query` is the string that will be used during the search and `edit_distance` is the proximity. A tilde ("~") is used to separate the edit distance from the search query. To use a fuzzy search pattern enter something similar to: ``` knife search client "name:boo~" ``` where `boo~` defines the fuzzy search pattern. This will return something similar to: ``` { "total": 1, "start": 0, "rows": [ { "public_key": "too long didn't read", "name": "foo", "_rev": "1-f11a58043906e33d39a686e9b58cd92f", "json_class": "Chef::ApiClient", "admin": false, "chef_type": "client" } ] } ``` ### About Operators An operator can be used to ensure that certain terms are included in the results, are excluded from the results, or are not included even when other aspects of the query match. Searches can use the following operators: | Operator | Description | | --- | --- | | `AND` | Use to find a match when both terms exist. | | `OR` | Use to find a match if either term exists. | | `NOT` | Use to exclude the term after `NOT` from the search results. | Operators must be in ALL CAPS. Parentheses can be used to group clauses and to form sub-queries. Warning Using `AND NOT` together may trigger an error. For example: ``` ERROR: knife search failed: invalid search query: 'datacenter%3A123%20AND%20NOT%20hostname%3Adev-%20AND%20NOT%20hostanem%3Asyslog-' Parse error at offset: 38 Reason: Expected one of \ at line 1, column 42 (byte 42) after AND ``` Use `-` instead of `NOT`. For example: ``` knife search sample "id:foo AND -id:bar" ``` #### AND To join queries using the `AND` boolean operator, enter the following: ``` knife search sample "id:b* AND animal:dog" ``` to return something like: ``` { "total": 1, "start": 0, "rows": [ { "comment": "an item named baz", "id": "baz", "animal": "dog" } ] } ``` Or, to find all of the computers running on the Microsoft Windows platform that are associated with a role named `jenkins`, enter: ``` knife search node 'platform:windows AND roles:jenkins' ``` to return something like: ``` 2 items found Node Name: windows-server-2012r2.domain.com Environment: _default FQDN: windows-server-2012r2 IP: 0000::0000:0000:0000:0000 Run List: role[jenkins-windows] Roles: jenkins-windows, jenkins Recipes: jenkins-client::windows, jenkins::node_windows Platform: windows 6.3.9600 Tags: Node Name: 123-windows-2012r2-amd64-builder Environment: _default FQDN: ABC-1234567890AB IP: 123.45.6.78 Run List: role[123-windows-2012r2-amd64-builder] Roles: 123-windows-2012r2-amd64-builder, jenkins Recipes: jenkins::node_windows, git_windows Platform: windows 6.3.9600 Tags: ``` #### NOT To negate search results using the `NOT` boolean operator, enter the following: ``` knife search sample "(NOT id:foo)" ``` to return something like: ``` { "total": 4, "start": 0, "rows": [ { "comment": "an item named bar", "id": "bar", "animal": "cat" }, { "comment": "an item named baz", "id": "baz" "animal": "dog" }, { "comment": "an item named abc", "id": "abc", "animal": "unicorn" }, { "comment": "an item named qux", "id": "qux", "animal", "penguin" } ] } ``` #### OR To join queries using the `OR` boolean operator, enter the following: ``` knife search sample "id:foo OR id:abc" ``` to return something like: ``` { "total": 2, "start": 0, "rows": [ { "comment": "an item named foo", "id": "foo", "animal": "pony" }, { "comment": "an item named abc", "id": "abc", "animal": "unicorn" } ] } ``` ### Special Characters A special character can be used to fine-tune a search query and to increase the accuracy of the search results. The following characters can be included within the search query syntax, but each occurrence of a special character must be escaped with a backslash (`\`), also (`/`) must be escaped against the Elasticsearch: ``` + - && | | ! ( ) { } [ ] ^ " ~ * ? : \ / ``` For example: ``` \(1\+1\)\:2 ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. `-b ROW`, `--start ROW` The row at which return results begin. `-f FILTER`, `--filter-result FILTER` Use to filter the search output based on the pattern that matc the specified `FILTER`. Only attributes in the `FILTER` will returned. For example: `\"ServerName=name, Kernel=kernel.version\`. `-i`, `--id-only` Show only matching object IDs. `INDEX` The name of the index to be queried: `client`, `environment`, `node`, `role`, or `DATA_BAG_NAME`. Default index: `node`. `-l`, `--long` Display all attributes in the output and show the output as JSON. `-m`, `--medium` Display normal attributes in the output and to show the output as JSON. `-q SEARCH_QUERY`, `--query SEARCH_QUERY` Protect search queries that start with a hyphen (-). A `-q` query may be specified as an argument or an option, but not both. `-r`, `--run-list` Show only the run-list. `-R INT`, `--rows INT` The number of rows to be returned. `SEARCH_QUERY` The search query used to identify a list of items on a Chef Infra Server. This option uses the same syntax as the `search` subcommand. Examples -------- The following examples show how to use this knife subcommand: **Search by platform ID** To search for the IDs of all nodes running on the Amazon EC2 platform, enter: ``` knife search node 'ec2:*' -i ``` to return something like: ``` 4 items found ip-0A7CA19F.ec2.internal ip-0A58CF8E.ec2.internal ip-0A58E134.ec2.internal ip-0A7CFFD5.ec2.internal ``` **Search by instance type** To search for the instance type (flavor) of all nodes running on the Amazon EC2 platform, enter: ``` knife search node 'ec2:*' -a ec2.instance_type ``` to return something like: ``` 4 items found ec2.instance_type: m1.large id: ip-0A7CA19F.ec2.internal ec2.instance_type: m1.large id: ip-0A58CF8E.ec2.internal ec2.instance_type: m1.large id: ip-0A58E134.ec2.internal ec2.instance_type: m1.large id: ip-0A7CFFD5.ec2.internal ``` **Search by recipe** To search for recipes that are used by a node, use the `recipes` attribute to search for the recipe names, enter something like: ``` knife search node 'recipes:recipe_name' ``` or: ``` knife search node '*:*' -a recipes | grep 'recipe_name' ``` **Search by cookbook, then recipe** To search for cookbooks on a node, use the `recipes` attribute followed by the `cookbook::recipe` pattern, escaping both of the `:` characters. For example: ``` knife search node 'recipes:cookbook_name\:\:recipe_name' ``` **Search by node** To search for all nodes running Ubuntu, enter: ``` knife search node 'platform:ubuntu' ``` **Search by node and environment** To search for all nodes running CentOS in the production environment, enter: ``` knife search node 'chef_environment:production AND platform:centos' ``` **Search for nested attributes** To find a nested attribute, use a pattern similar to the following: ``` knife search node <query_to_run> -a <main_attribute>.<nested_attribute``` **Search for multiple attributes** To build a search query to use more than one attribute, use an underscore (`_`) to separate each attribute. For example, the following query will search for all nodes running a specific version of Ruby: ``` knife search node "languages_ruby_version:2.7.0" ``` **Search for nested attributes using a search query** To build a search query that can find a nested attribute: ``` knife search node name: <node_name> -a kernel.machine ``` **Use a test query** To test a search query that will be used in a `knife ssh` subcommand: ``` knife search node "role:web NOT name:web03" ``` where the query in the previous example will search all servers that have the `web` role, but not on the server named `web03`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_search/knife role ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_role.md) A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. Use the `knife role` subcommand to manage the roles that are associated with one or more nodes on a Chef Infra Server. Note To add a role to a node and then build out the run-list for that node, use the [knife node](../knife_node/index) subcommand and its `run_list add` argument. Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. bulk delete ----------- Use the `bulk delete` argument to delete one or more roles that match a pattern defined by a regular expression. The regular expression must be within quotes and not be surrounded by forward slashes (/). ### Syntax This argument has the following syntax: ``` knife role bulk delete REGEX ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Bulk delete roles** Use a regular expression to define the pattern used to bulk delete roles: ``` knife role bulk delete "^[0-9]{3}$" ``` create ------ Use the `create` argument to add a role to the Chef Infra Server. Role data is saved as JSON on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife role create ROLE_NAME (options) ``` ### Options This argument has the following options: `--description DESCRIPTION` The description of the role. This value populates the description field for the role on the Chef Infra Server. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create a role** To add a role named `role1`, enter: ``` knife role create role1 ``` In the $EDITOR enter the role data in JSON: ``` { "name": "role1", "default_attributes": { }, "json_class": "Chef::Role", "run_list": ["recipe[cookbook_name::recipe_name]", "role[role_name]" ], "description": "", "chef_type": "role", "override_attributes": { } } ``` When finished, save it. delete ------ Use the `delete` argument to delete a role from the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife role delete ROLE_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Delete a role** ``` knife role delete devops ``` Type `Y` to confirm a deletion. edit ---- Use the `edit` argument to edit role details on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife role edit ROLE_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Edit a role** To edit the data for a role named `role1`, enter: ``` knife role edit role1 ``` Update the role data in JSON: ``` { "name": "role1", "description": "This is the description for the role1 role.", "json_class": "Chef::Role", "default_attributes": { }, "override_attributes": { }, "chef_type": "role", "run_list": ["recipe[cookbook_name::recipe_name]", "role[role_name]" ], "env_run_lists": { }, } ``` When finished, save it. from file --------- Use the `from file` argument to create a role using existing JSON data as a template. ### Syntax This argument has the following syntax: ``` knife role from file FILE ``` ### Options This command does not have any specific options. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create a role using JSON data** To view role details based on the values contained in a JSON file: ``` knife role from file "path to JSON file" ``` list ---- Use the `list` argument to view a list of roles that are currently available on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife role list ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### Examples The following examples show how to use this knife subcommand: **View a list of roles** To view a list of roles on the Chef Infra Server and display the URI for each role returned, enter: ``` knife role list -w ``` show ---- Use the `show` argument to view the details of a role. ### Syntax This argument has the following syntax: ``` knife role show ROLE_NAME ``` ### Options This argument has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Show as JSON data** To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife role show devops -F json ``` Other formats available include `text`, `yaml`, and `pp`. **Show as raw JSON data** To view node information in raw JSON, use the `-l` or `--long` option: ``` knife role show -l -F json <role_name``` and/or: ``` knife role show -l --format=json <role_name``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_role/knife serve =========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_serve.md) Use the `knife serve` subcommand to run a persistent chef-zero against the local chef-repo. (chef-zero is a lightweight Chef Infra Server that runs in-memory on the local machine.) This is the same as running the Chef Infra Client executable with the `--local-mode` option. The `chef_repo_path` is located automatically and the Chef Infra Server will bind to the first available port between `8889` and `9999`. `knife serve` will print the URL for the local Chef Infra Server, so that it may be added to the config.rb file. Syntax ------ This subcommand has the following syntax: ``` knife serve (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. Default value: same as `chef_repo_path` in the client.rb file. `--chef-zero-host IP` Override the host on which chef-zero listens. Default value: `127.0.0.1`. `--chef-zero-port PORT` The port on which chef-zero listens. The default behavior will bind to the first available port between `8889` and `9999`. `--repo-mode MODE` Use to specify the local chef-repo layout. Possible values: `static` (for environments, roles, data bags, and cookbooks), `everything` (same as static, plus nodes, clients, and users), `hosted_everything` (for ACLs, groups). Default value: `everything/hosted_everything`. Examples -------- None. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_serve/knife ssh ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_ssh.md) Use the `knife ssh` subcommand to invoke SSH commands (in parallel) on a subset of nodes within an organization, based on the results of a [search query](../../chef_search/index) made to the Chef Infra Server. Syntax ------ This subcommand has the following syntax: ``` knife ssh SEARCH_QUERY SSH_COMMAND (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-a SSH_ATTR`, `--attribute SSH_ATTR` The attribute used when opening an SSH connection. The default attribute is the FQDN of the host. Other possible values include a public IP address, a private IP address, or a hostname. `-A`, `--forward-agent` Enable SSH agent forwarding. `-C NUM`, `--concurrency NUM` The number of allowed concurrent connections. `-e`, `--exit-on-error` Use to exit immediately upon error. `-G GATEWAY`, `--ssh-gateway GATEWAY` The SSH tunnel or gateway that is used to run a bootstrap action on a machine that is not accessible from the workstation. `--ssh-gateway-identity SSH_GATEWAY_IDENTITY` The SSH identity file used to connect to the SSH gateway. *New in Chef Client 13.0.* `-i IDENTITY_FILE`, `--ssh-identity-file IDENTIFY_FILE` The SSH identity file used for authentication. Key-based authentication is recommended. `-m`, `--manual-list` Define a search query as a space-separated list of servers. If there is more than one item in the list, put quotes around the entire list. For example: `--manual-list "server01 server02 server03"` `--[no-]host-key-verify` Use `--no-host-key-verify` to disable host key verification. Default setting: `--host-key-verify`. `OTHER` The shell type. Possible values: `interactive`, `screen`, `tmux`, `macterm`, or `cssh`. (`csshx` is deprecated in favor of `cssh`.) `-p PORT`, `--ssh-port PORT` The SSH port. `-P PASSWORD`, `--ssh-password PASSWORD` The SSH password. This can be used to pass the password directly on the command line. If this option is not specified (and a password is required) knife prompts for the password. `SEARCH_QUERY` The search query used to return a list of servers to be accessed using SSH and the specified `SSH_COMMAND`. This option uses the same syntax as the search subcommand. If the `SEARCH_QUERY` does not contain a colon character (`:`), then the default query pattern is `tags:*#{@query}* OR roles:*#{@query}* OR fqdn:*#{@query}* OR addresses:*#{@query}*`, which means the following two search queries are effectively the same: ``` knife search ubuntu ``` or: ``` knife search node "tags:*ubuntu* OR roles:*ubuntu* OR fqdn:*ubuntu* (etc.)" ``` `SSH_COMMAND` The command to be run against the results of a search query. `-t SECONDS`, `--ssh-timeout SECONDS` The amount of time (in seconds) to wait for an SSH connection time out. `--tmux-split` Split the Tmux window. Default value: `false`. `-x USER_NAME`, `--ssh-user USER_NAME` The SSH user name. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Find server uptime** To find the uptime of all of web servers running Ubuntu on the Amazon EC2 platform, enter: ``` knife ssh "role:web" "uptime" -x ubuntu -a ec2.public_hostname ``` to return something like: ``` ec2-174-129-127-206.compute-1.amazonaws.com 13:50:47 up 1 day, 23:26, 1 user, load average: 0.25, 0.18, 0.11 ec2-67-202-63-102.compute-1.amazonaws.com 13:50:47 up 1 day, 23:33, 1 user, load average: 0.12, 0.13, 0.10 ec2-184-73-9-250.compute-1.amazonaws.com 13:50:48 up 16:45, 1 user, load average: 0.30, 0.22, 0.13 ec2-75-101-240-230.compute-1.amazonaws.com 13:50:48 up 1 day, 22:59, 1 user, load average: 0.24, 0.17, 0.11 ec2-184-73-60-141.compute-1.amazonaws.com 13:50:48 up 1 day, 23:30, 1 user, load average: 0.32, 0.17, 0.15 ``` **Run Chef Infra Client on all nodes** ``` knife ssh 'name:*' 'sudo chef-client' ``` **Force a Chef Infra Client run** To force a Chef Infra Client run on all of the web servers running Ubuntu on the Amazon EC2 platform, enter: ``` knife ssh "role:web" "sudo chef-client" -x ubuntu -a ec2.public_hostname ``` to return something like: ``` ec2-67-202-63-102.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:37 +0000] INFO: Starting Chef Run (Version 0.9.10) ec2-174-129-127-206.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:37 +0000] INFO: Starting Chef Run (Version 0.9.10) ec2-184-73-9-250.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:38 +0000] INFO: Starting Chef Run (Version 0.9.10) ec2-75-101-240-230.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:38 +0000] INFO: Starting Chef Run (Version 0.9.10) ec2-184-73-60-141.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:38 +0000] INFO: Starting Chef Run (Version 0.9.10) ec2-174-129-127-206.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Chef Run complete in 1.419243 seconds ec2-174-129-127-206.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: cleaning the checksum cache ec2-174-129-127-206.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Running report handlers ec2-174-129-127-206.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Report handlers complete ec2-67-202-63-102.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Chef Run complete in 1.578265 seconds ec2-67-202-63-102.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: cleaning the checksum cache ec2-67-202-63-102.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Running report handlers ec2-67-202-63-102.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Report handlers complete ec2-184-73-9-250.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Chef Run complete in 1.638884 seconds ec2-184-73-9-250.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: cleaning the checksum cache ec2-184-73-9-250.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Running report handlers ec2-184-73-9-250.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Report handlers complete ec2-75-101-240-230.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Chef Run complete in 1.540257 seconds ec2-75-101-240-230.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: cleaning the checksum cache ec2-75-101-240-230.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Running report handlers ec2-75-101-240-230.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Report handlers complete ec2-184-73-60-141.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Chef Run complete in 1.502489 seconds ec2-184-73-60-141.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: cleaning the checksum cache ec2-184-73-60-141.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Running report handlers ec2-184-73-60-141.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Report handlers complete ``` **Run a command based on search query** To query for all nodes that have the `webserver` role and then use SSH to run the command `sudo chef-client`, enter: ``` knife ssh "role:webserver" "sudo chef-client" ``` **Upgrade all nodes** ``` knife ssh name:* "sudo aptitude upgrade -y" ``` **Specify the shell type** To specify the shell type used on the nodes returned by a search query: ``` knife ssh roles:opscode-omnitruck macterm ``` where `screen` is one of the following values: `cssh`, `interactive`, `macterm`, `screen`, or `tmux`. If the node does not have the shell type installed, knife will return an error similar to the following: ``` you need the rb-appscript gem to use knife ssh macterm. `(sudo) gem install rb-appscript` to install ERROR: LoadError: cannot load such file -- appscript ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_ssh/knife ssl_fetch ================ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_ssl_fetch.md) Use the `knife ssl fetch` subcommand to copy SSL certificates from an HTTPS server to the `trusted_certs_dir` directory that is used by knife and Chef Infra Client to store trusted SSL certificates. When these certificates match the hostname of the remote server, running `knife ssl fetch` is the only step required to verify a remote server that is accessed by either knife or Chef Infra Client. Warning It is the user’s responsibility to verify the authenticity of every SSL certificate before downloading it to the `/.chef/trusted_certs` directory. knife will use any certificate in that directory as if it is a 100% trusted and authentic SSL certificate. knife will not be able to determine if any certificate in this directory has been tampered with, is forged, malicious, or otherwise harmful. Therefore it is essential that users take the proper steps before downloading certificates into this directory. Syntax ------ This subcommand has the following syntax: ``` knife ssl fetch (options) ``` Options ------- This subcommand has the following options: `URL_or_URI` The URL or URI for the location at which the SSL certificate is located. Default value: the URL for the Chef Infra Server, as defined in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Fetch the SSL certificates used by Knife from the Chef server** ``` knife ssl fetch ``` The response is similar to: ``` WARNING: Certificates from <chef_server_url> will be fetched and placed in your trusted_cert directory (/Users/grantmc/chef-repo/.chef/trusted_certs). Knife has no means to verify these are the correct certificates. You should verify the authenticity of these certificates after downloading. Adding certificate for <chef_server_url> in /Users/grantmc/chef-repo/.chef/trusted_certs/grantmc.crt Adding certificate for DigiCert Secure Server CA in /Users/grantmc/chef-repo/.chef/trusted_certs/DigiCert_Secure_Server_CA.crt ``` **Fetch SSL certificates from a URL or URI** ``` knife ssl fetch https://www.example.com ``` **Verify Checksums** The SSL certificate that is downloaded to the `/.chef/trusted_certs` directory should be verified to ensure that it is, in fact, the same certificate as the one located on the Chef Infra Server. This can be done by comparing the SHA-256 checksums. 1. View the checksum on the Chef Infra Server: ``` ssh <EMAIL> sudo sha256sum /var/opt/opscode/nginx/ca/chef-server.example.com.crt ``` The response is similar to: ``` <ABC123checksum> /var/opt/opscode/nginx/ca/chef-server.example.com.crt ``` 2. View the checksum on the workstation: ``` gsha256sum .chef/trusted_certs/chef-server.example.com.crt ``` The response is similar to: ``` <ABC123checksum> .chef/trusted_certs/chef-server.example.com.crt ``` 3. Verify that the checksum values are identical. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_ssl_fetch/knife status ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_status.md) Use the `knife status` subcommand to display a brief summary of the nodes on a Chef Infra Server, including the time of the most recent successful Chef Infra Client run. Syntax ------ This subcommand has the following syntax: ``` knife status (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `QUERY` The search query used to identify a list of items on a Chef Infra Server. This option uses the same syntax as the `search` subcommand. `--hide-by-mins` Hide nodes that have performed a successful Chef Infra Client run within the last specified number of minutes. The number of minutes to hide is provided as an integer, such as `--hide-by-mins 10`. `-l`, `--long` Display all attributes in the output and show the output as JSON. `-m`, `--medium` Display normal attributes in the output and to show the output as JSON. `-r RUN_LIST`, `--run-list RUN_LIST` A comma-separated list of roles and/or recipes to be applied. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **View status, include run-lists** To include run-lists in the status, enter: ``` knife status --run-list ``` to return something like: ``` 20 hours ago, dev-vm.chisamore.com, ubuntu 10.04, dev-vm.chisamore.com, 10.66.44.126, role[lb]. 3 hours ago, i-225f954f, ubuntu 10.04, ec2-67-202-63-102.compute-1.amazonaws.com, 67.202.63.102, role[web]. 3 hours ago, i-a45298c9, ubuntu 10.04, ec2-174-129-127-206.compute-1.amazonaws.com, 174.129.127.206, role[web]. 3 hours ago, i-5272a43f, ubuntu 10.04, ec2-184-73-9-250.compute-1.amazonaws.com, 184.73.9.250, role[web]. 3 hours ago, i-226ca64f, ubuntu 10.04, ec2-75-101-240-230.compute-1.amazonaws.com, 75.101.240.230, role[web]. 3 hours ago, i-f65c969b, ubuntu 10.04, ec2-184-73-60-141.compute-1.amazonaws.com, 184.73.60.141, role[web]. ``` **View status using a time range** To show the status of nodes on which Chef Infra Client did not run successfully within the past hour, enter: ``` knife status --hide-by-mins 60 ``` to return something like: ``` 422492 hours ago, runner-1-432.lxc, centos 6.8. 27 hours ago, union-3-432.lxc, centos 7.3.1611. ``` **View status using a query** To show the status of a subset of nodes that are returned by a specific query, enter: ``` knife status "role:web" --run-list ``` to return something like: ``` 3 hours ago, i-225f954f, ubuntu 10.04, ec2-67-202-63-102.compute-1.amazonaws.com, 67.202.63.102, role[web]. 3 hours ago, i-a45298c9, ubuntu 10.04, ec2-174-129-127-206.compute-1.amazonaws.com, 174.129.127.206, role[web]. 3 hours ago, i-5272a43f, ubuntu 10.04, ec2-184-73-9-250.compute-1.amazonaws.com, 184.73.9.250, role[web]. 3 hours ago, i-226ca64f, ubuntu 10.04, ec2-75-101-240-230.compute-1.amazonaws.com, 75.101.240.230, role[web]. 3 hours ago, i-f65c969b, ubuntu 10.04, ec2-184-73-60-141.compute-1.amazonaws.com, 184.73.60.141, role[web]. ``` **View status for all nodes** To view the status of all nodes in the organization, enter: ``` knife status ``` to return something like: ``` 20 hours ago, dev-vm.chisamore.com, ubuntu 10.04, dev-vm.chisamore.com, 10.66.44.126 3 hours ago, i-225f954f, ubuntu 10.04, ec2-67-202-63-102.compute-1.amazonaws.com, 67.202.63.102 3 hours ago, i-a45298c9, ubuntu 10.04, ec2-174-129-127-206.compute-1.amazonaws.com, 174.129.127.206 3 hours ago, i-5272a43f, ubuntu 10.04, ec2-184-73-9-250.compute-1.amazonaws.com, 184.73.9.250 3 hours ago, i-226ca64f, ubuntu 10.04, ec2-75-101-240-230.compute-1.amazonaws.com, 75.101.240.230 3 hours ago, i-f65c969b, ubuntu 10.04, ec2-184-73-60-141.compute-1.amazonaws.com, 184.73.60.141 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_status/knife ssl check =============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_ssl_check.md) Use the `knife ssl check` subcommand to verify the SSL configuration for the Chef Infra Server or a location specified by a URL or URI. Invalid certificates will not be used by OpenSSL. When this command is run, the certificate files (`*.crt` and/or `*.pem`) that are located in the `/.chef/trusted_certs` directory are checked to see if they have valid X.509 certificate properties. A warning is returned when certificates do not have valid X.509 certificate properties or if the `/.chef/trusted_certs` directory does not contain any certificates. Warning When verification of a remote server’s SSL certificate is disabled, Chef Infra Client will issue a warning similar to “SSL validation of HTTPS requests is disabled. HTTPS connections are still encrypted, but Chef Infra Client is not able to detect forged replies or man-in-the-middle attacks.” To configure SSL for Chef Infra Client, set `ssl_verify_mode` to `:verify_peer` (recommended) **or** `verify_api_cert` to `true` in the client.rb file. Syntax ------ This subcommand has the following syntax: ``` knife ssl check (options) ``` Options ------- This subcommand has the following options: `URL_or_URI` The URL or URI for the location at which the SSL certificate is located. Default value: the URL for the Chef Infra Server, as defined in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **SSL certificate has valid X.509 properties** If the SSL certificate can be verified, the response to ``` knife ssl check ``` is similar to: ``` Connecting to host chef-server.example.com:443 Successfully verified certificates from 'chef-server.example.com' ``` **SSL certificate has invalid X.509 properties** If the SSL certificate cannot be verified, the response to ``` knife ssl check ``` is similar to: ``` Connecting to host chef-server.example.com:443 ERROR: The SSL certificate of chef-server.example.com could not be verified Certificate issuer data: /C=US/ST=WA/L=S/O=Corp/OU=Ops/CN=chef-server.example.com/emailAddress=you<EMAIL> Configuration Info: OpenSSL Configuration: * Version: OpenSSL 1.0.2u 20 Dec 2019 * Certificate file: /opt/chef-workstation/embedded/ssl/cert.pem * Certificate directory: /opt/chef-workstation/embedded/ssl/certs Chef SSL Configuration: * ssl_ca_path: nil * ssl_ca_file: nil * trusted_certs_dir: "/Users/grantmc/Downloads/chef-repo/.chef/trusted_certs" TO FIX THIS ERROR: If the server you are connecting to uses a self-signed certificate, you must configure chef to trust that certificate. By default, the certificate is stored in the following location on the host where your Chef Infra Server runs: /var/opt/opscode/nginx/ca/SERVER_HOSTNAME.crt Copy that file to your trusted_certs_dir (currently: /Users/grantmc/Downloads/chef-repo/.chef/trusted_certs) using SSH/SCP or some other secure method, then re-run this command to confirm that the certificate is now trusted. ``` **Verify the SSL configuration for Chef Infra Client** The SSL certificates that are used by Chef Infra Client may be verified by specifying the path to the client.rb file. Use the `--config` option (that is available to any knife command) to specify this path: ``` knife ssl check --config /etc/chef/client.rb ``` **Verify an external server’s SSL certificate** ``` knife ssl check URL_or_URI ``` for example: ``` knife ssl check https://www.chef.io ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_ssl_check/knife tag ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_tag.md) A tag is a custom description that is applied to a node. A tag, once applied, can be helpful when managing nodes using knife or when building recipes by providing alternate methods of grouping similar types of information. Use the `knife tag` subcommand to apply tags to nodes on a Chef Infra Server. Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. create ------ Use the `create` argument to add one or more tags to a node. ### Syntax This argument has the following syntax: ``` knife tag create NODE_NAME [TAG...] ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Create tags** To create tags named `seattle`, `portland`, and `vancouver`, enter: ``` knife tag create node seattle portland vancouver ``` delete ------ Use the `delete` argument to delete one or more tags from a node. ### Syntax This argument has the following syntax: ``` knife tag delete NODE_NAME [TAG...] ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Delete tags** To delete tags named `denver` and `phoenix`, enter: ``` knife tag delete node denver phoenix ``` Type `Y` to confirm a deletion. list ---- Use the `list` argument to list all of the tags that have been applied to a node. ### Syntax This argument has the following syntax: ``` knife tag list [NODE_NAME...] ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **View a list of tags** To view the tags for a node named `devops_prod1`, enter: ``` knife tag list devops_prod1 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_tag/knife supermarket ================= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_supermarket.md) The `knife supermarket` subcommand is used to interact with cookbooks that are located in on the public Supermarket as well as private Chef Supermarket sites. A user account is required for any community actions that write data to the Chef Supermarket; however, the following arguments do not require a user account: `download`, `search`, `install`, and `list`. Note Please consider managing community cookbooks using the version of Berkshelf that ships with Chef Workstation. For more information about Chef Workstation, see [About Chef Workstation](../index). Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. download -------- Use the `download` argument to download a cookbook from Chef Supermarket. A cookbook will be downloaded as a tar.gz archive and placed in the current working directory. If a cookbook (or cookbook version) has been deprecated and the `--force` option is not used, knife will alert the user that the cookbook is deprecated and then will provide the name of the most recent non-deprecated version of that cookbook. ### Syntax This argument has the following syntax: ``` knife supermarket download COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `COOKBOOK_VERSION` The version of a cookbook to be downloaded. If a cookbook has only one version, this option does not need to be specified. If a cookbook has more than one version and this option is not specified, the most recent version of the cookbook is downloaded. `-f FILE`, `--file FILE` The file to which a cookbook download is written. `--force` Overwrite an existing directory. `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. ### Examples The following examples show how to use this knife subcommand: **Download a cookbook** To download the cookbook `mysql`, enter: ``` knife supermarket download mysql ``` install ------- Use the `install` argument to install a cookbook that has been downloaded from Chef Supermarket to a local git repository . This action uses the git version control system in conjunction with Chef Supermarket site to install community-contributed cookbooks to the local chef-repo. Using this argument does the following: 1. A new “pristine copy” branch is created in git for tracking the upstream. 2. All existing versions of a cookbook are removed from the branch. 3. The cookbook is downloaded from Chef Supermarket in the tar.gz format. 4. The downloaded cookbook is untarred and its contents are committed to git and a tag is created. 5. The “pristine copy” branch is merged into the master branch. This process allows the upstream cookbook in the master branch to be modified while letting git maintain changes as a separate patch. When an updated upstream version becomes available, those changes can be merged while maintaining any local modifications. ### Syntax This argument has the following syntax: ``` knife supermarket install COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `-b`, `--use-current-branch` Ensure that the current branch is used. `-B BRANCH`, `--branch BRANCH` The name of the default branch. This defaults to the master branch. `COOKBOOK_VERSION` The version of the cookbook to be installed. If a version is not specified, the most recent version of the cookbook is installed. `-D`, `--skip-dependencies` Ensure that all cookbooks to which the installed cookbook has a dependency are not installed. `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. ### Examples The following examples show how to use this knife subcommand: **Install a cookbook** To install the cookbook `mysql`, enter: ``` knife supermarket install mysql ``` list ---- Use the `list` argument to view a list of cookbooks that are currently available at Chef Supermarket. ### Syntax This argument has the following syntax: ``` knife supermarket list (options) ``` ### Options This argument has the following options: `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. `-w`, `--with-uri` Show the corresponding URIs. ### Examples The following examples show how to use this knife subcommand: **View a list of cookbooks** To view a list of cookbooks at the [Chef Supermarket](https://supermarket.chef.io/cookbooks) server, enter: ``` knife supermarket list ``` to return a list similar to: ``` 1password minecraft 301 mineos 7-zip minidlna AWS_see_spots_run minitest AmazonEC2Tag minitest-handler Appfirst-Cookbook mirage CVE-2014-3566-poodle mlocate CVE-2015-0235 mod_security Obfsproxy mod_security2 R modcloth-hubot Rstats modcloth-nad SysinternalsBginfo modman VRTSralus modules abiquo mogilefs acadock mongodb accel-ppp mongodb-10gen accounts mongodb-agents accumulator monit ... ``` search ------ Use the `search` argument to search for a cookbooks located at Chef Supermarket. A search query is used to return a list of these cookbooks and uses the same syntax as the `knife search` subcommand. ### Syntax This argument has the following syntax: ``` knife supermarket search SEARCH_QUERY (options) ``` ### Options This argument has the following options: `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. ### Examples The following examples show how to use this knife subcommand: **Search for cookbooks** To search for a cookbook, use a command similar to: ``` knife supermarket search mysql ``` where `mysql` is the search term. This will return something similar to: ``` mysql: cookbook: https://supermarket.chef.io/api/v1/cookbooks/mysql cookbook_description: Provides mysql_service, mysql_config, and mysql_client resources cookbook_maintainer: chef cookbook_name: mysql mysql-apt-config: cookbook: https://supermarket.chef.io/api/v1/cookbooks/mysql-apt-config cookbook_description: Installs/Configures mysql-apt-config cookbook_maintainer: tata cookbook_name: mysql-apt-config mysql-multi: cookbook: https://supermarket.chef.io/api/v1/cookbooks/mysql-multi cookbook_description: MySQL replication wrapper cookbook cookbook_maintainer: rackops cookbook_name: mysql-multi ``` share ----- Use the `share` argument to add a cookbook to Chef Supermarket. This action will require a user account and a certificate for [Chef Supermarket](https://supermarket.chef.io/). By default, knife will use the user name and API key that is identified in the configuration file used during the upload; otherwise these values must be specified on the command line or in an alternate configuration file. If a cookbook already exists in Chef Supermarket, then only an owner or maintainer of that cookbook can make updates. ### Syntax This argument has the following syntax: ``` knife supermarket share COOKBOOK_NAME CATEGORY (options) ``` ### Options This argument has the following options: `CATEGORY` The cookbook category: `"Databases"`, `"Web Servers"`, `"Process Management"`, `"Monitoring & Trending"`, `"Programming Languages"`, `"Package Management"`, `"Applications"`, `"Networking"`, `"Operating Systems & Virtualization"`, `"Utilities"`, or `"Other"`. `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. ### Examples The following examples show how to use this knife subcommand: **Share a cookbook** To share a cookbook named `my_apache2_cookbook` and add it to the `Web Servers` category in Chef Supermarket: ``` knife supermarket share "my_apache2_cookbook" "Web Servers" ``` show ---- Use the `show` argument to view information about a cookbook located at Chef Supermarket. ### Syntax This argument has the following syntax: ``` knife supermarket show COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `COOKBOOK_VERSION` The version of a cookbook to be shown. If a cookbook has only one version, this option does not need to be specified. If a cookbook has more than one version and this option is not specified, a list of cookbook versions is returned. `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. ### Examples The following examples show how to use this knife subcommand: **Show cookbook data** To show the details for a cookbook named `mysql`: ``` knife supermarket show mysql ``` to return something similar to: ``` average_rating: category: Other created_at: 2009-10-28T19:16:54.000Z deprecated: false description: Provides mysql_service, mysql_config, and mysql_client resources external_url: https://github.com/chef-cookbooks/mysql issues_url: https://github.com/chef-cookbooks/mysql/issues latest_version: https://supermarket.chef.io/api/v1/cookbooks/mysql/versions/8.5.1 maintainer: sous-chefs metrics: collaborators: 2 downloads: total: 128998032 versions: 0.10.0: 927561 0.15.0: 927536 0.20.0: 927321 0.21.0: 927298 0.21.1: 927311 0.21.2: 927424 0.21.3: 927441 0.21.5: 927326 0.22.0: 927297 0.23.0: 927353 0.23.1: 927862 0.24.0: 927316 ``` **Show cookbook version data** To show the details for a cookbook version, run a command similar to: ``` knife supermarket show mysql 8.5.1 ``` where `mysql` is the cookbook and `8.5.1` is the cookbook version. This will return something similar to: ``` average_rating: cookbook: https://supermarket.chef.io/api/v1/cookbooks/mysql file: https://supermarket.chef.io/api/v1/cookbooks/mysql/versions/8.5.1/download license: Apache-2.0 published_at: 2017-08-23T19:01:28Z quality_metrics: failed: false feedback: passed the No Binaries metric. Contains no obvious binaries. name: No Binaries failed: false feedback: mysql passed the publish metric name: Publish failed: false feedback: mysql supports at least one platform. name: Supported Platforms failed: false feedback: passed the Collaborators Metric with 2 collaborators. name: Collaborator Number failed: false feedback: Run with Foodcritic Version 14.0.0 with tags metadata,correctness ~FC031 ~FC045 and failure tags any name: Foodcritic failed: false feedback: passed the CONTRIBUTING.md file metric. name: Contributing File failed: false feedback: passed the version tag metric. name: Version Tag failed: false feedback: passed the TESTING.md file metric. name: Testing File supports: amazon: >= 0.0.0 centos: >= 6.0 debian: >= 7.0 fedora: >= 0.0.0 opensuseleap: >= 0.0.0 oracle: >= 6.0 redhat: >= 6.0 scientific: >= 6.0 suse: >= 12.0 ubuntu: >= 12.04 tarball_file_size: 23763 version: 8.5.1 ``` unshare ------- Use the `unshare` argument to stop the sharing of a cookbook located at Chef Supermarket. Only the maintainer of a cookbook may perform this action. Note Unsharing a cookbook will break a cookbook that has set a dependency on that cookbook or cookbook version. ### Syntax This argument has the following syntax: ``` knife supermarket unshare COOKBOOK_NAME/versions/VERSION (options) ``` ### Options This argument has the following options: `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. ### Examples The following examples show how to use this knife subcommand: **Unshare a cookbook** To unshare a cookbook named `my_apache2_cookbook`, enter: ``` knife supermarket unshare "my_apache2_cookbook" "Web Servers" ``` **Unshare a cookbook version** To unshare cookbook version `0.10.0` for the `my_apache2_cookbook` cookbook, enter: ``` knife supermarket unshare "my_apache2_cookbook/versions/0.10.0" ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_supermarket/knife user ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_user.md) Use the `knife user` subcommand to manage the list of users and their associated RSA public key-pairs. Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. create ------ Use the `create` argument to create a user. This process will generate an RSA key pair for the named user. The public key will be stored on the Chef Infra Server and the private key will be displayed on `STDOUT` or written to a named file. * For the user, the private key should be copied to the system as `/etc/chef/client.pem`. * For knife, the private key is typically copied to `~/.chef/client_name.pem` and referenced in the config.rb configuration file. ### Syntax This argument has the following syntax: ``` knife user create USERNAME DISPLAY_NAME FIRST_NAME LAST_NAME EMAIL PASSWORD (options) ``` ### Options This argument has the following options: `-f FILE`, `--file FILE` Save a private key to the specified file name. `--password PASSWORD` The user password. `--user-key FILENAME` The path to a file that contains the public key. If this option is not specified, the Chef Infra Server will generate a public/private key pair. `-k`, `--prevent-keygen` :Prevent Chef Infra Server from generating a default key pair for you. Cannot be passed with –user-key. `-o ORGNAME` `--orgname ORGNAME` :Associate new user to an organization matching ORGNAME `--first-name FIRST_NAME` :First name for the user `--last-name LAST_NAME` :Last name for the user `--email EMAIL` :Email for the user `--prompt-for-password`, `-p` :Prompt for user password Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create a user** ``` knife user create tbucatar "<NAME>" <EMAIL> -f /keys/tbucatar ``` ``` knife user create arno arno schmidt <EMAIL> password -----BEGIN RSA PRIVATE KEY----- [...] -----END RSA PRIVATE KEY----- ``` delete ------ Use the `delete` argument to delete a registered user. ### Syntax This argument has the following syntax: ``` knife user delete USER_NAME ``` ### Options `--no-disassociate-user`, `-d` :Don’t disassociate the user first `"--remove-from-admin-groups`, `-R` :If the user is a member of any org admin groups, attempt to remove from those groups. Ignored if –no-disassociate-user is set. ### Examples The following examples show how to use this knife subcommand: **Delete a user** ``` knife user delete "<NAME>" ``` edit ---- Use the `edit` argument to edit the details of a user. When this argument is run, knife will open $EDITOR. When finished, knife will update the Chef Infra Server with those changes. ### Syntax This argument has the following syntax: ``` knife user edit USER_NAME ``` ### Options `--input FILENAME`, `-i FILENAME` :Name of file to use for PUT or POST `--filename FILENAME`, `-f FILENAME` :Write private key to FILENAME rather than STDOUT ### Examples ``` EDITOR=ed knife user edit arno 639 1,%p { "username": "arno", "email": "<EMAIL>", "display_name": "<NAME>", "first_name": "arno", "last_name": "schmidt", "middle_name": "", "public_key": "-----BEGIN PUBLIC KEY-----\n[...]\n-----END PUBLIC KEY-----\n\n" } /email/s/chef.io/opscode.com/p "email": "<EMAIL>", wq 643 Saved arno. knife user show arno display_name: <NAME> email: <EMAIL> first_name: arno last_name: schmidt middle_name: public_key: -----BEGIN PUBLIC KEY----- [...] -----END PUBLIC KEY----- username: arno ``` list ---- Use the `list` argument to show list of all registered users. ### Syntax This argument has the following syntax: ``` knife user list ``` ### Options `-w`, `--with-uri`, :Show corresponding URIs. ### Examples The following examples show how to use this knife subcommand: ``` knife user list alice pivotal knife user list -w alice: https://chef-server.fqdn/users/alice pivotal: https://chef-server.fqdn/users/pivotal knife org list -w -a acme: https://chef-server.fqdn/organizations/acme ``` password -------- Command for managing password and authentication for a user. ### Syntax This argument has the following syntax: ``` knife user password USER_NAME [PASSWORD | ] ``` ### Options `--enable_external_auth`, :Enable external authentication for this user (such as LDAP). ### Examples The following examples show how to use this knife subcommand: ``` knife user password arno newpassword {"username"=>"arno", "email"=>"<EMAIL>", "display_name"=>"<NAME>", "first_name"=>"arno", "last_name"=>"schmidt", "middle_name"=>"", "public_key"=>"-----BEGIN PUBLIC KEY-----\n[...]\n-----END PUBLIC KEY-----\n\n", "password"=>"newpassword", "recovery_authentication_enabled"=>true} Authentication info updated for arno. ``` key create ---------- Use the `key create` argument to create a public key. ### Syntax This argument has the following syntax: ``` knife user key create USER_NAME (options) ``` ### Options This argument has the following options: `-e DATE`, `--expiration-date DATE` The expiration date for the public key, specified as an ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. If this option is not specified, the public key will not have an expiration date. For example: `2013-12-24T21:00:00Z`. `-f FILE`, `--file FILE` Save a private key to the specified file name. `-k NAME`, `--key-name NAME` The name of the public key. `-p FILE_NAME`, `--public-key FILE_NAME` The path to a file that contains the public key. If this option is not specified, and only if `--key-name` is specified, the Chef Infra Server will generate a public/private key pair. ### Examples None. key delete ---------- Use the `key delete` argument to delete a public key. ### Syntax This argument has the following syntax: ``` knife user key delete USER_NAME KEY_NAME ``` ### Examples None. key edit -------- Use the `key edit` argument to modify or rename a public key. ### Syntax This argument has the following syntax: ``` knife user key edit USER_NAME KEY_NAME (options) ``` ### Options This argument has the following options: `-c`, `--create-key` Generate a new public/private key pair and replace an existing public key with the newly-generated public key. To replace the public key with an existing public key, use `--public-key` instead. `-e DATE`, `--expiration-date DATE` The expiration date for the public key, specified as an ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. If this option is not specified, the public key will not have an expiration date. For example: `2013-12-24T21:00:00Z`. `-f FILE`, `--file FILE` Save a private key to the specified file name. If the `--public-key` option is not specified the Chef Infra Server will generate a private key. `-k NAME`, `--key-name NAME` The name of the public key. `-p FILE_NAME`, `--public-key FILE_NAME` The path to a file that contains the public key. If this option is not specified, and only if `--key-name` is specified, the Chef Infra Server will generate a public/private key pair. ### Examples None. key list -------- Use the `key list` argument to view a list of public keys for the named user. ### Syntax This argument has the following syntax: ``` knife user key list USER_NAME (options) ``` ### Options This argument has the following options: `-e`, `--only-expired` Show a list of public keys that have expired. `-n`, `--only-non-expired` Show a list of public keys that have not expired. `-w`, `--with-details` Show a list of public keys, including URIs and expiration status. ### Examples None. key show -------- Use the `key show` argument to view details for a specific public key. ### Syntax This argument has the following syntax: ``` knife user key show USER_NAME KEY_NAME ``` ### Examples None. list ---- Use the `list` argument to view a list of registered users. ### Syntax This argument has the following syntax: ``` knife user list (options) ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### Examples None. reregister ---------- Use the `reregister` argument to regenerate an RSA key pair for a user. The public key will be stored on the Chef Infra Server and the private key will be displayed on `STDOUT` or written to a named file. Note Running this argument will invalidate the previous RSA key pair, making it unusable during authentication to the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife user reregister USER_NAME (options) ``` ### Options This argument has the following options: `-f FILE_NAME`, `--file FILE_NAME` Save a private key to the specified file name. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Regenerate the RSA key-pair** ``` knife user reregister "<NAME>" ``` show ---- Use the `show` argument to show the details of a user. ### Syntax This argument has the following syntax: ``` knife user show USER_NAME (options) ``` ### Options This argument has the following options: `--with-orgs`, `-l` Show the organizations of which the user is a member. ### Examples The following examples show how to use this knife subcommand: **Show user data** To view a user named `<NAME>`, enter: ``` knife user show "<NAME>" ``` to return something like: ``` chef_type: user json_class: Chef::User name: <NAME> public_key: ``` ``` knife user show alice -l display_name: <NAME> email: <EMAIL> first_name: Alice last_name: Schmidt middle_name: organizations: acme public_key: -----BEGIN PUBLIC KEY----- [...] -----END PUBLIC KEY----- username: alice ``` **Show user data as JSON** To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife user show "<NAME>" -F json ``` (Other formats available include `text`, `yaml`, and `pp`, e.g. `-F yaml` for YAML.) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_user/knife upload ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_upload.md) Use the `knife upload` subcommand to upload data to the Chef Infra Server from the current working directory in the chef-repo. The following types of data may be uploaded with this subcommand: * Cookbooks * Data bags * Roles stored as JSON data * Environments stored as JSON data (Roles and environments stored as Ruby data will not be uploaded.) This subcommand is often used in conjunction with `knife diff`, which can be used to see exactly what changes will be uploaded, and then `knife download`, which does the opposite of `knife upload`. Syntax ------ This subcommand has the following syntax: ``` knife upload [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--[no-]diff` Upload only new and modified files. Set to `false` to upload all files. Default: `true`. `--[no-]force` Use `--force` to upload roles, cookbooks, etc. even if the file in the directory is identical (by default, no `POST` or `PUT` is performed unless an actual change would be made). Default: `--no-force`. `--[no-]freeze` Require changes to a cookbook be included as a new version. Only the `--force` option can override this setting. Default: `false`. `-n`, `--dry-run` Take no action and only print out results. Default: `false`. `--[no-]purge` Use `--purge` to delete roles, cookbooks, etc. from the Chef Infra Server if their corresponding files do not exist in the chef-repo. By default, such objects are left alone and NOT purged. Default: `--no-purge`. `--[no-]recurse` Use `--no-recurse` to disable uploading a directory recursively. Default: `--recurse`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Upload the entire chef-repo** Browse to the top level of the chef-repo and enter: ``` knife upload . ``` or from anywhere in the chef-repo, enter: ``` knife upload / ``` to upload all cookbooks and data bags, plus all roles and environments that are stored as JSON data. (Roles and environments stored as Ruby data will not be uploaded.) **Upload the /cookbooks directory** Browse to the top level of the chef-repo and enter: ``` knife upload cookbooks ``` or from anywhere in the chef-repo, enter: ``` knife upload /cookbooks ``` **Upload the /environments directory** Browse to the top level of the chef-repo and enter: ``` knife upload environments ``` or from anywhere in the chef-repo, enter: ``` knife upload /environments ``` to upload all environments that are stored as JSON data. (Environments stored as Ruby data will not be uploaded.) **Upload a single environment** Browse to the top level of the chef-repo and enter: ``` knife upload environments/production.json ``` or from the `environments/` directory, enter: ``` knife upload production.json ``` **Upload the /roles directory** Browse to the top level of the chef-repo and enter: ``` knife upload roles ``` or from anywhere in the chef-repo, enter: ``` knife upload /roles ``` to upload all roles that are stored as JSON data. (Roles stored as Ruby data will not be uploaded.) **Upload cookbooks and roles** Browse to the top level of the chef-repo and enter: ``` knife upload cookbooks/apache\* roles/webserver.json ``` **Use output of knife deps to pass command to knife upload** ``` knife upload `knife deps nodes/*.json` ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_upload/Knife Cloud Plugins =================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/plugin_knife.md) A knife plugin is a set of one (or more) subcommands that can be added to knife to support additional functionality that is not built-in to the base set of knife subcommands. Many of the knife plugins are built by members of the Chef community and several of them are built and maintained by Chef. * The same [common options](../knife_options/index) used by knife subcommands can also be used by knife plug-ins * A knife plugin can make authenticated API requests to the Chef server The following knife plug-ins are maintained by Chef: | Subcommand | Description | | --- | --- | | [knife-azure](https://github.com/chef/knife-azure) | Microsoft Azure is a cloud hosting platform from Microsoft that provides virtual machines for Linux and Windows Server, cloud and database services, and more. Use the `knife azure` subcommand to manage API-driven cloud servers hosted by Microsoft Azure. | | [knife-ec2](https://github.com/chef/knife-ec2) | Amazon EC2 is a web service that provides resizable compute capacity in the cloud, based on preconfigured operating systems and virtual application software using Amazon Machine Images (AMI). The `knife ec2` subcommand is used to manage API-driven cloud servers that are hosted by Amazon EC2. | | [knife-google](https://github.com/chef/knife-google) | Google Compute Engine is a cloud hosting platform that offers scalable and flexible virtual machine computing. The `knife google` subcommand is used to manage API-driven cloud servers that are hosted by Google Compute Engine. | | [knife-openstack](https://github.com/chef/knife-openstack) | The `knife openstack` subcommand is used to manage API-driven cloud servers that are hosted by OpenStack. | | [knife-rackspace](https://github.com/chef/knife-rackspace) | Rackspace is a cloud-driven platform of virtualized servers that provide services for storage and data, platform and networking, and cloud computing. The `knife rackspace` subcommand is used to manage API-driven cloud servers that are hosted by Rackspace cloud services | | [knife-vcenter](https://github.com/chef/knife-vcenter) | The `knife vcenter` subcommand is used to provision systems with VMware vCenter. | | [knife-vsphere](https://github.com/chef/knife-vsphere) | The `knife vsphere` subcommand is used to provision systems with VMware vSphere. | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/plugin_knife/Knife Windows ============= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_windows.md) Knife Windows Overview ---------------------- The `knife windows` subcommand is used to interact with Windows systems managed by Chef Infra. Nodes are configured using WinRM, which allows external applications to call native objects like batch scripts, Windows PowerShell scripts, or scripting library variables. The `knife windows` subcommand supports NTLM and Kerberos methods of authentication. Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. ### Requirements This subcommand requires WinRM to be installed, and then configured correctly, including ensuring the correct ports are open. For more information, see: <https://docs.microsoft.com/en-us/windows/desktop/WinRM/installation-and-configuration-for-windows-remote-management> and/or <https://support.microsoft.com/en-us/help/968930/windows-management-framework-core-package-windows-powershell-2-0-and-w>. Use the quick configuration option in WinRM to allow outside connections and the entire network path from knife (and the workstation). Run the following on the Windows target: ``` C:\> winrm quickconfig -q ``` Often commands can take longer than the default `MaxTimeoutms` WinRM configuration setting. Increase this value to `1800000` (30 minutes). To update this setting, run the following command on the Windows target: ``` C:\> winrm set winrm/config '@{MaxTimeoutms="1800000"}' ``` Ensure that the Windows Firewall is configured to allow WinRM connections between the workstation and the Chef Infra Server. For example: ``` C:\> netsh advfirewall firewall set rule name="Windows Remote Management (HTTP-In)" profile=public protocol=tcp localport=5985 remoteip=localsubnet new remoteip=any ``` ### Negotiate, NTLM When knife is executed from a Microsoft Windows system, it is no longer necessary to make additional configuration of the WinRM listener on the target node to enable successful authentication from the workstation. It is sufficient to have a WinRM listener on the remote node configured to use the default configuration for `winrm quickconfig`. This is because `knife windows` supports the Microsoft Windows negotiate protocol, including NTLM authentication, which matches the authentication requirements for the default configuration of the WinRM listener. Note To use Negotiate or NTLM to authenticate as the user specified by the `--winrm-user` option, include the user’s Microsoft Windows domain, using the format `domain\user`, where the backslash (`\`) separates the domain from the user. For example: ``` knife winrm web1.cloudapp.net 'dir' -x 'proddomain\webuser' -P 'password' ``` and: ``` knife winrm db1.cloudapp.net 'dir' -x '.\localadmin' -P 'password' ``` ### Domain Authentication The `knife windows` plugin supports Microsoft Windows domain authentication. This requires: * An SSL certificate on the target node * The certificate details can be viewed and its [thumbprint hex values copied](https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-view-certificates-with-the-mmc-snap-in) To create the listener over HTTPS, run the following command on the Windows target: ``` C:\> winrm create winrm/config/Listener?Address=IP:<ip_address>+Transport=HTTPS @{Hostname="<fqdn>";CertificateThumbprint="<hexidecimal_thumbprint_value>"} ``` where the `CertificateThumbprint` is the thumbprint hex value copied from the certificate details. (The hex value may require that spaces be removed before passing them to the node using the `knife windows` plugin.) WinRM 2.0 uses port `5985` for HTTP and port `5986` for HTTPS traffic, by default. To validate communication with the Windows system using domain authentication run: ``` knife winrm 'node1.domain.com' 'dir' -m -x domain\\administrator -P 'super_secret_password' -p 5986 ``` cert generate ------------- Use the `cert generate` argument to generate certificates for use with WinRM SSL listeners. This argument also generates a related public key file (in .pem format) to validate communication between listeners that are configured to use the generated certificate. ### Syntax This argument has the following syntax: ``` knife windows cert generate FILE_PATH (options) ``` ### Options This argument has the following options: `-cp PASSWORD`, `--cert-passphrase PASSWORD` The password for the SSL certificate. `-cv MONTHS`, `--cert-validity MONTHS` The number of months for which a certificate is valid. Default value: `24`. `-h HOSTNAME`, `--hostname HOSTNAME` The hostname for the listener. For example, `--hostname something.mydomain.com` or `*.mydomain.com`. Default value: `*`. `-k LENGTH`, `--key-length LENGTH` The length of the key. Default value: `2048`. `-o PATH`, `--output-file PATH` The location in which the `winrmcert.b64`, `winrmcert.pem`, and `winrmcert.pfx` files are generated. For example: `--output-file /home/.winrm/server_cert` will create `server_cert.b64`, `server_cert.pem`, and `server_cert.pfx` in the `server_cert` directory. Default location: `current_directory/winrmcert`. cert install ------------ Use the `cert install` argument to install a certificate (such as one generated by the `cert generate` argument) into the Microsoft Windows certificate store so that it may be used as the SSL certificate by a WinRM listener. ### Syntax This argument has the following syntax: ``` knife windows cert install CERT [CERT] (options) ``` ### Options This argument has the following options: `-cp PASSWORD`, `--cert-passphrase PASSWORD` The password for the SSL certificate. listener create --------------- Use the `listener create` argument to create a WinRM listener on the Microsoft Windows platform. Note This command may only be used on the Microsoft Windows platform. ### Syntax This argument has the following syntax: ``` knife windows listener create (options) ``` ### Options This argument has the following options: `-c CERT_PATH`, `--cert-install CERT_PATH` Add the specified certificate to the store before creating the listener. `-cp PASSWORD`, `--cert-passphrase PASSWORD` The password for the SSL certificate. `-h HOST_NAME`, `--hostname HOST_NAME` The hostname for the listener. For example, `--hostname something.mydomain.com` or `*.mydomain.com`. Default value: `*`. `-p PORT`, `--port PORT` The WinRM port. Default value: `5986`. `-t THUMBPRINT`, `--cert-thumbprint THUMBPRINT` The thumbprint of the SSL certificate. Required when the `--cert-install` option is not part of a command. winrm ----- Use the `winrm` argument to create a connection to one or more remote machines. As each connection is created, a password must be provided. This argument uses the same syntax as the `search` subcommand. WinRM requires that a target node be accessible via the ports configured to support access via HTTP or HTTPS. ### Syntax This argument has the following syntax: ``` knife winrm SEARCH_QUERY SSH_COMMAND (options) ``` ### Options This argument has the following options: `-a ATTR`, `--attribute ATTR` The attribute used when opening a connection. The default attribute is the FQDN of the host. Other possible values include a public IP address, a private IP address, or a hostname. `-C NUM`, `--concurrency NUM` Changed in knife-windows 1.9.0. The number of allowed concurrent connections. Defaults to 1. `-f CA_TRUST_FILE`, `--ca-trust-file CA_TRUST_FILE` Optional. The certificate authority (CA) trust file used for SSL transport. `-p PORT`, `--winrm-port PORT` The WinRM port. The TCP port on the remote system to which `knife windows` commands that are made using WinRM are sent. Default: `5986` when `--winrm-transport` is set to `ssl`, otherwise `5985`. `-P PASSWORD`, `--winrm-password PASSWORD` The WinRM password. `-R KERBEROS_REALM`, `--kerberos-realm KERBEROS_REALM` Optional. The administrative domain to which a user belongs. `--returns CODES` A comma-delimited list of return codes that indicate the success or failure of the command that was run remotely. `-S KERBEROS_SERVICE`, `--kerberos-service KERBEROS_SERVICE` Optional. The service principal used during Kerberos-based authentication. `SEARCH_QUERY` The search query used to return a list of servers to be accessed using SSH and the specified `SSH_COMMAND`. This option uses the same syntax as the search subcommand. `SSH_COMMAND` The command to be run against the results of a search query. `--session-timeout MINUTES` The amount of time (in minutes) for the maximum length of a WinRM session. `--ssl-peer-fingerprint FINGERPRINT` SSL Cert Fingerprint to bypass normal cert chain checks `-t TRANSPORT`, `--winrm-transport TRANSPORT` The WinRM transport type. Possible values: `ssl` or `plaintext`. `-T`, `--keytab-file KEYTAB_FILE` The keytab file that contains the encryption key required by Kerberos-based authentication. `--winrm-authentication-protocol PROTOCOL` The authentication protocol to be used during WinRM communication. Possible values: `basic`, `kerberos` or `negotiate`. Default value: `negotiate`. `--winrm-codepage Codepage` The codepage to use for the WinRM Command Shell `--winrm-shell SHELL` The WinRM shell type. Valid choices are `cmd`, `powershell` or `elevated`. Default value: `cmd`. The `elevated` shell is similar to the `powershell` option, but runs the powershell command from a scheduled task. `--winrm-ssl-verify-mode MODE` The peer verification mode that is used during WinRM communication. Possible values: `verify_none` or `verify_peer`. Default value: `verify_peer`. `-x USERNAME`, `--winrm-user USERNAME` The WinRM user name. Examples -------- **Find Uptime for Web Servers** To find the uptime of all web servers, enter: ``` knife winrm "role:web" "net stats srv" -x Administrator -P password ``` **Force a Chef Infra Client run** To force a Chef Infra Client run: ``` knife winrm 'ec2-50-xx-xx-124.amazonaws.com' 'chef-client -c c:/chef/client.rb' -m -x admin -P 'password' ec2-50-xx-xx-124.amazonaws.com [date] INFO: Starting Chef Run (Version 0.9.12) ec2-50-xx-xx-124.amazonaws.com [date] WARN: Node ip-0A502FFB has an empty run list. ec2-50-xx-xx-124.amazonaws.com [date] INFO: Chef Run complete in 4.383966 seconds ec2-50-xx-xx-124.amazonaws.com [date] INFO: cleaning the checksum cache ec2-50-xx-xx-124.amazonaws.com [date] INFO: Running report handlers ec2-50-xx-xx-124.amazonaws.com [date] INFO: Report handlers complete ``` Where in the examples above, `[date]` represents the date and time the long entry was created. For example: `[Fri, 04 Mar 2011 22:00:53 +0000]`. **Generate an SSL certificate, and then create a listener** Use the `listener create`, `cert generate`, and `cert install` arguments to create a new listener and assign it a newly-generated SSL certificate. First, make sure that WinRM is enabled on the machine. Do so by running the following command on the Windows node: ``` C:\> winrm quickconfig ``` Create the SSL certificate ``` knife windows cert generate --domain myorg.org --output-file $env:userprofile/winrmcerts/winrm-ssl ``` This command may be run on any machine and will output three file types: `.b64`, `.pem`, and `.pfx`. Next, create the SSL listener: ``` knife windows listener create --hostname *.myorg.org --cert-install $env:userprofile/winrmcerts/winrm-ssl.pfx ``` This will use the same `.pfx` file that was output by the `cert generate` argument. If the command is run on a different machine from that which generated the certificates, the required certificate files must first be transferred securely to the system on which the listener will be created. (Use the `cert install` argument to install a certificate on a machine.) The SSL listener is created and should be listening on TCP port `5986`, which is the default WinRM SSL port. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_windows/knife xargs =========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_xargs.md) Use the `knife xargs` subcommand to take patterns from standard input, download as JSON, run a command against the downloaded JSON, and then upload any changes. Syntax ------ This subcommand has the following syntax: ``` knife xargs [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-0` Default: `false`. `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--[no-]diff` Show a diff when a file changes. Default: `--diff`. `--dry-run` Prevent changes from being uploaded to the Chef Infra Server. Default: `false`. `--[no-]force` Force the upload of files even if they haven’t been changed. Default: `--no-force`. `-I REPLACE_STRING`, `--replace REPLACE_STRING` Define a string that is to be used to replace all occurrences o file name. Default: `nil`. `-J REPLACE_STRING`, `--replace-first REPLACE_STRING` Define a string that is to be used to replace the first occurrence of a file name. Default: `nil`. `--local` Build or execute a command line against a local file. Set to `false` to build or execute against a remote file. Default: `false`. `-n MAX_ARGS`, `--max-args MAX_ARGS` The maximum number of arguments per command line. Default: `nil`. `-p [PATTERN...]`, `--pattern [PATTERN...]` One (or more) patterns for a command line. If this option is not specified, a list of patterns may be expected on standard input. Default: `nil`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default value: `default`. `-s LENGTH`, `--max-chars LENGTH` The maximum size (in characters) for a command line. Default: `nil`. `-t` Run the print command on the command line. Default: `nil`. Note See [config.rb](../config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Find, and then replace data** The following example will go through all nodes on the server, and then replace the word `foobar` with `baz`: ``` knife xargs --pattern /nodes/* "perl -i -pe 's/foobar/baz'" ``` **Use output of knife list and Perl** The following examples show various ways of listing all nodes on the server, and then using Perl to replace `grantmc` with `gmc`: ``` knife list 'nodes/*' | knife xargs "perl -i -pe 's/grantmc/gmc'" ``` or without quotes and the backslash escaped: ``` knife list /nodes/\* | knife xargs "perl -i -pe 's/grantmc/gmc'" ``` or by using the `--pattern` option: ``` knife xargs --pattern '/nodes.*' "perl -i -pe 's/grantmc/gmc'" ``` **View security groups data** The following example shows how to display the content of all groups on the server: ``` knife xargs --pattern '/groups/*' cat ``` and will return something like: ``` { "name": "4bd14db60aasdfb10f525400cdde21", "users": [ "grantmc" ] }{ "name": "62c4e268e15fasdasc525400cd944b", "users": [ "robertf" ] }{ "name": "admins", "users": [ "grantmc", "robertf" ] }{ "name": "billing-admins", "users": [ "dtek" ] }{ "name": "clients", "clients": [ "12345", "67890", ] }{ "name": "users", "users": [ "grantmc" "robertf" "dtek" ], "groups": [ "4bd14db60aasdfb10f525400cdde21", "62c4e268e15fasdasc525400cd944b" ] } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/knife_xargs/Effortless Overview =================== [[edit on GitHub]](https://github.com/chef/effortless/tree/main/docs-chef-io/content/effortless/_index.md) Welcome to the Chef Effortless Patterns ======================================= The Effortless Pattern is a way to better manage Chef Infra and Chef InSpec workloads using Chef Habitat, and to visualize your fleet using Chef Automate. We believe that each of these technologies working together can help you better manage your infrastructure. Who Should Use Effortless ------------------------- If you use Chef Infra or Chef InSpec to manage your operating system configs, you should look at using Effortless. Effortless uses the power of Chef Habitat to help with you with Chef Infra and Chef InSpec dependency management. Chef Habitat pulls in the cookbooks and profiles that your cookbook and/or Chef InSpec profiles depend upon and packages them as a signed artifact. By packaging the latest and best practices for running Chef Infra and Chef InSpec on your systems, you do not have to worry about setting up the Chef Infra Client or the Chef InSpec client to run on your system. When Is Using Effortless Not The Best Approach ---------------------------------------------- * If you use Chef Infra to deploy complex applications, you may not want to use the Effortless pattern. + Effortless does not support situations that require a Chef Infra Server. For example, if you use search in your cookbooks, or use `chef vault` for secrets management, then Effortless will not work for those cookbooks + If you have complex applications, you should deploy them with Chef Habitat as it has more features that better support complex applications * If you have a bunch of nested cookbooks or Policyfiles in a complex [Chef Roles](../roles/index) and [Chef Environments](../environments/index) setup, you may not want to move to Effortless. + When you have a base cookbook and a bunch of Applications cookbooks dependent on that base cookbook, managing the build graph can become difficult because a change to the base cookbook will require a build to all the application cookbooks. Effortless in this situation can quickly become difficult to manage. Purpose ------- The purpose of the Effortless pattern is to reduce the amount of code and Chef knowledge a user needs to be successful with Chef products. Quick Links ----------- * [Chef Infra](https://github.com/chef/chef) - Chef Infra automates infrastructure configuration and ensures every system configures correctly and consistently. * [Chef InSpec](https://github.com/inspec/inspec) - Chef InSpec automates security tests, and ensures enforcement of consistent standards in every environment and at every stage of development. * [Chef Habitat](https://github.com/habitat-sh/habitat) - Chef Habitat codifies how the application builds, how it runs, and its dependencies to free the application from underlying infrastructure and make updates easy. * [Chef Automate](https://github.com/chef/automate) - Chef Automate provides an Enterprise dashboard and analytics tool to enable cross-team collaboration with actionable insights for configuration and compliance, and an auditable history of environment changes. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/effortless/Effortless Quick Start ====================== [[edit on GitHub]](https://github.com/chef/effortless/tree/main/docs-chef-io/content/effortless/quick_start.md) Quick Start =========== This is a quick guide on how to get started with Effortless. Effortless Environment Set-up ----------------------------- 1. Install [Chef Workstation](https://downloads.chef.io/chef-workstation) 2. Configure Chef Habitat on your workstation by running `hab setup` 3. Clone the [Chef Effortless GitHub Repository](https://github.com/chef/effortless) Effortless Config Quick Start Pattern ------------------------------------- 1. Change Directory into `examples/effortless_config/chef_repo_pattern` 2. Change the line 26 of the `kitchen.yml` file to use your origin: ``` provisioner:arguments:["<Your Origin>","effortless-config-baseline"] ``` 3. Build the package with the command: `hab pkg build .` 4. Run Test Kitchen to see the cookbook work: ``` kitchen converge base-centos ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/effortless/quick_start/Upgrade Lab: Chef Infra Client 12 to latest =========================================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/upgrade_lab.md) Chef Software’s Upgrade Lab provides an isolated cookbook development environment and in-line support to help you upgrade your system, so you can stop using legacy Chef Infra and start using modern Chef Infra. The Upgrade Lab provides a report of your existing nodes and cookbooks, so you will know the scope of the work and you can identify a good place to start. Upgrade Lab works by capturing any node from the production environment and recreating it locally by generating a repository for that node, which provides you with a sandbox to work through upgrading and testing your cookbooks at a safe distance from your production environment. About This Guide ---------------- This guide covers the straightforward pattern of upgrading from Chef Infra Client 12 to Chef Infra Client 16, including upgrading Chef Infra Server as you go. While we think this guide is the smoothest path forward, it is not meant to exclude other approaches. Unless otherwise indicated, you will run all commands in your local development environment. Note This guide illustrates the basic case of upgrading a single node in isolation, including migrating the node from one Chef Infra Server to a new Chef Infra Server. More complex situations, such as those involving pooled nodes using Chef Infra Server search for peer discovery, are not covered here. Please contact your Customer Success team for more complex cases. Chef Upgrade Lab Requirements ----------------------------- ### System Architecture Requirements The Chef Upgrade Lab makes some basic assumptions about your existing system: * Two Chef Infra Servers + A Chef Infra Server running some older version + A newly installed Chef Infra Server running the latest software, set up and configured for knife, but otherwise empty * One or more nodes + Running Chef Infra Client 12 or later + Minimum 512 MB RAM + [Recommended](../../chef_system_requirements/index#chef-infra-client) 5GB space + Bootstrapped to the older Chef Infra Server + `sudo` permissions on the node + SSH connectivity between the nodes and the administrator/developer workstation * An administrator/developer workstation + 64-bit architecture + Minimum 4 GB RAM + Recommended 10 GB of available disk space for installing Chef Workstation and running the Chef Upgrade Lab ### Software Requirements * Review the [platform and system requirements](../install_workstation/index) for Chef Workstation * Install or upgrade to the Chef Workstation [latest version](https://www.chef.io/downloads/tools/workstation) Chef does not prescribe any specific editor. However, the [Chef Infra extension](https://marketplace.visualstudio.com/items?itemName=chef-software.Chef) for [Visual Studio Code](https://code.visualstudio.com/) features several code generators and helpful features, such as running Cookstyle each time you save a recipe. ### Server Backup We recommend performing a backup before starting any server upgrade process. Follow the [Chef Infra Server Backup](../../runbook/server_backup_restore/index) documentation before starting your Upgrade Lab. ### Infrastructure Requirements #### Credentials Your credentials are set up using [knife profiles](../knife_setup/index#knife-profiles). This method allows you to keep your keys in a `credentials` file, and makes switching between credentials easier. For example, in `.chef/credentials`: ``` [old-server] client_name = "user_name" chef_server_url = "https://old-chef-server.dev/organizations/my-org" client_key = """ -----BEGIN RSA PRIVATE KEY----- MMM+some+key+goes+here+MMM -----END RSA PRIVATE KEY----- """ [new-server] client_name = "user_name" chef_server_url = "https://new-chef-server.dev/organizations/my-org" client_key = """ -----BEGIN RSA PRIVATE KEY----- MMM+another+key+goes+here+MMM -----END RSA PRIVATE KEY----- """ ``` #### Connectivity You must have a user key for both of the Chef Infra Servers and you must be able to connect to both Chef Infra Servers from your development workstation. Verify connectivity by running a `knife` command and receiving a reasonable response from each server: ``` chef exec knife user list --profile old-server user_name chef exec knife user list --profile new-server user_name ``` #### Convergence Your nodes are in a good working order. They converge cleanly under the older version of Chef Infra Client. Verify that the nodes are healthy by running: ``` chef exec knife status --profile old-server ``` The output should look similar to: ``` 42 minutes ago, node-01, ubuntu 18.04. ``` This command outputs the time of the last successful Chef Infra Client run of each node. Nodes that return radically different times for the last successful Chef Infra Client run are not in good working order. #### Cookbook CI/CD While we do not prescribe a particular choice of technology or the details of processes, the Chef Upgrade Lab expects a continuous integration pipeline and continuous delivery system (CI/CD) for cookbook deployments. The Upgrade Lab assumes but does not require that you have a continuous integration pipeline (CI) setup for your cookbooks with: * A version control system (for example, git) * Some degree of automated testing for proposed changes * A continuous delivery system (CD) that controls cookbook releases; the CD is the mechanism for updating cookbook versions and uploading them to the Chef Infra Server(s) If you do not have a version control system and CI/CD pipeline in place, then please contact your account team for help or find us at [<EMAIL>](mailto:<EMAIL>). You can also ask questions in the Chef community channels: * Chef Community Slack at <https://community-slack.chef.io/>. * Chef Mailing List <https://discourse.chef.io/ Upgrade Lab ----------- ### Inventory Your System with Chef Reports We recommend starting the upgrade process on a node with a simple setup, such as one with fewer and simpler cookbooks. The `chef report` command surveys your nodes and cookbooks. Use the reports to identify a good starting place. #### chef report nodes The `chef report nodes -p PROFILE` command will: * create a report of the nodes in your system from Ohai data * print a report summary to the screen * save the report to the `.chef-workstation/reports/` directory Create a node report from your development workstation by running: ``` chef report nodes -p old-server ``` Which outputs a node report: ``` Analyzing nodes... -- REPORT SUMMARY -- Node Name Chef Version Operating System Number Cookbooks --------------------------------+--------------+---------------------+------------------- node-01 12.22.5 windows v10.0.14393 18 node-02 12.22.5 windows v10.0.14393 18 node-03 12.22.5 windows v10.0.14393 5 node-04 12.18.31 windows v6.3.9600 5 Nodes report saved to /Users/user_name/.chef-workstation/reports/nodes-20200324135111.txt ``` #### chef report cookbooks The `chef report cookbooks -p PROFILE` command will: * create a report of the cookbooks in your system from Ohai data * print a report summary to the screen * save the report to the `.chef-workstation/reports/` directory This report shows that there are two cookbooks on the server. It analyzes the cookbooks, looking for cookbook issues that will be problematic in later versions of the Chef Infra Client by running the `cookstyle` program. Here, we see that the `cron` cookbook has a single violation, and which can be auto-corrected by `cookstyle`. Create a cookbook report from your development workstation by running: ``` chef report cookbooks -V -p old-server ``` Which outputs a cookbook report: ``` Cookbook Version Violations Auto-correctable Nodes Affected -----------------------+---------+------------+------------------+----------------- cron 1.7.5 1 1 1 upgrade_labs_problems 0.1.0 2 2 1 Cookbooks report saved to /Users/user_name/.chef-workstation/reports/cookbooks-20200504155204.txt ``` ### Create an Upgrade Environment with chef capture The `chef capture NODE` command will: * Create a repository for that node in the current directory * Help you obtain and organize the cookbooks you need to converge the node * Create a `kitchen.yml`, which allows you to use Test Kitchen to perform local development Run the command: ``` chef capture NODE ``` The screen output describes the capture process: ``` - Setting up local repository - Capturing node object '' - Capturing cookbooks... - Capturing environment... - Capturing roles... - Writing kitchen configuration... Repository has been created in './node-NODE-repo'. ``` #### Add Cookbook Source Locations After creating the repo, `chef capture NODE` prompts you to fetch the cookbooks from their original locations. Upgrading a node means upgrading its cookbooks so that it can run the latest version of Chef Infra Client. Ideally, you can get the cookbooks from their canonical source (that is, `git clone` or another similar version control operation). If you are working with a version control system, you can make and test your changes locally and then push the changes back to the cookbook’s source. This fully leverages the benefits of your cookbook CI/CD pipeline by allowing your changes to go through proper version control, peer review, automated testing, and automated deployment. If you can’t locate a cookbook, do not download it from an external source, such as the public Chef Supermarket. The cookbook version in your development environment must match the version on your node. [As a last resort](#download-cookbooks-from-chef-infra-server), the Upgrade Lab can get copies of your cookbooks from the Chef Infra Server during the `capture` phase. Likely cookbook locations: * Checked into your version control system * On a private Supermarket installation * In an existing [cookbook development directory](#main-cookbook-development-location) **Cookbook Directory Layout** If you have access to cookbook sources, storing cookbooks in one parent directory is easier, similar to this: ``` /Users/user_name/my_cookbooks/ --- cron -- .git/ # Or other version control bookkeeping -- recipes/ -- ... -- metadata.rb --- chef-client -- .cvs/ # Or other version control bookkeeping -- recipes/ -- ... -- metadata.rb --- my_custom_cookbook -- .git/ # Or other version control bookkeeping -- recipes/ -- ... -- metadata.rb ``` The Upgrade Lab works if you have cookbooks in different locations, but it involves more prompting from the command line. #### Main Cookbook Development Location The `chef capture` command prompts you first for your main cookbook source location: ``` Next, locate version-controlled copies of the cookbooks. This is important so that you can track changes to the cookbooks as you edit them. You may have one or more existing paths where you have checked out cookbooks. If not, now is a good time to open a separate terminal and clone or check out the cookbooks. If all cookbooks are not available in the same base location, you will have a chance to provide additional locations. Press Enter to Continue: Please clone or check out the following cookbooks locally from their original sources, and provide the base path for the checkout: - cron (v1.6.1) - chef-client (v4.3.0) - logrotate (v1.9.2) - windows (v1.44.1) - chef_handler (v1.4.0) If sources are not available for these cookbooks, leave this blank. Checkout Location [none]: ``` At this point, enter the path to your cookbook development directory, for example, `/Users/user_name/my_cookbooks` at the prompt. `chef capture` scans that path and locates the cookbooks that it needs. The command finishes once it accounts for all cookbook sources; but if any are missing, it will prompt for them in the next step. ``` Checkout Location [none]: /src/my_cookbooks Using your checked-out cookbook: cron using your checked-out cookbook: chef-client ``` **Alternate Cookbook Source Locations** Suppose that your node requires 5 cookbooks: * `cron` (v1.6.1) * `chef-client` (v4.3.0) * `logrotate` (v1.9.2) * `windows` (v1.44.1) * `chef_handler` (v1.4.0) If the directory you provided in the initial prompt contains only `cron` and `chef-client`, then `chef capture` prompts you to add the locations for sources for the remaining three: ``` Please provide the base checkout path for the following cookbooks, or leave blank if no more cookbooks are checked out: - logrotate (v1.9.2) - windows (v1.44.1) - chef_handler (v1.4.0) Checkout Location [none]: ``` `chef capture` scans the path that you provide and locates the cookbooks that it needs. The command finishes once it accounts for all cookbook sources; it prompts you for another path if it needs more cookbook sources. ### Download Cookbooks from Chef Infra Server If you do not have access to the original version-controlled source of a cookbook, press return at the prompt for `chef capture` to use a copy of the cookbook downloaded from the Chef Infra Server. Upgrading cookbooks from the Chef Infra Server is not an ideal practice. You will make changes to your cookbooks during the course of the upgrade. Making changes to your cookbooks without the ability to track your changes in version control almost inevitably leads to conflicts between cookbook sources. Reconciling cookbooks with untracked changes is a difficult and time-consuming process. If you find yourself using many cookbooks–or complex cookbooks–downloaded from the Chef Infra Server, it will be worth the effort in the long run to try to track down their version-controlled sources. Tracking and testing changes in a CI/CD pipeline is an important part of managing your Chef infrastructure, but are beyond the scope of this guide. See [Learn Chef Rally](https://learn.chef.io/) for tutorials and contact your Customer Success team when you are ready to modernize your system. ``` ------------------------ WARNING --------------------------- Changes made to the following cookbooks in ./node-MY_NODE-repo/cookbooks cannot be saved to the cookbook's source, though they can still be uploaded to a Chef Server: - logrotate (v1.9.2) - windows (v1.44.1) - chef_handler (v1.4.0) ----------------------------------------------------------- You're ready to begin! Start with 'kitchen converge'. As you identify issues, you can modify cookbooks in their original checkout locations or in the repository's cookbooks directory and they will be picked up on subsequent runs of 'kitchen converge'. ``` Detect and Correct Cookbook Errors ---------------------------------- Note Be cautious when running your cookbooks locally. It is possible to accidentally impact production infrastructure based on settings in your cookbooks and attributes. Read over your cookbooks and attributes, especially attributes set in roles and environments. If needed, override attributes so they can be tested locally in your `kitchen.yml`. ### Increment the Chef Infra Client Version In the `kitchen.yml` file, change the `product_version` line to `16`: ``` provisioner:name:chef_zeroproduct_name:chefproduct_version:16# Change this line ``` If needed, you can “step forward” versions by first going from 12 to 13, correcting any issues, and then incrementing from 13 to 14, etc. until you reach Chef Infra Client 16. ### Attempt a Converge and Check for Errors Save the file and test it in the `node-MY_NODE-repo` directory by running: ``` chef exec kitchen converge ``` Watch for Chef Infra errors. If any occur, fix them. ### Test and Correct with Cookstyle To check for version upgrade issues, run: ``` chef exec cookstyle cookbooks/my_cookbook ``` Repeat this process for each cookbook for that node. #### Using Cookstyle Auto-correct Use Cookstyle’s auto-correct feature to fix style errors by adding the `-a` (for auto-correct) flag: ``` chef exec cookstyle -a cookbooks/my_cookbook ``` Other issues may require manual intervention and editing. Repeat this process for each cookbook that the node consumes. ### Copy Data Bags If your Chef Infra Server uses data bags, you will need to download the `data_bags` directory into your chef repo with the `chef exec knife download data_bags` command. This command does not support embedded keys in credentials files. If you use embedded keys, move the key to a key file. ``` cd node-node-01-repo chef exec knife download data_bags --chef-repo-path . --profile old-server --key my-old-key.pem ``` Deploy Your Chef Lab Upgrades ----------------------------- Note This guide suggests migrating upgraded cookbooks and nodes to a new Chef Infra Server. This pattern is not possible for all customers, specifically those who rely on `chef search` for inventory and coordination. Migrating to a new server works for customers who do not rely on search because it creates a fresh start to build on for future migration to Effortless. If you rely on `knife search`, or setting up a new Chef Infra Server is not possible, upload the upgraded cookbooks to your existing Chef Infra Server. If you do this, be sure to pin your cookbook versions on existing nodes, so that the upgraded cookbook can be manually promoted to desired nodes. ### Commit Your Cookbook Upgrades As you make changes to the cookbooks, follow your organization’s existing software development practices. Commit your changes to your cookbooks and submit your changes to your cookbook pipeline to be tested by your automated testing system. Once the changes have passed testing, the cookbooks should receive new version numbers and be published to the new Chef Infra Server by the continuous deployment system. ### Optionally Upload Your Cookbook Upgrades to the New Server If your organization does not have a cookbook pipeline in place, or if you are setting up a proof of concept, you can directly upload the cookbooks to the new server. We do not recommend this because it makes it difficult to manage changes to cookbook code. This command does not support embedded keys in credentials files, so you must place the key in a key file. ``` cd node-node-01-repo chef exec knife upload cookbooks --chef-repo-path . --profile new-server --key ../keys/my-new-key.pem ``` ### Upload Supplemental Data to the New Server Next, upload the remaining data to the new server. Note that `knife upload` command does not support embedded keys in credentials files, so you must place the key in a key file. #### Node Data If you use node search, upload the node data to the new server: ``` chef exec knife upload nodes --chef-repo-path . --profile new-server --key ../keys/my-new-key.pem ``` #### Roles If you use roles, upload them to the new server: ``` chef exec knife upload roles --chef-repo-path . --profile new-server --key ../keys/my-new-key.pem ``` #### Environments If you use environments, upload them to the new server: ``` chef exec knife upload environments --chef-repo-path . --profile new-server --key ../keys/my-new-key.pem ``` #### Data Bags If you used data bags, upload them to the new server: ``` chef exec knife upload data_bags --chef-repo-path . --profile new-server --key ../keys/my-new-key.pem ``` Attach the Upgraded Node to the New Server ------------------------------------------ ### Issue a new Bootstrap Command Migrate your node to the new server by running a bootstrap command similar to: ``` chef exec knife bootstrap \ --profile new-server --chef-license accept \ -r cookbook::recipe,another_cookbook::recipe \ -N node-01 -y --sudo \ --bootstrap-version 16 \ user@somehost.example ``` Bootstrapping nodes in this way upgrades the installed Chef Infra Client to version 16. Congratulations! Optionally, delete your node record from the old server using: ``` chef exec knife node delete node-01 --profile old-server ``` Repeat as Needed ---------------- Happy Converging! © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/upgrade_lab/Writing Custom Knife Plugins ============================ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/plugin_knife_custom.md) A knife plugin is a set of one (or more) subcommands that can be added to knife to support additional functionality that is not built-in to the base set of knife subcommands. Many of the knife plugins are built by members of the Chef community and several of them are built and maintained by Chef. The Chef Infra Client will load knife plugins from the following locations: * The home directory: `~/.chef/plugins/knife/` * A `.chef/plugins/knife` directory in the cookbook repository * A plugin installed from RubyGems. (For more information about releasing a plugin on RubyGems, see: <http://guides.rubygems.org/make-your-own-gem/>.) This approach allows knife plugins to be reused across projects in the home directory, kept in a repository that is accessible to other team members, and distributable to the community using RubyGems. Syntax ------ There are many ways to structure a knife plugin. The following syntax shows a typical knife plugin: ``` require 'chef/knife' # other require attributes, as needed module ModuleName class SubclassName < Chef::Knife deps do require 'chef/dependency' # other dependencies, as needed end banner "knife subcommand argument VALUE (options)" option :name_of_option, :short => "-l VALUE", :long => "--long-option-name VALUE", :description => "The description for the option.", :proc => Proc.new { code_to_run } :boolean => true | false :default => default_value def run # Ruby code goes here end end end ``` where: * `require` identifies any other knife subcommands and/or knife plugins required by this plugin * `module ModuleName` declares the knife plugin as its own namespace * `class SubclassName < Chef::Knife` declares the plugin as a subclass of `Knife`, which is in the `Chef` namespace. The capitalization of this name is important. For example, `SubclassName` would have a knife command of `knife subclass name`, whereas `Subclassname` would have a knife command of `knife subclassname` * `deps do` is a list of dependencies * `banner "knife subcommand argument VALUE (options)"` is displayed when a user enters `knife subclassName --help` * `option :name_of_option` defines each of the command-line options that are available for this plugin. For example, `knife subclass -l VALUE` or `knife subclass --long-option-name VALUE` * `def run` is the Ruby code that is executed when the command is run and where for each command-line option: * `:short` defines the short option name * `:long` defines the long option name * `:description` defines a description that is displayed when a user enters `knife subclassName --help` * `:boolean` defines whether the option is `true` or `false`; if the `:short` and `:long` names define a `VALUE`, then this attribute must not be used * `:proc` defines code that determines the value for this option * `:default` defines a default value The following example shows part of a knife plugin named `knife windows`: ``` require 'chef/knife' require 'chef/knife/winrm_base' class Chef class Knife class Winrm < Knife include Chef::Knife::WinrmBase deps do require 'readline' require 'chef/search/query' require 'em-winrm' end attr_writer :password banner "knife winrm QUERY COMMAND (options)" option :attribute, :short => "-a ATTR", :long => "--attribute ATTR", :description => "The attribute to use for opening the connection - default is fqdn", :default => "fqdn" ... # more options def session session_opts = {} session_opts[:logger] = Chef::Log.logger if Chef::Log.level == :debug @session ||= begin s = EventMachine::WinRM::Session.new(session_opts) s.on_output do |host, data| print_data(host, data) end s.on_error do |host, err| print_data(host, err, :red) end s.on_command_complete do |host| host = host == :all ? 'All Servers' : host Chef::Log.debug("command complete on #{host}") end s end end ... # more def blocks end end end ``` Take a look at all of the code for this plugin on GitHub: <https://github.com/chef/knife-windows/blob/main/lib/chef/knife/winrm.rb>. ### Namespace A knife plugin should have its own namespace (even though knife will load a command regardless of its namespace). The namespace is declared using the `module` method, for example: ``` require 'chef/knife' ## other require attributes, as needed module MyNamespace class SubclassName < Chef::Knife ``` where `module MyNamespace` declares that the knife plugin has its own namespace, with a namespace of `MyNamespace`. ### Class Name The class name declares a plugin as a subclass of both `Knife` and `Chef`. For example: ``` class SubclassName < Chef::Knife ``` where `SubclassName` is the class name used by this plugin. The capitalization of this name is important. For example, `OMG` would have a knife command of `knife o m g`, whereas `Omg` would have a knife command of `knife omg`. Use the capitalization pattern to define the word grouping that best makes sense for the plugin. A plugin can override an existing knife subcommand by using the same class name as the existing subcommand. For example, to override the current functionality of `knife cookbook upload`, use the following class name: ``` class CookbookUpload < Chef::Knife ``` ### Banner A banner displays the syntax for the plugin to users when they enter the `--help` option. Use the `banner` method in the class body similar to the following: ``` module example class example < Chef::Knife banner "knife example" ... end ``` and the when a user enters `knife --help`, the following will be displayed: ``` **EXAMPLE COMMANDS** knife example ``` ### Dependencies The functionality of other knife plugins can be accessed from a plugin by using the `deps` method to ensure the necessary files are available. The `deps` method acts as a lazy loader, ensuring that dependencies are only loaded into knife when the plugin which requires them is run. Use the following syntax just below the class declaration: ``` class subclassName < Chef::Knife deps do require 'chef/knife/name_of_command' require 'chef/search/query' # other dependencies, as needed end ``` where the actual path may vary from plugin to plugin, but is typically located in the `chef/knife/` directory. Note Using the `deps` method instead of `require` is recommended, especially if the environment in which knife is being run contains a lot of plugins and/or any of those plugins have a lot of dependencies and/or requirements on other plugins and search functionality. #### Requirements The functionality of other knife plugins can be accessed from a plugin by using the `require` method to ensure the necessary files are available, and then within the code for the plugin, to create a new object of the class of the plugin to be used. First, ensure that the correct files are available using the following syntax: ``` require 'chef/knife/name_of_command' ``` where the actual path may vary from plugin to plugin, but is typically located in the `chef/knife/` directory. Note Using the `deps` method instead of `require` is recommended, especially when the environment in which knife is being run contains a lot of plugins and/or any of those plugins have a lot of dependencies and/or requirements on other plugins and search functionality. For example, use the following to require a plugin named `bootstrap`: ``` require 'chef/knife/bootstrap' ``` Next, for the required plugin, create an object of that plugin, like this: ``` bootstrap = Chef::Knife::Bootstrap.new ``` and then pass arguments or options to that object. This is done by altering that object’s `config` and `name_arg` variables. For example: ``` bootstrap.config[:ssh_user] = "myuser" bootstrap.config[:distro] = "ubuntu10.04-gems" bootstrap.config[:use_sudo] = true bootstrap.name_args = "some_host_name" ``` where the available configuration objects vary from plugin to plugin. Make sure those configuration objects are correct by verifying them in the source files for each plugin. And then call the object’s `run` method, like this: ``` bootstrap.run ``` ### Options Command-line options can be added to a knife plugin using the `option` method. An option can have a true/false value: ``` option :true_or_false, :short => "-t", :long => "--true-or-false", :description => "Is this value true? Or is this value false?", :boolean => true | false :default => true ``` and it can have a string value: ``` option :some_type_of_string_value, :short => "-s VALUE", :long => "--some-type-of-string-value VALUE", :description => "This is not a random string value.", :default => 47 ``` and can specify code that is run to determine the option’s value: ``` option :tags, :short => "-T T=V[,T=V,...]", :long => "--tags Tag=Value[,Tag=Value...]", :description => "A list of tags associated with the virtual machine", :proc => Proc.new { |tags| tags.split(',') } ``` where the knife command allows a comma-separated list of values and the `:proc` attribute converts that list of values into an array. When a user enters `knife --help`, the description attributes are displayed as part of the help. Using the previous examples, something like the following will be displayed: ``` **EXAMPLE COMMANDS** knife example -s, --some-type-of-string-value This is not a random string value. -t, --true-or-false Is this value true? Or is this value false? -T, --tags A list of tags associated with the virtual machine. ``` When knife runs the command, the options are parsed from the command-line and make the settings available as a hash that can be used to access the `config` method. For example, the following option: ``` option :omg, :short => '-O', :long => '--omg', :boolean => true, :description => "I'm so excited!" ``` can be used to update the `run` method of a class to change its behavior based on the `config` flag, similar to the following: ``` def run if config[:omg] # Oh yeah, we are pumped. puts "OMG HELLO WORLD!!!1!!11" else # meh puts "I am just a boring example." end end ``` For a knife plugin with the `--omg` option, run `knife example --omg` to return something like: ``` OMG HELLO WORLD!!!1!!11 ``` or just `knife example` to return: ``` I am just a boring example. ``` ### Arguments A knife plugin can also take command-line arguments that are not specified using the `option` flag, for example: `knife node show NODE`. These arguments are added using the `name_args` method. For example: ``` banner "knife hello world WHO" def run unless name_args.size == 1 puts "You need to say hello to someone!" show_usage exit 1 end who = name_args.first if config[:omg] puts "OMG HELLO #{who.upcase}!!!1!!11" else puts "Hello, #{who.capitalize}!" end end ``` where * `unless name_args.size == 1` is used to check the number of arguments given; the command should fail if the input does not make sense * `who = name_args.first` is used to access arguments using `name_args` * `show_usage` is used to display the correct usage before exiting (if the command fails) For example, the following command: ``` knife hello world ``` will return: ``` You need to say hello to someone! USAGE: knife hello world WHO ``` the following command: ``` knife hello world chefs ``` will return: ``` Hello, Chefs! ``` and the following command: ``` knife hello world chefs --omg ``` will return: ``` OMG HELLO CHEFS!!!1!!11 ``` ### config.rb Settings Certain settings defined by a knife plugin can be configured so that they can be set using the config.rb file. This can be done in two ways: * By using the `:proc` attribute of the `option` method and code that references `Chef::Config[:knife][:setting_name]` * By specifying the configuration setting directly within the `def` Ruby blocks using either `Chef::Config[:knife][:setting_name]` or `config[:setting_name]` An option that is defined in this manner may be configured using the config.rb file with the following syntax: ``` knife[:setting_name] ``` This approach can be useful when a particular setting is used a lot. The order of precedence for a knife option is: 1. A value passed via the command line 2. A value saved in the config.rb file 3. A default value The following example shows how the `knife bootstrap` subcommand checks for a value in the config.rb file by using the `:proc` attribute: ``` option :ssh_port, :short => "-p PORT", :long => "--ssh-port PORT", :description => "The ssh port", :proc => Proc.new { |key| Chef::Config[:knife][:ssh_port] = key } ``` where `Chef::Config[:knife][:ssh_port]` tells knife to check the config.rb file for a setting named `knife[:ssh_port]`. And the following example shows the `knife bootstrap` subcommand calling the `knife ssh` subcommand for the actual SSH part of running a bootstrap operation: ``` def knife_ssh ssh = Chef::Knife::Ssh.new ssh.ui = ui ssh.name_args = [ server_name, ssh_command ] ssh.config[:ssh_user] = Chef::Config[:knife][:ssh_user] || config[:ssh_user] ssh.config[:ssh_password] = config[:ssh_password] ssh.config[:ssh_port] = Chef::Config[:knife][:ssh_port] || config[:ssh_port] ssh.config[:ssh_gateway] = Chef::Config[:knife][:ssh_gateway] || config[:ssh_gateway] ssh.config[:identity_file] = Chef::Config[:knife][:identity_file] || config[:identity_file] ssh.config[:manual] = true ssh.config[:host_key_verify] = Chef::Config[:knife][:host_key_verify] || config[:host_key_verify] ssh.config[:on_error] = :raise ssh end ``` where * `ssh = Chef::Knife::Ssh.new` creates a new instance of the `Ssh` subclass named `ssh` * A series of settings in `knife ssh` are associated with `knife bootstrap` using the `ssh.config[:setting_name]` syntax * `Chef::Config[:knife][:setting_name]` tells knife to check the config.rb file for various settings * Raises an exception if any aspect of the SSH operation fails ### Search Use the Chef Infra Server search capabilities from a plugin to return information about the infrastructure to that plugin. Use the `require` method to ensure that search functionality is available with the following: ``` require 'chef/search/query' ``` Create a search query object and assign it to a variable: ``` variable_name = Chef::Search::Query.new ``` After the search object is created it can be used by the plugin to execute search queries for objects on the Chef Infra Server. For example, using a variable named `query_nodes` a plugin could search for nodes with the `webserver` role and then return the name of each node found: ``` query = "role:webserver" query_nodes.search('node', query) do |node_item| puts "Node Name: #{node_item.name}" end ``` This result can then be used to edit nodes. For example, searching for nodes with the `webserver` role, and then changing the run_list for those nodes to a role named `apache2`: ``` query = "role:webserver" query_nodes.search('node', query) do |node_item| ui.msg "Changing the run_list to role[apache2] for #{node_item.name}" node_item.run_list("role[apache2]") node_item.save ui.msg "New run_list: #{node_item.run_list}" end ``` It’s also possible to specify multiple items to add to the run_list: ``` node_item.run_list("role[apache2]", "recipe[mysql]") ``` And arguments sent with a plugin command can also be used to search. For example, if the command `knife envchange "web*"` is sent, then the command will search for any nodes in roles beginning with “web” and then change their environment to “web”: ``` module MyKnifePlugins class Envchange < Chef::Knife banner "knife envchange ROLE" deps do require 'chef/search/query' end def run if name_args.size == 1 role = name_args.first else ui.fatal "Please provide a role name to search for" exit 1 end query = "role:#{role}" query_nodes = Chef::Search::Query.new query_nodes.search('node', query) do |node_item| ui.msg "Moving #{node_item.name} to the web environment" node_item.chef_environment("web") node_item.save end end end ``` ### User Interaction The `ui` object provides a set of methods that can be used to define user interactions and to help ensure a consistent user experience across knife plugins. The following methods should be used in favor of manually handling user interactions: | Method | Description | | --- | --- | | `ui.ask(*args, &block)` | | | `ui.ask_question(question, opts={})` | Use to ask a user the question contained in `question`. If `:default => default_value` is passed as the second argument, `default_value` will be used if the user does not provide an answer. This method will respect the `--default` command-line option. | | `ui.color(string, *colors)` | Use to specify a color. For example, from the `knife rackspace server list` subcommand: ``` server_list = [ ui.color('Instance ID', :bold), ui.color('Name', :bold), ui.color('Public IP', :bold), ui.color('Private IP', :bold), ui.color('Flavor', :bold), ui.color('Image', :bold), ui.color('State', :bold) ] ``` and from the `knife eucalyptus server create` subcommand: ``` server = connection.servers.create(server_def) puts "#{ui.color("Instance ID", :cyan)}: #{server.id}" puts "#{ui.color("Flavor", :cyan)}: #{server.flavor_id}" puts "#{ui.color("Image", :cyan)}: #{server.image_id}" ... puts "#{ui.color("SSH Key", :cyan)}: #{server.key_name}" print "\n#{ui.color("Waiting for server", :magenta)}" ``` | | `ui.color?()` | Indicates that colored output should be used. (Colored output can only be used when output is sent to a terminal.) | | `ui.confirm(question, append_instructions=true)` | Use to ask a Y/N question. If the user responds with `N`, immediately exit with status code 3. | | `ui.edit_data(data, parse_output=true)` | Use to edit data. This opens the $EDITOR. | | `ui.edit_object(klass, name)` | | | `ui.error` | Use to present an error to the user. | | `ui.fatal` | Use to present a fatal error to the user. | | `ui.highline` | Use to provide direct access to the [Highline object](http://highline.rubyforge.org/doc/) used by many `ui` methods. | | `ui.info` | Use to present a message to a user. | | `ui.interchange` | Use to determine if the output is a data interchange format such as JSON or YAML. | | `ui.list(*args)` | | | `ui.msg(message)` | Use to present a message to the user. | | `ui.output(data)` | Use to present a data structure to the user. This method will respect the output requested when the `-F` command-line option is used. The output will use the generic default presenter. | | `ui.pretty_print(data)` | Use to enable pretty-print output for JSON data. | | `ui.use_presenter(presenter_class)` | Use to specify a custom output presenter. | | `ui.warn(message)` | Use to present a warning to the user. | For example, to show a fatal error in a plugin in the same way that it would be shown in knife do something similar to the following: ``` unless name_args.size == 1 ui.fatal "Be sure to say hello to someone!" show_usage exit 1 end ``` Create a Plugin --------------- A knife command is a Ruby class that inherits from the `Chef::Knife` class. A knife command is run by calling the `run` method on an instance of the command class. For example: ``` module MyKnifePlugins class HelloWorld < Chef::Knife def run puts "Hello, World!" end end end ``` and is run from the command line using: ``` knife hello world ``` Exceptions ---------- In most cases, the exception handling available within knife is enough to ensure that exception handling for a plugin is consistent with how knife ordinarily behaves. That said, exceptions can also be handled within a knife plugin in the same way they are handled in any Ruby program. Install a Plugin ---------------- To install a knife plugin from a file, do one of the following: * Copy the file to the `~/.chef/plugins/knife` directory; the file’s extension must be `.rb` * Add the file to the chef-repo at the `CHEF_REPO/.chef/plugins/knife`; the file’s extension must be `.rb` * Install the plugin from RubyGems © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/plugin_knife_custom/Effortless Audit ================ [[edit on GitHub]](https://github.com/chef/effortless/tree/main/docs-chef-io/content/effortless/effortless_audit.md) Effortless Audit ================ Effortless Audit is the pattern for managing your Chef InSpec profiles. It uses [Chef Habitat](../../habitat/index) and [Chef InSpec](../../inspec/index) to build an artifact that contains your profiles and its dependencies alongside the scripts necessary to run them on your systems. Learn more about [Chef InSpec profiles](../../inspec/profiles/index). Effortless Environment Set-up ----------------------------- 1. Install [Chef Workstation](https://downloads.chef.io/chef-workstation) 2. Install [Chef Habitat](../../habitat/install_habitat/index) 3. Configure Chef Habitat on your workstation by running `hab setup` Patterns -------- ### Wrapper Profile Pattern In Chef InSpec, a common pattern is to write a wrapper profile that depends on another profile. This pattern pulls profiles from a main profile source like the [Chef Automate Profile Store](../../automate/profiles/index). See an [example of this pattern](https://github.com/chef/effortless/tree/main/examples/effortless_audit). 1. To use this pattern, navigate to your profile: ``` cd my_profile ``` 2. Make a `habitat` directory: ``` mkdir habitat ``` 3. Make a plan file Use a `plan.ps1` for a profile targeting Windows. Use a `plan.sh` for a profile targeting Linux. If the profile targets both Windows and Linux, you can have both a `plan.ps1` and a `plan.sh` in the `habitat` directory. Create a plan in Linux with the following command: ``` touch plan.sh ``` 4. Add some information about your profile to the plan file Add this profile information to the Linux `plan.sh` file: ``` pkg_name=<my_profile> pkg_origin=<my_origin> pkg_version=<my_profile_version> pkg_maintainer="Your Name and Email" pkg_license=("Apache-2.0") pkg_scaffolding="chef/scaffolding-chef-inspec" ``` Add this profile information to the Microsoft Windows `plan.ps1` file: ``` $pkg_name="<my_profile>" $pkg_origin="<my_origin>" $pkg_version="<my_profile_version>" $pkg_maintainer="My Name and Email" $pkg_license=("Apache-2.0") $pkg_scaffolding="chef/scaffolding-chef-inspec" ``` 5. Build the package Run the following command to build the package: ``` hab pkg build . ``` 6. Add a `kitchen.yml` file to your profile with the following content: ``` ---driver:name:vagrantsynced_folders:- ["./results","/tmp/results"]provisioner:name:shellverifier:name:inspecplatforms:- name:centos-7.6suites:- name:baseprovisioner:arguments:["<my_origin>","<my_package_name>"]verifier:inspec_tests:test/integration/base ``` 7. Create a `bootstrap.sh` script and include: ``` #!/bin/bash export HAB_LICENSE="accept-no-persist" export CHEF_LICENSE="accept-no-persist" if [ ! -e "/bin/hab" ]; then curl https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh | sudo bash fi if grep "^hab:" /etc/passwd > /dev/null; then echo "Hab user exists" else useradd hab && true fi if grep "^hab:" /etc/group > /dev/null; then echo "Hab group exists" else groupadd hab && true fi pkg_origin=$1 pkg_name=$2 echo "Starting $pkg_origin/$pkg_name" latest_hart_file=$(ls -la /tmp/results/$pkg_origin-$pkg_name* | tail -n 1 | cut -d " " -f 9) echo "Latest hart file is $latest_hart_file" echo "Installing $latest_hart_file" hab pkg install $latest_hart_file echo "Determining pkg_prefix for $latest_hart_file" pkg_prefix=$(find /hab/pkgs/$pkg_origin/$pkg_name -maxdepth 2 -mindepth 2 | sort | tail -n 1) echo "Found $pkg_prefix" echo "Running inspec for $pkg_origin/$pkg_name" cd $pkg_prefix hab pkg exec $pkg_origin/$pkg_name inspec exec $pkg_prefix/*.tar.gz ``` 8. Run Test Kitchen to ensure your profile executes. Use this command to spin up a CentOS 7 virtual machine (VM) locally and run your profile using the latest Chef InSpec: ``` kitchen converge base-centos ``` If you experience failures when running the profile, know that most basic virtual machines are not fully hardened to your security policies. If you want to fix the failures, look at [Chef Infra and the Effortless Config Pattern](../effortless_config/index). 9. When ready, delete the VM instance by running: ``` kitchen destroy ``` 10. You can now upload your profile pkg to Chef Habitat Builder by running the following commands: ``` source results/lastbuild.env hab pkg upload results/$pkg_artifact ``` 11. To run your profile on a system, install Chef Habitat as a service and run: ``` hab svc load <your_origin>/<your_profile_name``` Features -------- ### Waivers With the release of `scaffolding-chef-inspec` version 0.16.0 (Linux) and version 0.18.0 (Windows), we added the Chef InSpec Waivers feature. This feature allows you to specify a control ID in your Chef Habitat config that you would like to skip, or waive. 1. Build an Effortless Audit profile and load it on your systems. 2. Create a `my_config.toml` file similar to: ``` [waivers] [waivers.control_id] run = false expiration_date: 2021-11-31 justification = I don't want this control to run cause it breaks my app ``` 3. Apply the new change to your Chef Habitat config: ``` hab config apply <my_profile_service>.<my_profile_service_group> $(date +'%s') <my_config.toml``` 4. Habitat will see a configuration change, automatically re-run your profile, and skip the control you specified in the `my_config.toml` file. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/effortless/effortless_audit/Effortless Config ================= [[edit on GitHub]](https://github.com/chef/effortless/tree/main/docs-chef-io/content/effortless/effortless_config.md) Effortless Config ================= Effortless Config is the pattern for managing your Chef Infra workloads. It uses [Chef Habitat](../../habitat/index) and [Chef Policyfiles](../../policyfile/index) to build an artifact that contains the cookbooks and their dependencies alongside the scripts necessary to run them on your systems. Effortless Environment Set-up ----------------------------- 1. Install [Chef Workstation](https://downloads.chef.io/chef-workstation) 2. Install [Chef Habitat](../../habitat/install_habitat/index) 3. Configure Chef Habitat on your workstation by running `hab setup` Patterns -------- ### Chef Repo Cookbook Pattern This pattern uses the [chef-repo](../../chef_repo/index) to store and organize everything you need to define your infrastructure with Chef Infra, including: * Cookbooks (including recipes, attributes, custom resources, libraries, and templates) * Data bags * Policyfiles The Chef Effortless GitHub repository has an [example chef-repo](https://github.com/chef/effortless/tree/main/examples/effortless_config/chef_repo_pattern) for you to explore. 1. To use this pattern, navigate to the chef-repo directory that you want to use: ``` cd chef-repo ``` 2. Create a `habitat` directory from the command line with: ``` mkdir habitat ``` 3. Make a plan file Make a `plan.ps1` for a cookbook that targets Microsoft Windows systems and a `plan.sh` for a cookbook that targets Linux systems. You can have both a `plan.ps1` and a `plan.sh` in the `habitat` directory for cookbooks that target both systems. Create a Linux plan: ``` touch plan.sh ``` 4. Add information about the cookbook to the plan Add this information to the `plan.sh` file: ``` pkg_name=<my_policyfile> pkg_origin=<my_origin> pkg_version="0.1.0" pkg_maintainer="My Name and Email" pkg_license=("Apache-2.0") pkg_scaffolding="chef/scaffolding-chef-infra" pkg_svc_user=("root") scaffold_policy_name="<my_policyfile>" ``` 5. If you do not have a `policyfiles` directory in your chef-repo, create one: ``` mkdir policyfiles ``` 6. Generate a Policyfile: ``` chef generate policyfile policyfiles/my_policyfile ``` Example of a `policyfile.rb`: ``` # Policyfile.rb - Describe how Chef Infra should build your system. # # For more information on the Policyfile feature, visit # https://docs.chef.io/policyfile.html name "base" # Where to find external cookbooks default_source :supermarket default_source :chef_repo, "../" # run_list: run these recipes in the order specified. run_list [ "patching::default", "hardening::default" ] # attributes: set attributes from your cookbooks default['hardening'] = {} default['patching'] = {} ``` 1. Build the package: Run the following command to build the package: ``` hab pkg build . ``` 2. Edit the `kitchen.yml` file to look similar to this: ``` ---driver:name:vagrantsynced_folders:- ["./results","/tmp/results"]provisioner:name:shellverifier:name:inspecplatforms:- name:centos-7.6suites:- name:baseprovisioner:arguments:["<my_origin>","<my_package_name>"]verifier:inspec_tests:test/integration/base ``` 3. Create a `bootstrap.sh` script and include: ``` #!/bin/bash export HAB_LICENSE="accept-no-persist" export CHEF_LICENSE="accept-no-persist" if [ ! -e "/bin/hab" ]; then curl https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh | sudo bash fi if grep "^hab:" /etc/passwd > /dev/null; then echo "Hab user exists" else useradd hab && true fi if grep "^hab:" /etc/group > /dev/null; then echo "Hab group exists" else groupadd hab && true fi pkg_origin=$1 pkg_name=$2 echo "Starting $pkg_origin/$pkg_name" latest_hart_file=$(ls -la /tmp/results/$pkg_origin-$pkg_name* | tail -n 1 | cut -d " " -f 9) echo "Latest hart file is $latest_hart_file" echo "Installing $latest_hart_file" hab pkg install $latest_hart_file echo "Determining pkg_prefix for $latest_hart_file" pkg_prefix=$(find /hab/pkgs/$pkg_origin/$pkg_name -maxdepth 2 -mindepth 2 | sort | tail -n 1) echo "Found $pkg_prefix" echo "Running chef for $pkg_origin/$pkg_name" cd $pkg_prefix hab pkg exec $pkg_origin/$pkg_name chef-client -z -c $pkg_prefix/config/bootstrap-config.rb ``` 4. Run Test Kitchen to ensure the cookbook works Use this command to spin up a CentOS 7 virtual machine (VM) locally and run the cookbook using the latest Chef Infra Client: ``` kitchen converge base-centos ``` If you experience errors in this Chef run, you may need to supply attributes or make modifications to your Policyfile, so that your cookbook can run using the latest Chef Infra Client. 5. When ready, delete the VM instance by running: ``` kitchen destroy ``` 6. Upload the Policyfile pkg to Chef Habitat builder by running the following commands: ``` source results/lastbuild.env hab pkg upload results/$pkg_artifact ``` 7. To run the Policyfile on a system, install Chef Habitat services and run: ``` hab svc load <my_origin>/<my_policyfile_name``` ### Policyfile Cookbook Pattern This pattern builds a Chef Habitat artifact for the Policyfile cookbook. You can find an [example Policyfile cookbook](https://github.com/chef/effortless/tree/main/examples/effortless_config/policyfile_cookbook_pattern) in the Chef Effortless GitHub repository. 1. To use this pattern, navigate to the cookbook you want to use: ``` cd chef-repo/cookbooks/my_cookbook ``` 2. Create a `habitat` directory from the command line with: ``` mkdir habitat ``` 3. Make a plan file Use a `plan.ps1` for a cookbook targeting Windows. Use a `plan.sh` for a cookbook targeting Linux. If the cookbook targets both Windows and Linux, you can have both a `plan.ps1` and a `plan.sh` in the `habitat` directory. Create a plan in Linux with the following command: ``` touch plan.sh ``` 4. Add some information about the cookbook to the plan plan.sh ``` pkg_name=<Name of my_cookbook artifact> pkg_origin=<my_origin> pkg_version="<Cookbook version>" pkg_maintainer="<My Name>" pkg_license=("<License for my_cookbook example Apache-2.0>") pkg_scaffolding="chef/scaffolding-chef-infra" scaffold_policy_name="Policyfile" scaffold_policyfile_path="$PLAN_CONTEXT/../" # habitat/../Policyfile.rb ``` 5. Make a Policyfile in the `cookbook` directory Example of a `policyfile.rb` file: ``` # Policyfile.rb - Describe how you want Chef to build your system. # # For more information on the Policyfile feature, visit # https://docs.chef.io/policyfile.html # A name that describes what the system you're building with Chef does. name '<my_cookbook_name>' # Where to find external cookbooks: default_source :supermarket # run_list: chef-client will run these recipes in the order specified. run_list '<my_cookbook_name>::default' # Specify a custom source for a single cookbook: cookbook '<my_cookbook_name>', path: '.' ``` 6. Build the package: ``` hab pkg build <my_cookbook``` 7. Edit the `kitchen.yml` file to look similar to this: ``` ---driver:name:vagrantsynced_folders:- ["./results","/tmp/results"]provisioner:name:shellverifier:name:inspecplatforms:- name:centos-7.6suites:- name:baseprovisioner:arguments:["<my_origin>","<my_cookbook>"]verifier:inspec_tests:test/integration/base ``` 8. Create a `bootstrap.sh` script and include: ``` #!/bin/bash export HAB_LICENSE="accept-no-persist" export CHEF_LICENSE="accept-no-persist" if [ ! -e "/bin/hab" ]; then curl https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh | sudo bash fi if grep "^hab:" /etc/passwd > /dev/null; then echo "Hab user exists" else useradd hab && true fi if grep "^hab:" /etc/group > /dev/null; then echo "Hab group exists" else groupadd hab && true fi pkg_origin=$1 pkg_name=$2 echo "Starting $pkg_origin/$pkg_name" latest_hart_file=$(ls -la /tmp/results/$pkg_origin-$pkg_name* | tail -n 1 | cut -d " " -f 9) echo "Latest hart file is $latest_hart_file" echo "Installing $latest_hart_file" hab pkg install $latest_hart_file echo "Determining pkg_prefix for $latest_hart_file" pkg_prefix=$(find /hab/pkgs/$pkg_origin/$pkg_name -maxdepth 2 -mindepth 2 | sort | tail -n 1) echo "Found $pkg_prefix" echo "Running chef for $pkg_origin/$pkg_name" cd $pkg_prefix hab pkg exec $pkg_origin/$pkg_name chef-client -z -c $pkg_prefix/config/bootstrap-config.rb ``` 9. Run Test Kitchen to ensure the cookbook works on Linux Use this command to spin up a CentOS 7 virtual machine (VM) locally and run the cookbook using the latest Chef Infra Client: ``` kitchen converge base-centos ``` If you experience errors in this Chef run, you may need to supply attributes or make modifications to your Policyfile, so that your cookbook can run using the latest Chef Infra Client. 10. When ready, delete the VM instance by running: ``` kitchen destroy ``` 11. Upload the habitat pkg to Chef Habitat builder by running the following commands: ``` source results/lastbuild.env hab pkg upload results/$pkg_artifact ``` 12. To run the cookbook on a system, install Chef Habitat services and run: ``` hab svc load my_origin/my_cookbook ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/effortless/effortless_config/Effortless What is Scaffolding ============================== [[edit on GitHub]](https://github.com/chef/effortless/tree/main/docs-chef-io/content/effortless/what_is_scaffolding.md) Chef Habitat Scaffolding ======================== Chef Habitat scaffolding is a way to build a Chef Habitat plan that overrides some of the default functions that Chef Habitat uses during its build process. You can find out more about [scaffolding](../../habitat/scaffolding/index) in the Chef Habitat documentation. Why The Effortless Pattern Uses Scaffolding ------------------------------------------- We use Chef Habitat scaffolding to provide the Effortless maintainers better management of the build and runtime steps needed to be successful with Chef Infra and Chef InSpec. This means a small plan file is the amount of code that you, the customer, need to maintain in order to build and run Chef Infra and Chef InSpec. Focus on writing Chef Infra cookbooks and Chef InSpec profiles, and not on how to build and run those things. How Scaffolding Works --------------------- By specifying the `pkg_scaffolding` variable in your plan, Chef Habitat will pull in the necessary package dependencies, run the build steps for Chef Infra and/or Chef InSpec, and provide you with a Chef Habitat artifact that contains your cookbooks or profiles and a way to run them on your systems. Find the source code for these steps here for [Chef Infra](https://github.com/chef/effortless/tree/main/scaffolding-chef-infra/lib) and for [Chef InSpec](https://github.com/chef/effortless/tree/main/scaffolding-chef-inspec/lib). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/effortless/what_is_scaffolding/Share Cookbooks on the Chef Supermarket ======================================= [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/supermarket_share_cookbook.md) This guide will show you how to share a cookbook on the public [Chef Supermarket](https://supermarket.chef.io/). The public Supermarket uses [Hosted Chef](https://manage.chef.io), the Chef-as-a-service provider, for user authentication. You will need a Hosted Chef account to share cookbooks. Note If you already use Hosted Chef as your Chef Infra Server, you can skip directly to the sharing your cookbook. Create a Hosted Chef Account ---------------------------- 1. Go to the [Hosted Chef signup page](https://manage.chef.io/signup) and enter the requested information to create your account. 2. You will receive a confirmation email. Use the link in the email to confirm your confirm your email address. 3. Log in to Hosted Chef and select the **Create New Organization** button: ![Image of Chef Manage login window.] 4. Download and extract the Hosted Chef starter kit: ![Image showing the Administration tab and the Download Starter Kit button.] Share Cookbooks via Knife ------------------------- Use the [knife supermarket](../../workstation/knife_supermarket/index) command to upload cookbooks to the Supermarket via Knife. In this section you’ll configure the chef-repo that was created by the Hosted Chef starter kit, and then upload cookbooks from your workstation’s cookbook repository. Note If you’re using Hosted Chef as your regular Chef Infra Server, skip to the second step. 1. The `config.rb` file located under `/chef-repo/.chef/config.rb` contains the basic information necessary to authenticate with Hosted Chef. It will look similar to the following: ``` current_dir = __dir__ node_name 'brewn' client_key "#{current_dir}/brewn.pem" chef_server_url 'https://api.chef.io/organizations/chfex' cookbook_path ["#{current_dir}/../cookbooks"] ``` However if you’re not an existing Hosted Chef user, you’ve most likely created your cookbooks within another repository with its own Knife configuration. Instead of modifying your workstation setup, simply add the path to your cookbook repository under the `cookbook_path` setting in your Hosted Chef chef-repo. For example: ``` cookbook_path ['~/my-repo/cookbooks'] ``` 2. Use the `knife supermarket` command to upload your cookbook to the Supermarket: ``` knife supermarket share example_cookbook ``` Alternatively, if you choose not to modify the location of your cookbook repository within your `config.rb`, you can specify the cookbook path in your `knife` command: ``` knife supermarket share example_cookbook -o ~/my-repo/cookbooks ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/supermarket/supermarket_share_cookbook/Effortless Variables and Config =============================== [[edit on GitHub]](https://github.com/chef/effortless/tree/main/docs-chef-io/content/effortless/variables_and_config.md) Plan Variables and Chef Habitat Configurations ============================================== This documents the options for both your plan and your `habitat` configuration file. Effortless Config ----------------- ### Effortless Config Plan Variables You can use all the default plan variables shipped with Chef Habitat. Read more about [plan variables](../../habitat/plan_variables/index) in the Chef Habitat documentation. scaffold_chef_client The Chef Habitat `chef-infra-client` package used. Change to use a different package. Default is `chef/chef-infra-client` scaffold_cacerts The Chef Habitat `cacerts` package used during the Chef Infra Client run. Change to use a different package.Default is `chef/cacerts` scaffold_policyfile_path Path to the policyfile. Default is `$PLAN_CONTEXT/../policyfiles` scaffold_data_bags_path Path to the `data_bags` directory that contains the `data_bags`, if needed by your cookbook. Default is `$PLAN_CONTEXT/../data_bags` ### Effortless Config Chef Habitat Settings interval Frequency of how often in seconds that the Chef Infra Client runs. Default is `1800` splay A randomly generated sleep time value in seconds added to the interval and helps determine when the chef-client runs again. Default is `1800` splay_first_run Splay value in seconds for the first run of the Chef Infra Client. Default is `0` run_lock_timeout Amount of time in seconds for the run lock timeout for the Chef Infra Client run. Default is `1800` log_level Log level for the `chef-client`. Default is `warn` env_path_prefix String that will be the Environment Path variable for the chef-client run. Linux Default is `/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin`. Windows Default is `;C:/WINDOWS;C:/WINDOWS/system32/;C:/WINDOWS/system32/WindowsPowerShell/v1.0;C:/ProgramData/chocolatey/bin` ssl_verify_mode SSL Verification mode for the Chef Infra Client. Default is `:verify_peer` verify_api_cert Boolean option to determine if the API certification should be verified. Default is `false` rubygems_url The location to source rubygems. Default value: `https://www.rubygems.org` #### Effortless Config Chef License This configuration needs to be under the `[chef_license]` block in the .toml file. acceptance Determines the Chef license acceptance at run time. Required for Chef Infra Client. See Chef License [here](../../chef_license_accept/index#accepting-the-chef-license). Default is `undefined` #### Effortless Config Chef Automate These configurations need to be under the `[automate]` block in the .toml file. enable Enables or disables reporting to Chef Automate. Boolean. Default is `false` server_url Chef Automate server URL. Example: `https://automate.example.com/data-collector/v0/`. Default is `https://<automate_url>` token Chef Automate API token. Example: `<KEY>`. Default is `<automate_token>` Effortless Audit ---------------- ### Effortless Audit Plan Variables scaffold_inspec_client The Chef Habitat `inspec` package. Change to use a different package. Default is `chef/inspec` This variable is required if the profile had a `depends` line for compliance in the `inspec.yml` example as shown below scaffold_cacerts The Chef Habitat `cacerts` package during the Chef Infra Client run. Change to use a different package. Default is `chef/cacerts`. This variable is required if the profile had a `depends` line for compliance in the `inspec.yml` example as shown below inspec.yml ``` depends:- name:cis-rhel7-level1-servercompliance:admin/cis-rhel7-level1-server ``` scaffold_automate_server_url Points to the Chef Automate server needed to fetch profile dependencies from the Chef Automate Asset Store. Example: `https://automate.example.com`. Required if the profile uses a line for compliance in the `inspec.yml` scaffold_automate_user Chef Automate user for the installed profile scaffold_automate_token Chef Automate API token ### Effortless Audit Chef Habitat Variables interval How often in seconds that `inspec` runs. Default is `1800` splay A randomly generated sleep time value in seconds added to the interval and helps determine when the chef-client runs again. Default is `1800` splay_first_run Splay value in seconds for the first run of the `inspec` client. Default is `0` log_level Log level for the `inspec` client. Default is `warn` #### Effortless Audit Chef License This configuration needs to be under the `[chef_license]` block in the .toml file. acceptance Determines the Chef license acceptance at run time. This setting is required for chef-client to run successfully. See Chef License [here](../../chef_license_accept/index#accepting-the-chef-license). Default is `undefined` #### Effortless Audit Chef Automate These configurations need to be under the `[automate]` block in your toml file. enable Enables or disables reporting to Chef Automate. Boolean. Default is `false` server_url The Chef Automate server URL. Example: `https://automate.example.com/data-collector/v0/`. Default is `https://<automate_url>` token Chef Automate API token. Example: `<KEY>`. Default is `<automate_token>` environment (Optional) Environment tag for the Chef InSpec report. Use this tag to help with filtering in Chef Automate. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/effortless/variables_and_config/Chef Supermarket ================ [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/_index.md) Chef Supermarket is the site for community cookbooks. It provides an easily searchable cookbook repository and a friendly web UI. Cookbooks that are part of the Chef Supermarket are accessible by any Chef user. There are two ways to use Chef Supermarket: * The public Chef Supermarket is hosted by Chef Software and is located at [Chef Supermarket](https://supermarket.chef.io/). * A private Chef Supermarket may be installed on-premise behind the firewall on the internal network. Cookbook retrieval from a private Chef Supermarket is often faster than from the public Chef Supermarket because of closer proximity and fewer cookbooks to resolve. A private Chef Supermarket can also help formalize internal cookbook release management processes (e.g. “a cookbook is not released until it’s published on the private Chef Supermarket”). Public Supermarket ------------------ The public Chef Supermarket hosted by Chef Software is located at [Chef Supermarket](https://supermarket.chef.io/). To interact with the public Chef Supermarket, use [knife supermarket](../workstation/knife_supermarket/index) commands. ![Image showing the Chef Supermarket website.] Private Supermarket ------------------- The private Chef Supermarket is installed behind the firewall on the internal network. Outside of changing the location from which community cookbooks are maintained, it otherwise behaves the same as the public Chef Supermarket. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/supermarket/Install Private Supermarket =========================== [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/install_supermarket.md) The source code for Chef Supermarket is located at the following URLs: * The application itself: <https://github.com/chef/supermarket>. Report issues to: <https://github.com/chef/supermarket/issues>. * The cookbook that is run by the `supermarket-ctl reconfigure` command: <https://github.com/chef/supermarket/tree/main/omnibus/cookbooks/omnibus-supermarket Requirements ------------ A private Chef Supermarket has the following requirements: * An working Chef Infra Server, which acts as the OAuth 2.0 provider * A user account on the Chef Infra Server with `admins` privileges * A key for the user account on the Chef server * An x86_64 compatible Linux host with at least 2 GB memory * System clocks synchronized on the Chef Infra Server and Supermarket hosts * Sufficient disk space on host to meet project cookbook storage capacity **or** credentials to store cookbooks in an Amazon Simple Storage Service (S3) bucket **Considerations with regard to storage capacity:** * PostgreSQL database size will grow linearly based on the number of cookbooks and the number of cookbook versions published * Redis database size is negligible as it is used only for background job queuing, and to cache a small number of API responses * Cookbook storage growth is entirely dependent on the size of the cookbooks published. Cookbooks that include binaries or other large files will consume more space than code-only cookbooks * Opting to run a private Supermarket with off-host PostgreSQL, Redis, and cookbook store is less a decision about storage sizing; it is about data service uptime, backup, and restore procedure for your organization * As a point of reference: as of May 2021 after six years of operation, the public Supermarket has approx 83,000 users, 4,000 cookbooks with a total of 27,000 versions published. The PostgreSQL database is 435 MB, and the S3 bucket containing the published community cookbooks is 3.1 GB Chef Identity ------------- Chef Identity (also referred to as **oc-id**) is an OAuth 2.0 authentication and authorization service packaged with the Chef Infra Server. Chef Identity must be configured to run with a private Chef Supermarket, after which users may use the same credentials to access the Chef Supermarket as they do to access the Chef Infra Server. Note The Chef Supermarket server must be able to reach (via HTTPS) the specified `chef_server_url` during OAuth 2.0 negotiation. This type of issue is typically with name resolution and firewall rules. ### Configure To configure Chef Supermarket to use Chef Identity, do the following: 1. Log on to the Chef Infra Server via SSH and elevate to an admin-level user. If running a multi-node Chef Infra Server cluster, log on to the node acting as the primary node in the cluster. 2. Update the `/etc/opscode/chef-server.rb` configuration file. To define OAuth 2 information for Chef Supermarket, create a Hash similar to: ``` oc_id['applications'] ||= {} oc_id['applications']['supermarket'] = { 'redirect_uri' => 'https://supermarket.mycompany.com/auth/chef_oauth2/callback', } ``` 3. Reconfigure the Chef Infra Server. ``` sudo chef-server-ctl reconfigure ``` 4. Retrieve Supermarket’s OAuth 2.0 client credentials: Depending on your Chef Infra Server version and configuration (see [chef-server.rb](../../server/config_rb_server_optional_settings/index#config-rb-server-insecure-addon-compat)), this can be retrieved via [chef-server-ctl oc-id-show-app supermarket](../../ctl_chef_server/index#ctl-chef-server-oc-id-show-app) or is located in `/etc/opscode/oc-id-applications/supermarket.json`: ``` { "name": "supermarket", "uid": "0bad0f2eb04e935718e081fb71asdfec3681c81acb9968a8e1e32451d08b", "secret": "17cf1141cc971a10ce307611beda7ffadstr4f1bc98d9f9ca76b9b127879", "redirect_uri": "https://supermarket.mycompany.com/auth/chef_oauth2/callback" } ``` The `uid` and `secret` values will be needed later on during the setup process for Chef Supermarket. Note Add as many Chef Identity applications to the `/etc/opscode/chef-server.rb` configuration file as necessary. A JSON file is generated for each application added, which contains the authentication tokens for that application. The secrets are added to the Chef Identity database and are available to all nodes in the Chef Infra Server front end group. The generated JSON files do not need to be copied anywhere. Note The redirect URL specified **MUST** match the FQDN of the Chef Supermarket server. The URI must also be correct: `/auth/chef_oauth2/callback`. Otherwise, an error message similar to `The redirect uri included is not valid.` will be shown. Install Supermarket ------------------- To install a private Chef Supermarket use the `supermarket-omnibus-cookbook`. This cookbook is [available from the public](https://supermarket.chef.io/cookbooks/supermarket-omnibus-cookbook) Chef Supermarket. * The `supermarket-omnibus-cookbook` cookbook is attribute-driven; use a custom cookbook to specify your organization’s unique `node[supermarket_omnibus]` attribute values. * The custom cookbook is a wrapper around `supermarket-omnibus-cookbook`, which performs the actual installation of the Chef Supermarket packages, and then writes the custom `node[supermarket_omnibus]` values to `/etc/supermarket/supermarket.json`. * The Chef Supermarket package itself contains an internal cookbook which configures the already-installed package using the attributes defined in `/etc/supermarket/supermarket.json`. Note In general, for production environments Chef recommends to start running Chef Supermarket with small virtual machines, and then increase the size of the virtual machine as necessary. Put the `/var/opt/supermarket` directory on a separate disk, and then use LVM so that may be expanded. ### Create a Wrapper A wrapper cookbook is used to define project- and/or organization-specific requirements around a community cookbook. ![Diagram showing a wrapper cookbook containing a private Supermarket.] In the case of installing a private Chef Supermarket, Chef recommends the use of a wrapper cookbook to specify certain attributes that are unique to your organization, while enabling the use of the generic installer cookbook which, in turn, installs the Chef Supermarket package behind your firewall. All of the keys under `node['supermarket_omnibus']` are written out as `/etc/supermarket/supermarket.json`. Add other keys as needed to override the default attributes specified in the Chef Supermarket [omnibus package](https://github.com/chef/supermarket/blob/main/omnibus/cookbooks/omnibus-supermarket/attributes/default.rb). For example: ``` default['supermarket_omnibus']['chef_server_url'] = 'https://chefserver.mycompany.com:443' default['supermarket_omnibus']['chef_oauth2_app_id'] = '14dfcf186221781cff51eedd5ac1616' default['supermarket_omnibus']['chef_oauth2_secret'] = 'a49402219627cfa6318d58b13e90aca' default['supermarket_omnibus']['chef_oauth2_verify_ssl'] = false default['supermarket_omnibus']['fqdn'] = 'supermarket.mycompany.com' ``` On your workstation, generate a new cookbook using the `chef` command line interface: 1. Generate the cookbook: ``` chef generate cookbook my_supermarket_wrapper ``` 2. Change directories into that cookbook: ``` cd my_supermarket_wrapper ``` 3. Defines the wrapper cookbook’s dependency on the `supermarket-omnibus-cookbook` cookbook. Open the metadata.rb file of the newly-created cookbook, and then add the following line: ``` depends 'supermarket-omnibus-cookbook' ``` 4. Save and close the metadata.rb file. 5. Open the `/recipes/default.rb` recipe located within the newly-generated cookbook and add the following content: ``` include_recipe 'supermarket-omnibus-cookbook' ``` This ensures that the `default.rb` file in the `supermarket-omnibus-cookbook` is run. ### Define Attributes Define the attributes for the Chef Supermarket installation and how it connects to the Chef Infra Server. One approach would be to hard-code attributes in the wrapper cookbook’s `default.rb` recipe. A better approach is to place these attributes in a data bag, and then reference them from the recipe. For example, the data bag could be named `apps` and then a data bag item within the data bag could be named `supermarket`. The following attribute values must be defined: * `chef_server_url` * `chef_oauth2_app_id` * `chef_oauth2_secret` Once configured, you can get the `chef_oauth2_app_id` and `chef_oauth2_secret` values from your Chef Infra Server within `/etc/opscode/oc-id-applications/supermarket.json`: For `chef_server_url`, enter in the URL of your chef server. For `chef_oauth2_app_id`, enter in the uid from `/etc/opscode/oc-id-applications/supermarket.json` For `chef_oauth2_secret`, enter in the secret from `/etc/opscode/oc-id-applications/supermarket.json` To define these attributes, do the following: 1. Open the `/recipes/default.rb` file and add the following, **BEFORE** the `include_recipe` line that was added in the previous step. This example uses a data bag named `apps` and a data bag item named `supermarket`: ``` app = data_bag_item('apps', 'supermarket') ``` 2. Set the attributes from the data bag: ``` node.override['supermarket_omnibus']['chef_server_url'] = app['chef_server_url'] node.override['supermarket_omnibus']['chef_oauth2_app_id'] = app['chef_oauth2_app_id'] node.override['supermarket_omnibus']['chef_oauth2_secret'] = app['chef_oauth2_secret'] ``` When finished, the `/recipes/default.rb` file should have code similar to: ``` app = data_bag_item('apps', 'supermarket') node.override['supermarket_omnibus']['chef_server_url'] = app['chef_server_url'] node.override['supermarket_omnibus']['chef_oauth2_app_id'] = app['chef_oauth2_app_id'] node.override['supermarket_omnibus']['chef_oauth2_secret'] = app['chef_oauth2_secret'] include_recipe 'supermarket-omnibus-cookbook' ``` 3. Save and close the `/recipes/default.rb` file. Note If you are running your private Supermarket in AWS, you may need to set an additional attribute for the node’s public IP address: ``` node.override['supermarket_omnibus']['config']['fqdn'] = your_node_public_ip ``` ### Upload the Wrapper The wrapper cookbook around the `supermarket-omnibus-cookbook` cookbook must be uploaded to the Chef Infra Server, along with any cookbooks against which the `supermarket-omnibus-cookbook` cookbook has dependencies. To upload the cookbooks necessary to install Chef Supermarket, do the following: 1. Install Berkshelf: ``` berks install ``` 2. Change directories into `~/.berkshelf/cookbooks`: ``` cd ~/.berkshelf/cookbooks ``` 3. Upload all cookbooks to the Chef Infra Server: ``` knife cookbook upload -a ``` 4. Change directories into the location in which the wrapper cookbook was created: ``` cd path/to/wrapper/cookbook/ ``` 5. Upload the wrapper cookbook to the Chef Infra Server: ``` knife cookbook upload -a ``` ### Bootstrap Supermarket Bootstrap the node on which Chef Supermarket is to be installed. For example, to bootstrap a node running Ubuntu on Amazon Web Services (AWS), the command is similar to: ``` knife bootstrap ip_address -N supermarket-node -x ubuntu --sudo ``` where * `-N` defines the name of the Chef Supermarket node: `supermarket-node` * `-x` defines the (ssh) user name: `ubuntu` * `--sudo` ensures that sudo is used while running commands on the node during the bootstrap operation When the bootstrap operation is finished, do the following: 1. Edit the node to add the wrapper cookbook’s `/recipes/default.rb` recipe to the run-list: ``` knife node edit supermarket-node ``` where `supermarket-node` is the name of the node that was just bootstrapped. 2. Add the recipe to the run-list: ``` "run_list": [ "recipe[my_supermarket_wrapper::default]" ] ``` 3. Start Chef Infra Client on the newly-bootstrapped Chef Supermarket node. For example, using SSH: ``` ssh ubuntu@your-supermarket-node-public-dns ``` 4. After accessing the Chef Supermarket node, run Chef Infra Client: ``` sudo chef-client ``` Install Supermarket Directly (without a cookbook) ------------------------------------------------- While there are many benefits to using the cookbook method to install Supermarket, there are also cases where it’s simpler to set up the Supermarket installation manually. These steps will walk you through the process of manually configuring your private Supermarket server. Before following these steps, be sure to complete the OAuth setup process detailed in the [Chef Identity](../../install_supermarket/index#chef-identity) section of this guide. 1. [Download](https://www.chef.io/downloads/tools/supermarket) the correct package for your operating system from `chef.io/downloads`. 2. Install Supermarket using the appropriate package manager for your distribution: * For Ubuntu: ``` dpkg -i /path/to/package/supermarket*.deb ``` * For RHEL / CentOS: ``` rpm -Uvh /path/to/package/supermarket*.rpm ``` 3. Run the `reconfigure` command to complete the initial installation: ``` sudo supermarket-ctl reconfigure ``` 4. Create an `/etc/supermarket/supermarket.json` file and add the following information, substituting the values for each configuration option with the OAuth 2.0 client credentials that were created in the [previous section](../../install_supermarket/index#chef-identity): ``` { "chef_server_url": "https://chefserver.mycompany.com", "chef_oauth2_app_id": "0bad0f2eb04e935718e081fb71asdfec3681c81acb9968a8e1e32451d08b", "chef_oauth2_secret": "17cf1141cc971a10ce307611beda7ffadstr4f1bc98d9f9ca76b9b127879", "fqdn": "supermarket.mycompany.com", "chef_oauth2_verify_ssl": false } ``` Where: * `"chef_server_url"` should contain the FQDN of your Chef Infra Server. Note that if you’re using a non-standard SSL port, this much be appended to the URL. For example: `https://chefserver.mycompany.com:65400` * `"chef_oauth2_app_id"` should contain the `"uid"` value from your OAuth credentials * `"chef_oauth2_secret"` should contain the `"secret"` value from your OAuth credentials * `chef_oauth2_verify_ssl` is set to false, which is necessary when using a self-signed certificate without a properly configured certificate authority * `fqdn` should contain the desired URL that will be used to access your private Supermarket. If not specified, this default to the FQDN of the machine 5. Issue another `reconfigure` command to apply your changes: ``` sudo supermarket-ctl reconfigure ``` Connect to Supermarket ---------------------- To reach the newly spun up private Chef Supermarket, the hostname must be resolvable from a workstation. For production use, the hostname should have a DNS entry in an appropriate domain that is trusted by each user’s workstation. 1. Visit the Chef Supermarket hostname in the browser. A private Chef Supermarket will generate and use a self-signed certificate, if a certificate is not supplied as part of the installation process (via the wrapper cookbook). 2. If an SSL notice is shown while connecting to Chef Supermarket via a web browser, accept the SSL certificate. A trusted SSL certificate should be used for private Chef Supermarket that is used in production. 3. After opening Chef Supermarket in a web browser, click the **Create Account** link. A prompt to log in to the Chef Infra Server is shown, but only if the user is not already logged in. Authorize the Chef Supermarket to use the Chef Infra Server account for authentication. Note The redirect URL specified for Chef Identity **MUST** match the fqdn hostname of the Chef Supermarket server. The URI must also be correct: `/auth/chef_oauth2/callback`. Otherwise, an error message similar to `The redirect uri included is not valid.` will be shown. Customize Supermarket --------------------- Chef Supermarket is a Ruby on Rails application with a PostgreSQL database. The private Chef Supermarket configuration may be scaled-out, such as using an external database, using an external cache, and using an external cookbook storage location. ### External Database A Chef Supermarket installation can use an external database running PostgreSQL (9.3 or higher) and with the `pgpsql` and `pg_trgm` installed and loaded. The public Chef Supermarket uses Amazon Relational Database Service (RDS). To use an external database, configure the following attributes in the `/recipes/default.rb` recipe of the wrapper cookbook: ``` node.override['supermarket_omnibus']['config']['postgresql']['enable'] = false node.override['supermarket_omnibus']['config']['database']['user'] = 'supermarket' node.override['supermarket_omnibus']['config']['database']['name'] = 'supermarket' node.override['supermarket_omnibus']['config']['database']['host'] = 'yourcompany...rds.amazon.com' node.override['supermarket_omnibus']['config']['database']['port'] = '5432' node.override['supermarket_omnibus']['config']['database']['pool'] = '25' node.override['supermarket_omnibus']['config']['database']['password'] = 'topsecretneverguessit' ``` ### External Cache Chef Supermarket installations can also use an external cache store. The public Chef Supermarket uses Redis on Amazon ElastiCache. One Redis instance per private Chef Supermarket application server may be run safely. Use Redis 2.8 (or higher) for a high availability pair. To use an external cache, configure the following attributes in the `/recipes/default.rb` recipe of the wrapper cookbook: ``` node.override['supermarket_omnibus']['config']['redis']['enable'] = false node.override['supermarket_omnibus']['config']['redis_url'] = 'redis://your-redis-instance:6379' ``` ### External Cookbook Storage Cookbook artifacts—tar.gz artifacts that are uploaded to Chef Supermarket when sharing a cookbook—can be stored either on the local filesystem of the Chef Supermarket node (`/var/opt/supermarket/data` by default) or in an Amazon Simple Storage Service (S3) bucket. To use an S3 bucket, configure the following attributes in the `/recipes/default.rb` recipe of the wrapper cookbook: ``` node.override['supermarket_omnibus']['config']['s3_access_key_id'] = 'yourkeyid' node.override['supermarket_omnibus']['config']['s3_bucket'] = 'all-our-awesome-cookbooks' node.override['supermarket_omnibus']['config']['s3_region'] = 'some-place-3' node.override['supermarket_omnibus']['config']['s3_secret_access_key'] = 'yoursecretaccesskey' ``` Note Encrypted S3 buckets are currently not supported. Upgrade a Private Supermarket ----------------------------- 1. Shut down the server running Private Supermarket. 2. Backup the `/var/opt/supermarket` directory. 3. Download the [Chef Supermarket](https://www.chef.io/downloads/tools/supermarket) package. 4. Upgrade your system with the new package using the appropriate package manager for your distribution: * For Ubuntu: ``` dpkg -i /path/to/package/supermarket*.deb ``` * For RHEL / CentOS: ``` rpm -Uvh /path/to/package/supermarket*.rpm ``` 5. [Reconfigure](../../ctl_supermarket/index#reconfigure) the server that Chef Supermarket is installed on: ``` sudo supermarket-ctl reconfigure ``` Private Supermarket is updated on your server now. We recommend restarting the services that run Chef Supermarket to ensure that the old installation of Chef Supermarket doesn’t persist in the server memory. 1. Get the name of the active unit: ``` systemctl list-units | grep runsvdir ``` 2. Restart the unit: ``` systemctl restart UNIT_NAME ``` This will restart the `runsvdir`, `runsv`, and `svlogd` service processes that run Chef Supermarket. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/supermarket/install_supermarket/supermarket-ctl (executable) ============================ [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/ctl_supermarket.md) The Chef Supermarket installations that are done using the Chef installer include a command-line utility named supermarket-ctl. This command-line tool is used to start and stop individual services, reconfigure the Chef Supermarket server, run smoke tests, and tail the Chef Supermarket log files. make-admin ---------- The `make-admin` subcommand is used to make the named Chef Supermarket user an administrator. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl make-admin USER_NAME ``` where `USER_NAME` represents the name of the user to be granted administrator privileges. spdx ---- The `spdx` subcommands are used to manage SPDX license information in cookbooks. Linked SPDX licenses appear on the cookbook information page. [The Software Package Data Exchange](https://spdx.dev/) (SPDX) is an open standard for software manifests, including components, licenses, copyrights, and security content. SPDX maintains a [License List](https://spdx.org/licenses/) of common licenses and exceptions used in open source development. Changes to the SPDX License List are not automatically reflected in your cookbooks. to To apply changes made by SPDX, rescan your cookbooks with the `spdx` subcommands. ### spdx-all The `spdx-all` command links the licenses known to SPDX for all cookbooks in your system. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl spdx-all ``` ### spdx-latest The `spdx-latest` command links the licenses known to SPDX for the specified cookbook. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl spdx-latest COOKBOOK_NAME ``` Where COOKBOOK_NAME is the name of cookbook for SPDX linking. The latest version of the cookbook receives SPDX linking. ### spdx-on-version The `spdx-on-version` command links the licenses known to SPDX for the specified cookbook version. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl spdx-on-version COOKBOOK_NAME VERSION ``` Where COOKBOOK_NAME is the name of cookbook and VERSION is the version of the cookbook that receives SPDX linking. Quality Metrics --------------- ### qm-flip-admin-only The `qm-flip-admin-only` command is used to make a single named quality metric visible only to admins. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-flip-admin-only "METRIC_NAME" ``` where `METRIC_NAME` is the name of the quality metric to make admin only. Names containing spaces must be surrounded by quotes. ### qm-flip-all-admin-only The `qm-flip-all-admin-only` command is used to make all quality metrics visible only to admins. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-flip-all-admin-only ``` ### qm-flip-all-public The `qm-flip-all-public` command is used to make all quality metrics visible to all users. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-flip-all-public ``` ### qm-flip-public The `qm-flip-public` command is used to make a single named quality metric visible to all users. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-flip-public "METRIC_NAME" ``` where `METRIC_NAME` is the name of the quality metric to make public. Names containing spaces must be surrounded by quotes. ### qm-list The `qm-list` command is used to list the names of quality metrics defined currently in a Supermarket. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-list ``` ### qm-run-all-the-latest The `qm-run-all-the-latest` command is used to run all quality metrics on the latest versions of all cookbooks. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-run-all-the-latest ``` ### qm-run-on-latest The `qm-run-on-latest` command is used to run all quality metrics on the latest version of a named cookbook. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-run-on-version COOKBOOK_NAME ``` where `COOKBOOK_NAME` is the name of the cookbook on which to run all quality metrics on its latest version. ### qm-run-on-version The `qm-run-on-version` command is used to run all quality metrics on a given version of a named cookbook. This subcommand has the following syntax: ``` sudo -u supermarket supermarket-ctl qm-run-on-version COOKBOOK_NAME VERSION ``` where `COOKBOOK_NAME` and `VERSION` are respectively the name and version of the cookbook on which to run all quality metrics. General Commands ---------------- ### cleanse The `cleanse` subcommand is used to re-set the server to the state it was in before the first time the `reconfigure` subcommand is run to destroy all data, configuration files, and logs. This subcommand has the following syntax: ``` supermarket-ctl cleanse ``` ### help The `help` subcommand is used to print a list of all available supermarket-ctl commands. This subcommand has the following syntax: ``` supermarket-ctl help ``` ### reconfigure The `reconfigure` subcommand is used when changes are made to the supermarket.rb file to reconfigure the server. When changes are made to the supermarket.rb file, they will not be applied to the Chef Supermarket configuration until after this command is run. This subcommand will also restart any services for which the `service_name['enabled']` setting is set to `true`. This subcommand has the following syntax: ``` supermarket-ctl reconfigure ``` ### show-config The `show-config` subcommand is used to view the configuration that will be generated by the `reconfigure` subcommand. This command is most useful in the early stages of a deployment to ensure that everything is built properly prior to installation. This subcommand has the following syntax: ``` supermarket-ctl show-config ``` ### uninstall The `uninstall` subcommand is used to remove the Chef Supermarket application, but without removing any of the data. This subcommand will shut down all services (including the `runit` process supervisor). This subcommand has the following syntax: ``` supermarket-ctl uninstall ``` Note To revert the `uninstall` subcommand, run the `reconfigure` subcommand (because the `start` subcommand is disabled by the `uninstall` command). Service Subcommands ------------------- This command has a built in process supervisor that ensures all of the required services are in the appropriate state at any given time. The supervisor starts two processes per service and provides the following subcommands for managing services: `hup`, `int`, `kill`, `once`, `restart`, `service-list`, `start`, `status`, `stop`, `tail`, and `term`. ### hup The `hup` subcommand is used to send a `SIGHUP` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl hup name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. ### int The `int` subcommand is used to send a `SIGINT` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl int name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. ### kill The `kill` subcommand is used to send a `SIGKILL` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl kill name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. ### once The supervisor for Chef Supermarket is configured to restart any service that fails, unless that service has been asked to change its state. The `once` subcommand is used to tell the supervisor to not attempt to restart any service that fails. This command is useful when troubleshooting configuration errors that prevent a service from starting. Run the `once` subcommand followed by the `status` subcommand to look for services in a down state and/or to identify which services are in trouble. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl once name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. ### restart The `restart` subcommand is used to restart all services enabled on Chef Supermarket or to restart an individual service by specifying the name of that service in the command. This subcommand has the following syntax: ``` supermarket-ctl restart name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully restarted the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` ### service-list The `service-list` subcommand is used to display a list of all available services. A service that is enabled is labeled with an asterisk (*). This subcommand has the following syntax: ``` supermarket-ctl service-list ``` ### start The `start` subcommand is used to start all services that are enabled in Chef Supermarket. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl start name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully started the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` The supervisor for Chef Supermarket is configured to wait seven seconds for a service to respond to a command from the supervisor. If you see output that references a timeout, it means that a signal has been sent to the process, but that the process has yet to actually comply. In general, processes that have timed out are not a big concern, unless they are failing to respond to the signals at all. If a process is not responding, use a command like the `kill` subcommand to stop the process, investigate the cause (if required), and then use the `start` subcommand to re-enable it. ### status The `status` subcommand is used to show the status of all services available to Chef Supermarket. The results will vary based on the configuration of a given server. This subcommand has the following syntax: ``` supermarket-ctl status ``` and will return the status for all services. Status can be returned for individual services by specifying the name of the service as part of the command: ``` supermarket-ctl status name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. When service status is requested, the output should be similar to: ``` run: service_name: (pid 12345) 12345s; run: log: (pid 1234) 67890s ``` where * `run:` is the state of the service (`run:` or `down:`) * `service_name:` is the name of the service for which status is returned * `(pid 12345)` is the process identifier * `12345s` is the uptime of the service, in seconds For example: ``` down: actions: (pid 35546) 10s ``` By default, runit will restart services automatically when the services fail. Therefore, runit may report the status of a service as `run:` even when there is an issue with that service. When investigating why a particular service is not running as it should be, look for the services with the shortest uptimes. For example, the list below indicates that the **actions** should be investigated further: ``` run: actions: (pid 6361) 4132s; run: log: (pid 6173) 4146s run: actions_consumer: (pid 6374) 5s; run: log: (pid 6227) 4139s run: actions_messages: (pid 6392) 4131s; run: log: (pid 6324) 4133s run: memcached: (pid 6115) 4157s; run: log: (pid 6129) 4156s ``` #### Log Files A typical status line for a service that is running in Chef Supermarket is similar to the following: ``` run: name_of_service: (pid 1486) 7819s; run: log: (pid 1485) 7819s ``` where: * `run` describes the state in which the supervisor attempts to keep processes. This state is either `run` or `down`. If a service is in a `down` state, it should be stopped * `name_of_service` is the service name * `(pid 1486) 7819s;` is the process identifier followed by the amount of time (in seconds) the service has been running * `run: log: (pid 1485) 7819s` is the log process. It is typical for a log process to have a longer run time than a service; this is because the supervisor does not need to restart the log process in order to connect the supervised process If the service is down, the status line will appear similar to the following: ``` down: actions: 3s, normally up; run: log: (pid 1485) 8526s ``` where * `down` indicates that the service is in a down state * `3s, normally up;` indicates that the service is normally in a run state and that the supervisor would attempt to restart this service after a reboot ### stop The `stop` subcommand is used to stop all services enabled on Chef Supermarket. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl stop name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully stopped the output should be similar to: ``` ok: diwb: service_name: 0s, normally up ``` For example: ``` supermarket-ctl stop ``` will return something similar to: ``` ok: down: actions: 1s, normally up ok: down: actions_consumer: 0s, normally up ok: down: actions_messages: 0s, normally up ok: down: memcached: 1s, normally up ``` ### tail The `tail` subcommand is used to follow all Chef Supermarket logs for all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl tail name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. ### term The `term` subcommand is used to send a `SIGTERM` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` supermarket-ctl term name_of_service ``` where `name_of_service` represents the name of any service that is listed after running the `service-list` subcommand. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/supermarket/ctl_supermarket/Chef Supermarket ================ [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/supermarket_private.md) Chef Supermarket is the site for community cookbooks. It provides an easily searchable cookbook repository and a friendly web UI. Cookbooks that are part of the Chef Supermarket are accessible by any Chef user. There are two ways to use Chef Supermarket: * The public Chef Supermarket is hosted by Chef Software and is located at [Chef Supermarket](https://supermarket.chef.io/). * A private Chef Supermarket may be installed on-premise behind the firewall on the internal network. Cookbook retrieval from a private Chef Supermarket is often faster than from the public Chef Supermarket because of closer proximity and fewer cookbooks to resolve. A private Chef Supermarket can also help formalize internal cookbook release management processes (e.g. “a cookbook is not released until it’s published on the private Chef Supermarket”). Private Supermarket ------------------- The private Chef Supermarket is installed behind the firewall on the internal network. Outside of changing the location from which community cookbooks are maintained, it otherwise behaves the same as the public Chef Supermarket. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/supermarket/supermarket_private/Upgrade Supermarket =================== [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/supermarket_upgrade.md) Upgrade Matrix -------------- | Running Version | Upgrade Version | Supported Version | | --- | --- | --- | | A1 | B1 | C1 | | A2 | B2 | C2 | | A3 | B3 | C3 | Upgrade Supermarket ------------------- ### Database Preparation ### Upgrade Steps External PostgreSQL ------------------- The External PostgreSQL upgrade steps are provided as a courtesy. It is the responsibility of the user to upgrade and maintain any External PostgreSQL configurations. Follow these steps to upgrade the PostgreSQL major version. Upgrade Supermarket ------------------- Do we need to upgrade Supermarket first? ### Backup PostgreSQL Database 1. Stop the Supermarket application ``` sudo supermarket-ctl stop ``` 1. Start the Supermarket PostgreSQL service ``` sudo supermarket-ctl start postgresql ``` 1. Back up the PostgreSQL database ``` /opt/supermarket/embedded/bin/pg_dumpall -U supermarket -p 15432 > /tmp/supermarket-dump.sql ``` 1. Vacuum the PostgreSQL database: ``` /opt/supermarket/embedded/bin/vacuumdb --all --full -p 15432 ``` 1. Reindex the PostgreSQL database: ``` /opt/supermarket/embedded/bin/reindexdb --all -p 15432 ``` 1. Restart the Supermarket application ``` supermarket-ctl restart ``` ### Recovering from Upgrade Failures If either the `vacuumdb` or `reindexdb` commands fail 1. Drop the Supermarket PostgreSQL database ``` /opt/supermarket/embedded/bin/psql -U supermarket -d postgres -p 15432 -c "drop database supermarket" ``` 1. Recreate the Supermarket PostgreSQL database ``` /opt/supermarket/embedded/bin/psql -U supermarket -d postgres -p 15432 -c "create database supermarket" ``` 1. Restore Supermarket PostgreSQL database from the existing `dump.sql` file ``` /opt/supermarket/embedded/bin/psql -U supermarket -d supermarket -p 15432 -f /tmp/supermarket-dump.sql ``` 1. Restart the Supermarket application ``` supermarket-ctl restart ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/supermarket/supermarket_upgrade/Supermarket Logs ================ [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/supermarket_logs.md) The Chef Supermarket omnibus package does not log Ruby on Rails messages by default. To enable debug logging, edit the `/opt/supermarket/embedded/service/supermarket/config/environments/production.rb` file and set the `config.log_level` setting to `:debug`: ``` config.logger = Logger.new('/var/log/supermarket/rails/rails.log') config.logger.level = 'DEBUG' config.log_level = :debug ``` Save the file, and then restart the Ruby on Rails service: ``` supermarket-ctl restart rails ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/supermarket/supermarket_logs/Monitor Supermarket =================== [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/supermarket_monitor.md) A private Chef Supermarket includes a URL for status monitoring, which has the format: `https://your_private_supermarket/status`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/supermarket/supermarket_monitor/Supermarket API =============== [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/supermarket_api.md) Note In general, using knife (and the `knife supermarket` subcommand) to manage cookbooks that are located on the Cookbooks site is more efficient than using the Supermarket API and is the recommended approach for managing cookbooks on that site. This document provides information about the Supermarket API in the event that using the API is necessary. The Supermarket API is used to provide access to cookbooks, tools, and users on the [Chef Supermarket](https://supermarket.chef.io). All of the cookbooks, tools, and users on the Supermarket are accessible through a RESTful API by accessing `supermarket.chef.io/api/v1/` via the supported endpoints. In most cases, knife is the best way to interact with the Supermarket; however in some cases, direct use of the Supermarket API is necessary. Endpoints --------- The Supermarket API has the following endpoints. ### /cookbooks A cookbook is the fundamental unit of configuration and policy distribution in Chef Infra. A cookbook defines a scenario and contains everything that is required to support that scenario: * Recipes that specify which Chef Infra built-in resources to use, as well as the order in which they are to be applied * Attribute values, which allow environment-based configurations such as `dev` or `prodution`. * Custom Resources for extending Chef Infra beyond the built-in resources. * Files and Templates for distributing information to systems. * Custom Ohai Plugins for extending system configuration collection beyond the Ohai defaults. * The `metadata.rb` file, which describes the cookbook itself and any dependencies it may have. The `/cookbooks` endpoint has the following methods: `GET` and `POST`. #### POST The `POST` method is used to create a new cookbook. This method has no parameters. **Request** ``` POST /api/v1/cookbooks/COOKBOOK_NAME ``` **Response** The response is similar to: ``` { "name": "apt", "maintainer": "sous-chefs", "description": "Configures apt and apt caching.", "category": "Other", "latest_version": "http://supermarket.chef.io/api/v1/cookbooks/apt/versions/2_4_0", "external_url": "https://github.com/sous-chefs/apt", "average_rating": null, "created_at": "2009-10-25T23:48:48.000Z", "updated_at": "2021-01-20T23:43:43.989Z" } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. The cookbook was posted to the Supermarket API. | | `400` | The request was unsuccessful. The cookbook was not posted to the Supermarket API. For example: ``` { "error_messages": ["You're not authorized to upload this cookbook."], "error_code": "UNAUTHORIZED" } ``` | #### GET The `GET` method is used to get a listing of the available cookbooks. Use the `start` and `items` parameters to set limits on the number of cookbooks returned. Use the `order` parameter to change the way results are sorted. Use the `user` parameter to filter cookbooks by maintainer: | Parameter | Description | | --- | --- | | `start` | The offset into a list of cookbooks, at which point the list of cookbooks will begin. | | `items` | The number of items to be returned as a result of the request. | | `order` | A token specifying how to order results. Possible values: `recently_updated`, `recently_added`, `most_downloaded`, or `most_followed`. | | `user` | The username to filter by. Only cookbooks maintained by this user will be returned. | **Request** ``` GET /api/v1/cookbooks?start=START&items=ITEMS ``` or: ``` GET /api/v1/cookbooks?user=smith ``` **Response** The response will return the name of the cookbook, a description, URI, the name of the individual who maintains the cookbook. In addition, the total number of cookbooks on Supermarket API is shown, as well (if `start` is specified) the point at which the list of returned cookbooks began: ``` { "total": 5234, "start": 20, "items": [ {"cookbook_name": "apache", "cookbook_description": "installs apache.", "cookbook": "http://supermarket.chef.io/api/v1/cookbooks/apache", "cookbook_maintainer": "john" }, {"cookbook_name": "nginx", "cookbook_description": "installs nginx.", "cookbook": "http://supermarket.chef.io/api/v1/cookbooks/nginx", "cookbook_maintainer": "jill" }, {"cookbook_name": "mysql", "cookbook_description": null, "cookbook": "http://supermarket.chef.io/api/v1/cookbooks/mysql", "cookbook_maintainer": "barry" }, {"cookbook_name": "postgresql", "cookbook_description": null, "cookbook": "http://supermarket.chef.io/api/v1/cookbooks/postgresql", "cookbook_maintainer": "pt" }, {"cookbook_name": "ptapache", "cookbook_description": "an alternate apache recipe.", "cookbook": "http://supermarket.chef.io/api/v1/cookbooks/ptapache", "cookbook_maintainer": "pt" } ] } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. One or more cookbooks were returned as a result of the search query. | ### /cookbooks/NAME The `cookbooks/[NAME]` endpoint allows a specific cookbook to be accessed. This endpoint has the following methods: `DELETE` and `GET`. #### DELETE The `DELETE` method is used to delete a cookbook. This method has no parameters. **Request** ``` DELETE /api/v1/cookbooks/cookbook_name ``` **Response** The response is similar to: ``` { "name": "apt", "maintainer": "sous-chefs", "description": "Configures apt and apt caching.", "category": "Other", "latest_version": "http://supermarket.chef.io/api/v1/cookbooks/apt/versions/7_4_0", "external_url": "https://github.com/chef-cookbooks/apt", "average_rating": null, "created_at": "2009-10-25T23:48:48.000Z", "updated_at": "2021-01-20T23:43:43.989Z" } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. The cookbook was deleted. | | `400` | The request was unsuccessful. The requested cookbook does not exist. For example: ``` { "error_messages": ["Resource does not exist"], "error_code": "NOT_FOUND" } ``` | | `403` | Unauthorized. The user who made the request is not authorized to perform the action. The user is not authorized to delete the cookbook. For example: ``` {} ``` | #### GET The `GET` method is used to get the details for a cookbook. This method has no parameters. **Request** ``` GET /api/v1/cookbooks/COOKBOOK_NAME ``` **Response** The response will return details for a cookbook, including name of the cookbook, the category to which it belongs, the name of the individual who maintains the cookbook, the URI for the latest version and previous versions, its description, and it also includes metrics about the cookbooks namely number of downloads and followers: ``` { "name": "yum", "maintainer": "sous-chefs", "description": "Configures various yum components on Red Hat-like systems", "category": "Other", "latest_version": "http://supermarket.chef.io/api/v1/cookbooks/yum/versions/7_1_0", "external_url": "https://github.com/sous-chefs/yum", "average_rating": null, "created_at": "2011-04-20T22:16:12.000Z", "updated_at": "2021-08-29T18:45:03.956Z", "deprecated": false, "versions": [ "http://supermarket.chef.io/api/v1/cookbooks/yum/versions/7_1_0", "http://supermarket.chef.io/api/v1/cookbooks/yum/versions/7_0_0" ], "metrics": { "downloads": { "total": 178894510 "versions": { "7_0_0": 13032, "7_1_0": 12188 } }, "followers": 189, "collaborators": 3 } } ``` If a cookbook is deprecated, that status is noted by the `deprecated` field (being `true`): ``` { "name": "apache", "category": "web servers", ... "deprecated": true, ... } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. The requested cookbook exists. | | `400` | The request was unsuccessful. The requested cookbook does not exist. For example: ``` { "error_messages": ["Resource does not exist"], "error_code": "NOT_FOUND" } ``` | ### /cookbooks/VERSION A cookbook version always takes the form x.y.z, where x, y, and z are decimal numbers that are used to represent major (x), minor (y), and patch (z) versions. A two-part version (x.y) is also allowed. When passing a cookbook version using this method, underscores ("_") should be used as the separator between versions. For example, a cookbook with a version 1.0.1 would be 1_0_1. The `/cookbooks/[VERSION]` endpoint has the following methods: `DELETE` and `GET`. #### DELETE The `DELETE` method is used to delete a cookbook version. This method has no parameters. **Request** ``` DELETE /api/v1/cookbooks/cookbook_name/versions/version ``` **Response** The response is similar to: ``` { "license": "Apache 2.0", "tarball_file_size": 18553, "version": "2.4.0", "average_rating": null, "cookbook": "http://supermarket.chef.io/api/v1/cookbooks/apt", "file": "http://supermarket.chef.io/api/v1/cookbooks/apt/versions/2_4_0/download", "dependencies": {}, "platforms": { "debian": ">= 0.0.0", "ubuntu": ">= 0.0.0" } } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. The cookbook version was deleted. | | `400` | The request was unsuccessful. The requested cookbook or cookbook version does not exist. For example: ``` { "error_messages": ["Resource does not exist"], "error_code": "NOT_FOUND" } ``` | | `403` | Unauthorized. The user who made the request is not authorized to perform the action. The user is not authorized to delete the cookbook version. For example: ``` {} ``` | #### GET The `GET` method is used to get a specific version of a cookbook. Use `latest` to get the most recent version of a cookbook. This method has no parameters. **Request** ``` GET /api/v1/cookbooks/COOKBOOK_NAME/versions/latest ``` or: ``` GET /api/v1/cookbooks/COOKBOOK_NAME/versions/VERSION ``` **Response** The response will return details for a cookbook version, including the license under which the cookbook is distributed, the most recent update, version, URI, date of cookbook creation, path to the cookbook’s tar.gz file, its dependencies and platforms it supports and more: ``` { "license": "Apache 2.0", "tarball_file_size": 18553, "version": "2.4.0", "average_rating": null, "cookbook": "http://supermarket.chef.io/api/v1/cookbooks/apt", "file": "http://supermarket.chef.io/api/v1/cookbooks/apt/versions/2_4_0/download", "dependencies": {}, "platforms": { "debian": ">= 0.0.0", "ubuntu": ">= 0.0.0" } } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. The requested cookbook exists. | | `400` | The request was unsuccessful. The requested cookbook does not exist. For example: ``` { "error_messages": ["Resource does not exist"], "error_code": "NOT_FOUND" } ``` | ### /search Search performs a fuzzy, keyword search on cookbook names, cookbook descriptions, and the cookbook owners' usernames. The `/search` endpoint has the following methods: `GET`. #### GET The `GET` method is used to get a list of cookbooks that match a search query. Use the `start` and `items` parameters to set limits on the number of cookbooks returned: | Parameter | Description | | --- | --- | | `q` | The search query used to identify a list of items on a Chef Infra Server. This option uses the same syntax as the `search` subcommand. | | `start` | The row at which return results begin. | | `items` | The number of rows to be returned. | **Request** ``` GET /api/v1/search?q=SEARCH_QUERY ``` or: ``` GET /api/v1/search?q=SEARCH_QUERY&start=START&items=ITEMS ``` **Response** The response will return a list of cookbooks by name and description and will return a list of cookbooks that match the search query. Each returned data set will include the name of the cookbook, a description, the URI, and the name of the individual who maintains the cookbook. In addition, the total number of cookbooks on Supermarket API is shown, as well (if `start` is specified) the point at which the list of returned cookbooks began: ``` { "total": 2, "start": 0, "items": [ { "cookbook_name": "apache", "cookbook_description": "installs a web server.", "cookbook": "http://supermarket.chef.io/api/v1/cookbooks/apache", "cookbook_maintainer": "jtimberman" }, { "cookbook_name": "webserver", "cookbook_description": "installs apache.", "cookbook": "http://supermarket.chef.io/api/v1/cookbooks/webserver", "cookbook_maintainer": "raxmus" } ] } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. One or more cookbooks were returned as a result of the search query. | ### /tools The `tools` endpoint allows Chef Supermarket tools to be accessed. This endpoint has the following methods: `GET`. #### GET The `GET` method is used to get a listing of the available tools. Use the `start` and `items` parameters to set limits on the number of tools returned. Use the `order` parameter to change the way results are sorted. | Parameter | Description | | --- | --- | | `start` | The offset into a list of tools, at which point the list of tools will begin. | | `items` | The number of items to be returned as a result of the request. | | `order` | A token specifying how to order results. Possible values: `recently_added`. | **Request** ``` GET /api/v1/tools?start=START&items=ITEMS ``` or: ``` GET /api/v1/tools?order=recently_added ``` **Response** The response will return the name of the tool, a type, description, owner, source URL and URI. In addition, the total number of tools on Supermarket API is shown, as well (if `start` is specified) the point at which the list of returned tools began: ``` { "start": 0, "total": 56, "items": [ { "tool_name": "Berkflow", "tool_type": "chef_tool", "tool_source_url": "https://github.com/reset/berkflow", "tool_description": "A Cookbook-Centric Deployment workflow tool", "tool_owner": "reset", "tool": "https://supermarket.chef.io/api/v1/tools/berkflow" }, { "tool_name": "Berkshelf", "tool_type": "chef_tool", "tool_source_url": "https://github.com/berkshelf/berkshelf", "tool_description": "A Chef Cookbook manager", "tool_owner": "reset", "tool": "https://supermarket.chef.io/api/v1/tools/berkshelf" }, { "tool_name": "Berkshelf-API", "tool_type": "chef_tool", "tool_source_url": "https://github.com/berkshelf/berkshelf-api", "tool_description": "Berkshelf dependency API server", "tool_owner": "reset", "tool": "https://supermarket.chef.io/api/v1/tools/berkshelf-api" } ] } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. One or more tools were returned. | ### /tools-search The `tools` endpoint allows Chef Supermarket tools to be searched. This endpoint has the following methods: `GET`. #### GET The `GET` method is used to get a list of tools that match a search query. Use the `start` and `items` parameters to set limits on the number of tools returned: | Parameter | Description | | --- | --- | | `q` | The search query used to identify a list of items on a Chef Infra Server. This option uses the same syntax as the `search` subcommand. | | `start` | The row at which return results begin. | | `items` | The number of rows to be returned. | **Request** ``` GET /api/v1/tools-search?q=SEARCH_QUERY ``` or: ``` GET /api/v1/tools-search?q=SEARCH_QUERY&start=START&items=ITEMS ``` **Response** The response will return a list of tools that match the search query. Each returned data set will include the name of the tool, a type, description, owner, source URL and URI. In addition, the total number of tools that match the query on Supermarket API is shown, as well (if `start` is specified) the point at which the list of returned tools began: ``` { "start": 0, "total": 1, "items": [ { "tool_name": "knife-rhn", "tool_type": "knife_plugin", "tool_source_url": "https://github.com/bflad/knife-rhn", "tool_description": "Knife Plugin for Red Hat Network (RHN)", "tool_owner": "bflad", "tool": "https://supermarket.chef.io/api/v1/tools/knife-rhn" } ] } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. One or more tools were returned as a result of the search query. | ### /tools/SLUG The `tools/[SLUG]` endpoint allows a specific tool to be accessed. This endpoint has the following methods: `GET`. #### GET The `GET` method is used to get the details for a tool. This method has no parameters. **Request** ``` GET /api/v1/tools/TOOL_SLUG ``` **Response** The response will return details for a tool, including the name of the tool, a type, description, owner, source URL and install instructions as markdown: ``` { "name": "Berkshelf", "slug": "berkshelf", "type": "chef_tool", "source_url": "https://github.com/berkshelf/berkshelf", "description": "A Chef Cookbook manager", "instructions": "# Berkshelf\r\n[![Gem Version](https://img.shields.io/gem/v/berkshelf.svg)][gem]\r\n[![Build Status](https://img.shields.io/travis/berkshelf/berkshelf.svg)][travis]\r\n\r\n[gem]: https://rubygems.org/gems/berkshelf\r\n[travis]: https://travis-ci.org/berkshelf/berkshelf\r\n\r\nManage a Cookbook or an Application's Cookbook dependencies\r\n\r\n## Installation\r\n\r\nBerkshelf is now included as part of the [Chef-DK](http://chef.io/downloads/chef-dk). This is fastest, easiest, and the recommended installation method for getting up and running with Berkshelf.\r\n\r\n> note: You may need to uninstall the Berkshelf gem especially if you are using a Ruby version manager you may need to uninstall all Berkshelf gems from each Ruby installation.\r\n\r\n### From Rubygems\r\n\r\nIf you are a developer or you prefer to install from Rubygems, we've got you covered.\r\n\r\nAdd Berkshelf to your repository's `Gemfile`:\r\n\r\n```ruby\r\ngem 'berkshelf'\r\n```\r\n\r\nOr run it as a standalone:\r\n\r\n gem install berkshelf\r\n\r\n## Usage\r\n\r\nSee [berkshelf.com](http://berkshelf.com) for up-to-date usage instructions.\r\n\r\n## Supported Platforms\r\n\r\nBerkshelf is tested on Ruby 1.9.3, 2.0, and 2.1.\r\n\r\nRuby 1.9 mode is required on all interpreters.\r\n\r\nRuby 1.9.1 and 1.9.2 are not officially supported. If you encounter problems, please upgrade to Ruby 2.0 or 1.9.3.\r\n\r\n## Configuration\r\n\r\nBerkshelf will search in specific locations for a configuration file. In order:\r\n\r\n $PWD/.berkshelf/config.json\r\n $PWD/berkshelf/config.json\r\n $PWD/berkshelf-config.json\r\n $PWD/config.json\r\n ~/.berkshelf/config.json\r\n\r\nYou are encouraged to keep project-specific configuration in the `$PWD/.berkshelf` directory. A default configuration file is generated for you, but you can update the values to suit your needs.\r\n\r\n## Shell Completion\r\n\r\n- [Bash](https://github.com/berkshelf/berkshelf-bash-plugin)\r\n- [ZSH](https://github.com/berkshelf/berkshelf-zsh-plugin)\r\n\r\n## Plugins\r\n\r\nPlease see [Plugins page](https://github.com/berkshelf/berkshelf/blob/main/PLUGINS.md) for more information.\r\n\r\n## Getting Help\r\n\r\n* If you have an issue: report it on the [issue tracker](https://github.com/berkshelf/berkshelf/issues)\r\n* If you have a question: visit the #general or #berkshelf channel in the Chef Community Slack (http://community-slack.chef.io/)\r\n\r\n## Authors\r\n\r\n[The Berkshelf Core Team](https://github.com/berkshelf/berkshelf/wiki/Core-Team)\r\n\r\nThank you to all of our [Contributors](https://github.com/berkshelf/berkshelf/graphs/contributors), testers, and users.\r\n\r\nIf you'd like to contribute, please see our [contribution guidelines](https://github.com/berkshelf/berkshelf/blob/main/CONTRIBUTING.md) first.\r\n", "owner": "reset" } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. The requested tool exists. | | `400` | The request was unsuccessful. The requested tool does not exist. For example: ``` { "error_messages": ["Resource does not exist"], "error_code": "NOT_FOUND" } ``` | ### /universe The universe is the known collection of cookbooks that have been uploaded to Chef Supermarket. The universe is JSON data organized by cookbook, then by cookbook version, and then by a dependency graph that lists each dependency a cookbook version may have on other cookbooks or cookbook versions. Use the `/universe` endpoint to retrieve the known collection of cookbooks, and then use it with Berkshelf. The `/universe` endpoint has the following methods: `GET`. #### GET The `GET` method is used to retrieve the universe data. This method has no parameters. **Request** ``` GET /universe ``` **Response** The response will return an embedded hash, with the name of each cookbook as a top-level key. Each cookbook will list each version, along with its location information and dependencies: ``` { "ffmpeg": { "0.1.0": { "location_path": "http://supermarket.chef.io/api/v1/cookbooks/ffmpeg/0.1.0/download" "location_type": "supermarket", "dependencies": { "git": ">= 0.0.0", "build-essential": ">= 0.0.0", "libvpx": "~> 0.1.1", "x264": "~> 0.1.1" }, }, "0.1.1": { "location_path": "http://supermarket.chef.io/api/v1/cookbooks/ffmpeg/0.1.1/download" "location_type": "supermarket", "dependencies": { "git": ">= 0.0.0", "build-essential": ">= 0.0.0", "libvpx": "~> 0.1.1", "x264": "~> 0.1.1" }, }, "pssh": { "0.1.0": { "location_path": "http://supermarket.chef.io/api/v1/cookbooks/pssh.1.0/download" "location_type": "supermarket", "dependencies": {}, } } } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. One (or more) cookbooks and associated cookbook version information was returned. | ### /users/USERNAME The `users/[USERNAME]` endpoint allows a specific Chef Supermarket user to be accessed. This endpoint has the following methods: `GET`. #### GET The `GET` method is used to get the details for a user. This method has no parameters. **Request** ``` GET /api/v1/users/USERNAME ``` **Response** The response will return details for a user, including their name, Chef username, associated account details, and a list of cookbooks and tools that are associated with the user. Cookbooks are grouped into three categories: those that are owned by this user, those in which this user has collaborated, and those that are followed. ``` { "username": "tbucatar", "name": "<NAME>", "company": "Chef Software, Inc", "github": [ "tbucatar" ], "twitter": "tbucatar", "irc": "tbucatar", "cookbooks": { "owns": { "bacon": "https://supermarket.chef.io/api/v1/cookbooks/bacon" "chef-sugar": "https://supermarket.chef.io/api/v1/cookbooks/chef-sugar" }, "collaborates": { "build-essential": "https://supermarket.chef.io/api/v1/cookbooks/build-essential" "jenkins": "https://supermarket.chef.io/api/v1/cookbooks/jenkin" }, "follows": { "bacon": "https://supermarket.chef.io/api/v1/cookbooks/bacon" "chef-sugar": "https://supermarket.chef.io/api/v1/cookbooks/chef-sugar" } }, "tools": { "owns": { "bacon_tool": "https://supermarket.chef.io/api/v1/tools/bacon_tool" } } } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/supermarket/supermarket_api/supermarket.rb Settings ======================= [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/config_rb_supermarket.md) The supermarket.rb file contains all of the non-default configuration settings used by the Chef Supermarket. The default settings are built-in to the Chef Supermarket configuration, and should only be added to the supermarket.rb file to apply non-default values. These configuration settings are processed when the `supermarket-ctl reconfigure` command is run. The supermarket.rb file is a Ruby file, which means that conditional statements can be used in the configuration file. Settings -------- The following settings are available in the `/etc/supermarket/supermarket.rb` file. Note You must run `supermarket-ctl reconfigure` to apply any changes made in the `supermarket.rb` file. ### General This configuration file has the following general settings: `default['enterprise']['name']` The enterprise name that is used by the [enterprise-chef-common](https://github.com/chef-cookbooks/enterprise-chef-common) cookbook. Default value: `'supermarket'`. `default['supermarket']['app_directory']` Default value: `"#{node['supermarket']['install_directory']}/embedded/service/supermarket"`. `default['supermarket']['chef_server_url']` The URL of the Chef Infra Server. `default['supermarket']['config_directory']` The directory that is used to store Supermarket configuration filesDefault value: `'/etc/supermarket'`. `default['supermarket']['features']` Use to enable additional features, such as announcements and GitHub integration. Default value: `'tools'`. Features currently available: `tools`, `fieri`, `announcement`, `github`, and `no_crawl`. `default['supermarket']['fqdn']` The fully qualified domain name for the Supermarket server. Defaults to using the current FQDN for the machine. `default['supermarket']['from_email']` The default sender address of all Supermarket mailers. Default value: `nil`. `default['supermarket']['group']` The system group that is used to manage Supermarket on the server. Default value: `'supermarket'`. `default['supermarket']['install_directory']` The directory where Supermarket is installed. Default value: `'/opt/supermarket'`. `default['supermarket']['install_path']` The directory in which Chef Supermarket is installed. Default value: `node['supermarket']['install_directory']`. `default['supermarket']['log_directory']` The directory that Supermarket will use to store logs. Default value: `'/var/log/supermarket'`. `default['supermarket']['log_mode']` The Supermarket log directory file permissions. Default value: `0700`. `default['supermarket']['sysvinit_id']` Use to specify 1-4 characters that define a unique identifier for the file located in `/etc/inittab`. Default value: `SUP`. `default['supermarket']['user']` The system user that is used to run Supermarket. Default value: `'supermarket'`. `default['supermarket']['var_directory']` The directory where data and cookbooks are installed. Default value: `'/var/opt/supermarket'`. ### Amazon Simple Storage Service (S3) Use these settings to upload cookbooks to an Amazon Simple Storage Service (S3) bucket. Note Encrypted S3 buckets are currently not supported. `default['supermarket']['cdn_url']` The URL for the content delivery network. (optional) `default['supermarket']['s3_access_key_id']` The secret key. (required to use S3) `default['supermarket']['s3_bucket']` The bucket name. (required to use S3) `default['supermarket']['s3_path']` **(Optional)** Directory structure to prepend to the standard path of the directory containing cookbooks. Set this if you must store cookbooks in a deeper directory structure within a shared bucket. However, keep in mind that dedicated S3 buckets are recommended for cookbook storage and distribution. `default['supermarket']['s3_private_objects']` Whether cookbooks stored in S3 should be public or private. `true/false` Default: `false` `default['supermarket']['s3_region']` The region of the bucket. (required to use S3) `default['supermarket']['s3_secret_access_key']` The access key identifier. (required to use S3) ### Database The following database options are available: `default['supermarket']['database']['extensions']` Determines which PostgreSQL extensions are enabled. Default value: `{ 'pgpsql' => true, 'pg_trgm' => 'true' }`. `default['supermarket']['database']['host']` The address PostgreSQL listens on. Default value: `node['supermarket']['postgresql']['listen_address']`. `default['supermarket']['database']['name']` The name of the Supermarket database. Default value: `'supermarket'`. `default['supermarket']['database']['pool']` The number of concurrent threads a database worker can create. Default value: `node['supermarket']['sidekiq']['concurrency']`. `default['supermarket']['database']['port']` The port that the database listens on. Default value: `node['supermarket']['postgresql']['port']`. `default['supermarket']['database']['user']` The database user. Default value: `node['supermarket']['postgresql']['username']`. `default['supermarket']['postgresql']['username']` The system user that runs PostgreSQL. By default, this uses the value of `node['supermarket']['user']`. ### Fieri Use these settings to enable [Fieri](../index#fieri), an optional service built into Supermarket that provides cookbook quality metrics. As a Supermarket feature, Fieri must be enabled via the `default['supermarket']['features']` option. `default['supermarket']['fieri_url']` The full URL that is used to access Fieri. Default value: `'http://localhost:13000/fieri/jobs'` `default['supermarket']['fieri_supermarket_endpoint']` The URL of the Chef Supermarket that is using Fieri. Default value: `'https://localhost:13000'` `default['supermarket']['fieri_key']` A string that is used as a key to authenticate Fieri. Default value: `nil`. This value should be set to a random string for fieri feature to work properly. One example to generate random string - `openssl rand -base64 32` ### GitHub Use these settings to integrate Supermarket with GitHub. As a Supermarket feature, GitHub must be enabled via the`default['supermarket']['features']` option. `default['supermarket']['github_access_token']` The access token created from your GitHub account. Default value:`nil`. `default['supermarket']['github_key']` The application client ID that is used to authenticate Supermarket to GitHub. Default value: `nil`. `default['supermarket']['github_secret']` The application client secret that is used to authenticate Supermarket to GitHub. Default value: `nil`. `default['supermarket']['github_url']` The GitHub URL that Supermarket connects to. Default value:`https://github.com/`. ### GitHub Enterprise Use these settings to integrate Supermarket with GitHub Enterprise. `default['supermarket']['github_access_token']` The access token created from your GitHub Enterprise account. Default value:`nil`. `default['supermarket']['github_key']` The application client ID that is used to authenticate Supermarket to GitHub Enterprise. Default value: `nil`. `default['supermarket']['github_secret']` The application client secret that is used to authenticate Supermarket to GitHub Enterprise. Default value: `nil`. `default['supermarket']['github_enterprise_url']` The GitHub Enterprise URL that Supermarket connects to. Default value:`nil`. `default['supermarket']['github_client_option_authorize_url']` The URL used to authorize with your implementation of GitHub Enterprise Server. For example: `https://github.example.com/login/oauth/authorize`. Default value: `nil`. `default['supermarket']['github_client_option_site']` The URL for your implementation of GitHub Enterprise. For example: `https://github.example.com/api/v3`. Default value: `nil`. `default['supermarket']['github_client_option_access_token_url']` The URL of the GitHub Enterprise access token: For example: `https://github.example.com/login/oauth/access_token`. Default value:`nil`. ### Google Analytics Use this setting to set up [Google Analytics](https://analytics.google.com) tracking for Supermarket: `default['supermarket']['google_analytics_id']` The Google Analytics [tracking ID](https://support.google.com/analytics/answer/7372977?hl=en) for Supermarket. Default value: `nil`. ### Nginx This configuration file has the following settings for nginx: `default['supermarket']['nginx']['access_log_options']` A string of [additional options](https://nginx.org/en/docs/http/ngx_http_log_module.html) to be added to the nginx access log directive. Default value: `nil`. `default['supermarket']['nginx']['cache']['directory']` The directory used by nginx for caching. Default value: `"#{node['supermarket']['var_directory']}/nginx//cache"`. `default['supermarket']['nginx']['cache']['enable']` Determines whether or not nginx caching is enabled. Default value: `false`. `default['supermarket']['nginx']['client_body_buffer_size']` The [client_body_buffer_size](https://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) used by nginx. Default value: `nil`. `default['supermarket']['nginx']['client_max_body_size']` The maximum accepted body size for a client request, as indicated by the `Content-Length` request header. When the maximum accepted body size is greater than this value, a `413 Request Entity Too Large` error is returned. Default value: `250m`. See the [nginx documentation](https://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size) for additional information. `default['supermarket']['nginx']['daemon_disable']` Determines whether or not nginx is daemonized. By default, this will be handled by the init system. Default value: `true`. `default['supermarket']['nginx']['default']['modules']` Determines which additional [nginx modules](https://www.nginx.com/resources/wiki/modules/) should be included. Default value: `[]`. `default['supermarket']['nginx']['default_site_enabled']` Determines whether or not the nginx default page is enabled. Default value: `false`. `default['supermarket']['nginx']['dir']` The working directory. The default value is the recommended value. Default value: `node['supermarket']['nginx']['directory']`. `default['supermarket']['nginx']['disable_access_log']` Allows you to disable the nginx access log. Default value: `false`. `default['supermarket']['nginx']['error_log_options']` A string of [additional options](https://nginx.org/en/docs/http/ngx_http_log_module.html) to be added to the nginx access log directive. Default value: `nil`. `default['supermarket']['nginx']['enable']` Enable the nginx service. Default value: `true`. `default['supermarket']['nginx']['event']` Set the event-model. By default nginx looks for the most suitable method for your OS. Default value: `nil`. `default['supermarket']['nginx']['force_ssl']` Force connections to use SSL. Default value: `true`. `default['supermarket']['nginx']['force_hsts']` Force connections to use HSTS headers. Only valid if `default['supermarket']['nginx']['force_ssl']` is `false`. This feature enables HSTS headers on a Supermarket installation that is behind an SSL-terminating load balancer. Default value: `false`. `default['supermarket']['nginx']['group']` The system group that is used to manage nginx. Default value: `node['supermarket']['group']`. `default['supermarket']['nginx']['gzip']` Enable gzip compression. Default value: `on`. `default['supermarket']['gzip_buffers']` Set the [gzip buffer](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) size. The nginx default is equal to one memory page, depending on the platform, it is either 4K 8K. Default value: `nil`. `default['supermarket']['nginx']['gzip_comp_level']` The compression level used with gzip, from least amount of compression (`1`, fastest) to the most (`2`, slowest). Default value: `2`. `default['supermarket']['gzip_disable']` Disables gzip compression when a `User-Agent` field is present in headers matching the specified regular expressions. Default value: `'MSIE [1-6]\.'`. `default['supermarket']['nginx']['gzip_http_version']` Enable gzip depending on the version of the HTTP request. Default value: `1.0`. `default['supermarket']['gzip_min_length']` The minimum response length that will be compressed by gzip, as determined by the `Content-Length` response header. Default value: `1000`. `default['supermarket']['nginx']['gzip_proxied']` Determines whether or not proxied requests are compressed with gzip, based on the presence of the `Via` request header field. Default value: `any`. `default['supermarket']['nginx']['gzip_static']` Allows you to send precompressed files with the `.gz` file extension instead of regular files. Requires the [ngx_http_gzip_static_module](https://nginx.org/en/docs/http/ngx_http_gzip_static_module.html) module. Default value: `'off'`. `default['supermarket']['nginx']['gzip_types']` Enable compression for the specified MIME-types. Default value: `[ 'text/plain', 'text/css', 'application/x-javascript', 'text/xml', 'application/xml', 'application/xml+rss', 'application/atom+xml', 'text/javascript', 'application/javascript', 'application/json' ]`. `default['supermarket']['gzip_vary']` Determines whether or not the `Vary: Accept-Encoding` response header field is inserted when the following directives are active: `gzip`,`gzip_static`, or `gunzip`. Default value: `'off'`. `default['supermarket']['nginx']['keepalive']` Use to enable HTTP keepalive. Default value: `'on'`. `default['supermarket']['nginx']['keepalive_timeout']` The amount of time (in seconds) to wait for requests on a HTTP keepalive connection. Default value: `65`. `default['supermarket']['nginx']['log_dir']` The directory in which log data is stored. The default value is the recommended value. Default value: `node['supermarket']['nginx']['log_directory']`. `default['supermarket']['nginx']['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `default['supermarket']['nginx']['multi_accept']` Determines whether a worker process accepts a single connection at a time, or all new connections at one time. The default value sets this to a single connection at a time. Default value: `false`. `default['supermarket']['nginx']['non_ssl_port']` The port on which the Automate interface and API are bound for non-SSL connections. Default value: `80`. Set to `false` to disable non-SSL connections. `default['supermarket']['nginx']['pid']` The system process ID for the nginx service. Default value: `"#{node['supermarket']['nginx']['directory']}/nginx.pid"`. `default['supermarket']['nginx']['proxy_read_timeout']` Defines a timeout between two successive read operations for reading a response from the proxied server. Default value: `nil`. `default['supermarket']['nginx']['redirect_to_canonical']` Redirect requests to the Supermarket server FQDN. Default value: `true`. `default['supermarket']['nginx']['sendfile']` Copy data between file descriptors when `sendfile()` is used. Default value: `on`. `default['supermarket']['nginx']['server_names_hash_bucket_size']` The size of the bucket that contains the server names hash tables. Default value: `64`. `default['supermarket']['nginx']['server_tokens']` Determines whether or not the nginx version is included in error pages and the `Server` response header. Default value: `nil`. `default['supermarket']['nginx']['ssl_port']` The port that is used by nginx to terminate SSL connections. Default value: `443`. `default['supermarket']['nginx']['types_hash_bucket_size']` Determines the bucket size for the types hash tables. Default value: `64`. `default['supermarket']['nginx']['types_hash_max_size']` Sets the maximum size of the types hash table. Default value: `2048`. `default['supermarket']['nginx']['user']` The system user that is used to run nginx. Default value: `node['supermarket']['user']`. `default['supermarket']['nginx']['worker_connections']` The maximum number of simultaneous clients. Use with `nginx['worker_processes']` to determine the maximum number of allowed clients. Default value: `1024`. `default['supermarket']['nginx']['worker_rlimit_nofile']` Determines the maximum number of open files allowed for worker processes. Default value: `nil`. `default['supermarket']['nginx']['worker_processes']` The number of allowed worker processes. Use with `nginx['worker_connections']` to determine the maximum number of allowed clients. Default value: `node['cpu'] && node['cpu']['total'] ? node['cpu']['total'] : 1`. ### Oauth2 This configuration file has the following settings for the Chef Infra Server identity service: `default['supermarket']['chef_oauth2_app_id']` The [Chef Identity](../../install_supermarket/index#chef-identity) application ID created for Supermarket on the Chef Infra Server. See the [Chef Identity configuration](../../install_supermarket/index#configure) section of the Supermarket installation guide for additional details. `default['supermarket']['chef_oauth2_secret']` The [Chef Identity](../../install_supermarket/index#chef-identity) application secret created for Supermarket on the Chef Infra Server. See the [Chef Identity configuration](../../install_supermarket/index#configure) section of the Supermarket installation guide for additional details. `default['supermarket']['chef_oauth2_url']` The URL of the Chef Infra Server that Supermarket connects to. Default value: `node['supermarket']['chef_server_url']`. `default['supermarket']['chef_oauth2_verify_ssl']` Determines whether or not Supermarket performs SSL verification. Default value: `true`. If your Chef Infra Server is using a self-signed certificate without a properly configured certificate authority, this must be set to `false`. ### PostgreSQL This configuration file has the following settings for PostgreSQL: `default['supermarket']['postgresql']['checkpoint_completion_target']` A completion percentage that is used to determine how quickly a checkpoint should finish in relation to the completion status of the next checkpoint. For example, if the value is `0.5`, then a checkpoint attempts to finish before 50% of the next checkpoint is done. Default value: `0.5`. `default['supermarket']['postgresql']['checkpoint_segments']` The maximum amount (in megabytes) between checkpoints in log file segments. Default value: `3`. `default['supermarket']['postgresql']['checkpoint_timeout']` The amount of time (in minutes) between checkpoints. Default value: `'5min'`. `default['supermarket']['postgresql']['checkpoint_warning']` The frequency (in seconds) at which messages are sent to the server log files if checkpoint segments are being filled faster than their currently configured values. Default value: `'30s'`. `default['supermarket']['postgresql']['data_directory']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `"#{node['supermarket']['var_directory']}/postgresql/9.3/data"`. `default['supermarket']['postgresql']['effective_cache_size']` The size of the disk cache that is used for data files. Default value: `'128MB'`. `default['supermarket']['postgresql']['enable']` Enable a service. Default value: `true`. `default['supermarket']['postgresql']['listen_address']` The connection source to which PostgreSQL is to respond. Default value: `'127.0.0.1'`. `default['supermarket']['postgresql']['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `"#{node['supermarket']['log_directory']}/postgresql"`. `default['supermarket']['postgresql']['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `default['supermarket']['postgresql']['max_connections']` The maximum number of allowed concurrent connections. Default value: `350`. `default['supermarket']['postgresql']['md5_auth_cidr_addresses']` Use to encrypt passwords using MD5 hashes. Default value: `['127.0.0.1/32', '::1/128']`. `default['supermarket']['postgresql']['port']` The port on which the service is to listen. Default value: `15432`. `default['supermarket']['postgresql']['shared_buffers']` The amount of memory that is dedicated to PostgreSQL for data caching. Default value: `"#{(node['memory']['total'].to_i / 4) / (1024)}MB"`. `default['supermarket']['postgresql']['shmall']` The total amount of available shared memory. Default value: `4194304`. `default['supermarket']['postgresql']['shmmax']` The maximum amount of shared memory. Default value: `17179869184`. `default['supermarket']['postgresql']['work_mem']` The size (in megabytes) of allowed in-memory sorting. Default value: `'8MB'`. ### Redis This configuration file has the following settings for Redis: `default['supermarket']['redis']['bind']` Bind Redis to the specified IP address. Default value: `'127.0.0.1'`. `default['supermarket']['redis']['directory']` The working directory. The default value is the recommended value. Default value: `"#{node['supermarket']['var_directory']}/redis"`. `default['supermarket']['redis']['enable']` Enable a service. Default value: `true`. `default['supermarket']['redis']['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `"#{node['supermarket']['log_directory']}/redis"`. `default['supermarket']['redis']['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `default['supermarket']['redis']['port']` The port on which the service is to listen. Default value: `'16379'`. ### Ruby on Rails This configuration file has the following settings for Ruby on Rails: `default['supermarket']['rails']['enable']` Enable a service. Default value: `true`. `default['supermarket']['rails']['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `"#{node['supermarket']['log_directory']}/rails"`. `default['supermarket']['rails']['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `default['supermarket']['rails']['port']` The port on which the service is to listen. Default value: `13000`. ### runit This configuration file has the following settings for runit: `default['supermarket']['runit']['svlogd_bin']` Default value: `"#{node['supermarket']['install_directory']}/embedded/bin/svlogd"`. ### Sentry This option is used to integrate Supermarket with the [Sentry](https://sentry.io/welcome/) error logging service: `default['supermarket']['sentry_url']` The Sentry URL that is used to send error reports. Default value: `nil`. ### Sidekiq This configuration file has the following settings for background processes that are managed by Sidekiq: `default['supermarket']['sidekiq']['concurrency']` Determines how many threads a Sidekiq process can spin up. Default value: `25`. `default['supermarket']['sidekiq']['enable']` Enable the Sidekiq service. Default value: `true`. `default['supermarket']['sidekiq']['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `"#{node['supermarket']['log_directory']}/sidekiq"`. `default['supermarket']['sidekiq']['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `default['supermarket']['sidekiq']['timeout']` The amount of time (in seconds) that Sidekiq should wait for a worker before it is terminated. Default value: `30`. ### SMTP This configuration file has the following settings for SMTP: `default['supermarket']['smtp_address']` The SMTP server address that Supermarket will use to send mail. `default['supermarket']['smtp_password']` The SMTP server password. `default['supermarket']['smtp_port']` The port on which the service is to listen. `default['supermarket']['smtp_user_name']` The user on the SMTP server. `default['supermarket']['from_email']` The default sender address of all Supermarket mailers. Default value: `nil`. ### SSL This configuration file has the following settings for SSL: `default['supermarket']['ssl']['certificate']` The SSL certificate used to verify communication over HTTPS. `default['supermarket']['ssl']['certificate_key']` The certificate key used for SSL communication. `default['supermarket']['ssl']['company_name']` The name of your company. Default value: `'My Supermarket'`. `default['supermarket']['ssl']['country_name']` The country in which your company is located. Default value: `'US'`. `default['supermarket']['ssl']['directory']` The working directory. Default value: `'/var/opt/supermarket/ssl'`. `default['supermarket']['ssl']['email_address']` The default email address for your company. Default value: `'<EMAIL>'`. `default['supermarket']['ssl']['locality_name']` The city in which your company is located. Default value: `'Seattle'`. `default['supermarket']['ssl']['openssl_bin']` Default value: `"#{node['supermarket']['install_directory']}/embedded/bin/openssl"`. `default['supermarket']['ssl']['organizational_unit_name']` The organization or group within your company that is running the Chef Infra Server. Default value: `'Operations'`. `default['supermarket']['ssl']['session_cache']` Default value: `'shared:SSL:4m'`. `default['supermarket']['ssl']['session_timeout']` Default value: `'5m'`. `default['supermarket']['ssl']['ciphers']` The list of supported cipher suites that are used to establish a secure connection. See <https://www.openssl.org/docs/man1.0.2/man1/ciphers.html> for more information. `default['supermarket']['ssl']['fips_ciphers']` The list of supported cipher suites that are used when FIPS mode is enabled. Default value `'FIPS@STRENGTH:!aNULL:!eNULL'`. `default['supermarket']['ssl']['protocols']` The SSL protocol versions that are enabled. Default value: `'TLSv1.2'`. `default['supermarket']['ssl']['state_name']` The state, province, or region in which your company is located. Default value: `'WA'`. ### StatsD This configuration file has the following settings for reporting to a StatsD server: `default['supermarket']['statsd_port']` The port on which the service is to listen. Default value: `nil`. `default['supermarket']['statsd_url']` The URL to which reporting metrics are sent. Default value: `nil`. ### Announcements Banner Starting with Supermarket 4.2 and later, users can define announcement banner text to display on the Supermarket homepage. `default['supermarket']['announcement_text']` The text string to display. ### URLs Use these settings to replace `chef.io` URLs with your own internal mirrors or alternatives. `default['supermarket']['chef_blog_url']` The URL of the Chef blog. Default value: `"https://www.#{node['supermarket']['chef_domain']}/blog"`. `default['supermarket']['chef_docs_url']` The URL of the Chef Docs site. Default value: `"https://docs.#{node['supermarket']['chef_domain']}"`. `default['supermarket']['chef_downloads_url']` The URL of the Chef downloads page. Default value: `"https://downloads.#{node['supermarket']['chef_domain']}"`. `default['supermarket']['chef_domain']` The root domain that is used by all Chef URLs. Most of the settings in this section rely upon this setting. Default value: `'chef.io'`. `default['supermarket']['chef_identity_url']` The URL that is used to interact with Chef Identity on the Chef Infra Server. Default value: `"#{node['supermarket']['chef_server_url']}/id"`. `default['supermarket']['chef_profile_url']` The URL that is used to log in to your Chef profile. Default value: `node['supermarket']['chef_server_url']`. `default['supermarket']['chef_sign_up_url']` The community signup URL. Default value: `"#{node['supermarket']['chef_server_url']}/signup?ref=community"`. `default['supermarket']['chef_www_url']` The Chef website URL. Default value: `"https://www.#{node['supermarket']['chef_domain']}"`. `default['supermarket']['learn_chef_url']` The Learn Chef URL. Default value: `"https://learn.#{node['supermarket']['chef_domain']}"`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/supermarket/config_rb_supermarket/manage.rb ========= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/config_rb_manage.md) [![Link to Chef Automate documentation.] Warning Chef Manage is [deprecated](../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. Danger This documentation applies to a [deprecated product](../versions#deprecated-products-and-versions). Chef Automate includes newer out-of-the-box compliance profiles, an improved compliance scanner with total cloud scanning functionality, better visualizations, role-based access control and many other features. Chef Automate is included as part of the Workflow license agreement and is [available via subscription](https://www.chef.io/pricing/). Chef management console is a web-based interface for the Chef Infra Server that provides users a way to manage the following objects: * Nodes * Cookbooks and recipes * Roles * Stores of JSON data (data bags), including encrypted data * Environments * Searching of indexed data * User accounts and user data for the individuals who have permission to log on to and access the Chef server The manage.rb file is the default configuration file used by Chef management console. These settings are applied every time `chef-manage-ctl reconfigure` is run. The configuration file is located at: `/etc/chef-manage/manage.rb`. Settings -------- Warning All of the following settings should be specified without using the equals symbol (`=`). For example: ``` chef_documentation_url 'https://docs.chef.io' ``` This configuration file has the following settings: `backbone_paginator_timeout` The amount of time (in milliseconds) after which search requests made via the web client will timeout and cause an error. Default value: `120000`. `chef_documentation_url` The URL at which documentation for Chef is located. Default value: `https://docs.chef.io`. `disable_sign_up` Use to disable sign-up and only allow sign-in. Default value: `false`. `email_from_address` The email address from which Chef Infra Server notifications are sent. Default value: `'Chef Notifications <<EMAIL>>'`. `events.port` The port on which the events services run. Default value: `11001`. `logging.chef_log_level` The log level used for requests to the Chef Infra Server from the web application. Default value: `info`. `logging.log_level` The log level for Ruby on Rails services. Default value: `info`. `max_login_failures` The the maximum number of failed login attempts allowed before the user must use the password reset link to reset their password (has no effect when using external authentication/LDAP). Default value: `7`. `nginx_addon_prefix` The prefix used by Chef management console. Default value: `30`. `org_creation_enabled` Whether or not users can create new organizations from Chef management console. Default value: `true`. `platform.user` The name of the privileged user that manages requests to the Chef Infra Server. Default value: `'pivotal'`. `public_port` The port on which the external load balancer will listen. Default value: `443`. `recaptcha.enabled` Enable reCAPTCHA for the sign-up page. Default value: `false`. `recaptcha.fail_open` If the reCAPTCHA service cannot be reached, allow to sign-up? Default value: `true`. `recaptcha.verify_url` Verify-URL of reCAPTCHA service to be used. Default value: `https://www.google.com/recaptcha/api/siteverify`. `recaptcha.site_key` The Site Key received from reCAPTCHA. `recaptcha.secret_key` The Secret Key received from reCAPTCHA. `redis.host` The host on which Redis runs. Default value: `localhost`. `redis.port` The port on which Redis listens. Default value: `11002`. `redis.url` The URL used by Redis. Default value: `redis://#{redis.host}:#{redis.port}/0`. `runit_timeout` The amount of time (in seconds) to wait before timing out. Default value: `30`. `secret_token` The secret token used by Ruby on Rails to prevent session tampering. See: <http://guides.rubyonrails.org/security.html#session-storage>. Default value: **generated**. To override the default value, use the [Secrets Management](../ctl_chef_server/index#ctl-chef-server-secrets-management) commands: `chef-server-ctl set-secret manage secret_token`. `services['opscode-manage-events'].enable` Use to enable the `opscode-manage-events` service. Default value: `true`. `services['opscode-manage-webapp'].enable` Use to enable the `opscode-manage-webapp` service. Default value: `true`. `services['opscode-manage-worker'].enable` Use to enable the `opscode-manage-worker` service. Default value: `true`. `session_timeout` The amount of time (in minutes) of inactivity before a user is logged out. When not set (or set to 0), a browser session will not have a timed expiration and will expire when the browser session ends, quits, or when the computer restarts, or when the absolute session time limit is hit (see `session_timeout_absolute`). Default value: `1440` (one day). `session_timeout_absolute` The amount of time (in minutes) after which a user will be logged out, regardless of activity. When not set (or set to 0), a browser session will not have a timed expiration unless a session is inactive longer than the session time limit (see `session_timeout`). Default value: `10080` (one week). `sign_in_page_message` A message to display on the sign-in page. If present, the message will show up in a box on the sign in page. Any valid HTML is allowed here. Default value: `nil`. `ssl_verify_mode` Enable or disable SSL verification for the connection to the Chef Infra Server. Valid settings: `:verify_none` and `:verify_peer`. Default value: `:verify_none` `trusted_certs_dir` Path to a directory containing trusted SSL certificates for verification when connecting to the Infra Server. Most common setting: `"/etc/chef/trusted_certs"` Default value: `""` `support_email_address` The email address used to send feedback. Default value: `<EMAIL>`. `support_site_url` The URL at which links to Chef support are located. Default value: `http://chef.io/support`. `support_tickets_url` The URL at which Chef support tickets are created. Default value: `https://chef.io/support/tickets`. `webapp.backlog` The size of the backlog. Default value: `1024`. `webapp.listen` The port on which Chef management console services listen. Default value: `{ '127.0.0.1:#{port}' }`. `webapp.port` The port on which Chef management console services run. Default value: `9462`. `webapp.tcp_nodelay` Enable the Nagle buffering algorithm. Default value: `true`. `webapp.worker_processes` The number of allowed worker processes. Default value: `node['cpu.total'].to_i`. `webapp.worker_timeout` The amount of time (in seconds) that a worker can be silent before it is killed and restarted. Default value: `3600`. Web UI Private Key ------------------ Chef Manage uses the Web UI private key for signing requests sent to the Chef Infra Server. The key is subject to Chef server’s [Secrets Management](../ctl_chef_server/index#ctl-chef-server-secrets-management), and will be stored in `/etc/opscode/private-chef-secrets.json`. Any run of `chef-server-ctl reconfigure` will ensure the key exists and is stored without any additional steps. To verify that the key is stored and ready to use by manage, run: ``` chef-server-ctl show-secret chef-server webui_key -----BEGIN RSA PRIVATE KEY----- <KEY> ... -----END RSA PRIVATE KEY----- ``` Example ------- The following example shows how the settings look when added to the configuration file: ``` chef_documentation_url '' disable_sign_up false events.port 11001 logging.chef_log_level 'info' logging.log_level 'info' nginx_addon_prefix 30 platform.user 'pivotal' public_port 443 redis.host 'localhost' redis.port 11002 # redis.url derived from redis.host and redis.port runit_timeout 30 services['opscode-manage-events'].enable true services['opscode-manage-webapp'].enable true services['opscode-manage-worker'].enable true support_email_address '<EMAIL>' support_site_url 'http://chef.io/support' support_tickets_url 'https://chef.io/support/tickets' webapp.backlog 1024 # webapp.listen derived from webapp.port webapp.port 9462 webapp.tcp_nodelay true webapp.worker_processes 2 webapp.worker_timeout 3600 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/config_rb_manage/Supermarket Backup and Restore ============================== [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/supermarket_backup_restore.md) Periodic backups of Supermarket data are an essential part of managing and maintaining a healthy configuration, and to help ensure that important data can be restored if required. In a typical installation of Supermarket, both the cookbook store and the database need to be backed up on a regular basis. Backup ------ ### Cookbook Backup If Supermarket is not configured to use AWS S3 storage for cookbooks, then the local cookbook storage location on the Supermarket server will need to be backed up. The default location is: `/var/opt/supermarket/data/cookbook_versions`. For example, a cookbook backup command: ``` cd /var/opt/supermarket/data/ tar cvzf ~/supermarket_cookbook_versions.tar.gz cookbook_versions ``` ### Database Backup A database export can be made in several formats. For example, a database export in a .dump format can be made with the following syntax: ``` /opt/supermarket/embedded/bin/pg_dump --host localhost --username supermarket --dbname supermarket --port 15432 --format c --blobs --verbose --file ~/supermarket_database_backup.dump ``` where, in a typical installation: * `/opt/supermarket/embedded/bin/pg_dump` is the path to the database export utility included in the Supermarket installation * `localhost` may alternatively be 127.0.0.1 * `15432` is the PostgreSQL port number, which may need to be modified * `--format c` sets the output to PostgreSQL’s “custom” binary file format Be sure to update the various local values in the `pg_dump` command as necessary to match your infrastructure. For documentation about the pg_dump utility, see the [pgdump](https://www.postgresql.org/docs/9.3/app-pgdump.html) documentation. To find local variables, look at `/etc/supermarket/supermarket-running.json`. This file lives next to `supermarket.rb` and `supermarket.json` where their configuration is set. `supermarket-running.json` contains the final values the system is operating with after running `sudo supermarket-ctl reconfigure`. There’s a “database” key in `supermarket-running.json`: ``` { "supermarket": { ... "database": { "user": "supermarket", "name": "supermarket", "host": "127.0.0.1", "port": "15432", "pool": "30", "extensions": { "plpgsql": true, "pg_trgm": true }, "password": "sup3rs3cr3t" }, ... } ``` Restore ------- ### Cookbook Restore When restoring cookbooks, **make sure the cookbook directory is writable by the Supermarket user.** For example, to restore your cookbook files, run: ``` cd /var/opt/supermarket/data/ tar xvzf /supermarket_cookbook_versions.tar.gz ``` ### Database Restore Note The restore does not support transferring backups across different versions of Supermarket. Backups taken must be restored to the same version of Supermarket that was in use when they were created. For example, to restore a backup in a .dump format, run: ``` pg_restore --host localhost --port 15432 --clean --no-acl --no-owner --dbname supermarket_production --verbose supermarket_database_backup.dump ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/supermarket/supermarket_backup_restore/Chef Manage =========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/manage.md) [![Link to Chef Automate documentation.] Warning Chef Manage is [deprecated](../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. Warning Chef Automate 2 does not deploy Chef Manage alongside Chef Infra Server. The Chef management console enables the management of nodes, data bags, roles, environments, and cookbooks by using a web user interface. In addition, access to nodes, data bags, roles, environments, and cookbooks is configurable using role-based access control (RBAC). Nodes ----- A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. The Chef management console provides ways for users to [delete nodes and reset their private keys](../server_manage_nodes/index#manage), [edit node attributes](../server_manage_nodes/index#node-attributes), [manage the run-lists](../server_manage_nodes/index#run-lists), [configure user and group permissions](../server_manage_nodes/index#permissions), and [manage tags](../server_manage_nodes/index#manage-tags). ![image] ### Search Search indexes allow queries to be made for any type of data that is indexed by the Chef Infra Server, including data bags (and data bag items), environments, nodes, and roles. A defined query syntax is used to support search patterns like exact, wildcard, range, and fuzzy. A search is a full-text query that can be done from several locations, including from within a recipe, by using the `search` subcommand in knife, the `search` method in the Chef Infra Language, the search box in the Chef management console, and by using the `/search` or `/search/INDEX` endpoints in the Chef Infra Server API. The search engine is based on Elasticsearch and is run from the Chef Infra Server. Note The syntax for search queries in the Chef management console is identical to the syntax for search queries used with knife, the command line tool used to manage objects on the Chef Infra Server. #### Query Syntax A search query is comprised of two parts: the key and the search pattern. A search query has the following syntax: ``` key:search_pattern ``` where `key` is a field name that is found in the JSON description of an indexable object on the Chef Infra Server (a role, node, client, environment, or data bag) and `search_pattern` defines what will be searched for, using one of the following search patterns: exact, wildcard, range, or fuzzy matching. Both `key` and `search_pattern` are case-sensitive; `key` has limited support for multiple character wildcard matching using an asterisk ("*") (and as long as it is not the first character). #### Keys A field name/description pair is available in the JSON object. Use the field name when searching for this information in the JSON object. Any field that exists in any JSON description for any role, node, Chef Infra Client, environment, or data bag can be searched. ##### Nested Fields A nested field appears deeper in the JSON data structure. For example, information about a network interface might be several layers deep: `node['network']['interfaces']['en1']`. When nested fields are present in a JSON structure, Chef Infra Client will extract those nested fields to the top-level, flattening them into compound fields that support wildcard search patterns. By combining wildcards with range-matching patterns and wildcard queries, it is possible to perform very powerful searches, such as using the vendor part of the MAC address to find every node that has a network card made by the specified vendor. Consider the following snippet of JSON data: ``` {"network": [ //snipped... "interfaces", {"en1": { "number": "1", "flags": [ "UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST" ], "addresses": { "fe80::fa1e:dfff:fed8:63a2": { "scope": "Link", "prefixlen": "64", "family": "inet6" }, "f8:1e:df:d8:63:a2": { "family": "lladdr" }, "192.0.2.0": { "netmask": "255.255.255.0", "broadcast": "192.168.0.255", "family": "inet" } }, "mtu": "1500", "media": { "supported": { "autoselect": { "options": [ ] } }, "selected": { "autoselect": { "options": [ ] } } }, "type": "en", "status": "active", "encapsulation": "Ethernet" }, //snipped... ``` Before this data is indexed on the Chef Infra Server, the nested fields are extracted into the top level, similar to: ``` "broadcast" => "192.168.0.255", "flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"] "mtu" => "1500" ``` which allows searches like the following to find data that is present in this node: ``` node "broadcast:192.168.0.*" ``` or: ``` node "mtu:1500" ``` or: ``` node "flags:UP" ``` This data is also flattened into various compound fields, which follow the same pattern as the JSON hierarchy and use underscores (`_`) to separate the levels of data, similar to: ``` # ...snip... "network_interfaces_en1_addresses_192.0.2.0_broadcast" => "192.168.0.255", "network_interfaces_en1_addresses_fe80::fa1e:tldr_family" => "inet6", "network_interfaces_en1_addresses" => ["fe80::fa1e:tldr","f8:1e:df:tldr","192.0.2.0"] # ...snip... ``` which allows searches like the following to find data that is present in this node: ``` node "network_interfaces_en1_addresses:192.0.2.0" ``` This flattened data structure also supports using wildcard compound fields, which allow searches to omit levels within the JSON data structure that are not important to the search query. In the following example, an asterisk (`*`) is used to show where the wildcard can exist when searching for a nested field: ``` "network_interfaces_*_flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"] "network_interfaces_*_addresses" => ["fe80::fa1e:dfff:fed8:63a2", "192.0.2.0", "f8:1e:df:d8:63:a2"] "network_interfaces_en0_media_*" => ["autoselect", "none", "1000baseT", "10baseT/UTP", "100baseTX"] "network_interfaces_en1_*" => ["1", "UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST", "fe80::fa1e:dfff:fed8:63a2", "f8:1e:df:d8:63:a2", "192.0.2.0", "1500", "supported", "selected", "en", "active", "Ethernet"] ``` For each of the wildcard examples above, the possible values are shown contained within the brackets. When running a search query, the query syntax for wildcards is to simply omit the name of the node (while preserving the underscores), similar to: ``` network_interfaces__flags ``` This query will search within the `flags` node, within the JSON structure, for each of `UP`, `BROADCAST`, `SMART`, `RUNNING`, `SIMPLEX`, and `MULTICAST`. #### About Patterns A search pattern is a way to fine-tune search results by returning anything that matches some type of incomplete search query. There are four types of search patterns that can be used when searching the search indexes on the Chef Infra Server: exact, wildcard, range, and fuzzy. ##### Exact Matching An exact matching search pattern is used to search for a key with a name that exactly matches a search query. If the name of the key contains spaces, quotes must be used in the search pattern to ensure the search query finds the key. The entire query must also be contained within quotes, so as to prevent it from being interpreted by Ruby or a command shell. The best way to ensure that quotes are used consistently is to quote the entire query using single quotes (' ‘) and a search pattern with double quotes (" “). ##### Wildcard Matching A wildcard matching search pattern is used to query for substring matches that replace zero (or more) characters in the search pattern with anything that could match the replaced character. There are two types of wildcard searches: * A question mark (`?`) can be used to replace exactly one character (as long as that character is not the first character in the search pattern) * An asterisk (`*`) can be used to replace any number of characters (including zero) ##### Range Matching A range matching search pattern is used to query for values that are within a range defined by upper and lower boundaries. A range matching search pattern can be inclusive or exclusive of the boundaries. Use square brackets ("[ ]") to denote inclusive boundaries and curly braces ("{ }") to denote exclusive boundaries and with the following syntax: ``` boundary TO boundary ``` where `TO` is required (and must be capitalized). ##### Fuzzy Matching A fuzzy matching search pattern is used to search based on the proximity of two strings of characters. An (optional) integer may be used as part of the search query to more closely define the proximity. A fuzzy matching search pattern has the following syntax: ``` "search_query"~edit_distance ``` where `search_query` is the string that will be used during the search and `edit_distance` is the proximity. A tilde ("~") is used to separate the edit distance from the search query. #### About Operators An operator can be used to ensure that certain terms are included in the results, are excluded from the results, or are not included even when other aspects of the query match. Searches can use the following operators: | Operator | Description | | --- | --- | | `AND` | Use to find a match when both terms exist. | | `OR` | Use to find a match if either term exists. | | `NOT` | Use to exclude the term after `NOT` from the search results. | Operators must be in ALL CAPS. Parentheses can be used to group clauses and to form sub-queries. Warning Using `AND NOT` together may trigger an error. For example: ``` ERROR: knife search failed: invalid search query: 'datacenter%3A123%20AND%20NOT%20hostname%3Adev-%20AND%20NOT%20hostanem%3Asyslog-' Parse error at offset: 38 Reason: Expected one of \ at line 1, column 42 (byte 42) after AND ``` Use `-` instead of `NOT`. For example: ``` knife search sample "id:foo AND -id:bar" ``` #### Special Characters A special character can be used to fine-tune a search query and to increase the accuracy of the search results. The following characters can be included within the search query syntax, but each occurrence of a special character must be escaped with a backslash (`\`), also (`/`) must be escaped against the Elasticsearch: ``` + - && | | ! ( ) { } [ ] ^ " ~ * ? : \ / ``` For example: ``` \(1\+1\)\:2 ``` Policy ------ Policy maps business and operational requirements, process, and workflow to settings and objects stored on the Chef Infra Server: * Roles define server types, such as “web server” or “database server” * Environments define process, such as “dev”, “staging”, or “production” * Certain types of data—passwords, user account data, and other sensitive items—can be placed in data bags, which are located in a secure sub-area on the Chef Infra Server that can only be accessed by nodes that authenticate to the Chef Infra Server with the correct SSL certificates * The cookbooks (and cookbook versions) in which organization-specific configuration policies are maintained The Chef management console provides ways for users to manage [data bags](../server_manage_data_bags/index), [environments](../server_manage_environments/index), [roles](../server_manage_roles/index), [cookbooks](../server_manage_cookbooks/index), [clients](../server_manage_clients/index), and [managing tags](../server_manage_nodes/index#manage-tags.html). ![image] Admin ----- Organizations, users, and groups can be managed from the Chef management console, including role-based access control for any user and group to any of the objects saved to the Chef Infra Server. The Chef Infra Server uses role-based access control (RBAC) to restrict access to objects—nodes, environments, roles, data bags, cookbooks, and so on. This ensures that only authorized user and/or Chef Infra Client requests to the Chef Infra Server are allowed. Access to objects on the Chef Infra Server is fine-grained, allowing access to be defined by object type, object, group, user, and organization. The Chef Infra Server uses permissions to define how a user may interact with an object, after they have been authorized to do so. ![image] Install Chef Manage ------------------- The `install` subcommand downloads packages from <https://packages.chef.io> by default. For systems that are not behind a firewall (and have connectivity to <https://packages.chef.io>), these packages can be installed as described below. 1. Install add-ons Install Chef Manage with: ``` sudo chef-server-ctl install chef-manage ``` 2. Reconfigure the server ``` sudo chef-server-ctl reconfigure ``` 3. Reconfigure add-ons Reconfigure Chef Manage with: ``` sudo chef-manage-ctl reconfigure ``` Finally, accept the [Chef License](../chef_license/index): ``` sudo chef-manage-ctl reconfigure --accept-license ``` ### Chef Manage Local Installation Use the `install` subcommand with the `--path` option to install the Chef Manage (`chef-manage`) add-on for Chef Infra Server. ``` sudo chef-server-ctl install PACKAGE_NAME --path /path/to/package/directory ``` For example: ``` sudo chef-server-ctl install chef-manage --path /root/packages ``` The `chef-server-ctl` command will install the first `chef-manage` package found in the `/root/packages` directory. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/manage/Active Directory and LDAP ========================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/server_ldap.md) The Chef Infra Server supports Active Directory and LDAP authentication, which enables users to log in to the Chef Infra Server using their corporate credential and the Manage interface. Without the Manage interface add-on installed, there is no need to enable the Chef Infra Server LDAP functionality. LDAP is not used with Supermarket logins, nor with any Chef Infra Client related authentication. Configure LDAP -------------- The Chef Infra Server supports using Active Directory or LDAP for any user that has an email address in the LDAP directory. This allows those users to log in to the Chef Infra Server by using their corporate credentials instead of having a separate username and password. Warning The following attributes **MUST** be in the user LDAP record: * `mail:` * `sAMAccountName:` or `uid:` The following attributes **SHOULD** be in the user LDAP record: * `displayname:` * `givenname:` * `sn:` * `c:` * `l:` To configure the Chef Infra Server to use Active Directory or LDAP do the following: 1. Install the Chef management console (if it is not already). 2. Add the following settings to the `/etc/opscode/chef-server.rb` file. These settings must be added to the `chef-server.rb` file on each machine in the Chef Infra Server frontend deployment of a High Availability installation as well as on Chef servers in a standalone installation. Warning The following settings **MUST** be in the config file for LDAP authentication to Active Directory to work: * `base_dn` * `bind_dn` * `group_dn` * `host` If those settings are missing, you will get authentication errors and be unable to proceed. This configuration file has the following settings for `ldap`: `ldap['base_dn']` The root LDAP node under which all other nodes exist in the directory structure. For Active Directory, this is typically `cn=users` and then the domain. For example: ``` 'OU=Employees,OU=Domain users,DC=example,DC=com' ``` Default value: `nil`. `ldap['bind_dn']` The distinguished name used to bind to the LDAP server. The user the Chef Infra Server will use to perform LDAP searches. This is often the administrator or manager user. This user needs to have read access to all LDAP users that require authentication. The Chef Infra Server must do an LDAP search before any user can log in. Many Active Directory and LDAP systems do not allow an anonymous bind. If anonymous bind is allowed, leave the `bind_dn` and `bind_password` settings blank. If anonymous bind is not allowed, a user with `READ` access to the directory is required. This user must be specified as an LDAP distinguished name similar to: ``` 'CN=user,OU=Employees,OU=Domainuser,DC=example,DC=com' ``` Note If you need to escape characters in a distinguished name, such as when using Active Directory, they must be [escaped with a backslash escape character](https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx). ``` 'CN=example\\user,OU=Employees,OU=Domainuser,DC=example,DC=com' ``` Default value: `nil`. `ldap['bind_password']` Legacy configuration for the password of the binding user. The password for the user specified by `ldap['bind_dn']`. Leave this value and `ldap['bind_dn']` unset if anonymous bind is sufficient. Default value: `nil`. As of Chef Server 12.14, this is no longer the preferred command. Please use `chef-server-ctl set-secret ldap bind_password` from the [Secrets Management](../ctl_chef_server#ctl-chef-server-secrets-management) commands. ``` chef-server-ctl set-secret ldap bind_password Enter ldap bind_password: (no terminal output) Re-enter ldap bind_password: (no terminal output) ``` Remove a set password via ``` chef-server-ctl remove-secret ldap bind_password ``` `ldap['group_dn']` The distinguished name for a group. When set to the distinguished name of a group, only members of that group can log in. This feature filters based on the `memberOf` attribute and only works with LDAP servers that provide such an attribute. In OpenLDAP, the `memberOf` overlay provides this attribute. For example, if the value of the `memberOf` attribute is `CN=abcxyz,OU=users,DC=company,DC=com`, then use: ``` ldap['group_dn'] = 'CN=abcxyz,OU=users,DC=company,DC=com' ``` `ldap['host']` The name (or IP address) of the LDAP server. The hostname of the LDAP or Active Directory server. Be sure the Chef Infra Server is able to resolve any host names. Default value: `ldap-server-host`. `ldap['login_attribute']` The LDAP attribute that holds the user’s login name. Use to specify the Chef Infra Server user name for an LDAP user. Default value: `sAMAccountName`. `ldap['port']` An integer that specifies the port on which the LDAP server listens. The default value is an appropriate value for most configurations. Default value: `389` or `636` when `ldap['encryption']` is set to `:simple_tls`. `ldap['ssl_enabled']` Cause the Chef Infra Server to connect to the LDAP server using SSL. Default value: `false`. Must be `false` when `ldap['tls_enabled']` is `true`. Note It’s recommended that you enable SSL for Active Directory. Note Previous versions of the Chef Infra Server used the `ldap['ssl_enabled']` setting to first enable SSL, and then the `ldap['encryption']` setting to specify the encryption type. These settings are deprecated. `ldap['system_adjective']` A descriptive name for the login system that is displayed to users in the Chef Infra Server management console. If a value like “corporate” is used, then the Chef management console user interface will display strings like “the corporate login server”, “corporate login”, or “corporate password.” Default value: `AD/LDAP`. Warning This setting is **not** used by the Chef Infra Server. It is used only by the Chef management console. `ldap['timeout']` The amount of time (in seconds) to wait before timing out. Default value: `60000`. `ldap['tls_enabled']` Enable TLS. When enabled, communication with the LDAP server is done via a secure SSL connection on a dedicated port. When `true`, `ldap['port']` is also set to `636`. Default value: `false`. Must be `false` when `ldap['ssl_enabled']` is `true`. Note Previous versions of the Chef Infra Server used the `ldap['ssl_enabled']` setting to first enable SSL, and then the `ldap['encryption']` setting to specify the encryption type. These settings are deprecated. Note If the chef-server.rb file does not exist, create a file called `chef-server.rb` and put it in the `/etc/opscode/` directory. 3. Reconfigure the Chef Infra Server and the Chef management console (standalone and frontend group members of a High Availabilty installation): ``` chef-server-ctl reconfigure ``` At this point, all users should be able to use their Active Directory or LDAP usernames and passwords to log in to the Chef Infra Server. Test LDAP Connectivity ---------------------- Use `ldapsearch` to test the ability of the Chef Infra Server to use Active Directory or LDAP. First, translate the Chef Infra Server LDAP settings into `ldapsearch` parameters: | Chef Infra Server Setting | `ldapsearch` Parameter | | --- | --- | | `ldap['host']` and `ldap['port']` | `-H [HOST:PORT]` | | `ldap['bind_dn']` | `-D [BIND_DN]` | | `ldap['bind_password']` | `-W`; `ldapsearch` will prompt for this parameter | | `ldap['base_dn']` | `-b [BASE_DN]` | | `ldap['login_attribute']` | Defaults to `SAMAccountName` | And then from a front end machine (in a high availability or tiered configuration) or from the Chef Infra Server in a standalone configuration, run the following command. Be sure to replace the uppercase placeholders with the values for your organization: ``` ldapsearch -LLL -H ldap://HOST:PORT -b 'BASE_DN' -D 'BIND_DN' -W '(LOGIN_ATTRIBUTE=YOUR_LDAP_ACCOUNT_USERNAME)' ``` For example: ``` ldapsearch -LLL -H ldap://win-ad1.chef.co:389 -b 'OU=Employees,OU=Domain users,DC=opscodecorp,DC=com' -D 'CN=<NAME>,OU=Employees,OU=Domain users,DC=opscodecorp,DC=com' -W '(sAMAccountName=rforster)' ``` Output similar to the following is returned: ``` ldapsearch -LLL -H ldap://win-ad1.chef.co:389 -b 'OU=Employees,OU=Domain users,DC=opscodecorp,DC=com' -D 'CN=<NAME>,OU=Employees,OU=Domain users,DC=opscodecorp,DC=com' -W '(sAMAccountName=rforster)' Enter LDAP Password: dn: CN=<NAME>,OU=Employees,OU=Domain users,DC=opscodecorp,DC=com objectClass: top objectClass: person objectClass: organizationalPerson objectClass: user cn: <NAME> sn: Forster c: 0 givenName: Robert distinguishedName: CN=<NAME>,OU=Employees,OU=Domain users,DC=opscodecorp,DC =com ``` Note The `ldapsearch` command may need to be installed on the platform. It is not included as part of the Chef Infra Server package. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server_ldap/Manage Cookbooks ================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/server_manage_cookbooks.md) [![Link to Chef Automate documentation.] Warning Chef Manage is [deprecated](../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. Note This topic is about using the Chef management console to manage cookbooks. A cookbook is the fundamental unit of configuration and policy distribution in Chef Infra. A cookbook defines a scenario and contains everything that is required to support that scenario: * Recipes that specify which Chef Infra built-in resources to use, as well as the order in which they are to be applied * Attribute values, which allow environment-based configurations such as `dev` or `prodution`. * Custom Resources for extending Chef Infra beyond the built-in resources. * Files and Templates for distributing information to systems. * Custom Ohai Plugins for extending system configuration collection beyond the Ohai defaults. * The `metadata.rb` file, which describes the cookbook itself and any dependencies it may have. Manage ------ Cookbooks can be viewed from the Chef management console web user interface. Cookbooks are managed using knife. ### View Cookbook Details To view cookbook details: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Cookbooks**. 4. Select a cookbook. 5. Click the **Details** tab: ![image] Cookbook Files -------------- A cookbook can contain the following types of files: | File Type | Description | | --- | --- | | Attributes | An attribute can be defined in a cookbook (or a recipe) and then used to override the default settings on a node. When a cookbook is loaded during a Chef Infra Client run, these attributes are compared to the attributes that are already present on the node. Attributes that are defined in attribute files are first loaded according to cookbook order. For each cookbook, attributes in the `default.rb` file are loaded first, and then additional attribute files (if present) are loaded in lexical sort order. When the cookbook attributes take precedence over the default attributes, Chef Infra Client applies those new settings and values during a Chef Infra Client run on the node. | | Files | Use the **cookbook_file** resource to transfer files from a sub-directory of `COOKBOOK_NAME/files/` to a specified path located on a host that is running Chef Infra Client. The file is selected according to file specificity, which allows different source files to be used based on the hostname, host platform (operating system, distro, or as appropriate), or platform version. Files that are located in the `COOKBOOK_NAME/files/default` sub-directory may be used on any platform. | | Libraries | A library allows arbitrary Ruby code to be included in a cookbook. The most common use for libraries is to write helpers that are used throughout recipes and custom resources. A library file is a Ruby file that is located within a cookbook’s `/libraries` directory. Because a library is built using Ruby, anything that can be done with Ruby can be done in a library file, including advanced functionality such as extending built-in Chef classes. | | Recipes | A recipe is the most fundamental configuration element within the organization. A recipe:* Is authored using Ruby, which is a programming language designed to read and behave in a predictable manner * Is mostly a collection of [resources](../resources/index), defined using patterns (resource names, attribute-value pairs, and actions); helper code is added around this using Ruby, when needed * Must define everything that is required to configure part of a system * Must be stored in a cookbook * May be included in another recipe * May use the results of a search query and read the contents of a data bag (including an encrypted data bag) * May have a dependency on one (or more) recipes * Must be added to a run-list before it can be used by Chef Infra Client * Is always executed in the same order as listed in a run-list | | Resources | A resource is a statement of configuration policy that:* Describes the desired state for a configuration item * Declares the steps needed to bring that item to the desired state * Specifies a resource type—such as `package`, `template`, or `service` * Lists additional details (also known as resource properties), as necessary * Are grouped into recipes, which describe working configurations | | Templates | A cookbook template is an Embedded Ruby (ERB) template that is used to dynamically generate static text files. Templates may contain Ruby expressions and statements, and are a great way to manage configuration files. Use the **template** resource to add cookbook templates to recipes; place the corresponding Embedded Ruby (ERB) template file in a cookbook’s `/templates` directory. | All of the file types that are part of any cookbook uploaded to the Chef Infra Server are visible from the Chef management console. ### Download File To download a file that is located in a cookbook: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Cookbooks**. 4. Select the file type: **Attributes**, **Definitions**, **Files**, **Recipes**, **Templates**, or **Root Files**. 5. Select a file. 6. Click **Download File**: ![image] 7. Specify the location to which the file should be saved. ### View a File To view a cookbook file: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Cookbooks**. 4. Select a cookbook. 5. Click the **Content** tab. 6. Select the file type: **Attributes**, **Definitions**, **Files**, **Recipes**, **Templates**, or **Root Files**. 7. Select a file: ![image] Permissions ----------- Permissions are used in the Chef Infra Server to define how users and groups can interact with objects on the server. Permissions are configured per-organization. The Chef Infra Server includes the following object permissions: | Permission | Description | | --- | --- | | **Delete** | Use the **Delete** permission to define which users and groups may delete an object. This permission is required for any user who uses the `knife [object] delete [object_name]` argument to interact with objects on the Chef Infra Server. | | **Grant** | Use the **Grant** permission to define which users and groups may configure permissions on an object. This permission is required for any user who configures permissions using the **Administration** tab in the Chef management console. | | **Read** | Use the **Read** permission to define which users and groups may view the details of an object. This permission is required for any user who uses the `knife [object] show [object_name]` argument to interact with objects on the Chef Infra Server. | | **Update** | Use the **Update** permission to define which users and groups may edit the details of an object. This permission is required for any user who uses the `knife [object] edit [object_name]` argument to interact with objects on the Chef Infra Server and for any Chef Infra Client to save node data to the Chef Infra Server at the conclusion of a Chef Infra Client run. | ### Set To set permissions list for a cookbook object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Cookbooks**. 4. Select a cookbook. 5. Click the **Permissions** tab. 6. For each group listed under **Name**, select or de-select the **Read**, **Update**, **Delete**, and **Grant** permissions. ### Update To update the permissions list for a cookbook object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Cookbooks**. 4. Select a cookbook. 5. Click the **Permissions** tab. 6. Click the **+ Add** button and enter the name of the user or group to be added. 7. Select or de-select **Read**, **Update**, **Delete**, and **Grant** to update the permissions list for the user or group. ### View To view permissions for a cookbook object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Cookbooks**. 4. Select a cookbook. 5. Click the **Permissions** tab. 6. Set the appropriate permissions: **Delete**, **Grant**, **Read**, and/or **Update**. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server_manage_cookbooks/Manage Data Bags ================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/server_manage_data_bags.md) [![Link to Chef Automate documentation.] Warning Chef Manage is [deprecated](../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. Note This topic is about using the Chef management console to manage data bags. Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. Manage ------ Data bags can be managed from the Chef management console web user interface. ### Add Data Bag To add a data bag: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Data Bags**. 4. Click **Create**. 5. In the **Create a Data Bag** dialog box, enter the name of the data bag. ![image] 6. Click **Create Data Bag**. ### Delete Data Bag To delete a data bag: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Data Bags**. 4. Select a data bag. 5. Click **Delete**. ![image] Manage Items ------------ A data bag is a container of related data bag items, where each individual data bag item is a JSON file. knife can load a data bag item by specifying the name of the data bag to which the item belongs and then the filename of the data bag item. The only structural requirement of a data bag item is that it must have an `id`: ``` { /* This is a supported comment style */ // This style is also supported "id": "ITEM_NAME", "key": "value" } ``` where * `key` and `value` are the `key:value` pair for each additional attribute within the data bag item * `/* ... */` and `// ...` show two ways to add comments to the data bag item ### Add Item To add a data bag item: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Data Bags**. 4. Select a data bag. 5. Click **Create Item**. 6. In the **Create a Data Bag Item** dialog box, enter the data bag identifier, and then JSON data that defines the data bag item. ![image] 7. Click **Create Data Bag Item**. ### Delete Item To delete a data bag item: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Data Bags**. 4. Select a data bag. 5. Select the **Items** tab. 6. Select an item. 7. Click **Delete**. ![image] ### Edit Item To edit a data bag item: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Data Bags**. 4. Select a data bag. 5. Select the **Items** tab. 6. Select an item. 7. Click **Edit**. ![image] 8. Make your changes. 9. Click **Save Item**. ### View Item To view data bag items for a data bag: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Data Bags**. 4. Select a data bag. 5. Select the **Items** tab. Manage Permissions ------------------ Permissions are used in the Chef Infra Server to define how users and groups can interact with objects on the server. Permissions are configured per-organization. The Chef Infra Server includes the following object permissions: | Permission | Description | | --- | --- | | **Delete** | Use the **Delete** permission to define which users and groups may delete an object. This permission is required for any user who uses the `knife [object] delete [object_name]` argument to interact with objects on the Chef Infra Server. | | **Grant** | Use the **Grant** permission to define which users and groups may configure permissions on an object. This permission is required for any user who configures permissions using the **Administration** tab in the Chef management console. | | **Read** | Use the **Read** permission to define which users and groups may view the details of an object. This permission is required for any user who uses the `knife [object] show [object_name]` argument to interact with objects on the Chef Infra Server. | | **Update** | Use the **Update** permission to define which users and groups may edit the details of an object. This permission is required for any user who uses the `knife [object] edit [object_name]` argument to interact with objects on the Chef Infra Server and for any Chef Infra Client to save node data to the Chef Infra Server at the conclusion of a Chef Infra Client run. | ### Set To set permissions list for a data bag object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Data Bags**. 4. Select a data bag. 5. Click the **Permissions** tab. 6. For each group listed under **Name**, select or de-select the **Read**, **Update**, **Delete**, and **Grant** permissions. ### Update To update the permissions list for a data bag object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Data Bags**. 4. Select a data bag. 5. Click the **Permissions** tab. 6. Click the **+ Add** button and enter the name of the user or group to be added. 7. Select or de-select **Read**, **Update**, **Delete**, and **Grant** to update the permissions list for the user or group. ### View To view permissions for a data bag object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Data Bags**. 4. Select a data bag. 5. Click the **Permissions** tab. 6. Set the appropriate permissions: **Read**, **Update**, **Delete**, and **Grant**. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server_manage_data_bags/chef-manage-ctl (executable) ============================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/ctl_manage.md) [![Link to Chef Automate documentation.] Warning Chef Manage is [deprecated](../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. Danger This documentation applies to a [deprecated product](../versions#deprecated-products-and-versions). Chef Automate includes newer out-of-the-box compliance profiles, an improved compliance scanner with total cloud scanning functionality, better visualizations, role-based access control and many other features. Chef Automate is included as part of the Workflow license agreement and is [available via subscription](https://www.chef.io/pricing/). The Chef management console includes a command-line utility named `chef-manage-ctl`. This command-line tool is used to reconfigure, cleanse (reset the Chef management console to initial configuration settings), and uninstall the Chef management console. help ---- The `help` subcommand is used to print a list of all available `chef-manage-ctl` commands. This subcommand has the following syntax: ``` chef-manage-ctl help ``` reconfigure ----------- The `reconfigure` subcommand is used when changes are made to the manage.rb file to reconfigure the server. When changes are made to the manage.rb file, they will not be applied to the Chef management console configuration until after this command is run. This subcommand has the following syntax: ``` chef-manage-ctl reconfigure ``` show-config ----------- The `show-config` subcommand is used to view the configuration that will be generated by the `reconfigure` subcommand. This command is most useful in the early stages of a deployment to ensure that everything is built properly prior to installation. This subcommand has the following syntax: ``` chef-manage-ctl show-config ``` uninstall --------- The `uninstall` subcommand is used to manage the hooks between runit and `sysvinit` or `upstart`. This subcommand does not [uninstall the Chef management console](../uninstall/index#chef-manage) or remove `.rpm` or `.deb` files. This subcommand has the following syntax: ``` chef-manage-ctl uninstall ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ctl_manage/Configuring for SAML Authentication =================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/server_configure_saml.md) [![Link to Chef Automate documentation.] Warning Chef Manage is [deprecated](../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. Chef Manage can support logging in users via SAML authentication. In order to do so, there must be a Chef Automate Server that is configured to act as a SAML Identity Provider (IdP). When the Chef Automate Server is configured to do so, it will provide an OpenID Connect (OIDC) protocol end-point that Chef Manage can use to initiate authentication. Configuring Chef Manage ----------------------- To configure the Chef Infra Server management console, first add the following code to `/etc/chef-manage/manage.rb`: ``` saml.enabled true saml.issuer_url '<AUTOMATE OIDC ENDPOINT>' ``` Second, store your OIDC client credentials with using the [Secrets Management](../ctl_chef_server/index#ctl-chef-server-secrets-management) commands: ``` chef-server-ctl set-secret saml client_id '<CLIENT ID>' chef-server-ctl set-secret saml client_secret '<CLIENT SECRET>' ``` The `issuer_url` property should be set to something like `'https://<yourChefAutomateDomain>/api/v0'`. Also, the `client_id` must be known to the Chef Automate server. For development purposes only, you may also need to turn off the TLS verification for the OIDC client by adding ``` saml.verify_tls false ``` to your Chef Manage configuration. Finally, run `chef-manage-ctl reconfigure` to apply these settings. Warning You cannot have both LDAP and SAML authentication enabled at the same time. If you do, the reconfigure will fail with an appropriate error message. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server_configure_saml/Manage Nodes ============ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/server_manage_nodes.md) [![Link to Chef Automate documentation.] Warning Chef Manage is [deprecated](../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. Note This topic is about using the Chef management console to manage nodes. A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. Manage ------ Nodes can be managed from the Chef management console web user interface. ### Delete To delete a node: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click **Delete**. 5. Confirm: ![Dialog box asking user if they want to delete a node.] ### Reset Key To reset the validation key for a node: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click **Edit Run List**. 5. In the **Reset Key** dialog box, confirm that the key should be regenerated and click the **Regenerate Key** button: ![Dialog box asking user to confirm that they want to delete a key.] 6. In the **Reset Key** dialog box, copy the key directly from the dialog box or click the **Download** button to download the key to your local machine: ![Dialog box showing newly generated key.] ### Search To search nodes: 1. Open the Chef management console. 2. Click **Nodes**. 3. In the search box in the upper right, enter the search query and click the search icon. ![image] 4. The results will appear in the list below. Node Attributes --------------- An attribute is a specific detail about a node. Attributes are used by Chef Infra Client to understand: * The current state of the node * What the state of the node was at the end of the previous Chef Infra Client run * What the state of the node should be at the end of the current Chef Infra Client run Attributes are defined by: * The node as saved on the Chef Infra Server * Attributes passed via JSON on the command line * Cookbooks (in attribute files and/or recipes) * Policyfiles During every Chef Infra Client run, Chef Infra Client builds the attribute list using: * Attributes passed via JSON on the command line * Data about the node collected by [Ohai](../ohai). * The node object that was saved to the Chef Infra Server at the end of the previous Chef Infra Client run. * The rebuilt node object from the current Chef Infra Client run, after it is updated for changes to cookbooks (attribute files and/or recipes) and/or Policyfiles, and updated for any changes to the state of the node itself. After the node object is rebuilt, all of the attributes are compared, and then the node is updated based on attribute precedence. At the end of every Chef Infra Client run, the node object that defines the current state of the node is uploaded to the Chef Infra Server so that it can be indexed for search. ### Edit Attribute To edit node attributes: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click the **Attributes** tab. 5. Click **Edit**. 6. In the **Edit Node Attributes** dialog box, make your changes: ![image] 7. Click **Save Attributes**. ### View Attributes To view the attributes for a node: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click the **Attributes** tab. 5. Click **Edit**. Run-lists --------- A run-list defines all of the information necessary for Chef to configure a node into the desired state. A run-list is: * An ordered list of roles and/or recipes that are run in the exact order defined in the run-list; if a recipe appears more than once in the run-list, Chef Infra Client will not run it twice * Always specific to the node on which it runs; nodes may have a run-list that is identical to the run-list used by other nodes * Stored as part of the node object on the Chef server * Maintained using knife and then uploaded from the workstation to the Chef Infra Server, or maintained using Chef Automate ### Add Recipe to To add a role or recipe to a run-list: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click **Edit Run List**. 5. In the **Edit Node Run List** dialog box, drag the role or recipe from the **Available Roles** or **Available Recipes** lists to the current run-list. ![image] 6. Click **Save Run List**. ### Add Role to To add a role or recipe to a run-list: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click **Edit Run List**. 5. In the **Edit Node Run List** dialog box, drag the role or recipe from the **Available Roles** or **Available Recipes** lists to the current run-list. ![image] 6. Click **Save Run List**. ### Edit To edit a run-list: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click **Edit Run List**. 5. In the **Edit Node Run List** dialog box, make your changes. 6. Click **Save Run List**. ### Remove Recipe from To remove a role or recipe from a run-list: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click **Edit Run List**. 5. In the **Edit Node Run List** dialog box, drag the role or recipe from the **Current Run List** to the list of available roles or recipes. ![image] 6. Click **Save Run List**. ### Remove Role from To remove a role or recipe from a run-list: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click **Edit Run List**. 5. In the **Edit Node Run List** dialog box, drag the role or recipe from the **Current Run List** to the list of available roles or recipes. ![image] 6. Click **Save Run List**. ### View Current To view the current run-list for a node: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click the **Details** tab. 5. The current run-list is shown in the lower right: ![image] Permissions ----------- Permissions are used in the Chef Infra Server to define how users and groups can interact with objects on the server. Permissions are configured per-organization. The Chef Infra Server includes the following object permissions: | Permission | Description | | --- | --- | | **Delete** | Use the **Delete** permission to define which users and groups may delete an object. This permission is required for any user who uses the `knife [object] delete [object_name]` argument to interact with objects on the Chef Infra Server. | | **Grant** | Use the **Grant** permission to define which users and groups may configure permissions on an object. This permission is required for any user who configures permissions using the **Administration** tab in the Chef management console. | | **Read** | Use the **Read** permission to define which users and groups may view the details of an object. This permission is required for any user who uses the `knife [object] show [object_name]` argument to interact with objects on the Chef Infra Server. | | **Update** | Use the **Update** permission to define which users and groups may edit the details of an object. This permission is required for any user who uses the `knife [object] edit [object_name]` argument to interact with objects on the Chef Infra Server and for any Chef Infra Client to save node data to the Chef Infra Server at the conclusion of a Chef Infra Client run. | ### Set To set permissions list for a node object: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click the **Permissions** tab. 5. For each group listed under **Name**, select or de-select the **Read**, **Update**, **Delete**, and **Grant** permissions. ### Update To update the permissions list for a node object: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click the **Permissions** tab. 5. Click the **+ Add** button and enter the name of the user or group to be added. 6. Select or de-select **Read**, **Update**, **Delete**, and **Grant** to update the permissions list for the user or group. ### View To view permissions for a node: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click the **Permissions** tab. 5. Set the appropriate permissions: **Delete**, **Grant**, **Read**, and/or **Update**. Manage Tags ----------- A tag is a custom description that is applied to a node. A tag, once applied, can be helpful when managing nodes using knife or when building recipes by providing alternate methods of grouping similar types of information. ### Add To add tags to a node (or a group of nodes): 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node (or a group of nodes). 4. Click **Manage Tags**. 5. In the **Manage Node Tags** dialog box, enter the name of the tag and then select **Add Tags** from the drop-down. ![image] 6. Click **Update Tags**. ### Delete To delete tags for a node (or a group of nodes): 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node (or a group of nodes). 4. Click **Manage Tags**. 5. In the **Manage Node Tags** dialog box, enter the name of the tag and then select **Delete Tags** from the drop-down. ![image] 6. Click **Update Tags**. ### View To view all of the nodes: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Select the **Details** tab. 5. The tags for the node appear under the **Tags** header: ![image] © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server_manage_nodes/Manage Client Keys ================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/server_manage_clients.md) [![Link to Chef Automate documentation.] Warning Chef Manage is [deprecated](../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. Note This topic is about using the Chef management console to manage keys. A client is an actor that has permission to access the Chef Infra Server. A client is most often a node (on which the Chef Infra Client runs), but is also a workstation (on which knife runs), or some other machine that is configured to use the Chef Infra Server API. Each request to the Chef Infra Server that is made by a client uses a private key for authentication that must be authorized by the public key on the Chef Infra Server. Use the Chef management console to create a key pair, download the private key, and then set permissions, to delete a key, or to reset a key. Manage Client Keys ------------------ Client keys can be managed from the Chef management console. Warning The images below refer to client keys as a “Client”. ### Add To add a client key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Click **Create**. 5. In the **Create Client** dialog box, enter the name of the client key. ![image] Click **Create Client**. 6. Copy the private key: ![image] or download and save the private key locally: ![image] ### Delete To delete a client key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a client key. 5. Click **Delete**. ![image] ### Reset Key To regenerate a client key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a client key. 5. Click the **Details** tab. 6. Click **Reset Key**. 7. In the **Reset Key** dialog box, confirm that the key should be regenerated and click the **Reset Key** button: ![image] 8. Copy the private key: ![image] or download and save the private key locally: ![image] ### View Details To view client key details: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a client key. 5. Click the **Details** tab. ### Permissions Permissions are used in the Chef Infra Server to define how users and groups can interact with objects on the server. Permissions are configured per-organization. The Chef Infra Server includes the following object permissions: | Permission | Description | | --- | --- | | **Delete** | Use the **Delete** permission to define which users and groups may delete an object. This permission is required for any user who uses the `knife [object] delete [object_name]` argument to interact with objects on the Chef Infra Server. | | **Grant** | Use the **Grant** permission to define which users and groups may configure permissions on an object. This permission is required for any user who configures permissions using the **Administration** tab in the Chef management console. | | **Read** | Use the **Read** permission to define which users and groups may view the details of an object. This permission is required for any user who uses the `knife [object] show [object_name]` argument to interact with objects on the Chef Infra Server. | | **Update** | Use the **Update** permission to define which users and groups may edit the details of an object. This permission is required for any user who uses the `knife [object] edit [object_name]` argument to interact with objects on the Chef Infra Server and for any Chef Infra Client to save node data to the Chef Infra Server at the conclusion of a Chef Infra Client run. | #### Set To set permissions list for a client key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a client key. 5. Click the **Permissions** tab. 6. For each group listed under **Name**, select or de-select the **Read**, **Update**, **Delete**, and **Grant** permissions. #### Update To update the permissions list for a client key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a client key. 5. Click the **Permissions** tab. 6. Click the **+ Add** button and enter the name of the user or group to be added. 7. Select or de-select **Read**, **Update**, **Delete**, and **Grant** to update the permissions list for the user or group. #### View To view permissions for a client key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a client key. 5. Click the **Permissions** tab. 6. Set the appropriate permissions: **Delete**, **Grant**, **Read**, and/or **Update**. chef-validator Keys ------------------- Every request made by Chef Infra Client to the Chef Infra Server must be an authenticated request using the Chef Infra Server API and a private key. When Chef Infra Client makes a request to the Chef Infra Server, Chef Infra Client authenticates each request using a private key located in `/etc/chef/client.pem`. The private key does not yet exist the first time that Chef Infra Client runs from a new node. During the first Chef Infra Client run: 1. Chef Infra Client uses the chef-validator private key, located in `/etc/chef/validation.pem` to register with Chef Infra Server 2. Chef Infra Server assigns Chef Infra Client a private key for all future authentication requests to the Chef Infra Server 3. Chef Infra Client saves the private key on the node as `/etc/chef/client.pem` If the request to communicate with Chef Infra Server with the chef-validator key fails, then the entire first Chef Infra Client run fails. After the first completed Chef Infra Client run, delete the chef-validator private key at `/etc/chef/validation.pem` ### Add To add a chef-validator key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Click **Create**. 5. In the **Create Client** dialog box, enter the name of the chef-validator key. ![image] Select the **Validation Client** option. Click **Create Client**. 6. Copy the private key: ![image] or download and save the private key locally: ![image] ### Delete To delete a chef-validator key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a chef-validator key. 5. Click **Delete**. ![image] ### Reset Key To reset a chef-validator key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a chef-validator key. 5. Click the **Details** tab. 6. Click **Reset Key**. 7. In the **Reset Key** dialog box, confirm that the key should be regenerated and click the **Reset Key** button: ![image] 8. Copy the private key: ![image] or download and save the private key locally: ![image] ### View Details To view details for a chef-validator key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a chef-validator key. ![image] 5. Click the **Details** tab. ### Permissions Permissions are used in the Chef Infra Server to define how users and groups can interact with objects on the server. Permissions are configured per-organization. The Chef Infra Server includes the following object permissions: | Permission | Description | | --- | --- | | **Delete** | Use the **Delete** permission to define which users and groups may delete an object. This permission is required for any user who uses the `knife [object] delete [object_name]` argument to interact with objects on the Chef Infra Server. | | **Grant** | Use the **Grant** permission to define which users and groups may configure permissions on an object. This permission is required for any user who configures permissions using the **Administration** tab in the Chef management console. | | **Read** | Use the **Read** permission to define which users and groups may view the details of an object. This permission is required for any user who uses the `knife [object] show [object_name]` argument to interact with objects on the Chef Infra Server. | | **Update** | Use the **Update** permission to define which users and groups may edit the details of an object. This permission is required for any user who uses the `knife [object] edit [object_name]` argument to interact with objects on the Chef Infra Server and for any Chef Infra Client to save node data to the Chef Infra Server at the conclusion of a Chef Infra Client run. | #### Set To update the permissions list for a chef-validator key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a chef-validator key. 5. Click the **Permissions** tab. 6. Click the **+ Add** button and enter the name of the user or group to be added. 7. Select or de-select **Delete**, **Grant**, **Read**, and/or **Update** to update the permissions list for the user or group. #### Update To update the permissions list for a client key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a client key. 5. Click the **Permissions** tab. 6. Click the **+ Add** button and enter the name of the user or group to be added. 7. Select or de-select **Read**, **Update**, **Delete**, and **Grant** to update the permissions list for the user or group. #### View To view permissions for a chef-validator key: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Clients**. 4. Select a chef-validator key. 5. Click the **Permissions** tab. 6. Set the appropriate permissions: **Delete**, **Grant**, **Read**, and/or **Update**. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server_manage_clients/Manage Environments =================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/server_manage_environments.md) [![Link to Chef Automate documentation.] Warning Chef Manage is [deprecated](../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. Note This topic is about using the Chef management console to manage environments. Note Chef Manage in all versions can only display 20 Environment items from the Chef Server search index. An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. Manage ------ Environments can be managed from the Chef management console web user interface. ### Add Environment To add an environment: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Environments**. 4. Click **Create**. 5. In the **Create an Environment** dialog box, enter the name of the environment and a description. ![image] Click **Next**. 6. Optional. Set a constraint by choosing a name, an operator, and a version: ![image] Click **Add**. Continue this process until all constraints are added. When finished, click **Next**. 7. Optional. Add default attributes as JSON data: ![image] Click **Next**. 8. Optional. Add override attributes as JSON data: ![image] 9. Click **Create Environment**. ### Delete Environment To delete an environment: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Environments**. 4. Select an environment. 5. Click **Delete**. ![image] ### Edit Details To edit the details of an environment: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Environments**. 4. Select an environment. 5. Click the **Details** tab. 6. Click **Edit**. ### Set To set the environment for a node: 1. Open the Chef management console. 2. Click **Nodes**. 3. Select a node. 4. Click the **Details** tab. 5. In the top right, from the **Environment** drop-down, select the environment: ![image] 6. Click **Save**. ### View Details To view environment details: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Environments**. 4. Select an environment. 5. Click the **Details** tab. Default Attributes ------------------ A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. ### Edit To edit default attributes for an environment: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Environments**. 4. Select an environment. 5. Click the **Attributes** tab. 6. Under **Default Attributes**, click **Edit**. 7. In the **Edit Environment Attributes** dialog box, enter the JSON data that defines the attribute (or attributes). ![image] 8. Click **Save**. ### View To view default attributes for an environment: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Environments**. 4. Select an environment. 5. Click the **Attributes** tab. Override Attributes ------------------- An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. ### Edit To edit override attributes for an environment: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Environments**. 4. Select an environment. 5. Click the **Attributes** tab. 6. Under **Override Attributes**, click **Edit**. 7. In the **Edit Environment Attributes** dialog box, enter the JSON data that defines the attribute (or attributes). ![image] 8. Click **Save Attributes**. ### View To view override attributes for an environment: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Environments**. 4. Select an environment. 5. Click the **Attributes** tab. Permissions ----------- Permissions are used in the Chef Infra Server to define how users and groups can interact with objects on the server. Permissions are configured per-organization. The Chef Infra Server includes the following object permissions: | Permission | Description | | --- | --- | | **Delete** | Use the **Delete** permission to define which users and groups may delete an object. This permission is required for any user who uses the `knife [object] delete [object_name]` argument to interact with objects on the Chef Infra Server. | | **Grant** | Use the **Grant** permission to define which users and groups may configure permissions on an object. This permission is required for any user who configures permissions using the **Administration** tab in the Chef management console. | | **Read** | Use the **Read** permission to define which users and groups may view the details of an object. This permission is required for any user who uses the `knife [object] show [object_name]` argument to interact with objects on the Chef Infra Server. | | **Update** | Use the **Update** permission to define which users and groups may edit the details of an object. This permission is required for any user who uses the `knife [object] edit [object_name]` argument to interact with objects on the Chef Infra Server and for any Chef Infra Client to save node data to the Chef Infra Server at the conclusion of a Chef Infra Client run. | ### Set To set permissions list for an environment object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Environments**. 4. Select an environment. 5. Click the **Permissions** tab. 6. For each group listed under **Name**, select or de-select the **Read**, **Update**, **Delete**, and **Grant** permissions. ### Update To update the permissions list for an environment object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Environments**. 4. Select an environment. 5. Click the **Permissions** tab. 6. Click the **+ Add** button and enter the name of the user or group to be added. 7. Select or de-select **Read**, **Update**, **Delete**, and **Grant** to update the permissions list for the user or group. ### View To view permissions for an environment object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Environments**. 4. Select an environment. 5. Click the **Permissions** tab. 6. Set the appropriate permissions: **Read**, **Update**, **Delete**, and **Grant**. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server_manage_environments/Manage Roles ============ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/server_manage_roles.md) [![Link to Chef Automate documentation.] Warning Chef Manage is [deprecated](../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. Note This topic is about using the Chef management console to manage roles. A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. Manage ------ Roles can be managed from the Chef management console web user interface. ### Add Role To add a role: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Roles**. 4. Click **Create**. 5. In the **Create Role** dialog box, enter the name of the role and a description. ![image] Click **Next**. 6. Optional. Build the run-list from the list of available roles and recipes: ![image] Click **Next**. 7. Optional. Add default attributes as JSON data: ![image] Click **Next**. 8. Optional. Add override attributes as JSON data: ![image] 9. Click **Create Role**. ### Delete Role To delete a role: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Roles**. 4. Select a role. 5. Click **Delete**. ![image] ### View All Roles To view all roles uploaded to the Chef Infra Server organization: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Roles**. Run-lists --------- A run-list defines all of the information necessary for Chef to configure a node into the desired state. A run-list is: * An ordered list of roles and/or recipes that are run in the exact order defined in the run-list; if a recipe appears more than once in the run-list, Chef Infra Client will not run it twice * Always specific to the node on which it runs; nodes may have a run-list that is identical to the run-list used by other nodes * Stored as part of the node object on the Chef server * Maintained using knife and then uploaded from the workstation to the Chef Infra Server, or maintained using Chef Automate ### Edit Role Run-list To edit the run-list for a role: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Roles**. 4. Select a role. 5. Click **Edit Run List**. ![image] 6. Make your changes. 7. Click **Save Run List**. Default Attributes ------------------ A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. ### Edit Default Attributes To edit default attributes for a role: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Roles**. 4. Select a role. 5. Click the **Attributes** tab. 6. Under **Default Attributes**, click **Edit**. 7. In the **Edit Role Attributes** dialog box, enter the JSON data that defines the attribute (or attributes). ![image] 8. Click **Save Attributes**. ### View Default Attributes To view default attributes for a role: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Roles**. 4. Select a role. 5. Click the **Attributes** tab. Override Attributes ------------------- An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. ### Edit Override Attributes To edit override attributes for a role: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Roles**. 4. Select a role. 5. Click the **Attributes** tab. 6. Under **Override Attributes**, click **Edit**. 7. In the **Edit Role Attributes** dialog box, enter the JSON data that defines the attribute (or attributes). ![image] 8. Click **Save Attributes**. ### View Override Attributes To view role details: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Roles**. 4. Select a role. 5. Click the **Details** tab. Permissions ----------- Permissions are used in the Chef Infra Server to define how users and groups can interact with objects on the server. Permissions are configured per-organization. The Chef Infra Server includes the following object permissions: | Permission | Description | | --- | --- | | **Delete** | Use the **Delete** permission to define which users and groups may delete an object. This permission is required for any user who uses the `knife [object] delete [object_name]` argument to interact with objects on the Chef Infra Server. | | **Grant** | Use the **Grant** permission to define which users and groups may configure permissions on an object. This permission is required for any user who configures permissions using the **Administration** tab in the Chef management console. | | **Read** | Use the **Read** permission to define which users and groups may view the details of an object. This permission is required for any user who uses the `knife [object] show [object_name]` argument to interact with objects on the Chef Infra Server. | | **Update** | Use the **Update** permission to define which users and groups may edit the details of an object. This permission is required for any user who uses the `knife [object] edit [object_name]` argument to interact with objects on the Chef Infra Server and for any Chef Infra Client to save node data to the Chef Infra Server at the conclusion of a Chef Infra Client run. | ### Set To set permissions list for a role object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Roles**. 4. Select a role. 5. Click the **Permissions** tab. 6. For each group listed under **Name**, select or de-select the **Read**, **Update**, **Delete**, and **Grant** permissions. ### Update To update the permissions list for a role object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Roles**. 4. Select a role. 5. Click the **Permissions** tab. 6. Click the **+ Add** button and enter the name of the user or group to be added. 7. Select or de-select **Read**, **Update**, **Delete**, and **Grant** to update the permissions list for the user or group. ### View To view permissions for a role object: 1. Open the Chef management console. 2. Click **Policy**. 3. Click **Roles**. 4. Select a role. 5. Click the **Permissions** tab. 6. Set the appropriate permissions: **Delete**, **Grant**, **Read**, and/or **Update**. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server_manage_roles/Users ===== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/server_users.md) The following tasks are available for user management in Chef Infra Server: * Creating users * Editing a user’s profile * Changing a password * Recovering a password * Regenerating a private key * Viewing a user’s profile chef-server-ctl --------------- The Chef Infra Server includes a command-line utility named chef-server-ctl. This command-line tool is used to start and stop individual services, reconfigure the Chef Infra Server, run chef-pedant, and then tail Chef Infra Server log files. Use the `user-create`, `user-delete`, `user-edit`, `user-list` and `user-show` subcommands to manage users. ### org-create The `org-create` subcommand is used to create an organization. (The validation key for the organization is returned to `STDOUT` when creating an organization with this command.) #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-create ORG_NAME "ORG_FULL_NAME" (options) ``` where: * The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. * The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `"Chef Software, Inc."`. #### Options This subcommand has the following options: `-a USER_NAME`, `--association_user USER_NAME` Associate a user with an organization and add them to the `admins` and `billing_admins` security groups. `-f FILE_NAME`, `--filename FILE_NAME` Write the ORGANIZATION-validator.pem to `FILE_NAME` instead of printing it to `STDOUT`. ### org-delete The `org-delete` subcommand is used to delete an organization. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-delete ORG_NAME ``` ### org-list The `org-list` subcommand is used to list all of the organizations currently present on the Chef Infra Server. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-list (options) ``` #### Options This subcommand has the following options: `-a`, `--all-orgs` Show all organizations. `-w`, `--with-uri` Show the corresponding URIs. ### org-show The `org-show` subcommand is used to show the details for an organization. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-show ORG_NAME ``` ### org-user-add Warning Early RC candidates for the Chef Server 12 release named this command `org-associate`. This is the same command, with the exception of the `--admin` flag, which is added to the command (along with the rename) for the upcoming final release of Chef Server 12. The `org-user-add` subcommand is used to add a user to an organization. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-user-add ORG_NAME USER_NAME (options) ``` #### Options This subcommand has the following options: `--admin` Add the user to the `admins` group. ### org-user-remove The `org-user-remove` subcommand is used to remove a user from an organization. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-user-remove ORG_NAME USER_NAME (options) ``` ### user-create The `user-create` subcommand is used to create a user. (The validation key for the organization may be returned to `STDOUT` when creating a user with this command.) #### Syntax This subcommand has the following syntax: ``` chef-server-ctl user-create USER_NAME FIRST_NAME [MIDDLE_NAME] LAST_NAME EMAIL 'PASSWORD' (options) ``` #### Options This subcommand has the following options: `-f FILE_NAME`, `--filename FILE_NAME` Write the USER.pem to a file instead of `STDOUT`. ### user-delete The `user-delete` subcommand is used to delete a user. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl user-delete USER_NAME ``` ### user-edit The `user-edit` subcommand is used to edit the details for a user. The data will be made available in the $EDITOR for editing. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl user-edit USER_NAME ``` ### user-list The `user-list` subcommand is used to view a list of users. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl user-list (options) ``` #### Options This subcommand has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### user-show The `user-show` subcommand is used to show the details for a user. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl user-show USER_NAME (options) ``` #### Options This subcommand has the following options: `-l`, `--with-orgs` Show all organizations. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server_users/Chef Infra Server Overview ========================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/_index.md) The Chef Infra Server acts as a hub for configuration data. The Chef Infra Server stores cookbooks, the policies that are applied to nodes, and the metadata that describes each registered node that is under management by Chef Infra Client. Nodes use Chef Infra Client to ask the Chef Infra Server for configuration details, such as recipes, templates, and file distributions. Chef Infra Client then does as much of the configuration work as possible on the nodes themselves (and not on the Chef Infra Server). This scalable approach distributes the configuration effort throughout the organization. The Chef Infra Server API is written in [Erlang](http://www.erlang.org/), which is an excellent language for critical enterprise concerns like concurrency, fault-tolerance, and distributed environments. The Chef Infra Server can scale to the size of any enterprise. Note The Chef Infra Server can be configured via the `/etc/opscode/chef-server.rb` file. Whenever this file is modified, the `chef-server-ctl reconfigure` command must be run to apply the changes. See the [Chef Infra Server settings](../server/config_rb_server/index) guide for additional information. Server Components ----------------- The following diagram shows the various components that are part of a Chef Infra Server deployment and how they relate to one another. ![Diagram of Chef Infra Server deployment] | Component | Description | | --- | --- | | Clients | The Chef Infra Server is accessed primarily by nodes that are under management by Chef, as Chef Infra Client runs occur. It is also accessed by individuals who maintain cookbooks and policy that is stored on the Chef Infra Server, typically from a workstation. And also by individual users with credentials to Chef Infra Server components, such as the Chef management console. | | Load Balancer | Nginx is an open-source HTTP and reverse proxy server that is used as the front-end load balancer for the Chef Infra Server. All requests to the Chef Infra Server API are routed through Nginx. | | Chef Manage | Chef Manage is the web interface for the Chef Infra Server, which uses the Chef Infra Server API for all communication to the Chef Infra Server. | | Chef Infra Server | Erchef is a complete rewrite of the core API for the Chef Infra Server, which allows it to be faster and more scalable than previous versions. The API itself is still compatible with the original Ruby-based Chef Infra Server, which means that cookbooks and recipes that were authored for the Ruby-based Chef Infra Server will continue to work on the Erlang-based Chef Infra Server. Chef Infra Client is still written in Ruby. Note Even though the Chef Infra Server is authored in Erlang, writing code in Erlang is NOT a requirement for using Chef Infra. | | Bookshelf | Bookshelf is used to store cookbook content—files, templates, and so on—that have been uploaded to the Chef Infra Server as part of a cookbook version. Cookbook content is stored by content checksum. If two different cookbooks or different versions of the same cookbook include the same file or template, Bookshelf will store that file only once. The cookbook content managed by Bookshelf is stored in flat files and is separated from the Chef Infra Server and search index repositories. All cookbooks are stored in a dedicated repository. | | Messages | chef-elasticsearch wraps Elastisearch and exposes its REST API for indexing and search. All messages are added to a dedicated search index repository. | | PostgreSQL | PostgreSQL is the data storage repository for the Chef Infra Server. | External Cookbooks ------------------ The following diagram highlights the specific changes that occur when cookbooks are stored at an external location, such as Amazon Simple Storage Service (S3). ![image] The following table describes the components that are different from the default configuration of the Chef Infra Server when cookbooks are stored at an external location: | Component | Description | | --- | --- | | Clients | The Chef Infra Server will provide signed URLs for cookbook requests made by the various clients (individual users, knife requests, and from the Chef Infra Client that is installed on nodes under management by Chef Infra). | | Load Balancer | The signed URLs for cookbooks are pointed here, and then routed to cookbook storage, as required. | | Chef Infra Server | Erchef is a complete rewrite of the core API for the Chef Infra Server, which allows it to be faster and more scalable than previous versions. The API itself is still compatible with the original Ruby-based Chef Infra Server, which means that cookbooks and recipes that were authored for the Ruby-based Chef Infra Server will continue to work on the Erlang-based Chef Infra Server. Chef Infra Client is still written in Ruby. Note Even though the Chef Infra Server is authored in Erlang, writing code in Erlang is NOT a requirement for using Chef Infra. | | Amazon Simple Storage Service (S3) | Bookshelf is used to store cookbook content—files, templates, and so on—that have been uploaded to the Chef Infra Server as part of a cookbook version. Cookbook content is stored by content checksum. If two different cookbooks or different versions of the same cookbook include the same file or template, Bookshelf will store that file only once. The cookbook content managed by Bookshelf is stored in flat files and is separated from the Chef Infra Server and search index repositories. This represents external cookbooks storage at Amazon Simple Storage Service (S3). | ### AWS Settings #### Required Settings To configure external cookbook storage using Amazon Simple Storage Service (S3) set the following configuration settings in the `chef-server.rb` file and run `chef-server-ctl reconfigure`: | Setting | Description | | --- | --- | | `bookshelf['access_key_id']` | The access key identifier. Default value: generated by default. Specifying this directly in the configuration file is discouraged. Please use `chef-server-ctl set-secret bookshelf access_key_id` from the [Secrets Management](../ctl_chef_server#ctl-chef-server-secrets-management) commands. | | `bookshelf['external_url']` | The full URL of the S3 bucket. | | `bookshelf['secret_access_key']` | The secret key. Default value: generated by default. Specifying this directly in the configuration file is discouraged. Please use `chef-server-ctl set-secret bookshelf secret_access_key` from the [Secrets Management](../ctl_chef_server#ctl-chef-server-secrets-management) commands. | | `opscode_erchef['s3_bucket']` | The name of the Amazon Simple Storage Service (S3) bucket. Default value: `bookshelf`. | | `bookshelf['vip']` | The virtual IP address or host name of the Amazon Simple Service (S3) API. Default value: `127.0.0.1`. | An example `chef-server.rb` configuration: ``` bookshelf['vip'] = 's3-external-1.amazonaws.com' bookshelf['external_url'] = 'https://s3-external-1.amazonaws.com' bookshelf['access_key_id'] = '<ACCESS_ID>' bookshelf['secret_access_key'] = '<ACCESS_KEY>' opscode_erchef['s3_bucket'] = '<BUCKET_NAME>' ``` #### Optional Settings The following optional settings are also available and may require modification when using an external S3 provider: | Setting | Description | | --- | --- | | `opscode_erchef['nginx_bookshelf_caching']` | Whether Nginx is used to cache cookbooks. When `:on`, Nginx serves up the cached content instead of forwarding the request. Default value: `:off`. | | `opscode_erchef['s3_parallel_ops_fanout']` | Default value: `20`. | | `opscode_erchef['s3_parallel_ops_timeout']` | Default value: `5000`. | | `opscode_erchef['s3_url_expiry_window_size']` | The frequency at which unique URLs are generated. This value may be a specific amount of time, i.e. `15m` (fifteen minutes) or a percentage of the value of `s3_url_ttl`, i.e. `10%`. Default value: `:off`. | | `opscode_erchef['s3_url_ttl']` | The amount of time (in seconds) before connections to the server expire. If node bootstraps are timing out, increase this setting. Default value: `28800`. | External PostgreSQL ------------------- The following diagram highlights the specific changes that occur when PostgreSQL is configured and managed independently of the Chef Infra Server configuration. ![image] The following table describes the components in an external PostgreSQL configuration that are different from the default configuration of the Chef Infra Server: | Component | Description | | --- | --- | | Chef Infra Server | The Chef Infra Server configuration file is updated to point to an independently configured set of servers for PostgreSQL. | | PostgreSQL | PostgreSQL is the data storage repository for the Chef Infra Server. This represents the independently configured set of servers that are running PostgreSQL and are configured to act as the data store for the Chef Infra Server. | ### PostgreSQL Settings Use the following configuration settings in the chef-server.rb file to configure external PostgreSQL for use with the Chef Infra Server: `postgresql['db_superuser']` Required when `postgresql['external']` is set to `true`. The PostgreSQL user name. This user must be granted either the `CREATE ROLE` and `CREATE DATABASE` permissions in PostgreSQL or be granted `SUPERUSER` permission. This user must also have an entry in the host-based authentication configuration file used by PostgreSQL (traditionally named `pg_hba.conf`). Default value: `'superuser_userid'`. `postgresql['db_superuser_password']` The password for the user specified by `postgresql['db_superuser']`. Required when `postgresql['external']` is set to `true`. The db_superuser_password can also be set using `chef-server-ctl set-db-superuser-password` from the [Secrets Management](../ctl_chef_server/index#ctl-chef-server-secrets-management) commands. `postgresql['external']` Required. Set to `true` to run PostgreSQL external to the Chef Infra Server. Must be set once only on a new installation of the Chef Infra Server before the first `chef-server-ctl reconfigure` command is run. If this is set after a reconfigure or set to `false`, any reconfigure of the Chef Infra Server will return an error. Default value: `false`. `postgresql['port']` Optional when `postgresql['external']` is set to `true`. The port on which the service is to listen. The port used by PostgreSQL if that port is **not** 5432. Default value: `5432`. `postgresql['vip']` Required when `postgresql['external']` is set to `true`. The virtual IP address. The host for this IP address must be online and reachable from the Chef Infra Server via the port specified by `postgresql['port']`. Set this value to the IP address or hostname for the machine on which external PostgreSQL is located when `postgresql['external']` is set to `true`. #### Optional Settings The following optional settings are required when configuring external PostgreSQL on Microsoft Azure: `bookshelf['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `bookshelf['sql_user']` (default: `'bookshelf'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `bookshelf['sql_user']` Default value: `nil`. `oc_bifrost['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `oc_bifrost['sql_user']` (default: `'bifrost'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_bifrost['sql_user']`. Default value: `nil`. `oc_id['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `oc_id['sql_user']` (default: `'od_id'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_id['sql_user']`. Default value: `nil`. `opscode_erchef['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>@my_<EMAIL>'`), where `username` would normally equal the value of `opscode-erchef['sql_user']` (default: `'opscode_chef'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `opscode_erchef['sql_user']`. Default value: `nil`. `postgresql['db_connection_superuser']` The PostgreSQL superuser name in `'username@hostname'` format (e.g. `'<EMAIL>@my_<EMAIL>'`), where `username` would normally equal the value of `postgresql['db_superuser']` with any dashes replaced by underscores. This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `postgresql['db_superuser']`. Default value: `nil`. An example `chef-server.rb` configuration for External PostgreSQL on Microsoft Azure: ``` topology 'standalone' postgresql['external'] = true postgresql['vip'] = 'my_postgresql.postgres.database.azure.com' postgresql['db_superuser'] = 'opscode_pgsql' postgresql['db_superuser_password'] = 'My_postgres_password1!' postgresql['db_connection_superuser'] = '<EMAIL>' # postgresql['sslmode']='require' # required if 'Enforce SSL connection' is enabled on Azure PostgreSQL bookshelf['sql_connection_user'] = '<EMAIL>' oc_bifrost['sql_connection_user'] = '<EMAIL>' oc_id['sql_connection_user'] = '<EMAIL>' opscode_erchef['sql_connection_user'] = '<EMAIL>' ``` Note See the list of [error messages that may be present](../errors/index#external-postgresql) when configuring the Chef Infra Server to use a remote PostgreSQL server. ### Bookshelf Settings In instances that require cookbooks to be stored within a SQL backend, such as in a high availability setup, you must set the `storage_type` to `:sql`: ``` bookshelf['storage_type'] = :sql ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server_overview/Organizations and Groups ======================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/server_orgs.md) The Chef Infra Server uses role-based access control (RBAC) to restrict access to objects—nodes, environments, roles, data bags, cookbooks, and so on. This ensures that only authorized user and/or Chef Infra Client requests to the Chef Infra Server are allowed. Access to objects on the Chef Infra Server is fine-grained, allowing access to be defined by object type, object, group, user, and organization. The Chef Infra Server uses permissions to define how a user may interact with an object, after they have been authorized to do so. The Chef Infra Server uses organizations, groups, and users to define role-based access control: | Feature | Description | | --- | --- | | image | An organization is the top-level entity for role-based access control in the Chef Infra Server. Each organization contains the default groups (`admins`, `clients`, and `users`, plus `billing_admins` for the hosted Chef Infra Server), at least one user and at least one node (on which the Chef Infra Client is installed). The Chef Infra Server supports multiple organizations. The Chef Infra Server includes a single default organization that is defined during setup. Additional organizations can be created after the initial setup and configuration of the Chef Infra Server. | | image | A group is used to define access to object types and objects in the Chef Infra Server and also to assign permissions that determine what types of tasks are available to members of that group who are authorized to perform them. Groups are configured per-organization. Individual users who are members of a group will inherit the permissions assigned to the group. The Chef Infra Server includes the following default groups: `admins`, `clients`, and `users`. For users of the hosted Chef Infra Server, an additional default group is provided: `billing_admins`. | | image | A user is any non-administrator human being who will manage data that is uploaded to the Chef Infra Server from a workstation or who will log on to the Chef management console web user interface. The Chef Infra Server includes a single default user that is defined during setup and is automatically assigned to the `admins` group. | | image | A client is an actor that has permission to access the Chef Infra Server. A client is most often a node (on which the Chef Infra Client runs), but is also a workstation (on which knife runs), or some other machine that is configured to use the Chef Infra Server API. Each request to the Chef Infra Server that is made by a client uses a private key for authentication that must be authorized by the public key on the Chef Infra Server. | When a user makes a request to the Chef Infra Server using the Chef Infra Server API, permission to perform that action is determined by the following process: 1. Check if the user has permission to the object type 2. If no, recursively check if the user is a member of a security group that has permission to that object 3. If yes, allow the user to perform the action Permissions are managed using the Chef management console add-on in the Chef Infra Server web user interface. Organizations ------------- A single instance of the Chef Infra Server can support many organizations. Each organization has a unique set of groups and users. Each organization manages a unique set of nodes, on which a Chef Infra Client is installed and configured so that it may interact with a single organization on the Chef Infra Server. ![image] A user may belong to multiple organizations under the following conditions: * Role-based access control is configured per-organization * For a single user to interact with the Chef Infra Server using knife from the same chef-repo, that user may need to edit their config.rb file prior to that interaction Using multiple organizations within the Chef Infra Server ensures that the same toolset, coding patterns and practices, physical hardware, and product support effort is being applied across the entire company, even when: * Multiple product groups must be supported—each product group can have its own security requirements, schedule, and goals * Updates occur on different schedules—the nodes in one organization are managed completely independently from the nodes in another * Individual teams have competing needs for object and object types—data bags, environments, roles, and cookbooks are unique to each organization, even if they share the same name ### Permissions Permissions are used in the Chef Infra Server to define how users and groups can interact with objects on the server. Permissions are configured per-organization. #### Object Permissions The Chef Infra Server includes the following object permissions: | Permission | Description | | --- | --- | | **Delete** | Use the **Delete** permission to define which users and groups may delete an object. This permission is required for any user who uses the `knife [object] delete [object_name]` argument to interact with objects on the Chef Infra Server. | | **Grant** | Use the **Grant** permission to define which users and groups may configure permissions on an object. This permission is required for any user who configures permissions using the **Administration** tab in the Chef management console. | | **Read** | Use the **Read** permission to define which users and groups may view the details of an object. This permission is required for any user who uses the `knife [object] show [object_name]` argument to interact with objects on the Chef Infra Server. | | **Update** | Use the **Update** permission to define which users and groups may edit the details of an object. This permission is required for any user who uses the `knife [object] edit [object_name]` argument to interact with objects on the Chef Infra Server and for any Chef Infra Client to save node data to the Chef Infra Server at the conclusion of a Chef Infra Client run. | #### Global Permissions The Chef Infra Server includes the following global permissions: | Permission | Description | | --- | --- | | **Create** | Use the **Create** global permission to define which users and groups may create the following server object types: cookbooks, data bags, environments, nodes, roles, and tags. This permission is required for any user who uses the `knife [object] create` argument to interact with objects on the Chef Infra Server. | | **List** | Use the **List** global permission to define which users and groups may view the following server object types: cookbooks, data bags, environments, nodes, roles, and tags. This permission is required for any user who uses the `knife [object] list` argument to interact with objects on the Chef Infra Server. | These permissions set the default permissions for the following Chef Infra Server object types: clients, cookbooks, data bags, environments, groups, nodes, roles, and sandboxes. #### Client Key Permissions Note This is only necessary after migrating a client from one Chef Infra Server to another. Permissions must be reset for client keys after the migration. Keys should have `DELETE`, `GRANT`, `READ` and `UPDATE` permissions. Use the following code to set the correct permissions: ``` #!/usr/bin/env ruby require 'chef/knife' #previously knife.rb Chef::Config.from_file(File.join(Chef::Knife.chef_config_dir, 'knife.rb')) rest = Chef::ServerAPI.new(Chef::Config[:chef_server_url]) Chef::Node.list.each do |node| %w(read update delete grant).each do |perm| ace = rest.get("nodes/#{node[0]}/_acl")[perm] ace['actors'] << node[0] unless ace['actors'].include?(node[0]) rest.put("nodes/#{node[0]}/_acl/#{perm}", perm => ace) puts "Client \"#{node[0]}\" granted \"#{perm}\" access on node \"#{node[0]}\"" end end ``` Save it as a Ruby script—`chef_server_permissions.rb`, for example—in the `.chef/scripts` directory located in the chef-repo, and then run a knife command similar to: ``` knife exec chef_server_permissions.rb ``` #### Knife ACL The knife plugin [knife-acl](https://github.com/chef/knife-acl) provides a fine-grained approach to modifying permissions, by wrapping API calls to the `_acl` endpoint and makes such permission changes easier to manage. Warning Chef Manage is [deprecated](../versions/index#deprecated-products-and-versions) and no longer under active development. It is supported on Chef Automate installations up to version 1.8 and replaced by Chef Automate 2.0. Contact your Chef account representative for information about upgrading your system. See our [Automate documentation](../automate/index) to learn more about Chef Automate 2. This document is no longer maintained. knife-acl and the Chef Manage browser interface are incompatible. After engaging knife-acl, you will need to discontinue using the Chef Manage browser interface from that point forward due to possible incompatibilities. Groups ------ The Chef Infra Server includes the following default groups: | Group | Description | | --- | --- | | `admins` | The `admins` group defines the list of users who have administrative rights to all objects and object types for a single organization. | | `billing_admins` | The `billing_admins` group defines the list of users who have permission to manage billing information. This permission exists only for the hosted Chef Infra Server. | | `clients` | The `clients` group defines the list of nodes on which a Chef Infra Client is installed and under management by Chef. In general, think of this permission as "all of the non-human actors---Chef Infra Client, in nearly every case---that get data from, and/or upload data to, the Chef server". Newly-created Chef Infra Client instances are added to this group automatically. | | `public_key_read_access` | The `public_key_read_access` group defines which users and clients have read permissions to key-related endpoints in the Chef Infra Server API. | | `users` | The `users` group defines the list of users who use knife and the Chef management console to interact with objects and object types. In general, think of this permission as "all of the non-admin human actors who work with data that is uploaded to and/or downloaded from the Chef server". | ### Example Default Permissions The following sections show the default permissions assigned by the Chef Infra Server to the `admins`, `billing_admins`, `clients`, and `users` groups. Note The creator of an object on the Chef Infra Server is assigned `create`, `delete`, `grant`, `read`, and `update` permission to that object. #### admins The `admins` group is assigned the following: | Group | Create | Delete | Grant | Read | Update | | --- | --- | --- | --- | --- | --- | | admins | yes | yes | yes | yes | yes | | clients | yes | yes | yes | yes | yes | | users | yes | yes | yes | yes | yes | #### billing_admins The `billing_admins` group is assigned the following: #### billing_admins The `billing_admins` group is assigned the following: | Group | Create | Delete | Read | Update | | --- | --- | --- | --- | --- | | billing_admins | no | no | yes | yes | #### clients The `clients` group is assigned the following: | Object | Create | Delete | Read | Update | | --- | --- | --- | --- | --- | | clients | no | no | no | no | | cookbooks | no | no | yes | no | | cookbook_artifacts | no | no | yes | no | | data | no | no | yes | no | | environments | no | no | yes | no | | nodes | yes | no | yes | no | | organization | no | no | yes | no | | policies | no | no | yes | no | | policy_groups | no | no | yes | no | | roles | no | no | yes | no | | sandboxes | no | no | no | no | #### public_key_read_access The `public_key_read_access` group controls which users and clients have [read permissions to the following endpoints](../api_chef_server/index): * GET /clients/CLIENT/keys * GET /clients/CLIENT/keys/KEY * GET /users/USER/keys * GET /users/USER/keys/ By default, the `public_key_read_access` assigns all members of the `users` and `clients` group permission to these endpoints: | Group | Create | Delete | Grant | Read | Update | | --- | --- | --- | --- | --- | --- | | admins | no | no | no | no | no | | clients | yes | yes | yes | yes | yes | | users | yes | yes | yes | yes | yes | #### users The `users` group is assigned the following: #### users The `users` group is assigned the following: | Object | Create | Delete | Read | Update | | --- | --- | --- | --- | --- | | clients | no | yes | yes | no | | cookbooks | yes | yes | yes | yes | | cookbook_artifacts | yes | yes | yes | yes | | data | yes | yes | yes | yes | | environments | yes | yes | yes | yes | | nodes | yes | yes | yes | yes | | organization | no | no | yes | no | | policies | yes | yes | yes | yes | | policy_groups | yes | yes | yes | yes | | roles | yes | yes | yes | yes | | sandboxes | yes | no | no | no | ### chef-validator Every request made by Chef Infra Client to the Chef Infra Server must be an authenticated request using the Chef Infra Server API and a private key. When Chef Infra Client makes a request to the Chef Infra Server, Chef Infra Client authenticates each request using a private key located in `/etc/chef/client.pem`. The chef-validator is allowed to do the following at the start of a Chef Infra Client run. After the Chef Infra Client is registered with Chef Infra Server, that Chef Infra Client is added to the `clients` group: | Object | Create | Delete | Read | Update | | --- | --- | --- | --- | --- | | clients | yes | no | no | no | Server Admins ------------- The `server-admins` group is a global group that grants its members permission to create, read, update, and delete user accounts, with the exception of superuser accounts. The `server-admins` group is useful for users who are responsible for day-to-day administration of the Chef Infra Server, especially user management via the `knife user` subcommand. Before members can be added to the `server-admins` group, they must already have a user account on the Chef Infra Server. ### Scenario The following user accounts exist on the Chef Infra Server: `pivotal` (a superuser account), `alice`, `bob`, `carol`, and `dan`. Run the following command to view a list of users on the Chef Infra Server: ``` chef-server-ctl user-list ``` and it returns the same list of users: ``` pivotal alice bob carol dan ``` Alice is a member of the IT team whose responsibilities include day-to-day administration of the Chef Infra Server, in particular managing the user accounts on the Chef Infra Server that are used by the rest of the organization. From a workstation, Alice runs the following command: ``` knife user list -c ~/.chef/alice.rb ``` and it returns the following error: ``` ERROR: You authenticated successfully to <chef_server_url> as alice but you are not authorized for this action Response: Missing read permission ``` Alice is not a superuser and does not have permissions on other users because user accounts are global to organizations in the Chef Infra Server. Let’s add Alice to the `server-admins` group: ``` chef-server-ctl grant-server-admin-permissions alice ``` and it returns the following response: ``` User alice was added to server-admins. ``` Alice can now create, read, update, and delete user accounts on the Chef Infra Server, even for organizations to which Alice is not a member. From a workstation, Alice re-runs the following command: ``` knife user list -c ~/.chef/alice.rb ``` which now returns: ``` pivotal alice bob carol dan ``` Alice is now a server administrator and can use the following knife subcommands to manage users on the Chef Infra Server: * `knife user-create` * `knife user-delete` * `knife user-edit` * `knife user-list` * `knife user-show` For example, Alice runs the following command: ``` knife user edit carol -c ~/.chef/alice.rb ``` and the $EDITOR opens in which Alice makes changes, and then saves them. #### Superuser Accounts Superuser accounts may not be managed by users who belong to the `server-admins` group. For example, Alice attempts to delete the `pivotal` superuser account: ``` knife user delete pivotal -c ~/.chef/alice.rb ``` and the following error is returned: ``` ERROR: You authenticated successfully to <chef_server_url> as user1 but you are not authorized for this action Response: Missing read permission ``` Alice’s action is unauthorized even with membership in the `server-admins` group. ### Manage server-admins Group Membership of the `server-admins` group is managed with a set of `chef-server-ctl` subcommands: * `chef-server-ctl grant-server-admin-permissions` * `chef-server-ctl list-server-admins` * `chef-server-ctl remove-server-admin-permissions` #### Add Members The `grant-server-admin-permissions` subcommand is used to add a user to the `server-admins` group. Run the command once per user added. This subcommand has the following syntax: ``` chef-server-ctl grant-server-admin-permissions USER_NAME ``` where `USER_NAME` is the user to add to the list of server administrators. For example: ``` chef-server-ctl grant-server-admin-permissions bob ``` returns: ``` User bob was added to server-admins. This user can now list, read, and create users (even for orgs they are not members of) for this Chef Infra Server. ``` #### Remove Members The `remove-server-admin-permissions` subcommand is used to remove a user from the `server-admins` group. Run the command once per user removed. This subcommand has the following syntax: ``` chef-server-ctl remove-server-admin-permissions USER_NAME ``` where `USER_NAME` is the user to remove from the list of server administrators. For example: ``` chef-server-ctl remove-server-admin-permissions bob ``` returns: ``` User bob was removed from server-admins. This user can no longer list, read, and create users for this Chef Infra Server except for where they have default permissions (such as within an org). ``` #### List Membership The `list-server-admins` subcommand is used to return a list of users who are members of the `server-admins` group. This subcommand has the following syntax: ``` chef-server-ctl list-server-admins ``` and will return a list of users similar to: ``` pivotal alice bob carol dan ``` Manage Organizations -------------------- Use the `org-create`, `org-delete`, `org-list`, `org-show`, `org-user-add` and `org-user-remove` commands to manage organizations. ### org-create The `org-create` subcommand is used to create an organization. (The validation key for the organization is returned to `STDOUT` when creating an organization with this command.) #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-create ORG_NAME "ORG_FULL_NAME" (options) ``` where: * The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. * The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `"Chef Software, Inc."`. #### Options This subcommand has the following options: `-a USER_NAME`, `--association_user USER_NAME` Associate a user with an organization and add them to the `admins` and `billing_admins` security groups. `-f FILE_NAME`, `--filename FILE_NAME` Write the ORGANIZATION-validator.pem to `FILE_NAME` instead of printing it to `STDOUT`. ### org-delete The `org-delete` subcommand is used to delete an organization. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-delete ORG_NAME ``` ### org-list The `org-list` subcommand is used to list all of the organizations currently present on the Chef Infra Server. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-list (options) ``` #### Options This subcommand has the following options: `-a`, `--all-orgs` Show all organizations. `-w`, `--with-uri` Show the corresponding URIs. ### org-show The `org-show` subcommand is used to show the details for an organization. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-show ORG_NAME ``` ### org-user-add The `org-user-add` subcommand is used to add a user to an organization. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-user-add ORG_NAME USER_NAME (options) ``` #### Options This subcommand has the following options: `--admin` Add the user to the `admins` group. ### org-user-remove The `org-user-remove` subcommand is used to remove a user from an organization. #### Syntax This subcommand has the following syntax: ``` chef-server-ctl org-user-remove ORG_NAME USER_NAME (options) ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/server_orgs/Install the Chef Infra Server ============================= [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/install_server.md) There are three configuration scenarios for the Chef Infra Server: * [Standalone](#standalone) (everything on a single machine) * [High availability](#high-availability) (machines configured for front-end and back-end, allowing for failover on the back-end and load-balancing on the front-end, as required) * [Tiered](#tiered-single-backend) (machines configured for front-end and back-end, with a single back-end and load-balancing on the front-end, as required) Supported Platforms ------------------- The following table lists the commercially-supported platforms and versions for the Chef Infra Server: | Platform | Architecture | Version | | --- | --- | --- | | Amazon Linux 2 | `x86_64` | `2.x` | | CentOS | `x86_64` | `7.x`, `8.x` | | Oracle Enterprise Linux | `x86_64` | `7.x`, `8.x` | | Red Hat Enterprise Linux | `x86_64` | `7.x`, `8.x` | | SUSE Enterprise Linux Server | `x86_64` | `12.x`, `15.x` | | Ubuntu | `x86_64` | `16.04`, `18.04`, `20.04` | Prerequisites ------------- The Chef Infra Server has the following prerequisites: * An x86_64 compatible system architecture; Red Hat Enterprise Linux and CentOS may require updates prior to installation * A resolvable hostname that is specified using a FQDN or an IP address * A connection to Network Time Protocol (NTP) to prevent clock drift * If host-based firewalls (iptables, ufw, etc.) are being used, ensure that ports 80 and 443 are open. See the [firewalls](../server/install_server_pre/index#firewalls) section of the install prerequisites for additional details. * A local mail transfer agent that allows the Chef Infra Server to send email notifications * Using cron and the `/etc/cron.d` directory for periodic maintenance tasks * Disabling the Apache Qpid daemon on CentOS and Red Hat systems. See the [Apache Qpid](../server/install_server_pre/index#apache-qpid) of the prerequisite documentation for detailed steps. * Optional. A local user account under which services will run, a local user account for PostgreSQL, and a group account under which services will run. See [UIDs and GIDs](../server/install_server_pre/index#uids-and-gids) for more information. Note See the [expanded list of prerequisites](../server/install_server_pre/index) for a detailed list of software and hardware requirements. Standalone ---------- The standalone installation of Chef Infra Server creates a working installation on a single server. This installation is also useful when you are installing Chef Infra Server in a virtual machine, for proof-of-concept deployments, or as a part of a development or testing loop. To install Chef Infra Server: 1. Download the package from <https://downloads.chef.io/chef-server/>. 2. Upload the package to the machine that will run the Chef Infra Server, and then record its location on the file system. The rest of these steps assume this location is in the `/tmp` directory. 3. As a root user, install the Chef Infra Server package on the server, using the name of the package provided by Chef. For Red Hat Enterprise Linux and CentOS: ``` sudo rpm -Uvh /tmp/chef-server-core-<version>.rpm ``` For Ubuntu: ``` sudo dpkg -i /tmp/chef-server-core-<version>.deb ``` After a few minutes, the Chef Infra Server will be installed. 4. Run the following to start all of the services: ``` sudo chef-server-ctl reconfigure ``` Because the Chef Infra Server is composed of many different services that work together to create a functioning system, this step may take a few minutes to complete. 5. Run the following command to create an administrator: ``` sudo chef-server-ctl user-create USER_NAME FIRST_NAME LAST_NAME EMAIL 'PASSWORD' --filename FILE_NAME ``` An RSA private key is generated automatically. This is the user’s private key and should be saved to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. For example: ``` sudo chef-server-ctl user-create janedoe <NAME> <EMAIL> 'abc123' --filename /path/to/janedoe.pem ``` 6. Run the following command to create an organization: ``` sudo chef-server-ctl org-create short_name 'full_organization_name' --association_user user_name --filename ORGANIZATION-validator.pem ``` For example: ``` sudo chef-server-ctl org-create 4thcafe 'Fourth Cafe, Inc.' --association_user janedoe --filename /path/to/4thcafe-validator.pem ``` The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `4thcafe`. The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `'Fourth Cafe, Inc.'`. The `--association_user` option will associate the `user_name` with the `admins` security group on the Chef Infra Server. An RSA private key is generated automatically. This is the chef-validator key and should be saved to a safe location. The `--filename` option will save the RSA private key to the specified absolute path. Update Configuration for Purchased Nodes ---------------------------------------- To use more than 25 nodes, you’ll need to change Chef Infra Server configuration for the server to recognize your purchased licenses. Edit your `/etc/opscode/chef-server.rb` file by following the process below: 1. On your Chef Infra Server, if the `chef-server.rb` file does not exist, create it. ``` sudo mkdir /etc/opscode && sudo touch /etc/opscode/chef-server.rb ``` 2. Open up the newly created `chef-server.rb` file in your favorite text editor, for example: ``` sudo vi /etc/opscode/chef-server.rb ``` 3. Paste or add the following text. Please note the placement of the single quotation (') marks. If you’re using the vi text editor, you’ll need to use the i key to insert the text. ``` license['nodes'] = N where N is the number of licensed nodes you have purchased ``` 4. Save the file. If you’re using vi, from the example above, use the esc key and then: ``` :wq ``` 5. Run `chef-server-ctl reconfigure` for the changes to be picked up by your Chef Infra Server. ``` sudo chef-server-ctl reconfigure ``` For more information on configuring your Chef Infra Server, see [chef-server.rb Settings](../server/config_rb_server/index) and [chef-server.rb Optional Settings](../server/config_rb_server_optional_settings/index). High Availability ----------------- The following links describe how to configure the Chef Infra Server for high availability. The **Backend Cluster** setup is strongly recommended for new installations: * [High Availability using Backend Cluster](../server/install_server_ha/index) Tiered (Single Backend) ----------------------- The following link describes how to configure the Chef Infra Server with a single backend machine and multiple frontend machines. Note that this process has been deprecated in favor of a [Backend Cluster](../server/install_server_ha/index) setup: * [Tiered Installation](../server/install_server_tiered/index) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/install_server/Chef Infra Server Prerequisites =============================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/install_server_pre.md) The following is a detailed discussion of the prerequisites for every installation of the Chef Infra Server. See [Install Chef Infra Server](../server/install_server/index) for installation instructions. Platforms --------- The following table lists the commercially-supported platforms and versions for the Chef Infra Server: | Platform | Architecture | Version | | --- | --- | --- | | Amazon Linux 2 | `x86_64` | `2.x` | | CentOS | `x86_64` | `7.x`, `8.x` | | Oracle Enterprise Linux | `x86_64` | `7.x`, `8.x` | | Red Hat Enterprise Linux | `x86_64` | `7.x`, `8.x` | | SUSE Enterprise Linux Server | `x86_64` | `12.x`, `15.x` | | Ubuntu | `x86_64` | `16.04`, `18.04`, `20.04` | ### Untested Platforms The following platforms are not tested by Chef Software: * Any Linux or UNIX distribution that is not listed as a Foundational platform. * Microsoft Windows * 32-bit architectures Capacity Planning ----------------- Read the [guidance around capacity planning](../server/index#capacity-planning) for information about how to choose the right topology for the Chef Infra Server. Hardware Requirements --------------------- All machines in a Chef Infra Server deployment have the following hardware requirements. Disk space for standalone and backend servers should scale up with the number of nodes that the servers are managing. A good rule to follow is to allocate 2 MB per node. The disk values listed below should be a good default value that you will want to modify later if/when your node count grows. Fast, redundant storage (SSD/RAID-based solution either on-prem or in a cloud environment) is preferred. **All Deployments** * 64-bit CPU architecture * CPU support for SSE4.2 extensions (Xeons starting in 2007 and Opterons in 2012) **Standalone Deployments** * 4 total cores (physical or virtual) * 8 GB of RAM or more * 5 GB of free disk space in `/opt` * 10 GB of free disk space in `/var` For a high availability deployment: **General Requirements** * Three backend servers; as many frontend servers as required * 1 x GigE NIC interface (if on premises) **Frontend Requirements** * 4 cores (physical or virtual) * 4GB RAM * 20 GB of free disk space (SSD if on premises, Premium Storage in Microsoft Azure, EBS-Optimized GP2 in AWS) **Backend Requirements** * 2 cores (physical or virtual) * 8GB RAM * 50 GB/backend server (SSD if on premises, Premium Storage in Microsoft Azure, EBS-Optimized GP2 in AWS) Warning The Chef Infra Server MUST NOT use a network file system of any type—virtual or physical—for backend storage. The Chef Infra Server database operates quickly. The behavior of operations, such as the writing of log files, will be unpredictable when run over a network file system. Software Requirements --------------------- Before installing the Chef Infra Server, ensure that each machine has the following installed and configured properly: * **Hostnames** — Ensure that all systems have properly configured hostnames. The hostname for the Chef Infra Server must be a FQDN, have fewer than 64 characters including the domain suffix, be lowercase, and resolvable. See [Hostnames, FQDNs](../install_server_pre#hostnames) for more information * **FQDNs** — Ensure that all systems have a resolvable FQDN * **NTP** — Ensure that every server is connected to NTP; the Chef Infra Server is sensitive to clock drift * **Mail Relay** — The Chef Infra Server uses email to send notifications for various events; a local mail transfer agent should be installed and available to the Chef server * **cron** — Periodic maintenance tasks are performed using cron * **git** — git must be installed so that various internal services can confirm revisions * **Apache Qpid** — This daemon must be disabled on CentOS and Red Hat systems * **Required users** — If the environment in which the Chef Infra Server will run has restrictions on the creation of local user and group accounts, ensure that the correct users and groups exist before reconfiguring * **Firewalls and ports** — If host-based firewalls (iptables, ufw, etc.) are being used, ensure that ports 80 and 443 are open. In addition: * **Browser** — Firefox, Google Chrome, Safari, or Internet Explorer (versions 9 or better) * **Chef Infra Client communication with the Chef Infra Server** The Chef Infra Server must be able to communicate with every node that will be configured by Chef Infra Client and every workstation that will upload data to the Chef Infra ### UIDs and GIDs The installation process for the Chef Infra Server requires the use of at least two user and group identifiers (UIDs and GIDs). These are used to create the `opscode` and `opscode-pgsql` users and their default groups. Note The creation of required user and group identifiers is done **automatically** during the installation process for the Chef Infra Server; however, the following user and group accounts **may** be created in advance of installing the Chef Infra Server if specific UIDs and GIDs are preferred. The user **and** group must be created as a pair to satisfy reconfiguration requirements. * A local user account named `opscode` under which services will run * A local user account named `opscode-pgsql` that is used by PostgreSQL * A group account for each user account, one named `opscode` and the other named `opscode-pgsql` under which services will run Warning If the UID and GID of `opscode` and `opscode-pgsql` do not match on both backend Chef Infra Server machines, a high availability configuration will not run correctly. The embedded Chef Infra Server cookbooks can handle two cases: * Both `opscode` and `opscode-pgsql` user and group not found on the new server * Both `opscode` and `opscode-pgsql` user and group found on the new server Having only the group and not the corresponding users present during a chef-server-ctl reconfigure is unsupported and may lead to an error in the reconfiguration run. To determine the current range of IDs, run the following command: ``` grep -E '(UID|GID)' /etc/login.defs ``` The defaults for CentOS and Red Hat Enterprise Linux systems look like this: ``` UID_MIN 500 UID_MAX 60000 GID_MIN 500 GID_MAX 60000 ``` If the defaults have been changed for any reason, and if that change would result in less than 2 UID/GIDs being available to the `useradd` program, edit `/etc/login.defs` with changes to make at least 2 more UIDs and GIDs available for association. The currently used ID ranges for UIDs and GIDs can be found in `/etc/passwd` and `/etc/group`, respectively. If the `opscode` and `opscode-pgsql` user and group identifiers exist prior to installing the Chef Infra Server, the Chef Infra Server installation process will use the existing identifiers instead of creating them. ### Firewalls #### iptables To allow access to your Chef Infra Server on ports 80 and 443 via the iptables firewall, issue the following command with root privileges: ``` iptables -A INPUT -p tcp -m multiport --destination-ports 80,443 -j ACCEPT ``` Note that you will need to make use of a tool such as [iptables-persistent](https://packages.ubuntu.com/xenial/admin/iptables-persistent) to restore your iptables rules upon reboot. #### FirewallD On RHEL and CentOS versions 7 and above, the FirewallD firewall is enabled by default. Issue the following command with root privileges to open ports 80 and 443: ``` firewall-cmd --permanent --zone public --add-service http && firewall-cmd --permanent --zone public --add-service https && firewall-cmd --reload ``` #### UFW While UFW is installed on Ubuntu, it is not enabled by default. However, if you wish to use a UFW-based firewall on your Chef Infra Server, issue the following command with root privileges to open ports 80 and 443: ``` ufw allow proto tcp from any to any port 80,443 ``` ### Security Modules #### SELinux On CentOS and Red Hat Enterprise Linux systems, SELinux is enabled in enforcing mode by default. The Chef Infra Server does not have a profile available to run under SELinux. In order for the Chef Infra Server to run, SELinux must be disabled or set to `Permissive` mode. To determine if SELinux is installed, run the following command: ``` getenforce ``` If a response other than `"Disabled"` or `"Permissive"` is returned, SELinux must be disabled. To set SELinux to `Permissive` mode, run: ``` setenforce Permissive ``` and then check the status: ``` getenforce ``` #### AppArmor On Ubuntu systems, AppArmor is enabled in enforcing mode by default. Chef products do not have a profile available to run under AppArmor. In order for the Chef products to run, AppArmor must set to `Complaining` mode or disabled. To determine if AppArmor is installed, run the following command: ``` sudo apparmor_status ``` To install AppArmor, run the following command: ``` sudo apt-get install apparmor-utils -yes ``` If a response other than `"0 processes are in enforce mode"` or `"0 profiles are in enforce mode."` is returned, AppArmor must be set to `Complaining` mode or disabled. To set AppArmor to `Complaining` mode, run: ``` sudo aa-complain /etc/apparmor.d/* ``` Or to disable AppArmor entirely, run: ``` sudo invoke-rc.d apparmor kill sudo update-rc.d -f apparmor remove ``` and then check the status: ``` sudo apparmor_status ``` ### Apache Qpid On CentOS and Red Hat Enterprise Linux systems, the Apache Qpid daemon is installed by default. To determine if Apache Qpid is installed, run the following command: ``` rpm -qa | grep qpid ``` If Apache Qpid is installed, a response similar to the following is displayed: ``` qpid-cpp-server-0.12-6.el6.x86_64 ``` To disable Apache Qpid run: ``` service qpidd stop ``` and then: ``` chkconfig --del qpidd ``` ### cron Periodic maintenance tasks are performed on the Chef Infra Server servers via cron and the `/etc/cron.d` directory. With certain CentOS 6 configurations, an additional step is required to install crontab: ``` yum install crontabs ``` ### Enterprise Linux Updates The Chef Infra Server requires an x86_64 compatible systems architecture. When the Chef Infra Server is installed on Red Hat Enterprise Linux or CentOS, run `yum update` prior to installing the Chef Infra Server. This will ensure those platforms are fully compatible with this requirement. ### IP Addresses Unless you intend to operate the Chef Infra Server in IPv6 mode, you should disable ipv6 in the system’s `/etc/hosts` file by commenting out or removing all references to IPv6 addresses like “::1” or “fe80:db8:85a3:8d3:1319:8a2e:370:7348”. Without these changes, a Chef Infra Server install intended to run in ipv4 mode will mistakenly only start the postgres service on the ipv6 loopback address of “::1” rather than the ipv4 loopback address of 127.0.0.1. This will make further progress through an initial reconfiguration impossible. ### Hostnames The hostname for the Chef Infra Server may be specified using a FQDN or an IP address. This hostname must be resolvable, be 64 characters or less, and be lowercase. For example, a Chef Infra Server running in a production environment with a resolvable FQDN hostname can be added the DNS system. But when deploying Chef Infra Server into a testing environment, adding the hostname to the `/etc/hosts` file is enough to ensure that hostname is resolvable. * **FQDN Hostnames** When the hostname for the Chef Infra Server is a FQDN be sure to include the domain suffix. For example, something like `mychefserver.example.com` (and not something like `mychefserver`). * **IP Address Hostnames** When the Chef Infra Server is run in IPv6 mode, a hostname specified using an IP address must also be bracketed (`[ ]`) or the Chef Infra Server will not be able to recognize it as an IPv6 address. For example: ``` bookshelf['url'] "https://[2001:db8:85a3:8d3:1319:8a2e:370:7348]" ``` The `api_fqdn` setting can be added to the private-chef.rb file (it is not there by default). When added, its value should be equal to the FQDN or IP address for the service URI used by the Chef Infra Server. Then configure the same value for the `bookshelf['vip']` setting prior to installing the Chef Infra Server. For example: `api_fqdn "chef.example.com"` or `api_fqdn 123.45.67.890`. #### Configure Hostnames Use the following sections to verify the hostnames that is used by the Chef Infra Server. **To verify if a hostname is a FQDN** To verify if a hostname is a FQDN, run the following command: ``` hostname ``` If the hostname is a FQDN, it will return something like: ``` mychefserver.example.com ``` If the hostname is not a FQDN, it must be configured so that it is one. **To verify the FQDN is all lowercase** To verify if the alphabetic parts of a FQDN are all lowercase, run the following command: ``` hostname -f | grep -E '^([[:digit:]]|[[:lower:]]|\.|-|_)+$' && echo yes ``` If the hostname is all lowercase, it will return something like: ``` mychefserver.example.com yes ``` If the hostname’s alphabetic parts are not all lowercase, it must be configured so that they are. **To verify a hostname is resolvable** To verify is a hostname is resolvable, run the following command: ``` hostname -f ``` If the hostname is resolvable, it will return something like: ``` mychefserver.example.com ``` **To change a hostname** In some cases, the hostname for the Chef Infra Server needs to be updated. The process for updating a hostname varies, depending on the platform on which the Chef Infra Server will run. Refer to the manual for the platform or contact a local systems administrator for specific guidance for a specific platform. The following example shows how a hostname can be changed when running Red Hat or CentOS: ``` sudo hostname 'mychefserver.example.com' ``` and then: ``` echo "mychefserver.example.com" | sudo tee /etc/hostname ``` **To add a hostname to /etc/hosts** If a hostname is not resolvable, refer to a local systems administrator for specific guidance on how to add the hostname to the DNS system. If the Chef Infra Server is being into a testing environment, just add the hostname to `/etc/hosts`. The following example shows how a hostname can be added to `/etc/hosts` when running Red Hat or CentOS: ``` echo -e "127.0.0.2 `hostname` `hostname -s`" | sudo tee -a /etc/hosts ``` Warning The FQDN for the Chef Infra Server should be resolvable, lowercase, and should not exceed 64 characters when using OpenSSL, as OpenSSL requires the `CN` in a certificate to be no longer than 64 characters. ### Mail Relay The Chef Infra Server server uses email to send notifications for various events: * Password resets * User invitations * Failover notifications * Failed job notifications Configure a local mail transfer agent on the Chef Infra Server using the steps appropriate for the platform on which the Chef Infra Server is running. ### NTP The Chef Infra Server requires that the systems on which it is running be connected to Network Time Protocol (NTP), as the Chef Infra Server is particularly sensitive to clock drift. For Red Hat and CentOS 6: ``` yum install ntp ``` or: ``` chkconfig ntpd on ``` or: ``` service ntpd start ``` For Ubuntu: ``` apt-get install ntp ``` #### Chef Infra Client The Chef Infra Server server requires that every node that is under management by Chef also have an accurate clock that is synchronized very closely with the clock on the Chef Infra Server. If the clocks are not synchronized closely, the authentication process may fail when the clocks are out-of-sync by more than 15 minutes. A failure will trigger a `401 Unauthorized` response similar to: ``` [Tue, 01 Nov 2011 16:55:23 -0700] INFO: *** Chef 11.X.X *** [Tue, 01 Nov 2011 16:55:23 -0700] INFO: Client key /etc/chef/client.pem is not present - registering [Tue, 01 Nov 2011 16:55:24 -0700] INFO: HTTP Request Returned 401 Unauthorized: Failed to authenticate as ORGANIZATION-validator. Synchronize the clock on your host. [Tue, 01 Nov 2011 16:55:24 -0700] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out [Tue, 01 Nov 2011 16:55:24 -0700] FATAL: Net::HTTPClientException: 401 "Unauthorized" ``` In this situation, re-synchronize the system clocks with the Network Time Protocol (NTP) server, and then re-run Chef Infra Client. ### Required Accounts By default, accounts required by the Chef Infra Server are created during setup. If your environment has restrictions on the creation of local user and group accounts that will prevent these accounts from being created automatically during setup, you will need to create these accounts. #### Group Accounts The following group accounts are required: | Group Account | Description | | --- | --- | | `opscode` | The group name under which services will run. | #### User Accounts The following user accounts are required: | User Account | Description | | --- | --- | | `opscode` | The user name under which services will run. | | `opscode-pgsql` | The user name for PostgreSQL. (This is only required on the back end servers in a high availability setup.) | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/install_server_pre/About Ohai ========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/ohai.md) Ohai is a tool for collecting system configuration data, which it then provides to Chef Infra Client to use in cookbooks. Chef Infra Client runs Ohai at the start of every Chef Infra run to determine system state. The attributes that Ohai collects are called `automatic attributes`. Chef Infra Client uses these attributes to ensure that nodes are in the desired state after each configuration run. The types of attributes Ohai collects include but are not limited to: * Operating System * Network * Memory * Disk * CPU * Kernel * Host names * Fully qualified domain names * Virtualization * Cloud provider metadata Ohai includes required and optional plugins to detect common configuration information. Ohai has a plugin model and language to write [custom plugins](ohai_custom/index) to collect additional system state information. Ohai collects data for many platforms, including AIX, macOS, Linux, FreeBSD, Solaris, and any Microsoft Windows operating systems. See the [Chef Infra Client release notes](https://docs.chef.io/release_notes_client/) for the latest information on Ohai. Automatic Attributes -------------------- Note Attributes can be configured in cookbooks (attribute files and recipes), roles, and environments. In addition, Ohai collects attribute data about each node at the start of a Chef Infra Client run. See [Attributes](attributes/index) for more information about how all of these attributes fit together. An automatic attribute is a specific detail about a node, such as an IP address, a host name, a list of loaded kernel modules, and so on. Automatic attributes are detected by Ohai and are then used by Chef Infra Client to ensure that they are handled properly during every Chef Infra Client run. The most commonly accessed automatic attributes are: | Attribute | Description | | --- | --- | | `node['platform']` | The platform on which a node is running. This attribute helps determine which providers will be used. | | `node['platform_family']` | The platform family is a Chef Infra specific grouping of similar platforms where cookbook code can often be shared. For example, `rhel` includes Red Hat Linux, Oracle Linux, CentOS, and several other platforms that are nearly identical to Red Hat Linux. | | `node['platform_version']` | The version of the platform. This attribute helps determine which providers will be used. | | `node['ipaddress']` | The IP address for a node. If the node has a default route, this is the IPV4 address for the interface. If the node does not have a default route, the value for this attribute should be `nil`. The IP address for default route is the recommended default value. | | `node['macaddress']` | The MAC address for a node, determined by the same interface that detects the `node['ipaddress']`. | | `node['fqdn']` | The fully qualified domain name for a node. This is used as the name of a node unless otherwise set. | | `node['hostname']` | The host name for the node. | | `node['domain']` | The domain for the node. | | `node['recipes']` | A list of recipes associated with a node (and part of that node's run-list). | | `node['roles']` | A list of roles associated with a node (and part of that node's run-list). | | `node['ohai_time']` | The time at which Ohai was last run. This attribute is not commonly used in recipes, but it is saved to the Chef Infra Server and can be accessed using the `knife status` subcommand. | ### Get a list of automatic attributes for a node Ohai collects a list of automatic attributes at the start of each Chef Infra Client run. This list will vary from organization to organization, by server type, and by the platform that runs those servers. All the attributes collected by Ohai are unmodifiable by Chef Infra Client. Run the `ohai` command on a system to see which automatic attributes Ohai has collected for a particular node. ### Attributes Blocklist Warning When attribute blocklist settings are used, any attribute defined in a blocklist will not be saved to the Chef Infra Server and any attribute that is not defined in a blocklist will be saved. Each attribute type must be blocklisted independently of the other attribute types. For example, if `blocked_automatic_attributes` defines attributes that will not be saved, but `blocked_normal_attributes`, `blocked_default_attributes`, and `blocked_override_attributes` are not defined, then all normal attributes, default attributes, and override attributes will be saved, as well as the automatic attributes that were not specifically excluded through blocklisting. Attributes that should not be saved by a node may be blocklisted in the [client.rb](config_rb_client/index) file. The blocklist is a Hash of keys that specify each attribute to be filtered out. Attributes are blocklisted by attribute type, with each attribute type being blocklisted independently. Each attribute type—`automatic`, `default`, `normal`, and `override`—may define blocklists by using the following settings in the client.rb file: | Setting | Description | | --- | --- | | `blocked_automatic_attributes` | A hash that blocklists `automatic` attributes, preventing blocklisted attributes from being saved. For example: `['network/interfaces/eth0']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | | `blocked_default_attributes` | A hash that blocklists `default` attributes, preventing blocklisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | | `blocked_normal_attributes` | A hash that blocklists `normal` attributes, preventing blocklisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | | `blocked_override_attributes` | A hash that blocklists `override` attributes, preventing blocklisted attributes from being saved. For example: `['map - autohome/size']`. Default value: `nil`, all attributes are saved. If the array is empty, all attributes are saved. | #### Blocklisting Ohai (automatic) Attributes The recommended practice is to use `blocked_automatic_attributes` to block attributes populated by Ohai’s system information gathering. Ohai gathers a large number of attributes that can consume a signicant amount of storage space on the Chef Infra Server. Many of these attributes may be considered highly valuable, while others could be blocklisted without any impact to data available in search. Normal, default, and override attributes are typically much more important attributes used within cookbooks and are more likely to cause issues if they are blocklisted incorrectly. For example, automatic attribute data similar to: ``` { "filesystem" => { "/dev/disk0s2" => { "size" => "10mb" }, "map - autohome" => { "size" => "10mb" } }, "network" => { "interfaces" => { "eth0" => {...}, "eth1" => {...}, } } } ``` To blocklist the `filesystem` attributes and allow the other attributes to be saved, update the client.rb file: ``` blocked_automatic_attributes ['filesystem'] ``` When a blocklist is defined, any attribute of that type that is not specified in that attribute blocklist **will** be saved. So based on the previous blocklist for automatic attributes, the `filesystem` and `map - autohome` attributes will not be saved, but the `network` attributes will. For attributes that contain slashes (`/`) within the attribute value, such as the `filesystem` attribute `'/dev/diskos2'`, use an array. For example: ``` blocked_automatic_attributes [['filesystem', '/dev/diskos2']] ``` ### Attribute Allowlist Warning When attribute allowlist settings are used, only the attributes defined in a allowlist will be saved and any attribute that is not defined in a allowlist will not be saved. Each attribute type is allowlisted independently of the other attribute types. For example, if `automatic_attribute_allowlist` defines attributes to be saved, but `normal_attribute_allowlist`, `default_attribute_allowlist`, and `override_attribute_allowlist` are not defined, then all normal attributes, default attributes, and override attributes are saved, as well as the automatic attributes that were specifically included through allowlisting. Attributes that should be saved by a node may be allowlisted in the client.rb file. The allowlist is a hash of keys that specifies each attribute to be saved. Attributes are allowlisted by attribute type, with each attribute type being allowlisted independently. Each attribute type—`automatic`, `default`, `normal`, and `override`—may define allowlists by using the following settings in the client.rb file: | Setting | Description | | --- | --- | | `allowed_automatic_attributes` | A hash that allowlists `automatic` attributes, preventing non-allowlisted attributes from being saved. For example: `['network/interfaces/eth0']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | | `allowed_default_attributes` | A hash that allowlists `default` attributes, preventing non-allowlisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | | `allowed_normal_attributes` | A hash that allowlists `normal` attributes, preventing non-allowlisted attributes from being saved. For example: `['filesystem/dev/disk0s2/size']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | | `allowed_override_attributes` | A hash that allowlists `override` attributes, preventing non-allowlisted attributes from being saved. For example: `['map - autohome/size']`. Default value: `nil`, all attributes are saved. If the hash is empty, no attributes are saved. | #### Allowlisting Ohai (automatic) Attributes The recommended practice is to use `allowed_automatic_attributes` to allow specific attributes populated by Ohai’s system information gathering. Ohai gathers a large number of attributes that can consume a signicant amount of storage space on the Chef Infra Server. Many of these attributes may be considered highly valuable, while others could be skipped without any impact to data available in search. Normal, default, and override attributes are typically much more important attributes used within cookbooks and are more likely to cause issues if they are ommited from an allowlist incorrectly. For example, automatic attribute data similar to: ``` { "filesystem" => { "/dev/disk0s2" => { "size" => "10mb" }, "map - autohome" => { "size" => "10mb" } }, "network" => { "interfaces" => { "eth0" => {...}, "eth1" => {...}, } } } ``` To allowlist the `network` attributes and prevent the other attributes from being saved, update the client.rb file: ``` allowed_automatic_attributes ['network/interfaces/'] ``` When a allowlist is defined, any attribute of that type that is not specified in that attribute allowlist **will not** be saved. So based on the previous allowlist for automatic attributes, the `filesystem` and `map - autohome` attributes will not be saved, but the `network` attributes will. Leave the value empty to prevent all attributes of that attribute type from being saved: ``` allowed_automatic_attributes [] ``` For attributes that contain slashes (`/`) within the attribute value, such as the `filesystem` attribute `'/dev/diskos2'`, use an array. For example: ``` allowed_automatic_attributes [['filesystem', '/dev/diskos2']] ``` Default Plugins --------------- The following list shows the type of plugins that are included with Ohai. See the `ohai/lib/ohai/plugins` directory in the version of Ohai installed on your system for the full list: ### General Purpose Plugins ``` azure.rb c.rb chef.rb cloud.rb command.rb cpu.rb digital_ocean.rb dmi.rb docker.rb ec2.rb elixir.rb erlang.rb eucalyptus.rb filesystem.rb freebsd gce.rb go.rb groovy.rb haskell.rb hostname.rb init_package.rb java.rb joyent.rb kernel.rb keys.rb languages.rb libvirt.rb linode.rb lua.rb mono.rb network.rb nodejs.rb ohai_time.rb ohai.rb memory.rb network.rb platform.rb openstack.rb os.rb packages.rb perl.rb php.rb platform.rb powershell.rb ps.rb python.rb rackspace.rb root_group.rb ruby.rb rust.rb scala.rb scaleway.rb shard.rb shells.rb softlayer.rb ssh_host_key.rb timezone.rb uptime.rb virtualbox.rb vmware.rb zpools.rb ``` ### Platform Specific Plugins ``` aix kernel.rb memory.rb network.rb platform.rb uptime.rb virtualization.rb bsd virtualization.rb darwin cpu.rb filesystem.rb hardware.rb memory.rb network.rb platform.rb system_profiler.rb virtualization.rb dragonflybsd cpu.rb memory.rb network.rb os.rb platform.rb freebsd cpu.rb memory.rb network.rb os.rb platform.rb linux block_device.rb cpu.rb filesystem.rb fips.rb hostnamectl.rb lsb.rb machineid.rb mdadm.rb memory.rb network.rb platform.rb sessions.rb virtualization.rb netbsd cpu.rb memory.rb network.rb platform.rb openbsd cpu.rb memory.rb network.rb platform.rb solaris2 cpu.rb dmi.rb filesystem.rb memory.rb network.rb platform.rb virtualization.rb windows cpu.rb drivers.rb filesystem.rb fips.rb memory.rb network.rb platform.rb system_enclosure.rb virtualization.rb ``` Optional Plugins ---------------- Ohai ships several optional plugins that you can enable in the [client.rb configuration file](config_rb_client/index). * `:Grub2` - Information from the Linux Grub2 bootloader * `:IPC` - SysV IPC shmem information (New in Chef Infra Client 16) * `:Interupts` - Data from /proc/interrupts and /proc/irq (New in Chef Infra Client 16) * `:Lspci` - PCI device information on Linux hosts. * `:Lsscsi` - SCSI device information on Linux hosts. * `:Passwd` - User and Group information on non-Windows hosts. This plugin can result in large node sizes if a system connects to Active Directory or LDAP. * `:Sessions` - Sessions data from loginctl on Linux hosts. * `:Sysctl` - All sysctl values on Linux hosts. ### Enabling Optional Plugins Optional plugins can be enabled in the [client.rb configuration file](config_rb_client/index): ``` ohai.optional_plugins = [ :Sessions, :Lspci, ] ``` Note The Ohai optional_plugins config array must contain an array of plugin names as Symbols not Strings. Ohai Settings in client.rb -------------------------- Ohai configuration settings can be added to the client.rb file. `ohai.directory` The directory in which Ohai plugins are located. `ohai.disabled_plugins` An array of Ohai plugins to be disabled on a node. The list of plugins included in Ohai can be found in the [ohai/lib/ohai/plugins](https://github.com/chef/ohai/tree/main/lib/ohai/plugins) source. For example, disabling a single plugin: ``` ohai.disabled_plugins = [ :MyPlugin ] ``` or disabling multiple plugins: ``` ohai.disabled_plugins = [ :MyPlugin, :MyPlugin2, :MyPlugin3 ] ``` When a plugin is disabled, the Chef Infra Client log file will contain entries similar to: ``` [2014-06-13T23:49:12+00:00] DEBUG: Skipping disabled plugin MyPlugin ``` `ohai.hints_path` The path to the file that contains hints for Ohai. `ohai.log_level` The level of logging to be stored in a log file. `ohai.log_location` The location of the log file. `ohai.plugin_path` An array of paths at which Ohai plugins are located. Default value: `[<CHEF_GEM_PATH>/ohai-9.9.9/lib/ohai/plugins]`. When custom Ohai plugins are added, the paths must be added to the array. For example, a single plugin: ``` ohai.plugin_path << '/etc/chef/ohai_plugins' ``` and for multiple plugins: ``` ohai.plugin_path += [ '/etc/chef/ohai_plugins', '/path/to/other/plugins' ] ``` Note The Ohai executable ignores settings in the client.rb file when Ohai is run independently of Chef Infra Client. Custom Plugins -------------- Custom Ohai plugins can be written to collect additional information from systems as necessary. See the [Ohai Custom Plugins](ohai_custom/index) docs for more information. Hints ----- Ohai hints are used to tell Ohai something about the system that it is running on that it would not be able to discover itself. An Ohai hint exists if a JSON file exists in the hint directory with the same name as the hint. For example, calling `hint?('antarctica')` in an Ohai plugin would return an empty hash if the file `antarctica.json` existed in the hints directory, and return nil if the file does not exist. If the hint file contains JSON content, it will be returned as a hash from the call to `hint?`. ``` { "snow": true, "penguins": "many" } ``` ``` antarctica_hint = hint?('antarctica') if antarctica_hint['snow'] "There are #{antarctica_hint['penguins']} penguins here." else 'There is no snow here, and penguins like snow.' end ``` Hint files are located in the `/etc/chef/ohai/hints/` directory by default. Use the `Ohai.config[:hints_path]` setting in the [client.rb configuration file](config_rb_client/index) to customize this location. `ohai` Resource ---------------- Chef Infra Client includes an `ohai` resource that allows you to reload the Ohai data on a node. This allows recipes or resources that change system attributes (like a recipe that adds a user) to refer to those attributes later on during a Chef Infra Client run. See the [ohai resource](resources/ohai) for complete usage information. ohai Command Line Tool ---------------------- Ohai can be run on the command line outside of the Chef Infra Client run. See [Ohai (executable)](ctl_ohai) for more information. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ohaiAbout Chef Licenses =================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_license.md) All Chef products have a license that governs the entire product, while some have separate licenses for the project source code and the distribution that we build from it. Third-party software included in our distributions may have individual licenses, which are listed in the `/opt/<PRODUCT-NAME>/LICENSE` file. Individual copies of all referenced licenses can be found in the `/opt/<PRODUCT-NAME>/LICENSES` directory. In April 2019 many of our software distributions switched to being governed under the Chef EULA, while the software projects remained governed by the Apache 2.0 license. To understand which license applies to those distributions, see the [versions page](versions/index). General information about this change can be found in our [announcement](https://blog.chef.io/2019/04/02/chef-software-announces-the-enterprise-automation-stack/). Chef EULA --------- The commercial distributions of our products—such as Chef Infra Client, Chef Habitat, or Chef InSpec— are governed by either the [Chef End User License Agreement (Chef EULA)](https://www.chef.io/end-user-license-agreement) or your commercial agreement with Progress Software Corporation as a customer. You are required to accept these terms when using the distributions for the first time. For additional information on how to accept the license, see [Accepting the Chef License](chef_license_accept/index) documentation. Chef MLSA --------- Distributions of older proprietary Chef products—such as Chef Automate 1.x and the Chef Management Console—are governed by the [Chef Master License and Services Agreement (Chef MLSA)](https://www.chef.io/online-master-agreement), which must be accepted as part of any install or upgrade process. Apache 2.0 ---------- All source code of our open source Chef projects—such as Chef Infra Client, Chef Automate, or Chef InSpec—are governed by the [Apache 2.0 license](https://www.apache.org/licenses/LICENSE-2.0). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_license.htmlAccepting the Chef License ========================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/chef_license_accept.md) This page aims to document how to accept the Chef license for all Chef Software products. For an overview of the license, see the [Chef license](chef_license/index) documentation. There are two types of license: MLSA and EULA. The MLSA applies to customers with a commercial contract with Chef Software, and the EULA covers all other cases. Accept the Chef MLSA -------------------- There are three ways to accept the Chef MLSA: 1. When running `chef-<PRODUCT-NAME>-ctl reconfigure` the Chef MLSA is printed. Type `yes` to accept it. Anything other than typing `yes` rejects the Chef MLSA, and the upgrade process will exit. Typing `yes` adds a `.license.accepted` file to the `/etc/chef/accepted_licenses/<PRODUCT-NAME>` file. As long as this file exists in this directory, the Chef MLSA is accepted and the reconfigure process will not prompt for `yes`. 2. Run the `chef-<PRODUCT-NAME>-ctl reconfigure` command using the `--chef-license=accept` option. This automatically types `yes` and skips printing the Chef MLSA. 3. Add a `.license.accepted` file to the `/var/opt/<PRODUCT-NAME>/` directory. The contents of this file do not matter. As long as this file exists in this directory, the Chef MLSA is accepted and the reconfigure process will not prompt for `yes`. Accept the Chef EULA -------------------- Products below are split below into two categories: workstation and server. Affected product versions which require accepting the EULA to use are shown. Versions before this do not require accepting the EULA. More information on supported versions can be seen at the [Supported Versions](versions/index) documentation. ### Workstation Products * Chef Workstation >= 0.4, which also contains: + Chef Infra Client + Chef InSpec * Chef Infra Client >= 15.0 * Chef InSpec >= 4.0 * Chef Habitat >= 0.80 These products are typically installed on a user’s workstation. Two methods are generally used to accept the license for these products: 1. `--chef-license <value>` argument passed to the command line invocation. 2. `CHEF_LICENSE="<value>"` as an environment variable. `<value>` can be specified as one of the following: 1. `accept` - Accepts the license and attempts to persist a marker file locally. Persisting these marker files means future invocations do not require accepting the license again. 2. `accept-silent` - Similar to `accept` except no messaging is sent to STDOUT 3. `accept-no-persist` - Similar to `accept-silent` except no marker file is persisted. Future invocation will require accepting the license again. If no command line argument or environment variable is set, these products will attempt to request acceptance through an interactive prompt. If the prompt cannot be displayed, then the product will fail with an exit code 172. If the product attempts to persist the accepted license and fails, a message will be sent to STDOUT, but product invocation will continue successfully. In a future invocation, however, the license would need to be accepted again. Please see [License File Persistence](https://github.com/chef/license-acceptance#license-file-persistence) for details about persisted marker files. The `--chef-license` command line argument is not backwards compatible to older non-EULA versions. If you are managing a multi-version environment, we recommend using the environment variable as that is ignored by older versions. Products with specific features or differences from this general behavior are documented below. #### Chef Workstation Chef Workstation contains multiple Chef Software products. When invoking the `chef` command line tool and accepting the license, users are required to accept the license for all the embedded products as well. The same license applies to all products, but each product must have its own license acceptance. `chef <command> --chef-license accept` will accept the license for Chef Workstation, Chef Infra Client, and Chef InSpec. For example, `chef env --chef-license accept`. #### Chef Infra Client In addition to the above methods, users can specify `chef_license 'accept'` in their Chef Infra Client and Chef Infra Server config. On a workstation, this can be specified in `~/.chef/config.rb` or `~/.chef/knife.rb`, and on a node, it can be specified in `/etc/chef/client.rb`. This method of license acceptance is backwards-compatible to non-EULA versions of Chef Infra Client. #### Habitat Two methods are generally used to accept the Chef Habitat license: 1. Users can execute `hab license accept` on the command line. 2. Alternatively, users can set `HAB_LICENSE="<value>"` as an environment variable. `<value>` can be specified as one of the following: 1. `accept` - Accepts the license and persists a marker file locally. Future invocations do not require accepting the license again. 2. `accept-no-persist` - accepts the license without persisting an marker file. Future invocation will require accepting the license again. If the license isn’t accepted through either of these methods, Habitat will request acceptance through an interactive prompt. Additionally, to accepting the license in CI or other automation, user may choose to create an empty file on the filesystem at `/hab/accepted-licenses/habitat` (if your hab commands run as root) or at `$HOME/.hab/accepted-licenses/habitat` (if your hab commands run as a user other than root). For situations where hab commands run as multiple users, it is advisable to create both files. #### Errors If the Chef Habitat License prompt cannot be displayed, then the product fails with an exit code 172. If Chef Habitat cannot persist the accepted license, it sends a message STDOUT, but the product invocation will continue successfully. In a future invocation, however, the user will need to accept the license again. #### Chef as Habitat packages Chef Software products are also distributed as Habitat packages, such as Chef Infra Client, Chef InSpec, etc. When Chef products are installed as Habitat, the products request license acceptance at product usage time. Whether installed as system packages or as Habitat packages, users accept the licenses in the same way detailed above. ### Server Products Some Chef products distributed as Habitat packages contain servers. In these cases, Habitat runs the server products as a supervisor. See the below sections for information on how to accept the license for these products when they are distributed as Habitat packages. | Product | Version | | --- | --- | | Chef Infra Server | >= 13.0 | | Chef Automate | >= 2.0 | | Supermarket | >= 4.0 | Server products are typically installed and managed by some kind of process supervisor. Chef Software server products do not allow interactive license acceptance because process supervisors do not easily allow interactivity. Instead, the license is accepted during the `reconfigure` command or `upgrade` command for the Omnibus ctl command. For example: * `chef-server-ctl reconfigure --chef-license=accept` * `CHEF_LICENSE="accept-no-persist" supermarket-ctl reconfigure` In addition, the Chef license can be accepted via the omnibus configuration file. Specify `chef_license 'accept'` in the `chef-server.rb` or `supermarket.rb` configuration. #### Chef Automate Automate has its own reconfigure tool, `automate-ctl`. This tool walks users through the install and setup of Automate. The Chef license is accepted after that in the browser. Please follow the in-product prompts. #### Chef Infra Server When installed as a system package, users accept the license with the ctl command. For example, `chef-server-ctl reconfigure --chef-license=accept`. Acceptance can also be set in the configuration file `chef-server.rb` as `chef_license "accept"`. Chef Infra Server is also distributed as a Habitat package and ran using the Habitat supervisor. In this mode, users accept the license by setting the correct Habitat configuration values. The key is `chef_license.acceptance`. For example: Against a supervisor running Chef Infra Server, run `echo "chef_license.acceptance = accept" | hab config apply server.default 100`. See the [Habitat config updates documentation](https://www.habitat.sh/docs/using-habitat/#config-updates) for more information about how to apply this configuration to a service group. ### Remote Management Products * Test Kitchen * `knife bootstrap` in Chef Infra Client * `chef-run` in Chef Workstation * Packer * Terraform Chef Provider (Deprecated) * Vagrant These products install or manage Chef on a remote instance. If a user has accepted the appropriate product license locally, it will be automatically transferred to the remote instance. For example, if a user has accepted the Chef Infra Client license locally and converges a Test Kitchen instance with the Chef provisioner, it will succeed by copying the acceptance to the remote instance. We aim to support this behavior, so Workstation users do not have their workflow affected, but any differences from that behavior are documented below. #### Test Kitchen Test Kitchen is not owned by or covered by the Chef license, but installing Chef Infra Client on a test instance is covered by the EULA. Without accepting the license, the converge will fail on the test instance. The Chef provisioner in Test Kitchen >= 2.3 has been updated to simplify accepting this license on behalf of the test instance. Users can set the `CHEF_LICENSE` environment variable or add `chef_license: accept` to their provisioner config in their **kitchen.yml**. Specifying **accept** will attempt to persist the license acceptance locally. If a local license marker file is detected, no configuration is required; acceptance is automatically transferred to the test instance. To disable this persistence, specify `accept-no-persist` on every test instance converge. `kitchen-inspec` uses Chef InSpec as a library, and is not covered by the EULA when installed as a gem, but is covered by the EULA when packaged as part of the Chef Workstation installation. Accept the license in a similar way to the Chef Infra Client license - specify the `CHEF_LICENSE` environment variable, specify the `chef_license` config under the verifier section in `kitchen.yml` or persist the acceptance locally. ##### Test Kitchen: Pin to Chef 14 You can pin to a specific version of chef in your kitchen.yml: ``` provisioner: name: chef_zero product_name: chef product_version: 14.12.3 ``` #### `knife bootstrap` `knife` usage does not require accepting the EULA. A Chef Infra Client instance does require EULA acceptance. Using `knife bootstrap` to manage a Chef Infra Client instance will prompt a user to accept the license locally before allowing for bootstrapping the remote instance. Without this, `knife bootstrap` would fail. In most usage cases via Chef Workstation, this license will already have been accepted and will transfer across transparently. But if a user installs Chef Workstation and the first command they ever run is `knife bootstrap`, it will perform the same license acceptance flow as the Chef Infra Client product. ##### `knife bootstrap` in Chef Client 14 The `knife bootstrap` command in Chef Client 14 cannot accept the Chef Infra Client 15 EULA on remote nodes unless you use a [custom template](workstation/knife_bootstrap/index#custom-templates) and add chef_license “accept” to the client.rb. This applies to workstations who have Chef Infra Client <= 14.x, ChefDK <= 3.x or Chef Workstation <= 0.3 installed. ##### `knife bootstrap`: Pin to Chef 14 Specify the following argument: ``` knife bootstrap --bootstrap-version 14.12.3 ``` #### `chef-run` `chef-run` in Chef Workstation >= 0.3 has been updated to add support for accepting the license locally when remotely running Chef Infra Client 15. As of Chef Workstation <= 0.4 there is no way to manage the version of Chef Infra Client installed on the remote node. It defaults to the latest stable version available. To accept the license, complete one of the following three tasks. Either pass the `--chef-license` command line flag, set the `CHEF_LICENSE` environment variable, or add the following to your `~/.chef-workstation/config.toml` file: ``` [chef] chef_license = "accept" ``` #### Packer Use a custom [Chef configuration template](https://www.packer.io/docs/provisioners/chef/chef-client#chef-configuration). In your provisioners config, include: ``` { "type": "chef-client", "config_template": "path/to/client.rb" } ``` In `path/to/client.rb`, include: ``` chef_license 'accept' ``` You may also add it to the [execute_command](https://www.packer.io/docs/provisioners/chef-client.html#execute_command), but this is not backwards-compatible, so it is not suggested. ##### Packer: Pin to Chef 14 In your [Packer provisioners config](https://www.packer.io/docs/provisioners/chef-client.html#install_command), include: ``` { "type": "chef-client", "install_command": "curl -L https://omnitruck.chef.io/install.sh | sudo bash -s -- -v 14.12.9" } ``` #### Terraform Chef Provisioner Warning Terraform deprecated the Chef Provisioner in the [0.13.4](https://www.terraform.io/docs/language/resources/provisioners/chef.html) release and they will remove it in a future version. Terraform continues to support the Chef Provider. The license can be accepted via the Chef Infra Client config file, which is specified by the `client_options` [Terraform provisioner config](https://www.terraform.io/docs/provisioners/chef.html#client_options-array-): ``` provisioner "chef" { client_options = ["chef_license 'accept'"] } ``` ##### Terraform: Pin to Chef 14 In your [Terraform provisioner config](https://www.terraform.io/docs/provisioners/chef.html#version-string-), include: ``` provisioner "chef" { version = "14.12.3" } ``` #### Terraform Habitat Provisioner Default behavior of this provisioner is to install the latest version of Habitat. [Documentation for this provisioner](https://www.terraform.io/docs/provisioners/habitat.html) will be updated in the near future once the provisioner is updated with options to accept license. For the time being, the provisioner can be pinned to a prior Habitat version as below. ##### Terraform: Pin to Chef Habitat 0.79 In your [Terraform provisioner config](https://www.terraform.io/docs/provisioners/habitat.html#version-string-), include: ``` provisioner "habitat" { version = "0.79.1" } ``` #### Vagrant This license acceptance can be done via the arguments API: ``` config.vm.provision 'chef_zero' do |chef| chef.arguments = '--chef-license accept' end ``` See the [Vagrant documentation](https://www.vagrantup.com/docs/provisioning/chef_common.html#arguments) for details. The `--chef-license` argument is not backwards-compatible to non-EULA Chef Infra Client versions. So instead, users can use the [custom config path](https://www.vagrantup.com/docs/provisioning/chef_common.html#custom_config_path) and point at a local file, which specifies the `chef_license` config. The environment variable is not currently supported. ##### Vagrant: Pin to Chef 14 This version pinning can be done via the [version API](https://www.vagrantup.com/docs/provisioning/chef_common.html#version). In your Chef provisioner config: ``` config.vm.provision 'chef_zero' do |chef| chef.version = '14.12.3' end ``` ### Pre-upgrade support Chef Software aims to make upgrading from a non-EULA version to a EULA version as simple as possible. For some products (Chef Client 14.12.9, Chef InSpec 3.9.3), we added backwards-compatible support for the `--chef-license` command that performs a no-op. This allows customers to start specifying that argument in whatever way they manage those products before upgrading. Alternatively, users can specify the `CHEF_LICENSE` environment variable when invoking any of the EULA products to accept the license. This environment variable is ignored by non-EULA products, and so is backwards-compatible to older versions. #### `chef-client` cookbook For users that manage their Chef Infra Client installation using the `chef-client` cookbook, we added a new attribute that can be specified. Specify the node attribute `node['chef_client']['chef_license'] = 'accept'` when running the cookbook to apply the license acceptance in a backwards-compatible way. This functionality allows users to set that attribute for a Chef Client 14 install, upgrade to Chef Infra Client 15, and have the product continue to work correctly. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_license_accept.htmlchef (executable) ================= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/ctl_chef.md) The chef executable is a command-line tool that does the following: * Generates repositories, cookbooks, recipes, attributes, templates, and custom resources. * Installs gems into the Chef development environment’s Ruby installation. chef capture ------------ Use the `chef capture` subcommand to capture a node’s state as a local [chef-repo](../chef_repo/index). Use the generated repository if you need to converge a node locally. ### Syntax This subcommand has the following syntax: ``` chef capture NODE-NAME [options] ``` ### Options `-c`, `--credentials` Credentials file (default $HOME/.chef/credentials). `-d`, `--with-data-bags` Download all data bags as part of node capture. `-h`, `--help` Show help for the command. `-k`, `--client-key` Chef Infra Server API client key. `-n`, `--client-name` Chef Infra Server API client name. `-o`, `--ssl-no-verify` Do not verify SSL when connecting to Chef Infra Server (default: verify). `-p`, `--profile` Profile to use from credentials file (default “default”). `-s`, `--chef-server-url` Chef Infra Server URL. ### Examples **Capture a node** To capture a node in a local repository, run a command similar to: ``` chef capture test-server ``` This will return something similar to: ``` - Setting up local repository - Capturing node object 'test-server' - Capturing policy data... - Capturing cookbook artifacts... - Writing kitchen configuration... Repository has been created in './node-test-server-repo'. Next, locate version-controlled copies of the cookbooks. This is important so that you can track changes to the cookbooks as you edit them. You may have one or more existing paths where you have checked out cookbooks. If not, now is a good time to open a separate terminal and clone or check out the cookbooks. If all cookbooks are not available in the same base location, you will have a chance to provide additional locations. Press Enter to Continue: You're ready to begin! Start with 'cd ./node-test-server-repo; kitchen converge'. As you identify issues, you can modify cookbooks in their original checkout locations or in the repository's cookbooks directory and they will be picked up on subsequent runs of 'kitchen converge'. ``` See the [Upgrade Lab](../workstation/upgrade_lab/index#create-an-upgrade-environment-with-chef-capture) documentation for additional information on upgrading Chef Infra Client. chef env -------- Use the `chef env` subcommand to configure the environment for Chef Workstation. ### Syntax This subcommand has the following syntax: ``` chef env ``` ### Options This command does not have any specific options. ### Examples None. chef exec --------- Use the `chef exec` subcommand to run arbitrary shell commands with the `PATH` environment variable and the `GEM_HOME` and `GEM_PATH` Ruby environment variables pointed at Chef Workstation. ### Syntax This subcommand has the following syntax: ``` chef exec SYSTEM_COMMAND (options) ``` ### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef gem -------- The `chef gem` subcommand is a wrapper around the `gem` command in RubyGems and is used by Chef to install RubyGems into Chef Workstation development environment. All knife plugins, drivers for Kitchen, and other Ruby applications that are not packaged within Chef Workstation will be installed to the `.Chef Workstation` path in the home directory: `~/.Chef Workstation/gem/ruby/ver.si.on/bin` (where `ver.si.on` is the version of Ruby that is packaged within Chef Workstation). ### Syntax This subcommand has the following syntax: ``` chef gem GEM_COMMAND GEM_OPTIONS (options) ``` ### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples **Show an existing gem in Chef Workstation** To show a gem, run a command similar to: ``` chef gem list cookstyle ``` to return something similar to: ``` *** LOCAL GEMS *** cookstyle (5.20.0) ``` **List all local gems** To list all of the installed gems on your development environment, use the `list` command without any arguments: ``` chef gem list ``` **Search for local gems** The `list` command can also be used to search for locally installed gems. For example, to list all of the gems with `knife` in their title: ``` chef gem list knife ``` which returns the following output: ``` *** LOCAL GEMS *** knife-opc (0.3.2) knife-windows (1.9.0) ``` **Search remote gems** Use the `search` command to search for remote gems available for installation: ``` chef gem search kitchen ``` to return something similar to: ``` *** REMOTE GEMS *** chefkitchen_cli (0.0.1) gst-kitchen (0.9.0) guard-kitchen (0.0.2) jackal-kitchen (0.1.2) jackal-kitchen-slack (0.1.2) kitchen (0.0.3) ``` **Install a gem** To install a gem, run a command similar to: ``` chef gem install knife-config ``` to return something similar to: ``` Successfully installed knife-config-1.1.0 1 gem installed ``` **Uninstall a gem** To uninstall a gem from Chef Workstation environment: ``` chef gem uninstall knife-config ``` to return something similar to: ``` Successfully uninstalled knife-config-1.1.0 ``` **View the contents of a gem** To view the contents of a gem, run a command similar to: ``` chef gem content knife-config ``` to return something similar to: ``` /Users/user/.chefdk/gem/ruby/2.1.0/gems/knife-config-1.1.0/LICENSE /Users/user/.chefdk/gem/ruby/2.1.0/gems/knife-config-1.1.0/README.md /Users/user/.chefdk/gem/ruby/2.1.0/gems/knife-config-1.1.0/lib/chef/knife/config.rb /Users/user/.chefdk/gem/ruby/2.1.0/gems/knife-config-1.1.0/lib/knife-config.rb ``` chef generate attribute ----------------------- Use the `chef generate attribute` subcommand to generate an attribute file in the `/attributes` directory. ### Syntax This subcommand has the following syntax: ``` chef generate attribute COOKBOOK_PATH NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples **Create an attribute** To generate an attribute, run a command similar to: ``` chef generate attribute /path/to/cookbook FOO ``` will return something similar to: ``` Recipe: code_generator::attribute * directory[/Users/grantmc/chef-repo/cookbooks/chef-repo/attributes] action create - create new directory /Users/grantmc/chef-repo/cookbooks/chef-repo/attributes * template[/Users/grantmc/chef-repo/cookbooks/chef-repo/attributes/FOO.rb] action create - create new file /Users/grantmc/chef-repo/cookbooks/chef-repo/attributes/FOO.rb ``` chef generate cookbook ---------------------- Use the `chef generate cookbook` subcommand to generate a cookbook. Note Cookbook and custom resource names should contain only alphanumeric characters. A hyphen (`-`) is a valid character and may be used in cookbook and custom resource names, but it is discouraged. Chef Infra Client will return an error if a hyphen is not converted to an underscore (`_`) when referencing from a recipe the name of a custom resource in which a hyphen is located. ### Syntax This subcommand has the following syntax: ``` chef generate cookbook COOKBOOK_PATH/COOKBOOK_NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-b`, `--berks` Create a Berksfile in the cookbook. Default: disabled. Optional. Use to create a berksfile by overriding default creation of a Policyfile. `-C COPYRIGHT`, `--copyright COPYRIGHT` Specify the copyright holder for copyright notices in generated files. Default value: `The Authors` `-d`, `--delivery` Generate a delivery config file and build cookbook inside the new cookbook. Default value: disabled. This option is disabled. It has no effect and exists only for compatibility with past releases `-m EMAIL`, `--email EMAIL` Specify the email address of the author. Default value: `<EMAIL>`. `-a KEY=VALUE`, `--generator-arg KEY=VALUE` Sets a property named `KEY` to the given `VALUE` on the generator context object in the generator cookbook. This allows custom generator cookbooks to accept optional user input on the command line. `-I LICENSE`, `--license LICENSE` Sets the license. Valid values are `all_rights`, `apache2`, `mit`, `gplv2`, or `gplv3`. Default value: `all_rights`. `-P`, `--policy` Create a Policyfile in the cookbook instead of a Berksfile. Default: enabled. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples **Create a cookbook** To generate a cookbook, run a command similar to: ``` chef generate cookbook chefdocs ``` will return something similar to: ``` Recipe: code_generator::cookbook * directory[/Users/grantmc/chefdocs] action create - create new directory /Users/grantmc/chefdocs * template[/Users/grantmc/chefdocs/metadata.rb] action create - create new file /Users/grantmc/chefdocs/metadata.rb * template[/Users/grantmc/chefdocs/README.md] action create - create new file /Users/grantmc/chefdocs/README.md * cookbook_file[/Users/grantmc/chefdocs/chefignore] action create - create new file /Users/grantmc/chefdocs/chefignore * cookbook_file[/Users/grantmc/chefdocs/Berksfile] action create - create new file /Users/grantmc/chefdocs/Berksfile * template[/Users/grantmc/chefdocs/kitchen.yml] action create - create new file /Users/grantmc/chefdocs/kitchen.yml * directory[/Users/grantmc/chefdocs/recipes] action create - create new directory /Users/grantmc/chefdocs/recipes * template[/Users/grantmc/chefdocs/recipes/default.rb] action create - create new file /Users/grantmc/chefdocs/recipes/default.rb * execute[initialize-git] action run - execute git init . * cookbook_file[/Users/grantmc/chefdocs/.gitignore] action create - create new file /Users/grantmc/chefdocs/.gitignore ``` and which creates a directory structure similar to: ``` /chefdocs /.git .gitignore kitchen.yml Berksfile chefignore metadata.rb README.md /recipes default.rb ``` **Create a cookbook using a custom skeleton cookbook** If a custom skeleton cookbook is located on a macOS desktop (and in this example, the `chef_generator` cookbook is simply a copy of the same cookbook that ships in Chef Workstation), the following command will use the skeleton cookbook at the custom location to generate a cookbook into the repository from which the `chef` command is run: ``` chef generate cookbook --generator-cookbook ~/Desktop testcookbook ``` Note The `code_generator` cookbook itself is not specified as part of the path. will return something similar to: ``` Compiling Cookbooks... Recipe: code_generator::cookbook * directory[/Users/grantmc/Desktop/chef-repo/test-cookbook] action create - create new directory /Users/grantmc/Desktop/chef-repo/test-cookbook * template[/Users/grantmc/Desktop/chef-repo/test-cookbook/metadata.rb] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/metadata.rb * template[/Users/grantmc/Desktop/chef-repo/test-cookbook/README.md] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/README.md * cookbook_file[/Users/grantmc/Desktop/chef-repo/test-cookbook/chefignore] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/chefignore * cookbook_file[/Users/grantmc/Desktop/chef-repo/test-cookbook/Berksfile] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/Berksfile * template[/Users/grantmc/Desktop/chef-repo/test-cookbook/kitchen.yml] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/kitchen.yml * directory[/Users/grantmc/Desktop/chef-repo/test-cookbook/recipes] action create - create new directory /Users/grantmc/Desktop/chef-repo/test-cookbook/recipes * template[/Users/grantmc/Desktop/chef-repo/test-cookbook/recipes/default.rb] action create - create new file /Users/grantmc/Desktop/chef-repo/test-cookbook/recipes/default.rb ``` chef generate build-cookbook ---------------------------- Use the `chef generate build-cookbook` subcommand to generate a delivery configuration file and build cookbook. ### Syntax This subcommand has the following syntax: ``` chef generate build-cookbook COOKBOOK_PATH/COOKBOOK_NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-C COPYRIGHT`, `--copyright COPYRIGHT` Specify the copyright holder for copyright notices in generated files. Default value: `The Authors` `-m EMAIL`, `--email EMAIL` Specify the email address of the author. Default value: `<EMAIL>`. `-a KEY=VALUE`, `--generator-arg KEY=VALUE` Sets a property named `KEY` to the given `VALUE` on the generator context object in the generator cookbook. This allows custom generator cookbooks to accept optional user input on the command line. `-I LICENSE`, `--license LICENSE` Sets the license. Valid values are `all_rights`, `apache2`, `mit`, `gplv2`, or `gplv3`. Default value: `all_rights`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef generate file ------------------ Use the `chef generate file` subcommand to generate a file in the `/files` directory. ### Syntax This subcommand has the following syntax: ``` chef generate file COOKBOOK_PATH NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-h`, `--help` Show help for the command. `-s SOURCE_FILE`, `--source SOURCE_FILE` Copy the contents from a source file. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef generate resource ---------------------- Use the `chef generate resource` subcommand to generate a custom resource in the `/resources` directory. Note Cookbook and custom resource names should contain only alphanumeric characters. A hyphen (`-`) is a valid character and may be used in cookbook and custom resource names, but it is discouraged. Chef Infra Client will return an error if a hyphen is not converted to an underscore (`_`) when referencing from a recipe the name of a custom resource in which a hyphen is located. ### Syntax This subcommand has the following syntax: ``` chef generate resource COOKBOOK_PATH NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef generate recipe -------------------- Use the `chef generate recipe` subcommand to generate a recipe in the `/recipes` directory. ### Syntax This subcommand has the following syntax: ``` chef generate recipe COOKBOOK_PATH NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef generate repo ------------------ Use the `chef generate repo` subcommand to create a chef-repo. By default, the repo is a cookbook repo with options available to support generating a cookbook that supports Policyfile. ### Syntax This subcommand has the following syntax: ``` chef generate repo REPO_NAME (options) ``` ### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-p`, `--policy-only` Create a repository that does not store cookbook files, only Policyfile files. `-P`, `--policy` Use Policyfile instead of Berkshelf. `-r`, `--roles` Create directories for `/roles` and `/environments` instead of creating directories for Policyfile. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef generate template ---------------------- Use the `chef generate template` subcommand to generate a template in the `/templates` directory. ### Syntax This subcommand has the following syntax: ``` chef generate template COOKBOOK_PATH NAME (options) ``` ### Options This subcommand has the following options: `-g GENERATOR_COOKBOOK_PATH`, `--generator-cookbook GENERATOR_COOKBOOK_PATH` The path at which a cookbook named `code_generator` is located. This cookbook is used by the `chef generate` subcommands to generate cookbooks, cookbook files, templates, attribute files, and so on. Default value: `lib/chef-dk/skeletons`, under which is the default `code_generator` cookbook that is included as part of Chef Workstation. `-h`, `--help` Show help for the command. `-s SOURCE_FILE`, `--source SOURCE_FILE` Copy the contents from a source file. `-v`, `--version` The Chef Infra Client version. ### Examples None. chef report cookbooks --------------------- Use the `chef report cookbooks` subcommand to generate a cookbook-oriented report for your Chef Infra environment. This report provides details about upgrade compatibility errors and node cookbook usage. ### Syntax This subcommand has the following syntax: ``` chef report cookbooks [options] ``` ### Options This subcommand has the following options: `-a`, `--anonymize` Replace cookbook and node names with hash values to protect the sensitive information. `-c`, `--credentials string` Credentials file (default $HOME/.chef/credentials). `-f`, `--format` Output format: txt is human readable, csv is machine readable (default “txt”). `-F`, `--node-filter` Search filter to apply to nodes. `-h`, `--help` Show help for the command. `-k`, `--client-key` Chef Infra Server API client key. `-n`, `--client-name` Chef Infra Server API client name. `-o`, `--ssl-no-verify` Do not verify SSL when connecting to Chef Infra Server (default: verify). `-p`, `--profile` Profile to use from credentials file (default “default”). `-s`, `--chef-server-url` Chef Infra Server URL. `-u`, `--only-unused` Generate a report that only includes cookbooks that are not included in any node’s runlist. `-V`, `--verify-upgrade` Verify the upgrade compatibility of every cookbook. `-w`, `--workers` Maximum number of parallel workers at once (default 50). ### Examples **Generate a report** To generate a cookbook oriented report, run a command similar to: ``` chef report cookbooks ``` will return something similar to: ``` Finding available cookbooks... (5 found) Analyzing cookbooks... 5 / 5 [----------------------------------------------------------------------------------------------------------------] 100.00% 13 p/s -- REPORT SUMMARY -- Cookbook Version Policy Group Policy Nodes Affected -----------+---------+--------------+--------+----------------- apt 2.7.0 2 Go 0.1.0 3 java 0.3.0 4 java Production K8s 1 K8s Production K8s 1 Cookbooks report saved to .chef-workstation/reports/cookbooks-20200722120938.txt ``` More details of this summary report can be viewed in the text file, the location for which is given at the end of the summary. See the [Upgrade Lab](../workstation/upgrade_lab/index#chef-report-cookbooks) documentation for additional information on upgrading Chef Infra Client. chef report nodes ----------------- Use the `chef report nodes` subcommand to generate a nodes-oriented report for your chef environment. This report provides details about nodes, applied policies and the cookbooks used during the most recent chef-client run. ### Syntax This subcommand has the following syntax: ``` chef report nodes [options] ``` ### Options This subcommand has the following options: `-a`, `--anonymize` Replace cookbook and node names with hash values to protect sensitive information. `-c`, `--credentials string` Credentials file (default $HOME/.chef/credentials). `-f`, `--format` Output format: txt is human readable, csv is machine readable (default “txt”). `-F`, `--node-filter` Search filter to apply to nodes. `-h`, `--help` Show help for the command. `-k`, `--client-key` Chef Infra Server API client key. `-n`, `--client-name` Chef Infra Server API client name. `-o`, `--ssl-no-verify` Do not verify SSL when connecting to Chef Infra Server (default: verify). `-p`, `--profile` Profile to use from credentials file (default “default”). `-s`, `--chef-server-url` Chef Infra Server URL. ### Examples **Generate a report** To generate a nodes oriented report, run a command similar to: ``` chef report nodes ``` will return something similar to: ``` Analyzing nodes... -- REPORT SUMMARY -- Node Name Chef Version Operating System Number Cookbooks ---------------------+--------------+------------------+------------------- dev-server-backend 16.1.16 redhat v8.2 3 dev-server-web 16.1.16 redhat v8.2 1 production-server 16.1.16 redhat v8.2 2 staging-server 16.1.16 redhat v8.2 4 test-server 16.1.16 redhat v8.2 3 Nodes report saved to .chef-workstation/reports/nodes-20200722130502.txt ``` More details of this summary report can be viewed in the text file, the location for which is given at the end of the summary. [Upgrade Lab](../workstation/upgrade_lab) provides further details on how this command can be used in Chef Infra Client upgrade process. chef shell-init --------------- Use the `chef shell-init` subcommand to set the Ruby included in Chef Workstation as the system Ruby. Chef Workstation is designed to allow the isolation of applications used by Chef Workstation from other Ruby development tools that may be present on the workstation. This supports Bash, fish, Windows PowerShell (posh), and zsh. bash zsh fish PowerShell (posh) ### Syntax This subcommand has the following syntax: ``` chef shell-init SHELL_NAME (options) ``` ### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. ### Examples **Set PowerShell** You can use the `chef shell-init` command with Windows PowerShell to add the appropriate variables to your environment. To try it in your current session: ``` chef shell-init powershell | Invoke-Expression ``` To enable it permanently: ``` "chef shell-init powershell | Invoke-Expression" >> $PROFILE ``` **Set the execution policy on new machines** On new Windows machines, PowerShell scripts will not work until an administrator runs the following command: ``` Set-ExecutionPolicy RemoteSigned ``` **Create a $PROFILE on new machines** On new Windows machines, commands cannot be appended to `$PROFILE` if the folder does not exist, or if there is a new user profile. This will result in an error similar to the following: ``` PS C:\Users\Stuart> "chef shell-init powershell | Invoke-Expression" >> $PROFILE out-file : Could not find a part of the path 'C:\Users\Stuart\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'. At line:1 char:1 + "chef shell-init powershell | Invoke-Expression" >> $PROFILE + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OpenError: (:) [Out-File], DirectoryNotFoundException + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand ``` In this situation, run the following `chef shell-init` command instead: ``` if(Test-Path $PROFILE){ chef shell-init powershell | Add-Content $PROFILE } else { New-Item -Force -ItemType File $PROFILE; chef shell-init powershell | Add-Content $PROFILE } ``` Policyfile Commands ------------------- The following commands are built into the `chef` executable and support the use of Policyfile files. ### chef clean-policy-cookbooks Use the `chef clean-policy-cookbooks` subcommand to delete cookbooks that are not used by Policyfile files. Cookbooks are considered unused when they are not referenced by any policy revisions on the Chef Infra Server. Note Cookbooks that are referenced by orphaned policy revisions are not removed. Use `chef clean-policy-revisions` to remove orphaned policies. #### Syntax This subcommand has the following syntax: ``` chef clean-policy-cookbooks (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef clean-policy-revisions Use the `chef clean-policy-revisions` subcommand to delete orphaned policy revisions to Policyfile files from the Chef Infra Server. An orphaned policy revision is not associated to any policy group and therefore is not in active use by any node. Use `chef show-policy --orphans` to view a list of orphaned policy revisions. #### Syntax This subcommand has the following syntax: ``` chef clean-policy-revisions (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef delete-policy Use the `chef delete-policy` subcommand to delete all revisions of the named policy that exist on the Chef Infra Server. (The state of the policy revision is backed up locally and may be restored using the `chef undelete` subcommand.) #### Syntax This subcommand has the following syntax: ``` chef delete-policy POLICY_NAME (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef delete-policy-group Use the `chef delete-policy-group` subcommand to delete the named policy group from the Chef Infra Server. Any policy revision associated with that policy group is not deleted. (The state of the policy group is backed up locally and may be restored using the `chef undelete` subcommand.) #### Syntax This subcommand has the following syntax: ``` chef delete-policy-group POLICY_GROUP (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef diff Use the `chef diff` subcommand to display an itemized comparison of two revisions of a `Policyfile.lock.json` file. #### Syntax This subcommand has the following syntax: ``` chef diff POLICY_FILE --head | --git POLICY_GROUP | POLICY_GROUP...POLICY_GROUP (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-g GIT_REF`, `--git GIT_REF` Compare the specified git reference against the current revision of a `Policyfile.lock.json` file or against another git reference. `-h`, `--help` Show help for the command. `--head` A shortcut for `chef diff --git HEAD`. When a git-specific flag is not provided, the on-disk `Policyfile.lock.json` file is compared to one on the Chef Infra Server or (if a `Policyfile.lock.json` file is not present on-disk) two `Policyfile.lock.json` files in the specified policy group on the Chef Infra Server are compared. `--[no-]pager` Use `--pager` to enable paged output for a `Policyfile.lock.json` file. Default value: `--pager`. `-v`, `--version` The Chef Infra Client version. #### Examples **Compare current lock to latest commit on latest branch** ``` chef diff --git HEAD ``` **Compare current lock with latest commit on master branch** ``` chef diff --git master ``` **Compare current lock to specified revision** ``` chef diff --git v1.0.0 ``` **Compare lock on master branch to lock on revision** ``` chef diff --git master...dev ``` **Compare lock for version with latest commit on master branch** ``` chef diff --git v1.0.0...master ``` **Compare current lock with latest lock for policy group** ``` chef diff staging ``` **Compare locks for two policy groups** ``` chef diff production...staging ``` ### chef export Use the `chef export` subcommand to create a chef-zero-compatible chef-repo that contains the cookbooks described by a `Policyfile.lock.json` file. After a chef-zero-compatible chef-repo is copied to a node, the policy can be applied locally on that machine by running `chef-client -z` (local mode). #### Syntax This subcommand has the following syntax: ``` chef export POLICY_FILE DIRECTORY (options) ``` #### Options This subcommand has the following options: `-a`, `--archive` Export an archive as a tarball, instead as a directory. Default value: `false`. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-f`, `--force` Remove the contents of the destination directory if that directory is not empty. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef generate policyfile Use the `chef generate policyfile` subcommand to generate a file to be used with Policyfile. #### Syntax This subcommand has the following syntax: ``` chef generate policyfile POLICY_NAME (options) ``` #### Options This subcommand has the following options: `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef install Use the `chef install` subcommand to evaluate a policy file and find a compatible set of cookbooks, build a run-list, cache it locally, and then emit a `Policyfile.lock.json` file that describes the locked policy set. The `Policyfile.lock.json` file may be used to install the locked policy set to other machines and may be pushed to a policy group on the Chef Infra Server to apply that policy to a group of nodes that are under management by Chef. #### Syntax This subcommand has the following syntax: ``` chef install POLICY_FILE (options) ``` #### Options This subcommand has the following options: `-D`, `--debug` Enable stack traces and other debug output. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Policyfile.lock.json When the `chef install` command is run, Chef Workstation caches any necessary cookbooks and emits a `Policyfile.lock.json` file that describes: * The versions of cookbooks in use * A Hash of cookbook content * The source for all cookbooks A `Policyfile.lock.json` file is associated with a specific policy group, i.e. is associated with one (or more) nodes that use the same revision of a given policy. A `Policyfile.lock.json` file is similar to: ``` { "revision_id": "288ed244f8db8bff3caf58147e840bbe079f76e0", "name": "jenkins", "run_list": [ "recipe[java::default]", "recipe[jenkins::master]", "recipe[policyfile_demo::default]" ], "cookbook_locks": { "policyfile_demo": { "version": "0.1.0", "identifier": "f04cc40faf628253fe7d9566d66a1733fb1afbe9", "dotted_decimal_identifier": "67638399371010690.23642238397896298.25512023620585", "source": "cookbooks/policyfile_demo", "cache_key": null, "scm_info": null, "source_options": { "path": "cookbooks/policyfile_demo" } }, "java": { "version": "1.24.0", "identifier": "4c24ae46a6633e424925c24e683e0f43786236a3", "dotted_decimal_identifier": "21432429158228798.18657774985439294.16782456927907", "cache_key": "java-1.24.0-supermarket.chef.io", "origin": "https://supermarket.chef.io/api/v1/cookbooks/java/versions/1.24.0/download", "source_options": { "artifactserver": "https://supermarket.chef.io/api/v1/cookbooks/java/versions/1.24.0/download", "version": "1.24.0" } ``` #### Examples None. ### chef push Use the `chef push` subcommand to upload an existing `Policyfile.lock.json` file to the Chef Infra Server, along with all of the cookbooks that are contained in the file. The `Policyfile.lock.json` file will be applied to the specified policy group, which is a set of nodes that share the same run-list and cookbooks. #### Syntax This subcommand has the following syntax: ``` chef push POLICY_GROUP POLICY_FILE (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef push-archive The `chef push-archive` subcommand is used to publish a policy archive file to the Chef Infra Server. (A policy archive is created using the `chef export` subcommand.) The policy archive is assigned to the specified policy group, which is a set of nodes that share the same run-list and cookbooks. #### Syntax This subcommand has the following syntax: ``` chef push-archive POLICY_GROUP ARCHIVE_FILE (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef show-policy Use the `chef show-policy` subcommand to display revisions for every `Policyfile.rb` file that is on the Chef Infra Server. By default, only active policy revisions are shown. When both a policy and policy group are specified, the contents of the active `Policyfile.lock.json` file for the policy group is returned. #### Syntax This subcommand has the following syntax: ``` chef show-policy POLICY_NAME POLICY_GROUP (options) ``` #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-o`, `--orphans` Show policy revisions that are not currently assigned to any policy group. `--[no-]pager` Use `--pager` to enable paged output for a `Policyfile.lock.json` file. Default value: `--pager`. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef undelete Use the `chef undelete` subcommand to recover a deleted policy or policy group. This command: * Does not detect conflicts. If a deleted item has been recreated, running this command will overwrite it * Does not include cookbooks that may be referenced by policy files; cookbooks that are cleaned after running this command may not be fully restorable to their previous state * Does not store access control data #### Syntax This subcommand has the following syntax: ``` chef undelete (options) ``` When run with no arguments, returns a list of available operations. #### Options This subcommand has the following options: `-c CONFIG_FILE`, `--config CONFIG_FILE` The path to the knife configuration file. `-D`, `--debug` Enable stack traces and other debug output. `-h`, `--help` Show help for the command. `-i ID`, `--id ID` Undo the delete operation specified by `ID`. `-l`, `--last` Undo the most recent delete operation. `--list` Default. Return a list of available operations. `-v`, `--version` The Chef Infra Client version. #### Examples None. ### chef update Use the `chef update` subcommand to read the `Policyfile.rb` file, and then apply any changes. This will resolve dependencies and will create a `Policyfile.lock.json` file. The locked policy will reflect any changes to the run-list and will pull in any cookbook updates that are compatible with any version constraints defined in the `Policyfile.rb` file. #### Syntax This subcommand has the following syntax: ``` chef update POLICY_FILE (options) ``` #### Options This subcommand has the following options: `-a`, `--attributes` Update attributes. Default value: `false`. `-D`, `--debug` Enable stack traces and other debug output. Default value: `false`. `-h`, `--help` Show help for the command. `-v`, `--version` The Chef Infra Client version. #### Examples None. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ctl_chef/About Attributes ================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/attributes.md) An attribute is a specific detail about a node. Attributes are used by Chef Infra Client to understand: * The current state of the node * What the state of the node was at the end of the previous Chef Infra Client run * What the state of the node should be at the end of the current Chef Infra Client run Attributes are defined by: * The node as saved on the Chef Infra Server * Attributes passed via JSON on the command line * Cookbooks (in attribute files and/or recipes) * Policyfiles During every Chef Infra Client run, Chef Infra Client builds the attribute list using: * Attributes passed via JSON on the command line * Data about the node collected by [Ohai](ohai). * The node object that was saved to the Chef Infra Server at the end of the previous Chef Infra Client run. * The rebuilt node object from the current Chef Infra Client run, after it is updated for changes to cookbooks (attribute files and/or recipes) and/or Policyfiles, and updated for any changes to the state of the node itself. After the node object is rebuilt, all of the attributes are compared, and then the node is updated based on attribute precedence. At the end of every Chef Infra Client run, the node object that defines the current state of the node is uploaded to the Chef Infra Server so that it can be indexed for search. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/attributesChef Infra Server Prerequisites =============================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/install_server_pre.md) The following is a detailed discussion of the prerequisites for every installation of the Chef Infra Server. See [Install Chef Infra Server](server/install_server/index) for installation instructions. Platforms --------- The following table lists the commercially-supported platforms and versions for the Chef Infra Server: | Platform | Architecture | Version | | --- | --- | --- | | Amazon Linux 2 | `x86_64` | `2.x` | | CentOS | `x86_64` | `7.x`, `8.x` | | Oracle Enterprise Linux | `x86_64` | `7.x`, `8.x` | | Red Hat Enterprise Linux | `x86_64` | `7.x`, `8.x` | | SUSE Enterprise Linux Server | `x86_64` | `12.x`, `15.x` | | Ubuntu | `x86_64` | `16.04`, `18.04`, `20.04` | ### Untested Platforms The following platforms are not tested by Chef Software: * Any Linux or UNIX distribution that is not listed as a Foundational platform. * Microsoft Windows * 32-bit architectures Capacity Planning ----------------- Read the [guidance around capacity planning](server/index#capacity-planning) for information about how to choose the right topology for the Chef Infra Server. Hardware Requirements --------------------- All machines in a Chef Infra Server deployment have the following hardware requirements. Disk space for standalone and backend servers should scale up with the number of nodes that the servers are managing. A good rule to follow is to allocate 2 MB per node. The disk values listed below should be a good default value that you will want to modify later if/when your node count grows. Fast, redundant storage (SSD/RAID-based solution either on-prem or in a cloud environment) is preferred. **All Deployments** * 64-bit CPU architecture * CPU support for SSE4.2 extensions (Xeons starting in 2007 and Opterons in 2012) **Standalone Deployments** * 4 total cores (physical or virtual) * 8 GB of RAM or more * 5 GB of free disk space in `/opt` * 10 GB of free disk space in `/var` For a high availability deployment: **General Requirements** * Three backend servers; as many frontend servers as required * 1 x GigE NIC interface (if on premises) **Frontend Requirements** * 4 cores (physical or virtual) * 4GB RAM * 20 GB of free disk space (SSD if on premises, Premium Storage in Microsoft Azure, EBS-Optimized GP2 in AWS) **Backend Requirements** * 2 cores (physical or virtual) * 8GB RAM * 50 GB/backend server (SSD if on premises, Premium Storage in Microsoft Azure, EBS-Optimized GP2 in AWS) Warning The Chef Infra Server MUST NOT use a network file system of any type—virtual or physical—for backend storage. The Chef Infra Server database operates quickly. The behavior of operations, such as the writing of log files, will be unpredictable when run over a network file system. Software Requirements --------------------- Before installing the Chef Infra Server, ensure that each machine has the following installed and configured properly: * **Hostnames** — Ensure that all systems have properly configured hostnames. The hostname for the Chef Infra Server must be a FQDN, have fewer than 64 characters including the domain suffix, be lowercase, and resolvable. See [Hostnames, FQDNs](install_server_pre#hostnames) for more information * **FQDNs** — Ensure that all systems have a resolvable FQDN * **NTP** — Ensure that every server is connected to NTP; the Chef Infra Server is sensitive to clock drift * **Mail Relay** — The Chef Infra Server uses email to send notifications for various events; a local mail transfer agent should be installed and available to the Chef server * **cron** — Periodic maintenance tasks are performed using cron * **git** — git must be installed so that various internal services can confirm revisions * **Apache Qpid** — This daemon must be disabled on CentOS and Red Hat systems * **Required users** — If the environment in which the Chef Infra Server will run has restrictions on the creation of local user and group accounts, ensure that the correct users and groups exist before reconfiguring * **Firewalls and ports** — If host-based firewalls (iptables, ufw, etc.) are being used, ensure that ports 80 and 443 are open. In addition: * **Browser** — Firefox, Google Chrome, Safari, or Internet Explorer (versions 9 or better) * **Chef Infra Client communication with the Chef Infra Server** The Chef Infra Server must be able to communicate with every node that will be configured by Chef Infra Client and every workstation that will upload data to the Chef Infra ### UIDs and GIDs The installation process for the Chef Infra Server requires the use of at least two user and group identifiers (UIDs and GIDs). These are used to create the `opscode` and `opscode-pgsql` users and their default groups. Note The creation of required user and group identifiers is done **automatically** during the installation process for the Chef Infra Server; however, the following user and group accounts **may** be created in advance of installing the Chef Infra Server if specific UIDs and GIDs are preferred. The user **and** group must be created as a pair to satisfy reconfiguration requirements. * A local user account named `opscode` under which services will run * A local user account named `opscode-pgsql` that is used by PostgreSQL * A group account for each user account, one named `opscode` and the other named `opscode-pgsql` under which services will run Warning If the UID and GID of `opscode` and `opscode-pgsql` do not match on both backend Chef Infra Server machines, a high availability configuration will not run correctly. The embedded Chef Infra Server cookbooks can handle two cases: * Both `opscode` and `opscode-pgsql` user and group not found on the new server * Both `opscode` and `opscode-pgsql` user and group found on the new server Having only the group and not the corresponding users present during a chef-server-ctl reconfigure is unsupported and may lead to an error in the reconfiguration run. To determine the current range of IDs, run the following command: ``` grep -E '(UID|GID)' /etc/login.defs ``` The defaults for CentOS and Red Hat Enterprise Linux systems look like this: ``` UID_MIN 500 UID_MAX 60000 GID_MIN 500 GID_MAX 60000 ``` If the defaults have been changed for any reason, and if that change would result in less than 2 UID/GIDs being available to the `useradd` program, edit `/etc/login.defs` with changes to make at least 2 more UIDs and GIDs available for association. The currently used ID ranges for UIDs and GIDs can be found in `/etc/passwd` and `/etc/group`, respectively. If the `opscode` and `opscode-pgsql` user and group identifiers exist prior to installing the Chef Infra Server, the Chef Infra Server installation process will use the existing identifiers instead of creating them. ### Firewalls #### iptables To allow access to your Chef Infra Server on ports 80 and 443 via the iptables firewall, issue the following command with root privileges: ``` iptables -A INPUT -p tcp -m multiport --destination-ports 80,443 -j ACCEPT ``` Note that you will need to make use of a tool such as [iptables-persistent](https://packages.ubuntu.com/xenial/admin/iptables-persistent) to restore your iptables rules upon reboot. #### FirewallD On RHEL and CentOS versions 7 and above, the FirewallD firewall is enabled by default. Issue the following command with root privileges to open ports 80 and 443: ``` firewall-cmd --permanent --zone public --add-service http && firewall-cmd --permanent --zone public --add-service https && firewall-cmd --reload ``` #### UFW While UFW is installed on Ubuntu, it is not enabled by default. However, if you wish to use a UFW-based firewall on your Chef Infra Server, issue the following command with root privileges to open ports 80 and 443: ``` ufw allow proto tcp from any to any port 80,443 ``` ### Security Modules #### SELinux On CentOS and Red Hat Enterprise Linux systems, SELinux is enabled in enforcing mode by default. The Chef Infra Server does not have a profile available to run under SELinux. In order for the Chef Infra Server to run, SELinux must be disabled or set to `Permissive` mode. To determine if SELinux is installed, run the following command: ``` getenforce ``` If a response other than `"Disabled"` or `"Permissive"` is returned, SELinux must be disabled. To set SELinux to `Permissive` mode, run: ``` setenforce Permissive ``` and then check the status: ``` getenforce ``` #### AppArmor On Ubuntu systems, AppArmor is enabled in enforcing mode by default. Chef products do not have a profile available to run under AppArmor. In order for the Chef products to run, AppArmor must set to `Complaining` mode or disabled. To determine if AppArmor is installed, run the following command: ``` sudo apparmor_status ``` To install AppArmor, run the following command: ``` sudo apt-get install apparmor-utils -yes ``` If a response other than `"0 processes are in enforce mode"` or `"0 profiles are in enforce mode."` is returned, AppArmor must be set to `Complaining` mode or disabled. To set AppArmor to `Complaining` mode, run: ``` sudo aa-complain /etc/apparmor.d/* ``` Or to disable AppArmor entirely, run: ``` sudo invoke-rc.d apparmor kill sudo update-rc.d -f apparmor remove ``` and then check the status: ``` sudo apparmor_status ``` ### Apache Qpid On CentOS and Red Hat Enterprise Linux systems, the Apache Qpid daemon is installed by default. To determine if Apache Qpid is installed, run the following command: ``` rpm -qa | grep qpid ``` If Apache Qpid is installed, a response similar to the following is displayed: ``` qpid-cpp-server-0.12-6.el6.x86_64 ``` To disable Apache Qpid run: ``` service qpidd stop ``` and then: ``` chkconfig --del qpidd ``` ### cron Periodic maintenance tasks are performed on the Chef Infra Server servers via cron and the `/etc/cron.d` directory. With certain CentOS 6 configurations, an additional step is required to install crontab: ``` yum install crontabs ``` ### Enterprise Linux Updates The Chef Infra Server requires an x86_64 compatible systems architecture. When the Chef Infra Server is installed on Red Hat Enterprise Linux or CentOS, run `yum update` prior to installing the Chef Infra Server. This will ensure those platforms are fully compatible with this requirement. ### IP Addresses Unless you intend to operate the Chef Infra Server in IPv6 mode, you should disable ipv6 in the system’s `/etc/hosts` file by commenting out or removing all references to IPv6 addresses like “::1” or “fe80:db8:85a3:8d3:1319:8a2e:370:7348”. Without these changes, a Chef Infra Server install intended to run in ipv4 mode will mistakenly only start the postgres service on the ipv6 loopback address of “::1” rather than the ipv4 loopback address of 127.0.0.1. This will make further progress through an initial reconfiguration impossible. ### Hostnames The hostname for the Chef Infra Server may be specified using a FQDN or an IP address. This hostname must be resolvable, be 64 characters or less, and be lowercase. For example, a Chef Infra Server running in a production environment with a resolvable FQDN hostname can be added the DNS system. But when deploying Chef Infra Server into a testing environment, adding the hostname to the `/etc/hosts` file is enough to ensure that hostname is resolvable. * **FQDN Hostnames** When the hostname for the Chef Infra Server is a FQDN be sure to include the domain suffix. For example, something like `mychefserver.example.com` (and not something like `mychefserver`). * **IP Address Hostnames** When the Chef Infra Server is run in IPv6 mode, a hostname specified using an IP address must also be bracketed (`[ ]`) or the Chef Infra Server will not be able to recognize it as an IPv6 address. For example: ``` bookshelf['url'] "https://[2001:db8:85a3:8d3:1319:8a2e:370:7348]" ``` The `api_fqdn` setting can be added to the private-chef.rb file (it is not there by default). When added, its value should be equal to the FQDN or IP address for the service URI used by the Chef Infra Server. Then configure the same value for the `bookshelf['vip']` setting prior to installing the Chef Infra Server. For example: `api_fqdn "chef.example.com"` or `api_fqdn 123.45.67.890`. #### Configure Hostnames Use the following sections to verify the hostnames that is used by the Chef Infra Server. **To verify if a hostname is a FQDN** To verify if a hostname is a FQDN, run the following command: ``` hostname ``` If the hostname is a FQDN, it will return something like: ``` mychefserver.example.com ``` If the hostname is not a FQDN, it must be configured so that it is one. **To verify the FQDN is all lowercase** To verify if the alphabetic parts of a FQDN are all lowercase, run the following command: ``` hostname -f | grep -E '^([[:digit:]]|[[:lower:]]|\.|-|_)+$' && echo yes ``` If the hostname is all lowercase, it will return something like: ``` mychefserver.example.com yes ``` If the hostname’s alphabetic parts are not all lowercase, it must be configured so that they are. **To verify a hostname is resolvable** To verify is a hostname is resolvable, run the following command: ``` hostname -f ``` If the hostname is resolvable, it will return something like: ``` mychefserver.example.com ``` **To change a hostname** In some cases, the hostname for the Chef Infra Server needs to be updated. The process for updating a hostname varies, depending on the platform on which the Chef Infra Server will run. Refer to the manual for the platform or contact a local systems administrator for specific guidance for a specific platform. The following example shows how a hostname can be changed when running Red Hat or CentOS: ``` sudo hostname 'mychefserver.example.com' ``` and then: ``` echo "mychefserver.example.com" | sudo tee /etc/hostname ``` **To add a hostname to /etc/hosts** If a hostname is not resolvable, refer to a local systems administrator for specific guidance on how to add the hostname to the DNS system. If the Chef Infra Server is being into a testing environment, just add the hostname to `/etc/hosts`. The following example shows how a hostname can be added to `/etc/hosts` when running Red Hat or CentOS: ``` echo -e "127.0.0.2 `hostname` `hostname -s`" | sudo tee -a /etc/hosts ``` Warning The FQDN for the Chef Infra Server should be resolvable, lowercase, and should not exceed 64 characters when using OpenSSL, as OpenSSL requires the `CN` in a certificate to be no longer than 64 characters. ### Mail Relay The Chef Infra Server server uses email to send notifications for various events: * Password resets * User invitations * Failover notifications * Failed job notifications Configure a local mail transfer agent on the Chef Infra Server using the steps appropriate for the platform on which the Chef Infra Server is running. ### NTP The Chef Infra Server requires that the systems on which it is running be connected to Network Time Protocol (NTP), as the Chef Infra Server is particularly sensitive to clock drift. For Red Hat and CentOS 6: ``` yum install ntp ``` or: ``` chkconfig ntpd on ``` or: ``` service ntpd start ``` For Ubuntu: ``` apt-get install ntp ``` #### Chef Infra Client The Chef Infra Server server requires that every node that is under management by Chef also have an accurate clock that is synchronized very closely with the clock on the Chef Infra Server. If the clocks are not synchronized closely, the authentication process may fail when the clocks are out-of-sync by more than 15 minutes. A failure will trigger a `401 Unauthorized` response similar to: ``` [Tue, 01 Nov 2011 16:55:23 -0700] INFO: *** Chef 11.X.X *** [Tue, 01 Nov 2011 16:55:23 -0700] INFO: Client key /etc/chef/client.pem is not present - registering [Tue, 01 Nov 2011 16:55:24 -0700] INFO: HTTP Request Returned 401 Unauthorized: Failed to authenticate as ORGANIZATION-validator. Synchronize the clock on your host. [Tue, 01 Nov 2011 16:55:24 -0700] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out [Tue, 01 Nov 2011 16:55:24 -0700] FATAL: Net::HTTPClientException: 401 "Unauthorized" ``` In this situation, re-synchronize the system clocks with the Network Time Protocol (NTP) server, and then re-run Chef Infra Client. ### Required Accounts By default, accounts required by the Chef Infra Server are created during setup. If your environment has restrictions on the creation of local user and group accounts that will prevent these accounts from being created automatically during setup, you will need to create these accounts. #### Group Accounts The following group accounts are required: | Group Account | Description | | --- | --- | | `opscode` | The group name under which services will run. | #### User Accounts The following user accounts are required: | User Account | Description | | --- | --- | | `opscode` | The user name under which services will run. | | `opscode-pgsql` | The user name for PostgreSQL. (This is only required on the back end servers in a high availability setup.) | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/install_server_pre.htmlChef Infra Client (executable) ============================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/ctl_chef_client.md) Chef Infra Client is an agent that runs locally on every node that is under management by Chef Infra Server. When Chef Infra Client runs, it performs all of the steps required for bringing a node into the expected state, including: * Registering and authenticating the node with Chef Infra Server * Synchronizing cookbooks from the Chef Infra Server to the node * Compiling the resource collection by loading each of the required cookbooks, including recipes, attributes, and all other dependencies * Taking the appropriate and required actions to configure the node based on recipes and attributes * Reporting summary information on the run to Chef Automate Note The Chef Infra Client executable can be run as a daemon. The Chef Infra Client executable is run as a command-line tool. Note The client.rb file specifies how Chef Infra Client is configured on a node and has the following characteristics: * This file is loaded every time the chef-client executable is run. * On Microsoft Windows machines, the default location for this file is `C:\chef\client.rb`. On all other systems the default location for this file is `/etc/chef/client.rb`. * Use the `--config` option from the command line to override the default location of the configuration file. * This file is not created by default Options ------- This command has the following syntax: ``` chef-client OPTION VALUE OPTION VALUE ... ``` This command has the following options: `-A`, `--fatal-windows-admin-check` Cause a Chef Infra Client run to fail when the Chef Infra Client does not have administrator privileges in Microsoft Windows. `-c CONFIG`, `--config CONFIG` The configuration file to use. `--config-option OPTION` Overrides a single configuration option. Can be used to override multiple configuration options by adding another `--config-option OPTION`. ``` property :db_password, String, sensitive: true ``` `--chef-zero-host HOST` The host on which chef-zero is started. `--chef-zero-port PORT` The port on which chef-zero listens. If a port is not specified—individually, as range of ports, or from the `chef_zero.port` setting in the client.rb file—the Chef Infra Client will scan for ports between 8889-9999 and will pick the first port that is available. `-d SECONDS`, `--daemonize SECONDS` Run the executable as a daemon. Use `SECONDS` to specify the number of seconds to wait before the first daemonized Chef Infra Client run. `SECONDS` is set to `0` by default. Left unset, the daemon uses the default `--interval` an `--splay` values. This option is only available on machines that run in UNIX or Linux environments. For machines that are running Microsoft Windows that require similar functionality, use the `chef-client::service` recipe in the `chef-client` cookbook: <https://supermarket.chef.io/cookbooks/chef-client>. This will install a Chef Infra Client service under Microsoft Windows using the Windows Service Wrapper. `--delete-entire-chef-repo` This option deletes an entire repository. This option may only be used when running the Chef Infra Client in local mode, (`--local-mode`). This option requires `--recipe-url` to be specified. `--disable-config` Use to run the Chef Infra Client using default settings. This will prevent the normally-associated configuration file from being used. This setting should only be used for testing purposes and should never be used in a production setting. `-E ENVIRONMENT_NAME`, `--environment ENVIRONMENT_NAME` The name of the environment. `-f`, `--[no-]fork` Contain Chef Infra Client runs in a secondary process with dedicated RAM. When a Chef Infra Client run is complete, the RAM is returned to the master process. This option helps ensure that a Chef Infra Client uses a steady amount of RAM over time because the master process does not run recipes. This option also helps prevent memory leaks such as those that can be introduced by the code contained within a poorly designed cookbook. Use `--no-fork` to disable running Chef Infra Client in fork node. Default value: `--fork`. `-F FORMAT`, `--format FORMAT` The output format: `doc` (default) or `min`. * Use `doc` to print the progress of a Chef Infra Client run using full strings that display a summary of updates as they occur. * Use `min` to print the progress of a Chef Infra Client run using single characters. A summary of updates is printed at the end of a Chef Infra Client run. A dot (`.`) is printed for events that do not have meaningful status information, such as loading a file or synchronizing a cookbook. For resources, a dot (`.`) is printed when the resource is up to date, an `S` is printed when the resource is skipped by `not_if` or `only_if`, and a `U` is printed when the resource is updated. Other formatting options are available when those formatters are configured in the client.rb file using the `add_formatter` option. `--force-formatter` Show formatter output instead of logger output. `--force-logger` Show logger output instead of formatter output. `-g GROUP`, `--group GROUP` The name of the group that owns a process. This is required when starting any executable as a daemon. `-h`, `--help` Show help for the command. `-i SECONDS`, `--interval SECONDS` The frequency (in seconds) at which Chef Infra Client runs. When running Chef Infra Client at intervals, apply `--splay` and `--interval` values before a Chef Infra Client run. Default value: `1800`. `-j PATH`, `--json-attributes PATH` The path to a file that contains JSON data. Used to setup the first client run. The attributes will persist on the Chef Infra Server for all future runs with option `-j`. **Run-lists** Use this option to define a `run_list` object. For example, a JSON file similar to: ``` "run_list": [ "recipe[base]", "recipe[foo]", "recipe[bar]", "role[webserver]" ], ``` may be used by running `chef-client -j path/to/file.json`. In certain situations this option may be used to update `normal` attributes. **Environments** Use this option to set the `chef_environment` value for a node. Note Any environment specified for `chef_environment` by a JSON file will take precedence over an environment specified by the `--environment` option when both options are part of the same command. For example, run the following: ``` chef-client -j /path/to/file.json ``` where `/path/to/file.json` is similar to: ``` { "chef_environment": "pre-production" } ``` This will set the environment for the node to `pre-production`. **All attributes are normal attributes** Any other attribute type that is contained in this JSON file will be treated as a `normal` attribute. Setting attributes at other precedence levels is not possible. For example, attempting to update `override` attributes using the `-j` option: ``` { "name": "dev-99", "description": "Install some stuff", "override_attributes": { "apptastic": { "enable_apptastic": "false", "apptastic_tier_name": "dev-99.bomb.com" } } } ``` will result in a node object similar to: ``` { "name": "maybe-dev-99", "normal": { "name": "dev-99", "description": "Install some stuff", "override_attributes": { "apptastic": { "enable_apptastic": "false", "apptastic_tier_name": "dev-99.bomb.com" } } } } ``` Note This has set the `normal` attribute `node['override_attributes']['apptastic']`. **Specify a policy** Use this option to use policy files by specifying a JSON file that contains the following settings: | Setting | Description | | --- | --- | | `policy_group` | The name of a policy group that exists on the Chef Infra Server. | | `policy_name` | The name of a policy, as identified by the `name` setting in a Policyfile.rb file. | For example: ``` { "policy_name": "appserver", "policy_group": "staging" } ``` `-k KEY_FILE`, `--client_key KEY_FILE` The location of the file that contains the client key. Default value: `/etc/chef/client.pem`. `-K KEY_FILE`, `--validation_key KEY_FILE` The location of the file that contains the key used when a Chef Infra Client is registered with a Chef Infra Server. A validation key is signed using the `validation_client_name` for authentication. Default value: `/etc/chef/validation.pem`. `-l LEVEL`, `--log_level LEVEL` The level of logging to be stored in a log file. Possible levels: `auto` (default), `debug`, `error`, `fatal`, `info`, `trace`, or `warn`. Default value: `warn` (when a terminal is available) or `info` (when a terminal is not available). `-L LOGLOCATION`, `--logfile LOGLOCATION` The location of the log file. This is recommended when starting any executable as a daemon. Default value: `STDOUT`. `--lockfile LOCATION` Use to specify the location of the lock file, which prevents multiple Chef Infra Client processes from converging at the same time. `--minimal-ohai` Run the Ohai plugins for name detection and resource/provider selection and no other Ohai plugins. Set to `true` during integration testing to speed up test cycles. `--[no-]color` View colored output. Default setting: `--color`. `--[no-]fips` Allows OpenSSL to enforce FIPS-validated security during a Chef Infra Client run. `--[no-]skip-cookbook-sync` Use cached cookbooks without overwriting local differences from the server. Use with caution. Useful for patching a set of cookbooks on a machine when iterating during development. `--[no-]listen` Run chef-zero in socketless mode. **This is the default behavior on Chef Client 13.1 and above.** `-n NAME`, `--named-run-list NAME` The run-list associated with a policy file. `-N NODE_NAME`, `--node-name NODE_NAME` The unique identifier of the node. `-o RUN_LIST_ITEM`, `--override-runlist RUN_LIST_ITEM` Replace the current run-list with the specified items. This option will not clear the list of cookbooks (and related files) that is cached on the node. This option will not persist node data at the end of the client run. `--once` Make only one Chef Infra Client run and cancel `interval` and `splay` options. `-P PID_FILE`, `--pid PID_FILE` The location in which a process identification number (pid) is saved. An executable, when started as a daemon, writes the pid to the specified file. Default value: `/tmp/name-of-executable.pid`. `--profile-ruby` Use the `--profile-ruby` option to dump a (large) profiling graph into `/var/chef/cache/graph_profile.out`. Use the graph output to help identify, and then resolve performance bottlenecks in a Chef Infra Client run. This option: * Generates a large amount of data about a Chef Infra Client run. * Has a dependency on the `ruby-prof` gem, which is packaged as part of Chef and Chef Workstation. * Increases the amount of time required to complete a Chef Infra Client run. * Should not be used in a production environment. `-r RUN_LIST_ITEM`, `--runlist RUN_LIST_ITEM` Permanently replace the current run-list with the specified run-list items. `-R`, `--enable-reporting` Enable Reporting, which performs data collection during a Chef Infra Client run. `RECIPE_FILE` The path to a recipe. For example, if a recipe file is in the current directory, use `recipe_file.rb`. This is typically used with the `--local-mode` option. `--recipe-url=RECIPE_URL` The location of a recipe when it exists at a URL. Use this option only when running Chef Infra Client with the `--local-mode` option. `--run-lock-timeout SECONDS` The amount of time (in seconds) to wait for a Chef Infra Client lock file to be deleted. Default value: not set (indefinite). Set to `0` to cause a second Chef Infra Client to exit immediately. `-s SECONDS`, `--splay SECONDS` A random number between zero and `splay` that is added to `interval`. Use splay to help balance the load on the Chef Infra Server by ensuring that many Chef Infra Client runs are not occurring at the same interval. When running Chef Infra Client at intervals, apply `--splay` and `--interval` values before a Chef Infra Client run. Changed in Chef Client 12.0 to be applied before the Chef Client run. `-S CHEF_SERVER_URL`, `--server CHEF_SERVER_URL` The URL for the Chef Infra Server. `-u USER`, `--user USER` The user that owns a process. This is required when starting any executable as a daemon. `-v`, `--version` The Chef Infra Client version. `-W`, `--why-run` Run the executable in why-run mode, which is a type of Chef Infra Client run that does everything except modify the system. Use why-run mode to understand why the Chef Infra Client makes the decisions that it makes and to learn more about the current and proposed state of the system. `-z`, `--local-mode` Run the Chef Infra Client in local mode. This allows all commands that work against the Chef Infra Server to also work against the local chef-repo. ### Chef Infra Client Lock File The Chef Infra Client uses a lock file to ensure that only one Chef Infra Client run is in progress at any time. A lock file is created at the start of a Chef Infra Client run and is deleted at the end of a Chef Infra Client run. A new Chef Infra Client run looks for the presence of a lock file and, if present, will wait for that lock file to be deleted. The location of the lock file can vary by platform. * Use the `lockfile` setting in the client.rb file to specify non-default locations for the lock file. (The default location is typically platform-dependent and is recommended.) * Use the `run_lock_timeout` setting in the client.rb file to specify the amount of time (in seconds) to wait for the lock file associated with an in-progress Chef Infra Client run to be deleted. Run in Local Mode ----------------- Local mode is a way to run the Chef Infra Client against the chef-repo on a local machine as if it were running against the Chef Infra Server. Local mode relies on chef-zero, which acts as a very lightweight instance of the Chef Infra Server. chef-zero reads and writes to the `chef_repo_path`, which allows all commands that normally work against the Chef Infra Server to be used against the local chef-repo. Local mode does not require a configuration file, instead it will look for a directory named `/cookbooks` and will set `chef_repo_path` to be just above that. (Local mode will honor the settings in a configuration file, if desired.) If the client.rb file is not found and no configuration file is specified, local mode will search for a config.rb file. Local mode will store temporary and cache files under the `<chef_repo_path>/.cache` directory by default. This allows a normal user to run the Chef Infra Client in local mode without requiring root access. ### About why-run Mode why-run mode is a way to see what Chef Infra Client would have configured, had an actual Chef Infra Client run occurred. This approach is similar to the concept of “no-operation” (or “no-op”): decide what should be done, but then don’t actually do anything until it’s done right. This approach to configuration management can help identify where complexity exists in the system, where inter-dependencies may be located, and to verify that everything will be configured in the desired manner. When why-run mode is enabled, a Chef Infra Client run will occur that does everything up to the point at which configuration would normally occur. This includes getting the configuration data, authenticating to the Chef Infra Server, rebuilding the node object, expanding the run-list, getting the necessary cookbook files, resetting node attributes, identifying the resources, and building the resource collection, but does not include mapping each resource to a provider or configuring any part of the system. Note why-run mode is not a replacement for running cookbooks in a test environment that mirrors the production environment. Chef uses why-run mode to learn more about what is going on, but also Kitchen on developer systems, along with an internal OpenStack cloud and external cloud providers to test more thoroughly. When Chef Infra Client is run in why-run mode, certain assumptions are made: * If the **service** resource cannot find the appropriate command to verify the status of a service, why-run mode will assume that the command would have been installed by a previous resource and that the service would not be running. * For `not_if` and `only_if` properties, why-run mode will assume these are commands or blocks that are safe to run. These conditions are not designed to be used to change the state of the system, but rather to help facilitate idempotency for the resource itself. That said, it may be possible that these attributes are being used in a way that modifies the system state * The closer the current state of the system is to the desired state, the more useful why-run mode will be. For example, if a full run-list is run against a fresh system, that run-list may not be completely correct on the first try, but also that run-list will produce more output than a smaller run-list For example, the **service** resource can be used to start a service. If the action is `:start`, then the service will start if it isn’t running and do nothing if it is running. If a service is installed from a package, then Chef Infra Client cannot check to see if the service is running until after the package is installed. In that case, why-run mode will indicate what Chef Infra Client would do about the state of the service after installing a package. This is important because service actions often trigger notifications to other resources, so it is important to know that these notifications are triggered correctly. ### About chef-zero chef-zero is a very lightweight Chef Infra Server that runs in-memory on the local machine. This allows the Chef Infra Client to be run against the chef-repo as if it were running against the Chef Infra Server. chef-zero was [originally a standalone tool](https://github.com/chef/chef-zero); it is enabled from within the Chef Infra Client by using the `--local-mode` option. chef-zero is very useful for quickly testing and validating the behavior of the Chef Infra Client, cookbooks, recipes, and run-lists before uploading that data to the actual Chef Infra Server. Note chef-zero does not save data between restarts. Because it is intended to be used locally, chef-zero does not perform input validation, authentication, or authorization, as these security measures are not necessary for local testing. For these reasons, we strongly recommend against using chef-zero as a persistent Chef Infra Server. Changed in Chef Client 12.8, now chef-zero supports all Chef Server API version 12 endpoints, except `/universe`. ### Use Encrypted Data Bags Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. **Create an encrypted data bag for use with Chef Infra Client local mode** To generate an encrypted data bag item in a JSON file for use when Chef Infra Client is run in local mode (via the `--local-mode` option), enter: ``` knife data bag from file my_data_bag /path/to/data_bag_item.json -z --secret-file /path/to/encrypted_data_bag_secret ``` this will create an encrypted JSON file in: ``` data_bags/my_data_bag/data_bag_item.json ``` Run in FIPS Mode ---------------- Federal Information Processing Standards (FIPS) is a United States government computer security standard that specifies security requirements for cryptography. The current version of the standard is FIPS 140-2. Chef Infra Client can be configured to allow OpenSSL to enforce FIPS-validated security during a Chef Infra Client run. This will disable cryptography that is explicitly disallowed in FIPS-validated software, including certain ciphers and hashing algorithms. Any attempt to use any disallowed cryptography will cause Chef Infra Client to throw an exception during a Chef Infra Client run. Note Chef uses MD5 hashes to uniquely identify files that are stored on the Chef Infra Server. MD5 is used only to generate a unique hash identifier and is not used for any cryptographic purpose. Notes about FIPS: * May be enabled for nodes running on Microsoft Windows and Enterprise Linux platforms * Should only be enabled for environments that require FIPS 140-2 compliance **Bootstrap a node using FIPS** ``` knife bootstrap 192.0.2.0 -P vanilla -x root -r 'recipe[apt],recipe[xfs],recipe[vim]' --fips ``` which shows something similar to: ``` OpenSSL FIPS 140 mode enabled ... 192.0.2.0 Chef Infra Client finished, 12/12 resources updated in 78.942455583 seconds ``` Run as a Service ---------------- The Chef Infra Client can be run as a daemon. Use the **Chef Infra Client** cookbook to configure the Chef Infra Client as a daemon. Add the `default` recipe to a node’s run-list, and then use attributes in that cookbook to configure the behavior of the Chef Infra Client. For more information about these configuration options, see the [Chef Infra Client cookbook repository on github](https://github.com/chef-cookbooks/chef-client/). When the Chef Infra Client is run as a daemon, the following signals may be used: `HUP` Use to reconfigure the Chef Infra Client. `INT` Use to terminate immediately without waiting for the current Chef Infra Client run to finish. `QUIT` Use to dump a stack trace, and continue to run. `TERM` Use to terminate but wait for the current Chef Infra Client run to finish, and then exit. `USR1` Use to wake up sleeping Chef Infra Client and trigger node convergence. On Microsoft Windows, both the `HUP` and `QUIT` signals are not supported. Run with Elevated Privileges ---------------------------- The Chef Infra Client may need to be run with elevated privileges in order to get a recipe to converge correctly. On UNIX and UNIX-like operating systems this can be done by running the command as root. On Microsoft Windows this can be done by running the command prompt as an administrator. ### Linux On Linux, the following error sometimes occurs when the permissions used to run the Chef Infra Client are incorrect: ``` chef-client [Tue, 29 Nov 2015 19:46:17 -0800] INFO: *** Chef 12.X.X *** [Tue, 29 Nov 2015 19:46:18 -0800] WARN: Failed to read the private key /etc/chef/client.pem: #<Errno::EACCES: Permission denied - /etc/chef/client.pem``` This can be resolved by running the command as root. There are a few ways this can be done: * Log in as root and then run the Chef Infra Client * Use `su` to become the root user, and then run the Chef Infra Client. For example: ``` su ``` and then: ``` chef-client ``` * Use the sudo utility ``` sudo chef-client ``` * Give a user access to read `/etc/chef` and also the files accessed by the Chef Infra Client. This requires super user privileges and, as such, is not a recommended approach ### Windows On Microsoft Windows, running without elevated privileges (when they are necessary) is an issue that fails silently. It will appear that Chef Infra Client completed its run successfully, but the changes will not have been made. When this occurs, do one of the following to run Chef Infra Client as the administrator: * Log in to the administrator account. (This is not the same as an account in the administrator’s security group.) * Run Chef Infra Client process from the administrator account while being logged into another account. Run the following command: ``` runas /user:Administrator "cmd /C chef-client" ``` This will prompt for the administrator account password. * Open a command prompt by right-clicking on the command prompt application, and then selecting **Run as administrator**. After the command window opens, Chef Infra Client can be run as the administrator Run as Non-root User -------------------- In large, distributed organizations the ability to modify the configuration of systems is sometimes segmented across teams, often with varying levels of access to those systems. For example, core application services may be deployed to systems by a central server provisioning team, and then developers on different teams build tooling to support specific applications. In this situation, a developer only requires limited access to machines and only needs to perform the operations that are necessary to deploy tooling for a specific application. The default configuration of the Chef Infra Client assumes that it is run as the root user. This affords the Chef Infra Client the greatest flexibility when managing the state of any object. However, the Chef Infra Client may be run as a non-root user—i.e. “run as a user with limited system privileges”—which can be useful when the objects on the system are available to other user accounts. When the Chef Infra Client is run as a non-root user the Chef Infra Client can perform any action allowed to that user, as long as that action does not also require elevated privileges (such as sudo or pbrun). Attempts to manage any object that requires elevated privileges will result in an error. For example, when the Chef Infra Client is run as a non-root user that is unable to create or modify users, the **user** resource will not work. ### Set the Cache Path To run a Chef Infra Client in non-root mode, add the `file_cache_path` setting to the client.rb file for the node that will run as the non-root user. Set the value of `file_cache_path` to be the home directory for the user that is running the Chef Infra Client. For example: ``` file_cache_path '~/.chef/cache' ``` or: ``` file_cache_path File.join(File.expand_path('~'), '.chef', 'cache') ``` Note When running the Chef Infra Client using the `--local-mode` option, `~/.chef/local-mode-cache` is the default value for `file_cache_path`. ### Elevate Commands Another example of running the Chef Infra Client as a non-root user involves using resources to pass sudo commands as as an attribute on the resource. For example, the **service** resource uses a series of `_command` attributes (like `start_command`, `stop_command`, and so on), the **package**-based resources use the `options` attribute, and the **script**-based resources use the `code` attribute. A command can be elevated similar to the following: ``` service 'apache2' do start_command 'sudo /etc/init.d/apache2 start' action :start end ``` This approach can work very well on a case-by-case basis. The challenge with this approach is often around managing the size of the `/etc/sudoers` file. Run on IBM AIX -------------- The Chef Infra Client may now be used to configure nodes that are running on the AIX platform, versions 7.1 (TL5 SP2 or higher, recommended) and 7.2. The **service** resource supports starting, stopping, and restarting services that are managed by System Resource Controller (SRC), as well as managing all service states with BSD-based init systems. **System Requirements** The Chef Infra Client has the [same system requirements](chef_system_requirements/index#chef-infra-client) on the AIX platform as any other platform, with the following notes: * Expand the file system on the AIX platform using `chfs` or by passing the `-X` flag to `installp` to automatically expand the logical partition (LPAR) * The EN_US (UTF-8) character set should be installed on the logical partition prior to installing the Chef Infra Client **Install the Chef Infra Client on the AIX platform** The Chef Infra Client is distributed as a Backup File Format (BFF) binary and is installed on the AIX platform using the following command run as a root user: ``` # installp -aYgd chef-12.0.0-1.powerpc.bff all ``` **Increase system process limits** The out-of-the-box system process limits for maximum process memory size (RSS) and number of open files are typically too low to run the Chef Infra Client on a logical partition (LPAR). When the system process limits are too low, the Chef Infra Client will not be able to create threads. To increase the system process limits: 1. Validate that the system process limits have not already been increased. 2. If they have not been increased, run the following commands as a root user: ``` chsec -f /etc/security/limits -s default -a "rss=-1" ``` and then: ``` chsec -f /etc/security/limits -s default -a "data=-1" ``` and then: ``` chsec -f /etc/security/limits -s default -a "nofiles=50000" ``` Note The previous commands may be run against the root user, instead of default. For example: ``` chsec -f /etc/security/limits -s root_user -a "rss=-1" ``` 3. Reboot the logical partition (LPAR) to apply the updated system process limits. When the system process limits are too low, an error is returned similar to: ``` Error Syncing Cookbooks: ================================================================== Unexpected Error: ----------------- ThreadError: can't create Thread: Resource temporarily unavailable ``` **Install the UTF-8 character set** The Chef Infra Client uses the EN_US (UTF-8) character set. By default, the AIX base operating system does not include the EN_US (UTF-8) character set and it must be installed prior to installing the Chef Infra Client. The EN_US (UTF-8) character set may be installed from the first disc in the AIX media or may be copied from `/installp/ppc/*EN_US*` to a location on the logical partition (LPAR). This topic assumes this location to be `/tmp/rte`. Use `smit` to install the EN_US (UTF-8) character set. This ensures that any workload partitions (WPARs) also have UTF-8 applied. Remember to point `INPUT device/directory` to `/tmp/rte` when not installing from CD. 1. From a root shell type: ``` # smit lang ``` A screen similar to the following is returned: ``` Manage Language Environment Move cursor to desired item and press Enter. Change/Show Primary Language Environment Add Additional Language Environments Remove Language Environments Change/Show Language Hierarchy Set User Languages Change/Show Applications for a Language Convert System Messages and Flat Files F1=Help F2=Refresh F3=Cancel F8=Image F9=Shell F10=Exit Enter=Do ``` 2. Select `Add Additional Language Environments` and press `Enter`. A screen similar to the following is returned: ``` Add Additional Language Environments Type or select values in entry fields. Press Enter AFTER making all desired changes. [Entry Fields] CULTURAL convention to install + LANGUAGE translation to install + INPUT device/directory for software [/dev/cd0] + EXTEND file systems if space needed? yes + WPAR Management Perform Operation in Global Environment yes + Perform Operation on Detached WPARs no + Detached WPAR Names [_all_wpars] + Remount Installation Device in WPARs yes + Alternate WPAR Installation Device [] F1=Help F2=Refresh F3=Cancel F4=List F5=Reset F6=Command F7=Edit F8=Image F9=Shell F10=Exit Enter=Do ``` 3. Cursor over the first two entries—`CULTURAL convention to install` and `LANGUAGE translation to install`—and use `F4` to navigate through the list until `UTF-8 English (United States) [EN_US]` is selected. (EN_US is in capital letters!) 4. Press `Enter` to apply and install the language set. **Providers** The **service** resource has the following providers to support the AIX platform: | Long name | Short name | Notes | | --- | --- | --- | | `Chef::Provider::Service::Aix` | `service` | The provider that is used with the AIX platforms. Use the `service` short name to start, stop, and restart services with System Resource Controller (SRC). | | `Chef::Provider::Service::AixInit` | `service` | The provider that is used to manage BSD-based init services on AIX. | **Enable a service on AIX using the mkitab command** The **service** resource does not support using the `:enable` and `:disable` actions with resources that are managed using System Resource Controller (SRC). This is because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot. One approach for enabling or disabling services that are managed by System Resource Controller (SRC) is to use the **execute** resource to invoke `mkitab`, and then use that command to enable or disable the service. The following example shows how to install a service: ``` execute "install #{node['chef_client']['svc_name']} in SRC" do command "mkssys -s #{node['chef_client']['svc_name']} -p #{node['chef_client']['bin']} -u root -S -n 15 -f 9 -o #{node['chef_client']['log_dir']}/client.log -e #{node['chef_client']['log_dir']}/client.log -a ' -i #{node['chef_client']['interval']} -s #{node['chef_client']['splay']}'" not_if "lssrc -s #{node['chef_client']['svc_name']}" action :run end ``` and then enable it using the `mkitab` command: ``` execute "enable #{node['chef_client']['svc_name']}" do command "mkitab '#{node['chef_client']['svc_name']}:2:once:/usr/bin/startsrc -s #{node['chef_client']['svc_name']} > /dev/console 2>&1'" not_if "lsitab #{node['chef_client']['svc_name']}" end ``` Configuring a Proxy Server -------------------------- See the [proxies](proxies/index) documentation for information on how to configure Chef Infra Client to use a proxy server. Examples -------- **Run the Chef Infra Client** ``` sudo chef-client ``` **Start a run when the Chef Infra Client is running as a daemon** A Chef Infra Client that is running as a daemon can be woken up and started by sending the process a `SIGUSR1`. For example, to trigger a Chef Infra Client run on a machine running Linux: ``` sudo killall -USR1 chef-client ``` **Setting the initial run-list using a JSON file** A node’s initial run-list is specified using a JSON file on the host system. When running Chef Infra Client as an executable, use the `-j` option to tell Chef Infra Client which JSON file to use. For example: ``` chef-client -j /etc/chef/file.json --environment _default ``` where `file.json` is similar to: ``` { "resolver": { "nameservers": [ "10.0.0.1" ], "search":"int.example.com" }, "run_list": [ "recipe[resolver]" ] } ``` and where `_default` is the name of the environment that is assigned to the node. Warning This approach may be used to update [normal](attributes#attribute-types) attributes, but should never be used to update any other attribute type, as all attributes updated using this option are treated as `normal` attributes. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ctl_chef_client.htmlchef-server-ctl (executable) ============================ [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/ctl_chef_server.md) The Chef Infra Server includes a command-line utility named chef-server-ctl. This command-line tool is used to start and stop individual services, reconfigure the Chef Infra Server, run chef-pedant, and then tail Chef Infra Server log files. Backup / Restore ---------------- Use the following commands to manage backups of Chef Infra Server data, and then to restore those backups. ### backup The `backup` subcommand is used to back up all Chef Infra Server data. This subcommand: * Requires rsync to be installed on the Chef Infra Server prior to running the command * Requires a `chef-server-ctl reconfigure` prior to running the command * Should not be run in a Chef Infra Server configuration with an external PostgreSQL database; [use knife ec backup](https://github.com/chef/knife-ec-backup) instead * Puts the initial backup in the `/var/opt/chef-backup` directory as a tar.gz file; move this backup to a new location for safe keeping **Options** This subcommand has the following options: `-y`, `--yes` Use to specify if the Chef Infra Server can go offline during tar.gz-based backups. `--pg-options` Use to specify and pass additional options PostgreSQL during backups. See the [PostgreSQL documentation](https://www.postgresql.org/docs/13/runtime-config.html) for more information. `-c`, `--config-only` Backup the Chef Infra Server configuration **without** backing up data. `-t`, `--timeout` Set the maximum amount of time in seconds to wait for shell commands (default 600). This option should be set to greater than 600 for backups taking longer than 10 minutes. `-h`, `--help` Show help message. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl backup ``` ### restore The `restore` subcommand is used to restore Chef Infra Server data from a backup that was created by the `backup` subcommand. This subcommand may also be used to add Chef Infra Server data to a newly-installed server. Do not run this command in a Chef Infra Server configuration that uses an external PostgreSQL database; [use knife ec backup](https://github.com/chef/knife-ec-backup) instead. This subcommand: * Requires rsync installed on the Chef Infra Server before running the command * Requires a `chef-server-ctl reconfigure` before running the command Ideally, the restore server will have the same FQDN as the server that you backed up. If the restore server has a different FQDN, then: 1. Replace the FQDN in the `/etc/opscode/chef-server.rb`. 2. Replace the FQDN in the `/etc/opscode/chef-server-running.json`. 3. Delete the old SSL certificate, key and `-ssl.conf` file from `/var/opt/opscode/nginx/ca`. 4. If you use a CA-issued certificate instead of a self-signed certificate, copy the CA-issued certificate and key into `/var/opt/opscode/nginx/ca`. 5. Update the `/etc/chef/client.rb` file on each client to point to the new server FQDN. 6. Run `chef-server-ctl reconfigure`. 7. Run ``chef-server-ctl restore`. **Options** This subcommand has the following options: `-c`, `--cleanse` Use to remove all existing data on the Chef Infra Server; it will be replaced by the data in the backup archive. `-d DIRECTORY`, `--staging-dir DIRECTORY` Use to specify that the path to an empty directory to be used during the restore process. This directory must have enough disk space to expand all data in the backup archive. `--pg-options` ``` : Use to specify and pass additional options PostgreSQL during backups. See the [PostgreSQL documentation](https://www.postgresql.org/docs/13/runtime-config.html) for more information. `-t`, `--timeout` : Set the maximum amount of time in seconds to wait for shell commands. Set to greater than 600 for backups that take longer than 10 minutes. Default: 600. `-h`, `--help` : Show help message. **Syntax** This subcommand has the following syntax: ```bash chef-server-ctl restore PATH_TO_BACKUP (options) ``` **Examples** ``` chef-server-ctl restore /path/to/tar/archive.tar.gz ``` cleanse ------- The `cleanse` subcommand is used to re-set the Chef Infra Server to the state it was in prior to the first time the `reconfigure` subcommand is run. This command will destroy all data, configuration files, and logs. The software that was put on-disk by the package installation will remain; re-run `chef-server-ctl reconfigure` to recreate the default data and configuration files. **Options** This subcommand has the following options: `--with-external` Use to specify that Chef Infra Server data on an external PostgreSQL database should be removed. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl cleanse ``` gather-logs ----------- The `gather-logs` subcommand is used to gather the Chef Infra Server log files into a tarball that contains all of the important log files and system information. This subcommand has the following syntax: ``` chef-server-ctl gather-logs ``` help ---- The `help` subcommand is used to print a list of all available chef-server-ctl commands. This subcommand has the following syntax: ``` chef-server-ctl help ``` install ------- The `install` subcommand is used to install premium features of the Chef Infra Server: Chef management console and Chef Infra Client run reporting, high availability configurations, and Chef Infra Server replication. Warning The `chef-server-ctl install` command no longer works in the 12.5 (and earlier) versions of the Chef Infra Server due to a change in how packages are downloaded from Chef. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl install name_of_addon (options) ``` where `name_of_addon` represents the command line value associated with the add-on or premium feature. **Options** This subcommand has the following options: `--path PATH` Use to specify the location of a package. This option is not required when packages are downloaded from <https://packages.chef.io/>. ### Use Downloads The `install` subcommand downloads packages from <https://packages.chef.io> by default. For systems that are not behind a firewall (and have connectivity to <https://packages.chef.io>), these packages can be installed as described below. 1. Install add-ons Install Chef Manage with: ``` sudo chef-server-ctl install chef-manage ``` 2. Reconfigure the server ``` sudo chef-server-ctl reconfigure ``` 3. Reconfigure add-ons Reconfigure Chef Manage with: ``` sudo chef-manage-ctl reconfigure ``` Finally, accept the [Chef License](../chef_license/index): ``` sudo chef-manage-ctl reconfigure --accept-license ``` ### Use Local Packages Use the `install` subcommand with the `--path` option to install the Chef Manage (`chef-manage`) add-on for Chef Infra Server. ``` sudo chef-server-ctl install PACKAGE_NAME --path /path/to/package/directory ``` For example: ``` sudo chef-server-ctl install chef-manage --path /root/packages ``` The `chef-server-ctl` command will install the first `chef-manage` package found in the `/root/packages` directory. Key Rotation ------------ Use the following commands to manage public and private key rotation for users and clients. ### add-client-key Use the `add-client-key` subcommand to add a client key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl add-client-key ORG_NAME CLIENT_NAME [--public-key-path PATH] [--expiration-date DATE] [--key-name NAME] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `CLIENT_NAME` The name of the client that you wish to add a key for. `-e DATE` `--expiration-date DATE` An ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. For example: `2013-12-24T21:00:00Z`. If not passed, expiration will default to infinity. `-k NAME` `--key-name NAME` String defining the name of your new key for this client. If not passed, it will default to the fingerprint of the public key. `ORG_NAME` The short name for the organization to which the client belongs. `-p PATH` `--public-key-path PATH` The location to a file containing valid PKCS#1 public key to be added. If not passed, then the server will generate a new one for you and return the private key to STDOUT. ### add-user-key Use the `add-user-key` subcommand to add a user key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl add-user-key USER_NAME [--public-key-path PATH] [--expiration-date DATE] [--key-name NAME] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `-e DATE` `--expiration-date DATE` An ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. For example: `2013-12-24T21:00:00Z`. If not passed, expiration will default to infinity. `-k NAME` `--key-name NAME` String defining the name of your new key for this user. If not passed, it will default to the fingerprint of the public key. `-p PATH` `--public-key-path PATH` The location to a file containing valid PKCS#1 public key to be added. If not passed, then the server will generate a new one for you and return the private key to STDOUT. `USER_NAME` The user name for the user for which a key is added. ### delete-client-key Use the `delete-client-key` subcommand to delete a client key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl delete-client-key ORG_NAME CLIENT_NAME KEY_NAME ``` **Options** This subcommand has the following arguments: `ORG_NAME` The short name for the organization to which the client belongs. `CLIENT_NAME` The name of the client. `KEY_NAME` The unique name to be assigned to the key you wish to delete. ### delete-user-key Use the `delete-user-key` subcommand to delete a user key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl delete-user-key USER_NAME KEY_NAME ``` Warning The parameters for this subcommand must be in the order specified above. **Options** This subcommand has the following arguments: `USER_NAME` The user name. `KEY_NAME` The unique name to be assigned to the key you wish to delete. ### list-client-keys Use the `list-client-keys` subcommand to list client keys. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl list-client-keys ORG_NAME CLIENT_NAME [--verbose] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `CLIENT_NAME` The name of the client. `ORG_NAME` The short name for the organization to which the client belongs. `--verbose` Use to show the full public key strings in command output. ### list-user-keys Use the `list-user-keys` subcommand to list client keys. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl list-user-keys USER_NAME [--verbose] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `USER_NAME` The user name you wish to list keys for. `--verbose` Use to show the full public key strings in command output. **Example** To view a list of user keys (including public key output): ``` chef-server-ctl list-user-keys applejack --verbose ``` Returns: ``` 2 total key(s) found for user applejack key_name: test-key expires_at: Infinity public_key: -----BEGIN PUBLIC KEY----- <KEY> -----END PUBLIC KEY----- key_name: default expires_at: Infinity public_key: -----<KEY>----- ``` Secrets Management ------------------ Use the following commands to manage and rotate shared secrets and service credentials. The secrets file used for storing these is located at `/etc/opscode/private-chef-secrets.json` on your Chef Infra Server. It should be owned and readable only by `root`. ### set-secret The `set-secret` subcommand allows storing shared secrets and service credentials. Only secrets known to Chef Infra Server can be stored. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl set-secret GROUP NAME ``` There are various ways to pass the secret to this command: 1. as a third argument: ``` chef-server-ctl set-secret ldap bind_password secretpassword ``` 2. via an environment variable: ``` export LDAP.BIND_PASSWORD="secretpassword" chef-server-ctl set-secret ldap bind_password ``` 3. via an interactive prompt: ``` chef-server-ctl set-secret ldap bind_password Enter ldap bind_password: (no terminal output) Re-enter ldap bind_password: (no terminal output) ``` **Options** This subcommand has the following options: `--with-restart` If any services depend on the secret being changed, attempt to restart them after changing the secret. Added in Chef Infra Server 12.16.2. ### remove-secret The `remove-secret` subcommand allows removing a stored shared secret and service credential. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl remove-secret GROUP NAME ``` **Example** ``` chef-server-ctl remove-secret ldap bind_password ``` ### show-secret The `show-secret` subcommand allows viewing a stored shared secret and service credential. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl show-secret GROUP NAME ``` ### set-db-superuser-password The `set-db-superuser-password` subcommand allows storing the database superuser password. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl set-db-superuser-password ``` Similar to `set-secret`, the superuser password can also be provided via the environment variable `DB_PASSWORD`. ### set-actions-password The `set-actions-password` subcommand allows storing the RabbitMQ Actions password. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl set-actions-password ``` Similar to `set-secret`, the action password can also be provided via the environment variable `ACTIONS_PASSWORD`. ### oc-id-show-app The `oc-id-show-app` subcommand allows for retrieving the client ID and client secret for applications known to **oc-id**. Note that with `insecure_addon_compat` [disabled](../server/server_security/index#chef-infra-server-credentials-management), this data will no longer be written to `/etc/opscode/oc-id-applications/APP.json`. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl oc-id-show-app APP ``` **Example** ``` chef-server-ctl oc-id-show-app supermarket { "name": "supermarket", "uid": "0bad0f2eb04e935718e081fb71asdfec3681c81acb9968a8e1e32451d08b", "secret": "17cf1141cc971a10ce307611beda7ffadstr4f1bc98d9f9ca76b9b127879", "redirect_uri": "https://supermarket.mycompany.com/auth/chef_oauth2/callback" } ``` ### require-credential-rotation The `require-credential-rotation` subcommand takes the Chef Infra Server offline and requires a complete service credential rotation before the Chef Infra Server(s) in your cluster can restart again. Run `rotate-shared-secrets` to create a new shared secret, salt, and generate the new service credentials. Then copy the secrets file to each Chef Infra Server and run `sudo chef-server-ctl reconfigure` on each server to complete the rotation process. Note Credential rotation does not rotate the pivotal, user, or client keys, or remove any Chef Infra Server policy or cookbooks that have been uploaded. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl require-credential-rotation (options) ``` **Options** This subcommand has the following options: `-y, --yes` Bypass a prompt in the terminal and agree that you want to disable the Chef Infra Server, and require credential rotation. ### rotate-all-credentials The `rotate-all-credentials` subcommand generates new credential values for all service credentials by incrementing the credential version number and creating a new hash value. You can choose whether to copy the updated secrets file to each node in the cluster and reconfiguring or by running this subcommand on all the nodes. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl rotate-all-credentials ``` ### rotate-credentials The `rotate-credentials` subcommand generates new credential values for all credentials for a given service by incrementing the value and creating a new hash value. You can choose whether to copy the updated secrets file to each node in the cluster and reconfiguring or by running this subcommand for that specific service on all the nodes. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl rotate-credentials SERVICE_NAME ``` ### rotate-shared-secrets The `rotate-shared-secrets` subcommand creates a new shared secret and salt, in addition to generating new service credentials. It also resets the `credential_version` number for the services to 0. After you have run this subcommand, a new shared secret has been created, so you must copy the secrets file to each Chef Infra Server and run `sudo chef-server-ctl reconfigure` on them to complete the rotation process. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl rotate-shared-secrets ``` ### show-service-credentials The `show-service-credentials` subcommand shows all of the service credentials for services running on the local Chef Infra Server. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl show-service-credentials ``` ### cleanup-bifrost The `cleanup-bifrost` subcommand removes unused authorization objects from the authorization database (called bifrost). These unused objects can accumulate on long-running Chef Infra Servers as a result of failed object creation requests. For most users, the unused authorization objects do not substantially affect the performance of Chef Infra Server; however in certain situations it can be helpful to clean them up. This command is primarily intended for use by Chef support. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl cleanup-bifrost OPTIONS ``` **Options** This subcommand has the following options: `--estimate-only` Provides an estimate of the number of unused objects that will be deleted, without deleting anything. `--wait-time SECONDS` The number of seconds to wait for in-flight requests to complete. Only decrease this value if you are running the command when the Chef Infra Server is not taking requests. `--force-cleanup` Removes internal tracking tables used during the cleanup process. Manual cleanup of these tables is only required if the cleanup command is killed unexpectedly. `--batch-size` The number of orphaned authorization actors to delete at a time. Manage Organizations -------------------- Use the `org-create`, `org-delete`, `org-list`, `org-show`, `org-user-add` and `org-user-remove` commands to manage organizations. ### org-create The `org-create` subcommand is used to create an organization. (The validation key for the organization is returned to `STDOUT` when creating an organization with this command.) **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-create ORG_NAME "ORG_FULL_NAME" (options) ``` where: * The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. * The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `"Chef Software, Inc."`. **Options** This subcommand has the following options: `-a USER_NAME`, `--association_user USER_NAME` Associate a user with an organization and add them to the `admins` and `billing_admins` security groups. `-f FILE_NAME`, `--filename FILE_NAME` Write the ORGANIZATION-validator.pem to `FILE_NAME` instead of printing it to `STDOUT`. **Examples** ``` chef-server-ctl org-create prod Production ``` ``` chef-server-ctl org-create staging Staging -a chef-admin ``` ``` chef-server-ctl org-create dev Development -f /tmp/id-dev.key ``` ``` chef-server-ctl org-create dev Development --association_user grantmc ``` ### org-delete The `org-delete` subcommand is used to delete an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-delete ORG_NAME ``` **Examples** ``` chef-server-ctl org-delete infra-testing-20140909 ``` ``` chef-server-ctl org-delete pedant-testing-org ``` ### org-list The `org-list` subcommand is used to list all of the organizations currently present on the Chef Infra Server. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-list (options) ``` **Options** This subcommand has the following options: `-a`, `--all-orgs` Show all organizations. `-w`, `--with-uri` Show the corresponding URIs. ### org-show The `org-show` subcommand is used to show the details for an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-show ORG_NAME ``` ### org-user-add The `org-user-add` subcommand is used to add a user to an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-user-add ORG_NAME USER_NAME (options) ``` **Options** This subcommand has the following options: `--admin` Add the user to the `admins` group. **Examples** ``` chef-server-ctl org-user-add prod john_smith ``` ``` chef-server-ctl org-user-add preprod testmaster ``` ``` chef-server-ctl org-user-add dev grantmc --admin ``` ### org-user-remove The `org-user-remove` subcommand is used to remove a user from an organization. Warning A user who belongs to the `admins` group must be removed from the group before they may be removed from an organization. To remove a user from the `admins` group, run the following: ``` EDITOR=vi knife edit /groups/admins.json ``` make the required changes, and then save the file. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-user-remove ORG_NAME USER_NAME (options) ``` **Options** This subcommand has the following options: `--force` Force the removal of a user from the organization’s `admins` and `billing-admins` groups. **Examples** ``` chef-server-ctl org-user-remove prod john_smith ``` ``` chef-server-ctl org-user-remove prod testmaster ``` ``` chef-server-ctl org-user-remove grantmc --force ``` password -------- The `password` subcommand is used to change a user’s password. When Active Directory or LDAP is enabled, this command enables (or disables) the system recovery password for that user. For example: This subcommand has the following syntax: ``` chef-server-ctl password USERNAME ``` This subcommand has the following options: `--disable` Use this option to disable a user’s system recovery password. **Examples** For example, to change a user’s password, enter: ``` chef-server-ctl password adamjacobs ``` and then enter the password and confirm it: ``` Enter the new password: ****** Enter the new password again: ****** ``` to return: ``` Password for adamjacobs successfully set. ``` To disable a system recovery password: ``` chef-server-ctl password adamjacobs --disable ``` to return: ``` Password for adamjacobs successfully disabled for System Recovery. ``` psql ---- The `psql` subcommand is used to log into the PostgreSQL database associated with the named service. This subcommand: * Uses `psql` (the interactive terminal for PostgreSQL) * Has read-only access by default * Is the recommended way to interact with any PostgreSQL database that is part of the Chef Infra Server * Automatically handles authentication **Syntax** This subcommand has the following syntax: ``` chef-server-ctl psql SERVICE_NAME (options) ``` **Options** This subcommand has the following options: `--write` Use to enable write access to the PostgreSQL database. reconfigure ----------- The `reconfigure` subcommand is used when changes are made to the chef-server.rb file to reconfigure the server. When changes are made to the chef-server.rb file, they will not be applied to the Chef Infra Server configuration until after this command is run. This subcommand will also restart any services for which the `service_name['enabled']` setting is set to `true`. This subcommand has the following syntax: ``` chef-server-ctl reconfigure ``` reindex ------- The `reindex` subcommand is used to reload Chef Infra Server data from PostgreSQL to Elasticsearch. This subcommand has the following syntax: ``` chef-server-ctl reindex ``` Note Chef Infra Server versions earlier than 14.5 configured with `nginx['enable_non_ssl'] = false` and `fips = true` require `export CSC_LB_URL=https://127.0.0.1` to run the command `chef-server-ctl reindex <options>` **Options** This subcommand has the following options: `-a`, `--all-orgs` Use to reindex all organizations on the Chef Infra Server. This option will override any organization specified as part of the command, i.e. `chef-server-ctl reindex ORG_NAME -a` will reindex all organizations and not just the specified organization. `-d`, `--disable-api` Use to disable the Chef Infra Server API to prevent writes during reindexing. `-t`, `--with-timing` Use to print timing information for the reindex processes. `-w`, `--wait` Use to wait for the reindexing queue to clear before exiting. This option only works when run on a standalone Chef Infra Server or on a primary backend Chef server within a legacy tier. Server Admins ------------- The `server-admins` group is a global group that grants its members permission to create, read, update, and delete user accounts, with the exception of superuser accounts. The `server-admins` group is useful for users who are responsible for day-to-day administration of the Chef Infra Server, especially user management via the `knife user` subcommand. Before members can be added to the `server-admins` group, they must already have a user account on the Chef Infra Server. ### Scenario The following user accounts exist on the Chef Infra Server: `pivotal` (a superuser account), `alice`, `bob`, `carol`, and `dan`. Run the following command to view a list of users on the Chef Infra Server: ``` chef-server-ctl user-list ``` and it returns the same list of users: ``` pivotal alice bob carol dan ``` Alice is a member of the IT team whose responsibilities include day-to-day administration of the Chef Infra Server, in particular managing the user accounts on the Chef Infra Server that are used by the rest of the organization. From a workstation, Alice runs the following command: ``` knife user list -c ~/.chef/alice.rb ``` and it returns the following error: ``` ERROR: You authenticated successfully to <chef_server_url> as alice but you are not authorized for this action Response: Missing read permission ``` Alice is not a superuser and does not have permissions on other users because user accounts are global to organizations in the Chef Infra Server. Let’s add Alice to the `server-admins` group: ``` chef-server-ctl grant-server-admin-permissions alice ``` and it returns the following response: ``` User alice was added to server-admins. ``` Alice can now create, read, update, and delete user accounts on the Chef Infra Server, even for organizations to which Alice is not a member. From a workstation, Alice re-runs the following command: ``` knife user list -c ~/.chef/alice.rb ``` which now returns: ``` pivotal alice bob carol dan ``` Alice is now a server administrator and can use the following knife subcommands to manage users on the Chef Infra Server: * `knife user-create` * `knife user-delete` * `knife user-edit` * `knife user-list` * `knife user-show` For example, Alice runs the following command: ``` knife user edit carol -c ~/.chef/alice.rb ``` and the $EDITOR opens in which Alice makes changes, and then saves them. #### Superuser Accounts Superuser accounts may not be managed by users who belong to the `server-admins` group. For example, Alice attempts to delete the `pivotal` superuser account: ``` knife user delete pivotal -c ~/.chef/alice.rb ``` and the following error is returned: ``` ERROR: You authenticated successfully to <chef_server_url> as user1 but you are not authorized for this action Response: Missing read permission ``` Alice’s action is unauthorized even with membership in the `server-admins` group. ### Manage server-admins Group Membership of the `server-admins` group is managed with a set of `chef-server-ctl` subcommands: * `chef-server-ctl grant-server-admin-permissions` * `chef-server-ctl list-server-admins` * `chef-server-ctl remove-server-admin-permissions` #### Add Members The `grant-server-admin-permissions` subcommand is used to add a user to the `server-admins` group. Run the command once per user added. This subcommand has the following syntax: ``` chef-server-ctl grant-server-admin-permissions USER_NAME ``` where `USER_NAME` is the user to add to the list of server administrators. For example: ``` chef-server-ctl grant-server-admin-permissions bob ``` returns: ``` User bob was added to server-admins. This user can now list, read, and create users (even for orgs they are not members of) for this Chef Infra Server. ``` #### Remove Members The `remove-server-admin-permissions` subcommand is used to remove a user from the `server-admins` group. Run the command once per user removed. This subcommand has the following syntax: ``` chef-server-ctl remove-server-admin-permissions USER_NAME ``` where `USER_NAME` is the user to remove from the list of server administrators. For example: ``` chef-server-ctl remove-server-admin-permissions bob ``` returns: ``` User bob was removed from server-admins. This user can no longer list, read, and create users for this Chef Infra Server except for where they have default permissions (such as within an org). ``` #### List Membership The `list-server-admins` subcommand is used to return a list of users who are members of the `server-admins` group. This subcommand has the following syntax: ``` chef-server-ctl list-server-admins ``` and will return a list of users similar to: ``` pivotal alice bob carol dan ``` show-config ----------- The `show-config` subcommand is used to view the configuration that will be generated by the `reconfigure` subcommand. This command is most useful in the early stages of a deployment to ensure that everything is built properly prior to installation. This subcommand has the following syntax: ``` chef-server-ctl show-config ``` uninstall --------- The `uninstall` subcommand is used to remove the Chef Infra Server application, but without removing any of the data. This subcommand will shut down all services (including the `runit` process supervisor). This subcommand has the following syntax: ``` chef-server-ctl uninstall ``` Note To revert the `uninstall` subcommand, run the `reconfigure` subcommand (because the `start` subcommand is disabled by the `uninstall` command). upgrade ------- The `upgrade` subcommand is used to upgrade the Chef Infra Server. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl upgrade (options) ``` **Options** This subcommand has the following options: `-d DIRECTORY`, `--chef11-data-dir DIRECTORY` The directory in which Chef Infra Server 11 data is located. Default value: a temporary directory. `-e DIRECTORY`, `--chef12-data-dir DIRECTORY` The directory in which Chef Infra Server 12 data is located. Default value: a temporary directory. `-f FULL_NAME`, `--full-org-name FULL_NAME` The full name of the Chef Infra Server organization. The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `Chef Software, Inc.`. If this option is not specified, the `upgrade` command will prompt for it. `-h`, `--help` Use to show help for the `chef-server-ctl upgrade` subcommand. `-k KEY_PATH`, `--key KEY_PATH` The Chef Infra Server 11 `admin.pem` key for the API client. This is the key used to download Chef Infra Server 11 data. Default value: `/etc/chef-server/admin.pem`. `-o ORG_NAME`, `--org-name ORG_NAME` The name of the Chef Infra Server organization. The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. If this option is not specified, the `upgrade` command will prompt for it. `-s URL`, `--chef11-server-url URL` The URL for the Chef Infra Server version 11. Default value: `https://localhost`. `-t NUMBER`, `--upload-threads NUMBER` The number of threads to use when migrating cookbooks. Default value: `10`. `-u USER`, `--user` Create a client as an admin client. This is required for any user to access Chef as an administrator. `-x URL`, `--chef12-server-url URL` The URL for the Chef Infra Server, version 12. Default value: `https://localhost`. `-y`, `--yes` Use to skip confirmation prompts during the upgrade process. User Management --------------- Use the `user-create`, `user-delete`, `user-edit`, `user-list` and `user-show` subcommands to manage users. ### user-create The `user-create` subcommand is used to create a user. (The validation key for the organization may be returned to `STDOUT` when creating a user with this command.) **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-create USER_NAME FIRST_NAME [MIDDLE_NAME] LAST_NAME EMAIL 'PASSWORD' (options) ``` **Options** This subcommand has the following options: `-f FILE_NAME`, `--filename FILE_NAME` Write the USER.pem to a file instead of `STDOUT`. **Examples** ``` chef-server-ctl user-create john_smith <NAME> <EMAIL> p@s5w0rD! ``` ``` chef-server-ctl user-create jane_doe <NAME> <EMAIL> p@s5w0rD! -f /tmp/jane_doe.key ``` ``` chef-server-ctl user-create waldendude <NAME> <EMAIL> excursions ``` ### user-delete The `user-delete` subcommand is used to delete a user. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-delete USER_NAME ``` **Examples** ``` chef-server-ctl user-delete john_smith ``` ``` chef-server-ctl user-delete jane_doe ``` **Options** This subcommand has the following options: `-R`, `--remove-from-admin-groups` Removes a user who is in one or more ‘admin’ groups unless that user is the only member of the ‘admin’ group(s). ### user-edit The `user-edit` subcommand is used to edit the details for a user. The data will be made available in the $EDITOR for editing. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-edit USER_NAME ``` **Examples** ``` chef-server-ctl user-edit john_smith ``` ``` chef-server-ctl user-edit jane_doe ``` ### user-list The `user-list` subcommand is used to view a list of users. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-list (options) ``` **Options** This subcommand has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### user-show The `user-show` subcommand is used to show the details for a user. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-show USER_NAME (options) ``` **Options** This subcommand has the following options: `-l`, `--with-orgs` Show all organizations. Service Subcommands ------------------- This command has a built in process supervisor that ensures all of the required services are in the appropriate state at any given time. The supervisor starts two processes per service and provides the following subcommands for managing services: `hup`, `int`, `kill`, `once`, `restart`, `service-list`, `start`, `status`, `stop`, `tail`, and `term`. Warning The following commands are disabled when an external PostgreSQL database is configured for the Chef Infra Server: `hup`, `int`, `kill`, `once`, `restart`, `start`, `stop`, `tail`, and `term`. ### hup The `hup` subcommand is used to send a `SIGHUP` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl hup SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### int The `int` subcommand is used to send a `SIGINT` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl int SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### kill The `kill` subcommand is used to send a `SIGKILL` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl kill SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### once The supervisor for the Chef Infra Server is configured to restart any service that fails, unless that service has been asked to change its state. The `once` subcommand is used to tell the supervisor to not attempt to restart any service that fails. This command is useful when troubleshooting configuration errors that prevent a service from starting. Run the `once` subcommand followed by the `status` subcommand to look for services in a down state and/or to identify which services are in trouble. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl once SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### restart The `restart` subcommand is used to restart all services enabled on the Chef Infra Server or to restart an individual service by specifying the name of that service in the command. Warning When running the Chef Infra Server in a high availability configuration, restarting all services may trigger failover. This subcommand has the following syntax: ``` chef-server-ctl restart SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully restarted the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` ### service-list The `service-list` subcommand is used to display a list of all available services. A service that is enabled is labeled with an asterisk (*). This subcommand has the following syntax: ``` chef-server-ctl service-list ``` ### start The `start` subcommand is used to start all services that are enabled in the Chef Infra Server. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl start SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully started the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` The supervisor for the Chef Infra Server is configured to wait seven seconds for a service to respond to a command from the supervisor. If you see output that references a timeout, it means that a signal has been sent to the process, but that the process has yet to actually comply. In general, processes that have timed out are not a big concern, unless they are failing to respond to the signals at all. If a process is not responding, use a command like the `kill` subcommand to stop the process, investigate the cause (if required), and then use the `start` subcommand to re-enable it. ### status The `status` subcommand is used to show the status of all services available to the Chef Infra Server. The results will vary based on the configuration of a given server. This subcommand has the following syntax: ``` chef-server-ctl status ``` and will return the status for all services. Status can be returned for individual services by specifying the name of the service as part of the command: ``` chef-server-ctl status SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When service status is requested, the output should be similar to: ``` run: service_name: (pid 12345) 12345s; run: log: (pid 1234) 67890s ``` where * `run:` is the state of the service (`run:` or `down:`) * `service_name:` is the name of the service for which status is returned * `(pid 12345)` is the process identifier * `12345s` is the uptime of the service, in seconds For example: ``` down: opscode-erchef: (pid 35546) 10s ``` By default, runit will restart services automatically when the services fail. Therefore, runit may report the status of a service as `run:` even when there is an issue with that service. When investigating why a particular service is not running as it should be, look for the services with the shortest uptimes. For example, the list below indicates that the **opscode-erchef** should be investigated further: ``` run: oc-id run: opscode-chef: (pid 4327) 13671s; run: log: (pid 4326) 13671s run: opscode-erchef: (pid 5383) 5s; run: log: (pid 4382) 13669s ``` #### Log Files A typical status line for a service that is running any of the Chef Infra Server front-end services is similar to the following: ``` run: name_of_service: (pid 1486) 7819s; run: log: (pid 1485) 7819s ``` where: * `run` describes the state in which the supervisor attempts to keep processes. This state is either `run` or `down`. If a service is in a `down` state, it should be stopped * `name_of_service` is the service name, for example: `opscode-erchef` * `(pid 1486) 7819s;` is the process identifier followed by the amount of time (in seconds) the service has been running * `run: log: (pid 1485) 7819s` is the log process. It is typical for a log process to have a longer run time than a service; this is because the supervisor does not need to restart the log process in order to connect the supervised process If the service is down, the status line will appear similar to the following: ``` down: opscode-erchef: 3s, normally up; run: log: (pid 1485) 8526s ``` where * `down` indicates that the service is in a down state * `3s, normally up;` indicates that the service is normally in a run state and that the supervisor would attempt to restart this service after a reboot ### stop The `stop` subcommand is used to stop all services enabled on the Chef Infra Server. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl stop SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully stopped the output should be similar to: ``` ok: down: service_name: 0s, normally up ``` For example: ``` chef-server-ctl stop ``` will return something similar to: ``` ok: down: nginx: 393s, normally up ok: down: opscode-chef: 391s, normally up ok: down: opscode-erchef: 391s, normally up ok: down: opscode-solr4: 389s, normally up ok: down: postgresql: 388s, normally up ok: down: redis_lb: 387s, normally up ``` ### tail The `tail` subcommand is used to follow all of the Chef Infra Server logs for all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl tail SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### term The `term` subcommand is used to send a `SIGTERM` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl term SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ctl_chef_server/About Nodes =========== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/nodes.md) A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. The types of nodes that can be managed by Chef include, but are not limited to, the following: | Node Type | Description | | --- | --- | | image | A physical node is typically a server or a virtual machine, but it can be any active device attached to a network that is capable of sending, receiving, and forwarding information over a communications channel. In other words, a physical node is any active device attached to a network that can run a Chef Infra Client and also allow that Chef Infra Client to communicate with a Chef Infra Server. | | image | A cloud-based node is hosted in an external cloud-based service, such as Amazon Web Services (AWS), OpenStack, Rackspace, Google Compute Engine, or Microsoft Azure. Plugins are available for knife that provide support for external cloud-based services. knife can use these plugins to create instances on cloud-based services. Once created, Chef Infra Client can be used to deploy, configure, and maintain those instances. | | image | A virtual node is a machine that runs only as a software implementation, but otherwise behaves much like a physical machine. | | image | A network node is any networking device---a switch, a router---that is being managed by a Chef Infra Client, such as networking devices by Juniper Networks, Arista, Cisco, and F5. Use Chef to automate common network configurations, such as physical and logical Ethernet link properties and VLANs, on these devices. | | image | Containers are an approach to virtualization that allows a single operating system to host many working configurations, where each working configuration---a container---is assigned a single responsibility that is isolated from all other responsibilities. Containers are popular as a way to manage distributed and scalable applications and services. | The key components of nodes that are under management by Chef include: | Component | Description | | --- | --- | | image | Chef Infra Client is an agent that runs locally on every node that is under management by Chef Infra Server. When Chef Infra Client runs, it performs all of the steps required for bringing a node into the expected state, including:* Registering and authenticating the node with Chef Infra Server * Synchronizing cookbooks from the Chef Infra Server to the node * Compiling the resource collection by loading each of the required cookbooks, including recipes, attributes, and all other dependencies * Taking the appropriate and required actions to configure the node based on recipes and attributes * Reporting summary information on the run to Chef Automate Chef Infra Client authenticates with the Chef Infra Server using RSA public key-pairs each time a Chef Infra Client needs access to data that is stored on the Chef Infra Server. This prevents any node from accessing data that it shouldn’t and it ensures that only nodes that are properly registered with the Chef Infra Server can be managed. | | image | Ohai is a tool for collecting system configuration data, which it then provides to Chef Infra Client to use in cookbooks. Chef Infra Client runs Ohai at the start of every Chef Infra run to determine system state. The attributes that Ohai collects are called `automatic attributes`. Chef Infra Client uses these attributes to ensure that nodes are in the desired state after each configuration run. The types of attributes Ohai collects include but are not limited to:* Operating System * Network * Memory * Disk * CPU * Kernel * Host names * Fully qualified domain names * Virtualization * Cloud provider metadata Ohai includes required and optional plugins to detect common configuration information. Ohai has a plugin model and language to write [custom plugins](ohai_custom/index) to collect additional system state information. | Node Names ---------- The name of a node is required as part of the authentication process to the Chef Infra Server. The name of each node must be unique within an organization, but otherwise can be any string that matches the following regular expression: ``` /^[\-[:alnum:]_:.]+$/ ``` The name of a node can be obtained from the `node_name` attribute in the client.rb file or by allowing Ohai to collect this data during a Chef Infra Client run. When Ohai collects this data during a Chef Infra Client run, it uses the node’s FQDN, which is always unique within an organization, as the name of the node. Using the FQDN as the node name, and then allowing Ohai to collect this information during each Chef Infra Client run, is the recommended approach and the easiest way to ensure that the names of all nodes across the organization are unique. Node Objects ------------ For Chef Infra Client, two important aspects of nodes are groups of attributes and run-lists. An attribute is a specific piece of data about the node, such as a network interface, a file system, the number of clients a service running on a node is capable of accepting, and so on. A run-list is an ordered list of recipes and/or roles that are run in an exact order. The node object consists of the run-list and node attributes, which is a JSON file that is stored on the Chef Infra Server. Chef Infra Client gets a copy of the node object from the Chef Infra Server during each Chef Infra Client run and places an updated copy on the Chef Infra Server at the end of each Chef Infra Client run. An attribute is a specific detail about a node. Attributes are used by Chef Infra Client to understand: * The current state of the node * What the state of the node was at the end of the previous Chef Infra Client run * What the state of the node should be at the end of the current Chef Infra Client run Attributes are defined by: * The node as saved on the Chef Infra Server * Attributes passed via JSON on the command line * Cookbooks (in attribute files and/or recipes) * Policyfiles During every Chef Infra Client run, Chef Infra Client builds the attribute list using: * Attributes passed via JSON on the command line * Data about the node collected by [Ohai](ohai). * The node object that was saved to the Chef Infra Server at the end of the previous Chef Infra Client run. * The rebuilt node object from the current Chef Infra Client run, after it is updated for changes to cookbooks (attribute files and/or recipes) and/or Policyfiles, and updated for any changes to the state of the node itself. After the node object is rebuilt, all of the attributes are compared, and then the node is updated based on attribute precedence. At the end of every Chef Infra Client run, the node object that defines the current state of the node is uploaded to the Chef Infra Server so that it can be indexed for search. ### Attributes An attribute is a specific detail about a node, such as an IP address, a host name, a list of loaded kernel modules, the version(s) of available programming languages that are available, and so on. An attribute may be unique to a specific node or it can be identical across every node in the organization. Attributes are most commonly set from a cookbook, by using knife, or are retrieved by Ohai from each node prior to every Chef Infra Client run. All attributes are indexed for search on the Chef Infra Server. Good candidates for attributes include: * any cross-platform abstraction for an application, such as the path to a configuration file * default values for tunable settings, such as the amount of memory assigned to a process or the number of workers to spawn * anything that may need to be persisted in node data between Chef Infra Client runs In general, attribute precedence is set to enable cookbooks and roles to define attribute defaults, for normal attributes to define the values that should be specific for a node, and for override attributes to force a certain value, even when a node already has that value specified. One approach is to set attributes at the same precedence level by setting attributes in a cookbook’s attribute files, and then also setting the same default attributes (but with different values) using a role. The attributes set in the role will be deep merged on top of the attributes from the attribute file, and the attributes set by the role will take precedence over the attributes specified in the cookbook’s attribute files. See [Attributes](attributes) for detailed information on the different types of node attributes and how they are used to set policy on nodes. ### Run-lists A run-list defines all of the information necessary for Chef to configure a node into the desired state. A run-list is: * An ordered list of roles and/or recipes that are run in the exact order defined in the run-list; if a recipe appears more than once in the run-list, Chef Infra Client will not run it twice * Always specific to the node on which it runs; nodes may have a run-list that is identical to the run-list used by other nodes * Stored as part of the node object on the Chef server * Maintained using knife and then uploaded from the workstation to the Chef Infra Server, or maintained using Chef Automate #### Run-list Format A run-list must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: ``` "role[NAME]" ``` or ``` "recipe[COOKBOOK::RECIPE]" ``` Use a comma to separate roles and recipes when adding more than one item the run-list: ``` "recipe[COOKBOOK::RECIPE],COOKBOOK::RECIPE,role[NAME]" ``` Managing Nodes -------------- You can manage nodes directly using Knife, Chef Automate, or by using command-line tools that are specific to Chef Infra Client. * [Knife](workstation/knife/index) can be used to create, edit, view, list, tag, and delete nodes. * Knife plug-ins can be used to create, edit, and manage nodes that are located on cloud providers. * Chef Infra Client can be used to manage node data using the command line and JSON files. Each JSON file contains a hash, the elements of which are added as node attributes. In addition, the `run_list` setting allows roles and/or recipes to be added to the node. * The command line can also be used to edit JSON files and files that are related to third-party services, such as Amazon EC2, where the JSON files can contain per-instance metadata that is stored in a file on-disk and then read by Chef Infra Client as required. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/nodesconfig.rb ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/config_rb.md) Warning The `config.rb` file is a replacement for the `knife.rb` file. The `config.rb` file has identical settings and behavior to the `knife.rb` file. Chef Infra Client looks first for the presence of the `config.rb` file and if it is not found, then looks for the `knife.rb` file. A `config.rb` file is used to specify configuration details for knife. A `config.rb` file: * Is loaded every time the knife executable is run * Is not created by default * Is located by default at `~/.chef/config.rb` (macOS and Linux platforms) or `c:\Users\username\.chef\config.rb` (Microsoft Windows platform), use the `--config` option from the command line to change this location * Will override the default configuration when a `config.rb` file exists at the default path or the path specified by the `--config` option Note When running Microsoft Windows, the `config.rb` file is located at `%HOMEDRIVE%:%HOMEPATH%\.chef` (e.g. `c:\Users\<username>\.chef`). Settings -------- This configuration file has the following settings: `bootstrap_template` The path to a template file to be used during a bootstrap operation. `chef_server_url` The URL for the Chef Infra Server. For example: ``` chef_server_url 'https://localhost/organizations/ORG_NAME' ``` Note If changes need to be made to any global end points like user or user keys, use [`knife exec`](knife_exec/index) with the `--server-url` flag to set `chef_server_url` to `https://localhost/`. `chef_zero.enabled` Enable chef-zero. This setting requires `local_mode` to be set to `true`. Default value: `false`. For example: ``` chef_zero.enabled true ``` `chef_zero[:port]` The port on which chef-zero is to listen. Default value: `8889`. For example: ``` chef_zero[:port] 8889 ``` `client_d_dir` A directory that contains additional configuration scripts to load for Chef Infra Client. `client_key` The location of the file that contains the client key, as an absolute path. Default value: `/etc/chef/client.pem`. For example: ``` client_key '/etc/chef/client.pem' ``` `cookbook_copyright` The name of the copyright holder. This option places a copyright notice that contains the name of the copyright holder in each of the pre-created files. If this option is not specified, a copyright name of “COMPANY_NAME” is used instead; it can easily be modified later. `cookbook_email` The email address for the individual who maintains the cookbook. This option places an email address in each of the pre-created files. If not specified, an email name of “YOUR_EMAIL” is used instead; this can easily be modified later. `cookbook_license` The type of license under which a cookbook is distributed: `apachev2`, `gplv2`, `gplv3`, `mit`, or `none` (default). This option places the appropriate license notice in the pre-created files: `Apache v2.0` (for `apachev2`), `GPL v2` (for `gplv2`), `GPL v3` (for `gplv3`), `MIT` (for `mit`), or `license 'Proprietary - All Rights Reserved` (for `none`). Be aware of the licenses for files inside of a cookbook and be sure to follow any restrictions they describe. `cookbook_path` The Chef Infra Client sub-directory for storing cookbooks. This value can be a string or an array of file system locations, processed in the specified order. The last cookbook is considered to override local modifications. For example: ``` cookbook_path [ '/var/chef/cookbooks', '/var/chef/site-cookbooks' ] ``` `data_bag_encrypt_version` The minimum required version of data bag encryption. Possible values: `1` or `2`. When all of the machines in an organization are running Chef Client 11.6 (or higher), it is recommended that this value be set to `2`. For example: ``` data_bag_encrypt_version 2 ``` `fips` Allows OpenSSL to enforce FIPS-validated security during a Chef Infra Client run. Set to `true` to enable FIPS-validated security. The following operating systems are supported: * Red Hat Enterprise Linux * Oracle Enterprise Linux * CentOS * Windows `local_mode` Run Chef Infra Client in local mode. This allows all commands that work against the Chef Infra Server to also work against the local chef-repo. For example: ``` local_mode true ``` `node_name` The name of the node. This may be a username with permission to authenticate to the Chef Infra Server or it may be the name of the machine from which knife is run. For example: ``` node_name 'user_name' ``` or: ``` node_name 'machine_name' ``` `no_proxy` A comma-separated list of URLs that do not need a proxy. Default value: `nil`. For example: ``` no_proxy 'localhost, 10.0.1.35, *.example.com, *.dev.example.com' ``` `ssh_agent_signing` **New in 14.2** Use `ssh-agent` to authenticate. When using this option, specify the location of the public key in `client_key`. Default value: `false`. Ensure the public key is in PKCS#1 format. You can convert an OpenSSH public key using `ssh-keygen`. For example: ``` ssh-keygen -f key.pub -e -m pem > key.pem ``` `ssh_timeout` The amount of time (in seconds) to wait for an SSH connection time out. `ssl_verify_mode` Set the verify mode for HTTPS requests. * Use `:verify_none` to do no validation of SSL certificates. * Use `:verify_peer` to do validation of all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS **remote_file** resource URLs used in a Chef Infra Client run. This is the recommended setting. Depending on how OpenSSL is configured, the `ssl_ca_path` may need to be specified. Default value: `:verify_peer`. `tmux_split` Split the Tmux window. Default value: `false`. `validation_client_name` The name of the chef-validator key that is used by Chef Infra Client to access the Chef Infra Server during the initial Chef Infra Client run when not using validatorless bootstrapping. For example: ``` validation_client_name 'chef-validator' ``` `validation_key` The location of the file that contains the key used when a Chef Infra Client is registered with a Chef Infra Server. A validation key is signed using the `validation_client_name` for authentication. Default value: `/etc/chef/validation.pem`. For example: ``` validation_key '/etc/chef/validation.pem' ``` `verify_api_cert` Verify the SSL certificate on the Chef Infra Server. When `true`, Chef Infra Client always verifies the SSL certificate. When `false`. Chef Infra Client uses the value of `ssl_verify_mode` to determine if the SSL certificate requires verification. Default value: `false`. `versioned_cookbooks` Append cookbook versions to cookbooks. Set to `false` to hide cookbook versions: `cookbooks/apache`. Set to `true` to show cookbook versions: `cookbooks/apache-1.0.0` and/or `cookbooks/apache-1.0.1`. When this setting is `true`, `knife download` downloads ALL cookbook versions, which can be useful if a full-fidelity backup of data on the Chef Infra Server is required. For example: ``` versioned_cookbooks true ``` `config_log_level` Sets the default value of `log_level` in the client.rb file of the node being bootstrapped. Possible values are `:debug`, `:info`, `:warn`, `:error` and `:fatal`. For example: ``` config_log_level :debug ``` `config_log_location` Sets the default value of `log_location` in the client.rb file of the node being bootstrapped. Possible values are `/path/to/log_location`, `STDOUT`, `STDERR`, `:win_evt` and `:syslog`. For example: ``` config_log_location "/path/to/log_location" # Please make sure that the path exists ``` ### Proxy Settings In certain situations the proxy used by the Chef Infra Server requires authentication. In this situation, three settings must be added to the configuration file. Which settings to add depends on the protocol used to access the Chef Infra Server: HTTP or HTTPS. If the Chef Infra Server is configured to use HTTP, add the following settings: `http_proxy` The proxy server for HTTP connections. Default value: `nil`. For example: ``` http_proxy 'http://proxy.example.com:3128' ``` `http_proxy_user` The user name for the proxy server when the proxy server is using an HTTP connection. Default value: `nil`. `http_proxy_pass` The password for the proxy server when the proxy server is using an HTTP connection. Default value: `nil`. #### HTTPS Proxy Settings (such as the hosted Chef Infra Server) `https_proxy` The proxy server for HTTPS connections. (The hosted Chef Infra Server uses an HTTPS connection.) Default value: `nil`. `https_proxy_user` The user name for the proxy server when the proxy server is using an HTTPS connection. Default value: `nil`. `https_proxy_pass` The password for the proxy server when the proxy server is using an HTTPS connection. Default value: `nil`. #### Settings for No-proxy URLs `no_proxy` A comma-separated list of URLs that do not need a proxy. Default value: `nil`. .d Directories -------------- Chef Infra Client supports reading multiple configuration files by putting them inside a `.d` configuration directory. For example: `/etc/chef/client.d`. All files that end in `.rb` in the `.d` directory are loaded; other non-`.rb` files are ignored. `.d` directories may exist in any location where the `client.rb`, `config.rb`, or `solo.rb` files are present, such as: * `/etc/chef/client.d` * `/etc/chef/config.d` * `~/chef/solo.d` (There is no support for a `knife.d` directory; use `config.d` instead.) For example, when using knife, the following configuration files would be loaded: * `~/.chef/config.rb` * `~/.chef/config.d/company_settings.rb` * `~/.chef/config.d/ec2_configuration.rb` * `~/.chef/config.d/old_settings.rb.bak` The `old_settings.rb.bak` file is ignored because it’s not a configuration file. The `config.rb`, `company_settings.rb`, and `ec2_configuration` files are merged together as if they are a single configuration file. Note If multiple configuration files exists in a `.d` directory, ensure that the same setting has the same value in all files. Optional Settings ----------------- In addition to the default settings in a `config.rb` file, there are other subcommand-specific settings that can be added: 1. A value passed via the command-line 2. A value contained in the `config.rb` file 3. The default value A value passed via the command line overrides a value in the `config.rb` file; a value in a `config.rb` file overrides a default value. Before adding any settings to the `config.rb` file: * Verify the settings by reviewing the documentation for the knife subcommands and/or knife plugins * Verify the use case(s) your organization has for adding them Also note that: * Custom plugins can be configured to use the same settings as the core knife subcommands * Many of these settings are used by more than one subcommand and/or plugin * Some of the settings are included only because knife checks for a value in the `config.rb` file To add settings to the `config.rb` file, use the following syntax: ``` knife[:setting_name] = value ``` where `value` may require quotation marks (' ‘) if that value is a string. For example: ``` knife[:ssh_port] = 22 knife[:bootstrap_template] = 'ubuntu14.04-gems' knife[:bootstrap_version] = '' knife[:bootstrap_proxy] = '' ``` ### Frequently Used Some of the optional `config.rb` settings are used often, such as the template file used in a bootstrap operation. The frequency of use of any option varies from organization to organization, so even though the following settings are often added to a `config.rb` file, they may not be the right settings to add for every organization: `knife[:bootstrap_proxy]` The proxy server for the node that is the target of a bootstrap operation. `knife[:bootstrap_template]` The path to a template file to be used during a bootstrap operation. `knife[:bootstrap_version]` The version of Chef Infra Client to install. `knife[:editor]` The $EDITOR that is used for all interactive commands. `knife[:ssh_gateway]` The SSH tunnel or gateway that is used to run a bootstrap action on a machine that is not accessible from the workstation. Adding this setting can be helpful when a user cannot SSH directly into a host. `knife[:ssh_port]` The SSH port. ### Additional SSH Settings Other SSH-related settings that are sometimes helpful when added to the `config.rb` file: `knife[:forward_agent]` Enable SSH agent forwarding. `knife[:ssh_attribute]` The attribute used when opening an SSH connection. `knife[:ssh_password]` The SSH password. This can be used to pass the password directly on the command line. If this option is not specified (and a password is required) knife prompts for the password. `knife[:ssh_user]` The SSH user name. ### Data Bag Settings Some organizations choose to have all data bags use the same secret and secret file, rather than have a unique secret and secret file for each data bag. To use the same secret and secret file for all data bags, add the following to `config.rb`: `knife[:secret]` The encryption key that is used for values contained within a data bag item. `knife[:secret_file]` The path to the file that contains the encryption key. ### Ohai Settings (Not Recommended) Some settings are better left to Ohai, which gets the value at the start of a Chef Infra Client run: `knife[:server_name]` Same as `node_name`. Recommended configuration is to allow Ohai to collect this value during each Chef Infra Client run. `node_name` Same as `knife[:server_name]`. Recommended configuration is to allow Ohai to collect this value during each Chef Infra Client run. Warning Review the full list of [optional settings](config_rb_optional_settings/index) that can be added to the `config.rb` file. Many of these optional settings should not be added to the `config.rb` file. The reasons for not adding them can vary. For example, using `--yes` as a default in the `config.rb` file causes knife to always assume that “Y” is the response to any prompt, which may lead to undesirable outcomes. Other settings, such as `--hide-healthy`(used only with the `knife status` subcommand) or `--bare-directories` (used only with the `knife list` subcommand) probably aren’t used often enough (and in the same exact way) to justify adding them to the `config.rb` file. In general, if the optional settings are not listed on the main config.rb[topic](config_rb/index), then add settings only after careful consideration. Do not use optional settings in a production environment until after the setting’s performance has been validated in a safe testing environment. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/config_rbTest Kitchen ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/kitchen.md) Use [Test Kitchen](https://kitchen.ci/) to automatically test cookbooks across any combination of platforms and test suites: * Test suites are defined in a kitchen.yml file. See the [configuration](../workstation/config_yml_kitchen/index) documentation for options and syntax information. * Supports cookbook testing across many cloud providers and virtualization technologies. * Uses a comprehensive set of operating system base images from Chef’s [Bento](https://github.com/chef/bento) project. The key concepts in Test Kitchen are: * A platform is the operating system or target environment on which a cookbook is to be tested * A suite is the Chef Infra Client configuration, a Policyfile or run-list, and (optionally) node attributes * An instance is the combination of a specific platform and a specific suite, with each instance being assigned an auto-generated name * A driver is the lifecycle that implements the actions associated with a specific instance—create the instance, do what is needed to converge on that instance (such as installing Chef Infra Client, uploading cookbooks, starting a Chef Infra Client run, and so on), setup anything else needed for testing, verify one (or more) suites post-converge, and then destroy that instance * A provisioner is the component on which the Chef Infra Client code will be run, either using chef-zero or chef-solo via the `chef_zero` and `chef_solo` provisioners, respectively Bento ----- [Bento](https://github.com/chef/bento) is a Chef Software project that produces base testing VirtualBox, Parallels, and VMware boxes for multiple operating systems for use with Test Kitchen. By default, Test Kitchen uses the base images provided by Bento although custom images may also be built using HashiCorp Packer. Drivers ------- Test Kitchen uses a driver plugin architecture to enable Test Kitchen to test instances on cloud providers such as Amazon EC2, Google Compute Engine, and Microsoft Azure. You can also test on multiple local hypervisors, such as VMware, Hyper-V, or VirtualBox. Note Chef Workstation includes many common Test Kitchen drivers. Most drivers have driver-specific configuration settings that must be added to the kitchen.yml file before Test Kitchen will be able to use that platform during cookbook testing. For information about these driver-specific settings, please refer to the driver-specific documentation. Some popular drivers: | Driver Plugin | Description | | --- | --- | | [kitchen-azurerm](https://github.com/test-kitchen/kitchen-azurerm) | A driver for Microsoft Azure. | | [kitchen-cloudstack](https://github.com/test-kitchen/kitchen-cloudstack) | A driver for CloudStack. | | [kitchen-digitalocean](https://github.com/test-kitchen/kitchen-digitalocean) | A driver for DigitalOcean. This driver ships in Chef Workstation. | | [kitchen-dokken](https://github.com/test-kitchen/kitchen-dokken) | A driver for Docker. This driver ships in Chef Workstation. | | [kitchen-dsc](https://github.com/test-kitchen/kitchen-dsc) | A driver for Windows PowerShell Desired State Configuration (DSC). | | [kitchen-ec2](https://github.com/test-kitchen/kitchen-ec2) | A driver for Amazon EC2. This driver ships in Chef Workstation. | | [kitchen-google](https://github.com/test-kitchen/kitchen-google) | A driver for Google Compute Engine. This driver ships in Chef Workstation | | [kitchen-hyperv](https://github.com/test-kitchen/kitchen-hyperv) | A driver for Microsoft Hyper-V Server. This driver ships in Chef Workstation. | | [kitchen-openstack](https://github.com/test-kitchen/kitchen-openstack) | A driver for OpenStack. This driver ships in Chef Workstation. | | [kitchen-rackspace](https://github.com/test-kitchen/kitchen-rackspace) | A driver for Rackspace. | | [kitchen-vagrant](https://github.com/test-kitchen/kitchen-vagrant) | A driver for HashiCorp Vagrant. This driver ships in Chef Workstation. | Validation with InSpec ---------------------- Test Kitchen will create a VM or cloud instance, install Chef Infra Client to that system, and converge Chef Infra Client with your local cookbook. Once this is complete, you will want to perform automated validation against the infrastructure you have built to validate its configuration. Test Kitchen allows you to run InSpec tests against your converged cookbook for easy local validation of your infrastructure. kitchen (executable) -------------------- kitchen is the command-line tool for Test Kitchen, an integration testing tool maintained by Chef Software. Test Kitchen runs tests against any combination of platforms using any combination of test suites. Each test, however, is done against a specific instance, which is comprised of a single platform and a single set of testing criteria. This allows each test to be run in isolation, ensuring that different behaviors within the same codebase can be tested thoroughly before those changes are committed to production. Note Any Test Kitchen subcommand that does not specify an instance will be applied to all instances. Note For more information about the `kitchen` command line tool, see [kitchen](../workstation/ctl_kitchen/index). kitchen.yml ----------- Use a kitchen.yml file to define what is required to run Test Kitchen, including drivers, provisioners, platforms, and test suites. Note For more information about the kitchen.yml file, see [kitchen.yml](../workstation/config_yml_kitchen/index). ### Syntax The basic structure of a kitchen.yml file is as follows: ``` driver:name:driver_nameprovisioner:name:provisioner_nameverifier:name:verifier_nametransport:name:transport_nameplatforms:- name:platform-versiondriver:name:driver_name- name:platform-versionsuites:- name:suite_namerun_list:- recipe[cookbook_name::recipe_name]attributes:{foo:"bar"}excludes:- platform-version- name:suite_namedriver:name:driver_namerun_list:- recipe[cookbook_name::recipe_name]attributes:{foo:"bar"}includes:- platform-version ``` where: * `driver_name` is the name of a driver that will be used to create platform instances used during cookbook testing. This is the default driver used for all platforms and suites **unless** a platform or suite specifies a `driver` to override the default driver for that platform or suite; a driver specified for a suite will override a driver set for a platform * `provisioner_name` specifies how Chef Infra Client will be simulated during testing. `chef_zero` and `chef_solo` are the most common provisioners used for testing cookbooks * `verifier_name` specifies which application to use when running tests, such as `inspec` * `transport_name` specifies which transport to use when executing commands remotely on the test instance. `winrm` is the default transport on Windows. The `ssh` transport is the default on all other operating systems. * `platform-version` is the name of a platform on which Test Kitchen will perform cookbook testing, for example, `ubuntu-20.04` or `centos-7`; depending on the platform, additional driver details—for example, instance names and URLs used with cloud platforms like OpenStack or Amazon EC2—may be required * `platforms` may define Chef Infra Server attributes that are common to the collection of test suites * `suites` is a collection of test suites, with each `suite_name` grouping defining an aspect of a cookbook to be tested. Each `suite_name` must specify a run-list, for example: ``` run_list: - recipe[cookbook_name::default] - recipe[cookbook_name::recipe_name] ``` * Each `suite_name` grouping may specify `attributes` as a Hash: `{ foo: "bar" }` * A `suite_name` grouping may use `excludes` and `includes` to exclude/include one (or more) platforms. For example: ``` excludes: - platform-version - platform-version # for additional platforms ``` For example, a very simple kitchen.yml file: ``` driver:name:vagrantprovisioner:name:chef_zeroplatforms:- name:ubuntu-20.04- name:centos-8- name:debian-10suites:- name:defaultrun_list:- recipe[apache::httpd]excludes:- debian-10 ``` This file uses HashiCorp Vagrant as the driver, which requires no additional configuration because it’s the default driver used by Test Kitchen, chef-zero as the provisioner, and a single (default) test suite that runs on Ubuntu 20.04, and CentOS 7. ### Work with Proxies The environment variables `http_proxy`, `https_proxy`, and `ftp_proxy` are honored by Test Kitchen for proxies. The client.rb file is read to look for proxy configuration settings. If `http_proxy`, `https_proxy`, and `ftp_proxy` are specified in the client.rb file, Chef Infra Client will configure the `ENV` variable based on these (and related) settings. For example: ``` http_proxy 'http://proxy.example.org:8080' http_proxy_user 'myself' http_proxy_pass 'Password1' ``` will be set to: ``` ENV['http_proxy'] = 'http://myself:<EMAIL>:8080' ``` Test Kitchen also supports `http_proxy` and `https_proxy` in the `kitchen.yml` file. You can set them manually or have them read from your local environment variables: ``` driver:name:vagrantprovisioner:name:chef_zero# Set proxy settings manually, orhttp_proxy:'http://user:password@server:port'https_proxy:'http://user:password@server:port'# Read from local environment variableshttp_proxy:<%= ENV['http_proxy'] %>https_proxy:<%= ENV['https_proxy'] %> ``` This will not set the proxy environment variables for applications other than Chef. The Vagrant plugin, [vagrant-proxyconf](http://tmatilai.github.io/vagrant-proxyconf/), can be used to set the proxy environment variables for applications inside the VM. For more information &mldr; --------------------------- For more information about test-driven development and Test Kitchen: * [kitchen.ci](https://kitchen.ci/) * [Getting Started with Test Kitchen](https://kitchen.ci/docs/getting-started/introduction/) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/kitchen/Chef InSpec Language ==================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/dsl_inspec.md) Chef InSpec is a run-time framework and rule language used to specify compliance, security, and policy requirements. It includes a collection of resources that help you write auditing controls quickly and easily. The syntax used by both open source and [Chef compliance](../compliance/index) auditing is the same. The open source [Chef InSpec resource](resources/index) framework is compatible with [Chef compliance](../compliance/index). The Chef InSpec Language is a Ruby DSL for writing audit controls, which includes audit resources that you can invoke. The following sections describe the syntax and show some simple examples of using the Chef InSpec resources. Syntax ------ The following resource tests |ssh| server configuration. For example, a simple control may described as: ``` describe sshd_config do its('Port') { should cmp 22 } end ``` In various use cases like implementing IT compliance across different departments, it becomes handy to extend the control with metadata. Each control may define an additional `impact`, `title` or `desc`. An example looks like: ``` control 'sshd-8' do impact 0.6 title 'Server: Configure the service port' desc 'Always specify which port the SSH server should listen.' desc 'rationale', 'This ensures that there are no unexpected settings' # Requires Chef InSpec >=2.3.4 tag 'ssh','sshd','openssh-server' tag cce: 'CCE-27072-8' ref 'NSA-RH6-STIG - Section 3.5.2.1', url: 'https://www.nsa.gov/ia/_files/os/redhat/rhel5-guide-i731.pdf' describe sshd_config do its('Port') { should cmp 22 } end end ``` where * `'sshd-8'` is the name of the control * `impact`, `title`, and `desc` define metadata that fully describes the importance of the control, its purpose, with a succinct and complete description * `desc` when given only one argument it sets the default description. As of Chef InSpec 2.3.4, when given 2 arguments (see: `'rationale'`) it will use the first argument as a header when rendering in Automate * `impact` is a string, or numeric that measures the importance of the compliance results. Valid strings for impact are `none`, `low`, `medium`, `high`, and `critical`. The values are based off CVSS 3.0. A numeric value must be between `0.0` and `1.0`. The value ranges are: + `0.0 to <0.01` these are controls with no impact, they only provide information + `0.01 to <0.4` these are controls with low impact + `0.4 to <0.7` these are controls with medium impact + `0.7 to <0.9` these are controls with high impact + `0.9 to 1.0` these are critical controls * `tag` is optional meta-information with key or key-value pairs * `ref` is a reference to an external document * `describe` is a block that contains at least one test. A `control` block must contain at least one `describe` block, but may contain as many as required * `sshd_config` is a Chef InSpec resource. For the full list of Chef InSpec resources, see Chef InSpec resource documentation * `its('Port')` is the matcher; `{ should eq '22' }` is the test. A `describe` block must contain at least one matcher, but may contain as many as required Advanced concepts ----------------- ### Checking if at least one condition passes with `describe.one` With Chef InSpec, you can check if at least one of a collection of checks is true. For example, if you configure a setting in two different locations, then you may want to test if either configuration A or configuration B is set. Do this task with the `describe.one` block. `describe.one` defines a set of `describe` blocks where only one block needs to pass. ``` describe.one do describe ConfigurationA do its('setting_1') { should eq true } end describe ConfigurationB do its('setting_2') { should eq true } end end ``` #### `describe.one` usage notes * A `describe.one` block passes if one of its nested `describe` blocks has all assertions passing. A `describe.one` block needs an entire `describe` block to pass and not just a single assertion. * Chef InSpec will always evaluate all the tests contained within `describe.one`. It does not short-circuit upon evaluating a passing `describe` block. * Nesting a `describe.one` block inside another `describe.one` block is not supported. ### Sensitive resources In some scenarios, you may be writing checks that involve resources with sensitive content, such as a file resource. In case of failures, you may desire to suppress output. Do this task by adding the `:sensitive` flag to the resource definition: ``` describe file('/tmp/mysecretfile'), :sensitive do its('content') { should match /secret_info/ } end ``` Examples -------- The following examples show simple compliance tests using a single `control` block. ### Test System Event Log The following test shows how to audit machines running Windows 2012 R2 that password complexity is enabled: ``` control 'windows-account-102' do impact 'critical' title 'Windows Password Complexity is Enabled' desc 'Password must meet complexity requirement' describe security_policy do its('PasswordComplexity') { should cmp 1 } end end ``` ### Test if PostgreSQL passwords are empty The following test shows how to audit machines running PostgreSQL to ensure that passwords are not empty. ``` control 'postgres-7' do impact 1.0 title "Don't allow empty passwords" describe postgres_session('user', 'pass').query("SELECT * FROM pg_shadow WHERE passwd IS NULL;") do its('output') { should cmp '' } end end ``` ### Test if MySQL passwords are in ENV The following test shows how to audit machines running MySQL to ensure that passwords are not stored in `ENV`: ``` control 'mysql-3' do impact 1.0 title 'Do not store your MySQL password in your ENV' desc ' Storing credentials in your ENV may easily expose them to an attacker. Prevent this at all costs. ' describe command('env') do its('stdout') { should_not match /^MYSQL_PWD=/ } end end ``` ### Test if `/etc/ssh` is a Directory The following test shows how to audit machines to ensure that `/etc/ssh` is a directory: ``` control 'basic-1' do impact 1.0 title '/etc/ssh should be a directory' desc ' In order for OpenSSH to function correctly, its configuration path must be a folder. ' describe file('/etc/ssh') do it { should be_directory } end end ``` ### Test if Apache running The following test shows how to audit machines to ensure that Apache is enabled and running: ``` control 'apache-1' do impact 'medium' title 'Apache2 should be configured and running' describe service(apache.service) do it { should be_enabled } it { should be_running } end end ``` ### Test if insecure packages are installed The following test shows how to audit machines for insecure packages: ``` control 'cis-os-services-5.1.3' do impact 0.7 title '5.1.3 Ensure rsh client is not installed' describe package('rsh') do it { should_not be_installed } end describe package('rsh-redone-client') do it { should_not be_installed } end end ``` ### Test Windows Registry Keys The following test shows how to audit machines to ensure Safe DLL Search Mode is enabled: ``` control 'windows-base-101' do impact 1.0 title 'Safe DLL Search Mode is Enabled' desc ' @link: https://msdn.microsoft.com/en-us/library/ms682586(v=vs.85).aspx ' describe registry_key('HKLM\\System\\CurrentControlSet\\Control\\Session Manager') do it { should exist } it { should_not have_property_value('SafeDllSearchMode', :type_dword, '0') } end end ``` ### Use `only_if` to exclude a specific control This example shows how to allow skipping certain controls if conditions are not met by using `only_if`. In this example, the control will not be performed if the `redis-cli` command does not exist. A optional message can say why it was skipped. ``` control 'nutcracker-connect-redis-001' do impact 'critical' title 'Check if nutcracker can pass commands to redis' desc 'execute redis-cli set key command, to check connectivity of the service' only_if('redis is not installed.') do command('redis-cli').exist? end describe command('redis-cli SET test_inspec "HELLO"') do its('stdout') { should match /OK/ } end end ``` This example checks for if certain pip packages are installed, but only if ‘/root/.aws’ exists: ``` control 'pip-packages-installed' do title 'Check if essential pips are installed' only_if('aws-cli config not created.') do directory('/root/.aws').exist? end %w(aws-mfa PyYAML awscli).each do |aws_pip_deps| describe pip(aws_pip_deps) do it { should be_installed } end end end ``` Mixing this with other conditionals, such as checking existence of the files, can help to test different test paths using Chef InSpec. With this way, you can skip certain controls, which would 100% fail due to the way servers are prepared, but you know that the same control suites are reused later in different circumstances by different teams. Some notes about `only_if`: * `only_if` applies to the entire `control`. If the results of the `only_if` block evaluate to false, any Chef InSpec resources mentioned as part of a `describe` block will not be run. Additionally, the contents of the describe blocks will not be run. However, bare Ruby expressions and bare Chef InSpec resources (not assocated with a describe block) preceding the only_if statement will run To illustrate: ``` control "whatruns" do command("do_something") # This will ALWAYS run describe command("do_another_thing") do # This will not run command("do_yet_another_thing") # This will not run end only_if { false } command("do_something_else") # This will not run end ``` * Only one `only_if` is permitted per `control` block. If multiple `only_if` blocks are present, only the last `only_if` block will be honored * If used outside a control block, `only_if` skips all controls in the current file * To implement complex logic, use Ruby ‘or’ (`||`) and ‘and’ (`&&`) inside your `only_if` block: ``` only_if('ready for launch') do rocket_is_ready && weather_is_clear end ``` ### Additional metadata for controls The following example illustrates various ways to add tags and references to `control` ``` control 'ssh-1' do impact 1.0 title 'Allow only SSH Protocol 2' desc ' Only SSH protocol version 2 connections should be permitted. The default setting in /etc/ssh/sshd_config is correct, and can be verified by ensuring that the following line appears: Protocol 2 ' tag 'production','development' tag 'ssh','sshd','openssh-server' tag cce: 'CCE-27072-8' tag disa: 'RHEL-06-000227' tag remediation: 'stig_rhel6/recipes/sshd-config.rb' tag remediation: 'https://supermarket.chef.io/cookbooks/ssh-hardening' ref 'NSA-RH6-STIG - Section 3.5.2.1', url: 'https://www.nsa.gov/ia/_files/os/redhat/rhel5-guide-i731.pdf' ref 'http://people.redhat.com/swells/scap-security-guide/RHEL/6/output/ssg-centos6-guide-C2S.html' describe ssh_config do its('Protocol') { should cmp 2 } end end ``` Using Ruby in InSpec -------------------- The Chef InSpec Language is a Ruby based language. This allows you to be flexible with Ruby code in controls: ``` json_obj = json('/file.json') json_obj['keys'].each do |value| .. end ``` Ruby allows a lot of freedoms, but should be limited in controls so that they remain portable and easy to understand. Please see our [profile style guide](style/index). Core and custom resources are written as regular Ruby classes which inherit from `Inspec.resource`. ### Interactive Debugging with Pry Here’s a sample Chef InSpec control that uses Ruby variables to instantiate a Chef InSpec resource once and use the content in multiple tests. ``` control 'check-perl' do impact 0.3 title 'Check perl compiled options and permissions' perl_out = command('perl -V') #require 'pry'; binding.pry; describe perl_out do its('exit_status') { should eq 0 } its('stdout') { should match /USE_64_BIT_ALL/ } its('stdout') { should match /useposix=true/ } its('stdout') { should match /-fstack-protector/ } end # extract an array of include directories perl_inc = perl_out.stdout.partition('@INC:').last.strip.split("\n") # ensure include directories are only writable by 'owner' perl_inc.each do |path| describe directory(path.strip) do it { should_not be_writable.by 'group' } it { should_not be_writable.by 'other' } end end end ``` An **advanced** but very useful Ruby tip. In the previous example, I commented out the `require 'pry'; binding.pry;` line. If you remove the `#` prefix and run the control, the execution will stop at that line and give you a `pry` shell. Use that to troubleshoot, print variables, see methods available, etc. For the above example: ``` [1] pry> perl_out.exit_status => 0 [2] pry> perl_out.stderr => "" [3] pry> ls perl_out Inspec::Plugins::Resource#methods: inspect Inspec::Resources::Cmd#methods: command exist? exit_status result stderr stdout to_s Inspec::Resource::Registry::Command#methods: inspec instance variables: @__backend_runner__ @__resource_name__ @command @result [4] pry> perl_out.stdout.partition('@INC:').last.strip.split("\n") => ["/Library/Perl/5.18/darwin-thread-multi-2level", " /Library/Perl/5.18", ...REDACTED... [5] pry> exit # or abort ``` You can use `pry` inside both the controls DSL and resources. Similarly, for dev and test, you can use `inspec shell` which is based on `pry`, for example: ``` $ inspec shell Welcome to the interactive InSpec Shell To find out how to use it, type: help inspec> command('ls ~/projects/github/inspec/docs').stdout => "README.md\nconfig.md\ndev\ndsl_inspec.md\ndsl_resource.md\nglossary.md\nhabitat.md\ninputs.md\ninspec_and_friends.md\nmatchers.md\nmigration.md\nplatforms.md\nplugin_kitchen_inspec.md\nplugins.md\nprofiles.md\nreporters.md\nresources\nshared\nshell.md\nstyle.md\nwaivers.md\n" inspec> command('ls ~/projects/github/inspec/docs').stdout.split("\n").first => "README.md" inspec> help command Name: command Description: Use the command InSpec audit resource to test an arbitrary command that is run on the system. Example: describe command('ls -al /') do it { should exist } its('stdout') { should match /bin/ } its('stderr') { should eq '' } its('exit_status') { should eq 0 } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/dsl_inspecDeprecation: Internal API Changes (CHEF-0) ========================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_internal_api.md) During the lifecycle of a release, we realise that some APIs are no longer fit for purpose, or are simply unused. We try to mark those APIs for removal in the next major release. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_internal_api/Deprecation: Old Exit Codes (CHEF-2) ==================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_exit_code.md) In older versions of Chef Client, it was not possible to discern why a chef run exited simply by examining the error code. This makes it very tricky for tools such as Test Kitchen to reason about the status of a Chef Client run. Starting in Chef Client 12.11, there are now well defined exit codes that the Chef Client can use to communicate the status of the run. This deprecation was added in Chef Client 12.11. In Chef Client 13, only the extended set of exit codes will be supported. For further information on the list of defined error codes, please see [RFC 62, which defines them](https://github.com/chef/chef-rfc/blob/main/rfc062-exit-status.md). Remediation ----------- If you have built automation that is dependent on the old behavior of Chef Client, we strongly recommend updating it to support the extended set of exit codes. However, it’s still possible to enable the old behavior. Add the setting ``` exit_status :disabled ``` to the Chef config file. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_exit_code/Deprecation: Chef Gem Compile Time (CHEF-3) =========================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_chef_gem_compile_time.md) Originally, the [chef gem](../resources/chef_gem/index) resource always ran during the compile phase (see this section on [Chef Infra Client runs](../chef_client_overview/index#the-chef-client-run) for further details). It is now possible to control which phase the resource is run in. Calling `chef_gem` without specifying the phase is now deprecated. This deprecation warning was added in Chef Client 12.1.0, and using `chef_gem` without specifying a phase will become an error in Chef Client 13. Remediation ----------- There are two possible remediations. The first is to set the `compile_time` property on the resource. To maintain the same behavior as before, the property should be set to `true`: ``` chef_gem 'etcd' do compile_time true end ``` The second, and preferred, is to add a [gem dependency](../config_rb_metadata/index) in your cookbook metadata. ``` gem 'etcd' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_chef_gem_compile_time/Deprecation: Some Attribute Methods (CHEF-4) ============================================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_attributes.md) We are continuously improving and streamlining the way attributes work in Chef, to make it easier for users to reason about and safely configure their servers. This page documents many deprecations over the course of many Chef releases. Method Access ------------- Setting and accessing node attributes has been standardized on “bracket” syntax. The older “method” syntax is deprecated and will be removed in Chef Client 13. Removal: Chef Client 13 ### Example Both lines in the example will cause separate deprecation warnings. ``` node.chef.server = 'https://my.chef.server' chef_server = node.chef.server ``` ### Remediation Convert method syntax to bracket syntax by using brackets to denote attribute names. The code below is identical in function to the example above: ``` node['chef']['server'] = 'https://my.chef.server' chef_server = node['chef']['server'] ``` Set and Set_Unless ------------------- Setting node attributes with `set` or `set_unless` has been deprecated in favor of explicitly setting the precedence level. These methods will be removed in Chef Client 14. Removal: Chef Client 14 ### Example ``` node.set['chef']['server'] = 'https://my.chef.server' node.set_unless['chef']['server'] = 'https://my.chef.server' ``` ### Remediation Choose the appropriate [precedence level](../attributes/index#attribute-precedence), then replace `set` with that precedence level. ``` node.default['chef']['server'] = 'https://my.chef.server' node.default_unless['chef']['server'] = 'https://my.chef.server' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_attributes/Deprecation: JSON Auto Inflate (CHEF-1) ======================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_json_auto_inflate.md) Internally, the `Chef::REST` class attempts to guess which Chef class a JSON document relates too, and then automatically turns the JSON in to that class. This deprecation warning was added in Chef Client 12.7.2, and JSON auto inflation will be removed permanently in Chef Client 13. Example ------- When loading an environment from the Chef Infra Server, you might previously have written: ``` name = 'my_environment' chef_server_rest.get("environments/#{name}") ``` and received a `Chef::Environment` object back. Remediation ----------- You now need to explicitly create a new object of the desired type. ``` name = 'my_environment' Chef::Environment.from_hash chef_server_rest.get("environments/#{name}") ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_json_auto_inflate/Deprecation: Easy Install Resource (CHEF-6) =========================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_easy_install.md) The Python community recommends that users prefer `pip` rather than `easy_install` to install python packages. The `easy_install` resource was deprecated in Chef Client 12.10, and will be removed in Chef Client 13. The [Cookstyle](../workstation/cookstyle/index) cop [ChefDeprecations/EasyInstallResource](https://github.com/chef/cookstyle/blob/main/docs/cops_chefdeprecations.md#chefdeprecationseasyinstallresource) has been introduced to detect this deprecation. Remediation ----------- There is no built-in replacement for `easy_install` in Chef Infra Client at this time. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_easy_install/Deprecation: Custom Resource Cleanups (CHEF-5) ============================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_custom_resource_cleanups.md) We are continuously improving and streamlining the way custom resources work in Chef, to make it easier for cookbook authors and Chef developers to build resources. This page documents many deprecations over the course of many Chef releases. Nil Properties -------------- In current versions of Chef, `nil` was often used to mean that a property had no good default, and needed to be set by the user. However, it is often to useful to set a property to `nil`, meaning that it’s not set and should be ignored. In Chef Client 13, it is an error to set `default: nil` on a property if that property doesn’t allow `nil` as a valid value. ### Remediation If it is valid for the property to be set to nil, then update the property to include that. ``` property :my_nillable_property, [ String, nil ], default: nil ``` Otherwise, remove the `default: nil` statement from the property. Invalid Defaults ---------------- Current versions of Chef emit a warning when a property’s default value is not valid. This is often because the type of the default value doesn’t match the specification of the property. For example: ``` property :my_property, [ String ], default: [] ``` sets the type of the property to be a String, but then sets the default to be an Array. In Chef Client 13, this will be an error. ### Remediation Ensure that the default value of a property is correct. Property Getters ---------------- When writing a resource in Chef Client 12, calling `some_property nil` behaves as a getter, returning the value of `some_property`. In Chef Client 13, this will change to set `some_property` to `nil`. ### Remediation Simply write `some_property` when retrieving the value of `some_property`. Specifying both “default” and “name_property” on a resource ------------------------------------------------------------ Current versions of Chef emit a warning if the property declaration has both `default` and `name_property` set. In Chef Client 13, that will become an error. For example: ``` property :my_property, [ String ], default: [], name_property: true ``` ### Remediation A property can either have a default, or it can be a “name” property (meaning that it will take the value of the resource’s name if not otherwise specified), but not both. Overriding provides? -------------------- Some providers override the `provides?` method, used to check whether they are a valid provider on the current platform. In Chef Client 13, this will cause an error if the provider does not also register themselves with the `provides` call. ### Example ``` def provides? true end ``` ### Remediation ``` provides :my_provider def provides? true end ``` Don’t use the updated method ---------------------------- The `updated=(true_or_false)` method is deprecated and will be removed from Chef Client 13. This method never performed its intended job, as notifications from the resource would not fire, and in general its use has always been buggy. The Chef Infra Client notification code checks `updated_by_last_action?` instead, so setting that is recommended as a substitute. See the [updated_by_last_action](../custom_resources_notes/index#updated-by-last-action) documentation for more information. Note Setting `updated_by_last_action` is almost always unnecessary, and correct use of `use_inline_resources` (which is the default in Chef Client 13 and above) makes the `updated_by_last_action` setting redundant. Simply deleting this code is very likely to be the correct course of action in nearly all cases. ### Example ``` action :foo do updated = true end ``` ### Remediation ``` action :foo do new_resource.updated_by_last_action true end ``` Don’t use the dsl_name method ------------------------------ The `dsl_name` method is deprecated and will be removed from Chef Client. It has been replaced by `resource_name`. ### Example ``` my_resource = MyResource.dsl_name ``` ### Remediation ``` my_resource = MyResource.resource_name ``` Don’t use the provider_base method ----------------------------------- The `Resource.provider_base` allows the developer to specify an alternative module to load providers from, rather than `Chef::Provider`. It is deprecated and will be removed in Chef Client 13. Instead, the provider should call `provides` to register itself, or the resource should call `provider` to specify the provider to use. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_custom_resource_cleanups/Deprecation: Verify File Expansion (CHEF-7) =========================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_verify_file.md) The `verify` metaproperty allows the user to specify a `{path}` variable that is expanded to the path of the file to be verified. Previously, it was possible to use `{file}` as the variable, but that is now deprecated. The `{file}` expansion was deprecated in Chef Client 12.5, and will be removed in Chef Client 13. Example ------- ``` file '/etc/nginx.conf' do verify 'nginx -t -c %{file}' end ``` Remediation ----------- Replace `%{file}` with `%{path}`: ``` file '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_verify_file/Deprecation: Supports metaproperty (CHEF-8) =========================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_supports_property.md) The `user` resource previously allowed a cookbook author to set policy for the resource in two ways. The `supports` metaproperty, which is now deprecated, enabled the `manage_home` and `non_unique` properties to be set. The `supports` metaproperty was deprecated in Chef Client 12.14 and will be removed in Chef Client 13. Example ------- ``` user 'betty' do supports({ manage_home: true, non_unique: true, }) end ``` Remediation ----------- Make the `manage_home` and `non_unique` settings properties rather than parts of the `supports` hash. ``` user 'betty' do manage_home true non_unique true end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_supports_property/ohai (executable) ================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/ctl_ohai.md) ohai is the command-line interface for Ohai, a tool that is used to detect attributes on a node, and then provide these attributes to Chef Infra Client at the start of every Chef Infra Client run. Options ------- This command has the following syntax: ``` ohai OPTION ``` This tool has the following options: `ATTRIBUTE_NAME ATTRIBUTE NAME ...` Use to have Ohai show only output for named attributes. `-c CONFIG`, `--config CONFIG` The path to a configuration file to use For example: `/etc/ohai/config.rb`. `-d DIRECTORY`, `--directory DIRECTORY` The directory in which additional Ohai plugins are located. For example: `/my/extra/plugins`. `-h`, `--help` Show help for the command. `-l LEVEL`, `--log_level LEVEL` The level of logging to be stored in a log file. `-L LOGLOCATION`, `--logfile LOGLOCATION` The location of the log file. `-v`, `--version` The version of Ohai. Examples -------- The following examples show how to use the Ohai command-line tool: ### Run a plugin independently of a Chef Infra Client run An Ohai plugin can be run independently of a Chef Infra Client run. First, ensure that the plugin is located in the `/plugins` directory and then use the `-f` option when running Ohai from the command line. For example, a plugin named `sl_installed` may look like the following: ``` Ohai.plugin(:Sl) do provides "sl" collect_data(:default) do sl Mash.new if ::File.exist?("/usr/games/sl") sl[:installed] = true else sl[:installed] = false end # sl[:installed] = ::File.exist?("/usr/games/sl") end end ``` To run that plugin from the command line, use the following command: ``` ohai --directory /path/to/directory sl ``` The command will return something similar to: ``` { "sl": { "installed": true } } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ctl_ohaiDeprecation: DNF Package allow_downgrade Property (CHEF-10) ============================================================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_dnf_package_allow_downgrade.md) The underlying `dnf` command in Red Hat based operating systems does not require `--allow-downgrade` like the previous `yum` command did. This property does not affect the `dnf_resource` resource execution and should be removed. Remediation ----------- Remove the `allow_downgrade` property on the `dnf_package` resource. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_dnf_package_allow_downgrade/ohai Resource ============= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [ohai.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/ohai.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](index) --- Use the **ohai** resource to reload the Ohai configuration on a node. This allows recipes that change system attributes (like a recipe that adds a user) to refer to those attributes later on during the Chef Infra Client run. Syntax ------ --- The full syntax for all of the properties that are available to the **ohai** resource is: ``` ohai 'name' do plugin String action Symbol # defaults to :reload if not specified end ``` where: * `ohai` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `plugin` is the property available to this resource. Actions ------- --- The **ohai** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reload` Reloads the Ohai data. (default) Properties ---------- --- The **ohai** resource has the following properties: `plugin` **Ruby Type:** String Specific Ohai attribute data to reload. This property behaves similar to specifying attributes when running Ohai on the command line and takes the attribute that you wish to reload instead of the actual plugin name. For instance, you can pass `ipaddress` to reload `node['ipaddress']` even though that data comes from the `Network` plugin. If this property is not specified, Chef Infra Client will reload all plugins. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **ohai** resource in recipes: Reload All Ohai Plugins ``` ohai 'reload' do action :reload end ``` Reload A Single Ohai Plugin ``` ohai 'reload' do plugin 'ipaddress' action :reload end ``` Reload Ohai after a new user is created ``` ohai 'reload_passwd' do action :nothing plugin 'etc' end user 'daemon_user' do home '/dev/null' shell '/sbin/nologin' system true notifies :reload, 'ohai[reload_passwd]', :immediately end ruby_block 'just an example' do block do # These variables will now have the new values puts node['etc']['passwd']['daemon_user']['uid'] puts node['etc']['passwd']['daemon_user']['gid'] end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/ohaiDeprecation: Chef REST (CHEF-9) =============================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_chef_rest.md) The `Chef::REST` class will be removed. `Chef::REST` was deprecated in Chef Client 12.7.2, and will be removed in Chef Client 13. The [Cookstyle](../workstation/cookstyle) cop [ChefDeprecations/UsesChefRESTHelpers](https://github.com/chef/cookstyle/blob/main/docs/cops_chefdeprecations.md#chefdeprecationsuseschefresthelpers) has been introduced to detect this deprecation. Remediation ----------- If writing code designed to be run internally to Chef, for example in a cookbook or a knife plugin, transition to using `Chef::ServerAPI`. In most cases this is as simple as creating a `Chef::ServerAPI` instance rather than a `Chef::REST` one. If writing code to interact with a Chef Infra Server from other code, move to the [chef-api gem](https://rubygems.org/gems/chef-api). © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_chef_rest/Deprecation: Resource Property Name Collision (CHEF-11) ======================================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_property_name_collision.md) A resource property, defined with the `property` method, conflicts with an already-existing property or method. This could indicate an error that could lead to unintended behavior. All Ruby objects have a number of methods that are expected to always be available. When a resource property is created, Ruby methods for setting and getting the property value are created for you. If a resource creates a property which is named the same as an existing method, the original method will be overwritten. For example, every Ruby object has a `hash` method which is expected to return a number. If a resource creates a property named `hash` and stores a string instead, it could cause errors in your Chef run. A deprecation warning is logged when this occurs. In Chef Client 13, this will raise an exception and your Chef run will fail. Remediation ----------- Modify the resource and choose a different name for the property that does not conflict with an already-existing method name. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_property_name_collision/Deprecation: Chef::Platform methods (CHEF-13) ============================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_chef_platform_methods.md) Several methods under `Chef::Platform` that were previously public APIs to control resolution of provider classes were replaced by the dynamic `Chef::ProviderResolver` work and the `provides` keyword. This deprecation warning was added in Chef Client 12.18.x, and using these APIs will become a hard error in Chef Client 13. Remediation ----------- Code which used to use `Chef::Platform.provider_for_resource` or `Chef::Platform.find_provider` to create providers for a resource: ``` resource = Chef::Resource::File.new("/tmp/foo.xyz", run_context) provider = Chef::Platform.provider_for_resource(resource, :create) resource = Chef::Resource::File.new("/tmp/foo.xyz", run_context) provider = Chef::Platform.find_provider("ubuntu", "16.04", resource) resource = Chef::Resource::File.new("/tmp/foo.xyz", run_context) provider = Chef::Platform.find_provider_for_node(node, resource) ``` Should instead use the `Chef::Resource#provider_for_action` API on the instance of the resource: ``` resource = Chef::Resource::File.new("/tmp/foo.xyz", run_context) provider = resource.provider_for_action(:create) ``` As the internal resources and providers in core chef have been ported over to use the `Chef::ProviderResolver` dynamic resolution the use of the old Chef::Platform class methods have actually been broken. Tools like `chefspec` and `chef-minitest-handler` were ported over to the new APIs in Chef Client 12.0. The `Chef::Resource#provider_for_action` API dates back to before Chef Client 11.0.0 and is fully backwards compatible, any remaining code using the old APIs should be exceedingly buggy at this point. Also, code which used to use `Chef::Platform.set` to register providers for a platform/platform_version should use the `provides` keyword on the provider instead: ``` Chef::Platform.set platform: :fedora, version: '>= 19', resource: :mysql_service, provider: Chef::Provider::MysqlServiceSystemd ``` Should be replaced by: ``` class Chef::Provider::MysqlServiceSystemd provides :mysql_service, platform: "fedora", platform_version: ">= 19" ``` This can also be directly sent to the provider class in library code, although this form is less encouraged (which does not mean the same thing as discouraged – but you gain better code organization with the prior code): ``` Chef::Provider::MysqlSserviceSystemd.provides :mysql_service, platform: "fedora", platform_version: ">= 19" ``` The `provides` API on providers is only supported in Chef Client 12.0 or later. This change will create a hard backwards compatibility break between Chef Client 13 and Chef Client 11 without the cookbook doing the work to check the Chef::VERSION and switch between these APIs. This API is supported back to Chef Client 12.0, although some more advanced forms of the `provides` syntax were only introduced in Chef Client 12.5.1. Also you may have found this web page due to deprecation of library-based resources and providers that do not declare provides in which case your Chef Infra Client run is likely full of a compilation of warnings and deprecations: ``` * foo[it] action doit[2016-12-07T14:28:59-08:00] WARN: Class Chef::Provider::Foo does not declare 'provides :foo'. [2016-12-07T14:28:59-08:00] WARN: This will no longer work in Chef Client 13: you must use 'provides' to use the resource's DSL. (up to date) Running handlers: Running handlers complete Deprecated features used! Class.find_provider_for_node is deprecated at 1 location: - /Users/lamont/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/forwardable.rb:189:in 'execute_each_resource' See /deprecations_chef_platform_methods.html for further details. Class.find_provider is deprecated at 1 location: - /Users/lamont/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/forwardable.rb:189:in 'execute_each_resource' See /deprecations_chef_platform_methods.html for further details. Class.find is deprecated at 1 location: - /Users/lamont/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/forwardable.rb:189:in 'execute_each_resource' See /deprecations_chef_platform_methods.html for further details. ``` In this case, the initial warning that `Class Chef::Provider::Foo does not declare 'provides :foo'` is accurate and gives the remediation. Code that looks like this: ``` class Chef::Provider::Foo < Chef::Provider::LWRPBase use_inline_resources action :doit do [ ... stuff ... ] end end ``` Must be changed to explicitly declare the resource it provides: ``` class Chef::Provider::Foo < Chef::Provider::LWRPBase provides :foo use_inline_resources action :doit do [ ... stuff ... ] end end ``` The use of custom resources over library class providers that inherit from LWRPBase is also encouraged. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_chef_platform_methods/Deprecation: Launchd hash Property (CHEF-12) ============================================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_launchd_hash_property.md) The launchd resource has a property called `hash` which conflicts with the already-existing Ruby `hash` method that exists on every object. The [CHEF-11](../deprecations_property_name_collision/index) deprecation warns whenever a resource property is named the same as an existing Ruby method. Chef’s core `launchd` resource is guilty of this behavior. The `hash` property accepts a Ruby Hash containing the data to be output to the launchd property list. However, `hash` is an already-existing Ruby method. A deprecation warning is logged when the `hash` property is used. In Chef Client 13, this will raise an exception and your Chef run will fail. The [Cookstyle](../workstation/cookstyle/index) cop [ChefDeprecations/LaunchdDeprecatedHashProperty](https://github.com/chef/cookstyle/blob/main/docs/cops_chefdeprecations.md#chefdeprecationslaunchddeprecatedhashproperty) has been introduced to detect and autocorrect this deprecation. Remediation ----------- When using the `launchd` resource and passing a hash for the launchd property list, use the `plist_hash` property instead of the `hash` property. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_launchd_hash_property/Deprecation: Deploy Resource (CHEF-20) ====================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_deploy_resource.md) The `deploy` and `deploy_revision` resources have been deprecated as of Chef Client 13.6, and will be removed in Chef Client 14. Remediation ----------- For users that require the `deploy` or `deploy_revision` resources, they are now part of the [deploy_resource](https://supermarket.chef.io/cookbooks/deploy_resource) backwards compatibility cookbook available on the Supermarket. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_deploy_resource/Deprecation: Deprecation of run_command (CHEF-14) ================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_run_command.md) The old run_command API has been replaced by shell_out (a wrapper around Mixlib::ShellOut). This deprecation warning was added in Chef Client 12.18.31, and run_command will be removed permanently in Chef Client 13. Example ------- Previously to run a command from Chef Infra Client code you might have written: ``` run_command(command: '/sbin/ifconfig eth0') ``` Remediation ----------- You now need to use shell_out! instead: ``` shell_out!('/sbin/ifconfig eth0') ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_run_command/Deprecation: Local Mode Listen (CHEF-18) ======================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_local_listen.md) When using chef-client Local Mode, there are two ways to launch the internal Chef Zero server. Originally we launched it as a normal network service on localhost and then connected to it as per normal. Unfortunately this meant that any user or process on the machine could also connect to the Zero server during the converge and because Chef Zero has no authentication or authorization systems, they could potentially alter data mid-converge. We later added a “socketless” mode, which runs the Zero server completely internally and never exposes it on a real socket. Remediation ----------- If you need to re-enable socket mode for now, you can run chef-client –local-mode –listen or set knife[:listen] = true in your .chef/knife.rb or .chef/config.rb. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_local_listen/Deprecation: Use of property_name inside of actions (CHEF-19) ============================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_namespace_collisions.md) In Chef Client 12.5.1, the custom resources API allowed specifying property names as the short form of `property_name` inside of actions, instead of the long form of `new_resource.property_name` (as was previously required in provider code in LWRPs/HWRPs/etc). That change caused unsolvable namespace clashes and will be removed in Chef Client 14.0, and it will become mandatory to refer to properties as `new_resource.property_name` in actions. Example ------- This code worked in Chef Client 12.5.1 and later revisions up to Chef Client 13.0: ``` property :my_content, String action :doit do file '/tmp/file.xy' do content my_content end end ``` Remediation ----------- The `my_content` reference will no longer be wired up automatically to the `new_resource` object and users will need to specify `new_resource.my_content` explicitly: ``` property :my_content, String action :doit do file '/tmp/file.xy' do content new_resource.my_content end end ``` Note ---- In some edge cases, this deprecation warning may mention that the property should be referred to as `current_resource.property_name` instead of `new_resource.property_name`, which is not a mistake; the user should instead use the `current_resource.property_name` to preserve prior behavior, or should modify their code to explicitly check the `current_resource` if the `new_resource` is not set. There are several possible remediations to this in the order of least complicated to the most compatible with the old behavior, and the user will need to select what works best for their use case: ``` content_to_set = new_resource.property_name || current_resource.property_name content_to_set = new_resource.property_name.nil? ? current_resource.property_name : new_resource.property_name content_to_set = new_resource.property_is_set?(:property_name) ? new_resource.property_name : current_resource.property_name ``` Unfortunately, if you were reliant upon the old code’s automatic switching between the `new_resource` and `current_resource` you will need to be explicit. Most users, however, were not aware that this was occurring and moving that uncommon logic explicitly into the action code will produce more comprehensible code that is less reliant on subtle tricks of the API. It is also entirely possible that the access of the `current_resource` was never intended by the user. If this behavior was undesired, the correct remediation would be to simply access the property through the `new_resource.property_name`. We cannot determine and accurately report to the user when this deprecation message is incorrect, we can only report on compatible behavior. The suggestion of the deprecation warning to access the property through `current_resource.property_name` may be incorrect, and it is up to the discretion of the user to choose the appropriate remediation for their needs. The fact that this is confusing behavior to explain is why it is being removed. Rationale --------- The change in Chef Client 12.5.1 caused several insolvable problems. One of the worst was that properties would override DSL commands so that (for example) if a user had a `template` property they could no longer use the template resource: ``` property :template, String action :doit do template '/tmp/file.xy' do # this would NOT create a template resource but would pass a string and a block to the template property source 'file.xy.erb' variables({ stuff: 'whatever' }) end end ``` The highly confusing workaround for this problem was to use `declare_resource` to avoid the use of the resource DSL: ``` property :template, String action :doit do declare_resource(:template, '/tmp/file.xy') do # now there is no ambiguity and we create a template resource source 'file.xy.erb' variables({ stuff: 'whatever' }) end end ``` This also caused issues when properties conflicted with properties on subresources, where this example is ambiguous as to if the `content` argument to `content` refers to the file subresource `content` property, or if it refers to the parent custom resource `content` property. ``` property :content, String action :doit do puts "content: #{content}" file '/tmp/file.xy' do content content end end ``` In fact, the subprocess wins (because it has to) and this code will result in the content always being nil and the file being empty. The output of the `puts` debugging will be correct, however, since `content` is being accessed outside of the file resource scope so it acquires it from the `new_resource` implicitly (in Chef Client 12.5.1 and Chef Client 13.x) The way to remediate that is by specifying the `new_resource`: ``` property :content, String action :doit do file '/tmp/file.xy' do content new_resource.content end end ``` We are now enforcing this as the correct way to write resources. Note that this namespace collision between custom resources and subresources occurs with properties that are not also being immediately used, and so this fails as well: ``` property :mode, String action :doit do file '/tmp/file.xy' do content mode # this accesses the mode property on the file resource rather than the mode property on the outer resource end end ``` This will also cause namespace collisions if at some point in the future a new property is introduced to a subresource. ``` property :spiffyness, String action :doit do file '/tmp/file.xy' do content spiffyness end end ``` This will work fine today, but if at some point in the future the file resource grows a `spiffyness` property, then this will cause a namespace collision with the custom resource and will result in the custom resource failing. This is avoided by the explicit use of `new_resource`: ``` property :spiffyness, String action :doit do file '/tmp/file.xy' do content new_resource.spiffyness # we are always referring to the outer custom resource's spiffiness property end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_namespace_collisions/Deprecation: Deprecation of the erl_call resource (CHEF-22) ============================================================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_erl_call_resource.md) The erl_call resource was deprecated in Chef Client 13.7 and removed from Chef Client 14.0 (April 2018). The [Cookstyle](../workstation/cookstyle/index) cop [ChefDeprecations/ErlCallResource](https://github.com/chef/cookstyle/blob/main/docs/cops_chefdeprecations.md#chefdeprecationserlcallresource) has been introduced to detect this deprecation. Remediation ----------- Remove usage of the erl_call resource from all cookbooks. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_erl_call_resource/Deprecation: Legacy HWRP mixins (CHEF-23) ========================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_legacy_hwrp_mixins.md) In Chef Client 14 several legacy mixins will be removed. Usage of these mixins has resulted in deprecation warnings for several years. They were traditionally used in some HWRPs, but are rarely found in code available on the Supermarket. The [Cookstyle](../workstation/cookstyle/index) cop [ChefDeprecations/UsesDeprecatedMixins](https://github.com/chef/cookstyle/blob/main/docs/cops_chefdeprecations.md#chefdeprecationsusesdeprecatedmixins) has been introduced to detect these mixins: * `Chef::Mixin::LanguageIncludeAttribute` * `Chef::Mixin::RecipeDefinitionDSLCore` * `Chef::Mixin::LanguageIncludeRecipe` * `Chef::Mixin::Language` * `Chef::DSL::Recipe::FullDSL` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_legacy_hwrp_mixins/Deprecation: Map Collision (CHEF-25) ==================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_map_collision.md) The resource(s) referenced in the error message has been loaded from a cookbook. This resource is now included in Chef Infra Client and will take precedence over the existing cookbook resource in the next major release of Chef Infra Client (15.0, April 2019). Alternatively, there may be a newer version of this cookbook without this resource. Remediation ----------- Please upgrade your cookbook to the latest version, which may fix your issue, or ignore this error message. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_map_collision/Deprecation: epic_fail (CHEF-24) ================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_epic_fail.md) The original name for the `ignore_failure` property in resources was `epic_fail`. Our documentation hasn’t referred to `epic_fail` for years and out of the 3500 cookbooks on the Supermarket only one uses `epic_fail`. In Chef Client 14 we will remove the `epic_fail` property entirely. The [Cookstyle](../workstation/cookstyle/index) cop [ChefDeprecations/EpicFail](https://github.com/chef/cookstyle/blob/main/docs/cops_chefdeprecations.md#chefdeprecationsepicfail) has been introduced to detect and autocorrect this deprecation. Remediation ----------- Replace any usage of `epic_fail` with `ignore_failure`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_epic_fail/Deprecation: Deprecation of legacy shell_out APIs (CHEF-26) ============================================================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_shell_out.md) The functionality of multiple legacy shell_out APIs has been collapsed into the shell_out API itself, and the legacy methods have been deprecated. The shell_out_compact API has been migrated into shell_out, so those methods can be renamed. The functionality of shell_out_compact_timeout and shell_out_with_timeout have been migrated into shell_out for internal resources, and will be migrated into custom resources and LWRPs in Chef-15, in the meantime consumers should use shell_out with a timeout: new_resource.timeout option. The functionality of shell_out_with_systems_locale has been replaced by the default_env: false flag. The “banged” versions of those APIs (e.g. shell_out_compact!) changes identically to use shell_out!. Example ------- The following code examples need to be changed to the corresponding code below: ``` shell_out_compact('rpm', '-qa') shell_out_compact_timeout('rpm', '-qa') shell_out_with_timeout('rpm', '-qa') shell_out_with_systems_locale('rpm', '-qa') ``` Remediation ----------- You now need to use shell_out! instead: ``` shell_out('rpm', '-qa') shell_out('rpm', '-qa', timeout: new_resource.timeout) shell_out('rpm', '-qa', timeout: new_resource.timeout) shell_out('rpm', '-qa', default_env: false) ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_shell_out/Deprecation: :uninstall Resource for chocolatey_package (CHEF-21) ================================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_chocolatey_uninstall.md) The Chocolatey cookbook’s `chocolatey_package` resource originally contained an `:uninstall` action. When [chocolatey_package](../resources/chocolatey_package/index) was moved into core Chef, we made `:uninstall` an alias for `:remove`. In Chef Client 14, `:uninstall` will no longer be a valid action. The [Cookstyle](../workstation/cookstyle/index) cop [ChefDeprecations/ChocolateyPackageUninstallAction](https://github.com/chef/cookstyle/blob/main/docs/cops_chefdeprecations.md#chefdeprecationschocolateypackageuninstallaction) has been introduced to detect and autocorrect this deprecation. Remediation ----------- The `:uninstall` action must be replaced with the `:remove` action when using the `chocolatey_package` resource in recipes that you intend to use with Chef Client 14. For example, where you might previously have used the following code to uninstall `nginx`: ``` chocolatey_package 'nginx' do action :uninstall end ``` You would instead use: ``` chocolatey_package 'nginx' do action :remove end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_chocolatey_uninstall/Deprecation: Sigar gem based plugins removal (OHAI-2) ===================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_sigar_plugins.md) When Ohai was first released it depended on the sigar gem for discovering system configuration details. As time went on Ohai was expanded with built-in discovery methods for various platforms. The sigar gem was still required by Ohai and used primarily for the HP-UX platform. The SIGAR project is no longer active, and there is no longer an active port of Ruby to HP-UX. Due to this we’ve chosen to remove the sigar dependency and all sigar-based plugins from Ohai 13. There is no anticipated impact for Chef Foundation Platforms or Secondary Platforms. See the [Platforms](../platforms/index) page for a complete list of platforms. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_sigar_plugins/Deprecation: Ohai::Config removal (OHAI-1) ========================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_legacy_config.md) Ohai 8.8.0 (Chef Client 12.6.0) introduced a new Ohai configuration system as defined in [RFC-053](https://github.com/chef/chef-rfc/blob/main/rfc053-ohai-config.md). This system replaced the existing usage of `Ohai::Config` config system, which will be removed in Chef Client 13. Remediation ----------- Previous Ohai configuration values in the `client.rb` file need to be updated for the new configuration system format. For example, to configure the `plugin_path` value previously you would set `Ohai::Config[:plugin_path] = "/etc/chef/ohai/plugins.local"`, where as you would now use `ohai.plugin_path = "/etc/chef/ohai/plugins.local"`. See the [Ohai Configuration Documentation](../ohai/index#ohai-settings-in-client-rb) for additional usage information. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_legacy_config/Deprecation: Deprecation of lc_all from locale resource (CHEF-27) ================================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_locale_lc_all.md) Setting the `LC_ALL` variable is NOT recommended. As a system-wide setting, `LANG` should provide the desired behavior. `LC_ALL` is intended to be used for temporarily troubleshooting issues rather than an everyday system setting. Changing `LC_ALL` can break Chef’s parsing of command output in unexpected ways. Use one of the more specific `LC_` properties as needed. This deprecation warning was added in Chef Infra Client 15.0. Support for property `lc_all` will be removed for Chef Infra Client 16.0. The [Cookstyle](../workstation/cookstyle/index) cop [ChefDeprecations/LocaleDeprecatedLcAllProperty](https://github.com/chef/cookstyle/blob/main/docs/cops_chefdeprecations.md#chefdeprecationslocaledeprecatedlcallproperty) has been introduced to detect and autocorrect this deprecation. Remediation ----------- Set `LC_ALL` in current shell as: ``` export LC_ALL="<locale_name>" ``` To check the `locale` value, run: ``` locale -v ``` You can also use **file** Resource and add this variable in any other file of your choice and then can source that file to reflect changes. ``` file "<path_to_file>" do content "LC_ALL=<locale_name>" end ``` Where `path_to_file` could be any one of: * `/etc/default/locale` * `/etc/sysconfig/i18n` * `/etc/environment` Setting **LC_** variables varies by platform, but these are the common locations to configure **LC_** variables. Warning Using the **file** Resource or other manual management method of LC configuration may overwrite settings from this resource and break your system. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_locale_lc_all/Deprecation: resource_name declaration without provides (CHEF-31) ================================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_resource_name_without_provides.md) In Chef Client 12.5.1 through 15, resources could be addressed from recipe code using only the name of the resource, provided that no other `provides` declaration was used in the same file. The intent was to fulfill the demands that “users should just be able to name a resource and it should work” with the demands that, for more complicated use cases, users should be able to use `provides` lines to arbitrarily wire up resources to the Chef recipe language. This failed because it attempted to overly simplify user intent while generating two separate constructs with confusing interactions. Most users were entirely unaware that the `resource_name` statement implicitly issued a `provides` statement which wired up a specially designated `canonical` DSL entry, which was then removed behind the scenes if any subsequent `provides` declaration followed. When this worked it was easy to use, but when it failed the edge conditions were confusing and required too much background knowledge to debug. An attempt was made to preserve more complete backwards compatibility between Chef Infra Client 16.0 and earlier versions by retaining some automatic wiring of the `provides` statement with the `resource_name`. This failed due to complicated interactions between cookbooks that used multiple resources with the same name wired up via `provides` lines to different resource implementations on different operating systems. This was a silent error and dependent upon the parse order of the resources in the cookbook for it to become apparent, and could not be easily detected or remedied. The solution eventually adopted in Chef Infra Client 16.2 was to require all resources to declare a `provides` lines, and to make the `resource_name` setting only affect the display output. As a result, any cookbook which declares a resource with only a `resource_name` needs to add a `provides` line for Chef Infra Client 16. While this is more disruptive to users it is simple, it can be auto-corrected via static analysis, and it results in a much simpler end state where the `resource_name` is just a display name and the `provides` statement is solely responsible for how the resource is addressed in recipe mode. There is also the very old standard that existed before resources could declare what they provided. In that standard, the resource was addressed by prepending the `cookbook_name` to the filename that the resource was declared in. That has remained unchanged and is not affected by this change. Remediation ----------- A resource with only a `resource_name` property: ``` resource_name :my_custom_resource property :my_property, String action :run do [ ...implementation of the action... ] end ``` Should have a `provides` statement added: ``` resource_name :my_custom_resource provides :my_custom_resource property :my_property, String action :run do [ ...implementation of the action... ] end ``` It also works to have the `provides` line come prior to the `resource_name`, the order does not matter. For cookbooks which do not have to support Chef Infra Client 15 or before, the `resource_name` can also be entirely omitted: ``` provides :my_custom_resource property :my_property, String action :run do [ ...implementation of the action... ] end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_resource_name_without_provides/Deprecation: Resource Cloning (CHEF-3694) ========================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_resource_cloning.md) Chef allows resources to be created with duplicate names, rather than treating that as an error. This means that several cookbooks can request the same package be installed, without needing to carefully create unique names. This is problematic because having multiple resources with the same name makes it impossible to safely deliver notifications to the right resource. In Chef Client 13, resources with the same name will be treated as entirely separate, without any cloning of properties. The behavior in Chef Client 12 and earlier, which is now deprecated, is that we will try to clone the existing resource, and then apply any properties from the new resource. For example: ``` file '/etc/my_file' do owner 'ken' end file '/etc/my_file' do mode '0755' end ``` will result in the second instance having the following properties: ``` file '/etc/my_file' do owner 'ken' mode '0755' end ``` Resource cloning was deprecated in Chef Client 10.18.0 and will be removed in Chef Client 13. Note Chef will only emit a deprecation warning in the situation that a cloned resource is significantly different from the existing one. Remediation ----------- Ensure that resources you intend to notify are given unique names. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_resource_cloning/Deprecation: Enabling Unified Mode (CHEF-33) ============================================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_unified_mode.md) Unified mode combines the compile and converge stages of the Chef Infra Client run into one phase. When a resource has unified mode enabled, the Chef Infra Client compiles and converges that resource’s action block in one pass and in the order that the code inside that block is compiled, from the beginning to the end. In Chef Infra Client 17 (April 2021) and some earlier versions, the default behavior is `unified_mode false`. Enable unified mode on a custom resource with `unified_mode true`. Chef Infra Client displays a deprecation message with `unified_mode false`. In Chef Infra Client 18 (April 2022), `unified_mode true` will become the default behavior. | Chef Infra Client | Unified Mode | | --- | --- | | 18.x (2022) | Default: `unified_mode true` | | 17.x (2021) | Default: `unified_mode false` | | 16.x (2020) | Default: `unified_mode false` | | 15.3 and higher | Default: `unified_mode false` | | 15.0–15.2 | Not available | | 14.14-14.15 | Default: `unified_mode false` | | Lower than 14.14 | Not available | Enable Unified Mode ------------------- Enable unified mode by adding the `unified_mode true` in the custom resource. You can upgrade most custom resources to use unified mode without additional work other than testing and validation. ``` # enable unified mode unified_mode true provides :myresource actions :run do [...] end ``` Troubleshoot Unified Mode ------------------------- Unified mode changes the execution of a custom resource to run in one phase, in the order that the code is written, from the first line of the code to the last. Custom resources designed to use two phases may need modification. These fall into three general types: * Resources with changes to internal sub-resources * Resources with actions on later resources * Resources that rely on the out-of-order execution When designing a custom resource for unified mode: * Declare a resource first and then declare actions on it * Write resources in run-time order ### Resources with Changes to Internal Sub-resources Some custom resources are designed to create and edit other sub-resources as part of the resource declaration. In unified mode, the Chef Infra Client parses a resource code block that creates or edits a sub-resource and immediately tries to apply that change, even though the sub-resource does not yet exist. This results in the execution of an incomplete resource. For example, with unified mode enabled, this code from the *dhcp cookbook* is designed to create and edit a shared `dhcp_subnet` resource, but it will not work as expected: ``` # 'edit_resource' results in an incomple subresource sr = edit_resource(:dhcp_subnet, "#{new_resource.name}_sharedsubnet_#{subnet}") do owner new_resource.owner group new_resource.group mode new_resource.mode ip_version new_resource.ip_version conf_dir new_resource.conf_dir shared_network true end properties.each do |property, value| sr.send(property, value) end ``` To correct custom resources that change sub-resources during their declaration, you can: * Apply properties in the code block (preferred) * Run the resource explicitly (not preferred) #### Apply Properties in the Code Block This pattern declares the sub-resource in one code block and then changes it in the next code block. This is the preferred pattern in unified mode because all resources execute in order at compile time. ``` dhcp_subnet "#{new_resource.name}_sharedsubnet_#{subnet}" do owner new_resource.owner group new_resource.group mode new_resource.mode ip_version new_resource.ip_version conf_dir new_resource.conf_dir shared_network true properties.each do |property, value| send(property, value) end end ``` #### Run the Resource Explicitly Another solution is to continue saving the resource as a variable, declaring `action :nothing` within the codeblock and then explicitly running the action in another codeblock. The pattern of saving a resource as a variable and then forcing it to run at compile time with an explicit `run_action` works as it has in the past, but it is not a preferred pattern. Unified mode forces resource execution to compile time by default, which makes this pattern redundant. ``` sr = edit_resource(:dhcp_subnet, "#{new_resource.name}_sharedsubnet_#{subnet}") do owner new_resource.owner group new_resource.group mode new_resource.mode ip_version new_resource.ip_version conf_dir new_resource.conf_dir shared_network true action :nothing end properties.each do |property, value| sr.send(property, value) end # Run the action explicitly sr.run_action(:create) ``` Actions on Later Resources -------------------------- Since unified mode executes your resource as it is compiled, `:immediate` notifications that execute later resources are handled differently than in the past. ### `:immediate` Notifications to Later Resources Unified mode delays immediate notifications to later resources. In unified mode the Chef Infra Client saves immediate notifications and executes them when the later resource is parsed. Immediate notifications to prior resources and delayed notifications behave the same as they did before unified mode. The end result of sequentially chaining immediate notifications is the same as before unified mode. Instead of immediately notifying results, the notifications fire *in order* as they are parsed, which has the same outcome. If the parse order and the intended execution order are very different, then the results may be different and are a reflection of the parse order. The changes to sending immediate notification could result in subtle changes to behaviors in some resources, but it is not a breaking change to common patterns of writing resources. Chaining immediate notifications to later resources: ``` remote_file "#{Chef::Config[:file_cache_path]}/myservice.tgz" do source "http://acme.com/myservice.tgz" notifies :extract, "archive_file[myservice.tgz]", :immediately end archive_file "#{Chef::Config[:file_cache_path]}/myservice.tgz" do destination '/srv/myservice' notifies :start, "service[myservice]", :immediately action :nothing end service "myservice" do action :nothing end ``` ### `:before` Notifications to Later Resources In unified mode, you must declare a resource before sending a `before` notification to it. Resources that subscribe to a `before` notification to a later resource must be declared after the resource that triggers the notification. This resource declares a `before` notification to a later resource and will no longer work: ``` package "myservice" do notifies :stop, "service[myservice]", :before notifies :start, "service[myservice]", :immediately end service "myservice" do action :nothing end ``` Instead, declare the resource and then declare actions. For example: ``` service "myservice" do action :nothing end package "myservice" do notifies :stop, "service[myservice]", :before notifies :start, "service[myservice]", :immediately end ``` ### Out of Order Execution Unified mode breaks custom resources that rely on the out-of-order execution of compile-time statements. Move any affected compile-time statements to the location in the code where they are intended to execute. Out-of-order execution is rare. Internally at Chef, none of our custom resources broke during our migration to unified mode. Instead, we discovered a few cases in which custom resource code was intended to run in order, but Chef Infra Client executed it out of order. In these cases, unified mode fixed errors instead of introducing bugs. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_unified_mode/Deprecation: Libvirt plugin attributes changes (OHAI-4) ======================================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_libvirt_plugin.md) The Ohai libvirt plugin no longer places libvirt attributes under `node['virtualization']` and instead uses the `node['libvirt']` namespace to match other virtualization plugins. Remediation ----------- Cookbooks utilizing attributes from the libvirt plugin under `node['virtualization']` will need to be updated to instead use those same attributes from `node['libvirt']`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_libvirt_plugin/Deprecation: DigitalOcean plugin attribute changes (OHAI-6) =========================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_digitalocean.md) Ohai’s previous Digital Ocean plugin relied on hint data passed to Ohai as well and the drop’s internal network interface configuration. The Digital Ocean plugin has been rewritten to poll information from the Digital Ocean Metadata endpoint instead. This provides additional Digital Ocean specific droplet configuration information as well as external IP address information that was previously not available. With the addition of new network configuration data, the format has changed and users relying on the previous format will need to update their cookbooks. Remediation ----------- Update cookbooks to use the new network data format as seen below. Example of previous data format: ``` { "networks": { "v4": [ { "ip_address": "138.68.99.253", "type": "public", "netmask": "255.255.240.0" }, { "ip_address": "10.19.0.5", "type": "private", "netmask": "255.255.0.0" } ], "v6": [ { "ip_address": "2a03:b0c0:0003:00d0:0000:0000:322a:3001", "type": "public", "cidr": "128" }, { "ip_address": "fe80:0000:0000:0000:d4b1:9eff:fe61:8cce", "type": "private", "cidr": "128" } ] } } ``` Example of new data format: ``` { "droplet_id": 12345678, "hostname": "mytestnode", "public_keys": [ "ssh-rsa SOMEKEY", ], "auth_key": "SOMEKEY", "region": "fra1", "interfaces": { "public": [ { "ipv4": { "ip_address": "138.68.99.253", "netmask": "255.255.240.0", "gateway": "138.68.96.1" }, "ipv6": { "ip_address": "2A03:B0C0:0003:00D0:0000:0000:322A:3001", "cidr": 64, "gateway": "2A03:B0C0:0003:00D0:0000:0000:0000:0001" }, "anchor_ipv4": { "ip_address": "10.19.0.5", "netmask": "255.255.0.0", "gateway": "10.19.0.1" }, "mac": "d6:b1:9e:61:8c:ce", "type": "public" } ] }, "floating_ip": { "ipv4": { "active": false } }, "dns": { "nameservers": [ "2001:4860:4860::8844", "2001:4860:4860::8888", "8.8.8.8" ] }, "tags": null } ``` As an example where you would previously use the attribute `node['digital_ocean']['networks']['v4'][0]['ipaddress']` you would now use `node['digital_ocean']['interfaces']['public'][0]['ipv4']['ip_address']`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_digitalocean/Deprecation: run_command and popen4 helper method removal (OHAI-3) =================================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_run_command_helpers.md) Ohai ships a command mixin for use by plugin authors in shelling out to external commands. This mixin originally included `run_command` and `popen4` methods, which were deprecated in Ohai 8.11.1 (Chef Client 12.8.1) in favor of the more robust `mixlib-shellout` gem functionality. In Chef Client 13 these deprecated methods will be removed, breaking any Ohai plugins authored using the deprecated methods. Remediation ----------- Plugins should be updated to use mixlib-shellout instead of the run_command. Deprecated run_command based code: ``` status, stdout, stderr = run_command(command: 'myapp --version') if status == 0 version = stdout end ``` Updated code for mixlib shellout: ``` so = shell_out('myapp --version') if so.exitstatus == 0 version = so.stdout end ``` See the [mixlib-shellout repo](https://github.com/chef/mixlib-shellout) for additional usage information. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_run_command_helpers/Deprecation: Amazon linux moved to the Amazon platform_family (OHAI-7) ======================================================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_amazon_linux.md) In Ohai/Chef releases prior to Chef Client 13, Amazon Linux was identified as `platform_family 'rhel'`. In Ohai/Chef Client 13 and later, Amazon Linux will be identified as the `platform_family 'amazon'`. When Amazon Linux was created it closely mirrored the structure and package naming of RHEL 5, and with the release of RHEL 6 Amazon Linux moved to closely resemble RHEL 6. With the release of RHEL 7 Red Hat switched to the systemd init system, however Amazon Linux has not yet decided to make that same switch. In addition to the init system differences, Amazon Linux has added many critical packages with their own unique naming conventions. This makes it very hard for users to write cookbooks for RHEL that will work on Amazon Linux systems out of the box. In order to simplify multi-platform cookbook code and to make it more clear when cookbooks actually support Amazon Linux, we’ve created the ‘`amazon` platform family and removed Amazon Linux from the `rhel` platform family. Remediation ----------- If you have a cookbook that relies on `platform_family 'rhel'` to support Red Hat based distributions as well as Amazon Linux, you’ll need to modify your code to specifically check for the `'amazon'` platform family. Existing code only checking for the `rhel` platform family: ``` if platform_family?('rhel') service 'foo' do action :start end end ``` Updated code to check for both `rhel` and `amazon` platform families: ``` if platform_family?('rhel', 'amazon') service 'foo' do action :start end end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_amazon_linux/Deprecation: Windows CPU plugin attribute changes. (OHAI-5) =========================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_windows_cpu.md) The Windows Ohai plugin has been updated to correctly return CPU information. Previously the CPU plugin reported a `model_name` value, which was actually the CPU’s description and not the actual model name. Ohai now reports the proper name value for `model_name` and provides `description` with the previous description value. This behavior aligns CPU plugin behavior between *nix and Windows hosts in Chef. Remediation ----------- If you rely on the format of a CPU model_name value such as `node['cpu'['0']['model_name']` you will need to update your cookbook code to reference `node['cpu']['0']['description']` instead. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_windows_cpu/Deprecation: Cloud plugin replaced by the Cloud_V2 plugin (OHAI-8) =================================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_cloud.md) In Ohai/Chef releases 13 we replaced the existing Cloud plugin with the Cloud_v2 plugin. This was done by having the Cloud_v2 plugin populate both `node['cloud']` and `node['cloud_v2']`. The Cloud_v2 plugin includes a different data format that resolves many of the longstanding bugs in the existing Cloud plugin. Remediation ----------- If you have a cookbook that relies on data from `node['cloud']` you will need to update the code to the new format in Chef Client 13. On a Chef Client 12 or earlier node you can compare the data formats by running `ohai cloud` and `ohai cloud_v2`. Here are examples of the old and new format of the cloud data: ``` { "public_ips": [ "52.88.253.144" ], "private_ips": [ "172.31.37.209" ], "public_ipv4": "52.88.253.144", "public_hostname": "ec2-52-88-253-144.us-west-2.compute.amazonaws.com", "local_ipv4": "172.31.37.209", "local_hostname": "ip-172-31-37-209.us-west-2.compute.internal", "provider": "ec2" } ``` ``` { "public_ipv4_addrs": [ "52.88.253.144" ], "local_ipv4_addrs": [ "172.31.37.209" ], "public_hostname": "ec2-52-88-253-144.us-west-2.compute.amazonaws.com", "local_hostname": "ip-172-31-37-209.us-west-2.compute.internal", "public_ipv4": "52.88.253.144", "local_ipv4": "172.31.37.209", "provider": "ec2" } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_cloud/Deprecation: Filesystem plugin replaced by the Filesystem V2 plugin. (OHAI-9) ============================================================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_filesystem.md) In Ohai/Chef Client 13 we replaced the existing Filesystem plugin with the Filesystem2 plugin. This was done by having the Filesystem2 plugin populate both `node['filesystem2']` and `node['filesystem']`. The Filesystem2 plugin includes a different data format that resolves many of the longstanding bugs in the Filesystem plugin. Remediation ----------- If you have a cookbook that relies on data from `node['filesystem']` you will need to update the code to use data in the new format when migrating to Chef Client 13 or later. On a Chef Client 12 or earlier node you can view the new format by running ohai filesystem2 or on a Chef Client 13+ node you can run `ohai filesystem`. The output of the filesystem plugin is too large to show the difference here, but as an example code that may reference `node['/dev/xvda1']['kb_size']` would need to be updated to reference `node['by_device']['/dev/xvda1']['kb_size']` as filesystem data is now displayed by both devices and mounts. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_filesystem/Deprecation: Removal of IpScopes Plugin (OHAI-13) ================================================= [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_ipscopes.md) Chef/Ohai 14 (April 2018) will remove the IpScopes plugin. The data returned by this plugin is nearly identical to information already returned by individual network plugins, and this plugin required the inclusion of an additional gem into the Chef installation. We believe that few users were installing the gem, and users would be better served by the data returned from network plugins. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_ipscopes/Deprecation: Filesystem2 attribute removal (OHAI-12) ==================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_filesystem_v2.md) In Ohai/Chef Client 13 we replaced the existing Filesystem plugin with the Filesystem V2 plugin. That was done by having Ohai populate both `node['filesystem']` and `node['filesystem_v2']` with the data previously found at `node['filesystem2']`. In Chef Client 14 we will no longer populate `node['filesystem2']`. Remediation ----------- If you have a cookbook that relies on data from `node['filesystem2']` you will need to update the code to instead use `node['filesystem']`. Keep in mind that if you’re attempting to support releases earlier than Chef Client 13 the data structure of node[‘filesystem’] will be different. Foodcritic’s FC094 rule will detect any usage of the `node['filesystem_v2']` attributes. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_filesystem_v2/Deprecation: Removal of support for Ohai version 6 plugins (OHAI-10) ==================================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_v6_plugins.md) Ohai 7.0 released with Chef Client 11.12 introduced an improved plugin DSL model. At the time we introduced deprecations for the existing plugin DSL, which we referred to as V6 plugins. In Ohai/Chef Client 14 we will remove the support for Ohai V6 plugins, causing a runtime error if they are used. Remediation ----------- If you have custom Ohai V6 plugins installed via cookbook or bootstrap you will need to update these plugins to the Ohai V7 plugin format. See the [Ohai Custom Plugins page](../ohai_custom/index) for additional information on writing V7 plugins. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_v6_plugins/Deprecation: System Profile plugin (OHAI-14) ============================================ [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_system_profile.md) The system_profile plugin will be removed from Chef/Ohai 15 in April 2019. This plugin does not correctly return data on modern Mac systems. Additionally the same data is provided by the hardware plugin, which has a format that is simpler to consume. Removing this plugin will reduce Ohai return by ~3 seconds and greatly reduce the size of the node object on the Chef Infra Server. Remediation ----------- If you relied on data in node[‘system_profile’], you should look at the format in node[‘hardware’] and migrate to that new data format. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_system_profile/config.rb ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/config_rb.md) Warning The `config.rb` file is a replacement for the `knife.rb` file. The `config.rb` file has identical settings and behavior to the `knife.rb` file. Chef Infra Client looks first for the presence of the `config.rb` file and if it is not found, then looks for the `knife.rb` file. A `config.rb` file is used to specify configuration details for knife. A `config.rb` file: * Is loaded every time the knife executable is run * Is not created by default * Is located by default at `~/.chef/config.rb` (macOS and Linux platforms) or `c:\Users\username\.chef\config.rb` (Microsoft Windows platform), use the `--config` option from the command line to change this location * Will override the default configuration when a `config.rb` file exists at the default path or the path specified by the `--config` option Note When running Microsoft Windows, the `config.rb` file is located at `%HOMEDRIVE%:%HOMEPATH%\.chef` (e.g. `c:\Users\<username>\.chef`). Settings -------- This configuration file has the following settings: `bootstrap_template` The path to a template file to be used during a bootstrap operation. `chef_server_url` The URL for the Chef Infra Server. For example: ``` chef_server_url 'https://localhost/organizations/ORG_NAME' ``` Note If changes need to be made to any global end points like user or user keys, use [`knife exec`](workstation/knife_exec/index) with the `--server-url` flag to set `chef_server_url` to `https://localhost/`. `chef_zero.enabled` Enable chef-zero. This setting requires `local_mode` to be set to `true`. Default value: `false`. For example: ``` chef_zero.enabled true ``` `chef_zero[:port]` The port on which chef-zero is to listen. Default value: `8889`. For example: ``` chef_zero[:port] 8889 ``` `client_d_dir` A directory that contains additional configuration scripts to load for Chef Infra Client. `client_key` The location of the file that contains the client key, as an absolute path. Default value: `/etc/chef/client.pem`. For example: ``` client_key '/etc/chef/client.pem' ``` `cookbook_copyright` The name of the copyright holder. This option places a copyright notice that contains the name of the copyright holder in each of the pre-created files. If this option is not specified, a copyright name of “COMPANY_NAME” is used instead; it can easily be modified later. `cookbook_email` The email address for the individual who maintains the cookbook. This option places an email address in each of the pre-created files. If not specified, an email name of “YOUR_EMAIL” is used instead; this can easily be modified later. `cookbook_license` The type of license under which a cookbook is distributed: `apachev2`, `gplv2`, `gplv3`, `mit`, or `none` (default). This option places the appropriate license notice in the pre-created files: `Apache v2.0` (for `apachev2`), `GPL v2` (for `gplv2`), `GPL v3` (for `gplv3`), `MIT` (for `mit`), or `license 'Proprietary - All Rights Reserved` (for `none`). Be aware of the licenses for files inside of a cookbook and be sure to follow any restrictions they describe. `cookbook_path` The Chef Infra Client sub-directory for storing cookbooks. This value can be a string or an array of file system locations, processed in the specified order. The last cookbook is considered to override local modifications. For example: ``` cookbook_path [ '/var/chef/cookbooks', '/var/chef/site-cookbooks' ] ``` `data_bag_encrypt_version` The minimum required version of data bag encryption. Possible values: `1` or `2`. When all of the machines in an organization are running Chef Client 11.6 (or higher), it is recommended that this value be set to `2`. For example: ``` data_bag_encrypt_version 2 ``` `fips` Allows OpenSSL to enforce FIPS-validated security during a Chef Infra Client run. Set to `true` to enable FIPS-validated security. The following operating systems are supported: * Red Hat Enterprise Linux * Oracle Enterprise Linux * CentOS * Windows `local_mode` Run Chef Infra Client in local mode. This allows all commands that work against the Chef Infra Server to also work against the local chef-repo. For example: ``` local_mode true ``` `node_name` The name of the node. This may be a username with permission to authenticate to the Chef Infra Server or it may be the name of the machine from which knife is run. For example: ``` node_name 'user_name' ``` or: ``` node_name 'machine_name' ``` `no_proxy` A comma-separated list of URLs that do not need a proxy. Default value: `nil`. For example: ``` no_proxy 'localhost, 10.0.1.35, *.example.com, *.dev.example.com' ``` `ssh_agent_signing` **New in 14.2** Use `ssh-agent` to authenticate. When using this option, specify the location of the public key in `client_key`. Default value: `false`. Ensure the public key is in PKCS#1 format. You can convert an OpenSSH public key using `ssh-keygen`. For example: ``` ssh-keygen -f key.pub -e -m pem > key.pem ``` `ssh_timeout` The amount of time (in seconds) to wait for an SSH connection time out. `ssl_verify_mode` Set the verify mode for HTTPS requests. * Use `:verify_none` to do no validation of SSL certificates. * Use `:verify_peer` to do validation of all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS **remote_file** resource URLs used in a Chef Infra Client run. This is the recommended setting. Depending on how OpenSSL is configured, the `ssl_ca_path` may need to be specified. Default value: `:verify_peer`. `tmux_split` Split the Tmux window. Default value: `false`. `validation_client_name` The name of the chef-validator key that is used by Chef Infra Client to access the Chef Infra Server during the initial Chef Infra Client run when not using validatorless bootstrapping. For example: ``` validation_client_name 'chef-validator' ``` `validation_key` The location of the file that contains the key used when a Chef Infra Client is registered with a Chef Infra Server. A validation key is signed using the `validation_client_name` for authentication. Default value: `/etc/chef/validation.pem`. For example: ``` validation_key '/etc/chef/validation.pem' ``` `verify_api_cert` Verify the SSL certificate on the Chef Infra Server. When `true`, Chef Infra Client always verifies the SSL certificate. When `false`. Chef Infra Client uses the value of `ssl_verify_mode` to determine if the SSL certificate requires verification. Default value: `false`. `versioned_cookbooks` Append cookbook versions to cookbooks. Set to `false` to hide cookbook versions: `cookbooks/apache`. Set to `true` to show cookbook versions: `cookbooks/apache-1.0.0` and/or `cookbooks/apache-1.0.1`. When this setting is `true`, `knife download` downloads ALL cookbook versions, which can be useful if a full-fidelity backup of data on the Chef Infra Server is required. For example: ``` versioned_cookbooks true ``` `config_log_level` Sets the default value of `log_level` in the client.rb file of the node being bootstrapped. Possible values are `:debug`, `:info`, `:warn`, `:error` and `:fatal`. For example: ``` config_log_level :debug ``` `config_log_location` Sets the default value of `log_location` in the client.rb file of the node being bootstrapped. Possible values are `/path/to/log_location`, `STDOUT`, `STDERR`, `:win_evt` and `:syslog`. For example: ``` config_log_location "/path/to/log_location" # Please make sure that the path exists ``` ### Proxy Settings In certain situations the proxy used by the Chef Infra Server requires authentication. In this situation, three settings must be added to the configuration file. Which settings to add depends on the protocol used to access the Chef Infra Server: HTTP or HTTPS. If the Chef Infra Server is configured to use HTTP, add the following settings: `http_proxy` The proxy server for HTTP connections. Default value: `nil`. For example: ``` http_proxy 'http://proxy.example.com:3128' ``` `http_proxy_user` The user name for the proxy server when the proxy server is using an HTTP connection. Default value: `nil`. `http_proxy_pass` The password for the proxy server when the proxy server is using an HTTP connection. Default value: `nil`. #### HTTPS Proxy Settings (such as the hosted Chef Infra Server) `https_proxy` The proxy server for HTTPS connections. (The hosted Chef Infra Server uses an HTTPS connection.) Default value: `nil`. `https_proxy_user` The user name for the proxy server when the proxy server is using an HTTPS connection. Default value: `nil`. `https_proxy_pass` The password for the proxy server when the proxy server is using an HTTPS connection. Default value: `nil`. #### Settings for No-proxy URLs `no_proxy` A comma-separated list of URLs that do not need a proxy. Default value: `nil`. .d Directories -------------- Chef Infra Client supports reading multiple configuration files by putting them inside a `.d` configuration directory. For example: `/etc/chef/client.d`. All files that end in `.rb` in the `.d` directory are loaded; other non-`.rb` files are ignored. `.d` directories may exist in any location where the `client.rb`, `config.rb`, or `solo.rb` files are present, such as: * `/etc/chef/client.d` * `/etc/chef/config.d` * `~/chef/solo.d` (There is no support for a `knife.d` directory; use `config.d` instead.) For example, when using knife, the following configuration files would be loaded: * `~/.chef/config.rb` * `~/.chef/config.d/company_settings.rb` * `~/.chef/config.d/ec2_configuration.rb` * `~/.chef/config.d/old_settings.rb.bak` The `old_settings.rb.bak` file is ignored because it’s not a configuration file. The `config.rb`, `company_settings.rb`, and `ec2_configuration` files are merged together as if they are a single configuration file. Note If multiple configuration files exists in a `.d` directory, ensure that the same setting has the same value in all files. Optional Settings ----------------- In addition to the default settings in a `config.rb` file, there are other subcommand-specific settings that can be added: 1. A value passed via the command-line 2. A value contained in the `config.rb` file 3. The default value A value passed via the command line overrides a value in the `config.rb` file; a value in a `config.rb` file overrides a default value. Before adding any settings to the `config.rb` file: * Verify the settings by reviewing the documentation for the knife subcommands and/or knife plugins * Verify the use case(s) your organization has for adding them Also note that: * Custom plugins can be configured to use the same settings as the core knife subcommands * Many of these settings are used by more than one subcommand and/or plugin * Some of the settings are included only because knife checks for a value in the `config.rb` file To add settings to the `config.rb` file, use the following syntax: ``` knife[:setting_name] = value ``` where `value` may require quotation marks (' ‘) if that value is a string. For example: ``` knife[:ssh_port] = 22 knife[:bootstrap_template] = 'ubuntu14.04-gems' knife[:bootstrap_version] = '' knife[:bootstrap_proxy] = '' ``` ### Frequently Used Some of the optional `config.rb` settings are used often, such as the template file used in a bootstrap operation. The frequency of use of any option varies from organization to organization, so even though the following settings are often added to a `config.rb` file, they may not be the right settings to add for every organization: `knife[:bootstrap_proxy]` The proxy server for the node that is the target of a bootstrap operation. `knife[:bootstrap_template]` The path to a template file to be used during a bootstrap operation. `knife[:bootstrap_version]` The version of Chef Infra Client to install. `knife[:editor]` The $EDITOR that is used for all interactive commands. `knife[:ssh_gateway]` The SSH tunnel or gateway that is used to run a bootstrap action on a machine that is not accessible from the workstation. Adding this setting can be helpful when a user cannot SSH directly into a host. `knife[:ssh_port]` The SSH port. ### Additional SSH Settings Other SSH-related settings that are sometimes helpful when added to the `config.rb` file: `knife[:forward_agent]` Enable SSH agent forwarding. `knife[:ssh_attribute]` The attribute used when opening an SSH connection. `knife[:ssh_password]` The SSH password. This can be used to pass the password directly on the command line. If this option is not specified (and a password is required) knife prompts for the password. `knife[:ssh_user]` The SSH user name. ### Data Bag Settings Some organizations choose to have all data bags use the same secret and secret file, rather than have a unique secret and secret file for each data bag. To use the same secret and secret file for all data bags, add the following to `config.rb`: `knife[:secret]` The encryption key that is used for values contained within a data bag item. `knife[:secret_file]` The path to the file that contains the encryption key. ### Ohai Settings (Not Recommended) Some settings are better left to Ohai, which gets the value at the start of a Chef Infra Client run: `knife[:server_name]` Same as `node_name`. Recommended configuration is to allow Ohai to collect this value during each Chef Infra Client run. `node_name` Same as `knife[:server_name]`. Recommended configuration is to allow Ohai to collect this value during each Chef Infra Client run. Warning Review the full list of [optional settings](workstation/config_rb_optional_settings/index) that can be added to the `config.rb` file. Many of these optional settings should not be added to the `config.rb` file. The reasons for not adding them can vary. For example, using `--yes` as a default in the `config.rb` file causes knife to always assume that “Y” is the response to any prompt, which may lead to undesirable outcomes. Other settings, such as `--hide-healthy`(used only with the `knife status` subcommand) or `--bare-directories` (used only with the `knife list` subcommand) probably aren’t used often enough (and in the same exact way) to justify adding them to the `config.rb` file. In general, if the optional settings are not listed on the main config.rb[topic](workstation/config_rb/index), then add settings only after careful consideration. Do not use optional settings in a production environment until after the setting’s performance has been validated in a safe testing environment. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/config_rb.htmlchef-shell (executable) ======================= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/chef_shell.md) chef-shell is a recipe debugging tool that allows the use of breakpoints within recipes. chef-shell runs as an Interactive Ruby (IRb) session. chef-shell supports both recipe and attribute file syntax, as well as interactive debugging features. The chef-shell executable is run as a command-line tool. Modes ----- chef-shell is tool that is run using an Interactive Ruby (IRb) session. chef-shell currently supports recipe and attribute file syntax, as well as interactive debugging features. chef-shell has three run modes: | Mode | Description | | --- | --- | | Standalone | Default. No cookbooks are loaded, and the run-list is empty. | | Solo | chef-shell acts as a Chef Solo Client. It attempts to load the chef-solo configuration file at `~/.chef/config.rb` and any JSON attributes passed. If the JSON attributes set a run-list, it will be honored. Cookbooks will be loaded in the same way that chef-solo loads them. chef-solo mode is activated with the `-s` or `--solo` command line option, and JSON attributes are specified in the same way as for chef-solo, with `-j /path/to/chef-solo.json`. | | Client | chef-shell acts as a Chef Infra Client. During startup, it reads the Chef Infra Client configuration file from `~/.chef/client.rb` and contacts the Chef Infra Server to get the node's run_list, attributes, and cookbooks. Chef Infra Client mode is activated with the `-z` or `--client` options. You can also specify the configuration file with `-c CONFIG` and the server URL with `-S SERVER_URL`. | Options ------- This command has the following syntax: ``` chef-shell OPTION VALUE OPTION VALUE ... ``` This command has the following options: `-a`, `--standalone` Run chef-shell in standalone mode. `-c CONFIG`, `--config CONFIG` The configuration file to use. `-h`, `--help` Show help for the command. `-j PATH`, `--json-attributes PATH` The path to a file that contains JSON data. Use this option to define a `run_list` object. For example, a JSON file similar to: ``` "run_list": [ "recipe[base]", "recipe[foo]", "recipe[bar]", "role[webserver]" ], ``` may be used by running `chef-shell -j path/to/file.json`. In certain situations this option may be used to update `normal` attributes. Warning Any other attribute type that is contained in this JSON file will be treated as a `normal` attribute. Setting attributes at other precedence levels is not possible. For example, attempting to update `override` attributes using the `-j` option: ``` { "name": "dev-99", "description": "Install some stuff", "override_attributes": { "apptastic": { "enable_apptastic": "false", "apptastic_tier_name": "dev-99.bomb.com" } } } ``` will result in a node object similar to: ``` { "name": "maybe-dev-99", "normal": { "name": "dev-99", "description": "Install some stuff", "override_attributes": { "apptastic": { "enable_apptastic": "false", "apptastic_tier_name": "dev-99.bomb.com" } } } } ``` `-l LEVEL`, `--log-level LEVEL` The level of logging to be stored in a log file. `-o RUN_LIST_ITEM`, `--override-runlist RUN_LIST_ITEM` Replace the current run-list with the specified items. Only applicable when also using `solo` or `server` modes. `-s`, `--solo` Run chef-shell in chef-solo mode. `-S CHEF_SERVER_URL`, `--server CHEF_SERVER_URL` The URL for the Chef Infra Server. `-v`, `--version` The Chef Infra Client version. `-z`, `--client` Run chef-shell in Chef Infra Client mode. Configure --------- chef-shell determines which configuration file to load based on the following: 1. If a configuration file is specified using the `-c` option, chef-shell will use the specified configuration file 2. If a NAMED_CONF is given, chef-shell will load ~/.chef/NAMED_CONF/chef_shell.rb 3. If no NAMED_CONF is given chef-shell will load ~/.chef/chef_shell.rb if it exists 4. If no chef_shell.rb can be found, chef-shell falls back to load: * /etc/chef/client.rb if -z option is given. * /etc/chef/solo.rb if –solo-legacy-mode option is given. * .chef/config.rb if -s option is given. * .chef/knife.rb if -s option is given. ### chef-shell.rb The chef-shell.rb file can be used to configure chef-shell in the same way as the client.rb file is used to configure Chef Infra Client. For example, to configure chef-shell to authenticate to the Chef Infra Server, copy the `node_name`, `client_key`, and `chef_server_url` settings from the config.rb file: ``` node_name 'your-knife-clientname' client_key File.expand_path('~/.chef/my-client.pem') chef_server_url 'https://api.opscode.com/organizations/myorg' ``` and then add them to the chef-shell.rb file. Other configuration possibilities include disabling Ohai plugins (which will speed up the chef-shell boot process) or including arbitrary Ruby code in the chef-shell.rb file. ### Run as a Chef Infra Client By default, chef-shell loads in standalone mode and does not connect to the Chef Infra Server. The chef-shell can be run as a Chef Infra Client to verify functionality that is only available when Chef Infra Client connects to the Chef Infra Server, such as search functionality or accessing data stored in data bags. chef-shell can use the same credentials as knife when connecting to a Chef Infra Server. Make sure that the settings in chef-shell.rb are the same as those in config.rb, and then use the `-z` option as part of the command. For example: ``` chef-shell -z ``` Debugging Cookbooks ------------------- chef-shell allows the current position in a run-list to be manipulated during a Chef Infra Client run. Add breakpoints to a recipe to take advantage of this functionality. ### Step Through Run-list To explore how using the **breakpoint** to manually step through a Chef Infra Client run, create a simple recipe in chef-shell: ``` chef > recipe_mode chef:recipe > echo off chef:recipe > file "/tmp/before-breakpoint" chef:recipe > breakpoint "foo" chef:recipe > file "/tmp/after-breakpoint" ``` and then run Chef Infra Client: ``` chef:recipe > run_chef [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:17:49 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint ``` Chef Infra Client ran the first resource before the breakpoint (`file[/tmp/before-breakpoint]`), but then stopped after execution. Chef Infra Client attempted to name the breakpoint after its position in the source file, but Chef Infra Client was confused because the resource was entered interactively. From here, chef-shell can resume the interrupted Chef Infra Client run: ``` chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:27:08 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` A quick view of the `/tmp` directory shows that the following files were created: ``` after-breakpoint before-breakpoint ``` You can rewind and step through a Chef Infra Client run: ``` chef:recipe > Chef::Log.level = :debug # debug logging won't turn on automatically in this case => :debug chef:recipe > chef_run.rewind => 0 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File => 1 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint => 2 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File => 3 ``` From the output, the rewound run-list is shown, but when the resources are executed again, they will repeat their checks for the existence of files. If they exist, Chef Infra Client will skip creating them. If the files are deleted, then: ``` chef:recipe > ls("/tmp").grep(/breakpoint/).each {|f| rm "/tmp/#{f}" } => ["after-breakpoint", "before-breakpoint"] ``` Rewind, and then resume your Chef Infra Client run to get the expected results: ``` chef:recipe > chef_run.rewind chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:48:56 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:49:20 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` ### Debug Existing Recipe chef-shell can be used to debug existing recipes. The recipe first needs to be added to a run-list for the node, so that it is cached when starting chef-shell and then used for debugging. chef-shell will report which recipes are being cached when it is started: ``` loading configuration: none (standalone session) Session type: standalone Loading.............done. Welcome to the chef-shell 15.8.23 For usage see https://docs.chef.io/chef_shell.html run `help' for help, `exit' or ^D to quit. chef (15.8.23)``` To just load one recipe from the run-list, go into the recipe and use the `include_recipe` command. For example: ``` chef > recipe_mode chef:recipe > include_recipe "getting-started" => [#< Chef::Recipe:0x10256f9e8 @cookbook_name="getting-started", ... output truncated ... ``` To load all of the recipes from a run-list, use code similar to the following: ``` node.run_list.expand(node.chef_environment).recipes.each do |r| include_recipe r end ``` After the recipes that are to be debugged have been loaded, use the `run_chef` command to run them. ### Advanced Debugging In chef-shell, it is possible to get verbose debugging using the tracing feature in Interactive Ruby (IRb). chef-shell provides a shortcut for turning tracing on and off. For example: ``` chef > tracing on tracing is on => nil chef ``` and: ``` chef > tracing off #0:(irb):2:Object:-: tracing off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:109:Shell::Extensions::ObjectCoreExtensions:>: def off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:110:Shell::Extensions::ObjectCoreExtensions:-: :off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:111:Shell::Extensions::ObjectCoreExtensions:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:272:main:>: def tracing(on_or_off) #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:273:main:-: conf.use_tracer = on_or_off.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:162:Shell::Extensions::Symbol:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:163:Shell::Extensions::Symbol:-: to_s.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:149:Shell::Extensions::String:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:150:Shell::Extensions::String:-: case self #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:154:Shell::Extensions::String:-: false #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:158:Shell::Extensions::String:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:164:Shell::Extensions::Symbol:<: end tracing is off => nil chef ``` Manipulating Chef Infra Server Data ----------------------------------- When chef-shell is configured to access a Chef Infra Server, chef-shell can list, show, search for and edit cookbooks, clients, nodes, roles, environments, policyfiles, and data bags. The syntax for managing objects on the Chef Infra Server is as follows: ``` chef-shell -z named_configuration ``` Where: * `named_configuration` is an existing configuration file in `~/.chef/named_configuration/chef_shell.rb`, such as `production`, `staging`, or `test`. Once in chef-shell, commands can be run against objects as follows: ``` chef (preprod) > items.command ``` Where: * `items` is the type of item to search for: `cookbooks`, `clients`, `nodes`, `roles`, `environments` or a data bag. * `command` is the command: `list`, `show`, `find`, or `edit`. For example, to list all of the nodes in a configuration named “preprod”, enter: ``` chef (preprod) > nodes.list ``` Which will return something similar to: ``` => [node[i-f09a939b], node[i-049a936f], node[i-eaaaa581], node[i-9154b1fb], node[i-6a213101], node[i-c2687aa9], node[i-7abeaa11], node[i-4eb8ac25], node[i-9a2030f1], node[i-a06875cb], node[i-145f457f], node[i-e032398b], node[i-dc8c98b7], node[i-6afdf401], node[i-f49b119c], node[i-5abfab31], node[i-78b8ac13], node[i-d99678b3], node[i-02322269], node[i-feb4a695], node[i-9e2232f5], node[i-6e213105], node[i-cdde3ba7], node[i-e8bfb083], node[i-743c2c1f], node[i-2eaca345], node[i-aa7f74c1], node[i-72fdf419], node[i-140e1e7f], node[i-f9d43193], node[i-bd2dc8d7], node[i-8e7f70e5], node[i-78f2e213], node[i-962232fd], node[i-4c322227], node[i-922232f9], node[i-c02728ab], node[i-f06c7b9b]] ``` The `list` command can take a code block, which will applied (but not saved), to each object that is returned from the server. For example: ``` chef (preprod) > nodes.list {|n| puts "#{n.name}: #{n.run_list}" } ``` will return something similar to: ``` => i-f09a939b: role[lb], role[preprod], recipe[aws] i-049a936f: role[lb], role[preprod], recipe[aws] i-9154b1fb: recipe[erlang], role[base], role[couchdb], role[preprod], i-6a213101: role[chef], role[preprod] # more... ``` The `show` command can be used to display a specific node. For example: ``` chef (preprod) > load_balancer = nodes.show('i-f09a939b') ``` will return something similar to: ``` => node[i-f09a939b] ``` Or: ``` chef (preprod) > load_balancer.ec2.public_hostname ``` will return something similar to: ``` => "ec2-111-22-333-44.compute-1.amazonaws.com" ``` The `find` command can be used to search the Chef Infra Server from the chef-shell. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') ``` You can also format the results with a code block. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } and nil ``` will return something similar to: ``` => ["ami-f8927a91", "ami-f8927a91", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1" # and more... ``` Or: ``` chef (preprod) > amis = nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } chef (preprod) > puts amis.uniq.sort ``` will return something similar to: ``` => ami-4b4ba522 ami-a89870c1 ami-eef61587 ami-f8927a91 ``` Examples -------- The following examples show how to use chef-shell. ### “Hello World” This example shows how to run chef-shell in standalone mode. (For chef-solo or Chef Infra Client modes, you would need to run chef-shell using the `-s` or `-z` command line options, and then take into consideration the necessary configuration settings.) When Chef Infra Client is installed using RubyGems or a package manager, chef-shell should already be installed. When Chef Infra Client is run from a git clone, it will be located in `chef/bin/chef shell`. To start chef-shell, just run it without any options. You’ll see the loading message, then the banner, and then the chef-shell prompt: ``` bin/chef-shell loading configuration: none (standalone session) Session type: standalone Loading.............done. Welcome to the chef-shell 15.8.23 For usage see https://docs.chef.io/chef_shell.html run `help' for help, `exit' or ^D to quit. chef (15.8.23)``` (Use the help command to print a list of supported commands.) Use the recipe_mode command to switch to recipe context: ``` chef > recipe_mode chef:recipe_mode ``` Typing is evaluated in the same context as recipes. Create a file resource: ``` chef:recipe_mode > file "/tmp/ohai2u_shef" => #< Chef::Resource::File:0x1b691ac @enclosing_provider=nil, @resource_name=:file, @before=nil, @supports={}, @backup=5, @allowed_actions=[:nothing, :create, :delete, :touch, :create_if_missing], @only_if=nil, @noop=nil, @collection=#< Chef::ResourceCollection:0x1b9926c @insert_after_idx=nil, @resources_by_name={"file[/tmp/ohai2u_shef]"=>0}, @resources=[#< Chef::Resource::File:0x1b691ac ...>]>, @updated=false, @provider=nil, @node=< Chef::Node:0xdeeaae @name="eigenstate.local">, @recipe_name=nil, @not_if=nil, @name="/tmp/ohai2u_shef", @action="create", @path="/tmp/ohai2u_shef", @source_line="/Users/username/ruby/chef/chef/(irb#1) line 1", @params={}, @actions={}, @cookbook_name=nil, @ignore_failure=false``` (The previous example was formatted for presentation.) At this point, chef-shell has created the resource and put it in the run-list, but not yet created the file. To initiate a Chef Infra Client run, use the `run_chef` command: ``` chef:recipe_mode > run_chef [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: Processing file[/tmp/ohai2u_shef] [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File [Fri, 15 Jan 2020 10:42:47 -0800] INFO: Creating file[/tmp/ohai2u_shef] at /tmp/ohai2u_shef => true ``` chef-shell can also switch to the same context as attribute files. Set an attribute with the following syntax: ``` chef:recipe_mode > attributes_mode chef:attributes > default[:hello] = "ohai2u-again" => "ohai2u-again" chef:attributes ``` Switch back to recipe_mode context and use the attributes: ``` chef:attributes > recipe_mode => :attributes chef:recipe_mode > file "/tmp/#{node.hello}" ``` Now, run Chef Infra Client again: ``` chef:recipe_mode > run_chef [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u_shef] [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u-again] [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u-again] using Chef::Provider::File [Fri, 15 Jan 2020 10:53:22 -0800] INFO: Creating file[/tmp/ohai2u-again] at /tmp/ohai2u-again => true chef:recipe_mode ``` Because the first resource (`file[/tmp/ohai2u_shef]`) is still in the run-list, it gets executed again. And because that file already exists, Chef Infra Client doesn’t attempt to re-create it. Finally, the files were created using the `ls` method: ``` chef:recipe_mode > ls("/tmp").grep(/ohai/) => ["ohai2u-again", "ohai2u_shef"] Shell Tutorial ``` ### Get Specific Nodes To get a list of nodes using a recipe named `postfix` use `search(:node,"recipe:postfix")`. To get a list of nodes using a sub-recipe named `delivery`, use chef-shell. For example: ``` search(:node, 'recipes:postfix\:\:delivery') ``` Note Single (' ‘) vs. double (" “) is important. This is because a backslash () needs to be included in the string, instead of having Ruby interpret it as an escape. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/chef_shell/Install Chef Workstation ======================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/install_workstation.md) Start your infrastructure automation quickly and easily with [Chef Workstation](workstation/index). Chef Workstation gives you everything you need to get started with Chef - ad hoc remote execution, remote scanning, configuration tasks, cookbook creation tools as well as robust dependency and testing software - all in one easy-to-install package. Chef Workstation includes: * Chef Infra Client * Chef InSpec * Chef Habitat * chef and knife command line tools * Testing tools such as Test Kitchen and Cookstyle * Everything else needed to author cookbooks and upload them to the Chef Infra Server Supported Platforms ------------------- Supported Host Operating Systems: | Platform | Version | | --- | --- | | Amazon Linux | 2 | | Apple macOS | 10.15, 11, 12 | | Microsoft Windows | 10, 11, Server 2012, Server 2012 R2, Server 2016, Server 2019, Server 2022 | | Red Hat Enterprise Linux / CentOS | 7.x, 8.x | | Ubuntu | 16.04, 18.04, 20.04 | | Debian | 9, 10, 11 | System Requirements ------------------- Minimum system requirements: * RAM: 4GB * Disk: 8GB * Additional memory and storage space may be necessary to take advantage of Chef Workstation tools such as Test Kitchen which creates and manages virtualized test environments. Additional Chef Workstation App Requirements: * On Linux you must have a graphical window manager running with support for system tray icons. For some distributions you may also need to install additional libraries. After you install the Chef Workstation package from the terminal, the post-install message will tell you which, if any, additional libraries are required to run the Chef Workstation App. Installation ------------ The Chef Workstation installer must run as a privileged user. Chef Workstation installs to `/opt/chef-workstation/` on macOS / Linux and `C:\opscode\chef-workstation\` on Windows. These file locations help avoid interference between these components and other applications that may be running on the target machine. ### macOS Install 1. Visit the [Chef Workstation downloads page](https://www.chef.io/downloads/tools/workstation?os=mac_os_x) and select the appropriate package for your macOS version. Select on the **Download** button. 2. Follow the steps to accept the license and install Chef Workstation. Alternately, install Chef Workstation using the [Homebrew](https://brew.sh/) package manager: `brew install --cask chef-workstation` ### Windows Install 1. Visit the [Chef Workstation downloads page](https://www.chef.io/downloads/tools/workstation?os=windows) and select the appropriate package for your Windows version. Click on the **Download** button. 2. Follow the steps to accept the license and install Chef Workstation. You will have the option to change your install location; by default the installer uses the `C:\opscode\chef-workstation\` directory. 3. **Optional:** Set the default shell. On Microsoft Windows it is strongly recommended to use Windows PowerShell instead of `cmd.exe`. Alternately, install Chef Workstation using the [Chocolatey](https://chocolatey.org/) package manager: `choco install chef-workstation` #### Headless Unattended Install “Headless” systems are configured to operate without a monitor (the “head”) keyboard, and mouse. They are usually administered remotely using protocols such as SSH or WinRM. Chef Workstation can be installed on a headless system using the `msiexec` command and flags to skip the installation of the Chef Workstation Application, which requires a GUI. Run the following command in Windows PowerShell or `cmd.exe`, replacing `MsiPath` with the path of the downloaded Chef Workstation installer. ``` msiexec /q /i MsiPath ADDLOCAL=ALL REMOVE=ChefWSApp ``` #### Spaces and Directories Directories that are used by Chef products on Windows cannot have spaces. For example, `C:\Users\User Name` will not work, but `C:\Users\UserName` will. Chef commands may fail if used against a directory with a space in its name. #### Top-level Directory Names Windows will throw errors when path name lengths are too long. For this reason, it’s often helpful to use a very short top-level directory, much like what is done in UNIX and Linux. For example, Chef uses `/opt/` to install Chef Workstation on macOS. A similar approach can be done on Microsoft Windows, by creating a top-level directory with a short name. For example: `C:\chef`. ### Linux 1. Visit the [Chef Workstation downloads page](https://www.chef.io/downloads/tools/workstation) and download the appropriate package for your distribution: * Red Hat Enterprise Linux ``` wget https://packages.chef.io/files/stable/chef-workstation/21.10.640/el/8/chef-workstation-21.10.640-1.el8.x86_64.rpm ``` * Debian/Ubuntu ``` wget https://packages.chef.io/files/stable/chef-workstation/21.10.640/ubuntu/20.04/chef-workstation_21.10.640-1_amd64.deb ``` 2. Use your distribution’s package manager to install Chef Workstation: * Red Hat Enterprise Linux: ``` yum localinstall chef-workstation-21.10.640-1.el8.x86_64.rpm ``` * Debian/Ubuntu: ``` dpkg -i chef-workstation_21.10.640-1_amd64.deb ``` Verify the Installation ----------------------- To verify the installation, run: ``` chef -v ``` Which returns the versions of all installed Chef tools: ``` Chef Workstation version: 21.10.640 Chef Infra Client version: 17.6.18 Chef InSpec version: 4.46.13 Chef CLI version: 5.4.2 Chef Habitat version: 1.6.351 Test Kitchen version: 3.1.0 Cookstyle version: 7.25.6 ``` Upgrading --------- To upgrade from ChefDK or an earlier release of Chef Workstation, follow the instructions provided under [Installing](workstation/install_workstation/index). Uninstalling ------------ ### Mac Uninstall Run `uninstall_chef_workstation` in your terminal. ### Windows Uninstall Use **Add / Remove Programs** to remove Chef Workstation. ### Linux Uninstall Ubuntu, Debian, and related: ``` sudo dpkg -P chef-workstation ``` Red Hat, CentOS, and related: ``` sudo yum remove chef-workstation ``` Next Steps ---------- Now that you’ve installed Chef Workstation, proceed to the [Setup](workstation/getting_started/index) guide to configure your Chef Workstation installation. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/install_dk.htmlchef-server-ctl (executable) ============================ [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/ctl_chef_server.md) The Chef Infra Server includes a command-line utility named chef-server-ctl. This command-line tool is used to start and stop individual services, reconfigure the Chef Infra Server, run chef-pedant, and then tail Chef Infra Server log files. Backup / Restore ---------------- Use the following commands to manage backups of Chef Infra Server data, and then to restore those backups. ### backup The `backup` subcommand is used to back up all Chef Infra Server data. This subcommand: * Requires rsync to be installed on the Chef Infra Server prior to running the command * Requires a `chef-server-ctl reconfigure` prior to running the command * Should not be run in a Chef Infra Server configuration with an external PostgreSQL database; [use knife ec backup](https://github.com/chef/knife-ec-backup) instead * Puts the initial backup in the `/var/opt/chef-backup` directory as a tar.gz file; move this backup to a new location for safe keeping **Options** This subcommand has the following options: `-y`, `--yes` Use to specify if the Chef Infra Server can go offline during tar.gz-based backups. `--pg-options` Use to specify and pass additional options PostgreSQL during backups. See the [PostgreSQL documentation](https://www.postgresql.org/docs/13/runtime-config.html) for more information. `-c`, `--config-only` Backup the Chef Infra Server configuration **without** backing up data. `-t`, `--timeout` Set the maximum amount of time in seconds to wait for shell commands (default 600). This option should be set to greater than 600 for backups taking longer than 10 minutes. `-h`, `--help` Show help message. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl backup ``` ### restore The `restore` subcommand is used to restore Chef Infra Server data from a backup that was created by the `backup` subcommand. This subcommand may also be used to add Chef Infra Server data to a newly-installed server. Do not run this command in a Chef Infra Server configuration that uses an external PostgreSQL database; [use knife ec backup](https://github.com/chef/knife-ec-backup) instead. This subcommand: * Requires rsync installed on the Chef Infra Server before running the command * Requires a `chef-server-ctl reconfigure` before running the command Ideally, the restore server will have the same FQDN as the server that you backed up. If the restore server has a different FQDN, then: 1. Replace the FQDN in the `/etc/opscode/chef-server.rb`. 2. Replace the FQDN in the `/etc/opscode/chef-server-running.json`. 3. Delete the old SSL certificate, key and `-ssl.conf` file from `/var/opt/opscode/nginx/ca`. 4. If you use a CA-issued certificate instead of a self-signed certificate, copy the CA-issued certificate and key into `/var/opt/opscode/nginx/ca`. 5. Update the `/etc/chef/client.rb` file on each client to point to the new server FQDN. 6. Run `chef-server-ctl reconfigure`. 7. Run ``chef-server-ctl restore`. **Options** This subcommand has the following options: `-c`, `--cleanse` Use to remove all existing data on the Chef Infra Server; it will be replaced by the data in the backup archive. `-d DIRECTORY`, `--staging-dir DIRECTORY` Use to specify that the path to an empty directory to be used during the restore process. This directory must have enough disk space to expand all data in the backup archive. `--pg-options` ``` : Use to specify and pass additional options PostgreSQL during backups. See the [PostgreSQL documentation](https://www.postgresql.org/docs/13/runtime-config.html) for more information. `-t`, `--timeout` : Set the maximum amount of time in seconds to wait for shell commands. Set to greater than 600 for backups that take longer than 10 minutes. Default: 600. `-h`, `--help` : Show help message. **Syntax** This subcommand has the following syntax: ```bash chef-server-ctl restore PATH_TO_BACKUP (options) ``` **Examples** ``` chef-server-ctl restore /path/to/tar/archive.tar.gz ``` cleanse ------- The `cleanse` subcommand is used to re-set the Chef Infra Server to the state it was in prior to the first time the `reconfigure` subcommand is run. This command will destroy all data, configuration files, and logs. The software that was put on-disk by the package installation will remain; re-run `chef-server-ctl reconfigure` to recreate the default data and configuration files. **Options** This subcommand has the following options: `--with-external` Use to specify that Chef Infra Server data on an external PostgreSQL database should be removed. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl cleanse ``` gather-logs ----------- The `gather-logs` subcommand is used to gather the Chef Infra Server log files into a tarball that contains all of the important log files and system information. This subcommand has the following syntax: ``` chef-server-ctl gather-logs ``` help ---- The `help` subcommand is used to print a list of all available chef-server-ctl commands. This subcommand has the following syntax: ``` chef-server-ctl help ``` install ------- The `install` subcommand is used to install premium features of the Chef Infra Server: Chef management console and Chef Infra Client run reporting, high availability configurations, and Chef Infra Server replication. Warning The `chef-server-ctl install` command no longer works in the 12.5 (and earlier) versions of the Chef Infra Server due to a change in how packages are downloaded from Chef. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl install name_of_addon (options) ``` where `name_of_addon` represents the command line value associated with the add-on or premium feature. **Options** This subcommand has the following options: `--path PATH` Use to specify the location of a package. This option is not required when packages are downloaded from <https://packages.chef.io/>. ### Use Downloads The `install` subcommand downloads packages from <https://packages.chef.io> by default. For systems that are not behind a firewall (and have connectivity to <https://packages.chef.io>), these packages can be installed as described below. 1. Install add-ons Install Chef Manage with: ``` sudo chef-server-ctl install chef-manage ``` 2. Reconfigure the server ``` sudo chef-server-ctl reconfigure ``` 3. Reconfigure add-ons Reconfigure Chef Manage with: ``` sudo chef-manage-ctl reconfigure ``` Finally, accept the [Chef License](chef_license/index): ``` sudo chef-manage-ctl reconfigure --accept-license ``` ### Use Local Packages Use the `install` subcommand with the `--path` option to install the Chef Manage (`chef-manage`) add-on for Chef Infra Server. ``` sudo chef-server-ctl install PACKAGE_NAME --path /path/to/package/directory ``` For example: ``` sudo chef-server-ctl install chef-manage --path /root/packages ``` The `chef-server-ctl` command will install the first `chef-manage` package found in the `/root/packages` directory. Key Rotation ------------ Use the following commands to manage public and private key rotation for users and clients. ### add-client-key Use the `add-client-key` subcommand to add a client key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl add-client-key ORG_NAME CLIENT_NAME [--public-key-path PATH] [--expiration-date DATE] [--key-name NAME] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `CLIENT_NAME` The name of the client that you wish to add a key for. `-e DATE` `--expiration-date DATE` An ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. For example: `2013-12-24T21:00:00Z`. If not passed, expiration will default to infinity. `-k NAME` `--key-name NAME` String defining the name of your new key for this client. If not passed, it will default to the fingerprint of the public key. `ORG_NAME` The short name for the organization to which the client belongs. `-p PATH` `--public-key-path PATH` The location to a file containing valid PKCS#1 public key to be added. If not passed, then the server will generate a new one for you and return the private key to STDOUT. ### add-user-key Use the `add-user-key` subcommand to add a user key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl add-user-key USER_NAME [--public-key-path PATH] [--expiration-date DATE] [--key-name NAME] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `-e DATE` `--expiration-date DATE` An ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. For example: `2013-12-24T21:00:00Z`. If not passed, expiration will default to infinity. `-k NAME` `--key-name NAME` String defining the name of your new key for this user. If not passed, it will default to the fingerprint of the public key. `-p PATH` `--public-key-path PATH` The location to a file containing valid PKCS#1 public key to be added. If not passed, then the server will generate a new one for you and return the private key to STDOUT. `USER_NAME` The user name for the user for which a key is added. ### delete-client-key Use the `delete-client-key` subcommand to delete a client key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl delete-client-key ORG_NAME CLIENT_NAME KEY_NAME ``` **Options** This subcommand has the following arguments: `ORG_NAME` The short name for the organization to which the client belongs. `CLIENT_NAME` The name of the client. `KEY_NAME` The unique name to be assigned to the key you wish to delete. ### delete-user-key Use the `delete-user-key` subcommand to delete a user key. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl delete-user-key USER_NAME KEY_NAME ``` Warning The parameters for this subcommand must be in the order specified above. **Options** This subcommand has the following arguments: `USER_NAME` The user name. `KEY_NAME` The unique name to be assigned to the key you wish to delete. ### list-client-keys Use the `list-client-keys` subcommand to list client keys. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl list-client-keys ORG_NAME CLIENT_NAME [--verbose] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `CLIENT_NAME` The name of the client. `ORG_NAME` The short name for the organization to which the client belongs. `--verbose` Use to show the full public key strings in command output. ### list-user-keys Use the `list-user-keys` subcommand to list client keys. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl list-user-keys USER_NAME [--verbose] ``` Warning All options for this subcommand must follow all arguments. **Options** This subcommand has the following options: `USER_NAME` The user name you wish to list keys for. `--verbose` Use to show the full public key strings in command output. **Example** To view a list of user keys (including public key output): ``` chef-server-ctl list-user-keys applejack --verbose ``` Returns: ``` 2 total key(s) found for user applejack key_name: test-key expires_at: Infinity public_key: -----BEGIN PUBLIC KEY----- <KEY> -----END PUBLIC KEY----- key_name: default expires_at: Infinity public_key: -----BEGIN PUBLIC KEY----- <KEY> -----END PUBLIC KEY----- ``` Secrets Management ------------------ Use the following commands to manage and rotate shared secrets and service credentials. The secrets file used for storing these is located at `/etc/opscode/private-chef-secrets.json` on your Chef Infra Server. It should be owned and readable only by `root`. ### set-secret The `set-secret` subcommand allows storing shared secrets and service credentials. Only secrets known to Chef Infra Server can be stored. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl set-secret GROUP NAME ``` There are various ways to pass the secret to this command: 1. as a third argument: ``` chef-server-ctl set-secret ldap bind_password secretpassword ``` 2. via an environment variable: ``` export LDAP.BIND_PASSWORD="secretpassword" chef-server-ctl set-secret ldap bind_password ``` 3. via an interactive prompt: ``` chef-server-ctl set-secret ldap bind_password Enter ldap bind_password: (no terminal output) Re-enter ldap bind_password: (no terminal output) ``` **Options** This subcommand has the following options: `--with-restart` If any services depend on the secret being changed, attempt to restart them after changing the secret. Added in Chef Infra Server 12.16.2. ### remove-secret The `remove-secret` subcommand allows removing a stored shared secret and service credential. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl remove-secret GROUP NAME ``` **Example** ``` chef-server-ctl remove-secret ldap bind_password ``` ### show-secret The `show-secret` subcommand allows viewing a stored shared secret and service credential. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl show-secret GROUP NAME ``` ### set-db-superuser-password The `set-db-superuser-password` subcommand allows storing the database superuser password. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl set-db-superuser-password ``` Similar to `set-secret`, the superuser password can also be provided via the environment variable `DB_PASSWORD`. ### set-actions-password The `set-actions-password` subcommand allows storing the RabbitMQ Actions password. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl set-actions-password ``` Similar to `set-secret`, the action password can also be provided via the environment variable `ACTIONS_PASSWORD`. ### oc-id-show-app The `oc-id-show-app` subcommand allows for retrieving the client ID and client secret for applications known to **oc-id**. Note that with `insecure_addon_compat` [disabled](server/server_security/index#chef-infra-server-credentials-management), this data will no longer be written to `/etc/opscode/oc-id-applications/APP.json`. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl oc-id-show-app APP ``` **Example** ``` chef-server-ctl oc-id-show-app supermarket { "name": "supermarket", "uid": "0bad0f2eb04e935718e081fb71asdfec3681c81acb9968a8e1e32451d08b", "secret": "17cf1141cc971a10ce307611beda7ffadstr4f1bc98d9f9ca76b9b127879", "redirect_uri": "https://supermarket.mycompany.com/auth/chef_oauth2/callback" } ``` ### require-credential-rotation The `require-credential-rotation` subcommand takes the Chef Infra Server offline and requires a complete service credential rotation before the Chef Infra Server(s) in your cluster can restart again. Run `rotate-shared-secrets` to create a new shared secret, salt, and generate the new service credentials. Then copy the secrets file to each Chef Infra Server and run `sudo chef-server-ctl reconfigure` on each server to complete the rotation process. Note Credential rotation does not rotate the pivotal, user, or client keys, or remove any Chef Infra Server policy or cookbooks that have been uploaded. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl require-credential-rotation (options) ``` **Options** This subcommand has the following options: `-y, --yes` Bypass a prompt in the terminal and agree that you want to disable the Chef Infra Server, and require credential rotation. ### rotate-all-credentials The `rotate-all-credentials` subcommand generates new credential values for all service credentials by incrementing the credential version number and creating a new hash value. You can choose whether to copy the updated secrets file to each node in the cluster and reconfiguring or by running this subcommand on all the nodes. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl rotate-all-credentials ``` ### rotate-credentials The `rotate-credentials` subcommand generates new credential values for all credentials for a given service by incrementing the value and creating a new hash value. You can choose whether to copy the updated secrets file to each node in the cluster and reconfiguring or by running this subcommand for that specific service on all the nodes. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl rotate-credentials SERVICE_NAME ``` ### rotate-shared-secrets The `rotate-shared-secrets` subcommand creates a new shared secret and salt, in addition to generating new service credentials. It also resets the `credential_version` number for the services to 0. After you have run this subcommand, a new shared secret has been created, so you must copy the secrets file to each Chef Infra Server and run `sudo chef-server-ctl reconfigure` on them to complete the rotation process. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl rotate-shared-secrets ``` ### show-service-credentials The `show-service-credentials` subcommand shows all of the service credentials for services running on the local Chef Infra Server. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl show-service-credentials ``` ### cleanup-bifrost The `cleanup-bifrost` subcommand removes unused authorization objects from the authorization database (called bifrost). These unused objects can accumulate on long-running Chef Infra Servers as a result of failed object creation requests. For most users, the unused authorization objects do not substantially affect the performance of Chef Infra Server; however in certain situations it can be helpful to clean them up. This command is primarily intended for use by Chef support. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl cleanup-bifrost OPTIONS ``` **Options** This subcommand has the following options: `--estimate-only` Provides an estimate of the number of unused objects that will be deleted, without deleting anything. `--wait-time SECONDS` The number of seconds to wait for in-flight requests to complete. Only decrease this value if you are running the command when the Chef Infra Server is not taking requests. `--force-cleanup` Removes internal tracking tables used during the cleanup process. Manual cleanup of these tables is only required if the cleanup command is killed unexpectedly. `--batch-size` The number of orphaned authorization actors to delete at a time. Manage Organizations -------------------- Use the `org-create`, `org-delete`, `org-list`, `org-show`, `org-user-add` and `org-user-remove` commands to manage organizations. ### org-create The `org-create` subcommand is used to create an organization. (The validation key for the organization is returned to `STDOUT` when creating an organization with this command.) **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-create ORG_NAME "ORG_FULL_NAME" (options) ``` where: * The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. * The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `"Chef Software, Inc."`. **Options** This subcommand has the following options: `-a USER_NAME`, `--association_user USER_NAME` Associate a user with an organization and add them to the `admins` and `billing_admins` security groups. `-f FILE_NAME`, `--filename FILE_NAME` Write the ORGANIZATION-validator.pem to `FILE_NAME` instead of printing it to `STDOUT`. **Examples** ``` chef-server-ctl org-create prod Production ``` ``` chef-server-ctl org-create staging Staging -a chef-admin ``` ``` chef-server-ctl org-create dev Development -f /tmp/id-dev.key ``` ``` chef-server-ctl org-create dev Development --association_user grantmc ``` ### org-delete The `org-delete` subcommand is used to delete an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-delete ORG_NAME ``` **Examples** ``` chef-server-ctl org-delete infra-testing-20140909 ``` ``` chef-server-ctl org-delete pedant-testing-org ``` ### org-list The `org-list` subcommand is used to list all of the organizations currently present on the Chef Infra Server. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-list (options) ``` **Options** This subcommand has the following options: `-a`, `--all-orgs` Show all organizations. `-w`, `--with-uri` Show the corresponding URIs. ### org-show The `org-show` subcommand is used to show the details for an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-show ORG_NAME ``` ### org-user-add The `org-user-add` subcommand is used to add a user to an organization. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-user-add ORG_NAME USER_NAME (options) ``` **Options** This subcommand has the following options: `--admin` Add the user to the `admins` group. **Examples** ``` chef-server-ctl org-user-add prod john_smith ``` ``` chef-server-ctl org-user-add preprod testmaster ``` ``` chef-server-ctl org-user-add dev grantmc --admin ``` ### org-user-remove The `org-user-remove` subcommand is used to remove a user from an organization. Warning A user who belongs to the `admins` group must be removed from the group before they may be removed from an organization. To remove a user from the `admins` group, run the following: ``` EDITOR=vi knife edit /groups/admins.json ``` make the required changes, and then save the file. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl org-user-remove ORG_NAME USER_NAME (options) ``` **Options** This subcommand has the following options: `--force` Force the removal of a user from the organization’s `admins` and `billing-admins` groups. **Examples** ``` chef-server-ctl org-user-remove prod john_smith ``` ``` chef-server-ctl org-user-remove prod testmaster ``` ``` chef-server-ctl org-user-remove grantmc --force ``` password -------- The `password` subcommand is used to change a user’s password. When Active Directory or LDAP is enabled, this command enables (or disables) the system recovery password for that user. For example: This subcommand has the following syntax: ``` chef-server-ctl password USERNAME ``` This subcommand has the following options: `--disable` Use this option to disable a user’s system recovery password. **Examples** For example, to change a user’s password, enter: ``` chef-server-ctl password adamjacobs ``` and then enter the password and confirm it: ``` Enter the new password: ****** Enter the new password again: ****** ``` to return: ``` Password for adamjacobs successfully set. ``` To disable a system recovery password: ``` chef-server-ctl password adamjacobs --disable ``` to return: ``` Password for adamjacobs successfully disabled for System Recovery. ``` psql ---- The `psql` subcommand is used to log into the PostgreSQL database associated with the named service. This subcommand: * Uses `psql` (the interactive terminal for PostgreSQL) * Has read-only access by default * Is the recommended way to interact with any PostgreSQL database that is part of the Chef Infra Server * Automatically handles authentication **Syntax** This subcommand has the following syntax: ``` chef-server-ctl psql SERVICE_NAME (options) ``` **Options** This subcommand has the following options: `--write` Use to enable write access to the PostgreSQL database. reconfigure ----------- The `reconfigure` subcommand is used when changes are made to the chef-server.rb file to reconfigure the server. When changes are made to the chef-server.rb file, they will not be applied to the Chef Infra Server configuration until after this command is run. This subcommand will also restart any services for which the `service_name['enabled']` setting is set to `true`. This subcommand has the following syntax: ``` chef-server-ctl reconfigure ``` reindex ------- The `reindex` subcommand is used to reload Chef Infra Server data from PostgreSQL to Elasticsearch. This subcommand has the following syntax: ``` chef-server-ctl reindex ``` Note Chef Infra Server versions earlier than 14.5 configured with `nginx['enable_non_ssl'] = false` and `fips = true` require `export CSC_LB_URL=https://127.0.0.1` to run the command `chef-server-ctl reindex <options>` **Options** This subcommand has the following options: `-a`, `--all-orgs` Use to reindex all organizations on the Chef Infra Server. This option will override any organization specified as part of the command, i.e. `chef-server-ctl reindex ORG_NAME -a` will reindex all organizations and not just the specified organization. `-d`, `--disable-api` Use to disable the Chef Infra Server API to prevent writes during reindexing. `-t`, `--with-timing` Use to print timing information for the reindex processes. `-w`, `--wait` Use to wait for the reindexing queue to clear before exiting. This option only works when run on a standalone Chef Infra Server or on a primary backend Chef server within a legacy tier. Server Admins ------------- The `server-admins` group is a global group that grants its members permission to create, read, update, and delete user accounts, with the exception of superuser accounts. The `server-admins` group is useful for users who are responsible for day-to-day administration of the Chef Infra Server, especially user management via the `knife user` subcommand. Before members can be added to the `server-admins` group, they must already have a user account on the Chef Infra Server. ### Scenario The following user accounts exist on the Chef Infra Server: `pivotal` (a superuser account), `alice`, `bob`, `carol`, and `dan`. Run the following command to view a list of users on the Chef Infra Server: ``` chef-server-ctl user-list ``` and it returns the same list of users: ``` pivotal alice bob carol dan ``` Alice is a member of the IT team whose responsibilities include day-to-day administration of the Chef Infra Server, in particular managing the user accounts on the Chef Infra Server that are used by the rest of the organization. From a workstation, Alice runs the following command: ``` knife user list -c ~/.chef/alice.rb ``` and it returns the following error: ``` ERROR: You authenticated successfully to <chef_server_url> as alice but you are not authorized for this action Response: Missing read permission ``` Alice is not a superuser and does not have permissions on other users because user accounts are global to organizations in the Chef Infra Server. Let’s add Alice to the `server-admins` group: ``` chef-server-ctl grant-server-admin-permissions alice ``` and it returns the following response: ``` User alice was added to server-admins. ``` Alice can now create, read, update, and delete user accounts on the Chef Infra Server, even for organizations to which Alice is not a member. From a workstation, Alice re-runs the following command: ``` knife user list -c ~/.chef/alice.rb ``` which now returns: ``` pivotal alice bob carol dan ``` Alice is now a server administrator and can use the following knife subcommands to manage users on the Chef Infra Server: * `knife user-create` * `knife user-delete` * `knife user-edit` * `knife user-list` * `knife user-show` For example, Alice runs the following command: ``` knife user edit carol -c ~/.chef/alice.rb ``` and the $EDITOR opens in which Alice makes changes, and then saves them. #### Superuser Accounts Superuser accounts may not be managed by users who belong to the `server-admins` group. For example, Alice attempts to delete the `pivotal` superuser account: ``` knife user delete pivotal -c ~/.chef/alice.rb ``` and the following error is returned: ``` ERROR: You authenticated successfully to <chef_server_url> as user1 but you are not authorized for this action Response: Missing read permission ``` Alice’s action is unauthorized even with membership in the `server-admins` group. ### Manage server-admins Group Membership of the `server-admins` group is managed with a set of `chef-server-ctl` subcommands: * `chef-server-ctl grant-server-admin-permissions` * `chef-server-ctl list-server-admins` * `chef-server-ctl remove-server-admin-permissions` #### Add Members The `grant-server-admin-permissions` subcommand is used to add a user to the `server-admins` group. Run the command once per user added. This subcommand has the following syntax: ``` chef-server-ctl grant-server-admin-permissions USER_NAME ``` where `USER_NAME` is the user to add to the list of server administrators. For example: ``` chef-server-ctl grant-server-admin-permissions bob ``` returns: ``` User bob was added to server-admins. This user can now list, read, and create users (even for orgs they are not members of) for this Chef Infra Server. ``` #### Remove Members The `remove-server-admin-permissions` subcommand is used to remove a user from the `server-admins` group. Run the command once per user removed. This subcommand has the following syntax: ``` chef-server-ctl remove-server-admin-permissions USER_NAME ``` where `USER_NAME` is the user to remove from the list of server administrators. For example: ``` chef-server-ctl remove-server-admin-permissions bob ``` returns: ``` User bob was removed from server-admins. This user can no longer list, read, and create users for this Chef Infra Server except for where they have default permissions (such as within an org). ``` #### List Membership The `list-server-admins` subcommand is used to return a list of users who are members of the `server-admins` group. This subcommand has the following syntax: ``` chef-server-ctl list-server-admins ``` and will return a list of users similar to: ``` pivotal alice bob carol dan ``` show-config ----------- The `show-config` subcommand is used to view the configuration that will be generated by the `reconfigure` subcommand. This command is most useful in the early stages of a deployment to ensure that everything is built properly prior to installation. This subcommand has the following syntax: ``` chef-server-ctl show-config ``` uninstall --------- The `uninstall` subcommand is used to remove the Chef Infra Server application, but without removing any of the data. This subcommand will shut down all services (including the `runit` process supervisor). This subcommand has the following syntax: ``` chef-server-ctl uninstall ``` Note To revert the `uninstall` subcommand, run the `reconfigure` subcommand (because the `start` subcommand is disabled by the `uninstall` command). upgrade ------- The `upgrade` subcommand is used to upgrade the Chef Infra Server. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl upgrade (options) ``` **Options** This subcommand has the following options: `-d DIRECTORY`, `--chef11-data-dir DIRECTORY` The directory in which Chef Infra Server 11 data is located. Default value: a temporary directory. `-e DIRECTORY`, `--chef12-data-dir DIRECTORY` The directory in which Chef Infra Server 12 data is located. Default value: a temporary directory. `-f FULL_NAME`, `--full-org-name FULL_NAME` The full name of the Chef Infra Server organization. The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `Chef Software, Inc.`. If this option is not specified, the `upgrade` command will prompt for it. `-h`, `--help` Use to show help for the `chef-server-ctl upgrade` subcommand. `-k KEY_PATH`, `--key KEY_PATH` The Chef Infra Server 11 `admin.pem` key for the API client. This is the key used to download Chef Infra Server 11 data. Default value: `/etc/chef-server/admin.pem`. `-o ORG_NAME`, `--org-name ORG_NAME` The name of the Chef Infra Server organization. The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. If this option is not specified, the `upgrade` command will prompt for it. `-s URL`, `--chef11-server-url URL` The URL for the Chef Infra Server version 11. Default value: `https://localhost`. `-t NUMBER`, `--upload-threads NUMBER` The number of threads to use when migrating cookbooks. Default value: `10`. `-u USER`, `--user` Create a client as an admin client. This is required for any user to access Chef as an administrator. `-x URL`, `--chef12-server-url URL` The URL for the Chef Infra Server, version 12. Default value: `https://localhost`. `-y`, `--yes` Use to skip confirmation prompts during the upgrade process. User Management --------------- Use the `user-create`, `user-delete`, `user-edit`, `user-list` and `user-show` subcommands to manage users. ### user-create The `user-create` subcommand is used to create a user. (The validation key for the organization may be returned to `STDOUT` when creating a user with this command.) **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-create USER_NAME FIRST_NAME [MIDDLE_NAME] LAST_NAME EMAIL 'PASSWORD' (options) ``` **Options** This subcommand has the following options: `-f FILE_NAME`, `--filename FILE_NAME` Write the USER.pem to a file instead of `STDOUT`. **Examples** ``` chef-server-ctl user-create john_smith <NAME> <EMAIL> p@s5w0rD! ``` ``` chef-server-ctl user-create jane_doe <NAME> <EMAIL> p@s5w0rD! -f /tmp/jane_doe.key ``` ``` chef-server-ctl user-create waldendude <NAME> <EMAIL> excursions ``` ### user-delete The `user-delete` subcommand is used to delete a user. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-delete USER_NAME ``` **Examples** ``` chef-server-ctl user-delete john_smith ``` ``` chef-server-ctl user-delete jane_doe ``` **Options** This subcommand has the following options: `-R`, `--remove-from-admin-groups` Removes a user who is in one or more ‘admin’ groups unless that user is the only member of the ‘admin’ group(s). ### user-edit The `user-edit` subcommand is used to edit the details for a user. The data will be made available in the $EDITOR for editing. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-edit USER_NAME ``` **Examples** ``` chef-server-ctl user-edit john_smith ``` ``` chef-server-ctl user-edit jane_doe ``` ### user-list The `user-list` subcommand is used to view a list of users. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-list (options) ``` **Options** This subcommand has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### user-show The `user-show` subcommand is used to show the details for a user. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl user-show USER_NAME (options) ``` **Options** This subcommand has the following options: `-l`, `--with-orgs` Show all organizations. Service Subcommands ------------------- This command has a built in process supervisor that ensures all of the required services are in the appropriate state at any given time. The supervisor starts two processes per service and provides the following subcommands for managing services: `hup`, `int`, `kill`, `once`, `restart`, `service-list`, `start`, `status`, `stop`, `tail`, and `term`. Warning The following commands are disabled when an external PostgreSQL database is configured for the Chef Infra Server: `hup`, `int`, `kill`, `once`, `restart`, `start`, `stop`, `tail`, and `term`. ### hup The `hup` subcommand is used to send a `SIGHUP` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl hup SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### int The `int` subcommand is used to send a `SIGINT` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl int SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### kill The `kill` subcommand is used to send a `SIGKILL` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl kill SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### once The supervisor for the Chef Infra Server is configured to restart any service that fails, unless that service has been asked to change its state. The `once` subcommand is used to tell the supervisor to not attempt to restart any service that fails. This command is useful when troubleshooting configuration errors that prevent a service from starting. Run the `once` subcommand followed by the `status` subcommand to look for services in a down state and/or to identify which services are in trouble. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl once SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### restart The `restart` subcommand is used to restart all services enabled on the Chef Infra Server or to restart an individual service by specifying the name of that service in the command. Warning When running the Chef Infra Server in a high availability configuration, restarting all services may trigger failover. This subcommand has the following syntax: ``` chef-server-ctl restart SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully restarted the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` ### service-list The `service-list` subcommand is used to display a list of all available services. A service that is enabled is labeled with an asterisk (*). This subcommand has the following syntax: ``` chef-server-ctl service-list ``` ### start The `start` subcommand is used to start all services that are enabled in the Chef Infra Server. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl start SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully started the output should be similar to: ``` ok: run: service_name: (pid 12345) 1s ``` The supervisor for the Chef Infra Server is configured to wait seven seconds for a service to respond to a command from the supervisor. If you see output that references a timeout, it means that a signal has been sent to the process, but that the process has yet to actually comply. In general, processes that have timed out are not a big concern, unless they are failing to respond to the signals at all. If a process is not responding, use a command like the `kill` subcommand to stop the process, investigate the cause (if required), and then use the `start` subcommand to re-enable it. ### status The `status` subcommand is used to show the status of all services available to the Chef Infra Server. The results will vary based on the configuration of a given server. This subcommand has the following syntax: ``` chef-server-ctl status ``` and will return the status for all services. Status can be returned for individual services by specifying the name of the service as part of the command: ``` chef-server-ctl status SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When service status is requested, the output should be similar to: ``` run: service_name: (pid 12345) 12345s; run: log: (pid 1234) 67890s ``` where * `run:` is the state of the service (`run:` or `down:`) * `service_name:` is the name of the service for which status is returned * `(pid 12345)` is the process identifier * `12345s` is the uptime of the service, in seconds For example: ``` down: opscode-erchef: (pid 35546) 10s ``` By default, runit will restart services automatically when the services fail. Therefore, runit may report the status of a service as `run:` even when there is an issue with that service. When investigating why a particular service is not running as it should be, look for the services with the shortest uptimes. For example, the list below indicates that the **opscode-erchef** should be investigated further: ``` run: oc-id run: opscode-chef: (pid 4327) 13671s; run: log: (pid 4326) 13671s run: opscode-erchef: (pid 5383) 5s; run: log: (pid 4382) 13669s ``` #### Log Files A typical status line for a service that is running any of the Chef Infra Server front-end services is similar to the following: ``` run: name_of_service: (pid 1486) 7819s; run: log: (pid 1485) 7819s ``` where: * `run` describes the state in which the supervisor attempts to keep processes. This state is either `run` or `down`. If a service is in a `down` state, it should be stopped * `name_of_service` is the service name, for example: `opscode-erchef` * `(pid 1486) 7819s;` is the process identifier followed by the amount of time (in seconds) the service has been running * `run: log: (pid 1485) 7819s` is the log process. It is typical for a log process to have a longer run time than a service; this is because the supervisor does not need to restart the log process in order to connect the supervised process If the service is down, the status line will appear similar to the following: ``` down: opscode-erchef: 3s, normally up; run: log: (pid 1485) 8526s ``` where * `down` indicates that the service is in a down state * `3s, normally up;` indicates that the service is normally in a run state and that the supervisor would attempt to restart this service after a reboot ### stop The `stop` subcommand is used to stop all services enabled on the Chef Infra Server. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl stop SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. When a service is successfully stopped the output should be similar to: ``` ok: down: service_name: 0s, normally up ``` For example: ``` chef-server-ctl stop ``` will return something similar to: ``` ok: down: nginx: 393s, normally up ok: down: opscode-chef: 391s, normally up ok: down: opscode-erchef: 391s, normally up ok: down: opscode-solr4: 389s, normally up ok: down: postgresql: 388s, normally up ok: down: redis_lb: 387s, normally up ``` ### tail The `tail` subcommand is used to follow all of the Chef Infra Server logs for all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl tail SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. ### term The `term` subcommand is used to send a `SIGTERM` to all services. This command can also be run for an individual service by specifying the name of the service in the command. This subcommand has the following syntax: ``` chef-server-ctl term SERVICE_NAME ``` where `SERVICE_NAME` represents the name of any service that is listed after running the `service-list` subcommand. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/ctl_chef_server.htmlBlockGuardWithOnlyString ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/BlockGuardWithOnlyString` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | A resource guard (not_if/only_if) that is a string should not be wrapped in `{}`. Wrapping a guard string in {} causes it to be executed as Ruby code which will always return true instead of a shell command that will actually run. ### Examples #### incorrect ``` template '/etc/foo' do mode '0644' source 'foo.erb' only_if { 'test -f /etc/foo' } end ``` #### correct ``` template '/etc/foo' do mode '0644' source 'foo.erb' only_if 'test -f /etc/foo' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_blockguardwithonlystring/ConditionalRubyShellout ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/ConditionalRubyShellout` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Don’t use Ruby to shellout in a `only_if` / `not_if` conditional. Any string value used in an `only_if` / `not_if` is executed in your system’s shell and the return code of the command is the result for the `not_if` / `only_if` determination. ### Examples #### incorrect ``` cookbook_file '/logs/foo/error.log' do source 'error.log' only_if { system('wget https://www.bar.com/foobar.txt -O /dev/null') } end cookbook_file '/logs/foo/error.log' do source 'error.log' only_if { shell_out('wget https://www.bar.com/foobar.txt -O /dev/null').exitstatus == 0 } end ``` #### correct ``` cookbook_file '/logs/foo/error.log' do source 'error.log' only_if 'wget https://www.bar.com/foobar.txt -O /dev/null' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.1.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_conditionalrubyshellout/ChefApplicationFatal ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/ChefApplicationFatal` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use `raise` to force Chef Infra Client to fail instead of using `Chef::Application.fatal`, which masks the full stack trace of the failure and makes debugging difficult. ### Examples #### incorrect ``` Chef::Application.fatal!('Something horrible happened!') ``` #### correct ``` raise "Something horrible happened!" ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.0.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_chefapplicationfatal/CookbookUsesNodeSave ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/CookbookUsesNodeSave` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Don’t use node.save to save partial node data to the Chef Infra Server mid-run unless it’s a requirement of cookbook design that can’t be avoided. Node.save can result in failed Chef Infra runs appearing in search and increases load on the Chef Infra Server." ### Examples #### incorrect ``` node.save ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_cookbookusesnodesave/DnfPackageAllowDowngrades ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/DnfPackageAllowDowngrades` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The `dnf_package` resource does not support the `allow_downgrades` property. ### Examples #### incorrect ``` dnf_package 'nginx' do version '1.2.3' allow_downgrades true end ``` #### correct ``` dnf_package 'nginx' do version '1.2.3' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_dnfpackageallowdowngrades/InvalidCookbookName =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidCookbookName` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Cookbook names should not contain invalid characters such as periods. ### Examples #### incorrect ``` name 'foo.bar' ``` #### correct ``` name 'foo_bar' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.27 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invalidcookbookname/IncorrectLibraryInjection ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/IncorrectLibraryInjection` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Libraries should be injected into the `Chef::DSL::Recipe` class and not `Chef::Recipe` or `Chef::Provider` classes directly. ### Examples #### incorrect ``` ::Chef::Recipe.send(:include, Filebeat::Helpers) ::Chef::Provider.send(:include, Filebeat::Helpers) ::Chef::Recipe.include Filebeat::Helpers ::Chef::Provider.include Filebeat::Helpers ``` #### correct ``` ::Chef::DSL::Recipe.send(:include, Filebeat::Helpers) # covers previous Recipe & Provider classes ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.10.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_incorrectlibraryinjection/Chef Infra Server API ===================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/api_chef_server.md) The Chef Infra Server API is a REST API that provides access to objects on the Chef Infra Server, including nodes, environments, roles, users, organizations, cookbooks (and cookbook versions), and is used to manage an API client list and the associated RSA public key-pairs. Requirements ------------ The Chef Infra Server API has the following requirements: * The `Accept` header must be set to `application/json`. * For `PUT` and `POST` requests, the `Content-Type` header must be set to `application/json`. * The `X-Chef-Version` header must be set to the version of the Chef Infra Server API that is being used. * A request must be signed by adding authentication headers. ‘Mixlib::Authentication’ may be used to sign requests. * A request must be well-formatted. The easiest way to ensure a well-formatted request is to use the `Chef::ServerAPI` library. Authentication Headers ---------------------- Authentication to the Chef Infra Server requires a specific set of HTTP headers signed using a private key that is associated with the client making the request. The request is authorized if the Chef Infra Server can verify the signature using the public key. Only authorized actions are allowed. Note Most authentication requests made to the Chef Infra Server are abstracted from the user. Such as when using knife or the Chef Infra Server user interface. In some cases, such as when using the `knife exec` subcommand, the authentication requests need to be made more explicitly, but still in a way that does not require authentication headers. In a few cases, such as when using arbitrary Ruby code, a Chef Infra Server API client, or cURL, it may be necessary to include the full authentication header as part of the request to the Chef Infra Server. ### Required Headers The following authentication headers are required: | Feature | Description | | --- | --- | | `Accept` | The format in which response data from the Chef Infra Server is provided. This header must be set to `application/json`. | | `Content-Type` | The format in which data is sent to the Chef Infra Server. This header is required for `PUT` and `POST` requests and must be set to `application/json`. | | `Host` | The host name (and port number) to which a request is sent. (Port number `80` does not need to be specified.) For example: `api.chef.io` (which is the same as `api.chef.io:80`) or `api.chef.io:443`. | | `Method` | The method from the request. | | `Path` | Omit for Authentication Version 1. Specify for Authentication Version 1.3 | | `X-Chef-Version` | The version of the Chef Infra Client executable from which a request is made. This header ensures that responses are in the correct format. For example: `12.0.2` or `11.16.x`. | | `X-Ops-Authorization-N` | One (or more) 60 character segments that comprise the canonical header. A canonical header is signed with the private key used by the client machine from which the request is sent, and is also encoded using Base64. If more than one segment is required, each should be named sequentially, e.g. `X-Ops-Authorization-1`, `X-Ops-Authorization-2`, `X-Ops-Authorization-N`, where `N` represents the integer used by the last header that is part of the request. | | `X-Ops-Content-Hash` | For API Version 1. The result of the SHA-1 hash of the request body encoded using Base64. Base64 encoding should have line breaks every 60 characters. For API Version 1.3. The result of the SHA-256 hash of the request body encoded using Base64. Base64 encoding should have line breaks every 60 characters. | | `X-Ops-Server-API-Version` | Use `X-Ops-Server-API-Version` to specify the version of the Chef Infra Server API. For example: `X-Ops-Server-API-Version: 1`. `X-Ops-Server-API-Version: 0` is supported for use with Chef Infra Server version 12, but will be deprecated as part of the next major release. | | `X-Ops-Sign` | Set this header to the following value: `algorithm=sha1,version=1.0` or `version=1.3`. | | `X-Ops-Timestamp` | The timestamp, in ISO-8601 format and with UTC indicated by a trailing `Z` and separated by the character `T`. For example: `2013-03-10T14:14:44Z`. | | `X-Ops-UserId` | The name of the API client whose private key will be used to create the authorization header. | Note Use `X-Ops-Server-API-Info` to identify the version of the Chef Infra Server API. #### Canonical Header Format 1.0 using SHA-1 The signed headers are encrypted using the OpenSSL RSA_private_encrypt method and encoded in Base64. The signed headers are used to create one or more X-Ops-Authorization-N headers of 60 character segments. The canonical header should be created by concatenating the following headers, encrypting and encoding: ``` Method:HTTP_METHOD Hashed Path:HASHED_PATH X-Ops-Content-Hash:HASHED_BODY X-Ops-Timestamp:TIME X-Ops-UserId:USERID ``` where: * `HTTP_METHOD` is the method used in the API request (`GET`, `POST`, and so on) * `HASHED_PATH` is the path of the request: `/organizations/NAME/name_of_endpoint`. The `HASHED_PATH` must be hashed using SHA-1 and encoded using Base64, must not have repeated forward slashes (`/`), must not end in a forward slash (unless the path is `/`), and must not include a query string. * `X-Ops-Content-Hash` is the Base64 encoded SHA256 hash of the json body of the request. * `X-Ops-Timestamp` UTC time in RFC3339 format. * `X-Ops-UserId` is the plain text client or user name. The Chef Infra Server decrypts this header and ensures its content matches the content of the non-encrypted headers that were in the request. The timestamp of the message is checked to ensure the request was received within a reasonable amount of time. One approach generating the signed headers is to use [mixlib-authentication](https://github.com/chef/mixlib-authentication), which is a class-based header signing authentication object similar to the one used by Chef Infra Client. ##### Example The following example shows an authentication request: ``` GET /organizations/NAME/nodes HTTP/1.1 Accept: application/json Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3 Host: api.chef.io:443 User-Agent: Chef Knife/12.0.2 (ruby-2.1.1-p320; ohai-8.0.0; x86_64-darwin12.0.2; +http://chef.io) X-Chef-Version: 12.0.2 X-Ops-Authorization-1: BE3NnBritishaf3ifuwLSPCCYasdfXaRN5oZb4c6hbW0aefI X-Ops-Authorization-2: sL4j1qtEZzi/2WeF67UuytdsdfgbOc5CjgECQwqrym9gCUON X-Ops-Authorization-3: yf0p7PrLRCNasdfaHhQ2LWSea+kTcu0dkasdfvaTghfCDC57 X-Ops-Authorization-4: 155i+ZlthfasfasdffukusbIUGBKUYFjhbvcds3k0i0gqs+V X-Ops-Authorization-5: /sLcR7JjQky7sdafIHNfsBQrISktNPower1236hbFIayFBx3 X-Ops-Authorization-6: nodilAGMb166@haC/fttwlWQ2N1LasdqqGomRedtyhSqXA== X-Ops-Content-Hash: 2jmj7l5rfasfgSw0ygaVb/vlWAghYkK/YBwk= X-Ops-Server-API-Info: 1 X-Ops-Sign: algorithm=sha1;version=1.0; X-Ops-Userid: user_id X-Ops-Timestamp: 2014-12-12T17:13:28Z ``` #### Canonical Header Format 1.3 using SHA-256 Chef Infra Server versions 12.4.0 and above support signing protocol version 1.3, which adds support for SHA-256 algorithms. It can be enabled on Chef Infra Client via the `client.rb` file: ``` authentication_protocol_version = '1.3' ``` And for Chef’s knife CLI via `config.rb`: ``` knife[:authentication_protocol_version] = '1.3' ``` To create the signed headers for direct use. Gather the following headers in the order listed, convert the signature headers to a concatenated string, sign and Base64 encode the result. The concatenation of signature headers is signed using the client RSA private key, with SHA-256 hashing and PKCS1v15 padding. Chop the Base64 encoded value into 60 character chunks and create X-Ops-Authorization-N headers with the chunks. ``` Method:HTTP_METHOD Path:PATH X-Ops-Content-Hash:HASHED_BODY X-Ops-Sign X-Ops-Timestamp:TIME X-Ops-UserId:USERID X-Ops-Server-API-Version ``` where: * `HTTP_METHOD` is the method used in the API request (`GET`, `POST`, &mldr;) * `PATH` is the path of the request: `/organizations/NAME/name_of_endpoint`. The value must not have repeated forward slashes (`/`), must not end in a forward slash (unless the path is `/`), and must not include a query string. * `X-Ops-Content-Hash` is the Base64 encoded SHA256 hash of the json body of the request. * `X-Ops-Sign` has the value “version=1.3”. * `X-Ops-Timestamp` UTC time in RFC3339 format. * `X-Ops-UserId` is the plain text client or user name. * `X-Ops-Server-API-Version` is the numeric value of the Chef Infra Server API. ##### Example The following example shows an authentication request: ``` GET /organizations/NAME/nodes HTTP/1.1 Accept: application/json Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3 Host: api.chef.io:443 Method: GET Path: /organizations/NAME/nodes User-Agent: Chef Knife/12.0.2 (ruby-2.1.1-p320; ohai-8.0.0; x86_64-darwin12.0.2; +http://chef.io) X-Chef-Version: 14.0.0 X-Ops-Content-Hash: 2jmj7l5rfasfgSw0ygaVb/vlWAghYkK/YBwk= X-Ops-Authorization-1: BE3NnBritishaf3ifuwLSPCCYasdfXaRN5oZb4c6hbW0aefI X-Ops-Authorization-2: sL4j1qtEZzi/2WeF67UuytdsdfgbOc5CjgECQwqrym9gCUON X-Ops-Authorization-3: yf0p7PrLRCNasdfaHhQ2LWSea+kTcu0dkasdfvaTghfCDC57 X-Ops-Authorization-4: 155i+ZlthfasfasdffukusbIUGBKUYFjhbvcds3k0i0gqs+V X-Ops-Authorization-5: /sLcR7JjQky7sdafIHNfsBQrISktNPower1236hbFIayFBx3 X-Ops-Authorization-6: nodilAGMb166@haC/fttwlWQ2N1LasdqqGomRedtyhSqXA== X-Ops-Server-API-Info: 1 X-Ops-Sign: version=1.3; X-Ops-Timestamp: 2014-12-12T17:13:28Z X-Ops-Userid: user_id ``` ### Knife API Requests A knife plugin is a set of one (or more) subcommands that can be added to knife to support additional functionality that is not built-in to the base set of knife subcommands. Many of the knife plugins are built by members of the Chef community and several of them are built and maintained by Chef. A knife plugin can be used to make authenticated API requests to the Chef Infra Server using the following methods: | Method | Description | | --- | --- | | `rest.delete_rest` | Use to delete an object from the Chef Infra Server. | | `rest.get_rest` | Use to get the details of an object on the Chef Infra Server. | | `rest.post_rest` | Use to add an object to the Chef Infra Server. | | `rest.put_rest` | Use to update an object on the Chef Infra Server. | For example: ``` module MyCommands class MyNodeDelete &lt; Chef::Knife #An implementation of knife node delete banner 'knife my node delete [NODE_NAME]' def run if name_args.length &lt; 1 show_usage ui.fatal('You must specify a node name.') exit 1 end nodename = name_args[0] api_endpoint = "nodes/#{nodename}" # Again, we could just call rest.delete_rest nodey = rest.get_rest(api_endpoint) ui.confirm("Do you really want to delete #{nodey}") nodey.destroy end end end ``` Global Endpoints ---------------- A global endpoint may be used to access all of the organizations on the Chef Infra Server. ### /authenticate_user The `/authenticate_user` endpoint has the following methods: `POST`. #### POST The `POST` method is used to authenticate a user. This endpoint is used by the Chef Identity Service to authenticate users of Chef Supermarket to the Chef Infra Server. This method has no parameters. **Request** ``` POST /authenticate_user ``` with a request body similar to: ``` { "username" : "grantmc", "password" : "p@ssw0rd" } ``` **Response** This method has no response body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, password, and that the correct key was used to sign the request. | ### /license Note This endpoint is used for information purposes only and to trigger a notification in the Chef management console about the number of licenses owned vs. the number of licenses that should be owned. No other action is taken and the functionality and behavior of the Chef Infra Server and any added component does not change. The `/license` endpoint has the following methods: `GET`. #### GET The `GET` method is used to get license information for the Chef Infra Server. This method has no parameters. **Request** ``` GET /license ``` This method has no request body. **Response** The response is similar to: ``` { "limit_exceeded": false, "node_license": 25, "node_count": 12, "upgrade_url": "https://www.chef.io/pricing" } ``` When `node_count` is greater than `node_license`, then `limit_exceeded` is `true` and the Chef management console will display a notification about this status. The way to resolve this is to visit the upgrade URL, add the appropriate number of licenses, and then update the configuration settings appropriately. The chef-server.rb file contains settings that can be used to edit the number of nodes that are under license: | Setting | Description | | --- | --- | | `license['nodes']` | The number of licensed nodes. Default value: `25`. | | `license['upgrade_url']` | The URL to visit for more information about how to update the number of nodes licensed for an organization. Default value: `"https://www.chef.io/pricing"`. | **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | ### /organizations The Chef Infra Server may contain multiple organizations. The `/organizations` endpoint has the following methods: `GET` and `POST`. Warning This endpoint may only be accessed by the `pivotal` user, which is created as part of the installation process for the Chef Infra Server. (See the “Query for Users and Orgs” example below for an example of how to access this endpoint with the `pivotal` user.) #### GET The `GET` method is used to get a list of organizations on the Chef Infra Server. **Request** ``` GET /organizations ``` **Response** The response is similar to: ``` { "org_name1": https://url/for/org_name1", "org_name2": https://url/for/org_name2" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create an organization on the Chef Infra Server. This method has no parameters. **Request** ``` POST /organizations ``` with a request body similar to: ``` { "name": "org_name1", "full_name": "Org_name1 Full Name" } ``` where: * `name` must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. * `full_name` must begin with a non-white space character and must be between 1 and 1023 characters. For example: `Chef Software, Inc.`. Note An organization isn’t usable until a user that belongs to the `admins` group is associated with the organization. **Response** The response is similar to: ``` { "clientname": "org_name1-validator", "private_key": "-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAx2uyX ...", "uri": "https://url/for/org_name1" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The request was successful. The organization was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The organization already exists. | ### /organizations/NAME An organization is a single instance of a Chef Infra Server, including all of the nodes that are managed by that Chef Infra Server and each of the workstations that will run knife and access the Chef Infra Server using the Chef Infra Server API. The `/organizations/NAME` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete an organization. This method has no parameters. **Request** ``` DELETE /organizations/NAME ``` **Response** The response is similar to: ``` { "name": "chef", "full_name": "<NAME>, Inc.", "guid": "f980d1asdfda0331235s00ff36862" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### GET The `GET` method is used to get the details for the named organization. This method has no parameters. **Request** ``` GET /organizations/NAME ``` **Response** The response is similar to: ``` { "name": "chef", "full_name": "<NAME>, Inc.", "guid": "f980d1asdfda0331235s00ff36862" ... } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### PUT The `PUT` method is used to update an organization definition. This method has no parameters. **Request** ``` PUT /organizations/NAME ``` with a request body similar to: ``` { "name": "chef", "full_name": "<NAME>, Inc." } ``` **Response** The response is similar to: ``` { "name": "chef", "full_name": "<NAME>, Inc.", "guid": "f980d1asdfda0331235s00ff36862" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `410` | Gone. Unable to update private key. | ### /_stats Use the `/_stats` endpoint to display statistics about connection pool usage inside Erchef, Postgresql, and the Erlang VM. The `_stats` endpoint uses Basic Authorization instead of the X-Ops-Authorization scheme usually used to connect to the Chef Infra Server. The default user used to query the `_stats` endpoint is `statsuser`. The password for the `statsuser` is available as the `opscode_erchef::stats_password` from the `chef-server-ctl show-service-credentials` command. The `/_stats` endpoint has the following method: `GET`. #### GET The `GET` method is used to get the statistics. This method has the following parameters: | Parameter | Description | | --- | --- | | `format=json` | Return results as JSON. | | `format=text` | Return results as text. | **Request** ``` GET /_stats ``` This method has no parameters. This method has no request body. The `/_stats` endpoint does not require authentication headers. **Response** The response body is similar to: ``` [ { "name": "erlang_vm_time_correction", "type": "UNTYPED", "help": "1 if time correction is enabled, otherwise 0.", "metrics": [ { "value": "1" } ] }, { "name": "erlang_vm_thread_pool_size", "type": "GAUGE", "help": "The number of async threads in the async thread pool used for asynchronous driver calls.", "metrics": [ { "value": "5" } ] }, ... { "name": "pg_stat_seq_scan", "type": "COUNTER", "help": "Number of sequential scans initiated on all tables", "metrics": [ { "value": "22147" } ] } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. | | `401` | Unauthorized. The user or password is not valid. | | `406` | Not Acceptable. An invalid format was requested. | ### /_status Use the `/_status` endpoint to check the status of communications between the front and back end servers. This endpoint is located at `/_status` on the front end servers. The `/_status` endpoint does not require authentication headers. #### GET The `GET` method is used to get the Chef Infra Server status details. **Request** ``` GET /_status ``` This method has no parameters. This method has no request body. **Response** The response will return something like the following: ``` { "status": "pong", "upstreams": { "service_name": "pong", "service_name": "pong", ... } "keygen": { "keys": 10, .... } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | All communications are OK. | | `500` | One (or more) services are down. For example: ``` { "status":"fail", "upstreams": { "service_name": "fail", "service_name": "pong", ... } } ``` | ### /users A user is an individual account that is created to allow access to the Chef Infra Server. For example: * A hosted Chef Infra Server account * The user that operates the workstation from which a Chef Infra Server will be managed The `/users` endpoint has the following methods: `GET` and `POST`. Warning This endpoint may only be accessed by the `pivotal` user, which is created as part of the installation process for the Chef Infra Server. (See the “Query for Users and Orgs” example below for an example of how to access this endpoint with the `pivotal` user.) Note This documentation for the `/users` endpoint is for version 1 of the Chef Infra Server API. Version 0 of the API has some differences in the request body and in the results. #### GET The `GET` method is used to get a list of users on the Chef Infra Server. This method has the following parameters: | Parameter | Description | | --- | --- | | `email=<EMAIL>` | Filter the users returned based on their email id. | | `external_authentication_uid=<EMAIL>` | Filter the users returned based on their external login id. | | `verbose=true` | Returns a user list with "email", "first_name", "last_name" fields. If this flag is set the email and external_authentication_uid parameters are ignored. | **Request** ``` GET /users ``` **Response** The response is similar to: ``` { "user1": "https://chef.example/users/user1", "user2": "https://chef.example/users/user2" } ``` The verbose response is similar to: ``` { "janechef": { "email": "<EMAIL>", "first_name": "jane", "last_name": "chef_user" }, "yaelsmith": { "email": "<EMAIL>", "first_name": "yeal", "last_name": "smith" } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | **Optional Filtering** Filtering on `/users` can be done with the `external_authentication_uid`. This is to support SAML authentication. As an example, to retrieve users whos `external_authentication_uid` is `<EMAIL>`, you would do the following: ``` GET /users?external_authentication_uid=jane%40doe.com ``` #### POST The `POST` method is used to create a user on the Chef Infra Server. This method has no parameters. **Request** ``` POST /users ``` with a request body similar to: ``` { "username": "robert-forster", "display_name": "robert", "email": "<EMAIL>", "first_name": "robert", "last_name": "forster", "middle_name": "", "password": "yeahpass", "create_key": true, "public_key": "-----<KEY>END PUBLIC KEY-----\n\n" } ``` where: * `username` must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores. For example: `chef`. `username` is required to be present and have a valid value. A valid username is a dot separated list of elements matching `a-z0-9!#$%&'*+/=?^_`{|}~-`. * `display_name` is required to be present. * `email` is required to be present and have a valid value. The email validation doesn’t allow for all unicode characters. * Either `external_authentication_uid` or `password` are required to be present and have a value. * During the POST, the `public_key` value will be broken out and resubmitted to the keys portion of the API in the latest Chef Infra Server versions. * Only one of the keys, `create_key` or `public_key`, may be specified. If `create_key` is specified, a default private key is generated and returned. **Response** The response is similar to: ``` { "uri": "https://chef.example/users/robert-forster", "chef_key": { "name": "default", "public_key": "-----BEGIN RSA PUBLIC KEY...", "expiration_date": "infinity", "uri": "https://chef.example/users/robert-forster/keys/default", "private_key": "-----BEGIN RSA PRIVATE KEY..." } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The user was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /users/NAME The `/users/USER_NAME` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. Note This documentation for the `/users/NAME` endpoint is for version 1 of the Chef Infra Server API. Version 0 of the API has some differences in the request body and in the results. #### DELETE The `DELETE` method is used to delete a user. This method has no parameters. **Request** ``` DELETE /users/USER_NAME ``` **Response** The response is similar to: ``` { } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return the details for a user. This method has no parameters. **Request** ``` GET /users/USER_NAME ``` **Response** The response is similar to: ``` { "username": "robert-forster", "display_name": "robert", "email": "<EMAIL>", "first_name": "robert", "last_name": "forster" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update a specific user. If values are not specified for the `PUT` method, the Chef Infra Server will use the existing values rather than assign default values. Note `PUT` supports renames. If `PUT /users/foo` is requested with `{ "username: "bar""}`, then it will rename `foo` to `bar` and all of the content previously associated with `foo` will be associated with `bar`. Note As of 12.1.0, the `"public_key"`, `"private_key"`, and `"create_key"` parameters in PUT requests to clients/users will cause a 400 response. This method has no parameters. **Request** ``` PUT /users/NAME ``` with a request body similar to: ``` { "username": "grant.mclennan", "display_name": "<NAME>", "email": "<EMAIL>", "first_name": "Grant", "last_name": "McLennan", "middle_name": "james", "public_key" : "-------- BEGIN PUBLIC KEY ----and a valid key here" } ``` **Response** The response is similar to: ``` { "uri": "https://chef.example/users/grant.mclennan", "chef_key": { "name": "default", "public_key": "-----BEGIN RSA PUBLIC KEY...", "expiration_date": "infinity", "uri": "https://chef.example/users/rober-forster/keys/default", "private_key": "" } } ``` If a new private key was generated, both the private and public keys are returned. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `201` | Created. The object was created. (This response code is only returned when the user is renamed.) | | `400` | Invalid. Invalid or missing values. Otherwise malformed request. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `409` | Conflict. This response code is only returned when a user is renamed, but a user already exists with that name. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /users/USER/keys/ The `/users/USER/keys` endpoint has the following methods: `GET` and `POST`. User keys are public RSA keys in the SSL `.pem` file format and are used for authentication. The Chef Infra Server does not save private keys for users. #### GET The `GET` method is used to retrieve all of the named user’s key identifiers, associated URIs, and expiry states. This method has no parameters. **Request** ``` GET /users/USER/keys/ ``` **Response** The response is similar to: ``` [ { "name" : "default", "uri" : "https://chef.example/users/USER/keys/default", "expired" : false }, { "name" : "key1", "uri" : "https://chef.example/users/USER/keys/key1", "expired" : false } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST The `POST` method is used to add a key for the specified user. This method has no parameters. **Request** ``` POST /users/USER/keys/ ``` with a request body similar to: ``` { "name" : "key1", "public_key" : "-------- BEGIN PUBLIC KEY ----and a valid key here", "expiration_date" : "infinity" } ``` **Response** The response is similar to: ``` { "name" : "key1", "uri" : "https://chapi_chef_server.mdef.example/users/user1/keys/key1", "expired": false } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The object was created. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /users/USER/keys/KEY The `/users/USER/keys/KEY` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete the specified key for the specified user. This method has no parameters. **Request** ``` DELETE /users/USER/keys/KEY ``` **Response** The response returns the information about the deleted key and is similar to: ``` { "name" : "default", "public_key" : "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date" : "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return details for a specific key for a specific user. This method has no parameters. **Request** ``` GET /users/USER/keys/KEY ``` **Response** The response is similar to: ``` { "name" : "default", "public_key" : "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date" : "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update one or more properties for a specific key for a specific user. This method has no parameters. **Request** ``` PUT /users/USER/keys/KEY ``` with a request body similar to: ``` { "name" : "new_key_name", "public_key" : "-------- BEGIN PUBLIC KEY ----and a valid key here", "expiration_date" : "2020-12-31T00:00:00Z" } ``` **Response** The response contains the updated information for the key, and is similar to: ``` { "name" : "new_key_name", "public_key" : "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date" : "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `201` | Created. The object was created. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | Organization Endpoints ---------------------- Each organization-specific authentication request must include `/organizations/NAME` as part of the name for the endpoint. For example, the full endpoint for getting a list of roles: ``` GET /organizations/NAME/roles ``` where `ORG_NAME` is the name of the organization. ### /association_requests Users may be invited to join organizations via the web user interface in the Chef management console or via the `POST` endpoint in the Chef Infra Server API. The `/association_requests` endpoint has the following methods: `DELETE`, `GET`, and `POST`. #### DELETE The `DELETE` method is used to delete a pending invitation. This method has no parameters. **Request** ``` DELETE /organizations/NAME/association_requests/ID ``` This method has no request body. **Response** The response is similar to: ``` { "id": "79b9382ab70e962907cee1747f9969a4", "orgname": "testorg", "username" "janedoe" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to get a list of pending invitations. This method has no parameters. **Request** ``` GET /organizations/NAME/association_requests ``` This method has no request body. **Response** The response returns a dictionary similar to: ``` [ { "id": "79b9382ab70e962907cee1747f9969a4", "username": "marygupta" }, { "id": "24t1432uf33x799382abb7096g8190b5", "username": "johnirving" } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create an invitation. This method has no parameters. **Request** ``` { "user": "billysmith" } POST /organizations/NAME/association_requests ``` **Response** The response is similar to: ``` { "uri": "https://chef.example/organizations/test/association_requests/79b9382ab70e962907cee1747f9969a4", "organization_user": { "username": "authorizeduser" }, "organization": { "name": "test" }, "user": { "email": "<EMAIL>", "first_name": "sally" } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. An invitation was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The invited user does not exist. | | `409` | Conflict. The object already exists. | ### /clients Use the `/clients` endpoint to manage clients and their associated RSA key-pairs. The `/clients` endpoint has the following methods: `GET` and `POST`. Note The clients should be managed using knife as opposed to the Chef Infra Server API. The interactions between clients, nodes and acls are tricky. #### GET The `GET` method is used to return a client list on the Chef Infra Server, including clients for nodes that have been registered with the Chef Infra Server, the chef-validator clients, and the chef-server-webui clients for the entire organization. This method has no parameters. **Request** ``` GET /organizations/NAME/clients ``` This method has no request body. **Response** The response is similar to: ``` { "org1-validator" : "https://chef.example/orgaizations/org1/clients/org1-validator", "client1" : "https://chef.example/orgaizations/org1/clients/client1" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create a new API client. Note As of 12.1.0, the `"admin"` parameter is no longer supported in client/user creation and support. If used in the `POST` or `PUT` of a client or user, the `"admin"` parameter is ignored. This method has no parameters. **Request** ``` POST /organizations/NAME/clients ``` with a request body similar to: ``` { "name": "name_of_API_client", "clientname": "name_of_API_client", "validator": true, "create_key": true } ``` where `name_of_API_client` is the name of the API client to be created and `admin` indicates whether the API client will be run as an admin API client. Either name or clientname needs to be specified. **Response** The response is similar to: ``` { "uri": "https://chef.example/orgaizations/org1/clients/client1", "chef_key": { "name": "default", "expiration_date": "infinity", "private_key": "-----BEGIN RSA PRIVATE KEY----- ...", "public_key": "-----BEGIN PUBLIC KEY----- ... ", "uri": "https://chef.example/orgaizations/org1/clients/client1/keys/default" } ``` Store the private key in a safe place. It will be required later (along with the client name) to access the Chef Infra Server when using the Chef Infra Server API. **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The client was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /clients/NAME The `/clients/NAME` endpoint is used to manage a specific client. This endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to remove a specific client. This method has no parameters. **Request** ``` DELETE /organizations/NAME/clients/NAME ``` This method has no request body. **Response** The response has no body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return a specific API client. This method has no parameters. **Request** ``` GET /organizations/NAME/clients/NAME ``` This method has no request body. **Response** The response is similar to: ``` { "name": "user1", "clientname": "user1", "orgname": "test", "json_class": "Chef::ApiClient", "chef_type": "client", "validator": "false" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update a specific client. If values are not specified for the `PUT` method, the Chef Infra Server will use the existing values rather than assign default values. Note `PUT` supports renames. If `PUT /client/foo` is requested with `{ "name: "bar""}`, then it will rename `foo` to `bar` and all of the content previously associated with `foo` will be associated with `bar`. Note As of 12.1.0, the `"admin"` parameter is no longer supported in client/user creation and support. If used in the `POST` or `PUT` of a client or user, then it is ignored. Note As of 12.1.0, including `"public_key"`, `"private_key"`, or `"create_key"` in PUT requests to clients/users will cause a 400 response. Note `"name"` and `"clientname"` are not independent values. Making a PUT request with different values will return a 400 error. Either name may be specified to set both values. **Request** ``` PUT /organizations/NAME/clients/NAME ``` with a request body similar to: ``` { "name": "monkeypants", "validator": false } ``` **Response** The response is similar to: ``` { "name": "monkeypants", "clientname": "monkeypants", "validator": true, "json_class":"Chef::ApiClient", "chef_type":"client" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `201` | Created. The client was updated. (This response code is only returned when the client is renamed.) | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `409` | Conflict. This response code is only returned when a client is renamed, but a client already exists with the new name. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /clients/CLIENT/keys/ The `/clients/CLIENT/keys` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to retrieve all of the named client’s key identifiers, associated URIs, and expiry states. This method has no parameters. **Request** ``` GET /organizations/NAME/clients/CLIENT/keys ``` This method has no request body. **Response** The response is similar to: ``` [ { "name": "default", "uri": "https://chef.example/organizations/example/clients/client1/keys/default", "expired": false }, { "name": "key1", "uri": "https://chef.example/organizations/example/clients/client1/keys/key1", "expired": true } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST The `POST` method is used to add a key for the specified client. This method has no parameters. **Request** ``` POST /organizations/NAME/clients/CLIENT/keys ``` with a request body similar to: ``` { "name": "key1", "public_key": "-------- BEGIN PUBLIC KEY ----and a valid key here", "expiration_date": "infinity" } ``` **Response** The response is similar to: ``` { "uri": "https://chef.example/organizations/example/clients/client1/keys/key1" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The object was created. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /clients/CLIENT/keys/KEY The `/clients/CLIENT/keys/KEY` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete the specified key for the specified client. This method has no parameters. **Request** ``` DELETE /organizations/NAME/clients/CLIENT/keys/KEY ``` This method has no request body. **Response** The response returns the information about the deleted key and is similar to: ``` { "name": "default", "public_key": "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date": "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return details for a specific key for a specific client. This method has no parameters. **Request** ``` GET /organizations/NAME/clients/CLIENT/keys/KEY ``` This method has no request body. **Response** The response is similar to: ``` { "name" : "default", "public_key" : "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date" : "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update one or more properties for a specific key for a specific client. This method has no parameters. **Request** ``` PUT /organizations/NAME/clients/CLIENT/keys/KEY ``` with a request body similar to: ``` { "name": "new_key_name", "public_key": "-------- BEGIN PUBLIC KEY ----and a valid key here", "expiration_date": "2020-12-31T00:00:00Z" } ``` **Response** The response contains the updated information for the key and is similar to: ``` { "name": "new_key_name", "public_key": "-------- BEGIN PUBLIC KEY --------- ...", "expiration_date": "2020-12-31T00:00:00Z" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `201` | Created. The object was created. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /containers The `/containers` endpoint has the following methods: `GET`, `POST`. #### GET The `GET` method is used to get a list of containers. Note: The `/containers` endpoint is not useful outside of the Chef Infra Server code. This method has no parameters. **Request** ``` GET /organizations/NAME/containers ``` This method does not use a request body. **Response** The response is similar to: ``` { "clients": "https://chef.example/organizations/example/containers/clients", "containers": "https://chef.example/organizations/example/containers/containers", "cookbooks": "https://chef.example/organizations/example/containers/cookbooks", "data": "https://chef.example/organizations/example/containers/data", "environments": "https://chef.example/organizations/example/containers/environments", "groups": "https://chef.example/organizations/example/containers/groups", "nodes": "https://chef.example/organizations/example/containers/nodes", "roles": "https://chef.example/organizations/example/containers/roles", "sandboxes": "https://chef.example/organizations/example/containers/sandboxes" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST The `POST` method is used to create a container. Note: Using the `POST` method of the `/containers` endpoint may have unexpected effects and is likely to break your system. Use of this method is not supported. This method has no parameters. **Request** ``` POST /organizations/NAME ``` This method has a request body similar to: ``` { "containername": "mycontainer", "containerpath": "mycontainer" } ``` **Response** The response is similar to: ``` { "uri"": "https://chef.example/organizations/test/containers/mycontainer" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /containers/NAME #### DELETE The `DELETE` method is used to remove a container. The `/containers/Name` endpoint has the following methods: `DELETE`, `GET`. Note: Using the `DELETE` method of the `/containers/NAME` endpoint may have unexpected effects and is likely to break your system. Use of this method is not supported. This method has no parameters. **Request** ``` DELETE /organizations/NAME/containers/NAME ``` This method does not use a request body. **Response** The response does not return response body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to get a container. This method has no parameters. **Request** ``` GET /organizations/NAME/containers/NAME ``` This method does not use a request body. **Response** The response is similar to: ``` { "containername"": "mycontainer", "containerpath"": "mycontainer" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /cookbook_artifacts Cookbook artifacts are specific versions of cookbooks that were specified by a Policyfile applied to a node. The `/organization/NAME/cookbook_artifacts` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a hash of all cookbook artifacts and their versions. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbook_artifacts ``` This method has no request body. **Response** The response is similar to: ``` { "oc-influxdb": { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/oc-influxdb", "versions": [ { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/oc-influxdb/9634a5d998b02ff069761f6e1309a41572d0f858", "identifier": "9634a5d998b02ff069761f6e1309a41572d0f858" }, { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/oc-influxdb/d774c9bb079f21b64c34275ecd4b371e0cae71a1", "identifier": "d774c9bb079f21b64c34275ecd4b371e0cae71a1" } ] }, "rabbitmq": { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq", "versions": [ { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq/58035a5b41c005f3b5b98f22ccaed1a0d6161e22", "identifier": "58035a5b41c005f3b5b98f22ccaed1a0d6161e22" }, { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq/5c08f92cc01f94ee37d382c32023b137ee343a1e", "identifier": "5c08f92cc01f94ee37d382c32023b137ee343a1e" } ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | ### /cookbook_artifacts/NAME This endpoint lists versions of a named cookbook artifact. The `/organization/NAME/cookbook_artifacts/NAME` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a hash of a single cookbook artifact and its versions. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbook_artifacts/NAME ``` This method has no request body. **Response** The response is similar to: ``` { "rabbitmq": { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq", "versions": [ { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq/0bd7539be0434e3355aff8ecccf4543ecf5c4be2", "identifier": "0bd7539be0434e3355aff8ecccf4543ecf5c4be2" }, { "url": "https://chef.example/organizations/example-org/cookbook_artifacts/rabbitmq/0e1016d364685b87456c648136da04a2559821ec", "identifier": "0e1016d364685b87456c648136da04a2559821ec" } ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /cookbook_artifacts/NAME/ID The `/organization/NAME/cookbook_artifacts/NAME/ID` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete a single cookbook artifact version. This method has no parameters. **Request** ``` DELETE /organizations/NAME/cookbook_artifacts/NAME/ID ``` This method has no request body. **Response** The response contains the record of the deleted resource and is similar to: ``` { "version": "5.7.7", "name": "rabbitmq", "identifier": "f3cf8ea7d8bfc59e35ec541946e3e82cd4b73e74", "frozen?": false, "chef_type": "cookbook_version", "attributes": [ { "name": "default.rb", "path": "attributes/default.rb", "checksum": "e5a530cca3898d8bd07604435dc5156e", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-e5a530cca3898d8bd07604435dc5156e" } ], "definitions": [ ], "files": [ ], "libraries": [ { "name": "matchers.rb", "path": "libraries/matchers.rb", "checksum": "24c3f44c4d1d62300a56051f0069f639", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-24c3f44c4d1d62300a56051f0069f639" }, { "name": "helpers.rb", "path": "libraries/helpers.rb", "checksum": "df65c4a7259fcb30c6f3f1305ebf7502", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-df65c4a7259fcb30c6f3f1305ebf7502" }, { "name": "default.rb", "path": "libraries/default.rb", "checksum": "94292faac84ba797e720501700b30f74", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-94292faac84ba797e720501700b30f74" } ], "providers": [ { "name": "user.rb", "path": "providers/user.rb", "checksum": "c31c9cc749f21962c825f983a6679d94", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-c31c9cc749f21962c825f983a6679d94" }, { "name": "policy.rb", "path": "providers/policy.rb", "checksum": "746c8a3f248f5bbfa51f5d2ba60b6315", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-746c8a3f248f5bbfa51f5d2ba60b6315" } ], "recipes": [ { "name": "default.rb", "path": "recipes/default.rb", "checksum": "99a9b404ff6038d6ac55a90ca68c347a", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-99a9b404ff6038d6ac55a90ca68c347a" }, { "name": "cluster.rb", "path": "recipes/cluster.rb", "checksum": "fc0a86c1f858c9d37e11282efc9fe329", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-fc0a86c1f858c9d37e11282efc9fe329" } ], "resources": [ { "name": "cluster.rb", "path": "resources/cluster.rb", "checksum": "85e74276e19bfdad581dce4f5c59f94a", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-85e74276e19bfdad581dce4f5c59f94a" } ], "root_files": [ { "name": "metadata.rb", "path": "metadata.rb", "checksum": "36b395e758138a4295d1e3f9b3df5da9", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-36b395e758138a4295d1e3f9b3df5da9" }, { "name": "README.md", "path": "README.md", "checksum": "99873670f0994642f5e6baade52c8020", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-99873670f0994642f5e6baade52c8020" } ], "templates": [ { "name": "default.rabbitmq-server.erb", "path": "templates/default/default.rabbitmq-server.erb", "checksum": "077855f4dc37f7fb708976134d8b2551", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-077855f4dc37f7fb708976134d8b2551" }, { "name": "90forceyes.erb", "path": "templates/default/90forceyes.erb", "checksum": "73cc571097cf77c74b4e7b5b680020c9", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-73cc571097cf77c74b4e7b5b680020c9" } ], "metadata": { "name": "rabbitmq", "description": "Installs and configures RabbitMQ server", "long_description": "", "maintainer": "Chef Software, Inc. and contributors", "maintainer_email": "<EMAIL>", "license": "Apache-2.0", "platforms": { "amazon": ">= 2.0", "centos": ">= 7.0", "debian": ">= 8.0", "opensuse": ">= 0.0.0", "opensuseleap": ">= 0.0.0", "oracle": ">= 0.0.0", "redhat": ">= 0.0.0", "scientific": ">= 0.0.0", "smartos": ">= 0.0.0", "suse": ">= 0.0.0", "ubuntu": ">= 14.04" }, "dependencies": { "erlang": ">= 0.0.0", "yum-epel": ">= 0.0.0", "yum-erlang_solutions": ">= 0.0.0", "dpkg_autostart": ">= 0.0.0", "logrotate": ">= 0.0.0" }, "providing": { "rabbitmq::cluster": ">= 0.0.0", "rabbitmq::community_plugins": ">= 0.0.0", "rabbitmq": ">= 0.0.0", "rabbitmq::erlang_package": ">= 0.0.0", "rabbitmq::esl_erlang_package": ">= 0.0.0", "rabbitmq::management_ui": ">= 0.0.0", "rabbitmq::mgmt_console": ">= 0.0.0", "rabbitmq::plugin_management": ">= 0.0.0", "rabbitmq::plugins": ">= 0.0.0", "rabbitmq::policies": ">= 0.0.0", "rabbitmq::policy_management": ">= 0.0.0", "rabbitmq::systemd_limits": ">= 0.0.0", "rabbitmq::user_management": ">= 0.0.0", "rabbitmq::users": ">= 0.0.0", "rabbitmq::vhosts": ">= 0.0.0", "rabbitmq::virtualhost_management": ">= 0.0.0" }, "recipes": { "rabbitmq": "Install and configure RabbitMQ", "rabbitmq::systemd_limits": "Sets up kernel limits (e.g. nofile) for RabbitMQ via systemd", "rabbitmq::cluster": "Set up RabbitMQ clustering.", "rabbitmq::management_ui": "Sets up RabbitMQ management plugin/UI", "rabbitmq::mgmt_console": "Deprecated, alias for rabbitmq::management_ui", "rabbitmq::plugins": "Manage plugins with node attributes", "rabbitmq::plugin_management": "Deprecated, alias for rabbitmq::plugins", "rabbitmq::vhosts": "Manage virtual hosts with node attributes", "rabbitmq::virtualhost_management": "Deprecated, alias for rabbitmq::vhosts", "rabbitmq::users": "Manage users with node attributes", "rabbitmq::user_management": "Deprecated, alias for rabbitmq::users", "rabbitmq::policies": "Manage policies with node attributes", "rabbitmq::policy_management": "Deprecated, alias for rabbitmq::policies", "rabbitmq::erlang_package": "Provisions Erlang via Team RabbitMQ packages", "rabbitmq::esl_erlang_package": "Alias for erlang::esl", "rabbitmq::community_plugins": "" }, "version": "5.7.7", "source_url": "https://github.com/rabbitmq/chef-cookbook", "issues_url": "https://github.com/rabbitmq/chef-cookbook/issues", "privacy": false, "chef_versions": [ ], "ohai_versions": [ ], "gems": [ ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return a single cookbook artifact version. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbook_artifacts/NAME/ID ``` This method has no request body. **Response** The response is similar to: ``` { "version": "5.7.7", "name": "rabbitmq", "identifier": "f3cf8ea7d8bfc59e35ec541946e3e82cd4b73e74", "frozen?": false, "chef_type": "cookbook_version", "attributes": [ { "name": "default.rb", "path": "attributes/default.rb", "checksum": "e5a530cca3898d8bd07604435dc5156e", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-e5a530cca3898d8bd07604435dc5156e" } ], "definitions": [ ], "files": [ ], "libraries": [ { "name": "matchers.rb", "path": "libraries/matchers.rb", "checksum": "24c3f44c4d1d62300a56051f0069f639", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-24c3f44c4d1d62300a56051f0069f639" }, { "name": "helpers.rb", "path": "libraries/helpers.rb", "checksum": "df65c4a7259fcb30c6f3f1305ebf7502", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-df65c4a7259fcb30c6f3f1305ebf7502" }, { "name": "default.rb", "path": "libraries/default.rb", "checksum": "94292faac84ba797e720501700b30f74", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-94292faac84ba797e720501700b30f74" } ], "providers": [ { "name": "user.rb", "path": "providers/user.rb", "checksum": "c31c9cc749f21962c825f983a6679d94", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-c31c9cc749f21962c825f983a6679d94" }, { "name": "policy.rb", "path": "providers/policy.rb", "checksum": "746c8a3f248f5bbfa51f5d2ba60b6315", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-746c8a3f248f5bbfa51f5d2ba60b6315" } ], "recipes": [ { "name": "default.rb", "path": "recipes/default.rb", "checksum": "99a9b404ff6038d6ac55a90ca68c347a", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-99a9b404ff6038d6ac55a90ca68c347a" }, { "name": "cluster.rb", "path": "recipes/cluster.rb", "checksum": "fc0a86c1f858c9d37e11282efc9fe329", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-fc0a86c1f858c9d37e11282efc9fe329" } ], "resources": [ { "name": "cluster.rb", "path": "resources/cluster.rb", "checksum": "85e74276e19bfdad581dce4f5c59f94a", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-85e74276e19bfdad581dce4f5c59f94a" } ], "root_files": [ { "name": "metadata.rb", "path": "metadata.rb", "checksum": "36b395e758138a4295d1e3f9b3df5da9", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-36b395e758138a4295d1e3f9b3df5da9" }, { "name": "README.md", "path": "README.md", "checksum": "99873670f0994642f5e6baade52c8020", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-99873670f0994642f5e6baade52c8020" } ], "templates": [ { "name": "default.rabbitmq-server.erb", "path": "templates/default/default.rabbitmq-server.erb", "checksum": "077855f4dc37f7fb708976134d8b2551", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-077855f4dc37f7fb708976134d8b2551" }, { "name": "90forceyes.erb", "path": "templates/default/90forceyes.erb", "checksum": "73cc571097cf77c74b4e7b5b680020c9", "specificity": "default", "url": "https://chef.example/bookshelf/organization-9f69768696feedcd165633b8b475cc0b/checksum-73cc571097cf77c74b4e7b5b680020c9" } ], "metadata": { "name": "rabbitmq", "description": "Installs and configures RabbitMQ server", "long_description": "", "maintainer": "Chef Software, Inc. and contributors", "maintainer_email": "<EMAIL>", "license": "Apache-2.0", "platforms": { "amazon": ">= 2.0", "centos": ">= 7.0", "debian": ">= 8.0", "opensuse": ">= 0.0.0", "opensuseleap": ">= 0.0.0", "oracle": ">= 0.0.0", "redhat": ">= 0.0.0", "scientific": ">= 0.0.0", "smartos": ">= 0.0.0", "suse": ">= 0.0.0", "ubuntu": ">= 14.04" }, "dependencies": { "erlang": ">= 0.0.0", "yum-epel": ">= 0.0.0", "yum-erlang_solutions": ">= 0.0.0", "dpkg_autostart": ">= 0.0.0", "logrotate": ">= 0.0.0" }, "providing": { "rabbitmq::cluster": ">= 0.0.0", "rabbitmq::community_plugins": ">= 0.0.0", "rabbitmq": ">= 0.0.0", "rabbitmq::erlang_package": ">= 0.0.0", "rabbitmq::esl_erlang_package": ">= 0.0.0", "rabbitmq::management_ui": ">= 0.0.0", "rabbitmq::mgmt_console": ">= 0.0.0", "rabbitmq::plugin_management": ">= 0.0.0", "rabbitmq::plugins": ">= 0.0.0", "rabbitmq::policies": ">= 0.0.0", "rabbitmq::policy_management": ">= 0.0.0", "rabbitmq::systemd_limits": ">= 0.0.0", "rabbitmq::user_management": ">= 0.0.0", "rabbitmq::users": ">= 0.0.0", "rabbitmq::vhosts": ">= 0.0.0", "rabbitmq::virtualhost_management": ">= 0.0.0" }, "recipes": { "rabbitmq": "Install and configure RabbitMQ", "rabbitmq::systemd_limits": "Sets up kernel limits (e.g. nofile) for RabbitMQ via systemd", "rabbitmq::cluster": "Set up RabbitMQ clustering.", "rabbitmq::management_ui": "Sets up RabbitMQ management plugin/UI", "rabbitmq::mgmt_console": "Deprecated, alias for rabbitmq::management_ui", "rabbitmq::plugins": "Manage plugins with node attributes", "rabbitmq::plugin_management": "Deprecated, alias for rabbitmq::plugins", "rabbitmq::vhosts": "Manage virtual hosts with node attributes", "rabbitmq::virtualhost_management": "Deprecated, alias for rabbitmq::vhosts", "rabbitmq::users": "Manage users with node attributes", "rabbitmq::user_management": "Deprecated, alias for rabbitmq::users", "rabbitmq::policies": "Manage policies with node attributes", "rabbitmq::policy_management": "Deprecated, alias for rabbitmq::policies", "rabbitmq::erlang_package": "Provisions Erlang via Team RabbitMQ packages", "rabbitmq::esl_erlang_package": "Alias for erlang::esl", "rabbitmq::community_plugins": "" }, "version": "5.7.7", "source_url": "https://github.com/rabbitmq/chef-cookbook", "issues_url": "https://github.com/rabbitmq/chef-cookbook/issues", "privacy": false, "chef_versions": [ ], "ohai_versions": [ ], "gems": [ ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to create or update a single cookbook artifact version. This method has no parameters. **Request** ``` PUT /organizations/NAME/cookbook_artifacts/NAME/ID ``` The request body is similar to: ``` { "definitions": [ { "name": "unicorn_config.rb", "checksum": "c92b659171552e896074caa58dada0c2", "path": "definitions/unicorn_config.rb", "specificity": "default" } ], "attributes": [], "files": [], "providers": [], "metadata": { "dependencies": {"ruby": [], "rubygems": []}, "name": "unicorn", "maintainer_email": "<EMAIL>", "attributes": {}, "license": "Apache 2.0", "suggestions": {}, "platforms": {}, "maintainer": "Chef Software, Inc.", "long_description": "= LICENSE AND AUTHOR:\\n\\nAuthor:: <NAME>...", "recommendations": {}, "version": "0.1.2", "conflicting": {}, "recipes": {"unicorn": "Installs unicorn rubygem"}, "groupings": {}, "replacing": {}, "description": "Installs/Configures unicorn", "providing": {} }, "libraries": [], "templates": [ { "name": "unicorn.rb.erb", "checksum": "36a1cc1b225708db96d48026c3f624b2", "path": "templates/default/unicorn.rb.erb", "specificity": "default" } ], "resources": [], "name": "unicorn", "identifier": "ba0dadcbca26710a521e0e3160cc5e20", "recipes": [ { "name": "default.rb", "checksum": "ba0dadcbca26710a521e0e3160cc5e20", "path": "recipes/default.rb", "specificity": "default" } ], "root_files": [ { "name": "README.rdoc", "checksum": "d18c630c8a68ffa4852d13214d0525a6", "path": "README.rdoc", "specificity": "default" }, { "name": "metadata.rb", "checksum": "967087a09f48f234028d3aa27a094882", "path": "metadata.rb", "specificity": "default" }, { "name": "metadata.json", "checksum": "45b27c78955f6a738d2d42d88056c57c", "path": "metadata.json", "specificity": "default" } ], "chef_type": "cookbook_artifact_version" } ``` where the `checksum` values must have already been uploaded to the Chef Infra Server using the sandbox endpoint. Once a file with a particular checksum has been uploaded by the user, redundant uploads are not necessary. Unused `checksum` values will be garbage collected. **Response** This method has no response body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /cookbooks A cookbook is the fundamental unit of configuration and policy distribution in Chef Infra. A cookbook defines a scenario and contains everything that is required to support that scenario: * Recipes that specify which Chef Infra built-in resources to use, as well as the order in which they are to be applied * Attribute values, which allow environment-based configurations such as `dev` or `prodution`. * Custom Resources for extending Chef Infra beyond the built-in resources. * Files and Templates for distributing information to systems. * Custom Ohai Plugins for extending system configuration collection beyond the Ohai defaults. * The `metadata.rb` file, which describes the cookbook itself and any dependencies it may have. When a cookbook is uploaded, only files that are new or updated will be included. This approach minimizes the amount of storage and time that is required during the modify-upload-test cycle. To keep track of which files have already been uploaded, Chef Infra Client uses a checksum and assigns a checksum to each file. These checksums are used in the cookbook version manifest, alongside the same records that store the file description (name, specificity, and so on), as well as the checksum and the URL from which the file’s contents can be retrieved. The `/cookbooks` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a hash of all cookbooks and cookbook versions. This method has the following parameters: | Parameter | Description | | --- | --- | | `num_versions=n` | The number of cookbook versions to include in the response, where `n` is the number of cookbook versions. For example: `num_versions=3` returns the three latest versions, in descending order (newest to oldest). Use `num_versions=all` to return all cookbook versions. If `num_versions` is not specified, a single cookbook version is returned. `0` is an invalid input (an empty array for the versions of each cookbook is returned). | **Request** ``` GET /organizations/NAME/cookbooks ``` **Response** The response is similar to: ``` { "apache2": { "url": "https://localhost/cookbooks/apache2", "versions": [ {"url": "https://localhost/cookbooks/apache2/5.1.0", "version": "5.1.0"}, {"url": "https://localhost/cookbooks/apache2/4.2.0", "version": "4.2.0"} ] }, "nginx": { "url": "https://localhost/cookbooks/nginx", "versions": [ {"url": "https://localhost/cookbooks/nginx/1.0.0", "version": "1.0.0"}, {"url": "https://localhost/cookbooks/nginx/0.3.0", "version": "0.3.0"} ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | ### /cookbooks/_latest The `/cookbooks/_latest` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a list of the most recent cookbook versions. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbooks/_latest ``` **Response** For example, if cookbooks `foo` and `bar` both exist on the Chef Infra Server and both with versions `0.1.0` and `0.2.0`, the response is similar to: ``` { "foo": "https://localhost/cookbooks/foo/0.2.0", "bar": "https://localhost/cookbooks/bar/0.2.0" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /cookbooks/_recipes The `/cookbooks/_recipes` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return the names of all recipes in the most recent cookbook versions. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbooks/_recipes ``` **Response** The response is similar to: ``` { } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /cookbooks/NAME The `/cookbooks/NAME` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a hash that contains a key-value pair that corresponds to the specified cookbook, with a URL for the cookbook and for each version of the cookbook. **Request** ``` GET /organizations/NAME/cookbooks/NAME ``` **Response** The response is similar to: ``` { "apache2": { "url": "https://localhost/cookbooks/apache2", "versions": [ {"url": "https://localhost/cookbooks/apache2/5.1.0", "version": "5.1.0"}, {"url": "https://localhost/cookbooks/apache2/4.2.0", "version": "4.2.0"} ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /cookbooks/NAME/version A cookbook version represents a set of functionality that is different from the cookbook on which it is based. A version may exist for many reasons, such as ensuring the correct use of a third-party component, updating a bug fix, or adding an improvement. A cookbook version is defined using syntax and operators, may be associated with environments, cookbook metadata, and/or run-lists, and may be frozen (to prevent unwanted updates from being made). A cookbook version is maintained just like a cookbook, with regard to source control, uploading it to the Chef Infra Server, and how Chef Infra Client applies that cookbook when configuring nodes. The `/cookbooks/NAME/VERSION` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete a cookbook version. This method has no parameters. **Request** ``` DELETE /organizations/NAME/cookbooks/NAME/VERSION ``` **Response** This method has no response body. Unused `checksum` values will be garbage collected. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return a description of a cookbook, including its metadata and links to component files. This method has no parameters. **Request** ``` GET /organizations/NAME/cookbooks/NAME/VERSION ``` where `VERSION` can be `_latest` in order to float to head. **Response** The response is similar to: ``` { "cookbook_name": "getting-started", "files": [ ], "chef_type": "cookbook_version", "definitions": [ ], "libraries": [ ], "attributes": [ { "url": "https://domain.com/org_name/(...rest of URL)", "path": "attributes/default.rb", "specificity": "default", "name": "default.rb", "checksum": "fa0fc4abf3f6787fdsaasadfrc5c35de667c" } ], "recipes": [ { "url": "https://domain.com/org_name/(...rest of URL)", "path": "recipes/default.rb", "specificity": "default", "name": "default.rb", "checksum": "7e79b1ace7728fdsadfsdaf857e60fc69" } ], "providers": [ ], "resources": [ ], "templates": [ { "url": "https://domain.com/org_name/(...rest of URL)", "path": "templates/default/chef-getting-started.txt.erb", "specificity": "default", "name": "chef-getting-started.txt.erb", "checksum": "a29d6f2545sdffds1f140c3a78b1fe" } ], "root_files": [ { "url": "https://domain.com/org_name/(...rest of URL)", "path": ".DS_Store", "specificity": "default", "name": ".DS_Store", "checksum": "c107b500aafd12asdffdsdf5c2a7d6" }, { "url": "https://domain.com/org_name/(...rest of URL)", "path": "metadata.json", "specificity": "default", "name": "metadata.json", "checksum": "20f09570e54dasdf0f3ae01e6401c90f" }, { "url": "https://domain.com/org_name/(...rest of URL)", "path": "metadata.rb", "specificity": "default", "name": "metadata.rb", "checksum": "71027aefasd487fdsa4cb6994b66ed" }, { "url": "https://domain.com/org_name/(...rest of URL)", "path": "README.rdoc", "specificity": "default", "name": "README.rdoc", "checksum": "8b9275e56fee974easdfasdfbb729" } ], "name": "getting-started-0.4.0", "frozen?": false, "version": "0.4.0", "json_class": "Chef::CookbookVersion", "metadata": { "maintainer": "Maintainer", "attributes": { }, "suggestions": { }, "recipes": { "getting-started": "" }, "dependencies": { }, "platforms": { }, "groupings": { }, "recommendations": { }, "name": "getting-started", "description": "description", "version": "0.4.0", "maintainer_email": "<EMAIL>", "long_description": "= DESCRIPTION:\n\nThis cookbook is used to do some things.\n\n", "providing": { "getting-started": ">= 0.0.0" }, "replacing": { }, "conflicting": { }, "license": "Apache 2.0" } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to create or update a cookbook version. This method has no parameters. **Request** ``` PUT /organizations/NAME/cookbooks/NAME/VERSION ``` with a request body similar to: ``` { "definitions": [ { "name": "unicorn_config.rb", "checksum": "c92b659171552e896074caa58dada0c2", "path": "definitions/unicorn_config.rb", "specificity": "default" } ], "name": "unicorn-0.1.2", "attributes": [], "files": [], "json_class": "Chef::CookbookVersion", "providers": [], "metadata": { "dependencies": {"ruby": [], "rubygems": []}, "name": "unicorn", "maintainer_email": "<EMAIL>", "attributes": {}, "license": "Apache 2.0", "suggestions": {}, "platforms": {}, "maintainer": "Chef Software, Inc.", "long_description": "= LICENSE AND AUTHOR:\n\nAuthor:: <NAME>...", "recommendations": {}, "version": "0.1.2", "conflicting": {}, "recipes": {"unicorn": "Installs unicorn rubygem"}, "groupings": {}, "replacing": {}, "description": "Installs/Configures unicorn", "providing": {} }, "libraries": [], "templates": [ { "name": "unicorn.rb.erb", "checksum": "36a1cc1b225708db96d48026c3f624b2", "path": "templates/default/unicorn.rb.erb", "specificity": "default" } ], "resources": [], "cookbook_name": "unicorn", "version": "0.1.2", "recipes": [ { "name": "default.rb", "checksum": "ba0dadcbca26710a521e0e3160cc5e20", "path": "recipes/default.rb", "specificity": "default" } ], "root_files": [ { "name": "README.rdoc", "checksum": "d18c630c8a68ffa4852d13214d0525a6", "path": "README.rdoc", "specificity": "default" }, { "name": "metadata.rb", "checksum": "967087a09f48f234028d3aa27a094882", "path": "metadata.rb", "specificity": "default" }, { "name": "metadata.json", "checksum": "45b27c78955f6a738d2d42d88056c57c", "path": "metadata.json", "specificity": "default" } ], "chef_type": "cookbook_version" } ``` where the `checksum` values must have already been uploaded to the Chef Infra Server using the sandbox endpoint. Once a file with a particular checksum has been uploaded by the user, redundant uploads are not necessary. Unused `checksum` values will be garbage collected. **Response** This method has no response body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /data Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. The `/data` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to return a list of all data bags on the Chef Infra Server. This method has no parameters. **Request** ``` GET /organizations/NAME/data ``` **Response** The response is similar to: ``` { "users": "https://chef.example/organizations/NAME/data/users", "applications": "https://chef.example/organizations/NAME/data/applications" } ``` shown as a list of key-value pairs, where (in the example above) `users` and `applications` are the names of data bags and `https://chef.example/organizations/NAME/data/foo` is the path to the data bag. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create a new data bag on the Chef Infra Server. This method has no parameters. **Request** ``` POST /organizations/NAME/data ``` with a request body that contains the key-value pair for the data bag and is similar to: ``` { "name": "users" } ``` where (in the example above) `name` is the key and “users” is the value. **Response** The response is similar to: ``` { "uri": "https://organizations/NAME/data/users", } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The object was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. A databag with that name already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /data/NAME The `/data/NAME` endpoint is used to view and update data for a specific data bag. This endpoint has the following methods: `DELETE`, `GET`, and `POST`. #### DELETE The `DELETE` method is used to delete a data bag. This method has no parameters. **Request** ``` DELETE /organizations/NAME/data/NAME ``` This method has no request body. **Response** The response is similar to: ``` { "name": "users", "json_class": "Chef::DataBag", "chef_type": "data_bag" } ``` where the key-value pairs represent the last state of the data bag item. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return a hash of all entries in the specified data bag. This method has no parameters. **Request** ``` GET /organizations/NAME/data/NAME ``` **Response** The response is similar to: ``` { "adam": "https://chef.example/organizations/NAME/data/users/adam" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST The `POST` method is used to create a new data bag item. This method has no parameters. **Request** ``` POST /organizations/NAME/data/NAME ``` with a request body similar to: ``` { "id": "adam", "real_name": "<NAME>" } ``` where `id` is required. **Response** This method has no response body. **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The item was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /data/NAME/ITEM A data bag is a container of related data bag items, where each individual data bag item is a JSON file. knife can load a data bag item by specifying the name of the data bag to which the item belongs and then the filename of the data bag item. The only structural requirement of a data bag item is that it must have an `id`: ``` { /* This is a supported comment style */ // This style is also supported "id": "ITEM_NAME", "key": "value" } ``` where * `key` and `value` are the `key:value` pair for each additional attribute within the data bag item * `/* ... */` and `// ...` show two ways to add comments to the data bag item The `/data/NAME/ITEM` endpoint allows the key-value pairs within a data bag item to be viewed and managed. This endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete a key-value pair in a data bag item. This method has no parameters. **Request** ``` DELETE /organizations/NAME/data/NAME/ITEM ``` **Response** The response is similar to: ``` { } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to view all of the key-value pairs in a data bag item. This method has no parameters. **Request** ``` GET /organizations/NAME/data/NAME/ITEM ``` **Response** The response is similar to: ``` { "real_name": "<NAME>", "id": "adam" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to replace the contents of a data bag item with the contents of this request. This method has no parameters. **Request** ``` PUT /organizations/NAME/data/NAME/ITEM ``` with a request body similar to: ``` { "real_name": "<NAME>", "id": "adam" } ``` where `id` is required. **Response** The response is similar to: ``` { } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /environments An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. The `/environments` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to return a data structure that contains a link to each available environment. This method has no parameters. **Request** ``` GET /organizations/NAME/environments ``` **Response** The response is similar to: ``` { "_default": "https://api.chef.io/organizations/org_name/environments/_default", "webserver": "https://api.chef.io/organizations/org_name/environments/webserver" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create a new environment. This method has no parameters. **Request** ``` POST /organizations/NAME/environments ``` with a request body similar to: ``` { "name": "dev", "default_attributes": {}, "json_class": "Chef::Environment", "description": "", "cookbook_versions": {}, "chef_type": "environment" } ``` **Response** The response is similar to: ``` { "uri": "https://localhost/environments/dev" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The object was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /environments/_default The `/environments/_default` endpoint has the following methods: `GET`. #### GET The `GET` method is used to get information about the `_default` environment on the Chef Infra Server. This method has no parameters. **Request** ``` GET /organizations/NAME/environments/_default ``` **Response** The response is similar to: ``` { "name": "_default", "description": "The default Chef environment", "json_class": "Chef::Environment", "chef_type": "environment", "default_attributes": { }, "override_attributes": { }, "cookbook_versions": { } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /environments/NAME The `/environments/NAME` endpoint has the following methods: `DELETE`, `GET`, and `PUT`. #### DELETE The `DELETE` method is used to delete an environment. This method has no parameters. **Request** ``` DELETE /organizations/NAME/environments/NAME ``` **Response** The response will return the JSON for the environment that was deleted, similar to: ``` { "name":"backend", "description":"", "cookbook_versions":{}, "json_class":"Chef::Environment", "chef_type":"environment", "default_attributes":{}, "override_attributes":{} } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return the details for an environment as JSON. This method has no parameters. **Request** ``` GET /organizations/NAME/environments/NAME ``` **Response** The response is similar to: ``` { "name": "_default", "description": "The default Chef environment", "json_class": "Chef::Environment", "chef_type": "environment", "default_attributes": { } "override_attributes": { }, "cookbook_versions": { }, } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update the details of an environment on the Chef Infra Server. This method has no parameters. **Request** ``` PUT /organizations/NAME/environments/NAME ``` with a request body that contains the updated JSON for the environment and is similar to: ``` { "name": "dev", "attributes": {}, "json_class": "Chef::Environment", "description": "The Dev Environment", "cookbook_versions": {}, "chef_type": "environment" } ``` **Response** The response will return the updated environment. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /environments/NAME/cookbooks/NAME The `/environments/NAME/cookbooks/NAME` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a hash of key-value pairs for the requested cookbook. This method has the following parameters: | Parameter | Description | | --- | --- | | `num_versions=n` | The number of cookbook versions to include in the response, where `n` is the number of cookbook versions. For example: `num_versions=3` returns the three latest versions, in descending order (newest to oldest). Use `num_versions=all` to return all cookbook versions. If `num_versions` is not specified, a single cookbook version is returned. `0` is an invalid input (an empty array for the versions of each cookbook is returned). | **Request** ``` GET /organizations/NAME/environments/NAME/cookbooks/NAME ``` where the first instance of `NAME` is the name of the environment, and the second instance is the name of the cookbook. **Response** The response is similar to: ``` { "apache2": { "url": "https://localhost/cookbooks/apache2", "versions": [ {"url": "https://localhost/cookbooks/apache2/5.1.0", "version": "5.1.0"}, {"url": "https://localhost/cookbooks/apache2/4.2.0", "version": "4.2.0"} ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /environments/NAME/cookbook_versions The `/environments/NAME/cookbook_versions` endpoint has the following methods: `POST`. #### POST The `POST` method is used to return a hash of the cookbooks and cookbook versions (including all dependencies) that are required by the `run_list` array. Version constraints may be specified using the `@` symbol after the cookbook name as a delimiter. Version constraints may also be present when the `cookbook_versions` attributes is specified for an environment or when dependencies are specified by a cookbook. This method has no parameters. **Request** ``` POST /organizations/NAME/environments/NAME/cookbook_versions ``` with a request body similar to: ``` { "run_list": [ "zed@0.0.1", "bar", "mysql", "gem", "nginx@0.99.2", "cron", "foo" ] } ``` where `@x.x.x` represents a constraint for a cookbook version. **Response** The response will return a list of cookbooks that are required by the `run_list` array contained in the request. The cookbooks that are returned are often the latest versions of each cookbook. Depending on any constraints present in the request or on dependencies a cookbook may have for specific cookbook versions, a request may not always return the latest cookbook version for each cookbook. The response is similar to: ``` { "cookbook_name": { "recipes": [ { "name": "default.rb", "path": "recipes/default.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "recipe_name.rb", "path": "recipes/recipe_name.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { ... } ], "definitions": [ ], "libraries": [ ], "attributes": [ ], "files": [ ], "templates": [ { "name": "template_name.erb", "path": "templates/default/template_name.erb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { ... } ], "resources": [ ], "providers": [ ], "root_files": [ { "name": "metadata.rb", "path": "metadata.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" } ], "cookbook_name": "cookbook_name-1.0.2", "metadata": { "name": "cookbook_name", "description": "description", "long_description": "", "maintainer": "maintainer", "maintainer_email": "<EMAIL>", "license": "license", "platforms": { }, "dependencies": { "cookbook_name": ">= 0.0.0", "cookbook_name": ">= 1.2.3", ... "cookbook_name": ">= 0.1.0" }, "recommendations": { }, "suggestions": { }, "conflicting": { }, "providing": { "cookbook_name": ">= 0.0.0", "cookbook_name::recipe_name": ">= 0.0.0", "cookbook_name::recipe_name": ">= 1.2.3", "cookbook_name::recipe_name": ">= 0.1.0" }, "replacing": { }, "attributes": { }, "groupings": { }, "recipes": { "cookbook_name": "description", "cookbook_name::recipe_name": "", ... "cookbook_name::recipe_name": "" }, "version": "0.0.0" }, "version": "0.0.0", "name": "cookbook_name-1.0.2", "frozen?": false, "chef_type": "cookbook_version", "json_class": "Chef::CookbookVersion" }, "cookbook_name": { "recipes": [ { "name": "default.rb", "path": "recipes/default.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, ], "definitions": [ ], "libraries": [ { "name": "library_file.rb", "path": "libraries/library_file.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" } ], "attributes": [ { "name": "default.rb", "path": "attributes/default.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" } ], "files": [ ], "templates": [ ], "resources": [ ], "providers": [ ], "root_files": [ { "name": ".gitignore", "path": ".gitignore", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": ".kitchen.yml", "path": ".kitchen.yml", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "CHANGELOG.md", "path": "CHANGELOG.md", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "CONTRIBUTING", "path": "CONTRIBUTING", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "LICENSE", "path": "LICENSE", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "metadata.json", "path": "metadata.json", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "metadata.rb", "path": "metadata.rb", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, { "name": "README.md", "path": "README.md", "checksum": "12345efg78912346abcddefg789", "specificity": "default", "url": "https://URL" }, ], "chef_type": "cookbook_version", "name": "cookbook_name-1.0.2", "cookbook_name": "cookbook_name", "version": "1.0.2", "metadata": { "name": "cookbook_name", "description": "description", "long_description": "", "maintainer": "maintainer", "maintainer_email": "<EMAIL>", "license": "license", "platforms": { }, "dependencies": { }, "recommendations": { }, "suggestions": { }, "conflicting": { }, "providing": { }, "replacing": { }, "attributes": { }, "groupings": { }, "recipes": { }, "version": "1.0.2" }, "frozen?": true, "json_class": "Chef::CookbookVersion" }, "cookbook_name": { ... } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `412` | Not allowed. A set of cookbooks and/or cookbook versions could not be found that met all of the requirements of the run-list. A cookbook in the run-list may not exist. A dependency may be present for a cookbook that does not exist. A constraint on a cookbook made by a run-list, environment, or cookbook version, may not match an available cookbook version. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /environments/NAME/cookbooks The `/environments/NAME/cookbooks` endpoint has the following methods: `GET`. #### GET The `GET` method is used to get a list of cookbooks and cookbook versions that are available to the specified environment. This method has the following parameters: | Parameter | Description | | --- | --- | | `num_versions=n` | The number of cookbook versions to include in the response, where `n` is the number of cookbook versions. For example: `num_versions=3` returns the three latest versions, in descending order (newest to oldest). Use `num_versions=all` to return all cookbook versions. If `num_versions` is not specified, a single cookbook version is returned. `0` is an invalid input (an empty array for the versions of each cookbook is returned). | **Request** ``` GET /organizations/NAME/environments/NAME/cookbooks ``` **Response** The response is similar to: ``` { "apache2": { "url": "https://localhost/cookbooks/apache2", "versions": [ {"url": "https://localhost/cookbooks/apache2/5.1.0", "version": "5.1.0"}, {"url": "https://localhost/cookbooks/apache2/4.2.0", "version": "4.2.0"} ] }, "nginx": { "url": "https://localhost/cookbooks/nginx", "versions": [ {"url": "https://localhost/cookbooks/nginx/1.0.0", "version": "1.0.0"}, {"url": "https://localhost/cookbooks/nginx/0.3.0", "version": "0.3.0"} ] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /environments/NAME/nodes The `/environments/NAME/nodes` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a list of nodes in a given environment. This method has no parameters. **Request** ``` GET /organizations/NAME/environments/NAME/nodes ``` **Response** The response is similar to: ``` { "blah": "https://api.chef.io/org/org_name/nodes/_default", "boxer": "https://api.chef.io/org/org_name/nodes/frontend", "blarrrrgh": "https://api.chef.io/org/org_name/nodes/backend" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /environments/NAME/recipes The `/environments/NAME/recipes` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return a list of recipes available to a given environment. This method has no parameters. **Request** ``` GET /organizations/NAME/environments/NAME/recipes ``` where the first instance of `NAME` is the name of the environment, and the second instance is the name of the recipe. **Response** The response is similar to: ``` [ "ant", "apache2", "apache2::mod_auth_openid", "apache2::mod_authnz_ldap", "apt", "aws", "capistrano", "chef", "chef::bootstrap_client", "chef-client::config", "chef-client", ... ] ``` The list of recipes will be the default recipes for a given cookbook. If an environment has multiple versions of a cookbook that matches its constraints, only the recipes from the latest version of that cookbook will be reported. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /environments/NAME/roles/NAME The `/environments/NAME/roles/NAME` endpoint has the following methods: `GET`. #### GET The `GET` method is used to return the `run_list` attribute of the role (when the name of the environment is `_default`) or to return `env_run_lists[environment_name]` (for non-default environments). Note The behavior of this endpoint is identical to `GET /roles/NAME/environments/NAME`; it is recommended (but not required) that `GET /roles/NAME/environments/NAME` be used instead of this endpoint. This method has no parameters. **Request** ``` GET /organizations/NAME/environments/NAME/roles/NAME ``` where the first instance of `NAME` is the name of the environment, and the second instance is the name of the role. **Response** The response is similar to: ``` { "run_list": [ "recipe[recipe_name]", "role[role_name]", "recipe[recipe_name]", "role[role_name]", "recipe[recipe_name]", "role[role_name]" ] } ``` Chef Infra Client will pick up the `_default` run-list if `env_run_list[environment_name]` is null or nonexistent. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /groups The `/groups` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to get a list of groups on the Chef Infra Server for a single organization. This method has no parameters. **Request** ``` GET /organizations/NAME/groups ``` **Response** The response is similar to: ``` { "33a5c28a8efe11e195005fsaes25400298d3f": "https://url/for/group1", "admins": "https://url/for/groups/admins", "billing-admins": "https://url/for/billing-admins", "clients": "https://url/for/clients", "developers": "https://url/for/developers", "users": "https://url/for/groups/users" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST The `POST` method is used to create a group on the Chef Infra Server for a single organization. **Request** ``` POST /organizations/NAME/groups ``` with a request body similar to: ``` { "name": "group1", "groupname": "group1", "orgname": "test", "actors": [] "clients": ["mynode"], "groups": ["admins"], "users": ["betina"] } ``` **Response** The response is similar to: ``` { "uri": "https://chef.example/organizations/test/groups/group1", } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The group was created. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `409` | Conflict. The requested group already exists. | ### /groups/GROUP_NAME The `/groups/GROUP_NAME` endpoint has the following methods: `DELETE`, `GET` and `PUT`. #### DELETE The `DELETE` method is used to remove a group from a single organization. This method has no parameters. **Request** ``` DELETE /organizations/NAME/groups/GROUP_NAME ``` without a request body. **Response** The response is similar to: ``` { } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The group was deleted. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to get lists of users and other groups that belong to a group. This method has no parameters. **Request** ``` GET /organizations/NAME/groups/GROUP_NAME ``` **Response** The response is similar to: ``` { "actors": [ "pivotal", "grantmc" ], "users": [ "pivotal", "grantmc" ], "clients": [ ], "groups": [ "000000000000ad94b5ddde157c070f0c" ], "orgname": "inbetweens", "name": "admins", "groupname": "admins" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update a group on a single organization. Updating the clients, groups and users memberships replaces the definitions for the group. `GET` the group and merge changes to create the desired member lists. This method has no parameters. **Request** ``` PUT /organizations/NAME/groups/GROUP_NAME ``` with a request body similar to: ``` { "name": "group1", "groupname": "groupnew", "actors": { "clients": ["mynode","addme"], "groups": ["admins"], "users": ["betina"] } } ``` **Response** The response is similar to: ``` { "name": "group1", "groupname": "groupnew", "orgname": "test", "actors": { "clients": ["mynode","addme"], "groups": ["admins"], "users": ["betina"] } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The group was updated. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /nodes A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. The `/nodes` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to return a hash of URIs for nodes on the Chef Infra Server. This method has no parameters. **Request** ``` GET /organizations/NAME/nodes ``` **Response** The response is similar to: ``` { "latte": "https://localhost/nodes/latte" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create a new node. This method has no parameters. **Request** ``` POST /organizations/NAME/nodes ``` with a request body similar to: ``` { "name": "latte", "chef_type": "node", "json_class": "Chef::Node", "attributes": { "hardware_type": "laptop" }, "overrides": {}, "defaults": {}, "run_list": [ "recipe[unicorn]" ] } ``` where `name` is the name of the node. Other attributes are optional. The order of the `run_list` attribute matters. **Response** The response is similar to: ``` { "uri": "https://localhost/nodes/latte" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The object was created. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /nodes/NAME The `/nodes/NAME` endpoint has the following methods: `DELETE`, `GET`, `HEAD` and `PUT`. #### DELETE The `DELETE` method is used to delete a node. This method has no parameters. **Request** ``` DELETE /organizations/NAME/nodes/NAME ``` **Response** The response will return the last known state of the node, similar to: ``` { "overrides": {}, "name": "latte", "chef_type": "node", "json_class": "Chef::Node", "attributes": { "hardware_type": "laptop" }, "run_list": [ "recipe[apache2]" ], "defaults": {} } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return the details of a node as JSON. This method has no parameters. **Request** ``` GET /organizations/NAME/nodes/NAME ``` **Response** The response is similar to: ``` { "name": "node_name", "chef_environment": "_default", "run_list": [ "recipe[recipe_name]" ] "json_class": "Chef::Node", "chef_type": "node", "automatic": { ... }, "normal": { "tags": [ ] }, "default": { }, "override": { } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### HEAD The `HEAD` method is used to check the existence of a node. This method has no parameters. **Request** ``` HEAD /organizations/NAME/nodes/NAME ``` **Response** The method does not return a body. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update a node. This method has no parameters. **Request** ``` PUT /organizations/NAME/nodes/NAME ``` with a request body similar to: ``` { "overrides": {}, "name": "latte", "chef_type": "node", "json_class": "Chef::Node", "attributes": { "hardware_type": "laptop" }, "run_list": [ 'recipe[cookbook_name::recipe_name], role[role_name]' ], "defaults": {} } ``` **Response** The response will return the updated node. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /policies The `/policies` endpoint has the following methods: `GET`. #### GET The `GET` method is used to get a list of policies (including policy revisions) from the Chef Infra Server. This method has no parameters. **Request** ``` GET /organizations/NAME/policies ``` **Response** The response groups policies by name and revision and is similar to: ``` { "aar": { "uri": "https://chef.example/organizations/org1/policies/aar", "revisions": { "37f9b658cdd1d9319bac8920581723efcc2014304b5f3827ee0779e10ffbdcc9": { }, "95040c199302c85c9ccf1bcc6746968b820b1fa25d92477ea2ec5386cd58b9c5": { }, "d81e80ae9bb9778e8c4b7652d29b11d2111e763a840d0cadb34b46a8b2ca4347": { } } }, "jenkins": { "uri": "https://chef.example/organizations/org1/policies/jenkins", "revisions": { "613f803bdd035d574df7fa6da525b38df45a74ca82b38b79655efed8a189e073": { }, "6fe753184c8946052d3231bb4212116df28d89a3a5f7ae52832ad408419dd5eb": { }, "cc1a0801e75df1d1ea5b0d2c71ba7d31c539423b81478f65e6388b9ee415ad87": { } } } } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | ### /policy_groups The `/policy_groups` endpoint has the following methods: `GET`. Each node has a 1:many relationship with policy settings stored on the Chef Infra Server. This relationship is based on the policy group to which the node is associated, and then the policy settings assigned to that group: * A policy is typically named after the functional role ahost performs, such as “application server”, “chat server”, “load balancer”, and so on * A policy group defines a set of hosts in a deployed units, typically mapped to organizational requirements such as “dev”, “test”, “staging”, and “production”, but can also be mapped to more detailed requirements as needed ### /principals/NAME The `/principals/NAME` endpoint has the following methods: `GET`. #### GET The `GET` method is used to get a list of public keys for clients and users in order to ensure that enough information is present for authorized requests. This method has no parameters. **Request** ``` GET /organizations/NAME/principals/NAME ``` **Response** For a user or client, the type value will vary. The response body returns an array of principals which allows for a client with the same name as a user. The response for a user or client is similar to: ``` { "Principals: [ { "name": "normal_user", "type": "user", "public_key": "-----BEGIN PUBLIC KEY-----...", "authz_id": "eca5fdd45a8b4bacc04bbc6e37a340bes", "org_member":false } ] } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `404` | Not found. The requested object does not exist. | ### /required_recipe The `/required_recipe` endpoint has the following method: `GET`. #### GET Use the `GET` method to view a recipe specified by a Chef Infra Server administrator as part of the Chef Infra Server configuration. This recipe will be run by all Chef Infra Clients that connect to the Chef Infra Server. The `required_recipe` feature is aimed at expert level practitioners delivering isolated configuration changes to target systems. The returned text is the content of a single recipe file. This method has no parameters. **Request** ``` GET /organizations/NAME/required_recipe ``` This method has no request body. **Response** The response is returned in plain text, not in JSON format. The response is similar to: ``` "# My required recipe file '/tmp/build' package 'secret_sauce' " ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. Required recipe is enabled, a path to a recipe is defined, and a recipe exists at the path location. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not Found. The required recipe function is not enabled. | ### /roles A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. The `/roles` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to get a list of roles along with their associated URIs. This method has no parameters. **Request** ``` GET /organizations/NAME/roles ``` **Response** The response is similar to: ``` { "webserver": "https://chef.example/organizations/org1/roles/webserver" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to create a new role on the Chef Infra Server. This method has no parameters. **Request** ``` POST /organizations/NAME/roles ``` with a request body similar to: ``` { "name": "webserver", "default_attributes": {}, "description": "A webserver", "env_run_lists": { "testenv": { "recipe[pegasus]" } }, "run_list": [ "recipe[unicorn]", "recipe[apache2]" ], "override_attributes": {} } ``` **Response** The response is similar to: ``` { "uri": "https://chef.example/organizations/org1/roles/webserver" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `201` | OK. The request was successful. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The object already exists. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /roles/NAME The `/roles/NAME` endpoint has the following methods: `GET`, `DELETE`, and `PUT`. #### DELETE The `DELETE` method is used to delete a role on the Chef Infra Server. This method has no parameters. **Request** ``` DELETE /organizations/NAME/roles/NAME ``` **Response** The response is similar to: ``` { "name": "webserver", "chef_type": "role", "json_class": "Chef::Role", "default_attributes": {}, "description": "A webserver", "env_run_lists": { "env1": { "recipe[foo1]" } }, "run_list": [ "recipe[apache2]" ], "override_attributes": {} } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return the details for a role as JSON. This method has no parameters. **Request** ``` GET /organizations/NAME/roles/NAME ``` **Response** The response is similar to: ``` { "name": "webserver", "chef_type": "role", "json_class": "Chef::Role", "default_attributes": {}, "description": "A webserver", "env_run_lists": {}, "run_list": [ "recipe[unicorn]", "recipe[apache2]" ], "override_attributes": {} } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### PUT The `PUT` method is used to update a role on the Chef Infra Server. This method has no parameters. **Request** ``` PUT /organizations/NAME/roles/NAME ``` with a request body similar to: ``` { "name": "webserver", "default_attributes": {}, "description": "A webserver", "env_run_lists": {}, "default_attributes": {}, "run_list": [ "recipe[apache2]" ], "override_attributes": {} } ``` **Response** The response will return the JSON for the updated role. **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /roles/NAME/environments The `/roles/NAME/environments` endpoint has the following method: `GET`. #### GET The `GET` method returns a list of the environments that have environment-specific run-lists in the given role as JSON data. This method has no parameters. **Request** ``` GET /organizations/NAME/roles/NAME/environments ``` **Response** The response is similar to: ``` ["_default","production","qa"] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /roles/NAME/environments/NAME The `/roles/NAME/environments/NAME` endpoint has the following method: `GET`. #### GET The `GET` method returns the environment-specific run-list (`env_run_lists[environment_name]`) for a role. This method has no parameters. **Request** ``` GET /organizations/NAME/roles/NAME/environments/NAME ``` where the first `NAME` is the name of the role and the second is the name of the environment. **Response** The response is similar to: ``` {"run_list":["recipe[foo]"]} ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | ### /sandboxes A sandbox is used to commit files so they only need to be updated one time, as opposed to every time a cookbook is uploaded. The `/sandboxes` endpoint has the following methods: `POST`. #### POST The `POST` method is used to create a new sandbox. This method accepts a list of checksums as input and returns the URLs against which to `PUT` files that need to be uploaded. This method has no parameters. **Request** ``` POST /organizations/NAME/sandboxes ``` with a request body similar to: ``` {"checksums": { "385ea5490c86570c7de71070bce9384a":null, "f6f73175e979bd90af6184ec277f760c":null, "2e03dd7e5b2e6c8eab1cf41ac61396d5":null } } ``` **Response** The response is similar to: ``` {"uri": "https://api.chef.io/organizations/testorg/sandboxes/eff7b6f8b3ef44c6867216662d5eeb5f", "checksums": {"385ea5490c86570c7de71070bce9384a": {"url": "https://s3.amazonaws.com/opscode-platform-production-data/organization-(...)", "needs_upload":true}, "f6f73175e979bd90af6184ec277f760c"=> {"url": "https://s3.amazonaws.com/opscode-platform-production-data/organization-(...)", "needs_upload":true}, "2e03dd7e5b2e6c8eab1cf41ac61396d5": {"url": "https://s3.amazonaws.com/opscode-platform-production-data/organization-(...)", "needs_upload":true} }, "sandbox_id"=>"eff7b6f8b3ef44c6867216662d5eeb5f" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. A hash that maps each checksum to a hash that contains a boolean `needs_upload` field and a URL if `needs_upload` is set to `true`. | | `400` | Bad request. The object has already been committed or one (or more) of the objects were not properly uploaded. The payload does not contain a well-formed `checksums` parameter that is a hash containing a key for each checksum. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /sandboxes/ID Each sandbox has a unique identifier. The `/sandboxes/ID` endpoint has the following methods: `PUT`. #### PUT The `PUT` method is used to commit files that are in a sandbox to their final location so that changes to cookbooks will not require re-uploading the same data. This method has no parameters. **Request** ``` PUT /organizations/NAME/sandboxes/ID ``` with a request body similar to: ``` {"is_completed":true} ``` **Response** The response is similar to: ``` { "guid": guid, "name": guid, "checksums": {"385ea5490c86570c7de71070bce9384a": {"url": "https://s3.amazonaws.com/opscode-platform-production-data/organization-(...)", "needs_upload":true} }, "create_time": <get an example of time format>, "is_completed": true } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /search Search indexes allow queries to be made for any type of data that is indexed by the Chef Infra Server, including data bags (and data bag items), environments, nodes, and roles. A defined query syntax is used to support search patterns like exact, wildcard, range, and fuzzy. A search is a full-text query that can be done from several locations, including from within a recipe, by using the `search` subcommand in knife, the `search` method in the Chef Infra Language, the search box in the Chef management console, and by using the `/search` or `/search/INDEX` endpoints in the Chef Infra Server API. The search engine is based on Elasticsearch and is run from the Chef Infra Server. The `/search` endpoint allows nodes, roles, data bags, environments to be searched. This endpoint has the following methods: `GET`. Note At the end of every Chef Infra Client run, the node object is saved to the Chef Infra Server. From the Chef Infra Server, each node object is then added to the Apache Solr search index. This process is asynchronous. By default, node objects are committed to the search index every 60 seconds or per 1000 node objects, whichever occurs first. Note This endpoint does not have any ACL restrictions, which means it may be used by any user or client that is able to make the request to the Chef Infra Server. #### GET The `GET` method is used to return a data structure that contains links to each available search index. By default, the `role`, `node`, `client`, and `data bag` indexes will always be available (where the `data bag` index is the name of the data bag on the Chef Infra Server). Search indexes may lag behind the most current data at any given time. If a situation occurs where data needs to be written and then immediately searched, an artificial delay (of at least 10 seconds) is recommended. This method has no parameters. **Request** ``` GET /organizations/NAME/search ``` This method has no request body. **Response** The response is similar to: ``` { "node": "https://chef.example/organizations/org1/search/node", "role": "https://chef.example/organizations/org1/search/role", "client": "https://chef.example/organizations/org1/search/client", "users": "https://chef.example/organizations/org1/search/users" } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | ### /search/INDEX Use the `/search/INDEX` endpoint to access the search indexes on the Chef Infra Server. The `/search/INDEX` endpoint has the following methods: `GET` and `POST`. A search query is comprised of two parts: the key and the search pattern. A search query has the following syntax: ``` key:search_pattern ``` where `key` is a field name that is found in the JSON description of an indexable object on the Chef Infra Server (a role, node, client, environment, or data bag) and `search_pattern` defines what will be searched for, using one of the following search patterns: exact, wildcard, range, or fuzzy matching. Both `key` and `search_pattern` are case-sensitive; `key` has limited support for multiple character wildcard matching using an asterisk ("*") (and as long as it is not the first character). #### GET The `GET` method is used to return all of the data that matches the query in the `GET` request. This method has the following parameters: | Parameter | Description | | --- | --- | | `q` | The search query used to identify a list of items on a Chef Infra Server. This option uses the same syntax as the `knife search` subcommand. | | `rows` | The number of rows to be returned. | | `start` | The row at which return results begin. | **Request** ``` GET /organizations/NAME/search/INDEX ``` **Response** The response contains the total number of rows that match the request and for a node index search is similar to: ``` { "total": 1, "start": 0, "rows": [ { "automatic": {"hardware_type": "laptop"}, "chef_environment": "_default", "chef_type": "node", "default": {} "json_class": "Chef::Node", "name": "latte", "normal": {}, "override": {"hardware_type": "laptop"}, "run_list": ["recipe[unicorn]"] } ] } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### POST A partial search query allows a search query to be made against specific attribute keys that are stored on the Chef Infra Server. A partial search query can search the same set of objects on the Chef Infra Server as a full search query, including specifying an object index and providing a query that can be matched to the relevant index. While a full search query will return an array of objects that match (each object containing a full set of attributes for the node), a partial search query will return only the values for the attributes that match. One primary benefit of using a partial search query is that it requires less memory and network bandwidth while Chef Infra Client processes the search results. The attributes to be returned by the partial search are specified in the request JSON body. This method has the following parameters: | Parameter | Description | | --- | --- | | `q` | The search query used to identify a list of items on a Chef Infra Server. This option uses the same syntax as the `search` subcommand. | | `rows` | The number of rows to be returned. | | `start` | The row at which return results begin. | **Request** ``` POST /organizations/NAME/search ``` with a request body similar to: ``` { "name": [ "name" ], "ip": [ "ipaddress" ], "kernel_version": [ "kernel", "version" ] } ``` **Response** The response is similar to: ``` { "total":1, "start":0, "rows": [ { "url": "https://chef.example/organization/org1/nodes/latte", "data": { "name": "latte", "ip": "123.4.5.6789", "kernel_version": {"linux": "1.2.3"} } } ] } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `413` | Request entity too large. A request may not be larger than 1000000 bytes. | ### /universe Use the `/universe` endpoint to retrieve the known collection of cookbooks, and then use it with Berkshelf and Chef Supermarket. The `/universe` endpoint has the following methods: `GET`. #### GET The `GET` method is used to retrieve the universe data. This method has no parameters. This method has no request body. **Request** ``` GET /universe ``` **Response** The response will return a json hash, with the name of each cookbook as a top-level key. Each cookbook will list each version, along with its location information and dependencies: ``` { "ffmpeg": { "0.1.0": { "location_path": "http://supermarket.chef.io/api/v1/cookbooks/ffmpeg/0.1.0/download", "location_type": "supermarket", "dependencies": { "git": ">= 0.0.0", "build-essential": ">= 0.0.0", "libvpx": "~> 0.1.1", "x264": "~> 0.1.1" } }, "0.1.1": { "location_path": "http://supermarket.chef.io/api/v1/cookbooks/ffmpeg/0.1.1/download", "location_type": "supermarket", "dependencies": { "git": ">= 0.0.0", "build-essential": ">= 0.0.0", "libvpx": "~> 0.1.1", "x264": "~> 0.1.1" } } }, "pssh": { "0.1.0": { "location_path": "http://supermarket.chef.io/api/v1/cookbooks/pssh.1.0/download", "location_type": "supermarket", "dependencies": {} } } } ``` | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. One (or more) cookbooks and associated cookbook version information was returned. | ### /updated_since The `/updated_since` endpoint ensures that replica instances of the Chef Infra Server are able to synchronize with the primary Chef Infra Server. `/updated_since` was part of the Chef Replication product. Chef Replication is no longer available as a product and the `/updated_since` endpoint is also deprecated. The expectation for almost all chef users is that use of the endpoint will return an http status of 404. The `/organizations/NAME/updated_since` endpoint has the following methods: `GET`. Warning This update is available after Chef replication is installed on the Chef Infra Server. #### GET The `GET` method is used to return the details of an organization as JSON. **Request** ``` GET /organizations/NAME/updated_since?seq=NUM ``` where `NUM` is the largest integer previously returned as an identifier. **Response** The response will return an array of paths for objects that have been created, updated, or deleted since `NUM`, similar to: ``` [ { "action": "create", "id": 1, "path": "/roles/foo" }, { "action": "create", "id": 2, "path": "/roles/foo2" }, { "action": "create", "id": 3, "path": "/roles/foo3" }, { "action": "update", "id": 4, "path": "/roles/foo3" } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name, and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist or the function is not implemented. | ### /users A user may be associated with an organization. The `/users` endpoint has the following methods: `GET` and `POST`. #### GET The `GET` method is used to return an array of usernames for users associated with an organization. This method has no parameters. **Request** ``` GET /organizations/NAME/users ``` This method has no request body. **Response** The response is similar to: ``` [ { "user": { "username": "paperlatte" } } ] ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | #### POST The `POST` method is used to associate a user with an organization immediately. Superuser only. This method has no parameters. **Request** ``` POST /organizations/NAME/users ``` with a request body similar to: ``` { "username": "paperlatte", } ``` where `username` is the name of the user to be associated. **Response** No response block is returned. **Response Codes** | Response Code | Description | | --- | --- | | `201` | Created. The user was associated with the organization. | | `400` | Bad request. The contents of the request are not formatted correctly. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `409` | Conflict. The user is already associated. | ### /users/NAME The `/users/NAME` endpoint has the following methods: `DELETE`, `GET`. #### DELETE The `DELETE` method is used to delete a user association with an organization. This method has no parameters. **Request** ``` DELETE /organizations/NAME/users/NAME ``` **Response** The response will return the end state of the user, similar to: ``` { "username": "paperlatte" "email": "latte", "display_name": "<NAME>", "first_name": "Paper", "last_name": "Latte", "public_key": "-----BEGIN PUBLIC KEY----- ... " } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. The user association was removed. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | #### GET The `GET` method is used to return the details of a user as JSON. This method has no parameters. **Request** ``` GET /organizations/NAME/users/NAME ``` **Response** The response is similar to: ``` { "username": "paperlatte" "email": "latte", "display_name": "<NAME>", "first_name": "Paper", "last_name": "Latte", "public_key": "-----BEGIN PUBLIC KEY----- ... " } ``` **Response Codes** | Response Code | Description | | --- | --- | | `200` | OK. The request was successful. | | `401` | Unauthorized. The user or client who made the request could not be authenticated. Verify the user/client name and that the correct key was used to sign the request. | | `403` | Forbidden. The user who made the request is not authorized to perform the action. | | `404` | Not found. The requested object does not exist. | Examples -------- The following sections show examples of using the Chef Infra Server API. ### Query for Users and Orgs The following example shows how to query the Chef Infra Server API for a listing of organizations and users. The `/organizations` and `/users` endpoints may only be accessed by the `pivotal` user, which is a user account that is created by Chef during the installation of the Chef Infra Server. Run the following from a `.chef` directory that contains a `pivotal.rb` file: ``` require 'chef' require 'chef/server_api' Chef::Config.from_file('.chef/pivotal.rb') rest = Chef::ServerAPI.new(Chef::Config[:chef_server_url]) orgs = rest.get('/organizations') puts "\n=== Listing of organizations" orgs.each do |org| puts org end puts "\n=== Listing of Users" users = rest.get('/users') users.each do |user| puts user end ``` An example of a `.chef/pivotal.rb` file is shown below: ``` current_dir = File.dirname(__FILE__) node_name 'pivotal' chef_server_url 'https://192.0.2.0:443' chef_server_root 'https://192.0.2.0:443' client_key "#{current_dir}/pivotal.pem" ``` Note The `pivotal.pem` file must exist in the specified location and the IP addresses must be correct for the Chef Infra Server. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/api_chef_server/command resource ================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/command.md) Use the `command` Chef InSpec audit resource to test an arbitrary command that is run on the system. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `command` resource block declares a command to be run, one (or more) expected values, and the location to which that output is sent: ``` describe command('command') do it { should exist } its('property') { should eq 'value' } end ``` where * `'command'` must specify a command to be run * `'property'` is one of `exit_status`, `stderr`, or `stdout` * `'output'` tests the output of the command run on the system versus the output value stated in the test Property Examples ----------------- The following examples show how to use this Chef InSpec audit resource. ### exit_status The `exit_status` property tests the exit status for the command: ``` its('exit_status') { should eq 123 } ``` ### stderr The `stderr` property tests results of the command as returned in standard error (stderr): ``` its('stderr') { should eq 'error' } ``` ### stdout The `stdout` property tests results of the command as returned in standard output (stdout). The following example shows matching output using a regular expression: ``` describe command('echo 1') do its('stdout') { should match (/[0-9]/) } end ``` ### Test standard output (stdout) ``` describe command('echo hello') do its('stdout') { should eq "hello\n" } its('stderr') { should eq '' } its('exit_status') { should eq 0 } end ``` ### Test standard error (stderr) ``` describe command('>&2 echo error') do its('stdout') { should eq '' } its('stderr') { should eq "error\n" } its('exit_status') { should eq 0 } end ``` ### Test an exit status code ``` describe command('exit 123') do its('stdout') { should eq '' } its('stderr') { should eq '' } its('exit_status') { should eq 123 } end ``` ### Test if the command shell exists ``` describe command('/bin/sh').exist? do it { should eq true } end ``` ### Test for a command that should not exist ``` describe command('this is not existing').exist? do it { should eq false } end ``` ### Test for PostgreSQL database running a RC, development, or beta release ``` describe command('psql -V') do its('stdout') { should eq '/RC/' } its('stdout') { should_not eq '/DEVEL/' } its('stdout') { should_not eq '/BETA/' } end ``` ### Verify NTP The following example shows how to use the `file` audit resource to verify if the `ntp.conf` and `leap-seconds` files are present, and then the `command` resource to verify if NTP is installed and running: ``` describe file('/etc/ntp.conf') do it { should be_file } end describe file('/etc/ntp.leapseconds') do it { should be_file } end describe command('pgrep ntp') do its('exit_status') { should eq 0 } end ``` ### Verify WiX Wix includes several tools – such as `candle` (preprocesses and compiles source files into object files), `light` (links and binds object files to an installer database), and `heat` (harvests files from various input formats). The following example uses a whitespace array and the `file` audit resource to verify if these three tools are present: ``` %w( candle.exe heat.exe light.exe ).each do |utility| describe file("C:/wix/##{utility}") do it { should be_file } end end ``` ### Timing Out Long-Running Commands On target platforms that support the feature, the command resource takes an optional `timeout:` parameter which specifies how long the command may run in seconds before erroring out and failing the control. ``` describe command("find / -owner badguy", timeout: 300) do its("stdout") { should be_empty } end ``` This example would run the `find` command for up to 300 seconds, then give up and fail the control if it exceeded that time. On supported target platforms, the default timeout is 3600 seconds (one hour). Aside from setting the value on a per-resource basis, you may also use the `--command-timeout` CLI option to globally set a command timeout. The CLI option takes precedence over any per-resource `timeout:` options. Currently supported target platforms include: * Local Unix-like OSes, including macOS * SSH targets * Windows targets via WinRM Any target platforms not listed are not supported at this time. On unsupported platforms, the timeout value is ignored and the command will run indefinitely. ### Redacting Sensitive Commands By default the command that is ran is shown in the Chef InSpec output. This can be problematic if the command contains sensitive arguments such as a password. These sensitive parts can be redacted by passing in `redact_regex` and a regular expression to redact. Optionally, you can use 2 capture groups to fine tune what is redacted. The following examples show how to use `redact_regex`: ``` # Example without capture groups describe command('myapp -p secretpassword -d no_redact', redact_regex: /-p .* -d/) do its('exit_status') { should cmp 0 } end # Result (no capture groups used) Command: `myapp REDACTED no_redact` ✔ exit_status should cmp == 0 # Example with capture groups # Each set of parenthesis is a capture group. # Anything in the two capture groups will not be 'REDACTED' describe command('myapp -p secretpassword -d no_redact', redact_regex: /(-p ).*( -d)/) do its('exit_status') { should cmp 0 } end # Result (capture groups used) Command: `myapp -p REDACTED -d no_redact` ✔ exit_status should cmp == 0 ``` For more info/help on regular expressions, we recommend [RegExr](https://regexr.com/) Matchers -------- For a full list of available matchers, please visit our [matchers page](../matchers/index). ### exist The `exist` matcher tests if a command may be run on the system: ``` it { should exist } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/commandChef InSpec Universal Matchers Reference ======================================== [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/matchers.md) Chef InSpec uses matchers to help compare resource values to expectations. The following matchers are available: You may also use any matcher provided by [RSpec::Expectations](https://relishapp.com/rspec/rspec-expectations/docs), but those matchers are outside of InSpec’s [scope of support](inspec_and_friends/index#rspec). The following InSpec-supported universal matchers are available: * [`be`](#be) - make numeric comparisons * [`be_in`](#be_in) - look for the property value in a list * [`cmp`](#cmp) - general-use equality (try this first) * [`eq`](#eq) - type-specific equality * [`include`](#include) - look for an expected value in a list-valued property * [`match`](#match) - look for patterns in text using regular expressions See [Explore Chef InSpec resources](https://learn.chef.io/modules/explore-inspec-resources#/) on Learn Chef Rally to learn more about InSpec’s built-in matchers. be -- This matcher can be followed by many different comparison operators. Always make sure to use numbers, not strings, for these comparisons. ``` describe file('/proc/cpuinfo') do its('size') { should be >= 10 } its('size') { should be < 1000 } end ``` cmp --- Unlike `eq`, `cmp` is a matcher for less-restrictive comparisons. It will try to fit the actual value to the type you are comparing it to. This is meant to relieve the user from having to write type-casts and resolutions. ``` describe sshd_config do its('Protocol') { should cmp 2 } end describe passwd.uid(0) do its('users') { should cmp 'root' } end ``` `cmp` behaves in the following way: * Compare strings to numbers ``` describe sshd_config do # Only `'2'` works its('Protocol') { should eq '2' } # Both of these work its('Protocol') { should cmp '2' } its('Protocol') { should cmp 2 } end ``` * String comparisons are not case-sensitive ``` describe auditd_conf do its('log_format') { should cmp 'raw' } its('log_format') { should cmp 'RAW' } end ``` * Recognize versions embedded in strings ``` describe package('curl') do its('version') { should cmp > '7.35.0-1ubuntu2.10' } end ``` * Compare arrays with only one entry to a value ``` describe passwd.uids(0) do its('users') { should cmp 'root' } its('users') { should cmp ['root'] } end ``` * Single-value arrays of strings may also be compared to a regex ``` describe auditd_conf do its('log_format') { should cmp /raw/i } end ``` * Improved printing of octal comparisons ``` describe file('/proc/cpuinfo') do its('mode') { should cmp '0345' } end expected: 0345 got: 0444 ``` eq -- Test for exact equality of two values. ``` describe sshd_config do its('RSAAuthentication') { should_not eq 'no' } its('Protocol') { should eq '2' } end ``` `eq` fails if types don’t match. Please keep this in mind, when comparing configuration entries that are numbers: ``` its('Port') { should eq '22' } # ok its('Port') { should eq 22 } # fails: '2' != 2 (string vs int) ``` For less restrictive comparisons, please use `cmp`. include ------- Verifies if a value is included in a list. ``` describe passwd do its('users') { should include 'my_user' } end ``` be_in ------ Verifies that an item is included in a list. ``` describe resource do its('item') { should be_in LIST } end ``` match ----- Check if a string matches a regular expression. ``` describe sshd_config do its('Ciphers') { should_not match /cbc/ } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/matchersparse_config_file resource ============================ [[edit on GitHub]](https://github.com/inspec/inspec/tree/main/docs-chef-io/content/inspec/resources/parse_config_file.md) Use the `parse_config_file` Chef InSpec audit resource to test arbitrary configuration files. It works in the same way as `parse_config`. Instead of using a command output, this resource works with files. Availability ------------ ### Installation This resource is distributed along with Chef InSpec itself. You can use it automatically. ### Version This resource first became available in v1.0.0 of InSpec. Syntax ------ A `parse_config_file` Chef InSpec audit resource block declares the location of the configuration file to be tested, and then which settings in that file are to be tested. ``` describe parse_config_file('/path/to/file', { data_config_option: value } ) do its('setting') { should eq 1 } end ``` or: ``` options = { assignment_regex: /^\s*([^:]*?)\s*:\s*(.*?)\s*$/, multiple_values: true } describe parse_config_file('path/to/file', options) do its('setting') { should eq 1 } end ``` where each test * Must declare the location of the configuration file to be tested * Must declare one (or more) settings to be tested * May run a command to `stdout`, and then run the test against that output * May use options to define how configuration data is to be parsed ### Option Names Containing Periods A possible behavior may occur when attempting to access option names containing periods with `its()`. There are two ways to work around it: * Access the option by using the `params` attribute of the returned resource object * Since 4.24.5, `its` can be used by passing the option name in a single-element array. See the `parse config file` examples. Options ------- This resource supports multiple options to parse configuration data. Use the options in an `options` block stated outside of (and immediately before) the actual test. For example: ``` options = { assignment_regex: /^\s*([^:]*?)\s*:\s*(.*?)\s*$/, multiple_values: true } describe parse_config_file('path/to/file', options) do its('setting') { should eq 1 } end ``` ### assignment_regex Use `assignment_regex` to test a key value using a regular expression: ``` 'key = value' ``` may be tested using the following regular expression, which determines assignment from key to value: ``` assignment_regex: /^\s*([^=]*?)\s*=\s*(.*?)\s*$/ ``` ### comment_char Use `comment_char` to test for comments in a configuration file: ``` comment_char: '#' ``` ### key_values Use `key_values` to test how many values a key contains: ``` key = a b c ``` contains three values. To test that value to ensure it only contains one, use: ``` key_values: 1 ``` ### multiple_values Use `multiple_values` if the source file uses the same key multiple times. All values will be aggregated in an array: ``` # # file structure: # key = a # key = b # key2 = c params['key'] = ['a', 'b'] params['key2'] = ['c'] ``` To use plain key value mapping, use `multiple_values: false`: ``` # # file structure: # key = a # key = b # key2 = c params['key'] = 'b' params['key2'] = 'c' ``` ### standalone_comments Use `standalone_comments` to parse comments as a line, otherwise inline comments are allowed: ``` 'key = value # comment' params['key'] = 'value # comment' ``` Use `standalone_comments: false`, to parse the following: ``` 'key = value # comment' params['key'] = 'value' ``` Matchers -------- For a full list of available matchers, please visit our [matchers page](../matchers/index). Examples -------- The following examples show how to use this Chef InSpec audit resource. ### Test A Configuration Setting ``` describe parse_config_file('/path/to/file.conf') do its('PARAM_X') { should eq 'Y' } end ``` ### Use Options And Then Test A Configuration Setting ``` describe parse_config_file('/path/to/file.conf', { multiple_values: true }) do its('PARAM_X') { should include 'Y' } end ``` ### Test A File With An INI File Structure `yum.conf` is one example of an INI file structure type. ``` describe parse_config_file('/path/to/yum.conf') do its('main') { should include('gpgcheck' => '1') } end ``` ### Test A Configuration Setting Containing Periods ``` describe parse_config_file('/etc/sysctl.conf') do its(['kernel.domainname']) { should eq 'example.com' } end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/inspec/resources/parse_config_fileUpgrade Lab: Chef Infra Client 12 to latest =========================================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/upgrade_lab.md) Chef Software’s Upgrade Lab provides an isolated cookbook development environment and in-line support to help you upgrade your system, so you can stop using legacy Chef Infra and start using modern Chef Infra. The Upgrade Lab provides a report of your existing nodes and cookbooks, so you will know the scope of the work and you can identify a good place to start. Upgrade Lab works by capturing any node from the production environment and recreating it locally by generating a repository for that node, which provides you with a sandbox to work through upgrading and testing your cookbooks at a safe distance from your production environment. About This Guide ---------------- This guide covers the straightforward pattern of upgrading from Chef Infra Client 12 to Chef Infra Client 16, including upgrading Chef Infra Server as you go. While we think this guide is the smoothest path forward, it is not meant to exclude other approaches. Unless otherwise indicated, you will run all commands in your local development environment. Note This guide illustrates the basic case of upgrading a single node in isolation, including migrating the node from one Chef Infra Server to a new Chef Infra Server. More complex situations, such as those involving pooled nodes using Chef Infra Server search for peer discovery, are not covered here. Please contact your Customer Success team for more complex cases. Chef Upgrade Lab Requirements ----------------------------- ### System Architecture Requirements The Chef Upgrade Lab makes some basic assumptions about your existing system: * Two Chef Infra Servers + A Chef Infra Server running some older version + A newly installed Chef Infra Server running the latest software, set up and configured for knife, but otherwise empty * One or more nodes + Running Chef Infra Client 12 or later + Minimum 512 MB RAM + [Recommended](../chef_system_requirements/index#chef-infra-client) 5GB space + Bootstrapped to the older Chef Infra Server + `sudo` permissions on the node + SSH connectivity between the nodes and the administrator/developer workstation * An administrator/developer workstation + 64-bit architecture + Minimum 4 GB RAM + Recommended 10 GB of available disk space for installing Chef Workstation and running the Chef Upgrade Lab ### Software Requirements * Review the [platform and system requirements](install_workstation/index) for Chef Workstation * Install or upgrade to the Chef Workstation [latest version](https://www.chef.io/downloads/tools/workstation) Chef does not prescribe any specific editor. However, the [Chef Infra extension](https://marketplace.visualstudio.com/items?itemName=chef-software.Chef) for [Visual Studio Code](https://code.visualstudio.com/) features several code generators and helpful features, such as running Cookstyle each time you save a recipe. ### Server Backup We recommend performing a backup before starting any server upgrade process. Follow the [Chef Infra Server Backup](../runbook/server_backup_restore/index) documentation before starting your Upgrade Lab. ### Infrastructure Requirements #### Credentials Your credentials are set up using [knife profiles](knife_setup/index#knife-profiles). This method allows you to keep your keys in a `credentials` file, and makes switching between credentials easier. For example, in `.chef/credentials`: ``` [old-server] client_name = "user_name" chef_server_url = "https://old-chef-server.dev/organizations/my-org" client_key = """ -----BEGIN RSA PRIVATE KEY----- MMM+some+key+goes+here+MMM -----END RSA PRIVATE KEY----- """ [new-server] client_name = "user_name" chef_server_url = "https://new-chef-server.dev/organizations/my-org" client_key = """ -----BEGIN RSA PRIVATE KEY----- MMM+another+key+goes+here+MMM -----END RSA PRIVATE KEY----- """ ``` #### Connectivity You must have a user key for both of the Chef Infra Servers and you must be able to connect to both Chef Infra Servers from your development workstation. Verify connectivity by running a `knife` command and receiving a reasonable response from each server: ``` chef exec knife user list --profile old-server user_name chef exec knife user list --profile new-server user_name ``` #### Convergence Your nodes are in a good working order. They converge cleanly under the older version of Chef Infra Client. Verify that the nodes are healthy by running: ``` chef exec knife status --profile old-server ``` The output should look similar to: ``` 42 minutes ago, node-01, ubuntu 18.04. ``` This command outputs the time of the last successful Chef Infra Client run of each node. Nodes that return radically different times for the last successful Chef Infra Client run are not in good working order. #### Cookbook CI/CD While we do not prescribe a particular choice of technology or the details of processes, the Chef Upgrade Lab expects a continuous integration pipeline and continuous delivery system (CI/CD) for cookbook deployments. The Upgrade Lab assumes but does not require that you have a continuous integration pipeline (CI) setup for your cookbooks with: * A version control system (for example, git) * Some degree of automated testing for proposed changes * A continuous delivery system (CD) that controls cookbook releases; the CD is the mechanism for updating cookbook versions and uploading them to the Chef Infra Server(s) If you do not have a version control system and CI/CD pipeline in place, then please contact your account team for help or find us at [<EMAIL>](mailto:<EMAIL>). You can also ask questions in the Chef community channels: * Chef Community Slack at <https://community-slack.chef.io/>. * Chef Mailing List <https://discourse.chef.io/ Upgrade Lab ----------- ### Inventory Your System with Chef Reports We recommend starting the upgrade process on a node with a simple setup, such as one with fewer and simpler cookbooks. The `chef report` command surveys your nodes and cookbooks. Use the reports to identify a good starting place. #### chef report nodes The `chef report nodes -p PROFILE` command will: * create a report of the nodes in your system from Ohai data * print a report summary to the screen * save the report to the `.chef-workstation/reports/` directory Create a node report from your development workstation by running: ``` chef report nodes -p old-server ``` Which outputs a node report: ``` Analyzing nodes... -- REPORT SUMMARY -- Node Name Chef Version Operating System Number Cookbooks --------------------------------+--------------+---------------------+------------------- node-01 12.22.5 windows v10.0.14393 18 node-02 12.22.5 windows v10.0.14393 18 node-03 12.22.5 windows v10.0.14393 5 node-04 12.18.31 windows v6.3.9600 5 Nodes report saved to /Users/user_name/.chef-workstation/reports/nodes-20200324135111.txt ``` #### chef report cookbooks The `chef report cookbooks -p PROFILE` command will: * create a report of the cookbooks in your system from Ohai data * print a report summary to the screen * save the report to the `.chef-workstation/reports/` directory This report shows that there are two cookbooks on the server. It analyzes the cookbooks, looking for cookbook issues that will be problematic in later versions of the Chef Infra Client by running the `cookstyle` program. Here, we see that the `cron` cookbook has a single violation, and which can be auto-corrected by `cookstyle`. Create a cookbook report from your development workstation by running: ``` chef report cookbooks -V -p old-server ``` Which outputs a cookbook report: ``` Cookbook Version Violations Auto-correctable Nodes Affected -----------------------+---------+------------+------------------+----------------- cron 1.7.5 1 1 1 upgrade_labs_problems 0.1.0 2 2 1 Cookbooks report saved to /Users/user_name/.chef-workstation/reports/cookbooks-20200504155204.txt ``` ### Create an Upgrade Environment with chef capture The `chef capture NODE` command will: * Create a repository for that node in the current directory * Help you obtain and organize the cookbooks you need to converge the node * Create a `kitchen.yml`, which allows you to use Test Kitchen to perform local development Run the command: ``` chef capture NODE ``` The screen output describes the capture process: ``` - Setting up local repository - Capturing node object '' - Capturing cookbooks... - Capturing environment... - Capturing roles... - Writing kitchen configuration... Repository has been created in './node-NODE-repo'. ``` #### Add Cookbook Source Locations After creating the repo, `chef capture NODE` prompts you to fetch the cookbooks from their original locations. Upgrading a node means upgrading its cookbooks so that it can run the latest version of Chef Infra Client. Ideally, you can get the cookbooks from their canonical source (that is, `git clone` or another similar version control operation). If you are working with a version control system, you can make and test your changes locally and then push the changes back to the cookbook’s source. This fully leverages the benefits of your cookbook CI/CD pipeline by allowing your changes to go through proper version control, peer review, automated testing, and automated deployment. If you can’t locate a cookbook, do not download it from an external source, such as the public Chef Supermarket. The cookbook version in your development environment must match the version on your node. [As a last resort](#download-cookbooks-from-chef-infra-server), the Upgrade Lab can get copies of your cookbooks from the Chef Infra Server during the `capture` phase. Likely cookbook locations: * Checked into your version control system * On a private Supermarket installation * In an existing [cookbook development directory](#main-cookbook-development-location) **Cookbook Directory Layout** If you have access to cookbook sources, storing cookbooks in one parent directory is easier, similar to this: ``` /Users/user_name/my_cookbooks/ --- cron -- .git/ # Or other version control bookkeeping -- recipes/ -- ... -- metadata.rb --- chef-client -- .cvs/ # Or other version control bookkeeping -- recipes/ -- ... -- metadata.rb --- my_custom_cookbook -- .git/ # Or other version control bookkeeping -- recipes/ -- ... -- metadata.rb ``` The Upgrade Lab works if you have cookbooks in different locations, but it involves more prompting from the command line. #### Main Cookbook Development Location The `chef capture` command prompts you first for your main cookbook source location: ``` Next, locate version-controlled copies of the cookbooks. This is important so that you can track changes to the cookbooks as you edit them. You may have one or more existing paths where you have checked out cookbooks. If not, now is a good time to open a separate terminal and clone or check out the cookbooks. If all cookbooks are not available in the same base location, you will have a chance to provide additional locations. Press Enter to Continue: Please clone or check out the following cookbooks locally from their original sources, and provide the base path for the checkout: - cron (v1.6.1) - chef-client (v4.3.0) - logrotate (v1.9.2) - windows (v1.44.1) - chef_handler (v1.4.0) If sources are not available for these cookbooks, leave this blank. Checkout Location [none]: ``` At this point, enter the path to your cookbook development directory, for example, `/Users/user_name/my_cookbooks` at the prompt. `chef capture` scans that path and locates the cookbooks that it needs. The command finishes once it accounts for all cookbook sources; but if any are missing, it will prompt for them in the next step. ``` Checkout Location [none]: /src/my_cookbooks Using your checked-out cookbook: cron using your checked-out cookbook: chef-client ``` **Alternate Cookbook Source Locations** Suppose that your node requires 5 cookbooks: * `cron` (v1.6.1) * `chef-client` (v4.3.0) * `logrotate` (v1.9.2) * `windows` (v1.44.1) * `chef_handler` (v1.4.0) If the directory you provided in the initial prompt contains only `cron` and `chef-client`, then `chef capture` prompts you to add the locations for sources for the remaining three: ``` Please provide the base checkout path for the following cookbooks, or leave blank if no more cookbooks are checked out: - logrotate (v1.9.2) - windows (v1.44.1) - chef_handler (v1.4.0) Checkout Location [none]: ``` `chef capture` scans the path that you provide and locates the cookbooks that it needs. The command finishes once it accounts for all cookbook sources; it prompts you for another path if it needs more cookbook sources. ### Download Cookbooks from Chef Infra Server If you do not have access to the original version-controlled source of a cookbook, press return at the prompt for `chef capture` to use a copy of the cookbook downloaded from the Chef Infra Server. Upgrading cookbooks from the Chef Infra Server is not an ideal practice. You will make changes to your cookbooks during the course of the upgrade. Making changes to your cookbooks without the ability to track your changes in version control almost inevitably leads to conflicts between cookbook sources. Reconciling cookbooks with untracked changes is a difficult and time-consuming process. If you find yourself using many cookbooks–or complex cookbooks–downloaded from the Chef Infra Server, it will be worth the effort in the long run to try to track down their version-controlled sources. Tracking and testing changes in a CI/CD pipeline is an important part of managing your Chef infrastructure, but are beyond the scope of this guide. See [Learn Chef Rally](https://learn.chef.io/) for tutorials and contact your Customer Success team when you are ready to modernize your system. ``` ------------------------ WARNING --------------------------- Changes made to the following cookbooks in ./node-MY_NODE-repo/cookbooks cannot be saved to the cookbook's source, though they can still be uploaded to a Chef Server: - logrotate (v1.9.2) - windows (v1.44.1) - chef_handler (v1.4.0) ----------------------------------------------------------- You're ready to begin! Start with 'kitchen converge'. As you identify issues, you can modify cookbooks in their original checkout locations or in the repository's cookbooks directory and they will be picked up on subsequent runs of 'kitchen converge'. ``` Detect and Correct Cookbook Errors ---------------------------------- Note Be cautious when running your cookbooks locally. It is possible to accidentally impact production infrastructure based on settings in your cookbooks and attributes. Read over your cookbooks and attributes, especially attributes set in roles and environments. If needed, override attributes so they can be tested locally in your `kitchen.yml`. ### Increment the Chef Infra Client Version In the `kitchen.yml` file, change the `product_version` line to `16`: ``` provisioner:name:chef_zeroproduct_name:chefproduct_version:16# Change this line ``` If needed, you can “step forward” versions by first going from 12 to 13, correcting any issues, and then incrementing from 13 to 14, etc. until you reach Chef Infra Client 16. ### Attempt a Converge and Check for Errors Save the file and test it in the `node-MY_NODE-repo` directory by running: ``` chef exec kitchen converge ``` Watch for Chef Infra errors. If any occur, fix them. ### Test and Correct with Cookstyle To check for version upgrade issues, run: ``` chef exec cookstyle cookbooks/my_cookbook ``` Repeat this process for each cookbook for that node. #### Using Cookstyle Auto-correct Use Cookstyle’s auto-correct feature to fix style errors by adding the `-a` (for auto-correct) flag: ``` chef exec cookstyle -a cookbooks/my_cookbook ``` Other issues may require manual intervention and editing. Repeat this process for each cookbook that the node consumes. ### Copy Data Bags If your Chef Infra Server uses data bags, you will need to download the `data_bags` directory into your chef repo with the `chef exec knife download data_bags` command. This command does not support embedded keys in credentials files. If you use embedded keys, move the key to a key file. ``` cd node-node-01-repo chef exec knife download data_bags --chef-repo-path . --profile old-server --key my-old-key.pem ``` Deploy Your Chef Lab Upgrades ----------------------------- Note This guide suggests migrating upgraded cookbooks and nodes to a new Chef Infra Server. This pattern is not possible for all customers, specifically those who rely on `chef search` for inventory and coordination. Migrating to a new server works for customers who do not rely on search because it creates a fresh start to build on for future migration to Effortless. If you rely on `knife search`, or setting up a new Chef Infra Server is not possible, upload the upgraded cookbooks to your existing Chef Infra Server. If you do this, be sure to pin your cookbook versions on existing nodes, so that the upgraded cookbook can be manually promoted to desired nodes. ### Commit Your Cookbook Upgrades As you make changes to the cookbooks, follow your organization’s existing software development practices. Commit your changes to your cookbooks and submit your changes to your cookbook pipeline to be tested by your automated testing system. Once the changes have passed testing, the cookbooks should receive new version numbers and be published to the new Chef Infra Server by the continuous deployment system. ### Optionally Upload Your Cookbook Upgrades to the New Server If your organization does not have a cookbook pipeline in place, or if you are setting up a proof of concept, you can directly upload the cookbooks to the new server. We do not recommend this because it makes it difficult to manage changes to cookbook code. This command does not support embedded keys in credentials files, so you must place the key in a key file. ``` cd node-node-01-repo chef exec knife upload cookbooks --chef-repo-path . --profile new-server --key ../keys/my-new-key.pem ``` ### Upload Supplemental Data to the New Server Next, upload the remaining data to the new server. Note that `knife upload` command does not support embedded keys in credentials files, so you must place the key in a key file. #### Node Data If you use node search, upload the node data to the new server: ``` chef exec knife upload nodes --chef-repo-path . --profile new-server --key ../keys/my-new-key.pem ``` #### Roles If you use roles, upload them to the new server: ``` chef exec knife upload roles --chef-repo-path . --profile new-server --key ../keys/my-new-key.pem ``` #### Environments If you use environments, upload them to the new server: ``` chef exec knife upload environments --chef-repo-path . --profile new-server --key ../keys/my-new-key.pem ``` #### Data Bags If you used data bags, upload them to the new server: ``` chef exec knife upload data_bags --chef-repo-path . --profile new-server --key ../keys/my-new-key.pem ``` Attach the Upgraded Node to the New Server ------------------------------------------ ### Issue a new Bootstrap Command Migrate your node to the new server by running a bootstrap command similar to: ``` chef exec knife bootstrap \ --profile new-server --chef-license accept \ -r cookbook::recipe,another_cookbook::recipe \ -N node-01 -y --sudo \ --bootstrap-version 16 \ user@somehost.example ``` Bootstrapping nodes in this way upgrades the installed Chef Infra Client to version 16. Congratulations! Optionally, delete your node record from the old server using: ``` chef exec knife node delete node-01 --profile old-server ``` Repeat as Needed ---------------- Happy Converging! © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/upgrade_labInvalidDefaultAction ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidDefaultAction` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Default actions in resources should be symbols or an array of symbols. ### Examples #### incorrect ``` default_action 'create' ``` #### correct ``` default_action :create ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.13.0 | String | Include | * `**/libraries/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invaliddefaultaction/InvalidNotificationResource =========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidNotificationResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The resource to notify when calling `notifies` or `subscribes` must be a string. ### Examples #### incorrect ``` template '/etc/www/configures-apache.conf' do notifies :restart, service['apache'], :immediately end template '/etc/www/configures-apache.conf' do notifies :restart, service[apache], :immediately end ``` #### correct ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :immediately end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.28 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invalidnotificationresource/InvalidPlatformFamilyHelper =========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidPlatformFamilyHelper` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Pass valid platform families to the `platform_family?` helper. See [Infra Language: Platform Family](../../../infra_language/checking_platforms/index#platform_family-values) for a complete list of platform families. ### Examples #### incorrect ``` platform_family?('redhat') platform_family?('sles') #### incorrect ```ruby platform_family?('rhel') platform_family?('suse') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.15.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invalidplatformfamilyhelper/InvalidPlatformInCase ===================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidPlatformInCase` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use valid platform values in case statements. See [Infra Language: Platform](../../../infra_language/checking_platforms/index#platform-values) for a list of many common platform values. ### Examples #### incorrect ``` case node['platform'] when 'rhel' puts "I'm on a Red Hat system!" end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.6.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invalidplatformincase/Deprecation: Cloud_v2 attribute removal (OHAI-11) ================================================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/deprecations_ohai_cloud_v2.md) In Ohai/Chef Client 13 we replaced the existing Cloud plugin with the Cloud V2 plugin. That was done by having Ohai populate both `node['cloud']` and `node['cloud_v2']` with the data previously found at `node['cloud_v2']`. In Chef Client 14 we will no longer populate `node['cloud_v2']`. Remediation ----------- If you have a cookbook that relies on data from `node['cloud_v2']` you will need to update the code to instead use `node['cloud']` attributes. Keep in mind that if you’re attempting to support Chef < 13 this data will be different. Foodcritic’s FC095 rule will detect any usage of the `node['cloud_v2']` attributes. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/deprecations_ohai_cloud_v2/InvalidPlatformFamilyInCase =========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidPlatformFamilyInCase` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use valid platform family values in case statements. See [Infra Language: Platform Family](../../../infra_language/checking_platforms/index#platform_family-values) for a complete list of platform families. ### Examples #### incorrect ``` case node['platform_family'] when 'redhat' puts "I'm on a RHEL-like system" end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.6.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invalidplatformfamilyincase/InvalidNotificationTiming ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidNotificationTiming` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Valid notification timings are `:immediately`, `:immediate` (alias for :immediately), `:delayed`, and `:before`. ### Examples #### incorrect ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :nope end ``` #### correct ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :immediately end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invalidnotificationtiming/InvalidPlatformHelper ===================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidPlatformHelper` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Pass valid platforms to the `platform?` helper. See [Infra Language: Platform](../../../infra_language/checking_platforms/index#platform-values) for a list of many common platform values. ### Examples #### incorrect ``` platform?('darwin') platform?('rhel) platform?('sles') ``` #### correct ``` platform?('mac_os_x') platform?('redhat) platform?('suse') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.15.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invalidplatformhelper/InvalidPlatformMetadata ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidPlatformMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | metadata.rb `supports` methods should contain valid platforms. See [Infra Language: Platform](../../../infra_language/checking_platforms/index#platform-values) for a list of many common platform values. ### Examples #### incorrect ``` supports 'darwin' supports 'mswin' ``` #### correct ``` supports 'mac_os_x' supports 'windows' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invalidplatformmetadata/InvalidPlatformValueForPlatformFamilyHelper =========================================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidPlatformValueForPlatformFamilyHelper` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Pass valid platform families to the value_for_platform_family helper. See [Infra Language: Platform Family](../../../infra_language/checking_platforms/index#platform_family-values) for a complete list of platform families. ### Examples #### incorrect ``` value_for_platform_family( %w(rhel sles) => 'foo', %w(mac) => 'foo' ) ``` #### correct ``` value_for_platform_family( %w(rhel suse) => 'foo', %w(mac_os_x) => 'foo' ) ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.15.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invalidplatformvalueforplatformfamilyhelper/LazyEvalNodeAttributeDefaults ============================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/LazyEvalNodeAttributeDefaults` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | When setting a node attribute as the default value for a custom resource property, wrap the node attribute in `lazy {}` so that its value is available when the resource executes. ### Examples #### incorrect ``` property :Something, String, default: node['hostname'] ``` #### correct ``` property :Something, String, default: lazy { node['hostname'] } ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.6.0 | String | Include | * `**/libraries/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_lazyevalnodeattributedefaults/InvalidVersionMetadata ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidVersionMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Cookbook metadata.rb version field should follow X.Y.Z version format. ### Examples #### incorrect ``` version '1.2.3.4' ``` #### correct ``` version '1.2.3' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.8.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invalidversionmetadata/InvalidPlatformValueForPlatformHelper ===================================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/InvalidPlatformValueForPlatformHelper` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Pass valid platforms to the value_for_platform helper. See [Infra Language: Platform](../../../infra_language/checking_platforms/index#platform-values) for a list of many common platform values. ### Examples #### incorrect ``` value_for_platform( %w(rhel mac_os_x_server) => { 'default' => 'foo' }, %w(sles) => { 'default' => 'bar' } )``` #### correct ```ruby value_for_platform( %w(redhat mac_os_x) => { 'default' => 'foo' }, %w(opensuseleap) => { 'default' => 'bar' } ) ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.15.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_invalidplatformvalueforplatformhelper/LazyInResourceGuard =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/LazyInResourceGuard` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Using `lazy {}` within a resource guard (not_if/only_if) will cause failures and is unnecessary as resource guards are always lazily evaluated. ### Examples #### incorrect ``` template '/etc/foo' do mode '0644' source 'foo.erb' only_if { lazy { ::File.exist?('/etc/foo')} } end ``` #### correct ``` template '/etc/foo' do mode '0644' source 'foo.erb' only_if { ::File.exist?('/etc/foo') } end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.18.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_lazyinresourceguard/MacosUserdefaultsInvalidType ============================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/MacosUserdefaultsInvalidType` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The macos_userdefaults resource prior to Chef Infra Client 16.3 would silently continue if invalid types were passed resulting in unexpected behavior. Valid values are: “array”, “bool”, “dict”, “float”, “int”, and “string”. ### Examples #### incorrect ``` macos_userdefaults 'set a value' do global true key 'key' type 'boolean' end ``` #### correct ``` macos_userdefaults 'set a value' do global true key 'key' type 'bool' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.14.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_macosuserdefaultsinvalidtype/MalformedPlatformValueForPlatformHelper ======================================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/MalformedPlatformValueForPlatformHelper` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | When using the value_for_platform helper you must include a hash of possible platforms where each platform contains a hash of versions and potential values. If you don’t wish to match on a particular version you can instead use the key ‘default’. ### Examples #### incorrect ``` value_for_platform( %w(redhat oracle) => 'baz' ) ``` #### correct ``` value_for_platform( %w(redhat oracle) => { '5' => 'foo', '6' => 'bar', 'default'd => 'baz', } ) value_for_platform( %w(redhat oracle) => { 'default' => 'foo', }, 'default' => 'bar' ) ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_malformedplatformvalueforplatformhelper/MetadataMissingName =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/MetadataMissingName` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | metadata.rb needs to include the name method or it will fail on Chef Infra Client 12 and later. ### Examples ``` #### correct ```ruby name 'foo' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_metadatamissingname/MetadataMissingVersion ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/MetadataMissingVersion` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | metadata.rb should define a version for the cookbook. ### Examples ``` #### correct ```ruby name 'foo' version '1.0.0' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.25 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_metadatamissingversion/MetadataMalformedDepends ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/MetadataMalformedDepends` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | metadata.rb cookbook dependencies and version constraints should be comma separated. ### Examples #### incorrect ``` depends 'some_awesome_cookbook' '= 4.5.5' depends 'some_other_cool_cookbook' '< 8.0' ``` #### correct ``` depends 'some_awesome_cookbook', '= 4.5.5' depends 'some_other_cool_cookbook', '< 8.0' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.16 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_metadatamalformeddepends/NodeNormal ========== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/NodeNormal` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Normal attributes are discouraged since their semantics differ importantly from the default and override levels. Their values persist in the node object even after all code referencing them has been deleted, unlike default and override. Code should be updated to use default or override levels, but this will change attribute merging behavior so needs to be validated manually and force_default or force_override levels may need to be used in recipe code. ### Examples #### incorrect ``` node.normal['foo'] = true ``` #### correct ``` node.default['foo'] = true node.override['foo'] = true node.force_default['foo'] = true node.force_override['foo'] = true ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_nodenormal/NotifiesActionNotSymbol ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/NotifiesActionNotSymbol` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | When notifying or subscribing actions within a resource the action should always be a symbol. In Chef Infra Client releases before 14.0, this may result in double notification. ### Examples #### incorrect ``` execute 'some command' do notifies 'restart', 'service[httpd]', 'delayed' end execute 'some command' do subscribes 'restart', 'service[httpd]', 'delayed' end ``` #### correct ``` execute 'some command' do notifies :restart, 'service[httpd]', 'delayed' end execute 'some command' do subscribes :restart, 'service[httpd]', 'delayed' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.10.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_notifiesactionnotsymbol/OctalModeAsString ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/OctalModeAsString` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Don’t represent file modes as Strings containing octal values. ### Examples #### incorrect ``` file '/etc/some_file' do mode '0o755' end ``` #### correct ``` file '/etc/some_file' do mode '0755' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.21.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_octalmodeasstring/OpenSSLPasswordHelpers ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/OpenSSLPasswordHelpers` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The OpenSSL cookbook provides a deprecated `secure_password` helper in the `Opscode::OpenSSL::Password` class, which should no longer be used. This helper would generate a random password that would be used when a data bag or attribute was no present. The practice of generating passwords to be stored on the node is bad security as it exposes the password to anyone that can view the nodes, and deleting a node deletes the password. Passwords should be retrieved from a secure source for use in cookbooks. #### incorrect ::Chef::Recipe.send(:include, Opscode::OpenSSL::Password) basic_auth_password = secure_password ### Examples ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.6.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_opensslpasswordhelpers/NodeNormalUnless ================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/NodeNormalUnless` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Normal attributes are discouraged since their semantics differ importantly from the default and override levels. Their values persist in the node object even after all code referencing them has been deleted, unlike default and override. Code should be updated to use default or override levels, but this will change attribute merging behavior so needs to be validated manually and force_default or force_override levels may need to be used in recipe code. ### Examples #### incorrect ``` node.normal_unless['foo'] = true ``` #### correct ``` node.default_unless['foo'] = true node.override_unless['foo'] = true node.force_default_unless['foo'] = true node.force_override_unless['foo'] = true ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_nodenormalunless/PowershellFileExists ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/PowershellFileExists` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Use Ruby’s built-in `File.exist?('C:\somefile')` method instead of executing PowerShell’s `Test-Path` cmdlet, which takes longer to load. ### Examples #### incorrect ``` powershell_out('Test-Path "C:\\Program Files\\LAPS\\CSE\\AdmPwd.dll"').stdout.strip == 'True' ``` #### correct ``` ::File.exist?('C:\Program Files\LAPS\CSE\AdmPwd.dll') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.19 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_powershellfileexists/PropertyWithoutType =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/PropertyWithoutType` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Resource properties or attributes should always define a type to help users understand the correct allowed values. ### Examples #### incorrect ``` property :size, regex: /^\d+[KMGTP]$/ attribute :size, regex: /^\d+[KMGTP]$/ ``` #### correct ``` property :size, String, regex: /^\d+[KMGTP]$/ attribute :size, kind_of: String, regex: /^\d+[KMGTP]$/ ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.18.0 | String | Include | * `**/libraries/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_propertywithouttype/ResourceSetsInternalProperties ============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/ResourceSetsInternalProperties` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Chef Infra Client uses properties in several resources to track state. These should not be set in recipes as they break the internal workings of the Chef Infra Client ### Examples #### incorrect ``` service 'foo' do running true action [:start, :enable] end ``` #### correct ``` service 'foo' do action [:start, :enable] end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_resourcesetsinternalproperties/ResourceSetsNameProperty ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/ResourceSetsNameProperty` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Use name properties instead of setting the name property in a resource. Setting the name property directly causes notification and reporting issues. ### Examples #### incorrect ``` service 'foo' do name 'bar' end ``` #### correct ``` service 'foo' do service_name 'bar' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_resourcesetsnameproperty/PowershellScriptDeleteFile ========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/PowershellScriptDeleteFile` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Use the `file` or `directory` resources built into Chef Infra Client with the :delete action to remove files/directories instead of using Remove-Item in a powershell_script resource #### correct file ‘C:\Windows\foo\bar.txt’ do action :delete end ### Examples #### incorrect ``` powershell_script 'Cleanup old files' do code 'Remove-Item C:\Windows\foo\bar.txt' only_if { ::File.exist?('C:\\Windows\\foo\\bar.txt') } end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.0.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_powershellscriptdeletefile/ResourceWithNoneAction ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/ResourceWithNoneAction` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The :nothing action is often typo’d as :none ### Examples #### incorrect ``` service 'foo' do action :none end ``` #### correct ``` service 'foo' do action :nothing end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_resourcewithnoneaction/SupportsMustBeFloat =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/SupportsMustBeFloat` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Versions used in metadata.rb supports calls should be floats not integers. ### Examples #### incorrect ``` supports 'redhat', '> 8' ``` #### correct ``` supports 'redhat', '> 8.0' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.13.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_supportsmustbefloat/TmpPath ======= [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/TmpPath` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Use file_cache_path rather than hard-coding system temp paths ### Examples #### incorrect ``` remote_file '/tmp/large-file.tar.gz' do ``` #### correct ``` remote_file "#{Chef::Config[:file_cache_path]}/large-file.tar.gz" do ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.0.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_tmppath/ScopedFileExist =============== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/ScopedFileExist` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Scope file exist to access the correct `File` class by using `::File.exist?` not `File.exist?`. ### Examples #### incorrect ``` not_if { File.exist?('/etc/foo/bar') } ``` #### correct ``` not_if { ::File.exist?('/etc/foo/bar') } ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.15.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_scopedfileexist/ServiceResource =============== [All Cookstyle Cops](../cops/index) The department is: `Chef/Correctness` The full name of the cop is: `Chef/Correctness/ServiceResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Use a service resource to start and stop services ### Examples #### incorrect ``` command "/etc/init.d/mysql start" command "/sbin/service/memcached start" ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.0.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_correctness_serviceresource/ChefDKGenerators ================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ChefDKGenerators` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Chef Workstation 0.8 and later renamed the `ChefDK` module used when writing custom cookbook generators from `ChefDK` to `ChefCLI`. For compatibility with the latest Chef Workstation releases you’ll need to reference the new class names. ### Examples #### incorrect ``` ChefDK::CLI ChefDK::Generator::TemplateHelper module ChefDK ... end ``` #### correct ``` ChefCLI::CLI ChefCLI::Generator::TemplateHelper module ChefCLI ... end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.12.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_chefdkgenerators/Cheffile ======== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/Cheffile` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The Librarian-Chef depsolving project is no longer maintained and a Cheffile should not be used for cookbook depsolving. Consider using Policyfiles instead. If the Policyfiles model is not compatible with your workflow you may find Berkshelf offers a more similar, and still supported, experience to Librarian-Chef. ### Examples ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.12.0 | String | Include | * `**/Cheffile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_cheffile/ChefHandlerUsesSupports ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ChefHandlerUsesSupports` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use the type `property` instead of the deprecated `supports` property in the `chef_handler` resource. The `supports` property was removed in `chef_handler` cookbook version 3.0 (June 2017) and Chef Infra Client 14.0. ### Examples #### incorrect ``` chef_handler 'whatever' do supports start: true, report: true, exception: true end0 ``` #### correct ``` chef_handler 'whatever' do type start: true, report: true, exception: true end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.9.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_chefhandlerusessupports/ChefHandlerRecipe ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ChefHandlerRecipe` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | There is no need to include the empty and deprecated chef_handler::default recipe to use the chef_handler resource ### Examples #### incorrect ``` include_recipe 'chef_handler' include_recipe 'chef_handler::default' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.12.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_chefhandlerrecipe/ChefSpecCoverageReport ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ChefSpecCoverageReport` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Don’t use the deprecated ChefSpec Coverage report functionality in your specs. This feature has been removed as coverage reports encourage cookbook authors to write ineffective specs. Focus on testing your logic instead of achieving 100% code coverage. ### Examples #### incorrect ``` at_exit { ChefSpec::Coverage.report! } ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.8.0 | String | Include | * `**/spec/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_chefspeccoveragereport/ChefRewind ========== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ChefRewind` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 12.10+ | Use `delete_resource` or `edit_resource` helpers introduced in Chef Infra Client 12.10 instead of functionality in the deprecated `chef-rewind` gem ### Examples chef_gem ‘chef-rewind’ require ‘chef/rewind’ rewind “user[postgres]” do home ‘/var/lib/pgsql/9.2’ cookbook ‘my-postgresql’ end unwind “user[postgres]” ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.14.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_chefrewind/ChefShellout ============ [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ChefShellout` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Don’t use the deprecated `Chef::ShellOut` class which was removed in Chef Infra Client 13. Use the `Mixlib::ShellOut` class instead, which behaves identically or convert to the simpler `shell_out` helper. ### Examples #### incorrect ``` include Chef::ShellOut require 'chef/shellout' Chef::ShellOut.new('some_command') ``` #### correct ``` include Mixlib::ShellOut require 'mixlib/shellout' Mixlib::ShellOut.new('some_command') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.17.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_chefshellout/ChefSpecLegacyRunner ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ChefSpecLegacyRunner` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use `ChefSpec::SoloRunner` or `ChefSpec::ServerRunner` instead of the deprecated `ChefSpec::Runner`. These new runners were introduced in ChefSpec 4.1 (Oct 2014). ### Examples #### incorrect ``` describe 'foo::default' do subject { ChefSpec::Runner.new.converge(described_recipe) } # some spec code end ``` #### correct ``` describe 'foo::default' do subject { ChefSpec::ServerRunner.new.converge(described_recipe) } # some spec code end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.8.0 | String | Include | * `**/spec/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_chefspeclegacyrunner/ChefSugarHelpers ================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ChefSugarHelpers` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Do not use legacy chef-sugar helper methods, which will not be moved into Chef Infra Client itself. For a complete set of chef-sugar helpers now shipping in Chef Infra Client itself see <https://github.com/chef/chef/tree/main/chef-utils#getting-started ### Examples #### incorrect ``` vagrant_key? vagrant_domain? vagrant_user? require_chef_gem best_ip_for(node) nexus? ios_xr? ruby_20? ruby_19? includes_recipe?('foo::bar') wrlinux? dev_null nexentacore_platform? opensolaris_platform? nexentacore? opensolaris? ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.3.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` * `**/Rakefile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_chefsugarhelpers/ChefWindowsPlatformHelper ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ChefWindowsPlatformHelper` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use `platform?('windows')` instead of the legacy `Chef::Platform.windows?` helper ### Examples #### incorrect ``` Chef::Platform.windows? ``` #### correct ``` platform?('windows') platform_family?('windows') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.0.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_chefwindowsplatformhelper/ChocolateyPackageUninstallAction ================================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ChocolateyPackageUninstallAction` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use the `:remove` action in the `chocolatey_package` resource instead of `:uninstall` which was removed in Chef Infra Client 14+. ### Examples #### incorrect ``` chocolatey_package 'nginx' do action :uninstall end ``` #### correct ``` chocolatey_package 'nginx' do action :remove end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_chocolateypackageuninstallaction/CookbookDependsOnCompatResource =============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/CookbookDependsOnCompatResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 12.19+ | Don’t depend on the deprecated `compat_resource` cookbook made obsolete by Chef Infra Client 12.19+. ### Examples #### incorrect ``` depends 'compat_resource' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_cookbookdependsoncompatresource/CookbookDependsOnPartialSearch ============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/CookbookDependsOnPartialSearch` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 13.0+ | Don’t depend on the `partial_search` cookbook made obsolete by Chef Infra Client 13. ### Examples #### incorrect ``` depends 'partial_search' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_cookbookdependsonpartialsearch/CookbookDependsOnPoise ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/CookbookDependsOnPoise` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Cookbooks should not depend on the deprecated Poise framework cookbooks. They should instead be refactored to use standard Chef Infra custom resources. ### Examples #### incorrect ``` depends 'poise' depends 'poise-service' depends 'poise-hoist' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_cookbookdependsonpoise/DeprecatedChefSpecPlatform ========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/DeprecatedChefSpecPlatform` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use currently supported platforms in ChefSpec listed at <https://github.com/chefspec/fauxhai/blob/main/PLATFORMS.md>. Fauxhai / ChefSpec will perform fuzzy matching on platform version values so it’s always best to be less specific ie. 10 instead of 10.3 ### Examples let(:chef_run) { ChefSpec::ServerRunner.new(platform: ‘ubuntu’, version: ‘14.04’) } ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.20.0 | String | Include | * `**/spec/**/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_deprecatedchefspecplatform/CookbooksDependsOnSelf ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/CookbooksDependsOnSelf` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Make sure a cookbook doesn’t depend on itself. This will fail on Chef Infra Client 13+ ### Examples #### incorrect ``` name 'foo' depends 'foo' ``` #### correct ``` name 'foo' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_cookbooksdependsonself/DependsOnOmnibusUpdaterCookbook =============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/DependsOnOmnibusUpdaterCookbook` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Don’t depend on the EOL `omnibus_updater` cookbook. This cookbook no longer works with newer Chef Infra Client releases and has been replaced with the more reliable `chef_client_updater` cookbook. ### Examples #### incorrect ``` depends 'omnibus_updater' ``` #### correct ``` depends 'chef_client_updater' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.20.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_dependsonomnibusupdatercookbook/DependsOnChefReportingCookbook ============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/DependsOnChefReportingCookbook` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Don’t depend on the chef-reporting cookbook made obsolete by Chef Infra Client 11.6. This cookbook installs a gem that is not compatible with newer Chef Infra Client releases. ### Examples #### incorrect ``` depends 'chef-reporting' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.20.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_dependsonchefreportingcookbook/DependsOnChefNginxCookbook ========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/DependsOnChefNginxCookbook` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Don’t depend on the deprecated `chef_nginx` cookbook that was replaced by the `nginx` cookbook. The legacy chef_nginx cookbook may not be compatible with newer Chef Infra Client releases. ### Examples #### incorrect ``` depends 'chef_nginx' ``` #### correct ``` depends 'nginx' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.20.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_dependsonchefnginxcookbook/DeprecatedPlatformMethods ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/DeprecatedPlatformMethods` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Use `provider_for_action` or provides instead of the deprecated `Chef::Platform` methods in resources, which were removed in Chef Infra Client 13. ### Examples #### incorrect ``` resource = Chef::Resource::File.new("/tmp/foo.xyz", run_context) provider = Chef::Platform.provider_for_resource(resource, :create) resource = Chef::Resource::File.new("/tmp/foo.xyz", run_context) provider = Chef::Platform.find_provider("ubuntu", "16.04", resource) resource = Chef::Resource::File.new("/tmp/foo.xyz", run_context) provider = Chef::Platform.find_provider_for_node(node, resource) Chef::Platform.set :platform => :mac_os_x, :resource => :package, :provider => Chef::Provider::Package::Homebrew ``` #### correct ``` resource = Chef::Resource::File.new("/tmp/foo.xyz", run_context) provider = resource.provider_for_action(:create) # provides :package, platform_family: 'mac_os_x' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Include | * `**/libraries/*.rb` * `**/resources/*.rb` * `**/providers/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_deprecatedplatformmethods/DeprecatedYumRepositoryActions ============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/DeprecatedYumRepositoryActions` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 12.14+ | With the release of Chef Infra Client 12.14 and the yum cookbook 3.0 the actions the `yum_repository` resource actions were renamed. The `add` action became `create` and `delete` became `remove` to better match other resources in Chef Infra Client. ### Examples #### incorrect ``` yum_repository 'OurCo' do description 'OurCo yum repository' baseurl 'http://artifacts.ourco.org/foo/bar' gpgkey 'http://artifacts.ourco.org/<KEY>' action :add end ``` #### correct ``` yum_repository 'OurCo' do description 'OurCo yum repository' baseurl 'http://artifacts.ourco.org/foo/bar' gpgkey 'http://artifacts.ourco.org/<KEY>' action :create end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.3.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` * `**/Rakefile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_deprecatedyumrepositoryactions/DeprecatedShelloutMethods ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/DeprecatedShelloutMethods` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 14.3+ | The large number of `shell_out` helper methods in Chef Infra Client has been reduced to just `shell_out` and `shell_out!` methods. The legacy methods were removed in Chef Infra Client and cookbooks using these legacy helpers will need to be updated. ### Examples #### incorrect ``` shell_out_compact('foo') shell_out_compact!('foo') shell_out_with_timeout('foo') shell_out_with_timeout!('foo') shell_out_with_systems_locale('foo') shell_out_with_systems_locale!('foo') shell_out_compact_timeout('foo') shell_out_compact_timeout!('foo') ``` #### correct ``` shell_out('foo') shell_out!('foo') shell_out!('foo', default_env: false) # replaces shell_out_with_systems_locale ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.3.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_deprecatedshelloutmethods/DeprecatedSudoActions ===================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/DeprecatedSudoActions` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.0+ | The `sudo` resource in the sudo cookbook 5.0 (2018) or Chef Infra Client 14 and later have replaced the existing `:install` and `:remove` actions with `:create` and `:delete` actions to better match other resources in Chef Infra. ### Examples #### incorrect ``` sudo 'admins' do users 'bob' groups 'sysadmins, superusers' action :remove end ``` #### correct ``` sudo 'admins' do users 'bob' groups 'sysadmins, superusers' action :delete end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.18.0 | String | Exclude | * `**/spec/**/*.rb` * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` * `**/Rakefile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_deprecatedsudoactions/DeprecatedWindowsVersionCheck ============================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/DeprecatedWindowsVersionCheck` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Don’t use the deprecated `older_than_win_2012_or_8?` helper. Windows versions before 2012 and 8 are now end of life and this helper will always return false. ### Examples #### incorrect ``` if older_than_win_2012_or_8? # do some legacy things end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.0.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_deprecatedwindowsversioncheck/EasyInstallResource =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/EasyInstallResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Don’t use the deprecated easy_install resource removed in Chef Infra Client 13. ### Examples #### incorrect ``` easy_install "my_thing" do bar end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_easyinstallresource/DeprecatedYumRepositoryProperties ================================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/DeprecatedYumRepositoryProperties` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 12.14+ | With the release of Chef Infra Client 12.14 and the yum cookbook 3.0 several properties in the `yum_repository` resource were renamed. `url` -> `baseurl`, `keyurl` -> `gpgkey`, and `mirrorexpire` -> `mirror_expire`. ### Examples #### incorrect ``` yum_repository 'OurCo' do description 'OurCo yum repository' url 'http://artifacts.ourco.org/foo/bar' keyurl 'http://artifacts.ourco.org/<KEY>' mirrorexpire 1440 action :create end ``` #### correct ``` yum_repository 'OurCo' do description 'OurCo yum repository' baseurl 'http://artifacts.ourco.org/foo/bar' gpgkey 'http://artifacts.ourco.org/<KEY>' mirror_expire 1440 action :create end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.10.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_deprecatedyumrepositoryproperties/EpicFail ======== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/EpicFail` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use `ignore_failure` in resources to continue when failures occur instead of the deprecated `epic_fail` property. ### Examples #### incorrect ``` package "foo" do epic_fail true end ``` #### correct ``` package "foo" do ignore_failure true end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_epicfail/EOLAuditModeUsage ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/EOLAuditModeUsage` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The beta Audit Mode for Chef Infra Client was removed in Chef Infra Client 15.0. Users should instead use InSpec and the audit cookbook or the Compliance Phase introduced in Chef Infra Client 17. See <https://www.inspec.io/> for more information. ### Examples #### incorrect ``` control_group 'Baseline' do control 'SSH' do it 'should be listening on port 22' do expect(port(22)).to be_listening end end end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.10.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_eolauditmodeusage/FoodcriticTesting ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/FoodcriticTesting` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The Foodcritic cookbook linter has been deprecated and should no longer be used for validating cookbooks. ### Examples #### incorrect ``` gem 'foodcritic' require 'foodcritic' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.1.0 | String | Include | * `**/Rakefile` * `**/Gemfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_foodcritictesting/ExecutePathProperty =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ExecutePathProperty` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | In Chef Infra Client 13 and later you must set path env vars in execute resources using the `environment` property not the legacy `path` property. ### Examples #### incorrect ``` execute 'some_cmd' do path '/foo/bar' end ``` #### correct ``` execute 'some_cmd' do environment {path: '/foo/bar'} end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.17.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_executepathproperty/ErlCallResource =============== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ErlCallResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Don’t use the deprecated `erl_call` resource removed in Chef Infra Client 13." ### Examples #### incorrect ``` erl_call "foo" do bar end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_erlcallresource/ExecuteRelativeCreatesWithoutCwd ================================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ExecuteRelativeCreatesWithoutCwd` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | In Chef Infra Client 13 and later you must either specific an absolute path when using the `execute` resource’s `creates` property or also use the `cwd` property. ### Examples #### incorrect ``` execute 'some_cmd' do creates 'something' end ``` #### correct ``` execute 'some_cmd' do creates '/tmp/something' end execute 'some_cmd' do creates 'something' cwd '/tmp/' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.17.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_executerelativecreateswithoutcwd/HWRPWithoutUnifiedTrue ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/HWRPWithoutUnifiedTrue` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 15.3+ | Chef Infra Client 15.3 and later include a new Unified Mode that simplifies the execution of resources by replace the traditional compile and converge phases with a single phase. Unified mode simplifies writing advanced resources and avoids confusing errors that often occur when mixing ruby and Chef Infra resources. Chef Infra Client 17.0 and later will begin warning that `unified_mode true` should be set in all resources to validate that they will continue to function in Chef Infra Client 18.0 (April 2022) when Unified Mode becomes the default. ### Examples #### incorrect ``` class Chef class Resource class UlimitRule < Chef::Resource provides :ulimit_rule property :type, [Symbol, String], required: true property :item, [Symbol, String], required: true # additional resource code end end end ``` #### correct ``` class Chef class Resource class UlimitRule < Chef::Resource provides :ulimit_rule unified_mode true property :type, [Symbol, String], required: true property :item, [Symbol, String], required: true # additional resource code end end end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.12.0 | String | Include | * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_hwrpwithoutunifiedtrue/HWRPWithoutProvides =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/HWRPWithoutProvides` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Chef Infra Client 16 and later a legacy HWRP resource must use `provides` to define how the resource is called in recipes or other resources. To maintain compatibility with Chef Infra Client < 16 use both `resource_name` and `provides`. #### correct when Chef Infra Client < 15 (but compatible with 16+ as well) class Chef class Resource class UlimitRule < Chef::Resource resource_name :ulimit_rule provides :ulimit_rule ``` property :type, [Symbol, String], required: true property :item, [Symbol, String], required: true # additional resource code end end ``` end #### correct when Chef Infra Client 16+ class Chef class Resource class UlimitRule < Chef::Resource provides :ulimit_rule ``` property :type, [Symbol, String], required: true property :item, [Symbol, String], required: true # additional resource code end end ``` end better ====== Convert your legacy HWRPs to custom resources ### Examples #### incorrect ``` class Chef class Resource class UlimitRule < Chef::Resource property :type, [Symbol, String], required: true property :item, [Symbol, String], required: true # additional resource code end end end #### incorrect ```ruby class Chef class Resource class UlimitRule < Chef::Resource resource_name :ulimit_rule property :type, [Symbol, String], required: true property :item, [Symbol, String], required: true # additional resource code end end end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.0.0 | String | Include | * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_hwrpwithoutprovides/LibrarianChefSpec ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/LibrarianChefSpec` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The Librarian-Chef depsolving project is no longer maintained and a Cheffile should not be used for cookbook depsolving. Consider using Policyfiles instead. ### Examples #### incorrect ``` require 'chefspec/librarian' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.1.0 | String | Include | * `**/specs/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_librarianchefspec/IncludingXMLRubyRecipe ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/IncludingXMLRubyRecipe` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Do not include the deprecated xml::ruby recipe to install the nokogiri gem. Chef Infra Client 12 and later ships with nokogiri included. ### Examples #### incorrect ``` include_recipe 'xml::ruby' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.4.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_includingxmlrubyrecipe/IncludingYumDNFCompatRecipe =========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/IncludingYumDNFCompatRecipe` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Don’t include the deprecated yum DNF compatibility recipe, which is no longer necessary as Chef Infra Client includes DNF package support ### Examples #### incorrect ``` include_recipe 'yum::dnf_yum_compat' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.3.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_includingyumdnfcompatrecipe/LaunchdDeprecatedHashProperty ============================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/LaunchdDeprecatedHashProperty` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 12.19+ | The launchd resource’s hash property was renamed to plist_hash in Chef Infra Client 13+ to avoid conflicts with Ruby’s hash class. ### Examples #### incorrect ``` launchd 'foo' do hash foo: 'bar' end ``` #### correct ``` launchd 'foo' do plist_hash foo: 'bar' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_launchddeprecatedhashproperty/LegacyNotifySyntax ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/LegacyNotifySyntax` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use the new-style notification syntax which allows you to notify resources defined later in a recipe or resource. ### Examples #### incorrect ``` template '/etc/www/configures-apache.conf' do notifies :restart, resources(service: 'apache') end template '/etc/www/configures-apache.conf' do notifies :restart, resources(service: 'apache'), :immediately end template '/etc/www/configures-apache.conf' do notifies :restart, resources(service: service_name_variable), :immediately end template '/etc/www/configures-apache.conf' do subscribes :restart, resources(service: service_name_variable), :immediately end ``` #### correct ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]' end template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :immediately end template '/etc/www/configures-apache.conf' do notifies :restart, "service[#{service_name_variable}]", :immediately end template '/etc/www/configures-apache.conf' do subscribes :restart, "service[#{service_name_variable}]", :immediately end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.13.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_legacynotifysyntax/LegacyYumCookbookRecipes ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/LegacyYumCookbookRecipes` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The Ohai default recipe previously allowed a user to ship custom Ohai plugins to a system by including them in a directory in the Ohai cookbook. This functionality was replaced with the ohai_plugin resource, which should be used instead as it doesn’t require forking the ohai cookbook. ### Examples #### incorrect ``` include_recipe 'yum::elrepo' include_recipe 'yum::epel' include_recipe 'yum::ius' include_recipe 'yum::remi' include_recipe 'yum::repoforge' include_recipe 'yum::yum' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.4.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_legacyyumcookbookrecipes/MacosUserdefaultsGlobalProperty =============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/MacosUserdefaultsGlobalProperty` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 16.3+ | The `global` property in the macos_userdefaults resource was deprecated in Chef Infra Client 16.3. This property was never properly implemented and caused failures under many conditions. Omitting the `domain` property will now set global defaults. ### Examples #### incorrect ``` macos_userdefaults 'set a value' do global true key 'key' value 'value' end ``` #### correct ``` macos_userdefaults 'set a value' do key 'key' value 'value' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.14.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_macosuserdefaultsglobalproperty/LogResourceNotifications ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/LogResourceNotifications` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 15.8+ | In Chef Infra Client 16 the log resource no longer notifies when logging so notifications should not be triggered from log resources. Use the notify_group resource introduced in Chef Infra Client 15.8 instead to aggregate notifications. ### Examples #### incorrect ``` template '/etc/foo' do source 'bar.erb' notifies :write, 'log[Aggregate notifications using a single log resource]', :immediately end log 'Aggregate notifications using a single log resource' do notifies :restart, 'service[foo]', :delayed end ``` #### correct ``` template '/etc/foo' do source 'bar.erb' notifies :run, 'notify_group[Aggregate notifications using a single notify_group resource]', :immediately end notify_group 'Aggregate notifications using a single notify_group resource' do notifies :restart, 'service[foo]', :delayed end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.0.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_logresourcenotifications/LocaleDeprecatedLcAllProperty ============================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/LocaleDeprecatedLcAllProperty` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The local resource’s lc_all property has been deprecated and will be removed in Chef Infra Client 17 ### Examples #### incorrect ``` locale 'set locale' do lang 'en_gb.utf-8' lc_all 'en_gb.utf-8' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_localedeprecatedlcallproperty/NamePropertyWithDefaultValue ============================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/NamePropertyWithDefaultValue` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | A resource property (or attribute) can’t be marked as a name_property (or name_attribute) and also have a default value. The name property is a special property that is derived from the name of the resource block in and thus always has a value passed to the resource. For example if you define `my_resource 'foo'` in recipe, then the name property of `my_resource` will automatically be set to `foo`. Setting a property to be both a name_property and have a default value will cause Chef Infra Client failures in 13.0 and later releases. ### Examples #### incorrect ``` property :config_file, String, default: 'foo', name_property: true attribute :config_file, String, default: 'foo', name_attribute: true ``` #### correct ``` property :config_file, String, name_property: true attribute :config_file, String, name_attribute: true ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.7.0 | String | Include | * `**/libraries/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_namepropertywithdefaultvalue/NodeMethodsInsteadofAttributes ============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/NodeMethodsInsteadofAttributes` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use node attributes to access data provided by Ohai instead of using node methods to access that data. ### Examples #### incorrect ``` node.fqdn node.platform node.platform_family node.platform_version node.hostname ``` #### correct ``` node['fqdn'] node['platform'] node['platform_family'] node['platform_version'] node['hostname'] ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.4.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_nodemethodsinsteadofattributes/NodeDeepFetch ============= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/NodeDeepFetch` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The node.deep_fetch method has been removed from Chef-Sugar, and must be replaced by the node.read API. ### Examples #### incorrect ``` node.deep_fetch("foo") ``` #### correct ``` node.read("foo") #### incorrect ```ruby node.deep_fetch!("foo") ``` #### correct ``` node.read!("foo") ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.12.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_nodedeepfetch/NodeSet ======= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/NodeSet` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The `node.set` method has been removed in Chef Infra Client 13 and usage must be replaced with `node.normal`. This cop will autocorrect code to use node.normal, which is functionally identical to node.set, but we also discourage the use of that method as normal level attributes persist on the node even if the code setting the attribute is later removed. ### Examples #### incorrect ``` node.set['foo'] = true ``` #### correct ``` node.normal['foo'] = true ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.0.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_nodeset/NodeSetUnless ============= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/NodeSetUnless` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The node.set_unless method has been removed in Chef Infra Client 13 and usage must be replaced with node.normal_unless. This cop will autocorrect code to use node.normal_unless, which is functionally identical to node.set_unless, but we also discourage the use of that method as normal level attributes persist on the node even if the code setting the attribute is later removed. ### Examples #### incorrect ``` node.set_unless['foo'] = true ``` #### correct ``` node.normal_unless['foo'] = true ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_nodesetunless/NodeSetWithoutLevel =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/NodeSetWithoutLevel` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | When setting a node attribute in Chef Infra Client 11 and later you must specify the precedence level. ### Examples #### incorrect ``` node['foo']['bar'] = 1 node['foo']['bar'] << 1 node['foo']['bar'] += 1 node['foo']['bar'] -= 1 ``` #### correct ``` node.default['foo']['bar'] = 1 node.default['foo']['bar'] << 1 node.default['foo']['bar'] += 1 node.default['foo']['bar'] -= 1 ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.13.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_nodesetwithoutlevel/PartialSearchClassUsage ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/PartialSearchClassUsage` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Legacy Chef::PartialSearch class usage should be updated to use the `search` helper instead with the `filter_result` key. ### Examples #### incorrect ``` ::Chef::PartialSearch.new.search((:node, 'role:web', keys: { 'name' => [ 'name' ], 'ip' => [ 'ipaddress' ], 'kernel_version' => %w(kernel version), } ).each do |result| puts result['name'] puts result['ip'] puts result['kernel_version'] end ``` #### correct ``` search(:node, 'role:web', filter_result: { 'name' => [ 'name' ], 'ip' => [ 'ipaddress' ], 'kernel_version' => %w(kernel version), } ).each do |result| puts result['name'] puts result['ip'] puts result['kernel_version'] end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.11.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_partialsearchclassusage/PartialSearchHelperUsage ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/PartialSearchHelperUsage` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Legacy partial_search usage should be updated to use :filter_result in the search helper instead ### Examples #### incorrect ``` partial_search(:node, 'role:web', keys: { 'name' => [ 'name' ], 'ip' => [ 'ipaddress' ], 'kernel_version' => %w(kernel version), } ).each do |result| puts result['name'] puts result['ip'] puts result['kernel_version'] end ``` #### correct ``` search(:node, 'role:web', filter_result: { 'name' => [ 'name' ], 'ip' => [ 'ipaddress' ], 'kernel_version' => %w(kernel version), } ).each do |result| puts result['name'] puts result['ip'] puts result['kernel_version'] end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.11.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_partialsearchhelperusage/PolicyfileCommunitySource ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/PolicyfileCommunitySource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The Policyfile source of `:community` has been replaced with `:supermarket` ### Examples #### incorrect ``` default_source :community ``` #### correct ``` default_source :supermarket ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.15.0 | String | Include | * `**/Policyfile.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_policyfilecommunitysource/PoiseArchiveUsage ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/PoiseArchiveUsage` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 15.0+ | The poise_archive resource in the deprecated poise-archive should be replaced with the archive_file resource found in Chef Infra Client 15+. ### Examples #### incorrect ``` poise_archive 'https://example.com/myapp.tgz' do destination '/opt/my_app' end ``` #### correct ``` archive_file 'https://example.com/myapp.tgz' do destination '/opt/my_app' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.11.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_poisearchiveusage/RequireRecipe ============= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/RequireRecipe` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Make sure to use include_recipe instead of require_recipe ### Examples #### incorrect ``` require_recipe 'foo' ``` #### correct ``` include_recipe 'foo' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_requirerecipe/ResourceOverridesProvidesMethod =============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ResourceOverridesProvidesMethod` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Some providers in resources override the provides? method, used to check whether they are a valid provider on the current platform. In Chef Infra Client 13, this will cause an error. Instead use `provides :SOME_PROVIDER_NAME` to register the provider. ### Examples #### incorrect ``` def provides? true end ``` #### correct ``` provides :SOME_PROVIDER_NAME ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.7.0 | String | Include | * `**/libraries/*.rb` * `**/providers/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_resourceoverridesprovidesmethod/ResourceInheritsFromCompatResource ================================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ResourceInheritsFromCompatResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Resources written in the class based HWRP style should inherit from the ‘Chef::Resource’ class and not the ‘ChefCompat::Resource’ class from the deprecated compat_resource cookbook. ### Examples #### incorrect ``` class AptUpdate < ChefCompat::Resource # some resource code end ``` #### correct ``` class AptUpdate < Chef::Resource # some resource code end # better Write a custom resource using the custom resource DSL and avoid class based HWRPs entirely ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.10.0 | String | Include | * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_resourceinheritsfromcompatresource/PowershellCookbookHelpers ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/PowershellCookbookHelpers` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use `node['powershell']['version']` or the new `powershell_version` helper available in Chef Infra Client 15.8+ instead of the deprecated PowerShell cookbook helpers ### Examples #### incorrect ``` Powershell::VersionHelper.powershell_version?('4.0') ``` #### correct ``` node['powershell']['version'].to_f == 4.0 # better (Chef Infra Client 15.8+) powershell_version == 4.0 ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.1.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_powershellcookbookhelpers/ResourceUsesDslNameMethod ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ResourceUsesDslNameMethod` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Don’t use the dsl_name method in a resource to find the name of the resource. Use the resource_name method instead. dsl_name was removed in Chef Infra Client 13 and will now result in an error. ### Examples #### incorrect ``` my_resource = MyResource.dsl_name ``` #### correct ``` my_resource = MyResource.resource_name ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.7.0 | String | Include | * `**/libraries/*.rb` * `**/providers/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_resourceusesdslnamemethod/ResourceUsesProviderBaseMethod ============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ResourceUsesProviderBaseMethod` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The Resource.provider_base allows the developer to specify within a resource a module to load the resource’s provider from. Instead, the provider should call provides to register itself, or the resource should call provider to specify the provider to use. ### Examples #### incorrect ``` provider_base ::Chef::Provider::SomethingSomething ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.7.0 | String | Include | * `**/libraries/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_resourceusesproviderbasemethod/ResourceUsesOnlyResourceName ============================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ResourceUsesOnlyResourceName` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Starting with Chef Infra Client 16, using `resource_name` without also using `provides` will result in resource failures. Make sure to use both `resource_name` and `provides` to change the name of the resource. You can also omit `resource_name` entirely if the value set matches the name Chef Infra Client automatically assigns based on COOKBOOKNAME_FILENAME. ### Examples #### incorrect ``` mycookbook/resources/myresource.rb: resource_name :mycookbook_myresource ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.7.0 | String | Include | * `**/libraries/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_resourceusesonlyresourcename/ResourceWithoutUnifiedTrue ========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ResourceWithoutUnifiedTrue` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 15.3+ | Chef Infra Client 15.3 and later include a new Unified Mode that simplifies the execution of resources by replace the traditional compile and converge phases with a single phase. Unified mode simplifies writing advanced resources and avoids confusing errors that often occur when mixing ruby and Chef Infra resources. Chef Infra Client 17.0 and later will begin warning that `unified_mode true` should be set in all resources to validate that they will continue to function in Chef Infra Client 18.0 (April 2022) when Unified Mode becomes the default. ### Examples #### incorrect ``` resource_name :foo provides :foo action :create do # some action code end ``` #### correct ``` resource_name :foo provides :foo unified_mode true action :create do # some action code end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.12.0 | String | ExcludeInclude | * `**/resources/_*.rb` * `**/spec/**/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_resourcewithoutunifiedtrue/ResourceUsesUpdatedMethod ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/ResourceUsesUpdatedMethod` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | All Versions | Don’t call the deprecated `updated=` method in a resource to set the resource to updated. This method was removed from Chef Infra Client 13 and this will now cause an error. Instead wrap code that updated the state of the node in a `converge_by` block. Documentation on using the `converge_by` block can be found at [https://docs.chef.io/custom_resources/](../../../custom_resources/index). ### Examples #### incorrect ``` action :foo do updated = true end ``` #### correct ``` action :foo do converge_by('resource did something) do # code that causes the resource to converge end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.7.0 | String | Include | * `**/libraries/*.rb` * `**/providers/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_resourceusesupdatedmethod/UseAutomaticResourceName ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/UseAutomaticResourceName` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The use_automatic_resource_name method was removed in Chef Infra Client 16. The resource name/provides should be set explicitly instead. ### Examples #### incorrect ``` module MyCookbook class MyCookbookService < Chef::Resource use_automatic_resource_name provides :mycookbook_service ... end end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.12.0 | String | Include | * `**/libraries/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_useautomaticresourcename/Ruby27KeywordArgumentWarnings ============================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/Ruby27KeywordArgumentWarnings` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Pass options to shell_out helpers without the brackets to avoid Ruby 2.7 deprecation warnings. ### Examples #### incorrect ``` shell_out!('hostnamectl status', { returns: [0, 1] }) shell_out('hostnamectl status', { returns: [0, 1] }) ``` #### correct ``` shell_out!('hostnamectl status', returns: [0, 1]) shell_out('hostnamectl status', returns: [0, 1]) ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.5.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_ruby27keywordargumentwarnings/RubyBlockCreateAction ===================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/RubyBlockCreateAction` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use the :run action in the ruby_block resource instead of the deprecated :create action ### Examples #### incorrect ``` ruby_block 'my special ruby block' do block do puts 'running' end action :create end ``` #### correct ``` ruby_block 'my special ruby block' do block do puts 'running' end action :run end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_rubyblockcreateaction/UsesDeprecatedMixins ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/UsesDeprecatedMixins` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Don’t use deprecated Mixins no longer included in Chef Infra Client 14 and later. ### Examples #### incorrect ``` include Chef::Mixin::LanguageIncludeAttribute include Chef::Mixin::RecipeDefinitionDSLCore include Chef::Mixin::LanguageIncludeRecipe include Chef::Mixin::Language include Chef::DSL::Recipe::FullDSL require 'chef/mixin/language' require 'chef/mixin/language_include_attribute' require 'chef/mixin/language_include_recipe' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.4.0 | String | Include | * `**/libraries/*.rb` * `**/providers/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_usesdeprecatedmixins/SearchUsesPositionalParameters ============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/SearchUsesPositionalParameters` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | correct query(:node, ‘*:*') search(:node, ‘*:*’, start: 0, rows: 1000, filter_result: { :ip_address => [“ipaddress”] }) search(:node, ‘*:*’, start: 0, rows: 1000) search(:node, ‘*:*’, start: 0) ### Examples ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.11.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_searchusespositionalparameters/UseInlineResourcesDefined ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/UseInlineResourcesDefined` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | use_inline_resources became the default in Chef Infra Client 13+ and no longer needs to be called in resources ### Examples #### incorrect ``` use_inline_resources use_inline_resources if defined?(use_inline_resources) use_inline_resources if respond_to?(:use_inline_resources) ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.4.0 | String | Include | * `**/libraries/*.rb` * `**/providers/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_useinlineresourcesdefined/UserDeprecatedSupportsProperty ============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/UserDeprecatedSupportsProperty` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The supports property was removed in Chef Infra Client 13 in favor of individual ‘manage_home’ and ‘non_unique’ properties. ### Examples #### incorrect ``` user "betty" do supports({ manage_home: true, non_unique: true }) end user 'betty' do supports :manage_home => true end ``` #### correct ``` user "betty" do manage_home true non_unique true end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_userdeprecatedsupportsproperty/UsesRunCommandHelper ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/UsesRunCommandHelper` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Use ‘shell_out!’ instead of the legacy ‘run_command’ or ‘run_command_with_systems_locale’ helpers for shelling out. The run_command helper was removed in Chef Infra Client 13. ### Examples #### incorrect ``` require 'chef/mixin/command' include Chef::Mixin::Command run_command('/bin/foo') run_command_with_systems_locale('/bin/foo') ``` #### correct ``` shell_out!('/bin/foo') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.9.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` * `**/Rakefile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_usesruncommandhelper/UsesChefRESTHelpers =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/UsesChefRESTHelpers` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The `Chef::REST` class was removed in Chef Infra Client 13. ### Examples #### incorrect ``` require 'chef/rest' Chef::REST::RESTRequest.new(:GET, FOO, nil).call ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_useschefresthelpers/VerifyPropertyUsesFileExpansion =============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/VerifyPropertyUsesFileExpansion` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 12.5+ | In Chef Infra Client 13 the “file” variable for use within the verify property was replaced with the “path” variable. ### Examples #### incorrect ``` file '/etc/nginx.conf' do verify 'nginx -t -c %{file}' end ``` #### correct ``` file '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.10.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_verifypropertyusesfileexpansion/UseYamlDump =========== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/UseYamlDump` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Chef Infra Client 16.5 introduced performance enhancements to Ruby library loading. Due to the underlying implementation of Ruby’s `.to_yaml` method, it does not automatically load the `yaml` library and `YAML.dump()` should be used instead to properly load the `yaml` library. ### Examples #### incorrect ``` {"foo" => "bar"}.to_yaml ``` #### correct ``` YAML.dump({"foo" => "bar"}) ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.21.0 | String | | | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_useyamldump/WindowsFeatureServermanagercmd ============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/WindowsFeatureServermanagercmd` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The `windows_feature` resource no longer supports setting the `install_method` to `:servermanagercmd`. `:windows_feature_dism` or `:windows_feature_powershell` should be used instead. ### Examples #### incorrect ``` windows_feature 'DHCP' do install_method :servermanagercmd end ``` #### correct ``` windows_feature 'DHCP' do install_method :windows_feature_dism end windows_feature 'DHCP' do install_method :windows_feature_powershell end windows_feature_dism 'DHCP' windows_feature_powershell 'DHCP' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.22.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_windowsfeatureservermanagercmd/WindowsPackageInstallerTypeString ================================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/WindowsPackageInstallerTypeString` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | In Chef Infra Client 13 and later the `windows_package` resource’s `installer_type` property must be a symbol. ### Examples #### incorrect ``` windows_package 'AppveyorDeploymentAgent' do source 'https://www.example.com/appveyor.msi' installer_type 'msi' options "/quiet /qn /norestart /log install.log" end ``` #### correct ``` windows_package 'AppveyorDeploymentAgent' do source 'https://www.example.com/appveyor.msi' installer_type :msi options "/quiet /qn /norestart /log install.log" end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.17.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_windowspackageinstallertypestring/WindowsTaskChangeAction ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/WindowsTaskChangeAction` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 13.0+ | The :change action in the windows_task resource was removed when windows_task was added to Chef Infra Client 13+ The default action of :create should can now be used to create an update tasks. ### Examples #### incorrect ``` windows_task 'chef ad-join leave start time' do task_name 'chef ad-join leave' start_day '06/09/2016' start_time '01:00' action [:change, :create] end ``` #### correct ``` windows_task 'chef ad-join leave start time' do task_name 'chef ad-join leave' start_day '06/09/2016' start_time '01:00' action :create end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_windowstaskchangeaction/WindowsVersionHelpers ===================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Deprecations` The full name of the cop is: `Chef/Deprecations/WindowsVersionHelpers` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.0+ | Use node[‘platform_version’] and node[‘kernel’] data instead of the deprecated Windows::VersionHelper helpers from the Windows cookbook. ### Examples #### incorrect ``` Windows::VersionHelper.nt_version Windows::VersionHelper.server_version? Windows::VersionHelper.core_version? Windows::VersionHelper.workstation_version? ``` #### correct ``` node['platform_version'].to_f node['kernel']['product_type'] == 'Server' node['kernel']['server_core'] node['kernel']['product_type'] == 'Workstation' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.4.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_deprecations_windowsversionhelpers/Berksfile ========= [All Cookstyle Cops](../cops/index) The department is: `Chef/Effortless` The full name of the cop is: `Chef/Effortless/Berksfile` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | All Versions | Policyfiles should be used for cookbook dependency solving instead of a Berkshelf Berksfile. ### Examples ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.12.0 | String | Include | * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_effortless_berksfile/ChefVaultUsed ============= [All Cookstyle Cops](../cops/index) The department is: `Chef/Effortless` The full name of the cop is: `Chef/Effortless/ChefVaultUsed` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | All Versions | Chef Vault is not supported in the Effortless pattern, so usage of Chef Vault must be shifted to another secrets management solution before leveraging the Effortless pattern. ### Examples #### incorrect ``` require 'chef-vault' #### incorrect ```ruby ChefVault::Item #### incorrect ```ruby include_recipe 'chef-vault' #### incorrect ```ruby chef_gem 'chef-vault' #### incorrect ```ruby chef_vault_item_for_environment(arg, arg1) #### incorrect ```ruby chef_vault_item(arg, arg1) ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.19 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_effortless_chefvaultused/CookbookUsesDatabags ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Effortless` The full name of the cop is: `Chef/Effortless/CookbookUsesDatabags` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | All Versions | Data bags cannot be used with the Effortless Infra pattern ### Examples #### incorrect ``` data_bag_item('admins', login) data_bag(data_bag_name) ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_effortless_cookbookusesdatabags/CookbookUsesEnvironments ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Effortless` The full name of the cop is: `Chef/Effortless/CookbookUsesEnvironments` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | All Versions | Neither Policyfiles or Effortless Infra which is based on Policyfiles supports Chef Environments ### Examples #### incorrect ``` node.environment == "production" node.chef_environment == "production" ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.10.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_effortless_cookbookusesenvironments/CookbookUsesPolicygroups ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Effortless` The full name of the cop is: `Chef/Effortless/CookbookUsesPolicygroups` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | All Versions | Effortless Infra does not support Policyfile’s Policygroup feature ### Examples #### incorrect ``` node.policy_group == "foo" ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.10.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_effortless_cookbookusespolicygroups/DependsChefVault ================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Effortless` The full name of the cop is: `Chef/Effortless/DependsChefVault` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | All Versions | Chef Vault is not supported in the Effortless pattern, so usage of Chef Vault must be shifted to another secrets management solution before leveraging the Effortless pattern. ### Examples #### incorrect ``` depends 'chef-vault' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.19 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_effortless_dependschefvault/CookbookUsesSearch ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Effortless` The full name of the cop is: `Chef/Effortless/CookbookUsesSearch` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | All Versions | Search is not compatible with the Effortless Infra pattern ### Examples #### incorrect ``` search(:node, 'run_list:recipe\[bacula\:\:server\]') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_effortless_cookbookusessearch/CookbookUsesRoles ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Effortless` The full name of the cop is: `Chef/Effortless/CookbookUsesRoles` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | All Versions | Neither Policyfiles or Effortless Infra which is based on Policyfiles supports Chef Infra Roles ### Examples #### incorrect ``` node.role?('web_server') node.roles.include?('web_server') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.10.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_effortless_cookbookusesroles/ActionMethodInResource ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ActionMethodInResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use the custom resource language’s `action :my_action` blocks instead of creating actions with methods. ### Examples #### incorrect ``` def action_create # :create action code here end ``` #### correct ``` action :create do # :create action code here end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.13.0 | String | Include | * `**/resources/*.rb` * `**/providers/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_actionmethodinresource/AllowedActionsFromInitialize ============================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/AllowedActionsFromInitialize` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The allowed actions can now be specified using the `allowed_actions` helper instead of using the @actions or @allowed_actions variables in the resource’s initialize method. In general we recommend against writing HWRPs, but if HWRPs are necessary you should utilize as much of the resource DSL as possible. ### Examples #### incorrect ``` def initialize(*args) super @actions = [ :create, :add ] end # also bad def initialize(*args) super @allowed_actions = [ :create, :add ] end ``` #### correct ``` allowed_actions [ :create, :add ] ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.15.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_allowedactionsfrominitialize/SearchForEnvironmentsOrRoles ============================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Effortless` The full name of the cop is: `Chef/Effortless/SearchForEnvironmentsOrRoles` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | All Versions | Policyfiles (and Effortless) do not use environments or roles so searching for those will need to be refactored before migrating to Policyfiles and the Effortless pattern. ### Examples #### incorrect ``` search(:node, 'chef_environment:foo') search(:node, 'role:bar') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.11.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_effortless_searchforenvironmentsorroles/ClassEvalActionClass ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ClassEvalActionClass` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 12.9+ | In Chef Infra Client 12.9 and later it is no longer necessary to call the class_eval method on the action class block. ### Examples #### incorrect ``` action_class.class_eval do foo end ``` #### correct ``` action_class do foo end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.23.0 | String | Include | * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_classevalactionclass/ChefGemNokogiri =============== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ChefGemNokogiri` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The nokogiri gem ships in Chef Infra Client 12+ and does not need to be installed before being used ### Examples #### incorrect ``` chef_gem 'nokogiri' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.14.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_chefgemnokogiri/ConditionalUsingTest ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ConditionalUsingTest` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use ::File.exist?('/foo/bar') instead of the slower ‘test -f /foo/bar’ which requires shelling out ### Examples #### incorrect ``` only_if 'test -f /bin/foo' ``` #### correct ``` only_if { ::File.exist?('bin/foo') } ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.11.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` * `**/attributes/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_conditionalusingtest/CronManageResource ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/CronManageResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.4+ | The cron_manage resource was renamed to cron_access in the 6.1 release of the cron cookbook, and later shipped in Chef Infra Client 14.4. The new resource name should be used. ### Examples #### incorrect ``` cron_manage 'mike' ``` #### correct ``` cron_access 'mike' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_cronmanageresource/DefaultActionFromInitialize =========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DefaultActionFromInitialize` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The default actions can now be specified using the `default_action` helper instead of using the @action variable in the resource provider initialize method. In general we recommend against writing HWRPs, but if HWRPs are necessary you should utilize as much of the resource DSL as possible. #### correct default_action :create ### Examples #### incorrect ``` def initialize(*args) super @action = :create end #### incorrect ```ruby def initialize(*args) super @default_action = :create end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.10.0 | String | Include | * `**/resources/*.rb` * `**/providers/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_defaultactionfrominitialize/DeclareActionClass ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DeclareActionClass` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 12.9+ | In Chef Infra Client 12.9 and later `action_class` can be used instead of `declare_action_class`. ### Examples #### incorrect ``` declare_action_class do foo end ``` #### correct ``` action_class do foo end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.26.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_declareactionclass/CronDFileOrTemplate =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/CronDFileOrTemplate` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 14.4+ | Use the cron_d resource that ships with Chef Infra Client 14.4+ instead of manually creating the file with template, file, or cookbook_file resources. ### Examples #### incorrect ``` template '/etc/cron.d/backup' do source 'cron_backup_job.erb' owner 'root' group 'root' mode '644' end cookbook_file '/etc/cron.d/backup' do owner 'root' group 'root' mode '644' end file '/etc/cron.d/backup' do content '*/30 * * * * backup /usr/local/bin/backup_script.sh' owner 'root' group 'root' mode '644' end file '/etc/cron.d/blogs' do action :delete end ``` #### correct ``` cron_d 'backup' do minute '1' hour '1' mailto '<EMAIL>' command '/usr/local/bin/backup_script.sh' end cron_d 'blogs' do action :delete end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.13.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` * `**/attributes/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_crondfileortemplate/CustomResourceWithAttributes ============================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/CustomResourceWithAttributes` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | In HWRPs and LWRPs you defined attributes, but custom resources changed the name to be properties to avoid confusion with chef recipe attributes. When writing a custom resource they should be called properties even though the two are aliased. ### Examples #### incorrect ``` attribute :something, String action :create do # some action code because we're in a custom resource end ``` #### correct ``` property :something, String action :create do # some action code because we're in a custom resource end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Include | * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_customresourcewithattributes/DatabagHelpers ============== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DatabagHelpers` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use the `data_bag_item` helper instead of `Chef::DataBagItem.load` or `Chef::EncryptedDataBagItem.load`. ### Examples #### incorrect ``` plain_text_data = Chef::DataBagItem.load('foo', 'bar') encrypted_data = Chef::EncryptedDataBagItem.load('foo2', 'bar2') ``` #### correct ``` plain_text_data = data_bag_item('foo', 'bar') encrypted_data = data_bag_item('foo2', 'bar2') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.0.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_databaghelpers/DefinesChefSpecMatchers ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DefinesChefSpecMatchers` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | ChefSpec 7.1 and later auto generate ChefSpec matchers. Matchers in cookbooks can now be removed. ### Examples #### incorrect ``` if defined?(ChefSpec) def create_yum_repository(resource_name) ChefSpec::Matchers::ResourceMatcher.new(:yum_repository, :create, resource_name) end end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.3.0 | String | Include | * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_defineschefspecmatchers/Definitions =========== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/Definitions` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | In 2016 with Chef Infra Client 12.5 Custom Resources were introduced as a way of writing reusable resource code that could be shipped in cookbooks. Custom Resources offer many advantages of legacy Definitions including unit testing with ChefSpec, input validation, actions, common properties like not_if/only_if, and resource reporting. ### Examples ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.11.0 | String | Include | * `**/definitions/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_definitions/DependsOnChefVaultCookbook ========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DependsOnChefVaultCookbook` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 16.0+ | Don’t depend on the chef-vault cookbook made obsolete by Chef Infra Client 16.0. The chef-vault gem and helpers are now included in Chef Infra Client itself. ### Examples #### incorrect ``` depends 'chef-vault' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.20.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_dependsonchefvaultcookbook/DependsOnChocolateyCookbooks ============================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DependsOnChocolateyCookbooks` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.3+ | Don’t depend on the chocolatey_source or chocolatey_config cookbooks made obsolete by Chef Infra Client 14.3. The chocolatey_source and chocolatey_config resources are now included in Chef Infra Client itself. ### Examples #### incorrect ``` depends 'chocolatey_source' depends 'chocolatey_config' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.20.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_dependsonchocolateycookbooks/DependsOnKernelModuleCookbook ============================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DependsOnKernelModuleCookbook` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.3+ | Don’t depend on the kernel_module cookbook made obsolete by Chef Infra Client 14.3. The kernel_module resource is now included in Chef Infra Client itself. ### Examples #### incorrect ``` depends 'kernel_module' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.19.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_dependsonkernelmodulecookbook/DependsOnOpensslCookbook ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DependsOnOpensslCookbook` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.4+ | Don’t depend on the `openssl` cookbook which was made obsolete by Chef Infra Client 14.4. All `openssl_*` resources are now included directly in Chef Infra Client. ### Examples #### incorrect ``` depends 'openssl' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.20.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_dependsonopensslcookbook/DependsOnLocaleCookbook ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DependsOnLocaleCookbook` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.5+ | Don’t depend on the locale cookbook made obsolete by Chef Infra Client 14.5. The locale resource is now included in Chef Infra Client itself. ### Examples #### incorrect ``` depends 'locale' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.19.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_dependsonlocalecookbook/DependsOnTimezoneLwrpCookbook ============================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DependsOnTimezoneLwrpCookbook` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.6+ | Don’t depend on the timezone_lwrp cookbook made obsolete by Chef Infra Client 14.6. The timezone resource is now included in Chef Infra Client itself. ### Examples #### incorrect ``` depends 'timezone_lwrp' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.19.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_dependsontimezonelwrpcookbook/DependsOnWindowsFirewallCookbook ================================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DependsOnWindowsFirewallCookbook` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.7+ | Don’t depend on the windows_firewall cookbook made obsolete by Chef Infra Client 14.7. The windows_firewall resource is now included in Chef Infra Client itself. ### Examples #### incorrect ``` depends 'windows_firewall' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.19.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_dependsonwindowsfirewallcookbook/DependsOnZypperCookbook ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DependsOnZypperCookbook` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 13.3+ | Don’t depend on the zypper cookbook as the zypper_repository resource is built into Chef Infra Client 13.3+ ### Examples #### incorrect ``` depends 'zypper' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_dependsonzyppercookbook/EmptyResourceInitializeMethod ============================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/EmptyResourceInitializeMethod` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | There is no need for an empty initialize method in a resource ### Examples #### incorrect ``` def initialize(*args) super end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.13.0 | String | Include | * `**/resources/*.rb` * `**/providers/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_emptyresourceinitializemethod/DslIncludeInResource ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/DslIncludeInResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Chef Infra Client 12.4+ includes the Chef::DSL::Recipe in the resource and provider classed by default so there is no need to include this DSL in your resources or providers. ### Examples #### incorrect ``` include Chef::DSL::Recipe include Chef::DSL::IncludeRecipe ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.17.0 | String | Include | * `**/resources/*.rb` * `**/providers/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_dslincludeinresource/ExecuteAptUpdate ================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ExecuteAptUpdate` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Instead of using the execute resource to run the `apt-get update` use Chef Infra Client’s built-n apt_update resource which is available in Chef Infra Client 12.7 and later. ### Examples #### incorrect ``` execute 'apt-get update' execute 'Apt all the apt cache' do command 'apt-get update' end execute 'some execute resource' do notifies :run, 'execute[apt-get update]', :immediately end ``` #### correct ``` apt_update apt_update 'update apt cache' execute 'some execute resource' do notifies :update, 'apt_update[update apt cache]', :immediately end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.3.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_executeaptupdate/ExecuteSysctl ============= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ExecuteSysctl` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 14.0+ | Chef Infra Client 14.0 and later includes a sysctl resource that should be used to idempotently load sysctl values instead of templating files and using execute to load them. ### Examples #### incorrect ``` file '/etc/sysctl.d/ipv4.conf' do notifies :run, 'execute[sysctl -p /etc/sysctl.d/ipv4.conf]', :immediately content '9000 65500' end execute 'sysctl -p /etc/sysctl.d/ipv4.conf' do action :nothing end ``` #### correct ``` sysctl 'net.ipv4.ip_local_port_range' do value '9000 65500' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.18.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_executesysctl/ExecuteScExe ============ [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ExecuteScExe` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 14.0+ | Chef Infra Client 14.0 and later includes :create, :delete, and :configure actions with the full idempotency of the windows_service resource. See the windows_service documentation at [https://docs.chef.io/resources/windows_service](../../../resources/windows_service) for additional details on creating services with the windows_service resource. ### Examples #### incorrect ``` execute "Delete chef-client service" do command "sc.exe delete chef-client" action :run end ``` #### correct ``` windows_service 'chef-client' do action :delete end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_executescexe/ExecuteSleep ============ [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ExecuteSleep` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 15.5+ | Chef Infra Client 15.5 and later include a chef_sleep resource that should be used to sleep between executing resources if necessary instead of using the bash or execute resources to run the sleep command. ### Examples #### incorrect ``` execute "sleep 60" do command "sleep 60" action :run end bash 'sleep' do user 'root' cwd '/tmp' code 'sleep 60' end ``` #### correct ``` chef_sleep '60' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_executesleep/ExecuteTzUtil ============= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ExecuteTzUtil` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 14.6+ | Instead of using the execute or powershell_script resources to run the `tzutil` command, use Chef Infra Client’s built-in timezone resource which is available in Chef Infra Client 14.6 and later. ### Examples #### incorrect ``` execute 'set tz' do command 'tzutil.exe /s UTC' end execute 'tzutil /s UTC' powershell_script 'set windows timezone' do code "tzutil.exe /s UTC" not_if { shell_out('tzutil.exe /g').stdout.include?('UTC') } end ``` #### correct ``` timezone 'UTC' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_executetzutil/FoodcriticComments ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/FoodcriticComments` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Remove legacy code comments that disable Foodcritic rules. These comments are no longer necessary if you’ve migrated from Foodcritic to Cookstyle for cookbook linting. ### Examples #### incorrect ``` # ~FC013 ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Exclude | * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_foodcriticcomments/IfProvidesDefaultAction ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/IfProvidesDefaultAction` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | if defined?(default_action) is no longer necessary in Chef Resources as default_action shipped in Chef 10.8. ### Examples #### incorrect ``` default_action :foo if defined?(default_action) ``` #### correct ``` default_action :foo ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.12.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_ifprovidesdefaultaction/IncludingAptDefaultRecipe ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/IncludingAptDefaultRecipe` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 12.7+ | For many users the apt::default cookbook is used only to update apt’s package cache. Chef Infra Client 12.7 and later include an apt_update resource which should be used to perform this instead. Keep in mind that some users will want to stick with the apt::default recipe as it also installs packages necessary for using https repositories on Debian systems and manages some configuration files. ### Examples #### incorrect ``` include_recipe 'apt::default' include_recipe 'apt' ``` #### correct ``` apt_update ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.3.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_includingaptdefaultrecipe/IncludingMixinShelloutInResources ================================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/IncludingMixinShelloutInResources` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | There is no need to include Chef::Mixin::ShellOut or Chef::Mixin::PowershellOut in resources or providers as this is already done by Chef Infra Client 12.4+. ### Examples #### incorrect ``` require 'chef/mixin/shell_out' include Chef::Mixin::ShellOut require 'chef/mixin/powershell_out' include Chef::Mixin::PowershellOut ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.4.0 | String | Include | * `**/resources/*.rb` * `**/providers/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_includingmixinshelloutinresources/IncludingOhaiDefaultRecipe ========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/IncludingOhaiDefaultRecipe` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The Ohai default recipe previously allowed a user to ship custom Ohai plugins to a system by including them in a directory in the Ohai cookbook. This functionality was replaced with the ohai_plugin resource, which should be used instead as it doesn’t require forking the ohai cookbook. ### Examples #### incorrect ``` include_recipe 'ohai::default' include_recipe 'ohai' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.4.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_includingohaidefaultrecipe/IncludingWindowsDefaultRecipe ============================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/IncludingWindowsDefaultRecipe` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Don’t include the windows default recipe that is either full of gem install that are part of the Chef Infra Client, or empty (depends on version). ### Examples #### incorrect ``` include_recipe 'windows::default' include_recipe 'windows' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.3.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_includingwindowsdefaultrecipe/LibarchiveFileResource ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/LibarchiveFileResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 15.0+ | Use the archive_file resource built into Chef Infra Client 15+ instead of the libarchive_file resource from the libarchive cookbook. ### Examples #### incorrect ``` depends 'libarchive' libarchive_file "C:\file.zip" do path 'C:\expand_here' end ``` #### correct ``` archive_file "C:\file.zip" do path 'C:\expand_here' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_libarchivefileresource/LegacyBerksfileSource ===================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/LegacyBerksfileSource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | There have been many different valid community site / Supermarket URLs to use in a cookbook’s Berksfile. These old URLs continue to function via redirects, but should be updated to point to the latest Supermarket URL. ### Examples #### incorrect ``` source 'http://community.opscode.com/api/v3' source 'https://supermarket.getchef.com' source 'https://api.berkshelf.com' site :opscode ``` #### correct ``` source 'https://supermarket.chef.io' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_legacyberksfilesource/MacOsXUserdefaults ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/MacOsXUserdefaults` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.0+ | The mac_os_x_userdefaults resource was renamed to macos_userdefaults when it was added to Chef Infra Client 14.0. The new resource name should be used. ### Examples #### incorrect ``` mac_os_x_userdefaults 'full keyboard access to all controls' do domain 'AppleKeyboardUIMode' global true value '2' end ``` #### correct ``` macos_userdefaults 'full keyboard access to all controls' do domain 'AppleKeyboardUIMode' global true value '2' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_macosxuserdefaults/MinitestHandlerUsage ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/MinitestHandlerUsage` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use Chef InSpec for testing instead of the Minitest Handler cookbook pattern. ### Examples #### incorrect ``` depends 'minitest-handler' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.4.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_minitesthandlerusage/NodeInitPackage =============== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/NodeInitPackage` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use node[‘init_package’] to check for systemd instead of reading the contents of ‘/proc/1/comm’ ### Examples #### incorrect ``` ::File.open('/proc/1/comm').gets.chomp == 'systemd' ::File.open('/proc/1/comm').chomp == 'systemd' File.open('/proc/1/comm').gets.chomp == 'systemd' File.open('/proc/1/comm').chomp == 'systemd' IO.read('/proc/1/comm').chomp == 'systemd' IO.read('/proc/1/comm').gets.chomp == 'systemd' ::IO.read('/proc/1/comm').chomp == 'systemd' ::IO.read('/proc/1/comm').gets.chomp == 'systemd' File.exist?('/proc/1/comm') && File.open('/proc/1/comm').chomp == 'systemd' only_if 'test -f /bin/systemctl && /bin/systemctl' ``` #### correct ``` node['init_package'] == 'systemd' only_if { node['init_package'] == 'systemd' } ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.22.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_nodeinitpackage/OpensslRsaKeyResource ===================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/OpensslRsaKeyResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.0+ | The openssl_rsa_key resource was renamed to openssl_rsa_private_key in Chef Infra Client 14.0. The new resource name should be used. ### Examples #### incorrect ``` openssl_rsa_key '/etc/httpd/ssl/server.key' do key_length 2048 end ``` #### correct ``` openssl_rsa_private_key '/etc/httpd/ssl/server.key' do key_length 2048 end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_opensslrsakeyresource/NodeRolesInclude ================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/NodeRolesInclude` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use `node.role?('foo')` to check if a node includes a role instead of `node['roles'].include?('foo')`. ### Examples #### incorrect ``` node['roles'].include?('foo') ``` #### correct ``` node.role?('foo') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.1.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_noderolesinclude/OpensslX509Resource =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/OpensslX509Resource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.4+ | The openssl_x509 resource was renamed to openssl_x509_certificate in Chef Infra Client 14.4. The new resource name should be used. ### Examples #### incorrect ``` openssl_x509 '/etc/httpd/ssl/mycert.pem' do common_name 'www.f00bar.com' org 'Foo Bar' org_unit 'Lab' country 'US' end ``` #### correct ``` openssl_x509_certificate '/etc/httpd/ssl/mycert.pem' do common_name 'www.f00bar.com' org 'Foo Bar' org_unit 'Lab' country 'US' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_opensslx509resource/OsxConfigProfileResource ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/OsxConfigProfileResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The osx_config_profile resource was renamed to osx_profile. The new resource name should be used. ### Examples #### incorrect ``` osx_config_profile 'Install screensaver profile' do profile 'screensaver/com.company.screensaver.mobileconfig' end ``` #### correct ``` osx_profile 'Install screensaver profile' do profile 'screensaver/com.company.screensaver.mobileconfig' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_osxconfigprofileresource/PowerShellGuardInterpreter ========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/PowerShellGuardInterpreter` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 13.0+ | PowerShell is already set as the default guard interpreter for `powershell_script` and `batch` resources in Chef Infra Client 13 and later and does not need to be specified. ### Examples #### incorrect ``` powershell_script 'Create Directory' do code "New-Item -ItemType Directory -Force -Path C:\mydir" guard_interpreter :powershell_script end batch 'Create Directory' do code "mkdir C:\mydir" guard_interpreter :powershell_script end ``` #### correct ``` powershell_script 'Create Directory' do code "New-Item -ItemType Directory -Force -Path C:\mydir" end batch 'Create Directory' do code "mkdir C:\mydir" end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.9.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_powershellguardinterpreter/PowershellInstallPackage ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/PowershellInstallPackage` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 12.16+ | Use the powershell_package resource built into Chef Infra Client instead of the powershell_script resource to run Install-Package #### correct powershell_package ‘docker’ ### Examples #### incorrect ``` powershell_script 'Expand website' do code 'Install-Package -Name docker' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_powershellinstallpackage/PowershellInstallWindowsFeature =============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/PowershellInstallWindowsFeature` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 14.0+ | Use the windows_feature resource built into Chef Infra Client 14+ instead of the powershell_script resource to run Install-WindowsFeature or Add-WindowsFeature #### correct windows_feature ‘Net-framework-Core’ do action :install install_method :windows_feature_powershell end ### Examples #### incorrect ``` powershell_script 'Install Feature' do code 'Install-WindowsFeature -Name "Net-framework-Core"' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_powershellinstallwindowsfeature/PropertyWithNameAttribute ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/PropertyWithNameAttribute` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | When using properties in a custom resource you should use name_property not the legacy name_attribute from the days of attributes ### Examples #### incorrect ``` property :bob, String, name_attribute: true ``` #### correct ``` property :bob, String, name_property: true ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_propertywithnameattribute/PowershellScriptExpandArchive ============================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/PowershellScriptExpandArchive` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 15.0+ | Use the archive_file resource built into Chef Infra Client 15+ instead of using the powershell_script resource to run Expand-Archive ### Examples #### incorrect ``` powershell_script 'Expand website' do code 'Expand-Archive "C:\\file.zip" -DestinationPath "C:\\inetpub\\wwwroot\\" -Force' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_powershellscriptexpandarchive/ProvidesFromInitialize ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ProvidesFromInitialize` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Provides should be set using the `provides` resource DSL method instead of instead of setting @provides in the initialize method. ### Examples #### incorrect ``` def initialize(*args) super @provides = :foo end ``` #### correct ``` provides :foo ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.0.0 | String | Include | * `**/resources/*.rb` * `**/providers/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_providesfrominitialize/ResourceForcingCompileTime ========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ResourceForcingCompileTime` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | The hostname, build_essential, chef_gem, and ohai_hint resources include ‘compile_time’ properties, which should be used to force the resources to run at compile time by setting `compile_time true`. ### Examples #### incorrect ``` build_essential 'install build tools' do action :nothing end.run_action(:install) ``` #### correct ``` build_essential 'install build tools' do compile_time true end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.18.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_resourceforcingcompiletime/RespondToProvides ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/RespondToProvides` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | In Chef Infra Client 12+ is is no longer necessary to gate the use of the provides methods in resources with `if respond_to?(:provides)` or `if defined? provides`. ### Examples #### incorrect ``` provides :foo if respond_to?(:provides) provides :foo if defined? provides ``` #### correct ``` provides :foo ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Include | * `**/providers/*.rb` * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_respondtoprovides/ResourceNameFromInitialize ========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ResourceNameFromInitialize` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The resource name can now be specified using the `resource_name` helper instead of using the @resource_name variable in the resource provider initialize method. In general we recommend against writing HWRPs, but if HWRPs are necessary you should utilize as much of the resource DSL as possible. #### correct resource_name :create ### Examples #### incorrect ``` def initialize(*args) super @resource_name = :foo end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.10.0 | String | Include | * `**/resources/*.rb` * `**/providers/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_resourcenamefrominitialize/SetOrReturnInResources ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/SetOrReturnInResources` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | set_or_return within a method should not be used to define property in a resource. Instead use the property method which properly validates and defines properties in a way that works with reporting and documentation functionality in Chef Infra Client ### Examples #### incorrect ``` def severity(arg = nil) set_or_return( :severity, arg, :kind_of => String, :default => nil ) end ``` #### correct ``` property :severity, String ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_setorreturninresources/RespondToInMetadata =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/RespondToInMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 12.15+ | It is not longer necessary respond_to?(:foo) or defined?(foo) in metadata. This was used to support new metadata methods in Chef 11 and early versions of Chef 12. ### Examples #### incorrect ``` chef_version '>= 13' if respond_to?(:chef_version) chef_version '>= 13' if defined?(chef_version) chef_version '>= 13' unless defined?(Ridley::Chef::Cookbook::Metadata) if defined(chef_version) chef_version '>= 13' end ``` #### correct ``` chef_version '>= 13' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_respondtoinmetadata/RespondToCompileTime ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/RespondToCompileTime` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 12.1+ | There is no need to check if the chef_gem resource supports compile_time as Chef Infra Client 12.1 and later support the compile_time property. ### Examples #### incorrect ``` chef_gem 'ultradns-sdk' do compile_time true if Chef::Resource::ChefGem.method_defined?(:compile_time) action :nothing end chef_gem 'ultradns-sdk' do compile_time true if Chef::Resource::ChefGem.instance_methods(false).include?(:compile_time) action :nothing end chef_gem 'ultradns-sdk' do compile_time true if respond_to?(:compile_time) action :nothing end ``` #### correct ``` chef_gem 'ultradns-sdk' do compile_time true action :nothing end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.3.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_respondtocompiletime/RespondToResourceName ===================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/RespondToResourceName` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Chef Infra Client 12.5 introduced the resource_name method for resources. Many cookbooks used respond_to?(:resource_name) to provide backwards compatibility with older chef-client releases. This backwards compatibility is no longer necessary. ### Examples #### incorrect ``` resource_name :foo if respond_to?(:resource_name) ``` #### correct ``` resource_name :foo ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_respondtoresourcename/SevenZipArchiveResource ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/SevenZipArchiveResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 15.0+ | Use the archive_file resource built into Chef Infra Client 15+ instead of the seven_zip_archive ### Examples #### incorrect ``` seven_zip_archive "C:\file.zip" do path 'C:\expand_here' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_sevenziparchiveresource/ShellOutHelper ============== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ShellOutHelper` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 12.11+ | Use the built-in `shell_out` helper available in Chef Infra Client 12.11+ instead of calling `Mixlib::ShellOut.new('foo').run_command`. ### Examples #### incorrect ``` Mixlib::ShellOut.new('foo').run_command ``` #### correct ``` shell_out('foo') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.5.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_shellouthelper/ShellOutToChocolatey ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ShellOutToChocolatey` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Use the Chocolatey resources built into Chef Infra Client instead of shelling out to the choco command powershell_script ‘add artifactory choco source’ do code “choco source add -n=artifactory -s=‘<https://mycorp.jfrog.io/mycorp/api/nuget/chocolatey-remote'> -u foo -p bar"x not_if ‘choco source list | findstr artifactory’ end ### Examples #### incorrect ``` execute 'install package foo' do command "choco install --source=artifactory \"foo\" -y --no-progress --ignore-package-exit-codes" end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.5.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_shellouttochocolatey/SimplifyAptPpaSetup =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/SimplifyAptPpaSetup` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The apt_repository resource allows setting up PPAs without using the full URL to ppa.launchpad.net, which should be used to simplify the resource code in your cookbooks. ### Examples #### incorrect ``` apt_repository 'atom-ppa' do uri 'http://ppa.launchpad.net/webupd8team/atom/ubuntu' components ['main'] keyserver 'keyserver.ubuntu.com' key 'C2518248EEA14886' end ``` #### correct ``` apt_repository 'atom-ppa' do uri 'ppa:webupd8team/atom' components ['main'] keyserver 'keyserver.ubuntu.com' key 'C2518248EEA14886' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.21.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_simplifyaptppasetup/UnnecessaryDependsChef15 ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/UnnecessaryDependsChef15` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 15.0+ | Don’t depend on cookbooks made obsolete by Chef Infra Client 15.0+. These community cookbooks contain resources that are now included in Chef Infra Client itself. ### Examples #### incorrect ``` depends 'libarchive' depends 'windows_dns' depends 'windows_uac' depends 'windows_dfs' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.19.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_unnecessarydependschef15/SysctlParamResource =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/SysctlParamResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.0+ | The sysctl_param resource was renamed to sysctl when it was added to Chef Infra Client 14.0. The new resource name should be used. ### Examples #### incorrect ``` sysctl_param 'fs.aio-max-nr' do value '1048576' end ``` #### correct ``` sysctl 'fs.aio-max-nr' do value '1048576' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_sysctlparamresource/UnnecessaryDependsChef14 ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/UnnecessaryDependsChef14` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 14.0+ | Don’t depend on cookbooks made obsolete by Chef Infra Client 14.0+ These community cookbooks contain resources that are now included in Chef Infra Client itself. ### Examples #### incorrect ``` depends 'build-essential' depends 'chef_handler' depends 'chef_hostname' depends 'dmg' depends 'mac_os_x' depends 'swap' depends 'sysctl' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_unnecessarydependschef14/UnnecessaryMixlibShelloutRequire ================================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/UnnecessaryMixlibShelloutRequire` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Chef Infra Client 12.4+ includes mixlib/shellout automatically in resources and providers. ### Examples #### incorrect ``` require 'mixlib/shellout' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.12.0 | String | Include | * `**/resources/*.rb` * `**/providers/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_unnecessarymixlibshelloutrequire/UseBuildEssentialResource ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/UseBuildEssentialResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use the build_essential resource from the build-essential cookbook 5.0+ or Chef Infra Client 14+ instead of using the build-essential::default recipe. ### Examples #### incorrect ``` depends 'build-essential' include_recipe 'build-essential::default' include_recipe 'build-essential' ``` #### correct ``` build_essential 'install compilation tools' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_usebuildessentialresource/UseChefLanguageCloudHelpers =========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/UseChefLanguageCloudHelpers` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 15.5+ | Chef Infra Client 15.5 and later include cloud helpers to make detecting instances that run on public and private clouds easier. ### Examples #### incorrect ``` node['cloud']['provider'] == 'alibaba' node['cloud']['provider'] == 'ec2' node['cloud']['provider'] == 'gce' node['cloud']['provider'] == 'rackspace' node['cloud']['provider'] == 'eucalyptus' node['cloud']['provider'] == 'linode' node['cloud']['provider'] == 'openstack' node['cloud']['provider'] == 'azure' node['cloud']['provider'] == 'digital_ocean' node['cloud']['provider'] == 'softlayer' ``` #### correct ``` alibaba? ec2? gce? rackspace? eucalyptus? linode? openstack? azure? digital_ocean? softlayer? ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.22.0 | String | Include | * `**/resources/*.rb` * `**/providers/*.rb` * `**/recipes/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_usecheflanguagecloudhelpers/UseChefLanguageSystemdHelper ============================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/UseChefLanguageSystemdHelper` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 15.5+ | Chef Infra Client 15.5 and later include a `systemd?` helper for checking if a Linux system uses systemd. ### Examples #### incorrect ``` node['init_package'] == 'systemd' ``` #### correct ``` systemd? ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.24.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_usecheflanguagesystemdhelper/UseChefLanguageEnvHelpers ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/UseChefLanguageEnvHelpers` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 15.5+ | Chef Infra Client 15.5 and later include a large number of new helpers in the Chef Infra Language to simplify checking the system configuration in recipes and resources. These should be used when possible over more complex attributes or ENV var comparisons. ### Examples #### incorrect ``` ENV['CI'] ENV['TEST_KITCHEN'] ``` #### correct ``` ci? kitchen? ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.21.0 | String | Include | * `**/resources/*.rb` * `**/providers/*.rb` * `**/recipes/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_usecheflanguageenvhelpers/WhyRunSupportedTrue =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/WhyRunSupportedTrue` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 13.0+ | whyrun_supported? no longer needs to be set to true as that is the default in Chef Infra Client 13+ ### Examples #### incorrect ``` def whyrun_supported? true end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/resources/*.rb` * `**/providers/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_whyrunsupportedtrue/WindowsRegistryUAC ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/WindowsRegistryUAC` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 15.0+ | Chef Infra Client 15.0 and later includes a windows_uac resource that should be used to set Windows UAC values instead of setting registry keys directly. ### Examples #### incorrect ``` registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' do values [{ name: 'EnableLUA', type: :dword, data: 0 }, { name: 'PromptOnSecureDesktop', type: :dword, data: 0 }, { name: 'ConsentPromptBehaviorAdmin', type: :dword, data: 0 }, ] action :create end ``` #### correct ``` windows_uac 'Set Windows UAC settings' do enable_uac false prompt_on_secure_desktop true consent_behavior_admins :no_prompt end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.22.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_windowsregistryuac/UseMultipackageInstalls ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/UseMultipackageInstalls` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Pass an array of packages to package resources instead of iterating over an array of packages when using multi-package capable package subsystem such as apt, yum, chocolatey, dnf, or zypper. Multi-package installs are faster and simplify logs. ### Examples #### incorrect ``` %w(bmon htop vim curl).each do |pkg| package pkg do action :install end end ``` #### correct ``` package %w(bmon htop vim curl) ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.0.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_usemultipackageinstalls/UseRequireRelative ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/UseRequireRelative` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Instead of using require with a File.expand_path and **FILE** use the simpler require_relative method. ### Examples #### incorrect ``` require File.expand_path('../../libraries/helpers', __FILE__) ``` #### correct ``` require_relative '../libraries/helpers' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.22.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_userequirerelative/UsesZypperRepo ============== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/UsesZypperRepo` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | 13.3+ | The zypper_repo resource was renamed zypper_repository when it was added to Chef Infra Client 13.3. ### Examples #### incorrect ``` zypper_repo 'apache' do baseurl 'http://download.opensuse.org/repositories/Apache' path '/openSUSE_Leap_42.2' type 'rpm-md' priority '100' end ``` #### correct ``` zypper_repository 'apache' do baseurl 'http://download.opensuse.org/repositories/Apache' path '/openSUSE_Leap_42.2' type 'rpm-md' priority '100' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_useszypperrepo/AttributeMetadata ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/AttributeMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The attribute metadata.rb method is not used and is unnecessary in cookbooks. ### Examples #### incorrect ``` attribute 'zookeeper_bridge/server', display_name: 'zookeeper server', description: 'Zookeeper server address.', type: 'string', required: 'optional', default: '"127.0.0.1:2181"' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_attributemetadata/WindowsScResource ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/WindowsScResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 14.0+ | The sc_windows resource from the sc cookbook allowed for the creation of windows services on legacy Chef Infra Client releases. Chef Infra Client 14.0 and later includes :create, :delete, and :configure actions without the need for additional cookbook dependencies. See the windows_service documentation at [https://docs.chef.io/resources/windows_service](../../../resources/windows_service) for additional details on creating services with the windows_service resource. ### Examples #### incorrect ``` sc_windows 'chef-client' do path "C:\\opscode\\chef\\bin" action :create end ``` #### correct ``` windows_service 'chef-client' do action :create binary_path_name "C:\\opscode\\chef\\bin" end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_windowsscresource/ZipfileResource =============== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/ZipfileResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 15.0+ | Use the archive_file resource built into Chef Infra Client 15+ instead of the zipfile resource from the zipfile cookbook. ### Examples #### incorrect ``` zipfile "C:\file.zip" do path 'C:\expand_here' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.12.0 | String | | | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_zipfileresource/AptRepositoryDistributionDefault ================================ [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/AptRepositoryDistributionDefault` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | There is no need to pass `distribution node['lsb']['codename']` to an apt_repository resource as this is done automatically by the apt_repository resource. ### Examples #### incorrect ``` apt_repository 'my repo' do uri 'http://packages.example.com/debian' components %w(stable main) deb_src false distribution node['lsb']['codename'] end ``` #### correct ``` apt_repository 'my repo' do uri 'http://packages.example.com/debian' components %w(stable main) deb_src false end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.17.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_aptrepositorydistributiondefault/WindowsZipfileUsage =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Modernize` The full name of the cop is: `Chef/Modernize/WindowsZipfileUsage` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | 15.0+ | Use the archive_file resource built into Chef Infra Client 15+ instead of the windows_zipfile from the Windows cookbook ### Examples #### incorrect ``` windows_zipfile 'C:\\files\\' do source 'C:\\Temp\\file.zip' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.4.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_modernize_windowszipfileusage/CustomResourceWithAllowedActions ================================ [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/CustomResourceWithAllowedActions` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | It is not necessary to set `actions` or `allowed_actions` in custom resources as Chef Infra Client determines these automatically from the set of all actions defined in the resource. ### Examples #### incorrect ``` allowed_actions [:create, :remove] # also bad actions [:create, :remove] ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Include | * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_customresourcewithallowedactions/AptRepositoryNotifiesAptUpdate ============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/AptRepositoryNotifiesAptUpdate` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | There is no need to notify an apt-get update when an apt_repository is created as this is done automatically by the apt_repository resource. ### Examples #### incorrect ``` apt_repository 'my repo' do uri 'http://packages.example.com/debian' components %w(stable main) deb_src false notifies :run, 'execute[apt-get update]', :immediately end ``` #### correct ``` apt_repository 'my repo' do uri 'http://packages.example.com/debian' components %w(stable main) deb_src false end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.17.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_aptrepositorynotifiesaptupdate/ConflictsMetadata ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/ConflictsMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The conflicts metadata.rb method is not used and is unnecessary in cookbooks. ### Examples #### incorrect ``` conflicts "another_cookbook" ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_conflictsmetadata/DoubleCompileTime ================= [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/DoubleCompileTime` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | If a resource includes the `compile_time` property there’s no need to also use `.run_action(:some_action)` on the resource block ### Examples #### incorrect ``` chef_gem 'deep_merge' do action :nothing compile_time true end.run_action(:install) ``` #### correct ``` chef_gem 'deep_merge' do action :install compile_time true end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.13.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_doublecompiletime/NamePropertyIsRequired ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/NamePropertyIsRequired` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | When using properties in a custom resource you shouldn’t set a property to be both required and a name_property. Name properties are a way to optionally override the name given to the resource block in cookbook code. In your resource code you use the name_property and if the user doesn’t pass in anything to that property its value will be populated with resource block’s name. This allows users to provide more friendly resource names for logging that give additional context on the change being made. How about a nice example! Here we have a resource called ntp_config that has a name_property of config_file. All throughout the code of this resource we’d use new_resource.config_file when referencing the path to the config. We can use a friendly name for the block and specific a value to config_file ntp_config ‘Configure the main config file’ do config_file ‘/etc/ntp/ntp.conf’ action :create end We can also just set the config path as the resource block and Chef will make sure to pass this in as new_resource.config_file as well. ntp_config ‘/etc/ntp/ntp.conf’ do action :create end The core tenant of the name property feature is that these properties are optional and making them required effectively turns off the functionality provided by name properties. If the goal is to always require the user to pass the config_file property then it should just be made a required property and not a name_property. ### Examples #### incorrect ``` property :config_file, String, required: true, name_property: true attribute :config_file, String, required: true, name_attribute: true ``` #### correct ``` property :config_file, String, required: true ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_namepropertyisrequired/MultiplePlatformChecks ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/MultiplePlatformChecks` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | You can pass multiple values to the platform? and platform_family? helpers instead of calling the helpers multiple times. ### Examples #### incorrect ``` platform?('redhat') || platform?('ubuntu') platform_family?('debian') || platform_family?('rhel') ``` #### correct ``` platform?('redhat', 'ubuntu') platform_family?('debian', 'rhel') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.10.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_multipleplatformchecks/GroupingMetadata ================ [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/GroupingMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The grouping metadata.rb method is not used and is unnecessary in cookbooks. ### Examples #### incorrect ``` grouping 'windows_log_rotate', title: 'Demonstration cookbook with code to switch loggers' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.19.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_groupingmetadata/LongDescriptionMetadata ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/LongDescriptionMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The long_description metadata.rb method is not used and is unnecessary in cookbooks. ### Examples #### incorrect ``` long_description 'this is my cookbook and this description will never be seen' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_longdescriptionmetadata/OhaiAttributeToString ===================== [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/OhaiAttributeToString` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Many Ohai node attributes are already strings and don’t need to be cast to strings again ### Examples #### incorrect ``` node['platform'].to_s node['platform_family'].to_s node['platform_version'].to_s node['fqdn'].to_s node['hostname'].to_s node['os'].to_s node['name'].to_s ``` #### correct ``` node['platform'] node['platform_family'] node['platform_version'] node['fqdn'] node['hostname'] node['os'] node['name'] ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.10.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_ohaiattributetostring/PropertySplatRegex ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/PropertySplatRegex` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | When a property has a type of String it can accept any string. There is no need to also validate string inputs against a regex that accept all values. ### Examples #### incorrect ``` property :config_file, String, regex: /.*/ attribute :config_file, String, regex: /.*/ ``` #### correct ``` property :config_file, String attribute :config_file, String ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.21.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_propertysplatregex/ProvidesMetadata ================ [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/ProvidesMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The provides metadata.rb method is not used and is unnecessary in cookbooks. ### Examples #### incorrect ``` provides "some_thing" ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_providesmetadata/PropertyWithRequiredAndDefault ============================== [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/PropertyWithRequiredAndDefault` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | When using properties in a custom resource you shouldn’t set a property to required and then provide a default value. If a property is required the user will always pass in a value and the default will never be used. In Chef Infra Client 13+ this became an error. ### Examples #### incorrect ``` property :bob, String, required: true, default: 'foo' ``` #### correct ``` property :bob, String, required: true ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_propertywithrequiredanddefault/RecipeMetadata ============== [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/RecipeMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The recipe metadata.rb method is not used and is unnecessary in cookbooks. Recipes should be documented in the cookbook’s README.md file instead. ### Examples #### incorrect ``` recipe 'openldap::default', 'Install and configure OpenLDAP' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_recipemetadata/ReplacesMetadata ================ [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/ReplacesMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The replaces metadata.rb method is not used and is unnecessary in cookbooks. Replacements for existing cookbooks should be documented in the cookbook’s README.md file instead. ### Examples #### incorrect ``` replaces "another_cookbook" ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_replacesmetadata/ResourceWithNothingAction ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/ResourceWithNothingAction` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Chef Infra Client provides the :nothing action by default for every resource. There is no need to define a :nothing action in your resource code. ### Examples #### incorrect ``` action :nothing # let's do nothing end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.12.0 | String | Include | * `**/libraries/*.rb` * `**/resources/*.rb` * `**/providers/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_resourcewithnothingaction/SuggestsMetadata ================ [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/SuggestsMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The suggests metadata.rb method is not used and is unnecessary in cookbooks. ### Examples #### incorrect ``` suggests "another_cookbook" ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_suggestsmetadata/SensitivePropertyInResource =========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/SensitivePropertyInResource` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Every Chef Infra resource already includes a sensitive property with a default value of false. #### incorrect property :sensitive, [true, false], default: false ### Examples ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_sensitivepropertyinresource/StringPropertyWithNilDefault ============================ [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/StringPropertyWithNilDefault` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Properties have a nil value by default so there is no need to set the default value to nil. ### Examples #### incorrect ``` property :config_file, String, default: nil property :config_file, [String, NilClass], default: nil ``` #### correct ``` property :config_file, String property :config_file, [String, NilClass] ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.21.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_stringpropertywithnildefault/UnnecessaryDesiredState ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/UnnecessaryDesiredState` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | There is no need to set a property/attribute to desired_state: true as all properties/attributes have a desired_state of true by default. ### Examples #### incorrect ``` property :foo, String, desired_state: true attribute :foo, String, desired_state: true ``` #### correct ``` property :foo, String attribute :foo, String ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_unnecessarydesiredstate/UnnecessaryNameProperty ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/UnnecessaryNameProperty` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | There is no need to define a property or attribute named :name in a resource as Chef Infra defines this on all resources by default. ### Examples #### incorrect ``` property :name, String property :name, String, name_property: true attribute :name, kind_of: String attribute :name, kind_of: String, name_attribute: true attribute :name, name_attribute: true, kind_of: String ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.8.0 | String | Include | * `**/resources/*.rb` * `**/libraries/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_unnecessarynameproperty/UseCreateIfMissing ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/RedundantCode` The full name of the cop is: `Chef/RedundantCode/UseCreateIfMissing` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use the `:create_if_missing` action instead of `not_if` with a `::File.exist(FOO)` check. ### Examples #### incorrect ``` cookbook_file '/logs/foo/error.log' do source 'error.log' owner 'root' group 'root' mode '0644' not_if { ::File.exists?('/logs/foo/error.log') } end remote_file 'Download file' do path '/foo/bar' source 'https://foo.com/bar' owner 'root' group 'root' mode '0644' not_if { ::File.exist?('/foo/bar') } end ``` #### correct ``` cookbook_file '/logs/foo/error.log' do source 'error.log' owner 'root' group 'root' mode '0644' action :create_if_missing end remote_file 'Download file' do path '/foo/bar' source 'https://foo.com/bar' owner 'root' group 'root' mode '0644' action :create_if_missing end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.2.0 | String | Exclude | * `**/metadata.rb` * `**/attributes/*.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_redundantcode_usecreateifmissing/DefaultMetadataMaintainer ========================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Sharing` The full name of the cop is: `Chef/Sharing/DefaultMetadataMaintainer` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Metadata contains default maintainer information from the `chef generate cookbook` command. This should be updated to reflect that actual maintainer of the cookbook. ### Examples #### incorrect ``` maintainer 'YOUR_COMPANY_NAME' maintainer_email 'YOUR_EMAIL' maintainer 'The Authors' maintainer_email '<EMAIL>'``` #### correct ```ruby maintainer '<NAME>' maintainer_email '<EMAIL>' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.4.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_sharing_defaultmetadatamaintainer/SshPrivateKey ============= [All Cookstyle Cops](../cops/index) The department is: `Chef/Security` The full name of the cop is: `Chef/Security/SshPrivateKey` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Do not include plain text SSH private keys in your cookbook code. This sensitive data should be fetched from secrets management systems so that secrets are not uploaded in plain text to the Chef Infra Server or committed to source control systems. ### Examples #### incorrect ``` file '/Users/bob_bobberson/.ssh/id_rsa' do content '-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----' mode '600' end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | | String | | | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_security_sshprivatekey/EmptyMetadataField ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Sharing` The full name of the cop is: `Chef/Sharing/EmptyMetadataField` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | metadata.rb should not include fields with an empty string. Either don’t include the field or add a value. ### Examples #### incorrect ``` license '' ``` #### correct ``` license 'Apache-2.0' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.8.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_sharing_emptymetadatafield/IncludePropertyDescriptions =========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Sharing` The full name of the cop is: `Chef/Sharing/IncludePropertyDescriptions` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | 13.9+ | Resource properties should include description fields to allow automated documentation. Requires Chef Infra Client 13.9 or later. ### Examples #### incorrect ``` property :foo, String ``` #### correct ``` property :foo, String, description: "Set the important thing to..." ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.1.0 | String | Include | * `**/libraries/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_sharing_includepropertydescriptions/IncludeResourceExamples ======================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Sharing` The full name of the cop is: `Chef/Sharing/IncludeResourceExamples` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | 13.9+ | Resources should include examples field to allow automated documentation. Requires Chef Infra Client 13.9 or later. ### Examples ``` #### correct ```ruby examples <<~DOC **Specify a global domain value** ```ruby macos_userdefaults 'full keyboard access to all controls' do key 'AppleKeyboardUIMode' value '2' end ``` DOC ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.10.0 | String | Include | * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_sharing_includeresourceexamples/ChefWhaaat ========== [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/ChefWhaaat` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | All Versions | Checks for comments that mention “Chef” without context. Do you mean Chef Infra or Chef Software? ### Examples #### incorrect ``` Chef makes software Chef configures your systems ``` #### correct ``` Chef Software makes software Chef Infra configures your systems ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.20.0 | String | | | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_chefwhaaat/InvalidLicenseString ==================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Sharing` The full name of the cop is: `Chef/Sharing/InvalidLicenseString` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | metadata.rb license field should include a SPDX compliant string or “all right reserved” (not case sensitive) list of valid SPDX.org license strings. To build an array run this ruby: ``` require 'json' require 'net/http' json_data = JSON.parse(Net::HTTP.get(URI('https://raw.githubusercontent.com/spdx/license-list-data/master/json/licenses.json'))) licenses = json_data['licenses'].map {|l| l['licenseId'] }.sort ``` ### Examples #### incorrect ``` license 'Apache 2.0' ``` #### correct ``` license 'Apache-2.0' license 'all rights reserved' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.2.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_sharing_invalidlicensestring/IncludeResourceDescriptions =========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Sharing` The full name of the cop is: `Chef/Sharing/IncludeResourceDescriptions` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | No | 13.9+ | Resources should include description fields to allow automated documentation. Requires Chef Infra Client 13.9 or later. ### Examples ``` #### correct ```ruby resource_name :foo description "The foo resource is used to do..." ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.1.0 | String | Include | * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_sharing_includeresourcedescriptions/InsecureCookbookURL =================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Sharing` The full name of the cop is: `Chef/Sharing/InsecureCookbookURL` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use secure Github and Gitlab URLs for source_url and issues_url ### Examples #### incorrect ``` source_url 'http://github.com/something/something' source_url 'http://www.github.com/something/something' source_url 'http://www.gitlab.com/something/something' source_url 'http://gitlab.com/something/something' ``` #### correct ``` source_url 'http://github.com/something/something' source_url 'http://gitlab.com/something/something' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_sharing_insecurecookbookurl/AttributeKeys ============= [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/AttributeKeys` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Check which style of keys are used to access node attributes. There are two supported styles: “symbols” and “strings”. ### Examples #### incorrect ``` node['foo'] node["foo"] ``` #### correct ``` node[:foo] ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.0.0 | String | Exclude | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_attributekeys/CommentFormat ============= [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/CommentFormat` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Checks for incorrectly formatted headers ### Examples #### incorrect ``` Copyright 2013-2016 Chef Software, Inc. Recipe default.rb Attributes default.rb License Apache2 Cookbook tomcat Cookbook Name:: Tomcat Attributes File:: default ``` #### correct ``` Copyright:: 2013-2016 Chef Software, Inc. Recipe:: default.rb Attributes:: default.rb License:: Apache License, Version 2.0 Cookbook:: Tomcat ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.0.0 | String | Exclude | * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_commentformat/CopyrightCommentFormat ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/CopyrightCommentFormat` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | Yes | All Versions | Checks for incorrectly formatted copyright comments. ### Examples #### incorrect ``` Copyright:: 2013-2022 Opscode, Inc. Copyright:: 2013-2022 Chef Inc. Copyright:: 2013-2022 Chef Software Inc. Copyright:: 2009-2010 2013-2022 Chef Software Inc. Copyright:: Chef Software Inc. Copyright:: <NAME> Copyright:: Copyright (c) 2015-2022 Chef Software, Inc. ``` #### correct ``` Copyright:: 2013-2022 Chef Software, Inc. Copyright:: 2013-2022 <NAME> Copyright:: 2019 37Signals, Inc. ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.0.0 | String | | | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_copyrightcommentformat/DefaultCopyrightComments ======================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/DefaultCopyrightComments` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | No | All Versions | Checks for default copyright comments from the chef generator cookbook command ### Examples #### incorrect ``` Copyright:: 2019 YOUR_NAME Copyright:: 2019 YOUR_COMPANY_NAME ``` #### correct ``` Copyright:: 2019 <NAME> Copyright:: 2019 Chef Software, Inc. ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.12.0 | String | | | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_defaultcopyrightcomments/FileMode ======== [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/FileMode` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use strings to represent file modes to avoid confusion between octal and base 10 integer formats. ### Examples #### incorrect ``` remote_directory '/etc/my.conf' do content 'some content' mode 0600 action :create end remote_directory 'handler' do source 'handlers' recursive true files_mode 644 action :create end ``` #### correct ``` remote_directory '/etc/my.conf' do content 'some content' mode '600' action :create end remote_directory 'handler' do source 'handlers' recursive true files_mode '644' action :create end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.0.0 | String | Exclude | * `**/attributes/*` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_filemode/CommentSentenceSpacing ====================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/CommentSentenceSpacing` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Not Enabled | Yes | All Versions | Replaces double spaces between sentences with a single space. Note: This is DISABLED by default. ### Examples ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.1.0 | String | | | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_commentsentencespacing/IncludeRecipeWithParentheses ============================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/IncludeRecipeWithParentheses` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | There is no need to wrap the recipe in parentheses when using the include_recipe helper. ### Examples #### incorrect ``` include_recipe('foo::bar') ``` #### correct ``` include_recipe 'foo::bar' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.11.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_includerecipewithparentheses/ImmediateNotificationTiming =========================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/ImmediateNotificationTiming` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use :immediately instead of :immediate for resource notification timing. ### Examples #### incorrect ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :immediate end ``` #### correct ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :immediately end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Exclude | * `**/attributes/*.rb` * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_immediatenotificationtiming/NegatingOnlyIf ============== [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/NegatingOnlyIf` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Instead of using only_if conditionals with ! to negate the returned value, use not_if which is easier to read ### Examples #### incorrect ``` package 'legacy-sysv-deps' do only_if { !systemd } end ``` #### correct ``` package 'legacy-sysv-deps' do not_if { systemd } end ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 6.2.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_negatingonlyif/SimplifyPlatformMajorVersionCheck ================================= [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/SimplifyPlatformMajorVersionCheck` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | When checking the major version number of a platform you can take the node[‘platform_version’] attribute and transform it to an integer to strip it down to just the major version number. This simple way of determining the major version number of a platform should be used instead of splitting the platform into multiple fields with ‘.’ as the delimiter. ### Examples #### incorrect ``` node['platform_version'].split('.').first node['platform_version'].split('.')[0] node['platform_version'].split('.').first.to_i node['platform_version'].split('.')[0].to_i ``` #### correct ``` # check to see if we're on RHEL 7 on a RHEL 7.6 node where node['platform_version] is 7.6.1810 if node['platform_version'].to_i == 7 ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.8.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_simplifyplatformmajorversioncheck/TrueClassFalseClassResourceProperties ===================================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/TrueClassFalseClassResourceProperties` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | When setting the allowed types for a resource to accept either true or false values it’s much simpler to use true and false instead of TrueClass and FalseClass. ### Examples #### incorrect ``` property :foo, [TrueClass, FalseClass] ``` #### correct ``` property :foo, [true, false] ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Include | * `**/libraries/*.rb` * `**/resources/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_trueclassfalseclassresourceproperties/OverlyComplexSupportsDependsMetadata ==================================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/OverlyComplexSupportsDependsMetadata` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Don’t loop over an array to set cookbook dependencies or supported platforms if you have fewer than three values to set. Setting multiple `supports` or `depends` values is simpler and easier to understand for new users. ### Examples #### incorrect ``` %w( debian ubuntu ).each do |os| supports os end %w( apt yum ).each do |cb| depends cb end ``` #### correct ``` supports 'debian' supports 'ubuntu' depends 'apt' depends 'yum' ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.19.0 | String | Include | * `**/metadata.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_overlycomplexsupportsdependsmetadata/UnnecessaryOSCheck ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/UnnecessaryOSCheck` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use the platform_family?() helpers instead of node[‘os] == ‘foo’ for platform_families that match one-to-one with OS values. These helpers are easier to read and can accept multiple platform arguments, which greatly simplifies complex platform logic. All values of `os` from Ohai match one-to-one with `platform_family` values except for `linux`, which has no single equivalent `platform_family`. ### Examples #### incorrect ``` node['os'] == 'darwin' node['os'] == 'windows' node['os'].eql?('aix') %w(netbsd openbsd freebsd).include?(node['os']) ``` #### correct ``` platform_family?('mac_os_x') platform_family?('windows') platform_family?('aix') platform_family?('netbsd', 'openbsd', 'freebsd) ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.21.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_unnecessaryoscheck/UnnecessaryPlatformCaseStatement ================================ [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/UnnecessaryPlatformCaseStatement` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use the platform?() and platform_family?() helpers instead of a case statement that only includes a single when statement. ### Examples #### incorrect ``` case node['platform'] when 'ubuntu' log "We're on Ubuntu" apt_update end case node['platform_family'] when 'rhel' include_recipe 'yum' end ``` #### correct ``` if platform?('ubuntu') log "We're on Ubuntu" apt_update end include_recipe 'yum' if platform_family?('rhel') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.16.0 | String | Exclude | * `**/metadata.rb` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_unnecessaryplatformcasestatement/UsePlatformHelpers ================== [All Cookstyle Cops](../cops/index) The department is: `Chef/Style` The full name of the cop is: `Chef/Style/UsePlatformHelpers` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | Use the platform?() and platform_family?() helpers instead of node[‘platform] == ‘foo’ and node[‘platform_family’] == ‘bar’. These helpers are easier to read and can accept multiple platform arguments, which greatly simplifies complex platform logic. ### Examples #### incorrect ``` node['platform'] == 'ubuntu' node['platform_family'] == 'debian' node['platform'] != 'ubuntu' node['platform_family'] != 'debian' %w(rhel suse).include?(node['platform_family']) node['platform'].eql?('ubuntu') ``` #### correct ``` platform?('ubuntu') !platform?('ubuntu') platform_family?('debian') !platform_family?('debian') platform_family?('rhel', 'suse') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 5.6.0 | String | Exclude | * `**/metadata.rb` * `**/libraries/*` * `**/Berksfile` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/chef_style_useplatformhelpers/AttributeHelper =============== [All Cookstyle Cops](../cops/index) The department is: `InSpec/Deprecations` The full name of the cop is: `InSpec/Deprecations/AttributeHelper` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | InSpec attributes have been renamed to inputs. Use the `input` method not the deprecation `attribute` method to access these values. ### Examples #### incorrect ``` login_defs_umask = attribute('login_defs_umask', value: '077', description: 'Default umask to set in login.defs') ``` #### correct ``` login_defs_umask = input('login_defs_umask', value: '077', description: 'Default umask to set in login.defs') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.14.0 | String | Include | * `**/controls/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/inspec_deprecations_attributehelper/Setting up Knife ================ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_setup.md) knife is a command-line tool that provides an interface between a local chef-repo and the Chef Infra Server. The knife command line tool must be configured to communicate with the Chef Infra Server as well as any other infrastructure within your organization. To configure knife to communicate with Chef Infra Server for the first time run `knife configure` to create a Chef Infra credentials file at `~/.chef/credentials`. Previous Chef Infra setups recommended setting up knife with a `config.rb` file. Configuring knife with `config.rb` is still valid, but only for working with a single Chef Infra Server with a single Chef Infra Server organization. ``` mkdir ~/.chef touch ~/.chef/config.rb ``` ``` New-Item -Path "c:\" -Name ".chef" -ItemType "directory" New-Item -ItemType "file" -Path "c:\.chef\config.rb" ``` The config.rb configuration can include arbitrary Ruby code to extend configuration beyond static values. This can be used to load environmental variables from the workstation. This makes it possible to write a single config.rb file that can be used by all users within your organization. This single file can also be checked into your chef-repo, allowing users to load different config.rb files based on which chef-repo they execute the commands from. This can be especially useful when each chef-repo points to a different chef server or organization. Example config.rb: ``` current_dir = File.dirname(__FILE__) user = ENV['CHEF_USER'] || ENV['USER'] node_name user client_key "#{ENV['HOME']}/chef-repo/.chef/#{user}.pem" chef_server_url "https://api.opscode.com/organizations/#{ENV['ORGNAME']}" syntax_check_cache_path "#{ENV['HOME']}/chef-repo/.chef/syntax_check_cache" cookbook_path ["#{current_dir}/../cookbooks"] cookbook_copyright "Your Company, Inc." cookbook_license "Apache-2.0" cookbook_email "<EMAIL>" # Amazon AWS knife[:aws_access_key_id] = ENV['AWS_ACCESS_KEY_ID'] knife[:aws_secret_access_key] = ENV['AWS_SECRET_ACCESS_KEY'] ``` **Profile Support since Chef 13.7** Knife profiles make switching knife between Chef Infra Servers or between organizations on the same Chef Infra Server easier. Knife profiles are an alternative to `config.rb`–you cannot use both. Set up knife profiles by adding them to the `.chef/credentials` file in your home directory on your workstation. The `credentials` file is TOML formatted. Each profile is listed as a separate ‘table’ name of your choice, and is followed by `key = value` pairs. The keys correspond to any setting permitted in the [config.rb](../workstation/config_rb/index) file. File paths, such as `client_key` or `validator_key`, are relative to `~/.chef` unless you provide absolute path. Identify clients with `client_name` (preferred) or `node_name`. Store credentials for use with target mode (`chef-client --target switch.example.org`) as a separate profile in the credentials file. Use the DNS name of the target as the profile name and surrounded by single quotes when the name contains a period. For example: `['switch.example.org']`. Keys that are valid configuration options get passed to train, such as `port`. ``` # Example .chef/credentials file [default] client_name = "barney" client_key = "barney_rubble.pem" chef_server_url = "https://api.chef.io/organizations/bedrock" # a 'config context' such as knife can be is configured as a separate table [default.knife] ssh_user = 'ubuntu' # this would have been knife[:ssh_user] in your config.rb aws_profile = 'engineering' use_sudo = true # a client_key may also be specified inline as in this example [dev] client_name = "admin" client_key = """ -----BEGIN RSA PRIVATE KEY----- <KEY> ...ABC123= -----END RSA PRIVATE KEY----- """ validator_key = "test-validator.pem" chef_server_url = "https://api.chef-server.dev/organizations/test" ['web.preprod'] client_name = "brubble" client_key = "preprod-brubble.pem" chef_server_url = "https://preprod.chef-server.dev/organizations/preprod" ['switch.example.org'] user = "cisco" password = "cisco" enable_password = "cisco" ``` There are four ways to select which profile to use and are listed in priority order: 1. Pass the `--profile` option to knife, e.g. `knife node list --profile dev`. 2. Set the profile name in the `CHEF_PROFILE` environment variable. 3. Write the profile name to the `~/.chef/context` file. 4. Otherwise, knife uses the ‘default’ profile. Knife Config ------------ **knife config support since Chef 14.4** Use the `knife config` command to manage your knife profiles. List your profiles with the `knife config list-profiles` command. For example: ``` knife config list-profiles ``` Returns something like: ``` ## Profile Client Key Server default barney ~/.chef/barney_rubble.pem https://api.chef.io/organizations/bedrock dev admin ~/.chef/admin.pem https://api.chef-server.dev/organizations/test web.preprod brubble ~/.chef/preprod-brubble.pem https://preprod.chef-server.dev/organizations/preprod switch.example.org btm ~/.chef/btm.pem https://localhost:443 ``` The line that begins with the asterisk is the currently selected profile. To change the current profile, run the `knife config use-profile NAME` command, which will write the profile name to the `~/.chef/context` file. Running `knife config get-profile` prints out the name of the currently selected profile. If you need to troubleshoot any settings, you can verify the value that knife is using with the `knife config get KEY` command, for example: ``` knife config get chef_server_url Loading from credentials file /home/barney/.chef/credentials chef_server_url: https://api.chef-server.dev/organizations/test ``` config.rb Configuration File ---------------------------- The `config.rb` file contains settings for the knife command-line tool and any installed knife plugins. See the [config.rb documentation](../workstation/config_rb/index) for a complete list of configuration options. ### Load Path Priority The config.rb file loads every time the knife command is invoked using the following load order: * From a specified location given the `--config` flag * From a specified location given the `$KNIFE_HOME` environment variable, if set * From a `config.rb` file within the current working directory, e.g., `./config.rb` * From a `config.rb` file within a `.chef` directory in the current working directory, e.g., `./.chef/config.rb` * From a `config.rb` file within a `.chef` directory located one directory above the current working directory, e.g., `../.chef/config.rb` * From `~/.chef/config.rb` (macOS and Linux platforms) or `c:\Users\<username>\.chef` (Microsoft Windows platform) Note On Microsoft Windows, the `config.rb` file is located at: `%HOMEDRIVE%:%HOMEPATH%\.chef` (e.g. `c:\Users\<username>\.chef`). In a script for Microsoft Windows, use: `%USERPROFILE%\chef-repo\.chef`. ### config.rb Configuration Within a Chef Repository Use knife configure command to generate your initial `config.rb` file in your home directory. See [knife configure](../workstation/knife_configure/index) for details. Setting Your Text Editor ------------------------ Some knife commands, such as `knife data bag edit`, require that information be edited as JSON data using a text editor. For example, the following command: ``` knife data bag edit admins admin_name ``` opens up the text editor with data similar to: ``` { "id": "admin_name" } ``` Then make changes to that file: ``` { "id": "<NAME>." "description": "I am passing the time by letting time pass over me ..." } ``` The type of text editor that is used by knife can be configured by adding an entry to your config.rb file, or by setting an `EDITOR` environment variable. For example, to configure knife to open the `vim` text editor, add the following to your config.rb file: ``` knife[:editor] = "/usr/bin/vim" ``` When a Microsoft Windows file path is enclosed in a double-quoted string (" “), the same backslash character (`\`) that is used to define the file path separator is also used in Ruby to define an escape character. The config.rb file is a Ruby file; therefore, file path separators must be escaped. In addition, spaces in the file path must be replaced with `~1` so that the length of each section within the file path is not more than 8 characters. For example, if EditPad Pro is the text editor of choice and is located at the following path: ``` C:\\Program Files (x86)\EditPad Pro\EditPad.exe ``` the setting in the config.rb file would be similar to: ``` knife[:editor] = "C:\\Progra~1\\EditPa~1\\EditPad.exe" ``` One approach to working around the double- vs. single-quote issue is to put the single-quotes outside of the double-quotes. For example, for Notepad++: ``` knife[:editor] = '"C:\Program Files (x86)\Notepad++\notepad++.exe" -nosession -multiInst' ``` for Sublime Text: ``` knife[:editor] = '"C:\Program Files\Sublime Text 2\sublime_text.exe" --wait' ``` for TextPad: ``` knife[:editor] = '"C:\Program Files (x86)\TextPad 7\TextPad.exe"' ``` and for vim: ``` knife[:editor] = '"C:\Program Files (x86)\vim\vim74\gvim.exe"' ``` ### Using Quotes The text editor command cannot include spaces that are not properly wrapped in quotes. The command can be entered with double quotes (” “) or single quotes (' ‘), but this should be done consistently as shown in the examples above. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_setup/Knife Common Options ==================== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_options.md) The following options can be run with all knife subcommands and plug-ins: `-c CONFIG_FILE`, `--config CONFIG_FILE` The configuration file to use. For example, when knife is run from a node that is configured to be managed by the Chef Infra Server, this option is used to allow knife to use the same credentials as Chef Infra Client looks when communicating with the Chef Infra Server. `--chef-zero-host HOST` The host to start Chef Infra Zero on. Chef Infra Zero is a lightweight, in-memory Chef Infra Server. `--chef-zero-port PORT` The port (or port range) to start chef-zero on. Port ranges l `1000,1010` or `8889-9999` will try all given ports until one works. `-d`, `--disable-editing` Prevent the $EDITOR from being opened and accept data as-is. `--defaults` Cause knife to use the default value instead of asking a user to provide one. `-e EDITOR`, `--editor EDITOR` The $EDITOR that is used for all interactive commands. `-E ENVIRONMENT`, `--environment ENVIRONMENT` The name of the environment. When this option is added to a command, the command will run only against the named environment. This option is ignored during search queries made using the `knife search` subcommand. `-F FORMAT`, `--format FORMAT` The output format: `summary` (default), `text`, `json`, `yaml`, `pp`. `-h`, `--help` Show help for the command. `-k KEY`, `--key KEY` The USER.pem file that knife uses to sign requests made by the API client to the Chef Infra Server. `--[no-]color` View colored output. `--[no-]fips` Allows OpenSSL to enforce FIPS-validated security during a C Infra Client run. `--print-after` Show data after a destructive operation. `-s URL`, `--server-url URL` The URL for the Chef Infra Server. `-u USER`, `--user USER` The user name used by knife to sign requests made by the API client to the Chef Infra Server. Authentication fails if the user name does not match the private key. `-v`, `--version` The Chef Infra Client version. `-V`, `--verbose` Set for more verbose outputs. Use `-VV` for much more verbose outputs. Use `-VVV` for maximum verbosity, which may provide more information than is actually helpful. `-y`, `--yes` Respond to all confirmation prompts with “Yes”. `-z`, `--local-mode` Run Chef Infra Client looks in local mode. This allows all commands that work against the Chef Infra Server to also work against the local chef-repo. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_options/config.rb ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/config_rb.md) Warning The `config.rb` file is a replacement for the `knife.rb` file. The `config.rb` file has identical settings and behavior to the `knife.rb` file. Chef Infra Client looks first for the presence of the `config.rb` file and if it is not found, then looks for the `knife.rb` file. A `config.rb` file is used to specify configuration details for knife. A `config.rb` file: * Is loaded every time the knife executable is run * Is not created by default * Is located by default at `~/.chef/config.rb` (macOS and Linux platforms) or `c:\Users\username\.chef\config.rb` (Microsoft Windows platform), use the `--config` option from the command line to change this location * Will override the default configuration when a `config.rb` file exists at the default path or the path specified by the `--config` option Note When running Microsoft Windows, the `config.rb` file is located at `%HOMEDRIVE%:%HOMEPATH%\.chef` (e.g. `c:\Users\<username>\.chef`). Settings -------- This configuration file has the following settings: `bootstrap_template` The path to a template file to be used during a bootstrap operation. `chef_server_url` The URL for the Chef Infra Server. For example: ``` chef_server_url 'https://localhost/organizations/ORG_NAME' ``` Note If changes need to be made to any global end points like user or user keys, use [`knife exec`](../workstation/knife_exec/index) with the `--server-url` flag to set `chef_server_url` to `https://localhost/`. `chef_zero.enabled` Enable chef-zero. This setting requires `local_mode` to be set to `true`. Default value: `false`. For example: ``` chef_zero.enabled true ``` `chef_zero[:port]` The port on which chef-zero is to listen. Default value: `8889`. For example: ``` chef_zero[:port] 8889 ``` `client_d_dir` A directory that contains additional configuration scripts to load for Chef Infra Client. `client_key` The location of the file that contains the client key, as an absolute path. Default value: `/etc/chef/client.pem`. For example: ``` client_key '/etc/chef/client.pem' ``` `cookbook_copyright` The name of the copyright holder. This option places a copyright notice that contains the name of the copyright holder in each of the pre-created files. If this option is not specified, a copyright name of “COMPANY_NAME” is used instead; it can easily be modified later. `cookbook_email` The email address for the individual who maintains the cookbook. This option places an email address in each of the pre-created files. If not specified, an email name of “YOUR_EMAIL” is used instead; this can easily be modified later. `cookbook_license` The type of license under which a cookbook is distributed: `apachev2`, `gplv2`, `gplv3`, `mit`, or `none` (default). This option places the appropriate license notice in the pre-created files: `Apache v2.0` (for `apachev2`), `GPL v2` (for `gplv2`), `GPL v3` (for `gplv3`), `MIT` (for `mit`), or `license 'Proprietary - All Rights Reserved` (for `none`). Be aware of the licenses for files inside of a cookbook and be sure to follow any restrictions they describe. `cookbook_path` The Chef Infra Client sub-directory for storing cookbooks. This value can be a string or an array of file system locations, processed in the specified order. The last cookbook is considered to override local modifications. For example: ``` cookbook_path [ '/var/chef/cookbooks', '/var/chef/site-cookbooks' ] ``` `data_bag_encrypt_version` The minimum required version of data bag encryption. Possible values: `1` or `2`. When all of the machines in an organization are running Chef Client 11.6 (or higher), it is recommended that this value be set to `2`. For example: ``` data_bag_encrypt_version 2 ``` `fips` Allows OpenSSL to enforce FIPS-validated security during a Chef Infra Client run. Set to `true` to enable FIPS-validated security. The following operating systems are supported: * Red Hat Enterprise Linux * Oracle Enterprise Linux * CentOS * Windows `local_mode` Run Chef Infra Client in local mode. This allows all commands that work against the Chef Infra Server to also work against the local chef-repo. For example: ``` local_mode true ``` `node_name` The name of the node. This may be a username with permission to authenticate to the Chef Infra Server or it may be the name of the machine from which knife is run. For example: ``` node_name 'user_name' ``` or: ``` node_name 'machine_name' ``` `no_proxy` A comma-separated list of URLs that do not need a proxy. Default value: `nil`. For example: ``` no_proxy 'localhost, 10.0.1.35, *.example.com, *.dev.example.com' ``` `ssh_agent_signing` **New in 14.2** Use `ssh-agent` to authenticate. When using this option, specify the location of the public key in `client_key`. Default value: `false`. Ensure the public key is in PKCS#1 format. You can convert an OpenSSH public key using `ssh-keygen`. For example: ``` ssh-keygen -f key.pub -e -m pem > key.pem ``` `ssh_timeout` The amount of time (in seconds) to wait for an SSH connection time out. `ssl_verify_mode` Set the verify mode for HTTPS requests. * Use `:verify_none` to do no validation of SSL certificates. * Use `:verify_peer` to do validation of all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS **remote_file** resource URLs used in a Chef Infra Client run. This is the recommended setting. Depending on how OpenSSL is configured, the `ssl_ca_path` may need to be specified. Default value: `:verify_peer`. `tmux_split` Split the Tmux window. Default value: `false`. `validation_client_name` The name of the chef-validator key that is used by Chef Infra Client to access the Chef Infra Server during the initial Chef Infra Client run when not using validatorless bootstrapping. For example: ``` validation_client_name 'chef-validator' ``` `validation_key` The location of the file that contains the key used when a Chef Infra Client is registered with a Chef Infra Server. A validation key is signed using the `validation_client_name` for authentication. Default value: `/etc/chef/validation.pem`. For example: ``` validation_key '/etc/chef/validation.pem' ``` `verify_api_cert` Verify the SSL certificate on the Chef Infra Server. When `true`, Chef Infra Client always verifies the SSL certificate. When `false`. Chef Infra Client uses the value of `ssl_verify_mode` to determine if the SSL certificate requires verification. Default value: `false`. `versioned_cookbooks` Append cookbook versions to cookbooks. Set to `false` to hide cookbook versions: `cookbooks/apache`. Set to `true` to show cookbook versions: `cookbooks/apache-1.0.0` and/or `cookbooks/apache-1.0.1`. When this setting is `true`, `knife download` downloads ALL cookbook versions, which can be useful if a full-fidelity backup of data on the Chef Infra Server is required. For example: ``` versioned_cookbooks true ``` `config_log_level` Sets the default value of `log_level` in the client.rb file of the node being bootstrapped. Possible values are `:debug`, `:info`, `:warn`, `:error` and `:fatal`. For example: ``` config_log_level :debug ``` `config_log_location` Sets the default value of `log_location` in the client.rb file of the node being bootstrapped. Possible values are `/path/to/log_location`, `STDOUT`, `STDERR`, `:win_evt` and `:syslog`. For example: ``` config_log_location "/path/to/log_location" # Please make sure that the path exists ``` ### Proxy Settings In certain situations the proxy used by the Chef Infra Server requires authentication. In this situation, three settings must be added to the configuration file. Which settings to add depends on the protocol used to access the Chef Infra Server: HTTP or HTTPS. If the Chef Infra Server is configured to use HTTP, add the following settings: `http_proxy` The proxy server for HTTP connections. Default value: `nil`. For example: ``` http_proxy 'http://proxy.example.com:3128' ``` `http_proxy_user` The user name for the proxy server when the proxy server is using an HTTP connection. Default value: `nil`. `http_proxy_pass` The password for the proxy server when the proxy server is using an HTTP connection. Default value: `nil`. #### HTTPS Proxy Settings (such as the hosted Chef Infra Server) `https_proxy` The proxy server for HTTPS connections. (The hosted Chef Infra Server uses an HTTPS connection.) Default value: `nil`. `https_proxy_user` The user name for the proxy server when the proxy server is using an HTTPS connection. Default value: `nil`. `https_proxy_pass` The password for the proxy server when the proxy server is using an HTTPS connection. Default value: `nil`. #### Settings for No-proxy URLs `no_proxy` A comma-separated list of URLs that do not need a proxy. Default value: `nil`. .d Directories -------------- Chef Infra Client supports reading multiple configuration files by putting them inside a `.d` configuration directory. For example: `/etc/chef/client.d`. All files that end in `.rb` in the `.d` directory are loaded; other non-`.rb` files are ignored. `.d` directories may exist in any location where the `client.rb`, `config.rb`, or `solo.rb` files are present, such as: * `/etc/chef/client.d` * `/etc/chef/config.d` * `~/chef/solo.d` (There is no support for a `knife.d` directory; use `config.d` instead.) For example, when using knife, the following configuration files would be loaded: * `~/.chef/config.rb` * `~/.chef/config.d/company_settings.rb` * `~/.chef/config.d/ec2_configuration.rb` * `~/.chef/config.d/old_settings.rb.bak` The `old_settings.rb.bak` file is ignored because it’s not a configuration file. The `config.rb`, `company_settings.rb`, and `ec2_configuration` files are merged together as if they are a single configuration file. Note If multiple configuration files exists in a `.d` directory, ensure that the same setting has the same value in all files. Optional Settings ----------------- In addition to the default settings in a `config.rb` file, there are other subcommand-specific settings that can be added: 1. A value passed via the command-line 2. A value contained in the `config.rb` file 3. The default value A value passed via the command line overrides a value in the `config.rb` file; a value in a `config.rb` file overrides a default value. Before adding any settings to the `config.rb` file: * Verify the settings by reviewing the documentation for the knife subcommands and/or knife plugins * Verify the use case(s) your organization has for adding them Also note that: * Custom plugins can be configured to use the same settings as the core knife subcommands * Many of these settings are used by more than one subcommand and/or plugin * Some of the settings are included only because knife checks for a value in the `config.rb` file To add settings to the `config.rb` file, use the following syntax: ``` knife[:setting_name] = value ``` where `value` may require quotation marks (' ‘) if that value is a string. For example: ``` knife[:ssh_port] = 22 knife[:bootstrap_template] = 'ubuntu14.04-gems' knife[:bootstrap_version] = '' knife[:bootstrap_proxy] = '' ``` ### Frequently Used Some of the optional `config.rb` settings are used often, such as the template file used in a bootstrap operation. The frequency of use of any option varies from organization to organization, so even though the following settings are often added to a `config.rb` file, they may not be the right settings to add for every organization: `knife[:bootstrap_proxy]` The proxy server for the node that is the target of a bootstrap operation. `knife[:bootstrap_template]` The path to a template file to be used during a bootstrap operation. `knife[:bootstrap_version]` The version of Chef Infra Client to install. `knife[:editor]` The $EDITOR that is used for all interactive commands. `knife[:ssh_gateway]` The SSH tunnel or gateway that is used to run a bootstrap action on a machine that is not accessible from the workstation. Adding this setting can be helpful when a user cannot SSH directly into a host. `knife[:ssh_port]` The SSH port. ### Additional SSH Settings Other SSH-related settings that are sometimes helpful when added to the `config.rb` file: `knife[:forward_agent]` Enable SSH agent forwarding. `knife[:ssh_attribute]` The attribute used when opening an SSH connection. `knife[:ssh_password]` The SSH password. This can be used to pass the password directly on the command line. If this option is not specified (and a password is required) knife prompts for the password. `knife[:ssh_user]` The SSH user name. ### Data Bag Settings Some organizations choose to have all data bags use the same secret and secret file, rather than have a unique secret and secret file for each data bag. To use the same secret and secret file for all data bags, add the following to `config.rb`: `knife[:secret]` The encryption key that is used for values contained within a data bag item. `knife[:secret_file]` The path to the file that contains the encryption key. ### Ohai Settings (Not Recommended) Some settings are better left to Ohai, which gets the value at the start of a Chef Infra Client run: `knife[:server_name]` Same as `node_name`. Recommended configuration is to allow Ohai to collect this value during each Chef Infra Client run. `node_name` Same as `knife[:server_name]`. Recommended configuration is to allow Ohai to collect this value during each Chef Infra Client run. Warning Review the full list of [optional settings](../workstation/config_rb_optional_settings/index) that can be added to the `config.rb` file. Many of these optional settings should not be added to the `config.rb` file. The reasons for not adding them can vary. For example, using `--yes` as a default in the `config.rb` file causes knife to always assume that “Y” is the response to any prompt, which may lead to undesirable outcomes. Other settings, such as `--hide-healthy`(used only with the `knife status` subcommand) or `--bare-directories` (used only with the `knife list` subcommand) probably aren’t used often enough (and in the same exact way) to justify adding them to the `config.rb` file. In general, if the optional settings are not listed on the main config.rb[topic](../workstation/config_rb/index), then add settings only after careful consideration. Do not use optional settings in a production environment until after the setting’s performance has been validated in a safe testing environment. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/config_rb/knife client ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_client.md) Use the `knife client` subcommand to manage an API client list and their associated RSA public key-pairs. This allows authentication requests to be made to the Chef Infra Server by any entity that uses the Chef Infra Server API, such as Chef Infra Client and knife. Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. bulk delete ----------- Use the `bulk delete` argument to delete any API client that matches a pattern defined by a regular expression. The regular expression must be within quotes and not be surrounded by forward slashes (`/`). ### Syntax This argument has the following syntax: ``` knife client bulk delete REGEX ``` ### Options This argument has the following options: `-D`, `--delete-validators` Force the deletion of the client when it is also a chef-validator. ### Examples None. create ------ Use the `create` argument to create a new API client. This process will generate an RSA key pair for the named API client. The public key will be stored on the Chef Infra Server and the private key will be displayed on `STDOUT` or written to a named file. . For Chef Infra Client, the private key should be copied to the system as `/etc/chef/client.pem`. . For knife, the private key is typically copied to `~/.chef/client_name.pem` and referenced in the config.rb configuration file. ### Syntax This argument has the following syntax: ``` knife client create CLIENT_NAME (options) ``` ### Options This argument has the following options: `-f FILE`, `--file FILE` Save a private key to the specified file name. `-k`, `--prevent-keygen` Create a user without a public key. This key may be managed later by using the `knife user key` subcommands. Note This option is valid only with Chef Infra Server API, version 1.0, which was released with Chef Server 12.1. If this option or the `--user-key` option are not passed in the command, the Chef Infra Server will create a user with a public key named `default` and will return the private key. For the Chef Server versions earlier than 12.1, this option will not work; a public key is always generated unless `--user-key` is passed in the command. `-p FILE`, `--public-key FILE` The path to a file that contains the public key. This option may not be passed in the same command with `--prevent-keygen`. When using Chef a default key is generated if this option is not passed in the command. For Chef Server version 12.x, see the `--prevent-keygen` option. `--validator` Create the client as the chef-validator. Default value: `true`. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create an admin client** To create a Chef Infra Client that can access the Chef Infra Server API as an administrator—sometimes referred to as an “API Chef Infra Client”—with the name “exampleorg” and save its private key to a file, enter: ``` knife client create exampleorg -a -f "/etc/chef/client.pem" ``` delete ------ Use the `delete` argument to delete a registered API client. If using Chef Client 12.17 or later, you can delete multiple clients using this subcommand. ### Syntax This argument has the following syntax: ``` knife client delete CLIENT_NAME ``` ### Options This argument has the following options: `-D`, `--delete-validators` Force the deletion of the client when it is also a chef-validator. ### Examples The following examples show how to use this knife subcommand: **Delete a client** To delete a client with the name “client_foo”, enter: ``` knife client delete client_foo ``` Type `Y` to confirm a deletion. edit ---- Use the `edit` argument to edit the details of a registered API client. When this argument is run, knife will open $EDITOR to enable editing of the `admin` attribute. (None of the other attributes should be changed using this argument.) When finished, knife will update the Chef Infra Server with those changes. ### Syntax This argument has the following syntax: ``` knife client edit CLIENT_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Edit a client** To edit a client with the name “exampleorg”, enter: ``` knife client edit exampleorg ``` key create ---------- Use the `key create` argument to create a public key. ### Syntax This argument has the following syntax: ``` knife client key create CLIENT_NAME (options) ``` ### Options This argument has the following options: `-e DATE`, `--expiration-date DATE` The expiration date for the public key, specified as an ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. If this option is not specified, the public key will not have an expiration date. For example: `2013-12-24T21:00:00Z`. `-f FILE`, `--file FILE` Save a private key to the specified file name. If the `--public-key` option is not specified the Chef Infra Server will generate a private key. `-k NAME`, `--key-name NAME` The name of the public key. `-p FILE_NAME`, `--public-key FILE_NAME` The path to a file that contains the public key. If this option is not specified, and only if `--key-name` is specified, the Chef Infra Server will generate a public/private key pair. ### Examples None. key delete ---------- Use the `key delete` argument to delete a public key. ### Syntax This argument has the following syntax: ``` knife client key delete CLIENT_NAME KEY_NAME ``` ### Examples None. key edit -------- Use the `key edit` argument to modify or rename a public key. ### Syntax This argument has the following syntax: ``` knife client key edit CLIENT_NAME KEY_NAME (options) ``` ### Options This argument has the following options: `-c`, `--create-key` Generate a new public/private key pair and replace an existing public key with the newly-generated public key. To replace the public key with an existing public key, use `--public-key` instead. `-e DATE`, `--expiration-date DATE` The expiration date for the public key, specified as an ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. If this option is not specified, the public key will not have an expiration date. For example: `2013-12-24T21:00:00Z`. `-f FILE`, `--file FILE` Save a private key to the specified file name. If the `--public-key` option is not specified the Chef Infra Server will generate a private key. `-k NAME`, `--key-name NAME` The name of the public key. `-p FILE_NAME`, `--public-key FILE_NAME` The path to a file that contains the public key. If this option is not specified, and only if `--key-name` is specified, the Chef Infra Server will generate a public/private key pair. ### Examples None. key list -------- Use the `key list` argument to view a list of public keys for the named client. ### Syntax This argument has the following syntax: ``` knife client key list CLIENT_NAME (options) ``` ### Options This argument has the following options: `-e`, `--only-expired` Show a list of public keys that have expired. `-n`, `--only-non-expired` Show a list of public keys that have not expired. `-w`, `--with-details` Show a list of public keys, including URIs and expiration status. ### Examples None. key show -------- Use the `key show` argument to view details for a specific public key. ### Syntax This argument has the following syntax: ``` knife client key show CLIENT_NAME KEY_NAME ``` ### Examples None. list ---- Use the `list` argument to view a list of registered API client. ### Syntax This argument has the following syntax: ``` knife client list (options) ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### Examples The following examples show how to use this knife subcommand: **View a list of clients** To verify the API client list for the Chef Infra Server, enter: ``` knife client list ``` to return something similar to: ``` exampleorg i-12345678 rs-123456 ``` To verify that an API client can authenticate to the Chef Infra Server correctly, try getting a list of clients using `-u` and `-k` options to specify its name and private key: ``` knife client list -u ORGNAME -k .chef/ORGNAME.pem ``` reregister ---------- Use the `reregister` argument to regenerate an RSA key pair for an API client. The public key will be stored on the Chef Infra Server and the private key will be displayed on `STDOUT` or written to a named file. Note Running this argument will invalidate the previous RSA key pair, making it unusable during authentication to the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife client reregister CLIENT_NAME (options) ``` ### Options This argument has the following options: `-f FILE_NAME`, `--file FILE_NAME` Save a private key to the specified file name. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Re-register a client** To re-register the RSA key pair for a client named “testclient” and save it to a file named “rsa_key”, enter: ``` knife client reregister testclient -f rsa_key ``` show ---- Use the `show` argument to show the details of an API client. ### Syntax This argument has the following syntax: ``` knife client show CLIENT_NAME (options) ``` ### Options This argument has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. ### Examples The following examples show how to use this knife subcommand: **Show clients** To view a client named “testclient”, enter: ``` knife client show testclient ``` to return something like: ``` admin: false chef_type: client json_class: Chef::ApiClient name: testclient public_key: ``` To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife client show devops -F json ``` Other formats available include `text`, `yaml`, and `pp`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_client/knife configure =============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_configure.md) Use the `knife configure` subcommand to create the [client.rb](../config_rb_client/index) and credential files so that they can be distributed to workstations and nodes. Syntax ------ This subcommand has the following syntax when creating a credentials file: ``` knife configure (options) ``` and the following syntax when creating a client.rb file: ``` knife configure client DIRECTORY ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options for use when configuring a config.rb file: `--admin-client-name NAME` The name of the client, typically the name of the admin client. `--admin-client-key PATH` The path to the private key used by the client, typically a file named `admin.pem`. `-i`, `--initial` Create a API client, typically an administrator client on a freshly-installed Chef Infra Server. `-r REPO`, `--repository REPO` The path to the chef-repo. `--validation-client-name NAME` The name of the validation client, typically a client named chef-validator. `--validation-key PATH` The path to the validation key used by the client, typically a file named chef-validator.pem. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Configure credentials file** ``` knife configure ``` **Configure client.rb** ``` knife configure client '/directory' ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_configure/AttributeDefault ================ [All Cookstyle Cops](../cops/index) The department is: `InSpec/Deprecations` The full name of the cop is: `InSpec/Deprecations/AttributeDefault` | Enabled by default | Supports autocorrection | Target Chef Version | | --- | --- | --- | | Enabled | Yes | All Versions | The InSpec inputs `default` option has been replaced with the `value` option. ### Examples #### incorrect ``` login_defs_umask = input('login_defs_umask', default: '077', description: 'Default umask to set in login.defs') ``` #### correct ``` login_defs_umask = input('login_defs_umask', value: '077', description: 'Default umask to set in login.defs') ``` ### Configurable attributes | Name | Default value | Configurable values | | --- | --- | --- | | Version Added | 7.14.0 | String | Include | * `**/controls/*.rb` | Array | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle/inspec_deprecations_attributedefault/knife bootstrap =============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_bootstrap.md) A node is any physical, virtual, or cloud device that is configured and maintained by an instance of Chef Infra Client. Bootstrapping installs Chef Infra Client on a target system so that it can run as a client and sets the node up to communicate with a Chef Infra Server. There are two ways to do this: * Run the `knife bootstrap` command from a workstation. * Perform an unattended install to bootstrap from the node itself, without requiring SSH or WinRM connectivity. Use the `knife bootstrap` subcommand to run a bootstrap operation that installs Chef Infra Client on the target system. The bootstrap operation must specify the IP address or FQDN of the target system. **Considerations:** * Knife will copy the contents of the `~/.chef/client.d` directory on your local workstation to the `client.d` directory on the device being bootstrapped with the `knife bootstrap` command. You can also set the `client_d_dir` option in the `config.rb` file to point to an arbitrary directory instead of `~/.chef/client.d`, and the contents of that directory will be copied to the device being bootstrapped. All config files inside the `client.d` directory will get copied into the `/etc/chef/client.d` directory on the system being bootstrapped. * SSL certificates from an on-premises Chef Infra Server can be copied to the `/trusted_certs_dir` directory on your local workstation automatically by running [knife ssl fetch](../workstation/knife_ssl_fetch/index). These certificates are used during `knife` operations to communicate with the Chef Infra Server. * By default, `knife bootstrap` will attempt to use `ssh` to connect to the target node. Use the `-o` to specify a different protocol, such as `winrm` for windows nodes. Syntax ------ This subcommand has the following syntax: ``` knife bootstrap FQDN_or_IP_ADDRESS (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. ### General Connection Options `-U USERNAME`, `--connection-user USERNAME` Authenticate to the target host with this user account. `-P PASSWORD`, `--connection-password PASSWORD` Authenticate to the target host with this password." `-p PORT`, `--connection-port PORT` The port on the target node to connect to." `-o PROTOCOL`, `--connection-protocol PROTOCOL` The protocol to use to connect to the target node. Options are `ssh` or `winrm`. `ssh` is default. `-W SECONDS`, `--max-wait SECONDS` The maximum time to wait for the initial connection to be established. `--session-timeout SECONDS` The number of seconds to wait for each connection operation to be acknowledged while running bootstrap. ### WinRM Connection Options `--winrm-ssl-peer-fingerprint FINGERPRINT` SSL certificate fingerprint expected from the target. `-f CA_TRUST_PATH`, `--ca-trust-file CA_TRUST_PATH` The Certificate Authority (CA) trust file used for SSL transport `--winrm-no-verify-cert` Do not verify the SSL certificate of the target node for WinRM. `--winrm-ssl` Use SSL in the WinRM connection. `-w AUTH-METHOD`, `--winrm-auth-method AUTH-METHOD` The WinRM authentication method to use. `--winrm-basic-auth-only` For WinRM basic authentication when using the ‘ssl’ auth method. `-R KERBEROS_REALM`, `--kerberos-realm KERBEROS_REALM` The Kerberos realm used for authentication. `-S KERBEROS_SERVICE`, `--kerberos-service KERBEROS_SERVICE` The Kerberos service used for authentication. ### SSH Connection Options `-G GATEWAY`, `--ssh-gateway GATEWAY` The SSH tunnel or gateway that is used to run a bootstrap action on a machine that is not accessible from the workstation. `--ssh-gateway-identity SSH_GATEWAY_IDENTITY` The SSH identity file used for gateway authentication. `-A`, `--ssh-forward-agent` Enable SSH agent forwarding. `-i IDENTITY_FILE`, `--ssh-identity-file IDENTITY_FILE` The SSH identity file used for authentication. Key-based authentication is recommended. `ssh_verify_host_key`, `--ssh-verify-host-key VALUE` Verify host key. Default is ‘always’ ### Chef Installation Options `--bootstrap-version VERSION` The version of Chef Infra Client to install. `--bootstrap-install-command COMMAND` Execute a custom installation command sequence for Chef Infra Client. This option may not be used in the same command with `--bootstrap-curl-options` or `--bootstrap-wget-options`. `--bootstrap-curl-options OPTIONS` Arbitrary options to be added to the bootstrap command when using cURL. This option may not be used in the same command with `--bootstrap-install-command`. `--bootstrap-wget-options OPTIONS` Arbitrary options to be added to the bootstrap command when using GNU Wget. This option may not be used in the same command with `--bootstrap-install-command`. `--bootstrap-preinstall-command COMMANDS` Custom commands to run before installing Chef Infra Client `--bootstrap-url URL` The URL to a custom installation script. `-m URL`, `--msi-url URL` Location of the Chef Infra Client MSI. The default templates will prefer to download from this location. The MSI will be downloaded from chef.io if not provided. `--sudo` Execute a bootstrap operation with sudo. `--sudo-preserve-home` Use to preserve the non-root user’s `HOME` environment. `--use-sudo-password` Perform a bootstrap operation with sudo; specify the password with the `-P` (or `--ssh-password`) option. `-t TEMPLATE`, `--bootstrap-template TEMPLATE` The bootstrap template to use. This may be the name of a bootstrap template—`chef-full` for example—or it may be the full path to an Embedded Ruby (ERB) template that defines a custom bootstrap. Default value: `chef-full`, which installs Chef Infra Client using the Chef Infra installer on all supported platforms. ### Proxy Options `--bootstrap-no-proxy NO_PROXY_URL_or_IP` A URL or IP address that specifies a location that should not be proxied during the bootstrap. `--bootstrap-proxy PROXY_URL` The proxy server for the node that is the target of a bootstrap operation. `--bootstrap-proxy-pass PROXY_PASS` The proxy authentication password for the node being bootstrapped. `--bootstrap-proxy-user PROXY_USER` The proxy authentication username for the node being bootstrapped. ### Node Options `-N NAME`, `--node-name NAME` The unique identifier of the node. Note This option is required for a validatorless bootstrap. `-E ENVIRONMENT`, `--environment ENVIRONMENT` The name of the environment to be applied. `-r RUN_LIST`, `--run-list RUN_LIST` A comma-separated list of roles and/or recipes to be applied. `--secret SECRET` The encryption key that is used for values contained within a data bag item. `--secret-file FILE` The path to the file that contains the encryption key. `--hint HINT_NAME[=HINT_FILE]` An Ohai hint to be set on the bootstrap target. See the [Ohai](../ohai/index#hints) documentation for more information. `HINT_FILE` is the name of the JSON file. `HINT_NAME` is the name of a hint in a JSON file. Use multiple `--hint` options to specify multiple hints. `-j JSON_ATTRIBS`, `--json-attributes JSON_ATTRIBS` A JSON string that is added to the first run of a Chef Infra Client. `--json-attribute-file FILE` A JSON file to be added to the first run of Chef Infra Client. `--[no-]fips` Allows OpenSSL to enforce FIPS-validated security during Chef Infra Client runs. `--policy-group POLICY_GROUP` The name of a policy group that exists on the Chef Infra Server. `--policy-name POLICY_NAME` The name of a policy, as identified by the name setting in a Policyfile.rb file. ### chef-vault Options `--bootstrap-vault-file VAULT_FILE` The path to a JSON file that contains a list of vaults and items to be updated. `--bootstrap-vault-item VAULT_ITEM` A single vault and item to update as `vault:item`. `--bootstrap-vault-json VAULT_JSON` A JSON string that contains a list of vaults and items to be updated. –bootstrap-vault-json ‘{ “vault1”: [“item1”, “item2”], “vault2”: “item2” }’ ### Key Verification Options `--[no-]host-key-verify` Use `--no-host-key-verify` to disable host key verification. Default setting: `--host-key-verify`. `--[no-]node-verify-api-cert` Verify the SSL certificate on the Chef Infra Server. When `true`, Chef Infra Client always verifies the SSL certificate. When `false`, Chef Infra Client uses the value of `ssl_verify_mode` to determine if the SSL certificate requires verification. If this option is not specified, the setting for `verify_api_cert` in the configuration file is applied. `--node-ssl-verify-mode MODE` Set the verify mode for HTTPS requests. Options: `none` or `peer`. Use `none` to do no validation of SSL certificates. Use `peer` to do validation of all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS **remote_file** resource URLs used in a Chef Infra Client run. This is the recommended setting. ### Debug Options `-V -V` Run the initial Chef Infra Client run at the `debug` log-level (e.g. `chef-client -l debug`). `-V -V -V` Run the initial Chef Infra Client run at the `trace` log-level (e.g. `chef-client -l trace`). Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Validatorless Bootstrap The ORGANIZATION-validator.pem is typically added to the .chef directory on the workstation. When a node is bootstrapped from that workstation, the ORGANIZATION-validator.pem is used to authenticate the newly-created node to the Chef Infra Server during the initial Chef Infra Client run. It is possible to bootstrap a node using the USER.pem file instead of the ORGANIZATION-validator.pem file. This is known as a “validatorless bootstrap”. To create a node via the USER.pem file, simply delete the ORGANIZATION-validator.pem file on the workstation. For example: ``` rm -f /home/lamont/.chef/myorg-validator.pem ``` and then make the following changes in the config.rb file: * Remove the `validation_client_name` setting * Edit the `validation_key` setting to be something that isn’t a path to an existent ORGANIZATION-validator.pem file. For example: `/nonexist`. As long as a USER.pem is also present on the workstation from which the validatorless bootstrap operation will be initiated, the bootstrap operation will run and will use the USER.pem file instead of the ORGANIZATION-validator.pem file. When running a validatorless `knife bootstrap` operation, the output is similar to: ``` desktop% knife bootstrap 10.1.1.1 -N foo01.acme.org \ -E dev -r 'role[base]' -j '{ "foo": "bar" }' \ --ssh-user vagrant --sudo Node foo01.acme.org exists, overwrite it? (Y/N) Client foo01.acme.org exists, overwrite it? (Y/N) Creating new client for foo01.acme.org Creating new node for foo01.acme.org Connecting to 10.1.1.1 10.1.1.1 Starting first Chef Client run... [....etc...] ``` Note The `--node-name` option is required for a validatorless bootstrap. ### FIPS Mode Federal Information Processing Standards (FIPS) is a United States government computer security standard that specifies security requirements for cryptography. The current version of the standard is FIPS 140-2. Chef Infra Client can be configured to allow OpenSSL to enforce FIPS-validated security during a Chef Infra Client run. This will disable cryptography that is explicitly disallowed in FIPS-validated software, including certain ciphers and hashing algorithms. Any attempt to use any disallowed cryptography will cause Chef Infra Client to throw an exception during a Chef Infra Client run. Note Chef uses MD5 hashes to uniquely identify files that are stored on the Chef Infra Server. MD5 is used only to generate a unique hash identifier and is not used for any cryptographic purpose. Notes about FIPS: * May be enabled for nodes running on Microsoft Windows and Enterprise Linux platforms * Should only be enabled for environments that require FIPS 140-2 compliance **Bootstrap a node using FIPS** ``` knife bootstrap 192.0.2.0 -P vanilla -x root -r 'recipe[apt],recipe[xfs],recipe[vim]' --fips ``` which shows something similar to: ``` OpenSSL FIPS 140 mode enabled ... 192.0.2.0 Chef Infra Client finished, 12/12 resources updated in 78.942455583 seconds ``` Custom Templates ---------------- The default `chef-full` template uses the Chef installer. For most bootstrap operations, regardless of the platform on which the target node is running, using the `chef-full` distribution is the best approach for installing Chef Infra Client on a target node. In some situations, a custom template may be required. For example, the default bootstrap operation relies on an Internet connection to get the distribution to the target node. If a target node cannot access the Internet, then a custom template can be used to define a specific location for the distribution so that the target node may access it during the bootstrap operation. The example below will show you how to create a bootstrap template that uses a custom artifact store for Chef packages and installation scripts, as well as a RubyGem mirror: 1. A custom bootstrap template file must be located in a `bootstrap/` directory, which is typically located within the `~/.chef/` directory on the local workstation. Navigate to the `.chef` directory, and create a `bootstrap` directory within it: ``` mkdir bootstrap ``` 2. Move to the `bootstrap` directory and create a blank template file; this example will use `template.erb` for the template name: ``` touch template.erb ``` 3. Still in the `bootstrap` directory, issue the following command to copy the `chef-full` configuration to your new template: ``` find /opt/chef-workstation/embedded/lib/ruby -type f -name chef-full.erb -exec cat {} \; > template.erb ``` This command searches for the `chef-full` template file under `/opt/chef-workstation/embedded/lib/ruby`, and then outputs the contents of the file to `template.erb`. If you used a different template file name, be sure to replace `template.erb` with the template file you created during the last step. 4. Update `template.erb` to replace `omnitruck.chef.io` with the URL of an `install.sh` script on your artifact store: ``` install_sh="<%= knife_config[:bootstrap_url] ? knife_config[:bootstrap_url] : "http://packages.example.com/install.sh" %>" ``` 5. Still in your text editor, locate the following line near the bottom of your `template.erb` file: ``` cat > /etc/chef/client.rb <<'EOP' <%= config_content %> EOP ``` Beneath it, add the following, replacing `gems.example.com` with the URL of your gem mirror: ``` cat >> /etc/chef/client.rb <<'EOP' rubygems_url "http://gems.example.com" EOP ``` This appends the appropriate `rubygems_url` setting to the `/etc/chef/client.rb` file that is created during bootstrap, which ensures that your nodes use your internal gem mirror. ### Bootstrap a Custom Template You can use the `--bootstrap-template` option with the `knife bootstrap` subcommand to specify the name of your bootstrap template file: ``` knife bootstrap 123.456.7.8 -x username -P password --sudo --bootstrap-template "template" ``` Alternatively, you can use the `knife[:bootstrap_template]` option within `config.rb` to specify the template that `knife bootstrap` will use by default when bootstrapping a node. It should point to your custom template within the `bootstrap` directory: ``` knife[:bootstrap_template] = "#{current_dir}/bootstrap/template.erb" ``` Examples -------- The following examples show how to use this knife subcommand: **Bootstrap a node** ``` knife bootstrap 192.0.2.0 -P vanilla -x root -r 'recipe[apt],recipe[xfs],recipe[vim]' ``` which shows something similar to: ``` ... 192.0.2.0 Chef Infra Client finished, 12/12 resources updated in 78.942455583 seconds ``` Use `knife node show` to verify: ``` knife node show debian-buster.int.domain.org ``` which returns something similar to: ``` Node Name: debian-buster.int.domain.org Environment: _default FQDN: debian-buster.int.domain.org IP: 192.0.2.0 Run List: recipe[apt], recipe[xfs], recipe[vim] Roles: Recipes: apt, xfs, vim, apt::default, xfs::default, vim::default Platform: debian 10.0 Tags: ``` **Use an SSH password** ``` knife bootstrap 192.0.2.0 -x username -P PASSWORD --sudo ``` **Use a file that contains a private key** ``` knife bootstrap 192.0.2.0 -x username -i ~/.ssh/id_rsa --sudo ``` **Specify options when using cURL** ``` knife bootstrap --bootstrap-curl-options "--proxy http://myproxy.com:8080" ``` **Specify options when using GNU Wget** ``` knife bootstrap --bootstrap-wget-options "-e use_proxy=yes -e http://myproxy.com:8080" ``` **Specify a custom installation command sequence** ``` knife bootstrap --bootstrap-install-command "curl -l http://mycustomserver.com/custom_install_chef_script.sh | sudo bash -s --" ``` **Bootstrap a Windows node via WinRM using a run list and environment** ``` knife bootstrap -o winrm 123.456.7.8 -U username -P 'PASSWORD' --node-name NODE_NAME --run-list 'recipe[cookbook]' -E ENV_NAME ``` **Bootstrap a Windows node via WinRM using a policyfile and policy group** ``` knife bootstrap -o winrm 123.456.7.8 -U username -P 'PASSWORD' --node-name NODE_NAME --policy-name PF_NAME --policy-group PG_NAME ``` **Bootstrap Windows node with shorthand syntax** ``` knife bootstrap winrm://username:PASSWORD@123.456.7.8 --run-list 'recipe[cookbook]' -E ENV_NAME ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_bootstrap/knife cookbook ============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_cookbook.md) A cookbook is the fundamental unit of configuration and policy distribution in Chef Infra. A cookbook defines a scenario and contains everything that is required to support that scenario: * Recipes that specify which Chef Infra built-in resources to use, as well as the order in which they are to be applied * Attribute values, which allow environment-based configurations such as `dev` or `prodution`. * Custom Resources for extending Chef Infra beyond the built-in resources. * Files and Templates for distributing information to systems. * Custom Ohai Plugins for extending system configuration collection beyond the Ohai defaults. * The `metadata.rb` file, which describes the cookbook itself and any dependencies it may have. Use the `knife cookbook` subcommand to interact with cookbooks that are located on the Chef Infra Server or the local chef-repo. Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. bulk delete ----------- Use the `bulk delete` argument to delete cookbook files that match a pattern defined by a regular expression. The regular expression must be within quotes and not be surrounded by forward slashes (/). ### Syntax This argument has the following syntax: ``` knife cookbook bulk delete REGEX (options) ``` ### Options This argument has the following options: `-p`, `--purge` Entirely remove a cookbook (or cookbook version) from the Chef Infra Server. Use this action carefully because only one copy of any single file is stored on the Chef Infra Server. Consequently, purging a cookbook disables any other cookbook that references one or more files from the cookbook that has been purged. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Bulk delete many cookbooks** Use a regular expression to define the pattern used to bulk delete cookbooks: ``` knife cookbook bulk delete "^[0-9]{3}$" -p ``` delete ------ Use the `delete` argument to delete a specified cookbook or cookbook version on the Chef Infra Server (and not locally). ### Syntax This argument has the following syntax: ``` knife cookbook delete COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `-a`, `--all` Delete all cookbooks (and cookbook versions). `COOKBOOK_VERSION` The version of a cookbook to be deleted. If a cookbook has only one version, this option does not need to be specified. If a cookbook has more than one version and this option is not specified, knife prompts for a version. `-p`, `--purge` Entirely remove a cookbook (or cookbook version) from the Chef Infra Server. Use this action carefully because only one copy of any single file is stored on the Chef Infra Server. Consequently, purging a cookbook disables any other cookbook that references one or more files from the cookbook that has been purged. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Delete a cookbook** ``` knife cookbook delete cookbook_name version ``` For example: ``` knife cookbook delete smartmon 0.8 ``` Type `Y` to confirm a deletion. download -------- Use the `download` argument to download a cookbook from the Chef Infra Server to the current working directory. ### Syntax This argument has the following syntax: ``` knife cookbook download COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `-d DOWNLOAD_DIRECTORY`, `--dir DOWNLOAD_DIRECTORY` The directory in which cookbooks are located. `-f`, `--force` Overwrite an existing directory. `-N`, `--latest` Download the most recent version of a cookbook. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Download a cookbook** To download a cookbook named `smartmon`, enter: ``` knife cookbook download smartmon ``` list ---- Use the `list` argument to view a list of cookbooks that are currently available on the Chef Infra Server. The list will contain only the most recent version for each cookbook by default. ### Syntax This argument has the following syntax: ``` knife cookbook list (options) ``` ### Options This argument has the following options: `-a`, `--all` Return all available versions for every cookbook. `-w`, `--with-uri` Show the corresponding URIs. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **View a list of cookbooks** To view a list of cookbooks: ``` knife cookbook list ``` metadata -------- Use the `metadata` argument to generate the metadata for one or more cookbooks. ### Syntax This argument has the following syntax: ``` knife cookbook metadata (options) ``` ### Options This argument has the following options: `-a`, `--all` Generate metadata for all cookbooks. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Generate metadata** ``` knife cookbook metadata -a ``` metadata from file ------------------ Use the `metadata from file` argument to load the metadata for a cookbook from a file. ### Syntax This argument has the following syntax: ``` knife cookbook metadata from file FILE ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **View metadata** ``` knife cookbook metadata from file /path/to/file ``` show ---- Use the `show` argument to view information about a cookbook, parts of a cookbook (attributes, definitions, files, libraries, providers, recipes, resources, and templates), or a file that is associated with a cookbook (including attributes such as checksum or specificity). ### Syntax This argument has the following syntax: ``` knife cookbook show COOKBOOK_NAME [COOKBOOK_VERSION] [PART...] [FILE_NAME] (options) ``` ### Options This argument has the following options: `COOKBOOK_VERSION` The version of a cookbook to be shown. If a cookbook has only one version, this option does not need to be specified. If a cookbook has more than one version and this option is not specified, a list of cookbook versions is returned. `-f FQDN`, `--fqdn FQDN` The FQDN of the host. `FILE_NAME` The name of a file that is associated with a cookbook. `-p PLATFORM`, `--platform PLATFORM` The platform for which a cookbook is designed. `PART` The part of the cookbook to show: `attributes`, `definitions`, `files`, `libraries`, `providers`, `recipes`, `resources`, or `templates`. More than one part can be specified. `-V PLATFORM_VERSION`, `--platform-version PLATFORM_VERSION` The version of the platform. `-w`, `--with-uri` Show the corresponding URIs. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Show cookbook data** To get the list of available versions of a cookbook named `getting-started`, enter: ``` knife cookbook show getting-started ``` to return something like: ``` getting-started 0.3.0 0.2.0 ``` **Show cookbook versions** To show a list of data about a cookbook using the name of the cookbook and the version, enter: ``` knife cookbook show getting-started 0.3.0 ``` to return something like: ``` attributes: checksum: fa0fc4abf3f6787aeb5c3c5c35de667c name: default.rb path: attributes/default.rb specificity: default url: https://somelongurlhere.com chef_type: cookbook_version cookbook_name: getting-started definitions: [] files: [] frozen?: false json_class: Chef::CookbookVersion libraries: [] ``` **Show a cookbook version** To only view data about templates, enter: ``` knife cookbook show getting-started 0.3.0 templates ``` to return something like: ``` checksum: a29d6f254577b830091f140c3a78b1fe name: chef-getting-started.txt.erb path: templates/default/chef-getting-started.txt.erb specificity: default url: https://someurlhere.com ``` **Show cookbook data as JSON** To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife cookbook show devops -F json ``` Other formats available include `text`, `yaml`, and `pp`. test ---- Use the `test` argument to test a cookbook for syntax errors. This argument uses Ruby syntax checking to verify every file in a cookbook that ends in .rb and Embedded Ruby (ERB). This argument will respect chefignore files when determining which cookbooks to test for syntax errors. Warning This feature is deprecated in favor of [Cookstyle](../workstation/cookstyle/index) and [ChefSpec](../workstation/chefspec/index) ### Syntax This argument has the following syntax: ``` knife cookbook test COOKBOOK_NAME (options) ``` ### Options This argument has the following options: `-a`, `--all` Test all cookbooks. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Test a cookbook** ``` knife cookbook test cookbook_name ``` upload ------ Use the `upload` argument to upload one or more cookbooks (and any files that are associated with those cookbooks) from a local repository to the Chef Infra Server. Only files that do not already exist on the Chef Infra Server will be uploaded. Note Use a chefignore file to prevent the upload of specific files and file types, such as temporary files or files placed in folders by version control systems. The chefignore file must be located in the root of the cookbook repository and must use rules similar to filename globbing (as defined by the Ruby `File.fnmatch` syntax). Note Empty directories are not uploaded to the Chef Infra Server. To upload an empty directory, create a “dot” file—e.g. `.keep`—in that directory to ensure that the directory itself is not empty. ### Syntax This argument has the following syntax: ``` knife cookbook upload [COOKBOOK_NAME...] (options) ``` ### Options This argument has the following options: `-a`, `--all` Upload all cookbooks. `--concurrency` The number of allowed concurrent connections. Default: `10`. `-d`, `--include-dependencies` Ensure that when a cookbook has a dependency on one (or more) cookbooks, those cookbooks are also uploaded. `-E ENVIRONMENT`, `--environment ENVIRONMENT` Use to set the environment version dependency to the cookbook version being uploaded. `--force` Update a cookbook even if the `--freeze` flag has been set. `--freeze` Require changes to a cookbook be included as a new version. Only the `--force` option can override this setting. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Upload a cookbook** ``` knife cookbook upload cookbook_name ``` **Freeze a cookbook** To upload a cookbook, and then prevent other users from being able to make changes to it, enter: ``` knife cookbook upload redis --freeze ``` to return something like: ``` Uploading redis... Upload completed ``` If a cookbook is frozen and the `--force` option is not specified, knife will return an error message similar to the following: ``` Uploading redis... ERROR: Version 0.1.6 of cookbook redis is frozen. Use --force to override. ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_cookbook/Site Map ======== This is a site map for the following products: * [Chef Automate](#chef-automate) * [Chef Desktop](#chef-desktop) * [Chef Habitat](#chef-habitat) * [Chef Infra](#chef-infra) * [Chef Infra Server](#chef-infra-server) * [Chef InSpec](#chef-inspec) * [Chef Workstation](#chef-workstation) * [Supermarket](#supermarket) This page has links to each topic in this doc set. You can also use the navigation tool or the search box to find what you're looking for. If you need documentation for previous versions, see the [Docs Archive](https://docs-archive.chef.io). Overview --------- [Platform Overview](../platform_overview/index) ### Community [About the Community](../community/index) | [Community Contributions](../community_contributions/index) | [Guidelines](../community_guidelines/index) | [Send Feedback](https://docs.chef.io/feedback/) ### Packages & Platforms [Packages](../packages/index) | [Platforms](../platforms/index) | [Supported Versions](../versions/index) | [Chef Software Install Script](../chef_install_script/index) | [Omnitruck API](../api_omnitruck/index) **Licensing** : [About Licensing](../chef_license/index) | [Accepting License](../chef_license_accept/index) ### Style Guide [Docs Style](../style_index/index) | [Chef House Style](../style_house/index) | [Tools](../style_tools/index) | [Hugo](../style_hugo/index) | [Markdown](../style_markdown/index) | [Content Reuse and Shortcodes Guide](../style_reuse/index) Chef Automate -------------- ### Getting Started [Quick Start Demo](../automate/index) | [System Requirements](../automate/system_requirements/index) ### Install [Install Guide](../automate/install/index) | [Install Airgapped](../automate/airgapped_installation/index) | [Install Habitat Builder On-prem](../automate/on_prem_builder/index) | [Install Chef Infra Server](../automate/infra_server/index) ### Configure [Overview](../automate/configuration/index) | [Data Collection](../automate/data_collection/index) | [Disclosure Panel and Banner](../automate/disclosure_panel_and_banner/index) | [Session Timeout](../automate/session_timeout/index) | [Telemetry](../automate/telemetry/index) ### Manage [Backup](../automate/backup/index) | [LDAP](../automate/ldap/index) | [Log Management](../automate/log_management/index) | [Migrate](../automate/migrate/index) | [Monitoring](../automate/monitoring/index) | [SAML](../automate/saml/index) | [Restore](../automate/restore/index) **Elasticsearch** : [Configure Elasticsearch](../automate/elasticsearch/index) **PostgreSQL** : [Configure Postgresql](../automate/postgresql/index) | [Upgrade External PostgreSQL](../automate/postgres_external_upgrade/index) ### Applications [Chef EAS](../automate/eas/index) | [Setting up the Applications Dashboard](../automate/applications_setup/index) | [Applications Dashboard](../automate/applications_dashboard/index) | [Desktop Dashboard](../automate/desktop/index) ### Authorization [IAM Overview](../automate/iam_v2_overview/index) | [IAM Users Guide](../automate/iam_v2_guide/index) | [IAM Actions](../automate/iam_actions/index) ### Compliance [Reports](../automate/reports/index) | [Scan Jobs](../automate/scan_jobs/index) | [Profiles](../automate/profiles/index) | [Nodes](../automate/nodes/index) | [Event Feed](../automate/event_feed/index) ### Infrastructure [Client Runs](../automate/client_runs/index) | [Chef Infra Server](../automate/chef_infra_server/index) ### Integrations **ServiceNow** : [Integration App](../automate/servicenow_integration/index) | [Incident App](../automate/servicenow_incident_creation/index) | [Administrator Reference](../automate/servicenow_reference/index) ### Settings [Notifications](../automate/notifications/index) | [Data Feeds](../automate/datafeed/index) | [Data Lifecycle](../automate/data_lifecycle/index) | [Node Integrations](../automate/node_integrations/index) | [Node Credentials](../automate/node_credentials/index) | [Users](../automate/users/index) | [Teams](../automate/teams/index) | [API Tokens](../automate/api_tokens/index) | [Policies](../automate/policies/index) | [Roles](../automate/roles/index) | [Projects](../automate/projects/index) | [User Profile](../automate/chef_automate_profile/index) | [Troubleshooting](../automate/troubleshooting/index) ### Reference [Architecture](../automate/architectural_overview/index) | [Chef Automate API](https://docs.chef.io/automate/api/) | [chef-automate CLI](../automate/cli_chef_automate/index) | [Feature Flags](../automate/flags/index) | [Upgrade](../automate/upgrade/index) Chef Desktop ------------- [About Chef Desktop](../desktop/index) ### Getting Started [Requirements](../desktop/requirements/index) | [Infrastructure Overview](../desktop/infrastructure_overview/index) ### Install [Quick Start guide](../desktop/demonstration_setup/index) | [Install Workstation](../desktop/install/index) | [Automate Server](../desktop/automate_server/index) | [Cookbook Setup](../desktop/cookbook_repository/index) | [Set up Policy](../desktop/policies/index) | [Set up Nodes](../desktop/nodes/index) | [Configure](index) ### Zero Touch Deployment **macOS** : [Enrollment](../desktop/zero_touch/macos/index) | [Application Management](../desktop/zero_touch/macos/application_management/index) **Windows** : [Enrollment](../desktop/zero_touch/windows/index) | [Application Management](../desktop/zero_touch/windows/application_management/index) | [Chef Desktop Cookbook Reference](../desktop/desktop-cookbook/index) ### Resources [All Resources (Single Page)](../desktop/resources/index) | [macos_admin_control](../desktop/resources/macos_admin_control/index) | [macos_app_management](../desktop/resources/macos_app_management/index) | [macos_automatic_logout](../desktop/resources/macos_automatic_logout/index) | [macos_automatic_software_updates](../desktop/resources/macos_automatic_software_updates/index) | [macos_desktop_screensaver](../desktop/resources/macos_desktop_screensaver/index) | [macos_disk_encryption](../desktop/resources/macos_disk_encryption/index) | [macos_firewall](../desktop/resources/macos_firewall/index) | [macos_password_policy](../desktop/resources/macos_password_policy/index) | [macos_power_management](../desktop/resources/macos_power_management/index) | [rescue_account](../desktop/resources/rescue_account/index) | [windows_admin_control](../desktop/resources/windows_admin_control/index) | [windows_app_management](../desktop/resources/windows_app_management/index) | [windows_automatic_logout](../desktop/resources/windows_automatic_logout/index) | [windows_choco_installer](../desktop/resources/windows_choco_installer/index) | [windows_defender](../desktop/resources/windows_defender/index) | [windows_defender_exclusion](../desktop/resources/windows_defender_exclusion/index) | [windows_desktop_screensaver](../desktop/resources/windows_desktop_screensaver/index) | [windows_desktop_winrm_settings](../desktop/resources/windows_desktop_winrm_settings/index) | [windows_disk_encryption](../desktop/resources/windows_disk_encryption/index) | [windows_firewall](../desktop/resources/windows_firewall/index) | [windows_ie_esc](../desktop/resources/windows_ie_esc/index) | [windows_password_policy](../desktop/resources/windows_password_policy/index) | [windows_power_management](../desktop/resources/windows_power_management/index) | [windows_update_settings](../desktop/resources/windows_update_settings/index) Chef Habitat ------------- [About Chef Habitat](../habitat/index) ### Install Habitat [Get Chef Habitat](../habitat/install_habitat/index) | [Set up the Chef Habitat CLI](../habitat/hab_setup/index) | [Download and Install FAQ](../habitat/install_faq/index) ### Builder [Chef Habitat Builder](../habitat/builder_overview/index) | [Create an Account](../habitat/builder_account/index) | [Builder Profile](../habitat/builder_profile/index) | [Origins](../habitat/builder_origins/index) | [Origin Packages](../habitat/builder_origin_packages/index) ### Origins [Create an Origin](../habitat/origins/index) | [Origin Keys](../habitat/origin_keys/index) | [Origin Membership & RBAC](../habitat/origin_rbac/index) | [Origin Settings](../habitat/origin_settings/index) ### Packages [Building Packages](../habitat/pkg_build/index) | [Promoting Packages](../habitat/pkg_promote/index) | [Exporting Packages](../habitat/pkg_exports/index) | [Continuous Integration](../habitat/continuous_integration/index) | [Runtime Binds](../habitat/pkg_binds/index) ### Plans [Plan Writing](../habitat/plan_writing/index) | [Plan Quickstart](../habitat/plan_quickstart/index) | [Plan Contents](../habitat/plan_contents/index) | [Scaffolding](../habitat/scaffolding/index) | [Binary Wrapper Packages](../habitat/binary_wrapper/index) ### Services [About Services](../habitat/about_services/index) | [Service Groups](../habitat/service_groups/index) | [Service Group Topologies](../habitat/service_group_topologies/index) | [Service Group Configuration](../habitat/service_group_configuration/index) | [Single Service Updates](../habitat/service_updates/index) | [Service Group Updates](../habitat/service_group_updates/index) | [Monitoring Services](../habitat/monitor_services/index) ### Supervisors [About Supervisors](../habitat/sup/index) | [Running Supervisors](../habitat/sup_run/index) | [Running Chef Habitat on Servers (Linux and Windows)](../habitat/running_habitat_servers/index) | [Supervisor Design](../habitat/sup_design/index) | [Leader Elections](../habitat/sup_elections/index) | [Setting Up a Ring](../habitat/sup_rings/index) | [Supervisor Networks](../habitat/sup_networks/index) | [Supervisor Cryptography](../habitat/sup_crypto/index) | [Securing Networks](../habitat/sup_secure/index) | [Supervisor Configuration File](../habitat/sup_config/index) | [Supervisor Log Configuration](../habitat/sup_log_configuration/index) | [Supervisor Package Configuration](../habitat/sup_pkg_config/index) | [Launcher](../habitat/sup_launcher/index) | [Remote Control](../habitat/sup_remote_control/index) ### Reference [Habitat CLI Reference](../habitat/habitat_cli/index) **API** : [Builder API](https://docs.chef.io/habitat/builder_api/) | [Supervisor API](https://docs.chef.io/habitat/supervisor_api/) | [Application Lifecycle Hooks](../habitat/application_lifecycle_hooks/index) | [Build Helpers](../habitat/build_helpers/index) | [Build Phase Callbacks](../habitat/build_phase_callbacks/index) | [Plan Configuration Helpers](../habitat/plan_helpers/index) | [Configuration Management](../habitat/configuration_management/index) | [Configuration Templates](../habitat/config_templates/index) | [Custom Certificates](../habitat/certs_custom/index) | [Environment Variables](../habitat/environment_variables/index) | [Keys](../habitat/keys/index) | [Package Contents](../habitat/package_contents/index) | [Package Identifiers](../habitat/pkg_ids/index) | [Pattern Library](../habitat/pattern_library/index) | [Plan Settings](../habitat/plan_settings/index) | [Plan Variables](../habitat/plan_variables/index) | [Service Template Data](../habitat/service_templates/index) | [Supervisor Log Codes](../habitat/sup_log_keys/index) ### Containers [Chef Habitat and Containers](../habitat/containers/index) | [Container Orchestration](../habitat/container_orchestration/index) | [Kubernetes](../habitat/kubernetes/index) | [Azure Container Services (AKS)](../habitat/aks/index) | [Amazon Container Services (ECS)](../habitat/ecs/index) | [Google Container Registry (GCR)](../habitat/gcr/index) | [Apache Mesos and DC/OS](../habitat/mesos_dcos/index) | [Running Chef Habitat Linux Containers](../habitat/running_habitat_linux_containers/index) | [Running Chef Habitat Windows Containers](../habitat/running_habitat_windows_containers/index) ### Diagrams [Architecture Overview](../habitat/architecture_overview/index) | [Initial Package Build Flow](../habitat/package_build_flow/index) | [Dependency Update Flow](../habitat/dependency_update_flow/index) | [Application Rebuild Flow](../habitat/application_rebuild_flow/index) | [Docker Container Publishing Flow](../habitat/docker_flow/index) | [Automated Docker Container Publishing Flow](../habitat/docker_automated_flow/index) | [Promote Packages Through Channels](../habitat/promote_packages/index) | [Runtime Services Group Binding](../habitat/runtime_binding/index) | [Chef Habitat Builder Architecture](../habitat/builder_architecture/index) | [Chef Habitat Builder on-prem Flow](../habitat/on_prem_flow/index) Chef Infra ----------- ### Overview [Chef Infra Overview](../chef_overview/index) | [Chef Infra Client Overview](../chef_client_overview/index) | [Nodes](../nodes/index) | [Quick Start](../quick_start/index) ### Install [System Requirements](../chef_system_requirements/index) | [Install via Bootstrap](../install_bootstrap/index) | [Working with Proxies](../proxies/index) | [client.rb](../config_rb_client/index) | [Air-gapped Installation](../install_chef_air_gap/index) | [Upgrade](../upgrade_client/index) | [Uninstall](../uninstall/index) ### Features **Chef Solo** : [About Chef Solo](../chef_solo/index) | [chef-solo (executable)](../ctl_chef_solo/index) | [solo.rb](../config_rb_solo/index) | [Compliance Phase](../chef_compliance_phase/index) **Ohai** : [About Ohai](../ohai/index) | [ohai (executable)](../ctl_ohai/index) | [Handlers](../handlers/index) | [Search](../chef_search/index) ### Policy [About Policy](../policy/index) | [About Policyfiles](../policyfile/index) | [Policyfile.rb](../config_rb_policyfile/index) | [Data Bags](../data_bags/index) | [Run-lists](../run_lists/index) | [Environments](../environments/index) | [Roles](../roles/index) ### Integrations [AWS Marketplace](../aws_marketplace/index) | [Google Cloud Platform](../google/index) | [VMware](../vmware/index) | [Chef and Terraform](../terraform/index) **Microsoft Azure** : [Azure Marketplace](../azure_marketplace/index) | [Azure Test Drive](../azure_testdrive/index) | [Chef Workstation in Azure Cloud Shell](../azure_cwa_cloud_shell/index) | [Microsoft Azure PowerShell](../azure_powershell/index) | [Microsoft Azure Chef Extension](../azure_chef_cli/index) **Microsoft Windows** : [Chef for Microsoft Windows](../windows/index) | [Windows Installation Guide](../install_windows/index) ### Security [Chef Infra Client Security](../chef_client_security/index) | [FIPS](../fips/index) ### Reference [chef-client (executable)](../ctl_chef_client/index) | [chef-solo (executable)](../ctl_chef_solo/index) | [Handler DSL](../dsl_handler/index) | [ohai (executable)](../ctl_ohai/index) | [supermarket-ctl](../ctl_supermarket/index) | [client.rb](../config_rb_client/index) | [metadata.rb](../config_rb_metadata/index) | [Policyfile.rb](../config_rb_policyfile/index) | [Deprecations](../chef_deprecations_client/index) | [solo.rb](../config_rb_solo/index) | [Glossary](../glossary/index) | [Troubleshooting](../errors/index) ### Cookbook Reference [About Cookbooks](../cookbooks/index) | [About chef-repo](../chef_repo/index) | [Cookbook Directory](../cookbook_repo/index) **Attributes** : [Attributes](../attributes/index) | [Attributes Arrays](../attribute_arrays/index) | [Attribute Persistence](../attribute_persistence/index) | [Attribute Precedence](../attribute_precedence/index) | [Attribute Sources](../attribute_sources/index) | [Attribute Types](../attribute_types/index) | [Files](../files/index) | [Libraries](../libraries/index) | [metadata.rb](../config_rb_metadata/index) **Recipes** : [About Recipes](../recipes/index) | [Debug Recipes, Client Runs](../debug/index) | [Templates](../templates/index) | [Versioning Cookbooks](../cookbook_versioning/index) ### Chef Infra Language [Language Overview](../infra_language/index) | [Checking Architectures](../infra_language/checking_architectures/index) | [Checking Clouds](../infra_language/checking_clouds/index) | [Checking Hypervisors](../infra_language/checking_hypervisors/index) | [Checking Platforms](../infra_language/checking_platforms/index) | [Cookbook Execution](../infra_language/cookbook_execution/index) | [Editing Resources](../infra_language/editing_resources/index) | [Logging](../infra_language/logging/index) | [Node Tags](../infra_language/node_tags/index) | [Reading Data Bags](../infra_language/reading_data_bags/index) | [Reading Registry Keys](../infra_language/registry_keys/index) | [Search](../infra_language/search/index) | [Secrets Management Integrations](../infra_language/secrets/index) | [Shelling Out](../infra_language/shelling_out/index) | [Windows](../infra_language/windows/index) | [Ruby Guide](../ruby/index) ### Chef Infra Resources [About Resources](../resource/index) | [About Unified Mode](../unified_mode/index) | [Common Resource Functionality](../resource_common/index) | [All Resources (Single Page)](../resources/index) **Custom Resources** : [Custom Resource Guide](../custom_resources/index) | [Accumulators](../accumulators/index) | [Helpers](../helpers/index) | [Partials](../partials/index) | [Migrating from Definitions](../definitions_to_custom_resources/index) | [Migration Notes](../custom_resources_notes/index) | [Migrating from LWRPs](../lwrp_to_custom_resources/index) | [Glossary](../custom_resource_glossary/index) | [alternatives](../resources/alternatives/index) | [apt_package](../resources/apt_package/index) | [apt_preference](../resources/apt_preference/index) | [apt_repository](../resources/apt_repository/index) | [apt_update](../resources/apt_update/index) | [archive_file](../resources/archive_file/index) | [bash](../resources/bash/index) | [batch](../resources/batch/index) | [bff_package](../resources/bff_package/index) | [breakpoint](../resources/breakpoint/index) | [build_essential](../resources/build_essential/index) | [cab_package](../resources/cab_package/index) | [chef_acl](../resources/chef_acl/index) | [chef_client](../resources/chef_client/index) | [chef_client_config](../resources/chef_client_config/index) | [chef_client_cron](../resources/chef_client_cron/index) | [chef_client_launchd](../resources/chef_client_launchd/index) | [chef_client_scheduled_task](../resources/chef_client_scheduled_task/index) | [chef_client_systemd_timer](../resources/chef_client_systemd_timer/index) | [chef_client_trusted_certificate](../resources/chef_client_trusted_certificate/index) | [chef_container](../resources/chef_container/index) | [chef_data_bag](../resources/chef_data_bag/index) | [chef_data_bag_item](../resources/chef_data_bag_item/index) | [chef_environment](../resources/chef_environment/index) | [chef_gem](../resources/chef_gem/index) | [chef_group](../resources/chef_group/index) | [chef_handler](../resources/chef_handler/index) | [chef_node](../resources/chef_node/index) | [chef_organization](../resources/chef_organization/index) | [chef_role](../resources/chef_role/index) | [chef_sleep](../resources/chef_sleep/index) | [chef_user](../resources/chef_user/index) | [chef_vault_secret](../resources/chef_vault_secret/index) | [chocolatey_config](../resources/chocolatey_config/index) | [chocolatey_feature](../resources/chocolatey_feature/index) | [chocolatey_package](../resources/chocolatey_package/index) | [chocolatey_source](../resources/chocolatey_source/index) | [cookbook_file](../resources/cookbook_file/index) | [cron](../resources/cron/index) | [cron_access](../resources/cron_access/index) | [cron_d](../resources/cron_d/index) | [csh](../resources/csh/index) | [directory](../resources/directory/index) | [dmg_package](../resources/dmg_package/index) | [dnf_package](../resources/dnf_package/index) | [dpkg_package](../resources/dpkg_package/index) | [dsc_resource](../resources/dsc_resource/index) | [dsc_script](../resources/dsc_script/index) | [execute](../resources/execute/index) | [file](../resources/file/index) | [freebsd_package](../resources/freebsd_package/index) | [gem_package](../resources/gem_package/index) | [git](../resources/git/index) | [group](../resources/group/index) | [habitat_config](../resources/habitat_config/index) | [habitat_install](../resources/habitat_install/index) | [habitat_package](../resources/habitat_package/index) | [habitat_service](../resources/habitat_service/index) | [habitat_sup](../resources/habitat_sup/index) | [habitat_user_toml](../resources/habitat_user_toml/index) | [homebrew_cask](../resources/homebrew_cask/index) | [homebrew_package](../resources/homebrew_package/index) | [homebrew_tap](../resources/homebrew_tap/index) | [homebrew_update](../resources/homebrew_update/index) | [hostname](../resources/hostname/index) | [http_request](../resources/http_request/index) | [ifconfig](../resources/ifconfig/index) | [inspec_input](../resources/inspec_input/index) | [inspec_waiver](../resources/inspec_waiver/index) | [inspec_waiver_file_entry](../resources/inspec_waiver_file_entry/index) | [ips_package](../resources/ips_package/index) | [kernel_module](../resources/kernel_module/index) | [ksh](../resources/ksh/index) | [launchd](../resources/launchd/index) | [link](../resources/link/index) | [locale](../resources/locale/index) | [log](../resources/log/index) | [macos_userdefaults](../resources/macos_userdefaults/index) | [macports_package](../resources/macports_package/index) | [mdadm](../resources/mdadm/index) | [mount](../resources/mount/index) | [msu_package](../resources/msu_package/index) | [notify_group](../resources/notify_group/index) | [ohai](../resources/ohai/index) | [ohai_hint](../resources/ohai_hint/index) | [openbsd_package](../resources/openbsd_package/index) | [openssl_dhparam](../resources/openssl_dhparam/index) | [openssl_ec_private_key](../resources/openssl_ec_private_key/index) | [openssl_ec_public_key](../resources/openssl_ec_public_key/index) | [openssl_rsa_private_key](../resources/openssl_rsa_private_key/index) | [openssl_rsa_public_key](../resources/openssl_rsa_public_key/index) | [openssl_x509_certificate](../resources/openssl_x509_certificate/index) | [openssl_x509_crl](../resources/openssl_x509_crl/index) | [openssl_x509_request](../resources/openssl_x509_request/index) | [osx_profile](../resources/osx_profile/index) | [package](../resources/package/index) | [pacman_package](../resources/pacman_package/index) | [paludis_package](../resources/paludis_package/index) | [perl](../resources/perl/index) | [plist](../resources/plist/index) | [portage_package](../resources/portage_package/index) | [powershell_package](../resources/powershell_package/index) | [powershell_package_source](../resources/powershell_package_source/index) | [powershell_script](../resources/powershell_script/index) | [python](../resources/python/index) | [reboot](../resources/reboot/index) | [registry_key](../resources/registry_key/index) | [remote_directory](../resources/remote_directory/index) | [remote_file](../resources/remote_file/index) | [rhsm_errata](../resources/rhsm_errata/index) | [rhsm_errata_level](../resources/rhsm_errata_level/index) | [rhsm_register](../resources/rhsm_register/index) | [rhsm_repo](../resources/rhsm_repo/index) | [rhsm_subscription](../resources/rhsm_subscription/index) | [route](../resources/route/index) | [rpm_package](../resources/rpm_package/index) | [ruby](../resources/ruby/index) | [ruby_block](../resources/ruby_block/index) | [script](../resources/script/index) | [service](../resources/service/index) | [smartos_package](../resources/smartos_package/index) | [snap_package](../resources/snap_package/index) | [solaris_package](../resources/solaris_package/index) | [ssh_known_hosts_entry](../resources/ssh_known_hosts_entry/index) | [subversion](../resources/subversion/index) | [sudo](../resources/sudo/index) | [swap_file](../resources/swap_file/index) | [sysctl](../resources/sysctl/index) | [systemd_unit](../resources/systemd_unit/index) | [template](../resources/template/index) | [timezone](../resources/timezone/index) | [user](../resources/user/index) | [user_ulimit](../resources/user_ulimit/index) | [windows_ad_join](../resources/windows_ad_join/index) | [windows_audit_policy](../resources/windows_audit_policy/index) | [windows_auto_run](../resources/windows_auto_run/index) | [windows_certificate](../resources/windows_certificate/index) | [windows_defender](../resources/windows_defender/index) | [windows_defender_exclusion](../resources/windows_defender_exclusion/index) | [windows_dfs_folder](../resources/windows_dfs_folder/index) | [windows_dfs_namespace](../resources/windows_dfs_namespace/index) | [windows_dfs_server](../resources/windows_dfs_server/index) | [windows_dns_record](../resources/windows_dns_record/index) | [windows_dns_zone](../resources/windows_dns_zone/index) | [windows_env](../resources/windows_env/index) | [windows_feature](../resources/windows_feature/index) | [windows_feature_dism](../resources/windows_feature_dism/index) | [windows_feature_powershell](../resources/windows_feature_powershell/index) | [windows_firewall_profile](../resources/windows_firewall_profile/index) | [windows_firewall_rule](../resources/windows_firewall_rule/index) | [windows_font](../resources/windows_font/index) | [windows_package](../resources/windows_package/index) | [windows_pagefile](../resources/windows_pagefile/index) | [windows_path](../resources/windows_path/index) | [windows_printer](../resources/windows_printer/index) | [windows_printer_port](../resources/windows_printer_port/index) | [windows_security_policy](../resources/windows_security_policy/index) | [windows_service](../resources/windows_service/index) | [windows_share](../resources/windows_share/index) | [windows_shortcut](../resources/windows_shortcut/index) | [windows_task](../resources/windows_task/index) | [windows_uac](../resources/windows_uac/index) | [windows_update_settings](../resources/windows_update_settings/index) | [windows_user_privilege](../resources/windows_user_privilege/index) | [windows_workgroup](../resources/windows_workgroup/index) | [yum_package](../resources/yum_package/index) | [yum_repository](../resources/yum_repository/index) | [zypper_package](../resources/zypper_package/index) | [zypper_repository](../resources/zypper_repository/index) ### Extension APIs **Handlers** : [Custom Handlers](../handlers/index#custom-handlers) | [Handler DSL](../dsl_handler/index) | [Community Handlers](../plugin_community/index#handlers) | [Compliance DSL](../inspec/dsl_inspec/index) **Ohai Plugins** : [Custom Plugins](../ohai_custom/index) | [Community Plugins](../plugin_community/index#ohai) Chef Infra Server ------------------ ### Overview [Infra Server Overview](../server/index) | [Server Users](../server/server_users/index) | [Authentication](../server/auth/index) | [Services](../server/server_services/index) | [Organizations & Groups](../server/server_orgs/index) ### Plan [Chef Infra Server Prerequisites](../server/install_server_pre/index) | [Capacity Planning](../server/capacity_planning/index) ### Install [Install Chef Infra Server](../server/install_server/index) | [Install High Availability](../server/install_server_ha/index) | [Airgap](../install_chef_air_gap/index#chef-infra-server) | [Tiered Installation](../server/install_server_tiered/index) | [Upgrades](../server/upgrades/index) | [Upgrade HA Cluster](../server/upgrade_server_ha_v2/index) ### Configure [chef-server.rb Settings](../server/config_rb_server/index) | [Chef Infra Server Optional Settings](../server/config_rb_server_optional_settings/index) | [chef-backend.rb Settings](../server/config_rb_backend/index) | [Server Firewalls and Ports](../server/server_firewalls_and_ports/index) | [Security](../server/server_security/index) ### Manage [Backup and Restore](../server/server_backup_restore/index) | [Backend Failure Recovery](../server/backend_failure_recovery/index) | [Monitor](../server/server_monitor/index) | [Tuning](../server/server_tuning/index) | [Log Files](../server/server_logs/index) ### Reference [chef-server-ctl](../server/ctl_chef_server/index) | [chef-backend-ctl](../server/ctl_chef_backend/index) | [Chef Infra Server API](../server/api_chef_server/index) | [Firewalls & Ports](../server/server_firewalls_and_ports/index) Chef InSpec ------------ [Chef InSpec Overview](../inspec/index) | [Install and Uninstall](../inspec/install/index) | [Chef InSpec for the Cloud](../inspec/platforms/index) | [Chef InSpec and Friends](../inspec/inspec_and_friends/index) | [Chef InSpec Glossary](../inspec/glossary/index) | [Troubleshooting](../inspec/troubleshooting/index) ### Chef InSpec Reference [InSpec Executable](../inspec/cli/index) | [Profiles](../inspec/profiles/index) | [Inputs](../inspec/inputs/index) | [Matchers](../inspec/matchers/index) | [Reporters](../inspec/reporters/index) | [Configuration](../inspec/config/index) | [Chef InSpec Language](../inspec/dsl_inspec/index) | [Profile Style Guide](../inspec/style/index) | [Custom Resources](../inspec/dsl_resource/index) | [Plugins](../inspec/plugins/index) | [kitchen-inspec](../inspec/plugin_kitchen_inspec/index) | [InSpec Shell](../inspec/shell/index) | [Chef Habitat Integration](../inspec/habitat/index) | [Migration from Serverspec](../inspec/migration/index) | [Waivers](../inspec/waivers/index) ### Chef InSpec Resources [InSpec Resources (Single Page)](../inspec/resources/index) **OS Resources** : [aide_conf](../inspec/resources/aide_conf/index) | [apache](../inspec/resources/apache/index) | [apache_conf](../inspec/resources/apache_conf/index) | [apt](../inspec/resources/apt/index) | [audit_policy](../inspec/resources/audit_policy/index) | [auditd](../inspec/resources/auditd/index) | [auditd_conf](../inspec/resources/auditd_conf/index) | [bash](../inspec/resources/bash/index) | [bond](../inspec/resources/bond/index) | [bridge](../inspec/resources/bridge/index) | [bsd_service](../inspec/resources/bsd_service/index) | [cassandradb_conf](../inspec/resources/cassandradb_conf/index) | [cassandradb_session](../inspec/resources/cassandradb_session/index) | [chocolatey_package](../inspec/resources/chocolatey_package/index) | [chrony_conf](../inspec/resources/chrony_conf/index) | [command](../inspec/resources/command/index) | [cpan](../inspec/resources/cpan/index) | [cran](../inspec/resources/cran/index) | [crontab](../inspec/resources/crontab/index) | [csv](../inspec/resources/csv/index) | [dh_params](../inspec/resources/dh_params/index) | [directory](../inspec/resources/directory/index) | [docker](../inspec/resources/docker/index) | [docker_container](../inspec/resources/docker_container/index) | [docker_image](../inspec/resources/docker_image/index) | [docker_plugin](../inspec/resources/docker_plugin/index) | [docker_service](../inspec/resources/docker_service/index) | [elasticsearch](../inspec/resources/elasticsearch/index) | [etc_fstab](../inspec/resources/etc_fstab/index) | [etc_group](../inspec/resources/etc_group/index) | [etc_hosts](../inspec/resources/etc_hosts/index) | [etc_hosts_allow](../inspec/resources/etc_hosts_allow/index) | [etc_hosts_deny](../inspec/resources/etc_hosts_deny/index) | [file](../inspec/resources/file/index) | [filesystem](../inspec/resources/filesystem/index) | [firewalld](../inspec/resources/firewalld/index) | [gem](../inspec/resources/gem/index) | [group](../inspec/resources/group/index) | [groups](../inspec/resources/groups/index) | [grub_conf](../inspec/resources/grub_conf/index) | [host](../inspec/resources/host/index) | [http](../inspec/resources/http/index) | [ibmdb2_conf](../inspec/resources/ibmdb2_conf/index) | [ibmdb2_session](../inspec/resources/ibmdb2_session/index) | [iis_app](../inspec/resources/iis_app/index) | [iis_site](../inspec/resources/iis_site/index) | [inetd_conf](../inspec/resources/inetd_conf/index) | [ini](../inspec/resources/ini/index) | [interface](../inspec/resources/interface/index) | [interfaces](../inspec/resources/interfaces/index) | [ip6tables](../inspec/resources/ip6tables/index) | [iptables](../inspec/resources/iptables/index) | [json](../inspec/resources/json/index) | [kernel_module](../inspec/resources/kernel_module/index) | [kernel_parameter](../inspec/resources/kernel_parameter/index) | [key_rsa](../inspec/resources/key_rsa/index) | [launchd_service](../inspec/resources/launchd_service/index) | [limits_conf](../inspec/resources/limits_conf/index) | [login_defs](../inspec/resources/login_defs/index) | [mongodb_conf](../inspec/resources/mongodb_conf/index) | [mongodb_session](../inspec/resources/mongodb_session/index) | [mount](../inspec/resources/mount/index) | [mssql_session](../inspec/resources/mssql_session/index) | [mssql_sys_conf](../inspec/resources/mssql_sys_conf/index) | [mysql_conf](../inspec/resources/mysql_conf/index) | [mysql_session](../inspec/resources/mysql_session/index) | [nginx](../inspec/resources/nginx/index) | [nginx_conf](../inspec/resources/nginx_conf/index) | [npm](../inspec/resources/npm/index) | [ntp_conf](../inspec/resources/ntp_conf/index) | [oneget](../inspec/resources/oneget/index) | [opa_api](../inspec/resources/opa_api/index) | [opa_cli](../inspec/resources/opa_cli/index) | [oracledb_conf](../inspec/resources/oracledb_conf/index) | [oracledb_listener_conf](../inspec/resources/oracledb_listener_conf/index) | [oracledb_session](../inspec/resources/oracledb_session/index) | [os](../inspec/resources/os/index) | [os_env](../inspec/resources/os_env/index) | [package](../inspec/resources/package/index) | [packages](../inspec/resources/packages/index) | [parse_config](../inspec/resources/parse_config/index) | [parse_config_file](../inspec/resources/parse_config_file/index) | [passwd](../inspec/resources/passwd/index) | [pip](../inspec/resources/pip/index) | [port](../inspec/resources/port/index) | [postfix_conf](../inspec/resources/postfix_conf/index) | [postgres_conf](../inspec/resources/postgres_conf/index) | [postgres_hba_conf](../inspec/resources/postgres_hba_conf/index) | [postgres_ident_conf](../inspec/resources/postgres_ident_conf/index) | [postgres_session](../inspec/resources/postgres_session/index) | [powershell](../inspec/resources/powershell/index) | [processes](../inspec/resources/processes/index) | [rabbitmq_config](../inspec/resources/rabbitmq_config/index) | [registry_key](../inspec/resources/registry_key/index) | [runit_service](../inspec/resources/runit_service/index) | [security_identifier](../inspec/resources/security_identifier/index) | [security_policy](../inspec/resources/security_policy/index) | [selinux](../inspec/resources/selinux/index) | [service](../inspec/resources/service/index) | [shadow](../inspec/resources/shadow/index) | [ssh_config](../inspec/resources/ssh_config/index) | [sshd_config](../inspec/resources/sshd_config/index) | [ssl](../inspec/resources/ssl/index) | [sybase_conf](../inspec/resources/sybase_conf/index) | [sybase_session](../inspec/resources/sybase_session/index) | [sys_info](../inspec/resources/sys_info/index) | [systemd_service](../inspec/resources/systemd_service/index) | [sysv_service](../inspec/resources/sysv_service/index) | [toml](../inspec/resources/toml/index) | [upstart_service](../inspec/resources/upstart_service/index) | [user](../inspec/resources/user/index) | [users](../inspec/resources/users/index) | [vbscript](../inspec/resources/vbscript/index) | [virtualization](../inspec/resources/virtualization/index) | [windows_feature](../inspec/resources/windows_feature/index) | [windows_firewall](../inspec/resources/windows_firewall/index) | [windows_firewall_rule](../inspec/resources/windows_firewall_rule/index) | [windows_hotfix](../inspec/resources/windows_hotfix/index) | [windows_task](../inspec/resources/windows_task/index) | [wmi](../inspec/resources/wmi/index) | [x509_certificate](../inspec/resources/x509_certificate/index) | [xinetd_conf](../inspec/resources/xinetd_conf/index) | [xml](../inspec/resources/xml/index) | [yaml](../inspec/resources/yaml/index) | [yum](../inspec/resources/yum/index) | [zfs_dataset](../inspec/resources/zfs_dataset/index) | [zfs_pool](../inspec/resources/zfs_pool/index) **AWS Resources** : [aws_alb](../inspec/resources/aws_alb/index) | [aws_albs](../inspec/resources/aws_albs/index) | [aws_auto_scaling_group](../inspec/resources/aws_auto_scaling_group/index) | [aws_auto_scaling_groups](../inspec/resources/aws_auto_scaling_groups/index) | [aws_cloudformation_stack](../inspec/resources/aws_cloudformation_stack/index) | [aws_cloudtrail_trail](../inspec/resources/aws_cloudtrail_trail/index) | [aws_cloudtrail_trails](../inspec/resources/aws_cloudtrail_trails/index) | [aws_cloudwatch_alarm](../inspec/resources/aws_cloudwatch_alarm/index) | [aws_cloudwatch_log_group](../inspec/resources/aws_cloudwatch_log_group/index) | [aws_cloudwatch_log_metric_filter](../inspec/resources/aws_cloudwatch_log_metric_filter/index) | [aws_config_delivery_channel](../inspec/resources/aws_config_delivery_channel/index) | [aws_config_recorder](../inspec/resources/aws_config_recorder/index) | [aws_db_subnet_group](../inspec/resources/aws_db_subnet_group/index) | [aws_db_subnet_groups](../inspec/resources/aws_db_subnet_groups/index) | [aws_dhcp_options](../inspec/resources/aws_dhcp_options/index) | [aws_dynamodb_table](../inspec/resources/aws_dynamodb_table/index) | [aws_ebs_volume](../inspec/resources/aws_ebs_volume/index) | [aws_ebs_volumes](../inspec/resources/aws_ebs_volumes/index) | [aws_ec2_instance](../inspec/resources/aws_ec2_instance/index) | [aws_ec2_instances](../inspec/resources/aws_ec2_instances/index) | [aws_ecr](../inspec/resources/aws_ecr/index) | [aws_ecr_image](../inspec/resources/aws_ecr_image/index) | [aws_ecr_images](../inspec/resources/aws_ecr_images/index) | [aws_ecr_repositories](../inspec/resources/aws_ecr_repositories/index) | [aws_ecr_repository](../inspec/resources/aws_ecr_repository/index) | [aws_ecs_cluster](../inspec/resources/aws_ecs_cluster/index) | [aws_ecs_clusters](../inspec/resources/aws_ecs_clusters/index) | [aws_efs_file_system](../inspec/resources/aws_efs_file_system/index) | [aws_efs_file_systems](../inspec/resources/aws_efs_file_systems/index) | [aws_eks_cluster](../inspec/resources/aws_eks_cluster/index) | [aws_eks_clusters](../inspec/resources/aws_eks_clusters/index) | [aws_elasticache_cluster](../inspec/resources/aws_elasticache_cluster/index) | [aws_elasticache_cluster_node](../inspec/resources/aws_elasticache_cluster_node/index) | [aws_elasticache_clusters](../inspec/resources/aws_elasticache_clusters/index) | [aws_elb](../inspec/resources/aws_elb/index) | [aws_elbs](../inspec/resources/aws_elbs/index) | [aws_flow_log](../inspec/resources/aws_flow_log/index) | [aws_hosted_zone](../inspec/resources/aws_hosted_zone/index) | [aws_hosted_zones](../inspec/resources/aws_hosted_zones/index) | [aws_iam_access_key](../inspec/resources/aws_iam_access_key/index) | [aws_iam_access_keys](../inspec/resources/aws_iam_access_keys/index) | [aws_iam_account_alias](../inspec/resources/aws_iam_account_alias/index) | [aws_iam_group](../inspec/resources/aws_iam_group/index) | [aws_iam_groups](../inspec/resources/aws_iam_groups/index) | [aws_iam_inline_policy](../inspec/resources/aws_iam_inline_policy/index) | [aws_iam_password_policy](../inspec/resources/aws_iam_password_policy/index) | [aws_iam_policies](../inspec/resources/aws_iam_policies/index) | [aws_iam_policy](../inspec/resources/aws_iam_policy/index) | [aws_iam_role](../inspec/resources/aws_iam_role/index) | [aws_iam_roles](../inspec/resources/aws_iam_roles/index) | [aws_iam_root_user](../inspec/resources/aws_iam_root_user/index) | [aws_iam_saml_provider](../inspec/resources/aws_iam_saml_provider/index) | [aws_iam_saml_providers](../inspec/resources/aws_iam_saml_providers/index) | [aws_iam_user](../inspec/resources/aws_iam_user/index) | [aws_iam_users](../inspec/resources/aws_iam_users/index) | [aws_internet_gateway](../inspec/resources/aws_internet_gateway/index) | [aws_internet_gateways](../inspec/resources/aws_internet_gateways/index) | [aws_kms_key](../inspec/resources/aws_kms_key/index) | [aws_kms_keys](../inspec/resources/aws_kms_keys/index) | [aws_lambda](../inspec/resources/aws_lambda/index) | [aws_lambdas](../inspec/resources/aws_lambdas/index) | [aws_launch_configuration](../inspec/resources/aws_launch_configuration/index) | [aws_nat_gateway](../inspec/resources/aws_nat_gateway/index) | [aws_nat_gateways](../inspec/resources/aws_nat_gateways/index) | [aws_organizations_member](../inspec/resources/aws_organizations_member/index) | [aws_rds_cluster](../inspec/resources/aws_rds_cluster/index) | [aws_rds_clusters](../inspec/resources/aws_rds_clusters/index) | [aws_rds_instance](../inspec/resources/aws_rds_instance/index) | [aws_rds_instances](../inspec/resources/aws_rds_instances/index) | [aws_region](../inspec/resources/aws_region/index) | [aws_regions](../inspec/resources/aws_regions/index) | [aws_route_table](../inspec/resources/aws_route_table/index) | [aws_route_tables](../inspec/resources/aws_route_tables/index) | [aws_s3_bucket](../inspec/resources/aws_s3_bucket/index) | [aws_s3_bucket_object](../inspec/resources/aws_s3_bucket_object/index) | [aws_s3_buckets](../inspec/resources/aws_s3_buckets/index) | [aws_security_group](../inspec/resources/aws_security_group/index) | [aws_security_groups](../inspec/resources/aws_security_groups/index) | [aws_sns_subscription](../inspec/resources/aws_sns_subscription/index) | [aws_sns_topic](../inspec/resources/aws_sns_topic/index) | [aws_sns_topics](../inspec/resources/aws_sns_topics/index) | [aws_sqs_queue](../inspec/resources/aws_sqs_queue/index) | [aws_sqs_queues](../inspec/resources/aws_sqs_queues/index) | [aws_ssm_parameter](../inspec/resources/aws_ssm_parameter/index) | [aws_ssm_parameters](../inspec/resources/aws_ssm_parameters/index) | [aws_sts_caller_identity](../inspec/resources/aws_sts_caller_identity/index) | [aws_subnet](../inspec/resources/aws_subnet/index) | [aws_subnets](../inspec/resources/aws_subnets/index) | [aws_transit_gateway](../inspec/resources/aws_transit_gateway/index) | [aws_vpc](../inspec/resources/aws_vpc/index) | [aws_vpcs](../inspec/resources/aws_vpcs/index) **Azure Resources** : [azure_generic_resource](../inspec/resources/azure_generic_resource/index) | [azure_resource_group](../inspec/resources/azure_resource_group/index) | [azure_virtual_machine](../inspec/resources/azure_virtual_machine/index) | [azure_virtual_machine_data_disk](../inspec/resources/azure_virtual_machine_data_disk/index) | [azurerm_ad_user](../inspec/resources/azurerm_ad_user/index) | [azurerm_ad_users](../inspec/resources/azurerm_ad_users/index) | [azurerm_aks_cluster](../inspec/resources/azurerm_aks_cluster/index) | [azurerm_aks_clusters](../inspec/resources/azurerm_aks_clusters/index) | [azurerm_cosmosdb_database_account](../inspec/resources/azurerm_cosmosdb_database_account/index) | [azurerm_event_hub_authorization_rule](../inspec/resources/azurerm_event_hub_authorization_rule/index) | [azurerm_event_hub_event_hub](../inspec/resources/azurerm_event_hub_event_hub/index) | [azurerm_event_hub_namespace](../inspec/resources/azurerm_event_hub_namespace/index) | [azurerm_iothub](../inspec/resources/azurerm_iothub/index) | [azurerm_iothub_event_hub_consumer_group](../inspec/resources/azurerm_iothub_event_hub_consumer_group/index) | [azurerm_iothub_event_hub_consumer_groups](../inspec/resources/azurerm_iothub_event_hub_consumer_groups/index) | [azurerm_key_vault](../inspec/resources/azurerm_key_vault/index) | [azurerm_key_vault_key](../inspec/resources/azurerm_key_vault_key/index) | [azurerm_key_vault_keys](../inspec/resources/azurerm_key_vault_keys/index) | [azurerm_key_vault_secret](../inspec/resources/azurerm_key_vault_secret/index) | [azurerm_key_vault_secrets](../inspec/resources/azurerm_key_vault_secrets/index) | [azurerm_key_vaults](../inspec/resources/azurerm_key_vaults/index) | [azurerm_load_balancer](../inspec/resources/azurerm_load_balancer/index) | [azurerm_load_balancers](../inspec/resources/azurerm_load_balancers/index) | [azurerm_locks](../inspec/resources/azurerm_locks/index) | [azurerm_management_group](../inspec/resources/azurerm_management_group/index) | [azurerm_management_groups](../inspec/resources/azurerm_management_groups/index) | [azurerm_monitor_activity_log_alert](../inspec/resources/azurerm_monitor_activity_log_alert/index) | [azurerm_monitor_activity_log_alerts](../inspec/resources/azurerm_monitor_activity_log_alerts/index) | [azurerm_monitor_log_profile](../inspec/resources/azurerm_monitor_log_profile/index) | [azurerm_monitor_log_profiles](../inspec/resources/azurerm_monitor_log_profiles/index) | [azurerm_mysql_database](../inspec/resources/azurerm_mysql_database/index) | [azurerm_mysql_databases](../inspec/resources/azurerm_mysql_databases/index) | [azurerm_mysql_server](../inspec/resources/azurerm_mysql_server/index) | [azurerm_mysql_servers](../inspec/resources/azurerm_mysql_servers/index) | [azurerm_network_interface](../inspec/resources/azurerm_network_interface/index) | [azurerm_network_interfaces](../inspec/resources/azurerm_network_interfaces/index) | [azurerm_network_security_group](../inspec/resources/azurerm_network_security_group/index) | [azurerm_network_security_groups](../inspec/resources/azurerm_network_security_groups/index) | [azurerm_network_watcher](../inspec/resources/azurerm_network_watcher/index) | [azurerm_network_watchers](../inspec/resources/azurerm_network_watchers/index) | [azurerm_postgresql_database](../inspec/resources/azurerm_postgresql_database/index) | [azurerm_postgresql_databases](../inspec/resources/azurerm_postgresql_databases/index) | [azurerm_postgresql_server](../inspec/resources/azurerm_postgresql_server/index) | [azurerm_postgresql_servers](../inspec/resources/azurerm_postgresql_servers/index) | [azurerm_resource_groups](../inspec/resources/azurerm_resource_groups/index) | [azurerm_role_definition](../inspec/resources/azurerm_role_definition/index) | [azurerm_role_definitions](../inspec/resources/azurerm_role_definitions/index) | [azurerm_security_center_policies](../inspec/resources/azurerm_security_center_policies/index) | [azurerm_security_center_policy](../inspec/resources/azurerm_security_center_policy/index) | [azurerm_sql_database](../inspec/resources/azurerm_sql_database/index) | [azurerm_sql_databases](../inspec/resources/azurerm_sql_databases/index) | [azurerm_sql_server](../inspec/resources/azurerm_sql_server/index) | [azurerm_sql_servers](../inspec/resources/azurerm_sql_servers/index) | [azurerm_storage_account_blob_container](../inspec/resources/azurerm_storage_account_blob_container/index) | [azurerm_storage_account_blob_containers](../inspec/resources/azurerm_storage_account_blob_containers/index) | [azurerm_subnet](../inspec/resources/azurerm_subnet/index) | [azurerm_subnets](../inspec/resources/azurerm_subnets/index) | [azurerm_subscription](../inspec/resources/azurerm_subscription/index) | [azurerm_virtual_machine](../inspec/resources/azurerm_virtual_machine/index) | [azurerm_virtual_machine_disk](../inspec/resources/azurerm_virtual_machine_disk/index) | [azurerm_virtual_machine_disks](../inspec/resources/azurerm_virtual_machine_disks/index) | [azurerm_virtual_machines](../inspec/resources/azurerm_virtual_machines/index) | [azurerm_virtual_network](../inspec/resources/azurerm_virtual_network/index) | [azurerm_virtual_networks](../inspec/resources/azurerm_virtual_networks/index) | [azurerm_webapp](../inspec/resources/azurerm_webapp/index) | [azurerm_webapps](../inspec/resources/azurerm_webapps/index) **GCP Resources** : [google_access_context_manager_access_policies](../inspec/resources/google_access_context_manager_access_policies/index) | [google_access_context_manager_access_policy](../inspec/resources/google_access_context_manager_access_policy/index) | [google_access_context_manager_service_perimeter](../inspec/resources/google_access_context_manager_service_perimeter/index) | [google_access_context_manager_service_perimeters](../inspec/resources/google_access_context_manager_service_perimeters/index) | [google_appengine_standard_app_version](../inspec/resources/google_appengine_standard_app_version/index) | [google_appengine_standard_app_versions](../inspec/resources/google_appengine_standard_app_versions/index) | [google_bigquery_dataset](../inspec/resources/google_bigquery_dataset/index) | [google_bigquery_datasets](../inspec/resources/google_bigquery_datasets/index) | [google_bigquery_table](../inspec/resources/google_bigquery_table/index) | [google_bigquery_tables](../inspec/resources/google_bigquery_tables/index) | [google_billing_project_billing_info](../inspec/resources/google_billing_project_billing_info/index) | [google_cloud_scheduler_job](../inspec/resources/google_cloud_scheduler_job/index) | [google_cloud_scheduler_jobs](../inspec/resources/google_cloud_scheduler_jobs/index) | [google_cloudbuild_trigger](../inspec/resources/google_cloudbuild_trigger/index) | [google_cloudbuild_triggers](../inspec/resources/google_cloudbuild_triggers/index) | [google_cloudfunctions_cloud_function](../inspec/resources/google_cloudfunctions_cloud_function/index) | [google_cloudfunctions_cloud_functions](../inspec/resources/google_cloudfunctions_cloud_functions/index) | [google_compute_address](../inspec/resources/google_compute_address/index) | [google_compute_addresses](../inspec/resources/google_compute_addresses/index) | [google_compute_autoscaler](../inspec/resources/google_compute_autoscaler/index) | [google_compute_autoscalers](../inspec/resources/google_compute_autoscalers/index) | [google_compute_backend_bucket](../inspec/resources/google_compute_backend_bucket/index) | [google_compute_backend_buckets](../inspec/resources/google_compute_backend_buckets/index) | [google_compute_backend_service](../inspec/resources/google_compute_backend_service/index) | [google_compute_backend_services](../inspec/resources/google_compute_backend_services/index) | [google_compute_disk](../inspec/resources/google_compute_disk/index) | [google_compute_disks](../inspec/resources/google_compute_disks/index) | [google_compute_firewall](../inspec/resources/google_compute_firewall/index) | [google_compute_firewalls](../inspec/resources/google_compute_firewalls/index) | [google_compute_forwarding_rule](../inspec/resources/google_compute_forwarding_rule/index) | [google_compute_forwarding_rules](../inspec/resources/google_compute_forwarding_rules/index) | [google_compute_global_address](../inspec/resources/google_compute_global_address/index) | [google_compute_global_addresses](../inspec/resources/google_compute_global_addresses/index) | [google_compute_global_forwarding_rule](../inspec/resources/google_compute_global_forwarding_rule/index) | [google_compute_global_forwarding_rules](../inspec/resources/google_compute_global_forwarding_rules/index) | [google_compute_health_check](../inspec/resources/google_compute_health_check/index) | [google_compute_health_checks](../inspec/resources/google_compute_health_checks/index) | [google_compute_http_health_check](../inspec/resources/google_compute_http_health_check/index) | [google_compute_http_health_checks](../inspec/resources/google_compute_http_health_checks/index) | [google_compute_https_health_check](../inspec/resources/google_compute_https_health_check/index) | [google_compute_https_health_checks](../inspec/resources/google_compute_https_health_checks/index) | [google_compute_image](../inspec/resources/google_compute_image/index) | [google_compute_instance](../inspec/resources/google_compute_instance/index) | [google_compute_instance_group](../inspec/resources/google_compute_instance_group/index) | [google_compute_instance_group_manager](../inspec/resources/google_compute_instance_group_manager/index) | [google_compute_instance_group_managers](../inspec/resources/google_compute_instance_group_managers/index) | [google_compute_instance_groups](../inspec/resources/google_compute_instance_groups/index) | [google_compute_instance_template](../inspec/resources/google_compute_instance_template/index) | [google_compute_instance_templates](../inspec/resources/google_compute_instance_templates/index) | [google_compute_instances](../inspec/resources/google_compute_instances/index) | [google_compute_network](../inspec/resources/google_compute_network/index) | [google_compute_network_endpoint_group](../inspec/resources/google_compute_network_endpoint_group/index) | [google_compute_network_endpoint_groups](../inspec/resources/google_compute_network_endpoint_groups/index) | [google_compute_networks](../inspec/resources/google_compute_networks/index) | [google_compute_node_group](../inspec/resources/google_compute_node_group/index) | [google_compute_node_groups](../inspec/resources/google_compute_node_groups/index) | [google_compute_node_template](../inspec/resources/google_compute_node_template/index) | [google_compute_node_templates](../inspec/resources/google_compute_node_templates/index) | [google_compute_project_info](../inspec/resources/google_compute_project_info/index) | [google_compute_region](../inspec/resources/google_compute_region/index) | [google_compute_region_backend_service](../inspec/resources/google_compute_region_backend_service/index) | [google_compute_region_backend_services](../inspec/resources/google_compute_region_backend_services/index) | [google_compute_region_instance_group_manager](../inspec/resources/google_compute_region_instance_group_manager/index) | [google_compute_region_instance_group_managers](../inspec/resources/google_compute_region_instance_group_managers/index) | [google_compute_regional_disk](../inspec/resources/google_compute_regional_disk/index) | [google_compute_regions](../inspec/resources/google_compute_regions/index) | [google_compute_route](../inspec/resources/google_compute_route/index) | [google_compute_router](../inspec/resources/google_compute_router/index) | [google_compute_router_nat](../inspec/resources/google_compute_router_nat/index) | [google_compute_router_nats](../inspec/resources/google_compute_router_nats/index) | [google_compute_routers](../inspec/resources/google_compute_routers/index) | [google_compute_routes](../inspec/resources/google_compute_routes/index) | [google_compute_security_policies](../inspec/resources/google_compute_security_policies/index) | [google_compute_security_policy](../inspec/resources/google_compute_security_policy/index) | [google_compute_snapshot](../inspec/resources/google_compute_snapshot/index) | [google_compute_snapshots](../inspec/resources/google_compute_snapshots/index) | [google_compute_ssl_certificate](../inspec/resources/google_compute_ssl_certificate/index) | [google_compute_ssl_certificates](../inspec/resources/google_compute_ssl_certificates/index) | [google_compute_ssl_policies](../inspec/resources/google_compute_ssl_policies/index) | [google_compute_ssl_policy](../inspec/resources/google_compute_ssl_policy/index) | [google_compute_subnetwork](../inspec/resources/google_compute_subnetwork/index) | [google_compute_subnetwork_iam_binding](../inspec/resources/google_compute_subnetwork_iam_binding/index) | [google_compute_subnetwork_iam_policy](../inspec/resources/google_compute_subnetwork_iam_policy/index) | [google_compute_subnetworks](../inspec/resources/google_compute_subnetworks/index) | [google_compute_target_http_proxies](../inspec/resources/google_compute_target_http_proxies/index) | [google_compute_target_http_proxy](../inspec/resources/google_compute_target_http_proxy/index) | [google_compute_target_https_proxies](../inspec/resources/google_compute_target_https_proxies/index) | [google_compute_target_https_proxy](../inspec/resources/google_compute_target_https_proxy/index) | [google_compute_target_pool](../inspec/resources/google_compute_target_pool/index) | [google_compute_target_pools](../inspec/resources/google_compute_target_pools/index) | [google_compute_target_tcp_proxies](../inspec/resources/google_compute_target_tcp_proxies/index) | [google_compute_target_tcp_proxy](../inspec/resources/google_compute_target_tcp_proxy/index) | [google_compute_url_map](../inspec/resources/google_compute_url_map/index) | [google_compute_url_maps](../inspec/resources/google_compute_url_maps/index) | [google_compute_vpn_tunnel](../inspec/resources/google_compute_vpn_tunnel/index) | [google_compute_vpn_tunnels](../inspec/resources/google_compute_vpn_tunnels/index) | [google_compute_zone](../inspec/resources/google_compute_zone/index) | [google_compute_zones](../inspec/resources/google_compute_zones/index) | [google_container_cluster](../inspec/resources/google_container_cluster/index) | [google_container_clusters](../inspec/resources/google_container_clusters/index) | [google_container_node_pool](../inspec/resources/google_container_node_pool/index) | [google_container_node_pools](../inspec/resources/google_container_node_pools/index) | [google_container_regional_cluster](../inspec/resources/google_container_regional_cluster/index) | [google_container_regional_clusters](../inspec/resources/google_container_regional_clusters/index) | [google_container_regional_node_pool](../inspec/resources/google_container_regional_node_pool/index) | [google_container_regional_node_pools](../inspec/resources/google_container_regional_node_pools/index) | [google_dataproc_cluster](../inspec/resources/google_dataproc_cluster/index) | [google_dataproc_clusters](../inspec/resources/google_dataproc_clusters/index) | [google_dns_managed_zone](../inspec/resources/google_dns_managed_zone/index) | [google_dns_managed_zones](../inspec/resources/google_dns_managed_zones/index) | [google_dns_resource_record_set](../inspec/resources/google_dns_resource_record_set/index) | [google_dns_resource_record_sets](../inspec/resources/google_dns_resource_record_sets/index) | [google_filestore_instance](../inspec/resources/google_filestore_instance/index) | [google_filestore_instances](../inspec/resources/google_filestore_instances/index) | [google_iam_custom_role](../inspec/resources/google_iam_custom_role/index) | [google_iam_custom_roles](../inspec/resources/google_iam_custom_roles/index) | [google_iam_organization_custom_role](../inspec/resources/google_iam_organization_custom_role/index) | [google_iam_organization_custom_roles](../inspec/resources/google_iam_organization_custom_roles/index) | [google_iam_service_account](../inspec/resources/google_iam_service_account/index) | [google_iam_service_account_key](../inspec/resources/google_iam_service_account_key/index) | [google_iam_service_account_keys](../inspec/resources/google_iam_service_account_keys/index) | [google_iam_service_accounts](../inspec/resources/google_iam_service_accounts/index) | [google_kms_crypto_key](../inspec/resources/google_kms_crypto_key/index) | [google_kms_crypto_key_iam_binding](../inspec/resources/google_kms_crypto_key_iam_binding/index) | [google_kms_crypto_key_iam_bindings](../inspec/resources/google_kms_crypto_key_iam_bindings/index) | [google_kms_crypto_key_iam_policy](../inspec/resources/google_kms_crypto_key_iam_policy/index) | [google_kms_crypto_keys](../inspec/resources/google_kms_crypto_keys/index) | [google_kms_key_ring](../inspec/resources/google_kms_key_ring/index) | [google_kms_key_ring_iam_binding](../inspec/resources/google_kms_key_ring_iam_binding/index) | [google_kms_key_ring_iam_bindings](../inspec/resources/google_kms_key_ring_iam_bindings/index) | [google_kms_key_ring_iam_policy](../inspec/resources/google_kms_key_ring_iam_policy/index) | [google_kms_key_rings](../inspec/resources/google_kms_key_rings/index) | [google_logging_folder_exclusion](../inspec/resources/google_logging_folder_exclusion/index) | [google_logging_folder_exclusions](../inspec/resources/google_logging_folder_exclusions/index) | [google_logging_folder_log_sink](../inspec/resources/google_logging_folder_log_sink/index) | [google_logging_folder_log_sinks](../inspec/resources/google_logging_folder_log_sinks/index) | [google_logging_organization_log_sink](../inspec/resources/google_logging_organization_log_sink/index) | [google_logging_organization_log_sinks](../inspec/resources/google_logging_organization_log_sinks/index) | [google_logging_project_exclusion](../inspec/resources/google_logging_project_exclusion/index) | [google_logging_project_exclusions](../inspec/resources/google_logging_project_exclusions/index) | [google_logging_project_sink](../inspec/resources/google_logging_project_sink/index) | [google_logging_project_sinks](../inspec/resources/google_logging_project_sinks/index) | [google_ml_engine_model](../inspec/resources/google_ml_engine_model/index) | [google_ml_engine_models](../inspec/resources/google_ml_engine_models/index) | [google_organization](../inspec/resources/google_organization/index) | [google_organization_iam_binding](../inspec/resources/google_organization_iam_binding/index) | [google_organization_iam_policy](../inspec/resources/google_organization_iam_policy/index) | [google_organization_policy](../inspec/resources/google_organization_policy/index) | [google_organizations](../inspec/resources/google_organizations/index) | [google_project](../inspec/resources/google_project/index) | [google_project_alert_policies](../inspec/resources/google_project_alert_policies/index) | [google_project_alert_policy](../inspec/resources/google_project_alert_policy/index) | [google_project_alert_policy_condition](../inspec/resources/google_project_alert_policy_condition/index) | [google_project_iam_binding](../inspec/resources/google_project_iam_binding/index) | [google_project_iam_bindings](../inspec/resources/google_project_iam_bindings/index) | [google_project_iam_custom_role](../inspec/resources/google_project_iam_custom_role/index) | [google_project_iam_custom_roles](../inspec/resources/google_project_iam_custom_roles/index) | [google_project_iam_policy](../inspec/resources/google_project_iam_policy/index) | [google_project_logging_audit_config](../inspec/resources/google_project_logging_audit_config/index) | [google_project_metric](../inspec/resources/google_project_metric/index) | [google_project_metrics](../inspec/resources/google_project_metrics/index) | [google_project_service](../inspec/resources/google_project_service/index) | [google_project_services](../inspec/resources/google_project_services/index) | [google_projects](../inspec/resources/google_projects/index) | [google_pubsub_subscription](../inspec/resources/google_pubsub_subscription/index) | [google_pubsub_subscription_iam_binding](../inspec/resources/google_pubsub_subscription_iam_binding/index) | [google_pubsub_subscription_iam_policy](../inspec/resources/google_pubsub_subscription_iam_policy/index) | [google_pubsub_subscriptions](../inspec/resources/google_pubsub_subscriptions/index) | [google_pubsub_topic](../inspec/resources/google_pubsub_topic/index) | [google_pubsub_topic_iam_binding](../inspec/resources/google_pubsub_topic_iam_binding/index) | [google_pubsub_topic_iam_policy](../inspec/resources/google_pubsub_topic_iam_policy/index) | [google_pubsub_topics](../inspec/resources/google_pubsub_topics/index) | [google_redis_instance](../inspec/resources/google_redis_instance/index) | [google_redis_instances](../inspec/resources/google_redis_instances/index) | [google_resourcemanager_folder](../inspec/resources/google_resourcemanager_folder/index) | [google_resourcemanager_folder_iam_binding](../inspec/resources/google_resourcemanager_folder_iam_binding/index) | [google_resourcemanager_folder_iam_policy](../inspec/resources/google_resourcemanager_folder_iam_policy/index) | [google_resourcemanager_folders](../inspec/resources/google_resourcemanager_folders/index) | [google_resourcemanager_organization_policy](../inspec/resources/google_resourcemanager_organization_policy/index) | [google_resourcemanager_project_iam_binding](../inspec/resources/google_resourcemanager_project_iam_binding/index) | [google_resourcemanager_project_iam_policy](../inspec/resources/google_resourcemanager_project_iam_policy/index) | [google_runtime_config_config](../inspec/resources/google_runtime_config_config/index) | [google_runtime_config_config_iam_binding](../inspec/resources/google_runtime_config_config_iam_binding/index) | [google_runtime_config_config_iam_policy](../inspec/resources/google_runtime_config_config_iam_policy/index) | [google_runtime_config_configs](../inspec/resources/google_runtime_config_configs/index) | [google_runtime_config_variable](../inspec/resources/google_runtime_config_variable/index) | [google_runtime_config_variables](../inspec/resources/google_runtime_config_variables/index) | [google_service_account](../inspec/resources/google_service_account/index) | [google_service_account_key](../inspec/resources/google_service_account_key/index) | [google_service_account_keys](../inspec/resources/google_service_account_keys/index) | [google_service_accounts](../inspec/resources/google_service_accounts/index) | [google_sourcerepo_repositories](../inspec/resources/google_sourcerepo_repositories/index) | [google_sourcerepo_repository](../inspec/resources/google_sourcerepo_repository/index) | [google_spanner_database](../inspec/resources/google_spanner_database/index) | [google_spanner_databases](../inspec/resources/google_spanner_databases/index) | [google_spanner_instance](../inspec/resources/google_spanner_instance/index) | [google_spanner_instance_iam_binding](../inspec/resources/google_spanner_instance_iam_binding/index) | [google_spanner_instance_iam_policy](../inspec/resources/google_spanner_instance_iam_policy/index) | [google_spanner_instances](../inspec/resources/google_spanner_instances/index) | [google_sql_database_instance](../inspec/resources/google_sql_database_instance/index) | [google_sql_database_instances](../inspec/resources/google_sql_database_instances/index) | [google_sql_user](../inspec/resources/google_sql_user/index) | [google_sql_users](../inspec/resources/google_sql_users/index) | [google_storage_bucket](../inspec/resources/google_storage_bucket/index) | [google_storage_bucket_acl](../inspec/resources/google_storage_bucket_acl/index) | [google_storage_bucket_iam_binding](../inspec/resources/google_storage_bucket_iam_binding/index) | [google_storage_bucket_iam_bindings](../inspec/resources/google_storage_bucket_iam_bindings/index) | [google_storage_bucket_iam_policy](../inspec/resources/google_storage_bucket_iam_policy/index) | [google_storage_bucket_object](../inspec/resources/google_storage_bucket_object/index) | [google_storage_bucket_objects](../inspec/resources/google_storage_bucket_objects/index) | [google_storage_buckets](../inspec/resources/google_storage_buckets/index) | [google_storage_default_object_acl](../inspec/resources/google_storage_default_object_acl/index) | [google_storage_object_acl](../inspec/resources/google_storage_object_acl/index) | [google_user](../inspec/resources/google_user/index) | [google_users](../inspec/resources/google_users/index) **Habitat Resources** : [habitat_package](../inspec/resources/habitat_package/index) | [habitat_packages](../inspec/resources/habitat_packages/index) | [habitat_service](../inspec/resources/habitat_service/index) | [habitat_services](../inspec/resources/habitat_services/index) Chef Workstation ----------------- [Overview](../workstation/index) | [Install](../workstation/install_workstation/index) | [Setup](../workstation/getting_started/index) | [Configure](../workstation/config/index) | [Troubleshooting](../workstation/troubleshooting/index) | [Privacy and Telemetry](../workstation/privacy/index) ### Chef Workstation Tools [Berkshelf](../workstation/berkshelf/index) **chef (executable)** : [chef executable (full page)](../workstation/ctl_chef/index) | [chef capture](../workstation/ctl_chef/index#chef-capture) | [chef env](../workstation/ctl_chef/index#chef-env) | [chef exec](../workstation/ctl_chef/index#chef-exec) | [chef gem](../workstation/ctl_chef/index#chef-gem) | [chef generate attribute](../workstation/ctl_chef/index#chef-generate-attribute) | [chef generate cookbook](../workstation/ctl_chef/index#chef-generate-cookbook) | [chef generate file](../workstation/ctl_chef/index#chef-generate-file) | [chef generate recipe](../workstation/ctl_chef/index#chef-generate-recipe) | [chef generate repo](../workstation/ctl_chef/index#chef-generate-repo) | [chef generate resource](../workstation/ctl_chef/index#chef-generate-resource) | [chef generate template](../workstation/ctl_chef/index#chef-generate-template) | [chef report cookbooks](../workstation/ctl_chef/index#chef-report-cookbooks) | [chef report nodes](../workstation/ctl_chef/index#chef-report-nodes) | [chef shell-init](../workstation/ctl_chef/index#chef-shell-init) | [chef-run (executable)](../workstation/chef_run/index) | [chef-shell (executable)](../workstation/chef_shell/index) | [chef-vault (executable)](../workstation/chef_vault/index) | [ChefSpec](../workstation/chefspec/index) | [Chef Workstation App](../workstation/chef-workstation-app/index) | [config.rb (knife.rb)](../workstation/config_rb/index) | [Optional config.rb Settings](../workstation/config_rb_optional_settings/index) **Cookstyle** : [About Cookstyle](../workstation/cookstyle/index) | [All Cookstyle Cops](../workstation/cookstyle/cops/index) | [Correctness Cops](../workstation/cookstyle/cops/index#chefcorrectness) | [Chef Deprecation Cops](../workstation/cookstyle/cops/index#chefdeprecations) | [Effortless Cops](../workstation/cookstyle/cops/index#chefeffortless) | [Modernization Cops](../workstation/cookstyle/cops/index#chefmodernize) | [Redundant Code Cops](../workstation/cookstyle/cops/index#chefredundantcode) | [Security Cops](../workstation/cookstyle/cops/index#chefsecurity) | [Sharing Cops](../workstation/cookstyle/cops/index#chefsharing) | [Style Cops](../workstation/cookstyle/cops/index#chefstyle) | [InSpec Deprecations Cops](../workstation/cookstyle/cops/index#inspecdeprecations) **Test Kitchen** : [About Test Kitchen](../workstation/kitchen/index) | [kitchen (executable)](../workstation/ctl_kitchen/index) | [kitchen.yml](../workstation/config_yml_kitchen/index) | [kitchen-vagrant](../workstation/plugin_kitchen_vagrant/index) **Knife** : [About Knife](../workstation/knife/index) | [Setting up Knife](../workstation/knife_setup/index) | [Knife Common Options](../workstation/knife_options/index) | [config.rb (knife.rb)](../workstation/config_rb/index) | [knife azurerm](../workstation/knife_azurerm/index) | [knife bootstrap](../workstation/knife_bootstrap/index) | [knife client](../workstation/knife_client/index) | [knife configure](../workstation/knife_configure/index) | [knife cookbook](../workstation/knife_cookbook/index) | [knife cookbook site](../workstation/knife_cookbook_site/index) | [knife data bag](../workstation/knife_data_bag/index) | [knife delete](../workstation/knife_delete/index) | [knife deps](../workstation/knife_deps/index) | [knife diff](../workstation/knife_diff/index) | [knife download](../workstation/knife_download/index) | [knife edit](../workstation/knife_edit/index) | [knife environment](../workstation/knife_environment/index) | [knife exec](../workstation/knife_exec/index) | [knife list](../workstation/knife_list/index) | [knife node](../workstation/knife_node/index) | [knife opc](../workstation/plugin_knife_opc/index) | [knife org](../workstation/knife_org/index) | [knife raw](../workstation/knife_raw/index) | [knife recipe list](../workstation/knife_recipe_list/index) | [knife role](../workstation/knife_role/index) | [knife search](../workstation/knife_search/index) | [knife serve](../workstation/knife_serve/index) | [knife show](../workstation/knife_show/index) | [knife ssh](../workstation/knife_ssh/index) | [knife ssl_check](../workstation/knife_ssl_check/index) | [knife ssl_fetch](../workstation/knife_ssl_fetch/index) | [knife status](../workstation/knife_status/index) | [knife supermarket](../workstation/knife_supermarket/index) | [knife tag](../workstation/knife_tag/index) | [knife upload](../workstation/knife_upload/index) | [knife user](../workstation/knife_user/index) | [knife windows](../workstation/knife_windows/index) | [knife xargs](../workstation/knife_xargs/index) | [Upgrade Lab](../workstation/upgrade_lab/index) ### Extension APIs **Knife Plugins** : [Cloud Plugins](../workstation/plugin_knife/index) | [Writing Custom Plugins](../workstation/plugin_knife_custom/index) Effortless Pattern ------------------- [Effortless Overview](../effortless/index) | [Quick Start](../effortless/quick_start/index) | [Effortless Audit](../effortless/effortless_audit/index) | [Effortless Config](../effortless/effortless_config/index) | [Variables and Config](../effortless/variables_and_config/index) | [What is Scaffolding](../effortless/what_is_scaffolding/index) Supermarket ------------ [About Supermarket](../supermarket/index) | [Share Cookbooks](../supermarket/supermarket_share_cookbook/index) ### Private Supermarket [About Private Supermarket](../supermarket/supermarket_private/index) | [Install](../supermarket/install_supermarket/index) | [Upgrades](../supermarket/supermarket_upgrade/index) | [Configure](../supermarket/config_rb_supermarket/index) | [Backup and Restore](../supermarket/supermarket_backup_restore/index) | [Monitor](../supermarket/supermarket_monitor/index) | [Log Files](../supermarket/supermarket_logs/index) ### Reference [supermarket-ctl](../supermarket/ctl_supermarket/index) | [Supermarket API](../supermarket/supermarket_api/index) Release Notes -------------- [Chef Automate](https://docs.chef.io/release_notes_automate/) | [Chef Backend](https://docs.chef.io/release_notes_backend/) | [Chef Habitat](https://docs.chef.io/release_notes_habitat/) | [Chef Infra Client](https://docs.chef.io/release_notes_client/) | [Chef Infra Server](https://docs.chef.io/release_notes_server/) | [Chef InSpec](https://docs.chef.io/release_notes_inspec/) | [Chef Manage](https://docs.chef.io/release_notes_manage/) | [Chef Supermarket](https://docs.chef.io/release_notes_supermarket/) | [Chef Workstation](https://docs.chef.io/release_notes_workstation/) ### Chef Cloud Resource Packs [AWS Cloud Resources](https://docs.chef.io/release_notes_inspec_aws/) | [Azure Cloud Resources](https://docs.chef.io/release_notes_inspec_azure/) Legacy ------- ### Chef Manage [About the Management Console](../manage/index) | [manage.rb](../config_rb_manage/index) | [chef-manage-ctl](../ctl_manage/index) | [Active Directory & LDAP](../server_ldap/index) | [Configure SAML](../server_configure_saml/index) | [Clients](../server_manage_clients/index) | [Cookbooks](../server_manage_cookbooks/index) | [Data Bags](../server_manage_data_bags/index) | [Environments](../server_manage_environments/index) | [Nodes](../server_manage_nodes/index) | [Roles](../server_manage_roles/index) | [Organizations & Groups](../server_orgs/index) | [Users](../server_users/index) [Send Feedback](https://docs.chef.io/feedback/) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/sitemap/knife delete ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_delete.md) Use the `knife delete` subcommand to delete an object from a Chef Infra Server. This subcommand works similar to `knife cookbook delete`, `knife data bag delete`, `knife environment delete`, `knife node delete`, and `knife role delete`, but with a single verb (and a single action). Syntax ------ This subcommand has the following syntax: ``` knife delete [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--both` Delete both local and remote copies of an object. Default: `false`. `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--local` Delete only the local copy of an object. A remote copy will not be deleted. Default: `false`. `-r`, `--[no-]recurse` Use `--recurse` to delete directories recursively. Default: `--no-recurse`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- None. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_delete/knife data bag ============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_data_bag.md) Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. A data bag item may be encrypted using [shared secret encryption](https://en.wikipedia.org/wiki/Symmetric-key_algorithm). This allows each data bag item to store confidential information (such as a database password) or to be managed in a source control system (without plain-text data appearing in revision history). Each data bag item may be encrypted individually; if a data bag contains multiple encrypted data bag items, these data bag items are not required to share the same encryption keys. Note Because the contents of encrypted data bag items are not visible to the Chef Infra Server, search queries against data bags with encrypted items will not return any results. Use the `knife data bag` subcommand to manage arbitrary stores of globally available JSON data. Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. create ------ Use the `create` argument to add a data bag to the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife data bag create DATA_BAG_NAME [DATA_BAG_ITEM] (options) ``` ### Options This argument has the following options: `DATA_BAG_ITEM` The name of a specific item within a data bag. `DATA_BAG_NAME` may not be `client`, `environment`, `node` or `role`, as these are reserved words for [knife search](../workstation/knife_search/index). `--secret SECRET` The encryption key that is used for values contained within a data bag item. If `secret` is not specified, Chef Infra Client looks for a secret at the path specified by the `encrypted_data_bag_secret` setting in the client.rb file. For encrypted data bag items, use **either** `--secret` or `--secret-file`, not both. `--secret-file FILE` The path to the file that contains the encryption key. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create a data bag** To create a data bag named “admins”, enter: ``` knife data bag create admins ``` to return: ``` Created data_bag[admins] ``` delete ------ Use the `delete` argument to delete a data bag or a data bag item from a Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife data bag delete DATA_BAG_NAME [DATA_BAG_ITEM] (options) ``` ### Options This argument has the following options: `DATA_BAG_ITEM` The name of a specific item within a data bag. ### Examples The following examples show how to use this knife subcommand: **Delete a data bag** ``` knife data bag delete data_bag_name ``` **Delete a data bag item** To delete an item named “charlie”, enter: ``` knife data bag delete admins charlie ``` Type `Y` to confirm a deletion. edit ---- Use the `edit` argument to edit the data contained in a data bag. If encryption is being used, the data bag will be decrypted, the data will be made available in the $EDITOR, and then encrypted again before saving it to the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife data bag edit DATA_BAG_NAME [DATA_BAG_ITEM] (options) ``` ### Options This argument has the following options: `DATA_BAG_ITEM` The name of a specific item within a data bag. `--secret SECRET` The encryption key that is used for values contained within a data bag item. If `secret` is not specified, Chef Infra Client looks for a secret at the path specified by the `encrypted_data_bag_secret` setting in the client.rb file. `--secret-file FILE` The path to the file that contains the encryption key. Note For encrypted data bag items, use *either* `--secret` or `--secret-file`, not both. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Edit a data bag** To edit the contents of a data bag, enter: ``` knife data bag edit dogs tibetanspaniel ``` where `dogs` is the name of the data bag and `tibetanspaniel` is the name of the data bag item. This will return something similar to the following in the knife editor: ``` { "name":"data_bag_item_dogs_tibetanspaniel", "json_class":"Chef::DataBagItem", "chef_type":"data_bag_item", "data_bag":"dogs", "raw_data": { "description":"small dog that likes to sit in windows", "id":"tibetanspaniel" } } ``` Make the necessary changes to the key-value pairs under `raw_data` and save them. **Edit a data bag item** To edit an item named “charlie” that is contained in a data bag named “admins”, enter: ``` knife data bag edit admins charlie ``` to open the $EDITOR. Once opened, you can update the data before saving it to the Chef Infra Server. For example, by changing: ``` { "id": "charlie" } ``` to: ``` { "id": "charlie", "uid": 1005, "gid": "ops", "shell": "/bin/zsh", "comment": "<NAME>" } ``` from file --------- Use the `from file` argument to: * Add a data bag item to a data bag * Update the contents of an existing data bag item The data bag itself must already exist on the Chef Infra Server and must be specified as part of the command. The contents of the data bag item are specified using a JSON file. This JSON file may be located at a relative or absolute path; its location must be specified as part of the command. The JSON file that defines the contents of the data bag item must at least contain the name of the data bag item—`"id": "name"`. ### Syntax This argument has the following syntax: ``` knife data bag from file DATA_BAG_NAME_or_PATH JSON_FILE ``` ### Options This argument has the following options: `-a`, `--all` Upload all data bags found at the specified path. `--secret SECRET` The encryption key that is used for values contained within a data bag item. If `secret` is not specified, Chef Infra Client looks for a secret at the path specified by the `encrypted_data_bag_secret` setting in the client.rb file. `--secret-file FILE` The path to the file that contains the encryption key. Note For encrypted data bag items, use *either* `--secret` or `--secret-file`, not both. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create a data bag from a file** To create a data bag on the Chef Infra Server from a file: ``` knife data bag from file "path to JSON file" ``` **Create an encrypted data bag from a file** To create a data bag named “devops_data” that contains encrypted data, enter: ``` knife data bag from file devops_data --secret-file "path to decryption file" ``` **Create an encrypted data bag for use with Chef Infra Client local mode** To generate an encrypted data bag item in a JSON file for use when Chef Infra Client is run in local mode (via the `--local-mode` option), enter: ``` knife data bag from file my_data_bag /path/to/data_bag_item.json -z --secret-file /path/to/encrypted_data_bag_secret ``` this will create an encrypted JSON file in: ``` data_bags/my_data_bag/data_bag_item.json ``` list ---- Use the `list` argument to view a list of data bags that are currently available on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife data bag list ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### Examples The following examples show how to use this knife subcommand: **View a list of data bags** ``` knife data bag list ``` show ---- Use the `show` argument to view the contents of a data bag. ### Syntax This argument has the following syntax: ``` knife data bag show DATA_BAG_NAME (options) ``` ### Options This argument has the following options: `DATA_BAG_ITEM` The name of a specific item within a data bag. `--secret SECRET` The encryption key that is used for values contained within a data bag item. If `secret` is not specified, Chef Infra Client looks for a secret at the path specified by the `encrypted_data_bag_secret` setting in the client.rb file. `--secret-file FILE` The path to the file that contains the encryption key. Note For encrypted data bag items, use *either* `--secret` or `--secret-file`, not both. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Show a data bag** ``` knife data bag show admins ``` to return something like: ``` charlie ``` **Show a data bag item** To show the contents of a specific item within data bag, enter: ``` knife data bag show admins charlie ``` to return: ``` comment: Crazy Charlie gid: ops id: charlie shell: /bin/zsh uid: 1005 ``` **Show a data bag, encrypted** To show the contents of a data bag named `passwords` with an item that contains encrypted data named `mysql`, enter: ``` knife data bag show passwords mysql ``` to return: ``` { "id": "mysql", "pass": "trywgFA6R70NO28PNhMpGhEvKBZuxouemnbnAUQsUyo=\n", "user": "e/p+8WJYVHY9fHcEgAAReg==\n" } ``` **Show a data bag, decrypted** To show the decrypted contents of the same data bag, enter: ``` knife data bag show --secret-file /path/to/decryption/file passwords mysql ``` to return: ``` { "id": "mysql", "pass": "thesecret123", "user": "fred" } ``` **Show a data bag as JSON** To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife data bag show admins -F json ``` Other formats available include `text`, `yaml`, and `pp`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_data_bag/knife deps ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_deps.md) Use the `knife deps` subcommand to identify dependencies for a node, role, or cookbook. Syntax ------ This subcommand has the following syntax: ``` knife deps (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--[no-]recurse` Use `--recurse` to list dependencies recursively. This option can only be used when `--tree` is set to `true`. Default: `--no-recurse`. `--remote` Determine dependencies from objects located on the Chef Infra Server instead of in the local chef-repo. Default: `false`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. `--tree` Show dependencies in a visual tree structure (including duplicates, if they exist). Default: `false`. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Find dependencies for a node** ``` knife deps nodes/node_name.json ``` **Find dependencies for a role** ``` knife deps roles/role_name.json ``` **Find dependencies for a cookbook** ``` knife deps cookbooks/cookbook_name.json ``` **Find dependencies for an environment** ``` knife deps environments/environment_name.json ``` **Find dependencies for a combination of nodes, roles, and so on** To find the dependencies for a combination of nodes, cookbooks, roles, and/or environments: ``` knife deps cookbooks/git.json cookbooks/github.json roles/base.json environments/desert.json nodes/mynode.json ``` **Use a wildcard** A wildcard can be used to return all of the child nodes. For example, all of the environments: ``` knife deps environments/*.json ``` **Return as tree** Use the `--tree` option to view the results with structure: ``` knife deps roles/webserver.json ``` to return something like: ``` roles/webserver.json roles/base.json cookbooks/github cookbooks/git cookbooks/users cookbooks/apache2 ``` **Pass knife deps output to knife upload** The output of `knife deps` can be passed to `knife upload`: ``` knife upload `knife deps nodes/*.json ``` **Pass knife deps output to knife xargs** The output of `knife deps` can be passed to `knife xargs`: ``` knife deps nodes/*.json | xargs knife upload ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_deps/knife diff ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_diff.md) Use the `knife diff` subcommand to compare the differences between files and directories on the Chef Infra Server and in the chef-repo. For example, to compare files on the Chef Infra Server prior to uploading or downloading files using the `knife download` and `knife upload` subcommands, or to ensure that certain files in multiple production environments are the same. This subcommand is similar to the `git diff` command that can be used to diff what is in the chef-repo with what is synced to a git repository. Syntax ------ This subcommand has the following syntax: ``` knife diff [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--cookbook-version VERSION` The version of a cookbook to download. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--diff-filter=[(A|D|M|T)...[*]]` Select only files that have been added (`A`), deleted (`D`), modified (`M`), and/or have had their type changed (`T`). Any combination of filter characters may be used, including no filter characters. Use `*` to select all paths if a file matches other criteria in the comparison. Default value: `nil`. `--name-only` Show only the names of modified files. `--name-status` Show only the names of files with a status of `Added`, `Deleted`, `Modified`, or `Type Changed`. `--no-recurse` Use `--no-recurse` to disable listing a directory recursively. Default: `--recurse`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Compare files that contain JSON data** To compare the `base.json` role to a `webserver.json` role, enter: ``` knife diff roles/base.json roles/webserver.json ``` **Compare the chef-repo and the server** To compare the differences between the local chef-repo and the files that are on the Chef Infra Server, enter: ``` knife diff ``` **Compare, then return results** To diff a node named `node-lb` and then only return files that have been added, deleted, modified, or changed, enter: ``` knife diff --name-status node-lb ``` to return something like: ``` node-lb/recipes/eip.rb node-lb/recipes/heartbeat-int.rb node-lb/templates/default/corpsite.conf.erb node-lb/files/default/wildcard.node.com.crt node-lb/files/default/wildcard.node.com.crt-2009 node-lb/files/default/wildcard.node.com.key node-lb/.gitignore node-lb/Rakefile ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_diff/knife download ============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_download.md) Use the `knife download` subcommand to download roles, cookbooks, environments, nodes, and data bags from the Chef Infra Server to the current working directory. It can be used to back up data on the Chef Infra Server, inspect the state of one or more files, or to extract out-of-process changes users may have made to files on the Chef Infra Server, such as if a user made a change that bypassed version source control. This subcommand is often used in conjunction with `knife diff`, which can be used to see exactly what changes will be downloaded, and then `knife upload`, which does the opposite of `knife download`. Syntax ------ This subcommand has the following syntax: ``` knife download [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--cookbook-version VERSION` The version of a cookbook to download. `-n`, `--dry-run` Take no action and only print out results. Default: `false`. `--[no-]diff` Download only new and modified files. Set to `false` to download all files. Default: `--diff`. `--[no-]force` Use `--force` to download files even when the file on the hard drive is identical to the object on the server (role, cookbook, etc.). By default, files are compared to see if they have equivalent content, and local files are only overwritten if they are different. Default: `--no-force`. `--[no-]purge` Use `--purge` to delete local files and directories that do not exist on the Chef Infra Server. By default, if a role, cookbook, etc. does not exist on the Chef Infra Server, the local file for said role is left alone and NOT deleted. Default: `--no-purge`. `--[no-]recurse` Use `--no-recurse` to disable downloading a directory recursively. Default: `--recurse`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Download the entire chef-repo** To download the entire chef-repo from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download / ``` **Download the /cookbooks directory** To download the `cookbooks/` directory from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download cookbooks ``` or from anywhere in the chef-repo, enter: ``` knife download /cookbooks ``` **Download the /environments directory** To download the `environments/` directory from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download environments ``` or from anywhere in the chef-repo, enter: ``` knife download /environments ``` **Download an environment** To download an environment named “production” from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download environments/production.json ``` or from the `environments/` directory, enter: ``` knife download production.json ``` **Download the /roles directory** To download the `roles/` directory from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download roles ``` or from anywhere in the chef-repo, enter: ``` knife download /roles ``` **Download cookbooks and roles** To download all cookbooks that start with “apache” and belong to the “webserver” role, browse to the top level of the chef-repo and enter: ``` knife download cookbooks/apache\* roles/webserver.json ``` **Download data bags** To download all data bags from the Chef Infra Server, browse to the top level of the chef-repo and enter: ``` knife download data_bags ``` or from anywhere in the chef-repo, enter: ``` knife download /data_bags ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_download/knife edit ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_edit.md) Use the `knife edit` subcommand to edit objects on the Chef Infra Server. This subcommand works similar to `knife cookbook edit`, `knife data bag edit`, `knife environment edit`, `knife node edit`, and `knife role edit`, but with a single verb (and a single action). Syntax ------ This subcommand has the following syntax: ``` knife edit (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--local` Show files in the local chef-repo instead of a remote location. Default: `false`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Remove a user from /groups/admins.json** A user who belongs to the `admins` group must be removed from the group before they may be removed from an organization. To remove a user from the `admins` group, run the following: ``` EDITOR=vi knife edit /groups/admins.json ``` make the required changes, and then save the file. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_edit/chef-server.rb Optional Settings ================================ Version: Chef Infra Server 14 Chef Infra Server 13.2 [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/v14/config_rb_server_optional_settings.md) The `/etc/opscode/chef-server.rb` file contains all of the non-default configuration settings used by the Chef Infra Server. The default settings are built into the Chef Infra Server configuration and should only be added to the `chef-server.rb` file to apply non-default values. These configuration settings are processed when the `chef-server-ctl reconfigure` command is run. The `chef-server.rb` file is a Ruby file, which means that conditional statements can be used within it. Settings -------- The following sections describe the various settings that are available in the chef-server.rb file. Note When changes are made to the chef-server.rb file the Chef Infra Server must be reconfigured by running the following command: ``` chef-server-ctl reconfigure ``` ### General This configuration file has the following general settings: `addons['install']` Default value: `false`. `addons['path']` Default value: `nil`. `addons['packages']` Default value: ``` %w{chef-manage} ``` `api_version` The version of the Chef Infra Server. Default value: `'12.0.0'`. `default_orgname` The `ORG_NAME` part of the `/organizations` endpoint in Chef Infra Server. `flavor` Default value: `'cs'`. `fips` Set to `true` to run the server in FIPS compliance mode. Set to `false` to force the server to run without FIPS compliance mode. Default: The value in the kernel configuration. Note Chef Infra Server versions earlier than 14.5 configured with `nginx['enable_non_ssl'] = false` and `fips = true` require `export CSC_LB_URL=https://127.0.0.1` to run the command `chef-server-ctl reindex <options>` `insecure_addon_compat` Set to `true` to keep Chef Infra Server compatible with older add-on versions by rendering secrets and credentials to `/etc/opscode/chef-server-running.json` and other files in `/etc/opscode/`. When set to `false`, secrets are **only** written to `/etc/opscode/private-chef-secrets.json` and **not** to any other files. Default value: `true`. See [Add-on Compatibility](../server/server_security/index#add-on-compatibility) for the minimum add-on versions supporting `insecure_addon_compat false`. `install_path` The directory in which the Chef Infra Server is installed. Default value: `'/opt/opscode'`. `from_email` The email address from which invitations to the Chef management console are sent. Default value: `'"Opscode" <<EMAIL>.io>'`. `license['nodes']` The number of licensed nodes. Default value: `25`. `license['upgrade_url']` The URL to visit for more information about how to update the number of nodes licensed for an organization. Default value: `'https://www.chef.io/pricing'`. `notification_email` The email addressed to which email notifications are sent. Default value: `'<EMAIL>'`. `role` The configuration type of the Chef Infra Server. Possible values: `backend`, `frontend`, or `standalone`. Default value: `'standalone'`. `topology` The topology of the Chef Infra Server. Possible values: `manual`, `standalone`, and `tier`. Default value: `'standalone'`. ### bookshelf The **bookshelf** service is an Amazon Simple Storage Service (S3)-compatible service that is used to store cookbooks, including all of the files—recipes, templates, and so on—that are associated with each cookbook. Note To [configure the server for external cookbook storage](../server/index#aws-settings), updates are made to settings for both the **bookshelf** and **opscode-erchef** services. This configuration file has the following settings for `bookshelf`: `bookshelf['access_key_id']` Deprecated. Use `chef-server-ctl set-secret bookshelf access_key_id` from the [Secrets Management](../server/ctl_chef_server/index#secrets-management) commands. The access key identifier. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../server/index#aws-settings) for more information on configuring external bookshelf. Default value: **generated**. `bookshelf['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `/var/opt/opscode/bookshelf/data`. `bookshelf['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/bookshelf`. `bookshelf['enable']` Enable a service. Default value: `true`. `bookshelf['enable_request_logging']` Use to configure request logging for the bookshelf service. Default value: `false`. `bookshelf['external_url']` The base URL to which the service is to return links to API resources. Use `:host_header` to ensure the URL is derived from the host header of the incoming HTTP request. Default value: `:host_header`. `bookshelf['listen']` The IP address on which the service is to listen. Default value: `127.0.0.1`. `bookshelf['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/bookshelf`. `bookshelf['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `bookshelf['port']` The port on which the service is to listen. Default value: `4321`. `bookshelf['secret_access_key']` Deprecated. Use `chef-server-ctl set-secret bookshelf secret_access_key` from the [Secrets Management](../server/ctl_chef_server/index#secrets-management) commands. The secret key. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../server/index#aws-settings) for more information on configuring external bookshelf. Default value: **generated**. `bookshelf['storage_type']` Determines where cookbooks are stored. Default value: `:filesystem`. In instances that require cookbooks to be stored within a SQL backend, such as in a high availability setup, you must set `storage_type` to `:sql`: ``` bookshelf['storage_type'] = :sql ``` `bookshelf['stream_download']` Enable stream downloading of cookbooks. This setting (when `true`) typically results in improved cookbook download performance, especially with the memory usage of the **bookshelf** service and the behavior of load balancers and proxies in-between Chef Infra Client and the Chef Infra Server. Default value: `true`. `bookshelf['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `bookshelf['sql_user']` (default: `'bookshelf'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `bookshelf['sql_user']`. Default value: `nil`. `bookshelf['vip']` The virtual IP address. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../server/index#aws-settings) for more information on configuring external bookshelf. Default value: `127.0.0.1`. ### bootstrap This configuration file has the following settings for `bootstrap`: `bootstrap['enable']` Indicates whether an attempt to bootstrap the Chef Infra Server is made. Generally only enabled on systems that have bootstrap enabled via a `server` entry. Default value: `true`. ### compliance forwarding The configuration file has the following settings for forwarding `compliance` requests using the Chef Infra Server authentication system. `profiles['root_url']` If set, any properly signed requests arriving at `/organizations/ORGNAME/owners/OWNER/compliance` will be forwarded to this URL. This is expected to be a fully qualified resource, e.g. `http://compliance.example.org/owners/OWNER/compliance`. ### dark_launch This configuration file has the following settings for `dark_launch`: `dark_launch['actions']` Enable Chef actions. Default value: `true`. `dark_launch['add_type_and_bag_to_items']` Default value: `true`. `dark_launch['new_theme']` Default value: `true`. `dark_launch['private-chef']` Default value: `true`. `dark_launch['quick_start']` Default value: `false`. `dark_launch['reporting']` Enable Reporting, which performs data collection during a Chef Infra Client run. Default value: `true`. `dark_launch['sql_users']` Default value: `true`. ### data_collector This configuration file has the following settings for `data_collector`: `data_collector['root_url']` The fully qualified URL to the data collector server API. When present, it will enable the data collector in **opscode-erchef**. This also enables Chef Infra Server authenticated forwarding any properly signed requests arriving at `/organizations/ORGNAME/data-collector` to this URL with the data collector token appended. This is also target for requests authenticated and forwarded by the `/organizations/ORGNAME/data-collector` endpoint. For the forwarding to work correctly the `data_collector['token']` field must also be set. For example, if the data collector in Chef Automate is being used, the URI would look like: `http://my_automate_server.example.org/data-collector/v0/`. `data_collector['proxy']` If set to `true`, Chef Infra Server will proxy all requests sent to `/data-collector` to the configured Chef Automate `data_collector['root_url']`. Note that *this route* does not check the request signature and add the right data_collector token, but just proxies the Chef Automate endpoint **as-is**. Default value: `nil`. `data_collector['token']` Deprecated. Use `chef-server-ctl set-secret data_collector token` from the [Secrets Management](../server/ctl_chef_server/index#secrets-management) commands. Legacy configuration for shared data collector security token. When configured, the token will be passed as an HTTP header named `x-data-collector-token` which the server can choose to accept or reject. `data_collector['timeout']` The amount of time (in milliseconds) before a request to the data collector API times out. Default value: 30000. `data_collector['http_init_count']` The initial worker count for the HTTP connection pool that is used by the data collector. Default value: 25. `data_collector['http_max_count']` The maximum worker count for the HTTP connection pool that is used by the data collector. Default value: 100. `data_collector['http_max_age']` The maximum connection worker age (in seconds) for the HTTP connection pool that is used by the data collector. Default value: "{70, sec}". `data_collector['http_cull_interval']` The maximum cull interval (in minutes) for the HTTP connection pool that is used by the data collector. Default value: "{1, min}". `data_collector['http_max_connection_duration']` The maximum connection duration (in seconds) for the HTTP connection pool that is used by the data collector. Default value: "{70, sec}". `data_collector['ibrowse_options']` An array of comma-separated key-value pairs of ibrowse options for the HTTP connection pool that is used by the data collector. Default value: "[{connect_timeout, 10000}]". `data_collector['health_check']` A boolean that controls whether the data collector health is included in the overall health at the `_status` endpoint. When set to `true`, Chef Infra Server will report that healthy front end Chef HA cluster members have failed when the data_collector[‘root_url’] cannot be reached. As a result, the load balancer will remove those members from the load balancer pool. Default value: true`. ### estatsd This configuration file has the following settings for `estatsd`: `estatsd['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/estatsd'`. `estatsd['enable']` Enable a service. Default value: `true`. `estatsd['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/log/opscode/estatsd'`. `estatsd['port']` The port on which the service is to listen. Default value: `9466`. `estatsd['protocol']` Use to send application statistics with StatsD protocol formatting. Set this value to `statsd` to apply StatsD protocol formatting. `estatsd['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### lb / lb_internal This configuration file has the following settings for `lb`: `lb['api_fqdn']` Default value: `node['fqdn']`. `lb['ban_refresh_interval']` Default value: `600`. `lb['bookshelf']` Default value: `127.0.0.1`. `lb['cache_cookbook_files']` Default value: `false`. `lb['chef_max_version']` The maximum version of Chef Infra Client that is allowed to access the Chef Infra Server via the Chef Infra Server API. Default value: `11`. `lb['chef_min_version']` The minimum version of Chef Infra Client that is allowed to access the Chef Infra Server via the Chef Infra Server API. Default value: `10`. `lb['chef_server_webui']` Default value: `127.0.0.1`. `lb['debug']` Default value: `false`. `lb['enable']` Enable a service. Default value: `true`. `lb['erchef']` Default value: `127.0.0.1`. `lb['maint_refresh_interval']` Default value: `600`. `lb['redis_connection_pool_size']` Default value: `250`. `lb['redis_connection_timeout']` The amount of time (in milliseconds) to wait before timing out. Default value: `1000`. `lb['redis_keepalive_timeout']` The amount of time (in milliseconds) to wait before timing out. Default value: `2000`. `lb['upstream']['bookshelf']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['oc_bifrost']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['opscode_erchef']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['opscode_solr4']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['vip']` The virtual IP address. Default value: `127.0.0.1`. `lb['web_ui_fqdn']` Default value: `node['fqdn']`. `lb['xdl_defaults']['503_mode']` The default value is the recommended value. Default value: `false`. `lb['xdl_defaults']['couchdb_acls']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_association_requests']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_associations']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_containers']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_groups']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_organizations']` The default value is the recommended value. Default value: `true`. And for the internal load balancers: `lb_internal['account_port']` Default value: `9685`. `lb_internal['chef_port']` Default value: `9680`. `lb_internal['enable']` Default value: `true`. `lb_internal['oc_bifrost_port']` Default value: `9683`. `lb_internal['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### ldap Warning The following settings **MUST** be in the config file for LDAP authentication to Active Directory to work: * `base_dn` * `bind_dn` * `group_dn` * `host` If those settings are missing, you will get authentication errors and be unable to proceed. This configuration file has the following settings for `ldap`: `ldap['base_dn']` The root LDAP node under which all other nodes exist in the directory structure. For Active Directory, this is typically `cn=users` and then the domain. For example: ``` 'OU=Employees,OU=Domain users,DC=example,DC=com' ``` Default value: `nil`. `ldap['bind_dn']` The distinguished name used to bind to the LDAP server. The user the Chef Infra Server will use to perform LDAP searches. This is often the administrator or manager user. This user needs to have read access to all LDAP users that require authentication. The Chef Infra Server must do an LDAP search before any user can log in. Many Active Directory and LDAP systems do not allow an anonymous bind. If anonymous bind is allowed, leave the `bind_dn` and `bind_password` settings blank. If anonymous bind is not allowed, a user with `READ` access to the directory is required. This user must be specified as an LDAP distinguished name similar to: ``` 'CN=user,OU=Employees,OU=Domainuser,DC=example,DC=com' ``` Note If you need to escape characters in a distinguished name, such as when using Active Directory, they must be [escaped with a backslash escape character](https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx). ``` 'CN=example\\user,OU=Employees,OU=Domainuser,DC=example,DC=com' ``` Default value: `nil`. `ldap['bind_password']` Deprecated. Use `chef-server-ctl set-secret ldap bind_password` from the [Secrets Management](../ctl_chef_server#ctl-chef-server-secrets-management) commands. Legacy configuration for the password of the binding user. The password for the user specified by `ldap['bind_dn']`. Leave this value and `ldap['bind_dn']` unset if anonymous bind is sufficient. Default value: `nil`. ``` chef-server-ctl set-secret ldap bind_password Enter ldap bind_password: (no terminal output) Re-enter ldap bind_password: (no terminal output) ``` Remove a set password via ``` chef-server-ctl remove-secret ldap bind_password ``` `ldap['group_dn']` The distinguished name for a group. When set to the distinguished name of a group, only members of that group can log in. This feature filters based on the `memberOf` attribute and only works with LDAP servers that provide such an attribute. In OpenLDAP, the `memberOf` overlay provides this attribute. For example, if the value of the `memberOf` attribute is `CN=abcxyz,OU=users,DC=company,DC=com`, then use: ``` ldap['group_dn'] = 'CN=abcxyz,OU=users,DC=company,DC=com' ``` `ldap['host']` The name (or IP address) of the LDAP server. The hostname of the LDAP or Active Directory server. Be sure the Chef Infra Server is able to resolve any host names. Default value: `ldap-server-host`. `ldap['login_attribute']` The LDAP attribute that holds the user’s login name. Use to specify the Chef Infra Server user name for an LDAP user. Default value: `sAMAccountName`. `ldap['port']` An integer that specifies the port on which the LDAP server listens. The default value is an appropriate value for most configurations. Default value: `389` or `636` when `ldap['encryption']` is set to `:simple_tls`. `ldap['ssl_enabled']` Cause the Chef Infra Server to connect to the LDAP server using SSL. Default value: `false`. Must be `false` when `ldap['tls_enabled']` is `true`. Note It’s recommended that you enable SSL for Active Directory. Note Previous versions of the Chef Infra Server used the `ldap['ssl_enabled']` setting to first enable SSL, and then the `ldap['encryption']` setting to specify the encryption type. These settings are deprecated. `ldap['system_adjective']` A descriptive name for the login system that is displayed to users in the Chef Infra Server management console. If a value like “corporate” is used, then the Chef management console user interface will display strings like “the corporate login server”, “corporate login”, or “corporate password.” Default value: `AD/LDAP`. Warning This setting is **not** used by the Chef Infra Server. It is used only by the Chef management console. `ldap['timeout']` The amount of time (in seconds) to wait before timing out. Default value: `60000`. `ldap['tls_enabled']` Enable TLS. When enabled, communication with the LDAP server is done via a secure SSL connection on a dedicated port. When `true`, `ldap['port']` is also set to `636`. Default value: `false`. Must be `false` when `ldap['ssl_enabled']` is `true`. Note Previous versions of the Chef Infra Server used the `ldap['ssl_enabled']` setting to first enable SSL, and then the `ldap['encryption']` setting to specify the encryption type. These settings are deprecated. ### nginx This configuration file has the following settings for `nginx`: `nginx['cache_max_size']` The `max_size` parameter used by the Nginx cache manager, which is part of the `proxy_cache_path` directive. When the size of file storage exceeds this value, the Nginx cache manager removes the least recently used data. Default value: `5000m`. `nginx['client_max_body_size']` The maximum accepted body size for a client request, as indicated by the `Content-Length` request header. Default value: `250m`. `nginx['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/nginx`. `nginx['enable']` Enable a service. Default value: `true`. `nginx['enable_ipv6']` Enable Internet Protocol version 6 (IPv6) addresses. Default value: `false`. `nginx['enable_non_ssl']` Allow port 80 redirects to port 443. Set to `true`, to enable SSL termination by the front-end hardware load balancers for WebUI and API endpoints. Default value: `false`. Note Chef Infra Server versions earlier than 14.5 configured with `nginx['enable_non_ssl'] = false` and `fips = true` require `export CSC_LB_URL=https://127.0.0.1` to run the command `chef-server-ctl reindex <options>` `nginx['enable_stub_status']` Enables the Nginx `stub_status` module. See `nginx['stub_status']['allow_list']`, `nginx['stub_status']['listen_host']`, `nginx['stub_status']['listen_port']`, and `nginx['stub_status']['location']`. Default value: `true`. `nginx['gzip']` Enable gzip compression. Default value: `on`. `nginx['gzip_comp_level']` The compression level used with gzip, from least amount of compression (`1`, fastest) to the most (`2`, slowest). Default value: `2`. `nginx['gzip_http_version']` Enable gzip depending on the version of the HTTP request. Default value: `1.0`. `nginx['gzip_proxied']` The type of compression used based on the request and response. Default value: `any`. `nginx['gzip_types']` Enable compression for the specified MIME-types. Default value: ``` [ 'text/plain', 'text/css', 'application/x-javascript', 'text/xml', 'application/xml', 'application/xml+rss', 'text/javascript', 'application/json' ] ``` `nginx['keepalive_timeout']` The amount of time (in seconds) to wait for requests on a HTTP keepalive connection. Default value: `65`. `nginx['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/nginx`. `nginx['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `nginx['log_x_forwarded_for']` Log $http_x_forwarded_for (“X-Forwarded-For”) instead of $remote_addr if `true`. Default value `false`. `nginx['non_ssl_port']` The port on which the WebUI and API are bound for non-SSL connections. Default value: `80`. Use `nginx['enable_non_ssl']` to enable or disable SSL redirects on this port number. Set to `false` to disable non-SSL connections. `nginx['sendfile']` Copy data between file descriptors when `sendfile()` is used. Default value: `on`. `nginx['server_name']` The FQDN for the server. Default value: `node['fqdn']`. `nginx['ssl_certificate']` The SSL certificate used to verify communication over HTTPS. Default value: `nil`. `nginx['ssl_certificate_key']` The certificate key used for SSL communication. Default value: `nil`. `nginx['ssl_ciphers']` The list of supported cipher suites that are used to establish a secure connection. To favor AES256 with ECDHE forward security, drop the `RC4-SHA:RC4-MD5:RC4:RSA` prefix. See [this link](https://www.openssl.org/docs/man1.0.2/man1/ciphers.html) for more information. For example: ``` nginx['ssl_ciphers'] = HIGH: ... :!PSK ``` `nginx['ssl_company_name']` The name of your company. Default value: `YouCorp`. `nginx['ssl_country_name']` The country in which your company is located. Default value: `US`. `nginx['ssl_email_address']` The default email address for your company. Default value: `<EMAIL>`. `nginx['ssl_locality_name']` The city in which your company is located. Default value: `Seattle`. `nginx['ssl_organizational_unit_name']` The organization or group within your company that is running the Chef Infra Server. Default value: `Operations`. `nginx['ssl_port']` Default value: `443`. `nginx['ssl_protocols']` The SSL protocol versions that are enabled for the Chef Infra Server API. Starting with Chef Infra Server 14.3, this value defaults to `'TLSv1.2'` for enhanced security. Previous releases defaulted to `'TLSv1 TLSv1.1 TLSv1.2'`, which allowed for less secure SSL connections. TLS 1.2 is supported on Chef Infra Client 10.16.4 and later on Linux, Unix, and macOS, and on Chef Infra Client 12.8 and later on Windows. If it is necessary to support these older end-of-life Chef Infra Client releases, set this value to `'TLSv1.1 TLSv1.2'`. ``` nginx['ssl_protocols'] = 'TLSv1.2' ``` Default value: `TLSv1.2`. `nginx['ssl_state_name']` The state, province, or region in which your company is located. Default value: `WA`. `nginx['strict_host_header']` Whether nginx should only respond to requests where the Host header matches one of the configured FQDNs. Default value: `false`. `nginx['stub_status']['allow_list']` The IP address on which accessing the `stub_status` endpoint is allowed. Default value: `["127.0.0.1"]`. `nginx['stub_status']['listen_host']` The host on which the Nginx `stub_status` module listens. Default value: `"127.0.0.1"`. `nginx['stub_status']['listen_port']` The port on which the Nginx `stub_status` module listens. Default value: `"9999"`. `nginx['stub_status']['location']` The name of the Nginx `stub_status` endpoint used to access data generated by the Nginx `stub_status` module. Default value: `"/nginx_status"`. `nginx['tcp_nodelay']` Enable the Nagle buffering algorithm. Default value: `on`. `nginx['tcp_nopush']` Enable TCP/IP transactions. Default value: `on`. `nginx["time_format"]` The time format of nginx `access.log`. Possible values : `"time_iso8601"` (ex: [2020-10-21T07:22:00+00:00]), `"time_local"` (ex: [07/Jun/2018:01:05:11 +0900]). Default value : `"time_iso8601"`. **New in Chef Infra Server 14.1** `nginx['url']` Default value: `https://#{node['fqdn']}`. `nginx['use_implicit_hosts']` Automatically add localhost and any local IP addresses to the configured FQDNs. Useful in combination with `nginx['strict_host_header']`. Default value: `true`. `nginx['show_welcome_page']` Determines whether or not the default nginx welcome page is shown. Default value: `true`. `nginx['worker_connections']` The maximum number of simultaneous clients. Use with `nginx['worker_processes']` to determine the maximum number of allowed clients. Default value: `10240`. `nginx['worker_processes']` The number of allowed worker processes. Use with `nginx['worker_connections']` to determine the maximum number of allowed clients. Default value: `node['cpu']['total'].to_i`. `nginx['x_forwarded_proto']` The protocol used to connect to the server. Possible values: `http` and `https`. This is the protocol used to connect to the Chef Infra Server by a Chef Infra Client or a workstation. Default value: `'https'`. `nginx['hsts_max_age']` Time duration in seconds till which the browser caches the `HSTS` information. Possible values: greater than or equal to `31536000` and less than or equal to `63072000`. Default value: `31536000` (1 year). `nginx['nginx_no_root']` Boolean, default `false`. Specifies that `nginx` processes, including the `master` process, should not run as the `root` user on a system and will instead run as `user['username']` (defaults to `opscode`). **REQUIRES** that `nginx['ssl_port']` and `nginx['non_ssl_port']` options are configured to non-privileged ports greater than `1024` or that the local system is otherwise allowed to bind to privileged ports with the user `user['username']`. **New in Chef Infra Server 14.10* ### oc_bifrost The **oc_bifrost** service ensures that every request to view or manage objects stored on the Chef Infra Server is authorized. This configuration file has the following settings for `oc_bifrost`: `oc_bifrost['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. This value should be increased if failures indicate that the **oc_bifrost** service ran out of connections. This value should be tuned in conjunction with the `postgresql['max_connections']` setting for PostgreSQL. Default value: `20`. `oc_bifrost['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/oc_bifrost`. `oc_bifrost['enable']` Enable a service. Default value: `true`. `oc_bifrost['enable_request_logging']` Use to configure request logging for the `oc_bifrost` service. Default value: `true`. `oc_bifrost['extended_perf_log']` Default value: `true`. `oc_bifrost['listen']` The IP address on which the service is to listen. Default value: `'127.0.0.1'`. `oc_bifrost['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/oc_bifrost`. `oc_bifrost['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `oc_bifrost['port']` The port on which the service is to listen. Default value: `9463`. `oc_bifrost['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `oc_bifrost['sql_user']` (default: `'bifrost'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_bifrost['sql_user']`. Default value: `nil`. `oc_bifrost['sql_password']` The password for the `sql_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_bifrost sql_password`. `oc_bifrost['sql_ro_password']` The password for the `sql_ro_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_bifrost sql_ro_password`. `oc_bifrost['sql_ro_user']` Default value: `'bifrost_ro'`. `oc_bifrost['sql_user']` The user with permission to publish data. Default value: `'bifrost'`. `oc_bifrost['superuser_id']` Default value: **generated**. `oc_bifrost['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### oc_chef_authz The **opscode-authz** service is used to handle authorization requests from oc_erchef to oc_bifrost in the Chef Infra Server. This configuration file has the following settings for `oc_chef_authz`: `oc_chef_authz['http_cull_interval']` Default value: `'{1, min}'`. `oc_chef_authz['http_init_count']` Default value: `25`. `oc_chef_authz['http_max_age']` Default value: `'{70, sec}'`. `oc_chef_authz['http_max_connection_duration']` Default value: `'{70, sec}'`. `oc_chef_authz['http_max_count']` Default value: `100`. `oc_chef_authz['ibrowse_options']` The amount of time (in milliseconds) to wait for a connection to be established. Default value: `'[{connect_timeout, 5000}]'`. `oc_chef_authz['max_connection_request_limit']` The maximum number of requests allowed per connection. Default value: `100`. ### oc-chef-pedant This configuration file has the following settings for `oc-chef-pedant`: `oc_chef_pedant['debug_org_creation']` Run tests with full output. Default value: `false`. `oc_chef_pedant['dir']` The working directory. The default value is the recommended value. Default value: ``` '/var/opt/opscode/oc-chef-pedant' ``` `oc_chef_pedant['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` '/var/log/opscode/oc-chef-pedant' ``` `oc_chef_pedant['log_http_requests']` Log HTTP requests in a file named `http-traffic.log` that is located in the path specified by `log_directory`. Default value: `true`. `oc_chef_pedant['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` ### oc-id The **oc-id** service enables OAuth 2.0 authentication to the Chef Infra Server by external applications, including Chef Supermarket. OAuth 2.0 uses token-based authentication, where external applications use tokens that are issued by the **oc-id** provider. No special credentials—`webui_priv.pem` or privileged keys—are stored on the external application. This configuration file has the following settings for `oc-id`: `oc_id['administrators']` An array of Chef Infra Server user names who may add applications to the identity service. For example, `['user1', 'user2']`. Default value: `[ ]`. `oc_id['applications']` A Hash that contains OAuth 2 application information. Default value: `{ }`. To define OAuth 2 information for Chef Supermarket, create a Hash similar to: ``` oc_id['applications'] ||= {} oc_id['applications']['supermarket'] = { 'redirect_uri' => 'https://supermarket.mycompany.com/auth/chef_oauth2/callback', } ``` `oc_id['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `'20'`. `oc_id['dir']` The working directory. The default value is the recommended value. Default value: none. `oc_id['enable']` Enable a service. Default value: `true`. `oc_id['email_from_address']` Outbound email address. Defaults to the `'from_email'` value. `oc_id['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/opt/opscode/oc_id'`. `oc_id['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `oc_id['origin']` The FQDN for the server that is sending outbound email. Defaults to the `'api_fqdn'` value, which is the FQDN for the Chef Infra Server. `oc_id['num_to_keep']` The number of log files to keep. Default value: `10`. `oc_id['port']` The port on which the service is to listen. Default value: `9090`. `oc_id['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `oc_id['sql_user']` (default: `'od_id'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_id['sql_user']`. Default value: `nil`. `oc_id['sql_database']` The name of the database. Default value: `oc_id`. `oc_id['sql_password']` The password for the `sql_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_id sql_password`. `oc_id['sql_user']` The user with permission to write to `sql_database`. Default value: `oc_id`. `oc_id['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### opscode-chef-mover This configuration file has the following settings for `opscode-chef-mover`: `opscode_chef_mover['bulk_fetch_batch_size']` Default value: `'5'`. `opscode_chef_mover['cache_ttl']` Default value: `'3600'`. `opscode_chef_mover['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `'5'`. `opscode_chef_mover['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: ``` '/var/opt/opscode/opscode-chef-mover/data' ``` `opscode_chef_mover['dir']` The working directory. The default value is the recommended value. Default value: ``` '/var/opt/opscode/opscode-chef-mover' ``` `opscode_chef_mover['enable']` Enable a service. Default value: `true`. `opscode_chef_mover['ibrowse_max_pipeline_size']` Default value: `1`. `opscode_chef_mover['ibrowse_max_sessions']` Default value: `256`. `opscode_chef_mover['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` '/var/log/opscode/opscode-chef-mover' ``` `opscode_chef_mover['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_chef_mover['max_cache_size']` Default value: `'10000'`. `opscode_chef_mover['solr_http_cull_interval']` Default value: `'{1, min}'`. `opscode_chef_mover['solr_http_init_count']` Default value: `25`. `opscode_chef_mover['solr_http_max_age']` Default value: `'{70, sec}'`. `opscode_chef_mover['solr_http_max_connection_duration']` Default value: `'{70, sec}'`. `opscode_chef_mover['solr_http_max_count']` Default value: `100`. `opscode_chef_mover['solr_ibrowse_options']` Default value: `'[{connect_timeout, 10000}]'`. `opscode_chef_mover['solr_timeout']` Default value: `30000`. ### opscode-erchef The **opscode-erchef** service is an Erlang-based service that is used to handle Chef Infra Server API requests to the following areas within the Chef Infra Server: * Cookbooks * Data bags * Environments * Nodes * Roles * Sandboxes * Search This configuration file has the following settings for `opscode-erchef`: `opscode_erchef["allow_email_update_only_from_manage"]` Set to `true`, users can only update their email from the Chef management console. Set to `false`, users can update their email using knife and the Chef management console. Default value : `false`. **New in Chef Infra Server 14.5** `opscode_erchef['auth_skew']` Default value: `900`. `opscode_erchef['authz_fanout']` Default value: `20`. `opscode_erchef['authz_timeout']` The amount of time (in seconds) before a request to the **oc_bifrost** service times out. Default value: `2000`. `opscode_erchef['base_resource_url']` The base URL to which the service is to return links to API resources. Use `:host_header` to ensure the URL is derived from the host header of the incoming HTTP request. Default value: `:host_header`. `opscode_erchef['bulk_fetch_batch_size']` The number of nodes that may be deserialized. Currently only applies to the `/search` endpoint in the Chef Infra Server API. The default value is the recommended value. Default value: `5`. `opscode_erchef['cache_ttl']` Default value: `3600`. `opscode_erchef['cleanup_batch_size']` Default value: `0`. `opscode_erchef['couchdb_max_conn']` Default value: `'100'`. `opscode_erchef['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `20`. `opscode_erchef['depsolver_timeout']` The amount of time (in milliseconds) to wait for cookbook dependency problems to be solved. Default value: `'5000'`. `opscode_erchef['depsolver_worker_count']` The number of Ruby processes for which cookbook dependency problems are unsolved. Use the `pgrep -fl depselector` command to verify the number of depsolver workers that are running. If you are seeing 503 service unavailable errors, increase this value. Default value: `'5'`. `opscode_erchef['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/opscode-erchef`. `opscode_erchef['enable']` Enable a service. Default value: `true`. `opscode_erchef['enable_actionlog']` Use to enable Chef actions, a premium feature of the Chef Infra Server. Default value: `false`. `opscode_erchef['enable_request_logging']` Use to configure request logging for the `opscode_erchef` service. Default value: `true`. `opscode_erchef['ibrowse_max_pipeline_size']` Default value: `1`. `opscode_erchef['ibrowse_max_sessions']` Default value: `256`. `opscode_erchef['enable_ibrowse_traces']` Use to configure ibrowse logging for the `opscode_erchef` service. Default value: `false`. `opscode_erchef["include_version_in_status"]` Set to `true` to include `server_version` as part of the `/_status` endpoint. Default value : `false`. **New in Chef Infra Server 14.1** `opscode_erchef['listen']` The IP address on which the service is to listen. Default value: `127.0.0.1`. `opscode_erchef['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/opscode-erchef`. `opscode_erchef['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_erchef['max_cache_size']` Default value: `10000`. `opscode_erchef['max_request_size']` When the request body size is greater than this value, a `413 Request Entity Too Large` error is returned. Default value: `2000000`. `opscode_erchef['nginx_bookshelf_caching']` Whether Nginx is used to cache cookbooks. When `:on`, Nginx serves up the cached content instead of forwarding the request. Default value: `:off`. `opscode_erchef['port']` The port on which the service is to listen. Default value: `8000`. `opscode_erchef['reindex_batch_size']` The number of items to fetch from the database and send to the search index at a time. Default value: `10`. `opscode_erchef['reindex_sleep_min_ms']` The minimum number of milliseconds to sleep before retrying a failed attempt to index an item. Retries are delayed a random number of miliseconds between `reindex_sleep_min_ms` and `reindex_sleep_max_ms`. Set both this and `reindex_sleep_max_ms` to 0 to retry without delay. Default value: `500` `opscode_erchef['reindex_sleep_max_ms']` The maximum number of milliseconds to sleep before retrying a failed attempt to index an item. Retries are delayed a random number of miliseconds between `reindex_sleep_min_ms` and `reindex_sleep_max_ms`. Set both this and `reindex_sleep_min_ms` to 0 to retry without delay. Default value: `2000` `opscode_erchef['reindex_item_retries']` The number of times to retry sending an object for indexing in the case of failure. Default value: `3` `opscode_erchef['root_metric_key']` Default value: `chefAPI`. `opscode_erchef['s3_bucket']` The name of the Amazon Simple Storage Service (S3) bucket. This may point at external storage locations, such as Amazon EC2. See [AWS external bookshelf settings](../server/index#aws-settings) for more information on configuring external bookshelf. `opscode_erchef['s3_parallel_ops_fanout']` Default value: `20`. `opscode_erchef['s3_parallel_ops_timeout']` Default value: `5000`. `opscode_erchef['s3_url_expiry_window_size']` The frequency at which unique URLs are generated. This value may be a specific amount of time, i.e. `15m` (fifteen minutes) or a percentage of the value of `s3_url_ttl`, i.e. `10%`. Default value: `:off`. `opscode_erchef['s3_url_ttl']` The amount of time (in seconds) before connections to the server expire. If node bootstraps are timing out, increase this setting. Default value: `28800`. `opscode_erchef['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `opscode-erchef['sql_user']` (default: `'opscode_chef'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `opscode_erchef['sql_user']`.Default value: `nil`. `opscode_erchef['strict_search_result_acls']` Use to specify that search results only return objects to which an actor (user, client, etc.) has read access, as determined by ACL settings. This affects all searches. When `true`, the performance of the Chef management console may increase because it enables the Chef management console to skip redundant ACL checks. To ensure the Chef management console is configured properly, after this setting has been applied with a `chef-server-ctl reconfigure` run `chef-manage-ctl reconfigure` to ensure the Chef management console also picks up the setting. Default value: `false`. Warning When `true`, `opscode_erchef['strict_search_result_acls']` affects all search results and any actor (user, client, etc.) that does not have read access to a search result will not be able to view it. For example, this could affect search results returned during a Chef Infra Client runs if a Chef Infra Client does not have permission to read the information. `opscode_erchef['udp_socket_pool_size']` Default value: `20`. `opscode_erchef['umask']` Default value: `0022`. `opscode_erchef['validation_client_name']` Default value: `chef-validator`. `opscode_erchef['vip']` The virtual IP address. Default value: `127.0.0.1`. `opscode_erchef['cbv_cache_enabled']` Enable cookbook version response caching by setting this to `true`. If you frequently see very long response times from `cookbook_versions` when under load, this is worth enabling. Enabling this makes it possible for a client to receive stale results. When a cookbook is updated in place (without incrementing the version), and the old response has not expired from the cache, the Infra Server will give the old response to the client. Subsequent client runs will receive the updated response. Default value: `false`. `opscode_erchef['cbv_cache_item_ttl']` The minimum time in milliseconds that Chef Infra Server will keep any given cookbook version response in the cache when when `cbv_cache_enabled` is enabled. Default value: `30000`. Note Be careful if increasing this number - requests for a given set of cookbook versions will be stale if the resolved cookbook versions are updated before the cache entry times out. This will not occur if you increment the version of a cookbook with every cookbook update, which is the recommended approach to updating cookbooks. ### Elasticsearch This configuration file has the following settings for `elasticsearch`: `elasticsearch['enable']` Enable a service. Default value: `true`. `elasticsearch['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/elasticsearch` `elasticsearch['data_dir']` :The paths used to store data. Default value: `/var/opt/opscode/elasticsearch/data` `elasticsearch['plugins_directory']` The default location of the plugins directory depends on which package you install. Default value: `/var/opt/opscode/elasticsearch/plugins` `elasticsearch['scripts_directory']` :The default location of the scripts directory depends on which package you install. Default value: `/var/opt/opscode/elasticsearch/scripts` `elasticsearch['temp_directory']` By default, Elasticsearch uses a private temporary directory that the startup script creates immediately below the system temporary directory. Default value: `/var/opt/opscode/elasticsearch/tmp` `elasticsearch['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/elasticsearch` `elasticsearch['log_rotation']['file_maxbytes']` The log rotation policy for this service. Log files are rotated when they exceed file_maxbytes. Default value for ‘file_maxbytes’: `104857600` `elasticsearch['log_rotation']['num_to_keep']` The log rotation policy for this service. The maximum number of log files in the rotation is defined by num_to_keep. Default value for ‘num_to_keep’: => `10` `elasticsearch['vip']` The virtual IP address for the machine on which Apache Solr is running. Default value: `127.0.0.1` `elasticsearch['listen']` The IP address for the machine on which Apache Solr is running. Default value: `127.0.0.1` `elasticsearch['port']` The port on which the service is to listen. Default value: `9200` `elasticsearch['enable_gc_log']` Enable or disable GC logging. Default value: `false` `elasticsearch['initial_cluster_join_timeout']` Default value: `90` `elasticsearch['jvm_opts']` Default values are set based on [JVM configuration options](https://github.com/elastic/elasticsearch/blob/6.8/distribution/src/config/jvm.options). Note Each item in this list will be placed as is into the java_opts config file. Entries are set in chef-server.rb as: ``` elasticsearch.jvm_opts = [ "-xoption1", "-xoption2", ... "optionN" ] ``` `elasticsearch['heap_size']` The amount of memory (in MBs) available to Elasticsearch. If there is not enough memory available, search queries made by nodes to Elasticsearch may fail. The amount of memory that must be available also depends on the number of nodes in the organization, the frequency of search queries, and other characteristics that are unique to each organization. In general, as the number of nodes increases, so does the amount of memory. The default value should work for many organizations with fewer than 25 nodes. For an organization with several hundred nodes, the amount of memory that is required often exceeds 3GB. Default value is is equivalent to 25% of the system memory or 1024 MB, whichever is greater. Note If new_size or heap_size is also specified directly in java_opts, it will be ignored in favor of the chef-server.rb values or the defaults as calculated here. Only use chef-server.rb to set heap and new sizes. Learn more about [Elasticsearch heap-size](https://www.elastic.co/guide/en/elasticsearch/reference/current/heap-size.html). It will error out if the system memory is less than 4 GB. This value is bounded between 1 GB - 28 GB. `elasticsearch['new_size']` Defaults to the larger of 1/16th the heap_size and 32 MB. Note If new_size or heap_size is also specified directly in java_opts, it will be ignored in favor of the chef-server.rb values or the defaults as calculated here. Only use chef-server.rb to set heap and new sizes. Learn more about [Elasticsearch heap-size documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/heap-size.html). ### postgresql The **postgresql** service is used to store node, object, and user data. This configuration file has the following settings for `postgresql`: `postgresql['checkpoint_completion_target']` A completion percentage that is used to determine how quickly a checkpoint should finish in relation to the completion status of the next checkpoint. For example, if the value is `0.5`, then a checkpoint attempts to finish before 50% of the next checkpoint is done. Default value: `0.5`. `postgresql['checkpoint_segments']` The maximum amount (in megabytes) between checkpoints in log file segments. Default value: `3`. `postgresql['checkpoint_timeout']` The amount of time (in minutes) between checkpoints. Default value: `5min`. `postgresql['checkpoint_warning']` The frequency (in seconds) at which messages are sent to the server log files if checkpoint segments are being filled faster than their currently configured values. Default value: `30s`. `postgresql['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `/var/opt/opscode/postgresql/#{node['private_chef']['postgresql']['version']}/data`. `postgresql['db_connection_superuser']` The PostgreSQL superuser name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `postgresql['db_superuser']` with any dashes replaced by underscores. This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `postgresql['db_superuser']`. Default value: `nil`. `postgresql['db_superuser']` Default value: `opscode-pgsql`. If `username` is set, set `db_superuser` to the same value. `postgresql['db_superuser_password']` Password for the DB superuser. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-db-superuser-password`. `postgresql['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/postgresql/#{node['private_chef']['postgresql']['version']}`. `postgresql['effective_cache_size']` The size of the disk cache that is used for data files. Default value: 50% of available RAM. `postgresql['enable']` Enable a service. Default value: `true`. `postgresql['home']` The home directory for PostgreSQL. Default value: `/var/opt/opscode/postgresql`. `postgresql['keepalives_count']` The maximum number of keepalive proves that should be sent before dropping a connection. Default value: `2`. `postgresql['keepalives_idle']` The amount of time (in seconds) a connection must remain idle before keepalive probes will resume. Default value: `60`. `postgresql['keepalives_interval']` The amount of time (in seconds) between probes. Default value: `15`. `postgresql['listen_address']` The connection source to which PostgreSQL is to respond. Default value: `localhost`. `postgresql['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/postgresql/#{node['private_chef']['postgresql']['version']}`. `postgresql['log_min_duration_statement']` When to log a slow PostgreSQL query statement. Possible values: `-1` (disabled, do not log any statements), `0` (log every statement), or an integer greater than zero. When the integer is greater than zero, this value is the amount of time (in milliseconds) that a query statement must have run before it is logged. Default value: `-1`. `postgresql['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `postgresql['max_connections']` The maximum number of allowed concurrent connections. Default value: `350`. `postgresql['md5_auth_cidr_addresses']` Use instead of `trust_auth_cidr_addresses` to encrypt passwords using MD5 hashes. Default value: `[ '127.0.0.1/32', '::1/128' ]`. `postgresql['port']` The port on which the service is to listen. Default value: `5432`. `postgresql['shared_buffers']` The amount of memory that is dedicated to PostgreSQL for data caching. Default value: `#{(node['memory']['total'].to_i / 4) / (1024)}MB`. `postgresql['shell']` Default value: `/bin/sh`. `postgresql['shmall']` The total amount of available shared memory. Default value: `4194304`. `postgresql['shmmax']` The maximum amount of shared memory. Default value: `17179869184`. `postgresql['sslmode']` SSL encryption mode between the Chef Infra Server and PostgreSQL. Valid settings are `'disable'` and `'require'`. Default value: `'disable'`. `postgresql['trust_auth_cidr_addresses']` Use for clear-text passwords. See `md5_auth_cidr_addresses`. Default value: `'127.0.0.1/32', '::1/128'`. `postgresql['user_path']` Default value: `/opt/opscode/embedded/bin:/opt/opscode/bin:$PATH`. `postgresql['username']` The PostgreSQL account user name. Default value: `opscode-pgsql`. If setting this value, must set `db_superuser` to the same value. `postgresql['version']` The (currently) hardcoded version of PostgreSQL. Default value: `'9.2'`. `postgresql['vip']` The virtual IP address. Default value: `127.0.0.1`. `postgresql['work_mem']` The size (in megabytes) of allowed in-memory sorting. Default value: `8MB`. `postgresql['pg_upgrade_timeout']` The timeout value (in seconds) for PostgreSQL upgrade. Default value: `7200`. ### redis_lb Key-value store used in conjunction with Nginx to route requests and populate request data used by the Chef Infra Server. This configuration file has the following settings for `redis_lb`: `redis_lb['activerehashing']` Enable active rehashing. Default value: `'no'`. `redis_lb['aof_rewrite_min_size']` The minimum size of the append-only file. Only files larger than this value are rewritten. Default value: `'16mb'`. `redis_lb['aof_rewrite_percent']` The size of the current append-only file, as compared to the base size. The append-only file is rewritten when the current file exceeds the base size by this value. Default value: `'50'`. `redis_lb['appendfsync']` The frequency at which the operating system writes data on-disk, instead of waiting for more data. Possible values: `no` (don’t fsync, let operating system flush data), `always` (fsync after every write to the append-only log file), and `everysec` (fsync only once time per second). Default value: `'always'`. `redis_lb['appendonly']` Dump data asynchronously on-disk or to an append-only log file. Set to `yes` to dump data to an append-only log file. Default value: `'no'`. `redis_lb['bind']` Bind Redis to the specified IP address. Default value: `'127.0.0.1'`. `redis_lb['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `'/var/opt/opscode/redis_lb/data'`. `redis_lb['databases']` The number of databases. Default value: `'16'`. `redis_lb['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/redis_lb'`. `redis_lb['enable']` Enable a service. Default value: `true`. `redis_lb['ha']` Run the Chef Infra Server in a high availability topology. When `topology` is set to `ha`, this setting defaults to `true`. Default value: `false`. `redis_lb['keepalive']` The amount of time (in seconds) to wait for requests on a connection. Default value: `'60'`. `redis_lb['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/log/opscode/redis_lb'`. `redis_lb['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `redis_lb['loglevel']` The level of logging to be stored in a log file.. Possible values: `debug`, `notice`, `verbose`, and `warning`. Default value: `'notice'`. `redis_lb['maxmemory']` The maximum amount of memory (in bytes). Default value: `'8m'`. `redis_lb['maxmemory_policy']` The policy applied when the maximum amount of memory is reached. Possible values: `allkeys-lru` (remove keys, starting with those used least frequently), `allkeys-random` (remove keys randomly), `noeviction` (don’t expire, return an error on write operation), `volatile-lru` (remove expired keys, starting with those used least frequently), `volatile-random` (remove expired keys randomly), and `volatile-ttl` (remove keys, starting with nearest expired time). Default value: `'noeviction'`. `redis_lb['port']` The port on which the service is to listen. Default value: `'16379'`. `redis_lb['save_frequency']` Set the save frequency. Pattern: `{ "seconds" => "keys", "seconds" => "keys", "seconds" => "keys" }`. Default value: ``` { '900' => '1', '300' => '10', '60' => '1000' } ``` Which saves the database every 15 minutes if at least one key changes, every 5 minutes if at least 10 keys change, and every 60 seconds if 10000 keys change. `redis_lb['timeout']` The amount of time (in seconds) a client may be idle before timeout. Default value: `'300'`. `redis_lb['vip']` The virtual IP address. Default value: `'127.0.0.1'`. `redis_lb['password']` Legacy configuration setting for the Redis password. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret redis_lb password`. ### upgrades This configuration file has the following settings for `upgrades`: `upgrades['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/upgrades'`. ### user This configuration file has the following settings for `user`: `user['home']` The home directory for the user under which Chef Infra Server services run. Default value: `/opt/opscode/embedded`. `user['shell']` The shell for the user under which Chef Infra Server services run. Default value: `/bin/sh`. `user['username']` The user name under which Chef Infra Server services run. Default value: `opscode`. ### required_recipe `required_recipe` is a feature that allows an administrator to specify a recipe that will be run by all Chef Infra Clients that connect to it, regardless of the node’s run list. This feature is targeted at expert level practitioners who are delivering isolated configuration changes to the target systems, such as self-contained agent software. Further explanation of the feature can be found in [Chef Infra Client Development Docs](https://github.com/chef/chef/blob/main/docs/dev/design_documents/server_enforced_recipes.md). This configuration file has the following settings for `required_recipe`: `required_recipe["enable"]` Whether the feature is enabled. Default value: `false`. `required_recipe["path"]` The location of the recipe to serve. The file must be owned by the root user and group, and may not be group or world-writeable. Default value: `nil`. **Note:** You are viewing documentation for an older version of Chef Infra Server. [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/v13_2/config_rb_server_optional_settings.md) The `/etc/opscode/chef-server.rb` file contains all of the non-default configuration settings used by the Chef Infra Server. The default settings are built into the Chef Infra Server configuration and should only be added to the `chef-server.rb` file to apply non-default values. These configuration settings are processed when the `chef-server-ctl reconfigure` command is run. The `chef-server.rb` file is a Ruby file, which means that conditional statements can be used within it. Settings -------- The following sections describe the various settings that are available in the chef-server.rb file. Note When changes are made to the chef-server.rb file the Chef Infra Server must be reconfigured by running the following command: ``` chef-server-ctl reconfigure ``` ### General This configuration file has the following general settings: `addons['install']` Default value: `false`. `addons['path']` Default value: `nil`. `addons['packages']` Default value: ``` %w{chef-manage} ``` `api_version` The version of the Chef Infra Server. Default value: `'12.0.0'`. `default_orgname` The `ORG_NAME` part of the `/organizations` endpoint in Chef Infra Server. `flavor` Default value: `'cs'`. `fips` Set to `true` to run the server in FIPS compliance mode. Set to `false` to force the server to run without FIPS compliance mode. Default: The kernel configuration FIPS value. Note Chef Infra Server versions earlier than 14.5 that are configured with `nginx['enable_non_ssl'] = false` and `fips = true` require `export CSC_LB_URL=https://127.0.0.1` to run the command `chef-server-ctl reindex <options>` `insecure_addon_compat` Set to `true` to keep Chef Infra Server compatible with older add-on versions by rendering secrets and credentials to `/etc/opscode/chef-server-running.json` and other files in `/etc/opscode/`. When set to `false`, secrets are **only** written to `/etc/opscode/private-chef-secrets.json` and **not** to any other files. Default value: `true`. See [Add-on Compatibility](../server/server_security/index#add-on-compatibility) for the minimum add-on versions supporting `insecure_addon_compat false`. `install_path` The directory in which the Chef Infra Server is installed. Default value: `'/opt/opscode'`. `from_email` The email address from which invitations to the Chef management console are sent. Default value: `'"Opscode" <<EMAIL>>'`. `license['nodes']` The number of licensed nodes. Default value: `25`. `license['upgrade_url']` The URL to visit for more information about how to update the number of nodes licensed for an organization. Default value: `https://www.chef.io/pricing'`. `notification_email` The email addressed to which email notifications are sent. Default value: `'<EMAIL>'`. `role` The configuration type of the Chef Infra Server. Possible values: `backend`, `frontend`, or `standalone`. Default value: `'standalone'`. `topology` The topology of the Chef Infra Server. Possible values: `manual`, `standalone`, and `tier`. Default value: `'standalone'`. ### bookshelf The **bookshelf** service is an Amazon Simple Storage Service (S3)-compatible service that is used to store cookbooks, including all of the files—recipes, templates, and so on—that are associated with each cookbook. Note To [configure the server for external cookbook storage](../server/index#aws-settings), updates are made to settings for both the **bookshelf** and **opscode-erchef** services. This configuration file has the following settings for `bookshelf`: `bookshelf['access_key_id']` Deprecated. Use `chef-server-ctl set-secret bookshelf access_key_id` from the [Secrets Management](../server/ctl_chef_server/index#secrets-management) commands. The access key identifier. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../server/index#aws-settings) for more information on configuring external bookshelf. Default value: **generated**. `bookshelf['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `/var/opt/opscode/bookshelf/data`. `bookshelf['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/bookshelf`. `bookshelf['enable']` Enable a service. Default value: `true`. `bookshelf['enable_request_logging']` Use to configure request logging for the bookshelf service. Default value: `false`. `bookshelf['external_url']` The base URL to which the service is to return links to API resources. Use `:host_header` to ensure the URL is derived from the host header of the incoming HTTP request. Default value: `:host_header`. `bookshelf['listen']` The IP address on which the service is to listen. Default value: `127.0.0.1`. `bookshelf['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/bookshelf`. `bookshelf['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `bookshelf['port']` The port on which the service is to listen. Default value: `4321`. `bookshelf['secret_access_key']` Deprecated. Use `chef-server-ctl set-secret bookshelf secret_access_key` from the [Secrets Management](../server/ctl_chef_server/index#secrets-management) commands. The secret key. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../server/index#aws-settings) for more information on configuring external bookshelf. Default value: **generated**. `bookshelf['storage_type']` Determines where cookbooks are stored. Default value: `:filesystem`. In instances that require cookbooks to be stored within a SQL backend, such as in a high availability setup, you must set `storage_type` to `:sql`: ``` bookshelf['storage_type'] = :sql ``` `bookshelf['stream_download']` Enable stream downloading of cookbooks. This setting (when `true`) typically results in improved cookbook download performance, especially with the memory usage of the **bookshelf** service and the behavior of load balancers and proxies in-between Chef Infra Client and the Chef Infra Server. Default value: `true`. `bookshelf['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>@my_<EMAIL>'`), where `username` would normally equal the value of `bookshelf['sql_user']` (default: `'bookshelf'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `bookshelf['sql_user']`. Default value: `nil`. `bookshelf['vip']` The virtual IP address. This may point at an external storage location, such as Amazon EC2. See [AWS external bookshelf settings](../server/index#aws-settings) for more information on configuring external bookshelf. Default value: `127.0.0.1`. ### bootstrap This configuration file has the following settings for `bootstrap`: `bootstrap['enable']` Indicates whether an attempt to bootstrap the Chef Infra Server is made. Generally only enabled on systems that have bootstrap enabled via a `server` entry. Default value: `true`. ### compliance forwarding The configuration file has the following settings for forwarding `compliance` requests using the chef server authentication system. `profiles['root_url']` If set, any properly signed requests arriving at `/organizations/ORGNAME/owners/OWNER/compliance` will be forwarded to this URL. This is expected to be a fully qualified resource, e.g. `http://compliance.example.org/owners/OWNER/compliance`. ### dark_launch This configuration file has the following settings for `dark_launch`: `dark_launch['actions']` Enable Chef actions. Default value: `true`. `dark_launch['add_type_and_bag_to_items']` Default value: `true`. `dark_launch['new_theme']` Default value: `true`. `dark_launch['private-chef']` Default value: `true`. `dark_launch['quick_start']` Default value: `false`. `dark_launch['reporting']` Enable Reporting, which performs data collection during a Chef Infra Client run. Default value: `true`. `dark_launch['sql_users']` Default value: `true`. ### data_collector This configuration file has the following settings for `data_collector`: `data_collector['root_url']` The fully qualified URL to the data collector server API. When present, it will enable the data collector in **opscode-erchef**. This also enables Chef Infra Server authenticated forwarding any properly signed requests arriving at `/organizations/ORGNAME/data-collector` to this URL with the data collector token appended. This is also target for requests authenticated and forwarded by the `/organizations/ORGNAME/data-collector` endpoint. For the forwarding to work correctly the `data_collector['token']` field must also be set. For example, if the data collector in Chef Automate is being used, the URI would look like: `http://my_automate_server.example.org/data-collector/v0/`. `data_collector['proxy']` If set to `true`, Chef Infra Server will proxy all requests sent to `/data-collector` to the configured Chef Automate `data_collector['root_url']`. Note that *this route* does not check the request signature and add the right data_collector token, but just proxies the Automate endpoint **as-is**. Default value: `nil`. `data_collector['token']` Deprecated. Use `chef-server-ctl set-secret data_collector token` from the [Secrets Management](../server/ctl_chef_server/index#secrets-management) commands. Legacy configuration for shared data collector security token. When configured, the token will be passed as an HTTP header named `x-data-collector-token` which the server can choose to accept or reject. `data_collector['timeout']` The amount of time (in milliseconds) before a request to the data collector API times out. Default value: 30000. `data_collector['http_init_count']` The initial worker count for the HTTP connection pool that is used by the data collector. Default value: 25. `data_collector['http_max_count']` The maximum worker count for the HTTP connection pool that is used by the data collector. Default value: 100. `data_collector['http_max_age']` The maximum connection worker age (in seconds) for the HTTP connection pool that is used by the data collector. Default value: "{70, sec}". `data_collector['http_cull_interval']` The maximum cull interval (in minutes) for the HTTP connection pool that is used by the data collector. Default value: "{1, min}". `data_collector['http_max_connection_duration']` The maximum connection duration (in seconds) for the HTTP connection pool that is used by the data collector. Default value: "{70, sec}". `data_collector['ibrowse_options']` An array of comma-separated key-value pairs of ibrowse options for the HTTP connection pool that is used by the data collector. Default value: "[{connect_timeout, 10000}]". `data_collector['health_check']` A boolean that controls whether the data collector health is included in the overall health at the `_status` endpoint. When set to `true`, Chef Infra Server will report that healthy front end Chef HA cluster members have failed when the data_collector[‘root_url’] cannot be reached. As a result, the load balancer will remove those members from the load balancer pool. Default value: true`. ### estatsd This configuration file has the following settings for `estatsd`: `estatsd['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/estatsd'`. `estatsd['enable']` Enable a service. Default value: `true`. `estatsd['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/log/opscode/estatsd'`. `estatsd['port']` The port on which the service is to listen. Default value: `9466`. `estatsd['protocol']` Use to send application statistics with StatsD protocol formatting. Set this value to `statsd` to apply StatsD protocol formatting. `estatsd['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### jetty This configuration file has the following settings for `jetty`: `jetty['enable']` Enable a service. Default value: `'false'`. This value should not be modified. `jetty['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` '/var/opt/opscode/opscode-solr4/jetty/logs' ``` ### lb / lb_internal This configuration file has the following settings for `lb`: `lb['api_fqdn']` Default value: `node['fqdn']`. `lb['ban_refresh_interval']` Default value: `600`. `lb['bookshelf']` Default value: `127.0.0.1`. `lb['cache_cookbook_files']` Default value: `false`. `lb['chef_max_version']` The maximum version of Chef Infra Client that is allowed to access the Chef Infra Server via the Chef Infra Server API. Default value: `11`. `lb['chef_min_version']` The minimum version of Chef Infra Client that is allowed to access the Chef Infra Server via the Chef Infra Server API. Default value: `10`. `lb['chef_server_webui']` Default value: `127.0.0.1`. `lb['debug']` Default value: `false`. `lb['enable']` Enable a service. Default value: `true`. `lb['erchef']` Default value: `127.0.0.1`. `lb['maint_refresh_interval']` Default value: `600`. `lb['redis_connection_pool_size']` Default value: `250`. `lb['redis_connection_timeout']` The amount of time (in milliseconds) to wait before timing out. Default value: `1000`. `lb['redis_keepalive_timeout']` The amount of time (in milliseconds) to wait before timing out. Default value: `2000`. `lb['upstream']['bookshelf']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['oc_bifrost']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['opscode_erchef']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['upstream']['opscode_solr4']` The default value is the recommended value. Default value: `[ '127.0.0.1' ]`. `lb['vip']` The virtual IP address. Default value: `127.0.0.1`. `lb['web_ui_fqdn']` Default value: `node['fqdn']`. `lb['xdl_defaults']['503_mode']` The default value is the recommended value. Default value: `false`. `lb['xdl_defaults']['couchdb_acls']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_association_requests']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_associations']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_containers']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_groups']` The default value is the recommended value. Default value: `true`. `lb['xdl_defaults']['couchdb_organizations']` The default value is the recommended value. Default value: `true`. And for the internal load balancers: `lb_internal['account_port']` Default value: `9685`. `lb_internal['chef_port']` Default value: `9680`. `lb_internal['enable']` Default value: `true`. `lb_internal['oc_bifrost_port']` Default value: `9683`. `lb_internal['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### ldap Warning The following settings **MUST** be in the config file for LDAP authentication to Active Directory to work: * `base_dn` * `bind_dn` * `group_dn` * `host` If those settings are missing, you will get authentication errors and be unable to proceed. This configuration file has the following settings for `ldap`: `ldap['base_dn']` The root LDAP node under which all other nodes exist in the directory structure. For Active Directory, this is typically `cn=users` and then the domain. For example: ``` 'OU=Employees,OU=Domain users,DC=example,DC=com' ``` Default value: `nil`. `ldap['bind_dn']` The distinguished name used to bind to the LDAP server. The user the Chef Infra Server will use to perform LDAP searches. This is often the administrator or manager user. This user needs to have read access to all LDAP users that require authentication. The Chef Infra Server must do an LDAP search before any user can log in. Many Active Directory and LDAP systems do not allow an anonymous bind. If anonymous bind is allowed, leave the `bind_dn` and `bind_password` settings blank. If anonymous bind is not allowed, a user with `READ` access to the directory is required. This user must be specified as an LDAP distinguished name similar to: ``` 'CN=user,OU=Employees,OU=Domainuser,DC=example,DC=com' ``` Note If you need to escape characters in a distinguished name, such as when using Active Directory, they must be [escaped with a backslash escape character](https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx). ``` 'CN=example\\user,OU=Employees,OU=Domainuser,DC=example,DC=com' ``` Default value: `nil`. `ldap['bind_password']` Deprecated. Use `chef-server-ctl set-secret ldap bind_password` from the [Secrets Management](../ctl_chef_server#ctl-chef-server-secrets-management) commands. Legacy configuration for the password of the binding user. The password for the user specified by `ldap['bind_dn']`. Leave this value and `ldap['bind_dn']` unset if anonymous bind is sufficient. Default value: `nil`. ``` chef-server-ctl set-secret ldap bind_password Enter ldap bind_password: (no terminal output) Re-enter ldap bind_password: (no terminal output) ``` Remove a set password via ``` chef-server-ctl remove-secret ldap bind_password ``` `ldap['group_dn']` The distinguished name for a group. When set to the distinguished name of a group, only members of that group can log in. This feature filters based on the `memberOf` attribute and only works with LDAP servers that provide such an attribute. In OpenLDAP, the `memberOf` overlay provides this attribute. For example, if the value of the `memberOf` attribute is `CN=abcxyz,OU=users,DC=company,DC=com`, then use: ``` ldap['group_dn'] = 'CN=abcxyz,OU=users,DC=company,DC=com' ``` `ldap['host']` The name (or IP address) of the LDAP server. The hostname of the LDAP or Active Directory server. Be sure the Chef Infra Server is able to resolve any host names. Default value: `ldap-server-host`. `ldap['login_attribute']` The LDAP attribute that holds the user’s login name. Use to specify the Chef Infra Server user name for an LDAP user. Default value: `sAMAccountName`. `ldap['port']` An integer that specifies the port on which the LDAP server listens. The default value is an appropriate value for most configurations. Default value: `389` or `636` when `ldap['encryption']` is set to `:simple_tls`. `ldap['ssl_enabled']` Cause the Chef Infra Server to connect to the LDAP server using SSL. Default value: `false`. Must be `false` when `ldap['tls_enabled']` is `true`. Note It’s recommended that you enable SSL for Active Directory. Note Previous versions of the Chef Infra Server used the `ldap['ssl_enabled']` setting to first enable SSL, and then the `ldap['encryption']` setting to specify the encryption type. These settings are deprecated. `ldap['system_adjective']` A descriptive name for the login system that is displayed to users in the Chef Infra Server management console. If a value like “corporate” is used, then the Chef management console user interface will display strings like “the corporate login server”, “corporate login”, or “corporate password.” Default value: `AD/LDAP`. Warning This setting is **not** used by the Chef Infra Server. It is used only by the Chef management console. `ldap['timeout']` The amount of time (in seconds) to wait before timing out. Default value: `60000`. `ldap['tls_enabled']` Enable TLS. When enabled, communication with the LDAP server is done via a secure SSL connection on a dedicated port. When `true`, `ldap['port']` is also set to `636`. Default value: `false`. Must be `false` when `ldap['ssl_enabled']` is `true`. Note Previous versions of the Chef Infra Server used the `ldap['ssl_enabled']` setting to first enable SSL, and then the `ldap['encryption']` setting to specify the encryption type. These settings are deprecated. ### nginx This configuration file has the following settings for `nginx`: `nginx['cache_max_size']` The `max_size` parameter used by the Nginx cache manager, which is part of the `proxy_cache_path` directive. When the size of file storage exceeds this value, the Nginx cache manager removes the least recently used data. Default value: `5000m`. `nginx['client_max_body_size']` The maximum accepted body size for a client request, as indicated by the `Content-Length` request header. Default value: `250m`. `nginx['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/nginx`. `nginx['enable']` Enable a service. Default value: `true`. `nginx['enable_ipv6']` Enable Internet Protocol version 6 (IPv6) addresses. Default value: `false`. `nginx['enable_non_ssl']` Allow port 80 redirects to port 443. When this value is set to `true`, load balancers on the front-end hardware are allowed to do SSL termination of the WebUI and API. Default value: `false`. Note Chef Infra Server versions earlier than 14.5 configured with `nginx['enable_non_ssl'] = false` and `fips = true` require `export CSC_LB_URL=https://127.0.0.1` to run the command `chef-server-ctl reindex <options>` `nginx['enable_stub_status']` Enables the Nginx `stub_status` module. See `nginx['stub_status']['allow_list']`, `nginx['stub_status']['listen_host']`, `nginx['stub_status']['listen_port']`, and `nginx['stub_status']['location']`. Default value: `true`. `nginx['gzip']` Enable gzip compression. Default value: `on`. `nginx['gzip_comp_level']` The compression level used with gzip, from least amount of compression (`1`, fastest) to the most (`2`, slowest). Default value: `2`. `nginx['gzip_http_version']` Enable gzip depending on the version of the HTTP request. Default value: `1.0`. `nginx['gzip_proxied']` The type of compression used based on the request and response. Default value: `any`. `nginx['gzip_types']` Enable compression for the specified MIME-types. Default value: ``` [ 'text/plain', 'text/css', 'application/x-javascript', 'text/xml', 'application/xml', 'application/xml+rss', 'text/javascript', 'application/json' ] ``` `nginx['keepalive_timeout']` The amount of time (in seconds) to wait for requests on a HTTP keepalive connection. Default value: `65`. `nginx['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/nginx`. `nginx['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `nginx['log_x_forwarded_for']` Log $http_x_forwarded_for (“X-Forwarded-For”) instead of $remote_addr if `true`. Default value `false`. `nginx['non_ssl_port']` The port on which the WebUI and API are bound for non-SSL connections. Default value: `80`. Use `nginx['enable_non_ssl']` to enable or disable SSL redirects on this port number. Set to `false` to disable non-SSL connections. `nginx['sendfile']` Copy data between file descriptors when `sendfile()` is used. Default value: `on`. `nginx['server_name']` The FQDN for the server. Default value: `node['fqdn']`. `nginx['ssl_certificate']` The SSL certificate used to verify communication over HTTPS. Default value: `nil`. `nginx['ssl_certificate_key']` The certificate key used for SSL communication. Default value: `nil`. `nginx['ssl_ciphers']` The list of supported cipher suites that are used to establish a secure connection. To favor AES256 with ECDHE forward security, drop the `RC4-SHA:RC4-MD5:RC4:RSA` prefix. See [this link](https://www.openssl.org/docs/man1.0.2/man1/ciphers.html) for more information. For example: ``` nginx['ssl_ciphers'] = HIGH: ... :!PSK ``` `nginx['ssl_company_name']` The name of your company. Default value: `YouCorp`. `nginx['ssl_country_name']` The country in which your company is located. Default value: `US`. `nginx['ssl_email_address']` The default email address for your company. Default value: `<EMAIL>`. `nginx['ssl_locality_name']` The city in which your company is located. Default value: `Seattle`. `nginx['ssl_organizational_unit_name']` The organization or group within your company that is running the Chef Infra Server. Default value: `Operations`. `nginx['ssl_port']` Default value: `443`. `nginx['ssl_protocols']` The SSL protocol versions that are enabled. For enhanced security set this value to `'TLSv1.2'`. TLS 1.2 is supported on Chef Infra Client 10.16.4 and later on Linux, Unix, and macOS, and on Chef Infra Client 12.8 and later on Windows. If it is necessary to support these older end-of-life Chef Infra Client releases, set this value to `'TLSv1.1 TLSv1.2'`. ``` nginx['ssl_protocols'] = 'TLSv1.2' ``` Default value: `TLSv1 TLSv1.1 TLSv1.2`. `nginx['ssl_state_name']` The state, province, or region in which your company is located. Default value: `WA`. `nginx['strict_host_header']` Whether nginx should only respond to requests where the Host header matches one of the configured FQDNs. Default value: `false`. `nginx['stub_status']['allow_list']` The IP address on which accessing the `stub_status` endpoint is allowed. Default value: `["127.0.0.1"]`. `nginx['stub_status']['listen_host']` The host on which the Nginx `stub_status` module listens. Default value: `"127.0.0.1"`. `nginx['stub_status']['listen_port']` The port on which the Nginx `stub_status` module listens. Default value: `"9999"`. `nginx['stub_status']['location']` The name of the Nginx `stub_status` endpoint used to access data generated by the Nginx `stub_status` module. Default value: `"/nginx_status"`. `nginx['tcp_nodelay']` Enable the Nagle buffering algorithm. Default value: `on`. `nginx['tcp_nopush']` Enable TCP/IP transactions. Default value: `on`. `nginx['url']` Default value: `https://#{node['fqdn']}`. `nginx['use_implicit_hosts']` Automatically add localhost and any local IP addresses to the configured FQDNs. Useful in combination with `nginx['strict_host_header']`. Default value: `true`. `nginx['show_welcome_page']` Determines whether or not the default nginx welcome page is shown. Default value: `true`. `nginx['worker_connections']` The maximum number of simultaneous clients. Use with `nginx['worker_processes']` to determine the maximum number of allowed clients. Default value: `10240`. `nginx['worker_processes']` The number of allowed worker processes. Use with `nginx['worker_connections']` to determine the maximum number of allowed clients. Default value: `node['cpu']['total'].to_i`. `nginx['x_forwarded_proto']` The protocol used to connect to the server. Possible values: `http` and `https`. This is the protocol used to connect to the Chef Infra Server by a Chef Infra Client or a workstation. Default value: `'https'`. ### oc_bifrost The **oc_bifrost** service ensures that every request to view or manage objects stored on the Chef Infra Server is authorized. This configuration file has the following settings for `oc_bifrost`: `oc_bifrost['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. This value should be increased if failures indicate that the **oc_bifrost** service ran out of connections. This value should be tuned in conjunction with the `postgresql['max_connections']` setting for PostgreSQL. Default value: `20`. `oc_bifrost['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/oc_bifrost`. `oc_bifrost['enable']` Enable a service. Default value: `true`. `oc_bifrost['enable_request_logging']` Use to configure request logging for the `oc_bifrost` service. Default value: `true`. `oc_bifrost['extended_perf_log']` Default value: `true`. `oc_bifrost['listen']` The IP address on which the service is to listen. Default value: `'127.0.0.1'`. `oc_bifrost['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/oc_bifrost`. `oc_bifrost['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `oc_bifrost['port']` The port on which the service is to listen. Default value: `9463`. `oc_bifrost['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `oc_bifrost['sql_user']` (default: `'bifrost'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_bifrost['sql_user']`. Default value: `nil`. `oc_bifrost['sql_password']` The password for the `sql_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_bifrost sql_password`. `oc_bifrost['sql_ro_password']` The password for the `sql_ro_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_bifrost sql_ro_password`. `oc_bifrost['sql_ro_user']` Default value: `'bifrost_ro'`. `oc_bifrost['sql_user']` The user with permission to publish data. Default value: `'bifrost'`. `oc_bifrost['superuser_id']` Default value: **generated**. `oc_bifrost['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### oc_chef_authz The **opscode-authz** service is used to handle authorization requests from oc_erchef to oc_bifrost in the Chef Infra Server. This configuration file has the following settings for `oc_chef_authz`: `oc_chef_authz['http_cull_interval']` Default value: `'{1, min}'`. `oc_chef_authz['http_init_count']` Default value: `25`. `oc_chef_authz['http_max_age']` Default value: `'{70, sec}'`. `oc_chef_authz['http_max_connection_duration']` Default value: `'{70, sec}'`. `oc_chef_authz['http_max_count']` Default value: `100`. `oc_chef_authz['ibrowse_options']` The amount of time (in milliseconds) to wait for a connection to be established. Default value: `'[{connect_timeout, 5000}]'`. ### oc-chef-pedant This configuration file has the following settings for `oc-chef-pedant`: `oc_chef_pedant['debug_org_creation']` Run tests with full output. Default value: `false`. `oc_chef_pedant['dir']` The working directory. The default value is the recommended value. Default value: ``` '/var/opt/opscode/oc-chef-pedant' ``` `oc_chef_pedant['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` '/var/log/opscode/oc-chef-pedant' ``` `oc_chef_pedant['log_http_requests']` Log HTTP requests in a file named `http-traffic.log` that is located in the path specified by `log_directory`. Default value: `true`. `oc_chef_pedant['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` ### oc-id The **oc-id** service enables OAuth 2.0 authentication to the Chef Infra Server by external applications, including Chef Supermarket. OAuth 2.0 uses token-based authentication, where external applications use tokens that are issued by the **oc-id** provider. No special credentials—`webui_priv.pem` or privileged keys—are stored on the external application. This configuration file has the following settings for `oc-id`: `oc_id['administrators']` An array of Chef Infra Server user names who may add applications to the identity service. For example, `['user1', 'user2']`. Default value: `[ ]`. `oc_id['applications']` A Hash that contains OAuth 2 application information. Default value: `{ }`. To define OAuth 2 information for Chef Supermarket, create a Hash similar to: ``` oc_id['applications'] ||= {} oc_id['applications']['supermarket'] = { 'redirect_uri' => 'https://supermarket.mycompany.com/auth/chef_oauth2/callback', } ``` `oc_id['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `'20'`. `oc_id['dir']` The working directory. The default value is the recommended value. Default value: none. `oc_id['enable']` Enable a service. Default value: `true`. `oc_id['email_from_address']` Outbound email address. Defaults to the `'from_email'` value. `oc_id['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/opt/opscode/oc_id'`. `oc_id['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `oc_id['origin']` The FQDN for the server that is sending outbound email. Defaults to the `'api_fqdn'` value, which is the FQDN for the Chef Infra Server. `oc_id['num_to_keep']` The number of log files to keep. Default value: `10`. `oc_id['port']` The port on which the service is to listen. Default value: `9090`. `oc_id['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>@my_postgresql.postgres.database.azure.com'`), where `username` would normally equal the value of `oc_id['sql_user']` (default: `'od_id'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `oc_id['sql_user']`. Default value: `nil`. `oc_id['sql_database']` The name of the database. Default value: `oc_id`. `oc_id['sql_password']` The password for the `sql_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret oc_id sql_password`. `oc_id['sql_user']` The user with permission to write to `sql_database`. Default value: `oc_id`. `oc_id['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### opscode-chef-mover This configuration file has the following settings for `opscode-chef-mover`: `opscode_chef_mover['bulk_fetch_batch_size']` Default value: `'5'`. `opscode_chef_mover['cache_ttl']` Default value: `'3600'`. `opscode_chef_mover['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `'5'`. `opscode_chef_mover['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: ``` '/var/opt/opscode/opscode-chef-mover/data' ``` `opscode_chef_mover['dir']` The working directory. The default value is the recommended value. Default value: ``` '/var/opt/opscode/opscode-chef-mover' ``` `opscode_chef_mover['enable']` Enable a service. Default value: `true`. `opscode_chef_mover['ibrowse_max_pipeline_size']` Default value: `1`. `opscode_chef_mover['ibrowse_max_sessions']` Default value: `256`. `opscode_chef_mover['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` '/var/log/opscode/opscode-chef-mover' ``` `opscode_chef_mover['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_chef_mover['max_cache_size']` Default value: `'10000'`. `opscode_chef_mover['solr_http_cull_interval']` Default value: `'{1, min}'`. `opscode_chef_mover['solr_http_init_count']` Default value: `25`. `opscode_chef_mover['solr_http_max_age']` Default value: `'{70, sec}'`. `opscode_chef_mover['solr_http_max_connection_duration']` Default value: `'{70, sec}'`. `opscode_chef_mover['solr_http_max_count']` Default value: `100`. `opscode_chef_mover['solr_ibrowse_options']` Default value: `'[{connect_timeout, 10000}]'`. `opscode_chef_mover['solr_timeout']` Default value: `30000`. ### opscode-erchef The **opscode-erchef** service is an Erlang-based service that is used to handle Chef Infra Server API requests to the following areas within the Chef Infra Server: * Cookbooks * Data bags * Environments * Nodes * Roles * Sandboxes * Search This configuration file has the following settings for `opscode-erchef`: `opscode_erchef['auth_skew']` Default value: `900`. `opscode_erchef['authz_fanout']` Default value: `20`. `opscode_erchef['authz_timeout']` The amount of time (in seconds) before a request to the **oc_bifrost** service times out. Default value: `2000`. `opscode_erchef['base_resource_url']` The base URL to which the service is to return links to API resources. Use `:host_header` to ensure the URL is derived from the host header of the incoming HTTP request. Default value: `:host_header`. `opscode_erchef['bulk_fetch_batch_size']` The number of nodes that may be deserialized. Currently only applies to the `/search` endpoint in the Chef Infra Server API. The default value is the recommended value. Default value: `5`. `opscode_erchef['cache_ttl']` Default value: `3600`. `opscode_erchef['cleanup_batch_size']` Default value: `0`. `opscode_erchef['couchdb_max_conn']` Default value: `'100'`. `opscode_erchef['db_pool_size']` The number of open connections to PostgreSQL that are maintained by the service. Default value: `20`. `opscode_erchef['depsolver_timeout']` The amount of time (in milliseconds) to wait for cookbook dependency problems to be solved. Default value: `'5000'`. `opscode_erchef['depsolver_worker_count']` The number of Ruby processes for which cookbook dependency problems are unsolved. Use the `pgrep -fl depselector` command to verify the number of depsolver workers that are running. If you are seeing 503 service unavailable errors, increase this value. Default value: `'5'`. `opscode_erchef['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/opscode-erchef`. `opscode_erchef['enable']` Enable a service. Default value: `true`. `opscode_erchef['enable_actionlog']` Use to enable Chef actions, a premium feature of the Chef Infra Server. Default value: `false`. `opscode_erchef['enable_request_logging']` Use to configure request logging for the `opscode_erchef` service. Default value: `true`. `opscode_erchef['ibrowse_max_pipeline_size']` Default value: `1`. `opscode_erchef['ibrowse_max_sessions']` Default value: `256`. `opscode_erchef['listen']` The IP address on which the service is to listen. Default value: `127.0.0.1`. `opscode_erchef['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/opscode-erchef`. `opscode_erchef['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_erchef['max_cache_size']` Default value: `10000`. `opscode_erchef['max_request_size']` When the request body size is greater than this value, a `413 Request Entity Too Large` error is returned. Default value: `2000000`. `opscode_erchef['nginx_bookshelf_caching']` Whether Nginx is used to cache cookbooks. When `:on`, Nginx serves up the cached content instead of forwarding the request. Default value: `:off`. `opscode_erchef['port']` The port on which the service is to listen. Default value: `8000`. `opscode_erchef['reindex_batch_size']` The number of items to fetch from the database and send to the search index at a time. Default value: `10`. `opscode_erchef['reindex_sleep_min_ms']` The minimum number of milliseconds to sleep before retrying a failed attempt to index an item. Retries are delayed a random number of miliseconds between `reindex_sleep_min_ms` and `reindex_sleep_max_ms`. Set both this and `reindex_sleep_max_ms` to 0 to retry without delay. Default value: `500` `opscode_erchef['reindex_sleep_max_ms']` The maximum number of milliseconds to sleep before retrying a failed attempt to index an item. Retries are delayed a random number of miliseconds between `reindex_sleep_min_ms` and `reindex_sleep_max_ms`. Set both this and `reindex_sleep_min_ms` to 0 to retry without delay. Default value: `2000` `opscode_erchef['reindex_item_retries']` The number of times to retry sending an object for indexing in the case of failure. Default value: `3` `opscode_erchef['root_metric_key']` Default value: `chefAPI`. `opscode_erchef['s3_bucket']` The name of the Amazon Simple Storage Service (S3) bucket. This may point at external storage locations, such as Amazon EC2. See [AWS external bookshelf settings](../server/index#aws-settings) for more information on configuring external bookshelf. `opscode_erchef['s3_parallel_ops_fanout']` Default value: `20`. `opscode_erchef['s3_parallel_ops_timeout']` Default value: `5000`. `opscode_erchef['s3_url_expiry_window_size']` The frequency at which unique URLs are generated. This value may be a specific amount of time, i.e. `15m` (fifteen minutes) or a percentage of the value of `s3_url_ttl`, i.e. `10%`. Default value: `:off`. `opscode_erchef['s3_url_ttl']` The amount of time (in seconds) before connections to the server expire. If node bootstraps are timing out, increase this setting. Default value: `28800`. `opscode_erchef['sql_connection_user']` The PostgreSQL user name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `opscode-erchef['sql_user']` (default: `'opscode_chef'`). This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `opscode_erchef['sql_user']`.Default value: `nil`. `opscode_erchef['strict_search_result_acls']` Use to specify that search results only return objects to which an actor (user, client, etc.) has read access, as determined by ACL settings. This affects all searches. When `true`, the performance of the Chef management console may increase because it enables the Chef management console to skip redundant ACL checks. To ensure the Chef management console is configured properly, after this setting has been applied with a `chef-server-ctl reconfigure` run `chef-manage-ctl reconfigure` to ensure the Chef management console also picks up the setting. Default value: `false`. Warning When `true`, `opscode_erchef['strict_search_result_acls']` affects all search results and any actor (user, client, etc.) that does not have read access to a search result will not be able to view it. For example, this could affect search results returned during a Chef Infra Client runs if a Chef Infra Client does not have permission to read the information. `opscode_erchef['udp_socket_pool_size']` Default value: `20`. `opscode_erchef['umask']` Default value: `0022`. `opscode_erchef['validation_client_name']` Default value: `chef-validator`. `opscode_erchef['vip']` The virtual IP address. Default value: `127.0.0.1`. ### opscode-expander The **opscode-expander** service is used to process data (pulled from the **rabbitmq** service’s message queue) so that it can be properly indexed by the **opscode-solr4** service. This configuration file has the following settings for `opscode-expander`: `opscode_expander['consumer_id']` The identity of the consumer to which messages are published. Default value: `default`. `opscode_expander['dir']` The working directory. The default value is the recommended value. Default value: ``` /var/opt/opscode/opscode-expander ``` `opscode_expander['enable']` Enable a service. Default value: `true`. `opscode_expander['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` /var/log/opscode/opscode-expander ``` `opscode_expander['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_expander['nodes']` The number of allowed worker processes. Default value: `2`. `opscode_expander['reindexer_log_directory']` The directory in which `opscode-expander-reindexer` logs files are located. Default value: ``` /var/log/opscode/opscode-expander-reindexer ``` ### opscode-solr4 The **opscode-solr4** service is used to create the search indexes used for searching objects like nodes, data bags, and cookbooks. (This service ensures timely search results via the Chef Infra Server API; data that is used by the Chef platform is stored in PostgreSQL.) This configuration file has the following settings for `opscode-solr4`: `opscode_solr4['auto_soft_commit']` The maximum number of documents before a soft commit is triggered. Default value: `1000`. `opscode_solr4['commit_interval']` The frequency (in seconds) at which node objects are added to the Apache Solr search index. This value should be tuned carefully. When data is committed to the Apache Solr index, all incoming updates are blocked. If the duration between updates is too short, it is possible for the rate at which updates are asked to occur to be faster than the rate at which objects can be actually committed. Default value: `60000` (every 60 seconds). `opscode_solr4['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: ``` /var/opt/opscode/opscode-solr4/data ``` `opscode_solr4['dir']` The working directory. The default value is the recommended value. Default value: ``` /var/opt/opscode/opscode-solr4 ``` `opscode_solr4['enable']` Enable a service. Default value: `true`. `opscode_solr4['heap_size']` The amount of memory (in MBs) available to Apache Solr. If there is not enough memory available, search queries made by nodes to Apache Solr may fail. The amount of memory that must be available also depends on the number of nodes in the organization, the frequency of search queries, and other characteristics that are unique to each organization. In general, as the number of nodes increases, so does the amount of memory. The default value should work for many organizations with fewer than 25 nodes. For an organization with several hundred nodes, the amount of memory that is required often exceeds 3GB. Default value: `nil`, which is equivalent to 25% of the system memory or 1024 (MB, but this setting is specified as an integer number of MB in EC11), whichever is smaller. `opscode_solr4['ip_address']` The IP address for the machine on which Apache Solr is running. Default value: `127.0.0.1`. `opscode_solr4['java_opts']` A Hash of `JAVA_OPTS` environment variables to be set. (`-XX:NewSize` is configured using the `new_size` setting.) Default value: `' '` (empty). `opscode_solr4['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: ``` /var/log/opscode/opscode-solr4 ``` `opscode_solr4['log_gc']` Enable or disable GC logging. Default is `true`. `opscode_solr4['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `opscode_solr4['max_commit_docs']` The frequency (in documents) at which node objects are added to the Apache Solr search index. This value should be tuned carefully. When data is committed to the Apache Solr index, all incoming updates are blocked. If the duration between updates is too short, it is possible for the rate at which updates are asked to occur to be faster than the rate at which objects can be actually committed. Default value: `1000` (every 1000 documents). `opscode_solr4['max_field_length']` The maximum field length (in number of tokens/terms). If a field length exceeds this value, Apache Solr may not be able to complete building the index. Default value: `100000` (increased from the Apache Solr default value of `10000`). `opscode_solr4['max_merge_docs']` The maximum number of index segments allowed before they are merged into a single index. Default value: `2147483647`. `opscode_solr4['merge_factor']` The maximum number of document updates that can be stored in memory before being flushed and added to the current index segment. Default value: `15`. `opscode_solr4['new_size']` Configure the `-XX:NewSize` `JAVA_OPTS` environment variable. Default value: `nil`. `opscode_solr4['poll_seconds']` The frequency (in seconds) at which the secondary machine polls the primary. Default value: `20`. `opscode_solr4['port']` The port on which the service is to listen. Default value: `8983`. `opscode_solr4['ram_buffer_size']` The size (in megabytes) of the RAM buffer. When document updates exceed this amout, pending updates are flushed. Default value: `100`. `opscode_solr4['url']` Default value: `'http://localhost:8983/solr'`. `opscode_solr4['vip']` The virtual IP address. Default value: `127.0.0.1`. ### postgresql The **postgresql** service is used to store node, object, and user data. This configuration file has the following settings for `postgresql`: `postgresql['checkpoint_completion_target']` A completion percentage that is used to determine how quickly a checkpoint should finish in relation to the completion status of the next checkpoint. For example, if the value is `0.5`, then a checkpoint attempts to finish before 50% of the next checkpoint is done. Default value: `0.5`. `postgresql['checkpoint_segments']` The maximum amount (in megabytes) between checkpoints in log file segments. Default value: `3`. `postgresql['checkpoint_timeout']` The amount of time (in minutes) between checkpoints. Default value: `5min`. `postgresql['checkpoint_warning']` The frequency (in seconds) at which messages are sent to the server log files if checkpoint segments are being filled faster than their currently configured values. Default value: `30s`. `postgresql['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `/var/opt/opscode/postgresql/#{node['private_chef']['postgresql']['version']}/data`. `postgresql['db_connection_superuser']` The PostgreSQL superuser name in `'username@hostname'` format (e.g. `'<EMAIL>'`), where `username` would normally equal the value of `postgresql['db_superuser']` with any dashes replaced by underscores. This setting is **required** in an external Azure PostgreSQL database-as-a-service configuration. If set to `nil`, Chef Infra Server assumes that the database is not on Azure and the PostgreSQL connection will be made using the value specified in `postgresql['db_superuser']`. Default value: `nil`. `postgresql['db_superuser']` Default value: `opscode-pgsql`. If `username` is set, set `db_superuser` to the same value. `postgresql['db_superuser_password']` Password for the DB superuser. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-db-superuser-password`. `postgresql['dir']` The working directory. The default value is the recommended value. Default value: `/var/opt/opscode/postgresql/#{node['private_chef']['postgresql']['version']}`. `postgresql['effective_cache_size']` The size of the disk cache that is used for data files. Default value: 50% of available RAM. `postgresql['enable']` Enable a service. Default value: `true`. `postgresql['home']` The home directory for PostgreSQL. Default value: `/var/opt/opscode/postgresql`. `postgresql['keepalives_count']` The maximum number of keepalive proves that should be sent before dropping a connection. Default value: `2`. `postgresql['keepalives_idle']` The amount of time (in seconds) a connection must remain idle before keepalive probes will resume. Default value: `60`. `postgresql['keepalives_interval']` The amount of time (in seconds) between probes. Default value: `15`. `postgresql['listen_address']` The connection source to which PostgreSQL is to respond. Default value: `localhost`. `postgresql['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `/var/log/opscode/postgresql/#{node['private_chef']['postgresql']['version']}`. `postgresql['log_min_duration_statement']` When to log a slow PostgreSQL query statement. Possible values: `-1` (disabled, do not log any statements), `0` (log every statement), or an integer greater than zero. When the integer is greater than zero, this value is the amount of time (in milliseconds) that a query statement must have run before it is logged. Default value: `-1`. `postgresql['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: `{ 'file_maxbytes' => 104857600, 'num_to_keep' => 10 }` `postgresql['max_connections']` The maximum number of allowed concurrent connections. Default value: `350`. `postgresql['md5_auth_cidr_addresses']` Use instead of `trust_auth_cidr_addresses` to encrypt passwords using MD5 hashes. Default value: `[ '127.0.0.1/32', '::1/128' ]`. `postgresql['port']` The port on which the service is to listen. Default value: `5432`. `postgresql['shared_buffers']` The amount of memory that is dedicated to PostgreSQL for data caching. Default value: `#{(node['memory']['total'].to_i / 4) / (1024)}MB`. `postgresql['shell']` Default value: `/bin/sh`. `postgresql['shmall']` The total amount of available shared memory. Default value: `4194304`. `postgresql['shmmax']` The maximum amount of shared memory. Default value: `17179869184`. `postgresql['sslmode']` SSL encryption mode between the Chef Infra Server and PostgreSQL. Valid settings are `'disable'` and `'require'`. Default value: `'disable'`. `postgresql['trust_auth_cidr_addresses']` Use for clear-text passwords. See `md5_auth_cidr_addresses`. Default value: `'127.0.0.1/32', '::1/128'`. `postgresql['user_path']` Default value: `/opt/opscode/embedded/bin:/opt/opscode/bin:$PATH`. `postgresql['username']` The PostgreSQL account user name. Default value: `opscode-pgsql`. If setting this value, must set `db_superuser` to the same value. `postgresql['version']` The (currently) hardcoded version of PostgreSQL. Default value: `'9.2'`. `postgresql['vip']` The virtual IP address. Default value: `127.0.0.1`. `postgresql['work_mem']` The size (in megabytes) of allowed in-memory sorting. Default value: `8MB`. ### rabbitmq The **rabbitmq** service is used to provide the message queue that is used by the Chef Infra Server to get search data to Apache Solr so that it can be indexed for search. This configuration file has the following settings for `rabbitmq`: `rabbitmq['actions_exchange']` The name of the exchange to which Chef actions publishes actions data. Default value: `'actions'`. `rabbitmq['actions_password']` Legacy configuration setting for the password of the `actions_user`. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-actions-password`. `rabbitmq['actions_user']` The user with permission to publish actions data. Default value: `'actions'`. `rabbitmq['actions_vhost']` The virtual host to which Chef actions publishes actions data. Default value: `'/analytics'`. `rabbitmq['analytics_max_length']` The maximum number of messages that can be queued before RabbitMQ automatically drops messages from the front of the queue to make room for new messages. Default value: `10000`. `rabbitmq['consumer_id']` The identity of the consumer to which messages are published. Default value: `'hotsauce'`. `rabbitmq['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `'/var/opt/opscode/rabbitmq/db'`. `rabbitmq['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/rabbitmq'`. `rabbitmq['drop_on_full_capacity']` Specify if messages will stop being sent to the RabbitMQ queue when it is at capacity. Default value: `true`. `rabbitmq['enable']` Enable a service. Default value: `true`. `rabbitmq['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/log/opscode/rabbitmq'`. `rabbitmq['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `rabbitmq['management_enabled']` Specify if the rabbitmq-management plugin is enabled. Default value: `true`. `rabbitmq['management_password']` Legacy configuration setting for rabbitmq-management plugin password. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret rabbitmq management_password`. `rabbitmq['management_port']` The rabbitmq-management plugin port. Default value: `15672`. `rabbitmq['management_user']` The rabbitmq-management plugin user. Default value: `'rabbitmgmt'`. `rabbitmq['node_ip_address']` The bind IP address for RabbitMQ. Default value: `'127.0.0.1'`. `rabbitmq['node_port']` The port on which the service is to listen. Default value: `'5672'`. `rabbitmq['nodename']` The unique identifier of the node. Default value: `'rabbit@localhost'`. `rabbitmq['password']` Legacy configuration setting for the password for the RabbitMQ user. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret rabbitmq password`. `rabbitmq['prevent_erchef_startup_on_full_capacity']` Specify if the Chef Infra Server will start when the monitored RabbitMQ queue is full. Default value: `false`. `rabbitmq['queue_at_capacity_affects_overall_status']` Specify if the `_status` endpoint in the Chef Infra Server API will fail if the monitored queue is at capacity. Default value: `false`. `rabbitmq['queue_length_monitor_enabled']` Specify if the queue length monitor is enabled. Default value: `true`. `rabbitmq['queue_length_monitor_millis']` The frequency (in milliseconds) at which the length of the RabbitMQ queue is checked. Default value: `30000`. `rabbitmq['queue_length_monitor_timeout_millis']` The timeout (in milliseconds) at which calls to the queue length monitor will stop if the Chef Infra Server is overloaded. Default value: `5000`. `rabbitmq['queue_length_monitor_queue']` The RabbitMQ queue that is observed by queue length monitor. Default value: `'alaska'`. `rabbitmq['queue_length_monitor_vhost']` The virtual host for the RabbitMQ queue that is observed by queue length monitor. Default value: `'/analytics'`. `rabbitmq['rabbit_mgmt_http_cull_interval']` The maximum cull interval (in seconds) for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `60`. `rabbitmq['rabbit_mgmt_http_init_count']` The initial worker count for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `25`. `rabbitmq['rabbit_mgmt_http_max_age']` The maximum connection worker age (in seconds) for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `70`. `rabbitmq['rabbit_mgmt_http_max_connection_duration']` The maximum connection duration (in seconds) for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `70`. `rabbitmq['rabbit_mgmt_http_max_count']` The maximum worker count for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `100`. `rabbitmq['rabbit_mgmt_ibrowse_options']` An array of comma-separated key-value pairs of ibrowse options for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `'{connect_timeout, 10000}'`. `rabbitmq['rabbit_mgmt_timeout']` The timeout for the HTTP connection pool that is used by the rabbitmq-management plugin. Default value: `30000`. `rabbitmq['reindexer_vhost']` Default value: `'/reindexer'`. `rabbitmq['ssl_versions']` The SSL versions used by the rabbitmq-management plugin. (See [RabbitMQ TLS support](https://www.rabbitmq.com/ssl.html) for more information.) Default value: `['tlsv1.2', 'tlsv1.1']`. `rabbitmq['user']` Default value: `'chef'`. `rabbitmq['vhost']` Default value: `'/chef'`. `rabbitmq['vip']` The virtual IP address. Default value: `'127.0.0.1'`. ### redis_lb Key-value store used in conjunction with Nginx to route requests and populate request data used by the Chef Infra Server. This configuration file has the following settings for `redis_lb`: `redis_lb['activerehashing']` Enable active rehashing. Default value: `'no'`. `redis_lb['aof_rewrite_min_size']` The minimum size of the append-only file. Only files larger than this value are rewritten. Default value: `'16mb'`. `redis_lb['aof_rewrite_percent']` The size of the current append-only file, as compared to the base size. The append-only file is rewritten when the current file exceeds the base size by this value. Default value: `'50'`. `redis_lb['appendfsync']` The frequency at which the operating system writes data on-disk, instead of waiting for more data. Possible values: `no` (don’t fsync, let operating system flush data), `always` (fsync after every write to the append-only log file), and `everysec` (fsync only once time per second). Default value: `'always'`. `redis_lb['appendonly']` Dump data asynchronously on-disk or to an append-only log file. Set to `yes` to dump data to an append-only log file. Default value: `'no'`. `redis_lb['bind']` Bind Redis to the specified IP address. Default value: `'127.0.0.1'`. `redis_lb['data_dir']` The directory in which on-disk data is stored. The default value is the recommended value. Default value: `'/var/opt/opscode/redis_lb/data'`. `redis_lb['databases']` The number of databases. Default value: `'16'`. `redis_lb['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/redis_lb'`. `redis_lb['enable']` Enable a service. Default value: `true`. `redis_lb['ha']` Run the Chef Infra Server in a high availability topology. When `topology` is set to `ha`, this setting defaults to `true`. Default value: `false`. `redis_lb['keepalive']` The amount of time (in seconds) to wait for requests on a connection. Default value: `'60'`. `redis_lb['log_directory']` The directory in which log data is stored. The default value is the recommended value. Default value: `'/var/log/opscode/redis_lb'`. `redis_lb['log_rotation']` The log rotation policy for this service. Log files are rotated when they exceed `file_maxbytes`. The maximum number of log files in the rotation is defined by `num_to_keep`. Default value: ``` { 'file_maxbytes' => 104857600, 'num_to_keep' => 10 } ``` `redis_lb['loglevel']` The level of logging to be stored in a log file.. Possible values: `debug`, `notice`, `verbose`, and `warning`. Default value: `'notice'`. `redis_lb['maxmemory']` The maximum amount of memory (in bytes). Default value: `'8m'`. `redis_lb['maxmemory_policy']` The policy applied when the maximum amount of memory is reached. Possible values: `allkeys-lru` (remove keys, starting with those used least frequently), `allkeys-random` (remove keys randomly), `noeviction` (don’t expire, return an error on write operation), `volatile-lru` (remove expired keys, starting with those used least frequently), `volatile-random` (remove expired keys randomly), and `volatile-ttl` (remove keys, starting with nearest expired time). Default value: `'noeviction'`. `redis_lb['port']` The port on which the service is to listen. Default value: `'16379'`. `redis_lb['save_frequency']` Set the save frequency. Pattern: `{ "seconds" => "keys", "seconds" => "keys", "seconds" => "keys" }`. Default value: ``` { '900' => '1', '300' => '10', '60' => '1000' } ``` Which saves the database every 15 minutes if at least one key changes, every 5 minutes if at least 10 keys change, and every 60 seconds if 10000 keys change. `redis_lb['timeout']` The amount of time (in seconds) a client may be idle before timeout. Default value: `'300'`. `redis_lb['vip']` The virtual IP address. Default value: `'127.0.0.1'`. `redis_lb['password']` Legacy configuration setting for the Redis password. Default value: **generated**. To override the default value, use the [Secrets Management](../server/ctl_chef_server/index#secrets-management) command: `chef-server-ctl set-secret redis_lb password`. ### upgrades This configuration file has the following settings for `upgrades`: `upgrades['dir']` The working directory. The default value is the recommended value. Default value: `'/var/opt/opscode/upgrades'`. ### user This configuration file has the following settings for `user`: `user['home']` The home directory for the user under which Chef Infra Server services run. Default value: `/opt/opscode/embedded`. `user['shell']` The shell for the user under which Chef Infra Server services run. Default value: `/bin/sh`. `user['username']` The user name under which Chef Infra Server services run. Default value: `opscode`. ### required_recipe `required_recipe` is a feature that allows an administrator to specify a recipe that will be run by all Chef Infra Clients that connect to it, regardless of the node’s run list. This feature is targeted at expert level practitioners who are delivering isolated configuration changes to the target systems, such as self-contained agent software. Further explanation of the feature can be found in [Chef Infra Client Development Docs](https://github.com/chef/chef/blob/main/docs/dev/design_documents/server_enforced_recipes.md). This configuration file has the following settings for `required_recipe`: `required_recipe["enable"]` Whether the feature is enabled. Default value: `false`. `required_recipe["path"]` The location of the recipe to serve. The file must be owned by the root user and group, and may not be group or world-writeable. Default value: `nil`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/config_rb_optional_settings/knife environment ================= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_environment.md) An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. Use the `knife environment` subcommand to manage environments within a single organization on the Chef Infra Server. Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. compare ------- Use the `compare` argument to compare the cookbook version constraints that are set on one (or more) environments. ### Syntax This argument has the following syntax: ``` knife environment compare [ENVIRONMENT_NAME...] (options) ``` ### Options This argument has the following options: `-a`, `--all` Upload all environments found at the specified path. `-m`, `--mismatch` Show only matching versions. ### Examples The following examples show how to use this knife subcommand: **Compare cookbook versions in a single environment** To compare cookbook versions for a single environment: ``` knife environment compare development ``` to return something similar to: ``` development apache 2.3.1 windows 4.1.2 ``` **Compare cookbook versions for multiple environments** To compare cookbook versions for multiple environments: ``` knife environment compare development staging ``` to return something similar to: ``` development staging apache 2.3.1 1.2.2 windows 4.1.2 1.0.0 postgresql 1.0.0 1.0.0 ``` **Compare cookbook versions for all environments** To compare all cookbook versions for all environments: ``` knife environment compare --all ``` to return something similar to: ``` staging development ulimit latest latest redisio latest latest journly latest latest aws latest latest test latest latest unicorn latest latest sensu latest latest runit latest latest templater latest latest powershell latest latest openssl latest latest rbenv latest latest rabbitmq latest latest postgresql latest latest mysql latest latest ohai latest latest git latest latest erlang latest latest ssh_known_hosts latest latest nginx latest latest database latest latest yum latest latest xfs latest latest apt latest latest dmg latest latest chef_handler latest latest windows 1.0.0 4.1.2 ``` create ------ Use the `create` argument to add an environment object to the Chef Infra Server. When this argument is run, knife will open $EDITOR to enable editing of the `ENVIRONMENT` description field (unless a description is specified as part of the command). When finished, knife will add the environment to the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife environment create ENVIRONMENT_NAME -d --description ENVIRONMENT_DESCRIPTION ``` ### Options This argument has the following options: `--description DESCRIPTION` The description of the environment. This value populates the description field for the environment on the Chef Infra Server. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create an environment** To create an environment named `dev` with a description of `The development environment.`: ``` knife environment create dev -d --description "The development environment." ``` delete ------ Use the `delete` argument to delete an environment from a Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife environment delete ENVIRONMENT_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Delete an environment** To delete an environment named `dev`, enter: ``` knife environment delete dev ``` Type `Y` to confirm a deletion. edit ---- Use the `edit` argument to edit the attributes of an environment. When this argument is run, knife will open $EDITOR to enable editing of `ENVIRONMENT` attributes. When finished, knife will update the Chef Infra Server with those changes. ### Syntax This argument has the following syntax: ``` knife environment edit ENVIRONMENT_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Edit an environment** To edit an environment named `devops`, enter: ``` knife environment edit devops ``` from file --------- Use the `from file` argument to add or update an environment using a JSON or Ruby DSL description. ### Syntax This argument has the following syntax: ``` knife environment from file FILE (options) ``` ### Options This argument has the following options: `-a`, `--all` Upload all environments found at the specified path. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create an environment from a JSON file** To add an environment using data contained in a JSON file: ``` knife environment from file "path to JSON file" ``` list ---- Use the `list` argument to list all of the environments that are currently available on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife environment list -w ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### Examples The following examples show how to use this knife subcommand: **View a list of environments** To view a list of environments: ``` knife environment list -w ``` show ---- Use the `show` argument to display information about the specified environment. ### Syntax This argument has the following syntax: ``` knife environment show ENVIRONMENT_NAME ``` ### Options This argument has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. ### Examples The following examples show how to use this knife subcommand: **Show environments** To view information about the `dev` environment enter: ``` knife environment show dev ``` to return: ``` % knife environment show dev chef_type: environment cookbook_versions: default_attributes: description: json_class: Chef::Environment name: dev override_attributes: \\ \\ \\ \\ ``` **Show environments as JSON** To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife environment show devops -F json ``` Other formats available include `text`, `yaml`, and `pp`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_environment/knife exec ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_exec.md) Use the `knife exec` subcommand to execute Ruby scripts in the context of a fully configured Chef Infra Client. Use this subcommand to run scripts that will only access Chef Infra Server one time (or otherwise very infrequently) or any time that an operation does not warrant full usage of the knife subcommand library. Authenticated API Requests -------------------------- The `knife exec` subcommand can be used to make authenticated API requests to the Chef Infra Server using the following methods: | Method | Description | | --- | --- | | `api.delete` | Use to delete an object from the Chef Infra Server. | | `api.get` | Use to get the details of an object on the Chef Infra Server. | | `api.post` | Use to add an object to the Chef Infra Server. | | `api.put` | Use to update an object on the Chef Infra Server. | These methods are used with the `-E` option, which executes that string locally on the workstation using chef-shell. These methods have the following syntax: ``` knife exec -E 'api.method(/endpoint)' ``` where: * `api.method` is the corresponding authentication method — `api.delete`, `api.get`, `api.post`, or `api.put` * `/endpoint` is an endpoint in the Chef Infra Server API For example, to get the data for a node named “Example_Node”: ``` knife exec -E 'puts api.get("/nodes/Example_Node")' ``` and to ensure that the output is visible in the console, add the `puts` in front of the API authorization request: ``` knife exec -E 'puts api.get("/nodes/Example_Node")' ``` where `puts` is the shorter version of the `$stdout.puts` predefined variable in Ruby. The following example shows how to add a client named “IBM305RAMAC” and the `/clients` endpoint, and then return the private key for that user in the console: ``` client_desc = { "name" => "IBM305RAMAC", "admin" => false } new_client = api.post("/clients", client_desc) puts new_client["private_key"] ``` Ruby Scripts ------------ For Ruby scripts that will be run using the `exec` subcommand, note the following: * The Ruby script must be located on the system from which knife is run (and not be located on any of the systems that knife will be managing). * Shell commands will be run from a management workstation. For example, something like `%x[ls -lash /opt/only-on-a-node]` would give you the directory listing for the “opt/only-on-a-node” directory or a “No such file or directory” error if the file does not already exist locally. * When the chef-shell DSL is available, the Chef Infra Client DSL will not be (unless the management workstation is also a Chef Infra Client). Without the Chef Infra Client DSL, a bash block cannot be used to run bash commands. Syntax ------ This subcommand has the following syntax: ``` knife exec SCRIPT (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-E CODE`, `--exec CODE` A string of code to be executed. `-p PATH:PATH`, `--script-path PATH:PATH` A colon-separated path at which Ruby scripts are located. Use to override the default location for scripts. When this option is not specified, knife will look for scripts located in `chef-repo/.chef/scripts` directory. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Run Ruby scripts** There are three ways to use `knife exec` to run Ruby script files. For example: ``` knife exec /path/to/script_file ``` or: ``` knife exec -E 'RUBY CODE' ``` or: ``` knife exec RUBY CODE ^D ``` **Chef Knife status** To check the status of knife using a Ruby script named `status.rb` (which looks like): ``` printf "%-5s %-12s %-8s %s\n", "Check In", "Name", "Ruby", "Recipes" nodes.all do |n| checkin = Time.at(n['ohai_time']).strftime("%F %R") rubyver = n['languages']['ruby']['version'] recipes = n.run_list.expand(_default).recipes.join(", ") printf "%-20s %-12s %-8s %s\n", checkin, n.name, rubyver, recipes end ``` and is located in a directory named `scripts/`, enter: ``` knife exec scripts/status.rb ``` **List available free memory** To show the available free memory for all nodes, enter: ``` knife exec -E 'nodes.all {|n| puts "#{n.name} has #{n.memory.total} free memory"}' ``` **List available search indexes** To list all of the available search indexes, enter: ``` knife exec -E 'puts api.get("search").keys' ``` **Operations on Users and User Keys** To change any global end points like user or user keys, use the `--server-url` flag: ``` knife exec -E 'api.delete("/users/myuser/keys/user33")' --server-url https:// ``` **Query for multiple attributes** To query a node for multiple attributes using a Ruby script named `search_attributes.rb` (which looks like): ``` % cat scripts/search_attributes.rb query = ARGV[2] attributes = ARGV[3].split(",") puts "Your query: #{query}" puts "Your attributes: #{attributes.join(" ")}" results = {} search(:node, query) do |n| results[n.name] = {} attributes.each {|a| results[n.name][a] = n[a]} end puts results exit 0 ``` enter: ``` % knife exec scripts/search_attributes.rb "hostname:test_system" ipaddress,fqdn ``` to return something like: ``` Your query: hostname:test_system Your attributes: ipaddress fqdn {"test_system.example.com"=>{"ipaddress"=>"10.1.1.200", "fqdn"=>"test_system.example.com"}} ``` **Find shadow cookbooks** To find all of the locations in which cookbooks exist that may shadow each other, create a file called `shadow-check.rb` that contains the following Ruby code: ``` config = Chef::Config cookbook_loader = begin Chef::Cookbook::FileVendor.on_create { |manifest| Chef::Cookbook::FileSystemFileVendor.new(manifest, config[:cookbook_path]) } Chef::CookbookLoader.new(config[:cookbook_path]) end ui = Chef::Knife::UI.new($stdout, $stderr, $stdin, {}) cookbook_loader.load_cookbooks if cookbook_loader.merged_cookbooks.empty? ui.msg "cookbooks ok" else ui.warn "* " * 40 ui.warn(<<-WARNING) The cookbooks: #{cookbook_loader.merged_cookbooks.join(', ')} exist in multiple places in your cookbook_path. A composite version of these cookbooks has been compiled for uploading. #{ui.color('IMPORTANT:', :red, :bold)} In a future version of Chef, this behavior will be removed and you will no longer be able to have the same version of a cookbook in multiple places in your cookbook_path. WARNING ui.warn "The affected cookbooks are located:" ui.output ui.format_for_display(cookbook_loader.merged_cookbook_paths) ui.warn "* " * 40 end ``` Put this file in the directory of your choice. Run the following command: ``` knife exec shadow-check.rb ``` and be sure to edit `shadow-check.rb` so that it defines the path to that file correctly. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_exec/knife list ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_list.md) Use the `knife list` subcommand to view a list of objects on the Chef Infra Server. This subcommand works similar to `knife cookbook list`, `knife data bag list`, `knife environment list`, `knife node list`, and `knife role list`, but with a single verb (and a single action). Syntax ------ This subcommand has the following syntax: ``` knife list [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-1` Show only one column of results. Default: `false`. `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `-d` Prevent a directory’s children from showing when a directory matches a pattern. Default value: `false`. `-f`, `--flat` Show a list of file names. Set to `false` to view `ls`-like output. Default: `false`. `--local` Return only the contents of the local directory. Default: `false`. `-p` Show directories with trailing slashes (/). Default: `false`. `-R` List directories recursively. Default: `false`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **List roles** For example, to view a list of roles on the Chef Infra Server: ``` knife list roles/ ``` **List roles and environments** To view a list of roles and environments on the Chef Infra Server: ``` knife list roles/ environments/ ``` **List everything** To view a list of absolutely everything on the Chef Infra Server: ``` knife list -R / ``` © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_list/knife raw ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_raw.md) Use the `knife raw` subcommand to send a REST request to an endpoint in the Chef Infra Server API. Syntax ------ This subcommand has the following syntax: ``` knife raw REQUEST_PATH (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-i FILE`, `--input FILE` The name of a file to be used with the `PUT` or a `POST` request. `--[no-]pretty` Use `--no-pretty` to disable pretty-print output for JSON. Default: `--pretty`. `-m METHOD`, `--method METHOD` The request method: `DELETE`, `GET`, `POST`, or `PUT`. Default value: `GET`. `--proxy-auth` Enable proxy authentication to the Chef Infra Server web user interface. Default value: `false`. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **View a client** To view information about a client: ``` knife raw /clients/<client_name``` **View a node** To view information about a node: ``` knife raw /nodes/<node_name``` **Delete a data bag** To delete a data bag, enter a command similar to: ``` knife raw -m DELETE /data/foo ``` to return something similar to: ``` { "name":"foo", "json_class":"Chef::DataBag", "chef_type":"data_bag" } ``` **Delete a role** To delete a role, enter a command similar to: ``` knife raw -m DELETE /roles/role-foo.json ``` to return something similar to: ``` { "name":"role-foo", "json_class":"Chef::Role", "chef_type":"role" } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_raw/knife node ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_node.md) A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. Use the `knife node` subcommand to manage the nodes that exist on a Chef Infra Server. Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. bulk delete ----------- Use the `bulk delete` argument to delete one or more nodes that match a pattern defined by a regular expression. The regular expression must be within quotes and not be surrounded by forward slashes (/). ### Syntax This argument has the following syntax: ``` knife node bulk delete REGEX ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Bulk delete nodes** Use a regular expression to define the pattern used to bulk delete nodes: ``` knife node bulk delete "^[0-9]{3}$" ``` Type `Y` to confirm a deletion. create ------ Use the `create` argument to add a node to the Chef Infra Server. Node data is stored as JSON on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife node create NODE_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Create a node** To add a node named `node1`, enter: ``` knife node create node1 ``` In the $EDITOR enter the node data in JSON: ``` { "normal": { }, "name": "foobar", "override": { }, "default": { }, "json_class": "Chef::Node", "automatic": { }, "run_list": [ "recipe[zsh]", "role[webserver]" ], "chef_type": "node" } ``` When finished, save it. delete ------ Use the `delete` argument to delete a node from the Chef Infra Server. If using Chef Client 12.17 or later, you can delete multiple nodes using this subcommand. Note Deleting a node will not delete any corresponding API clients. ### Syntax This argument has the following syntax: ``` knife node delete NODE_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Delete a node** To delete a node named `node1`, enter: ``` knife node delete node1 ``` edit ---- Use the `edit` argument to edit the details of a node on a Chef Infra Server. Node data is stored as JSON on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife node edit NODE_NAME (options) ``` ### Options This argument has the following options: `-a`, `--all` Display a node in the $EDITOR. By default, attributes that are default, override, or automatic, are not shown. ### Examples The following examples show how to use this knife subcommand: **Edit a node** To edit the data for a node named `node1`, enter: ``` knife node edit node1 -a ``` Update the role data in JSON: ``` { "normal": { }, "name": "node1", "override": { }, "default": { }, "json_class": "Chef::Node", "automatic": { }, "run_list": [ "recipe[devops]", "role[webserver]" ], "chef_type": "node" } ``` When finished, save it. environment set --------------- Use the `environment set` argument to set the environment for a node without editing the node object. ### Syntax This argument has the following syntax: ``` knife node environment_set NODE_NAME ENVIRONMENT_NAME (options) ``` ### Options This command does not have any specific options. ### Examples None. from file --------- Use the `from file` argument to create a node using existing node data as a template. ### Syntax This argument has the following syntax: ``` knife node from file FILE ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Create a node using a JSON file** To add a node using data contained in a JSON file: ``` knife node from file "PATH_TO_JSON_FILE" ``` list ---- Use the `list` argument to view all of the nodes that exist on a Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife node list (options) ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **View a list of nodes** To verify the list of nodes that are registered with the Chef Infra Server, enter: ``` knife node list ``` to return something similar to: ``` i-12345678 rs-123456 ``` policy set ---------- Use the `policy set` argument to set the policy group and policy name for a node. ### Syntax This argument has the following syntax: ``` knife node policy set NODE POLICY_GROUP POLICY_NAME ``` ### Examples Set the policy group and policy name for a node named `test-node`: ``` knife node policy set test-node 'test-group' 'test-name' ``` run_list add ------------- A run-list defines all of the information necessary for Chef to configure a node into the desired state. A run-list is: * An ordered list of roles and/or recipes that are run in the exact order defined in the run-list; if a recipe appears more than once in the run-list, Chef Infra Client will not run it twice * Always specific to the node on which it runs; nodes may have a run-list that is identical to the run-list used by other nodes * Stored as part of the node object on the Chef server * Maintained using knife and then uploaded from the workstation to the Chef Infra Server, or maintained using Chef Automate Use the `run_list add` argument to add run-list items (roles or recipes) to a node. A run-list must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: ``` "role[NAME]" ``` or ``` "recipe[COOKBOOK::RECIPE]" ``` Use a comma to separate roles and recipes when adding more than one item the run-list: ``` "recipe[COOKBOOK::RECIPE],COOKBOOK::RECIPE,role[NAME]" ``` ### Syntax This argument has the following syntax: ``` knife node run_list add NODE_NAME RUN_LIST_ITEM (options) ``` Warning When running knife in Microsoft Windows, a string may be interpreted as a wildcard pattern when quotes are not present in the command. The number of quotes to use depends on the shell from which the command is being run. When running knife from the command prompt, a string should be surrounded by single quotes (`' '`). For example: ``` knife node run_list set test-node 'recipe[iptables]' ``` When running knife from Windows PowerShell, a string should be surrounded by triple single quotes (`''' '''`). For example: ``` knife node run_list set test-node '''recipe[iptables]''' ``` Note The Chef Client 12.4 release adds an optional feature to the Microsoft Installer Package (MSI) for Chef. This feature enables the ability to pass quoted strings from the Windows PowerShell command line without the need for triple single quotes (`''' '''`). This feature installs a Windows PowerShell module (typically in `C:\opscode\chef\modules`) that is also appended to the `PSModulePath` environment variable. This feature is not enabled by default. To activate this feature, run the following command from within Windows PowerShell: ``` Import-Module chef ``` or add `Import-Module chef` to the profile for Windows PowerShell located at: ``` ~\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 ``` This module exports cmdlets that have the same name as the command-line tools—chef-client, knife—that are built into Chef. For example: ``` knife exec -E 'puts ARGV' """&s0meth1ng""" ``` is now: ``` knife exec -E 'puts ARGV' '&s0meth1ng' ``` and: ``` knife node run_list set test-node '''role[ssssssomething]''' ``` is now: ``` knife node run_list set test-node 'role[ssssssomething]' ``` To remove this feature, run the following command from within Windows PowerShell: ``` Remove-Module chef ``` ### Options This argument has the following options: `-a ITEM`, `--after ITEM` Add a run-list item after the specified run-list item. `-b ITEM`, `--before ITEM` Add a run-list item before the specified run-list item. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Add a role** To add a role to a run-list, enter: ``` knife node run_list add NODE_NAME 'role[ROLE_NAME]' ``` **Add roles and recipes** To add roles and recipes to a run-list, enter: ``` knife node run_list add NODE_NAME 'recipe[COOKBOOK::RECIPE_NAME],recipe[COOKBOOK::RECIPE_NAME],role[ROLE_NAME]' ``` **Add a recipe with a FQDN** To add a recipe to a run-list using the fully qualified format, enter: ``` knife node run_list add NODE_NAME 'recipe[COOKBOOK::RECIPE_NAME]' ``` **Add a recipe with a cookbook** To add a recipe to a run-list using the cookbook format, enter: ``` knife node run_list add NODE_NAME 'COOKBOOK::RECIPE_NAME' ``` **Add the default recipe** To add the default recipe of a cookbook to a run-list, enter: ``` knife node run_list add NODE_NAME 'COOKBOOK' ``` run_list remove ---------------- Use the `run_list remove` argument to remove run-list items (roles or recipes) from a node. A recipe must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: `'role[ROLE_NAME]'` or `'recipe[COOKBOOK::RECIPE_NAME]'`. Use a comma to separate roles and recipes when removing more than one, like this: `'recipe[COOKBOOK::RECIPE_NAME],COOKBOOK::RECIPE_NAME,role[ROLE_NAME]'`. ### Syntax This argument has the following syntax: ``` knife node run_list remove NODE_NAME RUN_LIST_ITEM ``` ### Options This command does not have any specific options. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Remove a role** To remove a role from a run-list, enter: ``` knife node run_list remove NODE_NAME 'role[ROLE_NAME]' ``` **Remove a run-list** To remove a recipe from a run-list using the fully qualified format, enter: ``` knife node run_list remove NODE_NAME 'recipe[COOKBOOK::RECIPE_NAME]' ``` run_list set ------------- Use the `run_list set` argument to set the run-list for a node. A recipe must be in one of the following formats: fully qualified, cookbook, or default. Both roles and recipes must be in quotes, for example: `"role[ROLE_NAME]"` or `"recipe[COOKBOOK::RECIPE_NAME]"`. Use a comma to separate roles and recipes when setting more than one, like this: `"recipe[COOKBOOK::RECIPE_NAME],COOKBOOK::RECIPE_NAME,role[ROLE_NAME]"`. ### Syntax This argument has the following syntax: ``` knife node run_list set NODE_NAME RUN_LIST_ITEM ``` Warning When running knife in Microsoft Windows, a string may be interpreted as a wildcard pattern when quotes are not present in the command. The number of quotes to use depends on the shell from which the command is being run. When running knife from the command prompt, a string should be surrounded by single quotes (`' '`). For example: ``` knife node run_list set test-node 'recipe[iptables]' ``` When running knife from Windows PowerShell, a string should be surrounded by triple single quotes (`''' '''`). For example: ``` knife node run_list set test-node '''recipe[iptables]''' ``` Note The Chef Client 12.4 release adds an optional feature to the Microsoft Installer Package (MSI) for Chef. This feature enables the ability to pass quoted strings from the Windows PowerShell command line without the need for triple single quotes (`''' '''`). This feature installs a Windows PowerShell module (typically in `C:\opscode\chef\modules`) that is also appended to the `PSModulePath` environment variable. This feature is not enabled by default. To activate this feature, run the following command from within Windows PowerShell: ``` Import-Module chef ``` or add `Import-Module chef` to the profile for Windows PowerShell located at: ``` ~\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 ``` This module exports cmdlets that have the same name as the command-line tools—chef-client, knife—that are built into Chef. For example: ``` knife exec -E 'puts ARGV' """&s0meth1ng""" ``` is now: ``` knife exec -E 'puts ARGV' '&s0meth1ng' ``` and: ``` knife node run_list set test-node '''role[ssssssomething]''' ``` is now: ``` knife node run_list set test-node 'role[ssssssomething]' ``` To remove this feature, run the following command from within Windows PowerShell: ``` Remove-Module chef ``` ### Options This command does not have any specific options. ### Examples None. show ---- Use the `show` argument to display information about a node. ### Syntax This argument has the following syntax: ``` knife node show NODE_NAME (options) ``` ### Options This argument has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. `-F json`, `--format=json` Display output as JSON. `-l`, `--long` Display all attributes in the output. `-m`, `--medium` Display normal attributes in the output. `-r`, `--run-list` Show only the run-list. ### Examples The following examples show how to use this knife subcommand: **Show all data about nodes** To view all data for a node named `build`, enter: ``` knife node show build ``` to return: ``` Node Name: build Environment: _default FQDN: IP: Run List: Roles: Recipes: Platform: ``` **Show basic information about nodes** To show basic information about a node, truncated and nicely formatted: ``` knife node show NODE_NAME ``` **Show all data about nodes, truncated** To show all information about a node, nicely formatted: ``` knife node show -l NODE_NAME ``` **Show attributes** To list a single node attribute: ``` knife node show NODE_NAME -a ATTRIBUTE_NAME ``` where `ATTRIBUTE_NAME` is something like `kernel` or `platform`. To list a nested attribute: ``` knife node show NODE_NAME -a ATTRIBUTE_NAME.NESTED_ATTRIBUTE_NAME ``` where `ATTRIBUTE_NAME` is something like `kernel` and `NESTED_ATTRIBUTE_NAME` is something like `machine`. **Show the FQDN** To view the FQDN for a node named `i-12345678`, enter: ``` knife node show i-12345678 -a fqdn ``` to return: ``` fqdn: ip-10-251-75-20.ec2.internal ``` **Show a run-list** To view the run-list for a node named `dev`, enter: ``` knife node show dev -r ``` **Show as JSON data** To view information in JSON format, use the `-F` common option; use a command like this for a node named `devops`: ``` knife node show devops -F json ``` Other formats available include `text`, `yaml`, and `pp`. **Show as raw JSON data** To view node information in raw JSON, use the `-l` or `--long` option: ``` knife node show -l -F json NODE_NAME ``` and/or: ``` knife node show -l --format=json NODE_NAME ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_node/knife recipe list ================= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_recipe_list.md) Use the `knife recipe list` subcommand to view all of the recipes that are on a Chef Infra Server. A regular expression can be used to limit the results to recipes that match a specific pattern. The regular expression must be within quotes and not be surrounded by forward slashes (/). Syntax ------ This subcommand has the following syntax: ``` knife recipe list REGEX ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This command does not have any specific options. Examples -------- The following examples show how to use this knife subcommand: **View a list of recipes** To view a list of recipes: ``` knife recipe list 'couchdb::*' ``` to return: ``` couchdb::main_monitors couchdb::master couchdb::default couchdb::org_cleanup ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_recipe_list/knife role ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_role.md) A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. Use the `knife role` subcommand to manage the roles that are associated with one or more nodes on a Chef Infra Server. Note To add a role to a node and then build out the run-list for that node, use the [knife node](../workstation/knife_node/index) subcommand and its `run_list add` argument. Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. bulk delete ----------- Use the `bulk delete` argument to delete one or more roles that match a pattern defined by a regular expression. The regular expression must be within quotes and not be surrounded by forward slashes (/). ### Syntax This argument has the following syntax: ``` knife role bulk delete REGEX ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Bulk delete roles** Use a regular expression to define the pattern used to bulk delete roles: ``` knife role bulk delete "^[0-9]{3}$" ``` create ------ Use the `create` argument to add a role to the Chef Infra Server. Role data is saved as JSON on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife role create ROLE_NAME (options) ``` ### Options This argument has the following options: `--description DESCRIPTION` The description of the role. This value populates the description field for the role on the Chef Infra Server. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create a role** To add a role named `role1`, enter: ``` knife role create role1 ``` In the $EDITOR enter the role data in JSON: ``` { "name": "role1", "default_attributes": { }, "json_class": "Chef::Role", "run_list": ["recipe[cookbook_name::recipe_name]", "role[role_name]" ], "description": "", "chef_type": "role", "override_attributes": { } } ``` When finished, save it. delete ------ Use the `delete` argument to delete a role from the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife role delete ROLE_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Delete a role** ``` knife role delete devops ``` Type `Y` to confirm a deletion. edit ---- Use the `edit` argument to edit role details on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife role edit ROLE_NAME ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Edit a role** To edit the data for a role named `role1`, enter: ``` knife role edit role1 ``` Update the role data in JSON: ``` { "name": "role1", "description": "This is the description for the role1 role.", "json_class": "Chef::Role", "default_attributes": { }, "override_attributes": { }, "chef_type": "role", "run_list": ["recipe[cookbook_name::recipe_name]", "role[role_name]" ], "env_run_lists": { }, } ``` When finished, save it. from file --------- Use the `from file` argument to create a role using existing JSON data as a template. ### Syntax This argument has the following syntax: ``` knife role from file FILE ``` ### Options This command does not have any specific options. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create a role using JSON data** To view role details based on the values contained in a JSON file: ``` knife role from file "path to JSON file" ``` list ---- Use the `list` argument to view a list of roles that are currently available on the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife role list ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### Examples The following examples show how to use this knife subcommand: **View a list of roles** To view a list of roles on the Chef Infra Server and display the URI for each role returned, enter: ``` knife role list -w ``` show ---- Use the `show` argument to view the details of a role. ### Syntax This argument has the following syntax: ``` knife role show ROLE_NAME ``` ### Options This argument has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Show as JSON data** To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife role show devops -F json ``` Other formats available include `text`, `yaml`, and `pp`. **Show as raw JSON data** To view node information in raw JSON, use the `-l` or `--long` option: ``` knife role show -l -F json <role_name``` and/or: ``` knife role show -l --format=json <role_name``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_role/knife serve =========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_serve.md) Use the `knife serve` subcommand to run a persistent chef-zero against the local chef-repo. (chef-zero is a lightweight Chef Infra Server that runs in-memory on the local machine.) This is the same as running the Chef Infra Client executable with the `--local-mode` option. The `chef_repo_path` is located automatically and the Chef Infra Server will bind to the first available port between `8889` and `9999`. `knife serve` will print the URL for the local Chef Infra Server, so that it may be added to the config.rb file. Syntax ------ This subcommand has the following syntax: ``` knife serve (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. Default value: same as `chef_repo_path` in the client.rb file. `--chef-zero-host IP` Override the host on which chef-zero listens. Default value: `127.0.0.1`. `--chef-zero-port PORT` The port on which chef-zero listens. The default behavior will bind to the first available port between `8889` and `9999`. `--repo-mode MODE` Use to specify the local chef-repo layout. Possible values: `static` (for environments, roles, data bags, and cookbooks), `everything` (same as static, plus nodes, clients, and users), `hosted_everything` (for ACLs, groups). Default value: `everything/hosted_everything`. Examples -------- None. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_serve/knife search ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_search.md) Search indexes allow queries to be made for any type of data that is indexed by the Chef Infra Server, including data bags (and data bag items), environments, nodes, and roles. A defined query syntax is used to support search patterns like exact, wildcard, range, and fuzzy. A search is a full-text query that can be done from several locations, including from within a recipe, by using the `search` subcommand in knife, the `search` method in the Chef Infra Language, the search box in the Chef management console, and by using the `/search` or `/search/INDEX` endpoints in the Chef Infra Server API. The search engine is based on Elasticsearch and is run from the Chef Infra Server. Use the `knife search` subcommand to run a search query for information that is indexed on a Chef Infra Server. Syntax ------ This subcommand has the following syntax: ``` knife search INDEX SEARCH_QUERY ``` where `INDEX` is one of `client`, `environment`, `node`, `role`, or the name of a data bag and `SEARCH_QUERY` is the search query syntax for the query that will be executed. `INDEX` is implied if omitted, and will default to `node`. For example: ``` knife search '*:*' -i ``` will return something similar to: ``` 8 items found centos-62-dev opensuse-15 ubuntu-1804-orgtest ubuntu-1804-ohai-test ubuntu-1804-ifcfg-test ohai-test win2k19-dev ``` and is the same search as: ``` knife search node '*:*' -i ``` If the `SEARCH_QUERY` does not contain a colon character (`:`), then the default query pattern is `tags:*#{@query}* OR roles:*#{@query}* OR fqdn:*#{@query}* OR addresses:*#{@query}*`, which means the following two search queries are effectively the same: ``` knife search ubuntu ``` or: ``` knife search node "tags:*ubuntu* OR roles:*ubuntu* OR fqdn:*ubuntu* (etc.)" ``` ### Query Syntax A search query is comprised of two parts: the key and the search pattern. A search query has the following syntax: ``` key:search_pattern ``` where `key` is a field name that is found in the JSON description of an indexable object on the Chef Infra Server (a role, node, client, environment, or data bag) and `search_pattern` defines what will be searched for, using one of the following search patterns: exact, wildcard, range, or fuzzy matching. Both `key` and `search_pattern` are case-sensitive; `key` has limited support for multiple character wildcard matching using an asterisk ("*") (and as long as it is not the first character). ### Keys A field name/description pair is available in the JSON object. Use the field name when searching for this information in the JSON object. Any field that exists in any JSON description for any role, node, Chef Infra Client, environment, or data bag can be searched. To search for the available fields for a particular object, use the `show` argument with any of the following knife subcommands: `knife client`, `knife data bag`, `knife environment`, `knife node`, or `knife role`. For example: `knife data bag show`. #### Nested Fields A nested field appears deeper in the JSON data structure. For example, information about a network interface might be several layers deep: `node['network']['interfaces']['en1']`. When nested fields are present in a JSON structure, Chef Infra Client will extract those nested fields to the top-level, flattening them into compound fields that support wildcard search patterns. By combining wildcards with range-matching patterns and wildcard queries, it is possible to perform very powerful searches, such as using the vendor part of the MAC address to find every node that has a network card made by the specified vendor. Consider the following snippet of JSON data: ``` {"network": [ //snipped... "interfaces", {"en1": { "number": "1", "flags": [ "UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST" ], "addresses": { "fe80::fa1e:dfff:fed8:63a2": { "scope": "Link", "prefixlen": "64", "family": "inet6" }, "f8:1e:df:d8:63:a2": { "family": "lladdr" }, "192.0.2.0": { "netmask": "255.255.255.0", "broadcast": "192.168.0.255", "family": "inet" } }, "mtu": "1500", "media": { "supported": { "autoselect": { "options": [ ] } }, "selected": { "autoselect": { "options": [ ] } } }, "type": "en", "status": "active", "encapsulation": "Ethernet" }, //snipped... ``` Before this data is indexed on the Chef Infra Server, the nested fields are extracted into the top level, similar to: ``` "broadcast" => "192.168.0.255", "flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"] "mtu" => "1500" ``` which allows searches like the following to find data that is present in this node: ``` node "broadcast:192.168.0.*" ``` or: ``` node "mtu:1500" ``` or: ``` node "flags:UP" ``` This data is also flattened into various compound fields, which follow the same pattern as the JSON hierarchy and use underscores (`_`) to separate the levels of data, similar to: ``` # ...snip... "network_interfaces_en1_addresses_192.0.2.0_broadcast" => "192.168.0.255", "network_interfaces_en1_addresses_fe80::fa1e:tldr_family" => "inet6", "network_interfaces_en1_addresses" => ["fe80::fa1e:tldr","f8:1e:df:tldr","192.0.2.0"] # ...snip... ``` which allows searches like the following to find data that is present in this node: ``` node "network_interfaces_en1_addresses:192.0.2.0" ``` This flattened data structure also supports using wildcard compound fields, which allow searches to omit levels within the JSON data structure that are not important to the search query. In the following example, an asterisk (`*`) is used to show where the wildcard can exist when searching for a nested field: ``` "network_interfaces_*_flags" => ["UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST"] "network_interfaces_*_addresses" => ["fe80::fa1e:dfff:fed8:63a2", "192.0.2.0", "f8:1e:df:d8:63:a2"] "network_interfaces_en0_media_*" => ["autoselect", "none", "1000baseT", "10baseT/UTP", "100baseTX"] "network_interfaces_en1_*" => ["1", "UP", "BROADCAST", "SMART", "RUNNING", "SIMPLEX", "MULTICAST", "fe80::fa1e:dfff:fed8:63a2", "f8:1e:df:d8:63:a2", "192.0.2.0", "1500", "supported", "selected", "en", "active", "Ethernet"] ``` For each of the wildcard examples above, the possible values are shown contained within the brackets. When running a search query, the query syntax for wildcards is to simply omit the name of the node (while preserving the underscores), similar to: ``` network_interfaces__flags ``` This query will search within the `flags` node, within the JSON structure, for each of `UP`, `BROADCAST`, `SMART`, `RUNNING`, `SIMPLEX`, and `MULTICAST`. #### Examples To see the available keys for a node, enter the following (for a node named `staging`): ``` knife node show staging -Fj | less ``` to return a full JSON description of the node and to view the available keys with which any search query can be based. To use a question mark (`?`) to replace a single character in a wildcard search, enter the following: ``` knife search node 'platfor?:ubuntu' ``` To use an asterisk (`*`) to replace zero (or more) characters in a wildcard search, enter the following: ``` knife search node 'platfo*:ubuntu' ``` To find all IP address that are on the same network, enter the following: ``` knife search node 'ipaddress:192.168*' ``` where `192.168*` is the network address for which the search will be run. To use a range search to find IP addresses within a subnet, enter the following: ``` knife search node 'ipaddress:[192.168.0.* TO 192.0.2.*]' ``` where `192.168.0.* TO 192.0.2.*` defines the subnet range. ### About Patterns A search pattern is a way to fine-tune search results by returning anything that matches some type of incomplete search query. There are four types of search patterns that can be used when searching the search indexes on the Chef Infra Server: exact, wildcard, range, and fuzzy. #### Exact Matching An exact matching search pattern is used to search for a key with a name that exactly matches a search query. If the name of the key contains spaces, quotes must be used in the search pattern to ensure the search query finds the key. The entire query must also be contained within quotes, so as to prevent it from being interpreted by Ruby or a command shell. The best way to ensure that quotes are used consistently is to quote the entire query using single quotes (' ‘) and a search pattern with double quotes (" “). To search in a specific data bag for a specific data bag item, enter the following: ``` knife search admins 'id:charlie' ``` where `admins` is the name of the data bag and `charlie` is the name of the data bag item. Something similar to the following will be returned: ``` 1 items found _rev: 1-39ff4099f2510f477b4c26bef81f75b9 chef_type: data_bag_item comment: <NAME> data_bag: admins gid: ops id: charlie shell: /bin/zsh uid: 1005 ``` To search in a specific data bag using a string to find any matching data bag item, enter the following: ``` knife search admins 'comment:"<NAME>"' ``` where `admins` is the name of the data bag and `<NAME>` is the string that will be used during the search. Something similar to the following will be returned: ``` 1 items found _rev: 1-39ff4099f2510f477b4c26bef81f75b9 chef_type: data_bag_item comment: <NAME> data_bag: admins gid: ops id: charlie shell: /bin/zsh uid: 1005 ``` #### Wildcard Matching A wildcard matching search pattern is used to query for substring matches that replace zero (or more) characters in the search pattern with anything that could match the replaced character. There are two types of wildcard searches: * A question mark (`?`) can be used to replace exactly one character (as long as that character is not the first character in the search pattern) * An asterisk (`*`) can be used to replace any number of characters (including zero) To search for any node that contains the specified key, enter the following: ``` knife search node 'foo:*' ``` where `foo` is the name of the node. To search for a node using a partial name, enter one of the following: ``` knife search node 'name:app*' ``` or: ``` knife search node 'name:app1*.example.com' ``` or: ``` knife search node 'name:app?.example.com' ``` or: ``` knife search node 'name:app1.example.???' ``` to return `app1.example.com` (and any other node that matches any of the string searches above). #### Range Matching A range matching search pattern is used to query for values that are within a range defined by upper and lower boundaries. A range matching search pattern can be inclusive or exclusive of the boundaries. Use square brackets ("[ ]") to denote inclusive boundaries and curly braces ("{ }") to denote exclusive boundaries and with the following syntax: ``` boundary TO boundary ``` where `TO` is required (and must be capitalized). A data bag named `sample` contains four data bag items: `abc`, `bar`, `baz`, and `quz`. All of the items in-between `bar` and `foo`, inclusive, can be searched for using an inclusive search pattern. To search using an inclusive range, enter the following: ``` knife search sample "id:[bar TO foo]" ``` where square brackets (`[ ]`) are used to define the range. A data bag named `sample` contains four data bag items: `abc`, `bar`, `baz`, and `quz`. All of the items that are exclusive to `bar` and `foo` can be searched for using an exclusive search pattern. To search using an exclusive range, enter the following: ``` knife search sample "id:{bar TO foo}" ``` where curly braces (`{ }`) are used to define the range. #### Fuzzy Matching A fuzzy matching search pattern is used to search based on the proximity of two strings of characters. An (optional) integer may be used as part of the search query to more closely define the proximity. A fuzzy matching search pattern has the following syntax: ``` "search_query"~edit_distance ``` where `search_query` is the string that will be used during the search and `edit_distance` is the proximity. A tilde ("~") is used to separate the edit distance from the search query. To use a fuzzy search pattern enter something similar to: ``` knife search client "name:boo~" ``` where `boo~` defines the fuzzy search pattern. This will return something similar to: ``` { "total": 1, "start": 0, "rows": [ { "public_key": "too long didn't read", "name": "foo", "_rev": "1-f11a58043906e33d39a686e9b58cd92f", "json_class": "Chef::ApiClient", "admin": false, "chef_type": "client" } ] } ``` ### About Operators An operator can be used to ensure that certain terms are included in the results, are excluded from the results, or are not included even when other aspects of the query match. Searches can use the following operators: | Operator | Description | | --- | --- | | `AND` | Use to find a match when both terms exist. | | `OR` | Use to find a match if either term exists. | | `NOT` | Use to exclude the term after `NOT` from the search results. | Operators must be in ALL CAPS. Parentheses can be used to group clauses and to form sub-queries. Warning Using `AND NOT` together may trigger an error. For example: ``` ERROR: knife search failed: invalid search query: 'datacenter%3A123%20AND%20NOT%20hostname%3Adev-%20AND%20NOT%20hostanem%3Asyslog-' Parse error at offset: 38 Reason: Expected one of \ at line 1, column 42 (byte 42) after AND ``` Use `-` instead of `NOT`. For example: ``` knife search sample "id:foo AND -id:bar" ``` #### AND To join queries using the `AND` boolean operator, enter the following: ``` knife search sample "id:b* AND animal:dog" ``` to return something like: ``` { "total": 1, "start": 0, "rows": [ { "comment": "an item named baz", "id": "baz", "animal": "dog" } ] } ``` Or, to find all of the computers running on the Microsoft Windows platform that are associated with a role named `jenkins`, enter: ``` knife search node 'platform:windows AND roles:jenkins' ``` to return something like: ``` 2 items found Node Name: windows-server-2012r2.domain.com Environment: _default FQDN: windows-server-2012r2 IP: 0000::0000:0000:0000:0000 Run List: role[jenkins-windows] Roles: jenkins-windows, jenkins Recipes: jenkins-client::windows, jenkins::node_windows Platform: windows 6.3.9600 Tags: Node Name: 123-windows-2012r2-amd64-builder Environment: _default FQDN: ABC-1234567890AB IP: 123.45.6.78 Run List: role[123-windows-2012r2-amd64-builder] Roles: 123-windows-2012r2-amd64-builder, jenkins Recipes: jenkins::node_windows, git_windows Platform: windows 6.3.9600 Tags: ``` #### NOT To negate search results using the `NOT` boolean operator, enter the following: ``` knife search sample "(NOT id:foo)" ``` to return something like: ``` { "total": 4, "start": 0, "rows": [ { "comment": "an item named bar", "id": "bar", "animal": "cat" }, { "comment": "an item named baz", "id": "baz" "animal": "dog" }, { "comment": "an item named abc", "id": "abc", "animal": "unicorn" }, { "comment": "an item named qux", "id": "qux", "animal", "penguin" } ] } ``` #### OR To join queries using the `OR` boolean operator, enter the following: ``` knife search sample "id:foo OR id:abc" ``` to return something like: ``` { "total": 2, "start": 0, "rows": [ { "comment": "an item named foo", "id": "foo", "animal": "pony" }, { "comment": "an item named abc", "id": "abc", "animal": "unicorn" } ] } ``` ### Special Characters A special character can be used to fine-tune a search query and to increase the accuracy of the search results. The following characters can be included within the search query syntax, but each occurrence of a special character must be escaped with a backslash (`\`), also (`/`) must be escaped against the Elasticsearch: ``` + - && | | ! ( ) { } [ ] ^ " ~ * ? : \ / ``` For example: ``` \(1\+1\)\:2 ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. `-b ROW`, `--start ROW` The row at which return results begin. `-f FILTER`, `--filter-result FILTER` Use to filter the search output based on the pattern that matc the specified `FILTER`. Only attributes in the `FILTER` will returned. For example: `\"ServerName=name, Kernel=kernel.version\`. `-i`, `--id-only` Show only matching object IDs. `INDEX` The name of the index to be queried: `client`, `environment`, `node`, `role`, or `DATA_BAG_NAME`. Default index: `node`. `-l`, `--long` Display all attributes in the output and show the output as JSON. `-m`, `--medium` Display normal attributes in the output and to show the output as JSON. `-q SEARCH_QUERY`, `--query SEARCH_QUERY` Protect search queries that start with a hyphen (-). A `-q` query may be specified as an argument or an option, but not both. `-r`, `--run-list` Show only the run-list. `-R INT`, `--rows INT` The number of rows to be returned. `SEARCH_QUERY` The search query used to identify a list of items on a Chef Infra Server. This option uses the same syntax as the `search` subcommand. Examples -------- The following examples show how to use this knife subcommand: **Search by platform ID** To search for the IDs of all nodes running on the Amazon EC2 platform, enter: ``` knife search node 'ec2:*' -i ``` to return something like: ``` 4 items found ip-0A7CA19F.ec2.internal ip-0A58CF8E.ec2.internal ip-0A58E134.ec2.internal ip-0A7CFFD5.ec2.internal ``` **Search by instance type** To search for the instance type (flavor) of all nodes running on the Amazon EC2 platform, enter: ``` knife search node 'ec2:*' -a ec2.instance_type ``` to return something like: ``` 4 items found ec2.instance_type: m1.large id: ip-0A7CA19F.ec2.internal ec2.instance_type: m1.large id: ip-0A58CF8E.ec2.internal ec2.instance_type: m1.large id: ip-0A58E134.ec2.internal ec2.instance_type: m1.large id: ip-0A7CFFD5.ec2.internal ``` **Search by recipe** To search for recipes that are used by a node, use the `recipes` attribute to search for the recipe names, enter something like: ``` knife search node 'recipes:recipe_name' ``` or: ``` knife search node '*:*' -a recipes | grep 'recipe_name' ``` **Search by cookbook, then recipe** To search for cookbooks on a node, use the `recipes` attribute followed by the `cookbook::recipe` pattern, escaping both of the `:` characters. For example: ``` knife search node 'recipes:cookbook_name\:\:recipe_name' ``` **Search by node** To search for all nodes running Ubuntu, enter: ``` knife search node 'platform:ubuntu' ``` **Search by node and environment** To search for all nodes running CentOS in the production environment, enter: ``` knife search node 'chef_environment:production AND platform:centos' ``` **Search for nested attributes** To find a nested attribute, use a pattern similar to the following: ``` knife search node <query_to_run> -a <main_attribute>.<nested_attribute``` **Search for multiple attributes** To build a search query to use more than one attribute, use an underscore (`_`) to separate each attribute. For example, the following query will search for all nodes running a specific version of Ruby: ``` knife search node "languages_ruby_version:2.7.0" ``` **Search for nested attributes using a search query** To build a search query that can find a nested attribute: ``` knife search node name: <node_name> -a kernel.machine ``` **Use a test query** To test a search query that will be used in a `knife ssh` subcommand: ``` knife search node "role:web NOT name:web03" ``` where the query in the previous example will search all servers that have the `web` role, but not on the server named `web03`. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_search/knife show ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_show.md) Use the `knife show` subcommand to view the details of one (or more) objects on the Chef Infra Server. This subcommand works similar to `knife cookbook show`, `knife data bag show`, `knife environment show`, `knife node show`, and `knife role show`, but with a single verb (and a single action). Syntax ------ This subcommand has the following syntax: ``` knife show [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-a ATTR`, `--attribute ATTR` The attribute (or attributes) to show. `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--local` Show local files instead of remote files. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. `-S SEPARATOR`, `--field-separator SEPARATOR` Character separator used to delineate nesting in –attribute filters. For example, to use a colon as the delimiter, specify `-S:` in your `knife node show` subcommand. Default is `.` Examples -------- The following examples show how to use this knife subcommand: **Show all cookbooks** To show all cookbooks in the `cookbooks/` directory: ``` knife show cookbooks/ ``` or, (if already in the `cookbooks/` directory in the local chef-repo): ``` knife show ``` **Show roles and environments** ``` knife show roles/ environments/ ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_show/knife ssh ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_ssh.md) Use the `knife ssh` subcommand to invoke SSH commands (in parallel) on a subset of nodes within an organization, based on the results of a [search query](../chef_search/index) made to the Chef Infra Server. Syntax ------ This subcommand has the following syntax: ``` knife ssh SEARCH_QUERY SSH_COMMAND (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-a SSH_ATTR`, `--attribute SSH_ATTR` The attribute used when opening an SSH connection. The default attribute is the FQDN of the host. Other possible values include a public IP address, a private IP address, or a hostname. `-A`, `--forward-agent` Enable SSH agent forwarding. `-C NUM`, `--concurrency NUM` The number of allowed concurrent connections. `-e`, `--exit-on-error` Use to exit immediately upon error. `-G GATEWAY`, `--ssh-gateway GATEWAY` The SSH tunnel or gateway that is used to run a bootstrap action on a machine that is not accessible from the workstation. `--ssh-gateway-identity SSH_GATEWAY_IDENTITY` The SSH identity file used to connect to the SSH gateway. *New in Chef Client 13.0.* `-i IDENTITY_FILE`, `--ssh-identity-file IDENTIFY_FILE` The SSH identity file used for authentication. Key-based authentication is recommended. `-m`, `--manual-list` Define a search query as a space-separated list of servers. If there is more than one item in the list, put quotes around the entire list. For example: `--manual-list "server01 server02 server03"` `--[no-]host-key-verify` Use `--no-host-key-verify` to disable host key verification. Default setting: `--host-key-verify`. `OTHER` The shell type. Possible values: `interactive`, `screen`, `tmux`, `macterm`, or `cssh`. (`csshx` is deprecated in favor of `cssh`.) `-p PORT`, `--ssh-port PORT` The SSH port. `-P PASSWORD`, `--ssh-password PASSWORD` The SSH password. This can be used to pass the password directly on the command line. If this option is not specified (and a password is required) knife prompts for the password. `SEARCH_QUERY` The search query used to return a list of servers to be accessed using SSH and the specified `SSH_COMMAND`. This option uses the same syntax as the search subcommand. If the `SEARCH_QUERY` does not contain a colon character (`:`), then the default query pattern is `tags:*#{@query}* OR roles:*#{@query}* OR fqdn:*#{@query}* OR addresses:*#{@query}*`, which means the following two search queries are effectively the same: ``` knife search ubuntu ``` or: ``` knife search node "tags:*ubuntu* OR roles:*ubuntu* OR fqdn:*ubuntu* (etc.)" ``` `SSH_COMMAND` The command to be run against the results of a search query. `-t SECONDS`, `--ssh-timeout SECONDS` The amount of time (in seconds) to wait for an SSH connection time out. `--tmux-split` Split the Tmux window. Default value: `false`. `-x USER_NAME`, `--ssh-user USER_NAME` The SSH user name. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Find server uptime** To find the uptime of all of web servers running Ubuntu on the Amazon EC2 platform, enter: ``` knife ssh "role:web" "uptime" -x ubuntu -a ec2.public_hostname ``` to return something like: ``` ec2-174-129-127-206.compute-1.amazonaws.com 13:50:47 up 1 day, 23:26, 1 user, load average: 0.25, 0.18, 0.11 ec2-67-202-63-102.compute-1.amazonaws.com 13:50:47 up 1 day, 23:33, 1 user, load average: 0.12, 0.13, 0.10 ec2-184-73-9-250.compute-1.amazonaws.com 13:50:48 up 16:45, 1 user, load average: 0.30, 0.22, 0.13 ec2-75-101-240-230.compute-1.amazonaws.com 13:50:48 up 1 day, 22:59, 1 user, load average: 0.24, 0.17, 0.11 ec2-184-73-60-141.compute-1.amazonaws.com 13:50:48 up 1 day, 23:30, 1 user, load average: 0.32, 0.17, 0.15 ``` **Run Chef Infra Client on all nodes** ``` knife ssh 'name:*' 'sudo chef-client' ``` **Force a Chef Infra Client run** To force a Chef Infra Client run on all of the web servers running Ubuntu on the Amazon EC2 platform, enter: ``` knife ssh "role:web" "sudo chef-client" -x ubuntu -a ec2.public_hostname ``` to return something like: ``` ec2-67-202-63-102.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:37 +0000] INFO: Starting Chef Run (Version 0.9.10) ec2-174-129-127-206.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:37 +0000] INFO: Starting Chef Run (Version 0.9.10) ec2-184-73-9-250.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:38 +0000] INFO: Starting Chef Run (Version 0.9.10) ec2-75-101-240-230.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:38 +0000] INFO: Starting Chef Run (Version 0.9.10) ec2-184-73-60-141.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:38 +0000] INFO: Starting Chef Run (Version 0.9.10) ec2-174-129-127-206.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Chef Run complete in 1.419243 seconds ec2-174-129-127-206.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: cleaning the checksum cache ec2-174-129-127-206.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Running report handlers ec2-174-129-127-206.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Report handlers complete ec2-67-202-63-102.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Chef Run complete in 1.578265 seconds ec2-67-202-63-102.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: cleaning the checksum cache ec2-67-202-63-102.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Running report handlers ec2-67-202-63-102.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:39 +0000] INFO: Report handlers complete ec2-184-73-9-250.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Chef Run complete in 1.638884 seconds ec2-184-73-9-250.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: cleaning the checksum cache ec2-184-73-9-250.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Running report handlers ec2-184-73-9-250.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Report handlers complete ec2-75-101-240-230.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Chef Run complete in 1.540257 seconds ec2-75-101-240-230.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: cleaning the checksum cache ec2-75-101-240-230.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Running report handlers ec2-75-101-240-230.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Report handlers complete ec2-184-73-60-141.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Chef Run complete in 1.502489 seconds ec2-184-73-60-141.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: cleaning the checksum cache ec2-184-73-60-141.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Running report handlers ec2-184-73-60-141.compute-1.amazonaws.com [Fri, 22 Oct 2010 14:18:40 +0000] INFO: Report handlers complete ``` **Run a command based on search query** To query for all nodes that have the `webserver` role and then use SSH to run the command `sudo chef-client`, enter: ``` knife ssh "role:webserver" "sudo chef-client" ``` **Upgrade all nodes** ``` knife ssh name:* "sudo aptitude upgrade -y" ``` **Specify the shell type** To specify the shell type used on the nodes returned by a search query: ``` knife ssh roles:opscode-omnitruck macterm ``` where `screen` is one of the following values: `cssh`, `interactive`, `macterm`, `screen`, or `tmux`. If the node does not have the shell type installed, knife will return an error similar to the following: ``` you need the rb-appscript gem to use knife ssh macterm. `(sudo) gem install rb-appscript` to install ERROR: LoadError: cannot load such file -- appscript ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_ssh/knife ssl check =============== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_ssl_check.md) Use the `knife ssl check` subcommand to verify the SSL configuration for the Chef Infra Server or a location specified by a URL or URI. Invalid certificates will not be used by OpenSSL. When this command is run, the certificate files (`*.crt` and/or `*.pem`) that are located in the `/.chef/trusted_certs` directory are checked to see if they have valid X.509 certificate properties. A warning is returned when certificates do not have valid X.509 certificate properties or if the `/.chef/trusted_certs` directory does not contain any certificates. Warning When verification of a remote server’s SSL certificate is disabled, Chef Infra Client will issue a warning similar to “SSL validation of HTTPS requests is disabled. HTTPS connections are still encrypted, but Chef Infra Client is not able to detect forged replies or man-in-the-middle attacks.” To configure SSL for Chef Infra Client, set `ssl_verify_mode` to `:verify_peer` (recommended) **or** `verify_api_cert` to `true` in the client.rb file. Syntax ------ This subcommand has the following syntax: ``` knife ssl check (options) ``` Options ------- This subcommand has the following options: `URL_or_URI` The URL or URI for the location at which the SSL certificate is located. Default value: the URL for the Chef Infra Server, as defined in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **SSL certificate has valid X.509 properties** If the SSL certificate can be verified, the response to ``` knife ssl check ``` is similar to: ``` Connecting to host chef-server.example.com:443 Successfully verified certificates from 'chef-server.example.com' ``` **SSL certificate has invalid X.509 properties** If the SSL certificate cannot be verified, the response to ``` knife ssl check ``` is similar to: ``` Connecting to host chef-server.example.com:443 ERROR: The SSL certificate of chef-server.example.com could not be verified Certificate issuer data: /C=US/ST=WA/L=S/O=Corp/OU=Ops/CN=chef-server.example.com/emailAddress=<EMAIL> Configuration Info: OpenSSL Configuration: * Version: OpenSSL 1.0.2u 20 Dec 2019 * Certificate file: /opt/chef-workstation/embedded/ssl/cert.pem * Certificate directory: /opt/chef-workstation/embedded/ssl/certs Chef SSL Configuration: * ssl_ca_path: nil * ssl_ca_file: nil * trusted_certs_dir: "/Users/grantmc/Downloads/chef-repo/.chef/trusted_certs" TO FIX THIS ERROR: If the server you are connecting to uses a self-signed certificate, you must configure chef to trust that certificate. By default, the certificate is stored in the following location on the host where your Chef Infra Server runs: /var/opt/opscode/nginx/ca/SERVER_HOSTNAME.crt Copy that file to your trusted_certs_dir (currently: /Users/grantmc/Downloads/chef-repo/.chef/trusted_certs) using SSH/SCP or some other secure method, then re-run this command to confirm that the certificate is now trusted. ``` **Verify the SSL configuration for Chef Infra Client** The SSL certificates that are used by Chef Infra Client may be verified by specifying the path to the client.rb file. Use the `--config` option (that is available to any knife command) to specify this path: ``` knife ssl check --config /etc/chef/client.rb ``` **Verify an external server’s SSL certificate** ``` knife ssl check URL_or_URI ``` for example: ``` knife ssl check https://www.chef.io ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_ssl_check/knife ssl_fetch ================ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_ssl_fetch.md) Use the `knife ssl fetch` subcommand to copy SSL certificates from an HTTPS server to the `trusted_certs_dir` directory that is used by knife and Chef Infra Client to store trusted SSL certificates. When these certificates match the hostname of the remote server, running `knife ssl fetch` is the only step required to verify a remote server that is accessed by either knife or Chef Infra Client. Warning It is the user’s responsibility to verify the authenticity of every SSL certificate before downloading it to the `/.chef/trusted_certs` directory. knife will use any certificate in that directory as if it is a 100% trusted and authentic SSL certificate. knife will not be able to determine if any certificate in this directory has been tampered with, is forged, malicious, or otherwise harmful. Therefore it is essential that users take the proper steps before downloading certificates into this directory. Syntax ------ This subcommand has the following syntax: ``` knife ssl fetch (options) ``` Options ------- This subcommand has the following options: `URL_or_URI` The URL or URI for the location at which the SSL certificate is located. Default value: the URL for the Chef Infra Server, as defined in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Fetch the SSL certificates used by Knife from the Chef server** ``` knife ssl fetch ``` The response is similar to: ``` WARNING: Certificates from <chef_server_url> will be fetched and placed in your trusted_cert directory (/Users/grantmc/chef-repo/.chef/trusted_certs). Knife has no means to verify these are the correct certificates. You should verify the authenticity of these certificates after downloading. Adding certificate for <chef_server_url> in /Users/grantmc/chef-repo/.chef/trusted_certs/grantmc.crt Adding certificate for DigiCert Secure Server CA in /Users/grantmc/chef-repo/.chef/trusted_certs/DigiCert_Secure_Server_CA.crt ``` **Fetch SSL certificates from a URL or URI** ``` knife ssl fetch https://www.example.com ``` **Verify Checksums** The SSL certificate that is downloaded to the `/.chef/trusted_certs` directory should be verified to ensure that it is, in fact, the same certificate as the one located on the Chef Infra Server. This can be done by comparing the SHA-256 checksums. 1. View the checksum on the Chef Infra Server: ``` ssh ubuntu@chef-server.example.com sudo sha256sum /var/opt/opscode/nginx/ca/chef-server.example.com.crt ``` The response is similar to: ``` <ABC123checksum> /var/opt/opscode/nginx/ca/chef-server.example.com.crt ``` 2. View the checksum on the workstation: ``` gsha256sum .chef/trusted_certs/chef-server.example.com.crt ``` The response is similar to: ``` <ABC123checksum> .chef/trusted_certs/chef-server.example.com.crt ``` 3. Verify that the checksum values are identical. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_ssl_fetch/knife status ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_status.md) Use the `knife status` subcommand to display a brief summary of the nodes on a Chef Infra Server, including the time of the most recent successful Chef Infra Client run. Syntax ------ This subcommand has the following syntax: ``` knife status (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `QUERY` The search query used to identify a list of items on a Chef Infra Server. This option uses the same syntax as the `search` subcommand. `--hide-by-mins` Hide nodes that have performed a successful Chef Infra Client run within the last specified number of minutes. The number of minutes to hide is provided as an integer, such as `--hide-by-mins 10`. `-l`, `--long` Display all attributes in the output and show the output as JSON. `-m`, `--medium` Display normal attributes in the output and to show the output as JSON. `-r RUN_LIST`, `--run-list RUN_LIST` A comma-separated list of roles and/or recipes to be applied. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **View status, include run-lists** To include run-lists in the status, enter: ``` knife status --run-list ``` to return something like: ``` 20 hours ago, dev-vm.chisamore.com, ubuntu 10.04, dev-vm.chisamore.com, 10.66.44.126, role[lb]. 3 hours ago, i-225f954f, ubuntu 10.04, ec2-67-202-63-102.compute-1.amazonaws.com, 67.202.63.102, role[web]. 3 hours ago, i-a45298c9, ubuntu 10.04, ec2-174-129-127-206.compute-1.amazonaws.com, 174.129.127.206, role[web]. 3 hours ago, i-5272a43f, ubuntu 10.04, ec2-184-73-9-250.compute-1.amazonaws.com, 184.73.9.250, role[web]. 3 hours ago, i-226ca64f, ubuntu 10.04, ec2-75-101-240-230.compute-1.amazonaws.com, 75.101.240.230, role[web]. 3 hours ago, i-f65c969b, ubuntu 10.04, ec2-184-73-60-141.compute-1.amazonaws.com, 184.73.60.141, role[web]. ``` **View status using a time range** To show the status of nodes on which Chef Infra Client did not run successfully within the past hour, enter: ``` knife status --hide-by-mins 60 ``` to return something like: ``` 422492 hours ago, runner-1-432.lxc, centos 6.8. 27 hours ago, union-3-432.lxc, centos 7.3.1611. ``` **View status using a query** To show the status of a subset of nodes that are returned by a specific query, enter: ``` knife status "role:web" --run-list ``` to return something like: ``` 3 hours ago, i-225f954f, ubuntu 10.04, ec2-67-202-63-102.compute-1.amazonaws.com, 67.202.63.102, role[web]. 3 hours ago, i-a45298c9, ubuntu 10.04, ec2-174-129-127-206.compute-1.amazonaws.com, 174.129.127.206, role[web]. 3 hours ago, i-5272a43f, ubuntu 10.04, ec2-184-73-9-250.compute-1.amazonaws.com, 184.73.9.250, role[web]. 3 hours ago, i-226ca64f, ubuntu 10.04, ec2-75-101-240-230.compute-1.amazonaws.com, 75.101.240.230, role[web]. 3 hours ago, i-f65c969b, ubuntu 10.04, ec2-184-73-60-141.compute-1.amazonaws.com, 184.73.60.141, role[web]. ``` **View status for all nodes** To view the status of all nodes in the organization, enter: ``` knife status ``` to return something like: ``` 20 hours ago, dev-vm.chisamore.com, ubuntu 10.04, dev-vm.chisamore.com, 10.66.44.126 3 hours ago, i-225f954f, ubuntu 10.04, ec2-67-202-63-102.compute-1.amazonaws.com, 67.202.63.102 3 hours ago, i-a45298c9, ubuntu 10.04, ec2-174-129-127-206.compute-1.amazonaws.com, 174.129.127.206 3 hours ago, i-5272a43f, ubuntu 10.04, ec2-184-73-9-250.compute-1.amazonaws.com, 184.73.9.250 3 hours ago, i-226ca64f, ubuntu 10.04, ec2-75-101-240-230.compute-1.amazonaws.com, 75.101.240.230 3 hours ago, i-f65c969b, ubuntu 10.04, ec2-184-73-60-141.compute-1.amazonaws.com, 184.73.60.141 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_status/knife tag ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_tag.md) A tag is a custom description that is applied to a node. A tag, once applied, can be helpful when managing nodes using knife or when building recipes by providing alternate methods of grouping similar types of information. Use the `knife tag` subcommand to apply tags to nodes on a Chef Infra Server. Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. create ------ Use the `create` argument to add one or more tags to a node. ### Syntax This argument has the following syntax: ``` knife tag create NODE_NAME [TAG...] ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Create tags** To create tags named `seattle`, `portland`, and `vancouver`, enter: ``` knife tag create node seattle portland vancouver ``` delete ------ Use the `delete` argument to delete one or more tags from a node. ### Syntax This argument has the following syntax: ``` knife tag delete NODE_NAME [TAG...] ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **Delete tags** To delete tags named `denver` and `phoenix`, enter: ``` knife tag delete node denver phoenix ``` Type `Y` to confirm a deletion. list ---- Use the `list` argument to list all of the tags that have been applied to a node. ### Syntax This argument has the following syntax: ``` knife tag list [NODE_NAME...] ``` ### Options This command does not have any specific options. ### Examples The following examples show how to use this knife subcommand: **View a list of tags** To view the tags for a node named `devops_prod1`, enter: ``` knife tag list devops_prod1 ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_tag/knife supermarket ================= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_supermarket.md) The `knife supermarket` subcommand is used to interact with cookbooks that are located in on the public Supermarket as well as private Chef Supermarket sites. A user account is required for any community actions that write data to the Chef Supermarket; however, the following arguments do not require a user account: `download`, `search`, `install`, and `list`. Note Please consider managing community cookbooks using the version of Berkshelf that ships with Chef Workstation. For more information about Chef Workstation, see [About Chef Workstation](../workstation/index). Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. download -------- Use the `download` argument to download a cookbook from Chef Supermarket. A cookbook will be downloaded as a tar.gz archive and placed in the current working directory. If a cookbook (or cookbook version) has been deprecated and the `--force` option is not used, knife will alert the user that the cookbook is deprecated and then will provide the name of the most recent non-deprecated version of that cookbook. ### Syntax This argument has the following syntax: ``` knife supermarket download COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `COOKBOOK_VERSION` The version of a cookbook to be downloaded. If a cookbook has only one version, this option does not need to be specified. If a cookbook has more than one version and this option is not specified, the most recent version of the cookbook is downloaded. `-f FILE`, `--file FILE` The file to which a cookbook download is written. `--force` Overwrite an existing directory. `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. ### Examples The following examples show how to use this knife subcommand: **Download a cookbook** To download the cookbook `mysql`, enter: ``` knife supermarket download mysql ``` install ------- Use the `install` argument to install a cookbook that has been downloaded from Chef Supermarket to a local git repository . This action uses the git version control system in conjunction with Chef Supermarket site to install community-contributed cookbooks to the local chef-repo. Using this argument does the following: 1. A new “pristine copy” branch is created in git for tracking the upstream. 2. All existing versions of a cookbook are removed from the branch. 3. The cookbook is downloaded from Chef Supermarket in the tar.gz format. 4. The downloaded cookbook is untarred and its contents are committed to git and a tag is created. 5. The “pristine copy” branch is merged into the master branch. This process allows the upstream cookbook in the master branch to be modified while letting git maintain changes as a separate patch. When an updated upstream version becomes available, those changes can be merged while maintaining any local modifications. ### Syntax This argument has the following syntax: ``` knife supermarket install COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `-b`, `--use-current-branch` Ensure that the current branch is used. `-B BRANCH`, `--branch BRANCH` The name of the default branch. This defaults to the master branch. `COOKBOOK_VERSION` The version of the cookbook to be installed. If a version is not specified, the most recent version of the cookbook is installed. `-D`, `--skip-dependencies` Ensure that all cookbooks to which the installed cookbook has a dependency are not installed. `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. ### Examples The following examples show how to use this knife subcommand: **Install a cookbook** To install the cookbook `mysql`, enter: ``` knife supermarket install mysql ``` list ---- Use the `list` argument to view a list of cookbooks that are currently available at Chef Supermarket. ### Syntax This argument has the following syntax: ``` knife supermarket list (options) ``` ### Options This argument has the following options: `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. `-w`, `--with-uri` Show the corresponding URIs. ### Examples The following examples show how to use this knife subcommand: **View a list of cookbooks** To view a list of cookbooks at the [Chef Supermarket](https://supermarket.chef.io/cookbooks) server, enter: ``` knife supermarket list ``` to return a list similar to: ``` 1password minecraft 301 mineos 7-zip minidlna AWS_see_spots_run minitest AmazonEC2Tag minitest-handler Appfirst-Cookbook mirage CVE-2014-3566-poodle mlocate CVE-2015-0235 mod_security Obfsproxy mod_security2 R modcloth-hubot Rstats modcloth-nad SysinternalsBginfo modman VRTSralus modules abiquo mogilefs acadock mongodb accel-ppp mongodb-10gen accounts mongodb-agents accumulator monit ... ``` search ------ Use the `search` argument to search for a cookbooks located at Chef Supermarket. A search query is used to return a list of these cookbooks and uses the same syntax as the `knife search` subcommand. ### Syntax This argument has the following syntax: ``` knife supermarket search SEARCH_QUERY (options) ``` ### Options This argument has the following options: `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. ### Examples The following examples show how to use this knife subcommand: **Search for cookbooks** To search for a cookbook, use a command similar to: ``` knife supermarket search mysql ``` where `mysql` is the search term. This will return something similar to: ``` mysql: cookbook: https://supermarket.chef.io/api/v1/cookbooks/mysql cookbook_description: Provides mysql_service, mysql_config, and mysql_client resources cookbook_maintainer: chef cookbook_name: mysql mysql-apt-config: cookbook: https://supermarket.chef.io/api/v1/cookbooks/mysql-apt-config cookbook_description: Installs/Configures mysql-apt-config cookbook_maintainer: tata cookbook_name: mysql-apt-config mysql-multi: cookbook: https://supermarket.chef.io/api/v1/cookbooks/mysql-multi cookbook_description: MySQL replication wrapper cookbook cookbook_maintainer: rackops cookbook_name: mysql-multi ``` share ----- Use the `share` argument to add a cookbook to Chef Supermarket. This action will require a user account and a certificate for [Chef Supermarket](https://supermarket.chef.io/). By default, knife will use the user name and API key that is identified in the configuration file used during the upload; otherwise these values must be specified on the command line or in an alternate configuration file. If a cookbook already exists in Chef Supermarket, then only an owner or maintainer of that cookbook can make updates. ### Syntax This argument has the following syntax: ``` knife supermarket share COOKBOOK_NAME CATEGORY (options) ``` ### Options This argument has the following options: `CATEGORY` The cookbook category: `"Databases"`, `"Web Servers"`, `"Process Management"`, `"Monitoring & Trending"`, `"Programming Languages"`, `"Package Management"`, `"Applications"`, `"Networking"`, `"Operating Systems & Virtualization"`, `"Utilities"`, or `"Other"`. `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. `-o PATH:PATH`, `--cookbook-path PATH:PATH` The directory in which cookbooks are created. This can be a colon-separated path. ### Examples The following examples show how to use this knife subcommand: **Share a cookbook** To share a cookbook named `my_apache2_cookbook` and add it to the `Web Servers` category in Chef Supermarket: ``` knife supermarket share "my_apache2_cookbook" "Web Servers" ``` show ---- Use the `show` argument to view information about a cookbook located at Chef Supermarket. ### Syntax This argument has the following syntax: ``` knife supermarket show COOKBOOK_NAME [COOKBOOK_VERSION] (options) ``` ### Options This argument has the following options: `COOKBOOK_VERSION` The version of a cookbook to be shown. If a cookbook has only one version, this option does not need to be specified. If a cookbook has more than one version and this option is not specified, a list of cookbook versions is returned. `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. ### Examples The following examples show how to use this knife subcommand: **Show cookbook data** To show the details for a cookbook named `mysql`: ``` knife supermarket show mysql ``` to return something similar to: ``` average_rating: category: Other created_at: 2009-10-28T19:16:54.000Z deprecated: false description: Provides mysql_service, mysql_config, and mysql_client resources external_url: https://github.com/chef-cookbooks/mysql issues_url: https://github.com/chef-cookbooks/mysql/issues latest_version: https://supermarket.chef.io/api/v1/cookbooks/mysql/versions/8.5.1 maintainer: sous-chefs metrics: collaborators: 2 downloads: total: 128998032 versions: 0.10.0: 927561 0.15.0: 927536 0.20.0: 927321 0.21.0: 927298 0.21.1: 927311 0.21.2: 927424 0.21.3: 927441 0.21.5: 927326 0.22.0: 927297 0.23.0: 927353 0.23.1: 927862 0.24.0: 927316 ``` **Show cookbook version data** To show the details for a cookbook version, run a command similar to: ``` knife supermarket show mysql 8.5.1 ``` where `mysql` is the cookbook and `8.5.1` is the cookbook version. This will return something similar to: ``` average_rating: cookbook: https://supermarket.chef.io/api/v1/cookbooks/mysql file: https://supermarket.chef.io/api/v1/cookbooks/mysql/versions/8.5.1/download license: Apache-2.0 published_at: 2017-08-23T19:01:28Z quality_metrics: failed: false feedback: passed the No Binaries metric. Contains no obvious binaries. name: No Binaries failed: false feedback: mysql passed the publish metric name: Publish failed: false feedback: mysql supports at least one platform. name: Supported Platforms failed: false feedback: passed the Collaborators Metric with 2 collaborators. name: Collaborator Number failed: false feedback: Run with Foodcritic Version 14.0.0 with tags metadata,correctness ~FC031 ~FC045 and failure tags any name: Foodcritic failed: false feedback: passed the CONTRIBUTING.md file metric. name: Contributing File failed: false feedback: passed the version tag metric. name: Version Tag failed: false feedback: passed the TESTING.md file metric. name: Testing File supports: amazon: >= 0.0.0 centos: >= 6.0 debian: >= 7.0 fedora: >= 0.0.0 opensuseleap: >= 0.0.0 oracle: >= 6.0 redhat: >= 6.0 scientific: >= 6.0 suse: >= 12.0 ubuntu: >= 12.04 tarball_file_size: 23763 version: 8.5.1 ``` unshare ------- Use the `unshare` argument to stop the sharing of a cookbook located at Chef Supermarket. Only the maintainer of a cookbook may perform this action. Note Unsharing a cookbook will break a cookbook that has set a dependency on that cookbook or cookbook version. ### Syntax This argument has the following syntax: ``` knife supermarket unshare COOKBOOK_NAME/versions/VERSION (options) ``` ### Options This argument has the following options: `-m`, `--supermarket-site` The URL at which the Chef Supermarket is located. Default value: `https://supermarket.chef.io`. ### Examples The following examples show how to use this knife subcommand: **Unshare a cookbook** To unshare a cookbook named `my_apache2_cookbook`, enter: ``` knife supermarket unshare "my_apache2_cookbook" "Web Servers" ``` **Unshare a cookbook version** To unshare cookbook version `0.10.0` for the `my_apache2_cookbook` cookbook, enter: ``` knife supermarket unshare "my_apache2_cookbook/versions/0.10.0" ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_supermarket/knife upload ============ [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_upload.md) Use the `knife upload` subcommand to upload data to the Chef Infra Server from the current working directory in the chef-repo. The following types of data may be uploaded with this subcommand: * Cookbooks * Data bags * Roles stored as JSON data * Environments stored as JSON data (Roles and environments stored as Ruby data will not be uploaded.) This subcommand is often used in conjunction with `knife diff`, which can be used to see exactly what changes will be uploaded, and then `knife download`, which does the opposite of `knife upload`. Syntax ------ This subcommand has the following syntax: ``` knife upload [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--[no-]diff` Upload only new and modified files. Set to `false` to upload all files. Default: `true`. `--[no-]force` Use `--force` to upload roles, cookbooks, etc. even if the file in the directory is identical (by default, no `POST` or `PUT` is performed unless an actual change would be made). Default: `--no-force`. `--[no-]freeze` Require changes to a cookbook be included as a new version. Only the `--force` option can override this setting. Default: `false`. `-n`, `--dry-run` Take no action and only print out results. Default: `false`. `--[no-]purge` Use `--purge` to delete roles, cookbooks, etc. from the Chef Infra Server if their corresponding files do not exist in the chef-repo. By default, such objects are left alone and NOT purged. Default: `--no-purge`. `--[no-]recurse` Use `--no-recurse` to disable uploading a directory recursively. Default: `--recurse`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default: `everything` / `hosted_everything`. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Upload the entire chef-repo** Browse to the top level of the chef-repo and enter: ``` knife upload . ``` or from anywhere in the chef-repo, enter: ``` knife upload / ``` to upload all cookbooks and data bags, plus all roles and environments that are stored as JSON data. (Roles and environments stored as Ruby data will not be uploaded.) **Upload the /cookbooks directory** Browse to the top level of the chef-repo and enter: ``` knife upload cookbooks ``` or from anywhere in the chef-repo, enter: ``` knife upload /cookbooks ``` **Upload the /environments directory** Browse to the top level of the chef-repo and enter: ``` knife upload environments ``` or from anywhere in the chef-repo, enter: ``` knife upload /environments ``` to upload all environments that are stored as JSON data. (Environments stored as Ruby data will not be uploaded.) **Upload a single environment** Browse to the top level of the chef-repo and enter: ``` knife upload environments/production.json ``` or from the `environments/` directory, enter: ``` knife upload production.json ``` **Upload the /roles directory** Browse to the top level of the chef-repo and enter: ``` knife upload roles ``` or from anywhere in the chef-repo, enter: ``` knife upload /roles ``` to upload all roles that are stored as JSON data. (Roles stored as Ruby data will not be uploaded.) **Upload cookbooks and roles** Browse to the top level of the chef-repo and enter: ``` knife upload cookbooks/apache\* roles/webserver.json ``` **Use output of knife deps to pass command to knife upload** ``` knife upload `knife deps nodes/*.json` ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_upload/knife user ========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_user.md) Use the `knife user` subcommand to manage the list of users and their associated RSA public key-pairs. Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. create ------ Use the `create` argument to create a user. This process will generate an RSA key pair for the named user. The public key will be stored on the Chef Infra Server and the private key will be displayed on `STDOUT` or written to a named file. * For the user, the private key should be copied to the system as `/etc/chef/client.pem`. * For knife, the private key is typically copied to `~/.chef/client_name.pem` and referenced in the config.rb configuration file. ### Syntax This argument has the following syntax: ``` knife user create USERNAME DISPLAY_NAME FIRST_NAME LAST_NAME EMAIL PASSWORD (options) ``` ### Options This argument has the following options: `-f FILE`, `--file FILE` Save a private key to the specified file name. `--password PASSWORD` The user password. `--user-key FILENAME` The path to a file that contains the public key. If this option is not specified, the Chef Infra Server will generate a public/private key pair. `-k`, `--prevent-keygen` :Prevent Chef Infra Server from generating a default key pair for you. Cannot be passed with –user-key. `-o ORGNAME` `--orgname ORGNAME` :Associate new user to an organization matching ORGNAME `--first-name FIRST_NAME` :First name for the user `--last-name LAST_NAME` :Last name for the user `--email EMAIL` :Email for the user `--prompt-for-password`, `-p` :Prompt for user password Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Create a user** ``` knife user create tbucatar "<NAME>" <EMAIL> -f /keys/tbucatar ``` ``` knife user create arno arno schmidt <EMAIL> password -----BEGIN RSA PRIVATE KEY----- [...] -----END RSA PRIVATE KEY----- ``` delete ------ Use the `delete` argument to delete a registered user. ### Syntax This argument has the following syntax: ``` knife user delete USER_NAME ``` ### Options `--no-disassociate-user`, `-d` :Don’t disassociate the user first `"--remove-from-admin-groups`, `-R` :If the user is a member of any org admin groups, attempt to remove from those groups. Ignored if –no-disassociate-user is set. ### Examples The following examples show how to use this knife subcommand: **Delete a user** ``` knife user delete "<NAME>" ``` edit ---- Use the `edit` argument to edit the details of a user. When this argument is run, knife will open $EDITOR. When finished, knife will update the Chef Infra Server with those changes. ### Syntax This argument has the following syntax: ``` knife user edit USER_NAME ``` ### Options `--input FILENAME`, `-i FILENAME` :Name of file to use for PUT or POST `--filename FILENAME`, `-f FILENAME` :Write private key to FILENAME rather than STDOUT ### Examples ``` EDITOR=ed knife user edit arno 639 1,%p { "username": "arno", "email": "<EMAIL>", "display_name": "<NAME>", "first_name": "arno", "last_name": "schmidt", "middle_name": "", "public_key": "-----BEGIN PUBLIC KEY-----\n[...]\n-----END PUBLIC KEY-----\n\n" } /email/s/chef.io/opscode.com/p "email": "<EMAIL>", wq 643 Saved arno. knife user show arno display_name: <NAME> email: <EMAIL> first_name: arno last_name: schmidt middle_name: public_key: -----BEGIN PUBLIC KEY----- [...] -----END PUBLIC KEY----- username: arno ``` list ---- Use the `list` argument to show list of all registered users. ### Syntax This argument has the following syntax: ``` knife user list ``` ### Options `-w`, `--with-uri`, :Show corresponding URIs. ### Examples The following examples show how to use this knife subcommand: ``` knife user list alice pivotal knife user list -w alice: https://chef-server.fqdn/users/alice pivotal: https://chef-server.fqdn/users/pivotal knife org list -w -a acme: https://chef-server.fqdn/organizations/acme ``` password -------- Command for managing password and authentication for a user. ### Syntax This argument has the following syntax: ``` knife user password USER_NAME [PASSWORD | ] ``` ### Options `--enable_external_auth`, :Enable external authentication for this user (such as LDAP). ### Examples The following examples show how to use this knife subcommand: ``` knife user password arno newpassword {"username"=>"arno", "email"=>"<EMAIL>", "display_name"=>"<NAME>", "first_name"=>"arno", "last_name"=>"schmidt", "middle_name"=>"", "public_key"=>"-----BEGIN PUBLIC KEY-----\n[...]\n-----END PUBLIC KEY-----\n\n", "password"=>"newpassword", "recovery_authentication_enabled"=>true} Authentication info updated for arno. ``` key create ---------- Use the `key create` argument to create a public key. ### Syntax This argument has the following syntax: ``` knife user key create USER_NAME (options) ``` ### Options This argument has the following options: `-e DATE`, `--expiration-date DATE` The expiration date for the public key, specified as an ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. If this option is not specified, the public key will not have an expiration date. For example: `2013-12-24T21:00:00Z`. `-f FILE`, `--file FILE` Save a private key to the specified file name. `-k NAME`, `--key-name NAME` The name of the public key. `-p FILE_NAME`, `--public-key FILE_NAME` The path to a file that contains the public key. If this option is not specified, and only if `--key-name` is specified, the Chef Infra Server will generate a public/private key pair. ### Examples None. key delete ---------- Use the `key delete` argument to delete a public key. ### Syntax This argument has the following syntax: ``` knife user key delete USER_NAME KEY_NAME ``` ### Examples None. key edit -------- Use the `key edit` argument to modify or rename a public key. ### Syntax This argument has the following syntax: ``` knife user key edit USER_NAME KEY_NAME (options) ``` ### Options This argument has the following options: `-c`, `--create-key` Generate a new public/private key pair and replace an existing public key with the newly-generated public key. To replace the public key with an existing public key, use `--public-key` instead. `-e DATE`, `--expiration-date DATE` The expiration date for the public key, specified as an ISO 8601 formatted string: `YYYY-MM-DDTHH:MM:SSZ`. If this option is not specified, the public key will not have an expiration date. For example: `2013-12-24T21:00:00Z`. `-f FILE`, `--file FILE` Save a private key to the specified file name. If the `--public-key` option is not specified the Chef Infra Server will generate a private key. `-k NAME`, `--key-name NAME` The name of the public key. `-p FILE_NAME`, `--public-key FILE_NAME` The path to a file that contains the public key. If this option is not specified, and only if `--key-name` is specified, the Chef Infra Server will generate a public/private key pair. ### Examples None. key list -------- Use the `key list` argument to view a list of public keys for the named user. ### Syntax This argument has the following syntax: ``` knife user key list USER_NAME (options) ``` ### Options This argument has the following options: `-e`, `--only-expired` Show a list of public keys that have expired. `-n`, `--only-non-expired` Show a list of public keys that have not expired. `-w`, `--with-details` Show a list of public keys, including URIs and expiration status. ### Examples None. key show -------- Use the `key show` argument to view details for a specific public key. ### Syntax This argument has the following syntax: ``` knife user key show USER_NAME KEY_NAME ``` ### Examples None. list ---- Use the `list` argument to view a list of registered users. ### Syntax This argument has the following syntax: ``` knife user list (options) ``` ### Options This argument has the following options: `-w`, `--with-uri` Show the corresponding URIs. ### Examples None. reregister ---------- Use the `reregister` argument to regenerate an RSA key pair for a user. The public key will be stored on the Chef Infra Server and the private key will be displayed on `STDOUT` or written to a named file. Note Running this argument will invalidate the previous RSA key pair, making it unusable during authentication to the Chef Infra Server. ### Syntax This argument has the following syntax: ``` knife user reregister USER_NAME (options) ``` ### Options This argument has the following options: `-f FILE_NAME`, `--file FILE_NAME` Save a private key to the specified file name. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. ### Examples The following examples show how to use this knife subcommand: **Regenerate the RSA key-pair** ``` knife user reregister "<NAME>" ``` show ---- Use the `show` argument to show the details of a user. ### Syntax This argument has the following syntax: ``` knife user show USER_NAME (options) ``` ### Options This argument has the following options: `--with-orgs`, `-l` Show the organizations of which the user is a member. ### Examples The following examples show how to use this knife subcommand: **Show user data** To view a user named `<NAME>`, enter: ``` knife user show "<NAME>" ``` to return something like: ``` chef_type: user json_class: Chef::User name: <NAME> public_key: ``` ``` knife user show alice -l display_name: <NAME> email: <EMAIL> first_name: Alice last_name: Schmidt middle_name: organizations: acme public_key: -----BEGIN PUBLIC KEY----- [...] -----END PUBLIC KEY----- username: alice ``` **Show user data as JSON** To view information in JSON format, use the `-F` common option as part of the command like this: ``` knife user show "Tamira Bucatar" -F json ``` (Other formats available include `text`, `yaml`, and `pp`, e.g. `-F yaml` for YAML.) © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_user/Backup and Restore a Standalone or Frontend install =================================================== [[edit on GitHub]](https://github.com/chef/chef-server/blob/main/docs-chef-io/content/server/server_backup_restore.md) Periodic backups of Chef Infra Server data are an essential part of managing and maintaining a healthy configuration and ensuring that important data can be restored, if required. The backup takes around 4 to 5 minutes per GB of data on a t3.2xlarge AWS EC2 instance. chef-server-ctl --------------- For the majority of use cases, `chef-server-ctl backup` is the recommended way to take backups of the Chef Infra Server. Use the following commands for managing backups of Chef Infra Server data, and for restoring those backups. ### backup The `backup` subcommand is used to back up all Chef Infra Server data. This subcommand: * Requires rsync to be installed on the Chef Infra Server prior to running the command * Requires a `chef-server-ctl reconfigure` prior to running the command * Should not be run in a Chef Infra Server configuration with an external PostgreSQL database; [use knife ec backup](https://github.com/chef/knife-ec-backup) instead * Puts the initial backup in the `/var/opt/chef-backup` directory as a tar.gz file; move this backup to a new location for safe keeping **Options** This subcommand has the following options: `-y`, `--yes` Use to specify if the Chef Infra Server can go offline during tar.gz-based backups. `--pg-options` Use to specify and pass additional options PostgreSQL during backups. See the [PostgreSQL documentation](https://www.postgresql.org/docs/13/runtime-config.html) for more information. `-c`, `--config-only` Backup the Chef Infra Server configuration **without** backing up data. `-t`, `--timeout` Set the maximum amount of time in seconds to wait for shell commands (default 600). This option should be set to greater than 600 for backups taking longer than 10 minutes. `-h`, `--help` Show help message. **Syntax** This subcommand has the following syntax: ``` chef-server-ctl backup ``` ### restore The `restore` subcommand is used to restore Chef Infra Server data from a backup that was created by the `backup` subcommand. This subcommand may also be used to add Chef Infra Server data to a newly-installed server. Do not run this command in a Chef Infra Server configuration that uses an external PostgreSQL database; [use knife ec backup](https://github.com/chef/knife-ec-backup) instead. This subcommand: * Requires rsync installed on the Chef Infra Server before running the command * Requires a `chef-server-ctl reconfigure` before running the command Ideally, the restore server will have the same FQDN as the server that you backed up. If the restore server has a different FQDN, then: 1. Replace the FQDN in the `/etc/opscode/chef-server.rb`. 2. Replace the FQDN in the `/etc/opscode/chef-server-running.json`. 3. Delete the old SSL certificate, key and `-ssl.conf` file from `/var/opt/opscode/nginx/ca`. 4. If you use a CA-issued certificate instead of a self-signed certificate, copy the CA-issued certificate and key into `/var/opt/opscode/nginx/ca`. 5. Update the `/etc/chef/client.rb` file on each client to point to the new server FQDN. 6. Run `chef-server-ctl reconfigure`. 7. Run ``chef-server-ctl restore`. **Options** This subcommand has the following options: `-c`, `--cleanse` Use to remove all existing data on the Chef Infra Server; it will be replaced by the data in the backup archive. `-d DIRECTORY`, `--staging-dir DIRECTORY` Use to specify that the path to an empty directory to be used during the restore process. This directory must have enough disk space to expand all data in the backup archive. `--pg-options` ``` : Use to specify and pass additional options PostgreSQL during backups. See the [PostgreSQL documentation](https://www.postgresql.org/docs/13/runtime-config.html) for more information. `-t`, `--timeout` : Set the maximum amount of time in seconds to wait for shell commands. Set to greater than 600 for backups that take longer than 10 minutes. Default: 600. `-h`, `--help` : Show help message. **Syntax** This subcommand has the following syntax: ```bash chef-server-ctl restore PATH_TO_BACKUP (options) ``` **Examples** ``` chef-server-ctl restore /path/to/tar/archive.tar.gz ``` Backup and restore a Chef Backend install ----------------------------------------- Warning Chef Backend is [deprecated](../../versions/index#deprecated-products-and-versions) and no longer under active development. Contact your Chef account representative for information about migrating to Chef Automate HA. This document is no longer maintained. In a disaster recovery scenario, the backup and restore processes allow you to restore a data backup into a newly built cluster. It is not intended for the recovery of an individual machine in the chef-backend cluster or for a point-in-time rollback of an existing cluster. ### Backup Restoring your data in the case of an emergency depends on having previously made backups of: * the data in your Chef Backend cluster * the configuration from your Chef server To make backups for future use in disaster scenarios: 1. On a follower chef-backend node, run `chef-backend-ctl backup` 2. On a Chef Infra Server node run: `chef-server-ctl backup --config-only` 3. Move the tar archives created in steps (1) and (2) to a long-term storage location. ### Restore To restore a Chef Backend-based Chef Infra Server cluster: 1. Restore the node and an IP address that can be used to reach the node on the first machine that you want to use in your new Chef Backend cluster. The argument to the `--publish_address` option should be the IP address for reaching the node you are restoring. ``` chef-backend-ctl restore --publish_address X.Y.Z.W /path/to/backup.tar.gz ``` 2. Join additional nodes to your Chef Backend cluster. (If you are only testing and verifying your restore process you can test against a single Chef Backend node and a single Chef Infra Server node.) ``` chef-backend-ctl join-cluster IP_OF_FIRST_NODE --publish_address IP_OF_THIS_NODE ``` 3. Restore Chef Infra Server from your backed up Infra Server configuration (See step 2 in the backup instructions above). Alternatively, you can generate new configuration for this node and reconfigure it using the steps found in [the installation instructions.](../../server/install_server_ha/index#step-5-install-and-configure-first-frontend). ``` chef-server-ctl restore /path/to/chef-server-backup.tar.gz ``` 4. Run the `reindex` command to re-populate your search index ``` chef-server-ctl reindex --all ``` ### Verify We recommend periodically verifying your backup by restoring a single Chef Backend node, a single Chef Infra Server node, and ensuring that various knife commands and Chef Infra Client runs can successfully complete against your backup. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/runbook/server_backup_restore/knife xargs =========== [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/knife_xargs.md) Use the `knife xargs` subcommand to take patterns from standard input, download as JSON, run a command against the downloaded JSON, and then upload any changes. Syntax ------ This subcommand has the following syntax: ``` knife xargs [PATTERN...] (options) ``` Options ------- Note Review the list of [common options](../workstation/knife_options/index) available to this (and all) knife subcommands and plugins. This subcommand has the following options: `-0` Default: `false`. `--chef-repo-path PATH` The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by `chef_repo_path` in client.rb. `--concurrency` The number of allowed concurrent connections. Default: `10`. `--[no-]diff` Show a diff when a file changes. Default: `--diff`. `--dry-run` Prevent changes from being uploaded to the Chef Infra Server. Default: `false`. `--[no-]force` Force the upload of files even if they haven’t been changed. Default: `--no-force`. `-I REPLACE_STRING`, `--replace REPLACE_STRING` Define a string that is to be used to replace all occurrences o file name. Default: `nil`. `-J REPLACE_STRING`, `--replace-first REPLACE_STRING` Define a string that is to be used to replace the first occurrence of a file name. Default: `nil`. `--local` Build or execute a command line against a local file. Set to `false` to build or execute against a remote file. Default: `false`. `-n MAX_ARGS`, `--max-args MAX_ARGS` The maximum number of arguments per command line. Default: `nil`. `-p [PATTERN...]`, `--pattern [PATTERN...]` One (or more) patterns for a command line. If this option is not specified, a list of patterns may be expected on standard input. Default: `nil`. `--repo-mode MODE` The layout of the local chef-repo. Possible values: `static`, `everything`, or `hosted_everything`. Use `static` for just roles, environments, cookbooks, and data bags. By default, `everything` and `hosted_everything` are dynamically selected depending on the server type. Default value: `default`. `-s LENGTH`, `--max-chars LENGTH` The maximum size (in characters) for a command line. Default: `nil`. `-t` Run the print command on the command line. Default: `nil`. Note See [config.rb](../workstation/config_rb_optional_settings/index) for more information about how to add certain knife options as settings in the config.rb file. Examples -------- The following examples show how to use this knife subcommand: **Find, and then replace data** The following example will go through all nodes on the server, and then replace the word `foobar` with `baz`: ``` knife xargs --pattern /nodes/* "perl -i -pe 's/foobar/baz'" ``` **Use output of knife list and Perl** The following examples show various ways of listing all nodes on the server, and then using Perl to replace `grantmc` with `gmc`: ``` knife list 'nodes/*' | knife xargs "perl -i -pe 's/grantmc/gmc'" ``` or without quotes and the backslash escaped: ``` knife list /nodes/\* | knife xargs "perl -i -pe 's/grantmc/gmc'" ``` or by using the `--pattern` option: ``` knife xargs --pattern '/nodes.*' "perl -i -pe 's/grantmc/gmc'" ``` **View security groups data** The following example shows how to display the content of all groups on the server: ``` knife xargs --pattern '/groups/*' cat ``` and will return something like: ``` { "name": "4bd14db60aasdfb10f525400cdde21", "users": [ "grantmc" ] }{ "name": "62c4e268e15fasdasc525400cd944b", "users": [ "robertf" ] }{ "name": "admins", "users": [ "grantmc", "robertf" ] }{ "name": "billing-admins", "users": [ "dtek" ] }{ "name": "clients", "clients": [ "12345", "67890", ] }{ "name": "users", "users": [ "grantmc" "robertf" "dtek" ], "groups": [ "4bd14db60aasdfb10f525400cdde21", "62c4e268e15fasdasc525400cd944b" ] } ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/knife_xargs/Install Private Supermarket =========================== [[edit on GitHub]](https://github.com/chef/supermarket/blob/main/docs-chef-io/content/supermarket/install_supermarket.md) The source code for Chef Supermarket is located at the following URLs: * The application itself: <https://github.com/chef/supermarket>. Report issues to: <https://github.com/chef/supermarket/issues>. * The cookbook that is run by the `supermarket-ctl reconfigure` command: <https://github.com/chef/supermarket/tree/main/omnibus/cookbooks/omnibus-supermarket Requirements ------------ A private Chef Supermarket has the following requirements: * An working Chef Infra Server, which acts as the OAuth 2.0 provider * A user account on the Chef Infra Server with `admins` privileges * A key for the user account on the Chef server * An x86_64 compatible Linux host with at least 2 GB memory * System clocks synchronized on the Chef Infra Server and Supermarket hosts * Sufficient disk space on host to meet project cookbook storage capacity **or** credentials to store cookbooks in an Amazon Simple Storage Service (S3) bucket **Considerations with regard to storage capacity:** * PostgreSQL database size will grow linearly based on the number of cookbooks and the number of cookbook versions published * Redis database size is negligible as it is used only for background job queuing, and to cache a small number of API responses * Cookbook storage growth is entirely dependent on the size of the cookbooks published. Cookbooks that include binaries or other large files will consume more space than code-only cookbooks * Opting to run a private Supermarket with off-host PostgreSQL, Redis, and cookbook store is less a decision about storage sizing; it is about data service uptime, backup, and restore procedure for your organization * As a point of reference: as of May 2021 after six years of operation, the public Supermarket has approx 83,000 users, 4,000 cookbooks with a total of 27,000 versions published. The PostgreSQL database is 435 MB, and the S3 bucket containing the published community cookbooks is 3.1 GB Chef Identity ------------- Chef Identity (also referred to as **oc-id**) is an OAuth 2.0 authentication and authorization service packaged with the Chef Infra Server. Chef Identity must be configured to run with a private Chef Supermarket, after which users may use the same credentials to access the Chef Supermarket as they do to access the Chef Infra Server. Note The Chef Supermarket server must be able to reach (via HTTPS) the specified `chef_server_url` during OAuth 2.0 negotiation. This type of issue is typically with name resolution and firewall rules. ### Configure To configure Chef Supermarket to use Chef Identity, do the following: 1. Log on to the Chef Infra Server via SSH and elevate to an admin-level user. If running a multi-node Chef Infra Server cluster, log on to the node acting as the primary node in the cluster. 2. Update the `/etc/opscode/chef-server.rb` configuration file. To define OAuth 2 information for Chef Supermarket, create a Hash similar to: ``` oc_id['applications'] ||= {} oc_id['applications']['supermarket'] = { 'redirect_uri' => 'https://supermarket.mycompany.com/auth/chef_oauth2/callback', } ``` 3. Reconfigure the Chef Infra Server. ``` sudo chef-server-ctl reconfigure ``` 4. Retrieve Supermarket’s OAuth 2.0 client credentials: Depending on your Chef Infra Server version and configuration (see [chef-server.rb](../server/config_rb_server_optional_settings/index#config-rb-server-insecure-addon-compat)), this can be retrieved via [chef-server-ctl oc-id-show-app supermarket](../ctl_chef_server/index#ctl-chef-server-oc-id-show-app) or is located in `/etc/opscode/oc-id-applications/supermarket.json`: ``` { "name": "supermarket", "uid": "0bad0f2eb04e935718e081fb71asdfec3681c81acb9968a8e1e32451d08b", "secret": "17cf1141cc971a10ce307611beda7ffadstr4f1bc98d9f9ca76b9b127879", "redirect_uri": "https://supermarket.mycompany.com/auth/chef_oauth2/callback" } ``` The `uid` and `secret` values will be needed later on during the setup process for Chef Supermarket. Note Add as many Chef Identity applications to the `/etc/opscode/chef-server.rb` configuration file as necessary. A JSON file is generated for each application added, which contains the authentication tokens for that application. The secrets are added to the Chef Identity database and are available to all nodes in the Chef Infra Server front end group. The generated JSON files do not need to be copied anywhere. Note The redirect URL specified **MUST** match the FQDN of the Chef Supermarket server. The URI must also be correct: `/auth/chef_oauth2/callback`. Otherwise, an error message similar to `The redirect uri included is not valid.` will be shown. Install Supermarket ------------------- To install a private Chef Supermarket use the `supermarket-omnibus-cookbook`. This cookbook is [available from the public](https://supermarket.chef.io/cookbooks/supermarket-omnibus-cookbook) Chef Supermarket. * The `supermarket-omnibus-cookbook` cookbook is attribute-driven; use a custom cookbook to specify your organization’s unique `node[supermarket_omnibus]` attribute values. * The custom cookbook is a wrapper around `supermarket-omnibus-cookbook`, which performs the actual installation of the Chef Supermarket packages, and then writes the custom `node[supermarket_omnibus]` values to `/etc/supermarket/supermarket.json`. * The Chef Supermarket package itself contains an internal cookbook which configures the already-installed package using the attributes defined in `/etc/supermarket/supermarket.json`. Note In general, for production environments Chef recommends to start running Chef Supermarket with small virtual machines, and then increase the size of the virtual machine as necessary. Put the `/var/opt/supermarket` directory on a separate disk, and then use LVM so that may be expanded. ### Create a Wrapper A wrapper cookbook is used to define project- and/or organization-specific requirements around a community cookbook. ![Diagram showing a wrapper cookbook containing a private Supermarket.] In the case of installing a private Chef Supermarket, Chef recommends the use of a wrapper cookbook to specify certain attributes that are unique to your organization, while enabling the use of the generic installer cookbook which, in turn, installs the Chef Supermarket package behind your firewall. All of the keys under `node['supermarket_omnibus']` are written out as `/etc/supermarket/supermarket.json`. Add other keys as needed to override the default attributes specified in the Chef Supermarket [omnibus package](https://github.com/chef/supermarket/blob/main/omnibus/cookbooks/omnibus-supermarket/attributes/default.rb). For example: ``` default['supermarket_omnibus']['chef_server_url'] = 'https://chefserver.mycompany.com:443' default['supermarket_omnibus']['chef_oauth2_app_id'] = '14dfcf186221781cff51eedd5ac1616' default['supermarket_omnibus']['chef_oauth2_secret'] = 'a49402219627cfa6318d58b13e90aca' default['supermarket_omnibus']['chef_oauth2_verify_ssl'] = false default['supermarket_omnibus']['fqdn'] = 'supermarket.mycompany.com' ``` On your workstation, generate a new cookbook using the `chef` command line interface: 1. Generate the cookbook: ``` chef generate cookbook my_supermarket_wrapper ``` 2. Change directories into that cookbook: ``` cd my_supermarket_wrapper ``` 3. Defines the wrapper cookbook’s dependency on the `supermarket-omnibus-cookbook` cookbook. Open the metadata.rb file of the newly-created cookbook, and then add the following line: ``` depends 'supermarket-omnibus-cookbook' ``` 4. Save and close the metadata.rb file. 5. Open the `/recipes/default.rb` recipe located within the newly-generated cookbook and add the following content: ``` include_recipe 'supermarket-omnibus-cookbook' ``` This ensures that the `default.rb` file in the `supermarket-omnibus-cookbook` is run. ### Define Attributes Define the attributes for the Chef Supermarket installation and how it connects to the Chef Infra Server. One approach would be to hard-code attributes in the wrapper cookbook’s `default.rb` recipe. A better approach is to place these attributes in a data bag, and then reference them from the recipe. For example, the data bag could be named `apps` and then a data bag item within the data bag could be named `supermarket`. The following attribute values must be defined: * `chef_server_url` * `chef_oauth2_app_id` * `chef_oauth2_secret` Once configured, you can get the `chef_oauth2_app_id` and `chef_oauth2_secret` values from your Chef Infra Server within `/etc/opscode/oc-id-applications/supermarket.json`: For `chef_server_url`, enter in the URL of your chef server. For `chef_oauth2_app_id`, enter in the uid from `/etc/opscode/oc-id-applications/supermarket.json` For `chef_oauth2_secret`, enter in the secret from `/etc/opscode/oc-id-applications/supermarket.json` To define these attributes, do the following: 1. Open the `/recipes/default.rb` file and add the following, **BEFORE** the `include_recipe` line that was added in the previous step. This example uses a data bag named `apps` and a data bag item named `supermarket`: ``` app = data_bag_item('apps', 'supermarket') ``` 2. Set the attributes from the data bag: ``` node.override['supermarket_omnibus']['chef_server_url'] = app['chef_server_url'] node.override['supermarket_omnibus']['chef_oauth2_app_id'] = app['chef_oauth2_app_id'] node.override['supermarket_omnibus']['chef_oauth2_secret'] = app['chef_oauth2_secret'] ``` When finished, the `/recipes/default.rb` file should have code similar to: ``` app = data_bag_item('apps', 'supermarket') node.override['supermarket_omnibus']['chef_server_url'] = app['chef_server_url'] node.override['supermarket_omnibus']['chef_oauth2_app_id'] = app['chef_oauth2_app_id'] node.override['supermarket_omnibus']['chef_oauth2_secret'] = app['chef_oauth2_secret'] include_recipe 'supermarket-omnibus-cookbook' ``` 3. Save and close the `/recipes/default.rb` file. Note If you are running your private Supermarket in AWS, you may need to set an additional attribute for the node’s public IP address: ``` node.override['supermarket_omnibus']['config']['fqdn'] = your_node_public_ip ``` ### Upload the Wrapper The wrapper cookbook around the `supermarket-omnibus-cookbook` cookbook must be uploaded to the Chef Infra Server, along with any cookbooks against which the `supermarket-omnibus-cookbook` cookbook has dependencies. To upload the cookbooks necessary to install Chef Supermarket, do the following: 1. Install Berkshelf: ``` berks install ``` 2. Change directories into `~/.berkshelf/cookbooks`: ``` cd ~/.berkshelf/cookbooks ``` 3. Upload all cookbooks to the Chef Infra Server: ``` knife cookbook upload -a ``` 4. Change directories into the location in which the wrapper cookbook was created: ``` cd path/to/wrapper/cookbook/ ``` 5. Upload the wrapper cookbook to the Chef Infra Server: ``` knife cookbook upload -a ``` ### Bootstrap Supermarket Bootstrap the node on which Chef Supermarket is to be installed. For example, to bootstrap a node running Ubuntu on Amazon Web Services (AWS), the command is similar to: ``` knife bootstrap ip_address -N supermarket-node -x ubuntu --sudo ``` where * `-N` defines the name of the Chef Supermarket node: `supermarket-node` * `-x` defines the (ssh) user name: `ubuntu` * `--sudo` ensures that sudo is used while running commands on the node during the bootstrap operation When the bootstrap operation is finished, do the following: 1. Edit the node to add the wrapper cookbook’s `/recipes/default.rb` recipe to the run-list: ``` knife node edit supermarket-node ``` where `supermarket-node` is the name of the node that was just bootstrapped. 2. Add the recipe to the run-list: ``` "run_list": [ "recipe[my_supermarket_wrapper::default]" ] ``` 3. Start Chef Infra Client on the newly-bootstrapped Chef Supermarket node. For example, using SSH: ``` ssh ubuntu@your-supermarket-node-public-dns ``` 4. After accessing the Chef Supermarket node, run Chef Infra Client: ``` sudo chef-client ``` Install Supermarket Directly (without a cookbook) ------------------------------------------------- While there are many benefits to using the cookbook method to install Supermarket, there are also cases where it’s simpler to set up the Supermarket installation manually. These steps will walk you through the process of manually configuring your private Supermarket server. Before following these steps, be sure to complete the OAuth setup process detailed in the [Chef Identity](index#chef-identity) section of this guide. 1. [Download](https://www.chef.io/downloads/tools/supermarket) the correct package for your operating system from `chef.io/downloads`. 2. Install Supermarket using the appropriate package manager for your distribution: * For Ubuntu: ``` dpkg -i /path/to/package/supermarket*.deb ``` * For RHEL / CentOS: ``` rpm -Uvh /path/to/package/supermarket*.rpm ``` 3. Run the `reconfigure` command to complete the initial installation: ``` sudo supermarket-ctl reconfigure ``` 4. Create an `/etc/supermarket/supermarket.json` file and add the following information, substituting the values for each configuration option with the OAuth 2.0 client credentials that were created in the [previous section](index#chef-identity): ``` { "chef_server_url": "https://chefserver.mycompany.com", "chef_oauth2_app_id": "0bad0f2eb04e935718e081fb71asdfec3681c81acb9968a8e1e32451d08b", "chef_oauth2_secret": "17cf1141cc971a10ce307611beda7ffadstr4f1bc98d9f9ca76b9b127879", "fqdn": "supermarket.mycompany.com", "chef_oauth2_verify_ssl": false } ``` Where: * `"chef_server_url"` should contain the FQDN of your Chef Infra Server. Note that if you’re using a non-standard SSL port, this much be appended to the URL. For example: `https://chefserver.mycompany.com:65400` * `"chef_oauth2_app_id"` should contain the `"uid"` value from your OAuth credentials * `"chef_oauth2_secret"` should contain the `"secret"` value from your OAuth credentials * `chef_oauth2_verify_ssl` is set to false, which is necessary when using a self-signed certificate without a properly configured certificate authority * `fqdn` should contain the desired URL that will be used to access your private Supermarket. If not specified, this default to the FQDN of the machine 5. Issue another `reconfigure` command to apply your changes: ``` sudo supermarket-ctl reconfigure ``` Connect to Supermarket ---------------------- To reach the newly spun up private Chef Supermarket, the hostname must be resolvable from a workstation. For production use, the hostname should have a DNS entry in an appropriate domain that is trusted by each user’s workstation. 1. Visit the Chef Supermarket hostname in the browser. A private Chef Supermarket will generate and use a self-signed certificate, if a certificate is not supplied as part of the installation process (via the wrapper cookbook). 2. If an SSL notice is shown while connecting to Chef Supermarket via a web browser, accept the SSL certificate. A trusted SSL certificate should be used for private Chef Supermarket that is used in production. 3. After opening Chef Supermarket in a web browser, click the **Create Account** link. A prompt to log in to the Chef Infra Server is shown, but only if the user is not already logged in. Authorize the Chef Supermarket to use the Chef Infra Server account for authentication. Note The redirect URL specified for Chef Identity **MUST** match the fqdn hostname of the Chef Supermarket server. The URI must also be correct: `/auth/chef_oauth2/callback`. Otherwise, an error message similar to `The redirect uri included is not valid.` will be shown. Customize Supermarket --------------------- Chef Supermarket is a Ruby on Rails application with a PostgreSQL database. The private Chef Supermarket configuration may be scaled-out, such as using an external database, using an external cache, and using an external cookbook storage location. ### External Database A Chef Supermarket installation can use an external database running PostgreSQL (9.3 or higher) and with the `pgpsql` and `pg_trgm` installed and loaded. The public Chef Supermarket uses Amazon Relational Database Service (RDS). To use an external database, configure the following attributes in the `/recipes/default.rb` recipe of the wrapper cookbook: ``` node.override['supermarket_omnibus']['config']['postgresql']['enable'] = false node.override['supermarket_omnibus']['config']['database']['user'] = 'supermarket' node.override['supermarket_omnibus']['config']['database']['name'] = 'supermarket' node.override['supermarket_omnibus']['config']['database']['host'] = 'yourcompany...rds.amazon.com' node.override['supermarket_omnibus']['config']['database']['port'] = '5432' node.override['supermarket_omnibus']['config']['database']['pool'] = '25' node.override['supermarket_omnibus']['config']['database']['password'] = 'topsecretneverguessit' ``` ### External Cache Chef Supermarket installations can also use an external cache store. The public Chef Supermarket uses Redis on Amazon ElastiCache. One Redis instance per private Chef Supermarket application server may be run safely. Use Redis 2.8 (or higher) for a high availability pair. To use an external cache, configure the following attributes in the `/recipes/default.rb` recipe of the wrapper cookbook: ``` node.override['supermarket_omnibus']['config']['redis']['enable'] = false node.override['supermarket_omnibus']['config']['redis_url'] = 'redis://your-redis-instance:6379' ``` ### External Cookbook Storage Cookbook artifacts—tar.gz artifacts that are uploaded to Chef Supermarket when sharing a cookbook—can be stored either on the local filesystem of the Chef Supermarket node (`/var/opt/supermarket/data` by default) or in an Amazon Simple Storage Service (S3) bucket. To use an S3 bucket, configure the following attributes in the `/recipes/default.rb` recipe of the wrapper cookbook: ``` node.override['supermarket_omnibus']['config']['s3_access_key_id'] = 'yourkeyid' node.override['supermarket_omnibus']['config']['s3_bucket'] = 'all-our-awesome-cookbooks' node.override['supermarket_omnibus']['config']['s3_region'] = 'some-place-3' node.override['supermarket_omnibus']['config']['s3_secret_access_key'] = 'yoursecretaccesskey' ``` Note Encrypted S3 buckets are currently not supported. Upgrade a Private Supermarket ----------------------------- 1. Shut down the server running Private Supermarket. 2. Backup the `/var/opt/supermarket` directory. 3. Download the [Chef Supermarket](https://www.chef.io/downloads/tools/supermarket) package. 4. Upgrade your system with the new package using the appropriate package manager for your distribution: * For Ubuntu: ``` dpkg -i /path/to/package/supermarket*.deb ``` * For RHEL / CentOS: ``` rpm -Uvh /path/to/package/supermarket*.rpm ``` 5. [Reconfigure](../ctl_supermarket/index#reconfigure) the server that Chef Supermarket is installed on: ``` sudo supermarket-ctl reconfigure ``` Private Supermarket is updated on your server now. We recommend restarting the services that run Chef Supermarket to ensure that the old installation of Chef Supermarket doesn’t persist in the server memory. 1. Get the name of the active unit: ``` systemctl list-units | grep runsvdir ``` 2. Restart the unit: ``` systemctl restart UNIT_NAME ``` This will restart the `runsvdir`, `runsv`, and `svlogd` service processes that run Chef Supermarket. © <NAME>, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/install_supermarket/Supported Versions ================== [[edit on GitHub]](https://github.com/chef/chef-web-docs/blob/main/content/versions.md) This section lists the free and commercial Chef products and versions we currently support. The lifecycle stage defines the involvement by Chef Software in updating and maintaining each product. Lifecycle Definitions --------------------- ### Generally Available (GA) This stage indicates that the product or version is in active development and/or maintenance. * Chef continues to provide releases to the application or version in response to customer needs and security vulnerabilities * Chef welcomes customer feature requests for the product roadmap for the application ### Deprecated This stage indicates that an application or version is no longer in active development and will eventually move to end of life status. Chef continues to provide support [according to our SLAs](https://www.chef.io/service-level-agreement/). * Chef no longer provides scheduled releases * Customers should use the GA alternative to these products; contact us for help with product selection and deployment * Chef may provide a release for a critical defect or security vulnerability ### End of Life (EOL) This stage indicates that Chef has set a date after which the application or version will no longer be supported or recommended for use by customers. * As of the end of life date, the application will no longer be supported by Chef and will no longer be available for download * Documentation for the application will be moved to <https://docs-archive.chef.io ### Versions and Status Important Unless otherwise stated, versions older than those listed below are EOL. Supported Commercial Distributions ---------------------------------- Use of these and later versions of these distributions must be in accordance with the [Chef End User License Agreement](https://www.chef.io/end-user-license-agreement) or a commercial agreement with Chef. Additional information is available in [this announcement](https://blog.chef.io/2019/04/02/chef-software-announces-the-enterprise-automation-stack/). | Product | Version | Lifecycle Status | EOL Date | | --- | --- | --- | --- | | Chef Automate | Latest | GA | n/a | | Chef Infra Client | 17.x | GA | April 30, 2023 | | Chef Infra Server | 14.x | GA | n/a | | Chef Habitat | 0.81+ | GA | n/a | | Chef InSpec | 4.x | GA | n/a | | Chef Workstation | 20.x (2020), 21.x (2021) | GA | n/a | | Chef Backend | 3.x | Releasing 2021 | 2022 | Note **Chef Backend** does not directly require acceptance of the Chef EULA, but it does have functionality that requires its acceptance in other products. Supported Free Distributions ---------------------------- Use of the following distributions is governed by the Apache License, version 2.0. | Product | Version | Lifecycle Status | EOL Date | | --- | --- | --- | --- | | Supermarket | 3.x | GA | TBD | Deprecated Products and Versions -------------------------------- The following products are deprecated. Users are advised to move to newer versions or products. | Product | Version | Lifecycle Status | EOL Date | | --- | --- | --- | --- | | Chef Backend | 2.x | Deprecated | December 31, 2022 | | Chef Infra Client | 16.x | Deprecated | April 30, 2022 | | Chef Manage | 2.5.x+ | Deprecated | December 31, 2022 | End of Life (EOL) Products -------------------------- | Product | Version | Lifecycle Status | EOL Date | | --- | --- | --- | --- | | Analytics | All | EOL | December 31, 2018 | | Automate | 1.x | EOL | December 31, 2019 | | Chef Infra Client | 15 and under | EOL | April 30, 2021 | | Chef Compliance Server | All | EOL | December 31, 2018 | | ChefDK | ALL | EOL | December 31, 2020 | | Chef Infra Server | 13.x | EOL | June 30, 2021 | | Chef InSpec | 2 and under | EOL | December 31, 2019 | | Chef InSpec | 3.x | EOL | April 30, 2020 | | Chef Provisioning | All | EOL | August 31, 2019 | | Chef Push Jobs | All | EOL | December 31, 2020 | | Chef Replication/Sync | All | EOL | August 31, 2019 | | Chef Server DRBD HA | All | EOL | March 31, 2019 | | Chef Workflow (Delivery) | All | EOL | December 31, 2020 | | Enterprise Chef | All | EOL | December 31, 2018 | | Reporting | All | EOL | December 31, 2018 | © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/versions.htmlwindows_service Resource ========================= Edit this page in the Chef repository This page is generated from the [Chef Infra Client source code](https://github.com/chef/chef). To suggest a change, edit the [windows_service.rb](https://github.com/chef/chef/blob/main/lib/chef/resource/windows_service.rb) file and submit a pull request to the [Chef Infra Client repository](https://github.com/chef/chef). [All Infra resources page](index) --- Use the **windows_service** resource to create, delete, or manage a service on the Microsoft Windows platform. Syntax ------ --- A **windows_service** resource block manages the state of a service on a machine that is running Microsoft Windows. For example: ``` windows_service 'BITS' do action :configure_startup startup_type :manual end ``` The full syntax for all of the properties that are available to the **windows_service** resource is: ``` windows_service 'name' do binary_path_name String delayed_start true, false # default value: false dependencies String, Array description String desired_access Integer # default value: 983551 display_name String error_control Integer # default value: 1 init_command String load_order_group String pattern String reload_command String, false restart_command String, false run_as_password String run_as_user String # default value: "LocalSystem" service_name String # default value: 'name' unless specified service_type Integer # default value: "SERVICE_WIN32_OWN_PROCESS" start_command String, false startup_type Symbol # default value: :automatic status_command String, false stop_command String, false supports Hash # default value: {"restart"=>nil, "reload"=>nil, "status"=>nil} timeout Integer action Symbol # defaults to :nothing if not specified end ``` where: * `windows_service` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `binary_path_name`, `display_name`, `desired_access`, `delayed_start`, `dependencies`, `description`, `error_control`, `init_command`, `load_order_group`, `pattern`, `reload_command`, `restart_command`, `run_as_password`, `run_as_user`, `service_name`, `service_type`, `start_command`, `startup_type`, `status_command`, `stop_command`, `supports`, and `timeout` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. Actions ------- --- The **windows_service** resource has the following actions: `:configure` Configure a pre-existing service. *New in Chef Client 14.0.* `:configure_startup` Configure a service based on the value of the `startup_type` property. `:create` Create the service based on the value of the `binary_path_name`, `service_name` and/or `display_name` property. *New in Chef Client 14.0.* `:delete` Delete the service based on the value of the `service_name` property. *New in Chef Client 14.0.* `:disable` Disable a service. This action is equivalent to a `Disabled` startup type on the Microsoft Windows platform. `:enable` Enable a service at boot. This action is equivalent to an `Automatic` startup type on the Microsoft Windows platform. `:nothing` Default. Do nothing with a service. `:reload` Reload the configuration for this service. This action is not supported on the Windows platform and will raise an error if used. `:restart` Restart a service. `:start` Start a service, and keep it running until stopped or disabled. `:stop` Stop a service. Properties ---------- --- The **windows_service** resource has the following properties: `binary_path_name` **Ruby Type:** String The fully qualified path to the service binary file. The path can also include arguments for an auto-start service. This is required for `:create` and `:configure` actions New in Chef Client 14.0 `delayed_start` **Ruby Type:** true, false | **Default Value:** `false` Set the startup type to delayed start. This only applies if `startup_type` is `:automatic` New in Chef Client 14.0 `dependencies` **Ruby Type:** String, Array A pointer to a double null-terminated array of null-separated names of services or load ordering groups that the system must start before this service. Specify `nil` or an empty string if the service has no dependencies. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group. New in Chef Client 14.0 `description` **Ruby Type:** String Description of the service. New in Chef Client 14.0 `desired_access` **Ruby Type:** Integer | **Default Value:** `983551` New in Chef Client 14.0 `display_name` **Ruby Type:** String The display name to be used by user interface programs to identify the service. This string has a maximum length of 256 characters. New in Chef Client 14.0 `error_control` **Ruby Type:** Integer | **Default Value:** `1` New in Chef Client 14.0 `load_order_group` **Ruby Type:** String The name of the service’s load ordering group(s). New in Chef Client 14.0 `pattern` **Ruby Type:** String | **Default Value:** `The value provided to 'service_name' or the resource block's name` The pattern to look for in the process table. `reload_command` **Ruby Type:** String, false The command used to tell a service to reload its configuration. `restart_command` **Ruby Type:** String, false The command used to restart a service. `run_as_password` **Ruby Type:** String The password for the user specified by `run_as_user`. `run_as_user` **Ruby Type:** String | **Default Value:** `localsystem` The user under which a Microsoft Windows service runs. `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the service name if it differs from the resource block’s name. `service_type` **Ruby Type:** Integer | **Default Value:** `16` New in Chef Client 14.0 `start_command` **Ruby Type:** String, false The command used to start a service. `startup_type` **Ruby Type:** Symbol | **Default Value:** `:automatic` **Allowed Values:** `:automatic, :disabled, :manual` Use to specify the startup type of the service. `status_command` **Ruby Type:** String, false The command used to check the run status for a service. `stop_command` **Ruby Type:** String, false The command used to stop a service. `supports` **Ruby Type:** Hash | **Default Value:** `{"restart"=>nil, "reload"=>nil, "status"=>nil}` A list of properties that controls how Chef Infra Client is to attempt to manage a service: `:restart`, `:reload`, `:status`. For `:restart`, the init script or other service provider can use a restart command; if `:restart` is not specified, Chef Infra Client attempts to stop and then start a service. For `:reload`, the init script or other service provider can use a reload command. For `:status`, the init script or other service provider can use a status command to determine if the service is running; if `:status` is not specified, Chef Infra Client attempts to match the `service_name` against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: `{ restart: false, reload: false, status: false }` for all platforms (except for the Red Hat platform family, which defaults to `{ restart: false, reload: false, status: true }`.) `timeout` **Ruby Type:** Integer | **Default Value:** `60` The amount of time (in seconds) to wait before timing out. Common Resource Functionality ----------------------------- --- Chef resources include common properties, notifications, and resource guards. ### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. ### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. Examples -------- --- The following examples demonstrate various approaches for using the **windows_service** resource in recipes: **Starting Services** Start a service with a `manual` startup type: ``` windows_service 'BITS' do action :configure_startup startup_type :manual end ``` **Creating Services** Create a service named chef-client: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" end ``` Create a service with `service_name` and `display_name`: ``` windows_service 'Setup chef-client as a service' do action :create display_name 'CHEF-CLIENT' service_name 'chef-client' binary_path_name "C:\opscode\chef\bin" end ``` Create a service with the `manual` startup type: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :manual end ``` Create a service with the `disabled` startup type: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :disabled end ``` Create a service with the `automatic` startup type and delayed start enabled: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :automatic delayed_start true end ``` Create a service with a description: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :automatic description "Chef client as service" end ``` **Deleting Services** Delete a service named chef-client: ``` windows_service 'chef-client' do action :delete end ``` Delete a service with the `service_name` property: ``` windows_service 'Delete chef client' do action :delete service_name 'chef-client' end ``` **Configuring Services** Change an existing service from automatic to manual startup: ``` windows_service 'chef-client' do action :configure binary_path_name "C:\opscode\chef\bin" startup_type :manual end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resources/windows_serviceCookstyle ========= [[edit on GitHub]](https://github.com/chef/chef-workstation/blob/main/docs-chef-io/content/workstation/cookstyle/_index.md) Cookstyle is a code linting tool that helps you write better Chef Infra cookbooks by detecting and automatically correcting style, syntax, and logic mistakes in your code. Cookstyle is powered by the RuboCop linting engine. RuboCop ships with over three-hundred rules, or cops, designed to detect common Ruby coding mistakes and enforce a common coding style. We’ve customized Cookstyle with a subset of those cops that we believe are perfectly tailored for cookbook development. We also ship Chef-specific cops that catch common cookbook coding mistakes, cleanup portions of code that are no longer necessary, and detect deprecations that prevent cookbooks from running on the latest releases of Chef Infra Client. Cookstyle increases code quality by: * Enforcing style conventions and best practices. * Helping every member of a team author similarly structured code. * Maintaining uniformity in the source code. * Setting expectations for fellow (and future) project contributors. * Detecting deprecated code that creates errors after upgrading to a newer Chef Infra Client release. * Detecting common Chef Infra mistakes that cause code to fail or behave incorrectly. Cookstyle vs. Rubocop --------------------- Cookstyle is more stable than Rubocop and is customized for Chef Cookbook code. This means that linting Cookbooks with Cookstyle will be more consistent and less likely to produce CI test failures. ### Tailored cops Cookbook development differs from traditional Ruby software development, so we maintain a tailored set of built-in cops from Rubocop. Cops that are not useful for cookbook development are disabled and occasionally we change the configuration of a rule to enforce a different behavior. We’ve also extended the base RuboCop package with a set of our own Chef Infra-specific cops. These cops are only found in Cookstyle and will help you to write more reliable and future-proof cookbooks. ### New cops New cops are continuously added to Rubocop. New cops can make existing codebases fail CI tests and force authors to constantly update their code. With Cookstyle, we update the RuboCop engine for bug and performance fixes, but we only change the set of cops that will fail tests once a year during Chef Infra’s major release in April. All new cops are introduced at RuboCop’s “refactor” alert level, meaning they will alert to the screen as you run Cookstyle, but they won’t fail a build. This stability means you are free to upgrade releases of Cookstyle without being forced to update your infrastructure code. Run Cookstyle ------------- Cookstyle is run from the command line, typically against a single cookbook and all of the Ruby files contained within it: ``` cookstyle /path/to/cookbook ``` Cookstyle may also be run from the root of an individual cookbook directory: ``` cookstyle . ``` Cookstyle returns a list, via standard output, that shows the results of the evaluation: ``` Inspecting 8 files CWCWCCCC Offences: cookbooks/apache/attributes/default.rb:1:1: C: Missing utf-8 encoding comment. default["apache"]["indexfile"] = "index1.html" ^ cookbooks/apache/attributes/default.rb:1:9: C: Prefer single-quoted strings when you don't need string interpolation or special symbols. default["apache"]["indexfile"] = "index1.html" ^^^^^^^^ cookbooks/apache/attributes/default.rb:1:19: C: Prefer single-quoted strings when you don't need string interpolation or special symbols. default["apache"]["indexfile"] = "index1.html" ^^^^^^^^^^^ ``` ### Output Cookstyle output: * States the number of files found and examined. For example: `Inspecting 8 files` * Lists the results of those files as a series of symbols. For example: `CWCWCCCC` * For each symbol, states the file name, line number, character number, type of issue or error, describes the issue or error, and specifies the location in the source code at which the issue or error is located A Cookstyle evaluation has the following syntax: ``` FILENAME:LINE_NUMBER:CHARACTER_NUMBER: TYPE_OF_ERROR: MESSAGE SOURCE CODE ^^^^^^^^^^^ ``` For example: ``` cookbooks/apache/attributes/default.rb:1:9: C: Prefer single-quoted strings when you don't need string interpolation or special symbols. default["apache"]["indexfile"] = "index1.html" ^^^^^^^^ ``` #### Symbols The following symbols appear in the standard output and are used to indicate the result of an evaluation: | Symbol | Description | | --- | --- | | `.` | The file does not have any issues. | | `C` | The file has an issue with convention. | | `E` | The file contains an error. | | `F` | The file contains a fatal error. | | `W` | The file contains a warning. | | `R` | The file contains code that should be refactored. | Autocorrecting Cookstyle Warnings --------------------------------- Many of the Cookstyle Cops include the ability to autocorrect violations. To autocorrect code run the following from the cookbook directory: ``` cookstyle -a . ``` Take particular care after running this command to ensure the autocorrection logic resulted in appropriate cookbook code. .rubocop.yml ------------ Use a .rubocop.yml file in a cookbook to override the default settings in Cookstyle for enabled and disabled rules. Only enabled rules—either in the `enabled.yml` file in Cookstyle itself or rules that are specifically enabled in a cookbook’s .rubocop.yml file—will be used during the evaluation. Any rule that becomes unhelpful should be disabled in the .rubocop.yml file. Each cookbook has its own .rubocop.yml file, which means that each cookbook may have its own set of enabled, disabled, and custom rules. That said, it’s more common for all cookbooks to have the same set of enabled, disabled, and custom rules. When RuboCop is run against a cookbook, the full set of enabled and disabled rules (as defined the `enabled.yml` and `disabled.yml` files in Cookstyle itself) are loaded first, and are then compared against the settings in the cookbook’s .rubocop.yml file. Custom rules should be specified in the .rubocop.yml file. The state of rules—enabled or disabled—in a .rubocop.yml file take precedence over the state of rules defined in the `enabled.yml` and `disabled.yml` files. ### Syntax A .rubocop.yml file has the following syntax: ``` NAME_OF_RULE:Description:'a description of a rule'Enabled :(true or false)KEY:VALUE ``` where * `NAME_OF_RULE` is the name of a rule * `Description` is the string that prints as part of the standard output that describes the rule if it is triggered during the evaluation * `Enabled` enables a rule (`true`) or disables a rule (`false`); for non-custom rules, this value will override the settings in the `enabled.yml` and `disabled.yml` files in Cookstyle * `KEY: VALUE` adds additional details for a rule, if necessary. For example, `Max: 200` sets the line length to 200 characters for the `LineLength` rule ### .rubocop_todo.yml Use a .rubocop_todo.yml file to capture the current state of all evaluations, and then write them to a file. This allows evaluations to reviewed one at a time. Disable any evaluations that are unhelpful, and then address the ones that are. To generate the .rubocop_todo.yml file, run the following command: ``` cookstyle --auto-gen-config ``` Note Rename this file to .rubocop.yml to adopt this evaluation state as the standard. Include this file in the .rubocop.yml file by adding `inherit_from: .rubocop_todo.yml` to the top of the .rubocop.yml file. © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/workstation/cookstyle.htmlAll Infra Resources =================== This reference describes each of the resources available to Chef Infra Client, including a list of actions, properties, and usage examples. Common Functionality -------------------- The properties and actions in this section apply to all resources. ### Actions The following actions may be used with any resource: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. #### Examples The following examples show how to use common actions in a recipe. **Use the :nothing action** ``` service 'memcached' do action :nothing end ``` ### Properties The following properties are common to every resource: `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Examples The following examples show how to use common properties in a recipe. **Use the ignore_failure common property** ``` gem_package 'syntax' do action :install ignore_failure true end ``` **Use the retries and retry_delay common properties** ``` service 'apache' do action [ :enable, :start ] retries 3 retry_delay 5 end ``` ### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. #### Properties The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Arguments The following arguments can be used with the `not_if` or `only_if` guard properties: `:user` Specify the user that a command will run as. For example: ``` not_if 'grep adam /etc/passwd', user: 'adam' ``` `:group` Specify the group that a command will run as. For example: ``` not_if 'grep adam /etc/passwd', group: 'adam' ``` `:environment` Specify a Hash of environment variables to be set. For example: ``` not_if 'grep adam /etc/passwd', environment: { 'HOME' => '/home/adam', } ``` `:cwd` Set the current working directory before running a command. For example: ``` not_if 'grep adam passwd', cwd: '/etc' ``` `:timeout` Set a timeout for a command. For example: ``` not_if 'sleep 10000', timeout: 10 ``` #### not_if Examples The following examples show how to use `not_if` as a condition in a recipe: **Create a file, but not if an attribute has a specific value** The following example shows how to use the `not_if` condition to create a file based on a template and using the presence of an attribute value on the node to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if { node['some_value'] } end ``` **Create a file with a Ruby block, but not if “/etc/passwd” exists** The following example shows how to use the `not_if` condition to create a file based on a template and then Ruby code to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if do ::File.exist?('/etc/passwd') end end ``` **Create a file with Ruby block that has curly braces, but not if “/etc/passwd” exists** The following example shows how to use the `not_if` condition to create a file based on a template and using a Ruby block (with curly braces) to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if { ::File.exist?('/etc/passwd') } end ``` **Create a file using a string, but not if “/etc/passwd” exists** The following example shows how to use the `not_if` condition to create a file based on a template and using a string to specify the condition: ``` template '/etc/some_config' do mode '0640' source 'some_config.erb' not_if 'some_app --check-config' end ``` #### only_if Examples The following examples show how to use `only_if` as a condition in a recipe: **Create a file, but only if an attribute has a specific value** The following example shows how to use the `only_if` condition to create a file based on a template and using the presence of an attribute on the node to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if { node['some_value'] } end ``` **Create a file with a Ruby block, but only if “/etc/passwd” does not exist** The following example shows how to use the `only_if` condition to create a file based on a template, and then use Ruby to specify a condition: ``` template '/etc/some_app/some_config' do mode '0640' source 'some_config.erb' only_if { ::File.exist?('/etc/some_app/') } end ``` **Create a file using a string, but only if “/etc/passwd” exists** The following example shows how to use the `only_if` condition to create a file based on a template and using a string to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if 'test -f /etc/passwd' end ``` ### Guard Interpreters Any resource that passes a string command may also specify the interpreter that will be used to evaluate that string command. This is done by using the `guard_interpreter` property to specify a **script**-based resource. #### Attributes The `guard_interpreter` property may be set to any of the following values: `:bash` Evaluates a string command using the **bash** resource. `:batch` Evaluates a string command using the **batch** resource. Default value (within a **batch** resource block): `:batch`. `:csh` Evaluates a string command using the **csh** resource. `:default` Default. Executes the default interpreter as identified by Chef Infra Client. `:perl` Evaluates a string command using the **perl** resource. `:powershell_script` Evaluates a string command using the **powershell_script** resource. Default value (within a **powershell_script** resource block): `:powershell_script`. `:python` Evaluates a string command using the **python** resource. `:ruby` Evaluates a string command using the **ruby** resource. #### Inheritance The `guard_interpreter` property is set to `:default` by default for the **bash**, **csh**, **perl**, **python**, and **ruby** resources. When the `guard_interpreter` property is set to `:default`, `not_if` or `only_if` guard statements **do not inherit** properties that are defined by the **script**-based resource. Warning The **batch** and **powershell_script** resources inherit properties by default. The `guard_interpreter` property is set to `:batch` or `:powershell_script` automatically when using a `not_if` or `only_if` guard statement within a **batch** or **powershell_script** resource, respectively. For example, the `not_if` guard statement in the following resource example **does not inherit** the `environment` property: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` and requires adding the `environment` property to the `not_if` guard statement so that it may use the `JAVA_HOME` path as part of its evaluation: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started', :environment => 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' end ``` To inherit properties, add the `guard_interpreter` property to the resource block and set it to the appropriate value: * `:bash` for **bash** * `:csh` for **csh** * `:perl` for **perl** * `:python` for **python** * `:ruby` for **ruby** For example, using the same example as from above, but this time adding the `guard_interpreter` property and setting it to `:bash`: ``` bash 'javatooling' do guard_interpreter :bash environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` The `not_if` statement now inherits the `environment` property and will use the `JAVA_HOME` path as part of its evaluation. #### Examples For example, the following code block will ensure the command is evaluated using the default interpreter as identified by Chef Infra Client: ``` resource 'name' do guard_interpreter :default # code end ``` ### Lazy Evaluation In some cases, the value for a property cannot be known until the execution phase of a Chef Infra Client run. In this situation, using lazy evaluation of property values can be helpful. Instead of a property being assigned a value, it may instead be assigned a code block. The syntax for using lazy evaluation is as follows: ``` property_name lazy { code_block } ``` where `lazy` is used to tell Chef Infra Client to evaluate the contents of the code block later on in the resource evaluation process (instead of immediately) and `{ code_block }` is arbitrary Ruby code that provides the value. For example, a resource that is **not** doing lazy evaluation: ``` template 'template_name' do # some properties path '/foo/bar' end ``` and a resource block that is doing lazy evaluation: ``` template 'template_name' do # some properties path lazy { ' some Ruby code ' } end ``` In the previous examples, the first resource uses the value `/foo/bar` and the second resource uses the value provided by the code block, as long as the contents of that code block are a valid resource property. The following example shows how to use lazy evaluation with template variables: ``` template '/tmp/canvey_island.txt' do source 'canvey_island.txt.erb' variables( lazy do { canvey_island: node.run_state['sea_power'] } end ) end ``` ### Notifications A notification is a property on a resource that listens to other resources in the resource collection and then takes actions based on the notification type (`notifies` or `subscribes`). #### Timers A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. #### Notifies A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` ##### Examples The following examples show how to use the `notifies` notification in a recipe. **Delay notifications** ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :delayed end ``` **Notify immediately** By default, notifications are `:delayed`, that is they are queued up as they are triggered, and then executed at the very end of a Chef Infra Client run. To run an action immediately, use `:immediately`: ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :immediately end ``` and then Chef Infra Client would immediately run the following: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing end ``` **Notify multiple resources** ``` template '/etc/chef/server.rb' do source 'server.rb.erb' owner 'root' group 'root' mode '0755' notifies :restart, 'service[chef-elasticsearch]', :delayed notifies :restart, 'service[chef-server]', :delayed end ``` **Notify in a specific order** To notify multiple resources, and then have these resources run in a certain order, do something like the following: ``` execute 'foo' do command '...' notifies :create, 'template[baz]', :immediately notifies :install, 'package[bar]', :immediately notifies :run, 'execute[final]', :immediately end template 'baz' do ... notifies :run, 'execute[restart_baz]', :immediately end package 'bar' execute 'restart_baz' execute 'final' do command '...' end ``` where the sequencing will be in the same order as the resources are listed in the recipe: `execute 'foo'`, `template 'baz'`, `execute [restart_baz]`, `package 'bar'`, and `execute 'final'`. **Reload a service** ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' notifies :reload, 'service[apache]', :immediately end ``` **Restart a service when a template is modified** ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :immediately end ``` **Send notifications to multiple resources** To send notifications to multiple resources, just use multiple attributes. Multiple attributes will get sent to the notified resources in the order specified. ``` template '/etc/netatalk/netatalk.conf' do notifies :restart, 'service[afpd]', :immediately notifies :restart, 'service[cnid]', :immediately end service 'afpd' service 'cnid' ``` **Execute a command using a template** The following example shows how to set up IPv4 packet forwarding using the **execute** resource to run a command named `forward_ipv4` that uses a template defined by the **template** resource: ``` execute 'forward_ipv4' do command 'echo > /proc/.../ipv4/ip_forward' action :nothing end template '/etc/file_name.conf' do source 'routing/file_name.conf.erb' notifies :run, 'execute[forward_ipv4]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[forward_ipv4]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. **Restart a service, and then notify a different service** The following example shows how start a service named `example_service` and immediately notify the Nginx service to restart. ``` service 'example_service' do action :start notifies :restart, 'service[nginx]', :immediately end ``` **Restart one service before restarting another** This example uses the `:before` notification to restart the `php-fpm` service before restarting `nginx`: ``` service 'nginx' do action :restart notifies :restart, 'service[php-fpm]', :before end ``` With the `:before` notification, the action specified for the `nginx` resource will not run until action has been taken on the notified resource (`php-fpm`). **Notify when a remote source changes** ``` remote_file '/tmp/couch.png' do source 'http://couchdb.apache.org/img/sketch.png' action :nothing end http_request 'HEAD http://couchdb.apache.org/img/sketch.png' do message '' url 'http://couchdb.apache.org/img/sketch.png' action :head if ::File.exist?('/tmp/couch.png') headers 'If-Modified-Since' => File.mtime('/tmp/couch.png').httpdate end notifies :create, 'remote_file[/tmp/couch.png]', :immediately end ``` #### Subscribes A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ##### Examples The following examples show how to use the `subscribes` notification in a recipe. **Prevent restart and reconfigure if configuration is broken** Use the `:nothing` action (common to all resources) to prevent the test from starting automatically, and then use the `subscribes` notification to run a configuration test when a change to the template is detected: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing subscribes :run, 'template[/etc/nagios3/configures-nagios.conf]', :immediately end ``` **Reload a service using a template** To reload a service that is based on a template, use the **template** and **service** resources together in the same recipe, similar to the following: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' end service 'apache' do action :enable subscribes :reload, 'template[/tmp/somefile]', :immediately end ``` where the `subscribes` notification is used to reload the service whenever the template is modified. **Stash a file in a data bag** The following example shows how to use the **ruby_block** resource to stash a BitTorrent file in a data bag so that it can be distributed to nodes in the organization. ``` # the following code sample comes from the ``seed`` recipe # in the following cookbook: https://github.com/mattray/bittorrent-cookbook ruby_block 'share the torrent file' do block do f = File.open(node['bittorrent']['torrent'], 'rb') #read the .torrent file and base64 encode it enc = Base64.encode64(f.read) data = { 'id' => bittorrent_item_id(node['bittorrent']['file']), 'seed' => node['ipaddress'], 'torrent' => enc, } item = Chef::DataBagItem.new item.data_bag('bittorrent') item.raw_data = data item.save end action :nothing subscribes :create, "bittorrent_torrent[#{node['bittorrent']['torrent']}]", :immediately end ``` ### Relative Paths The following relative paths can be used with any resource: `#{ENV['HOME']}` Use to return the `~` path in Linux and macOS or the `%HOMEPATH%` in Microsoft Windows. #### Examples ``` template "#{ENV['HOME']}/chef-getting-started.txt" do source 'chef-getting-started.txt.erb' mode '0755' end ``` ### Run in Compile Phase Chef Infra Client processes recipes in two phases: 1. First, each resource in the node object is identified and a resource collection is built. All recipes are loaded in a specific order, and then the actions specified within each of them are identified. This is also referred to as the “compile phase”. 2. Next, Chef Infra Client configures the system based on the order of the resources in the resource collection. Each resource then examines the node and performs the necessary steps to complete the action. This is also referred to as the “execution phase”. Typically, actions are processed during the execution phase of a Chef Infra Client run. However, sometimes it is necessary to run an action during the compile phase. For example, a resource can be configured to install a package during the compile phase to ensure that application is available to other resources during the execution phase. Note Use the **chef_gem** resource to install gems that are needed by Chef Infra Client during the execution phase. #### run_action Use `.run_action(:some_action)` at the end of a resource block to run the specified action during the compile phase. For example: ``` build_essential 'Install compilers' do action :nothing end.run_action(:install) ``` where `action` is set to `:nothing` to ensure the `run_action` is run during the compile phase and not later during the execution phase. This can be simplified by using the `compile_time` flag in Chef Infra Client 16 and later versions: ``` build_essential 'Install compilers' do compile_time true end ``` That flag both forces the resource to run at compile time and sets the converge action to `:nothing`. The following examples show when (and when not) to use `run_action`. **Using Custom Resources preferred to forcing to compile time** Compile time execution is often used to install gems before requiring them in recipe code. This is a poor pattern since gems may depend on native gems which may require installing compilers at compile time. ``` build_essential 'Install compilers' do compile_time true end chef_gem 'aws-dsk' do compile_time true end require 'aws-sdk' ``` A better strategy is to move the code, which requires the gem, into a custom resource. Since all the actions of custom resources run at converge time, this defers requiring the gem until later in the overall Chef Infra Client execution. Unified mode can also be used in the resource to eliminate compile/converge mode issues entirely: ``` unified_mode true action :run do build_essential 'Install compilers' chef_gem 'aws-sdk' require 'aws-sdk' end ``` **Download and parse a configuration file** A common use case is to download a configuration file, parse it, and then use the values in templates and to control other configuration. An important distinction to make is that the downloaded configuration file only exists in a temporary state to be used by the Chef Infra Client. It will not be used directly by the system or applications that are managed by the Chef Infra Client. To download and parse a JSON file and render it in a template, it makes sense to download the file during compile time: ``` # the remote_file is being downloaded to a temporary file remote_file "#{Chef::Config[:file_cache_path]}/users.json" do source "https://jsonplaceholder.typicode.com/users" compile_time true end # this parsing needs to happen after the remote_file is downloaded, but will # be executed at compile time. array = JSON.parse(IO.read("#{Chef::Config[:file_cache_path]}/users.json") # the `array.last["phone"]` expression here will also be evaluated at compile # time and must be lazied via wrapping the expresssion in `lazy {}` file "/tmp/phone_number.txt" do content array.last["phone"] end ``` This is considerably cleaner than the alternative of lazy evaluating both the parsing of the JSON and the rendering of the data into the file template, which will happen if the `remote_file` resource is not run at compile time: ``` # the execution of this is now deferred remote_file "#{Chef::Config[:file_cache_path]}/users.json" do source "https://jsonplaceholder.typicode.com/users" end # it is necessary due to lexical scoping issues to create this variable here array = nil # the parsing of the JSON is now deferred due to the ruby_block ruby_block "parse JSON" do block do array = JSON.parse(IO.read("#{Chef::Config[:file_cache_path]}/users.json") end end # the argument to the content property must now also be deferred file "/tmp/phone_number.txt" do content lazy { array.last["phone"] } end ``` This is an example of code that overuses deferred execution, uses more “lazy” evaluation, and is considerably harder to understand and write correctly. **Notifications will not work** Resources that are executed during the compile phase cannot notify other resources. For example: ``` execute 'ifconfig' package 'vim-enhanced' do compile_time true notifies :run, 'execute[ifconfig]', :immediately end ``` A better approach in this type of situation is to install the package before the resource collection is built to ensure that it is available to other resources later on. The best approach to this problem is to use `unified mode` which eliminates the compile time and converge time distinction, while allowing notifications to work correctly. **Resources that are forced to compile time by default** The `ohai_hint` and `hostname` resources run at compile time by default. This is due to the fact that later resources may consume the node attributes which are set by those resources leading to excessive use of `lazy` in subsequent resources (and similar issues to the `remote_file` example above). The `chef_gem` resource used to execute at compile time by default, but now we recommend that users move code that executes at compile time to custom resources. ### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. ### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. Resources --------- The following resources are built into the Chef Infra Client: alternatives resource --------------------- [alternatives resource page](resources/alternatives/index) --- Use the **alternatives** resource to configure command alternatives in Linux using the alternatives or update-alternatives packages. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **alternatives** resource is: ``` alternatives 'name' do link String # default value: "/usr/bin/LINK_NAME" link_name String # default value: 'name' unless specified path String priority String, Integer action Symbol # defaults to :install if not specified end ``` where: * `alternatives` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `link`, `link_name`, `path`, and `priority` are the properties available to this resource. ### Actions --- The **alternatives** resource has the following actions: `:auto` Set an alternative up in automatic mode with the highest priority automatically selected. `:install` Install an alternative on the system including symlinks. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:refresh` Refresh alternatives. `:remove` Remove an alternative and all associated links. `:set` Set the symlink for an alternative. ### Properties --- The **alternatives** resource has the following properties: `link` **Ruby Type:** String | **Default Value:** `/usr/bin/LINK_NAME` The path to the alternatives link. `link_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the link to create. This will be the command you type on the command line such as `ruby` or `gcc`. `path` **Ruby Type:** String The absolute path to the original application binary such as `/usr/bin/ruby27`. `priority` **Ruby Type:** String, Integer The priority of the alternative. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **alternatives** resource in recipes: **Install an alternative**: ``` alternatives 'python install 2' do link_name 'python' path '/usr/bin/python2.7' priority 100 action :install end ``` **Set an alternative**: ``` alternatives 'python set version 3' do link_name 'python' path '/usr/bin/python3' action :set end ``` **Set the automatic alternative state**: ``` alternatives 'python auto' do link_name 'python' action :auto end ``` **Refresh an alternative**: ``` alternatives 'python refresh' do link_name 'python' action :refresh end ``` **Remove an alternative**: ``` alternatives 'python remove' do link_name 'python' path '/usr/bin/python3' action :remove end ``` apt_package resource --------------------- [apt_package resource page](resources/apt_package/index) --- Use the **apt_package** resource to manage packages on Debian, Ubuntu, and other platforms that use the APT package system. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **apt_package** resource block manages a package on a node, typically by installing it. The simplest use of the **apt_package** resource is: `apt_package 'package_name'` which will install the named package using all of the default options and the default action of `:install`. The full syntax for all of the properties that are available to the **apt_package** resource is: ``` apt_package 'name' do default_release String options String, Array overwrite_config_files true, false # default value: false package_name String, Array response_file String response_file_variables Hash # default value: {} timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `apt_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `default_release`, `options`, `overwrite_config_files`, `package_name`, `response_file`, `response_file_variables`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **apt_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:lock` Locks the apt package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:unlock` Unlocks the apt package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **apt_package** resource has the following properties: `default_release` **Ruby Type:** String The default release. For example: `stable`. `options` **Ruby Type:** String, Array One (or more) additional options that are passed to the command. For example, common apt-get directives, such as `--no-install-recommends`. See the [apt-get man page](http://manpages.ubuntu.com/manpages/jammy/en/man8/apt-get.8.html) for the full list. `overwrite_config_files` **Ruby Type:** true, false | **Default Value:** `false` Overwrite existing configuration files with those supplied by the package, if prompted by APT. New in Chef Client 14.0 `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `response_file` **Ruby Type:** String The direct path to the file used to pre-seed a package. `response_file_variables` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of response file variables in the form of {‘VARIABLE’ => ‘VALUE’}. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **apt_package** resource in recipes: **Install a package using package manager**: ``` apt_package 'name of package' do action :install end ``` **Install a package without specifying the default action**: ``` apt_package 'name of package' ``` **Install multiple packages at once**: ``` apt_package %w(package1 package2 package3) ``` **Install without using recommend packages as a dependency**: ``` package 'apache2' do options '--no-install-recommends' end ``` apt_preference resource ------------------------ [apt_preference resource page](resources/apt_preference/index) --- Use the **apt_preference** resource to create APT [preference files](https://wiki.debian.org/AptPreferences). Preference files are used to control which package versions and sources are prioritized during installation. **New in Chef Infra Client 13.3.** ### Syntax --- The full syntax for all of the properties that are available to the **apt_preference** resource is: ``` apt_preference 'name' do glob String package_name String # default value: 'name' unless specified pin String pin_priority String, Integer action Symbol # defaults to :add if not specified end ``` where: * `apt_preference` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `glob`, `package_name`, `pin`, and `pin_priority` are the properties available to this resource. ### Actions --- The **apt_preference** resource has the following actions: `:add` Creates a preferences file under `/etc/apt/preferences.d`. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes the preferences file, thus unpinning the package. ### Properties --- The **apt_preference** resource has the following properties: `glob` **Ruby Type:** String Pin by a `glob()` expression or with a regular expression surrounded by `/`. `package_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the package name if it differs from the resource block’s name. `pin` **Ruby Type:** String | `REQUIRED` The package version or repository to pin. `pin_priority` **Ruby Type:** String, Integer | `REQUIRED` Sets the Pin-Priority for a package. See <https://wiki.debian.org/AptPreferences> for more details. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **apt_preference** resource in recipes: **Pin libmysqlclient16 to a version 5.1.49-3**: ``` apt_preference 'libmysqlclient16' do pin 'version 5.1.49-3' pin_priority '700' end ``` Note: The `pin_priority` of `700` ensures that this version will be preferred over any other available versions. **Unpin a libmysqlclient16**: ``` apt_preference 'libmysqlclient16' do action :remove end ``` **Pin all packages to prefer the packages.dotdeb.org repository**: ``` apt_preference 'dotdeb' do glob '*' pin 'origin packages.dotdeb.org' pin_priority '700' end ``` apt_repository resource ------------------------ [apt_repository resource page](resources/apt_repository/index) --- Use the **apt_repository** resource to specify additional APT repositories. Adding a new repository will update the APT package cache immediately. **New in Chef Infra Client 12.9.** ### Syntax --- The full syntax for all of the properties that are available to the **apt_repository** resource is: ``` apt_repository 'name' do arch String, false cache_rebuild true, false # default value: true components Array # default value: `main` if using a PPA repository. cookbook String, false deb_src true, false # default value: false distribution String, false # default value: The LSB codename of the node such as 'focal'. key String, Array, false # default value: [] key_proxy String, false keyserver String, false # default value: "keyserver.ubuntu.com" repo_name String # default value: 'name' unless specified trusted true, false # default value: false uri String action Symbol # defaults to :add if not specified end ``` where: * `apt_repository` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `arch`, `cache_rebuild`, `components`, `cookbook`, `deb_src`, `distribution`, `key`, `key_proxy`, `keyserver`, `repo_name`, `trusted`, and `uri` are the properties available to this resource. ### Actions --- The **apt_repository** resource has the following actions: `:add` Creates a repository file at `/etc/apt/sources.list.d/` and builds the repository listing. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes the repository listing. ### Properties --- The **apt_repository** resource has the following properties: `arch` **Ruby Type:** String, false Constrain packages to a particular CPU architecture such as `i386` or `amd64`. `cache_rebuild` **Ruby Type:** true, false | **Default Value:** `true` Determines whether to rebuild the APT package cache. `components` **Ruby Type:** Array | **Default Value:** ``main` if using a PPA repository.` Package groupings, such as ‘main’ and ‘stable’. `cookbook` **Ruby Type:** String, false If key should be a cookbook_file, specify a cookbook where the key is located for files/default. Default value is nil, so it will use the cookbook where the resource is used. `deb_src` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not to add the repository as a source repo as well. `distribution` **Ruby Type:** String, false | **Default Value:** `The LSB codename of the node such as 'focal'.` Usually a distribution’s codename, such as `xenial`, `bionic`, or `focal`. `key` **Ruby Type:** String, Array, false | **Default Value:** `[]` If a keyserver is provided, this is assumed to be the fingerprint; otherwise it can be either the URI of GPG key for the repo, or a cookbook_file. `key_proxy` **Ruby Type:** String, false If set, a specified proxy is passed to GPG via `http-proxy=`. `keyserver` **Ruby Type:** String, false | **Default Value:** `keyserver.ubuntu.com` The GPG keyserver where the key for the repo should be retrieved. `repo_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the repository name if it differs from the resource block’s name. The value of this setting must not contain spaces. New in Chef Client 14.1 `trusted` **Ruby Type:** true, false | **Default Value:** `false` Determines whether you should treat all packages from this repository as authenticated regardless of signature. `uri` **Ruby Type:** String The base of the Debian distribution. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **apt_repository** resource in recipes: **Add repository with basic settings**: ``` apt_repository 'nginx' do uri 'http://nginx.org/packages/ubuntu/' components ['nginx'] end ``` **Enable Ubuntu multiverse repositories**: ``` apt_repository 'security-ubuntu-multiverse' do uri 'http://security.ubuntu.com/ubuntu' distribution 'xenial-security' components ['multiverse'] deb_src true end ``` **Add the Nginx PPA, autodetect the key and repository url**: ``` apt_repository 'nginx-php' do uri 'ppa:nginx/stable' end ``` **Add the JuJu PPA, grab the key from the Ubuntu keyserver, and add source repo**: ``` apt_repository 'juju' do uri 'ppa:juju/stable' components ['main'] distribution 'xenial' key 'C8068B11' action :add deb_src true end ``` **Add repository that requires multiple keys to authenticate packages**: ``` apt_repository 'rundeck' do uri 'https://dl.bintray.com/rundeck/rundeck-deb' distribution '/' key ['379CE192D401AB61', 'http://rundeck.org/keys/BUILD-GPG-KEY-Rundeck.org.key'] keyserver 'keyserver.ubuntu.com' action :add end ``` **Add the Cloudera Repo of CDH4 packages for Ubuntu 16.04 on AMD64**: ``` apt_repository 'cloudera' do uri 'http://archive.cloudera.com/cdh4/ubuntu/xenial/amd64/cdh' arch 'amd64' distribution 'xenial-cdh4' components ['contrib'] key 'http://archive.cloudera.com/debian/archive.key' end ``` **Remove a repository from the list**: ``` apt_repository 'zenoss' do action :remove end ``` apt_update resource -------------------- [apt_update resource page](resources/apt_update/index) --- Use the **apt_update** resource to manage APT repository updates on Debian and Ubuntu platforms. **New in Chef Infra Client 12.7.** ### Syntax --- The full syntax for all of the properties that are available to the **apt_update** resource is: ``` apt_update 'name' do frequency Integer # default value: 86400 action Symbol # defaults to :periodic if not specified end ``` where: * `apt_update` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `frequency` is the property available to this resource. ### Nameless This resource can be **nameless**. Add the resource itself to your recipe to get the default behavior: ``` apt_update ``` will behave the same as: ``` apt_update 'update' ``` ### Actions --- The **apt_update** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:periodic` Update the Apt repository at the interval specified by the `frequency` property. (default) `:update` Update the Apt repository at the start of a Chef Infra Client run. ### Properties --- The **apt_update** resource has the following properties: `frequency` **Ruby Type:** Integer | **Default Value:** `86400` Determines how frequently (in seconds) APT repository updates are made. Use this property when the `:periodic` action is specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **apt_update** resource in recipes: **Update the Apt repository at a specified interval**: ``` apt_update 'all platforms' do frequency 86400 action :periodic end ``` **Update the Apt repository at the start of a Chef Infra Client run**: ``` apt_update 'update' ``` archive_file resource ---------------------- [archive_file resource page](resources/archive_file/index) --- Use the **archive_file** resource to extract archive files to disk. This resource uses the libarchive library to extract multiple archive formats including tar, gzip, bzip, and zip formats. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **archive_file** resource is: ``` archive_file 'name' do destination String group String mode String, Integer # default value: "'755'" options Array, Symbol overwrite true, false, auto # default value: false owner String path String # default value: 'name' unless specified strip_components Integer # default value: 0 action Symbol # defaults to :extract if not specified end ``` where: * `archive_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `destination`, `group`, `mode`, `options`, `overwrite`, `owner`, `path`, and `strip_components` are the properties available to this resource. ### Actions --- The **archive_file** resource has the following actions: `:extract` Extract and archive file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **archive_file** resource has the following properties: `destination` **Ruby Type:** String | `REQUIRED` The file path to extract the archive file to. `group` **Ruby Type:** String The group of the extracted files. `mode` **Ruby Type:** String, Integer | **Default Value:** `'755'` The mode of the extracted files. Integer values are deprecated as octal values (ex. 0755) would not be interpreted correctly. `options` **Ruby Type:** Array, Symbol | **Default Value:** `lazy default` An array of symbols representing extraction flags. Example: `:no_overwrite` to prevent overwriting files on disk. By default, this properly sets `:time` which preserves the modification timestamps of files in the archive when writing them to disk. `overwrite` **Ruby Type:** true, false, auto | **Default Value:** `false` Should the resource overwrite the destination file contents if they already exist? If set to `:auto` the date stamp of files within the archive will be compared to those on disk and disk contents will be overwritten if they differ. This may cause unintended consequences if disk date stamps are changed between runs, which will result in the files being overwritten during each client run. Make sure to properly test any change to this property. `owner` **Ruby Type:** String The owner of the extracted files. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the file path to the archive to extract if it differs from the resource block’s name. `strip_components` **Ruby Type:** Integer | **Default Value:** `0` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. This behaves similarly to tar’s –strip-components command line argument. New in Chef Infra Client 17.5 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **archive_file** resource in recipes: **Extract a zip file to a specified directory**: ``` archive_file 'Precompiled.zip' do path '/tmp/Precompiled.zip' destination '/srv/files' end ``` **Set specific permissions on the extracted files**: ``` archive_file 'Precompiled.zip' do owner 'tsmith' group 'staff' mode '700' path '/tmp/Precompiled.zip' destination '/srv/files' end ``` bash resource ------------- [bash resource page](resources/bash/index) --- Use the **bash** resource to execute scripts using the Bash interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **bash** resource block executes scripts using Bash: ``` bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` where: * `cwd` specifies the directory from which the command is run * `code` specifies the command to run The full syntax for all of the properties that are available to the **bash** resource is: ``` bash 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `bash` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **bash** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a script. ### Properties --- The **bash** resource has the following properties: `code` **Ruby Type:** String | `REQUIRED` A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **bash** resource in recipes: Use a named provider to run a script ``` bash 'install_something' do user 'root' cwd '/tmp' code <<-EOH wget http://www.example.com/tarball.tar.gz tar -zxf tarball.tar.gz cd tarball ./configure make make install EOH end ``` Install a file from a remote location using bash The following is an example of how to install the `foo123` module for Nginx. This module adds shell-style functionality to an Nginx configuration file and does the following: * Declares three variables * Gets the Nginx file from a remote location * Installs the file using Bash to the path specified by the `src_filepath` variable ``` # the following code sample is similar to the ``upload_progress_module`` # recipe in the ``nginx`` cookbook: # https://github.com/chef-cookbooks/nginx src_filename = "foo123-nginx-module-v#{ node['nginx']['foo123']['version'] }.tar.gz" src_filepath = "#{Chef::Config['file_cache_path']}/#{src_filename}" extract_path = "#{ Chef::Config['file_cache_path'] }/nginx_foo123_module/#{ node['nginx']['foo123']['checksum'] }" remote_file 'src_filepath' do source node['nginx']['foo123']['url'] checksum node['nginx']['foo123']['checksum'] owner 'root' group 'root' mode '0755' end bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` Install an application from git using bash The following example shows how Bash can be used to install a plug-in for rbenv named `ruby-build`, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which `ruby-build` is located, and then runs a command. ``` git "#{Chef::Config[:file_cache_path]}/ruby-build" do repository 'git://github.com/sstephenson/ruby-build.git' revision 'master' action :sync end bash 'install_ruby_build' do cwd "#{Chef::Config[:file_cache_path]}/ruby-build" user 'rbenv' group 'rbenv' code <<-EOH ./install.sh EOH environment 'PREFIX' => '/usr/local' end ``` To read more about `ruby-build`, see here: <https://github.com/sstephenson/ruby-build>. Store certain settings The following recipe shows how an attributes file can be used to store certain settings. An attributes file is located in the `attributes/` directory in the same cookbook as the recipe which calls the attributes file. In this example, the attributes file specifies certain settings for Python that are then used across all nodes against which this recipe will run. Python packages have versions, installation directories, URLs, and checksum files. An attributes file that exists to support this type of recipe would include settings like the following: ``` default['python']['version'] = '2.7.1' if python['install_method'] == 'package' default['python']['prefix_dir'] = '/usr' else default['python']['prefix_dir'] = '/usr/local' end default['python']['url'] = 'http://www.python.org/ftp/python' default['python']['checksum'] = '80e387...85fd61' ``` and then the methods in the recipe may refer to these values. A recipe that is used to install Python will need to do the following: * Identify each package to be installed (implied in this example, not shown) * Define variables for the package `version` and the `install_path` * Get the package from a remote location, but only if the package does not already exist on the target system * Use the **bash** resource to install the package on the node, but only when the package is not already installed ``` # the following code sample comes from the ``oc-nginx`` cookbook on |github|: https://github.com/cookbooks/oc-nginx version = node['python']['version'] install_path = "#{node['python']['prefix_dir']}/lib/python#{version.split(/(^\d+\.\d+)/)[1]}" remote_file "#{Chef::Config[:file_cache_path]}/Python-#{version}.tar.bz2" do source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2" checksum node['python']['checksum'] mode '0755' not_if { ::File.exist?(install_path) } end bash 'build-and-install-python' do cwd Chef::Config[:file_cache_path] code <<-EOF tar -jxvf Python-#{version}.tar.bz2 (cd Python-#{version} && ./configure #{configure_options}) (cd Python-#{version} && make && make install) EOF not_if { ::File.exist?(install_path) } end ``` batch resource -------------- [batch resource page](resources/batch/index) --- Use the **batch** resource to execute a batch script using the cmd.exe interpreter on Windows. The batch resource creates and executes a temporary file (similar to how the script resource behaves), rather than running the command inline. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **batch** resource block executes a batch script using the cmd.exe interpreter: ``` batch 'echo some env vars' do code <<-EOH echo %TEMP% echo %SYSTEMDRIVE% echo %PATH% echo %WINDIR% EOH end ``` The full syntax for all of the properties that are available to the **batch** resource is: ``` batch 'name' do architecture Symbol code String command String, Array creates String cwd String flags String group String, Integer guard_interpreter Symbol interpreter String returns Integer, Array timeout Integer, Float user String password String domain String action Symbol # defaults to :run if not specified end ``` where: * `batch` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `architecture`, `code`, `command`, `creates`, `cwd`, `flags`, `group`, `guard_interpreter`, `interpreter`, `returns`, `timeout`, `user`, `password` and `domain` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **batch** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Run a batch file. ### Properties --- The **batch** resource has the following properties: `architecture` **Ruby Type:** Symbol The architecture of the process under which a script is executed. If a value is not provided, Chef Infra Client defaults to the correct value for the architecture, as determined by Ohai. An exception is raised when anything other than `:i386` is specified for a 32-bit process. Possible values: `:i386` (for 32-bit processes) and `:x86_64` (for 64-bit processes). `code` **Ruby Type:** String | `REQUIRED` A quoted string of code to be executed. `command` **Ruby Type:** String, Array The name of the command to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `guard_interpreter` **Ruby Type:** Symbol | **Default Value:** `:batch` When this property is set to `:batch`, the 64-bit version of the cmd.exe shell will be used to evaluate strings values for the `not_if` and `only_if` properties. Set this value to `:default` to use the 32-bit version of the cmd.exe shell. `interpreter` **Ruby Type:** String The script interpreter to use during code execution. Changing the default value of this property is not supported. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. domainuser or [<EMAIL>](mailto:<EMAIL>) via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified. `password` **Ruby Type:** String *Windows only*: The password of the user specified by the user property. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. `domain` **Ruby Type:** String *Windows only*: The domain of the user user specified by the user property. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef Infra Client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **batch** resource in recipes: Unzip a file, and then move it To run a batch file that unzips and then moves Ruby, do something like: ``` batch 'unzip_and_move_ruby' do code <<-EOH 7z.exe x #{Chef::Config[:file_cache_path]}/ruby-1.8.7-p352-i386-mingw32.7z -oC:\\source -r -y xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y EOH end batch 'echo some env vars' do code <<-EOH echo %TEMP% echo %SYSTEMDRIVE% echo %PATH% echo %WINDIR% EOH end ``` or: ``` batch 'unzip_and_move_ruby' do code <<-EOH 7z.exe x #{Chef::Config[:file_cache_path]}/ruby-1.8.7-p352-i386-mingw32.7z -oC:\\source -r -y xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y EOH end batch 'echo some env vars' do code 'echo %TEMP%\\necho %SYSTEMDRIVE%\\necho %PATH%\\necho %WINDIR%' end ``` Run a command as an alternate user *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] domain "domain" user "username" password "password" end # Passing username = 'domain-name\\username'. No domain is passed batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "domain-name\\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed batch 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end ``` bff_package resource --------------------- [bff_package resource page](resources/bff_package/index) --- Use the **bff_package** resource to manage packages for the AIX platform using the installp utility. When a package is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. Note A Backup File Format (BFF) package may not have a `.bff` file extension. Chef Infra Client will still identify the correct provider to use based on the platform, regardless of the file extension. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- The full syntax for all of the properties that are available to the **bff_package** resource is: ``` bff_package 'name' do options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `bff_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **bff_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. ### Properties --- The **bff_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String Required. The path to a package in the local file system. The AIX platform requires `source` to be a local file system path because `installp` does not retrieve packages using HTTP or FTP. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **bff_package** resource in recipes: The **bff_package** resource is the default package provider on the AIX platform. The base **package** resource may be used, and then when the platform is AIX, Chef Infra Client will identify the correct package provider. The following examples show how to install part of the IBM XL C/C++ compiler. **Installing using the base package resource** ``` package 'xlccmp.13.1.0' do source '/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0' action :install end ``` **Installing using the bff_package resource** ``` bff_package 'xlccmp.13.1.0' do source '/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0' action :install end ``` breakpoint resource ------------------- [breakpoint resource page](resources/breakpoint/index) --- Use the **breakpoint** resource to add breakpoints to recipes. Run the chef-shell in Chef Infra Client mode, and then use those breakpoints to debug recipes. Breakpoints are ignored by the chef-client during an actual chef-client run. That said, breakpoints are typically used to debug recipes only when running them in a non-production environment, after which they are removed from those recipes before the parent cookbook is uploaded to the Chef server. **New in Chef Infra Client 12.0.** ### Syntax --- The full syntax for all of the properties that are available to the **breakpoint** resource is: ``` breakpoint 'name' do action Symbol # defaults to :break if not specified end ``` where: * `breakpoint` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. ### Actions --- The **breakpoint** resource has the following actions: `:break` Add a breakpoint for use with chef-shell (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- This resource does not have any properties. ### Debug Recipes with chef-shell chef-shell is a recipe debugging tool that allows the use of breakpoints within recipes. chef-shell runs as an Interactive Ruby (IRb) session. chef-shell supports both recipe and attribute file syntax, as well as interactive debugging features. #### Modes chef-shell is tool that is run using an Interactive Ruby (IRb) session. chef-shell currently supports recipe and attribute file syntax, as well as interactive debugging features. chef-shell has three run modes: | Mode | Description | | --- | --- | | Standalone | Default. No cookbooks are loaded, and the run-list is empty. | | Solo | chef-shell acts as a Chef Solo Client. It attempts to load the chef-solo configuration file at `~/.chef/config.rb` and any JSON attributes passed. If the JSON attributes set a run-list, it will be honored. Cookbooks will be loaded in the same way that chef-solo loads them. chef-solo mode is activated with the `-s` or `--solo` command line option, and JSON attributes are specified in the same way as for chef-solo, with `-j /path/to/chef-solo.json`. | | Client | chef-shell acts as a Chef Infra Client. During startup, it reads the Chef Infra Client configuration file from `~/.chef/client.rb` and contacts the Chef Infra Server to get the node's run_list, attributes, and cookbooks. Chef Infra Client mode is activated with the `-z` or `--client` options. You can also specify the configuration file with `-c CONFIG` and the server URL with `-S SERVER_URL`. | #### Configure chef-shell determines which configuration file to load based on the following: 1. If a configuration file is specified using the `-c` option, chef-shell will use the specified configuration file 2. If a NAMED_CONF is given, chef-shell will load ~/.chef/NAMED_CONF/chef_shell.rb 3. If no NAMED_CONF is given chef-shell will load ~/.chef/chef_shell.rb if it exists 4. If no chef_shell.rb can be found, chef-shell falls back to load: * /etc/chef/client.rb if -z option is given. * /etc/chef/solo.rb if –solo-legacy-mode option is given. * .chef/config.rb if -s option is given. * .chef/knife.rb if -s option is given. ##### chef-shell.rb The chef-shell.rb file can be used to configure chef-shell in the same way as the client.rb file is used to configure Chef Infra Client. For example, to configure chef-shell to authenticate to the Chef Infra Server, copy the `node_name`, `client_key`, and `chef_server_url` settings from the config.rb file: ``` node_name 'your-knife-clientname' client_key File.expand_path('~/.chef/my-client.pem') chef_server_url 'https://api.opscode.com/organizations/myorg' ``` and then add them to the chef-shell.rb file. Other configuration possibilities include disabling Ohai plugins (which will speed up the chef-shell boot process) or including arbitrary Ruby code in the chef-shell.rb file. ##### Run as a Chef Infra Client By default, chef-shell loads in standalone mode and does not connect to the Chef Infra Server. The chef-shell can be run as a Chef Infra Client to verify functionality that is only available when Chef Infra Client connects to the Chef Infra Server, such as search functionality or accessing data stored in data bags. chef-shell can use the same credentials as knife when connecting to a Chef Infra Server. Make sure that the settings in chef-shell.rb are the same as those in config.rb, and then use the `-z` option as part of the command. For example: ``` chef-shell -z ``` #### Manage When chef-shell is configured to access a Chef Infra Server, chef-shell can list, show, search for and edit cookbooks, clients, nodes, roles, environments, policyfiles, and data bags. The syntax for managing objects on the Chef Infra Server is as follows: ``` chef-shell -z named_configuration ``` Where: * `named_configuration` is an existing configuration file in `~/.chef/named_configuration/chef_shell.rb`, such as `production`, `staging`, or `test`. Once in chef-shell, commands can be run against objects as follows: ``` chef (preprod) > items.command ``` Where: * `items` is the type of item to search for: `cookbooks`, `clients`, `nodes`, `roles`, `environments` or a data bag. * `command` is the command: `list`, `show`, `find`, or `edit`. For example, to list all of the nodes in a configuration named “preprod”, enter: ``` chef (preprod) > nodes.list ``` Which will return something similar to: ``` => [node[i-f09a939b], node[i-049a936f], node[i-eaaaa581], node[i-9154b1fb], node[i-6a213101], node[i-c2687aa9], node[i-7abeaa11], node[i-4eb8ac25], node[i-9a2030f1], node[i-a06875cb], node[i-145f457f], node[i-e032398b], node[i-dc8c98b7], node[i-6afdf401], node[i-f49b119c], node[i-5abfab31], node[i-78b8ac13], node[i-d99678b3], node[i-02322269], node[i-feb4a695], node[i-9e2232f5], node[i-6e213105], node[i-cdde3ba7], node[i-e8bfb083], node[i-743c2c1f], node[i-2eaca345], node[i-aa7f74c1], node[i-72fdf419], node[i-140e1e7f], node[i-f9d43193], node[i-bd2dc8d7], node[i-8e7f70e5], node[i-78f2e213], node[i-962232fd], node[i-4c322227], node[i-922232f9], node[i-c02728ab], node[i-f06c7b9b]] ``` The `list` command can take a code block, which will applied (but not saved), to each object that is returned from the server. For example: ``` chef (preprod) > nodes.list {|n| puts "#{n.name}: #{n.run_list}" } ``` will return something similar to: ``` => i-f09a939b: role[lb], role[preprod], recipe[aws] i-049a936f: role[lb], role[preprod], recipe[aws] i-9154b1fb: recipe[erlang], role[base], role[couchdb], role[preprod], i-6a213101: role[chef], role[preprod] # more... ``` The `show` command can be used to display a specific node. For example: ``` chef (preprod) > load_balancer = nodes.show('i-f09a939b') ``` will return something similar to: ``` => node[i-f09a939b] ``` Or: ``` chef (preprod) > load_balancer.ec2.public_hostname ``` will return something similar to: ``` => "ec2-111-22-333-44.compute-1.amazonaws.com" ``` The `find` command can be used to search the Chef Infra Server from the chef-shell. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') ``` You can also format the results with a code block. For example: ``` chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } and nil ``` will return something similar to: ``` => ["ami-f8927a91", "ami-f8927a91", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1", "ami-a89870c1" # and more... ``` Or: ``` chef (preprod) > amis = nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } chef (preprod) > puts amis.uniq.sort ``` will return something similar to: ``` => ami-4b4ba522 ami-a89870c1 ami-eef61587 ami-f8927a91 ``` #### Use Breakpoints chef-shell allows the current position in a run-list to be manipulated during a Chef Infra Client run. Add breakpoints to a recipe to take advantage of this functionality. ##### Step Through Run-list To explore how using the **breakpoint** to manually step through a Chef Infra Client run, create a simple recipe in chef-shell: ``` chef > recipe_mode chef:recipe > echo off chef:recipe > file "/tmp/before-breakpoint" chef:recipe > breakpoint "foo" chef:recipe > file "/tmp/after-breakpoint" ``` and then run Chef Infra Client: ``` chef:recipe > run_chef [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:17:49 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:17:49 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint ``` Chef Infra Client ran the first resource before the breakpoint (`file[/tmp/before-breakpoint]`), but then stopped after execution. Chef Infra Client attempted to name the breakpoint after its position in the source file, but Chef Infra Client was confused because the resource was entered interactively. From here, chef-shell can resume the interrupted Chef Infra Client run: ``` chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:27:08 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` A quick view of the `/tmp` directory shows that the following files were created: ``` after-breakpoint before-breakpoint ``` You can rewind and step through a Chef Infra Client run: ``` chef:recipe > Chef::Log.level = :debug # debug logging won't turn on automatically in this case => :debug chef:recipe > chef_run.rewind => 0 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File => 1 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint => 2 chef:recipe > chef_run.step [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:40:56 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File => 3 ``` From the output, the rewound run-list is shown, but when the resources are executed again, they will repeat their checks for the existence of files. If they exist, Chef Infra Client will skip creating them. If the files are deleted, then: ``` chef:recipe > ls("/tmp").grep(/breakpoint/).each {|f| rm "/tmp/#{f}" } => ["after-breakpoint", "before-breakpoint"] ``` Rewind, and then resume your Chef Infra Client run to get the expected results: ``` chef:recipe > chef_run.rewind chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing file[/tmp/before-breakpoint] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:48:56 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint chef:recipe > chef_run.resume [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: Processing file[/tmp/after-breakpoint] [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File [Fri, 15 Jan 2020 14:49:20 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint ``` ##### Debug Existing Recipe chef-shell can be used to debug existing recipes. The recipe first needs to be added to a run-list for the node, so that it is cached when starting chef-shell and then used for debugging. chef-shell will report which recipes are being cached when it is started: ``` loading configuration: none (standalone session) Session type: standalone Loading.............done. Welcome to the chef-shell 15.8.23 For usage see https://docs.chef.io/chef_shell.html run `help' for help, `exit' or ^D to quit. chef (15.8.23)``` To just load one recipe from the run-list, go into the recipe and use the `include_recipe` command. For example: ``` chef > recipe_mode chef:recipe > include_recipe "getting-started" => [#< Chef::Recipe:0x10256f9e8 @cookbook_name="getting-started", ... output truncated ... ``` To load all of the recipes from a run-list, use code similar to the following: ``` node.run_list.expand(node.chef_environment).recipes.each do |r| include_recipe r end ``` After the recipes that are to be debugged have been loaded, use the `run_chef` command to run them. ##### Advanced Debugging In chef-shell, it is possible to get verbose debugging using the tracing feature in Interactive Ruby (IRb). chef-shell provides a shortcut for turning tracing on and off. For example: ``` chef > tracing on tracing is on => nil chef ``` and: ``` chef > tracing off #0:(irb):2:Object:-: tracing off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:109:Shell::Extensions::ObjectCoreExtensions:>: def off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:110:Shell::Extensions::ObjectCoreExtensions:-: :off #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:111:Shell::Extensions::ObjectCoreExtensions:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:272:main:>: def tracing(on_or_off) #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:273:main:-: conf.use_tracer = on_or_off.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:162:Shell::Extensions::Symbol:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:163:Shell::Extensions::Symbol:-: to_s.on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:149:Shell::Extensions::String:>: def on_off_to_bool #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:150:Shell::Extensions::String:-: case self #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:154:Shell::Extensions::String:-: false #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:158:Shell::Extensions::String:<: end #0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:164:Shell::Extensions::Symbol:<: end tracing is off => nil chef ``` #### Debug Examples The following examples show how to use chef-shell. ##### "Hello World" This example shows how to run chef-shell in standalone mode. (For chef-solo or Chef Infra Client modes, you would need to run chef-shell using the `-s` or `-z` command line options, and then take into consideration the necessary configuration settings.) When Chef Infra Client is installed using RubyGems or a package manager, chef-shell should already be installed. When Chef Infra Client is run from a git clone, it will be located in `chef/bin/chef shell`. To start chef-shell, just run it without any options. You’ll see the loading message, then the banner, and then the chef-shell prompt: ``` bin/chef-shell loading configuration: none (standalone session) Session type: standalone Loading.............done. Welcome to the chef-shell 15.8.23 For usage see https://docs.chef.io/chef_shell.html run `help' for help, `exit' or ^D to quit. chef (15.8.23)``` (Use the help command to print a list of supported commands.) Use the recipe_mode command to switch to recipe context: ``` chef > recipe_mode chef:recipe_mode ``` Typing is evaluated in the same context as recipes. Create a file resource: ``` chef:recipe_mode > file "/tmp/ohai2u_shef" => #< Chef::Resource::File:0x1b691ac @enclosing_provider=nil, @resource_name=:file, @before=nil, @supports={}, @backup=5, @allowed_actions=[:nothing, :create, :delete, :touch, :create_if_missing], @only_if=nil, @noop=nil, @collection=#< Chef::ResourceCollection:0x1b9926c @insert_after_idx=nil, @resources_by_name={"file[/tmp/ohai2u_shef]"=>0}, @resources=[#< Chef::Resource::File:0x1b691ac ...>]>, @updated=false, @provider=nil, @node=< Chef::Node:0xdeeaae @name="eigenstate.local">, @recipe_name=nil, @not_if=nil, @name="/tmp/ohai2u_shef", @action="create", @path="/tmp/ohai2u_shef", @source_line="/Users/username/ruby/chef/chef/(irb#1) line 1", @params={}, @actions={}, @cookbook_name=nil, @ignore_failure=false``` (The previous example was formatted for presentation.) At this point, chef-shell has created the resource and put it in the run-list, but not yet created the file. To initiate a Chef Infra Client run, use the `run_chef` command: ``` chef:recipe_mode > run_chef [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: Processing file[/tmp/ohai2u_shef] [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File [Fri, 15 Jan 2020 10:42:47 -0800] INFO: Creating file[/tmp/ohai2u_shef] at /tmp/ohai2u_shef => true ``` chef-shell can also switch to the same context as attribute files. Set an attribute with the following syntax: ``` chef:recipe_mode > attributes_mode chef:attributes > default[:hello] = "ohai2u-again" => "ohai2u-again" chef:attributes ``` Switch back to recipe_mode context and use the attributes: ``` chef:attributes > recipe_mode => :attributes chef:recipe_mode > file "/tmp/#{node.hello}" ``` Now, run Chef Infra Client again: ``` chef:recipe_mode > run_chef [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u_shef] [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u-again] [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u-again] using Chef::Provider::File [Fri, 15 Jan 2020 10:53:22 -0800] INFO: Creating file[/tmp/ohai2u-again] at /tmp/ohai2u-again => true chef:recipe_mode ``` Because the first resource (`file[/tmp/ohai2u_shef]`) is still in the run-list, it gets executed again. And because that file already exists, Chef Infra Client doesn’t attempt to re-create it. Finally, the files were created using the `ls` method: ``` chef:recipe_mode > ls("/tmp").grep(/ohai/) => ["ohai2u-again", "ohai2u_shef"] Shell Tutorial ``` ##### Get Specific Nodes To get a list of nodes using a recipe named `postfix` use `search(:node,"recipe:postfix")`. To get a list of nodes using a sub-recipe named `delivery`, use chef-shell. For example: ``` search(:node, 'recipes:postfix\:\:delivery') ``` Note Single (' ‘) vs. double (" “) is important. This is because a backslash () needs to be included in the string, instead of having Ruby interpret it as an escape. ### Examples --- The following examples demonstrate various approaches for using the **breakpoint** resource in recipes: **A recipe without a breakpoint** ``` yum_key node['yum']['elrepo']['key'] do url node['yum']['elrepo']['key_url'] action :add end yum_repository 'elrepo' do description 'ELRepo.org Community Enterprise Linux Extras Repository' key node['yum']['elrepo']['key'] mirrorlist node['yum']['elrepo']['url'] includepkgs node['yum']['elrepo']['includepkgs'] exclude node['yum']['elrepo']['exclude'] action :create end ``` **The same recipe with breakpoints** In the following example, the name of each breakpoint is an arbitrary string. ``` breakpoint "before yum_key node['yum']['repo_name']['key']" do action :break end yum_key node['yum']['repo_name']['key'] do url node['yum']['repo_name']['key_url'] action :add end breakpoint "after yum_key node['yum']['repo_name']['key']" do action :break end breakpoint "before yum_repository 'repo_name'" do action :break end yum_repository 'repo_name' do description 'description' key node['yum']['repo_name']['key'] mirrorlist node['yum']['repo_name']['url'] includepkgs node['yum']['repo_name']['includepkgs'] exclude node['yum']['repo_name']['exclude'] action :create end breakpoint "after yum_repository 'repo_name'" do action :break end ``` In the previous examples, the names are used to indicate if the breakpoint is before or after a resource and also to specify which resource it is before or after. build_essential resource ------------------------- [build_essential resource page](resources/build_essential/index) --- Use the **build_essential** resource to install the packages required for compiling C software from source. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **build_essential** resource is: ``` build_essential 'name' do raise_if_unsupported true, false # default value: false action Symbol # defaults to :install if not specified end ``` where: * `build_essential` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `raise_if_unsupported` is the property available to this resource. ### Nameless This resource can be **nameless**. Add the resource itself to your recipe to get the default behavior: ``` build_essential ``` will behave the same as: ``` build_essential 'install tools' ``` ### Actions --- The **build_essential** resource has the following actions: `:install` Install build essential packages. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:upgrade` Upgrade the Xcode CLI Tools on macOS hosts. **New in Chef Infra Client 16** ### Properties --- The **build_essential** resource has the following properties: `raise_if_unsupported` **Ruby Type:** true, false | **Default Value:** `false` Raise a hard error on platforms where this resource is unsupported. New in Chef Infra Client 15.5 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **build_essential** resource in recipes: **Install compilation packages**: ``` build_essential ``` **Install compilation packages during the compilation phase**: ``` build_essential 'Install compilation tools' do compile_time true end ``` **Upgrade compilation packages on macOS systems**: ``` build_essential 'Install compilation tools' do action :upgrade end ``` cab_package resource --------------------- [cab_package resource page](resources/cab_package/index) --- Use the **cab_package** resource to install or remove Microsoft Windows cabinet (.cab) packages. **New in Chef Infra Client 12.15.** ### Syntax --- The full syntax for all of the properties that are available to the **cab_package** resource is: ``` cab_package 'name' do options String, Array package_name String source String # default value: The package name. timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `cab_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **cab_package** resource has the following actions: `:install` Installs the cabinet package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes the cabinet package. ### Properties --- The **cab_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String | **Default Value:** `The package name.` The local file path or URL for the CAB package. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **cab_package** resource in recipes: **Using local path in source** ``` cab_package 'Install .NET 3.5 sp1 via KB958488' do source 'C:\Users\xyz\AppData\Local\Temp\Windows6.1-KB958488-x64.cab' action :install end cab_package 'Remove .NET 3.5 sp1 via KB958488' do source 'C:\Users\xyz\AppData\Local\Temp\Windows6.1-KB958488-x64.cab' action :remove end ``` **Using URL in source** ``` cab_package 'Install .NET 3.5 sp1 via KB958488' do source 'https://s3.amazonaws.com/my_bucket/Windows6.1-KB958488-x64.cab' action :install end cab_package 'Remove .NET 3.5 sp1 via KB958488' do source 'https://s3.amazonaws.com/my_bucket/Temp\Windows6.1-KB958488-x64.cab' action :remove end ``` chef_acl resource ------------------ [chef_acl resource page](resources/chef_acl/index) --- Use the **chef_acl** resource to interact with access control lists (ACLs) that exist on the Chef Infra Server. ### Syntax --- The syntax for using the **chef_acl** resource in a recipe is as follows: ``` chef_acl 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_acl` tells Chef Infra Client to use the `Chef::Provider::ChefAcl` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `path` property is not specified as part of a recipe, `name` is also the name of the Chef Infra Client. * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_acl** resource has the following actions: `:create` Default. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_acl** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a chef-client completely. When `true`, any property not specified by this resource will be reset to default property values. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `path` A path to a directory in the chef-repo against which the ACL is applied. For example: `nodes`, `nodes/*`, `nodes/my_node`, `*/*`, `**`, `roles/base`, `data/secrets`, `cookbooks/apache2`, `/users/*`, and so on. `raw_json` Chef Infra Client as JSON data. For example: ``` { "clientname": "client_name", "orgname": "org_name", "validator": false, "certificate": "-----BEGIN CERTIFICATE-----\n ... 1234567890abcdefghijklmnopq\n ... -----END CERTIFICATE-----\n", "name": "node_name" } ``` `recursive` Use to apply changes to child objects. Use `:on_change` to apply changes to child objects only if the parent object changes. Set to `true` to apply changes even if the parent object does not change. Set to `false` to prevent any changes. Default value: `:on_change`. `remove_rights` Use to remove rights. For example: ``` remove_rights :read, :users => 'jkeiser', :groups => [ 'admins', 'users' ] ``` or: ``` remove_rights [ :create, :read ], :users => [ 'jkeiser', 'adam' ] ``` or: ``` remove_rights :all, :users => [ 'jkeiser', 'adam' ] ``` `rights` Use to add rights. Syntax: `:right, :right => 'user', :groups => [ 'group', 'group']`. For example: ``` rights :read, :users => 'jkeiser', :groups => [ 'admins', 'users' ] ``` or: ``` rights [ :create, :read ], :users => [ 'jkeiser', 'adam' ] ``` or: ``` rights :all, :users => 'jkeiser' ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_client resource --------------------- [chef_client resource page](resources/chef_client/index) --- Use the **chef_client** resource to create clients on your Chef Infra Server from within Chef Infra cookbook code. ### Syntax --- The syntax for using the **chef_client** resource in a recipe is as follows: ``` chef_client 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_client` tells Chef Infra Client to use the `Chef::Provider::ChefClient` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the Chef Infra Client * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_client** resource has the following actions: `:create` Default. Use to create a chef-client. `:delete` Use to delete a chef-client. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:regenerate_keys` Use to regenerate the RSA public key for a chef-client. ### Properties --- The **chef_client** resource has the following properties: `admin` Use to specify whether Chef Infra Client is an API client. `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a chef-client completely. When `true`, any property not specified by this resource will be reset to default property values. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of Chef Infra Client. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `output_key_format` Use to specify the format of a public key. Possible values: `pem`, `der`, or `openssh`. Default value: `openssh`. `output_key_path` Use to specify the path to the location in which a public key will be written. `raw_json` Chef Infra Client as JSON data. For example: ``` { "clientname": "client_name", "orgname": "org_name", "validator": false, "certificate": "-----BEGIN CERTIFICATE-----\n ... 1234567890abcdefghijklmnopq\n ... -----END CERTIFICATE-----\n", "name": "node_name" } ``` `source_key` Use to copy a public or private key, but apply a different `format` and `password`. Use in conjunction with `source_key_pass_phrase` and `source_key_path`. `source_key_pass_phrase` The pass phrase for the public key. Use in conjunction with `source_key` and `source_key_path`. `source_key_path` The path to the public key. Use in conjunction with `source_key` and `source_key_pass_phrase`. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `validator` Use to specify if Chef Infra Client is a chef-validator. ### Examples --- This resource does not have any examples. chef_client_config resource ----------------------------- [chef_client_config resource page](resources/chef_client_config/index) --- Use the **chef_client_config** resource to create a client.rb file in the Chef Infra Client configuration directory. See the [client.rb docs](config_rb_client/index) for more details on options available in the client.rb configuration file. **New in Chef Infra Client 16.6.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_config** resource is: ``` chef_client_config 'name' do additional_config String chef_license String chef_server_url String config_directory String data_collector_server_url String data_collector_token String event_loggers Array # default value: [] exception_handlers Array # default value: [] file_backup_path String file_cache_path String file_staging_uses_destdir String formatters Array # default value: [] ftp_proxy String group String http_proxy String https_proxy String log_level Symbol log_location String, Symbol minimal_ohai true, false named_run_list String no_proxy String, Array # default value: [] node_name String ohai_disabled_plugins Array # default value: [] ohai_optional_plugins Array # default value: [] pid_file String policy_group String policy_name String policy_persist_run_list true, false report_handlers Array # default value: [] ssl_verify_mode Symbol, String start_handlers Array # default value: [] user String action Symbol # defaults to :create if not specified end ``` where: * `chef_client_config` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `additional_config`, `chef_license`, `chef_server_url`, `config_directory`, `data_collector_server_url`, `data_collector_token`, `event_loggers`, `exception_handlers`, `file_backup_path`, `file_cache_path`, `file_staging_uses_destdir`, `formatters`, `ftp_proxy`, `group`, `http_proxy`, `https_proxy`, `log_level`, `log_location`, `minimal_ohai`, `named_run_list`, `no_proxy`, `node_name`, `ohai_disabled_plugins`, `ohai_optional_plugins`, `pid_file`, `policy_group`, `policy_name`, `policy_persist_run_list`, `report_handlers`, `ssl_verify_mode`, `start_handlers`, and `user` are the properties available to this resource. ### Actions --- The **chef_client_config** resource has the following actions: `:create` Create a client.rb config file for configuring Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a client.rb config file for configuring Chef Infra Client. ### Properties --- The **chef_client_config** resource has the following properties: `additional_config` **Ruby Type:** String Additional text to add at the bottom of the client.rb config. This can be used to run custom Ruby or to add less common config options `chef_license` **Ruby Type:** String **Allowed Values:** `"accept", "accept-no-persist", "accept-silent"` Accept the [Chef EULA](https://www.chef.io/end-user-license-agreement/) `chef_server_url` **Ruby Type:** String | `REQUIRED` The URL for the Chef Infra Server. `config_directory` **Ruby Type:** String | **Default Value:** ``/etc/chef/` on *nix-like systems and `C:\chef\` on Windows` The directory to store the client.rb in. `data_collector_server_url` **Ruby Type:** String The data collector URL (typically automate) to send node, converge, and compliance data. Note If possible, use Chef Infra Server to do all data collection reporting, as this removes the need to distribute tokens to individual nodes. New in Chef Infra Client 17.8 `data_collector_token` **Ruby Type:** String The data collector token to interact with the data collector server URL (Automate). Note If possible, use Chef Infra Server to do all data collection reporting, as this removes the need to distribute tokens to individual nodes. New in Chef Infra Client 17.8 `event_loggers` **Ruby Type:** Array | **Default Value:** `[]` `exception_handlers` **Ruby Type:** Array | **Default Value:** `[]` An array of hashes that contain a exception handler class and the arguments to pass to that class on initialization. The hash should include `class` and `argument` keys where `class` is a String and `argument` is an array of quoted String values. For example: `[{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]` `file_backup_path` **Ruby Type:** String The location in which backup files are stored. If this value is empty, backup files are stored in the directory of the target file `file_cache_path` **Ruby Type:** String The location in which cookbooks (and other transient data) files are stored when they are synchronized. This value can also be used in recipes to download files with the `remote_file` resource. `file_staging_uses_destdir` **Ruby Type:** String How file staging (via temporary files) is done. When `true`, temporary files are created in the directory in which files will reside. When `false`, temporary files are created under `ENV['TMP']` `formatters` **Ruby Type:** Array | **Default Value:** `[]` Client logging formatters to load. `ftp_proxy` **Ruby Type:** String The proxy server to use for FTP connections. `group` **Ruby Type:** String The group that should own the client.rb file and the configuration directory if it needs to be created. Note The configuration directory will not be created if it already exists, which allows you to further control the setup of that directory outside of this resource. `http_proxy` **Ruby Type:** String The proxy server to use for HTTP connections. `https_proxy` **Ruby Type:** String The proxy server to use for HTTPS connections. `log_level` **Ruby Type:** Symbol **Allowed Values:** `:auto, :debug, :fatal, :info, :trace, :warn` The level of logging performed by the Chef Infra Client. `log_location` **Ruby Type:** String, Symbol The location to save logs to. This can either by a path to a log file on disk `:syslog` to log to Syslog, `:win_evt` to log to the Windows Event Log, or `'STDERR'`/`'STDOUT'` to log to the *nix text streams. `minimal_ohai` **Ruby Type:** true, false Run a minimal set of Ohai plugins providing data necessary for the execution of Chef Infra Client’s built-in resources. Setting this to true will skip many large and time consuming data sets such as `cloud` or `packages`. Setting this this to true may break cookbooks that assume all Ohai data will be present. `named_run_list` **Ruby Type:** String A specific named runlist defined in the node’s applied Policyfile, which the should be used when running Chef Infra Client. `no_proxy` **Ruby Type:** String, Array | **Default Value:** `[]` A comma-separated list or an array of URLs that do not need a proxy. `node_name` **Ruby Type:** String | **Default Value:** `The `node.name` value reported by Chef Infra Client.` The name of the node. This configuration sets the `node.name` value used in cookbooks and the `client_name` value used when authenticating to a Chef Infra Server to determine what configuration to apply. Note By default this configuration uses the `node.name` value which would be set during bootstrap. Hard coding this value in the `client.rb` config avoids logic within Chef Infra Server that performs DNS lookups and may fail in the event of a DNS outage. To skip this default value and instead use the built-in Chef Infra Server logic, set this property to `nil` `ohai_disabled_plugins` **Ruby Type:** Array | **Default Value:** `[]` Ohai plugins that should be disabled in order to speed up the Chef Infra Client run and reduce the size of node data sent to Chef Infra Client `ohai_optional_plugins` **Ruby Type:** Array | **Default Value:** `[]` Optional Ohai plugins that should be enabled to provide additional Ohai data for use in cookbooks. `pid_file` **Ruby Type:** String The location in which a process identification number (pid) is saved. An executable, when started as a daemon, writes the pid to the specified file. `policy_group` **Ruby Type:** String The name of a `policy group` that exists on the Chef Infra Server. `policy_name` must also be specified when setting this property. `policy_name` **Ruby Type:** String The name of a policy, as identified by the `name` setting in a Policyfile.rb file. `policy_group` when setting this property. `policy_persist_run_list` **Ruby Type:** true, false Override run lists defined in a Policyfile with the `run_list` defined on the Chef Infra Server. New in Chef Infra Client 17.3 `report_handlers` **Ruby Type:** Array | **Default Value:** `[]` An array of hashes that contain a report handler class and the arguments to pass to that class on initialization. The hash should include `class` and `argument` keys where `class` is a String and `argument` is an array of quoted String values. For example: `[{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]` `ssl_verify_mode` **Ruby Type:** Symbol, String **Allowed Values:** `:verify_none, :verify_peer` Set the verify mode for HTTPS requests. * Use :verify_none for no validation of SSL certificates. * Use :verify_peer for validation of all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS remote_file resource URLs used in Chef Infra Client runs. This is the recommended setting. `start_handlers` **Ruby Type:** Array | **Default Value:** `[]` An array of hashes that contain a report handler class and the arguments to pass to that class on initialization. The hash should include `class` and `argument` keys where `class` is a String and `argument` is an array of quoted String values. For example: `[{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]` `user` **Ruby Type:** String The user that should own the client.rb file and the configuration directory if it needs to be created. Note The configuration directory will not be created if it already exists, which allows you to further control the setup of that directory outside of this resource. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_config** resource in recipes: **Bare minimum Chef Infra Client client.rb**: The absolute minimum configuration necessary for a node to communicate with the Chef Infra Server is the URL of the Chef Infra Server. All other configuration options either have values at the server side (Policyfiles, Roles, Environments, etc) or have default values determined at client startup. ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' end ``` **More complex Chef Infra Client client.rb**: ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' log_level :info log_location :syslog http_proxy 'proxy.example.dmz' https_proxy 'proxy.example.dmz' no_proxy %w(internal.example.dmz) end ``` **Adding additional config content to the client.rb**: This resource aims to provide common configuration options. Some configuration options are missing and some users may want to use arbitrary Ruby code within their configuration. For this we offer an `additional_config` property that can be used to add any configuration or code to the bottom of the `client.rb` file. Also keep in mind that within the configuration directory is a `client.d` directory where you can put additional `.rb` files containing configuration options. These can be created using `file` or `template` resources within your cookbooks as necessary. ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' additional_config <<~CONFIG # Extra config code to safely load a gem into the client run. # Since the config is Ruby you can run any Ruby code you want via the client.rb. # It's a great way to break things, so be careful begin require 'aws-sdk' rescue LoadError Chef::Log.warn "Failed to load aws-sdk." end CONFIG end ``` **Setup two report handlers in the client.rb**: ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' report_handlers [ { 'class' => 'ReportHandler1Class', 'arguments' => ["'FirstArgument'", "'SecondArgument'"], }, { 'class' => 'ReportHandler2Class', 'arguments' => ["'FirstArgument'", "'SecondArgument'"], }, ] end ``` **Report directly to the [Chef Automate data collector endpoint](automate/data_collection/index#configure-chef-infra-client-to-use-the-data-collector-endpoint-in-chef-automate).** ``` chef_client_config 'Create client.rb' do chef_server_url 'https://chef.example.dmz' data_collector_server_url 'https://automate.example.dmz' data_collector_token 'TEST_TOKEN_TEST' end ``` chef_client_cron resource --------------------------- [chef_client_cron resource page](resources/chef_client_cron/index) --- Use the **chef_client_cron** resource to setup the Chef Infra Client to run as a cron job. This resource will also create the specified log directory if it doesn’t already exist. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_cron** resource is: ``` chef_client_cron 'name' do accept_chef_license true, false # default value: false append_log_file true, false # default value: true chef_binary_path String # default value: "/opt/chef/bin/chef-client" comment String config_directory String # default value: "/etc/chef" daemon_options Array # default value: [] day Integer, String # default value: "*" environment Hash # default value: {} hour Integer, String # default value: "*" job_name String # default value: "chef-client" log_directory String log_file_name String # default value: "client.log" mailto String minute Integer, String # default value: "0,30" month Integer, String # default value: "*" nice Integer, String splay Integer, String # default value: 300 user String # default value: "root" weekday Integer, String # default value: "*" action Symbol # defaults to :add if not specified end ``` where: * `chef_client_cron` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `append_log_file`, `chef_binary_path`, `comment`, `config_directory`, `daemon_options`, `day`, `environment`, `hour`, `job_name`, `log_directory`, `log_file_name`, `mailto`, `minute`, `month`, `nice`, `splay`, `user`, and `weekday` are the properties available to this resource. ### Actions --- The **chef_client_cron** resource has the following actions: `:add` Add a cron job to run Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a cron job for Chef Infra Client. ### Properties --- The **chef_client_cron** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `append_log_file` **Ruby Type:** true, false | **Default Value:** `true` Append to the log file instead of overwriting the log file on each run. `chef_binary_path` **Ruby Type:** String | **Default Value:** `/opt/chef/bin/chef-client` The path to the chef-client binary. `comment` **Ruby Type:** String A comment to place in the cron.d file. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `day` **Ruby Type:** Integer, String | **Default Value:** `*` The day of month at which Chef Infra Client is to run (1 - 31) or a cron pattern such as ‘1,7,14,21,28’. `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. `hour` **Ruby Type:** Integer, String | **Default Value:** `*` The hour at which Chef Infra Client is to run (0 - 23) or a cron pattern such as ‘0,12’. `job_name` **Ruby Type:** String | **Default Value:** `chef-client` The name of the cron job to create. `log_directory` **Ruby Type:** String | **Default Value:** `/Library/Logs/Chef on macOS and /var/log/chef otherwise` The path of the directory to create the log file in. `log_file_name` **Ruby Type:** String | **Default Value:** `client.log` The name of the log file to use. `mailto` **Ruby Type:** String The e-mail address to e-mail any cron task failures to. `minute` **Ruby Type:** Integer, String | **Default Value:** `0,30` The minute at which Chef Infra Client is to run (0 - 59) or a cron pattern such as ‘0,30’. `month` **Ruby Type:** Integer, String | **Default Value:** `*` The month in the year on which Chef Infra Client is to run (1 - 12, jan-dec, or *). `nice` **Ruby Type:** Integer, String The process priority to run the chef-client process at. A value of -20 is the highest priority and 19 is the lowest priority. New in Chef Infra Client 16.5 `splay` **Ruby Type:** Integer, String | **Default Value:** `300` A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time. `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that Chef Infra Client runs as. `weekday` **Ruby Type:** Integer, String | **Default Value:** `*` The day of the week on which Chef Infra Client is to run (0-7, mon-sun, or *), where Sunday is both 0 and 7. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_cron** resource in recipes: **Setup Chef Infra Client to run using the default 30 minute cadence**: ``` chef_client_cron 'Run Chef Infra Client as a cron job' ``` **Run Chef Infra Client twice a day**: ``` chef_client_cron 'Run Chef Infra Client every 12 hours' do minute 0 hour '0,12' end ``` **Run Chef Infra Client with extra options passed to the client**: ``` chef_client_cron 'Run an override recipe' do daemon_options ['--override-runlist mycorp_base::default'] end ``` chef_client_launchd resource ------------------------------ [chef_client_launchd resource page](resources/chef_client_launchd/index) --- Use the **chef_client_launchd** resource to configure the Chef Infra Client to run on a schedule on macOS systems. **New in Chef Infra Client 16.5.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_launchd** resource is: ``` chef_client_launchd 'name' do accept_chef_license true, false # default value: false chef_binary_path String # default value: "/opt/chef/bin/chef-client" config_directory String # default value: "/etc/chef" daemon_options Array # default value: [] environment Hash # default value: {} interval Integer, String # default value: 30 log_directory String # default value: "/Library/Logs/Chef" log_file_name String # default value: "client.log" low_priority_io true, false # default value: true nice Integer, String splay Integer, String # default value: 300 user String # default value: "root" working_directory String # default value: "/var/root" action Symbol # defaults to :enable if not specified end ``` where: * `chef_client_launchd` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `chef_binary_path`, `config_directory`, `daemon_options`, `environment`, `interval`, `log_directory`, `log_file_name`, `low_priority_io`, `nice`, `splay`, `user`, and `working_directory` are the properties available to this resource. ### Actions --- The **chef_client_launchd** resource has the following actions: `:disable` Disable running Chef Infra Client on a schedule using launchd `:enable` Enable running Chef Infra Client on a schedule using launchd. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_client_launchd** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `chef_binary_path` **Ruby Type:** String | **Default Value:** `/opt/chef/bin/chef-client` The path to the chef-client binary. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the launchd daemon will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. `interval` **Ruby Type:** Integer, String | **Default Value:** `30` Time in minutes between Chef Infra Client executions. `log_directory` **Ruby Type:** String | **Default Value:** `/Library/Logs/Chef` The path of the directory to create the log file in. `log_file_name` **Ruby Type:** String | **Default Value:** `client.log` The name of the log file to use. `low_priority_io` **Ruby Type:** true, false | **Default Value:** `true` Run the chef-client process with low priority disk IO `nice` **Ruby Type:** Integer, String The process priority to run the chef-client process at. A value of -20 is the highest priority and 19 is the lowest priority. `splay` **Ruby Type:** Integer, String | **Default Value:** `300` A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time. `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that Chef Infra Client runs as. `working_directory` **Ruby Type:** String | **Default Value:** `/var/root` The working directory to run the Chef Infra Client from. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_launchd** resource in recipes: **Set the Chef Infra Client to run on a schedule**: ``` chef_client_launchd 'Setup the Chef Infra Client to run every 30 minutes' do interval 30 action :enable end ``` **Disable the Chef Infra Client running on a schedule**: ``` chef_client_launchd 'Prevent the Chef Infra Client from running on a schedule' do action :disable end ``` chef_client_scheduled_task resource -------------------------------------- [chef_client_scheduled_task resource page](resources/chef_client_scheduled_task/index) --- Use the **chef_client_scheduled_task** resource to setup the Chef Infra Client to run as a Windows scheduled task. This resource will also create the specified log directory if it doesn’t already exist. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_scheduled_task** resource is: ``` chef_client_scheduled_task 'name' do accept_chef_license true, false # default value: false chef_binary_path String # default value: "C:/opscode/chef/bin/chef-client" config_directory String # default value: "/etc/chef" daemon_options Array # default value: [] frequency String # default value: "minute" frequency_modifier Integer, String # default value: "30 if frequency is 'minute', 1 otherwise" log_directory String # default value: "CONFIG_DIRECTORY/log" log_file_name String # default value: "client.log" password String priority Integer # default value: 7 run_on_battery true, false # default value: true splay Integer, String # default value: 300 start_date String start_time String task_name String # default value: "chef-client" use_consistent_splay true, false # default value: false user String # default value: "System" action Symbol # defaults to :add if not specified end ``` where: * `chef_client_scheduled_task` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `chef_binary_path`, `config_directory`, `daemon_options`, `frequency`, `frequency_modifier`, `log_directory`, `log_file_name`, `password`, `priority`, `run_on_battery`, `splay`, `start_date`, `start_time`, `task_name`, `use_consistent_splay`, and `user` are the properties available to this resource. ### Actions --- The **chef_client_scheduled_task** resource has the following actions: `:add` Add a Windows Scheduled Task that runs Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows Scheduled Task that runs Chef Infra Client. ### Properties --- The **chef_client_scheduled_task** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `chef_binary_path` **Ruby Type:** String | **Default Value:** `C:/opscode/chef/bin/chef-client` The path to the chef-client binary. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `frequency` **Ruby Type:** String | **Default Value:** `minute` **Allowed Values:** `"daily", "hourly", "minute", "monthly", "on_idle", "on_logon", "once", "onstart"` Frequency with which to run the task. `frequency_modifier` **Ruby Type:** Integer, String | **Default Value:** `30 if frequency is 'minute', 1 otherwise` Numeric value to go with the scheduled task frequency `log_directory` **Ruby Type:** String | **Default Value:** `CONFIG_DIRECTORY/log` The path of the directory to create the log file in. `log_file_name` **Ruby Type:** String | **Default Value:** `client.log` The name of the log file to use. `password` **Ruby Type:** String The password for the user that Chef Infra Client runs as. `priority` **Ruby Type:** Integer | **Default Value:** `7` Use to set Priority Levels range from 0 to 10. New in Chef Infra Client 17.5 `run_on_battery` **Ruby Type:** true, false | **Default Value:** `true` Run the Chef Infra Client task when the system is on batteries. `splay` **Ruby Type:** Integer, String | **Default Value:** `300` A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time. `start_date` **Ruby Type:** String The start date for the task in m:d:Y format (ex: 12/17/2020). `start_time` **Ruby Type:** String The start time for the task in HH:mm format (ex: 14:00). If the frequency is minute default start time will be Time.now plus the frequency_modifier number of minutes. `task_name` **Ruby Type:** String | **Default Value:** `chef-client` The name of the scheduled task to create. `use_consistent_splay` **Ruby Type:** true, false | **Default Value:** `false` Always use the same random splay amount for each node to ensure consistent frequencies between chef-client execution. New in Chef Infra Client 17.5 `user` **Ruby Type:** String | **Default Value:** `System` The name of the user that Chef Infra Client runs as. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_scheduled_task** resource in recipes: **Setup Chef Infra Client to run using the default 30 minute cadence**: ``` chef_client_scheduled_task 'Run Chef Infra Client as a scheduled task' ``` **Run Chef Infra Client on system start**: ``` chef_client_scheduled_task 'Chef Infra Client on start' do frequency 'onstart' end ``` **Run Chef Infra Client with extra options passed to the client**: ``` chef_client_scheduled_task 'Run an override recipe' do daemon_options ['--override-runlist mycorp_base::default'] end ``` **Run Chef Infra Client daily at 01:00 am, specifying a named run-list**: ``` chef_client_scheduled_task 'Run chef-client named run-list daily' do frequency 'daily' start_time '01:00' daemon_options ['-n audit_only'] end ``` **Run Chef Infra Client with a persistent delay on every run calculated once, similar to how chef_client_cron resource works**: ``` chef_client_scheduled_task 'Run chef-client with persistent splay' do use_consistent_splay true end ``` chef_client_systemd_timer resource ------------------------------------- [chef_client_systemd_timer resource page](resources/chef_client_systemd_timer/index) --- Use the **chef_client_systemd_timer** resource to setup the Chef Infra Client to run as a systemd timer. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_systemd_timer** resource is: ``` chef_client_systemd_timer 'name' do accept_chef_license true, false # default value: false chef_binary_path String # default value: "/opt/chef/bin/chef-client" config_directory String # default value: "/etc/chef" cpu_quota Integer, String daemon_options Array # default value: [] delay_after_boot String # default value: "1min" description String # default value: "Chef Infra Client periodic execution" environment Hash # default value: {} interval String # default value: "30min" job_name String # default value: "chef-client" run_on_battery true, false # default value: true splay String # default value: "5min" user String # default value: "root" action Symbol # defaults to :add if not specified end ``` where: * `chef_client_systemd_timer` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_chef_license`, `chef_binary_path`, `config_directory`, `cpu_quota`, `daemon_options`, `delay_after_boot`, `description`, `environment`, `interval`, `job_name`, `run_on_battery`, `splay`, and `user` are the properties available to this resource. ### Actions --- The **chef_client_systemd_timer** resource has the following actions: `:add` Add a systemd timer that runs Chef Infra Client. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a systemd timer that runs Chef Infra Client. ### Properties --- The **chef_client_systemd_timer** resource has the following properties: `accept_chef_license` **Ruby Type:** true, false | **Default Value:** `false` Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement `chef_binary_path` **Ruby Type:** String | **Default Value:** `/opt/chef/bin/chef-client` The path to the chef-client binary. `config_directory` **Ruby Type:** String | **Default Value:** `/etc/chef` The path of the config directory. `cpu_quota` **Ruby Type:** Integer, String The systemd CPUQuota to run the chef-client process with. This is a percentage value of the total CPU time available on the system. If the system has more than 1 core this may be a value greater than 100. New in Chef Infra Client 16.5 `daemon_options` **Ruby Type:** Array | **Default Value:** `[]` An array of options to pass to the chef-client command. `delay_after_boot` **Ruby Type:** String | **Default Value:** `1min` The time to wait after booting before the interval starts. This is expressed as a systemd time span such as `300seconds`, `1hr`, or `1m`. See <https://www.freedesktop.org/software/systemd/man/systemd.time.html> for a complete list of allowed time span values. `description` **Ruby Type:** String | **Default Value:** `Chef Infra Client periodic execution` The description to add to the systemd timer. This will be displayed when running `systemctl status` for the timer. `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the systemd timer will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. `interval` **Ruby Type:** String | **Default Value:** `30min` The interval to wait between executions. This is expressed as a systemd time span such as `300seconds`, `1hr`, or `1m`. See <https://www.freedesktop.org/software/systemd/man/systemd.time.html> for a complete list of allowed time span values. `job_name` **Ruby Type:** String | **Default Value:** `chef-client` The name of the system timer to create. `run_on_battery` **Ruby Type:** true, false | **Default Value:** `true` Run the timer for Chef Infra Client if the system is on battery. `splay` **Ruby Type:** String | **Default Value:** `5min` A interval between 0 and X to add to the interval so that all chef-client commands don’t execute at the same time. This is expressed as a systemd time span such as `300seconds`, `1hr`, or `1m`. See <https://www.freedesktop.org/software/systemd/man/systemd.time.html> for a complete list of allowed time span values. `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that Chef Infra Client runs as. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_systemd_timer** resource in recipes: **Setup Chef Infra Client to run using the default 30 minute cadence**: ``` chef_client_systemd_timer 'Run Chef Infra Client as a systemd timer' ``` **Run Chef Infra Client every 1 hour**: ``` chef_client_systemd_timer 'Run Chef Infra Client every 1 hour' do interval '1hr' end ``` **Run Chef Infra Client with extra options passed to the client**: ``` chef_client_systemd_timer 'Run an override recipe' do daemon_options ['--override-runlist mycorp_base::default'] end ``` chef_client_trusted_certificate resource ------------------------------------------- [chef_client_trusted_certificate resource page](resources/chef_client_trusted_certificate/index) --- Use the **chef_client_trusted_certificate** resource to add certificates to Chef Infra Client’s trusted certificate directory. This allows the Chef Infra Client to communicate with internal encrypted resources without errors. **New in Chef Infra Client 16.5.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_client_trusted_certificate** resource is: ``` chef_client_trusted_certificate 'name' do cert_name String # default value: 'name' unless specified certificate String action Symbol # defaults to :add if not specified end ``` where: * `chef_client_trusted_certificate` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `cert_name` and `certificate` are the properties available to this resource. ### Actions --- The **chef_client_trusted_certificate** resource has the following actions: `:add` Add a trusted certificate to Chef Infra Client’s trusted certificate directory (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a trusted certificate from Chef Infra Client’s trusted certificate directory ### Properties --- The **chef_client_trusted_certificate** resource has the following properties: `cert_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name to use for the certificate file on disk. If not provided the name of the resource block will be used instead. `certificate` **Ruby Type:** String | `REQUIRED` The text of the certificate file including the BEGIN/END comment lines. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_client_trusted_certificate** resource in recipes: **Trust a self signed certificate**: ``` chef_client_trusted_certificate 'self-signed.badssl.com' do certificate <<~CERT -----BEGIN CERTIFICATE----- MIIDeTCCAmGgAwIBAgIJAPziuikCTox4MA0GCSqGSIb3DQEBCwUAMGIxCzAJBgNV BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNp c2NvMQ8wDQYDVQQKDAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTAeFw0x OTEwMDkyMzQxNTJaFw0yMTEwMDgyMzQxNTJaMGIxCzAJBgNVBAYTAlVTMRMwEQYD VQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc<KEY>wW0W75Va5AEnJuqpQrKwl3KQVe wGj67WWRgLfSr+4QG1mNvCZb2CkjZWmxkGPuoP40/y7Yu5OFqxP5tAjj4YixCYTW EVA0pmzIzgBg+JIe3PdRy27T0asgQW/F4TY61Yk= -----END CERTIFICATE----- CERT end ``` chef_container resource ------------------------ [chef_container resource page](resources/chef_container/index) --- Use the **chef_container** resource to interact with container objects that exist on the Chef Infra Server. ### Syntax --- The syntax for using the **chef_container** resource in a recipe is as follows: ``` chef_container 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_container` tells Chef Infra Client to use the `Chef::Provider::ChefContainer` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_container** resource has the following actions: `:create` Default. `:delete` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_container** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the container. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_data_bag resource ------------------------ [chef_data_bag resource page](resources/chef_data_bag/index) --- Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search. Use the **chef_data_bag** resource to manage data bags. ### Syntax --- The syntax for using the **chef_data_bag** resource in a recipe is as follows: ``` chef_data_bag 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_data_bag` tells Chef Infra Client to use the `Chef::Provider::ChefDataBag` provider during a Chef Infra Client run * `name` is the name of the resource block and also the name of the data bag * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_data_bag** resource has the following actions: `:create` Default. Use to create a data bag. `:delete` Use to delete a data bag. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_data_bag** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the data bag. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_data_bag_item resource ------------------------------ [chef_data_bag_item resource page](resources/chef_data_bag_item/index) --- A data bag is a container of related data bag items, where each individual data bag item is a JSON file. knife can load a data bag item by specifying the name of the data bag to which the item belongs and then the filename of the data bag item. The only structural requirement of a data bag item is that it must have an `id`: ``` { /* This is a supported comment style */ // This style is also supported "id": "ITEM_NAME", "key": "value" } ``` where * `key` and `value` are the `key:value` pair for each additional attribute within the data bag item * `/* ... */` and `// ...` show two ways to add comments to the data bag item Use the **chef_data_bag_item** resource to manage data bag items. ### Syntax --- The syntax for using the **chef_data_bag_item** resource in a recipe is as follows: ``` chef_data_bag_item 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_data_bag_item` tells Chef Infra Client to use the `Chef::Provider::ChefDataBagItem` provider during a Chef Infra Client run * `name` is the name of the resource block and also the name of the data bag item * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_data_bag_item** resource has the following actions: `:create` Default. Use to create a data bag item. `:delete` Use to delete a data bag item. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_data_bag_item** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a data bag item completely. When `true`, any property not specified by this resource will be reset to default property values. `encrypt` Use to specify whether encryption is used for a data bag item. `encryption_version` The minimum required version of data bag encryption. Possible values: `0`, `1`, `2`, and `3`. When all of the machines in an organization are running chef-client version 13.0.113 (or higher), it is recommended that this value be set to `3`. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `raw_data` Use to create a data bag from a local file from `./data_bags/bag_name/file`. `raw_json` The data bag item as JSON data. For example: ``` { "id": "adam", "real_name": "<NAME>" } ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_environment resource -------------------------- [chef_environment resource page](resources/chef_environment/index) --- An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production. Use the **chef_environment** resource to manage environments. ### Syntax --- The syntax for using the **chef_environment** resource in a recipe is as follows: ``` chef_environment 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_environment` tells Chef Infra Client to use the `Chef::Provider::ChefEnvironment` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the environment * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_environment** resource has the following actions: `:create` Default. Use to create an environment. `:delete` Use to delete an environment. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_environment** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines an environment completely. When `true`, any property not specified by this resource will be reset to default property values. `cookbook_versions` The cookbook versions used with the environment. Default value: `{}`. `default_attributes` A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. Default value: `{}`. `description` The description of the environment. This value populates the description field for the environment on the Chef Infra Server. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the environment. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `override_attributes` An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. Default value: `{}`. `raw_json` The environment as JSON data. For example: ``` { "name":"backend", "description":"", "cookbook_versions":{}, "json_class":"Chef::Environment", "chef_type":"environment", "default_attributes":{}, "override_attributes":{} } ``` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_gem resource ------------------ [chef_gem resource page](resources/chef_gem/index) --- Use the **chef_gem** resource to install a gem only for the instance of Ruby that is dedicated to the chef-client. When a gem is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. The **chef_gem** resource works with all of the same properties and options as the **gem_package** resource, but does not accept the `gem_binary` property because it always uses the `CurrentGemEnvironment` under which the `chef-client` is running. In addition to performing actions similar to the **gem_package** resource, the **chef_gem** resource does the following: * Runs its actions immediately, before convergence, allowing a gem to be used in a recipe immediately after it is installed. * Runs `Gem.clear_paths` after the action, ensuring that gem is aware of changes so that it can be required immediately after it is installed. Warning The **chef_gem** and **gem_package** resources are both used to install Ruby gems. For any machine on which Chef Infra Client is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is available only to Chef Infra Client. Use the **chef_gem** resource to install gems into the instance of Ruby that is dedicated to Chef Infra Client. Use the **gem_package** resource to install all other gems (i.e. install gems system-wide). ### Syntax --- The full syntax for all of the properties that are available to the **chef_gem** resource is: ``` chef_gem 'name' do clear_sources true, false gem_binary String include_default_source true, false options String, Hash, Array package_name String source String, Array timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `chef_gem` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `clear_sources`, `gem_binary`, `include_default_source`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **chef_gem** resource has the following actions: `:install` Default. Install a gem. If a version is specified, install the specified version of the gem. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a gem. This action typically removes the configuration files as well as the gem. `:reconfig` Reconfigure a gem. This action requires a response file. `:remove` Remove a gem. `:upgrade` Install a gem and/or ensure that a gem is the latest version. ### Properties --- The **chef_gem** resource has the following properties: `clear_sources` **Ruby Type:** true, false | **Default Value:** `false unless `clear_gem_sources` set to true in the `client.rb` config.` Set to `true` to download a gem from the path specified by the `source` property (and not from RubyGems). `gem_binary` **Ruby Type:** String | **Default Value:** `The `gem` binary included with Chef Infra Client.` The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by Chef Infra Client will be used. `include_default_source` **Ruby Type:** true, false Set to `false` to not include `Chef::Config[:rubygems_url]` in the sources. New in Chef Client 13.0 `options` **Ruby Type:** String, Hash, Array Options for the gem install, either a Hash or a String. When a hash is given, the options are passed to `Gem::DependencyInstaller.new`, and the gem will be installed via the gems API. When a String is given, the gem will be installed by shelling out to the gem command. Using a Hash of options with an explicit gem_binary will result in undefined behavior. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String, Array Optional. The URL, or list of URLs, at which the gem package is located. This list is added to the source configured in `Chef::Config[:rubygems_url]` (see also include_default_source) to construct the complete list of rubygems sources. Users in an ‘airgapped’ environment should set Chef::Config[:rubygems_url] to their local RubyGems mirror. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_gem** resource in recipes: **Compile time vs. converge time installation of gems** To install a gem while Chef Infra Client is configuring the node (the converge phase), set the `compile_time` property to `false`: ``` chef_gem 'loofah' do compile_time false action :install end ``` To install a gem while the resource collection is being built (the compile phase), set the `compile_time` property to `true`: ``` chef_gem 'loofah' do compile_time true action :install end ``` **Install MySQL gem into Chef Infra Client*** ``` apt_update build_essential 'install compilation tools' do compile_time true end chef_gem 'mysql' ``` chef_group resource -------------------- [chef_group resource page](resources/chef_group/index) --- Use the **chef_group** resource to interact with group objects that exist on the Chef server. ### Syntax --- The syntax for using the **chef_group** resource in a recipe is as follows: ``` chef_group 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_group` tells Chef Infra Client to use the `Chef::Provider::ChefGroup` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_group** resource has the following actions: `:create` Default. `:delete` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_group** resource has the following properties: `chef_server` The URL for the Chef server. `clients` &mldr; `complete` Use to specify if this resource defines a chef-client completely. When `true`, any property not specified by this resource will be reset to default property values. `groups` &mldr; `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `raw_json` The group as JSON data. For example: ``` { :groupname => "chef" } ``` `remove_clients` &mldr; `remove_groups` &mldr; `remove_users` &mldr; `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `users` &mldr; ### Examples --- This resource does not have any examples. chef_handler resource ---------------------- [chef_handler resource page](resources/chef_handler/index) --- Use the **chef_handler** resource to enable handlers during a Chef Infra Client run. The resource allows arguments to be passed to Chef Infra Client, which then applies the conditions defined by the custom handler to the node attribute data collected during a Chef Infra Client run, and then processes the handler based on that data. The **chef_handler** resource is typically defined early in a node’s run-list (often being the first item). This ensures that all of the handlers will be available for the entire Chef Infra Client run. **New in Chef Infra Client 14.0.** ### Handler Types There are three types of handlers: | Handler | Description | | --- | --- | | exception | An exception handler is used to identify situations that have caused a Chef Infra Client run to fail. An exception handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the **chef_handler** resource to a node's run-list. An exception handler runs when the `failed?` property for the `run_status` object returns `true`. | | report | A report handler is used when a Chef Infra Client run succeeds and reports back on certain details about that Chef Infra Client run. A report handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the **chef_handler** resource to a node's run-list. A report handler runs when the `success?` property for the `run_status` object returns `true`. | | start | A start handler is used to run events at the beginning of a Chef Infra Client run. A start handler can be loaded at the start of a Chef Infra Client run by adding the start handler to the `start_handlers` setting in the client.rb file or by installing the gem that contains the start handler by using the **chef_gem** resource in a recipe in the **chef-client** cookbook. (A start handler may not be loaded using the `chef_handler` resource.) | #### Exception / Report Exception and report handlers are used to trigger certain behaviors in response to specific situations, typically identified during a Chef Infra Client run. * An exception handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run fails. * A report handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run is successful. Both types of handlers can be used to gather data about a Chef Infra Client run and can provide rich levels of data about all types of usage, which can be used later for trending and analysis across the entire organization. Exception and report handlers are made available to a Chef Infra Client run in one of the following ways: * By adding the **chef_handler** resource to a recipe, and then adding that recipe to the run-list for a node. (The **chef_handler** resource is available from the **chef_handler** cookbook.) * By adding the handler to one of the following settings in the node’s client.rb file: `exception_handlers` and/or `report_handlers` The **chef_handler** resource allows exception and report handlers to be enabled from within recipes, which can then added to the run-list for any node on which the exception or report handler should run. The **chef_handler** resource is available from the **chef_handler** cookbook. To use the **chef_handler** resource in a recipe, add code similar to the following: ``` chef_handler 'name_of_handler' do source '/path/to/handler/handler_name' action :enable end ``` For example, a handler for Growl needs to be enabled at the beginning of a Chef Infra Client run: ``` chef_gem 'chef-handler-growl' ``` and then is activated in a recipe by using the **chef_handler** resource: ``` chef_handler 'Chef::Handler::Growl' do source 'chef/handler/growl' action :enable end ``` #### Start A start handler is not loaded into a Chef Infra Client run from a recipe, but is instead listed in the client.rb file using the `start_handlers` attribute. The start handler must be installed on the node and be available to Chef Infra Client prior to the start of a Chef Infra Client run. Use the **chef-client** cookbook to install the start handler. Start handlers are made available to a Chef Infra Client run in one of the following ways: * By adding a start handler to the **chef-client** cookbook, which installs the handler on the node so that it is available to Chef Infra Client at the start of a Chef Infra Client run * By adding the handler to one of the following settings in the node’s client.rb file: `start_handlers` The **chef-client** cookbook can be configured to automatically install and configure gems that are required by a start handler. For example: ``` node.override['chef_client']['load_gems']['chef-reporting'] = { require_name: 'chef_reporting', action: :install, } node.override['chef_client']['config']['start_handlers'] = [ { class: 'Chef::Reporting::StartHandler', arguments: [], }, ] include_recipe 'chef-client::config' ``` ### Syntax --- A **chef_handler** resource block enables handlers during a chef-client run. Two handlers—`JsonFile` and `ErrorReport`—are built into Chef: ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments :path => '/var/chef/reports' action :enable end ``` and: ``` chef_handler 'Chef::Handler::ErrorReport' do source 'chef/handler/error_report' action :enable end ``` show how to enable those handlers in a recipe. The full syntax for all of the properties that are available to the **chef_handler** resource is: ``` chef_handler 'name' do arguments Array, Hash # default value: [] class_name String # default value: 'name' unless specified source String type Hash # default value: {"report"=>true, "exception"=>true} action Symbol # defaults to :enable if not specified end ``` where: * `chef_handler` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `arguments`, `class_name`, `source`, and `type` are the properties available to this resource. ### Actions --- The **chef_handler** resource has the following actions: `:disable` Disables the handler for the current Chef Infra Client run on the current node. `:enable` Enables the handler for the current Chef Infra Client run on the current node. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_handler** resource has the following properties: `arguments` **Ruby Type:** Array, Hash | **Default Value:** `[]` An array of arguments that are passed to the initializer for the handler class. For example: ``` arguments :key1 => 'val1' ``` or: ``` arguments [:key1 => 'val1', :key2 => 'val2'] ``` `class_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the handler class. This can be module name-spaced. `source` **Ruby Type:** String The full path to the handler file. Can also be a gem path if the handler ships as part of a Ruby gem. `type` **Ruby Type:** Hash | **Default Value:** `{"report"=>true, "exception"=>true}` The type of handler to register as, i.e. :report, :exception or both. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_handler** resource in recipes: **Enable the ‘MyHandler’ handler** The following example shows how to enable a fictional ‘MyHandler’ handler which is located on disk at `/etc/chef/my_handler.rb`. The handler will be configured to run with Chef Infra Client and will be passed values to the handler’s initializer method: ``` chef_handler 'MyHandler' do source '/etc/chef/my_handler.rb' # the file should already be at this path arguments path: '/var/chef/reports' action :enable end ``` **Enable handlers during the compile phase** ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' action :enable compile_time true end ``` **Handle only exceptions** ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' type exception: true action :enable end ``` **Cookbook Versions (a custom handler)** [@juliandunn](https://github.com/juliandunn) created a custom report handler that logs all of the cookbooks and cookbook versions that were used during a Chef Infra Client run, and then reports after the run is complete. cookbook_versions.rb: The following custom handler defines how cookbooks and cookbook versions that are used during a Chef Infra Client run will be compiled into a report using the `Chef::Log` class in Chef Infra Client: ``` require 'chef/log' module Chef class CookbookVersionsHandler < Chef::Handler def report cookbooks = run_context.cookbook_collection Chef::Log.info('Cookbooks and versions run: #{cookbooks.map {|x| x.name.to_s + ' ' + x.version }}') end end end ``` default.rb: The following recipe is added to the run-list for every node on which a list of cookbooks and versions will be generated as report output after every Chef Infra Client run. ``` cookbook_file '/etc/chef/cookbook_versions.rb' do source 'cookbook_versions.rb' action :create end chef_handler 'Chef::CookbookVersionsHandler' do source '/etc/chef/cookbook_versions.rb' type report: true action :enable end ``` This recipe will generate report output similar to the following: ``` [2013-11-26T03:11:06+00:00] INFO: Chef Infra Client Run complete in 0.300029878 seconds [2013-11-26T03:11:06+00:00] INFO: Running report handlers [2013-11-26T03:11:06+00:00] INFO: Cookbooks and versions run: ["cookbook_versions_handler 1.0.0"] [2013-11-26T03:11:06+00:00] INFO: Report handlers complete ``` **JsonFile Handler** The JsonFile handler is available from the `chef_handler` cookbook and can be used with exceptions and reports. It serializes run status data to a JSON file. This handler may be enabled in one of the following ways. By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how Chef Infra Client is being run: ``` require 'chef/handler/json_file' report_handlers << Chef::Handler::JsonFile.new(path: '/var/chef/reports') exception_handlers << Chef::Handler::JsonFile.new(path: '/var/chef/reports') ``` By using the `chef_handler` resource in a recipe, similar to the following: ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' action :enable end ``` After it has run, the run status data can be loaded and inspected via Interactive Ruby (IRb): ``` irb(main):002:0> require 'json' => true irb(main):003:0> require 'chef' => true irb(main):004:0> r = JSON.parse(IO.read('/var/chef/reports/chef-run-report-20110322060731.json')) => ... output truncated irb(main):005:0> r.keys => ['end_time', 'node', 'updated_resources', 'exception', 'all_resources', 'success', 'elapsed_time', 'start_time', 'backtrace'] irb(main):006:0> r['elapsed_time'] => 0.00246 ``` Register the JsonFile handler ``` chef_handler 'Chef::Handler::JsonFile' do source 'chef/handler/json_file' arguments path: '/var/chef/reports' action :enable end ``` **ErrorReport Handler** The ErrorReport handler is built into Chef Infra Client and can be used for both exceptions and reports. It serializes error report data to a JSON file. This handler may be enabled in one of the following ways. By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how Chef Infra Client is being run: ``` require 'chef/handler/error_report' report_handlers << Chef::Handler::ErrorReport.new exception_handlers << Chef::Handler::ErrorReport.new ``` By using the `chef_handler` resource in a recipe, similar to the following: ``` chef_handler 'Chef::Handler::ErrorReport' do source 'chef/handler/error_report' action :enable end ``` chef_node resource ------------------- [chef_node resource page](resources/chef_node/index) --- A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra. Use the **chef_node** resource to manage nodes. ### Syntax --- The syntax for using the **chef_node** resource in a recipe is as follows: ``` chef_node 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_node` tells Chef Infra Client to use the `Chef::Provider::ChefNode` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_node** resource has the following actions: `:create` Default. Use to create a node. `:delete` Use to delete a node. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_node** resource has the following properties: `automatic_attributes` An `automatic` attribute contains data that is identified by Ohai at the beginning of every Chef Infra Client run. An `automatic` attribute cannot be modified and always has the highest attribute precedence. Default value: `{}`. `chef_environment` The Chef Infra Server environment in which this node should exist (or does exist). `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a node completely. When `true`, any property not specified by this resource will be reset to default property values. `default_attributes` A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. Default value: `{}`. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The unique identifier of the node. `normal_attributes` A `normal` attribute is a setting that persists in the node object. A `normal` attribute has a higher attribute precedence than a `default` attribute. Default value: `{}`. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `override_attributes` An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. Default value: `{}`. `raw_json` The node as JSON data. For example: ``` { "overrides": {}, "name": "latte", "chef_type": "node", "json_class": "Chef::Node", "attributes": { "hardware_type": "laptop" }, "run_list": [ "recipe[apache2]" ], "defaults": {} } ``` `run_list` A comma-separated list of roles and/or recipes to be applied. Default value: `[]`. For example: `["recipe[default]","recipe[apache2]"]` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_organization resource --------------------------- [chef_organization resource page](resources/chef_organization/index) --- Use the **chef_organization** resource to interact with organization objects that exist on the Chef Infra Server. ### Syntax --- The syntax for using the **chef_organization** resource in a recipe is as follows: ``` chef_organization 'name' do attribute 'value' # see attributes section below ... action :action # see actions section below end ``` where: * `chef_organization` tells Chef Infra Client to use the `Chef::Provider::ChefOrganization` provider during a Chef Infra Client run * `name` is the name of the resource block * `attribute` is zero (or more) of the attributes that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_organization** resource has the following actions: `:create` Default. `:delete` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_organization** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines an organization completely. When `true`, any property not specified by this resource will be reset to default property values. `full_name` The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: `Chef Software, Inc.`. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `invites` Use to specify a list of users to be invited to the organization. An invitation is sent to any user in this list who is not already a member of the organization. `members` Use to specify a list of users who MUST be members of the organization. These users will be added directly to the organization. The user who initiates this operation MUST also have permission to add users to the specified organization. `members_specified` Use to discover if a user is a member of an organization. Will return `true` if the user is a member. `name` The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: `chef`. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `raw_json` The organization as JSON data. For example: ``` { "name": "chef", "full_name": "<NAME>, Inc", "guid": "f980d1asdfda0331235s00ff36862 ... } ``` `remove_members` Use to remove the specified users from an organization. Invitations that have not been accepted will be cancelled. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_role resource ------------------- [chef_role resource page](resources/chef_role/index) --- A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role. Use the **chef_role** resource to manage roles. ### Syntax --- The syntax for using the **chef_role** resource in a recipe is as follows: ``` chef_role 'name' do attribute 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_role` tells Chef Infra Client to use the `Chef::Provider::ChefRole` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the role * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_role** resource has the following actions: `:create` Default. Use to create a role. `:delete` Use to delete a role. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_role** resource has the following properties: `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a role completely. When `true`, any property not specified by this resource will be reset to default property values. `default_attributes` A `default` attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use `default` attributes as often as possible in cookbooks. Default value: `{}`. `description` The description of the role. This value populates the description field for the role on the Chef Infra Server. `env_run_lists` The environment-specific run-list for a role. Default value: `[]`. For example: `["env_run_lists[webserver]"]` `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the role. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `override_attributes` An `override` attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than `default`, `force_default`, and `normal` attributes. An `override` attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses `override` attributes only when required. Default value: `{}`. `raw_json` The role as JSON data. For example: ``` { "name": "webserver", "chef_type": "role", "json_class": "Chef::Role", "default_attributes": {}, "description": "A webserver", "run_list": [ "recipe[apache2]" ], "override_attributes": {} } ``` `run_list` A comma-separated list of roles and/or recipes to be applied. Default value: `[]`. For example: `["recipe[default]","recipe[apache2]"]` `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_sleep resource -------------------- [chef_sleep resource page](resources/chef_sleep/index) --- Use the **chef_sleep** resource to pause (sleep) for a number of seconds during a Chef Infra Client run. Only use this resource when a command or service exits successfully but is not ready for the next step in a recipe. **New in Chef Infra Client 15.5.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_sleep** resource is: ``` chef_sleep 'name' do seconds String, Integer # default value: 'name' unless specified action Symbol # defaults to :sleep if not specified end ``` where: * `chef_sleep` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `seconds` is the property available to this resource. ### Actions --- The **chef_sleep** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:sleep` Pause the Chef Infra Client run for a specified number of seconds. (default) ### Properties --- The **chef_sleep** resource has the following properties: `seconds` **Ruby Type:** String, Integer | **Default Value:** `The resource block's name` The number of seconds to sleep. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_sleep** resource in recipes: **Sleep for 10 seconds**: ``` chef_sleep '10' ``` **Sleep for 10 seconds with a descriptive resource name for logging**: ``` chef_sleep 'wait for the service to start' do seconds 10 end ``` **Use a notification from another resource to sleep only when necessary**: ``` service 'Service that is slow to start and reports as started' do service_name 'my_database' action :start notifies :sleep, 'chef_sleep[wait for service start]' end chef_sleep 'wait for service start' do seconds 30 action :nothing end ``` chef_user resource ------------------- [chef_user resource page](resources/chef_user/index) --- Use the **chef_user** resource to manage users. ### Syntax --- The syntax for using the **chef_user** resource in a recipe is as follows: ``` chef_user 'value' # see properties section below ... action :action # see actions section below end ``` where: * `chef_user` tells Chef Infra Client to use the `Chef::Provider::ChefUser` provider during a Chef Infra Client run * `name` is the name of the resource block; when the `name` property is not specified as part of a recipe, `name` is also the name of the user * `attribute` is zero (or more) of the properties that are available for this resource * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state ### Actions --- The **chef_user** resource has the following actions: `:create` Default. Use to create a user. `:delete` Use to delete a user. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_user** resource has the following properties: `admin` Create a client as an admin client. This is required for any user to access Chef as an administrator. `chef_server` The URL for the Chef Infra Server. `complete` Use to specify if this resource defines a user completely. When `true`, any property not specified by this resource will be reset to default property values. `email` The email address for the user. `external_authentication_uid` &mldr; `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `name` The name of the user. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `output_key_format` Use to specify the format of a public key. Possible values: `pem`, `der`, or `openssh`. Default value: `openssh`. `output_key_path` Use to specify the path to the location in which a public key will be written. `raw_json` The user as JSON data. For example: ``` { "name": "<NAME>" } ``` `recovery_authentication_enabled` &mldr; `source_key` Use to copy a public or private key, but apply a different `format` and `password`. Use in conjunction with `source_key_pass_phrase` and `source_key_path`. `source_key_pass_phrase` The pass phrase for the public key. Use in conjunction with `source_key` and `source_key_path`. `source_key_path` The path to the public key. Use in conjunction with `source_key` and `source_key_pass_phrase`. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` ### Examples --- This resource does not have any examples. chef_vault_secret resource ---------------------------- [chef_vault_secret resource page](resources/chef_vault_secret/index) --- Use the **chef_vault_secret** resource to store secrets in Chef Vault items. Where possible and relevant, this resource attempts to map behavior and functionality to the knife vault sub-commands. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **chef_vault_secret** resource is: ``` chef_vault_secret 'name' do admins String, Array clients String, Array data_bag String environment String id String # default value: 'name' unless specified raw_data Hash, Mash (Hash-like) # default value: {} search String # default value: "*:*" action Symbol # defaults to :create if not specified end ``` where: * `chef_vault_secret` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `admins`, `clients`, `data_bag`, `environment`, `id`, `raw_data`, and `search` are the properties available to this resource. ### Actions --- The **chef_vault_secret** resource has the following actions: `:create` Creates the item, or updates it if it already exists. (default) `:create_if_missing` Calls the create action unless it exists. `:delete` Deletes the item and the item’s keys (‘id’_keys). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chef_vault_secret** resource has the following properties: `admins` **Ruby Type:** String, Array | `REQUIRED` A list of admin users who should have access to the item. Corresponds to the ‘admin’ option when using the chef-vault knife plugin. Can be specified as a comma separated string or an array. `clients` **Ruby Type:** String, Array A search query for the nodes' API clients that should have access to the item. `data_bag` **Ruby Type:** String | `REQUIRED` The data bag that contains the item. `environment` **Ruby Type:** String The Chef environment of the data if storing per environment values. `id` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the data bag item if it differs from the name of the resource block `raw_data` **Ruby Type:** Hash, Mash (Hash-like) | **Default Value:** `{}` The raw data, as a Ruby Hash, that will be stored in the item. `search` **Ruby Type:** String | **Default Value:** `*:*` Search query that would match the same used for the clients, gets stored as a field in the item. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chef_vault_secret** resource in recipes: **To create a ‘foo’ item in an existing ‘bar’ data bag**: ``` chef_vault_secret 'foo' do data_bag 'bar' raw_data({ 'auth' => 'baz' }) admins 'jtimberman' search '*:*' end ``` **To allow multiple admins access to an item**: ``` chef_vault_secret 'root-password' do admins 'jtimberman,paulmooring' data_bag 'secrets' raw_data({ 'auth' => 'DoNotUseThisPasswordForRoot' }) search '*:*' end ``` chocolatey_config resource --------------------------- [chocolatey_config resource page](resources/chocolatey_config/index) --- Use the **chocolatey_config** resource to add or remove Chocolatey configuration keys. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [Chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. **New in Chef Infra Client 14.3.** ### Syntax --- The full syntax for all of the properties that are available to the **chocolatey_config** resource is: ``` chocolatey_config 'name' do config_key String # default value: 'name' unless specified value String action Symbol # defaults to :set if not specified end ``` where: * `chocolatey_config` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `config_key` and `value` are the properties available to this resource. ### Actions --- The **chocolatey_config** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Sets a Chocolatey config value. (default) `:unset` Unsets a Chocolatey config value. ### Properties --- The **chocolatey_config** resource has the following properties: `config_key` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the config key name if it differs from the resource block’s name. `value` **Ruby Type:** String The value to set. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chocolatey_config** resource in recipes: **Set the Chocolatey cacheLocation config**: ``` chocolatey_config 'Set cacheLocation config' do config_key 'cacheLocation' value 'C:\temp\choco' end ``` **Unset a Chocolatey config**: ``` chocolatey_config 'BogusConfig' do action :unset end ``` chocolatey_feature resource ---------------------------- [chocolatey_feature resource page](resources/chocolatey_feature/index) --- Use the **chocolatey_feature** resource to enable and disable Chocolatey features. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [Chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. **New in Chef Infra Client 15.1.** ### Syntax --- The full syntax for all of the properties that are available to the **chocolatey_feature** resource is: ``` chocolatey_feature 'name' do feature_name String # default value: 'name' unless specified action Symbol # defaults to :enable if not specified end ``` where: * `chocolatey_feature` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `feature_name` is the property available to this resource. ### Actions --- The **chocolatey_feature** resource has the following actions: `:disable` Disables a named Chocolatey feature. `:enable` Enables a named Chocolatey feature. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **chocolatey_feature** resource has the following properties: `feature_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the Chocolatey feature to enable or disable. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chocolatey_feature** resource in recipes: **Enable the checksumFiles Chocolatey feature** ``` chocolatey_feature 'checksumFiles' do action :enable end ``` **Disable the checksumFiles Chocolatey feature** ``` chocolatey_feature 'checksumFiles' do action :disable end ``` chocolatey_package resource ---------------------------- [chocolatey_package resource page](resources/chocolatey_package/index) --- Use the **chocolatey_package** resource to manage packages using the Chocolatey package manager on the Microsoft Windows platform. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. Warning The **chocolatey_package** resource must be specified as `chocolatey_package` and cannot be shortened to `package` in a recipe. **New in Chef Infra Client 12.7.** ### Syntax --- The full syntax for all of the properties that are available to the **chocolatey_package** resource is: ``` chocolatey_package 'name' do list_options String options String, Array package_name String, Array password String returns Integer, Array # default value: [0, 2] source String timeout String, Integer user String version String, Array action Symbol # defaults to :install if not specified end ``` where: * `chocolatey_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `list_options`, `options`, `package_name`, `password`, `returns`, `source`, `timeout`, `user`, and `version` are the properties available to this resource. ### Actions --- The **chocolatey_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and ensure that a package is the latest version. ### Properties --- The **chocolatey_package** resource has the following properties: `list_options` **Ruby Type:** String One (or more) additional list options that are passed to the command. New in Chef Infra Client 15.3 `options` **Ruby Type:** String, Array One (or more) additional options that are passed to the command. `package_name` **Ruby Type:** String, Array The name of the package. Default value: the name of the resource block. `password` **Ruby Type:** String The password to authenticate to the source. New in Chef Infra Client 15.3 `returns` **Ruby Type:** Integer, Array | **Default Value:** `[0, 2]` The exit code(s) returned by the `choco` command that indicate a successful action. See [Chocolatey Exit Codes](https://docs.chocolatey.org/en-us/choco/commands/info#exit-codes) for a complete list of exit codes used by Chocolatey. New in Chef Client 12.18 `source` **Ruby Type:** String The optional path to a package on the local file system or a reachable UNC path. Ensure that the path specified is to the **folder** containing the chocolatey package(s), not to the package itself. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `user` **Ruby Type:** String The username to authenticate feeds. New in Chef Infra Client 15.3 `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chocolatey_package** resource in recipes: **Install a Chocolatey package**: ``` chocolatey_package 'name of package' do action :install end ``` **Install a package with options with Chocolatey’s `--checksum` option**: ``` chocolatey_package 'name of package' do options '--checksum 1234567890' action :install end ``` chocolatey_source resource --------------------------- [chocolatey_source resource page](resources/chocolatey_source/index) --- Use the **chocolatey_source** resource to add, remove, enable, or disable Chocolatey sources. Note The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the [Chocolatey cookbook](https://supermarket.chef.io/cookbooks/chocolatey/) to your node’s run list. **New in Chef Infra Client 14.3.** ### Syntax --- The full syntax for all of the properties that are available to the **chocolatey_source** resource is: ``` chocolatey_source 'name' do admin_only true, false # default value: false allow_self_service true, false # default value: false bypass_proxy true, false # default value: false cert String cert_password String password String priority Integer # default value: 0 source String source_name String # default value: 'name' unless specified username String action Symbol # defaults to :add if not specified end ``` where: * `chocolatey_source` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `admin_only`, `allow_self_service`, `bypass_proxy`, `cert`, `cert_password`, `password`, `priority`, `source`, `source_name`, and `username` are the properties available to this resource. ### Actions --- The **chocolatey_source** resource has the following actions: `:add` Adds a Chocolatey source (default) `:disable` Disables a Chocolatey source. **New in Chef Infra Client 15.1.** `:enable` Enables a Chocolatey source. **New in Chef Infra Client 15.1.** `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Removes a Chocolatey source. ### Properties --- The **chocolatey_source** resource has the following properties: `admin_only` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to set the source to be accessible to only admins. New in Chef Infra Client 15.1 `allow_self_service` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to set the source to be used for self service. New in Chef Infra Client 15.1 `bypass_proxy` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to bypass the system’s proxy settings to access the source. `cert` **Ruby Type:** String The certificate to use when authenticating against the source New in Chef Infra Client 17.7 `cert_password` **Ruby Type:** String The password for the certificate to use when authenticating against the source New in Chef Infra Client 17.7 `password` **Ruby Type:** String The password to use when authenticating against the source New in Chef Infra Client 17.7 `priority` **Ruby Type:** Integer | **Default Value:** `0` The priority level of the source. `source` **Ruby Type:** String The source URL. `source_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the source name if it differs from the resource block’s name. `username` **Ruby Type:** String The username to use when authenticating against the source New in Chef Infra Client 17.7 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **chocolatey_source** resource in recipes: **Add a Chocolatey source** ``` chocolatey_source 'MySource' do source 'http://example.com/something' action :add end ``` **Remove a Chocolatey source** ``` chocolatey_source 'MySource' do action :remove end ``` cookbook_file resource ----------------------- [cookbook_file resource page](resources/cookbook_file/index) --- Use the **cookbook_file** resource to transfer files from a sub-directory of `COOKBOOK_NAME/files/` to a specified path located on a host that is running Chef Infra Client. The file is selected according to file specificity, which allows different source files to be used based on the hostname, host platform (operating system, distro, or as appropriate), or platform version. Files that are located in the `COOKBOOK_NAME/files/default` sub-directory may be used on any platform. During a Chef Infra Client run, the checksum for each local file is calculated and then compared against the checksum for the same file as it currently exists in the cookbook on the Chef Infra Server. A file is not transferred when the checksums match. Only files that require an update are transferred from the Chef Infra Server to a node. ### Syntax --- A **cookbook_file** resource block manages files by using files that exist within a cookbook’s `/files` directory. For example, to write the home page for an Apache website: ``` cookbook_file '/var/www/customers/public_html/index.php' do source 'index.php' owner 'web_admin' group 'web_admin' mode '0755' action :create end ``` where: * `'/var/www/customers/public_html/index.php'` is path to the file to be created * `'index.php'` is a file in the `/files` directory in a cookbook that is used to create that file (the contents of the file in the cookbook will become the contents of the file on the node) * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **cookbook_file** resource is: ``` cookbook_file 'name' do atomic_update true, false backup Integer, false # default value: 5 cookbook String force_unlink true, false # default value: false group String, Integer inherits true, false manage_symlink_source true, false mode String, Integer owner String, Integer path String # default value: 'name' unless specified rights Hash source String, Array verify String, Block action Symbol # defaults to :create if not specified end ``` where: * `cookbook_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `atomic_update`, `backup`, `cookbook`, `force_unlink`, `group`, `inherits`, `manage_symlink_source`, `mode`, `owner`, `path`, `rights`, `source`, and `verify` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **cookbook_file** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the **file** resource.) ### Properties --- The **cookbook_file** resource has the following properties: `atomic_update` **Ruby Type:** true, false | **Default Value:** `False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.` Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the `client.rb` file. `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `cookbook` **Ruby Type:** String | **Default Value:** `The current cookbook name` The cookbook in which a file is located (if it is not located in the current cookbook). `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `true`, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `false`, Chef will follow the symlink and will manage the permissions and content of the symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String The path to the destination at which a file is to be created. For example: `file.txt`. Microsoft Windows: A path that begins with a forward slash (`/`) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (`/`) is not recommended. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String, Array | **Default Value:** `The resource block's name` The name of the file in `COOKBOOK_NAME/files/default` or the path to a file located in `COOKBOOK_NAME/files`. The path must include the file name and its extension. This can be used to distribute specific files depending upon the platform used - see [File Specificity](#cookbook-file-specificity) for more information. `verify` **Ruby Type:** String, Block A block or a string that returns `true` or `false`. A string, when `true` is executed as a system command. A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block is `true`, Chef Infra Client will continue to update the file as appropriate. For example, this should return `true`: ``` cookbook_file '/tmp/baz' do verify { 1 == 1 } end ``` This should return `true`: ``` cookbook_file '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` This should return `true`: ``` cookbook_file '/tmp/bar' do verify { 1 == 1} end ``` And this should return `true`: ``` cookbook_file '/tmp/foo' do verify do |path| true end end ``` Whereas, this should return `false`: ``` cookbook_file '/tmp/turtle' do verify '/usr/bin/false' end ``` If a string or a block return `false`, the Chef Infra Client run will stop and an error is returned. #### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(<NAME>) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### File Specificity A cookbook is frequently designed to work across many platforms and is often required to distribute a specific file to a specific platform. A cookbook can be designed to support the distribution of files across platforms, while ensuring that the correct file ends up on each system. The pattern for file specificity depends on two things: the lookup path and the source attribute. The first pattern that matches is used: 1. /host-$fqdn/$source 2. /$platform-$platform_version/$source 3. /$platform/$source 4. /default/$source 5. /$source Use an array with the `source` attribute to define an explicit lookup path. For example: ``` file '/conf.py' do source ['#{node.chef_environment}.py', 'conf.py'] end ``` The following example emulates the entire file specificity pattern by defining it as an explicit path: ``` file '/conf.py' do source %W( host-#{node['fqdn']}/conf.py #{node['platform']}-#{node['platform_version']}/conf.py #{node['platform']}/conf.py default/conf.py ) end ``` A cookbook may have a `/files` directory structure like this: ``` files/ host-foo.example.com ubuntu-20.04 ubuntu-20 ubuntu redhat-8.2 redhat-7.8 ... default ``` and a resource that looks something like the following: ``` cookbook_file '/usr/local/bin/apache2_module_conf_generate.pl' do source 'apache2_module_conf_generate.pl' mode '0755' owner 'root' group 'root' end ``` This resource is matched in the same order as the `/files` directory structure. For a node that is running Ubuntu 20.04, the second item would be the matching item and the location to which the file identified in the **cookbook_file** resource would be distributed: ``` host-foo.example.com/apache2_module_conf_generate.pl ubuntu-20.04/apache2_module_conf_generate.pl ubuntu-20/apache2_module_conf_generate.pl ubuntu/apache2_module_conf_generate.pl default/apache2_module_conf_generate.pl ``` If the `apache2_module_conf_generate.pl` file was located in the cookbook directory under `files/host-foo.example.com/`, the specified file(s) would only be copied to the machine with the domain name foo.example.com. **Host Notation** The naming of folders within cookbook directories must literally match the host notation used for file specificity matching. For example, if a host is named `foo.example.com`, the folder must be named `host-foo.example.com`. ### Examples --- The following examples demonstrate various approaches for using the **cookbook_file** resource in recipes: Transfer a file ``` cookbook_file 'file.txt' do mode '0755' end ``` Handle cookbook_file and package resources in the same recipe When a **cookbook_file** resource and a **package** resource are both called from within the same recipe, use the `flush_cache` attribute to dump the in-memory Yum cache, and then use the repository immediately to ensure that the correct package is installed: ``` cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' end package 'only-in-custom-repo' do action :install flush_cache [ :before ] end ``` Install repositories from a file, trigger a command, and force the internal cache to reload The following example shows how to install new Yum repositories from a file, where the installation of the repository triggers a creation of the Yum cache that forces the internal cache for Chef Infra Client to reload: ``` execute 'create-yum-cache' do command 'yum -q makecache' action :nothing end ruby_block 'reload-internal-yum-cache' do block do Chef::Provider::Package::Yum::YumCache.instance.reload end action :nothing end cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' notifies :run, 'execute[create-yum-cache]', :immediately notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately end ``` Use a case statement The following example shows how a case statement can be used to handle a situation where an application needs to be installed on multiple platforms, but where the install directories are different paths, depending on the platform: ``` cookbook_file 'application.pm' do path case node['platform'] when 'centos','redhat' '/usr/lib/version/1.2.3/dir/application.pm' when 'arch' '/usr/share/version/core_version/dir/application.pm' else '/etc/version/dir/application.pm' end source "application-#{node['languages']['perl']['version']}.pm" owner 'root' group 'root' mode '0755' end ``` Manage dotfiles The following example shows using the **directory** and **cookbook_file** resources to manage dotfiles. The dotfiles are defined by a JSON data structure similar to: ``` "files": { ".zshrc": { "mode": '0755', "source": "dot-zshrc" }, ".bashrc": { "mode": '0755', "source": "dot-bashrc" }, ".bash_profile": { "mode": '0755', "source": "dot-bash_profile" }, } ``` and then the following resources manage the dotfiles: ``` if u.has_key?('files') u['files'].each do |filename, file_data| directory "#{home_dir}/#{File.dirname(filename)}" do recursive true mode '0755' end if file_data['subdir'] cookbook_file "#{home_dir}/#{filename}" do source "#{u['id']}/#{file_data['source']}" owner 'u['id']' group 'group_id' mode 'file_data['mode']' ignore_failure true backup 0 end end ``` cron resource ------------- [cron resource page](resources/cron/index) --- Use the **cron** resource to manage cron entries for time-based job scheduling. Properties for a schedule will default to * if not provided. The cron resource requires access to a crontab program, typically cron. Warning The cron resource should only be used to modify an entry in a crontab file. The `cron_d` resource directly manages `cron.d` files. This resource ships in Chef Infra Client 14.4 or later and can also be found in the [cron](https://github.com/chef-cookbooks/cron) cookbook) for previous Chef Infra Client releases. ### Syntax --- The full syntax for all of the properties that are available to the **cron** resource is: ``` cron 'name' do command String day Integer, String # default value: "*" environment Hash # default value: {} home String hour Integer, String # default value: "*" mailto String minute Integer, String # default value: "*" month Integer, String # default value: "*" path String shell String time Symbol time_out Hash # default value: {} user String # default value: "root" weekday Integer, String, Symbol # default value: "*" action Symbol # defaults to :create if not specified end ``` where: * `cron` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command`, `day`, `environment`, `home`, `hour`, `mailto`, `minute`, `month`, `path`, `shell`, `time`, `time_out`, `user`, and `weekday` are the properties available to this resource. ### Actions --- The **cron** resource has the following actions: `:create` Create an entry in a cron table file (crontab). If an entry already exists (but does not match), update that entry to match. (default) `:delete` Delete an entry from a cron table file (crontab). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **cron** resource has the following properties: `command` **Ruby Type:** String | `REQUIRED` The command to be run, or the path to a file that contains the command to be run. `day` **Ruby Type:** Integer, String | **Default Value:** `*` The day of month at which the cron entry should run (`1 - 31`). `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `home` **Ruby Type:** String Set the `HOME` environment variable. `hour` **Ruby Type:** Integer, String | **Default Value:** `*` The hour at which the cron entry is to run (`0 - 23`). `mailto` **Ruby Type:** String Set the `MAILTO` environment variable. `minute` **Ruby Type:** Integer, String | **Default Value:** `*` The minute at which the cron entry should run (`0 - 59`). `month` **Ruby Type:** Integer, String | **Default Value:** `*` The month in the year on which a cron entry is to run (`1 - 12`, `jan-dec`, or `*`). `path` **Ruby Type:** String Set the `PATH` environment variable. `shell` **Ruby Type:** String Set the `SHELL` environment variable. `time` **Ruby Type:** Symbol **Allowed Values:** `:annually, :daily, :hourly, :midnight, :monthly, :reboot, :weekly, :yearly` A time interval. `time_out` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of timeouts in the form of `({'OPTION' => 'VALUE'})`. Accepted valid options are: * `preserve-status` (BOOL, default: ‘false’), * `foreground` (BOOL, default: ‘false’), * `kill-after` (in seconds), * `signal` (a name like ‘HUP’ or a number) New in Chef Infra Client 15.7 `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that runs the command. If the user property is changed, the original user for the crontab program continues to run until that crontab program is deleted. This property is not applicable on the AIX platform. `weekday` **Ruby Type:** Integer, String, Symbol | **Default Value:** `*` The day of the week on which this entry is to run (`0-7`, `mon-sun`, `monday-sunday`, or `*`), where Sunday is both `0` and `7`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **cron** resource in recipes: **Run a program at a specified interval** ``` cron 'noop' do hour '5' minute '0' command '/bin/true' end ``` **Run an entry if a folder exists** ``` cron 'ganglia_tomcat_thread_max' do command "/usr/bin/gmetric -n 'tomcat threads max' -t uint32 -v '/usr/local/bin/tomcat-stat --thread-max'" only_if { ::File.exist?('/home/jboss') } end ``` **Run every Saturday, 8:00 AM** The following example shows a schedule that will run every hour at 8:00 each Saturday morning, and will then send an email to “<EMAIL>” after each run. ``` cron 'name_of_cron_entry' do minute '0' hour '8' weekday '6' mailto '<EMAIL>' action :create end ``` **Run once a week** ``` cron 'cookbooks_report' do minute '0' hour '0' weekday '1' user 'chefio' mailto '<EMAIL>' home '/srv/supermarket/shared/system' command %W{ cd /srv/supermarket/current && env RUBYLIB="/srv/supermarket/current/lib" RAILS_ASSET_ID=`git rev-parse HEAD` RAILS_ENV="#{rails_env}" bundle exec rake cookbooks_report }.join(' ') action :create end ``` **Run only in November** The following example shows a schedule that will run at 8:00 PM, every weekday (Monday through Friday), but only in November: ``` cron 'name_of_cron_entry' do minute '0' hour '20' day '*' month '11' weekday '1-5' action :create end ``` cron_access resource --------------------- [cron_access resource page](resources/cron_access/index) --- Use the **cron_access** resource to manage cron’s cron.allow and cron.deny files. Note This resource previously shipped in the `cron` cookbook as `cron_manage`, which it can still be used as for backwards compatibility with existing Chef Infra Client releases. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **cron_access** resource is: ``` cron_access 'name' do user String # default value: 'name' unless specified action Symbol # defaults to :allow if not specified end ``` where: * `cron_access` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `user` is the property available to this resource. ### Actions --- The **cron_access** resource has the following actions: `:allow` Add the user to the cron.allow file. (default) `:deny` Add the user to the cron.deny file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **cron_access** resource has the following properties: `user` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the user name if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **cron_access** resource in recipes: **Add the mike user to cron.allow** ``` cron_access 'mike' ``` **Add the mike user to cron.deny** ``` cron_access 'mike' do action :deny end ``` **Specify the username with the user property** ``` cron_access 'Deny the jenkins user access to cron for security purposes' do user 'jenkins' action :deny end ``` cron_d resource ---------------- [cron_d resource page](resources/cron_d/index) --- Use the **cron_d** resource to manage cron job files in the `/etc/cron.d` directory. Warning Chef Infra Client also ships with the **cron** resource for managing the monolithic `/etc/crontab` file on platforms that lack cron.d support. See the [cron resource](resources/cron/index) for information on using that resource. **New in Chef Infra Client 14.4.** ### Syntax --- A **cron_d** resource block manages cron.d files. For example, to get a weekly cookbook report from the Chef Supermarket: ``` cron_d 'cookbooks_report' do action :create minute '0' hour '0' weekday '1' user 'getchef' mailto '<EMAIL>' home '/srv/supermarket/shared/system' command %W{ cd /srv/supermarket/current && env RUBYLIB="/srv/supermarket/current/lib" RAILS_ASSET_ID=`git rev-parse HEAD` RAILS_ENV="#{rails_env}" bundle exec rake cookbooks_report }.join(' ') end ``` The full syntax for all of the properties that are available to the **cron_d** resource is: ``` cron_d 'name' do command String comment String cron_name String # default value: 'name' unless specified day Integer, String # default value: "*" environment Hash # default value: {} home String hour Integer, String # default value: "*" mailto String minute Integer, String # default value: "*" mode String, Integer # default value: "0600" month Integer, String # default value: "*" path String predefined_value String random_delay Integer shell String time_out Hash # default value: {} user String # default value: "root" weekday Integer, String, Symbol # default value: "*" action Symbol # defaults to :create if not specified end ``` where: * `cron_d` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command`, `comment`, `cron_name`, `day`, `environment`, `home`, `hour`, `mailto`, `minute`, `mode`, `month`, `path`, `predefined_value`, `random_delay`, `shell`, `time_out`, `user`, and `weekday` are the properties available to this resource. ### Actions --- The **cron_d** resource has the following actions: `:create` (default) `:create_if_missing` Add a cron definition file to `/etc/cron.d`, but do not update an existing file. `:delete` Remove a cron definition file from `/etc/cron.d` if it exists. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **cron_d** resource has the following properties: `command` **Ruby Type:** String | `REQUIRED` The command to be run, or the path to a file that contains the command to be run. `comment` **Ruby Type:** String A comment to place in the cron.d file. `cron_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the cron name if it differs from the resource block’s name. `day` **Ruby Type:** Integer, String | **Default Value:** `*` The day of month at which the cron entry should run (`1 - 31`). `environment` **Ruby Type:** Hash | **Default Value:** `{}` A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `home` **Ruby Type:** String Set the `HOME` environment variable. `hour` **Ruby Type:** Integer, String | **Default Value:** `*` The hour at which the cron entry is to run (`0 - 23`). `mailto` **Ruby Type:** String Set the `MAILTO` environment variable. `minute` **Ruby Type:** Integer, String | **Default Value:** `*` The minute at which the cron entry should run (`0 - 59`). `mode` **Ruby Type:** String, Integer | **Default Value:** `0600` The octal mode of the generated crontab file. `month` **Ruby Type:** Integer, String | **Default Value:** `*` The month in the year on which a cron entry is to run (`1 - 12`, `jan-dec`, or `*`). `path` **Ruby Type:** String Set the `PATH` environment variable. `predefined_value` **Ruby Type:** String **Allowed Values:** `"@annually", "@daily", "@hourly", "@midnight", "@monthly", "@reboot", "@weekly", "@yearly"` Schedule your cron job with one of the special predefined value instead of ** * pattern. `random_delay` **Ruby Type:** Integer Set the `RANDOM_DELAY` environment variable in the cron.d file. `shell` **Ruby Type:** String Set the `SHELL` environment variable. `time_out` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of timeouts in the form of `({'OPTION' => 'VALUE'})`. Accepted valid options are: * `preserve-status` (BOOL, default: ‘false’), * `foreground` (BOOL, default: ‘false’), * `kill-after` (in seconds), * `signal` (a name like ‘HUP’ or a number) New in Chef Infra Client 15.7 `user` **Ruby Type:** String | **Default Value:** `root` The name of the user that runs the command. `weekday` **Ruby Type:** Integer, String, Symbol | **Default Value:** `*` The day of the week on which this entry is to run (`0-7`, `mon-sun`, `monday-sunday`, or `*`), where Sunday is both `0` and `7`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **cron_d** resource in recipes: **Run a program on the fifth hour of the day** ``` cron_d 'noop' do hour '5' minute '0' command '/bin/true' end ``` **Run an entry if a folder exists** ``` cron_d 'ganglia_tomcat_thread_max' do command "/usr/bin/gmetric -n 'tomcat threads max' -t uint32 -v '/usr/local/bin/tomcat-stat --thread-max'" only_if { ::File.exist?('/home/jboss') } end ``` **Run an entry every Saturday, 8:00 AM** ``` cron_d 'name_of_cron_entry' do minute '0' hour '8' weekday '6' mailto '<EMAIL>' command '/bin/true' action :create end ``` **Run an entry at 8:00 PM, every weekday (Monday through Friday), but only in November** ``` cron_d 'name_of_cron_entry' do minute '0' hour '20' day '*' month '11' weekday '1-5' command '/bin/true' action :create end ``` **Remove a cron job by name**: ``` cron_d 'job_to_remove' do action :delete end ``` csh resource ------------ [csh resource page](resources/csh/index) --- Use the **csh** resource to execute scripts using the csh interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **csh** resource block executes scripts using csh: ``` csh 'hello world' do code <<-EOH echo "Hello world!" echo "Current directory: " $cwd EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **csh** resource is: ``` csh 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `csh` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **csh** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. ### Properties --- The **csh** resource has the following properties: `code` **Ruby Type:** String | `REQUIRED` A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. directory resource ------------------ [directory resource page](resources/directory/index) --- Use the **directory** resource to manage a directory, which is a hierarchy of folders that comprises all of the information stored on a computer. The root directory is the top-level, under which the rest of the directory is organized. The directory resource uses the name property to specify the path to a location in a directory. Typically, permission to access that location in the directory is required. ### Syntax --- A **directory** resource block declares a directory and the permissions needed on that directory. For example: ``` directory '/etc/apache2' do owner 'root' group 'root' mode '0755' action :create end ``` where: * `'/etc/apache2'` specifies the directory * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **directory** resource is: ``` directory 'name' do group String, Integer inherits true, false mode String, Integer owner String, Integer path String # defaults to 'name' if not specified recursive true, false rights Hash action Symbol # defaults to :create if not specified end ``` where: * `directory` is the resource. * `name` is the name of the resource block; when the `path` property is not specified, `name` is also the path to the directory, from the root * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `group`, `inherits`, `mode`, `owner`, `path`, `recursive`, and `rights` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **directory** resource has the following actions: `:create` Default. Create a directory. If a directory already exists (but does not match), update that directory to match. `:delete` Delete a directory. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **directory** resource has the following properties: `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the directory already exists, the existing mode on the directory is used. If `mode` is not specified, the directory does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'`, and then applies the umask for the system on which the directory is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the `name` of the resource block. See “Syntax” section above for more information. `recursive` **Ruby Type:** true, false | **Default Value:** `false` Create or delete parent directories recursively. For the owner, group, and mode properties, the value of this property applies only to the leaf directory. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. #### Recursive Directories The **remote_directory** resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the `recursive` attribute only applies `group`, `mode`, and `owner` attribute values to the remote directory itself and any inner directories the resource copies. A directory structure: ``` /foo /bar /baz ``` The following example shows a way create a file in the `/baz` directory: ``` remote_directory '/foo/bar/baz' do owner 'root' group 'root' mode '0755' action :create end ``` But with this example, the `group`, `mode`, and `owner` attribute values will only be applied to `/baz`. Which is fine, if that’s what you want. But most of the time, when the entire `/foo/bar/baz` directory structure is not there, you must be explicit about each directory. For example: ``` %w( /foo /foo/bar /foo/bar/baz ).each do |path| remote_directory path do owner 'root' group 'root' mode '0755' end end ``` This approach will create the correct hierarchy—`/foo`, then `/bar` in `/foo`, and then `/baz` in `/bar`—and also with the correct attribute values for `group`, `mode`, and `owner`. #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **directory** resource in recipes: Create a directory ``` directory '/tmp/something' do owner 'root' group 'root' mode '0755' action :create end ``` Create a directory in Microsoft Windows ``` directory "C:\\tmp\\something" do rights :full_control, "DOMAIN\\User" inherits false action :create end ``` or: ``` directory 'C:\tmp\something' do rights :full_control, 'DOMAIN\User' inherits false action :create end ``` Note The difference between the two previous examples is the single- versus double-quoted strings, where if the double quotes are used, the backslash character (`\`) must be escaped using the Ruby escape character (which is a backslash). Create a directory recursively ``` %w{dir1 dir2 dir3}.each do |dir| directory "/tmp/mydirs/#{dir}" do mode '0755' owner 'root' group 'root' action :create recursive true end end ``` Delete a directory ``` directory '/tmp/something' do recursive true action :delete end ``` Set directory permissions using a variable The following example shows how read/write/execute permissions can be set using a variable named `user_home`, and then for owners and groups on any matching node: ``` user_home = "/#{node[:matching_node][:user]}" directory user_home do owner 'node[:matching_node][:user]' group 'node[:matching_node][:group]' mode '0755' action :create end ``` where `matching_node` represents a type of node. For example, if the `user_home` variable specified `{node[:nginx]...}`, a recipe might look similar to: ``` user_home = "/#{node[:nginx][:user]}" directory user_home do owner 'node[:nginx][:user]' group 'node[:nginx][:group]' mode '0755' action :create end ``` Set directory permissions for a specific type of node The following example shows how permissions can be set for the `/certificates` directory on any node that is running Nginx. In this example, permissions are being set for the `owner` and `group` properties as `root`, and then read/write permissions are granted to the root. ``` directory "#{node[:nginx][:dir]}/shared/certificates" do owner 'root' group 'root' mode '0755' recursive true end ``` Reload the configuration The following example shows how to reload the configuration of a chef-client using the **remote_file** resource to: * using an if statement to check whether the plugins on a node are the latest versions * identify the location from which Ohai plugins are stored * using the `notifies` property and a **ruby_block** resource to trigger an update (if required) and to then reload the client.rb file. ``` directory 'node[:ohai][:plugin_path]' do owner 'chef' recursive true end ruby_block 'reload_config' do block do Chef::Config.from_file('/etc/chef/client.rb') end action :nothing end if node[:ohai].key?(:plugins) node[:ohai][:plugins].each do |plugin| remote_file node[:ohai][:plugin_path] +"/#{plugin}" do source plugin owner 'chef' notifies :run, 'ruby_block[reload_config]', :immediately end end end ``` Manage dotfiles The following example shows using the **directory** and **cookbook_file** resources to manage dotfiles. The dotfiles are defined by a JSON data structure similar to: ``` "files": { ".zshrc": { "mode": '0755', "source": "dot-zshrc" }, ".bashrc": { "mode": '0755', "source": "dot-bashrc" }, ".bash_profile": { "mode": '0755', "source": "dot-bash_profile" }, } ``` and then the following resources manage the dotfiles: ``` if u.has_key?('files') u['files'].each do |filename, file_data| directory "#{home_dir}/#{File.dirname(filename)}" do recursive true mode '0755' end if file_data['subdir'] cookbook_file "#{home_dir}/#{filename}" do source "#{u['id']}/#{file_data['source']}" owner 'u['id']' group 'group_id' mode 'file_data['mode']' ignore_failure true backup 0 end end ``` dmg_package resource --------------------- [dmg_package resource page](resources/dmg_package/index) --- Use the **dmg_package** resource to install a package from a .dmg file. The resource will retrieve the dmg file from a remote URL, mount it using macOS' `hdidutil`, copy the application (.app directory) to the specified destination (`/Applications`), and detach the image using `hdiutil`. The dmg file will be stored in the `Chef::Config[:file_cache_path]`. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **dmg_package** resource is: ``` dmg_package 'name' do accept_eula true, false # default value: false allow_untrusted true, false # default value: false app String # default value: 'name' unless specified checksum String destination String # default value: "/Applications" dmg_name String # default value: The value passed for the application name. dmg_passphrase String file String headers Hash owner String, Integer package_id String source String type String # default value: "app" volumes_dir String # default value: The value passed for the application name. action Symbol # defaults to :install if not specified end ``` where: * `dmg_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_eula`, `allow_untrusted`, `app`, `checksum`, `destination`, `dmg_name`, `dmg_passphrase`, `file`, `headers`, `owner`, `package_id`, `source`, `type`, and `volumes_dir` are the properties available to this resource. ### Actions --- The **dmg_package** resource has the following actions: `:install` Installs the application. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **dmg_package** resource has the following properties: `accept_eula` **Ruby Type:** true, false | **Default Value:** `false` Specify whether to accept the EULA. Certain dmg files require acceptance of EULA before mounting. `allow_untrusted` **Ruby Type:** true, false | **Default Value:** `false` Allow installation of packages that do not have trusted certificates. `app` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the application as it appears in the `/Volumes` directory if it differs from the resource block’s name. `checksum` **Ruby Type:** String The sha256 checksum of the `.dmg` file to download. `destination` **Ruby Type:** String | **Default Value:** `/Applications` The directory to copy the `.app` into. `dmg_name` **Ruby Type:** String | **Default Value:** `The value passed for the application name.` The name of the `.dmg` file if it differs from that of the app, or if the name has spaces. `dmg_passphrase` **Ruby Type:** String Specify a passphrase to be used to decrypt the `.dmg` file during the mount process. `file` **Ruby Type:** String The absolute path to the `.dmg` file on the local system. `headers` **Ruby Type:** Hash Allows custom HTTP headers (like cookies) to be set on the `remote_file` resource. `owner` **Ruby Type:** String, Integer The user that should own the package installation. `package_id` **Ruby Type:** String The package ID that is registered with `pkgutil` when a `pkg` or `mpkg` is installed. `source` **Ruby Type:** String The remote URL that is used to download the `.dmg` file, if specified. `type` **Ruby Type:** String | **Default Value:** `app` **Allowed Values:** `"app", "mpkg", "pkg"` The type of package. `volumes_dir` **Ruby Type:** String | **Default Value:** `The value passed for the application name.` The directory under `/Volumes` where the `dmg` is mounted if it differs from the name of the `.dmg` file. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **dmg_package** resource in recipes: **Install Google Chrome via the DMG package**: ``` dmg_package 'Google Chrome' do dmg_name 'googlechrome' source 'https://dl-ssl.google.com/chrome/mac/stable/GGRM/googlechrome.dmg' checksum '7daa2dc5c46d9bfb14f1d7ff4b33884325e5e63e694810adc58f14795165c91a' action :install end ``` **Install VirtualBox from the .mpkg**: ``` dmg_package 'Virtualbox' do source 'http://dlc.sun.com.edgesuite.net/virtualbox/4.0.8/VirtualBox-4.0.8-71778-OSX.dmg' type 'mpkg' end ``` **Install pgAdmin and automatically accept the EULA**: ``` dmg_package 'pgAdmin3' do source 'http://wwwmaster.postgresql.org/redir/198/h/pgadmin3/release/v1.12.3/osx/pgadmin3-1.12.3.dmg' checksum '9435f79d5b52d0febeddfad392adf82db9df159196f496c1ab139a6957242ce9' accept_eula true end ``` dnf_package resource --------------------- [dnf_package resource page](resources/dnf_package/index) --- Use the **dnf_package** resource to install, upgrade, and remove packages with DNF for Fedora and RHEL 8+. The dnf_package resource is able to resolve provides data for packages much like DNF can do when it is run from the command line. This allows a variety of options for installing packages, like minimum versions, virtual provides and library names. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. **New in Chef Infra Client 12.18.** ### Syntax --- A **dnf_package** resource block manages a package on a node, typically by installing it. The simplest use of the **dnf_package** resource is: ``` dnf_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **dnf_package** resource is: ``` dnf_package 'name' do allow_downgrade true, false # default value: true arch String, Array flush_cache Hash # default value: {"before"=>false, "after"=>false} options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `dnf_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `arch`, `flush_cache`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **dnf_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:lock` Locks the DNF package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:unlock` Unlocks the DNF package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **dnf_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. `arch` **Ruby Type:** String, Array The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name. `flush_cache` **Ruby Type:** Hash | **Default Value:** `{"before"=>false, "after"=>false}` Flush the in-memory cache before or after a DNF operation that installs, upgrades, or removes a package. DNF automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while a Chef Infra Client run is in-progress. As an array: ``` dnf_package 'some-package' do #... flush_cache [ :before ] #... end ``` and as a Hash: ``` dnf_package 'some-package' do #... flush_cache( { :after => true } ) #... end ``` Note The `flush_cache` property does not flush the local DNF cache! Use dnf tools—`dnf clean metadata`, `dnf clean packages`, `dnf clean all`—to clean the local DNF cache. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. This property is ignored when using the `:upgrade` action. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **dnf_package** resource in recipes: Install an exact version ``` dnf_package 'netpbm = 10.35.58-8.el5' ``` Install a minimum version ``` dnf_package 'netpbm >= 10.35.58-8.el5' ``` Install a minimum version using the default action ``` dnf_package 'netpbm' ``` To install a package ``` dnf_package 'netpbm' do action :install end ``` To install a partial minimum version ``` dnf_package 'netpbm >= 10' ``` To install a specific architecture ``` dnf_package 'netpbm' do arch 'i386' end ``` or: ``` dnf_package 'netpbm.x86_64' ``` To install a specific version-release ``` dnf_package 'netpbm' do version '10.35.58-8.el5' end ``` To install a specific version (even when older than the current) ``` dnf_package 'tzdata' do version '2011b-1.el5' end ``` Handle cookbook_file and dnf_package resources in the same recipe When a **cookbook_file** resource and a **dnf_package** resource are both called from within the same recipe, use the `flush_cache` attribute to dump the in-memory DNF cache, and then use the repository immediately to ensure that the correct package is installed: ``` cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' end dnf_package 'only-in-custom-repo' do action :install flush_cache [ :before ] end ``` dpkg_package resource ---------------------- [dpkg_package resource page](resources/dpkg_package/index) --- Use the **dpkg_package** resource to manage packages for the dpkg platform. When a package is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. ### Syntax --- A **dpkg_package** resource block manages a package on a node, typically by installing it. The simplest use of the **dpkg_package** resource is: ``` dpkg_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **dpkg_package** resource is: ``` dpkg_package 'name' do options String, Array package_name String, Array response_file String response_file_variables Hash source String, Array timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `dpkg_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `response_file`, `response_file_variables`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **dpkg_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. ### Properties --- The **dpkg_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `response_file` **Ruby Type:** String The direct path to the file used to pre-seed a package. `response_file_variables` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of response file variables in the form of {‘VARIABLE’ => ‘VALUE’}. `source` **Ruby Type:** String, Array The path to a package in the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **dpkg_package** resource in recipes: Install a package ``` dpkg_package 'wget_1.13.4-2ubuntu1.4_amd64.deb' do source '/foo/bar/wget_1.13.4-2ubuntu1.4_amd64.deb' action :install end ``` dsc_resource resource ---------------------- [dsc_resource resource page](resources/dsc_resource/index) --- Windows PowerShell is a task-based command-line shell and scripting language developed by Microsoft. Windows PowerShell uses a document-oriented approach for managing Microsoft Windows-based machines, similar to the approach that is used for managing Unix and Linux-based machines. Windows PowerShell is [a tool-agnostic platform](https://docs.microsoft.com/en-us/powershell/scripting/powershell-scripting) that supports using Chef for configuration management. Desired State Configuration (DSC) is a feature of Windows PowerShell that provides [a set of language extensions, cmdlets, and resources](https://docs.microsoft.com/en-us/powershell/dsc/overview) that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell. The **dsc_resource** resource allows any DSC resource to be used in a Chef recipe, as well as any custom resources that have been added to your Windows PowerShell environment. Microsoft [frequently adds new resources](https://github.com/powershell/DscResources) to the DSC resource collection. Warning Using the **dsc_resource** has the following requirements: * Windows Management Framework (WMF) 5.0 (or higher) * The **dsc_resource** resource can only use binary- or script-based resources. Composite DSC resources may not be used. This is because composite resources aren’t “real” resources from the perspective of the Local Configuration Manager (LCM). Composite resources are used by the “configuration” keyword from the `PSDesiredStateConfiguration` module, and then evaluated in that context. When using DSC to create the configuration document (the Managed Object Framework (MOF) file) from the configuration command, the composite resource is evaluated. Any individual resources from that composite resource are written into the Managed Object Framework (MOF) document. As far as the Local Configuration Manager (LCM) is concerned, there is no such thing as a composite resource. Unless that changes, the **dsc_resource** resource and/or `Invoke-DscResource` command cannot directly use them. ### Syntax --- A **dsc_resource** resource block allows DSC resources to be used in a Chef recipe. For example, the DSC `Archive` resource: ``` Archive ExampleArchive { Ensure = "Present" Path = "C:\Users\Public\Documents\example.zip" Destination = "C:\Users\Public\Documents\ExtractionPath" } ``` and then the same **dsc_resource** with Chef: ``` dsc_resource 'example' do resource :archive property :ensure, 'Present' property :path, "C:\Users\Public\Documents\example.zip" property :destination, "C:\Users\Public\Documents\ExtractionPath" end``` ``` The full syntax for all of the properties that are available to the **dsc_resource** resource is: ``` dsc_resource 'name' do module_name String module_version String property Symbol reboot_action Symbol # default value: :nothing resource Symbol timeout Integer action Symbol # defaults to :run if not specified end ``` where: * `dsc_resource` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `property` is zero (or more) properties in the DSC resource, where each property is entered on a separate line, `:dsc_property_name` is the case-insensitive name of that property, and `"property_value"` is a Ruby value to be applied by Chef Infra Client * `module_name`, `module_version`, `property`, `reboot_action`, `resource`, and `timeout` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **dsc_resource** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Use to run the DSC configuration defined as defined in this resource. ### Properties --- The **dsc_resource** resource has the following properties: `module_name` **Ruby Type:** String The name of the module from which a DSC resource originates. If this property is not specified, it will be inferred. `module_version` **Ruby Type:** String The version number of the module to use. PowerShell 5.0.10018.0 (or higher) supports having multiple versions of a module installed. This should be specified along with the `module_name`. New in Chef Client 12.21 `property` **Ruby Type:** Symbol A property from a Desired State Configuration (DSC) resource. Use this property multiple times, one for each property in the Desired State Configuration (DSC) resource. The format for this property must follow `property :dsc_property_name, "property_value"` for each DSC property added to the resource block. The `:dsc_property_name` must be a symbol. Use the following Ruby types to define `property_value`: | Ruby | Windows PowerShell | | --- | --- | | `Array` | `Object[]` | | `Chef::Util::Powershell:PSCredential` | `PSCredential` | | `False` | `bool($false)` | | `Fixnum` | `Integer` | | `Float` | `Double` | | `Hash` | `Hashtable` | | `True` | `bool($true)` | These are converted into the corresponding Windows PowerShell type during a Chef Infra Client run. `reboot_action` **Ruby Type:** Symbol | **Default Value:** `:nothing` **Allowed Values:** `:nothing, :reboot_now, :request_reboot` Use to request an immediate reboot or to queue a reboot using the :reboot_now (immediate reboot) or :request_reboot (queued reboot) actions built into the reboot resource. New in Chef Client 12.6 `resource` **Ruby Type:** Symbol The name of the DSC resource. This value is case-insensitive and must be a symbol that matches the name of the DSC resource. For built-in DSC resources, use the following values: | Value | Description | | --- | --- | | `:archive` | Use to [unpack archive (.zip) files](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/archiveresource). | | `:environment` | Use to [manage system environment variables](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/environmentresource). | | `:file` | Use to [manage files and directories](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/fileresource). | | `:group` | Use to [manage local groups](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/groupresource). | | `:log` | Use to [log configuration messages](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/logresource). | | `:package` | Use to [install and manage packages](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/packageresource). | | `:registry` | Use to [manage registry keys and registry key values](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/registryresource). | | `:script` | Use to [run PowerShell script blocks](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/scriptresource). | | `:service` | Use to [manage services](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/serviceresource). | | `:user` | Use to [manage local user accounts](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/userresource). | | `:windowsfeature` | Use to [add or remove Windows features and roles](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/windowsfeatureresource). | | `:windowsoptionalfeature` | Use to configure Microsoft Windows optional features. | | `:windowsprocess` | Use to [configure Windows processes](https://docs.microsoft.com/en-us/powershell/dsc/reference/resources/windows/windowsprocessresource). | Any DSC resource may be used in a Chef recipe. For example, the DSC Resource Kit contains resources for [configuring Active Directory components](http://www.powershellgallery.com/packages/xActiveDirectory/2.8.0.0), such as `xADDomain`, `xADDomainController`, and `xADUser`. Assuming that these resources are available to Chef Infra Client, the corresponding values for the `resource` attribute would be: `:xADDomain`, `:xADDomainController`, and `xADUser`. `timeout` **Ruby Type:** Integer The amount of time (in seconds) a command is to wait before timing out. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **dsc_resource** resource in recipes: Open a Zip file ``` dsc_resource 'example' do resource :archive property :ensure, 'Present' property :path, 'C:\Users\Public\Documents\example.zip' property :destination, 'C:\Users\Public\Documents\ExtractionPath' end ``` Manage users and groups ``` dsc_resource 'demogroupadd' do resource :group property :groupname, 'demo1' property :ensure, 'present' end dsc_resource 'useradd' do resource :user property :username, 'Foobar1' property :fullname, 'Foobar1' property :password, ps_credential('P@assword!') property :ensure, 'present' end dsc_resource 'AddFoobar1ToUsers' do resource :Group property :GroupName, 'demo1' property :MembersToInclude, ['Foobar1'] end ``` Create and register a windows service The following example creates a windows service, defines it’s execution path, and prevents windows from starting the service in case the executable is not at the defined location: ``` dsc_resource 'NAME' do resource :service property :name, 'NAME' property :startuptype, 'Disabled' property :path, 'D:\\Sites\\Site_name\file_to_run.exe' property :ensure, 'Present' property :state, 'Stopped' end ``` Create a test message queue The following example creates a file on a node (based on one that is located in a cookbook), unpacks the `MessageQueue.zip` Windows PowerShell module, and then uses the **dsc_resource** to ensure that Message Queuing (MSMQ) sub-features are installed, a test queue is created, and that permissions are set on the test queue: ``` cookbook_file 'cMessageQueue.zip' do path "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip" action :create_if_missing end windows_zipfile "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" do source "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip" action :unzip end dsc_resource 'install-sub-features' do resource :windowsfeature property :ensure, 'Present' property :name, 'msmq' property :IncludeAllSubFeature, true end dsc_resource 'create-test-queue' do resource :cPrivateMsmqQueue property :ensure, 'Present' property :name, 'Test_Queue' end dsc_resource 'set-permissions' do resource :cPrivateMsmqQueuePermissions property :ensure, 'Present' property :name, 'Test_Queue_Permissions' property :QueueNames, 'Test_Queue' property :ReadUsers, node['msmq']['read_user'] end ``` Example to show usage of module properties ``` dsc_resource 'test-cluster' do resource :xCluster module_name 'xFailOverCluster' module_version '1.6.0.0' property :name, 'TestCluster' property :staticipaddress, '10.0.0.3' property :domainadministratorcredential, ps_credential('abcd') end ``` dsc_script resource -------------------- [dsc_script resource page](resources/dsc_script/index) --- Windows PowerShell is a task-based command-line shell and scripting language developed by Microsoft. Windows PowerShell uses a document-oriented approach for managing Microsoft Windows-based machines, similar to the approach that is used for managing Unix and Linux-based machines. Windows PowerShell is [a tool-agnostic platform](https://docs.microsoft.com/en-us/powershell/scripting/powershell-scripting) that supports using Chef for configuration management. Desired State Configuration (DSC) is a feature of Windows PowerShell that provides [a set of language extensions, cmdlets, and resources](https://docs.microsoft.com/en-us/powershell/dsc/overview) that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell. Many DSC resources are comparable to built-in Chef Infra resources. For example, both DSC and Chef have **file**, **package**, and **service** resources. The **dsc_script** resource is most useful for those DSC resources that do not have a direct comparison to a resource in Chef, such as the `Archive` resource, a custom DSC resource, an existing DSC script that performs an important task, and so on. Use the **dsc_script** resource to embed the code that defines a DSC configuration directly within a Chef Infra recipe. Note Windows PowerShell 4.0 is required for using the **dsc_script** resource with Chef Infra. Note The WinRM service must be enabled. (Use `winrm quickconfig` to enable the service.) Warning The **dsc_script** resource may not be used in the same run-list with the **dsc_resource**. This is because the **dsc_script** resource requires that `RefreshMode` in the Local Configuration Manager be set to `Push`, whereas the **dsc_resource** resource requires it to be set to `Disabled`. ### Syntax --- A **dsc_script** resource block embeds the code that defines a DSC configuration directly within a Chef recipe: ``` dsc_script 'get-dsc-resource-kit' do code <<-EOH Archive reskit { ensure = 'Present' path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" } EOH end ``` where: * the **remote_file** resource is first used to download the `DSCResourceKit620082014.zip` file. The full syntax for all of the properties that are available to the **dsc_script** resource is: ``` dsc_script 'name' do code String command String configuration_data String configuration_data_script String configuration_name String cwd String environment Hash flags Hash imports Array timeout Integer action Symbol # defaults to :run if not specified end ``` where: * `dsc_script` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `command`, `configuration_data`, `configuration_data_script`, `configuration_name`, `cwd`, `environment`, `flags`, `imports`, and `timeout` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **dsc_script** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Use to run the DSC configuration defined as defined in this resource. ### Properties --- The **dsc_script** resource has the following properties: `code` **Ruby Type:** String The code for the DSC configuration script. This property may not be used in conjunction with the `command` property. `command` **Ruby Type:** String The path to a valid Windows PowerShell data file that contains the DSC configuration script. This data file must be capable of running independently of Chef and must generate a valid DSC configuration. This property may not be used in conjunction with the `code` property. `configuration_data` **Ruby Type:** String The configuration data for the DSC script. The configuration data must be [a valid Windows PowerShell data file](https://docs.microsoft.com/en-us/powershell/). This property may not be used in conjunction with the `configuration_data_script` property. `configuration_data_script` **Ruby Type:** String The path to a valid Windows PowerShell data file that also contains a node called `localhost`. This property may not be used in conjunction with the `configuration_data` property. `configuration_name` **Ruby Type:** String The name of a valid Windows PowerShell cmdlet. The name may only contain letter (a-z, A-Z), number (0-9), and underscore (_) characters and should start with a letter. The name may not be null or empty. This property may not be used in conjunction with the `code` property. `cwd` **Ruby Type:** String The current working directory. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of ({‘ENV_VARIABLE’ => ‘VALUE’}). (These variables must exist for a command to be run successfully). `flags` **Ruby Type:** Hash Pass parameters to the DSC script that is specified by the `command` property. Parameters are defined as key-value pairs, where the value of each key is the parameter to pass. This property may not be used in the same recipe as the `code` property. For example: `flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' })`. `imports` **Ruby Type:** Array Warning This property **MUST** be used with the `code` attribute. Use to import DSC resources from a module. To import all resources from a module, specify only the module name: ``` imports 'module_name' ``` To import specific resources, specify the module name, and then specify the name for each resource in that module to import: ``` imports 'module_name', 'resource_name_a', 'resource_name_b', ... ``` For example, to import all resources from a module named `cRDPEnabled`: ``` imports 'cRDPEnabled' ``` To import only the `PSHOrg_cRDPEnabled` resource: ``` imports 'cRDPEnabled', 'PSHOrg_cRDPEnabled' ``` `timeout` **Ruby Type:** Integer The amount of time (in seconds) a command is to wait before timing out. #### ps_credential Helper Use the `ps_credential` helper to embed a `PSCredential` object— [a set of security credentials, such as a user name or password](https://technet.microsoft.com/en-us/magazine/ff714574.aspx) —within a script, which allows that script to be run using security credentials. For example, assuming the `CertificateID` is configured in the local configuration manager, the `SeaPower1@3` object is created and embedded within the `seapower-user` script: ``` dsc_script 'seapower-user' do code <<-EOH User AlbertAtom { UserName = 'AlbertAtom' Password = #{ps_credential('SeaPower1@3')} } EOH configuration_data <<-EOH @{ AllNodes = @( @{ NodeName = "localhost"; CertificateID = 'A8D1234559F349F7EF19104678908F701D4167' } ) } EOH end ``` ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **dsc_script** resource in recipes: Specify DSC code directly DSC data can be specified directly in a recipe: ``` dsc_script 'emacs' do code <<-EOH Environment 'texteditor' { Name = 'EDITOR' Value = 'c:\\emacs\\bin\\emacs.exe' } EOH end ``` Specify DSC code using a Windows PowerShell data file Use the `command` property to specify the path to a Windows PowerShell data file. For example, the following Windows PowerShell script defines the `DefaultEditor`: ``` Configuration 'DefaultEditor' { Environment 'texteditor' { Name = 'EDITOR' Value = 'c:\emacs\bin\emacs.exe' } } ``` Use the following recipe to specify the location of that data file: ``` dsc_script 'DefaultEditor' do command 'c:\dsc_scripts\emacs.ps1' end ``` Pass parameters to DSC configurations If a DSC script contains configuration data that takes parameters, those parameters may be passed using the `flags` property. For example, the following Windows PowerShell script takes parameters for the `EditorChoice` and `EditorFlags` settings: ``` $choices = @{'emacs' = 'c:\emacs\bin\emacs';'vi' = 'c:\vim\vim.exe';'powershell' = 'powershell_ise.exe'} Configuration 'DefaultEditor' { [CmdletBinding()] param ( $EditorChoice, $EditorFlags = '' ) Environment 'TextEditor' { Name = 'EDITOR' Value = "$($choices[$EditorChoice]) $EditorFlags" } } ``` Use the following recipe to set those parameters: ``` dsc_script 'DefaultEditor' do flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' }) command 'c:\dsc_scripts\editors.ps1' end ``` Use custom configuration data Configuration data in DSC scripts may be customized from a recipe. For example, scripts are typically customized to set the behavior for Windows PowerShell credential data types. Configuration data may be specified in one of three ways: * By using the `configuration_data` attribute * By using the `configuration_data_script` attribute * By specifying the path to a valid Windows PowerShell data file The following example shows how to specify custom configuration data using the `configuration_data` property: ``` dsc_script 'BackupUser' do configuration_data <<-EOH @{ AllNodes = @( @{ NodeName = "localhost"; PSDscAllowPlainTextPassword = $true }) } EOH code <<-EOH $user = 'backup' $password = ConvertTo-SecureString -String "YourPass$(random)" -AsPlainText -Force $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $password User $user { UserName = $user Password = $cred Description = 'Backup operator' Ensure = "Present" Disabled = $false PasswordNeverExpires = $true PasswordChangeRequired = $false } EOH end ``` The following example shows how to specify custom configuration data using the `configuration_name` property. For example, the following Windows PowerShell script defines the `vi` configuration: ``` Configuration 'emacs' { Environment 'TextEditor' { Name = 'EDITOR' Value = 'c:\emacs\bin\emacs.exe' } } Configuration 'vi' { Environment 'TextEditor' { Name = 'EDITOR' Value = 'c:\vim\bin\vim.exe' } } ``` Use the following recipe to specify that configuration: ``` dsc_script 'EDITOR' do configuration_name 'vi' command 'C:\dsc_scripts\editors.ps1' end ``` Using DSC with other Chef resources The **dsc_script** resource can be used with other resources. The following example shows how to download a file using the **remote_file** resource, and then uncompress it using the DSC `Archive` resource: ``` remote_file "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" do source 'http://gallery.technet.microsoft.com/DSC-Resource-Kit-All-c449312d/file/124481/1/DSC%20Resource%20Kit%20Wave%206%2008282014.zip' end dsc_script 'get-dsc-resource-kit' do code <<-EOH Archive reskit { ensure = 'Present' path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" } EOH end ``` execute resource ---------------- [execute resource page](resources/execute/index) --- Use the **execute** resource to execute a single command. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. Note Use the **script** resource to execute a script using a specific interpreter (Ruby, Python, Perl, csh, or Bash). ### Syntax --- An **execute** resource block typically executes a single command that is unique to the environment in which a recipe will run. Some **execute** resource commands are run by themselves, but often they are run in combination with other Chef resources. For example, a single command that is run by itself: ``` execute 'apache_configtest' do command '/usr/sbin/apachectl configtest' end ``` The full syntax for all of the properties that are available to the **execute** resource is: ``` execute 'name' do command String, Array # default value: 'name' unless specified creates String cwd String default_env true, false # default value: false domain String elevated true, false # default value: false environment Hash group String, Integer input String live_stream true, false # default value: false login true, false # default value: false password String returns Integer, Array # default value: 0 timeout Integer, String, Float # default value: 3600 user String, Integer action Symbol # defaults to :run if not specified end ``` where: * `execute` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command`, `creates`, `cwd`, `default_env`, `domain`, `elevated`, `environment`, `group`, `input`, `live_stream`, `login`, `password`, `returns`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **execute** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Run a command. (default) ### Properties --- The **execute** resource has the following properties: `command` **Ruby Type:** String, Array | **Default Value:** `The resource block's name` An optional property to set the command to be executed if it differs from the resource block’s name. Note Use the **execute** resource to run a single command. Use multiple **execute** resource blocks to run multiple commands. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `default_env` **Ruby Type:** true, false | **Default Value:** `false` When true this enables ENV magic to add path_sanity to the PATH and force the locale to English+UTF-8 for parsing output New in Chef Client 14.2 `domain` **Ruby Type:** String Windows only: The domain of the user specified by the user property. If not specified, the username and password specified by the `user` and `password` properties will be used to resolve that user against the domain in which the system running Chef Infra Client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. New in Chef Client 12.21 `elevated` **Ruby Type:** true, false | **Default Value:** `false` Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) from interactively blocking the process. This will cause the process to be run under a batch login instead of an interactive login. The user running chef-client needs the ‘Replace a process level token’ and ‘Adjust Memory Quotas for a process’ permissions. The user that is running the command needs the ‘Log on as a batch job’ permission. Because this requires a login, the user and password properties are required. New in Chef Client 13.3 `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `input` **Ruby Type:** String An optional property to set the input sent to the command as STDIN. New in Chef Infra Client 16.2 `live_stream` **Ruby Type:** true, false | **Default Value:** `false` Send the output of the command run by this execute resource block to the Chef Infra Client event stream. `login` **Ruby Type:** true, false | **Default Value:** `false` Use a login shell to run the commands instead of inheriting the existing execution environment. New in Chef Infra Client 17.0 `password` **Ruby Type:** String Windows only: The password of the user specified by the user property. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. New in Chef Client 12.21 `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. `domain\user` or `<EMAIL>@my.dns.<EMAIL>.com` via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain property. On Windows only, if this property is specified, the password property must be specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **execute** resource in recipes: **Run a command upon notification**: ``` execute 'slapadd' do command 'slapadd < /tmp/something.ldif' creates '/var/lib/slapd/uid.bdb' action :nothing end template '/tmp/something.ldif' do source 'something.ldif' notifies :run, 'execute[slapadd]', :immediately end ``` **Run a touch file only once while running a command**: ``` execute 'upgrade script' do command 'php upgrade-application.php && touch /var/application/.upgraded' creates '/var/application/.upgraded' action :run end ``` **Run a command which requires an environment variable**: ``` execute 'slapadd' do command 'slapadd < /tmp/something.ldif' creates '/var/lib/slapd/uid.bdb' action :run environment ({'HOME' => '/home/my_home'}) end ``` **Delete a repository using yum to scrub the cache**: ``` # the following code sample thanks to gaffneyc @ https://gist.github.com/918711 execute 'clean-yum-cache' do command 'yum clean all' action :nothing end file '/etc/yum.repos.d/bad.repo' do action :delete notifies :run, 'execute[clean-yum-cache]', :immediately end ``` **Prevent restart and reconfigure if configuration is broken**: Use the `:nothing` action (common to all resources) to prevent the test from starting automatically, and then use the `subscribes` notification to run a configuration test when a change to the template is detected. ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing subscribes :run, 'template[/etc/nagios3/configures-nagios.conf]', :immediately end ``` **Notify in a specific order**: To notify multiple resources, and then have these resources run in a certain order, do something like the following. ``` execute 'foo' do command '...' notifies :create, 'template[baz]', :immediately notifies :install, 'package[bar]', :immediately notifies :run, 'execute[final]', :immediately end template 'baz' do #... notifies :run, 'execute[restart_baz]', :immediately end package 'bar' execute 'restart_baz' execute 'final' do command '...' end ``` where the sequencing will be in the same order as the resources are listed in the recipe: `execute 'foo'`, `template 'baz'`, `execute [restart_baz]`, `package 'bar'`, and `execute 'final'`. **Execute a command using a template**: The following example shows how to set up IPv4 packet forwarding using the **execute** resource to run a command named `forward_ipv4` that uses a template defined by the **template** resource. ``` execute 'forward_ipv4' do command 'echo > /proc/.../ipv4/ip_forward' action :nothing end template '/etc/file_name.conf' do source 'routing/file_name.conf.erb' notifies :run, 'execute[forward_ipv4]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[forward_ipv4]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. **Add a rule to an IP table**: The following example shows how to add a rule named `test_rule` to an IP table using the **execute** resource to run a command using a template that is defined by the **template** resource: ``` execute 'test_rule' do command "command_to_run --option value --option value --source #{node[:name_of_node][:ipsec][:local][:subnet]} -j test_rule" action :nothing end template '/etc/file_name.local' do source 'routing/file_name.local.erb' notifies :run, 'execute[test_rule]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[test_rule]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. **Stop a service, do stuff, and then restart it**: The following example shows how to use the **execute**, **service**, and **mount** resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following: * Checks to see if the Amazon EC2 node has MySQL * If the node has MySQL, stops MySQL * Installs MySQL * Mounts the node * Restarts MySQL ``` # the following code sample comes from the ``server_ec2`` # recipe in the following cookbook: # https://github.com/chef-cookbooks/mysql if (node.attribute?('ec2') && !FileTest.directory?(node['mysql']['ec2_path'])) service 'mysql' do action :stop end execute 'install-mysql' do command "mv #{node['mysql']['data_dir']}#{node['mysql']['ec2_path']}" not_if { ::File.directory?(node['mysql']['ec2_path']) } end [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir| directory dir do owner 'mysql' group 'mysql' end end mount node['mysql']['data_dir'] do device node['mysql']['ec2_path'] fstype 'none' options 'bind,rw' action [:mount, :enable] end service 'mysql' do action :start end end ``` where * the two **service** resources are used to stop, and then restart the MySQL service * the **execute** resource is used to install MySQL * the **mount** resource is used to mount the node and enable MySQL **Use the platform_family? method**: The following is an example of using the `platform_family?` method in the Recipe DSL to create a variable that can be used with other resources in the same recipe. In this example, `platform_family?` is being used to ensure that a specific binary is used for a specific platform before using the **remote_file** resource to download a file from a remote location, and then using the **execute** resource to install that file by running a command. ``` if platform_family?('rhel') pip_binary = '/usr/bin/pip' else pip_binary = '/usr/local/bin/pip' end remote_file "#{Chef::Config[:file_cache_path]}/distribute_setup.py" do source 'http://python-distribute.org/distribute_setup.py' mode '0755' not_if { ::File.exist?(pip_binary) } end execute 'install-pip' do cwd Chef::Config[:file_cache_path] command <<~EOF # command for installing Python goes here EOF not_if { ::File.exist?(pip_binary) } end ``` where a command for installing Python might look something like: ``` #{node['python']['binary']} distribute_setup.py #{::File.dirname(pip_binary)}/easy_install pip ``` **Control a service using the execute resource**: Warning This is an example of something that should NOT be done. Use the **service** resource to control a service, not the **execute** resource. Do something like this: ``` service 'tomcat' do action :start end ``` and NOT something like this: ``` execute 'start-tomcat' do command '/etc/init.d/tomcat start' action :run end ``` There is no reason to use the **execute** resource to control a service because the **service** resource exposes the `start_command` property directly, which gives a recipe full control over the command issued in a much cleaner, more direct manner. **Use the search Infra Language helper to find users**: The following example shows how to use the `search` method in the Chef Infra Language to search for users: ``` # the following code sample comes from the openvpn cookbook: search("users", "*:*") do |u| execute "generate-openvpn-#{u['id']}" do command "./pkitool #{u['id']}" cwd '/etc/openvpn/easy-rsa' end %w{ conf ovpn }.each do |ext| template "#{node['openvpn']['key_dir']}/#{u['id']}.#{ext}" do source 'client.conf.erb' variables :username => u['id'] end end end ``` where * the search data will be used to create **execute** resources * the **template** resource tells Chef Infra Client which template to use **Enable remote login for macOS**: ``` execute 'enable ssh' do command '/usr/sbin/systemsetup -setremotelogin on' not_if '/usr/sbin/systemsetup -getremotelogin | /usr/bin/grep On' action :run end ``` **Execute code immediately, based on the template resource**: By default, notifications are `:delayed`, that is they are queued up as they are triggered, and then executed at the very end of a Chef Infra Client run. To run an action immediately, use `:immediately`: ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :immediately end ``` and then Chef Infra Client would immediately run the following: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing end ``` **Sourcing a file**: The **execute** resource cannot be used to source a file (e.g. `command 'source filename'`). The following example will fail because `source` is not an executable: ``` execute 'foo' do command 'source /tmp/foo.sh' end ``` Instead, use the **script** resource or one of the **script**-based resources (**bash**, **csh**, **perl**, **python**, or **ruby**). For example: ``` bash 'foo' do code 'source /tmp/foo.sh' end ``` **Run a Knife command**: ``` execute 'create_user' do command <<~EOM knife user create #{user} --admin --password password --disable-editing --file /home/vagrant/.chef/user.pem --config /tmp/knife-admin.rb EOM end ``` **Run install command into virtual environment**: The following example shows how to install a lightweight JavaScript framework into Vagrant: ``` execute "install q and zombiejs" do cwd "/home/vagrant" user "vagrant" environment ({'HOME' => '/home/vagrant', 'USER' => 'vagrant'}) command "npm install -g q zombie should mocha coffee-script" action :run end ``` **Run a command as a named user**: The following example shows how to run `bundle install` from a Chef Infra Client run as a specific user. This will put the gem into the path of the user (`vagrant`) instead of the root user (under which the Chef Infra Client runs): ``` execute '/opt/chefdk/embedded/bin/bundle install' do cwd node['chef_workstation']['bundler_path'] user node['chef_workstation']['user'] environment ({ 'HOME' => "/home/#{node['chef_workstation']['user']}", 'USER' => node['chef_workstation']['user'] }) not_if 'bundle check' end ``` **Run a command as an alternate user**: *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] domain "domain-name" user "user" password "password" end # Passing username = 'domain-name\username'. No domain is passed execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] user "domain-name\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed execute 'mkdir test_dir' do cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end ``` **Run a command with an external input file**: execute ‘md5sum’ do input File.read(**FILE**) end file resource ------------- [file resource page](resources/file/index) --- Use the **file** resource to manage files directly on a node. Note Use the **cookbook_file** resource to copy a file from a cookbook’s `/files` directory. Use the **template** resource to create a file based on a template in a cookbook’s `/templates` directory. And use the **remote_file** resource to transfer a file to a node from a remote location. ### Syntax --- A **file** resource block manages files that exist on nodes. For example, to write the home page for an Apache website: ``` file '/var/www/customers/public_html/index.php' do content '<html>This is a placeholder for the home page.</html>' mode '0755' owner 'web_admin' group 'web_admin' end ``` where: * `'/var/www/customers/public_html/index.php'` is path to the file and also the filename to be managed * `content` defines the contents of the file The full syntax for all of the properties that are available to the **file** resource is: ``` file 'name' do atomic_update true, false backup false, Integer checksum String content String force_unlink true, false group String, Integer inherits true, false manage_symlink_source true, false mode String, Integer owner String, Integer path String # defaults to 'name' if not specified rights Hash verify String, Block, Symbol action Symbol # defaults to :create if not specified end ``` where: * `file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `atomic_update`, `backup`, `checksum`, `content`, `force_unlink`, `group`, `inherits`, `manage_symlink_source`, `mode`, `owner`, `path`, `rights`, `sensitive`, and `verify` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **file** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. ### Properties --- The **file** resource has the following properties: `atomic_update` **Ruby Type:** true, false | **Default Value:** `False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.` Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the `client.rb` file. `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `checksum` **Ruby Type:** String The SHA-256 checksum of the file. Use to ensure that a specific file is used. If the checksum does not match, the file is not used. `content` **Ruby Type:** String A string that is written to the file. The contents of this property replace any previous content when this property has something other than the default value. The default behavior will not modify content. `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `false`, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `true`, Chef will follow the symlink and will manage the permissions and content of symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String The full path to the file, including the file name and its extension. For example: `/files/file.txt`. Default value: the `name` of the resource block. See “Syntax” section above for more information. Microsoft Windows: A path that begins with a forward slash (`/`) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (`/`) is not recommended. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `verify` **Ruby Type:** String, Block, Symbol Allows verification of a file'’s contents before it is created. Creates a temporary file and then allows execution of commands or Ruby code. If this code evaluates to true, the file is created. If the code evaluates to false, an error is raised. The types for this property are a block, string, or a symbol. When specified as a block, it returns `true` or `false`. When specified as a string, it is executed as a system command. It returns `true` if the command returns 0 as its exit status code and `false` if the command returns a non-zero exit status code. When using a built-in verifier symbol it returns `true` if the verifier succeeds else it returns `false`. Currently suppported verifiers are `:yaml`, `:json` and `:systemd_unit`. Note A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block returns `true`, Chef Infra Client will continue to update the file as appropriate.' For example, this should return `true`: ``` file '/tmp/baz' do verify { 1 == 1 } end ``` This should also return `true`: ``` file '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` In this example, the `%{path}` portion of this command is expanded to the temporary location where a copy of the file to be created exists. This will use Nginx’s syntax checking feature to ensure the file is a valid Nginx configuration file before writing the file. An error will be raised if the executed command returns a non-zero exit status code. This should return `true`: ``` file '/tmp/foo' do content "hello" verify do |path| open(path).read.include? "hello" end end ``` Whereas, this should return `false`: ``` file '/tmp/foo' do content "goodbye" verify do |path| open(path).read.include? "hello" end end ``` When using one of the built-in symbols(`:json`, `:yaml`, `:systemd_unit`) This should return `true`: ``` file 'foo.json' do content '{"foo": "bar"}' verify :json end ``` Whereas, this should return `false`: ``` file 'foo.yaml' do content "--- foo: 'foo-" verify :yaml end ``` If a string, block or symbol returns `false`, the Chef Infra Client run will stop and an error is raised. #### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **file** resource in recipes: Create a file ``` file '/tmp/something' do owner 'root' group 'root' mode '0755' action :create end ``` Create a file in Microsoft Windows To create a file in Microsoft Windows, be sure to add an escape character—`\`—before the backslashes in the paths: ``` file 'C:\\tmp\\something.txt' do rights :read, 'Everyone' rights :full_control, 'DOMAIN\\User' action :create end ``` Remove a file ``` file '/tmp/something' do action :delete end ``` Set file modes ``` file '/tmp/something' do mode '0755' end ``` Delete a repository using yum to scrub the cache ``` # the following code sample thanks to gaffneyc @ https://gist.github.com/918711 execute 'clean-yum-cache' do command 'yum clean all' action :nothing end file '/etc/yum.repos.d/bad.repo' do action :delete notifies :run, 'execute[clean-yum-cache]', :immediately notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately end ``` Add the value of a data bag item to a file The following example shows how to get the contents of a data bag item named `impossible_things`, create a .pem file located at `some/directory/path/`, and then use the `content` attribute to update the contents of that file with the value of the `impossible_things` data bag item: ``` private_key = data_bag_item('impossible_things', private_key_name)['private_key'] file "some/directory/path/#{private_key_name}.pem" do content private_key owner 'root' group 'group' mode '0755' end ``` Write a YAML file The following example shows how to use the `content` property to write a YAML file: ``` file "#{app['deploy_to']}/shared/config/settings.yml" do owner "app['owner']" group "app['group']" mode '0755' content app.to_yaml end ``` Write a string to a file The following example specifies a directory, and then uses the `content` property to add a string to the file created in that directory: ``` status_file = '/path/to/file/status_file' file status_file do owner 'root' group 'root' mode '0755' content 'My favourite foremost coastal Antarctic shelf, oh Larsen B!' end ``` Create a file from a copy The following example shows how to copy a file from one directory to another, locally on a node: ``` file '/root/1.txt' do content IO.read('/tmp/1.txt') action :create end ``` where the `content` attribute uses the Ruby `IO.read` method to get the contents of the `/tmp/1.txt` file. freebsd_package resource ------------------------- [freebsd_package resource page](resources/freebsd_package/index) --- Use the **freebsd_package** resource to manage packages for the FreeBSD platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **freebsd_package** resource block manages a package on a node, typically by installing it. The simplest use of the **freebsd_package** resource is: ``` freebsd_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **freebsd_package** resource is: ``` freebsd_package 'name' do options String package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `freebsd_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **freebsd_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. ### Properties --- The **freebsd_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **freebsd_package** resource in recipes: Install a package ``` freebsd_package 'name of package' do action :install end ``` gem_package resource --------------------- [gem_package resource page](resources/gem_package/index) --- Use the **gem_package** resource to manage gem packages that are only included in recipes. When a gem is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. Note The **gem_package** resource must be specified as `gem_package` and cannot be shortened to `package` in a recipe. Warning The **chef_gem** and **gem_package** resources are both used to install Ruby gems. For any machine on which Chef Infra Client is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is available only to Chef Infra Client. Use the **chef_gem** resource to install gems into the instance of Ruby that is dedicated to Chef Infra Client. Use the **gem_package** resource to install all other gems (i.e. install gems system-wide). ### Syntax --- The full syntax for all of the properties that are available to the **gem_package** resource is: ``` gem_package 'name' do clear_sources true, false gem_binary String include_default_source true, false options String, Hash, Array package_name String source String, Array timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `gem_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `clear_sources`, `gem_binary`, `include_default_source`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **gem_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **gem_package** resource has the following properties: `clear_sources` **Ruby Type:** true, false | **Default Value:** `false unless `clear_gem_sources` set to true in the `client.rb` config.` Set to `true` to download a gem from the path specified by the `source` property (and not from RubyGems). `gem_binary` **Ruby Type:** String The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by Chef Infra Client will be used. `include_default_source` **Ruby Type:** true, false Set to `false` to not include `Chef::Config[:rubygems_url]` in the sources. New in Chef Client 13.0 `options` **Ruby Type:** String, Hash, Array Options for the gem install, either a Hash or a String. When a hash is given, the options are passed to `Gem::DependencyInstaller.new`, and the gem will be installed via the gems API. When a String is given, the gem will be installed by shelling out to the gem command. Using a Hash of options with an explicit gem_binary will result in undefined behavior. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String, Array Optional. The URL, or list of URLs, at which the gem package is located. This list is added to the source configured in `Chef::Config[:rubygems_url]` (see also include_default_source) to construct the complete list of rubygems sources. Users in an ‘airgapped’ environment should set Chef::Config[:rubygems_url] to their local RubyGems mirror. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **gem_package** resource in recipes: The following examples demonstrate various approaches for using the **gem_package** resource in recipes: **Install a gem file from the local file system** ``` gem_package 'loofah' do source '/tmp/loofah-2.7.0.gem' action :install end ``` **Use the `ignore_failure` common attribute** ``` gem_package 'syntax' do action :install ignore_failure true end ``` git resource ------------ [git resource page](resources/git/index) --- Use the **git** resource to manage source control resources that exist in a git repository. git version 1.6.5 (or higher) is required to use all of the functionality in the git resource. ### Syntax --- A **git** resource block manages source control resources that exist in a git repository: ``` git "#{Chef::Config[:file_cache_path]}/app_name" do repository node[:app_name][:git_repository] revision node[:app_name][:git_revision] action :sync end ``` The full syntax for all of the properties that are available to the **git** resource is: ``` git 'name' do additional_remotes Hash # default value: {} checkout_branch String depth Integer destination String # default value: 'name' unless specified enable_checkout true, false # default value: true enable_submodules true, false # default value: false environment Hash group String, Integer remote String # default value: "origin" repository String revision String # default value: "HEAD" ssh_wrapper String timeout Integer user String, Integer action Symbol # defaults to :sync if not specified end ``` where: * `git` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `additional_remotes`, `checkout_branch`, `depth`, `destination`, `enable_checkout`, `enable_submodules`, `environment`, `group`, `remote`, `repository`, `revision`, `ssh_wrapper`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **git** resource has the following actions: `:checkout` Clone or check out the source. When a checkout is available, this provider does nothing. `:export` Export the source, excluding or removing any version control artifacts. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:sync` Default. Update the source to the specified version, or get a new clone or checkout. This action causes a hard reset of the index and working tree, discarding any uncommitted changes. ### Properties --- The **git** resource has the following properties: `additional_remotes` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of additional remotes that are added to the git repository configuration. `checkout_branch` **Ruby Type:** String Do a one-time checkout from git **or** use when a branch in the upstream repository is named `deploy`. To prevent the **git** resource from attempting to check out master from master, set `enable_checkout` to `false` when using the `checkout_branch` property. See `revision`. `depth` **Ruby Type:** Integer The number of past revisions to be included in the git shallow clone. Unless specified the default behavior will do a full clone. `destination` **Ruby Type:** String | **Default Value:** `The resource block's name` The location path to which the source is to be cloned, checked out, or exported. Default value: the name of the resource block. `enable_checkout` **Ruby Type:** true, false | **Default Value:** `true` Check out a repo from master. Set to `false` when using the `checkout_branch` attribute to prevent the git resource from attempting to check out `master` from `master`. `enable_submodules` **Ruby Type:** true, false | **Default Value:** `false` Perform a sub-module initialization and update. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) Note The **git** provider automatically sets the `ENV['HOME']` and `ENV['GIT_SSH']` environment variables. To override this behavior and provide different values, add `ENV['HOME']` and/or `ENV['GIT_SSH']` to the `environment` Hash. `group` **Ruby Type:** String, Integer The system group that will own the checked-out code. `remote` **Ruby Type:** String | **Default Value:** `origin` The remote repository to use when synchronizing an existing clone. `repository` **Ruby Type:** String The URI of the code repository. `revision` **Ruby Type:** String | **Default Value:** `HEAD` A branch, tag, or commit to be synchronized with git. This can be symbolic, like `HEAD` or it can be a source control management-specific revision identifier. See `checkout_branch`. The value of the `revision` attribute may change over time. From one branch to another, to a tag, to a specific SHA for a commit, and then back to a branch. The `revision` attribute may even be changed in a way where history gets rewritten. Instead of tracking a specific branch or doing a headless checkout, Chef Infra Client maintains its own branch (via the **git** resource) that does not exist in the upstream repository. Chef Infra Client is then free to forcibly check out this branch to any commit without destroying the local history of an existing branch. For example, to explicitly track an upstream repository’s master branch: ``` revision 'master' ``` Use the `git rev-parse` and `git ls-remote` commands to verify that Chef Infra Client is synchronizing commits correctly. (Chef Infra Client always runs `git ls-remote` on the upstream repository to verify the commit is made to the correct repository.) `ssh_wrapper` **Ruby Type:** String The path to the wrapper script used when running SSH with git. The `GIT_SSH` environment variable is set to this. `timeout` **Ruby Type:** Integer The amount of time (in seconds) to wait for a command to execute before timing out. When this property is specified using the **deploy** resource, the value of the `timeout` property is passed from the **deploy** resource to the **git** resource. `user` **Ruby Type:** String, Integer | **Default Value:** ``HOME` environment variable of the user running chef-client` The system user that will own the checked-out code. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **git** resource in recipes: **Use the git mirror** ``` git '/opt/my_sources/couch' do repository 'git://git.apache.org/couchdb.git' revision 'master' action :sync end ``` **Use different branches** To use different branches, depending on the environment of the node: ``` branch_name = if node.chef_environment == 'QA' 'staging' else 'master' end git '/home/user/deployment' do repository '<EMAIL>:git_site/deployment.git' revision branch_name action :sync user 'user' group 'test' end ``` Where the `branch_name` variable is set to staging or master, depending on the environment of the node. Once this is determined, the `branch_name` variable is used to set the revision for the repository. If the git status command is used after running the example above, it will return the branch name as `deploy`, as this is the default value. Run Chef Infra Client in debug mode to verify that the correct branches are being checked out: ``` sudo chef-client -l debug ``` **Install an application from git using bash** The following example shows how Bash can be used to install a plug-in for rbenv named ruby-build, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which ruby-build is located, and then runs a command. ``` git "/Users/tsmith/.chef/cache/ruby-build" do repository 'git://github.com/rbenv/ruby-build.git' revision 'master' action :sync end bash 'install_ruby_build' do cwd "/Users/tsmith/.chef/cache/ruby-build" user 'rbenv' group 'rbenv' code <<-EOH ./install.sh EOH environment 'PREFIX' => '/usr/local' end ``` **Notify a resource post-checkout** ``` git "/Users/tsmith/.chef/cache/my_app" do repository node['my_app']['git_repository'] revision node['my_app']['git_revision'] action :sync notifies :run, 'bash[compile_my_app]', :immediately end ``` **Pass in environment variables** ``` git '/opt/my_sources/couch' do repository 'git://git.apache.org/couchdb.git' revision 'master' environment 'VAR' => 'whatever' action :sync end ``` group resource -------------- [group resource page](resources/group/index) --- Use the **group** resource to manage a local group. ### Syntax --- The full syntax for all of the properties that are available to the **group** resource is: ``` group 'name' do append true, false # default value: false comment String excluded_members String, Array # default value: [] gid String, Integer group_name String # default value: 'name' unless specified members String, Array # default value: [] non_unique true, false # default value: false system true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `group` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `append`, `comment`, `excluded_members`, `gid`, `group_name`, `members`, `non_unique`, and `system` are the properties available to this resource. ### Actions --- The **group** resource has the following actions: `:create` Default. Create a group. If a group already exists (but does not match), update that group to match. `:manage` Manage an existing group. This action does nothing if the group does not exist. `:modify` Modify an existing group. This action raises an exception if the group does not exist. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a group. ### Properties --- The **group** resource has the following properties: `append` **Ruby Type:** true, false | **Default Value:** `false` How members should be appended and/or removed from a group. When true, `members` are appended and `excluded_members` are removed. When `false`, group members are reset to the value of the `members` property. `comment` **Ruby Type:** String Specifies a comment to associate with the local group. New in Chef Client 14.9 `excluded_members` **Ruby Type:** String, Array | **Default Value:** `[]` Remove users from a group. May only be used when `append` is set to `true`. `gid` **Ruby Type:** String, Integer The identifier for the group. `group_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the group. Default value: the `name` of the resource block. See “Syntax” section above for more information. `members` **Ruby Type:** String, Array | **Default Value:** `[]` Which users should be set or appended to a group. When more than one group member is identified, the list of members should be an array: `members ['user1', 'user2']`. `non_unique` **Ruby Type:** true, false | **Default Value:** `false` Allow gid duplication. May only be used with the `Groupadd` user resource provider. `system` **Ruby Type:** true, false | **Default Value:** `false` Set to `true` if the group belongs to a system group. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **group** resource in recipes: Append users to groups\n\n `ruby\n group 'www-data' do\n \ \ action :modify\n members 'maintenance'\n append true\n end\n` \n\n \ \ Add a user to group on the Windows platform\n\n `ruby\n group 'Administrators'\ \ do\n members ['domain\\foo']\n append true\n action :modify\n end\n\ \` \n" habitat_config resource ------------------------ [habitat_config resource page](resources/habitat_config/index) --- Use the **habitat_config** resource to apply a configuration to a Chef Habitat service. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_config** resource is: ``` habitat_config 'name' do config Mash (Hash-like) gateway_auth_token String remote_sup String # default value: "127.0.0.1:9632" remote_sup_http String # default value: "127.0.0.1:9631" service_group String # default value: 'name' unless specified user String action Symbol # defaults to :apply if not specified end ``` where: * `habitat_config` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `config`, `gateway_auth_token`, `remote_sup`, `remote_sup_http`, `service_group`, and `user` are the properties available to this resource. ### Actions --- The **habitat_config** resource has the following actions: `:apply` applies the given configuration (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **habitat_config** resource has the following properties: `config` **Ruby Type:** Mash (Hash-like) | `REQUIRED` The configuration to apply as a ruby hash, for example, `{ worker_count: 2, http: { keepalive_timeout: 120 } }`. `gateway_auth_token` **Ruby Type:** String Auth token for accessing the remote supervisor’s http port. `remote_sup` **Ruby Type:** String | **Default Value:** `127.0.0.1:9632` Address to a remote supervisor’s control gateway. `remote_sup_http` **Ruby Type:** String | **Default Value:** `127.0.0.1:9631` Address for remote supervisor http port. Used to pull existing. `service_group` **Ruby Type:** String | **Default Value:** `The resource block's name` The service group to apply the configuration to. For example, `nginx.default` `user` **Ruby Type:** String Name of user key to use for encryption. Passes `--user` to `hab config apply`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_config** resource in recipes: **Configure your nginx defaults** ``` habitat_config 'nginx.default' do config({ worker_count: 2, http: { keepalive_timeout: 120 } }) end ``` habitat_install resource ------------------------- [habitat_install resource page](resources/habitat_install/index) --- Use the **habitat_install** resource to install Chef Habitat. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_install** resource is: ``` habitat_install 'name' do bldr_url String create_user true, false # default value: true hab_version String install_url String license String tmp_dir String action Symbol # defaults to :install if not specified end ``` where: * `habitat_install` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bldr_url`, `create_user`, `hab_version`, `install_url`, `license`, and `tmp_dir` are the properties available to this resource. ### Actions --- The **habitat_install** resource has the following actions: `:install` Installs Habitat. Does nothing if the `hab` binary is found in the default location for the system (`/bin/hab` on Linux, `/usr/local/bin/hab` on macOS, `C:/habitat/hab.exe` on Windows) (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **habitat_install** resource has the following properties: `bldr_url` **Ruby Type:** String Optional URL to an alternate Habitat Builder. `create_user` **Ruby Type:** true, false | **Default Value:** `true` Creates the `hab` system user. `hab_version` **Ruby Type:** String Specify the version of `Habitat` you would like to install. `install_url` **Ruby Type:** String | **Default Value:** `https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh` URL to the install script, default is from the [habitat repo](https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh) . `license` **Ruby Type:** String **Allowed Values:** `"accept"` Specifies acceptance of habitat license when set to `accept`. `tmp_dir` **Ruby Type:** String Sets TMPDIR environment variable for location to place temp files. Note This is required if `/tmp` and `/var/tmp` are mounted `noexec`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_install** resource in recipes: **Installation Without a Resource Name** ``` habitat_install ``` **Installation specifying a habitat builder URL** ``` habitat_install 'install habitat' do bldr_url 'http://localhost' end ``` **Installation specifying version and habitat builder URL** ``` habitat_install 'install habitat' do bldr_url 'http://localhost' hab_version '1.5.50' end ``` habitat_package resource ------------------------- [habitat_package resource page](resources/habitat_package/index) --- Use the **habitat_package** to install or remove Chef Habitat packages from Habitat Builder. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_package** resource is: ``` habitat_package 'name' do auth_token String binlink true, false, force # default value: false bldr_url String # default value: "https://bldr.habitat.sh" channel String # default value: "stable" exclude String keep_latest String no_deps true, false # default value: false options String package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `habitat_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `auth_token`, `binlink`, `bldr_url`, `channel`, `exclude`, `keep_latest`, `no_deps`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **habitat_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:lock` `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` `:remove` Remove a package. `:unlock` `:upgrade` Install a package and ensure that a package is the latest version. ### Properties --- The **habitat_package** resource has the following properties: `auth_token` **Ruby Type:** String Auth token for installing a package from a private organization on Habitat builder. `binlink` **Ruby Type:** true, false, force | **Default Value:** `false` If habitat should attempt to binlink the package. Acceptable values: `true`, `false`, `:force`. Will fail on binlinking if set to `true` and binary or binlink exists. `bldr_url` **Ruby Type:** String | **Default Value:** `https://bldr.habitat.sh` The habitat builder url where packages will be downloaded from. **Defaults to public Habitat Builder** `channel` **Ruby Type:** String | **Default Value:** `stable` The release channel to install your package from. `exclude` **Ruby Type:** String Identifier of one or more packages that should not be uninstalled. (ex: core/redis, core/busybox-static/1.42.2/21120102031201) `keep_latest` **Ruby Type:** String Ability to uninstall while retaining a specified version **This feature only works in Habitat 1.5.86+.** `no_deps` **Ruby Type:** true, false | **Default Value:** `false` Remove package but retain dependencies. `options` **Ruby Type:** String Pass any additional parameters to the habitat package command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_package** resource in recipes: **Install core/redis** ``` habitat_package 'core/redis' ``` **Install specific version of a package from the unstable channel** ``` habitat_package 'core/redis' do version '3.2.3' channel 'unstable' end ``` **Install a package with specific version and revision** ``` habitat_package 'core/redis' do version '3.2.3/20160920131015' end ``` **Install a package and force linking it’s binary files to the system path** ``` habitat_package 'core/nginx' do binlink :force end ``` **Install a package and link it’s binary files to the system path** ``` habitat_package 'core/nginx' do options '--binlink' end ``` **Remove package and all of it’s versions** ``` habitat_package 'core/nginx' action :remove end ``` **Remove specified version of a package** ``` habitat_package 'core/nginx/3.2.3' action :remove end ``` **Remove package but retain some versions Note: Only available as of Habitat 1.5.86** ``` habitat_package 'core/nginx' keep_latest '2' action :remove end ``` ``` **Remove package but keep dependencies** habitat_package 'core/nginx' no_deps false action :remove end ``` habitat_service resource ------------------------- [habitat_service resource page](resources/habitat_service/index) --- Use the **habitat_service** resource to manage Chef Habitat services. This requires that `core/hab-sup` be running as a service. See the `habitat_sup` resource documentation for more information. Note Applications may run as a specific user. Often with Habitat, the default is `hab`, or `root`. If the application requires another user, then it should be created with Chef’s `user` resource. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_service** resource is: ``` habitat_service 'name' do bind String, Array # default value: [] binding_mode Symbol, String # default value: :strict bldr_url String # default value: "https://bldr.habitat.sh/" channel Symbol, String # default value: :stable gateway_auth_token String health_check_interval Integer # default value: 30 remote_sup String # default value: "127.0.0.1:9632" remote_sup_http String # default value: "127.0.0.1:9631" service_group String # default value: "default" service_name String # default value: 'name' unless specified shutdown_timeout Integer # default value: 8 strategy Symbol, String # default value: :none topology Symbol, String # default value: :standalone update_condition Symbol, String # default value: :latest action Symbol # defaults to :load if not specified end ``` where: * `habitat_service` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bind`, `binding_mode`, `bldr_url`, `channel`, `gateway_auth_token`, `health_check_interval`, `remote_sup`, `remote_sup_http`, `service_group`, `service_name`, `shutdown_timeout`, `strategy`, `topology`, and `update_condition` are the properties available to this resource. ### Actions --- The **habitat_service** resource has the following actions: `:load` (default action) runs `hab service load` to load and start the specified application service (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reload` runs the `:unload` and then `:load` actions `:restart` runs the `:stop` and then `:start` actions `:start` runs `hab service start` to start the specified application service `:stop` runs `hab service stop` to stop the specified application service `:unload` runs `hab service unload` to unload and stop the specified application service ### Properties --- The **habitat_service** resource has the following properties: `bind` **Ruby Type:** String, Array | **Default Value:** `[]` Passes `--bind` with the specified services to bind to the hab command. If an array of multiple service binds are specified then a `--bind` flag is added for each. `binding_mode` **Ruby Type:** Symbol, String | **Default Value:** `:strict` **Allowed Values:** `:strict, "strict", :relaxed, "relaxed"` Passes `--binding-mode` with the specified binding mode. Defaults to `:strict`. Options are `:strict` or `:relaxed` `bldr_url` **Ruby Type:** String | **Default Value:** `https://bldr.habitat.sh/` Passes `--url` with the specified Habitat Builder URL to the hab command. Depending on the type of Habitat Builder you are connecting to, this URL will look different, here are the **3** current types: - Public Habitat Builder (default) - `https://bldr.habitat.sh` - On-Prem Habitat Builder installed using the [Source Install Method](https://github.com/habitat-sh/on-prem-builder) - `https://your.bldr.url` - On-Prem Habitat Builder installed using the [Automate Installer](https://automate.chef.io/docs/on-prem-builder/) - `https://your.bldr.url/bldr/v1` `channel` **Ruby Type:** Symbol, String | **Default Value:** `:stable` Passes `--channel` with the specified channel to the hab command `gateway_auth_token` **Ruby Type:** String Auth token for accessing the remote supervisor’s http port. `health_check_interval` **Ruby Type:** Integer | **Default Value:** `30` The interval (seconds) on which to run health checks. `remote_sup` **Ruby Type:** String | **Default Value:** `127.0.0.1:9632` Address to a remote Supervisor’s Control Gateway `remote_sup_http` **Ruby Type:** String | **Default Value:** `127.0.0.1:9631` IP address and port used to communicate with the remote supervisor. If this value is invalid, the resource will update the supervisor configuration each time Chef Infra Server runs. `service_group` **Ruby Type:** String | **Default Value:** `default` Passes `--group` with the specified service group to the hab command `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the service, must be in the form of `origin/name` `shutdown_timeout` **Ruby Type:** Integer | **Default Value:** `8` The timeout in seconds allowed during shutdown. `strategy` **Ruby Type:** Symbol, String | **Default Value:** `:none` **Allowed Values:** `:none, "none", :"at-once", "at-once", :rolling, "rolling"` Passes `--strategy` with the specified update strategy to the hab command. Defaults to `:none`. Other options are `:'at-once'` and `:rolling` `topology` **Ruby Type:** Symbol, String | **Default Value:** `:standalone` **Allowed Values:** `:standalone, "standalone", :leader, "leader"` Passes `--topology` with the specified service topology to the hab command `update_condition` **Ruby Type:** Symbol, String | **Default Value:** `:latest` **Allowed Values:** `:latest, "latest", :"track-channel", "track-channel"` Passes `--update-condition` dictating when this service should updated. Defaults to `latest`. Options are `latest` or `track-channel` **_ Note This requires a minimum habitat version of 1.5.71_** - `latest`: Runs the latest package that can be found in the configured channel and local packages. - `track-channel`: Always run the package at the head of a given channel. This enables service rollback, where demoting a package from a channel will cause the package to rollback to an older version of the package. A ramification of enabling this condition is that packages that are newer than the package at the head of the channel are also uninstalled during a service rollback. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_service** resource in recipes: **Install and load nginx** ``` habitat_package 'core/nginx' habitat_service 'core/nginx' habitat_service 'core/nginx unload' do service_name 'core/nginx' action :unload end ``` **Pass the `strategy` and `topology` options to hab service commands** ``` habitat_service 'core/redis' do strategy 'rolling' topology 'standalone' end ``` **Using update_condition** ``` habitat_service 'core/redis' do strategy 'rolling' update_condition 'track-channel' topology 'standalone' end ``` **If the service has it’s own user specified that is not the `hab` user, don’t create the `hab` user on install, and instead create the application user with Chef’s `user` resource** ``` habitat_install 'install habitat' do create_user false end user 'acme-apps' do system true end habitat_service 'acme/apps' ``` habitat_sup resource --------------------- [habitat_sup resource page](resources/habitat_sup/index) --- Use the **habitat_sup** resource to runs a Chef Habitat supervisor for one or more Chef Habitat services. The resource is commonly used in conjunction with `habitat_service` which will manage the services loaded and started within the supervisor. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_sup** resource is: ``` habitat_sup 'name' do auth_token String auto_update true, false # default value: false bldr_url String event_stream_application String event_stream_cert String event_stream_environment String event_stream_site String event_stream_token String event_stream_url String gateway_auth_token String hab_channel String health_check_interval String, Integer keep_latest String launcher_version String license String limit_no_files String listen_ctl String listen_gossip String listen_http String org String # default value: "default" peer String, Array permanent_peer true, false # default value: false ring String service_version String sup_version String toml_config true, false # default value: false update_condition String action Symbol # defaults to :run if not specified end ``` where: * `habitat_sup` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `auth_token`, `auto_update`, `bldr_url`, `event_stream_application`, `event_stream_cert`, `event_stream_environment`, `event_stream_site`, `event_stream_token`, `event_stream_url`, `gateway_auth_token`, `hab_channel`, `health_check_interval`, `keep_latest`, `launcher_version`, `license`, `limit_no_files`, `listen_ctl`, `listen_gossip`, `listen_http`, `org`, `peer`, `permanent_peer`, `ring`, `service_version`, `sup_version`, `toml_config`, and `update_condition` are the properties available to this resource. ### Actions --- The **habitat_sup** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` The `run` action handles installing Habitat using the `habitat_install` resource, ensures that the appropriate versions of the `core/hab-sup` and `core/hab-launcher` packages are installed using `habitat_package`, and then drops off the appropriate init system definitions and manages the service. (default) `:stop` ### Properties --- The **habitat_sup** resource has the following properties: `auth_token` **Ruby Type:** String Auth token for accessing a private organization on bldr. This value is templated into the appropriate service file. `auto_update` **Ruby Type:** true, false | **Default Value:** `false` Passes `--auto-update`. This will set the Habitat supervisor to automatically update itself any time a stable version has been released. `bldr_url` **Ruby Type:** String The Habitat Builder URL for the `habitat_package` resource, if needed. `event_stream_application` **Ruby Type:** String The name of your application that will be displayed in the Chef Automate Applications Dashboard. `event_stream_cert` **Ruby Type:** String With `Intermediary Certificates` or, Automate 2 being set to use TLS with a valid cert, you will need to provide `Habitat` with your certificate for communication with Automate to work. [Follow these steps!](https://automate.chef.io/docs/applications-setup/#share-the-tls-certificate-with-chef-habitat). `event_stream_environment` **Ruby Type:** String The application environment for the supervisor, this is for grouping in the Applications Dashboard. `event_stream_site` **Ruby Type:** String Application Dashboard label for the ‘site’ of the application - can be filtered in the dashboard. `event_stream_token` **Ruby Type:** String Chef Automate token for sending application event stream data. `event_stream_url` **Ruby Type:** String `AUTOMATE_HOSTNAME:4222` - the Chef Automate URL with port 4222 specified Note The port can be changed if needed. `gateway_auth_token` **Ruby Type:** String Auth token for accessing the supervisor’s HTTP gateway. This value is templated into the appropriate service file. `hab_channel` **Ruby Type:** String The channel to install Habitat from. Defaults to stable `health_check_interval` **Ruby Type:** String, Integer The interval (seconds) on which to run health checks. `keep_latest` **Ruby Type:** String Automatically cleans up old packages. If this flag is enabled, service startup will initiate an uninstall of all previous versions of the associated package. This also applies when a service is restarted due to an update. If a number is passed to this argument, that number of latest versions will be kept. The same logic applies to the Supervisor package `env:HAB_KEEP_LATEST_PACKAGES=1` Note This requires Habitat version `1.5.86+` `launcher_version` **Ruby Type:** String Allows you to choose which version of launcher to install. `license` **Ruby Type:** String **Allowed Values:** `"accept"` Specifies acceptance of habitat license when set to `accept`. `limit_no_files` **Ruby Type:** String allows you to set LimitNOFILE in the systemd service when used Note Linux Only. `listen_ctl` **Ruby Type:** String Only valid for `:run` action, passes `--listen-ctl` with the specified address and port, e.g., `0.0.0.0:9632`, to the hab command. `listen_gossip` **Ruby Type:** String Only valid for `:run` action, passes `--listen-gossip` with the specified address and port, e.g., `0.0.0.0:9638`, to the hab command. `listen_http` **Ruby Type:** String Only valid for `:run` action, passes `--listen-http` with the specified address and port, e.g., `0.0.0.0:9631`, to the hab command. `org` **Ruby Type:** String | **Default Value:** `default` Only valid for `:run` action, passes `--org` with the specified org name to the hab command. `peer` **Ruby Type:** String, Array Only valid for `:run` action, passes `--peer` with the specified initial peer to the hab command. `permanent_peer` **Ruby Type:** true, false | **Default Value:** `false` Only valid for `:run` action, passes `--permanent-peer` to the hab command. `ring` **Ruby Type:** String Only valid for `:run` action, passes `--ring` with the specified ring key name to the hab command. `service_version` **Ruby Type:** String Allows you to choose which version of the ***Windows Service*** to install. `sup_version` **Ruby Type:** String Allows you to choose which version of supervisor you would like to install. Note If a version is provided, it will also install that version of habitat if not previously installed. `toml_config` **Ruby Type:** true, false | **Default Value:** `false` Supports using the Supervisor toml configuration instead of passing exec parameters to the service, [reference](https://www.habitat.sh/docs/reference/#supervisor-config). `update_condition` **Ruby Type:** String Passes `--update-condition` dictating when this service should updated. Defaults to `latest`. Options are `latest` or `track-channel` **_ Note This requires a minimum habitat version of 1.5.71_** - `latest`: Runs the latest package that can be found in the configured channel and local packages. - `track-channel`: Always run what is at the head of a given channel. This enables service rollback where demoting a package from a channel will cause the package to rollback to an older version of the package. A ramification of enabling this condition is packages newer than the package at the head of the channel will be automatically uninstalled during a service rollback. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_sup** resource in recipes: **Set up with just the defaults** ``` habitat_sup 'default' ``` **Update listen ports and use Supervisor toml config** ``` habitat_sup 'test-options' do listen_http '0.0.0.0:9999' listen_gossip '0.0.0.0:9998' toml_config true end ``` **Use with an on-prem Habitat Builder. Note: Access to public builder may not be available due to your company policies** ``` habitat_sup 'default' do bldr_url 'https://bldr.example.com' end ``` **Using update_condition** ``` habitat_sup 'default' do bldr_url 'https://bldr.example.com' habitat_channel 'dev' update_condition 'track-channel' end ``` **Provide event_stream_* information** ``` habitat_sup 'default' do license 'accept' event_stream_application 'myapp' event_stream_environment 'production' event_stream_site 'MySite' event_stream_url 'automate.example.com:4222' event_stream_token 'myawesomea2clitoken=' event_stream_cert '/hab/cache/ssl/mycert.crt' end ``` **Provide specific versions** ``` habitat_sup 'default' do bldr_url 'https://bldr.example.com' sup_version '1.5.50' launcher_version '13458' service_version '0.6.0' # WINDOWS ONLY end ``` **Set latest version of packages to retain** habitat_sup ‘default’ do bldr_url ‘<https://bldr.example.com>’ sup_version ‘1.5.86’ launcher_version ‘13458’ service_version ‘0.6.0’ # WINDOWS ONLY keep_latest ‘2’ end habitat_user_toml resource ---------------------------- [habitat_user_toml resource page](resources/habitat_user_toml/index) --- Use the **habitat_user_toml** to template a `user.toml` for Chef Habitat services. Configurations set in the `user.toml` override the `default.toml` for a given package, which makes it an alternative to applying service group level configuration. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **habitat_user_toml** resource is: ``` habitat_user_toml 'name' do config Mash (Hash-like) service_name String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `habitat_user_toml` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `config` and `service_name` are the properties available to this resource. ### Actions --- The **habitat_user_toml** resource has the following actions: `:create` (default action) Create the user.toml from the specified config. (default) `:delete` Delete the user.toml `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **habitat_user_toml** resource has the following properties: `config` **Ruby Type:** Mash (Hash-like) | `REQUIRED` Only valid for `:create` action. The configuration to apply as a ruby hash, for example, `{ worker_count: 2, http: { keepalive_timeout: 120 } }`. `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The service group to apply the configuration to, for example, `nginx.default`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **habitat_user_toml** resource in recipes: **Configure user specific settings to nginx** ``` habitat_user_toml 'nginx' do config({ worker_count: 2, http: { keepalive_timeout: 120 } }) end ``` homebrew_cask resource ----------------------- [homebrew_cask resource page](resources/homebrew_cask/index) --- Use the **homebrew_cask** resource to install binaries distributed via the Homebrew package manager. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **homebrew_cask** resource is: ``` homebrew_cask 'name' do cask_name String # default value: 'name' unless specified homebrew_path String # default value: "/usr/local/bin/brew" install_cask true, false # default value: true options String owner String, Integer # default value: "Calculated default username" action Symbol # defaults to :install if not specified end ``` where: * `homebrew_cask` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `cask_name`, `homebrew_path`, `install_cask`, `options`, and `owner` are the properties available to this resource. ### Actions --- The **homebrew_cask** resource has the following actions: `:install` Install an application that is packaged as a Homebrew cask. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an application that is packaged as a Homebrew cask. ### Properties --- The **homebrew_cask** resource has the following properties: `cask_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the cask name if it differs from the resource block’s name. `homebrew_path` **Ruby Type:** String | **Default Value:** `/usr/local/bin/brew` The path to the homebrew binary. `install_cask` **Ruby Type:** true, false | **Default Value:** `true` Automatically install the Homebrew cask tap, if necessary. `options` **Ruby Type:** String Options to pass to the brew command during installation. `owner` **Ruby Type:** String, Integer | **Default Value:** `Calculated default username` The owner of the Homebrew installation. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. homebrew_package resource -------------------------- [homebrew_package resource page](resources/homebrew_package/index) --- Use the **homebrew_package** resource to manage packages for the macOS platform. Note Starting with Chef Infra Client 16 the homebrew resource now accepts an array of packages for installing multiple packages at once. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. **New in Chef Infra Client 12.0.** ### Syntax --- The full syntax for all of the properties that are available to the **homebrew_package** resource is: ``` homebrew_package 'name' do homebrew_user String, Integer options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `homebrew_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `homebrew_user`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **homebrew_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and ensure that a package is the latest version. ### Properties --- The **homebrew_package** resource has the following properties: `homebrew_user` **Ruby Type:** String, Integer The name or uid of the Homebrew owner to be used by Chef Infra Client when executing a command. Chef Infra Client, by default, will attempt to execute a Homebrew command as the owner of the `/usr/local/bin/brew` executable. If that executable does not exist, Chef Infra Client will attempt to find the user by executing `which brew`. If that executable cannot be found, Chef Infra Client will print an error message: `Could not find the 'brew' executable in /usr/local/bin or anywhere on the path.`. Set this property to specify the Homebrew owner for situations where Chef Infra Client cannot automatically detect the correct owner.' `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **homebrew_package** resource in recipes: **Install a package**: ``` homebrew_package 'git' ``` **Install multiple packages at once**: ``` homebrew_package %w(git fish ruby) ``` **Specify the Homebrew user with a UUID** ``` homebrew_package 'git' do homebrew_user 1001 end ``` **Specify the Homebrew user with a string**: ``` homebrew_package 'vim' do homebrew_user 'user1' end ``` homebrew_tap resource ---------------------- [homebrew_tap resource page](resources/homebrew_tap/index) --- Use the **homebrew_tap** resource to add additional formula repositories to the Homebrew package manager. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **homebrew_tap** resource is: ``` homebrew_tap 'name' do homebrew_path String # default value: "/usr/local/bin/brew" owner String # default value: "Calculated default username" tap_name String # default value: 'name' unless specified url String action Symbol # defaults to :tap if not specified end ``` where: * `homebrew_tap` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `homebrew_path`, `owner`, `tap_name`, and `url` are the properties available to this resource. ### Actions --- The **homebrew_tap** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:tap` Add a Homebrew tap. (default) `:untap` Remove a Homebrew tap. ### Properties --- The **homebrew_tap** resource has the following properties: `homebrew_path` **Ruby Type:** String | **Default Value:** `/usr/local/bin/brew` The path to the Homebrew binary. `owner` **Ruby Type:** String | **Default Value:** `Calculated default username` The owner of the Homebrew installation. `tap_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the tap name if it differs from the resource block’s name. `url` **Ruby Type:** String The URL of the tap. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. homebrew_update resource ------------------------- [homebrew_update resource page](resources/homebrew_update/index) --- Use the **homebrew_update** resource to manage Homebrew repository updates on macOS. **New in Chef Infra Client 16.2.** ### Syntax --- The full syntax for all of the properties that are available to the **homebrew_update** resource is: ``` homebrew_update 'name' do frequency Integer # default value: 86400 action Symbol # defaults to :periodic if not specified end ``` where: * `homebrew_update` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `frequency` is the property available to this resource. ### Actions --- The **homebrew_update** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:periodic` Run a periodic update based on the frequency property. (default) `:update` Run an immediate update. ### Properties --- The **homebrew_update** resource has the following properties: `frequency` **Ruby Type:** Integer | **Default Value:** `86400` Determines how frequently (in seconds) Homebrew updates are made. Use this property when the `:periodic` action is specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **homebrew_update** resource in recipes: **Update the homebrew repository data at a specified interval**: ``` homebrew_update 'all platforms' do frequency 86400 action :periodic end ``` **Update the Homebrew repository at the start of a Chef Infra Client run**: ``` homebrew_update 'update' ``` hostname resource ----------------- [hostname resource page](resources/hostname/index) --- Use the **hostname** resource to set the system’s hostname, configure hostname and hosts config file, and re-run the Ohai hostname plugin so the hostname will be available in subsequent cookbooks. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **hostname** resource is: ``` hostname 'name' do aliases Array compile_time true, false # default value: true domain_password String domain_user String fqdn String hostname String # default value: 'name' unless specified ipaddress String # default value: The node's IP address as determined by Ohai. windows_reboot true, false # default value: true action Symbol # defaults to :set if not specified end ``` where: * `hostname` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `aliases`, `compile_time`, `domain_password`, `domain_user`, `fqdn`, `hostname`, `ipaddress`, and `windows_reboot` are the properties available to this resource. ### Actions --- The **hostname** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Sets the node’s hostname. (default) ### Properties --- The **hostname** resource has the following properties: `aliases` **Ruby Type:** Array An array of hostname aliases to use when configuring the hosts file. `compile_time` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the resource should be run at compile time. `domain_password` **Ruby Type:** String The password to accompany the domain_user parameter New in Chef Infra Client 17.2 `domain_user` **Ruby Type:** String A domain account specified in the form of DOMAIN\user used when renaming a domain-joined device New in Chef Infra Client 17.2 `fqdn` **Ruby Type:** String An optional property to set the fqdn if it differs from the resource block’s hostname. New in Chef Infra Client 17.0 `hostname` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the hostname if it differs from the resource block’s name. `ipaddress` **Ruby Type:** String | **Default Value:** `The node's IP address as determined by Ohai.` The IP address to use when configuring the hosts file. `windows_reboot` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not Windows should be reboot after changing the hostname, as this is required for the change to take effect. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **hostname** resource in recipes: **Set the hostname using the IP address, as detected by Ohai**: ``` hostname 'example' ``` **Manually specify the hostname and IP address**: ``` hostname 'statically_configured_host' do hostname 'example' ipaddress '198.51.100.2' end ``` **Change the hostname of a Windows, Non-Domain joined node**: ``` hostname 'renaming a workgroup computer' do hostname 'Foo' end ``` **Change the hostname of a Windows, Domain-joined node (new in 17.2)**: ``` hostname 'renaming a domain-joined computer' do hostname 'Foo' domain_user "Domain\Someone" domain_password 'SomePassword' end ``` http_request resource ---------------------- [http_request resource page](resources/http_request/index) --- Use the **http_request** resource to send an HTTP request (`GET`, `PUT`, `POST`, `DELETE`, `HEAD`, or `OPTIONS`) with an arbitrary message. This resource is often useful when custom callbacks are necessary. ### Syntax --- A **http_request** resource block sends HTTP requests with an arbitrary message. For example, send a `DELETE` request to `'http://www.chef.io/some_page?message=please_delete_me'`. ``` http_request 'please_delete_me' do url 'http://www.chef.io/some_page' action :delete end ``` The full syntax for all of the properties that are available to the **http_request** resource is: ``` http_request 'name' do headers Hash message Object # defaults to 'name' if not specified url String action Symbol # defaults to :get if not specified end ``` where: * `http_request` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `headers`, `message`, and `url` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **http_request** resource has the following actions: `:delete` Send a `DELETE` request. `:get` Default. Send a `GET` request. Changed in Chef Client 12.0 to deprecate the hard-coded query string from earlier versions. Cookbooks that rely on this string need to be updated to manually add it to the URL as it is passed to the resource. `:head` Send a `HEAD` request. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:options` Send an `OPTIONS` request. `:post` Send a `POST` request. `:put` Send a `PUT` request. ### Properties --- The **http_request** resource has the following properties: `headers` **Ruby Type:** Hash A Hash of custom headers. `message` **Ruby Type:** Object The message that is sent by the HTTP request. Default value: the `name` of the resource block. See “Syntax” section above for more information. `url` **Ruby Type:** String The URL to which an HTTP request is sent. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **http_request** resource in recipes: Send a GET request ``` http_request 'some_message' do url 'http://example.com/check_in' end ``` The message is sent as `http://example.com/check_in?message=some_message`. Send a POST request To send a `POST` request as JSON data, convert the message to JSON and include the correct content-type header. For example: ``` http_request 'posting data' do action :post url 'http://example.com/check_in' message ({:some => 'data'}.to_json) headers({'AUTHORIZATION' => "Basic #{ Base64.encode64('username:password')}", 'Content-Type' => 'application/data' }) end ``` Transfer a file only when the remote source changes ``` remote_file '/tmp/couch.png' do source 'http://couchdb.apache.org/img/sketch.png' action :nothing end http_request 'HEAD http://couchdb.apache.org/img/sketch.png' do message '' url 'http://couchdb.apache.org/img/sketch.png' action :head if ::File.exist?('/tmp/couch.png') headers 'If-Modified-Since' => File.mtime('/tmp/couch.png').httpdate end notifies :create, 'remote_file[/tmp/couch.png]', :immediately end ``` ifconfig resource ----------------- [ifconfig resource page](resources/ifconfig/index) --- Use the **ifconfig** resource to manage interfaces on Unix and Linux systems. Note This resource requires the ifconfig binary to be present on the system and may require additional packages to be installed first. On Ubuntu 18.04 or later you will need to install the `ifupdown` package, which disables the built in Netplan functionality. Warning This resource will not work with Fedora release 33 or later. ### Syntax --- The full syntax for all of the properties that are available to the **ifconfig** resource is: ``` ifconfig 'name' do bcast String bonding_opts String bootproto String bridge String device String ethtool_opts String family String # default value: "inet" gateway String hwaddr String inet_addr String mask String master String metric String mtu String network String onboot String onparent String slave String target String # default value: 'name' unless specified vlan String action Symbol # defaults to :add if not specified end ``` where: * `ifconfig` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bcast`, `bonding_opts`, `bootproto`, `bridge`, `device`, `ethtool_opts`, `family`, `gateway`, `hwaddr`, `inet_addr`, `mask`, `master`, `metric`, `mtu`, `network`, `onboot`, `onparent`, `slave`, `target`, and `vlan` are the properties available to this resource. ### Actions --- The **ifconfig** resource has the following actions: `:add` Run ifconfig to configure a network interface and (on some platforms) write a configuration file for that network interface. (default) `:delete` Run ifconfig to disable a network interface and (on some platforms) delete that network interface’s configuration file. `:disable` Run ifconfig to disable a network interface. `:enable` Run ifconfig to enable a network interface. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **ifconfig** resource has the following properties: `bcast` **Ruby Type:** String The broadcast address for a network interface. On some platforms this property is not set using ifconfig, but instead is added to the startup configuration file for the network interface. `bonding_opts` **Ruby Type:** String Bonding options to pass via `BONDING_OPTS` on RHEL and CentOS. For example: `mode=active-backup miimon=100`. New in Chef Client 13.4 `bootproto` **Ruby Type:** String The boot protocol used by a network interface. `bridge` **Ruby Type:** String The bridge interface this interface is a member of on Red Hat based systems. New in Chef Infra Client 16.7 `device` **Ruby Type:** String The network interface to be configured. `ethtool_opts` **Ruby Type:** String Options to be passed to ethtool(8). For example: `-A eth0 autoneg off rx off tx off`. New in Chef Client 13.4 `family` **Ruby Type:** String | **Default Value:** `inet` Networking family option for Debian-based systems; for example: `inet` or `inet6`. New in Chef Client 14.0 `gateway` **Ruby Type:** String The gateway to use for the interface. New in Chef Client 14.4 `hwaddr` **Ruby Type:** String The hardware address for the network interface. `inet_addr` **Ruby Type:** String The Internet host address for the network interface. `mask` **Ruby Type:** String The decimal representation of the network mask. For example: `255.255.255.0`. `master` **Ruby Type:** String Specifies the channel bonding interface to which the Ethernet interface is linked. New in Chef Client 13.4 `metric` **Ruby Type:** String The routing metric for the interface. `mtu` **Ruby Type:** String The maximum transmission unit (MTU) for the network interface. `network` **Ruby Type:** String The address for the network interface. `onboot` **Ruby Type:** String Bring up the network interface on boot. `onparent` **Ruby Type:** String Bring up the network interface when its parent interface is brought up. `slave` **Ruby Type:** String When set to `yes`, this device is controlled by the channel bonding interface that is specified via the `master` property. New in Chef Client 13.4 `target` **Ruby Type:** String | **Default Value:** `The resource block's name` The IP address that is to be assigned to the network interface. If not specified we’ll use the resource’s name. `vlan` **Ruby Type:** String The VLAN to assign the interface to. New in Chef Client 14.4 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **ifconfig** resource in recipes: **Configure a network interface with a static IP** ``` ifconfig '33.33.33.80' do device 'eth1' end ``` will create the following interface configuration: ``` iface eth1 inet static address 33.33.33.80 ``` **Configure an interface to use DHCP** ``` ifconfig 'Set eth1 to DHCP' do device 'eth1' bootproto 'dhcp' end ``` will create the following interface configuration: ``` iface eth1 inet dhcp ``` **Update a static IP address with a boot protocol** ``` ifconfig "33.33.33.80" do bootproto "dhcp" device "eth1" end ``` will update the interface configuration from static to dhcp: ``` iface eth1 inet dhcp address 33.33.33.80 ``` inspec_input resource ---------------------- [inspec_input resource page](resources/inspec_input/index) --- Use the **inspec_input** resource to add an input to the Compliance Phase. **New in Chef Infra Client 17.5.** ### Syntax --- The full syntax for all of the properties that are available to the **inspec_input** resource is: ``` inspec_input 'name' do input Hash, String # default value: 'name' unless specified source Hash, String # default value: 'name' unless specified action Symbol # defaults to :add if not specified end ``` where: * `inspec_input` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `input` and `source` are the properties available to this resource. ### Actions --- The **inspec_input** resource has the following actions: `:add` Add an input to the compliance phase (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **inspec_input** resource has the following properties: `input` **Ruby Type:** Hash, String | **Default Value:** `The resource block's name` `source` **Ruby Type:** Hash, String | **Default Value:** `The resource block's name` ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **inspec_input** resource in recipes: **Activate the default input in the openssh cookbook’s compliance segment**: ``` inspec_input 'openssh' do action :add end ``` **Activate all inputs in the openssh cookbook’s compliance segment**: ``` inspec_input 'openssh::.*' do action :add end ``` **Add an InSpec input to the Compliance Phase from a hash**: ``` inspec_input { ssh_custom_path: '/whatever2' } ``` **Add an InSpec input to the Compliance Phase using the ‘name’ property to identify the input**: ``` inspec_input "setting my input" do source( { ssh_custom_path: '/whatever2' }) end ``` **Add an InSpec input to the Compliance Phase using a TOML, JSON, or YAML file**: ``` inspec_input "/path/to/my/input.yml" ``` **Add an InSpec input to the Compliance Phase using a TOML, JSON, or YAML file, using the ‘name’ property**: ``` inspec_input "setting my input" do source "/path/to/my/input.yml" end ``` Note that the **inspec_input** resource does not update and will not fire notifications (similar to the log resource). This is done to preserve the ability to use the resource while not causing the updated resource count to be larger than zero. Since the resource does not update the state of the managed node, this behavior is still consistent with the configuration management model. Instead, you should use events to observe configuration changes for the compliance phase. It is possible to use the `notify_group` resource to chain notifications of the two resources, but notifications are the wrong model to use, and you should use pure ruby conditionals instead. Compliance configuration should be independent of other resources and should only be conditional based on state/attributes, not other resources. inspec_waiver resource ----------------------- [inspec_waiver resource page](resources/inspec_waiver/index) --- Use the **inspec_waiver** resource to add a waiver to the Compliance Phase. **New in Chef Infra Client 17.5.** ### Syntax --- The full syntax for all of the properties that are available to the **inspec_waiver** resource is: ``` inspec_waiver 'name' do control String # default value: 'name' unless specified expiration String justification String run_test true, false source Hash, String action Symbol # defaults to :add if not specified end ``` where: * `inspec_waiver` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `control`, `expiration`, `justification`, `run_test`, and `source` are the properties available to this resource. ### Actions --- The **inspec_waiver** resource has the following actions: `:add` Add a waiver to the compliance phase (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **inspec_waiver** resource has the following properties: `control` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the control being waived `expiration` **Ruby Type:** String The expiration date of the waiver - provided in YYYY-MM-DD format `justification` **Ruby Type:** String Can be any text you want and might include a reason for the waiver as well as who signed off on the waiver. `run_test` **Ruby Type:** true, false If present and true, the control will run and be reported, but failures in it won’t make the overall run fail. If absent or false, the control will not be run. `source` **Ruby Type:** Hash, String ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **inspec_waiver** resource in recipes: **Activate the default waiver in the openssh cookbook’s compliance segment**: ``` inspec_waiver 'openssh' do action :add end ``` **Activate all waivers in the openssh cookbook’s compliance segment**: ``` inspec_waiver 'openssh::.*' do action :add end ``` **Add an InSpec waiver to the Compliance Phase**: ``` inspec_waiver 'Add waiver entry for control' do control 'my_inspec_control_01' run_test false justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" expiration '2022-01-01' action :add end ``` **Add an InSpec waiver to the Compliance Phase using the ‘name’ property to identify the control**: ``` inspec_waiver 'my_inspec_control_01' do justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" action :add end ``` **Add an InSpec waiver to the Compliance Phase using an arbitrary YAML, JSON, or TOML file**: ``` # files ending in .yml or .yaml that exist are parsed as YAML inspec_waiver "/path/to/my/waiver.yml" inspec_waiver "my-waiver-name" do source "/path/to/my/waiver.yml" end # files ending in .json that exist are parsed as JSON inspec_waiver "/path/to/my/waiver.json" inspec_waiver "my-waiver-name" do source "/path/to/my/waiver.json" end # files ending in .toml that exist are parsed as TOML inspec_waiver "/path/to/my/waiver.toml" inspec_waiver "my-waiver-name" do source "/path/to/my/waiver.toml" end ``` **Add an InSpec waiver to the Compliance Phase using a hash**: ``` my_hash = { "ssh-01" => { "expiration_date" => "2033-07-31", "run" => false, "justification" => "because" } } inspec_waiver "my-waiver-name" do source my_hash end ``` Note that the **inspec_waiver** resource does not update and will not fire notifications (similar to the log resource). This is done to preserve the ability to use the resource while not causing the updated resource count to be larger than zero. Since the resource does not update the state of the managed node, this behavior is still consistent with the configuration management model. Instead, you should use events to observe configuration changes for the compliance phase. It is possible to use the `notify_group` resource to chain notifications of the two resources, but notifications are the wrong model to use, and you should use pure ruby conditionals instead. Compliance configuration should be independent of other resources and should only be conditional based on state/attributes, not other resources. inspec_waiver_file_entry resource ------------------------------------ [inspec_waiver_file_entry resource page](resources/inspec_waiver_file_entry/index) --- Use the **inspec_waiver_file_entry** resource to add or remove entries from an InSpec waiver file. This can be used in conjunction with the Compliance Phase. **New in Chef Infra Client 17.1.** ### Syntax --- The full syntax for all of the properties that are available to the **inspec_waiver_file_entry** resource is: ``` inspec_waiver_file_entry 'name' do backup false, Integer # default value: false control String # default value: 'name' unless specified expiration String file_path String justification String run_test true, false action Symbol # defaults to :add if not specified end ``` where: * `inspec_waiver_file_entry` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `backup`, `control`, `expiration`, `file_path`, `justification`, and `run_test` are the properties available to this resource. ### Actions --- The **inspec_waiver_file_entry** resource has the following actions: `:add` (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` ### Properties --- The **inspec_waiver_file_entry** resource has the following properties: `backup` **Ruby Type:** false, Integer | **Default Value:** `false` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `control` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the control being added or removed to the waiver file `expiration` **Ruby Type:** String The expiration date of the given waiver - provided in YYYY-MM-DD format `file_path` **Ruby Type:** String | **Default Value:** ``/etc/chef/inspec_waivers.yml` on Linux/Unix and `C:\chef\inspec_waivers.yml` on Windows` | `REQUIRED` The path to the waiver file being modified `justification` **Ruby Type:** String Can be any text you want and might include a reason for the waiver as well as who signed off on the waiver. `run_test` **Ruby Type:** true, false If present and `true`, the control will run and be reported, but failures in it won’t make the overall run fail. If absent or `false`, the control will not be run. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **inspec_waiver_file_entry** resource in recipes: **Add an InSpec waiver entry to a given waiver file**: ``` inspec_waiver_file_entry 'Add waiver entry for control' do file_path 'C:\chef\inspec_waiver_file.yml' control 'my_inspec_control_01' run_test false justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" expiration '2022-01-01' action :add end ``` **Add an InSpec waiver entry to a given waiver file using the ‘name’ property to identify the control**: ``` inspec_waiver_file_entry 'my_inspec_control_01' do justification "The subject of this control is not managed by Chef Infra Client on the systems in policy group #{node['policy_group']}" action :add end ``` **Remove an InSpec waiver entry to a given waiver file**: ``` inspec_waiver_file_entry "my_inspec_control_01" do action :remove end ``` ips_package resource --------------------- [ips_package resource page](resources/ips_package/index) --- Use the **ips_package** resource to manage packages (using Image Packaging System (IPS)) on the Solaris 11 platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **ips_package** resource block manages a package on a node, typically by installing it. The simplest use of the **ips_package** resource is: ``` ips_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **ips_package** resource is: ``` ips_package 'name' do accept_license true, false # default value: false options String package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `ips_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `accept_license`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **ips_package** resource has the following actions: `:install` Install a package. If a version is specified, install the specified version of the package. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **ips_package** resource has the following properties: `accept_license` **Ruby Type:** true, false | **Default Value:** `false` Accept an end-user license agreement, automatically. `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **ips_package** resource in recipes: Install a package ``` ips_package 'name of package' do action :install end ``` kernel_module resource ----------------------- [kernel_module resource page](resources/kernel_module/index) --- Use the **kernel_module** resource to manage kernel modules on Linux systems. This resource can load, unload, blacklist, disable, enable, install, and uninstall modules. **New in Chef Infra Client 14.3.** ### Syntax --- The full syntax for all of the properties that are available to the **kernel_module** resource is: ``` kernel_module 'name' do load_dir String # default value: "/etc/modules-load.d" modname String # default value: 'name' unless specified options Array unload_dir String # default value: "/etc/modprobe.d" action Symbol # defaults to :install if not specified end ``` where: * `kernel_module` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `load_dir`, `modname`, `options`, and `unload_dir` are the properties available to this resource. ### Actions --- The **kernel_module** resource has the following actions: `:blacklist` Blacklist a kernel module. `:disable` Disable a kernel module. **New in Chef Infra Client 15.2.** `:enable` Enable a kernel module. Reverse :disable actions `:install` Load kernel module, and ensure it loads on reboot. (default) `:load` Load a kernel module. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:uninstall` Unload a kernel module and remove module config, so it doesn’t load on reboot. `:unload` Unload kernel module. ### Properties --- The **kernel_module** resource has the following properties: `load_dir` **Ruby Type:** String | **Default Value:** `/etc/modules-load.d` The directory to load modules from. `modname` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the kernel module name if it differs from the resource block’s name. `options` **Ruby Type:** Array An optional property to set options for the kernel module. New in Chef Infra Client 15.4 `unload_dir` **Ruby Type:** String | **Default Value:** `/etc/modprobe.d` The modprobe.d directory. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **kernel_module** resource in recipes: Install and load a kernel module, and ensure it loads on reboot. ``` kernel_module 'loop' ``` Install and load a kernel with a specific set of options, and ensure it loads on reboot. Consult kernel module documentation for specific options that are supported. ``` kernel_module 'loop' do options [ 'max_loop=4', 'max_part=8', ] end ``` Load a kernel module. ``` kernel_module 'loop' do action :load end ``` Unload a kernel module and remove module config, so it doesn’t load on reboot. ``` kernel_module 'loop' do action :uninstall end ``` Unload kernel module. ``` kernel_module 'loop' do action :unload end ``` Blacklist a module from loading. ``` kernel_module 'loop' do action :blacklist end ``` Disable a kernel module so that it is not installable. ``` kernel_module 'loop' do action :disable end ``` Enable a kernel module so that it is can be installed. Does not load or install. ``` kernel_module 'loop' do action :enable end ``` ksh resource ------------ [ksh resource page](resources/ksh/index) --- Use the **ksh** resource to execute scripts using the Korn shell (ksh) interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **ksh** resource block executes scripts using ksh: ``` ksh 'hello world' do code <<-EOH echo "Hello world!" echo "Current directory: " $cwd EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **ksh** resource is: ``` ksh 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `ksh` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **ksh** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. ### Properties --- The **ksh** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. launchd resource ---------------- [launchd resource page](resources/launchd/index) --- Use the **launchd** resource to manage system-wide services (daemons) and per-user services (agents) on the macOS platform. **New in Chef Infra Client 12.8.** ### Syntax --- The full syntax for all of the properties that are available to the **launchd** resource is: ``` launchd 'name' do abandon_process_group true, false backup Integer, false cookbook String debug true, false disabled true, false # default value: false enable_globbing true, false enable_transactions true, false environment_variables Hash exit_timeout Integer group String, Integer hard_resource_limits Hash inetd_compatibility Hash init_groups true, false keep_alive true, false, Hash label String # default value: 'name' unless specified launch_events Hash launch_only_once true, false ld_group String limit_load_from_hosts Array limit_load_to_hosts Array limit_load_to_session_type Array, String low_priority_io true, false mach_services Hash mode String, Integer nice Integer on_demand true, false owner String, Integer path String plist_hash Hash process_type String program String program_arguments Array queue_directories Array root_directory String run_at_load true, false session_type String sockets Hash soft_resource_limits Array source String standard_error_path String standard_in_path String standard_out_path String start_calendar_interval Hash, Array start_interval Integer start_on_mount true, false throttle_interval Integer time_out Integer type String # default value: "daemon" username String wait_for_debugger true, false watch_paths Array working_directory String action Symbol # defaults to :create if not specified end ``` where: * `launchd` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `abandon_process_group`, `backup`, `cookbook`, `debug`, `disabled`, `enable_globbing`, `enable_transactions`, `environment_variables`, `exit_timeout`, `group`, `hard_resource_limits`, `inetd_compatibility`, `init_groups`, `keep_alive`, `label`, `launch_events`, `launch_only_once`, `ld_group`, `limit_load_from_hosts`, `limit_load_to_hosts`, `limit_load_to_session_type`, `low_priority_io`, `mach_services`, `mode`, `nice`, `on_demand`, `owner`, `path`, `plist_hash`, `process_type`, `program`, `program_arguments`, `queue_directories`, `root_directory`, `run_at_load`, `session_type`, `sockets`, `soft_resource_limits`, `source`, `standard_error_path`, `standard_in_path`, `standard_out_path`, `start_calendar_interval`, `start_interval`, `start_on_mount`, `throttle_interval`, `time_out`, `type`, `username`, `wait_for_debugger`, `watch_paths`, and `working_directory` are the properties available to this resource. ### Actions --- The **launchd** resource has the following actions: `:create` Create a launchd property list. (default) `:create_if_missing` Create a launchd property list, if it does not already exist. `:delete` Delete a launchd property list. This will unload a daemon or agent, if loaded. `:disable` Disable a launchd property list. `:enable` Create a launchd property list, and then ensure that it is enabled. If a launchd property list already exists, but does not match, updates the property list to match, and then restarts the daemon or agent. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:restart` Restart a launchd managed daemon or agent. ### Properties --- The **launchd** resource has the following properties: `abandon_process_group` **Ruby Type:** true, false If a job dies, all remaining processes with the same process ID may be kept running. Set to true to kill all remaining processes. `backup` **Ruby Type:** Integer, false The number of backups to be kept in `/var/chef/backup`. Set to `false` to prevent backups from being kept. `cookbook` **Ruby Type:** String The name of the cookbook in which the source files are located. `group` **Ruby Type:** String, Integer When launchd is run as the root user, the group to run the job as. If the `username` property is specified and this property is not, this value is set to the default group for the user. `label` **Ruby Type:** String The unique identifier for the job. `mode` **Ruby Type:** Integer, String | **Default Value:** `'0755'` A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the `name` of the resource block. See “Syntax” section above for more information. `plist_hash` **Ruby Type:** Hash A Hash of key value pairs used to create the launchd property list. `session_type` **Ruby Type:** String The type of launchd plist to be created. Possible values: `system` (default) or `user`. `source` **Ruby Type:** String The path to the launchd property list. `type` **Ruby Type:** String The type of resource. Possible values: `daemon` (default), `agent`. `abandon_process_group` **Ruby Type:** true, false If a job dies, all remaining processes with the same process ID may be kept running. Set to true to kill all remaining processes. `debug` **Ruby Type:** true, false Sets the log mask to `LOG_DEBUG` for this job. `disabled` **Ruby Type:** true, false | **Default Value:** `false` Hints to `launchctl` to not submit this job to launchd. `enable_globbing` **Ruby Type:** true, false Update program arguments before invocation. `enable_transactions` **Ruby Type:** true, false Track in-progress transactions; if none, then send the `SIGKILL` signal. `environment_variables` **Ruby Type:** Hash Additional environment variables to set before running a job. `exit_timeout` **Ruby Type:** Integer The amount of time (in seconds) launchd waits before sending a `SIGKILL` signal. `hard_resource_limits` **Ruby Type:** Hash A Hash of resource limits to be imposed on a job. `inetd_compatibility` **Ruby Type:** Hash Specifies if a daemon expects to be run as if it were launched from inetd. Set to `wait => true` to pass standard input, output, and error file descriptors. Set to `wait => false` to call the accept system call on behalf of the job, and then pass standard input, output, and error file descriptors. `init_groups` **Ruby Type:** true, false Specify if `initgroups` is called before running a job. `keep_alive` **Ruby Type:** true, false, Hash Keep a job running continuously (true) or allow demand and conditions on the node to determine if the job keeps running (`false`). New in Chef Client 12.14 `launch_events` **Ruby Type:** Hash Specify higher-level event types to be used as launch-on-demand event sources. New in Chef Infra Client 15.1 `launch_only_once` **Ruby Type:** true, false Specify if a job can be run only one time. Set this value to true if a job cannot be restarted without a full machine reboot. `limit_load_from_hosts` **Ruby Type:** Array An array of hosts to which this configuration file does not apply, i.e. ‘apply this configuration file to all hosts not specified in this array’. `limit_load_to_hosts` **Ruby Type:** Array An array of hosts to which this configuration file applies. `limit_load_to_session_type` **Ruby Type:** Array, String The session type(s) to which this configuration file applies. `low_priority_io` **Ruby Type:** true, false Specify if the kernel on the node should consider this daemon to be low priority during file system I/O. `mach_services` **Ruby Type:** Hash Specify services to be registered with the bootstrap subsystem. `nice` **Ruby Type:** Integer The program scheduling priority value in the range -20 to 19. `on_demand` **Ruby Type:** true, false Keep a job alive. Only applies to macOS version 10.4 (and earlier); use `keep_alive` instead for newer versions. `process_type` **Ruby Type:** String The intended purpose of the job: `Adaptive`, `Background`, `Interactive`, or `Standard`. `program` **Ruby Type:** String The first argument of `execvp`, typically the file name associated with the file to be executed. This value must be specified if `program_arguments` is not specified, and vice-versa. `program_arguments` **Ruby Type:** Array The second argument of `execvp`. If program is not specified, this property must be specified and will be handled as if it were the first argument. `queue_directories` **Ruby Type:** Array An array of non-empty directories which, if any are modified, will cause a job to be started. `root_directory` **Ruby Type:** String `chroot` to this directory, and then run the job. `run_at_load` **Ruby Type:** true, false Launch a job once (at the time it is loaded). `sockets` **Ruby Type:** Hash A Hash of on-demand sockets that notify launchd when a job should be run. `soft_resource_limits` **Ruby Type:** Array A Hash of resource limits to be imposed on a job. `standard_error_path` **Ruby Type:** String The file to which standard error (`stderr`) is sent. `standard_in_path` **Ruby Type:** String The file to which standard input (`stdin`) is sent. `standard_out_path` **Ruby Type:** String The file to which standard output (`stdout`) is sent. `start_calendar_interval` **Ruby Type:** Hash A Hash (similar to `crontab`) that defines the calendar frequency at which a job is started. For example: `{ Minute => "0", Hour => "20", Day => "*", Weekday => "1-5", Month => "*" }` will run a job at 8:00 PM every day, Monday through Friday, every month of the year. `start_interval` **Ruby Type:** Integer The frequency (in seconds) at which a job is started. `start_on_mount` **Ruby Type:** true, false Start a job every time a file system is mounted. `throttle_interval` **Ruby Type:** Integer | **Default Value:** `10` The frequency (in seconds) at which jobs are allowed to spawn. `time_out` **Ruby Type:** Integer The amount of time (in seconds) a job may be idle before it times out. If no value is specified, the default timeout value for launchd will be used. `username` **Ruby Type:** String When launchd is run as the root user, the user to run the job as. `wait_for_debugger` **Ruby Type:** true, false Specify if launchd has a job wait for a debugger to attach before executing code. `watch_paths` **Ruby Type:** Array An array of paths which, if any are modified, will cause a job to be started. `working_directory` **Ruby Type:** String `chdir` to this directory, and then run the job. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **launchd** resource in recipes: Create a Launch Daemon from a cookbook file ``` launchd 'com.chef.every15' do source 'com.chef.every15.plist' end ``` Create a Launch Daemon using keys ``` launchd 'call.mom.weekly' do program '/Library/scripts/call_mom.sh' start_calendar_interval 'Weekday' => 7, 'Hourly' => 10 time_out 300 end ``` Remove a Launch Daemon ``` launchd 'com.chef.every15' do action :delete end ``` link resource ------------- [link resource page](resources/link/index) --- Use the **link** resource to create symbolic or hard links. A symbolic link—sometimes referred to as a soft link—is a directory entry that associates a file name with a string that contains an absolute or relative path to a file on any file system. In other words, “a file that contains a path that points to another file.” A symbolic link creates a new file with a new inode that points to the inode location of the original file. A hard link is a directory entry that associates a file with another file in the same file system. In other words, “multiple directory entries to the same file.” A hard link creates a new file that points to the same inode as the original file. On Windows, this resource can be used to create directory junction/reparse points. ### Syntax --- A **link** resource block creates symbolic or hard links. For example, to create a hard link from `/tmp/file` to `/etc/file`: ``` link '/tmp/file' do to '/etc/file' link_type :hard end ``` Because the default value for `link_type` is symbolic, and because properties that are not specified in the resource block will be assigned their default values, the following example creates a symbolic link: ``` link '/tmp/file' do to '/etc/file' end ``` The full syntax for all of the properties that are available to the **link** resource is: ``` link 'name' do group String, Integer link_type String, Symbol # default value: :symbolic mode Integer, String owner String, Integer target_file String # default value: 'name' unless specified to String action Symbol # defaults to :create if not specified end ``` where: * `link` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `group`, `link_type`, `mode`, `owner`, `target_file`, and `to` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **link** resource has the following actions: `:create` Default. Create a link. If a link already exists (but does not match), update that link to match. `:delete` Delete a link. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **link** resource has the following properties: `group` **Ruby Type:** String, Integer A group name or ID number that identifies the group associated with a symbolic link. `link_type` **Ruby Type:** String, Symbol | **Default Value:** `:symbolic` **Allowed Values:** `:hard, :symbolic` The type of link: `:symbolic` or `:hard`. On Windows, `:symbolic` will create a junction point if the target is a directory. `mode` **Ruby Type:** Integer, String | **Default Value:** `777` If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** String, Integer The owner associated with a symbolic link. `target_file` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the target file if it differs from the resource block’s name. `to` **Ruby Type:** String The actual file to which the link is to be created. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **link** resource in recipes: Create symbolic links The following example will create a symbolic link from `/tmp/file` to `/etc/file`: ``` link '/tmp/file' do to '/etc/file' end ``` Create hard links The following example will create a hard link from `/tmp/file` to `/etc/file`: ``` link '/tmp/file' do to '/etc/file' link_type :hard end ``` Delete links The following example will delete the `/tmp/file` symbolic link and uses the `only_if` guard to run the `test -L` command, which verifies that `/tmp/file` is a symbolic link, and then only deletes `/tmp/file` if the test passes: ``` link '/tmp/file' do action :delete only_if 'test -L /tmp/file' end ``` Create multiple symbolic links The following example creates symbolic links from two files in the `/vol/webserver/cert/` directory to files located in the `/etc/ssl/certs/` directory: ``` link '/vol/webserver/cert/server.crt' do to '/etc/ssl/certs/ssl-cert-name.pem' end link '/vol/webserver/cert/server.key' do to '/etc/ssl/certs/ssl-cert-name.key' end ``` Create platform-specific symbolic links The following example shows installing a filter module on Apache. The package name is different for different platforms, and for the Red Hat Enterprise Linux family, a symbolic link is required: ``` include_recipe 'apache2::default' case node['platform_family'] when 'debian' ... when 'suse' ... when 'rhel', 'fedora' ... link '/usr/lib64/httpd/modules/mod_apreq.so' do to '/usr/lib64/httpd/modules/mod_apreq2.so' only_if 'test -f /usr/lib64/httpd/modules/mod_apreq2.so' end link '/usr/lib/httpd/modules/mod_apreq.so' do to '/usr/lib/httpd/modules/mod_apreq2.so' only_if 'test -f /usr/lib/httpd/modules/mod_apreq2.so' end end ... ``` For the complete recipe, see <https://github.com/onehealth-cookbooks/apache2/blob/68bdfba4680e70b3e90f77e40223dd535bf22c17/recipes/mod_apreq2.rb>. **Create Windows junction/reparse points** This example demonstrates how to create a directory junction/reparse point. In this example, `C:\destination` will be a junction/reparse point to the `C:\source` directory. ``` directory 'C:/source' link 'C:/destination' do link_type :symbolic to 'C:/source' end ``` locale resource --------------- [locale resource page](resources/locale/index) --- Use the **locale** resource to set the system’s locale on Debian and Windows systems. Windows support was added in Chef Infra Client 16.0 **New in Chef Infra Client 14.5.** ### Syntax --- The full syntax for all of the properties that are available to the **locale** resource is: ``` locale 'name' do lang String lc_env Hash # default value: {} action Symbol # defaults to :update if not specified end ``` where: * `locale` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `lang` and `lc_env` are the properties available to this resource. ### Actions --- The **locale** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:update` Update the system’s locale. (default) ### Properties --- The **locale** resource has the following properties: `lang` **Ruby Type:** String Sets the default system language. `lc_env` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of LC_* env variables in the form of `({ 'LC_ENV_VARIABLE' => 'VALUE' })`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **locale** resource in recipes: Set the lang to ‘en_US.UTF-8’ ``` locale 'set system locale' do lang 'en_US.UTF-8' end ``` log resource ------------ [log resource page](resources/log/index) --- ### Syntax --- A **log** resource block adds messages to the log file based on events that occur during a Chef Infra Client run: ``` log 'message' do message 'A message add to the log.' level :info end ``` The full syntax for all of the properties that are available to the **log** resource is: ``` log 'name' do level Symbol # default value: :info message String # default value: 'name' unless specified action Symbol # defaults to :write if not specified end ``` where: * `log` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `level` and `message` are the properties available to this resource. ### Properties --- The log resource has the following properties: `level` **Ruby Type:** Symbol | **Default Value:** `:info` The logging level for displaying this message. Options (in order of priority): `:debug`, `:info`, `:warn`, `:error`, and `:fatal`. `message` **Ruby Type:** String | **Default Value:** `The resource block's name` The message to be added to a log file. Default value: the `name` of the resource block. See “Syntax” section above for more information. ### Log Entries `Chef::Log` will print log entries to the default logger that is configured for the machine on which Chef Infra Client is running. (To create a log entry that is built into the resource collection, use the [log resource](resources/log/index) instead of `Chef::Log`.) ### Supported Log Levels | Log Level | Syntax | | --- | --- | | Fatal | `Chef::Log.fatal('string')` | | Error | `Chef::Log.error('string')` | | Warn | `Chef::Log.warn('string')` | | Info | `Chef::Log.info('string')` | | Debug | `Chef::Log.debug('string')` | The following example shows a series of fatal `Chef::Log` entries: ``` unless node['splunk']['upgrade_enabled'] Chef::Log.fatal('The chef-splunk::upgrade recipe was added to the node,') Chef::Log.fatal('but the attribute `node["splunk"]["upgrade_enabled"]` was not set.') Chef::Log.fatal('I am bailing here so this node does not upgrade.') raise end service 'splunk_stop' do service_name 'splunk' supports status: true action :stop end if node['splunk']['is_server'] splunk_package = 'splunk' url_type = 'server' else splunk_package = 'splunkforwarder' url_type = 'forwarder' end splunk_installer splunk_package do url node['splunk']['upgrade']["#{url_type}_url"] end if node['splunk']['accept_license'] execute 'splunk-unattended-upgrade' do command "#{splunk_cmd} start --accept-license --answer-yes" end else Chef::Log.fatal('You did not accept the license (set node["splunk"]["accept_license"] to true)') Chef::Log.fatal('Splunk is stopped and cannot be restarted until the license is accepted!') raise end ``` The following example shows using multiple `Chef::Log` entry types: ``` ... begin aws = Chef::DataBagItem.load(:aws, :main) Chef::Log.info("Loaded AWS information from DataBagItem aws[#{aws['id']}]") rescue Chef::Log.fatal("Could not find the 'main' item in the 'aws' data bag") raise end ... ``` ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **log** resource in recipes: Set default logging level ``` log 'a string to log' ``` Set debug logging level ``` log 'a debug string' do level :debug end ``` Add a message to a log file ``` log 'message' do message 'This is the message that will be added to the log.' level :info end ``` macos_userdefaults resource ---------------------------- [macos_userdefaults resource page](resources/macos_userdefaults/index) --- Use the **macos_userdefaults** resource to manage the macOS user defaults system. The properties of this resource are passed to the defaults command, and the parameters follow the convention of that command. See the defaults(1) man page for details on how the tool works. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **macos_userdefaults** resource is: ``` macos_userdefaults 'name' do domain String # default value: NSGlobalDomain: the global domain. host String, Symbol key String user String, Symbol value Integer, Float, String, true, false, Hash, Array action Symbol # defaults to :write if not specified end ``` where: * `macos_userdefaults` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `domain`, `host`, `key`, `user`, and `value` are the properties available to this resource. ### Actions --- The **macos_userdefaults** resource has the following actions: `:delete` Delete a key from a domain. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:write` Write the value to the specified domain/key. (default) ### Properties --- The **macos_userdefaults** resource has the following properties: `domain` **Ruby Type:** String | **Default Value:** `NSGlobalDomain: the global domain.` The domain that the user defaults belong to. `host` **Ruby Type:** String, Symbol Set either :current, :all or a hostname to set the user default at the host level. New in Chef Infra Client 16.3 `key` **Ruby Type:** String | `REQUIRED` The preference key. `user` **Ruby Type:** String, Symbol The system user that the default will be applied to. Set :current for current user, :all for all users or pass a valid username `value` **Ruby Type:** Integer, Float, String, true, false, Hash, Array | `REQUIRED` The value of the key. Note With the `type` property set to `bool`, `String` forms of Boolean true/false values that Apple accepts in the defaults command will be coerced: 0/1, ‘TRUE’/‘FALSE,’ ‘true’/false', ‘YES’/‘NO’, or ‘yes’/‘no’. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macos_userdefaults** resource in recipes: **Specify a global domain value** ``` macos_userdefaults 'Full keyboard access to all controls' do key 'AppleKeyboardUIMode' value 2 end ``` **Setting a value on a specific domain** ``` macos_userdefaults 'Enable macOS firewall' do domain '/Library/Preferences/com.apple.alf' key 'globalstate' value 1 end ``` **Specifying the type of a key to skip automatic type detection** ``` macos_userdefaults 'Finder expanded save dialogs' do key 'NSNavPanelExpandedStateForSaveMode' value 'TRUE' type 'bool' end ``` macports_package resource -------------------------- [macports_package resource page](resources/macports_package/index) --- Use the **macports_package** resource to manage packages for the macOS platform using the MacPorts package management system. ### Syntax --- A **macports_package** resource block manages a package on a node, typically by installing it. The simplest use of the **macports_package** resource is: ``` macports_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **macports_package** resource is: ``` macports_package 'name' do options String package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `macports_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **macports_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **macports_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **macports_package** resource in recipes: Install a package ``` macports_package 'name of package' do action :install end ``` mdadm resource -------------- [mdadm resource page](resources/mdadm/index) --- Use the **mdadm** resource to manage RAID devices in a Linux environment using the mdadm utility. The mdadm resource will create and assemble an array, but it will not create the config file that is used to persist the array upon reboot. If the config file is required, it must be done by specifying a template with the correct array layout, and then by using the mount provider to create a file systems table (fstab) entry. ### Syntax --- The full syntax for all of the properties that are available to the **mdadm** resource is: ``` mdadm 'name' do bitmap String chunk Integer # default value: 16 devices Array # default value: [] layout String level Integer # default value: 1 metadata String # default value: "0.90" raid_device String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `mdadm` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `bitmap`, `chunk`, `devices`, `layout`, `level`, `metadata`, and `raid_device` are the properties available to this resource. ### Actions --- The **mdadm** resource has the following actions: `:assemble` Assemble a previously created array into an active array. `:create` Create an array with per-device superblocks. If an array already exists (but does not match), update that array to match. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:stop` Stop an active array. ### Properties --- The **mdadm** resource has the following properties: `bitmap` **Ruby Type:** String The path to a file in which a write-intent bitmap is stored. `chunk` **Ruby Type:** Integer | **Default Value:** `16` The chunk size. This property should not be used for a RAID 1 mirrored pair (i.e. when the `level` property is set to `1`). `devices` **Ruby Type:** Array | **Default Value:** `[]` The devices to be part of a RAID array. `layout` **Ruby Type:** String The RAID5 parity algorithm. Possible values: `left-asymmetric` (or `la`), `left-symmetric` (or ls), `right-asymmetric` (or `ra`), or `right-symmetric` (or `rs`). `level` **Ruby Type:** Integer | **Default Value:** `1` The RAID level. `metadata` **Ruby Type:** String | **Default Value:** `0.90` The superblock type for RAID metadata. `raid_device` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to specify the name of the RAID device if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **mdadm** resource in recipes: **Create and assemble a RAID 0 array** The mdadm command can be used to create RAID arrays. For example, a RAID 0 array named /dev/md0 with 10 devices would have a command similar to the following: ``` mdadm --create /dev/md0 --level=0 --raid-devices=10 /dev/s01.../dev/s10 ``` where /dev/s01 .. /dev/s10 represents 10 devices (01, 02, 03, and so on). This same command, when expressed as a recipe using the mdadm resource, would be similar to: ``` mdadm '/dev/md0' do devices [ '/dev/s01', ... '/dev/s10' ] level 0 action :create end ``` (again, where /dev/s01 .. /dev/s10 represents devices /dev/s01, /dev/s02, /dev/s03, and so on). **Create and assemble a RAID 1 array** ``` mdadm '/dev/md0' do devices [ '/dev/sda', '/dev/sdb' ] level 1 action [ :create, :assemble ] end ``` **Create and assemble a RAID 5 array** The mdadm command can be used to create RAID arrays. For example, a RAID 5 array named /dev/sd0 with 4, and a superblock type of 0.90 would be similar to: ``` mdadm '/dev/sd0' do devices [ '/dev/s1', '/dev/s2', '/dev/s3', '/dev/s4' ] level 5 metadata '0.90' chunk 32 action :create end ``` mount resource -------------- [mount resource page](resources/mount/index) --- Use the **mount** resource to manage a mounted file system. ### Syntax --- The full syntax for all of the properties that are available to the **mount** resource is: ``` mount 'name' do device String device_type String, Symbol # default value: :device domain String dump Integer, false # default value: 0 enabled true, false # default value: false fsck_device String # default value: "-" fstype String # default value: "auto" mount_point String # default value: 'name' unless specified options Array, String # default value: ["defaults"] pass Integer, false # default value: 2 password String supports Array, Hash # default value: { remount: false } username String action Symbol # defaults to :mount if not specified end ``` where: * `mount` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `device`, `device_type`, `domain`, `dump`, `enabled`, `fsck_device`, `fstype`, `mount_point`, `options`, `pass`, `password`, `supports`, and `username` are the properties available to this resource. ### Actions --- The **mount** resource has the following actions: `:disable` Remove an entry from the file systems table (`fstab`). `:enable` Add an entry to the file systems table (`fstab`). `:mount` Default. Mount a device. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remount` Remount a device. `:umount` Unmount a device. `:unmount` Alias for `:umount` action. ### Properties --- The **mount** resource has the following properties: `device` **Ruby Type:** String Required for `:umount` and `:remount` actions (for the purpose of checking the mount command output for presence). The special block device or remote node, a label, or a uuid to be mounted. `device_type` **Ruby Type:** String, Symbol | **Default Value:** `:device` **Allowed Values:** `:device, :label, :uuid` The type of device: :device, :label, or :uuid `domain` **Ruby Type:** String Windows only: Use to specify the domain in which the `username` and `password` are located. `dump` **Ruby Type:** Integer, false | **Default Value:** `0` The dump frequency (in days) used while creating a file systems table (fstab) entry. `enabled` **Ruby Type:** true, false | **Default Value:** `false` Use to specify if a mounted file system is enabled. `fsck_device` **Ruby Type:** String | **Default Value:** `-` Solaris only: The fsck device. `fstype` **Ruby Type:** String | **Default Value:** `auto` The file system type (fstype) of the device. `mount_point` **Ruby Type:** String | **Default Value:** `The resource block's name` The directory (or path) in which the device is to be mounted. Defaults to the name of the resource block if not provided. `options` **Ruby Type:** Array, String | **Default Value:** `["defaults"]` An array or comma separated list of options for the mount. `pass` **Ruby Type:** Integer, false | **Default Value:** `2` The pass number used by the file system check (fsck) command while creating a file systems table (fstab) entry. `password` **Ruby Type:** String Windows only:. Use to specify the password for username. `supports` **Ruby Type:** Array, Hash | **Default Value:** `{ remount: false }` Specify a Hash of supported mount features. `username` **Ruby Type:** String Windows only: Use to specify the user name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **mount** resource in recipes: Mount a labeled file system ``` mount '/mnt/volume1' do device 'volume1' device_type :label fstype 'xfs' options 'rw' end ``` Mount a local block drive ``` mount '/mnt/local' do device '/dev/sdb1' fstype 'ext3' end ``` Mount a non-block file system ``` mount '/mount/tmp' do pass 0 fstype 'tmpfs' device '/dev/null' options 'nr_inodes=999k,mode=755,size=500m' action [:mount, :enable] end ``` Mount and add to the file systems table ``` mount '/export/www' do device 'nas1prod:/export/web_sites' fstype 'nfs' options 'rw' action [:mount, :enable] end ``` Mount a remote file system ``` mount '/export/www' do device 'nas1prod:/export/web_sites' fstype 'nfs' options 'rw' end ``` Mount a remote folder in Microsoft Windows ``` mount 'T:' do action :mount device '\\\\hostname.example.com\\folder' end ``` Unmount a remote folder in Microsoft Windows ``` mount 'T:' do action :umount device '\\\\hostname.example.com\\D$' end ``` Stop a service, do stuff, and then restart it The following example shows how to use the **execute**, **service**, and **mount** resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following: * Checks to see if the Amazon EC2 node has MySQL * If the node has MySQL, stops MySQL * Installs MySQL * Mounts the node * Restarts MySQL ``` # the following code sample comes from the ``server_ec2`` # recipe in the following cookbook: # https://github.com/chef-cookbooks/mysql if (node.attribute?('ec2') && ! FileTest.directory?(node['mysql']['ec2_path'])) service 'mysql' do action :stop end execute 'install-mysql' do command "mv #{node['mysql']['data_dir']}#{node['mysql']['ec2_path']}" not_if do FileTest.directory?(node['mysql']['ec2_path']) end end [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir| directory dir do owner 'mysql' group 'mysql' end end mount node['mysql']['data_dir'] do device node['mysql']['ec2_path'] fstype 'none' options 'bind,rw' action [:mount, :enable] end service 'mysql' do action :start end end ``` where * the two **service** resources are used to stop, and then restart the MySQL service * the **execute** resource is used to install MySQL * the **mount** resource is used to mount the node and enable MySQL msu_package resource --------------------- [msu_package resource page](resources/msu_package/index) --- Use the **msu_package** resource to install Microsoft Update(MSU) packages on Microsoft Windows machines. **New in Chef Infra Client 12.17.** ### Syntax --- The full syntax for all of the properties that are available to the **msu_package** resource is: ``` msu_package 'name' do checksum String options String package_name String source String timeout String, Integer # default value: 3600 action Symbol # defaults to :install if not specified end ``` where: * `msu_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `checksum`, `options`, `package_name`, `source`, and `timeout` are the properties available to this resource. ### Actions --- The **msu_package** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **msu_package** resource has the following properties: `checksum` **Ruby Type:** String SHA-256 digest used to verify the checksum of the downloaded MSU package. `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The local file path or URL for the MSU package. `timeout` **Ruby Type:** String, Integer | **Default Value:** `3600` The amount of time (in seconds) to wait before timing out. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **msu_package** resource in recipes: Using local path in source ``` msu_package 'Install Windows 2012R2 Update KB2959977' do source 'C:\Users\xyz\AppData\Local\Temp\Windows8.1-KB2959977-x64.msu' action :install end ``` ``` msu_package 'Remove Windows 2012R2 Update KB2959977' do source 'C:\Users\xyz\AppData\Local\Temp\Windows8.1-KB2959977-x64.msu' action :remove end ``` Using URL in source ``` msu_package 'Install Windows 2012R2 Update KB2959977' do source 'https://s3.amazonaws.com/my_bucket/Windows8.1-KB2959977-x64.msu' action :install end ``` ``` msu_package 'Remove Windows 2012R2 Update KB2959977' do source 'https://s3.amazonaws.com/my_bucket/Windows8.1-KB2959977-x64.msu' action :remove end ``` notify_group resource ---------------------- [notify_group resource page](resources/notify_group/index) --- The notify_group resource does nothing, and always fires notifications which are set on it. Use it to DRY blocks of notifications that are common to multiple resources, and provide a single target for other resources to notify. Unlike most resources, its default action is :nothing. **New in Chef Infra Client 15.8.** ### Syntax --- The full syntax for all of the properties that are available to the **notify_group** resource is: ``` notify_group 'name' do action Symbol # defaults to :nothing if not specified end ``` where: * `notify_group` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. ### Actions --- The **notify_group** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` ### Properties --- This resource does not have any properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **notify_group** resource in recipes: Wire up a notification from a service resource to stop and start the service with a 60 second delay. ``` service "crude" do action [ :enable, :start ] end chef_sleep "60" do action :nothing end # Example code for a hypothetical badly behaved service that requires # 60 seconds between a stop and start in order to restart the service # (due to race conditions, bleeding connections down, resources that only # slowly unlock in the background, or other poor software behaviors that # are sometimes encountered). # notify_group "crude_stop_and_start" do notifies :stop, "service[crude]", :immediately notifies :sleep, "chef_sleep[60]", :immediately notifies :start, "service[crude]", :immediately end template "/etc/crude/crude.conf" do source "crude.conf.erb" variables node["crude"] notifies :run, "notify_group[crude_stop_and_start]", :immediately end ``` ohai resource ------------- [ohai resource page](resources/ohai/index) --- Use the **ohai** resource to reload the Ohai configuration on a node. This allows recipes that change system attributes (like a recipe that adds a user) to refer to those attributes later on during the Chef Infra Client run. ### Syntax --- The full syntax for all of the properties that are available to the **ohai** resource is: ``` ohai 'name' do plugin String action Symbol # defaults to :reload if not specified end ``` where: * `ohai` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `plugin` is the property available to this resource. ### Actions --- The **ohai** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reload` Reloads the Ohai data. (default) ### Properties --- The **ohai** resource has the following properties: `plugin` **Ruby Type:** String Specific Ohai attribute data to reload. This property behaves similar to specifying attributes when running Ohai on the command line and takes the attribute that you wish to reload instead of the actual plugin name. For instance, you can pass `ipaddress` to reload `node['ipaddress']` even though that data comes from the `Network` plugin. If this property is not specified, Chef Infra Client will reload all plugins. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **ohai** resource in recipes: Reload All Ohai Plugins ``` ohai 'reload' do action :reload end ``` Reload A Single Ohai Plugin ``` ohai 'reload' do plugin 'ipaddress' action :reload end ``` Reload Ohai after a new user is created ``` ohai 'reload_passwd' do action :nothing plugin 'etc' end user 'daemon_user' do home '/dev/null' shell '/sbin/nologin' system true notifies :reload, 'ohai[reload_passwd]', :immediately end ruby_block 'just an example' do block do # These variables will now have the new values puts node['etc']['passwd']['daemon_user']['uid'] puts node['etc']['passwd']['daemon_user']['gid'] end end ``` ohai_hint resource ------------------- [ohai_hint resource page](resources/ohai_hint/index) --- Use the **ohai_hint** resource to aid in configuration detection by passing hint data to Ohai. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **ohai_hint** resource is: ``` ohai_hint 'name' do compile_time true, false # default value: true content Hash hint_name String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `ohai_hint` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `compile_time`, `content`, and `hint_name` are the properties available to this resource. ### Actions --- The **ohai_hint** resource has the following actions: `:create` Create an Ohai hint file. (default) `:delete` Delete an Ohai hint file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **ohai_hint** resource has the following properties: `compile_time` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the resource is executed during the compile time phase. `content` **Ruby Type:** Hash Values to include in the hint file. `hint_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the hint name if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **ohai_hint** resource in recipes: **Create a hint file** ``` ohai_hint 'example' do content a: 'test_content' end ``` **Create a hint file with a name that does not match the resource name** ``` ohai_hint 'example' do hint_name 'custom' end ``` **Create a hint file that is not loaded at compile time** ``` ohai_hint 'example' do compile_time false end ``` **Delete a hint file** ``` ohai_hint 'example' do action :delete end ``` openbsd_package resource ------------------------- [openbsd_package resource page](resources/openbsd_package/index) --- Use the **openbsd_package** resource to manage packages for the OpenBSD platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **openbsd_package** resource block manages a package on a node, typically by installing it. The simplest use of the **openbsd_package** resource is: ``` openbsd_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **openbsd_package** resource is: ``` openbsd_package 'name' do options String package_name String source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `openbsd_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **openbsd_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. ### Properties --- The **openbsd_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openbsd_package** resource in recipes: **Install a package** ``` openbsd_package 'name of package' do action :install end ``` **Remove a package** ``` openbsd_package 'name of package' do action :remove end ``` openssl_dhparam resource ------------------------- [openssl_dhparam resource page](resources/openssl_dhparam/index) --- Use the **openssl_dhparam** resource to generate `dhparam.pem` files. If a valid `dhparam.pem` file is found at the specified location, no new file will be created. If a file is found at the specified location but it is not a valid `dhparam.pem` file, it will be overwritten. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_dhparam** resource is: ``` openssl_dhparam 'name' do generator Integer # default value: 2 group String, Integer key_length Integer # default value: 2048 mode Integer, String # default value: "0640" owner String, Integer path String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `openssl_dhparam` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `generator`, `group`, `key_length`, `mode`, `owner`, and `path` are the properties available to this resource. ### Actions --- The **openssl_dhparam** resource has the following actions: `:create` Create the `dhparam.pem` file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_dhparam** resource has the following properties: `generator` **Ruby Type:** Integer | **Default Value:** `2` **Allowed Values:** `2, 5` The desired Diffie-Hellmann generator. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key. `mode` **Ruby Type:** Integer, String | **Default Value:** `0640` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_dhparam** resource in recipes: **Create a dhparam file** ``` openssl_dhparam '/etc/httpd/ssl/dhparam.pem' ``` **Create a dhparam file with a specific key length** ``` openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do key_length 4096 end ``` **Create a dhparam file with specific user/group ownership** ``` openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do owner 'www-data' group 'www-data' end ``` **Manually specify the dhparam file path** ``` openssl_dhparam 'httpd_dhparam' do path '/etc/httpd/ssl/dhparam.pem' end ``` openssl_ec_private_key resource ---------------------------------- [openssl_ec_private_key resource page](resources/openssl_ec_private_key/index) --- Use the **openssl_ec_private_key** resource to generate an elliptic curve (EC) private key file. If a valid EC key file can be opened at the specified location, no new file will be created. If the EC key file cannot be opened, either because it does not exist or because the password to the EC key file does not match the password in the recipe, then it will be overwritten. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_ec_private_key** resource is: ``` openssl_ec_private_key 'name' do force true, false # default value: false group String, Integer key_cipher String # default value: "des3" key_curve String # default value: "prime256v1" key_pass String mode Integer, String # default value: "0600" owner String, Integer path String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `openssl_ec_private_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `force`, `group`, `key_cipher`, `key_curve`, `key_pass`, `mode`, `owner`, and `path` are the properties available to this resource. ### Actions --- The **openssl_ec_private_key** resource has the following actions: `:create` Generate the EC private key file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_ec_private_key** resource has the following properties: `force` **Ruby Type:** true, false | **Default Value:** `false` Force creation of the key even if the same key already exists on the node. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_cipher` **Ruby Type:** String | **Default Value:** `des3` The designed cipher to use when generating your key. Run `openssl list-cipher-algorithms` to see available options. `key_curve` **Ruby Type:** String | **Default Value:** `prime256v1` **Allowed Values:** `"prime256v1", "secp224r1", "secp256k1", "secp384r1", "secp521r1"` The desired curve of the generated key (if key_type is equal to ‘ec’). Run openssl ecparam -list_curves to see available options. `key_pass` **Ruby Type:** String The desired passphrase for the key. `mode` **Ruby Type:** Integer, String | **Default Value:** `0600` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_ec_private_key** resource in recipes: **Generate a new ec privatekey with prime256v1 key curve and default des3 cipher** ``` openssl_ec_private_key '/etc/ssl_files/eckey_prime256v1_des3.pem' do key_curve 'prime256v1' key_pass 'something' action :create end ``` **Generate a new ec private key with prime256v1 key curve and aes-128-cbc cipher** ``` openssl_ec_private_key '/etc/ssl_files/eckey_prime256v1_des3.pem' do key_curve 'prime256v1' key_cipher '<KEY>' key_pass 'something' action :create end ``` openssl_ec_public_key resource --------------------------------- [openssl_ec_public_key resource page](resources/openssl_ec_public_key/index) --- Use the **openssl_ec_public_key** resource to generate elliptic curve (EC) public key files from a given EC private key. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_ec_public_key** resource is: ``` openssl_ec_public_key 'name' do group String, Integer mode Integer, String # default value: "0640" owner String, Integer path String # default value: 'name' unless specified private_key_content String private_key_pass String private_key_path String action Symbol # defaults to :create if not specified end ``` where: * `openssl_ec_public_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `group`, `mode`, `owner`, `path`, `private_key_content`, `private_key_pass`, and `private_key_path` are the properties available to this resource. ### Actions --- The **openssl_ec_public_key** resource has the following actions: `:create` Generate the EC public key file from a private key. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_ec_public_key** resource has the following properties: `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `mode` **Ruby Type:** Integer, String | **Default Value:** `0640` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `private_key_content` **Ruby Type:** String The content of the private key including new lines. This property is used in place of private_key_path in instances where you want to avoid having to first write the private key to disk `private_key_pass` **Ruby Type:** String The passphrase of the provided private key. `private_key_path` **Ruby Type:** String The path to the private key file. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_ec_public_key** resource in recipes: **Generate new EC public key from a private key on disk** ``` openssl_ec_public_key '/etc/ssl_files/eckey_prime256v1_des3.pub' do private_key_path '/etc/ssl_files/eckey_prime256v1_des3.pem' private_key_pass 'something' action :create end ``` **Generate new EC public key by passing in a private key** ``` openssl_ec_public_key '/etc/ssl_files/eckey_prime256v1_des3_2.pub' do private_key_content "-----BEGIN EC PRIVATE KEY----- <KEY> " action :create end ``` openssl_rsa_private_key resource ----------------------------------- [openssl_rsa_private_key resource page](resources/openssl_rsa_private_key/index) --- Use the **openssl_rsa_private_key** resource to generate RSA private key files. If a valid RSA key file can be opened at the specified location, no new file will be created. If the RSA key file cannot be opened, either because it does not exist or because the password to the RSA key file does not match the password in the recipe, it will be overwritten. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_rsa_private_key** resource is: ``` openssl_rsa_private_key 'name' do force true, false # default value: false group String, Integer key_cipher String # default value: "des3" key_length Integer # default value: 2048 key_pass String mode Integer, String # default value: "0600" owner String, Integer path String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `openssl_rsa_private_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `force`, `group`, `key_cipher`, `key_length`, `key_pass`, `mode`, `owner`, and `path` are the properties available to this resource. ### Actions --- The **openssl_rsa_private_key** resource has the following actions: `:create` Create the RSA private key file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_rsa_private_key** resource has the following properties: `force` **Ruby Type:** true, false | **Default Value:** `false` Force creation of the key even if the same key already exists on the node. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_cipher` **Ruby Type:** String | **Default Value:** `des3` The designed cipher to use when generating your key. Run `openssl list-cipher-algorithms` to see available options. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key. `key_pass` **Ruby Type:** String The desired passphrase for the key. `mode` **Ruby Type:** Integer, String | **Default Value:** `0600` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_rsa_private_key** resource in recipes: Generate new 2048bit key with the default des3 cipher ``` openssl_rsa_private_key '/etc/ssl_files/rsakey_des3.pem' do key_length 2048 action :create end ``` Generate new 1024bit key with the aes-128-cbc cipher ``` openssl_rsa_private_key '/etc/ssl_files/rsakey_aes128cbc.pem' do key_length 1024 key_cipher 'aes-128-cbc' action :create end ``` openssl_rsa_public_key resource ---------------------------------- [openssl_rsa_public_key resource page](resources/openssl_rsa_public_key/index) --- Use the **openssl_rsa_public_key** resource to generate RSA public key files for a given RSA private key. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_rsa_public_key** resource is: ``` openssl_rsa_public_key 'name' do group String, Integer mode Integer, String # default value: "0640" owner String, Integer path String # default value: 'name' unless specified private_key_content String private_key_pass String private_key_path String action Symbol # defaults to :create if not specified end ``` where: * `openssl_rsa_public_key` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `group`, `mode`, `owner`, `path`, `private_key_content`, `private_key_pass`, and `private_key_path` are the properties available to this resource. ### Actions --- The **openssl_rsa_public_key** resource has the following actions: `:create` Create the RSA public key file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_rsa_public_key** resource has the following properties: `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `mode` **Ruby Type:** Integer, String | **Default Value:** `0640` The permission mode applied to all files created by the resource. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to the public key if it differs from the resource block’s name. `private_key_content` **Ruby Type:** String The content of the private key, including new lines. This property is used in place of private_key_path in instances where you want to avoid having to first write the private key to disk. `private_key_pass` **Ruby Type:** String The passphrase of the provided private key. `private_key_path` **Ruby Type:** String The path to the private key file. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_rsa_public_key** resource in recipes: Generate new public key from a private key on disk ``` openssl_rsa_public_key '/etc/ssl_files/rsakey_des3.pub' do private_key_path '/etc/ssl_files/rsakey_des3.pem' private_key_pass 'something' action :create end ``` Generate new public key by passing in a private key ``` openssl_rsa_public_key '/etc/ssl_files/rsakey_2.pub' do private_key_pass 'something' private_key_content "-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,5EE0AE9A5FE3342E <KEY> " action :create end ``` openssl_x509_certificate resource ----------------------------------- [openssl_x509_certificate resource page](resources/openssl_x509_certificate/index) --- Use the **openssl_x509_certificate** resource to generate signed or self-signed, PEM-formatted x509 certificates. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate. If a CA private key and certificate are provided, the certificate will be signed with them. Note This resource was renamed from openssl_x509 to openssl_x509_certificate. The legacy name will continue to function, but cookbook code should be updated for the new resource name. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_x509_certificate** resource is: ``` openssl_x509_certificate 'name' do ca_cert_file String ca_key_file String ca_key_pass String city String common_name String country String csr_file String email String expire Integer # default value: 365 extensions Hash # default value: {} group String, Integer key_curve String # default value: "prime256v1" key_file String key_length Integer # default value: 2048 key_pass String key_type String # default value: "rsa" mode Integer, String org String org_unit String owner String, Integer path String # default value: 'name' unless specified renew_before_expiry Integer state String subject_alt_name Array # default value: [] action Symbol # defaults to :create if not specified end ``` where: * `openssl_x509_certificate` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ca_cert_file`, `ca_key_file`, `ca_key_pass`, `city`, `common_name`, `country`, `csr_file`, `email`, `expire`, `extensions`, `group`, `key_curve`, `key_file`, `key_length`, `key_pass`, `key_type`, `mode`, `org`, `org_unit`, `owner`, `path`, `renew_before_expiry`, `state`, and `subject_alt_name` are the properties available to this resource. ### Actions --- The **openssl_x509_certificate** resource has the following actions: `:create` Generate a certificate file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_x509_certificate** resource has the following properties: `ca_cert_file` **Ruby Type:** String The path to the CA X509 Certificate on the filesystem. If the `ca_cert_file` property is specified, the `ca_key_file` property must also be specified, the certificate will be signed with them. `ca_key_file` **Ruby Type:** String The path to the CA private key on the filesystem. If the `ca_key_file` property is specified, the `ca_cert_file` property must also be specified, the certificate will be signed with them. `ca_key_pass` **Ruby Type:** String The passphrase for CA private key’s passphrase. `city` **Ruby Type:** String Value for the `L` certificate field. `common_name` **Ruby Type:** String Value for the `CN` certificate field. `country` **Ruby Type:** String Value for the `C` certificate field. `csr_file` **Ruby Type:** String The path to a X509 Certificate Request (CSR) on the filesystem. If the `csr_file` property is specified, the resource will attempt to source a CSR from this location. If no CSR file is found, the resource will generate a Self-Signed Certificate and the certificate fields must be specified (common_name at last). `email` **Ruby Type:** String Value for the `email` certificate field. `expire` **Ruby Type:** Integer | **Default Value:** `365` Value representing the number of days from now through which the issued certificate cert will remain valid. The certificate will expire after this period. `extensions` **Ruby Type:** Hash | **Default Value:** `{}` Hash of X509 Extensions entries, in format `{ 'keyUsage' => { 'values' => %w( keyEncipherment digitalSignature), 'critical' => true } }`. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_curve` **Ruby Type:** String | **Default Value:** `prime256v1` **Allowed Values:** `"prime256v1", "secp384r1", "secp521r1"` The desired curve of the generated key (if key_type is equal to ‘ec’). Run `openssl ecparam -list_curves` to see available options. `key_file` **Ruby Type:** String The path to a certificate key file on the filesystem. If the key_file property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the key_file property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key (if key_type is equal to ‘rsa’). `key_pass` **Ruby Type:** String The passphrase for an existing key’s passphrase. `key_type` **Ruby Type:** String | **Default Value:** `rsa` **Allowed Values:** `"ec", "rsa"` The desired type of the generated key. `mode` **Ruby Type:** Integer, String The permission mode applied to all files created by the resource. `org` **Ruby Type:** String Value for the `O` certificate field. `org_unit` **Ruby Type:** String Value for the `OU` certificate field. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `renew_before_expiry` **Ruby Type:** Integer The number of days before the expiry. The certificate will be automatically renewed when the value is reached. New in Chef Infra Client 15.7 `state` **Ruby Type:** String Value for the `ST` certificate field. `subject_alt_name` **Ruby Type:** Array | **Default Value:** `[]` Array of Subject Alternative Name entries, in format `DNS:example.com` or `IP:1.2.3.4`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_x509_certificate** resource in recipes: Create a simple self-signed certificate file ``` openssl_x509_certificate '/etc/httpd/ssl/mycert.pem' do common_name 'www.f00bar.com' org 'Foo Bar' org_unit 'Lab' country 'US' end ``` Create a certificate using additional options ``` openssl_x509_certificate '/etc/ssl_files/my_signed_cert.crt' do common_name 'www.<EMAIL>' ca_key_file '/etc/ssl_files/my_ca.key' ca_cert_file '/etc/ssl_files/my_ca.crt' expire 365 extensions( 'keyUsage' => { 'values' => %w( keyEncipherment digitalSignature), 'critical' => true, }, 'extendedKeyUsage' => { 'values' => %w(serverAuth), 'critical' => false, } ) subject_alt_name ['IP:127.0.0.1', 'DNS:localhost.localdomain'] end ``` openssl_x509_crl resource --------------------------- [openssl_x509_crl resource page](resources/openssl_x509_crl/index) --- Use the **openssl_x509_crl** resource to generate PEM-formatted x509 certificate revocation list (CRL) files. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_x509_crl** resource is: ``` openssl_x509_crl 'name' do ca_cert_file String ca_key_file String ca_key_pass String expire Integer # default value: 8 group String, Integer mode Integer, String owner String, Integer path String # default value: 'name' unless specified renewal_threshold Integer # default value: 1 revocation_reason Integer # default value: 0 serial_to_revoke Integer, String action Symbol # defaults to :create if not specified end ``` where: * `openssl_x509_crl` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ca_cert_file`, `ca_key_file`, `ca_key_pass`, `expire`, `group`, `mode`, `owner`, `path`, `renewal_threshold`, `revocation_reason`, and `serial_to_revoke` are the properties available to this resource. ### Actions --- The **openssl_x509_crl** resource has the following actions: `:create` Create the certificate revocation list (CRL) file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_x509_crl** resource has the following properties: `ca_cert_file` **Ruby Type:** String | `REQUIRED` The path to the CA X509 Certificate on the filesystem. If the `ca_cert_file` property is specified, the `ca_key_file` property must also be specified, the CRL will be signed with them. `ca_key_file` **Ruby Type:** String | `REQUIRED` The path to the CA private key on the filesystem. If the `ca_key_file` property is specified, the `ca_cert_file` property must also be specified, the CRL will be signed with them. `ca_key_pass` **Ruby Type:** String The passphrase for CA private key’s passphrase. `expire` **Ruby Type:** Integer | **Default Value:** `8` Value representing the number of days from now through which the issued CRL will remain valid. The CRL will expire after this period. `group` **Ruby Type:** String, Integer The group permission for the CRL file. `mode` **Ruby Type:** Integer, String The permission mode of the CRL file. `owner` **Ruby Type:** String, Integer The owner permission for the CRL file. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `renewal_threshold` **Ruby Type:** Integer | **Default Value:** `1` Number of days before the expiration. It this threshold is reached, the CRL will be renewed. `revocation_reason` **Ruby Type:** Integer | **Default Value:** `0` Reason for the revocation. `serial_to_revoke` **Ruby Type:** Integer, String Serial of the X509 Certificate to revoke. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_x509_crl** resource in recipes: **Create a certificate revocation file** ``` openssl_x509_crl '/etc/ssl_test/my_ca.crl' do ca_cert_file '/etc/ssl_test/my_ca.crt' ca_key_file '/etc/ssl_test/my_ca.key' end ``` **Create a certificate revocation file for a particular serial** ``` openssl_x509_crl '/etc/ssl_test/my_ca.crl' do ca_cert_file '/etc/ssl_test/my_ca.crt' ca_key_file '/etc/ssl_test/my_ca.key' serial_to_revoke C7BCB6602A2E4251EF4E2827A228CB52BC0CEA2F end ``` openssl_x509_request resource ------------------------------- [openssl_x509_request resource page](resources/openssl_x509_request/index) --- Use the **openssl_x509_request** resource to generate PEM-formatted x509 certificates requests. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate. **New in Chef Infra Client 14.4.** ### Syntax --- The full syntax for all of the properties that are available to the **openssl_x509_request** resource is: ``` openssl_x509_request 'name' do city String common_name String country String email String group String, Integer key_curve String # default value: "prime256v1" key_file String key_length Integer # default value: 2048 key_pass String key_type String # default value: "ec" mode Integer, String org String org_unit String owner String, Integer path String # default value: 'name' unless specified state String action Symbol # defaults to :create if not specified end ``` where: * `openssl_x509_request` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `city`, `common_name`, `country`, `email`, `group`, `key_curve`, `key_file`, `key_length`, `key_pass`, `key_type`, `mode`, `org`, `org_unit`, `owner`, `path`, and `state` are the properties available to this resource. ### Actions --- The **openssl_x509_request** resource has the following actions: `:create` Generate a certificate request file. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **openssl_x509_request** resource has the following properties: `city` **Ruby Type:** String Value for the `L` certificate field. `common_name` **Ruby Type:** String | `REQUIRED` Value for the `CN` certificate field. `country` **Ruby Type:** String Value for the `C` certificate field. `email` **Ruby Type:** String Value for the `email` certificate field. `group` **Ruby Type:** String, Integer The group ownership applied to all files created by the resource. `key_curve` **Ruby Type:** String | **Default Value:** `prime256v1` **Allowed Values:** `"prime256v1", "secp384r1", "secp521r1"` The desired curve of the generated key (if key_type is equal to `ec`). Run `openssl ecparam -list_curves` to see available options. `key_file` **Ruby Type:** String The path to a certificate key file on the filesystem. If the `key_file` property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the `key_file` property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate. `key_length` **Ruby Type:** Integer | **Default Value:** `2048` **Allowed Values:** `1024, 2048, 4096, 8192` The desired bit length of the generated key (if key_type is equal to `rsa`). `key_pass` **Ruby Type:** String The passphrase for an existing key’s passphrase. `key_type` **Ruby Type:** String | **Default Value:** `ec` **Allowed Values:** `"ec", "rsa"` The desired type of the generated key. `mode` **Ruby Type:** Integer, String The permission mode applied to all files created by the resource. `org` **Ruby Type:** String Value for the `O` certificate field. `org_unit` **Ruby Type:** String Value for the `OU` certificate field. `owner` **Ruby Type:** String, Integer The owner applied to all files created by the resource. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the path to write the file to if it differs from the resource block’s name. `state` **Ruby Type:** String Value for the `ST` certificate field. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **openssl_x509_request** resource in recipes: **Generate new EC key and CSR file** ``` openssl_x509_request '/etc/ssl_files/my_ec_request.csr' do common_name 'myecrequest.example.com' org 'Test Kitchen Example' org_unit 'Kitchens' country 'UK' end ``` **Generate a new CSR file from an existing EC key** ``` openssl_x509_request '/etc/ssl_files/my_ec_request2.csr' do common_name 'myecrequest2.example.com' org 'Test Kitchen Example' org_unit 'Kitchens' country 'UK' key_file '/etc/ssl_files/my_ec_request.key' end ``` **Generate new RSA key and CSR file** ``` openssl_x509_request '/etc/ssl_files/my_rsa_request.csr' do common_name 'myrsarequest.example.com' org 'Test Kitchen Example' org_unit 'Kitchens' country 'UK' key_type 'rsa' end ``` osx_profile resource --------------------- [osx_profile resource page](resources/osx_profile/index) --- Use the **osx_profile** resource to manage configuration profiles (`.mobileconfig` files) on the macOS platform. The **osx_profile** resource installs profiles by using the uuidgen library to generate a unique `ProfileUUID`, and then using the `profiles` command to install the profile on the system. **New in Chef Infra Client 12.7.** ### Syntax --- The full syntax for all of the properties that are available to the **osx_profile** resource is: ``` osx_profile 'name' do identifier String profile String, Hash profile_name String # default value: 'name' unless specified action Symbol # defaults to :install if not specified end ``` where: * `osx_profile` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `identifier`, `profile`, and `profile_name` are the properties available to this resource. ### Actions --- The **osx_profile** resource has the following actions: `:install` Install the specified configuration profile. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove the specified configuration profile. ### Properties --- The **osx_profile** resource has the following properties: `identifier` **Ruby Type:** String Use to specify the identifier for the profile, such as `com.company.screensaver`. `profile` **Ruby Type:** String, Hash Use to specify a profile. This may be the name of a profile contained in a cookbook or a Hash that contains the contents of the profile. `profile_name` **Ruby Type:** String | **Default Value:** `The resource block's name` Use to specify the name of the profile, if different from the name of the resource block. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **osx_profile** resource in recipes: **Install a profile from a cookbook file** ``` osx_profile 'com.company.screensaver.mobileconfig' ``` **Install profile from a hash** ``` profile_hash = { 'PayloadIdentifier' => 'com.company.screensaver', 'PayloadRemovalDisallowed' => false, 'PayloadScope' => 'System', 'PayloadType' => 'Configuration', 'PayloadUUID' => '1781fbec-3325-565f-9022-8aa28135c3cc', 'PayloadOrganization' => 'Chef', 'PayloadVersion' => 1, 'PayloadDisplayName' => 'Screensaver Settings', 'PayloadContent' => [ { 'PayloadType' => 'com.apple.ManagedClient.preferences', 'PayloadVersion' => 1, 'PayloadIdentifier' => 'com.company.screensaver', 'PayloadUUID' => '73fc30e0-1e57-0131-c32d-000c2944c108', 'PayloadEnabled' => true, 'PayloadDisplayName' => 'com.apple.screensaver', 'PayloadContent' => { 'com.apple.screensaver' => { 'Forced' => [ { 'mcx_preference_settings' => { 'idleTime' => 0, }, }, ], }, }, }, ], } osx_profile 'Install screensaver profile' do profile profile_hash end ``` **Remove profile using identifier in resource name** ``` osx_profile 'com.company.screensaver' do action :remove end ``` **Remove profile by identifier and user friendly resource name** ``` osx_profile 'Remove screensaver profile' do identifier 'com.company.screensaver' action :remove end ``` package resource ---------------- [package resource page](resources/package/index) --- Use the **package** resource to manage packages. When the package is installed from a local file (such as with RubyGems, dpkg, or RPM Package Manager), the file must be added to the node using the **remote_file** or **cookbook_file** resources. This resource is the base resource for several other resources used for package management on specific platforms. While it is possible to use each of these specific resources, it is recommended to use the **package** resource as often as possible. For more information about specific resources for specific platforms, see the following topics: * [apt_package](resources/apt_package/index) * [bff_package](resources/bff_package/index) * [cab_package](resources/cab_package/index) * [chef_gem](resources/chef_gem/index) * [chocolatey_package](resources/chocolatey_package/index) * [dmg_package](resources/dmg_package/index) * [dnf_package](resources/dnf_package/index) * [dpkg_package](resources/dpkg_package/index) * [freebsd_package](resources/freebsd_package/index) * [gem_package](resources/gem_package/index) * [homebrew_package](resources/homebrew_package/index) * [ips_package](resources/ips_package/index) * [macports_package](resources/macports_package/index) * [msu_package](resources/msu_package/index) * [openbsd_package](resources/openbsd_package/index) * [pacman_package](resources/pacman_package/index) * [paludis_package](resources/paludis_package/index) * [portage_package](resources/portage_package/index) * [rpm_package](resources/rpm_package/index) * [smartos_package](resources/smartos_package/index) * [snap_package](resources/snap_package/index) * [solaris_package](resources/solaris_package/index) * [windows_package](resources/windows_package/index) * [yum_package](resources/yum_package/index) * [zypper_package](resources/zypper_package/index) ### Syntax --- A **package** resource block manages a package on a node, typically by installing it. The simplest use of the **package** resource is: ``` package 'httpd' ``` which will install Apache using all of the default options and the default action (`:install`). For a package that has different package names, depending on the platform, use a `case` statement within the **package**: ``` package 'Install Apache' do case node[:platform] when 'redhat', 'centos' package_name 'httpd' when 'ubuntu', 'debian' package_name 'apache2' end end ``` where: * `'redhat', 'centos'` will install Apache using the `httpd` package and `'ubuntu', 'debian'` will install it using the `apache2` package The full syntax for all of the properties that are available to the **package** resource is: ``` package 'name' do allow_downgrade true, false # Yum, RPM packages only arch String, Array # Yum packages only default_release String # Apt packages only flush_cache Array gem_binary String homebrew_user String, Integer # Homebrew packages only notifies # see description options String package_name String, Array # defaults to 'name' if not specified response_file String # Apt packages only response_file_variables Hash # Apt packages only source String subscribes # see description timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `package` tells Chef Infra Client to manage a package; Chef Infra Client will determine the correct package provider to use based on the platform running on the node * `'name'` is the name of the package * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state * `allow_downgrade`, `arch`, `default_release`, `flush_cache`, `gem_binary`, `homebrew_user`, `options`, `package_name`, `response_file`, `response_file_variables`, `source`, `recursive`, `timeout`, and `version` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Gem Package Options The RubyGems package provider attempts to use the RubyGems API to install gems without spawning a new process, whenever possible. A gems command to install will be spawned under the following conditions: * When a `gem_binary` property is specified (as a hash, a string, or by a .gemrc file), Chef Infra Client will run that command to examine its environment settings and then again to install the gem. * When install options are specified as a string, Chef Infra Client will span a gems command with those options when installing the gem. * The Chef installer will search the `PATH` for a gem command rather than defaulting to the current gem environment. As part of `enforce_default_paths`, the `bin` directories area added to the `PATH`, which means when there are no other proceeding RubyGems, the installation will still be operated against it. #### Specify with Hash You should provide the install options as a hash if you are not using an explicit `gem_binary` parameter with the `gem_package` resource. This approach allows the provider to install the gem without needing to spawn an external gem process. The following RubyGems options are available for inclusion within a hash and are passed to the RubyGems DependencyInstaller: * `:env_shebang` * `:force` * `:format_executable` * `:ignore_dependencies` * `:prerelease` * `:security_policy` * `:wrappers` For more information about these options, see the RubyGems documentation: <https://docs.ruby-lang.org/en/2.2.0/Gem/DependencyInstaller.html>. **Example** ``` gem_package 'bundler' do options(prerelease: true, format_executable: false) end ``` #### Specify with String When using an explicit `gem_binary`, options must be passed as a string. When not using an explicit `gem_binary`, Chef Infra Client is forced to spawn a gems process to install the gems (which uses more system resources) when options are passed as a string. String options are passed verbatim to the gems command and should be specified just as if they were passed on a command line. For example, `--prerelease` for a pre-release gem. **Example** ``` gem_package 'nokogiri' do gem_binary('/opt/ree/bin/gem') options('--prerelease --no-format-executable') end ``` #### Specify with .gemrc File Options can be specified in a .gemrc file. By default the `gem_package` resource will use the Ruby interface to install gems which will ignore the .gemrc file. The `gem_package` resource can be forced to use the gems command instead (and to read the .gemrc file) by adding the `gem_binary` attribute to a code block. A template named `gemrc.erb` is located in a cookbook’s `/templates` directory: ``` :sources: - http://<%= node['gem_file']['host'] %>:<%= node['gem_file']['port'] %>/ ``` A recipe can be built that does the following: * Builds a `.gemrc` file based on a `gemrc.erb` template * Runs a `Gem.configuration` command * Installs a package using the `.gemrc` file ``` template '/root/.gemrc' do source 'gemrc.erb' action :create notifies :run, 'ruby_block[refresh_gemrc]', :immediately end ruby_block 'refresh_gemrc' do action :nothing block do Gem.configuration = Gem::ConfigFile.new [] end end gem_package 'di-ruby-lvm' do gem_binary '/opt/chef/embedded/bin/gem' action :install end ``` ### Actions --- The **package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. (Debian platform only; for other platforms, use the `:remove` action.) `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` **yum_package** resource only. Downgrade a package to satisfy requested version requirements. `arch` **Ruby Type:** String, Array **yum_package** resource only. The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name. `default_release` **Ruby Type:** String **apt_package** resource only. The default release. For example: `stable`. `flush_cache` **Ruby Type:** Array Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Default value: `[ :before, :after ]`. The value may also be a Hash: `( { :before => true/false, :after => true/false } )`. Yum automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while the Chef Infra Client run is in-progress. As an array: ``` yum_package 'some-package' do #... flush_cache [ :before ] #... end ``` and as a Hash: ``` yum_package 'some-package' do #... flush_cache( { :after => true } ) #... end ``` Note The `flush_cache` property does not flush the local Yum cache! Use Yum tools—`yum clean headers`, `yum clean packages`, `yum clean all`—to clean the local Yum cache. `gem_binary` **Ruby Type:** String A property for the `gem_package` provider that is used to specify a gems binary. `homebrew_user` **Ruby Type:** String, Integer **homebrew_package** resource only. The name of the Homebrew owner to be used by Chef Infra Client when executing a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `options` **Ruby Type:** String One (or more) additional options that are passed to the command. `package_name` **Ruby Type:** String, Array The name of the package. Default value: the `name` of the resource block. See “Syntax” section above for more information. `response_file` **Ruby Type:** String **apt_package** and **dpkg_package** resources only. The direct path to the file used to pre-seed a package. `response_file_variables` **Ruby Type:** Hash **apt_package** and **dpkg_package** resources only. A Hash of response file variables in the form of `{"VARIABLE" => "VALUE"}`. `source` **Ruby Type:** String Optional. The path to a package in the local file system. Note The AIX platform requires `source` to be a local file system path because `installp` does not retrieve packages using HTTP or FTP. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **package** resource in recipes: Install a gems file for use in recipes ``` chef_gem 'right_aws' do action :install end require 'right_aws' ``` Install a gems file from the local file system ``` gem_package 'right_aws' do source '/tmp/right_aws-1.11.0.gem' action :install end ``` Install a package ``` package 'tar' do action :install end ``` Install a package version ``` package 'tar' do version '1.16.1-1' action :install end ``` Install a package with options ``` package 'debian-archive-keyring' do action :install options '--force-yes' end ``` Install a package with a response_file Use of a `response_file` is only supported on Debian and Ubuntu at this time. Custom resources must be written to support the use of a `response_file`, which contains debconf answers to questions normally asked by the package manager on installation. Put the file in `/files/default` of the cookbook where the package is specified and Chef Infra Client will use the **cookbook_file** resource to retrieve it. To install a package with a `response_file`: ``` package 'sun-java6-jdk' do response_file 'java.seed' end ``` Install a specified architecture using a named provider ``` yum_package 'glibc-devel' do arch 'i386' end ``` Purge a package ``` package 'tar' do action :purge end ``` Remove a package ``` package 'tar' do action :remove end ``` Upgrade a package ``` package 'tar' do action :upgrade end ``` Use the ignore_failure common attribute ``` gem_package 'syntax' do action :install ignore_failure true end ``` Avoid unnecessary string interpolation Do this: ``` package 'mysql-server' do version node['mysql']['version'] action :install end ``` and not this: ``` package 'mysql-server' do version "#{node['mysql']['version']}" action :install end ``` Install a package in a platform The following example shows how to use the **package** resource to install an application named `app` and ensure that the correct packages are installed for the correct platform: ``` package 'app_name' do action :install end case node[:platform] when 'ubuntu','debian' package 'app_name-doc' do action :install end when 'centos' package 'app_name-html' do action :install end end ``` **Install sudo, then configure /etc/sudoers/ file** The following example shows how to install sudo and then configure the `/etc/sudoers` file: ``` # the following code sample comes from the ``default`` recipe in the ``sudo`` cookbook: https://github.com/chef-cookbooks/sudo package 'sudo' do action :install end if node['authorization']['sudo']['include_sudoers_d'] directory '/etc/sudoers.d' do mode '0755' owner 'root' group 'root' action :create end cookbook_file '/etc/sudoers.d/README' do source 'README' mode '0440' owner 'root' group 'root' action :create end end template '/etc/sudoers' do source 'sudoers.erb' mode '0440' owner 'root' group platform?('freebsd') ? 'wheel' : 'root' variables( :sudoers_groups => node['authorization']['sudo']['groups'], :sudoers_users => node['authorization']['sudo']['users'], :passwordless => node['authorization']['sudo']['passwordless'] ) end ``` where * the **package** resource is used to install sudo * the `if` statement is used to ensure availability of the `/etc/sudoers.d` directory * the **template** resource tells Chef Infra Client where to find the `sudoers` template * the `variables` property is a hash that passes values to template files (that are located in the `templates/` directory for the cookbook Use a case statement to specify the platform The following example shows how to use a case statement to tell Chef Infra Client which platforms and packages to install using cURL. ``` package 'curl' case node[:platform] when 'redhat', 'centos' package 'package_1' package 'package_2' package 'package_3' when 'ubuntu', 'debian' package 'package_a' package 'package_b' package 'package_c' end end ``` where `node[:platform]` for each node is identified by Ohai during every Chef Infra Client run. For example: ``` package 'curl' case node[:platform] when 'redhat', 'centos' package 'zlib-devel' package 'openssl-devel' package 'libc6-dev' when 'ubuntu', 'debian' package 'openssl' package 'pkg-config' package 'subversion' end end ``` Use symbols to reference attributes Symbols may be used to reference attributes: ``` package 'mysql-server' do version node[:mysql][:version] action :install end ``` instead of strings: ``` package 'mysql-server' do version node['mysql']['version'] action :install end ``` Use a whitespace array to simplify a recipe The following examples show different ways of doing the same thing. The first shows a series of packages that will be upgraded: ``` package 'package-a' do action :upgrade end package 'package-b' do action :upgrade end package 'package-c' do action :upgrade end package 'package-d' do action :upgrade end ``` and the next uses a single **package** resource and a whitespace array (`%w`): ``` package %w{package-a package-b package-c package-d} do action :upgrade end ``` Specify the Homebrew user with a UUID ``` homebrew_package 'emacs' do homebrew_user 1001 end ``` Specify the Homebrew user with a string ``` homebrew_package 'vim' do homebrew_user 'user1' end ``` pacman_package resource ------------------------ [pacman_package resource page](resources/pacman_package/index) --- Use the **pacman_package** resource to manage packages (using pacman) on the Arch Linux platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **pacman_package** resource block manages a package on a node, typically by installing it. The simplest use of the **pacman_package** resource is: ``` pacman_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **pacman_package** resource is: ``` pacman_package 'name' do options String package_name String source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `pacman_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **pacman_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **pacman_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **pacman_package** resource in recipes: Install a package ``` pacman_package 'name of package' do action :install end ``` paludis_package resource ------------------------- [paludis_package resource page](resources/paludis_package/index) --- Use the **paludis_package** resource to manage packages for the Paludis platform. ### Syntax --- A **paludis_package** resource block manages a package on a node, typically by installing it. The simplest use of the **paludis_package** resource is: ``` paludis_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **paludis_package** resource is: ``` paludis_package 'name' do options String package_name String source String timeout Integer # default value: 3600 version String action Symbol # defaults to :install if not specified end ``` where: * `paludis_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **paludis_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **paludis_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer | **Default Value:** `3600` The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **paludis_package** resource in recipes: Install a package ``` paludis_package 'name of package' do action :install end ``` perl resource ------------- [perl resource page](resources/perl/index) --- Use the **perl** resource to execute scripts using the Perl interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **perl** resource block executes scripts Perl: ``` perl 'hello world' do code <<-EOH print "Hello world! From Chef and Perl."; EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **perl** resource is: ``` perl 'name' do code String creates String cwd String environment Hash flags String group String, Integer notifies # see description path Array returns Integer, Array subscribes # see description timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `perl` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **perl** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. ### Properties --- The **perl** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. plist resource -------------- [plist resource page](resources/plist/index) --- Use the **plist** resource to set config values in plist files on macOS systems. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **plist** resource is: ``` plist 'name' do encoding String # default value: "binary" entry String group String # default value: "wheel" mode String, Integer owner String # default value: "root" path String # default value: 'name' unless specified value true, false, String, Integer, Float, Hash action Symbol # defaults to :set if not specified end ``` where: * `plist` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `encoding`, `entry`, `group`, `mode`, `owner`, `path`, and `value` are the properties available to this resource. ### Actions --- The **plist** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set a value in a plist file. (default) ### Properties --- The **plist** resource has the following properties: `encoding` **Ruby Type:** String | **Default Value:** `binary` `entry` **Ruby Type:** String `group` **Ruby Type:** String | **Default Value:** `wheel` The group of the plist file. `mode` **Ruby Type:** String, Integer The file mode of the plist file. Ex: ‘644’ `owner` **Ruby Type:** String | **Default Value:** `root` The owner of the plist file. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path on disk to the plist file. `value` **Ruby Type:** true, false, String, Integer, Float, Hash ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **plist** resource in recipes: **Show hidden files in finder**: ``` plist 'show hidden files' do path '/Users/vagrant/Library/Preferences/com.apple.finder.plist' entry 'AppleShowAllFiles' value true end ``` portage_package resource ------------------------- [portage_package resource page](resources/portage_package/index) --- Use the **portage_package** resource to manage packages for the Gentoo platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- The full syntax for all of the properties that are available to the **portage_package** resource is: ``` portage_package 'name' do options String package_name String source String timeout String, Integer # default value: 3600 version String action Symbol # defaults to :install if not specified end ``` where: * `portage_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **portage_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **portage_package** resource has the following properties: `options` **Ruby Type:** String One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer | **Default Value:** `3600` The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **portage_package** resource in recipes: Install a package ``` portage_package 'name of package' do action :install end ``` powershell_package resource ---------------------------- [powershell_package resource page](resources/powershell_package/index) --- Use the **powershell_package** resource to install and manage packages via the PowerShell Package Manager for the Microsoft Windows platform. The **powershell_package** resource requires administrative access, and a source must be configured in the PowerShell Package Manager via the [Register-PackageSource](https://docs.microsoft.com/en-us/powershell/module/packagemanagement/register-packagesource?view=powershell-5.1) command or the [powershell_package_source](resources/powershell_package_source/index) resource. **New in Chef Infra Client 12.16.** ### Syntax --- A **powershell_package** resource block manages a package on a node, typically by installing it. The simplest use of the **powershell_package** resource is: ``` powershell_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The powershell_package resource has the following syntax: ``` powershell_package 'name' do options String, Array package_name String, Array skip_publisher_check true, false # default value: false source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `powershell_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `skip_publisher_check`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **powershell_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:remove` Remove a package. ### Properties --- The **powershell_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array The name of the package. Default value: the name of the resource block. `skip_publisher_check` **Ruby Type:** true, false | **Default Value:** `false` Skip validating module author. New in Chef Client 14.3 `source` **Ruby Type:** String Specify the source of the package. New in Chef Client 14.0 `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **powershell_package** resource in recipes: Install a specific version of a package: ``` powershell_package 'xCertificate' do action :install version '1.1.0.0' end ``` Install multiple packages: ``` powershell_package 'Install Multiple Packages' do action :install package_name %w(xCertificate xNetworking) end ``` Install a package from a custom source: ``` powershell_package 'xCertificate' do action :install source 'MyGallery' end ``` Install multiple packages, and specify package versions: ``` powershell_package 'Install Multiple Packages' do action :install package_name %w(xCertificate xNetworking) version ['2.0.0.0', '2.12.0.0'] end ``` Install multiple packages, specifying the package version for one package but not the other: ``` powershell_package 'Install Multiple Packages' do action :install package_name %w(xCertificate xNetworking) version [nil, '2.12.0.0'] end ``` In this example, the `nil` tells `powershell_package` to install the most up to date version of `xCertificate` that is available, while pinning `xNetworking` to version 2.12.0.0. Remove a package: ``` powershell_package 'xCertificate' do action :remove end ``` powershell_package_source resource ------------------------------------ [powershell_package_source resource page](resources/powershell_package_source/index) --- Use the **powershell_package_source** resource to register a PowerShell package source and a Powershell package provider. There are two distinct objects we care about here. The first is a package source like a PowerShell repository or a NuGet Source. The second object is a provider that PowerShell uses to get to that source with, like PowerShellGet, NuGet, Chocolatey, etc. **New in Chef Infra Client 14.3.** ### Syntax --- The full syntax for all of the properties that are available to the **powershell_package_source** resource is: ``` powershell_package_source 'name' do new_name String password String provider_name String # default value: "NuGet" publish_location String script_publish_location String script_source_location String source_location String source_name String # default value: 'name' unless specified trusted true, false # default value: false user String action Symbol # defaults to :register if not specified end ``` where: * `powershell_package_source` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `new_name`, `password`, `provider_name`, `publish_location`, `script_publish_location`, `script_source_location`, `source_location`, `source_name`, `trusted`, and `user` are the properties available to this resource. ### Actions --- The **powershell_package_source** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:register` Registers a PowerShell package source. (default) `:set` Updates an existing PowerShell repository or package source. `:unregister` Unregisters the PowerShell package source. ### Properties --- The **powershell_package_source** resource has the following properties: `new_name` **Ruby Type:** String Used to change the name of a standard package source. New in Chef Infra Client 17.6 `password` **Ruby Type:** String A password that, as part of a credential object, is used to register a repository or other package source with. New in Chef Infra Client 17.6 `provider_name` **Ruby Type:** String | **Default Value:** `NuGet` **Allowed Values:** `"NuGet", "PowerShellGet", "Programs", "chocolatey", "msi", "msu", "psl", "winget"` The package management provider for the package source. The default is `PowerShellGet`. Only change this option in specific use cases. `publish_location` **Ruby Type:** String The URL where modules will be published to. Only valid if the provider is `PowerShellGet`. `script_publish_location` **Ruby Type:** String The location where scripts will be published to for this source. Only valid if the provider is `PowerShellGet`. `script_source_location` **Ruby Type:** String The URL where scripts are located for this source. Only valid if the provider is `PowerShellGet`. `source_location` **Ruby Type:** String The URL to the location to retrieve modules from. New in Chef Infra Client 17.6 `source_name` **Ruby Type:** String | **Default Value:** `The resource block's name` A label that names your package source. `trusted` **Ruby Type:** true, false | **Default Value:** `false` Whether or not to trust packages from this source. Used when creating a non-PowerShell repository package source. `user` **Ruby Type:** String A username that, as part of a credential object, is used to register a repository or other package source with. New in Chef Infra Client 17.6 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **powershell_package_source** resource in recipes: **Add a new PowerShell repository that is not trusted and which requires credentials to connect to**: ``` powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted false user "<EMAIL>" password "my_password" provider_name "PSRepository" action :register end ``` **Add a new package source that uses Chocolatey as the package provider**: ``` powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted true provider_name "chocolatey" action :register end ``` **Add a new PowerShell script source that is trusted**: ``` powershell_package_source 'MyDodgyScript' do source_name "MyDodgyScript" script_source_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" script_publish_location "https://pkgs.dev.azure.com/some-org/some-project/_packaging/some_feed/nuget/v2" trusted true action :register end ``` **Update an existing PowerShell repository to make it trusted**: ``` powershell_package_source 'MyPSModule' do source_name "MyPSModule" trusted true action :set end ``` **Update a Nuget package source with a new name and make it trusted**: ``` powershell_package_source 'PowerShellModules -> GoldFishBowl' do source_name "PowerShellModules" new_name "GoldFishBowl" provider_name "Nuget" trusted true action :set end ``` **Update a Nuget package source with a new name when the source is secured with a username and password**: ``` powershell_package_source 'PowerShellModules -> GoldFishBowl' do source_name "PowerShellModules" new_name "GoldFishBowl" trusted true user "<EMAIL>" password "some_secret_password" action :set end ``` **Unregister a package source**: ``` powershell_package_source 'PowerShellModules' do source_name "PowerShellModules" action :unregister end ``` powershell_script resource --------------------------- [powershell_script resource page](resources/powershell_script/index) --- Use the **powershell_script** resource to execute a script using the Windows PowerShell interpreter, much like how the script and script-based resources **bash**, **csh**, **perl**, **python**, and **ruby** are used. The powershell_script is specific to the Microsoft Windows platform, but may use both the the Windows PowerShell interpreter or the PowerShell Core (pwsh) interpreter as of Chef Infra Client 16.6 and later. The powershell_script resource creates and executes a temporary file rather than running the command inline. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` conditionals to guard this resource for idempotence. ### Syntax --- A **powershell_script** resource block executes a batch script using the Windows PowerShell interpreter. For example, writing to an interpolated path: ``` powershell_script 'write-to-interpolated-path' do code <<-EOH $stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt" $stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.") $stream.close() EOH end ``` The full syntax for all of the properties that are available to the **powershell_script** resource is: ``` powershell_script 'name' do code String command String, Array # default value: 'name' unless specified convert_boolean_return true, false # default value: false creates String cwd String domain String elevated true, false # default value: false environment Hash flags String group String, Integer input String interpreter String # default value: "powershell" live_stream true, false # default value: false password String returns Integer, Array # default value: 0 timeout Integer, String, Float # default value: 3600 user String, Integer action Symbol # defaults to :run if not specified end ``` where: * `powershell_script` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `command`, `convert_boolean_return`, `creates`, `cwd`, `domain`, `elevated`, `environment`, `flags`, `group`, `input`, `interpreter`, `live_stream`, `password`, `returns`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **powershell_script** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run the script. ### Properties --- The **powershell_script** resource has the following properties: `architecture` **Ruby Type:** Symbol The architecture of the process under which a script is executed. If a value is not provided, Chef Infra Client defaults to the correct value for the architecture, as determined by Ohai. An exception is raised when anything other than `:i386` is specified for a 32-bit process. Possible values: `:i386` (for 32-bit processes) and `:x86_64` (for 64-bit processes). `code` **Ruby Type:** String | `REQUIRED` A quoted string of code to be executed. `command` **Ruby Type:** String, Array | **Default Value:** `The resource block's name` An optional property to set the command to be executed if it differs from the resource block’s name. `convert_boolean_return` **Ruby Type:** true, false | **Default Value:** `false` Return `0` if the last line of a command is evaluated to be true or to return `1` if the last line is evaluated to be false. When the `guard_interpreter` common attribute is set to `:powershell_script`, a string command will be evaluated as if this value were set to `true`. This is because the behavior of this attribute is similar to the value of the `"$?"` expression common in UNIX interpreters. For example, this: ``` powershell_script 'make_safe_backup' do guard_interpreter :powershell_script code 'cp ~/data/nodes.json ~/data/nodes.bak' not_if 'test-path ~/data/nodes.bak' end ``` is similar to: ``` bash 'make_safe_backup' do code 'cp ~/data/nodes.json ~/data/nodes.bak' not_if 'test -e ~/data/nodes.bak' end ``` `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `domain` **Ruby Type:** String The domain of the username specified by the user property. If not specified, the username and password specified by the `user` and `password` properties will be used to resolve that user against the domain in which the system running Chef Infra Client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. New in Chef Client 12.21 `elevated` **Ruby Type:** true, false | **Default Value:** `false` Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) from interactively blocking the process. This will cause the process to be run under a batch login instead of an interactive login. The user running chef-client needs the ‘Replace a process level token’ and ‘Adjust Memory Quotas for a process’ permissions. The user that is running the command needs the ‘Log on as a batch job’ permission. Because this requires a login, the user and password properties are required. New in Chef Client 13.3 `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String A string that is passed to the Windows PowerShell command. Default value (Windows PowerShell 3.0+): `-NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy Bypass, -InputFormat None`. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `guard_interpreter` **Ruby Type:** Symbol | **Default Value:** `:powershell_script` When this property is set to `:powershell_script`, the 64-bit version of the Windows PowerShell shell will be used to evaluate strings values for the `not_if` and `only_if` properties. Set this value to `:default` to use the 32-bit version of the cmd.exe shell. `input` **Ruby Type:** String An optional property to set the input sent to the command as STDIN. New in Chef Infra Client 16.2 `interpreter` **Ruby Type:** String | **Default Value:** `powershell` **Allowed Values:** `"powershell", "pwsh"` The interpreter type, `powershell` or `pwsh` (PowerShell Core) `live_stream` **Ruby Type:** true, false | **Default Value:** `false` Send the output of the command run by this execute resource block to the Chef Infra Client event stream. `password` **Ruby Type:** String The password of the user specified by the user property. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. New in Chef Client 12.21 `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. `domain\user` or `user@my.dns.domain.com` via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain property. On Windows only, if this property is specified, the password property must be specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **powershell_script** resource in recipes: Write to an interpolated path ``` powershell_script 'write-to-interpolated-path' do code <<-EOH $stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt" $stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.") $stream.close() EOH end ``` Change the working directory ``` powershell_script 'cwd-then-write' do cwd Chef::Config[:file_cache_path] code <<-EOH $stream = [System.IO.StreamWriter] "C:/powershell-test2.txt" $pwd = pwd $stream.WriteLine("This is the contents of: $pwd") $dirs = dir foreach ($dir in $dirs) { $stream.WriteLine($dir.fullname) } $stream.close() EOH end ``` Change the working directory in Microsoft Windows ``` powershell_script 'cwd-to-win-env-var' do cwd '%TEMP%' code <<-EOH $stream = [System.IO.StreamWriter] "./temp-write-from-chef.txt" $stream.WriteLine("chef on windows rox yo!") $stream.close() EOH end ``` Pass an environment variable to a script ``` powershell_script 'read-env-var' do cwd Chef::Config[:file_cache_path] environment ({'foo' => 'BAZ'}) code <<-EOH $stream = [System.IO.StreamWriter] "./test-read-env-var.txt" $stream.WriteLine("FOO is $env:foo") $stream.close() EOH end ``` **Evaluate for true and/or false** Use the `convert_boolean_return` attribute to raise an exception when certain conditions are met. For example, the following fragments will run successfully without error: ``` powershell_script 'false' do code '$false' end ``` and: ``` powershell_script 'true' do code '$true' end ``` whereas the following will raise an exception: ``` powershell_script 'false' do convert_boolean_return true code '$false' end ``` Use the flags attribute ``` powershell_script 'Install IIS' do code <<-EOH Import-Module ServerManager Add-WindowsFeature Web-Server EOH flags '-NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy Unrestricted, -InputFormat None, -File' guard_interpreter :powershell_script not_if '(Get-WindowsFeature -Name Web-Server).Installed' end ``` Rename computer, join domain, reboot The following example shows how to rename a computer, join a domain, and then reboot the computer: ``` reboot 'Restart Computer' do action :nothing end powershell_script 'Rename and Join Domain' do code <<-EOH ...your rename and domain join logic here... EOH not_if <<-EOH $ComputerSystem = gwmi win32_computersystem ($ComputerSystem.Name -like '#{node['some_attribute_that_has_the_new_name']}') -and $ComputerSystem.partofdomain) EOH notifies :reboot_now, 'reboot[Restart Computer]', :immediately end ``` where: * The **powershell_script** resource block renames a computer, and then joins a domain * The **reboot** resource restarts the computer * The `not_if` guard prevents the Windows PowerShell script from running when the settings in the `not_if` guard match the desired state * The `notifies` statement tells the **reboot** resource block to run if the **powershell_script** block was executed during a Chef Infra Client run Run a command as an alternate user *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] domain "domain" user "username" password "password" end # Passing username = 'domain-name\\username'. No domain is passed powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "domain-name\\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end # Work around User Access Control (UAC) powershell_script 'mkdir test_dir' do code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" elevated true end ``` python resource --------------- [python resource page](resources/python/index) --- Use the **python** resource to execute scripts using the Python interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- The python resource has the following syntax: ``` python 'hello world' do code <<-EOH print "Hello world! From Chef and Python." EOH end ``` where: * `code` specifies the command to run The full syntax for all of the properties that are available to the **python** resource is: ``` python 'name' do code String command String # default value: 'name' unless specified creates String cwd String default_env true, false # default value: false domain String elevated true, false # default value: false environment Hash flags String group String, Integer interpreter String live_stream true, false # default value: false password String returns Integer, Array # default value: 0 sensitive true, false # default value: "True if the password property is set. False otherwise." timeout Integer, Float umask String, Integer user String, Integer action Symbol # defaults to :run if not specified end ``` where: * `python` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `command`, `creates`, `cwd`, `default_env`, `domain`, `elevated`, `environment`, `flags`, `group`, `interpreter`, `live_stream`, `password`, `returns`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **python** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a script. ### Properties --- The **python** resource has the following properties: `code` **Ruby Type:** String | `REQUIRED` A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({'ENV_VARIABLE' => 'VALUE'})`. **Note**: These variables must exist for a command to be run successfully. `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** Integer, String, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. `user` **Ruby Type:** String, Integer The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. `domain\user` or `<EMAIL>` via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain property. On Windows only, if this property is specified, the password property must be specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. reboot resource --------------- [reboot resource page](resources/reboot/index) --- Use the **reboot** resource to reboot a node, a necessary step with some installations on certain platforms. This resource is supported for use on the Microsoft Windows, macOS, and Linux platforms. In using this resource via notifications, it’s important to *only* use immediate notifications. Delayed notifications produce unintuitive and probably undesired results. **New in Chef Infra Client 12.0.** ### Syntax --- The full syntax for all of the properties that are available to the **reboot** resource is: ``` reboot 'name' do delay_mins Integer # default value: 0 reason String # default value: "Reboot by Chef Infra Client" action Symbol # defaults to :nothing if not specified end ``` where: * `reboot` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `delay_mins` and `reason` are the properties available to this resource. ### Actions --- The **reboot** resource has the following actions: `:cancel` Cancel a pending reboot request. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reboot_now` Reboot a node so that the Chef Infra Client may continue the installation process. `:request_reboot` Reboot a node at the end of a Chef Infra Client run. ### Properties --- The **reboot** resource has the following properties: `delay_mins` **Ruby Type:** Integer | **Default Value:** `0` The amount of time (in minutes) to delay a reboot request. `reason` **Ruby Type:** String | **Default Value:** `Reboot by Chef Infra Client` A string that describes the reboot action. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **reboot** resource in recipes: **Reboot a node immediately** ``` reboot 'now' do action :nothing reason 'Cannot continue Chef run without a reboot.' delay_mins 2 end execute 'foo' do command '...' notifies :reboot_now, 'reboot[now]', :immediately end ``` **Reboot a node at the end of a Chef Infra Client run** ``` reboot 'app_requires_reboot' do action :request_reboot reason 'Need to reboot when the run completes successfully.' delay_mins 5 end ``` **Cancel a reboot** ``` reboot 'cancel_reboot_request' do action :cancel reason 'Cancel a previous end-of-run reboot request.' end ``` registry_key resource ---------------------- [registry_key resource page](resources/registry_key/index) --- Use the **registry_key** resource to create and delete registry keys in Microsoft Windows. Note 64-bit versions of Microsoft Windows have a 32-bit compatibility layer in the registry that reflects and redirects certain keys (and their values) into specific locations (or logical views) of the registry hive. Chef Infra Client can access any reflected or redirected registry key. The machine architecture of the system on which Chef Infra Client is running is used as the default (non-redirected) location. Access to the SysWow64 location is redirected must be specified. Typically, this is only necessary to ensure compatibility with 32-bit applications that are running on a 64-bit operating system. For more information, see: [Registry Reflection](https://docs.microsoft.com/en-us/windows/win32/winprog64/registry-reflection). ### Syntax --- A **registry_key** resource block creates and deletes registry keys in Microsoft Windows: ``` registry_key 'HKEY_LOCAL_MACHINE\\...\\System' do values [{ name: 'NewRegistryKeyValue', type: :multi_string, data: %w(foo bar baz), }] action :create end ``` Use multiple registry key entries with key values that are based on node attributes: ``` registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\name_of_registry_key' do values [{name: 'key_name', type: :string, data: 'C:\Windows\System32\file_name.bmp'}, {name: 'key_name', type: :string, data: node['node_name']['attribute']['value']}, {name: 'key_name', type: :string, data: node['node_name']['attribute']['value']} ] action :create end ``` The registry_key resource has the following syntax: ``` registry_key 'name' do architecture Symbol # default value: :machine key String # default value: 'name' unless specified recursive true, false # default value: false values action Symbol # defaults to :create if not specified end ``` where: * `registry_key` is the resource * `name` is the name of the resource block * `values` is a hash that contains at least one registry key to be created or deleted. Each registry key in the hash is grouped by brackets in which the `name:`, `type:`, and `data:` values for that registry key are specified. * `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. Warning `:multi_string` must be an array, even if there is only a single string. * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `architecture`, `key`, `recursive` and `values` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. #### Registry Key Path Separators A Microsoft Windows registry key can be used as a string in Ruby code, such as when a registry key is used as the name of a recipe. In Ruby, when a registry key is enclosed in a double-quoted string (`" "`), the same backslash character (`\`) that is used to define the registry key path separator is also used in Ruby to define an escape character. Therefore, the registry key path separators must be escaped when they are enclosed in a double-quoted string. For example, the following registry key: ``` HKCU\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Themes ``` may be enclosed in a single-quoted string with a single backslash: ``` 'HKCU\SOFTWARE\path\to\key\Themes' ``` or may be enclosed in a double-quoted string with an extra backslash as an escape character: ``` "HKCU\\SOFTWARE\\path\\to\\key\\Themes" ``` #### Chef Infra Language Methods Six methods are present in the Chef Infra Language to help verify the registry during a Chef Infra Client run on the Microsoft Windows platform—`registry_data_exists?`, `registry_get_subkeys`, `registry_get_values`, `registry_has_subkeys?`, `registry_key_exists?`, and `registry_value_exists?`—these helpers ensure the **powershell_script** resource is idempotent. ##### registry_data_exists? Use the `registry_data_exists?` method to find out if a Microsoft Windows registry key contains the specified data of the specified type under the value. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_data_exists?` method is as follows: ``` registry_data_exists?( KEY_PATH, { name: 'NAME', type: TYPE, data: DATA }, ARCHITECTURE ) ``` where: * `KEY_PATH` is the path to the registry key value. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `{ name: 'NAME', type: TYPE, data: DATA }` is a hash that contains the expected name, type, and data of the registry key value * `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. ##### registry_get_subkeys Use the `registry_get_subkeys` method to get a list of registry key values that are present for a Microsoft Windows registry key. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_get_subkeys` method is as follows: ``` subkey_array = registry_get_subkeys(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This returns an array of registry key values. ##### registry_get_values Use the `registry_get_values` method to get the registry key values (name, type, and data) for a Microsoft Windows registry key. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_get_values` method is as follows: ``` subkey_array = registry_get_values(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This returns an array of registry key values. ##### registry_has_subkeys? Use the `registry_has_subkeys?` method to find out if a Microsoft Windows registry key has one (or more) values. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_has_subkeys?` method is as follows: ``` registry_has_subkeys?(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. ##### registry_key_exists? Use the `registry_key_exists?` method to find out if a Microsoft Windows registry key exists at the specified path. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_key_exists?` method is as follows: ``` registry_key_exists?(KEY_PATH, ARCHITECTURE) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. (Any registry key values that are associated with this registry key are ignored.) ##### registry_value_exists? Use the `registry_value_exists?` method to find out if a registry key value exists. Use `registry_data_exists?` to test for the type and data of a registry key value. Note This method can be used in recipes and from within the `not_if` and `only_if` blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the **registry_key** resource. The syntax for the `registry_dvalue_exists?` method is as follows: ``` registry_value_exists?( KEY_PATH, { name: 'NAME' }, ARCHITECTURE ) ``` where: * `KEY_PATH` is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. * `{ name: 'NAME' }` is a hash that contains the name of the registry key value; if either `type:` or `:value` are specified in the hash, they are ignored * `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. * `ARCHITECTURE` is one of the following values: `:x86_64`, `:i386`, or `:machine`. Set to `:i386` to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to`:x86_64` to force write to a 64-bit registry location, however Chef Infra Client returns an exception if `:x86_64` is used on a 32-bit machine. Set to `:machine` to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: `:machine`. This method will return `true` or `false`. ### Actions --- The **registry_key** resource has the following actions: `:create` Default. Create a registry key. If a registry key already exists (but does not match), update that registry key to match. `:create_if_missing` Create a registry key if it does not exist. Also, create a registry key value if it does not exist. `:delete` Delete the specified values for a registry key. `:delete_key` Delete the specified registry key and all of its subkeys. The `:delete_key` action with the `recursive` attribute will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **registry_key** resource has the following properties: `architecture` **Ruby Type:** Symbol | **Default Value:** `:machine` **Allowed Values:** `:i386, :machine, :x86_64` The architecture of the node for which keys are to be created or deleted. Possible values: `:i386` (for nodes with a 32-bit registry), `:x86_64` (for nodes with a 64-bit registry), and `:machine` (to have Chef Infra Client determine the architecture during a Chef Infra Client run). In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the `architecture` property must be set to `:i386`. The `:x86_64` value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (`:machine`) because Chef Infra Client returns an exception if `:x86_64` is used and the machine turns out to be a 32-bit machine (whereas with `:machine`, Chef Infra Client is able to access the registry key on the 32-bit machine). `key` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to the location in which a registry key is to be created or from which a registry key is to be deleted. Default value: the `name` of the resource block. See “Syntax” section above for more information. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both `HKLM\SECURITY` and `HKEY_LOCAL_MACHINE\SECURITY` are both valid and equivalent. The following hives are valid: `HKEY_LOCAL_MACHINE`, `HKLM`, `HKEY_CURRENT_CONFIG`, `HKCC`, `HKEY_CLASSES_ROOT`, `HKCR`, `HKEY_USERS`, `HKU`, `HKEY_CURRENT_USER`, and `HKCU`. `recursive` **Ruby Type:** true, false | **Default Value:** `false` When creating a key, this value specifies that the required keys for the specified path are to be created. When using the `:delete_key` action in a recipe, and if the registry key has subkeys, then set the value for this property to `true`. The `:delete_key` action with the `recursive` attribute will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client. `values` **Ruby Type:** Hash, Array An array of hashes, where each Hash contains the values that are to be set under a registry key. Each Hash must contain `name:`, `type:`, and `data:` (and must contain no other key values). `type:` represents the values available for registry keys in Microsoft Windows. Use `:binary` for REG_BINARY, `:string` for REG_SZ, `:multi_string` for REG_MULTI_SZ, `:expand_string` for REG_EXPAND_SZ, `:dword` for REG_DWORD, `:dword_big_endian` for REG_DWORD_BIG_ENDIAN, or `:qword` for REG_QWORD. Warning `:multi_string` must be an array, even if there is only a single string. ### Examples --- The following examples demonstrate various approaches for using the **registry_key** resource in recipes: Create a registry key Use a double-quoted string: ``` registry_key "HKEY_LOCAL_MACHINE\\path-to-key\\Policies\\System" do values [{ name: 'EnableLUA', type: :dword, data: 0 }] action :create end ``` or a single-quoted string: ``` registry_key 'HKEY_LOCAL_MACHINE\path-to-key\Policies\System' do values [{ name: 'EnableLUA', type: :dword, data: 0 }] action :create end ``` Delete a registry key value Use a double-quoted string: ``` registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\path\\to\\key\\AU" do values [{ name: 'NoAutoRebootWithLoggedOnUsers', type: :dword, data: '' }] action :delete end ``` or a single-quoted string: ``` registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\path\to\key\AU' do values [{ name: 'NoAutoRebootWithLoggedOnUsers', type: :dword, data: '' }] action :delete end ``` Note If `data:` is not specified, you get an error: `Missing data key in RegistryKey values hash` Delete a registry key and its subkeys, recursively Use a double-quoted string: ``` registry_key "HKCU\\SOFTWARE\\Policies\\path\\to\\key\\Themes" do recursive true action :delete_key end ``` or a single-quoted string: ``` registry_key 'HKCU\SOFTWARE\Policies\path\to\key\Themes' do recursive true action :delete_key end ``` Note Be careful when using the `:delete_key` action with the `recursive` attribute. This will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client. Use re-directed keys In 64-bit versions of Microsoft Windows, `HKEY_LOCAL_MACHINE\SOFTWARE\Example` is a re-directed key. In the following examples, because `HKEY_LOCAL_MACHINE\SOFTWARE\Example` is a 32-bit key, the output will be “Found 32-bit key” if they are run on a version of Microsoft Windows that is 64-bit: ``` registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\Example" do architecture :i386 recursive true action :create end ``` or: ``` registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\Example" do architecture :x86_64 recursive true action :delete_key end ``` or: ``` ruby_block 'check 32-bit' do block do puts 'Found 32-bit key' end only_if { registry_key_exists?("HKEY_LOCAL_MACHINE\SOFTWARE\\Example", :i386) } end ``` or: ``` ruby_block 'check 64-bit' do block do puts 'Found 64-bit key' end only_if { registry_key_exists?("HKEY_LOCAL_MACHINE\\SOFTWARE\\Example", :x86_64) } end ``` Set proxy settings to be the same as those used by Chef Infra Client Use a double-quoted string: ``` proxy = URI.parse(Chef::Config[:http_proxy]) registry_key 'HKCU\Software\Microsoft\path\to\key\Internet Settings' do values [{name: 'ProxyEnable', type: :reg_dword, data: 1}, {name: 'ProxyServer', data: "#{proxy.host}:#{proxy.port}"}, {name: 'ProxyOverride', type: :reg_string, data: <local>}, ] action :create end ``` or a single-quoted string: ``` proxy = URI.parse(Chef::Config[:http_proxy]) registry_key 'HKCU\Software\Microsoft\path\to\key\Internet Settings' do values [{name: 'ProxyEnable', type: :reg_dword, data: 1}, {name: 'ProxyServer', data: "#{proxy.host}:#{proxy.port}"}, {name: 'ProxyOverride', type: :reg_string, data: <local>}, ] action :create end ``` **Set the name of a registry key to “(Default)"** Use a double-quoted string: ``` registry_key 'Set (Default) value' do key "HKLM\\Software\\Test\\Key\\Path" values [ {name: '', type: :string, data: 'test'}, ] action :create end ``` or a single-quoted string: ``` registry_key 'Set (Default) value' do key 'HKLM\Software\Test\Key\Path' values [ {name: '', type: :string, data: 'test'}, ] action :create end ``` where `name: ''` contains an empty string, which will set the name of the registry key to `(Default)`. remote_directory resource -------------------------- [remote_directory resource page](resources/remote_directory/index) --- Use the **remote_directory** resource to incrementally transfer a directory from a cookbook to a node. The directory that is copied from the cookbook should be located under `COOKBOOK_NAME/files/default/REMOTE_DIRECTORY`. The `remote_directory` resource will obey file specificity. ### Syntax --- A **remote_directory** resource block transfers a directory from a cookbook to a node, and then assigns the permissions needed on that directory. For example: ``` remote_directory '/etc/apache2' do source 'apache2' owner 'root' group 'root' mode '0755' action :create end ``` where: * `'/etc/apache2'` specifies the directory * `source` specifies a directory in the current cookbook (use the `cookbook` property to specify a file that is in a different cookbook) * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **remote_directory** resource is: ``` remote_directory 'name' do cookbook String files_backup Integer, false # default value: 5 files_group String, Integer files_mode String, Integer # default value: 0644 on *nix systems files_owner String, Integer group String, Integer inherits true, false mode String, Integer overwrite true, false # default value: true owner String, Integer path String # default value: 'name' unless specified purge true, false recursive true, false rights Hash source String action Symbol # defaults to :create if not specified end ``` where: * `remote_directory` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `cookbook`, `files_backup`, `files_group`, `files_mode`, `files_owner`, `group`, `mode`, `overwrite`, `owner`, `path`, `purge`, `recursive`, and `source` are the properties available to this resource. ### Actions --- The **remote_directory** resource has the following actions: `:create` Default. Create a directory and/or the contents of that directory. If a directory or its contents already exist (but does not match), update that directory or its contents to match. `:create_if_missing` Create a directory and/or the contents of that directory, but only if it does not exist. `:delete` Delete a directory, including the contents of that directory. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **remote_directory** resource has the following properties: `cookbook` **Ruby Type:** String The cookbook in which a file is located (if it is not located in the current cookbook). The default value is the current cookbook. `files_backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backup copies to keep for files in the directory. `files_group` **Ruby Type:** String, Integer Configure group permissions for files. A string or ID that identifies the group owner by group name, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available). `files_mode` **Ruby Type:** String, Integer | **Default Value:** `0644 on *nix systems` The octal mode for a file. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `files_owner` **Ruby Type:** String, Integer Configure owner permissions for files. A string or ID that identifies the group owner by user name, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `group` **Ruby Type:** Integer, String Use to configure permissions for directories. A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the directory already exists, the existing mode on the directory is used. If `mode` is not specified, the directory does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'`, and then applies the umask for the system on which the directory is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `overwrite` **Ruby Type:** true, false | **Default Value:** `true` Overwrite a file when it is different. `owner` **Ruby Type:** Integer, String Use to configure permissions for directories. A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the `name` of the resource block. See “Syntax” section above for more information. `purge` **Ruby Type:** true, false | **Default Value:** `false` Purge extra files found in the target directory. `recursive` **Ruby Type:** true, false | **Default Value:** `true` Create or delete directories recursively. Chef Infra Client must be able to create the directory structure, including parent directories (if missing), as defined in `COOKBOOK_NAME/files/default/REMOTE_DIRECTORY`. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String | **Default Value:** `The base portion of the 'path' property.` The base name of the source file (and inferred from the `path` property). For example, in the default value, ‘/some/path/’ would be ‘path’. #### Recursive Directories The **remote_directory** resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the `recursive` attribute only applies `group`, `mode`, and `owner` attribute values to the remote directory itself and any inner directories the resource copies. A directory structure: ``` /foo /bar /baz ``` The following example shows a way create a file in the `/baz` directory: ``` remote_directory '/foo/bar/baz' do owner 'root' group 'root' mode '0755' action :create end ``` But with this example, the `group`, `mode`, and `owner` attribute values will only be applied to `/baz`. Which is fine, if that’s what you want. But most of the time, when the entire `/foo/bar/baz` directory structure is not there, you must be explicit about each directory. For example: ``` %w( /foo /foo/bar /foo/bar/baz ).each do |path| remote_directory path do owner 'root' group 'root' mode '0755' end end ``` This approach will create the correct hierarchy—`/foo`, then `/bar` in `/foo`, and then `/baz` in `/bar`—and also with the correct attribute values for `group`, `mode`, and `owner`. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Recursive Directories The **remote_directory** resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the `recursive` attribute only applies `group`, `mode`, and `owner` attribute values to the remote directory itself and any inner directories the resource copies. A directory structure: ``` /foo /bar /baz ``` The following example shows a way create a file in the `/baz` directory: ``` remote_directory '/foo/bar/baz' do owner 'root' group 'root' mode '0755' action :create end ``` But with this example, the `group`, `mode`, and `owner` attribute values will only be applied to `/baz`. Which is fine, if that’s what you want. But most of the time, when the entire `/foo/bar/baz` directory structure is not there, you must be explicit about each directory. For example: ``` %w( /foo /foo/bar /foo/bar/baz ).each do |path| remote_directory path do owner 'root' group 'root' mode '0755' end end ``` This approach will create the correct hierarchy—`/foo`, then `/bar` in `/foo`, and then `/baz` in `/bar`—and also with the correct attribute values for `group`, `mode`, and `owner`. ##### Example This section contains a more detailed example of how Chef Infra Client manages recursive directory structures: * A cookbook named `cumbria` that is used to build a website * A subfolder in the `/files/default` directory named `/website` * A file named `index.html`, which is the root page for the website * Directories within `/website` named `/cities`, `/places`, and `/football`, which contains pages about cities, places, and football teams * A directory named `/images`, which contains images These files are placed in the `/files/default` directory in the `cumbria` cookbook, like this: ``` cumbria /files /default /website index.html /cities carisle.html kendal.html penrith.html windermere.html /football carisle_united.html /images carisle_united.png furness_abbey.png hadrians_wall.png kendal.png /places furness_abbey.html hadrians_wall.html ``` The **remote_directory** resource can be used to build a website using these files. This website is being run on an Apache web server. The resource would be similar to the following: ``` remote_directory '/var/www/html' do files_mode '0440' files_owner 'yan' mode '0770' owner 'hamilton' source 'website' end ``` When Chef Infra Client runs, the **remote_directory** resource will tell Chef Infra Client to copy the directory tree from the cookbook to the file system using the structure defined in cookbook: ``` /var /www /html index.html /cities carisle.html kendal.html penrith.html windermere.html /football carisle_united.html /images carisle_united.png furness_abbey.png hadrians_wall.png kendal.png /places furness_abbey.html hadrians_wall.html ``` Chef Infra Client will manage the permissions of the entire directory structure below `/html`, for a total of 12 files and 4 directories. For example: ``` dr-xr-xr-x 2 root root 4096 /var/www/html dr--r----- 1 yan root 4096 /var/www/html/index.html drwxrwx--- 2 hamilton root 4096 /var/www/html/cities dr--r----- 1 yan root 4096 /var/www/html/cities/carlisle.html dr--r----- 1 yan root 4096 /var/www/html/cities/kendal.html dr--r----- 1 yan root 4096 /var/www/html/cities/penrith.html dr--r----- 1 yan root 4096 /var/www/html/cities/windermere.html drwxrwx--- 2 hamilton root 4096 /var/www/html/football dr--r----- 1 yan root 4096 /var/www/html/football/carlisle_united.html drwxrwx--- 2 hamilton root 4096 /var/www/html/images dr--r----- 1 yan root 4096 /var/www/html/images/carlisle_united/png dr--r----- 1 yan root 4096 /var/www/html/images/furness_abbey/png dr--r----- 1 yan root 4096 /var/www/html/images/hadrians_wall.png dr--r----- 1 yan root 4096 /var/www/html/images/kendal.png drwxrwx--- 2 hamilton root 4096 /var/www/html/places dr--r----- 1 yan root 4096 /var/www/html/places/furness_abbey.html dr--r----- 1 yan root 4096 /var/www/html/places/hadrians_wall.html ``` #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(<NAME>) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. ### Examples --- The following examples demonstrate various approaches for using the **remote_directory** resource in recipes: Recursively transfer a directory from a remote location ``` # create up to 10 backups of the files # set the files owner different from the directory remote_directory '/tmp/remote_something' do source 'something' files_backup 10 files_owner 'root' files_group 'root' files_mode '0644' owner 'nobody' group 'nobody' mode '0755' end ``` Use with the chef_handler resource The following example shows how to use the **remote_directory** resource and the **chef_handler** resource to reboot a handler named `WindowsRebootHandler`: ``` # the following code sample comes from the # ``reboot_handler`` recipe in the ``windows`` cookbook: # https://github.com/chef-cookbooks/windows remote_directory node['chef_handler']['handler_path'] do source 'handlers' recursive true action :create end chef_handler 'WindowsRebootHandler' do source "#{node['chef_handler']['handler_path']}/windows_reboot_handler.rb" arguments node['windows']['allow_pending_reboots'] supports :report => true, :exception => false action :enable end ``` remote_file resource --------------------- [remote_file resource page](resources/remote_file/index) --- Use the **remote_file** resource to transfer a file from a remote location using file specificity. This resource is similar to the **file** resource. Note Fetching files from the `files/` directory in a cookbook should be done with the **cookbook_file** resource. ### Syntax --- A **remote_file** resource block manages files by using files that exist remotely. For example, to write the home page for an Apache website: ``` remote_file '/var/www/customers/public_html/index.html' do source 'http://somesite.com/index.html' owner 'web_admin' group 'web_admin' mode '0755' action :create end ``` where: * `'/var/www/customers/public_html/index.html'` is path to the file to be created * `'http://somesite.com/index.html'` specifies the location of the remote file, the file is downloaded from there * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **remote_file** resource is: ``` remote_file 'name' do atomic_update true, false authentication # default value: remote backup Integer, false # default value: 5 checksum String content String, nil force_unlink true, false # default value: false ftp_active_mode true, false # default value: false group String, Integer headers Hash inherits true, false manage_symlink_source true, false mode String, Integer notifies # see description owner String, Integer path String # defaults to 'name' if not specified rights Hash source String, Array subscribes # see description use_conditional_get true, false verify String, Block remote_domain String remote_password String remote_user String show_progress true, false # default value: false use_etag true, false # default value: true use_last_modified true, false # default value: true sensitive true, false # default value: false verifications Array action Symbol # defaults to :create if not specified end ``` where: * `remote_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `atomic_update`, `authentication`, `backup`, `checksum`, `content`, `force_unlink`, `ftp_active_mode`, `group`, `headers`, `http_options`, `manage_symlink_source`, `mode`, `owner`, `path`, `remote_domain`, `remote_password`, `remote_user`, `show_progress`, `ssl_verify_mode`, `use_etag`, and `use_last_modified` are the properties available to this resource. ### Actions --- The **remote_file** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the **file** resource.) ### Properties --- The **remote_file** resource has the following properties: `atomic_update` **Ruby Type:** true, false | **Default Value:** `False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.` Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the `client.rb` file. `authentication` **Ruby Type:** Symbol | **Default Value:** `:remote` **Allowed Values:** `:local, :remote` `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `checksum` **Ruby Type:** String Optional, see `use_conditional_get`. The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, Chef Infra Client does not download it. `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `ftp_active_mode` **Ruby Type:** true, false | **Default Value:** `false` Whether Chef Infra Client uses active or passive FTP. Set to `true` to use active FTP. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `headers` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of custom headers. For example: ``` headers({ "Cookie" => "user=user_name; pass=p@ssw0rd!" }) ``` or: ``` headers({ "Referer" => "#{header}" }) ``` or: ``` headers( "Authorization"=>"Basic #{ Base64.encode64("#{username}:#{password}").gsub("\n", "") }" ) ``` `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `http_options` **Ruby Type:** Hash | **Default Value:** `{}` A Hash of custom HTTP options. For example: `http_options({ http_retry_count: 0, http_retry_delay: 2 })` New in Chef Infra Client 17.5 `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `true`, the Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `false`, Chef Infra Client will follow the symlink and will manage the permissions and content of the symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The full path to the file, including the file name and its extension. Default value: the `name` of the resource block. See “Syntax” section above for more information. `remote_domain` **Ruby Type:** String **Windows only** The domain of the user specified by the `remote_user` property. By default the resource will authenticate against the domain of the remote system, or as a local account if the remote system is not joined to a domain. If the remote system is not part of a domain, it is necessary to authenticate as a local user on the remote system by setting the domain to `.`, for example: remote_domain ‘.’. The domain may also be specified as part of the `remote_user` property. New in Chef Client 13.4 `remote_password` **Ruby Type:** String **Windows only** The password of the user specified by the `remote_user` property. This property is required if `remote_user` is specified and may only be specified if `remote_user` is specified. The `sensitive` property for this resource will automatically be set to `true` if `remote_password` is specified. New in Chef Client 13.4 `remote_user` **Ruby Type:** String **Windows only** The name of a user with access to the remote file specified by the source property. The user name may optionally be specified with a domain, such as: `domain\user` or `<EMAIL>` via Universal Principal Name (UPN) format. The domain may also be set using the `remote_domain` property. Note that this property is ignored if source is not a UNC path. If this property is specified, the `remote_password` property is required. New in Chef Client 13.4 `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String, Array Required. The location of the source file. The location of the source file may be HTTP (`http://`), FTP (`ftp://`), SFTP (`sftp://`), local (`file:///`), or UNC (`\\host\share\file.tar.gz`). There are many ways to define the location of a source file. By using a path: ``` source 'http://couchdb.apache.org/img/sketch.png' ``` By using FTP: ``` source 'ftp://remote_host/path/to/img/sketch.png' ``` By using SFTP: ``` source 'sftp://username:password@remote_host:22/path/to/img/sketch.png' ``` By using a local path: ``` source 'file:///path/to/img/sketch.png' ``` By using a Microsoft Windows UNC: ``` source '\\\\path\\to\\img\\sketch.png' ``` By using a node attribute: ``` source node['nginx']['foo123']['url'] ``` By using attributes to define paths: ``` source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2" ``` By defining multiple paths for multiple locations: ``` source 'http://seapower/spring.png', 'http://seapower/has_sprung.png' ``` By defining those same multiple paths as an array: ``` source ['http://seapower/spring.png', 'http://seapower/has_sprung.png'] ``` When multiple paths are specified, Chef Infra Client will attempt to download the files in the order listed, stopping after the first successful download. `use_conditional_get` **Ruby Type:** true, false | **Default Value:** `true` Enable conditional HTTP requests by using a conditional `GET` (with the If-Modified-Since header) or an opaque identifier (ETag). To use If-Modified-Since headers, `use_last_modified` must also be set to `true`. To use ETag headers, `use_etag` must also be set to `true`. `show_progress` **Ruby Type:** true, false | **Default Value:** `false` Displays the progress of the file download. `ssl_verify_mode` **Ruby Type:** Symbol **Allowed Values:** `:verify_none, :verify_peer` Optional property to override SSL policy. If not specified, uses the SSL policy from `config.rb`. New in Chef Infra Client 16.2 `use_etag` **Ruby Type:** true, false | **Default Value:** `true` Enable ETag headers. Set to `false` to disable ETag headers. To use this setting, `use_conditional_get` must also be set to true. `use_last_modified` **Ruby Type:** true, false | **Default Value:** `true` Enable `If-Modified-Since` headers. Set to `false` to disable `If-Modified-Since` headers. To use this setting, `use_conditional_get` must also be set to `true`. `verify` **Ruby Type:** String, Block A block or a string that returns `true` or `false`. A string, when `true` is executed as a system command. A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block is `true`, Chef Infra Client will continue to update the file as appropriate. For example, this should return `true`: ``` remote_file '/tmp/baz' do verify { 1 == 1 } end ``` This should return `true`: ``` remote_file '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` This should return `true`: ``` remote_file '/tmp/bar' do verify { 1 == 1} end ``` And this should return `true`: ``` remote_file '/tmp/foo' do verify do |path| true end end ``` Whereas, this should return `false`: ``` remote_file '/tmp/turtle' do verify '/usr/bin/false' end ``` If a string or a block return `false`, the Chef Infra Client run will stop and an error is returned. #### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(<NAME>) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. #### Prevent Re-downloads To prevent Chef Infra Client from re-downloading files that are already present on a node, use one of the following attributes in a recipe: `use_conditional_get` (default) or `checksum`. * The `use_conditional_get` attribute is the default behavior of Chef Infra Client. If the remote file is located on a server that supports ETag and/or If-Modified-Since headers, Chef Infra Client will use a conditional `GET` to determine if the file has been updated. If the file has been updated, Chef Infra Client will re-download the file. * The `checksum` attribute will ask Chef Infra Client to compare the checksum for the local file to the one at the remote location. If they match, Chef Infra Client will not re-download the file. Using a local checksum for comparison requires that the local checksum be the correct checksum. The desired approach just depends on the desired workflow. For example, if a node requires a new file every day, using the checksum approach would require that the local checksum be updated and/or verified every day as well, in order to ensure that the local checksum was the correct one. Using a conditional `GET` in this scenario will greatly simplify the management required to ensure files are being updated accurately. #### Access a remote UNC path on Windows The `remote_file` resource on Windows supports accessing files from a remote SMB/CIFS share. The file name should be specified in the source property as a UNC path e.g. `\myserver\myshare\mydirectory\myfile.txt`. This allows access to the file at that path location even if the Chef Infra Client process identity does not have permission to access the file. Credentials for authenticating to the remote system can be specified using the `remote_user`, `remote_domain`, and `remote_password` properties when the user that Chef Infra Client is running does not have access to the remote file. See the “Properties” section for more details on these options. **Note**: This is primarily for accessing remote files when the user that Chef Infra Client is running as does not have sufficient access, and alternative credentials need to be specified. If the user already has access, the credentials do not need to be specified. In a case where the local system and remote system are in the same domain, the `remote_user` and `remote_password` properties often do not need to be specified, as the user may already have access to the remote file share. Examples: **Access a file from a different domain account:** ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_domain 'domain' remote_user 'username' remote_password 'password' end ``` OR ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_user 'domain\username' remote_password 'password' end ``` **Access a file using a local account on the remote machine:** ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_domain '.' remote_user 'username' remote_password 'password' end ``` OR ``` remote_file 'E:/domain_test.txt' do source '\\myserver\myshare\mydirectory\myfile.txt' remote_user '.\username' remote_password 'password' end ``` ### Examples --- The following examples demonstrate various approaches for using the **remote_file** resource in recipes: **Download a file without checking the checksum**: ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' end ``` **Download a file with a checksum to validate**: ``` remote_file '/tmp/test_file' do source 'http://www.example.com/tempfiles/test_file' mode '0755' checksum '3a7dac00b1' # A SHA256 (or portion thereof) of the file. end ``` **Download a file only if it’s not already present**: ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' checksum '3a7dac00b1' # A SHA256 (or portion thereof) of the file. action :create_if_missing end ``` **Using HTTP Basic Authentication in Headers**: ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' headers('Authorization' => "Basic #{Base64.encode64("USERNAME_VALUE:PASSWORD_VALUE").delete("\n")}") checksum '3a7dac00b1' # A SHA256 (or portion thereof) of the file. action :create_if_missing end ``` **Downloading a file to the Chef file cache dir for execution**: ``` remote_file '#{Chef::Config['file_cache_path']}/install.sh' do source 'https://example.org/install.sh' action :create_if_missing end execute '#{Chef::Config['file_cache_path']}/install.sh' ``` **Specify advanced HTTP connection options including Net::HTTP (nethttp) options:** ``` remote_file '/tmp/remote.txt' do source 'https://example.org/remote.txt' http_options({ http_retry_delay: 0, http_retry_count: 0, keepalives: false, nethttp: { continue_timeout: 5, max_retries: 5, read_timeout: 5, write_timeout: 5, ssl_timeout: 5, }, }) end ``` rhsm_errata resource --------------------- [rhsm_errata resource page](resources/rhsm_errata/index) --- Use the **rhsm_errata** resource to install packages associated with a given Red Hat Subscription Manager Errata ID. This is helpful if packages to mitigate a single vulnerability must be installed on your hosts. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **rhsm_errata** resource is: ``` rhsm_errata 'name' do errata_id String # default value: 'name' unless specified action Symbol # defaults to :install if not specified end ``` where: * `rhsm_errata` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `errata_id` is the property available to this resource. ### Actions --- The **rhsm_errata** resource has the following actions: `:install` Install a package for a specific errata ID. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **rhsm_errata** resource has the following properties: `errata_id` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the errata ID if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **rhsm_errata** resource in recipes: **Install a package from an Errata ID** ``` rhsm_errata 'RHSA:2018-1234' ``` **Specify an Errata ID that differs from the resource name** ``` rhsm_errata 'errata-install' errata_id 'RHSA:2018-1234' end ``` rhsm_errata_level resource ---------------------------- [rhsm_errata_level resource page](resources/rhsm_errata_level/index) --- Use the **rhsm_errata_level** resource to install all packages of a specified errata level from the Red Hat Subscription Manager. For example, you can ensure that all packages associated with errata marked at a ‘Critical’ security level are installed. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **rhsm_errata_level** resource is: ``` rhsm_errata_level 'name' do errata_level String # default value: 'name' unless specified action Symbol # defaults to :install if not specified end ``` where: * `rhsm_errata_level` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `errata_level` is the property available to this resource. ### Actions --- The **rhsm_errata_level** resource has the following actions: `:install` Install all packages of the specified errata level. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **rhsm_errata_level** resource has the following properties: `errata_level` **Ruby Type:** String | **Default Value:** `The resource block's name` **Allowed Values:** `"critical", "important", "low", "moderate"` An optional property for specifying the errata level of packages to install if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **rhsm_errata_level** resource in recipes: **Specify an errata level that differs from the resource name** ``` rhsm_errata_level 'example_install_moderate' do errata_level 'moderate' end ``` rhsm_register resource ----------------------- [rhsm_register resource page](resources/rhsm_register/index) --- Use the **rhsm_register** resource to register a node with the Red Hat Subscription Manager or a local Red Hat Satellite server. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **rhsm_register** resource is: ``` rhsm_register 'name' do activation_key String, Array auto_attach true, false # default value: false base_url String environment String force true, false # default value: false https_for_ca_consumer true, false # default value: false install_katello_agent true, false # default value: true organization String password String release Float, String satellite_host String server_url String service_level String system_name String username String action Symbol # defaults to :register if not specified end ``` where: * `rhsm_register` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `activation_key`, `auto_attach`, `base_url`, `environment`, `force`, `https_for_ca_consumer`, `install_katello_agent`, `organization`, `password`, `release`, `satellite_host`, `server_url`, `service_level`, `system_name`, and `username` are the properties available to this resource. ### Actions --- The **rhsm_register** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:register` Register the node with RHSM. (default) `:unregister` Unregister the node from RHSM. ### Properties --- The **rhsm_register** resource has the following properties: `activation_key` **Ruby Type:** String, Array A string or array of activation keys to use when registering; you must also specify the ‘organization’ property when using this property. `auto_attach` **Ruby Type:** true, false | **Default Value:** `false` If true, RHSM will attempt to automatically attach the host to applicable subscriptions. It is generally better to use an activation key with the subscriptions pre-defined. `base_url` **Ruby Type:** String The hostname of the content delivery server to use to receive updates. Both Customer Portal Subscription Management and Subscription Asset Manager use Red Hat’s hosted content delivery services, with the URL <https://cdn.redhat.com>. Since Satellite 6 hosts its own content, the URL must be used for systems registered with Satellite 6. New in Chef Infra Client 17.8 `environment` **Ruby Type:** String The environment to use when registering; required when using the username and password properties. `force` **Ruby Type:** true, false | **Default Value:** `false` If true, the system will be registered even if it is already registered. Normally, any register operations will fail if the machine has already been registered. `https_for_ca_consumer` **Ruby Type:** true, false | **Default Value:** `false` If true, Chef Infra Client will fetch the katello-ca-consumer-latest.noarch.rpm from the satellite_host using HTTPS. New in Chef Infra Client 15.9 `install_katello_agent` **Ruby Type:** true, false | **Default Value:** `true` If true, the ‘katello-agent’ RPM will be installed. `organization` **Ruby Type:** String The organization to use when registering; required when using the ‘activation_key’ property. `password` **Ruby Type:** String The password to use when registering. This property is not applicable if using an activation key. If specified, username and environment are also required. `release` **Ruby Type:** Float, String Sets the operating system minor release to use for subscriptions for the system. Products and updates are limited to the specified minor release version. This is used only used with the `auto_attach` option. For example, `release '6.4'` will append `--release=6.4` to the register command. New in Chef Infra Client 17.8 `satellite_host` **Ruby Type:** String The FQDN of the Satellite host to register with. If this property is not specified, the host will register with Red Hat’s public RHSM service. `server_url` **Ruby Type:** String The hostname of the subscription service to use. The default is Customer Portal Subscription Management, subscription.rhn.redhat.com. If you do not use this option, the system registers with Customer Portal Subscription Management. New in Chef Infra Client 17.8 `service_level` **Ruby Type:** String Sets the service level to use for subscriptions on the registering machine. This is only used with the `auto_attach` option. New in Chef Infra Client 17.8 `system_name` **Ruby Type:** String The name of the system to register, defaults to the hostname. New in Chef Infra Client 16.5 `username` **Ruby Type:** String The username to use when registering. This property is not applicable if using an activation key. If specified, password and environment properties are also required. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **rhsm_register** resource in recipes: **Register a node with RHSM* ``` rhsm_register 'my-host' do activation_key 'ABCD1234' organization 'my_org' end ``` rhsm_repo resource ------------------- [rhsm_repo resource page](resources/rhsm_repo/index) --- Use the **rhsm_repo** resource to enable or disable Red Hat Subscription Manager repositories that are made available via attached subscriptions. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **rhsm_repo** resource is: ``` rhsm_repo 'name' do repo_name String # default value: 'name' unless specified action Symbol # defaults to :enable if not specified end ``` where: * `rhsm_repo` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `repo_name` is the property available to this resource. ### Actions --- The **rhsm_repo** resource has the following actions: `:disable` Disable a RHSM repository. `:enable` Enable a RHSM repository. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **rhsm_repo** resource has the following properties: `repo_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the repository name if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **rhsm_repo** resource in recipes: **Enable an RHSM repository** ``` rhsm_repo 'rhel-7-server-extras-rpms' ``` **Disable an RHSM repository** ``` rhsm_repo 'rhel-7-server-extras-rpms' do action :disable end ``` rhsm_subscription resource --------------------------- [rhsm_subscription resource page](resources/rhsm_subscription/index) --- Use the **rhsm_subscription** resource to add or remove Red Hat Subscription Manager subscriptions from your host. This can be used when a host’s activation_key does not attach all necessary subscriptions to your host. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **rhsm_subscription** resource is: ``` rhsm_subscription 'name' do pool_id String # default value: 'name' unless specified action Symbol # defaults to :attach if not specified end ``` where: * `rhsm_subscription` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `pool_id` is the property available to this resource. ### Actions --- The **rhsm_subscription** resource has the following actions: `:attach` Attach the node to a subscription pool. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove the node from a subscription pool. ### Properties --- The **rhsm_subscription** resource has the following properties: `pool_id` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for specifying the Pool ID if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. route resource -------------- [route resource page](resources/route/index) --- Use the **route** resource to manage the system routing table in a Linux environment. ### Syntax --- A **route** resource block manages the system routing table in a Linux environment: ``` route '10.0.1.10/32' do gateway '10.0.0.20' device 'eth1' end ``` The full syntax for all of the properties that are available to the **route** resource is: ``` route 'name' do comment String device String gateway String metric Integer netmask String route_type Symbol, String # default value: :host target String # default value: 'name' unless specified action Symbol # defaults to :add if not specified end ``` where: * `route` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `comment`, `device`, `gateway`, `metric`, `netmask`, `route_type`, and `target` are the properties available to this resource. ### Actions --- The **route** resource has the following actions: `:add` Default. Add a route. `:delete` Delete a route. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **route** resource has the following properties: `comment` **Ruby Type:** String Add a comment for the route. New in Chef Client 14.0 `device` **Ruby Type:** String The network interface to which the route applies. `gateway` **Ruby Type:** String The gateway for the route. `metric` **Ruby Type:** Integer The route metric value. `netmask` **Ruby Type:** String The decimal representation of the network mask. For example: `255.255.255.0`. `route_type` **Ruby Type:** Symbol, String | **Default Value:** `:host` **Allowed Values:** `:host, :net` `target` **Ruby Type:** String | **Default Value:** `The resource block's name` The IP address of the target route. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. rpm_package resource --------------------- [rpm_package resource page](resources/rpm_package/index) --- Use the **rpm_package** resource to manage packages using the RPM Package Manager. ### Syntax --- The full syntax for all of the properties that are available to the **rpm_package** resource is: ``` rpm_package 'name' do allow_downgrade true, false # default value: true options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `rpm_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **rpm_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **rpm_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **rpm_package** resource in recipes: Install a package ``` rpm_package 'name of package' do action :install end ``` ruby resource ------------- [ruby resource page](resources/ruby/index) --- Use the **ruby** resource to execute scripts using the Ruby interpreter. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. ### Syntax --- A **ruby** resource block executes scripts using Ruby: ``` ruby 'hello world' do code <<-EOH puts "Hello world! From Chef and Ruby." EOH end ``` where: * `cwd` specifies the directory from which the command is run * `code` specifies the command to run The full syntax for all of the properties that are available to the **ruby** resource is: ``` ruby 'name' do code String creates String cwd String environment Hash flags String group String, Integer path Array returns Integer, Array timeout Integer, Float user String, Integer umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `ruby` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `path`, `returns`, `timeout`, `user`, and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **ruby** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a script. ### Properties --- The **ruby** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `ignore_failure` **Ruby Type:** true, false | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `notifies` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `subscribes` **Ruby Type:** Symbol, Chef::Resource\[String\] A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String, Integer The user name or user ID that should be changed before running a command. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. ruby_block resource -------------------- [ruby_block resource page](resources/ruby_block/index) --- Use the **ruby_block** resource to execute Ruby code during a Chef Infra Client run. Ruby code in the `ruby_block` resource is evaluated with other resources during convergence, whereas Ruby code outside of a `ruby_block` resource is evaluated before other resources, as the recipe is compiled. ### Syntax --- A **ruby_block** resource block executes a block of arbitrary Ruby code. For example, to reload the client.rb file during a Chef Infra Client run: ``` ruby_block 'reload_client_config' do block do Chef::Config.from_file("/etc/chef/client.rb") end action :run end ``` The full syntax for all of the properties that are available to the **ruby_block** resource is: ``` ruby_block 'name' do block Block block_name String # defaults to 'name' if not specified action Symbol # defaults to :run if not specified end ``` where: * `ruby_block` is the resource. * `name` is the name given to the resource block. * `block` is the block of Ruby code to be executed. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `block` and `block_name` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **ruby_block** resource has the following actions: `:create` The same as `:run`. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Default. Run a Ruby block. ### Properties --- The **ruby_block** resource has the following properties: `block` **Ruby Type:** Block A block of Ruby code. `block_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the Ruby block. Default value: the `name` of the resource block. See “Syntax” section above for more information. ### Examples --- The following examples demonstrate various approaches for using the **ruby_block** resource in recipes: **Re-read configuration data** ``` ruby_block 'reload_client_config' do block do Chef::Config.from_file('/etc/chef/client.rb') end action :run end ``` **Run a block on a particular platform** The following example shows how an if statement can be used with the `windows?` method in the Chef Infra Language to run code specific to Microsoft Windows. The code is defined using the ruby_block resource: ``` if windows? ruby_block 'copy libmysql.dll into ruby path' do block do require 'fileutils' FileUtils.cp "#{node['mysql']['client']['lib_dir']}\\libmysql.dll", node['mysql']['client']['ruby_dir'] end not_if { ::File.exist?("#{node['mysql']['client']['ruby_dir']}\\libmysql.dll") } end end ``` **Stash a file in a data bag** The following example shows how to use the ruby_block resource to stash a BitTorrent file in a data bag so that it can be distributed to nodes in the organization. ``` ruby_block 'share the torrent file' do block do f = File.open(node['bittorrent']['torrent'],'rb') #read the .torrent file and base64 encode it enc = Base64.encode64(f.read) data = { 'id'=>bittorrent_item_id(node['bittorrent']['file']), 'seed'=>node.ipaddress, 'torrent'=>enc } item = Chef::DataBagItem.new item.data_bag('bittorrent') item.raw_data = data item.save end action :nothing subscribes :create, "bittorrent_torrent[#{node['bittorrent']['torrent']}]", :immediately end ``` **Update the /etc/hosts file** The following example shows how the ruby_block resource can be used to update the /etc/hosts file: ``` ruby_block 'edit etc hosts' do block do rc = Chef::Util::FileEdit.new('/etc/hosts') rc.search_file_replace_line(/^127\.0\.0\.1 localhost$/, '127.0.0.1 #{new_fqdn} #{new_hostname} localhost') rc.write_file end end ``` **Set environment variables** The following example shows how to use variables within a Ruby block to set environment variables using rbenv. ``` node.override[:rbenv][:root] = rbenv_root node.override[:ruby_build][:bin_path] = rbenv_binary_path ruby_block 'initialize' do block do ENV['RBENV_ROOT'] = node[:rbenv][:root] ENV['PATH'] = "#{node[:rbenv][:root]}/bin:#{node[:ruby_build][:bin_path]}:#{ENV['PATH']}" end end ``` **Call methods in a gem** The following example shows how to call methods in gems not shipped in Chef Infra Client ``` chef_gem 'mongodb' ruby_block 'config_replicaset' do block do MongoDB.configure_replicaset(node, replicaset_name, rs_nodes) end action :run end ``` script resource --------------- [script resource page](resources/script/index) --- Use the **script** resource to execute scripts using a specified interpreter, such as Bash, csh, Perl, Python, or Ruby. This resource may also use any of the actions and properties that are available to the **execute** resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use `not_if` and `only_if` to guard this resource for idempotence. This resource is the base resource for several other resources used for scripting on specific platforms. For more information about specific resources for specific platforms, see the following topics: * [bash](resources/bash/index) * [csh](resources/csh/index) * [ksh](resources/ksh/index) * [perl](resources/perl/index) * [python](resources/python/index) * [ruby](resources/ruby/index) Changed in 12.19 to support windows alternate user identity in execute resources ### Syntax --- A **script** resource block typically executes scripts using a specified interpreter, such as Bash, csh, Perl, Python, or Ruby: ``` script 'extract_module' do interpreter "bash" cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` where: * `interpreter` specifies the command shell to use * `cwd` specifies the directory from which the command is run * `code` specifies the command to run It is more common to use the **script**-based resource that is specific to the command shell. Chef has shell-specific resources for Bash, csh, ksh, Perl, Python, and Ruby. The same command as above, but run using the **bash** resource: ``` bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` The full syntax for all of the properties that are available to the **script** resource is: ``` script 'name' do code String creates String cwd String environment Hash flags String group String, Integer interpreter String path Array returns Integer, Array timeout Integer, Float user String password String domain String umask String, Integer action Symbol # defaults to :run if not specified end ``` where: * `script` is the resource * `name` is the name of the resource block * `cwd` is the location from which the command is run * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `code`, `creates`, `cwd`, `environment`, `flags`, `group`, `interpreter`, `path`, `returns`, `timeout`, `user`, `password`, `domain` and `umask` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **script** resource has the following actions: `:nothing` Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. `:run` Default. Run a script. ### Properties --- The **script** resource has the following properties: `code` **Ruby Type:** String A quoted (" “) string of code to be executed. `creates` **Ruby Type:** String Prevent a command from creating a file when that file already exists. `cwd` **Ruby Type:** String The current working directory from which the command will be run. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of `({"ENV_VARIABLE" => "VALUE"})`. (These variables must exist for a command to be run successfully.) `flags` **Ruby Type:** String One or more command line flags that are passed to the interpreter when a command is invoked. `group` **Ruby Type:** String, Integer The group name or group ID that must be changed before running a command. `interpreter` **Ruby Type:** String The script interpreter to use during code execution. `returns` **Ruby Type:** Integer, Array | **Default Value:** `0` The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. `timeout` **Ruby Type:** Integer, Float | **Default Value:** `3600` The amount of time (in seconds) a command is to wait before timing out. `user` **Ruby Type:** String The user name of the user identity with which to launch the new process. Default value: nil. The user name may optionally be specified with a domain, i.e. domainuser or [<EMAIL>](mailto:<EMAIL>) via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified. `password` **Ruby Type:** String *Windows only*: The password of the user specified by the user property. Default value: nil. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. `domain` **Ruby Type:** String *Windows only*: The domain of the user user specified by the user property. Default value: nil. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. `umask` **Ruby Type:** String, Integer The file mode creation mask, or umask. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Guard Interpreter Any resource that passes a string command may also specify the interpreter that will be used to evaluate that string command. This is done by using the `guard_interpreter` property to specify a **script**-based resource. **Attributes** The `guard_interpreter` property may be set to any of the following values: `:bash` Evaluates a string command using the **bash** resource. `:batch` Evaluates a string command using the **batch** resource. Default value (within a **batch** resource block): `:batch`. `:csh` Evaluates a string command using the **csh** resource. `:default` Default. Executes the default interpreter as identified by Chef Infra Client. `:perl` Evaluates a string command using the **perl** resource. `:powershell_script` Evaluates a string command using the **powershell_script** resource. Default value (within a **powershell_script** resource block): `:powershell_script`. `:python` Evaluates a string command using the **python** resource. `:ruby` Evaluates a string command using the **ruby** resource. **Inheritance** The `guard_interpreter` property is set to `:default` by default for the **bash**, **csh**, **perl**, **python**, and **ruby** resources. When the `guard_interpreter` property is set to `:default`, `not_if` or `only_if` guard statements **do not inherit** properties that are defined by the **script**-based resource. Warning The **batch** and **powershell_script** resources inherit properties by default. The `guard_interpreter` property is set to `:batch` or `:powershell_script` automatically when using a `not_if` or `only_if` guard statement within a **batch** or **powershell_script** resource, respectively. For example, the `not_if` guard statement in the following resource example **does not inherit** the `environment` property: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` and requires adding the `environment` property to the `not_if` guard statement so that it may use the `JAVA_HOME` path as part of its evaluation: ``` bash 'javatooling' do environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started', :environment => 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' end ``` To inherit properties, add the `guard_interpreter` property to the resource block and set it to the appropriate value: * `:bash` for **bash** * `:csh` for **csh** * `:perl` for **perl** * `:python` for **python** * `:ruby` for **ruby** For example, using the same example as from above, but this time adding the `guard_interpreter` property and setting it to `:bash`: ``` bash 'javatooling' do guard_interpreter :bash environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home' code 'java-based-daemon-ctl.sh -start' not_if 'java-based-daemon-ctl.sh -test-started' end ``` The `not_if` statement now inherits the `environment` property and will use the `JAVA_HOME` path as part of its evaluation. **Example** For example, the following code block will ensure the command is evaluated using the default interpreter as identified by Chef Infra Client: ``` resource 'name' do guard_interpreter :default # code end ``` ### Examples --- The following examples demonstrate various approaches for using the **script** resource in recipes: Use a named provider to run a script ``` bash 'install_something' do user 'root' cwd '/tmp' code <<-EOH wget http://www.example.com/tarball.tar.gz tar -zxf tarball.tar.gz cd tarball ./configure make make install EOH end ``` Run a script ``` script 'install_something' do interpreter 'bash' user 'root' cwd '/tmp' code <<-EOH wget http://www.example.com/tarball.tar.gz tar -zxf tarball.tar.gz cd tarball ./configure make make install EOH end ``` or something like: ``` bash 'openvpn-server-key' do environment('KEY_CN' => 'server') code <<-EOF openssl req -batch -days #{node['openvpn']['key']['expire']} \ -nodes -new -newkey rsa:#{key_size} -keyout #{key_dir}/server.key \ -out #{key_dir}/server.csr -extensions server \ -config #{key_dir}/openssl.cnf EOF not_if { File.exist?('#{key_dir}/server.crt') } end ``` where `code` contains the OpenSSL command to be run. The `not_if` property tells Chef Infra Client not to run the command if the file already exists. Install a file from a remote location using bash The following is an example of how to install the `foo123` module for Nginx. This module adds shell-style functionality to an Nginx configuration file and does the following: * Declares three variables * Gets the Nginx file from a remote location * Installs the file using Bash to the path specified by the `src_filepath` variable ``` # the following code sample is similar to the ``upload_progress_module`` # recipe in the ``nginx`` cookbook: # https://github.com/chef-cookbooks/nginx src_filename = "foo123-nginx-module-v#{ node['nginx']['foo123']['version'] }.tar.gz" src_filepath = "#{Chef::Config['file_cache_path']}/#{src_filename}" extract_path = "#{ Chef::Config['file_cache_path'] }/nginx_foo123_module/#{ node['nginx']['foo123']['checksum'] }" remote_file 'src_filepath' do source node['nginx']['foo123']['url'] checksum node['nginx']['foo123']['checksum'] owner 'root' group 'root' mode '0755' end bash 'extract_module' do cwd ::File.dirname(src_filepath) code <<-EOH mkdir -p #{extract_path} tar xzf #{src_filename} -C #{extract_path} mv #{extract_path}/*/* #{extract_path}/ EOH not_if { ::File.exist?(extract_path) } end ``` Install an application from git using bash The following example shows how Bash can be used to install a plug-in for rbenv named `ruby-build`, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which `ruby-build` is located, and then runs a command. ``` git "#{Chef::Config[:file_cache_path]}/ruby-build" do repository 'git://github.com/sstephenson/ruby-build.git' revision 'master' action :sync end bash 'install_ruby_build' do cwd "#{Chef::Config[:file_cache_path]}/ruby-build" user 'rbenv' group 'rbenv' code <<-EOH ./install.sh EOH environment 'PREFIX' => '/usr/local' end ``` To read more about `ruby-build`, see here: <https://github.com/sstephenson/ruby-build>. Store certain settings The following recipe shows how an attributes file can be used to store certain settings. An attributes file is located in the `attributes/` directory in the same cookbook as the recipe which calls the attributes file. In this example, the attributes file specifies certain settings for Python that are then used across all nodes against which this recipe will run. Python packages have versions, installation directories, URLs, and checksum files. An attributes file that exists to support this type of recipe would include settings like the following: ``` default['python']['version'] = '2.7.1' if python['install_method'] == 'package' default['python']['prefix_dir'] = '/usr' else default['python']['prefix_dir'] = '/usr/local' end default['python']['url'] = 'http://www.python.org/ftp/python' default['python']['checksum'] = '80e387...85fd61' ``` and then the methods in the recipe may refer to these values. A recipe that is used to install Python will need to do the following: * Identify each package to be installed (implied in this example, not shown) * Define variables for the package `version` and the `install_path` * Get the package from a remote location, but only if the package does not already exist on the target system * Use the **bash** resource to install the package on the node, but only when the package is not already installed ``` # the following code sample comes from the ``oc-nginx`` cookbook on |github|: https://github.com/cookbooks/oc-nginx version = node['python']['version'] install_path = "#{node['python']['prefix_dir']}/lib/python#{version.split(/(^\d+\.\d+)/)[1]}" remote_file "#{Chef::Config[:file_cache_path]}/Python-#{version}.tar.bz2" do source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2" checksum node['python']['checksum'] mode '0755' not_if { ::File.exist?(install_path) } end bash 'build-and-install-python' do cwd Chef::Config[:file_cache_path] code <<-EOF tar -jxvf Python-#{version}.tar.bz2 (cd Python-#{version} && ./configure #{configure_options}) (cd Python-#{version} && make && make install) EOF not_if { ::File.exist?(install_path) } end ``` Run a command as an alternate user *Note*: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator. This right can be added and checked in a recipe using this example: ``` # Add 'SeAssignPrimaryTokenPrivilege' for the user Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege') # Check if the user has 'SeAssignPrimaryTokenPrivilege' rights Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege') ``` The following example shows how to run `mkdir test_dir` from a Chef Infra Client run as an alternate user. ``` # Passing only username and password script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username" password "password" end # Passing username and domain script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] domain "domain-name" user "username" password "password" end # Passing username = 'domain-name\\username'. No domain is passed script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "domain-name\\username" password "password" end # Passing username = 'username@domain-name'. No domain is passed script 'mkdir test_dir' do interpreter "bash" code "mkdir test_dir" cwd Chef::Config[:file_cache_path] user "username@domain-name" password "password" end ``` service resource ---------------- [service resource page](resources/service/index) --- Use the **service** resource to manage a service. ### Syntax --- The full syntax for all of the properties that are available to the **service** resource is: ``` service 'name' do init_command String options Array, String parameters Hash pattern String priority Integer, String, Hash reload_command String, false restart_command String, false run_levels Array service_name String # default value: 'name' unless specified start_command String, false status_command String, false stop_command String, false supports Hash # default value: {"restart"=>nil, "reload"=>nil, "status"=>nil} timeout Integer # default value: 900 user String action Symbol # defaults to :nothing if not specified end ``` where: * `service` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `init_command`, `options`, `parameters`, `pattern`, `priority`, `reload_command`, `restart_command`, `run_levels`, `service_name`, `start_command`, `status_command`, `stop_command`, `supports`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **service** resource has the following actions: `:disable` Disable a service. This action is equivalent to a `Disabled` startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot. `:enable` Enable a service at boot. This action is equivalent to an `Automatic` startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:reload` Reload the configuration for this service. `:restart` Restart a service. `:start` Start a service, and keep it running until stopped or disabled. `:stop` Stop a service. ### Properties --- The **service** resource has the following properties: `init_command` **Ruby Type:** String The path to the init script that is associated with the service. Use `init_command` to prevent the need to specify overrides for the `start_command`, `stop_command`, and `restart_command` properties. When this property is not specified, Chef Infra Client will use the default init command for the service provider being used. `options` **Ruby Type:** Array, String Solaris platform only. Options to pass to the service command. See the `svcadm` manual for details of possible options. `parameters` **Ruby Type:** Hash Upstart only: A hash of parameters to pass to the service command for use in the service definition. `pattern` **Ruby Type:** String | **Default Value:** `The value provided to 'service_name' or the resource block's name` The pattern to look for in the process table. `priority` **Ruby Type:** Integer, String, Hash Debian platform only. The relative priority of the program for start and shutdown ordering. May be an integer or a Hash. An integer is used to define the start run levels; stop run levels are then 100-integer. A Hash is used to define values for specific run levels. For example, `{ 2 => [:start, 20], 3 => [:stop, 55] }` will set a priority of twenty for run level two and a priority of fifty-five for run level three. `reload_command` **Ruby Type:** String, false The command used to tell a service to reload its configuration. `restart_command` **Ruby Type:** String, false The command used to restart a service. `run_levels` **Ruby Type:** Array RHEL platforms only: Specific run_levels the service will run under. `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the service name if it differs from the resource block’s name. `start_command` **Ruby Type:** String, false The command used to start a service. `status_command` **Ruby Type:** String, false The command used to check the run status for a service. `stop_command` **Ruby Type:** String, false The command used to stop a service. `supports` **Ruby Type:** Hash | **Default Value:** `{"restart" => nil, "reload" => nil, "status" => nil}` A list of properties that controls how Chef Infra Client is to attempt to manage a service: `:restart`, `:reload`, `:status`. For `:restart`, the init script or other service provider can use a restart command; if `:restart` is not specified, Chef Infra Client attempts to stop and then start a service. For `:reload`, the init script or other service provider can use a reload command. For `:status`, the init script or other service provider can use a status command to determine if the service is running; if `:status` is not specified, Chef Infra Client attempts to match the `service_name` against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: `{ restart: false, reload: false, status: false }` for all platforms (except for the Red Hat platform family, which defaults to `{ restart: false, reload: false, status: true }`.) `timeout` **Ruby Type:** Integer | **Default Value:** `900` The amount of time (in seconds) to wait before timing out. `user` **Ruby Type:** String systemd only: A username to run the service under. New in Chef Client 12.21 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **service** resource in recipes: Start a service ``` service 'example_service' do action :start end ``` Start a service, enable it ``` service 'example_service' do supports status: true, restart: true, reload: true action [ :enable, :start ] end ``` Use a pattern ``` service 'samba' do pattern 'smbd' action [:enable, :start] end ``` Use the :nothing common action ``` service 'memcached' do action :nothing end ``` Use the retries common attribute ``` service 'apache' do action [ :enable, :start ] retries 3 end ``` Manage a service, depending on the node platform ``` service 'example_service' do if redhat? service_name 'redhat_name' else service_name 'other_name' end supports restart: true action [ :enable, :start ] end ``` Reload a service using a template To reload a service that is based on a template, use the **template** and **service** resources together in the same recipe, similar to the following: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' end service 'apache' do action :enable subscribes :reload, 'template[/tmp/somefile]', :immediately end ``` where the `subscribes` notification is used to reload the service whenever the template is modified. Enable a service after a restart or reload ``` service 'apache' do supports restart: true, reload: true action :enable end ``` Set an IP address using variables and a template The following example shows how the **template** resource can be used in a recipe to combine settings stored in an attributes file, variables within a recipe, and a template to set the IP addresses that are used by the Nginx service. The attributes file contains the following: ``` default['nginx']['dir'] = '/etc/nginx' ``` The recipe then does the following to: * Declare two variables at the beginning of the recipe, one for the remote IP address and the other for the authorized IP address * Use the **service** resource to restart and reload the Nginx service * Load a template named `authorized_ip.erb` from the `/templates` directory that is used to set the IP address values based on the variables specified in the recipe ``` node.default['nginx']['remote_ip_var'] = 'remote_addr' node.default['nginx']['authorized_ips'] = ['127.0.0.1/32'] service 'nginx' do supports :status => true, :restart => true, :reload => true end template 'authorized_ip' do path "#{node['nginx']['dir']}/authorized_ip" source 'modules/authorized_ip.erb' owner 'root' group 'root' mode '0755' variables( :remote_ip_var => node['nginx']['remote_ip_var'], :authorized_ips => node['nginx']['authorized_ips'] ) notifies :reload, 'service[nginx]', :immediately end ``` where the `variables` property tells the template to use the variables set at the beginning of the recipe and the `source` property is used to call a template file located in the cookbook’s `/templates` directory. The template file looks similar to: ``` geo $<%= @remote_ip_var %> $authorized_ip { default no; <% @authorized_ips.each do |ip| %> <%= "#{ip} yes;" %> <% end %> } ``` Use a cron timer to manage a service The following example shows how to install the crond application using two resources and a variable: ``` # the following code sample comes from the ``cron`` cookbook: # https://github.com/chef-cookbooks/cron cron_package = case node['platform'] when 'redhat', 'centos', 'scientific', 'fedora', 'amazon' node['platform_version'].to_f >= 6.0 ? 'cronie' : 'vixie-cron' else 'cron' end package cron_package do action :install end service 'crond' do case node['platform'] when 'redhat', 'centos', 'scientific', 'fedora', 'amazon' service_name 'crond' when 'debian', 'ubuntu', 'suse' service_name 'cron' end action [:start, :enable] end ``` where * `cron_package` is a variable that is used to identify which platforms apply to which install packages * the **package** resource uses the `cron_package` variable to determine how to install the crond application on various nodes (with various platforms) * the **service** resource enables the crond application on nodes that have Red Hat, CentOS, Red Hat Enterprise Linux, Fedora, or Amazon Web Services (AWS), and the cron service on nodes that run Debian, Ubuntu, or openSUSE Restart a service, and then notify a different service The following example shows how start a service named `example_service` and immediately notify the Nginx service to restart. ``` service 'example_service' do action :start notifies :restart, 'service[nginx]', :immediately end ``` Restart one service before restarting another This example uses the `:before` notification to restart the `php-fpm` service before restarting `nginx`: ``` service 'nginx' do action :restart notifies :restart, 'service[php-fpm]', :before end ``` With the `:before` notification, the action specified for the `nginx` resource will not run until action has been taken on the notified resource (`php-fpm`). Stop a service, do stuff, and then restart it The following example shows how to use the **execute**, **service**, and **mount** resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following: * Checks to see if the Amazon EC2 node has MySQL * If the node has MySQL, stops MySQL * Installs MySQL * Mounts the node * Restarts MySQL ``` # the following code sample comes from the ``server_ec2`` # recipe in the following cookbook: # https://github.com/chef-cookbooks/mysql if (node.attribute?('ec2') && ! FileTest.directory?(node['mysql']['ec2_path'])) service 'mysql' do action :stop end execute 'install-mysql' do command "mv #{node['mysql']['data_dir']}#{node['mysql']['ec2_path']}" not_if do FileTest.directory?(node['mysql']['ec2_path']) end end [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir| directory dir do owner 'mysql' group 'mysql' end end mount node['mysql']['data_dir'] do device node['mysql']['ec2_path'] fstype 'none' options 'bind,rw' action [:mount, :enable] end service 'mysql' do action :start end end ``` where * the two **service** resources are used to stop, and then restart the MySQL service * the **execute** resource is used to install MySQL * the **mount** resource is used to mount the node and enable MySQL Control a service using the execute resource Warning This is an example of something that should NOT be done. Use the **service** resource to control a service, not the **execute** resource. Do something like this: ``` service 'tomcat' do action :start end ``` and NOT something like this: ``` execute 'start-tomcat' do command '/etc/init.d/tomcat6 start' action :run end ``` There is no reason to use the **execute** resource to control a service because the **service** resource exposes the `start_command` property directly, which gives a recipe full control over the command issued in a much cleaner, more direct manner. Enable a service on AIX using the mkitab command The **service** resource does not support using the `:enable` and `:disable` actions with resources that are managed using System Resource Controller (SRC). This is because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot. One approach for enabling or disabling services that are managed by System Resource Controller (SRC) is to use the **execute** resource to invoke `mkitab`, and then use that command to enable or disable the service. The following example shows how to install a service: ``` execute "install #{node['chef_client']['svc_name']} in SRC" do command "mkssys -s #{node['chef_client']['svc_name']} -p #{node['chef_client']['bin']} -u root -S -n 15 -f 9 -o #{node['chef_client']['log_dir']}/client.log -e #{node['chef_client']['log_dir']}/client.log -a ' -i #{node['chef_client']['interval']} -s #{node['chef_client']['splay']}'" not_if "lssrc -s #{node['chef_client']['svc_name']}" action :run end ``` and then enable it using the `mkitab` command: ``` execute "enable #{node['chef_client']['svc_name']}" do command "mkitab '#{node['chef_client']['svc_name']}:2:once:/usr/bin/startsrc -s #{node['chef_client']['svc_name']} > /dev/console 2>&1'" not_if "lsitab #{node['chef_client']['svc_name']}" end ``` smartos_package resource ------------------------- [smartos_package resource page](resources/smartos_package/index) --- Use the **smartos_package** resource to manage packages for the SmartOS platform. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- The full syntax for all of the properties that are available to the **smartos_package** resource is: ``` smartos_package 'name' do options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `smartos_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **smartos_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **smartos_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. snap_package resource ---------------------- [snap_package resource page](resources/snap_package/index) --- Use the **snap_package** resource to manage snap packages on Debian and Ubuntu platforms. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **snap_package** resource is: ``` snap_package 'name' do channel String # default value: "stable" options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `snap_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `channel`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **snap_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:lock` Locks the apt package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:unlock` Unlocks the apt package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **snap_package** resource has the following properties: `channel` **Ruby Type:** String | **Default Value:** `stable` **Allowed Values:** `"beta", "candidate", "edge", "stable"` The default channel. For example: stable. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- This resource does not have any examples. solaris_package resource ------------------------- [solaris_package resource page](resources/solaris_package/index) --- Use the **solaris_package** resource to manage packages on the Solaris platform. ### Syntax --- The full syntax for all of the properties that are available to the **solaris_package** resource is: ``` solaris_package 'name' do options String, Array package_name String source String timeout String, Integer version String action Symbol # defaults to :install if not specified end ``` where: * `solaris_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **solaris_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. ### Properties --- The **solaris_package** resource has the following properties: `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **solaris_package** resource in recipes: Install a package ``` solaris_package 'name of package' do source '/packages_directory' action :install end ``` ssh_known_hosts_entry resource --------------------------------- [ssh_known_hosts_entry resource page](resources/ssh_known_hosts_entry/index) --- Use the **ssh_known_hosts_entry** resource to add an entry for the specified host in /etc/ssh/ssh_known_hosts or a user’s known hosts file if specified. **New in Chef Infra Client 14.3.** ### Syntax --- The full syntax for all of the properties that are available to the **ssh_known_hosts_entry** resource is: ``` ssh_known_hosts_entry 'name' do file_location String # default value: "/etc/ssh/ssh_known_hosts" group String, Integer # default value: The root user's group depending on platform. hash_entries true, false # default value: false host String # default value: 'name' unless specified key String key_type String # default value: "rsa" mode String # default value: "0644" owner String, Integer # default value: "root" port Integer # default value: 22 timeout Integer # default value: 30 action Symbol # defaults to :create if not specified end ``` where: * `ssh_known_hosts_entry` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `file_location`, `group`, `hash_entries`, `host`, `key`, `key_type`, `mode`, `owner`, `port`, and `timeout` are the properties available to this resource. ### Actions --- The **ssh_known_hosts_entry** resource has the following actions: `:create` Create an entry in the ssh_known_hosts file. (default) `:flush` Immediately flush the entries to the config file. Without this the actual writing of the file is delayed in the Chef Infra Client run so all entries can be accumulated before writing the file out. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **ssh_known_hosts_entry** resource has the following properties: `file_location` **Ruby Type:** String | **Default Value:** `/etc/ssh/ssh_known_hosts` The location of the ssh known hosts file. Change this to set a known host file for a particular user. `group` **Ruby Type:** String, Integer | **Default Value:** `The root user's group depending on platform.` The file group for the ssh_known_hosts file. `hash_entries` **Ruby Type:** true, false | **Default Value:** `false` Hash the hostname and addresses in the ssh_known_hosts file for privacy. `host` **Ruby Type:** String | **Default Value:** `The resource block's name` The host to add to the known hosts file. `key` **Ruby Type:** String An optional key for the host. If not provided this will be automatically determined. `key_type` **Ruby Type:** String | **Default Value:** `rsa` The type of key to store. `mode` **Ruby Type:** String | **Default Value:** `0644` The file mode for the ssh_known_hosts file. `owner` **Ruby Type:** String, Integer | **Default Value:** `root` The file owner for the ssh_known_hosts file. `port` **Ruby Type:** Integer | **Default Value:** `22` The server port that the ssh-keyscan command will use to gather the public key. `timeout` **Ruby Type:** Integer | **Default Value:** `30` The timeout in seconds for ssh-keyscan. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **ssh_known_hosts_entry** resource in recipes: **Add a single entry for github.com with the key auto detected** ``` ssh_known_hosts_entry 'github.com' ``` **Add a single entry with your own provided key** ``` ssh_known_hosts_entry 'github.com' do key 'node.example.com ssh-rsa ...' end ``` subversion resource ------------------- [subversion resource page](resources/subversion/index) --- Use the **subversion** resource to manage source control resources that exist in a Subversion repository. Warning The subversion resource has known bugs and may not work as expected. For more information see Chef GitHub issues, particularly [#4050](https://github.com/chef/chef/issues/4050) and [#4257](https://github.com/chef/chef/issues/4257). ### Syntax --- The full syntax for all of the properties that are available to the **subversion** resource is: ``` subversion 'name' do destination String # default value: 'name' unless specified environment Hash group String, Integer repository String revision String # default value: "HEAD" svn_arguments String, false # default value: "--no-auth-cache" svn_binary String svn_info_args String, false # default value: "--no-auth-cache" svn_password String svn_username String timeout Integer user String, Integer action Symbol # defaults to :sync if not specified end ``` where: * `subversion` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `destination`, `environment`, `group`, `repository`, `revision`, `svn_arguments`, `svn_binary`, `svn_info_args`, `svn_password`, `svn_username`, `timeout`, and `user` are the properties available to this resource. ### Actions --- The **subversion** resource has the following actions: `:checkout` Clone or check out the source. When a checkout is available, this provider does nothing. `:export` Export the source, excluding or removing any version control artifacts. `:force_export` Export the source, excluding or removing any version control artifacts and force an export of the source that is overwriting the existing copy (if it exists). `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:sync` Update the source to the specified version, or get a new clone or checkout. This action causes a hard reset of the index and working tree, discarding any uncommitted changes. (default) ### Properties --- The **subversion** resource has the following properties: `destination` **Ruby Type:** String | **Default Value:** `The resource block's name` The location path to which the source is to be cloned, checked out, or exported. Default value: the name of the resource block. `environment` **Ruby Type:** Hash A Hash of environment variables in the form of ({‘ENV_VARIABLE’ => ‘VALUE’}). `group` **Ruby Type:** String, Integer The system group that will own the checked-out code. `repository` **Ruby Type:** String The URI of the code repository. `revision` **Ruby Type:** String | **Default Value:** `HEAD` A branch, tag, or commit to be synchronized with git. This can be symbolic, like `HEAD` or it can be a source control management-specific revision identifier. `svn_arguments` **Ruby Type:** String, false | **Default Value:** `--no-auth-cache` The extra arguments that are passed to the Subversion command. `svn_binary` **Ruby Type:** String The location of the svn binary. `svn_info_args` **Ruby Type:** String, false | **Default Value:** `--no-auth-cache` Use when the `svn info` command is used by Chef Infra Client and arguments need to be passed. The `svn_arguments` command does not work when the `svn info` command is used. `svn_password` **Ruby Type:** String The password for a user that has access to the Subversion repository. `svn_username` **Ruby Type:** String The user name for a user that has access to the Subversion repository. `timeout` **Ruby Type:** Integer The amount of time (in seconds) to wait before timing out. `user` **Ruby Type:** String, Integer | **Default Value:** ``HOME` environment variable of the user running chef-client` The system user that will own the checked-out code. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **subversion** resource in recipes: **Get the latest version of an application** ``` subversion 'CouchDB Edge' do repository 'http://svn.apache.org/repos/asf/couchdb/trunk' revision 'HEAD' destination '/opt/my_sources/couch' action :sync end ``` sudo resource ------------- [sudo resource page](resources/sudo/index) --- Use the **sudo** resource to add or remove individual sudo entries using sudoers.d files. Sudo version 1.7.2 or newer is required to use the sudo resource, as it relies on the `#includedir` directive introduced in version 1.7.2. This resource does not enforce installation of the required sudo version. Chef-supported releases of Ubuntu, SuSE, Debian, and RHEL (6+) all support this feature. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **sudo** resource is: ``` sudo 'name' do command_aliases Array # default value: [] commands Array # default value: ["ALL"] config_prefix String # default value: "Prefix values based on the node's platform" defaults Array # default value: [] env_keep_add Array # default value: [] env_keep_subtract Array # default value: [] filename String # default value: 'name' unless specified groups String, Array # default value: [] host String # default value: "ALL" noexec true, false # default value: false nopasswd true, false # default value: false runas String # default value: "ALL" setenv true, false # default value: false template String users String, Array # default value: [] variables Hash visudo_binary String # default value: "/usr/sbin/visudo" action Symbol # defaults to :create if not specified end ``` where: * `sudo` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `command_aliases`, `commands`, `config_prefix`, `defaults`, `env_keep_add`, `env_keep_subtract`, `filename`, `groups`, `host`, `noexec`, `nopasswd`, `runas`, `setenv`, `template`, `users`, `variables`, and `visudo_binary` are the properties available to this resource. ### Actions --- The **sudo** resource has the following actions: `:create` Create a single sudoers configuration file in the `sudoers.d` directory. (default) `:delete` Remove a sudoers configuration file from the `sudoers.d` directory. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **sudo** resource has the following properties: `command_aliases` **Ruby Type:** Array | **Default Value:** `[]` Command aliases that can be used as allowed commands later in the configuration. `commands` **Ruby Type:** Array | **Default Value:** `["ALL"]` An array of full paths to commands this sudoer can execute. `config_prefix` **Ruby Type:** String | **Default Value:** `Prefix values based on the node's platform` The directory that contains the sudoers configuration file. `defaults` **Ruby Type:** Array | **Default Value:** `[]` An array of defaults for the user/group. `env_keep_add` **Ruby Type:** Array | **Default Value:** `[]` An array of strings to add to `env_keep`. `env_keep_subtract` **Ruby Type:** Array | **Default Value:** `[]` An array of strings to remove from `env_keep`. `filename` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the sudoers.d file if it differs from the name of the resource block `groups` **Ruby Type:** String, Array | **Default Value:** `[]` Group(s) to provide sudo privileges to. This property accepts either an array or a comma separated list. Leading % on group names is optional. `host` **Ruby Type:** String | **Default Value:** `ALL` The host to set in the sudo configuration. `noexec` **Ruby Type:** true, false | **Default Value:** `false` Prevent commands from shelling out. `nopasswd` **Ruby Type:** true, false | **Default Value:** `false` Allow sudo to be run without specifying a password. `runas` **Ruby Type:** String | **Default Value:** `ALL` User that the command(s) can be run as. `setenv` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not to permit preservation of the environment with `sudo -E`. `template` **Ruby Type:** String The name of the erb template in your cookbook, if you wish to supply your own template. `users` **Ruby Type:** String, Array | **Default Value:** `[]` User(s) to provide sudo privileges to. This property accepts either an array or a comma separated list. `variables` **Ruby Type:** Hash The variables to pass to the custom template. This property is ignored if not using a custom template. `visudo_binary` **Ruby Type:** String | **Default Value:** `/usr/sbin/visudo` The path to visudo for configuration verification. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **sudo** resource in recipes: **Grant a user sudo privileges for any command** ``` sudo 'admin' do user 'admin' end ``` **Grant a user and groups sudo privileges for any command** ``` sudo 'admins' do users 'bob' groups 'sysadmins, superusers' end ``` **Grant passwordless sudo privileges for specific commands** ``` sudo 'passwordless-access' do commands ['/bin/systemctl restart httpd', '/bin/systemctl restart mysql'] nopasswd true end ``` swap_file resource ------------------- [swap_file resource page](resources/swap_file/index) --- Use the **swap_file** resource to create or delete swap files on Linux systems, and optionally to manage the swappiness configuration for a host. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **swap_file** resource is: ``` swap_file 'name' do path String # default value: 'name' unless specified persist true, false # default value: false size Integer swappiness Integer timeout Integer # default value: 600 action Symbol # defaults to :create if not specified end ``` where: * `swap_file` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `path`, `persist`, `size`, `swappiness`, and `timeout` are the properties available to this resource. ### Actions --- The **swap_file** resource has the following actions: `:create` Create a swapfile. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a swapfile and disable swap. ### Properties --- The **swap_file** resource has the following properties: `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The path where the swap file will be created on the system if it differs from the resource block’s name. `persist` **Ruby Type:** true, false | **Default Value:** `false` Persist the swapon. `size` **Ruby Type:** Integer The size (in MBs) of the swap file. `swappiness` **Ruby Type:** Integer The swappiness value to set on the system. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Timeout for `dd` / `fallocate` commands. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **swap_file** resource in recipes: **Create a swap file** ``` swap_file '/dev/sda1' do size 1024 end ``` **Remove a swap file** ``` swap_file '/dev/sda1' do action :remove end ``` sysctl resource --------------- [sysctl resource page](resources/sysctl/index) --- Use the **sysctl** resource to set or remove kernel parameters using the `sysctl` command line tool and configuration files in the system’s `sysctl.d` directory. Configuration files managed by this resource are named `99-chef-KEYNAME.conf`. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **sysctl** resource is: ``` sysctl 'name' do comment Array, String # default value: [] conf_dir String # default value: "/etc/sysctl.d" ignore_error true, false # default value: false key String # default value: 'name' unless specified value Array, String, Integer, Float action Symbol # defaults to :apply if not specified end ``` where: * `sysctl` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `comment`, `conf_dir`, `ignore_error`, `key`, and `value` are the properties available to this resource. ### Actions --- The **sysctl** resource has the following actions: `:apply` Set the kernel parameter and update the `sysctl` settings. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove the kernel parameter and update the `sysctl` settings. ### Properties --- The **sysctl** resource has the following properties: `comment` **Ruby Type:** Array, String | **Default Value:** `[]` Comments, placed above the resource setting in the generated file. For multi-line comments, use an array of strings, one per line. New in Chef Infra Client 15.8 `conf_dir` **Ruby Type:** String | **Default Value:** `/etc/sysctl.d` The configuration directory to write the config to. `ignore_error` **Ruby Type:** true, false | **Default Value:** `false` Ignore any errors when setting the value on the command line. `key` **Ruby Type:** String | **Default Value:** `The resource block's name` The kernel parameter key in dotted format if it differs from the resource block’s name. `value` **Ruby Type:** Array, String, Integer, Float | `REQUIRED` The value to set. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **sysctl** resource in recipes: **Set vm.swappiness**: ``` sysctl 'vm.swappiness' do value 19 end ``` **Remove kernel.msgmax**: **Note**: This only removes the sysctl.d config for kernel.msgmax. The value will be set back to the kernel default value. ``` sysctl 'kernel.msgmax' do action :remove end ``` **Adding Comments to sysctl configuration files**: ``` sysctl 'vm.swappiness' do value 19 comment "define how aggressively the kernel will swap memory pages." end ``` This produces /etc/sysctl.d/99-chef-vm.swappiness.conf as follows: ``` # define how aggressively the kernel will swap memory pages. vm.swappiness = 1 ``` **Converting sysctl settings from shell scripts**: Example of existing settings: ``` fs.aio-max-nr = 1048576 net.ipv4.ip_local_port_range = 9000 65500 kernel.sem = 250 32000 100 128 ``` Converted to sysctl resources: ``` sysctl 'fs.aio-max-nr' do value '1048576' end sysctl 'net.ipv4.ip_local_port_range' do value '9000 65500' end sysctl 'kernel.sem' do value '250 32000 100 128' end ``` systemd_unit resource ---------------------- [systemd_unit resource page](resources/systemd_unit/index) --- Use the **systemd_unit** resource to create, manage, and run [systemd units](https://www.freedesktop.org/software/systemd/man/systemd.html#Concepts). **New in Chef Infra Client 12.11.** ### Syntax --- The full syntax for all of the properties that are available to the **systemd_unit** resource is: ``` systemd_unit 'name' do content String, Hash triggers_reload true, false # default value: true unit_name String # default value: 'name' unless specified user String verify true, false # default value: true action Symbol # defaults to :nothing if not specified end ``` where: * `systemd_unit` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `content`, `triggers_reload`, `unit_name`, `user`, and `verify` are the properties available to this resource. ### Actions --- The **systemd_unit** resource has the following actions: `:create` Create a systemd unit file, if it does not already exist. `:delete` Delete a systemd unit file, if it exists. `:disable` Ensure the unit will not be started after the next system boot. `:enable` Ensure the unit will be started after the next system boot. `:mask` Ensure the unit will not start, even to satisfy dependencies. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:preset` Restore the preset ‘`enable`/`disable`’ configuration for a systemd unit. *New in Chef Infra Client 14.0.* `:reenable` Reenable a unit file. *New in Chef Infra Client 14.0.* `:reload` Reload the configuration file for a systemd unit. `:reload_or_restart` For systemd units that are services, this action reloads the configuration of the service without restarting, if possible; otherwise, it will restart the service so the new configuration is applied. `:reload_or_try_restart` For systemd units that are services, this action reloads the configuration of the service without restarting, if possible; otherwise, it will try to restart the service so the new configuration is applied. `:restart` Restart a systemd unit. `:revert` Revert to a vendor’s version of a systemd unit file. *New in Chef Infra Client 14.0.* `:start` Start a systemd unit. `:stop` Stop a running systemd unit. `:try_restart` Try to restart a systemd unit if the unit is running. `:unmask` Stop the unit from being masked and cause it to start as specified. ### Properties --- The **systemd_unit** resource has the following properties: `content` **Ruby Type:** String, Hash A string or hash that contains a systemd [unit file](https://www.freedesktop.org/software/systemd/man/systemd.unit.html) definition that describes the properties of systemd-managed entities, such as services, sockets, devices, and so on. In Chef Infra Client 14.4 or later, repeatable options can be implemented with an array. `triggers_reload` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether to trigger a daemon reload when creating or deleting a unit. `unit_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the unit file if it differs from the resource block’s name. New in Chef Client 13.7 `user` **Ruby Type:** String The user account that the systemd unit process is run under. The path to the unit for that user would be something like ‘/etc/systemd/user/sshd.service’. If no user account is specified, the systemd unit will run under a ‘system’ account, with the path to the unit being something like ‘/etc/systemd/system/sshd.service’. `verify` **Ruby Type:** true, false | **Default Value:** `true` Specifies if the unit will be verified before installation. Systemd can be overly strict when verifying units, so in certain cases it is preferable not to verify the unit. ### Unit file verification The unit file is verified via a `systemd-analyze verify` call before being written to disk. Be aware that the referenced commands and files need to already exist before verification. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **systemd_unit** resource in recipes: **Create systemd service unit file from a Hash** ``` systemd_unit 'etcd.service' do content({ Unit: { Description: 'Etcd', Documentation: ['https://coreos.com/etcd', 'man:etcd(1)'], After: 'network.target', }, Service: { Type: 'notify', ExecStart: '/usr/local/etcd', Restart: 'always', }, Install: { WantedBy: 'multi-user.target', } }) action [:create, :enable] end ``` **Create systemd service unit file from a String** ``` systemd_unit 'sysstat-collect.timer' do content <<~EOU [Unit] Description=Run system activity accounting tool every 10 minutes [Timer] OnCalendar=*:00/10 [Install] WantedBy=sysstat.service EOU action [:create, :enable] end ``` template resource ----------------- [template resource page](resources/template/index) --- A cookbook template is an Embedded Ruby (ERB) template that is used to dynamically generate static text files. Templates may contain Ruby expressions and statements, and are a great way to manage configuration files. Use the **template** resource to add cookbook templates to recipes; place the corresponding Embedded Ruby (ERB) template file in a cookbook’s `/templates` directory. Use the **template** resource to manage the contents of a file using an Embedded Ruby (ERB) template by transferring files from a sub-directory of `COOKBOOK_NAME/templates/` to a specified path located on a host that is running Chef Infra Client. This resource includes actions and properties from the **file** resource. Template files managed by the **template** resource follow the same file specificity rules as the **remote_file** and **file** resources. ### Syntax --- A **template** resource block typically declares the location in which a file is to be created, the source template that will be used to create the file, and the permissions needed on that file. For example: ``` template '/etc/motd' do source 'motd.erb' owner 'root' group 'root' mode '0755' end ``` where: * `'/etc/motd'` specifies the location in which the file is created * `'motd.erb'` specifies the name of a template that exists in in the `/templates` folder of a cookbook * `owner`, `group`, and `mode` define the permissions The full syntax for all of the properties that are available to the **template** resource is: ``` template 'name' do atomic_update true, false backup false, Integer cookbook String force_unlink true, false group String, Integer helper(:method) Method { String } # see Helpers below helpers(module) Module # see Helpers below inherits true, false local true, false manage_symlink_source true, false mode String, Integer owner String, Integer path String # defaults to 'name' if not specified rights Hash sensitive true, false source String, Array variables Hash verify String, Block action Symbol # defaults to :create if not specified end ``` where: * `template` is the resource * `name` is the name of the resource block, typically the path to the location in which a file is created *and also* the name of the file to be managed. For example: `/var/www/html/index.html`, where `/var/www/html/` is the fully qualified path to the location and `index.html` is the name of the file * `source` is the template file that will be used to create the file on the node, for example: `index.html.erb`; the template file is located in the `/templates` directory of a cookbook * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `atomic_update`, `backup`, `cookbook`, `force_unlink`, `group`, `helper`, `helpers`, `inherits`, `local`, `manage_symlink_source`, `mode`, `owner`, `path`, `rights`, `source`, `variables`, and `verify` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **template** resource has the following actions: `:create` Default. Create a file. If a file already exists (but does not match), update that file to match. `:create_if_missing` Create a file only if the file does not exist. When the file exists, nothing happens. `:delete` Delete a file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:touch` Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the **file** resource.) ### Properties --- The **template** resource has the following properties: `atomic_update` **Ruby Type:** true, false Perform atomic file updates on a per-resource basis. Set to `true` for atomic file updates. Set to `false` for non-atomic file updates. This setting overrides `file_atomic_update`, which is a global setting found in the client.rb file. `backup` **Ruby Type:** Integer, false | **Default Value:** `5` The number of backups to be kept in `/var/chef/backup` (for UNIX- and Linux-based platforms) or `C:/chef/backup` (for the Microsoft Windows platform). Set to `false` to prevent backups from being kept. `cookbook` **Ruby Type:** String The cookbook in which a file is located (if it is not located in the current cookbook). The default value is the current cookbook. `force_unlink` **Ruby Type:** true, false | **Default Value:** `false` How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to `false` for Chef Infra Client to raise an error. `group` **Ruby Type:** Integer, String A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as `domain\group` or `group@domain`. If this value is not specified, existing groups remain unchanged and new group assignments use the default `POSIX` group (if available). `helper` **Ruby Type:** Method | **Default Value:** `{}` Define a helper method inline. For example: `helper(:hello_world) { "hello world" }` or `helper(:app) { node["app"] }` or `helper(:app_conf) { |setting| node["app"][setting] }`. `helpers` **Ruby Type:** Module | **Default Value:** `[]` Define a helper module inline or in a library. For example, an inline module: `helpers do`, which is then followed by a block of Ruby code. And for a library module: `helpers(MyHelperModule)`. `inherits` **Ruby Type:** true, false | **Default Value:** `true` Microsoft Windows only. Whether a file inherits rights from its parent directory. `local` **Ruby Type:** true, false | **Default Value:** `false` Load a template from a local path. By default, Chef Infra Client loads templates from a cookbook’s `/templates` directory. When this property is set to `true`, use the `source` property to specify the path to a template on the local node. `manage_symlink_source` **Ruby Type:** true, false | **Default Value:** `true` (with warning) Change the behavior of the file resource if it is pointed at a symlink. When this value is set to `true`, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to `false`, Chef will follow the symlink and will manage the permissions and content of the symlink’s target file. The default behavior is `true` but emits a warning that the default value will be changed to `false` in a future version; setting this explicitly to `true` or `false` suppresses this warning. `mode` **Ruby Type:** Integer, String A quoted 3-5 character string that defines the octal mode. For example: `'755'`, `'0755'`, or `00755`. If `mode` is not specified and if the file already exists, the existing mode on the file is used. If `mode` is not specified, the file does not exist, and the `:create` action is specified, Chef Infra Client assumes a mask value of `'0777'` and then applies the umask for the system on which the file is to be created to the `mask` value. For example, if the umask on a system is `'022'`, Chef Infra Client uses the default value of `'0755'`. The behavior is different depending on the platform. UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: `'755'`, `'0755'`, or `00755`. If the value is specified as a quoted string, it works exactly as if the `chmod` command was passed. If the value is specified as an integer, prepend a zero (`0`) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use `'0777'` or `'777'`; for the same rights, plus the sticky bit, use `01777` or `'1777'`. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: `'755'`, `'0755'`, or `00755`. Values up to `'0777'` are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where `4` equals `GENERIC_READ`, `2` equals `GENERIC_WRITE`, and `1` equals `GENERIC_EXECUTE`. This property cannot be used to set `:full_control`. This property has no effect if not specified, but when it and `rights` are both specified, the effects are cumulative. `owner` **Ruby Type:** Integer, String A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as `domain\user` or `user@domain`. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). `path` **Ruby Type:** String | **Default Value:** `The resource block's name` The full path to the file, including the file name and its extension. Microsoft Windows: A path that begins with a forward slash (`/`) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (`/`) is not recommended. `rights` **Ruby Type:** Integer, String Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: `rights <permissions>, <principal>, <options>` where `<permissions>` specifies the rights granted to the principal, `<principal>` is the group or user name, and `<options>` is a Hash with one (or more) advanced rights options. `source` **Ruby Type:** String, Array The location of a template file. By default, Chef Infra Client looks for a template file in the `/templates` directory of a cookbook. When the `local` property is set to `true`, use to specify the path to a template on the local node. This property may also be used to distribute specific files to specific platforms. See “File Specificity” below for more information. Default value: the `name` of the resource block. See “Syntax” section above for more information. `variables` **Ruby Type:** Hash A Hash of variables that are passed into a Ruby template file. The `variables` property of the **template** resource can be used to reference a partial template file by using a Hash. For example: ``` template '/file/name.txt' do variables partials: { 'partial_name_1.txt.erb' => 'message', 'partial_name_2.txt.erb' => 'message', 'partial_name_3.txt.erb' => 'message', } end ``` where each of the partial template files can then be combined using normal Ruby template patterns within a template file, such as: ``` <% @partials.each do |partial, message| %> Here is <%= partial %> <%= render partial, :variables => {:message => message} %> <% end %``` `verify` **Ruby Type:** String, Block A block or a string that returns `true` or `false`. A string, when `true` is executed as a system command. A block is arbitrary Ruby defined within the resource block by using the `verify` property. When a block is `true`, Chef Infra Client will continue to update the file as appropriate. For example, this should return `true`: ``` template '/tmp/baz' do verify { 1 == 1 } end ``` This should return `true`: ``` template '/etc/nginx.conf' do verify 'nginx -t -c %{path}' end ``` This should return `true`: ``` template '/tmp/bar' do verify { 1 == 1} end ``` And this should return `true`: ``` template '/tmp/foo' do verify do |path| true end end ``` Whereas, this should return `false`: ``` template '/tmp/turtle' do verify '/usr/bin/false' end ``` If a string or a block return `false`, the Chef Infra Client run will stop and an error is returned. #### Atomic File Updates Atomic updates are used with **file**-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the `file_atomic_update` setting in the client.rb file. They can be managed on a per-resource basis using the `atomic_update` property that is available with the **cookbook_file**, **file**, **remote_file**, and **template** resources. Note On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the `restorecon` command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected. #### Windows File Security To support Microsoft Windows security, the **template**, **file**, **remote_file**, **cookbook_file**, **directory**, and **remote_directory** resources support the use of inheritance and access control lists (ACLs) within recipes. **Access Control Lists (ACLs)** The `rights` property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the `rights` property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the `rights` property is as follows: ``` rights permission, principal, option_type => value ``` where `permission` Use to specify which rights are granted to the `principal`. The possible values are: `:read`, `:write`, `read_execute`, `:modify`, `:full_control`, or an integer. Integers used for permissions must match the following list [FileSystemRights Enum](https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=windowsdesktop-5.0#fields) fields. ``` These permissions are cumulative. If `:write` is specified, then it includes `:read`. If `:full_control` is specified, then it includes both `:write` and `:read`. (For those who know the Microsoft Windows API: `:read` corresponds to `GENERIC_READ`; `:write` corresponds to `GENERIC_WRITE`; `:read_execute` corresponds to `GENERIC_READ` and `GENERIC_EXECUTE`; `:modify` corresponds to `GENERIC_WRITE`, `GENERIC_READ`, `GENERIC_EXECUTE`, and `DELETE`; `:full_control` corresponds to `GENERIC_ALL`, which allows a user to change the owner and other metadata about a file.) ``` `principal` Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as `user_name`, `domain\user_name`, or `user_name@fully_qualified_domain_name`. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). Chef Infra Client does not need to know if a principal is a user or a group. `option_type` A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: `rights :write, 'domain\group_name', :one_level_deep => true`. Possible option types: | Option Type | Description | | --- | --- | | `:applies_to_children` | Specify how permissions are applied to children. Possible values: `true` to inherit both child directories and files; `false` to not inherit any child directories or files; `:containers_only` to inherit only child directories (and not files); `:objects_only` to recursively inherit files (and not child directories). | | `:applies_to_self` | Indicates whether a permission is applied to the parent directory. Possible values: `true` to apply to the parent directory or file and its children; `false` to not apply only to child directories and files. | | `:one_level_deep` | Indicates the depth to which permissions will be applied. Possible values: `true` to apply only to the first level of children; `false` to apply to all children. | For example: ``` resource 'x.txt' do rights :read, 'S-1-1-0' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true end ``` or: ``` rights :read, %w(Administrators Everyone) rights :full_control, 'Users', applies_to_children: true rights :write, 'Sally', applies_to_children: :containers_only, applies_to_self: false, one_level_deep: true ``` Some other important things to know when using the `rights` attribute: * Only inherited rights remain. All existing explicit rights on the object are removed and replaced. * If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified. * Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the `deny_rights` property to deny specific rights to specific users. The ordering is independent of using the `rights` property. For example, it doesn’t matter if rights are granted to everyone is placed before or after `deny_rights :read, ['Julian', 'Lewis']`, both Julian and Lewis will be unable to read the document. For example: ``` resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', applies_to_children: true deny_rights :read, %w(Julian Lewis) end ``` or: ``` deny_rights :full_control, ['Sally'] ``` **Inheritance** By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The `inherits` property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end ``` and then the following example specifies how to use inheritance to deny access to the child directory: ``` directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end ``` If the `deny_rights` permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: ``` directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end ``` but then not use the `inherits` property to deny those rights on a child directory: ``` directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end ``` Because the `inherits` property is not specified, Chef Infra Client will default it to `true`, which will ensure that security settings for existing files remain unchanged. ### Using Templates To use a template, two things must happen: 1. A template resource must be added to a recipe 2. An Embedded Ruby (ERB) template must be added to a cookbook For example, the following template file and template resource settings can be used to manage a configuration file named `/etc/sudoers`. Within a cookbook that uses sudo, the following resource could be added to `/recipes/default.rb`: ``` template '/etc/sudoers' do source 'sudoers.erb' mode '0440' owner 'root' group 'root' variables(sudoers_groups: node['authorization']['sudo']['groups'], sudoers_users: node['authorization']['sudo']['users']) end ``` And then create a template called `sudoers.erb` and save it to `templates/default/sudoers.erb`: ``` # # /etc/sudoers # # Generated by Chef for <%= node['fqdn'] %> # Defaults !lecture,tty_tickets,!fqdn # User privilege specification root ALL=(ALL) ALL <% @sudoers_users.each do |user| -%> <%= user %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% end -%> # Members of the sysadmin group may gain root privileges %sysadmin ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% @sudoers_groups.each do |group| -%> # Members of the group '<%= group %>' may gain root privileges <%= group %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL <% end -%``` And then set the default attributes in `attributes/default.rb`: ``` default['authorization']['sudo']['groups'] = %w(sysadmin wheel admin) default['authorization']['sudo']['users'] = %w(jerry greg) ``` #### File Specificity A cookbook is frequently designed to work across many platforms and is often required to distribute a specific template to a specific platform. A cookbook can be designed to support the distribution of templates across platforms, while ensuring that the correct template ends up on each system. The pattern for template specificity depends on two things: the lookup path and the source. The first pattern that matches is used: 1. `/host-$fqdn/$source` 2. `/$platform-$platform_version/$source` 3. `/$platform/$source` 4. `/default/$source` 5. `/$source` Note To specify a particular Windows version, use the [operating system version number](https://docs.microsoft.com/en-us/windows/win32/sysinfo/operating-system-version). For example, a template in `templates/windows-6.3` will be deployed on systems installed with Windows 8.1. Use an array with the `source` property to define an explicit lookup path. For example: ``` template '/test' do source ["#{node.chef_environment}.erb", 'default.erb'] end ``` The following example emulates the entire file specificity pattern by defining it as an explicit path: ``` template '/test' do source %W( host-#{node['fqdn']}/test.erb #{node['platform']}-#{node['platform_version']}/test.erb #{node['platform']}/test.erb default/test.erb ) end ``` A cookbook may have a `/templates` directory structure like this: ``` /templates/ windows-10 windows-6.3 windows default ``` and a resource that looks something like the following: ``` template 'C:\path\to\file\text_file.txt' do source 'text_file.txt' mode '0755' owner 'root' group 'root' end ``` This resource would be matched in the same order as the `/templates` directory structure. For a node named `host-node-desktop` that is running Windows 8.1, the second item would be the matching item and the location: ``` /templates windows-10/text_file.txt windows-6.3/text_file.txt windows/text_file.txt default/text_file.txt ``` #### Helpers A helper is a method or a module that can be used to extend a template. There are three approaches: * An inline helper method * An inline helper module * A cookbook library module Use the `helper` attribute in a recipe to define an inline helper method. Use the `helpers` attribute to define an inline helper module or a cookbook library module. ##### Inline Methods A template helper method is always defined inline on a per-resource basis. A simple example: ``` template '/path' do helper(:hello_world) { 'hello world' } end ``` Another way to define an inline helper method is to reference a node object so that repeated calls to one (or more) cookbook attributes can be done efficiently: ``` template '/path' do helper(:app) { node['app'] } end ``` An inline helper method can also take arguments: ``` template '/path' do helper(:app_conf) { |setting| node['app'][setting] } end ``` Once declared, a template can then use the helper methods to build a file. For example: ``` Say hello: <%= hello_world %``` or: ``` node['app']['listen_port'] is: <%= app['listen_port'] %``` or: ``` node['app']['log_location'] is: <%= app_conf('log_location') %``` ##### Inline Modules A template helper module can be defined inline on a per-resource basis. This approach can be useful when a template requires more complex information. For example: ``` template '/path' do helpers do def hello_world 'hello world' end def app node['app'] end def app_conf(setting) node['app']['setting'] end end end ``` where the `hello_world`, `app`, and `app_conf(setting)` methods comprise the module that extends a template. ##### Library Modules A template helper module can be defined in a library. This is useful when extensions need to be reused across recipes or to make it easier to manage code that would otherwise be defined inline on a per-recipe basis. ``` template '/path/to/template.erb' do helpers(MyHelperModule) end ``` #### Host Notation The naming of folders within cookbook directories must literally match the host notation used for template specificity matching. For example, if a host is named `foo.example.com`, then the folder must be named `host-foo.example.com`. #### Partial Templates A template can be built in a way that allows it to contain references to one (or more) smaller template files. (These smaller template files are also referred to as partials.) A partial can be referenced from a template file in one of the following ways: * By using the `render` method in the template file * By using the **template** resource and the `variables` property. ##### render Method Use the `render` method in a template to reference a partial template file: ``` <%= render 'partial_name.txt.erb', :option => {} %``` where `partial_name` is the name of the partial template file and `:option` is one (or more) of the following: | Option | Description | | --- | --- | | `:cookbook` | By default, a partial template file is assumed to be located in the cookbook that contains the top-level template. Use this option to specify the path to a different cookbook | | `:local` | Indicates that the name of the partial template file should be interpreted as a path to a file in the local file system or looked up in a cookbook using the normal rules for template files. Set to `true` to interpret as a path to a file in the local file system and to `false` to use the normal rules for template files | | `:source` | By default, a partial template file is identified by its file name. Use this option to specify a different name or a local path to use (instead of the name of the partial template file) | | `:variables` | A hash of `variable_name => value` that will be made available to the partial template file. When this option is used, any variables that are defined in the top-level template that are required by the partial template file must have them defined explicitly using this option | For example: ``` <%= render 'simple.txt.erb', :variables => {:user => Etc.getlogin }, :local => true %``` #### Transfer Frequency The Chef Infra Client caches a template when it is first requested. On each subsequent request for that template, the Chef Infra Client compares that request to the template located on the Chef Infra Server. If the templates are the same, no transfer occurs. #### Variables An Embedded Ruby (ERB) template allows Ruby code to be embedded inside a text file within specially formatted tags. Ruby code can be embedded using expressions and statements. An expression is delimited by `<%=` and `%>`. For example: ``` <%= "my name is #{$ruby}" %``` A statement is delimited by a modifier, such as `if`, `elsif`, and `else`. For example: ``` if false # this won't happen elsif nil # this won't either end ``` Using a Ruby expression is the most common approach for defining template variables because this is how all variables that are sent to a template are referenced. Whenever a template needs to use an `each`, `if`, or `end`, use a Ruby statement. When a template is rendered, Ruby expressions and statements are evaluated by Chef Infra Client. The variables listed in the **template** resource’s `variables` parameter and in the node object are evaluated. Chef Infra Client then passes these variables to the template, where they will be accessible as instance variables within the template. The node object can be accessed just as if it were part of a recipe, using the same syntax. For example, a simple template resource like this: ``` node['fqdn'] = 'latte' template '/tmp/foo' do source 'foo.erb' variables(x_men: 'are keen') end ``` And a simple Embedded Ruby (ERB) template like this: ``` The node <%= node[:fqdn] %> thinks the x-men <%= @x_men %``` Would render something like: ``` The node latte thinks the x-men are keen ``` Even though this is a very simple example, the full capabilities of Ruby can be used to tackle even the most complex and demanding template requirements. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **template** resource in recipes: Configure a file from a template ``` template '/tmp/config.conf' do source 'config.conf.erb' end ``` Configure a file from a local template ``` template '/tmp/config.conf' do local true source '/tmp/config.conf.erb' end ``` Configure a file using a variable map ``` template '/tmp/config.conf' do source 'config.conf.erb' variables( :config_var => node['configs']['config_var'] ) end ``` Use the not_if condition The following example shows how to use the `not_if` condition to create a file based on a template and using the presence of an attribute value on the node to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if { node['some_value'] } end ``` The following example shows how to use the `not_if` condition to create a file based on a template and then Ruby code to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if do File.exist?('/etc/passwd') end end ``` The following example shows how to use the `not_if` condition to create a file based on a template and using a Ruby block (with curly braces) to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if { File.exist?('/etc/passwd') } end ``` The following example shows how to use the `not_if` condition to create a file based on a template and using a string to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' not_if 'test -f /etc/passwd' end ``` Use the only_if condition The following example shows how to use the `only_if` condition to create a file based on a template and using the presence of an attribute on the node to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if { node['some_value'] } end ``` The following example shows how to use the `only_if` condition to create a file based on a template, and then use Ruby to specify a condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if { ! ::File.exist?('/etc/passwd') } end ``` The following example shows how to use the `only_if` condition to create a file based on a template and using a string to specify the condition: ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' only_if 'test -f /etc/passwd' end ``` Use a whitespace array (%w) The following example shows how to use a Ruby whitespace array to define a list of configuration tools, and then use that list of tools within the **template** resource to ensure that all of these configuration tools are using the same RSA key: ``` %w{openssl.cnf pkitool vars Rakefile}.each do |f| template "/etc/openvpn/easy-rsa/#{f}" do source "#{f}.erb" owner 'root' group 'root' mode '0755' end end ``` Use a relative path ``` template "#{ENV['HOME']}/chef-getting-started.txt" do source 'chef-getting-started.txt.erb' mode '0755' end ``` Delay notifications ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :delayed end ``` Notify immediately By default, notifications are `:delayed`, that is they are queued up as they are triggered, and then executed at the very end of a Chef Infra Client run. To run an action immediately, use `:immediately`: ``` template '/etc/nagios3/configures-nagios.conf' do # other parameters notifies :run, 'execute[test-nagios-config]', :immediately end ``` and then Chef Infra Client would immediately run the following: ``` execute 'test-nagios-config' do command 'nagios3 --verify-config' action :nothing end ``` Notify multiple resources ``` template '/etc/chef/server.rb' do source 'server.rb.erb' owner 'root' group 'root' mode '0755' notifies :restart, 'service[chef-solr]', :delayed notifies :restart, 'service[chef-solr-indexer]', :delayed notifies :restart, 'service[chef-server]', :delayed end ``` Reload a service ``` template '/tmp/somefile' do mode '0755' source 'somefile.erb' notifies :reload, 'service[apache]', :immediately end ``` Restart a service when a template is modified ``` template '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]', :immediately end ``` Send notifications to multiple resources To send notifications to multiple resources, just use multiple attributes. Multiple attributes will get sent to the notified resources in the order specified. ``` template '/etc/netatalk/netatalk.conf' do notifies :restart, 'service[afpd]', :immediately notifies :restart, 'service[cnid]', :immediately end service 'afpd' service 'cnid' ``` Execute a command using a template The following example shows how to set up IPv4 packet forwarding using the **execute** resource to run a command named `forward_ipv4` that uses a template defined by the **template** resource: ``` execute 'forward_ipv4' do command 'echo > /proc/.../ipv4/ip_forward' action :nothing end template '/etc/file_name.conf' do source 'routing/file_name.conf.erb' notifies :run, 'execute[forward_ipv4]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[forward_ipv4]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. Set an IP address using variables and a template The following example shows how the **template** resource can be used in a recipe to combine settings stored in an attributes file, variables within a recipe, and a template to set the IP addresses that are used by the Nginx service. The attributes file contains the following: ``` default['nginx']['dir'] = '/etc/nginx' ``` The recipe then does the following to: * Declare two variables at the beginning of the recipe, one for the remote IP address and the other for the authorized IP address * Use the **service** resource to restart and reload the Nginx service * Load a template named `authorized_ip.erb` from the `/templates` directory that is used to set the IP address values based on the variables specified in the recipe ``` node.default['nginx']['remote_ip_var'] = 'remote_addr' node.default['nginx']['authorized_ips'] = ['127.0.0.1/32'] service 'nginx' do supports :status => true, :restart => true, :reload => true end template 'authorized_ip' do path "#{node['nginx']['dir']}/authorized_ip" source 'modules/authorized_ip.erb' owner 'root' group 'root' mode '0755' variables( :remote_ip_var => node['nginx']['remote_ip_var'], :authorized_ips => node['nginx']['authorized_ips'] ) notifies :reload, 'service[nginx]', :immediately end ``` where the `variables` property tells the template to use the variables set at the beginning of the recipe and the `source` property is used to call a template file located in the cookbook’s `/templates` directory. The template file looks similar to: ``` geo $<%= @remote_ip_var %> $authorized_ip { default no; <% @authorized_ips.each do |ip| %> <%= "#{ip} yes;" %> <% end %> } ``` Add a rule to an IP table The following example shows how to add a rule named `test_rule` to an IP table using the **execute** resource to run a command using a template that is defined by the **template** resource: ``` execute 'test_rule' do command 'command_to_run --option value ... --option value --source #{node[:name_of_node][:ipsec][:local][:subnet]} -j test_rule' action :nothing end template '/etc/file_name.local' do source 'routing/file_name.local.erb' notifies :run, 'execute[test_rule]', :delayed end ``` where the `command` property for the **execute** resource contains the command that is to be run and the `source` property for the **template** resource specifies which template to use. The `notifies` property for the **template** specifies that the `execute[test_rule]` (which is defined by the **execute** resource) should be queued up and run at the end of a Chef Infra Client run. Apply proxy settings consistently across a Chef organization The following example shows how a template can be used to apply consistent proxy settings for all nodes of the same type: ``` template "#{node['matching_node']['dir']}/sites-available/site_proxy.conf" do source 'site_proxy.matching_node.conf.erb' owner 'root' group 'root' mode '0755' variables( :ssl_certificate => "#{node['matching_node']['dir']}/shared/certificates/site_proxy.crt", :ssl_key => "#{node['matching_node']['dir']}/shared/certificates/site_proxy.key", :listen_port => node['site']['matching_node_proxy']['listen_port'], :server_name => node['site']['matching_node_proxy']['server_name'], :fqdn => node['fqdn'], :server_options => node[:site]['matching_node']['server']['options'], :proxy_options => node[:site]['matching_node']['proxy']['options'] ) end ``` where `matching_node` represents a type of node (like Nginx) and `site_proxy` represents the type of proxy being used for that type of node (like Nexus). Get template settings from a local file The **template** resource can be used to render a template based on settings contained in a local file on disk or to get the settings from a template in a cookbook. Most of the time, the settings are retrieved from a template in a cookbook. The following example shows how the **template** resource can be used to retrieve these settings from a local file. The following example is based on a few assumptions: * The environment is a Ruby on Rails application that needs render a file named `database.yml` * Information about the application—the user, their password, the server—is stored in a data bag on the Chef server * The application is already deployed to the system and that only requirement in this example is to render the `database.yml` file The application source tree looks something like: ``` myapp/ -> config/ -> database.yml.erb ``` Note There should not be a file named `database.yml` (without the `.erb`), as the `database.yml` file is what will be rendered using the **template** resource. The deployment of the app will end up in `/srv`, so the full path to this template would be something like `/srv/myapp/current/config/database.yml.erb`. The content of the template itself may look like this: ``` <%= @rails_env %>: adapter: <%= @adapter %> host: <%= @host %> database: <%= @database %> username: <%= @username %> password: <%= @password %> encoding: 'utf8' reconnect: true ``` The recipe will be similar to the following: ``` results = search(:node, "role:myapp_database_master AND chef_environment:#{node.chef_environment}") db_master = results[0] template '/srv/myapp/shared/database.yml' do source '/srv/myapp/current/config/database.yml.erb' local true variables( :rails_env => node.chef_environment, :adapter => db_master['myapp']['db_adapter'], :host => db_master['fqdn'], :database => "myapp_#{node.chef_environment}", :username => "myapp", :password => "SUPERSECRET", ) end ``` where: * the `search` method in the Chef Infra Language is used to find the first node that is the database master (of which there should only be one) * the `:adapter` variable property may also require an attribute to have been set on a role, which then determines the correct adapter The template will render similar to the following: ``` production: adapter: mysql host: domU-12-31-39-14-F1-C3.compute-1.internal database: myapp_production username: myapp password: SUPERSECRET encoding: utf8 reconnect: true ``` This example showed how to use the **template** resource to render a template based on settings contained in a local file. Some other issues that should be considered when using this type of approach include: * Should the `database.yml` file be in a `.gitignore` file? * How do developers run the application locally? * Does this work with chef-solo? Pass values from recipe to template The following example shows how pass a value to a template using the `variables` property in the **template** resource. The template file is similar to: ``` [tcpout] defaultGroup = splunk_indexers_<%= node['splunk']['receiver_port'] %> disabled=false [tcpout:splunk_indexers_<%= node['splunk']['receiver_port'] %>] server=<% @splunk_servers.map do |s| -%><%= s['ipaddress'] %>:<%= s['splunk']['receiver_port'] %> <% end.join(', ') -%> <% @outputs_conf.each_pair do |name, value| -%> <%= name %> = <%= value %> <% end -%``` The recipe then uses the `variables` attribute to find the values for `splunk_servers` and `outputs_conf`, before passing them into the template: ``` template "#{splunk_dir}/etc/system/local/outputs.conf" do source 'outputs.conf.erb' mode '0755' variables :splunk_servers => splunk_servers, :outputs_conf => node['splunk']['outputs_conf'] notifies :restart, 'service[splunk]' end ``` This example can be found in the `client.rb` recipe and the `outputs.conf.erb` template files that are located in the [chef-splunk cookbook](https://github.com/chef-cookbooks/chef-splunk/) that is maintained by Chef. timezone resource ----------------- [timezone resource page](resources/timezone/index) --- Use the **timezone** resource to change the system timezone on Windows, Linux, and macOS hosts. Timezones are specified in tz database format, with a complete list of available TZ values for Linux and macOS here: <https://en.wikipedia.org/wiki/List_of_tz_database_time_zones>. On Windows systems run `tzutil /l` for a complete list of valid timezones. **New in Chef Infra Client 14.6.** ### Syntax --- The full syntax for all of the properties that are available to the **timezone** resource is: ``` timezone 'name' do timezone String # default value: 'name' unless specified action Symbol # defaults to :set if not specified end ``` where: * `timezone` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `timezone` is the property available to this resource. ### Actions --- The **timezone** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set the system timezone. (default) ### Properties --- The **timezone** resource has the following properties: `timezone` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the timezone value if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **timezone** resource in recipes: **Set the timezone to UTC** ``` timezone 'UTC' ``` **Set the timezone to America/Los_Angeles with a friendly resource name on Linux/macOS** ``` timezone "Set the host's timezone to America/Los_Angeles" do timezone 'America/Los_Angeles' end ``` **Set the timezone to PST with a friendly resource name on Windows** ``` timezone "Set the host's timezone to PST" do timezone 'Pacific Standard time' end ``` user resource ------------- [user resource page](resources/user/index) --- Use the **user** resource to add users, update existing users, remove users, and to lock/unlock user passwords. Note System attributes are collected by Ohai at the start of every Chef Infra Client run. By design, the actions available to the **user** resource are processed **after** the start of a Chef Infra Client run. This means that system attributes added or modified by the **user** resource during a Chef Infra Client run must be reloaded before they can be available to Chef Infra Client. These system attributes can be reloaded in two ways: by picking up the values at the start of the (next) Chef Infra Client run or by using the [ohai resource](resources/ohai/index) to reload the system attributes during the current Chef Infra Client run. ### Syntax --- A **user** resource block manages users on a node: ``` user 'a user' do comment 'A random user' uid 1234 gid 'groupname' home '/home/random' shell '/bin/bash' password '$1$JJsvHslasdfjVEroftprNn4JHtDi' end ``` The full syntax for all of the properties that are available to the **user** resource is: ``` user 'name' do comment String force true, false # see description gid String, Integer home String iterations Integer manage_home true, false non_unique true, false password String salt String shell String system true, false uid String, Integer username String # defaults to 'name' if not specified action Symbol # defaults to :create if not specified end ``` where: * `user` is the resource * `name` is the name of the resource block * `action` identifies the steps Chef Infra Client will take to bring the node into the desired state * `comment`, `force`, `gid`, `home`, `iterations`, `manage_home`, `non_unique`, `password`, `salt`, `shell`, `system`, `uid`, and `username` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **user** resource has the following actions: `:create` Default. Create a user with given properties. If a user already exists (but does not match), update that user to match. `:lock` Lock a user’s password. `:manage` Manage an existing user. This action does nothing if the user does not exist. `:modify` Modify an existing user. This action raises an exception if the user does not exist. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a user. `:unlock` Unlock a user’s password. ### Properties --- The **user** resource has the following properties: `comment` **Ruby Type:** String One (or more) comments about the user. `force` **Ruby Type:** true, false Force the removal of a user. May be used only with the `:remove` action. Warning Using this property may leave the system in an inconsistent state. For example, a user account will be removed even if the user is logged in. A user’s home directory will be removed, even if that directory is shared by multiple users. `gid` **Ruby Type:** String, Integer The identifier for the group. This property was previously named `group` and both continue to function. `home` **Ruby Type:** String The location of the home directory. `iterations` **Ruby Type:** Integer macOS platform only. The number of iterations for a password with a SALTED-SHA512-PBKDF2 shadow hash. `manage_home` **Ruby Type:** true, false Manage a user’s home directory. When used with the `:create` action, a user’s home directory is created based on `HOME_DIR`. If the home directory is missing, it is created unless `CREATE_HOME` in `/etc/login.defs` is set to `no`. When created, a skeleton set of files and subdirectories are included within the home directory. When used with the `:modify` action, a user’s home directory is moved to `HOME_DIR`. If the home directory is missing, it is created unless `CREATE_HOME` in `/etc/login.defs` is set to `no`. The contents of the user’s home directory are moved to the new location. `non_unique` **Ruby Type:** true, false Create a duplicate (non-unique) user account. `password` **Ruby Type:** String The password shadow hash `salt` **Ruby Type:** String A SALTED-SHA512-PBKDF2 hash. `shell` **Ruby Type:** String The login shell. `system` **Ruby Type:** true, false Create a system user. This property may be used with `useradd` as the provider to create a system user which passes the `-r` flag to `useradd`. `uid` **Ruby Type:** String, Integer The numeric user identifier. `username` **Ruby Type:** String The name of the user. Default value: the `name` of the resource block. See “Syntax” section above for more information. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **user** resource in recipes: Create a system user ``` user 'systemguy' do comment 'system guy' system true shell '/bin/false' end ``` Create a system user with a variable The following example shows how to create a system user. In this instance, the `home` value is calculated and stored in a variable called `user_home` which sets the user’s `home` attribute. ``` user_home = "/home/#{node['cookbook_name']['user']}" user node['cookbook_name']['user'] do gid node['cookbook_name']['group'] shell '/bin/bash' home user_home system true action :create end ``` Use SALTED-SHA512-PBKDF2 passwords macOS 10.8 (and higher) calculates the password shadow hash using SALTED-SHA512-PBKDF2. The length of the shadow hash value is 128 bytes, the salt value is 32 bytes, and an integer specifies the number of iterations. The following code will calculate password shadow hashes for macOS 10.8 (and higher): ``` password = 'my_awesome_password' salt = OpenSSL::Random.random_bytes(32) iterations = 25000 # Any value above 20k should be fine. shadow_hash = OpenSSL::PKCS5::pbkdf2_hmac( password, salt, iterations, 128, OpenSSL::Digest::SHA512.new ).unpack('H*').first salt_value = salt.unpack('H*').first ``` Use the calculated password shadow hash with the **user** resource: ``` user 'my_awesome_user' do password 'cbd1a....fc843' # Length: 256 salt 'bd1a....fc83' # Length: 64 iterations 25000 end ``` user_ulimit resource --------------------- [user_ulimit resource page](resources/user_ulimit/index) --- Use the **user_ulimit** resource to create individual ulimit files that are installed into the `/etc/security/limits.d/` directory. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **user_ulimit** resource is: ``` user_ulimit 'name' do core_hard_limit String, Integer core_limit String, Integer core_soft_limit String, Integer filehandle_hard_limit String, Integer filehandle_limit String, Integer filehandle_soft_limit String, Integer filename String memory_limit String, Integer process_hard_limit String, Integer process_limit String, Integer process_soft_limit String, Integer rtprio_hard_limit String, Integer rtprio_limit String, Integer rtprio_soft_limit String, Integer stack_hard_limit String, Integer stack_limit String, Integer stack_soft_limit String, Integer username String # default value: 'name' unless specified virt_limit String, Integer action Symbol # defaults to :create if not specified end ``` where: * `user_ulimit` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `core_hard_limit`, `core_limit`, `core_soft_limit`, `filehandle_hard_limit`, `filehandle_limit`, `filehandle_soft_limit`, `filename`, `memory_limit`, `process_hard_limit`, `process_limit`, `process_soft_limit`, `rtprio_hard_limit`, `rtprio_limit`, `rtprio_soft_limit`, `stack_hard_limit`, `stack_limit`, `stack_soft_limit`, `username`, and `virt_limit` are the properties available to this resource. ### Actions --- The **user_ulimit** resource has the following actions: `:create` Create a ulimit configuration file. (default) `:delete` Delete an existing ulimit configuration file. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **user_ulimit** resource has the following properties: `core_hard_limit` **Ruby Type:** String, Integer `core_limit` **Ruby Type:** String, Integer `core_soft_limit` **Ruby Type:** String, Integer `filehandle_hard_limit` **Ruby Type:** String, Integer `filehandle_limit` **Ruby Type:** String, Integer `filehandle_soft_limit` **Ruby Type:** String, Integer `filename` **Ruby Type:** String | **Default Value:** `lazy default` `memory_limit` **Ruby Type:** String, Integer `process_hard_limit` **Ruby Type:** String, Integer `process_limit` **Ruby Type:** String, Integer `process_soft_limit` **Ruby Type:** String, Integer `rtprio_hard_limit` **Ruby Type:** String, Integer `rtprio_limit` **Ruby Type:** String, Integer `rtprio_soft_limit` **Ruby Type:** String, Integer `stack_hard_limit` **Ruby Type:** String, Integer `stack_limit` **Ruby Type:** String, Integer `stack_soft_limit` **Ruby Type:** String, Integer `username` **Ruby Type:** String | **Default Value:** `The resource block's name` `virt_limit` **Ruby Type:** String, Integer ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **user_ulimit** resource in recipes: **Set filehandle limit for the tomcat user**: ``` user_ulimit 'tomcat' do filehandle_limit 8192 end ``` **Specify a username that differs from the name given to the resource block**: ``` user_ulimit 'Bump filehandle limits for tomcat user' do username 'tomcat' filehandle_limit 8192 end ``` **Set filehandle limit for the tomcat user with a non-default filename**: ``` user_ulimit 'tomcat' do filehandle_limit 8192 filename 'tomcat_filehandle_limits.conf' end ``` windows_ad_join resource -------------------------- [windows_ad_join resource page](resources/windows_ad_join/index) --- Use the **windows_ad_join** resource to join a Windows Active Directory domain. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_ad_join** resource is: ``` windows_ad_join 'name' do domain_name String # default value: 'name' unless specified domain_password String domain_user String new_hostname String ou_path String reboot Symbol # default value: :immediate reboot_delay Integer # default value: 0 workgroup_name String action Symbol # defaults to :join if not specified end ``` where: * `windows_ad_join` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `domain_name`, `domain_password`, `domain_user`, `new_hostname`, `ou_path`, `reboot`, `reboot_delay`, and `workgroup_name` are the properties available to this resource. ### Actions --- The **windows_ad_join** resource has the following actions: `:join` Join the Active Directory domain. (default) `:leave` Leave an Active Directory domain and re-join a workgroup. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_ad_join** resource has the following properties: `domain_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the FQDN of the Active Directory domain to join if it differs from the resource block’s name. `domain_password` **Ruby Type:** String | `REQUIRED` The password for the domain user. Note that this resource is set to hide sensitive information by default. `domain_user` **Ruby Type:** String | `REQUIRED` The domain user that will be used to join the domain. `new_hostname` **Ruby Type:** String Specifies a new hostname for the computer in the new domain. New in Chef Client 14.5 `ou_path` **Ruby Type:** String The path to the Organizational Unit where the host will be placed. `reboot` **Ruby Type:** Symbol | **Default Value:** `:immediate` **Allowed Values:** `:delayed, :immediate, :never, :reboot_now, :request_reboot` Controls the system reboot behavior post domain joining. Reboot immediately, after the Chef Infra Client run completes, or never. Note that a reboot is necessary for changes to take effect. `reboot_delay` **Ruby Type:** Integer | **Default Value:** `0` The amount of time (in minutes) to delay a reboot request. New in Chef Infra Client 16.5 `workgroup_name` **Ruby Type:** String Specifies the name of a workgroup to which the computer is added to when it is removed from the domain. The default value is WORKGROUP. This property is only applicable to the :leave action. New in Chef Infra Client 15.4 ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_ad_join** resource in recipes: **Join a domain** ``` windows_ad_join 'ad.example.org' do domain_user 'nick' domain_password 'p@ssw0rd1' end ``` **Join a domain, as `win-workstation`** ``` windows_ad_join 'ad.example.org' do domain_user 'nick' domain_password 'p@ssw0rd1' new_hostname 'win-workstation' end ``` **Leave the current domain and re-join the `local` workgroup** ``` windows_ad_join 'Leave domain' do action :leave workgroup 'local' end ``` windows_audit_policy resource ------------------------------- [windows_audit_policy resource page](resources/windows_audit_policy/index) --- Use the **windows_audit_policy** resource to configure system level and per-user Windows advanced audit policy settings. **New in Chef Infra Client 16.2.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_audit_policy** resource is: ``` windows_audit_policy 'name' do audit_base_directories true, false audit_base_objects true, false crash_on_audit_fail true, false exclude_user String failure true, false full_privilege_auditing true, false include_user String subcategory String, Array success true, false action Symbol # defaults to :set if not specified end ``` where: * `windows_audit_policy` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `audit_base_directories`, `audit_base_objects`, `crash_on_audit_fail`, `exclude_user`, `failure`, `full_privilege_auditing`, `include_user`, `subcategory`, and `success` are the properties available to this resource. ### Actions --- The **windows_audit_policy** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Configure an audit policy. (default) ### Properties --- The **windows_audit_policy** resource has the following properties: `audit_base_directories` **Ruby Type:** true, false Setting this audit policy option to true will force the system to assign a System Access Control List to named objects to enable auditing of container objects such as directories. `audit_base_objects` **Ruby Type:** true, false Setting this audit policy option to true will force the system to assign a System Access Control List to named objects to enable auditing of base objects such as mutexes. `crash_on_audit_fail` **Ruby Type:** true, false Setting this audit policy option to true will cause the system to crash if the auditing system is unable to log events. `exclude_user` **Ruby Type:** String The audit policy specified by the category or subcategory is applied per-user if specified. When a user is specified, exclude user. Include and exclude cannot be used at the same time. `failure` **Ruby Type:** true, false Specify failure auditing. By setting this property to true the resource will enable failure for the category or sub category. Success is the default and is applied if neither success nor failure are specified. `full_privilege_auditing` **Ruby Type:** true, false Setting this audit policy option to true will force the audit of all privilege changes except SeAuditPrivilege. Setting this property may cause the logs to fill up more quickly. `include_user` **Ruby Type:** String The audit policy specified by the category or subcategory is applied per-user if specified. When a user is specified, include user. Include and exclude cannot be used at the same time. `subcategory` **Ruby Type:** String, Array The audit policy subcategory, specified by GUID or name. Applied system-wide if no user is specified. `success` **Ruby Type:** true, false Specify success auditing. By setting this property to true the resource will enable success for the category or sub category. Success is the default and is applied if neither success nor failure are specified. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_audit_policy** resource in recipes: **Set Logon and Logoff policy to “Success and Failure”**: ``` windows_audit_policy "Set Audit Policy for 'Logon and Logoff' actions to 'Success and Failure'" do subcategory %w(Logon Logoff) success true failure true action :set end ``` **Set Credential Validation policy to “Success”**: ``` windows_audit_policy "Set Audit Policy for 'Credential Validation' actions to 'Success'" do subcategory 'Credential Validation' success true failure false action :set end ``` **Enable CrashOnAuditFail option**: ``` windows_audit_policy 'Enable CrashOnAuditFail option' do crash_on_audit_fail true action :set end ``` windows_auto_run resource --------------------------- [windows_auto_run resource page](resources/windows_auto_run/index) --- Use the **windows_auto_run** resource to set applications to run at login. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_auto_run** resource is: ``` windows_auto_run 'name' do args String path String program_name String # default value: 'name' unless specified root Symbol # default value: :machine action Symbol # defaults to :create if not specified end ``` where: * `windows_auto_run` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `args`, `path`, `program_name`, and `root` are the properties available to this resource. ### Actions --- The **windows_auto_run** resource has the following actions: `:create` Create an item to be run at login. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an item that was previously configured to run at login. ### Properties --- The **windows_auto_run** resource has the following properties: `args` **Ruby Type:** String Any arguments to be used with the program. `path` **Ruby Type:** String The path to the program that will run at login. `program_name` **Ruby Type:** String | **Default Value:** `The resource block's name` The name of the program to run at login if it differs from the resource block’s name. `root` **Ruby Type:** Symbol | **Default Value:** `:machine` **Allowed Values:** `:machine, :user` The registry root key to put the entry under. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_auto_run** resource in recipes: **Run BGInfo at login** ``` windows_auto_run 'BGINFO' do program 'C:/Sysinternals/bginfo.exe' args ''C:/Sysinternals/Config.bgi' /NOLICPROMPT /TIMER:0' action :create end ``` windows_certificate resource ----------------------------- [windows_certificate resource page](resources/windows_certificate/index) --- Use the **windows_certificate** resource to install a certificate into the Windows certificate store from a file. The resource grants read-only access to the private key for designated accounts. Due to current limitations in WinRM, installing certificates remotely may not work if the operation requires a user profile. Operations on the local machine store should still work. **New in Chef Infra Client 14.7.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_certificate** resource is: ``` windows_certificate 'name' do exportable true, false # default value: false output_path String pfx_password String private_key_acl Array source String # default value: 'name' unless specified store_name String # default value: "MY" user_store true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_certificate` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `exportable`, `output_path`, `pfx_password`, `private_key_acl`, `source`, `store_name`, and `user_store` are the properties available to this resource. ### Actions --- The **windows_certificate** resource has the following actions: `:acl_add` Adds read-only entries to a certificate’s private key ACL. `:create` Creates or updates a certificate. (default) `:delete` Deletes a certificate. `:fetch` Fetches a certificate. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:verify` Verifies a certificate and logs the result. ### Properties --- The **windows_certificate** resource has the following properties: `exportable` **Ruby Type:** true, false | **Default Value:** `false` Ensure that imported pfx certificate is exportable. Please provide ‘true’ if you want the certificate to be exportable. New in Chef Infra Client 16.8 `output_path` **Ruby Type:** String A path on the node where a certificate object (PFX, PEM, CER, KEY, etc) can be exported to. New in Chef Infra Client 17.0 `pfx_password` **Ruby Type:** String The password to access the object with if it is a PFX file. `private_key_acl` **Ruby Type:** Array An array of ‘domain\account’ entries to be granted read-only access to the certificate’s private key. Not idempotent. `source` **Ruby Type:** String | **Default Value:** `The resource block's name` The source file (for `create` and `acl_add`), thumbprint (for `delete`, `export`, and `acl_add`), or subject (for `delete` or `export`) if it differs from the resource block’s name. `store_name` **Ruby Type:** String | **Default Value:** `MY` **Allowed Values:** `"AUTHROOT", "CA", "CLIENTAUTHISSUER", "DISALLOWED", "MY", "REMOTE DESKTOP", "ROOT", "SMARTCARDROOT", "TRUST", "TRUSTEDDEVICES", "TRUSTEDPEOPLE", "TRUSTEDPUBLISHER", "TrustedPublisher", "WEBHOSTING"` The certificate store to manipulate. `user_store` **Ruby Type:** true, false | **Default Value:** `false` Use the `CurrentUser` store instead of the default `LocalMachine` store. Note Prior to chef-client. 16.10 this property was ignored. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_certificate** resource in recipes: **Add PFX cert to local machine personal store and grant accounts read-only access to private key** ``` windows_certificate 'c:/test/mycert.pfx' do pfx_password 'password' private_key_acl ["acme\fred", "pc\jane"] end ``` **Add cert to trusted intermediate store** ``` windows_certificate 'c:/test/mycert.cer' do store_name 'CA' end ``` **Remove all certificates matching the subject** ``` windows_certificate 'me.acme.com' do action :delete end ``` windows_defender resource -------------------------- [windows_defender resource page](resources/windows_defender/index) --- Use the **windows_defender** resource to enable or disable the Microsoft Windows Defender service. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_defender** resource is: ``` windows_defender 'name' do intrusion_protection_system true, false # default value: true lock_ui true, false # default value: false realtime_protection true, false # default value: true scan_archives true, false # default value: true scan_email true, false # default value: false scan_mapped_drives true, false # default value: true scan_network_files true, false # default value: false scan_removable_drives true, false # default value: false scan_scripts true, false # default value: false action Symbol # defaults to :enable if not specified end ``` where: * `windows_defender` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `intrusion_protection_system`, `lock_ui`, `realtime_protection`, `scan_archives`, `scan_email`, `scan_mapped_drives`, `scan_network_files`, `scan_removable_drives`, and `scan_scripts` are the properties available to this resource. ### Actions --- The **windows_defender** resource has the following actions: `:disable` Disable Windows Defender. `:enable` Enable and configure Windows Defender. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_defender** resource has the following properties: `intrusion_protection_system` **Ruby Type:** true, false | **Default Value:** `true` Enable network protection against exploitation of known vulnerabilities. `lock_ui` **Ruby Type:** true, false | **Default Value:** `false` Lock the UI to prevent users from changing Windows Defender settings. `realtime_protection` **Ruby Type:** true, false | **Default Value:** `true` Enable realtime scanning of downloaded files and attachments. `scan_archives` **Ruby Type:** true, false | **Default Value:** `true` Scan file archives such as .zip or .gz archives. `scan_email` **Ruby Type:** true, false | **Default Value:** `false` Scan e-mails for malware. `scan_mapped_drives` **Ruby Type:** true, false | **Default Value:** `true` Scan files on mapped network drives. `scan_network_files` **Ruby Type:** true, false | **Default Value:** `false` Scan files on a network. `scan_removable_drives` **Ruby Type:** true, false | **Default Value:** `false` Scan content of removable drives. `scan_scripts` **Ruby Type:** true, false | **Default Value:** `false` Scan scripts in malware scans. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_defender** resource in recipes: **Configure Windows Defender AV settings**: ``` windows_defender 'Configure Defender' do realtime_protection true intrusion_protection_system true lock_ui true scan_archives true scan_scripts true scan_email true scan_removable_drives true scan_network_files false scan_mapped_drives false action :enable end ``` **Disable Windows Defender AV**: ``` windows_defender 'Disable Defender' do action :disable end ``` windows_defender_exclusion resource ------------------------------------- [windows_defender_exclusion resource page](resources/windows_defender_exclusion/index) --- Use the **windows_defender_exclusion** resource to exclude paths, processes, or file types from Windows Defender realtime protection scanning. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_defender_exclusion** resource is: ``` windows_defender_exclusion 'name' do extensions String, Array # default value: [] paths String, Array # default value: [] process_paths String, Array # default value: [] action Symbol # defaults to :add if not specified end ``` where: * `windows_defender_exclusion` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `extensions`, `paths`, and `process_paths` are the properties available to this resource. ### Actions --- The **windows_defender_exclusion** resource has the following actions: `:add` Add an exclusion to Windows Defender. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an exclusion to Windows Defender. ### Properties --- The **windows_defender_exclusion** resource has the following properties: `extensions` **Ruby Type:** String, Array | **Default Value:** `[]` File extensions to exclude from scanning. `paths` **Ruby Type:** String, Array | **Default Value:** `[]` File or directory paths to exclude from scanning. `process_paths` **Ruby Type:** String, Array | **Default Value:** `[]` Paths to executables to exclude from scanning. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_defender_exclusion** resource in recipes: **Add excluded items to Windows Defender scans**: ``` windows_defender_exclusion 'Add to things to be excluded from scanning' do paths 'c:\foo\bar, d:\bar\baz' extensions 'png, foo, ppt, doc' process_paths 'c:\windows\system32' action :add end ``` **Remove excluded items from Windows Defender scans**: ``` windows_defender_exclusion 'Remove things from the list to be excluded' do process_paths 'c:\windows\system32' action :remove end ``` windows_dfs_folder resource ----------------------------- [windows_dfs_folder resource page](resources/windows_dfs_folder/index) --- Use the **windows_dfs_folder** resource to creates a folder within DFS as many levels deep as required. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_dfs_folder** resource is: ``` windows_dfs_folder 'name' do description String folder_path String # default value: 'name' unless specified namespace_name String target_path String action Symbol # defaults to :create if not specified end ``` where: * `windows_dfs_folder` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `description`, `folder_path`, `namespace_name`, and `target_path` are the properties available to this resource. ### Actions --- The **windows_dfs_folder** resource has the following actions: `:create` Creates the folder in dfs namespace. (default) `:delete` Deletes the folder in the dfs namespace. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_dfs_folder** resource has the following properties: `description` **Ruby Type:** String Description for the share. `folder_path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the path of the dfs folder if it differs from the resource block’s name. `namespace_name` **Ruby Type:** String | `REQUIRED` The namespace this should be created within. `target_path` **Ruby Type:** String The target that this path will connect you to. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. windows_dfs_namespace resource -------------------------------- [windows_dfs_namespace resource page](resources/windows_dfs_namespace/index) --- Use the **windows_dfs_namespace** resource to creates a share and DFS namespace on a Windows server. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_dfs_namespace** resource is: ``` windows_dfs_namespace 'name' do change_users Array # default value: [] description String full_users Array # default value: ["BUILTIN\\administrators"] namespace_name String # default value: 'name' unless specified read_users Array # default value: [] root String # default value: "C:\\DFSRoots" action Symbol # defaults to :create if not specified end ``` where: * `windows_dfs_namespace` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `change_users`, `description`, `full_users`, `namespace_name`, `read_users`, and `root` are the properties available to this resource. ### Actions --- The **windows_dfs_namespace** resource has the following actions: `:create` Creates the dfs namespace on the server. (default) `:delete` Deletes a DFS Namespace including the directory on disk. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_dfs_namespace** resource has the following properties: `change_users` **Ruby Type:** Array | **Default Value:** `[]` Determines which users should have change access to the share. `description` **Ruby Type:** String | `REQUIRED` Description of the share. `full_users` **Ruby Type:** Array | **Default Value:** `["BUILTIN\\administrators"]` Determines which users should have full access to the share. `namespace_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the dfs namespace if it differs from the resource block’s name. `read_users` **Ruby Type:** Array | **Default Value:** `[]` Determines which users should have read access to the share. `root` **Ruby Type:** String | **Default Value:** `C:\DFSRoots` The root from which to create the DFS tree. Defaults to C:\DFSRoots. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. windows_dfs_server resource ----------------------------- [windows_dfs_server resource page](resources/windows_dfs_server/index) --- Use the **windows_dfs_server** resource to set system-wide DFS settings. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_dfs_server** resource is: ``` windows_dfs_server 'name' do enable_site_costed_referrals true, false # default value: false ldap_timeout_secs Integer # default value: 30 prefer_login_dc true, false # default value: false sync_interval_secs Integer # default value: 3600 use_fqdn true, false # default value: false action Symbol # defaults to :configure if not specified end ``` where: * `windows_dfs_server` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `enable_site_costed_referrals`, `ldap_timeout_secs`, `prefer_login_dc`, `sync_interval_secs`, and `use_fqdn` are the properties available to this resource. ### Actions --- The **windows_dfs_server** resource has the following actions: `:configure` Configure DFS settings (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_dfs_server** resource has the following properties: `enable_site_costed_referrals` **Ruby Type:** true, false | **Default Value:** `false` `ldap_timeout_secs` **Ruby Type:** Integer | **Default Value:** `30` `prefer_login_dc` **Ruby Type:** true, false | **Default Value:** `false` `sync_interval_secs` **Ruby Type:** Integer | **Default Value:** `3600` `use_fqdn` **Ruby Type:** true, false | **Default Value:** `false` Indicates whether a DFS namespace server uses FQDNs in referrals. If this property is set to true, the server uses FQDNs in referrals. If this property is set to false then the server uses NetBIOS names. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. windows_dns_record resource ----------------------------- [windows_dns_record resource page](resources/windows_dns_record/index) --- The windows_dns_record resource creates a DNS record for the given domain. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_dns_record** resource is: ``` windows_dns_record 'name' do dns_server String # default value: "localhost" record_name String # default value: 'name' unless specified record_type String # default value: "ARecord" target String zone String action Symbol # defaults to :create if not specified end ``` where: * `windows_dns_record` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `dns_server`, `record_name`, `record_type`, `target`, and `zone` are the properties available to this resource. ### Actions --- The **windows_dns_record** resource has the following actions: `:create` Creates and updates the DNS entry. (default) `:delete` Deletes a DNS entry. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_dns_record** resource has the following properties: `dns_server` **Ruby Type:** String | **Default Value:** `localhost` The name of the DNS server on which to create the record. New in Chef Infra Client 16.3 `record_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the dns record name if it differs from the resource block’s name. `record_type` **Ruby Type:** String | **Default Value:** `ARecord` **Allowed Values:** `"ARecord", "CNAME", "PTR"` The type of record to create, can be either ARecord, CNAME or PTR. `target` **Ruby Type:** String | `REQUIRED` The target for the record. `zone` **Ruby Type:** String | `REQUIRED` The zone to create the record in. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. windows_dns_zone resource --------------------------- [windows_dns_zone resource page](resources/windows_dns_zone/index) --- The windows_dns_zone resource creates an Active Directory Integrated DNS Zone on the local server. **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_dns_zone** resource is: ``` windows_dns_zone 'name' do replication_scope String # default value: "Domain" server_type String # default value: "Domain" zone_name String # default value: 'name' unless specified action Symbol # defaults to :create if not specified end ``` where: * `windows_dns_zone` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `replication_scope`, `server_type`, and `zone_name` are the properties available to this resource. ### Actions --- The **windows_dns_zone** resource has the following actions: `:create` Creates and updates a DNS Zone. (default) `:delete` Deletes a DNS Zone. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_dns_zone** resource has the following properties: `replication_scope` **Ruby Type:** String | **Default Value:** `Domain` The replication scope for the zone, required if server_type set to ‘Domain’. `server_type` **Ruby Type:** String | **Default Value:** `Domain` **Allowed Values:** `"Domain", "Standalone"` The type of DNS server, Domain or Standalone. `zone_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the dns zone name if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- This resource does not have any examples. windows_env resource --------------------- [windows_env resource page](resources/windows_env/index) --- Use the **windows_env** resource to manage environment keys in Microsoft Windows. After an environment key is set, Microsoft Windows must be restarted before the environment key will be available to the Task Scheduler. This resource was previously called the **env** resource; its name was updated in Chef Infra Client 14.0 to reflect the fact that only Windows is supported. Existing cookbooks using `env` will continue to function, but should be updated to use the new name. Note On UNIX-based systems, the best way to manipulate environment keys is with the `ENV` variable in Ruby; however, this approach does not have the same permanent effect as using the windows_env resource. ### Syntax --- The full syntax for all of the properties that are available to the **windows_env** resource is: ``` windows_env 'name' do delim String, false key_name String # default value: 'name' unless specified user String # default value: "<System>" value String action Symbol # defaults to :create if not specified end ``` where: * `windows_env` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `delim`, `key_name`, `user`, and `value` are the properties available to this resource. ### Actions --- The **windows_env** resource has the following actions: `:create` Create an environment variable. If an environment variable already exists (but does not match), update that environment variable to match. (default) `:delete` Delete an environment variable. `:modify` Modify an existing environment variable. This prepends the new value to the existing value, using the delimiter specified by the `delim` property. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_env** resource has the following properties: `delim` **Ruby Type:** String, false The delimiter that is used to separate multiple values for a single key. `key_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the name of the key that is to be created, deleted, or modified if it differs from the resource block’s name. `user` **Ruby Type:** String | **Default Value:** `<System>` `value` **Ruby Type:** String | `REQUIRED` The value of the environmental variable to set. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_env** resource in recipes: **Set an environment variable**: ``` windows_env 'ComSpec' do value 'C:\Windows\system32\cmd.exe' end ``` windows_feature resource ------------------------- [windows_feature resource page](resources/windows_feature/index) --- Use the **windows_feature** resource to add, remove or entirely delete Windows features and roles. This resource calls the [windows_feature_dism](resources/windows_feature_dism/index) or [windows_feature_powershell](resources/windows_feature_powershell/index) resources depending on the specified installation method, and defaults to DISM, which is available on both Workstation and Server editions of Windows. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_feature** resource is: ``` windows_feature 'name' do all true, false # default value: false feature_name Array, String # default value: 'name' unless specified install_method Symbol # default value: :windows_feature_dism management_tools true, false # default value: false source String timeout Integer # default value: 600 action Symbol # defaults to :install if not specified end ``` where: * `windows_feature` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `all`, `feature_name`, `install_method`, `management_tools`, `source`, and `timeout` are the properties available to this resource. ### Actions --- The **windows_feature** resource has the following actions: `:delete` Remove a Windows role or feature from the image. `:install` Install a Windows role or feature. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows role or feature. ### Properties --- The **windows_feature** resource has the following properties: `all` **Ruby Type:** true, false | **Default Value:** `false` Install all sub-features. `feature_name` **Ruby Type:** Array, String | **Default Value:** `The resource block's name` The name of the feature(s) or role(s) to install if they differ from the resource block’s name. The same feature may have different names depending on the underlying installation method being used (ie DHCPServer vs DHCP; DNS-Server-Full-Role vs DNS). `install_method` **Ruby Type:** Symbol | **Default Value:** `:windows_feature_dism` **Allowed Values:** `:windows_feature_dism, :windows_feature_powershell, :windows_feature_servermanagercmd` The underlying installation method to use for feature installation. Specify `:windows_feature_dism` for DISM or `:windows_feature_powershell` for PowerShell. `management_tools` **Ruby Type:** true, false | **Default Value:** `false` Install all applicable management tools for the roles, role services, or features (PowerShell-only). `source` **Ruby Type:** String Specify a local repository for the feature install. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Specifies a timeout (in seconds) for the feature installation. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_feature** resource in recipes: **Install the DHCP Server feature**: ``` windows_feature 'DHCPServer' do action :install end ``` **Install the .Net 3.5.1 feature using repository files on DVD**: ``` windows_feature "NetFx3" do action :install source 'd:\sources\sxs' end ``` **Remove Telnet Server and Client features**: ``` windows_feature %w(TelnetServer TelnetClient) do action :remove end ``` **Add the SMTP Server feature using the PowerShell provider**: ``` windows_feature 'smtp-server' do action :install all true install_method :windows_feature_powershell end ``` **Install multiple features using one resource with the PowerShell provider**: ``` windows_feature %w(Web-Asp-Net45 Web-Net-Ext45) do action :install install_method :windows_feature_powershell end ``` **Install the Network Policy and Access Service feature, including the management tools**: ``` windows_feature 'NPAS' do action :install management_tools true install_method :windows_feature_powershell end ``` windows_feature_dism resource ------------------------------- [windows_feature_dism resource page](resources/windows_feature_dism/index) --- Use the **windows_feature_dism** resource to add, remove, or entirely delete Windows features and roles using DISM. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_feature_dism** resource is: ``` windows_feature_dism 'name' do all true, false # default value: false feature_name Array, String # default value: 'name' unless specified source String timeout Integer # default value: 600 action Symbol # defaults to :install if not specified end ``` where: * `windows_feature_dism` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `all`, `feature_name`, `source`, and `timeout` are the properties available to this resource. ### Actions --- The **windows_feature_dism** resource has the following actions: `:delete` Remove a Windows role or feature from the image using DISM. `:install` Install a Windows role/feature using DISM. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows role or feature using DISM. ### Properties --- The **windows_feature_dism** resource has the following properties: `all` **Ruby Type:** true, false | **Default Value:** `false` Install all sub-features. When set to `true`, this is the equivalent of specifying the `/All` switch to `dism.exe` `feature_name` **Ruby Type:** Array, String | **Default Value:** `The resource block's name` The name of the feature(s) or role(s) to install if they differ from the resource name. `source` **Ruby Type:** String Specify a local repository for the feature install. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Specifies a timeout (in seconds) for the feature installation. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_feature_dism** resource in recipes: **Installing the TelnetClient service**: ``` windows_feature_dism "TelnetClient" ``` **Installing two features by using an array**: ``` windows_feature_dism %w(TelnetClient TFTP) ``` windows_feature_powershell resource ------------------------------------- [windows_feature_powershell resource page](resources/windows_feature_powershell/index) --- Use the **windows_feature_powershell** resource to add, remove, or entirely delete Windows features and roles using PowerShell. This resource offers significant speed benefits over the [windows_feature_dism](resources/windows_feature_dism/index) resource, but requires installation of the Remote Server Administration Tools on non-server releases of Windows. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_feature_powershell** resource is: ``` windows_feature_powershell 'name' do all true, false # default value: false feature_name Array, String # default value: 'name' unless specified management_tools true, false # default value: false source String timeout Integer # default value: 600 action Symbol # defaults to :install if not specified end ``` where: * `windows_feature_powershell` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `all`, `feature_name`, `management_tools`, `source`, and `timeout` are the properties available to this resource. ### Actions --- The **windows_feature_powershell** resource has the following actions: `:delete` Delete a Windows role or feature from the image using PowerShell. `:install` Install a Windows role or feature using PowerShell. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a Windows role or feature using PowerShell. ### Properties --- The **windows_feature_powershell** resource has the following properties: `all` **Ruby Type:** true, false | **Default Value:** `false` Install all subfeatures. When set to `true`, this is the equivalent of specifying the `-InstallAllSubFeatures` switch with `Add-WindowsFeature`. `feature_name` **Ruby Type:** Array, String | **Default Value:** `The resource block's name` The name of the feature(s) or role(s) to install if they differ from the resource block’s name. `management_tools` **Ruby Type:** true, false | **Default Value:** `false` Install all applicable management tools for the roles, role services, or features. `source` **Ruby Type:** String Specify a local repository for the feature install. `timeout` **Ruby Type:** Integer | **Default Value:** `600` Specifies a timeout (in seconds) for the feature installation. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_feature_powershell** resource in recipes: **Add the SMTP Server feature**: ``` windows_feature_powershell "smtp-server" do action :install all true end ``` **Install multiple features using one resource**: ``` windows_feature_powershell ['Web-Asp-Net45', 'Web-Net-Ext45'] do action :install end ``` **Install the Network Policy and Access Service feature**: ``` windows_feature_powershell 'NPAS' do action :install management_tools true end ``` windows_firewall_profile resource ----------------------------------- [windows_firewall_profile resource page](resources/windows_firewall_profile/index) --- Use the **windows_firewall_profile** resource to enable, disable, and configure the Windows firewall. **New in Chef Infra Client 16.3.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_firewall_profile** resource is: ``` windows_firewall_profile 'name' do allow_inbound_rules true, false, String allow_local_firewall_rules true, false, String allow_local_ipsec_rules true, false, String allow_unicast_response true, false, String allow_user_apps true, false, String allow_user_ports true, false, String default_inbound_action String default_outbound_action String display_notification true, false, String profile String # default value: 'name' unless specified action Symbol # defaults to :enable if not specified end ``` where: * `windows_firewall_profile` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_inbound_rules`, `allow_local_firewall_rules`, `allow_local_ipsec_rules`, `allow_unicast_response`, `allow_user_apps`, `allow_user_ports`, `default_inbound_action`, `default_outbound_action`, `display_notification`, and `profile` are the properties available to this resource. ### Actions --- The **windows_firewall_profile** resource has the following actions: `:disable` Disable a Windows Firewall profile. `:enable` Enable and optionally configure a Windows Firewall profile. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_firewall_profile** resource has the following properties: `allow_inbound_rules` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow users to set inbound firewall rules `allow_local_firewall_rules` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Merges inbound firewall rules into the policy `allow_local_ipsec_rules` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow users to manage local connection security rules `allow_unicast_response` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow unicast responses to multicast and broadcast messages `allow_user_apps` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow user applications to manage firewall `allow_user_ports` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Allow users to manage firewall port rules `default_inbound_action` **Ruby Type:** String **Allowed Values:** `"Allow", "Block", "NotConfigured"` Set the default policy for inbound network traffic `default_outbound_action` **Ruby Type:** String **Allowed Values:** `"Allow", "Block", "NotConfigured"` Set the default policy for outbound network traffic `display_notification` **Ruby Type:** true, false, String **Allowed Values:** `true, false, "NotConfigured"` Display a notification when firewall blocks certain activity `profile` **Ruby Type:** String | **Default Value:** `The resource block's name` **Allowed Values:** `"Domain", "Private", "Public"` Set the Windows Profile being configured ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_firewall_profile** resource in recipes: **Enable and Configure the Private Profile of the Windows Profile**: ``` windows_firewall_profile 'Private' do default_inbound_action 'Block' default_outbound_action 'Allow' allow_inbound_rules true display_notification false action :enable end ``` **Enable and Configure the Public Profile of the Windows Firewall**: ``` windows_firewall_profile 'Public' do default_inbound_action 'Block' default_outbound_action 'Allow' allow_inbound_rules false display_notification false action :enable end ``` **Disable the Domain Profile of the Windows Firewall**: ``` windows_firewall_profile 'Disable the Domain Profile of the Windows Firewall' do profile 'Domain' action :disable end ``` windows_firewall_rule resource -------------------------------- [windows_firewall_rule resource page](resources/windows_firewall_rule/index) --- Use the **windows_firewall_rule** resource to create, change or remove Windows firewall rules. **New in Chef Infra Client 14.7.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_firewall_rule** resource is: ``` windows_firewall_rule 'name' do description String direction Symbol, String # default value: :inbound displayname String # default value: The rule_name property value. enabled true, false # default value: true firewall_action Symbol, String # default value: :allow group String icmp_type String, Integer # default value: "Any" interface_type Symbol, String # default value: :any local_address String local_port String, Integer, Array profile Symbol, String, Array # default value: :any program String protocol String # default value: "TCP" remote_address String, Array remote_port String, Integer, Array rule_name String # default value: 'name' unless specified service String action Symbol # defaults to :create if not specified end ``` where: * `windows_firewall_rule` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `description`, `direction`, `displayname`, `enabled`, `firewall_action`, `group`, `icmp_type`, `interface_type`, `local_address`, `local_port`, `profile`, `program`, `protocol`, `remote_address`, `remote_port`, `rule_name`, and `service` are the properties available to this resource. ### Actions --- The **windows_firewall_rule** resource has the following actions: `:create` Create a Windows firewall entry. (default) `:delete` Delete an existing Windows firewall entry. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_firewall_rule** resource has the following properties: `description` **Ruby Type:** String The description to assign to the firewall rule. `direction` **Ruby Type:** Symbol, String | **Default Value:** `:inbound` **Allowed Values:** `:inbound, :outbound` The direction of the firewall rule. Direction means either inbound or outbound traffic. `displayname` **Ruby Type:** String | **Default Value:** `The rule_name property value.` The displayname to assign to the firewall rule. New in Chef Infra Client 16.0 `enabled` **Ruby Type:** true, false | **Default Value:** `true` Whether or not to enable the firewall rule. `firewall_action` **Ruby Type:** Symbol, String | **Default Value:** `:allow` **Allowed Values:** `:allow, :block, :notconfigured` The action of the firewall rule. `group` **Ruby Type:** String Specifies that only matching firewall rules of the indicated group association are copied. New in Chef Infra Client 16.0 `icmp_type` **Ruby Type:** String, Integer | **Default Value:** `Any` Specifies the ICMP Type parameter for using a protocol starting with ICMP New in Chef Infra Client 16.0 `interface_type` **Ruby Type:** Symbol, String | **Default Value:** `:any` **Allowed Values:** `:any, :remoteaccess, :wired, :wireless` The interface type the firewall rule applies to. `local_address` **Ruby Type:** String The local address the firewall rule applies to. `local_port` **Ruby Type:** String, Integer, Array The local port the firewall rule applies to. `profile` **Ruby Type:** Symbol, String, Array | **Default Value:** `:any` The profile the firewall rule applies to. `program` **Ruby Type:** String The program the firewall rule applies to. `protocol` **Ruby Type:** String | **Default Value:** `TCP` The protocol the firewall rule applies to. `remote_address` **Ruby Type:** String, Array The remote address(es) the firewall rule applies to. `remote_port` **Ruby Type:** String, Integer, Array The remote port the firewall rule applies to. `rule_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the name of the firewall rule to assign if it differs from the resource block’s name. `service` **Ruby Type:** String The service the firewall rule applies to. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_firewall_rule** resource in recipes: **Allowing port 80 access**: ``` windows_firewall_rule 'IIS' do local_port '80' protocol 'TCP' firewall_action :allow end ``` **Configuring multiple remote-address ports on a rule**: ``` windows_firewall_rule 'MyRule' do description 'Testing out remote address arrays' enabled false local_port 1434 remote_address %w(10.17.3.101 172.7.7.53) protocol 'TCP' action :create end ``` **Allow protocol ICMPv6 with ICMP Type**: ``` windows_firewall_rule 'CoreNet-Rule' do rule_name 'CoreNet-ICMP6-LR2-In' display_name 'Core Networking - Multicast Listener Report v2 (ICMPv6-In)' local_port 'RPC' protocol 'ICMPv6' icmp_type '8' end ``` **Blocking WinRM over HTTP on a particular IP**: ``` windows_firewall_rule 'Disable WinRM over HTTP' do local_port '5985' protocol 'TCP' firewall_action :block local_address '192.168.1.1' end ``` **Deleting an existing rule** ``` windows_firewall_rule 'Remove the SSH rule' do rule_name 'ssh' action :delete end ``` windows_font resource ---------------------- [windows_font resource page](resources/windows_font/index) --- Use the **windows_font** resource to install font files on Windows. By default, the font is sourced from the cookbook using the resource, but a URI source can be specified as well. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_font** resource is: ``` windows_font 'name' do font_name String # default value: 'name' unless specified source String action Symbol # defaults to :install if not specified end ``` where: * `windows_font` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `font_name` and `source` are the properties available to this resource. ### Actions --- The **windows_font** resource has the following actions: `:install` Install a font to the system fonts directory. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_font** resource has the following properties: `font_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the name of the font to install if it differs from the resource block’s name. `source` **Ruby Type:** String A local filesystem path or URI that is used to source the font file. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_font** resource in recipes: **Install a font from a https source**: ``` windows_font 'Custom.otf' do source 'https://example.com/Custom.otf' end ``` windows_package resource ------------------------- [windows_package resource page](resources/windows_package/index) --- Use the **windows_package** resource to manage packages on the Microsoft Windows platform. The **windows_package** resource supports these installer formats: * Microsoft Installer Package (MSI) * Nullsoft Scriptable Install System (NSIS) * Inno Setup (inno) * Wise * InstallShield * Custom installers such as installing a non-.msi file that embeds an .msi-based installer To enable idempotence of the `:install` action or to enable the `:remove` action with no source property specified, `package_name` MUST be an exact match of the name used by the package installer. The names of installed packages Windows knows about can be found in **Add/Remove programs**, in the output of `ohai packages`, or in the `DisplayName` property in one of the following in the Windows registry: * `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall` * `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall` * `HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall` Note If there are multiple versions of a package installed with the same display name, all of those packages will be removed unless a version is provided in the **version** property or unless it can be discovered in the installer file specified by the **source** property. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- A **windows_package** resource block manages a package on a node, typically by installing it. The simplest use of the **windows_package** resource is: ``` windows_package 'package_name' ``` which will install the named package using all of the default options and the default action (`:install`). The full syntax for all of the properties that are available to the **windows_package** resource is: ``` windows_package 'name' do checksum String installer_type Symbol options String package_name String remote_file_attributes Hash returns String, Integer, Array source String # default value: "The resource block's name" timeout String, Integer # default value: "600 (seconds)" version String action Symbol # defaults to :install if not specified end ``` where: * `windows_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `checksum`, `installer_type`, `options`, `package_name`, `remote_file_attributes`, `returns`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **windows_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a package. ### Properties --- The **windows_package** resource has the following properties: `checksum` **Ruby Type:** String The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, Chef Infra Client does not download it. Use when a URL is specified by the `source` property. `installer_type` **Ruby Type:** Symbol **Allowed Values:** `:custom, :inno, :installshield, :msi, :nsis, :wise` A symbol that specifies the type of package. Possible values: `:custom` (such as installing a non-.msi file that embeds an .msi-based installer), `:inno` (Inno Setup), `:installshield` (InstallShield), `:msi` (Microsoft Installer Package (MSI)), `:nsis` (Nullsoft Scriptable Install System (NSIS)), `:wise` (Wise). `options` **Ruby Type:** String One (or more) additional options that are passed to the command. `package_name` **Ruby Type:** String An optional property to set the package name if it differs from the resource block’s name. `remote_file_attributes` **Ruby Type:** Hash This property allows you to define a hash of properties and their value if the source package to be installed is at a remote location. This hash will be used by the underlying **remote_file** resource which will fetch the source package. `returns` **Ruby Type:** String, Integer, Array of integers | **Default Value:** `0 (success) and 3010 (success where a reboot is necessary)` A comma-delimited list of return codes that indicate the success or failure of the package command that was run. `source` **Ruby Type:** String | **Default Value:** `The resource block's name` The path to a package in the local file system. The location of the package may be at a URL. If the `source` property is not specified, the package name MUST be exactly the same as the display name found in **Add/Remove programs** or exactly the same as the `DisplayName` property in the appropriate registry key, which may be one of the following: ``` HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall ``` Note If there are multiple versions of a package installed with the same display name, all of those packages will be removed unless a version is provided in the `version` property or unless it can be discovered in the installer file specified by the `source` property. `timeout` **Ruby Type:** String, Integer | **Default Value:** `600 (seconds)` The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String The version of a package to be installed or upgraded. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_package** resource in recipes: **Install a package**: ``` windows_package '7zip' do action :install source 'C:\7z920.msi' end ``` **Specify a URL for the source attribute**: ``` windows_package '7zip' do source 'http://www.7-zip.org/a/7z938-x64.msi' end ``` **Specify path and checksum**: ``` windows_package '7zip' do source 'http://www.7-zip.org/a/7z938-x64.msi' checksum '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3' end ``` **Modify remote_file resource attributes**: The windows_package resource may specify a package at a remote location using the remote_file_attributes property. This uses the remote_file resource to download the contents at the specified URL and passes in a Hash that modifies the properties of the remote_file resource. ``` windows_package '7zip' do source 'http://www.7-zip.org/a/7z938-x64.msi' remote_file_attributes ({ :path => 'C:\7zip.msi', :checksum => '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3' }) end ``` **Download a nsis (Nullsoft) package resource**: ``` windows_package 'Mercurial 3.6.1 (64-bit)' do source 'http://mercurial.selenic.com/release/windows/Mercurial-3.6.1-x64.exe' checksum 'febd29578cb6736163d232708b834a2ddd119aa40abc536b2c313fc5e1b5831d' end ``` **Download a custom package**: ``` windows_package 'Microsoft Visual C++ 2005 Redistributable' do source 'https://download.microsoft.com/download/6/B/B/6BB661D6-A8AE-4819-B79F-236472F6070C/vcredist_x86.exe' installer_type :custom options '/Q' end ``` windows_pagefile resource -------------------------- [windows_pagefile resource page](resources/windows_pagefile/index) --- Use the **windows_pagefile** resource to configure pagefile settings on Windows. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_pagefile** resource is: ``` windows_pagefile 'name' do automatic_managed true, false initial_size Integer maximum_size Integer path String # default value: 'name' unless specified system_managed true, false action Symbol # defaults to :set if not specified end ``` where: * `windows_pagefile` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `automatic_managed`, `initial_size`, `maximum_size`, `path`, and `system_managed` are the properties available to this resource. ### Actions --- The **windows_pagefile** resource has the following actions: `:delete` Deletes the specified pagefile. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Configures the default pagefile, creating if it doesn’t exist. (default) ### Properties --- The **windows_pagefile** resource has the following properties: `automatic_managed` **Ruby Type:** true, false Enable automatic management of pagefile initial and maximum size. Setting this to true ignores `initial_size` and `maximum_size` properties. `initial_size` **Ruby Type:** Integer Initial size of the pagefile in megabytes. `maximum_size` **Ruby Type:** Integer Maximum size of the pagefile in megabytes. `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the pagefile name if it differs from the resource block’s name. `system_managed` **Ruby Type:** true, false Configures whether the system manages the pagefile size. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_pagefile** resource in recipes: **Set the system to manage pagefiles**: ``` windows_pagefile 'Enable automatic management of pagefiles' do automatic_managed true end ``` **Delete a pagefile**: ``` windows_pagefile 'Delete the pagefile' do path 'C' action :delete end ``` **Switch to system managed pagefiles**: ``` windows_pagefile 'Change the pagefile to System Managed' do path 'E:' system_managed true action :set end ``` **Create a pagefile with an initial and maximum size**: ``` windows_pagefile 'create the pagefile with these sizes' do path 'f:' initial_size 100 maximum_size 200 end ``` windows_path resource ---------------------- [windows_path resource page](resources/windows_path/index) --- Use the **windows_path** resource to manage the path environment variable on Microsoft Windows. **New in Chef Infra Client 13.4.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_path** resource is: ``` windows_path 'name' do path String # default value: 'name' unless specified action Symbol # defaults to :add if not specified end ``` where: * `windows_path` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `path` is the property available to this resource. ### Actions --- The **windows_path** resource has the following actions: `:add` Add an item to the system path. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove an item from the system path. ### Properties --- The **windows_path** resource has the following properties: `path` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the path value if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_path** resource in recipes: **Add Sysinternals to the system path**: ``` windows_path 'C:\Sysinternals' do action :add end ``` **Remove 7-Zip from the system path**: ``` windows_path 'C:\7-Zip' do action :remove end ``` windows_printer resource ------------------------- [windows_printer resource page](resources/windows_printer/index) --- Use the **windows_printer** resource to setup Windows printers. This resource will automatically install the driver specified in the `driver_name` property and will automatically create a printer port using either the `ipv4_address` property or the `port_name` property. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_printer** resource is: ``` windows_printer 'name' do comment String create_port true, false # default value: true default true, false # default value: false device_id String # default value: 'name' unless specified driver_name String ipv4_address String location String port_name String share_name String shared true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_printer` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `comment`, `create_port`, `default`, `device_id`, `driver_name`, `ipv4_address`, `location`, `port_name`, `share_name`, and `shared` are the properties available to this resource. ### Actions --- The **windows_printer** resource has the following actions: `:create` Create a new printer and printer port, if one doesn’t already. (default) `:delete` Delete an existing printer. Note that this resource does not delete the associated printer port. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_printer** resource has the following properties: `comment` **Ruby Type:** String Optional descriptor for the printer queue. `create_port` **Ruby Type:** true, false | **Default Value:** `true` Create a printer port for the printer. Set this to false and specify the `port_name` property if using the `windows_printer_port` resource to create the port instead. New in Chef Infra Client 17.3 `default` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not this should be the system’s default printer. `device_id` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the printer queue name if it differs from the resource block’s name. Example: `HP LJ 5200 in fifth floor copy room`. `driver_name` **Ruby Type:** String | `REQUIRED` The exact name of printer driver installed on the system. `ipv4_address` **Ruby Type:** String The IPv4 address of the printer, such as `10.4.64.23` `location` **Ruby Type:** String Printer location, such as `Fifth floor copy room`. `port_name` **Ruby Type:** String | **Default Value:** `The resource block name or the ipv4_address prepended with IP_.` The port name. New in Chef Infra Client 17.3 `share_name` **Ruby Type:** String The name used to identify the shared printer. `shared` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not the printer is shared. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_printer** resource in recipes: **Create a printer**: ``` windows_printer 'HP LaserJet 5th Floor' do driver_name 'HP LaserJet 4100 Series PCL6' ipv4_address '10.4.64.38' end ``` **Delete a printer**: Note: this doesn’t delete the associated printer port. See windows_printer_port above for how to delete the port. ``` windows_printer 'HP LaserJet 5th Floor' do action :delete end ``` **Create a printer port and a printer that uses that port (new in 17.3)** ``` windows_printer_port '10.4.64.39' do port_name 'My awesome printer port' snmp_enabled true port_protocol 2 end windows_printer 'HP LaserJet 5th Floor' do driver_name 'HP LaserJet 4100 Series PCL6' port_name 'My awesome printer port' ipv4_address '10.4.64.38' create_port false end ``` windows_printer_port resource ------------------------------- [windows_printer_port resource page](resources/windows_printer_port/index) --- Use the **windows_printer_port** resource to create and delete TCP/IPv4 printer ports on Windows. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_printer_port** resource is: ``` windows_printer_port 'name' do ipv4_address String # default value: 'name' unless specified port_name String port_number Integer # default value: 9100 port_protocol Integer # default value: 1 snmp_enabled true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_printer_port` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ipv4_address`, `port_name`, `port_number`, `port_protocol`, and `snmp_enabled` are the properties available to this resource. ### Actions --- The **windows_printer_port** resource has the following actions: `:create` Create or update the printer port. (default) `:delete` Delete an existing printer port. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_printer_port** resource has the following properties: `ipv4_address` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property for the IPv4 address of the printer if it differs from the resource block’s name. `port_name` **Ruby Type:** String | **Default Value:** `The resource block name or the ipv4_address prepended with IP_.` The port name. `port_number` **Ruby Type:** Integer | **Default Value:** `9100` The TCP port number. `port_protocol` **Ruby Type:** Integer | **Default Value:** `1` **Allowed Values:** `1, 2` The printer port protocol: 1 (RAW) or 2 (LPR). `snmp_enabled` **Ruby Type:** true, false | **Default Value:** `false` Determines if SNMP is enabled on the port. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_printer_port** resource in recipes: **Delete a printer port** ``` windows_printer_port '10.4.64.37' do action :delete end ``` **Delete a port with a custom port_name** ``` windows_printer_port '10.4.64.38' do port_name 'My awesome port' action :delete end ``` **Create a port with more options** ``` windows_printer_port '10.4.64.39' do port_name 'My awesome port' snmp_enabled true port_protocol 2 end ``` windows_security_policy resource ---------------------------------- [windows_security_policy resource page](resources/windows_security_policy/index) --- Use the **windows_security_policy** resource to set a security policy on the Microsoft Windows platform. **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_security_policy** resource is: ``` windows_security_policy 'name' do secoption String # default value: 'name' unless specified secvalue String action Symbol # defaults to :set if not specified end ``` where: * `windows_security_policy` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `secoption` and `secvalue` are the properties available to this resource. ### Actions --- The **windows_security_policy** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set the Windows security policy (default) ### Properties --- The **windows_security_policy** resource has the following properties: `secoption` **Ruby Type:** String | **Default Value:** `The resource block's name` | `REQUIRED` **Allowed Values:** `"AuditPolicyChange", "ClearTextPassword", "EnableAdminAccount", "EnableGuestAccount", "ForceLogoffWhenHourExpire", "LSAAnonymousNameLookup", "LockoutBadCount", "LockoutDuration", "LockoutDuration", "MaximumPasswordAge", "MinimumPasswordAge", "MinimumPasswordLength", "NewAdministratorName", "NewGuestName", "PasswordComplexity", "PasswordHistorySize", "RequireLogonToChangePassword", "ResetLockoutCount"` The name of the policy to be set on windows platform to maintain its security. `secvalue` **Ruby Type:** String | `REQUIRED` Policy value to be set for policy name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_security_policy** resource in recipes: **Set Administrator Account to Enabled**: ``` windows_security_policy 'EnableAdminAccount' do secvalue '1' action :set end ``` **Rename Administrator Account**: ``` windows_security_policy 'NewAdministratorName' do secvalue 'AwesomeChefGuy' action :set end ``` **Set Guest Account to Disabled**: ``` windows_security_policy 'EnableGuestAccount' do secvalue '0' action :set end ``` windows_service resource ------------------------- [windows_service resource page](resources/windows_service/index) --- Use the **windows_service** resource to create, delete, or manage a service on the Microsoft Windows platform. ### Syntax --- A **windows_service** resource block manages the state of a service on a machine that is running Microsoft Windows. For example: ``` windows_service 'BITS' do action :configure_startup startup_type :manual end ``` The full syntax for all of the properties that are available to the **windows_service** resource is: ``` windows_service 'name' do binary_path_name String delayed_start true, false # default value: false dependencies String, Array description String desired_access Integer # default value: 983551 display_name String error_control Integer # default value: 1 init_command String load_order_group String pattern String reload_command String, false restart_command String, false run_as_password String run_as_user String # default value: "LocalSystem" service_name String # default value: 'name' unless specified service_type Integer # default value: "SERVICE_WIN32_OWN_PROCESS" start_command String, false startup_type Symbol # default value: :automatic status_command String, false stop_command String, false supports Hash # default value: {"restart"=>nil, "reload"=>nil, "status"=>nil} timeout Integer action Symbol # defaults to :nothing if not specified end ``` where: * `windows_service` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `binary_path_name`, `display_name`, `desired_access`, `delayed_start`, `dependencies`, `description`, `error_control`, `init_command`, `load_order_group`, `pattern`, `reload_command`, `restart_command`, `run_as_password`, `run_as_user`, `service_name`, `service_type`, `start_command`, `startup_type`, `status_command`, `stop_command`, `supports`, and `timeout` are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. ### Actions --- The **windows_service** resource has the following actions: `:configure` Configure a pre-existing service. *New in Chef Client 14.0.* `:configure_startup` Configure a service based on the value of the `startup_type` property. `:create` Create the service based on the value of the `binary_path_name`, `service_name` and/or `display_name` property. *New in Chef Client 14.0.* `:delete` Delete the service based on the value of the `service_name` property. *New in Chef Client 14.0.* `:disable` Disable a service. This action is equivalent to a `Disabled` startup type on the Microsoft Windows platform. `:enable` Enable a service at boot. This action is equivalent to an `Automatic` startup type on the Microsoft Windows platform. `:nothing` Default. Do nothing with a service. `:reload` Reload the configuration for this service. This action is not supported on the Windows platform and will raise an error if used. `:restart` Restart a service. `:start` Start a service, and keep it running until stopped or disabled. `:stop` Stop a service. ### Properties --- The **windows_service** resource has the following properties: `binary_path_name` **Ruby Type:** String The fully qualified path to the service binary file. The path can also include arguments for an auto-start service. This is required for `:create` and `:configure` actions New in Chef Client 14.0 `delayed_start` **Ruby Type:** true, false | **Default Value:** `false` Set the startup type to delayed start. This only applies if `startup_type` is `:automatic` New in Chef Client 14.0 `dependencies` **Ruby Type:** String, Array A pointer to a double null-terminated array of null-separated names of services or load ordering groups that the system must start before this service. Specify `nil` or an empty string if the service has no dependencies. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group. New in Chef Client 14.0 `description` **Ruby Type:** String Description of the service. New in Chef Client 14.0 `desired_access` **Ruby Type:** Integer | **Default Value:** `983551` New in Chef Client 14.0 `display_name` **Ruby Type:** String The display name to be used by user interface programs to identify the service. This string has a maximum length of 256 characters. New in Chef Client 14.0 `error_control` **Ruby Type:** Integer | **Default Value:** `1` New in Chef Client 14.0 `load_order_group` **Ruby Type:** String The name of the service’s load ordering group(s). New in Chef Client 14.0 `pattern` **Ruby Type:** String | **Default Value:** `The value provided to 'service_name' or the resource block's name` The pattern to look for in the process table. `reload_command` **Ruby Type:** String, false The command used to tell a service to reload its configuration. `restart_command` **Ruby Type:** String, false The command used to restart a service. `run_as_password` **Ruby Type:** String The password for the user specified by `run_as_user`. `run_as_user` **Ruby Type:** String | **Default Value:** `localsystem` The user under which a Microsoft Windows service runs. `service_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the service name if it differs from the resource block’s name. `service_type` **Ruby Type:** Integer | **Default Value:** `16` New in Chef Client 14.0 `start_command` **Ruby Type:** String, false The command used to start a service. `startup_type` **Ruby Type:** Symbol | **Default Value:** `:automatic` **Allowed Values:** `:automatic, :disabled, :manual` Use to specify the startup type of the service. `status_command` **Ruby Type:** String, false The command used to check the run status for a service. `stop_command` **Ruby Type:** String, false The command used to stop a service. `supports` **Ruby Type:** Hash | **Default Value:** `{"restart"=>nil, "reload"=>nil, "status"=>nil}` A list of properties that controls how Chef Infra Client is to attempt to manage a service: `:restart`, `:reload`, `:status`. For `:restart`, the init script or other service provider can use a restart command; if `:restart` is not specified, Chef Infra Client attempts to stop and then start a service. For `:reload`, the init script or other service provider can use a reload command. For `:status`, the init script or other service provider can use a status command to determine if the service is running; if `:status` is not specified, Chef Infra Client attempts to match the `service_name` against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: `{ restart: false, reload: false, status: false }` for all platforms (except for the Red Hat platform family, which defaults to `{ restart: false, reload: false, status: true }`.) `timeout` **Ruby Type:** Integer | **Default Value:** `60` The amount of time (in seconds) to wait before timing out. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_service** resource in recipes: **Starting Services** Start a service with a `manual` startup type: ``` windows_service 'BITS' do action :configure_startup startup_type :manual end ``` **Creating Services** Create a service named chef-client: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" end ``` Create a service with `service_name` and `display_name`: ``` windows_service 'Setup chef-client as a service' do action :create display_name 'CHEF-CLIENT' service_name 'chef-client' binary_path_name "C:\opscode\chef\bin" end ``` Create a service with the `manual` startup type: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :manual end ``` Create a service with the `disabled` startup type: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :disabled end ``` Create a service with the `automatic` startup type and delayed start enabled: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :automatic delayed_start true end ``` Create a service with a description: ``` windows_service 'chef-client' do action :create binary_path_name "C:\opscode\chef\bin" startup_type :automatic description "Chef client as service" end ``` **Deleting Services** Delete a service named chef-client: ``` windows_service 'chef-client' do action :delete end ``` Delete a service with the `service_name` property: ``` windows_service 'Delete chef client' do action :delete service_name 'chef-client' end ``` **Configuring Services** Change an existing service from automatic to manual startup: ``` windows_service 'chef-client' do action :configure binary_path_name "C:\opscode\chef\bin" startup_type :manual end ``` windows_share resource ----------------------- [windows_share resource page](resources/windows_share/index) --- Use the **windows_share** resource to create, modify and remove Windows shares. **New in Chef Infra Client 14.7.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_share** resource is: ``` windows_share 'name' do ca_timeout Integer # default value: 0 change_users Array # default value: [] concurrent_user_limit Integer # default value: 0 continuously_available true, false # default value: false description String encrypt_data true, false # default value: false full_users Array # default value: [] path String read_users Array # default value: [] scope_name String # default value: "*" share_name String # default value: 'name' unless specified temporary true, false # default value: false action Symbol # defaults to :create if not specified end ``` where: * `windows_share` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `ca_timeout`, `change_users`, `concurrent_user_limit`, `continuously_available`, `description`, `encrypt_data`, `full_users`, `path`, `read_users`, `scope_name`, `share_name`, and `temporary` are the properties available to this resource. ### Actions --- The **windows_share** resource has the following actions: `:create` Create or modify a Windows share. (default) `:delete` Delete an existing Windows share. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_share** resource has the following properties: `ca_timeout` **Ruby Type:** Integer | **Default Value:** `0` The continuous availability time-out for the share. `change_users` **Ruby Type:** Array | **Default Value:** `[]` The users that should have ‘modify’ permission on the share in domain\username format. `concurrent_user_limit` **Ruby Type:** Integer | **Default Value:** `0` The maximum number of concurrently connected users the share can accommodate. `continuously_available` **Ruby Type:** true, false | **Default Value:** `false` Indicates that the share is continuously available. `description` **Ruby Type:** String The description to be applied to the share. `encrypt_data` **Ruby Type:** true, false | **Default Value:** `false` Indicates that the share is encrypted. `full_users` **Ruby Type:** Array | **Default Value:** `[]` The users that should have ‘Full control’ permissions on the share in domain\username format. `path` **Ruby Type:** String The path of the folder to share. Required when creating. If the share already exists on a different path then it is deleted and re-created. `read_users` **Ruby Type:** Array | **Default Value:** `[]` The users that should have ‘read’ permission on the share in domain\username format. `scope_name` **Ruby Type:** String | **Default Value:** `*` The scope name of the share. `share_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the share name if it differs from the resource block’s name. `temporary` **Ruby Type:** true, false | **Default Value:** `false` The lifetime of the new SMB share. A temporary share does not persist beyond the next restart of the computer. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_share** resource in recipes: **Create a share**: ``` windows_share 'foo' do action :create path 'C:\foo' full_users ['DOMAIN_A\some_user', 'DOMAIN_B\some_other_user'] read_users ['DOMAIN_C\Domain users'] end ``` **Delete a share**: ``` windows_share 'foo' do action :delete end ``` windows_shortcut resource -------------------------- [windows_shortcut resource page](resources/windows_shortcut/index) --- Use the **windows_shortcut** resource to create shortcut files on Windows. **New in Chef Infra Client 14.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_shortcut** resource is: ``` windows_shortcut 'name' do arguments String cwd String description String iconlocation String shortcut_name String # default value: 'name' unless specified target String action Symbol # defaults to :create if not specified end ``` where: * `windows_shortcut` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `arguments`, `cwd`, `description`, `iconlocation`, `shortcut_name`, and `target` are the properties available to this resource. ### Actions --- The **windows_shortcut** resource has the following actions: `:create` Create or modify a Windows shortcut. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_shortcut** resource has the following properties: `arguments` **Ruby Type:** String Arguments to pass to the target when the shortcut is executed. `cwd` **Ruby Type:** String Working directory to use when the target is executed. `description` **Ruby Type:** String The description of the shortcut `iconlocation` **Ruby Type:** String Icon to use for the shortcut. Accepts the format of `path, index`, where index is the icon file to use. See Microsoft’s [documentation](https://msdn.microsoft.com/en-us/library/3s9bx7at.aspx) for details `shortcut_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the shortcut name if it differs from the resource block’s name. `target` **Ruby Type:** String The destination that the shortcut links to. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_shortcut** resource in recipes: **Create a shortcut with a description**: ``` windows_shortcut 'C:\shortcut_dir.lnk' do target 'C:\original_dir' description 'Make a shortcut to C:\original_dir' end ``` windows_task resource ---------------------- [windows_task resource page](resources/windows_task/index) --- Use the **windows_task** resource to create, delete or run a Windows scheduled task. **New in Chef Infra Client 13.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_task** resource is: ``` windows_task 'name' do backup Integer, false # default value: 5 command String cwd String day String, Integer description String disallow_start_if_on_batteries true, false # default value: false execution_time_limit String, Integer # default value: "PT72H (72 hours in ISO8601 duration format)" force true, false # default value: false frequency Symbol frequency_modifier Integer, String # default value: 1 idle_time Integer interactive_enabled true, false # default value: false minutes_duration String, Integer minutes_interval String, Integer months String password String priority Integer # default value: 7 random_delay String, Integer run_level Symbol # default value: :limited start_day String # default value: The current date. start_time String start_when_available true, false # default value: false stop_if_going_on_batteries true, false # default value: false task_name String # default value: 'name' unless specified user String # default value: The localized SYSTEM user for the node. action Symbol # defaults to :create if not specified end ``` where: * `windows_task` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `backup`, `command`, `cwd`, `day`, `description`, `disallow_start_if_on_batteries`, `execution_time_limit`, `force`, `frequency`, `frequency_modifier`, `idle_time`, `interactive_enabled`, `minutes_duration`, `minutes_interval`, `months`, `password`, `priority`, `random_delay`, `run_level`, `start_day`, `start_time`, `start_when_available`, `stop_if_going_on_batteries`, `task_name`, and `user` are the properties available to this resource. ### Actions --- The **windows_task** resource has the following actions: `:create` Creates a scheduled task, or updates an existing task if any property has changed. (default) `:delete` Deletes a scheduled task. `:disable` Disables a scheduled task. `:enable` Enables a scheduled task. `:end` Ends a scheduled task. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:run` Runs a scheduled task. ### Properties --- The **windows_task** resource has the following properties: `backup` **Ruby Type:** Integer, false | **Default Value:** `5` Number of backups to keep of the task when modified/deleted. Set to false to disable backups. New in Chef Infra Client 17.0 `command` **Ruby Type:** String The command to be executed by the windows scheduled task. `cwd` **Ruby Type:** String The directory the task will be run from. `day` **Ruby Type:** String, Integer The day(s) on which the task runs. * Use this property when setting `frequency` to `:monthly` or `:weekly`. * Valid values with frequency `:weekly` are `MON`-`SUN` or `*`. * Valid values with frequency `:monthly` are `1-31`, `MON`-`SUN`, and `LASTDAY`. * Use `MON`-`SUN` or `LASTDAY` if you are setting `frequency_modifier` as “FIRST, SECOND, THIRD etc.” else use 1-31. * Multiple days should be comma separated. e.g `1, 2, 3` or `MON, WED, FRI`. `description` **Ruby Type:** String The task description. New in Chef Client 14.7 `disallow_start_if_on_batteries` **Ruby Type:** true, false | **Default Value:** `false` Disallow start of the task if the system is running on battery power. New in Chef Client 14.4 `execution_time_limit` **Ruby Type:** String, Integer | **Default Value:** `PT72H (72 hours in ISO8601 duration format)` The maximum time the task will run. This field accepts either seconds or an ISO8601 duration value. `force` **Ruby Type:** true, false | **Default Value:** `false` When used with create, will update the task. `frequency` **Ruby Type:** Symbol **Allowed Values:** `:daily, :hourly, :minute, :monthly, :none, :on_idle, :on_logon, :once, :onstart, :weekly` The frequency with which to run the task. Note This property is required in Chef Infra Client 14.1 or later. Note The `:once` value requires the `start_time` property to be set. `frequency_modifier` **Ruby Type:** Integer, String | **Default Value:** `1` * For frequency `:minute` valid values are 1 to 1439 * For frequency `:hourly` valid values are 1 to 23 * For frequency `:daily` valid values are 1 to 365 * For frequency `:weekly` valid values are 1 to 52 * For frequency `:monthly` valid values are `('FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST')` OR `1-12`. + e.g. If user want to run the task on `second week of the month` use `frequency_modifier` value as `SECOND`. Multiple values for weeks of the month should be comma separated e.g. `"FIRST, THIRD, LAST"`. + To run task every (n) months use values 1 to 12. `idle_time` **Ruby Type:** Integer For `:on_idle` frequency, the time (in minutes) without user activity that must pass to trigger the task, from `1` - `999`. `interactive_enabled` **Ruby Type:** true, false | **Default Value:** `false` Allow task to run interactively or non-interactively. Requires user and password to also be set. `minutes_duration` **Ruby Type:** String, Integer `minutes_interval` **Ruby Type:** String, Integer `months` **Ruby Type:** String The Months of the year on which the task runs, such as: `JAN, FEB` or `*`. Multiple months should be comma delimited. e.g. `Jan, Feb, Mar, Dec`. `password` **Ruby Type:** String The user’s password. The user property must be set if using this property. `priority` **Ruby Type:** Integer | **Default Value:** `7` Use to set Priority Levels range from 0 to 10. `random_delay` **Ruby Type:** String, Integer Delays the task up to a given time (in seconds). `run_level` **Ruby Type:** Symbol | **Default Value:** `:limited` **Allowed Values:** `:highest, :limited` Run with `:limited` or `:highest` privileges. `start_day` **Ruby Type:** String | **Default Value:** `The current date.` Specifies the first date on which the task runs in **MM/DD/YYYY** format. `start_time` **Ruby Type:** String Specifies the start time to run the task, in **HH:mm** format. `start_when_available` **Ruby Type:** true, false | **Default Value:** `false` To start the task at any time after its scheduled time has passed. New in Chef Client 14.15 `stop_if_going_on_batteries` **Ruby Type:** true, false | **Default Value:** `false` Scheduled task option when system is switching on battery. New in Chef Client 14.4 `task_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the task name if it differs from the resource block’s name. Example: `Task Name` or `/Task Name` `user` **Ruby Type:** String | **Default Value:** `The localized SYSTEM user for the node.` The user to run the task as. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_task** resource in recipes: **Create a scheduled task to run every 15 minutes as the Administrator user**: ``` windows_task 'chef-client' do user 'Administrator' password 'password' command 'chef-client' run_level :highest frequency :minute frequency_modifier 15 end ``` **Create a scheduled task to run every 2 days**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :daily frequency_modifier 2 end ``` **Create a scheduled task to run on specific days of the week**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly day 'Mon, Thu' end ``` **Create a scheduled task to run only once**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :once start_time '16:10' end ``` **Create a scheduled task to run on current day every 3 weeks and delay upto 1 min**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly frequency_modifier 3 random_delay '60' end ``` **Create a scheduled task to run weekly starting on Dec 28th 2018**: ``` windows_task 'chef-client 8' do command 'chef-client' run_level :highest frequency :weekly start_day '12/28/2018' end ``` **Create a scheduled task to run every Monday, Friday every 2 weeks**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :weekly frequency_modifier 2 day 'Mon, Fri' end ``` **Create a scheduled task to run when computer is idle with idle duration 20 min**: ``` windows_task 'chef-client' do command 'chef-client' run_level :highest frequency :on_idle idle_time 20 end ``` **Delete a task named “old task”**: ``` windows_task 'old task' do action :delete end ``` **Enable a task named “chef-client”**: ``` windows_task 'chef-client' do action :enable end ``` **Disable a task named “ProgramDataUpdater” with TaskPath “\Microsoft\Windows\Application Experience\ProgramDataUpdater”** ``` windows_task '\Microsoft\Windows\Application Experience\ProgramDataUpdater' do action :disable end ``` windows_uac resource --------------------- [windows_uac resource page](resources/windows_uac/index) --- The *windows_uac* resource configures UAC on Windows hosts by setting registry keys at `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System` **New in Chef Infra Client 15.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_uac** resource is: ``` windows_uac 'name' do consent_behavior_admins Symbol # default value: :prompt_for_consent_non_windows_binaries consent_behavior_users Symbol # default value: :prompt_for_creds detect_installers true, false enable_uac true, false # default value: true prompt_on_secure_desktop true, false # default value: true require_signed_binaries true, false # default value: false action Symbol # defaults to :configure if not specified end ``` where: * `windows_uac` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `consent_behavior_admins`, `consent_behavior_users`, `detect_installers`, `enable_uac`, `prompt_on_secure_desktop`, and `require_signed_binaries` are the properties available to this resource. ### Actions --- The **windows_uac** resource has the following actions: `:configure` Configures UAC by setting registry keys at `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System`. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_uac** resource has the following properties: `consent_behavior_admins` **Ruby Type:** Symbol | **Default Value:** `:prompt_for_consent_non_windows_binaries` **Allowed Values:** `:no_prompt, :prompt_for_consent, :prompt_for_consent_non_windows_binaries, :prompt_for_creds, :secure_prompt_for_consent, :secure_prompt_for_creds` Behavior of the elevation prompt for administrators in Admin Approval Mode. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ConsentPromptBehaviorAdmin. `consent_behavior_users` **Ruby Type:** Symbol | **Default Value:** `:prompt_for_creds` **Allowed Values:** `:auto_deny, :prompt_for_creds, :secure_prompt_for_creds` Behavior of the elevation prompt for standard users. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ConsentPromptBehaviorUser. `detect_installers` **Ruby Type:** true, false Detect application installations and prompt for elevation. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\EnableInstallerDetection. `enable_uac` **Ruby Type:** true, false | **Default Value:** `true` Enable or disable UAC Admin Approval Mode. If this is changed a system restart is required. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA. `prompt_on_secure_desktop` **Ruby Type:** true, false | **Default Value:** `true` Switch to the secure desktop when prompting for elevation. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\PromptOnSecureDesktop. `require_signed_binaries` **Ruby Type:** true, false | **Default Value:** `false` Only elevate executables that are signed and validated. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ValidateAdminCodeSignatures. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_uac** resource in recipes: **Disable UAC prompts for the admin**: ``` windows_uac 'Disable UAC prompts for the admin' do enable_uac true prompt_on_secure_desktop false consent_behavior_admins :no_prompt end ``` **Disable UAC entirely**: ``` windows_uac 'Disable UAC entirely' do enable_uac false end ``` windows_update_settings resource ---------------------------------- [windows_update_settings resource page](resources/windows_update_settings/index) --- Use the **windows_update_settings** resource to manage the various Windows Update patching options. **New in Chef Infra Client 17.3.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_update_settings** resource is: ``` windows_update_settings 'name' do automatic_update_option Integer, Symbol # default value: :download_and_schedule automatically_install_minor_updates true, false # default value: false block_windows_update_website true, false # default value: false custom_detection_frequency Integer # default value: 22 disable_automatic_updates true, false # default value: false disable_os_upgrades true, false # default value: false elevate_non_admins true, false # default value: true enable_detection_frequency true, false # default value: false no_reboot_with_users_logged_on true, false # default value: true scheduled_install_day String # default value: "Everyday" scheduled_install_hour Integer target_wsus_group_name String update_other_ms_products true, false # default value: true wsus_server_url String action Symbol # defaults to :set if not specified end ``` where: * `windows_update_settings` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `automatic_update_option`, `automatically_install_minor_updates`, `block_windows_update_website`, `custom_detection_frequency`, `disable_automatic_updates`, `disable_os_upgrades`, `elevate_non_admins`, `enable_detection_frequency`, `no_reboot_with_users_logged_on`, `scheduled_install_day`, `scheduled_install_hour`, `target_wsus_group_name`, `update_other_ms_products`, and `wsus_server_url` are the properties available to this resource. ### Actions --- The **windows_update_settings** resource has the following actions: `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:set` Set Windows Update settings. (default) ### Properties --- The **windows_update_settings** resource has the following properties: `automatic_update_option` **Ruby Type:** Integer, Symbol | **Default Value:** `:download_and_schedule` **Allowed Values:** `:download_and_notify, :download_and_schedule, :local_admin_decides, :notify` Control what to do when updates are found. This allows you to notify, automatically download and notify to install, automatically download and schedule the install, or let the local admin decide what action to take. `automatically_install_minor_updates` **Ruby Type:** true, false | **Default Value:** `false` Automatically install minor updates. `block_windows_update_website` **Ruby Type:** true, false | **Default Value:** `false` Block accessing the Windows Update website. `custom_detection_frequency` **Ruby Type:** Integer | **Default Value:** `22` If you decided to override the OS default detection frequency, specify your choice here. Valid choices are 0 - 22 `disable_automatic_updates` **Ruby Type:** true, false | **Default Value:** `false` Disable Windows Update. `disable_os_upgrades` **Ruby Type:** true, false | **Default Value:** `false` Disable OS upgrades. `elevate_non_admins` **Ruby Type:** true, false | **Default Value:** `true` Allow normal user accounts to temporarily be elevated to install patches. `enable_detection_frequency` **Ruby Type:** true, false | **Default Value:** `false` Used to override the OS default of how often to check for updates `no_reboot_with_users_logged_on` **Ruby Type:** true, false | **Default Value:** `true` Prevents the OS from rebooting while someone is on the console. `scheduled_install_day` **Ruby Type:** String | **Default Value:** `Everyday` **Allowed Values:** `"Everyday", "Friday", "Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday"` A day of the week to tell Windows when to install updates. `scheduled_install_hour` **Ruby Type:** Integer If you chose a scheduled day to install, then choose an hour on that day for you installation `target_wsus_group_name` **Ruby Type:** String Add the node to a WSUS Target Group. `update_other_ms_products` **Ruby Type:** true, false | **Default Value:** `true` Allows for other Microsoft products to get updates too `wsus_server_url` **Ruby Type:** String The URL of your WSUS server if you use one. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_update_settings** resource in recipes: **Set Windows Update settings**: ``` windows_update_settings 'Settings to Configure Windows Nodes to automatically receive updates' do disable_os_upgrades true elevate_non_admins true block_windows_update_website true automatically_install_minor_updates true scheduled_install_day 'Friday' scheduled_install_hour 18 update_other_ms_products true action :enable end ``` windows_user_privilege resource --------------------------------- [windows_user_privilege resource page](resources/windows_user_privilege/index) --- The windows_user_privilege resource allows to add and set principal (User/Group) to the specified privilege. Ref: <https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/user-rights-assignment **New in Chef Infra Client 16.0.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_user_privilege** resource is: ``` windows_user_privilege 'name' do principal String # default value: 'name' unless specified privilege Array, String users Array, String action Symbol # defaults to :add if not specified end ``` where: * `windows_user_privilege` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `principal`, `privilege`, and `users` are the properties available to this resource. ### Actions --- The **windows_user_privilege** resource has the following actions: `:add` Add a user privilege. (default) `:clear` Clear all user privileges `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:remove` Remove a user privilege `:set` Set the privileges that are listed in the `privilege` property for only the users listed in the `users` property. ### Properties --- The **windows_user_privilege** resource has the following properties: `principal` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to add the user to the given privilege. Use only with add and remove action. `privilege` **Ruby Type:** Array, String | `REQUIRED` One or more privileges to set for users. `users` **Ruby Type:** Array, String An optional property to set the privilege for given users. Use only with set action. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_user_privilege** resource in recipes: **Set the SeNetworkLogonRight Privilege for the Builtin Administrators Group and Authenticated Users**: ``` windows_user_privilege 'Network Logon Rights' do privilege 'SeNetworkLogonRight' users ['BUILTIN\Administrators', 'NT AUTHORITY\Authenticated Users'] action :set end ``` **Add the SeDenyRemoteInteractiveLogonRight Privilege to the Builtin Guests and Local Accounts User Groups**: ``` windows_user_privilege 'Remote interactive logon' do privilege 'SeDenyRemoteInteractiveLogonRight' users ['Builtin\Guests', 'NT AUTHORITY\Local Account'] action :add end ``` **Provide only the Builtin Guests and Administrator Groups with the SeCreatePageFile Privilege**: ``` windows_user_privilege 'Create Pagefile' do privilege 'SeCreatePagefilePrivilege' users ['BUILTIN\Guests', 'BUILTIN\Administrators'] action :set end ``` **Remove the SeCreatePageFile Privilege from the Builtin Guests Group**: ``` windows_user_privilege 'Create Pagefile' do privilege 'SeCreatePagefilePrivilege' users ['BUILTIN\Guests'] action :remove end ``` **Clear all users from the SeDenyNetworkLogonRight Privilege**: ``` windows_user_privilege 'Allow any user the Network Logon right' do privilege 'SeDenyNetworkLogonRight' action :clear end ``` windows_workgroup resource --------------------------- [windows_workgroup resource page](resources/windows_workgroup/index) --- Use the **windows_workgroup** resource to join or change the workgroup of a Windows host. **New in Chef Infra Client 14.5.** ### Syntax --- The full syntax for all of the properties that are available to the **windows_workgroup** resource is: ``` windows_workgroup 'name' do password String reboot Symbol # default value: :immediate user String workgroup_name String # default value: 'name' unless specified action Symbol # defaults to :join if not specified end ``` where: * `windows_workgroup` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `password`, `reboot`, `user`, and `workgroup_name` are the properties available to this resource. ### Actions --- The **windows_workgroup** resource has the following actions: `:join` Update the workgroup. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **windows_workgroup** resource has the following properties: `password` **Ruby Type:** String The password for the local administrator user. Required if using the `user` property. `reboot` **Ruby Type:** Symbol | **Default Value:** `:immediate` **Allowed Values:** `:never, :reboot_now, :request_reboot` Controls the system reboot behavior post workgroup joining. Reboot immediately, after the Chef Infra Client run completes, or never. Note that a reboot is necessary for changes to take effect. `user` **Ruby Type:** String The local administrator user to use to change the workgroup. Required if using the `password` property. `workgroup_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the workgroup name if it differs from the resource block’s name. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **windows_workgroup** resource in recipes: **Join a workgroup**: ``` windows_workgroup 'myworkgroup' ``` **Join a workgroup using a specific user**: ``` windows_workgroup 'myworkgroup' do user 'Administrator' password 'passw0rd' end ``` yum_package resource --------------------- [yum_package resource page](resources/yum_package/index) --- Use the **yum_package** resource to install, upgrade, and remove packages with Yum for the Red Hat and CentOS platforms. The yum_package resource is able to resolve `provides` data for packages much like Yum can do when it is run from the command line. This allows a variety of options for installing packages, like minimum versions, virtual provides, and library names. Note Support for using file names to install packages (as in `yum_package '/bin/sh'`) is not available because the volume of data required to parse for this is excessive. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- The full syntax for all of the properties that are available to the **yum_package** resource is: ``` yum_package 'name' do allow_downgrade true, false # default value: true arch String, Array flush_cache Hash # default value: {"before"=>false, "after"=>false} options String, Array package_name String, Array source String timeout String, Integer version String, Array yum_binary String action Symbol # defaults to :install if not specified end ``` where: * `yum_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `arch`, `flush_cache`, `options`, `package_name`, `source`, `timeout`, `version`, and `yum_binary` are the properties available to this resource. ### Actions --- The **yum_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:lock` Locks the yum package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:remove` Remove a package. `:unlock` Unlocks the yum package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. This action will ignore the `version` attribute. ### Properties --- The **yum_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. `arch` **Ruby Type:** String, Array The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name. `flush_cache` **Ruby Type:** Hash | **Default Value:** `{"before"=>false, "after"=>false}` Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Accepts a Hash in the form: { :before => true/false, :after => true/false } or an Array in the form [ :before, :after ]. Yum automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while the Chef Infra Client run is in-progress. As an array: ``` yum_package 'some-package' do #... flush_cache [ :before ] #... end ``` and as a Hash: ``` yum_package 'some-package' do #... flush_cache( { :after => true } ) #... end ``` Note The `flush_cache` property does not flush the local Yum cache! Use Yum tools—`yum clean headers`, `yum clean packages`, `yum clean all`—to clean the local Yum cache. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array One of the following: the name of a package, the name of a package and its architecture, the name of a dependency. Default value: the `name` of the resource block. See “Syntax” section above for more information. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. This property is ignored when using the `:upgrade` action. `yum_binary` **Ruby Type:** String The path to the yum binary. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **yum_package** resource in recipes: **Install an exact version**: ``` yum_package 'netpbm = 10.35.58-8.el8' ``` **Install a minimum version**: ``` yum_package 'netpbm >= 10.35.58-8.el8' ``` **Install a minimum version using the default action**: ``` yum_package 'netpbm' ``` **Install a version without worrying about the exact release**: ``` yum_package 'netpbm-10.35*' ``` **To install a package**: ``` yum_package 'netpbm' do action :install end ``` **To install a partial minimum version**: ``` yum_package 'netpbm >= 10' ``` **To install a specific architecture**: ``` yum_package 'netpbm' do arch 'i386' end ``` or: ``` yum_package 'netpbm.x86_64' ``` **To install a specific version-release** ``` yum_package 'netpbm' do version '10.35.58-8.el8' end ``` **Handle cookbook_file and yum_package resources in the same recipe**: When a **cookbook_file** resource and a **yum_package** resource are both called from within the same recipe, use the `flush_cache` attribute to dump the in-memory Yum cache, and then use the repository immediately to ensure that the correct package is installed: ``` cookbook_file '/etc/yum.repos.d/custom.repo' do source 'custom' mode '0755' end yum_package 'pkg-that-is-only-in-custom-repo' do action :install flush_cache [ :before ] end ``` yum_repository resource ------------------------ [yum_repository resource page](resources/yum_repository/index) --- Use the **yum_repository** resource to manage a Yum repository configuration file located at `/etc/yum.repos.d/repositoryid.repo` on the local machine. This configuration file specifies which repositories to reference, how to handle cached data, etc. **New in Chef Infra Client 12.14.** ### Syntax --- The full syntax for all of the properties that are available to the **yum_repository** resource is: ``` yum_repository 'name' do baseurl String, Array clean_metadata true, false # default value: true cost String description String # default value: "Yum Repository" enabled true, false # default value: true enablegroups true, false exclude String failovermethod String fastestmirror_enabled true, false gpgcheck true, false # default value: true gpgkey String, Array http_caching String include_config String includepkgs String keepalive true, false make_cache true, false # default value: true max_retries String, Integer metadata_expire String metalink String mirror_expire String mirrorlist String mirrorlist_expire String mode String, Integer # default value: "0644" options Hash password String priority String proxy String proxy_password String proxy_username String repo_gpgcheck true, false report_instanceid true, false reposdir String # default value: "/etc/yum.repos.d/" repositoryid String # default value: 'name' unless specified skip_if_unavailable true, false source String sslcacert String sslclientcert String sslclientkey String sslverify true, false throttle String, Integer timeout String username String action Symbol # defaults to :create if not specified end ``` where: * `yum_repository` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `baseurl`, `clean_metadata`, `cost`, `description`, `enabled`, `enablegroups`, `exclude`, `failovermethod`, `fastestmirror_enabled`, `gpgcheck`, `gpgkey`, `http_caching`, `include_config`, `includepkgs`, `keepalive`, `make_cache`, `max_retries`, `metadata_expire`, `metalink`, `mirror_expire`, `mirrorlist`, `mirrorlist_expire`, `mode`, `options`, `password`, `priority`, `proxy`, `proxy_password`, `proxy_username`, `repo_gpgcheck`, `report_instanceid`, `reposdir`, `repositoryid`, `skip_if_unavailable`, `source`, `sslcacert`, `sslclientcert`, `sslclientkey`, `sslverify`, `throttle`, `timeout`, and `username` are the properties available to this resource. ### Actions --- The **yum_repository** resource has the following actions: `:create` Create a repository based on the properties. (default) `:delete` Remove a repository. `:makecache` Force the creation of the repository cache. This is also done automatically when a repository is updated. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. ### Properties --- The **yum_repository** resource has the following properties: `baseurl` **Ruby Type:** String, Array URL to the directory where the Yum repository’s `repodata` directory lives. Can be an `http://`, `https://` or a `ftp://` URLs. You can specify multiple URLs in one `baseurl` statement. `clean_metadata` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether you want to purge all of the packages downloaded from a Yum repository and held in a cache directory. `cost` **Ruby Type:** String Relative cost of accessing this repository. Useful for weighing one repo’s packages as greater/less than any other. `description` **Ruby Type:** String | **Default Value:** `Yum Repository` Descriptive name for the repository channel and maps to the ‘name’ parameter in a repository .conf. `enabled` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether or not Yum should use this repository. `enablegroups` **Ruby Type:** true, false Specifies whether Yum will allow the use of package groups for this repository. `exclude` **Ruby Type:** String List of packages to exclude from updates or installs. This should be a space separated list. Shell globs using wildcards (eg. * and ?) are allowed. `failovermethod` **Ruby Type:** String **Allowed Values:** `"priority", "roundrobin"` Method to determine how to switch to a new server if the current one fails, which can either be `roundrobin` or `priority`. `roundrobin` randomly selects a URL out of the list of URLs to start with and proceeds through each of them as it encounters a failure contacting the host. `priority` starts from the first `baseurl` listed and reads through them sequentially. `fastestmirror_enabled` **Ruby Type:** true, false Specifies whether to use the fastest mirror from a repository configuration when more than one mirror is listed in that configuration. `gpgcheck` **Ruby Type:** true, false | **Default Value:** `true` Specifies whether or not Yum should perform a GPG signature check on the packages received from a repository. `gpgkey` **Ruby Type:** String, Array URL pointing to the ASCII-armored GPG key file for the repository. This is used if Yum needs a public key to verify a package and the required key hasn’t been imported into the RPM database. If this option is set, Yum will automatically import the key from the specified URL. Multiple URLs may be specified in the same manner as the baseurl option. If a GPG key is required to install a package from a repository, all keys specified for that repository will be installed. Multiple URLs may be specified in the same manner as the baseurl option. If a GPG key is required to install a package from a repository, all keys specified for that repository will be installed. `http_caching` **Ruby Type:** String **Allowed Values:** `"all", "none", "packages"` Determines how upstream HTTP caches are instructed to handle any HTTP downloads that Yum does. This option can take the following values: * `all` means all HTTP downloads should be cached * `packages` means only RPM package downloads should be cached, but not repository metadata downloads * `none` means no HTTP downloads should be cached. The default value of `all` is recommended unless you are experiencing caching related issues. `include_config` **Ruby Type:** String An external configuration file using the format `url://to/some/location`. `includepkgs` **Ruby Type:** String Inverse of exclude property. This is a list of packages you want to use from a repository. If this option lists only one package then that is all Yum will ever see from the repository. `keepalive` **Ruby Type:** true, false Determines whether or not HTTP/1.1 `keep-alive` should be used with this repository. `make_cache` **Ruby Type:** true, false | **Default Value:** `true` Determines whether package files downloaded by Yum stay in cache directories. By using cached data, you can carry out certain operations without a network connection. `max_retries` **Ruby Type:** String, Integer Number of times any attempt to retrieve a file should retry before returning an error. Setting this to `0` makes Yum try forever. `metadata_expire` **Ruby Type:** String Time (in seconds) after which the metadata will expire. If the current metadata downloaded is less than the value specified, then Yum will not update the metadata against the repository. If you find that Yum is not downloading information on updates as often as you would like lower the value of this option. You can also change from the default of using seconds to using days, hours or minutes by appending a `d`, `h` or `m` respectively. The default is six hours to compliment yum-updates running once per hour. It is also possible to use the word `never`, meaning that the metadata will never expire. Note When using a metalink file, the metalink must always be newer than the metadata for the repository due to the validation, so this timeout also applies to the metalink file. `metalink` **Ruby Type:** String Specifies a URL to a metalink file for the repomd.xml, a list of mirrors for the entire repository are generated by converting the mirrors for the repomd.xml file to a baseurl. `mirror_expire` **Ruby Type:** String Time (in seconds) after which the mirrorlist locally cached will expire. If the current mirrorlist is less than this many seconds old then Yum will not download another copy of the mirrorlist, it has the same extra format as metadata_expire. If you find that Yum is not downloading the mirrorlists as often as you would like lower the value of this option. You can also change from the default of using seconds to using days, hours or minutes by appending a `d`, `h` or `m` respectively. `mirrorlist` **Ruby Type:** String URL to a file containing a list of baseurls. This can be used instead of or with the baseurl option. Substitution variables, described below, can be used with this option. `mirrorlist_expire` **Ruby Type:** String Specifies the time (in seconds) after which the mirrorlist locally cached will expire. If the current mirrorlist is less than the value specified, then Yum will not download another copy of the mirrorlist. You can also change from the default of using seconds to using days, hours or minutes by appending a `d`, `h` or `m` respectively. `mode` **Ruby Type:** String, Integer | **Default Value:** `0644` Permissions mode of .repo file on disk. This is useful for scenarios where secrets are in the repo file. If this value is set to `600`, normal users will not be able to use Yum search, Yum info, etc. `options` **Ruby Type:** Hash Specifies the repository options. `password` **Ruby Type:** String Password to use with the username for basic authentication. `priority` **Ruby Type:** String Assigns a priority to a repository where the priority value is between `1` and `99` inclusive. Priorities are used to enforce ordered protection of repositories. Packages from repositories with a lower priority (higher numerical value) will never be used to upgrade packages that were installed from a repository with a higher priority (lower numerical value). The repositories with the lowest numerical priority number have the highest priority. `proxy` **Ruby Type:** String URL to the proxy server that Yum should use. `proxy_password` **Ruby Type:** String Password for this proxy. `proxy_username` **Ruby Type:** String Username to use for proxy. `repo_gpgcheck` **Ruby Type:** true, false Determines whether or not Yum should perform a GPG signature check on the repodata from this repository. `report_instanceid` **Ruby Type:** true, false Determines whether to report the instance ID when using Amazon Linux AMIs and repositories. `reposdir` **Ruby Type:** String | **Default Value:** `/etc/yum.repos.d/` The directory where the Yum repository files should be stored New in Chef Infra Client 16.9 `repositoryid` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the repository name if it differs from the resource block’s name. `skip_if_unavailable` **Ruby Type:** true, false Allow yum to continue if this repository cannot be contacted for any reason. `source` **Ruby Type:** String Use a custom template source instead of the default one. `sslcacert` **Ruby Type:** String Path to the directory containing the databases of the certificate authorities Yum should use to verify SSL certificates. `sslclientcert` **Ruby Type:** String Path to the SSL client certificate Yum should use to connect to repos/remote sites. `sslclientkey` **Ruby Type:** String Path to the SSL client key Yum should use to connect to repos/remote sites. `sslverify` **Ruby Type:** true, false Determines whether Yum will verify SSL certificates/hosts. `throttle` **Ruby Type:** String, Integer Enable bandwidth throttling for downloads. `timeout` **Ruby Type:** String Number of seconds to wait for a connection before timing out. Defaults to 30 seconds. This may be too short of a time for extremely overloaded sites. `username` **Ruby Type:** String Username to use for basic authentication to a repository. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **yum_repository** resource in recipes: **Add an internal company repository**: ``` yum_repository 'OurCo' do description 'OurCo yum repository' mirrorlist 'http://artifacts.ourco.org/mirrorlist?repo=ourco-8&arch=$basearch' gpgkey 'http://artifacts.ourco.org/pub/<KEY>' action :create end ``` **Delete a repository**: ``` yum_repository 'CentOS-Media' do action :delete end ``` zypper_package resource ------------------------ [zypper_package resource page](resources/zypper_package/index) --- Use the **zypper_package** resource to install, upgrade, and remove packages with Zypper for the SUSE Enterprise and openSUSE platforms. Note In many cases, it is better to use the **package** resource instead of this one. This is because when the **package** resource is used in a recipe, Chef Infra Client will use details that are collected by Ohai at the start of a Chef Infra Client run to determine the correct package application. Using the **package** resource allows a recipe to be authored in a way that allows it to be used across many platforms. ### Syntax --- The full syntax for all of the properties that are available to the **zypper_package** resource is: ``` zypper_package 'name' do allow_downgrade true, false # default value: true global_options String, Array gpg_check true, false # default value: "true" options String, Array package_name String, Array source String timeout String, Integer version String, Array action Symbol # defaults to :install if not specified end ``` where: * `zypper_package` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `allow_downgrade`, `global_options`, `gpg_check`, `options`, `package_name`, `source`, `timeout`, and `version` are the properties available to this resource. ### Actions --- The **zypper_package** resource has the following actions: `:install` Default. Install a package. If a version is specified, install the specified version of the package. `:lock` Locks the zypper package to a specific version. `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:purge` Purge a package. This action typically removes the configuration files as well as the package. `:reconfig` Reconfigure a package. This action requires a response file. `:remove` Remove a package. `:unlock` Unlocks the zypper package so that it can be upgraded to a newer version. `:upgrade` Install a package and/or ensure that a package is the latest version. ### Properties --- The **zypper_package** resource has the following properties: `allow_downgrade` **Ruby Type:** true, false | **Default Value:** `true` Allow downgrading a package to satisfy requested version requirements. New in Chef Client 13.6 `global_options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. For example, common zypper directives, such as `--no-recommends`. See the [zypper man page](https://en.opensuse.org/SDB:Zypper_manual_(plain)) for the full list. New in Chef Client 14.6 `gpg_check` **Ruby Type:** true, false | **Default Value:** `true` Verify the package’s GPG signature. Can also be controlled site-wide using the `zypper_check_gpg` config option. `options` **Ruby Type:** String, Array One (or more) additional command options that are passed to the command. `package_name` **Ruby Type:** String, Array An optional property to set the package name if it differs from the resource block’s name. `source` **Ruby Type:** String The optional path to a package on the local file system. `timeout` **Ruby Type:** String, Integer The amount of time (in seconds) to wait before timing out. `version` **Ruby Type:** String, Array The version of a package to be installed or upgraded. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. #### Multiple Packages A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to: * Download the specified packages and versions via a single HTTP transaction * Update or install multiple packages with a single resource during a Chef Infra Client run For example, installing multiple packages: ``` package %w(package1 package2) ``` Installing multiple packages with versions: ``` package %w(package1 package2) do version [ '1.3.4-2', '4.3.6-1'] end ``` Upgrading multiple packages: ``` package %w(package1 package2) do action :upgrade end ``` Removing multiple packages: ``` package %w(package1 package2) do action :remove end ``` Purging multiple packages: ``` package %w(package1 package2) do action :purge end ``` Notifications, via an implicit name: ``` package %w(package1 package2) do action :nothing end log 'call a notification' do notifies :install, 'package[package1, package2]', :immediately end ``` Note Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the `package_name` or `version` properties. ### Examples --- The following examples demonstrate various approaches for using the **zypper_package** resource in recipes: **Install a package using package manager:** ``` zypper_package 'name of package' do action :install end ``` **Install a package using local file:** ``` zypper_package 'jwhois' do action :install source '/path/to/jwhois.rpm' end ``` **Install without using recommend packages as a dependency:** ``` package 'apache2' do options '--no-recommends' end ``` zypper_repository resource --------------------------- [zypper_repository resource page](resources/zypper_repository/index) --- Use the **zypper_repository** resource to create Zypper package repositories on SUSE Enterprise Linux and openSUSE systems. This resource maintains full compatibility with the **zypper_repository** resource in the existing **zypper** cookbook. **New in Chef Infra Client 13.3.** ### Syntax --- The full syntax for all of the properties that are available to the **zypper_repository** resource is: ``` zypper_repository 'name' do autorefresh true, false # default value: true baseurl String cookbook String # default value: "The cookbook containing the resource" description String enabled true, false # default value: true gpgautoimportkeys true, false # default value: true gpgcheck true, false # default value: true gpgkey String, Array # default value: [] keeppackages true, false # default value: false mirrorlist String mode String, Integer # default value: "0644" path String priority Integer # default value: 99 refresh_cache true, false # default value: true repo_name String # default value: 'name' unless specified source String type String # default value: "NONE" action Symbol # defaults to :create if not specified end ``` where: * `zypper_repository` is the resource. * `name` is the name given to the resource block. * `action` identifies which steps Chef Infra Client will take to bring the node into the desired state. * `autorefresh`, `baseurl`, `cookbook`, `description`, `enabled`, `gpgautoimportkeys`, `gpgcheck`, `gpgkey`, `keeppackages`, `mirrorlist`, `mode`, `path`, `priority`, `refresh_cache`, `repo_name`, `source`, and `type` are the properties available to this resource. ### Actions --- The **zypper_repository** resource has the following actions: `:create` Add a new Zypper repository. (default) `:nothing` This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run. `:refresh` Refresh Zypper repository. `:remove` Remove a Zypper repository. ### Properties --- The **zypper_repository** resource has the following properties: `autorefresh` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the repository should be refreshed automatically. `baseurl` **Ruby Type:** String The base URL for the Zypper repository, such as `http://download.opensuse.org`. `cookbook` **Ruby Type:** String | **Default Value:** `The cookbook containing the resource` The cookbook to source the repository template file from. Only necessary if you’re using a custom template for the repository file. `description` **Ruby Type:** String The description of the repository that will be shown by the `zypper repos` command. `enabled` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the repository should be enabled. `gpgautoimportkeys` **Ruby Type:** true, false | **Default Value:** `true` Automatically import the specified key when setting up the repository. `gpgcheck` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not to perform a GPG signature check on the repository. `gpgkey` **Ruby Type:** String, Array | **Default Value:** `[]` The location of the repository key(s) to be imported. `keeppackages` **Ruby Type:** true, false | **Default Value:** `false` Determines whether or not packages should be saved. `mirrorlist` **Ruby Type:** String The URL of the mirror list that will be used. `mode` **Ruby Type:** String, Integer | **Default Value:** `0644` The file mode of the repository file. `path` **Ruby Type:** String The relative path from the repository’s base URL. `priority` **Ruby Type:** Integer | **Default Value:** `99` Determines the priority of the Zypper repository. `refresh_cache` **Ruby Type:** true, false | **Default Value:** `true` Determines whether or not the package cache should be refreshed. `repo_name` **Ruby Type:** String | **Default Value:** `The resource block's name` An optional property to set the repository name if it differs from the resource block’s name. `source` **Ruby Type:** String The name of the template for the repository file. Only necessary if you’re using a custom template for the repository file. `type` **Ruby Type:** String | **Default Value:** `NONE` Specifies the repository type. ### Common Resource Functionality --- Chef resources include common properties, notifications, and resource guards. #### Common Properties The following properties are common to every resource: `compile_time` **Ruby Type:** true, false | **Default Value:** `false` Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the `compile phase`). Set to false to run while Chef Infra Client is configuring the node (the `converge phase`). `ignore_failure` **Ruby Type:** true, false, :quiet | **Default Value:** `false` Continue running a recipe if a resource fails for any reason. `:quiet` will not display the full stack trace and the recipe will continue to run if a resource fails. `retries` **Ruby Type:** Integer | **Default Value:** `0` The number of attempts to catch exceptions and retry the resource. `retry_delay` **Ruby Type:** Integer | **Default Value:** `2` The delay in seconds between retry attempts. `sensitive` **Ruby Type:** true, false | **Default Value:** `false` Ensure that sensitive resource data is not logged by Chef Infra Client. #### Notifications `notifies` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may notify another resource to take action when its state changes. Specify a `'resource[name]'`, the `:action` that resource should take, and then the `:timer` for that action. A resource may notify more than one resource; use a `notifies` statement for each resource to be notified. If the referenced resource does not exist, an error is raised. In contrast, `subscribes` will not fail if the source resource is not found. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `notifies` is: ``` notifies :action, 'resource[name]', :timer ``` `subscribes` **Ruby Type:** Symbol, 'Chef::Resource[String]' A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a `'resource[name]'`, the `:action` to be taken, and then the `:timer` for that action. Note that `subscribes` does not apply the specified action to the resource that it listens to - for example: ``` file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end ``` In this case the `subscribes` property reloads the `nginx` service whenever its certificate file, located under `/etc/nginx/ssl/example.crt`, is updated. `subscribes` does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the `:reload` action for its resource (in this example `nginx`) when a change is detected. If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of `notifies`, which will raise an error if the other resource does not exist. A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available: `:before` Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. `:delayed` Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run. `:immediate`, `:immediately` Specifies that a notification should be run immediately, per resource notified. The syntax for `subscribes` is: ``` subscribes :action, 'resource[name]', :timer ``` #### Guards A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value: * A string is executed as a shell command. If the command returns `0`, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a **powershell_script** run Windows PowerShell commands and may return `true` in addition to `0`. * A block is executed as Ruby code that must return either `true` or `false`. If the block returns `true`, the guard property is applied. If the block returns `false`, the guard property is not applied. A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing. **Properties** The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run: `not_if` Prevent a resource from executing when the condition returns `true`. `only_if` Allow a resource to execute only if the condition returns `true`. ### Examples --- The following examples demonstrate various approaches for using the **zypper_repository** resource in recipes: **Add the Apache repo on openSUSE Leap 15**: ``` zypper_repository 'apache' do baseurl 'http://download.opensuse.org/repositories/Apache' path '/openSUSE_Leap_15.2' type 'rpm-md' priority '100' end ``` **Remove the repo named ‘apache’**: ``` zypper_repository 'apache' do action :delete end ``` **Refresh the repo named ‘apache’**: ``` zypper_repository 'apache' do action :refresh end ``` © Chef Software, Inc. Licensed under the Creative Commons Attribution 3.0 Unported License. The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission. We are not affiliated with, endorsed or sponsored by Chef Inc. <https://docs.chef.io/resourceschef~18
kretes
npm
JavaScript
Kretes === Kretes is a **programming environment** for building modern web applications using TypeScript & Node.js with *batteries included* approach. It is an **integrated** solution that optimizes for programmers productivity by reducing choices and incorporating community conventions. ### [kretes.dev](https://kretes.dev) • [Tutorial](https://kretes.dev/docs/tutorial/) Table of Contents --- * [Rationale](#rationale) * [Features In A Nutshell](#features-in-a-nutshell) Rationale --- Kretes is being built with *battery included* approach in mind, i.e. it comes with a (eventually large) library of useful modules which are developed in a coherent way. This stands in direct opposition to Koa approach. Kretes tries to formalize conventions and eliminate valueless choices by providing solid defaults for building web applications that increase the programmers productivity. Kretes fights against [the accidental complexity](https://wiki.c2.com/?AccidentalComplexity). Let's focus on business needs of our applications instead of constantly configuring, patching and putting together various software elements. Features In A Nutshell --- Kretes bridges client-side (*frontend*) and server-side (*backend*) development by using [a single programming language - JavaScript - across the board](https://cdb.reacttraining.com/universal-javascript-4761051b7ae9). The project draws inspiration from Rails while trying to be less *magical*, if any at all. In Kretes, you write your applications using [TypeScript](https://www.typescriptlang.org/). As a secondary goal, Kretes tries to minimize the dependencies. It uses external packages only if absolutely necessary (e.g. security, OS abstractions etc). Roadmap --- Kretes keeps track of the upcoming fixes and features on GitHub Projects: [Kretes Roadmap](https://github.com/kreteshq/kretes/projects/1) Bug reports --- We use *Github Issues* for managing bug reports and feature requests. If you run into problems, please search the *issues* or submit a new one here: <https://github.com/kreteshq/kretes/issuesDetailed bug reports are always great; it's event better if you are able to include test cases. Readme --- ### Keywords * kretes * typescript * framework * node.js * web * snowpack * esbuild * api * react * vue * solidjs * front-end
madmom
readthedoc
SQL
madmom 0.17.dev0 documentation [madmom](index.html#document-index) --- Madmom documentation[¶](#madmom-documentation) === Introduction[¶](#introduction) --- Madmom is an audio signal processing library written in Python with a strong focus on music information retrieval (MIR) tasks. The project is on [GitHub](https://github.com/CPJKU/madmom). It’s main features / design goals are: * ease of use, * rapid prototyping of signal processing workflows, * most things are modeled as numpy arrays (enhanced by additional methods and attributes), * simple conversion of a workflow to a running program by the use of processors, * no dependencies on other software packages (not even for machine learning stuff), * inclusion of reference implementations for several state-of-the-art algorithms. Madmom is a work in progress, thus input is always welcome. The available documentation is limited for now, but [you can help to improve it](index.html#write-documentation). Installation[¶](#installation) --- Please do not try to install from the .zip files provided by GitHub. Rather install either install [from package](#install-from-package) (if you just want to use it) or [from source](#install-from-source) (if you plan to use it for development). Whichever variant you choose, please make sure that all [prerequisites](#install-prerequisites) are installed. ### Prerequisites[¶](#prerequisites) To install the `madmom` package, you must have either Python 2.7 or Python 3.3 or newer and the following packages installed: To install the `madmom` package, you must have either Python 2.7 or Python 3.5 or newer and the following packages installed: * [numpy](http://www.numpy.org) * [scipy](http://www.scipy.org) * [cython](http://www.cython.org) * [mido](https://github.com/olemb/mido) In order to test your installation, process live audio input, or have improved FFT performance, additionally install these packages: * [pytest](https://www.pytest.org/) * [pyaudio](http://people.csail.mit.edu/hubert/pyaudio/) * [pyfftw](https://github.com/pyFFTW/pyFFTW/) If you need support for audio files other than `.wav` with a sample rate of 44.1kHz and 16 bit depth, you need `ffmpeg` (`avconv` on Ubuntu Linux has some decoding bugs, so we advise not to use it!). Please refer to the `requirements.txt` file for the minimum required versions and make sure that these modules are up to date, otherwise it can result in unexpected errors or false computations! ### Install from package[¶](#install-from-package) The instructions given here should be used if you just want to install the package, e.g. to run the bundled programs or use some functionality for your own project. If you intend to change anything within the madmom package, please follow the steps in [the next section](#install-from-source). The easiest way to install the package is via `pip` from the [PyPI (Python Package Index)](https://pypi.python.org/pypi): ``` pip install madmom ``` This includes the latest code and trained models and will install all dependencies automatically. You might need higher privileges (use su or sudo) to install the package, model files and scripts globally. Alternatively you can install the package locally (i.e. only for you) by adding the `--user` argument: ``` pip install --user madmom ``` This will also install the executable programs to a common place (e.g. `/usr/local/bin`), which should be in your `$PATH` already. If you installed the package locally, the programs will be copied to a folder which might not be included in your `$PATH` (e.g. `~/Library/Python/2.7/bin` on Mac OS X or `~/.local/bin` on Ubuntu Linux, `pip` will tell you). Thus the programs need to be called explicitely or you can add their install path to your `$PATH` environment variable: ``` export PATH='path/to/scripts':$PATH ``` ### Install from source[¶](#install-from-source) If you plan to use the package as a developer, clone the Git repository: ``` git clone --recursive https://github.com/CPJKU/madmom.git ``` Since the pre-trained model/data files are not included in this repository but rather added as a Git submodule, you either have to clone the repo recursively. This is equivalent to these steps: ``` git clone https://github.com/CPJKU/madmom.git cd madmom git submodule update --init --remote ``` Then you can simply install the package in development mode: ``` python setup.py develop --user ``` To run the included tests: ``` python setup.py pytest ``` ### Upgrade of existing installations[¶](#upgrade-of-existing-installations) To upgrade the package, please use the same mechanism (pip vs. source) as you did for installation. If you want to change from package to source, please uninstall the package first. #### Upgrade a package[¶](#upgrade-a-package) Simply upgrade the package via pip: ``` pip install --upgrade madmom [--user] ``` If some of the provided programs or models changed (please refer to the CHANGELOG) you should first uninstall the package and then reinstall: ``` pip uninstall madmom pip install madmom [--user] ``` #### Upgrade from source[¶](#upgrade-from-source) Simply pull the latest sources: ``` git pull ``` To update the models contained in the submodule: ``` git submodule update ``` If any of the `.pyx` or `.pxd` files changed, you have to recompile the modules with Cython: ``` python setup.py build_ext --inplace ``` Usage[¶](#usage) --- ### Executable programs[¶](#executable-programs) The package includes executable programs in the `/bin` folder. These are standalone reference implementations of the algorithms contained in the package. If you just want to try/use these programs, please follow the [instruction to install from a package](index.html#install-from-package). All scripts can be run in different modes: in `single` file mode to process a single audio file and write the output to STDOUT or the given output file: ``` DBNBeatTracker single [-o OUTFILE] INFILE ``` If multiple audio files should be processed, the scripts can also be run in `batch` mode to write the outputs to files with the given suffix: ``` DBNBeatTracker batch [-o OUTPUT_DIR] [-s OUTPUT_SUFFIX] FILES ``` If no output directory is given, the program writes the output files to same location as the audio files. Some programs can also be run in `online` mode, i.e. operate on live audio signals. This requires [pyaudio](http://people.csail.mit.edu/hubert/pyaudio/) to be installed: ``` DBNBeatTracker online [-o OUTFILE] [INFILE] ``` The `pickle` mode can be used to store the used parameters to be able to exactly reproduce experiments. Please note that the program itself as well as the modes have help messages: ``` DBNBeatTracker -h DBNBeatTracker single -h DBNBeatTracker batch -h DBNBeatTracker online -h DBNBeatTracker pickle -h ``` will give different help messages. ### Library usage[¶](#library-usage) To use the library, [installing it from source](index.html#install-from-source) is the preferred way. Installation from package works as well, but you’re limited to the functionality provided and can’t extend the library. The basic usage is: ``` import madmom import numpy as np ``` To learn more about how to use the library please follow the [tutorials](index.html#document-tutorial). Tutorials[¶](#tutorials) --- This page gives instructions on how to use the package. They are bundled as a loose collection of jupyter (IPython) notebooks. You can view them online: <https://github.com/CPJKU/madmom_tutorialsDevelopment[¶](#development) --- As an open-source project by researchers for researchers, we highly welcome any contribution! ### What to contribute[¶](#what-to-contribute) #### Give feedback[¶](#give-feedback) To send us general feedback, questions or ideas for improvement, please post on [our mailing list](https://groups.google.com/d/forum/madmom-users). #### Report bugs[¶](#report-bugs) Please report any bugs at the [issue tracker on GitHub](https://github.com/CPJKU/madmom/issues). If you are reporting a bug, please include: * your version of madmom, * steps to reproduce the bug, ideally reduced to as few commands as possible, * the results you obtain, and the results you expected instead. If you are unsure whether the experienced behaviour is intended or a bug, please just ask on [our mailing list](https://groups.google.com/d/forum/madmom-users) first. #### Fix bugs[¶](#fix-bugs) Look for anything tagged with “bug” on the [issue tracker on GitHub](https://github.com/CPJKU/madmom/issues) and fix it. #### Features[¶](#features) Please do not hesitate to propose any ideas at the [issue tracker on GitHub](https://github.com/CPJKU/madmom/issues). Think about posting them on [our mailing list](https://groups.google.com/d/forum/madmom-users) first, so we can discuss it and/or guide you through the implementation. Alternatively, you can look for anything tagged with “feature request” or “enhancement” on the [issue tracker on GitHub](https://github.com/CPJKU/madmom/issues). #### Write documentation[¶](#write-documentation) Whenever you find something not explained well, misleading or just wrong, please update it! The *Edit on GitHub* link on the top right of every documentation page and the *[source]* link for every documented entity in the API reference will help you to quickly locate the origin of any text. ### How to contribute[¶](#how-to-contribute) #### Edit on GitHub[¶](#edit-on-github) As a very easy way of just fixing issues in the documentation, use the *Edit on GitHub* link on the top right of a documentation page or the *[source]* link of an entity in the API reference to open the corresponding source file in GitHub, then click the *Edit this file* link to edit the file in your browser and send us a Pull Request. For any more substantial changes, please follow the steps below. #### Fork the project[¶](#fork-the-project) First, fork the project on [GitHub](https://github.com/CPJKU/madmom). Then, follow the [general installation instructions](index.html#document-installation) and, more specifically, the [installation from source](index.html#install-from-source). Please note that you should clone from your fork instead. #### Documentation[¶](#documentation) The documentation is generated with [Sphinx](http://sphinx-doc.org/latest/index.html). To build it locally, run the following commands: ``` cd docs make html ``` Afterwards, open `docs/_build/html/index.html` to view the documentation as it would appear on [readthedocs](http://madmom.readthedocs.org/). If you changed a lot and seem to get misleading error messages or warnings, run `make clean html` to force Sphinx to recreate all files from scratch. When writing docstrings, follow existing documentation as much as possible to ensure consistency throughout the library. For additional information on the syntax and conventions used, please refer to the following documents: * [reStructuredText Primer](http://sphinx-doc.org/rest.html) * [Sphinx reST markup constructs](http://sphinx-doc.org/markup/index.html) * [A Guide to NumPy/SciPy Documentation](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt) Citation[¶](#citation) --- If you use madmom in your work, please consider citing it: ``` @inproceedings{madmom, Title = {{madmom: a new Python Audio and Music Signal Processing Library}}, Author = {B{\"o}ck, <NAME>, <NAME> Schl{\"u}ter, <NAME>, <NAME> Widmer, Gerhard}, Booktitle = {Proceedings of the 24th ACM International Conference on Multimedia}, Month = {10}, Year = {2016}, Pages = {1174--1178}, Address = {Amsterdam, The Netherlands}, Doi = {10.1145/2964284.2973795} } ``` madmom.audio[¶](#madmom-audio) --- ### Submodules[¶](#submodules) #### madmom.audio.signal[¶](#madmom-audio-signal) #### madmom.audio.filters[¶](#madmom-audio-filters) #### madmom.audio.comb_filters[¶](#madmom-audio-comb-filters) #### madmom.audio.stft[¶](#madmom-audio-stft) #### madmom.audio.spectrogram[¶](#madmom-audio-spectrogram) #### madmom.audio.cepstrogram[¶](#madmom-audio-cepstrogram) #### madmom.audio.chroma[¶](#madmom-audio-chroma) #### madmom.audio.hpss[¶](#madmom-audio-hpss) madmom.features[¶](#madmom-features) --- ### Submodules[¶](#submodules) #### madmom.features.beats[¶](#madmom-features-beats) #### madmom.features.beats_crf[¶](#madmom-features-beats-crf) #### madmom.features.beats_hmm[¶](#madmom-features-beats-hmm) #### madmom.features.chords[¶](#madmom-features-chords) #### madmom.features.downbeats[¶](#madmom-features-downbeats) #### madmom.features.key[¶](#madmom-features-key) #### madmom.features.notes[¶](#madmom-features-notes) #### madmom.features.notes_hmm[¶](#madmom-features-notes-hmm) #### madmom.features.onsets[¶](#madmom-features-onsets) #### madmom.features.tempo[¶](#madmom-features-tempo) madmom.io[¶](#madmom-io) --- ### Submodules[¶](#submodules) #### madmom.io.audio[¶](#madmom-io-audio) #### madmom.io.midi[¶](#madmom-io-midi) madmom.ml[¶](#madmom-ml) --- ### Submodules[¶](#submodules) #### madmom.ml.crf[¶](#madmom-ml-crf) #### madmom.ml.gmm[¶](#madmom-ml-gmm) #### madmom.ml.hmm[¶](#madmom-ml-hmm) #### madmom.ml.nn[¶](#madmom-ml-nn) ##### madmom.ml.nn.layers[¶](#madmom-ml-nn-layers) ##### madmom.ml.nn.activations[¶](#madmom-ml-nn-activations) madmom.utils[¶](#madmom-utils) --- ### Submodules[¶](#submodules) #### madmom.utils.midi[¶](#madmom-utils-midi) #### madmom.utils.stats[¶](#madmom-utils-stats) madmom.processors[¶](#madmom-processors) --- madmom.evaluation[¶](#madmom-evaluation) --- ### Submodules[¶](#submodules) #### madmom.evaluation.alignment[¶](#madmom-evaluation-alignment) #### madmom.evaluation.beats[¶](#madmom-evaluation-beats) #### madmom.evaluation.chords[¶](#madmom-evaluation-chords) #### madmom.evaluation.key[¶](#madmom-evaluation-key) #### madmom.evaluation.notes[¶](#madmom-evaluation-notes) #### madmom.evaluation.onsets[¶](#madmom-evaluation-onsets) #### madmom.evaluation.tempo[¶](#madmom-evaluation-tempo) Indices and tables[¶](#indices-and-tables) --- * [Index](genindex.html) * [Module Index](py-modindex.html) * [Search Page](search.html) Acknowledgements[¶](#acknowledgements) --- Supported by the European Commission through the [GiantSteps project](http://www.giantsteps-project.eu) (FP7 grant agreement no. 610591) and the [Phenicx project](http://phenicx.upf.edu) (FP7 grant agreement no. 601166) as well as the [Austrian Science Fund (FWF)](https://www.fwf.ac.at) project Z159.
GITHUB_edsomjr_TEP.zip_unzipped_PT-2.pdf
free_programming_book
Unknown
Ponteiros Funcoes e Arquivos Prof. <NAME> - UnB/FGA 2018 Sumario 1. Ponteiros e funcoes 2. Ponteiros e arquivos 1 Ponteiros e funcoes Passagem de parametros Os parametros das funcoes e metodos podem ser passados de duas maneiras: por valor ou por referencia Na passagem por valor, os valores das variaveis passadas para a funcao ou metodo sao copiados para os parametros formais Na passagem por referencia, as funcoes recebem em seus parametros referencias para as variaveis passadas como parametros A passagem por copia tem maior custo de execucao do que a passagem por referencia, mas garante que as variaveis passadas como parametros nao serao modificadas pela funcao 2 Passagem de parametros em C/C++ Em C, a unica forma de passagem de parametros e por valor C++ suporta ambos metodos de passagem Para se utilizar a passagem por referencia em C, deve-se declarar o parametro como um ponteiro para o tipo de dado desejado Efetivamente, a passagem por referenciado C e uma passagem por copia, onde o ponteiro e copiado e o acesso a variavel e feita atraves do ponteiro Embora o mesmo seja verdadeiro para C++, a linguagem suporta passagem por referencia nativamente O mecanismo de referencia de C++ simplifica a notacao, mas deixa apenas implcito que os valores podem ser modificados pela funcao 3 Exemplo de passagem de parametros em C 1 2 #include <stdio.h> #include <time.h> 3 typedef struct _Registro { char nome[128]; 6 char sexo; 7 float peso; 8 int idade; 9 } Registro; 4 5 10 11 12 void por_valor(Registro registro) {} void por_referencia(Registro *registro) {} 13 14 static const unsigned long quantidade_chamadas = 1e8; 15 int main() { 18 Registro registro; 19 time_t inicio, fim; 20 unsigned long i; 16 17 21 4 Exemplo de passagem de parametros em C inicio = clock(); 22 23 for (i = 0; i < quantidade_chamadas; i++) por_valor(registro); 24 25 26 fim = clock(); 27 28 printf("Valor: %.8f s\n", 1.0*(fim - inicio)/CLOCKS_PER_SEC); 29 30 inicio = clock(); 31 32 for (i = 0; i < quantidade_chamadas; i++) por_referencia(&registro); 33 34 35 fim = clock(); 36 37 printf("Referencia: %.8f s\n", 1.0*(fim - inicio)/CLOCKS_PER_SEC); 38 39 return 0; 40 41 } 5 Exemplo de passagem de parametros em C++ 1 #include <iostream> 2 3 using namespace std; 4 void swap_por_valor(int x, int y) { int temp = x; 7 x = y; 8 y = temp; 9 } 5 6 10 void swap_com_ponteiros(int *x, int *y) { int temp = *x; 13 *x = *y; 14 *y = temp; 15 } 11 12 16 void swap_por_referencia(int& x, int& y) { int temp = x; 19 x = y; 20 y = temp; 21 } 17 18 6 Exemplo de passagem de parametros em C++ int main() { 25 int x = 1, y = 2; 23 24 26 cout << "Valores iniciais: x = " << x << ", y = " << y << endl; 27 28 swap_por_valor(x, y); cout << "swap_por_valor(): x = " << x << ", y = " << y << endl; 29 30 31 swap_por_referencia(x,y); cout << "swap_por_referencia(): x = " << x << ", y = " << y << endl; 32 33 34 swap_com_ponteiros(&x, &y); cout << "swap_com_ponteiros(): x = " << x << ", y = " << y << endl; 35 36 37 return 0; 38 39 } 7 Ponteiros para funcoes Sintaxe para declaracao de ponteiros para funcoes tipo_retorno (*nome_ponteiro)([parametros]); O ponto de entrada de uma funcao ocupa uma posicao na memoria: logo podemos declarar ponteiros para funcoes O endereco de uma funcao pode ser obtido atraves do nome da funcao, como no caso de vetores O ponteiro para funcao pode ser usado para fazer uma chamada a funcao, com a mesma sintaxe de chamadas comuns. Exemplo: void * (*ptr)(size_t, size_t); ptr = calloc; ... int *p = (int *) ptr(2, 8); Ponteiros para funcoes permitem a construcao de programas dinamicos e podem aumentar a organizacao do codigo 8 Exemplo de uso de ponteiros de funcoes 1 2 #ifndef PLUGIN_H #define PLUGIN_H 3 typedef struct _Plugin { void *handle; 6 const char * (*symbol) (); 7 int (*operation) (int, int); 8 } Plugin; 4 5 9 10 11 extern Plugin * load(const char *path); extern void release(Plugin *plugin); 12 13 #endif 9 Exemplo de uso de ponteiros de funcoes #include <stdlib.h> #include <stdio.h> 3 #include <dlfcn.h> 4 #include "plugin.h" 1 2 5 Plugin * load(const char *path) { 8 void *handle = NULL; 9 Plugin *plugin = NULL; 10 const char * (*symbol)() = NULL; 11 int (*operation) (int, int) = NULL; 6 7 12 13 14 if (!path) return NULL; 15 16 handle = dlopen(path, RTLD_LAZY | RTLD_GLOBAL); 17 18 19 20 21 if (!handle) { fprintf(stderr, "Load plugin error: %s\n", dlerror()); return NULL; } 10 Exemplo de uso de ponteiros de funcoes operation = dlsym(handle, "operation"); symbol = dlsym(handle, "symbol"); 23 24 25 if (!operation || !symbol) { fprintf(stderr, "Load plugin error: %s\n", dlerror()); dlclose(handle); return NULL; } 26 27 28 29 30 31 plugin = (Plugin *) malloc(sizeof(Plugin)); 32 33 if (!plugin) { dlclose(handle); return NULL; } 34 35 36 37 38 plugin->handle = handle; plugin->symbol = symbol; plugin->operation = operation; return plugin; 39 40 41 42 43 } 11 Exemplo de uso de ponteiros de funcoes void release(Plugin *plugin) { 47 if (!plugin) 48 return; 45 46 49 if (plugin->handle) dlclose(plugin->handle); 50 51 52 free(plugin); 53 54 } 12 Exemplo de uso de ponteiros de funcoes /* soma.c * 3 * Compile com a linha abaixo: 4 * 5 * $ gcc -o soma.so -shared soma.c -fPIC 6 */ 7 #include <stdlib.h> 8 #include "plugin.h" 1 2 9 const char * symbol() { 12 return "+"; 13 } 10 11 14 int operation(int a, int b) { 17 return a + b; 18 } 15 16 13 Exemplo de uso de ponteiros de funcoes /* subtracao.c * 3 * Compile com a linha abaixo: 4 * 5 * $ gcc -o subtracao.so -shared subtracao.c -fPIC 6 */ 7 #include <stdlib.h> 8 #include "plugin.h" 1 2 9 const char * symbol() { 12 return "-"; 13 } 10 11 14 int operation(int a, int b) { 17 return a - b; 18 } 15 16 14 Exemplo de uso de ponteiros de funcoes /* calculadora.c * 3 * Compile com a linha abaixo: 4 * 5 * $ gcc -o calculadora calculadora.c plugin.c -I. -ldl 6 * 7 * Os plugins devem estar no diretorio 'plugins'. 8 */ 9 #include <stdio.h> 10 #include <stdlib.h> 11 #include <string.h> 12 #include <sys/types.h> 13 #include <dirent.h> 14 #include "plugin.h" 1 2 15 Plugin ** load_plugins(const char *directory, int *qtd) { DIR *dir = NULL; 18 Plugin **plugins; 19 struct dirent *entry; 20 int size = 0; 21 char path[4096]; 16 17 15 Exemplo de uso de ponteiros de funcoes 23 dir = opendir(directory); 24 25 26 if (!dir) return NULL; 27 28 29 while (entry = readdir(dir)) size++; 30 31 closedir(dir); 32 33 plugins = (Plugin **) calloc(size, sizeof(Plugin *)); 34 35 36 37 38 if (!plugins) { fprintf(stderr, "Sem memoria\n"); return NULL; } 39 40 41 *qtd = 0; dir = opendir(directory); 42 43 if (!dir) return plugins; 16 Exemplo de uso de ponteiros de funcoes while (entry = readdir(dir)) { if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) continue; 45 46 47 48 sprintf(path, "%s/%s", directory, entry->d_name); plugins[*qtd] = load(path); 49 50 51 if (plugins[*qtd]) { (*qtd)++; printf("Plugin %s loaded\n", path); } 52 53 54 55 } 56 57 closedir(dir); 58 59 return plugins; 60 61 } 62 17 Exemplo de uso de ponteiros de funcoes int main() { Plugin **plugins = NULL; 65 char symbol[128], line[4096]; 66 int x, y, qtd = 0, i; 63 64 67 68 plugins = load_plugins("plugins", &qtd); 69 70 71 72 73 if (!plugins) { fprintf(stderr, "Can't load plugins\n"); return -1; } 74 75 76 77 while (1) { printf("Insira a expressao: "); fgets(line, 4096, stdin); 78 79 80 if (!strcmp(line, "quit\n")) break; 81 82 83 sscanf(line, "%d %s %d", &x, symbol, &y); 18 Exemplo de uso de ponteiros de funcoes for (i = 0; i < qtd; i++) { if (!strcmp(symbol, plugins[i]->symbol())) { printf("%d %s %d = %d\n", x, symbol, y, plugins[i]->operation(x, y)); break; } } 84 85 86 87 88 89 90 91 if (i == qtd) printf("Operacao nao suportada\n"); 92 93 } 94 95 for (i = 0; i < qtd; i++) release(plugins[i]); 96 97 98 free(plugins); 99 100 return 0; 101 102 } 19 Ponteiros e arquivos Leitura e escrita em arquivos em C Em C, a manipulacao de arquivos e feita atraves da estrutura FILE e as funcoes associadas a ela, que fazem parte da biblioteca stdio.h A abertura de arquivos em C e feita atraves da funcao fopen(), cuja assinatura e FILE *fopen(const char *path, const char *mode); Os parametros da funcao fopen() sao o caminho para o arquivo (path) e o modo de abertura: r para leitura, w para escrita e a para anexar O retorno e um ponteiro para a estrutura FILE, que deve ser passada para as diversas funcoes que realizam a leitura e a escrita de dados em arquivo, alem das funcoes de posicionamento do cursor 20 Leitura e escrita em arquivos em C Entre as funcoes de escrita, as mais comuns sao: fprintf(), fputc(), fwrite() Entre as funcoes de leitura, as mais comuns sao: fscanf(), fgetc(), fread() As funcoes para manipulacao do cursor sao: fseek(), ftell(), rewind() Ao finalizar o uso de um arquivo, a estrutura FILE deve ser desalocada atraves da chamada da funcao fclose() Em C++, a manipulacao de arquivos e feita pelas classes da biblioteca fstream Uma vez inicializados os fluxos de entrada e sada da fstream, a leitura e a escrita sao feitas da mesma forma que sao feitas com as classes cin e cout 21 Exemplo de manipulacao de arquivos em C 1 2 #ifndef CRIPTO_H #define CRIPTO_H 3 4 typedef char byte; 5 6 7 extern byte cipher(byte message, byte key); extern byte decipher(byte cipher, byte key); 8 9 #endif 22 Exemplo de manipulacao de arquivos em C 1 #include "cripto.h" 2 byte cipher(byte message, byte key) 5 { 6 return message + key; 7 } 3 4 8 byte decipher(byte cipher, byte key) 11 { 12 return cipher - key; 13 } 9 10 23 Exemplo de manipulacao de arquivos em C /* * Compile com a linha abaixo: 3 * 4 * $ gcc cripto.c main.c -o cipherfile 5 * $ gcc cripto.c main.c -o decipherfile 6 * 7 */ 8 #include <stdio.h> 9 #include <stdlib.h> 10 #include <string.h> 11 #include "cripto.h" 1 2 12 int main(int argc, char *argv[]) { FILE *in, *out; 15 byte (*op)(byte, byte) = NULL, key; 16 int c; 13 14 17 18 19 20 21 if (argc < 4) { fprintf(stderr, "Uso: %s <entrada> <saida> <chave>\n", argv[0]); return -1; } 24 Exemplo de manipulacao de arquivos em C 23 in = fopen(argv[1], "r"); 24 25 26 27 28 if (!in) { fprintf(stderr, "Erro ao abrir %s para leitura\n", argv[1]); return -2; } 29 30 out = fopen(argv[2], "w"); 31 32 33 34 35 36 37 if (!out) { fprintf(stderr, "Erro ao abrir %s para escrita\n", argv[2]); fclose(in); return -3; } 38 39 40 41 42 if (!strcmp(argv[0], "./cipherfile")) op = cipher; else if (!strcmp(argv[0], "./decipherfile")) op = decipher; 25 Exemplo de manipulacao de arquivos em C else { fprintf(stderr, "Operacao desconhecida\n"); fclose(in); fclose(out); 43 44 45 46 47 return -4; 48 } 49 50 key = (byte) atoi(argv[3]); 51 52 while ((c = fgetc(in)) != EOF) fputc(op((byte) c, key), out); 53 54 55 fclose(in); fclose(out); 56 57 58 return 0; 59 60 } 26 Referencias 1. KERNIGHAN, Bryan; RITCHIE, Dennis. The C Programming Language, 1978. 2. SCHILDT, Herbert. C Completo e Total, 1997. 3. STROUSTROUP, Bjarne. The C++ Programming Language, 2013. 4. C Man Pages1 . 5. C++ Reference2 . 1 Comando man no Linux. 2 https://en.cppreference.com/w/ 27
tailwindcss
devdocs
HTML
Get started with Tailwind CSS ============================= Tailwind CSS works by scanning all of your HTML files, JavaScript components, and any other templates for class names, generating the corresponding styles and then writing them to a static CSS file. It's fast, flexible, and reliable — with zero-runtime. Installation ------------ * [Tailwind CLI](https://tailwindcss.com/docs/installation) --------------------------------------------------------- * [Using PostCSS](/docs/installation) ----------------------------------- * [Framework Guides](/docs/installation) -------------------------------------- * [Play CDN](/docs/installation) ------------------------------ ### Installing Tailwind CLI The simplest and fastest way to get up and running with Tailwind CSS from scratch is with the Tailwind CLI tool. The CLI is also available as a [standalone executable](https://tailwindcss.com/blog/standalone-cli) if you want to use it without installing Node.js. 1. #### Install Tailwind CSS Install `tailwindcss` via npm, and create your `tailwind.config.js` file. Terminal ``` npm install -D tailwindcssnpx tailwindcss init ``` 2. #### Configure your template paths Add the paths to all of your template files in your `tailwind.config.js` file. tailwind.config.js ``` /** @type {import('tailwindcss').Config} */ module.exports = { content: ["./src/**/*.{html,js}"], theme: { extend: {}, }, plugins: [], } ``` 3. #### Add the Tailwind directives to your CSS Add the `@tailwind` directives for each of Tailwind’s layers to your main CSS file. src/input.css ``` @tailwind base; @tailwind components; @tailwind utilities; ``` 4. #### Start the Tailwind CLI build process Run the CLI tool to scan your template files for classes and build your CSS. Terminal ``` npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch ``` 5. #### Start using Tailwind in your HTML Add your compiled CSS file to the `<head>` and start using Tailwind’s utility classes to style your content. src/index.html ``` <!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="/dist/output.css" rel="stylesheet"> </head> <body> <h1 class="text-3xl font-bold underline"> Hello world! </h1> </body> </html``` What to read next ----------------- Get familiar with some of the core concepts that make Tailwind CSS different from writing traditional CSS. * ### [Utility-First Fundamentals](utility-first) Using a utility-first workflow to build complex components from a constrained set of primitive utilities. * ### [Responsive Design](responsive-design) Build fully responsive user interfaces that adapt to any screen size using responsive modifiers. * ### [Hover, Focus & Other States](hover-focus-and-other-states) Style elements in interactive states like hover, focus, and more using conditional modifiers. * ### [Dark Mode](dark-mode) Optimize your site for dark mode directly in your HTML using the dark mode modifier. * ### [Reusing Styles](reusing-styles) Manage duplication and keep your projects maintainable by creating reusable abstractions. * ### [Customizing the Framework](adding-custom-styles) Customize the framework to match your brand and extend it with your own custom styles. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docsUtility-First Fundamentals ========================== Building complex components from a constrained set of primitive utilities. Overview -------- Traditionally, whenever you need to style something on the web, you write CSS. Using a traditional approach where custom designs require custom CSS ``` <div class="chat-notification"> <div class="chat-notification-logo-wrapper"> <img class="chat-notification-logo" src="/img/logo.svg" alt="ChitChat Logo"> </div> <div class="chat-notification-content"> <h4 class="chat-notification-title">ChitChat</h4> <p class="chat-notification-message">You have a new message!</p> </div> </div<style> .chat-notification { display: flex; max-width: 24rem; margin: 0 auto; padding: 1.5rem; border-radius: 0.5rem; background-color: #fff; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); } .chat-notification-logo-wrapper { flex-shrink: 0; } .chat-notification-logo { height: 3rem; width: 3rem; } .chat-notification-content { margin-left: 1.5rem; padding-top: 0.25rem; } .chat-notification-title { color: #1a202c; font-size: 1.25rem; line-height: 1.25; } .chat-notification-message { color: #718096; font-size: 1rem; line-height: 1.5; } </style> ``` With Tailwind, you style elements by applying pre-existing classes directly in your HTML. Using utility classes to build custom designs without writing CSS ``` <div class="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-lg flex items-center space-x-4"> <div class="shrink-0"> <img class="h-12 w-12" src="/img/logo.svg" alt="ChitChat Logo"> </div> <div> <div class="text-xl font-medium text-black">ChitChat</div> <p class="text-slate-500">You have a new message!</p> </div> </div> ``` In the example above, we’ve used: * Tailwind’s [flexbox](display#flex) and <padding> utilities (`flex`, `shrink-0`, and `p-6`) to control the overall card layout * The <max-width> and <margin> utilities (`max-w-sm` and `mx-auto`) to constrain the card width and center it horizontally * The [background color](background-color), [border radius](border-radius), and <box-shadow> utilities (`bg-white`, `rounded-xl`, and `shadow-lg`) to style the card’s appearance * The <width> and <height> utilities (`w-12` and `h-12`) to size the logo image * The [space-between](space) utilities (`space-x-4`) to handle the spacing between the logo and the text * The [font size](font-size), [text color](text-color), and <font-weight> utilities (`text-xl`, `text-black`, `font-medium`, etc.) to style the card text This approach allows us to implement a completely custom component design without writing a single line of custom CSS. Now I know what you’re thinking, *“this is an atrocity, what a horrible mess!”* and you’re right, it’s kind of ugly. In fact it’s just about impossible to think this is a good idea the first time you see it — **you have to actually try it**. But once you’ve actually built something this way, you’ll quickly notice some really important benefits: * **You aren’t wasting energy inventing class names**. No more adding silly class names like `sidebar-inner-wrapper` just to be able to style something, and no more agonizing over the perfect abstract name for something that’s really just a flex container. * **Your CSS stops growing**. Using a traditional approach, your CSS files get bigger every time you add a new feature. With utilities, everything is reusable so you rarely need to write new CSS. * **Making changes feels safer**. CSS is global and you never know what you’re breaking when you make a change. Classes in your HTML are local, so you can change them without worrying about something else breaking. When you realize how productive you can be working exclusively in HTML with predefined utility classes, working any other way will feel like torture. Why not just use inline styles? ------------------------------- A common reaction to this approach is wondering, “isn’t this just inline styles?” and in some ways it is — you’re applying styles directly to elements instead of assigning them a class name and then styling that class. But using utility classes has a few important advantages over inline styles: * **Designing with constraints**. Using inline styles, every value is a magic number. With utilities, you’re choosing styles from a predefined [design system](theme), which makes it much easier to build visually consistent UIs. * **Responsive design**. You can’t use media queries in inline styles, but you can use Tailwind’s [responsive utilities](responsive-design) to build fully responsive interfaces easily. * **Hover, focus, and other states**. Inline styles can’t target states like hover or focus, but Tailwind’s [state variants](hover-focus-and-other-states) make it easy to style those states with utility classes. This component is fully responsive and includes a button with hover and focus styles, and is built entirely with utility classes: ``` <div class="py-8 px-8 max-w-sm mx-auto bg-white rounded-xl shadow-lg space-y-2 sm:py-4 sm:flex sm:items-center sm:space-y-0 sm:space-x-6"> <img class="block mx-auto h-24 rounded-full sm:mx-0 sm:shrink-0" src="/img/erin-lindford.jpg" alt="Woman's Face" /> <div class="text-center space-y-2 sm:text-left"> <div class="space-y-0.5"> <p class="text-lg text-black font-semibold"> <NAME> </p> <p class="text-slate-500 font-medium"> Product Engineer </p> </div> <button class="px-4 py-1 text-sm text-purple-600 font-semibold rounded-full border border-purple-200 hover:text-white hover:bg-purple-600 hover:border-transparent focus:outline-none focus:ring-2 focus:ring-purple-600 focus:ring-offset-2">Message</button> </div> </div> ``` Maintainability concerns ------------------------ The biggest maintainability concern when using a utility-first approach is managing commonly repeated utility combinations. This is easily solved by [extracting components and partials](reusing-styles#extracting-components-and-partials), and using [editor and language features](reusing-styles#using-editor-and-language-features) like multi-cursor editing and simple loops. ``` <!-- PrimaryButton.vue --> <template> <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"> <slot/> </button> </template> ``` Aside from that, maintaining a utility-first CSS project turns out to be a lot easier than maintaining a large CSS codebase, simply because HTML is so much easier to maintain than CSS. Large companies like GitHub, Netflix, Heroku, Kickstarter, Twitch, Segment, and more are using this approach with great success. If you’d like to hear about others’ experiences with this approach, check out the following resources: * [By The Numbers: A Year and a Half with Atomic CSS](https://medium.com/@johnpolacek/by-the-numbers-a-year-and-half-with-atomic-css-39d75b1263b4) by <NAME> * [No, Utility Classes Aren’t the Same As Inline Styles](https://frontstuff.io/no-utility-classes-arent-the-same-as-inline-styles) by Sar<NAME> of Algolia * [Diana Mounter on using utility classes at GitHub](http://www.fullstackradio.com/75), a podcast interview For even more, check out [The Case for Atomic/Utility-First CSS](https://johnpolacek.github.io/the-case-for-atomic-css/), curated by [<NAME>](https://twitter.com/johnpolacek). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/utility-firstResponsive Design ================= Using responsive utility variants to build adaptive user interfaces. Overview -------- Every utility class in Tailwind can be applied conditionally at different breakpoints, which makes it a piece of cake to build complex responsive interfaces without ever leaving your HTML. There are five breakpoints by default, inspired by common device resolutions: | Breakpoint prefix | Minimum width | CSS | | --- | --- | --- | | `sm` | 640px | `@media (min-width: 640px) { ... }` | | `md` | 768px | `@media (min-width: 768px) { ... }` | | `lg` | 1024px | `@media (min-width: 1024px) { ... }` | | `xl` | 1280px | `@media (min-width: 1280px) { ... }` | | `2xl` | 1536px | `@media (min-width: 1536px) { ... }` | To add a utility but only have it take effect at a certain breakpoint, all you need to do is prefix the utility with the breakpoint name, followed by the `:` character: ``` <!-- Width of 16 by default, 32 on medium screens, and 48 on large screens --> <img class="w-16 md:w-32 lg:w-48" src="..."> ``` This works for **every utility class in the framework**, which means you can change literally anything at a given breakpoint — even things like letter spacing or cursor styles. Here’s a simple example of a marketing page component that uses a stacked layout on small screens, and a side-by-side layout on larger screens *(resize your browser to see it in action)*: ``` <div class="max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl"> <div class="md:flex"> <div class="md:shrink-0"> <img class="h-48 w-full object-cover md:h-full md:w-48" src="/img/building.jpg" alt="Modern building architecture"> </div> <div class="p-8"> <div class="uppercase tracking-wide text-sm text-indigo-500 font-semibold">Company retreats</div> <a href="#" class="block mt-1 text-lg leading-tight font-medium text-black hover:underline">Incredible accommodation for your team</a> <p class="mt-2 text-slate-500">Looking to take your team away on a retreat to enjoy awesome food and take in some sunshine? We have a list of places to do just that.</p> </div> </div> </div> ``` Here’s how the example above works: * By default, the outer `div` is `display: block`, but by adding the `md:flex` utility, it becomes `display: flex` on medium screens and larger. * When the parent is a flex container, we want to make sure the image never shrinks, so we’ve added `md:shrink-0` to prevent shrinking on medium screens and larger. Technically we could have just used `shrink-0` since it would do nothing on smaller screens, but since it only matters on `md` screens, it’s a good idea to make that clear in the class name. * On small screens the image is automatically full width by default. On medium screens and up, we’ve constrained the width to a fixed size and ensured the image is full height using `md:h-full md:w-48`. We’ve only used one breakpoint in this example, but you could easily customize this component at other sizes using the `sm`, `lg`, `xl`, or `2xl` responsive prefixes as well. Working mobile-first -------------------- By default, Tailwind uses a mobile-first breakpoint system, similar to what you might be used to in other frameworks like Bootstrap. What this means is that unprefixed utilities (like `uppercase`) take effect on all screen sizes, while prefixed utilities (like `md:uppercase`) only take effect at the specified breakpoint *and above*. ### Targeting mobile screens Where this approach surprises people most often is that to style something for mobile, you need to use the unprefixed version of a utility, not the `sm:` prefixed version. Don’t think of `sm:` as meaning “on small screens”, think of it as “at the small *breakpoint*“. Don’t use `sm:` to target mobile devices ``` <!-- This will only center text on screens 640px and wider, not on small screens --> <div class="sm:text-center"></div> ``` Use unprefixed utilities to target mobile, and override them at larger breakpoints ``` <!-- This will center text on mobile, and left align it on screens 640px and wider --> <div class="text-center sm:text-left"></div> ``` For this reason, it’s often a good idea to implement the mobile layout for a design first, then layer on any changes that make sense for `sm` screens, followed by `md` screens, etc. ### Targeting a breakpoint range By default, styles applied by rules like `md:flex` will apply at that breakpoint and stay applied at larger breakpoints. If you’d like to apply a utility *only* when a specific breakpoint range is active, stack a responsive modifier like `md` with a `max-*` modifier to limit that style to a specific range: ``` <div class="md:max-xl:flex"> <!-- ... --> </div> ``` Tailwind generates a corresponding `max-*` modifier for each breakpoint, so out of the box the following modifiers are available: | Modifier | Media query | | --- | --- | | `max-sm` | `@media not all and (min-width: 640px) { ... }` | | `max-md` | `@media not all and (min-width: 768px) { ... }` | | `max-lg` | `@media not all and (min-width: 1024px) { ... }` | | `max-xl` | `@media not all and (min-width: 1280px) { ... }` | | `max-2xl` | `@media not all and (min-width: 1536px) { ... }` | ### Targeting a single breakpoint To target a single breakpoint, target the range for that breakpoint by stacking a responsive modifier like `md` with the `max-*` modifier for the next breakpoint: ``` <div class="md:max-lg:flex"> <!-- ... --> </div> ``` Read about [targeting breakpoint ranges](responsive-design#targeting-a-breakpoint-range) to learn more. Using custom breakpoints ------------------------ ### Customizing your theme You can completely customize your breakpoints in your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { theme: { screens: { 'tablet': '640px', // => @media (min-width: 640px) { ... } 'laptop': '1024px', // => @media (min-width: 1024px) { ... } 'desktop': '1280px', // => @media (min-width: 1280px) { ... } }, } } ``` Learn more in the [customizing breakpoints documentation](/docs/screens). ### Arbitrary values If you need to use a one-off breakpoint that doesn’t make sense to include in your theme, use the `min` or `max` modifiers to generate a custom breakpoint on the fly using any arbitrary value. ``` <div class="min-[320px]:text-center max-[600px]:bg-sky-300"> <!-- ... --> </div> ``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/responsive-designFunctions & Directives ====================== A reference for the custom functions and directives Tailwind exposes to your CSS. Directives ---------- Directives are custom Tailwind-specific [at-rules](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule) you can use in your CSS that offer special functionality for Tailwind CSS projects. ### @tailwind Use the `@tailwind` directive to insert Tailwind’s `base`, `components`, `utilities` and `variants` styles into your CSS. ``` /** * This injects Tailwind's base styles and any base styles registered by * plugins. */ @tailwind base; /** * This injects Tailwind's component classes and any component classes * registered by plugins. */ @tailwind components; /** * This injects Tailwind's utility classes and any utility classes registered * by plugins. */ @tailwind utilities; /** * Use this directive to control where Tailwind injects the hover, focus, * responsive, dark mode, and other variants of each class. * * If omitted, Tailwind will append these classes to the very end of * your stylesheet by default. */ @tailwind variants; ``` ### @layer Use the `@layer` directive to tell Tailwind which “bucket” a set of custom styles belong to. Valid layers are `base`, `components`, and `utilities`. ``` @tailwind base; @tailwind components; @tailwind utilities; @layer base { h1 { @apply text-2xl; } h2 { @apply text-xl; } } @layer components { .btn-blue { @apply bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded; } } @layer utilities { .filter-none { filter: none; } .filter-grayscale { filter: grayscale(100%); } } ``` Tailwind will automatically move the CSS within any `@layer` directive to the same place as the corresponding `@tailwind` rule, so you don’t have to worry about authoring your CSS in a specific order to avoid specificity issues. Any custom CSS added to a layer will only be included in the final build if that CSS is actually used in your HTML, just like all of the classes built in to Tailwind by default. Wrapping any custom CSS with `@layer` also makes it possible to use modifiers with those rules, like `hover:` and `focus:` or responsive modifiers like `md:` and `lg:`. ### @apply Use `@apply` to inline any existing utility classes into your own custom CSS. This is useful when you need to write custom CSS (like to override the styles in a third-party library) but still want to work with your design tokens and use the same syntax you’re used to using in your HTML. ``` .select2-dropdown { @apply rounded-b-lg shadow-md; } .select2-search { @apply border border-gray-300 rounded; } .select2-results__group { @apply text-lg font-bold text-gray-900; } ``` Any rules inlined with `@apply` will have `!important` **removed** by default to avoid specificity issues: ``` /* Input */ .foo { color: blue !important; } .bar { @apply foo; } /* Output */ .foo { color: blue !important; } .bar { color: blue; } ``` If you’d like to `@apply` an existing class and make it `!important`, simply add `!important` to the end of the declaration: ``` /* Input */ .btn { @apply font-bold py-2 px-4 rounded !important; } /* Output */ .btn { font-weight: 700 !important; padding-top: .5rem !important; padding-bottom: .5rem !important; padding-right: 1rem !important; padding-left: 1rem !important; border-radius: .25rem !important; } ``` Note that if you’re using Sass/SCSS, you’ll need to use Sass’ interpolation feature to get this to work: ``` .btn { @apply font-bold py-2 px-4 rounded #{!important}; } ``` #### Using @apply with per-component CSS Component frameworks like Vue and Svelte support adding per-component styles within a `<style>` block that lives in each component file. If you try to `@apply` a custom class you’ve defined in your global CSS in one of these per-component `<style>` blocks, you’ll get an error about the class not existing: main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer components { .card { background-color: theme(colors.white); border-radius: theme(borderRadius.lg); padding: theme(spacing.6); box-shadow: theme(boxShadow.xl); } } ``` Card.svelte ``` <div> <slot></slot> </div<style> div { /* Won't work because this file and main.css are processed separately */ @apply card; } </style> ``` This is because under-the-hood, frameworks like Vue and Svelte are processing every single `<style>` block independently, and running your PostCSS plugin chain against each one in isolation. That means if you have 10 components that each have a `<style>` block, Tailwind is being run 10 separate times, and each run has zero knowledge about the other runs. Because of this, when you try to `@apply card` in `Card.svelte` it fails, because Tailwind has no idea that the `card` class exists since Svelte processed `Card.svelte` and `main.css` in total isolation from each other. The solution to this problem is to define any custom styles you want to `@apply` in your components using the [plugin system](plugins) instead: tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { // ... plugins: [ plugin(function ({ addComponents, theme }) { addComponents({ '.card': { backgroundColor: theme('colors.white'), borderRadius: theme('borderRadius.lg'), padding: theme('spacing.6'), boxShadow: theme('boxShadow.xl'), } }) }) ] } ``` This way any file processed by Tailwind that uses this config file will have access to those styles. Honestly though the best solution is to just not do weird stuff like this at all. Use Tailwind’s utilities directly in your markup the way they are intended to be used, and don’t abuse the `@apply` feature to do things like this and you will have a much better experience. ### @config Use the `@config` directive to specify which config file Tailwind should use when compiling that CSS file. This is useful for projects that need to use different configuration files for different CSS entry points. The path you provide to the `@config` directive is relative to that CSS file, and will take precedence over a path defined in your PostCSS configuration or in the Tailwind CLI. Note that if you’re using `postcss-import`, your `@import` statements need to come before `@config` for things to work correctly, as `postcss-import` is strict about following the CSS spec which requires `@import` statements to precede any other rules in the file. Don’t put `@config` before your `@import` statements admin.css ``` @config "./tailwind.admin.config.js"; @import "tailwindcss/base"; @import "./custom-base.css"; @import "tailwindcss/components"; @import "./custom-components.css"; @import "tailwindcss/utilities"; ``` Put your `@import` statements before the `@config` directive admin.css ``` @import "tailwindcss/base"; @import "./custom-base.css"; @import "tailwindcss/components"; @import "./custom-components.css"; @import "tailwindcss/utilities"; @config "./tailwind.admin.config.js"; ``` Functions --------- Tailwind adds a few custom functions you can use in your CSS to access Tailwind-specific values. These functions are evaluated at build-time, and are replaced by static values in your final CSS. ### theme() Use the `theme()` function to access your Tailwind config values using dot notation. ``` .content-area { height: calc(100vh - theme(spacing.12)); } ``` If you need to access a value that contains a dot (like the `2.5` value in the spacing scale), you can use square bracket notation: ``` .content-area { height: calc(100vh - theme(spacing[2.5])); } ``` Since Tailwind uses a [nested object syntax](customizing-colors#color-object-syntax) to define its default color palette, make sure to use dot notation to access the nested colors. Don’t use the dash syntax when accessing nested color values ``` .btn-blue { background-color: theme(colors.blue-500); } ``` Use dot notation to access nested color values ``` .btn-blue { background-color: theme(colors.blue.500); } ``` To adjust the opacity of a color retrieved with `theme`, use a slash followed by the opacity value you want to use: ``` .btn-blue { background-color: theme(colors.blue.500 / 75%); } ``` ### screen() The `screen` function allows you to create media queries that reference your breakpoints by name instead of duplicating their values in your own CSS. ``` @media screen(sm) { /* ... */ } ``` This will resolve to the underlying screen value at build-time, generating a regular media query that matches specified breakpoint: ``` @media (min-width: 640px) { /* ... */ } ``` © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/functions-and-directivesHandling Hover, Focus, and Other States ======================================= Using utilities to style elements on hover, focus, and more. Every utility class in Tailwind can be applied *conditionally* by adding a modifier to the beginning of the class name that describes the condition you want to target. For example, to apply the `bg-sky-700` class on hover, use the `hover:bg-sky-700` class: ``` <button class="bg-sky-500 hover:bg-sky-700 ..."> Save changes </button> ``` How does this compare to traditional CSS?When writing CSS the traditional way, a single class name would do different things based on the current state. Traditionally the same class name applies different styles on hover ``` .btn-primary { background-color: #0ea5e9; } .btn-primary:hover { background-color: #0369a1; } ``` In Tailwind, rather than adding the styles for a hover state to an existing class, you add another class to the element that *only* does something on hover. In Tailwind, separate classes are used for the default state and the hover state ``` .bg-sky-500 { background-color: #0ea5e9; } .hover\:bg-sky-700:hover { background-color: #0369a1; } ``` Notice how `hover:bg-sky-700` *only* defines styles for the `:hover` state? It does nothing by default, but as soon as you hover over an element with that class, the background color will change to `sky-700`. This is what we mean when we say a utility class can be applied *conditionally* — by using modifiers you can control exactly how your design behaves in different states, without ever leaving your HTML. Tailwind includes modifiers for just about everything you’ll ever need, including: * [Pseudo-classes](hover-focus-and-other-states#pseudo-classes), like `:hover`, `:focus`, `:first-child`, and `:required` * [Pseudo-elements](hover-focus-and-other-states#pseudo-elements), like `::before`, `::after`, `::placeholder`, and `::selection` * [Media and feature queries](hover-focus-and-other-states#media-and-feature-queries), like responsive breakpoints, dark mode, and `prefers-reduced-motion` * [Attribute selectors](hover-focus-and-other-states#attribute-selectors), like `[dir="rtl"]` and `[open]` These modifiers can even be [stacked](hover-focus-and-other-states#ordering-stacked-modifiers) to target more specific situations, for example changing the background color in dark mode, at the medium breakpoint, on hover: ``` <button class="dark:md:hover:bg-fuchsia-600 ..."> Save changes </button> ``` In this guide you’ll learn about every modifier available in the framework, how to use them with your own custom classes, and even how to create your own. Pseudo-classes -------------- ### Hover, focus, and active Style elements on hover, focus, and active using the `hover`, `focus`, and `active` modifiers: ``` <button class="bg-violet-500 hover:bg-violet-600 active:bg-violet-700 focus:outline-none focus:ring focus:ring-violet-300 ..."> Save changes </button> ``` Tailwind also includes modifiers for other interactive states like `:visited`, `:focus-within`, `:focus-visible`, and more. See the [pseudo-class reference](hover-focus-and-other-states#pseudo-class-reference) for a complete list of available pseudo-class modifiers. ### First, last, odd, and even Style an element when it is the first-child or last-child using the `first` and `last` modifiers: ``` <ul role="list" class="p-6 divide-y divide-slate-200"> {#each people as person} <!-- Remove top/bottom padding when first/last child --> <li class="flex py-4 first:pt-0 last:pb-0"> <img class="h-10 w-10 rounded-full" src="{person.imageUrl}" alt="" /> <div class="ml-3 overflow-hidden"> <p class="text-sm font-medium text-slate-900">{person.name}</p> <p class="text-sm text-slate-500 truncate">{person.email}</p> </div> </li> {/each} </ul> ``` You can also style an element when it’s an odd or even child using the `odd` and `even` modifiers: ``` <table> <!-- ... --> <tbody> {#each people as person} <!-- Use a white background for odd rows, and slate-50 for even rows --> <tr class="odd:bg-white even:bg-slate-50"> <td>{person.name}</td> <td>{person.title}</td> <td>{person.email}</td> </tr> {/each} </tbody> </table> ``` Tailwind also includes modifiers for other structural pseudo-classes like `:only-child`, `:first-of-type`, `:empty`, and more. See the [pseudo-class reference](hover-focus-and-other-states#pseudo-class-reference) for a complete list of available pseudo-class modifiers. ### Form states Style form elements in different states using modifiers like `required`, `invalid`, and `disabled`: ``` <form> <label class="block"> <span class="block text-sm font-medium text-slate-700">Username</span> <!-- Using form state modifiers, the classes can be identical for every input --> <input type="text" value="tbone" disabled class="mt-1 block w-full px-3 py-2 bg-white border border-slate-300 rounded-md text-sm shadow-sm placeholder-slate-400 focus:outline-none focus:border-sky-500 focus:ring-1 focus:ring-sky-500 disabled:bg-slate-50 disabled:text-slate-500 disabled:border-slate-200 disabled:shadow-none invalid:border-pink-500 invalid:text-pink-600 focus:invalid:border-pink-500 focus:invalid:ring-pink-500 "/> </label> <!-- ... --> </form> ``` Using modifiers for this sort of thing can reduce the amount of conditional logic in your templates, letting you use the same set of classes regardless of what state an input is in and letting the browser apply the right styles for you. Tailwind also includes modifiers for other form states like `:read-only`, `:indeterminate`, `:checked`, and more. See the [pseudo-class reference](hover-focus-and-other-states#disabled) for a complete list of available pseudo-class modifiers. ### Styling based on parent state (group-{modifier}) When you need to style an element based on the state of some *parent* element, mark the parent with the `group` class, and use `group-*` modifiers like `group-hover` to style the target element: ``` <a href="#" class="group block max-w-xs mx-auto rounded-lg p-6 bg-white ring-1 ring-slate-900/5 shadow-lg space-y-3 hover:bg-sky-500 hover:ring-sky-500"> <div class="flex items-center space-x-3"> <svg class="h-6 w-6 stroke-sky-500 group-hover:stroke-white" fill="none" viewBox="0 0 24 24"><!-- ... --></svg> <h3 class="text-slate-900 group-hover:text-white text-sm font-semibold">New project</h3> </div> <p class="text-slate-500 group-hover:text-white text-sm">Create a new project from a variety of starting templates.</p> </a> ``` This pattern works with every pseudo-class modifier, for example `group-focus`, `group-active`, or even `group-odd`. #### Differentiating nested groups When nesting groups, you can style something based on the state of a *specific* parent group by giving that parent a unique group name using a `group/{name}` class, and including that name in modifiers using classes like `group-hover/{name}`: ``` <ul role="list"> {#each people as person} <li class="group/item hover:bg-slate-100 ..."> <img src="{person.imageUrl}" alt="" /> <div> <a href="{person.url}">{person.name}</a> <p>{person.title}</p> </div> <a class="group/edit invisible hover:bg-slate-200 group-hover/item:visible ..." href="tel:{person.phone}"> <span class="group-hover/edit:text-gray-700 ...">Call</span> <svg class="group-hover/edit:translate-x-0.5 group-hover/edit:text-slate-500 ..."> <!-- ... --> </svg> </a> </li> {/each} </ul> ``` Groups can be named however you like and don’t need to be configured in any way — just name your groups directly in your markup and Tailwind will automatically generate the necessary CSS. #### Arbitrary groups You can create one-off `group-*` modifiers on the fly by providing your own selector as an [arbitrary value](adding-custom-styles#using-arbitrary-values) between square brackets: For more control, you can use the `&` character to mark where `.group` should end up in the final selector relative to the selector you are passing in: ### Styling based on sibling state (peer-{modifier}) When you need to style an element based on the state of a *sibling* element, mark the sibling with the `peer` class, and use `peer-*` modifiers like `peer-invalid` to style the target element: ``` <form> <label class="block"> <span class="block text-sm font-medium text-slate-700">Email</span> <input type="email" class="peer ..."/> <p class="mt-2 invisible peer-invalid:visible text-pink-600 text-sm"> Please provide a valid email address. </p> </label> </form> ``` This makes it possible to do all sorts of neat tricks, like [floating labels](https://www.youtube.com/watch?v=nJzKi6oIvBA) for example without any JS. This pattern works with every pseudo-class modifier, for example `peer-focus`, `peer-required`, and `peer-disabled`. It’s important to note that the `peer` marker can only be used on *previous* siblings because of how the [general sibling combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator) works in CSS. Won’t work, only previous siblings can be marked as peers ``` <label> <span class="peer-invalid:text-red-500 ...">Email</span> <input type="email" class="peer ..."/> </label> ``` #### Differentiating peers When using multiple peers, you can style something on the state of a *specific* peer by giving that peer a unique name using a `peer/{name}` class, and including that name in modifiers using classes like `peer-checked/{name}`: ``` <fieldset> <legend>Published status</legend <input id="draft" class="peer/draft" type="radio" name="status" checked /> <label for="draft" class="peer-checked/draft:text-sky-500">Draft</label <input id="published" class="peer/published" type="radio" name="status" /> <label for="published" class="peer-checked/published:text-sky-500">Published</label <div class="hidden peer-checked/draft:block">Drafts are only visible to administrators.</div> <div class="hidden peer-checked/published:block">Your post will be publicly visible on your site.</div> </fieldset> ``` Peers can be named however you like and don’t need to be configured in any way — just name your peers directly in your markup and Tailwind will automatically generate the necessary CSS. #### Arbitrary peers You can create one-off `peer-*` modifiers on the fly by providing your own selector as an [arbitrary value](adding-custom-styles#using-arbitrary-values) between square brackets: For more control, you can use the `&` character to mark where `.peer` should end up in the final selector relative to the selector you are passing in: Pseudo-elements --------------- ### Before and after Style the `::before` and `::after` pseudo-elements using the `before` and `after` modifiers: ``` <label class="block"> <span class="after:content-['*'] after:ml-0.5 after:text-red-500 block text-sm font-medium text-slate-700"> Email </span> <input type="email" name="email" class="mt-1 px-3 py-2 bg-white border shadow-sm border-slate-300 placeholder-slate-400 focus:outline-none focus:border-sky-500 focus:ring-sky-500 block w-full rounded-md sm:text-sm focus:ring-1" placeholder="<EMAIL>" /> </label> ``` When using these modifiers, Tailwind will automatically add `content: ''` by default so you don’t have to specify it unless you want a different value: ``` <blockquote class="text-2xl font-semibold italic text-center text-slate-900"> When you look <span class="before:block before:absolute before:-inset-1 before:-skew-y-3 before:bg-pink-500 relative inline-block"> <span class="relative text-white">annoyed</span> </span> all the time, people think that you're busy. </blockquote> ``` It’s worth noting that you don’t really need `::before` and `::after` pseudo-elements for most things in Tailwind projects — it’s usually simpler to just use a real HTML element. For example, here’s the same design from above but using a `<span>` instead of the `::before` pseudo-element, which is a little easier to read and is actually less code: ``` <blockquote class="text-2xl font-semibold italic text-center text-slate-900"> When you look <span class="relative"> <span class="block absolute -inset-1 -skew-y-3 bg-pink-500" aria-hidden="true"></span> <span class="relative text-white">annoyed</span> </span> all the time, people think that you're busy. </blockquote``` Save `before` and `after` for situations where it’s important that the content of the pseudo-element is not actually in the DOM and can’t be selected by the user. Note that if you’ve disabled our [preflight base styles](preflight), the content property will not be set to an empty string by default, and you will need to include `content-['']` any time you use the `before` and `after` modifiers. If you’ve disabled preflight make sure to set the content manually ``` <div class="before:content-[''] before:block ..."> <!-- ... --> </div> ``` ### Placeholder text Style the placeholder text of any input or textarea using the `placeholder` modifier: ``` <label class="relative block"> <span class="sr-only">Search</span> <span class="absolute inset-y-0 left-0 flex items-center pl-2"> <svg class="h-5 w-5 fill-slate-300" viewBox="0 0 20 20"><!-- ... --></svg> </span> <input class="placeholder:italic placeholder:text-slate-400 block bg-white w-full border border-slate-300 rounded-md py-2 pl-9 pr-3 shadow-sm focus:outline-none focus:border-sky-500 focus:ring-sky-500 focus:ring-1 sm:text-sm" placeholder="Search for anything..." type="text" name="search"/> </label> ``` ### File input buttons Style the button in file inputs using the `file` modifier: ``` <form class="flex items-center space-x-6"> <div class="shrink-0"> <img class="h-16 w-16 object-cover rounded-full" src="https://images.unsplash.com/photo-1580489944761-15a19d654956?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1361&q=80" alt="Current profile photo" /> </div> <label class="block"> <span class="sr-only">Choose profile photo</span> <input type="file" class="block w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-violet-50 file:text-violet-700 hover:file:bg-violet-100 "/> </label> </form> ``` Note that Tailwind’s [border reset](preflight#border-styles-are-reset-globally) is not applied to file input buttons. This means that to add a border to a file input button, you need to explicitly set the <border-style> using a class like `file:border-solid` alongside any <border-width> utility: ``` <input type="file" class="file:border file:border-solid ..." /> ``` ### List markers Style the counters or bullets in lists using the `marker` modifier: ``` <ul role="list" class="marker:text-sky-400 list-disc pl-5 space-y-3 text-slate-500"> <li>5 cups chopped Porcini mushrooms</li> <li>1/2 cup of olive oil</li> <li>3lb of celery</li> </ul><ul role="list" class="marker:text-sky-400 list-disc pl-5 space-y-3 text-slate-400"> <li>5 cups chopped Porcini mushrooms</li> <li>1/2 cup of olive oil</li> <li>3lb of celery</li> </ul> ``` We’ve designed the `marker` modifier to be inheritable, so although you can use it directly on an `<li>` element, you can also use it on a parent to avoid repeating yourself. ### Highlighted text Style the active text selection using the `selection` modifier: ``` <div class="selection:bg-fuchsia-300 selection:text-fuchsia-900"> <p> So I started to walk into the water. I won't lie to you boys, I was terrified. But I pressed on, and as I made my way past the breakers a strange calm came over me. I don't know if it was divine intervention or the kinship of all living things but I tell you Jerry at that moment, I <em>was</em> a marine biologist. </p> </div> ``` We’ve designed the `selection` modifier to be inheritable, so you can add it anywhere in the tree and it will be applied to all descendant elements. This makes it easy to set the selection color to match your brand across your entire site: ``` <html> <head> <!-- ... --> </head> <body class="selection:bg-pink-300"> <!-- ... --> </body> </html> ``` ### First-line and first-letter Style the first line in a block of content using the `first-line` modifier, and the first letter using the `first-letter` modifier: ``` <p class="first-line:uppercase first-line:tracking-widest first-letter:text-7xl first-letter:font-bold first-letter:text-slate-900 first-letter:mr-3 first-letter:float-left "> Well, let me tell you something, funny boy. Y'know that little stamp, the one that says "New York Public Library"? Well that may not mean anything to you, but that means a lot to me. One whole hell of a lot. </p><p class="first-line:uppercase first-line:tracking-widest first-letter:text-7xl first-letter:font-bold first-letter:text-white first-letter:mr-3 first-letter:float-left "> Well, let me tell you something, funny boy. Y'know that little stamp, the one that says "New York Public Library"? Well that may not mean anything to you, but that means a lot to me. One whole hell of a lot. </p> ``` ### Dialog backdrops Style the backdrop of a [native `<dialog>` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog) using the `backdrop` modifier: ``` <dialog class="backdrop:bg-gray-50"> <form method="dialog"> <!-- ... --> </form> </dialog> ``` If you’re using native `<dialog>` elements in your project, you may also want to read about [styling open/closed states](hover-focus-and-other-states#open-closed-state) using the `open` modifier. Media and feature queries ------------------------- ### Responsive breakpoints To style an element at a specific breakpoint, use responsive modifiers like `md` and `lg`. For example, this will render a 3-column grid on mobile, a 4-column grid on medium-width screens, and a 6-column grid on large-width screens: ``` <div class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6"> <!-- ... --> </div> ``` Check out the [Responsive Design](responsive-design) documentation for an in-depth look at how these features work. ### Prefers color scheme The `prefers-color-scheme` media query tells you whether the user prefers a light theme or dark theme, and is usually configured at the operating system level. Use utilities with no modifier to target light mode, and use the `dark` modifier to provide overrides for dark mode: ``` <div class="bg-white dark:bg-slate-900 rounded-lg px-6 py-8 ring-1 ring-slate-900/5 shadow-xl"> <div> <span class="inline-flex items-center justify-center p-2 bg-indigo-500 rounded-md shadow-lg"> <svg class="h-6 w-6 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true"><!-- ... --></svg> </span> </div> <h3 class="text-slate-900 dark:text-white mt-5 text-base font-medium tracking-tight">Writes Upside-Down</h3> <p class="text-slate-500 dark:text-slate-400 mt-2 text-sm"> The Zero Gravity Pen can be used to write in any orientation, including upside-down. It even works in outer space. </p> </div> ``` Check out the [Dark Mode](dark-mode) documentation for an in-depth look at how this feature works. ### Prefers reduced motion The `prefers-reduced-motion` media query tells you if the user has requested that you minimize non-essential motion. Use the `motion-reduce` modifier to conditionally add styles when the user has requested reduced motion: ``` <button type="button" class="bg-indigo-500 ..." disabled> <svg class="motion-reduce:hidden animate-spin ..." viewBox="0 0 24 24"><!-- ... --></svg> Processing... </button> ``` Tailwind also includes a `motion-safe` modifier that only adds styles when the user has *not* requested reduced motion. This can be useful when using the `motion-reduce` helper would mean having to “undo” a lot of styles: ``` <!-- Using `motion-reduce` can mean lots of "undoing" styles --> <button class="hover:-translate-y-0.5 transition motion-reduce:hover:translate-y-0 motion-reduce:transition-none ..."> Save changes </button<!-- Using `motion-safe` is less code in these situations --> <button class="motion-safe:hover:-translate-x-0.5 motion-safe:transition ..."> Save changes </button> ``` ### Prefers contrast The `prefers-contrast` media query tells you if the user has requested more or less contrast. Use the `contrast-more` modifier to conditionally add styles when the user has requested more contrast: ``` <form> <label class="block"> <span class="block text-sm font-medium text-slate-700">Social Security Number</span> <input class="border-slate-200 placeholder-slate-400 contrast-more:border-slate-400 contrast-more:placeholder-slate-500"/> <p class="mt-2 opacity-10 contrast-more:opacity-100 text-slate-600 text-sm"> We need this to steal your identity. </p> </label> </form> ``` Tailwind also includes a `contrast-less` modifier you can use to conditionally add styles when the user has requested less contrast. ### Viewport orientation Use the `portrait` and `landscape` modifiers to conditionally add styles when the viewport is in a specific orientation: ``` <div> <div class="portrait:hidden"> <!-- ... --> </div> <div class="landscape:hidden"> <p> This experience is designed to be viewed in landscape. Please rotate your device to view the site. </p> </div> </div> ``` ### Print styles Use the `print` modifier to conditionally add styles that only apply when the document is being printed: ``` <div> <article class="print:hidden"> <h1>My Secret Pizza Recipe</h1> <p>This recipe is a secret, and must not be shared with anyone</p> <!-- ... --> </article> <div class="hidden print:block"> Are you seriously trying to print this? It's secret! </div> </div> ``` ### Supports rules Use the `supports-[...]` modifier to style things based on whether a certain feature is supported in the user’s browser. ``` <div class="flex supports-[display:grid]:grid ..."> <!-- ... --> </div> ``` Under the hood the `supports-[...]` modifier generates [`@supports rules`](https://developer.mozilla.org/en-US/docs/Web/CSS/@supports) and takes anything you’d use with `@supports (...)` between the square brackets, like a property/value pair, and even expressions using `and` and `or`. For terseness, if you only need to check if a property is supported (and not a specific value), you can just specify the property name: ``` <div class="bg-black/75 supports-[backdrop-filter]:bg-black/25 supports-[backdrop-filter]:backdrop-blur ..."> <!-- ... --> </div> ``` You can configure shortcuts for common `@supports` rules you’re using in your project in the `theme.supports` section of your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { theme: { supports: { grid: 'display: grid', }, }, } ``` You can then use these custom `supports-*` modifiers in your project: ``` <div class="supports-grid:grid"> <!-- ... --> </div> ``` Attribute selectors ------------------- ### ARIA states Use the `aria-*` modifier to conditionally style things based on [ARIA attributes](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes). For example, to apply the `bg-sky-700` class when the `aria-checked` attribute is set to `true`, use the `aria-checked:bg-sky-700` class: ``` <div aria-checked="true" class="bg-gray-600 aria-checked:bg-sky-700"> <!-- ... --> </div> ``` By default we’ve included modifiers for the most common boolean ARIA attributes: | Modifier | CSS | | --- | --- | | `aria-checked` | `&[aria-checked=“true”]` | | `aria-disabled` | `&[aria-disabled=“true”]` | | `aria-expanded` | `&[aria-expanded=“true”]` | | `aria-hidden` | `&[aria-hidden=“true”]` | | `aria-pressed` | `&[aria-pressed=“true”]` | | `aria-readonly` | `&[aria-readonly=“true”]` | | `aria-required` | `&[aria-required=“true”]` | | `aria-selected` | `&[aria-selected=“true”]` | You can customize which `aria-*` modifiers are available by editing `theme.aria` or `theme.extend.aria` in your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { theme: { extend: { aria: { asc: 'sort="ascending"', desc: 'sort="descending"', }, }, }, }; ``` If you need to use a one-off `aria` modifier that doesn’t make sense to include in your theme, or for more complex ARIA attributes that take specific values, use square brackets to generate a property on the fly using any arbitrary value. ARIA state modifiers can also target parent and sibling elements using the `group-aria-*` and `peer-aria-*` modifiers: ### Data attributes Use the `data-*` modifier to conditionally apply styles based on [data attributes](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes). Since there are no standard `data-*` attributes by definition, by default we only support arbitrary values out of the box, for example: ``` <!-- Will apply --> <div data-size="large" class="data-[size=large]:p-8"> <!-- ... --> </div<!-- Will not apply --> <div data-size="medium" class="data-[size=large]:p-8"> <!-- ... --> </div> ``` You can configure shortcuts for common data attribute selectors you’re using in your project in the `theme.data` section of your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { theme: { data: { checked: 'ui~="checked"', }, }, } ``` You can then use these custom `data-*` modifiers in your project: ``` <div data-ui="checked active" class="data-checked:underline"> <!-- ... --> </div> ``` ### RTL support Use the `rtl` and `ltr` modifiers to conditionally add styles in right-to-left and left-to-right modes respectively when building multi-directional layouts: ``` <div class="group flex items-center"> <img class="shrink-0 h-12 w-12 rounded-full" src="..." alt="" /> <div class="ltr:ml-3 rtl:mr-3"> <p class="text-sm font-medium text-slate-700 group-hover:text-slate-900">...</p> <p class="text-sm font-medium text-slate-500 group-hover:text-slate-700">...</p> </div> </div> <div class="group flex items-center"> <img class="shrink-0 h-12 w-12 rounded-full" src="..." alt="" /> <div class="ltr:ml-3 rtl:mr-3"> <p class="text-sm font-medium text-slate-300 group-hover:text-white">...</p> <p class="text-sm font-medium text-slate-500 group-hover:text-slate-300">...</p> </div> </div``` Note that the `ltr` modifier will not take effect unless the `dir` attribute is explicitly set to `ltr`, so if you are building a multi-directional site make sure to always set a direction, not just in `rtl` mode. Always set the direction, even if left-to-right is your default ``` <html dir="ltr"> <!-- ... --> </html> ``` Remember, these modifiers are only useful if you are building a site that needs to support *both* left-to-right and right-to-left layouts. If you’re building a site that only needs to support a single direction, you don’t need these modifiers — just apply the styles that make sense for your content. ### Open/closed state Use the `open` modifier to conditionally add styles when a `<details>` or `<dialog>` element is in an open state: ``` <div class="max-w-lg mx-auto p-8"> <details class="open:bg-white dark:open:bg-slate-900 open:ring-1 open:ring-black/5 dark:open:ring-white/10 open:shadow-lg p-6 rounded-lg" open> <summary class="text-sm leading-6 text-slate-900 dark:text-white font-semibold select-none"> Why do they call it Ovaltine? </summary> <div class="mt-3 text-sm leading-6 text-slate-600 dark:text-slate-400"> <p>The mug is round. The jar is round. They should call it Roundtine.</p> </div> </details> </div``` Custom modifiers ---------------- ### Using arbitrary variants Just like [arbitrary values](adding-custom-styles#using-arbitrary-values) let you use custom values with your utility classes, arbitrary variants let you write custom selector modifiers directly in your HTML. Arbitrary variants are just format strings that represent the selector, wrapped in square brackets. For example, this arbitrary modifier selects an element only when it is the third child: The format string is the same as what you’d use with the [`addVariant` plugin API](plugins#adding-variants), with the `&` representing the selector being modified. Arbitrary variants can be stacked with built-in modifiers or with each other, just like the rest of the modifiers in Tailwind: If you need spaces in your selector, you can use an underscore. For example, this arbitrary modifier selects all `p` elements within the element where you’ve added the class: You can also use at-rules like `@media` or `@supports` in arbitrary variants: With at-rule custom modifiers the `&` placeholder isn’t necessary, just like when nesting with a preprocessor. You can even combine at-rules and regular selector modifiers by including the selector modifier within curly braces after the at-rule: ### Creating a plugin If you find yourself using the same arbitrary modifier multiple times in your project, it might be worth extracting it to a plugin using the `addVariant` API: tailwind.config.js ``` let plugin = require('tailwindcss/plugin') module.exports = { // ... plugins: [ plugin(function ({ addVariant }) { // Add a `third` variant, ie. `third:pb-0` addVariant('third', '&:nth-child(3)') }) ] } ``` Learn more in the [adding variant plugins](plugins#adding-variants) documentation. Advanced topics --------------- ### Using with your own classes All of Tailwind’s modifiers are available to use with your own custom classes as long as you’ve defined them in one of Tailwind’s [layers](adding-custom-styles#using-css-and-layer) or added them using a [plugin](adding-custom-styles#writing-plugins): main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer utilities { .content-auto { content-visibility: auto; } } ``` HTML ``` <div class="lg:content-auto"> <!-- ... --> </div> ``` ### Ordering stacked modifiers When stacking modifiers, they are applied from the inside-out, like nested function calls: ``` // These modifiers: 'dark:group-hover:focus:opacity-100' // ...are applied like this: dark(groupHover(focus('opacity-100'))) ``` For the most part this doesn’t actually matter, but there are a few situations where the order you use actually generates meaningfully different CSS. For example, if you have `darkMode` configured to `class`, combining the `dark` and `group-hover` modifiers generates a different result depending on the order you use: ``` /* dark:group-hover:opacity-100 */ .dark .group:hover .dark\:group-hover\:opacity-100 { opacity: 1; } /* group-hover:dark:opacity-100 */ .group:hover .dark .group-hover\:dark\:opacity-100 { opacity: 1; } ``` In the first example, the `dark` element needs to be a parent of the `group` element, but in the second example it’s reversed. Another place this is important is when using modifiers like `prose-headings` that are included with the official typography plugin: ``` /* prose-headings:hover:underline */ .prose-headings\:hover\:underline:hover :is(:where(h1, h2, h3, h4, th)) { text-decoration: underline; } /* hover:prose-headings:underline */ .hover\:prose-headings\:underline :is(:where(h1, h2, h3, h4, th)):hover { text-decoration: underline; } ``` In the first example, every single heading is underlined when you hover over the article itself, whereas in the second example each heading is only underlined when you hover over that heading. Appendix -------- ### Quick reference A quick reference table of every single modifier included in Tailwind by default. | Modifier | CSS | | --- | --- | | [hover](#hover) | `&:hover` | | [focus](#focus) | `&:focus` | | [focus-within](#focus-within) | `&:focus-within` | | [focus-visible](#focus-visible) | `&:focus-visible` | | [active](#active) | `&:active` | | [visited](#visited) | `&:visited` | | [target](#target) | `&:target` | | [first](#first) | `&:first-child` | | [last](#last) | `&:last-child` | | [only](#only) | `&:only-child` | | [odd](#odd) | `&:nth-child(odd)` | | [even](#even) | `&:nth-child(even)` | | [first-of-type](#first-of-type) | `&:first-of-type` | | [last-of-type](#last-of-type) | `&:last-of-type` | | [only-of-type](#only-of-type) | `&:only-of-type` | | [empty](#empty) | `&:empty` | | [disabled](#disabled) | `&:disabled` | | [enabled](#enabled) | `&:enabled` | | [checked](#checked) | `&:checked` | | [indeterminate](#indeterminate) | `&:indeterminate` | | [default](#default) | `&:default` | | [required](#required) | `&:required` | | [valid](#valid) | `&:valid` | | [invalid](#invalid) | `&:invalid` | | [in-range](#in-range) | `&:in-range` | | [out-of-range](#out-of-range) | `&:out-of-range` | | [placeholder-shown](#placeholder-shown) | `&:placeholder-shown` | | [autofill](#autofill) | `&:autofill` | | [read-only](#read-only) | `&:read-only` | | [before](#before-and-after) | `&::before` | | [after](#before-and-after) | `&::after` | | [first-letter](#first-line-and-first-letter) | `&::first-letter` | | [first-line](#first-line-and-first-letter) | `&::first-line` | | [marker](#highlighted-text) | `&::marker` | | [selection](#selection) | `&::selection` | | [file](#file-input-buttons) | `&::file-selector-button` | | [backdrop](#dialog-backdrops) | `&::backdrop` | | [placeholder](#placeholder) | `&::placeholder` | | [sm](#responsive-breakpoints) | `@media (min-width: 640px)` | | [md](#responsive-breakpoints) | `@media (min-width: 768px)` | | [lg](#responsive-breakpoints) | `@media (min-width: 1024px)` | | [xl](#responsive-breakpoints) | `@media (min-width: 1280px)` | | [2xl](#responsive-breakpoints) | `@media (min-width: 1536px)` | | [min-[…]](#responsive-breakpoints) | `@media (min-width: …)` | | [max-sm](#responsive-breakpoints) | `@media not all and (min-width: 640px)` | | [max-md](#responsive-breakpoints) | `@media not all and (min-width: 768px)` | | [max-lg](#responsive-breakpoints) | `@media not all and (min-width: 1024px)` | | [max-xl](#responsive-breakpoints) | `@media not all and (min-width: 1280px)` | | [max-2xl](#responsive-breakpoints) | `@media not all and (min-width: 1536px)` | | [max-[…]](#responsive-breakpoints) | `@media (max-width: …)` | | [dark](#prefers-color-scheme) | `@media (prefers-color-scheme: dark)` | | [portrait](#viewport-orientation) | `@media (orientation: portrait)` | | [landscape](#viewport-orientation) | `@media (orientation: landscape)` | | [motion-safe](#prefers-reduced-motion) | `@media (prefers-reduced-motion: no-preference)` | | [motion-reduce](#prefers-reduced-motion) | `@media (prefers-reduced-motion: reduce)` | | [contrast-more](#prefers-contrast) | `@media (prefers-contrast: more)` | | [contrast-less](#prefers-contrast) | `@media (prefers-contrast: less)` | | [print](#print-styles) | `@media print` | | [supports-[…]](#supports) | `@supports (…)` | | [aria-checked](#aria-states) | `&[aria-checked=“true”]` | | [aria-disabled](#aria-states) | `&[aria-disabled=“true”]` | | [aria-expanded](#aria-states) | `&[aria-expanded=“true”]` | | [aria-hidden](#aria-states) | `&[aria-hidden=“true”]` | | [aria-pressed](#aria-states) | `&[aria-pressed=“true”]` | | [aria-readonly](#aria-states) | `&[aria-readonly=“true”]` | | [aria-required](#aria-states) | `&[aria-required=“true”]` | | [aria-selected](#aria-states) | `&[aria-selected=“true”]` | | [aria-[…]](#aria-states) | `&[aria-…]` | | [data-[…]](#data-attributes) | `&[data-…]` | | [rtl](#rtl-support) | `[dir=“rtl”] &` | | [ltr](#rtl-support) | `[dir=“ltr”] &` | | [open](#open-closed-state) | `&[open]` | ### Pseudo-class reference This is a comprehensive list of examples for all the pseudo-class modifiers included in Tailwind to complement the [pseudo-classes documentation](hover-focus-and-other-states#pseudo-classes) at the beginning of this guide. #### hover (:hover) Style an element when the user hovers over it with the mouse cursor using the `hover` modifier: ``` <div class="bg-black hover:bg-white ..."> <!-- ... --> </div> ``` #### focus (:focus) Style an element when it has focus using the `focus` modifier: ``` <input class="border-gray-300 focus:border-blue-400 ..." /> ``` #### focus-within (:focus-within) Style an element when it or one of its descendants has focus using the `focus-within` modifier: ``` <div class="focus-within:shadow-lg ..."> <input type="text" /> </div> ``` #### focus-visible (:focus-visible) Style an element when it has been focused using the keyboard using the `focus-visible` modifier: ``` <button class="focus:outline-none focus-visible:ring ..."> Submit </button> ``` #### active (:active) Style an element when it is being pressed using the `active` modifier: ``` <button class="bg-blue-500 active:bg-blue-600 ..."> Submit </button> ``` #### visited (:visited) Style a link when it has already been visited using the `visited` modifier: ``` <a href="https://seinfeldquotes.com" class="text-blue-600 visited:text-purple-600 ..."> Inspiration </a> ``` #### target (:target) Style an element if its ID matches the current URL fragment using the `target` modifier: ``` <div id="about" class="target:shadow-lg ..."> <!-- ... --> </div> ``` #### first (:first-child) Style an element if it’s the first child using the `first` modifier: ``` <ul> {#each people as person} <li class="py-4 first:pt-0 ..."> <!-- ... --> </li> {/each} </ul> ``` #### last (:last-child) Style an element if it’s the last child using the `last` modifier: ``` <ul> {#each people as person} <li class="py-4 last:pb-0 ..."> <!-- ... --> </li> {/each} </ul> ``` #### only (:only-child) Style an element if it’s the only child using the `only` modifier: ``` <ul> {#each people as person} <li class="py-4 only:py-0 ..."> <!-- ... --> </li> {/each} </ul> ``` #### odd (:nth-child(odd)) Style an element if it’s an oddly numbered child using the `odd` modifier: ``` <table> {#each people as person} <tr class="bg-white odd:bg-gray-100 ..."> <!-- ... --> </tr> {/each} </table> ``` #### even (:nth-child(even)) Style an element if it’s an evenly numbered child using the `even` modifier: ``` <table> {#each people as person} <tr class="bg-white even:bg-gray-100 ..."> <!-- ... --> </tr> {/each} </table> ``` #### first-of-type (:first-of-type) Style an element if it’s the first child of its type using the `first-of-type` modifier: ``` <nav> <img src="/logo.svg" alt="Vandelay Industries" /> {#each links as link} <a href="#" class="ml-2 first-of-type:ml-6 ..."> <!-- ... --> </a> {/each} </table> ``` #### last-of-type (:last-of-type) Style an element if it’s the last child of its type using the `last-of-type` modifier: ``` <nav> <img src="/logo.svg" alt="Vandelay Industries" /> {#each links as link} <a href="#" class="mr-2 last-of-type:mr-6 ..."> <!-- ... --> </a> {/each} <button>More</button> </table> ``` #### only-of-type (:only-of-type) Style an element if it’s the only child of its type using the `only-of-type` modifier: ``` <nav> <img src="/logo.svg" alt="Vandelay Industries" /> {#each links as link} <a href="#" class="mx-2 only-of-type:mx-6 ..."> <!-- ... --> </a> {/each} <button>More</button> </table> ``` #### empty (:empty) Style an element if it has no content using the `empty` modifier: ``` <ul> {#each people as person} <li class="empty:hidden ...">{person.hobby}</li> {/each} </ul> ``` #### disabled (:disabled) Style an input when it’s disabled using the `disabled` modifier: ``` <input class="disabled:opacity-75 ..." /> ``` #### enabled (:enabled) Style an input when it’s enabled using the `enabled` modifier, most helpful when you only want to apply another style when an element is not disabled: ``` <input class="enabled:hover:border-gray-400 disabled:opacity-75 ..." /> ``` #### checked (:checked) Style a checkbox or radio button when it’s checked using the `checked` modifier: ``` <input type="checkbox" class="appearance-none checked:bg-blue-500 ..." /> ``` #### indeterminate (:indeterminate) Style a checkbox or radio button in an indeterminate state using the `indeterminate` modifier: ``` <input type="checkbox" class="appearance-none indeterminate:bg-gray-300 ..." /> ``` #### default (:default) Style an option, checkbox or radio button that was the default value when the page initially loaded using the `default` modifier: ``` <input type="checkbox" class="default:ring-2 ..." /> ``` #### required (:required) Style an input when it’s required using the `required` modifier: ``` <input class="required:border-red-500 ..." /> ``` #### valid (:valid) Style an input when it’s valid using the `valid` modifier: ``` <input class="valid:border-green-500 ..." /> ``` #### invalid (:invalid) Style an input when it’s invalid using the `invalid` modifier: ``` <input class="invalid:border-red-500 ..." /> ``` #### in-range (:in-range) Style an input when it’s value is within a specified range limit using the `in-range` modifier: ``` <input min="1" max="5" class="in-range:border-green-500 ..." /> ``` #### out-of-range (:out-of-range) Style an input when it’s value is outside of a specified range limit using the `out-of-range` modifier: ``` <input min="1" max="5" class="out-of-range:border-red-500 ..." /> ``` #### placeholder-shown (:placeholder-shown) Style an input when the placeholder is shown using the `placeholder-shown` modifier: ``` <input class="placeholder-shown:border-gray-500 ..." placeholder="<EMAIL>" /> ``` #### autofill (:autofill) Style an input when it has been autofilled by the browser using the `autofill` modifier: ``` <input class="autofill:bg-yellow-200 ..." /> ``` #### read-only (:read-only) Style an input when it is read-only using the `read-only` modifier: ``` <input class="read-only:bg-gray-100 ..." /> ``` © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/hover-focus-and-other-statesDark Mode ========= Using Tailwind CSS to style your site in dark mode. Basic usage ----------- Now that dark mode is a first-class feature of many operating systems, it’s becoming more and more common to design a dark version of your website to go along with the default design. To make this as easy as possible, Tailwind includes a `dark` variant that lets you style your site differently when dark mode is enabled: ``` <div class="bg-white dark:bg-slate-800 rounded-lg px-6 py-8 ring-1 ring-slate-900/5 shadow-xl"> <div> <span class="inline-flex items-center justify-center p-2 bg-indigo-500 rounded-md shadow-lg"> <svg class="h-6 w-6 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true"><!-- ... --></svg> </span> </div> <h3 class="text-slate-900 dark:text-white mt-5 text-base font-medium tracking-tight">Writes Upside-Down</h3> <p class="text-slate-500 dark:text-slate-400 mt-2 text-sm"> The Zero Gravity Pen can be used to write in any orientation, including upside-down. It even works in outer space. </p> </div> ``` By default this uses the `prefers-color-scheme` CSS media feature, but you can also build sites that support toggling dark mode manually using the [‘class’ strategy](dark-mode#toggling-dark-mode-manually). Toggling dark mode manually --------------------------- If you want to support toggling dark mode manually instead of relying on the operating system preference, use the `class` strategy instead of the `media` strategy: tailwind.config.js ``` module.exports = { darkMode: 'class', // ... } ``` Now instead of `dark:{class}` classes being applied based on `prefers-color-scheme`, they will be applied whenever `dark` class is present earlier in the HTML tree. ``` <!-- Dark mode not enabled --> <html> <body> <!-- Will be white --> <div class="bg-white dark:bg-black"> <!-- ... --> </div> </body> </html<!-- Dark mode enabled --> <html class="dark"> <body> <!-- Will be black --> <div class="bg-white dark:bg-black"> <!-- ... --> </div> </body> </html> ``` If you’ve set [a prefix](configuration#prefix) in your Tailwind config, be sure to add that to the `dark` class. For example, if you have a prefix of `tw-`, you’ll need to use the `tw-dark` class to enable dark mode. How you add the `dark` class to the `html` element is up to you, but a common approach is to use a bit of JS that reads a preference from somewhere (like `localStorage`) and updates the DOM accordingly. ### Supporting system preference and manual selection The `class` strategy can be used to support both the user’s system preference *or* a manually selected mode by using the [`Window.matchMedia()` API](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia). Here’s a simple example of how you can support light mode, dark mode, as well as respecting the operating system preference: spaghetti.js ``` // On page load or when changing themes, best to add inline in `head` to avoid FOUC if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) { document.documentElement.classList.add('dark') } else { document.documentElement.classList.remove('dark') } // Whenever the user explicitly chooses light mode localStorage.theme = 'light' // Whenever the user explicitly chooses dark mode localStorage.theme = 'dark' // Whenever the user explicitly chooses to respect the OS preference localStorage.removeItem('theme') ``` Again you can manage this however you like, even storing the preference server-side in a database and rendering the class on the server — it’s totally up to you. ### Customizing the class name Some frameworks (like NativeScript) have their own approach to enabling dark mode and add a different class name when dark mode is active. You can customize the dark mode selector name by setting `darkMode` to an array with your custom selector as the second item: tailwind.config.js ``` module.exports = { darkMode: ['class', '[data-mode="dark"]'], // ... } ``` © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/dark-modeReusing Styles ============== Managing duplication and creating reusable abstractions. Tailwind encourages a <utility-first> workflow, where designs are implemented using only low-level utility classes. This is a powerful way to avoid premature abstraction and the pain points that come with it. But of course as a project grows, you’ll inevitably find yourself repeating common utility combinations to recreate the same design in many different places. For example, in the template below you can see the utility classes for each avatar image are repeated five separate times: ``` <div> <div class="flex items-center space-x-2 text-base"> <h4 class="font-semibold text-slate-900">Contributors</h4> <span class="rounded-full bg-slate-100 px-2 py-1 text-xs font-semibold text-slate-700">204</span> </div> <div class="mt-3 flex -space-x-2 overflow-hidden"> <img class="inline-block h-12 w-12 rounded-full ring-2 ring-white" src="https://images.unsplash.com/photo-1491528323818-fdd1faba62cc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt=""/> <img class="inline-block h-12 w-12 rounded-full ring-2 ring-white" src="https://images.unsplash.com/photo-1550525811-e5869dd03032?ixlib=rb-1.2.1&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt=""/> <img class="inline-block h-12 w-12 rounded-full ring-2 ring-white" src="https://images.unsplash.com/photo-1500648767791-00dcc994a43e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2.25&w=256&h=256&q=80" alt=""/> <img class="inline-block h-12 w-12 rounded-full ring-2 ring-white" src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt=""/> <img class="inline-block h-12 w-12 rounded-full ring-2 ring-white" src="https://images.unsplash.com/photo-1517365830460-955ce3ccd263?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt=""/> </div> <div class="mt-3 text-sm font-medium"> <a href="#" class="text-blue-500">+ 198 others</a> </div> </div> ``` Don’t panic! In this guide, you’ll learn about different strategies for reusing styles in your project, as well as best practices for when to employ each one. Using editor and language features ---------------------------------- A lot of the time, duplication like this isn’t even a real problem because it’s all together in one place, or doesn’t even actually exist because you’re iterating over an array of items and only writing the markup once. If the styles you need to reuse only need to be reused within a single file, multi-cursor editing and loops are the simplest way to manage any duplication. ### Multi-cursor editing When duplication is localized to a group of elements in a single file, the easiest way to deal with it to use [multi-cursor editing](https://code.visualstudio.com/docs/editor/codebasics#_multiple-selections-multicursor) to quickly select and edit the class list for each element at once: ``` <nav class="flex justify-center space-x-4"> <a href="/dashboard" class="font-medium px-3 py-2 text-slate-700 rounded-lg hover:bg-slate-100 hover:text-slate-900">Home</a> <a href="/team" class="font-medium px-3 py-2 text-slate-700 rounded-lg hover:bg-slate-100 hover:text-slate-900">Team</a> <a href="/projects" class="font-medium px-3 py-2 text-slate-700 rounded-lg hover:bg-slate-100 hover:text-slate-900">Projects</a> <a href="/reports" class="font-medium px-3 py-2 text-slate-700 rounded-lg hover:bg-slate-100 hover:text-slate-900">Reports</a> </nav``` You’d be surprised at how often this ends up being the best solution. If you can quickly edit all of the duplicated class lists simultaneously, there’s no benefit to introducing any additional abstraction. ### Loops Before you assume you’re going to need to extract a component or create a custom class for something, make sure you’re *actually* using it more than once in your template. A lot of the time a design element that shows up more than once in the rendered page is only actually authored once because the actual markup is rendered in a loop. For example, the duplicate avatars at the beginning of this guide would almost certainly be rendered in a loop in a real project: ``` <div> <div class="flex items-center space-x-2 text-base"> <h4 class="font-semibold text-slate-900">Contributors</h4> <span class="rounded-full bg-slate-100 px-2 py-1 text-xs font-semibold text-slate-700">204</span> </div> <div class="mt-3 flex -space-x-2 overflow-hidden"> {#each contributors as user} <img class="inline-block h-12 w-12 rounded-full ring-2 ring-white" src="{user.avatarUrl}" alt="{user.handle}"/> {/each} </div> <div class="mt-3 text-sm font-medium"> <a href="#" class="text-blue-500">+ 198 others</a> </div> </div> ``` You could even rewrite the navigation example using a loop or `map` if you preferred as well: ``` <nav className="flex sm:justify-center space-x-4"> {[ ['Home', '/dashboard'], ['Team', '/team'], ['Projects', '/projects'], ['Reports', '/reports'], ].map(([title, url]) => ( <a href={url} className="rounded-lg px-3 py-2 text-slate-700 font-medium hover:bg-slate-100 hover:text-slate-900">{title}</a> ))} </nav> ``` When elements are rendered in a loop like this, the actual class list is only written once so there’s no actual duplication problem to solve. Extracting components and partials ---------------------------------- If you need to reuse some styles across multiple files, the best strategy is to create a *component* if you’re using a front-end framework like React, Svelte, or Vue, or a *template partial* if you’re using a templating language like Blade, ERB, Twig, or Nunjucks. VacationCard.vue ``` <template> <div> <img class="rounded" :src="img" :alt="imgAlt"> <div class="mt-2"> <div> <div class="text-xs text-slate-600 uppercase font-bold tracking-wider">{{ eyebrow }}</div> <div class="font-bold text-slate-700 leading-snug"> <a :href="url" class="hover:underline">{{ title }}</a> </div> <div class="mt-2 text-sm text-slate-600">{{ pricing }}</div> </div> </div> </div> </template<script> export default { props: ['img', 'imgAlt', 'eyebrow', 'title', 'pricing', 'url'] } </script> ``` Now you can use this component in as many places as you like, while still having a single source of truth for the styles so they can easily be updated together in one place. ### Compared to CSS abstractions Unless a component is a single HTML element, the information needed to define it can’t be captured in CSS alone. For anything even remotely complex, the HTML structure is just as important as the CSS. Don’t rely on CSS classes to extract complex components ``` <!-- Even with custom CSS, you still need to duplicate this HTML structure --> <div class="chat-notification"> <div class="chat-notification-logo-wrapper"> <img class="chat-notification-logo" src="/img/logo.svg" alt="ChitChat Logo"> </div> <div class="chat-notification-content"> <h4 class="chat-notification-title">ChitChat</h4> <p class="chat-notification-message">You have a new message!</p> </div> </div<style> .chat-notification { /* ... */ } .chat-notification-logo-wrapper { /* ... */ } .chat-notification-logo { /* ... */ } .chat-notification-content { /* ... */ } .chat-notification-title { /* ... */ } .chat-notification-message { /* ... */ } </style> ``` Even if you create classes for the different elements in a component like this, *you still have to duplicate the HTML every time you want to use this component*. Sure you can update the font-size for every instance in a single place, but what if you need to turn the title into a link? Components and template partials solve this problem much better than CSS-only abstractions because a component can encapsulate the HTML *and* the styles. Changing the font-size for every instance is just as easy as it is with CSS, but now you can turn all of the titles into links in a single place too. Create a template partial or JavaScript component Notification.jsx ``` function Notification({ imageUrl, imageAlt, title, message }) { return ( <div className="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-md flex items-center space-x-4"> <div className="shrink-0"> <img className="h-12 w-12" src={imageUrl.src} alt={imageAlt}> </div> <div> <div className="text-xl font-medium text-black">{title}</div> <p className="text-slate-500">{message}</p> </div> </div> ) } ``` When you create components and template partials like this, there’s no reason to use anything other than utility classes because you already have a single source of truth for the styles. Extracting classes with @apply ------------------------------ If you’re using a traditional templating language like ERB or Twig, creating a template partial for something as small as a button can feel like overkill compared to a simple CSS class like `btn`. While it’s highly recommended that you create proper template partials for more complex components, you can use Tailwind’s `@apply` directive to extract repeated utility patterns to custom CSS classes when a template partial feels heavy-handed. Here’s what a `btn-primary` class might look like using `@apply` to compose it from existing utilities: HTML ``` <!-- Before extracting a custom class --> <button class="py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75"> Save changes </button<!-- After extracting a custom class --> <button class="btn-primary"> Save changes </button> ``` CSS ``` @tailwind base; @tailwind components; @tailwind utilities; @layer components { .btn-primary { @apply py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75; } } ``` Learn more about `@apply` and `@layer` in the [Functions & Directives](functions-and-directives#layer) documentation. ### Avoiding premature abstraction Whatever you do, **don’t use `@apply` just to make things look “cleaner”**. Yes, HTML templates littered with Tailwind classes are kind of ugly. Making changes in a project that has tons of custom CSS is worse. If you start using `@apply` for everything, you are basically just writing CSS again and throwing away all of the workflow and maintainability advantages Tailwind gives you, for example: * **You have to think up class names all the time** — nothing will slow you down or drain your energy like coming up with a class name for something that doesn’t deserve to be named. * **You have to jump between multiple files to make changes** — which is a way bigger workflow killer than you’d think before co-locating everything together. * **Changing styles is scarier** — CSS is global, are you *sure* you can change the min-width value in that class without breaking something in another part of the site? * **Your CSS bundle will be bigger** — oof. If you’re going to use `@apply`, use it for very small, highly reusable things like buttons and form controls — and even then only if you’re not using a framework like React where a component would be a better choice. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/reusing-stylesAdding Custom Styles ==================== Best practices for adding your own custom styles to Tailwind. Often the biggest challenge when working with a framework is figuring out what you’re supposed to do when there’s something you need that the framework doesn’t handle for you. Tailwind has been designed from the ground up to be extensible and customizable, so that no matter what you’re building you never feel like you’re fighting the framework. This guide covers topics like customizing your design tokens, how to break out of those constraints when necessary, adding your own custom CSS, and extending the framework with plugins. Customizing your theme ---------------------- If you want to change things like your color palette, spacing scale, typography scale, or breakpoints, add your customizations to the `theme` section of your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { theme: { screens: { sm: '480px', md: '768px', lg: '976px', xl: '1440px', }, colors: { 'blue': '#1fb6ff', 'pink': '#ff49db', 'orange': '#ff7849', 'green': '#13ce66', 'gray-dark': '#273444', 'gray': '#8492a6', 'gray-light': '#d3dce6', }, fontFamily: { sans: ['Graphik', 'sans-serif'], serif: ['Merriweather', 'serif'], }, extend: { spacing: { '128': '32rem', '144': '36rem', }, borderRadius: { '4xl': '2rem', } } } } ``` Learn more about customizing your theme in the [Theme Configuration](theme) documentation. Using arbitrary values ---------------------- While you can usually build the bulk of a well-crafted design using a constrained set of design tokens, once in a while you need to break out of those constraints to get things pixel-perfect. When you find yourself really needing something like `top: 117px` to get a background image in just the right spot, use Tailwind’s square bracket notation to generate a class on the fly with any arbitrary value: ``` <div class="top-[117px]"> <!-- ... --> </div> ``` This is basically like inline styles, with the major benefit that you can combine it with interactive modifiers like `hover` and responsive modifiers like `lg`: ``` <div class="top-[117px] lg:top-[344px]"> <!-- ... --> </div> ``` This works for everything in the framework, including things like background colors, font sizes, pseudo-element content, and more: ``` <div class="bg-[#bada55] text-[22px] before:content-['Festivus']"> <!-- ... --> </div> ``` It’s even possible to use the [`theme` function](functions-and-directives#theme) to reference the design tokens in your `tailwind.config.js` file: ``` <div class="grid grid-cols-[fit-content(theme(spacing.32))]"> <!-- ... --> </div> ``` When using a CSS variable as an arbitrary value, wrapping your variable in `var(...)` isn’t needed — just providing the actual variable name is enough: ``` <div class="bg-[--my-color]"> <!-- ... --> </div> ``` ### Arbitrary properties If you ever need to use a CSS property that Tailwind doesn’t include a utility for out of the box, you can also use square bracket notation to write completely arbitrary CSS: ``` <div class="[mask-type:luminance]"> <!-- ... --> </div> ``` This is *really* like inline styles, but again with the benefit that you can use modifiers: ``` <div class="[mask-type:luminance] hover:[mask-type:alpha]"> <!-- ... --> </div> ``` This can be useful for things like CSS variables as well, especially when they need to change under different conditions: ``` <div class="[--scroll-offset:56px] lg:[--scroll-offset:44px]"> <!-- ... --> </div> ``` ### Arbitrary variants Arbitrary *variants* are like arbitrary values but for doing on-the-fly selector modification, like you can with built-in pseudo-class variants like `hover:{utility}` or responsive variants like `md:{utility}` but using square bracket notation directly in your HTML. Learn more in the [arbitrary variants](hover-focus-and-other-states#using-arbitrary-variants) documentation. ### Handling whitespace When an arbitrary value needs to contain a space, use an underscore (`_`) instead and Tailwind will automatically convert it to a space at build-time: ``` <div class="grid grid-cols-[1fr_500px_2fr]"> <!-- ... --> </div> ``` In situations where underscores are common but spaces are invalid, Tailwind will preserve the underscore instead of converting it to a space, for example in URLs: ``` <div class="bg-[url('/what_a_rush.png')]"> <!-- ... --> </div> ``` In the rare case that you actually need to use an underscore but it’s ambiguous because a space is valid as well, escape the underscore with a backslash and Tailwind won’t convert it to a space: ``` <div class="before:content-['hello_world']"> <!-- ... --> </div> ``` If you’re using something like JSX where the backslash is stripped from the rendered HTML, use [String.raw()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw) so the backslash isn’t treated as a JavaScript escape character: ``` <div className={String.raw`before:content-['hello_world']`}> <!-- ... --> </div> ``` ### Resolving ambiguities Many utilities in Tailwind share a common namespace but map to different CSS properties. For example `text-lg` and `text-black` both share the `text-` namespace, but one is for `font-size` and the other is for `color`. When using arbitrary values, Tailwind can generally handle this ambiguity automatically based on the value you pass in: ``` <!-- Will generate a font-size utility --> <div class="text-[22px]">...</div<!-- Will generate a color utility --> <div class="text-[#bada55]">...</div> ``` Sometimes it really is ambiguous though, for example when using CSS variables: ``` <div class="text-[var(--my-var)]">...</div> ``` In these situations, you can “hint” the underlying type to Tailwind by adding a [CSS data type](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Types) before the value: ``` <!-- Will generate a font-size utility --> <div class="text-[length:var(--my-var)]">...</div<!-- Will generate a color utility --> <div class="text-[color:var(--my-var)]">...</div> ``` Using CSS and @layer -------------------- When you need to add truly custom CSS rules to a Tailwind project, the easiest approach is to just add the custom CSS to your stylesheet: main.css ``` @tailwind base; @tailwind components; @tailwind utilities; .my-custom-style { /* ... */ } ``` For more power, you can also use the `@layer` directive to add styles to Tailwind’s `base`, `components`, and `utilities` layers: main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer components { .my-custom-style { /* ... */ } } ``` Why does Tailwind group styles into “layers”?In CSS, the order of the rules in your stylesheet decides which declaration wins when two selectors have the same specificity: ``` .btn { background: blue; /* ... */ } .bg-black { background: black; } ``` Here, both buttons will be black since `.bg-black` comes after `.btn` in the CSS: ``` <button class="btn bg-black">...</button> <button class="bg-black btn">...</button> ``` To manage this, Tailwind organizes the styles it generates into three different “layers” — a concept popularized by [ITCSS](https://www.xfive.co/blog/itcss-scalable-maintainable-css-architecture/#what-is-itcss). * The `base` layer is for things like reset rules or default styles applied to plain HTML elements. * The `components` layer is for class-based styles that you want to be able to override with utilities. * The `utilities` layer is for small, single-purpose classes that should always take precedence over any other styles. Being explicit about this makes it easier to understand how your styles will interact with each other, and using the `@layer` directive lets you control the final declaration order while still organizing your actual code in whatever way you like. The `@layer` directive helps you control declaration order by automatically relocating your styles to the corresponding `@tailwind` directive, and also enables features like [modifiers](adding-custom-styles#using-modifiers-with-custom-css) and [tree-shaking](adding-custom-styles#removing-unused-custom-css) for your own custom CSS. ### Adding base styles If you just want to set some defaults for the page (like the text color, background color, or font family), the easiest option is just adding some classes to the `html` or `body` elements: ``` <!doctype html> <html lang="en" class="text-gray-900 bg-gray-100 font-serif"> <!-- ... --> </html> ``` This keeps your base styling decisions in your markup alongside all of your other styles, instead of hiding them in a separate file. If you want to add your own default base styles for specific HTML elements, use the `@layer` directive to add those styles to Tailwind’s `base` layer: main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer base { h1 { @apply text-2xl; } h2 { @apply text-xl; } /* ... */ } ``` Use the [`theme`](functions-and-directives#theme) function or [`@apply`](functions-and-directives#apply) directive when adding custom base styles if you want to refer to any of the values defined in your <theme>. ### Adding component classes Use the `components` layer for any more complicated classes you want to add to your project that you’d still like to be able to override with utility classes. Traditionally these would be classes like `card`, `btn`, `badge` — that kind of thing. main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer components { .card { background-color: theme('colors.white'); border-radius: theme('borderRadius.lg'); padding: theme('spacing.6'); box-shadow: theme('boxShadow.xl'); } /* ... */ } ``` By defining component classes in the `components` layer, you can still use utility classes to override them when necessary: ``` <!-- Will look like a card, but with square corners --> <div class="card rounded-none"> <!-- ... --> </div> ``` Using Tailwind you probably don’t need these types of classes as often as you think. Read our guide on [Reusing Styles](reusing-styles) for our recommendations. The `components` layer is also a good place to put custom styles for any third-party components you’re using: main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer components { .select2-dropdown { @apply rounded-b-lg shadow-md; } .select2-search { @apply border border-gray-300 rounded; } .select2-results__group { @apply text-lg font-bold text-gray-900; } /* ... */ } ``` Use the [`theme`](functions-and-directives#theme) function or [`@apply`](functions-and-directives#apply) directive when adding custom component styles if you want to refer to any of the values defined in your <theme>. ### Adding custom utilities Add any of your own custom utility classes to Tailwind’s `utilities` layer: main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer utilities { .content-auto { content-visibility: auto; } } ``` This can be useful when there’s a CSS feature you’d like to use in your project that Tailwind doesn’t include utilities for out of the box. ### Using modifiers with custom CSS Any custom styles you add to Tailwind with `@layer` will automatically support Tailwind’s modifier syntax for handling things like hover states, responsive breakpoints, dark mode, and more. CSS ``` @tailwind base; @tailwind components; @tailwind utilities; @layer utilities { .content-auto { content-visibility: auto; } } ``` HTML ``` <div class="lg:dark:content-auto"> <!-- ... --> </div> ``` Learn more about how these modifiers work in the [Hover, Focus, and Other States](hover-focus-and-other-states) documentation. ### Removing unused custom CSS Any custom styles you add to the `base`, `components`, or `utilities` layers will only be included in your compiled CSS if those styles are actually used in your HTML. main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer components { /* This won't be included in your compiled CSS unless you actually use it */ .card { /* ... */ } } ``` If you want to add some custom CSS that should always be included, add it to your stylesheet without using the `@layer` directive: main.css ``` @tailwind base; @tailwind components; /* This will always be included in your compiled CSS */ .card { /* ... */ } @tailwind utilities; ``` Make sure to put your custom styles where they need to go to get the precedence behavior you want. In the example above, we’ve added the `.card` class before `@tailwind utilities` to make sure utilities can still override it. ### Using multiple CSS files If you are writing a lot of CSS and organizing it into multiple files, make sure those files are combined into a single stylesheet before processing them with Tailwind, or you’ll see errors about using `@layer` without the corresponding `@tailwind` directive. The easiest way to do this is using the [postcss-import](https://github.com/postcss/postcss-import) plugin: postcss.config.js ``` module.exports = { plugins: { 'postcss-import': {}, tailwindcss: {}, autoprefixer: {}, } } ``` Learn more in our [build-time imports](https://tailwindcss.com/docs/using-with-preprocessors#build-time-imports) documentation. ### Layers and per-component CSS Component frameworks like Vue and Svelte support adding per-component styles within a `<style>` block that lives in each component file. While you can use features like `@apply` and `theme` inside component styles like this, the `@layer` directive will not work and you’ll see an error about `@layer` being used without a matching `@tailwind` directive: Don’t use `@layer` in component styles Card.svelte ``` <div> <slot></slot> </div<style> /* Won't work because this file is processed in isolation */ @layer components { div { background-color: theme('colors.white'); border-radius: theme('borderRadius.lg'); padding: theme('spacing.6'); box-shadow: theme('boxShadow.xl'); } } </style> ``` This is because under-the-hood, frameworks like Vue and Svelte are processing every single `<style>` block independently, and running your PostCSS plugin chain against each one in isolation. That means if you have 10 components that each have a `<style>` block, Tailwind is being run 10 separate times, and each run has zero knowledge about the other runs. Because of this, Tailwind can’t take the styles you define in a `@layer` and move them to the corresponding `@tailwind` directive, because as far as Tailwind can tell there is no `@tailwind` directive to move it to. One solution to this is to simply *not* use `@layer` inside your component styles: Add your styles without using `@layer` Card.svelte ``` <div> <slot></slot> </div<style> div { background-color: theme('colors.white'); border-radius: theme('borderRadius.lg'); padding: theme('spacing.6'); box-shadow: theme('boxShadow.xl'); } </style> ``` You lose the ability to control the precedence of your styles, but unfortunately that’s totally out of our control because of how these tools work. Our recommendation is that you just don’t use component styles like this at all and instead use Tailwind the way it’s intended to be used — as a single global stylesheet where you use the classes directly in your HTML: Use Tailwind’s utilities instead of component styles Card.svelte ``` <div class="bg-white rounded-lg p-6 shadow-xl"> <slot></slot> </div> ``` Writing plugins --------------- You can also add custom styles to your project using Tailwind’s plugin system instead of using a CSS file: tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { // ... plugins: [ plugin(function ({ addBase, addComponents, addUtilities, theme }) { addBase({ 'h1': { fontSize: theme('fontSize.2xl'), }, 'h2': { fontSize: theme('fontSize.xl'), }, }) addComponents({ '.card': { backgroundColor: theme('colors.white'), borderRadius: theme('borderRadius.lg'), padding: theme('spacing.6'), boxShadow: theme('boxShadow.xl'), } }) addUtilities({ '.content-auto': { contentVisibility: 'auto', } }) }) ] } ``` Learn more about writing your own plugins in the [Plugins](plugins) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/adding-custom-stylesConfiguration ============= A guide to configuring and customizing your Tailwind installation. Because Tailwind is a framework for building bespoke user interfaces, it has been designed from the ground up with customization in mind. By default, Tailwind will look for an optional `tailwind.config.js` file at the root of your project where you can define any customizations. tailwind.config.js ``` module.exports = { content: ['./src/**/*.{html,js}'], theme: { colors: { 'blue': '#1fb6ff', 'purple': '#7e5bef', 'pink': '#ff49db', 'orange': '#ff7849', 'green': '#13ce66', 'yellow': '#ffc82c', 'gray-dark': '#273444', 'gray': '#8492a6', 'gray-light': '#d3dce6', }, fontFamily: { sans: ['Graphik', 'sans-serif'], serif: ['Merriweather', 'serif'], }, extend: { spacing: { '8xl': '96rem', '9xl': '128rem', }, borderRadius: { '4xl': '2rem', } } }, } ``` Every section of the config file is optional, so you only have to specify what you’d like to change. Any missing sections will fall back to Tailwind’s [default configuration](https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/config.full.js). Creating your configuration file -------------------------------- Generate a Tailwind config file for your project using the Tailwind CLI utility included when you install the `tailwindcss` npm package: ``` npx tailwindcss init ``` This will create a minimal `tailwind.config.js` file at the root of your project: tailwind.config.js ``` module.exports = { content: [], theme: { extend: {}, }, plugins: [], } ``` ### Using a different file name To use a name other than `tailwind.config.js`, pass it as an argument on the command-line: ``` npx tailwindcss init tailwindcss-config.js ``` When you use a custom file name, you will need to specify it as a command-line argument when compiling your CSS with the Tailwind CLI tool: ``` npx tailwindcss -c ./tailwindcss-config.js -i input.css -o output.css ``` If you’re using Tailwind as a PostCSS plugin, you will need to specify your custom configuration path in your PostCSS configuration: postcss.config.js ``` module.exports = { plugins: { tailwindcss: { config: './tailwindcss-config.js' }, }, } ``` Alternatively, you can specify your custom configuration path using the `@config` directive: ``` @config "./tailwindcss-config.js"; @tailwind base; @tailwind components; @tailwind utilities; ``` Learn more about the `@config` directive in the [Functions & Directives](functions-and-directives#config) documentation. ### Generating a PostCSS configuration file Use the `-p` flag if you’d like to also generate a basic `postcss.config.js` file alongside your `tailwind.config.js` file: ``` npx tailwindcss init -p ``` This will generate a `postcss.config.js` file in your project that looks like this: postcss.config.js ``` module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, } ``` ### Scaffolding the entire default configuration For most users we encourage you to keep your config file as minimal as possible, and only specify the things you want to customize. If you’d rather scaffold a complete configuration file that includes all of Tailwind’s default configuration, use the `--full` option: ``` npx tailwindcss init --full ``` You’ll get a file that matches the [default configuration file](https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/config.full.js) Tailwind uses internally. Configuration options --------------------- ### Content The `content` section is where you configure the paths to all of your HTML templates, JS components, and any other files that contain Tailwind class names. tailwind.config.js ``` module.exports = { content: [ './pages/**/*.{html,js}', './components/**/*.{html,js}', ], // ... } ``` Learn more about configuring your content sources in the [Content Configuration](content-configuration) documentation. ### Theme The `theme` section is where you define your color palette, fonts, type scale, border sizes, breakpoints — anything related to the visual design of your site. tailwind.config.js ``` module.exports = { // ... theme: { colors: { 'blue': '#1fb6ff', 'purple': '#7e5bef', 'pink': '#ff49db', 'orange': '#ff7849', 'green': '#13ce66', 'yellow': '#ffc82c', 'gray-dark': '#273444', 'gray': '#8492a6', 'gray-light': '#d3dce6', }, fontFamily: { sans: ['Graphik', 'sans-serif'], serif: ['Merriweather', 'serif'], }, extend: { spacing: { '8xl': '96rem', '9xl': '128rem', }, borderRadius: { '4xl': '2rem', } } } } ``` Learn more about the default theme and how to customize it in the [theme configuration guide](theme). ### Plugins The `plugins` section allows you to register plugins with Tailwind that can be used to generate extra utilities, components, base styles, or custom variants. tailwind.config.js ``` module.exports = { // ... plugins: [ require('@tailwindcss/forms'), require('@tailwindcss/aspect-ratio'), require('@tailwindcss/typography'), require('tailwindcss-children'), ], } ``` Learn more about writing your own plugins in the [plugin authoring guide](plugins). ### Presets The `presets` section allows you to specify your own custom base configuration instead of using Tailwind’s default base configuration. tailwind.config.js ``` module.exports = { // ... presets: [ require('@acmecorp/base-tailwind-config') ], // Project-specific customizations theme: { //... }, } ``` Learn more about presets in the [presets documentation](presets). ### Prefix The `prefix` option allows you to add a custom prefix to all of Tailwind’s generated utility classes. This can be really useful when layering Tailwind on top of existing CSS where there might be naming conflicts. For example, you could add a `tw-` prefix by setting the `prefix` option like so: tailwind.config.js ``` module.exports = { prefix: 'tw-', } ``` Now every class will be generated with the configured prefix: ``` .tw-text-left { text-align: left; } .tw-text-center { text-align: center; } .tw-text-right { text-align: right; } /* etc. */ ``` It’s important to understand that this prefix is added *after* any variant modifiers. That means that classes with responsive or state modifiers like `sm:` or `hover:` will still have the responsive or state modifier *first*, with your custom prefix appearing after the colon: ``` <div class="tw-text-lg md:tw-text-xl tw-bg-red-500 hover:tw-bg-blue-500"> <!-- --> </div> ``` The dash modifier for negative values should be added before your prefix, so `-mt-8` would become `-tw-mt-8` if you’ve configured `tw-` as your prefix: ``` <div class="-tw-mt-8"> <!-- --> </div> ``` Prefixes are only added to classes generated by Tailwind; **no prefix will be added to your own custom classes.** That means if you add your own custom utility like this: ``` @layer utilities { .bg-brand-gradient { /* ... */ } } ``` …the generated variants will not have your configured prefix: ``` .bg-brand-gradient { /* ... */ } .hover\:bg-brand-gradient:hover { /* ... */ } ``` If you’d like to prefix your own utilities as well, just add the prefix to the class definition: ``` @layer utilities { .tw-bg-brand-gradient { /* ... */ } } ``` ### Important The `important` option lets you control whether or not Tailwind’s utilities should be marked with `!important`. This can be really useful when using Tailwind with existing CSS that has high specificity selectors. To generate utilities as `!important`, set the `important` key in your configuration options to `true`: tailwind.config.js ``` module.exports = { important: true, } ``` Now all of Tailwind’s utility classes will be generated as `!important`: ``` .leading-none { line-height: 1 !important; } .leading-tight { line-height: 1.25 !important; } .leading-snug { line-height: 1.375 !important; } /* etc. */ ``` This also applies to any custom utilities you define in your CSS using the `@layer utilities` directive: ``` /* Input */ @layer utilities { .bg-brand-gradient { background-image: linear-gradient(#3490dc, #6574cd); } } /* Output */ .bg-brand-gradient { background-image: linear-gradient(#3490dc, #6574cd) !important; } ``` #### Selector strategy Setting `important` to `true` can introduce some issues when incorporating third-party JS libraries that add inline styles to your elements. In those cases, Tailwind’s `!important` utilities defeat the inline styles, which can break your intended design. To get around this, you can set `important` to an ID selector like `#app` instead: tailwind.config.js ``` module.exports = { // ... important: '#app', } ``` This configuration will prefix all of your utilities with the given selector, effectively increasing their specificity without actually making them `!important`. After you specify the `important` selector, you’ll need to ensure that the root element of your site matches it. Using the example above, we would need to set our root element’s `id` attribute to `app` in order for styles to work properly. After your configuration is all set up and your root element matches the selector in your Tailwind config, all of Tailwind’s utilities will have a high enough specificity to defeat other classes used in your project, **without** interfering with inline styles: ``` <html> <!-- ... --> <style> .high-specificity .nested .selector { color: blue; } </style> <body id="app"> <div class="high-specificity"> <div class="nested"> <!-- Will be red-500 --> <div class="selector text-red-500"><!-- ... --></div> </div> </div <!-- Will be #bada55 --> <div class="text-red-500" style="color: #bada55;"><!-- ... --></div> </body> </html> ``` When using the selector strategy, be sure that the template file that includes your root selector is included in your [content configuration](https://tailwindcss.com/docs/optimizing-for-production#basic-usage), otherwise all of your CSS will be removed when building for production. #### Important modifier Alternatively, you can make any utility important by adding a `!` character to the beginning: ``` <p class="font-bold !font-medium"> This will be medium even though bold comes later in the CSS. </p> ``` The `!` always goes at the beginning of the utility name, after any variants, but before any prefix: ``` <div class="sm:hover:!tw-font-bold"> ``` This can be useful in rare situations where you need to increase specificity because you’re at war with some styles you don’t control. ### Separator The `separator` option lets you customize which character should be used to separate modifiers (screen sizes, `hover`, `focus`, etc.) from utility names (`text-center`, `items-end`, etc.). We use a colon by default (`:`), but it can be useful to change this if you’re using a templating language like [Pug](https://pugjs.org) that doesn’t support special characters in class names. tailwind.config.js ``` module.exports = { separator: '_', } ``` ### Core Plugins The `corePlugins` section lets you completely disable classes that Tailwind would normally generate by default if you don’t need them for your project. To disable specific core plugins, provide an object for `corePlugins` that sets those plugins to `false`: tailwind.config.js ``` module.exports = { corePlugins: { float: false, objectFit: false, objectPosition: false, } } ``` If you’d like to safelist which core plugins should be enabled, provide an array that includes a list of the core plugins you’d like to use: tailwind.config.js ``` module.exports = { corePlugins: [ 'margin', 'padding', 'backgroundColor', // ... ] } ``` If you’d like to disable all of Tailwind’s core plugins and simply use Tailwind as a tool for processing your own custom plugins, provide an empty array: tailwind.config.js ``` module.exports = { corePlugins: [] } ``` Here’s a list of every core plugin for reference: | Core Plugin | Description | | --- | --- | | `accentColor` | The `accent-color` utilities like `accent-green-800` | | `accessibility` | The `sr-only` and `not-sr-only` utilities | | `alignContent` | The `align-content` utilities like `content-between` | | `alignItems` | The `align-items` utilities like `items-center` | | `alignSelf` | The `align-self` utilities like `self-end` | | `animation` | The `animation` utilities like `animate-ping` | | `appearance` | The `appearance` utilities like `appearance-none` | | `aspectRatio` | The `aspect-ratio` utilities like `aspect-square` | | `backdropBlur` | The `backdrop-blur` utilities like `backdrop-blur-md` | | `backdropBrightness` | The `backdrop-brightness` utilities like `backdrop-brightness-100` | | `backdropContrast` | The `backdrop-contrast` utilities like `backdrop-contrast-100` | | `backdropFilter` | The `backdrop-filter` utilities like `backdrop-filter` | | `backdropGrayscale` | The `backdrop-grayscale` utilities like `backdrop-grayscale-0` | | `backdropHueRotate` | The `backdrop-hue-rotate` utilities like `backdrop-hue-rotate-30` | | `backdropInvert` | The `backdrop-invert` utilities like `backdrop-invert-0` | | `backdropOpacity` | The `backdrop-opacity` utilities like `backdrop-opacity-50` | | `backdropSaturate` | The `backdrop-saturate` utilities like `backdrop-saturate-100` | | `backdropSepia` | The `backdrop-sepia` utilities like `backdrop-sepia-0` | | `backgroundAttachment` | The `background-attachment` utilities like `bg-local` | | `backgroundBlendMode` | The `background-blend-mode` utilities like `bg-blend-color-burn` | | `backgroundClip` | The `background-clip` utilities like `bg-clip-padding` | | `backgroundColor` | The `background-color` utilities like `bg-green-800` | | `backgroundImage` | The `background-image` utilities like `bg-gradient-to-br` | | `backgroundOpacity` | The `background-color` opacity utilities like `bg-opacity-25` | | `backgroundOrigin` | The `background-origin` utilities like `bg-origin-padding` | | `backgroundPosition` | The `background-position` utilities like `bg-left-top` | | `backgroundRepeat` | The `background-repeat` utilities like `bg-repeat-x` | | `backgroundSize` | The `background-size` utilities like `bg-cover` | | `blur` | The `blur` utilities like `blur-md` | | `borderCollapse` | The `border-collapse` utilities like `border-collapse` | | `borderColor` | The `border-color` utilities like `border-e-green-800` | | `borderOpacity` | The `border-color` opacity utilities like `border-opacity-25` | | `borderRadius` | The `border-radius` utilities like `rounded-ss-lg` | | `borderSpacing` | The `border-spacing` utilities like `border-spacing-x-28` | | `borderStyle` | The `border-style` utilities like `border-dotted` | | `borderWidth` | The `border-width` utilities like `border-e-4` | | `boxDecorationBreak` | The `box-decoration-break` utilities like `decoration-clone` | | `boxShadow` | The `box-shadow` utilities like `shadow-lg` | | `boxShadowColor` | The `box-shadow-color` utilities like `shadow-green-800` | | `boxSizing` | The `box-sizing` utilities like `box-border` | | `breakAfter` | The `break-after` utilities like `break-after-avoid-page` | | `breakBefore` | The `break-before` utilities like `break-before-avoid-page` | | `breakInside` | The `break-inside` utilities like `break-inside-avoid` | | `brightness` | The `brightness` utilities like `brightness-100` | | `captionSide` | The `caption-side` utilities like `caption-top` | | `caretColor` | The `caret-color` utilities like `caret-green-800` | | `clear` | The `clear` utilities like `clear-right` | | `columns` | The `columns` utilities like `columns-auto` | | `container` | The `container` component | | `content` | The `content` utilities like `content-none` | | `contrast` | The `contrast` utilities like `contrast-100` | | `cursor` | The `cursor` utilities like `cursor-grab` | | `display` | The `display` utilities like `table-column-group` | | `divideColor` | The between elements `border-color` utilities like `divide-slate-500` | | `divideOpacity` | The `divide-opacity` utilities like `divide-opacity-50` | | `divideStyle` | The `divide-style` utilities like `divide-dotted` | | `divideWidth` | The between elements `border-width` utilities like `divide-x-2` | | `dropShadow` | The `drop-shadow` utilities like `drop-shadow-lg` | | `fill` | The `fill` utilities like `fill-green-700` | | `filter` | The `filter` utilities like `filter` | | `flex` | The `flex` utilities like `flex-auto` | | `flexBasis` | The `flex-basis` utilities like `basis-px` | | `flexDirection` | The `flex-direction` utilities like `flex-row-reverse` | | `flexGrow` | The `flex-grow` utilities like `flex-grow` | | `flexShrink` | The `flex-shrink` utilities like `flex-shrink` | | `flexWrap` | The `flex-wrap` utilities like `flex-wrap-reverse` | | `float` | The `float` utilities like `float-left` | | `fontFamily` | The `font-family` utilities like `font-serif` | | `fontSize` | The `font-size` utilities like `text-3xl` | | `fontSmoothing` | The `font-smoothing` utilities like `antialiased` | | `fontStyle` | The `font-style` utilities like `italic` | | `fontVariantNumeric` | The `font-variant-numeric` utilities like `oldstyle-nums` | | `fontWeight` | The `font-weight` utilities like `font-medium` | | `gap` | The `gap` utilities like `gap-x-28` | | `gradientColorStops` | The `gradient-color-stops` utilities like `via-emerald-700` | | `grayscale` | The `grayscale` utilities like `grayscale-0` | | `gridAutoColumns` | The `grid-auto-columns` utilities like `auto-cols-min` | | `gridAutoFlow` | The `grid-auto-flow` utilities like `grid-flow-dense` | | `gridAutoRows` | The `grid-auto-rows` utilities like `auto-rows-min` | | `gridColumn` | The `grid-column` utilities like `col-span-6` | | `gridColumnEnd` | The `grid-column-end` utilities like `col-end-7` | | `gridColumnStart` | The `grid-column-start` utilities like `col-start-7` | | `gridRow` | The `grid-row` utilities like `row-span-3` | | `gridRowEnd` | The `grid-row-end` utilities like `row-end-4` | | `gridRowStart` | The `grid-row-start` utilities like `row-start-4` | | `gridTemplateColumns` | The `grid-template-columns` utilities like `grid-cols-7` | | `gridTemplateRows` | The `grid-template-rows` utilities like `grid-rows-4` | | `height` | The `height` utilities like `h-72` | | `hueRotate` | The `hue-rotate` utilities like `hue-rotate-30` | | `hyphens` | The `hyphens` utilities like `hyphens-manual` | | `inset` | The `inset` utilities like `end-44` | | `invert` | The `invert` utilities like `invert-0` | | `isolation` | The `isolation` utilities like `isolate` | | `justifyContent` | The `justify-content` utilities like `justify-center` | | `justifyItems` | The `justify-items` utilities like `justify-items-end` | | `justifySelf` | The `justify-self` utilities like `justify-self-end` | | `letterSpacing` | The `letter-spacing` utilities like `tracking-normal` | | `lineClamp` | The `line-clamp` utilities like `line-clamp-4` | | `lineHeight` | The `line-height` utilities like `leading-9` | | `listStyleImage` | The `list-style-image` utilities like `list-image-none` | | `listStylePosition` | The `list-style-position` utilities like `list-inside` | | `listStyleType` | The `list-style-type` utilities like `list-disc` | | `margin` | The `margin` utilities like `me-28` | | `maxHeight` | The `max-height` utilities like `max-h-40` | | `maxWidth` | The `max-width` utilities like `max-w-6xl` | | `minHeight` | The `min-height` utilities like `min-h-screen` | | `minWidth` | The `min-width` utilities like `min-w-min` | | `mixBlendMode` | The `mix-blend-mode` utilities like `mix-blend-hard-light` | | `objectFit` | The `object-fit` utilities like `object-fill` | | `objectPosition` | The `object-position` utilities like `object-left-top` | | `opacity` | The `opacity` utilities like `opacity-50` | | `order` | The `order` utilities like `order-8` | | `outlineColor` | The `outline-color` utilities like `outline-green-800` | | `outlineOffset` | The `outline-offset` utilities like `outline-offset-2` | | `outlineStyle` | The `outline-style` utilities like `outline-dashed` | | `outlineWidth` | The `outline-width` utilities like `outline-2` | | `overflow` | The `overflow` utilities like `overflow-x-hidden` | | `overscrollBehavior` | The `overscroll-behavior` utilities like `overscroll-y-contain` | | `padding` | The `padding` utilities like `pe-28` | | `placeContent` | The `place-content` utilities like `place-content-between` | | `placeItems` | The `place-items` utilities like `place-items-center` | | `placeSelf` | The `place-self` utilities like `place-self-end` | | `placeholderColor` | The placeholder `color` utilities like `placeholder-red-600` | | `placeholderOpacity` | The placeholder `color` opacity utilities like `placeholder-opacity-25` | | `pointerEvents` | The `pointer-events` utilities like `pointer-events-none` | | `position` | The `position` utilities like `absolute` | | `preflight` | Tailwind's base/reset styles | | `resize` | The `resize` utilities like `resize-y` | | `ringColor` | The `ring-color` utilities like `ring-green-800` | | `ringOffsetColor` | The `ring-offset-color` utilities like `ring-offset-green-800` | | `ringOffsetWidth` | The `ring-offset-width` utilities like `ring-offset-2` | | `ringOpacity` | The `ring-opacity` utilities like `ring-opacity-50` | | `ringWidth` | The `ring-width` utilities like `ring-4` | | `rotate` | The `rotate` utilities like `rotate-6` | | `saturate` | The `saturate` utilities like `saturate-100` | | `scale` | The `scale` utilities like `scale-x-95` | | `scrollBehavior` | The `scroll-behavior` utilities like `scroll-auto` | | `scrollMargin` | The `scroll-margin` utilities like `scroll-me-28` | | `scrollPadding` | The `scroll-padding` utilities like `scroll-pe-28` | | `scrollSnapAlign` | The `scroll-snap-align` utilities like `snap-end` | | `scrollSnapStop` | The `scroll-snap-stop` utilities like `snap-normal` | | `scrollSnapType` | The `scroll-snap-type` utilities like `snap-y` | | `sepia` | The `sepia` utilities like `sepia-0` | | `skew` | The `skew` utilities like `skew-x-12` | | `space` | The "space-between" utilities like `space-x-4` | | `stroke` | The `stroke` utilities like `stroke-green-700` | | `strokeWidth` | The `stroke-width` utilities like `stroke-1` | | `tableLayout` | The `table-layout` utilities like `table-auto` | | `textAlign` | The `text-align` utilities like `text-right` | | `textColor` | The `text-color` utilities like `text-green-800` | | `textDecoration` | The `text-decoration` utilities like `overline` | | `textDecorationColor` | The `text-decoration-color` utilities like `decoration-green-800` | | `textDecorationStyle` | The `text-decoration-style` utilities like `decoration-dotted` | | `textDecorationThickness` | The `text-decoration-thickness` utilities like `decoration-4` | | `textIndent` | The `text-indent` utilities like `indent-28` | | `textOpacity` | The `text-opacity` utilities like `text-opacity-50` | | `textOverflow` | The `text-overflow` utilities like `overflow-ellipsis` | | `textTransform` | The `text-transform` utilities like `lowercase` | | `textUnderlineOffset` | The `text-underline-offset` utilities like `underline-offset-2` | | `touchAction` | The `touch-action` utilities like `touch-pan-right` | | `transform` | The `transform` utility (for enabling transform features) | | `transformOrigin` | The `transform-origin` utilities like `origin-bottom-right` | | `transitionDelay` | The `transition-delay` utilities like `delay-200` | | `transitionDuration` | The `transition-duration` utilities like `duration-200` | | `transitionProperty` | The `transition-property` utilities like `transition-colors` | | `transitionTimingFunction` | The `transition-timing-function` utilities like `ease-in` | | `translate` | The `translate` utilities like `translate-x-full` | | `userSelect` | The `user-select` utilities like `select-text` | | `verticalAlign` | The `vertical-align` utilities like `align-bottom` | | `visibility` | The `visibility` utilities like `invisible` | | `whitespace` | The `whitespace` utilities like `whitespace-pre` | | `width` | The `width` utilities like `w-1.5` | | `willChange` | The `will-change` utilities like `will-change-scroll` | | `wordBreak` | The `word-break` utilities like `break-words` | | `zIndex` | The `z-index` utilities like `z-30` | Using multiple configurations ----------------------------- For projects that need to generate multiple CSS files using different Tailwind configurations, use the `@config` directive to specify which config file should be used for each CSS entry point: Learn more about the `@config` directive in the [Functions & Directives](functions-and-directives#config) documentation. Referencing in JavaScript ------------------------- It can often be useful to reference your configuration values in your own client-side JavaScript — for example to access some of your theme values when dynamically applying inline styles in a React or Vue component. To make this easy, Tailwind provides a `resolveConfig` helper you can use to generate a fully merged version of your configuration object: ``` import resolveConfig from 'tailwindcss/resolveConfig' import tailwindConfig from './tailwind.config.js' const fullConfig = resolveConfig(tailwindConfig) fullConfig.theme.width[4] // => '1rem' fullConfig.theme.screens.md // => '768px' fullConfig.theme.boxShadow['2xl'] // => '0 25px 50px -12px rgba(0, 0, 0, 0.25)' ``` Note that this will transitively pull in a lot of our build-time dependencies, resulting in bigger client-side bundle size. To avoid this, we recommend using a tool like [babel-plugin-preval](https://github.com/kentcdodds/babel-plugin-preval) to generate a static version of your configuration at build-time. TypeScript types ---------------- We ship first-party TypeScript types for the `tailwind.config.js` file which give you all sorts of useful IDE support, and makes it a lot easier to make changes to your configuration without referencing the documentation quite as much. Configuration files generated with Tailwind CLI include the necessary type annotation by default, but to configure TypeScript types manually, just add the type annotation above your configuration object: tailwind.config.js ``` /** @type {import('tailwindcss').Config} */ module.exports = { content: [ // ... ], theme: { extend: {}, }, plugins: [], } ``` © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/configurationContent Configuration ===================== Configuring the content sources for your project. The `content` section of your `tailwind.config.js` file is where you configure the paths to all of your HTML templates, JavaScript components, and any other source files that contain Tailwind class names. tailwind.config.js ``` module.exports = { content: [ './pages/**/*.{html,js}', './components/**/*.{html,js}', ], // ... } ``` This guide covers everything you need to know to make sure Tailwind generates all of the CSS needed for your project. Configuring source paths ------------------------ Tailwind CSS works by scanning all of your HTML, JavaScript components, and any other template files for class names, then generating all of the corresponding CSS for those styles. In order for Tailwind to generate all of the CSS you need, it needs to know about every single file in your project that contains any Tailwind class names. Configure the paths to all of your content files in the `content` section of your configuration file: tailwind.config.js ``` module.exports = { content: [ './pages/**/*.{html,js}', './components/**/*.{html,js}' ], // ... } ``` Paths are configured as [glob patterns](https://en.wikipedia.org/wiki/Glob_(programming)), making it easy to match all of the content files in your project without a ton of configuration: * Use `*` to match anything except slashes and hidden files * Use `**` to match zero or more directories * Use comma separate values between `{}` to match against a list of options Tailwind uses the [fast-glob](https://github.com/mrmlnc/fast-glob) library under-the-hood — check out their documentation for other supported pattern features. Paths are relative to your project root, *not* your `tailwind.config.js` file, so if your `tailwind.config.js` file is in a custom location, you should still write your paths relative to the root of your project. ### Pattern recommendations For the best performance and to avoid false positives, be as specific as possible with your content configuration. If you use a really broad pattern like this one, Tailwind will even scan `node_modules` for content which is probably not what you want: Don’t use extremely broad patterns tailwind.config.js ``` module.exports = { content: [ './**/*.{html,js}', ], // ... } ``` If you have any files you need to scan that are at the root of your project (often an `index.html` file), list that file independently so your other patterns can be more specific: Be specific with your content patterns tailwind.config.js ``` module.exports = { content: [ './components/**/*.{html,js}', './pages/**/*.{html,js}', './index.html', ], // ... } ``` Some frameworks hide their main HTML entry point in a different place than the rest of your templates (often `public/index.html`), so if you are adding Tailwind classes to that file make sure it’s included in your configuration as well: Remember to include your HTML entry point if applicable tailwind.config.js ``` module.exports = { content: [ './public/index.html', './src/**/*.{html,js}', ], // ... } ``` If you have any JavaScript files that manipulate your HTML to add classes, make sure you include those as well: tailwind.config.js ``` module.exports = { content: [ // ... './src/**/*.js', ], // ... } ``` src/spaghetti.js ``` // ... menuButton.addEventListener('click', function () { let classList = document.getElementById('nav').classList classList.toggle('hidden') classList.toggle('block') }) // ... ``` It’s also important that you don’t scan any CSS files — configure Tailwind to scan your *templates* where your class names are being used, never the CSS file that Tailwind is generating. Never include CSS files in your content configuration tailwind.config.js ``` module.exports = { content: [ './src/**/*.css', ], // ... } ``` ### Class detection in-depth The way Tailwind scans your source code for classes is intentionally very simple — we don’t actually parse or execute any of your code in the language it’s written in, we just use regular expressions to extract every string that could possibly be a class name. For example, here’s some HTML with every potential class name string individually highlighted: ``` <div class="md:flex"> <div class="md:flex-shrink-0"> <img class="rounded-lg md:w-56" src="/img/shopping.jpg" alt="Woman paying for a purchase"> </div> <div class="mt-4 md:mt-0 md:ml-6"> <div class="uppercase tracking-wide text-sm text-indigo-600 font-bold"> Marketing </div> <a href="/get-started" class="block mt-1 text-lg leading-tight font-semibold text-gray-900 hover:underline"> Finding customers for your new business </a> <p class="mt-2 text-gray-600"> Getting a new business off the ground is a lot of hard work. Here are five ideas you can use to find your first customers. </p> </div> </div> ``` We don’t just limit our search to `class="..."` attributes because you could be using classes anywhere, like in some JavaScript for toggling a menu: spaghetti.js ``` <script> menuButton.addEventListener('click', function () { let classList = document.getElementById('nav').classList classList.toggle('hidden') classList.toggle('block') }) </script> ``` By using this very simple approach, Tailwind works extremely reliably with any programming language, like JSX for example: Button.jsx ``` const sizes = { md: 'px-4 py-2 rounded-md text-base', lg: 'px-5 py-3 rounded-lg text-lg', } const colors = { indigo: 'bg-indigo-500 hover:bg-indigo-600 text-white', cyan: 'bg-cyan-600 hover:bg-cyan-700 text-white', } export default function Button({ color, size, children }) { let colorClasses = colors[color] let sizeClasses = sizes[size] return ( <button type="button" className={`font-bold ${sizeClasses} ${colorClasses}`}> {children} </button> ) } ``` ### Dynamic class names The most important implication of how Tailwind extracts class names is that it will only find classes that exist *as complete unbroken strings* in your source files. If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS: Don’t construct class names dynamically ``` <div class="text-{{ error ? 'red' : 'green' }}-600"></div> ``` In the example above, the strings `text-red-600` and `text-green-600` do not exist, so Tailwind will not generate those classes. Instead, make sure any class names you’re using exist in full: Always use complete class names ``` <div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div> ``` If you’re using a component library like React or Vue, this means you shouldn’t use props to dynamically construct classes: Don’t use props to build class names dynamically ``` function Button({ color, children }) { return ( <button className={`bg-${color}-600 hover:bg-${color}-500 ...`}> {children} </button> ) } ``` Instead, map props to complete class names that are statically detectable at build-time: Always map props to static class names ``` function Button({ color, children }) { const colorVariants = { blue: 'bg-blue-600 hover:bg-blue-500', red: 'bg-red-600 hover:bg-red-500', } return ( <button className={`${colorVariants[color]} ...`}> {children} </button> ) } ``` This has the added benefit of letting you map different prop values to different color shades for example: ``` function Button({ color, children }) { const colorVariants = { blue: 'bg-blue-600 hover:bg-blue-500 text-white', red: 'bg-red-500 hover:bg-red-400 text-white', yellow: 'bg-yellow-300 hover:bg-yellow-400 text-black', } return ( <button className={`${colorVariants[color]} ...`}> {children} </button> ) } ``` As long as you always use complete class names in your code, Tailwind will generate all of your CSS perfectly every time. ### Working with third-party libraries If you’re working with any third-party libraries (for example [Select2](https://select2.org/)) and styling that library with your own custom CSS, we recommend writing those styles *without* using Tailwind’s `@layer` feature: main.css ``` @tailwind base; @tailwind components; .select2-dropdown { @apply rounded-b-lg shadow-md; } .select2-search { @apply border border-gray-300 rounded; } .select2-results__group { @apply text-lg font-bold text-gray-900; } /* ... */ @tailwind utilities; ``` This will ensure that Tailwind *always* includes those styles in your CSS, which is a lot easier than configuring Tailwind to scan the source code of a third-party library. If you’ve created your own reusable set of components that are styled with Tailwind and are importing them in multiple projects, make sure to configure Tailwind to scan those components for class names: tailwind.config.js ``` module.exports = { content: [ './components/**/*.{html,js}', './pages/**/*.{html,js}', './node_modules/@my-company/tailwind-components/**/*.js', ], // ... } ``` This will make sure Tailwind generates all of the CSS needed for those components as well. If you’re working in a monorepo with workspaces, you may need to use `require.resolve` to make sure Tailwind can see your content files: tailwind.config.js ``` const path = require('path'); module.exports = { content: [ './components/**/*.{html,js}', './pages/**/*.{html,js}', path.join(path.dirname(require.resolve('@my-company/tailwind-components')), '**/*.js'), ], // ... } ``` ### Using relative paths By default Tailwind resolves non-absolute content paths relative to the current working directory, not the `tailwind.config.js` file. This can lead to unexpected results if you run Tailwind from a different directory. To always resolve paths relative to the `tailwind.config.js` file, use the object notation for your `content` configuration and set the `relative` property to `true`: tailwind.config.js ``` module.exports = { content: { relative: true, files: [ './pages/**/*.{html,js}', './components/**/*.{html,js}', ], }, // ... } ``` This will likely become the default behavior in the next major version of the framework. ### Configuring raw content If for whatever reason you need to configure Tailwind to scan some raw content rather than the contents of a file, use an object with a `raw` key instead of a path: tailwind.config.js ``` module.exports = { content: [ './pages/**/*.{html,js}', './components/**/*.{html,js}', { raw: '<div class="font-bold">', extension: 'html' }, ], // ... } ``` There aren’t many valid use-cases for this — [safelisting](content-configuration#safelisting-classes) is usually what you really want instead. Safelisting classes ------------------- For the smallest file size and best development experience, we highly recommend relying on your `content` configuration to tell Tailwind which classes to generate as much as possible. Safelisting is a last-resort, and should only be used in situations where it’s impossible to scan certain content for class names. These situations are rare, and you should almost never need this feature. If you need to make sure Tailwind generates certain class names that don’t exist in your content files, use the `safelist` option: tailwind.config.js ``` module.exports = { content: [ './pages/**/*.{html,js}', './components/**/*.{html,js}', ], safelist: [ 'bg-red-500', 'text-3xl', 'lg:text-4xl', ] // ... } ``` One example of where this can be useful is if your site displays user-generated content and you want users to be able to use a constrained set of Tailwind classes in their content that might not exist in your own site’s source files. ### Using regular expressions Tailwind supports pattern-based safelisting for situations where you need to safelist a lot of classes: tailwind.config.js ``` module.exports = { content: [ './pages/**/*.{html,js}', './components/**/*.{html,js}', ], safelist: [ 'text-2xl', 'text-3xl', { pattern: /bg-(red|green|blue)-(100|200|300)/, }, ], // ... } ``` Patterns can only match against base utility names like `/bg-red-.+/`, and won’t match if the pattern includes a variant modifier like `/hover:bg-red-.+/`. If you want to force Tailwind to generate variants for any matched classes, include them using the `variants` option: tailwind.config.js ``` module.exports = { content: [ './pages/**/*.{html,js}', './components/**/*.{html,js}', ], safelist: [ 'text-2xl', 'text-3xl', { pattern: /bg-(red|green|blue)-(100|200|300)/, variants: ['lg', 'hover', 'focus', 'lg:hover'], }, ], // ... } ``` ### Discarding classes Since Tailwind uses a very simple approach to detecting class names in your content, you may find that some classes are being generated that you don’t actually need. For example, this HTML would still generate the `container` class, even though that class is not actually being used: ``` <div class="text-lg leading-8 text-gray-600"> Every custom pool we design starts as a used shipping container, and is retrofitted with state of the art technology and finishes to turn it into a beautiful and functional way to entertain your guests all summer long. </div> ``` You may also want to prevent Tailwind from generating certain classes when those classes would conflict with some existing CSS, but you don’t want to go so far as to prefix all of your Tailwind classes. In these situations, you can use the `blocklist` option to tell Tailwind to ignore specific classes that it detects in your content: tailwind.config.js ``` module.exports = { content: [ './pages/**/*.{html,js}', './components/**/*.{html,js}', ], blocklist: [ 'container', 'collapse', ], // ... } ``` The `blocklist` option only affects CSS that would be generated by Tailwind, not custom CSS you’ve authored yourself or are importing from another library. Unlike `safelist`, the `blocklist` option only supports strings, and you cannot block classes using regular expressions. Transforming source files ------------------------- If you’re authoring content in a format that *compiles* to HTML (like Markdown), it often makes sense to compile that content to HTML *before* scanning it for class names. Use the `content.transform` option to transform any content matching a specific file extension before extracting classes: tailwind.config.js ``` const remark = require('remark') module.exports = { content: { files: ['./src/**/*.{html,md}'], transform: { md: (content) => { return remark().process(content) } } }, // ... } ``` When using `content.transform`, you’ll need to provide your source paths using `content.files` instead of as a top-level array under `content`. Customizing extraction logic ---------------------------- Use the `extract` option to override the logic Tailwind uses to detect class names for specific file extensions: tailwind.config.js ``` module.exports = { content: { files: ['./src/**/*.{html,wtf}'], extract: { wtf: (content) => { return content.match(/[^<>"'`\s]*/) } } }, // ... } ``` This is an advanced feature and most users won’t need it — the default extraction logic in Tailwind works extremely well for almost all projects. As with transforming, when using `content.extract`, you’ll need to provide your source paths using `content.files` instead of as a top-level array under `content`. Troubleshooting --------------- ### Classes aren’t generated If Tailwind isn’t generating classes, make sure your `content` configuration is correct and matches all of the right source files. A common mistake is missing a file extension, for example if you’re using `jsx` instead of `js` for your React components: tailwind.config.js ``` module.exports = { content: [ './src/**/*.{html,js}', './src/**/*.{html,js,jsx}' ], // ... } ``` Or creating a new folder mid-project that wasn’t covered originally and forgetting to add it to your configuration: tailwind.config.js ``` module.exports = { content: [ './pages/**/*.{html,js}', './components/**/*.{html,js}', './util/**/*.{html,js}' ], // ... } ``` It could also be that you are trying to use dynamic class names, which won’t work because Tailwind doesn’t actually evaluate your source code and can only detect static unbroken class strings. Don’t construct class names dynamically ``` <div class="text-{{ error ? 'red' : 'green' }}-600"></div> ``` Make sure you always use complete class names in your code: Always use complete class names ``` <div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div> ``` Read our documentation on [dynamic class names](content-configuration#dynamic-class-names) for more details. ### Styles rebuild in an infinite loop If your CSS seems to be rebuilding in an infinite loop, there’s a good chance it’s because your build tool doesn’t support the `glob` option when [registering PostCSS dependencies](https://github.com/postcss/postcss/blob/main/docs/guidelines/runner.md#31-rebuild-when-dependencies-change). Many build tools (such as webpack) don’t support this option, and as a result we can only tell them to watch specific files or *entire directories*. We can’t tell webpack to *only* watch `*.html` files in a directory for example. That means that if building your CSS causes *any* files in those directories to change, a rebuild will be triggered, even if the changed file doesn’t match the extension in your glob. tailwind.config.js ``` module.exports = { content: [ // With some build tools, your CSS will rebuild // any time *any* file in `src` changes. './src/**/*.{html,js}', ], // ... } ``` So if you are watching `src/**/*.html` for changes, but you are writing your CSS output file to `src/css/styles.css`, you will get an infinite rebuild loop using some tools. Ideally we could warn you about this in the console, but many tools support it perfectly fine (including our own CLI tool), and we have no reliable way to detect what build tool you are using. To solve this problem, use more specific paths in your `content` config, making sure to only include directories that won’t change when your CSS builds: tailwind.config.js ``` module.exports = { content: [ './src/**/*.{html,js}', './src/pages/**/*.{html,js}', './src/components/**/*.{html,js}', './src/layouts/**/*.{html,js}', './src/index.html', ], // ... } ``` If necessary, adjust your actual project directory structure to make sure you can target your template files without accidentally catching your CSS file or other build artifacts like manifest files. If you absolutely can’t change your content config or directory structure, your best bet is to compile your CSS separately with a tool that has complete glob support. We recommend using [Tailwind CLI](https://tailwindcss.com/docs/installation), which is a fast, simple, purpose-built tool for compiling your CSS with Tailwind. ### It just isn’t working properly If you are experiencing weird, hard to describe issues with the output, or things just don’t seem like they are working at all, there’s a good chance it’s due to your build tool not supporting PostCSS dependency messages properly *(or at all)*. One known example of this currently is [Stencil](https://github.com/ionic-team/stencil-postcss/issues/38). When you are having these sorts of issues, we recommend using [Tailwind CLI](https://tailwindcss.com/docs/installation) to compile your CSS separately instead of trying to integrate Tailwind into your existing tooling. You can use packages like `npm-run-all` or `concurrently` to compile your CSS alongside your usual development command by adding some scripts to your project like this: ``` // package.json { // ... "scripts": { "start": "concurrently \"npm run start:css\" \"react-scripts start\"", "start:css": "tailwindcss -o src/tailwind.css --watch", "build": "npm run build:css && react-scripts build", "build:css": "NODE_ENV=production tailwindcss -o src/tailwind.css -m", }, } ``` Either way, please be sure to [check for an existing issue](https://github.com/tailwindlabs/tailwindcss/issues) or [open a new one](https://github.com/tailwindlabs/tailwindcss/issues/new/choose) so we can figure out the problem and try to improve compatibility with whatever tool you are using. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/content-configurationTheme Configuration =================== Customizing the default theme for your project. The `theme` section of your `tailwind.config.js` file is where you define your project’s color palette, type scale, fonts, breakpoints, border radius values, and more. tailwind.config.js ``` module.exports = { theme: { screens: { sm: '480px', md: '768px', lg: '976px', xl: '1440px', }, colors: { 'blue': '#1fb6ff', 'purple': '#7e5bef', 'pink': '#ff49db', 'orange': '#ff7849', 'green': '#13ce66', 'yellow': '#ffc82c', 'gray-dark': '#273444', 'gray': '#8492a6', 'gray-light': '#d3dce6', }, fontFamily: { sans: ['Graphik', 'sans-serif'], serif: ['Merriweather', 'serif'], }, extend: { spacing: { '128': '32rem', '144': '36rem', }, borderRadius: { '4xl': '2rem', } } } } ``` We provide a sensible [default theme](https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/config.full.js) with a very generous set of values to get you started, but don’t be afraid to change it or extend it; you’re encouraged to customize it as much as you need to fit the goals of your design. Theme structure --------------- The `theme` object contains keys for `screens`, `colors`, and `spacing`, as well as a key for each customizable [core plugin](configuration#core-plugins). See the [theme configuration reference](theme#configuration-reference) or the [default theme](https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/config.full.js#L7) for a complete list of theme options. ### Screens The `screens` key allows you to customize the responsive breakpoints in your project. tailwind.config.js ``` module.exports = { theme: { screens: { 'sm': '640px', 'md': '768px', 'lg': '1024px', 'xl': '1280px', '2xl': '1536px', } } } ``` To learn more, see the [breakpoint customization documentation](/docs/screens). ### Colors The `colors` key allows you to customize the global color palette for your project. tailwind.config.js ``` module.exports = { theme: { colors: { transparent: 'transparent', black: '#000', white: '#fff', gray: { 100: '#f7fafc', // ... 900: '#1a202c', }, // ... } } } ``` By default, these colors are inherited by all color-related core plugins, like `backgroundColor`, `borderColor`, `textColor`, and others. To learn more, see the [color customization documentation](/docs/customizing-colors). ### Spacing The `spacing` key allows you to customize the global spacing and sizing scale for your project. tailwind.config.js ``` module.exports = { theme: { spacing: { px: '1px', 0: '0', 0.5: '0.125rem', 1: '0.25rem', 1.5: '0.375rem', 2: '0.5rem', 2.5: '0.625rem', 3: '0.75rem', 3.5: '0.875rem', 4: '1rem', 5: '1.25rem', 6: '1.5rem', 7: '1.75rem', 8: '2rem', 9: '2.25rem', 10: '2.5rem', 11: '2.75rem', 12: '3rem', 14: '3.5rem', 16: '4rem', 20: '5rem', 24: '6rem', 28: '7rem', 32: '8rem', 36: '9rem', 40: '10rem', 44: '11rem', 48: '12rem', 52: '13rem', 56: '14rem', 60: '15rem', 64: '16rem', 72: '18rem', 80: '20rem', 96: '24rem', }, } } ``` By default, these values are inherited by the `padding`, `margin`, `width`, `height`, `maxHeight`, `flex-basis`, `gap`, `inset`, `space`, `translate`, `scrollMargin`, `scrollPadding`, and `textIndent` core plugins. To learn more, see the [spacing customization documentation](customizing-spacing). ### Core plugins The rest of the `theme` section is used to configure which values are available for each individual core plugin. For example, the `borderRadius` key lets you customize which border radius utilities will be generated: ``` module.exports = { theme: { borderRadius: { 'none': '0', 'sm': '.125rem', DEFAULT: '.25rem', 'lg': '.5rem', 'full': '9999px', }, } } ``` The keys determine the suffix for the generated classes, and the values determine the value of the actual CSS declaration. The example `borderRadius` configuration above would generate the following CSS classes: ``` .rounded-none { border-radius: 0 } .rounded-sm { border-radius: .125rem } .rounded { border-radius: .25rem } .rounded-lg { border-radius: .5rem } .rounded-full { border-radius: 9999px } ``` You’ll notice that using a key of `DEFAULT` in the theme configuration created the class `rounded` with no suffix. This is a common convention in Tailwind and is supported by all core plugins. To learn more about customizing a specific core plugin, visit the documentation for that plugin. For a complete reference of available theme properties and their default values, [see the default theme configuration](https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/config.full.js). Customizing the default theme ----------------------------- Out of the box, your project will automatically inherit the values from [the default theme configuration](https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/config.full.js). If you would like to customize the default theme, you have a few different options depending on your goals. ### Extending the default theme If you’d like to preserve the default values for a theme option but also add new values, add your extensions under the `extend` key in the `theme` section of your configuration file. For example, if you wanted to add an extra breakpoint but preserve the existing ones, you could extend the `screens` property: tailwind.config.js ``` module.exports = { theme: { extend: { // Adds a new breakpoint in addition to the default breakpoints screens: { '3xl': '1600px', } } } } ``` ### Overriding the default theme To override an option in the default theme, add your overrides directly under the `theme` section of your `tailwind.config.js`: tailwind.config.js ``` module.exports = { theme: { // Replaces all of the default `opacity` values opacity: { '0': '0', '20': '0.2', '40': '0.4', '60': '0.6', '80': '0.8', '100': '1', } } } ``` This will completely replace Tailwind’s default configuration for that key, so in the example above none of the default opacity utilities would be generated. Any keys you **do not** provide will be inherited from the default theme, so in the above example, the default theme configuration for things like colors, spacing, border-radius, background-position, etc. would be preserved. You can of course both override some parts of the default theme and extend other parts of the default theme within the same configuration: tailwind.config.js ``` module.exports = { theme: { opacity: { '0': '0', '20': '0.2', '40': '0.4', '60': '0.6', '80': '0.8', '100': '1', }, extend: { screens: { '3xl': '1600px', } } } } ``` ### Referencing other values If you need to reference another value in your theme, you can do so by providing a closure instead of a static value. The closure will receive an object that includes a `theme()` function that you can use to look up other values in your theme using dot notation. For example, you could generate `background-size` utilities for every value in your spacing scale by referencing `theme('spacing')` in your `backgroundSize` configuration: tailwind.config.js ``` module.exports = { theme: { spacing: { // ... }, backgroundSize: ({ theme }) => ({ auto: 'auto', cover: 'cover', contain: 'contain', ...theme('spacing') }) } } ``` The `theme()` function attempts to find the value you are looking for from the fully merged theme object, so it can reference your own customizations as well as the default theme values. It also works recursively, so as long as there is a static value at the end of the chain it will be able to resolve the value you are looking for. Note that you can only use this kind of closure with top-level theme keys, not the keys inside of each section. You can’t use functions for individual values tailwind.config.js ``` module.exports = { theme: { fill: { gray: ({ theme }) => theme('colors.gray') } } } ``` Use functions for top-level theme keys tailwind.config.js ``` module.exports = { theme: { fill: ({ theme }) => ({ gray: theme('colors.gray') }) } } ``` ### Referencing the default theme If you’d like to reference a value in the default theme for any reason, you can import it from `tailwindcss/defaultTheme`. One example of where this is useful is if you’d like to add a font family to one of Tailwind’s default font stacks: tailwind.config.js ``` const defaultTheme = require('tailwindcss/defaultTheme') module.exports = { theme: { extend: { fontFamily: { sans: [ 'Lato', ...defaultTheme.fontFamily.sans, ] } } } } ``` ### Disabling an entire core plugin If you don’t want to generate any classes for a certain core plugin, it’s better to set that plugin to false in your `corePlugins` configuration than to provide an empty object for that key in your `theme` configuration. Don’t assign an empty object in your theme configuration tailwind.config.js ``` module.exports = { theme: { opacity: {}, } } ``` Do disable the plugin in your corePlugins configuration tailwind.config.js ``` module.exports = { corePlugins: { opacity: false, } } ``` The end result is the same, but since many core plugins expose no configuration they can only be disabled using `corePlugins` anyways, so it’s better to be consistent. Configuration reference ----------------------- Except for `screens`, `colors`, and `spacing`, all of the keys in the `theme` object map to one of Tailwind’s [core plugins](configuration#core-plugins). Since many plugins are responsible for CSS properties that only accept a static set of values (like `float` for example), note that not every plugin has a corresponding key in the `theme` object. All of these keys are also available under the `theme.extend` key to enable [extending the default theme](theme#extending-the-default-theme). | Key | Description | | --- | --- | | `accentColor` | Values for the `accent-color` property | | `animation` | Values for the `animation` property | | `aria` | Values for the `aria` property | | `aspectRatio` | Values for the `aspect-ratio` property | | `backdropBlur` | Values for the `backdropBlur` plugin | | `backdropBrightness` | Values for the `backdropBrightness` plugin | | `backdropContrast` | Values for the `backdropContrast` plugin | | `backdropGrayscale` | Values for the `backdropGrayscale` plugin | | `backdropHueRotate` | Values for the `backdropHueRotate` plugin | | `backdropInvert` | Values for the `backdropInvert` plugin | | `backdropOpacity` | Values for the `backdropOpacity` plugin | | `backdropSaturate` | Values for the `backdropSaturate` plugin | | `backdropSepia` | Values for the `backdropSepia` plugin | | `backgroundColor` | Values for the `background-color` property | | `backgroundImage` | Values for the `background-image` property | | `backgroundOpacity` | Values for the `background-opacity` property | | `backgroundPosition` | Values for the `background-position` property | | `backgroundSize` | Values for the `background-size` property | | `blur` | Values for the `blur` plugin | | `borderColor` | Values for the `border-color` property | | `borderOpacity` | Values for the `borderOpacity` plugin | | `borderRadius` | Values for the `border-radius` property | | `borderSpacing` | Values for the `border-spacing` property | | `borderWidth` | Values for the `borderWidth` plugin | | `boxShadow` | Values for the `box-shadow` property | | `boxShadowColor` | Values for the `boxShadowColor` plugin | | `brightness` | Values for the `brightness` plugin | | `caretColor` | Values for the `caret-color` property | | `colors` | Your project's color palette | | `columns` | Values for the `columns` property | | `container` | Configuration for the `container` plugin | | `content` | Values for the `content` property | | `contrast` | Values for the `contrast` plugin | | `cursor` | Values for the `cursor` property | | `divideColor` | Values for the `divideColor` plugin | | `divideOpacity` | Values for the `divideOpacity` plugin | | `divideWidth` | Values for the `divideWidth` plugin | | `dropShadow` | Values for the `dropShadow` plugin | | `fill` | Values for the `fill` plugin | | `flex` | Values for the `flex` property | | `flexBasis` | Values for the `flex-basis` property | | `flexGrow` | Values for the `flex-grow` property | | `flexShrink` | Values for the `flex-shrink` property | | `fontFamily` | Values for the `font-family` property | | `fontSize` | Values for the `font-size` property | | `fontWeight` | Values for the `font-weight` property | | `gap` | Values for the `gap` property | | `gradientColorStops` | Values for the `gradientColorStops` plugin | | `gradientColorStopPositions` | Values for the `gradient-color-stop-positions` property | | `grayscale` | Values for the `grayscale` plugin | | `gridAutoColumns` | Values for the `grid-auto-columns` property | | `gridAutoRows` | Values for the `grid-auto-rows` property | | `gridColumn` | Values for the `grid-column` property | | `gridColumnEnd` | Values for the `grid-column-end` property | | `gridColumnStart` | Values for the `grid-column-start` property | | `gridRow` | Values for the `grid-row` property | | `gridRowEnd` | Values for the `grid-row-end` property | | `gridRowStart` | Values for the `grid-row-start` property | | `gridTemplateColumns` | Values for the `grid-template-columns` property | | `gridTemplateRows` | Values for the `grid-template-rows` property | | `height` | Values for the `height` property | | `hueRotate` | Values for the `hueRotate` plugin | | `inset` | Values for the `top`, `right`, `bottom`, and `left` properties | | `invert` | Values for the `invert` plugin | | `keyframes` | Keyframe values used in the `animation` plugin | | `letterSpacing` | Values for the `letter-spacing` property | | `lineHeight` | Values for the `line-height` property | | `listStyleType` | Values for the `list-style-type` property | | `listStyleImage` | Values for the `list-style-image` property | | `margin` | Values for the `margin` property | | `lineClamp` | Values for the `line-clamp` property | | `maxHeight` | Values for the `max-height` property | | `maxWidth` | Values for the `max-width` property | | `minHeight` | Values for the `min-height` property | | `minWidth` | Values for the `min-width` property | | `objectPosition` | Values for the `object-position` property | | `opacity` | Values for the `opacity` property | | `order` | Values for the `order` property | | `outlineColor` | Values for the `outline-color` property | | `outlineOffset` | Values for the `outline-offset` property | | `outlineWidth` | Values for the `outline-width` property | | `padding` | Values for the `padding` property | | `placeholderColor` | Values for the `placeholderColor` plugin | | `placeholderOpacity` | Values for the `placeholderOpacity` plugin | | `ringColor` | Values for the `ringColor` plugin | | `ringOffsetColor` | Values for the `ringOffsetColor` plugin | | `ringOffsetWidth` | Values for the `ringOffsetWidth` plugin | | `ringOpacity` | Values for the `ringOpacity` plugin | | `ringWidth` | Values for the `ringWidth` plugin | | `rotate` | Values for the `rotate` plugin | | `saturate` | Values for the `saturate` plugin | | `scale` | Values for the `scale` plugin | | `screens` | Your project's responsive breakpoints | | `scrollMargin` | Values for the `scroll-margin` property | | `scrollPadding` | Values for the `scroll-padding` property | | `sepia` | Values for the `sepia` plugin | | `skew` | Values for the `skew` plugin | | `space` | Values for the `space` plugin | | `spacing` | Your project's spacing scale | | `stroke` | Values for the `stroke` property | | `strokeWidth` | Values for the `stroke-width` property | | `supports` | Values for the `supports` property | | `data` | Values for the `data` property | | `textColor` | Values for the `text-color` property | | `textDecorationColor` | Values for the `text-decoration-color` property | | `textDecorationThickness` | Values for the `text-decoration-thickness` property | | `textIndent` | Values for the `text-indent` property | | `textOpacity` | Values for the `textOpacity` plugin | | `textUnderlineOffset` | Values for the `text-underline-offset` property | | `transformOrigin` | Values for the `transform-origin` property | | `transitionDelay` | Values for the `transition-delay` property | | `transitionDuration` | Values for the `transition-duration` property | | `transitionProperty` | Values for the `transition-property` property | | `transitionTimingFunction` | Values for the `transition-timing-function` property | | `translate` | Values for the `translate` plugin | | `width` | Values for the `width` property | | `willChange` | Values for the `will-change` property | | `zIndex` | Values for the `z-index` property | © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/themeCustomizing Screens =================== Customizing the default breakpoints for your project. Configuring custom screens -------------------------- You define your project’s breakpoints in the `theme.screens` section of your `tailwind.config.js` file. The keys become your [responsive modifiers](responsive-design) (like `md:text-center`), and the values are the `min-width` where that breakpoint should start. The default breakpoints are inspired by common device resolutions: tailwind.config.js ``` module.exports = { theme: { screens: { 'sm': '640px', // => @media (min-width: 640px) { ... } 'md': '768px', // => @media (min-width: 768px) { ... } 'lg': '1024px', // => @media (min-width: 1024px) { ... } 'xl': '1280px', // => @media (min-width: 1280px) { ... } '2xl': '1536px', // => @media (min-width: 1536px) { ... } } } } ``` Feel free to have as few or as many screens as you want, naming them in whatever way you’d prefer for your project. ### Overriding the defaults To completely replace the default breakpoints, add your custom `screens` configuration directly under the `theme` key: tailwind.config.js ``` module.exports = { theme: { screens: { 'sm': '576px', // => @media (min-width: 576px) { ... } 'md': '960px', // => @media (min-width: 960px) { ... } 'lg': '1440px', // => @media (min-width: 1440px) { ... } }, } } ``` Any default screens you haven’t overridden (such as `xl` using the above example) will be removed and will not be available as screen modifiers. ### Overriding a single screen To override a single screen size (like `lg`), add your custom `screens` value under the `theme.extend` key: tailwind.config.js ``` module.exports = { theme: { extend: { screens: { 'lg': '992px', // => @media (min-width: 992px) { ... } }, }, }, } ``` This will replace the default `screens` value with the same name, without changing the order of your breakpoints. ### Adding larger breakpoints The easiest way to add an additional larger breakpoint is using the `extend` key: tailwind.config.js ``` module.exports = { theme: { extend: { screens: { '3xl': '1600px', }, }, }, plugins: [], } ``` This will add your custom screen to the end of the default breakpoint list. ### Adding smaller breakpoints If you want to add an additional small breakpoint, you can’t use `extend` because the small breakpoint would be added to the end of the breakpoint list, and breakpoints need to be sorted from smallest to largest in order to work as expected with a min-width breakpoint system. Instead, override the entire `screens` key, re-specifying the default breakpoints: tailwind.config.js ``` const defaultTheme = require('tailwindcss/defaultTheme') module.exports = { theme: { screens: { 'xs': '475px', ...defaultTheme.screens, }, }, plugins: [], } ``` We expose the default theme at `tailwindcss/defaultTheme` so you don’t have to maintain the list of default breakpoints yourself. ### Using custom screen names You can name your custom screens whatever you like, and are not limited to following the `sm`/`md`/`lg`/`xl`/`2xl` convention that Tailwind uses by default. tailwind.config.js ``` module.exports = { theme: { screens: { 'tablet': '640px', // => @media (min-width: 640px) { ... } 'laptop': '1024px', // => @media (min-width: 1024px) { ... } 'desktop': '1280px', // => @media (min-width: 1280px) { ... } }, } } ``` Your responsive modifiers will reflect these custom screen names, so using them in your HTML would now look like this: ``` <div class="grid grid-cols-1 tablet:grid-cols-2 laptop:grid-cols-3 desktop:grid-cols-4"> <!-- ... --> </div> ``` Advanced configuration ---------------------- By default, breakpoints are min-width to encourage a [mobile-first](responsive-design#working-mobile-first) workflow. If you need more control over your media queries, you can also define them using an object syntax that lets you specify explicit min-width and max-width values. ### Max-width breakpoints If you want to work with max-width breakpoints instead of min-width, you can specify your screens as objects with a `max` key: tailwind.config.js ``` module.exports = { theme: { screens: { '2xl': {'max': '1535px'}, // => @media (max-width: 1535px) { ... } 'xl': {'max': '1279px'}, // => @media (max-width: 1279px) { ... } 'lg': {'max': '1023px'}, // => @media (max-width: 1023px) { ... } 'md': {'max': '767px'}, // => @media (max-width: 767px) { ... } 'sm': {'max': '639px'}, // => @media (max-width: 639px) { ... } } } } ``` Make sure to list max-width breakpoints in descending order so that they override each other as expected. ### Fixed-range breakpoints If you want your breakpoints to specify both a `min-width` and a `max-width`, use the `min` and `max` keys together: tailwind.config.js ``` module.exports = { theme: { screens: { 'sm': {'min': '640px', 'max': '767px'}, // => @media (min-width: 640px and max-width: 767px) { ... } 'md': {'min': '768px', 'max': '1023px'}, // => @media (min-width: 768px and max-width: 1023px) { ... } 'lg': {'min': '1024px', 'max': '1279px'}, // => @media (min-width: 1024px and max-width: 1279px) { ... } 'xl': {'min': '1280px', 'max': '1535px'}, // => @media (min-width: 1280px and max-width: 1535px) { ... } '2xl': {'min': '1536px'}, // => @media (min-width: 1536px) { ... } }, } } ``` Unlike regular min-width or max-width breakpoints, breakpoints defined this way will only take effect when the viewport size is explicitly within the defined range. ``` <div class="md:text-center"> This text will be centered on medium screens, but revert back to the default (left-aligned) at all other screen sizes. </div> ``` ### Multi-range breakpoints Sometimes it can be useful to have a single breakpoint definition apply in multiple ranges. For example, say you have a sidebar and want your breakpoints to be based on the content-area width rather than the entire viewport. You can simulate this by having one of your breakpoints fall back to a smaller breakpoint when the sidebar becomes visible and shrinks the content area: tailwind.config.js ``` module.exports = { theme: { screens: { 'sm': '500px', 'md': [ // Sidebar appears at 768px, so revert to `sm:` styles between 768px // and 868px, after which the main content area is wide enough again to // apply the `md:` styles. {'min': '668px', 'max': '767px'}, {'min': '868px'} ], 'lg': '1100px', 'xl': '1400px', } } } ``` ### Custom media queries If you want full control over the generated media query, use the `raw` key: tailwind.config.js ``` module.exports = { theme: { extend: { screens: { 'tall': { 'raw': '(min-height: 800px)' }, // => @media (min-height: 800px) { ... } } } } } ``` Media queries defined using the `raw` key will be output as-is, and the `min` and `max` keys will be ignored. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/screensCustomizing Colors ================== Customizing the default color palette for your project. Default color palette --------------------- Tailwind includes an expertly-crafted default color palette out-of-the-box that is a great starting point if you don’t have your own specific branding in mind. Slate 50 #f8fafc 100 #f1f5f9 200 #e2e8f0 300 #cbd5e1 400 #94a3b8 500 #64748b 600 #475569 700 #334155 800 #1e293b 900 #0f172a 950 #020617 Gray 50 #f9fafb 100 #f3f4f6 200 #e5e7eb 300 #d1d5db 400 #9ca3af 500 #6b7280 600 #4b5563 700 #374151 800 #1f2937 900 #111827 950 #030712 Zinc 50 #fafafa 100 #f4f4f5 200 #e4e4e7 300 #d4d4d8 400 #a1a1aa 500 #71717a 600 #52525b 700 #3f3f46 800 #27272a 900 #18181b 950 #09090b Neutral 50 #fafafa 100 #f5f5f5 200 #e5e5e5 300 #d4d4d4 400 #a3a3a3 500 #737373 600 #525252 700 #404040 800 #262626 900 #171717 950 #0a0a0a Stone 50 #fafaf9 100 #f5f5f4 200 #e7e5e4 300 #d6d3d1 400 #a8a29e 500 #78716c 600 #57534e 700 #44403c 800 #292524 900 #1c1917 950 #0c0a09 Red 50 #fef2f2 100 #fee2e2 200 #fecaca 300 #fca5a5 400 #f87171 500 #ef4444 600 #dc2626 700 #b91c1c 800 #991b1b 900 #7f1d1d 950 #450a0a Orange 50 #fff7ed 100 #ffedd5 200 #fed7aa 300 #fdba74 400 #fb923c 500 #f97316 600 #ea580c 700 #c2410c 800 #9a3412 900 #7c2d12 950 #431407 Amber 50 #fffbeb 100 #fef3c7 200 #fde68a 300 #fcd34d 400 #fbbf24 500 #f59e0b 600 #d97706 700 #b45309 800 #92400e 900 #78350f 950 #451a03 Yellow 50 #fefce8 100 #fef9c3 200 #fef08a 300 #fde047 400 #facc15 500 #eab308 600 #ca8a04 700 #a16207 800 #854d0e 900 #713f12 950 #422006 Lime 50 #f7fee7 100 #ecfccb 200 #d9f99d 300 #bef264 400 #a3e635 500 #84cc16 600 #65a30d 700 #4d7c0f 800 #3f6212 900 #365314 950 #1a2e05 Green 50 #f0fdf4 100 #dcfce7 200 #bbf7d0 300 #86efac 400 #4ade80 500 #22c55e 600 #16a34a 700 #15803d 800 #166534 900 #14532d 950 #052e16 Emerald 50 #ecfdf5 100 #d1fae5 200 #a7f3d0 300 #6ee7b7 400 #34d399 500 #10b981 600 #059669 700 #047857 800 #065f46 900 #064e3b 950 #022c22 Teal 50 #f0fdfa 100 #ccfbf1 200 #99f6e4 300 #5eead4 400 #2dd4bf 500 #14b8a6 600 #0d9488 700 #0f766e 800 #115e59 900 #134e4a 950 #042f2e Cyan 50 #ecfeff 100 #cffafe 200 #a5f3fc 300 #67e8f9 400 #22d3ee 500 #06b6d4 600 #0891b2 700 #0e7490 800 #155e75 900 #164e63 950 #083344 Sky 50 #f0f9ff 100 #e0f2fe 200 #bae6fd 300 #7dd3fc 400 #38bdf8 500 #0ea5e9 600 #0284c7 700 #0369a1 800 #075985 900 #0c4a6e 950 #082f49 Blue 50 #eff6ff 100 #dbeafe 200 #bfdbfe 300 #93c5fd 400 #60a5fa 500 #3b82f6 600 #2563eb 700 #1d4ed8 800 #1e40af 900 #1e3a8a 950 #172554 Indigo 50 #eef2ff 100 #e0e7ff 200 #c7d2fe 300 #a5b4fc 400 #818cf8 500 #6366f1 600 #4f46e5 700 #4338ca 800 #3730a3 900 #312e81 950 #1e1b4b Violet 50 #f5f3ff 100 #ede9fe 200 #ddd6fe 300 #c4b5fd 400 #a78bfa 500 #8b5cf6 600 #7c3aed 700 #6d28d9 800 #5b21b6 900 #4c1d95 950 #2e1065 Purple 50 #faf5ff 100 #f3e8ff 200 #e9d5ff 300 #d8b4fe 400 #c084fc 500 #a855f7 600 #9333ea 700 #7e22ce 800 #6b21a8 900 #581c87 950 #3b0764 Fuchsia 50 #fdf4ff 100 #fae8ff 200 #f5d0fe 300 #f0abfc 400 #e879f9 500 #d946ef 600 #c026d3 700 #a21caf 800 #86198f 900 #701a75 950 #4a044e Pink 50 #fdf2f8 100 #fce7f3 200 #fbcfe8 300 #f9a8d4 400 #f472b6 500 #ec4899 600 #db2777 700 #be185d 800 #9d174d 900 #831843 950 #500724 Rose 50 #fff1f2 100 #ffe4e6 200 #fecdd3 300 #fda4af 400 #fb7185 500 #f43f5e 600 #e11d48 700 #be123c 800 #9f1239 900 #881337 950 #4c0519 But when you do need to customize your palette, you can configure your colors under the `colors` key in the `theme` section of your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { theme: { colors: { // Configure your color palette here } } } ``` When it comes to building a custom color palette, you can either [configure your own custom colors](customizing-colors#using-custom-colors) from scratch if you know exactly what you want, or [curate your colors](customizing-colors#using-the-default-colors) from our extensive included color palette if you want a head start. Using custom colors ------------------- If you’d like to completely replace the default color palette with your own custom colors, add your colors directly under the `theme.colors` section of your configuration file: tailwind.config.js ``` module.exports = { theme: { colors: { transparent: 'transparent', current: 'currentColor', 'white': '#ffffff', 'purple': '#3f3cbb', 'midnight': '#121063', 'metal': '#565584', 'tahiti': '#3ab7bf', 'silver': '#ecebff', 'bubble-gum': '#ff77e9', 'bermuda': '#78dcca', }, }, } ``` By default, these colors will be made available everywhere in the framework where you use colors, like the [text color](text-color) utilities, [border color](border-color) utilities, [background color](background-color) utilities, and more. ``` <div class="bg-midnight text-tahiti"> <!-- ... --> </div> ``` Don’t forget to include values like `transparent` and `currentColor` if you want to use them in your project. ### Color object syntax When your palette includes multiple shades of the same color, it can be convenient to group them together using our nested color object syntax: tailwind.config.js ``` module.exports = { theme: { colors: { transparent: 'transparent', current: 'currentColor', 'white': '#ffffff', 'tahiti': { 100: '#cffafe', 200: '#a5f3fc', 300: '#67e8f9', 400: '#22d3ee', 500: '#06b6d4', 600: '#0891b2', 700: '#0e7490', 800: '#155e75', 900: '#164e63', }, // ... }, }, } ``` The nested keys will be combined with the parent key to form class names like `bg-tahiti-400`. Like many other places in Tailwind, the special `DEFAULT` key can be used when you want to define a value with no suffix: tailwind.config.js ``` module.exports = { theme: { colors: { // ... 'tahiti': { light: '#67e8f9', DEFAULT: '#06b6d4', dark: '#0e7490', }, // ... }, }, } ``` This will create classes like `bg-tahiti`, `bg-tahiti-light`, and `bg-tahiti-dark`. ### Arbitrary values If you need a one-off custom color in your project, consider using Tailwind’s arbitrary value notation to generate a class for that color on-demand instead of adding it to your theme: ``` <button class="bg-[#1da1f2] text-white ..."> <svg><!-- ... --></svg> Share on Twitter </button> ``` Learn more in the [using arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. ### Generating colors If you’re wondering how to automatically generate the 50–950 shades of your own custom colors, bad news — color is complicated and despite trying dozens of different tools, we’ve yet to find one that does a good job generating color palettes like this automatically. We picked all of Tailwind’s default colors by hand, meticulously balancing them by eye and testing them in real designs to make sure we were happy with them. Two useful tools we *can* recommend are [Palettte](https://palettte.app/) and [ColorBox](https://colorbox.io/) — they won’t do the work for you but their interfaces are well-designed for doing this sort of work. Using the default colors ------------------------ If you don’t have a set of completely custom colors in mind for your project, you can curate your colors from our default palette by importing `tailwindcss/colors` in your configuration file and choosing the colors you want to use: tailwind.config.js ``` const colors = require('tailwindcss/colors') module.exports = { theme: { colors: { transparent: 'transparent', current: 'currentColor', black: colors.black, white: colors.white, gray: colors.gray, emerald: colors.emerald, indigo: colors.indigo, yellow: colors.yellow, }, }, } ``` This can be helpful if you want to deliberately limit your color palette and reduce the number of class names suggested by [IntelliSense](https://tailwindcss.com/docs/editor-setup#intelli-sense-for-vs-code). ### Aliasing color names You can also alias the colors in our default palette to make the names simpler and easier to remember: tailwind.config.js ``` const colors = require('tailwindcss/colors') module.exports = { theme: { colors: { transparent: 'transparent', current: 'currentColor', black: colors.black, white: colors.white, gray: colors.slate, green: colors.emerald, purple: colors.violet, yellow: colors.amber, pink: colors.fuchsia, }, }, } ``` This is especially common for grays, as you usually only use one set in any given project and it’s nice to be able to type `bg-gray-300` instead of `bg-neutral-300` for example. ### Adding additional colors If you’d like to add a brand new color to the default palette, add it in the `theme.extend.colors` section of your configuration file: tailwind.config.js ``` module.exports = { theme: { extend: { colors: { brown: { 50: '#fdf8f6', 100: '#f2e8e5', 200: '#eaddd7', 300: '#e0cec7', 400: '#d2bab0', 500: '#bfa094', 600: '#a18072', 700: '#977669', 800: '#846358', 900: '#43302b', }, } }, }, } ``` You can also use `theme.extend.colors` to add additional shades to an existing color if it’s needed for your design: tailwind.config.js ``` module.exports = { theme: { extend: { colors: { blue: { 950: '#17275c', }, } }, }, } ``` ### Disabling a default color If you’d like to disable any of the default colors, the best approach is to override the default color palette and just include the colors you *do* want: tailwind.config.js ``` const colors = require('tailwindcss/colors') module.exports = { theme: { colors: { transparent: 'transparent', current: 'currentColor', black: colors.black, white: colors.white, gray: colors.gray, emerald: colors.emerald, indigo: colors.indigo, yellow: colors.yellow, }, }, } ``` Naming your colors ------------------ Tailwind uses literal color names *(like red, green, etc.)* and a numeric scale *(where 50 is light and 900 is dark)* by default. We think this is the best choice for most projects, and have found it easier to maintain than using abstract names like `primary` or `danger`. That said, you can name your colors in Tailwind whatever you like, and if you’re working on a project that needs to support multiple themes for example, it might make sense to use more abstract names: tailwind.config.js ``` module.exports = { theme: { colors: { primary: '#5c6ac4', secondary: '#ecc94b', // ... } } } ``` You can configure those colors explicitly like we have above, or you can pull in colors from our default color palette and alias them: tailwind.config.js ``` const colors = require('tailwindcss/colors') module.exports = { theme: { colors: { primary: colors.indigo, secondary: colors.yellow, neutral: colors.gray, } } } ``` Again, we recommend sticking to the default naming convention for most projects, and only using abstract names if you have a really good reason. Using CSS variables ------------------- If you’d like to define your colors as CSS variables, you’ll need to define those variables as just the color *channels* if you want them to work with the [opacity modifier syntax](text-color#changing-the-opacity): Define your CSS variables as channels with no color space function main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { --color-primary: 255 115 179; --color-secondary: 111 114 185; /* ... */ } } ``` Don’t include the color space function or opacity modifiers won’t work main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { --color-primary: rgb(255 115 179); --color-secondary: rgb(111 114 185); /* ... */ } } ``` Then define your colors in your configuration file, being sure to include the color space you’re using, and the special `<alpha-value>` placeholder that Tailwind will use to inject the alpha value when using an opacity modifier: tailwind.config.js ``` module.exports = { theme: { colors: { // Using modern `rgb` primary: 'rgb(var(--color-primary) / <alpha-value>)', secondary: 'rgb(var(--color-secondary) / <alpha-value>)', // Using modern `hsl` primary: 'hsl(var(--color-primary) / <alpha-value>)', secondary: 'hsl(var(--color-secondary) / <alpha-value>)', // Using legacy `rgba` primary: 'rgba(var(--color-primary), <alpha-value>)', secondary: 'rgba(var(--color-secondary), <alpha-value>)', } } } ``` When defining your colors this way, make sure that the format of your CSS variables is correct for the color function you are using. You’ll want to use spaces if using the modern [space-separated syntax](https://css-tricks.com/the-expanding-gamut-of-color-on-the-web/#aa-a-tale-of-new-syntaxes), and commas if using legacy functions like `rgba` or `hsla`: main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { /* For rgb(255 115 179 / <alpha-value>) */ --color-primary: 255 115 179; /* For hsl(198deg 93% 60% / <alpha-value>) */ --color-primary: 198deg 93% 60%; /* For rgba(255, 115, 179, <alpha-value>) */ --color-primary: 255, 115, 179; } } ``` © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/customizing-colorsCustomizing Spacing =================== Customizing the default spacing and sizing scale for your project. Use the `spacing` key in the `theme` section of your `tailwind.config.js` file to customize Tailwind’s [default spacing/sizing scale](customizing-spacing#default-spacing-scale). tailwind.config.js ``` module.exports = { theme: { spacing: { '1': '8px', '2': '12px', '3': '16px', '4': '24px', '5': '32px', '6': '48px', } } } ``` By default the spacing scale is inherited by the `padding`, `margin`, `width`, `height`, `maxHeight`, `gap`, `inset`, `space`, and `translate` core plugins. Extending the default spacing scale ----------------------------------- As described in the [theme documentation](theme#extending-the-default-theme), if you’d like to extend the default spacing scale, you can do so using the `theme.extend.spacing` section of your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '13': '3.25rem', '15': '3.75rem', '128': '32rem', '144': '36rem', } } } } ``` This will generate classes like `p-13`, `m-15`, and `h-128` in addition to all of Tailwind’s default spacing/sizing utilities. Overriding the default spacing scale ------------------------------------ As described in the [theme documentation](theme#overriding-the-default-theme), if you’d like to override the default spacing scale, you can do so using the `theme.spacing` section of your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { theme: { spacing: { sm: '8px', md: '12px', lg: '16px', xl: '24px', } } } ``` This will disable Tailwind’s default spacing scale and generate classes like `p-sm`, `m-md`, `w-lg`, and `h-xl` instead. Default spacing scale --------------------- By default, Tailwind includes a generous and comprehensive numeric spacing scale. The values are proportional, so `16` is twice as much spacing as `8` for example. One spacing unit is equal to `0.25rem`, which translates to `4px` by default in common browsers. | Name | Size | Pixels | Preview | | --- | --- | --- | --- | | 0 | 0px | 0px | | | px | 1px | 1px | | | 0.5 | 0.125rem | 2px | | | 1 | 0.25rem | 4px | | | 1.5 | 0.375rem | 6px | | | 2 | 0.5rem | 8px | | | 2.5 | 0.625rem | 10px | | | 3 | 0.75rem | 12px | | | 3.5 | 0.875rem | 14px | | | 4 | 1rem | 16px | | | 5 | 1.25rem | 20px | | | 6 | 1.5rem | 24px | | | 7 | 1.75rem | 28px | | | 8 | 2rem | 32px | | | 9 | 2.25rem | 36px | | | 10 | 2.5rem | 40px | | | 11 | 2.75rem | 44px | | | 12 | 3rem | 48px | | | 14 | 3.5rem | 56px | | | 16 | 4rem | 64px | | | 20 | 5rem | 80px | | | 24 | 6rem | 96px | | | 28 | 7rem | 112px | | | 32 | 8rem | 128px | | | 36 | 9rem | 144px | | | 40 | 10rem | 160px | | | 44 | 11rem | 176px | | | 48 | 12rem | 192px | | | 52 | 13rem | 208px | | | 56 | 14rem | 224px | | | 60 | 15rem | 240px | | | 64 | 16rem | 256px | | | 72 | 18rem | 288px | | | 80 | 20rem | 320px | | | 96 | 24rem | 384px | | © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/customizing-spacingPlugins ======= Extending Tailwind with reusable third-party plugins. Overview -------- Plugins let you register new styles for Tailwind to inject into the user’s stylesheet using JavaScript instead of CSS. To get started with your first plugin, import Tailwind’s `plugin` function from `tailwindcss/plugin`. Then inside your `plugins` array, call the imported `plugin` function with an anonymous function as the first argument. tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { plugins: [ plugin(function({ addUtilities, addComponents, e, config }) { // Add your custom styles here }), ] } ``` Plugin functions receive a single object argument that can be [destructured](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) into several helper functions: * `addUtilities()`, for registering new static utility styles * `matchUtilities()`, for registering new dynamic utility styles * `addComponents()`, for registering new static component styles * `matchComponents()`, for registering new dynamic component styles * `addBase()`, for registering new base styles * `addVariant()`, for registering custom static variants * `matchVariant()`, for registering custom dynamic variants * `theme()`, for looking up values in the user’s theme configuration * `config()`, for looking up values in the user’s Tailwind configuration * `corePlugins()`, for checking if a core plugin is enabled * `e()`, for manually escaping strings meant to be used in class names Official plugins ---------------- We’ve developed a handful of official plugins for popular features that for one reason or another don’t belong in core yet. Plugins can be added to your project by installing them via npm, then adding them to your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { // ... plugins: [ require('@tailwindcss/typography'), require('@tailwindcss/forms'), require('@tailwindcss/aspect-ratio'), require('@tailwindcss/container-queries'), ] } ``` ### Typography The `@tailwindcss/typography` plugin adds a set of `prose` classes that can be used to quickly add sensible typographic styles to content blocks that come from sources like markdown or a CMS database. ``` <article class="prose lg:prose-xl"> <h1>Garlic bread with cheese: What the science tells us</h1> <p> For years parents have espoused the health benefits of eating garlic bread with cheese to their children, with the food earning such an iconic status in our culture that kids will often dress up as warm, cheesy loaf for Halloween. </p> <p> But a recent study shows that the celebrated appetizer may be linked to a series of rabies cases springing up around the country. </p> <!-- ... --> </article> ``` [Learn more about the typography plugin →](typography-plugin) ### Forms The `@tailwindcss/forms` plugin adds an opinionated form reset layer that makes it easier to style form elements with utility classes. ``` <!-- You can actually customize padding on a select element: --> <select class="px-4 py-3 rounded-full"> <!-- ... --> </select<!-- Or change a checkbox color using text color utilities: --> <input type="checkbox" class="rounded text-pink-500" /> ``` [Learn more about the forms plugin →](https://github.com/tailwindlabs/tailwindcss-forms) ### Aspect ratio The `@tailwindcss/aspect-ratio` plugin is an alternative to native `aspect-ratio` support that works in older browsers, and adds `aspect-w-{n}` and `aspect-h-{n}` classes that can be combined to give an element a fixed aspect ratio. ``` <div class="aspect-w-16 aspect-h-9"> <iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> ``` [Learn more about the aspect ratio plugin →](https://github.com/tailwindlabs/tailwindcss-aspect-ratio) ### Container queries The `@tailwindcss/container-queries` plugin adds new `@{size}` variants like `@sm` and `@md` that let you style an element based on the dimensions of a parent marked with `@container` instead of the viewport. ``` <div class="@container"> <div class="@lg:text-sky-400"> <!-- ... --> </div> </div> ``` [Learn more about the container queries plugin →](https://github.com/tailwindlabs/tailwindcss-container-queries) Adding utilities ---------------- The `addUtilities` and `matchUtilities` functions allow you to register new styles in Tailwind’s `utilities` layer. Like with the utilities Tailwind includes by default, utilities added by a plugin will only be included in the generated CSS if they are actually being used in the project. ### Static utilities Use the `addUtilities` function to register simple static utilities that don’t support user-provided values: tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { plugins: [ plugin(function({ addUtilities }) { addUtilities({ '.content-auto': { 'content-visibility': 'auto', }, '.content-hidden': { 'content-visibility': 'hidden', }, '.content-visible': { 'content-visibility': 'visible', }, }) }) ] } ``` Learn more about how to represent your styles in JavaScript in the [CSS-in-JS syntax](plugins#css-in-js-syntax) reference. ### Dynamic utilities Use the `matchUtilities` function to register utilities that map to values defined in the user’s `theme` configuration: tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { theme: { tabSize: { 1: '1', 2: '2', 4: '4', 8: '8', } }, plugins: [ plugin(function({ matchUtilities, theme }) { matchUtilities( { tab: (value) => ({ tabSize: value }), }, { values: theme('tabSize') } ) }) ] } ``` Utilities defined this way also support [arbitrary values](adding-custom-styles#using-arbitrary-values), which means you can use values not present in the theme using square bracket notation: ``` <div class="tab-[13]"> <!-- ... --> </div> ``` ### Prefix and important By default, plugin utilities automatically respect the user’s [`prefix`](configuration#prefix) and [`important`](configuration#important) preferences. That means that given this Tailwind configuration: tailwind.config.js ``` module.exports = { prefix: 'tw-', important: true, // ... } ``` …the example plugin above would generate the following CSS: ``` .tw-content-auto { content-visibility: auto !important; } .tw-content-hidden { content-visibility: hidden !important; } .tw-content-visible { content-visibility: visible !important; } ``` ### Using with modifiers Any custom utilities added using `addUtilities` can automatically be used with modifiers: ``` <div class="content-auto lg:content-visible"> <!-- ... --> </div> ``` Learn more in the [Hover, Focus, and Other States](hover-focus-and-other-states) documentation. ### Providing default values Utility plugins can provide default values by including a configuration object as the second argument to the `plugin` function: ./plugins/tab-size.js ``` const plugin = require('tailwindcss/plugin') module.exports = plugin(function({ matchUtilities, theme }) { matchUtilities( { tab: (value) => ({ tabSize: value }), }, { values: theme('tabSize') } ) }, { theme: { tabSize: { 1: '1', 2: '2', 4: '4', 8: '8', } } }) ``` These values behave just like the values in the default configuration, and can be overridden or extended by the end user. Adding components ----------------- The `addComponents` function allows you to register new styles in Tailwind’s `components` layer. Use it to add more opinionated, complex classes like buttons, form controls, alerts, etc; the sort of pre-built components you often see in other frameworks that you might need to override with utility classes. To add new component styles from a plugin, call `addComponents`, passing in your styles using [CSS-in-JS syntax](plugins#css-in-js-syntax): tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { plugins: [ plugin(function({ addComponents }) { addComponents({ '.btn': { padding: '.5rem 1rem', borderRadius: '.25rem', fontWeight: '600', }, '.btn-blue': { backgroundColor: '#3490dc', color: '#fff', '&:hover': { backgroundColor: '#2779bd' }, }, '.btn-red': { backgroundColor: '#e3342f', color: '#fff', '&:hover': { backgroundColor: '#cc1f1a' }, }, }) }) ] } ``` Like with other component classes in Tailwind, component classes added by a plugin will only be included in the generated CSS if they are actually being used in the project. ### Prefix and important By default, component classes automatically respect the user’s `prefix` preference, but *they are not affected* by the user’s `important` preference. That means that given this Tailwind configuration: tailwind.config.js ``` module.exports = { prefix: 'tw-', important: true, // ... } ``` …the example plugin above would generate the following CSS: ``` .tw-btn { padding: .5rem 1rem; border-radius: .25rem; font-weight: 600; } .tw-btn-blue { background-color: #3490dc; color: #fff; } .tw-btn-blue:hover { background-color: #2779bd; } .tw-btn-red { background-color: #e3342f; color: #fff; } .tw-btn-red:hover { background-color: #cc1f1a; } ``` Although there’s rarely a good reason to make component declarations important, if you really need to do it you can always add `!important` manually: tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { plugins: [ plugin(function({ addComponents }) { addComponents({ '.btn': { padding: '.5rem 1rem !important', borderRadius: '.25rem !important', fontWeight: '600 !important', }, // ... }) }) ] } ``` All classes in a selector will be prefixed by default, so if you add a more complex style like: tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { prefix: 'tw-', plugins: [ plugin(function({ addComponents }) { const components = { // ... '.navbar-inverse a.nav-link': { color: '#fff', } } addComponents(components) }) ] } ``` …the following CSS would be generated: ``` .tw-navbar-inverse a.tw-nav-link { color: #fff; } ``` ### Using with modifiers Any component classes added using `addComponents` can automatically be used with modifiers: ``` <div class="btn md:btn-lg"> <!-- ... --> </div> ``` Learn more in the [Hover, Focus, and Other States](hover-focus-and-other-states) documentation. Adding base styles ------------------ The `addBase` function allows you to register new styles in Tailwind’s `base` layer. Use it to add things like base typography styles, opinionated global resets, or `@font-face` rules. To add new base styles from a plugin, call `addBase`, passing in your styles using [CSS-in-JS syntax](plugins#css-in-js-syntax): tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { plugins: [ plugin(function({ addBase, theme }) { addBase({ 'h1': { fontSize: theme('fontSize.2xl') }, 'h2': { fontSize: theme('fontSize.xl') }, 'h3': { fontSize: theme('fontSize.lg') }, }) }) ] } ``` Since base styles are meant to target bare selectors like `div` or `h1`, they do not respect the user’s `prefix` or `important` configuration. Adding variants --------------- The `addVariant` and `matchVariant` functions allow you to register your own custom [modifiers](hover-focus-and-other-states) that can be used just like built-in variants like `hover`, `focus`, or `supports`. ### Static variants Use the `addVariant` function for simple custom variants, passing in the name of your custom variant, and a format string that represents how the selector should be modified. tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { // ... plugins: [ plugin(function({ addVariant }) { addVariant('optional', '&:optional') addVariant('hocus', ['&:hover', '&:focus']) addVariant('inverted-colors', '@media (inverted-colors: inverted)') }) ] } ``` The first argument is the modifier name that users will use in their HTML, so the above example would make it possible to write classes like these: ``` <form class="flex inverted-colors:outline ..."> <input class="optional:border-gray-300 ..." /> <button class="bg-blue-500 hocus:bg-blue-600">...</button> </form> ``` ### Dynamic variants Use the `matchVariant` function to register new parameterized variants like the built-in `supports-*`, `data-*`, and `aria-*` variants: tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { plugins: [ plugin(function({ matchVariant }) { matchVariant( 'nth', (value) => { return `&:nth-child(${value})`; }, { values: { 1: '1', 2: '2', 3: '3', } } ); }) ] } ``` Variants defined with `matchVariant` also support arbitrary values using square bracket notation: ``` <div class="nth-[3n+1]:bg-blue-500 ..."> <!-- ... --> </div> ``` Use the `sort` option to control the source order of the generated CSS if needed to avoid precedence issues with other values that come from the same variant: ``` matchVariant("min", (value) => `@media (min-width: ${value})`, { sort(a, z) { return parseInt(a.value) - parseInt(z.value); }, }); ``` ### Parent and sibling states Your custom modifiers won’t automatically work with Tailwind’s [parent](hover-focus-and-other-states#styling-based-on-parent-state) and [sibling](hover-focus-and-other-states#styling-based-on-sibling-state) state modifiers. To support the `group-*` and `peer-*` versions of your own custom modifiers, register them as separate variants using the special `:merge` directive to ensure the `.group` and `.peer` classes only appear once in the final selector. tailwind.config.js ``` const plugin = require('tailwindcss/plugin') module.exports = { // ... plugins: [ plugin(function({ addVariant }) { addVariant('optional', '&:optional') addVariant('group-optional', ':merge(.group):optional &') addVariant('peer-optional', ':merge(.peer):optional ~ &') }) ] } ``` Extending the configuration --------------------------- Plugins can merge their own set of configuration values into the user’s `tailwind.config.js` configuration by providing an object as the second argument to the `plugin` function: ./plugins/tab-size.js ``` const plugin = require('tailwindcss/plugin') module.exports = plugin(function({ matchUtilities, theme }) { matchUtilities( { tab: (value) => ({ tabSize: value }), }, { values: theme('tabSize') } ) }, { theme: { tabSize: { 1: '1', 2: '2', 4: '4', 8: '8', } } }) ``` This can be useful for things like providing default `theme` values for the classes your plugin generates. Exposing options ---------------- Sometimes it makes sense for a plugin to be configurable in a way that doesn’t really belong under `theme`, like perhaps you want users to be able to customize the class name your plugin uses. For cases like this, you can use `plugin.withOptions` to define a plugin that can be invoked with a configuration object. This API is similar to the regular `plugin` API, except each argument should be a function that receives the user’s `options` and returns the value that you would have normally passed in using the regular API: ./plugins/markdown.js ``` const plugin = require('tailwindcss/plugin') module.exports = plugin.withOptions(function (options = {}) { return function({ addComponents }) { const className = options.className ?? 'markdown' addComponents({ [`.${className}`]: { // ... } }) } }, function (options) { return { theme: { markdown: { // ... } }, } }) ``` The user would invoke your plugin passing along their options when registering it in their `plugins` configuration: tailwind.config.js ``` module.exports = { theme: { // ... }, plugins: [ require('./plugins/markdown.js')({ className: 'wysiwyg' }) ], } ``` The user can also register plugins created this way normally without invoking them if they don’t need to pass in any custom options: tailwind.config.js ``` module.exports = { theme: { // ... }, plugins: [ require('./plugins/markdown.js') ], } ``` CSS-in-JS syntax ---------------- Tailwind’s plugin system expects CSS rules written as JavaScript objects, using the same sort of syntax you might recognize from CSS-in-JS libraries like [Emotion](https://emotion.sh/docs/object-styles), powered by [postcss-js](https://github.com/postcss/postcss-js) under-the-hood. Consider this simple CSS rule: ``` .card { background-color: #fff; border-radius: .25rem; box-shadow: 0 2px 4px rgba(0,0,0,0.2); } ``` Translating this to a CSS-in-JS object would look like this: ``` addComponents({ '.card': { 'background-color': '#fff', 'border-radius': '.25rem', 'box-shadow': '0 2px 4px rgba(0,0,0,0.2)', } }) ``` For convenience, property names can also be written in camelCase and will be automatically translated to dash-case: ``` addComponents({ '.card': { backgroundColor: '#fff', borderRadius: '.25rem', boxShadow: '0 2px 4px rgba(0,0,0,0.2)', } }) ``` Nesting is also supported (powered by [postcss-nested](https://github.com/postcss/postcss-nested)), using the same syntax you might be familiar with from Sass or Less: ``` addComponents({ '.card': { backgroundColor: '#fff', borderRadius: '.25rem', boxShadow: '0 2px 4px rgba(0,0,0,0.2)', '&:hover': { boxShadow: '0 10px 15px rgba(0,0,0,0.2)', }, '@media (min-width: 500px)': { borderRadius: '.5rem', } } }) ``` Multiple rules can be defined in the same object: ``` addComponents({ '.btn': { padding: '.5rem 1rem', borderRadius: '.25rem', fontWeight: '600', }, '.btn-blue': { backgroundColor: '#3490dc', color: '#fff', '&:hover': { backgroundColor: '#2779bd' }, }, '.btn-red': { backgroundColor: '#e3342f', color: '#fff', '&:hover': { backgroundColor: '#cc1f1a' }, }, }) ``` …or as an array of objects in case you need to repeat the same key: ``` addComponents([ { '@media (min-width: 500px)': { // ... } }, { '@media (min-width: 500px)': { // ... } }, { '@media (min-width: 500px)': { // ... } }, ]) ``` © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/pluginsPresets ======= Creating your own reusable configuration presets. By default, any configuration you add in your own `tailwind.config.js` file is intelligently merged with the [default configuration](https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/config.full.js), with your own configuration acting as a set of overrides and extensions. The `presets` option lets you specify a *different* configuration to use as your base, making it easy to package up a set of customizations that you’d like to reuse across projects. tailwind.config.js ``` module.exports = { presets: [ require('@acmecorp/tailwind-base') ], // ... } ``` This can be very useful for teams that manage multiple Tailwind projects for the same brand where they want a single source of truth for colors, fonts, and other common customizations. Creating a preset ----------------- Presets are just regular Tailwind configuration objects, taking the exact same shape as the configuration you would add in your `tailwind.config.js` file. my-preset.js ``` // Example preset module.exports = { theme: { colors: { blue: { light: '#85d7ff', DEFAULT: '#1fb6ff', dark: '#009eeb', }, pink: { light: '#ff7ce5', DEFAULT: '#ff49db', dark: '#ff16d1', }, gray: { darkest: '#1f2d3d', dark: '#3c4858', DEFAULT: '#c0ccda', light: '#e0e6ed', lightest: '#f9fafc', } }, fontFamily: { sans: ['Graphik', 'sans-serif'], }, extend: { flexGrow: { 2: '2', 3: '3', }, zIndex: { 60: '60', 70: '70', 80: '80', 90: '90', 100: '100', }, } }, plugins: [ require('@tailwindcss/typography'), require('@tailwindcss/aspect-ratio'), ], } ``` As you can see, presets can contain all of the configuration options you’re used to, including theme overrides and extensions, adding plugins, configuring a prefix, and so on. Read about [how configurations are merged](presets#merging-logic-in-depth) for more details. Assuming this preset was saved at `./my-preset.js`, you would use it by adding it to the `tailwind.config.js` file in your actual project under the `presets` key: tailwind.config.js ``` module.exports = { presets: [ require('./my-preset.js') ], // Customizations specific to this project would go here theme: { extend: { minHeight: { 48: '12rem', } } }, } ``` By default, presets themselves extend Tailwind’s [default configuration](https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/config.full.js) just like your own configuration would. If you’d like to create a preset that completely replaces the default configuration, include an empty `presets` key in the preset itself: ``` // Example preset module.exports = { presets: [], theme: { // ... }, plugins: [ // ... ], } ``` For more information, read about [disabling the default configuration](presets#disabling-the-default-configuration). Merging logic in-depth ---------------------- Project-specific configurations (those found in your `tailwind.config.js` file) are merged against presets the same way they are merged against the default configuration. The following options in `tailwind.config.js` simply **replace** the same option if present in a preset: * `content` * `darkMode` * `prefix` * `important` * `variantOrder` * `separator` * `safelist` The remaining options are each carefully merged in the way that makes the most sense for that option, explained in more detail below. ### Theme The `theme` object is merged shallowly, with top-level keys in `tailwind.config.js` replacing the same top-level keys in any presets. The exception to this is the `extend` key, which is collected across all configurations and applied on top of the rest of the theme configuration. Learn more about how the `theme` option works in the [theme configuration documentation](theme). ### Presets The `presets` array is merged across configurations, allowing presets to include their own presets, which can also include their own presets. ### Plugins The `plugins` array is merged across configurations to make it possible for a preset to register plugins while also allowing you to add additional plugins at the project-level. This means it’s not possible to disable a plugin that has been added by a preset. If you find yourself wanting to disable a plugin in a preset, it’s a sign that you should probably remove that plugin from the preset and include it on a project-by-project basis instead, or [split your preset into two presets](presets#extending-multiple-presets). ### Core plugins The `corePlugins` option behaves differently depending on whether you configure it as an object or as an array. If you configure `corePlugins` as an object, it is merged across configurations. my-preset.js ``` module.exports = { // ... corePlugins: { float: false, }, } ``` tailwind.config.js ``` module.exports = { presets: [ require('./my-preset.js'), ], // This configuration will be merged corePlugins: { cursor: false } } ``` If you configure `corePlugins` as an array, it replaces any `corePlugins` configuration provided by your configured preset(s). my-preset.js ``` module.exports = { // ... corePlugins: { float: false, }, } ``` tailwind.config.js ``` module.exports = { presets: [ require('./example-preset.js'), ], // This will replace the configuration in the preset corePlugins: ['float', 'padding', 'margin'] } ``` Extending multiple presets -------------------------- The `presets` option is an array and can accept multiple presets. This is useful if you want to split your reusable customizations up into composable chunks that can be imported independently. tailwind.config.js ``` module.exports = { presets: [ require('@acmecorp/tailwind-colors'), require('@acmecorp/tailwind-fonts'), require('@acmecorp/tailwind-spacing'), ] } ``` When adding multiple presets, it’s important to note that if they overlap in any way, they are resolved the same way your own customizations are resolved against a preset, and the last configuration wins. For example, if both of these configurations provided a custom color palette (and were not using `extend`), the color palette from `configuration-b` would be used: tailwind.config.js ``` module.exports = { presets: [ require('@acmecorp/configuration-a'), require('@acmecorp/configuration-b'), ] } ``` Disabling the default configuration ----------------------------------- If you’d like to completely disable the default configuration and start with no base configuration at all, set `presets` to an empty array: tailwind.config.js ``` module.exports = { presets: [], // ... } ``` This will completely disable all of Tailwind’s defaults, so no colors, font families, font sizes, spacing values, etc. will be generated at all. You can also do this from within a preset if you’d like your preset to provide a complete design system on its own that doesn’t extend Tailwind’s defaults: my-preset.js ``` module.exports = { presets: [], // ... } ``` tailwind.config.js ``` module.exports = { presets: [ require('./my-preset.js') ], // ... } ``` © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/presetsPreflight ========= An opinionated set of base styles for Tailwind projects. Overview -------- Built on top of [modern-normalize](https://github.com/sindresorhus/modern-normalize), Preflight is a set of base styles for Tailwind projects that are designed to smooth over cross-browser inconsistencies and make it easier for you to work within the constraints of your design system. Tailwind automatically injects these styles when you include `@tailwind base` in your CSS: ``` @tailwind base; /* Preflight will be injected here */ @tailwind components; @tailwind utilities; ``` While most of the styles in Preflight are meant to go unnoticed — they simply make things behave more like you’d expect them to — some are more opinionated and can be surprising when you first encounter them. For a complete reference of all the styles applied by Preflight, [see the stylesheet](https://unpkg.com/tailwindcss@%5E3/src/css/preflight.css). Default margins are removed --------------------------- Preflight removes all of the default margins from elements like headings, blockquotes, paragraphs, etc. ``` blockquote, dl, dd, h1, h2, h3, h4, h5, h6, hr, figure, p, pre { margin: 0; } ``` This makes it harder to accidentally rely on margin values applied by the user-agent stylesheet that are not part of your spacing scale. Headings are unstyled --------------------- All heading elements are completely unstyled by default, and have the same font-size and font-weight as normal text. ``` h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } ``` The reason for this is two-fold: * **It helps you avoid accidentally deviating from your type scale**. By default, browsers assign sizes to headings that don’t exist in Tailwind’s default type scale, and aren’t guaranteed to exist in your own type scale. * **In UI development, headings should often be visually de-emphasized**. Making headings unstyled by default means any styling you apply to headings happens consciously and deliberately. You can always add default header styles to your project by [adding your own base styles](/docs/adding-custom-styles#adding-base-styles). If you’d like to selectively introduce sensible default heading styles into article-style parts of a page, we recommend the [@tailwindcss/typography plugin](typography-plugin). Lists are unstyled ------------------ Ordered and unordered lists are unstyled by default, with no bullets/numbers and no margin or padding. ``` ol, ul { list-style: none; margin: 0; padding: 0; } ``` If you’d like to style a list, you can do so using the <list-style-type> and <list-style-position> utilities: ``` <ul class="list-disc list-inside"> <li>One</li> <li>Two</li> <li>Three</li> </ul> ``` You can always add default list styles to your project by [adding your own base styles](/docs/adding-custom-styles#adding-base-styles). If you’d like to selectively introduce default list styles into article-style parts of a page, we recommend the [@tailwindcss/typography plugin](typography-plugin). ### Accessibility considerations Unstyled lists are [not announced as lists by VoiceOver](https://unfetteredthoughts.net/2017/09/26/voiceover-and-list-style-type-none/). If your content is truly a list but you would like to keep it unstyled, [add a “list” role](https://www.scottohara.me/blog/2019/01/12/lists-and-safari.html) to the element: ``` <ul role="list"> <li>One</li> <li>Two</li> <li>Three</li> </ul> ``` Images are block-level ---------------------- Images and other replaced elements (like `svg`, `video`, `canvas`, and others) are `display: block` by default. ``` img, svg, video, canvas, audio, iframe, embed, object { display: block; vertical-align: middle; } ``` This helps to avoid unexpected alignment issues that you often run into using the browser default of `display: inline`. If you ever need to make one of these elements `inline` instead of `block`, simply use the `inline` utility: ``` <img class="inline" src="..." alt="..."> ``` Images are constrained to the parent width ------------------------------------------ Images and videos are constrained to the parent width in a way that preserves their intrinsic aspect ratio. ``` img, video { max-width: 100%; height: auto; } ``` This prevents them from overflowing their containers and makes them responsive by default. If you ever need to override this behavior, use the `max-w-none` utility: ``` <img class="max-w-none" src="..." alt="..."> ``` Border styles are reset globally -------------------------------- In order to make it easy to add a border by simply adding the `border` class, Tailwind overrides the default border styles for all elements with the following rules: ``` *, ::before, ::after { border-width: 0; border-style: solid; border-color: theme('borderColor.DEFAULT', currentColor); } ``` Since the `border` class only sets the `border-width` property, this reset ensures that adding that class always adds a solid 1px border using your configured default border color. This can cause some unexpected results when integrating certain third-party libraries, like [Google maps](https://github.com/tailwindlabs/tailwindcss/issues/484) for example. When you run into situations like this, you can work around them by overriding the Preflight styles with your own custom CSS: ``` .google-map * { border-style: none; } ``` Extending Preflight ------------------- If you’d like to add your own base styles on top of Preflight, simply add them to your CSS using the `@layer base` directive: ``` @tailwind base; @layer base { h1 { @apply text-2xl; } h2 { @apply text-xl; } h3 { @apply text-lg; } a { @apply text-blue-600 underline; } } @tailwind components; @tailwind utilities; ``` Learn more in the [adding base styles documentation](/docs/adding-custom-styles#adding-base-styles). Disabling Preflight ------------------- If you’d like to completely disable Preflight — perhaps because you’re integrating Tailwind into an existing project or because you’d like to provide your own base styles — all you need to do is set `preflight` to `false` in the `corePlugins` section of your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { corePlugins: { preflight: false, } } ``` © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/preflightAspect Ratio ============ Utilities for controlling the aspect ratio of an element. Quick reference --------------- | Class | Properties | | --- | --- | | aspect-auto | aspect-ratio: auto; | | aspect-square | aspect-ratio: 1 / 1; | | aspect-video | aspect-ratio: 16 / 9; | Basic usage ----------- ### Setting the aspect ratio Use the `aspect-{ratio}` utilities to set the desired aspect ratio of an element. ``` <iframe class="w-full aspect-video ..." src="https://www.youtube.com/..."></iframe> ``` Tailwind doesn’t include a large set of aspect ratio values out of the box since it’s easier to just use arbitrary values. See the [arbitrary values](aspect-ratio#arbitrary-values) section for more information. ### Browser support The `aspect-{ratio}` utilities use the native `aspect-ratio` CSS property, which was not supported in Safari until version 15. Until Safari 15 is popularized, Tailwind’s [aspect-ratio](https://github.com/tailwindlabs/tailwindcss-aspect-ratio) plugin is a good alternative. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:aspect-square` to only apply the `aspect-square` utility on hover. ``` <iframe class="w-full aspect-video hover:aspect-square" src="https://www.youtube.com/..."></iframe> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:aspect-square` to apply the `aspect-square` utility at only medium screen sizes and above. ``` <iframe class="w-full aspect-video md:aspect-square" src="https://www.youtube.com/..."></iframe> ``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides a minimal set of `aspect-ratio` utilities. You can customize these values by editing `theme.aspectRatio` or `theme.extend.aspectRatio` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { aspectRatio: { '4/3': '4 / 3', }, } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `aspect-ratio` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <iframe class="w-full aspect-[4/3]" src="https://www.youtube.com/..."></iframe> ``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/aspect-ratioContainer ========= A component for fixing an element's width to the current breakpoint. Quick reference --------------- | Class | Breakpoint | Properties | | --- | --- | --- | | container | None | width: 100%; | | sm (640px) | max-width: 640px; | | md (768px) | max-width: 768px; | | lg (1024px) | max-width: 1024px; | | xl (1280px) | max-width: 1280px; | | 2xl (1536px) | max-width: 1536px; | Basic usage ----------- ### Using the container The `container` class sets the `max-width` of an element to match the `min-width` of the current breakpoint. This is useful if you’d prefer to design for a fixed set of screen sizes instead of trying to accommodate a fully fluid viewport. Note that unlike containers you might have used in other frameworks, **Tailwind’s container does not center itself automatically and does not have any built-in horizontal padding.** To center a container, use the `mx-auto` utility: ``` <div class="container mx-auto"> <!-- ... --> </div> ``` To add horizontal padding, use the `px-{size}` utilities: ``` <div class="container mx-auto px-4"> <!-- ... --> </div> ``` If you’d like to center your containers by default or include default horizontal padding, see the [customization options](container#customizing) below. Applying conditionally ---------------------- ### Responsive variants The `container` class also includes responsive variants like `md:container` by default that allow you to make something behave like a container at only a certain breakpoint and up: ``` <!-- Full-width fluid until the `md` breakpoint, then lock to container --> <div class="md:container md:mx-auto"> <!-- ... --> </div> ``` Customizing ----------- ### Centering by default To center containers by default, set the `center` option to `true` in the `theme.container` section of your config file: tailwind.config.js ``` module.exports = { theme: { container: { center: true, }, }, } ``` ### Adding horizontal padding To add horizontal padding by default, specify the amount of padding you’d like using the `padding` option in the `theme.container` section of your config file: tailwind.config.js ``` module.exports = { theme: { container: { padding: '2rem', }, }, } ``` If you want to specify a different padding amount for each breakpoint, use an object to provide a `default` value and any breakpoint-specific overrides: tailwind.config.js ``` module.exports = { theme: { container: { padding: { DEFAULT: '1rem', sm: '2rem', lg: '4rem', xl: '5rem', '2xl': '6rem', }, }, }, }; ``` © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/containerColumns ======= Utilities for controlling the number of columns within an element. Quick reference --------------- | Class | Properties | | --- | --- | | columns-1 | columns: 1; | | columns-2 | columns: 2; | | columns-3 | columns: 3; | | columns-4 | columns: 4; | | columns-5 | columns: 5; | | columns-6 | columns: 6; | | columns-7 | columns: 7; | | columns-8 | columns: 8; | | columns-9 | columns: 9; | | columns-10 | columns: 10; | | columns-11 | columns: 11; | | columns-12 | columns: 12; | | columns-auto | columns: auto; | | columns-3xs | columns: 16rem; /* 256px */ | | columns-2xs | columns: 18rem; /* 288px */ | | columns-xs | columns: 20rem; /* 320px */ | | columns-sm | columns: 24rem; /* 384px */ | | columns-md | columns: 28rem; /* 448px */ | | columns-lg | columns: 32rem; /* 512px */ | | columns-xl | columns: 36rem; /* 576px */ | | columns-2xl | columns: 42rem; /* 672px */ | | columns-3xl | columns: 48rem; /* 768px */ | | columns-4xl | columns: 56rem; /* 896px */ | | columns-5xl | columns: 64rem; /* 1024px */ | | columns-6xl | columns: 72rem; /* 1152px */ | | columns-7xl | columns: 80rem; /* 1280px */ | Basic usage ----------- ### Adding based on column count Use the `columns-{count}` utilities to set the number of columns that should be created for the content within an element. The column width will be automatically adjusted to accommodate that number. ``` <div class="columns-3 ..."> <img class="w-full aspect-video ..." src="..." /> <img class="w-full aspect-square ..." src="..." /> <!-- ... --> </div> ``` ### Adding based on column width Use the `columns-{width}` utilities to set the ideal column width for the content within an element, with the number of columns (the count) automatically adjusting to accommodate that value. This “t-shirt” scale is the same as the <max-width> scale, with the addition of `2xs` and `3xs`, since smaller columns may be desirable. ``` <div class="columns-3xs ..."> <img class="w-full aspect-video ..." src="..." /> <img class="w-full aspect-square ..." src="..." /> <!-- ... --> </div> ``` ### Setting the column gap To specify the width between columns, you can use the [gap-x](gap) utilities: ``` <div class="gap-8 columns-3 ..."> <img class="w-full aspect-video ..." src="..." /> <img class="w-full aspect-square ..." src="..." /> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:columns-3` to only apply the `columns-3` utility on hover. ``` <div class="columns-2 hover:columns-3"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:columns-3` to apply the `columns-3` utility at only medium screen sizes and above. ``` <div class="columns-2 md:columns-3"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides a column count scale from `1-12` as well as a column t-shirt scale from `3xs-7xl`. You can customize these values by editing `theme.columns` or `theme.extend.columns` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { columns: { '4xs': '14rem', } }, } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `columns` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="columns-[10rem]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/columnsBreak After =========== Utilities for controlling how a column or page should break after an element. Quick reference --------------- | Class | Properties | | --- | --- | | break-after-auto | break-after: auto; | | break-after-avoid | break-after: avoid; | | break-after-all | break-after: all; | | break-after-avoid-page | break-after: avoid-page; | | break-after-page | break-after: page; | | break-after-left | break-after: left; | | break-after-right | break-after: right; | | break-after-column | break-after: column; | Basic usage ----------- ### Setting the break-after behavior Use the `break-after-{value}` utilities to control how a column or page break should behave after an element. For example, use the `break-after-column` utility to force a column break after an element. ``` <div class="columns-2"> <p>Well, let me tell you something, ...</p> <p class="break-after-column">Sure, go ahead, laugh...</p> <p>Maybe we can live without...</p> <p>Look. If you think this is...</p> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:break-after-column` to only apply the `break-after-column` utility on hover. ``` <div class="hover:break-after-column"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:break-after-column` to apply the `break-after-column` utility at only medium screen sizes and above. ``` <div class="md:break-after-column"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/break-afterBreak Before ============ Utilities for controlling how a column or page should break before an element. Quick reference --------------- | Class | Properties | | --- | --- | | break-before-auto | break-before: auto; | | break-before-avoid | break-before: avoid; | | break-before-all | break-before: all; | | break-before-avoid-page | break-before: avoid-page; | | break-before-page | break-before: page; | | break-before-left | break-before: left; | | break-before-right | break-before: right; | | break-before-column | break-before: column; | Basic usage ----------- ### Setting the break-before behavior Use the `break-before-{value}` utilities to control how a column or page break should behave before an element. For example, use the `break-before-column` utility to force a column break before an element. ``` <div class="columns-2"> <p>Well, let me tell you something, ...</p> <p class="break-before-column">Sure, go ahead, laugh...</p> <p>Maybe we can live without...</p> <p>Look. If you think this is...</p> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:break-before-column` to only apply the `break-before-column` utility on hover. ``` <div class="hover:break-before-column"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:break-before-column` to apply the `break-before-column` utility at only medium screen sizes and above. ``` <div class="md:break-before-column"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/break-beforeBreak Inside ============ Utilities for controlling how a column or page should break within an element. Quick reference --------------- | Class | Properties | | --- | --- | | break-inside-auto | break-inside: auto; | | break-inside-avoid | break-inside: avoid; | | break-inside-avoid-page | break-inside: avoid-page; | | break-inside-avoid-column | break-inside: avoid-column; | Basic usage ----------- ### Setting the break-inside behavior Use the `break-inside-{value}` utilities to control how a column or page break should behave within an element. For example, use the `break-inside-avoid-column` utility to avoid a column break within an element. ``` <div class="columns-2"> <p>Well, let me tell you something, ...</p> <p class="break-inside-avoid-column">Sure, go ahead, laugh...</p> <p>Maybe we can live without...</p> <p>Look. If you think this is...</p> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:break-inside-avoid-column` to only apply the `break-inside-avoid-column` utility on hover. ``` <div class="hover:break-inside-avoid-column"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:break-inside-avoid-column` to apply the `break-inside-avoid-column` utility at only medium screen sizes and above. ``` <div class="md:break-inside-avoid-column"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/break-insideBox Decoration Break ==================== Utilities for controlling how element fragments should be rendered across multiple lines, columns, or pages. Quick reference --------------- | Class | Properties | | --- | --- | | box-decoration-clone | box-decoration-break: clone; | | box-decoration-slice | box-decoration-break: slice; | Basic usage ----------- ### Setting the box decoration break Use the `box-decoration-slice` and `box-decoration-clone` utilities to control whether properties like background, border, border-image, box-shadow, clip-page, margin, and padding should be rendered as if the element were one continuous fragment, or distinct blocks. ``` <span class="box-decoration-slice bg-gradient-to-r from-indigo-600 to-pink-500 text-white px-2 ..."> Hello<br /> World </span> <span class="box-decoration-clone bg-gradient-to-r from-indigo-600 to-pink-500 text-white px-2 ..."> Hello<br /> World </span> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:box-decoration-slice` to only apply the `box-decoration-slice` utility on hover. ``` <div class="box-decoration-clone hover:box-decoration-slice"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:box-decoration-slice` to apply the `box-decoration-slice` utility at only medium screen sizes and above. ``` <div class="box-decoration-clone md:box-decoration-slice"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/box-decoration-breakFloats ====== Utilities for controlling the wrapping of content around an element. Quick reference --------------- | Class | Properties | | --- | --- | | float-right | float: right; | | float-left | float: left; | | float-none | float: none; | Basic usage ----------- ### Floating elements to the right Use `float-right` to float an element to the right of its container. ``` <img class="float-right ..." src="path/to/image.jpg"> <p>Maybe we can live without libraries, people like you and me. ...</p> ``` ### Floating elements to the left Use `float-left` to float an element to the left of its container. ``` <img class="float-left ..." src="path/to/image.jpg"> <p>Maybe we can live without libraries, people like you and me. ...</p> ``` ### Disabling a float Use `float-none` to reset any floats that are applied to an element. This is the default value for the float property. ``` <img class="float-none ..." src="path/to/image.jpg"> <p>Maybe we can live without libraries, people like you and me. ...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:float-right` to only apply the `float-right` utility on hover. ``` <img class="float-right hover:float-left" src="path/to/image.jpg"> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:float-right` to apply the `float-right` utility at only medium screen sizes and above. ``` <img class="float-right md:float-left" src="path/to/image.jpg"> ``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/floatDisplay ======= Utilities for controlling the display box type of an element. Quick reference --------------- | Class | Properties | | --- | --- | | block | display: block; | | inline-block | display: inline-block; | | inline | display: inline; | | flex | display: flex; | | inline-flex | display: inline-flex; | | table | display: table; | | inline-table | display: inline-table; | | table-caption | display: table-caption; | | table-cell | display: table-cell; | | table-column | display: table-column; | | table-column-group | display: table-column-group; | | table-footer-group | display: table-footer-group; | | table-header-group | display: table-header-group; | | table-row-group | display: table-row-group; | | table-row | display: table-row; | | flow-root | display: flow-root; | | grid | display: grid; | | inline-grid | display: inline-grid; | | contents | display: contents; | | list-item | display: list-item; | | hidden | display: none; | Basic usage ----------- ### Block & Inline Use `inline`, `inline-block`, and `block` to control the flow of text and elements. ``` <div> When controlling the flow of text, using the CSS property <span class="inline">display: inline</span> will cause the text inside the element to wrap normally. While using the property <span class="inline-block">display: inline-block</span> will wrap the element to prevent the text inside from extending beyond its parent. Lastly, using the property <span class="block">display: block</span> will put the element on its own line and fill its parent. </div> ``` ### Flow Root Use `flow-root` to create a block-level element with its own [block formatting context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context). ``` <div class="p-4"> <div class="flow-root ..."> <div class="my-4 ...">Well, let me tell you something, ...</div> </div> <div class="flow-root ..."> <div class="my-4 ...">Sure, go ahead, laugh if you want...</div> </div> </div> ``` ### Flex Use `flex` to create a block-level flex container. ``` <div class="flex items-center"> <img src="path/to/image.jpg"> <div> <strong><NAME></strong> <span>Technical advisor</span> </div> </div> ``` ### Inline Flex Use `inline-flex` to create an inline flex container that flows with text. ``` <p> Today I spent most of the day researching ways to ... <span class="inline-flex items-baseline"> <img src="path/to/image.jpg" alt="" class="self-center w-5 h-5 rounded-full mx-1" /> <span>Kramer</span> </span> keeps telling me there is no way to make it work, that ... </p> ``` ### Grid Use `grid` to create a grid container. ``` <div class="grid gap-4 grid-cols-3 grid-rows-3"> <!-- ... --> </div> ``` ### Inline Grid Use `inline-grid` to create an inline grid container. ``` <span class="inline-grid grid-cols-3 gap-4"> <span>01</span> <span>02</span> <span>03</span> <span>04</span> <span>05</span> <span>06</span> </span> <span class="inline-grid grid-cols-3 gap-4"> <span>01</span> <span>02</span> <span>03</span> <span>04</span> <span>05</span> <span>06</span> </span> ``` ### Contents Use `contents` to create a “phantom” container whose children act like direct children of the parent. ``` <div class="flex ..."> <div class="flex-1 ...">01</div> <div class="contents"> <div class="flex-1 ...">02</div> <div class="flex-1 ...">03</div> </div> <div class="flex-1 ...">04</div> </div> ``` ### Table Use the `table`, `table-row`, `table-cell`, `table-caption`, `table-column`, `table-column-group`, `table-header-group`, `table-row-group`, and `table-footer-group` utilities to create elements that behave like their respective table elements. ``` <div class="table w-full ..."> <div class="table-header-group ..."> <div class="table-row"> <div class="table-cell text-left ...">Song</div> <div class="table-cell text-left ...">Artist</div> <div class="table-cell text-left ...">Year</div> </div> </div> <div class="table-row-group"> <div class="table-row"> <div class="table-cell ...">The Sliding Mr. Bones (Next Stop, Pottersville)</div> <div class="table-cell ...">Malcolm Lockyer</div> <div class="table-cell ...">1961</div> </div> <div class="table-row"> <div class="table-cell ...">Witchy Woman</div> <div class="table-cell ...">The Eagles</div> <div class="table-cell ...">1972</div> </div> <div class="table-row"> <div class="table-cell ...">Shining Star</div> <div class="table-cell ...">Earth, Wind, and Fire</div> <div class="table-cell ...">1975</div> </div> </div> </div> ``` ### Hidden Use `hidden` to set an element to `display: none` and remove it from the page layout (compare with `invisible` from the [visibility](visibility#invisible) documentation). ``` <div class="flex ..."> <div class="hidden ...">01</div> <div>02</div> <div>03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:inline-flex` to only apply the `inline-flex` utility on hover. ``` <div class="flex hover:inline-flex"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:inline-flex` to apply the `inline-flex` utility at only medium screen sizes and above. ``` <div class="flex md:inline-flex"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/displayBox Sizing ========== Utilities for controlling how the browser should calculate an element's total size. Quick reference --------------- | Class | Properties | | --- | --- | | box-border | box-sizing: border-box; | | box-content | box-sizing: content-box; | Basic usage ----------- ### Including borders and padding Use `box-border` to set an element’s `box-sizing` to `border-box`, telling the browser to include the element’s borders and padding when you give it a height or width. This means a 100px × 100px element with a 2px border and 4px of padding on all sides will be rendered as 100px × 100px, with an internal content area of 88px × 88px. Tailwind makes this the default for all elements in our [preflight base styles](preflight). ``` <div class="box-border h-32 w-32 p-4 border-4 ..."> <!-- ... --> </div> ``` ### Excluding borders and padding Use `box-content` to set an element’s `box-sizing` to `content-box`, telling the browser to add borders and padding on top of the element’s specified width or height. This means a 100px × 100px element with a 2px border and 4px of padding on all sides will actually be rendered as 112px × 112px, with an internal content area of 100px × 100px. ``` <div class="box-content h-32 w-32 p-4 border-4 ..."> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:box-content` to only apply the `box-content` utility on hover. ``` <div class="box-border hover:box-content"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:box-content` to apply the `box-content` utility at only medium screen sizes and above. ``` <div class="box-border md:box-content"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/box-sizingClear ===== Utilities for controlling the wrapping of content around an element. Quick reference --------------- | Class | Properties | | --- | --- | | clear-left | clear: left; | | clear-right | clear: right; | | clear-both | clear: both; | | clear-none | clear: none; | Basic usage ----------- ### Clearing left-floated elements Use `clear-left` to position an element below any preceding left-floated elements. ``` <img class="float-left ..." src="path/to/image.jpg"> <img class="float-right ..." src="path/to/image.jpg"> <p class="clear-left ...">Maybe we can live without libraries...</p> ``` ### Clearing right-floated elements Use `clear-right` to position an element below any preceding right-floated elements. ``` <img class="float-left ..." src="path/to/image.jpg"> <img class="float-right ..." src="path/to/image.jpg"> <p class="clear-right ...">Maybe we can live without libraries...</p> ``` ### Clearing all floated elements Use `clear-both` to position an element below all preceding floated elements. ``` <img class="float-left ..." src="path/to/image.jpg"> <img class="float-right ..." src="path/to/image.jpg"> <p class="clear-both ...">Maybe we can live without libraries...</p> ``` ### Disabling applied clears Use `clear-none` to reset any clears that are applied to an element. This is the default value for the clear property. ``` <img class="float-left ..." src="path/to/image.jpg"> <img class="float-right ..." src="path/to/image.jpg"> <p class="clear-none ...">Maybe we can live without libraries...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:clear-none` to only apply the `clear-none` utility on hover. ``` <p class="clear-left hover:clear-none"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:clear-none` to apply the `clear-none` utility at only medium screen sizes and above. ``` <p class="clear-left md:clear-none"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/clearIsolation ========= Utilities for controlling whether an element should explicitly create a new stacking context. Quick reference --------------- | Class | Properties | | --- | --- | | isolate | isolation: isolate; | | isolation-auto | isolation: auto; | Basic usage ----------- ### Setting the stacking context Use the `isolate` and `isolation-auto` utilities to control whether an element should explicitly create a new stacking context. ``` <div class="isolate ..."> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:isolation-auto` to only apply the `isolation-auto` utility on hover. ``` <div class="isolate hover:isolation-auto"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:isolation-auto` to apply the `isolation-auto` utility at only medium screen sizes and above. ``` <div class="isolate md:isolation-auto"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/isolationObject Fit ========== Utilities for controlling how a replaced element's content should be resized. Quick reference --------------- | Class | Properties | | --- | --- | | object-contain | object-fit: contain; | | object-cover | object-fit: cover; | | object-fill | object-fit: fill; | | object-none | object-fit: none; | | object-scale-down | object-fit: scale-down; | Basic usage ----------- ### Resizing to cover a container Resize an element’s content to cover its container using `object-cover`. ``` <div class="bg-indigo-300 ..."> <img class="object-cover h-48 w-96 ..."> </div> ``` ### Containing an element Resize an element’s content to stay contained within its container using `object-contain`. ``` <div class="bg-purple-300 ..."> <img class="object-contain h-48 w-96 ..."> </div> ``` ### Stretching to fit a container Stretch an element’s content to fit its container using `object-fill`. ``` <div class="bg-sky-300 ..."> <img class="object-fill h-48 w-96 ..."> </div> ``` ### Scaling down if too large Display an element’s content at its original size but scale it down to fit its container if necessary using `object-scale-down`. ``` <div class="bg-cyan-300"> <img class="object-scale-down h-48 w-96 ..."> </div> ``` ### Using an element’s original size Display an element’s content at its original size ignoring the container size using `object-none`. ``` <div class="bg-yellow-300"> <img class="object-none h-48 w-96 ..."> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:object-scale-down` to only apply the `object-scale-down` utility on hover. ``` <img class="object-contain hover:object-scale-down"> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:object-scale-down` to apply the `object-scale-down` utility at only medium screen sizes and above. ``` <img class="object-contain md:object-scale-down"> ``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/object-fitObject Position =============== Utilities for controlling how a replaced element's content should be positioned within its container. Quick reference --------------- | Class | Properties | | --- | --- | | object-bottom | object-position: bottom; | | object-center | object-position: center; | | object-left | object-position: left; | | object-left-bottom | object-position: left bottom; | | object-left-top | object-position: left top; | | object-right | object-position: right; | | object-right-bottom | object-position: right bottom; | | object-right-top | object-position: right top; | | object-top | object-position: top; | Basic usage ----------- ### Positioning a replaced element Use the `object-{side}` utilities to specify how a replaced element’s content should be positioned within its container. ``` <img class="object-none object-left-top bg-yellow-300 w-24 h-24 ..." src="..."> <img class="object-none object-top bg-yellow-300 w-24 h-24 ..." src="..."> <img class="object-none object-right-top bg-yellow-300 w-24 h-24 ..." src="..."> <img class="object-none object-left bg-yellow-300 w-24 h-24 ..." src="..."> <img class="object-none object-center bg-yellow-300 w-24 h-24 ..." src="..."> <img class="object-none object-right bg-yellow-300 w-24 h-24 ..." src="..."> <img class="object-none object-left-bottom bg-yellow-300 w-24 h-24 ..." src="..."> <img class="object-none object-bottom bg-yellow-300 w-24 h-24 ..." src="..."> <img class="object-none object-right-bottom bg-yellow-300 w-24 h-24 ..." src="..."> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:object-top` to only apply the `object-top` utility on hover. ``` <img class="object-center hover:object-top" src="..."> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:object-top` to apply the `object-top` utility at only medium screen sizes and above. ``` <img class="object-center md:object-top" src="..."> ``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides nine object position utilities. You can customize these values by editing `theme.objectPosition` or `theme.extend.objectPosition` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { objectPosition: { 'center-bottom': 'center bottom', } }, } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `object-position` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <img class="object-[center_bottom]" src="..."> ``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/object-positionOverflow ======== Utilities for controlling how an element handles content that is too large for the container. Quick reference --------------- | Class | Properties | | --- | --- | | overflow-auto | overflow: auto; | | overflow-hidden | overflow: hidden; | | overflow-clip | overflow: clip; | | overflow-visible | overflow: visible; | | overflow-scroll | overflow: scroll; | | overflow-x-auto | overflow-x: auto; | | overflow-y-auto | overflow-y: auto; | | overflow-x-hidden | overflow-x: hidden; | | overflow-y-hidden | overflow-y: hidden; | | overflow-x-clip | overflow-x: clip; | | overflow-y-clip | overflow-y: clip; | | overflow-x-visible | overflow-x: visible; | | overflow-y-visible | overflow-y: visible; | | overflow-x-scroll | overflow-x: scroll; | | overflow-y-scroll | overflow-y: scroll; | Basic usage ----------- ### Showing content that overflows Use `overflow-visible` to prevent content within an element from being clipped. Note that any content that overflows the bounds of the element will then be visible. ``` <div class="overflow-visible ..."></div> ``` ### Hiding content that overflows Use `overflow-hidden` to clip any content within an element that overflows the bounds of that element. ``` <div class="overflow-hidden ..."></div> ``` ### Scrolling if needed Use `overflow-auto` to add scrollbars to an element in the event that its content overflows the bounds of that element. Unlike `overflow-scroll`, which always shows scrollbars, this utility will only show them if scrolling is necessary. ``` <div class="overflow-auto ..."></div> ``` ### Scrolling horizontally if needed Use `overflow-x-auto` to allow horizontal scrolling if needed. ``` <div class="overflow-x-auto ..."></div> ``` ### Scrolling vertically if needed Use `overflow-y-auto` to allow vertical scrolling if needed. ``` <div class="overflow-y-auto h-32 ..."></div> ``` ### Scrolling horizontally always Use `overflow-x-scroll` to allow horizontal scrolling and always show scrollbars unless always-visible scrollbars are disabled by the operating system. ``` <div class="overflow-x-scroll ..."></div> ``` ### Scrolling vertically always Use `overflow-y-scroll` to allow vertical scrolling and always show scrollbars unless always-visible scrollbars are disabled by the operating system. ``` <div class="overflow-y-scroll ..."></div> ``` ### Scrolling in all directions Use `overflow-scroll` to add scrollbars to an element. Unlike `overflow-auto`, which only shows scrollbars if they are necessary, this utility always shows them. Note that some operating systems (like macOS) hide unnecessary scrollbars regardless of this setting. ``` <div class="overflow-scroll ..."></div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:overflow-scroll` to only apply the `overflow-scroll` utility on hover. ``` <div class="overflow-auto hover:overflow-scroll"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:overflow-scroll` to apply the `overflow-scroll` utility at only medium screen sizes and above. ``` <div class="overflow-auto md:overflow-scroll"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/overflowOverscroll Behavior =================== Utilities for controlling how the browser behaves when reaching the boundary of a scrolling area. Quick reference --------------- | Class | Properties | | --- | --- | | overscroll-auto | overscroll-behavior: auto; | | overscroll-contain | overscroll-behavior: contain; | | overscroll-none | overscroll-behavior: none; | | overscroll-y-auto | overscroll-behavior-y: auto; | | overscroll-y-contain | overscroll-behavior-y: contain; | | overscroll-y-none | overscroll-behavior-y: none; | | overscroll-x-auto | overscroll-behavior-x: auto; | | overscroll-x-contain | overscroll-behavior-x: contain; | | overscroll-x-none | overscroll-behavior-x: none; | Basic usage ----------- ### Preventing parent overscrolling Use `overscroll-contain` to prevent scrolling in the target area from triggering scrolling in the parent element, but preserve “bounce” effects when scrolling past the end of the container in operating systems that support it. ``` <div class="overscroll-contain ...">Well, let me tell you something, ...</div> ``` ### Preventing overscroll bouncing Use `overscroll-none` to prevent scrolling in the target area from triggering scrolling in the parent element, and also prevent “bounce” effects when scrolling past the end of the container. ``` <div class="overscroll-none ...">Well, let me tell you something, ...</div> ``` ### Using the default overscroll behavior Use `overscroll-auto` to make it possible for the user to continue scrolling a parent scroll area when they reach the boundary of the primary scroll area. ``` <div class="overscroll-auto ...">Well, let me tell you something, ...</div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:overscroll-contain` to only apply the `overscroll-contain` utility on hover. ``` <div class="overscroll-auto hover:overscroll-contain"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:overscroll-contain` to apply the `overscroll-contain` utility at only medium screen sizes and above. ``` <div class="overscroll-auto md:overscroll-contain"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/overscroll-behaviorPosition ======== Utilities for controlling how an element is positioned in the DOM. Quick reference --------------- | Class | Properties | | --- | --- | | static | position: static; | | fixed | position: fixed; | | absolute | position: absolute; | | relative | position: relative; | | sticky | position: sticky; | Basic usage ----------- ### Statically positioning elements Use `static` to position an element according to the normal flow of the document. Any [offsets](top-right-bottom-left) will be ignored and the element will not act as a position reference for absolutely positioned children. ``` <div class="static ..."> <p>Static parent</p> <div class="absolute bottom-0 left-0 ..."> <p>Absolute child</p> </div> </div> ``` ### Relatively positioning elements Use `relative` to position an element according to the normal flow of the document. Any [offsets](top-right-bottom-left) are calculated relative to the element’s normal position and the element *will* act as a position reference for absolutely positioned children. ``` <div class="relative ..."> <p>Relative parent</p> <div class="absolute bottom-0 left-0 ..."> <p>Absolute child</p> </div> </div> ``` ### Absolutely positioning elements Use `absolute` to position an element *outside* of the normal flow of the document, causing neighboring elements to act as if the element doesn’t exist. Any [offsets](top-right-bottom-left) are calculated relative to the nearest parent that has a position other than `static`, and the element *will* act as a position reference for other absolutely positioned children. ``` <div class="static ..."> <!-- Static parent --> <div class="static ..."><p>Static child</p></div> <div class="inline-block ..."><p>Static sibling</p></div> <!-- Static parent --> <div class="absolute ..."><p>Absolute child</p></div> <div class="inline-block ..."><p>Static sibling</p></div> </div> ``` ### Fixed positioning elements Use `fixed` to position an element relative to the browser window. Any [offsets](top-right-bottom-left) are calculated relative to the viewport and the element *will* act as a position reference for absolutely positioned children. ``` <div class="relative"> <div class="fixed top-0 left-0 right-0">Contacts</div> <div> <div> <img src="..." /> <strong><NAME></strong> </div> <div> <img src="..." /> <strong><NAME></strong> </div> <!-- ... --> </div> </div> ``` ### Sticky positioning elements Use `sticky` to position an element as `relative` until it crosses a specified threshold, then treat it as fixed until its parent is off screen. Any [offsets](top-right-bottom-left) are calculated relative to the element’s normal position and the element *will* act as a position reference for absolutely positioned children. ``` <div> <div> <div class="sticky top-0 ...">A</div> <div> <div> <img src="..." /> <strong><NAME></strong> </div> <div> <img src="..." /> <strong><NAME></strong> </div> <!-- ... --> </div> </div> <div> <div class="sticky top-0">B</div> <div> <div> <img src="..." /> <strong><NAME></strong> </div> <!-- ... --> </div> </div> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:absolute` to only apply the `absolute` utility on hover. ``` <div class="relative hover:absolute"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:absolute` to apply the `absolute` utility at only medium screen sizes and above. ``` <div class="relative md:absolute"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/positionTop / Right / Bottom / Left =========================== Utilities for controlling the placement of positioned elements. Quick reference --------------- | Class | Properties | | --- | --- | | inset-0 | inset: 0px; | | inset-x-0 | left: 0px; right: 0px; | | inset-y-0 | top: 0px; bottom: 0px; | | start-0 | inset-inline-start: 0px; | | end-0 | inset-inline-end: 0px; | | top-0 | top: 0px; | | right-0 | right: 0px; | | bottom-0 | bottom: 0px; | | left-0 | left: 0px; | | inset-px | inset: 1px; | | inset-x-px | left: 1px; right: 1px; | | inset-y-px | top: 1px; bottom: 1px; | | start-px | inset-inline-start: 1px; | | end-px | inset-inline-end: 1px; | | top-px | top: 1px; | | right-px | right: 1px; | | bottom-px | bottom: 1px; | | left-px | left: 1px; | | inset-0.5 | inset: 0.125rem; /* 2px */ | | inset-x-0.5 | left: 0.125rem; /* 2px */ right: 0.125rem; /* 2px */ | | inset-y-0.5 | top: 0.125rem; /* 2px */ bottom: 0.125rem; /* 2px */ | | start-0.5 | inset-inline-start: 0.125rem; /* 2px */ | | end-0.5 | inset-inline-end: 0.125rem; /* 2px */ | | top-0.5 | top: 0.125rem; /* 2px */ | | right-0.5 | right: 0.125rem; /* 2px */ | | bottom-0.5 | bottom: 0.125rem; /* 2px */ | | left-0.5 | left: 0.125rem; /* 2px */ | | inset-1 | inset: 0.25rem; /* 4px */ | | inset-x-1 | left: 0.25rem; /* 4px */ right: 0.25rem; /* 4px */ | | inset-y-1 | top: 0.25rem; /* 4px */ bottom: 0.25rem; /* 4px */ | | start-1 | inset-inline-start: 0.25rem; /* 4px */ | | end-1 | inset-inline-end: 0.25rem; /* 4px */ | | top-1 | top: 0.25rem; /* 4px */ | | right-1 | right: 0.25rem; /* 4px */ | | bottom-1 | bottom: 0.25rem; /* 4px */ | | left-1 | left: 0.25rem; /* 4px */ | | inset-1.5 | inset: 0.375rem; /* 6px */ | | inset-x-1.5 | left: 0.375rem; /* 6px */ right: 0.375rem; /* 6px */ | | inset-y-1.5 | top: 0.375rem; /* 6px */ bottom: 0.375rem; /* 6px */ | | start-1.5 | inset-inline-start: 0.375rem; /* 6px */ | | end-1.5 | inset-inline-end: 0.375rem; /* 6px */ | | top-1.5 | top: 0.375rem; /* 6px */ | | right-1.5 | right: 0.375rem; /* 6px */ | | bottom-1.5 | bottom: 0.375rem; /* 6px */ | | left-1.5 | left: 0.375rem; /* 6px */ | | inset-2 | inset: 0.5rem; /* 8px */ | | inset-x-2 | left: 0.5rem; /* 8px */ right: 0.5rem; /* 8px */ | | inset-y-2 | top: 0.5rem; /* 8px */ bottom: 0.5rem; /* 8px */ | | start-2 | inset-inline-start: 0.5rem; /* 8px */ | | end-2 | inset-inline-end: 0.5rem; /* 8px */ | | top-2 | top: 0.5rem; /* 8px */ | | right-2 | right: 0.5rem; /* 8px */ | | bottom-2 | bottom: 0.5rem; /* 8px */ | | left-2 | left: 0.5rem; /* 8px */ | | inset-2.5 | inset: 0.625rem; /* 10px */ | | inset-x-2.5 | left: 0.625rem; /* 10px */ right: 0.625rem; /* 10px */ | | inset-y-2.5 | top: 0.625rem; /* 10px */ bottom: 0.625rem; /* 10px */ | | start-2.5 | inset-inline-start: 0.625rem; /* 10px */ | | end-2.5 | inset-inline-end: 0.625rem; /* 10px */ | | top-2.5 | top: 0.625rem; /* 10px */ | | right-2.5 | right: 0.625rem; /* 10px */ | | bottom-2.5 | bottom: 0.625rem; /* 10px */ | | left-2.5 | left: 0.625rem; /* 10px */ | | inset-3 | inset: 0.75rem; /* 12px */ | | inset-x-3 | left: 0.75rem; /* 12px */ right: 0.75rem; /* 12px */ | | inset-y-3 | top: 0.75rem; /* 12px */ bottom: 0.75rem; /* 12px */ | | start-3 | inset-inline-start: 0.75rem; /* 12px */ | | end-3 | inset-inline-end: 0.75rem; /* 12px */ | | top-3 | top: 0.75rem; /* 12px */ | | right-3 | right: 0.75rem; /* 12px */ | | bottom-3 | bottom: 0.75rem; /* 12px */ | | left-3 | left: 0.75rem; /* 12px */ | | inset-3.5 | inset: 0.875rem; /* 14px */ | | inset-x-3.5 | left: 0.875rem; /* 14px */ right: 0.875rem; /* 14px */ | | inset-y-3.5 | top: 0.875rem; /* 14px */ bottom: 0.875rem; /* 14px */ | | start-3.5 | inset-inline-start: 0.875rem; /* 14px */ | | end-3.5 | inset-inline-end: 0.875rem; /* 14px */ | | top-3.5 | top: 0.875rem; /* 14px */ | | right-3.5 | right: 0.875rem; /* 14px */ | | bottom-3.5 | bottom: 0.875rem; /* 14px */ | | left-3.5 | left: 0.875rem; /* 14px */ | | inset-4 | inset: 1rem; /* 16px */ | | inset-x-4 | left: 1rem; /* 16px */ right: 1rem; /* 16px */ | | inset-y-4 | top: 1rem; /* 16px */ bottom: 1rem; /* 16px */ | | start-4 | inset-inline-start: 1rem; /* 16px */ | | end-4 | inset-inline-end: 1rem; /* 16px */ | | top-4 | top: 1rem; /* 16px */ | | right-4 | right: 1rem; /* 16px */ | | bottom-4 | bottom: 1rem; /* 16px */ | | left-4 | left: 1rem; /* 16px */ | | inset-5 | inset: 1.25rem; /* 20px */ | | inset-x-5 | left: 1.25rem; /* 20px */ right: 1.25rem; /* 20px */ | | inset-y-5 | top: 1.25rem; /* 20px */ bottom: 1.25rem; /* 20px */ | | start-5 | inset-inline-start: 1.25rem; /* 20px */ | | end-5 | inset-inline-end: 1.25rem; /* 20px */ | | top-5 | top: 1.25rem; /* 20px */ | | right-5 | right: 1.25rem; /* 20px */ | | bottom-5 | bottom: 1.25rem; /* 20px */ | | left-5 | left: 1.25rem; /* 20px */ | | inset-6 | inset: 1.5rem; /* 24px */ | | inset-x-6 | left: 1.5rem; /* 24px */ right: 1.5rem; /* 24px */ | | inset-y-6 | top: 1.5rem; /* 24px */ bottom: 1.5rem; /* 24px */ | | start-6 | inset-inline-start: 1.5rem; /* 24px */ | | end-6 | inset-inline-end: 1.5rem; /* 24px */ | | top-6 | top: 1.5rem; /* 24px */ | | right-6 | right: 1.5rem; /* 24px */ | | bottom-6 | bottom: 1.5rem; /* 24px */ | | left-6 | left: 1.5rem; /* 24px */ | | inset-7 | inset: 1.75rem; /* 28px */ | | inset-x-7 | left: 1.75rem; /* 28px */ right: 1.75rem; /* 28px */ | | inset-y-7 | top: 1.75rem; /* 28px */ bottom: 1.75rem; /* 28px */ | | start-7 | inset-inline-start: 1.75rem; /* 28px */ | | end-7 | inset-inline-end: 1.75rem; /* 28px */ | | top-7 | top: 1.75rem; /* 28px */ | | right-7 | right: 1.75rem; /* 28px */ | | bottom-7 | bottom: 1.75rem; /* 28px */ | | left-7 | left: 1.75rem; /* 28px */ | | inset-8 | inset: 2rem; /* 32px */ | | inset-x-8 | left: 2rem; /* 32px */ right: 2rem; /* 32px */ | | inset-y-8 | top: 2rem; /* 32px */ bottom: 2rem; /* 32px */ | | start-8 | inset-inline-start: 2rem; /* 32px */ | | end-8 | inset-inline-end: 2rem; /* 32px */ | | top-8 | top: 2rem; /* 32px */ | | right-8 | right: 2rem; /* 32px */ | | bottom-8 | bottom: 2rem; /* 32px */ | | left-8 | left: 2rem; /* 32px */ | | inset-9 | inset: 2.25rem; /* 36px */ | | inset-x-9 | left: 2.25rem; /* 36px */ right: 2.25rem; /* 36px */ | | inset-y-9 | top: 2.25rem; /* 36px */ bottom: 2.25rem; /* 36px */ | | start-9 | inset-inline-start: 2.25rem; /* 36px */ | | end-9 | inset-inline-end: 2.25rem; /* 36px */ | | top-9 | top: 2.25rem; /* 36px */ | | right-9 | right: 2.25rem; /* 36px */ | | bottom-9 | bottom: 2.25rem; /* 36px */ | | left-9 | left: 2.25rem; /* 36px */ | | inset-10 | inset: 2.5rem; /* 40px */ | | inset-x-10 | left: 2.5rem; /* 40px */ right: 2.5rem; /* 40px */ | | inset-y-10 | top: 2.5rem; /* 40px */ bottom: 2.5rem; /* 40px */ | | start-10 | inset-inline-start: 2.5rem; /* 40px */ | | end-10 | inset-inline-end: 2.5rem; /* 40px */ | | top-10 | top: 2.5rem; /* 40px */ | | right-10 | right: 2.5rem; /* 40px */ | | bottom-10 | bottom: 2.5rem; /* 40px */ | | left-10 | left: 2.5rem; /* 40px */ | | inset-11 | inset: 2.75rem; /* 44px */ | | inset-x-11 | left: 2.75rem; /* 44px */ right: 2.75rem; /* 44px */ | | inset-y-11 | top: 2.75rem; /* 44px */ bottom: 2.75rem; /* 44px */ | | start-11 | inset-inline-start: 2.75rem; /* 44px */ | | end-11 | inset-inline-end: 2.75rem; /* 44px */ | | top-11 | top: 2.75rem; /* 44px */ | | right-11 | right: 2.75rem; /* 44px */ | | bottom-11 | bottom: 2.75rem; /* 44px */ | | left-11 | left: 2.75rem; /* 44px */ | | inset-12 | inset: 3rem; /* 48px */ | | inset-x-12 | left: 3rem; /* 48px */ right: 3rem; /* 48px */ | | inset-y-12 | top: 3rem; /* 48px */ bottom: 3rem; /* 48px */ | | start-12 | inset-inline-start: 3rem; /* 48px */ | | end-12 | inset-inline-end: 3rem; /* 48px */ | | top-12 | top: 3rem; /* 48px */ | | right-12 | right: 3rem; /* 48px */ | | bottom-12 | bottom: 3rem; /* 48px */ | | left-12 | left: 3rem; /* 48px */ | | inset-14 | inset: 3.5rem; /* 56px */ | | inset-x-14 | left: 3.5rem; /* 56px */ right: 3.5rem; /* 56px */ | | inset-y-14 | top: 3.5rem; /* 56px */ bottom: 3.5rem; /* 56px */ | | start-14 | inset-inline-start: 3.5rem; /* 56px */ | | end-14 | inset-inline-end: 3.5rem; /* 56px */ | | top-14 | top: 3.5rem; /* 56px */ | | right-14 | right: 3.5rem; /* 56px */ | | bottom-14 | bottom: 3.5rem; /* 56px */ | | left-14 | left: 3.5rem; /* 56px */ | | inset-16 | inset: 4rem; /* 64px */ | | inset-x-16 | left: 4rem; /* 64px */ right: 4rem; /* 64px */ | | inset-y-16 | top: 4rem; /* 64px */ bottom: 4rem; /* 64px */ | | start-16 | inset-inline-start: 4rem; /* 64px */ | | end-16 | inset-inline-end: 4rem; /* 64px */ | | top-16 | top: 4rem; /* 64px */ | | right-16 | right: 4rem; /* 64px */ | | bottom-16 | bottom: 4rem; /* 64px */ | | left-16 | left: 4rem; /* 64px */ | | inset-20 | inset: 5rem; /* 80px */ | | inset-x-20 | left: 5rem; /* 80px */ right: 5rem; /* 80px */ | | inset-y-20 | top: 5rem; /* 80px */ bottom: 5rem; /* 80px */ | | start-20 | inset-inline-start: 5rem; /* 80px */ | | end-20 | inset-inline-end: 5rem; /* 80px */ | | top-20 | top: 5rem; /* 80px */ | | right-20 | right: 5rem; /* 80px */ | | bottom-20 | bottom: 5rem; /* 80px */ | | left-20 | left: 5rem; /* 80px */ | | inset-24 | inset: 6rem; /* 96px */ | | inset-x-24 | left: 6rem; /* 96px */ right: 6rem; /* 96px */ | | inset-y-24 | top: 6rem; /* 96px */ bottom: 6rem; /* 96px */ | | start-24 | inset-inline-start: 6rem; /* 96px */ | | end-24 | inset-inline-end: 6rem; /* 96px */ | | top-24 | top: 6rem; /* 96px */ | | right-24 | right: 6rem; /* 96px */ | | bottom-24 | bottom: 6rem; /* 96px */ | | left-24 | left: 6rem; /* 96px */ | | inset-28 | inset: 7rem; /* 112px */ | | inset-x-28 | left: 7rem; /* 112px */ right: 7rem; /* 112px */ | | inset-y-28 | top: 7rem; /* 112px */ bottom: 7rem; /* 112px */ | | start-28 | inset-inline-start: 7rem; /* 112px */ | | end-28 | inset-inline-end: 7rem; /* 112px */ | | top-28 | top: 7rem; /* 112px */ | | right-28 | right: 7rem; /* 112px */ | | bottom-28 | bottom: 7rem; /* 112px */ | | left-28 | left: 7rem; /* 112px */ | | inset-32 | inset: 8rem; /* 128px */ | | inset-x-32 | left: 8rem; /* 128px */ right: 8rem; /* 128px */ | | inset-y-32 | top: 8rem; /* 128px */ bottom: 8rem; /* 128px */ | | start-32 | inset-inline-start: 8rem; /* 128px */ | | end-32 | inset-inline-end: 8rem; /* 128px */ | | top-32 | top: 8rem; /* 128px */ | | right-32 | right: 8rem; /* 128px */ | | bottom-32 | bottom: 8rem; /* 128px */ | | left-32 | left: 8rem; /* 128px */ | | inset-36 | inset: 9rem; /* 144px */ | | inset-x-36 | left: 9rem; /* 144px */ right: 9rem; /* 144px */ | | inset-y-36 | top: 9rem; /* 144px */ bottom: 9rem; /* 144px */ | | start-36 | inset-inline-start: 9rem; /* 144px */ | | end-36 | inset-inline-end: 9rem; /* 144px */ | | top-36 | top: 9rem; /* 144px */ | | right-36 | right: 9rem; /* 144px */ | | bottom-36 | bottom: 9rem; /* 144px */ | | left-36 | left: 9rem; /* 144px */ | | inset-40 | inset: 10rem; /* 160px */ | | inset-x-40 | left: 10rem; /* 160px */ right: 10rem; /* 160px */ | | inset-y-40 | top: 10rem; /* 160px */ bottom: 10rem; /* 160px */ | | start-40 | inset-inline-start: 10rem; /* 160px */ | | end-40 | inset-inline-end: 10rem; /* 160px */ | | top-40 | top: 10rem; /* 160px */ | | right-40 | right: 10rem; /* 160px */ | | bottom-40 | bottom: 10rem; /* 160px */ | | left-40 | left: 10rem; /* 160px */ | | inset-44 | inset: 11rem; /* 176px */ | | inset-x-44 | left: 11rem; /* 176px */ right: 11rem; /* 176px */ | | inset-y-44 | top: 11rem; /* 176px */ bottom: 11rem; /* 176px */ | | start-44 | inset-inline-start: 11rem; /* 176px */ | | end-44 | inset-inline-end: 11rem; /* 176px */ | | top-44 | top: 11rem; /* 176px */ | | right-44 | right: 11rem; /* 176px */ | | bottom-44 | bottom: 11rem; /* 176px */ | | left-44 | left: 11rem; /* 176px */ | | inset-48 | inset: 12rem; /* 192px */ | | inset-x-48 | left: 12rem; /* 192px */ right: 12rem; /* 192px */ | | inset-y-48 | top: 12rem; /* 192px */ bottom: 12rem; /* 192px */ | | start-48 | inset-inline-start: 12rem; /* 192px */ | | end-48 | inset-inline-end: 12rem; /* 192px */ | | top-48 | top: 12rem; /* 192px */ | | right-48 | right: 12rem; /* 192px */ | | bottom-48 | bottom: 12rem; /* 192px */ | | left-48 | left: 12rem; /* 192px */ | | inset-52 | inset: 13rem; /* 208px */ | | inset-x-52 | left: 13rem; /* 208px */ right: 13rem; /* 208px */ | | inset-y-52 | top: 13rem; /* 208px */ bottom: 13rem; /* 208px */ | | start-52 | inset-inline-start: 13rem; /* 208px */ | | end-52 | inset-inline-end: 13rem; /* 208px */ | | top-52 | top: 13rem; /* 208px */ | | right-52 | right: 13rem; /* 208px */ | | bottom-52 | bottom: 13rem; /* 208px */ | | left-52 | left: 13rem; /* 208px */ | | inset-56 | inset: 14rem; /* 224px */ | | inset-x-56 | left: 14rem; /* 224px */ right: 14rem; /* 224px */ | | inset-y-56 | top: 14rem; /* 224px */ bottom: 14rem; /* 224px */ | | start-56 | inset-inline-start: 14rem; /* 224px */ | | end-56 | inset-inline-end: 14rem; /* 224px */ | | top-56 | top: 14rem; /* 224px */ | | right-56 | right: 14rem; /* 224px */ | | bottom-56 | bottom: 14rem; /* 224px */ | | left-56 | left: 14rem; /* 224px */ | | inset-60 | inset: 15rem; /* 240px */ | | inset-x-60 | left: 15rem; /* 240px */ right: 15rem; /* 240px */ | | inset-y-60 | top: 15rem; /* 240px */ bottom: 15rem; /* 240px */ | | start-60 | inset-inline-start: 15rem; /* 240px */ | | end-60 | inset-inline-end: 15rem; /* 240px */ | | top-60 | top: 15rem; /* 240px */ | | right-60 | right: 15rem; /* 240px */ | | bottom-60 | bottom: 15rem; /* 240px */ | | left-60 | left: 15rem; /* 240px */ | | inset-64 | inset: 16rem; /* 256px */ | | inset-x-64 | left: 16rem; /* 256px */ right: 16rem; /* 256px */ | | inset-y-64 | top: 16rem; /* 256px */ bottom: 16rem; /* 256px */ | | start-64 | inset-inline-start: 16rem; /* 256px */ | | end-64 | inset-inline-end: 16rem; /* 256px */ | | top-64 | top: 16rem; /* 256px */ | | right-64 | right: 16rem; /* 256px */ | | bottom-64 | bottom: 16rem; /* 256px */ | | left-64 | left: 16rem; /* 256px */ | | inset-72 | inset: 18rem; /* 288px */ | | inset-x-72 | left: 18rem; /* 288px */ right: 18rem; /* 288px */ | | inset-y-72 | top: 18rem; /* 288px */ bottom: 18rem; /* 288px */ | | start-72 | inset-inline-start: 18rem; /* 288px */ | | end-72 | inset-inline-end: 18rem; /* 288px */ | | top-72 | top: 18rem; /* 288px */ | | right-72 | right: 18rem; /* 288px */ | | bottom-72 | bottom: 18rem; /* 288px */ | | left-72 | left: 18rem; /* 288px */ | | inset-80 | inset: 20rem; /* 320px */ | | inset-x-80 | left: 20rem; /* 320px */ right: 20rem; /* 320px */ | | inset-y-80 | top: 20rem; /* 320px */ bottom: 20rem; /* 320px */ | | start-80 | inset-inline-start: 20rem; /* 320px */ | | end-80 | inset-inline-end: 20rem; /* 320px */ | | top-80 | top: 20rem; /* 320px */ | | right-80 | right: 20rem; /* 320px */ | | bottom-80 | bottom: 20rem; /* 320px */ | | left-80 | left: 20rem; /* 320px */ | | inset-96 | inset: 24rem; /* 384px */ | | inset-x-96 | left: 24rem; /* 384px */ right: 24rem; /* 384px */ | | inset-y-96 | top: 24rem; /* 384px */ bottom: 24rem; /* 384px */ | | start-96 | inset-inline-start: 24rem; /* 384px */ | | end-96 | inset-inline-end: 24rem; /* 384px */ | | top-96 | top: 24rem; /* 384px */ | | right-96 | right: 24rem; /* 384px */ | | bottom-96 | bottom: 24rem; /* 384px */ | | left-96 | left: 24rem; /* 384px */ | | inset-auto | inset: auto; | | inset-1/2 | inset: 50%; | | inset-1/3 | inset: 33.333333%; | | inset-2/3 | inset: 66.666667%; | | inset-1/4 | inset: 25%; | | inset-2/4 | inset: 50%; | | inset-3/4 | inset: 75%; | | inset-full | inset: 100%; | | inset-x-auto | left: auto; right: auto; | | inset-x-1/2 | left: 50%; right: 50%; | | inset-x-1/3 | left: 33.333333%; right: 33.333333%; | | inset-x-2/3 | left: 66.666667%; right: 66.666667%; | | inset-x-1/4 | left: 25%; right: 25%; | | inset-x-2/4 | left: 50%; right: 50%; | | inset-x-3/4 | left: 75%; right: 75%; | | inset-x-full | left: 100%; right: 100%; | | inset-y-auto | top: auto; bottom: auto; | | inset-y-1/2 | top: 50%; bottom: 50%; | | inset-y-1/3 | top: 33.333333%; bottom: 33.333333%; | | inset-y-2/3 | top: 66.666667%; bottom: 66.666667%; | | inset-y-1/4 | top: 25%; bottom: 25%; | | inset-y-2/4 | top: 50%; bottom: 50%; | | inset-y-3/4 | top: 75%; bottom: 75%; | | inset-y-full | top: 100%; bottom: 100%; | | start-auto | inset-inline-start: auto; | | start-1/2 | inset-inline-start: 50%; | | start-1/3 | inset-inline-start: 33.333333%; | | start-2/3 | inset-inline-start: 66.666667%; | | start-1/4 | inset-inline-start: 25%; | | start-2/4 | inset-inline-start: 50%; | | start-3/4 | inset-inline-start: 75%; | | start-full | inset-inline-start: 100%; | | end-auto | inset-inline-end: auto; | | end-1/2 | inset-inline-end: 50%; | | end-1/3 | inset-inline-end: 33.333333%; | | end-2/3 | inset-inline-end: 66.666667%; | | end-1/4 | inset-inline-end: 25%; | | end-2/4 | inset-inline-end: 50%; | | end-3/4 | inset-inline-end: 75%; | | end-full | inset-inline-end: 100%; | | top-auto | top: auto; | | top-1/2 | top: 50%; | | top-1/3 | top: 33.333333%; | | top-2/3 | top: 66.666667%; | | top-1/4 | top: 25%; | | top-2/4 | top: 50%; | | top-3/4 | top: 75%; | | top-full | top: 100%; | | right-auto | right: auto; | | right-1/2 | right: 50%; | | right-1/3 | right: 33.333333%; | | right-2/3 | right: 66.666667%; | | right-1/4 | right: 25%; | | right-2/4 | right: 50%; | | right-3/4 | right: 75%; | | right-full | right: 100%; | | bottom-auto | bottom: auto; | | bottom-1/2 | bottom: 50%; | | bottom-1/3 | bottom: 33.333333%; | | bottom-2/3 | bottom: 66.666667%; | | bottom-1/4 | bottom: 25%; | | bottom-2/4 | bottom: 50%; | | bottom-3/4 | bottom: 75%; | | bottom-full | bottom: 100%; | | left-auto | left: auto; | | left-1/2 | left: 50%; | | left-1/3 | left: 33.333333%; | | left-2/3 | left: 66.666667%; | | left-1/4 | left: 25%; | | left-2/4 | left: 50%; | | left-3/4 | left: 75%; | | left-full | left: 100%; | Basic usage ----------- ### Placing a positioned element Use the `{top|right|bottom|left|inset}-{size}` utilities to set the horizontal or vertical position of a [positioned element](position). ``` <!-- Pin to top left corner --> <div class="relative h-32 w-32 ..."> <div class="absolute left-0 top-0 h-16 w-16 ...">01</div> </div<!-- Span top edge --> <div class="relative h-32 w-32 ..."> <div class="absolute inset-x-0 top-0 h-16 ...">02</div> </div<!-- Pin to top right corner --> <div class="relative h-32 w-32 ..."> <div class="absolute top-0 right-0 h-16 w-16 ...">03</div> </div<!-- Span left edge --> <div class="relative h-32 w-32 ..."> <div class="absolute inset-y-0 left-0 w-16 ...">04</div> </div<!-- Fill entire parent --> <div class="relative h-32 w-32 ..."> <div class="absolute inset-0 ...">05</div> </div<!-- Span right edge --> <div class="relative h-32 w-32 ..."> <div class="absolute inset-y-0 right-0 w-16 ...">06</div> </div<!-- Pin to bottom left corner --> <div class="relative h-32 w-32 ..."> <div class="absolute bottom-0 left-0 h-16 w-16 ...">07</div> </div<!-- Span bottom edge --> <div class="relative h-32 w-32 ..."> <div class="absolute inset-x-0 bottom-0 h-16 ...">08</div> </div<!-- Pin to bottom right corner --> <div class="relative h-32 w-32 ..."> <div class="absolute bottom-0 right-0 h-16 w-16 ...">09</div> </div> ``` ### Using negative values To use a negative top/right/bottom/left value, prefix the class name with a dash to convert it to a negative value. ``` <div class="relative h-32 w-32 ..."> <div class="absolute h-14 w-14 -left-4 -top-4 ..."></div> </div> ``` ### Using logical properties Use the `start-*` and `end-*` utilities to set the `inset-inline-start` and `inset-inline-end` [logical properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties/Basic_concepts), which map to either the left or right side based on the text direction. ``` <div dir="ltr"> <div class="relative h-32 w-32 ..."> <div class="absolute h-14 w-14 top-0 start-0 ..."></div> </div> <div<div dir="rtl"> <div class="relative h-32 w-32 ..."> <div class="absolute h-14 w-14 top-0 start-0 ..."></div> </div> <div> ``` For more control, you can also use the [LTR and RTL modifiers](hover-focus-and-other-states#rtl-support) to conditionally apply specific styles depending on the current text direction. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:top-6` to only apply the `top-6` utility on hover. ``` <div class="top-4 hover:top-6"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:top-6` to apply the `top-6` utility at only medium screen sizes and above. ``` <div class="top-4 md:top-6"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides top/right/bottom/left/inset utilities for a combination of the [default spacing scale](customizing-spacing#default-spacing-scale), `auto`, `full` as well as some additional fraction values. You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '3px': '3px', } } } } ``` Alternatively, you can customize just the top/right/bottom/left/inset scale by editing `theme.inset` or `theme.extend.inset` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { inset: { '3px': '3px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `top/right/bottom/left` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="top-[3px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/top-right-bottom-leftVisibility ========== Utilities for controlling the visibility of an element. Quick reference --------------- | Class | Properties | | --- | --- | | visible | visibility: visible; | | invisible | visibility: hidden; | | collapse | visibility: collapse; | Basic usage ----------- ### Making elements invisible Use `invisible` to hide an element, but still maintain its place in the DOM, affecting the layout of other elements (compare with `hidden` from the [display](display#hidden) documentation). ``` <div class="grid grid-cols-3 gap-4"> <div>01</div> <div class="invisible ...">02</div> <div>03</div> </div> ``` ### Collapsing elements Use `collapse` to hide table rows, row groups, columns, and column groups as if they were set to `display: none`, but without impacting the size of other rows and columns. This makes it possible to dynamically toggle rows and columns without affecting the table layout. ``` <table> <thead> <tr> <th>Invoice #</th> <th>Client</th> <th>Amount</th> </tr> </thead> <tbody> <tr> <td>#100</td> <td>Pendant Publishing</td> <td>$2,000.00</td> </tr> <tr class="collapse"> <td>#101</td> <td>Kruger Industrial Smoothing</td> <td>$545.00</td> </tr> <tr> <td>#102</td> <td><NAME></td> <td>$10,000.25</td> </tr> </tbody> </table> ``` ### Making elements visible Use `visible` to make an element visible. This is mostly useful for undoing the `invisible` utility at different screen sizes. ``` <div class="grid grid-cols-3 gap-4"> <div>01</div> <div class="visible ...">02</div> <div>03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:invisible` to only apply the `invisible` utility on hover. ``` <div class="visible hover:invisible"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:invisible` to apply the `invisible` utility at only medium screen sizes and above. ``` <div class="visible md:invisible"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/visibilityZ-Index ======= Utilities for controlling the stack order of an element. Quick reference --------------- | Class | Properties | | --- | --- | | z-0 | z-index: 0; | | z-10 | z-index: 10; | | z-20 | z-index: 20; | | z-30 | z-index: 30; | | z-40 | z-index: 40; | | z-50 | z-index: 50; | | z-auto | z-index: auto; | Basic usage ----------- ### Setting the z-index Control the stack order (or three-dimensional positioning) of an element in Tailwind, regardless of order it has been displayed, using the `z-{index}` utilities. ``` <div class="z-40 ...">05</div> <div class="z-30 ...">04</div> <div class="z-20 ...">03</div> <div class="z-10 ...">02</div> <div class="z-0 ...">01</div> ``` ### Using negative values To use a negative z-index value, prefix the class name with a dash to convert it to a negative value. ``` <div class="-z-50"> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:z-50` to only apply the `z-50` utility on hover. ``` <div class="z-0 hover:z-50"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:z-50` to apply the `z-50` utility at only medium screen sizes and above. ``` <div class="z-0 md:z-50"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides six numeric `z-index` utilities and an `auto` utility. You can customize these values by editing `theme.zIndex` or `theme.extend.zIndex` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { zIndex: { '100': '100', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `z-index` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="z-[100]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/z-indexFlex Basis ========== Utilities for controlling the initial size of flex items. Quick reference --------------- | Class | Properties | | --- | --- | | basis-0 | flex-basis: 0px; | | basis-1 | flex-basis: 0.25rem; /* 4px */ | | basis-2 | flex-basis: 0.5rem; /* 8px */ | | basis-3 | flex-basis: 0.75rem; /* 12px */ | | basis-4 | flex-basis: 1rem; /* 16px */ | | basis-5 | flex-basis: 1.25rem; /* 20px */ | | basis-6 | flex-basis: 1.5rem; /* 24px */ | | basis-7 | flex-basis: 1.75rem; /* 28px */ | | basis-8 | flex-basis: 2rem; /* 32px */ | | basis-9 | flex-basis: 2.25rem; /* 36px */ | | basis-10 | flex-basis: 2.5rem; /* 40px */ | | basis-11 | flex-basis: 2.75rem; /* 44px */ | | basis-12 | flex-basis: 3rem; /* 48px */ | | basis-14 | flex-basis: 3.5rem; /* 56px */ | | basis-16 | flex-basis: 4rem; /* 64px */ | | basis-20 | flex-basis: 5rem; /* 80px */ | | basis-24 | flex-basis: 6rem; /* 96px */ | | basis-28 | flex-basis: 7rem; /* 112px */ | | basis-32 | flex-basis: 8rem; /* 128px */ | | basis-36 | flex-basis: 9rem; /* 144px */ | | basis-40 | flex-basis: 10rem; /* 160px */ | | basis-44 | flex-basis: 11rem; /* 176px */ | | basis-48 | flex-basis: 12rem; /* 192px */ | | basis-52 | flex-basis: 13rem; /* 208px */ | | basis-56 | flex-basis: 14rem; /* 224px */ | | basis-60 | flex-basis: 15rem; /* 240px */ | | basis-64 | flex-basis: 16rem; /* 256px */ | | basis-72 | flex-basis: 18rem; /* 288px */ | | basis-80 | flex-basis: 20rem; /* 320px */ | | basis-96 | flex-basis: 24rem; /* 384px */ | | basis-auto | flex-basis: auto; | | basis-px | flex-basis: 1px; | | basis-0.5 | flex-basis: 0.125rem; /* 2px */ | | basis-1.5 | flex-basis: 0.375rem; /* 6px */ | | basis-2.5 | flex-basis: 0.625rem; /* 10px */ | | basis-3.5 | flex-basis: 0.875rem; /* 14px */ | | basis-1/2 | flex-basis: 50%; | | basis-1/3 | flex-basis: 33.333333%; | | basis-2/3 | flex-basis: 66.666667%; | | basis-1/4 | flex-basis: 25%; | | basis-2/4 | flex-basis: 50%; | | basis-3/4 | flex-basis: 75%; | | basis-1/5 | flex-basis: 20%; | | basis-2/5 | flex-basis: 40%; | | basis-3/5 | flex-basis: 60%; | | basis-4/5 | flex-basis: 80%; | | basis-1/6 | flex-basis: 16.666667%; | | basis-2/6 | flex-basis: 33.333333%; | | basis-3/6 | flex-basis: 50%; | | basis-4/6 | flex-basis: 66.666667%; | | basis-5/6 | flex-basis: 83.333333%; | | basis-1/12 | flex-basis: 8.333333%; | | basis-2/12 | flex-basis: 16.666667%; | | basis-3/12 | flex-basis: 25%; | | basis-4/12 | flex-basis: 33.333333%; | | basis-5/12 | flex-basis: 41.666667%; | | basis-6/12 | flex-basis: 50%; | | basis-7/12 | flex-basis: 58.333333%; | | basis-8/12 | flex-basis: 66.666667%; | | basis-9/12 | flex-basis: 75%; | | basis-10/12 | flex-basis: 83.333333%; | | basis-11/12 | flex-basis: 91.666667%; | | basis-full | flex-basis: 100%; | Basic usage ----------- ### Setting the flex basis Use the `basis-{size}` utilities to set the initial size of flex items. ``` <div class="flex flex-row"> <div class="basis-1/4">01</div> <div class="basis-1/4">02</div> <div class="basis-1/2">03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:basis-1/2` to only apply the `basis-1/2` utility on hover. ``` <div class="basis-1/3 hover:basis-1/2"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:basis-1/3` to apply the `basis-1/3` utility at only medium screen sizes and above. ``` <div class="flex flex-row"> <div class="basis-1/4 md:basis-1/3">01</div> <div class="basis-1/4 md:basis-1/3">02</div> <div class="basis-1/2 md:basis-1/3">03</div> </div> ``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme The default flex basis scale is a combination of the [default spacing scale](customizing-spacing#default-spacing-scale) as well as a set of percentage based values. You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '112': '28rem', '128': '32rem', } } } } ``` Alternatively, you can customize just the flex basis scale by editing `theme.flexBasis` or `theme.extend.flexBasis` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { flexBasis: { '1/7': '14.2857143%', '2/7': '28.5714286%', '3/7': '42.8571429%', '4/7': '57.1428571%', '5/7': '71.4285714%', '6/7': '85.7142857%', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `flex-basis` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="basis-[14.2857143%]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/flex-basisFlex Direction ============== Utilities for controlling the direction of flex items. Quick reference --------------- | Class | Properties | | --- | --- | | flex-row | flex-direction: row; | | flex-row-reverse | flex-direction: row-reverse; | | flex-col | flex-direction: column; | | flex-col-reverse | flex-direction: column-reverse; | Basic usage ----------- ### Row Use `flex-row` to position flex items horizontally in the same direction as text: ``` <div class="flex flex-row ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Row reversed Use `flex-row-reverse` to position flex items horizontally in the opposite direction: ``` <div class="flex flex-row-reverse ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Column Use `flex-col` to position flex items vertically: ``` <div class="flex flex-col ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Column reversed Use `flex-col-reverse` to position flex items vertically in the opposite direction: ``` <div class="flex flex-col-reverse ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:flex-row` to only apply the `flex-row` utility on hover. ``` <div class="flex flex-col hover:flex-row"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:flex-row` to apply the `flex-row` utility at only medium screen sizes and above. ``` <div class="flex flex-col md:flex-row"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/flex-directionFlex Wrap ========= Utilities for controlling how flex items wrap. Quick reference --------------- | Class | Properties | | --- | --- | | flex-wrap | flex-wrap: wrap; | | flex-wrap-reverse | flex-wrap: wrap-reverse; | | flex-nowrap | flex-wrap: nowrap; | Basic usage ----------- ### Don’t wrap Use `flex-nowrap` to prevent flex items from wrapping, causing inflexible items to overflow the container if necessary: ``` <div class="flex flex-nowrap"> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Wrap normally Use `flex-wrap` to allow flex items to wrap: ``` <div class="flex flex-wrap"> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Wrap reversed Use `flex-wrap-reverse` to wrap flex items in the reverse direction: ``` <div class="flex flex-wrap-reverse"> <div>01</div> <div>02</div> <div>03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:flex-wrap-reverse` to only apply the `flex-wrap-reverse` utility on hover. ``` <div class="flex flex-wrap hover:flex-wrap-reverse"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:flex-wrap-reverse` to apply the `flex-wrap-reverse` utility at only medium screen sizes and above. ``` <div class="flex flex-wrap md:flex-wrap-reverse"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/flex-wrapFlex ==== Utilities for controlling how flex items both grow and shrink. Quick reference --------------- | Class | Properties | | --- | --- | | flex-1 | flex: 1 1 0%; | | flex-auto | flex: 1 1 auto; | | flex-initial | flex: 0 1 auto; | | flex-none | flex: none; | Basic usage ----------- ### Initial Use `flex-initial` to allow a flex item to shrink but not grow, taking into account its initial size: ``` <div class="flex"> <div class="flex-none w-14 h-14"> 01 </div> <div class="flex-initial w-64 ..."> 02 </div> <div class="flex-initial w-32 ..."> 03 </div> </div> ``` ### Flex 1 Use `flex-1` to allow a flex item to grow and shrink as needed, ignoring its initial size: ``` <div class="flex"> <div class="flex-none ..."> 01 </div> <div class="flex-1 w-64 ..."> 02 </div> <div class="flex-1 w-32 ..."> 03 </div> </div> ``` ### Auto Use `flex-auto` to allow a flex item to grow and shrink, taking into account its initial size: ``` <div class="flex ..."> <div class="flex-none ..."> 01 </div> <div class="flex-auto w-64 ..."> 02 </div> <div class="flex-auto w-32 ..."> 03 </div> </div> ``` ### None Use `flex-none` to prevent a flex item from growing or shrinking: ``` <div class="flex ..."> <div class="flex-none w-14 h-14 ..."> 01 </div> <div class="flex-none ..."> 02 </div> <div class="flex-1 ..."> 03 </div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:flex-1` to only apply the `flex-1` utility on hover. ``` <div class="flex-none hover:flex-1"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:flex-1` to apply the `flex-1` utility at only medium screen sizes and above. ``` <div class="flex-none md:flex-1"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides four `flex` utilities. You can customize these values by editing `theme.flex` or `theme.extend.flex` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { flex: { '2': '2 2 0%' } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `flex` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="flex-[2_2_0%]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/flexFlex Grow ========= Utilities for controlling how flex items grow. Quick reference --------------- | Class | Properties | | --- | --- | | grow | flex-grow: 1; | | grow-0 | flex-grow: 0; | Basic usage ----------- ### Grow Use `grow` to allow a flex item to grow to fill any available space: ``` <div class="flex ..."> <div class="flex-none w-14 h-14 ..."> 01 </div> <div class="grow h-14 ..."> 02 </div> <div class="flex-none w-14 h-14 ..."> 03 </div> </div> ``` ### Don’t grow Use `grow-0` to prevent a flex item from growing: ``` <div class="flex ..."> <div class="grow h-14 ..."> 01 </div> <div class="grow-0 h-14 ..."> 02 </div> <div class="grow h-14 ..."> 03 </div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:grow-0` to only apply the `grow-0` utility on hover. ``` <div class="grow hover:grow-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:grow-0` to apply the `grow-0` utility at only medium screen sizes and above. ``` <div class="grow md:grow-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides two `grow` utilities. You can customize these values by editing `theme.flexGrow` or `theme.extend.flexGrow` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { flexGrow: { 2: '2' } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `flex-grow` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="grow-[2]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/flex-growFlex Shrink =========== Utilities for controlling how flex items shrink. Quick reference --------------- | Class | Properties | | --- | --- | | shrink | flex-shrink: 1; | | shrink-0 | flex-shrink: 0; | Basic usage ----------- ### Shrink Use `shrink` to allow a flex item to shrink if needed: ``` <div class="flex ..."> <div class="flex-none w-14 h-14 ..."> 01 </div> <div class="shrink w-64 h-14 ..."> 02 </div> <div class="flex-none w-14 h-14 ..."> 03 </div> </div> ``` ### Don’t shrink Use `shrink-0` to prevent a flex item from shrinking: ``` <div class="flex ..."> <div class="flex-1 h-16 ..."> 01 </div> <div class="shrink-0 h-16 w-32 ..."> 02 </div> <div class="flex-1 h-16 ..."> 03 </div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:shrink-0` to only apply the `shrink-0` utility on hover. ``` <div class="shrink hover:shrink-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:shrink-0` to apply the `shrink-0` utility at only medium screen sizes and above. ``` <div class="shrink md:shrink-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides two `shrink` utilities. You can customize these values by editing `theme.flexShrink` or `theme.extend.flexShrink` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { flexShrink: { 2: '2' } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `flex-shrink` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="shrink-[2]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/flex-shrinkOrder ===== Utilities for controlling the order of flex and grid items. Quick reference --------------- | Class | Properties | | --- | --- | | order-1 | order: 1; | | order-2 | order: 2; | | order-3 | order: 3; | | order-4 | order: 4; | | order-5 | order: 5; | | order-6 | order: 6; | | order-7 | order: 7; | | order-8 | order: 8; | | order-9 | order: 9; | | order-10 | order: 10; | | order-11 | order: 11; | | order-12 | order: 12; | | order-first | order: -9999; | | order-last | order: 9999; | | order-none | order: 0; | Basic usage ----------- ### Ordering flex and grid items Use `order-{order}` to render flex and grid items in a different order than they appear in the DOM. ``` <div class="flex justify-between ..."> <div class="order-last">01</div> <div>02</div> <div>03</div> </div> ``` ### Using negative values To use a negative order value, prefix the class name with a dash to convert it to a negative value. ``` <div class="-order-1"> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:order-last` to only apply the `order-last` utility on hover. ``` <div class="order-first hover:order-last"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:order-last` to apply the `order-last` utility at only medium screen sizes and above. ``` <div class="order-first md:order-last"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides utilities for `order-first`, `order-last`, `order-none`, and an `order-{number}` utility for the numbers 1 through 12. You can customize these values by editing `theme.order` or `theme.extend.order` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { order: { '13': '13' } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `order` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="order-[13]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/orderGrid Template Columns ===================== Utilities for specifying the columns in a grid layout. Quick reference --------------- | Class | Properties | | --- | --- | | grid-cols-1 | grid-template-columns: repeat(1, minmax(0, 1fr)); | | grid-cols-2 | grid-template-columns: repeat(2, minmax(0, 1fr)); | | grid-cols-3 | grid-template-columns: repeat(3, minmax(0, 1fr)); | | grid-cols-4 | grid-template-columns: repeat(4, minmax(0, 1fr)); | | grid-cols-5 | grid-template-columns: repeat(5, minmax(0, 1fr)); | | grid-cols-6 | grid-template-columns: repeat(6, minmax(0, 1fr)); | | grid-cols-7 | grid-template-columns: repeat(7, minmax(0, 1fr)); | | grid-cols-8 | grid-template-columns: repeat(8, minmax(0, 1fr)); | | grid-cols-9 | grid-template-columns: repeat(9, minmax(0, 1fr)); | | grid-cols-10 | grid-template-columns: repeat(10, minmax(0, 1fr)); | | grid-cols-11 | grid-template-columns: repeat(11, minmax(0, 1fr)); | | grid-cols-12 | grid-template-columns: repeat(12, minmax(0, 1fr)); | | grid-cols-none | grid-template-columns: none; | Basic usage ----------- ### Specifying the columns in a grid Use the `grid-cols-{n}` utilities to create grids with *n* equally sized columns. ``` <div class="grid grid-cols-4 gap-4"> <div>01</div> <!-- ... --> <div>09</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:grid-cols-6` to only apply the `grid-cols-6` utility on hover. ``` <div class="grid grid-cols-1 hover:grid-cols-6"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:grid-cols-6` to apply the `grid-cols-6` utility at only medium screen sizes and above. ``` <div class="grid grid-cols-1 md:grid-cols-6"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes `grid-template-column` utilities for creating basic grids with up to 12 equal width columns. You can customize these values by editing `theme.gridTemplateColumns` or `theme.extend.gridTemplateColumns` in your `tailwind.config.js` file. You have direct access to the `grid-template-columns` CSS property here so you can make your custom column values as generic or as complicated and site-specific as you like. tailwind.config.js ``` module.exports = { theme: { extend: { gridTemplateColumns: { // Simple 16 column grid '16': 'repeat(16, minmax(0, 1fr))', // Complex site-specific column configuration 'footer': '200px minmax(900px, 1fr) 100px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `grid-template-columns` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="grid grid-cols-[200px_minmax(900px,_1fr)_100px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/grid-template-columnsGrid Column Start / End ======================= Utilities for controlling how elements are sized and placed across grid columns. Quick reference --------------- | Class | Properties | | --- | --- | | col-auto | grid-column: auto; | | col-span-1 | grid-column: span 1 / span 1; | | col-span-2 | grid-column: span 2 / span 2; | | col-span-3 | grid-column: span 3 / span 3; | | col-span-4 | grid-column: span 4 / span 4; | | col-span-5 | grid-column: span 5 / span 5; | | col-span-6 | grid-column: span 6 / span 6; | | col-span-7 | grid-column: span 7 / span 7; | | col-span-8 | grid-column: span 8 / span 8; | | col-span-9 | grid-column: span 9 / span 9; | | col-span-10 | grid-column: span 10 / span 10; | | col-span-11 | grid-column: span 11 / span 11; | | col-span-12 | grid-column: span 12 / span 12; | | col-span-full | grid-column: 1 / -1; | | col-start-1 | grid-column-start: 1; | | col-start-2 | grid-column-start: 2; | | col-start-3 | grid-column-start: 3; | | col-start-4 | grid-column-start: 4; | | col-start-5 | grid-column-start: 5; | | col-start-6 | grid-column-start: 6; | | col-start-7 | grid-column-start: 7; | | col-start-8 | grid-column-start: 8; | | col-start-9 | grid-column-start: 9; | | col-start-10 | grid-column-start: 10; | | col-start-11 | grid-column-start: 11; | | col-start-12 | grid-column-start: 12; | | col-start-13 | grid-column-start: 13; | | col-start-auto | grid-column-start: auto; | | col-end-1 | grid-column-end: 1; | | col-end-2 | grid-column-end: 2; | | col-end-3 | grid-column-end: 3; | | col-end-4 | grid-column-end: 4; | | col-end-5 | grid-column-end: 5; | | col-end-6 | grid-column-end: 6; | | col-end-7 | grid-column-end: 7; | | col-end-8 | grid-column-end: 8; | | col-end-9 | grid-column-end: 9; | | col-end-10 | grid-column-end: 10; | | col-end-11 | grid-column-end: 11; | | col-end-12 | grid-column-end: 12; | | col-end-13 | grid-column-end: 13; | | col-end-auto | grid-column-end: auto; | Basic usage ----------- ### Spanning columns Use the `col-span-{n}` utilities to make an element span *n* columns. ``` <div class="grid grid-cols-3 gap-4"> <div class="...">01</div> <div class="...">02</div> <div class="...">03</div> <div class="col-span-2 ...">04</div> <div class="...">05</div> <div class="...">06</div> <div class="col-span-2 ...">07</div> </div> ``` ### Starting and ending lines Use the `col-start-{n}` and `col-end-{n}` utilities to make an element start or end at the *nth* grid line. These can also be combined with the `col-span-{n}` utilities to span a specific number of columns. Note that CSS grid lines start at 1, not 0, so a full-width element in a 6-column grid would start at line 1 and end at line 7. ``` <div class="grid grid-cols-6 gap-4"> <div class="col-start-2 col-span-4 ...">01</div> <div class="col-start-1 col-end-3 ...">02</div> <div class="col-end-7 col-span-2 ...">03</div> <div class="col-start-1 col-end-7 ...">04</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:col-span-6` to only apply the `col-span-6` utility on hover. ``` <div class="col-span-2 hover:col-span-6"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:col-span-6` to apply the `col-span-6` utility at only medium screen sizes and above. ``` <div class="col-span-2 md:col-span-6"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes grid-column utilities for working with grids with up to 12 columns. You change, add, or remove these by customizing the `gridColumn`, `gridColumnStart`, and `gridColumnEnd` sections of your Tailwind theme config. For creating more `col-{value}` utilities that control the `grid-column` shorthand property directly, customize the `gridColumn` section of your Tailwind theme config: tailwind.config.js ``` module.exports = { theme: { extend: { gridColumn: { 'span-16': 'span 16 / span 16', } } } } ``` We use this internally for our `col-span-{n}` utilities. Note that since this configures the `grid-column` shorthand property directly, we include the word `span` directly in the value name, it’s *not* baked into the class name automatically. That means you are free to add entries that do whatever you want here — they don’t just have to be `span` utilities. To add new `col-start-{n}` utilities, use the `gridColumnStart` section of your Tailwind theme config: tailwind.config.js ``` module.exports = { theme: { extend: { gridColumnStart: { '13': '13', '14': '14', '15': '15', '16': '16', '17': '17', } } } } ``` To add new `col-end-{n}` utilities, use the `gridColumnEnd` section of your Tailwind theme config: tailwind.config.js ``` module.exports = { theme: { extend: { gridColumnEnd: { '13': '13', '14': '14', '15': '15', '16': '16', '17': '17', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `grid-column/grid-column-start/grid-column-end` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="col-[16_/_span_16]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/grid-columnPlace Items =========== Utilities for controlling how items are justified and aligned at the same time. Quick reference --------------- | Class | Properties | | --- | --- | | place-items-start | place-items: start; | | place-items-end | place-items: end; | | place-items-center | place-items: center; | | place-items-baseline | place-items: baseline; | | place-items-stretch | place-items: stretch; | Basic usage ----------- ### Start Use `place-items-start` to place grid items on the start of their grid areas on both axes: ``` <div class="grid grid-cols-3 gap-4 place-items-start ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` ### End Use `place-items-end` to place grid items on the end of their grid areas on both axes: ``` <div class="grid grid-cols-3 gap-4 place-items-end h-56 ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` ### Center Use `place-items-center` to place grid items on the center of their grid areas on both axes: ``` <div class="grid grid-cols-3 gap-4 place-items-center h-56 ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` ### Stretch Use `place-items-stretch` to stretch items along their grid areas on both axes: ``` <div class="grid grid-cols-3 gap-4 place-items-stretch h-56 ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:place-items-center` to only apply the `place-items-center` utility on hover. ``` <div class="grid place-items-start hover:place-items-center"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:place-items-center` to apply the `place-items-center` utility at only medium screen sizes and above. ``` <div class="grid place-items-start md:place-items-center"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/place-itemsGrid Auto Flow ============== Utilities for controlling how elements in a grid are auto-placed. Quick reference --------------- | Class | Properties | | --- | --- | | grid-flow-row | grid-auto-flow: row; | | grid-flow-col | grid-auto-flow: column; | | grid-flow-dense | grid-auto-flow: dense; | | grid-flow-row-dense | grid-auto-flow: row dense; | | grid-flow-col-dense | grid-auto-flow: column dense; | Basic usage ----------- ### Controlling grid element placement Use the `grid-flow-{keyword}` utilities to control how the auto-placement algorithm works for a grid layout. ``` <div class="grid grid-flow-row-dense grid-cols-3 grid-rows-3 ..."> <div class="col-span-2">01</div> <div class="col-span-2">02</div> <div>03</div> <div>04</div> <div>05</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:grid-flow-row` to only apply the `grid-flow-row` utility on hover. ``` <div class="grid grid-flow-col hover:grid-flow-row"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:grid-flow-row` to apply the `grid-flow-row` utility at only medium screen sizes and above. ``` <div class="grid grid-flow-col md:grid-flow-row"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/grid-auto-flowGrid Auto Columns ================= Utilities for controlling the size of implicitly-created grid columns. Quick reference --------------- | Class | Properties | | --- | --- | | auto-cols-auto | grid-auto-columns: auto; | | auto-cols-min | grid-auto-columns: min-content; | | auto-cols-max | grid-auto-columns: max-content; | | auto-cols-fr | grid-auto-columns: minmax(0, 1fr); | Basic usage ----------- ### Sizing implicitly-created grid columns Use the `auto-cols-{size}` utilities to control the size of implicitly-created grid columns. ``` <div class="grid grid-flow-col auto-cols-max"> <div>01</div> <div>02</div> <div>03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:auto-cols-min` to only apply the `auto-cols-min` utility on hover. ``` <div class="grid grid-flow-col auto-cols-max hover:auto-cols-min"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:auto-cols-min` to apply the `auto-cols-min` utility at only medium screen sizes and above. ``` <div class="grid grid-flow-col auto-cols-max md:auto-cols-min"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes four general purpose `grid-auto-columns` utilities. You can customize these values by editing `theme.gridAutoColumns` or `theme.extend.gridAutoColumns` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { gridAutoColumns: { '2fr': 'minmax(0, 2fr)', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `grid-auto-columns` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="grid grid-flow-col auto-cols-[minmax(0,_2fr)]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/grid-auto-columnsGap === Utilities for controlling gutters between grid and flexbox items. Quick reference --------------- | Class | Properties | | --- | --- | | gap-0 | gap: 0px; | | gap-x-0 | column-gap: 0px; | | gap-y-0 | row-gap: 0px; | | gap-px | gap: 1px; | | gap-x-px | column-gap: 1px; | | gap-y-px | row-gap: 1px; | | gap-0.5 | gap: 0.125rem; /* 2px */ | | gap-x-0.5 | column-gap: 0.125rem; /* 2px */ | | gap-y-0.5 | row-gap: 0.125rem; /* 2px */ | | gap-1 | gap: 0.25rem; /* 4px */ | | gap-x-1 | column-gap: 0.25rem; /* 4px */ | | gap-y-1 | row-gap: 0.25rem; /* 4px */ | | gap-1.5 | gap: 0.375rem; /* 6px */ | | gap-x-1.5 | column-gap: 0.375rem; /* 6px */ | | gap-y-1.5 | row-gap: 0.375rem; /* 6px */ | | gap-2 | gap: 0.5rem; /* 8px */ | | gap-x-2 | column-gap: 0.5rem; /* 8px */ | | gap-y-2 | row-gap: 0.5rem; /* 8px */ | | gap-2.5 | gap: 0.625rem; /* 10px */ | | gap-x-2.5 | column-gap: 0.625rem; /* 10px */ | | gap-y-2.5 | row-gap: 0.625rem; /* 10px */ | | gap-3 | gap: 0.75rem; /* 12px */ | | gap-x-3 | column-gap: 0.75rem; /* 12px */ | | gap-y-3 | row-gap: 0.75rem; /* 12px */ | | gap-3.5 | gap: 0.875rem; /* 14px */ | | gap-x-3.5 | column-gap: 0.875rem; /* 14px */ | | gap-y-3.5 | row-gap: 0.875rem; /* 14px */ | | gap-4 | gap: 1rem; /* 16px */ | | gap-x-4 | column-gap: 1rem; /* 16px */ | | gap-y-4 | row-gap: 1rem; /* 16px */ | | gap-5 | gap: 1.25rem; /* 20px */ | | gap-x-5 | column-gap: 1.25rem; /* 20px */ | | gap-y-5 | row-gap: 1.25rem; /* 20px */ | | gap-6 | gap: 1.5rem; /* 24px */ | | gap-x-6 | column-gap: 1.5rem; /* 24px */ | | gap-y-6 | row-gap: 1.5rem; /* 24px */ | | gap-7 | gap: 1.75rem; /* 28px */ | | gap-x-7 | column-gap: 1.75rem; /* 28px */ | | gap-y-7 | row-gap: 1.75rem; /* 28px */ | | gap-8 | gap: 2rem; /* 32px */ | | gap-x-8 | column-gap: 2rem; /* 32px */ | | gap-y-8 | row-gap: 2rem; /* 32px */ | | gap-9 | gap: 2.25rem; /* 36px */ | | gap-x-9 | column-gap: 2.25rem; /* 36px */ | | gap-y-9 | row-gap: 2.25rem; /* 36px */ | | gap-10 | gap: 2.5rem; /* 40px */ | | gap-x-10 | column-gap: 2.5rem; /* 40px */ | | gap-y-10 | row-gap: 2.5rem; /* 40px */ | | gap-11 | gap: 2.75rem; /* 44px */ | | gap-x-11 | column-gap: 2.75rem; /* 44px */ | | gap-y-11 | row-gap: 2.75rem; /* 44px */ | | gap-12 | gap: 3rem; /* 48px */ | | gap-x-12 | column-gap: 3rem; /* 48px */ | | gap-y-12 | row-gap: 3rem; /* 48px */ | | gap-14 | gap: 3.5rem; /* 56px */ | | gap-x-14 | column-gap: 3.5rem; /* 56px */ | | gap-y-14 | row-gap: 3.5rem; /* 56px */ | | gap-16 | gap: 4rem; /* 64px */ | | gap-x-16 | column-gap: 4rem; /* 64px */ | | gap-y-16 | row-gap: 4rem; /* 64px */ | | gap-20 | gap: 5rem; /* 80px */ | | gap-x-20 | column-gap: 5rem; /* 80px */ | | gap-y-20 | row-gap: 5rem; /* 80px */ | | gap-24 | gap: 6rem; /* 96px */ | | gap-x-24 | column-gap: 6rem; /* 96px */ | | gap-y-24 | row-gap: 6rem; /* 96px */ | | gap-28 | gap: 7rem; /* 112px */ | | gap-x-28 | column-gap: 7rem; /* 112px */ | | gap-y-28 | row-gap: 7rem; /* 112px */ | | gap-32 | gap: 8rem; /* 128px */ | | gap-x-32 | column-gap: 8rem; /* 128px */ | | gap-y-32 | row-gap: 8rem; /* 128px */ | | gap-36 | gap: 9rem; /* 144px */ | | gap-x-36 | column-gap: 9rem; /* 144px */ | | gap-y-36 | row-gap: 9rem; /* 144px */ | | gap-40 | gap: 10rem; /* 160px */ | | gap-x-40 | column-gap: 10rem; /* 160px */ | | gap-y-40 | row-gap: 10rem; /* 160px */ | | gap-44 | gap: 11rem; /* 176px */ | | gap-x-44 | column-gap: 11rem; /* 176px */ | | gap-y-44 | row-gap: 11rem; /* 176px */ | | gap-48 | gap: 12rem; /* 192px */ | | gap-x-48 | column-gap: 12rem; /* 192px */ | | gap-y-48 | row-gap: 12rem; /* 192px */ | | gap-52 | gap: 13rem; /* 208px */ | | gap-x-52 | column-gap: 13rem; /* 208px */ | | gap-y-52 | row-gap: 13rem; /* 208px */ | | gap-56 | gap: 14rem; /* 224px */ | | gap-x-56 | column-gap: 14rem; /* 224px */ | | gap-y-56 | row-gap: 14rem; /* 224px */ | | gap-60 | gap: 15rem; /* 240px */ | | gap-x-60 | column-gap: 15rem; /* 240px */ | | gap-y-60 | row-gap: 15rem; /* 240px */ | | gap-64 | gap: 16rem; /* 256px */ | | gap-x-64 | column-gap: 16rem; /* 256px */ | | gap-y-64 | row-gap: 16rem; /* 256px */ | | gap-72 | gap: 18rem; /* 288px */ | | gap-x-72 | column-gap: 18rem; /* 288px */ | | gap-y-72 | row-gap: 18rem; /* 288px */ | | gap-80 | gap: 20rem; /* 320px */ | | gap-x-80 | column-gap: 20rem; /* 320px */ | | gap-y-80 | row-gap: 20rem; /* 320px */ | | gap-96 | gap: 24rem; /* 384px */ | | gap-x-96 | column-gap: 24rem; /* 384px */ | | gap-y-96 | row-gap: 24rem; /* 384px */ | Basic usage ----------- ### Setting the gap between elements Use `gap-{size}` to change the gap between both rows and columns in grid and flexbox layouts. ``` <div class="grid gap-4 grid-cols-2"> <div>01</div> <div>02</div> <div>03</div> <div>04</div> </div> ``` ### Changing row and column gaps independently Use `gap-x-{size}` and `gap-y-{size}` to change the gap between rows and columns independently. ``` <div class="grid gap-x-8 gap-y-4 grid-cols-3"> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:gap-6` to only apply the `gap-6` utility on hover. ``` <div class="grid gap-4 hover:gap-6"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:gap-6` to apply the `gap-6` utility at only medium screen sizes and above. ``` <div class="grid gap-4 md:gap-6"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind’s gap scale uses the [default spacing scale](customizing-spacing). You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '11': '2.75rem', } } } } ``` Alternatively, you can customize just the gap scale by editing `theme.gap` or `theme.extend.gap` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { gap: { '11': '2.75rem', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `gap` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="grid gap-[2.75rem]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/gapJustify Content =============== Utilities for controlling how flex and grid items are positioned along a container's main axis. Quick reference --------------- | Class | Properties | | --- | --- | | justify-normal | justify-content: normal; | | justify-start | justify-content: flex-start; | | justify-end | justify-content: flex-end; | | justify-center | justify-content: center; | | justify-between | justify-content: space-between; | | justify-around | justify-content: space-around; | | justify-evenly | justify-content: space-evenly; | | justify-stretch | justify-content: stretch; | Basic usage ----------- ### Start Use `justify-start` to justify items against the start of the container’s main axis: ``` <div class="flex justify-start ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Center Use `justify-center` to justify items along the center of the container’s main axis: ``` <div class="flex justify-center ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### End Use `justify-end` to justify items against the end of the container’s main axis: ``` <div class="flex justify-end ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Space between Use `justify-between` to justify items along the container’s main axis such that there is an equal amount of space between each item: ``` <div class="flex justify-between ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Space around Use `justify-around` to justify items along the container’s main axis such that there is an equal amount of space on each side of each item: ``` <div class="flex justify-around ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Space evenly Use `justify-evenly` to justify items along the container’s main axis such that there is an equal amount of space around each item, but also accounting for the doubling of space you would normally see between each item when using `justify-around`: ``` <div class="flex justify-evenly ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Stretch Use `justify-stretch` to allow content items to fill the available space along the container’s main axis: ``` <div class="grid grid-flow-col justify-stretch ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Normal Use `justify-normal` to pack content items in their default position as if no `justify-content` value was set: ``` <div class="flex justify-normal ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:justify-between` to only apply the `justify-between` utility on hover. ``` <div class="flex justify-start hover:justify-between"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:justify-between` to apply the `justify-between` utility at only medium screen sizes and above. ``` <div class="flex justify-start md:justify-between"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/justify-contentJustify Items ============= Utilities for controlling how grid items are aligned along their inline axis. Quick reference --------------- | Class | Properties | | --- | --- | | justify-items-start | justify-items: start; | | justify-items-end | justify-items: end; | | justify-items-center | justify-items: center; | | justify-items-stretch | justify-items: stretch; | Basic usage ----------- ### Start Use `justify-items-start` to justify grid items against the start of their inline axis: ``` <div class="grid justify-items-start ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` ### End Use `justify-items-end` to justify grid items against the end of their inline axis: ``` <div class="grid justify-items-end ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` ### Center Use `justify-items-center` to justify grid items along their inline axis: ``` <div class="grid justify-items-center ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` ### Stretch Use `justify-items-stretch` to stretch items along their inline axis: ``` <div class="grid justify-items-stretch ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:justify-items-center` to only apply the `justify-items-center` utility on hover. ``` <div class="grid justify-items-start hover:justify-items-center"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:justify-items-center` to apply the `justify-items-center` utility at only medium screen sizes and above. ``` <div class="grid justify-items-start md:justify-items-center"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/justify-itemsPlace Content ============= Utilities for controlling how content is justified and aligned at the same time. Quick reference --------------- | Class | Properties | | --- | --- | | place-content-center | place-content: center; | | place-content-start | place-content: start; | | place-content-end | place-content: end; | | place-content-between | place-content: space-between; | | place-content-around | place-content: space-around; | | place-content-evenly | place-content: space-evenly; | | place-content-baseline | place-content: baseline; | | place-content-stretch | place-content: stretch; | Basic usage ----------- ### Center Use `place-content-center` to pack items in the center of the block axis: ``` <div class="grid grid-cols-2 gap-4 place-content-center h-48 ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> </div> ``` ### Start Use `place-content-start` to pack items against the start of the block axis: ``` <div class="grid grid-cols-2 gap-4 place-content-start h-48 ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> </div> ``` ### End Use `place-content-end` to to pack items against the end of the block axis: ``` <div class="grid grid-cols-2 gap-4 place-content-end h-48 ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> </div> ``` ### Space between Use `place-content-between` to distribute grid items along the block axis so that that there is an equal amount of space between each row on the block axis. ``` <div class="grid grid-cols-2 gap-4 place-content-between h-48 ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> </div> ``` ### Space around Use `place-content-around` distribute grid items such that there is an equal amount of space around each row on the block axis: ``` <div class="grid grid-cols-2 gap-4 place-content-around h-48 ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> </div> ``` ### Space evenly Use `place-content-evenly` to distribute grid items such that they are evenly spaced on the block axis: ``` <div class="grid grid-cols-2 gap-4 place-content-evenly h-48 ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> </div> ``` ### Stretch Use `place-content-stretch` to stretch grid items along their grid areas on the block axis: ``` <div class="grid grid-cols-2 gap-4 place-content-stretch h-48 ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:place-content-center` to only apply the `place-content-center` utility on hover. ``` <div class="grid place-content-start hover:place-content-center"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:place-content-center` to apply the `place-content-center` utility at only medium screen sizes and above. ``` <div class="grid place-content-start md:place-content-center"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/place-contentPlace Self ========== Utilities for controlling how an individual item is justified and aligned at the same time. Quick reference --------------- | Class | Properties | | --- | --- | | place-self-auto | place-self: auto; | | place-self-start | place-self: start; | | place-self-end | place-self: end; | | place-self-center | place-self: center; | | place-self-stretch | place-self: stretch; | Basic usage ----------- ### Auto Use `place-self-auto` to align an item based on the value of the container’s `place-items` property: ``` <div class="grid grid-cols-3 gap-4 ..."> <div>01</div> <div class="place-self-auto ...">02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` ### Start Use `place-self-start` to align an item to the start on both axes: ``` <div class="grid grid-cols-3 gap-4 ..."> <div>01</div> <div class="place-self-start ...">02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` ### Center Use `place-self-center` to align an item at the center on both axes: ``` <div class="grid grid-cols-3 gap-4 ..."> <div>01</div> <div class="place-self-center ...">02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` ### End Use `place-self-end` to align an item to the end on both axes: ``` <div class="grid grid-cols-3 gap-4 ..."> <div>01</div> <div class="place-self-end ...">02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` ### Stretch Use `place-self-stretch` to stretch an item on both axes: ``` <div class="grid grid-cols-3 gap-2 ..."> <div>01</div> <div class="place-self-stretch ...">02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:place-self-end` to only apply the `place-self-end` utility on hover. ``` <div class="place-self-start hover:place-self-end"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:place-self-end` to apply the `place-self-end` utility at only medium screen sizes and above. ``` <div class="place-self-start md:place-self-end"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/place-selfSpace Between ============= Utilities for controlling the space between child elements. Quick reference --------------- | Class | Properties | | --- | --- | | space-x-0 > * + * | margin-left: 0px; | | space-y-0 > * + * | margin-top: 0px; | | space-x-0.5 > * + * | margin-left: 0.125rem; /* 2px */ | | space-y-0.5 > * + * | margin-top: 0.125rem; /* 2px */ | | space-x-1 > * + * | margin-left: 0.25rem; /* 4px */ | | space-y-1 > * + * | margin-top: 0.25rem; /* 4px */ | | space-x-1.5 > * + * | margin-left: 0.375rem; /* 6px */ | | space-y-1.5 > * + * | margin-top: 0.375rem; /* 6px */ | | space-x-2 > * + * | margin-left: 0.5rem; /* 8px */ | | space-y-2 > * + * | margin-top: 0.5rem; /* 8px */ | | space-x-2.5 > * + * | margin-left: 0.625rem; /* 10px */ | | space-y-2.5 > * + * | margin-top: 0.625rem; /* 10px */ | | space-x-3 > * + * | margin-left: 0.75rem; /* 12px */ | | space-y-3 > * + * | margin-top: 0.75rem; /* 12px */ | | space-x-3.5 > * + * | margin-left: 0.875rem; /* 14px */ | | space-y-3.5 > * + * | margin-top: 0.875rem; /* 14px */ | | space-x-4 > * + * | margin-left: 1rem; /* 16px */ | | space-y-4 > * + * | margin-top: 1rem; /* 16px */ | | space-x-5 > * + * | margin-left: 1.25rem; /* 20px */ | | space-y-5 > * + * | margin-top: 1.25rem; /* 20px */ | | space-x-6 > * + * | margin-left: 1.5rem; /* 24px */ | | space-y-6 > * + * | margin-top: 1.5rem; /* 24px */ | | space-x-7 > * + * | margin-left: 1.75rem; /* 28px */ | | space-y-7 > * + * | margin-top: 1.75rem; /* 28px */ | | space-x-8 > * + * | margin-left: 2rem; /* 32px */ | | space-y-8 > * + * | margin-top: 2rem; /* 32px */ | | space-x-9 > * + * | margin-left: 2.25rem; /* 36px */ | | space-y-9 > * + * | margin-top: 2.25rem; /* 36px */ | | space-x-10 > * + * | margin-left: 2.5rem; /* 40px */ | | space-y-10 > * + * | margin-top: 2.5rem; /* 40px */ | | space-x-11 > * + * | margin-left: 2.75rem; /* 44px */ | | space-y-11 > * + * | margin-top: 2.75rem; /* 44px */ | | space-x-12 > * + * | margin-left: 3rem; /* 48px */ | | space-y-12 > * + * | margin-top: 3rem; /* 48px */ | | space-x-14 > * + * | margin-left: 3.5rem; /* 56px */ | | space-y-14 > * + * | margin-top: 3.5rem; /* 56px */ | | space-x-16 > * + * | margin-left: 4rem; /* 64px */ | | space-y-16 > * + * | margin-top: 4rem; /* 64px */ | | space-x-20 > * + * | margin-left: 5rem; /* 80px */ | | space-y-20 > * + * | margin-top: 5rem; /* 80px */ | | space-x-24 > * + * | margin-left: 6rem; /* 96px */ | | space-y-24 > * + * | margin-top: 6rem; /* 96px */ | | space-x-28 > * + * | margin-left: 7rem; /* 112px */ | | space-y-28 > * + * | margin-top: 7rem; /* 112px */ | | space-x-32 > * + * | margin-left: 8rem; /* 128px */ | | space-y-32 > * + * | margin-top: 8rem; /* 128px */ | | space-x-36 > * + * | margin-left: 9rem; /* 144px */ | | space-y-36 > * + * | margin-top: 9rem; /* 144px */ | | space-x-40 > * + * | margin-left: 10rem; /* 160px */ | | space-y-40 > * + * | margin-top: 10rem; /* 160px */ | | space-x-44 > * + * | margin-left: 11rem; /* 176px */ | | space-y-44 > * + * | margin-top: 11rem; /* 176px */ | | space-x-48 > * + * | margin-left: 12rem; /* 192px */ | | space-y-48 > * + * | margin-top: 12rem; /* 192px */ | | space-x-52 > * + * | margin-left: 13rem; /* 208px */ | | space-y-52 > * + * | margin-top: 13rem; /* 208px */ | | space-x-56 > * + * | margin-left: 14rem; /* 224px */ | | space-y-56 > * + * | margin-top: 14rem; /* 224px */ | | space-x-60 > * + * | margin-left: 15rem; /* 240px */ | | space-y-60 > * + * | margin-top: 15rem; /* 240px */ | | space-x-64 > * + * | margin-left: 16rem; /* 256px */ | | space-y-64 > * + * | margin-top: 16rem; /* 256px */ | | space-x-72 > * + * | margin-left: 18rem; /* 288px */ | | space-y-72 > * + * | margin-top: 18rem; /* 288px */ | | space-x-80 > * + * | margin-left: 20rem; /* 320px */ | | space-y-80 > * + * | margin-top: 20rem; /* 320px */ | | space-x-96 > * + * | margin-left: 24rem; /* 384px */ | | space-y-96 > * + * | margin-top: 24rem; /* 384px */ | | space-x-px > * + * | margin-left: 1px; | | space-y-px > * + * | margin-top: 1px; | | space-y-reverse > * + * | --tw-space-y-reverse: 1; | | space-x-reverse > * + * | --tw-space-x-reverse: 1; | Basic usage ----------- ### Add horizontal space between children Control the horizontal space between elements using the `space-x-{amount}` utilities. ``` <div class="flex space-x-4 ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Add vertical space between children Control the vertical space between elements using the `space-y-{amount}` utilities. ``` <div class="flex flex-col space-y-4 ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Reversing children order If your elements are in reverse order (using say `flex-row-reverse` or `flex-col-reverse`), use the `space-x-reverse` or `space-y-reverse` utilities to ensure the space is added to the correct side of each element. ``` <div class="flex flex-row-reverse space-x-4 space-x-reverse ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Using negative values To use a negative space value, prefix the class name with a dash to convert it to a negative value. ``` <div class="flex -space-x-4 ..."> <!-- ... --> </div> ``` Limitations ----------- These utilities are really just a shortcut for adding margin to all-but-the-first-item in a group, and aren’t designed to handle complex cases like grids, layouts that wrap, or situations where the children are rendered in a complex custom order rather than their natural DOM order. For those situations, it’s better to use the [gap utilities](gap) when possible, or add margin to every element with a matching negative margin on the parent: ``` <div class="flow-root"> <div class="-m-2 flex flex-wrap"> <div class="m-2 ..."></div> <div class="m-2 ..."></div> <div class="m-2 ..."></div> </div> </div> ``` ### Cannot be paired with divide utilities The `space-*` utilities are not designed to work together with the [divide utilities](divide-width). For those situations, consider adding margin/padding utilities to the children instead. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:space-x-8` to only apply the `space-x-8` utility on hover. ``` <div class="flex space-x-2 hover:space-x-8"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:space-x-8` to apply the `space-x-8` utility at only medium screen sizes and above. ``` <div class="flex space-x-2 md:space-x-8"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind’s space scale uses the [default spacing scale](customizing-spacing). You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '5px': '5px', } } } } ``` Alternatively, you can customize just the space scale by editing `theme.space` or `theme.extend.space` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { space: { '5px': '5px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `space-{x|y}` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="space-y-[5px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/spaceMin-Width ========= Utilities for setting the minimum width of an element. Quick reference --------------- | Class | Properties | | --- | --- | | min-w-0 | min-width: 0px; | | min-w-full | min-width: 100%; | | min-w-min | min-width: min-content; | | min-w-max | min-width: max-content; | | min-w-fit | min-width: fit-content; | Basic usage ----------- ### Setting the minimum width Set the minimum width of an element using the `min-w-{width}` utilities. ``` <span class="min-w-full ..."> <!-- ... --> </span> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:min-w-0` to only apply the `min-w-0` utility on hover. ``` <div class="w-24 min-w-full hover:min-w-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:min-w-0` to apply the `min-w-0` utility at only medium screen sizes and above. ``` <div class="w-24 min-w-full md:min-w-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme You can customize your `min-width` scale by editing `theme.minWidth` or `theme.extend.minWidth` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { minWidth: { '1/2': '50%', } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `min-width` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="min-w-[50%]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/min-widthGrid Template Rows ================== Utilities for specifying the rows in a grid layout. Quick reference --------------- | Class | Properties | | --- | --- | | grid-rows-1 | grid-template-rows: repeat(1, minmax(0, 1fr)); | | grid-rows-2 | grid-template-rows: repeat(2, minmax(0, 1fr)); | | grid-rows-3 | grid-template-rows: repeat(3, minmax(0, 1fr)); | | grid-rows-4 | grid-template-rows: repeat(4, minmax(0, 1fr)); | | grid-rows-5 | grid-template-rows: repeat(5, minmax(0, 1fr)); | | grid-rows-6 | grid-template-rows: repeat(6, minmax(0, 1fr)); | | grid-rows-none | grid-template-rows: none; | Basic usage ----------- ### Specifying the rows in a grid Use the `grid-rows-{n}` utilities to create grids with *n* equally sized rows. ``` <div class="grid grid-rows-4 grid-flow-col gap-4"> <div>01</div> <!-- ... --> <div>09</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:grid-rows-6` to only apply the `grid-rows-6` utility on hover. ``` <div class="grid grid-rows-2 hover:grid-rows-6"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:grid-rows-6` to apply the `grid-rows-6` utility at only medium screen sizes and above. ``` <div class="grid grid-rows-2 md:grid-rows-6"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes `grid-template-row` utilities for creating basic grids with up to 6 equal width rows. You can customize these values by editing `theme.gridTemplateRows` or `theme.extend.gridTemplateRows` in your `tailwind.config.js` file. You have direct access to the `grid-template-rows` CSS property here so you can make your custom rows values as generic or as complicated and site-specific as you like. tailwind.config.js ``` module.exports = { theme: { extend: { gridTemplateRows: { // Simple 8 row grid '8': 'repeat(8, minmax(0, 1fr))', // Complex site-specific row configuration 'layout': '200px minmax(900px, 1fr) 100px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `grid-template-rows` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="grid grid-rows-[200px_minmax(900px,_1fr)_100px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/grid-template-rowsGrid Row Start / End ==================== Utilities for controlling how elements are sized and placed across grid rows. Quick reference --------------- | Class | Properties | | --- | --- | | row-auto | grid-row: auto; | | row-span-1 | grid-row: span 1 / span 1; | | row-span-2 | grid-row: span 2 / span 2; | | row-span-3 | grid-row: span 3 / span 3; | | row-span-4 | grid-row: span 4 / span 4; | | row-span-5 | grid-row: span 5 / span 5; | | row-span-6 | grid-row: span 6 / span 6; | | row-span-full | grid-row: 1 / -1; | | row-start-1 | grid-row-start: 1; | | row-start-2 | grid-row-start: 2; | | row-start-3 | grid-row-start: 3; | | row-start-4 | grid-row-start: 4; | | row-start-5 | grid-row-start: 5; | | row-start-6 | grid-row-start: 6; | | row-start-7 | grid-row-start: 7; | | row-start-auto | grid-row-start: auto; | | row-end-1 | grid-row-end: 1; | | row-end-2 | grid-row-end: 2; | | row-end-3 | grid-row-end: 3; | | row-end-4 | grid-row-end: 4; | | row-end-5 | grid-row-end: 5; | | row-end-6 | grid-row-end: 6; | | row-end-7 | grid-row-end: 7; | | row-end-auto | grid-row-end: auto; | Basic usage ----------- ### Spanning rows Use the `row-span-{n}` utilities to make an element span *n* rows. ``` <div class="grid grid-rows-3 grid-flow-col gap-4"> <div class="row-span-3 ...">01</div> <div class="col-span-2 ...">02</div> <div class="row-span-2 col-span-2 ...">03</div> </div> ``` ### Starting and ending lines Use the `row-start-{n}` and `row-end-{n}` utilities to make an element start or end at the *nth* grid line. These can also be combined with the `row-span-{n}` utilities to span a specific number of rows. Note that CSS grid lines start at 1, not 0, so a full-height element in a 3-row grid would start at line 1 and end at line 4. ``` <div class="grid grid-rows-3 grid-flow-col gap-4"> <div class="row-start-2 row-span-2 ...">01</div> <div class="row-end-3 row-span-2 ...">02</div> <div class="row-start-1 row-end-4 ...">03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:row-span-4` to only apply the `row-span-4` utility on hover. ``` <div class="row-span-3 hover:row-span-4"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:row-span-4` to apply the `row-span-4` utility at only medium screen sizes and above. ``` <div class="row-span-3 md:row-span-4"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes grid-row utilities for working with grids with up to 6 explicit rows. You can customize these values by editing `theme.gridRow`, `theme.extend.gridRow`, `theme.gridRowStart`, `theme.extend.gridRowStart`, `theme.gridRowEnd`, and `theme.extend.gridRowEnd` in your `tailwind.config.js` file. For creating more `row-{value}` utilities that control the `grid-row` shorthand property directly, customize the `gridRow` section of your Tailwind theme config: tailwind.config.js ``` module.exports = { theme: { extend: { gridRow: { 'span-16': 'span 16 / span 16', } } } } ``` We use this internally for our `row-span-{n}` utilities. Note that since this configures the `grid-row` shorthand property directly, we include the word `span` directly in the value name, it’s *not* baked into the class name automatically. That means you are free to add entries that do whatever you want here — they don’t just have to be `span` utilities. To add new `row-start-{n}` utilities, use the `gridRowStart` section of your Tailwind theme config: tailwind.config.js ``` module.exports = { theme: { extend: { gridRowStart: { '8': '8', '9': '9', '10': '10', '11': '11', '12': '12', '13': '13', } } } } ``` To add new `row-end-{n}` utilities, use the `gridRowEnd` section of your Tailwind theme config: tailwind.config.js ``` module.exports = { theme: { extend: { gridRowEnd: { '8': '8', '9': '9', '10': '10', '11': '11', '12': '12', '13': '13', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `grid-row/grid-row-start/grid-row-end` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="row-[span_16_/_span_16]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/grid-rowGrid Auto Rows ============== Utilities for controlling the size of implicitly-created grid rows. Quick reference --------------- | Class | Properties | | --- | --- | | auto-rows-auto | grid-auto-rows: auto; | | auto-rows-min | grid-auto-rows: min-content; | | auto-rows-max | grid-auto-rows: max-content; | | auto-rows-fr | grid-auto-rows: minmax(0, 1fr); | Basic usage ----------- ### Sizing implicitly-created grid rows Use the `auto-rows-{size}` utilities to control the size of implicitly-created grid rows. ``` <div class="grid grid-flow-row auto-rows-max"> <div>01</div> <div>02</div> <div>03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:auto-rows-min` to only apply the `auto-rows-min` utility on hover. ``` <div class="grid grid-flow-row auto-rows-max hover:auto-rows-min"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:auto-rows-min` to apply the `auto-rows-min` utility at only medium screen sizes and above. ``` <div class="grid grid-flow-row auto-rows-max md:auto-rows-min"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes four general purpose `grid-auto-rows` utilities. You can customize these values by editing `theme.gridAutoRows` or `theme.extend.gridAutoRows` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { gridAutoRows: { '2fr': 'minmax(0, 2fr)', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `grid-auto-rows` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="grid grid-flow-row auto-rows-[minmax(0,_2fr)]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/grid-auto-rowsJustify Self ============ Utilities for controlling how an individual grid item is aligned along its inline axis. Quick reference --------------- | Class | Properties | | --- | --- | | justify-self-auto | justify-self: auto; | | justify-self-start | justify-self: start; | | justify-self-end | justify-self: end; | | justify-self-center | justify-self: center; | | justify-self-stretch | justify-self: stretch; | Basic usage ----------- ### Auto Use `justify-self-auto` to align an item based on the value of the grid’s `justify-items` property: ``` <div class="grid justify-items-stretch ..."> <!-- ... --> <div class="justify-self-auto ...">02</div> <!-- ... --> <!-- ... --> <!-- ... --> <!-- ... --> </div> ``` ### Start Use `justify-self-start` to align a grid item to the start its inline axis: ``` <div class="grid justify-items-stretch ..."> <!-- ... --> <div class="justify-self-start ...">02</div> <!-- ... --> <!-- ... --> <!-- ... --> <!-- ... --> </div> ``` ### Center Use `justify-self-center` to align a grid item along the center its inline axis: ``` <div class="grid justify-items-stretch ..."> <!-- ... --> <div class="justify-self-center ...">02</div> <!-- ... --> <!-- ... --> <!-- ... --> <!-- ... --> </div> ``` ### End Use `justify-self-end` to align a grid item to the end its inline axis: ``` <div class="grid justify-items-stretch ..."> <!-- ... --> <div class="justify-self-end ...">02</div> <!-- ... --> <!-- ... --> <!-- ... --> <!-- ... --> </div> ``` ### Stretch Use `justify-self-stretch` to stretch a grid item to fill the grid area on its inline axis: ``` <div class="grid justify-items-start ..."> <!-- ... --> <div class="justify-self-stretch ...">02</div> <!-- ... --> <!-- ... --> <!-- ... --> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:justify-self-end` to only apply the `justify-self-end` utility on hover. ``` <div class="justify-self-start hover:justify-self-end"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:justify-self-end` to apply the `justify-self-end` utility at only medium screen sizes and above. ``` <div class="justify-self-start md:justify-self-end"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/justify-selfAlign Content ============= Utilities for controlling how rows are positioned in multi-row flex and grid containers. Quick reference --------------- | Class | Properties | | --- | --- | | content-normal | align-content: normal; | | content-center | align-content: center; | | content-start | align-content: flex-start; | | content-end | align-content: flex-end; | | content-between | align-content: space-between; | | content-around | align-content: space-around; | | content-evenly | align-content: space-evenly; | | content-baseline | align-content: baseline; | | content-stretch | align-content: stretch; | Basic usage ----------- ### Start Use `content-start` to pack rows in a container against the start of the cross axis: ``` <div class="h-56 grid grid-cols-3 gap-4 content-start ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> </div> ``` ### Center Use `content-center` to pack rows in a container in the center of the cross axis: ``` <div class="h-56 grid grid-cols-3 gap-4 content-center ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> </div> ``` ### End Use `content-end` to pack rows in a container against the end of the cross axis: ``` <div class="h-56 grid grid-cols-3 gap-4 content-end ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> </div> ``` ### Space between Use `content-between` to distribute rows in a container such that there is an equal amount of space between each line: ``` <div class="h-56 grid grid-cols-3 gap-4 content-between ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> </div> ``` ### Space around Use `content-around` to distribute rows in a container such that there is an equal amount of space around each line: ``` <div class="h-56 grid grid-cols-3 gap-4 content-around ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> </div> ``` ### Space evenly Use `content-evenly` to distribute rows in a container such that there is an equal amount of space around each item, but also accounting for the doubling of space you would normally see between each item when using `content-around`: ``` <div class="h-56 grid grid-cols-3 gap-4 content-evenly ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> </div> ``` ### Stretch Use `content-stretch` to allow content items to fill the available space along the container’s cross axis: ``` <div class="h-56 grid grid-cols-3 gap-4 content-stretch ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> </div> ``` ### Normal Use `content-normal` to pack content items in their default position as if no `align-content` value was set: ``` <div class="h-56 grid grid-cols-3 gap-4 content-normal ..."> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:content-around` to only apply the `content-around` utility on hover. ``` <div class="grid content-start hover:content-around"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:content-around` to apply the `content-around` utility at only medium screen sizes and above. ``` <div class="grid content-start md:content-around"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/align-contentAlign Items =========== Utilities for controlling how flex and grid items are positioned along a container's cross axis. Quick reference --------------- | Class | Properties | | --- | --- | | items-start | align-items: flex-start; | | items-end | align-items: flex-end; | | items-center | align-items: center; | | items-baseline | align-items: baseline; | | items-stretch | align-items: stretch; | Basic usage ----------- ### Stretch Use `items-stretch` to stretch items to fill the container’s cross axis: ``` <div class="flex items-stretch ..."> <div class="py-4">01</div> <div class="py-12">02</div> <div class="py-8">03</div> </div> ``` ### Start Use `items-start` to align items to the start of the container’s cross axis: ``` <div class="flex items-start ..."> <div class="py-4">01</div> <div class="py-12">02</div> <div class="py-8">03</div> </div> ``` ### Center Use `items-center` to align items along the center of the container’s cross axis: ``` <div class="flex items-center ..."> <div class="py-4">01</div> <div class="py-12">02</div> <div class="py-8">03</div> </div> ``` ### End Use `items-end` to align items to the end of the container’s cross axis: ``` <div class="flex items-end ..."> <div class="py-4">01</div> <div class="py-12">02</div> <div class="py-8">03</div> </div> ``` ### Baseline Use `items-baseline` to align items along the container’s cross axis such that all of their baselines align: ``` <div class="flex items-baseline ..."> <div class="pt-2 pb-6">01</div> <div class="pt-8 pb-12">02</div> <div class="pt-12 pb-4">03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:items-center` to only apply the `items-center` utility on hover. ``` <div class="flex items-stretch hover:items-center"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:items-center` to apply the `items-center` utility at only medium screen sizes and above. ``` <div class="flex items-stretch md:items-center"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/align-itemsAlign Self ========== Utilities for controlling how an individual flex or grid item is positioned along its container's cross axis. Quick reference --------------- | Class | Properties | | --- | --- | | self-auto | align-self: auto; | | self-start | align-self: flex-start; | | self-end | align-self: flex-end; | | self-center | align-self: center; | | self-stretch | align-self: stretch; | | self-baseline | align-self: baseline; | Basic usage ----------- ### Auto Use `self-auto` to align an item based on the value of the container’s `align-items` property: ``` <div class="flex items-stretch ..."> <div>01</div> <div class="self-auto ...">02</div> <div>03</div> </div> ``` ### Start Use `self-start` to align an item to the start of the container’s cross axis, despite the container’s `align-items` value: ``` <div class="flex items-stretch ..."> <div>01</div> <div class="self-start ...">02</div> <div>03</div> </div> ``` ### Center Use `self-center` to align an item along the center of the container’s cross axis, despite the container’s `align-items` value: ``` <div class="flex items-stretch ..."> <div>01</div> <div class="self-center ...">02</div> <div>03</div> </div> ``` ### End Use `self-end` to align an item to the end of the container’s cross axis, despite the container’s `align-items` value: ``` <div class="flex items-stretch ..."> <div>01</div> <div class="self-end ...">02</div> <div>03</div> </div> ``` ### Stretch Use `self-stretch` to stretch an item to fill the container’s cross axis, despite the container’s `align-items` value: ``` <div class="flex items-stretch ..."> <div>01</div> <div class="self-stretch ...">02</div> <div>03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:self-end` to only apply the `self-end` utility on hover. ``` <div class="self-auto hover:self-end"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:self-end` to apply the `self-end` utility at only medium screen sizes and above. ``` <div class="self-auto md:self-end"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/align-selfPadding ======= Utilities for controlling an element's padding. Quick reference --------------- | Class | Properties | | --- | --- | | p-0 | padding: 0px; | | px-0 | padding-left: 0px; padding-right: 0px; | | py-0 | padding-top: 0px; padding-bottom: 0px; | | ps-0 | padding-inline-start: 0px; | | pe-0 | padding-inline-end: 0px; | | pt-0 | padding-top: 0px; | | pr-0 | padding-right: 0px; | | pb-0 | padding-bottom: 0px; | | pl-0 | padding-left: 0px; | | p-px | padding: 1px; | | px-px | padding-left: 1px; padding-right: 1px; | | py-px | padding-top: 1px; padding-bottom: 1px; | | ps-px | padding-inline-start: 1px; | | pe-px | padding-inline-end: 1px; | | pt-px | padding-top: 1px; | | pr-px | padding-right: 1px; | | pb-px | padding-bottom: 1px; | | pl-px | padding-left: 1px; | | p-0.5 | padding: 0.125rem; /* 2px */ | | px-0.5 | padding-left: 0.125rem; /* 2px */ padding-right: 0.125rem; /* 2px */ | | py-0.5 | padding-top: 0.125rem; /* 2px */ padding-bottom: 0.125rem; /* 2px */ | | ps-0.5 | padding-inline-start: 0.125rem; /* 2px */ | | pe-0.5 | padding-inline-end: 0.125rem; /* 2px */ | | pt-0.5 | padding-top: 0.125rem; /* 2px */ | | pr-0.5 | padding-right: 0.125rem; /* 2px */ | | pb-0.5 | padding-bottom: 0.125rem; /* 2px */ | | pl-0.5 | padding-left: 0.125rem; /* 2px */ | | p-1 | padding: 0.25rem; /* 4px */ | | px-1 | padding-left: 0.25rem; /* 4px */ padding-right: 0.25rem; /* 4px */ | | py-1 | padding-top: 0.25rem; /* 4px */ padding-bottom: 0.25rem; /* 4px */ | | ps-1 | padding-inline-start: 0.25rem; /* 4px */ | | pe-1 | padding-inline-end: 0.25rem; /* 4px */ | | pt-1 | padding-top: 0.25rem; /* 4px */ | | pr-1 | padding-right: 0.25rem; /* 4px */ | | pb-1 | padding-bottom: 0.25rem; /* 4px */ | | pl-1 | padding-left: 0.25rem; /* 4px */ | | p-1.5 | padding: 0.375rem; /* 6px */ | | px-1.5 | padding-left: 0.375rem; /* 6px */ padding-right: 0.375rem; /* 6px */ | | py-1.5 | padding-top: 0.375rem; /* 6px */ padding-bottom: 0.375rem; /* 6px */ | | ps-1.5 | padding-inline-start: 0.375rem; /* 6px */ | | pe-1.5 | padding-inline-end: 0.375rem; /* 6px */ | | pt-1.5 | padding-top: 0.375rem; /* 6px */ | | pr-1.5 | padding-right: 0.375rem; /* 6px */ | | pb-1.5 | padding-bottom: 0.375rem; /* 6px */ | | pl-1.5 | padding-left: 0.375rem; /* 6px */ | | p-2 | padding: 0.5rem; /* 8px */ | | px-2 | padding-left: 0.5rem; /* 8px */ padding-right: 0.5rem; /* 8px */ | | py-2 | padding-top: 0.5rem; /* 8px */ padding-bottom: 0.5rem; /* 8px */ | | ps-2 | padding-inline-start: 0.5rem; /* 8px */ | | pe-2 | padding-inline-end: 0.5rem; /* 8px */ | | pt-2 | padding-top: 0.5rem; /* 8px */ | | pr-2 | padding-right: 0.5rem; /* 8px */ | | pb-2 | padding-bottom: 0.5rem; /* 8px */ | | pl-2 | padding-left: 0.5rem; /* 8px */ | | p-2.5 | padding: 0.625rem; /* 10px */ | | px-2.5 | padding-left: 0.625rem; /* 10px */ padding-right: 0.625rem; /* 10px */ | | py-2.5 | padding-top: 0.625rem; /* 10px */ padding-bottom: 0.625rem; /* 10px */ | | ps-2.5 | padding-inline-start: 0.625rem; /* 10px */ | | pe-2.5 | padding-inline-end: 0.625rem; /* 10px */ | | pt-2.5 | padding-top: 0.625rem; /* 10px */ | | pr-2.5 | padding-right: 0.625rem; /* 10px */ | | pb-2.5 | padding-bottom: 0.625rem; /* 10px */ | | pl-2.5 | padding-left: 0.625rem; /* 10px */ | | p-3 | padding: 0.75rem; /* 12px */ | | px-3 | padding-left: 0.75rem; /* 12px */ padding-right: 0.75rem; /* 12px */ | | py-3 | padding-top: 0.75rem; /* 12px */ padding-bottom: 0.75rem; /* 12px */ | | ps-3 | padding-inline-start: 0.75rem; /* 12px */ | | pe-3 | padding-inline-end: 0.75rem; /* 12px */ | | pt-3 | padding-top: 0.75rem; /* 12px */ | | pr-3 | padding-right: 0.75rem; /* 12px */ | | pb-3 | padding-bottom: 0.75rem; /* 12px */ | | pl-3 | padding-left: 0.75rem; /* 12px */ | | p-3.5 | padding: 0.875rem; /* 14px */ | | px-3.5 | padding-left: 0.875rem; /* 14px */ padding-right: 0.875rem; /* 14px */ | | py-3.5 | padding-top: 0.875rem; /* 14px */ padding-bottom: 0.875rem; /* 14px */ | | ps-3.5 | padding-inline-start: 0.875rem; /* 14px */ | | pe-3.5 | padding-inline-end: 0.875rem; /* 14px */ | | pt-3.5 | padding-top: 0.875rem; /* 14px */ | | pr-3.5 | padding-right: 0.875rem; /* 14px */ | | pb-3.5 | padding-bottom: 0.875rem; /* 14px */ | | pl-3.5 | padding-left: 0.875rem; /* 14px */ | | p-4 | padding: 1rem; /* 16px */ | | px-4 | padding-left: 1rem; /* 16px */ padding-right: 1rem; /* 16px */ | | py-4 | padding-top: 1rem; /* 16px */ padding-bottom: 1rem; /* 16px */ | | ps-4 | padding-inline-start: 1rem; /* 16px */ | | pe-4 | padding-inline-end: 1rem; /* 16px */ | | pt-4 | padding-top: 1rem; /* 16px */ | | pr-4 | padding-right: 1rem; /* 16px */ | | pb-4 | padding-bottom: 1rem; /* 16px */ | | pl-4 | padding-left: 1rem; /* 16px */ | | p-5 | padding: 1.25rem; /* 20px */ | | px-5 | padding-left: 1.25rem; /* 20px */ padding-right: 1.25rem; /* 20px */ | | py-5 | padding-top: 1.25rem; /* 20px */ padding-bottom: 1.25rem; /* 20px */ | | ps-5 | padding-inline-start: 1.25rem; /* 20px */ | | pe-5 | padding-inline-end: 1.25rem; /* 20px */ | | pt-5 | padding-top: 1.25rem; /* 20px */ | | pr-5 | padding-right: 1.25rem; /* 20px */ | | pb-5 | padding-bottom: 1.25rem; /* 20px */ | | pl-5 | padding-left: 1.25rem; /* 20px */ | | p-6 | padding: 1.5rem; /* 24px */ | | px-6 | padding-left: 1.5rem; /* 24px */ padding-right: 1.5rem; /* 24px */ | | py-6 | padding-top: 1.5rem; /* 24px */ padding-bottom: 1.5rem; /* 24px */ | | ps-6 | padding-inline-start: 1.5rem; /* 24px */ | | pe-6 | padding-inline-end: 1.5rem; /* 24px */ | | pt-6 | padding-top: 1.5rem; /* 24px */ | | pr-6 | padding-right: 1.5rem; /* 24px */ | | pb-6 | padding-bottom: 1.5rem; /* 24px */ | | pl-6 | padding-left: 1.5rem; /* 24px */ | | p-7 | padding: 1.75rem; /* 28px */ | | px-7 | padding-left: 1.75rem; /* 28px */ padding-right: 1.75rem; /* 28px */ | | py-7 | padding-top: 1.75rem; /* 28px */ padding-bottom: 1.75rem; /* 28px */ | | ps-7 | padding-inline-start: 1.75rem; /* 28px */ | | pe-7 | padding-inline-end: 1.75rem; /* 28px */ | | pt-7 | padding-top: 1.75rem; /* 28px */ | | pr-7 | padding-right: 1.75rem; /* 28px */ | | pb-7 | padding-bottom: 1.75rem; /* 28px */ | | pl-7 | padding-left: 1.75rem; /* 28px */ | | p-8 | padding: 2rem; /* 32px */ | | px-8 | padding-left: 2rem; /* 32px */ padding-right: 2rem; /* 32px */ | | py-8 | padding-top: 2rem; /* 32px */ padding-bottom: 2rem; /* 32px */ | | ps-8 | padding-inline-start: 2rem; /* 32px */ | | pe-8 | padding-inline-end: 2rem; /* 32px */ | | pt-8 | padding-top: 2rem; /* 32px */ | | pr-8 | padding-right: 2rem; /* 32px */ | | pb-8 | padding-bottom: 2rem; /* 32px */ | | pl-8 | padding-left: 2rem; /* 32px */ | | p-9 | padding: 2.25rem; /* 36px */ | | px-9 | padding-left: 2.25rem; /* 36px */ padding-right: 2.25rem; /* 36px */ | | py-9 | padding-top: 2.25rem; /* 36px */ padding-bottom: 2.25rem; /* 36px */ | | ps-9 | padding-inline-start: 2.25rem; /* 36px */ | | pe-9 | padding-inline-end: 2.25rem; /* 36px */ | | pt-9 | padding-top: 2.25rem; /* 36px */ | | pr-9 | padding-right: 2.25rem; /* 36px */ | | pb-9 | padding-bottom: 2.25rem; /* 36px */ | | pl-9 | padding-left: 2.25rem; /* 36px */ | | p-10 | padding: 2.5rem; /* 40px */ | | px-10 | padding-left: 2.5rem; /* 40px */ padding-right: 2.5rem; /* 40px */ | | py-10 | padding-top: 2.5rem; /* 40px */ padding-bottom: 2.5rem; /* 40px */ | | ps-10 | padding-inline-start: 2.5rem; /* 40px */ | | pe-10 | padding-inline-end: 2.5rem; /* 40px */ | | pt-10 | padding-top: 2.5rem; /* 40px */ | | pr-10 | padding-right: 2.5rem; /* 40px */ | | pb-10 | padding-bottom: 2.5rem; /* 40px */ | | pl-10 | padding-left: 2.5rem; /* 40px */ | | p-11 | padding: 2.75rem; /* 44px */ | | px-11 | padding-left: 2.75rem; /* 44px */ padding-right: 2.75rem; /* 44px */ | | py-11 | padding-top: 2.75rem; /* 44px */ padding-bottom: 2.75rem; /* 44px */ | | ps-11 | padding-inline-start: 2.75rem; /* 44px */ | | pe-11 | padding-inline-end: 2.75rem; /* 44px */ | | pt-11 | padding-top: 2.75rem; /* 44px */ | | pr-11 | padding-right: 2.75rem; /* 44px */ | | pb-11 | padding-bottom: 2.75rem; /* 44px */ | | pl-11 | padding-left: 2.75rem; /* 44px */ | | p-12 | padding: 3rem; /* 48px */ | | px-12 | padding-left: 3rem; /* 48px */ padding-right: 3rem; /* 48px */ | | py-12 | padding-top: 3rem; /* 48px */ padding-bottom: 3rem; /* 48px */ | | ps-12 | padding-inline-start: 3rem; /* 48px */ | | pe-12 | padding-inline-end: 3rem; /* 48px */ | | pt-12 | padding-top: 3rem; /* 48px */ | | pr-12 | padding-right: 3rem; /* 48px */ | | pb-12 | padding-bottom: 3rem; /* 48px */ | | pl-12 | padding-left: 3rem; /* 48px */ | | p-14 | padding: 3.5rem; /* 56px */ | | px-14 | padding-left: 3.5rem; /* 56px */ padding-right: 3.5rem; /* 56px */ | | py-14 | padding-top: 3.5rem; /* 56px */ padding-bottom: 3.5rem; /* 56px */ | | ps-14 | padding-inline-start: 3.5rem; /* 56px */ | | pe-14 | padding-inline-end: 3.5rem; /* 56px */ | | pt-14 | padding-top: 3.5rem; /* 56px */ | | pr-14 | padding-right: 3.5rem; /* 56px */ | | pb-14 | padding-bottom: 3.5rem; /* 56px */ | | pl-14 | padding-left: 3.5rem; /* 56px */ | | p-16 | padding: 4rem; /* 64px */ | | px-16 | padding-left: 4rem; /* 64px */ padding-right: 4rem; /* 64px */ | | py-16 | padding-top: 4rem; /* 64px */ padding-bottom: 4rem; /* 64px */ | | ps-16 | padding-inline-start: 4rem; /* 64px */ | | pe-16 | padding-inline-end: 4rem; /* 64px */ | | pt-16 | padding-top: 4rem; /* 64px */ | | pr-16 | padding-right: 4rem; /* 64px */ | | pb-16 | padding-bottom: 4rem; /* 64px */ | | pl-16 | padding-left: 4rem; /* 64px */ | | p-20 | padding: 5rem; /* 80px */ | | px-20 | padding-left: 5rem; /* 80px */ padding-right: 5rem; /* 80px */ | | py-20 | padding-top: 5rem; /* 80px */ padding-bottom: 5rem; /* 80px */ | | ps-20 | padding-inline-start: 5rem; /* 80px */ | | pe-20 | padding-inline-end: 5rem; /* 80px */ | | pt-20 | padding-top: 5rem; /* 80px */ | | pr-20 | padding-right: 5rem; /* 80px */ | | pb-20 | padding-bottom: 5rem; /* 80px */ | | pl-20 | padding-left: 5rem; /* 80px */ | | p-24 | padding: 6rem; /* 96px */ | | px-24 | padding-left: 6rem; /* 96px */ padding-right: 6rem; /* 96px */ | | py-24 | padding-top: 6rem; /* 96px */ padding-bottom: 6rem; /* 96px */ | | ps-24 | padding-inline-start: 6rem; /* 96px */ | | pe-24 | padding-inline-end: 6rem; /* 96px */ | | pt-24 | padding-top: 6rem; /* 96px */ | | pr-24 | padding-right: 6rem; /* 96px */ | | pb-24 | padding-bottom: 6rem; /* 96px */ | | pl-24 | padding-left: 6rem; /* 96px */ | | p-28 | padding: 7rem; /* 112px */ | | px-28 | padding-left: 7rem; /* 112px */ padding-right: 7rem; /* 112px */ | | py-28 | padding-top: 7rem; /* 112px */ padding-bottom: 7rem; /* 112px */ | | ps-28 | padding-inline-start: 7rem; /* 112px */ | | pe-28 | padding-inline-end: 7rem; /* 112px */ | | pt-28 | padding-top: 7rem; /* 112px */ | | pr-28 | padding-right: 7rem; /* 112px */ | | pb-28 | padding-bottom: 7rem; /* 112px */ | | pl-28 | padding-left: 7rem; /* 112px */ | | p-32 | padding: 8rem; /* 128px */ | | px-32 | padding-left: 8rem; /* 128px */ padding-right: 8rem; /* 128px */ | | py-32 | padding-top: 8rem; /* 128px */ padding-bottom: 8rem; /* 128px */ | | ps-32 | padding-inline-start: 8rem; /* 128px */ | | pe-32 | padding-inline-end: 8rem; /* 128px */ | | pt-32 | padding-top: 8rem; /* 128px */ | | pr-32 | padding-right: 8rem; /* 128px */ | | pb-32 | padding-bottom: 8rem; /* 128px */ | | pl-32 | padding-left: 8rem; /* 128px */ | | p-36 | padding: 9rem; /* 144px */ | | px-36 | padding-left: 9rem; /* 144px */ padding-right: 9rem; /* 144px */ | | py-36 | padding-top: 9rem; /* 144px */ padding-bottom: 9rem; /* 144px */ | | ps-36 | padding-inline-start: 9rem; /* 144px */ | | pe-36 | padding-inline-end: 9rem; /* 144px */ | | pt-36 | padding-top: 9rem; /* 144px */ | | pr-36 | padding-right: 9rem; /* 144px */ | | pb-36 | padding-bottom: 9rem; /* 144px */ | | pl-36 | padding-left: 9rem; /* 144px */ | | p-40 | padding: 10rem; /* 160px */ | | px-40 | padding-left: 10rem; /* 160px */ padding-right: 10rem; /* 160px */ | | py-40 | padding-top: 10rem; /* 160px */ padding-bottom: 10rem; /* 160px */ | | ps-40 | padding-inline-start: 10rem; /* 160px */ | | pe-40 | padding-inline-end: 10rem; /* 160px */ | | pt-40 | padding-top: 10rem; /* 160px */ | | pr-40 | padding-right: 10rem; /* 160px */ | | pb-40 | padding-bottom: 10rem; /* 160px */ | | pl-40 | padding-left: 10rem; /* 160px */ | | p-44 | padding: 11rem; /* 176px */ | | px-44 | padding-left: 11rem; /* 176px */ padding-right: 11rem; /* 176px */ | | py-44 | padding-top: 11rem; /* 176px */ padding-bottom: 11rem; /* 176px */ | | ps-44 | padding-inline-start: 11rem; /* 176px */ | | pe-44 | padding-inline-end: 11rem; /* 176px */ | | pt-44 | padding-top: 11rem; /* 176px */ | | pr-44 | padding-right: 11rem; /* 176px */ | | pb-44 | padding-bottom: 11rem; /* 176px */ | | pl-44 | padding-left: 11rem; /* 176px */ | | p-48 | padding: 12rem; /* 192px */ | | px-48 | padding-left: 12rem; /* 192px */ padding-right: 12rem; /* 192px */ | | py-48 | padding-top: 12rem; /* 192px */ padding-bottom: 12rem; /* 192px */ | | ps-48 | padding-inline-start: 12rem; /* 192px */ | | pe-48 | padding-inline-end: 12rem; /* 192px */ | | pt-48 | padding-top: 12rem; /* 192px */ | | pr-48 | padding-right: 12rem; /* 192px */ | | pb-48 | padding-bottom: 12rem; /* 192px */ | | pl-48 | padding-left: 12rem; /* 192px */ | | p-52 | padding: 13rem; /* 208px */ | | px-52 | padding-left: 13rem; /* 208px */ padding-right: 13rem; /* 208px */ | | py-52 | padding-top: 13rem; /* 208px */ padding-bottom: 13rem; /* 208px */ | | ps-52 | padding-inline-start: 13rem; /* 208px */ | | pe-52 | padding-inline-end: 13rem; /* 208px */ | | pt-52 | padding-top: 13rem; /* 208px */ | | pr-52 | padding-right: 13rem; /* 208px */ | | pb-52 | padding-bottom: 13rem; /* 208px */ | | pl-52 | padding-left: 13rem; /* 208px */ | | p-56 | padding: 14rem; /* 224px */ | | px-56 | padding-left: 14rem; /* 224px */ padding-right: 14rem; /* 224px */ | | py-56 | padding-top: 14rem; /* 224px */ padding-bottom: 14rem; /* 224px */ | | ps-56 | padding-inline-start: 14rem; /* 224px */ | | pe-56 | padding-inline-end: 14rem; /* 224px */ | | pt-56 | padding-top: 14rem; /* 224px */ | | pr-56 | padding-right: 14rem; /* 224px */ | | pb-56 | padding-bottom: 14rem; /* 224px */ | | pl-56 | padding-left: 14rem; /* 224px */ | | p-60 | padding: 15rem; /* 240px */ | | px-60 | padding-left: 15rem; /* 240px */ padding-right: 15rem; /* 240px */ | | py-60 | padding-top: 15rem; /* 240px */ padding-bottom: 15rem; /* 240px */ | | ps-60 | padding-inline-start: 15rem; /* 240px */ | | pe-60 | padding-inline-end: 15rem; /* 240px */ | | pt-60 | padding-top: 15rem; /* 240px */ | | pr-60 | padding-right: 15rem; /* 240px */ | | pb-60 | padding-bottom: 15rem; /* 240px */ | | pl-60 | padding-left: 15rem; /* 240px */ | | p-64 | padding: 16rem; /* 256px */ | | px-64 | padding-left: 16rem; /* 256px */ padding-right: 16rem; /* 256px */ | | py-64 | padding-top: 16rem; /* 256px */ padding-bottom: 16rem; /* 256px */ | | ps-64 | padding-inline-start: 16rem; /* 256px */ | | pe-64 | padding-inline-end: 16rem; /* 256px */ | | pt-64 | padding-top: 16rem; /* 256px */ | | pr-64 | padding-right: 16rem; /* 256px */ | | pb-64 | padding-bottom: 16rem; /* 256px */ | | pl-64 | padding-left: 16rem; /* 256px */ | | p-72 | padding: 18rem; /* 288px */ | | px-72 | padding-left: 18rem; /* 288px */ padding-right: 18rem; /* 288px */ | | py-72 | padding-top: 18rem; /* 288px */ padding-bottom: 18rem; /* 288px */ | | ps-72 | padding-inline-start: 18rem; /* 288px */ | | pe-72 | padding-inline-end: 18rem; /* 288px */ | | pt-72 | padding-top: 18rem; /* 288px */ | | pr-72 | padding-right: 18rem; /* 288px */ | | pb-72 | padding-bottom: 18rem; /* 288px */ | | pl-72 | padding-left: 18rem; /* 288px */ | | p-80 | padding: 20rem; /* 320px */ | | px-80 | padding-left: 20rem; /* 320px */ padding-right: 20rem; /* 320px */ | | py-80 | padding-top: 20rem; /* 320px */ padding-bottom: 20rem; /* 320px */ | | ps-80 | padding-inline-start: 20rem; /* 320px */ | | pe-80 | padding-inline-end: 20rem; /* 320px */ | | pt-80 | padding-top: 20rem; /* 320px */ | | pr-80 | padding-right: 20rem; /* 320px */ | | pb-80 | padding-bottom: 20rem; /* 320px */ | | pl-80 | padding-left: 20rem; /* 320px */ | | p-96 | padding: 24rem; /* 384px */ | | px-96 | padding-left: 24rem; /* 384px */ padding-right: 24rem; /* 384px */ | | py-96 | padding-top: 24rem; /* 384px */ padding-bottom: 24rem; /* 384px */ | | ps-96 | padding-inline-start: 24rem; /* 384px */ | | pe-96 | padding-inline-end: 24rem; /* 384px */ | | pt-96 | padding-top: 24rem; /* 384px */ | | pr-96 | padding-right: 24rem; /* 384px */ | | pb-96 | padding-bottom: 24rem; /* 384px */ | | pl-96 | padding-left: 24rem; /* 384px */ | Basic usage ----------- ### Add padding to a single side Control the padding on one side of an element using the `p{t|r|b|l}-{size}` utilities. For example, `pt-6` would add `1.5rem` of padding to the top of an element, `pr-4` would add `1rem` of padding to the right of an element, `pb-8` would add `2rem` of padding to the bottom of an element, and `pl-2` would add `0.5rem` of padding to the left of an element. ``` <div class="pt-6 ...">pt-6</div> <div class="pr-4 ...">pr-4</div> <div class="pb-8 ...">pb-8</div> <div class="pl-2 ...">pl-2</div> ``` ### Add horizontal padding Control the horizontal padding of an element using the `px-{size}` utilities. ``` <div class="px-8 ...">px-8</div> ``` ### Add vertical padding Control the vertical padding of an element using the `py-{size}` utilities. ``` <div class="py-8 ...">py-8</div> ``` ### Add padding to all sides Control the padding on all sides of an element using the `p-{size}` utilities. ``` <div class="p-8 ...">p-8</div> ``` ### Using logical properties Use the `ps-*` and `pe-*` utilities to set the `padding-inline-start` and `padding-inline-end` [logical properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties/Basic_concepts), which map to either the left or right side based on the text direction. ``` <div dir="ltr"> <div class="ps-8 ...">ps-8</div> <div class="pe-8 ...">pe-8</div> <div<div dir="rtl"> <div class="ps-8 ...">ps-8</div> <div class="pe-8 ...">pe-8</div> <div> ``` For more control, you can also use the [LTR and RTL modifiers](hover-focus-and-other-states#rtl-support) to conditionally apply specific styles depending on the current text direction. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:py-8` to only apply the `py-8` utility on hover. ``` <div class="py-4 hover:py-8"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:py-8` to apply the `py-8` utility at only medium screen sizes and above. ``` <div class="py-4 md:py-8"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind’s padding scale uses the [default spacing scale](customizing-spacing). You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '5px': '5px', } } } } ``` Alternatively, you can customize just the padding scale by editing `theme.padding` or `theme.extend.padding` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { padding: { '5px': '5px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `padding` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="p-[5px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/paddingMargin ====== Utilities for controlling an element's margin. Quick reference --------------- | Class | Properties | | --- | --- | | m-0 | margin: 0px; | | mx-0 | margin-left: 0px; margin-right: 0px; | | my-0 | margin-top: 0px; margin-bottom: 0px; | | ms-0 | margin-inline-start: 0px; | | me-0 | margin-inline-end: 0px; | | mt-0 | margin-top: 0px; | | mr-0 | margin-right: 0px; | | mb-0 | margin-bottom: 0px; | | ml-0 | margin-left: 0px; | | m-px | margin: 1px; | | mx-px | margin-left: 1px; margin-right: 1px; | | my-px | margin-top: 1px; margin-bottom: 1px; | | ms-px | margin-inline-start: 1px; | | me-px | margin-inline-end: 1px; | | mt-px | margin-top: 1px; | | mr-px | margin-right: 1px; | | mb-px | margin-bottom: 1px; | | ml-px | margin-left: 1px; | | m-0.5 | margin: 0.125rem; /* 2px */ | | mx-0.5 | margin-left: 0.125rem; /* 2px */ margin-right: 0.125rem; /* 2px */ | | my-0.5 | margin-top: 0.125rem; /* 2px */ margin-bottom: 0.125rem; /* 2px */ | | ms-0.5 | margin-inline-start: 0.125rem; /* 2px */ | | me-0.5 | margin-inline-end: 0.125rem; /* 2px */ | | mt-0.5 | margin-top: 0.125rem; /* 2px */ | | mr-0.5 | margin-right: 0.125rem; /* 2px */ | | mb-0.5 | margin-bottom: 0.125rem; /* 2px */ | | ml-0.5 | margin-left: 0.125rem; /* 2px */ | | m-1 | margin: 0.25rem; /* 4px */ | | mx-1 | margin-left: 0.25rem; /* 4px */ margin-right: 0.25rem; /* 4px */ | | my-1 | margin-top: 0.25rem; /* 4px */ margin-bottom: 0.25rem; /* 4px */ | | ms-1 | margin-inline-start: 0.25rem; /* 4px */ | | me-1 | margin-inline-end: 0.25rem; /* 4px */ | | mt-1 | margin-top: 0.25rem; /* 4px */ | | mr-1 | margin-right: 0.25rem; /* 4px */ | | mb-1 | margin-bottom: 0.25rem; /* 4px */ | | ml-1 | margin-left: 0.25rem; /* 4px */ | | m-1.5 | margin: 0.375rem; /* 6px */ | | mx-1.5 | margin-left: 0.375rem; /* 6px */ margin-right: 0.375rem; /* 6px */ | | my-1.5 | margin-top: 0.375rem; /* 6px */ margin-bottom: 0.375rem; /* 6px */ | | ms-1.5 | margin-inline-start: 0.375rem; /* 6px */ | | me-1.5 | margin-inline-end: 0.375rem; /* 6px */ | | mt-1.5 | margin-top: 0.375rem; /* 6px */ | | mr-1.5 | margin-right: 0.375rem; /* 6px */ | | mb-1.5 | margin-bottom: 0.375rem; /* 6px */ | | ml-1.5 | margin-left: 0.375rem; /* 6px */ | | m-2 | margin: 0.5rem; /* 8px */ | | mx-2 | margin-left: 0.5rem; /* 8px */ margin-right: 0.5rem; /* 8px */ | | my-2 | margin-top: 0.5rem; /* 8px */ margin-bottom: 0.5rem; /* 8px */ | | ms-2 | margin-inline-start: 0.5rem; /* 8px */ | | me-2 | margin-inline-end: 0.5rem; /* 8px */ | | mt-2 | margin-top: 0.5rem; /* 8px */ | | mr-2 | margin-right: 0.5rem; /* 8px */ | | mb-2 | margin-bottom: 0.5rem; /* 8px */ | | ml-2 | margin-left: 0.5rem; /* 8px */ | | m-2.5 | margin: 0.625rem; /* 10px */ | | mx-2.5 | margin-left: 0.625rem; /* 10px */ margin-right: 0.625rem; /* 10px */ | | my-2.5 | margin-top: 0.625rem; /* 10px */ margin-bottom: 0.625rem; /* 10px */ | | ms-2.5 | margin-inline-start: 0.625rem; /* 10px */ | | me-2.5 | margin-inline-end: 0.625rem; /* 10px */ | | mt-2.5 | margin-top: 0.625rem; /* 10px */ | | mr-2.5 | margin-right: 0.625rem; /* 10px */ | | mb-2.5 | margin-bottom: 0.625rem; /* 10px */ | | ml-2.5 | margin-left: 0.625rem; /* 10px */ | | m-3 | margin: 0.75rem; /* 12px */ | | mx-3 | margin-left: 0.75rem; /* 12px */ margin-right: 0.75rem; /* 12px */ | | my-3 | margin-top: 0.75rem; /* 12px */ margin-bottom: 0.75rem; /* 12px */ | | ms-3 | margin-inline-start: 0.75rem; /* 12px */ | | me-3 | margin-inline-end: 0.75rem; /* 12px */ | | mt-3 | margin-top: 0.75rem; /* 12px */ | | mr-3 | margin-right: 0.75rem; /* 12px */ | | mb-3 | margin-bottom: 0.75rem; /* 12px */ | | ml-3 | margin-left: 0.75rem; /* 12px */ | | m-3.5 | margin: 0.875rem; /* 14px */ | | mx-3.5 | margin-left: 0.875rem; /* 14px */ margin-right: 0.875rem; /* 14px */ | | my-3.5 | margin-top: 0.875rem; /* 14px */ margin-bottom: 0.875rem; /* 14px */ | | ms-3.5 | margin-inline-start: 0.875rem; /* 14px */ | | me-3.5 | margin-inline-end: 0.875rem; /* 14px */ | | mt-3.5 | margin-top: 0.875rem; /* 14px */ | | mr-3.5 | margin-right: 0.875rem; /* 14px */ | | mb-3.5 | margin-bottom: 0.875rem; /* 14px */ | | ml-3.5 | margin-left: 0.875rem; /* 14px */ | | m-4 | margin: 1rem; /* 16px */ | | mx-4 | margin-left: 1rem; /* 16px */ margin-right: 1rem; /* 16px */ | | my-4 | margin-top: 1rem; /* 16px */ margin-bottom: 1rem; /* 16px */ | | ms-4 | margin-inline-start: 1rem; /* 16px */ | | me-4 | margin-inline-end: 1rem; /* 16px */ | | mt-4 | margin-top: 1rem; /* 16px */ | | mr-4 | margin-right: 1rem; /* 16px */ | | mb-4 | margin-bottom: 1rem; /* 16px */ | | ml-4 | margin-left: 1rem; /* 16px */ | | m-5 | margin: 1.25rem; /* 20px */ | | mx-5 | margin-left: 1.25rem; /* 20px */ margin-right: 1.25rem; /* 20px */ | | my-5 | margin-top: 1.25rem; /* 20px */ margin-bottom: 1.25rem; /* 20px */ | | ms-5 | margin-inline-start: 1.25rem; /* 20px */ | | me-5 | margin-inline-end: 1.25rem; /* 20px */ | | mt-5 | margin-top: 1.25rem; /* 20px */ | | mr-5 | margin-right: 1.25rem; /* 20px */ | | mb-5 | margin-bottom: 1.25rem; /* 20px */ | | ml-5 | margin-left: 1.25rem; /* 20px */ | | m-6 | margin: 1.5rem; /* 24px */ | | mx-6 | margin-left: 1.5rem; /* 24px */ margin-right: 1.5rem; /* 24px */ | | my-6 | margin-top: 1.5rem; /* 24px */ margin-bottom: 1.5rem; /* 24px */ | | ms-6 | margin-inline-start: 1.5rem; /* 24px */ | | me-6 | margin-inline-end: 1.5rem; /* 24px */ | | mt-6 | margin-top: 1.5rem; /* 24px */ | | mr-6 | margin-right: 1.5rem; /* 24px */ | | mb-6 | margin-bottom: 1.5rem; /* 24px */ | | ml-6 | margin-left: 1.5rem; /* 24px */ | | m-7 | margin: 1.75rem; /* 28px */ | | mx-7 | margin-left: 1.75rem; /* 28px */ margin-right: 1.75rem; /* 28px */ | | my-7 | margin-top: 1.75rem; /* 28px */ margin-bottom: 1.75rem; /* 28px */ | | ms-7 | margin-inline-start: 1.75rem; /* 28px */ | | me-7 | margin-inline-end: 1.75rem; /* 28px */ | | mt-7 | margin-top: 1.75rem; /* 28px */ | | mr-7 | margin-right: 1.75rem; /* 28px */ | | mb-7 | margin-bottom: 1.75rem; /* 28px */ | | ml-7 | margin-left: 1.75rem; /* 28px */ | | m-8 | margin: 2rem; /* 32px */ | | mx-8 | margin-left: 2rem; /* 32px */ margin-right: 2rem; /* 32px */ | | my-8 | margin-top: 2rem; /* 32px */ margin-bottom: 2rem; /* 32px */ | | ms-8 | margin-inline-start: 2rem; /* 32px */ | | me-8 | margin-inline-end: 2rem; /* 32px */ | | mt-8 | margin-top: 2rem; /* 32px */ | | mr-8 | margin-right: 2rem; /* 32px */ | | mb-8 | margin-bottom: 2rem; /* 32px */ | | ml-8 | margin-left: 2rem; /* 32px */ | | m-9 | margin: 2.25rem; /* 36px */ | | mx-9 | margin-left: 2.25rem; /* 36px */ margin-right: 2.25rem; /* 36px */ | | my-9 | margin-top: 2.25rem; /* 36px */ margin-bottom: 2.25rem; /* 36px */ | | ms-9 | margin-inline-start: 2.25rem; /* 36px */ | | me-9 | margin-inline-end: 2.25rem; /* 36px */ | | mt-9 | margin-top: 2.25rem; /* 36px */ | | mr-9 | margin-right: 2.25rem; /* 36px */ | | mb-9 | margin-bottom: 2.25rem; /* 36px */ | | ml-9 | margin-left: 2.25rem; /* 36px */ | | m-10 | margin: 2.5rem; /* 40px */ | | mx-10 | margin-left: 2.5rem; /* 40px */ margin-right: 2.5rem; /* 40px */ | | my-10 | margin-top: 2.5rem; /* 40px */ margin-bottom: 2.5rem; /* 40px */ | | ms-10 | margin-inline-start: 2.5rem; /* 40px */ | | me-10 | margin-inline-end: 2.5rem; /* 40px */ | | mt-10 | margin-top: 2.5rem; /* 40px */ | | mr-10 | margin-right: 2.5rem; /* 40px */ | | mb-10 | margin-bottom: 2.5rem; /* 40px */ | | ml-10 | margin-left: 2.5rem; /* 40px */ | | m-11 | margin: 2.75rem; /* 44px */ | | mx-11 | margin-left: 2.75rem; /* 44px */ margin-right: 2.75rem; /* 44px */ | | my-11 | margin-top: 2.75rem; /* 44px */ margin-bottom: 2.75rem; /* 44px */ | | ms-11 | margin-inline-start: 2.75rem; /* 44px */ | | me-11 | margin-inline-end: 2.75rem; /* 44px */ | | mt-11 | margin-top: 2.75rem; /* 44px */ | | mr-11 | margin-right: 2.75rem; /* 44px */ | | mb-11 | margin-bottom: 2.75rem; /* 44px */ | | ml-11 | margin-left: 2.75rem; /* 44px */ | | m-12 | margin: 3rem; /* 48px */ | | mx-12 | margin-left: 3rem; /* 48px */ margin-right: 3rem; /* 48px */ | | my-12 | margin-top: 3rem; /* 48px */ margin-bottom: 3rem; /* 48px */ | | ms-12 | margin-inline-start: 3rem; /* 48px */ | | me-12 | margin-inline-end: 3rem; /* 48px */ | | mt-12 | margin-top: 3rem; /* 48px */ | | mr-12 | margin-right: 3rem; /* 48px */ | | mb-12 | margin-bottom: 3rem; /* 48px */ | | ml-12 | margin-left: 3rem; /* 48px */ | | m-14 | margin: 3.5rem; /* 56px */ | | mx-14 | margin-left: 3.5rem; /* 56px */ margin-right: 3.5rem; /* 56px */ | | my-14 | margin-top: 3.5rem; /* 56px */ margin-bottom: 3.5rem; /* 56px */ | | ms-14 | margin-inline-start: 3.5rem; /* 56px */ | | me-14 | margin-inline-end: 3.5rem; /* 56px */ | | mt-14 | margin-top: 3.5rem; /* 56px */ | | mr-14 | margin-right: 3.5rem; /* 56px */ | | mb-14 | margin-bottom: 3.5rem; /* 56px */ | | ml-14 | margin-left: 3.5rem; /* 56px */ | | m-16 | margin: 4rem; /* 64px */ | | mx-16 | margin-left: 4rem; /* 64px */ margin-right: 4rem; /* 64px */ | | my-16 | margin-top: 4rem; /* 64px */ margin-bottom: 4rem; /* 64px */ | | ms-16 | margin-inline-start: 4rem; /* 64px */ | | me-16 | margin-inline-end: 4rem; /* 64px */ | | mt-16 | margin-top: 4rem; /* 64px */ | | mr-16 | margin-right: 4rem; /* 64px */ | | mb-16 | margin-bottom: 4rem; /* 64px */ | | ml-16 | margin-left: 4rem; /* 64px */ | | m-20 | margin: 5rem; /* 80px */ | | mx-20 | margin-left: 5rem; /* 80px */ margin-right: 5rem; /* 80px */ | | my-20 | margin-top: 5rem; /* 80px */ margin-bottom: 5rem; /* 80px */ | | ms-20 | margin-inline-start: 5rem; /* 80px */ | | me-20 | margin-inline-end: 5rem; /* 80px */ | | mt-20 | margin-top: 5rem; /* 80px */ | | mr-20 | margin-right: 5rem; /* 80px */ | | mb-20 | margin-bottom: 5rem; /* 80px */ | | ml-20 | margin-left: 5rem; /* 80px */ | | m-24 | margin: 6rem; /* 96px */ | | mx-24 | margin-left: 6rem; /* 96px */ margin-right: 6rem; /* 96px */ | | my-24 | margin-top: 6rem; /* 96px */ margin-bottom: 6rem; /* 96px */ | | ms-24 | margin-inline-start: 6rem; /* 96px */ | | me-24 | margin-inline-end: 6rem; /* 96px */ | | mt-24 | margin-top: 6rem; /* 96px */ | | mr-24 | margin-right: 6rem; /* 96px */ | | mb-24 | margin-bottom: 6rem; /* 96px */ | | ml-24 | margin-left: 6rem; /* 96px */ | | m-28 | margin: 7rem; /* 112px */ | | mx-28 | margin-left: 7rem; /* 112px */ margin-right: 7rem; /* 112px */ | | my-28 | margin-top: 7rem; /* 112px */ margin-bottom: 7rem; /* 112px */ | | ms-28 | margin-inline-start: 7rem; /* 112px */ | | me-28 | margin-inline-end: 7rem; /* 112px */ | | mt-28 | margin-top: 7rem; /* 112px */ | | mr-28 | margin-right: 7rem; /* 112px */ | | mb-28 | margin-bottom: 7rem; /* 112px */ | | ml-28 | margin-left: 7rem; /* 112px */ | | m-32 | margin: 8rem; /* 128px */ | | mx-32 | margin-left: 8rem; /* 128px */ margin-right: 8rem; /* 128px */ | | my-32 | margin-top: 8rem; /* 128px */ margin-bottom: 8rem; /* 128px */ | | ms-32 | margin-inline-start: 8rem; /* 128px */ | | me-32 | margin-inline-end: 8rem; /* 128px */ | | mt-32 | margin-top: 8rem; /* 128px */ | | mr-32 | margin-right: 8rem; /* 128px */ | | mb-32 | margin-bottom: 8rem; /* 128px */ | | ml-32 | margin-left: 8rem; /* 128px */ | | m-36 | margin: 9rem; /* 144px */ | | mx-36 | margin-left: 9rem; /* 144px */ margin-right: 9rem; /* 144px */ | | my-36 | margin-top: 9rem; /* 144px */ margin-bottom: 9rem; /* 144px */ | | ms-36 | margin-inline-start: 9rem; /* 144px */ | | me-36 | margin-inline-end: 9rem; /* 144px */ | | mt-36 | margin-top: 9rem; /* 144px */ | | mr-36 | margin-right: 9rem; /* 144px */ | | mb-36 | margin-bottom: 9rem; /* 144px */ | | ml-36 | margin-left: 9rem; /* 144px */ | | m-40 | margin: 10rem; /* 160px */ | | mx-40 | margin-left: 10rem; /* 160px */ margin-right: 10rem; /* 160px */ | | my-40 | margin-top: 10rem; /* 160px */ margin-bottom: 10rem; /* 160px */ | | ms-40 | margin-inline-start: 10rem; /* 160px */ | | me-40 | margin-inline-end: 10rem; /* 160px */ | | mt-40 | margin-top: 10rem; /* 160px */ | | mr-40 | margin-right: 10rem; /* 160px */ | | mb-40 | margin-bottom: 10rem; /* 160px */ | | ml-40 | margin-left: 10rem; /* 160px */ | | m-44 | margin: 11rem; /* 176px */ | | mx-44 | margin-left: 11rem; /* 176px */ margin-right: 11rem; /* 176px */ | | my-44 | margin-top: 11rem; /* 176px */ margin-bottom: 11rem; /* 176px */ | | ms-44 | margin-inline-start: 11rem; /* 176px */ | | me-44 | margin-inline-end: 11rem; /* 176px */ | | mt-44 | margin-top: 11rem; /* 176px */ | | mr-44 | margin-right: 11rem; /* 176px */ | | mb-44 | margin-bottom: 11rem; /* 176px */ | | ml-44 | margin-left: 11rem; /* 176px */ | | m-48 | margin: 12rem; /* 192px */ | | mx-48 | margin-left: 12rem; /* 192px */ margin-right: 12rem; /* 192px */ | | my-48 | margin-top: 12rem; /* 192px */ margin-bottom: 12rem; /* 192px */ | | ms-48 | margin-inline-start: 12rem; /* 192px */ | | me-48 | margin-inline-end: 12rem; /* 192px */ | | mt-48 | margin-top: 12rem; /* 192px */ | | mr-48 | margin-right: 12rem; /* 192px */ | | mb-48 | margin-bottom: 12rem; /* 192px */ | | ml-48 | margin-left: 12rem; /* 192px */ | | m-52 | margin: 13rem; /* 208px */ | | mx-52 | margin-left: 13rem; /* 208px */ margin-right: 13rem; /* 208px */ | | my-52 | margin-top: 13rem; /* 208px */ margin-bottom: 13rem; /* 208px */ | | ms-52 | margin-inline-start: 13rem; /* 208px */ | | me-52 | margin-inline-end: 13rem; /* 208px */ | | mt-52 | margin-top: 13rem; /* 208px */ | | mr-52 | margin-right: 13rem; /* 208px */ | | mb-52 | margin-bottom: 13rem; /* 208px */ | | ml-52 | margin-left: 13rem; /* 208px */ | | m-56 | margin: 14rem; /* 224px */ | | mx-56 | margin-left: 14rem; /* 224px */ margin-right: 14rem; /* 224px */ | | my-56 | margin-top: 14rem; /* 224px */ margin-bottom: 14rem; /* 224px */ | | ms-56 | margin-inline-start: 14rem; /* 224px */ | | me-56 | margin-inline-end: 14rem; /* 224px */ | | mt-56 | margin-top: 14rem; /* 224px */ | | mr-56 | margin-right: 14rem; /* 224px */ | | mb-56 | margin-bottom: 14rem; /* 224px */ | | ml-56 | margin-left: 14rem; /* 224px */ | | m-60 | margin: 15rem; /* 240px */ | | mx-60 | margin-left: 15rem; /* 240px */ margin-right: 15rem; /* 240px */ | | my-60 | margin-top: 15rem; /* 240px */ margin-bottom: 15rem; /* 240px */ | | ms-60 | margin-inline-start: 15rem; /* 240px */ | | me-60 | margin-inline-end: 15rem; /* 240px */ | | mt-60 | margin-top: 15rem; /* 240px */ | | mr-60 | margin-right: 15rem; /* 240px */ | | mb-60 | margin-bottom: 15rem; /* 240px */ | | ml-60 | margin-left: 15rem; /* 240px */ | | m-64 | margin: 16rem; /* 256px */ | | mx-64 | margin-left: 16rem; /* 256px */ margin-right: 16rem; /* 256px */ | | my-64 | margin-top: 16rem; /* 256px */ margin-bottom: 16rem; /* 256px */ | | ms-64 | margin-inline-start: 16rem; /* 256px */ | | me-64 | margin-inline-end: 16rem; /* 256px */ | | mt-64 | margin-top: 16rem; /* 256px */ | | mr-64 | margin-right: 16rem; /* 256px */ | | mb-64 | margin-bottom: 16rem; /* 256px */ | | ml-64 | margin-left: 16rem; /* 256px */ | | m-72 | margin: 18rem; /* 288px */ | | mx-72 | margin-left: 18rem; /* 288px */ margin-right: 18rem; /* 288px */ | | my-72 | margin-top: 18rem; /* 288px */ margin-bottom: 18rem; /* 288px */ | | ms-72 | margin-inline-start: 18rem; /* 288px */ | | me-72 | margin-inline-end: 18rem; /* 288px */ | | mt-72 | margin-top: 18rem; /* 288px */ | | mr-72 | margin-right: 18rem; /* 288px */ | | mb-72 | margin-bottom: 18rem; /* 288px */ | | ml-72 | margin-left: 18rem; /* 288px */ | | m-80 | margin: 20rem; /* 320px */ | | mx-80 | margin-left: 20rem; /* 320px */ margin-right: 20rem; /* 320px */ | | my-80 | margin-top: 20rem; /* 320px */ margin-bottom: 20rem; /* 320px */ | | ms-80 | margin-inline-start: 20rem; /* 320px */ | | me-80 | margin-inline-end: 20rem; /* 320px */ | | mt-80 | margin-top: 20rem; /* 320px */ | | mr-80 | margin-right: 20rem; /* 320px */ | | mb-80 | margin-bottom: 20rem; /* 320px */ | | ml-80 | margin-left: 20rem; /* 320px */ | | m-96 | margin: 24rem; /* 384px */ | | mx-96 | margin-left: 24rem; /* 384px */ margin-right: 24rem; /* 384px */ | | my-96 | margin-top: 24rem; /* 384px */ margin-bottom: 24rem; /* 384px */ | | ms-96 | margin-inline-start: 24rem; /* 384px */ | | me-96 | margin-inline-end: 24rem; /* 384px */ | | mt-96 | margin-top: 24rem; /* 384px */ | | mr-96 | margin-right: 24rem; /* 384px */ | | mb-96 | margin-bottom: 24rem; /* 384px */ | | ml-96 | margin-left: 24rem; /* 384px */ | | m-auto | margin: auto; | | mx-auto | margin-left: auto; margin-right: auto; | | my-auto | margin-top: auto; margin-bottom: auto; | | ms-auto | margin-inline-start: auto; | | me-auto | margin-inline-end: auto; | | mt-auto | margin-top: auto; | | mr-auto | margin-right: auto; | | mb-auto | margin-bottom: auto; | | ml-auto | margin-left: auto; | Basic usage ----------- ### Add margin to a single side Control the margin on one side of an element using the `m{t|r|b|l}-{size}` utilities. For example, `mt-6` would add `1.5rem` of margin to the top of an element, `mr-4` would add `1rem` of margin to the right of an element, `mb-8` would add `2rem` of margin to the bottom of an element, and `ml-2` would add `0.5rem` of margin to the left of an element. ``` <div class="mt-6 ...">mt-6</div> <div class="mr-4 ...">mr-4</div> <div class="mb-8 ...">mb-8</div> <div class="ml-2 ...">ml-2</div> ``` ### Add horizontal margin Control the horizontal margin of an element using the `mx-{size}` utilities. ``` <div class="mx-8 ...">mx-8</div> ``` ### Add vertical margin Control the vertical margin of an element using the `my-{size}` utilities. ``` <div class="my-8 ...">my-8</div> ``` ### Add margin to all sides Control the margin on all sides of an element using the `m-{size}` utilities. ``` <div class="m-8 ...">m-8</div> ``` ### Using negative values To use a negative margin value, prefix the class name with a dash to convert it to a negative value. ``` <div class="w-36 h-16 bg-sky-400 opacity-20 ..."></div> <div class="-mt-8 bg-sky-300 ...">-mt-8</div> ``` ### Using logical properties Use the `ms-*` and `me-*` utilities to set the `margin-inline-start` and `margin-inline-end` [logical properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties/Basic_concepts), which map to either the left or right side based on the text direction. ``` <div dir="ltr"> <div class="ms-8 ...">ms-8</div> <div class="me-8 ...">me-8</div> <div<div dir="rtl"> <div class="ms-8 ...">ms-8</div> <div class="me-8 ...">me-8</div> <div> ``` For more control, you can also use the [LTR and RTL modifiers](hover-focus-and-other-states#rtl-support) to conditionally apply specific styles depending on the current text direction. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:mt-8` to only apply the `mt-8` utility on hover. ``` <div class="mt-4 hover:mt-8"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:mt-8` to apply the `mt-8` utility at only medium screen sizes and above. ``` <div class="mt-4 md:mt-8"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind’s margin scale uses the [default spacing scale](customizing-spacing). You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '5px': '5px', } } } } ``` Alternatively, you can customize just the margin scale by editing `theme.margin` or `theme.extend.margin` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { margin: { '5px': '5px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `margin` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="m-[5px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/marginWidth ===== Utilities for setting the width of an element. Quick reference --------------- | Class | Properties | | --- | --- | | w-0 | width: 0px; | | w-px | width: 1px; | | w-0.5 | width: 0.125rem; /* 2px */ | | w-1 | width: 0.25rem; /* 4px */ | | w-1.5 | width: 0.375rem; /* 6px */ | | w-2 | width: 0.5rem; /* 8px */ | | w-2.5 | width: 0.625rem; /* 10px */ | | w-3 | width: 0.75rem; /* 12px */ | | w-3.5 | width: 0.875rem; /* 14px */ | | w-4 | width: 1rem; /* 16px */ | | w-5 | width: 1.25rem; /* 20px */ | | w-6 | width: 1.5rem; /* 24px */ | | w-7 | width: 1.75rem; /* 28px */ | | w-8 | width: 2rem; /* 32px */ | | w-9 | width: 2.25rem; /* 36px */ | | w-10 | width: 2.5rem; /* 40px */ | | w-11 | width: 2.75rem; /* 44px */ | | w-12 | width: 3rem; /* 48px */ | | w-14 | width: 3.5rem; /* 56px */ | | w-16 | width: 4rem; /* 64px */ | | w-20 | width: 5rem; /* 80px */ | | w-24 | width: 6rem; /* 96px */ | | w-28 | width: 7rem; /* 112px */ | | w-32 | width: 8rem; /* 128px */ | | w-36 | width: 9rem; /* 144px */ | | w-40 | width: 10rem; /* 160px */ | | w-44 | width: 11rem; /* 176px */ | | w-48 | width: 12rem; /* 192px */ | | w-52 | width: 13rem; /* 208px */ | | w-56 | width: 14rem; /* 224px */ | | w-60 | width: 15rem; /* 240px */ | | w-64 | width: 16rem; /* 256px */ | | w-72 | width: 18rem; /* 288px */ | | w-80 | width: 20rem; /* 320px */ | | w-96 | width: 24rem; /* 384px */ | | w-auto | width: auto; | | w-1/2 | width: 50%; | | w-1/3 | width: 33.333333%; | | w-2/3 | width: 66.666667%; | | w-1/4 | width: 25%; | | w-2/4 | width: 50%; | | w-3/4 | width: 75%; | | w-1/5 | width: 20%; | | w-2/5 | width: 40%; | | w-3/5 | width: 60%; | | w-4/5 | width: 80%; | | w-1/6 | width: 16.666667%; | | w-2/6 | width: 33.333333%; | | w-3/6 | width: 50%; | | w-4/6 | width: 66.666667%; | | w-5/6 | width: 83.333333%; | | w-1/12 | width: 8.333333%; | | w-2/12 | width: 16.666667%; | | w-3/12 | width: 25%; | | w-4/12 | width: 33.333333%; | | w-5/12 | width: 41.666667%; | | w-6/12 | width: 50%; | | w-7/12 | width: 58.333333%; | | w-8/12 | width: 66.666667%; | | w-9/12 | width: 75%; | | w-10/12 | width: 83.333333%; | | w-11/12 | width: 91.666667%; | | w-full | width: 100%; | | w-screen | width: 100vw; | | w-min | width: min-content; | | w-max | width: max-content; | | w-fit | width: fit-content; | Basic usage ----------- ### Fixed widths Use `w-{number}` or `w-px` to set an element to a fixed width. ``` <div class="w-96 ..."></div> <div class="w-80 ..."></div> <div class="w-64 ..."></div> <div class="w-48 ..."></div> <div class="w-40 ..."></div> <div class="w-32 ..."></div> <div class="w-24 ..."></div> ``` ### Percentage widths Use `w-{fraction}` or `w-full` to set an element to a percentage based width. ``` <div class="flex ..."> <div class="w-1/2 ... ">w-1/2</div> <div class="w-1/2 ... ">w-1/2</div> </div> <div class="flex ..."> <div class="w-2/5 ...">w-2/5</div> <div class="w-3/5 ...">w-3/5</div> </div> <div class="flex ..."> <div class="w-1/3 ...">w-1/3</div> <div class="w-2/3 ...">w-2/3</div> </div> <div class="flex ..."> <div class="w-1/4 ...">w-1/4</div> <div class="w-3/4 ...">w-3/4</div> </div> <div class="flex ..."> <div class="w-1/5 ...">w-1/5</div> <div class="w-4/5 ...">w-4/5</div> </div> <div class="flex ..."> <div class="w-1/6 ...">w-1/6</div> <div class="w-5/6 ...">w-5/6</div> </div> <div class="w-full ...">w-full</div> ``` ### Viewport width Use `w-screen` to make an element span the entire width of the viewport. ``` <div class="w-screen"> <!-- ... --> </div> ``` ### Resetting the width The `w-auto` utility can be useful if you need to remove an element’s assigned width under a specific condition, like at a particular breakpoint: ``` <div class="w-full md:w-auto"> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:w-full` to only apply the `w-full` utility on hover. ``` <div class="w-1/2 hover:w-full"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:w-full` to apply the `w-full` utility at only medium screen sizes and above. ``` <div class="w-1/2 md:w-full"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind’s width scale is a combination of the [default spacing scale](customizing-spacing#default-spacing-scale) as well as some additional values specific to widths. You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '128': '32rem', } } } } ``` To customize width separately, use the `theme.width` section of your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { width: { '128': '32rem', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `width` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="w-[32rem]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/widthMax-Width ========= Utilities for setting the maximum width of an element. Quick reference --------------- | Class | Properties | | --- | --- | | max-w-0 | max-width: 0rem; /* 0px */ | | max-w-none | max-width: none; | | max-w-xs | max-width: 20rem; /* 320px */ | | max-w-sm | max-width: 24rem; /* 384px */ | | max-w-md | max-width: 28rem; /* 448px */ | | max-w-lg | max-width: 32rem; /* 512px */ | | max-w-xl | max-width: 36rem; /* 576px */ | | max-w-2xl | max-width: 42rem; /* 672px */ | | max-w-3xl | max-width: 48rem; /* 768px */ | | max-w-4xl | max-width: 56rem; /* 896px */ | | max-w-5xl | max-width: 64rem; /* 1024px */ | | max-w-6xl | max-width: 72rem; /* 1152px */ | | max-w-7xl | max-width: 80rem; /* 1280px */ | | max-w-full | max-width: 100%; | | max-w-min | max-width: min-content; | | max-w-max | max-width: max-content; | | max-w-fit | max-width: fit-content; | | max-w-prose | max-width: 65ch; | | max-w-screen-sm | max-width: 640px; | | max-w-screen-md | max-width: 768px; | | max-w-screen-lg | max-width: 1024px; | | max-w-screen-xl | max-width: 1280px; | | max-w-screen-2xl | max-width: 1536px; | Basic usage ----------- ### Setting the maximum width Set the maximum width of an element using the `max-w-{size}` utilities. ``` <div class="max-w-md ..."> <!-- ... --> </div> ``` ### Reading width The `max-w-prose` utility gives an element a max-width optimized for readability and adapts based on the font size. ``` <div class="text-sm max-w-prose ..."> <p>Oh yeah. It's the best part. It's crunchy, it's explosive, it's where the muffin breaks free of the pan and sort of does it's own thing. I'll tell you. That's a million dollar idea right there. Just sell the tops.</p> </div<div class="text-base max-w-prose ..."> <p>Oh yeah. It's the best part. It's crunchy, it's explosive, it's where the muffin breaks free of the pan and sort of does it's own thing. I'll tell you. That's a million dollar idea right there. Just sell the tops.</p> </div<div class="text-xl max-w-prose ..."> <p>Oh yeah. It's the best part. It's crunchy, it's explosive, it's where the muffin breaks free of the pan and sort of does it's own thing. I'll tell you. That's a million dollar idea right there. Just sell the tops.</p> </div> ``` ### Constraining to your breakpoints The `max-w-screen-{breakpoint}` classes can be used to give an element a max-width matching a specific breakpoint. These values are automatically derived from the [`theme.screens` section](theme#screens) of your `tailwind.config.js` file. ``` <div class="max-w-screen-2xl"> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:max-w-lg` to only apply the `max-w-lg` utility on hover. ``` <div class="max-w-sm hover:max-w-lg"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:max-w-lg` to apply the `max-w-lg` utility at only medium screen sizes and above. ``` <div class="max-w-sm md:max-w-lg"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme You can customize your `max-width` scale by editing `theme.maxWidth` or `theme.extend.maxWidth` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { maxWidth: { '1/2': '50%', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `max-width` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="max-w-[50%]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/max-widthHeight ====== Utilities for setting the height of an element. Quick reference --------------- | Class | Properties | | --- | --- | | h-0 | height: 0px; | | h-px | height: 1px; | | h-0.5 | height: 0.125rem; /* 2px */ | | h-1 | height: 0.25rem; /* 4px */ | | h-1.5 | height: 0.375rem; /* 6px */ | | h-2 | height: 0.5rem; /* 8px */ | | h-2.5 | height: 0.625rem; /* 10px */ | | h-3 | height: 0.75rem; /* 12px */ | | h-3.5 | height: 0.875rem; /* 14px */ | | h-4 | height: 1rem; /* 16px */ | | h-5 | height: 1.25rem; /* 20px */ | | h-6 | height: 1.5rem; /* 24px */ | | h-7 | height: 1.75rem; /* 28px */ | | h-8 | height: 2rem; /* 32px */ | | h-9 | height: 2.25rem; /* 36px */ | | h-10 | height: 2.5rem; /* 40px */ | | h-11 | height: 2.75rem; /* 44px */ | | h-12 | height: 3rem; /* 48px */ | | h-14 | height: 3.5rem; /* 56px */ | | h-16 | height: 4rem; /* 64px */ | | h-20 | height: 5rem; /* 80px */ | | h-24 | height: 6rem; /* 96px */ | | h-28 | height: 7rem; /* 112px */ | | h-32 | height: 8rem; /* 128px */ | | h-36 | height: 9rem; /* 144px */ | | h-40 | height: 10rem; /* 160px */ | | h-44 | height: 11rem; /* 176px */ | | h-48 | height: 12rem; /* 192px */ | | h-52 | height: 13rem; /* 208px */ | | h-56 | height: 14rem; /* 224px */ | | h-60 | height: 15rem; /* 240px */ | | h-64 | height: 16rem; /* 256px */ | | h-72 | height: 18rem; /* 288px */ | | h-80 | height: 20rem; /* 320px */ | | h-96 | height: 24rem; /* 384px */ | | h-auto | height: auto; | | h-1/2 | height: 50%; | | h-1/3 | height: 33.333333%; | | h-2/3 | height: 66.666667%; | | h-1/4 | height: 25%; | | h-2/4 | height: 50%; | | h-3/4 | height: 75%; | | h-1/5 | height: 20%; | | h-2/5 | height: 40%; | | h-3/5 | height: 60%; | | h-4/5 | height: 80%; | | h-1/6 | height: 16.666667%; | | h-2/6 | height: 33.333333%; | | h-3/6 | height: 50%; | | h-4/6 | height: 66.666667%; | | h-5/6 | height: 83.333333%; | | h-full | height: 100%; | | h-screen | height: 100vh; | | h-min | height: min-content; | | h-max | height: max-content; | | h-fit | height: fit-content; | Basic usage ----------- ### Fixed heights Use `h-{number}` or `h-px` to set an element to a fixed height. ``` <div class="h-96 ...">h-96</div> <div class="h-80 ...">h-80</div> <div class="h-64 ...">h-64</div> <div class="h-48 ...">h-48</div> <div class="h-40 ...">h-40</div> <div class="h-32 ...">h-32</div> <div class="h-24 ...">h-24</div> ``` ### Full height Use `h-full` to set an element’s height to 100% of its parent, as long as the parent has a defined height. ``` <div class="h-48"> <div class="h-full ..."> <!-- This element will have a height of `12rem` (h-48) --> </div> </div> ``` ### Viewport height Use `h-screen` to make an element span the entire height of the viewport. ``` <div class="h-screen"> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:h-full` to only apply the `h-full` utility on hover. ``` <div class="h-8 hover:h-full"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:h-full` to apply the `h-full` utility at only medium screen sizes and above. ``` <div class="h-8 md:h-full"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind’s height scale is a combination of the [default spacing scale](customizing-spacing#default-spacing-scale) as well as some additional values specific to heights. You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '128': '32rem', } } } } ``` To customize height separately, use the `theme.height` section of your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { height: { '128': '32rem', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `height` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="h-[32rem]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/heightMin-Height ========== Utilities for setting the minimum height of an element. Quick reference --------------- | Class | Properties | | --- | --- | | min-h-0 | min-height: 0px; | | min-h-full | min-height: 100%; | | min-h-screen | min-height: 100vh; | | min-h-min | min-height: min-content; | | min-h-max | min-height: max-content; | | min-h-fit | min-height: fit-content; | Basic usage ----------- ### Setting the minimum height Set the minimum height of an element using the `min-h-0`, `min-h-full`, or `min-h-screen` utilities. ``` <div class="h-48"> <div class="h-24 min-h-full"> <!-- ... --> </div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:min-h-full` to only apply the `min-h-full` utility on hover. ``` <div class="h-24 min-h-0 hover:min-h-full"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:min-h-full` to apply the `min-h-full` utility at only medium screen sizes and above. ``` <div class="h-24 min-h-0 md:min-h-full"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme You can customize your `min-height` scale by editing `theme.minHeight` or `theme.extend.minHeight` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { minHeight: { '1/2': '50%', } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `min-height` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="min-h-[50%]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/min-heightMax-Height ========== Utilities for setting the maximum height of an element. Quick reference --------------- | Class | Properties | | --- | --- | | max-h-0 | max-height: 0px; | | max-h-px | max-height: 1px; | | max-h-0.5 | max-height: 0.125rem; /* 2px */ | | max-h-1 | max-height: 0.25rem; /* 4px */ | | max-h-1.5 | max-height: 0.375rem; /* 6px */ | | max-h-2 | max-height: 0.5rem; /* 8px */ | | max-h-2.5 | max-height: 0.625rem; /* 10px */ | | max-h-3 | max-height: 0.75rem; /* 12px */ | | max-h-3.5 | max-height: 0.875rem; /* 14px */ | | max-h-4 | max-height: 1rem; /* 16px */ | | max-h-5 | max-height: 1.25rem; /* 20px */ | | max-h-6 | max-height: 1.5rem; /* 24px */ | | max-h-7 | max-height: 1.75rem; /* 28px */ | | max-h-8 | max-height: 2rem; /* 32px */ | | max-h-9 | max-height: 2.25rem; /* 36px */ | | max-h-10 | max-height: 2.5rem; /* 40px */ | | max-h-11 | max-height: 2.75rem; /* 44px */ | | max-h-12 | max-height: 3rem; /* 48px */ | | max-h-14 | max-height: 3.5rem; /* 56px */ | | max-h-16 | max-height: 4rem; /* 64px */ | | max-h-20 | max-height: 5rem; /* 80px */ | | max-h-24 | max-height: 6rem; /* 96px */ | | max-h-28 | max-height: 7rem; /* 112px */ | | max-h-32 | max-height: 8rem; /* 128px */ | | max-h-36 | max-height: 9rem; /* 144px */ | | max-h-40 | max-height: 10rem; /* 160px */ | | max-h-44 | max-height: 11rem; /* 176px */ | | max-h-48 | max-height: 12rem; /* 192px */ | | max-h-52 | max-height: 13rem; /* 208px */ | | max-h-56 | max-height: 14rem; /* 224px */ | | max-h-60 | max-height: 15rem; /* 240px */ | | max-h-64 | max-height: 16rem; /* 256px */ | | max-h-72 | max-height: 18rem; /* 288px */ | | max-h-80 | max-height: 20rem; /* 320px */ | | max-h-96 | max-height: 24rem; /* 384px */ | | max-h-none | max-height: none; | | max-h-full | max-height: 100%; | | max-h-screen | max-height: 100vh; | | max-h-min | max-height: min-content; | | max-h-max | max-height: max-content; | | max-h-fit | max-height: fit-content; | Basic usage ----------- ### Setting the maximum height Set the maximum height of an element using the `max-h-full` or `max-h-screen` utilities. ``` <div class="h-24 ..."> <div class="h-48 max-h-full ..."> <!-- ... --> </div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:max-h-screen` to only apply the `max-h-screen` utility on hover. ``` <div class="h-48 max-h-full hover:max-h-screen"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:max-h-screen` to apply the `max-h-screen` utility at only medium screen sizes and above. ``` <div class="h-48 max-h-full md:max-h-screen"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind’s max-height scale uses a combination of the [default spacing scale](customizing-spacing) as well as some additional height related values. You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '128': '32rem', } } } } ``` Alternatively, you can customize just the max-height scale by editing `theme.maxHeight` or `theme.extend.maxHeight` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { maxHeight: { '128': '32rem', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `max-height` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="max-h-[32rem]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/max-heightFont Family =========== Utilities for controlling the font family of an element. Quick reference --------------- | Class | Properties | | --- | --- | | font-sans | font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; | | font-serif | font-family: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif; | | font-mono | font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; | Basic usage ----------- ### Setting the font family You can control the typeface of text using the font family utilities. ``` <p class="font-sans ...">The quick brown fox ...</p> <p class="font-serif ...">The quick brown fox ...</p> <p class="font-mono ...">The quick brown fox ...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:font-serif` to only apply the `font-serif` utility on hover. ``` <p class="font-sans hover:font-serif"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:font-serif` to apply the `font-serif` utility at only medium screen sizes and above. ``` <p class="font-sans md:font-serif"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides three font family utilities: a cross-browser sans-serif stack, a cross-browser serif stack, and a cross-browser monospaced stack. You can change, add, or remove these by editing the `theme.fontFamily` section of your Tailwind config. tailwind.config.js ``` module.exports = { theme: { fontFamily: { 'sans': ['ui-sans-serif', 'system-ui', ...], 'serif': ['ui-serif', 'Georgia', ...], 'mono': ['ui-monospace', 'SFMono-Regular', ...], 'display': ['Oswald', ...], 'body': ['"Open Sans"', ...], } } } ``` Font families can be specified as an array or as a simple comma-delimited string: ``` { // Array format: 'sans': ['Helvetica', 'Arial', 'sans-serif'], // Comma-delimited format: 'sans': 'Helvetica, Arial, sans-serif', } ``` Note that **Tailwind does not automatically escape font names** for you. If you’re using a font that contains an invalid identifier, wrap it in quotes or escape the invalid characters. ``` { // Won't work: 'sans': ['Exo 2', ...], // Add quotes: 'sans': ['"Exo 2"', ...], // ...or escape the space: 'sans': ['Exo\\ 2', ...], } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. #### Providing default font settings You can optionally provide default [font-feature-settings](https://developer.mozilla.org/en-US/docs/Web/CSS/font-feature-settings) and [font-variation-settings](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variation-settings) for each font in your project using a tuple of the form `[fontFamilies, { fontFeatureSettings, fontVariationSettings }]` when configuring custom fonts. tailwind.config.js ``` module.exports = { theme: { fontFamily: { sans: [ "Inter var, sans-serif", { fontFeatureSettings: '"cv11", "ss01"', fontVariationSettings: '"opsz" 32' }, ], }, }, } ``` ### Arbitrary values If you need to use a one-off `font-family` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <p class="font-['Open_Sans']"> <!-- ... --> </p``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. ### Customizing the default font For convenience, [Preflight](preflight) sets the font family on the `html` element to match your configured `sans` font, so one way to change the default font for your project is to customize the `sans` key in your `fontFamily` configuration: tailwind.config.js ``` const defaultTheme = require('tailwindcss/defaultTheme') module.exports = { theme: { extend: { fontFamily: { 'sans': ['Proxima Nova', ...defaultTheme.fontFamily.sans], }, } } } ``` You can also customize the default font used in your project by [adding a custom base style](adding-custom-styles#adding-base-styles) that sets the `font-family` property explicitly: main.css ``` @tailwind base; @tailwind components; @tailwind utilities; @layer base { html { font-family: Proxima Nova, system-ui, sans-serif; } } ``` This is the best approach if you have customized your font family utilities to have different names and don’t want there to be `font-sans` utility available in your project. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/font-familyFont Size ========= Utilities for controlling the font size of an element. Quick reference --------------- | Class | Properties | | --- | --- | | text-xs | font-size: 0.75rem; /* 12px */ line-height: 1rem; /* 16px */ | | text-sm | font-size: 0.875rem; /* 14px */ line-height: 1.25rem; /* 20px */ | | text-base | font-size: 1rem; /* 16px */ line-height: 1.5rem; /* 24px */ | | text-lg | font-size: 1.125rem; /* 18px */ line-height: 1.75rem; /* 28px */ | | text-xl | font-size: 1.25rem; /* 20px */ line-height: 1.75rem; /* 28px */ | | text-2xl | font-size: 1.5rem; /* 24px */ line-height: 2rem; /* 32px */ | | text-3xl | font-size: 1.875rem; /* 30px */ line-height: 2.25rem; /* 36px */ | | text-4xl | font-size: 2.25rem; /* 36px */ line-height: 2.5rem; /* 40px */ | | text-5xl | font-size: 3rem; /* 48px */ line-height: 1; | | text-6xl | font-size: 3.75rem; /* 60px */ line-height: 1; | | text-7xl | font-size: 4.5rem; /* 72px */ line-height: 1; | | text-8xl | font-size: 6rem; /* 96px */ line-height: 1; | | text-9xl | font-size: 8rem; /* 128px */ line-height: 1; | Basic usage ----------- ### Setting the font size Control the font size of an element using the `text-{size}` utilities. ``` <p class="text-sm ...">The quick brown fox ...</p> <p class="text-base ...">The quick brown fox ...</p> <p class="text-lg ...">The quick brown fox ...</p> <p class="text-xl ...">The quick brown fox ...</p> <p class="text-2xl ...">The quick brown fox ...</p> ``` ### Setting the line-height Set an element’s line-height at the same time you set the font size by adding a line-height modifier to any font size utility. For example, use `text-xl/8` to set a font size of `1.25rem` with a line-height of `2rem`. ``` <p class="text-base/6 ...">So I started to walk into the water...</p> <p class="text-base/7 ...">So I started to walk into the water...</p> <p class="text-base/loose ...">So I started to walk into the water...</p> ``` You can use any value defined in your [line-height scale](line-height), or use arbitrary values if you need to deviate from your design tokens. ``` <p class="text-sm/[17px] ..."></p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:text-base` to only apply the `text-base` utility on hover. ``` <p class="text-sm hover:text-base"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:text-base` to apply the `text-base` utility at only medium screen sizes and above. ``` <p class="text-sm md:text-base"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme You can configure your own custom set of font size utilities using the `theme.fontSize` section of your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { fontSize: { sm: '0.8rem', base: '1rem', xl: '1.25rem', '2xl': '1.563rem', '3xl': '1.953rem', '4xl': '2.441rem', '5xl': '3.052rem', } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. #### Providing a default line-height Tailwind’s default theme configures a sensible default `line-height` for each `text-{size}` utility. You can configure your own default line heights when using custom font sizes by defining each size using a tuple of the form `[fontSize, lineHeight]` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { fontSize: { sm: ['14px', '20px'], base: ['16px', '24px'], lg: ['20px', '28px'], xl: ['24px', '32px'], } } } ``` You can also specify a default line height using the object syntax, which allows you to also provide default `letter-spacing` and `font-weight` values. You can do this using a tuple of the form `[fontSize, { lineHeight?, letterSpacing?, fontWeight? }]`. tailwind.config.js ``` module.exports = { theme: { fontSize: { '2xl': ['1.5rem', { lineHeight: '2rem', letterSpacing: '-0.01em', fontWeight: '500', }], '3xl': ['1.875rem', { lineHeight: '2.25rem', letterSpacing: '-0.02em', fontWeight: '700', }], } } } ``` ### Arbitrary values If you need to use a one-off `font-size` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <p class="text-[14px]"> <!-- ... --> </p``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/font-sizeFont Smoothing ============== Utilities for controlling the font smoothing of an element. Quick reference --------------- | Class | Properties | | --- | --- | | antialiased | -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; | | subpixel-antialiased | -webkit-font-smoothing: auto; -moz-osx-font-smoothing: auto; | Basic usage ----------- ### Applying font smoothing Use the `subpixel-antialiased` utility to render text using subpixel antialiasing and the `antialiased` utility to render text using grayscale antialiasing. ``` <p class="subpixel-antialiased ...">The quick brown fox ...</p> <p class="antialiased ...">The quick brown fox ...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:subpixel-antialiased` to only apply the `subpixel-antialiased` utility on hover. ``` <p class="antialiased hover:subpixel-antialiased"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:subpixel-antialiased` to apply the `subpixel-antialiased` utility at only medium screen sizes and above. ``` <p class="antialiased md:subpixel-antialiased"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/font-smoothingFont Style ========== Utilities for controlling the style of text. Quick reference --------------- | Class | Properties | | --- | --- | | italic | font-style: italic; | | not-italic | font-style: normal; | Basic usage ----------- ### Italicizing text The `italic` utility can be used to make text italic. Likewise, the `not-italic` utility can be used to display text normally — typically to reset italic text at different breakpoints. ``` <p class="italic ...">The quick brown fox ...</p> <p class="not-italic ...">The quick brown fox ...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:not-italic` to only apply the `not-italic` utility on hover. ``` <p class="italic hover:not-italic"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:not-italic` to apply the `not-italic` utility at only medium screen sizes and above. ``` <p class="italic md:not-italic"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/font-styleFont Weight =========== Utilities for controlling the font weight of an element. Quick reference --------------- | Class | Properties | | --- | --- | | font-thin | font-weight: 100; | | font-extralight | font-weight: 200; | | font-light | font-weight: 300; | | font-normal | font-weight: 400; | | font-medium | font-weight: 500; | | font-semibold | font-weight: 600; | | font-bold | font-weight: 700; | | font-extrabold | font-weight: 800; | | font-black | font-weight: 900; | Basic usage ----------- ### Setting the font weight Control the font weight of an element using the `font-{weight}` utilities. ``` <p class="font-light ...">The quick brown fox ...</p> <p class="font-normal ...">The quick brown fox ...</p> <p class="font-medium ...">The quick brown fox ...</p> <p class="font-semibold ...">The quick brown fox ...</p> <p class="font-bold ...">The quick brown fox ...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:font-bold` to only apply the `font-bold` utility on hover. ``` <p class="font-normal hover:font-bold"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:font-bold` to apply the `font-bold` utility at only medium screen sizes and above. ``` <p class="font-normal md:font-bold"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides nine `font-weight` utilities. You change, add, or remove these by editing the `theme.fontWeight` section of your Tailwind config. tailwind.config.js ``` module.exports = { theme: { fontWeight: { thin: '100', hairline: '100', extralight: '200', light: '300', normal: '400', medium: '500', semibold: '600', bold: '700', extrabold: '800', 'extra-bold': '800', black: '900', } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `font-weight` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <p class="font-[1100]"> <!-- ... --> </p``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/font-weightFont Variant Numeric ==================== Utilities for controlling the variant of numbers. Quick reference --------------- | Class | Properties | | --- | --- | | normal-nums | font-variant-numeric: normal; | | ordinal | font-variant-numeric: ordinal; | | slashed-zero | font-variant-numeric: slashed-zero; | | lining-nums | font-variant-numeric: lining-nums; | | oldstyle-nums | font-variant-numeric: oldstyle-nums; | | proportional-nums | font-variant-numeric: proportional-nums; | | tabular-nums | font-variant-numeric: tabular-nums; | | diagonal-fractions | font-variant-numeric: diagonal-fractions; | | stacked-fractions | font-variant-numeric: stacked-fractions; | Basic usage ----------- ### Applying numeric variants Use the `font-variant-numeric` utilities to enable additional glyphs for numbers, fractions, and ordinal markers *(in fonts that support them)*. These utilities are composable so you can enable multiple `font-variant-numeric` features by combining multiple classes in your HTML: ``` <p class="ordinal slashed-zero tabular-nums ..."> 1234567890 </p> ``` Note that many fonts don’t support these features *(stacked fractions support for example is especially rare)*, so some of these utilities may have no effect depending on the font family you are using. ### Ordinal Use the `ordinal` utility to enable special glyphs for the ordinal markers. ``` <p class="ordinal ...">1st</p> ``` ### Slashed Zero Use the `slashed-zero` utility to force a 0 with a slash; this is useful when a clear distinction between O and 0 is needed. ``` <p class="slashed-zero ...">0</p> ``` ### Lining figures Use the `lining-nums` utility to use the numeric glyphs that are all aligned by their baseline. This corresponds to the `lnum` OpenType feature. This is the default for most fonts. ``` <p class="lining-nums ..."> 1234567890 </p> ``` ### Oldstyle figures Use the `oldstyle-nums` utility to use numeric glyphs where some numbers have descenders. This corresponds to the `onum` OpenType feature. ``` <p class="oldstyle-nums ..."> 1234567890 </p> ``` ### Proportional figures Use the `proportional-nums` utility to use numeric glyphs that have proportional widths (rather than uniform/tabular). This corresponds to the `pnum` OpenType feature. ``` <p class="proportional-nums ..."> 12121 </p> <p class="proportional-nums ..."> 90909 </p> ``` ### Tabular figures Use the `tabular-nums` utility to use numeric glyphs that have uniform/tabular widths (rather than proportional). This corresponds to the `tnum` OpenType feature. ``` <p class="tabular-nums ..."> 12121 </p> <p class="tabular-nums ..."> 90909 </p> ``` ### Diagonal fractions Use the `diagonal-fractions` utility to replace numbers separated by a slash with common diagonal fractions. This corresponds to the `frac` OpenType feature. ``` <p class="diagonal-fractions ..."> 1/2 3/4 5/6 </p> ``` ### Stacked fractions Use the `stacked-fractions` utility to replace numbers separated by a slash with common stacked fractions. This corresponds to the `afrc` OpenType feature. Very few fonts seem to support this feature — we’ve used Ubuntu Mono here. ``` <p class="stacked-fractions ..."> 1/2 3/4 5/6 </p> ``` ### Resetting numeric font variants Use the `normal-nums` propery to reset numeric font variants. This is usually useful for resetting a font feature at a particular breakpoint: ``` <p class="slashed-zero tabular-nums md:normal-nums ..."> 12345 </p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:tabular-nums` to only apply the `tabular-nums` utility on hover. ``` <p class="proportional-nums hover:tabular-nums"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:tabular-nums` to apply the `tabular-nums` utility at only medium screen sizes and above. ``` <p class="proportional-nums md:tabular-nums"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/font-variant-numericLetter Spacing ============== Utilities for controlling the tracking (letter spacing) of an element. Quick reference --------------- | Class | Properties | | --- | --- | | tracking-tighter | letter-spacing: -0.05em; | | tracking-tight | letter-spacing: -0.025em; | | tracking-normal | letter-spacing: 0em; | | tracking-wide | letter-spacing: 0.025em; | | tracking-wider | letter-spacing: 0.05em; | | tracking-widest | letter-spacing: 0.1em; | Basic usage ----------- ### Setting the letter spacing Control the letter spacing of an element using the `tracking-{size}` utilities. ``` <p class="tracking-tight ...">The quick brown fox ...</p> <p class="tracking-normal ...">The quick brown fox ...</p> <p class="tracking-wide ...">The quick brown fox ...</p> ``` ### Using negative values To use a negative letter-spacing value, prefix the class name with a dash to convert it to a negative value. Using negative values doesn’t make a ton of sense with the letter-spacing scale Tailwind includes out of the box, but if you’ve opted to customize your letter-spacing scale to use numbers instead of descriptive words like “wide” the negative value modifier can be useful. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:tracking-wide` to only apply the `tracking-wide` utility on hover. ``` <p class="tracking-tight hover:tracking-wide"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:tracking-wide` to apply the `tracking-wide` utility at only medium screen sizes and above. ``` <p class="tracking-tight md:tracking-wide"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides six tracking utilities. You can change, add, or remove these by editing the `theme.letterSpacing` section of your Tailwind config. tailwind.config.js ``` module.exports = { theme: { letterSpacing: { tightest: '-.075em', tighter: '-.05em', tight: '-.025em', normal: '0', wide: '.025em', wider: '.05em', widest: '.1em', widest: '.25em', } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `letter-spacing` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <p class="tracking-[.25em]"> <!-- ... --> </p``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/letter-spacingLine Clamp ========== Utilities for clamping text to a specific number of lines. Quick reference --------------- | Class | Properties | | --- | --- | | line-clamp-1 | overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 1; | | line-clamp-2 | overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; | | line-clamp-3 | overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; | | line-clamp-4 | overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; | | line-clamp-5 | overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 5; | | line-clamp-6 | overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 6; | | line-clamp-none | overflow: visible; display: block; -webkit-box-orient: horizontal; -webkit-line-clamp: none; | Basic usage ----------- ### Truncating multi-line text Use the `line-clamp-*` utilities to truncate a block of text after a specific number of lines. ``` <article> <time>Mar 10, 2020</time> <h2>Boost your conversion rate</h2> <p class="line-clamp-3">Nulla dolor velit adipisicing duis excepteur esse in duis nostrud occaecat mollit incididunt deserunt sunt. Ut ut sunt laborum ex occaecat eu tempor labore enim adipisicing minim ad. Est in quis eu dolore occaecat excepteur fugiat dolore nisi aliqua fugiat enim ut cillum. Labore enim duis nostrud eu. Est ut eiusmod consequat irure quis deserunt ex. Enim laboris dolor magna pariatur. Dolor et ad sint voluptate sunt elit mollit officia ad enim sit consectetur enim.</p> <div> <img src="..." /> <NAME> </div> </article> ``` ### Undoing line clamping Use `line-clamp-none` to undo a previously applied line clamp utility. ``` <p class="line-clamp-3 lg:line-clamp-none"> <!-- ... --> </p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:line-clamp-4` to only apply the `line-clamp-4` utility on hover. ``` <p class="line-clamp-3 hover:line-clamp-4"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:line-clamp-4` to apply the `line-clamp-4` utility at only medium screen sizes and above. ``` <p class="line-clamp-3 md:line-clamp-4"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides the six `line-clamp` utilities. You can customize these values by editing `theme.lineClamp` or `theme.extend.lineClamp` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { lineClamp: { 7: '7', }, } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `line-clamp` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <p class="line-clamp-[7]"> <!-- ... --> </p``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/line-clampLine Height =========== Utilities for controlling the leading (line height) of an element. Quick reference --------------- | Class | Properties | | --- | --- | | leading-3 | line-height: .75rem; /* 12px */ | | leading-4 | line-height: 1rem; /* 16px */ | | leading-5 | line-height: 1.25rem; /* 20px */ | | leading-6 | line-height: 1.5rem; /* 24px */ | | leading-7 | line-height: 1.75rem; /* 28px */ | | leading-8 | line-height: 2rem; /* 32px */ | | leading-9 | line-height: 2.25rem; /* 36px */ | | leading-10 | line-height: 2.5rem; /* 40px */ | | leading-none | line-height: 1; | | leading-tight | line-height: 1.25; | | leading-snug | line-height: 1.375; | | leading-normal | line-height: 1.5; | | leading-relaxed | line-height: 1.625; | | leading-loose | line-height: 2; | Basic usage ----------- ### Relative line-heights Use the `leading-none`, `leading-tight`, `leading-snug`, `leading-normal`, `leading-relaxed`, and `leading-loose` utilities to give an element a relative line-height based on its current font-size. ``` <p class="leading-normal ...">So I started to walk into the water...</p> <p class="leading-relaxed ...">So I started to walk into the water...</p> <p class="leading-loose ...">So I started to walk into the water...</p> ``` ### Fixed line-heights Use the `leading-{size}` utilities to give an element a fixed line-height, irrespective of the current font-size. These are useful when you need very precise control over an element’s final size. ``` <p class="leading-6 ...">So I started to walk into the water...</p> <p class="leading-7 ...">So I started to walk into the water...</p> <p class="leading-8 ...">So I started to walk into the water...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:leading-loose` to only apply the `leading-loose` utility on hover. ``` <p class="leading-none hover:leading-loose"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:leading-loose` to apply the `leading-loose` utility at only medium screen sizes and above. ``` <p class="leading-none md:leading-loose"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). ### Overriding default line-heights It’s important to note that by default, Tailwind’s <font-size> utilities each set their own default line-height. This means that any time you use a responsive font-size utility like `sm:text-xl`, any explicit line-height you have set for a smaller breakpoint will be overridden. ``` <!-- The `leading-loose` class will be overridden at the `md` breakpoint --> <p class="text-lg leading-loose md:text-xl"> Maybe we can live without libraries... </p> ``` If you want to override the default line-height after setting a breakpoint-specific font-size, make sure to set a breakpoint-specific line-height as well: ``` <!-- The `leading-loose` class will be overridden at the `md` breakpoint --> <p class="text-lg leading-loose md:text-xl md:leading-loose"> Maybe we can live without libraries... </p> ``` Using the same line-height across different font sizes is generally not going to give you good typographic results. Line-height should typically get smaller as font-size increases, so the default behavior here usually saves you a ton of work. If you find yourself fighting it, you can always [customize your font-size scale](font-size#customizing) to not include default line-heights. Using custom values ------------------- ### Customizing your theme By default, Tailwind provides six relative and eight fixed `line-height` utilities. You change, add, or remove these by customizing the `lineHeight` section of your Tailwind theme config. tailwind.config.js ``` module.exports = { theme: { extend: { lineHeight: { 'extra-loose': '2.5', '12': '3rem', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `line-height` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <p class="leading-[3rem]"> <!-- ... --> </p``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/line-heightList Style Image ================ Utilities for controlling the marker images for list items. Quick reference --------------- | Class | Properties | | --- | --- | | list-image-none | list-style-image: none; | Basic usage ----------- ### Setting the list style image Control the marker image for list items using the `list-image-{value}` utilities. Out of the box, `list-image-none` is the only available preconfigured list style image utility. And while you can add additional utilities by [customizing your theme](list-style-image#customizing-your-theme), you can also use the square bracket notation to generate an arbitrary value on the fly. ``` <ul class="list-image-[url(checkmark.png)] ..."> <li>5 cups chopped Porcini mushrooms</li> <!-- ... --> </ul> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:list-image-[url(checkmark.png)]` to only apply the `list-image-[url(checkmark.png)]` utility on hover. ``` <ul class="list-image-none hover:list-image-[url(checkmark.png)]"> <!-- ... --> </ul``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:list-image-[url(checkmark.png)]` to apply the `list-image-[url(checkmark.png)]` utility at only medium screen sizes and above. ``` <ul class="list-image-none md:list-image-[url(checkmark.png)]"> <!-- ... --> </ul``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind only provides the `list-image-none` utility. You can customize these values by editing `theme.listStyleImage` or `theme.extend.listStyleImage` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { listStyleImage: { checkmark: 'url("/img/checkmark.png")', }, } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `list-image` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <ul class="list-image-[url(checkmark.png)]"> <!-- ... --> </ul``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/list-style-imageList Style Position =================== Utilities for controlling the position of bullets/numbers in lists. Quick reference --------------- | Class | Properties | | --- | --- | | list-inside | list-style-position: inside; | | list-outside | list-style-position: outside; | Basic usage ----------- ### Setting the list style position Control the position of the markers and text indentation in a list using the `list-inside` and `list-outside` utilities. ``` <ul class="list-inside ..."> <li>5 cups chopped Porcini mushrooms</li> <!-- ... --> </ul<ul class="list-outside ..."> <li>5 cups chopped Porcini mushrooms</li> <!-- ... --> </ul> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:list-inside` to only apply the `list-inside` utility on hover. ``` <ul class="list-outside hover:list-inside"> <!-- ... --> </ul``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:list-inside` to apply the `list-inside` utility at only medium screen sizes and above. ``` <ul class="list-outside md:list-inside"> <!-- ... --> </ul``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/list-style-positionList Style Type =============== Utilities for controlling the bullet/number style of a list. Quick reference --------------- | Class | Properties | | --- | --- | | list-none | list-style-type: none; | | list-disc | list-style-type: disc; | | list-decimal | list-style-type: decimal; | Basic usage ----------- ### Setting the list style type To create bulleted or numeric lists, use the `list-disc` and `list-decimal` utilities. ``` <ul class="list-disc"> <li>Now this is a story all about how, my life got flipped-turned upside down</li> <!-- ... --> </ul<ol class="list-decimal"> <li>Now this is a story all about how, my life got flipped-turned upside down</li> <!-- ... --> </ol<ul class="list-none"> <li>Now this is a story all about how, my life got flipped-turned upside down</li> <!-- ... --> </ul> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:list-disc` to only apply the `list-disc` utility on hover. ``` <ul class="list-none hover:list-disc"> <!-- ... --> </ul``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:list-disc` to apply the `list-disc` utility at only medium screen sizes and above. ``` <ul class="list-none md:list-disc"> <!-- ... --> </ul``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides three utilities for the most common list style types. You change, add, or remove these by editing the `theme.listStyleType` section of your Tailwind config. tailwind.config.js ``` module.exports = { theme: { listStyleType: { none: 'none', disc: 'disc', decimal: 'decimal', square: 'square', roman: 'upper-roman', } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `list-style-type` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <ul class="list-[upper-roman]"> <!-- ... --> </ul``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/list-style-typeText Align ========== Utilities for controlling the alignment of text. Quick reference --------------- | Class | Properties | | --- | --- | | text-left | text-align: left; | | text-center | text-align: center; | | text-right | text-align: right; | | text-justify | text-align: justify; | | text-start | text-align: start; | | text-end | text-align: end; | Basic usage ----------- ### Setting the text alignment Control the text alignment of an element using the `text-left`, `text-center`, `text-right`, and `text-justify` utilities. ``` <p class="text-left ...">So I started to walk into the water...</p> ``` ``` <p class="text-center ...">So I started to walk into the water...</p> ``` ``` <p class="text-right ...">So I started to walk into the water...</p> ``` ``` <p class="text-justify ...">So I started to walk into the water...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:text-center` to only apply the `text-center` utility on hover. ``` <p class="text-left hover:text-center"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:text-center` to apply the `text-center` utility at only medium screen sizes and above. ``` <p class="text-left md:text-center"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/text-alignText Color ========== Utilities for controlling the text color of an element. Quick reference --------------- | Class | Properties | Preview | | --- | --- | --- | | text-inherit | color: inherit; | Aa | | text-current | color: currentColor; | Aa | | text-transparent | color: transparent; | Aa | | text-black | color: rgb(0 0 0); | Aa | | text-white | color: rgb(255 255 255); | Aa | | text-slate-50 | color: rgb(248 250 252); | Aa | | text-slate-100 | color: rgb(241 245 249); | Aa | | text-slate-200 | color: rgb(226 232 240); | Aa | | text-slate-300 | color: rgb(203 213 225); | Aa | | text-slate-400 | color: rgb(148 163 184); | Aa | | text-slate-500 | color: rgb(100 116 139); | Aa | | text-slate-600 | color: rgb(71 85 105); | Aa | | text-slate-700 | color: rgb(51 65 85); | Aa | | text-slate-800 | color: rgb(30 41 59); | Aa | | text-slate-900 | color: rgb(15 23 42); | Aa | | text-slate-950 | color: rgb(2 6 23); | Aa | | text-gray-50 | color: rgb(249 250 251); | Aa | | text-gray-100 | color: rgb(243 244 246); | Aa | | text-gray-200 | color: rgb(229 231 235); | Aa | | text-gray-300 | color: rgb(209 213 219); | Aa | | text-gray-400 | color: rgb(156 163 175); | Aa | | text-gray-500 | color: rgb(107 114 128); | Aa | | text-gray-600 | color: rgb(75 85 99); | Aa | | text-gray-700 | color: rgb(55 65 81); | Aa | | text-gray-800 | color: rgb(31 41 55); | Aa | | text-gray-900 | color: rgb(17 24 39); | Aa | | text-gray-950 | color: rgb(3 7 18); | Aa | | text-zinc-50 | color: rgb(250 250 250); | Aa | | text-zinc-100 | color: rgb(244 244 245); | Aa | | text-zinc-200 | color: rgb(228 228 231); | Aa | | text-zinc-300 | color: rgb(212 212 216); | Aa | | text-zinc-400 | color: rgb(161 161 170); | Aa | | text-zinc-500 | color: rgb(113 113 122); | Aa | | text-zinc-600 | color: rgb(82 82 91); | Aa | | text-zinc-700 | color: rgb(63 63 70); | Aa | | text-zinc-800 | color: rgb(39 39 42); | Aa | | text-zinc-900 | color: rgb(24 24 27); | Aa | | text-zinc-950 | color: rgb(9 9 11); | Aa | | text-neutral-50 | color: rgb(250 250 250); | Aa | | text-neutral-100 | color: rgb(245 245 245); | Aa | | text-neutral-200 | color: rgb(229 229 229); | Aa | | text-neutral-300 | color: rgb(212 212 212); | Aa | | text-neutral-400 | color: rgb(163 163 163); | Aa | | text-neutral-500 | color: rgb(115 115 115); | Aa | | text-neutral-600 | color: rgb(82 82 82); | Aa | | text-neutral-700 | color: rgb(64 64 64); | Aa | | text-neutral-800 | color: rgb(38 38 38); | Aa | | text-neutral-900 | color: rgb(23 23 23); | Aa | | text-neutral-950 | color: rgb(10 10 10); | Aa | | text-stone-50 | color: rgb(250 250 249); | Aa | | text-stone-100 | color: rgb(245 245 244); | Aa | | text-stone-200 | color: rgb(231 229 228); | Aa | | text-stone-300 | color: rgb(214 211 209); | Aa | | text-stone-400 | color: rgb(168 162 158); | Aa | | text-stone-500 | color: rgb(120 113 108); | Aa | | text-stone-600 | color: rgb(87 83 78); | Aa | | text-stone-700 | color: rgb(68 64 60); | Aa | | text-stone-800 | color: rgb(41 37 36); | Aa | | text-stone-900 | color: rgb(28 25 23); | Aa | | text-stone-950 | color: rgb(12 10 9); | Aa | | text-red-50 | color: rgb(254 242 242); | Aa | | text-red-100 | color: rgb(254 226 226); | Aa | | text-red-200 | color: rgb(254 202 202); | Aa | | text-red-300 | color: rgb(252 165 165); | Aa | | text-red-400 | color: rgb(248 113 113); | Aa | | text-red-500 | color: rgb(239 68 68); | Aa | | text-red-600 | color: rgb(220 38 38); | Aa | | text-red-700 | color: rgb(185 28 28); | Aa | | text-red-800 | color: rgb(153 27 27); | Aa | | text-red-900 | color: rgb(127 29 29); | Aa | | text-red-950 | color: rgb(69 10 10); | Aa | | text-orange-50 | color: rgb(255 247 237); | Aa | | text-orange-100 | color: rgb(255 237 213); | Aa | | text-orange-200 | color: rgb(254 215 170); | Aa | | text-orange-300 | color: rgb(253 186 116); | Aa | | text-orange-400 | color: rgb(251 146 60); | Aa | | text-orange-500 | color: rgb(249 115 22); | Aa | | text-orange-600 | color: rgb(234 88 12); | Aa | | text-orange-700 | color: rgb(194 65 12); | Aa | | text-orange-800 | color: rgb(154 52 18); | Aa | | text-orange-900 | color: rgb(124 45 18); | Aa | | text-orange-950 | color: rgb(67 20 7); | Aa | | text-amber-50 | color: rgb(255 251 235); | Aa | | text-amber-100 | color: rgb(254 243 199); | Aa | | text-amber-200 | color: rgb(253 230 138); | Aa | | text-amber-300 | color: rgb(252 211 77); | Aa | | text-amber-400 | color: rgb(251 191 36); | Aa | | text-amber-500 | color: rgb(245 158 11); | Aa | | text-amber-600 | color: rgb(217 119 6); | Aa | | text-amber-700 | color: rgb(180 83 9); | Aa | | text-amber-800 | color: rgb(146 64 14); | Aa | | text-amber-900 | color: rgb(120 53 15); | Aa | | text-amber-950 | color: rgb(69 26 3); | Aa | | text-yellow-50 | color: rgb(254 252 232); | Aa | | text-yellow-100 | color: rgb(254 249 195); | Aa | | text-yellow-200 | color: rgb(254 240 138); | Aa | | text-yellow-300 | color: rgb(253 224 71); | Aa | | text-yellow-400 | color: rgb(250 204 21); | Aa | | text-yellow-500 | color: rgb(234 179 8); | Aa | | text-yellow-600 | color: rgb(202 138 4); | Aa | | text-yellow-700 | color: rgb(161 98 7); | Aa | | text-yellow-800 | color: rgb(133 77 14); | Aa | | text-yellow-900 | color: rgb(113 63 18); | Aa | | text-yellow-950 | color: rgb(66 32 6); | Aa | | text-lime-50 | color: rgb(247 254 231); | Aa | | text-lime-100 | color: rgb(236 252 203); | Aa | | text-lime-200 | color: rgb(217 249 157); | Aa | | text-lime-300 | color: rgb(190 242 100); | Aa | | text-lime-400 | color: rgb(163 230 53); | Aa | | text-lime-500 | color: rgb(132 204 22); | Aa | | text-lime-600 | color: rgb(101 163 13); | Aa | | text-lime-700 | color: rgb(77 124 15); | Aa | | text-lime-800 | color: rgb(63 98 18); | Aa | | text-lime-900 | color: rgb(54 83 20); | Aa | | text-lime-950 | color: rgb(26 46 5); | Aa | | text-green-50 | color: rgb(240 253 244); | Aa | | text-green-100 | color: rgb(220 252 231); | Aa | | text-green-200 | color: rgb(187 247 208); | Aa | | text-green-300 | color: rgb(134 239 172); | Aa | | text-green-400 | color: rgb(74 222 128); | Aa | | text-green-500 | color: rgb(34 197 94); | Aa | | text-green-600 | color: rgb(22 163 74); | Aa | | text-green-700 | color: rgb(21 128 61); | Aa | | text-green-800 | color: rgb(22 101 52); | Aa | | text-green-900 | color: rgb(20 83 45); | Aa | | text-green-950 | color: rgb(5 46 22); | Aa | | text-emerald-50 | color: rgb(236 253 245); | Aa | | text-emerald-100 | color: rgb(209 250 229); | Aa | | text-emerald-200 | color: rgb(167 243 208); | Aa | | text-emerald-300 | color: rgb(110 231 183); | Aa | | text-emerald-400 | color: rgb(52 211 153); | Aa | | text-emerald-500 | color: rgb(16 185 129); | Aa | | text-emerald-600 | color: rgb(5 150 105); | Aa | | text-emerald-700 | color: rgb(4 120 87); | Aa | | text-emerald-800 | color: rgb(6 95 70); | Aa | | text-emerald-900 | color: rgb(6 78 59); | Aa | | text-emerald-950 | color: rgb(2 44 34); | Aa | | text-teal-50 | color: rgb(240 253 250); | Aa | | text-teal-100 | color: rgb(204 251 241); | Aa | | text-teal-200 | color: rgb(153 246 228); | Aa | | text-teal-300 | color: rgb(94 234 212); | Aa | | text-teal-400 | color: rgb(45 212 191); | Aa | | text-teal-500 | color: rgb(20 184 166); | Aa | | text-teal-600 | color: rgb(13 148 136); | Aa | | text-teal-700 | color: rgb(15 118 110); | Aa | | text-teal-800 | color: rgb(17 94 89); | Aa | | text-teal-900 | color: rgb(19 78 74); | Aa | | text-teal-950 | color: rgb(4 47 46); | Aa | | text-cyan-50 | color: rgb(236 254 255); | Aa | | text-cyan-100 | color: rgb(207 250 254); | Aa | | text-cyan-200 | color: rgb(165 243 252); | Aa | | text-cyan-300 | color: rgb(103 232 249); | Aa | | text-cyan-400 | color: rgb(34 211 238); | Aa | | text-cyan-500 | color: rgb(6 182 212); | Aa | | text-cyan-600 | color: rgb(8 145 178); | Aa | | text-cyan-700 | color: rgb(14 116 144); | Aa | | text-cyan-800 | color: rgb(21 94 117); | Aa | | text-cyan-900 | color: rgb(22 78 99); | Aa | | text-cyan-950 | color: rgb(8 51 68); | Aa | | text-sky-50 | color: rgb(240 249 255); | Aa | | text-sky-100 | color: rgb(224 242 254); | Aa | | text-sky-200 | color: rgb(186 230 253); | Aa | | text-sky-300 | color: rgb(125 211 252); | Aa | | text-sky-400 | color: rgb(56 189 248); | Aa | | text-sky-500 | color: rgb(14 165 233); | Aa | | text-sky-600 | color: rgb(2 132 199); | Aa | | text-sky-700 | color: rgb(3 105 161); | Aa | | text-sky-800 | color: rgb(7 89 133); | Aa | | text-sky-900 | color: rgb(12 74 110); | Aa | | text-sky-950 | color: rgb(8 47 73); | Aa | | text-blue-50 | color: rgb(239 246 255); | Aa | | text-blue-100 | color: rgb(219 234 254); | Aa | | text-blue-200 | color: rgb(191 219 254); | Aa | | text-blue-300 | color: rgb(147 197 253); | Aa | | text-blue-400 | color: rgb(96 165 250); | Aa | | text-blue-500 | color: rgb(59 130 246); | Aa | | text-blue-600 | color: rgb(37 99 235); | Aa | | text-blue-700 | color: rgb(29 78 216); | Aa | | text-blue-800 | color: rgb(30 64 175); | Aa | | text-blue-900 | color: rgb(30 58 138); | Aa | | text-blue-950 | color: rgb(23 37 84); | Aa | | text-indigo-50 | color: rgb(238 242 255); | Aa | | text-indigo-100 | color: rgb(224 231 255); | Aa | | text-indigo-200 | color: rgb(199 210 254); | Aa | | text-indigo-300 | color: rgb(165 180 252); | Aa | | text-indigo-400 | color: rgb(129 140 248); | Aa | | text-indigo-500 | color: rgb(99 102 241); | Aa | | text-indigo-600 | color: rgb(79 70 229); | Aa | | text-indigo-700 | color: rgb(67 56 202); | Aa | | text-indigo-800 | color: rgb(55 48 163); | Aa | | text-indigo-900 | color: rgb(49 46 129); | Aa | | text-indigo-950 | color: rgb(30 27 75); | Aa | | text-violet-50 | color: rgb(245 243 255); | Aa | | text-violet-100 | color: rgb(237 233 254); | Aa | | text-violet-200 | color: rgb(221 214 254); | Aa | | text-violet-300 | color: rgb(196 181 253); | Aa | | text-violet-400 | color: rgb(167 139 250); | Aa | | text-violet-500 | color: rgb(139 92 246); | Aa | | text-violet-600 | color: rgb(124 58 237); | Aa | | text-violet-700 | color: rgb(109 40 217); | Aa | | text-violet-800 | color: rgb(91 33 182); | Aa | | text-violet-900 | color: rgb(76 29 149); | Aa | | text-violet-950 | color: rgb(46 16 101); | Aa | | text-purple-50 | color: rgb(250 245 255); | Aa | | text-purple-100 | color: rgb(243 232 255); | Aa | | text-purple-200 | color: rgb(233 213 255); | Aa | | text-purple-300 | color: rgb(216 180 254); | Aa | | text-purple-400 | color: rgb(192 132 252); | Aa | | text-purple-500 | color: rgb(168 85 247); | Aa | | text-purple-600 | color: rgb(147 51 234); | Aa | | text-purple-700 | color: rgb(126 34 206); | Aa | | text-purple-800 | color: rgb(107 33 168); | Aa | | text-purple-900 | color: rgb(88 28 135); | Aa | | text-purple-950 | color: rgb(59 7 100); | Aa | | text-fuchsia-50 | color: rgb(253 244 255); | Aa | | text-fuchsia-100 | color: rgb(250 232 255); | Aa | | text-fuchsia-200 | color: rgb(245 208 254); | Aa | | text-fuchsia-300 | color: rgb(240 171 252); | Aa | | text-fuchsia-400 | color: rgb(232 121 249); | Aa | | text-fuchsia-500 | color: rgb(217 70 239); | Aa | | text-fuchsia-600 | color: rgb(192 38 211); | Aa | | text-fuchsia-700 | color: rgb(162 28 175); | Aa | | text-fuchsia-800 | color: rgb(134 25 143); | Aa | | text-fuchsia-900 | color: rgb(112 26 117); | Aa | | text-fuchsia-950 | color: rgb(74 4 78); | Aa | | text-pink-50 | color: rgb(253 242 248); | Aa | | text-pink-100 | color: rgb(252 231 243); | Aa | | text-pink-200 | color: rgb(251 207 232); | Aa | | text-pink-300 | color: rgb(249 168 212); | Aa | | text-pink-400 | color: rgb(244 114 182); | Aa | | text-pink-500 | color: rgb(236 72 153); | Aa | | text-pink-600 | color: rgb(219 39 119); | Aa | | text-pink-700 | color: rgb(190 24 93); | Aa | | text-pink-800 | color: rgb(157 23 77); | Aa | | text-pink-900 | color: rgb(131 24 67); | Aa | | text-pink-950 | color: rgb(80 7 36); | Aa | | text-rose-50 | color: rgb(255 241 242); | Aa | | text-rose-100 | color: rgb(255 228 230); | Aa | | text-rose-200 | color: rgb(254 205 211); | Aa | | text-rose-300 | color: rgb(253 164 175); | Aa | | text-rose-400 | color: rgb(251 113 133); | Aa | | text-rose-500 | color: rgb(244 63 94); | Aa | | text-rose-600 | color: rgb(225 29 72); | Aa | | text-rose-700 | color: rgb(190 18 60); | Aa | | text-rose-800 | color: rgb(159 18 57); | Aa | | text-rose-900 | color: rgb(136 19 55); | Aa | | text-rose-950 | color: rgb(76 5 25); | Aa | Basic usage ----------- ### Setting the text color Control the text color of an element using the `text-{color}` utilities. ``` <p class="text-blue-600">The quick brown fox...</p><p class="text-sky-400">The quick brown fox...</p> ``` ### Changing the opacity Control the opacity of an element’s text color using the color opacity modifier. ``` <p class="text-blue-600/100">The quick brown fox...</p> <p class="text-blue-600/75">The quick brown fox...</p> <p class="text-blue-600/50">The quick brown fox...</p> <p class="text-blue-600/25">The quick brown fox...</p> <p class="text-blue-600/0">The quick brown fox...</p><p class="text-sky-400/100">The quick brown fox...</p> <p class="text-sky-400/75">The quick brown fox...</p> <p class="text-sky-400/50">The quick brown fox...</p> <p class="text-sky-400/25">The quick brown fox...</p> <p class="text-sky-400/0">The quick brown fox...</p> ``` You can use any value defined in your [opacity scale](opacity), or use arbitrary values if you need to deviate from your design tokens. ``` <p class="text-blue-600/[.06]">The quick brown fox...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:text-blue-600` to only apply the `text-blue-600` utility on hover. ``` <p class="text-slate-500 hover:text-blue-600">The quick brown fox...</p><p class="text-slate-400 hover:text-sky-400">The quick brown fox...</p> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:text-green-600` to apply the `text-green-600` utility at only medium screen sizes and above. ``` <p class="text-blue-600 md:text-green-600"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as text colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your text colors by editing `theme.textColor` or `theme.extend.textColor` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `color` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <p class="text-[#50d71e]"> <!-- ... --> </p``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/text-colorText Decoration =============== Utilities for controlling the decoration of text. Quick reference --------------- | Class | Properties | | --- | --- | | underline | text-decoration-line: underline; | | overline | text-decoration-line: overline; | | line-through | text-decoration-line: line-through; | | no-underline | text-decoration-line: none; | Basic usage ----------- ### Setting the text decoration Control how text is decorated with the `underline`, `no-underline`, and `line-through` utilities. ``` <p class="underline ...">The quick brown fox ...</p> <p class="overline ...">The quick brown fox ...</p> <p class="line-through ...">The quick brown fox ...</p> <p class="no-underline ...">The quick brown fox ...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:text-center` to only apply the `text-center` utility on hover. ``` <a href="#" class="no-underline hover:underline ...">Link</a> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:underline` to apply the `underline` utility at only medium screen sizes and above. ``` <p class="no-underline md:underline"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/text-decorationText Decoration Color ===================== Utilities for controlling the color of text decorations. Quick reference --------------- | Class | Properties | | --- | --- | | decoration-inherit | text-decoration-color: inherit; | | decoration-current | text-decoration-color: currentColor; | | decoration-transparent | text-decoration-color: transparent; | | decoration-black | text-decoration-color: #000; | | decoration-white | text-decoration-color: #fff; | | decoration-slate-50 | text-decoration-color: #f8fafc; | | decoration-slate-100 | text-decoration-color: #f1f5f9; | | decoration-slate-200 | text-decoration-color: #e2e8f0; | | decoration-slate-300 | text-decoration-color: #cbd5e1; | | decoration-slate-400 | text-decoration-color: #94a3b8; | | decoration-slate-500 | text-decoration-color: #64748b; | | decoration-slate-600 | text-decoration-color: #475569; | | decoration-slate-700 | text-decoration-color: #334155; | | decoration-slate-800 | text-decoration-color: #1e293b; | | decoration-slate-900 | text-decoration-color: #0f172a; | | decoration-slate-950 | text-decoration-color: #020617; | | decoration-gray-50 | text-decoration-color: #f9fafb; | | decoration-gray-100 | text-decoration-color: #f3f4f6; | | decoration-gray-200 | text-decoration-color: #e5e7eb; | | decoration-gray-300 | text-decoration-color: #d1d5db; | | decoration-gray-400 | text-decoration-color: #9ca3af; | | decoration-gray-500 | text-decoration-color: #6b7280; | | decoration-gray-600 | text-decoration-color: #4b5563; | | decoration-gray-700 | text-decoration-color: #374151; | | decoration-gray-800 | text-decoration-color: #1f2937; | | decoration-gray-900 | text-decoration-color: #111827; | | decoration-gray-950 | text-decoration-color: #030712; | | decoration-zinc-50 | text-decoration-color: #fafafa; | | decoration-zinc-100 | text-decoration-color: #f4f4f5; | | decoration-zinc-200 | text-decoration-color: #e4e4e7; | | decoration-zinc-300 | text-decoration-color: #d4d4d8; | | decoration-zinc-400 | text-decoration-color: #a1a1aa; | | decoration-zinc-500 | text-decoration-color: #71717a; | | decoration-zinc-600 | text-decoration-color: #52525b; | | decoration-zinc-700 | text-decoration-color: #3f3f46; | | decoration-zinc-800 | text-decoration-color: #27272a; | | decoration-zinc-900 | text-decoration-color: #18181b; | | decoration-zinc-950 | text-decoration-color: #09090b; | | decoration-neutral-50 | text-decoration-color: #fafafa; | | decoration-neutral-100 | text-decoration-color: #f5f5f5; | | decoration-neutral-200 | text-decoration-color: #e5e5e5; | | decoration-neutral-300 | text-decoration-color: #d4d4d4; | | decoration-neutral-400 | text-decoration-color: #a3a3a3; | | decoration-neutral-500 | text-decoration-color: #737373; | | decoration-neutral-600 | text-decoration-color: #525252; | | decoration-neutral-700 | text-decoration-color: #404040; | | decoration-neutral-800 | text-decoration-color: #262626; | | decoration-neutral-900 | text-decoration-color: #171717; | | decoration-neutral-950 | text-decoration-color: #0a0a0a; | | decoration-stone-50 | text-decoration-color: #fafaf9; | | decoration-stone-100 | text-decoration-color: #f5f5f4; | | decoration-stone-200 | text-decoration-color: #e7e5e4; | | decoration-stone-300 | text-decoration-color: #d6d3d1; | | decoration-stone-400 | text-decoration-color: #a8a29e; | | decoration-stone-500 | text-decoration-color: #78716c; | | decoration-stone-600 | text-decoration-color: #57534e; | | decoration-stone-700 | text-decoration-color: #44403c; | | decoration-stone-800 | text-decoration-color: #292524; | | decoration-stone-900 | text-decoration-color: #1c1917; | | decoration-stone-950 | text-decoration-color: #0c0a09; | | decoration-red-50 | text-decoration-color: #fef2f2; | | decoration-red-100 | text-decoration-color: #fee2e2; | | decoration-red-200 | text-decoration-color: #fecaca; | | decoration-red-300 | text-decoration-color: #fca5a5; | | decoration-red-400 | text-decoration-color: #f87171; | | decoration-red-500 | text-decoration-color: #ef4444; | | decoration-red-600 | text-decoration-color: #dc2626; | | decoration-red-700 | text-decoration-color: #b91c1c; | | decoration-red-800 | text-decoration-color: #991b1b; | | decoration-red-900 | text-decoration-color: #7f1d1d; | | decoration-red-950 | text-decoration-color: #450a0a; | | decoration-orange-50 | text-decoration-color: #fff7ed; | | decoration-orange-100 | text-decoration-color: #ffedd5; | | decoration-orange-200 | text-decoration-color: #fed7aa; | | decoration-orange-300 | text-decoration-color: #fdba74; | | decoration-orange-400 | text-decoration-color: #fb923c; | | decoration-orange-500 | text-decoration-color: #f97316; | | decoration-orange-600 | text-decoration-color: #ea580c; | | decoration-orange-700 | text-decoration-color: #c2410c; | | decoration-orange-800 | text-decoration-color: #9a3412; | | decoration-orange-900 | text-decoration-color: #7c2d12; | | decoration-orange-950 | text-decoration-color: #431407; | | decoration-amber-50 | text-decoration-color: #fffbeb; | | decoration-amber-100 | text-decoration-color: #fef3c7; | | decoration-amber-200 | text-decoration-color: #fde68a; | | decoration-amber-300 | text-decoration-color: #fcd34d; | | decoration-amber-400 | text-decoration-color: #fbbf24; | | decoration-amber-500 | text-decoration-color: #f59e0b; | | decoration-amber-600 | text-decoration-color: #d97706; | | decoration-amber-700 | text-decoration-color: #b45309; | | decoration-amber-800 | text-decoration-color: #92400e; | | decoration-amber-900 | text-decoration-color: #78350f; | | decoration-amber-950 | text-decoration-color: #451a03; | | decoration-yellow-50 | text-decoration-color: #fefce8; | | decoration-yellow-100 | text-decoration-color: #fef9c3; | | decoration-yellow-200 | text-decoration-color: #fef08a; | | decoration-yellow-300 | text-decoration-color: #fde047; | | decoration-yellow-400 | text-decoration-color: #facc15; | | decoration-yellow-500 | text-decoration-color: #eab308; | | decoration-yellow-600 | text-decoration-color: #ca8a04; | | decoration-yellow-700 | text-decoration-color: #a16207; | | decoration-yellow-800 | text-decoration-color: #854d0e; | | decoration-yellow-900 | text-decoration-color: #713f12; | | decoration-yellow-950 | text-decoration-color: #422006; | | decoration-lime-50 | text-decoration-color: #f7fee7; | | decoration-lime-100 | text-decoration-color: #ecfccb; | | decoration-lime-200 | text-decoration-color: #d9f99d; | | decoration-lime-300 | text-decoration-color: #bef264; | | decoration-lime-400 | text-decoration-color: #a3e635; | | decoration-lime-500 | text-decoration-color: #84cc16; | | decoration-lime-600 | text-decoration-color: #65a30d; | | decoration-lime-700 | text-decoration-color: #4d7c0f; | | decoration-lime-800 | text-decoration-color: #3f6212; | | decoration-lime-900 | text-decoration-color: #365314; | | decoration-lime-950 | text-decoration-color: #1a2e05; | | decoration-green-50 | text-decoration-color: #f0fdf4; | | decoration-green-100 | text-decoration-color: #dcfce7; | | decoration-green-200 | text-decoration-color: #bbf7d0; | | decoration-green-300 | text-decoration-color: #86efac; | | decoration-green-400 | text-decoration-color: #4ade80; | | decoration-green-500 | text-decoration-color: #22c55e; | | decoration-green-600 | text-decoration-color: #16a34a; | | decoration-green-700 | text-decoration-color: #15803d; | | decoration-green-800 | text-decoration-color: #166534; | | decoration-green-900 | text-decoration-color: #14532d; | | decoration-green-950 | text-decoration-color: #052e16; | | decoration-emerald-50 | text-decoration-color: #ecfdf5; | | decoration-emerald-100 | text-decoration-color: #d1fae5; | | decoration-emerald-200 | text-decoration-color: #a7f3d0; | | decoration-emerald-300 | text-decoration-color: #6ee7b7; | | decoration-emerald-400 | text-decoration-color: #34d399; | | decoration-emerald-500 | text-decoration-color: #10b981; | | decoration-emerald-600 | text-decoration-color: #059669; | | decoration-emerald-700 | text-decoration-color: #047857; | | decoration-emerald-800 | text-decoration-color: #065f46; | | decoration-emerald-900 | text-decoration-color: #064e3b; | | decoration-emerald-950 | text-decoration-color: #022c22; | | decoration-teal-50 | text-decoration-color: #f0fdfa; | | decoration-teal-100 | text-decoration-color: #ccfbf1; | | decoration-teal-200 | text-decoration-color: #99f6e4; | | decoration-teal-300 | text-decoration-color: #5eead4; | | decoration-teal-400 | text-decoration-color: #2dd4bf; | | decoration-teal-500 | text-decoration-color: #14b8a6; | | decoration-teal-600 | text-decoration-color: #0d9488; | | decoration-teal-700 | text-decoration-color: #0f766e; | | decoration-teal-800 | text-decoration-color: #115e59; | | decoration-teal-900 | text-decoration-color: #134e4a; | | decoration-teal-950 | text-decoration-color: #042f2e; | | decoration-cyan-50 | text-decoration-color: #ecfeff; | | decoration-cyan-100 | text-decoration-color: #cffafe; | | decoration-cyan-200 | text-decoration-color: #a5f3fc; | | decoration-cyan-300 | text-decoration-color: #67e8f9; | | decoration-cyan-400 | text-decoration-color: #22d3ee; | | decoration-cyan-500 | text-decoration-color: #06b6d4; | | decoration-cyan-600 | text-decoration-color: #0891b2; | | decoration-cyan-700 | text-decoration-color: #0e7490; | | decoration-cyan-800 | text-decoration-color: #155e75; | | decoration-cyan-900 | text-decoration-color: #164e63; | | decoration-cyan-950 | text-decoration-color: #083344; | | decoration-sky-50 | text-decoration-color: #f0f9ff; | | decoration-sky-100 | text-decoration-color: #e0f2fe; | | decoration-sky-200 | text-decoration-color: #bae6fd; | | decoration-sky-300 | text-decoration-color: #7dd3fc; | | decoration-sky-400 | text-decoration-color: #38bdf8; | | decoration-sky-500 | text-decoration-color: #0ea5e9; | | decoration-sky-600 | text-decoration-color: #0284c7; | | decoration-sky-700 | text-decoration-color: #0369a1; | | decoration-sky-800 | text-decoration-color: #075985; | | decoration-sky-900 | text-decoration-color: #0c4a6e; | | decoration-sky-950 | text-decoration-color: #082f49; | | decoration-blue-50 | text-decoration-color: #eff6ff; | | decoration-blue-100 | text-decoration-color: #dbeafe; | | decoration-blue-200 | text-decoration-color: #bfdbfe; | | decoration-blue-300 | text-decoration-color: #93c5fd; | | decoration-blue-400 | text-decoration-color: #60a5fa; | | decoration-blue-500 | text-decoration-color: #3b82f6; | | decoration-blue-600 | text-decoration-color: #2563eb; | | decoration-blue-700 | text-decoration-color: #1d4ed8; | | decoration-blue-800 | text-decoration-color: #1e40af; | | decoration-blue-900 | text-decoration-color: #1e3a8a; | | decoration-blue-950 | text-decoration-color: #172554; | | decoration-indigo-50 | text-decoration-color: #eef2ff; | | decoration-indigo-100 | text-decoration-color: #e0e7ff; | | decoration-indigo-200 | text-decoration-color: #c7d2fe; | | decoration-indigo-300 | text-decoration-color: #a5b4fc; | | decoration-indigo-400 | text-decoration-color: #818cf8; | | decoration-indigo-500 | text-decoration-color: #6366f1; | | decoration-indigo-600 | text-decoration-color: #4f46e5; | | decoration-indigo-700 | text-decoration-color: #4338ca; | | decoration-indigo-800 | text-decoration-color: #3730a3; | | decoration-indigo-900 | text-decoration-color: #312e81; | | decoration-indigo-950 | text-decoration-color: #1e1b4b; | | decoration-violet-50 | text-decoration-color: #f5f3ff; | | decoration-violet-100 | text-decoration-color: #ede9fe; | | decoration-violet-200 | text-decoration-color: #ddd6fe; | | decoration-violet-300 | text-decoration-color: #c4b5fd; | | decoration-violet-400 | text-decoration-color: #a78bfa; | | decoration-violet-500 | text-decoration-color: #8b5cf6; | | decoration-violet-600 | text-decoration-color: #7c3aed; | | decoration-violet-700 | text-decoration-color: #6d28d9; | | decoration-violet-800 | text-decoration-color: #5b21b6; | | decoration-violet-900 | text-decoration-color: #4c1d95; | | decoration-violet-950 | text-decoration-color: #2e1065; | | decoration-purple-50 | text-decoration-color: #faf5ff; | | decoration-purple-100 | text-decoration-color: #f3e8ff; | | decoration-purple-200 | text-decoration-color: #e9d5ff; | | decoration-purple-300 | text-decoration-color: #d8b4fe; | | decoration-purple-400 | text-decoration-color: #c084fc; | | decoration-purple-500 | text-decoration-color: #a855f7; | | decoration-purple-600 | text-decoration-color: #9333ea; | | decoration-purple-700 | text-decoration-color: #7e22ce; | | decoration-purple-800 | text-decoration-color: #6b21a8; | | decoration-purple-900 | text-decoration-color: #581c87; | | decoration-purple-950 | text-decoration-color: #3b0764; | | decoration-fuchsia-50 | text-decoration-color: #fdf4ff; | | decoration-fuchsia-100 | text-decoration-color: #fae8ff; | | decoration-fuchsia-200 | text-decoration-color: #f5d0fe; | | decoration-fuchsia-300 | text-decoration-color: #f0abfc; | | decoration-fuchsia-400 | text-decoration-color: #e879f9; | | decoration-fuchsia-500 | text-decoration-color: #d946ef; | | decoration-fuchsia-600 | text-decoration-color: #c026d3; | | decoration-fuchsia-700 | text-decoration-color: #a21caf; | | decoration-fuchsia-800 | text-decoration-color: #86198f; | | decoration-fuchsia-900 | text-decoration-color: #701a75; | | decoration-fuchsia-950 | text-decoration-color: #4a044e; | | decoration-pink-50 | text-decoration-color: #fdf2f8; | | decoration-pink-100 | text-decoration-color: #fce7f3; | | decoration-pink-200 | text-decoration-color: #fbcfe8; | | decoration-pink-300 | text-decoration-color: #f9a8d4; | | decoration-pink-400 | text-decoration-color: #f472b6; | | decoration-pink-500 | text-decoration-color: #ec4899; | | decoration-pink-600 | text-decoration-color: #db2777; | | decoration-pink-700 | text-decoration-color: #be185d; | | decoration-pink-800 | text-decoration-color: #9d174d; | | decoration-pink-900 | text-decoration-color: #831843; | | decoration-pink-950 | text-decoration-color: #500724; | | decoration-rose-50 | text-decoration-color: #fff1f2; | | decoration-rose-100 | text-decoration-color: #ffe4e6; | | decoration-rose-200 | text-decoration-color: #fecdd3; | | decoration-rose-300 | text-decoration-color: #fda4af; | | decoration-rose-400 | text-decoration-color: #fb7185; | | decoration-rose-500 | text-decoration-color: #f43f5e; | | decoration-rose-600 | text-decoration-color: #e11d48; | | decoration-rose-700 | text-decoration-color: #be123c; | | decoration-rose-800 | text-decoration-color: #9f1239; | | decoration-rose-900 | text-decoration-color: #881337; | | decoration-rose-950 | text-decoration-color: #4c0519; | Basic usage ----------- ### Setting the text decoration color Use the `decoration-{color}` utilities to change the color of an element’s [text decoration](text-decoration). ``` <div> <p> I’m Derek, an astro-engineer based in Tattooine. I like to build X-Wings at <a class="underline decoration-sky-500">My Company, Inc</a>. Outside of work, I like to <a class="underline decoration-pink-500">watch pod-racing</a> and have <a class="underline decoration-indigo-500">light-saber</a> fights. </p> </div> ``` ### Changing the opacity Control the opacity of an element’s text decoration color using the color opacity modifier. ``` <div> <p> I’m Derek, an astro-engineer based in Tattooine. I like to build X-Wings at <a class="underline decoration-sky-500/30">My Company, Inc</a>. Outside of work, I like to <a class="underline decoration-pink-500/30">watch pod-racing</a> and have <a class="underline decoration-indigo-500/30">light-saber</a> fights. </p> </div> ``` You can use any value defined in your [opacity scale](opacity), or use arbitrary values if you need to deviate from your design tokens. ``` <strong class="underline decoration-sky-500/[.33]"></strong> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:decoration-blue-400` to only apply the `decoration-blue-400` utility on hover. ``` <p class="underline decoration-sky-600 hover:decoration-blue-400"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:decoration-blue-400` to apply the `decoration-blue-400` utility at only medium screen sizes and above. ``` <p class="underline decoration-sky-600 md:decoration-blue-400"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as text decoration colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your text decoration colors by editing `theme.textDecorationColor` or `theme.extend.textDecorationColor` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `text-decoration-color` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <p class="decoration-[#50d71e]"> <!-- ... --> </p``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/text-decoration-colorText Decoration Style ===================== Utilities for controlling the style of text decorations. Quick reference --------------- | Class | Properties | | --- | --- | | decoration-solid | text-decoration-style: solid; | | decoration-double | text-decoration-style: double; | | decoration-dotted | text-decoration-style: dotted; | | decoration-dashed | text-decoration-style: dashed; | | decoration-wavy | text-decoration-style: wavy; | Basic usage ----------- ### Setting the text decoration style Use the `decoration-{style}` utilities to change the style of an element’s [text decoration](text-decoration). ``` <p class="underline decoration-solid ...">The quick brown fox...</p> <p class="underline decoration-double ...">The quick brown fox...</p> <p class="underline decoration-dotted ...">The quick brown fox...</p> <p class="underline decoration-dashed ...">The quick brown fox...</p> <p class="underline decoration-wavy ...">The quick brown fox...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:decoration-dashed` to only apply the `decoration-dashed` utility on hover. ``` <p class="underline hover:decoration-dashed"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:decoration-dashed` to apply the `decoration-dashed` utility at only medium screen sizes and above. ``` <p class="underline md:decoration-dashed"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/text-decoration-styleText Decoration Thickness ========================= Utilities for controlling the thickness of text decorations. Quick reference --------------- | Class | Properties | | --- | --- | | decoration-auto | text-decoration-thickness: auto; | | decoration-from-font | text-decoration-thickness: from-font; | | decoration-0 | text-decoration-thickness: 0px; | | decoration-1 | text-decoration-thickness: 1px; | | decoration-2 | text-decoration-thickness: 2px; | | decoration-4 | text-decoration-thickness: 4px; | | decoration-8 | text-decoration-thickness: 8px; | Basic usage ----------- ### Setting the text decoration thickness Use the `decoration-{width}` utilities to change the thickness of an element’s [text decoration](text-decoration). ``` <p class="underline decoration-1 ...">The quick brown fox...</p> <p class="underline decoration-2 ...">The quick brown fox...</p> <p class="underline decoration-4 ...">The quick brown fox...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:decoration-4` to only apply the `decoration-4` utility on hover. ``` <p class="underline hover:decoration-4"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:decoration-4` to apply the `decoration-4` utility at only medium screen sizes and above. ``` <p class="underline md:decoration-4"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme You can customize the `decoration-{width}` utilities by editing `theme.textDecorationThickness` or `theme.extend.textDecorationThickness` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { textDecorationThickness: { 3: '3px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `text-decoration-thickness` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <p class="decoration-[3px]"> <!-- ... --> </p``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/text-decoration-thicknessText Underline Offset ===================== Utilities for controlling the offset of a text underline. Quick reference --------------- | Class | Properties | | --- | --- | | underline-offset-auto | text-underline-offset: auto; | | underline-offset-0 | text-underline-offset: 0px; | | underline-offset-1 | text-underline-offset: 1px; | | underline-offset-2 | text-underline-offset: 2px; | | underline-offset-4 | text-underline-offset: 4px; | | underline-offset-8 | text-underline-offset: 8px; | Basic usage ----------- ### Setting the underline offset Use the `underline-offset-{width}` utilities to change the offset of a text underline. ``` <p class="underline underline-offset-1 ...">The quick brown fox...</p> <p class="underline underline-offset-2 ...">The quick brown fox...</p> <p class="underline underline-offset-4 ...">The quick brown fox...</p> <p class="underline underline-offset-8 ...">The quick brown fox...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:underline-offset-4` to only apply the `underline-offset-4` utility on hover. ``` <p class="underline hover:underline-offset-4"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:underline-offset-4` to apply the `underline-offset-4` utility at only medium screen sizes and above. ``` <p class="underline md:underline-offset-4"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme You can customize the `underline-offset-{width}` utilities by editing `theme.textUnderlineOffset` or `theme.extend.textUnderlineOffset` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { textUnderlineOffset: { 3: '3px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `text-underline-offset` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <p class="underline-offset-[3px]"> <!-- ... --> </p``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/text-underline-offsetText Transform ============== Utilities for controlling the transformation of text. Quick reference --------------- | Class | Properties | | --- | --- | | uppercase | text-transform: uppercase; | | lowercase | text-transform: lowercase; | | capitalize | text-transform: capitalize; | | normal-case | text-transform: none; | Basic usage ----------- ### Transforming text The `uppercase` and `lowercase` will uppercase and lowercase text respectively, whereas `capitalize` utility will convert text to title-case. The `normal-case` utility can be used to preserve the original casing — typically to reset capitalization at different breakpoints. ``` <p class="normal-case ...">The quick brown fox ...</p> <p class="uppercase ...">The quick brown fox ...</p> <p class="lowercase ...">The quick brown fox ...</p> <p class="capitalize ...">The quick brown fox ...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:uppercase` to only apply the `uppercase` utility on hover. ``` <p class="capitalize hover:uppercase"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:uppercase` to apply the `uppercase` utility at only medium screen sizes and above. ``` <p class="capitalize md:uppercase"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/text-transformText Overflow ============= Utilities for controlling text overflow in an element. Quick reference --------------- | Class | Properties | | --- | --- | | truncate | overflow: hidden; text-overflow: ellipsis; white-space: nowrap; | | text-ellipsis | text-overflow: ellipsis; | | text-clip | text-overflow: clip; | Basic usage ----------- ### Truncate Use `truncate` to truncate overflowing text with an ellipsis (`…`) if needed. ``` <p class="truncate ...">...</p> ``` ### Ellipsis Use `text-ellipsis` to truncate overflowing text with an ellipsis (`…`) if needed. ``` <p class="text-ellipsis overflow-hidden ...">...</p> ``` ### Clip Use `text-clip` to truncate the text at the limit of the content area. ``` <p class="text-clip overflow-hidden ...">...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:text-clip` to only apply the `text-clip` utility on hover. ``` <p class="truncate hover:text-clip"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:text-clip` to apply the `text-clip` utility at only medium screen sizes and above. ``` <p class="truncate md:text-clip"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/text-overflowText Indent =========== Utilities for controlling the amount of empty space shown before text in a block. Quick reference --------------- | Class | Properties | | --- | --- | | indent-0 | text-indent: 0px; | | indent-px | text-indent: 1px; | | indent-0.5 | text-indent: 0.125rem; /* 2px */ | | indent-1 | text-indent: 0.25rem; /* 4px */ | | indent-1.5 | text-indent: 0.375rem; /* 6px */ | | indent-2 | text-indent: 0.5rem; /* 8px */ | | indent-2.5 | text-indent: 0.625rem; /* 10px */ | | indent-3 | text-indent: 0.75rem; /* 12px */ | | indent-3.5 | text-indent: 0.875rem; /* 14px */ | | indent-4 | text-indent: 1rem; /* 16px */ | | indent-5 | text-indent: 1.25rem; /* 20px */ | | indent-6 | text-indent: 1.5rem; /* 24px */ | | indent-7 | text-indent: 1.75rem; /* 28px */ | | indent-8 | text-indent: 2rem; /* 32px */ | | indent-9 | text-indent: 2.25rem; /* 36px */ | | indent-10 | text-indent: 2.5rem; /* 40px */ | | indent-11 | text-indent: 2.75rem; /* 44px */ | | indent-12 | text-indent: 3rem; /* 48px */ | | indent-14 | text-indent: 3.5rem; /* 56px */ | | indent-16 | text-indent: 4rem; /* 64px */ | | indent-20 | text-indent: 5rem; /* 80px */ | | indent-24 | text-indent: 6rem; /* 96px */ | | indent-28 | text-indent: 7rem; /* 112px */ | | indent-32 | text-indent: 8rem; /* 128px */ | | indent-36 | text-indent: 9rem; /* 144px */ | | indent-40 | text-indent: 10rem; /* 160px */ | | indent-44 | text-indent: 11rem; /* 176px */ | | indent-48 | text-indent: 12rem; /* 192px */ | | indent-52 | text-indent: 13rem; /* 208px */ | | indent-56 | text-indent: 14rem; /* 224px */ | | indent-60 | text-indent: 15rem; /* 240px */ | | indent-64 | text-indent: 16rem; /* 256px */ | | indent-72 | text-indent: 18rem; /* 288px */ | | indent-80 | text-indent: 20rem; /* 320px */ | | indent-96 | text-indent: 24rem; /* 384px */ | Basic usage ----------- ### Adding a text indent Use the `indent-{width}` utilities to set the amount of empty space (indentation) that’s shown before text in a block. ``` <p class="indent-8"> So I started to walk into the water. I won't lie to you boys, I was terrified. But I pressed on, and as I made my way past the breakers a strange calm came over me. I don't know if it was divine intervention or the kinship of all living things but I tell you Jerry at that moment, I <em>was</em> a marine biologist. </p> ``` ### Using negative values To use a negative text indent value, prefix the class name with a dash to convert it to a negative value. ``` <div class="-indent-8"> So I started to walk into the water. I won't lie to... </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:indent-8` to only apply the `indent-8` utility on hover. ``` <div class="indent-4 hover:indent-8"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:indent-8` to apply the `indent-8` utility at only medium screen sizes and above. ``` <div class="indent-4 md:indent-8"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme The default text indent scale is based on the [default spacing scale](customizing-spacing#default-spacing-scale). You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '128': '32rem', } } } } ``` Alternatively, you can customize just the text indent scale by editing `theme.textIndent` or `theme.extend.textIndent` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { textIndent: { '128': '32rem', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `text-indent` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="indent-[50%]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/text-indentVertical Align ============== Utilities for controlling the vertical alignment of an inline or table-cell box. Quick reference --------------- | Class | Properties | | --- | --- | | align-baseline | vertical-align: baseline; | | align-top | vertical-align: top; | | align-middle | vertical-align: middle; | | align-bottom | vertical-align: bottom; | | align-text-top | vertical-align: text-top; | | align-text-bottom | vertical-align: text-bottom; | | align-sub | vertical-align: sub; | | align-super | vertical-align: super; | Basic usage ----------- ### Baseline Use `align-baseline` to align the baseline of an element with the baseline of its parent. ``` <span class="inline-block align-baseline ...">...</span> ``` ### Top Use `align-top` to align the top of an element and its descendants with the top of the entire line. ``` <span class="inline-block align-top ...">...</span> ``` ### Middle Use `align-middle` to align the middle of an element with the baseline plus half the x-height of the parent. ``` <span class="inline-block align-middle ...">...</span> ``` ### Bottom Use `align-bottom` to align the bottom of an element and its descendants with the bottom of the entire line. ``` <span class="inline-block align-bottom ...">...</span> ``` ### Text Top Use `align-text-top` to align the top of an element with the top of the parent element’s font. ``` <span class="inline-block align-text-top ...">...</span> ``` ### Text Bottom Use `align-text-bottom` to align the bottom of an element with the bottom of the parent element’s font. ``` <span class="inline-block align-text-bottom ...">...</span> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:align-top` to only apply the `align-top` utility on hover. ``` <p class="align-middle hover:align-top"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:align-top` to apply the `align-top` utility at only medium screen sizes and above. ``` <p class="align-middle md:align-top"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Arbitrary values If you need to use a one-off `vertical-align` value that isn't included in Tailwind by default, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="align-[4px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/vertical-alignWhitespace ========== Utilities for controlling an element's white-space property. Quick reference --------------- | Class | Properties | | --- | --- | | whitespace-normal | white-space: normal; | | whitespace-nowrap | white-space: nowrap; | | whitespace-pre | white-space: pre; | | whitespace-pre-line | white-space: pre-line; | | whitespace-pre-wrap | white-space: pre-wrap; | | whitespace-break-spaces | white-space: break-spaces; | Basic usage ----------- ### Normal Use `whitespace-normal` to cause text to wrap normally within an element. Newlines and spaces will be collapsed. ``` <div class="w-3/4 ..."> <div class="whitespace-normal ...">Hey everyone! It's almost 2022 and we still don't know if there is aliens living among us, or do we? Maybe the person writing this is an alien. You will never know.</div> </div> ``` ### No Wrap Use `whitespace-nowrap` to prevent text from wrapping within an element. Newlines and spaces will be collapsed. ``` <div class="w-3/4 overflow-x-auto ..."> <div class="whitespace-nowrap ...">Hey everyone! It's almost 2022 and we still don't know if there is aliens living among us, or do we? Maybe the person writing this is an alien. You will never know.</div> </div> ``` ### Pre Use `whitespace-pre` to preserve newlines and spaces within an element. Text will not be wrapped. ``` <div class="w-3/4 overflow-x-auto ..."> <div class="whitespace-pre ...">Hey everyone! It's almost 2022 and we still don't know if there is aliens living among us, or do we? Maybe the person writing this is an alien. You will never know.</div> </div> ``` ### Pre Line Use `whitespace-pre-line` to preserve newlines but not spaces within an element. Text will be wrapped normally. ``` <div class="w-3/4 ..."> <div class="whitespace-pre-line ...">Hey everyone! It's almost 2022 and we still don't know if there is aliens living among us, or do we? Maybe the person writing this is an alien. You will never know.</div> </div> ``` ### Pre Wrap Use `whitespace-pre-wrap` to preserve newlines and spaces within an element. Text will be wrapped normally. ``` <div class="w-3/4 ..."> <div class="whitespace-pre-wrap ...">Hey everyone! It's almost 2022 and we still don't know if there is aliens living among us, or do we? Maybe the person writing this is an alien. You will never know.</div> </div> ``` ### Break Spaces Use `whitespace-break-spaces` to preserve newlines and spaces within an element. White space at the end of lines will not hang, but will wrap to the next line. ``` <div class="w-3/4 ..."> <div class="whitespace-break-spaces ...">Hey everyone! It's almost 2022 and we still don't know if there is aliens living among us, or do we? Maybe the person writing this is an alien. You will never know.</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:whitespace-pre` to only apply the `whitespace-pre` utility on hover. ``` <div class="whitespace-normal hover:whitespace-pre"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:whitespace-pre` to apply the `whitespace-pre` utility at only medium screen sizes and above. ``` <div class="whitespace-normal md:whitespace-pre"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/whitespaceWord Break ========== Utilities for controlling word breaks in an element. Quick reference --------------- | Class | Properties | | --- | --- | | break-normal | overflow-wrap: normal; word-break: normal; | | break-words | overflow-wrap: break-word; | | break-all | word-break: break-all; | | break-keep | word-break: keep-all; | Basic usage ----------- ### Normal Use `break-normal` to only add line breaks at normal word break points. ``` <p class="break-normal ...">...</p> ``` ### Break Words Use `break-words` to add line breaks mid-word if needed. ``` <p class="break-words ...">...</p> ``` ### Break All Use `break-all` to add line breaks whenever necessary, without trying to preserve whole words. ``` <p class="break-all ...">...</p> ``` ### Break Keep Use `break-keep` to prevent line breaks from being applied to Chinese/Japanese/Korean (CJK) text. For non-CJK text `break-keep` has the same behavior as `break-normal`. ``` <p class="break-keep ...">...</p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:break-all` to only apply the `break-all` utility on hover. ``` <p class="break-normal hover:break-all"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:break-all` to apply the `break-all` utility at only medium screen sizes and above. ``` <p class="break-normal md:break-all"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/word-breakHyphens ======= Utilities for controlling how words should be hyphenated. Quick reference --------------- | Class | Properties | | --- | --- | | hyphens-none | hyphens: none; | | hyphens-manual | hyphens: manual; | | hyphens-auto | hyphens: auto; | Basic usage ----------- ### None Use `hyphens-none` to prevent words from being hyphenated even if the line break suggestion `&shy;` is used: ``` <p class="hyphens-none ..."> ... Kraftfahrzeug&shy;haftpflichtversicherung is a ... </p> ``` ### Manual Use `hyphens-manual` to only set hyphenation points where the line break suggestion `&shy;` is used: ``` <p class="hyphens-manual ..."> ... Kraftfahrzeug&shy;haftpflichtversicherung is a ... </p> ``` ### Auto Use `hyphens-auto` to allow the browser to automatically choose hyphenation points based on the language. The line break suggestion `&shy;` will be preferred over automatic hyphenation points. ``` <p class="hyphens-auto ..." lang="de"> ... Kraftfahrzeughaftpflichtversicherung is a ... </p> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:hyphens-auto` to only apply the `hyphens-auto` utility on hover. ``` <p class="hyphens-none hover:hyphens-auto"> <!-- ... --> </p``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:hyphens-auto` to apply the `hyphens-auto` utility at only medium screen sizes and above. ``` <p class="hyphens-none md:hyphens-auto"> <!-- ... --> </p``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/hyphensContent ======= Utilities for controlling the content of the before and after pseudo-elements. Quick reference --------------- | Class | Properties | | --- | --- | | content-none | content: none; | Basic usage ----------- ### Setting a pseudo-element’s content Use the `content-{value}` utilities along with the `before` and `after` variant modifiers to set the contents of the `::before` and `::after` pseudo-elements. Out of the box, `content-none` is the only available preconfigured content utility. And while you can add additional utilities by [customizing your theme](content#customizing-your-theme), it generally makes more sense to just use an arbitrary value. Use the square bracket notation to define any arbitrary content value on the fly. ``` Higher resolution means more than just a better-quality image. With a Retina 6K display, <a class="text-blue-600 after:content-['_↗'] ..." href="https://www. apple.com/pro-display-xdr/" target="_blank">Pro Display XDR</a> gives you nearly 40 percent more screen real estate than a 5K display.Higher resolution means more than just a better-quality image. With a Retina 6K display, <a class="text-sky-400 after:content-['_↗'] ..." href="https://www. apple.com/pro-display-xdr/" target="_blank">Pro Display XDR</a> gives you nearly 40 percent more screen real estate than a 5K display. ``` ### Referencing an attribute value These content utilities even support CSS features like the `attr()` function, which you can use to reference a value stored in an attribute: ``` <div before="Hello World" class="before:content-[attr(before)]"> <!-- ... --> </div> ``` ### Using spaces and underscores Since whitespace denotes the end of a class in HTML, replace any spaces in an arbitrary value with an underscore: ``` <div class="before:content-['Hello_World']"> <!-- ... --> </div> ``` If you need to include an actual underscore, you can do this by escaping it with a backslash: ``` <div class="before:content-['Hello_World']"> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:before:content-['Hovering']` to only apply the `before:content-['Hovering']` utility on hover. ``` <div class="before:content-['Not_Hovering'] hover:before:content-['Hovering']"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:before:content-['Desktop']` to apply the `before:content-['Desktop']` utility at only medium screen sizes and above. ``` <div class="before:content-['Mobile'] md:before:content-['Desktop']"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind only provides the `content-none` utility. You can customize these values by editing `theme.content` or `theme.extend.content` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { content: { 'link': 'url("/icons/link.svg")', }, } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `content` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="before:content-['Hello_World']"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/contentBackground Attachment ===================== Utilities for controlling how a background image behaves when scrolling. Quick reference --------------- | Class | Properties | | --- | --- | | bg-fixed | background-attachment: fixed; | | bg-local | background-attachment: local; | | bg-scroll | background-attachment: scroll; | Basic usage ----------- ### Fixed Use `bg-fixed` to fix the background image relative to the viewport. ``` <div class="bg-fixed ..." style="background-image: url(...)"></div> ``` ### Local Use `bg-local` to scroll the background image with the container and the viewport. ``` <div class="bg-local ..." style="background-image: url(...)"></div> ``` ### Scroll Use `bg-scroll` to scroll the background image with the viewport, but not with the container. ``` <div class="bg-scroll ..." style="background-image: url(...)"></div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:bg-fixed` to only apply the `bg-fixed` utility on hover. ``` <div class="bg-local hover:bg-fixed"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:bg-fixed` to apply the `bg-fixed` utility at only medium screen sizes and above. ``` <div class="bg-local md:bg-fixed"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/background-attachmentBackground Clip =============== Utilities for controlling the bounding box of an element's background. Quick reference --------------- | Class | Properties | | --- | --- | | bg-clip-border | background-clip: border-box; | | bg-clip-padding | background-clip: padding-box; | | bg-clip-content | background-clip: content-box; | | bg-clip-text | background-clip: text; | Basic usage ----------- ### Setting the background clip Use the `bg-clip-{keyword}` utilities to control the bounding box of an element’s background. ``` <div class="bg-clip-border p-6 bg-violet-600 border-4 border-violet-300 border-dashed"></div> <div class="bg-clip-padding p-6 bg-violet-600 border-4 border-violet-300 border-dashed"></div> <div class="bg-clip-content p-6 bg-violet-600 border-4 border-violet-300 border-dashed"></div> ``` ### Cropping to text Use `bg-clip-text` to crop an element’s background to match the shape of the text. Useful for effects where you want a background image to be visible through the text. ``` <div class="text-5xl font-extrabold ..."> <span class="bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500"> Hello world </span> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:bg-clip-padding` to only apply the `bg-clip-padding` utility on hover. ``` <div class="bg-clip-border hover:bg-clip-padding"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:bg-clip-padding` to apply the `bg-clip-padding` utility at only medium screen sizes and above. ``` <div class="bg-clip-border md:bg-clip-padding"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/background-clipBackground Color ================ Utilities for controlling an element's background color. Quick reference --------------- | Class | Properties | Preview | | --- | --- | --- | | bg-inherit | background-color: inherit; | | | bg-current | background-color: currentColor; | | | bg-transparent | background-color: transparent; | | | bg-black | background-color: rgb(0 0 0); | | | bg-white | background-color: rgb(255 255 255); | | | bg-slate-50 | background-color: rgb(248 250 252); | | | bg-slate-100 | background-color: rgb(241 245 249); | | | bg-slate-200 | background-color: rgb(226 232 240); | | | bg-slate-300 | background-color: rgb(203 213 225); | | | bg-slate-400 | background-color: rgb(148 163 184); | | | bg-slate-500 | background-color: rgb(100 116 139); | | | bg-slate-600 | background-color: rgb(71 85 105); | | | bg-slate-700 | background-color: rgb(51 65 85); | | | bg-slate-800 | background-color: rgb(30 41 59); | | | bg-slate-900 | background-color: rgb(15 23 42); | | | bg-slate-950 | background-color: rgb(2 6 23); | | | bg-gray-50 | background-color: rgb(249 250 251); | | | bg-gray-100 | background-color: rgb(243 244 246); | | | bg-gray-200 | background-color: rgb(229 231 235); | | | bg-gray-300 | background-color: rgb(209 213 219); | | | bg-gray-400 | background-color: rgb(156 163 175); | | | bg-gray-500 | background-color: rgb(107 114 128); | | | bg-gray-600 | background-color: rgb(75 85 99); | | | bg-gray-700 | background-color: rgb(55 65 81); | | | bg-gray-800 | background-color: rgb(31 41 55); | | | bg-gray-900 | background-color: rgb(17 24 39); | | | bg-gray-950 | background-color: rgb(3 7 18); | | | bg-zinc-50 | background-color: rgb(250 250 250); | | | bg-zinc-100 | background-color: rgb(244 244 245); | | | bg-zinc-200 | background-color: rgb(228 228 231); | | | bg-zinc-300 | background-color: rgb(212 212 216); | | | bg-zinc-400 | background-color: rgb(161 161 170); | | | bg-zinc-500 | background-color: rgb(113 113 122); | | | bg-zinc-600 | background-color: rgb(82 82 91); | | | bg-zinc-700 | background-color: rgb(63 63 70); | | | bg-zinc-800 | background-color: rgb(39 39 42); | | | bg-zinc-900 | background-color: rgb(24 24 27); | | | bg-zinc-950 | background-color: rgb(9 9 11); | | | bg-neutral-50 | background-color: rgb(250 250 250); | | | bg-neutral-100 | background-color: rgb(245 245 245); | | | bg-neutral-200 | background-color: rgb(229 229 229); | | | bg-neutral-300 | background-color: rgb(212 212 212); | | | bg-neutral-400 | background-color: rgb(163 163 163); | | | bg-neutral-500 | background-color: rgb(115 115 115); | | | bg-neutral-600 | background-color: rgb(82 82 82); | | | bg-neutral-700 | background-color: rgb(64 64 64); | | | bg-neutral-800 | background-color: rgb(38 38 38); | | | bg-neutral-900 | background-color: rgb(23 23 23); | | | bg-neutral-950 | background-color: rgb(10 10 10); | | | bg-stone-50 | background-color: rgb(250 250 249); | | | bg-stone-100 | background-color: rgb(245 245 244); | | | bg-stone-200 | background-color: rgb(231 229 228); | | | bg-stone-300 | background-color: rgb(214 211 209); | | | bg-stone-400 | background-color: rgb(168 162 158); | | | bg-stone-500 | background-color: rgb(120 113 108); | | | bg-stone-600 | background-color: rgb(87 83 78); | | | bg-stone-700 | background-color: rgb(68 64 60); | | | bg-stone-800 | background-color: rgb(41 37 36); | | | bg-stone-900 | background-color: rgb(28 25 23); | | | bg-stone-950 | background-color: rgb(12 10 9); | | | bg-red-50 | background-color: rgb(254 242 242); | | | bg-red-100 | background-color: rgb(254 226 226); | | | bg-red-200 | background-color: rgb(254 202 202); | | | bg-red-300 | background-color: rgb(252 165 165); | | | bg-red-400 | background-color: rgb(248 113 113); | | | bg-red-500 | background-color: rgb(239 68 68); | | | bg-red-600 | background-color: rgb(220 38 38); | | | bg-red-700 | background-color: rgb(185 28 28); | | | bg-red-800 | background-color: rgb(153 27 27); | | | bg-red-900 | background-color: rgb(127 29 29); | | | bg-red-950 | background-color: rgb(69 10 10); | | | bg-orange-50 | background-color: rgb(255 247 237); | | | bg-orange-100 | background-color: rgb(255 237 213); | | | bg-orange-200 | background-color: rgb(254 215 170); | | | bg-orange-300 | background-color: rgb(253 186 116); | | | bg-orange-400 | background-color: rgb(251 146 60); | | | bg-orange-500 | background-color: rgb(249 115 22); | | | bg-orange-600 | background-color: rgb(234 88 12); | | | bg-orange-700 | background-color: rgb(194 65 12); | | | bg-orange-800 | background-color: rgb(154 52 18); | | | bg-orange-900 | background-color: rgb(124 45 18); | | | bg-orange-950 | background-color: rgb(67 20 7); | | | bg-amber-50 | background-color: rgb(255 251 235); | | | bg-amber-100 | background-color: rgb(254 243 199); | | | bg-amber-200 | background-color: rgb(253 230 138); | | | bg-amber-300 | background-color: rgb(252 211 77); | | | bg-amber-400 | background-color: rgb(251 191 36); | | | bg-amber-500 | background-color: rgb(245 158 11); | | | bg-amber-600 | background-color: rgb(217 119 6); | | | bg-amber-700 | background-color: rgb(180 83 9); | | | bg-amber-800 | background-color: rgb(146 64 14); | | | bg-amber-900 | background-color: rgb(120 53 15); | | | bg-amber-950 | background-color: rgb(69 26 3); | | | bg-yellow-50 | background-color: rgb(254 252 232); | | | bg-yellow-100 | background-color: rgb(254 249 195); | | | bg-yellow-200 | background-color: rgb(254 240 138); | | | bg-yellow-300 | background-color: rgb(253 224 71); | | | bg-yellow-400 | background-color: rgb(250 204 21); | | | bg-yellow-500 | background-color: rgb(234 179 8); | | | bg-yellow-600 | background-color: rgb(202 138 4); | | | bg-yellow-700 | background-color: rgb(161 98 7); | | | bg-yellow-800 | background-color: rgb(133 77 14); | | | bg-yellow-900 | background-color: rgb(113 63 18); | | | bg-yellow-950 | background-color: rgb(66 32 6); | | | bg-lime-50 | background-color: rgb(247 254 231); | | | bg-lime-100 | background-color: rgb(236 252 203); | | | bg-lime-200 | background-color: rgb(217 249 157); | | | bg-lime-300 | background-color: rgb(190 242 100); | | | bg-lime-400 | background-color: rgb(163 230 53); | | | bg-lime-500 | background-color: rgb(132 204 22); | | | bg-lime-600 | background-color: rgb(101 163 13); | | | bg-lime-700 | background-color: rgb(77 124 15); | | | bg-lime-800 | background-color: rgb(63 98 18); | | | bg-lime-900 | background-color: rgb(54 83 20); | | | bg-lime-950 | background-color: rgb(26 46 5); | | | bg-green-50 | background-color: rgb(240 253 244); | | | bg-green-100 | background-color: rgb(220 252 231); | | | bg-green-200 | background-color: rgb(187 247 208); | | | bg-green-300 | background-color: rgb(134 239 172); | | | bg-green-400 | background-color: rgb(74 222 128); | | | bg-green-500 | background-color: rgb(34 197 94); | | | bg-green-600 | background-color: rgb(22 163 74); | | | bg-green-700 | background-color: rgb(21 128 61); | | | bg-green-800 | background-color: rgb(22 101 52); | | | bg-green-900 | background-color: rgb(20 83 45); | | | bg-green-950 | background-color: rgb(5 46 22); | | | bg-emerald-50 | background-color: rgb(236 253 245); | | | bg-emerald-100 | background-color: rgb(209 250 229); | | | bg-emerald-200 | background-color: rgb(167 243 208); | | | bg-emerald-300 | background-color: rgb(110 231 183); | | | bg-emerald-400 | background-color: rgb(52 211 153); | | | bg-emerald-500 | background-color: rgb(16 185 129); | | | bg-emerald-600 | background-color: rgb(5 150 105); | | | bg-emerald-700 | background-color: rgb(4 120 87); | | | bg-emerald-800 | background-color: rgb(6 95 70); | | | bg-emerald-900 | background-color: rgb(6 78 59); | | | bg-emerald-950 | background-color: rgb(2 44 34); | | | bg-teal-50 | background-color: rgb(240 253 250); | | | bg-teal-100 | background-color: rgb(204 251 241); | | | bg-teal-200 | background-color: rgb(153 246 228); | | | bg-teal-300 | background-color: rgb(94 234 212); | | | bg-teal-400 | background-color: rgb(45 212 191); | | | bg-teal-500 | background-color: rgb(20 184 166); | | | bg-teal-600 | background-color: rgb(13 148 136); | | | bg-teal-700 | background-color: rgb(15 118 110); | | | bg-teal-800 | background-color: rgb(17 94 89); | | | bg-teal-900 | background-color: rgb(19 78 74); | | | bg-teal-950 | background-color: rgb(4 47 46); | | | bg-cyan-50 | background-color: rgb(236 254 255); | | | bg-cyan-100 | background-color: rgb(207 250 254); | | | bg-cyan-200 | background-color: rgb(165 243 252); | | | bg-cyan-300 | background-color: rgb(103 232 249); | | | bg-cyan-400 | background-color: rgb(34 211 238); | | | bg-cyan-500 | background-color: rgb(6 182 212); | | | bg-cyan-600 | background-color: rgb(8 145 178); | | | bg-cyan-700 | background-color: rgb(14 116 144); | | | bg-cyan-800 | background-color: rgb(21 94 117); | | | bg-cyan-900 | background-color: rgb(22 78 99); | | | bg-cyan-950 | background-color: rgb(8 51 68); | | | bg-sky-50 | background-color: rgb(240 249 255); | | | bg-sky-100 | background-color: rgb(224 242 254); | | | bg-sky-200 | background-color: rgb(186 230 253); | | | bg-sky-300 | background-color: rgb(125 211 252); | | | bg-sky-400 | background-color: rgb(56 189 248); | | | bg-sky-500 | background-color: rgb(14 165 233); | | | bg-sky-600 | background-color: rgb(2 132 199); | | | bg-sky-700 | background-color: rgb(3 105 161); | | | bg-sky-800 | background-color: rgb(7 89 133); | | | bg-sky-900 | background-color: rgb(12 74 110); | | | bg-sky-950 | background-color: rgb(8 47 73); | | | bg-blue-50 | background-color: rgb(239 246 255); | | | bg-blue-100 | background-color: rgb(219 234 254); | | | bg-blue-200 | background-color: rgb(191 219 254); | | | bg-blue-300 | background-color: rgb(147 197 253); | | | bg-blue-400 | background-color: rgb(96 165 250); | | | bg-blue-500 | background-color: rgb(59 130 246); | | | bg-blue-600 | background-color: rgb(37 99 235); | | | bg-blue-700 | background-color: rgb(29 78 216); | | | bg-blue-800 | background-color: rgb(30 64 175); | | | bg-blue-900 | background-color: rgb(30 58 138); | | | bg-blue-950 | background-color: rgb(23 37 84); | | | bg-indigo-50 | background-color: rgb(238 242 255); | | | bg-indigo-100 | background-color: rgb(224 231 255); | | | bg-indigo-200 | background-color: rgb(199 210 254); | | | bg-indigo-300 | background-color: rgb(165 180 252); | | | bg-indigo-400 | background-color: rgb(129 140 248); | | | bg-indigo-500 | background-color: rgb(99 102 241); | | | bg-indigo-600 | background-color: rgb(79 70 229); | | | bg-indigo-700 | background-color: rgb(67 56 202); | | | bg-indigo-800 | background-color: rgb(55 48 163); | | | bg-indigo-900 | background-color: rgb(49 46 129); | | | bg-indigo-950 | background-color: rgb(30 27 75); | | | bg-violet-50 | background-color: rgb(245 243 255); | | | bg-violet-100 | background-color: rgb(237 233 254); | | | bg-violet-200 | background-color: rgb(221 214 254); | | | bg-violet-300 | background-color: rgb(196 181 253); | | | bg-violet-400 | background-color: rgb(167 139 250); | | | bg-violet-500 | background-color: rgb(139 92 246); | | | bg-violet-600 | background-color: rgb(124 58 237); | | | bg-violet-700 | background-color: rgb(109 40 217); | | | bg-violet-800 | background-color: rgb(91 33 182); | | | bg-violet-900 | background-color: rgb(76 29 149); | | | bg-violet-950 | background-color: rgb(46 16 101); | | | bg-purple-50 | background-color: rgb(250 245 255); | | | bg-purple-100 | background-color: rgb(243 232 255); | | | bg-purple-200 | background-color: rgb(233 213 255); | | | bg-purple-300 | background-color: rgb(216 180 254); | | | bg-purple-400 | background-color: rgb(192 132 252); | | | bg-purple-500 | background-color: rgb(168 85 247); | | | bg-purple-600 | background-color: rgb(147 51 234); | | | bg-purple-700 | background-color: rgb(126 34 206); | | | bg-purple-800 | background-color: rgb(107 33 168); | | | bg-purple-900 | background-color: rgb(88 28 135); | | | bg-purple-950 | background-color: rgb(59 7 100); | | | bg-fuchsia-50 | background-color: rgb(253 244 255); | | | bg-fuchsia-100 | background-color: rgb(250 232 255); | | | bg-fuchsia-200 | background-color: rgb(245 208 254); | | | bg-fuchsia-300 | background-color: rgb(240 171 252); | | | bg-fuchsia-400 | background-color: rgb(232 121 249); | | | bg-fuchsia-500 | background-color: rgb(217 70 239); | | | bg-fuchsia-600 | background-color: rgb(192 38 211); | | | bg-fuchsia-700 | background-color: rgb(162 28 175); | | | bg-fuchsia-800 | background-color: rgb(134 25 143); | | | bg-fuchsia-900 | background-color: rgb(112 26 117); | | | bg-fuchsia-950 | background-color: rgb(74 4 78); | | | bg-pink-50 | background-color: rgb(253 242 248); | | | bg-pink-100 | background-color: rgb(252 231 243); | | | bg-pink-200 | background-color: rgb(251 207 232); | | | bg-pink-300 | background-color: rgb(249 168 212); | | | bg-pink-400 | background-color: rgb(244 114 182); | | | bg-pink-500 | background-color: rgb(236 72 153); | | | bg-pink-600 | background-color: rgb(219 39 119); | | | bg-pink-700 | background-color: rgb(190 24 93); | | | bg-pink-800 | background-color: rgb(157 23 77); | | | bg-pink-900 | background-color: rgb(131 24 67); | | | bg-pink-950 | background-color: rgb(80 7 36); | | | bg-rose-50 | background-color: rgb(255 241 242); | | | bg-rose-100 | background-color: rgb(255 228 230); | | | bg-rose-200 | background-color: rgb(254 205 211); | | | bg-rose-300 | background-color: rgb(253 164 175); | | | bg-rose-400 | background-color: rgb(251 113 133); | | | bg-rose-500 | background-color: rgb(244 63 94); | | | bg-rose-600 | background-color: rgb(225 29 72); | | | bg-rose-700 | background-color: rgb(190 18 60); | | | bg-rose-800 | background-color: rgb(159 18 57); | | | bg-rose-900 | background-color: rgb(136 19 55); | | | bg-rose-950 | background-color: rgb(76 5 25); | | Basic usage ----------- ### Setting the background color Control the background color of an element using the `bg-{color}` utilities. ``` <button class="bg-indigo-500 ..."> Save changes </button> ``` ### Changing the opacity Control the opacity of an element’s background color using the color opacity modifier. ``` <button class="bg-sky-500/100 ..."></button> <button class="bg-sky-500/75 ..."></button> <button class="bg-sky-500/50 ..."></button> ``` You can use any value defined in your [opacity scale](opacity), or use arbitrary values if you need to deviate from your design tokens. ``` <div class="bg-sky-500/[.06] ..."></div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:bg-cyan-600` to only apply the `bg-cyan-600` utility on hover. ``` <button class="bg-cyan-500 hover:bg-cyan-600 ...">Subscribe</button> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:bg-green-500` to apply the `bg-green-500` utility at only medium screen sizes and above. ``` <button class="bg-blue-500 md:bg-green-500 ...">Subscribe</button> ``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as background colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your background colors by editing `theme.backgroundColor` or `theme.extend.backgroundColor` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `color` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <p class="bg-[#50d71e]"> <!-- ... --> </p``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/background-colorBackground Origin ================= Utilities for controlling how an element's background is positioned relative to borders, padding, and content. Quick reference --------------- | Class | Properties | | --- | --- | | bg-origin-border | background-origin: border-box; | | bg-origin-padding | background-origin: padding-box; | | bg-origin-content | background-origin: content-box; | Basic usage ----------- ### Setting the background origin Use `bg-origin-border`, `bg-origin-padding`, and `bg-origin-content` to control where an element’s background is rendered. ``` <div class="bg-origin-border p-4 border-4 border-dashed ..." style="background-image: url(...)"></div> <div class="bg-origin-padding p-4 border-4 border-dashed ..." style="background-image: url(...)"></div> <div class="bg-origin-content p-4 border-4 border-dashed ..." style="background-image: url(...)"></div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:bg-origin-padding` to only apply the `bg-origin-padding` utility on hover. ``` <div class="bg-origin-border hover:bg-origin-padding"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:bg-origin-padding` to apply the `bg-origin-padding` utility at only medium screen sizes and above. ``` <div class="bg-origin-border md:bg-origin-padding"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/background-originBackground Position =================== Utilities for controlling the position of an element's background image. Quick reference --------------- | Class | Properties | | --- | --- | | bg-bottom | background-position: bottom; | | bg-center | background-position: center; | | bg-left | background-position: left; | | bg-left-bottom | background-position: left bottom; | | bg-left-top | background-position: left top; | | bg-right | background-position: right; | | bg-right-bottom | background-position: right bottom; | | bg-right-top | background-position: right top; | | bg-top | background-position: top; | Basic usage ----------- ### Setting the background position Use the `bg-{side}` utilities to control the position of an element’s background image. ``` <div class="bg-no-repeat bg-left-top ..." style="background-image: url(...);"></div> <div class="bg-no-repeat bg-top ..." style="background-image: url(...);"></div> <div class="bg-no-repeat bg-right-top ..." style="background-image: url(...);"></div> <div class="bg-no-repeat bg-left ..." style="background-image: url(...);"></div> <div class="bg-no-repeat bg-center ..." style="background-image: url(...);"></div> <div class="bg-no-repeat bg-right ..." style="background-image: url(...);"></div> <div class="bg-no-repeat bg-left-bottom ..." style="background-image: url(...);"></div> <div class="bg-no-repeat bg-bottom ..." style="background-image: url(...);"></div> <div class="bg-no-repeat bg-right-bottom ..." style="background-image: url(...);"></div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:bg-top` to only apply the `bg-top` utility on hover. ``` <div class="bg-center hover:bg-top ..." style="background-image: url(...)"></div> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:bg-top` to apply the `bg-top` utility at only medium screen sizes and above. ``` <div class="bg-center md:bg-top ..." style="background-image: url(...)"></div> ``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides nine `background-position` utilities. You change, add, or remove these by editing the `theme.backgroundPosition` section of your Tailwind config. tailwind.config.js ``` module.exports = { theme: { backgroundPosition: { bottom: 'bottom', 'bottom-4': 'center bottom 1rem', center: 'center', left: 'left', 'left-bottom': 'left bottom', 'left-top': 'left top', right: 'right', 'right-bottom': 'right bottom', 'right-top': 'right top', top: 'top', 'top-4': 'center top 1rem', } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `background-position` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="bg-[center_top_1rem]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/background-positionBackground Repeat ================= Utilities for controlling the repetition of an element's background image. Quick reference --------------- | Class | Properties | | --- | --- | | bg-repeat | background-repeat: repeat; | | bg-no-repeat | background-repeat: no-repeat; | | bg-repeat-x | background-repeat: repeat-x; | | bg-repeat-y | background-repeat: repeat-y; | | bg-repeat-round | background-repeat: round; | | bg-repeat-space | background-repeat: space; | Basic usage ----------- ### Repeat Use `bg-repeat` to repeat the background image both vertically and horizontally. ``` <div class="bg-repeat ..." style="background-image: url(...)"></div> ``` ### No Repeat Use `bg-no-repeat` when you don’t want to repeat the background image. ``` <div class="bg-no-repeat bg-center ..." style="background-image: url(...)"></div> ``` ### Repeat Horizontally Use `bg-repeat-x` to repeat the background image only horizontally. ``` <div class="bg-repeat-x bg-center ..." style="background-image: url(...)"></div> ``` ### Repeat Vertically Use `bg-repeat-y` to repeat the background image only vertically. ``` <div class="bg-repeat-y bg-center ..." style="background-image: url(...)"></div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:bg-repeat-x` to only apply the `bg-repeat-x` utility on hover. ``` <div class="bg-repeat hover:bg-repeat-x"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:bg-repeat-x` to apply the `bg-repeat-x` utility at only medium screen sizes and above. ``` <div class="bg-repeat md:bg-repeat-x"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/background-repeatBackground Size =============== Utilities for controlling the background size of an element's background image. Quick reference --------------- | Class | Properties | | --- | --- | | bg-auto | background-size: auto; | | bg-cover | background-size: cover; | | bg-contain | background-size: contain; | Basic usage ----------- ### Auto Use `bg-auto` to display the background image at its default size. ``` <div class="bg-auto bg-no-repeat bg-center ..." style="background-image: url(...)"></div> ``` ### Cover Use `bg-cover` to scale the background image until it fills the background layer. ``` <div class="bg-cover bg-center ..." style="background-image: url(...)"></div> ``` ### Contain Use `bg-contain` to scale the background image to the outer edges without cropping or stretching. ``` <div class="bg-contain bg-center ..." style="background-image: url(...)"></div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:bg-contain` to only apply the `bg-contain` utility on hover. ``` <div class="bg-auto hover:bg-contain"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:bg-contain` to apply the `bg-contain` utility at only medium screen sizes and above. ``` <div class="bg-auto md:bg-contain"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides utilities for `auto`, `cover`, and `contain` background sizes. You can change, add, or remove these by editing the `theme.backgroundSize` section of your config. tailwind.config.js ``` module.exports = { theme: { backgroundSize: { 'auto': 'auto', 'cover': 'cover', 'contain': 'contain', '50%': '50%', '16': '4rem', } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `background-size` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="bg-[length:200px_100px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/background-sizeBackground Image ================ Utilities for controlling an element's background image. Quick reference --------------- | Class | Properties | | --- | --- | | bg-none | background-image: none; | | bg-gradient-to-t | background-image: linear-gradient(to top, var(--tw-gradient-stops)); | | bg-gradient-to-tr | background-image: linear-gradient(to top right, var(--tw-gradient-stops)); | | bg-gradient-to-r | background-image: linear-gradient(to right, var(--tw-gradient-stops)); | | bg-gradient-to-br | background-image: linear-gradient(to bottom right, var(--tw-gradient-stops)); | | bg-gradient-to-b | background-image: linear-gradient(to bottom, var(--tw-gradient-stops)); | | bg-gradient-to-bl | background-image: linear-gradient(to bottom left, var(--tw-gradient-stops)); | | bg-gradient-to-l | background-image: linear-gradient(to left, var(--tw-gradient-stops)); | | bg-gradient-to-tl | background-image: linear-gradient(to top left, var(--tw-gradient-stops)); | Basic usage ----------- ### Linear gradients To give an element a linear gradient background, use one of the `bg-gradient-{direction}` utilities, in combination with the [gradient color stop](gradient-color-stops) utilities. ``` <div class="h-14 bg-gradient-to-r from-cyan-500 to-blue-500"></div> <div class="h-14 bg-gradient-to-r from-sky-500 to-indigo-500"></div> <div class="h-14 bg-gradient-to-r from-violet-500 to-fuchsia-500"></div> <div class="h-14 bg-gradient-to-r from-purple-500 to-pink-500"></div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:bg-gradient-to-r` to only apply the `bg-gradient-to-r` utility on hover. ``` <div class="bg-gradient-to-l hover:bg-gradient-to-r"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:bg-gradient-to-r` to apply the `bg-gradient-to-r` utility at only medium screen sizes and above. ``` <div class="bg-gradient-to-l md:bg-gradient-to-r"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes background image utilities for creating linear gradient backgrounds in eight directions. You can add your own background images by editing the `theme.backgroundImage` section of your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { theme: { extend: { backgroundImage: { 'hero-pattern': "url('/img/hero-pattern.svg')", 'footer-texture': "url('/img/footer-texture.png')", } } } } ``` These don’t just have to be gradients — they can be any background images you need. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `background-image` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="bg-[url('/img/hero-pattern.svg')]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/background-imageBorder Radius ============= Utilities for controlling the border radius of an element. Quick reference --------------- | Class | Properties | | --- | --- | | rounded-none | border-radius: 0px; | | rounded-sm | border-radius: 0.125rem; /* 2px */ | | rounded | border-radius: 0.25rem; /* 4px */ | | rounded-md | border-radius: 0.375rem; /* 6px */ | | rounded-lg | border-radius: 0.5rem; /* 8px */ | | rounded-xl | border-radius: 0.75rem; /* 12px */ | | rounded-2xl | border-radius: 1rem; /* 16px */ | | rounded-3xl | border-radius: 1.5rem; /* 24px */ | | rounded-full | border-radius: 9999px; | | rounded-s-none | border-start-start-radius: 0px; border-end-start-radius: 0px; | | rounded-s-sm | border-start-start-radius: 0.125rem; /* 2px */ border-end-start-radius: 0.125rem; /* 2px */ | | rounded-s | border-start-start-radius: 0.25rem; /* 4px */ border-end-start-radius: 0.25rem; /* 4px */ | | rounded-s-md | border-start-start-radius: 0.375rem; /* 6px */ border-end-start-radius: 0.375rem; /* 6px */ | | rounded-s-lg | border-start-start-radius: 0.5rem; /* 8px */ border-end-start-radius: 0.5rem; /* 8px */ | | rounded-s-xl | border-start-start-radius: 0.75rem; /* 12px */ border-end-start-radius: 0.75rem; /* 12px */ | | rounded-s-2xl | border-start-start-radius: 1rem; /* 16px */ border-end-start-radius: 1rem; /* 16px */ | | rounded-s-3xl | border-start-start-radius: 1.5rem; /* 24px */ border-end-start-radius: 1.5rem; /* 24px */ | | rounded-s-full | border-start-start-radius: 9999px; border-end-start-radius: 9999px; | | rounded-e-none | border-start-end-radius: 0px; border-end-end-radius: 0px; | | rounded-e-sm | border-start-end-radius: 0.125rem; /* 2px */ border-end-end-radius: 0.125rem; /* 2px */ | | rounded-e | border-start-end-radius: 0.25rem; /* 4px */ border-end-end-radius: 0.25rem; /* 4px */ | | rounded-e-md | border-start-end-radius: 0.375rem; /* 6px */ border-end-end-radius: 0.375rem; /* 6px */ | | rounded-e-lg | border-start-end-radius: 0.5rem; /* 8px */ border-end-end-radius: 0.5rem; /* 8px */ | | rounded-e-xl | border-start-end-radius: 0.75rem; /* 12px */ border-end-end-radius: 0.75rem; /* 12px */ | | rounded-e-2xl | border-start-end-radius: 1rem; /* 16px */ border-end-end-radius: 1rem; /* 16px */ | | rounded-e-3xl | border-start-end-radius: 1.5rem; /* 24px */ border-end-end-radius: 1.5rem; /* 24px */ | | rounded-e-full | border-start-end-radius: 9999px; border-end-end-radius: 9999px; | | rounded-t-none | border-top-left-radius: 0px; border-top-right-radius: 0px; | | rounded-t-sm | border-top-left-radius: 0.125rem; /* 2px */ border-top-right-radius: 0.125rem; /* 2px */ | | rounded-t | border-top-left-radius: 0.25rem; /* 4px */ border-top-right-radius: 0.25rem; /* 4px */ | | rounded-t-md | border-top-left-radius: 0.375rem; /* 6px */ border-top-right-radius: 0.375rem; /* 6px */ | | rounded-t-lg | border-top-left-radius: 0.5rem; /* 8px */ border-top-right-radius: 0.5rem; /* 8px */ | | rounded-t-xl | border-top-left-radius: 0.75rem; /* 12px */ border-top-right-radius: 0.75rem; /* 12px */ | | rounded-t-2xl | border-top-left-radius: 1rem; /* 16px */ border-top-right-radius: 1rem; /* 16px */ | | rounded-t-3xl | border-top-left-radius: 1.5rem; /* 24px */ border-top-right-radius: 1.5rem; /* 24px */ | | rounded-t-full | border-top-left-radius: 9999px; border-top-right-radius: 9999px; | | rounded-r-none | border-top-right-radius: 0px; border-bottom-right-radius: 0px; | | rounded-r-sm | border-top-right-radius: 0.125rem; /* 2px */ border-bottom-right-radius: 0.125rem; /* 2px */ | | rounded-r | border-top-right-radius: 0.25rem; /* 4px */ border-bottom-right-radius: 0.25rem; /* 4px */ | | rounded-r-md | border-top-right-radius: 0.375rem; /* 6px */ border-bottom-right-radius: 0.375rem; /* 6px */ | | rounded-r-lg | border-top-right-radius: 0.5rem; /* 8px */ border-bottom-right-radius: 0.5rem; /* 8px */ | | rounded-r-xl | border-top-right-radius: 0.75rem; /* 12px */ border-bottom-right-radius: 0.75rem; /* 12px */ | | rounded-r-2xl | border-top-right-radius: 1rem; /* 16px */ border-bottom-right-radius: 1rem; /* 16px */ | | rounded-r-3xl | border-top-right-radius: 1.5rem; /* 24px */ border-bottom-right-radius: 1.5rem; /* 24px */ | | rounded-r-full | border-top-right-radius: 9999px; border-bottom-right-radius: 9999px; | | rounded-b-none | border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; | | rounded-b-sm | border-bottom-right-radius: 0.125rem; /* 2px */ border-bottom-left-radius: 0.125rem; /* 2px */ | | rounded-b | border-bottom-right-radius: 0.25rem; /* 4px */ border-bottom-left-radius: 0.25rem; /* 4px */ | | rounded-b-md | border-bottom-right-radius: 0.375rem; /* 6px */ border-bottom-left-radius: 0.375rem; /* 6px */ | | rounded-b-lg | border-bottom-right-radius: 0.5rem; /* 8px */ border-bottom-left-radius: 0.5rem; /* 8px */ | | rounded-b-xl | border-bottom-right-radius: 0.75rem; /* 12px */ border-bottom-left-radius: 0.75rem; /* 12px */ | | rounded-b-2xl | border-bottom-right-radius: 1rem; /* 16px */ border-bottom-left-radius: 1rem; /* 16px */ | | rounded-b-3xl | border-bottom-right-radius: 1.5rem; /* 24px */ border-bottom-left-radius: 1.5rem; /* 24px */ | | rounded-b-full | border-bottom-right-radius: 9999px; border-bottom-left-radius: 9999px; | | rounded-l-none | border-top-left-radius: 0px; border-bottom-left-radius: 0px; | | rounded-l-sm | border-top-left-radius: 0.125rem; /* 2px */ border-bottom-left-radius: 0.125rem; /* 2px */ | | rounded-l | border-top-left-radius: 0.25rem; /* 4px */ border-bottom-left-radius: 0.25rem; /* 4px */ | | rounded-l-md | border-top-left-radius: 0.375rem; /* 6px */ border-bottom-left-radius: 0.375rem; /* 6px */ | | rounded-l-lg | border-top-left-radius: 0.5rem; /* 8px */ border-bottom-left-radius: 0.5rem; /* 8px */ | | rounded-l-xl | border-top-left-radius: 0.75rem; /* 12px */ border-bottom-left-radius: 0.75rem; /* 12px */ | | rounded-l-2xl | border-top-left-radius: 1rem; /* 16px */ border-bottom-left-radius: 1rem; /* 16px */ | | rounded-l-3xl | border-top-left-radius: 1.5rem; /* 24px */ border-bottom-left-radius: 1.5rem; /* 24px */ | | rounded-l-full | border-top-left-radius: 9999px; border-bottom-left-radius: 9999px; | | rounded-ss-none | border-start-start-radius: 0px; | | rounded-ss-sm | border-start-start-radius: 0.125rem; /* 2px */ | | rounded-ss | border-start-start-radius: 0.25rem; /* 4px */ | | rounded-ss-md | border-start-start-radius: 0.375rem; /* 6px */ | | rounded-ss-lg | border-start-start-radius: 0.5rem; /* 8px */ | | rounded-ss-xl | border-start-start-radius: 0.75rem; /* 12px */ | | rounded-ss-2xl | border-start-start-radius: 1rem; /* 16px */ | | rounded-ss-3xl | border-start-start-radius: 1.5rem; /* 24px */ | | rounded-ss-full | border-start-start-radius: 9999px; | | rounded-se-none | border-start-end-radius: 0px; | | rounded-se-sm | border-start-end-radius: 0.125rem; /* 2px */ | | rounded-se | border-start-end-radius: 0.25rem; /* 4px */ | | rounded-se-md | border-start-end-radius: 0.375rem; /* 6px */ | | rounded-se-lg | border-start-end-radius: 0.5rem; /* 8px */ | | rounded-se-xl | border-start-end-radius: 0.75rem; /* 12px */ | | rounded-se-2xl | border-start-end-radius: 1rem; /* 16px */ | | rounded-se-3xl | border-start-end-radius: 1.5rem; /* 24px */ | | rounded-se-full | border-start-end-radius: 9999px; | | rounded-ee-none | border-end-end-radius: 0px; | | rounded-ee-sm | border-end-end-radius: 0.125rem; /* 2px */ | | rounded-ee | border-end-end-radius: 0.25rem; /* 4px */ | | rounded-ee-md | border-end-end-radius: 0.375rem; /* 6px */ | | rounded-ee-lg | border-end-end-radius: 0.5rem; /* 8px */ | | rounded-ee-xl | border-end-end-radius: 0.75rem; /* 12px */ | | rounded-ee-2xl | border-end-end-radius: 1rem; /* 16px */ | | rounded-ee-3xl | border-end-end-radius: 1.5rem; /* 24px */ | | rounded-ee-full | border-end-end-radius: 9999px; | | rounded-es-none | border-end-start-radius: 0px; | | rounded-es-sm | border-end-start-radius: 0.125rem; /* 2px */ | | rounded-es | border-end-start-radius: 0.25rem; /* 4px */ | | rounded-es-md | border-end-start-radius: 0.375rem; /* 6px */ | | rounded-es-lg | border-end-start-radius: 0.5rem; /* 8px */ | | rounded-es-xl | border-end-start-radius: 0.75rem; /* 12px */ | | rounded-es-2xl | border-end-start-radius: 1rem; /* 16px */ | | rounded-es-3xl | border-end-start-radius: 1.5rem; /* 24px */ | | rounded-es-full | border-end-start-radius: 9999px; | | rounded-tl-none | border-top-left-radius: 0px; | | rounded-tl-sm | border-top-left-radius: 0.125rem; /* 2px */ | | rounded-tl | border-top-left-radius: 0.25rem; /* 4px */ | | rounded-tl-md | border-top-left-radius: 0.375rem; /* 6px */ | | rounded-tl-lg | border-top-left-radius: 0.5rem; /* 8px */ | | rounded-tl-xl | border-top-left-radius: 0.75rem; /* 12px */ | | rounded-tl-2xl | border-top-left-radius: 1rem; /* 16px */ | | rounded-tl-3xl | border-top-left-radius: 1.5rem; /* 24px */ | | rounded-tl-full | border-top-left-radius: 9999px; | | rounded-tr-none | border-top-right-radius: 0px; | | rounded-tr-sm | border-top-right-radius: 0.125rem; /* 2px */ | | rounded-tr | border-top-right-radius: 0.25rem; /* 4px */ | | rounded-tr-md | border-top-right-radius: 0.375rem; /* 6px */ | | rounded-tr-lg | border-top-right-radius: 0.5rem; /* 8px */ | | rounded-tr-xl | border-top-right-radius: 0.75rem; /* 12px */ | | rounded-tr-2xl | border-top-right-radius: 1rem; /* 16px */ | | rounded-tr-3xl | border-top-right-radius: 1.5rem; /* 24px */ | | rounded-tr-full | border-top-right-radius: 9999px; | | rounded-br-none | border-bottom-right-radius: 0px; | | rounded-br-sm | border-bottom-right-radius: 0.125rem; /* 2px */ | | rounded-br | border-bottom-right-radius: 0.25rem; /* 4px */ | | rounded-br-md | border-bottom-right-radius: 0.375rem; /* 6px */ | | rounded-br-lg | border-bottom-right-radius: 0.5rem; /* 8px */ | | rounded-br-xl | border-bottom-right-radius: 0.75rem; /* 12px */ | | rounded-br-2xl | border-bottom-right-radius: 1rem; /* 16px */ | | rounded-br-3xl | border-bottom-right-radius: 1.5rem; /* 24px */ | | rounded-br-full | border-bottom-right-radius: 9999px; | | rounded-bl-none | border-bottom-left-radius: 0px; | | rounded-bl-sm | border-bottom-left-radius: 0.125rem; /* 2px */ | | rounded-bl | border-bottom-left-radius: 0.25rem; /* 4px */ | | rounded-bl-md | border-bottom-left-radius: 0.375rem; /* 6px */ | | rounded-bl-lg | border-bottom-left-radius: 0.5rem; /* 8px */ | | rounded-bl-xl | border-bottom-left-radius: 0.75rem; /* 12px */ | | rounded-bl-2xl | border-bottom-left-radius: 1rem; /* 16px */ | | rounded-bl-3xl | border-bottom-left-radius: 1.5rem; /* 24px */ | | rounded-bl-full | border-bottom-left-radius: 9999px; | Basic usage ----------- ### Rounded corners Use utilities like `rounded-sm`, `rounded`, or `rounded-lg` to apply different border radius sizes to an element. ``` <div class="rounded ..."></div> <div class="rounded-md ..."></div> <div class="rounded-lg ..."></div> <div class="rounded-full ..."></div> ``` ### Pill buttons Use the `rounded-full` utility to create pill buttons. ``` <button class="rounded-full ...">Save Changes</button> ``` ### No rounding Use `rounded-none` to remove an existing border radius from an element. ``` <button class="rounded-none ...">Save Changes</button> ``` This is most commonly used to remove a border radius that was applied at a smaller breakpoint. ### Rounding sides separately Use `rounded-{t|r|b|l}{-size?}` to only round one side of an element. ``` <div class="rounded-t-lg ..."></div> <div class="rounded-r-lg ..."></div> <div class="rounded-b-lg ..."></div> <div class="rounded-l-lg ..."></div> ``` ### Rounding corners separately Use `rounded-{tl|tr|br|bl}{-size?}` to only round one corner an element. ``` <div class="rounded-tl-lg ..."></div> <div class="rounded-tr-lg ..."></div> <div class="rounded-br-lg ..."></div> <div class="rounded-bl-lg ..."></div> ``` ### Using logical properties Use the `rounded-{s|e|ss|se|es|ee}{-size?}` utilities to set the border radius using [logical properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties/Basic_concepts), which map to the appropriate corners based on the text direction. ``` <div dir="ltr"> <div class="rounded-s-lg ..."></div> <div<div dir="rtl"> <div class="rounded-s-lg ..."></div> <div> ``` Here are all the available border color logical property utilities and their physical property equivalents in both LTR and RTL modes. | Class | Left-to-right | Right-to-left | | --- | --- | --- | | `rounded-s-*` | `rounded-l-*` | `rounded-r-*` | | `rounded-e-*` | `rounded-r-*` | `rounded-l-*` | | `rounded-ss-*` | `rounded-tl-*` | `rounded-tr-*` | | `rounded-se-*` | `rounded-tr-*` | `rounded-tl-*` | | `rounded-es-*` | `rounded-bl-*` | `rounded-br-*` | | `rounded-ee-*` | `rounded-br-*` | `rounded-bl-*` | For more control, you can also use the [LTR and RTL modifiers](hover-focus-and-other-states#rtl-support) to conditionally apply specific styles depending on the current text direction. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:rounded-lg` to only apply the `rounded-lg` utility on hover. ``` <div class="rounded hover:rounded-lg"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:rounded-lg` to apply the `rounded-lg` utility at only medium screen sizes and above. ``` <div class="rounded md:rounded-lg"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides five border radius size utilities. You can change, add, or remove these by editing the `theme.borderRadius` section of your Tailwind config. tailwind.config.js ``` module.exports = { theme: { borderRadius: { 'none': '0', 'sm': '0.125rem', DEFAULT: '0.25rem', DEFAULT: '4px', 'md': '0.375rem', 'lg': '0.5rem', 'full': '9999px', 'large': '12px', } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `border-radius` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="rounded-[12px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/border-radiusBorder Width ============ Utilities for controlling the width of an element's borders. Quick reference --------------- | Class | Properties | | --- | --- | | border-0 | border-width: 0px; | | border-2 | border-width: 2px; | | border-4 | border-width: 4px; | | border-8 | border-width: 8px; | | border | border-width: 1px; | | border-x-0 | border-left-width: 0px; border-right-width: 0px; | | border-x-2 | border-left-width: 2px; border-right-width: 2px; | | border-x-4 | border-left-width: 4px; border-right-width: 4px; | | border-x-8 | border-left-width: 8px; border-right-width: 8px; | | border-x | border-left-width: 1px; border-right-width: 1px; | | border-y-0 | border-top-width: 0px; border-bottom-width: 0px; | | border-y-2 | border-top-width: 2px; border-bottom-width: 2px; | | border-y-4 | border-top-width: 4px; border-bottom-width: 4px; | | border-y-8 | border-top-width: 8px; border-bottom-width: 8px; | | border-y | border-top-width: 1px; border-bottom-width: 1px; | | border-s-0 | border-inline-start-width: 0px; | | border-s-2 | border-inline-start-width: 2px; | | border-s-4 | border-inline-start-width: 4px; | | border-s-8 | border-inline-start-width: 8px; | | border-s | border-inline-start-width: 1px; | | border-e-0 | border-inline-end-width: 0px; | | border-e-2 | border-inline-end-width: 2px; | | border-e-4 | border-inline-end-width: 4px; | | border-e-8 | border-inline-end-width: 8px; | | border-e | border-inline-end-width: 1px; | | border-t-0 | border-top-width: 0px; | | border-t-2 | border-top-width: 2px; | | border-t-4 | border-top-width: 4px; | | border-t-8 | border-top-width: 8px; | | border-t | border-top-width: 1px; | | border-r-0 | border-right-width: 0px; | | border-r-2 | border-right-width: 2px; | | border-r-4 | border-right-width: 4px; | | border-r-8 | border-right-width: 8px; | | border-r | border-right-width: 1px; | | border-b-0 | border-bottom-width: 0px; | | border-b-2 | border-bottom-width: 2px; | | border-b-4 | border-bottom-width: 4px; | | border-b-8 | border-bottom-width: 8px; | | border-b | border-bottom-width: 1px; | | border-l-0 | border-left-width: 0px; | | border-l-2 | border-left-width: 2px; | | border-l-4 | border-left-width: 4px; | | border-l-8 | border-left-width: 8px; | | border-l | border-left-width: 1px; | Basic usage ----------- ### All sides Use the `border`, `border-0`, `border-2`, `border-4`, or `border-8` utilities to set the border width for all sides of an element. ``` <div class="border border-indigo-600 ..."></div> <div class="border-2 border-indigo-600 ..."></div> <div class="border-4 border-indigo-600 ..."></div> <div class="border-8 border-indigo-600 ..."></div><div class="border border-sky-500"></div> <div class="border-2 border-sky-500"></div> <div class="border-4 border-sky-500"></div> <div class="border-8 border-sky-500"></div> ``` ### Individual sides Use the `border-{side}`, `border-{side}-0`, `border-{side}-2`, `border-{side}-4`, or `border-{side}-8` utilities to set the border width for one side of an element. ``` <div class="border-t-4 border-indigo-500 ..."></div> <div class="border-r-4 border-indigo-500 ..."></div> <div class="border-b-4 border-indigo-500 ..."></div> <div class="border-l-4 border-indigo-500 ..."></div> ``` ### Horizontal and vertical sides Use the `border-{x|y}-{width}` utilities to set the border width on two sides of an element at the same time. ``` <div class="border-x-4 border-indigo-500 ..."></div> <div class="border-y-4 border-indigo-500 ..."></div> ``` ### Between elements You can also add borders between child elements using the `divide-{x/y}-{width}` and `divide-{color}` utilities. ``` <div class="divide-y divide-slate-200 ..."> <div>01</div> <div>02</div> <div>03</div> </div><div class="divide-y divide-slate-700 ..."> <div>01</div> <div>02</div> <div>03</div> </div> ``` Learn more in the [Divide Width](divide-width) and [Divide Color](divide-color) documentation. ### Using logical properties Use the `border-s-*` and `border-e-*` utilities to set the `border-inline-start-width` and `border-inline-end-width` [logical properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties/Basic_concepts), which map to either the left or right border based on the text direction. ``` <div dir="ltr"> <div class="border-s-4 ..."></div> <div<div dir="rtl"> <div class="border-s-4 ..."></div> <div> ``` For more control, you can also use the [LTR and RTL modifiers](hover-focus-and-other-states#rtl-support) to conditionally apply specific styles depending on the current text direction. ### Using without Preflight If you’ve [disabled Preflight](preflight#disabling-preflight) in your project, you’ll need to include a [border style](border-style) utility any time you use one of the `border-width` utilities for the border to actually take effect: ``` <div class="border-4 border-indigo-500 ..."> <div class="border-4 border-solid border-indigo-500 ..."> <!-- ... --> </div``` This is because browsers set the `border-style` of most elements to `none` by default, so adding a `border-width` on its own isn’t enough to render a border. Preflight applies a global [border reset](preflight#border-styles-are-reset-globally) that sets `border-style` to `solid` and `border-width` to `0`, which is what makes it possible to add a border to an element using just a `border-width` utility in projects using Preflight. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:border-t-4` to only apply the `border-t-4` utility on hover. ``` <div class="border-2 hover:border-t-4"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:border-t-4` to apply the `border-t-4` utility at only medium screen sizes and above. ``` <div class="border-2 md:border-t-4"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides five `border-width` utilities, and the same number of utilities per side (horizontal, vertical, top, right, bottom, and left). You change, add, or remove these by editing the `theme.borderWidth` section of your Tailwind config. tailwind.config.js ``` module.exports = { theme: { borderWidth: { DEFAULT: '1px', '0': '0', '2': '2px', '3': '3px', '4': '4px', '6': '6px', '8': '8px', } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `border-{side}-{width}` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="border-t-[3px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/border-widthBorder Style ============ Utilities for controlling the style of an element's borders. Quick reference --------------- | Class | Properties | | --- | --- | | border-solid | border-style: solid; | | border-dashed | border-style: dashed; | | border-dotted | border-style: dotted; | | border-double | border-style: double; | | border-hidden | border-style: hidden; | | border-none | border-style: none; | Basic usage ----------- ### Setting the border style Use `border-{style}` to control an element’s border style. ``` <div class="border-solid border-2 border-indigo-600 ..."></div> <div class="border-dashed border-2 border-indigo-600 ..."></div> <div class="border-dotted border-2 border-indigo-600 ..."></div> <div class="border-double border-4 border-indigo-600 ..."></div><div class="border-solid border-2 border-sky-500 ..."></div> <div class="border-dashed border-2 border-sky-500 ..."></div> <div class="border-dotted border-2 border-sky-500 ..."></div> <div class="border-double border-4 border-sky-500 ..."></div> ``` ### No style Use `border-none` to remove an existing border style from an element. This is most commonly used to remove a border style that was applied at a smaller breakpoint. ``` <button class="border-none ...">Save Changes</button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:border-dotted` to only apply the `border-dotted` utility on hover. ``` <div class="border-solid hover:border-dotted"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:border-dotted` to apply the `border-dotted` utility at only medium screen sizes and above. ``` <div class="border-solid md:border-dotted"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/border-styleDivide Width ============ Utilities for controlling the border width between elements. Quick reference --------------- | Class | Properties | | --- | --- | | divide-x-0 > * + * | border-right-width: 0px; border-left-width: 0px; | | divide-x-2 > * + * | border-right-width: 0px; border-left-width: 2px; | | divide-x-4 > * + * | border-right-width: 0px; border-left-width: 4px; | | divide-x-8 > * + * | border-right-width: 0px; border-left-width: 8px; | | divide-x > * + * | border-right-width: 0px; border-left-width: 1px; | | divide-y-0 > * + * | border-top-width: 0px; border-bottom-width: 0px; | | divide-y-2 > * + * | border-top-width: 2px; border-bottom-width: 0px; | | divide-y-4 > * + * | border-top-width: 4px; border-bottom-width: 0px; | | divide-y-8 > * + * | border-top-width: 8px; border-bottom-width: 0px; | | divide-y > * + * | border-top-width: 1px; border-bottom-width: 0px; | | divide-y-reverse > * + * | --tw-divide-y-reverse: 1; | | divide-x-reverse > * + * | --tw-divide-x-reverse: 1; | Basic usage ----------- ### Add borders between horizontal children Add borders between horizontal elements using the `divide-x-{width}` utilities. ``` <div class="grid grid-cols-3 divide-x"> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Add borders between stacked children Add borders between stacked elements using the `divide-y-{width}` utilities. ``` <div class="grid grid-cols-1 divide-y"> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Reversing children order If your elements are in reverse order (using say `flex-row-reverse` or `flex-col-reverse`), use the `divide-x-reverse` or `divide-y-reverse` utilities to ensure the border is added to the correct side of each element. ``` <div class="flex flex-col-reverse divide-y divide-y-reverse"> <div>01</div> <div>02</div> <div>03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:divide-y-8` to only apply the `divide-y-8` utility on hover. ``` <div class="divide-y divide-gray-400 hover:divide-y-8"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:divide-y-8` to apply the `divide-y-8` utility at only medium screen sizes and above. ``` <div class="divide-y divide-gray-400 md:divide-y-8"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme The divide width scale inherits its values from the `borderWidth` scale by default, so if you’d like to customize your values for both border width and divide width together, use the `theme.borderWidth` section of your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { borderWidth: { DEFAULT: '1px', '0': '0', '2': '2px', '3': '3px', '4': '4px', '6': '6px', '8': '8px', } } } ``` To customize only the divide width values, use the `theme.divideWidth` section of your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { divideWidth: { DEFAULT: '1px', '0': '0', '2': '2px', '3': '3px', '4': '4px', '6': '6px', '8': '8px', } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `divide-{x|y}-{width}` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="divide-x-[3px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/divide-widthDivide Color ============ Utilities for controlling the border color between elements. Quick reference --------------- | Class | Properties | Preview | | --- | --- | --- | | divide-inherit > * + * | border-color: inherit; | | | divide-current > * + * | border-color: currentColor; | | | divide-transparent > * + * | border-color: transparent; | | | divide-black > * + * | border-color: rgb(0 0 0); | | | divide-white > * + * | border-color: rgb(255 255 255); | | | divide-slate-50 > * + * | border-color: rgb(248 250 252); | | | divide-slate-100 > * + * | border-color: rgb(241 245 249); | | | divide-slate-200 > * + * | border-color: rgb(226 232 240); | | | divide-slate-300 > * + * | border-color: rgb(203 213 225); | | | divide-slate-400 > * + * | border-color: rgb(148 163 184); | | | divide-slate-500 > * + * | border-color: rgb(100 116 139); | | | divide-slate-600 > * + * | border-color: rgb(71 85 105); | | | divide-slate-700 > * + * | border-color: rgb(51 65 85); | | | divide-slate-800 > * + * | border-color: rgb(30 41 59); | | | divide-slate-900 > * + * | border-color: rgb(15 23 42); | | | divide-slate-950 > * + * | border-color: rgb(2 6 23); | | | divide-gray-50 > * + * | border-color: rgb(249 250 251); | | | divide-gray-100 > * + * | border-color: rgb(243 244 246); | | | divide-gray-200 > * + * | border-color: rgb(229 231 235); | | | divide-gray-300 > * + * | border-color: rgb(209 213 219); | | | divide-gray-400 > * + * | border-color: rgb(156 163 175); | | | divide-gray-500 > * + * | border-color: rgb(107 114 128); | | | divide-gray-600 > * + * | border-color: rgb(75 85 99); | | | divide-gray-700 > * + * | border-color: rgb(55 65 81); | | | divide-gray-800 > * + * | border-color: rgb(31 41 55); | | | divide-gray-900 > * + * | border-color: rgb(17 24 39); | | | divide-gray-950 > * + * | border-color: rgb(3 7 18); | | | divide-zinc-50 > * + * | border-color: rgb(250 250 250); | | | divide-zinc-100 > * + * | border-color: rgb(244 244 245); | | | divide-zinc-200 > * + * | border-color: rgb(228 228 231); | | | divide-zinc-300 > * + * | border-color: rgb(212 212 216); | | | divide-zinc-400 > * + * | border-color: rgb(161 161 170); | | | divide-zinc-500 > * + * | border-color: rgb(113 113 122); | | | divide-zinc-600 > * + * | border-color: rgb(82 82 91); | | | divide-zinc-700 > * + * | border-color: rgb(63 63 70); | | | divide-zinc-800 > * + * | border-color: rgb(39 39 42); | | | divide-zinc-900 > * + * | border-color: rgb(24 24 27); | | | divide-zinc-950 > * + * | border-color: rgb(9 9 11); | | | divide-neutral-50 > * + * | border-color: rgb(250 250 250); | | | divide-neutral-100 > * + * | border-color: rgb(245 245 245); | | | divide-neutral-200 > * + * | border-color: rgb(229 229 229); | | | divide-neutral-300 > * + * | border-color: rgb(212 212 212); | | | divide-neutral-400 > * + * | border-color: rgb(163 163 163); | | | divide-neutral-500 > * + * | border-color: rgb(115 115 115); | | | divide-neutral-600 > * + * | border-color: rgb(82 82 82); | | | divide-neutral-700 > * + * | border-color: rgb(64 64 64); | | | divide-neutral-800 > * + * | border-color: rgb(38 38 38); | | | divide-neutral-900 > * + * | border-color: rgb(23 23 23); | | | divide-neutral-950 > * + * | border-color: rgb(10 10 10); | | | divide-stone-50 > * + * | border-color: rgb(250 250 249); | | | divide-stone-100 > * + * | border-color: rgb(245 245 244); | | | divide-stone-200 > * + * | border-color: rgb(231 229 228); | | | divide-stone-300 > * + * | border-color: rgb(214 211 209); | | | divide-stone-400 > * + * | border-color: rgb(168 162 158); | | | divide-stone-500 > * + * | border-color: rgb(120 113 108); | | | divide-stone-600 > * + * | border-color: rgb(87 83 78); | | | divide-stone-700 > * + * | border-color: rgb(68 64 60); | | | divide-stone-800 > * + * | border-color: rgb(41 37 36); | | | divide-stone-900 > * + * | border-color: rgb(28 25 23); | | | divide-stone-950 > * + * | border-color: rgb(12 10 9); | | | divide-red-50 > * + * | border-color: rgb(254 242 242); | | | divide-red-100 > * + * | border-color: rgb(254 226 226); | | | divide-red-200 > * + * | border-color: rgb(254 202 202); | | | divide-red-300 > * + * | border-color: rgb(252 165 165); | | | divide-red-400 > * + * | border-color: rgb(248 113 113); | | | divide-red-500 > * + * | border-color: rgb(239 68 68); | | | divide-red-600 > * + * | border-color: rgb(220 38 38); | | | divide-red-700 > * + * | border-color: rgb(185 28 28); | | | divide-red-800 > * + * | border-color: rgb(153 27 27); | | | divide-red-900 > * + * | border-color: rgb(127 29 29); | | | divide-red-950 > * + * | border-color: rgb(69 10 10); | | | divide-orange-50 > * + * | border-color: rgb(255 247 237); | | | divide-orange-100 > * + * | border-color: rgb(255 237 213); | | | divide-orange-200 > * + * | border-color: rgb(254 215 170); | | | divide-orange-300 > * + * | border-color: rgb(253 186 116); | | | divide-orange-400 > * + * | border-color: rgb(251 146 60); | | | divide-orange-500 > * + * | border-color: rgb(249 115 22); | | | divide-orange-600 > * + * | border-color: rgb(234 88 12); | | | divide-orange-700 > * + * | border-color: rgb(194 65 12); | | | divide-orange-800 > * + * | border-color: rgb(154 52 18); | | | divide-orange-900 > * + * | border-color: rgb(124 45 18); | | | divide-orange-950 > * + * | border-color: rgb(67 20 7); | | | divide-amber-50 > * + * | border-color: rgb(255 251 235); | | | divide-amber-100 > * + * | border-color: rgb(254 243 199); | | | divide-amber-200 > * + * | border-color: rgb(253 230 138); | | | divide-amber-300 > * + * | border-color: rgb(252 211 77); | | | divide-amber-400 > * + * | border-color: rgb(251 191 36); | | | divide-amber-500 > * + * | border-color: rgb(245 158 11); | | | divide-amber-600 > * + * | border-color: rgb(217 119 6); | | | divide-amber-700 > * + * | border-color: rgb(180 83 9); | | | divide-amber-800 > * + * | border-color: rgb(146 64 14); | | | divide-amber-900 > * + * | border-color: rgb(120 53 15); | | | divide-amber-950 > * + * | border-color: rgb(69 26 3); | | | divide-yellow-50 > * + * | border-color: rgb(254 252 232); | | | divide-yellow-100 > * + * | border-color: rgb(254 249 195); | | | divide-yellow-200 > * + * | border-color: rgb(254 240 138); | | | divide-yellow-300 > * + * | border-color: rgb(253 224 71); | | | divide-yellow-400 > * + * | border-color: rgb(250 204 21); | | | divide-yellow-500 > * + * | border-color: rgb(234 179 8); | | | divide-yellow-600 > * + * | border-color: rgb(202 138 4); | | | divide-yellow-700 > * + * | border-color: rgb(161 98 7); | | | divide-yellow-800 > * + * | border-color: rgb(133 77 14); | | | divide-yellow-900 > * + * | border-color: rgb(113 63 18); | | | divide-yellow-950 > * + * | border-color: rgb(66 32 6); | | | divide-lime-50 > * + * | border-color: rgb(247 254 231); | | | divide-lime-100 > * + * | border-color: rgb(236 252 203); | | | divide-lime-200 > * + * | border-color: rgb(217 249 157); | | | divide-lime-300 > * + * | border-color: rgb(190 242 100); | | | divide-lime-400 > * + * | border-color: rgb(163 230 53); | | | divide-lime-500 > * + * | border-color: rgb(132 204 22); | | | divide-lime-600 > * + * | border-color: rgb(101 163 13); | | | divide-lime-700 > * + * | border-color: rgb(77 124 15); | | | divide-lime-800 > * + * | border-color: rgb(63 98 18); | | | divide-lime-900 > * + * | border-color: rgb(54 83 20); | | | divide-lime-950 > * + * | border-color: rgb(26 46 5); | | | divide-green-50 > * + * | border-color: rgb(240 253 244); | | | divide-green-100 > * + * | border-color: rgb(220 252 231); | | | divide-green-200 > * + * | border-color: rgb(187 247 208); | | | divide-green-300 > * + * | border-color: rgb(134 239 172); | | | divide-green-400 > * + * | border-color: rgb(74 222 128); | | | divide-green-500 > * + * | border-color: rgb(34 197 94); | | | divide-green-600 > * + * | border-color: rgb(22 163 74); | | | divide-green-700 > * + * | border-color: rgb(21 128 61); | | | divide-green-800 > * + * | border-color: rgb(22 101 52); | | | divide-green-900 > * + * | border-color: rgb(20 83 45); | | | divide-green-950 > * + * | border-color: rgb(5 46 22); | | | divide-emerald-50 > * + * | border-color: rgb(236 253 245); | | | divide-emerald-100 > * + * | border-color: rgb(209 250 229); | | | divide-emerald-200 > * + * | border-color: rgb(167 243 208); | | | divide-emerald-300 > * + * | border-color: rgb(110 231 183); | | | divide-emerald-400 > * + * | border-color: rgb(52 211 153); | | | divide-emerald-500 > * + * | border-color: rgb(16 185 129); | | | divide-emerald-600 > * + * | border-color: rgb(5 150 105); | | | divide-emerald-700 > * + * | border-color: rgb(4 120 87); | | | divide-emerald-800 > * + * | border-color: rgb(6 95 70); | | | divide-emerald-900 > * + * | border-color: rgb(6 78 59); | | | divide-emerald-950 > * + * | border-color: rgb(2 44 34); | | | divide-teal-50 > * + * | border-color: rgb(240 253 250); | | | divide-teal-100 > * + * | border-color: rgb(204 251 241); | | | divide-teal-200 > * + * | border-color: rgb(153 246 228); | | | divide-teal-300 > * + * | border-color: rgb(94 234 212); | | | divide-teal-400 > * + * | border-color: rgb(45 212 191); | | | divide-teal-500 > * + * | border-color: rgb(20 184 166); | | | divide-teal-600 > * + * | border-color: rgb(13 148 136); | | | divide-teal-700 > * + * | border-color: rgb(15 118 110); | | | divide-teal-800 > * + * | border-color: rgb(17 94 89); | | | divide-teal-900 > * + * | border-color: rgb(19 78 74); | | | divide-teal-950 > * + * | border-color: rgb(4 47 46); | | | divide-cyan-50 > * + * | border-color: rgb(236 254 255); | | | divide-cyan-100 > * + * | border-color: rgb(207 250 254); | | | divide-cyan-200 > * + * | border-color: rgb(165 243 252); | | | divide-cyan-300 > * + * | border-color: rgb(103 232 249); | | | divide-cyan-400 > * + * | border-color: rgb(34 211 238); | | | divide-cyan-500 > * + * | border-color: rgb(6 182 212); | | | divide-cyan-600 > * + * | border-color: rgb(8 145 178); | | | divide-cyan-700 > * + * | border-color: rgb(14 116 144); | | | divide-cyan-800 > * + * | border-color: rgb(21 94 117); | | | divide-cyan-900 > * + * | border-color: rgb(22 78 99); | | | divide-cyan-950 > * + * | border-color: rgb(8 51 68); | | | divide-sky-50 > * + * | border-color: rgb(240 249 255); | | | divide-sky-100 > * + * | border-color: rgb(224 242 254); | | | divide-sky-200 > * + * | border-color: rgb(186 230 253); | | | divide-sky-300 > * + * | border-color: rgb(125 211 252); | | | divide-sky-400 > * + * | border-color: rgb(56 189 248); | | | divide-sky-500 > * + * | border-color: rgb(14 165 233); | | | divide-sky-600 > * + * | border-color: rgb(2 132 199); | | | divide-sky-700 > * + * | border-color: rgb(3 105 161); | | | divide-sky-800 > * + * | border-color: rgb(7 89 133); | | | divide-sky-900 > * + * | border-color: rgb(12 74 110); | | | divide-sky-950 > * + * | border-color: rgb(8 47 73); | | | divide-blue-50 > * + * | border-color: rgb(239 246 255); | | | divide-blue-100 > * + * | border-color: rgb(219 234 254); | | | divide-blue-200 > * + * | border-color: rgb(191 219 254); | | | divide-blue-300 > * + * | border-color: rgb(147 197 253); | | | divide-blue-400 > * + * | border-color: rgb(96 165 250); | | | divide-blue-500 > * + * | border-color: rgb(59 130 246); | | | divide-blue-600 > * + * | border-color: rgb(37 99 235); | | | divide-blue-700 > * + * | border-color: rgb(29 78 216); | | | divide-blue-800 > * + * | border-color: rgb(30 64 175); | | | divide-blue-900 > * + * | border-color: rgb(30 58 138); | | | divide-blue-950 > * + * | border-color: rgb(23 37 84); | | | divide-indigo-50 > * + * | border-color: rgb(238 242 255); | | | divide-indigo-100 > * + * | border-color: rgb(224 231 255); | | | divide-indigo-200 > * + * | border-color: rgb(199 210 254); | | | divide-indigo-300 > * + * | border-color: rgb(165 180 252); | | | divide-indigo-400 > * + * | border-color: rgb(129 140 248); | | | divide-indigo-500 > * + * | border-color: rgb(99 102 241); | | | divide-indigo-600 > * + * | border-color: rgb(79 70 229); | | | divide-indigo-700 > * + * | border-color: rgb(67 56 202); | | | divide-indigo-800 > * + * | border-color: rgb(55 48 163); | | | divide-indigo-900 > * + * | border-color: rgb(49 46 129); | | | divide-indigo-950 > * + * | border-color: rgb(30 27 75); | | | divide-violet-50 > * + * | border-color: rgb(245 243 255); | | | divide-violet-100 > * + * | border-color: rgb(237 233 254); | | | divide-violet-200 > * + * | border-color: rgb(221 214 254); | | | divide-violet-300 > * + * | border-color: rgb(196 181 253); | | | divide-violet-400 > * + * | border-color: rgb(167 139 250); | | | divide-violet-500 > * + * | border-color: rgb(139 92 246); | | | divide-violet-600 > * + * | border-color: rgb(124 58 237); | | | divide-violet-700 > * + * | border-color: rgb(109 40 217); | | | divide-violet-800 > * + * | border-color: rgb(91 33 182); | | | divide-violet-900 > * + * | border-color: rgb(76 29 149); | | | divide-violet-950 > * + * | border-color: rgb(46 16 101); | | | divide-purple-50 > * + * | border-color: rgb(250 245 255); | | | divide-purple-100 > * + * | border-color: rgb(243 232 255); | | | divide-purple-200 > * + * | border-color: rgb(233 213 255); | | | divide-purple-300 > * + * | border-color: rgb(216 180 254); | | | divide-purple-400 > * + * | border-color: rgb(192 132 252); | | | divide-purple-500 > * + * | border-color: rgb(168 85 247); | | | divide-purple-600 > * + * | border-color: rgb(147 51 234); | | | divide-purple-700 > * + * | border-color: rgb(126 34 206); | | | divide-purple-800 > * + * | border-color: rgb(107 33 168); | | | divide-purple-900 > * + * | border-color: rgb(88 28 135); | | | divide-purple-950 > * + * | border-color: rgb(59 7 100); | | | divide-fuchsia-50 > * + * | border-color: rgb(253 244 255); | | | divide-fuchsia-100 > * + * | border-color: rgb(250 232 255); | | | divide-fuchsia-200 > * + * | border-color: rgb(245 208 254); | | | divide-fuchsia-300 > * + * | border-color: rgb(240 171 252); | | | divide-fuchsia-400 > * + * | border-color: rgb(232 121 249); | | | divide-fuchsia-500 > * + * | border-color: rgb(217 70 239); | | | divide-fuchsia-600 > * + * | border-color: rgb(192 38 211); | | | divide-fuchsia-700 > * + * | border-color: rgb(162 28 175); | | | divide-fuchsia-800 > * + * | border-color: rgb(134 25 143); | | | divide-fuchsia-900 > * + * | border-color: rgb(112 26 117); | | | divide-fuchsia-950 > * + * | border-color: rgb(74 4 78); | | | divide-pink-50 > * + * | border-color: rgb(253 242 248); | | | divide-pink-100 > * + * | border-color: rgb(252 231 243); | | | divide-pink-200 > * + * | border-color: rgb(251 207 232); | | | divide-pink-300 > * + * | border-color: rgb(249 168 212); | | | divide-pink-400 > * + * | border-color: rgb(244 114 182); | | | divide-pink-500 > * + * | border-color: rgb(236 72 153); | | | divide-pink-600 > * + * | border-color: rgb(219 39 119); | | | divide-pink-700 > * + * | border-color: rgb(190 24 93); | | | divide-pink-800 > * + * | border-color: rgb(157 23 77); | | | divide-pink-900 > * + * | border-color: rgb(131 24 67); | | | divide-pink-950 > * + * | border-color: rgb(80 7 36); | | | divide-rose-50 > * + * | border-color: rgb(255 241 242); | | | divide-rose-100 > * + * | border-color: rgb(255 228 230); | | | divide-rose-200 > * + * | border-color: rgb(254 205 211); | | | divide-rose-300 > * + * | border-color: rgb(253 164 175); | | | divide-rose-400 > * + * | border-color: rgb(251 113 133); | | | divide-rose-500 > * + * | border-color: rgb(244 63 94); | | | divide-rose-600 > * + * | border-color: rgb(225 29 72); | | | divide-rose-700 > * + * | border-color: rgb(190 18 60); | | | divide-rose-800 > * + * | border-color: rgb(159 18 57); | | | divide-rose-900 > * + * | border-color: rgb(136 19 55); | | | divide-rose-950 > * + * | border-color: rgb(76 5 25); | | Basic usage ----------- ### Setting the divide color Control the border color between elements using the `divide-{color}` utilities. ``` <div class="divide-y divide-blue-200"> <div>01</div> <div>02</div> <div>03</div> </div> ``` ### Changing the opacity Control the opacity of the divide color using the color opacity modifier. ``` <div class="divide-y-4 divide-slate-400/25 ..."> <!-- ... --> </div> ``` You can use any value defined in your [opacity scale](opacity), or use arbitrary values if you need to deviate from your design tokens. ``` <div class="divide-y-4 divide-slate-400/[.24] ..."> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:divide-pink-400` to only apply the `divide-pink-400` utility on hover. ``` <div class="divide-y divide-teal-400 hover:divide-pink-400"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:divide-pink-400` to apply the `divide-pink-400` utility at only medium screen sizes and above. ``` <div class="divide-y divide-teal-400 md:divide-pink-400"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as divide colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your divide colors by editing `theme.divideColor` or `theme.extend.divideColor` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `divide-{color}` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="divide-[#243c5a]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/divide-colorDivide Style ============ Utilities for controlling the border style between elements. Quick reference --------------- | Class | Properties | | --- | --- | | divide-solid > * + * | border-style: solid; | | divide-dashed > * + * | border-style: dashed; | | divide-dotted > * + * | border-style: dotted; | | divide-double > * + * | border-style: double; | | divide-none > * + * | border-style: none; | Basic usage ----------- ### Set the divide style Control the border style between elements using the `divide-{style}` utilities. ``` <div class="divide-y divide-dashed"> <div>01</div> <div>02</div> <div>03</div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:divide-solid` to only apply the `divide-solid` utility on hover. ``` <div class="divide-y divide-dashed hover:divide-solid"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:divide-solid` to apply the `divide-solid` utility at only medium screen sizes and above. ``` <div class="divide-y divide-dashed md:divide-solid"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/divide-styleOutline Width ============= Utilities for controlling the width of an element's outline. Quick reference --------------- | Class | Properties | | --- | --- | | outline-0 | outline-width: 0px; | | outline-1 | outline-width: 1px; | | outline-2 | outline-width: 2px; | | outline-4 | outline-width: 4px; | | outline-8 | outline-width: 8px; | Basic usage ----------- ### Setting the outline width Use the `outline-{width}` utilities to change the width of an element’s outline. ``` <button class="outline outline-offset-2 outline-1 ...">Button A</button> <button class="outline outline-offset-2 outline-2 ...">Button B</button> <button class="outline outline-offset-2 outline-4 ...">Button C</button> ``` The default outline width is `3px`. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:outline-2` to only apply the `outline-2` utility on hover. ``` <div class="outline hover:outline-2"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:outline-2` to apply the `outline-2` utility at only medium screen sizes and above. ``` <div class="outline md:outline-2"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme You can customize the `outline-{width}` utilities by editing `theme.outlineWidth` or `theme.extend.outlineWidth` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { outlineWidth: { 5: '5px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `outline-width` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="outline-[5px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/outline-widthOutline Color ============= Utilities for controlling the color of an element's outline. Quick reference --------------- | Class | Properties | | --- | --- | | outline-inherit | outline-color: inherit; | | outline-current | outline-color: currentColor; | | outline-transparent | outline-color: transparent; | | outline-black | outline-color: #000; | | outline-white | outline-color: #fff; | | outline-slate-50 | outline-color: #f8fafc; | | outline-slate-100 | outline-color: #f1f5f9; | | outline-slate-200 | outline-color: #e2e8f0; | | outline-slate-300 | outline-color: #cbd5e1; | | outline-slate-400 | outline-color: #94a3b8; | | outline-slate-500 | outline-color: #64748b; | | outline-slate-600 | outline-color: #475569; | | outline-slate-700 | outline-color: #334155; | | outline-slate-800 | outline-color: #1e293b; | | outline-slate-900 | outline-color: #0f172a; | | outline-slate-950 | outline-color: #020617; | | outline-gray-50 | outline-color: #f9fafb; | | outline-gray-100 | outline-color: #f3f4f6; | | outline-gray-200 | outline-color: #e5e7eb; | | outline-gray-300 | outline-color: #d1d5db; | | outline-gray-400 | outline-color: #9ca3af; | | outline-gray-500 | outline-color: #6b7280; | | outline-gray-600 | outline-color: #4b5563; | | outline-gray-700 | outline-color: #374151; | | outline-gray-800 | outline-color: #1f2937; | | outline-gray-900 | outline-color: #111827; | | outline-gray-950 | outline-color: #030712; | | outline-zinc-50 | outline-color: #fafafa; | | outline-zinc-100 | outline-color: #f4f4f5; | | outline-zinc-200 | outline-color: #e4e4e7; | | outline-zinc-300 | outline-color: #d4d4d8; | | outline-zinc-400 | outline-color: #a1a1aa; | | outline-zinc-500 | outline-color: #71717a; | | outline-zinc-600 | outline-color: #52525b; | | outline-zinc-700 | outline-color: #3f3f46; | | outline-zinc-800 | outline-color: #27272a; | | outline-zinc-900 | outline-color: #18181b; | | outline-zinc-950 | outline-color: #09090b; | | outline-neutral-50 | outline-color: #fafafa; | | outline-neutral-100 | outline-color: #f5f5f5; | | outline-neutral-200 | outline-color: #e5e5e5; | | outline-neutral-300 | outline-color: #d4d4d4; | | outline-neutral-400 | outline-color: #a3a3a3; | | outline-neutral-500 | outline-color: #737373; | | outline-neutral-600 | outline-color: #525252; | | outline-neutral-700 | outline-color: #404040; | | outline-neutral-800 | outline-color: #262626; | | outline-neutral-900 | outline-color: #171717; | | outline-neutral-950 | outline-color: #0a0a0a; | | outline-stone-50 | outline-color: #fafaf9; | | outline-stone-100 | outline-color: #f5f5f4; | | outline-stone-200 | outline-color: #e7e5e4; | | outline-stone-300 | outline-color: #d6d3d1; | | outline-stone-400 | outline-color: #a8a29e; | | outline-stone-500 | outline-color: #78716c; | | outline-stone-600 | outline-color: #57534e; | | outline-stone-700 | outline-color: #44403c; | | outline-stone-800 | outline-color: #292524; | | outline-stone-900 | outline-color: #1c1917; | | outline-stone-950 | outline-color: #0c0a09; | | outline-red-50 | outline-color: #fef2f2; | | outline-red-100 | outline-color: #fee2e2; | | outline-red-200 | outline-color: #fecaca; | | outline-red-300 | outline-color: #fca5a5; | | outline-red-400 | outline-color: #f87171; | | outline-red-500 | outline-color: #ef4444; | | outline-red-600 | outline-color: #dc2626; | | outline-red-700 | outline-color: #b91c1c; | | outline-red-800 | outline-color: #991b1b; | | outline-red-900 | outline-color: #7f1d1d; | | outline-red-950 | outline-color: #450a0a; | | outline-orange-50 | outline-color: #fff7ed; | | outline-orange-100 | outline-color: #ffedd5; | | outline-orange-200 | outline-color: #fed7aa; | | outline-orange-300 | outline-color: #fdba74; | | outline-orange-400 | outline-color: #fb923c; | | outline-orange-500 | outline-color: #f97316; | | outline-orange-600 | outline-color: #ea580c; | | outline-orange-700 | outline-color: #c2410c; | | outline-orange-800 | outline-color: #9a3412; | | outline-orange-900 | outline-color: #7c2d12; | | outline-orange-950 | outline-color: #431407; | | outline-amber-50 | outline-color: #fffbeb; | | outline-amber-100 | outline-color: #fef3c7; | | outline-amber-200 | outline-color: #fde68a; | | outline-amber-300 | outline-color: #fcd34d; | | outline-amber-400 | outline-color: #fbbf24; | | outline-amber-500 | outline-color: #f59e0b; | | outline-amber-600 | outline-color: #d97706; | | outline-amber-700 | outline-color: #b45309; | | outline-amber-800 | outline-color: #92400e; | | outline-amber-900 | outline-color: #78350f; | | outline-amber-950 | outline-color: #451a03; | | outline-yellow-50 | outline-color: #fefce8; | | outline-yellow-100 | outline-color: #fef9c3; | | outline-yellow-200 | outline-color: #fef08a; | | outline-yellow-300 | outline-color: #fde047; | | outline-yellow-400 | outline-color: #facc15; | | outline-yellow-500 | outline-color: #eab308; | | outline-yellow-600 | outline-color: #ca8a04; | | outline-yellow-700 | outline-color: #a16207; | | outline-yellow-800 | outline-color: #854d0e; | | outline-yellow-900 | outline-color: #713f12; | | outline-yellow-950 | outline-color: #422006; | | outline-lime-50 | outline-color: #f7fee7; | | outline-lime-100 | outline-color: #ecfccb; | | outline-lime-200 | outline-color: #d9f99d; | | outline-lime-300 | outline-color: #bef264; | | outline-lime-400 | outline-color: #a3e635; | | outline-lime-500 | outline-color: #84cc16; | | outline-lime-600 | outline-color: #65a30d; | | outline-lime-700 | outline-color: #4d7c0f; | | outline-lime-800 | outline-color: #3f6212; | | outline-lime-900 | outline-color: #365314; | | outline-lime-950 | outline-color: #1a2e05; | | outline-green-50 | outline-color: #f0fdf4; | | outline-green-100 | outline-color: #dcfce7; | | outline-green-200 | outline-color: #bbf7d0; | | outline-green-300 | outline-color: #86efac; | | outline-green-400 | outline-color: #4ade80; | | outline-green-500 | outline-color: #22c55e; | | outline-green-600 | outline-color: #16a34a; | | outline-green-700 | outline-color: #15803d; | | outline-green-800 | outline-color: #166534; | | outline-green-900 | outline-color: #14532d; | | outline-green-950 | outline-color: #052e16; | | outline-emerald-50 | outline-color: #ecfdf5; | | outline-emerald-100 | outline-color: #d1fae5; | | outline-emerald-200 | outline-color: #a7f3d0; | | outline-emerald-300 | outline-color: #6ee7b7; | | outline-emerald-400 | outline-color: #34d399; | | outline-emerald-500 | outline-color: #10b981; | | outline-emerald-600 | outline-color: #059669; | | outline-emerald-700 | outline-color: #047857; | | outline-emerald-800 | outline-color: #065f46; | | outline-emerald-900 | outline-color: #064e3b; | | outline-emerald-950 | outline-color: #022c22; | | outline-teal-50 | outline-color: #f0fdfa; | | outline-teal-100 | outline-color: #ccfbf1; | | outline-teal-200 | outline-color: #99f6e4; | | outline-teal-300 | outline-color: #5eead4; | | outline-teal-400 | outline-color: #2dd4bf; | | outline-teal-500 | outline-color: #14b8a6; | | outline-teal-600 | outline-color: #0d9488; | | outline-teal-700 | outline-color: #0f766e; | | outline-teal-800 | outline-color: #115e59; | | outline-teal-900 | outline-color: #134e4a; | | outline-teal-950 | outline-color: #042f2e; | | outline-cyan-50 | outline-color: #ecfeff; | | outline-cyan-100 | outline-color: #cffafe; | | outline-cyan-200 | outline-color: #a5f3fc; | | outline-cyan-300 | outline-color: #67e8f9; | | outline-cyan-400 | outline-color: #22d3ee; | | outline-cyan-500 | outline-color: #06b6d4; | | outline-cyan-600 | outline-color: #0891b2; | | outline-cyan-700 | outline-color: #0e7490; | | outline-cyan-800 | outline-color: #155e75; | | outline-cyan-900 | outline-color: #164e63; | | outline-cyan-950 | outline-color: #083344; | | outline-sky-50 | outline-color: #f0f9ff; | | outline-sky-100 | outline-color: #e0f2fe; | | outline-sky-200 | outline-color: #bae6fd; | | outline-sky-300 | outline-color: #7dd3fc; | | outline-sky-400 | outline-color: #38bdf8; | | outline-sky-500 | outline-color: #0ea5e9; | | outline-sky-600 | outline-color: #0284c7; | | outline-sky-700 | outline-color: #0369a1; | | outline-sky-800 | outline-color: #075985; | | outline-sky-900 | outline-color: #0c4a6e; | | outline-sky-950 | outline-color: #082f49; | | outline-blue-50 | outline-color: #eff6ff; | | outline-blue-100 | outline-color: #dbeafe; | | outline-blue-200 | outline-color: #bfdbfe; | | outline-blue-300 | outline-color: #93c5fd; | | outline-blue-400 | outline-color: #60a5fa; | | outline-blue-500 | outline-color: #3b82f6; | | outline-blue-600 | outline-color: #2563eb; | | outline-blue-700 | outline-color: #1d4ed8; | | outline-blue-800 | outline-color: #1e40af; | | outline-blue-900 | outline-color: #1e3a8a; | | outline-blue-950 | outline-color: #172554; | | outline-indigo-50 | outline-color: #eef2ff; | | outline-indigo-100 | outline-color: #e0e7ff; | | outline-indigo-200 | outline-color: #c7d2fe; | | outline-indigo-300 | outline-color: #a5b4fc; | | outline-indigo-400 | outline-color: #818cf8; | | outline-indigo-500 | outline-color: #6366f1; | | outline-indigo-600 | outline-color: #4f46e5; | | outline-indigo-700 | outline-color: #4338ca; | | outline-indigo-800 | outline-color: #3730a3; | | outline-indigo-900 | outline-color: #312e81; | | outline-indigo-950 | outline-color: #1e1b4b; | | outline-violet-50 | outline-color: #f5f3ff; | | outline-violet-100 | outline-color: #ede9fe; | | outline-violet-200 | outline-color: #ddd6fe; | | outline-violet-300 | outline-color: #c4b5fd; | | outline-violet-400 | outline-color: #a78bfa; | | outline-violet-500 | outline-color: #8b5cf6; | | outline-violet-600 | outline-color: #7c3aed; | | outline-violet-700 | outline-color: #6d28d9; | | outline-violet-800 | outline-color: #5b21b6; | | outline-violet-900 | outline-color: #4c1d95; | | outline-violet-950 | outline-color: #2e1065; | | outline-purple-50 | outline-color: #faf5ff; | | outline-purple-100 | outline-color: #f3e8ff; | | outline-purple-200 | outline-color: #e9d5ff; | | outline-purple-300 | outline-color: #d8b4fe; | | outline-purple-400 | outline-color: #c084fc; | | outline-purple-500 | outline-color: #a855f7; | | outline-purple-600 | outline-color: #9333ea; | | outline-purple-700 | outline-color: #7e22ce; | | outline-purple-800 | outline-color: #6b21a8; | | outline-purple-900 | outline-color: #581c87; | | outline-purple-950 | outline-color: #3b0764; | | outline-fuchsia-50 | outline-color: #fdf4ff; | | outline-fuchsia-100 | outline-color: #fae8ff; | | outline-fuchsia-200 | outline-color: #f5d0fe; | | outline-fuchsia-300 | outline-color: #f0abfc; | | outline-fuchsia-400 | outline-color: #e879f9; | | outline-fuchsia-500 | outline-color: #d946ef; | | outline-fuchsia-600 | outline-color: #c026d3; | | outline-fuchsia-700 | outline-color: #a21caf; | | outline-fuchsia-800 | outline-color: #86198f; | | outline-fuchsia-900 | outline-color: #701a75; | | outline-fuchsia-950 | outline-color: #4a044e; | | outline-pink-50 | outline-color: #fdf2f8; | | outline-pink-100 | outline-color: #fce7f3; | | outline-pink-200 | outline-color: #fbcfe8; | | outline-pink-300 | outline-color: #f9a8d4; | | outline-pink-400 | outline-color: #f472b6; | | outline-pink-500 | outline-color: #ec4899; | | outline-pink-600 | outline-color: #db2777; | | outline-pink-700 | outline-color: #be185d; | | outline-pink-800 | outline-color: #9d174d; | | outline-pink-900 | outline-color: #831843; | | outline-pink-950 | outline-color: #500724; | | outline-rose-50 | outline-color: #fff1f2; | | outline-rose-100 | outline-color: #ffe4e6; | | outline-rose-200 | outline-color: #fecdd3; | | outline-rose-300 | outline-color: #fda4af; | | outline-rose-400 | outline-color: #fb7185; | | outline-rose-500 | outline-color: #f43f5e; | | outline-rose-600 | outline-color: #e11d48; | | outline-rose-700 | outline-color: #be123c; | | outline-rose-800 | outline-color: #9f1239; | | outline-rose-900 | outline-color: #881337; | | outline-rose-950 | outline-color: #4c0519; | Basic usage ----------- ### Setting the outline color Use the `outline-{color}` utilities to change the color of an element’s outline. ``` <button class="outline outline-offset-2 outline-blue-500 ...">Button A</button> <button class="outline outline-offset-2 outline-cyan-500 ...">Button B</button> <button class="outline outline-offset-2 outline-pink-500 ...">Button C</button> ``` ### Changing the opacity Control the opacity of an element’s outline color using the color opacity modifier. ``` <button class="outline-2 outline-blue-500/50 ...">Save Changes</button> ``` You can use any value defined in your [opacity scale](opacity), or use arbitrary values if you need to deviate from your design tokens. ``` <button class="outline-4 outline-pink-400/[.55] ..."></button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:outline-blue-400` to only apply the `outline-blue-400` utility on hover. ``` <button class="outline hover:outline-blue-400"> <!-- ... --> </button``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:outline-blue-400` to apply the `outline-blue-400` utility at only medium screen sizes and above. ``` <button class="outline md:outline-blue-400"> <!-- ... --> </button``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as outline colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your outline colors by editing `theme.outlineColor` or `theme.extend.outlineColor` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `outline-color` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <button class="outline-[#243c5a]"> <!-- ... --> </button``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/outline-colorOutline Style ============= Utilities for controlling the style of an element's outline. Quick reference --------------- | Class | Properties | | --- | --- | | outline-none | outline: 2px solid transparent; outline-offset: 2px; | | outline | outline-style: solid; | | outline-dashed | outline-style: dashed; | | outline-dotted | outline-style: dotted; | | outline-double | outline-style: double; | Basic usage ----------- ### Setting the outline style Use the `outline-{style}` utilities to change the style of an element’s outline. ``` <button class="outline outline-2 outline-offset-2 ...">Button A</button> <button class="outline-dashed outline-2 outline-offset-2 ...">Button B</button> <button class="outline-dotted outline-2 outline-offset-2 ...">Button C</button> <button class="outline-double outline-3 outline-offset-2 ...">Button D</button> ``` ### Removing outlines Use `outline-none` to hide the default browser outline on focused elements. It is highly recommended to apply your own focus styling for accessibility when using this utility. ``` <input type="text" placeholder="Default focus style" class="..." /<input type="text" placeholder="Custom focus style" class="focus:outline-none focus:ring focus:border-blue-500 ..." /> ``` The `outline-none` utility is implemented using a transparent outline under the hood to ensure elements are still visibly focused to [Windows high contrast mode](https://blogs.windows.com/msedgedev/2020/09/17/styling-for-windows-high-contrast-with-new-standards-for-forced-colors/) users. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:outline-dashed` to only apply the `outline-dashed` utility on hover. ``` <div class="outline hover:outline-dashed"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:outline-dashed` to apply the `outline-dashed` utility at only medium screen sizes and above. ``` <div class="outline md:outline-dashed"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/outline-styleGradient Color Stops ==================== Utilities for controlling the color stops in background gradients. Quick reference --------------- | Class | Properties | Preview | | --- | --- | --- | | from-inherit | --tw-gradient-from: inherit var(--tw-gradient-from-position); --tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-current | --tw-gradient-from: currentColor var(--tw-gradient-from-position); --tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-transparent | --tw-gradient-from: transparent var(--tw-gradient-from-position); --tw-gradient-to: rgb(0 0 0 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-black | --tw-gradient-from: #000 var(--tw-gradient-from-position); --tw-gradient-to: rgb(0 0 0 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-white | --tw-gradient-from: #fff var(--tw-gradient-from-position); --tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-slate-50 | --tw-gradient-from: #f8fafc var(--tw-gradient-from-position); --tw-gradient-to: rgb(248 250 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-slate-100 | --tw-gradient-from: #f1f5f9 var(--tw-gradient-from-position); --tw-gradient-to: rgb(241 245 249 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-slate-200 | --tw-gradient-from: #e2e8f0 var(--tw-gradient-from-position); --tw-gradient-to: rgb(226 232 240 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-slate-300 | --tw-gradient-from: #cbd5e1 var(--tw-gradient-from-position); --tw-gradient-to: rgb(203 213 225 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-slate-400 | --tw-gradient-from: #94a3b8 var(--tw-gradient-from-position); --tw-gradient-to: rgb(148 163 184 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-slate-500 | --tw-gradient-from: #64748b var(--tw-gradient-from-position); --tw-gradient-to: rgb(100 116 139 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-slate-600 | --tw-gradient-from: #475569 var(--tw-gradient-from-position); --tw-gradient-to: rgb(71 85 105 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-slate-700 | --tw-gradient-from: #334155 var(--tw-gradient-from-position); --tw-gradient-to: rgb(51 65 85 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-slate-800 | --tw-gradient-from: #1e293b var(--tw-gradient-from-position); --tw-gradient-to: rgb(30 41 59 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-slate-900 | --tw-gradient-from: #0f172a var(--tw-gradient-from-position); --tw-gradient-to: rgb(15 23 42 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-slate-950 | --tw-gradient-from: #020617 var(--tw-gradient-from-position); --tw-gradient-to: rgb(2 6 23 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-gray-50 | --tw-gradient-from: #f9fafb var(--tw-gradient-from-position); --tw-gradient-to: rgb(249 250 251 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-gray-100 | --tw-gradient-from: #f3f4f6 var(--tw-gradient-from-position); --tw-gradient-to: rgb(243 244 246 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-gray-200 | --tw-gradient-from: #e5e7eb var(--tw-gradient-from-position); --tw-gradient-to: rgb(229 231 235 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-gray-300 | --tw-gradient-from: #d1d5db var(--tw-gradient-from-position); --tw-gradient-to: rgb(209 213 219 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-gray-400 | --tw-gradient-from: #9ca3af var(--tw-gradient-from-position); --tw-gradient-to: rgb(156 163 175 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-gray-500 | --tw-gradient-from: #6b7280 var(--tw-gradient-from-position); --tw-gradient-to: rgb(107 114 128 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-gray-600 | --tw-gradient-from: #4b5563 var(--tw-gradient-from-position); --tw-gradient-to: rgb(75 85 99 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-gray-700 | --tw-gradient-from: #374151 var(--tw-gradient-from-position); --tw-gradient-to: rgb(55 65 81 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-gray-800 | --tw-gradient-from: #1f2937 var(--tw-gradient-from-position); --tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-gray-900 | --tw-gradient-from: #111827 var(--tw-gradient-from-position); --tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-gray-950 | --tw-gradient-from: #030712 var(--tw-gradient-from-position); --tw-gradient-to: rgb(3 7 18 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-zinc-50 | --tw-gradient-from: #fafafa var(--tw-gradient-from-position); --tw-gradient-to: rgb(250 250 250 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-zinc-100 | --tw-gradient-from: #f4f4f5 var(--tw-gradient-from-position); --tw-gradient-to: rgb(244 244 245 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-zinc-200 | --tw-gradient-from: #e4e4e7 var(--tw-gradient-from-position); --tw-gradient-to: rgb(228 228 231 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-zinc-300 | --tw-gradient-from: #d4d4d8 var(--tw-gradient-from-position); --tw-gradient-to: rgb(212 212 216 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-zinc-400 | --tw-gradient-from: #a1a1aa var(--tw-gradient-from-position); --tw-gradient-to: rgb(161 161 170 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-zinc-500 | --tw-gradient-from: #71717a var(--tw-gradient-from-position); --tw-gradient-to: rgb(113 113 122 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-zinc-600 | --tw-gradient-from: #52525b var(--tw-gradient-from-position); --tw-gradient-to: rgb(82 82 91 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-zinc-700 | --tw-gradient-from: #3f3f46 var(--tw-gradient-from-position); --tw-gradient-to: rgb(63 63 70 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-zinc-800 | --tw-gradient-from: #27272a var(--tw-gradient-from-position); --tw-gradient-to: rgb(39 39 42 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-zinc-900 | --tw-gradient-from: #18181b var(--tw-gradient-from-position); --tw-gradient-to: rgb(24 24 27 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-zinc-950 | --tw-gradient-from: #09090b var(--tw-gradient-from-position); --tw-gradient-to: rgb(9 9 11 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-neutral-50 | --tw-gradient-from: #fafafa var(--tw-gradient-from-position); --tw-gradient-to: rgb(250 250 250 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-neutral-100 | --tw-gradient-from: #f5f5f5 var(--tw-gradient-from-position); --tw-gradient-to: rgb(245 245 245 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-neutral-200 | --tw-gradient-from: #e5e5e5 var(--tw-gradient-from-position); --tw-gradient-to: rgb(229 229 229 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-neutral-300 | --tw-gradient-from: #d4d4d4 var(--tw-gradient-from-position); --tw-gradient-to: rgb(212 212 212 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-neutral-400 | --tw-gradient-from: #a3a3a3 var(--tw-gradient-from-position); --tw-gradient-to: rgb(163 163 163 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-neutral-500 | --tw-gradient-from: #737373 var(--tw-gradient-from-position); --tw-gradient-to: rgb(115 115 115 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-neutral-600 | --tw-gradient-from: #525252 var(--tw-gradient-from-position); --tw-gradient-to: rgb(82 82 82 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-neutral-700 | --tw-gradient-from: #404040 var(--tw-gradient-from-position); --tw-gradient-to: rgb(64 64 64 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-neutral-800 | --tw-gradient-from: #262626 var(--tw-gradient-from-position); --tw-gradient-to: rgb(38 38 38 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-neutral-900 | --tw-gradient-from: #171717 var(--tw-gradient-from-position); --tw-gradient-to: rgb(23 23 23 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-neutral-950 | --tw-gradient-from: #0a0a0a var(--tw-gradient-from-position); --tw-gradient-to: rgb(10 10 10 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-stone-50 | --tw-gradient-from: #fafaf9 var(--tw-gradient-from-position); --tw-gradient-to: rgb(250 250 249 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-stone-100 | --tw-gradient-from: #f5f5f4 var(--tw-gradient-from-position); --tw-gradient-to: rgb(245 245 244 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-stone-200 | --tw-gradient-from: #e7e5e4 var(--tw-gradient-from-position); --tw-gradient-to: rgb(231 229 228 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-stone-300 | --tw-gradient-from: #d6d3d1 var(--tw-gradient-from-position); --tw-gradient-to: rgb(214 211 209 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-stone-400 | --tw-gradient-from: #a8a29e var(--tw-gradient-from-position); --tw-gradient-to: rgb(168 162 158 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-stone-500 | --tw-gradient-from: #78716c var(--tw-gradient-from-position); --tw-gradient-to: rgb(120 113 108 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-stone-600 | --tw-gradient-from: #57534e var(--tw-gradient-from-position); --tw-gradient-to: rgb(87 83 78 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-stone-700 | --tw-gradient-from: #44403c var(--tw-gradient-from-position); --tw-gradient-to: rgb(68 64 60 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-stone-800 | --tw-gradient-from: #292524 var(--tw-gradient-from-position); --tw-gradient-to: rgb(41 37 36 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-stone-900 | --tw-gradient-from: #1c1917 var(--tw-gradient-from-position); --tw-gradient-to: rgb(28 25 23 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-stone-950 | --tw-gradient-from: #0c0a09 var(--tw-gradient-from-position); --tw-gradient-to: rgb(12 10 9 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-red-50 | --tw-gradient-from: #fef2f2 var(--tw-gradient-from-position); --tw-gradient-to: rgb(254 242 242 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-red-100 | --tw-gradient-from: #fee2e2 var(--tw-gradient-from-position); --tw-gradient-to: rgb(254 226 226 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-red-200 | --tw-gradient-from: #fecaca var(--tw-gradient-from-position); --tw-gradient-to: rgb(254 202 202 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-red-300 | --tw-gradient-from: #fca5a5 var(--tw-gradient-from-position); --tw-gradient-to: rgb(252 165 165 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-red-400 | --tw-gradient-from: #f87171 var(--tw-gradient-from-position); --tw-gradient-to: rgb(248 113 113 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-red-500 | --tw-gradient-from: #ef4444 var(--tw-gradient-from-position); --tw-gradient-to: rgb(239 68 68 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-red-600 | --tw-gradient-from: #dc2626 var(--tw-gradient-from-position); --tw-gradient-to: rgb(220 38 38 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-red-700 | --tw-gradient-from: #b91c1c var(--tw-gradient-from-position); --tw-gradient-to: rgb(185 28 28 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-red-800 | --tw-gradient-from: #991b1b var(--tw-gradient-from-position); --tw-gradient-to: rgb(153 27 27 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-red-900 | --tw-gradient-from: #7f1d1d var(--tw-gradient-from-position); --tw-gradient-to: rgb(127 29 29 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-red-950 | --tw-gradient-from: #450a0a var(--tw-gradient-from-position); --tw-gradient-to: rgb(69 10 10 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-orange-50 | --tw-gradient-from: #fff7ed var(--tw-gradient-from-position); --tw-gradient-to: rgb(255 247 237 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-orange-100 | --tw-gradient-from: #ffedd5 var(--tw-gradient-from-position); --tw-gradient-to: rgb(255 237 213 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-orange-200 | --tw-gradient-from: #fed7aa var(--tw-gradient-from-position); --tw-gradient-to: rgb(254 215 170 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-orange-300 | --tw-gradient-from: #fdba74 var(--tw-gradient-from-position); --tw-gradient-to: rgb(253 186 116 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-orange-400 | --tw-gradient-from: #fb923c var(--tw-gradient-from-position); --tw-gradient-to: rgb(251 146 60 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-orange-500 | --tw-gradient-from: #f97316 var(--tw-gradient-from-position); --tw-gradient-to: rgb(249 115 22 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-orange-600 | --tw-gradient-from: #ea580c var(--tw-gradient-from-position); --tw-gradient-to: rgb(234 88 12 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-orange-700 | --tw-gradient-from: #c2410c var(--tw-gradient-from-position); --tw-gradient-to: rgb(194 65 12 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-orange-800 | --tw-gradient-from: #9a3412 var(--tw-gradient-from-position); --tw-gradient-to: rgb(154 52 18 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-orange-900 | --tw-gradient-from: #7c2d12 var(--tw-gradient-from-position); --tw-gradient-to: rgb(124 45 18 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-orange-950 | --tw-gradient-from: #431407 var(--tw-gradient-from-position); --tw-gradient-to: rgb(67 20 7 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-amber-50 | --tw-gradient-from: #fffbeb var(--tw-gradient-from-position); --tw-gradient-to: rgb(255 251 235 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-amber-100 | --tw-gradient-from: #fef3c7 var(--tw-gradient-from-position); --tw-gradient-to: rgb(254 243 199 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-amber-200 | --tw-gradient-from: #fde68a var(--tw-gradient-from-position); --tw-gradient-to: rgb(253 230 138 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-amber-300 | --tw-gradient-from: #fcd34d var(--tw-gradient-from-position); --tw-gradient-to: rgb(252 211 77 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-amber-400 | --tw-gradient-from: #fbbf24 var(--tw-gradient-from-position); --tw-gradient-to: rgb(251 191 36 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-amber-500 | --tw-gradient-from: #f59e0b var(--tw-gradient-from-position); --tw-gradient-to: rgb(245 158 11 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-amber-600 | --tw-gradient-from: #d97706 var(--tw-gradient-from-position); --tw-gradient-to: rgb(217 119 6 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-amber-700 | --tw-gradient-from: #b45309 var(--tw-gradient-from-position); --tw-gradient-to: rgb(180 83 9 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-amber-800 | --tw-gradient-from: #92400e var(--tw-gradient-from-position); --tw-gradient-to: rgb(146 64 14 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-amber-900 | --tw-gradient-from: #78350f var(--tw-gradient-from-position); --tw-gradient-to: rgb(120 53 15 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-amber-950 | --tw-gradient-from: #451a03 var(--tw-gradient-from-position); --tw-gradient-to: rgb(69 26 3 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-yellow-50 | --tw-gradient-from: #fefce8 var(--tw-gradient-from-position); --tw-gradient-to: rgb(254 252 232 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-yellow-100 | --tw-gradient-from: #fef9c3 var(--tw-gradient-from-position); --tw-gradient-to: rgb(254 249 195 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-yellow-200 | --tw-gradient-from: #fef08a var(--tw-gradient-from-position); --tw-gradient-to: rgb(254 240 138 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-yellow-300 | --tw-gradient-from: #fde047 var(--tw-gradient-from-position); --tw-gradient-to: rgb(253 224 71 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-yellow-400 | --tw-gradient-from: #facc15 var(--tw-gradient-from-position); --tw-gradient-to: rgb(250 204 21 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-yellow-500 | --tw-gradient-from: #eab308 var(--tw-gradient-from-position); --tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-yellow-600 | --tw-gradient-from: #ca8a04 var(--tw-gradient-from-position); --tw-gradient-to: rgb(202 138 4 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-yellow-700 | --tw-gradient-from: #a16207 var(--tw-gradient-from-position); --tw-gradient-to: rgb(161 98 7 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-yellow-800 | --tw-gradient-from: #854d0e var(--tw-gradient-from-position); --tw-gradient-to: rgb(133 77 14 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-yellow-900 | --tw-gradient-from: #713f12 var(--tw-gradient-from-position); --tw-gradient-to: rgb(113 63 18 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-yellow-950 | --tw-gradient-from: #422006 var(--tw-gradient-from-position); --tw-gradient-to: rgb(66 32 6 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-lime-50 | --tw-gradient-from: #f7fee7 var(--tw-gradient-from-position); --tw-gradient-to: rgb(247 254 231 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-lime-100 | --tw-gradient-from: #ecfccb var(--tw-gradient-from-position); --tw-gradient-to: rgb(236 252 203 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-lime-200 | --tw-gradient-from: #d9f99d var(--tw-gradient-from-position); --tw-gradient-to: rgb(217 249 157 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-lime-300 | --tw-gradient-from: #bef264 var(--tw-gradient-from-position); --tw-gradient-to: rgb(190 242 100 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-lime-400 | --tw-gradient-from: #a3e635 var(--tw-gradient-from-position); --tw-gradient-to: rgb(163 230 53 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-lime-500 | --tw-gradient-from: #84cc16 var(--tw-gradient-from-position); --tw-gradient-to: rgb(132 204 22 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-lime-600 | --tw-gradient-from: #65a30d var(--tw-gradient-from-position); --tw-gradient-to: rgb(101 163 13 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-lime-700 | --tw-gradient-from: #4d7c0f var(--tw-gradient-from-position); --tw-gradient-to: rgb(77 124 15 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-lime-800 | --tw-gradient-from: #3f6212 var(--tw-gradient-from-position); --tw-gradient-to: rgb(63 98 18 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-lime-900 | --tw-gradient-from: #365314 var(--tw-gradient-from-position); --tw-gradient-to: rgb(54 83 20 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-lime-950 | --tw-gradient-from: #1a2e05 var(--tw-gradient-from-position); --tw-gradient-to: rgb(26 46 5 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-green-50 | --tw-gradient-from: #f0fdf4 var(--tw-gradient-from-position); --tw-gradient-to: rgb(240 253 244 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-green-100 | --tw-gradient-from: #dcfce7 var(--tw-gradient-from-position); --tw-gradient-to: rgb(220 252 231 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-green-200 | --tw-gradient-from: #bbf7d0 var(--tw-gradient-from-position); --tw-gradient-to: rgb(187 247 208 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-green-300 | --tw-gradient-from: #86efac var(--tw-gradient-from-position); --tw-gradient-to: rgb(134 239 172 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-green-400 | --tw-gradient-from: #4ade80 var(--tw-gradient-from-position); --tw-gradient-to: rgb(74 222 128 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-green-500 | --tw-gradient-from: #22c55e var(--tw-gradient-from-position); --tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-green-600 | --tw-gradient-from: #16a34a var(--tw-gradient-from-position); --tw-gradient-to: rgb(22 163 74 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-green-700 | --tw-gradient-from: #15803d var(--tw-gradient-from-position); --tw-gradient-to: rgb(21 128 61 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-green-800 | --tw-gradient-from: #166534 var(--tw-gradient-from-position); --tw-gradient-to: rgb(22 101 52 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-green-900 | --tw-gradient-from: #14532d var(--tw-gradient-from-position); --tw-gradient-to: rgb(20 83 45 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-green-950 | --tw-gradient-from: #052e16 var(--tw-gradient-from-position); --tw-gradient-to: rgb(5 46 22 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-emerald-50 | --tw-gradient-from: #ecfdf5 var(--tw-gradient-from-position); --tw-gradient-to: rgb(236 253 245 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-emerald-100 | --tw-gradient-from: #d1fae5 var(--tw-gradient-from-position); --tw-gradient-to: rgb(209 250 229 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-emerald-200 | --tw-gradient-from: #a7f3d0 var(--tw-gradient-from-position); --tw-gradient-to: rgb(167 243 208 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-emerald-300 | --tw-gradient-from: #6ee7b7 var(--tw-gradient-from-position); --tw-gradient-to: rgb(110 231 183 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-emerald-400 | --tw-gradient-from: #34d399 var(--tw-gradient-from-position); --tw-gradient-to: rgb(52 211 153 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-emerald-500 | --tw-gradient-from: #10b981 var(--tw-gradient-from-position); --tw-gradient-to: rgb(16 185 129 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-emerald-600 | --tw-gradient-from: #059669 var(--tw-gradient-from-position); --tw-gradient-to: rgb(5 150 105 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-emerald-700 | --tw-gradient-from: #047857 var(--tw-gradient-from-position); --tw-gradient-to: rgb(4 120 87 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-emerald-800 | --tw-gradient-from: #065f46 var(--tw-gradient-from-position); --tw-gradient-to: rgb(6 95 70 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-emerald-900 | --tw-gradient-from: #064e3b var(--tw-gradient-from-position); --tw-gradient-to: rgb(6 78 59 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-emerald-950 | --tw-gradient-from: #022c22 var(--tw-gradient-from-position); --tw-gradient-to: rgb(2 44 34 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-teal-50 | --tw-gradient-from: #f0fdfa var(--tw-gradient-from-position); --tw-gradient-to: rgb(240 253 250 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-teal-100 | --tw-gradient-from: #ccfbf1 var(--tw-gradient-from-position); --tw-gradient-to: rgb(204 251 241 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-teal-200 | --tw-gradient-from: #99f6e4 var(--tw-gradient-from-position); --tw-gradient-to: rgb(153 246 228 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-teal-300 | --tw-gradient-from: #5eead4 var(--tw-gradient-from-position); --tw-gradient-to: rgb(94 234 212 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-teal-400 | --tw-gradient-from: #2dd4bf var(--tw-gradient-from-position); --tw-gradient-to: rgb(45 212 191 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-teal-500 | --tw-gradient-from: #14b8a6 var(--tw-gradient-from-position); --tw-gradient-to: rgb(20 184 166 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-teal-600 | --tw-gradient-from: #0d9488 var(--tw-gradient-from-position); --tw-gradient-to: rgb(13 148 136 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-teal-700 | --tw-gradient-from: #0f766e var(--tw-gradient-from-position); --tw-gradient-to: rgb(15 118 110 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-teal-800 | --tw-gradient-from: #115e59 var(--tw-gradient-from-position); --tw-gradient-to: rgb(17 94 89 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-teal-900 | --tw-gradient-from: #134e4a var(--tw-gradient-from-position); --tw-gradient-to: rgb(19 78 74 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-teal-950 | --tw-gradient-from: #042f2e var(--tw-gradient-from-position); --tw-gradient-to: rgb(4 47 46 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-cyan-50 | --tw-gradient-from: #ecfeff var(--tw-gradient-from-position); --tw-gradient-to: rgb(236 254 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-cyan-100 | --tw-gradient-from: #cffafe var(--tw-gradient-from-position); --tw-gradient-to: rgb(207 250 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-cyan-200 | --tw-gradient-from: #a5f3fc var(--tw-gradient-from-position); --tw-gradient-to: rgb(165 243 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-cyan-300 | --tw-gradient-from: #67e8f9 var(--tw-gradient-from-position); --tw-gradient-to: rgb(103 232 249 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-cyan-400 | --tw-gradient-from: #22d3ee var(--tw-gradient-from-position); --tw-gradient-to: rgb(34 211 238 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-cyan-500 | --tw-gradient-from: #06b6d4 var(--tw-gradient-from-position); --tw-gradient-to: rgb(6 182 212 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-cyan-600 | --tw-gradient-from: #0891b2 var(--tw-gradient-from-position); --tw-gradient-to: rgb(8 145 178 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-cyan-700 | --tw-gradient-from: #0e7490 var(--tw-gradient-from-position); --tw-gradient-to: rgb(14 116 144 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-cyan-800 | --tw-gradient-from: #155e75 var(--tw-gradient-from-position); --tw-gradient-to: rgb(21 94 117 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-cyan-900 | --tw-gradient-from: #164e63 var(--tw-gradient-from-position); --tw-gradient-to: rgb(22 78 99 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-cyan-950 | --tw-gradient-from: #083344 var(--tw-gradient-from-position); --tw-gradient-to: rgb(8 51 68 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-sky-50 | --tw-gradient-from: #f0f9ff var(--tw-gradient-from-position); --tw-gradient-to: rgb(240 249 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-sky-100 | --tw-gradient-from: #e0f2fe var(--tw-gradient-from-position); --tw-gradient-to: rgb(224 242 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-sky-200 | --tw-gradient-from: #bae6fd var(--tw-gradient-from-position); --tw-gradient-to: rgb(186 230 253 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-sky-300 | --tw-gradient-from: #7dd3fc var(--tw-gradient-from-position); --tw-gradient-to: rgb(125 211 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-sky-400 | --tw-gradient-from: #38bdf8 var(--tw-gradient-from-position); --tw-gradient-to: rgb(56 189 248 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-sky-500 | --tw-gradient-from: #0ea5e9 var(--tw-gradient-from-position); --tw-gradient-to: rgb(14 165 233 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-sky-600 | --tw-gradient-from: #0284c7 var(--tw-gradient-from-position); --tw-gradient-to: rgb(2 132 199 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-sky-700 | --tw-gradient-from: #0369a1 var(--tw-gradient-from-position); --tw-gradient-to: rgb(3 105 161 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-sky-800 | --tw-gradient-from: #075985 var(--tw-gradient-from-position); --tw-gradient-to: rgb(7 89 133 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-sky-900 | --tw-gradient-from: #0c4a6e var(--tw-gradient-from-position); --tw-gradient-to: rgb(12 74 110 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-sky-950 | --tw-gradient-from: #082f49 var(--tw-gradient-from-position); --tw-gradient-to: rgb(8 47 73 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-blue-50 | --tw-gradient-from: #eff6ff var(--tw-gradient-from-position); --tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-blue-100 | --tw-gradient-from: #dbeafe var(--tw-gradient-from-position); --tw-gradient-to: rgb(219 234 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-blue-200 | --tw-gradient-from: #bfdbfe var(--tw-gradient-from-position); --tw-gradient-to: rgb(191 219 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-blue-300 | --tw-gradient-from: #93c5fd var(--tw-gradient-from-position); --tw-gradient-to: rgb(147 197 253 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-blue-400 | --tw-gradient-from: #60a5fa var(--tw-gradient-from-position); --tw-gradient-to: rgb(96 165 250 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-blue-500 | --tw-gradient-from: #3b82f6 var(--tw-gradient-from-position); --tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-blue-600 | --tw-gradient-from: #2563eb var(--tw-gradient-from-position); --tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-blue-700 | --tw-gradient-from: #1d4ed8 var(--tw-gradient-from-position); --tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-blue-800 | --tw-gradient-from: #1e40af var(--tw-gradient-from-position); --tw-gradient-to: rgb(30 64 175 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-blue-900 | --tw-gradient-from: #1e3a8a var(--tw-gradient-from-position); --tw-gradient-to: rgb(30 58 138 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-blue-950 | --tw-gradient-from: #172554 var(--tw-gradient-from-position); --tw-gradient-to: rgb(23 37 84 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-indigo-50 | --tw-gradient-from: #eef2ff var(--tw-gradient-from-position); --tw-gradient-to: rgb(238 242 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-indigo-100 | --tw-gradient-from: #e0e7ff var(--tw-gradient-from-position); --tw-gradient-to: rgb(224 231 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-indigo-200 | --tw-gradient-from: #c7d2fe var(--tw-gradient-from-position); --tw-gradient-to: rgb(199 210 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-indigo-300 | --tw-gradient-from: #a5b4fc var(--tw-gradient-from-position); --tw-gradient-to: rgb(165 180 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-indigo-400 | --tw-gradient-from: #818cf8 var(--tw-gradient-from-position); --tw-gradient-to: rgb(129 140 248 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-indigo-500 | --tw-gradient-from: #6366f1 var(--tw-gradient-from-position); --tw-gradient-to: rgb(99 102 241 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-indigo-600 | --tw-gradient-from: #4f46e5 var(--tw-gradient-from-position); --tw-gradient-to: rgb(79 70 229 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-indigo-700 | --tw-gradient-from: #4338ca var(--tw-gradient-from-position); --tw-gradient-to: rgb(67 56 202 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-indigo-800 | --tw-gradient-from: #3730a3 var(--tw-gradient-from-position); --tw-gradient-to: rgb(55 48 163 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-indigo-900 | --tw-gradient-from: #312e81 var(--tw-gradient-from-position); --tw-gradient-to: rgb(49 46 129 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-indigo-950 | --tw-gradient-from: #1e1b4b var(--tw-gradient-from-position); --tw-gradient-to: rgb(30 27 75 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-violet-50 | --tw-gradient-from: #f5f3ff var(--tw-gradient-from-position); --tw-gradient-to: rgb(245 243 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-violet-100 | --tw-gradient-from: #ede9fe var(--tw-gradient-from-position); --tw-gradient-to: rgb(237 233 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-violet-200 | --tw-gradient-from: #ddd6fe var(--tw-gradient-from-position); --tw-gradient-to: rgb(221 214 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-violet-300 | --tw-gradient-from: #c4b5fd var(--tw-gradient-from-position); --tw-gradient-to: rgb(196 181 253 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-violet-400 | --tw-gradient-from: #a78bfa var(--tw-gradient-from-position); --tw-gradient-to: rgb(167 139 250 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-violet-500 | --tw-gradient-from: #8b5cf6 var(--tw-gradient-from-position); --tw-gradient-to: rgb(139 92 246 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-violet-600 | --tw-gradient-from: #7c3aed var(--tw-gradient-from-position); --tw-gradient-to: rgb(124 58 237 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-violet-700 | --tw-gradient-from: #6d28d9 var(--tw-gradient-from-position); --tw-gradient-to: rgb(109 40 217 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-violet-800 | --tw-gradient-from: #5b21b6 var(--tw-gradient-from-position); --tw-gradient-to: rgb(91 33 182 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-violet-900 | --tw-gradient-from: #4c1d95 var(--tw-gradient-from-position); --tw-gradient-to: rgb(76 29 149 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-violet-950 | --tw-gradient-from: #2e1065 var(--tw-gradient-from-position); --tw-gradient-to: rgb(46 16 101 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-purple-50 | --tw-gradient-from: #faf5ff var(--tw-gradient-from-position); --tw-gradient-to: rgb(250 245 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-purple-100 | --tw-gradient-from: #f3e8ff var(--tw-gradient-from-position); --tw-gradient-to: rgb(243 232 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-purple-200 | --tw-gradient-from: #e9d5ff var(--tw-gradient-from-position); --tw-gradient-to: rgb(233 213 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-purple-300 | --tw-gradient-from: #d8b4fe var(--tw-gradient-from-position); --tw-gradient-to: rgb(216 180 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-purple-400 | --tw-gradient-from: #c084fc var(--tw-gradient-from-position); --tw-gradient-to: rgb(192 132 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-purple-500 | --tw-gradient-from: #a855f7 var(--tw-gradient-from-position); --tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-purple-600 | --tw-gradient-from: #9333ea var(--tw-gradient-from-position); --tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-purple-700 | --tw-gradient-from: #7e22ce var(--tw-gradient-from-position); --tw-gradient-to: rgb(126 34 206 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-purple-800 | --tw-gradient-from: #6b21a8 var(--tw-gradient-from-position); --tw-gradient-to: rgb(107 33 168 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-purple-900 | --tw-gradient-from: #581c87 var(--tw-gradient-from-position); --tw-gradient-to: rgb(88 28 135 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-purple-950 | --tw-gradient-from: #3b0764 var(--tw-gradient-from-position); --tw-gradient-to: rgb(59 7 100 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-fuchsia-50 | --tw-gradient-from: #fdf4ff var(--tw-gradient-from-position); --tw-gradient-to: rgb(253 244 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-fuchsia-100 | --tw-gradient-from: #fae8ff var(--tw-gradient-from-position); --tw-gradient-to: rgb(250 232 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-fuchsia-200 | --tw-gradient-from: #f5d0fe var(--tw-gradient-from-position); --tw-gradient-to: rgb(245 208 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-fuchsia-300 | --tw-gradient-from: #f0abfc var(--tw-gradient-from-position); --tw-gradient-to: rgb(240 171 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-fuchsia-400 | --tw-gradient-from: #e879f9 var(--tw-gradient-from-position); --tw-gradient-to: rgb(232 121 249 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-fuchsia-500 | --tw-gradient-from: #d946ef var(--tw-gradient-from-position); --tw-gradient-to: rgb(217 70 239 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-fuchsia-600 | --tw-gradient-from: #c026d3 var(--tw-gradient-from-position); --tw-gradient-to: rgb(192 38 211 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-fuchsia-700 | --tw-gradient-from: #a21caf var(--tw-gradient-from-position); --tw-gradient-to: rgb(162 28 175 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-fuchsia-800 | --tw-gradient-from: #86198f var(--tw-gradient-from-position); --tw-gradient-to: rgb(134 25 143 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-fuchsia-900 | --tw-gradient-from: #701a75 var(--tw-gradient-from-position); --tw-gradient-to: rgb(112 26 117 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-fuchsia-950 | --tw-gradient-from: #4a044e var(--tw-gradient-from-position); --tw-gradient-to: rgb(74 4 78 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-pink-50 | --tw-gradient-from: #fdf2f8 var(--tw-gradient-from-position); --tw-gradient-to: rgb(253 242 248 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-pink-100 | --tw-gradient-from: #fce7f3 var(--tw-gradient-from-position); --tw-gradient-to: rgb(252 231 243 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-pink-200 | --tw-gradient-from: #fbcfe8 var(--tw-gradient-from-position); --tw-gradient-to: rgb(251 207 232 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-pink-300 | --tw-gradient-from: #f9a8d4 var(--tw-gradient-from-position); --tw-gradient-to: rgb(249 168 212 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-pink-400 | --tw-gradient-from: #f472b6 var(--tw-gradient-from-position); --tw-gradient-to: rgb(244 114 182 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-pink-500 | --tw-gradient-from: #ec4899 var(--tw-gradient-from-position); --tw-gradient-to: rgb(236 72 153 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-pink-600 | --tw-gradient-from: #db2777 var(--tw-gradient-from-position); --tw-gradient-to: rgb(219 39 119 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-pink-700 | --tw-gradient-from: #be185d var(--tw-gradient-from-position); --tw-gradient-to: rgb(190 24 93 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-pink-800 | --tw-gradient-from: #9d174d var(--tw-gradient-from-position); --tw-gradient-to: rgb(157 23 77 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-pink-900 | --tw-gradient-from: #831843 var(--tw-gradient-from-position); --tw-gradient-to: rgb(131 24 67 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-pink-950 | --tw-gradient-from: #500724 var(--tw-gradient-from-position); --tw-gradient-to: rgb(80 7 36 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-rose-50 | --tw-gradient-from: #fff1f2 var(--tw-gradient-from-position); --tw-gradient-to: rgb(255 241 242 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-rose-100 | --tw-gradient-from: #ffe4e6 var(--tw-gradient-from-position); --tw-gradient-to: rgb(255 228 230 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-rose-200 | --tw-gradient-from: #fecdd3 var(--tw-gradient-from-position); --tw-gradient-to: rgb(254 205 211 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-rose-300 | --tw-gradient-from: #fda4af var(--tw-gradient-from-position); --tw-gradient-to: rgb(253 164 175 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-rose-400 | --tw-gradient-from: #fb7185 var(--tw-gradient-from-position); --tw-gradient-to: rgb(251 113 133 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-rose-500 | --tw-gradient-from: #f43f5e var(--tw-gradient-from-position); --tw-gradient-to: rgb(244 63 94 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-rose-600 | --tw-gradient-from: #e11d48 var(--tw-gradient-from-position); --tw-gradient-to: rgb(225 29 72 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-rose-700 | --tw-gradient-from: #be123c var(--tw-gradient-from-position); --tw-gradient-to: rgb(190 18 60 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-rose-800 | --tw-gradient-from: #9f1239 var(--tw-gradient-from-position); --tw-gradient-to: rgb(159 18 57 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-rose-900 | --tw-gradient-from: #881337 var(--tw-gradient-from-position); --tw-gradient-to: rgb(136 19 55 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-rose-950 | --tw-gradient-from: #4c0519 var(--tw-gradient-from-position); --tw-gradient-to: rgb(76 5 25 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); | | | from-0% | --tw-gradient-from-position: 0%; | | | from-5% | --tw-gradient-from-position: 5%; | | | from-10% | --tw-gradient-from-position: 10%; | | | from-15% | --tw-gradient-from-position: 15%; | | | from-20% | --tw-gradient-from-position: 20%; | | | from-25% | --tw-gradient-from-position: 25%; | | | from-30% | --tw-gradient-from-position: 30%; | | | from-35% | --tw-gradient-from-position: 35%; | | | from-40% | --tw-gradient-from-position: 40%; | | | from-45% | --tw-gradient-from-position: 45%; | | | from-50% | --tw-gradient-from-position: 50%; | | | from-55% | --tw-gradient-from-position: 55%; | | | from-60% | --tw-gradient-from-position: 60%; | | | from-65% | --tw-gradient-from-position: 65%; | | | from-70% | --tw-gradient-from-position: 70%; | | | from-75% | --tw-gradient-from-position: 75%; | | | from-80% | --tw-gradient-from-position: 80%; | | | from-85% | --tw-gradient-from-position: 85%; | | | from-90% | --tw-gradient-from-position: 90%; | | | from-95% | --tw-gradient-from-position: 95%; | | | from-100% | --tw-gradient-from-position: 100%; | | | via-inherit | --tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), inherit var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-current | --tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), currentColor var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-transparent | --tw-gradient-to: rgb(0 0 0 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), transparent var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-black | --tw-gradient-to: rgb(0 0 0 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #000 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-white | --tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-slate-50 | --tw-gradient-to: rgb(248 250 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f8fafc var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-slate-100 | --tw-gradient-to: rgb(241 245 249 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f1f5f9 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-slate-200 | --tw-gradient-to: rgb(226 232 240 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #e2e8f0 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-slate-300 | --tw-gradient-to: rgb(203 213 225 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #cbd5e1 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-slate-400 | --tw-gradient-to: rgb(148 163 184 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #94a3b8 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-slate-500 | --tw-gradient-to: rgb(100 116 139 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #64748b var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-slate-600 | --tw-gradient-to: rgb(71 85 105 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #475569 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-slate-700 | --tw-gradient-to: rgb(51 65 85 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #334155 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-slate-800 | --tw-gradient-to: rgb(30 41 59 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #1e293b var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-slate-900 | --tw-gradient-to: rgb(15 23 42 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #0f172a var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-slate-950 | --tw-gradient-to: rgb(2 6 23 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #020617 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-gray-50 | --tw-gradient-to: rgb(249 250 251 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f9fafb var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-gray-100 | --tw-gradient-to: rgb(243 244 246 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f3f4f6 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-gray-200 | --tw-gradient-to: rgb(229 231 235 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #e5e7eb var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-gray-300 | --tw-gradient-to: rgb(209 213 219 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #d1d5db var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-gray-400 | --tw-gradient-to: rgb(156 163 175 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #9ca3af var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-gray-500 | --tw-gradient-to: rgb(107 114 128 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #6b7280 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-gray-600 | --tw-gradient-to: rgb(75 85 99 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #4b5563 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-gray-700 | --tw-gradient-to: rgb(55 65 81 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #374151 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-gray-800 | --tw-gradient-to: rgb(31 41 55 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #1f2937 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-gray-900 | --tw-gradient-to: rgb(17 24 39 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #111827 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-gray-950 | --tw-gradient-to: rgb(3 7 18 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #030712 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-zinc-50 | --tw-gradient-to: rgb(250 250 250 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fafafa var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-zinc-100 | --tw-gradient-to: rgb(244 244 245 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f4f4f5 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-zinc-200 | --tw-gradient-to: rgb(228 228 231 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #e4e4e7 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-zinc-300 | --tw-gradient-to: rgb(212 212 216 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #d4d4d8 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-zinc-400 | --tw-gradient-to: rgb(161 161 170 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #a1a1aa var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-zinc-500 | --tw-gradient-to: rgb(113 113 122 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #71717a var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-zinc-600 | --tw-gradient-to: rgb(82 82 91 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #52525b var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-zinc-700 | --tw-gradient-to: rgb(63 63 70 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #3f3f46 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-zinc-800 | --tw-gradient-to: rgb(39 39 42 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #27272a var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-zinc-900 | --tw-gradient-to: rgb(24 24 27 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #18181b var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-zinc-950 | --tw-gradient-to: rgb(9 9 11 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #09090b var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-neutral-50 | --tw-gradient-to: rgb(250 250 250 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fafafa var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-neutral-100 | --tw-gradient-to: rgb(245 245 245 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f5f5f5 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-neutral-200 | --tw-gradient-to: rgb(229 229 229 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #e5e5e5 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-neutral-300 | --tw-gradient-to: rgb(212 212 212 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #d4d4d4 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-neutral-400 | --tw-gradient-to: rgb(163 163 163 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #a3a3a3 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-neutral-500 | --tw-gradient-to: rgb(115 115 115 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #737373 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-neutral-600 | --tw-gradient-to: rgb(82 82 82 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #525252 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-neutral-700 | --tw-gradient-to: rgb(64 64 64 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #404040 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-neutral-800 | --tw-gradient-to: rgb(38 38 38 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #262626 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-neutral-900 | --tw-gradient-to: rgb(23 23 23 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #171717 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-neutral-950 | --tw-gradient-to: rgb(10 10 10 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #0a0a0a var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-stone-50 | --tw-gradient-to: rgb(250 250 249 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fafaf9 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-stone-100 | --tw-gradient-to: rgb(245 245 244 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f5f5f4 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-stone-200 | --tw-gradient-to: rgb(231 229 228 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #e7e5e4 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-stone-300 | --tw-gradient-to: rgb(214 211 209 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #d6d3d1 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-stone-400 | --tw-gradient-to: rgb(168 162 158 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #a8a29e var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-stone-500 | --tw-gradient-to: rgb(120 113 108 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #78716c var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-stone-600 | --tw-gradient-to: rgb(87 83 78 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #57534e var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-stone-700 | --tw-gradient-to: rgb(68 64 60 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #44403c var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-stone-800 | --tw-gradient-to: rgb(41 37 36 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #292524 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-stone-900 | --tw-gradient-to: rgb(28 25 23 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #1c1917 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-stone-950 | --tw-gradient-to: rgb(12 10 9 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #0c0a09 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-red-50 | --tw-gradient-to: rgb(254 242 242 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fef2f2 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-red-100 | --tw-gradient-to: rgb(254 226 226 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fee2e2 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-red-200 | --tw-gradient-to: rgb(254 202 202 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fecaca var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-red-300 | --tw-gradient-to: rgb(252 165 165 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fca5a5 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-red-400 | --tw-gradient-to: rgb(248 113 113 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f87171 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-red-500 | --tw-gradient-to: rgb(239 68 68 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ef4444 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-red-600 | --tw-gradient-to: rgb(220 38 38 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #dc2626 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-red-700 | --tw-gradient-to: rgb(185 28 28 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #b91c1c var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-red-800 | --tw-gradient-to: rgb(153 27 27 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #991b1b var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-red-900 | --tw-gradient-to: rgb(127 29 29 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #7f1d1d var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-red-950 | --tw-gradient-to: rgb(69 10 10 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #450a0a var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-orange-50 | --tw-gradient-to: rgb(255 247 237 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fff7ed var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-orange-100 | --tw-gradient-to: rgb(255 237 213 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ffedd5 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-orange-200 | --tw-gradient-to: rgb(254 215 170 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fed7aa var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-orange-300 | --tw-gradient-to: rgb(253 186 116 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fdba74 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-orange-400 | --tw-gradient-to: rgb(251 146 60 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fb923c var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-orange-500 | --tw-gradient-to: rgb(249 115 22 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f97316 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-orange-600 | --tw-gradient-to: rgb(234 88 12 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ea580c var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-orange-700 | --tw-gradient-to: rgb(194 65 12 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #c2410c var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-orange-800 | --tw-gradient-to: rgb(154 52 18 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #9a3412 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-orange-900 | --tw-gradient-to: rgb(124 45 18 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #7c2d12 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-orange-950 | --tw-gradient-to: rgb(67 20 7 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #431407 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-amber-50 | --tw-gradient-to: rgb(255 251 235 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fffbeb var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-amber-100 | --tw-gradient-to: rgb(254 243 199 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fef3c7 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-amber-200 | --tw-gradient-to: rgb(253 230 138 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fde68a var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-amber-300 | --tw-gradient-to: rgb(252 211 77 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fcd34d var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-amber-400 | --tw-gradient-to: rgb(251 191 36 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fbbf24 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-amber-500 | --tw-gradient-to: rgb(245 158 11 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f59e0b var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-amber-600 | --tw-gradient-to: rgb(217 119 6 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #d97706 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-amber-700 | --tw-gradient-to: rgb(180 83 9 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #b45309 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-amber-800 | --tw-gradient-to: rgb(146 64 14 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #92400e var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-amber-900 | --tw-gradient-to: rgb(120 53 15 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #78350f var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-amber-950 | --tw-gradient-to: rgb(69 26 3 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #451a03 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-yellow-50 | --tw-gradient-to: rgb(254 252 232 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fefce8 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-yellow-100 | --tw-gradient-to: rgb(254 249 195 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fef9c3 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-yellow-200 | --tw-gradient-to: rgb(254 240 138 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fef08a var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-yellow-300 | --tw-gradient-to: rgb(253 224 71 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fde047 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-yellow-400 | --tw-gradient-to: rgb(250 204 21 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #facc15 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-yellow-500 | --tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #eab308 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-yellow-600 | --tw-gradient-to: rgb(202 138 4 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ca8a04 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-yellow-700 | --tw-gradient-to: rgb(161 98 7 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #a16207 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-yellow-800 | --tw-gradient-to: rgb(133 77 14 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #854d0e var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-yellow-900 | --tw-gradient-to: rgb(113 63 18 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #713f12 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-yellow-950 | --tw-gradient-to: rgb(66 32 6 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #422006 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-lime-50 | --tw-gradient-to: rgb(247 254 231 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f7fee7 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-lime-100 | --tw-gradient-to: rgb(236 252 203 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ecfccb var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-lime-200 | --tw-gradient-to: rgb(217 249 157 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #d9f99d var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-lime-300 | --tw-gradient-to: rgb(190 242 100 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #bef264 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-lime-400 | --tw-gradient-to: rgb(163 230 53 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #a3e635 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-lime-500 | --tw-gradient-to: rgb(132 204 22 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #84cc16 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-lime-600 | --tw-gradient-to: rgb(101 163 13 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #65a30d var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-lime-700 | --tw-gradient-to: rgb(77 124 15 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #4d7c0f var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-lime-800 | --tw-gradient-to: rgb(63 98 18 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #3f6212 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-lime-900 | --tw-gradient-to: rgb(54 83 20 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #365314 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-lime-950 | --tw-gradient-to: rgb(26 46 5 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #1a2e05 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-green-50 | --tw-gradient-to: rgb(240 253 244 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f0fdf4 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-green-100 | --tw-gradient-to: rgb(220 252 231 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #dcfce7 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-green-200 | --tw-gradient-to: rgb(187 247 208 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #bbf7d0 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-green-300 | --tw-gradient-to: rgb(134 239 172 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #86efac var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-green-400 | --tw-gradient-to: rgb(74 222 128 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #4ade80 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-green-500 | --tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #22c55e var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-green-600 | --tw-gradient-to: rgb(22 163 74 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #16a34a var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-green-700 | --tw-gradient-to: rgb(21 128 61 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #15803d var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-green-800 | --tw-gradient-to: rgb(22 101 52 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #166534 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-green-900 | --tw-gradient-to: rgb(20 83 45 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #14532d var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-green-950 | --tw-gradient-to: rgb(5 46 22 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #052e16 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-emerald-50 | --tw-gradient-to: rgb(236 253 245 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ecfdf5 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-emerald-100 | --tw-gradient-to: rgb(209 250 229 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #d1fae5 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-emerald-200 | --tw-gradient-to: rgb(167 243 208 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #a7f3d0 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-emerald-300 | --tw-gradient-to: rgb(110 231 183 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #6ee7b7 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-emerald-400 | --tw-gradient-to: rgb(52 211 153 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #34d399 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-emerald-500 | --tw-gradient-to: rgb(16 185 129 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #10b981 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-emerald-600 | --tw-gradient-to: rgb(5 150 105 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #059669 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-emerald-700 | --tw-gradient-to: rgb(4 120 87 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #047857 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-emerald-800 | --tw-gradient-to: rgb(6 95 70 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #065f46 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-emerald-900 | --tw-gradient-to: rgb(6 78 59 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #064e3b var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-emerald-950 | --tw-gradient-to: rgb(2 44 34 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #022c22 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-teal-50 | --tw-gradient-to: rgb(240 253 250 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f0fdfa var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-teal-100 | --tw-gradient-to: rgb(204 251 241 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ccfbf1 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-teal-200 | --tw-gradient-to: rgb(153 246 228 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #99f6e4 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-teal-300 | --tw-gradient-to: rgb(94 234 212 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #5eead4 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-teal-400 | --tw-gradient-to: rgb(45 212 191 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #2dd4bf var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-teal-500 | --tw-gradient-to: rgb(20 184 166 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #14b8a6 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-teal-600 | --tw-gradient-to: rgb(13 148 136 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #0d9488 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-teal-700 | --tw-gradient-to: rgb(15 118 110 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #0f766e var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-teal-800 | --tw-gradient-to: rgb(17 94 89 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #115e59 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-teal-900 | --tw-gradient-to: rgb(19 78 74 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #134e4a var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-teal-950 | --tw-gradient-to: rgb(4 47 46 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #042f2e var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-cyan-50 | --tw-gradient-to: rgb(236 254 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ecfeff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-cyan-100 | --tw-gradient-to: rgb(207 250 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #cffafe var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-cyan-200 | --tw-gradient-to: rgb(165 243 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #a5f3fc var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-cyan-300 | --tw-gradient-to: rgb(103 232 249 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #67e8f9 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-cyan-400 | --tw-gradient-to: rgb(34 211 238 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #22d3ee var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-cyan-500 | --tw-gradient-to: rgb(6 182 212 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #06b6d4 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-cyan-600 | --tw-gradient-to: rgb(8 145 178 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #0891b2 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-cyan-700 | --tw-gradient-to: rgb(14 116 144 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #0e7490 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-cyan-800 | --tw-gradient-to: rgb(21 94 117 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #155e75 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-cyan-900 | --tw-gradient-to: rgb(22 78 99 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #164e63 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-cyan-950 | --tw-gradient-to: rgb(8 51 68 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #083344 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-sky-50 | --tw-gradient-to: rgb(240 249 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f0f9ff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-sky-100 | --tw-gradient-to: rgb(224 242 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #e0f2fe var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-sky-200 | --tw-gradient-to: rgb(186 230 253 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #bae6fd var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-sky-300 | --tw-gradient-to: rgb(125 211 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #7dd3fc var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-sky-400 | --tw-gradient-to: rgb(56 189 248 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #38bdf8 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-sky-500 | --tw-gradient-to: rgb(14 165 233 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #0ea5e9 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-sky-600 | --tw-gradient-to: rgb(2 132 199 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #0284c7 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-sky-700 | --tw-gradient-to: rgb(3 105 161 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #0369a1 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-sky-800 | --tw-gradient-to: rgb(7 89 133 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #075985 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-sky-900 | --tw-gradient-to: rgb(12 74 110 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #0c4a6e var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-sky-950 | --tw-gradient-to: rgb(8 47 73 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #082f49 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-blue-50 | --tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #eff6ff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-blue-100 | --tw-gradient-to: rgb(219 234 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #dbeafe var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-blue-200 | --tw-gradient-to: rgb(191 219 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #bfdbfe var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-blue-300 | --tw-gradient-to: rgb(147 197 253 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #93c5fd var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-blue-400 | --tw-gradient-to: rgb(96 165 250 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #60a5fa var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-blue-500 | --tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #3b82f6 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-blue-600 | --tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #2563eb var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-blue-700 | --tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #1d4ed8 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-blue-800 | --tw-gradient-to: rgb(30 64 175 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #1e40af var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-blue-900 | --tw-gradient-to: rgb(30 58 138 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #1e3a8a var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-blue-950 | --tw-gradient-to: rgb(23 37 84 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #172554 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-indigo-50 | --tw-gradient-to: rgb(238 242 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #eef2ff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-indigo-100 | --tw-gradient-to: rgb(224 231 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #e0e7ff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-indigo-200 | --tw-gradient-to: rgb(199 210 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #c7d2fe var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-indigo-300 | --tw-gradient-to: rgb(165 180 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #a5b4fc var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-indigo-400 | --tw-gradient-to: rgb(129 140 248 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #818cf8 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-indigo-500 | --tw-gradient-to: rgb(99 102 241 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #6366f1 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-indigo-600 | --tw-gradient-to: rgb(79 70 229 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #4f46e5 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-indigo-700 | --tw-gradient-to: rgb(67 56 202 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #4338ca var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-indigo-800 | --tw-gradient-to: rgb(55 48 163 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #3730a3 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-indigo-900 | --tw-gradient-to: rgb(49 46 129 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #312e81 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-indigo-950 | --tw-gradient-to: rgb(30 27 75 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #1e1b4b var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-violet-50 | --tw-gradient-to: rgb(245 243 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f5f3ff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-violet-100 | --tw-gradient-to: rgb(237 233 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ede9fe var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-violet-200 | --tw-gradient-to: rgb(221 214 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ddd6fe var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-violet-300 | --tw-gradient-to: rgb(196 181 253 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #c4b5fd var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-violet-400 | --tw-gradient-to: rgb(167 139 250 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #a78bfa var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-violet-500 | --tw-gradient-to: rgb(139 92 246 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #8b5cf6 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-violet-600 | --tw-gradient-to: rgb(124 58 237 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #7c3aed var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-violet-700 | --tw-gradient-to: rgb(109 40 217 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #6d28d9 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-violet-800 | --tw-gradient-to: rgb(91 33 182 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #5b21b6 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-violet-900 | --tw-gradient-to: rgb(76 29 149 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #4c1d95 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-violet-950 | --tw-gradient-to: rgb(46 16 101 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #2e1065 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-purple-50 | --tw-gradient-to: rgb(250 245 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #faf5ff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-purple-100 | --tw-gradient-to: rgb(243 232 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f3e8ff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-purple-200 | --tw-gradient-to: rgb(233 213 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #e9d5ff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-purple-300 | --tw-gradient-to: rgb(216 180 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #d8b4fe var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-purple-400 | --tw-gradient-to: rgb(192 132 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #c084fc var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-purple-500 | --tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #a855f7 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-purple-600 | --tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #9333ea var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-purple-700 | --tw-gradient-to: rgb(126 34 206 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #7e22ce var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-purple-800 | --tw-gradient-to: rgb(107 33 168 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #6b21a8 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-purple-900 | --tw-gradient-to: rgb(88 28 135 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #581c87 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-purple-950 | --tw-gradient-to: rgb(59 7 100 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #3b0764 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-fuchsia-50 | --tw-gradient-to: rgb(253 244 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fdf4ff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-fuchsia-100 | --tw-gradient-to: rgb(250 232 255 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fae8ff var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-fuchsia-200 | --tw-gradient-to: rgb(245 208 254 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f5d0fe var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-fuchsia-300 | --tw-gradient-to: rgb(240 171 252 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f0abfc var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-fuchsia-400 | --tw-gradient-to: rgb(232 121 249 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #e879f9 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-fuchsia-500 | --tw-gradient-to: rgb(217 70 239 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #d946ef var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-fuchsia-600 | --tw-gradient-to: rgb(192 38 211 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #c026d3 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-fuchsia-700 | --tw-gradient-to: rgb(162 28 175 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #a21caf var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-fuchsia-800 | --tw-gradient-to: rgb(134 25 143 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #86198f var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-fuchsia-900 | --tw-gradient-to: rgb(112 26 117 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #701a75 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-fuchsia-950 | --tw-gradient-to: rgb(74 4 78 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #4a044e var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-pink-50 | --tw-gradient-to: rgb(253 242 248 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fdf2f8 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-pink-100 | --tw-gradient-to: rgb(252 231 243 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fce7f3 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-pink-200 | --tw-gradient-to: rgb(251 207 232 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fbcfe8 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-pink-300 | --tw-gradient-to: rgb(249 168 212 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f9a8d4 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-pink-400 | --tw-gradient-to: rgb(244 114 182 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f472b6 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-pink-500 | --tw-gradient-to: rgb(236 72 153 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ec4899 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-pink-600 | --tw-gradient-to: rgb(219 39 119 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #db2777 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-pink-700 | --tw-gradient-to: rgb(190 24 93 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #be185d var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-pink-800 | --tw-gradient-to: rgb(157 23 77 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #9d174d var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-pink-900 | --tw-gradient-to: rgb(131 24 67 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #831843 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-pink-950 | --tw-gradient-to: rgb(80 7 36 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #500724 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-rose-50 | --tw-gradient-to: rgb(255 241 242 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fff1f2 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-rose-100 | --tw-gradient-to: rgb(255 228 230 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #ffe4e6 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-rose-200 | --tw-gradient-to: rgb(254 205 211 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fecdd3 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-rose-300 | --tw-gradient-to: rgb(253 164 175 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fda4af var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-rose-400 | --tw-gradient-to: rgb(251 113 133 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #fb7185 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-rose-500 | --tw-gradient-to: rgb(244 63 94 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #f43f5e var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-rose-600 | --tw-gradient-to: rgb(225 29 72 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #e11d48 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-rose-700 | --tw-gradient-to: rgb(190 18 60 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #be123c var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-rose-800 | --tw-gradient-to: rgb(159 18 57 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #9f1239 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-rose-900 | --tw-gradient-to: rgb(136 19 55 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #881337 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-rose-950 | --tw-gradient-to: rgb(76 5 25 / 0) var(--tw-gradient-to-position); --tw-gradient-stops: var(--tw-gradient-from), #4c0519 var(--tw-gradient-via-position), var(--tw-gradient-to); | | | via-0% | --tw-gradient-via-position: 0%; | | | via-5% | --tw-gradient-via-position: 5%; | | | via-10% | --tw-gradient-via-position: 10%; | | | via-15% | --tw-gradient-via-position: 15%; | | | via-20% | --tw-gradient-via-position: 20%; | | | via-25% | --tw-gradient-via-position: 25%; | | | via-30% | --tw-gradient-via-position: 30%; | | | via-35% | --tw-gradient-via-position: 35%; | | | via-40% | --tw-gradient-via-position: 40%; | | | via-45% | --tw-gradient-via-position: 45%; | | | via-50% | --tw-gradient-via-position: 50%; | | | via-55% | --tw-gradient-via-position: 55%; | | | via-60% | --tw-gradient-via-position: 60%; | | | via-65% | --tw-gradient-via-position: 65%; | | | via-70% | --tw-gradient-via-position: 70%; | | | via-75% | --tw-gradient-via-position: 75%; | | | via-80% | --tw-gradient-via-position: 80%; | | | via-85% | --tw-gradient-via-position: 85%; | | | via-90% | --tw-gradient-via-position: 90%; | | | via-95% | --tw-gradient-via-position: 95%; | | | via-100% | --tw-gradient-via-position: 100%; | | | to-inherit | --tw-gradient-to: inherit var(--tw-gradient-to-position); | | | to-current | --tw-gradient-to: currentColor var(--tw-gradient-to-position); | | | to-transparent | --tw-gradient-to: transparent var(--tw-gradient-to-position); | | | to-black | --tw-gradient-to: #000 var(--tw-gradient-to-position); | | | to-white | --tw-gradient-to: #fff var(--tw-gradient-to-position); | | | to-slate-50 | --tw-gradient-to: #f8fafc var(--tw-gradient-to-position); | | | to-slate-100 | --tw-gradient-to: #f1f5f9 var(--tw-gradient-to-position); | | | to-slate-200 | --tw-gradient-to: #e2e8f0 var(--tw-gradient-to-position); | | | to-slate-300 | --tw-gradient-to: #cbd5e1 var(--tw-gradient-to-position); | | | to-slate-400 | --tw-gradient-to: #94a3b8 var(--tw-gradient-to-position); | | | to-slate-500 | --tw-gradient-to: #64748b var(--tw-gradient-to-position); | | | to-slate-600 | --tw-gradient-to: #475569 var(--tw-gradient-to-position); | | | to-slate-700 | --tw-gradient-to: #334155 var(--tw-gradient-to-position); | | | to-slate-800 | --tw-gradient-to: #1e293b var(--tw-gradient-to-position); | | | to-slate-900 | --tw-gradient-to: #0f172a var(--tw-gradient-to-position); | | | to-slate-950 | --tw-gradient-to: #020617 var(--tw-gradient-to-position); | | | to-gray-50 | --tw-gradient-to: #f9fafb var(--tw-gradient-to-position); | | | to-gray-100 | --tw-gradient-to: #f3f4f6 var(--tw-gradient-to-position); | | | to-gray-200 | --tw-gradient-to: #e5e7eb var(--tw-gradient-to-position); | | | to-gray-300 | --tw-gradient-to: #d1d5db var(--tw-gradient-to-position); | | | to-gray-400 | --tw-gradient-to: #9ca3af var(--tw-gradient-to-position); | | | to-gray-500 | --tw-gradient-to: #6b7280 var(--tw-gradient-to-position); | | | to-gray-600 | --tw-gradient-to: #4b5563 var(--tw-gradient-to-position); | | | to-gray-700 | --tw-gradient-to: #374151 var(--tw-gradient-to-position); | | | to-gray-800 | --tw-gradient-to: #1f2937 var(--tw-gradient-to-position); | | | to-gray-900 | --tw-gradient-to: #111827 var(--tw-gradient-to-position); | | | to-gray-950 | --tw-gradient-to: #030712 var(--tw-gradient-to-position); | | | to-zinc-50 | --tw-gradient-to: #fafafa var(--tw-gradient-to-position); | | | to-zinc-100 | --tw-gradient-to: #f4f4f5 var(--tw-gradient-to-position); | | | to-zinc-200 | --tw-gradient-to: #e4e4e7 var(--tw-gradient-to-position); | | | to-zinc-300 | --tw-gradient-to: #d4d4d8 var(--tw-gradient-to-position); | | | to-zinc-400 | --tw-gradient-to: #a1a1aa var(--tw-gradient-to-position); | | | to-zinc-500 | --tw-gradient-to: #71717a var(--tw-gradient-to-position); | | | to-zinc-600 | --tw-gradient-to: #52525b var(--tw-gradient-to-position); | | | to-zinc-700 | --tw-gradient-to: #3f3f46 var(--tw-gradient-to-position); | | | to-zinc-800 | --tw-gradient-to: #27272a var(--tw-gradient-to-position); | | | to-zinc-900 | --tw-gradient-to: #18181b var(--tw-gradient-to-position); | | | to-zinc-950 | --tw-gradient-to: #09090b var(--tw-gradient-to-position); | | | to-neutral-50 | --tw-gradient-to: #fafafa var(--tw-gradient-to-position); | | | to-neutral-100 | --tw-gradient-to: #f5f5f5 var(--tw-gradient-to-position); | | | to-neutral-200 | --tw-gradient-to: #e5e5e5 var(--tw-gradient-to-position); | | | to-neutral-300 | --tw-gradient-to: #d4d4d4 var(--tw-gradient-to-position); | | | to-neutral-400 | --tw-gradient-to: #a3a3a3 var(--tw-gradient-to-position); | | | to-neutral-500 | --tw-gradient-to: #737373 var(--tw-gradient-to-position); | | | to-neutral-600 | --tw-gradient-to: #525252 var(--tw-gradient-to-position); | | | to-neutral-700 | --tw-gradient-to: #404040 var(--tw-gradient-to-position); | | | to-neutral-800 | --tw-gradient-to: #262626 var(--tw-gradient-to-position); | | | to-neutral-900 | --tw-gradient-to: #171717 var(--tw-gradient-to-position); | | | to-neutral-950 | --tw-gradient-to: #0a0a0a var(--tw-gradient-to-position); | | | to-stone-50 | --tw-gradient-to: #fafaf9 var(--tw-gradient-to-position); | | | to-stone-100 | --tw-gradient-to: #f5f5f4 var(--tw-gradient-to-position); | | | to-stone-200 | --tw-gradient-to: #e7e5e4 var(--tw-gradient-to-position); | | | to-stone-300 | --tw-gradient-to: #d6d3d1 var(--tw-gradient-to-position); | | | to-stone-400 | --tw-gradient-to: #a8a29e var(--tw-gradient-to-position); | | | to-stone-500 | --tw-gradient-to: #78716c var(--tw-gradient-to-position); | | | to-stone-600 | --tw-gradient-to: #57534e var(--tw-gradient-to-position); | | | to-stone-700 | --tw-gradient-to: #44403c var(--tw-gradient-to-position); | | | to-stone-800 | --tw-gradient-to: #292524 var(--tw-gradient-to-position); | | | to-stone-900 | --tw-gradient-to: #1c1917 var(--tw-gradient-to-position); | | | to-stone-950 | --tw-gradient-to: #0c0a09 var(--tw-gradient-to-position); | | | to-red-50 | --tw-gradient-to: #fef2f2 var(--tw-gradient-to-position); | | | to-red-100 | --tw-gradient-to: #fee2e2 var(--tw-gradient-to-position); | | | to-red-200 | --tw-gradient-to: #fecaca var(--tw-gradient-to-position); | | | to-red-300 | --tw-gradient-to: #fca5a5 var(--tw-gradient-to-position); | | | to-red-400 | --tw-gradient-to: #f87171 var(--tw-gradient-to-position); | | | to-red-500 | --tw-gradient-to: #ef4444 var(--tw-gradient-to-position); | | | to-red-600 | --tw-gradient-to: #dc2626 var(--tw-gradient-to-position); | | | to-red-700 | --tw-gradient-to: #b91c1c var(--tw-gradient-to-position); | | | to-red-800 | --tw-gradient-to: #991b1b var(--tw-gradient-to-position); | | | to-red-900 | --tw-gradient-to: #7f1d1d var(--tw-gradient-to-position); | | | to-red-950 | --tw-gradient-to: #450a0a var(--tw-gradient-to-position); | | | to-orange-50 | --tw-gradient-to: #fff7ed var(--tw-gradient-to-position); | | | to-orange-100 | --tw-gradient-to: #ffedd5 var(--tw-gradient-to-position); | | | to-orange-200 | --tw-gradient-to: #fed7aa var(--tw-gradient-to-position); | | | to-orange-300 | --tw-gradient-to: #fdba74 var(--tw-gradient-to-position); | | | to-orange-400 | --tw-gradient-to: #fb923c var(--tw-gradient-to-position); | | | to-orange-500 | --tw-gradient-to: #f97316 var(--tw-gradient-to-position); | | | to-orange-600 | --tw-gradient-to: #ea580c var(--tw-gradient-to-position); | | | to-orange-700 | --tw-gradient-to: #c2410c var(--tw-gradient-to-position); | | | to-orange-800 | --tw-gradient-to: #9a3412 var(--tw-gradient-to-position); | | | to-orange-900 | --tw-gradient-to: #7c2d12 var(--tw-gradient-to-position); | | | to-orange-950 | --tw-gradient-to: #431407 var(--tw-gradient-to-position); | | | to-amber-50 | --tw-gradient-to: #fffbeb var(--tw-gradient-to-position); | | | to-amber-100 | --tw-gradient-to: #fef3c7 var(--tw-gradient-to-position); | | | to-amber-200 | --tw-gradient-to: #fde68a var(--tw-gradient-to-position); | | | to-amber-300 | --tw-gradient-to: #fcd34d var(--tw-gradient-to-position); | | | to-amber-400 | --tw-gradient-to: #fbbf24 var(--tw-gradient-to-position); | | | to-amber-500 | --tw-gradient-to: #f59e0b var(--tw-gradient-to-position); | | | to-amber-600 | --tw-gradient-to: #d97706 var(--tw-gradient-to-position); | | | to-amber-700 | --tw-gradient-to: #b45309 var(--tw-gradient-to-position); | | | to-amber-800 | --tw-gradient-to: #92400e var(--tw-gradient-to-position); | | | to-amber-900 | --tw-gradient-to: #78350f var(--tw-gradient-to-position); | | | to-amber-950 | --tw-gradient-to: #451a03 var(--tw-gradient-to-position); | | | to-yellow-50 | --tw-gradient-to: #fefce8 var(--tw-gradient-to-position); | | | to-yellow-100 | --tw-gradient-to: #fef9c3 var(--tw-gradient-to-position); | | | to-yellow-200 | --tw-gradient-to: #fef08a var(--tw-gradient-to-position); | | | to-yellow-300 | --tw-gradient-to: #fde047 var(--tw-gradient-to-position); | | | to-yellow-400 | --tw-gradient-to: #facc15 var(--tw-gradient-to-position); | | | to-yellow-500 | --tw-gradient-to: #eab308 var(--tw-gradient-to-position); | | | to-yellow-600 | --tw-gradient-to: #ca8a04 var(--tw-gradient-to-position); | | | to-yellow-700 | --tw-gradient-to: #a16207 var(--tw-gradient-to-position); | | | to-yellow-800 | --tw-gradient-to: #854d0e var(--tw-gradient-to-position); | | | to-yellow-900 | --tw-gradient-to: #713f12 var(--tw-gradient-to-position); | | | to-yellow-950 | --tw-gradient-to: #422006 var(--tw-gradient-to-position); | | | to-lime-50 | --tw-gradient-to: #f7fee7 var(--tw-gradient-to-position); | | | to-lime-100 | --tw-gradient-to: #ecfccb var(--tw-gradient-to-position); | | | to-lime-200 | --tw-gradient-to: #d9f99d var(--tw-gradient-to-position); | | | to-lime-300 | --tw-gradient-to: #bef264 var(--tw-gradient-to-position); | | | to-lime-400 | --tw-gradient-to: #a3e635 var(--tw-gradient-to-position); | | | to-lime-500 | --tw-gradient-to: #84cc16 var(--tw-gradient-to-position); | | | to-lime-600 | --tw-gradient-to: #65a30d var(--tw-gradient-to-position); | | | to-lime-700 | --tw-gradient-to: #4d7c0f var(--tw-gradient-to-position); | | | to-lime-800 | --tw-gradient-to: #3f6212 var(--tw-gradient-to-position); | | | to-lime-900 | --tw-gradient-to: #365314 var(--tw-gradient-to-position); | | | to-lime-950 | --tw-gradient-to: #1a2e05 var(--tw-gradient-to-position); | | | to-green-50 | --tw-gradient-to: #f0fdf4 var(--tw-gradient-to-position); | | | to-green-100 | --tw-gradient-to: #dcfce7 var(--tw-gradient-to-position); | | | to-green-200 | --tw-gradient-to: #bbf7d0 var(--tw-gradient-to-position); | | | to-green-300 | --tw-gradient-to: #86efac var(--tw-gradient-to-position); | | | to-green-400 | --tw-gradient-to: #4ade80 var(--tw-gradient-to-position); | | | to-green-500 | --tw-gradient-to: #22c55e var(--tw-gradient-to-position); | | | to-green-600 | --tw-gradient-to: #16a34a var(--tw-gradient-to-position); | | | to-green-700 | --tw-gradient-to: #15803d var(--tw-gradient-to-position); | | | to-green-800 | --tw-gradient-to: #166534 var(--tw-gradient-to-position); | | | to-green-900 | --tw-gradient-to: #14532d var(--tw-gradient-to-position); | | | to-green-950 | --tw-gradient-to: #052e16 var(--tw-gradient-to-position); | | | to-emerald-50 | --tw-gradient-to: #ecfdf5 var(--tw-gradient-to-position); | | | to-emerald-100 | --tw-gradient-to: #d1fae5 var(--tw-gradient-to-position); | | | to-emerald-200 | --tw-gradient-to: #a7f3d0 var(--tw-gradient-to-position); | | | to-emerald-300 | --tw-gradient-to: #6ee7b7 var(--tw-gradient-to-position); | | | to-emerald-400 | --tw-gradient-to: #34d399 var(--tw-gradient-to-position); | | | to-emerald-500 | --tw-gradient-to: #10b981 var(--tw-gradient-to-position); | | | to-emerald-600 | --tw-gradient-to: #059669 var(--tw-gradient-to-position); | | | to-emerald-700 | --tw-gradient-to: #047857 var(--tw-gradient-to-position); | | | to-emerald-800 | --tw-gradient-to: #065f46 var(--tw-gradient-to-position); | | | to-emerald-900 | --tw-gradient-to: #064e3b var(--tw-gradient-to-position); | | | to-emerald-950 | --tw-gradient-to: #022c22 var(--tw-gradient-to-position); | | | to-teal-50 | --tw-gradient-to: #f0fdfa var(--tw-gradient-to-position); | | | to-teal-100 | --tw-gradient-to: #ccfbf1 var(--tw-gradient-to-position); | | | to-teal-200 | --tw-gradient-to: #99f6e4 var(--tw-gradient-to-position); | | | to-teal-300 | --tw-gradient-to: #5eead4 var(--tw-gradient-to-position); | | | to-teal-400 | --tw-gradient-to: #2dd4bf var(--tw-gradient-to-position); | | | to-teal-500 | --tw-gradient-to: #14b8a6 var(--tw-gradient-to-position); | | | to-teal-600 | --tw-gradient-to: #0d9488 var(--tw-gradient-to-position); | | | to-teal-700 | --tw-gradient-to: #0f766e var(--tw-gradient-to-position); | | | to-teal-800 | --tw-gradient-to: #115e59 var(--tw-gradient-to-position); | | | to-teal-900 | --tw-gradient-to: #134e4a var(--tw-gradient-to-position); | | | to-teal-950 | --tw-gradient-to: #042f2e var(--tw-gradient-to-position); | | | to-cyan-50 | --tw-gradient-to: #ecfeff var(--tw-gradient-to-position); | | | to-cyan-100 | --tw-gradient-to: #cffafe var(--tw-gradient-to-position); | | | to-cyan-200 | --tw-gradient-to: #a5f3fc var(--tw-gradient-to-position); | | | to-cyan-300 | --tw-gradient-to: #67e8f9 var(--tw-gradient-to-position); | | | to-cyan-400 | --tw-gradient-to: #22d3ee var(--tw-gradient-to-position); | | | to-cyan-500 | --tw-gradient-to: #06b6d4 var(--tw-gradient-to-position); | | | to-cyan-600 | --tw-gradient-to: #0891b2 var(--tw-gradient-to-position); | | | to-cyan-700 | --tw-gradient-to: #0e7490 var(--tw-gradient-to-position); | | | to-cyan-800 | --tw-gradient-to: #155e75 var(--tw-gradient-to-position); | | | to-cyan-900 | --tw-gradient-to: #164e63 var(--tw-gradient-to-position); | | | to-cyan-950 | --tw-gradient-to: #083344 var(--tw-gradient-to-position); | | | to-sky-50 | --tw-gradient-to: #f0f9ff var(--tw-gradient-to-position); | | | to-sky-100 | --tw-gradient-to: #e0f2fe var(--tw-gradient-to-position); | | | to-sky-200 | --tw-gradient-to: #bae6fd var(--tw-gradient-to-position); | | | to-sky-300 | --tw-gradient-to: #7dd3fc var(--tw-gradient-to-position); | | | to-sky-400 | --tw-gradient-to: #38bdf8 var(--tw-gradient-to-position); | | | to-sky-500 | --tw-gradient-to: #0ea5e9 var(--tw-gradient-to-position); | | | to-sky-600 | --tw-gradient-to: #0284c7 var(--tw-gradient-to-position); | | | to-sky-700 | --tw-gradient-to: #0369a1 var(--tw-gradient-to-position); | | | to-sky-800 | --tw-gradient-to: #075985 var(--tw-gradient-to-position); | | | to-sky-900 | --tw-gradient-to: #0c4a6e var(--tw-gradient-to-position); | | | to-sky-950 | --tw-gradient-to: #082f49 var(--tw-gradient-to-position); | | | to-blue-50 | --tw-gradient-to: #eff6ff var(--tw-gradient-to-position); | | | to-blue-100 | --tw-gradient-to: #dbeafe var(--tw-gradient-to-position); | | | to-blue-200 | --tw-gradient-to: #bfdbfe var(--tw-gradient-to-position); | | | to-blue-300 | --tw-gradient-to: #93c5fd var(--tw-gradient-to-position); | | | to-blue-400 | --tw-gradient-to: #60a5fa var(--tw-gradient-to-position); | | | to-blue-500 | --tw-gradient-to: #3b82f6 var(--tw-gradient-to-position); | | | to-blue-600 | --tw-gradient-to: #2563eb var(--tw-gradient-to-position); | | | to-blue-700 | --tw-gradient-to: #1d4ed8 var(--tw-gradient-to-position); | | | to-blue-800 | --tw-gradient-to: #1e40af var(--tw-gradient-to-position); | | | to-blue-900 | --tw-gradient-to: #1e3a8a var(--tw-gradient-to-position); | | | to-blue-950 | --tw-gradient-to: #172554 var(--tw-gradient-to-position); | | | to-indigo-50 | --tw-gradient-to: #eef2ff var(--tw-gradient-to-position); | | | to-indigo-100 | --tw-gradient-to: #e0e7ff var(--tw-gradient-to-position); | | | to-indigo-200 | --tw-gradient-to: #c7d2fe var(--tw-gradient-to-position); | | | to-indigo-300 | --tw-gradient-to: #a5b4fc var(--tw-gradient-to-position); | | | to-indigo-400 | --tw-gradient-to: #818cf8 var(--tw-gradient-to-position); | | | to-indigo-500 | --tw-gradient-to: #6366f1 var(--tw-gradient-to-position); | | | to-indigo-600 | --tw-gradient-to: #4f46e5 var(--tw-gradient-to-position); | | | to-indigo-700 | --tw-gradient-to: #4338ca var(--tw-gradient-to-position); | | | to-indigo-800 | --tw-gradient-to: #3730a3 var(--tw-gradient-to-position); | | | to-indigo-900 | --tw-gradient-to: #312e81 var(--tw-gradient-to-position); | | | to-indigo-950 | --tw-gradient-to: #1e1b4b var(--tw-gradient-to-position); | | | to-violet-50 | --tw-gradient-to: #f5f3ff var(--tw-gradient-to-position); | | | to-violet-100 | --tw-gradient-to: #ede9fe var(--tw-gradient-to-position); | | | to-violet-200 | --tw-gradient-to: #ddd6fe var(--tw-gradient-to-position); | | | to-violet-300 | --tw-gradient-to: #c4b5fd var(--tw-gradient-to-position); | | | to-violet-400 | --tw-gradient-to: #a78bfa var(--tw-gradient-to-position); | | | to-violet-500 | --tw-gradient-to: #8b5cf6 var(--tw-gradient-to-position); | | | to-violet-600 | --tw-gradient-to: #7c3aed var(--tw-gradient-to-position); | | | to-violet-700 | --tw-gradient-to: #6d28d9 var(--tw-gradient-to-position); | | | to-violet-800 | --tw-gradient-to: #5b21b6 var(--tw-gradient-to-position); | | | to-violet-900 | --tw-gradient-to: #4c1d95 var(--tw-gradient-to-position); | | | to-violet-950 | --tw-gradient-to: #2e1065 var(--tw-gradient-to-position); | | | to-purple-50 | --tw-gradient-to: #faf5ff var(--tw-gradient-to-position); | | | to-purple-100 | --tw-gradient-to: #f3e8ff var(--tw-gradient-to-position); | | | to-purple-200 | --tw-gradient-to: #e9d5ff var(--tw-gradient-to-position); | | | to-purple-300 | --tw-gradient-to: #d8b4fe var(--tw-gradient-to-position); | | | to-purple-400 | --tw-gradient-to: #c084fc var(--tw-gradient-to-position); | | | to-purple-500 | --tw-gradient-to: #a855f7 var(--tw-gradient-to-position); | | | to-purple-600 | --tw-gradient-to: #9333ea var(--tw-gradient-to-position); | | | to-purple-700 | --tw-gradient-to: #7e22ce var(--tw-gradient-to-position); | | | to-purple-800 | --tw-gradient-to: #6b21a8 var(--tw-gradient-to-position); | | | to-purple-900 | --tw-gradient-to: #581c87 var(--tw-gradient-to-position); | | | to-purple-950 | --tw-gradient-to: #3b0764 var(--tw-gradient-to-position); | | | to-fuchsia-50 | --tw-gradient-to: #fdf4ff var(--tw-gradient-to-position); | | | to-fuchsia-100 | --tw-gradient-to: #fae8ff var(--tw-gradient-to-position); | | | to-fuchsia-200 | --tw-gradient-to: #f5d0fe var(--tw-gradient-to-position); | | | to-fuchsia-300 | --tw-gradient-to: #f0abfc var(--tw-gradient-to-position); | | | to-fuchsia-400 | --tw-gradient-to: #e879f9 var(--tw-gradient-to-position); | | | to-fuchsia-500 | --tw-gradient-to: #d946ef var(--tw-gradient-to-position); | | | to-fuchsia-600 | --tw-gradient-to: #c026d3 var(--tw-gradient-to-position); | | | to-fuchsia-700 | --tw-gradient-to: #a21caf var(--tw-gradient-to-position); | | | to-fuchsia-800 | --tw-gradient-to: #86198f var(--tw-gradient-to-position); | | | to-fuchsia-900 | --tw-gradient-to: #701a75 var(--tw-gradient-to-position); | | | to-fuchsia-950 | --tw-gradient-to: #4a044e var(--tw-gradient-to-position); | | | to-pink-50 | --tw-gradient-to: #fdf2f8 var(--tw-gradient-to-position); | | | to-pink-100 | --tw-gradient-to: #fce7f3 var(--tw-gradient-to-position); | | | to-pink-200 | --tw-gradient-to: #fbcfe8 var(--tw-gradient-to-position); | | | to-pink-300 | --tw-gradient-to: #f9a8d4 var(--tw-gradient-to-position); | | | to-pink-400 | --tw-gradient-to: #f472b6 var(--tw-gradient-to-position); | | | to-pink-500 | --tw-gradient-to: #ec4899 var(--tw-gradient-to-position); | | | to-pink-600 | --tw-gradient-to: #db2777 var(--tw-gradient-to-position); | | | to-pink-700 | --tw-gradient-to: #be185d var(--tw-gradient-to-position); | | | to-pink-800 | --tw-gradient-to: #9d174d var(--tw-gradient-to-position); | | | to-pink-900 | --tw-gradient-to: #831843 var(--tw-gradient-to-position); | | | to-pink-950 | --tw-gradient-to: #500724 var(--tw-gradient-to-position); | | | to-rose-50 | --tw-gradient-to: #fff1f2 var(--tw-gradient-to-position); | | | to-rose-100 | --tw-gradient-to: #ffe4e6 var(--tw-gradient-to-position); | | | to-rose-200 | --tw-gradient-to: #fecdd3 var(--tw-gradient-to-position); | | | to-rose-300 | --tw-gradient-to: #fda4af var(--tw-gradient-to-position); | | | to-rose-400 | --tw-gradient-to: #fb7185 var(--tw-gradient-to-position); | | | to-rose-500 | --tw-gradient-to: #f43f5e var(--tw-gradient-to-position); | | | to-rose-600 | --tw-gradient-to: #e11d48 var(--tw-gradient-to-position); | | | to-rose-700 | --tw-gradient-to: #be123c var(--tw-gradient-to-position); | | | to-rose-800 | --tw-gradient-to: #9f1239 var(--tw-gradient-to-position); | | | to-rose-900 | --tw-gradient-to: #881337 var(--tw-gradient-to-position); | | | to-rose-950 | --tw-gradient-to: #4c0519 var(--tw-gradient-to-position); | | | to-0% | --tw-gradient-to-position: 0%; | | | to-5% | --tw-gradient-to-position: 5%; | | | to-10% | --tw-gradient-to-position: 10%; | | | to-15% | --tw-gradient-to-position: 15%; | | | to-20% | --tw-gradient-to-position: 20%; | | | to-25% | --tw-gradient-to-position: 25%; | | | to-30% | --tw-gradient-to-position: 30%; | | | to-35% | --tw-gradient-to-position: 35%; | | | to-40% | --tw-gradient-to-position: 40%; | | | to-45% | --tw-gradient-to-position: 45%; | | | to-50% | --tw-gradient-to-position: 50%; | | | to-55% | --tw-gradient-to-position: 55%; | | | to-60% | --tw-gradient-to-position: 60%; | | | to-65% | --tw-gradient-to-position: 65%; | | | to-70% | --tw-gradient-to-position: 70%; | | | to-75% | --tw-gradient-to-position: 75%; | | | to-80% | --tw-gradient-to-position: 80%; | | | to-85% | --tw-gradient-to-position: 85%; | | | to-90% | --tw-gradient-to-position: 90%; | | | to-95% | --tw-gradient-to-position: 95%; | | | to-100% | --tw-gradient-to-position: 100%; | | Basic usage ----------- ### Starting color Set the starting color of a gradient using the `from-{color}` utilities. ``` <div class="bg-gradient-to-r from-indigo-500 ..."></div> ``` ### Ending color Set the ending color of a gradient using the `to-{color}` utilities. ``` <div class="bg-gradient-to-r from-cyan-500 to-blue-500 ..."></div> ``` Gradients to **do not** fade in from transparent by default. To fade in from transparent, reverse the gradient direction and use a `from-{color}` utility. ### Middle color Add a middle color to a gradient using the `via-{color}` utilities. ``` <div class="bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 ..."></div> ``` Gradients with a `from-{color}` and `via-{color}` will fade out to transparent by default if no `to-{color}` is present. ### Specifying stop positions For more control over the gradient color stop positions, combine the `from-{position}`, `via-{position}` and `to-{position}` utilities with the gradient color utilities. ``` <div class="bg-gradient-to-r from-indigo-500 from-10% via-sky-500 via-30% to-emerald-500 to-90% ..."></div> ``` ### Fading to transparent Gradients fade out to transparent by default, without requiring you to add `to-transparent` explicitly. Tailwind intelligently calculates the *right* “transparent” value to use based on the starting color to avoid [a bug in Safari < 15.4](https://bugs.webkit.org/show_bug.cgi?id=150940) that causes fading to simply the `transparent` keyword to fade through gray, which just looks awful. Don’t add `to-transparent` explicitly ``` <div class="bg-gradient-to-r from-blue-500 to-transparent"> <!-- ... --> </div> ``` Only specify a from color and fade to transparent automatically ``` <div class="bg-gradient-to-r from-blue-500"> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:from-pink-500` to only apply the `from-pink-500` utility on hover. ``` <button type="button" class="bg-gradient-to-r from-green-400 to-blue-500 hover:from-pink-500 hover:to-yellow-500 ..."> Hover me </button> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:from-yellow-500` to apply the `from-yellow-500` utility at only medium screen sizes and above. ``` <div class="bg-gradient-to-r from-purple-400 md:from-yellow-500"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as gradient colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your gradient colors by editing `theme.gradientColorStops` or `theme.extend.gradientColorStops` in your `tailwind.config.js` file. In addition to the colors, you can also customize the gradient color stop positions by editing `theme.gradientColorStopPositions` or `theme.extend.gradientColorStopPositions`. tailwind.config.js ``` module.exports = { theme: { extend: { gradientColorStopPositions: { 33: '33%', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `from|via|to-{color|position}` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="from-[#243c5a]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/gradient-color-stopsOutline Offset ============== Utilities for controlling the offset of an element's outline. Quick reference --------------- | Class | Properties | | --- | --- | | outline-offset-0 | outline-offset: 0px; | | outline-offset-1 | outline-offset: 1px; | | outline-offset-2 | outline-offset: 2px; | | outline-offset-4 | outline-offset: 4px; | | outline-offset-8 | outline-offset: 8px; | Basic usage ----------- ### Setting the outline offset Use the `outline-{offset}` utilities to change the offset of an element’s outline. ``` <button class="outline outline-offset-0 ...">Button A</button> <button class="outline outline-offset-2 ...">Button B</button> <button class="outline outline-offset-4 ...">Button C</button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:outline-offset-2` to only apply the `outline-offset-2` utility on hover. ``` <button class="outline hover:outline-offset-2"> <!-- ... --> </button``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:outline-offset-2` to apply the `outline-offset-2` utility at only medium screen sizes and above. ``` <button class="outline md:outline-offset-2"> <!-- ... --> </button``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme You can customize the `outline-offset-{width}` utilities by editing `theme.outlineOffset` or `theme.extend.outlineOffset` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { outlineOffset: { 3: '3px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `outline-offset` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <button class="outline-offset-[3px]"> <!-- ... --> </button``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/outline-offsetRing Width ========== Utilities for creating outline rings with box-shadows. Quick reference --------------- | Class | Properties | | --- | --- | | ring-0 | box-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color); | | ring-1 | box-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); | | ring-2 | box-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color); | | ring | box-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color); | | ring-4 | box-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color); | | ring-8 | box-shadow: var(--tw-ring-inset) 0 0 0 calc(8px + var(--tw-ring-offset-width)) var(--tw-ring-color); | | ring-inset | --tw-ring-inset: inset; | Basic usage ----------- ### Adding a ring Use the `ring-{width}` utilities to apply solid box-shadow of a specific thickness to an element. Rings are a semi-transparent blue color by default, similar to the default focus ring style in many systems. ``` <button class="... ring-offset-2 ring-2">Button A</button> <button class="... ring-offset-2 ring">Button B</button> <button class="... ring-offset-2 ring-4">Button C</button> ``` Ring utilities compose gracefully with regular `shadow-{size}` utilities and can be combined on the same element. You can also control the color, opacity, and offset of rings using the [ringColor](ring-color), [ringOpacity](/docs/ring-color#changing-the-opacity), and [ringOffsetWidth](ring-offset-width) utilities. ### Focus rings The ring width utilities make it easy to use custom focus rings by adding `focus:` to the beginning of any `ring-{width}` utility. ``` <button class="... focus:ring-2">Save Changes</button> ``` The `focus` variant is enabled by default for the [ringColor](ring-color), [ringOpacity](/docs/ring-color#changing-the-opacity), [ringOffsetWidth](ring-offset-width), and [ringOffsetColor](ring-offset-color) utilities as well. ### Inset rings Use the `ring-inset` utility to force a ring to render on the inside of an element instead of the outside. This can be useful for elements at the edge of the screen where part of the ring wouldn’t be visible. ``` <button class="... ring-2 ring-pink-300 ring-inset"> Save Changes </button><button class="... ring-2 ring-pink-500 ring-inset"> Save Changes </button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:ring-4` to only apply the `ring-4` utility on hover. ``` <div class="ring-2 hover:ring-4"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:ring-4` to apply the `ring-4` utility at only medium screen sizes and above. ``` <div class="ring-2 md:ring-4"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `ring-width` utilities. You can customize these values by editing `theme.ringWidth` or `theme.extend.ringWidth` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { ringWidth: { '10': '10px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `ring` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="ring-[10px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/ring-widthRing Color ========== Utilities for setting the color of outline rings. Quick reference --------------- | Class | Properties | | --- | --- | | ring-inherit | --tw-ring-color: inherit; | | ring-current | --tw-ring-color: currentColor; | | ring-transparent | --tw-ring-color: transparent; | | ring-black | --tw-ring-color: rgb(0 0 0); | | ring-white | --tw-ring-color: rgb(255 255 255); | | ring-slate-50 | --tw-ring-color: rgb(248 250 252); | | ring-slate-100 | --tw-ring-color: rgb(241 245 249); | | ring-slate-200 | --tw-ring-color: rgb(226 232 240); | | ring-slate-300 | --tw-ring-color: rgb(203 213 225); | | ring-slate-400 | --tw-ring-color: rgb(148 163 184); | | ring-slate-500 | --tw-ring-color: rgb(100 116 139); | | ring-slate-600 | --tw-ring-color: rgb(71 85 105); | | ring-slate-700 | --tw-ring-color: rgb(51 65 85); | | ring-slate-800 | --tw-ring-color: rgb(30 41 59); | | ring-slate-900 | --tw-ring-color: rgb(15 23 42); | | ring-slate-950 | --tw-ring-color: rgb(2 6 23); | | ring-gray-50 | --tw-ring-color: rgb(249 250 251); | | ring-gray-100 | --tw-ring-color: rgb(243 244 246); | | ring-gray-200 | --tw-ring-color: rgb(229 231 235); | | ring-gray-300 | --tw-ring-color: rgb(209 213 219); | | ring-gray-400 | --tw-ring-color: rgb(156 163 175); | | ring-gray-500 | --tw-ring-color: rgb(107 114 128); | | ring-gray-600 | --tw-ring-color: rgb(75 85 99); | | ring-gray-700 | --tw-ring-color: rgb(55 65 81); | | ring-gray-800 | --tw-ring-color: rgb(31 41 55); | | ring-gray-900 | --tw-ring-color: rgb(17 24 39); | | ring-gray-950 | --tw-ring-color: rgb(3 7 18); | | ring-zinc-50 | --tw-ring-color: rgb(250 250 250); | | ring-zinc-100 | --tw-ring-color: rgb(244 244 245); | | ring-zinc-200 | --tw-ring-color: rgb(228 228 231); | | ring-zinc-300 | --tw-ring-color: rgb(212 212 216); | | ring-zinc-400 | --tw-ring-color: rgb(161 161 170); | | ring-zinc-500 | --tw-ring-color: rgb(113 113 122); | | ring-zinc-600 | --tw-ring-color: rgb(82 82 91); | | ring-zinc-700 | --tw-ring-color: rgb(63 63 70); | | ring-zinc-800 | --tw-ring-color: rgb(39 39 42); | | ring-zinc-900 | --tw-ring-color: rgb(24 24 27); | | ring-zinc-950 | --tw-ring-color: rgb(9 9 11); | | ring-neutral-50 | --tw-ring-color: rgb(250 250 250); | | ring-neutral-100 | --tw-ring-color: rgb(245 245 245); | | ring-neutral-200 | --tw-ring-color: rgb(229 229 229); | | ring-neutral-300 | --tw-ring-color: rgb(212 212 212); | | ring-neutral-400 | --tw-ring-color: rgb(163 163 163); | | ring-neutral-500 | --tw-ring-color: rgb(115 115 115); | | ring-neutral-600 | --tw-ring-color: rgb(82 82 82); | | ring-neutral-700 | --tw-ring-color: rgb(64 64 64); | | ring-neutral-800 | --tw-ring-color: rgb(38 38 38); | | ring-neutral-900 | --tw-ring-color: rgb(23 23 23); | | ring-neutral-950 | --tw-ring-color: rgb(10 10 10); | | ring-stone-50 | --tw-ring-color: rgb(250 250 249); | | ring-stone-100 | --tw-ring-color: rgb(245 245 244); | | ring-stone-200 | --tw-ring-color: rgb(231 229 228); | | ring-stone-300 | --tw-ring-color: rgb(214 211 209); | | ring-stone-400 | --tw-ring-color: rgb(168 162 158); | | ring-stone-500 | --tw-ring-color: rgb(120 113 108); | | ring-stone-600 | --tw-ring-color: rgb(87 83 78); | | ring-stone-700 | --tw-ring-color: rgb(68 64 60); | | ring-stone-800 | --tw-ring-color: rgb(41 37 36); | | ring-stone-900 | --tw-ring-color: rgb(28 25 23); | | ring-stone-950 | --tw-ring-color: rgb(12 10 9); | | ring-red-50 | --tw-ring-color: rgb(254 242 242); | | ring-red-100 | --tw-ring-color: rgb(254 226 226); | | ring-red-200 | --tw-ring-color: rgb(254 202 202); | | ring-red-300 | --tw-ring-color: rgb(252 165 165); | | ring-red-400 | --tw-ring-color: rgb(248 113 113); | | ring-red-500 | --tw-ring-color: rgb(239 68 68); | | ring-red-600 | --tw-ring-color: rgb(220 38 38); | | ring-red-700 | --tw-ring-color: rgb(185 28 28); | | ring-red-800 | --tw-ring-color: rgb(153 27 27); | | ring-red-900 | --tw-ring-color: rgb(127 29 29); | | ring-red-950 | --tw-ring-color: rgb(69 10 10); | | ring-orange-50 | --tw-ring-color: rgb(255 247 237); | | ring-orange-100 | --tw-ring-color: rgb(255 237 213); | | ring-orange-200 | --tw-ring-color: rgb(254 215 170); | | ring-orange-300 | --tw-ring-color: rgb(253 186 116); | | ring-orange-400 | --tw-ring-color: rgb(251 146 60); | | ring-orange-500 | --tw-ring-color: rgb(249 115 22); | | ring-orange-600 | --tw-ring-color: rgb(234 88 12); | | ring-orange-700 | --tw-ring-color: rgb(194 65 12); | | ring-orange-800 | --tw-ring-color: rgb(154 52 18); | | ring-orange-900 | --tw-ring-color: rgb(124 45 18); | | ring-orange-950 | --tw-ring-color: rgb(67 20 7); | | ring-amber-50 | --tw-ring-color: rgb(255 251 235); | | ring-amber-100 | --tw-ring-color: rgb(254 243 199); | | ring-amber-200 | --tw-ring-color: rgb(253 230 138); | | ring-amber-300 | --tw-ring-color: rgb(252 211 77); | | ring-amber-400 | --tw-ring-color: rgb(251 191 36); | | ring-amber-500 | --tw-ring-color: rgb(245 158 11); | | ring-amber-600 | --tw-ring-color: rgb(217 119 6); | | ring-amber-700 | --tw-ring-color: rgb(180 83 9); | | ring-amber-800 | --tw-ring-color: rgb(146 64 14); | | ring-amber-900 | --tw-ring-color: rgb(120 53 15); | | ring-amber-950 | --tw-ring-color: rgb(69 26 3); | | ring-yellow-50 | --tw-ring-color: rgb(254 252 232); | | ring-yellow-100 | --tw-ring-color: rgb(254 249 195); | | ring-yellow-200 | --tw-ring-color: rgb(254 240 138); | | ring-yellow-300 | --tw-ring-color: rgb(253 224 71); | | ring-yellow-400 | --tw-ring-color: rgb(250 204 21); | | ring-yellow-500 | --tw-ring-color: rgb(234 179 8); | | ring-yellow-600 | --tw-ring-color: rgb(202 138 4); | | ring-yellow-700 | --tw-ring-color: rgb(161 98 7); | | ring-yellow-800 | --tw-ring-color: rgb(133 77 14); | | ring-yellow-900 | --tw-ring-color: rgb(113 63 18); | | ring-yellow-950 | --tw-ring-color: rgb(66 32 6); | | ring-lime-50 | --tw-ring-color: rgb(247 254 231); | | ring-lime-100 | --tw-ring-color: rgb(236 252 203); | | ring-lime-200 | --tw-ring-color: rgb(217 249 157); | | ring-lime-300 | --tw-ring-color: rgb(190 242 100); | | ring-lime-400 | --tw-ring-color: rgb(163 230 53); | | ring-lime-500 | --tw-ring-color: rgb(132 204 22); | | ring-lime-600 | --tw-ring-color: rgb(101 163 13); | | ring-lime-700 | --tw-ring-color: rgb(77 124 15); | | ring-lime-800 | --tw-ring-color: rgb(63 98 18); | | ring-lime-900 | --tw-ring-color: rgb(54 83 20); | | ring-lime-950 | --tw-ring-color: rgb(26 46 5); | | ring-green-50 | --tw-ring-color: rgb(240 253 244); | | ring-green-100 | --tw-ring-color: rgb(220 252 231); | | ring-green-200 | --tw-ring-color: rgb(187 247 208); | | ring-green-300 | --tw-ring-color: rgb(134 239 172); | | ring-green-400 | --tw-ring-color: rgb(74 222 128); | | ring-green-500 | --tw-ring-color: rgb(34 197 94); | | ring-green-600 | --tw-ring-color: rgb(22 163 74); | | ring-green-700 | --tw-ring-color: rgb(21 128 61); | | ring-green-800 | --tw-ring-color: rgb(22 101 52); | | ring-green-900 | --tw-ring-color: rgb(20 83 45); | | ring-green-950 | --tw-ring-color: rgb(5 46 22); | | ring-emerald-50 | --tw-ring-color: rgb(236 253 245); | | ring-emerald-100 | --tw-ring-color: rgb(209 250 229); | | ring-emerald-200 | --tw-ring-color: rgb(167 243 208); | | ring-emerald-300 | --tw-ring-color: rgb(110 231 183); | | ring-emerald-400 | --tw-ring-color: rgb(52 211 153); | | ring-emerald-500 | --tw-ring-color: rgb(16 185 129); | | ring-emerald-600 | --tw-ring-color: rgb(5 150 105); | | ring-emerald-700 | --tw-ring-color: rgb(4 120 87); | | ring-emerald-800 | --tw-ring-color: rgb(6 95 70); | | ring-emerald-900 | --tw-ring-color: rgb(6 78 59); | | ring-emerald-950 | --tw-ring-color: rgb(2 44 34); | | ring-teal-50 | --tw-ring-color: rgb(240 253 250); | | ring-teal-100 | --tw-ring-color: rgb(204 251 241); | | ring-teal-200 | --tw-ring-color: rgb(153 246 228); | | ring-teal-300 | --tw-ring-color: rgb(94 234 212); | | ring-teal-400 | --tw-ring-color: rgb(45 212 191); | | ring-teal-500 | --tw-ring-color: rgb(20 184 166); | | ring-teal-600 | --tw-ring-color: rgb(13 148 136); | | ring-teal-700 | --tw-ring-color: rgb(15 118 110); | | ring-teal-800 | --tw-ring-color: rgb(17 94 89); | | ring-teal-900 | --tw-ring-color: rgb(19 78 74); | | ring-teal-950 | --tw-ring-color: rgb(4 47 46); | | ring-cyan-50 | --tw-ring-color: rgb(236 254 255); | | ring-cyan-100 | --tw-ring-color: rgb(207 250 254); | | ring-cyan-200 | --tw-ring-color: rgb(165 243 252); | | ring-cyan-300 | --tw-ring-color: rgb(103 232 249); | | ring-cyan-400 | --tw-ring-color: rgb(34 211 238); | | ring-cyan-500 | --tw-ring-color: rgb(6 182 212); | | ring-cyan-600 | --tw-ring-color: rgb(8 145 178); | | ring-cyan-700 | --tw-ring-color: rgb(14 116 144); | | ring-cyan-800 | --tw-ring-color: rgb(21 94 117); | | ring-cyan-900 | --tw-ring-color: rgb(22 78 99); | | ring-cyan-950 | --tw-ring-color: rgb(8 51 68); | | ring-sky-50 | --tw-ring-color: rgb(240 249 255); | | ring-sky-100 | --tw-ring-color: rgb(224 242 254); | | ring-sky-200 | --tw-ring-color: rgb(186 230 253); | | ring-sky-300 | --tw-ring-color: rgb(125 211 252); | | ring-sky-400 | --tw-ring-color: rgb(56 189 248); | | ring-sky-500 | --tw-ring-color: rgb(14 165 233); | | ring-sky-600 | --tw-ring-color: rgb(2 132 199); | | ring-sky-700 | --tw-ring-color: rgb(3 105 161); | | ring-sky-800 | --tw-ring-color: rgb(7 89 133); | | ring-sky-900 | --tw-ring-color: rgb(12 74 110); | | ring-sky-950 | --tw-ring-color: rgb(8 47 73); | | ring-blue-50 | --tw-ring-color: rgb(239 246 255); | | ring-blue-100 | --tw-ring-color: rgb(219 234 254); | | ring-blue-200 | --tw-ring-color: rgb(191 219 254); | | ring-blue-300 | --tw-ring-color: rgb(147 197 253); | | ring-blue-400 | --tw-ring-color: rgb(96 165 250); | | ring-blue-500 | --tw-ring-color: rgb(59 130 246); | | ring-blue-600 | --tw-ring-color: rgb(37 99 235); | | ring-blue-700 | --tw-ring-color: rgb(29 78 216); | | ring-blue-800 | --tw-ring-color: rgb(30 64 175); | | ring-blue-900 | --tw-ring-color: rgb(30 58 138); | | ring-blue-950 | --tw-ring-color: rgb(23 37 84); | | ring-indigo-50 | --tw-ring-color: rgb(238 242 255); | | ring-indigo-100 | --tw-ring-color: rgb(224 231 255); | | ring-indigo-200 | --tw-ring-color: rgb(199 210 254); | | ring-indigo-300 | --tw-ring-color: rgb(165 180 252); | | ring-indigo-400 | --tw-ring-color: rgb(129 140 248); | | ring-indigo-500 | --tw-ring-color: rgb(99 102 241); | | ring-indigo-600 | --tw-ring-color: rgb(79 70 229); | | ring-indigo-700 | --tw-ring-color: rgb(67 56 202); | | ring-indigo-800 | --tw-ring-color: rgb(55 48 163); | | ring-indigo-900 | --tw-ring-color: rgb(49 46 129); | | ring-indigo-950 | --tw-ring-color: rgb(30 27 75); | | ring-violet-50 | --tw-ring-color: rgb(245 243 255); | | ring-violet-100 | --tw-ring-color: rgb(237 233 254); | | ring-violet-200 | --tw-ring-color: rgb(221 214 254); | | ring-violet-300 | --tw-ring-color: rgb(196 181 253); | | ring-violet-400 | --tw-ring-color: rgb(167 139 250); | | ring-violet-500 | --tw-ring-color: rgb(139 92 246); | | ring-violet-600 | --tw-ring-color: rgb(124 58 237); | | ring-violet-700 | --tw-ring-color: rgb(109 40 217); | | ring-violet-800 | --tw-ring-color: rgb(91 33 182); | | ring-violet-900 | --tw-ring-color: rgb(76 29 149); | | ring-violet-950 | --tw-ring-color: rgb(46 16 101); | | ring-purple-50 | --tw-ring-color: rgb(250 245 255); | | ring-purple-100 | --tw-ring-color: rgb(243 232 255); | | ring-purple-200 | --tw-ring-color: rgb(233 213 255); | | ring-purple-300 | --tw-ring-color: rgb(216 180 254); | | ring-purple-400 | --tw-ring-color: rgb(192 132 252); | | ring-purple-500 | --tw-ring-color: rgb(168 85 247); | | ring-purple-600 | --tw-ring-color: rgb(147 51 234); | | ring-purple-700 | --tw-ring-color: rgb(126 34 206); | | ring-purple-800 | --tw-ring-color: rgb(107 33 168); | | ring-purple-900 | --tw-ring-color: rgb(88 28 135); | | ring-purple-950 | --tw-ring-color: rgb(59 7 100); | | ring-fuchsia-50 | --tw-ring-color: rgb(253 244 255); | | ring-fuchsia-100 | --tw-ring-color: rgb(250 232 255); | | ring-fuchsia-200 | --tw-ring-color: rgb(245 208 254); | | ring-fuchsia-300 | --tw-ring-color: rgb(240 171 252); | | ring-fuchsia-400 | --tw-ring-color: rgb(232 121 249); | | ring-fuchsia-500 | --tw-ring-color: rgb(217 70 239); | | ring-fuchsia-600 | --tw-ring-color: rgb(192 38 211); | | ring-fuchsia-700 | --tw-ring-color: rgb(162 28 175); | | ring-fuchsia-800 | --tw-ring-color: rgb(134 25 143); | | ring-fuchsia-900 | --tw-ring-color: rgb(112 26 117); | | ring-fuchsia-950 | --tw-ring-color: rgb(74 4 78); | | ring-pink-50 | --tw-ring-color: rgb(253 242 248); | | ring-pink-100 | --tw-ring-color: rgb(252 231 243); | | ring-pink-200 | --tw-ring-color: rgb(251 207 232); | | ring-pink-300 | --tw-ring-color: rgb(249 168 212); | | ring-pink-400 | --tw-ring-color: rgb(244 114 182); | | ring-pink-500 | --tw-ring-color: rgb(236 72 153); | | ring-pink-600 | --tw-ring-color: rgb(219 39 119); | | ring-pink-700 | --tw-ring-color: rgb(190 24 93); | | ring-pink-800 | --tw-ring-color: rgb(157 23 77); | | ring-pink-900 | --tw-ring-color: rgb(131 24 67); | | ring-pink-950 | --tw-ring-color: rgb(80 7 36); | | ring-rose-50 | --tw-ring-color: rgb(255 241 242); | | ring-rose-100 | --tw-ring-color: rgb(255 228 230); | | ring-rose-200 | --tw-ring-color: rgb(254 205 211); | | ring-rose-300 | --tw-ring-color: rgb(253 164 175); | | ring-rose-400 | --tw-ring-color: rgb(251 113 133); | | ring-rose-500 | --tw-ring-color: rgb(244 63 94); | | ring-rose-600 | --tw-ring-color: rgb(225 29 72); | | ring-rose-700 | --tw-ring-color: rgb(190 18 60); | | ring-rose-800 | --tw-ring-color: rgb(159 18 57); | | ring-rose-900 | --tw-ring-color: rgb(136 19 55); | | ring-rose-950 | --tw-ring-color: rgb(76 5 25); | Basic usage ----------- ### Setting the ring color Use the `ring-{color}` utilities to set the color of an [outline ring](ring-width). ``` <button class="... ring-2 ring-blue-500"> Create account </button> ``` ### Changing the opacity Control the opacity of an element’s background color using the color opacity modifier. ``` <button class="... ring-2 ring-blue-500/50">Subscribe</button> ``` You can use any value defined in your [opacity scale](opacity), or use arbitrary values if you need to deviate from your design tokens. ``` <button class="... ring-2 ring-blue-500/[.55]">Subscribe</button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:ring-blue-500` to only apply the `ring-blue-500` utility on hover. ``` <div class="ring ring-blue-300 hover:ring-blue-500"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:ring-blue-500` to apply the `ring-blue-500` utility at only medium screen sizes and above. ``` <div class="ring ring-blue-300 md:ring-blue-500"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as ring colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your ring colors by editing `theme.ringColor` or `theme.extend.ringColor` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `ring-{color}` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="ring-[#50d71e]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/ring-colorRing Offset Width ================= Utilities for simulating an offset when adding outline rings. Quick reference --------------- | Class | Properties | | --- | --- | | ring-offset-0 | --tw-ring-offset-width: 0px; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-1 | --tw-ring-offset-width: 1px; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-2 | --tw-ring-offset-width: 2px; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-4 | --tw-ring-offset-width: 4px; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-8 | --tw-ring-offset-width: 8px; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | Basic usage ----------- ### Setting the ring offset width Use the `ring-offset-{width}` utilities to simulate an offset by adding solid white box-shadow and increasing the thickness of the accompanying outline ring to accommodate the offset. ``` <button class="... ring ring-pink-500 ring-offset-0">Button A</button> <button class="... ring ring-pink-500 ring-offset-2">Button B</button> <button class="... ring ring-pink-500 ring-offset-4">Button C</button> ``` ### Changing the offset color You can’t actually offset a box-shadow in CSS, so we have to fake it using a solid color shadow that matches the parent background color. We use white by default, but if you are adding a ring offset over a different background color, you should use the `ring-offset-{color}` utilities to match the parent background color: ``` <button class="ring ring-pink-500 ring-offset-2 ring-offset-slate-50 dark:ring-offset-slate-900 ..."> Save Changes </button> ``` For more information, see the [ring offset color](ring-offset-color) documentation. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:ring-offset-4` to only apply the `ring-offset-4` utility on hover. ``` <button class="ring-2 ring-offset-2 hover:ring-offset-4"> <!-- ... --> </button``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:ring-offset-4` to apply the `ring-offset-4` utility at only medium screen sizes and above. ``` <button class="ring-2 ring-offset-2 md:ring-offset-4"> <!-- ... --> </button``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme To customize which ring offset width utilities are generated, add your custom values under `ringOffsetWidth` key in the `theme` section of your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { ringOffsetWidth: { '3': '3px', '6': '6px', '10': '10px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `ring-offset` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="ring-offset-[3px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/ring-offset-widthRing Offset Color ================= Utilities for setting the color of outline ring offsets. Quick reference --------------- | Class | Properties | | --- | --- | | ring-offset-inherit | --tw-ring-offset-color: inherit; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-current | --tw-ring-offset-color: currentColor; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-transparent | --tw-ring-offset-color: transparent; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-black | --tw-ring-offset-color: #000; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-white | --tw-ring-offset-color: #fff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-slate-50 | --tw-ring-offset-color: #f8fafc; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-slate-100 | --tw-ring-offset-color: #f1f5f9; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-slate-200 | --tw-ring-offset-color: #e2e8f0; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-slate-300 | --tw-ring-offset-color: #cbd5e1; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-slate-400 | --tw-ring-offset-color: #94a3b8; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-slate-500 | --tw-ring-offset-color: #64748b; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-slate-600 | --tw-ring-offset-color: #475569; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-slate-700 | --tw-ring-offset-color: #334155; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-slate-800 | --tw-ring-offset-color: #1e293b; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-slate-900 | --tw-ring-offset-color: #0f172a; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-slate-950 | --tw-ring-offset-color: #020617; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-gray-50 | --tw-ring-offset-color: #f9fafb; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-gray-100 | --tw-ring-offset-color: #f3f4f6; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-gray-200 | --tw-ring-offset-color: #e5e7eb; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-gray-300 | --tw-ring-offset-color: #d1d5db; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-gray-400 | --tw-ring-offset-color: #9ca3af; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-gray-500 | --tw-ring-offset-color: #6b7280; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-gray-600 | --tw-ring-offset-color: #4b5563; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-gray-700 | --tw-ring-offset-color: #374151; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-gray-800 | --tw-ring-offset-color: #1f2937; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-gray-900 | --tw-ring-offset-color: #111827; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-gray-950 | --tw-ring-offset-color: #030712; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-zinc-50 | --tw-ring-offset-color: #fafafa; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-zinc-100 | --tw-ring-offset-color: #f4f4f5; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-zinc-200 | --tw-ring-offset-color: #e4e4e7; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-zinc-300 | --tw-ring-offset-color: #d4d4d8; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-zinc-400 | --tw-ring-offset-color: #a1a1aa; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-zinc-500 | --tw-ring-offset-color: #71717a; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-zinc-600 | --tw-ring-offset-color: #52525b; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-zinc-700 | --tw-ring-offset-color: #3f3f46; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-zinc-800 | --tw-ring-offset-color: #27272a; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-zinc-900 | --tw-ring-offset-color: #18181b; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-zinc-950 | --tw-ring-offset-color: #09090b; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-neutral-50 | --tw-ring-offset-color: #fafafa; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-neutral-100 | --tw-ring-offset-color: #f5f5f5; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-neutral-200 | --tw-ring-offset-color: #e5e5e5; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-neutral-300 | --tw-ring-offset-color: #d4d4d4; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-neutral-400 | --tw-ring-offset-color: #a3a3a3; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-neutral-500 | --tw-ring-offset-color: #737373; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-neutral-600 | --tw-ring-offset-color: #525252; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-neutral-700 | --tw-ring-offset-color: #404040; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-neutral-800 | --tw-ring-offset-color: #262626; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-neutral-900 | --tw-ring-offset-color: #171717; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-neutral-950 | --tw-ring-offset-color: #0a0a0a; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-stone-50 | --tw-ring-offset-color: #fafaf9; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-stone-100 | --tw-ring-offset-color: #f5f5f4; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-stone-200 | --tw-ring-offset-color: #e7e5e4; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-stone-300 | --tw-ring-offset-color: #d6d3d1; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-stone-400 | --tw-ring-offset-color: #a8a29e; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-stone-500 | --tw-ring-offset-color: #78716c; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-stone-600 | --tw-ring-offset-color: #57534e; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-stone-700 | --tw-ring-offset-color: #44403c; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-stone-800 | --tw-ring-offset-color: #292524; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-stone-900 | --tw-ring-offset-color: #1c1917; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-stone-950 | --tw-ring-offset-color: #0c0a09; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-red-50 | --tw-ring-offset-color: #fef2f2; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-red-100 | --tw-ring-offset-color: #fee2e2; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-red-200 | --tw-ring-offset-color: #fecaca; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-red-300 | --tw-ring-offset-color: #fca5a5; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-red-400 | --tw-ring-offset-color: #f87171; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-red-500 | --tw-ring-offset-color: #ef4444; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-red-600 | --tw-ring-offset-color: #dc2626; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-red-700 | --tw-ring-offset-color: #b91c1c; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-red-800 | --tw-ring-offset-color: #991b1b; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-red-900 | --tw-ring-offset-color: #7f1d1d; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-red-950 | --tw-ring-offset-color: #450a0a; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-orange-50 | --tw-ring-offset-color: #fff7ed; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-orange-100 | --tw-ring-offset-color: #ffedd5; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-orange-200 | --tw-ring-offset-color: #fed7aa; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-orange-300 | --tw-ring-offset-color: #fdba74; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-orange-400 | --tw-ring-offset-color: #fb923c; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-orange-500 | --tw-ring-offset-color: #f97316; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-orange-600 | --tw-ring-offset-color: #ea580c; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-orange-700 | --tw-ring-offset-color: #c2410c; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-orange-800 | --tw-ring-offset-color: #9a3412; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-orange-900 | --tw-ring-offset-color: #7c2d12; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-orange-950 | --tw-ring-offset-color: #431407; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-amber-50 | --tw-ring-offset-color: #fffbeb; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-amber-100 | --tw-ring-offset-color: #fef3c7; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-amber-200 | --tw-ring-offset-color: #fde68a; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-amber-300 | --tw-ring-offset-color: #fcd34d; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-amber-400 | --tw-ring-offset-color: #fbbf24; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-amber-500 | --tw-ring-offset-color: #f59e0b; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-amber-600 | --tw-ring-offset-color: #d97706; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-amber-700 | --tw-ring-offset-color: #b45309; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-amber-800 | --tw-ring-offset-color: #92400e; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-amber-900 | --tw-ring-offset-color: #78350f; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-amber-950 | --tw-ring-offset-color: #451a03; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-yellow-50 | --tw-ring-offset-color: #fefce8; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-yellow-100 | --tw-ring-offset-color: #fef9c3; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-yellow-200 | --tw-ring-offset-color: #fef08a; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-yellow-300 | --tw-ring-offset-color: #fde047; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-yellow-400 | --tw-ring-offset-color: #facc15; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-yellow-500 | --tw-ring-offset-color: #eab308; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-yellow-600 | --tw-ring-offset-color: #ca8a04; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-yellow-700 | --tw-ring-offset-color: #a16207; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-yellow-800 | --tw-ring-offset-color: #854d0e; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-yellow-900 | --tw-ring-offset-color: #713f12; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-yellow-950 | --tw-ring-offset-color: #422006; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-lime-50 | --tw-ring-offset-color: #f7fee7; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-lime-100 | --tw-ring-offset-color: #ecfccb; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-lime-200 | --tw-ring-offset-color: #d9f99d; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-lime-300 | --tw-ring-offset-color: #bef264; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-lime-400 | --tw-ring-offset-color: #a3e635; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-lime-500 | --tw-ring-offset-color: #84cc16; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-lime-600 | --tw-ring-offset-color: #65a30d; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-lime-700 | --tw-ring-offset-color: #4d7c0f; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-lime-800 | --tw-ring-offset-color: #3f6212; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-lime-900 | --tw-ring-offset-color: #365314; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-lime-950 | --tw-ring-offset-color: #1a2e05; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-green-50 | --tw-ring-offset-color: #f0fdf4; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-green-100 | --tw-ring-offset-color: #dcfce7; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-green-200 | --tw-ring-offset-color: #bbf7d0; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-green-300 | --tw-ring-offset-color: #86efac; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-green-400 | --tw-ring-offset-color: #4ade80; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-green-500 | --tw-ring-offset-color: #22c55e; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-green-600 | --tw-ring-offset-color: #16a34a; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-green-700 | --tw-ring-offset-color: #15803d; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-green-800 | --tw-ring-offset-color: #166534; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-green-900 | --tw-ring-offset-color: #14532d; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-green-950 | --tw-ring-offset-color: #052e16; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-emerald-50 | --tw-ring-offset-color: #ecfdf5; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-emerald-100 | --tw-ring-offset-color: #d1fae5; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-emerald-200 | --tw-ring-offset-color: #a7f3d0; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-emerald-300 | --tw-ring-offset-color: #6ee7b7; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-emerald-400 | --tw-ring-offset-color: #34d399; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-emerald-500 | --tw-ring-offset-color: #10b981; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-emerald-600 | --tw-ring-offset-color: #059669; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-emerald-700 | --tw-ring-offset-color: #047857; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-emerald-800 | --tw-ring-offset-color: #065f46; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-emerald-900 | --tw-ring-offset-color: #064e3b; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-emerald-950 | --tw-ring-offset-color: #022c22; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-teal-50 | --tw-ring-offset-color: #f0fdfa; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-teal-100 | --tw-ring-offset-color: #ccfbf1; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-teal-200 | --tw-ring-offset-color: #99f6e4; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-teal-300 | --tw-ring-offset-color: #5eead4; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-teal-400 | --tw-ring-offset-color: #2dd4bf; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-teal-500 | --tw-ring-offset-color: #14b8a6; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-teal-600 | --tw-ring-offset-color: #0d9488; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-teal-700 | --tw-ring-offset-color: #0f766e; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-teal-800 | --tw-ring-offset-color: #115e59; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-teal-900 | --tw-ring-offset-color: #134e4a; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-teal-950 | --tw-ring-offset-color: #042f2e; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-cyan-50 | --tw-ring-offset-color: #ecfeff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-cyan-100 | --tw-ring-offset-color: #cffafe; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-cyan-200 | --tw-ring-offset-color: #a5f3fc; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-cyan-300 | --tw-ring-offset-color: #67e8f9; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-cyan-400 | --tw-ring-offset-color: #22d3ee; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-cyan-500 | --tw-ring-offset-color: #06b6d4; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-cyan-600 | --tw-ring-offset-color: #0891b2; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-cyan-700 | --tw-ring-offset-color: #0e7490; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-cyan-800 | --tw-ring-offset-color: #155e75; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-cyan-900 | --tw-ring-offset-color: #164e63; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-cyan-950 | --tw-ring-offset-color: #083344; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-sky-50 | --tw-ring-offset-color: #f0f9ff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-sky-100 | --tw-ring-offset-color: #e0f2fe; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-sky-200 | --tw-ring-offset-color: #bae6fd; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-sky-300 | --tw-ring-offset-color: #7dd3fc; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-sky-400 | --tw-ring-offset-color: #38bdf8; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-sky-500 | --tw-ring-offset-color: #0ea5e9; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-sky-600 | --tw-ring-offset-color: #0284c7; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-sky-700 | --tw-ring-offset-color: #0369a1; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-sky-800 | --tw-ring-offset-color: #075985; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-sky-900 | --tw-ring-offset-color: #0c4a6e; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-sky-950 | --tw-ring-offset-color: #082f49; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-blue-50 | --tw-ring-offset-color: #eff6ff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-blue-100 | --tw-ring-offset-color: #dbeafe; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-blue-200 | --tw-ring-offset-color: #bfdbfe; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-blue-300 | --tw-ring-offset-color: #93c5fd; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-blue-400 | --tw-ring-offset-color: #60a5fa; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-blue-500 | --tw-ring-offset-color: #3b82f6; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-blue-600 | --tw-ring-offset-color: #2563eb; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-blue-700 | --tw-ring-offset-color: #1d4ed8; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-blue-800 | --tw-ring-offset-color: #1e40af; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-blue-900 | --tw-ring-offset-color: #1e3a8a; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-blue-950 | --tw-ring-offset-color: #172554; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-indigo-50 | --tw-ring-offset-color: #eef2ff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-indigo-100 | --tw-ring-offset-color: #e0e7ff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-indigo-200 | --tw-ring-offset-color: #c7d2fe; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-indigo-300 | --tw-ring-offset-color: #a5b4fc; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-indigo-400 | --tw-ring-offset-color: #818cf8; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-indigo-500 | --tw-ring-offset-color: #6366f1; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-indigo-600 | --tw-ring-offset-color: #4f46e5; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-indigo-700 | --tw-ring-offset-color: #4338ca; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-indigo-800 | --tw-ring-offset-color: #3730a3; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-indigo-900 | --tw-ring-offset-color: #312e81; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-indigo-950 | --tw-ring-offset-color: #1e1b4b; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-violet-50 | --tw-ring-offset-color: #f5f3ff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-violet-100 | --tw-ring-offset-color: #ede9fe; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-violet-200 | --tw-ring-offset-color: #ddd6fe; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-violet-300 | --tw-ring-offset-color: #c4b5fd; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-violet-400 | --tw-ring-offset-color: #a78bfa; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-violet-500 | --tw-ring-offset-color: #8b5cf6; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-violet-600 | --tw-ring-offset-color: #7c3aed; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-violet-700 | --tw-ring-offset-color: #6d28d9; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-violet-800 | --tw-ring-offset-color: #5b21b6; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-violet-900 | --tw-ring-offset-color: #4c1d95; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-violet-950 | --tw-ring-offset-color: #2e1065; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-purple-50 | --tw-ring-offset-color: #faf5ff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-purple-100 | --tw-ring-offset-color: #f3e8ff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-purple-200 | --tw-ring-offset-color: #e9d5ff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-purple-300 | --tw-ring-offset-color: #d8b4fe; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-purple-400 | --tw-ring-offset-color: #c084fc; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-purple-500 | --tw-ring-offset-color: #a855f7; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-purple-600 | --tw-ring-offset-color: #9333ea; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-purple-700 | --tw-ring-offset-color: #7e22ce; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-purple-800 | --tw-ring-offset-color: #6b21a8; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-purple-900 | --tw-ring-offset-color: #581c87; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-purple-950 | --tw-ring-offset-color: #3b0764; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-fuchsia-50 | --tw-ring-offset-color: #fdf4ff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-fuchsia-100 | --tw-ring-offset-color: #fae8ff; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-fuchsia-200 | --tw-ring-offset-color: #f5d0fe; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-fuchsia-300 | --tw-ring-offset-color: #f0abfc; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-fuchsia-400 | --tw-ring-offset-color: #e879f9; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-fuchsia-500 | --tw-ring-offset-color: #d946ef; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-fuchsia-600 | --tw-ring-offset-color: #c026d3; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-fuchsia-700 | --tw-ring-offset-color: #a21caf; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-fuchsia-800 | --tw-ring-offset-color: #86198f; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-fuchsia-900 | --tw-ring-offset-color: #701a75; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-fuchsia-950 | --tw-ring-offset-color: #4a044e; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-pink-50 | --tw-ring-offset-color: #fdf2f8; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-pink-100 | --tw-ring-offset-color: #fce7f3; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-pink-200 | --tw-ring-offset-color: #fbcfe8; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-pink-300 | --tw-ring-offset-color: #f9a8d4; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-pink-400 | --tw-ring-offset-color: #f472b6; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-pink-500 | --tw-ring-offset-color: #ec4899; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-pink-600 | --tw-ring-offset-color: #db2777; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-pink-700 | --tw-ring-offset-color: #be185d; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-pink-800 | --tw-ring-offset-color: #9d174d; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-pink-900 | --tw-ring-offset-color: #831843; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-pink-950 | --tw-ring-offset-color: #500724; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-rose-50 | --tw-ring-offset-color: #fff1f2; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-rose-100 | --tw-ring-offset-color: #ffe4e6; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-rose-200 | --tw-ring-offset-color: #fecdd3; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-rose-300 | --tw-ring-offset-color: #fda4af; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-rose-400 | --tw-ring-offset-color: #fb7185; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-rose-500 | --tw-ring-offset-color: #f43f5e; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-rose-600 | --tw-ring-offset-color: #e11d48; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-rose-700 | --tw-ring-offset-color: #be123c; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-rose-800 | --tw-ring-offset-color: #9f1239; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-rose-900 | --tw-ring-offset-color: #881337; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | | ring-offset-rose-950 | --tw-ring-offset-color: #4c0519; box-shadow: 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color), var(--tw-ring-shadow); | Basic usage ----------- ### Setting the ring offset color Use the `ring-offset-{color}` utilities to change the color of a ring offset. Usually this is done to try and match the offset to the parent background color, since true box-shadow offsets aren’t actually possible in CSS. ``` <button class="ring-2 ring-purple-500 ring-offset-4 ring-offset-slate-50 dark:ring-offset-slate-900 ..."> Save Changes </button> ``` ### Changing the opacity Control the opacity of an element’s ring offset color using the color opacity modifier. ``` <button class="ring-2 ring-purple-500 ring-offset-4 ring-offset-purple-100/50"></button> ``` You can use any value defined in your [opacity scale](opacity), or use arbitrary values if you need to deviate from your design tokens. ``` <button class="ring-2 ring-purple-500 ring-offset-4 ring-offset-purple-100/[.55]"></button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:ring-offset-blue-500` to only apply the `ring-offset-blue-500` utility on hover. ``` <div class="ring-2 ring-offset-2 ring-offset-blue-300 hover:ring-offset-blue-500"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:ring-offset-blue-500` to apply the `ring-offset-blue-500` utility at only medium screen sizes and above. ``` <div class="ring-2 ring-offset-2 ring-offset-blue-300 md:ring-offset-blue-500"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as ring offset color colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your ring offset color colors by editing `theme.ringOffsetColor` or `theme.extend.ringOffsetColor` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `ring-offset-{color}` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="ring-offset-[#50d71e]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/ring-offset-colorBox Shadow ========== Utilities for controlling the box shadow of an element. Quick reference --------------- | Class | Properties | | --- | --- | | shadow-sm | box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); | | shadow | box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1); | | shadow-md | box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); | | shadow-lg | box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); | | shadow-xl | box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1); | | shadow-2xl | box-shadow: 0 25px 50px -12px rgb(0 0 0 / 0.25); | | shadow-inner | box-shadow: inset 0 2px 4px 0 rgb(0 0 0 / 0.05); | | shadow-none | box-shadow: 0 0 #0000; | Basic usage ----------- ### Adding an outer shadow Use the `shadow-sm`, `shadow`, `shadow-md`, `shadow-lg`, `shadow-xl`, or `shadow-2xl` utilities to apply different sized outer box shadows to an element. ``` <div class="shadow-md ..."></div> <div class="shadow-lg ..."></div> <div class="shadow-xl ..."></div> <div class="shadow-2xl ..."></div> ``` ### Adding an inner shadow Use the `shadow-inner` utility to apply a subtle inset box shadow to an element. This can be useful for things like form controls or wells. ``` <div class="shadow-inner ..."></div> ``` ### Removing the shadow Use `shadow-none` to remove an existing box shadow from an element. This is most commonly used to remove a shadow that was applied at a smaller breakpoint. ``` <div class="shadow-none ..."></div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:shadow-lg` to only apply the `shadow-lg` utility on hover. ``` <div class="shadow hover:shadow-lg"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:shadow-lg` to apply the `shadow-lg` utility at only medium screen sizes and above. ``` <div class="shadow md:shadow-lg"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides six drop shadow utilities, one inner shadow utility, and a utility for removing existing shadows. You can customize these values by editing `theme.boxShadow` or `theme.extend.boxShadow` in your `tailwind.config.js` file. If a `DEFAULT` shadow is provided, it will be used for the non-suffixed `shadow` utility. Any other keys will be used as suffixes, for example the key `'2'` will create a corresponding `shadow-2` utility. tailwind.config.js ``` module.exports = { theme: { extend: { boxShadow: { '3xl': '0 35px 60px -15px rgba(0, 0, 0, 0.3)', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `box-shadow` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="shadow-[0_35px_60px_-15px_rgba(0,0,0,0.3)]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/box-shadowBox Shadow Color ================ Utilities for controlling the color of a box shadow. Quick reference --------------- | Class | Properties | | --- | --- | | shadow-inherit | --tw-shadow-color: inherit; | | shadow-current | --tw-shadow-color: currentColor; | | shadow-transparent | --tw-shadow-color: transparent; | | shadow-black | --tw-shadow-color: #000; | | shadow-white | --tw-shadow-color: #fff; | | shadow-slate-50 | --tw-shadow-color: #f8fafc; | | shadow-slate-100 | --tw-shadow-color: #f1f5f9; | | shadow-slate-200 | --tw-shadow-color: #e2e8f0; | | shadow-slate-300 | --tw-shadow-color: #cbd5e1; | | shadow-slate-400 | --tw-shadow-color: #94a3b8; | | shadow-slate-500 | --tw-shadow-color: #64748b; | | shadow-slate-600 | --tw-shadow-color: #475569; | | shadow-slate-700 | --tw-shadow-color: #334155; | | shadow-slate-800 | --tw-shadow-color: #1e293b; | | shadow-slate-900 | --tw-shadow-color: #0f172a; | | shadow-slate-950 | --tw-shadow-color: #020617; | | shadow-gray-50 | --tw-shadow-color: #f9fafb; | | shadow-gray-100 | --tw-shadow-color: #f3f4f6; | | shadow-gray-200 | --tw-shadow-color: #e5e7eb; | | shadow-gray-300 | --tw-shadow-color: #d1d5db; | | shadow-gray-400 | --tw-shadow-color: #9ca3af; | | shadow-gray-500 | --tw-shadow-color: #6b7280; | | shadow-gray-600 | --tw-shadow-color: #4b5563; | | shadow-gray-700 | --tw-shadow-color: #374151; | | shadow-gray-800 | --tw-shadow-color: #1f2937; | | shadow-gray-900 | --tw-shadow-color: #111827; | | shadow-gray-950 | --tw-shadow-color: #030712; | | shadow-zinc-50 | --tw-shadow-color: #fafafa; | | shadow-zinc-100 | --tw-shadow-color: #f4f4f5; | | shadow-zinc-200 | --tw-shadow-color: #e4e4e7; | | shadow-zinc-300 | --tw-shadow-color: #d4d4d8; | | shadow-zinc-400 | --tw-shadow-color: #a1a1aa; | | shadow-zinc-500 | --tw-shadow-color: #71717a; | | shadow-zinc-600 | --tw-shadow-color: #52525b; | | shadow-zinc-700 | --tw-shadow-color: #3f3f46; | | shadow-zinc-800 | --tw-shadow-color: #27272a; | | shadow-zinc-900 | --tw-shadow-color: #18181b; | | shadow-zinc-950 | --tw-shadow-color: #09090b; | | shadow-neutral-50 | --tw-shadow-color: #fafafa; | | shadow-neutral-100 | --tw-shadow-color: #f5f5f5; | | shadow-neutral-200 | --tw-shadow-color: #e5e5e5; | | shadow-neutral-300 | --tw-shadow-color: #d4d4d4; | | shadow-neutral-400 | --tw-shadow-color: #a3a3a3; | | shadow-neutral-500 | --tw-shadow-color: #737373; | | shadow-neutral-600 | --tw-shadow-color: #525252; | | shadow-neutral-700 | --tw-shadow-color: #404040; | | shadow-neutral-800 | --tw-shadow-color: #262626; | | shadow-neutral-900 | --tw-shadow-color: #171717; | | shadow-neutral-950 | --tw-shadow-color: #0a0a0a; | | shadow-stone-50 | --tw-shadow-color: #fafaf9; | | shadow-stone-100 | --tw-shadow-color: #f5f5f4; | | shadow-stone-200 | --tw-shadow-color: #e7e5e4; | | shadow-stone-300 | --tw-shadow-color: #d6d3d1; | | shadow-stone-400 | --tw-shadow-color: #a8a29e; | | shadow-stone-500 | --tw-shadow-color: #78716c; | | shadow-stone-600 | --tw-shadow-color: #57534e; | | shadow-stone-700 | --tw-shadow-color: #44403c; | | shadow-stone-800 | --tw-shadow-color: #292524; | | shadow-stone-900 | --tw-shadow-color: #1c1917; | | shadow-stone-950 | --tw-shadow-color: #0c0a09; | | shadow-red-50 | --tw-shadow-color: #fef2f2; | | shadow-red-100 | --tw-shadow-color: #fee2e2; | | shadow-red-200 | --tw-shadow-color: #fecaca; | | shadow-red-300 | --tw-shadow-color: #fca5a5; | | shadow-red-400 | --tw-shadow-color: #f87171; | | shadow-red-500 | --tw-shadow-color: #ef4444; | | shadow-red-600 | --tw-shadow-color: #dc2626; | | shadow-red-700 | --tw-shadow-color: #b91c1c; | | shadow-red-800 | --tw-shadow-color: #991b1b; | | shadow-red-900 | --tw-shadow-color: #7f1d1d; | | shadow-red-950 | --tw-shadow-color: #450a0a; | | shadow-orange-50 | --tw-shadow-color: #fff7ed; | | shadow-orange-100 | --tw-shadow-color: #ffedd5; | | shadow-orange-200 | --tw-shadow-color: #fed7aa; | | shadow-orange-300 | --tw-shadow-color: #fdba74; | | shadow-orange-400 | --tw-shadow-color: #fb923c; | | shadow-orange-500 | --tw-shadow-color: #f97316; | | shadow-orange-600 | --tw-shadow-color: #ea580c; | | shadow-orange-700 | --tw-shadow-color: #c2410c; | | shadow-orange-800 | --tw-shadow-color: #9a3412; | | shadow-orange-900 | --tw-shadow-color: #7c2d12; | | shadow-orange-950 | --tw-shadow-color: #431407; | | shadow-amber-50 | --tw-shadow-color: #fffbeb; | | shadow-amber-100 | --tw-shadow-color: #fef3c7; | | shadow-amber-200 | --tw-shadow-color: #fde68a; | | shadow-amber-300 | --tw-shadow-color: #fcd34d; | | shadow-amber-400 | --tw-shadow-color: #fbbf24; | | shadow-amber-500 | --tw-shadow-color: #f59e0b; | | shadow-amber-600 | --tw-shadow-color: #d97706; | | shadow-amber-700 | --tw-shadow-color: #b45309; | | shadow-amber-800 | --tw-shadow-color: #92400e; | | shadow-amber-900 | --tw-shadow-color: #78350f; | | shadow-amber-950 | --tw-shadow-color: #451a03; | | shadow-yellow-50 | --tw-shadow-color: #fefce8; | | shadow-yellow-100 | --tw-shadow-color: #fef9c3; | | shadow-yellow-200 | --tw-shadow-color: #fef08a; | | shadow-yellow-300 | --tw-shadow-color: #fde047; | | shadow-yellow-400 | --tw-shadow-color: #facc15; | | shadow-yellow-500 | --tw-shadow-color: #eab308; | | shadow-yellow-600 | --tw-shadow-color: #ca8a04; | | shadow-yellow-700 | --tw-shadow-color: #a16207; | | shadow-yellow-800 | --tw-shadow-color: #854d0e; | | shadow-yellow-900 | --tw-shadow-color: #713f12; | | shadow-yellow-950 | --tw-shadow-color: #422006; | | shadow-lime-50 | --tw-shadow-color: #f7fee7; | | shadow-lime-100 | --tw-shadow-color: #ecfccb; | | shadow-lime-200 | --tw-shadow-color: #d9f99d; | | shadow-lime-300 | --tw-shadow-color: #bef264; | | shadow-lime-400 | --tw-shadow-color: #a3e635; | | shadow-lime-500 | --tw-shadow-color: #84cc16; | | shadow-lime-600 | --tw-shadow-color: #65a30d; | | shadow-lime-700 | --tw-shadow-color: #4d7c0f; | | shadow-lime-800 | --tw-shadow-color: #3f6212; | | shadow-lime-900 | --tw-shadow-color: #365314; | | shadow-lime-950 | --tw-shadow-color: #1a2e05; | | shadow-green-50 | --tw-shadow-color: #f0fdf4; | | shadow-green-100 | --tw-shadow-color: #dcfce7; | | shadow-green-200 | --tw-shadow-color: #bbf7d0; | | shadow-green-300 | --tw-shadow-color: #86efac; | | shadow-green-400 | --tw-shadow-color: #4ade80; | | shadow-green-500 | --tw-shadow-color: #22c55e; | | shadow-green-600 | --tw-shadow-color: #16a34a; | | shadow-green-700 | --tw-shadow-color: #15803d; | | shadow-green-800 | --tw-shadow-color: #166534; | | shadow-green-900 | --tw-shadow-color: #14532d; | | shadow-green-950 | --tw-shadow-color: #052e16; | | shadow-emerald-50 | --tw-shadow-color: #ecfdf5; | | shadow-emerald-100 | --tw-shadow-color: #d1fae5; | | shadow-emerald-200 | --tw-shadow-color: #a7f3d0; | | shadow-emerald-300 | --tw-shadow-color: #6ee7b7; | | shadow-emerald-400 | --tw-shadow-color: #34d399; | | shadow-emerald-500 | --tw-shadow-color: #10b981; | | shadow-emerald-600 | --tw-shadow-color: #059669; | | shadow-emerald-700 | --tw-shadow-color: #047857; | | shadow-emerald-800 | --tw-shadow-color: #065f46; | | shadow-emerald-900 | --tw-shadow-color: #064e3b; | | shadow-emerald-950 | --tw-shadow-color: #022c22; | | shadow-teal-50 | --tw-shadow-color: #f0fdfa; | | shadow-teal-100 | --tw-shadow-color: #ccfbf1; | | shadow-teal-200 | --tw-shadow-color: #99f6e4; | | shadow-teal-300 | --tw-shadow-color: #5eead4; | | shadow-teal-400 | --tw-shadow-color: #2dd4bf; | | shadow-teal-500 | --tw-shadow-color: #14b8a6; | | shadow-teal-600 | --tw-shadow-color: #0d9488; | | shadow-teal-700 | --tw-shadow-color: #0f766e; | | shadow-teal-800 | --tw-shadow-color: #115e59; | | shadow-teal-900 | --tw-shadow-color: #134e4a; | | shadow-teal-950 | --tw-shadow-color: #042f2e; | | shadow-cyan-50 | --tw-shadow-color: #ecfeff; | | shadow-cyan-100 | --tw-shadow-color: #cffafe; | | shadow-cyan-200 | --tw-shadow-color: #a5f3fc; | | shadow-cyan-300 | --tw-shadow-color: #67e8f9; | | shadow-cyan-400 | --tw-shadow-color: #22d3ee; | | shadow-cyan-500 | --tw-shadow-color: #06b6d4; | | shadow-cyan-600 | --tw-shadow-color: #0891b2; | | shadow-cyan-700 | --tw-shadow-color: #0e7490; | | shadow-cyan-800 | --tw-shadow-color: #155e75; | | shadow-cyan-900 | --tw-shadow-color: #164e63; | | shadow-cyan-950 | --tw-shadow-color: #083344; | | shadow-sky-50 | --tw-shadow-color: #f0f9ff; | | shadow-sky-100 | --tw-shadow-color: #e0f2fe; | | shadow-sky-200 | --tw-shadow-color: #bae6fd; | | shadow-sky-300 | --tw-shadow-color: #7dd3fc; | | shadow-sky-400 | --tw-shadow-color: #38bdf8; | | shadow-sky-500 | --tw-shadow-color: #0ea5e9; | | shadow-sky-600 | --tw-shadow-color: #0284c7; | | shadow-sky-700 | --tw-shadow-color: #0369a1; | | shadow-sky-800 | --tw-shadow-color: #075985; | | shadow-sky-900 | --tw-shadow-color: #0c4a6e; | | shadow-sky-950 | --tw-shadow-color: #082f49; | | shadow-blue-50 | --tw-shadow-color: #eff6ff; | | shadow-blue-100 | --tw-shadow-color: #dbeafe; | | shadow-blue-200 | --tw-shadow-color: #bfdbfe; | | shadow-blue-300 | --tw-shadow-color: #93c5fd; | | shadow-blue-400 | --tw-shadow-color: #60a5fa; | | shadow-blue-500 | --tw-shadow-color: #3b82f6; | | shadow-blue-600 | --tw-shadow-color: #2563eb; | | shadow-blue-700 | --tw-shadow-color: #1d4ed8; | | shadow-blue-800 | --tw-shadow-color: #1e40af; | | shadow-blue-900 | --tw-shadow-color: #1e3a8a; | | shadow-blue-950 | --tw-shadow-color: #172554; | | shadow-indigo-50 | --tw-shadow-color: #eef2ff; | | shadow-indigo-100 | --tw-shadow-color: #e0e7ff; | | shadow-indigo-200 | --tw-shadow-color: #c7d2fe; | | shadow-indigo-300 | --tw-shadow-color: #a5b4fc; | | shadow-indigo-400 | --tw-shadow-color: #818cf8; | | shadow-indigo-500 | --tw-shadow-color: #6366f1; | | shadow-indigo-600 | --tw-shadow-color: #4f46e5; | | shadow-indigo-700 | --tw-shadow-color: #4338ca; | | shadow-indigo-800 | --tw-shadow-color: #3730a3; | | shadow-indigo-900 | --tw-shadow-color: #312e81; | | shadow-indigo-950 | --tw-shadow-color: #1e1b4b; | | shadow-violet-50 | --tw-shadow-color: #f5f3ff; | | shadow-violet-100 | --tw-shadow-color: #ede9fe; | | shadow-violet-200 | --tw-shadow-color: #ddd6fe; | | shadow-violet-300 | --tw-shadow-color: #c4b5fd; | | shadow-violet-400 | --tw-shadow-color: #a78bfa; | | shadow-violet-500 | --tw-shadow-color: #8b5cf6; | | shadow-violet-600 | --tw-shadow-color: #7c3aed; | | shadow-violet-700 | --tw-shadow-color: #6d28d9; | | shadow-violet-800 | --tw-shadow-color: #5b21b6; | | shadow-violet-900 | --tw-shadow-color: #4c1d95; | | shadow-violet-950 | --tw-shadow-color: #2e1065; | | shadow-purple-50 | --tw-shadow-color: #faf5ff; | | shadow-purple-100 | --tw-shadow-color: #f3e8ff; | | shadow-purple-200 | --tw-shadow-color: #e9d5ff; | | shadow-purple-300 | --tw-shadow-color: #d8b4fe; | | shadow-purple-400 | --tw-shadow-color: #c084fc; | | shadow-purple-500 | --tw-shadow-color: #a855f7; | | shadow-purple-600 | --tw-shadow-color: #9333ea; | | shadow-purple-700 | --tw-shadow-color: #7e22ce; | | shadow-purple-800 | --tw-shadow-color: #6b21a8; | | shadow-purple-900 | --tw-shadow-color: #581c87; | | shadow-purple-950 | --tw-shadow-color: #3b0764; | | shadow-fuchsia-50 | --tw-shadow-color: #fdf4ff; | | shadow-fuchsia-100 | --tw-shadow-color: #fae8ff; | | shadow-fuchsia-200 | --tw-shadow-color: #f5d0fe; | | shadow-fuchsia-300 | --tw-shadow-color: #f0abfc; | | shadow-fuchsia-400 | --tw-shadow-color: #e879f9; | | shadow-fuchsia-500 | --tw-shadow-color: #d946ef; | | shadow-fuchsia-600 | --tw-shadow-color: #c026d3; | | shadow-fuchsia-700 | --tw-shadow-color: #a21caf; | | shadow-fuchsia-800 | --tw-shadow-color: #86198f; | | shadow-fuchsia-900 | --tw-shadow-color: #701a75; | | shadow-fuchsia-950 | --tw-shadow-color: #4a044e; | | shadow-pink-50 | --tw-shadow-color: #fdf2f8; | | shadow-pink-100 | --tw-shadow-color: #fce7f3; | | shadow-pink-200 | --tw-shadow-color: #fbcfe8; | | shadow-pink-300 | --tw-shadow-color: #f9a8d4; | | shadow-pink-400 | --tw-shadow-color: #f472b6; | | shadow-pink-500 | --tw-shadow-color: #ec4899; | | shadow-pink-600 | --tw-shadow-color: #db2777; | | shadow-pink-700 | --tw-shadow-color: #be185d; | | shadow-pink-800 | --tw-shadow-color: #9d174d; | | shadow-pink-900 | --tw-shadow-color: #831843; | | shadow-pink-950 | --tw-shadow-color: #500724; | | shadow-rose-50 | --tw-shadow-color: #fff1f2; | | shadow-rose-100 | --tw-shadow-color: #ffe4e6; | | shadow-rose-200 | --tw-shadow-color: #fecdd3; | | shadow-rose-300 | --tw-shadow-color: #fda4af; | | shadow-rose-400 | --tw-shadow-color: #fb7185; | | shadow-rose-500 | --tw-shadow-color: #f43f5e; | | shadow-rose-600 | --tw-shadow-color: #e11d48; | | shadow-rose-700 | --tw-shadow-color: #be123c; | | shadow-rose-800 | --tw-shadow-color: #9f1239; | | shadow-rose-900 | --tw-shadow-color: #881337; | | shadow-rose-950 | --tw-shadow-color: #4c0519; | Basic usage ----------- ### Setting the box shadow color Use the `shadow-{color}` utilities to change the color of an existing box shadow. By default colored shadows have an opacity of 100%, but you can adjust this using the opacity modifier. ``` <button class="bg-cyan-500 shadow-lg shadow-cyan-500/50 ...">Subscribe</button> <button class="bg-blue-500 shadow-lg shadow-blue-500/50 ...">Subscribe</button> <button class="bg-indigo-500 shadow-lg shadow-indigo-500/50 ...">Subscribe</button> ``` ### Using shadows on colored backgrounds When using shadows on a colored background, colored shadows can often look more natural than the default black-based shadows, which tend to appear gray and washed-out. ``` <!-- Default shadow--> <button class="shadow-lg">Subscribe</button<!-- Colored shadow--> <button class="shadow-lg shadow-indigo-500/40 ...">Subscribe</button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:shadow-indigo-500/40` to only apply the `shadow-indigo-500/40` utility on hover. ``` <button class="shadow shadow-blue-500/40 hover:shadow-indigo-500/40"> <!-- ... --> </button``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:shadow-indigo-500/40` to apply the `shadow-indigo-500/40` utility at only medium screen sizes and above. ``` <button class="shadow shadow-blue-500/40 md:shadow-indigo-500/40"> <!-- ... --> </button``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). ### Preserving shadow color when changing the shadow size Note that if you change the [box shadow](box-shadow) size at a different breakpoint, or on another state like hover, it will override any existing shadow colors. ``` <!-- This shadow will NOT be red at medium screens and above --> <div class="shadow-lg shadow-red-500 md:shadow-xl"></div> ``` To preserve the shadow color in these states, it needs to be respecified: ``` <!-- This shadow WILL be red at medium screens and above --> <div class="shadow-lg shadow-red-500 md:shadow-xl md:shadow-red-500"></div> ``` It’s necessary for Tailwind to work this way, as otherwise there would be no way to switch back to the default shadow. Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as box shadow colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your box shadow colors by editing `theme.boxShadowColor` or `theme.extend.boxShadowColor` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `box-shadow` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <button class="shadow-[#50d71e]"> <!-- ... --> </button``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/box-shadow-colorOpacity ======= Utilities for controlling the opacity of an element. Quick reference --------------- | Class | Properties | | --- | --- | | opacity-0 | opacity: 0; | | opacity-5 | opacity: 0.05; | | opacity-10 | opacity: 0.1; | | opacity-20 | opacity: 0.2; | | opacity-25 | opacity: 0.25; | | opacity-30 | opacity: 0.3; | | opacity-40 | opacity: 0.4; | | opacity-50 | opacity: 0.5; | | opacity-60 | opacity: 0.6; | | opacity-70 | opacity: 0.7; | | opacity-75 | opacity: 0.75; | | opacity-80 | opacity: 0.8; | | opacity-90 | opacity: 0.9; | | opacity-95 | opacity: 0.95; | | opacity-100 | opacity: 1; | Basic usage ----------- ### Changing an element’s opacity Control the opacity of an element using the `opacity-{amount}` utilities. ``` <button class="bg-indigo-500 opacity-100 ..."></button> <button class="bg-indigo-500 opacity-75 ..."></button> <button class="bg-indigo-500 opacity-50 ..."></button> <button class="bg-indigo-500 opacity-25 ..."></button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:opacity-100` to only apply the `opacity-100` utility on hover. ``` <div class="opacity-50 hover:opacity-100"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:opacity-100` to apply the `opacity-100` utility at only medium screen sizes and above. ``` <div class="opacity-50 md:opacity-100"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides several opacity utilities for general purpose use. You can customize these values by editing `theme.opacity` or `theme.extend.opacity` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { opacity: { '67': '.67', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `opacity` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="opacity-[.67]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/opacityMix Blend Mode ============== Utilities for controlling how an element should blend with the background. Quick reference --------------- | Class | Properties | | --- | --- | | mix-blend-normal | mix-blend-mode: normal; | | mix-blend-multiply | mix-blend-mode: multiply; | | mix-blend-screen | mix-blend-mode: screen; | | mix-blend-overlay | mix-blend-mode: overlay; | | mix-blend-darken | mix-blend-mode: darken; | | mix-blend-lighten | mix-blend-mode: lighten; | | mix-blend-color-dodge | mix-blend-mode: color-dodge; | | mix-blend-color-burn | mix-blend-mode: color-burn; | | mix-blend-hard-light | mix-blend-mode: hard-light; | | mix-blend-soft-light | mix-blend-mode: soft-light; | | mix-blend-difference | mix-blend-mode: difference; | | mix-blend-exclusion | mix-blend-mode: exclusion; | | mix-blend-hue | mix-blend-mode: hue; | | mix-blend-saturation | mix-blend-mode: saturation; | | mix-blend-color | mix-blend-mode: color; | | mix-blend-luminosity | mix-blend-mode: luminosity; | | mix-blend-plus-lighter | mix-blend-mode: plus-lighter; | Basic usage ----------- ### Setting an element’s blend mode Use the `mix-blend-{mode}` utilities to control how an element’s content should be blended with the background. ``` <div class="flex justify-center -space-x-14"> <div class="mix-blend-multiply bg-blue-400 ..."></div> <div class="mix-blend-multiply bg-pink-400 ..."></div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:mix-blend-overlay` to only apply the `mix-blend-overlay` utility on hover. ``` <div class="mix-blend-multiply hover:mix-blend-overlay"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:mix-blend-overlay` to apply the `mix-blend-overlay` utility at only medium screen sizes and above. ``` <div class="mix-blend-multiply md:mix-blend-overlay"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/mix-blend-modeBackground Blend Mode ===================== Utilities for controlling how an element's background image should blend with its background color. Quick reference --------------- | Class | Properties | | --- | --- | | bg-blend-normal | background-blend-mode: normal; | | bg-blend-multiply | background-blend-mode: multiply; | | bg-blend-screen | background-blend-mode: screen; | | bg-blend-overlay | background-blend-mode: overlay; | | bg-blend-darken | background-blend-mode: darken; | | bg-blend-lighten | background-blend-mode: lighten; | | bg-blend-color-dodge | background-blend-mode: color-dodge; | | bg-blend-color-burn | background-blend-mode: color-burn; | | bg-blend-hard-light | background-blend-mode: hard-light; | | bg-blend-soft-light | background-blend-mode: soft-light; | | bg-blend-difference | background-blend-mode: difference; | | bg-blend-exclusion | background-blend-mode: exclusion; | | bg-blend-hue | background-blend-mode: hue; | | bg-blend-saturation | background-blend-mode: saturation; | | bg-blend-color | background-blend-mode: color; | | bg-blend-luminosity | background-blend-mode: luminosity; | Basic usage ----------- ### Setting the background blend mode Use the `bg-blend-{mode}` utilities to control how an element’s background image(s) should blend with its background color. ``` <div class="bg-blend-multiply ..."> <!-- ... --> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:bg-blend-darken` to only apply the `bg-blend-darken` utility on hover. ``` <div class="bg-blend-lighten hover:bg-blend-darken"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:bg-blend-darken` to apply the `bg-blend-darken` utility at only medium screen sizes and above. ``` <div class="bg-blend-lighten md:bg-blend-darken"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/background-blend-modeBlur ==== Utilities for applying blur filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | blur-none | filter: blur(0); | | blur-sm | filter: blur(4px); | | blur | filter: blur(8px); | | blur-md | filter: blur(12px); | | blur-lg | filter: blur(16px); | | blur-xl | filter: blur(24px); | | blur-2xl | filter: blur(40px); | | blur-3xl | filter: blur(64px); | Basic usage ----------- ### Blurring elements Use the `blur-{amount?}` utilities to blur an element. ``` <div class="blur-none ..."> <!-- ... --> </div> <div class="blur-sm ..."> <!-- ... --> </div> <div class="blur-lg ..."> <!-- ... --> </div> <div class="blur-2xl ..."> <!-- ... --> </div> ``` ### Removing filters To remove all of the filters on an element at once, use the `filter-none` utility: ``` <div class="blur-md invert brightness-150 md:filter-none"> <!-- ... --> </div``` This can be useful when you want to remove filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:blur-lg` to only apply the `blur-lg` utility on hover. ``` <div class="blur hover:blur-lg"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:blur-lg` to apply the `blur-lg` utility at only medium screen sizes and above. ``` <div class="blur md:blur-lg"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `blur` utilities. You can customize these values by editing `theme.blur` or `theme.extend.blur` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { blur: { xs: '2px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `blur` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="blur-[2px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/blurBrightness ========== Utilities for applying brightness filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | brightness-0 | filter: brightness(0); | | brightness-50 | filter: brightness(.5); | | brightness-75 | filter: brightness(.75); | | brightness-90 | filter: brightness(.9); | | brightness-95 | filter: brightness(.95); | | brightness-100 | filter: brightness(1); | | brightness-105 | filter: brightness(1.05); | | brightness-110 | filter: brightness(1.1); | | brightness-125 | filter: brightness(1.25); | | brightness-150 | filter: brightness(1.5); | | brightness-200 | filter: brightness(2); | Basic usage ----------- ### Changing element brightness Use the `brightness-{amount?}` utilities to control an element’s brightness. ``` <div class="brightness-50 ..."> <!-- ... --> </div> <div class="brightness-100 ..."> <!-- ... --> </div> <div class="brightness-125 ..."> <!-- ... --> </div> <div class="brightness-200 ..."> <!-- ... --> </div> ``` ### Removing filters To remove all of the filters on an element at once, use the `filter-none` utility: ``` <div class="blur-md invert brightness-150 md:filter-none"> <!-- ... --> </div``` This can be useful when you want to remove filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:brightness-150` to only apply the `brightness-150` utility on hover. ``` <div class="brightness-110 hover:brightness-150"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:brightness-150` to apply the `brightness-150` utility at only medium screen sizes and above. ``` <div class="brightness-110 md:brightness-150"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `brightness` utilities. You can customize these values by editing `theme.brightness` or `theme.extend.brightness` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { brightness: { 25: '.25', 175: '1.75', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `brightness` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="brightness-[1.75]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/brightnessContrast ======== Utilities for applying contrast filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | contrast-0 | filter: contrast(0); | | contrast-50 | filter: contrast(.5); | | contrast-75 | filter: contrast(.75); | | contrast-100 | filter: contrast(1); | | contrast-125 | filter: contrast(1.25); | | contrast-150 | filter: contrast(1.5); | | contrast-200 | filter: contrast(2); | Basic usage ----------- ### Changing element contrast Use the `contrast-{amount?}` utilities to control an element’s contrast. ``` <div class="contrast-50 ..."> <!-- ... --> </div> <div class="contrast-100 ..."> <!-- ... --> </div> <div class="contrast-125 ..."> <!-- ... --> </div> <div class="contrast-200 ..."> <!-- ... --> </div> ``` ### Removing filters To remove all of the filters on an element at once, use the `filter-none` utility: ``` <div class="blur-md invert contrast-125 md:filter-none"> <!-- ... --> </div``` This can be useful when you want to remove filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:contrast-150` to only apply the `contrast-150` utility on hover. ``` <div class="contrast-125 hover:contrast-150"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:contrast-150` to apply the `contrast-150` utility at only medium screen sizes and above. ``` <div class="contrast-125 md:contrast-150"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `contrast` utilities. You can customize these values by editing `theme.contrast` or `theme.extend.contrast` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { contrast: { 25: '.25', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `contrast` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="contrast-[.25]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/contrastDrop Shadow =========== Utilities for applying drop-shadow filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | drop-shadow-sm | filter: drop-shadow(0 1px 1px rgb(0 0 0 / 0.05)); | | drop-shadow | filter: drop-shadow(0 1px 2px rgb(0 0 0 / 0.1)) drop-shadow(0 1px 1px rgb(0 0 0 / 0.06)); | | drop-shadow-md | filter: drop-shadow(0 4px 3px rgb(0 0 0 / 0.07)) drop-shadow(0 2px 2px rgb(0 0 0 / 0.06)); | | drop-shadow-lg | filter: drop-shadow(0 10px 8px rgb(0 0 0 / 0.04)) drop-shadow(0 4px 3px rgb(0 0 0 / 0.1)); | | drop-shadow-xl | filter: drop-shadow(0 20px 13px rgb(0 0 0 / 0.03)) drop-shadow(0 8px 5px rgb(0 0 0 / 0.08)); | | drop-shadow-2xl | filter: drop-shadow(0 25px 25px rgb(0 0 0 / 0.15)); | | drop-shadow-none | filter: drop-shadow(0 0 #0000); | Basic usage ----------- ### Adding a drop shadow Use the `drop-shadow-{amount}` utilities to add a drop shadow to an element. ``` <div class="drop-shadow-md ..."> <!-- ... --> </div> <div class="drop-shadow-lg ..."> <!-- ... --> </div> <div class="drop-shadow-xl ..."> <!-- ... --> </div> <div class="drop-shadow-2xl ..."> <!-- ... --> </div> ``` ### Removing filters To remove all of the filters on an element at once, use the `filter-none` utility: ``` <div class="blur-md invert drop-shadow-xl md:filter-none"> <!-- ... --> </div``` This can be useful when you want to remove filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:drop-shadow-xl` to only apply the `drop-shadow-xl` utility on hover. ``` <div class="drop-shadow-md hover:drop-shadow-xl"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:drop-shadow-xl` to apply the `drop-shadow-xl` utility at only medium screen sizes and above. ``` <div class="drop-shadow-md md:drop-shadow-xl"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `dropShadow` utilities. You can customize these values by editing `theme.dropShadow` or `theme.extend.dropShadow` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { dropShadow: { '3xl': '0 35px 35px rgba(0, 0, 0, 0.25)', '4xl': [ '0 35px 35px rgba(0, 0, 0, 0.25)', '0 45px 65px rgba(0, 0, 0, 0.15)' ] } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `drop-shadow` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="drop-shadow-[0_35px_35px_rgba(0,0,0,0.25)]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/drop-shadowGrayscale ========= Utilities for applying grayscale filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | grayscale-0 | filter: grayscale(0); | | grayscale | filter: grayscale(100%); | Basic usage ----------- ### Making an element grayscale Use the `grayscale` and `grayscale-0` utilities to control whether an element should be rendered as grayscale or in full color. ``` <div class="grayscale-0 ..."> <!-- ... --> </div> <div class="grayscale ..."> <!-- ... --> </div> ``` ### Removing filters To remove all of the filters on an element at once, use the `filter-none` utility: ``` <div class="blur-md invert grayscale md:filter-none"> <!-- ... --> </div``` This can be useful when you want to remove filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:grayscale-0` to only apply the `grayscale-0` utility on hover. ``` <div class="grayscale hover:grayscale-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:grayscale-0` to apply the `grayscale-0` utility at only medium screen sizes and above. ``` <div class="grayscale md:grayscale-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `grayscale` utilities. You can customize these values by editing `theme.grayscale` or `theme.extend.grayscale` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { grayscale: { 50: '50%', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `grayscale` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="grayscale-[50%]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/grayscaleHue Rotate ========== Utilities for applying hue-rotate filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | hue-rotate-0 | filter: hue-rotate(0deg); | | hue-rotate-15 | filter: hue-rotate(15deg); | | hue-rotate-30 | filter: hue-rotate(30deg); | | hue-rotate-60 | filter: hue-rotate(60deg); | | hue-rotate-90 | filter: hue-rotate(90deg); | | hue-rotate-180 | filter: hue-rotate(180deg); | Basic usage ----------- ### Rotating an element’s hue Use the `hue-rotate-{amount}` utilities to rotate the hue of an element. ``` <div class="hue-rotate-15 ..."> <!-- ... --> </div> <div class="hue-rotate-90 ..."> <!-- ... --> </div> <div class="hue-rotate-180 ..."> <!-- ... --> </div> <div class="-hue-rotate-60 ..."> <!-- ... --> </div> ``` ### Using negative values To use a negative hue-rotate value, prefix the class name with a dash to convert it to a negative value. ``` <div class="-hue-rotate-60 ..."> <!-- ... --> </div> ``` ### Removing filters To remove all of the filters on an element at once, use the `filter-none` utility: ``` <div class="blur-md invert hue-rotate-180 md:filter-none"> <!-- ... --> </div``` This can be useful when you want to remove filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:hue-rotate-0` to only apply the `hue-rotate-0` utility on hover. ``` <div class="hue-rotate-60 hover:hue-rotate-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:hue-rotate-0` to apply the `hue-rotate-0` utility at only medium screen sizes and above. ``` <div class="hue-rotate-60 md:hue-rotate-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `hue-rotate` utilities. You can customize these values by editing `theme.hueRotate` or `theme.extend.hueRotate` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { hueRotate: { '-270': '-270deg', 270: '270deg', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `hue-rotate` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="hue-rotate-[270deg]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/hue-rotateInvert ====== Utilities for applying invert filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | invert-0 | filter: invert(0); | | invert | filter: invert(100%); | Basic usage ----------- ### Inverting an element’s color Use the `invert` and `invert-0` utilities to control whether an element should be rendered with inverted colors or normally. ``` <div class="invert-0 ..."> <!-- ... --> </div> <div class="invert ..."> <!-- ... --> </div> ``` ### Removing filters To remove all of the filters on an element at once, use the `filter-none` utility: ``` <div class="blur-md invert brightness-150 md:filter-none"> <!-- ... --> </div``` This can be useful when you want to remove filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:invert-0` to only apply the `invert-0` utility on hover. ``` <div class="invert hover:invert-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:invert-0` to apply the `invert-0` utility at only medium screen sizes and above. ``` <div class="invert md:invert-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `invert` utilities. You can customize these values by editing `theme.invert` or `theme.extend.invert` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { invert: { 25: '.25', 50: '.5', 75: '.75', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `invert` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="invert-[.25]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/invertSaturate ======== Utilities for applying saturation filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | saturate-0 | filter: saturate(0); | | saturate-50 | filter: saturate(.5); | | saturate-100 | filter: saturate(1); | | saturate-150 | filter: saturate(1.5); | | saturate-200 | filter: saturate(2); | Basic usage ----------- ### Changing element saturation Use the `saturate-{amount}` utilities to control an element’s saturation. ``` <div class="saturate-50 ..."> <!-- ... --> </div> <div class="saturate-100 ..."> <!-- ... --> </div> <div class="saturate-150 ..."> <!-- ... --> </div> <div class="saturate-200 ..."> <!-- ... --> </div> ``` ### Removing filters To remove all of the filters on an element at once, use the `filter-none` utility: ``` <div class="blur-md invert saturate-150 md:filter-none"> <!-- ... --> </div``` This can be useful when you want to remove filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:saturate-150` to only apply the `saturate-150` utility on hover. ``` <div class="saturate-50 hover:saturate-150"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:saturate-150` to apply the `saturate-150` utility at only medium screen sizes and above. ``` <div class="saturate-50 md:saturate-150"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `saturate` utilities. You can customize these values by editing `theme.saturate` or `theme.extend.saturate` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { saturate: { 25: '.25', 75: '.75', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `saturate` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="saturate-[.25]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/saturateSepia ===== Utilities for applying sepia filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | sepia-0 | filter: sepia(0); | | sepia | filter: sepia(100%); | Basic usage ----------- ### Adding sepia filters Use the `sepia` and `sepia-0` utilities to control whether an element should be rendered as sepia or in full color. ``` <div class="sepia-0 ..."> <!-- ... --> </div> <div class="sepia ..."> <!-- ... --> </div> ``` ### Removing filters To remove all of the filters on an element at once, use the `filter-none` utility: ``` <div class="blur-md invert sepia md:filter-none"> <!-- ... --> </div``` This can be useful when you want to remove filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:sepia-0` to only apply the `sepia-0` utility on hover. ``` <div class="sepia hover:sepia-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:sepia-0` to apply the `sepia-0` utility at only medium screen sizes and above. ``` <div class="sepia md:sepia-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `sepia` utilities. You can customize these values by editing `theme.sepia` or `theme.extend.sepia` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { sepia: { 25: '.25', 75: '.75', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `sepia` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="sepia-[.25]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/sepiaBackdrop Blur ============= Utilities for applying backdrop blur filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | backdrop-blur-none | backdrop-filter: blur(0); | | backdrop-blur-sm | backdrop-filter: blur(4px); | | backdrop-blur | backdrop-filter: blur(8px); | | backdrop-blur-md | backdrop-filter: blur(12px); | | backdrop-blur-lg | backdrop-filter: blur(16px); | | backdrop-blur-xl | backdrop-filter: blur(24px); | | backdrop-blur-2xl | backdrop-filter: blur(40px); | | backdrop-blur-3xl | backdrop-filter: blur(64px); | Basic usage ----------- ### Blurring behind an element Use the `backdrop-blur-{amount?}` utilities to control an element’s backdrop blur. ``` <div class="backdrop-blur-sm bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-blur-md bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-blur-xl bg-white/30 ..."> <!-- ... --> </div> ``` ### Removing backdrop filters To remove all of the backdrop filters on an element at once, use the `backdrop-filter-none` utility: ``` <div class="backdrop-blur-md backdrop-brightness-150 md:backdrop-filter-none"> <!-- ... --> </div``` This can be useful when you want to remove backdrop filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:backdrop-blur-lg` to only apply the `backdrop-blur-lg` utility on hover. ``` <div class="backdrop-blur-sm hover:backdrop-blur-lg"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:backdrop-blur-lg` to apply the `backdrop-blur-lg` utility at only medium screen sizes and above. ``` <div class="backdrop-blur-sm md:backdrop-blur-lg"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `backdrop-blur` utilities. You can customize these values by editing `theme.backdropBlur` or `theme.extend.backdropBlur` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { backdropBlur: { xs: '2px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `backdrop-blur` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="backdrop-blur-[2px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/backdrop-blurBackdrop Brightness =================== Utilities for applying backdrop brightness filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | backdrop-brightness-0 | backdrop-filter: brightness(0); | | backdrop-brightness-50 | backdrop-filter: brightness(.5); | | backdrop-brightness-75 | backdrop-filter: brightness(.75); | | backdrop-brightness-90 | backdrop-filter: brightness(.9); | | backdrop-brightness-95 | backdrop-filter: brightness(.95); | | backdrop-brightness-100 | backdrop-filter: brightness(1); | | backdrop-brightness-105 | backdrop-filter: brightness(1.05); | | backdrop-brightness-110 | backdrop-filter: brightness(1.1); | | backdrop-brightness-125 | backdrop-filter: brightness(1.25); | | backdrop-brightness-150 | backdrop-filter: brightness(1.5); | | backdrop-brightness-200 | backdrop-filter: brightness(2); | Basic usage ----------- ### Controlling backdrop brightness Use the `backdrop-brightness-{amount?}` utilities to control an element’s backdrop brightness. ``` <div class="backdrop-brightness-50 bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-brightness-125 bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-brightness-200 bg-white/30 ..."> <!-- ... --> </div> ``` ### Removing backdrop filters To remove all of the backdrop filters on an element at once, use the `backdrop-filter-none` utility: ``` <div class="backdrop-blur-md backdrop-brightness-150 md:backdrop-filter-none"> <!-- ... --> </div``` This can be useful when you want to remove backdrop filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:backdrop-brightness-150` to only apply the `backdrop-brightness-150` utility on hover. ``` <div class="backdrop-brightness-110 hover:backdrop-brightness-150"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:backdrop-brightness-150` to apply the `backdrop-brightness-150` utility at only medium screen sizes and above. ``` <div class="backdrop-brightness-110 md:backdrop-brightness-150"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `backdrop-brightness` utilities. You can customize these values by editing `theme.backdropBrightness` or `theme.extend.backdropBrightness` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { backdropBrightness: { 25: '.25', 175: '1.75', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `backdrop-brightness` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="backdrop-brightness-[1.75]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/backdrop-brightnessBackdrop Contrast ================= Utilities for applying backdrop contrast filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | backdrop-contrast-0 | backdrop-filter: contrast(0); | | backdrop-contrast-50 | backdrop-filter: contrast(.5); | | backdrop-contrast-75 | backdrop-filter: contrast(.75); | | backdrop-contrast-100 | backdrop-filter: contrast(1); | | backdrop-contrast-125 | backdrop-filter: contrast(1.25); | | backdrop-contrast-150 | backdrop-filter: contrast(1.5); | | backdrop-contrast-200 | backdrop-filter: contrast(2); | Basic usage ----------- ### Controlling backdrop contrast Use the `backdrop-contrast-{amount?}` utilities to control an element’s backdrop contrast. ``` <div class="backdrop-contrast-50 bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-contrast-125 bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-contrast-200 bg-white/30 ..."> <!-- ... --> </div> ``` ### Removing backdrop filters To remove all of the backdrop filters on an element at once, use the `backdrop-filter-none` utility: ``` <div class="backdrop-blur-md backdrop-contrast-125 md:backdrop-filter-none"> <!-- ... --> </div``` This can be useful when you want to remove backdrop filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:backdrop-contrast-150` to only apply the `backdrop-contrast-150` utility on hover. ``` <div class="backdrop-contrast-125 hover:backdrop-contrast-150"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:backdrop-contrast-150` to apply the `backdrop-contrast-150` utility at only medium screen sizes and above. ``` <div class="backdrop-contrast-125 md:backdrop-contrast-150"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `backdrop-contrast` utilities. You can customize these values by editing `theme.backdropContrast` or `theme.extend.backdropContrast` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { backdropContrast: { 25: '.25', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `backdrop-contrast` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="backdrop-contrast-[.25]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/backdrop-contrastBackdrop Grayscale ================== Utilities for applying backdrop grayscale filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | backdrop-grayscale-0 | backdrop-filter: grayscale(0); | | backdrop-grayscale | backdrop-filter: grayscale(100%); | Basic usage ----------- ### Making an element grayscale Use the `backdrop-grayscale` and `backdrop-grayscale-0` utilities to control whether an element’s backdrop should be rendered as grayscale or in full color. ``` <div class="backdrop-grayscale-0 bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-grayscale bg-white/30 ..."> <!-- ... --> </div> ``` ### Removing backdrop filters To remove all of the backdrop filters on an element at once, use the `backdrop-filter-none` utility: ``` <div class="backdrop-blur-md backdrop-grayscale md:backdrop-filter-none"> <!-- ... --> </div``` This can be useful when you want to remove backdrop filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:backdrop-grayscale-0` to only apply the `backdrop-grayscale-0` utility on hover. ``` <div class="backdrop-grayscale hover:backdrop-grayscale-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:backdrop-grayscale-0` to apply the `backdrop-grayscale-0` utility at only medium screen sizes and above. ``` <div class="backdrop-grayscale md:backdrop-grayscale-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `backdrop-grayscale` utilities. You can customize these values by editing `theme.backdropGrayscale` or `theme.extend.backdropGrayscale` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { backdropGrayscale: { 50: '.5', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `backdrop-grayscale` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="backdrop-grayscale-[.5]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/backdrop-grayscaleBackdrop Hue Rotate =================== Utilities for applying backdrop hue-rotate filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | backdrop-hue-rotate-0 | backdrop-filter: hue-rotate(0deg); | | backdrop-hue-rotate-15 | backdrop-filter: hue-rotate(15deg); | | backdrop-hue-rotate-30 | backdrop-filter: hue-rotate(30deg); | | backdrop-hue-rotate-60 | backdrop-filter: hue-rotate(60deg); | | backdrop-hue-rotate-90 | backdrop-filter: hue-rotate(90deg); | | backdrop-hue-rotate-180 | backdrop-filter: hue-rotate(180deg); | Basic usage ----------- ### Rotating the backdrop’s hue Use the `backdrop-hue-rotate-{amount}` utilities to rotate the hue of an element’s backdrop. ``` <div class="backdrop-hue-rotate-90 bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-hue-rotate-180 bg-white/30 ..."> <!-- ... --> </div> <div class="-backdrop-hue-rotate-60 bg-white/30 ..."> <!-- ... --> </div> ``` ### Using negative values To use a negative backdrop hue rotate value, prefix the class name with a dash to convert it to a negative value. ``` <div class="-backdrop-hue-rotate-60"> <!-- ... --> </div> ``` ### Removing backdrop filters To remove all of the backdrop filters on an element at once, use the `backdrop-filter-none` utility: ``` <div class="backdrop-blur-md backdrop-hue-rotate-180 md:backdrop-filter-none"> <!-- ... --> </div``` This can be useful when you want to remove backdrop filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:backdrop-hue-rotate-60` to only apply the `backdrop-hue-rotate-60` utility on hover. ``` <div class="backdrop-hue-rotate-15 hover:backdrop-hue-rotate-60"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:backdrop-hue-rotate-60` to apply the `backdrop-hue-rotate-60` utility at only medium screen sizes and above. ``` <div class="backdrop-hue-rotate-15 md:backdrop-hue-rotate-60"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `backdrop-hue-rotate` utilities. You can customize these values by editing `theme.backdropHueRotate` or `theme.extend.backdropHueRotate` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { backdropHueRotate: { '-270': '-270deg', 270: '270deg', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `backdrop-hue-rotate` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="backdrop-hue-rotate-[270deg]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/backdrop-hue-rotateBackdrop Invert =============== Utilities for applying backdrop invert filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | backdrop-invert-0 | backdrop-filter: invert(0); | | backdrop-invert | backdrop-filter: invert(100%); | Basic usage ----------- ### Inverting an element’s backdrop Use the `backdrop-invert` and `backdrop-invert-0` utilities to control whether an element should be rendered with inverted backdrop colors or normally. ``` <div class="backdrop-invert-0 bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-invert bg-white/30 ..."> <!-- ... --> </div> ``` ### Removing backdrop filters To remove all of the backdrop filters on an element at once, use the `backdrop-filter-none` utility: ``` <div class="backdrop-blur-md backdrop-invert md:backdrop-filter-none"> <!-- ... --> </div``` This can be useful when you want to remove backdrop filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:backdrop-invert-0` to only apply the `backdrop-invert-0` utility on hover. ``` <div class="backdrop-invert hover:backdrop-invert-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:backdrop-invert-0` to apply the `backdrop-invert-0` utility at only medium screen sizes and above. ``` <div class="backdrop-invert md:backdrop-invert-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `backdrop-invert` utilities. You can customize these values by editing `theme.backdropInvert` or `theme.extend.backdropInvert` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { backdropInvert: { 25: '.25', 75: '.75', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `backdrop-invert` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="backdrop-invert-[.25]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/backdrop-invertBackdrop Opacity ================ Utilities for applying backdrop opacity filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | backdrop-opacity-0 | backdrop-filter: opacity(0); | | backdrop-opacity-5 | backdrop-filter: opacity(0.05); | | backdrop-opacity-10 | backdrop-filter: opacity(0.1); | | backdrop-opacity-20 | backdrop-filter: opacity(0.2); | | backdrop-opacity-25 | backdrop-filter: opacity(0.25); | | backdrop-opacity-30 | backdrop-filter: opacity(0.3); | | backdrop-opacity-40 | backdrop-filter: opacity(0.4); | | backdrop-opacity-50 | backdrop-filter: opacity(0.5); | | backdrop-opacity-60 | backdrop-filter: opacity(0.6); | | backdrop-opacity-70 | backdrop-filter: opacity(0.7); | | backdrop-opacity-75 | backdrop-filter: opacity(0.75); | | backdrop-opacity-80 | backdrop-filter: opacity(0.8); | | backdrop-opacity-90 | backdrop-filter: opacity(0.9); | | backdrop-opacity-95 | backdrop-filter: opacity(0.95); | | backdrop-opacity-100 | backdrop-filter: opacity(1); | Basic usage ----------- ### Controlling opacity of backdrop filters Use the `backdrop-opacity-{amount}` utilities to control the opacity of other backdrop filters applied to an element. ``` <div class="backdrop-opacity-10 backdrop-invert bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-opacity-60 backdrop-invert bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-opacity-95 backdrop-invert bg-white/30 ..."> <!-- ... --> </div> ``` ### Removing backdrop filters To remove all of the backdrop filters on an element at once, use the `backdrop-filter-none` utility: ``` <div class="backdrop-blur-md backdrop-opacity-60 md:backdrop-filter-none"> <!-- ... --> </div``` This can be useful when you want to remove backdrop filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:backdrop-opacity-60` to only apply the `backdrop-opacity-60` utility on hover. ``` <div class="backdrop-opacity-100 hover:backdrop-opacity-60"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:backdrop-opacity-60` to apply the `backdrop-opacity-60` utility at only medium screen sizes and above. ``` <div class="backdrop-opacity-100 md:backdrop-opacity-60"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `backdrop-opacity` utilities. You can customize these values by editing `theme.backdropOpacity` or `theme.extend.backdropOpacity` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { backdropOpacity: { 15: '.15', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `backdrop-opacity` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="backdrop-opacity-[.15]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/backdrop-opacityBackdrop Saturate ================= Utilities for applying backdrop saturation filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | backdrop-saturate-0 | backdrop-filter: saturate(0); | | backdrop-saturate-50 | backdrop-filter: saturate(.5); | | backdrop-saturate-100 | backdrop-filter: saturate(1); | | backdrop-saturate-150 | backdrop-filter: saturate(1.5); | | backdrop-saturate-200 | backdrop-filter: saturate(2); | Basic usage ----------- ### Changing backdrop saturation Use the `backdrop-saturate-{amount}` utilities to control an element’s backdrop saturation. ``` <div class="backdrop-saturate-50 bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-saturate-125 bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-saturate-200 bg-white/30 ..."> <!-- ... --> </div> ``` ### Removing backdrop filters To remove all of the backdrop filters on an element at once, use the `backdrop-filter-none` utility: ``` <div class="backdrop-blur-md backdrop-saturate-150 md:backdrop-filter-none"> <!-- ... --> </div``` This can be useful when you want to remove backdrop filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:backdrop-saturate-150` to only apply the `backdrop-saturate-150` utility on hover. ``` <div class="backdrop-saturate-50 hover:backdrop-saturate-150"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:backdrop-saturate-150` to apply the `backdrop-saturate-150` utility at only medium screen sizes and above. ``` <div class="backdrop-saturate-50 md:backdrop-saturate-150"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `backdrop-saturate` utilities. You can customize these values by editing `theme.backdropSaturate` or `theme.extend.backdropSaturate` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { backdropSaturate: { 25: '.25', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `backdrop-saturate` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="backdrop-saturate-[.25]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/backdrop-saturateBackdrop Sepia ============== Utilities for applying backdrop sepia filters to an element. Quick reference --------------- | Class | Properties | | --- | --- | | backdrop-sepia-0 | backdrop-filter: sepia(0); | | backdrop-sepia | backdrop-filter: sepia(100%); | Basic usage ----------- ### Adding backdrop sepia filters Use the `backdrop-sepia` and `backdrop-sepia-0` utilities to control whether an element’s backdrop should be rendered as sepia or in full color. ``` <div class="backdrop-sepia-0 bg-white/30 ..."> <!-- ... --> </div> <div class="backdrop-sepia bg-white/30 ..."> <!-- ... --> </div> ``` ### Removing backdrop filters To remove all of the backdrop filters on an element at once, use the `backdrop-filter-none` utility: ``` <div class="backdrop-blur-md backdrop-sepia md:backdrop-filter-none"> <!-- ... --> </div``` This can be useful when you want to remove backdrop filters conditionally, such as on hover or at a particular breakpoint. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:backdrop-sepia-0` to only apply the `backdrop-sepia-0` utility on hover. ``` <div class="backdrop-sepia hover:backdrop-sepia-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:backdrop-sepia-0` to apply the `backdrop-sepia-0` utility at only medium screen sizes and above. ``` <div class="backdrop-sepia md:backdrop-sepia-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `backdrop-sepia` utilities. You can customize these values by editing `theme.backdropSepia` or `theme.extend.backdropSepia` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { backdropSepia: { 25: '.25', 75: '.75', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `backdrop-sepia` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="backdrop-sepia-[.25]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/backdrop-sepiaBorder Collapse =============== Utilities for controlling whether table borders should collapse or be separated. Quick reference --------------- | Class | Properties | | --- | --- | | border-collapse | border-collapse: collapse; | | border-separate | border-collapse: separate; | Basic usage ----------- ### Collapse Use `border-collapse` to combine adjacent cell borders into a single border when possible. Note that this includes collapsing borders on the top-level `<table>` tag. ``` <table class="border-collapse border border-slate-400 ..."> <thead> <tr> <th class="border border-slate-300 ...">State</th> <th class="border border-slate-300 ...">City</th> </tr> </thead> <tbody> <tr> <td class="border border-slate-300 ...">Indiana</td> <td class="border border-slate-300 ...">Indianapolis</td> </tr> <tr> <td class="border border-slate-300 ...">Ohio</td> <td class="border border-slate-300 ...">Columbus</td> </tr> <tr> <td class="border border-slate-300 ...">Michigan</td> <td class="border border-slate-300 ...">Detroit</td> </tr> </tbody> </table><table class="border-collapse border border-slate-500 ..."> <thead> <tr> <th class="border border-slate-600 ...">State</th> <th class="border border-slate-600 ...">City</th> </tr> </thead> <tbody> <tr> <td class="border border-slate-700 ...">Indiana</td> <td class="border border-slate-700 ...">Indianapolis</td> </tr> <tr> <td class="border border-slate-700 ...">Ohio</td> <td class="border border-slate-700 ...">Columbus</td> </tr> <tr> <td class="border border-slate-700 ...">Michigan</td> <td class="border border-slate-700 ...">Detroit</td> </tr> </tbody> </table> ``` ### Separate Use `border-separate` to force each cell to display its own separate borders. ``` <table class="border-separate border border-slate-400 ..."> <thead> <tr> <th class="border border-slate-300 ...">State</th> <th class="border border-slate-300 ...">City</th> </tr> </thead> <tbody> <tr> <td class="border border-slate-300 ...">Indiana</td> <td class="border border-slate-300 ...">Indianapolis</td> </tr> <tr> <td class="border border-slate-300 ...">Ohio</td> <td class="border border-slate-300 ...">Columbus</td> </tr> <tr> <td class="border border-slate-300 ...">Michigan</td> <td class="border border-slate-300 ...">Detroit</td> </tr> </tbody> </table><table class="border-separate border border-slate-500 ..."> <thead> <tr> <th class="border border-slate-600 ...">State</th> <th class="border border-slate-600 ...">City</th> </tr> </thead> <tbody> <tr> <td class="border border-slate-700 ...">Indiana</td> <td class="border border-slate-700 ...">Indianapolis</td> </tr> <tr> <td class="border border-slate-700 ...">Ohio</td> <td class="border border-slate-700 ...">Columbus</td> </tr> <tr> <td class="border border-slate-700 ...">Michigan</td> <td class="border border-slate-700 ...">Detroit</td> </tr> </tbody> </table> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:border-collapse` to only apply the `border-collapse` utility on hover. ``` <table class="hover:border-collapse"> <!-- ... --> </table``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:border-collapse` to apply the `border-collapse` utility at only medium screen sizes and above. ``` <table class="md:border-collapse"> <!-- ... --> </table``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/border-collapseBorder Color ============ Utilities for controlling the color of an element's borders. Quick reference --------------- | Class | Properties | | --- | --- | | border-inherit | border-color: inherit; | | border-current | border-color: currentColor; | | border-transparent | border-color: transparent; | | border-black | border-color: rgb(0 0 0); | | border-white | border-color: rgb(255 255 255); | | border-slate-50 | border-color: rgb(248 250 252); | | border-slate-100 | border-color: rgb(241 245 249); | | border-slate-200 | border-color: rgb(226 232 240); | | border-slate-300 | border-color: rgb(203 213 225); | | border-slate-400 | border-color: rgb(148 163 184); | | border-slate-500 | border-color: rgb(100 116 139); | | border-slate-600 | border-color: rgb(71 85 105); | | border-slate-700 | border-color: rgb(51 65 85); | | border-slate-800 | border-color: rgb(30 41 59); | | border-slate-900 | border-color: rgb(15 23 42); | | border-slate-950 | border-color: rgb(2 6 23); | | border-gray-50 | border-color: rgb(249 250 251); | | border-gray-100 | border-color: rgb(243 244 246); | | border-gray-200 | border-color: rgb(229 231 235); | | border-gray-300 | border-color: rgb(209 213 219); | | border-gray-400 | border-color: rgb(156 163 175); | | border-gray-500 | border-color: rgb(107 114 128); | | border-gray-600 | border-color: rgb(75 85 99); | | border-gray-700 | border-color: rgb(55 65 81); | | border-gray-800 | border-color: rgb(31 41 55); | | border-gray-900 | border-color: rgb(17 24 39); | | border-gray-950 | border-color: rgb(3 7 18); | | border-zinc-50 | border-color: rgb(250 250 250); | | border-zinc-100 | border-color: rgb(244 244 245); | | border-zinc-200 | border-color: rgb(228 228 231); | | border-zinc-300 | border-color: rgb(212 212 216); | | border-zinc-400 | border-color: rgb(161 161 170); | | border-zinc-500 | border-color: rgb(113 113 122); | | border-zinc-600 | border-color: rgb(82 82 91); | | border-zinc-700 | border-color: rgb(63 63 70); | | border-zinc-800 | border-color: rgb(39 39 42); | | border-zinc-900 | border-color: rgb(24 24 27); | | border-zinc-950 | border-color: rgb(9 9 11); | | border-neutral-50 | border-color: rgb(250 250 250); | | border-neutral-100 | border-color: rgb(245 245 245); | | border-neutral-200 | border-color: rgb(229 229 229); | | border-neutral-300 | border-color: rgb(212 212 212); | | border-neutral-400 | border-color: rgb(163 163 163); | | border-neutral-500 | border-color: rgb(115 115 115); | | border-neutral-600 | border-color: rgb(82 82 82); | | border-neutral-700 | border-color: rgb(64 64 64); | | border-neutral-800 | border-color: rgb(38 38 38); | | border-neutral-900 | border-color: rgb(23 23 23); | | border-neutral-950 | border-color: rgb(10 10 10); | | border-stone-50 | border-color: rgb(250 250 249); | | border-stone-100 | border-color: rgb(245 245 244); | | border-stone-200 | border-color: rgb(231 229 228); | | border-stone-300 | border-color: rgb(214 211 209); | | border-stone-400 | border-color: rgb(168 162 158); | | border-stone-500 | border-color: rgb(120 113 108); | | border-stone-600 | border-color: rgb(87 83 78); | | border-stone-700 | border-color: rgb(68 64 60); | | border-stone-800 | border-color: rgb(41 37 36); | | border-stone-900 | border-color: rgb(28 25 23); | | border-stone-950 | border-color: rgb(12 10 9); | | border-red-50 | border-color: rgb(254 242 242); | | border-red-100 | border-color: rgb(254 226 226); | | border-red-200 | border-color: rgb(254 202 202); | | border-red-300 | border-color: rgb(252 165 165); | | border-red-400 | border-color: rgb(248 113 113); | | border-red-500 | border-color: rgb(239 68 68); | | border-red-600 | border-color: rgb(220 38 38); | | border-red-700 | border-color: rgb(185 28 28); | | border-red-800 | border-color: rgb(153 27 27); | | border-red-900 | border-color: rgb(127 29 29); | | border-red-950 | border-color: rgb(69 10 10); | | border-orange-50 | border-color: rgb(255 247 237); | | border-orange-100 | border-color: rgb(255 237 213); | | border-orange-200 | border-color: rgb(254 215 170); | | border-orange-300 | border-color: rgb(253 186 116); | | border-orange-400 | border-color: rgb(251 146 60); | | border-orange-500 | border-color: rgb(249 115 22); | | border-orange-600 | border-color: rgb(234 88 12); | | border-orange-700 | border-color: rgb(194 65 12); | | border-orange-800 | border-color: rgb(154 52 18); | | border-orange-900 | border-color: rgb(124 45 18); | | border-orange-950 | border-color: rgb(67 20 7); | | border-amber-50 | border-color: rgb(255 251 235); | | border-amber-100 | border-color: rgb(254 243 199); | | border-amber-200 | border-color: rgb(253 230 138); | | border-amber-300 | border-color: rgb(252 211 77); | | border-amber-400 | border-color: rgb(251 191 36); | | border-amber-500 | border-color: rgb(245 158 11); | | border-amber-600 | border-color: rgb(217 119 6); | | border-amber-700 | border-color: rgb(180 83 9); | | border-amber-800 | border-color: rgb(146 64 14); | | border-amber-900 | border-color: rgb(120 53 15); | | border-amber-950 | border-color: rgb(69 26 3); | | border-yellow-50 | border-color: rgb(254 252 232); | | border-yellow-100 | border-color: rgb(254 249 195); | | border-yellow-200 | border-color: rgb(254 240 138); | | border-yellow-300 | border-color: rgb(253 224 71); | | border-yellow-400 | border-color: rgb(250 204 21); | | border-yellow-500 | border-color: rgb(234 179 8); | | border-yellow-600 | border-color: rgb(202 138 4); | | border-yellow-700 | border-color: rgb(161 98 7); | | border-yellow-800 | border-color: rgb(133 77 14); | | border-yellow-900 | border-color: rgb(113 63 18); | | border-yellow-950 | border-color: rgb(66 32 6); | | border-lime-50 | border-color: rgb(247 254 231); | | border-lime-100 | border-color: rgb(236 252 203); | | border-lime-200 | border-color: rgb(217 249 157); | | border-lime-300 | border-color: rgb(190 242 100); | | border-lime-400 | border-color: rgb(163 230 53); | | border-lime-500 | border-color: rgb(132 204 22); | | border-lime-600 | border-color: rgb(101 163 13); | | border-lime-700 | border-color: rgb(77 124 15); | | border-lime-800 | border-color: rgb(63 98 18); | | border-lime-900 | border-color: rgb(54 83 20); | | border-lime-950 | border-color: rgb(26 46 5); | | border-green-50 | border-color: rgb(240 253 244); | | border-green-100 | border-color: rgb(220 252 231); | | border-green-200 | border-color: rgb(187 247 208); | | border-green-300 | border-color: rgb(134 239 172); | | border-green-400 | border-color: rgb(74 222 128); | | border-green-500 | border-color: rgb(34 197 94); | | border-green-600 | border-color: rgb(22 163 74); | | border-green-700 | border-color: rgb(21 128 61); | | border-green-800 | border-color: rgb(22 101 52); | | border-green-900 | border-color: rgb(20 83 45); | | border-green-950 | border-color: rgb(5 46 22); | | border-emerald-50 | border-color: rgb(236 253 245); | | border-emerald-100 | border-color: rgb(209 250 229); | | border-emerald-200 | border-color: rgb(167 243 208); | | border-emerald-300 | border-color: rgb(110 231 183); | | border-emerald-400 | border-color: rgb(52 211 153); | | border-emerald-500 | border-color: rgb(16 185 129); | | border-emerald-600 | border-color: rgb(5 150 105); | | border-emerald-700 | border-color: rgb(4 120 87); | | border-emerald-800 | border-color: rgb(6 95 70); | | border-emerald-900 | border-color: rgb(6 78 59); | | border-emerald-950 | border-color: rgb(2 44 34); | | border-teal-50 | border-color: rgb(240 253 250); | | border-teal-100 | border-color: rgb(204 251 241); | | border-teal-200 | border-color: rgb(153 246 228); | | border-teal-300 | border-color: rgb(94 234 212); | | border-teal-400 | border-color: rgb(45 212 191); | | border-teal-500 | border-color: rgb(20 184 166); | | border-teal-600 | border-color: rgb(13 148 136); | | border-teal-700 | border-color: rgb(15 118 110); | | border-teal-800 | border-color: rgb(17 94 89); | | border-teal-900 | border-color: rgb(19 78 74); | | border-teal-950 | border-color: rgb(4 47 46); | | border-cyan-50 | border-color: rgb(236 254 255); | | border-cyan-100 | border-color: rgb(207 250 254); | | border-cyan-200 | border-color: rgb(165 243 252); | | border-cyan-300 | border-color: rgb(103 232 249); | | border-cyan-400 | border-color: rgb(34 211 238); | | border-cyan-500 | border-color: rgb(6 182 212); | | border-cyan-600 | border-color: rgb(8 145 178); | | border-cyan-700 | border-color: rgb(14 116 144); | | border-cyan-800 | border-color: rgb(21 94 117); | | border-cyan-900 | border-color: rgb(22 78 99); | | border-cyan-950 | border-color: rgb(8 51 68); | | border-sky-50 | border-color: rgb(240 249 255); | | border-sky-100 | border-color: rgb(224 242 254); | | border-sky-200 | border-color: rgb(186 230 253); | | border-sky-300 | border-color: rgb(125 211 252); | | border-sky-400 | border-color: rgb(56 189 248); | | border-sky-500 | border-color: rgb(14 165 233); | | border-sky-600 | border-color: rgb(2 132 199); | | border-sky-700 | border-color: rgb(3 105 161); | | border-sky-800 | border-color: rgb(7 89 133); | | border-sky-900 | border-color: rgb(12 74 110); | | border-sky-950 | border-color: rgb(8 47 73); | | border-blue-50 | border-color: rgb(239 246 255); | | border-blue-100 | border-color: rgb(219 234 254); | | border-blue-200 | border-color: rgb(191 219 254); | | border-blue-300 | border-color: rgb(147 197 253); | | border-blue-400 | border-color: rgb(96 165 250); | | border-blue-500 | border-color: rgb(59 130 246); | | border-blue-600 | border-color: rgb(37 99 235); | | border-blue-700 | border-color: rgb(29 78 216); | | border-blue-800 | border-color: rgb(30 64 175); | | border-blue-900 | border-color: rgb(30 58 138); | | border-blue-950 | border-color: rgb(23 37 84); | | border-indigo-50 | border-color: rgb(238 242 255); | | border-indigo-100 | border-color: rgb(224 231 255); | | border-indigo-200 | border-color: rgb(199 210 254); | | border-indigo-300 | border-color: rgb(165 180 252); | | border-indigo-400 | border-color: rgb(129 140 248); | | border-indigo-500 | border-color: rgb(99 102 241); | | border-indigo-600 | border-color: rgb(79 70 229); | | border-indigo-700 | border-color: rgb(67 56 202); | | border-indigo-800 | border-color: rgb(55 48 163); | | border-indigo-900 | border-color: rgb(49 46 129); | | border-indigo-950 | border-color: rgb(30 27 75); | | border-violet-50 | border-color: rgb(245 243 255); | | border-violet-100 | border-color: rgb(237 233 254); | | border-violet-200 | border-color: rgb(221 214 254); | | border-violet-300 | border-color: rgb(196 181 253); | | border-violet-400 | border-color: rgb(167 139 250); | | border-violet-500 | border-color: rgb(139 92 246); | | border-violet-600 | border-color: rgb(124 58 237); | | border-violet-700 | border-color: rgb(109 40 217); | | border-violet-800 | border-color: rgb(91 33 182); | | border-violet-900 | border-color: rgb(76 29 149); | | border-violet-950 | border-color: rgb(46 16 101); | | border-purple-50 | border-color: rgb(250 245 255); | | border-purple-100 | border-color: rgb(243 232 255); | | border-purple-200 | border-color: rgb(233 213 255); | | border-purple-300 | border-color: rgb(216 180 254); | | border-purple-400 | border-color: rgb(192 132 252); | | border-purple-500 | border-color: rgb(168 85 247); | | border-purple-600 | border-color: rgb(147 51 234); | | border-purple-700 | border-color: rgb(126 34 206); | | border-purple-800 | border-color: rgb(107 33 168); | | border-purple-900 | border-color: rgb(88 28 135); | | border-purple-950 | border-color: rgb(59 7 100); | | border-fuchsia-50 | border-color: rgb(253 244 255); | | border-fuchsia-100 | border-color: rgb(250 232 255); | | border-fuchsia-200 | border-color: rgb(245 208 254); | | border-fuchsia-300 | border-color: rgb(240 171 252); | | border-fuchsia-400 | border-color: rgb(232 121 249); | | border-fuchsia-500 | border-color: rgb(217 70 239); | | border-fuchsia-600 | border-color: rgb(192 38 211); | | border-fuchsia-700 | border-color: rgb(162 28 175); | | border-fuchsia-800 | border-color: rgb(134 25 143); | | border-fuchsia-900 | border-color: rgb(112 26 117); | | border-fuchsia-950 | border-color: rgb(74 4 78); | | border-pink-50 | border-color: rgb(253 242 248); | | border-pink-100 | border-color: rgb(252 231 243); | | border-pink-200 | border-color: rgb(251 207 232); | | border-pink-300 | border-color: rgb(249 168 212); | | border-pink-400 | border-color: rgb(244 114 182); | | border-pink-500 | border-color: rgb(236 72 153); | | border-pink-600 | border-color: rgb(219 39 119); | | border-pink-700 | border-color: rgb(190 24 93); | | border-pink-800 | border-color: rgb(157 23 77); | | border-pink-900 | border-color: rgb(131 24 67); | | border-pink-950 | border-color: rgb(80 7 36); | | border-rose-50 | border-color: rgb(255 241 242); | | border-rose-100 | border-color: rgb(255 228 230); | | border-rose-200 | border-color: rgb(254 205 211); | | border-rose-300 | border-color: rgb(253 164 175); | | border-rose-400 | border-color: rgb(251 113 133); | | border-rose-500 | border-color: rgb(244 63 94); | | border-rose-600 | border-color: rgb(225 29 72); | | border-rose-700 | border-color: rgb(190 18 60); | | border-rose-800 | border-color: rgb(159 18 57); | | border-rose-900 | border-color: rgb(136 19 55); | | border-rose-950 | border-color: rgb(76 5 25); | | border-x-inherit | border-left-color: inherit; border-right-color: inherit; | | border-x-current | border-left-color: currentColor; border-right-color: currentColor; | | border-x-transparent | border-left-color: transparent; border-right-color: transparent; | | border-x-black | border-left-color: rgb(0 0 0); border-right-color: rgb(0 0 0); | | border-x-white | border-left-color: rgb(255 255 255); border-right-color: rgb(255 255 255); | | border-x-slate-50 | border-left-color: rgb(248 250 252); border-right-color: rgb(248 250 252); | | border-x-slate-100 | border-left-color: rgb(241 245 249); border-right-color: rgb(241 245 249); | | border-x-slate-200 | border-left-color: rgb(226 232 240); border-right-color: rgb(226 232 240); | | border-x-slate-300 | border-left-color: rgb(203 213 225); border-right-color: rgb(203 213 225); | | border-x-slate-400 | border-left-color: rgb(148 163 184); border-right-color: rgb(148 163 184); | | border-x-slate-500 | border-left-color: rgb(100 116 139); border-right-color: rgb(100 116 139); | | border-x-slate-600 | border-left-color: rgb(71 85 105); border-right-color: rgb(71 85 105); | | border-x-slate-700 | border-left-color: rgb(51 65 85); border-right-color: rgb(51 65 85); | | border-x-slate-800 | border-left-color: rgb(30 41 59); border-right-color: rgb(30 41 59); | | border-x-slate-900 | border-left-color: rgb(15 23 42); border-right-color: rgb(15 23 42); | | border-x-slate-950 | border-left-color: rgb(2 6 23); border-right-color: rgb(2 6 23); | | border-x-gray-50 | border-left-color: rgb(249 250 251); border-right-color: rgb(249 250 251); | | border-x-gray-100 | border-left-color: rgb(243 244 246); border-right-color: rgb(243 244 246); | | border-x-gray-200 | border-left-color: rgb(229 231 235); border-right-color: rgb(229 231 235); | | border-x-gray-300 | border-left-color: rgb(209 213 219); border-right-color: rgb(209 213 219); | | border-x-gray-400 | border-left-color: rgb(156 163 175); border-right-color: rgb(156 163 175); | | border-x-gray-500 | border-left-color: rgb(107 114 128); border-right-color: rgb(107 114 128); | | border-x-gray-600 | border-left-color: rgb(75 85 99); border-right-color: rgb(75 85 99); | | border-x-gray-700 | border-left-color: rgb(55 65 81); border-right-color: rgb(55 65 81); | | border-x-gray-800 | border-left-color: rgb(31 41 55); border-right-color: rgb(31 41 55); | | border-x-gray-900 | border-left-color: rgb(17 24 39); border-right-color: rgb(17 24 39); | | border-x-gray-950 | border-left-color: rgb(3 7 18); border-right-color: rgb(3 7 18); | | border-x-zinc-50 | border-left-color: rgb(250 250 250); border-right-color: rgb(250 250 250); | | border-x-zinc-100 | border-left-color: rgb(244 244 245); border-right-color: rgb(244 244 245); | | border-x-zinc-200 | border-left-color: rgb(228 228 231); border-right-color: rgb(228 228 231); | | border-x-zinc-300 | border-left-color: rgb(212 212 216); border-right-color: rgb(212 212 216); | | border-x-zinc-400 | border-left-color: rgb(161 161 170); border-right-color: rgb(161 161 170); | | border-x-zinc-500 | border-left-color: rgb(113 113 122); border-right-color: rgb(113 113 122); | | border-x-zinc-600 | border-left-color: rgb(82 82 91); border-right-color: rgb(82 82 91); | | border-x-zinc-700 | border-left-color: rgb(63 63 70); border-right-color: rgb(63 63 70); | | border-x-zinc-800 | border-left-color: rgb(39 39 42); border-right-color: rgb(39 39 42); | | border-x-zinc-900 | border-left-color: rgb(24 24 27); border-right-color: rgb(24 24 27); | | border-x-zinc-950 | border-left-color: rgb(9 9 11); border-right-color: rgb(9 9 11); | | border-x-neutral-50 | border-left-color: rgb(250 250 250); border-right-color: rgb(250 250 250); | | border-x-neutral-100 | border-left-color: rgb(245 245 245); border-right-color: rgb(245 245 245); | | border-x-neutral-200 | border-left-color: rgb(229 229 229); border-right-color: rgb(229 229 229); | | border-x-neutral-300 | border-left-color: rgb(212 212 212); border-right-color: rgb(212 212 212); | | border-x-neutral-400 | border-left-color: rgb(163 163 163); border-right-color: rgb(163 163 163); | | border-x-neutral-500 | border-left-color: rgb(115 115 115); border-right-color: rgb(115 115 115); | | border-x-neutral-600 | border-left-color: rgb(82 82 82); border-right-color: rgb(82 82 82); | | border-x-neutral-700 | border-left-color: rgb(64 64 64); border-right-color: rgb(64 64 64); | | border-x-neutral-800 | border-left-color: rgb(38 38 38); border-right-color: rgb(38 38 38); | | border-x-neutral-900 | border-left-color: rgb(23 23 23); border-right-color: rgb(23 23 23); | | border-x-neutral-950 | border-left-color: rgb(10 10 10); border-right-color: rgb(10 10 10); | | border-x-stone-50 | border-left-color: rgb(250 250 249); border-right-color: rgb(250 250 249); | | border-x-stone-100 | border-left-color: rgb(245 245 244); border-right-color: rgb(245 245 244); | | border-x-stone-200 | border-left-color: rgb(231 229 228); border-right-color: rgb(231 229 228); | | border-x-stone-300 | border-left-color: rgb(214 211 209); border-right-color: rgb(214 211 209); | | border-x-stone-400 | border-left-color: rgb(168 162 158); border-right-color: rgb(168 162 158); | | border-x-stone-500 | border-left-color: rgb(120 113 108); border-right-color: rgb(120 113 108); | | border-x-stone-600 | border-left-color: rgb(87 83 78); border-right-color: rgb(87 83 78); | | border-x-stone-700 | border-left-color: rgb(68 64 60); border-right-color: rgb(68 64 60); | | border-x-stone-800 | border-left-color: rgb(41 37 36); border-right-color: rgb(41 37 36); | | border-x-stone-900 | border-left-color: rgb(28 25 23); border-right-color: rgb(28 25 23); | | border-x-stone-950 | border-left-color: rgb(12 10 9); border-right-color: rgb(12 10 9); | | border-x-red-50 | border-left-color: rgb(254 242 242); border-right-color: rgb(254 242 242); | | border-x-red-100 | border-left-color: rgb(254 226 226); border-right-color: rgb(254 226 226); | | border-x-red-200 | border-left-color: rgb(254 202 202); border-right-color: rgb(254 202 202); | | border-x-red-300 | border-left-color: rgb(252 165 165); border-right-color: rgb(252 165 165); | | border-x-red-400 | border-left-color: rgb(248 113 113); border-right-color: rgb(248 113 113); | | border-x-red-500 | border-left-color: rgb(239 68 68); border-right-color: rgb(239 68 68); | | border-x-red-600 | border-left-color: rgb(220 38 38); border-right-color: rgb(220 38 38); | | border-x-red-700 | border-left-color: rgb(185 28 28); border-right-color: rgb(185 28 28); | | border-x-red-800 | border-left-color: rgb(153 27 27); border-right-color: rgb(153 27 27); | | border-x-red-900 | border-left-color: rgb(127 29 29); border-right-color: rgb(127 29 29); | | border-x-red-950 | border-left-color: rgb(69 10 10); border-right-color: rgb(69 10 10); | | border-x-orange-50 | border-left-color: rgb(255 247 237); border-right-color: rgb(255 247 237); | | border-x-orange-100 | border-left-color: rgb(255 237 213); border-right-color: rgb(255 237 213); | | border-x-orange-200 | border-left-color: rgb(254 215 170); border-right-color: rgb(254 215 170); | | border-x-orange-300 | border-left-color: rgb(253 186 116); border-right-color: rgb(253 186 116); | | border-x-orange-400 | border-left-color: rgb(251 146 60); border-right-color: rgb(251 146 60); | | border-x-orange-500 | border-left-color: rgb(249 115 22); border-right-color: rgb(249 115 22); | | border-x-orange-600 | border-left-color: rgb(234 88 12); border-right-color: rgb(234 88 12); | | border-x-orange-700 | border-left-color: rgb(194 65 12); border-right-color: rgb(194 65 12); | | border-x-orange-800 | border-left-color: rgb(154 52 18); border-right-color: rgb(154 52 18); | | border-x-orange-900 | border-left-color: rgb(124 45 18); border-right-color: rgb(124 45 18); | | border-x-orange-950 | border-left-color: rgb(67 20 7); border-right-color: rgb(67 20 7); | | border-x-amber-50 | border-left-color: rgb(255 251 235); border-right-color: rgb(255 251 235); | | border-x-amber-100 | border-left-color: rgb(254 243 199); border-right-color: rgb(254 243 199); | | border-x-amber-200 | border-left-color: rgb(253 230 138); border-right-color: rgb(253 230 138); | | border-x-amber-300 | border-left-color: rgb(252 211 77); border-right-color: rgb(252 211 77); | | border-x-amber-400 | border-left-color: rgb(251 191 36); border-right-color: rgb(251 191 36); | | border-x-amber-500 | border-left-color: rgb(245 158 11); border-right-color: rgb(245 158 11); | | border-x-amber-600 | border-left-color: rgb(217 119 6); border-right-color: rgb(217 119 6); | | border-x-amber-700 | border-left-color: rgb(180 83 9); border-right-color: rgb(180 83 9); | | border-x-amber-800 | border-left-color: rgb(146 64 14); border-right-color: rgb(146 64 14); | | border-x-amber-900 | border-left-color: rgb(120 53 15); border-right-color: rgb(120 53 15); | | border-x-amber-950 | border-left-color: rgb(69 26 3); border-right-color: rgb(69 26 3); | | border-x-yellow-50 | border-left-color: rgb(254 252 232); border-right-color: rgb(254 252 232); | | border-x-yellow-100 | border-left-color: rgb(254 249 195); border-right-color: rgb(254 249 195); | | border-x-yellow-200 | border-left-color: rgb(254 240 138); border-right-color: rgb(254 240 138); | | border-x-yellow-300 | border-left-color: rgb(253 224 71); border-right-color: rgb(253 224 71); | | border-x-yellow-400 | border-left-color: rgb(250 204 21); border-right-color: rgb(250 204 21); | | border-x-yellow-500 | border-left-color: rgb(234 179 8); border-right-color: rgb(234 179 8); | | border-x-yellow-600 | border-left-color: rgb(202 138 4); border-right-color: rgb(202 138 4); | | border-x-yellow-700 | border-left-color: rgb(161 98 7); border-right-color: rgb(161 98 7); | | border-x-yellow-800 | border-left-color: rgb(133 77 14); border-right-color: rgb(133 77 14); | | border-x-yellow-900 | border-left-color: rgb(113 63 18); border-right-color: rgb(113 63 18); | | border-x-yellow-950 | border-left-color: rgb(66 32 6); border-right-color: rgb(66 32 6); | | border-x-lime-50 | border-left-color: rgb(247 254 231); border-right-color: rgb(247 254 231); | | border-x-lime-100 | border-left-color: rgb(236 252 203); border-right-color: rgb(236 252 203); | | border-x-lime-200 | border-left-color: rgb(217 249 157); border-right-color: rgb(217 249 157); | | border-x-lime-300 | border-left-color: rgb(190 242 100); border-right-color: rgb(190 242 100); | | border-x-lime-400 | border-left-color: rgb(163 230 53); border-right-color: rgb(163 230 53); | | border-x-lime-500 | border-left-color: rgb(132 204 22); border-right-color: rgb(132 204 22); | | border-x-lime-600 | border-left-color: rgb(101 163 13); border-right-color: rgb(101 163 13); | | border-x-lime-700 | border-left-color: rgb(77 124 15); border-right-color: rgb(77 124 15); | | border-x-lime-800 | border-left-color: rgb(63 98 18); border-right-color: rgb(63 98 18); | | border-x-lime-900 | border-left-color: rgb(54 83 20); border-right-color: rgb(54 83 20); | | border-x-lime-950 | border-left-color: rgb(26 46 5); border-right-color: rgb(26 46 5); | | border-x-green-50 | border-left-color: rgb(240 253 244); border-right-color: rgb(240 253 244); | | border-x-green-100 | border-left-color: rgb(220 252 231); border-right-color: rgb(220 252 231); | | border-x-green-200 | border-left-color: rgb(187 247 208); border-right-color: rgb(187 247 208); | | border-x-green-300 | border-left-color: rgb(134 239 172); border-right-color: rgb(134 239 172); | | border-x-green-400 | border-left-color: rgb(74 222 128); border-right-color: rgb(74 222 128); | | border-x-green-500 | border-left-color: rgb(34 197 94); border-right-color: rgb(34 197 94); | | border-x-green-600 | border-left-color: rgb(22 163 74); border-right-color: rgb(22 163 74); | | border-x-green-700 | border-left-color: rgb(21 128 61); border-right-color: rgb(21 128 61); | | border-x-green-800 | border-left-color: rgb(22 101 52); border-right-color: rgb(22 101 52); | | border-x-green-900 | border-left-color: rgb(20 83 45); border-right-color: rgb(20 83 45); | | border-x-green-950 | border-left-color: rgb(5 46 22); border-right-color: rgb(5 46 22); | | border-x-emerald-50 | border-left-color: rgb(236 253 245); border-right-color: rgb(236 253 245); | | border-x-emerald-100 | border-left-color: rgb(209 250 229); border-right-color: rgb(209 250 229); | | border-x-emerald-200 | border-left-color: rgb(167 243 208); border-right-color: rgb(167 243 208); | | border-x-emerald-300 | border-left-color: rgb(110 231 183); border-right-color: rgb(110 231 183); | | border-x-emerald-400 | border-left-color: rgb(52 211 153); border-right-color: rgb(52 211 153); | | border-x-emerald-500 | border-left-color: rgb(16 185 129); border-right-color: rgb(16 185 129); | | border-x-emerald-600 | border-left-color: rgb(5 150 105); border-right-color: rgb(5 150 105); | | border-x-emerald-700 | border-left-color: rgb(4 120 87); border-right-color: rgb(4 120 87); | | border-x-emerald-800 | border-left-color: rgb(6 95 70); border-right-color: rgb(6 95 70); | | border-x-emerald-900 | border-left-color: rgb(6 78 59); border-right-color: rgb(6 78 59); | | border-x-emerald-950 | border-left-color: rgb(2 44 34); border-right-color: rgb(2 44 34); | | border-x-teal-50 | border-left-color: rgb(240 253 250); border-right-color: rgb(240 253 250); | | border-x-teal-100 | border-left-color: rgb(204 251 241); border-right-color: rgb(204 251 241); | | border-x-teal-200 | border-left-color: rgb(153 246 228); border-right-color: rgb(153 246 228); | | border-x-teal-300 | border-left-color: rgb(94 234 212); border-right-color: rgb(94 234 212); | | border-x-teal-400 | border-left-color: rgb(45 212 191); border-right-color: rgb(45 212 191); | | border-x-teal-500 | border-left-color: rgb(20 184 166); border-right-color: rgb(20 184 166); | | border-x-teal-600 | border-left-color: rgb(13 148 136); border-right-color: rgb(13 148 136); | | border-x-teal-700 | border-left-color: rgb(15 118 110); border-right-color: rgb(15 118 110); | | border-x-teal-800 | border-left-color: rgb(17 94 89); border-right-color: rgb(17 94 89); | | border-x-teal-900 | border-left-color: rgb(19 78 74); border-right-color: rgb(19 78 74); | | border-x-teal-950 | border-left-color: rgb(4 47 46); border-right-color: rgb(4 47 46); | | border-x-cyan-50 | border-left-color: rgb(236 254 255); border-right-color: rgb(236 254 255); | | border-x-cyan-100 | border-left-color: rgb(207 250 254); border-right-color: rgb(207 250 254); | | border-x-cyan-200 | border-left-color: rgb(165 243 252); border-right-color: rgb(165 243 252); | | border-x-cyan-300 | border-left-color: rgb(103 232 249); border-right-color: rgb(103 232 249); | | border-x-cyan-400 | border-left-color: rgb(34 211 238); border-right-color: rgb(34 211 238); | | border-x-cyan-500 | border-left-color: rgb(6 182 212); border-right-color: rgb(6 182 212); | | border-x-cyan-600 | border-left-color: rgb(8 145 178); border-right-color: rgb(8 145 178); | | border-x-cyan-700 | border-left-color: rgb(14 116 144); border-right-color: rgb(14 116 144); | | border-x-cyan-800 | border-left-color: rgb(21 94 117); border-right-color: rgb(21 94 117); | | border-x-cyan-900 | border-left-color: rgb(22 78 99); border-right-color: rgb(22 78 99); | | border-x-cyan-950 | border-left-color: rgb(8 51 68); border-right-color: rgb(8 51 68); | | border-x-sky-50 | border-left-color: rgb(240 249 255); border-right-color: rgb(240 249 255); | | border-x-sky-100 | border-left-color: rgb(224 242 254); border-right-color: rgb(224 242 254); | | border-x-sky-200 | border-left-color: rgb(186 230 253); border-right-color: rgb(186 230 253); | | border-x-sky-300 | border-left-color: rgb(125 211 252); border-right-color: rgb(125 211 252); | | border-x-sky-400 | border-left-color: rgb(56 189 248); border-right-color: rgb(56 189 248); | | border-x-sky-500 | border-left-color: rgb(14 165 233); border-right-color: rgb(14 165 233); | | border-x-sky-600 | border-left-color: rgb(2 132 199); border-right-color: rgb(2 132 199); | | border-x-sky-700 | border-left-color: rgb(3 105 161); border-right-color: rgb(3 105 161); | | border-x-sky-800 | border-left-color: rgb(7 89 133); border-right-color: rgb(7 89 133); | | border-x-sky-900 | border-left-color: rgb(12 74 110); border-right-color: rgb(12 74 110); | | border-x-sky-950 | border-left-color: rgb(8 47 73); border-right-color: rgb(8 47 73); | | border-x-blue-50 | border-left-color: rgb(239 246 255); border-right-color: rgb(239 246 255); | | border-x-blue-100 | border-left-color: rgb(219 234 254); border-right-color: rgb(219 234 254); | | border-x-blue-200 | border-left-color: rgb(191 219 254); border-right-color: rgb(191 219 254); | | border-x-blue-300 | border-left-color: rgb(147 197 253); border-right-color: rgb(147 197 253); | | border-x-blue-400 | border-left-color: rgb(96 165 250); border-right-color: rgb(96 165 250); | | border-x-blue-500 | border-left-color: rgb(59 130 246); border-right-color: rgb(59 130 246); | | border-x-blue-600 | border-left-color: rgb(37 99 235); border-right-color: rgb(37 99 235); | | border-x-blue-700 | border-left-color: rgb(29 78 216); border-right-color: rgb(29 78 216); | | border-x-blue-800 | border-left-color: rgb(30 64 175); border-right-color: rgb(30 64 175); | | border-x-blue-900 | border-left-color: rgb(30 58 138); border-right-color: rgb(30 58 138); | | border-x-blue-950 | border-left-color: rgb(23 37 84); border-right-color: rgb(23 37 84); | | border-x-indigo-50 | border-left-color: rgb(238 242 255); border-right-color: rgb(238 242 255); | | border-x-indigo-100 | border-left-color: rgb(224 231 255); border-right-color: rgb(224 231 255); | | border-x-indigo-200 | border-left-color: rgb(199 210 254); border-right-color: rgb(199 210 254); | | border-x-indigo-300 | border-left-color: rgb(165 180 252); border-right-color: rgb(165 180 252); | | border-x-indigo-400 | border-left-color: rgb(129 140 248); border-right-color: rgb(129 140 248); | | border-x-indigo-500 | border-left-color: rgb(99 102 241); border-right-color: rgb(99 102 241); | | border-x-indigo-600 | border-left-color: rgb(79 70 229); border-right-color: rgb(79 70 229); | | border-x-indigo-700 | border-left-color: rgb(67 56 202); border-right-color: rgb(67 56 202); | | border-x-indigo-800 | border-left-color: rgb(55 48 163); border-right-color: rgb(55 48 163); | | border-x-indigo-900 | border-left-color: rgb(49 46 129); border-right-color: rgb(49 46 129); | | border-x-indigo-950 | border-left-color: rgb(30 27 75); border-right-color: rgb(30 27 75); | | border-x-violet-50 | border-left-color: rgb(245 243 255); border-right-color: rgb(245 243 255); | | border-x-violet-100 | border-left-color: rgb(237 233 254); border-right-color: rgb(237 233 254); | | border-x-violet-200 | border-left-color: rgb(221 214 254); border-right-color: rgb(221 214 254); | | border-x-violet-300 | border-left-color: rgb(196 181 253); border-right-color: rgb(196 181 253); | | border-x-violet-400 | border-left-color: rgb(167 139 250); border-right-color: rgb(167 139 250); | | border-x-violet-500 | border-left-color: rgb(139 92 246); border-right-color: rgb(139 92 246); | | border-x-violet-600 | border-left-color: rgb(124 58 237); border-right-color: rgb(124 58 237); | | border-x-violet-700 | border-left-color: rgb(109 40 217); border-right-color: rgb(109 40 217); | | border-x-violet-800 | border-left-color: rgb(91 33 182); border-right-color: rgb(91 33 182); | | border-x-violet-900 | border-left-color: rgb(76 29 149); border-right-color: rgb(76 29 149); | | border-x-violet-950 | border-left-color: rgb(46 16 101); border-right-color: rgb(46 16 101); | | border-x-purple-50 | border-left-color: rgb(250 245 255); border-right-color: rgb(250 245 255); | | border-x-purple-100 | border-left-color: rgb(243 232 255); border-right-color: rgb(243 232 255); | | border-x-purple-200 | border-left-color: rgb(233 213 255); border-right-color: rgb(233 213 255); | | border-x-purple-300 | border-left-color: rgb(216 180 254); border-right-color: rgb(216 180 254); | | border-x-purple-400 | border-left-color: rgb(192 132 252); border-right-color: rgb(192 132 252); | | border-x-purple-500 | border-left-color: rgb(168 85 247); border-right-color: rgb(168 85 247); | | border-x-purple-600 | border-left-color: rgb(147 51 234); border-right-color: rgb(147 51 234); | | border-x-purple-700 | border-left-color: rgb(126 34 206); border-right-color: rgb(126 34 206); | | border-x-purple-800 | border-left-color: rgb(107 33 168); border-right-color: rgb(107 33 168); | | border-x-purple-900 | border-left-color: rgb(88 28 135); border-right-color: rgb(88 28 135); | | border-x-purple-950 | border-left-color: rgb(59 7 100); border-right-color: rgb(59 7 100); | | border-x-fuchsia-50 | border-left-color: rgb(253 244 255); border-right-color: rgb(253 244 255); | | border-x-fuchsia-100 | border-left-color: rgb(250 232 255); border-right-color: rgb(250 232 255); | | border-x-fuchsia-200 | border-left-color: rgb(245 208 254); border-right-color: rgb(245 208 254); | | border-x-fuchsia-300 | border-left-color: rgb(240 171 252); border-right-color: rgb(240 171 252); | | border-x-fuchsia-400 | border-left-color: rgb(232 121 249); border-right-color: rgb(232 121 249); | | border-x-fuchsia-500 | border-left-color: rgb(217 70 239); border-right-color: rgb(217 70 239); | | border-x-fuchsia-600 | border-left-color: rgb(192 38 211); border-right-color: rgb(192 38 211); | | border-x-fuchsia-700 | border-left-color: rgb(162 28 175); border-right-color: rgb(162 28 175); | | border-x-fuchsia-800 | border-left-color: rgb(134 25 143); border-right-color: rgb(134 25 143); | | border-x-fuchsia-900 | border-left-color: rgb(112 26 117); border-right-color: rgb(112 26 117); | | border-x-fuchsia-950 | border-left-color: rgb(74 4 78); border-right-color: rgb(74 4 78); | | border-x-pink-50 | border-left-color: rgb(253 242 248); border-right-color: rgb(253 242 248); | | border-x-pink-100 | border-left-color: rgb(252 231 243); border-right-color: rgb(252 231 243); | | border-x-pink-200 | border-left-color: rgb(251 207 232); border-right-color: rgb(251 207 232); | | border-x-pink-300 | border-left-color: rgb(249 168 212); border-right-color: rgb(249 168 212); | | border-x-pink-400 | border-left-color: rgb(244 114 182); border-right-color: rgb(244 114 182); | | border-x-pink-500 | border-left-color: rgb(236 72 153); border-right-color: rgb(236 72 153); | | border-x-pink-600 | border-left-color: rgb(219 39 119); border-right-color: rgb(219 39 119); | | border-x-pink-700 | border-left-color: rgb(190 24 93); border-right-color: rgb(190 24 93); | | border-x-pink-800 | border-left-color: rgb(157 23 77); border-right-color: rgb(157 23 77); | | border-x-pink-900 | border-left-color: rgb(131 24 67); border-right-color: rgb(131 24 67); | | border-x-pink-950 | border-left-color: rgb(80 7 36); border-right-color: rgb(80 7 36); | | border-x-rose-50 | border-left-color: rgb(255 241 242); border-right-color: rgb(255 241 242); | | border-x-rose-100 | border-left-color: rgb(255 228 230); border-right-color: rgb(255 228 230); | | border-x-rose-200 | border-left-color: rgb(254 205 211); border-right-color: rgb(254 205 211); | | border-x-rose-300 | border-left-color: rgb(253 164 175); border-right-color: rgb(253 164 175); | | border-x-rose-400 | border-left-color: rgb(251 113 133); border-right-color: rgb(251 113 133); | | border-x-rose-500 | border-left-color: rgb(244 63 94); border-right-color: rgb(244 63 94); | | border-x-rose-600 | border-left-color: rgb(225 29 72); border-right-color: rgb(225 29 72); | | border-x-rose-700 | border-left-color: rgb(190 18 60); border-right-color: rgb(190 18 60); | | border-x-rose-800 | border-left-color: rgb(159 18 57); border-right-color: rgb(159 18 57); | | border-x-rose-900 | border-left-color: rgb(136 19 55); border-right-color: rgb(136 19 55); | | border-x-rose-950 | border-left-color: rgb(76 5 25); border-right-color: rgb(76 5 25); | | border-y-inherit | border-top-color: inherit; border-bottom-color: inherit; | | border-y-current | border-top-color: currentColor; border-bottom-color: currentColor; | | border-y-transparent | border-top-color: transparent; border-bottom-color: transparent; | | border-y-black | border-top-color: rgb(0 0 0); border-bottom-color: rgb(0 0 0); | | border-y-white | border-top-color: rgb(255 255 255); border-bottom-color: rgb(255 255 255); | | border-y-slate-50 | border-top-color: rgb(248 250 252); border-bottom-color: rgb(248 250 252); | | border-y-slate-100 | border-top-color: rgb(241 245 249); border-bottom-color: rgb(241 245 249); | | border-y-slate-200 | border-top-color: rgb(226 232 240); border-bottom-color: rgb(226 232 240); | | border-y-slate-300 | border-top-color: rgb(203 213 225); border-bottom-color: rgb(203 213 225); | | border-y-slate-400 | border-top-color: rgb(148 163 184); border-bottom-color: rgb(148 163 184); | | border-y-slate-500 | border-top-color: rgb(100 116 139); border-bottom-color: rgb(100 116 139); | | border-y-slate-600 | border-top-color: rgb(71 85 105); border-bottom-color: rgb(71 85 105); | | border-y-slate-700 | border-top-color: rgb(51 65 85); border-bottom-color: rgb(51 65 85); | | border-y-slate-800 | border-top-color: rgb(30 41 59); border-bottom-color: rgb(30 41 59); | | border-y-slate-900 | border-top-color: rgb(15 23 42); border-bottom-color: rgb(15 23 42); | | border-y-slate-950 | border-top-color: rgb(2 6 23); border-bottom-color: rgb(2 6 23); | | border-y-gray-50 | border-top-color: rgb(249 250 251); border-bottom-color: rgb(249 250 251); | | border-y-gray-100 | border-top-color: rgb(243 244 246); border-bottom-color: rgb(243 244 246); | | border-y-gray-200 | border-top-color: rgb(229 231 235); border-bottom-color: rgb(229 231 235); | | border-y-gray-300 | border-top-color: rgb(209 213 219); border-bottom-color: rgb(209 213 219); | | border-y-gray-400 | border-top-color: rgb(156 163 175); border-bottom-color: rgb(156 163 175); | | border-y-gray-500 | border-top-color: rgb(107 114 128); border-bottom-color: rgb(107 114 128); | | border-y-gray-600 | border-top-color: rgb(75 85 99); border-bottom-color: rgb(75 85 99); | | border-y-gray-700 | border-top-color: rgb(55 65 81); border-bottom-color: rgb(55 65 81); | | border-y-gray-800 | border-top-color: rgb(31 41 55); border-bottom-color: rgb(31 41 55); | | border-y-gray-900 | border-top-color: rgb(17 24 39); border-bottom-color: rgb(17 24 39); | | border-y-gray-950 | border-top-color: rgb(3 7 18); border-bottom-color: rgb(3 7 18); | | border-y-zinc-50 | border-top-color: rgb(250 250 250); border-bottom-color: rgb(250 250 250); | | border-y-zinc-100 | border-top-color: rgb(244 244 245); border-bottom-color: rgb(244 244 245); | | border-y-zinc-200 | border-top-color: rgb(228 228 231); border-bottom-color: rgb(228 228 231); | | border-y-zinc-300 | border-top-color: rgb(212 212 216); border-bottom-color: rgb(212 212 216); | | border-y-zinc-400 | border-top-color: rgb(161 161 170); border-bottom-color: rgb(161 161 170); | | border-y-zinc-500 | border-top-color: rgb(113 113 122); border-bottom-color: rgb(113 113 122); | | border-y-zinc-600 | border-top-color: rgb(82 82 91); border-bottom-color: rgb(82 82 91); | | border-y-zinc-700 | border-top-color: rgb(63 63 70); border-bottom-color: rgb(63 63 70); | | border-y-zinc-800 | border-top-color: rgb(39 39 42); border-bottom-color: rgb(39 39 42); | | border-y-zinc-900 | border-top-color: rgb(24 24 27); border-bottom-color: rgb(24 24 27); | | border-y-zinc-950 | border-top-color: rgb(9 9 11); border-bottom-color: rgb(9 9 11); | | border-y-neutral-50 | border-top-color: rgb(250 250 250); border-bottom-color: rgb(250 250 250); | | border-y-neutral-100 | border-top-color: rgb(245 245 245); border-bottom-color: rgb(245 245 245); | | border-y-neutral-200 | border-top-color: rgb(229 229 229); border-bottom-color: rgb(229 229 229); | | border-y-neutral-300 | border-top-color: rgb(212 212 212); border-bottom-color: rgb(212 212 212); | | border-y-neutral-400 | border-top-color: rgb(163 163 163); border-bottom-color: rgb(163 163 163); | | border-y-neutral-500 | border-top-color: rgb(115 115 115); border-bottom-color: rgb(115 115 115); | | border-y-neutral-600 | border-top-color: rgb(82 82 82); border-bottom-color: rgb(82 82 82); | | border-y-neutral-700 | border-top-color: rgb(64 64 64); border-bottom-color: rgb(64 64 64); | | border-y-neutral-800 | border-top-color: rgb(38 38 38); border-bottom-color: rgb(38 38 38); | | border-y-neutral-900 | border-top-color: rgb(23 23 23); border-bottom-color: rgb(23 23 23); | | border-y-neutral-950 | border-top-color: rgb(10 10 10); border-bottom-color: rgb(10 10 10); | | border-y-stone-50 | border-top-color: rgb(250 250 249); border-bottom-color: rgb(250 250 249); | | border-y-stone-100 | border-top-color: rgb(245 245 244); border-bottom-color: rgb(245 245 244); | | border-y-stone-200 | border-top-color: rgb(231 229 228); border-bottom-color: rgb(231 229 228); | | border-y-stone-300 | border-top-color: rgb(214 211 209); border-bottom-color: rgb(214 211 209); | | border-y-stone-400 | border-top-color: rgb(168 162 158); border-bottom-color: rgb(168 162 158); | | border-y-stone-500 | border-top-color: rgb(120 113 108); border-bottom-color: rgb(120 113 108); | | border-y-stone-600 | border-top-color: rgb(87 83 78); border-bottom-color: rgb(87 83 78); | | border-y-stone-700 | border-top-color: rgb(68 64 60); border-bottom-color: rgb(68 64 60); | | border-y-stone-800 | border-top-color: rgb(41 37 36); border-bottom-color: rgb(41 37 36); | | border-y-stone-900 | border-top-color: rgb(28 25 23); border-bottom-color: rgb(28 25 23); | | border-y-stone-950 | border-top-color: rgb(12 10 9); border-bottom-color: rgb(12 10 9); | | border-y-red-50 | border-top-color: rgb(254 242 242); border-bottom-color: rgb(254 242 242); | | border-y-red-100 | border-top-color: rgb(254 226 226); border-bottom-color: rgb(254 226 226); | | border-y-red-200 | border-top-color: rgb(254 202 202); border-bottom-color: rgb(254 202 202); | | border-y-red-300 | border-top-color: rgb(252 165 165); border-bottom-color: rgb(252 165 165); | | border-y-red-400 | border-top-color: rgb(248 113 113); border-bottom-color: rgb(248 113 113); | | border-y-red-500 | border-top-color: rgb(239 68 68); border-bottom-color: rgb(239 68 68); | | border-y-red-600 | border-top-color: rgb(220 38 38); border-bottom-color: rgb(220 38 38); | | border-y-red-700 | border-top-color: rgb(185 28 28); border-bottom-color: rgb(185 28 28); | | border-y-red-800 | border-top-color: rgb(153 27 27); border-bottom-color: rgb(153 27 27); | | border-y-red-900 | border-top-color: rgb(127 29 29); border-bottom-color: rgb(127 29 29); | | border-y-red-950 | border-top-color: rgb(69 10 10); border-bottom-color: rgb(69 10 10); | | border-y-orange-50 | border-top-color: rgb(255 247 237); border-bottom-color: rgb(255 247 237); | | border-y-orange-100 | border-top-color: rgb(255 237 213); border-bottom-color: rgb(255 237 213); | | border-y-orange-200 | border-top-color: rgb(254 215 170); border-bottom-color: rgb(254 215 170); | | border-y-orange-300 | border-top-color: rgb(253 186 116); border-bottom-color: rgb(253 186 116); | | border-y-orange-400 | border-top-color: rgb(251 146 60); border-bottom-color: rgb(251 146 60); | | border-y-orange-500 | border-top-color: rgb(249 115 22); border-bottom-color: rgb(249 115 22); | | border-y-orange-600 | border-top-color: rgb(234 88 12); border-bottom-color: rgb(234 88 12); | | border-y-orange-700 | border-top-color: rgb(194 65 12); border-bottom-color: rgb(194 65 12); | | border-y-orange-800 | border-top-color: rgb(154 52 18); border-bottom-color: rgb(154 52 18); | | border-y-orange-900 | border-top-color: rgb(124 45 18); border-bottom-color: rgb(124 45 18); | | border-y-orange-950 | border-top-color: rgb(67 20 7); border-bottom-color: rgb(67 20 7); | | border-y-amber-50 | border-top-color: rgb(255 251 235); border-bottom-color: rgb(255 251 235); | | border-y-amber-100 | border-top-color: rgb(254 243 199); border-bottom-color: rgb(254 243 199); | | border-y-amber-200 | border-top-color: rgb(253 230 138); border-bottom-color: rgb(253 230 138); | | border-y-amber-300 | border-top-color: rgb(252 211 77); border-bottom-color: rgb(252 211 77); | | border-y-amber-400 | border-top-color: rgb(251 191 36); border-bottom-color: rgb(251 191 36); | | border-y-amber-500 | border-top-color: rgb(245 158 11); border-bottom-color: rgb(245 158 11); | | border-y-amber-600 | border-top-color: rgb(217 119 6); border-bottom-color: rgb(217 119 6); | | border-y-amber-700 | border-top-color: rgb(180 83 9); border-bottom-color: rgb(180 83 9); | | border-y-amber-800 | border-top-color: rgb(146 64 14); border-bottom-color: rgb(146 64 14); | | border-y-amber-900 | border-top-color: rgb(120 53 15); border-bottom-color: rgb(120 53 15); | | border-y-amber-950 | border-top-color: rgb(69 26 3); border-bottom-color: rgb(69 26 3); | | border-y-yellow-50 | border-top-color: rgb(254 252 232); border-bottom-color: rgb(254 252 232); | | border-y-yellow-100 | border-top-color: rgb(254 249 195); border-bottom-color: rgb(254 249 195); | | border-y-yellow-200 | border-top-color: rgb(254 240 138); border-bottom-color: rgb(254 240 138); | | border-y-yellow-300 | border-top-color: rgb(253 224 71); border-bottom-color: rgb(253 224 71); | | border-y-yellow-400 | border-top-color: rgb(250 204 21); border-bottom-color: rgb(250 204 21); | | border-y-yellow-500 | border-top-color: rgb(234 179 8); border-bottom-color: rgb(234 179 8); | | border-y-yellow-600 | border-top-color: rgb(202 138 4); border-bottom-color: rgb(202 138 4); | | border-y-yellow-700 | border-top-color: rgb(161 98 7); border-bottom-color: rgb(161 98 7); | | border-y-yellow-800 | border-top-color: rgb(133 77 14); border-bottom-color: rgb(133 77 14); | | border-y-yellow-900 | border-top-color: rgb(113 63 18); border-bottom-color: rgb(113 63 18); | | border-y-yellow-950 | border-top-color: rgb(66 32 6); border-bottom-color: rgb(66 32 6); | | border-y-lime-50 | border-top-color: rgb(247 254 231); border-bottom-color: rgb(247 254 231); | | border-y-lime-100 | border-top-color: rgb(236 252 203); border-bottom-color: rgb(236 252 203); | | border-y-lime-200 | border-top-color: rgb(217 249 157); border-bottom-color: rgb(217 249 157); | | border-y-lime-300 | border-top-color: rgb(190 242 100); border-bottom-color: rgb(190 242 100); | | border-y-lime-400 | border-top-color: rgb(163 230 53); border-bottom-color: rgb(163 230 53); | | border-y-lime-500 | border-top-color: rgb(132 204 22); border-bottom-color: rgb(132 204 22); | | border-y-lime-600 | border-top-color: rgb(101 163 13); border-bottom-color: rgb(101 163 13); | | border-y-lime-700 | border-top-color: rgb(77 124 15); border-bottom-color: rgb(77 124 15); | | border-y-lime-800 | border-top-color: rgb(63 98 18); border-bottom-color: rgb(63 98 18); | | border-y-lime-900 | border-top-color: rgb(54 83 20); border-bottom-color: rgb(54 83 20); | | border-y-lime-950 | border-top-color: rgb(26 46 5); border-bottom-color: rgb(26 46 5); | | border-y-green-50 | border-top-color: rgb(240 253 244); border-bottom-color: rgb(240 253 244); | | border-y-green-100 | border-top-color: rgb(220 252 231); border-bottom-color: rgb(220 252 231); | | border-y-green-200 | border-top-color: rgb(187 247 208); border-bottom-color: rgb(187 247 208); | | border-y-green-300 | border-top-color: rgb(134 239 172); border-bottom-color: rgb(134 239 172); | | border-y-green-400 | border-top-color: rgb(74 222 128); border-bottom-color: rgb(74 222 128); | | border-y-green-500 | border-top-color: rgb(34 197 94); border-bottom-color: rgb(34 197 94); | | border-y-green-600 | border-top-color: rgb(22 163 74); border-bottom-color: rgb(22 163 74); | | border-y-green-700 | border-top-color: rgb(21 128 61); border-bottom-color: rgb(21 128 61); | | border-y-green-800 | border-top-color: rgb(22 101 52); border-bottom-color: rgb(22 101 52); | | border-y-green-900 | border-top-color: rgb(20 83 45); border-bottom-color: rgb(20 83 45); | | border-y-green-950 | border-top-color: rgb(5 46 22); border-bottom-color: rgb(5 46 22); | | border-y-emerald-50 | border-top-color: rgb(236 253 245); border-bottom-color: rgb(236 253 245); | | border-y-emerald-100 | border-top-color: rgb(209 250 229); border-bottom-color: rgb(209 250 229); | | border-y-emerald-200 | border-top-color: rgb(167 243 208); border-bottom-color: rgb(167 243 208); | | border-y-emerald-300 | border-top-color: rgb(110 231 183); border-bottom-color: rgb(110 231 183); | | border-y-emerald-400 | border-top-color: rgb(52 211 153); border-bottom-color: rgb(52 211 153); | | border-y-emerald-500 | border-top-color: rgb(16 185 129); border-bottom-color: rgb(16 185 129); | | border-y-emerald-600 | border-top-color: rgb(5 150 105); border-bottom-color: rgb(5 150 105); | | border-y-emerald-700 | border-top-color: rgb(4 120 87); border-bottom-color: rgb(4 120 87); | | border-y-emerald-800 | border-top-color: rgb(6 95 70); border-bottom-color: rgb(6 95 70); | | border-y-emerald-900 | border-top-color: rgb(6 78 59); border-bottom-color: rgb(6 78 59); | | border-y-emerald-950 | border-top-color: rgb(2 44 34); border-bottom-color: rgb(2 44 34); | | border-y-teal-50 | border-top-color: rgb(240 253 250); border-bottom-color: rgb(240 253 250); | | border-y-teal-100 | border-top-color: rgb(204 251 241); border-bottom-color: rgb(204 251 241); | | border-y-teal-200 | border-top-color: rgb(153 246 228); border-bottom-color: rgb(153 246 228); | | border-y-teal-300 | border-top-color: rgb(94 234 212); border-bottom-color: rgb(94 234 212); | | border-y-teal-400 | border-top-color: rgb(45 212 191); border-bottom-color: rgb(45 212 191); | | border-y-teal-500 | border-top-color: rgb(20 184 166); border-bottom-color: rgb(20 184 166); | | border-y-teal-600 | border-top-color: rgb(13 148 136); border-bottom-color: rgb(13 148 136); | | border-y-teal-700 | border-top-color: rgb(15 118 110); border-bottom-color: rgb(15 118 110); | | border-y-teal-800 | border-top-color: rgb(17 94 89); border-bottom-color: rgb(17 94 89); | | border-y-teal-900 | border-top-color: rgb(19 78 74); border-bottom-color: rgb(19 78 74); | | border-y-teal-950 | border-top-color: rgb(4 47 46); border-bottom-color: rgb(4 47 46); | | border-y-cyan-50 | border-top-color: rgb(236 254 255); border-bottom-color: rgb(236 254 255); | | border-y-cyan-100 | border-top-color: rgb(207 250 254); border-bottom-color: rgb(207 250 254); | | border-y-cyan-200 | border-top-color: rgb(165 243 252); border-bottom-color: rgb(165 243 252); | | border-y-cyan-300 | border-top-color: rgb(103 232 249); border-bottom-color: rgb(103 232 249); | | border-y-cyan-400 | border-top-color: rgb(34 211 238); border-bottom-color: rgb(34 211 238); | | border-y-cyan-500 | border-top-color: rgb(6 182 212); border-bottom-color: rgb(6 182 212); | | border-y-cyan-600 | border-top-color: rgb(8 145 178); border-bottom-color: rgb(8 145 178); | | border-y-cyan-700 | border-top-color: rgb(14 116 144); border-bottom-color: rgb(14 116 144); | | border-y-cyan-800 | border-top-color: rgb(21 94 117); border-bottom-color: rgb(21 94 117); | | border-y-cyan-900 | border-top-color: rgb(22 78 99); border-bottom-color: rgb(22 78 99); | | border-y-cyan-950 | border-top-color: rgb(8 51 68); border-bottom-color: rgb(8 51 68); | | border-y-sky-50 | border-top-color: rgb(240 249 255); border-bottom-color: rgb(240 249 255); | | border-y-sky-100 | border-top-color: rgb(224 242 254); border-bottom-color: rgb(224 242 254); | | border-y-sky-200 | border-top-color: rgb(186 230 253); border-bottom-color: rgb(186 230 253); | | border-y-sky-300 | border-top-color: rgb(125 211 252); border-bottom-color: rgb(125 211 252); | | border-y-sky-400 | border-top-color: rgb(56 189 248); border-bottom-color: rgb(56 189 248); | | border-y-sky-500 | border-top-color: rgb(14 165 233); border-bottom-color: rgb(14 165 233); | | border-y-sky-600 | border-top-color: rgb(2 132 199); border-bottom-color: rgb(2 132 199); | | border-y-sky-700 | border-top-color: rgb(3 105 161); border-bottom-color: rgb(3 105 161); | | border-y-sky-800 | border-top-color: rgb(7 89 133); border-bottom-color: rgb(7 89 133); | | border-y-sky-900 | border-top-color: rgb(12 74 110); border-bottom-color: rgb(12 74 110); | | border-y-sky-950 | border-top-color: rgb(8 47 73); border-bottom-color: rgb(8 47 73); | | border-y-blue-50 | border-top-color: rgb(239 246 255); border-bottom-color: rgb(239 246 255); | | border-y-blue-100 | border-top-color: rgb(219 234 254); border-bottom-color: rgb(219 234 254); | | border-y-blue-200 | border-top-color: rgb(191 219 254); border-bottom-color: rgb(191 219 254); | | border-y-blue-300 | border-top-color: rgb(147 197 253); border-bottom-color: rgb(147 197 253); | | border-y-blue-400 | border-top-color: rgb(96 165 250); border-bottom-color: rgb(96 165 250); | | border-y-blue-500 | border-top-color: rgb(59 130 246); border-bottom-color: rgb(59 130 246); | | border-y-blue-600 | border-top-color: rgb(37 99 235); border-bottom-color: rgb(37 99 235); | | border-y-blue-700 | border-top-color: rgb(29 78 216); border-bottom-color: rgb(29 78 216); | | border-y-blue-800 | border-top-color: rgb(30 64 175); border-bottom-color: rgb(30 64 175); | | border-y-blue-900 | border-top-color: rgb(30 58 138); border-bottom-color: rgb(30 58 138); | | border-y-blue-950 | border-top-color: rgb(23 37 84); border-bottom-color: rgb(23 37 84); | | border-y-indigo-50 | border-top-color: rgb(238 242 255); border-bottom-color: rgb(238 242 255); | | border-y-indigo-100 | border-top-color: rgb(224 231 255); border-bottom-color: rgb(224 231 255); | | border-y-indigo-200 | border-top-color: rgb(199 210 254); border-bottom-color: rgb(199 210 254); | | border-y-indigo-300 | border-top-color: rgb(165 180 252); border-bottom-color: rgb(165 180 252); | | border-y-indigo-400 | border-top-color: rgb(129 140 248); border-bottom-color: rgb(129 140 248); | | border-y-indigo-500 | border-top-color: rgb(99 102 241); border-bottom-color: rgb(99 102 241); | | border-y-indigo-600 | border-top-color: rgb(79 70 229); border-bottom-color: rgb(79 70 229); | | border-y-indigo-700 | border-top-color: rgb(67 56 202); border-bottom-color: rgb(67 56 202); | | border-y-indigo-800 | border-top-color: rgb(55 48 163); border-bottom-color: rgb(55 48 163); | | border-y-indigo-900 | border-top-color: rgb(49 46 129); border-bottom-color: rgb(49 46 129); | | border-y-indigo-950 | border-top-color: rgb(30 27 75); border-bottom-color: rgb(30 27 75); | | border-y-violet-50 | border-top-color: rgb(245 243 255); border-bottom-color: rgb(245 243 255); | | border-y-violet-100 | border-top-color: rgb(237 233 254); border-bottom-color: rgb(237 233 254); | | border-y-violet-200 | border-top-color: rgb(221 214 254); border-bottom-color: rgb(221 214 254); | | border-y-violet-300 | border-top-color: rgb(196 181 253); border-bottom-color: rgb(196 181 253); | | border-y-violet-400 | border-top-color: rgb(167 139 250); border-bottom-color: rgb(167 139 250); | | border-y-violet-500 | border-top-color: rgb(139 92 246); border-bottom-color: rgb(139 92 246); | | border-y-violet-600 | border-top-color: rgb(124 58 237); border-bottom-color: rgb(124 58 237); | | border-y-violet-700 | border-top-color: rgb(109 40 217); border-bottom-color: rgb(109 40 217); | | border-y-violet-800 | border-top-color: rgb(91 33 182); border-bottom-color: rgb(91 33 182); | | border-y-violet-900 | border-top-color: rgb(76 29 149); border-bottom-color: rgb(76 29 149); | | border-y-violet-950 | border-top-color: rgb(46 16 101); border-bottom-color: rgb(46 16 101); | | border-y-purple-50 | border-top-color: rgb(250 245 255); border-bottom-color: rgb(250 245 255); | | border-y-purple-100 | border-top-color: rgb(243 232 255); border-bottom-color: rgb(243 232 255); | | border-y-purple-200 | border-top-color: rgb(233 213 255); border-bottom-color: rgb(233 213 255); | | border-y-purple-300 | border-top-color: rgb(216 180 254); border-bottom-color: rgb(216 180 254); | | border-y-purple-400 | border-top-color: rgb(192 132 252); border-bottom-color: rgb(192 132 252); | | border-y-purple-500 | border-top-color: rgb(168 85 247); border-bottom-color: rgb(168 85 247); | | border-y-purple-600 | border-top-color: rgb(147 51 234); border-bottom-color: rgb(147 51 234); | | border-y-purple-700 | border-top-color: rgb(126 34 206); border-bottom-color: rgb(126 34 206); | | border-y-purple-800 | border-top-color: rgb(107 33 168); border-bottom-color: rgb(107 33 168); | | border-y-purple-900 | border-top-color: rgb(88 28 135); border-bottom-color: rgb(88 28 135); | | border-y-purple-950 | border-top-color: rgb(59 7 100); border-bottom-color: rgb(59 7 100); | | border-y-fuchsia-50 | border-top-color: rgb(253 244 255); border-bottom-color: rgb(253 244 255); | | border-y-fuchsia-100 | border-top-color: rgb(250 232 255); border-bottom-color: rgb(250 232 255); | | border-y-fuchsia-200 | border-top-color: rgb(245 208 254); border-bottom-color: rgb(245 208 254); | | border-y-fuchsia-300 | border-top-color: rgb(240 171 252); border-bottom-color: rgb(240 171 252); | | border-y-fuchsia-400 | border-top-color: rgb(232 121 249); border-bottom-color: rgb(232 121 249); | | border-y-fuchsia-500 | border-top-color: rgb(217 70 239); border-bottom-color: rgb(217 70 239); | | border-y-fuchsia-600 | border-top-color: rgb(192 38 211); border-bottom-color: rgb(192 38 211); | | border-y-fuchsia-700 | border-top-color: rgb(162 28 175); border-bottom-color: rgb(162 28 175); | | border-y-fuchsia-800 | border-top-color: rgb(134 25 143); border-bottom-color: rgb(134 25 143); | | border-y-fuchsia-900 | border-top-color: rgb(112 26 117); border-bottom-color: rgb(112 26 117); | | border-y-fuchsia-950 | border-top-color: rgb(74 4 78); border-bottom-color: rgb(74 4 78); | | border-y-pink-50 | border-top-color: rgb(253 242 248); border-bottom-color: rgb(253 242 248); | | border-y-pink-100 | border-top-color: rgb(252 231 243); border-bottom-color: rgb(252 231 243); | | border-y-pink-200 | border-top-color: rgb(251 207 232); border-bottom-color: rgb(251 207 232); | | border-y-pink-300 | border-top-color: rgb(249 168 212); border-bottom-color: rgb(249 168 212); | | border-y-pink-400 | border-top-color: rgb(244 114 182); border-bottom-color: rgb(244 114 182); | | border-y-pink-500 | border-top-color: rgb(236 72 153); border-bottom-color: rgb(236 72 153); | | border-y-pink-600 | border-top-color: rgb(219 39 119); border-bottom-color: rgb(219 39 119); | | border-y-pink-700 | border-top-color: rgb(190 24 93); border-bottom-color: rgb(190 24 93); | | border-y-pink-800 | border-top-color: rgb(157 23 77); border-bottom-color: rgb(157 23 77); | | border-y-pink-900 | border-top-color: rgb(131 24 67); border-bottom-color: rgb(131 24 67); | | border-y-pink-950 | border-top-color: rgb(80 7 36); border-bottom-color: rgb(80 7 36); | | border-y-rose-50 | border-top-color: rgb(255 241 242); border-bottom-color: rgb(255 241 242); | | border-y-rose-100 | border-top-color: rgb(255 228 230); border-bottom-color: rgb(255 228 230); | | border-y-rose-200 | border-top-color: rgb(254 205 211); border-bottom-color: rgb(254 205 211); | | border-y-rose-300 | border-top-color: rgb(253 164 175); border-bottom-color: rgb(253 164 175); | | border-y-rose-400 | border-top-color: rgb(251 113 133); border-bottom-color: rgb(251 113 133); | | border-y-rose-500 | border-top-color: rgb(244 63 94); border-bottom-color: rgb(244 63 94); | | border-y-rose-600 | border-top-color: rgb(225 29 72); border-bottom-color: rgb(225 29 72); | | border-y-rose-700 | border-top-color: rgb(190 18 60); border-bottom-color: rgb(190 18 60); | | border-y-rose-800 | border-top-color: rgb(159 18 57); border-bottom-color: rgb(159 18 57); | | border-y-rose-900 | border-top-color: rgb(136 19 55); border-bottom-color: rgb(136 19 55); | | border-y-rose-950 | border-top-color: rgb(76 5 25); border-bottom-color: rgb(76 5 25); | | border-s-inherit | border-inline-start-color: inherit; | | border-s-current | border-inline-start-color: currentColor; | | border-s-transparent | border-inline-start-color: transparent; | | border-s-black | border-inline-start-color: rgb(0 0 0); | | border-s-white | border-inline-start-color: rgb(255 255 255); | | border-s-slate-50 | border-inline-start-color: rgb(248 250 252); | | border-s-slate-100 | border-inline-start-color: rgb(241 245 249); | | border-s-slate-200 | border-inline-start-color: rgb(226 232 240); | | border-s-slate-300 | border-inline-start-color: rgb(203 213 225); | | border-s-slate-400 | border-inline-start-color: rgb(148 163 184); | | border-s-slate-500 | border-inline-start-color: rgb(100 116 139); | | border-s-slate-600 | border-inline-start-color: rgb(71 85 105); | | border-s-slate-700 | border-inline-start-color: rgb(51 65 85); | | border-s-slate-800 | border-inline-start-color: rgb(30 41 59); | | border-s-slate-900 | border-inline-start-color: rgb(15 23 42); | | border-s-slate-950 | border-inline-start-color: rgb(2 6 23); | | border-s-gray-50 | border-inline-start-color: rgb(249 250 251); | | border-s-gray-100 | border-inline-start-color: rgb(243 244 246); | | border-s-gray-200 | border-inline-start-color: rgb(229 231 235); | | border-s-gray-300 | border-inline-start-color: rgb(209 213 219); | | border-s-gray-400 | border-inline-start-color: rgb(156 163 175); | | border-s-gray-500 | border-inline-start-color: rgb(107 114 128); | | border-s-gray-600 | border-inline-start-color: rgb(75 85 99); | | border-s-gray-700 | border-inline-start-color: rgb(55 65 81); | | border-s-gray-800 | border-inline-start-color: rgb(31 41 55); | | border-s-gray-900 | border-inline-start-color: rgb(17 24 39); | | border-s-gray-950 | border-inline-start-color: rgb(3 7 18); | | border-s-zinc-50 | border-inline-start-color: rgb(250 250 250); | | border-s-zinc-100 | border-inline-start-color: rgb(244 244 245); | | border-s-zinc-200 | border-inline-start-color: rgb(228 228 231); | | border-s-zinc-300 | border-inline-start-color: rgb(212 212 216); | | border-s-zinc-400 | border-inline-start-color: rgb(161 161 170); | | border-s-zinc-500 | border-inline-start-color: rgb(113 113 122); | | border-s-zinc-600 | border-inline-start-color: rgb(82 82 91); | | border-s-zinc-700 | border-inline-start-color: rgb(63 63 70); | | border-s-zinc-800 | border-inline-start-color: rgb(39 39 42); | | border-s-zinc-900 | border-inline-start-color: rgb(24 24 27); | | border-s-zinc-950 | border-inline-start-color: rgb(9 9 11); | | border-s-neutral-50 | border-inline-start-color: rgb(250 250 250); | | border-s-neutral-100 | border-inline-start-color: rgb(245 245 245); | | border-s-neutral-200 | border-inline-start-color: rgb(229 229 229); | | border-s-neutral-300 | border-inline-start-color: rgb(212 212 212); | | border-s-neutral-400 | border-inline-start-color: rgb(163 163 163); | | border-s-neutral-500 | border-inline-start-color: rgb(115 115 115); | | border-s-neutral-600 | border-inline-start-color: rgb(82 82 82); | | border-s-neutral-700 | border-inline-start-color: rgb(64 64 64); | | border-s-neutral-800 | border-inline-start-color: rgb(38 38 38); | | border-s-neutral-900 | border-inline-start-color: rgb(23 23 23); | | border-s-neutral-950 | border-inline-start-color: rgb(10 10 10); | | border-s-stone-50 | border-inline-start-color: rgb(250 250 249); | | border-s-stone-100 | border-inline-start-color: rgb(245 245 244); | | border-s-stone-200 | border-inline-start-color: rgb(231 229 228); | | border-s-stone-300 | border-inline-start-color: rgb(214 211 209); | | border-s-stone-400 | border-inline-start-color: rgb(168 162 158); | | border-s-stone-500 | border-inline-start-color: rgb(120 113 108); | | border-s-stone-600 | border-inline-start-color: rgb(87 83 78); | | border-s-stone-700 | border-inline-start-color: rgb(68 64 60); | | border-s-stone-800 | border-inline-start-color: rgb(41 37 36); | | border-s-stone-900 | border-inline-start-color: rgb(28 25 23); | | border-s-stone-950 | border-inline-start-color: rgb(12 10 9); | | border-s-red-50 | border-inline-start-color: rgb(254 242 242); | | border-s-red-100 | border-inline-start-color: rgb(254 226 226); | | border-s-red-200 | border-inline-start-color: rgb(254 202 202); | | border-s-red-300 | border-inline-start-color: rgb(252 165 165); | | border-s-red-400 | border-inline-start-color: rgb(248 113 113); | | border-s-red-500 | border-inline-start-color: rgb(239 68 68); | | border-s-red-600 | border-inline-start-color: rgb(220 38 38); | | border-s-red-700 | border-inline-start-color: rgb(185 28 28); | | border-s-red-800 | border-inline-start-color: rgb(153 27 27); | | border-s-red-900 | border-inline-start-color: rgb(127 29 29); | | border-s-red-950 | border-inline-start-color: rgb(69 10 10); | | border-s-orange-50 | border-inline-start-color: rgb(255 247 237); | | border-s-orange-100 | border-inline-start-color: rgb(255 237 213); | | border-s-orange-200 | border-inline-start-color: rgb(254 215 170); | | border-s-orange-300 | border-inline-start-color: rgb(253 186 116); | | border-s-orange-400 | border-inline-start-color: rgb(251 146 60); | | border-s-orange-500 | border-inline-start-color: rgb(249 115 22); | | border-s-orange-600 | border-inline-start-color: rgb(234 88 12); | | border-s-orange-700 | border-inline-start-color: rgb(194 65 12); | | border-s-orange-800 | border-inline-start-color: rgb(154 52 18); | | border-s-orange-900 | border-inline-start-color: rgb(124 45 18); | | border-s-orange-950 | border-inline-start-color: rgb(67 20 7); | | border-s-amber-50 | border-inline-start-color: rgb(255 251 235); | | border-s-amber-100 | border-inline-start-color: rgb(254 243 199); | | border-s-amber-200 | border-inline-start-color: rgb(253 230 138); | | border-s-amber-300 | border-inline-start-color: rgb(252 211 77); | | border-s-amber-400 | border-inline-start-color: rgb(251 191 36); | | border-s-amber-500 | border-inline-start-color: rgb(245 158 11); | | border-s-amber-600 | border-inline-start-color: rgb(217 119 6); | | border-s-amber-700 | border-inline-start-color: rgb(180 83 9); | | border-s-amber-800 | border-inline-start-color: rgb(146 64 14); | | border-s-amber-900 | border-inline-start-color: rgb(120 53 15); | | border-s-amber-950 | border-inline-start-color: rgb(69 26 3); | | border-s-yellow-50 | border-inline-start-color: rgb(254 252 232); | | border-s-yellow-100 | border-inline-start-color: rgb(254 249 195); | | border-s-yellow-200 | border-inline-start-color: rgb(254 240 138); | | border-s-yellow-300 | border-inline-start-color: rgb(253 224 71); | | border-s-yellow-400 | border-inline-start-color: rgb(250 204 21); | | border-s-yellow-500 | border-inline-start-color: rgb(234 179 8); | | border-s-yellow-600 | border-inline-start-color: rgb(202 138 4); | | border-s-yellow-700 | border-inline-start-color: rgb(161 98 7); | | border-s-yellow-800 | border-inline-start-color: rgb(133 77 14); | | border-s-yellow-900 | border-inline-start-color: rgb(113 63 18); | | border-s-yellow-950 | border-inline-start-color: rgb(66 32 6); | | border-s-lime-50 | border-inline-start-color: rgb(247 254 231); | | border-s-lime-100 | border-inline-start-color: rgb(236 252 203); | | border-s-lime-200 | border-inline-start-color: rgb(217 249 157); | | border-s-lime-300 | border-inline-start-color: rgb(190 242 100); | | border-s-lime-400 | border-inline-start-color: rgb(163 230 53); | | border-s-lime-500 | border-inline-start-color: rgb(132 204 22); | | border-s-lime-600 | border-inline-start-color: rgb(101 163 13); | | border-s-lime-700 | border-inline-start-color: rgb(77 124 15); | | border-s-lime-800 | border-inline-start-color: rgb(63 98 18); | | border-s-lime-900 | border-inline-start-color: rgb(54 83 20); | | border-s-lime-950 | border-inline-start-color: rgb(26 46 5); | | border-s-green-50 | border-inline-start-color: rgb(240 253 244); | | border-s-green-100 | border-inline-start-color: rgb(220 252 231); | | border-s-green-200 | border-inline-start-color: rgb(187 247 208); | | border-s-green-300 | border-inline-start-color: rgb(134 239 172); | | border-s-green-400 | border-inline-start-color: rgb(74 222 128); | | border-s-green-500 | border-inline-start-color: rgb(34 197 94); | | border-s-green-600 | border-inline-start-color: rgb(22 163 74); | | border-s-green-700 | border-inline-start-color: rgb(21 128 61); | | border-s-green-800 | border-inline-start-color: rgb(22 101 52); | | border-s-green-900 | border-inline-start-color: rgb(20 83 45); | | border-s-green-950 | border-inline-start-color: rgb(5 46 22); | | border-s-emerald-50 | border-inline-start-color: rgb(236 253 245); | | border-s-emerald-100 | border-inline-start-color: rgb(209 250 229); | | border-s-emerald-200 | border-inline-start-color: rgb(167 243 208); | | border-s-emerald-300 | border-inline-start-color: rgb(110 231 183); | | border-s-emerald-400 | border-inline-start-color: rgb(52 211 153); | | border-s-emerald-500 | border-inline-start-color: rgb(16 185 129); | | border-s-emerald-600 | border-inline-start-color: rgb(5 150 105); | | border-s-emerald-700 | border-inline-start-color: rgb(4 120 87); | | border-s-emerald-800 | border-inline-start-color: rgb(6 95 70); | | border-s-emerald-900 | border-inline-start-color: rgb(6 78 59); | | border-s-emerald-950 | border-inline-start-color: rgb(2 44 34); | | border-s-teal-50 | border-inline-start-color: rgb(240 253 250); | | border-s-teal-100 | border-inline-start-color: rgb(204 251 241); | | border-s-teal-200 | border-inline-start-color: rgb(153 246 228); | | border-s-teal-300 | border-inline-start-color: rgb(94 234 212); | | border-s-teal-400 | border-inline-start-color: rgb(45 212 191); | | border-s-teal-500 | border-inline-start-color: rgb(20 184 166); | | border-s-teal-600 | border-inline-start-color: rgb(13 148 136); | | border-s-teal-700 | border-inline-start-color: rgb(15 118 110); | | border-s-teal-800 | border-inline-start-color: rgb(17 94 89); | | border-s-teal-900 | border-inline-start-color: rgb(19 78 74); | | border-s-teal-950 | border-inline-start-color: rgb(4 47 46); | | border-s-cyan-50 | border-inline-start-color: rgb(236 254 255); | | border-s-cyan-100 | border-inline-start-color: rgb(207 250 254); | | border-s-cyan-200 | border-inline-start-color: rgb(165 243 252); | | border-s-cyan-300 | border-inline-start-color: rgb(103 232 249); | | border-s-cyan-400 | border-inline-start-color: rgb(34 211 238); | | border-s-cyan-500 | border-inline-start-color: rgb(6 182 212); | | border-s-cyan-600 | border-inline-start-color: rgb(8 145 178); | | border-s-cyan-700 | border-inline-start-color: rgb(14 116 144); | | border-s-cyan-800 | border-inline-start-color: rgb(21 94 117); | | border-s-cyan-900 | border-inline-start-color: rgb(22 78 99); | | border-s-cyan-950 | border-inline-start-color: rgb(8 51 68); | | border-s-sky-50 | border-inline-start-color: rgb(240 249 255); | | border-s-sky-100 | border-inline-start-color: rgb(224 242 254); | | border-s-sky-200 | border-inline-start-color: rgb(186 230 253); | | border-s-sky-300 | border-inline-start-color: rgb(125 211 252); | | border-s-sky-400 | border-inline-start-color: rgb(56 189 248); | | border-s-sky-500 | border-inline-start-color: rgb(14 165 233); | | border-s-sky-600 | border-inline-start-color: rgb(2 132 199); | | border-s-sky-700 | border-inline-start-color: rgb(3 105 161); | | border-s-sky-800 | border-inline-start-color: rgb(7 89 133); | | border-s-sky-900 | border-inline-start-color: rgb(12 74 110); | | border-s-sky-950 | border-inline-start-color: rgb(8 47 73); | | border-s-blue-50 | border-inline-start-color: rgb(239 246 255); | | border-s-blue-100 | border-inline-start-color: rgb(219 234 254); | | border-s-blue-200 | border-inline-start-color: rgb(191 219 254); | | border-s-blue-300 | border-inline-start-color: rgb(147 197 253); | | border-s-blue-400 | border-inline-start-color: rgb(96 165 250); | | border-s-blue-500 | border-inline-start-color: rgb(59 130 246); | | border-s-blue-600 | border-inline-start-color: rgb(37 99 235); | | border-s-blue-700 | border-inline-start-color: rgb(29 78 216); | | border-s-blue-800 | border-inline-start-color: rgb(30 64 175); | | border-s-blue-900 | border-inline-start-color: rgb(30 58 138); | | border-s-blue-950 | border-inline-start-color: rgb(23 37 84); | | border-s-indigo-50 | border-inline-start-color: rgb(238 242 255); | | border-s-indigo-100 | border-inline-start-color: rgb(224 231 255); | | border-s-indigo-200 | border-inline-start-color: rgb(199 210 254); | | border-s-indigo-300 | border-inline-start-color: rgb(165 180 252); | | border-s-indigo-400 | border-inline-start-color: rgb(129 140 248); | | border-s-indigo-500 | border-inline-start-color: rgb(99 102 241); | | border-s-indigo-600 | border-inline-start-color: rgb(79 70 229); | | border-s-indigo-700 | border-inline-start-color: rgb(67 56 202); | | border-s-indigo-800 | border-inline-start-color: rgb(55 48 163); | | border-s-indigo-900 | border-inline-start-color: rgb(49 46 129); | | border-s-indigo-950 | border-inline-start-color: rgb(30 27 75); | | border-s-violet-50 | border-inline-start-color: rgb(245 243 255); | | border-s-violet-100 | border-inline-start-color: rgb(237 233 254); | | border-s-violet-200 | border-inline-start-color: rgb(221 214 254); | | border-s-violet-300 | border-inline-start-color: rgb(196 181 253); | | border-s-violet-400 | border-inline-start-color: rgb(167 139 250); | | border-s-violet-500 | border-inline-start-color: rgb(139 92 246); | | border-s-violet-600 | border-inline-start-color: rgb(124 58 237); | | border-s-violet-700 | border-inline-start-color: rgb(109 40 217); | | border-s-violet-800 | border-inline-start-color: rgb(91 33 182); | | border-s-violet-900 | border-inline-start-color: rgb(76 29 149); | | border-s-violet-950 | border-inline-start-color: rgb(46 16 101); | | border-s-purple-50 | border-inline-start-color: rgb(250 245 255); | | border-s-purple-100 | border-inline-start-color: rgb(243 232 255); | | border-s-purple-200 | border-inline-start-color: rgb(233 213 255); | | border-s-purple-300 | border-inline-start-color: rgb(216 180 254); | | border-s-purple-400 | border-inline-start-color: rgb(192 132 252); | | border-s-purple-500 | border-inline-start-color: rgb(168 85 247); | | border-s-purple-600 | border-inline-start-color: rgb(147 51 234); | | border-s-purple-700 | border-inline-start-color: rgb(126 34 206); | | border-s-purple-800 | border-inline-start-color: rgb(107 33 168); | | border-s-purple-900 | border-inline-start-color: rgb(88 28 135); | | border-s-purple-950 | border-inline-start-color: rgb(59 7 100); | | border-s-fuchsia-50 | border-inline-start-color: rgb(253 244 255); | | border-s-fuchsia-100 | border-inline-start-color: rgb(250 232 255); | | border-s-fuchsia-200 | border-inline-start-color: rgb(245 208 254); | | border-s-fuchsia-300 | border-inline-start-color: rgb(240 171 252); | | border-s-fuchsia-400 | border-inline-start-color: rgb(232 121 249); | | border-s-fuchsia-500 | border-inline-start-color: rgb(217 70 239); | | border-s-fuchsia-600 | border-inline-start-color: rgb(192 38 211); | | border-s-fuchsia-700 | border-inline-start-color: rgb(162 28 175); | | border-s-fuchsia-800 | border-inline-start-color: rgb(134 25 143); | | border-s-fuchsia-900 | border-inline-start-color: rgb(112 26 117); | | border-s-fuchsia-950 | border-inline-start-color: rgb(74 4 78); | | border-s-pink-50 | border-inline-start-color: rgb(253 242 248); | | border-s-pink-100 | border-inline-start-color: rgb(252 231 243); | | border-s-pink-200 | border-inline-start-color: rgb(251 207 232); | | border-s-pink-300 | border-inline-start-color: rgb(249 168 212); | | border-s-pink-400 | border-inline-start-color: rgb(244 114 182); | | border-s-pink-500 | border-inline-start-color: rgb(236 72 153); | | border-s-pink-600 | border-inline-start-color: rgb(219 39 119); | | border-s-pink-700 | border-inline-start-color: rgb(190 24 93); | | border-s-pink-800 | border-inline-start-color: rgb(157 23 77); | | border-s-pink-900 | border-inline-start-color: rgb(131 24 67); | | border-s-pink-950 | border-inline-start-color: rgb(80 7 36); | | border-s-rose-50 | border-inline-start-color: rgb(255 241 242); | | border-s-rose-100 | border-inline-start-color: rgb(255 228 230); | | border-s-rose-200 | border-inline-start-color: rgb(254 205 211); | | border-s-rose-300 | border-inline-start-color: rgb(253 164 175); | | border-s-rose-400 | border-inline-start-color: rgb(251 113 133); | | border-s-rose-500 | border-inline-start-color: rgb(244 63 94); | | border-s-rose-600 | border-inline-start-color: rgb(225 29 72); | | border-s-rose-700 | border-inline-start-color: rgb(190 18 60); | | border-s-rose-800 | border-inline-start-color: rgb(159 18 57); | | border-s-rose-900 | border-inline-start-color: rgb(136 19 55); | | border-s-rose-950 | border-inline-start-color: rgb(76 5 25); | | border-e-inherit | border-inline-end-color: inherit; | | border-e-current | border-inline-end-color: currentColor; | | border-e-transparent | border-inline-end-color: transparent; | | border-e-black | border-inline-end-color: rgb(0 0 0); | | border-e-white | border-inline-end-color: rgb(255 255 255); | | border-e-slate-50 | border-inline-end-color: rgb(248 250 252); | | border-e-slate-100 | border-inline-end-color: rgb(241 245 249); | | border-e-slate-200 | border-inline-end-color: rgb(226 232 240); | | border-e-slate-300 | border-inline-end-color: rgb(203 213 225); | | border-e-slate-400 | border-inline-end-color: rgb(148 163 184); | | border-e-slate-500 | border-inline-end-color: rgb(100 116 139); | | border-e-slate-600 | border-inline-end-color: rgb(71 85 105); | | border-e-slate-700 | border-inline-end-color: rgb(51 65 85); | | border-e-slate-800 | border-inline-end-color: rgb(30 41 59); | | border-e-slate-900 | border-inline-end-color: rgb(15 23 42); | | border-e-slate-950 | border-inline-end-color: rgb(2 6 23); | | border-e-gray-50 | border-inline-end-color: rgb(249 250 251); | | border-e-gray-100 | border-inline-end-color: rgb(243 244 246); | | border-e-gray-200 | border-inline-end-color: rgb(229 231 235); | | border-e-gray-300 | border-inline-end-color: rgb(209 213 219); | | border-e-gray-400 | border-inline-end-color: rgb(156 163 175); | | border-e-gray-500 | border-inline-end-color: rgb(107 114 128); | | border-e-gray-600 | border-inline-end-color: rgb(75 85 99); | | border-e-gray-700 | border-inline-end-color: rgb(55 65 81); | | border-e-gray-800 | border-inline-end-color: rgb(31 41 55); | | border-e-gray-900 | border-inline-end-color: rgb(17 24 39); | | border-e-gray-950 | border-inline-end-color: rgb(3 7 18); | | border-e-zinc-50 | border-inline-end-color: rgb(250 250 250); | | border-e-zinc-100 | border-inline-end-color: rgb(244 244 245); | | border-e-zinc-200 | border-inline-end-color: rgb(228 228 231); | | border-e-zinc-300 | border-inline-end-color: rgb(212 212 216); | | border-e-zinc-400 | border-inline-end-color: rgb(161 161 170); | | border-e-zinc-500 | border-inline-end-color: rgb(113 113 122); | | border-e-zinc-600 | border-inline-end-color: rgb(82 82 91); | | border-e-zinc-700 | border-inline-end-color: rgb(63 63 70); | | border-e-zinc-800 | border-inline-end-color: rgb(39 39 42); | | border-e-zinc-900 | border-inline-end-color: rgb(24 24 27); | | border-e-zinc-950 | border-inline-end-color: rgb(9 9 11); | | border-e-neutral-50 | border-inline-end-color: rgb(250 250 250); | | border-e-neutral-100 | border-inline-end-color: rgb(245 245 245); | | border-e-neutral-200 | border-inline-end-color: rgb(229 229 229); | | border-e-neutral-300 | border-inline-end-color: rgb(212 212 212); | | border-e-neutral-400 | border-inline-end-color: rgb(163 163 163); | | border-e-neutral-500 | border-inline-end-color: rgb(115 115 115); | | border-e-neutral-600 | border-inline-end-color: rgb(82 82 82); | | border-e-neutral-700 | border-inline-end-color: rgb(64 64 64); | | border-e-neutral-800 | border-inline-end-color: rgb(38 38 38); | | border-e-neutral-900 | border-inline-end-color: rgb(23 23 23); | | border-e-neutral-950 | border-inline-end-color: rgb(10 10 10); | | border-e-stone-50 | border-inline-end-color: rgb(250 250 249); | | border-e-stone-100 | border-inline-end-color: rgb(245 245 244); | | border-e-stone-200 | border-inline-end-color: rgb(231 229 228); | | border-e-stone-300 | border-inline-end-color: rgb(214 211 209); | | border-e-stone-400 | border-inline-end-color: rgb(168 162 158); | | border-e-stone-500 | border-inline-end-color: rgb(120 113 108); | | border-e-stone-600 | border-inline-end-color: rgb(87 83 78); | | border-e-stone-700 | border-inline-end-color: rgb(68 64 60); | | border-e-stone-800 | border-inline-end-color: rgb(41 37 36); | | border-e-stone-900 | border-inline-end-color: rgb(28 25 23); | | border-e-stone-950 | border-inline-end-color: rgb(12 10 9); | | border-e-red-50 | border-inline-end-color: rgb(254 242 242); | | border-e-red-100 | border-inline-end-color: rgb(254 226 226); | | border-e-red-200 | border-inline-end-color: rgb(254 202 202); | | border-e-red-300 | border-inline-end-color: rgb(252 165 165); | | border-e-red-400 | border-inline-end-color: rgb(248 113 113); | | border-e-red-500 | border-inline-end-color: rgb(239 68 68); | | border-e-red-600 | border-inline-end-color: rgb(220 38 38); | | border-e-red-700 | border-inline-end-color: rgb(185 28 28); | | border-e-red-800 | border-inline-end-color: rgb(153 27 27); | | border-e-red-900 | border-inline-end-color: rgb(127 29 29); | | border-e-red-950 | border-inline-end-color: rgb(69 10 10); | | border-e-orange-50 | border-inline-end-color: rgb(255 247 237); | | border-e-orange-100 | border-inline-end-color: rgb(255 237 213); | | border-e-orange-200 | border-inline-end-color: rgb(254 215 170); | | border-e-orange-300 | border-inline-end-color: rgb(253 186 116); | | border-e-orange-400 | border-inline-end-color: rgb(251 146 60); | | border-e-orange-500 | border-inline-end-color: rgb(249 115 22); | | border-e-orange-600 | border-inline-end-color: rgb(234 88 12); | | border-e-orange-700 | border-inline-end-color: rgb(194 65 12); | | border-e-orange-800 | border-inline-end-color: rgb(154 52 18); | | border-e-orange-900 | border-inline-end-color: rgb(124 45 18); | | border-e-orange-950 | border-inline-end-color: rgb(67 20 7); | | border-e-amber-50 | border-inline-end-color: rgb(255 251 235); | | border-e-amber-100 | border-inline-end-color: rgb(254 243 199); | | border-e-amber-200 | border-inline-end-color: rgb(253 230 138); | | border-e-amber-300 | border-inline-end-color: rgb(252 211 77); | | border-e-amber-400 | border-inline-end-color: rgb(251 191 36); | | border-e-amber-500 | border-inline-end-color: rgb(245 158 11); | | border-e-amber-600 | border-inline-end-color: rgb(217 119 6); | | border-e-amber-700 | border-inline-end-color: rgb(180 83 9); | | border-e-amber-800 | border-inline-end-color: rgb(146 64 14); | | border-e-amber-900 | border-inline-end-color: rgb(120 53 15); | | border-e-amber-950 | border-inline-end-color: rgb(69 26 3); | | border-e-yellow-50 | border-inline-end-color: rgb(254 252 232); | | border-e-yellow-100 | border-inline-end-color: rgb(254 249 195); | | border-e-yellow-200 | border-inline-end-color: rgb(254 240 138); | | border-e-yellow-300 | border-inline-end-color: rgb(253 224 71); | | border-e-yellow-400 | border-inline-end-color: rgb(250 204 21); | | border-e-yellow-500 | border-inline-end-color: rgb(234 179 8); | | border-e-yellow-600 | border-inline-end-color: rgb(202 138 4); | | border-e-yellow-700 | border-inline-end-color: rgb(161 98 7); | | border-e-yellow-800 | border-inline-end-color: rgb(133 77 14); | | border-e-yellow-900 | border-inline-end-color: rgb(113 63 18); | | border-e-yellow-950 | border-inline-end-color: rgb(66 32 6); | | border-e-lime-50 | border-inline-end-color: rgb(247 254 231); | | border-e-lime-100 | border-inline-end-color: rgb(236 252 203); | | border-e-lime-200 | border-inline-end-color: rgb(217 249 157); | | border-e-lime-300 | border-inline-end-color: rgb(190 242 100); | | border-e-lime-400 | border-inline-end-color: rgb(163 230 53); | | border-e-lime-500 | border-inline-end-color: rgb(132 204 22); | | border-e-lime-600 | border-inline-end-color: rgb(101 163 13); | | border-e-lime-700 | border-inline-end-color: rgb(77 124 15); | | border-e-lime-800 | border-inline-end-color: rgb(63 98 18); | | border-e-lime-900 | border-inline-end-color: rgb(54 83 20); | | border-e-lime-950 | border-inline-end-color: rgb(26 46 5); | | border-e-green-50 | border-inline-end-color: rgb(240 253 244); | | border-e-green-100 | border-inline-end-color: rgb(220 252 231); | | border-e-green-200 | border-inline-end-color: rgb(187 247 208); | | border-e-green-300 | border-inline-end-color: rgb(134 239 172); | | border-e-green-400 | border-inline-end-color: rgb(74 222 128); | | border-e-green-500 | border-inline-end-color: rgb(34 197 94); | | border-e-green-600 | border-inline-end-color: rgb(22 163 74); | | border-e-green-700 | border-inline-end-color: rgb(21 128 61); | | border-e-green-800 | border-inline-end-color: rgb(22 101 52); | | border-e-green-900 | border-inline-end-color: rgb(20 83 45); | | border-e-green-950 | border-inline-end-color: rgb(5 46 22); | | border-e-emerald-50 | border-inline-end-color: rgb(236 253 245); | | border-e-emerald-100 | border-inline-end-color: rgb(209 250 229); | | border-e-emerald-200 | border-inline-end-color: rgb(167 243 208); | | border-e-emerald-300 | border-inline-end-color: rgb(110 231 183); | | border-e-emerald-400 | border-inline-end-color: rgb(52 211 153); | | border-e-emerald-500 | border-inline-end-color: rgb(16 185 129); | | border-e-emerald-600 | border-inline-end-color: rgb(5 150 105); | | border-e-emerald-700 | border-inline-end-color: rgb(4 120 87); | | border-e-emerald-800 | border-inline-end-color: rgb(6 95 70); | | border-e-emerald-900 | border-inline-end-color: rgb(6 78 59); | | border-e-emerald-950 | border-inline-end-color: rgb(2 44 34); | | border-e-teal-50 | border-inline-end-color: rgb(240 253 250); | | border-e-teal-100 | border-inline-end-color: rgb(204 251 241); | | border-e-teal-200 | border-inline-end-color: rgb(153 246 228); | | border-e-teal-300 | border-inline-end-color: rgb(94 234 212); | | border-e-teal-400 | border-inline-end-color: rgb(45 212 191); | | border-e-teal-500 | border-inline-end-color: rgb(20 184 166); | | border-e-teal-600 | border-inline-end-color: rgb(13 148 136); | | border-e-teal-700 | border-inline-end-color: rgb(15 118 110); | | border-e-teal-800 | border-inline-end-color: rgb(17 94 89); | | border-e-teal-900 | border-inline-end-color: rgb(19 78 74); | | border-e-teal-950 | border-inline-end-color: rgb(4 47 46); | | border-e-cyan-50 | border-inline-end-color: rgb(236 254 255); | | border-e-cyan-100 | border-inline-end-color: rgb(207 250 254); | | border-e-cyan-200 | border-inline-end-color: rgb(165 243 252); | | border-e-cyan-300 | border-inline-end-color: rgb(103 232 249); | | border-e-cyan-400 | border-inline-end-color: rgb(34 211 238); | | border-e-cyan-500 | border-inline-end-color: rgb(6 182 212); | | border-e-cyan-600 | border-inline-end-color: rgb(8 145 178); | | border-e-cyan-700 | border-inline-end-color: rgb(14 116 144); | | border-e-cyan-800 | border-inline-end-color: rgb(21 94 117); | | border-e-cyan-900 | border-inline-end-color: rgb(22 78 99); | | border-e-cyan-950 | border-inline-end-color: rgb(8 51 68); | | border-e-sky-50 | border-inline-end-color: rgb(240 249 255); | | border-e-sky-100 | border-inline-end-color: rgb(224 242 254); | | border-e-sky-200 | border-inline-end-color: rgb(186 230 253); | | border-e-sky-300 | border-inline-end-color: rgb(125 211 252); | | border-e-sky-400 | border-inline-end-color: rgb(56 189 248); | | border-e-sky-500 | border-inline-end-color: rgb(14 165 233); | | border-e-sky-600 | border-inline-end-color: rgb(2 132 199); | | border-e-sky-700 | border-inline-end-color: rgb(3 105 161); | | border-e-sky-800 | border-inline-end-color: rgb(7 89 133); | | border-e-sky-900 | border-inline-end-color: rgb(12 74 110); | | border-e-sky-950 | border-inline-end-color: rgb(8 47 73); | | border-e-blue-50 | border-inline-end-color: rgb(239 246 255); | | border-e-blue-100 | border-inline-end-color: rgb(219 234 254); | | border-e-blue-200 | border-inline-end-color: rgb(191 219 254); | | border-e-blue-300 | border-inline-end-color: rgb(147 197 253); | | border-e-blue-400 | border-inline-end-color: rgb(96 165 250); | | border-e-blue-500 | border-inline-end-color: rgb(59 130 246); | | border-e-blue-600 | border-inline-end-color: rgb(37 99 235); | | border-e-blue-700 | border-inline-end-color: rgb(29 78 216); | | border-e-blue-800 | border-inline-end-color: rgb(30 64 175); | | border-e-blue-900 | border-inline-end-color: rgb(30 58 138); | | border-e-blue-950 | border-inline-end-color: rgb(23 37 84); | | border-e-indigo-50 | border-inline-end-color: rgb(238 242 255); | | border-e-indigo-100 | border-inline-end-color: rgb(224 231 255); | | border-e-indigo-200 | border-inline-end-color: rgb(199 210 254); | | border-e-indigo-300 | border-inline-end-color: rgb(165 180 252); | | border-e-indigo-400 | border-inline-end-color: rgb(129 140 248); | | border-e-indigo-500 | border-inline-end-color: rgb(99 102 241); | | border-e-indigo-600 | border-inline-end-color: rgb(79 70 229); | | border-e-indigo-700 | border-inline-end-color: rgb(67 56 202); | | border-e-indigo-800 | border-inline-end-color: rgb(55 48 163); | | border-e-indigo-900 | border-inline-end-color: rgb(49 46 129); | | border-e-indigo-950 | border-inline-end-color: rgb(30 27 75); | | border-e-violet-50 | border-inline-end-color: rgb(245 243 255); | | border-e-violet-100 | border-inline-end-color: rgb(237 233 254); | | border-e-violet-200 | border-inline-end-color: rgb(221 214 254); | | border-e-violet-300 | border-inline-end-color: rgb(196 181 253); | | border-e-violet-400 | border-inline-end-color: rgb(167 139 250); | | border-e-violet-500 | border-inline-end-color: rgb(139 92 246); | | border-e-violet-600 | border-inline-end-color: rgb(124 58 237); | | border-e-violet-700 | border-inline-end-color: rgb(109 40 217); | | border-e-violet-800 | border-inline-end-color: rgb(91 33 182); | | border-e-violet-900 | border-inline-end-color: rgb(76 29 149); | | border-e-violet-950 | border-inline-end-color: rgb(46 16 101); | | border-e-purple-50 | border-inline-end-color: rgb(250 245 255); | | border-e-purple-100 | border-inline-end-color: rgb(243 232 255); | | border-e-purple-200 | border-inline-end-color: rgb(233 213 255); | | border-e-purple-300 | border-inline-end-color: rgb(216 180 254); | | border-e-purple-400 | border-inline-end-color: rgb(192 132 252); | | border-e-purple-500 | border-inline-end-color: rgb(168 85 247); | | border-e-purple-600 | border-inline-end-color: rgb(147 51 234); | | border-e-purple-700 | border-inline-end-color: rgb(126 34 206); | | border-e-purple-800 | border-inline-end-color: rgb(107 33 168); | | border-e-purple-900 | border-inline-end-color: rgb(88 28 135); | | border-e-purple-950 | border-inline-end-color: rgb(59 7 100); | | border-e-fuchsia-50 | border-inline-end-color: rgb(253 244 255); | | border-e-fuchsia-100 | border-inline-end-color: rgb(250 232 255); | | border-e-fuchsia-200 | border-inline-end-color: rgb(245 208 254); | | border-e-fuchsia-300 | border-inline-end-color: rgb(240 171 252); | | border-e-fuchsia-400 | border-inline-end-color: rgb(232 121 249); | | border-e-fuchsia-500 | border-inline-end-color: rgb(217 70 239); | | border-e-fuchsia-600 | border-inline-end-color: rgb(192 38 211); | | border-e-fuchsia-700 | border-inline-end-color: rgb(162 28 175); | | border-e-fuchsia-800 | border-inline-end-color: rgb(134 25 143); | | border-e-fuchsia-900 | border-inline-end-color: rgb(112 26 117); | | border-e-fuchsia-950 | border-inline-end-color: rgb(74 4 78); | | border-e-pink-50 | border-inline-end-color: rgb(253 242 248); | | border-e-pink-100 | border-inline-end-color: rgb(252 231 243); | | border-e-pink-200 | border-inline-end-color: rgb(251 207 232); | | border-e-pink-300 | border-inline-end-color: rgb(249 168 212); | | border-e-pink-400 | border-inline-end-color: rgb(244 114 182); | | border-e-pink-500 | border-inline-end-color: rgb(236 72 153); | | border-e-pink-600 | border-inline-end-color: rgb(219 39 119); | | border-e-pink-700 | border-inline-end-color: rgb(190 24 93); | | border-e-pink-800 | border-inline-end-color: rgb(157 23 77); | | border-e-pink-900 | border-inline-end-color: rgb(131 24 67); | | border-e-pink-950 | border-inline-end-color: rgb(80 7 36); | | border-e-rose-50 | border-inline-end-color: rgb(255 241 242); | | border-e-rose-100 | border-inline-end-color: rgb(255 228 230); | | border-e-rose-200 | border-inline-end-color: rgb(254 205 211); | | border-e-rose-300 | border-inline-end-color: rgb(253 164 175); | | border-e-rose-400 | border-inline-end-color: rgb(251 113 133); | | border-e-rose-500 | border-inline-end-color: rgb(244 63 94); | | border-e-rose-600 | border-inline-end-color: rgb(225 29 72); | | border-e-rose-700 | border-inline-end-color: rgb(190 18 60); | | border-e-rose-800 | border-inline-end-color: rgb(159 18 57); | | border-e-rose-900 | border-inline-end-color: rgb(136 19 55); | | border-e-rose-950 | border-inline-end-color: rgb(76 5 25); | | border-t-inherit | border-top-color: inherit; | | border-t-current | border-top-color: currentColor; | | border-t-transparent | border-top-color: transparent; | | border-t-black | border-top-color: rgb(0 0 0); | | border-t-white | border-top-color: rgb(255 255 255); | | border-t-slate-50 | border-top-color: rgb(248 250 252); | | border-t-slate-100 | border-top-color: rgb(241 245 249); | | border-t-slate-200 | border-top-color: rgb(226 232 240); | | border-t-slate-300 | border-top-color: rgb(203 213 225); | | border-t-slate-400 | border-top-color: rgb(148 163 184); | | border-t-slate-500 | border-top-color: rgb(100 116 139); | | border-t-slate-600 | border-top-color: rgb(71 85 105); | | border-t-slate-700 | border-top-color: rgb(51 65 85); | | border-t-slate-800 | border-top-color: rgb(30 41 59); | | border-t-slate-900 | border-top-color: rgb(15 23 42); | | border-t-slate-950 | border-top-color: rgb(2 6 23); | | border-t-gray-50 | border-top-color: rgb(249 250 251); | | border-t-gray-100 | border-top-color: rgb(243 244 246); | | border-t-gray-200 | border-top-color: rgb(229 231 235); | | border-t-gray-300 | border-top-color: rgb(209 213 219); | | border-t-gray-400 | border-top-color: rgb(156 163 175); | | border-t-gray-500 | border-top-color: rgb(107 114 128); | | border-t-gray-600 | border-top-color: rgb(75 85 99); | | border-t-gray-700 | border-top-color: rgb(55 65 81); | | border-t-gray-800 | border-top-color: rgb(31 41 55); | | border-t-gray-900 | border-top-color: rgb(17 24 39); | | border-t-gray-950 | border-top-color: rgb(3 7 18); | | border-t-zinc-50 | border-top-color: rgb(250 250 250); | | border-t-zinc-100 | border-top-color: rgb(244 244 245); | | border-t-zinc-200 | border-top-color: rgb(228 228 231); | | border-t-zinc-300 | border-top-color: rgb(212 212 216); | | border-t-zinc-400 | border-top-color: rgb(161 161 170); | | border-t-zinc-500 | border-top-color: rgb(113 113 122); | | border-t-zinc-600 | border-top-color: rgb(82 82 91); | | border-t-zinc-700 | border-top-color: rgb(63 63 70); | | border-t-zinc-800 | border-top-color: rgb(39 39 42); | | border-t-zinc-900 | border-top-color: rgb(24 24 27); | | border-t-zinc-950 | border-top-color: rgb(9 9 11); | | border-t-neutral-50 | border-top-color: rgb(250 250 250); | | border-t-neutral-100 | border-top-color: rgb(245 245 245); | | border-t-neutral-200 | border-top-color: rgb(229 229 229); | | border-t-neutral-300 | border-top-color: rgb(212 212 212); | | border-t-neutral-400 | border-top-color: rgb(163 163 163); | | border-t-neutral-500 | border-top-color: rgb(115 115 115); | | border-t-neutral-600 | border-top-color: rgb(82 82 82); | | border-t-neutral-700 | border-top-color: rgb(64 64 64); | | border-t-neutral-800 | border-top-color: rgb(38 38 38); | | border-t-neutral-900 | border-top-color: rgb(23 23 23); | | border-t-neutral-950 | border-top-color: rgb(10 10 10); | | border-t-stone-50 | border-top-color: rgb(250 250 249); | | border-t-stone-100 | border-top-color: rgb(245 245 244); | | border-t-stone-200 | border-top-color: rgb(231 229 228); | | border-t-stone-300 | border-top-color: rgb(214 211 209); | | border-t-stone-400 | border-top-color: rgb(168 162 158); | | border-t-stone-500 | border-top-color: rgb(120 113 108); | | border-t-stone-600 | border-top-color: rgb(87 83 78); | | border-t-stone-700 | border-top-color: rgb(68 64 60); | | border-t-stone-800 | border-top-color: rgb(41 37 36); | | border-t-stone-900 | border-top-color: rgb(28 25 23); | | border-t-stone-950 | border-top-color: rgb(12 10 9); | | border-t-red-50 | border-top-color: rgb(254 242 242); | | border-t-red-100 | border-top-color: rgb(254 226 226); | | border-t-red-200 | border-top-color: rgb(254 202 202); | | border-t-red-300 | border-top-color: rgb(252 165 165); | | border-t-red-400 | border-top-color: rgb(248 113 113); | | border-t-red-500 | border-top-color: rgb(239 68 68); | | border-t-red-600 | border-top-color: rgb(220 38 38); | | border-t-red-700 | border-top-color: rgb(185 28 28); | | border-t-red-800 | border-top-color: rgb(153 27 27); | | border-t-red-900 | border-top-color: rgb(127 29 29); | | border-t-red-950 | border-top-color: rgb(69 10 10); | | border-t-orange-50 | border-top-color: rgb(255 247 237); | | border-t-orange-100 | border-top-color: rgb(255 237 213); | | border-t-orange-200 | border-top-color: rgb(254 215 170); | | border-t-orange-300 | border-top-color: rgb(253 186 116); | | border-t-orange-400 | border-top-color: rgb(251 146 60); | | border-t-orange-500 | border-top-color: rgb(249 115 22); | | border-t-orange-600 | border-top-color: rgb(234 88 12); | | border-t-orange-700 | border-top-color: rgb(194 65 12); | | border-t-orange-800 | border-top-color: rgb(154 52 18); | | border-t-orange-900 | border-top-color: rgb(124 45 18); | | border-t-orange-950 | border-top-color: rgb(67 20 7); | | border-t-amber-50 | border-top-color: rgb(255 251 235); | | border-t-amber-100 | border-top-color: rgb(254 243 199); | | border-t-amber-200 | border-top-color: rgb(253 230 138); | | border-t-amber-300 | border-top-color: rgb(252 211 77); | | border-t-amber-400 | border-top-color: rgb(251 191 36); | | border-t-amber-500 | border-top-color: rgb(245 158 11); | | border-t-amber-600 | border-top-color: rgb(217 119 6); | | border-t-amber-700 | border-top-color: rgb(180 83 9); | | border-t-amber-800 | border-top-color: rgb(146 64 14); | | border-t-amber-900 | border-top-color: rgb(120 53 15); | | border-t-amber-950 | border-top-color: rgb(69 26 3); | | border-t-yellow-50 | border-top-color: rgb(254 252 232); | | border-t-yellow-100 | border-top-color: rgb(254 249 195); | | border-t-yellow-200 | border-top-color: rgb(254 240 138); | | border-t-yellow-300 | border-top-color: rgb(253 224 71); | | border-t-yellow-400 | border-top-color: rgb(250 204 21); | | border-t-yellow-500 | border-top-color: rgb(234 179 8); | | border-t-yellow-600 | border-top-color: rgb(202 138 4); | | border-t-yellow-700 | border-top-color: rgb(161 98 7); | | border-t-yellow-800 | border-top-color: rgb(133 77 14); | | border-t-yellow-900 | border-top-color: rgb(113 63 18); | | border-t-yellow-950 | border-top-color: rgb(66 32 6); | | border-t-lime-50 | border-top-color: rgb(247 254 231); | | border-t-lime-100 | border-top-color: rgb(236 252 203); | | border-t-lime-200 | border-top-color: rgb(217 249 157); | | border-t-lime-300 | border-top-color: rgb(190 242 100); | | border-t-lime-400 | border-top-color: rgb(163 230 53); | | border-t-lime-500 | border-top-color: rgb(132 204 22); | | border-t-lime-600 | border-top-color: rgb(101 163 13); | | border-t-lime-700 | border-top-color: rgb(77 124 15); | | border-t-lime-800 | border-top-color: rgb(63 98 18); | | border-t-lime-900 | border-top-color: rgb(54 83 20); | | border-t-lime-950 | border-top-color: rgb(26 46 5); | | border-t-green-50 | border-top-color: rgb(240 253 244); | | border-t-green-100 | border-top-color: rgb(220 252 231); | | border-t-green-200 | border-top-color: rgb(187 247 208); | | border-t-green-300 | border-top-color: rgb(134 239 172); | | border-t-green-400 | border-top-color: rgb(74 222 128); | | border-t-green-500 | border-top-color: rgb(34 197 94); | | border-t-green-600 | border-top-color: rgb(22 163 74); | | border-t-green-700 | border-top-color: rgb(21 128 61); | | border-t-green-800 | border-top-color: rgb(22 101 52); | | border-t-green-900 | border-top-color: rgb(20 83 45); | | border-t-green-950 | border-top-color: rgb(5 46 22); | | border-t-emerald-50 | border-top-color: rgb(236 253 245); | | border-t-emerald-100 | border-top-color: rgb(209 250 229); | | border-t-emerald-200 | border-top-color: rgb(167 243 208); | | border-t-emerald-300 | border-top-color: rgb(110 231 183); | | border-t-emerald-400 | border-top-color: rgb(52 211 153); | | border-t-emerald-500 | border-top-color: rgb(16 185 129); | | border-t-emerald-600 | border-top-color: rgb(5 150 105); | | border-t-emerald-700 | border-top-color: rgb(4 120 87); | | border-t-emerald-800 | border-top-color: rgb(6 95 70); | | border-t-emerald-900 | border-top-color: rgb(6 78 59); | | border-t-emerald-950 | border-top-color: rgb(2 44 34); | | border-t-teal-50 | border-top-color: rgb(240 253 250); | | border-t-teal-100 | border-top-color: rgb(204 251 241); | | border-t-teal-200 | border-top-color: rgb(153 246 228); | | border-t-teal-300 | border-top-color: rgb(94 234 212); | | border-t-teal-400 | border-top-color: rgb(45 212 191); | | border-t-teal-500 | border-top-color: rgb(20 184 166); | | border-t-teal-600 | border-top-color: rgb(13 148 136); | | border-t-teal-700 | border-top-color: rgb(15 118 110); | | border-t-teal-800 | border-top-color: rgb(17 94 89); | | border-t-teal-900 | border-top-color: rgb(19 78 74); | | border-t-teal-950 | border-top-color: rgb(4 47 46); | | border-t-cyan-50 | border-top-color: rgb(236 254 255); | | border-t-cyan-100 | border-top-color: rgb(207 250 254); | | border-t-cyan-200 | border-top-color: rgb(165 243 252); | | border-t-cyan-300 | border-top-color: rgb(103 232 249); | | border-t-cyan-400 | border-top-color: rgb(34 211 238); | | border-t-cyan-500 | border-top-color: rgb(6 182 212); | | border-t-cyan-600 | border-top-color: rgb(8 145 178); | | border-t-cyan-700 | border-top-color: rgb(14 116 144); | | border-t-cyan-800 | border-top-color: rgb(21 94 117); | | border-t-cyan-900 | border-top-color: rgb(22 78 99); | | border-t-cyan-950 | border-top-color: rgb(8 51 68); | | border-t-sky-50 | border-top-color: rgb(240 249 255); | | border-t-sky-100 | border-top-color: rgb(224 242 254); | | border-t-sky-200 | border-top-color: rgb(186 230 253); | | border-t-sky-300 | border-top-color: rgb(125 211 252); | | border-t-sky-400 | border-top-color: rgb(56 189 248); | | border-t-sky-500 | border-top-color: rgb(14 165 233); | | border-t-sky-600 | border-top-color: rgb(2 132 199); | | border-t-sky-700 | border-top-color: rgb(3 105 161); | | border-t-sky-800 | border-top-color: rgb(7 89 133); | | border-t-sky-900 | border-top-color: rgb(12 74 110); | | border-t-sky-950 | border-top-color: rgb(8 47 73); | | border-t-blue-50 | border-top-color: rgb(239 246 255); | | border-t-blue-100 | border-top-color: rgb(219 234 254); | | border-t-blue-200 | border-top-color: rgb(191 219 254); | | border-t-blue-300 | border-top-color: rgb(147 197 253); | | border-t-blue-400 | border-top-color: rgb(96 165 250); | | border-t-blue-500 | border-top-color: rgb(59 130 246); | | border-t-blue-600 | border-top-color: rgb(37 99 235); | | border-t-blue-700 | border-top-color: rgb(29 78 216); | | border-t-blue-800 | border-top-color: rgb(30 64 175); | | border-t-blue-900 | border-top-color: rgb(30 58 138); | | border-t-blue-950 | border-top-color: rgb(23 37 84); | | border-t-indigo-50 | border-top-color: rgb(238 242 255); | | border-t-indigo-100 | border-top-color: rgb(224 231 255); | | border-t-indigo-200 | border-top-color: rgb(199 210 254); | | border-t-indigo-300 | border-top-color: rgb(165 180 252); | | border-t-indigo-400 | border-top-color: rgb(129 140 248); | | border-t-indigo-500 | border-top-color: rgb(99 102 241); | | border-t-indigo-600 | border-top-color: rgb(79 70 229); | | border-t-indigo-700 | border-top-color: rgb(67 56 202); | | border-t-indigo-800 | border-top-color: rgb(55 48 163); | | border-t-indigo-900 | border-top-color: rgb(49 46 129); | | border-t-indigo-950 | border-top-color: rgb(30 27 75); | | border-t-violet-50 | border-top-color: rgb(245 243 255); | | border-t-violet-100 | border-top-color: rgb(237 233 254); | | border-t-violet-200 | border-top-color: rgb(221 214 254); | | border-t-violet-300 | border-top-color: rgb(196 181 253); | | border-t-violet-400 | border-top-color: rgb(167 139 250); | | border-t-violet-500 | border-top-color: rgb(139 92 246); | | border-t-violet-600 | border-top-color: rgb(124 58 237); | | border-t-violet-700 | border-top-color: rgb(109 40 217); | | border-t-violet-800 | border-top-color: rgb(91 33 182); | | border-t-violet-900 | border-top-color: rgb(76 29 149); | | border-t-violet-950 | border-top-color: rgb(46 16 101); | | border-t-purple-50 | border-top-color: rgb(250 245 255); | | border-t-purple-100 | border-top-color: rgb(243 232 255); | | border-t-purple-200 | border-top-color: rgb(233 213 255); | | border-t-purple-300 | border-top-color: rgb(216 180 254); | | border-t-purple-400 | border-top-color: rgb(192 132 252); | | border-t-purple-500 | border-top-color: rgb(168 85 247); | | border-t-purple-600 | border-top-color: rgb(147 51 234); | | border-t-purple-700 | border-top-color: rgb(126 34 206); | | border-t-purple-800 | border-top-color: rgb(107 33 168); | | border-t-purple-900 | border-top-color: rgb(88 28 135); | | border-t-purple-950 | border-top-color: rgb(59 7 100); | | border-t-fuchsia-50 | border-top-color: rgb(253 244 255); | | border-t-fuchsia-100 | border-top-color: rgb(250 232 255); | | border-t-fuchsia-200 | border-top-color: rgb(245 208 254); | | border-t-fuchsia-300 | border-top-color: rgb(240 171 252); | | border-t-fuchsia-400 | border-top-color: rgb(232 121 249); | | border-t-fuchsia-500 | border-top-color: rgb(217 70 239); | | border-t-fuchsia-600 | border-top-color: rgb(192 38 211); | | border-t-fuchsia-700 | border-top-color: rgb(162 28 175); | | border-t-fuchsia-800 | border-top-color: rgb(134 25 143); | | border-t-fuchsia-900 | border-top-color: rgb(112 26 117); | | border-t-fuchsia-950 | border-top-color: rgb(74 4 78); | | border-t-pink-50 | border-top-color: rgb(253 242 248); | | border-t-pink-100 | border-top-color: rgb(252 231 243); | | border-t-pink-200 | border-top-color: rgb(251 207 232); | | border-t-pink-300 | border-top-color: rgb(249 168 212); | | border-t-pink-400 | border-top-color: rgb(244 114 182); | | border-t-pink-500 | border-top-color: rgb(236 72 153); | | border-t-pink-600 | border-top-color: rgb(219 39 119); | | border-t-pink-700 | border-top-color: rgb(190 24 93); | | border-t-pink-800 | border-top-color: rgb(157 23 77); | | border-t-pink-900 | border-top-color: rgb(131 24 67); | | border-t-pink-950 | border-top-color: rgb(80 7 36); | | border-t-rose-50 | border-top-color: rgb(255 241 242); | | border-t-rose-100 | border-top-color: rgb(255 228 230); | | border-t-rose-200 | border-top-color: rgb(254 205 211); | | border-t-rose-300 | border-top-color: rgb(253 164 175); | | border-t-rose-400 | border-top-color: rgb(251 113 133); | | border-t-rose-500 | border-top-color: rgb(244 63 94); | | border-t-rose-600 | border-top-color: rgb(225 29 72); | | border-t-rose-700 | border-top-color: rgb(190 18 60); | | border-t-rose-800 | border-top-color: rgb(159 18 57); | | border-t-rose-900 | border-top-color: rgb(136 19 55); | | border-t-rose-950 | border-top-color: rgb(76 5 25); | | border-r-inherit | border-right-color: inherit; | | border-r-current | border-right-color: currentColor; | | border-r-transparent | border-right-color: transparent; | | border-r-black | border-right-color: rgb(0 0 0); | | border-r-white | border-right-color: rgb(255 255 255); | | border-r-slate-50 | border-right-color: rgb(248 250 252); | | border-r-slate-100 | border-right-color: rgb(241 245 249); | | border-r-slate-200 | border-right-color: rgb(226 232 240); | | border-r-slate-300 | border-right-color: rgb(203 213 225); | | border-r-slate-400 | border-right-color: rgb(148 163 184); | | border-r-slate-500 | border-right-color: rgb(100 116 139); | | border-r-slate-600 | border-right-color: rgb(71 85 105); | | border-r-slate-700 | border-right-color: rgb(51 65 85); | | border-r-slate-800 | border-right-color: rgb(30 41 59); | | border-r-slate-900 | border-right-color: rgb(15 23 42); | | border-r-slate-950 | border-right-color: rgb(2 6 23); | | border-r-gray-50 | border-right-color: rgb(249 250 251); | | border-r-gray-100 | border-right-color: rgb(243 244 246); | | border-r-gray-200 | border-right-color: rgb(229 231 235); | | border-r-gray-300 | border-right-color: rgb(209 213 219); | | border-r-gray-400 | border-right-color: rgb(156 163 175); | | border-r-gray-500 | border-right-color: rgb(107 114 128); | | border-r-gray-600 | border-right-color: rgb(75 85 99); | | border-r-gray-700 | border-right-color: rgb(55 65 81); | | border-r-gray-800 | border-right-color: rgb(31 41 55); | | border-r-gray-900 | border-right-color: rgb(17 24 39); | | border-r-gray-950 | border-right-color: rgb(3 7 18); | | border-r-zinc-50 | border-right-color: rgb(250 250 250); | | border-r-zinc-100 | border-right-color: rgb(244 244 245); | | border-r-zinc-200 | border-right-color: rgb(228 228 231); | | border-r-zinc-300 | border-right-color: rgb(212 212 216); | | border-r-zinc-400 | border-right-color: rgb(161 161 170); | | border-r-zinc-500 | border-right-color: rgb(113 113 122); | | border-r-zinc-600 | border-right-color: rgb(82 82 91); | | border-r-zinc-700 | border-right-color: rgb(63 63 70); | | border-r-zinc-800 | border-right-color: rgb(39 39 42); | | border-r-zinc-900 | border-right-color: rgb(24 24 27); | | border-r-zinc-950 | border-right-color: rgb(9 9 11); | | border-r-neutral-50 | border-right-color: rgb(250 250 250); | | border-r-neutral-100 | border-right-color: rgb(245 245 245); | | border-r-neutral-200 | border-right-color: rgb(229 229 229); | | border-r-neutral-300 | border-right-color: rgb(212 212 212); | | border-r-neutral-400 | border-right-color: rgb(163 163 163); | | border-r-neutral-500 | border-right-color: rgb(115 115 115); | | border-r-neutral-600 | border-right-color: rgb(82 82 82); | | border-r-neutral-700 | border-right-color: rgb(64 64 64); | | border-r-neutral-800 | border-right-color: rgb(38 38 38); | | border-r-neutral-900 | border-right-color: rgb(23 23 23); | | border-r-neutral-950 | border-right-color: rgb(10 10 10); | | border-r-stone-50 | border-right-color: rgb(250 250 249); | | border-r-stone-100 | border-right-color: rgb(245 245 244); | | border-r-stone-200 | border-right-color: rgb(231 229 228); | | border-r-stone-300 | border-right-color: rgb(214 211 209); | | border-r-stone-400 | border-right-color: rgb(168 162 158); | | border-r-stone-500 | border-right-color: rgb(120 113 108); | | border-r-stone-600 | border-right-color: rgb(87 83 78); | | border-r-stone-700 | border-right-color: rgb(68 64 60); | | border-r-stone-800 | border-right-color: rgb(41 37 36); | | border-r-stone-900 | border-right-color: rgb(28 25 23); | | border-r-stone-950 | border-right-color: rgb(12 10 9); | | border-r-red-50 | border-right-color: rgb(254 242 242); | | border-r-red-100 | border-right-color: rgb(254 226 226); | | border-r-red-200 | border-right-color: rgb(254 202 202); | | border-r-red-300 | border-right-color: rgb(252 165 165); | | border-r-red-400 | border-right-color: rgb(248 113 113); | | border-r-red-500 | border-right-color: rgb(239 68 68); | | border-r-red-600 | border-right-color: rgb(220 38 38); | | border-r-red-700 | border-right-color: rgb(185 28 28); | | border-r-red-800 | border-right-color: rgb(153 27 27); | | border-r-red-900 | border-right-color: rgb(127 29 29); | | border-r-red-950 | border-right-color: rgb(69 10 10); | | border-r-orange-50 | border-right-color: rgb(255 247 237); | | border-r-orange-100 | border-right-color: rgb(255 237 213); | | border-r-orange-200 | border-right-color: rgb(254 215 170); | | border-r-orange-300 | border-right-color: rgb(253 186 116); | | border-r-orange-400 | border-right-color: rgb(251 146 60); | | border-r-orange-500 | border-right-color: rgb(249 115 22); | | border-r-orange-600 | border-right-color: rgb(234 88 12); | | border-r-orange-700 | border-right-color: rgb(194 65 12); | | border-r-orange-800 | border-right-color: rgb(154 52 18); | | border-r-orange-900 | border-right-color: rgb(124 45 18); | | border-r-orange-950 | border-right-color: rgb(67 20 7); | | border-r-amber-50 | border-right-color: rgb(255 251 235); | | border-r-amber-100 | border-right-color: rgb(254 243 199); | | border-r-amber-200 | border-right-color: rgb(253 230 138); | | border-r-amber-300 | border-right-color: rgb(252 211 77); | | border-r-amber-400 | border-right-color: rgb(251 191 36); | | border-r-amber-500 | border-right-color: rgb(245 158 11); | | border-r-amber-600 | border-right-color: rgb(217 119 6); | | border-r-amber-700 | border-right-color: rgb(180 83 9); | | border-r-amber-800 | border-right-color: rgb(146 64 14); | | border-r-amber-900 | border-right-color: rgb(120 53 15); | | border-r-amber-950 | border-right-color: rgb(69 26 3); | | border-r-yellow-50 | border-right-color: rgb(254 252 232); | | border-r-yellow-100 | border-right-color: rgb(254 249 195); | | border-r-yellow-200 | border-right-color: rgb(254 240 138); | | border-r-yellow-300 | border-right-color: rgb(253 224 71); | | border-r-yellow-400 | border-right-color: rgb(250 204 21); | | border-r-yellow-500 | border-right-color: rgb(234 179 8); | | border-r-yellow-600 | border-right-color: rgb(202 138 4); | | border-r-yellow-700 | border-right-color: rgb(161 98 7); | | border-r-yellow-800 | border-right-color: rgb(133 77 14); | | border-r-yellow-900 | border-right-color: rgb(113 63 18); | | border-r-yellow-950 | border-right-color: rgb(66 32 6); | | border-r-lime-50 | border-right-color: rgb(247 254 231); | | border-r-lime-100 | border-right-color: rgb(236 252 203); | | border-r-lime-200 | border-right-color: rgb(217 249 157); | | border-r-lime-300 | border-right-color: rgb(190 242 100); | | border-r-lime-400 | border-right-color: rgb(163 230 53); | | border-r-lime-500 | border-right-color: rgb(132 204 22); | | border-r-lime-600 | border-right-color: rgb(101 163 13); | | border-r-lime-700 | border-right-color: rgb(77 124 15); | | border-r-lime-800 | border-right-color: rgb(63 98 18); | | border-r-lime-900 | border-right-color: rgb(54 83 20); | | border-r-lime-950 | border-right-color: rgb(26 46 5); | | border-r-green-50 | border-right-color: rgb(240 253 244); | | border-r-green-100 | border-right-color: rgb(220 252 231); | | border-r-green-200 | border-right-color: rgb(187 247 208); | | border-r-green-300 | border-right-color: rgb(134 239 172); | | border-r-green-400 | border-right-color: rgb(74 222 128); | | border-r-green-500 | border-right-color: rgb(34 197 94); | | border-r-green-600 | border-right-color: rgb(22 163 74); | | border-r-green-700 | border-right-color: rgb(21 128 61); | | border-r-green-800 | border-right-color: rgb(22 101 52); | | border-r-green-900 | border-right-color: rgb(20 83 45); | | border-r-green-950 | border-right-color: rgb(5 46 22); | | border-r-emerald-50 | border-right-color: rgb(236 253 245); | | border-r-emerald-100 | border-right-color: rgb(209 250 229); | | border-r-emerald-200 | border-right-color: rgb(167 243 208); | | border-r-emerald-300 | border-right-color: rgb(110 231 183); | | border-r-emerald-400 | border-right-color: rgb(52 211 153); | | border-r-emerald-500 | border-right-color: rgb(16 185 129); | | border-r-emerald-600 | border-right-color: rgb(5 150 105); | | border-r-emerald-700 | border-right-color: rgb(4 120 87); | | border-r-emerald-800 | border-right-color: rgb(6 95 70); | | border-r-emerald-900 | border-right-color: rgb(6 78 59); | | border-r-emerald-950 | border-right-color: rgb(2 44 34); | | border-r-teal-50 | border-right-color: rgb(240 253 250); | | border-r-teal-100 | border-right-color: rgb(204 251 241); | | border-r-teal-200 | border-right-color: rgb(153 246 228); | | border-r-teal-300 | border-right-color: rgb(94 234 212); | | border-r-teal-400 | border-right-color: rgb(45 212 191); | | border-r-teal-500 | border-right-color: rgb(20 184 166); | | border-r-teal-600 | border-right-color: rgb(13 148 136); | | border-r-teal-700 | border-right-color: rgb(15 118 110); | | border-r-teal-800 | border-right-color: rgb(17 94 89); | | border-r-teal-900 | border-right-color: rgb(19 78 74); | | border-r-teal-950 | border-right-color: rgb(4 47 46); | | border-r-cyan-50 | border-right-color: rgb(236 254 255); | | border-r-cyan-100 | border-right-color: rgb(207 250 254); | | border-r-cyan-200 | border-right-color: rgb(165 243 252); | | border-r-cyan-300 | border-right-color: rgb(103 232 249); | | border-r-cyan-400 | border-right-color: rgb(34 211 238); | | border-r-cyan-500 | border-right-color: rgb(6 182 212); | | border-r-cyan-600 | border-right-color: rgb(8 145 178); | | border-r-cyan-700 | border-right-color: rgb(14 116 144); | | border-r-cyan-800 | border-right-color: rgb(21 94 117); | | border-r-cyan-900 | border-right-color: rgb(22 78 99); | | border-r-cyan-950 | border-right-color: rgb(8 51 68); | | border-r-sky-50 | border-right-color: rgb(240 249 255); | | border-r-sky-100 | border-right-color: rgb(224 242 254); | | border-r-sky-200 | border-right-color: rgb(186 230 253); | | border-r-sky-300 | border-right-color: rgb(125 211 252); | | border-r-sky-400 | border-right-color: rgb(56 189 248); | | border-r-sky-500 | border-right-color: rgb(14 165 233); | | border-r-sky-600 | border-right-color: rgb(2 132 199); | | border-r-sky-700 | border-right-color: rgb(3 105 161); | | border-r-sky-800 | border-right-color: rgb(7 89 133); | | border-r-sky-900 | border-right-color: rgb(12 74 110); | | border-r-sky-950 | border-right-color: rgb(8 47 73); | | border-r-blue-50 | border-right-color: rgb(239 246 255); | | border-r-blue-100 | border-right-color: rgb(219 234 254); | | border-r-blue-200 | border-right-color: rgb(191 219 254); | | border-r-blue-300 | border-right-color: rgb(147 197 253); | | border-r-blue-400 | border-right-color: rgb(96 165 250); | | border-r-blue-500 | border-right-color: rgb(59 130 246); | | border-r-blue-600 | border-right-color: rgb(37 99 235); | | border-r-blue-700 | border-right-color: rgb(29 78 216); | | border-r-blue-800 | border-right-color: rgb(30 64 175); | | border-r-blue-900 | border-right-color: rgb(30 58 138); | | border-r-blue-950 | border-right-color: rgb(23 37 84); | | border-r-indigo-50 | border-right-color: rgb(238 242 255); | | border-r-indigo-100 | border-right-color: rgb(224 231 255); | | border-r-indigo-200 | border-right-color: rgb(199 210 254); | | border-r-indigo-300 | border-right-color: rgb(165 180 252); | | border-r-indigo-400 | border-right-color: rgb(129 140 248); | | border-r-indigo-500 | border-right-color: rgb(99 102 241); | | border-r-indigo-600 | border-right-color: rgb(79 70 229); | | border-r-indigo-700 | border-right-color: rgb(67 56 202); | | border-r-indigo-800 | border-right-color: rgb(55 48 163); | | border-r-indigo-900 | border-right-color: rgb(49 46 129); | | border-r-indigo-950 | border-right-color: rgb(30 27 75); | | border-r-violet-50 | border-right-color: rgb(245 243 255); | | border-r-violet-100 | border-right-color: rgb(237 233 254); | | border-r-violet-200 | border-right-color: rgb(221 214 254); | | border-r-violet-300 | border-right-color: rgb(196 181 253); | | border-r-violet-400 | border-right-color: rgb(167 139 250); | | border-r-violet-500 | border-right-color: rgb(139 92 246); | | border-r-violet-600 | border-right-color: rgb(124 58 237); | | border-r-violet-700 | border-right-color: rgb(109 40 217); | | border-r-violet-800 | border-right-color: rgb(91 33 182); | | border-r-violet-900 | border-right-color: rgb(76 29 149); | | border-r-violet-950 | border-right-color: rgb(46 16 101); | | border-r-purple-50 | border-right-color: rgb(250 245 255); | | border-r-purple-100 | border-right-color: rgb(243 232 255); | | border-r-purple-200 | border-right-color: rgb(233 213 255); | | border-r-purple-300 | border-right-color: rgb(216 180 254); | | border-r-purple-400 | border-right-color: rgb(192 132 252); | | border-r-purple-500 | border-right-color: rgb(168 85 247); | | border-r-purple-600 | border-right-color: rgb(147 51 234); | | border-r-purple-700 | border-right-color: rgb(126 34 206); | | border-r-purple-800 | border-right-color: rgb(107 33 168); | | border-r-purple-900 | border-right-color: rgb(88 28 135); | | border-r-purple-950 | border-right-color: rgb(59 7 100); | | border-r-fuchsia-50 | border-right-color: rgb(253 244 255); | | border-r-fuchsia-100 | border-right-color: rgb(250 232 255); | | border-r-fuchsia-200 | border-right-color: rgb(245 208 254); | | border-r-fuchsia-300 | border-right-color: rgb(240 171 252); | | border-r-fuchsia-400 | border-right-color: rgb(232 121 249); | | border-r-fuchsia-500 | border-right-color: rgb(217 70 239); | | border-r-fuchsia-600 | border-right-color: rgb(192 38 211); | | border-r-fuchsia-700 | border-right-color: rgb(162 28 175); | | border-r-fuchsia-800 | border-right-color: rgb(134 25 143); | | border-r-fuchsia-900 | border-right-color: rgb(112 26 117); | | border-r-fuchsia-950 | border-right-color: rgb(74 4 78); | | border-r-pink-50 | border-right-color: rgb(253 242 248); | | border-r-pink-100 | border-right-color: rgb(252 231 243); | | border-r-pink-200 | border-right-color: rgb(251 207 232); | | border-r-pink-300 | border-right-color: rgb(249 168 212); | | border-r-pink-400 | border-right-color: rgb(244 114 182); | | border-r-pink-500 | border-right-color: rgb(236 72 153); | | border-r-pink-600 | border-right-color: rgb(219 39 119); | | border-r-pink-700 | border-right-color: rgb(190 24 93); | | border-r-pink-800 | border-right-color: rgb(157 23 77); | | border-r-pink-900 | border-right-color: rgb(131 24 67); | | border-r-pink-950 | border-right-color: rgb(80 7 36); | | border-r-rose-50 | border-right-color: rgb(255 241 242); | | border-r-rose-100 | border-right-color: rgb(255 228 230); | | border-r-rose-200 | border-right-color: rgb(254 205 211); | | border-r-rose-300 | border-right-color: rgb(253 164 175); | | border-r-rose-400 | border-right-color: rgb(251 113 133); | | border-r-rose-500 | border-right-color: rgb(244 63 94); | | border-r-rose-600 | border-right-color: rgb(225 29 72); | | border-r-rose-700 | border-right-color: rgb(190 18 60); | | border-r-rose-800 | border-right-color: rgb(159 18 57); | | border-r-rose-900 | border-right-color: rgb(136 19 55); | | border-r-rose-950 | border-right-color: rgb(76 5 25); | | border-b-inherit | border-bottom-color: inherit; | | border-b-current | border-bottom-color: currentColor; | | border-b-transparent | border-bottom-color: transparent; | | border-b-black | border-bottom-color: rgb(0 0 0); | | border-b-white | border-bottom-color: rgb(255 255 255); | | border-b-slate-50 | border-bottom-color: rgb(248 250 252); | | border-b-slate-100 | border-bottom-color: rgb(241 245 249); | | border-b-slate-200 | border-bottom-color: rgb(226 232 240); | | border-b-slate-300 | border-bottom-color: rgb(203 213 225); | | border-b-slate-400 | border-bottom-color: rgb(148 163 184); | | border-b-slate-500 | border-bottom-color: rgb(100 116 139); | | border-b-slate-600 | border-bottom-color: rgb(71 85 105); | | border-b-slate-700 | border-bottom-color: rgb(51 65 85); | | border-b-slate-800 | border-bottom-color: rgb(30 41 59); | | border-b-slate-900 | border-bottom-color: rgb(15 23 42); | | border-b-slate-950 | border-bottom-color: rgb(2 6 23); | | border-b-gray-50 | border-bottom-color: rgb(249 250 251); | | border-b-gray-100 | border-bottom-color: rgb(243 244 246); | | border-b-gray-200 | border-bottom-color: rgb(229 231 235); | | border-b-gray-300 | border-bottom-color: rgb(209 213 219); | | border-b-gray-400 | border-bottom-color: rgb(156 163 175); | | border-b-gray-500 | border-bottom-color: rgb(107 114 128); | | border-b-gray-600 | border-bottom-color: rgb(75 85 99); | | border-b-gray-700 | border-bottom-color: rgb(55 65 81); | | border-b-gray-800 | border-bottom-color: rgb(31 41 55); | | border-b-gray-900 | border-bottom-color: rgb(17 24 39); | | border-b-gray-950 | border-bottom-color: rgb(3 7 18); | | border-b-zinc-50 | border-bottom-color: rgb(250 250 250); | | border-b-zinc-100 | border-bottom-color: rgb(244 244 245); | | border-b-zinc-200 | border-bottom-color: rgb(228 228 231); | | border-b-zinc-300 | border-bottom-color: rgb(212 212 216); | | border-b-zinc-400 | border-bottom-color: rgb(161 161 170); | | border-b-zinc-500 | border-bottom-color: rgb(113 113 122); | | border-b-zinc-600 | border-bottom-color: rgb(82 82 91); | | border-b-zinc-700 | border-bottom-color: rgb(63 63 70); | | border-b-zinc-800 | border-bottom-color: rgb(39 39 42); | | border-b-zinc-900 | border-bottom-color: rgb(24 24 27); | | border-b-zinc-950 | border-bottom-color: rgb(9 9 11); | | border-b-neutral-50 | border-bottom-color: rgb(250 250 250); | | border-b-neutral-100 | border-bottom-color: rgb(245 245 245); | | border-b-neutral-200 | border-bottom-color: rgb(229 229 229); | | border-b-neutral-300 | border-bottom-color: rgb(212 212 212); | | border-b-neutral-400 | border-bottom-color: rgb(163 163 163); | | border-b-neutral-500 | border-bottom-color: rgb(115 115 115); | | border-b-neutral-600 | border-bottom-color: rgb(82 82 82); | | border-b-neutral-700 | border-bottom-color: rgb(64 64 64); | | border-b-neutral-800 | border-bottom-color: rgb(38 38 38); | | border-b-neutral-900 | border-bottom-color: rgb(23 23 23); | | border-b-neutral-950 | border-bottom-color: rgb(10 10 10); | | border-b-stone-50 | border-bottom-color: rgb(250 250 249); | | border-b-stone-100 | border-bottom-color: rgb(245 245 244); | | border-b-stone-200 | border-bottom-color: rgb(231 229 228); | | border-b-stone-300 | border-bottom-color: rgb(214 211 209); | | border-b-stone-400 | border-bottom-color: rgb(168 162 158); | | border-b-stone-500 | border-bottom-color: rgb(120 113 108); | | border-b-stone-600 | border-bottom-color: rgb(87 83 78); | | border-b-stone-700 | border-bottom-color: rgb(68 64 60); | | border-b-stone-800 | border-bottom-color: rgb(41 37 36); | | border-b-stone-900 | border-bottom-color: rgb(28 25 23); | | border-b-stone-950 | border-bottom-color: rgb(12 10 9); | | border-b-red-50 | border-bottom-color: rgb(254 242 242); | | border-b-red-100 | border-bottom-color: rgb(254 226 226); | | border-b-red-200 | border-bottom-color: rgb(254 202 202); | | border-b-red-300 | border-bottom-color: rgb(252 165 165); | | border-b-red-400 | border-bottom-color: rgb(248 113 113); | | border-b-red-500 | border-bottom-color: rgb(239 68 68); | | border-b-red-600 | border-bottom-color: rgb(220 38 38); | | border-b-red-700 | border-bottom-color: rgb(185 28 28); | | border-b-red-800 | border-bottom-color: rgb(153 27 27); | | border-b-red-900 | border-bottom-color: rgb(127 29 29); | | border-b-red-950 | border-bottom-color: rgb(69 10 10); | | border-b-orange-50 | border-bottom-color: rgb(255 247 237); | | border-b-orange-100 | border-bottom-color: rgb(255 237 213); | | border-b-orange-200 | border-bottom-color: rgb(254 215 170); | | border-b-orange-300 | border-bottom-color: rgb(253 186 116); | | border-b-orange-400 | border-bottom-color: rgb(251 146 60); | | border-b-orange-500 | border-bottom-color: rgb(249 115 22); | | border-b-orange-600 | border-bottom-color: rgb(234 88 12); | | border-b-orange-700 | border-bottom-color: rgb(194 65 12); | | border-b-orange-800 | border-bottom-color: rgb(154 52 18); | | border-b-orange-900 | border-bottom-color: rgb(124 45 18); | | border-b-orange-950 | border-bottom-color: rgb(67 20 7); | | border-b-amber-50 | border-bottom-color: rgb(255 251 235); | | border-b-amber-100 | border-bottom-color: rgb(254 243 199); | | border-b-amber-200 | border-bottom-color: rgb(253 230 138); | | border-b-amber-300 | border-bottom-color: rgb(252 211 77); | | border-b-amber-400 | border-bottom-color: rgb(251 191 36); | | border-b-amber-500 | border-bottom-color: rgb(245 158 11); | | border-b-amber-600 | border-bottom-color: rgb(217 119 6); | | border-b-amber-700 | border-bottom-color: rgb(180 83 9); | | border-b-amber-800 | border-bottom-color: rgb(146 64 14); | | border-b-amber-900 | border-bottom-color: rgb(120 53 15); | | border-b-amber-950 | border-bottom-color: rgb(69 26 3); | | border-b-yellow-50 | border-bottom-color: rgb(254 252 232); | | border-b-yellow-100 | border-bottom-color: rgb(254 249 195); | | border-b-yellow-200 | border-bottom-color: rgb(254 240 138); | | border-b-yellow-300 | border-bottom-color: rgb(253 224 71); | | border-b-yellow-400 | border-bottom-color: rgb(250 204 21); | | border-b-yellow-500 | border-bottom-color: rgb(234 179 8); | | border-b-yellow-600 | border-bottom-color: rgb(202 138 4); | | border-b-yellow-700 | border-bottom-color: rgb(161 98 7); | | border-b-yellow-800 | border-bottom-color: rgb(133 77 14); | | border-b-yellow-900 | border-bottom-color: rgb(113 63 18); | | border-b-yellow-950 | border-bottom-color: rgb(66 32 6); | | border-b-lime-50 | border-bottom-color: rgb(247 254 231); | | border-b-lime-100 | border-bottom-color: rgb(236 252 203); | | border-b-lime-200 | border-bottom-color: rgb(217 249 157); | | border-b-lime-300 | border-bottom-color: rgb(190 242 100); | | border-b-lime-400 | border-bottom-color: rgb(163 230 53); | | border-b-lime-500 | border-bottom-color: rgb(132 204 22); | | border-b-lime-600 | border-bottom-color: rgb(101 163 13); | | border-b-lime-700 | border-bottom-color: rgb(77 124 15); | | border-b-lime-800 | border-bottom-color: rgb(63 98 18); | | border-b-lime-900 | border-bottom-color: rgb(54 83 20); | | border-b-lime-950 | border-bottom-color: rgb(26 46 5); | | border-b-green-50 | border-bottom-color: rgb(240 253 244); | | border-b-green-100 | border-bottom-color: rgb(220 252 231); | | border-b-green-200 | border-bottom-color: rgb(187 247 208); | | border-b-green-300 | border-bottom-color: rgb(134 239 172); | | border-b-green-400 | border-bottom-color: rgb(74 222 128); | | border-b-green-500 | border-bottom-color: rgb(34 197 94); | | border-b-green-600 | border-bottom-color: rgb(22 163 74); | | border-b-green-700 | border-bottom-color: rgb(21 128 61); | | border-b-green-800 | border-bottom-color: rgb(22 101 52); | | border-b-green-900 | border-bottom-color: rgb(20 83 45); | | border-b-green-950 | border-bottom-color: rgb(5 46 22); | | border-b-emerald-50 | border-bottom-color: rgb(236 253 245); | | border-b-emerald-100 | border-bottom-color: rgb(209 250 229); | | border-b-emerald-200 | border-bottom-color: rgb(167 243 208); | | border-b-emerald-300 | border-bottom-color: rgb(110 231 183); | | border-b-emerald-400 | border-bottom-color: rgb(52 211 153); | | border-b-emerald-500 | border-bottom-color: rgb(16 185 129); | | border-b-emerald-600 | border-bottom-color: rgb(5 150 105); | | border-b-emerald-700 | border-bottom-color: rgb(4 120 87); | | border-b-emerald-800 | border-bottom-color: rgb(6 95 70); | | border-b-emerald-900 | border-bottom-color: rgb(6 78 59); | | border-b-emerald-950 | border-bottom-color: rgb(2 44 34); | | border-b-teal-50 | border-bottom-color: rgb(240 253 250); | | border-b-teal-100 | border-bottom-color: rgb(204 251 241); | | border-b-teal-200 | border-bottom-color: rgb(153 246 228); | | border-b-teal-300 | border-bottom-color: rgb(94 234 212); | | border-b-teal-400 | border-bottom-color: rgb(45 212 191); | | border-b-teal-500 | border-bottom-color: rgb(20 184 166); | | border-b-teal-600 | border-bottom-color: rgb(13 148 136); | | border-b-teal-700 | border-bottom-color: rgb(15 118 110); | | border-b-teal-800 | border-bottom-color: rgb(17 94 89); | | border-b-teal-900 | border-bottom-color: rgb(19 78 74); | | border-b-teal-950 | border-bottom-color: rgb(4 47 46); | | border-b-cyan-50 | border-bottom-color: rgb(236 254 255); | | border-b-cyan-100 | border-bottom-color: rgb(207 250 254); | | border-b-cyan-200 | border-bottom-color: rgb(165 243 252); | | border-b-cyan-300 | border-bottom-color: rgb(103 232 249); | | border-b-cyan-400 | border-bottom-color: rgb(34 211 238); | | border-b-cyan-500 | border-bottom-color: rgb(6 182 212); | | border-b-cyan-600 | border-bottom-color: rgb(8 145 178); | | border-b-cyan-700 | border-bottom-color: rgb(14 116 144); | | border-b-cyan-800 | border-bottom-color: rgb(21 94 117); | | border-b-cyan-900 | border-bottom-color: rgb(22 78 99); | | border-b-cyan-950 | border-bottom-color: rgb(8 51 68); | | border-b-sky-50 | border-bottom-color: rgb(240 249 255); | | border-b-sky-100 | border-bottom-color: rgb(224 242 254); | | border-b-sky-200 | border-bottom-color: rgb(186 230 253); | | border-b-sky-300 | border-bottom-color: rgb(125 211 252); | | border-b-sky-400 | border-bottom-color: rgb(56 189 248); | | border-b-sky-500 | border-bottom-color: rgb(14 165 233); | | border-b-sky-600 | border-bottom-color: rgb(2 132 199); | | border-b-sky-700 | border-bottom-color: rgb(3 105 161); | | border-b-sky-800 | border-bottom-color: rgb(7 89 133); | | border-b-sky-900 | border-bottom-color: rgb(12 74 110); | | border-b-sky-950 | border-bottom-color: rgb(8 47 73); | | border-b-blue-50 | border-bottom-color: rgb(239 246 255); | | border-b-blue-100 | border-bottom-color: rgb(219 234 254); | | border-b-blue-200 | border-bottom-color: rgb(191 219 254); | | border-b-blue-300 | border-bottom-color: rgb(147 197 253); | | border-b-blue-400 | border-bottom-color: rgb(96 165 250); | | border-b-blue-500 | border-bottom-color: rgb(59 130 246); | | border-b-blue-600 | border-bottom-color: rgb(37 99 235); | | border-b-blue-700 | border-bottom-color: rgb(29 78 216); | | border-b-blue-800 | border-bottom-color: rgb(30 64 175); | | border-b-blue-900 | border-bottom-color: rgb(30 58 138); | | border-b-blue-950 | border-bottom-color: rgb(23 37 84); | | border-b-indigo-50 | border-bottom-color: rgb(238 242 255); | | border-b-indigo-100 | border-bottom-color: rgb(224 231 255); | | border-b-indigo-200 | border-bottom-color: rgb(199 210 254); | | border-b-indigo-300 | border-bottom-color: rgb(165 180 252); | | border-b-indigo-400 | border-bottom-color: rgb(129 140 248); | | border-b-indigo-500 | border-bottom-color: rgb(99 102 241); | | border-b-indigo-600 | border-bottom-color: rgb(79 70 229); | | border-b-indigo-700 | border-bottom-color: rgb(67 56 202); | | border-b-indigo-800 | border-bottom-color: rgb(55 48 163); | | border-b-indigo-900 | border-bottom-color: rgb(49 46 129); | | border-b-indigo-950 | border-bottom-color: rgb(30 27 75); | | border-b-violet-50 | border-bottom-color: rgb(245 243 255); | | border-b-violet-100 | border-bottom-color: rgb(237 233 254); | | border-b-violet-200 | border-bottom-color: rgb(221 214 254); | | border-b-violet-300 | border-bottom-color: rgb(196 181 253); | | border-b-violet-400 | border-bottom-color: rgb(167 139 250); | | border-b-violet-500 | border-bottom-color: rgb(139 92 246); | | border-b-violet-600 | border-bottom-color: rgb(124 58 237); | | border-b-violet-700 | border-bottom-color: rgb(109 40 217); | | border-b-violet-800 | border-bottom-color: rgb(91 33 182); | | border-b-violet-900 | border-bottom-color: rgb(76 29 149); | | border-b-violet-950 | border-bottom-color: rgb(46 16 101); | | border-b-purple-50 | border-bottom-color: rgb(250 245 255); | | border-b-purple-100 | border-bottom-color: rgb(243 232 255); | | border-b-purple-200 | border-bottom-color: rgb(233 213 255); | | border-b-purple-300 | border-bottom-color: rgb(216 180 254); | | border-b-purple-400 | border-bottom-color: rgb(192 132 252); | | border-b-purple-500 | border-bottom-color: rgb(168 85 247); | | border-b-purple-600 | border-bottom-color: rgb(147 51 234); | | border-b-purple-700 | border-bottom-color: rgb(126 34 206); | | border-b-purple-800 | border-bottom-color: rgb(107 33 168); | | border-b-purple-900 | border-bottom-color: rgb(88 28 135); | | border-b-purple-950 | border-bottom-color: rgb(59 7 100); | | border-b-fuchsia-50 | border-bottom-color: rgb(253 244 255); | | border-b-fuchsia-100 | border-bottom-color: rgb(250 232 255); | | border-b-fuchsia-200 | border-bottom-color: rgb(245 208 254); | | border-b-fuchsia-300 | border-bottom-color: rgb(240 171 252); | | border-b-fuchsia-400 | border-bottom-color: rgb(232 121 249); | | border-b-fuchsia-500 | border-bottom-color: rgb(217 70 239); | | border-b-fuchsia-600 | border-bottom-color: rgb(192 38 211); | | border-b-fuchsia-700 | border-bottom-color: rgb(162 28 175); | | border-b-fuchsia-800 | border-bottom-color: rgb(134 25 143); | | border-b-fuchsia-900 | border-bottom-color: rgb(112 26 117); | | border-b-fuchsia-950 | border-bottom-color: rgb(74 4 78); | | border-b-pink-50 | border-bottom-color: rgb(253 242 248); | | border-b-pink-100 | border-bottom-color: rgb(252 231 243); | | border-b-pink-200 | border-bottom-color: rgb(251 207 232); | | border-b-pink-300 | border-bottom-color: rgb(249 168 212); | | border-b-pink-400 | border-bottom-color: rgb(244 114 182); | | border-b-pink-500 | border-bottom-color: rgb(236 72 153); | | border-b-pink-600 | border-bottom-color: rgb(219 39 119); | | border-b-pink-700 | border-bottom-color: rgb(190 24 93); | | border-b-pink-800 | border-bottom-color: rgb(157 23 77); | | border-b-pink-900 | border-bottom-color: rgb(131 24 67); | | border-b-pink-950 | border-bottom-color: rgb(80 7 36); | | border-b-rose-50 | border-bottom-color: rgb(255 241 242); | | border-b-rose-100 | border-bottom-color: rgb(255 228 230); | | border-b-rose-200 | border-bottom-color: rgb(254 205 211); | | border-b-rose-300 | border-bottom-color: rgb(253 164 175); | | border-b-rose-400 | border-bottom-color: rgb(251 113 133); | | border-b-rose-500 | border-bottom-color: rgb(244 63 94); | | border-b-rose-600 | border-bottom-color: rgb(225 29 72); | | border-b-rose-700 | border-bottom-color: rgb(190 18 60); | | border-b-rose-800 | border-bottom-color: rgb(159 18 57); | | border-b-rose-900 | border-bottom-color: rgb(136 19 55); | | border-b-rose-950 | border-bottom-color: rgb(76 5 25); | | border-l-inherit | border-left-color: inherit; | | border-l-current | border-left-color: currentColor; | | border-l-transparent | border-left-color: transparent; | | border-l-black | border-left-color: rgb(0 0 0); | | border-l-white | border-left-color: rgb(255 255 255); | | border-l-slate-50 | border-left-color: rgb(248 250 252); | | border-l-slate-100 | border-left-color: rgb(241 245 249); | | border-l-slate-200 | border-left-color: rgb(226 232 240); | | border-l-slate-300 | border-left-color: rgb(203 213 225); | | border-l-slate-400 | border-left-color: rgb(148 163 184); | | border-l-slate-500 | border-left-color: rgb(100 116 139); | | border-l-slate-600 | border-left-color: rgb(71 85 105); | | border-l-slate-700 | border-left-color: rgb(51 65 85); | | border-l-slate-800 | border-left-color: rgb(30 41 59); | | border-l-slate-900 | border-left-color: rgb(15 23 42); | | border-l-slate-950 | border-left-color: rgb(2 6 23); | | border-l-gray-50 | border-left-color: rgb(249 250 251); | | border-l-gray-100 | border-left-color: rgb(243 244 246); | | border-l-gray-200 | border-left-color: rgb(229 231 235); | | border-l-gray-300 | border-left-color: rgb(209 213 219); | | border-l-gray-400 | border-left-color: rgb(156 163 175); | | border-l-gray-500 | border-left-color: rgb(107 114 128); | | border-l-gray-600 | border-left-color: rgb(75 85 99); | | border-l-gray-700 | border-left-color: rgb(55 65 81); | | border-l-gray-800 | border-left-color: rgb(31 41 55); | | border-l-gray-900 | border-left-color: rgb(17 24 39); | | border-l-gray-950 | border-left-color: rgb(3 7 18); | | border-l-zinc-50 | border-left-color: rgb(250 250 250); | | border-l-zinc-100 | border-left-color: rgb(244 244 245); | | border-l-zinc-200 | border-left-color: rgb(228 228 231); | | border-l-zinc-300 | border-left-color: rgb(212 212 216); | | border-l-zinc-400 | border-left-color: rgb(161 161 170); | | border-l-zinc-500 | border-left-color: rgb(113 113 122); | | border-l-zinc-600 | border-left-color: rgb(82 82 91); | | border-l-zinc-700 | border-left-color: rgb(63 63 70); | | border-l-zinc-800 | border-left-color: rgb(39 39 42); | | border-l-zinc-900 | border-left-color: rgb(24 24 27); | | border-l-zinc-950 | border-left-color: rgb(9 9 11); | | border-l-neutral-50 | border-left-color: rgb(250 250 250); | | border-l-neutral-100 | border-left-color: rgb(245 245 245); | | border-l-neutral-200 | border-left-color: rgb(229 229 229); | | border-l-neutral-300 | border-left-color: rgb(212 212 212); | | border-l-neutral-400 | border-left-color: rgb(163 163 163); | | border-l-neutral-500 | border-left-color: rgb(115 115 115); | | border-l-neutral-600 | border-left-color: rgb(82 82 82); | | border-l-neutral-700 | border-left-color: rgb(64 64 64); | | border-l-neutral-800 | border-left-color: rgb(38 38 38); | | border-l-neutral-900 | border-left-color: rgb(23 23 23); | | border-l-neutral-950 | border-left-color: rgb(10 10 10); | | border-l-stone-50 | border-left-color: rgb(250 250 249); | | border-l-stone-100 | border-left-color: rgb(245 245 244); | | border-l-stone-200 | border-left-color: rgb(231 229 228); | | border-l-stone-300 | border-left-color: rgb(214 211 209); | | border-l-stone-400 | border-left-color: rgb(168 162 158); | | border-l-stone-500 | border-left-color: rgb(120 113 108); | | border-l-stone-600 | border-left-color: rgb(87 83 78); | | border-l-stone-700 | border-left-color: rgb(68 64 60); | | border-l-stone-800 | border-left-color: rgb(41 37 36); | | border-l-stone-900 | border-left-color: rgb(28 25 23); | | border-l-stone-950 | border-left-color: rgb(12 10 9); | | border-l-red-50 | border-left-color: rgb(254 242 242); | | border-l-red-100 | border-left-color: rgb(254 226 226); | | border-l-red-200 | border-left-color: rgb(254 202 202); | | border-l-red-300 | border-left-color: rgb(252 165 165); | | border-l-red-400 | border-left-color: rgb(248 113 113); | | border-l-red-500 | border-left-color: rgb(239 68 68); | | border-l-red-600 | border-left-color: rgb(220 38 38); | | border-l-red-700 | border-left-color: rgb(185 28 28); | | border-l-red-800 | border-left-color: rgb(153 27 27); | | border-l-red-900 | border-left-color: rgb(127 29 29); | | border-l-red-950 | border-left-color: rgb(69 10 10); | | border-l-orange-50 | border-left-color: rgb(255 247 237); | | border-l-orange-100 | border-left-color: rgb(255 237 213); | | border-l-orange-200 | border-left-color: rgb(254 215 170); | | border-l-orange-300 | border-left-color: rgb(253 186 116); | | border-l-orange-400 | border-left-color: rgb(251 146 60); | | border-l-orange-500 | border-left-color: rgb(249 115 22); | | border-l-orange-600 | border-left-color: rgb(234 88 12); | | border-l-orange-700 | border-left-color: rgb(194 65 12); | | border-l-orange-800 | border-left-color: rgb(154 52 18); | | border-l-orange-900 | border-left-color: rgb(124 45 18); | | border-l-orange-950 | border-left-color: rgb(67 20 7); | | border-l-amber-50 | border-left-color: rgb(255 251 235); | | border-l-amber-100 | border-left-color: rgb(254 243 199); | | border-l-amber-200 | border-left-color: rgb(253 230 138); | | border-l-amber-300 | border-left-color: rgb(252 211 77); | | border-l-amber-400 | border-left-color: rgb(251 191 36); | | border-l-amber-500 | border-left-color: rgb(245 158 11); | | border-l-amber-600 | border-left-color: rgb(217 119 6); | | border-l-amber-700 | border-left-color: rgb(180 83 9); | | border-l-amber-800 | border-left-color: rgb(146 64 14); | | border-l-amber-900 | border-left-color: rgb(120 53 15); | | border-l-amber-950 | border-left-color: rgb(69 26 3); | | border-l-yellow-50 | border-left-color: rgb(254 252 232); | | border-l-yellow-100 | border-left-color: rgb(254 249 195); | | border-l-yellow-200 | border-left-color: rgb(254 240 138); | | border-l-yellow-300 | border-left-color: rgb(253 224 71); | | border-l-yellow-400 | border-left-color: rgb(250 204 21); | | border-l-yellow-500 | border-left-color: rgb(234 179 8); | | border-l-yellow-600 | border-left-color: rgb(202 138 4); | | border-l-yellow-700 | border-left-color: rgb(161 98 7); | | border-l-yellow-800 | border-left-color: rgb(133 77 14); | | border-l-yellow-900 | border-left-color: rgb(113 63 18); | | border-l-yellow-950 | border-left-color: rgb(66 32 6); | | border-l-lime-50 | border-left-color: rgb(247 254 231); | | border-l-lime-100 | border-left-color: rgb(236 252 203); | | border-l-lime-200 | border-left-color: rgb(217 249 157); | | border-l-lime-300 | border-left-color: rgb(190 242 100); | | border-l-lime-400 | border-left-color: rgb(163 230 53); | | border-l-lime-500 | border-left-color: rgb(132 204 22); | | border-l-lime-600 | border-left-color: rgb(101 163 13); | | border-l-lime-700 | border-left-color: rgb(77 124 15); | | border-l-lime-800 | border-left-color: rgb(63 98 18); | | border-l-lime-900 | border-left-color: rgb(54 83 20); | | border-l-lime-950 | border-left-color: rgb(26 46 5); | | border-l-green-50 | border-left-color: rgb(240 253 244); | | border-l-green-100 | border-left-color: rgb(220 252 231); | | border-l-green-200 | border-left-color: rgb(187 247 208); | | border-l-green-300 | border-left-color: rgb(134 239 172); | | border-l-green-400 | border-left-color: rgb(74 222 128); | | border-l-green-500 | border-left-color: rgb(34 197 94); | | border-l-green-600 | border-left-color: rgb(22 163 74); | | border-l-green-700 | border-left-color: rgb(21 128 61); | | border-l-green-800 | border-left-color: rgb(22 101 52); | | border-l-green-900 | border-left-color: rgb(20 83 45); | | border-l-green-950 | border-left-color: rgb(5 46 22); | | border-l-emerald-50 | border-left-color: rgb(236 253 245); | | border-l-emerald-100 | border-left-color: rgb(209 250 229); | | border-l-emerald-200 | border-left-color: rgb(167 243 208); | | border-l-emerald-300 | border-left-color: rgb(110 231 183); | | border-l-emerald-400 | border-left-color: rgb(52 211 153); | | border-l-emerald-500 | border-left-color: rgb(16 185 129); | | border-l-emerald-600 | border-left-color: rgb(5 150 105); | | border-l-emerald-700 | border-left-color: rgb(4 120 87); | | border-l-emerald-800 | border-left-color: rgb(6 95 70); | | border-l-emerald-900 | border-left-color: rgb(6 78 59); | | border-l-emerald-950 | border-left-color: rgb(2 44 34); | | border-l-teal-50 | border-left-color: rgb(240 253 250); | | border-l-teal-100 | border-left-color: rgb(204 251 241); | | border-l-teal-200 | border-left-color: rgb(153 246 228); | | border-l-teal-300 | border-left-color: rgb(94 234 212); | | border-l-teal-400 | border-left-color: rgb(45 212 191); | | border-l-teal-500 | border-left-color: rgb(20 184 166); | | border-l-teal-600 | border-left-color: rgb(13 148 136); | | border-l-teal-700 | border-left-color: rgb(15 118 110); | | border-l-teal-800 | border-left-color: rgb(17 94 89); | | border-l-teal-900 | border-left-color: rgb(19 78 74); | | border-l-teal-950 | border-left-color: rgb(4 47 46); | | border-l-cyan-50 | border-left-color: rgb(236 254 255); | | border-l-cyan-100 | border-left-color: rgb(207 250 254); | | border-l-cyan-200 | border-left-color: rgb(165 243 252); | | border-l-cyan-300 | border-left-color: rgb(103 232 249); | | border-l-cyan-400 | border-left-color: rgb(34 211 238); | | border-l-cyan-500 | border-left-color: rgb(6 182 212); | | border-l-cyan-600 | border-left-color: rgb(8 145 178); | | border-l-cyan-700 | border-left-color: rgb(14 116 144); | | border-l-cyan-800 | border-left-color: rgb(21 94 117); | | border-l-cyan-900 | border-left-color: rgb(22 78 99); | | border-l-cyan-950 | border-left-color: rgb(8 51 68); | | border-l-sky-50 | border-left-color: rgb(240 249 255); | | border-l-sky-100 | border-left-color: rgb(224 242 254); | | border-l-sky-200 | border-left-color: rgb(186 230 253); | | border-l-sky-300 | border-left-color: rgb(125 211 252); | | border-l-sky-400 | border-left-color: rgb(56 189 248); | | border-l-sky-500 | border-left-color: rgb(14 165 233); | | border-l-sky-600 | border-left-color: rgb(2 132 199); | | border-l-sky-700 | border-left-color: rgb(3 105 161); | | border-l-sky-800 | border-left-color: rgb(7 89 133); | | border-l-sky-900 | border-left-color: rgb(12 74 110); | | border-l-sky-950 | border-left-color: rgb(8 47 73); | | border-l-blue-50 | border-left-color: rgb(239 246 255); | | border-l-blue-100 | border-left-color: rgb(219 234 254); | | border-l-blue-200 | border-left-color: rgb(191 219 254); | | border-l-blue-300 | border-left-color: rgb(147 197 253); | | border-l-blue-400 | border-left-color: rgb(96 165 250); | | border-l-blue-500 | border-left-color: rgb(59 130 246); | | border-l-blue-600 | border-left-color: rgb(37 99 235); | | border-l-blue-700 | border-left-color: rgb(29 78 216); | | border-l-blue-800 | border-left-color: rgb(30 64 175); | | border-l-blue-900 | border-left-color: rgb(30 58 138); | | border-l-blue-950 | border-left-color: rgb(23 37 84); | | border-l-indigo-50 | border-left-color: rgb(238 242 255); | | border-l-indigo-100 | border-left-color: rgb(224 231 255); | | border-l-indigo-200 | border-left-color: rgb(199 210 254); | | border-l-indigo-300 | border-left-color: rgb(165 180 252); | | border-l-indigo-400 | border-left-color: rgb(129 140 248); | | border-l-indigo-500 | border-left-color: rgb(99 102 241); | | border-l-indigo-600 | border-left-color: rgb(79 70 229); | | border-l-indigo-700 | border-left-color: rgb(67 56 202); | | border-l-indigo-800 | border-left-color: rgb(55 48 163); | | border-l-indigo-900 | border-left-color: rgb(49 46 129); | | border-l-indigo-950 | border-left-color: rgb(30 27 75); | | border-l-violet-50 | border-left-color: rgb(245 243 255); | | border-l-violet-100 | border-left-color: rgb(237 233 254); | | border-l-violet-200 | border-left-color: rgb(221 214 254); | | border-l-violet-300 | border-left-color: rgb(196 181 253); | | border-l-violet-400 | border-left-color: rgb(167 139 250); | | border-l-violet-500 | border-left-color: rgb(139 92 246); | | border-l-violet-600 | border-left-color: rgb(124 58 237); | | border-l-violet-700 | border-left-color: rgb(109 40 217); | | border-l-violet-800 | border-left-color: rgb(91 33 182); | | border-l-violet-900 | border-left-color: rgb(76 29 149); | | border-l-violet-950 | border-left-color: rgb(46 16 101); | | border-l-purple-50 | border-left-color: rgb(250 245 255); | | border-l-purple-100 | border-left-color: rgb(243 232 255); | | border-l-purple-200 | border-left-color: rgb(233 213 255); | | border-l-purple-300 | border-left-color: rgb(216 180 254); | | border-l-purple-400 | border-left-color: rgb(192 132 252); | | border-l-purple-500 | border-left-color: rgb(168 85 247); | | border-l-purple-600 | border-left-color: rgb(147 51 234); | | border-l-purple-700 | border-left-color: rgb(126 34 206); | | border-l-purple-800 | border-left-color: rgb(107 33 168); | | border-l-purple-900 | border-left-color: rgb(88 28 135); | | border-l-purple-950 | border-left-color: rgb(59 7 100); | | border-l-fuchsia-50 | border-left-color: rgb(253 244 255); | | border-l-fuchsia-100 | border-left-color: rgb(250 232 255); | | border-l-fuchsia-200 | border-left-color: rgb(245 208 254); | | border-l-fuchsia-300 | border-left-color: rgb(240 171 252); | | border-l-fuchsia-400 | border-left-color: rgb(232 121 249); | | border-l-fuchsia-500 | border-left-color: rgb(217 70 239); | | border-l-fuchsia-600 | border-left-color: rgb(192 38 211); | | border-l-fuchsia-700 | border-left-color: rgb(162 28 175); | | border-l-fuchsia-800 | border-left-color: rgb(134 25 143); | | border-l-fuchsia-900 | border-left-color: rgb(112 26 117); | | border-l-fuchsia-950 | border-left-color: rgb(74 4 78); | | border-l-pink-50 | border-left-color: rgb(253 242 248); | | border-l-pink-100 | border-left-color: rgb(252 231 243); | | border-l-pink-200 | border-left-color: rgb(251 207 232); | | border-l-pink-300 | border-left-color: rgb(249 168 212); | | border-l-pink-400 | border-left-color: rgb(244 114 182); | | border-l-pink-500 | border-left-color: rgb(236 72 153); | | border-l-pink-600 | border-left-color: rgb(219 39 119); | | border-l-pink-700 | border-left-color: rgb(190 24 93); | | border-l-pink-800 | border-left-color: rgb(157 23 77); | | border-l-pink-900 | border-left-color: rgb(131 24 67); | | border-l-pink-950 | border-left-color: rgb(80 7 36); | | border-l-rose-50 | border-left-color: rgb(255 241 242); | | border-l-rose-100 | border-left-color: rgb(255 228 230); | | border-l-rose-200 | border-left-color: rgb(254 205 211); | | border-l-rose-300 | border-left-color: rgb(253 164 175); | | border-l-rose-400 | border-left-color: rgb(251 113 133); | | border-l-rose-500 | border-left-color: rgb(244 63 94); | | border-l-rose-600 | border-left-color: rgb(225 29 72); | | border-l-rose-700 | border-left-color: rgb(190 18 60); | | border-l-rose-800 | border-left-color: rgb(159 18 57); | | border-l-rose-900 | border-left-color: rgb(136 19 55); | | border-l-rose-950 | border-left-color: rgb(76 5 25); | Basic usage ----------- ### Setting the border color Control the border color of an element using the `border-{color}` utilities. ``` <input class="border-2 border-rose-600 ..."><input class="border-2 border-rose-500 ..."> ``` ### Changing the opacity Control the opacity of an element’s border color using the color opacity modifier. ``` <div class="border-4 border-indigo-500/100 ..."></div> <div class="border-4 border-indigo-500/75 ..."></div> <div class="border-4 border-indigo-500/50 ..."></div> ``` You can use any value defined in your [opacity scale](opacity), or use arbitrary values if you need to deviate from your design tokens. ``` <div class="border-4 border-indigo-600/[.55] ..."></div> ``` ### Individual sides Use the `border-{side}-{color}` utilities to set the border color for one side of an element. ``` <div class="border-4 border-indigo-200 border-t-indigo-500 ..."></div> <div class="border-4 border-indigo-200 border-r-indigo-500 ..."></div> <div class="border-4 border-indigo-200 border-b-indigo-500 ..."></div> <div class="border-4 border-indigo-200 border-l-indigo-500 ..."></div> ``` ### Horizontal and vertical sides Use the `border-{x|y}-{color}` utilities to set the border color on two sides of an element at the same time. ``` <div class="border-4 border-indigo-200 border-x-indigo-500 ..."></div> <div class="border-4 border-indigo-200 border-y-indigo-500 ..."></div> ``` ### Using logical properties Use the `border-s-*` and `border-e-*` utilities to set the `border-inline-start-color` and `border-inline-end-color` [logical properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties/Basic_concepts), which map to either the left or right border based on the text direction. ``` <div dir="ltr"> <div class="border-s-indigo-500 ..."></div> <div<div dir="rtl"> <div class="border-s-indigo-500 ..."></div> <div> ``` For more control, you can also use the [LTR and RTL modifiers](hover-focus-and-other-states#rtl-support) to conditionally apply specific styles depending on the current text direction. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:border-gray-500` to only apply the `border-gray-500` utility on hover. ``` <button class="border border-slate-300 hover:border-indigo-300 ..."> Send email </button><button class="border border-slate-300 hover:border-slate-400 ..."> Send email </button> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:border-green-500` to apply the `border-green-500` utility at only medium screen sizes and above. ``` <button class="border-blue-500 md:border-green-500"> <!-- ... --> </button``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as border colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your border colors by editing `theme.borderColor` or `theme.extend.borderColor` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `border-color` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <button class="border-[#243c5a]"> <!-- ... --> </button``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/border-colorBorder Spacing ============== Utilities for controlling the spacing between table borders. Quick reference --------------- | Class | Properties | | --- | --- | | border-spacing-0 | border-spacing: 0px 0px; | | border-spacing-x-0 | border-spacing: 0px var(--tw-border-spacing-y); | | border-spacing-y-0 | border-spacing: var(--tw-border-spacing-x) 0px; | | border-spacing-px | border-spacing: 1px 1px; | | border-spacing-x-px | border-spacing: 1px var(--tw-border-spacing-y); | | border-spacing-y-px | border-spacing: var(--tw-border-spacing-x) 1px; | | border-spacing-0.5 | border-spacing: 0.125rem 0.125rem; | | border-spacing-x-0.5 | border-spacing: 0.125rem var(--tw-border-spacing-y); | | border-spacing-y-0.5 | border-spacing: var(--tw-border-spacing-x) 0.125rem; | | border-spacing-1 | border-spacing: 0.25rem 0.25rem; | | border-spacing-x-1 | border-spacing: 0.25rem var(--tw-border-spacing-y); | | border-spacing-y-1 | border-spacing: var(--tw-border-spacing-x) 0.25rem; | | border-spacing-1.5 | border-spacing: 0.375rem 0.375rem; | | border-spacing-x-1.5 | border-spacing: 0.375rem var(--tw-border-spacing-y); | | border-spacing-y-1.5 | border-spacing: var(--tw-border-spacing-x) 0.375rem; | | border-spacing-2 | border-spacing: 0.5rem 0.5rem; | | border-spacing-x-2 | border-spacing: 0.5rem var(--tw-border-spacing-y); | | border-spacing-y-2 | border-spacing: var(--tw-border-spacing-x) 0.5rem; | | border-spacing-2.5 | border-spacing: 0.625rem 0.625rem; | | border-spacing-x-2.5 | border-spacing: 0.625rem var(--tw-border-spacing-y); | | border-spacing-y-2.5 | border-spacing: var(--tw-border-spacing-x) 0.625rem; | | border-spacing-3 | border-spacing: 0.75rem 0.75rem; | | border-spacing-x-3 | border-spacing: 0.75rem var(--tw-border-spacing-y); | | border-spacing-y-3 | border-spacing: var(--tw-border-spacing-x) 0.75rem; | | border-spacing-3.5 | border-spacing: 0.875rem 0.875rem; | | border-spacing-x-3.5 | border-spacing: 0.875rem var(--tw-border-spacing-y); | | border-spacing-y-3.5 | border-spacing: var(--tw-border-spacing-x) 0.875rem; | | border-spacing-4 | border-spacing: 1rem 1rem; | | border-spacing-x-4 | border-spacing: 1rem var(--tw-border-spacing-y); | | border-spacing-y-4 | border-spacing: var(--tw-border-spacing-x) 1rem; | | border-spacing-5 | border-spacing: 1.25rem 1.25rem; | | border-spacing-x-5 | border-spacing: 1.25rem var(--tw-border-spacing-y); | | border-spacing-y-5 | border-spacing: var(--tw-border-spacing-x) 1.25rem; | | border-spacing-6 | border-spacing: 1.5rem 1.5rem; | | border-spacing-x-6 | border-spacing: 1.5rem var(--tw-border-spacing-y); | | border-spacing-y-6 | border-spacing: var(--tw-border-spacing-x) 1.5rem; | | border-spacing-7 | border-spacing: 1.75rem 1.75rem; | | border-spacing-x-7 | border-spacing: 1.75rem var(--tw-border-spacing-y); | | border-spacing-y-7 | border-spacing: var(--tw-border-spacing-x) 1.75rem; | | border-spacing-8 | border-spacing: 2rem 2rem; | | border-spacing-x-8 | border-spacing: 2rem var(--tw-border-spacing-y); | | border-spacing-y-8 | border-spacing: var(--tw-border-spacing-x) 2rem; | | border-spacing-9 | border-spacing: 2.25rem 2.25rem; | | border-spacing-x-9 | border-spacing: 2.25rem var(--tw-border-spacing-y); | | border-spacing-y-9 | border-spacing: var(--tw-border-spacing-x) 2.25rem; | | border-spacing-10 | border-spacing: 2.5rem 2.5rem; | | border-spacing-x-10 | border-spacing: 2.5rem var(--tw-border-spacing-y); | | border-spacing-y-10 | border-spacing: var(--tw-border-spacing-x) 2.5rem; | | border-spacing-11 | border-spacing: 2.75rem 2.75rem; | | border-spacing-x-11 | border-spacing: 2.75rem var(--tw-border-spacing-y); | | border-spacing-y-11 | border-spacing: var(--tw-border-spacing-x) 2.75rem; | | border-spacing-12 | border-spacing: 3rem 3rem; | | border-spacing-x-12 | border-spacing: 3rem var(--tw-border-spacing-y); | | border-spacing-y-12 | border-spacing: var(--tw-border-spacing-x) 3rem; | | border-spacing-14 | border-spacing: 3.5rem 3.5rem; | | border-spacing-x-14 | border-spacing: 3.5rem var(--tw-border-spacing-y); | | border-spacing-y-14 | border-spacing: var(--tw-border-spacing-x) 3.5rem; | | border-spacing-16 | border-spacing: 4rem 4rem; | | border-spacing-x-16 | border-spacing: 4rem var(--tw-border-spacing-y); | | border-spacing-y-16 | border-spacing: var(--tw-border-spacing-x) 4rem; | | border-spacing-20 | border-spacing: 5rem 5rem; | | border-spacing-x-20 | border-spacing: 5rem var(--tw-border-spacing-y); | | border-spacing-y-20 | border-spacing: var(--tw-border-spacing-x) 5rem; | | border-spacing-24 | border-spacing: 6rem 6rem; | | border-spacing-x-24 | border-spacing: 6rem var(--tw-border-spacing-y); | | border-spacing-y-24 | border-spacing: var(--tw-border-spacing-x) 6rem; | | border-spacing-28 | border-spacing: 7rem 7rem; | | border-spacing-x-28 | border-spacing: 7rem var(--tw-border-spacing-y); | | border-spacing-y-28 | border-spacing: var(--tw-border-spacing-x) 7rem; | | border-spacing-32 | border-spacing: 8rem 8rem; | | border-spacing-x-32 | border-spacing: 8rem var(--tw-border-spacing-y); | | border-spacing-y-32 | border-spacing: var(--tw-border-spacing-x) 8rem; | | border-spacing-36 | border-spacing: 9rem 9rem; | | border-spacing-x-36 | border-spacing: 9rem var(--tw-border-spacing-y); | | border-spacing-y-36 | border-spacing: var(--tw-border-spacing-x) 9rem; | | border-spacing-40 | border-spacing: 10rem 10rem; | | border-spacing-x-40 | border-spacing: 10rem var(--tw-border-spacing-y); | | border-spacing-y-40 | border-spacing: var(--tw-border-spacing-x) 10rem; | | border-spacing-44 | border-spacing: 11rem 11rem; | | border-spacing-x-44 | border-spacing: 11rem var(--tw-border-spacing-y); | | border-spacing-y-44 | border-spacing: var(--tw-border-spacing-x) 11rem; | | border-spacing-48 | border-spacing: 12rem 12rem; | | border-spacing-x-48 | border-spacing: 12rem var(--tw-border-spacing-y); | | border-spacing-y-48 | border-spacing: var(--tw-border-spacing-x) 12rem; | | border-spacing-52 | border-spacing: 13rem 13rem; | | border-spacing-x-52 | border-spacing: 13rem var(--tw-border-spacing-y); | | border-spacing-y-52 | border-spacing: var(--tw-border-spacing-x) 13rem; | | border-spacing-56 | border-spacing: 14rem 14rem; | | border-spacing-x-56 | border-spacing: 14rem var(--tw-border-spacing-y); | | border-spacing-y-56 | border-spacing: var(--tw-border-spacing-x) 14rem; | | border-spacing-60 | border-spacing: 15rem 15rem; | | border-spacing-x-60 | border-spacing: 15rem var(--tw-border-spacing-y); | | border-spacing-y-60 | border-spacing: var(--tw-border-spacing-x) 15rem; | | border-spacing-64 | border-spacing: 16rem 16rem; | | border-spacing-x-64 | border-spacing: 16rem var(--tw-border-spacing-y); | | border-spacing-y-64 | border-spacing: var(--tw-border-spacing-x) 16rem; | | border-spacing-72 | border-spacing: 18rem 18rem; | | border-spacing-x-72 | border-spacing: 18rem var(--tw-border-spacing-y); | | border-spacing-y-72 | border-spacing: var(--tw-border-spacing-x) 18rem; | | border-spacing-80 | border-spacing: 20rem 20rem; | | border-spacing-x-80 | border-spacing: 20rem var(--tw-border-spacing-y); | | border-spacing-y-80 | border-spacing: var(--tw-border-spacing-x) 20rem; | | border-spacing-96 | border-spacing: 24rem 24rem; | | border-spacing-x-96 | border-spacing: 24rem var(--tw-border-spacing-y); | | border-spacing-y-96 | border-spacing: var(--tw-border-spacing-x) 24rem; | Basic usage ----------- ### Setting the border spacing Use the `border-spacing-*`, `border-spacing-x-*`, and `border-spacing-y-*` utilities to control the space between the borders of table cells with [separate borders](border-collapse#separate). ``` <table class="border-separate border-spacing-2 border border-slate-400 ..."> <thead> <tr> <th class="border border-slate-300 ...">State</th> <th class="border border-slate-300 ...">City</th> </tr> </thead> <tbody> <tr> <td class="border border-slate-300 ...">Indiana</td> <td class="border border-slate-300 ...">Indianapolis</td> </tr> <tr> <td class="border border-slate-300 ...">Ohio</td> <td class="border border-slate-300 ...">Columbus</td> </tr> <tr> <td class="border border-slate-300 ...">Michigan</td> <td class="border border-slate-300 ...">Detroit</td> </tr> </tbody> </table><table class="border-separate border-spacing-2 border border-slate-500 ..."> <thead> <tr> <th class="border border-slate-600 ...">State</th> <th class="border border-slate-600 ...">City</th> </tr> </thead> <tbody> <tr> <td class="border border-slate-700 ...">Indiana</td> <td class="border border-slate-700 ...">Indianapolis</td> </tr> <tr> <td class="border border-slate-700 ...">Ohio</td> <td class="border border-slate-700 ...">Columbus</td> </tr> <tr> <td class="border border-slate-700 ...">Michigan</td> <td class="border border-slate-700 ...">Detroit</td> </tr> </tbody> </table> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:border-spacing-2` to only apply the `border-spacing-2` utility on hover. ``` <table class="hover:border-spacing-2"> <!-- ... --> </table``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:border-spacing-4` to apply the `border-spacing-4` utility at only medium screen sizes and above. ``` <table class="md:border-spacing-4"> <!-- ... --> </table``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind’s border spacing utilities use the [default spacing scale](customizing-spacing). You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '13': '3.25rem', } } } } ``` Alternatively, you can customize just the border spacing scale by editing `theme.borderSpacing` or `theme.extend.borderSpacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { borderSpacing: { '13': '3.25rem', }, } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `border-spacing` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="border-spacing-[7px]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/border-spacingTable Layout ============ Utilities for controlling the table layout algorithm. Quick reference --------------- | Class | Properties | | --- | --- | | table-auto | table-layout: auto; | | table-fixed | table-layout: fixed; | Basic usage ----------- ### Auto Use `table-auto` to allow the table to automatically size columns to fit the contents of the cell. ``` <table class="table-auto"> <thead> <tr> <th>Song</th> <th>Artist</th> <th>Year</th> </tr> </thead> <tbody> <tr> <td>The Sliding Mr. Bones (Next Stop, Pottersville)</td> <td><NAME></td> <td>1961</td> </tr> <tr> <td>Witchy Woman</td> <td>The Eagles</td> <td>1972</td> </tr> <tr> <td>Shining Star</td> <td>Earth, Wind, and Fire</td> <td>1975</td> </tr> </tbody> </table> ``` ### Fixed Use `table-fixed` to allow the table to ignore the content and use fixed widths for columns. The width of the first row will set the column widths for the whole table. You can manually set the widths for some columns and the rest of the available width will be divided evenly amongst the columns without explicit width. ``` <table class="table-fixed"> <thead> <tr> <th>Song</th> <th>Artist</th> <th>Year</th> </tr> </thead> <tbody> <tr> <td>The Sliding Mr. Bones (Next Stop, Pottersville)</td> <td><NAME></td> <td>1961</td> </tr> <tr> <td>Witchy Woman</td> <td>The Eagles</td> <td>1972</td> </tr> <tr> <td>Shining Star</td> <td>Earth, Wind, and Fire</td> <td>1975</td> </tr> </tbody> </table> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:table-fixed` to only apply the `table-fixed` utility on hover. ``` <table class="hover:table-fixed"> <!-- ... --> </table``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:table-fixed` to apply the `table-fixed` utility at only medium screen sizes and above. ``` <table class="md:table-fixed"> <!-- ... --> </table``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/table-layoutCaption Side ============ Utilities for controlling the alignment of a caption element inside of a table. Quick reference --------------- | Class | Properties | | --- | --- | | caption-top | caption-side: top; | | caption-bottom | caption-side: bottom; | Basic usage ----------- ### Top Use `caption-top` to position a caption element at the top of a table. ``` <table> <caption class="caption-top"> Table 3.1: Professional wrestlers and their signature moves. </caption> <thead> <tr> <th>Wrestler</th> <th>Signature Move(s)</th> </tr> </thead> <tbody> <tr> <td>"Stone Cold" <NAME></td> <td>Stone Cold Stunner, Lou Thesz Press</td> </tr> <tr> <td>Bret "The Hitman" Hart</td> <td >The Sharpshooter</td> </tr> <tr> <td>Razor Ramon</td> <td>Razor's Edge, Fallaway Slam</td> </tr> </tbody> </table> ``` ### Bottom Use `caption-bottom` to position a caption element at the bottom of a table. ``` <table> <caption class="caption-bottom"> Table 3.1: Professional wrestlers and their signature moves. </caption> <thead> <tr> <th>Wrestler</th> <th>Signature Move(s)</th> </tr> </thead> <tbody> <tr> <td>"Stone Cold" <NAME></td> <td>Stone Cold Stunner, Lou Thesz Press</td> </tr> <tr> <td>Bret "The Hitman" Hart</td> <td >The Sharpshooter</td> </tr> <tr> <td>Razor Ramon</td> <td>Razor's Edge, Fallaway Slam</td> </tr> </tbody> </table> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:caption-bottom` to only apply the `caption-bottom` utility on hover. ``` <table class="caption-top hover:caption-bottom"> <!-- ... --> </table``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:caption-bottom` to apply the `caption-bottom` utility at only medium screen sizes and above. ``` <table class="caption-top md:caption-bottom"> <!-- ... --> </table``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/caption-sideTransition Property =================== Utilities for controlling which CSS properties transition. Quick reference --------------- | Class | Properties | | --- | --- | | transition-none | transition-property: none; | | transition-all | transition-property: all; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; | | transition | transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; | | transition-colors | transition-property: color, background-color, border-color, text-decoration-color, fill, stroke; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; | | transition-opacity | transition-property: opacity; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; | | transition-shadow | transition-property: box-shadow; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; | | transition-transform | transition-property: transform; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; | Basic usage ----------- ### Controlling transitioned properties Use the `transition-{properties}` utilities to specify which properties should transition when they change. ``` <button class="transition ease-in-out delay-150 bg-blue-500 hover:-translate-y-1 hover:scale-110 hover:bg-indigo-500 duration-300 ..."> Save Changes </button> ``` ### Prefers-reduced-motion For situations where the user has specified that they prefer reduced motion, you can conditionally apply animations and transitions using the `motion-safe` and `motion-reduce` variants: ``` <button class="transition transform hover:-translate-y-1 motion-reduce:transition-none motion-reduce:hover:transform-none ..."> Hover me </button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:transition-all` to only apply the `transition-all` utility on hover. ``` <div class="hover:transition-all"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:transition-all` to apply the `transition-all` utility at only medium screen sizes and above. ``` <div class="md:transition-all"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides transition-property utilities for seven common property combinations. You can customize these values by editing `theme.transitionProperty` or `theme.extend.transitionProperty` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { transitionProperty: { 'height': 'height', 'spacing': 'margin, padding', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `transition-property` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="transition-[height]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/transition-propertyTransition Duration =================== Utilities for controlling the duration of CSS transitions. Quick reference --------------- | Class | Properties | | --- | --- | | duration-0 | transition-duration: 0s; | | duration-75 | transition-duration: 75ms; | | duration-100 | transition-duration: 100ms; | | duration-150 | transition-duration: 150ms; | | duration-200 | transition-duration: 200ms; | | duration-300 | transition-duration: 300ms; | | duration-500 | transition-duration: 500ms; | | duration-700 | transition-duration: 700ms; | | duration-1000 | transition-duration: 1000ms; | Basic usage ----------- ### Changing transition duration Use the `duration-{amount}` utilities to control an element’s transition-duration. ``` <button class="transition duration-150 ease-in-out ...">Button A</button> <button class="transition duration-300 ease-in-out ...">Button B</button> <button class="transition duration-700 ease-in-out ...">Button C</button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:duration-150` to only apply the `duration-150` utility on hover. ``` <div class="transition duration-0 hover:duration-150"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:duration-150` to apply the `duration-150` utility at only medium screen sizes and above. ``` <div class="transition duration-0 md:duration-150"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides eight general purpose transition-duration utilities. You can customize these values by editing `theme.transitionDuration` or `theme.extend.transitionDuration` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { transitionDuration: { '2000': '2000ms', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `transition-duration` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="duration-[2000ms]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/transition-durationTransition Timing Function ========================== Utilities for controlling the easing of CSS transitions. Quick reference --------------- | Class | Properties | | --- | --- | | ease-linear | transition-timing-function: linear; | | ease-in | transition-timing-function: cubic-bezier(0.4, 0, 1, 1); | | ease-out | transition-timing-function: cubic-bezier(0, 0, 0.2, 1); | | ease-in-out | transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); | Basic usage ----------- ### Controlling the easing curve Use the `ease-{timing}` utilities to control an element’s easing curve. ``` <button class="ease-in duration-300 ...">Button A</button> <button class="ease-out duration-300 ...">Button B</button> <button class="ease-in-out duration-300 ...">Button C</button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:ease-in` to only apply the `ease-in` utility on hover. ``` <div class="transition duration-150 ease-out hover:ease-in"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:ease-in` to apply the `ease-in` utility at only medium screen sizes and above. ``` <div class="transition duration-150 ease-out md:ease-in"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides four general purpose transition-timing-function utilities. You can customize these values by editing `theme.transitionTimingFunction` or `theme.extend.transitionTimingFunction` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { transitionTimingFunction: { 'in-expo': 'cubic-bezier(0.95, 0.05, 0.795, 0.035)', 'out-expo': 'cubic-bezier(0.19, 1, 0.22, 1)', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `transition-timing-function` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="ease-[cubic-bezier(0.95,0.05,0.795,0.035)]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/transition-timing-functionTransition Delay ================ Utilities for controlling the delay of CSS transitions. Quick reference --------------- | Class | Properties | | --- | --- | | delay-0 | transition-delay: 0s; | | delay-75 | transition-delay: 75ms; | | delay-100 | transition-delay: 100ms; | | delay-150 | transition-delay: 150ms; | | delay-200 | transition-delay: 200ms; | | delay-300 | transition-delay: 300ms; | | delay-500 | transition-delay: 500ms; | | delay-700 | transition-delay: 700ms; | | delay-1000 | transition-delay: 1000ms; | Basic usage ----------- ### Delaying transitions Use the `delay-{amount}` utilities to control an element’s transition-delay. ``` <button class="transition delay-150 duration-300 ease-in-out ...">Button A</button> <button class="transition delay-300 duration-300 ease-in-out ...">Button B</button> <button class="transition delay-700 duration-300 ease-in-out ...">Button C</button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:delay-300` to only apply the `delay-300` utility on hover. ``` <div class="transition duration-300 delay-150 hover:delay-300"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:delay-300` to apply the `delay-300` utility at only medium screen sizes and above. ``` <div class="transition duration-300 delay-150 md:delay-300"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides eight general purpose transition-delay utilities. You can customize these values by editing `theme.transitionDelay` or `theme.extend.transitionDelay` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { transitionDelay: { '2000': '2000ms', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `transition-delay` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="delay-[2000ms]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/transition-delayAnimation ========= Utilities for animating elements with CSS animations. Quick reference --------------- | Class | Properties | | --- | --- | | animate-none | animation: none; | | animate-spin | animation: spin 1s linear infinite; @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } | | animate-ping | animation: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite; @keyframes ping { 75%, 100% { transform: scale(2); opacity: 0; } } | | animate-pulse | animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .5; } } | | animate-bounce | animation: bounce 1s infinite; @keyframes bounce { 0%, 100% { transform: translateY(-25%); animation-timing-function: cubic-bezier(0.8, 0, 1, 1); } 50% { transform: translateY(0); animation-timing-function: cubic-bezier(0, 0, 0.2, 1); } } | Basic usage ----------- ### Spin Add the `animate-spin` utility to add a linear spin animation to elements like loading indicators. ``` <button type="button" class="bg-indigo-500 ..." disabled> <svg class="animate-spin h-5 w-5 mr-3 ..." viewBox="0 0 24 24"> <!-- ... --> </svg> Processing... </button> ``` ### Ping Add the `animate-ping` utility to make an element scale and fade like a radar ping or ripple of water — useful for things like notification badges. ``` <span class="relative flex h-3 w-3"> <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-sky-400 opacity-75"></span> <span class="relative inline-flex rounded-full h-3 w-3 bg-sky-500"></span> </span> ``` ### Pulse Add the `animate-pulse` utility to make an element gently fade in and out — useful for things like skeleton loaders. ``` <div class="border border-blue-300 shadow rounded-md p-4 max-w-sm w-full mx-auto"> <div class="animate-pulse flex space-x-4"> <div class="rounded-full bg-slate-200 h-10 w-10"></div> <div class="flex-1 space-y-6 py-1"> <div class="h-2 bg-slate-200 rounded"></div> <div class="space-y-3"> <div class="grid grid-cols-3 gap-4"> <div class="h-2 bg-slate-200 rounded col-span-2"></div> <div class="h-2 bg-slate-200 rounded col-span-1"></div> </div> <div class="h-2 bg-slate-200 rounded"></div> </div> </div> </div> </div><div class="border border-blue-300 shadow rounded-md p-4 max-w-sm w-full mx-auto"> <div class="animate-pulse flex space-x-4"> <div class="rounded-full bg-slate-700 h-10 w-10"></div> <div class="flex-1 space-y-6 py-1"> <div class="h-2 bg-slate-700 rounded"></div> <div class="space-y-3"> <div class="grid grid-cols-3 gap-4"> <div class="h-2 bg-slate-700 rounded col-span-2"></div> <div class="h-2 bg-slate-700 rounded col-span-1"></div> </div> <div class="h-2 bg-slate-700 rounded"></div> </div> </div> </div> </div> ``` ### Bounce Add the `animate-bounce` utility to make an element bounce up and down — useful for things like “scroll down” indicators. ``` <svg class="animate-bounce w-6 h-6 ..."> <!-- ... --> </svg> ``` ### Prefers-reduced-motion For situations where the user has specified that they prefer reduced motion, you can conditionally apply animations and transitions using the `motion-safe` and `motion-reduce` variants: ``` <button type="button" class="bg-indigo-600 ..." disabled> <svg class="motion-safe:animate-spin h-5 w-5 mr-3 ..." viewBox="0 0 24 24"> <!-- ... --> </svg> Processing </button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:animate-spin` to only apply the `animate-spin` utility on hover. ``` <div class="hover:animate-spin"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:animate-spin` to apply the `animate-spin` utility at only medium screen sizes and above. ``` <div class="md:animate-spin"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme Animations by their very nature tend to be highly project-specific. **The animations we include by default are best thought of as helpful examples**, and you’re encouraged to customize your animations to better suit your needs. By default, Tailwind provides utilities for four different example animations, as well as the `animate-none` utility. You can customize these values by editing `theme.animation` or `theme.extend.animation` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { animation: { 'spin-slow': 'spin 3s linear infinite', } } } } ``` To add new animation `@keyframes`, use the `keyframes` section of your theme configuration: tailwind.config.js ``` module.exports = { theme: { extend: { keyframes: { wiggle: { '0%, 100%': { transform: 'rotate(-3deg)' }, '50%': { transform: 'rotate(3deg)' }, } } } } } ``` You can then reference these keyframes by name in the `animation` section of your theme configuration: tailwind.config.js ``` module.exports = { theme: { extend: { animation: { wiggle: 'wiggle 1s ease-in-out infinite', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `animation` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="animate-[wiggle_1s_ease-in-out_infinite]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/animationScale ===== Utilities for scaling elements with transform. Quick reference --------------- | Class | Properties | | --- | --- | | scale-0 | transform: scale(0); | | scale-x-0 | transform: scaleX(0); | | scale-y-0 | transform: scaleY(0); | | scale-50 | transform: scale(.5); | | scale-x-50 | transform: scaleX(.5); | | scale-y-50 | transform: scaleY(.5); | | scale-75 | transform: scale(.75); | | scale-x-75 | transform: scaleX(.75); | | scale-y-75 | transform: scaleY(.75); | | scale-90 | transform: scale(.9); | | scale-x-90 | transform: scaleX(.9); | | scale-y-90 | transform: scaleY(.9); | | scale-95 | transform: scale(.95); | | scale-x-95 | transform: scaleX(.95); | | scale-y-95 | transform: scaleY(.95); | | scale-100 | transform: scale(1); | | scale-x-100 | transform: scaleX(1); | | scale-y-100 | transform: scaleY(1); | | scale-105 | transform: scale(1.05); | | scale-x-105 | transform: scaleX(1.05); | | scale-y-105 | transform: scaleY(1.05); | | scale-110 | transform: scale(1.1); | | scale-x-110 | transform: scaleX(1.1); | | scale-y-110 | transform: scaleY(1.1); | | scale-125 | transform: scale(1.25); | | scale-x-125 | transform: scaleX(1.25); | | scale-y-125 | transform: scaleY(1.25); | | scale-150 | transform: scale(1.5); | | scale-x-150 | transform: scaleX(1.5); | | scale-y-150 | transform: scaleY(1.5); | Basic usage ----------- ### Scaling an element Use the `scale-{percentage}`, `scale-x-{percentage}`, and `scale-y-{percentage}` utilities to scale an element. ``` <img class="scale-75 ..."> <img class="scale-100 ..."> <img class="scale-125 ..."> ``` ### Using negative values To use a negative scale value, prefix the class name with a dash to convert it to a negative value. ``` <img class="-scale-50"> ``` ### Removing transforms To remove all of the transforms on an element at once, use the `transform-none` utility: ``` <div class="scale-75 translate-x-4 skew-y-3 md:transform-none"> <!-- ... --> </div``` This can be useful when you want to remove transforms conditionally, such as on hover or at a particular breakpoint. ### Hardware acceleration If your transition performs better when rendered by the GPU instead of the CPU, you can force hardware acceleration by adding the `transform-gpu` utility: ``` <div class="scale-150 transform-gpu"> <!-- ... --> </div``` Use `transform-cpu` to force things back to the CPU if you need to undo this conditionally. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:scale-125` to only apply the `scale-125` utility on hover. ``` <div class="hover:scale-125"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:scale-125` to apply the `scale-125` utility at only medium screen sizes and above. ``` <div class="md:scale-125"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `scale` utilities. You can customize these values by editing `theme.scale` or `theme.extend.scale` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { scale: { '175': '1.75', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `scale` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="scale-[1.7]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/scaleRotate ====== Utilities for rotating elements with transform. Quick reference --------------- | Class | Properties | | --- | --- | | rotate-0 | transform: rotate(0deg); | | rotate-1 | transform: rotate(1deg); | | rotate-2 | transform: rotate(2deg); | | rotate-3 | transform: rotate(3deg); | | rotate-6 | transform: rotate(6deg); | | rotate-12 | transform: rotate(12deg); | | rotate-45 | transform: rotate(45deg); | | rotate-90 | transform: rotate(90deg); | | rotate-180 | transform: rotate(180deg); | Basic usage ----------- ### Rotating an element Use the `rotate-{angle}` utilities to rotate an element. ``` <img class="rotate-0 ..."> <img class="rotate-45 ..."> <img class="rotate-90 ..."> <img class="rotate-180 ..."> ``` ### Using negative values To use a negative rotate value, prefix the class name with a dash to convert it to a negative value. ``` <img class="-rotate-45 ..."> ``` ### Removing transforms To remove all of the transforms on an element at once, use the `transform-none` utility: ``` <div class="scale-75 translate-x-4 skew-y-3 md:transform-none"> <!-- ... --> </div``` This can be useful when you want to remove transforms conditionally, such as on hover or at a particular breakpoint. ### Hardware acceleration If your transition performs better when rendered by the GPU instead of the CPU, you can force hardware acceleration by adding the `transform-gpu` utility: ``` <div class="rotate-45 transform-gpu"> <!-- ... --> </div``` Use `transform-cpu` to force things back to the CPU if you need to undo this conditionally. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:rotate-45` to only apply the `rotate-45` utility on hover. ``` <div class="hover:rotate-45"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:rotate-45` to apply the `rotate-45` utility at only medium screen sizes and above. ``` <div class="md:rotate-45"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `rotate` utilities. You can customize these values by editing `theme.rotate` or `theme.extend.rotate` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { rotate: { '17': '17deg', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `rotate` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="rotate-[17deg]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/rotateTranslate ========= Utilities for translating elements with transform. Quick reference --------------- | Class | Properties | | --- | --- | | translate-x-0 | transform: translateX(0px); | | translate-y-0 | transform: translateY(0px); | | translate-x-px | transform: translateX(1px); | | translate-y-px | transform: translateY(1px); | | translate-x-0.5 | transform: translateX(0.125rem); | | translate-y-0.5 | transform: translateY(0.125rem); | | translate-x-1 | transform: translateX(0.25rem); | | translate-y-1 | transform: translateY(0.25rem); | | translate-x-1.5 | transform: translateX(0.375rem); | | translate-y-1.5 | transform: translateY(0.375rem); | | translate-x-2 | transform: translateX(0.5rem); | | translate-y-2 | transform: translateY(0.5rem); | | translate-x-2.5 | transform: translateX(0.625rem); | | translate-y-2.5 | transform: translateY(0.625rem); | | translate-x-3 | transform: translateX(0.75rem); | | translate-y-3 | transform: translateY(0.75rem); | | translate-x-3.5 | transform: translateX(0.875rem); | | translate-y-3.5 | transform: translateY(0.875rem); | | translate-x-4 | transform: translateX(1rem); | | translate-y-4 | transform: translateY(1rem); | | translate-x-5 | transform: translateX(1.25rem); | | translate-y-5 | transform: translateY(1.25rem); | | translate-x-6 | transform: translateX(1.5rem); | | translate-y-6 | transform: translateY(1.5rem); | | translate-x-7 | transform: translateX(1.75rem); | | translate-y-7 | transform: translateY(1.75rem); | | translate-x-8 | transform: translateX(2rem); | | translate-y-8 | transform: translateY(2rem); | | translate-x-9 | transform: translateX(2.25rem); | | translate-y-9 | transform: translateY(2.25rem); | | translate-x-10 | transform: translateX(2.5rem); | | translate-y-10 | transform: translateY(2.5rem); | | translate-x-11 | transform: translateX(2.75rem); | | translate-y-11 | transform: translateY(2.75rem); | | translate-x-12 | transform: translateX(3rem); | | translate-y-12 | transform: translateY(3rem); | | translate-x-14 | transform: translateX(3.5rem); | | translate-y-14 | transform: translateY(3.5rem); | | translate-x-16 | transform: translateX(4rem); | | translate-y-16 | transform: translateY(4rem); | | translate-x-20 | transform: translateX(5rem); | | translate-y-20 | transform: translateY(5rem); | | translate-x-24 | transform: translateX(6rem); | | translate-y-24 | transform: translateY(6rem); | | translate-x-28 | transform: translateX(7rem); | | translate-y-28 | transform: translateY(7rem); | | translate-x-32 | transform: translateX(8rem); | | translate-y-32 | transform: translateY(8rem); | | translate-x-36 | transform: translateX(9rem); | | translate-y-36 | transform: translateY(9rem); | | translate-x-40 | transform: translateX(10rem); | | translate-y-40 | transform: translateY(10rem); | | translate-x-44 | transform: translateX(11rem); | | translate-y-44 | transform: translateY(11rem); | | translate-x-48 | transform: translateX(12rem); | | translate-y-48 | transform: translateY(12rem); | | translate-x-52 | transform: translateX(13rem); | | translate-y-52 | transform: translateY(13rem); | | translate-x-56 | transform: translateX(14rem); | | translate-y-56 | transform: translateY(14rem); | | translate-x-60 | transform: translateX(15rem); | | translate-y-60 | transform: translateY(15rem); | | translate-x-64 | transform: translateX(16rem); | | translate-y-64 | transform: translateY(16rem); | | translate-x-72 | transform: translateX(18rem); | | translate-y-72 | transform: translateY(18rem); | | translate-x-80 | transform: translateX(20rem); | | translate-y-80 | transform: translateY(20rem); | | translate-x-96 | transform: translateX(24rem); | | translate-y-96 | transform: translateY(24rem); | | translate-x-1/2 | transform: translateX(50%); | | translate-x-1/3 | transform: translateX(33.333333%); | | translate-x-2/3 | transform: translateX(66.666667%); | | translate-x-1/4 | transform: translateX(25%); | | translate-x-2/4 | transform: translateX(50%); | | translate-x-3/4 | transform: translateX(75%); | | translate-x-full | transform: translateX(100%); | | translate-y-1/2 | transform: translateY(50%); | | translate-y-1/3 | transform: translateY(33.333333%); | | translate-y-2/3 | transform: translateY(66.666667%); | | translate-y-1/4 | transform: translateY(25%); | | translate-y-2/4 | transform: translateY(50%); | | translate-y-3/4 | transform: translateY(75%); | | translate-y-full | transform: translateY(100%); | Basic usage ----------- ### Translating an element Use the `translate-x-{amount}` and `translate-y-{amount}` utilities to translate an element. ``` <img class="translate-y-6 ..."> <img class="-translate-y-6 ..."> <img class="translate-x-6 ..."> ``` ### Using negative values To use a negative translate value, prefix the class name with a dash to convert it to a negative value. ``` <img class="-translate-y-6 ..."> ``` ### Removing transforms To remove all of the transforms on an element at once, use the `transform-none` utility: ``` <div class="scale-75 translate-x-4 skew-y-3 md:transform-none"> <!-- ... --> </div``` This can be useful when you want to remove transforms conditionally, such as on hover or at a particular breakpoint. ### Hardware acceleration If your transition performs better when rendered by the GPU instead of the CPU, you can force hardware acceleration by adding the `transform-gpu` utility: ``` <div class="translate-y-6 transform-gpu"> <!-- ... --> </div``` Use `transform-cpu` to force things back to the CPU if you need to undo this conditionally. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:translate-y-12` to only apply the `translate-y-12` utility on hover. ``` <div class="hover:translate-y-12"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:translate-y-12` to apply the `translate-y-12` utility at only medium screen sizes and above. ``` <div class="md:translate-y-12"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides fixed value `translate` utilities that match the [default spacing scale](customizing-spacing), as well as 50% and 100% variations for translating relative to the element’s size. You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '4.25': '17rem', } } } } ``` Alternatively, you can customize just the translate scale by editing `theme.translate` or `theme.extend.translate` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { translate: { '4.25': '17rem', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `translate` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="translate-y-[17rem]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/translateSkew ==== Utilities for skewing elements with transform. Quick reference --------------- | Class | Properties | | --- | --- | | skew-x-0 | transform: skewX(0deg); | | skew-y-0 | transform: skewY(0deg); | | skew-x-1 | transform: skewX(1deg); | | skew-y-1 | transform: skewY(1deg); | | skew-x-2 | transform: skewX(2deg); | | skew-y-2 | transform: skewY(2deg); | | skew-x-3 | transform: skewX(3deg); | | skew-y-3 | transform: skewY(3deg); | | skew-x-6 | transform: skewX(6deg); | | skew-y-6 | transform: skewY(6deg); | | skew-x-12 | transform: skewX(12deg); | | skew-y-12 | transform: skewY(12deg); | Basic usage ----------- ### Skewing an element Use the `skew-x-{amount}` and `skew-y-{amount}` utilities to skew an element. ``` <img class="skew-y-0 ..."> <img class="skew-y-3 ..."> <img class="skew-y-6 ..."> <img class="skew-y-12 ..."> ``` ### Using negative values To use a negative skew value, prefix the class name with a dash to convert it to a negative value. ``` <img class="-skew-y-6 ..."> ``` ### Removing transforms To remove all of the transforms on an element at once, use the `transform-none` utility: ``` <div class="scale-75 translate-x-4 skew-y-3 md:transform-none"> <!-- ... --> </div``` This can be useful when you want to remove transforms conditionally, such as on hover or at a particular breakpoint. ### Hardware acceleration If your transition performs better when rendered by the GPU instead of the CPU, you can force hardware acceleration by adding the `transform-gpu` utility: ``` <div class="skew-y-6 transform-gpu"> <!-- ... --> </div``` Use `transform-cpu` to force things back to the CPU if you need to undo this conditionally. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:skew-y-12` to only apply the `skew-y-12` utility on hover. ``` <div class="hover:skew-y-12"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:skew-y-12` to apply the `skew-y-12` utility at only medium screen sizes and above. ``` <div class="md:skew-y-12"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes a handful of general purpose `skew` utilities. You can customize these values by editing `theme.skew` or `theme.extend.skew` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { skew: { '17': '17deg', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `skew` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="skew-y-[17deg]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/skewTransform Origin ================ Utilities for specifying the origin for an element's transformations. Quick reference --------------- | Class | Properties | | --- | --- | | origin-center | transform-origin: center; | | origin-top | transform-origin: top; | | origin-top-right | transform-origin: top right; | | origin-right | transform-origin: right; | | origin-bottom-right | transform-origin: bottom right; | | origin-bottom | transform-origin: bottom; | | origin-bottom-left | transform-origin: bottom left; | | origin-left | transform-origin: left; | | origin-top-left | transform-origin: top left; | Basic usage ----------- ### Changing the transform origin Specify an element’s transform origin using the `origin-{keyword}` utilities. ``` <img class="origin-center rotate-45 ..."> <img class="origin-top-left rotate-12 ..."> <img class="origin-bottom -rotate-12 ..."> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:origin-top` to only apply the `origin-top` utility on hover. ``` <div class="origin-center hover:origin-top"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:origin-top` to apply the `origin-top` utility at only medium screen sizes and above. ``` <div class="origin-center md:origin-top"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides `transform-origin` utilities for all of the built-in browser keyword options. You can customize these values by editing `theme.transformOrigin` or `theme.extend.transformOrigin` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { transformOrigin: { 'top-left-1/3-3/4': '33% 75%', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `transform-origin` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="origin-[33%_75%]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/transform-originAccent Color ============ Utilities for controlling the accented color of a form control. Quick reference --------------- | Class | Properties | | --- | --- | | accent-inherit | accent-color: inherit; | | accent-current | accent-color: currentColor; | | accent-transparent | accent-color: transparent; | | accent-black | accent-color: #000; | | accent-white | accent-color: #fff; | | accent-slate-50 | accent-color: #f8fafc; | | accent-slate-100 | accent-color: #f1f5f9; | | accent-slate-200 | accent-color: #e2e8f0; | | accent-slate-300 | accent-color: #cbd5e1; | | accent-slate-400 | accent-color: #94a3b8; | | accent-slate-500 | accent-color: #64748b; | | accent-slate-600 | accent-color: #475569; | | accent-slate-700 | accent-color: #334155; | | accent-slate-800 | accent-color: #1e293b; | | accent-slate-900 | accent-color: #0f172a; | | accent-slate-950 | accent-color: #020617; | | accent-gray-50 | accent-color: #f9fafb; | | accent-gray-100 | accent-color: #f3f4f6; | | accent-gray-200 | accent-color: #e5e7eb; | | accent-gray-300 | accent-color: #d1d5db; | | accent-gray-400 | accent-color: #9ca3af; | | accent-gray-500 | accent-color: #6b7280; | | accent-gray-600 | accent-color: #4b5563; | | accent-gray-700 | accent-color: #374151; | | accent-gray-800 | accent-color: #1f2937; | | accent-gray-900 | accent-color: #111827; | | accent-gray-950 | accent-color: #030712; | | accent-zinc-50 | accent-color: #fafafa; | | accent-zinc-100 | accent-color: #f4f4f5; | | accent-zinc-200 | accent-color: #e4e4e7; | | accent-zinc-300 | accent-color: #d4d4d8; | | accent-zinc-400 | accent-color: #a1a1aa; | | accent-zinc-500 | accent-color: #71717a; | | accent-zinc-600 | accent-color: #52525b; | | accent-zinc-700 | accent-color: #3f3f46; | | accent-zinc-800 | accent-color: #27272a; | | accent-zinc-900 | accent-color: #18181b; | | accent-zinc-950 | accent-color: #09090b; | | accent-neutral-50 | accent-color: #fafafa; | | accent-neutral-100 | accent-color: #f5f5f5; | | accent-neutral-200 | accent-color: #e5e5e5; | | accent-neutral-300 | accent-color: #d4d4d4; | | accent-neutral-400 | accent-color: #a3a3a3; | | accent-neutral-500 | accent-color: #737373; | | accent-neutral-600 | accent-color: #525252; | | accent-neutral-700 | accent-color: #404040; | | accent-neutral-800 | accent-color: #262626; | | accent-neutral-900 | accent-color: #171717; | | accent-neutral-950 | accent-color: #0a0a0a; | | accent-stone-50 | accent-color: #fafaf9; | | accent-stone-100 | accent-color: #f5f5f4; | | accent-stone-200 | accent-color: #e7e5e4; | | accent-stone-300 | accent-color: #d6d3d1; | | accent-stone-400 | accent-color: #a8a29e; | | accent-stone-500 | accent-color: #78716c; | | accent-stone-600 | accent-color: #57534e; | | accent-stone-700 | accent-color: #44403c; | | accent-stone-800 | accent-color: #292524; | | accent-stone-900 | accent-color: #1c1917; | | accent-stone-950 | accent-color: #0c0a09; | | accent-red-50 | accent-color: #fef2f2; | | accent-red-100 | accent-color: #fee2e2; | | accent-red-200 | accent-color: #fecaca; | | accent-red-300 | accent-color: #fca5a5; | | accent-red-400 | accent-color: #f87171; | | accent-red-500 | accent-color: #ef4444; | | accent-red-600 | accent-color: #dc2626; | | accent-red-700 | accent-color: #b91c1c; | | accent-red-800 | accent-color: #991b1b; | | accent-red-900 | accent-color: #7f1d1d; | | accent-red-950 | accent-color: #450a0a; | | accent-orange-50 | accent-color: #fff7ed; | | accent-orange-100 | accent-color: #ffedd5; | | accent-orange-200 | accent-color: #fed7aa; | | accent-orange-300 | accent-color: #fdba74; | | accent-orange-400 | accent-color: #fb923c; | | accent-orange-500 | accent-color: #f97316; | | accent-orange-600 | accent-color: #ea580c; | | accent-orange-700 | accent-color: #c2410c; | | accent-orange-800 | accent-color: #9a3412; | | accent-orange-900 | accent-color: #7c2d12; | | accent-orange-950 | accent-color: #431407; | | accent-amber-50 | accent-color: #fffbeb; | | accent-amber-100 | accent-color: #fef3c7; | | accent-amber-200 | accent-color: #fde68a; | | accent-amber-300 | accent-color: #fcd34d; | | accent-amber-400 | accent-color: #fbbf24; | | accent-amber-500 | accent-color: #f59e0b; | | accent-amber-600 | accent-color: #d97706; | | accent-amber-700 | accent-color: #b45309; | | accent-amber-800 | accent-color: #92400e; | | accent-amber-900 | accent-color: #78350f; | | accent-amber-950 | accent-color: #451a03; | | accent-yellow-50 | accent-color: #fefce8; | | accent-yellow-100 | accent-color: #fef9c3; | | accent-yellow-200 | accent-color: #fef08a; | | accent-yellow-300 | accent-color: #fde047; | | accent-yellow-400 | accent-color: #facc15; | | accent-yellow-500 | accent-color: #eab308; | | accent-yellow-600 | accent-color: #ca8a04; | | accent-yellow-700 | accent-color: #a16207; | | accent-yellow-800 | accent-color: #854d0e; | | accent-yellow-900 | accent-color: #713f12; | | accent-yellow-950 | accent-color: #422006; | | accent-lime-50 | accent-color: #f7fee7; | | accent-lime-100 | accent-color: #ecfccb; | | accent-lime-200 | accent-color: #d9f99d; | | accent-lime-300 | accent-color: #bef264; | | accent-lime-400 | accent-color: #a3e635; | | accent-lime-500 | accent-color: #84cc16; | | accent-lime-600 | accent-color: #65a30d; | | accent-lime-700 | accent-color: #4d7c0f; | | accent-lime-800 | accent-color: #3f6212; | | accent-lime-900 | accent-color: #365314; | | accent-lime-950 | accent-color: #1a2e05; | | accent-green-50 | accent-color: #f0fdf4; | | accent-green-100 | accent-color: #dcfce7; | | accent-green-200 | accent-color: #bbf7d0; | | accent-green-300 | accent-color: #86efac; | | accent-green-400 | accent-color: #4ade80; | | accent-green-500 | accent-color: #22c55e; | | accent-green-600 | accent-color: #16a34a; | | accent-green-700 | accent-color: #15803d; | | accent-green-800 | accent-color: #166534; | | accent-green-900 | accent-color: #14532d; | | accent-green-950 | accent-color: #052e16; | | accent-emerald-50 | accent-color: #ecfdf5; | | accent-emerald-100 | accent-color: #d1fae5; | | accent-emerald-200 | accent-color: #a7f3d0; | | accent-emerald-300 | accent-color: #6ee7b7; | | accent-emerald-400 | accent-color: #34d399; | | accent-emerald-500 | accent-color: #10b981; | | accent-emerald-600 | accent-color: #059669; | | accent-emerald-700 | accent-color: #047857; | | accent-emerald-800 | accent-color: #065f46; | | accent-emerald-900 | accent-color: #064e3b; | | accent-emerald-950 | accent-color: #022c22; | | accent-teal-50 | accent-color: #f0fdfa; | | accent-teal-100 | accent-color: #ccfbf1; | | accent-teal-200 | accent-color: #99f6e4; | | accent-teal-300 | accent-color: #5eead4; | | accent-teal-400 | accent-color: #2dd4bf; | | accent-teal-500 | accent-color: #14b8a6; | | accent-teal-600 | accent-color: #0d9488; | | accent-teal-700 | accent-color: #0f766e; | | accent-teal-800 | accent-color: #115e59; | | accent-teal-900 | accent-color: #134e4a; | | accent-teal-950 | accent-color: #042f2e; | | accent-cyan-50 | accent-color: #ecfeff; | | accent-cyan-100 | accent-color: #cffafe; | | accent-cyan-200 | accent-color: #a5f3fc; | | accent-cyan-300 | accent-color: #67e8f9; | | accent-cyan-400 | accent-color: #22d3ee; | | accent-cyan-500 | accent-color: #06b6d4; | | accent-cyan-600 | accent-color: #0891b2; | | accent-cyan-700 | accent-color: #0e7490; | | accent-cyan-800 | accent-color: #155e75; | | accent-cyan-900 | accent-color: #164e63; | | accent-cyan-950 | accent-color: #083344; | | accent-sky-50 | accent-color: #f0f9ff; | | accent-sky-100 | accent-color: #e0f2fe; | | accent-sky-200 | accent-color: #bae6fd; | | accent-sky-300 | accent-color: #7dd3fc; | | accent-sky-400 | accent-color: #38bdf8; | | accent-sky-500 | accent-color: #0ea5e9; | | accent-sky-600 | accent-color: #0284c7; | | accent-sky-700 | accent-color: #0369a1; | | accent-sky-800 | accent-color: #075985; | | accent-sky-900 | accent-color: #0c4a6e; | | accent-sky-950 | accent-color: #082f49; | | accent-blue-50 | accent-color: #eff6ff; | | accent-blue-100 | accent-color: #dbeafe; | | accent-blue-200 | accent-color: #bfdbfe; | | accent-blue-300 | accent-color: #93c5fd; | | accent-blue-400 | accent-color: #60a5fa; | | accent-blue-500 | accent-color: #3b82f6; | | accent-blue-600 | accent-color: #2563eb; | | accent-blue-700 | accent-color: #1d4ed8; | | accent-blue-800 | accent-color: #1e40af; | | accent-blue-900 | accent-color: #1e3a8a; | | accent-blue-950 | accent-color: #172554; | | accent-indigo-50 | accent-color: #eef2ff; | | accent-indigo-100 | accent-color: #e0e7ff; | | accent-indigo-200 | accent-color: #c7d2fe; | | accent-indigo-300 | accent-color: #a5b4fc; | | accent-indigo-400 | accent-color: #818cf8; | | accent-indigo-500 | accent-color: #6366f1; | | accent-indigo-600 | accent-color: #4f46e5; | | accent-indigo-700 | accent-color: #4338ca; | | accent-indigo-800 | accent-color: #3730a3; | | accent-indigo-900 | accent-color: #312e81; | | accent-indigo-950 | accent-color: #1e1b4b; | | accent-violet-50 | accent-color: #f5f3ff; | | accent-violet-100 | accent-color: #ede9fe; | | accent-violet-200 | accent-color: #ddd6fe; | | accent-violet-300 | accent-color: #c4b5fd; | | accent-violet-400 | accent-color: #a78bfa; | | accent-violet-500 | accent-color: #8b5cf6; | | accent-violet-600 | accent-color: #7c3aed; | | accent-violet-700 | accent-color: #6d28d9; | | accent-violet-800 | accent-color: #5b21b6; | | accent-violet-900 | accent-color: #4c1d95; | | accent-violet-950 | accent-color: #2e1065; | | accent-purple-50 | accent-color: #faf5ff; | | accent-purple-100 | accent-color: #f3e8ff; | | accent-purple-200 | accent-color: #e9d5ff; | | accent-purple-300 | accent-color: #d8b4fe; | | accent-purple-400 | accent-color: #c084fc; | | accent-purple-500 | accent-color: #a855f7; | | accent-purple-600 | accent-color: #9333ea; | | accent-purple-700 | accent-color: #7e22ce; | | accent-purple-800 | accent-color: #6b21a8; | | accent-purple-900 | accent-color: #581c87; | | accent-purple-950 | accent-color: #3b0764; | | accent-fuchsia-50 | accent-color: #fdf4ff; | | accent-fuchsia-100 | accent-color: #fae8ff; | | accent-fuchsia-200 | accent-color: #f5d0fe; | | accent-fuchsia-300 | accent-color: #f0abfc; | | accent-fuchsia-400 | accent-color: #e879f9; | | accent-fuchsia-500 | accent-color: #d946ef; | | accent-fuchsia-600 | accent-color: #c026d3; | | accent-fuchsia-700 | accent-color: #a21caf; | | accent-fuchsia-800 | accent-color: #86198f; | | accent-fuchsia-900 | accent-color: #701a75; | | accent-fuchsia-950 | accent-color: #4a044e; | | accent-pink-50 | accent-color: #fdf2f8; | | accent-pink-100 | accent-color: #fce7f3; | | accent-pink-200 | accent-color: #fbcfe8; | | accent-pink-300 | accent-color: #f9a8d4; | | accent-pink-400 | accent-color: #f472b6; | | accent-pink-500 | accent-color: #ec4899; | | accent-pink-600 | accent-color: #db2777; | | accent-pink-700 | accent-color: #be185d; | | accent-pink-800 | accent-color: #9d174d; | | accent-pink-900 | accent-color: #831843; | | accent-pink-950 | accent-color: #500724; | | accent-rose-50 | accent-color: #fff1f2; | | accent-rose-100 | accent-color: #ffe4e6; | | accent-rose-200 | accent-color: #fecdd3; | | accent-rose-300 | accent-color: #fda4af; | | accent-rose-400 | accent-color: #fb7185; | | accent-rose-500 | accent-color: #f43f5e; | | accent-rose-600 | accent-color: #e11d48; | | accent-rose-700 | accent-color: #be123c; | | accent-rose-800 | accent-color: #9f1239; | | accent-rose-900 | accent-color: #881337; | | accent-rose-950 | accent-color: #4c0519; | | accent-auto | accent-color: auto; | Basic usage ----------- ### Setting the accent color Use the `accent-{color}` utilities to change the accent color of an element. This is helpful for styling elements like checkboxes and radio groups by overriding the browser’s default color. ``` <label> <input type="checkbox" checked> Browser default </label> <label> <input type="checkbox" class="accent-pink-500" checked> Customized </label> ``` ### Changing the opacity While it’s possible to control the opacity of the accent color using the color opacity modifier, the `rgba()` alpha value is only supported in Firefox at this time *(last tested November 2021)*. ``` <input type="checkbox" class="accent-emerald-500/25" checked> Emerald ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:accent-pink-500` to only apply the `accent-pink-500` utility on hover. ``` <input type="checkbox" class="accent-pink-300 focus:accent-pink-500" checked> ``` Note, while it’s possible to set an accent color using the `hover` and `active` modifiers, the resulting color will be slightly different than what you set, as browsers automatically adjust the brightness of the accent color for these two states. For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:accent-pink-500` to apply the `accent-pink-500` utility at only medium screen sizes and above. ``` <input type="checkbox" class="accent-pink-300 md:accent-pink-500" checked> ``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as accent colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your accent colors by editing `theme.accentColor` or `theme.extend.accentColor` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `accent-color` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <input type="checkbox" class="accent-[#50d71e]" checked> ``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/accent-colorAppearance ========== Utilities for suppressing native form control styling. Quick reference --------------- | Class | Properties | | --- | --- | | appearance-none | appearance: none; | Basic usage ----------- ### Removing default element appearance Use `appearance-none` to reset any browser specific styling on an element. This utility is often used when creating [custom form components](examples/forms). ``` <select> <option>Yes</option> <option>No</option> <option>Maybe</option> </select<select class="appearance-none"> <option>Yes</option> <option>No</option> <option>Maybe</option> </select> ``` © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/appearanceCursor ====== Utilities for controlling the cursor style when hovering over an element. Quick reference --------------- | Class | Properties | Preview | | --- | --- | --- | | cursor-auto | cursor: auto; | | | cursor-default | cursor: default; | | | cursor-pointer | cursor: pointer; | | | cursor-wait | cursor: wait; | | | cursor-text | cursor: text; | | | cursor-move | cursor: move; | | | cursor-help | cursor: help; | | | cursor-not-allowed | cursor: not-allowed; | | | cursor-none | cursor: none; | | | cursor-context-menu | cursor: context-menu; | | | cursor-progress | cursor: progress; | | | cursor-cell | cursor: cell; | | | cursor-crosshair | cursor: crosshair; | | | cursor-vertical-text | cursor: vertical-text; | | | cursor-alias | cursor: alias; | | | cursor-copy | cursor: copy; | | | cursor-no-drop | cursor: no-drop; | | | cursor-grab | cursor: grab; | | | cursor-grabbing | cursor: grabbing; | | | cursor-all-scroll | cursor: all-scroll; | | | cursor-col-resize | cursor: col-resize; | | | cursor-row-resize | cursor: row-resize; | | | cursor-n-resize | cursor: n-resize; | | | cursor-e-resize | cursor: e-resize; | | | cursor-s-resize | cursor: s-resize; | | | cursor-w-resize | cursor: w-resize; | | | cursor-ne-resize | cursor: ne-resize; | | | cursor-nw-resize | cursor: nw-resize; | | | cursor-se-resize | cursor: se-resize; | | | cursor-sw-resize | cursor: sw-resize; | | | cursor-ew-resize | cursor: ew-resize; | | | cursor-ns-resize | cursor: ns-resize; | | | cursor-nesw-resize | cursor: nesw-resize; | | | cursor-nwse-resize | cursor: nwse-resize; | | | cursor-zoom-in | cursor: zoom-in; | | | cursor-zoom-out | cursor: zoom-out; | | Basic usage ----------- ### Setting the cursor style Use the `cursor-{style}` to control which cursor is displayed when hovering over an element. ``` <button type="button" class="cursor-pointer ..."> Submit </button> <button type="button" class="cursor-progress ..."> Saving... </button> <button type="button" disabled class="cursor-not-allowed ..."> Confirm </button> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `focus:cursor-auto` to only apply the `cursor-auto` utility on focus. ``` <div class="cursor-not-allowed focus:cursor-auto"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:cursor-auto` to apply the `cursor-auto` utility at only medium screen sizes and above. ``` <div class="cursor-not-allowed md:cursor-auto"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes `cursor` utilities for many built in options. You can customize these values by editing `theme.cursor` or `theme.extend.cursor` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { cursor: { 'fancy': 'url(hand.cur), pointer', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `cursor` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="cursor-[url(hand.cur),_pointer]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/cursorCaret Color =========== Utilities for controlling the color of the text input cursor. Quick reference --------------- | Class | Properties | | --- | --- | | caret-inherit | caret-color: inherit; | | caret-current | caret-color: currentColor; | | caret-transparent | caret-color: transparent; | | caret-black | caret-color: #000; | | caret-white | caret-color: #fff; | | caret-slate-50 | caret-color: #f8fafc; | | caret-slate-100 | caret-color: #f1f5f9; | | caret-slate-200 | caret-color: #e2e8f0; | | caret-slate-300 | caret-color: #cbd5e1; | | caret-slate-400 | caret-color: #94a3b8; | | caret-slate-500 | caret-color: #64748b; | | caret-slate-600 | caret-color: #475569; | | caret-slate-700 | caret-color: #334155; | | caret-slate-800 | caret-color: #1e293b; | | caret-slate-900 | caret-color: #0f172a; | | caret-slate-950 | caret-color: #020617; | | caret-gray-50 | caret-color: #f9fafb; | | caret-gray-100 | caret-color: #f3f4f6; | | caret-gray-200 | caret-color: #e5e7eb; | | caret-gray-300 | caret-color: #d1d5db; | | caret-gray-400 | caret-color: #9ca3af; | | caret-gray-500 | caret-color: #6b7280; | | caret-gray-600 | caret-color: #4b5563; | | caret-gray-700 | caret-color: #374151; | | caret-gray-800 | caret-color: #1f2937; | | caret-gray-900 | caret-color: #111827; | | caret-gray-950 | caret-color: #030712; | | caret-zinc-50 | caret-color: #fafafa; | | caret-zinc-100 | caret-color: #f4f4f5; | | caret-zinc-200 | caret-color: #e4e4e7; | | caret-zinc-300 | caret-color: #d4d4d8; | | caret-zinc-400 | caret-color: #a1a1aa; | | caret-zinc-500 | caret-color: #71717a; | | caret-zinc-600 | caret-color: #52525b; | | caret-zinc-700 | caret-color: #3f3f46; | | caret-zinc-800 | caret-color: #27272a; | | caret-zinc-900 | caret-color: #18181b; | | caret-zinc-950 | caret-color: #09090b; | | caret-neutral-50 | caret-color: #fafafa; | | caret-neutral-100 | caret-color: #f5f5f5; | | caret-neutral-200 | caret-color: #e5e5e5; | | caret-neutral-300 | caret-color: #d4d4d4; | | caret-neutral-400 | caret-color: #a3a3a3; | | caret-neutral-500 | caret-color: #737373; | | caret-neutral-600 | caret-color: #525252; | | caret-neutral-700 | caret-color: #404040; | | caret-neutral-800 | caret-color: #262626; | | caret-neutral-900 | caret-color: #171717; | | caret-neutral-950 | caret-color: #0a0a0a; | | caret-stone-50 | caret-color: #fafaf9; | | caret-stone-100 | caret-color: #f5f5f4; | | caret-stone-200 | caret-color: #e7e5e4; | | caret-stone-300 | caret-color: #d6d3d1; | | caret-stone-400 | caret-color: #a8a29e; | | caret-stone-500 | caret-color: #78716c; | | caret-stone-600 | caret-color: #57534e; | | caret-stone-700 | caret-color: #44403c; | | caret-stone-800 | caret-color: #292524; | | caret-stone-900 | caret-color: #1c1917; | | caret-stone-950 | caret-color: #0c0a09; | | caret-red-50 | caret-color: #fef2f2; | | caret-red-100 | caret-color: #fee2e2; | | caret-red-200 | caret-color: #fecaca; | | caret-red-300 | caret-color: #fca5a5; | | caret-red-400 | caret-color: #f87171; | | caret-red-500 | caret-color: #ef4444; | | caret-red-600 | caret-color: #dc2626; | | caret-red-700 | caret-color: #b91c1c; | | caret-red-800 | caret-color: #991b1b; | | caret-red-900 | caret-color: #7f1d1d; | | caret-red-950 | caret-color: #450a0a; | | caret-orange-50 | caret-color: #fff7ed; | | caret-orange-100 | caret-color: #ffedd5; | | caret-orange-200 | caret-color: #fed7aa; | | caret-orange-300 | caret-color: #fdba74; | | caret-orange-400 | caret-color: #fb923c; | | caret-orange-500 | caret-color: #f97316; | | caret-orange-600 | caret-color: #ea580c; | | caret-orange-700 | caret-color: #c2410c; | | caret-orange-800 | caret-color: #9a3412; | | caret-orange-900 | caret-color: #7c2d12; | | caret-orange-950 | caret-color: #431407; | | caret-amber-50 | caret-color: #fffbeb; | | caret-amber-100 | caret-color: #fef3c7; | | caret-amber-200 | caret-color: #fde68a; | | caret-amber-300 | caret-color: #fcd34d; | | caret-amber-400 | caret-color: #fbbf24; | | caret-amber-500 | caret-color: #f59e0b; | | caret-amber-600 | caret-color: #d97706; | | caret-amber-700 | caret-color: #b45309; | | caret-amber-800 | caret-color: #92400e; | | caret-amber-900 | caret-color: #78350f; | | caret-amber-950 | caret-color: #451a03; | | caret-yellow-50 | caret-color: #fefce8; | | caret-yellow-100 | caret-color: #fef9c3; | | caret-yellow-200 | caret-color: #fef08a; | | caret-yellow-300 | caret-color: #fde047; | | caret-yellow-400 | caret-color: #facc15; | | caret-yellow-500 | caret-color: #eab308; | | caret-yellow-600 | caret-color: #ca8a04; | | caret-yellow-700 | caret-color: #a16207; | | caret-yellow-800 | caret-color: #854d0e; | | caret-yellow-900 | caret-color: #713f12; | | caret-yellow-950 | caret-color: #422006; | | caret-lime-50 | caret-color: #f7fee7; | | caret-lime-100 | caret-color: #ecfccb; | | caret-lime-200 | caret-color: #d9f99d; | | caret-lime-300 | caret-color: #bef264; | | caret-lime-400 | caret-color: #a3e635; | | caret-lime-500 | caret-color: #84cc16; | | caret-lime-600 | caret-color: #65a30d; | | caret-lime-700 | caret-color: #4d7c0f; | | caret-lime-800 | caret-color: #3f6212; | | caret-lime-900 | caret-color: #365314; | | caret-lime-950 | caret-color: #1a2e05; | | caret-green-50 | caret-color: #f0fdf4; | | caret-green-100 | caret-color: #dcfce7; | | caret-green-200 | caret-color: #bbf7d0; | | caret-green-300 | caret-color: #86efac; | | caret-green-400 | caret-color: #4ade80; | | caret-green-500 | caret-color: #22c55e; | | caret-green-600 | caret-color: #16a34a; | | caret-green-700 | caret-color: #15803d; | | caret-green-800 | caret-color: #166534; | | caret-green-900 | caret-color: #14532d; | | caret-green-950 | caret-color: #052e16; | | caret-emerald-50 | caret-color: #ecfdf5; | | caret-emerald-100 | caret-color: #d1fae5; | | caret-emerald-200 | caret-color: #a7f3d0; | | caret-emerald-300 | caret-color: #6ee7b7; | | caret-emerald-400 | caret-color: #34d399; | | caret-emerald-500 | caret-color: #10b981; | | caret-emerald-600 | caret-color: #059669; | | caret-emerald-700 | caret-color: #047857; | | caret-emerald-800 | caret-color: #065f46; | | caret-emerald-900 | caret-color: #064e3b; | | caret-emerald-950 | caret-color: #022c22; | | caret-teal-50 | caret-color: #f0fdfa; | | caret-teal-100 | caret-color: #ccfbf1; | | caret-teal-200 | caret-color: #99f6e4; | | caret-teal-300 | caret-color: #5eead4; | | caret-teal-400 | caret-color: #2dd4bf; | | caret-teal-500 | caret-color: #14b8a6; | | caret-teal-600 | caret-color: #0d9488; | | caret-teal-700 | caret-color: #0f766e; | | caret-teal-800 | caret-color: #115e59; | | caret-teal-900 | caret-color: #134e4a; | | caret-teal-950 | caret-color: #042f2e; | | caret-cyan-50 | caret-color: #ecfeff; | | caret-cyan-100 | caret-color: #cffafe; | | caret-cyan-200 | caret-color: #a5f3fc; | | caret-cyan-300 | caret-color: #67e8f9; | | caret-cyan-400 | caret-color: #22d3ee; | | caret-cyan-500 | caret-color: #06b6d4; | | caret-cyan-600 | caret-color: #0891b2; | | caret-cyan-700 | caret-color: #0e7490; | | caret-cyan-800 | caret-color: #155e75; | | caret-cyan-900 | caret-color: #164e63; | | caret-cyan-950 | caret-color: #083344; | | caret-sky-50 | caret-color: #f0f9ff; | | caret-sky-100 | caret-color: #e0f2fe; | | caret-sky-200 | caret-color: #bae6fd; | | caret-sky-300 | caret-color: #7dd3fc; | | caret-sky-400 | caret-color: #38bdf8; | | caret-sky-500 | caret-color: #0ea5e9; | | caret-sky-600 | caret-color: #0284c7; | | caret-sky-700 | caret-color: #0369a1; | | caret-sky-800 | caret-color: #075985; | | caret-sky-900 | caret-color: #0c4a6e; | | caret-sky-950 | caret-color: #082f49; | | caret-blue-50 | caret-color: #eff6ff; | | caret-blue-100 | caret-color: #dbeafe; | | caret-blue-200 | caret-color: #bfdbfe; | | caret-blue-300 | caret-color: #93c5fd; | | caret-blue-400 | caret-color: #60a5fa; | | caret-blue-500 | caret-color: #3b82f6; | | caret-blue-600 | caret-color: #2563eb; | | caret-blue-700 | caret-color: #1d4ed8; | | caret-blue-800 | caret-color: #1e40af; | | caret-blue-900 | caret-color: #1e3a8a; | | caret-blue-950 | caret-color: #172554; | | caret-indigo-50 | caret-color: #eef2ff; | | caret-indigo-100 | caret-color: #e0e7ff; | | caret-indigo-200 | caret-color: #c7d2fe; | | caret-indigo-300 | caret-color: #a5b4fc; | | caret-indigo-400 | caret-color: #818cf8; | | caret-indigo-500 | caret-color: #6366f1; | | caret-indigo-600 | caret-color: #4f46e5; | | caret-indigo-700 | caret-color: #4338ca; | | caret-indigo-800 | caret-color: #3730a3; | | caret-indigo-900 | caret-color: #312e81; | | caret-indigo-950 | caret-color: #1e1b4b; | | caret-violet-50 | caret-color: #f5f3ff; | | caret-violet-100 | caret-color: #ede9fe; | | caret-violet-200 | caret-color: #ddd6fe; | | caret-violet-300 | caret-color: #c4b5fd; | | caret-violet-400 | caret-color: #a78bfa; | | caret-violet-500 | caret-color: #8b5cf6; | | caret-violet-600 | caret-color: #7c3aed; | | caret-violet-700 | caret-color: #6d28d9; | | caret-violet-800 | caret-color: #5b21b6; | | caret-violet-900 | caret-color: #4c1d95; | | caret-violet-950 | caret-color: #2e1065; | | caret-purple-50 | caret-color: #faf5ff; | | caret-purple-100 | caret-color: #f3e8ff; | | caret-purple-200 | caret-color: #e9d5ff; | | caret-purple-300 | caret-color: #d8b4fe; | | caret-purple-400 | caret-color: #c084fc; | | caret-purple-500 | caret-color: #a855f7; | | caret-purple-600 | caret-color: #9333ea; | | caret-purple-700 | caret-color: #7e22ce; | | caret-purple-800 | caret-color: #6b21a8; | | caret-purple-900 | caret-color: #581c87; | | caret-purple-950 | caret-color: #3b0764; | | caret-fuchsia-50 | caret-color: #fdf4ff; | | caret-fuchsia-100 | caret-color: #fae8ff; | | caret-fuchsia-200 | caret-color: #f5d0fe; | | caret-fuchsia-300 | caret-color: #f0abfc; | | caret-fuchsia-400 | caret-color: #e879f9; | | caret-fuchsia-500 | caret-color: #d946ef; | | caret-fuchsia-600 | caret-color: #c026d3; | | caret-fuchsia-700 | caret-color: #a21caf; | | caret-fuchsia-800 | caret-color: #86198f; | | caret-fuchsia-900 | caret-color: #701a75; | | caret-fuchsia-950 | caret-color: #4a044e; | | caret-pink-50 | caret-color: #fdf2f8; | | caret-pink-100 | caret-color: #fce7f3; | | caret-pink-200 | caret-color: #fbcfe8; | | caret-pink-300 | caret-color: #f9a8d4; | | caret-pink-400 | caret-color: #f472b6; | | caret-pink-500 | caret-color: #ec4899; | | caret-pink-600 | caret-color: #db2777; | | caret-pink-700 | caret-color: #be185d; | | caret-pink-800 | caret-color: #9d174d; | | caret-pink-900 | caret-color: #831843; | | caret-pink-950 | caret-color: #500724; | | caret-rose-50 | caret-color: #fff1f2; | | caret-rose-100 | caret-color: #ffe4e6; | | caret-rose-200 | caret-color: #fecdd3; | | caret-rose-300 | caret-color: #fda4af; | | caret-rose-400 | caret-color: #fb7185; | | caret-rose-500 | caret-color: #f43f5e; | | caret-rose-600 | caret-color: #e11d48; | | caret-rose-700 | caret-color: #be123c; | | caret-rose-800 | caret-color: #9f1239; | | caret-rose-900 | caret-color: #881337; | | caret-rose-950 | caret-color: #4c0519; | Basic usage ----------- ### Setting the caret color Use the `caret-{color}` utilities to change the color of the text input cursor. ``` <textarea class="caret-pink-500 ..."></textarea> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `focus:caret-indigo-500` to only apply the `caret-indigo-500` utility on focus. ``` <textarea class="caret-blue-500 focus:caret-indigo-500"></textarea> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:caret-indigo-500` to apply the `caret-indigo-500` utility at only medium screen sizes and above. ``` <textarea class="caret-blue-500 md:caret-indigo-500"></textarea> ``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as caret colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your caret colors by editing `theme.caretColor` or `theme.extend.caretColor` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `caret-color` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <textarea class="caret-[#50d71e]"></textarea> ``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/caret-colorPointer Events ============== Utilities for controlling whether an element responds to pointer events. Quick reference --------------- | Class | Properties | | --- | --- | | pointer-events-none | pointer-events: none; | | pointer-events-auto | pointer-events: auto; | Basic usage ----------- ### Controlling pointer event behavior Use `pointer-events-auto` to revert to the default browser behavior for pointer events (like `:hover` and `click`). Use `pointer-events-none` to make an element ignore pointer events. The pointer events will still trigger on child elements and pass-through to elements that are “beneath” the target. ``` <div class="relative ..."> <div class="absolute pointer-events-auto ..."> <svg class="absolute text-slate-400 h-5 w-5" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" /> </svg> </div> <input type="text" placeholder="Search" class="..."> </div<div class="relative ..."> <div class="absolute pointer-events-none ..."> <svg class="absolute text-slate-400 h-5 w-5" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" /> </svg> </div> <input type="text" placeholder="Search" class="..."> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `focus:pointer-events-auto` to only apply the `pointer-events-auto` utility on focus. ``` <div class="pointer-events-none focus:pointer-events-auto"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:pointer-events-auto` to apply the `pointer-events-auto` utility at only medium screen sizes and above. ``` <div class="pointer-events-none md:pointer-events-auto"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/pointer-eventsResize ====== Utilities for controlling how an element can be resized. Quick reference --------------- | Class | Properties | | --- | --- | | resize-none | resize: none; | | resize-y | resize: vertical; | | resize-x | resize: horizontal; | | resize | resize: both; | Basic usage ----------- ### Resizing in all directions Use `resize` to make an element horizontally and vertically resizable. ``` <textarea class="resize rounded-md"></textarea> ``` ### Resizing vertically Use `resize-y` to make an element vertically resizable. ``` <textarea class="resize-y rounded-md"></textarea> ``` ### Resizing horizontally Use `resize-x` to make an element horizontally resizable. ``` <textarea class="resize-x rounded-md"></textarea> ``` ### Preventing resizing Use `resize-none` to prevent an element from being resizable. ``` <textarea class="resize-none rounded-md"></textarea> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:resize` to only apply the `resize` utility on hover. ``` <div class="resize-none hover:resize"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:resize` to apply the `resize` utility at only medium screen sizes and above. ``` <div class="resize-none md:resize"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/resizeScroll Behavior =============== Utilities for controlling the scroll behavior of an element. Quick reference --------------- | Class | Properties | | --- | --- | | scroll-auto | scroll-behavior: auto; | | scroll-smooth | scroll-behavior: smooth; | Basic usage ----------- ### Adding smooth scrolling Use the `scroll-smooth` utilities to enable smooth scrolling within an element. ``` <html class="scroll-smooth"> <!-- ... --> </html> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:scroll-auto` to only apply the `scroll-auto` utility on hover. ``` <html class="scroll-smooth hover:scroll-auto"> <!-- ... --> </html``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:scroll-auto` to apply the `scroll-auto` utility at only medium screen sizes and above. ``` <html class="scroll-smooth md:scroll-auto"> <!-- ... --> </html``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/scroll-behaviorScroll Margin ============= Utilities for controlling the scroll offset around items in a snap container. Quick reference --------------- | Class | Properties | | --- | --- | | scroll-m-0 | scroll-margin: 0px; | | scroll-mx-0 | scroll-margin-left: 0px; scroll-margin-right: 0px; | | scroll-my-0 | scroll-margin-top: 0px; scroll-margin-bottom: 0px; | | scroll-ms-0 | scroll-margin-inline-start: 0px; | | scroll-me-0 | scroll-margin-inline-end: 0px; | | scroll-mt-0 | scroll-margin-top: 0px; | | scroll-mr-0 | scroll-margin-right: 0px; | | scroll-mb-0 | scroll-margin-bottom: 0px; | | scroll-ml-0 | scroll-margin-left: 0px; | | scroll-m-px | scroll-margin: 1px; | | scroll-mx-px | scroll-margin-left: 1px; scroll-margin-right: 1px; | | scroll-my-px | scroll-margin-top: 1px; scroll-margin-bottom: 1px; | | scroll-ms-px | scroll-margin-inline-start: 1px; | | scroll-me-px | scroll-margin-inline-end: 1px; | | scroll-mt-px | scroll-margin-top: 1px; | | scroll-mr-px | scroll-margin-right: 1px; | | scroll-mb-px | scroll-margin-bottom: 1px; | | scroll-ml-px | scroll-margin-left: 1px; | | scroll-m-0.5 | scroll-margin: 0.125rem; /* 2px */ | | scroll-mx-0.5 | scroll-margin-left: 0.125rem; /* 2px */ scroll-margin-right: 0.125rem; /* 2px */ | | scroll-my-0.5 | scroll-margin-top: 0.125rem; /* 2px */ scroll-margin-bottom: 0.125rem; /* 2px */ | | scroll-ms-0.5 | scroll-margin-inline-start: 0.125rem; /* 2px */ | | scroll-me-0.5 | scroll-margin-inline-end: 0.125rem; /* 2px */ | | scroll-mt-0.5 | scroll-margin-top: 0.125rem; /* 2px */ | | scroll-mr-0.5 | scroll-margin-right: 0.125rem; /* 2px */ | | scroll-mb-0.5 | scroll-margin-bottom: 0.125rem; /* 2px */ | | scroll-ml-0.5 | scroll-margin-left: 0.125rem; /* 2px */ | | scroll-m-1 | scroll-margin: 0.25rem; /* 4px */ | | scroll-mx-1 | scroll-margin-left: 0.25rem; /* 4px */ scroll-margin-right: 0.25rem; /* 4px */ | | scroll-my-1 | scroll-margin-top: 0.25rem; /* 4px */ scroll-margin-bottom: 0.25rem; /* 4px */ | | scroll-ms-1 | scroll-margin-inline-start: 0.25rem; /* 4px */ | | scroll-me-1 | scroll-margin-inline-end: 0.25rem; /* 4px */ | | scroll-mt-1 | scroll-margin-top: 0.25rem; /* 4px */ | | scroll-mr-1 | scroll-margin-right: 0.25rem; /* 4px */ | | scroll-mb-1 | scroll-margin-bottom: 0.25rem; /* 4px */ | | scroll-ml-1 | scroll-margin-left: 0.25rem; /* 4px */ | | scroll-m-1.5 | scroll-margin: 0.375rem; /* 6px */ | | scroll-mx-1.5 | scroll-margin-left: 0.375rem; /* 6px */ scroll-margin-right: 0.375rem; /* 6px */ | | scroll-my-1.5 | scroll-margin-top: 0.375rem; /* 6px */ scroll-margin-bottom: 0.375rem; /* 6px */ | | scroll-ms-1.5 | scroll-margin-inline-start: 0.375rem; /* 6px */ | | scroll-me-1.5 | scroll-margin-inline-end: 0.375rem; /* 6px */ | | scroll-mt-1.5 | scroll-margin-top: 0.375rem; /* 6px */ | | scroll-mr-1.5 | scroll-margin-right: 0.375rem; /* 6px */ | | scroll-mb-1.5 | scroll-margin-bottom: 0.375rem; /* 6px */ | | scroll-ml-1.5 | scroll-margin-left: 0.375rem; /* 6px */ | | scroll-m-2 | scroll-margin: 0.5rem; /* 8px */ | | scroll-mx-2 | scroll-margin-left: 0.5rem; /* 8px */ scroll-margin-right: 0.5rem; /* 8px */ | | scroll-my-2 | scroll-margin-top: 0.5rem; /* 8px */ scroll-margin-bottom: 0.5rem; /* 8px */ | | scroll-ms-2 | scroll-margin-inline-start: 0.5rem; /* 8px */ | | scroll-me-2 | scroll-margin-inline-end: 0.5rem; /* 8px */ | | scroll-mt-2 | scroll-margin-top: 0.5rem; /* 8px */ | | scroll-mr-2 | scroll-margin-right: 0.5rem; /* 8px */ | | scroll-mb-2 | scroll-margin-bottom: 0.5rem; /* 8px */ | | scroll-ml-2 | scroll-margin-left: 0.5rem; /* 8px */ | | scroll-m-2.5 | scroll-margin: 0.625rem; /* 10px */ | | scroll-mx-2.5 | scroll-margin-left: 0.625rem; /* 10px */ scroll-margin-right: 0.625rem; /* 10px */ | | scroll-my-2.5 | scroll-margin-top: 0.625rem; /* 10px */ scroll-margin-bottom: 0.625rem; /* 10px */ | | scroll-ms-2.5 | scroll-margin-inline-start: 0.625rem; /* 10px */ | | scroll-me-2.5 | scroll-margin-inline-end: 0.625rem; /* 10px */ | | scroll-mt-2.5 | scroll-margin-top: 0.625rem; /* 10px */ | | scroll-mr-2.5 | scroll-margin-right: 0.625rem; /* 10px */ | | scroll-mb-2.5 | scroll-margin-bottom: 0.625rem; /* 10px */ | | scroll-ml-2.5 | scroll-margin-left: 0.625rem; /* 10px */ | | scroll-m-3 | scroll-margin: 0.75rem; /* 12px */ | | scroll-mx-3 | scroll-margin-left: 0.75rem; /* 12px */ scroll-margin-right: 0.75rem; /* 12px */ | | scroll-my-3 | scroll-margin-top: 0.75rem; /* 12px */ scroll-margin-bottom: 0.75rem; /* 12px */ | | scroll-ms-3 | scroll-margin-inline-start: 0.75rem; /* 12px */ | | scroll-me-3 | scroll-margin-inline-end: 0.75rem; /* 12px */ | | scroll-mt-3 | scroll-margin-top: 0.75rem; /* 12px */ | | scroll-mr-3 | scroll-margin-right: 0.75rem; /* 12px */ | | scroll-mb-3 | scroll-margin-bottom: 0.75rem; /* 12px */ | | scroll-ml-3 | scroll-margin-left: 0.75rem; /* 12px */ | | scroll-m-3.5 | scroll-margin: 0.875rem; /* 14px */ | | scroll-mx-3.5 | scroll-margin-left: 0.875rem; /* 14px */ scroll-margin-right: 0.875rem; /* 14px */ | | scroll-my-3.5 | scroll-margin-top: 0.875rem; /* 14px */ scroll-margin-bottom: 0.875rem; /* 14px */ | | scroll-ms-3.5 | scroll-margin-inline-start: 0.875rem; /* 14px */ | | scroll-me-3.5 | scroll-margin-inline-end: 0.875rem; /* 14px */ | | scroll-mt-3.5 | scroll-margin-top: 0.875rem; /* 14px */ | | scroll-mr-3.5 | scroll-margin-right: 0.875rem; /* 14px */ | | scroll-mb-3.5 | scroll-margin-bottom: 0.875rem; /* 14px */ | | scroll-ml-3.5 | scroll-margin-left: 0.875rem; /* 14px */ | | scroll-m-4 | scroll-margin: 1rem; /* 16px */ | | scroll-mx-4 | scroll-margin-left: 1rem; /* 16px */ scroll-margin-right: 1rem; /* 16px */ | | scroll-my-4 | scroll-margin-top: 1rem; /* 16px */ scroll-margin-bottom: 1rem; /* 16px */ | | scroll-ms-4 | scroll-margin-inline-start: 1rem; /* 16px */ | | scroll-me-4 | scroll-margin-inline-end: 1rem; /* 16px */ | | scroll-mt-4 | scroll-margin-top: 1rem; /* 16px */ | | scroll-mr-4 | scroll-margin-right: 1rem; /* 16px */ | | scroll-mb-4 | scroll-margin-bottom: 1rem; /* 16px */ | | scroll-ml-4 | scroll-margin-left: 1rem; /* 16px */ | | scroll-m-5 | scroll-margin: 1.25rem; /* 20px */ | | scroll-mx-5 | scroll-margin-left: 1.25rem; /* 20px */ scroll-margin-right: 1.25rem; /* 20px */ | | scroll-my-5 | scroll-margin-top: 1.25rem; /* 20px */ scroll-margin-bottom: 1.25rem; /* 20px */ | | scroll-ms-5 | scroll-margin-inline-start: 1.25rem; /* 20px */ | | scroll-me-5 | scroll-margin-inline-end: 1.25rem; /* 20px */ | | scroll-mt-5 | scroll-margin-top: 1.25rem; /* 20px */ | | scroll-mr-5 | scroll-margin-right: 1.25rem; /* 20px */ | | scroll-mb-5 | scroll-margin-bottom: 1.25rem; /* 20px */ | | scroll-ml-5 | scroll-margin-left: 1.25rem; /* 20px */ | | scroll-m-6 | scroll-margin: 1.5rem; /* 24px */ | | scroll-mx-6 | scroll-margin-left: 1.5rem; /* 24px */ scroll-margin-right: 1.5rem; /* 24px */ | | scroll-my-6 | scroll-margin-top: 1.5rem; /* 24px */ scroll-margin-bottom: 1.5rem; /* 24px */ | | scroll-ms-6 | scroll-margin-inline-start: 1.5rem; /* 24px */ | | scroll-me-6 | scroll-margin-inline-end: 1.5rem; /* 24px */ | | scroll-mt-6 | scroll-margin-top: 1.5rem; /* 24px */ | | scroll-mr-6 | scroll-margin-right: 1.5rem; /* 24px */ | | scroll-mb-6 | scroll-margin-bottom: 1.5rem; /* 24px */ | | scroll-ml-6 | scroll-margin-left: 1.5rem; /* 24px */ | | scroll-m-7 | scroll-margin: 1.75rem; /* 28px */ | | scroll-mx-7 | scroll-margin-left: 1.75rem; /* 28px */ scroll-margin-right: 1.75rem; /* 28px */ | | scroll-my-7 | scroll-margin-top: 1.75rem; /* 28px */ scroll-margin-bottom: 1.75rem; /* 28px */ | | scroll-ms-7 | scroll-margin-inline-start: 1.75rem; /* 28px */ | | scroll-me-7 | scroll-margin-inline-end: 1.75rem; /* 28px */ | | scroll-mt-7 | scroll-margin-top: 1.75rem; /* 28px */ | | scroll-mr-7 | scroll-margin-right: 1.75rem; /* 28px */ | | scroll-mb-7 | scroll-margin-bottom: 1.75rem; /* 28px */ | | scroll-ml-7 | scroll-margin-left: 1.75rem; /* 28px */ | | scroll-m-8 | scroll-margin: 2rem; /* 32px */ | | scroll-mx-8 | scroll-margin-left: 2rem; /* 32px */ scroll-margin-right: 2rem; /* 32px */ | | scroll-my-8 | scroll-margin-top: 2rem; /* 32px */ scroll-margin-bottom: 2rem; /* 32px */ | | scroll-ms-8 | scroll-margin-inline-start: 2rem; /* 32px */ | | scroll-me-8 | scroll-margin-inline-end: 2rem; /* 32px */ | | scroll-mt-8 | scroll-margin-top: 2rem; /* 32px */ | | scroll-mr-8 | scroll-margin-right: 2rem; /* 32px */ | | scroll-mb-8 | scroll-margin-bottom: 2rem; /* 32px */ | | scroll-ml-8 | scroll-margin-left: 2rem; /* 32px */ | | scroll-m-9 | scroll-margin: 2.25rem; /* 36px */ | | scroll-mx-9 | scroll-margin-left: 2.25rem; /* 36px */ scroll-margin-right: 2.25rem; /* 36px */ | | scroll-my-9 | scroll-margin-top: 2.25rem; /* 36px */ scroll-margin-bottom: 2.25rem; /* 36px */ | | scroll-ms-9 | scroll-margin-inline-start: 2.25rem; /* 36px */ | | scroll-me-9 | scroll-margin-inline-end: 2.25rem; /* 36px */ | | scroll-mt-9 | scroll-margin-top: 2.25rem; /* 36px */ | | scroll-mr-9 | scroll-margin-right: 2.25rem; /* 36px */ | | scroll-mb-9 | scroll-margin-bottom: 2.25rem; /* 36px */ | | scroll-ml-9 | scroll-margin-left: 2.25rem; /* 36px */ | | scroll-m-10 | scroll-margin: 2.5rem; /* 40px */ | | scroll-mx-10 | scroll-margin-left: 2.5rem; /* 40px */ scroll-margin-right: 2.5rem; /* 40px */ | | scroll-my-10 | scroll-margin-top: 2.5rem; /* 40px */ scroll-margin-bottom: 2.5rem; /* 40px */ | | scroll-ms-10 | scroll-margin-inline-start: 2.5rem; /* 40px */ | | scroll-me-10 | scroll-margin-inline-end: 2.5rem; /* 40px */ | | scroll-mt-10 | scroll-margin-top: 2.5rem; /* 40px */ | | scroll-mr-10 | scroll-margin-right: 2.5rem; /* 40px */ | | scroll-mb-10 | scroll-margin-bottom: 2.5rem; /* 40px */ | | scroll-ml-10 | scroll-margin-left: 2.5rem; /* 40px */ | | scroll-m-11 | scroll-margin: 2.75rem; /* 44px */ | | scroll-mx-11 | scroll-margin-left: 2.75rem; /* 44px */ scroll-margin-right: 2.75rem; /* 44px */ | | scroll-my-11 | scroll-margin-top: 2.75rem; /* 44px */ scroll-margin-bottom: 2.75rem; /* 44px */ | | scroll-ms-11 | scroll-margin-inline-start: 2.75rem; /* 44px */ | | scroll-me-11 | scroll-margin-inline-end: 2.75rem; /* 44px */ | | scroll-mt-11 | scroll-margin-top: 2.75rem; /* 44px */ | | scroll-mr-11 | scroll-margin-right: 2.75rem; /* 44px */ | | scroll-mb-11 | scroll-margin-bottom: 2.75rem; /* 44px */ | | scroll-ml-11 | scroll-margin-left: 2.75rem; /* 44px */ | | scroll-m-12 | scroll-margin: 3rem; /* 48px */ | | scroll-mx-12 | scroll-margin-left: 3rem; /* 48px */ scroll-margin-right: 3rem; /* 48px */ | | scroll-my-12 | scroll-margin-top: 3rem; /* 48px */ scroll-margin-bottom: 3rem; /* 48px */ | | scroll-ms-12 | scroll-margin-inline-start: 3rem; /* 48px */ | | scroll-me-12 | scroll-margin-inline-end: 3rem; /* 48px */ | | scroll-mt-12 | scroll-margin-top: 3rem; /* 48px */ | | scroll-mr-12 | scroll-margin-right: 3rem; /* 48px */ | | scroll-mb-12 | scroll-margin-bottom: 3rem; /* 48px */ | | scroll-ml-12 | scroll-margin-left: 3rem; /* 48px */ | | scroll-m-14 | scroll-margin: 3.5rem; /* 56px */ | | scroll-mx-14 | scroll-margin-left: 3.5rem; /* 56px */ scroll-margin-right: 3.5rem; /* 56px */ | | scroll-my-14 | scroll-margin-top: 3.5rem; /* 56px */ scroll-margin-bottom: 3.5rem; /* 56px */ | | scroll-ms-14 | scroll-margin-inline-start: 3.5rem; /* 56px */ | | scroll-me-14 | scroll-margin-inline-end: 3.5rem; /* 56px */ | | scroll-mt-14 | scroll-margin-top: 3.5rem; /* 56px */ | | scroll-mr-14 | scroll-margin-right: 3.5rem; /* 56px */ | | scroll-mb-14 | scroll-margin-bottom: 3.5rem; /* 56px */ | | scroll-ml-14 | scroll-margin-left: 3.5rem; /* 56px */ | | scroll-m-16 | scroll-margin: 4rem; /* 64px */ | | scroll-mx-16 | scroll-margin-left: 4rem; /* 64px */ scroll-margin-right: 4rem; /* 64px */ | | scroll-my-16 | scroll-margin-top: 4rem; /* 64px */ scroll-margin-bottom: 4rem; /* 64px */ | | scroll-ms-16 | scroll-margin-inline-start: 4rem; /* 64px */ | | scroll-me-16 | scroll-margin-inline-end: 4rem; /* 64px */ | | scroll-mt-16 | scroll-margin-top: 4rem; /* 64px */ | | scroll-mr-16 | scroll-margin-right: 4rem; /* 64px */ | | scroll-mb-16 | scroll-margin-bottom: 4rem; /* 64px */ | | scroll-ml-16 | scroll-margin-left: 4rem; /* 64px */ | | scroll-m-20 | scroll-margin: 5rem; /* 80px */ | | scroll-mx-20 | scroll-margin-left: 5rem; /* 80px */ scroll-margin-right: 5rem; /* 80px */ | | scroll-my-20 | scroll-margin-top: 5rem; /* 80px */ scroll-margin-bottom: 5rem; /* 80px */ | | scroll-ms-20 | scroll-margin-inline-start: 5rem; /* 80px */ | | scroll-me-20 | scroll-margin-inline-end: 5rem; /* 80px */ | | scroll-mt-20 | scroll-margin-top: 5rem; /* 80px */ | | scroll-mr-20 | scroll-margin-right: 5rem; /* 80px */ | | scroll-mb-20 | scroll-margin-bottom: 5rem; /* 80px */ | | scroll-ml-20 | scroll-margin-left: 5rem; /* 80px */ | | scroll-m-24 | scroll-margin: 6rem; /* 96px */ | | scroll-mx-24 | scroll-margin-left: 6rem; /* 96px */ scroll-margin-right: 6rem; /* 96px */ | | scroll-my-24 | scroll-margin-top: 6rem; /* 96px */ scroll-margin-bottom: 6rem; /* 96px */ | | scroll-ms-24 | scroll-margin-inline-start: 6rem; /* 96px */ | | scroll-me-24 | scroll-margin-inline-end: 6rem; /* 96px */ | | scroll-mt-24 | scroll-margin-top: 6rem; /* 96px */ | | scroll-mr-24 | scroll-margin-right: 6rem; /* 96px */ | | scroll-mb-24 | scroll-margin-bottom: 6rem; /* 96px */ | | scroll-ml-24 | scroll-margin-left: 6rem; /* 96px */ | | scroll-m-28 | scroll-margin: 7rem; /* 112px */ | | scroll-mx-28 | scroll-margin-left: 7rem; /* 112px */ scroll-margin-right: 7rem; /* 112px */ | | scroll-my-28 | scroll-margin-top: 7rem; /* 112px */ scroll-margin-bottom: 7rem; /* 112px */ | | scroll-ms-28 | scroll-margin-inline-start: 7rem; /* 112px */ | | scroll-me-28 | scroll-margin-inline-end: 7rem; /* 112px */ | | scroll-mt-28 | scroll-margin-top: 7rem; /* 112px */ | | scroll-mr-28 | scroll-margin-right: 7rem; /* 112px */ | | scroll-mb-28 | scroll-margin-bottom: 7rem; /* 112px */ | | scroll-ml-28 | scroll-margin-left: 7rem; /* 112px */ | | scroll-m-32 | scroll-margin: 8rem; /* 128px */ | | scroll-mx-32 | scroll-margin-left: 8rem; /* 128px */ scroll-margin-right: 8rem; /* 128px */ | | scroll-my-32 | scroll-margin-top: 8rem; /* 128px */ scroll-margin-bottom: 8rem; /* 128px */ | | scroll-ms-32 | scroll-margin-inline-start: 8rem; /* 128px */ | | scroll-me-32 | scroll-margin-inline-end: 8rem; /* 128px */ | | scroll-mt-32 | scroll-margin-top: 8rem; /* 128px */ | | scroll-mr-32 | scroll-margin-right: 8rem; /* 128px */ | | scroll-mb-32 | scroll-margin-bottom: 8rem; /* 128px */ | | scroll-ml-32 | scroll-margin-left: 8rem; /* 128px */ | | scroll-m-36 | scroll-margin: 9rem; /* 144px */ | | scroll-mx-36 | scroll-margin-left: 9rem; /* 144px */ scroll-margin-right: 9rem; /* 144px */ | | scroll-my-36 | scroll-margin-top: 9rem; /* 144px */ scroll-margin-bottom: 9rem; /* 144px */ | | scroll-ms-36 | scroll-margin-inline-start: 9rem; /* 144px */ | | scroll-me-36 | scroll-margin-inline-end: 9rem; /* 144px */ | | scroll-mt-36 | scroll-margin-top: 9rem; /* 144px */ | | scroll-mr-36 | scroll-margin-right: 9rem; /* 144px */ | | scroll-mb-36 | scroll-margin-bottom: 9rem; /* 144px */ | | scroll-ml-36 | scroll-margin-left: 9rem; /* 144px */ | | scroll-m-40 | scroll-margin: 10rem; /* 160px */ | | scroll-mx-40 | scroll-margin-left: 10rem; /* 160px */ scroll-margin-right: 10rem; /* 160px */ | | scroll-my-40 | scroll-margin-top: 10rem; /* 160px */ scroll-margin-bottom: 10rem; /* 160px */ | | scroll-ms-40 | scroll-margin-inline-start: 10rem; /* 160px */ | | scroll-me-40 | scroll-margin-inline-end: 10rem; /* 160px */ | | scroll-mt-40 | scroll-margin-top: 10rem; /* 160px */ | | scroll-mr-40 | scroll-margin-right: 10rem; /* 160px */ | | scroll-mb-40 | scroll-margin-bottom: 10rem; /* 160px */ | | scroll-ml-40 | scroll-margin-left: 10rem; /* 160px */ | | scroll-m-44 | scroll-margin: 11rem; /* 176px */ | | scroll-mx-44 | scroll-margin-left: 11rem; /* 176px */ scroll-margin-right: 11rem; /* 176px */ | | scroll-my-44 | scroll-margin-top: 11rem; /* 176px */ scroll-margin-bottom: 11rem; /* 176px */ | | scroll-ms-44 | scroll-margin-inline-start: 11rem; /* 176px */ | | scroll-me-44 | scroll-margin-inline-end: 11rem; /* 176px */ | | scroll-mt-44 | scroll-margin-top: 11rem; /* 176px */ | | scroll-mr-44 | scroll-margin-right: 11rem; /* 176px */ | | scroll-mb-44 | scroll-margin-bottom: 11rem; /* 176px */ | | scroll-ml-44 | scroll-margin-left: 11rem; /* 176px */ | | scroll-m-48 | scroll-margin: 12rem; /* 192px */ | | scroll-mx-48 | scroll-margin-left: 12rem; /* 192px */ scroll-margin-right: 12rem; /* 192px */ | | scroll-my-48 | scroll-margin-top: 12rem; /* 192px */ scroll-margin-bottom: 12rem; /* 192px */ | | scroll-ms-48 | scroll-margin-inline-start: 12rem; /* 192px */ | | scroll-me-48 | scroll-margin-inline-end: 12rem; /* 192px */ | | scroll-mt-48 | scroll-margin-top: 12rem; /* 192px */ | | scroll-mr-48 | scroll-margin-right: 12rem; /* 192px */ | | scroll-mb-48 | scroll-margin-bottom: 12rem; /* 192px */ | | scroll-ml-48 | scroll-margin-left: 12rem; /* 192px */ | | scroll-m-52 | scroll-margin: 13rem; /* 208px */ | | scroll-mx-52 | scroll-margin-left: 13rem; /* 208px */ scroll-margin-right: 13rem; /* 208px */ | | scroll-my-52 | scroll-margin-top: 13rem; /* 208px */ scroll-margin-bottom: 13rem; /* 208px */ | | scroll-ms-52 | scroll-margin-inline-start: 13rem; /* 208px */ | | scroll-me-52 | scroll-margin-inline-end: 13rem; /* 208px */ | | scroll-mt-52 | scroll-margin-top: 13rem; /* 208px */ | | scroll-mr-52 | scroll-margin-right: 13rem; /* 208px */ | | scroll-mb-52 | scroll-margin-bottom: 13rem; /* 208px */ | | scroll-ml-52 | scroll-margin-left: 13rem; /* 208px */ | | scroll-m-56 | scroll-margin: 14rem; /* 224px */ | | scroll-mx-56 | scroll-margin-left: 14rem; /* 224px */ scroll-margin-right: 14rem; /* 224px */ | | scroll-my-56 | scroll-margin-top: 14rem; /* 224px */ scroll-margin-bottom: 14rem; /* 224px */ | | scroll-ms-56 | scroll-margin-inline-start: 14rem; /* 224px */ | | scroll-me-56 | scroll-margin-inline-end: 14rem; /* 224px */ | | scroll-mt-56 | scroll-margin-top: 14rem; /* 224px */ | | scroll-mr-56 | scroll-margin-right: 14rem; /* 224px */ | | scroll-mb-56 | scroll-margin-bottom: 14rem; /* 224px */ | | scroll-ml-56 | scroll-margin-left: 14rem; /* 224px */ | | scroll-m-60 | scroll-margin: 15rem; /* 240px */ | | scroll-mx-60 | scroll-margin-left: 15rem; /* 240px */ scroll-margin-right: 15rem; /* 240px */ | | scroll-my-60 | scroll-margin-top: 15rem; /* 240px */ scroll-margin-bottom: 15rem; /* 240px */ | | scroll-ms-60 | scroll-margin-inline-start: 15rem; /* 240px */ | | scroll-me-60 | scroll-margin-inline-end: 15rem; /* 240px */ | | scroll-mt-60 | scroll-margin-top: 15rem; /* 240px */ | | scroll-mr-60 | scroll-margin-right: 15rem; /* 240px */ | | scroll-mb-60 | scroll-margin-bottom: 15rem; /* 240px */ | | scroll-ml-60 | scroll-margin-left: 15rem; /* 240px */ | | scroll-m-64 | scroll-margin: 16rem; /* 256px */ | | scroll-mx-64 | scroll-margin-left: 16rem; /* 256px */ scroll-margin-right: 16rem; /* 256px */ | | scroll-my-64 | scroll-margin-top: 16rem; /* 256px */ scroll-margin-bottom: 16rem; /* 256px */ | | scroll-ms-64 | scroll-margin-inline-start: 16rem; /* 256px */ | | scroll-me-64 | scroll-margin-inline-end: 16rem; /* 256px */ | | scroll-mt-64 | scroll-margin-top: 16rem; /* 256px */ | | scroll-mr-64 | scroll-margin-right: 16rem; /* 256px */ | | scroll-mb-64 | scroll-margin-bottom: 16rem; /* 256px */ | | scroll-ml-64 | scroll-margin-left: 16rem; /* 256px */ | | scroll-m-72 | scroll-margin: 18rem; /* 288px */ | | scroll-mx-72 | scroll-margin-left: 18rem; /* 288px */ scroll-margin-right: 18rem; /* 288px */ | | scroll-my-72 | scroll-margin-top: 18rem; /* 288px */ scroll-margin-bottom: 18rem; /* 288px */ | | scroll-ms-72 | scroll-margin-inline-start: 18rem; /* 288px */ | | scroll-me-72 | scroll-margin-inline-end: 18rem; /* 288px */ | | scroll-mt-72 | scroll-margin-top: 18rem; /* 288px */ | | scroll-mr-72 | scroll-margin-right: 18rem; /* 288px */ | | scroll-mb-72 | scroll-margin-bottom: 18rem; /* 288px */ | | scroll-ml-72 | scroll-margin-left: 18rem; /* 288px */ | | scroll-m-80 | scroll-margin: 20rem; /* 320px */ | | scroll-mx-80 | scroll-margin-left: 20rem; /* 320px */ scroll-margin-right: 20rem; /* 320px */ | | scroll-my-80 | scroll-margin-top: 20rem; /* 320px */ scroll-margin-bottom: 20rem; /* 320px */ | | scroll-ms-80 | scroll-margin-inline-start: 20rem; /* 320px */ | | scroll-me-80 | scroll-margin-inline-end: 20rem; /* 320px */ | | scroll-mt-80 | scroll-margin-top: 20rem; /* 320px */ | | scroll-mr-80 | scroll-margin-right: 20rem; /* 320px */ | | scroll-mb-80 | scroll-margin-bottom: 20rem; /* 320px */ | | scroll-ml-80 | scroll-margin-left: 20rem; /* 320px */ | | scroll-m-96 | scroll-margin: 24rem; /* 384px */ | | scroll-mx-96 | scroll-margin-left: 24rem; /* 384px */ scroll-margin-right: 24rem; /* 384px */ | | scroll-my-96 | scroll-margin-top: 24rem; /* 384px */ scroll-margin-bottom: 24rem; /* 384px */ | | scroll-ms-96 | scroll-margin-inline-start: 24rem; /* 384px */ | | scroll-me-96 | scroll-margin-inline-end: 24rem; /* 384px */ | | scroll-mt-96 | scroll-margin-top: 24rem; /* 384px */ | | scroll-mr-96 | scroll-margin-right: 24rem; /* 384px */ | | scroll-mb-96 | scroll-margin-bottom: 24rem; /* 384px */ | | scroll-ml-96 | scroll-margin-left: 24rem; /* 384px */ | Basic usage ----------- ### Setting the scroll margin Use the `scroll-m{side}-{size}` utilities to set the scroll offset around items within a snap container. ``` <div class="snap-x ..."> <div class="scroll-ml-6 snap-start ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="scroll-ml-6 snap-start ..."> <img src="https://images.unsplash.com/photo-1540206351-d6465b3ac5c1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="scroll-ml-6 snap-start ..."> <img src="https://images.unsplash.com/photo-1622890806166-111d7f6c7c97?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="scroll-ml-6 snap-start ..."> <img src="https://images.unsplash.com/photo-1590523277543-a94d2e4eb00b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="scroll-ml-6 snap-start ..."> <img src="https://images.unsplash.com/photo-1575424909138-46b05e5919ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> </div> ``` ### Using negative values To use a negative scroll margin value, prefix the class name with a dash to convert it to a negative value. ``` <div class="-scroll-ml-6 snap-start ..."> <!-- ... --> </div> ``` ### Using logical properties Use the `scroll-ms-*` and `scroll-me-*` utilities to set the `scroll-margin-inline-start` and `scroll-margin-inline-end` [logical properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties/Basic_concepts), which map to either the left or right side based on the text direction. ``` <div dir="ltr"> <div class="snap-x ..."> <div class="scroll-ms-6 snap-start ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <!-- ... --> </div> </div<div dir="rtl"> <div class="snap-x ..."> <div class="scroll-ms-6 snap-start ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <!-- ... --> </div> </div> ``` For more control, you can also use the [LTR and RTL modifiers](hover-focus-and-other-states#rtl-support) to conditionally apply specific styles depending on the current text direction. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:scroll-m-0` to only apply the `scroll-m-0` utility on hover. ``` <div class="scroll-m-8 hover:scroll-m-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:scroll-m-0` to apply the `scroll-m-0` utility at only medium screen sizes and above. ``` <div class="scroll-m-8 md:scroll-m-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind’s scroll margin scale uses the [default spacing scale](customizing-spacing). You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '96': '24rem', } } } } ``` Alternatively, you can customize just the scroll margin scale by editing `theme.scrollMargin` or `theme.extend.scrollMargin` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { scrollMargin: { '96': '24rem', }, } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `scroll-margin` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="scroll-m-[24rem]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/scroll-marginScroll Padding ============== Utilities for controlling an element's scroll offset within a snap container. Quick reference --------------- | Class | Properties | | --- | --- | | scroll-p-0 | scroll-padding: 0px; | | scroll-px-0 | scroll-padding-left: 0px; scroll-padding-right: 0px; | | scroll-py-0 | scroll-padding-top: 0px; scroll-padding-bottom: 0px; | | scroll-ps-0 | scroll-padding-inline-start: 0px; | | scroll-pe-0 | scroll-padding-inline-end: 0px; | | scroll-pt-0 | scroll-padding-top: 0px; | | scroll-pr-0 | scroll-padding-right: 0px; | | scroll-pb-0 | scroll-padding-bottom: 0px; | | scroll-pl-0 | scroll-padding-left: 0px; | | scroll-p-px | scroll-padding: 1px; | | scroll-px-px | scroll-padding-left: 1px; scroll-padding-right: 1px; | | scroll-py-px | scroll-padding-top: 1px; scroll-padding-bottom: 1px; | | scroll-ps-px | scroll-padding-inline-start: 1px; | | scroll-pe-px | scroll-padding-inline-end: 1px; | | scroll-pt-px | scroll-padding-top: 1px; | | scroll-pr-px | scroll-padding-right: 1px; | | scroll-pb-px | scroll-padding-bottom: 1px; | | scroll-pl-px | scroll-padding-left: 1px; | | scroll-p-0.5 | scroll-padding: 0.125rem; /* 2px */ | | scroll-px-0.5 | scroll-padding-left: 0.125rem; /* 2px */ scroll-padding-right: 0.125rem; /* 2px */ | | scroll-py-0.5 | scroll-padding-top: 0.125rem; /* 2px */ scroll-padding-bottom: 0.125rem; /* 2px */ | | scroll-ps-0.5 | scroll-padding-inline-start: 0.125rem; /* 2px */ | | scroll-pe-0.5 | scroll-padding-inline-end: 0.125rem; /* 2px */ | | scroll-pt-0.5 | scroll-padding-top: 0.125rem; /* 2px */ | | scroll-pr-0.5 | scroll-padding-right: 0.125rem; /* 2px */ | | scroll-pb-0.5 | scroll-padding-bottom: 0.125rem; /* 2px */ | | scroll-pl-0.5 | scroll-padding-left: 0.125rem; /* 2px */ | | scroll-p-1 | scroll-padding: 0.25rem; /* 4px */ | | scroll-px-1 | scroll-padding-left: 0.25rem; /* 4px */ scroll-padding-right: 0.25rem; /* 4px */ | | scroll-py-1 | scroll-padding-top: 0.25rem; /* 4px */ scroll-padding-bottom: 0.25rem; /* 4px */ | | scroll-ps-1 | scroll-padding-inline-start: 0.25rem; /* 4px */ | | scroll-pe-1 | scroll-padding-inline-end: 0.25rem; /* 4px */ | | scroll-pt-1 | scroll-padding-top: 0.25rem; /* 4px */ | | scroll-pr-1 | scroll-padding-right: 0.25rem; /* 4px */ | | scroll-pb-1 | scroll-padding-bottom: 0.25rem; /* 4px */ | | scroll-pl-1 | scroll-padding-left: 0.25rem; /* 4px */ | | scroll-p-1.5 | scroll-padding: 0.375rem; /* 6px */ | | scroll-px-1.5 | scroll-padding-left: 0.375rem; /* 6px */ scroll-padding-right: 0.375rem; /* 6px */ | | scroll-py-1.5 | scroll-padding-top: 0.375rem; /* 6px */ scroll-padding-bottom: 0.375rem; /* 6px */ | | scroll-ps-1.5 | scroll-padding-inline-start: 0.375rem; /* 6px */ | | scroll-pe-1.5 | scroll-padding-inline-end: 0.375rem; /* 6px */ | | scroll-pt-1.5 | scroll-padding-top: 0.375rem; /* 6px */ | | scroll-pr-1.5 | scroll-padding-right: 0.375rem; /* 6px */ | | scroll-pb-1.5 | scroll-padding-bottom: 0.375rem; /* 6px */ | | scroll-pl-1.5 | scroll-padding-left: 0.375rem; /* 6px */ | | scroll-p-2 | scroll-padding: 0.5rem; /* 8px */ | | scroll-px-2 | scroll-padding-left: 0.5rem; /* 8px */ scroll-padding-right: 0.5rem; /* 8px */ | | scroll-py-2 | scroll-padding-top: 0.5rem; /* 8px */ scroll-padding-bottom: 0.5rem; /* 8px */ | | scroll-ps-2 | scroll-padding-inline-start: 0.5rem; /* 8px */ | | scroll-pe-2 | scroll-padding-inline-end: 0.5rem; /* 8px */ | | scroll-pt-2 | scroll-padding-top: 0.5rem; /* 8px */ | | scroll-pr-2 | scroll-padding-right: 0.5rem; /* 8px */ | | scroll-pb-2 | scroll-padding-bottom: 0.5rem; /* 8px */ | | scroll-pl-2 | scroll-padding-left: 0.5rem; /* 8px */ | | scroll-p-2.5 | scroll-padding: 0.625rem; /* 10px */ | | scroll-px-2.5 | scroll-padding-left: 0.625rem; /* 10px */ scroll-padding-right: 0.625rem; /* 10px */ | | scroll-py-2.5 | scroll-padding-top: 0.625rem; /* 10px */ scroll-padding-bottom: 0.625rem; /* 10px */ | | scroll-ps-2.5 | scroll-padding-inline-start: 0.625rem; /* 10px */ | | scroll-pe-2.5 | scroll-padding-inline-end: 0.625rem; /* 10px */ | | scroll-pt-2.5 | scroll-padding-top: 0.625rem; /* 10px */ | | scroll-pr-2.5 | scroll-padding-right: 0.625rem; /* 10px */ | | scroll-pb-2.5 | scroll-padding-bottom: 0.625rem; /* 10px */ | | scroll-pl-2.5 | scroll-padding-left: 0.625rem; /* 10px */ | | scroll-p-3 | scroll-padding: 0.75rem; /* 12px */ | | scroll-px-3 | scroll-padding-left: 0.75rem; /* 12px */ scroll-padding-right: 0.75rem; /* 12px */ | | scroll-py-3 | scroll-padding-top: 0.75rem; /* 12px */ scroll-padding-bottom: 0.75rem; /* 12px */ | | scroll-ps-3 | scroll-padding-inline-start: 0.75rem; /* 12px */ | | scroll-pe-3 | scroll-padding-inline-end: 0.75rem; /* 12px */ | | scroll-pt-3 | scroll-padding-top: 0.75rem; /* 12px */ | | scroll-pr-3 | scroll-padding-right: 0.75rem; /* 12px */ | | scroll-pb-3 | scroll-padding-bottom: 0.75rem; /* 12px */ | | scroll-pl-3 | scroll-padding-left: 0.75rem; /* 12px */ | | scroll-p-3.5 | scroll-padding: 0.875rem; /* 14px */ | | scroll-px-3.5 | scroll-padding-left: 0.875rem; /* 14px */ scroll-padding-right: 0.875rem; /* 14px */ | | scroll-py-3.5 | scroll-padding-top: 0.875rem; /* 14px */ scroll-padding-bottom: 0.875rem; /* 14px */ | | scroll-ps-3.5 | scroll-padding-inline-start: 0.875rem; /* 14px */ | | scroll-pe-3.5 | scroll-padding-inline-end: 0.875rem; /* 14px */ | | scroll-pt-3.5 | scroll-padding-top: 0.875rem; /* 14px */ | | scroll-pr-3.5 | scroll-padding-right: 0.875rem; /* 14px */ | | scroll-pb-3.5 | scroll-padding-bottom: 0.875rem; /* 14px */ | | scroll-pl-3.5 | scroll-padding-left: 0.875rem; /* 14px */ | | scroll-p-4 | scroll-padding: 1rem; /* 16px */ | | scroll-px-4 | scroll-padding-left: 1rem; /* 16px */ scroll-padding-right: 1rem; /* 16px */ | | scroll-py-4 | scroll-padding-top: 1rem; /* 16px */ scroll-padding-bottom: 1rem; /* 16px */ | | scroll-ps-4 | scroll-padding-inline-start: 1rem; /* 16px */ | | scroll-pe-4 | scroll-padding-inline-end: 1rem; /* 16px */ | | scroll-pt-4 | scroll-padding-top: 1rem; /* 16px */ | | scroll-pr-4 | scroll-padding-right: 1rem; /* 16px */ | | scroll-pb-4 | scroll-padding-bottom: 1rem; /* 16px */ | | scroll-pl-4 | scroll-padding-left: 1rem; /* 16px */ | | scroll-p-5 | scroll-padding: 1.25rem; /* 20px */ | | scroll-px-5 | scroll-padding-left: 1.25rem; /* 20px */ scroll-padding-right: 1.25rem; /* 20px */ | | scroll-py-5 | scroll-padding-top: 1.25rem; /* 20px */ scroll-padding-bottom: 1.25rem; /* 20px */ | | scroll-ps-5 | scroll-padding-inline-start: 1.25rem; /* 20px */ | | scroll-pe-5 | scroll-padding-inline-end: 1.25rem; /* 20px */ | | scroll-pt-5 | scroll-padding-top: 1.25rem; /* 20px */ | | scroll-pr-5 | scroll-padding-right: 1.25rem; /* 20px */ | | scroll-pb-5 | scroll-padding-bottom: 1.25rem; /* 20px */ | | scroll-pl-5 | scroll-padding-left: 1.25rem; /* 20px */ | | scroll-p-6 | scroll-padding: 1.5rem; /* 24px */ | | scroll-px-6 | scroll-padding-left: 1.5rem; /* 24px */ scroll-padding-right: 1.5rem; /* 24px */ | | scroll-py-6 | scroll-padding-top: 1.5rem; /* 24px */ scroll-padding-bottom: 1.5rem; /* 24px */ | | scroll-ps-6 | scroll-padding-inline-start: 1.5rem; /* 24px */ | | scroll-pe-6 | scroll-padding-inline-end: 1.5rem; /* 24px */ | | scroll-pt-6 | scroll-padding-top: 1.5rem; /* 24px */ | | scroll-pr-6 | scroll-padding-right: 1.5rem; /* 24px */ | | scroll-pb-6 | scroll-padding-bottom: 1.5rem; /* 24px */ | | scroll-pl-6 | scroll-padding-left: 1.5rem; /* 24px */ | | scroll-p-7 | scroll-padding: 1.75rem; /* 28px */ | | scroll-px-7 | scroll-padding-left: 1.75rem; /* 28px */ scroll-padding-right: 1.75rem; /* 28px */ | | scroll-py-7 | scroll-padding-top: 1.75rem; /* 28px */ scroll-padding-bottom: 1.75rem; /* 28px */ | | scroll-ps-7 | scroll-padding-inline-start: 1.75rem; /* 28px */ | | scroll-pe-7 | scroll-padding-inline-end: 1.75rem; /* 28px */ | | scroll-pt-7 | scroll-padding-top: 1.75rem; /* 28px */ | | scroll-pr-7 | scroll-padding-right: 1.75rem; /* 28px */ | | scroll-pb-7 | scroll-padding-bottom: 1.75rem; /* 28px */ | | scroll-pl-7 | scroll-padding-left: 1.75rem; /* 28px */ | | scroll-p-8 | scroll-padding: 2rem; /* 32px */ | | scroll-px-8 | scroll-padding-left: 2rem; /* 32px */ scroll-padding-right: 2rem; /* 32px */ | | scroll-py-8 | scroll-padding-top: 2rem; /* 32px */ scroll-padding-bottom: 2rem; /* 32px */ | | scroll-ps-8 | scroll-padding-inline-start: 2rem; /* 32px */ | | scroll-pe-8 | scroll-padding-inline-end: 2rem; /* 32px */ | | scroll-pt-8 | scroll-padding-top: 2rem; /* 32px */ | | scroll-pr-8 | scroll-padding-right: 2rem; /* 32px */ | | scroll-pb-8 | scroll-padding-bottom: 2rem; /* 32px */ | | scroll-pl-8 | scroll-padding-left: 2rem; /* 32px */ | | scroll-p-9 | scroll-padding: 2.25rem; /* 36px */ | | scroll-px-9 | scroll-padding-left: 2.25rem; /* 36px */ scroll-padding-right: 2.25rem; /* 36px */ | | scroll-py-9 | scroll-padding-top: 2.25rem; /* 36px */ scroll-padding-bottom: 2.25rem; /* 36px */ | | scroll-ps-9 | scroll-padding-inline-start: 2.25rem; /* 36px */ | | scroll-pe-9 | scroll-padding-inline-end: 2.25rem; /* 36px */ | | scroll-pt-9 | scroll-padding-top: 2.25rem; /* 36px */ | | scroll-pr-9 | scroll-padding-right: 2.25rem; /* 36px */ | | scroll-pb-9 | scroll-padding-bottom: 2.25rem; /* 36px */ | | scroll-pl-9 | scroll-padding-left: 2.25rem; /* 36px */ | | scroll-p-10 | scroll-padding: 2.5rem; /* 40px */ | | scroll-px-10 | scroll-padding-left: 2.5rem; /* 40px */ scroll-padding-right: 2.5rem; /* 40px */ | | scroll-py-10 | scroll-padding-top: 2.5rem; /* 40px */ scroll-padding-bottom: 2.5rem; /* 40px */ | | scroll-ps-10 | scroll-padding-inline-start: 2.5rem; /* 40px */ | | scroll-pe-10 | scroll-padding-inline-end: 2.5rem; /* 40px */ | | scroll-pt-10 | scroll-padding-top: 2.5rem; /* 40px */ | | scroll-pr-10 | scroll-padding-right: 2.5rem; /* 40px */ | | scroll-pb-10 | scroll-padding-bottom: 2.5rem; /* 40px */ | | scroll-pl-10 | scroll-padding-left: 2.5rem; /* 40px */ | | scroll-p-11 | scroll-padding: 2.75rem; /* 44px */ | | scroll-px-11 | scroll-padding-left: 2.75rem; /* 44px */ scroll-padding-right: 2.75rem; /* 44px */ | | scroll-py-11 | scroll-padding-top: 2.75rem; /* 44px */ scroll-padding-bottom: 2.75rem; /* 44px */ | | scroll-ps-11 | scroll-padding-inline-start: 2.75rem; /* 44px */ | | scroll-pe-11 | scroll-padding-inline-end: 2.75rem; /* 44px */ | | scroll-pt-11 | scroll-padding-top: 2.75rem; /* 44px */ | | scroll-pr-11 | scroll-padding-right: 2.75rem; /* 44px */ | | scroll-pb-11 | scroll-padding-bottom: 2.75rem; /* 44px */ | | scroll-pl-11 | scroll-padding-left: 2.75rem; /* 44px */ | | scroll-p-12 | scroll-padding: 3rem; /* 48px */ | | scroll-px-12 | scroll-padding-left: 3rem; /* 48px */ scroll-padding-right: 3rem; /* 48px */ | | scroll-py-12 | scroll-padding-top: 3rem; /* 48px */ scroll-padding-bottom: 3rem; /* 48px */ | | scroll-ps-12 | scroll-padding-inline-start: 3rem; /* 48px */ | | scroll-pe-12 | scroll-padding-inline-end: 3rem; /* 48px */ | | scroll-pt-12 | scroll-padding-top: 3rem; /* 48px */ | | scroll-pr-12 | scroll-padding-right: 3rem; /* 48px */ | | scroll-pb-12 | scroll-padding-bottom: 3rem; /* 48px */ | | scroll-pl-12 | scroll-padding-left: 3rem; /* 48px */ | | scroll-p-14 | scroll-padding: 3.5rem; /* 56px */ | | scroll-px-14 | scroll-padding-left: 3.5rem; /* 56px */ scroll-padding-right: 3.5rem; /* 56px */ | | scroll-py-14 | scroll-padding-top: 3.5rem; /* 56px */ scroll-padding-bottom: 3.5rem; /* 56px */ | | scroll-ps-14 | scroll-padding-inline-start: 3.5rem; /* 56px */ | | scroll-pe-14 | scroll-padding-inline-end: 3.5rem; /* 56px */ | | scroll-pt-14 | scroll-padding-top: 3.5rem; /* 56px */ | | scroll-pr-14 | scroll-padding-right: 3.5rem; /* 56px */ | | scroll-pb-14 | scroll-padding-bottom: 3.5rem; /* 56px */ | | scroll-pl-14 | scroll-padding-left: 3.5rem; /* 56px */ | | scroll-p-16 | scroll-padding: 4rem; /* 64px */ | | scroll-px-16 | scroll-padding-left: 4rem; /* 64px */ scroll-padding-right: 4rem; /* 64px */ | | scroll-py-16 | scroll-padding-top: 4rem; /* 64px */ scroll-padding-bottom: 4rem; /* 64px */ | | scroll-ps-16 | scroll-padding-inline-start: 4rem; /* 64px */ | | scroll-pe-16 | scroll-padding-inline-end: 4rem; /* 64px */ | | scroll-pt-16 | scroll-padding-top: 4rem; /* 64px */ | | scroll-pr-16 | scroll-padding-right: 4rem; /* 64px */ | | scroll-pb-16 | scroll-padding-bottom: 4rem; /* 64px */ | | scroll-pl-16 | scroll-padding-left: 4rem; /* 64px */ | | scroll-p-20 | scroll-padding: 5rem; /* 80px */ | | scroll-px-20 | scroll-padding-left: 5rem; /* 80px */ scroll-padding-right: 5rem; /* 80px */ | | scroll-py-20 | scroll-padding-top: 5rem; /* 80px */ scroll-padding-bottom: 5rem; /* 80px */ | | scroll-ps-20 | scroll-padding-inline-start: 5rem; /* 80px */ | | scroll-pe-20 | scroll-padding-inline-end: 5rem; /* 80px */ | | scroll-pt-20 | scroll-padding-top: 5rem; /* 80px */ | | scroll-pr-20 | scroll-padding-right: 5rem; /* 80px */ | | scroll-pb-20 | scroll-padding-bottom: 5rem; /* 80px */ | | scroll-pl-20 | scroll-padding-left: 5rem; /* 80px */ | | scroll-p-24 | scroll-padding: 6rem; /* 96px */ | | scroll-px-24 | scroll-padding-left: 6rem; /* 96px */ scroll-padding-right: 6rem; /* 96px */ | | scroll-py-24 | scroll-padding-top: 6rem; /* 96px */ scroll-padding-bottom: 6rem; /* 96px */ | | scroll-ps-24 | scroll-padding-inline-start: 6rem; /* 96px */ | | scroll-pe-24 | scroll-padding-inline-end: 6rem; /* 96px */ | | scroll-pt-24 | scroll-padding-top: 6rem; /* 96px */ | | scroll-pr-24 | scroll-padding-right: 6rem; /* 96px */ | | scroll-pb-24 | scroll-padding-bottom: 6rem; /* 96px */ | | scroll-pl-24 | scroll-padding-left: 6rem; /* 96px */ | | scroll-p-28 | scroll-padding: 7rem; /* 112px */ | | scroll-px-28 | scroll-padding-left: 7rem; /* 112px */ scroll-padding-right: 7rem; /* 112px */ | | scroll-py-28 | scroll-padding-top: 7rem; /* 112px */ scroll-padding-bottom: 7rem; /* 112px */ | | scroll-ps-28 | scroll-padding-inline-start: 7rem; /* 112px */ | | scroll-pe-28 | scroll-padding-inline-end: 7rem; /* 112px */ | | scroll-pt-28 | scroll-padding-top: 7rem; /* 112px */ | | scroll-pr-28 | scroll-padding-right: 7rem; /* 112px */ | | scroll-pb-28 | scroll-padding-bottom: 7rem; /* 112px */ | | scroll-pl-28 | scroll-padding-left: 7rem; /* 112px */ | | scroll-p-32 | scroll-padding: 8rem; /* 128px */ | | scroll-px-32 | scroll-padding-left: 8rem; /* 128px */ scroll-padding-right: 8rem; /* 128px */ | | scroll-py-32 | scroll-padding-top: 8rem; /* 128px */ scroll-padding-bottom: 8rem; /* 128px */ | | scroll-ps-32 | scroll-padding-inline-start: 8rem; /* 128px */ | | scroll-pe-32 | scroll-padding-inline-end: 8rem; /* 128px */ | | scroll-pt-32 | scroll-padding-top: 8rem; /* 128px */ | | scroll-pr-32 | scroll-padding-right: 8rem; /* 128px */ | | scroll-pb-32 | scroll-padding-bottom: 8rem; /* 128px */ | | scroll-pl-32 | scroll-padding-left: 8rem; /* 128px */ | | scroll-p-36 | scroll-padding: 9rem; /* 144px */ | | scroll-px-36 | scroll-padding-left: 9rem; /* 144px */ scroll-padding-right: 9rem; /* 144px */ | | scroll-py-36 | scroll-padding-top: 9rem; /* 144px */ scroll-padding-bottom: 9rem; /* 144px */ | | scroll-ps-36 | scroll-padding-inline-start: 9rem; /* 144px */ | | scroll-pe-36 | scroll-padding-inline-end: 9rem; /* 144px */ | | scroll-pt-36 | scroll-padding-top: 9rem; /* 144px */ | | scroll-pr-36 | scroll-padding-right: 9rem; /* 144px */ | | scroll-pb-36 | scroll-padding-bottom: 9rem; /* 144px */ | | scroll-pl-36 | scroll-padding-left: 9rem; /* 144px */ | | scroll-p-40 | scroll-padding: 10rem; /* 160px */ | | scroll-px-40 | scroll-padding-left: 10rem; /* 160px */ scroll-padding-right: 10rem; /* 160px */ | | scroll-py-40 | scroll-padding-top: 10rem; /* 160px */ scroll-padding-bottom: 10rem; /* 160px */ | | scroll-ps-40 | scroll-padding-inline-start: 10rem; /* 160px */ | | scroll-pe-40 | scroll-padding-inline-end: 10rem; /* 160px */ | | scroll-pt-40 | scroll-padding-top: 10rem; /* 160px */ | | scroll-pr-40 | scroll-padding-right: 10rem; /* 160px */ | | scroll-pb-40 | scroll-padding-bottom: 10rem; /* 160px */ | | scroll-pl-40 | scroll-padding-left: 10rem; /* 160px */ | | scroll-p-44 | scroll-padding: 11rem; /* 176px */ | | scroll-px-44 | scroll-padding-left: 11rem; /* 176px */ scroll-padding-right: 11rem; /* 176px */ | | scroll-py-44 | scroll-padding-top: 11rem; /* 176px */ scroll-padding-bottom: 11rem; /* 176px */ | | scroll-ps-44 | scroll-padding-inline-start: 11rem; /* 176px */ | | scroll-pe-44 | scroll-padding-inline-end: 11rem; /* 176px */ | | scroll-pt-44 | scroll-padding-top: 11rem; /* 176px */ | | scroll-pr-44 | scroll-padding-right: 11rem; /* 176px */ | | scroll-pb-44 | scroll-padding-bottom: 11rem; /* 176px */ | | scroll-pl-44 | scroll-padding-left: 11rem; /* 176px */ | | scroll-p-48 | scroll-padding: 12rem; /* 192px */ | | scroll-px-48 | scroll-padding-left: 12rem; /* 192px */ scroll-padding-right: 12rem; /* 192px */ | | scroll-py-48 | scroll-padding-top: 12rem; /* 192px */ scroll-padding-bottom: 12rem; /* 192px */ | | scroll-ps-48 | scroll-padding-inline-start: 12rem; /* 192px */ | | scroll-pe-48 | scroll-padding-inline-end: 12rem; /* 192px */ | | scroll-pt-48 | scroll-padding-top: 12rem; /* 192px */ | | scroll-pr-48 | scroll-padding-right: 12rem; /* 192px */ | | scroll-pb-48 | scroll-padding-bottom: 12rem; /* 192px */ | | scroll-pl-48 | scroll-padding-left: 12rem; /* 192px */ | | scroll-p-52 | scroll-padding: 13rem; /* 208px */ | | scroll-px-52 | scroll-padding-left: 13rem; /* 208px */ scroll-padding-right: 13rem; /* 208px */ | | scroll-py-52 | scroll-padding-top: 13rem; /* 208px */ scroll-padding-bottom: 13rem; /* 208px */ | | scroll-ps-52 | scroll-padding-inline-start: 13rem; /* 208px */ | | scroll-pe-52 | scroll-padding-inline-end: 13rem; /* 208px */ | | scroll-pt-52 | scroll-padding-top: 13rem; /* 208px */ | | scroll-pr-52 | scroll-padding-right: 13rem; /* 208px */ | | scroll-pb-52 | scroll-padding-bottom: 13rem; /* 208px */ | | scroll-pl-52 | scroll-padding-left: 13rem; /* 208px */ | | scroll-p-56 | scroll-padding: 14rem; /* 224px */ | | scroll-px-56 | scroll-padding-left: 14rem; /* 224px */ scroll-padding-right: 14rem; /* 224px */ | | scroll-py-56 | scroll-padding-top: 14rem; /* 224px */ scroll-padding-bottom: 14rem; /* 224px */ | | scroll-ps-56 | scroll-padding-inline-start: 14rem; /* 224px */ | | scroll-pe-56 | scroll-padding-inline-end: 14rem; /* 224px */ | | scroll-pt-56 | scroll-padding-top: 14rem; /* 224px */ | | scroll-pr-56 | scroll-padding-right: 14rem; /* 224px */ | | scroll-pb-56 | scroll-padding-bottom: 14rem; /* 224px */ | | scroll-pl-56 | scroll-padding-left: 14rem; /* 224px */ | | scroll-p-60 | scroll-padding: 15rem; /* 240px */ | | scroll-px-60 | scroll-padding-left: 15rem; /* 240px */ scroll-padding-right: 15rem; /* 240px */ | | scroll-py-60 | scroll-padding-top: 15rem; /* 240px */ scroll-padding-bottom: 15rem; /* 240px */ | | scroll-ps-60 | scroll-padding-inline-start: 15rem; /* 240px */ | | scroll-pe-60 | scroll-padding-inline-end: 15rem; /* 240px */ | | scroll-pt-60 | scroll-padding-top: 15rem; /* 240px */ | | scroll-pr-60 | scroll-padding-right: 15rem; /* 240px */ | | scroll-pb-60 | scroll-padding-bottom: 15rem; /* 240px */ | | scroll-pl-60 | scroll-padding-left: 15rem; /* 240px */ | | scroll-p-64 | scroll-padding: 16rem; /* 256px */ | | scroll-px-64 | scroll-padding-left: 16rem; /* 256px */ scroll-padding-right: 16rem; /* 256px */ | | scroll-py-64 | scroll-padding-top: 16rem; /* 256px */ scroll-padding-bottom: 16rem; /* 256px */ | | scroll-ps-64 | scroll-padding-inline-start: 16rem; /* 256px */ | | scroll-pe-64 | scroll-padding-inline-end: 16rem; /* 256px */ | | scroll-pt-64 | scroll-padding-top: 16rem; /* 256px */ | | scroll-pr-64 | scroll-padding-right: 16rem; /* 256px */ | | scroll-pb-64 | scroll-padding-bottom: 16rem; /* 256px */ | | scroll-pl-64 | scroll-padding-left: 16rem; /* 256px */ | | scroll-p-72 | scroll-padding: 18rem; /* 288px */ | | scroll-px-72 | scroll-padding-left: 18rem; /* 288px */ scroll-padding-right: 18rem; /* 288px */ | | scroll-py-72 | scroll-padding-top: 18rem; /* 288px */ scroll-padding-bottom: 18rem; /* 288px */ | | scroll-ps-72 | scroll-padding-inline-start: 18rem; /* 288px */ | | scroll-pe-72 | scroll-padding-inline-end: 18rem; /* 288px */ | | scroll-pt-72 | scroll-padding-top: 18rem; /* 288px */ | | scroll-pr-72 | scroll-padding-right: 18rem; /* 288px */ | | scroll-pb-72 | scroll-padding-bottom: 18rem; /* 288px */ | | scroll-pl-72 | scroll-padding-left: 18rem; /* 288px */ | | scroll-p-80 | scroll-padding: 20rem; /* 320px */ | | scroll-px-80 | scroll-padding-left: 20rem; /* 320px */ scroll-padding-right: 20rem; /* 320px */ | | scroll-py-80 | scroll-padding-top: 20rem; /* 320px */ scroll-padding-bottom: 20rem; /* 320px */ | | scroll-ps-80 | scroll-padding-inline-start: 20rem; /* 320px */ | | scroll-pe-80 | scroll-padding-inline-end: 20rem; /* 320px */ | | scroll-pt-80 | scroll-padding-top: 20rem; /* 320px */ | | scroll-pr-80 | scroll-padding-right: 20rem; /* 320px */ | | scroll-pb-80 | scroll-padding-bottom: 20rem; /* 320px */ | | scroll-pl-80 | scroll-padding-left: 20rem; /* 320px */ | | scroll-p-96 | scroll-padding: 24rem; /* 384px */ | | scroll-px-96 | scroll-padding-left: 24rem; /* 384px */ scroll-padding-right: 24rem; /* 384px */ | | scroll-py-96 | scroll-padding-top: 24rem; /* 384px */ scroll-padding-bottom: 24rem; /* 384px */ | | scroll-ps-96 | scroll-padding-inline-start: 24rem; /* 384px */ | | scroll-pe-96 | scroll-padding-inline-end: 24rem; /* 384px */ | | scroll-pt-96 | scroll-padding-top: 24rem; /* 384px */ | | scroll-pr-96 | scroll-padding-right: 24rem; /* 384px */ | | scroll-pb-96 | scroll-padding-bottom: 24rem; /* 384px */ | | scroll-pl-96 | scroll-padding-left: 24rem; /* 384px */ | Basic usage ----------- ### Setting the scroll padding Use the `scroll-p{side}-{size}` utilities to set the scroll offset of an element within a snap container. ``` <div class="scroll-pl-6 snap-x ..."> <div class="snap-start ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-start ..."> <img src="https://images.unsplash.com/photo-1540206351-d6465b3ac5c1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-start ..."> <img src="https://images.unsplash.com/photo-1622890806166-111d7f6c7c97?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-start ..."> <img src="https://images.unsplash.com/photo-1590523277543-a94d2e4eb00b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-start ..."> <img src="https://images.unsplash.com/photo-1575424909138-46b05e5919ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> </div> ``` ### Using logical properties Use the `scroll-ps-*` and `scroll-pe-*` utilities to set the `scroll-padding-inline-start` and `scroll-padding-inline-end` [logical properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties/Basic_concepts), which map to either the left or right side based on the text direction. ``` <div dir="ltr"> <div class="scroll-ps-6 snap-x ..."> <!-- ... --> </div> </div<div dir="rtl"> <div class="scroll-ps-6 snap-x ..."> <!-- ... --> </div> </div> ``` For more control, you can also use the [LTR and RTL modifiers](hover-focus-and-other-states#rtl-support) to conditionally apply specific styles depending on the current text direction. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:scroll-p-0` to only apply the `scroll-p-0` utility on hover. ``` <div class="scroll-p-8 hover:scroll-p-0"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:scroll-p-0` to apply the `scroll-p-0` utility at only medium screen sizes and above. ``` <div class="scroll-p-8 md:scroll-p-0"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind’s scroll padding scale uses the [default spacing scale](customizing-spacing). You can customize your spacing scale by editing `theme.spacing` or `theme.extend.spacing` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { spacing: { '96': '24rem', } } } } ``` Alternatively, you can customize just the scroll padding scale by editing `theme.scrollPadding` or `theme.extend.scrollPadding` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { scrollPadding: { '96': '24rem', }, } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `scroll-padding` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="scroll-p-[24rem]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/scroll-paddingScroll Snap Align ================= Utilities for controlling the scroll snap alignment of an element. Quick reference --------------- | Class | Properties | | --- | --- | | snap-start | scroll-snap-align: start; | | snap-end | scroll-snap-align: end; | | snap-center | scroll-snap-align: center; | | snap-align-none | scroll-snap-align: none; | Basic usage ----------- ### Snapping to the center Use the `snap-center` utility to snap an element to its center when being scrolled inside a snap container. ``` <div class="snap-x ..."> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1540206351-d6465b3ac5c1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1622890806166-111d7f6c7c97?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1590523277543-a94d2e4eb00b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1575424909138-46b05e5919ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1559333086-b0a56225a93c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> </div> ``` ### Snapping to the start Use the `snap-start` utility to snap an element to its start when being scrolled inside a snap container. ``` <div class="snap-x ..."> <div class="snap-start ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-start ..."> <img src="https://images.unsplash.com/photo-1540206351-d6465b3ac5c1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-start ..."> <img src="https://images.unsplash.com/photo-1622890806166-111d7f6c7c97?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-start ..."> <img src="https://images.unsplash.com/photo-1590523277543-a94d2e4eb00b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-start ..."> <img src="https://images.unsplash.com/photo-1575424909138-46b05e5919ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-start ..."> <img src="https://images.unsplash.com/photo-1559333086-b0a56225a93c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> </div> ``` ### Snapping to the end Use the `snap-end` utility to snap an element to its end when being scrolled inside a snap container. ``` <div class="snap-x ..."> <div class="snap-end ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-end ..."> <img src="https://images.unsplash.com/photo-1540206351-d6465b3ac5c1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-end ..."> <img src="https://images.unsplash.com/photo-1622890806166-111d7f6c7c97?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-end ..."> <img src="https://images.unsplash.com/photo-1590523277543-a94d2e4eb00b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-end ..."> <img src="https://images.unsplash.com/photo-1575424909138-46b05e5919ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-end ..."> <img src="https://images.unsplash.com/photo-1559333086-b0a56225a93c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:snap-start` to only apply the `snap-start` utility on hover. ``` <div class="snap-center hover:snap-start"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:snap-start` to apply the `snap-start` utility at only medium screen sizes and above. ``` <div class="snap-center md:snap-start"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/scroll-snap-alignScroll Snap Stop ================ Utilities for controlling whether you can skip past possible snap positions. Quick reference --------------- | Class | Properties | | --- | --- | | snap-normal | scroll-snap-stop: normal; | | snap-always | scroll-snap-stop: always; | Basic usage ----------- ### Forcing snap position stops Use the `snap-always` utility together with the `snap-mandatory` utility to force a snap container to always stop on an element before the user can continue scrolling to the next item. ``` <div class="snap-x snap-mandatory ..."> <div class="snap-always snap-center ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-always snap-center ..."> <img src="https://images.unsplash.com/photo-1540206351-d6465b3ac5c1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-always snap-center ..."> <img src="https://images.unsplash.com/photo-1622890806166-111d7f6c7c97?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-always snap-center ..."> <img src="https://images.unsplash.com/photo-1590523277543-a94d2e4eb00b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-always snap-center ..."> <img src="https://images.unsplash.com/photo-1575424909138-46b05e5919ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-always snap-center ..."> <img src="https://images.unsplash.com/photo-1559333086-b0a56225a93c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> </div> ``` ### Skipping snap position stops Use the `snap-normal` utility to allow a snap container to skip past possible scroll snap positions. ``` <div class="snap-x ..."> <div class="snap-normal snap-center ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-normal snap-center ..."> <img src="https://images.unsplash.com/photo-1540206351-d6465b3ac5c1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-normal snap-center ..."> <img src="https://images.unsplash.com/photo-1622890806166-111d7f6c7c97?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-normal snap-center ..."> <img src="https://images.unsplash.com/photo-1590523277543-a94d2e4eb00b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-normal snap-center ..."> <img src="https://images.unsplash.com/photo-1575424909138-46b05e5919ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-normal snap-center ..."> <img src="https://images.unsplash.com/photo-1559333086-b0a56225a93c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:snap-normal` to only apply the `snap-normal` utility on hover. ``` <div class="snap-always hover:snap-normal"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:snap-normal` to apply the `snap-normal` utility at only medium screen sizes and above. ``` <div class="snap-always md:snap-normal"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/scroll-snap-stopScroll Snap Type ================ Utilities for controlling how strictly snap points are enforced in a snap container. Quick reference --------------- | Class | Properties | | --- | --- | | snap-none | scroll-snap-type: none; | | snap-x | scroll-snap-type: x var(--tw-scroll-snap-strictness); | | snap-y | scroll-snap-type: y var(--tw-scroll-snap-strictness); | | snap-both | scroll-snap-type: both var(--tw-scroll-snap-strictness); | | snap-mandatory | --tw-scroll-snap-strictness: mandatory; | | snap-proximity | --tw-scroll-snap-strictness: proximity; | Basic usage ----------- ### Horizontal scroll snapping Use the `snap-x` utility to enable horizontal scroll snapping within an element. For scroll snapping to work, you need to also set the [scroll snap alignment](scroll-snap-align) on the children within the element. ``` <div class="snap-x ..."> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1540206351-d6465b3ac5c1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1622890806166-111d7f6c7c97?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1590523277543-a94d2e4eb00b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1575424909138-46b05e5919ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1559333086-b0a56225a93c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> </div> ``` ### Mandatory scroll snapping Use the `snap-mandatory` utility to force a snap container to always come to rest on a snap point. ``` <div class="snap-mandatory snap-x ..."> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1540206351-d6465b3ac5c1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1622890806166-111d7f6c7c97?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1590523277543-a94d2e4eb00b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1575424909138-46b05e5919ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1559333086-b0a56225a93c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> </div> ``` ### Proximity scroll snapping Use the `snap-proximity` utility to make a snap container come to rest on snap points that are close in proximity. This is the browser default. ``` <div class="snap-proximity snap-x ..."> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1604999565976-8913ad2ddb7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1540206351-d6465b3ac5c1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1622890806166-111d7f6c7c97?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1590523277543-a94d2e4eb00b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> <div class="snap-center ..."> <img src="https://images.unsplash.com/photo-1575424909138-46b05e5919ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=320&h=160&q=80" /> </div> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:snap-x` to only apply the `snap-x` utility on hover. ``` <div class="hover:snap-x"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:snap-x` to apply the `snap-x` utility at only medium screen sizes and above. ``` <div class="md:snap-x"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/scroll-snap-typeTouch Action ============ Utilities for controlling how an element can be scrolled and zoomed on touchscreens. Quick reference --------------- | Class | Properties | | --- | --- | | touch-auto | touch-action: auto; | | touch-none | touch-action: none; | | touch-pan-x | touch-action: pan-x; | | touch-pan-left | touch-action: pan-left; | | touch-pan-right | touch-action: pan-right; | | touch-pan-y | touch-action: pan-y; | | touch-pan-up | touch-action: pan-up; | | touch-pan-down | touch-action: pan-down; | | touch-pinch-zoom | touch-action: pinch-zoom; | | touch-manipulation | touch-action: manipulation; | Basic usage ----------- ### Setting the touch action Use the `touch-{action}` utilities to control how an element can be scrolled (panned) and zoomed (pinched) on touchscreens. ``` <div class="w-full h-48 overflow-auto touch-auto ..."> <img class="w-[150%] max-w-none h-auto" src="..." /> </div> <div class="w-full h-48 overflow-auto touch-none ..."> <img class="w-[150%] max-w-none h-auto" src="..." /> </div> <div class="w-full h-48 overflow-auto touch-pan-x ..."> <img class="w-[150%] max-w-none h-auto" src="..." /> </div> <div class="w-full h-48 overflow-auto touch-pan-y ..."> <img class="w-[150%] max-w-none h-auto" src="..." /> </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `focus:touch-pan-x` to only apply the `touch-pan-x` utility on focus. ``` <div class="focus:touch-pan-x"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:touch-pan-x` to apply the `touch-pan-x` utility at only medium screen sizes and above. ``` <div class="md:touch-pan-x"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/touch-actionUser Select =========== Utilities for controlling whether the user can select text in an element. Quick reference --------------- | Class | Properties | | --- | --- | | select-none | user-select: none; | | select-text | user-select: text; | | select-all | user-select: all; | | select-auto | user-select: auto; | Basic usage ----------- ### Disabling text selection Use `select-none` to prevent selecting text in an element and its children. ``` <div class="select-none ..."> The quick brown fox jumps over the lazy dog. </div> ``` ### Allowing text selection Use `select-text` to allow selecting text in an element and its children. ``` <div class="select-text ..."> The quick brown fox jumps over the lazy dog. </div> ``` ### Selecting all text in one click Use `select-all` to automatically select all the text in an element when a user clicks. ``` <div class="select-all ..."> The quick brown fox jumps over the lazy dog. </div> ``` ### Using auto select behaviour Use `select-auto` to use the default browser behavior for selecting text. Useful for undoing other classes like `select-none` at different breakpoints. ``` <div class="select-auto ..."> The quick brown fox jumps over the lazy dog. </div> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:select-all` to only apply the `select-all` utility on hover. ``` <div class="hover:select-all"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:select-all` to apply the `select-all` utility at only medium screen sizes and above. ``` <div class="md:select-all"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/user-selectWill Change =========== Utilities for optimizing upcoming animations of elements that are expected to change. Quick reference --------------- | Class | Properties | | --- | --- | | will-change-auto | will-change: auto; | | will-change-scroll | will-change: scroll-position; | | will-change-contents | will-change: contents; | | will-change-transform | will-change: transform; | Basic usage ----------- ### Optimizing with will change Use `will-change-scroll`, `will-change-contents` and `will-change-transform` to optimize an element that’s expected to change in the near future by instructing the browser to prepare the necessary animation before it actually begins. ``` <div class="overflow-auto will-change-scroll"> <!-- ... --> </div> ``` It’s recommended that you apply these utilities just before an element changes, and then remove it shortly after it finishes using `will-change-auto`. The will-change property is intended to be used as a last resort when dealing with **known performance problems**. Avoid using these utilities too much, or simply in anticipation of performance issues, as it could actually cause the page to be less performant. Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:will-change-scroll` to only apply the `will-change-scroll` utility on hover. ``` <div class="will-change-auto hover:will-change-scroll"> <!-- ... --> </div``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:will-change-scroll` to apply the `will-change-scroll` utility at only medium screen sizes and above. ``` <div class="will-change-auto md:will-change-scroll"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind provides four `will-change` utilities. You can customize these values by editing `theme.willChange` or `theme.extend.willChange` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { willChange: { 'left-top': 'left, top', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `will-change` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <div class="will-change-[top,left]"> <!-- ... --> </div``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/will-changeFill ==== Utilities for styling the fill of SVG elements. Quick reference --------------- | Class | Properties | | --- | --- | | fill-none | fill: none; | | fill-inherit | fill: inherit; | | fill-current | fill: currentColor; | | fill-transparent | fill: transparent; | | fill-black | fill: #000; | | fill-white | fill: #fff; | | fill-slate-50 | fill: #f8fafc; | | fill-slate-100 | fill: #f1f5f9; | | fill-slate-200 | fill: #e2e8f0; | | fill-slate-300 | fill: #cbd5e1; | | fill-slate-400 | fill: #94a3b8; | | fill-slate-500 | fill: #64748b; | | fill-slate-600 | fill: #475569; | | fill-slate-700 | fill: #334155; | | fill-slate-800 | fill: #1e293b; | | fill-slate-900 | fill: #0f172a; | | fill-slate-950 | fill: #020617; | | fill-gray-50 | fill: #f9fafb; | | fill-gray-100 | fill: #f3f4f6; | | fill-gray-200 | fill: #e5e7eb; | | fill-gray-300 | fill: #d1d5db; | | fill-gray-400 | fill: #9ca3af; | | fill-gray-500 | fill: #6b7280; | | fill-gray-600 | fill: #4b5563; | | fill-gray-700 | fill: #374151; | | fill-gray-800 | fill: #1f2937; | | fill-gray-900 | fill: #111827; | | fill-gray-950 | fill: #030712; | | fill-zinc-50 | fill: #fafafa; | | fill-zinc-100 | fill: #f4f4f5; | | fill-zinc-200 | fill: #e4e4e7; | | fill-zinc-300 | fill: #d4d4d8; | | fill-zinc-400 | fill: #a1a1aa; | | fill-zinc-500 | fill: #71717a; | | fill-zinc-600 | fill: #52525b; | | fill-zinc-700 | fill: #3f3f46; | | fill-zinc-800 | fill: #27272a; | | fill-zinc-900 | fill: #18181b; | | fill-zinc-950 | fill: #09090b; | | fill-neutral-50 | fill: #fafafa; | | fill-neutral-100 | fill: #f5f5f5; | | fill-neutral-200 | fill: #e5e5e5; | | fill-neutral-300 | fill: #d4d4d4; | | fill-neutral-400 | fill: #a3a3a3; | | fill-neutral-500 | fill: #737373; | | fill-neutral-600 | fill: #525252; | | fill-neutral-700 | fill: #404040; | | fill-neutral-800 | fill: #262626; | | fill-neutral-900 | fill: #171717; | | fill-neutral-950 | fill: #0a0a0a; | | fill-stone-50 | fill: #fafaf9; | | fill-stone-100 | fill: #f5f5f4; | | fill-stone-200 | fill: #e7e5e4; | | fill-stone-300 | fill: #d6d3d1; | | fill-stone-400 | fill: #a8a29e; | | fill-stone-500 | fill: #78716c; | | fill-stone-600 | fill: #57534e; | | fill-stone-700 | fill: #44403c; | | fill-stone-800 | fill: #292524; | | fill-stone-900 | fill: #1c1917; | | fill-stone-950 | fill: #0c0a09; | | fill-red-50 | fill: #fef2f2; | | fill-red-100 | fill: #fee2e2; | | fill-red-200 | fill: #fecaca; | | fill-red-300 | fill: #fca5a5; | | fill-red-400 | fill: #f87171; | | fill-red-500 | fill: #ef4444; | | fill-red-600 | fill: #dc2626; | | fill-red-700 | fill: #b91c1c; | | fill-red-800 | fill: #991b1b; | | fill-red-900 | fill: #7f1d1d; | | fill-red-950 | fill: #450a0a; | | fill-orange-50 | fill: #fff7ed; | | fill-orange-100 | fill: #ffedd5; | | fill-orange-200 | fill: #fed7aa; | | fill-orange-300 | fill: #fdba74; | | fill-orange-400 | fill: #fb923c; | | fill-orange-500 | fill: #f97316; | | fill-orange-600 | fill: #ea580c; | | fill-orange-700 | fill: #c2410c; | | fill-orange-800 | fill: #9a3412; | | fill-orange-900 | fill: #7c2d12; | | fill-orange-950 | fill: #431407; | | fill-amber-50 | fill: #fffbeb; | | fill-amber-100 | fill: #fef3c7; | | fill-amber-200 | fill: #fde68a; | | fill-amber-300 | fill: #fcd34d; | | fill-amber-400 | fill: #fbbf24; | | fill-amber-500 | fill: #f59e0b; | | fill-amber-600 | fill: #d97706; | | fill-amber-700 | fill: #b45309; | | fill-amber-800 | fill: #92400e; | | fill-amber-900 | fill: #78350f; | | fill-amber-950 | fill: #451a03; | | fill-yellow-50 | fill: #fefce8; | | fill-yellow-100 | fill: #fef9c3; | | fill-yellow-200 | fill: #fef08a; | | fill-yellow-300 | fill: #fde047; | | fill-yellow-400 | fill: #facc15; | | fill-yellow-500 | fill: #eab308; | | fill-yellow-600 | fill: #ca8a04; | | fill-yellow-700 | fill: #a16207; | | fill-yellow-800 | fill: #854d0e; | | fill-yellow-900 | fill: #713f12; | | fill-yellow-950 | fill: #422006; | | fill-lime-50 | fill: #f7fee7; | | fill-lime-100 | fill: #ecfccb; | | fill-lime-200 | fill: #d9f99d; | | fill-lime-300 | fill: #bef264; | | fill-lime-400 | fill: #a3e635; | | fill-lime-500 | fill: #84cc16; | | fill-lime-600 | fill: #65a30d; | | fill-lime-700 | fill: #4d7c0f; | | fill-lime-800 | fill: #3f6212; | | fill-lime-900 | fill: #365314; | | fill-lime-950 | fill: #1a2e05; | | fill-green-50 | fill: #f0fdf4; | | fill-green-100 | fill: #dcfce7; | | fill-green-200 | fill: #bbf7d0; | | fill-green-300 | fill: #86efac; | | fill-green-400 | fill: #4ade80; | | fill-green-500 | fill: #22c55e; | | fill-green-600 | fill: #16a34a; | | fill-green-700 | fill: #15803d; | | fill-green-800 | fill: #166534; | | fill-green-900 | fill: #14532d; | | fill-green-950 | fill: #052e16; | | fill-emerald-50 | fill: #ecfdf5; | | fill-emerald-100 | fill: #d1fae5; | | fill-emerald-200 | fill: #a7f3d0; | | fill-emerald-300 | fill: #6ee7b7; | | fill-emerald-400 | fill: #34d399; | | fill-emerald-500 | fill: #10b981; | | fill-emerald-600 | fill: #059669; | | fill-emerald-700 | fill: #047857; | | fill-emerald-800 | fill: #065f46; | | fill-emerald-900 | fill: #064e3b; | | fill-emerald-950 | fill: #022c22; | | fill-teal-50 | fill: #f0fdfa; | | fill-teal-100 | fill: #ccfbf1; | | fill-teal-200 | fill: #99f6e4; | | fill-teal-300 | fill: #5eead4; | | fill-teal-400 | fill: #2dd4bf; | | fill-teal-500 | fill: #14b8a6; | | fill-teal-600 | fill: #0d9488; | | fill-teal-700 | fill: #0f766e; | | fill-teal-800 | fill: #115e59; | | fill-teal-900 | fill: #134e4a; | | fill-teal-950 | fill: #042f2e; | | fill-cyan-50 | fill: #ecfeff; | | fill-cyan-100 | fill: #cffafe; | | fill-cyan-200 | fill: #a5f3fc; | | fill-cyan-300 | fill: #67e8f9; | | fill-cyan-400 | fill: #22d3ee; | | fill-cyan-500 | fill: #06b6d4; | | fill-cyan-600 | fill: #0891b2; | | fill-cyan-700 | fill: #0e7490; | | fill-cyan-800 | fill: #155e75; | | fill-cyan-900 | fill: #164e63; | | fill-cyan-950 | fill: #083344; | | fill-sky-50 | fill: #f0f9ff; | | fill-sky-100 | fill: #e0f2fe; | | fill-sky-200 | fill: #bae6fd; | | fill-sky-300 | fill: #7dd3fc; | | fill-sky-400 | fill: #38bdf8; | | fill-sky-500 | fill: #0ea5e9; | | fill-sky-600 | fill: #0284c7; | | fill-sky-700 | fill: #0369a1; | | fill-sky-800 | fill: #075985; | | fill-sky-900 | fill: #0c4a6e; | | fill-sky-950 | fill: #082f49; | | fill-blue-50 | fill: #eff6ff; | | fill-blue-100 | fill: #dbeafe; | | fill-blue-200 | fill: #bfdbfe; | | fill-blue-300 | fill: #93c5fd; | | fill-blue-400 | fill: #60a5fa; | | fill-blue-500 | fill: #3b82f6; | | fill-blue-600 | fill: #2563eb; | | fill-blue-700 | fill: #1d4ed8; | | fill-blue-800 | fill: #1e40af; | | fill-blue-900 | fill: #1e3a8a; | | fill-blue-950 | fill: #172554; | | fill-indigo-50 | fill: #eef2ff; | | fill-indigo-100 | fill: #e0e7ff; | | fill-indigo-200 | fill: #c7d2fe; | | fill-indigo-300 | fill: #a5b4fc; | | fill-indigo-400 | fill: #818cf8; | | fill-indigo-500 | fill: #6366f1; | | fill-indigo-600 | fill: #4f46e5; | | fill-indigo-700 | fill: #4338ca; | | fill-indigo-800 | fill: #3730a3; | | fill-indigo-900 | fill: #312e81; | | fill-indigo-950 | fill: #1e1b4b; | | fill-violet-50 | fill: #f5f3ff; | | fill-violet-100 | fill: #ede9fe; | | fill-violet-200 | fill: #ddd6fe; | | fill-violet-300 | fill: #c4b5fd; | | fill-violet-400 | fill: #a78bfa; | | fill-violet-500 | fill: #8b5cf6; | | fill-violet-600 | fill: #7c3aed; | | fill-violet-700 | fill: #6d28d9; | | fill-violet-800 | fill: #5b21b6; | | fill-violet-900 | fill: #4c1d95; | | fill-violet-950 | fill: #2e1065; | | fill-purple-50 | fill: #faf5ff; | | fill-purple-100 | fill: #f3e8ff; | | fill-purple-200 | fill: #e9d5ff; | | fill-purple-300 | fill: #d8b4fe; | | fill-purple-400 | fill: #c084fc; | | fill-purple-500 | fill: #a855f7; | | fill-purple-600 | fill: #9333ea; | | fill-purple-700 | fill: #7e22ce; | | fill-purple-800 | fill: #6b21a8; | | fill-purple-900 | fill: #581c87; | | fill-purple-950 | fill: #3b0764; | | fill-fuchsia-50 | fill: #fdf4ff; | | fill-fuchsia-100 | fill: #fae8ff; | | fill-fuchsia-200 | fill: #f5d0fe; | | fill-fuchsia-300 | fill: #f0abfc; | | fill-fuchsia-400 | fill: #e879f9; | | fill-fuchsia-500 | fill: #d946ef; | | fill-fuchsia-600 | fill: #c026d3; | | fill-fuchsia-700 | fill: #a21caf; | | fill-fuchsia-800 | fill: #86198f; | | fill-fuchsia-900 | fill: #701a75; | | fill-fuchsia-950 | fill: #4a044e; | | fill-pink-50 | fill: #fdf2f8; | | fill-pink-100 | fill: #fce7f3; | | fill-pink-200 | fill: #fbcfe8; | | fill-pink-300 | fill: #f9a8d4; | | fill-pink-400 | fill: #f472b6; | | fill-pink-500 | fill: #ec4899; | | fill-pink-600 | fill: #db2777; | | fill-pink-700 | fill: #be185d; | | fill-pink-800 | fill: #9d174d; | | fill-pink-900 | fill: #831843; | | fill-pink-950 | fill: #500724; | | fill-rose-50 | fill: #fff1f2; | | fill-rose-100 | fill: #ffe4e6; | | fill-rose-200 | fill: #fecdd3; | | fill-rose-300 | fill: #fda4af; | | fill-rose-400 | fill: #fb7185; | | fill-rose-500 | fill: #f43f5e; | | fill-rose-600 | fill: #e11d48; | | fill-rose-700 | fill: #be123c; | | fill-rose-800 | fill: #9f1239; | | fill-rose-900 | fill: #881337; | | fill-rose-950 | fill: #4c0519; | Basic usage ----------- ### Setting the fill color Use the `fill-{color}` utilities to change the fill color of an SVG. ``` <svg class="fill-blue-500 ..."> <!-- ... --> </svg> ``` This can be useful for styling icon sets like [Heroicons](https://heroicons.com). Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:fill-cyan-700` to only apply the `fill-cyan-700` utility on hover. ``` <svg class="fill-cyan-500 hover:fill-cyan-700"> <!-- ... --> </svg``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:fill-cyan-700` to apply the `fill-cyan-700` utility at only medium screen sizes and above. ``` <svg class="fill-cyan-500 md:fill-cyan-700"> <!-- ... --> </svg``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as fill colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your fill colors by editing `theme.fill` or `theme.extend.fill` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `fill` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <svg class="fill-[#243c5a]"> <!-- ... --> </svg``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/fillStroke ====== Utilities for styling the stroke of SVG elements. Quick reference --------------- | Class | Properties | | --- | --- | | stroke-none | stroke: none; | | stroke-inherit | stroke: inherit; | | stroke-current | stroke: currentColor; | | stroke-transparent | stroke: transparent; | | stroke-black | stroke: #000; | | stroke-white | stroke: #fff; | | stroke-slate-50 | stroke: #f8fafc; | | stroke-slate-100 | stroke: #f1f5f9; | | stroke-slate-200 | stroke: #e2e8f0; | | stroke-slate-300 | stroke: #cbd5e1; | | stroke-slate-400 | stroke: #94a3b8; | | stroke-slate-500 | stroke: #64748b; | | stroke-slate-600 | stroke: #475569; | | stroke-slate-700 | stroke: #334155; | | stroke-slate-800 | stroke: #1e293b; | | stroke-slate-900 | stroke: #0f172a; | | stroke-slate-950 | stroke: #020617; | | stroke-gray-50 | stroke: #f9fafb; | | stroke-gray-100 | stroke: #f3f4f6; | | stroke-gray-200 | stroke: #e5e7eb; | | stroke-gray-300 | stroke: #d1d5db; | | stroke-gray-400 | stroke: #9ca3af; | | stroke-gray-500 | stroke: #6b7280; | | stroke-gray-600 | stroke: #4b5563; | | stroke-gray-700 | stroke: #374151; | | stroke-gray-800 | stroke: #1f2937; | | stroke-gray-900 | stroke: #111827; | | stroke-gray-950 | stroke: #030712; | | stroke-zinc-50 | stroke: #fafafa; | | stroke-zinc-100 | stroke: #f4f4f5; | | stroke-zinc-200 | stroke: #e4e4e7; | | stroke-zinc-300 | stroke: #d4d4d8; | | stroke-zinc-400 | stroke: #a1a1aa; | | stroke-zinc-500 | stroke: #71717a; | | stroke-zinc-600 | stroke: #52525b; | | stroke-zinc-700 | stroke: #3f3f46; | | stroke-zinc-800 | stroke: #27272a; | | stroke-zinc-900 | stroke: #18181b; | | stroke-zinc-950 | stroke: #09090b; | | stroke-neutral-50 | stroke: #fafafa; | | stroke-neutral-100 | stroke: #f5f5f5; | | stroke-neutral-200 | stroke: #e5e5e5; | | stroke-neutral-300 | stroke: #d4d4d4; | | stroke-neutral-400 | stroke: #a3a3a3; | | stroke-neutral-500 | stroke: #737373; | | stroke-neutral-600 | stroke: #525252; | | stroke-neutral-700 | stroke: #404040; | | stroke-neutral-800 | stroke: #262626; | | stroke-neutral-900 | stroke: #171717; | | stroke-neutral-950 | stroke: #0a0a0a; | | stroke-stone-50 | stroke: #fafaf9; | | stroke-stone-100 | stroke: #f5f5f4; | | stroke-stone-200 | stroke: #e7e5e4; | | stroke-stone-300 | stroke: #d6d3d1; | | stroke-stone-400 | stroke: #a8a29e; | | stroke-stone-500 | stroke: #78716c; | | stroke-stone-600 | stroke: #57534e; | | stroke-stone-700 | stroke: #44403c; | | stroke-stone-800 | stroke: #292524; | | stroke-stone-900 | stroke: #1c1917; | | stroke-stone-950 | stroke: #0c0a09; | | stroke-red-50 | stroke: #fef2f2; | | stroke-red-100 | stroke: #fee2e2; | | stroke-red-200 | stroke: #fecaca; | | stroke-red-300 | stroke: #fca5a5; | | stroke-red-400 | stroke: #f87171; | | stroke-red-500 | stroke: #ef4444; | | stroke-red-600 | stroke: #dc2626; | | stroke-red-700 | stroke: #b91c1c; | | stroke-red-800 | stroke: #991b1b; | | stroke-red-900 | stroke: #7f1d1d; | | stroke-red-950 | stroke: #450a0a; | | stroke-orange-50 | stroke: #fff7ed; | | stroke-orange-100 | stroke: #ffedd5; | | stroke-orange-200 | stroke: #fed7aa; | | stroke-orange-300 | stroke: #fdba74; | | stroke-orange-400 | stroke: #fb923c; | | stroke-orange-500 | stroke: #f97316; | | stroke-orange-600 | stroke: #ea580c; | | stroke-orange-700 | stroke: #c2410c; | | stroke-orange-800 | stroke: #9a3412; | | stroke-orange-900 | stroke: #7c2d12; | | stroke-orange-950 | stroke: #431407; | | stroke-amber-50 | stroke: #fffbeb; | | stroke-amber-100 | stroke: #fef3c7; | | stroke-amber-200 | stroke: #fde68a; | | stroke-amber-300 | stroke: #fcd34d; | | stroke-amber-400 | stroke: #fbbf24; | | stroke-amber-500 | stroke: #f59e0b; | | stroke-amber-600 | stroke: #d97706; | | stroke-amber-700 | stroke: #b45309; | | stroke-amber-800 | stroke: #92400e; | | stroke-amber-900 | stroke: #78350f; | | stroke-amber-950 | stroke: #451a03; | | stroke-yellow-50 | stroke: #fefce8; | | stroke-yellow-100 | stroke: #fef9c3; | | stroke-yellow-200 | stroke: #fef08a; | | stroke-yellow-300 | stroke: #fde047; | | stroke-yellow-400 | stroke: #facc15; | | stroke-yellow-500 | stroke: #eab308; | | stroke-yellow-600 | stroke: #ca8a04; | | stroke-yellow-700 | stroke: #a16207; | | stroke-yellow-800 | stroke: #854d0e; | | stroke-yellow-900 | stroke: #713f12; | | stroke-yellow-950 | stroke: #422006; | | stroke-lime-50 | stroke: #f7fee7; | | stroke-lime-100 | stroke: #ecfccb; | | stroke-lime-200 | stroke: #d9f99d; | | stroke-lime-300 | stroke: #bef264; | | stroke-lime-400 | stroke: #a3e635; | | stroke-lime-500 | stroke: #84cc16; | | stroke-lime-600 | stroke: #65a30d; | | stroke-lime-700 | stroke: #4d7c0f; | | stroke-lime-800 | stroke: #3f6212; | | stroke-lime-900 | stroke: #365314; | | stroke-lime-950 | stroke: #1a2e05; | | stroke-green-50 | stroke: #f0fdf4; | | stroke-green-100 | stroke: #dcfce7; | | stroke-green-200 | stroke: #bbf7d0; | | stroke-green-300 | stroke: #86efac; | | stroke-green-400 | stroke: #4ade80; | | stroke-green-500 | stroke: #22c55e; | | stroke-green-600 | stroke: #16a34a; | | stroke-green-700 | stroke: #15803d; | | stroke-green-800 | stroke: #166534; | | stroke-green-900 | stroke: #14532d; | | stroke-green-950 | stroke: #052e16; | | stroke-emerald-50 | stroke: #ecfdf5; | | stroke-emerald-100 | stroke: #d1fae5; | | stroke-emerald-200 | stroke: #a7f3d0; | | stroke-emerald-300 | stroke: #6ee7b7; | | stroke-emerald-400 | stroke: #34d399; | | stroke-emerald-500 | stroke: #10b981; | | stroke-emerald-600 | stroke: #059669; | | stroke-emerald-700 | stroke: #047857; | | stroke-emerald-800 | stroke: #065f46; | | stroke-emerald-900 | stroke: #064e3b; | | stroke-emerald-950 | stroke: #022c22; | | stroke-teal-50 | stroke: #f0fdfa; | | stroke-teal-100 | stroke: #ccfbf1; | | stroke-teal-200 | stroke: #99f6e4; | | stroke-teal-300 | stroke: #5eead4; | | stroke-teal-400 | stroke: #2dd4bf; | | stroke-teal-500 | stroke: #14b8a6; | | stroke-teal-600 | stroke: #0d9488; | | stroke-teal-700 | stroke: #0f766e; | | stroke-teal-800 | stroke: #115e59; | | stroke-teal-900 | stroke: #134e4a; | | stroke-teal-950 | stroke: #042f2e; | | stroke-cyan-50 | stroke: #ecfeff; | | stroke-cyan-100 | stroke: #cffafe; | | stroke-cyan-200 | stroke: #a5f3fc; | | stroke-cyan-300 | stroke: #67e8f9; | | stroke-cyan-400 | stroke: #22d3ee; | | stroke-cyan-500 | stroke: #06b6d4; | | stroke-cyan-600 | stroke: #0891b2; | | stroke-cyan-700 | stroke: #0e7490; | | stroke-cyan-800 | stroke: #155e75; | | stroke-cyan-900 | stroke: #164e63; | | stroke-cyan-950 | stroke: #083344; | | stroke-sky-50 | stroke: #f0f9ff; | | stroke-sky-100 | stroke: #e0f2fe; | | stroke-sky-200 | stroke: #bae6fd; | | stroke-sky-300 | stroke: #7dd3fc; | | stroke-sky-400 | stroke: #38bdf8; | | stroke-sky-500 | stroke: #0ea5e9; | | stroke-sky-600 | stroke: #0284c7; | | stroke-sky-700 | stroke: #0369a1; | | stroke-sky-800 | stroke: #075985; | | stroke-sky-900 | stroke: #0c4a6e; | | stroke-sky-950 | stroke: #082f49; | | stroke-blue-50 | stroke: #eff6ff; | | stroke-blue-100 | stroke: #dbeafe; | | stroke-blue-200 | stroke: #bfdbfe; | | stroke-blue-300 | stroke: #93c5fd; | | stroke-blue-400 | stroke: #60a5fa; | | stroke-blue-500 | stroke: #3b82f6; | | stroke-blue-600 | stroke: #2563eb; | | stroke-blue-700 | stroke: #1d4ed8; | | stroke-blue-800 | stroke: #1e40af; | | stroke-blue-900 | stroke: #1e3a8a; | | stroke-blue-950 | stroke: #172554; | | stroke-indigo-50 | stroke: #eef2ff; | | stroke-indigo-100 | stroke: #e0e7ff; | | stroke-indigo-200 | stroke: #c7d2fe; | | stroke-indigo-300 | stroke: #a5b4fc; | | stroke-indigo-400 | stroke: #818cf8; | | stroke-indigo-500 | stroke: #6366f1; | | stroke-indigo-600 | stroke: #4f46e5; | | stroke-indigo-700 | stroke: #4338ca; | | stroke-indigo-800 | stroke: #3730a3; | | stroke-indigo-900 | stroke: #312e81; | | stroke-indigo-950 | stroke: #1e1b4b; | | stroke-violet-50 | stroke: #f5f3ff; | | stroke-violet-100 | stroke: #ede9fe; | | stroke-violet-200 | stroke: #ddd6fe; | | stroke-violet-300 | stroke: #c4b5fd; | | stroke-violet-400 | stroke: #a78bfa; | | stroke-violet-500 | stroke: #8b5cf6; | | stroke-violet-600 | stroke: #7c3aed; | | stroke-violet-700 | stroke: #6d28d9; | | stroke-violet-800 | stroke: #5b21b6; | | stroke-violet-900 | stroke: #4c1d95; | | stroke-violet-950 | stroke: #2e1065; | | stroke-purple-50 | stroke: #faf5ff; | | stroke-purple-100 | stroke: #f3e8ff; | | stroke-purple-200 | stroke: #e9d5ff; | | stroke-purple-300 | stroke: #d8b4fe; | | stroke-purple-400 | stroke: #c084fc; | | stroke-purple-500 | stroke: #a855f7; | | stroke-purple-600 | stroke: #9333ea; | | stroke-purple-700 | stroke: #7e22ce; | | stroke-purple-800 | stroke: #6b21a8; | | stroke-purple-900 | stroke: #581c87; | | stroke-purple-950 | stroke: #3b0764; | | stroke-fuchsia-50 | stroke: #fdf4ff; | | stroke-fuchsia-100 | stroke: #fae8ff; | | stroke-fuchsia-200 | stroke: #f5d0fe; | | stroke-fuchsia-300 | stroke: #f0abfc; | | stroke-fuchsia-400 | stroke: #e879f9; | | stroke-fuchsia-500 | stroke: #d946ef; | | stroke-fuchsia-600 | stroke: #c026d3; | | stroke-fuchsia-700 | stroke: #a21caf; | | stroke-fuchsia-800 | stroke: #86198f; | | stroke-fuchsia-900 | stroke: #701a75; | | stroke-fuchsia-950 | stroke: #4a044e; | | stroke-pink-50 | stroke: #fdf2f8; | | stroke-pink-100 | stroke: #fce7f3; | | stroke-pink-200 | stroke: #fbcfe8; | | stroke-pink-300 | stroke: #f9a8d4; | | stroke-pink-400 | stroke: #f472b6; | | stroke-pink-500 | stroke: #ec4899; | | stroke-pink-600 | stroke: #db2777; | | stroke-pink-700 | stroke: #be185d; | | stroke-pink-800 | stroke: #9d174d; | | stroke-pink-900 | stroke: #831843; | | stroke-pink-950 | stroke: #500724; | | stroke-rose-50 | stroke: #fff1f2; | | stroke-rose-100 | stroke: #ffe4e6; | | stroke-rose-200 | stroke: #fecdd3; | | stroke-rose-300 | stroke: #fda4af; | | stroke-rose-400 | stroke: #fb7185; | | stroke-rose-500 | stroke: #f43f5e; | | stroke-rose-600 | stroke: #e11d48; | | stroke-rose-700 | stroke: #be123c; | | stroke-rose-800 | stroke: #9f1239; | | stroke-rose-900 | stroke: #881337; | | stroke-rose-950 | stroke: #4c0519; | Basic usage ----------- ### Setting the stroke color Use the `stroke-{color}` utilities to change the stroke color of an SVG. ``` <svg class="stroke-cyan-500 ..."> <!-- ... --> </svg> ``` This can be useful for styling icon sets like [Heroicons](https://heroicons.com). Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:stroke-cyan-700` to only apply the `stroke-cyan-700` utility on hover. ``` <svg class="stroke-cyan-500 hover:stroke-cyan-700"> <!-- ... --> </svg``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:stroke-cyan-700` to apply the `stroke-cyan-700` utility at only medium screen sizes and above. ``` <svg class="stroke-cyan-500 md:stroke-cyan-700"> <!-- ... --> </svg``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind makes the entire [default color palette](customizing-colors#default-color-palette) available as stroke colors. You can [customize your color palette](/docs/customizing-colors#customizing) by editing `theme.colors` or `theme.extend.colors` in your `tailwind.config.js` file. tailwind.config.js ``` module.exports = { theme: { extend: { colors: { 'regal-blue': '#243c5a', }, } } } ``` Alternatively, you can customize just your stroke colors by editing `theme.stroke` or `theme.extend.stroke` in your `tailwind.config.js` file. Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `stroke` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <svg class="stroke-[#243c5a]"> <!-- ... --> </svg``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/strokeStroke Width ============ Utilities for styling the stroke width of SVG elements. Quick reference --------------- | Class | Properties | | --- | --- | | stroke-0 | stroke-width: 0; | | stroke-1 | stroke-width: 1; | | stroke-2 | stroke-width: 2; | Basic usage ----------- ### Setting the stroke width Use the `stroke-{width}` utilities to set the stroke width of an SVG. ``` <svg class="stroke-1 ..."></svg> <svg class="stroke-2 ..."></svg> ``` This can be useful for styling icon sets like [Heroicons](https://heroicons.com). Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `hover:stroke-2` to only apply the `stroke-2` utility on hover. ``` <svg class="stroke-1 hover:stroke-2"> <!-- ... --> </svg``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:stroke-2` to apply the `stroke-2` utility at only medium screen sizes and above. ``` <svg class="stroke-1 md:stroke-2"> <!-- ... --> </svg``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). Using custom values ------------------- ### Customizing your theme By default, Tailwind includes `stroke-width` utilities for creating basic grids with up to 6 equal width rows. You can customize these values by editing `theme.strokeWidth` or `theme.extend.strokeWidth` in your `tailwind.config.js` file. You have direct access to the `stroke-width` CSS property here so you can make your custom rows values as generic or as complicated and site-specific as you like. tailwind.config.js ``` module.exports = { theme: { extend: { strokeWidth: { '2': '2px', } } } } ``` Learn more about customizing the default theme in the [theme customization](theme#customizing-the-default-theme) documentation. ### Arbitrary values If you need to use a one-off `stroke-width` value that doesn’t make sense to include in your theme, use square brackets to generate a property on the fly using any arbitrary value. ``` <svg class="stroke-[2px]"> <!-- ... --> </svg``` Learn more about arbitrary value support in the [arbitrary values](adding-custom-styles#using-arbitrary-values) documentation. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/stroke-widthScreen Readers ============== Utilities for improving accessibility with screen readers. Quick reference --------------- | Class | Properties | | --- | --- | | sr-only | position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border-width: 0; | | not-sr-only | position: static; width: auto; height: auto; padding: 0; margin: 0; overflow: visible; clip: auto; white-space: normal; | Basic usage ----------- ### Screen-reader-only elements Use `sr-only` to hide an element visually without hiding it from screen readers: ``` <a href="#"> <svg><!-- ... --></svg> <span class="sr-only">Settings</span> </a> ``` ### Undoing screen-reader-only elements Use `not-sr-only` to undo `sr-only`, making an element visible to sighted users as well as screen readers. This can be useful when you want to visually hide something on small screens but show it on larger screens for example: ``` <a href="#"> <svg><!-- ... --></svg> <span class="sr-only sm:not-sr-only">Settings</span> </a> ``` Applying conditionally ---------------------- ### Hover, focus, and other states Tailwind lets you conditionally apply utility classes in different states using variant modifiers. For example, use `focus:not-sr-only` to only apply the `not-sr-only` utility on focus. ``` <a href="#content" class="sr-only focus:not-sr-only"> Skip to content </a> ``` For a complete list of all available state modifiers, check out the [Hover, Focus, & Other States](hover-focus-and-other-states) documentation. ### Breakpoints and media queries You can also use variant modifiers to target media queries like responsive breakpoints, dark mode, prefers-reduced-motion, and more. For example, use `md:not-sr-only` to apply the `not-sr-only` utility at only medium screen sizes and above. ``` <div class="sr-only md:not-sr-only"> <!-- ... --> </div``` To learn more, check out the documentation on [Responsive Design](responsive-design), [Dark Mode](dark-mode) and [other media query modifiers](hover-focus-and-other-states#media-queries). © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/screen-readers@tailwindcss/typography ======================= [View on GitHub](https://github.com/tailwindlabs/tailwindcss-typography) Beautiful typographic defaults for HTML you don't control. The official Tailwind CSS Typography plugin provides a set of `prose` classes you can use to add beautiful typographic defaults to any vanilla HTML you don’t control, like HTML rendered from Markdown, or pulled from a CMS. [![Tailwind CSS IntelliSense extension for Visual Studio Code](https://tailwindcss.com/_next/static/media/typography-demo.e7148517.jpg)](https://play.tailwindcss.com/uj1vGACRJA?layout=preview) ``` <article class="prose lg:prose-xl"> {{ markdown }} </article> ``` To see what it looks like in action, check out our [live demo](https://play.tailwindcss.com/uj1vGACRJA?layout=preview) on Tailwind Play. Installation ------------ Install the plugin from npm: ``` npm install -D @tailwindcss/typography ``` Then add the plugin to your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { theme: { // ... }, plugins: [ require('@tailwindcss/typography'), // ... ], } ``` Basic usage ----------- Now you can use the `prose` classes to add sensible typography styles to any vanilla HTML: ``` <article class="prose lg:prose-xl"> <h1>Garlic bread with cheese: What the science tells us</h1> <p> For years parents have espoused the health benefits of eating garlic bread with cheese to their children, with the food earning such an iconic status in our culture that kids will often dress up as warm, cheesy loaf for Halloween. </p> <p> But a recent study shows that the celebrated appetizer may be linked to a series of rabies cases springing up around the country. </p> <!-- ... --> </article> ``` ### Choosing a gray scale This plugin includes a modifier class for each of the five gray scales Tailwind includes by default so you can easily style your content to match the grays you’re using in your project. ``` <article class="prose prose-slate"> {{ markdown }} </article> ``` Here are the classes that are generated using a totally default Tailwind CSS v2.0 build: | Class | Gray scale | | --- | --- | | `prose-gray` *(default)* | Gray | | `prose-slate` | Slate | | `prose-zinc` | Zinc | | `prose-neutral` | Neutral | | `prose-stone` | Stone | Modifier classes are designed to be used with the [multi-class modifier pattern](http://nicolasgallagher.com/about-html-semantics-front-end-architecture/#component-modifiers) and must be used in conjunction with the base `prose` class. Always include the `prose` class when adding a gray scale modifier ``` <article class="prose prose-stone"> {{ markdown }} </article> ``` To learn about creating your own color themes, read the [adding custom color themes](typography-plugin#adding-custom-color-themes) documentation. ### Applying a type scale Size modifiers allow you to adjust the overall size of your typography for different contexts. ``` <article class="prose prose-xl"> {{ markdown }} </article> ``` Five different typography sizes are included out of the box: | Class | Body font size | | --- | --- | | `prose-sm` | 0.875rem *(14px)* | | `prose-base` *(default)* | 1rem *(16px)* | | `prose-lg` | 1.125rem *(18px)* | | `prose-xl` | 1.25rem *(20px)* | | `prose-2xl` | 1.5rem *(24px)* | These can be used in combination with Tailwind’s [breakpoint modifiers](responsive-design) to change the overall font size of a piece of content at different viewport sizes: ``` <article class="prose md:prose-lg lg:prose-xl"> {{ markdown }} </article> ``` Everything about the provided size modifiers has been hand-tuned by professional designers to look as beautiful as possible, including the relationships between font sizes, heading spacing, code block padding, and more. Size modifiers are designed to be used with the [multi-class modifier pattern](http://nicolasgallagher.com/about-html-semantics-front-end-architecture/#component-modifiers) and must be used in conjunction with the base `prose` class. Always include the `prose` class when adding a size modifier ``` <article class="prose prose-lg"> {{ markdown }} </article> ``` To learn about customizing the included type scales, read the documentation on [customizing the CSS](typography-plugin#customizing-the-css). ### Adapting to dark mode Each default color theme includes a hand-designed dark mode version that you can trigger by adding the `prose-invert` class: ``` <article class="prose dark:prose-invert"> {{ markdown }} </article> ``` To learn about creating your own color themes, read the [adding custom color themes](typography-plugin#adding-custom-color-themes) documentation. ### Element modifiers Use element modifiers to customize the style of individual elements in your content directly in your HTML: ``` <article class="prose prose-img:rounded-xl prose-headings:underline prose-a:text-blue-600"> {{ markdown }} </article> ``` This makes it easy to do things like style links to match your brand, add a border radius to images, and tons more. Here’s a complete list of available element modifiers: | Modifier | Target | | --- | --- | | `prose-headings:{utility}` | `h1`, `h2`, `h3`, `h4`, `th` | | `prose-lead:{utility}` | `[class~="lead"]` | | `prose-h1:{utility}` | `h1` | | `prose-h2:{utility}` | `h2` | | `prose-h3:{utility}` | `h3` | | `prose-h4:{utility}` | `h4` | | `prose-p:{utility}` | `p` | | `prose-a:{utility}` | `a` | | `prose-blockquote:{utility}` | `blockquote` | | `prose-figure:{utility}` | `figure` | | `prose-figcaption:{utility}` | `figcaption` | | `prose-strong:{utility}` | `strong` | | `prose-em:{utility}` | `em` | | `prose-code:{utility}` | `code` | | `prose-pre:{utility}` | `pre` | | `prose-ol:{utility}` | `ol` | | `prose-ul:{utility}` | `ul` | | `prose-li:{utility}` | `li` | | `prose-table:{utility}` | `table` | | `prose-thead:{utility}` | `thead` | | `prose-tr:{utility}` | `tr` | | `prose-th:{utility}` | `th` | | `prose-td:{utility}` | `td` | | `prose-img:{utility}` | `img` | | `prose-video:{utility}` | `video` | | `prose-hr:{utility}` | `hr` | When stacking these modifiers with other modifiers like `hover`, you most likely want the other modifier to come first: ``` <article class="prose prose-a:text-blue-600 hover:prose-a:text-blue-500"> {{ markdown }} </article> ``` Read the Tailwind CSS documentation on [ordering stacked modifiers](hover-focus-and-other-states#ordering-stacked-modifiers) to learn more. ### Overriding max-width Each size modifier comes with a baked in `max-width` designed to keep the content as readable as possible. This isn’t always what you want though, and sometimes you’ll want the content to just fill the width of its container. In those cases, all you need to do is add `max-w-none` to your content to override the embedded max-width: ``` <div class="grid grid-cols-4"> <div class="col-span-1"> <!-- ... --> </div> <div class="col-span-3"> <article class="prose max-w-none"> {{ markdown }} </article> </div> </div> ``` Advanced topics --------------- ### Undoing typography styles If you have a block of markup embedded in some content that shouldn’t inherit the `prose` styles, use the `not-prose` class to sandbox it: ``` <article class="prose"> <h1>My Heading</h1> <p>...</p <div class="not-prose"> <!-- Some example or demo that needs to be prose-free --> </div <p>...</p> <!-- ... --> </article> ``` Note that you can’t nest new `prose` instances within a `not-prose` block at this time. ### Adding custom color themes You can create your own color theme by adding a new key in the `typography` section of your `tailwind.config.js` file and providing your colors under the `css` key: tailwind.config.js ``` module.exports = { theme: { extend: { typography: ({ theme }) => ({ pink: { css: { '--tw-prose-body': theme('colors.pink[800]'), '--tw-prose-headings': theme('colors.pink[900]'), '--tw-prose-lead': theme('colors.pink[700]'), '--tw-prose-links': theme('colors.pink[900]'), '--tw-prose-bold': theme('colors.pink[900]'), '--tw-prose-counters': theme('colors.pink[600]'), '--tw-prose-bullets': theme('colors.pink[400]'), '--tw-prose-hr': theme('colors.pink[300]'), '--tw-prose-quotes': theme('colors.pink[900]'), '--tw-prose-quote-borders': theme('colors.pink[300]'), '--tw-prose-captions': theme('colors.pink[700]'), '--tw-prose-code': theme('colors.pink[900]'), '--tw-prose-pre-code': theme('colors.pink[100]'), '--tw-prose-pre-bg': theme('colors.pink[900]'), '--tw-prose-th-borders': theme('colors.pink[300]'), '--tw-prose-td-borders': theme('colors.pink[200]'), '--tw-prose-invert-body': theme('colors.pink[200]'), '--tw-prose-invert-headings': theme('colors.white'), '--tw-prose-invert-lead': theme('colors.pink[300]'), '--tw-prose-invert-links': theme('colors.white'), '--tw-prose-invert-bold': theme('colors.white'), '--tw-prose-invert-counters': theme('colors.pink[400]'), '--tw-prose-invert-bullets': theme('colors.pink[600]'), '--tw-prose-invert-hr': theme('colors.pink[700]'), '--tw-prose-invert-quotes': theme('colors.pink[100]'), '--tw-prose-invert-quote-borders': theme('colors.pink[700]'), '--tw-prose-invert-captions': theme('colors.pink[400]'), '--tw-prose-invert-code': theme('colors.white'), '--tw-prose-invert-pre-code': theme('colors.pink[300]'), '--tw-prose-invert-pre-bg': 'rgb(0 0 0 / 50%)', '--tw-prose-invert-th-borders': theme('colors.pink[600]'), '--tw-prose-invert-td-borders': theme('colors.pink[700]'), }, }, }), }, }, plugins: [ require('@tailwindcss/typography'), // ... ], } ``` See our internal [style definitions](https://github.com/tailwindlabs/tailwindcss-typography/blob/master/src/styles.js) for some more examples. ### Changing the default class name If you need to use a class name other than `prose` for any reason, you can do so using the `className` option when registering the plugin: tailwind.config.js ``` module.exports = { theme: { // ... }, plugins: [ require('@tailwindcss/typography')({ className: 'wysiwyg', }), ] ... } ``` Now every instance of `prose` in the default class names will be replaced by your custom class name: ``` <article class="wysiwyg wysiwyg-slate lg:wysiwyg-xl"> <h1>My Heading</h1> <p>...</p <div class="not-wysiwyg"> <!-- Some example or demo that needs to be prose-free --> </div <p>...</p> <!-- ... --> </article> ``` ### Customizing the CSS If you want to customize the raw CSS generated by this plugin, add your overrides under the `typography` key in the `theme` section of your `tailwind.config.js` file: tailwind.config.js ``` module.exports = { theme: { extend: { typography: { DEFAULT: { css: { color: '#333', a: { color: '#3182ce', '&:hover': { color: '#2c5282', }, }, }, }, }, }, }, plugins: [ require('@tailwindcss/typography'), // ... ], } ``` Like with all theme customizations in Tailwind, you can also define the `typography` key as a function if you need access to the `theme` helper: tailwind.config.js ``` module.exports = { theme: { extend: { typography: (theme) => ({ DEFAULT: { css: { color: theme('colors.gray.800'), // ... }, }, }), }, }, plugins: [ require('@tailwindcss/typography'), // ... ], } ``` Customizations should be applied to a specific modifier like `DEFAULT` or `xl`, and must be added under the `css` property. Customizations are authored in the same [CSS-in-JS syntax](plugins#css-in-js-syntax) used to write Tailwind plugins. See [the default styles](https://github.com/tailwindlabs/tailwindcss-typography/blob/master/src/styles.js) for this plugin for more in-depth examples of configuring each modifier. © 2022 Tailwind Labs Inc. <https://tailwindcss.com/docs/typography-plugintailwindcss
google-container1
rust
Rust
Crate google_container1 === This documentation was generated from *Container* crate version *5.0.3+20230104*, where *20230104* is the exact revision of the *container:v1* schema built by the mako code generator *v5.0.3*. Everything else about the *Container* *v1* API can be found at the official documentation site. The original source code is on github. Features --- Handle the following *Resources* with ease from the central hub … * projects * *aggregated usable subnetworks list*, *locations clusters complete ip rotation*, *locations clusters create*, *locations clusters delete*, *locations clusters get*, *locations clusters get jwks*, *locations clusters list*, *locations clusters node pools complete upgrade*, *locations clusters node pools create*, *locations clusters node pools delete*, *locations clusters node pools get*, *locations clusters node pools list*, *locations clusters node pools rollback*, *locations clusters node pools set autoscaling*, *locations clusters node pools set management*, *locations clusters node pools set size*, *locations clusters node pools update*, *locations clusters set addons*, *locations clusters set legacy abac*, *locations clusters set locations*, *locations clusters set logging*, *locations clusters set maintenance policy*, *locations clusters set master auth*, *locations clusters set monitoring*, *locations clusters set network policy*, *locations clusters set resource labels*, *locations clusters start ip rotation*, *locations clusters update*, *locations clusters update master*, *locations clusters well-known get openid-configuration*, *locations get server config*, *locations operations cancel*, *locations operations get*, *locations operations list*, *zones clusters addons*, *zones clusters complete ip rotation*, *zones clusters create*, *zones clusters delete*, *zones clusters get*, *zones clusters legacy abac*, *zones clusters list*, *zones clusters locations*, *zones clusters logging*, *zones clusters master*, *zones clusters monitoring*, *zones clusters node pools autoscaling*, *zones clusters node pools create*, *zones clusters node pools delete*, *zones clusters node pools get*, *zones clusters node pools list*, *zones clusters node pools rollback*, *zones clusters node pools set management*, *zones clusters node pools set size*, *zones clusters node pools update*, *zones clusters resource labels*, *zones clusters set maintenance policy*, *zones clusters set master auth*, *zones clusters set network policy*, *zones clusters start ip rotation*, *zones clusters update*, *zones get serverconfig*, *zones operations cancel*, *zones operations get* and *zones operations list* Not what you are looking for ? Find all other Google APIs in their Rust documentation index. Structure of this Library --- The API is structured into the following primary items: * **Hub** + a central object to maintain state and allow accessing all *Activities* + creates *Method Builders* which in turn allow access to individual *Call Builders* * **Resources** + primary types that you can apply *Activities* to + a collection of properties and *Parts* + **Parts** - a collection of properties - never directly used in *Activities* * **Activities** + operations to apply to *Resources* All *structures* are marked with applicable traits to further categorize them and ease browsing. Generally speaking, you can invoke *Activities* like this: ``` let r = hub.resource().activity(...).doit().await ``` Or specifically … ``` let r = hub.projects().locations_clusters_node_pools_create(...).doit().await let r = hub.projects().locations_clusters_node_pools_delete(...).doit().await let r = hub.projects().locations_clusters_node_pools_rollback(...).doit().await let r = hub.projects().locations_clusters_node_pools_set_autoscaling(...).doit().await let r = hub.projects().locations_clusters_node_pools_set_management(...).doit().await let r = hub.projects().locations_clusters_node_pools_set_size(...).doit().await let r = hub.projects().locations_clusters_node_pools_update(...).doit().await let r = hub.projects().locations_clusters_complete_ip_rotation(...).doit().await let r = hub.projects().locations_clusters_create(...).doit().await let r = hub.projects().locations_clusters_delete(...).doit().await let r = hub.projects().locations_clusters_set_addons(...).doit().await let r = hub.projects().locations_clusters_set_legacy_abac(...).doit().await let r = hub.projects().locations_clusters_set_locations(...).doit().await let r = hub.projects().locations_clusters_set_logging(...).doit().await let r = hub.projects().locations_clusters_set_maintenance_policy(...).doit().await let r = hub.projects().locations_clusters_set_master_auth(...).doit().await let r = hub.projects().locations_clusters_set_monitoring(...).doit().await let r = hub.projects().locations_clusters_set_network_policy(...).doit().await let r = hub.projects().locations_clusters_set_resource_labels(...).doit().await let r = hub.projects().locations_clusters_start_ip_rotation(...).doit().await let r = hub.projects().locations_clusters_update(...).doit().await let r = hub.projects().locations_clusters_update_master(...).doit().await let r = hub.projects().locations_operations_get(...).doit().await let r = hub.projects().zones_clusters_node_pools_autoscaling(...).doit().await let r = hub.projects().zones_clusters_node_pools_create(...).doit().await let r = hub.projects().zones_clusters_node_pools_delete(...).doit().await let r = hub.projects().zones_clusters_node_pools_rollback(...).doit().await let r = hub.projects().zones_clusters_node_pools_set_management(...).doit().await let r = hub.projects().zones_clusters_node_pools_set_size(...).doit().await let r = hub.projects().zones_clusters_node_pools_update(...).doit().await let r = hub.projects().zones_clusters_addons(...).doit().await let r = hub.projects().zones_clusters_complete_ip_rotation(...).doit().await let r = hub.projects().zones_clusters_create(...).doit().await let r = hub.projects().zones_clusters_delete(...).doit().await let r = hub.projects().zones_clusters_legacy_abac(...).doit().await let r = hub.projects().zones_clusters_locations(...).doit().await let r = hub.projects().zones_clusters_logging(...).doit().await let r = hub.projects().zones_clusters_master(...).doit().await let r = hub.projects().zones_clusters_monitoring(...).doit().await let r = hub.projects().zones_clusters_resource_labels(...).doit().await let r = hub.projects().zones_clusters_set_maintenance_policy(...).doit().await let r = hub.projects().zones_clusters_set_master_auth(...).doit().await let r = hub.projects().zones_clusters_set_network_policy(...).doit().await let r = hub.projects().zones_clusters_start_ip_rotation(...).doit().await let r = hub.projects().zones_clusters_update(...).doit().await let r = hub.projects().zones_operations_get(...).doit().await ``` The `resource()` and `activity(...)` calls create builders. The second one dealing with `Activities` supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be specified right away (i.e. `(...)`), whereas all optional ones can be build up as desired. The `doit()` method performs the actual communication with the server and returns the respective result. Usage --- ### Setting up your Project To use this library, you would put the following lines into your `Cargo.toml` file: ``` [dependencies] google-container1 = "*" serde = "^1.0" serde_json = "^1.0" ``` ### A complete example ``` extern crate hyper; extern crate hyper_rustls; extern crate google_container1 as container1; use container1::{Result, Error}; use std::default::Default; use container1::{Container, oauth2, hyper, hyper_rustls, chrono, FieldMask}; // Get an ApplicationSecret instance by some means. It contains the `client_id` and // `client_secret`, among other things. let secret: oauth2::ApplicationSecret = Default::default(); // Instantiate the authenticator. It will choose a suitable authentication flow for you, // unless you replace `None` with the desired Flow. // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and // retrieve them from storage. let auth = oauth2::InstalledFlowAuthenticator::builder( secret, oauth2::InstalledFlowReturnMethod::HTTPRedirect, ).build().await.unwrap(); let mut hub = Container::new(hyper::Client::builder().build(hyper_rustls::HttpsConnectorBuilder::new().with_native_roots().https_or_http().enable_http1().build()), auth); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_delete("name") .zone("sanctus") .project_id("sed") .node_pool_id("amet.") .cluster_id("takimata") .doit().await; match result { Err(e) => match e { // The Error enum provides details about what exactly happened. // You can also just use its `Debug`, `Display` or `Error` traits Error::HttpError(_) |Error::Io(_) |Error::MissingAPIKey |Error::MissingToken(_) |Error::Cancelled |Error::UploadSizeLimitExceeded(_, _) |Error::Failure(_) |Error::BadRequest(_) |Error::FieldClash(_) |Error::JsonDecodeError(_, _) => println!("{}", e), }, Ok(res) => println!("Success: {:?}", res), } ``` ### Handling Errors All errors produced by the system are provided either as Result enumeration as return value of the doit() methods, or handed as possibly intermediate results to either the Hub Delegate, or the Authenticator Delegate. When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This makes the system potentially resilient to all kinds of errors. ### Uploads and Downloads If a method supports downloads, the response body, which is part of the Result, should be read by you to obtain the media. If such a method also supports a Response Result, it will return that by default. You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making this call: `.param("alt", "media")`. Methods supporting uploads can do so using up to 2 different protocols: *simple* and *resumable*. The distinctiveness of each is represented by customized `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. ### Customization and Callbacks You may alter the way an `doit()` method is called by providing a delegate to the Method Builder before making the final `doit()` call. Respective methods will be called to provide progress information, as well as determine whether the system should retry on failure. The delegate trait is default-implemented, allowing you to customize it with minimal effort. ### Optional Parts in Server-Requests All structures provided by this library are made to be encodable and decodable via *json*. Optionals are used to indicate that partial requests are responses are valid. Most optionals are are considered Parts which are identifiable by name, which will be sent to the server to indicate either the set parts of the request or the desired parts in the response. ### Builder Arguments Using method builders, you are able to prepare an action call by repeatedly calling it’s methods. These will always take a single argument, for which the following statements are true. * PODs are handed by copy * strings are passed as `&str` * request values are moved Arguments will always be copied or cloned into the builder, to make them independent of their original life times. Re-exports --- * `pub extern crate google_apis_common as client;` * `pub use api::Container;` * `pub use hyper;` * `pub use hyper_rustls;` * `pub use client::chrono;` * `pub use client::oauth2;` Modules --- * api Structs --- * FieldMaskA `FieldMask` as defined in `https://github.com/protocolbuffers/protobuf/blob/ec1a70913e5793a7d0a7b5fbf7e0e4f75409dd41/src/google/protobuf/field_mask.proto#L180` Enums --- * Error Traits --- * DelegateA trait specifying functionality to help controlling any request performed by the API. The trait has a conservative default implementation. Type Aliases --- * ResultA universal result type used as return for all calls. Crate google_container1 === This documentation was generated from *Container* crate version *5.0.3+20230104*, where *20230104* is the exact revision of the *container:v1* schema built by the mako code generator *v5.0.3*. Everything else about the *Container* *v1* API can be found at the official documentation site. The original source code is on github. Features --- Handle the following *Resources* with ease from the central hub … * projects * *aggregated usable subnetworks list*, *locations clusters complete ip rotation*, *locations clusters create*, *locations clusters delete*, *locations clusters get*, *locations clusters get jwks*, *locations clusters list*, *locations clusters node pools complete upgrade*, *locations clusters node pools create*, *locations clusters node pools delete*, *locations clusters node pools get*, *locations clusters node pools list*, *locations clusters node pools rollback*, *locations clusters node pools set autoscaling*, *locations clusters node pools set management*, *locations clusters node pools set size*, *locations clusters node pools update*, *locations clusters set addons*, *locations clusters set legacy abac*, *locations clusters set locations*, *locations clusters set logging*, *locations clusters set maintenance policy*, *locations clusters set master auth*, *locations clusters set monitoring*, *locations clusters set network policy*, *locations clusters set resource labels*, *locations clusters start ip rotation*, *locations clusters update*, *locations clusters update master*, *locations clusters well-known get openid-configuration*, *locations get server config*, *locations operations cancel*, *locations operations get*, *locations operations list*, *zones clusters addons*, *zones clusters complete ip rotation*, *zones clusters create*, *zones clusters delete*, *zones clusters get*, *zones clusters legacy abac*, *zones clusters list*, *zones clusters locations*, *zones clusters logging*, *zones clusters master*, *zones clusters monitoring*, *zones clusters node pools autoscaling*, *zones clusters node pools create*, *zones clusters node pools delete*, *zones clusters node pools get*, *zones clusters node pools list*, *zones clusters node pools rollback*, *zones clusters node pools set management*, *zones clusters node pools set size*, *zones clusters node pools update*, *zones clusters resource labels*, *zones clusters set maintenance policy*, *zones clusters set master auth*, *zones clusters set network policy*, *zones clusters start ip rotation*, *zones clusters update*, *zones get serverconfig*, *zones operations cancel*, *zones operations get* and *zones operations list* Not what you are looking for ? Find all other Google APIs in their Rust documentation index. Structure of this Library --- The API is structured into the following primary items: * **Hub** + a central object to maintain state and allow accessing all *Activities* + creates *Method Builders* which in turn allow access to individual *Call Builders* * **Resources** + primary types that you can apply *Activities* to + a collection of properties and *Parts* + **Parts** - a collection of properties - never directly used in *Activities* * **Activities** + operations to apply to *Resources* All *structures* are marked with applicable traits to further categorize them and ease browsing. Generally speaking, you can invoke *Activities* like this: ``` let r = hub.resource().activity(...).doit().await ``` Or specifically … ``` let r = hub.projects().locations_clusters_node_pools_create(...).doit().await let r = hub.projects().locations_clusters_node_pools_delete(...).doit().await let r = hub.projects().locations_clusters_node_pools_rollback(...).doit().await let r = hub.projects().locations_clusters_node_pools_set_autoscaling(...).doit().await let r = hub.projects().locations_clusters_node_pools_set_management(...).doit().await let r = hub.projects().locations_clusters_node_pools_set_size(...).doit().await let r = hub.projects().locations_clusters_node_pools_update(...).doit().await let r = hub.projects().locations_clusters_complete_ip_rotation(...).doit().await let r = hub.projects().locations_clusters_create(...).doit().await let r = hub.projects().locations_clusters_delete(...).doit().await let r = hub.projects().locations_clusters_set_addons(...).doit().await let r = hub.projects().locations_clusters_set_legacy_abac(...).doit().await let r = hub.projects().locations_clusters_set_locations(...).doit().await let r = hub.projects().locations_clusters_set_logging(...).doit().await let r = hub.projects().locations_clusters_set_maintenance_policy(...).doit().await let r = hub.projects().locations_clusters_set_master_auth(...).doit().await let r = hub.projects().locations_clusters_set_monitoring(...).doit().await let r = hub.projects().locations_clusters_set_network_policy(...).doit().await let r = hub.projects().locations_clusters_set_resource_labels(...).doit().await let r = hub.projects().locations_clusters_start_ip_rotation(...).doit().await let r = hub.projects().locations_clusters_update(...).doit().await let r = hub.projects().locations_clusters_update_master(...).doit().await let r = hub.projects().locations_operations_get(...).doit().await let r = hub.projects().zones_clusters_node_pools_autoscaling(...).doit().await let r = hub.projects().zones_clusters_node_pools_create(...).doit().await let r = hub.projects().zones_clusters_node_pools_delete(...).doit().await let r = hub.projects().zones_clusters_node_pools_rollback(...).doit().await let r = hub.projects().zones_clusters_node_pools_set_management(...).doit().await let r = hub.projects().zones_clusters_node_pools_set_size(...).doit().await let r = hub.projects().zones_clusters_node_pools_update(...).doit().await let r = hub.projects().zones_clusters_addons(...).doit().await let r = hub.projects().zones_clusters_complete_ip_rotation(...).doit().await let r = hub.projects().zones_clusters_create(...).doit().await let r = hub.projects().zones_clusters_delete(...).doit().await let r = hub.projects().zones_clusters_legacy_abac(...).doit().await let r = hub.projects().zones_clusters_locations(...).doit().await let r = hub.projects().zones_clusters_logging(...).doit().await let r = hub.projects().zones_clusters_master(...).doit().await let r = hub.projects().zones_clusters_monitoring(...).doit().await let r = hub.projects().zones_clusters_resource_labels(...).doit().await let r = hub.projects().zones_clusters_set_maintenance_policy(...).doit().await let r = hub.projects().zones_clusters_set_master_auth(...).doit().await let r = hub.projects().zones_clusters_set_network_policy(...).doit().await let r = hub.projects().zones_clusters_start_ip_rotation(...).doit().await let r = hub.projects().zones_clusters_update(...).doit().await let r = hub.projects().zones_operations_get(...).doit().await ``` The `resource()` and `activity(...)` calls create builders. The second one dealing with `Activities` supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be specified right away (i.e. `(...)`), whereas all optional ones can be build up as desired. The `doit()` method performs the actual communication with the server and returns the respective result. Usage --- ### Setting up your Project To use this library, you would put the following lines into your `Cargo.toml` file: ``` [dependencies] google-container1 = "*" serde = "^1.0" serde_json = "^1.0" ``` ### A complete example ``` extern crate hyper; extern crate hyper_rustls; extern crate google_container1 as container1; use container1::{Result, Error}; use std::default::Default; use container1::{Container, oauth2, hyper, hyper_rustls, chrono, FieldMask}; // Get an ApplicationSecret instance by some means. It contains the `client_id` and // `client_secret`, among other things. let secret: oauth2::ApplicationSecret = Default::default(); // Instantiate the authenticator. It will choose a suitable authentication flow for you, // unless you replace `None` with the desired Flow. // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and // retrieve them from storage. let auth = oauth2::InstalledFlowAuthenticator::builder( secret, oauth2::InstalledFlowReturnMethod::HTTPRedirect, ).build().await.unwrap(); let mut hub = Container::new(hyper::Client::builder().build(hyper_rustls::HttpsConnectorBuilder::new().with_native_roots().https_or_http().enable_http1().build()), auth); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_delete("name") .zone("sanctus") .project_id("sed") .node_pool_id("amet.") .cluster_id("takimata") .doit().await; match result { Err(e) => match e { // The Error enum provides details about what exactly happened. // You can also just use its `Debug`, `Display` or `Error` traits Error::HttpError(_) |Error::Io(_) |Error::MissingAPIKey |Error::MissingToken(_) |Error::Cancelled |Error::UploadSizeLimitExceeded(_, _) |Error::Failure(_) |Error::BadRequest(_) |Error::FieldClash(_) |Error::JsonDecodeError(_, _) => println!("{}", e), }, Ok(res) => println!("Success: {:?}", res), } ``` ### Handling Errors All errors produced by the system are provided either as Result enumeration as return value of the doit() methods, or handed as possibly intermediate results to either the Hub Delegate, or the Authenticator Delegate. When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This makes the system potentially resilient to all kinds of errors. ### Uploads and Downloads If a method supports downloads, the response body, which is part of the Result, should be read by you to obtain the media. If such a method also supports a Response Result, it will return that by default. You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making this call: `.param("alt", "media")`. Methods supporting uploads can do so using up to 2 different protocols: *simple* and *resumable*. The distinctiveness of each is represented by customized `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. ### Customization and Callbacks You may alter the way an `doit()` method is called by providing a delegate to the Method Builder before making the final `doit()` call. Respective methods will be called to provide progress information, as well as determine whether the system should retry on failure. The delegate trait is default-implemented, allowing you to customize it with minimal effort. ### Optional Parts in Server-Requests All structures provided by this library are made to be encodable and decodable via *json*. Optionals are used to indicate that partial requests are responses are valid. Most optionals are are considered Parts which are identifiable by name, which will be sent to the server to indicate either the set parts of the request or the desired parts in the response. ### Builder Arguments Using method builders, you are able to prepare an action call by repeatedly calling it’s methods. These will always take a single argument, for which the following statements are true. * PODs are handed by copy * strings are passed as `&str` * request values are moved Arguments will always be copied or cloned into the builder, to make them independent of their original life times. Re-exports --- * `pub extern crate google_apis_common as client;` * `pub use api::Container;` * `pub use hyper;` * `pub use hyper_rustls;` * `pub use client::chrono;` * `pub use client::oauth2;` Modules --- * api Structs --- * FieldMaskA `FieldMask` as defined in `https://github.com/protocolbuffers/protobuf/blob/ec1a70913e5793a7d0a7b5fbf7e0e4f75409dd41/src/google/protobuf/field_mask.proto#L180` Enums --- * Error Traits --- * DelegateA trait specifying functionality to help controlling any request performed by the API. The trait has a conservative default implementation. Type Aliases --- * ResultA universal result type used as return for all calls. Struct google_container1::api::Container === ``` pub struct Container<S> { pub client: Client<S, Body>, pub auth: Box<dyn GetToken>, /* private fields */ } ``` Central instance to access all Container related resource activities Examples --- Instantiate a new hub ``` extern crate hyper; extern crate hyper_rustls; extern crate google_container1 as container1; use container1::{Result, Error}; use std::default::Default; use container1::{Container, oauth2, hyper, hyper_rustls, chrono, FieldMask}; // Get an ApplicationSecret instance by some means. It contains the `client_id` and // `client_secret`, among other things. let secret: oauth2::ApplicationSecret = Default::default(); // Instantiate the authenticator. It will choose a suitable authentication flow for you, // unless you replace `None` with the desired Flow. // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and // retrieve them from storage. let auth = oauth2::InstalledFlowAuthenticator::builder( secret, oauth2::InstalledFlowReturnMethod::HTTPRedirect, ).build().await.unwrap(); let mut hub = Container::new(hyper::Client::builder().build(hyper_rustls::HttpsConnectorBuilder::new().with_native_roots().https_or_http().enable_http1().build()), auth); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_delete("name") .zone("duo") .project_id("ipsum") .node_pool_id("gubergren") .cluster_id("Lorem") .doit().await; match result { Err(e) => match e { // The Error enum provides details about what exactly happened. // You can also just use its `Debug`, `Display` or `Error` traits Error::HttpError(_) |Error::Io(_) |Error::MissingAPIKey |Error::MissingToken(_) |Error::Cancelled |Error::UploadSizeLimitExceeded(_, _) |Error::Failure(_) |Error::BadRequest(_) |Error::FieldClash(_) |Error::JsonDecodeError(_, _) => println!("{}", e), }, Ok(res) => println!("Success: {:?}", res), } ``` Fields --- `client: Client<S, Body>``auth: Box<dyn GetToken>`Implementations --- ### impl<'a, S> Container<S#### pub fn new<A: 'static + GetToken>( client: Client<S, Body>, auth: A ) -> Container<S#### pub fn projects(&'a self) -> ProjectMethods<'a, S#### pub fn user_agent(&mut self, agent_name: String) -> String Set the user-agent header field to use in all requests to the server. It defaults to `google-api-rust-client/5.0.3`. Returns the previously set user-agent. #### pub fn base_url(&mut self, new_base_url: String) -> String Set the base url to use in all requests to the server. It defaults to `https://container.googleapis.com/`. Returns the previously set base url. #### pub fn root_url(&mut self, new_root_url: String) -> String Set the root url to use in all requests to the server. It defaults to `https://container.googleapis.com/`. Returns the previously set root url. Trait Implementations --- ### impl<S: Clone> Clone for Container<S#### fn clone(&self) -> Container<SReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. --- ### impl<S> !RefUnwindSafe for Container<S### impl<S> Send for Container<S>where S: Send, ### impl<S> Sync for Container<S>where S: Sync, ### impl<S> Unpin for Container<S>where S: Unpin, ### impl<S> !UnwindSafe for Container<SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectAggregatedUsableSubnetworkListCall === ``` pub struct ProjectAggregatedUsableSubnetworkListCall<'a, S>where S: 'a,{ /* private fields */ } ``` Lists subnetworks that are usable for creating clusters in a project. A builder for the *aggregated.usableSubnetworks.list* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().aggregated_usable_subnetworks_list("parent") .page_token("eos") .page_size(-4) .filter("ea") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectAggregatedUsableSubnetworkListCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit( self ) -> Result<(Response<Body>, ListUsableSubnetworksResponse)Perform the operation you have build so far. #### pub fn parent( self, new_value: &str ) -> ProjectAggregatedUsableSubnetworkListCall<'a, SThe parent project where subnetworks are usable. Specified in the format `projects/*`. Sets the *parent* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn page_token( self, new_value: &str ) -> ProjectAggregatedUsableSubnetworkListCall<'a, SSpecifies a page token to use. Set this to the nextPageToken returned by previous list requests to get the next page of results. Sets the *page token* query property to the given value. #### pub fn page_size( self, new_value: i32 ) -> ProjectAggregatedUsableSubnetworkListCall<'a, SThe max number of results per page that should be returned. If the number of available results is larger than `page_size`, a `next_page_token` is returned which can be used to get the next page of results in subsequent requests. Acceptable values are 0 to 500, inclusive. (Default: 500) Sets the *page size* query property to the given value. #### pub fn filter( self, new_value: &str ) -> ProjectAggregatedUsableSubnetworkListCall<'a, SFiltering currently only supports equality on the networkProjectId and must be in the form: “networkProjectId=[PROJECTID]”, where `networkProjectId` is the project which owns the listed subnetworks. This defaults to the parent project ID. Sets the *filter* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectAggregatedUsableSubnetworkListCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectAggregatedUsableSubnetworkListCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectAggregatedUsableSubnetworkListCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectAggregatedUsableSubnetworkListCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectAggregatedUsableSubnetworkListCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectAggregatedUsableSubnetworkListCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectAggregatedUsableSubnetworkListCall<'a, S### impl<'a, S> Send for ProjectAggregatedUsableSubnetworkListCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectAggregatedUsableSubnetworkListCall<'a, S### impl<'a, S> Unpin for ProjectAggregatedUsableSubnetworkListCall<'a, S### impl<'a, S> !UnwindSafe for ProjectAggregatedUsableSubnetworkListCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterCompleteIpRotationCall === ``` pub struct ProjectLocationClusterCompleteIpRotationCall<'a, S>where S: 'a,{ /* private fields */ } ``` Completes master IP rotation. A builder for the *locations.clusters.completeIpRotation* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::CompleteIPRotationRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = CompleteIPRotationRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_complete_ip_rotation(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterCompleteIpRotationCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: CompleteIPRotationRequest ) -> ProjectLocationClusterCompleteIpRotationCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterCompleteIpRotationCall<'a, SThe name (project, location, cluster name) of the cluster to complete IP rotation. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterCompleteIpRotationCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterCompleteIpRotationCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterCompleteIpRotationCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterCompleteIpRotationCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterCompleteIpRotationCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterCompleteIpRotationCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterCompleteIpRotationCall<'a, S### impl<'a, S> Send for ProjectLocationClusterCompleteIpRotationCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterCompleteIpRotationCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterCompleteIpRotationCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterCompleteIpRotationCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterCreateCall === ``` pub struct ProjectLocationClusterCreateCall<'a, S>where S: 'a,{ /* private fields */ } ``` Creates a cluster, consisting of the specified number and type of Google Compute Engine instances. By default, the cluster is created in the project’s default network. One firewall is added for the cluster. After cluster creation, the Kubelet creates routes for each node to allow the containers on that node to communicate with all other instances in the cluster. Finally, an entry is added to the project’s global metadata indicating which CIDR range the cluster is using. A builder for the *locations.clusters.create* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::CreateClusterRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = CreateClusterRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_create(req, "parent") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterCreateCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: CreateClusterRequest ) -> ProjectLocationClusterCreateCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn parent(self, new_value: &str) -> ProjectLocationClusterCreateCall<'a, SThe parent (project and location) where the cluster will be created. Specified in the format `projects/*/locations/*`. Sets the *parent* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterCreateCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterCreateCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectLocationClusterCreateCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterCreateCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterCreateCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterCreateCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterCreateCall<'a, S### impl<'a, S> Send for ProjectLocationClusterCreateCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterCreateCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterCreateCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterCreateCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterDeleteCall === ``` pub struct ProjectLocationClusterDeleteCall<'a, S>where S: 'a,{ /* private fields */ } ``` Deletes the cluster, including the Kubernetes endpoint and all worker nodes. Firewalls and routes that were configured during cluster creation are also deleted. Other Google Compute Engine resources that might be in use by the cluster, such as load balancer resources, are not deleted if they weren’t present when the cluster was initially created. A builder for the *locations.clusters.delete* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_delete("name") .zone("et") .project_id("sed") .cluster_id("et") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterDeleteCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn name(self, new_value: &str) -> ProjectLocationClusterDeleteCall<'a, SThe name (project, location, cluster) of the cluster to delete. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectLocationClusterDeleteCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* query property to the given value. #### pub fn project_id( self, new_value: &str ) -> ProjectLocationClusterDeleteCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* query property to the given value. #### pub fn cluster_id( self, new_value: &str ) -> ProjectLocationClusterDeleteCall<'a, SDeprecated. The name of the cluster to delete. This field has been deprecated and replaced by the name field. Sets the *cluster id* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterDeleteCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterDeleteCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectLocationClusterDeleteCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterDeleteCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterDeleteCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterDeleteCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterDeleteCall<'a, S### impl<'a, S> Send for ProjectLocationClusterDeleteCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterDeleteCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterDeleteCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterDeleteCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterGetCall === ``` pub struct ProjectLocationClusterGetCall<'a, S>where S: 'a,{ /* private fields */ } ``` Gets the details of a specific cluster. A builder for the *locations.clusters.get* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_get("name") .zone("vero") .project_id("erat") .cluster_id("sed") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterGetCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Cluster)Perform the operation you have build so far. #### pub fn name(self, new_value: &str) -> ProjectLocationClusterGetCall<'a, SThe name (project, location, cluster) of the cluster to retrieve. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectLocationClusterGetCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* query property to the given value. #### pub fn project_id(self, new_value: &str) -> ProjectLocationClusterGetCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* query property to the given value. #### pub fn cluster_id(self, new_value: &str) -> ProjectLocationClusterGetCall<'a, SDeprecated. The name of the cluster to retrieve. This field has been deprecated and replaced by the name field. Sets the *cluster id* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterGetCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>(self, name: T, value: T) -> ProjectLocationClusterGetCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectLocationClusterGetCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterGetCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterGetCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterGetCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterGetCall<'a, S### impl<'a, S> Send for ProjectLocationClusterGetCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterGetCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterGetCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterGetCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterGetJwkCall === ``` pub struct ProjectLocationClusterGetJwkCall<'a, S>where S: 'a,{ /* private fields */ } ``` Gets the public component of the cluster signing keys in JSON Web Key format. This API is not yet intended for general use, and is not available for all clusters. A builder for the *locations.clusters.getJwks* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_get_jwks("parent") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterGetJwkCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, GetJSONWebKeysResponse)Perform the operation you have build so far. #### pub fn parent(self, new_value: &str) -> ProjectLocationClusterGetJwkCall<'a, SThe cluster (project, location, cluster name) to get keys for. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *parent* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterGetJwkCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterGetJwkCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterGetJwkCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterGetJwkCall<'a, S### impl<'a, S> Send for ProjectLocationClusterGetJwkCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterGetJwkCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterGetJwkCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterGetJwkCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterListCall === ``` pub struct ProjectLocationClusterListCall<'a, S>where S: 'a,{ /* private fields */ } ``` Lists all clusters owned by a project in either the specified zone or all zones. A builder for the *locations.clusters.list* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_list("parent") .zone("et") .project_id("voluptua.") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterListCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, ListClustersResponse)Perform the operation you have build so far. #### pub fn parent(self, new_value: &str) -> ProjectLocationClusterListCall<'a, SThe parent (project and location) where the clusters will be listed. Specified in the format `projects/*/locations/*`. Location “-” matches all zones and all regions. Sets the *parent* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectLocationClusterListCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides, or “-” for all zones. This field has been deprecated and replaced by the parent field. Sets the *zone* query property to the given value. #### pub fn project_id( self, new_value: &str ) -> ProjectLocationClusterListCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the parent field. Sets the *project id* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterListCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterListCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectLocationClusterListCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterListCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterListCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterListCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterListCall<'a, S### impl<'a, S> Send for ProjectLocationClusterListCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterListCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterListCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterListCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterNodePoolCompleteUpgradeCall === ``` pub struct ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, S>where S: 'a,{ /* private fields */ } ``` CompleteNodePoolUpgrade will signal an on-going node pool upgrade to complete. A builder for the *locations.clusters.nodePools.completeUpgrade* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::CompleteNodePoolUpgradeRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = CompleteNodePoolUpgradeRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_complete_upgrade(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Empty)Perform the operation you have build so far. #### pub fn request( self, new_value: CompleteNodePoolUpgradeRequest ) -> ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, SThe name (project, location, cluster, node pool id) of the node pool to complete upgrade. Specified in the format `projects/*/locations/*/clusters/*/nodePools/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes( self ) -> ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, S### impl<'a, S> Send for ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterNodePoolCompleteUpgradeCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterNodePoolCreateCall === ``` pub struct ProjectLocationClusterNodePoolCreateCall<'a, S>where S: 'a,{ /* private fields */ } ``` Creates a node pool for a cluster. A builder for the *locations.clusters.nodePools.create* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::CreateNodePoolRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = CreateNodePoolRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_create(req, "parent") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterNodePoolCreateCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: CreateNodePoolRequest ) -> ProjectLocationClusterNodePoolCreateCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn parent( self, new_value: &str ) -> ProjectLocationClusterNodePoolCreateCall<'a, SThe parent (project, location, cluster name) where the node pool will be created. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *parent* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterNodePoolCreateCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterNodePoolCreateCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterNodePoolCreateCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterNodePoolCreateCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterNodePoolCreateCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterNodePoolCreateCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterNodePoolCreateCall<'a, S### impl<'a, S> Send for ProjectLocationClusterNodePoolCreateCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterNodePoolCreateCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterNodePoolCreateCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterNodePoolCreateCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterNodePoolDeleteCall === ``` pub struct ProjectLocationClusterNodePoolDeleteCall<'a, S>where S: 'a,{ /* private fields */ } ``` Deletes a node pool from a cluster. A builder for the *locations.clusters.nodePools.delete* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_delete("name") .zone("duo") .project_id("ipsum") .node_pool_id("sed") .cluster_id("ut") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterNodePoolDeleteCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterNodePoolDeleteCall<'a, SThe name (project, location, cluster, node pool id) of the node pool to delete. Specified in the format `projects/*/locations/*/clusters/*/nodePools/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectLocationClusterNodePoolDeleteCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* query property to the given value. #### pub fn project_id( self, new_value: &str ) -> ProjectLocationClusterNodePoolDeleteCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* query property to the given value. #### pub fn node_pool_id( self, new_value: &str ) -> ProjectLocationClusterNodePoolDeleteCall<'a, SDeprecated. The name of the node pool to delete. This field has been deprecated and replaced by the name field. Sets the *node pool id* query property to the given value. #### pub fn cluster_id( self, new_value: &str ) -> ProjectLocationClusterNodePoolDeleteCall<'a, SDeprecated. The name of the cluster. This field has been deprecated and replaced by the name field. Sets the *cluster id* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterNodePoolDeleteCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterNodePoolDeleteCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterNodePoolDeleteCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterNodePoolDeleteCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterNodePoolDeleteCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterNodePoolDeleteCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterNodePoolDeleteCall<'a, S### impl<'a, S> Send for ProjectLocationClusterNodePoolDeleteCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterNodePoolDeleteCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterNodePoolDeleteCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterNodePoolDeleteCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterNodePoolGetCall === ``` pub struct ProjectLocationClusterNodePoolGetCall<'a, S>where S: 'a,{ /* private fields */ } ``` Retrieves the requested node pool. A builder for the *locations.clusters.nodePools.get* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_get("name") .zone("rebum.") .project_id("est") .node_pool_id("ipsum") .cluster_id("ipsum") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterNodePoolGetCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, NodePool)Perform the operation you have build so far. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterNodePoolGetCall<'a, SThe name (project, location, cluster, node pool id) of the node pool to get. Specified in the format `projects/*/locations/*/clusters/*/nodePools/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectLocationClusterNodePoolGetCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* query property to the given value. #### pub fn project_id( self, new_value: &str ) -> ProjectLocationClusterNodePoolGetCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* query property to the given value. #### pub fn node_pool_id( self, new_value: &str ) -> ProjectLocationClusterNodePoolGetCall<'a, SDeprecated. The name of the node pool. This field has been deprecated and replaced by the name field. Sets the *node pool id* query property to the given value. #### pub fn cluster_id( self, new_value: &str ) -> ProjectLocationClusterNodePoolGetCall<'a, SDeprecated. The name of the cluster. This field has been deprecated and replaced by the name field. Sets the *cluster id* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterNodePoolGetCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterNodePoolGetCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterNodePoolGetCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterNodePoolGetCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterNodePoolGetCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterNodePoolGetCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterNodePoolGetCall<'a, S### impl<'a, S> Send for ProjectLocationClusterNodePoolGetCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterNodePoolGetCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterNodePoolGetCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterNodePoolGetCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterNodePoolListCall === ``` pub struct ProjectLocationClusterNodePoolListCall<'a, S>where S: 'a,{ /* private fields */ } ``` Lists the node pools for a cluster. A builder for the *locations.clusters.nodePools.list* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_list("parent") .zone("gubergren") .project_id("ea") .cluster_id("dolor") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterNodePoolListCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, ListNodePoolsResponse)Perform the operation you have build so far. #### pub fn parent( self, new_value: &str ) -> ProjectLocationClusterNodePoolListCall<'a, SThe parent (project, location, cluster name) where the node pools will be listed. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *parent* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectLocationClusterNodePoolListCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the parent field. Sets the *zone* query property to the given value. #### pub fn project_id( self, new_value: &str ) -> ProjectLocationClusterNodePoolListCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the parent field. Sets the *project id* query property to the given value. #### pub fn cluster_id( self, new_value: &str ) -> ProjectLocationClusterNodePoolListCall<'a, SDeprecated. The name of the cluster. This field has been deprecated and replaced by the parent field. Sets the *cluster id* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterNodePoolListCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterNodePoolListCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterNodePoolListCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterNodePoolListCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterNodePoolListCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterNodePoolListCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterNodePoolListCall<'a, S### impl<'a, S> Send for ProjectLocationClusterNodePoolListCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterNodePoolListCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterNodePoolListCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterNodePoolListCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterNodePoolRollbackCall === ``` pub struct ProjectLocationClusterNodePoolRollbackCall<'a, S>where S: 'a,{ /* private fields */ } ``` Rolls back a previously Aborted or Failed NodePool upgrade. This makes no changes if the last upgrade successfully completed. A builder for the *locations.clusters.nodePools.rollback* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::RollbackNodePoolUpgradeRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = RollbackNodePoolUpgradeRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_rollback(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterNodePoolRollbackCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: RollbackNodePoolUpgradeRequest ) -> ProjectLocationClusterNodePoolRollbackCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterNodePoolRollbackCall<'a, SThe name (project, location, cluster, node pool id) of the node poll to rollback upgrade. Specified in the format `projects/*/locations/*/clusters/*/nodePools/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterNodePoolRollbackCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterNodePoolRollbackCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterNodePoolRollbackCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterNodePoolRollbackCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterNodePoolRollbackCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterNodePoolRollbackCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterNodePoolRollbackCall<'a, S### impl<'a, S> Send for ProjectLocationClusterNodePoolRollbackCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterNodePoolRollbackCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterNodePoolRollbackCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterNodePoolRollbackCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterNodePoolSetAutoscalingCall === ``` pub struct ProjectLocationClusterNodePoolSetAutoscalingCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the autoscaling settings for the specified node pool. A builder for the *locations.clusters.nodePools.setAutoscaling* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetNodePoolAutoscalingRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetNodePoolAutoscalingRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_set_autoscaling(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterNodePoolSetAutoscalingCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetNodePoolAutoscalingRequest ) -> ProjectLocationClusterNodePoolSetAutoscalingCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterNodePoolSetAutoscalingCall<'a, SThe name (project, location, cluster, node pool) of the node pool to set autoscaler settings. Specified in the format `projects/*/locations/*/clusters/*/nodePools/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterNodePoolSetAutoscalingCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterNodePoolSetAutoscalingCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterNodePoolSetAutoscalingCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterNodePoolSetAutoscalingCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes( self ) -> ProjectLocationClusterNodePoolSetAutoscalingCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterNodePoolSetAutoscalingCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterNodePoolSetAutoscalingCall<'a, S### impl<'a, S> Send for ProjectLocationClusterNodePoolSetAutoscalingCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterNodePoolSetAutoscalingCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterNodePoolSetAutoscalingCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterNodePoolSetAutoscalingCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterNodePoolSetManagementCall === ``` pub struct ProjectLocationClusterNodePoolSetManagementCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the NodeManagement options for a node pool. A builder for the *locations.clusters.nodePools.setManagement* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetNodePoolManagementRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetNodePoolManagementRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_set_management(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterNodePoolSetManagementCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetNodePoolManagementRequest ) -> ProjectLocationClusterNodePoolSetManagementCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterNodePoolSetManagementCall<'a, SThe name (project, location, cluster, node pool id) of the node pool to set management properties. Specified in the format `projects/*/locations/*/clusters/*/nodePools/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterNodePoolSetManagementCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterNodePoolSetManagementCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterNodePoolSetManagementCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterNodePoolSetManagementCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes( self ) -> ProjectLocationClusterNodePoolSetManagementCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterNodePoolSetManagementCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterNodePoolSetManagementCall<'a, S### impl<'a, S> Send for ProjectLocationClusterNodePoolSetManagementCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterNodePoolSetManagementCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterNodePoolSetManagementCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterNodePoolSetManagementCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterNodePoolSetSizeCall === ``` pub struct ProjectLocationClusterNodePoolSetSizeCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the size for a specific node pool. The new size will be used for all replicas, including future replicas created by modifying NodePool.locations. A builder for the *locations.clusters.nodePools.setSize* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetNodePoolSizeRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetNodePoolSizeRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_set_size(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterNodePoolSetSizeCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetNodePoolSizeRequest ) -> ProjectLocationClusterNodePoolSetSizeCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterNodePoolSetSizeCall<'a, SThe name (project, location, cluster, node pool id) of the node pool to set size. Specified in the format `projects/*/locations/*/clusters/*/nodePools/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterNodePoolSetSizeCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterNodePoolSetSizeCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterNodePoolSetSizeCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterNodePoolSetSizeCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterNodePoolSetSizeCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterNodePoolSetSizeCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterNodePoolSetSizeCall<'a, S### impl<'a, S> Send for ProjectLocationClusterNodePoolSetSizeCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterNodePoolSetSizeCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterNodePoolSetSizeCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterNodePoolSetSizeCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterNodePoolUpdateCall === ``` pub struct ProjectLocationClusterNodePoolUpdateCall<'a, S>where S: 'a,{ /* private fields */ } ``` Updates the version and/or image type for the specified node pool. A builder for the *locations.clusters.nodePools.update* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::UpdateNodePoolRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = UpdateNodePoolRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_node_pools_update(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterNodePoolUpdateCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: UpdateNodePoolRequest ) -> ProjectLocationClusterNodePoolUpdateCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterNodePoolUpdateCall<'a, SThe name (project, location, cluster, node pool) of the node pool to update. Specified in the format `projects/*/locations/*/clusters/*/nodePools/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterNodePoolUpdateCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterNodePoolUpdateCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterNodePoolUpdateCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterNodePoolUpdateCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterNodePoolUpdateCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterNodePoolUpdateCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterNodePoolUpdateCall<'a, S### impl<'a, S> Send for ProjectLocationClusterNodePoolUpdateCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterNodePoolUpdateCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterNodePoolUpdateCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterNodePoolUpdateCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterSetAddonCall === ``` pub struct ProjectLocationClusterSetAddonCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the addons for a specific cluster. A builder for the *locations.clusters.setAddons* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetAddonsConfigRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetAddonsConfigRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_set_addons(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterSetAddonCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetAddonsConfigRequest ) -> ProjectLocationClusterSetAddonCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name(self, new_value: &str) -> ProjectLocationClusterSetAddonCall<'a, SThe name (project, location, cluster) of the cluster to set addons. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterSetAddonCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterSetAddonCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterSetAddonCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterSetAddonCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterSetAddonCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterSetAddonCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterSetAddonCall<'a, S### impl<'a, S> Send for ProjectLocationClusterSetAddonCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterSetAddonCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterSetAddonCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterSetAddonCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterSetLegacyAbacCall === ``` pub struct ProjectLocationClusterSetLegacyAbacCall<'a, S>where S: 'a,{ /* private fields */ } ``` Enables or disables the ABAC authorization mechanism on a cluster. A builder for the *locations.clusters.setLegacyAbac* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetLegacyAbacRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetLegacyAbacRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_set_legacy_abac(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterSetLegacyAbacCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetLegacyAbacRequest ) -> ProjectLocationClusterSetLegacyAbacCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterSetLegacyAbacCall<'a, SThe name (project, location, cluster name) of the cluster to set legacy abac. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterSetLegacyAbacCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterSetLegacyAbacCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterSetLegacyAbacCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterSetLegacyAbacCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterSetLegacyAbacCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterSetLegacyAbacCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterSetLegacyAbacCall<'a, S### impl<'a, S> Send for ProjectLocationClusterSetLegacyAbacCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterSetLegacyAbacCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterSetLegacyAbacCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterSetLegacyAbacCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterSetLocationCall === ``` pub struct ProjectLocationClusterSetLocationCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the locations for a specific cluster. Deprecated. Use projects.locations.clusters.update instead. A builder for the *locations.clusters.setLocations* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetLocationsRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetLocationsRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_set_locations(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterSetLocationCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetLocationsRequest ) -> ProjectLocationClusterSetLocationCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterSetLocationCall<'a, SThe name (project, location, cluster) of the cluster to set locations. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterSetLocationCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterSetLocationCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterSetLocationCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterSetLocationCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterSetLocationCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterSetLocationCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterSetLocationCall<'a, S### impl<'a, S> Send for ProjectLocationClusterSetLocationCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterSetLocationCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterSetLocationCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterSetLocationCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterSetLoggingCall === ``` pub struct ProjectLocationClusterSetLoggingCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the logging service for a specific cluster. A builder for the *locations.clusters.setLogging* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetLoggingServiceRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetLoggingServiceRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_set_logging(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterSetLoggingCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetLoggingServiceRequest ) -> ProjectLocationClusterSetLoggingCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterSetLoggingCall<'a, SThe name (project, location, cluster) of the cluster to set logging. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterSetLoggingCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterSetLoggingCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterSetLoggingCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterSetLoggingCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterSetLoggingCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterSetLoggingCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterSetLoggingCall<'a, S### impl<'a, S> Send for ProjectLocationClusterSetLoggingCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterSetLoggingCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterSetLoggingCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterSetLoggingCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterSetMaintenancePolicyCall === ``` pub struct ProjectLocationClusterSetMaintenancePolicyCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the maintenance policy for a cluster. A builder for the *locations.clusters.setMaintenancePolicy* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetMaintenancePolicyRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetMaintenancePolicyRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_set_maintenance_policy(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterSetMaintenancePolicyCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetMaintenancePolicyRequest ) -> ProjectLocationClusterSetMaintenancePolicyCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterSetMaintenancePolicyCall<'a, SThe name (project, location, cluster name) of the cluster to set maintenance policy. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterSetMaintenancePolicyCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterSetMaintenancePolicyCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterSetMaintenancePolicyCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterSetMaintenancePolicyCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes( self ) -> ProjectLocationClusterSetMaintenancePolicyCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterSetMaintenancePolicyCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterSetMaintenancePolicyCall<'a, S### impl<'a, S> Send for ProjectLocationClusterSetMaintenancePolicyCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterSetMaintenancePolicyCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterSetMaintenancePolicyCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterSetMaintenancePolicyCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterSetMasterAuthCall === ``` pub struct ProjectLocationClusterSetMasterAuthCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets master auth materials. Currently supports changing the admin password or a specific cluster, either via password generation or explicitly setting the password. A builder for the *locations.clusters.setMasterAuth* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetMasterAuthRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetMasterAuthRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_set_master_auth(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterSetMasterAuthCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetMasterAuthRequest ) -> ProjectLocationClusterSetMasterAuthCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterSetMasterAuthCall<'a, SThe name (project, location, cluster) of the cluster to set auth. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterSetMasterAuthCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterSetMasterAuthCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterSetMasterAuthCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterSetMasterAuthCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterSetMasterAuthCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterSetMasterAuthCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterSetMasterAuthCall<'a, S### impl<'a, S> Send for ProjectLocationClusterSetMasterAuthCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterSetMasterAuthCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterSetMasterAuthCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterSetMasterAuthCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterSetMonitoringCall === ``` pub struct ProjectLocationClusterSetMonitoringCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the monitoring service for a specific cluster. A builder for the *locations.clusters.setMonitoring* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetMonitoringServiceRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetMonitoringServiceRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_set_monitoring(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterSetMonitoringCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetMonitoringServiceRequest ) -> ProjectLocationClusterSetMonitoringCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterSetMonitoringCall<'a, SThe name (project, location, cluster) of the cluster to set monitoring. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterSetMonitoringCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterSetMonitoringCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterSetMonitoringCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterSetMonitoringCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterSetMonitoringCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterSetMonitoringCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterSetMonitoringCall<'a, S### impl<'a, S> Send for ProjectLocationClusterSetMonitoringCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterSetMonitoringCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterSetMonitoringCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterSetMonitoringCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterSetNetworkPolicyCall === ``` pub struct ProjectLocationClusterSetNetworkPolicyCall<'a, S>where S: 'a,{ /* private fields */ } ``` Enables or disables Network Policy for a cluster. A builder for the *locations.clusters.setNetworkPolicy* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetNetworkPolicyRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetNetworkPolicyRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_set_network_policy(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterSetNetworkPolicyCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetNetworkPolicyRequest ) -> ProjectLocationClusterSetNetworkPolicyCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterSetNetworkPolicyCall<'a, SThe name (project, location, cluster name) of the cluster to set networking policy. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterSetNetworkPolicyCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterSetNetworkPolicyCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterSetNetworkPolicyCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterSetNetworkPolicyCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterSetNetworkPolicyCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterSetNetworkPolicyCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterSetNetworkPolicyCall<'a, S### impl<'a, S> Send for ProjectLocationClusterSetNetworkPolicyCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterSetNetworkPolicyCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterSetNetworkPolicyCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterSetNetworkPolicyCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterSetResourceLabelCall === ``` pub struct ProjectLocationClusterSetResourceLabelCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets labels on a cluster. A builder for the *locations.clusters.setResourceLabels* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetLabelsRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetLabelsRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_set_resource_labels(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterSetResourceLabelCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetLabelsRequest ) -> ProjectLocationClusterSetResourceLabelCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterSetResourceLabelCall<'a, SThe name (project, location, cluster name) of the cluster to set labels. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterSetResourceLabelCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterSetResourceLabelCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterSetResourceLabelCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterSetResourceLabelCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterSetResourceLabelCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterSetResourceLabelCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterSetResourceLabelCall<'a, S### impl<'a, S> Send for ProjectLocationClusterSetResourceLabelCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterSetResourceLabelCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterSetResourceLabelCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterSetResourceLabelCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterStartIpRotationCall === ``` pub struct ProjectLocationClusterStartIpRotationCall<'a, S>where S: 'a,{ /* private fields */ } ``` Starts master IP rotation. A builder for the *locations.clusters.startIpRotation* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::StartIPRotationRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = StartIPRotationRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_start_ip_rotation(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterStartIpRotationCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: StartIPRotationRequest ) -> ProjectLocationClusterStartIpRotationCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterStartIpRotationCall<'a, SThe name (project, location, cluster name) of the cluster to start IP rotation. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterStartIpRotationCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterStartIpRotationCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterStartIpRotationCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterStartIpRotationCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterStartIpRotationCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterStartIpRotationCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterStartIpRotationCall<'a, S### impl<'a, S> Send for ProjectLocationClusterStartIpRotationCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterStartIpRotationCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterStartIpRotationCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterStartIpRotationCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterUpdateCall === ``` pub struct ProjectLocationClusterUpdateCall<'a, S>where S: 'a,{ /* private fields */ } ``` Updates the settings of a specific cluster. A builder for the *locations.clusters.update* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::UpdateClusterRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = UpdateClusterRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_update(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterUpdateCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: UpdateClusterRequest ) -> ProjectLocationClusterUpdateCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name(self, new_value: &str) -> ProjectLocationClusterUpdateCall<'a, SThe name (project, location, cluster) of the cluster to update. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterUpdateCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterUpdateCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectLocationClusterUpdateCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterUpdateCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterUpdateCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterUpdateCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterUpdateCall<'a, S### impl<'a, S> Send for ProjectLocationClusterUpdateCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterUpdateCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterUpdateCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterUpdateCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterUpdateMasterCall === ``` pub struct ProjectLocationClusterUpdateMasterCall<'a, S>where S: 'a,{ /* private fields */ } ``` Updates the master for a specific cluster. A builder for the *locations.clusters.updateMaster* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::UpdateMasterRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = UpdateMasterRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_update_master(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterUpdateMasterCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: UpdateMasterRequest ) -> ProjectLocationClusterUpdateMasterCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectLocationClusterUpdateMasterCall<'a, SThe name (project, location, cluster) of the cluster to update. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterUpdateMasterCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterUpdateMasterCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationClusterUpdateMasterCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationClusterUpdateMasterCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationClusterUpdateMasterCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterUpdateMasterCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterUpdateMasterCall<'a, S### impl<'a, S> Send for ProjectLocationClusterUpdateMasterCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterUpdateMasterCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterUpdateMasterCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterUpdateMasterCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationClusterWellKnownGetOpenidConfigurationCall === ``` pub struct ProjectLocationClusterWellKnownGetOpenidConfigurationCall<'a, S>where S: 'a,{ /* private fields */ } ``` Gets the OIDC discovery document for the cluster. See the OpenID Connect Discovery 1.0 specification for details. This API is not yet intended for general use, and is not available for all clusters. A builder for the *locations.clusters.well-known.getOpenid-configuration* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_clusters_well_known_get_openid_configuration("parent") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationClusterWellKnownGetOpenidConfigurationCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, GetOpenIDConfigResponse)Perform the operation you have build so far. #### pub fn parent( self, new_value: &str ) -> ProjectLocationClusterWellKnownGetOpenidConfigurationCall<'a, SThe cluster (project, location, cluster name) to get the discovery document for. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *parent* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationClusterWellKnownGetOpenidConfigurationCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationClusterWellKnownGetOpenidConfigurationCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationClusterWellKnownGetOpenidConfigurationCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationClusterWellKnownGetOpenidConfigurationCall<'a, S### impl<'a, S> Send for ProjectLocationClusterWellKnownGetOpenidConfigurationCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationClusterWellKnownGetOpenidConfigurationCall<'a, S### impl<'a, S> Unpin for ProjectLocationClusterWellKnownGetOpenidConfigurationCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationClusterWellKnownGetOpenidConfigurationCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationGetServerConfigCall === ``` pub struct ProjectLocationGetServerConfigCall<'a, S>where S: 'a,{ /* private fields */ } ``` Returns configuration info about the Google Kubernetes Engine service. A builder for the *locations.getServerConfig* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_get_server_config("name") .zone("takimata") .project_id("consetetur") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationGetServerConfigCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, ServerConfig)Perform the operation you have build so far. #### pub fn name(self, new_value: &str) -> ProjectLocationGetServerConfigCall<'a, SThe name (project and location) of the server config to get, specified in the format `projects/*/locations/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectLocationGetServerConfigCall<'a, SDeprecated. The name of the Google Compute Engine zone to return operations for. This field has been deprecated and replaced by the name field. Sets the *zone* query property to the given value. #### pub fn project_id( self, new_value: &str ) -> ProjectLocationGetServerConfigCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationGetServerConfigCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationGetServerConfigCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationGetServerConfigCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationGetServerConfigCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationGetServerConfigCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationGetServerConfigCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationGetServerConfigCall<'a, S### impl<'a, S> Send for ProjectLocationGetServerConfigCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationGetServerConfigCall<'a, S### impl<'a, S> Unpin for ProjectLocationGetServerConfigCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationGetServerConfigCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationOperationCancelCall === ``` pub struct ProjectLocationOperationCancelCall<'a, S>where S: 'a,{ /* private fields */ } ``` Cancels the specified operation. A builder for the *locations.operations.cancel* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::CancelOperationRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = CancelOperationRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_operations_cancel(req, "name") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationOperationCancelCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Empty)Perform the operation you have build so far. #### pub fn request( self, new_value: CancelOperationRequest ) -> ProjectLocationOperationCancelCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name(self, new_value: &str) -> ProjectLocationOperationCancelCall<'a, SThe name (project, location, operation id) of the operation to cancel. Specified in the format `projects/*/locations/*/operations/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationOperationCancelCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationOperationCancelCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectLocationOperationCancelCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationOperationCancelCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationOperationCancelCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationOperationCancelCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationOperationCancelCall<'a, S### impl<'a, S> Send for ProjectLocationOperationCancelCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationOperationCancelCall<'a, S### impl<'a, S> Unpin for ProjectLocationOperationCancelCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationOperationCancelCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationOperationGetCall === ``` pub struct ProjectLocationOperationGetCall<'a, S>where S: 'a,{ /* private fields */ } ``` Gets the specified operation. A builder for the *locations.operations.get* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_operations_get("name") .zone("vero") .project_id("elitr") .operation_id("Lorem") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationOperationGetCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn name(self, new_value: &str) -> ProjectLocationOperationGetCall<'a, SThe name (project, location, operation id) of the operation to get. Specified in the format `projects/*/locations/*/operations/*`. Sets the *name* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectLocationOperationGetCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* query property to the given value. #### pub fn project_id( self, new_value: &str ) -> ProjectLocationOperationGetCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* query property to the given value. #### pub fn operation_id( self, new_value: &str ) -> ProjectLocationOperationGetCall<'a, SDeprecated. The server-assigned `name` of the operation. This field has been deprecated and replaced by the name field. Sets the *operation id* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationOperationGetCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationOperationGetCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectLocationOperationGetCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationOperationGetCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationOperationGetCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationOperationGetCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationOperationGetCall<'a, S### impl<'a, S> Send for ProjectLocationOperationGetCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationOperationGetCall<'a, S### impl<'a, S> Unpin for ProjectLocationOperationGetCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationOperationGetCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectLocationOperationListCall === ``` pub struct ProjectLocationOperationListCall<'a, S>where S: 'a,{ /* private fields */ } ``` Lists all operations in a project in a specific zone or all zones. A builder for the *locations.operations.list* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().locations_operations_list("parent") .zone("no") .project_id("ipsum") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectLocationOperationListCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, ListOperationsResponse)Perform the operation you have build so far. #### pub fn parent(self, new_value: &str) -> ProjectLocationOperationListCall<'a, SThe parent (project and location) where the operations will be listed. Specified in the format `projects/*/locations/*`. Location “-” matches all zones and all regions. Sets the *parent* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectLocationOperationListCall<'a, SDeprecated. The name of the Google Compute Engine zone to return operations for, or `-` for all zones. This field has been deprecated and replaced by the parent field. Sets the *zone* query property to the given value. #### pub fn project_id( self, new_value: &str ) -> ProjectLocationOperationListCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the parent field. Sets the *project id* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectLocationOperationListCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectLocationOperationListCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectLocationOperationListCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectLocationOperationListCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectLocationOperationListCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectLocationOperationListCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectLocationOperationListCall<'a, S### impl<'a, S> Send for ProjectLocationOperationListCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectLocationOperationListCall<'a, S### impl<'a, S> Unpin for ProjectLocationOperationListCall<'a, S### impl<'a, S> !UnwindSafe for ProjectLocationOperationListCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterAddonCall === ``` pub struct ProjectZoneClusterAddonCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the addons for a specific cluster. A builder for the *zones.clusters.addons* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetAddonsConfigRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetAddonsConfigRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_addons(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterAddonCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetAddonsConfigRequest ) -> ProjectZoneClusterAddonCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id(self, new_value: &str) -> ProjectZoneClusterAddonCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterAddonCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id(self, new_value: &str) -> ProjectZoneClusterAddonCall<'a, SDeprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterAddonCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>(self, name: T, value: T) -> ProjectZoneClusterAddonCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneClusterAddonCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>(self, scopes: I) -> ProjectZoneClusterAddonCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterAddonCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterAddonCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterAddonCall<'a, S### impl<'a, S> Send for ProjectZoneClusterAddonCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterAddonCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterAddonCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterAddonCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterCompleteIpRotationCall === ``` pub struct ProjectZoneClusterCompleteIpRotationCall<'a, S>where S: 'a,{ /* private fields */ } ``` Completes master IP rotation. A builder for the *zones.clusters.completeIpRotation* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::CompleteIPRotationRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = CompleteIPRotationRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_complete_ip_rotation(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterCompleteIpRotationCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: CompleteIPRotationRequest ) -> ProjectZoneClusterCompleteIpRotationCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterCompleteIpRotationCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectZoneClusterCompleteIpRotationCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterCompleteIpRotationCall<'a, SDeprecated. The name of the cluster. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterCompleteIpRotationCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterCompleteIpRotationCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterCompleteIpRotationCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterCompleteIpRotationCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterCompleteIpRotationCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterCompleteIpRotationCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterCompleteIpRotationCall<'a, S### impl<'a, S> Send for ProjectZoneClusterCompleteIpRotationCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterCompleteIpRotationCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterCompleteIpRotationCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterCompleteIpRotationCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterCreateCall === ``` pub struct ProjectZoneClusterCreateCall<'a, S>where S: 'a,{ /* private fields */ } ``` Creates a cluster, consisting of the specified number and type of Google Compute Engine instances. By default, the cluster is created in the project’s default network. One firewall is added for the cluster. After cluster creation, the Kubelet creates routes for each node to allow the containers on that node to communicate with all other instances in the cluster. Finally, an entry is added to the project’s global metadata indicating which CIDR range the cluster is using. A builder for the *zones.clusters.create* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::CreateClusterRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = CreateClusterRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_create(req, "projectId", "zone") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterCreateCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: CreateClusterRequest ) -> ProjectZoneClusterCreateCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id(self, new_value: &str) -> ProjectZoneClusterCreateCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the parent field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterCreateCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the parent field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterCreateCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>(self, name: T, value: T) -> ProjectZoneClusterCreateCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneClusterCreateCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>(self, scopes: I) -> ProjectZoneClusterCreateCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterCreateCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterCreateCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterCreateCall<'a, S### impl<'a, S> Send for ProjectZoneClusterCreateCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterCreateCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterCreateCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterCreateCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterDeleteCall === ``` pub struct ProjectZoneClusterDeleteCall<'a, S>where S: 'a,{ /* private fields */ } ``` Deletes the cluster, including the Kubernetes endpoint and all worker nodes. Firewalls and routes that were configured during cluster creation are also deleted. Other Google Compute Engine resources that might be in use by the cluster, such as load balancer resources, are not deleted if they weren’t present when the cluster was initially created. A builder for the *zones.clusters.delete* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_delete("projectId", "zone", "clusterId") .name("aliquyam") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterDeleteCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn project_id(self, new_value: &str) -> ProjectZoneClusterDeleteCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterDeleteCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id(self, new_value: &str) -> ProjectZoneClusterDeleteCall<'a, SDeprecated. The name of the cluster to delete. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name(self, new_value: &str) -> ProjectZoneClusterDeleteCall<'a, SThe name (project, location, cluster) of the cluster to delete. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterDeleteCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>(self, name: T, value: T) -> ProjectZoneClusterDeleteCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneClusterDeleteCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>(self, scopes: I) -> ProjectZoneClusterDeleteCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterDeleteCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterDeleteCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterDeleteCall<'a, S### impl<'a, S> Send for ProjectZoneClusterDeleteCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterDeleteCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterDeleteCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterDeleteCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterGetCall === ``` pub struct ProjectZoneClusterGetCall<'a, S>where S: 'a,{ /* private fields */ } ``` Gets the details of a specific cluster. A builder for the *zones.clusters.get* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_get("projectId", "zone", "clusterId") .name("aliquyam") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterGetCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Cluster)Perform the operation you have build so far. #### pub fn project_id(self, new_value: &str) -> ProjectZoneClusterGetCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterGetCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id(self, new_value: &str) -> ProjectZoneClusterGetCall<'a, SDeprecated. The name of the cluster to retrieve. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name(self, new_value: &str) -> ProjectZoneClusterGetCall<'a, SThe name (project, location, cluster) of the cluster to retrieve. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *name* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterGetCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>(self, name: T, value: T) -> ProjectZoneClusterGetCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneClusterGetCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>(self, scopes: I) -> ProjectZoneClusterGetCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterGetCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterGetCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterGetCall<'a, S### impl<'a, S> Send for ProjectZoneClusterGetCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterGetCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterGetCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterGetCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterLegacyAbacCall === ``` pub struct ProjectZoneClusterLegacyAbacCall<'a, S>where S: 'a,{ /* private fields */ } ``` Enables or disables the ABAC authorization mechanism on a cluster. A builder for the *zones.clusters.legacyAbac* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetLegacyAbacRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetLegacyAbacRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_legacy_abac(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterLegacyAbacCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetLegacyAbacRequest ) -> ProjectZoneClusterLegacyAbacCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterLegacyAbacCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterLegacyAbacCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterLegacyAbacCall<'a, SDeprecated. The name of the cluster to update. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterLegacyAbacCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterLegacyAbacCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneClusterLegacyAbacCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterLegacyAbacCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterLegacyAbacCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterLegacyAbacCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterLegacyAbacCall<'a, S### impl<'a, S> Send for ProjectZoneClusterLegacyAbacCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterLegacyAbacCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterLegacyAbacCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterLegacyAbacCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterListCall === ``` pub struct ProjectZoneClusterListCall<'a, S>where S: 'a,{ /* private fields */ } ``` Lists all clusters owned by a project in either the specified zone or all zones. A builder for the *zones.clusters.list* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_list("projectId", "zone") .parent("consetetur") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterListCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, ListClustersResponse)Perform the operation you have build so far. #### pub fn project_id(self, new_value: &str) -> ProjectZoneClusterListCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the parent field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterListCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides, or “-” for all zones. This field has been deprecated and replaced by the parent field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn parent(self, new_value: &str) -> ProjectZoneClusterListCall<'a, SThe parent (project and location) where the clusters will be listed. Specified in the format `projects/*/locations/*`. Location “-” matches all zones and all regions. Sets the *parent* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterListCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>(self, name: T, value: T) -> ProjectZoneClusterListCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneClusterListCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>(self, scopes: I) -> ProjectZoneClusterListCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterListCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterListCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterListCall<'a, S### impl<'a, S> Send for ProjectZoneClusterListCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterListCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterListCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterListCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterLocationCall === ``` pub struct ProjectZoneClusterLocationCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the locations for a specific cluster. Deprecated. Use projects.locations.clusters.update instead. A builder for the *zones.clusters.locations* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetLocationsRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetLocationsRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_locations(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterLocationCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetLocationsRequest ) -> ProjectZoneClusterLocationCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterLocationCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterLocationCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterLocationCall<'a, SDeprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterLocationCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterLocationCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneClusterLocationCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterLocationCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterLocationCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterLocationCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterLocationCall<'a, S### impl<'a, S> Send for ProjectZoneClusterLocationCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterLocationCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterLocationCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterLocationCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterLoggingCall === ``` pub struct ProjectZoneClusterLoggingCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the logging service for a specific cluster. A builder for the *zones.clusters.logging* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetLoggingServiceRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetLoggingServiceRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_logging(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterLoggingCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetLoggingServiceRequest ) -> ProjectZoneClusterLoggingCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id(self, new_value: &str) -> ProjectZoneClusterLoggingCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterLoggingCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id(self, new_value: &str) -> ProjectZoneClusterLoggingCall<'a, SDeprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterLoggingCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>(self, name: T, value: T) -> ProjectZoneClusterLoggingCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneClusterLoggingCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterLoggingCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterLoggingCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterLoggingCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterLoggingCall<'a, S### impl<'a, S> Send for ProjectZoneClusterLoggingCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterLoggingCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterLoggingCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterLoggingCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterMasterCall === ``` pub struct ProjectZoneClusterMasterCall<'a, S>where S: 'a,{ /* private fields */ } ``` Updates the master for a specific cluster. A builder for the *zones.clusters.master* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::UpdateMasterRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = UpdateMasterRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_master(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterMasterCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: UpdateMasterRequest ) -> ProjectZoneClusterMasterCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id(self, new_value: &str) -> ProjectZoneClusterMasterCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterMasterCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id(self, new_value: &str) -> ProjectZoneClusterMasterCall<'a, SDeprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterMasterCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>(self, name: T, value: T) -> ProjectZoneClusterMasterCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneClusterMasterCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>(self, scopes: I) -> ProjectZoneClusterMasterCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterMasterCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterMasterCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterMasterCall<'a, S### impl<'a, S> Send for ProjectZoneClusterMasterCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterMasterCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterMasterCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterMasterCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterMonitoringCall === ``` pub struct ProjectZoneClusterMonitoringCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the monitoring service for a specific cluster. A builder for the *zones.clusters.monitoring* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetMonitoringServiceRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetMonitoringServiceRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_monitoring(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterMonitoringCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetMonitoringServiceRequest ) -> ProjectZoneClusterMonitoringCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterMonitoringCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterMonitoringCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterMonitoringCall<'a, SDeprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterMonitoringCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterMonitoringCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneClusterMonitoringCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterMonitoringCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterMonitoringCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterMonitoringCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterMonitoringCall<'a, S### impl<'a, S> Send for ProjectZoneClusterMonitoringCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterMonitoringCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterMonitoringCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterMonitoringCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterNodePoolAutoscalingCall === ``` pub struct ProjectZoneClusterNodePoolAutoscalingCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the autoscaling settings for the specified node pool. A builder for the *zones.clusters.nodePools.autoscaling* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetNodePoolAutoscalingRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetNodePoolAutoscalingRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_node_pools_autoscaling(req, "projectId", "zone", "clusterId", "nodePoolId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterNodePoolAutoscalingCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetNodePoolAutoscalingRequest ) -> ProjectZoneClusterNodePoolAutoscalingCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolAutoscalingCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectZoneClusterNodePoolAutoscalingCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolAutoscalingCall<'a, SDeprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn node_pool_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolAutoscalingCall<'a, SDeprecated. The name of the node pool to upgrade. This field has been deprecated and replaced by the name field. Sets the *node pool id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterNodePoolAutoscalingCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterNodePoolAutoscalingCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterNodePoolAutoscalingCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterNodePoolAutoscalingCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterNodePoolAutoscalingCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterNodePoolAutoscalingCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterNodePoolAutoscalingCall<'a, S### impl<'a, S> Send for ProjectZoneClusterNodePoolAutoscalingCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterNodePoolAutoscalingCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterNodePoolAutoscalingCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterNodePoolAutoscalingCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterNodePoolCreateCall === ``` pub struct ProjectZoneClusterNodePoolCreateCall<'a, S>where S: 'a,{ /* private fields */ } ``` Creates a node pool for a cluster. A builder for the *zones.clusters.nodePools.create* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::CreateNodePoolRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = CreateNodePoolRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_node_pools_create(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterNodePoolCreateCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: CreateNodePoolRequest ) -> ProjectZoneClusterNodePoolCreateCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolCreateCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the parent field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectZoneClusterNodePoolCreateCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the parent field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolCreateCall<'a, SDeprecated. The name of the cluster. This field has been deprecated and replaced by the parent field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterNodePoolCreateCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterNodePoolCreateCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterNodePoolCreateCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterNodePoolCreateCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterNodePoolCreateCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterNodePoolCreateCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterNodePoolCreateCall<'a, S### impl<'a, S> Send for ProjectZoneClusterNodePoolCreateCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterNodePoolCreateCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterNodePoolCreateCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterNodePoolCreateCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterNodePoolDeleteCall === ``` pub struct ProjectZoneClusterNodePoolDeleteCall<'a, S>where S: 'a,{ /* private fields */ } ``` Deletes a node pool from a cluster. A builder for the *zones.clusters.nodePools.delete* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_node_pools_delete("projectId", "zone", "clusterId", "nodePoolId") .name("voluptua.") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterNodePoolDeleteCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolDeleteCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectZoneClusterNodePoolDeleteCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolDeleteCall<'a, SDeprecated. The name of the cluster. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn node_pool_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolDeleteCall<'a, SDeprecated. The name of the node pool to delete. This field has been deprecated and replaced by the name field. Sets the *node pool id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name( self, new_value: &str ) -> ProjectZoneClusterNodePoolDeleteCall<'a, SThe name (project, location, cluster, node pool id) of the node pool to delete. Specified in the format `projects/*/locations/*/clusters/*/nodePools/*`. Sets the *name* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterNodePoolDeleteCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterNodePoolDeleteCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterNodePoolDeleteCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterNodePoolDeleteCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterNodePoolDeleteCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterNodePoolDeleteCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterNodePoolDeleteCall<'a, S### impl<'a, S> Send for ProjectZoneClusterNodePoolDeleteCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterNodePoolDeleteCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterNodePoolDeleteCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterNodePoolDeleteCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterNodePoolGetCall === ``` pub struct ProjectZoneClusterNodePoolGetCall<'a, S>where S: 'a,{ /* private fields */ } ``` Retrieves the requested node pool. A builder for the *zones.clusters.nodePools.get* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_node_pools_get("projectId", "zone", "clusterId", "nodePoolId") .name("amet.") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterNodePoolGetCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, NodePool)Perform the operation you have build so far. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolGetCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterNodePoolGetCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolGetCall<'a, SDeprecated. The name of the cluster. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn node_pool_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolGetCall<'a, SDeprecated. The name of the node pool. This field has been deprecated and replaced by the name field. Sets the *node pool id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name(self, new_value: &str) -> ProjectZoneClusterNodePoolGetCall<'a, SThe name (project, location, cluster, node pool id) of the node pool to get. Specified in the format `projects/*/locations/*/clusters/*/nodePools/*`. Sets the *name* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterNodePoolGetCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterNodePoolGetCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterNodePoolGetCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterNodePoolGetCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterNodePoolGetCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterNodePoolGetCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterNodePoolGetCall<'a, S### impl<'a, S> Send for ProjectZoneClusterNodePoolGetCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterNodePoolGetCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterNodePoolGetCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterNodePoolGetCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterNodePoolListCall === ``` pub struct ProjectZoneClusterNodePoolListCall<'a, S>where S: 'a,{ /* private fields */ } ``` Lists the node pools for a cluster. A builder for the *zones.clusters.nodePools.list* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_node_pools_list("projectId", "zone", "clusterId") .parent("invidunt") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterNodePoolListCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, ListNodePoolsResponse)Perform the operation you have build so far. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolListCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the parent field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterNodePoolListCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the parent field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolListCall<'a, SDeprecated. The name of the cluster. This field has been deprecated and replaced by the parent field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn parent( self, new_value: &str ) -> ProjectZoneClusterNodePoolListCall<'a, SThe parent (project, location, cluster name) where the node pools will be listed. Specified in the format `projects/*/locations/*/clusters/*`. Sets the *parent* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterNodePoolListCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterNodePoolListCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterNodePoolListCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterNodePoolListCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterNodePoolListCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterNodePoolListCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterNodePoolListCall<'a, S### impl<'a, S> Send for ProjectZoneClusterNodePoolListCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterNodePoolListCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterNodePoolListCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterNodePoolListCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterNodePoolRollbackCall === ``` pub struct ProjectZoneClusterNodePoolRollbackCall<'a, S>where S: 'a,{ /* private fields */ } ``` Rolls back a previously Aborted or Failed NodePool upgrade. This makes no changes if the last upgrade successfully completed. A builder for the *zones.clusters.nodePools.rollback* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::RollbackNodePoolUpgradeRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = RollbackNodePoolUpgradeRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_node_pools_rollback(req, "projectId", "zone", "clusterId", "nodePoolId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterNodePoolRollbackCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: RollbackNodePoolUpgradeRequest ) -> ProjectZoneClusterNodePoolRollbackCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolRollbackCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectZoneClusterNodePoolRollbackCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolRollbackCall<'a, SDeprecated. The name of the cluster to rollback. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn node_pool_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolRollbackCall<'a, SDeprecated. The name of the node pool to rollback. This field has been deprecated and replaced by the name field. Sets the *node pool id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterNodePoolRollbackCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterNodePoolRollbackCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterNodePoolRollbackCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterNodePoolRollbackCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterNodePoolRollbackCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterNodePoolRollbackCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterNodePoolRollbackCall<'a, S### impl<'a, S> Send for ProjectZoneClusterNodePoolRollbackCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterNodePoolRollbackCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterNodePoolRollbackCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterNodePoolRollbackCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterNodePoolSetManagementCall === ``` pub struct ProjectZoneClusterNodePoolSetManagementCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the NodeManagement options for a node pool. A builder for the *zones.clusters.nodePools.setManagement* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetNodePoolManagementRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetNodePoolManagementRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_node_pools_set_management(req, "projectId", "zone", "clusterId", "nodePoolId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterNodePoolSetManagementCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetNodePoolManagementRequest ) -> ProjectZoneClusterNodePoolSetManagementCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolSetManagementCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectZoneClusterNodePoolSetManagementCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolSetManagementCall<'a, SDeprecated. The name of the cluster to update. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn node_pool_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolSetManagementCall<'a, SDeprecated. The name of the node pool to update. This field has been deprecated and replaced by the name field. Sets the *node pool id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterNodePoolSetManagementCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterNodePoolSetManagementCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterNodePoolSetManagementCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterNodePoolSetManagementCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterNodePoolSetManagementCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterNodePoolSetManagementCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterNodePoolSetManagementCall<'a, S### impl<'a, S> Send for ProjectZoneClusterNodePoolSetManagementCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterNodePoolSetManagementCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterNodePoolSetManagementCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterNodePoolSetManagementCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterNodePoolSetSizeCall === ``` pub struct ProjectZoneClusterNodePoolSetSizeCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the size for a specific node pool. The new size will be used for all replicas, including future replicas created by modifying NodePool.locations. A builder for the *zones.clusters.nodePools.setSize* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetNodePoolSizeRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetNodePoolSizeRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_node_pools_set_size(req, "projectId", "zone", "clusterId", "nodePoolId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterNodePoolSetSizeCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetNodePoolSizeRequest ) -> ProjectZoneClusterNodePoolSetSizeCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolSetSizeCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectZoneClusterNodePoolSetSizeCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolSetSizeCall<'a, SDeprecated. The name of the cluster to update. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn node_pool_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolSetSizeCall<'a, SDeprecated. The name of the node pool to update. This field has been deprecated and replaced by the name field. Sets the *node pool id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterNodePoolSetSizeCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterNodePoolSetSizeCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterNodePoolSetSizeCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterNodePoolSetSizeCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterNodePoolSetSizeCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterNodePoolSetSizeCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterNodePoolSetSizeCall<'a, S### impl<'a, S> Send for ProjectZoneClusterNodePoolSetSizeCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterNodePoolSetSizeCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterNodePoolSetSizeCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterNodePoolSetSizeCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterNodePoolUpdateCall === ``` pub struct ProjectZoneClusterNodePoolUpdateCall<'a, S>where S: 'a,{ /* private fields */ } ``` Updates the version and/or image type for the specified node pool. A builder for the *zones.clusters.nodePools.update* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::UpdateNodePoolRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = UpdateNodePoolRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_node_pools_update(req, "projectId", "zone", "clusterId", "nodePoolId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterNodePoolUpdateCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: UpdateNodePoolRequest ) -> ProjectZoneClusterNodePoolUpdateCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolUpdateCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectZoneClusterNodePoolUpdateCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolUpdateCall<'a, SDeprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn node_pool_id( self, new_value: &str ) -> ProjectZoneClusterNodePoolUpdateCall<'a, SDeprecated. The name of the node pool to upgrade. This field has been deprecated and replaced by the name field. Sets the *node pool id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterNodePoolUpdateCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterNodePoolUpdateCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterNodePoolUpdateCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterNodePoolUpdateCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterNodePoolUpdateCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterNodePoolUpdateCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterNodePoolUpdateCall<'a, S### impl<'a, S> Send for ProjectZoneClusterNodePoolUpdateCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterNodePoolUpdateCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterNodePoolUpdateCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterNodePoolUpdateCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterResourceLabelCall === ``` pub struct ProjectZoneClusterResourceLabelCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets labels on a cluster. A builder for the *zones.clusters.resourceLabels* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetLabelsRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetLabelsRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_resource_labels(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterResourceLabelCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetLabelsRequest ) -> ProjectZoneClusterResourceLabelCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterResourceLabelCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterResourceLabelCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterResourceLabelCall<'a, SDeprecated. The name of the cluster. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterResourceLabelCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterResourceLabelCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterResourceLabelCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterResourceLabelCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterResourceLabelCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterResourceLabelCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterResourceLabelCall<'a, S### impl<'a, S> Send for ProjectZoneClusterResourceLabelCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterResourceLabelCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterResourceLabelCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterResourceLabelCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterSetMaintenancePolicyCall === ``` pub struct ProjectZoneClusterSetMaintenancePolicyCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets the maintenance policy for a cluster. A builder for the *zones.clusters.setMaintenancePolicy* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetMaintenancePolicyRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetMaintenancePolicyRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_set_maintenance_policy(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterSetMaintenancePolicyCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetMaintenancePolicyRequest ) -> ProjectZoneClusterSetMaintenancePolicyCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterSetMaintenancePolicyCall<'a, SRequired. The Google Developers Console project ID or project number. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectZoneClusterSetMaintenancePolicyCall<'a, SRequired. The name of the Google Compute Engine zone in which the cluster resides. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterSetMaintenancePolicyCall<'a, SRequired. The name of the cluster to update. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterSetMaintenancePolicyCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterSetMaintenancePolicyCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterSetMaintenancePolicyCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterSetMaintenancePolicyCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterSetMaintenancePolicyCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterSetMaintenancePolicyCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterSetMaintenancePolicyCall<'a, S### impl<'a, S> Send for ProjectZoneClusterSetMaintenancePolicyCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterSetMaintenancePolicyCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterSetMaintenancePolicyCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterSetMaintenancePolicyCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterSetMasterAuthCall === ``` pub struct ProjectZoneClusterSetMasterAuthCall<'a, S>where S: 'a,{ /* private fields */ } ``` Sets master auth materials. Currently supports changing the admin password or a specific cluster, either via password generation or explicitly setting the password. A builder for the *zones.clusters.setMasterAuth* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetMasterAuthRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetMasterAuthRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_set_master_auth(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterSetMasterAuthCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetMasterAuthRequest ) -> ProjectZoneClusterSetMasterAuthCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterSetMasterAuthCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterSetMasterAuthCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterSetMasterAuthCall<'a, SDeprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterSetMasterAuthCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterSetMasterAuthCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterSetMasterAuthCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterSetMasterAuthCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterSetMasterAuthCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterSetMasterAuthCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterSetMasterAuthCall<'a, S### impl<'a, S> Send for ProjectZoneClusterSetMasterAuthCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterSetMasterAuthCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterSetMasterAuthCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterSetMasterAuthCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterSetNetworkPolicyCall === ``` pub struct ProjectZoneClusterSetNetworkPolicyCall<'a, S>where S: 'a,{ /* private fields */ } ``` Enables or disables Network Policy for a cluster. A builder for the *zones.clusters.setNetworkPolicy* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::SetNetworkPolicyRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = SetNetworkPolicyRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_set_network_policy(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterSetNetworkPolicyCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: SetNetworkPolicyRequest ) -> ProjectZoneClusterSetNetworkPolicyCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterSetNetworkPolicyCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectZoneClusterSetNetworkPolicyCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterSetNetworkPolicyCall<'a, SDeprecated. The name of the cluster. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterSetNetworkPolicyCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterSetNetworkPolicyCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterSetNetworkPolicyCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterSetNetworkPolicyCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterSetNetworkPolicyCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterSetNetworkPolicyCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterSetNetworkPolicyCall<'a, S### impl<'a, S> Send for ProjectZoneClusterSetNetworkPolicyCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterSetNetworkPolicyCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterSetNetworkPolicyCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterSetNetworkPolicyCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterStartIpRotationCall === ``` pub struct ProjectZoneClusterStartIpRotationCall<'a, S>where S: 'a,{ /* private fields */ } ``` Starts master IP rotation. A builder for the *zones.clusters.startIpRotation* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::StartIPRotationRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = StartIPRotationRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_start_ip_rotation(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterStartIpRotationCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: StartIPRotationRequest ) -> ProjectZoneClusterStartIpRotationCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneClusterStartIpRotationCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone( self, new_value: &str ) -> ProjectZoneClusterStartIpRotationCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id( self, new_value: &str ) -> ProjectZoneClusterStartIpRotationCall<'a, SDeprecated. The name of the cluster. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterStartIpRotationCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneClusterStartIpRotationCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>( self, scope: St ) -> ProjectZoneClusterStartIpRotationCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneClusterStartIpRotationCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterStartIpRotationCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterStartIpRotationCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterStartIpRotationCall<'a, S### impl<'a, S> Send for ProjectZoneClusterStartIpRotationCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterStartIpRotationCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterStartIpRotationCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterStartIpRotationCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneClusterUpdateCall === ``` pub struct ProjectZoneClusterUpdateCall<'a, S>where S: 'a,{ /* private fields */ } ``` Updates the settings of a specific cluster. A builder for the *zones.clusters.update* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::UpdateClusterRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = UpdateClusterRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_clusters_update(req, "projectId", "zone", "clusterId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneClusterUpdateCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn request( self, new_value: UpdateClusterRequest ) -> ProjectZoneClusterUpdateCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id(self, new_value: &str) -> ProjectZoneClusterUpdateCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneClusterUpdateCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn cluster_id(self, new_value: &str) -> ProjectZoneClusterUpdateCall<'a, SDeprecated. The name of the cluster to upgrade. This field has been deprecated and replaced by the name field. Sets the *cluster id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneClusterUpdateCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>(self, name: T, value: T) -> ProjectZoneClusterUpdateCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneClusterUpdateCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>(self, scopes: I) -> ProjectZoneClusterUpdateCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneClusterUpdateCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneClusterUpdateCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneClusterUpdateCall<'a, S### impl<'a, S> Send for ProjectZoneClusterUpdateCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneClusterUpdateCall<'a, S### impl<'a, S> Unpin for ProjectZoneClusterUpdateCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneClusterUpdateCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneGetServerconfigCall === ``` pub struct ProjectZoneGetServerconfigCall<'a, S>where S: 'a,{ /* private fields */ } ``` Returns configuration info about the Google Kubernetes Engine service. A builder for the *zones.getServerconfig* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_get_serverconfig("projectId", "zone") .name("sea") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneGetServerconfigCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, ServerConfig)Perform the operation you have build so far. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneGetServerconfigCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneGetServerconfigCall<'a, SDeprecated. The name of the Google Compute Engine zone to return operations for. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name(self, new_value: &str) -> ProjectZoneGetServerconfigCall<'a, SThe name (project and location) of the server config to get, specified in the format `projects/*/locations/*`. Sets the *name* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneGetServerconfigCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneGetServerconfigCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneGetServerconfigCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneGetServerconfigCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneGetServerconfigCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneGetServerconfigCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneGetServerconfigCall<'a, S### impl<'a, S> Send for ProjectZoneGetServerconfigCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneGetServerconfigCall<'a, S### impl<'a, S> Unpin for ProjectZoneGetServerconfigCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneGetServerconfigCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneOperationCancelCall === ``` pub struct ProjectZoneOperationCancelCall<'a, S>where S: 'a,{ /* private fields */ } ``` Cancels the specified operation. A builder for the *zones.operations.cancel* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` use container1::api::CancelOperationRequest; // As the method needs a request, you would usually fill it with the desired information // into the respective structure. Some of the parts shown here might not be applicable ! // Values shown here are possibly random and not representative ! let mut req = CancelOperationRequest::default(); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_operations_cancel(req, "projectId", "zone", "operationId") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneOperationCancelCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Empty)Perform the operation you have build so far. #### pub fn request( self, new_value: CancelOperationRequest ) -> ProjectZoneOperationCancelCall<'a, SSets the *request* property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn project_id( self, new_value: &str ) -> ProjectZoneOperationCancelCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneOperationCancelCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the operation resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn operation_id( self, new_value: &str ) -> ProjectZoneOperationCancelCall<'a, SDeprecated. The server-assigned `name` of the operation. This field has been deprecated and replaced by the name field. Sets the *operation id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneOperationCancelCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>( self, name: T, value: T ) -> ProjectZoneOperationCancelCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneOperationCancelCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>( self, scopes: I ) -> ProjectZoneOperationCancelCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneOperationCancelCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneOperationCancelCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneOperationCancelCall<'a, S### impl<'a, S> Send for ProjectZoneOperationCancelCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneOperationCancelCall<'a, S### impl<'a, S> Unpin for ProjectZoneOperationCancelCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneOperationCancelCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneOperationGetCall === ``` pub struct ProjectZoneOperationGetCall<'a, S>where S: 'a,{ /* private fields */ } ``` Gets the specified operation. A builder for the *zones.operations.get* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_operations_get("projectId", "zone", "operationId") .name("erat") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneOperationGetCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, Operation)Perform the operation you have build so far. #### pub fn project_id(self, new_value: &str) -> ProjectZoneOperationGetCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the name field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneOperationGetCall<'a, SDeprecated. The name of the Google Compute Engine zone in which the cluster resides. This field has been deprecated and replaced by the name field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn operation_id(self, new_value: &str) -> ProjectZoneOperationGetCall<'a, SDeprecated. The server-assigned `name` of the operation. This field has been deprecated and replaced by the name field. Sets the *operation id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn name(self, new_value: &str) -> ProjectZoneOperationGetCall<'a, SThe name (project, location, operation id) of the operation to get. Specified in the format `projects/*/locations/*/operations/*`. Sets the *name* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneOperationGetCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>(self, name: T, value: T) -> ProjectZoneOperationGetCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneOperationGetCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>(self, scopes: I) -> ProjectZoneOperationGetCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneOperationGetCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneOperationGetCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneOperationGetCall<'a, S### impl<'a, S> Send for ProjectZoneOperationGetCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneOperationGetCall<'a, S### impl<'a, S> Unpin for ProjectZoneOperationGetCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneOperationGetCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct google_container1::api::ProjectZoneOperationListCall === ``` pub struct ProjectZoneOperationListCall<'a, S>where S: 'a,{ /* private fields */ } ``` Lists all operations in a project in a specific zone or all zones. A builder for the *zones.operations.list* method supported by a *project* resource. It is not used directly, but through a `ProjectMethods` instance. Example --- Instantiate a resource method builder ``` // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! let result = hub.projects().zones_operations_list("projectId", "zone") .parent("et") .doit().await; ``` Implementations --- ### impl<'a, S> ProjectZoneOperationListCall<'a, S>where S: Service<Uri> + Clone + Send + Sync + 'static, S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static, S::Future: Send + Unpin + 'static, S::Error: Into<Box<dyn StdError + Send + Sync>>, #### pub async fn doit(self) -> Result<(Response<Body>, ListOperationsResponse)Perform the operation you have build so far. #### pub fn project_id(self, new_value: &str) -> ProjectZoneOperationListCall<'a, SDeprecated. The Google Developers Console project ID or project number. This field has been deprecated and replaced by the parent field. Sets the *project id* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn zone(self, new_value: &str) -> ProjectZoneOperationListCall<'a, SDeprecated. The name of the Google Compute Engine zone to return operations for, or `-` for all zones. This field has been deprecated and replaced by the parent field. Sets the *zone* path property to the given value. Even though the property as already been set when instantiating this call, we provide this method for API completeness. #### pub fn parent(self, new_value: &str) -> ProjectZoneOperationListCall<'a, SThe parent (project and location) where the operations will be listed. Specified in the format `projects/*/locations/*`. Location “-” matches all zones and all regions. Sets the *parent* query property to the given value. #### pub fn delegate( self, new_value: &'a mut dyn Delegate ) -> ProjectZoneOperationListCall<'a, SThe delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong while executing the actual API request. ``` It should be used to handle progress information, and to implement a certain level of resilience. ``` Sets the *delegate* property to the given value. #### pub fn param<T>(self, name: T, value: T) -> ProjectZoneOperationListCall<'a, S>where T: AsRef<str>, Set any additional parameter of the query string used in the request. It should be used to set parameters which are not yet available through their own setters. Please note that this method must not be used to set any of the known parameters which have their own setter method. If done anyway, the request will fail. ##### Additional Parameters * *$.xgafv* (query-string) - V1 error format. * *access_token* (query-string) - OAuth access token. * *alt* (query-string) - Data format for response. * *callback* (query-string) - JSONP * *fields* (query-string) - Selector specifying which fields to include in a partial response. * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * *oauth_token* (query-string) - OAuth 2.0 token for the current user. * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * *uploadType* (query-string) - Legacy upload protocol for media (e.g. “media”, “multipart”). * *upload_protocol* (query-string) - Upload protocol for media (e.g. “raw”, “multipart”). #### pub fn add_scope<St>(self, scope: St) -> ProjectZoneOperationListCall<'a, S>where St: AsRef<str>, Identifies the authorization scope for the method you are building. Use this method to actively specify which scope should be used, instead of the default `Scope` variant `Scope::CloudPlatform`. The `scope` will be added to a set of scopes. This is important as one can maintain access tokens for more than one scope. Usually there is more than one suitable scope to authorize an operation, some of which may encompass more rights than others. For example, for listing resources, a *read-only* scope will be sufficient, a read-write scope will do as well. #### pub fn add_scopes<I, St>(self, scopes: I) -> ProjectZoneOperationListCall<'a, S>where I: IntoIterator<Item = St>, St: AsRef<str>, Identifies the authorization scope(s) for the method you are building. See `Self::add_scope()` for details. #### pub fn clear_scopes(self) -> ProjectZoneOperationListCall<'a, SRemoves all scopes, and no default scope will be used either. In this case, you have to specify your API-key using the `key` parameter (see `Self::param()` for details). Trait Implementations --- ### impl<'a, S> CallBuilder for ProjectZoneOperationListCall<'a, SAuto Trait Implementations --- ### impl<'a, S> !RefUnwindSafe for ProjectZoneOperationListCall<'a, S### impl<'a, S> Send for ProjectZoneOperationListCall<'a, S>where S: Sync, ### impl<'a, S> !Sync for ProjectZoneOperationListCall<'a, S### impl<'a, S> Unpin for ProjectZoneOperationListCall<'a, S### impl<'a, S> !UnwindSafe for ProjectZoneOperationListCall<'a, SBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Type Alias google_container1::Result === ``` pub type Result<T> = Result<T, Error>; ``` A universal result type used as return for all calls. Trait google_container1::Delegate === ``` pub trait Delegate: Send { // Provided methods fn begin(&mut self, _info: MethodInfo) { ... } fn http_error(&mut self, _err: &Error) -> Retry { ... } fn api_key(&mut self) -> Option<String> { ... } fn token( &mut self, e: Box<dyn Error + Send + Sync, Global> ) -> Result<Option<String>, Box<dyn Error + Send + Sync, Global>> { ... } fn upload_url(&mut self) -> Option<String> { ... } fn store_upload_url(&mut self, url: Option<&str>) { ... } fn response_json_decode_error( &mut self, json_encoded_value: &str, json_decode_error: &Error ) { ... } fn http_failure(&mut self, _: &Response<Body>, _err: Option<Value>) -> Retry { ... } fn pre_request(&mut self) { ... } fn chunk_size(&mut self) -> u64 { ... } fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { ... } fn finished(&mut self, is_success: bool) { ... } } ``` A trait specifying functionality to help controlling any request performed by the API. The trait has a conservative default implementation. It contains methods to deal with all common issues, as well with the ones related to uploading media Provided Methods --- #### fn begin(&mut self, _info: MethodInfo) Called at the beginning of any API request. The delegate should store the method information if he is interesting in knowing more context when further calls to it are made. The matching `finished()` call will always be made, no matter whether or not the API request was successful. That way, the delegate may easily maintain a clean state between various API calls. #### fn http_error(&mut self, _err: &Error) -> Retry Called whenever there is an HttpError, usually if there are network problems. If you choose to retry after a duration, the duration should be chosen using the exponential backoff algorithm. Return retry information. #### fn api_key(&mut self) -> Option<StringCalled whenever there is the need for your applications API key after the official authenticator implementation didn’t provide one, for some reason. If this method returns None as well, the underlying operation will fail #### fn token( &mut self, e: Box<dyn Error + Send + Sync, Global> ) -> Result<Option<String>, Box<dyn Error + Send + Sync, Global>Called whenever the Authenticator didn’t yield a token. The delegate may attempt to provide one, or just take it as a general information about the impending failure. The given Error provides information about why the token couldn’t be acquired in the first place #### fn upload_url(&mut self) -> Option<StringCalled during resumable uploads to provide a URL for the impending upload. It was saved after a previous call to `store_upload_url(...)`, and if not None, will be used instead of asking the server for a new upload URL. This is useful in case a previous resumable upload was aborted/canceled, but should now be resumed. The returned URL will be used exactly once - if it fails again and the delegate allows to retry, we will ask the server for a new upload URL. #### fn store_upload_url(&mut self, url: Option<&str>) Called after we have retrieved a new upload URL for a resumable upload to store it in case we fail or cancel. That way, we can attempt to resume the upload later, see `upload_url()`. It will also be called with None after a successful upload, which allows the delegate to forget the URL. That way, we will not attempt to resume an upload that has already finished. #### fn response_json_decode_error( &mut self, json_encoded_value: &str, json_decode_error: &Error ) Called whenever a server response could not be decoded from json. It’s for informational purposes only, the caller will return with an error accordingly. ##### Arguments * `json_encoded_value` - The json-encoded value which failed to decode. * `json_decode_error` - The decoder error #### fn http_failure(&mut self, _: &Response<Body>, _err: Option<Value>) -> Retry Called whenever the http request returns with a non-success status code. This can involve authentication issues, or anything else that very much depends on the used API method. The delegate should check the status, header and decoded json error to decide whether to retry or not. In the latter case, the underlying call will fail. If you choose to retry after a duration, the duration should be chosen using the exponential backoff algorithm. #### fn pre_request(&mut self) Called prior to sending the main request of the given method. It can be used to time the call or to print progress information. It’s also useful as you can be sure that a request will definitely be made. #### fn chunk_size(&mut self) -> u64 Return the size of each chunk of a resumable upload. Must be a power of two, with 1<<18 being the smallest allowed chunk size. Will be called once before starting any resumable upload. #### fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool Called before the given chunk is uploaded to the server. If true is returned, the upload will be interrupted. However, it may be resumable if you stored the upload URL in a previous call to `store_upload_url()` #### fn finished(&mut self, is_success: bool) Called before the API request method returns, in every case. It can be used to clean up internal state between calls to the API. This call always has a matching call to `begin(...)`. ##### Arguments * `is_success` - a true value indicates the operation was successful. If false, you should discard all values stored during `store_upload_url`. Implementors --- ### impl Delegate for DefaultDelegate Struct google_container1::FieldMask === ``` pub struct FieldMask(_); ``` A `FieldMask` as defined in `https://github.com/protocolbuffers/protobuf/blob/ec1a70913e5793a7d0a7b5fbf7e0e4f75409dd41/src/google/protobuf/field_mask.proto#L180` Trait Implementations --- ### impl Clone for FieldMask #### fn clone(&self) -> FieldMask Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn default() -> FieldMask Returns the “default value” for a type. #### fn deserialize<D>( deserializer: D ) -> Result<FieldMask, <D as Deserializer<'de>>::Error>where D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Err = Infallible The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<FieldMask, <FieldMask as FromStr>::ErrParses a string `s` to return a value of this type. #### fn eq(&self, other: &FieldMask) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Serialize for FieldMask #### fn serialize<S>( &self, s: S ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where S: Serializer, Serialize this value into the given Serde serializer. ### impl StructuralEq for FieldMask ### impl StructuralPartialEq for FieldMask Auto Trait Implementations --- ### impl RefUnwindSafe for FieldMask ### impl Send for FieldMask ### impl Sync for FieldMask ### impl Unpin for FieldMask ### impl UnwindSafe for FieldMask Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. T: for<'de> Deserialize<'de>, Enum google_container1::Error === ``` pub enum Error { HttpError(Error), UploadSizeLimitExceeded(u64, u64), BadRequest(Value), MissingAPIKey, MissingToken(Box<dyn Error + Send + Sync, Global>), Cancelled, FieldClash(&'static str), JsonDecodeError(String, Error), Failure(Response<Body>), Io(Error), } ``` Variants --- ### HttpError(Error) The http connection failed ### UploadSizeLimitExceeded(u64, u64) An attempt was made to upload a resource with size stored in field `.0` even though the maximum upload size is what is stored in field `.1`. ### BadRequest(Value) Represents information about a request that was not understood by the server. Details are included. ### MissingAPIKey We needed an API key for authentication, but didn’t obtain one. Neither through the authenticator, nor through the Delegate. ### MissingToken(Box<dyn Error + Send + Sync, Global>) We required a Token, but didn’t get one from the Authenticator ### Cancelled The delgate instructed to cancel the operation ### FieldClash(&'static str) An additional, free form field clashed with one of the built-in optional ones ### JsonDecodeError(String, Error) Shows that we failed to decode the server response. This can happen if the protocol changes in conjunction with strict json decoding. ### Failure(Response<Body>) Indicates an HTTP repsonse with a non-success status code ### Io(Error) An IO error occurred while reading a stream into memory Trait Implementations --- ### impl Debug for Error #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn from(err: Error) -> Error Converts to this type from the input type.Auto Trait Implementations --- ### impl !RefUnwindSafe for Error ### impl Send for Error ### impl Sync for Error ### impl Unpin for Error ### impl !UnwindSafe for Error Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToString for Twhere T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more
tinyrand
rust
Rust
Crate tinyrand === Traits describing a basic RNG and various capability extenders. The traits and RNGs here do not need stdlib to work, nor do they need `alloc`. Re-exports --- `pub use counter::Counter;``pub use splitmix::SplitMix;``pub use wyrand::Wyrand;``pub use xorshift::Xorshift;``pub use mock_support::RefCellExt;`Modules --- counterA wrap-around 64-bit counter. Useful for seeding and testing. durationExtensions for generating random `Duration`s. mock_supportSupporting capabilities for mocking. splitmix`SplitMix` RNG. wyrandWyrand RNG. xorshiftXorshift RNG. Structs --- ProbabilityRepresents a probability in the range [0, 1]. Traits --- RandA minimal specification of a random number generator. RandLimRandRangeSeededThe means for seeding an RNG. Type Definitions --- StdRandThe default/recommended `Rand` implementation. Crate tinyrand === Traits describing a basic RNG and various capability extenders. The traits and RNGs here do not need stdlib to work, nor do they need `alloc`. Re-exports --- `pub use counter::Counter;``pub use splitmix::SplitMix;``pub use wyrand::Wyrand;``pub use xorshift::Xorshift;``pub use mock_support::RefCellExt;`Modules --- counterA wrap-around 64-bit counter. Useful for seeding and testing. durationExtensions for generating random `Duration`s. mock_supportSupporting capabilities for mocking. splitmix`SplitMix` RNG. wyrandWyrand RNG. xorshiftXorshift RNG. Structs --- ProbabilityRepresents a probability in the range [0, 1]. Traits --- RandA minimal specification of a random number generator. RandLimRandRangeSeededThe means for seeding an RNG. Type Definitions --- StdRandThe default/recommended `Rand` implementation. Struct tinyrand::counter::Counter === ``` pub struct Counter(_); ``` A wrap-around counter. Examples --- ``` use tinyrand::{Counter, Rand}; let mut rand = Counter::default(); assert_eq!(0, rand.next_u64()); assert_eq!(1, rand.next_u64()); ``` Implementations --- ### impl Counter #### pub fn new(seed: u64) -> Self Trait Implementations --- ### impl Debug for Counter #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more ### impl Default for Counter #### fn default() -> Counter Returns the “default value” for a type. Read more ### impl Rand for Counter #### fn next_u64(&mut self) -> u64 Returns the next random `u64`. #### fn next_u16(&mut self) -> u16 Returns the next random `u16`. #### fn next_u32(&mut self) -> u32 Returns the next random `u32`. #### fn next_u128(&mut self) -> u128 Returns the next random `u128`. #### fn next_usize(&mut self) -> usize Returns the next random `usize`. #### fn next_bool(&mut self, p: Probability) -> bool Returns a `bool` with a probability `p` of being true. Read more #### fn next_lim_u16(&mut self, lim: u16) -> u16 Generates a random number in `0..lim`. #### fn next_lim_u32(&mut self, lim: u32) -> u32 Generates a random number in `0..lim`. #### fn next_lim_u64(&mut self, lim: u64) -> u64 Generates a random number in `0..lim`. #### fn next_lim_u128(&mut self, lim: u128) -> u128 Generates a random number in `0..lim`. #### fn next_lim_usize(&mut self, lim: usize) -> usize Generates a random number in `0..lim`. ### impl Seeded for Counter #### type R = Counter #### fn seed(seed: u64) -> Self::R Creates a new `Rand` instance from the given seed. Auto Trait Implementations --- ### impl RefUnwindSafe for Counter ### impl Send for Counter ### impl Sync for Counter ### impl Unpin for Counter ### impl UnwindSafe for Counter Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more ### impl<T> Borrow<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more ### impl<T> BorrowMut<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<R> RandLim<u128> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u128) -> u128 Generates a random number in `0..N`. ### impl<R> RandLim<u16> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u16) -> u16 Generates a random number in `0..N`. ### impl<R> RandLim<u32> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u32) -> u32 Generates a random number in `0..N`. ### impl<R> RandLim<u64> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u64) -> u64 Generates a random number in `0..N`. ### impl<R> RandLim<usize> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: usize) -> usize Generates a random number in `0..N`. ### impl<R> RandRange<Duration> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<Duration>) -> Duration Generates a random number in the given range. ### impl<R> RandRange<u128> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u128>) -> u128 Generates a random number in the given range. ### impl<R> RandRange<u16> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u16>) -> u16 Generates a random number in the given range. ### impl<R> RandRange<u32> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u32>) -> u32 Generates a random number in the given range. ### impl<R> RandRange<u64> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u64>) -> u64 Generates a random number in the given range. ### impl<R> RandRange<usize> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<usize>) -> usize Generates a random number in the given range. ### impl<T, U> TryFrom<U> for Twhere    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. ### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct tinyrand::splitmix::SplitMix === ``` pub struct SplitMix(_); ``` Trait Implementations --- ### impl Default for SplitMix #### fn default() -> Self Returns the “default value” for a type. Read more ### impl Rand for SplitMix #### fn next_u64(&mut self) -> u64 Returns the next random `u64`. #### fn next_u16(&mut self) -> u16 Returns the next random `u16`. #### fn next_u32(&mut self) -> u32 Returns the next random `u32`. #### fn next_u128(&mut self) -> u128 Returns the next random `u128`. #### fn next_usize(&mut self) -> usize Returns the next random `usize`. #### fn next_bool(&mut self, p: Probability) -> bool Returns a `bool` with a probability `p` of being true. Read more #### fn next_lim_u16(&mut self, lim: u16) -> u16 Generates a random number in `0..lim`. #### fn next_lim_u32(&mut self, lim: u32) -> u32 Generates a random number in `0..lim`. #### fn next_lim_u64(&mut self, lim: u64) -> u64 Generates a random number in `0..lim`. #### fn next_lim_u128(&mut self, lim: u128) -> u128 Generates a random number in `0..lim`. #### fn next_lim_usize(&mut self, lim: usize) -> usize Generates a random number in `0..lim`. ### impl Seeded for SplitMix #### type R = SplitMix #### fn seed(seed: u64) -> Self::R Creates a new `Rand` instance from the given seed. Auto Trait Implementations --- ### impl RefUnwindSafe for SplitMix ### impl Send for SplitMix ### impl Sync for SplitMix ### impl Unpin for SplitMix ### impl UnwindSafe for SplitMix Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more ### impl<T> Borrow<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more ### impl<T> BorrowMut<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<R> RandLim<u128> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u128) -> u128 Generates a random number in `0..N`. ### impl<R> RandLim<u16> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u16) -> u16 Generates a random number in `0..N`. ### impl<R> RandLim<u32> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u32) -> u32 Generates a random number in `0..N`. ### impl<R> RandLim<u64> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u64) -> u64 Generates a random number in `0..N`. ### impl<R> RandLim<usize> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: usize) -> usize Generates a random number in `0..N`. ### impl<R> RandRange<Duration> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<Duration>) -> Duration Generates a random number in the given range. ### impl<R> RandRange<u128> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u128>) -> u128 Generates a random number in the given range. ### impl<R> RandRange<u16> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u16>) -> u16 Generates a random number in the given range. ### impl<R> RandRange<u32> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u32>) -> u32 Generates a random number in the given range. ### impl<R> RandRange<u64> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u64>) -> u64 Generates a random number in the given range. ### impl<R> RandRange<usize> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<usize>) -> usize Generates a random number in the given range. ### impl<T, U> TryFrom<U> for Twhere    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. ### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct tinyrand::wyrand::Wyrand === ``` pub struct Wyrand(_); ``` Trait Implementations --- ### impl Default for Wyrand #### fn default() -> Wyrand Returns the “default value” for a type. Read more ### impl Rand for Wyrand #### fn next_u64(&mut self) -> u64 Returns the next random `u64`. #### fn next_u16(&mut self) -> u16 Returns the next random `u16`. #### fn next_u32(&mut self) -> u32 Returns the next random `u32`. #### fn next_u128(&mut self) -> u128 Returns the next random `u128`. #### fn next_usize(&mut self) -> usize Returns the next random `usize`. #### fn next_bool(&mut self, p: Probability) -> bool Returns a `bool` with a probability `p` of being true. Read more #### fn next_lim_u16(&mut self, lim: u16) -> u16 Generates a random number in `0..lim`. #### fn next_lim_u32(&mut self, lim: u32) -> u32 Generates a random number in `0..lim`. #### fn next_lim_u64(&mut self, lim: u64) -> u64 Generates a random number in `0..lim`. #### fn next_lim_u128(&mut self, lim: u128) -> u128 Generates a random number in `0..lim`. #### fn next_lim_usize(&mut self, lim: usize) -> usize Generates a random number in `0..lim`. ### impl Seeded for Wyrand #### type R = Wyrand #### fn seed(seed: u64) -> Self::R Creates a new `Rand` instance from the given seed. Auto Trait Implementations --- ### impl RefUnwindSafe for Wyrand ### impl Send for Wyrand ### impl Sync for Wyrand ### impl Unpin for Wyrand ### impl UnwindSafe for Wyrand Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more ### impl<T> Borrow<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more ### impl<T> BorrowMut<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<R> RandLim<u128> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u128) -> u128 Generates a random number in `0..N`. ### impl<R> RandLim<u16> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u16) -> u16 Generates a random number in `0..N`. ### impl<R> RandLim<u32> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u32) -> u32 Generates a random number in `0..N`. ### impl<R> RandLim<u64> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u64) -> u64 Generates a random number in `0..N`. ### impl<R> RandLim<usize> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: usize) -> usize Generates a random number in `0..N`. ### impl<R> RandRange<Duration> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<Duration>) -> Duration Generates a random number in the given range. ### impl<R> RandRange<u128> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u128>) -> u128 Generates a random number in the given range. ### impl<R> RandRange<u16> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u16>) -> u16 Generates a random number in the given range. ### impl<R> RandRange<u32> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u32>) -> u32 Generates a random number in the given range. ### impl<R> RandRange<u64> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u64>) -> u64 Generates a random number in the given range. ### impl<R> RandRange<usize> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<usize>) -> usize Generates a random number in the given range. ### impl<T, U> TryFrom<U> for Twhere    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. ### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct tinyrand::xorshift::Xorshift === ``` pub struct Xorshift(_); ``` Trait Implementations --- ### impl Default for Xorshift #### fn default() -> Self Returns the “default value” for a type. Read more ### impl Rand for Xorshift #### fn next_u64(&mut self) -> u64 Returns the next random `u64`. #### fn next_u16(&mut self) -> u16 Returns the next random `u16`. #### fn next_u32(&mut self) -> u32 Returns the next random `u32`. #### fn next_u128(&mut self) -> u128 Returns the next random `u128`. #### fn next_usize(&mut self) -> usize Returns the next random `usize`. #### fn next_bool(&mut self, p: Probability) -> bool Returns a `bool` with a probability `p` of being true. Read more #### fn next_lim_u16(&mut self, lim: u16) -> u16 Generates a random number in `0..lim`. #### fn next_lim_u32(&mut self, lim: u32) -> u32 Generates a random number in `0..lim`. #### fn next_lim_u64(&mut self, lim: u64) -> u64 Generates a random number in `0..lim`. #### fn next_lim_u128(&mut self, lim: u128) -> u128 Generates a random number in `0..lim`. #### fn next_lim_usize(&mut self, lim: usize) -> usize Generates a random number in `0..lim`. ### impl Seeded for Xorshift #### type R = Xorshift #### fn seed(seed: u64) -> Self::R Creates a new `Rand` instance from the given seed. Auto Trait Implementations --- ### impl RefUnwindSafe for Xorshift ### impl Send for Xorshift ### impl Sync for Xorshift ### impl Unpin for Xorshift ### impl UnwindSafe for Xorshift Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more ### impl<T> Borrow<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more ### impl<T> BorrowMut<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<R> RandLim<u128> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u128) -> u128 Generates a random number in `0..N`. ### impl<R> RandLim<u16> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u16) -> u16 Generates a random number in `0..N`. ### impl<R> RandLim<u32> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u32) -> u32 Generates a random number in `0..N`. ### impl<R> RandLim<u64> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: u64) -> u64 Generates a random number in `0..N`. ### impl<R> RandLim<usize> for Rwhere    R: Rand, #### fn next_lim(&mut self, lim: usize) -> usize Generates a random number in `0..N`. ### impl<R> RandRange<Duration> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<Duration>) -> Duration Generates a random number in the given range. ### impl<R> RandRange<u128> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u128>) -> u128 Generates a random number in the given range. ### impl<R> RandRange<u16> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u16>) -> u16 Generates a random number in the given range. ### impl<R> RandRange<u32> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u32>) -> u32 Generates a random number in the given range. ### impl<R> RandRange<u64> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<u64>) -> u64 Generates a random number in the given range. ### impl<R> RandRange<usize> for Rwhere    R: Rand, #### fn next_range(&mut self, range: Range<usize>) -> usize Generates a random number in the given range. ### impl<T, U> TryFrom<U> for Twhere    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. ### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Trait tinyrand::mock_support::RefCellExt === ``` pub trait RefCellExt<T> { fn get(&self) -> T; fn set(&self, val: T); } ``` Accessor and mutator methods for `RefCell`. Required Methods --- #### fn get(&self) -> T #### fn set(&self, val: T) Implementations on Foreign Types --- ### impl<T: Copy> RefCellExt<T> for RefCell<T#### fn get(&self) -> T #### fn set(&self, val: T) Implementors --- Module tinyrand::counter === A wrap-around 64-bit counter. Useful for seeding and testing. Structs --- CounterA wrap-around counter. Module tinyrand::duration === Extensions for generating random `Duration`s. Functions --- from_nanos`Duration::from_nanos` has limited range, which was not reverted post-stabilisation. This function permits the creation of a [`Duration]` from a `u128`, making it consistent with `Duration::as_nanos`. Module tinyrand::mock_support === Supporting capabilities for mocking. Traits --- RefCellExtAccessor and mutator methods for `RefCell`. Module tinyrand::splitmix === `SplitMix` RNG. Structs --- SplitMix Module tinyrand::wyrand === Wyrand RNG. Structs --- Wyrand Module tinyrand::xorshift === Xorshift RNG. Structs --- Xorshift Struct tinyrand::Probability === ``` pub struct Probability(_); ``` Represents a probability in the range [0, 1]. Implementations --- ### impl Probability #### pub fn new(p: f64) -> Self Creates a new `Probability` value, bounded in the range [0, 1]. ##### Example ``` use tinyrand::Probability; let p = Probability::new(0.25); assert_eq!(0.25, p.into()); ``` ##### Panics If `p < 0` or `p > 1`. #### pub const unsafe fn new_unchecked(p: f64) -> Self Creates a new `Probability` value, without checking the bounds. ##### Safety If a probability is created outside the range [0, 1], its behaviour with an RNG is undefined. Trait Implementations --- ### impl Clone for Probability #### fn clone(&self) -> Probability Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more ### impl Debug for Probability #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more ### impl From<Probability> for f64 #### fn from(p: Probability) -> Self Converts to this type from the input type. ### impl From<f64> for Probability #### fn from(p: f64) -> Self Converts to this type from the input type. ### impl PartialEq<Probability> for Probability #### fn eq(&self, other: &Probability) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more 1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more ### impl Copy for Probability ### impl StructuralPartialEq for Probability Auto Trait Implementations --- ### impl RefUnwindSafe for Probability ### impl Send for Probability ### impl Sync for Probability ### impl Unpin for Probability ### impl UnwindSafe for Probability Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more ### impl<T> Borrow<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more ### impl<T> BorrowMut<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. ### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Trait tinyrand::Rand === ``` pub trait Rand { fn next_u64(&mut self) -> u64; fn next_u16(&mut self) -> u16 { ... } fn next_u32(&mut self) -> u32 { ... } fn next_u128(&mut self) -> u128 { ... } fn next_usize(&mut self) -> usize { ... } fn next_bool(&mut self, p: Probability) -> bool { ... } fn next_lim_u16(&mut self, lim: u16) -> u16 { ... } fn next_lim_u32(&mut self, lim: u32) -> u32 { ... } fn next_lim_u64(&mut self, lim: u64) -> u64 { ... } fn next_lim_u128(&mut self, lim: u128) -> u128 { ... } fn next_lim_usize(&mut self, lim: usize) -> usize { ... } } ``` A minimal specification of a random number generator. Implementers must, at minimum, provide a working `Rand::next_u64`. The rest of the methods will be derived. The default implementations either truncate the generated number (`u16`, `u32`) or generate several numbers and splice the outputs (`u128`). Implementers may provide more efficient versions for `u16`, `u32` and `u128` generators, overriding the defaults. Required Methods --- #### fn next_u64(&mut self) -> u64 Returns the next random `u64`. Provided Methods --- #### fn next_u16(&mut self) -> u16 Returns the next random `u16`. #### fn next_u32(&mut self) -> u32 Returns the next random `u32`. #### fn next_u128(&mut self) -> u128 Returns the next random `u128`. #### fn next_usize(&mut self) -> usize Returns the next random `usize`. #### fn next_bool(&mut self, p: Probability) -> bool Returns a `bool` with a probability `p` of being true. ##### Example ``` use tinyrand::{StdRand, Probability, Rand}; let mut rng = StdRand::default(); println!("{}", rng.next_bool(Probability::new(1.0 / 3.0))); ``` #### fn next_lim_u16(&mut self, lim: u16) -> u16 Generates a random number in `0..lim`. #### fn next_lim_u32(&mut self, lim: u32) -> u32 Generates a random number in `0..lim`. #### fn next_lim_u64(&mut self, lim: u64) -> u64 Generates a random number in `0..lim`. #### fn next_lim_u128(&mut self, lim: u128) -> u128 Generates a random number in `0..lim`. #### fn next_lim_usize(&mut self, lim: usize) -> usize Generates a random number in `0..lim`. Implementors --- ### impl Rand for Counter ### impl Rand for SplitMix ### impl Rand for Wyrand ### impl Rand for Xorshift Trait tinyrand::RandLim === ``` pub trait RandLim<N> { fn next_lim(&mut self, lim: N) -> N; } ``` Required Methods --- #### fn next_lim(&mut self, lim: N) -> N Generates a random number in `0..N`. Implementors --- ### impl<R: Rand> RandLim<u16> for R ### impl<R: Rand> RandLim<u32> for R ### impl<R: Rand> RandLim<u64> for R ### impl<R: Rand> RandLim<u128> for R ### impl<R: Rand> RandLim<usize> for R Trait tinyrand::RandRange === ``` pub trait RandRange<N> { fn next_range(&mut self, range: Range<N>) -> N; } ``` Required Methods --- #### fn next_range(&mut self, range: Range<N>) -> N Generates a random number in the given range. Implementors --- ### impl<R: Rand> RandRange<u16> for R ### impl<R: Rand> RandRange<u32> for R ### impl<R: Rand> RandRange<u64> for R ### impl<R: Rand> RandRange<u128> for R ### impl<R: Rand> RandRange<usize> for R ### impl<R: Rand> RandRange<Duration> for R Trait tinyrand::Seeded === ``` pub trait Seeded { type R: Rand; fn seed(seed: u64) -> Self::R; } ``` The means for seeding an RNG. Required Associated Types --- #### type R: Rand Required Methods --- #### fn seed(seed: u64) -> Self::R Creates a new `Rand` instance from the given seed. Implementors --- ### impl Seeded for Counter #### type R = Counter ### impl Seeded for SplitMix #### type R = SplitMix ### impl Seeded for Wyrand #### type R = Wyrand ### impl Seeded for Xorshift #### type R = Xorshift Type Definition tinyrand::StdRand === ``` pub type StdRand = Wyrand; ``` The default/recommended `Rand` implementation.
Hebel
readthedoc
YAML
Hebel 0.02 documentation [Hebel](index.html#document-index) --- Welcome to Hebel’s documentation![¶](#welcome-to-hebel-s-documentation) === Contents: Getting Started[¶](#getting-started) --- There are two basic methods how you can run Hebel: 1. You can write a YAML configuration file that describes your model architecture, data set, and hyperparameters and run it using the `train_model.py` script. 2. In your own Python script or program, you can create instances of models and optimizers programmatically. The first makes estimating a model the easiest, as you don’t have to write any actual code. You simply specify all your parameters and data set in an easy to read YAML configuration file and pass it to the `train_model.py` script. The script will create a directory for your results where it will save intermediary models (in pickle-format), the logs and final results. The second method gives you more control over how exactly the model is estimated and lets you interact with Hebel from other Python programs. ### Running models from YAML configuration files[¶](#running-models-from-yaml-configuration-files) If you check the example YAML files in `examples/` you will see that the configuration file defines three top-level sections: 1. `run_conf`: These options are passed to the method [`hebel.optimizers.SGD.run()`](index.html#hebel.optimizers.SGD.run). 2. `optimizer`: Here you instantiate a [`hebel.optimizers.SGD`](index.html#hebel.optimizers.SGD) object, including the model you want to train and the data to use for training and validation. 3. `test_dataset`: This section is optional, but here you can define test data to evaluate the model on after training. Check out `examples/mnist_neural_net_shallow.yml`, which includes everything to train a one layer neural network on the [MNIST dataset](http://yann.lecun.com/exdb/mnist/): ``` run_conf: iterations: 50 optimizer: !obj:hebel.optimizers.SGD { model: !obj:hebel.models.NeuralNet { layers: [ !obj:hebel.layers.HiddenLayer { n_in: 784, n_units: 2000, dropout: yes, l2_penalty_weight: .0 } ], top_layer: !obj:hebel.layers.SoftmaxLayer { n_in: 2000, n_out: 10 } }, parameter_updater: !import hebel.parameter_updaters.MomentumUpdate, train_data: !obj:hebel.data_providers.MNISTDataProvider { batch_size: 100, array: train }, validation_data: !obj:hebel.data_providers.MNISTDataProvider { array: val }, learning_rate_schedule: !obj:hebel.schedulers.exponential_scheduler { init_value: 30., decay: .995 }, momentum_schedule: !obj:hebel.schedulers.linear_scheduler_up { init_value: .5, target_value: .9, duration: 10 }, progress_monitor: !obj:hebel.monitors.ProgressMonitor { experiment_name: mnist_shallow, save_model_path: examples/mnist, output_to_log: yes } } test_dataset: test_data: !obj:hebel.data_providers.MNISTDataProvider { array: test } ``` You can see that the only option we pass to `run_conf` is the number of iterations to train the model. The `optimizer` section is more interesting. Hebel uses the special `!obj`, `!import`, and `!pkl` directives from [PyLearn 2](http://deeplearning.net/software/pylearn2/yaml_tutorial/index.html#yaml-tutorial). The `!obj` directive is used most extensively and can be used to instantiate any Python class. First the optimizer [`hebel.optimizers.SGD`](index.html#hebel.optimizers.SGD) is instantiated and in the lines below we are instantiating the model: ``` optimizer: !obj:hebel.optimizers.SGD { model: !obj:hebel.models.NeuralNet { layers: [ !obj:hebel.layers.HiddenLayer { n_in: 784, n_units: 2000, dropout: yes, l2_penalty_weight: .0 } ], top_layer: !obj:hebel.layers.SoftmaxLayer { n_in: 2000, n_out: 10 } }, ``` We are designing a model with one hidden layer that has 784 input units (the dimensionality of the MNIST data) and 2000 hidden units. We are also using [dropout](http://arxiv.org/abs/1207.0580) for regularization. The logistic output layer uses 10 classes (the number of classes in the MNIST data). You can also add different amounts of L1 or L2 penalization to each layer, which we are not doing here. Next, we define a `parameter_updater`, which is a rule that defines how the weights are updated given the gradients: ``` parameter_updater: !import hebel.parameter_updaters.MomentumUpdate, ``` There are currently three choices: * [`hebel.parameter_updaters.SimpleSGDUpdate`](index.html#hebel.parameter_updaters.SimpleSGDUpdate), which performs regular gradient descent * [`hebel.parameter_updaters.MomentumUpdate`](index.html#hebel.parameter_updaters.MomentumUpdate), which performs gradient descent with momentum, and * [`hebel.parameter_updaters.NesterovMomentumUpdate`](index.html#hebel.parameter_updaters.NesterovMomentumUpdate), which performs gradient descent with Nesterov momentum. The next two sections define the data for the model. All data must be given as instances of `DataProvider` objects: ``` train_data: !obj:hebel.data_providers.MNISTDataProvider { batch_size: 100, array: train }, validation_data: !obj:hebel.data_providers.MNISTDataProvider { array: val }, ``` A `DataProvider` is a class that defines an iterator which returns successive minibatches of the data as well as saves some metadata, such as the number of data points. There is a special [`hebel.data_providers.MNISTDataProvider`](index.html#hebel.data_providers.MNISTDataProvider) especially for the MNIST data. We use the standard splits for training and validation data here. There are several `DataProviders` defined in [`hebel.data_providers`](index.html#module-hebel.data_providers). The next few lines define how some of the hyperparameters are changed over the course of the training: ``` learning_rate_schedule: !obj:hebel.schedulers.exponential_scheduler { init_value: 30., decay: .995 }, momentum_schedule: !obj:hebel.schedulers.linear_scheduler_up { init_value: .5, target_value: .9, duration: 10 }, ``` The module `hebel.schedulers` defines several schedulers, which are basically just simple rules how certain parameters should evolve. Here, we define that the learning rate should decay exponentially with a factor of 0.995 in every epoch and the momentum should increase from 0.5 to 0.9 during the first 10 epochs and then stay at this value. The last entry argument to [`hebel.optimizers.SGD`](index.html#hebel.optimizers.SGD) is `progress_monitor`: ``` progress_monitor: !obj:hebel.monitors.ProgressMonitor { experiment_name: mnist_shallow, save_model_path: examples/mnist, output_to_log: yes } } ``` A progress monitor is an object that takes care of reporting periodic progress of our model, saving snapshots of the model at regular intervals, etc. When you are using the YAML configuration system, you’ll probably want to use [`hebel.monitors.ProgressMonitor`](index.html#hebel.monitors.ProgressMonitor), which will save logs, outputs, and snapshots to disk. In contrast, [`hebel.monitors.SimpleProgressMonitor`](index.html#hebel.monitors.SimpleProgressMonitor) will only print progress to the terminal without saving the model itself. Finally, you can define a test data set to be evaluated after the training completes: ``` test_data: !obj:hebel.data_providers.MNISTDataProvider { array: test } ``` Here, we are specifying the MNIST test split. Once you have your configuration file defined, you can run it such as in: ``` python train_model.py examples/mnist_neural_net_shallow.yml ``` The script will create the output directory you specified in `save_model_path` if it doesn’t exist yet and start writing the log into a file called `output_log`. If you are interested in keeping an eye on the training process you can check on that file with: ``` tail -f output_log ``` ### Using Hebel in Your Own Code[¶](#using-hebel-in-your-own-code) If you want more control over the training procedure or integrate Hebel with your own code, then you can use Hebel programmatically. Unlike the simpler one hidden layer model from the previous part, here we are going to build a more powerful deep neural net with multiple hidden layers. For an example, have a look at `examples/mnist_neural_net_deep_script.py`: ``` #!/usr/bin/env python import hebel from hebel.models import NeuralNet from hebel.optimizers import SGD from hebel.parameter_updaters import MomentumUpdate from hebel.data_providers import MNISTDataProvider from hebel.monitors import ProgressMonitor from hebel.schedulers import exponential_scheduler, linear_scheduler_up hebel.init(random_seed=0) # Initialize data providers train_data = MNISTDataProvider('train', batch_size=100) validation_data = MNISTDataProvider('val') test_data = MNISTDataProvider('test') D = train_data.D # Dimensionality of inputs K = 10 # Number of classes # Create model object model = NeuralNet(n_in=train_data.D, n_out=K, layers=[2000, 2000, 2000, 500], activation_function='relu', dropout=True, input_dropout=0.2) # Create optimizer object progress_monitor = ProgressMonitor( experiment_name='mnist', save_model_path='examples/mnist', save_interval=5, output_to_log=True) optimizer = SGD(model, MomentumUpdate, train_data, validation_data, progress_monitor, learning_rate_schedule=exponential_scheduler(5., .995), momentum_schedule=linear_scheduler_up(.1, .9, 100)) # Run model optimizer.run(50) # Evaulate error on test set test_error = model.test_error(test_data) print "Error on test set: %.3f" % test_error ``` There are three basic tasks you have to do to train a model in Hebel: 1. Define the data you want to use for training, validation, or testing using `DataProvider` objects, 2. instantiate a `Model` object, and 3. instantiate an `SGD` object that will train the model using stochastic gradient descent. #### Defining a Data Set[¶](#defining-a-data-set) In this example we’re using the MNIST data set again through the [`hebel.data_providers.MNISTDataProvider`](index.html#hebel.data_providers.MNISTDataProvider) class: ``` from hebel.schedulers import exponential_scheduler, linear_scheduler_up hebel.init(random_seed=0) ``` We create three data sets, corresponding to the official training, validation, and test data splits of MNIST. For the training data set, we set a batch size of 100 training examples, while the validation and test data sets are used as complete batches. #### Instantiating a model[¶](#instantiating-a-model) To train a model, you simply need to create an object representing a model that inherits from the abstract base class [`hebel.models.Model`](index.html#hebel.models.Model). ``` D = train_data.D # Dimensionality of inputs K = 10 # Number of classes # Create model object ``` Currently, Hebel implements the following models: * [`hebel.models.NeuralNet`](index.html#hebel.models.NeuralNet): A neural net with any number of hidden layers for classification, using the cross-entropy loss function and softmax units in the output layer. * [`hebel.models.LogisticRegression`](index.html#hebel.models.LogisticRegression): Multi-class logistic regression. Like [`hebel.models.NeuralNet`](index.html#hebel.models.NeuralNet) but does not have any hidden layers. * [`hebel.models.MultitaskNeuralNet`](index.html#hebel.models.MultitaskNeuralNet): A neural net trained on multiple tasks simultaneously. A multi-task neural net can have any number of hidden layers with weights that are shared between the tasks and any number of output layers with separate weights for each task. * [`hebel.models.NeuralNetRegression`](index.html#hebel.models.NeuralNetRegression): A neural net with a linear regression output layer to model continuous variables. The [`hebel.models.NeuralNet`](index.html#hebel.models.NeuralNet) model we are using here takes as input the dimensionality of the data, the number of classes, the sizes of the hidden layers, the activation function to use, and whether to use dropout for regularization. There are also a few more options such as for L1 or L2 weight regularization, that we don’t use here. Here, we are using the simpler form of the constructor rather than the extended form that we used in the YAML example. Also we are adding a small amount of dropout (20%) to the input layer. #### Training the model[¶](#training-the-model) To train the model, you first need to create an instance of [`hebel.optimizers.SGD`](index.html#hebel.optimizers.SGD): ``` layers=[2000, 2000, 2000, 500], activation_function='relu', dropout=True, input_dropout=0.2) # Create optimizer object progress_monitor = ProgressMonitor( experiment_name='mnist', save_model_path='examples/mnist', save_interval=5, output_to_log=True) optimizer = SGD(model, MomentumUpdate, train_data, validation_data, progress_monitor, learning_rate_schedule=exponential_scheduler(5., .995), ``` First we are creating a [`hebel.monitors.ProgressMonitor`](index.html#hebel.monitors.ProgressMonitor) object, that will save regular snapshots of the model during training and save the logs and results to disk. Next, we are creating the [`hebel.optimizers.SGD`](index.html#hebel.optimizers.SGD) object. We instantiate the optimizer with the model, the parameter update rule, training data, validation data, and the schedulers for the learning rate and the momentum parameters. Finally, we can start the training by invoking the [`hebel.optimizers.SGD.run()`](index.html#hebel.optimizers.SGD.run) method. Here we train the model for 100 epochs. However, by default [`hebel.optimizers.SGD`](index.html#hebel.optimizers.SGD) uses early stopping which means that it remembers the parameters that give the best result on the validation set and will reset the model parameters to them after the end of training. #### Evaluating on test data[¶](#evaluating-on-test-data) After training is complete we can do anything we want with the trained model, such as using it in some prediction pipeline, pickle it to disk, etc. Here we are evaluating the performance of the model on the MNIST test data split: ``` # Run model optimizer.run(50) ``` Initialization[¶](#module-hebel) --- Before Hebel can be used, it must be initialized using the function [`hebel.init()`](#hebel.init). `hebel.``init`(*device_id=None*, *random_seed=None*)[¶](#hebel.init) Initialize Hebel. This function creates a CUDA context, CUBLAS context and initializes and seeds the pseudo-random number generator. **Parameters:** device_id : integer, optional The ID of the GPU device to use. If this is omitted, PyCUDA’s default context is used, which by default uses the fastest available device on the system. Alternatively, you can put the device id in the environment variable `CUDA_DEVICE` or into the file `.cuda-device` in the user’s home directory. random_seed : integer, optional The seed to use for the pseudo-random number generator. If this is omitted, the seed is taken from the environment variable `RANDOM_SEED` and if that is not defined, a random integer is used as a seed. Data Providers[¶](#module-hebel.data_providers) --- All data consumed by Hebel models must be provided in the form of `DataProvider` objects. `DataProviders` are classes that provide iterators which return batches for training. By writing custom `DataProviders``, this creates a lot of flexibility about where data can come from and enables any sort of pre-processing on the data. For example, a user could write a `DataProvider` that receives data from the internet or through a pipe from a different process. Or, when working with text data, a user may define a custom `DataProvider` to perform tokenization and stemming on the text before returning it. A `DataProvider` is defined by subclassing the `hebel.data_provider.DataProvider` class and must implement at a minimum the special methods `__iter__` and `next`. ### Abstract Base Class[¶](#abstract-base-class) *class* `hebel.data_providers.``DataProvider`(*data*, *targets*, *batch_size*)[¶](#hebel.data_providers.DataProvider) This is the abstract base class for `DataProvider` objects. Subclass this class to implement a custom design. At a minimum you must provide implementations of the `next` method. ### Minibatch Data Provider[¶](#minibatch-data-provider) *class* `hebel.data_providers.``MiniBatchDataProvider`(*data*, *targets*, *batch_size*)[¶](#hebel.data_providers.MiniBatchDataProvider) This is the standard `DataProvider` for mini-batch learning with stochastic gradient descent. Input and target data may either be provided as `numpy.array` objects, or as `pycuda.GPUArray` objects. The latter is preferred if the data can fit on GPU memory and will be much faster, as the data won’t have to be transferred to the GPU for every minibatch. If the data is provided as a `numpy.array`, then every minibatch is automatically converted to to a `pycuda.GPUArray` and transferred to the GPU. | Parameters: | * **data** – Input data. * **targets** – Target data. * **batch_size** – The size of mini-batches. | ### Multi-Task Data Provider[¶](#multi-task-data-provider) *class* `hebel.data_providers.``MultiTaskDataProvider`(*data*, *targets*, *batch_size=None*)[¶](#hebel.data_providers.MultiTaskDataProvider) `DataProvider` for multi-task learning that uses the same training data for multiple targets. This `DataProvider` is similar to the `hebel.data_provider.MiniBatchDataProvider`, except that it has not one but multiple targets. | Parameters: | * **data** – Input data. * **targets** – Multiple targets as a list or tuple. * **batch_size** – The size of mini-batches. | **See also:** [`hebel.models.MultitaskNeuralNet`](index.html#hebel.models.MultitaskNeuralNet), [`hebel.layers.MultitaskTopLayer`](index.html#hebel.layers.MultitaskTopLayer) ### Batch Data Provider[¶](#batch-data-provider) *class* `hebel.data_providers.``BatchDataProvider`(*data*, *targets*)[¶](#hebel.data_providers.BatchDataProvider) `DataProvider` for batch learning. Always returns the full data set. | Parameters: | * **data** – Input data. * **targets** – Target data. | **See also:** [`hebel.data_providers.MiniBatchDataProvider`](#hebel.data_providers.MiniBatchDataProvider) ### Dummy Data Provider[¶](#dummy-data-provider) *class* `hebel.data_providers.``DummyDataProvider`(**args*, ***kwargs*)[¶](#hebel.data_providers.DummyDataProvider) A dummy `DataProvider` that does not store any data and always returns `None`. ### MNIST Data Provider[¶](#mnist-data-provider) *class* `hebel.data_providers.``MNISTDataProvider`(*array*, *batch_size=None*)[¶](#hebel.data_providers.MNISTDataProvider) `DataProvider` that automatically provides data from the [MNIST](http://yann.lecun.com/exdb/mnist/) data set of hand-written digits. Depends on the [skdata](http://jaberg.github.io/skdata/) package. | Parameters: | * **array** – {‘train’, ‘val’, ‘test’} Whether to use the official training, validation, or test data split of MNIST. * **batch_size** – The size of mini-batches. | Layers[¶](#layers) --- ### Hidden Layer[¶](#hidden-layer) *class* `hebel.layers.``HiddenLayer`(*n_in*, *n_units*, *activation_function='sigmoid'*, *dropout=False*, *parameters=None*, *weights_scale=None*, *l1_penalty_weight=0.0*, *l2_penalty_weight=0.0*, *lr_multiplier=None*)[¶](#hebel.layers.HiddenLayer) A fully connected hidden layer. The `HiddenLayer` class represents a fully connected hidden layer that can use a multitude of activation functions and supports dropout, L1, and L2 regularization. **Parameters:** n_in : integer Number of input units. n_out : integer Number of hidden units. activation_function : {`sigmoid`, `tanh`, `relu`, `linear`}, optional Which activation function to use. Default is sigmoid. dropout : bool Whether the layer should use dropout (with dropout probability 0.5) parameters : array_like of `GPUArray` Parameters used to initialize the layer. If this is omitted, then the weights are initalized randomly using *Bengio’s rule* (uniform distribution with scale \(4 \cdot \sqrt{6 / (\mathtt{n\_in} + \mathtt{n\_out})}\) if using sigmoid activations and \(\sqrt{6 / (\mathtt{n\_in} + \mathtt{n\_out})}\) if using tanh, relu, or linear activations) and the biases are initialized to zero. If `parameters` is given, then is must be in the form `[weights, biases]`, where the shape of weights is `(n_in, n_out)` and the shape of `biases` is `(n_out,)`. Both weights and biases must be `GPUArray`. weights_scale : float, optional If `parameters` is omitted, then this factor is used as scale for initializing the weights instead of *Bengio’s rule*. l1_penalty_weight : float, optional Weight used for L1 regularization of the weights. l2_penalty_weight : float, optional Weight used for L2 regularization of the weights. lr_multiplier : float, optional If this parameter is omitted, then the learning rate for the layer is scaled by \(2 / \sqrt{\mathtt{n\_in}}\). You may specify a different factor here. **Examples**: ``` # Use the simple initializer and initialize with random weights hidden_layer = HiddenLayer(500, 10000) # Sample weights yourself, specify an L1 penalty, and don't # use learning rate scaling import numpy as np from pycuda import gpuarray n_in = 500 n_out = 1000 weights = gpuarray.to_gpu(.01 * np.random.randn(n_in, n_out)) biases = gpuarray.to_gpu(np.zeros((n_out,))) hidden_layer = HiddenLayer(n_in, n_out, parameters=(weights, biases), l1_penalty_weight=.1, lr_multiplier=1.) ``` `architecture`[¶](#hebel.layers.HiddenLayer.architecture) Returns a dictionary describing the architecture of the layer. `backprop`(*input_data*, *df_output*, *cache=None*)[¶](#hebel.layers.HiddenLayer.backprop) Backpropagate through the hidden layer **Parameters:** input_data : `GPUArray` Inpute data to compute activations for. df_output : `GPUArray` Gradients with respect to the activations of this layer (received from the layer above). cache : list of `GPUArray` Cache obtained from forward pass. If the cache is provided, then the activations are not recalculated. **Returns:** gradients : tuple of `GPUArray` Gradients with respect to the weights and biases in the form `(df_weights, df_biases)`. df_input : `GPUArray` Gradients with respect to the input. `feed_forward`(*input_data*, *prediction=False*)[¶](#hebel.layers.HiddenLayer.feed_forward) Propagate forward through the layer **Parameters:** input_data : `GPUArray` Inpute data to compute activations for. prediction : bool, optional Whether to use prediction model. Only relevant when using dropout. If true, then weights are halved if the layers uses dropout. **Returns:** activations : `GPUArray` The activations of the hidden units. `parameters`[¶](#hebel.layers.HiddenLayer.parameters) Return a tuple `(weights, biases)` *class* `hebel.layers.``InputDropout`(*n_in*, *dropout_probability=0.2*, *compute_input_gradients=False*)[¶](#hebel.layers.InputDropout) This layer performs dropout on the input data. It does not have any learnable parameters of its own. It should be used as the first layer and will perform dropout with any dropout probability on the incoming data. **Parameters:** n_in : integer Number of input units. dropout_probability : float in [0, 1] Probability of dropping out each unit. compute_input_gradients : Bool Whether to compute the gradients with respect to the input data. This only necessary if you’re training a model where the input itself is learned. `backprop`(*input_data*, *df_output*, *cache=None*)[¶](#hebel.layers.InputDropout.backprop) Backpropagate through the hidden layer **Parameters:** input_data : `GPUArray` Inpute data to perform dropout on. df_output : `GPUArray` Gradients with respect to the output of this layer (received from the layer above). cache : list of `GPUArray` Cache obtained from forward pass. If the cache is provided, then the activations are not recalculated. **Returns:** gradients : empty tuple Gradients are empty since this layer has no parameters. df_input : `GPUArray` Gradients with respect to the input. `feed_forward`(*input_data*, *prediction=False*)[¶](#hebel.layers.InputDropout.feed_forward) Propagate forward through the layer **Parameters:** input_data : `GPUArray` Inpute data to perform dropout on. prediction : bool, optional Whether to use prediction model. If true, then the data is scaled by `1 - dropout_probability` uses dropout. **Returns:** dropout_data : `GPUArray` The data after performing dropout. *class* `hebel.layers.``DummyLayer`(*n_in*)[¶](#hebel.layers.DummyLayer) This class has no hidden units and simply passes through its input ### Top Layers[¶](#top-layers) #### Abstract Base Class Top Layer[¶](#abstract-base-class-top-layer) *class* `hebel.layers.``TopLayer`(*n_in*, *n_units*, *activation_function='sigmoid'*, *dropout=False*, *parameters=None*, *weights_scale=None*, *l1_penalty_weight=0.0*, *l2_penalty_weight=0.0*, *lr_multiplier=None*)[¶](#hebel.layers.TopLayer) Abstract base class for a top-level layer. #### Logistic Layer[¶](#logistic-layer) *class* `hebel.layers.``LogisticLayer`(*n_in*, *parameters=None*, *weights_scale=None*, *l1_penalty_weight=0.0*, *l2_penalty_weight=0.0*, *lr_multiplier=None*, *test_error_fct='class_error'*)[¶](#hebel.layers.LogisticLayer) A logistic classification layer for two classes, using cross-entropy loss function and sigmoid activations. **Parameters:** n_in : integer Number of input units. parameters : array_like of `GPUArray` Parameters used to initialize the layer. If this is omitted, then the weights are initalized randomly using *Bengio’s rule* (uniform distribution with scale \(4 \cdot \sqrt{6 / (\mathtt{n\_in} + \mathtt{n\_out})}\)) and the biases are initialized to zero. If `parameters` is given, then is must be in the form `[weights, biases]`, where the shape of weights is `(n_in, n_out)` and the shape of `biases` is `(n_out,)`. Both weights and biases must be `GPUArray`. weights_scale : float, optional If `parameters` is omitted, then this factor is used as scale for initializing the weights instead of *Bengio’s rule*. l1_penalty_weight : float, optional Weight used for L1 regularization of the weights. l2_penalty_weight : float, optional Weight used for L2 regularization of the weights. lr_multiplier : float, optional If this parameter is omitted, then the learning rate for the layer is scaled by \(2 / \sqrt{\mathtt{n\_in}}\). You may specify a different factor here. test_error_fct : {`class_error`, `kl_error`, `cross_entropy_error`}, optional Which error function to use on the test set. Default is `class_error` for classification error. Other choices are `kl_error`, the Kullback-Leibler divergence, or `cross_entropy_error`. **See also:** [`hebel.layers.SoftmaxLayer`](#hebel.layers.SoftmaxLayer), [`hebel.models.NeuralNet`](index.html#hebel.models.NeuralNet), [`hebel.models.NeuralNetRegression`](index.html#hebel.models.NeuralNetRegression), [`hebel.layers.LinearRegressionLayer`](#hebel.layers.LinearRegressionLayer) **Examples**: ``` # Use the simple initializer and initialize with random weights logistic_layer = LogisticLayer(1000) # Sample weights yourself, specify an L1 penalty, and don't # use learning rate scaling import numpy as np from pycuda import gpuarray n_in = 1000 weights = gpuarray.to_gpu(.01 * np.random.randn(n_in, 1)) biases = gpuarray.to_gpu(np.zeros((1,))) softmax_layer = SoftmaxLayer(n_in, parameters=(weights, biases), l1_penalty_weight=.1, lr_multiplier=1.) ``` `backprop`(*input_data*, *targets*, *cache=None*)[¶](#hebel.layers.LogisticLayer.backprop) Backpropagate through the logistic layer. **Parameters:** input_data : `GPUArray` Inpute data to compute activations for. targets : `GPUArray` The target values of the units. cache : list of `GPUArray` Cache obtained from forward pass. If the cache is provided, then the activations are not recalculated. **Returns:** gradients : tuple of `GPUArray` Gradients with respect to the weights and biases in the form `(df_weights, df_biases)`. df_input : `GPUArray` Gradients with respect to the input. `class_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=False*)[¶](#hebel.layers.LogisticLayer.class_error) Return the classification error rate `cross_entropy_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=False*)[¶](#hebel.layers.LogisticLayer.cross_entropy_error) Return the cross entropy error `feed_forward`(*input_data*, *prediction=False*)[¶](#hebel.layers.LogisticLayer.feed_forward) Propagate forward through the layer. **Parameters:** input_data : `GPUArray` Inpute data to compute activations for. prediction : bool, optional Whether to use prediction model. Only relevant when using dropout. If true, then weights are halved if the layers uses dropout. **Returns:** activations : `GPUArray` The activations of the output units. `test_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=True*)[¶](#hebel.layers.LogisticLayer.test_error) Compute the test error function given some data and targets. Uses the error function defined in `SoftmaxLayer.test_error_fct`, which may be different from the cross-entropy error function used for training’. Alternatively, the other test error functions may be called directly. **Parameters:** input_data : `GPUArray` Inpute data to compute the test error function for. targets : `GPUArray` The target values of the units. average : bool Whether to divide the value of the error function by the number of data points given. cache : list of `GPUArray` Cache obtained from forward pass. If the cache is provided, then the activations are not recalculated. prediction : bool, optional Whether to use prediction model. Only relevant when using dropout. If true, then weights are halved if the layers uses dropout. **Returns:** test_error : float `train_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=False*)[¶](#hebel.layers.LogisticLayer.train_error) Return the cross entropy error #### Softmax Layer[¶](#softmax-layer) *class* `hebel.layers.``SoftmaxLayer`(*n_in*, *n_out*, *parameters=None*, *weights_scale=None*, *l1_penalty_weight=0.0*, *l2_penalty_weight=0.0*, *lr_multiplier=None*, *test_error_fct='class_error'*)[¶](#hebel.layers.SoftmaxLayer) A multiclass classification layer, using cross-entropy loss function and softmax activations. **Parameters:** n_in : integer Number of input units. n_out : integer Number of output units (classes). parameters : array_like of `GPUArray` Parameters used to initialize the layer. If this is omitted, then the weights are initalized randomly using *Bengio’s rule* (uniform distribution with scale \(4 \cdot \sqrt{6 / (\mathtt{n\_in} + \mathtt{n\_out})}\)) and the biases are initialized to zero. If `parameters` is given, then is must be in the form `[weights, biases]`, where the shape of weights is `(n_in, n_out)` and the shape of `biases` is `(n_out,)`. Both weights and biases must be `GPUArray`. weights_scale : float, optional If `parameters` is omitted, then this factor is used as scale for initializing the weights instead of *Bengio’s rule*. l1_penalty_weight : float, optional Weight used for L1 regularization of the weights. l2_penalty_weight : float, optional Weight used for L2 regularization of the weights. lr_multiplier : float, optional If this parameter is omitted, then the learning rate for the layer is scaled by \(2 / \sqrt{\mathtt{n\_in}}\). You may specify a different factor here. test_error_fct : {`class_error`, `kl_error`, `cross_entropy_error`}, optional Which error function to use on the test set. Default is `class_error` for classification error. Other choices are `kl_error`, the Kullback-Leibler divergence, or `cross_entropy_error`. **See also:** [`hebel.layers.LogisticLayer`](#hebel.layers.LogisticLayer), [`hebel.models.NeuralNet`](index.html#hebel.models.NeuralNet), [`hebel.models.NeuralNetRegression`](index.html#hebel.models.NeuralNetRegression), [`hebel.layers.LinearRegressionLayer`](#hebel.layers.LinearRegressionLayer) **Examples**: ``` # Use the simple initializer and initialize with random weights softmax_layer = SoftmaxLayer(1000, 10) # Sample weights yourself, specify an L1 penalty, and don't # use learning rate scaling import numpy as np from pycuda import gpuarray n_in = 1000 n_out = 10 weights = gpuarray.to_gpu(.01 * np.random.randn(n_in, n_out)) biases = gpuarray.to_gpu(np.zeros((n_out,))) softmax_layer = SoftmaxLayer(n_in, n_out, parameters=(weights, biases), l1_penalty_weight=.1, lr_multiplier=1.) ``` `backprop`(*input_data*, *targets*, *cache=None*)[¶](#hebel.layers.SoftmaxLayer.backprop) Backpropagate through the logistic layer. **Parameters:** input_data : `GPUArray` Inpute data to compute activations for. targets : `GPUArray` The target values of the units. cache : list of `GPUArray` Cache obtained from forward pass. If the cache is provided, then the activations are not recalculated. **Returns:** gradients : tuple of `GPUArray` Gradients with respect to the weights and biases in the form `(df_weights, df_biases)`. df_input : `GPUArray` Gradients with respect to the input. `class_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=False*)[¶](#hebel.layers.SoftmaxLayer.class_error) Return the classification error rate `cross_entropy_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=False*)[¶](#hebel.layers.SoftmaxLayer.cross_entropy_error) Return the cross entropy error `feed_forward`(*input_data*, *prediction=False*)[¶](#hebel.layers.SoftmaxLayer.feed_forward) Propagate forward through the layer. **Parameters:** input_data : `GPUArray` Inpute data to compute activations for. prediction : bool, optional Whether to use prediction model. Only relevant when using dropout. If true, then weights are halved if the layers uses dropout. **Returns:** activations : `GPUArray` The activations of the output units. `kl_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=True*)[¶](#hebel.layers.SoftmaxLayer.kl_error) The KL divergence error `test_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=True*)[¶](#hebel.layers.SoftmaxLayer.test_error) Compute the test error function given some data and targets. Uses the error function defined in `SoftmaxLayer.test_error_fct`, which may be different from the cross-entropy error function used for training’. Alternatively, the other test error functions may be called directly. **Parameters:** input_data : `GPUArray` Inpute data to compute the test error function for. targets : `GPUArray` The target values of the units. average : bool Whether to divide the value of the error function by the number of data points given. cache : list of `GPUArray` Cache obtained from forward pass. If the cache is provided, then the activations are not recalculated. prediction : bool, optional Whether to use prediction model. Only relevant when using dropout. If true, then weights are halved if the layers uses dropout. **Returns:** test_error : float `train_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=False*)[¶](#hebel.layers.SoftmaxLayer.train_error) Return the cross entropy error #### Linear Regression Layer[¶](#linear-regression-layer) *class* `hebel.layers.``LinearRegressionLayer`(*n_in*, *n_out*, *parameters=None*, *weights_scale=None*, *l1_penalty_weight=0.0*, *l2_penalty_weight=0.0*, *lr_multiplier=None*)[¶](#hebel.layers.LinearRegressionLayer) Linear regression layer with linear outputs and squared loss error function. > **Parameters:** n_in : integer Number of input units. n_out : integer Number of output units (classes). parameters : array_like of `GPUArray` Parameters used to initialize the layer. If this is omitted, then the weights are initalized randomly using *Bengio’s rule* (uniform distribution with scale \(4 \cdot \sqrt{6 / (\mathtt{n\_in} + \mathtt{n\_out})}\)) and the biases are initialized to zero. If `parameters` is given, then is must be in the form `[weights, biases]`, where the shape of weights is `(n_in, n_out)` and the shape of `biases` is `(n_out,)`. Both weights and biases must be `GPUArray`. weights_scale : float, optional If `parameters` is omitted, then this factor is used as scale for initializing the weights instead of *Bengio’s rule*. l1_penalty_weight : float, optional Weight used for L1 regularization of the weights. l2_penalty_weight : float, optional Weight used for L2 regularization of the weights. lr_multiplier : float, optional If this parameter is omitted, then the learning rate for the layer is scaled by \(2 / \sqrt{\mathtt{n\_in}}\). You may specify a different factor here. test_error_fct : {`class_error`, `kl_error`, `cross_entropy_error`}, optional Which error function to use on the test set. Default is `class_error` for classification error. Other choices are `kl_error`, the Kullback-Leibler divergence, or `cross_entropy_error`. **See also:** [`hebel.models.NeuralNetRegression`](index.html#hebel.models.NeuralNetRegression), [`hebel.models.NeuralNet`](index.html#hebel.models.NeuralNet), [`hebel.layers.LogisticLayer`](#hebel.layers.LogisticLayer) `feed_forward`(*input_data*, *prediction=False*)[¶](#hebel.layers.LinearRegressionLayer.feed_forward) Propagate forward through the layer. **Parameters:** input_data : `GPUArray` Inpute data to compute activations for. prediction : bool, optional Whether to use prediction model. Only relevant when using dropout. If true, then weights are halved if the layers uses dropout. **Returns:** activations : `GPUArray` The activations of the output units. `test_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=True*)[¶](#hebel.layers.LinearRegressionLayer.test_error) Compute the test error function given some data and targets. Uses the error function defined in `SoftmaxLayer.test_error_fct`, which may be different from the cross-entropy error function used for training’. Alternatively, the other test error functions may be called directly. **Parameters:** input_data : `GPUArray` Inpute data to compute the test error function for. targets : `GPUArray` The target values of the units. average : bool Whether to divide the value of the error function by the number of data points given. cache : list of `GPUArray` Cache obtained from forward pass. If the cache is provided, then the activations are not recalculated. prediction : bool, optional Whether to use prediction model. Only relevant when using dropout. If true, then weights are halved if the layers uses dropout. **Returns:** test_error : float #### Multitask Top Layer[¶](#multitask-top-layer) *class* `hebel.layers.``MultitaskTopLayer`(*n_in=None*, *n_out=None*, *test_error_fct='class_error'*, *l1_penalty_weight=0.0*, *l2_penalty_weight=0.0*, *tasks=None*, *task_weights=None*, *n_tasks=None*, *lr_multiplier=None*)[¶](#hebel.layers.MultitaskTopLayer) Top layer for performing multi-task training. This is a top layer that enables multi-task training, which can be thought of as training multiple models on the same data and sharing weights in all but the final layer. A `MultitaskTopLayer` has multiple layers as children that are subclasses of [`hebel.layers.TopLayer`](#hebel.layers.TopLayer). During the forward pass, the input from the previous layer is passed on to all tasks and during backpropagation, the gradients are added together from the different tasks (with different weights if necessary). There are two ways of initializing `MultitaskTopLayer`: 1. By supplying `n_in`, `n_out`, and optionally `n_tasks`, which will initialize all tasks with [`hebel.layers.LogisticLayer`](#hebel.layers.LogisticLayer). If `n_tasks` is given, `n_out` must be an integer and `n_tasks` identical tasks will be created. If `n_out` is an `array_like`, then as many tasks will be created as there are elements in `n_out` and `n_tasks` will be ignored. 2. If `tasks` is supplied, then it must be an `array_like` of objects derived from [`hebel.layers.TopLayer`](#hebel.layers.TopLayer), one object for each class. In this case `n_in`, `n_out`, and `n_tasks` will be ignored. The user must make sure that all tasks have their `n_in` member variable set to the same value. **Parameters:** n_in : integer, optional Number of input units. Is ignored, when `tasks` is supplied. n_out : integer or array_like, optional Number of output units. May be an integer (all tasks get the same number of units; `n_tasks` must be given), or `array_like` (create as many tasks as elements in `n_out` with different sizes; `n_tasks is ignored). Is always ignored when ``tasks` is supplied. test_error_fct : string, optional See [`hebel.layers.LogisticLayer`](#hebel.layers.LogisticLayer) for options. Ignored when `tasks` is supplied. l1_penalty_weight : float or list/tuple of floats, optional Weight(s) for L1 regularization. Ignored when `tasks` is supplied. l2_penalty_weight : float or list/tuple of floats, optional Weight(s)for L2 regularization. Ignored when `tasks` is supplied. tasks : list/tuple of [`hebel.layers.TopLayer`](#hebel.layers.TopLayer) objects, optional Tasks for multitask learning. Overrides `n_in`, `n_out`, `test_error_fct`, `l1_penalty_weight`, `l2_penalty_weight`, `n_tasks`, and `lr_multiplier`. task_weights : list/tuple of floats, optional Weights to use when adding the gradients from the different tasks. Default is `1./self.n_tasks`. The weights don’t need to necessarily add up to one. n_tasks : integer, optional Number of tasks. Ignored if `n_out` is a list, or `tasks` is supplied. lr_multiplier : float or list/tuple of floats A task dependant multiplier for the learning rate. If this is ignored, then the tasks default is used. It is ignored when `tasks` is supplied. **See also:** [`hebel.layers.TopLayer`](#hebel.layers.TopLayer), [`hebel.layers.LogisticLayer`](#hebel.layers.LogisticLayer) **Examples**: ``` # Simple form of the constructor # Creating five tasks with same number of classes multitask_layer = MultitaskTopLayer(n_in=1000, n_out=10, n_tasks=5) # Extended form of the constructor # Initializing every task independently n_in = 1000 # n_in must be the same for all tasks tasks = ( SoftmaxLayer(n_in, 10, l1_penalty_weight=.1), SoftmaxLayer(n_in, 15, l2_penalty_weight=.2), SoftmaxLayer(n_in, 10), SoftmaxLayer(n_in, 10), SoftmaxLayer(n_in, 20) ) task_weights = [1./5, 1./10, 1./10, 2./5, 1./5] multitask_layer = MultitaskTopLayer(tasks=tasks, task_weights=task_weights) ``` `architecture`[¶](#hebel.layers.MultitaskTopLayer.architecture) Returns a dictionary describing the architecture of the layer. `backprop`(*input_data*, *targets*, *cache=None*)[¶](#hebel.layers.MultitaskTopLayer.backprop) Compute gradients for each task and combine the results. **Parameters:** input_data : `GPUArray` Inpute data to compute activations for. targets : `GPUArray` The target values of the units. cache : list of `GPUArray` Cache obtained from forward pass. If the cache is provided, then the activations are not recalculated. **Returns:** gradients : list Gradients with respect to the weights and biases for each task df_input : `GPUArray` Gradients with respect to the input, obtained by adding the gradients with respect to the inputs from each task, weighted by `MultitaskTopLayer.task_weights`. `cross_entropy_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=False*, *sum_errors=True*)[¶](#hebel.layers.MultitaskTopLayer.cross_entropy_error) Computes the cross-entropy error for all tasks. `feed_forward`(*input_data*, *prediction=False*)[¶](#hebel.layers.MultitaskTopLayer.feed_forward) Call `feed_forward` for each task and combine the activations. Passes `input_data` to all tasks and returns the activations as a list. **Parameters:** input_data : `GPUArray` Inpute data to compute activations for. prediction : bool, optional Whether to use prediction model. Only relevant when using dropout. If true, then weights are halved if the task uses dropout. **Returns:** activations : list of `GPUArray` The activations of the output units, one element for each task. `l1_penalty`[¶](#hebel.layers.MultitaskTopLayer.l1_penalty) Compute the L1 penalty for all tasks. `l2_penalty`[¶](#hebel.layers.MultitaskTopLayer.l2_penalty) Compute the L2 penalty for all tasks. `parameters`[¶](#hebel.layers.MultitaskTopLayer.parameters) Return a list where each element contains the parameters for a task. `test_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=False*, *sum_errors=True*)[¶](#hebel.layers.MultitaskTopLayer.test_error) Compute the error function on a test data set. **Parameters:** input_data : `GPUArray` Inpute data to compute the test error function for. targets : `GPUArray` The target values of the units. average : bool Whether to divide the value of the error function by the number of data points given. cache : list of `GPUArray` Cache obtained from forward pass. If the cache is provided, then the activations are not recalculated. prediction : bool, optional Whether to use prediction model. Only relevant when using dropout. If true, then weights are halved if the layers uses dropout. sum_errors : bool, optional Whether to add up the errors from the different tasks. If this option is chosen, the user must make sure that all tasks use the same test error function. **Returns:** test_error : float or list Returns a float when `sum_errors == True` and a list with the individual errors otherwise. `train_error`(*input_data*, *targets*, *average=True*, *cache=None*, *prediction=False*, *sum_errors=True*)[¶](#hebel.layers.MultitaskTopLayer.train_error) Computes the cross-entropy error for all tasks. Monitors[¶](#monitors) --- ### Progress Monitor[¶](#progress-monitor) *class* `hebel.monitors.``ProgressMonitor`(*experiment_name=None*, *save_model_path=None*, *save_interval=None*, *output_to_log=False*, *model=None*)[¶](#hebel.monitors.ProgressMonitor) `avg_weight`()[¶](#hebel.monitors.ProgressMonitor.avg_weight) `finish_training`()[¶](#hebel.monitors.ProgressMonitor.finish_training) `makedir`()[¶](#hebel.monitors.ProgressMonitor.makedir) `print_`(*obj*)[¶](#hebel.monitors.ProgressMonitor.print_) `print_error`(*epoch*, *train_error*, *validation_error=None*, *new_best=None*)[¶](#hebel.monitors.ProgressMonitor.print_error) `report`(*epoch*, *train_error*, *validation_error=None*, *new_best=None*, *epoch_t=None*)[¶](#hebel.monitors.ProgressMonitor.report) `start_training`()[¶](#hebel.monitors.ProgressMonitor.start_training) `test_error`[¶](#hebel.monitors.ProgressMonitor.test_error) `yaml_config`[¶](#hebel.monitors.ProgressMonitor.yaml_config) ### Simple Progress Monitor[¶](#simple-progress-monitor) *class* `hebel.monitors.``SimpleProgressMonitor`(*model=None*)[¶](#hebel.monitors.SimpleProgressMonitor) `avg_weight`()[¶](#hebel.monitors.SimpleProgressMonitor.avg_weight) `finish_training`()[¶](#hebel.monitors.SimpleProgressMonitor.finish_training) `print_error`(*epoch*, *train_error*, *validation_error=None*)[¶](#hebel.monitors.SimpleProgressMonitor.print_error) `report`(*epoch*, *train_error*, *validation_error=None*, *new_best=None*, *epoch_t=None*)[¶](#hebel.monitors.SimpleProgressMonitor.report) `start_training`()[¶](#hebel.monitors.SimpleProgressMonitor.start_training) Models[¶](#models) --- ### Abstract Base Class Model[¶](#abstract-base-class-model) *class* `hebel.models.``Model`[¶](#hebel.models.Model) Abstract base-class for a Hebel model `evaluate`(*input_data*, *targets*, *return_cache=False*, *prediction=True*)[¶](#hebel.models.Model.evaluate) Evaluate the loss function without computing gradients `feed_forward`(*input_data*, *return_cache=False*, *prediction=True*)[¶](#hebel.models.Model.feed_forward) Get predictions from the model `test_error`(*input_data*, *targets*, *average=True*, *cache=None*)[¶](#hebel.models.Model.test_error) Evaulate performance on a test set `training_pass`(*input_data*, *targets*)[¶](#hebel.models.Model.training_pass) Perform a full forward and backward pass through the model ### Neural Network[¶](#neural-network) *class* `hebel.models.``NeuralNet`(*layers*, *top_layer=None*, *activation_function='sigmoid'*, *dropout=False*, *input_dropout=0.0*, *n_in=None*, *n_out=None*, *l1_penalty_weight=0.0*, *l2_penalty_weight=0.0*, ***kwargs*)[¶](#hebel.models.NeuralNet) A neural network for classification using the cross-entropy loss function. **Parameters:** layers : array_like An array of either integers or instances of `hebel.models.HiddenLayer` objects. If integers are given, they represent the number of hidden units in each layer and new `HiddenLayer` objects will be created. If `HiddenLayer` instances are given, the user must make sure that each `HiddenLayer` has `n_in` set to the preceding layer’s `n_units`. If `HiddenLayer` instances are passed, then `activation_function`, `dropout`, `n_in`, `l1_penalty_weight`, and `l2_penalty_weight` are ignored. top_layer : `hebel.models.TopLayer` instance, optional If `top_layer` is given, then it is used for the output layer, otherwise, a `LogisticLayer` instance is created. activation_function : {‘sigmoid’, ‘tanh’, ‘relu’, or ‘linear’}, optional The activation function to be used in the hidden layers. dropout : bool, optional Whether to use dropout regularization input_dropout : float, in `[0, 1]` Dropout probability for the input (default 0.0). n_in : integer, optional The dimensionality of the input. Must be given, if the first hidden layer is not passed as a `hebel.models.HiddenLayer` instance. n_out : integer, optional The number of classes to predict from. Must be given, if a `hebel.models.HiddenLayer` instance is not given in `top_layer`. l1_penalty_weight : float, optional Weight for L1 regularization l2_penalty_weight : float, optional Weight for L2 regularization kwargs : optional Any additional arguments are passed on to `top_layer` **See also:** [`hebel.models.LogisticRegression`](#hebel.models.LogisticRegression), [`hebel.models.NeuralNetRegression`](#hebel.models.NeuralNetRegression), [`hebel.models.MultitaskNeuralNet`](#hebel.models.MultitaskNeuralNet) **Examples**: ``` # Simple form model = NeuralNet(layers=[1000, 1000], activation_function='relu', dropout=True, n_in=784, n_out=10, l1_penalty_weight=.1) # Extended form, initializing with ``HiddenLayer`` and ``TopLayer`` objects hidden_layers = [HiddenLayer(784, 1000, 'relu', dropout=True, l1_penalty_weight=.2), HiddenLayer(1000, 1000, 'relu', dropout=True, l1_penalty_weight=.1)] softmax_layer = LogisticLayer(1000, 10, l1_penalty_weight=.1) model = NeuralNet(hidden_layers, softmax_layer) ``` `TopLayerClass`[¶](#hebel.models.NeuralNet.TopLayerClass) alias of `SoftmaxLayer` `checksum`()[¶](#hebel.models.NeuralNet.checksum) Returns an MD5 digest of the model. This can be used to easily identify whether two models have the same architecture. `evaluate`(*input_data*, *targets*, *return_cache=False*, *prediction=True*)[¶](#hebel.models.NeuralNet.evaluate) Evaluate the loss function without computing gradients. **Parameters:** input_data : GPUArray Data to evaluate targets: GPUArray Targets return_cache : bool, optional Whether to return intermediary variables from the computation and the hidden activations. prediction : bool, optional Whether to use prediction model. Only relevant when using dropout. If true, then weights are halved in layers that use dropout. **Returns:** loss : float The value of the loss function. hidden_cache : list, only returned if `return_cache == True` Cache as returned by [`hebel.models.NeuralNet.feed_forward()`](#hebel.models.NeuralNet.feed_forward). activations : list, only returned if `return_cache == True` Hidden activations as returned by [`hebel.models.NeuralNet.feed_forward()`](#hebel.models.NeuralNet.feed_forward). `feed_forward`(*input_data*, *return_cache=False*, *prediction=True*)[¶](#hebel.models.NeuralNet.feed_forward) Run data forward through the model. **Parameters:** input_data : GPUArray Data to run through the model. return_cache : bool, optional Whether to return the intermediary results. prediction : bool, optional Whether to run in prediction mode. Only relevant when using dropout. If true, weights are halved. If false, then half of hidden units are randomly dropped and the dropout mask is returned in case `return_cache==True`. **Returns:** prediction : GPUArray Predictions from the model. cache : list of GPUArray, only returned if `return_cache == True` Results of intermediary computations. `parameters`[¶](#hebel.models.NeuralNet.parameters) A property that returns all of the model’s parameters. `test_error`(*test_data*, *average=True*)[¶](#hebel.models.NeuralNet.test_error) Evaulate performance on a test set. **Parameters:** test_data : :class:`hebel.data_provider.DataProvider` A `DataProvider` instance to evaluate on the model. average : bool, optional Whether to divide the loss function by the number of examples in the test data set. **Returns:** test_error : float `training_pass`(*input_data*, *targets*)[¶](#hebel.models.NeuralNet.training_pass) Perform a full forward and backward pass through the model. **Parameters:** input_data : GPUArray Data to train the model with. targets : GPUArray Training targets. **Returns:** loss : float Value of loss function as evaluated on the data and targets. gradients : list of GPUArray Gradients obtained from backpropagation in the backward pass. ### Neural Network Regression[¶](#neural-network-regression) *class* `hebel.models.``NeuralNetRegression`(*layers*, *top_layer=None*, *activation_function='sigmoid'*, *dropout=False*, *input_dropout=0.0*, *n_in=None*, *n_out=None*, *l1_penalty_weight=0.0*, *l2_penalty_weight=0.0*, ***kwargs*)[¶](#hebel.models.NeuralNetRegression) A neural network for regression using the squared error loss function. This class exists for convenience. The same results can be achieved by creating a [`hebel.models.NeuralNet`](#hebel.models.NeuralNet) instance and passing a [`hebel.layers.LinearRegressionLayer`](index.html#hebel.layers.LinearRegressionLayer) instance as the `top_layer` argument. **Parameters:** layers : array_like An array of either integers or instances of `hebel.models.HiddenLayer` objects. If integers are given, they represent the number of hidden units in each layer and new `HiddenLayer` objects will be created. If `HiddenLayer` instances are given, the user must make sure that each `HiddenLayer` has `n_in` set to the preceding layer’s `n_units`. If `HiddenLayer` instances are passed, then `activation_function`, `dropout`, `n_in`, `l1_penalty_weight`, and `l2_penalty_weight` are ignored. top_layer : `hebel.models.TopLayer` instance, optional If `top_layer` is given, then it is used for the output layer, otherwise, a `LinearRegressionLayer` instance is created. activation_function : {‘sigmoid’, ‘tanh’, ‘relu’, or ‘linear’}, optional The activation function to be used in the hidden layers. dropout : bool, optional Whether to use dropout regularization n_in : integer, optional The dimensionality of the input. Must be given, if the first hidden layer is not passed as a `hebel.models.HiddenLayer` instance. n_out : integer, optional The number of classes to predict from. Must be given, if a `hebel.models.HiddenLayer` instance is not given in `top_layer`. l1_penalty_weight : float, optional Weight for L1 regularization l2_penalty_weight : float, optional Weight for L2 regularization kwargs : optional Any additional arguments are passed on to `top_layer` **See also:** [`hebel.models.NeuralNet`](#hebel.models.NeuralNet), [`hebel.models.MultitaskNeuralNet`](#hebel.models.MultitaskNeuralNet), [`hebel.layers.LinearRegressionLayer`](index.html#hebel.layers.LinearRegressionLayer) `TopLayerClass`[¶](#hebel.models.NeuralNetRegression.TopLayerClass) alias of `LinearRegressionLayer` ### Logistic Regression[¶](#logistic-regression) *class* `hebel.models.``LogisticRegression`(*n_in*, *n_out*, *test_error_fct='class_error'*)[¶](#hebel.models.LogisticRegression) A logistic regression model ### Multi-Task Neural Net[¶](#multi-task-neural-net) *class* `hebel.models.``MultitaskNeuralNet`(*layers*, *top_layer=None*, *activation_function='sigmoid'*, *dropout=False*, *input_dropout=0.0*, *n_in=None*, *n_out=None*, *l1_penalty_weight=0.0*, *l2_penalty_weight=0.0*, ***kwargs*)[¶](#hebel.models.MultitaskNeuralNet) `TopLayerClass`[¶](#hebel.models.MultitaskNeuralNet.TopLayerClass) alias of `MultitaskTopLayer` Optimizers[¶](#optimizers) --- ### Stochastic Gradient Descent[¶](#stochastic-gradient-descent) *class* `hebel.optimizers.``SGD`(*model*, *parameter_updater*, *train_data*, *validation_data=None*, *progress_monitor=None*, *learning_rate_schedule=<generator object constant_scheduler>*, *momentum_schedule=None*, *early_stopping=True*)[¶](#hebel.optimizers.SGD) `best_validation_loss`[¶](#hebel.optimizers.SGD.best_validation_loss) `norm_v_norm`()[¶](#hebel.optimizers.SGD.norm_v_norm) `run`(*iterations=200*, *validation_interval=5*, *yaml_config=None*, *task_id=None*)[¶](#hebel.optimizers.SGD.run) Parameter Updaters[¶](#parameter-updaters) --- ### Abstract Base Class[¶](#abstract-base-class) *class* `hebel.parameter_updaters.``ParameterUpdater`(*model*)[¶](#hebel.parameter_updaters.ParameterUpdater) `post_gradient_update`(*gradients*, *stream=None*)[¶](#hebel.parameter_updaters.ParameterUpdater.post_gradient_update) `pre_gradient_update`(*stream=None*)[¶](#hebel.parameter_updaters.ParameterUpdater.pre_gradient_update) ### Simple SGD Update[¶](#simple-sgd-update) *class* `hebel.parameter_updaters.``SimpleSGDUpdate`(*model*)[¶](#hebel.parameter_updaters.SimpleSGDUpdate) `post_gradient_update`(*gradients*, *batch_size*, *learning_parameters*, *stream=None*)[¶](#hebel.parameter_updaters.SimpleSGDUpdate.post_gradient_update) ### Momentum Update[¶](#momentum-update) *class* `hebel.parameter_updaters.``MomentumUpdate`(*model*)[¶](#hebel.parameter_updaters.MomentumUpdate) `post_gradient_update`(*gradients*, *batch_size*, *learning_parameters*, *stream=None*)[¶](#hebel.parameter_updaters.MomentumUpdate.post_gradient_update) ### Nesterov Momentum Update[¶](#nesterov-momentum-update) *class* `hebel.parameter_updaters.``NesterovMomentumUpdate`(*model*)[¶](#hebel.parameter_updaters.NesterovMomentumUpdate) `post_gradient_update`(*gradients*, *batch_size*, *learning_parameters*, *stream=None*)[¶](#hebel.parameter_updaters.NesterovMomentumUpdate.post_gradient_update) Second step of Nesterov momentum method: take step in direction of new gradient and update velocity `pre_gradient_update`()[¶](#hebel.parameter_updaters.NesterovMomentumUpdate.pre_gradient_update) First step of Nesterov momentum method: take step in direction of accumulated gradient Schedulers[¶](#schedulers) --- ### Constant Scheduler[¶](#constant-scheduler) `hebel.schedulers.``constant_scheduler`(*value*)[¶](#hebel.schedulers.constant_scheduler) ### Exponential Scheduler[¶](#exponential-scheduler) `hebel.schedulers.``exponential_scheduler`(*init_value*, *decay*)[¶](#hebel.schedulers.exponential_scheduler) Decreases exponentially ### Linear Scheduler Up[¶](#linear-scheduler-up) `hebel.schedulers.``linear_scheduler_up`(*init_value*, *target_value*, *duration*)[¶](#hebel.schedulers.linear_scheduler_up) Increases linearly and then stays flat ### Linear Scheduler Up-Down[¶](#linear-scheduler-up-down) `hebel.schedulers.``linear_scheduler_up_down`(*init_value*, *target_value*, *final_value*, *duration_up*, *t_decrease*, *duration_down*)[¶](#hebel.schedulers.linear_scheduler_up_down) Increases linearly to target_value, stays at target_value until t_decrease and then decreases linearly Indices and tables[¶](#indices-and-tables) === * [Index](genindex.html) * [Module Index](py-modindex.html) * [Search Page](search.html)
DPtree
cran
R
Package ‘DPtree’ October 12, 2022 Title Dirichlet-Based Polya Tree Version 1.0.1 Description Contains functions to perform copula estimation by the non-parametric Bayesian method, Dirichlet-based Polya Tree. See Ning (2018) <doi:10.1080/00949655.2017.1421194>. Depends R (>= 3.3.1) License MIT + file LICENSE Encoding UTF-8 LazyData true Imports MCMCpack, stats, plyr, MASS, Rdpack RdMacros Rdpack RoxygenNote 6.0.1 NeedsCompilation no Author <NAME> [aut, cre] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2018-06-19 09:17:55 UTC R topics documented: dDPTreeRealiz... 2 DPTreeDensit... 2 DPTreePMeanDensit... 3 DPTreePosterio... 4 DPTreePosteriorMult... 5 DPTreePrio... 6 pDPTreeRealiz... 6 RealizeDPTre... 7 SampleDPTreeDensit... 8 dDPTreeRealize The disitribution function for realized distribution from D-P tree. Description dDPTreeRealize returns the value of density function of realized distribution from D-P tree at certain given point on copula space. Usage dDPTreeRealize(d, x) Arguments d A 2m by 2m matrix, m being the approximating level. Normalized measures for all 2m by 2m sub-partititons on copula space given by the realized distribution from D-P tree, as returned by DPTreeDensity. x An array of dimension n by 2. The points on copula space for density function evluation. Should be between 0 and 1. Value An array of length n. The values of PDF of the input D-P tree distribution evaluated at the input points. References <NAME> and <NAME> (2018). “A nonparametric Bayesian approach to copula estimation.” Jour- nal of Statistical Computation and Simulation, 88(6), pp. 1081-1105. doi: 10.1080/00949655.2017.1421194. Examples dDPTreeRealize(DPTreePMeanDensity(DPTreePrior(m=2, z=1)),c(0.5,0.5)) DPTreeDensity Calculating sub-partition probabiltiy measures for a realized distribu- tion from D-P tree. Description DPTreeDensity returns the probablity measures in the finest sub-partitions of a realized distribution from D-P tree prior/posterior. Usage DPTreeDensity(Z) Arguments Z An array of dimension of 2m by 2m by m, m being the approximation level. Realized Z’s for all partitions at each level, as returned by RealizeDPTree. Value A 2m by 2m matrix. Normalized measures for all 2m by 2m sub-partititons on copula space given by the realized distribution from D-P tree. References <NAME> and <NAME> (2018). “A nonparametric Bayesian approach to copula estimation.” Jour- nal of Statistical Computation and Simulation, 88(6), pp. 1081-1105. doi: 10.1080/00949655.2017.1421194. Examples dp.rlz <- RealizeDPTree(DPTreePrior(m=2, z=1)) DPTreeDensity(dp.rlz) DPTreePMeanDensity Calculating sub-partition probabiltiy measures for the posterior mean distribution from D-P tree. Description DPTreePMeanDensity returns the probablity measures in the finest sub-partitions of the posterior mean from D-P tree. Usage DPTreePMeanDensity(prior) Arguments prior A list. D-P tree specification. Should be in same format as returned from DPTreePrior or DPTreePosterior. Value A 2m by 2m matrix. Normalized measures for all 2m by 2m sub-partititons on copula space given by the posterior mean distribution from D-P tree. References <NAME> and <NAME> (2018). “A nonparametric Bayesian approach to copula estimation.” Jour- nal of Statistical Computation and Simulation, 88(6), pp. 1081-1105. doi: 10.1080/00949655.2017.1421194. Examples DPTreePMeanDensity(DPTreePrior(m=2, z=1)) DPTreePosterior D-P tree posterior updating from a single copula observation. Description DPTreePosterior returns the D-P tree posterior given input copula data. Usage DPTreePosterior(x, prior, w = 1) Arguments x An array of length 2. Single copula data observation. Each element should be between 0 and 1. prior A list. Should be in same format as returned from DPTreePrior. w A positive number. Weight of data for posterior updating. Default 1. Value A list. a An array containing the hyperparameters of D-P trees. References <NAME> and <NAME> (2018). “A nonparametric Bayesian approach to copula estimation.” Jour- nal of Statistical Computation and Simulation, 88(6), pp. 1081-1105. doi: 10.1080/00949655.2017.1421194. Examples nsim = 1 rho = 0.9 data1 <- MASS::mvrnorm(n=nsim, mu=rep(0, 2), Sigma=matrix(c(1, rho, rho, 1), 2, 2)) data2 <- stats::pnorm(data1) DPTreePosterior(x=data2, prior=DPTreePrior(m=4, z=1)) DPTreePosteriorMulti D-P tree posterior updating from multiple copula observations. Description DPTreePosteriorMulti returns the D-P tree posterior given input copula data. Usage DPTreePosteriorMulti(x, prior, w = 1) Arguments x An array of dimension n by 2. Multiple copula data observations, with each row being a bivariate copula observation. All elements should be between 0 and 1. prior A list. Should be in same format as returned from DPTreePrior. w A positive number or an array of length n. Weight of data for posterior updating. Default 1. Value A list. a An array containing the hyperparameters of D-P trees. References <NAME> and <NAME> (2018). “A nonparametric Bayesian approach to copula estimation.” Jour- nal of Statistical Computation and Simulation, 88(6), pp. 1081-1105. doi: 10.1080/00949655.2017.1421194. Examples nsim = 10 rho = 0.9 data1 <- MASS::mvrnorm(n=nsim, mu=rep(0, 2), Sigma=matrix(c(1, rho, rho, 1), 2, 2)) data2 <- stats::pnorm(data1) DPTreePosteriorMulti(x=data2, prior=DPTreePrior(m=4, z=1)) DPTreePrior Generating the standard D-P Tree prior Description DPTreePrior returns a standard D-P Tree prior based on specified hyperparameters. Usage DPTreePrior(m = 4, z = 1) Arguments m A positive integer. The finite approximation level for D-P tree. Default m=4. z A positive number. On i-th level, the hyperparameter for D-P tree prior is z × i2 . Default z=1. Value A list. a An array containing the hyperparameters of D-P trees. References <NAME> and <NAME> (2018). “A nonparametric Bayesian approach to copula estimation.” Jour- nal of Statistical Computation and Simulation, 88(6), pp. 1081-1105. doi: 10.1080/00949655.2017.1421194. Examples DPTreePrior(m=6, z=1) pDPTreeRealize The disitribution function for realized distribution from D-P tree. Description pDPTreeRealize returns the value of distribution function of realized distribution from D-P tree at certain given point on copula space. Usage pDPTreeRealize(d, x) Arguments d A 2m by 2m matrix, m being the approximating level. Normalized measures for all 2m by 2m sub-partititons on copula space given by the realized distribution from D-P tree, as returned by DPTreeDensity. x An array of dimension n by 2. The points on copula space for distribution func- tion evluation. Should be between 0 and 1. Value An array of length n. The values of CDF of the input D-P tree distribution evaluated at the input points. References <NAME> and <NAME> (2018). “A nonparametric Bayesian approach to copula estimation.” Jour- nal of Statistical Computation and Simulation, 88(6), pp. 1081-1105. doi: 10.1080/00949655.2017.1421194. Examples pDPTreeRealize(DPTreePMeanDensity(DPTreePrior(m=2, z=1)),c(0.5,0.5)) RealizeDPTree Sampling a realized distribution from the D-P Tree. Description RealizeDPTree returns a realized (copula) distribtuion sampled from the input D-P Tree. Usage RealizeDPTree(prior) Arguments prior A list. Should be in same format as returned from DPTreePrior. Value An array of dimension 2m by 2m by m. m is the approximation level. Realized Z’s for all partitions at each level. Three dimensions reprensent two marginals, and the level respectively. References <NAME> and <NAME> (2018). “A nonparametric Bayesian approach to copula estimation.” Jour- nal of Statistical Computation and Simulation, 88(6), pp. 1081-1105. doi: 10.1080/00949655.2017.1421194. Examples RealizeDPTree(DPTreePrior(m=2, z=1)) SampleDPTreeDensity Sample a copula observation from a realized distribution from D-P tree. Description SampleDPTreeDensity returns a copula sample from a realized distribution from D-P tree. Usage SampleDPTreeDensity(nsam, d) Arguments nsam A positive integer. The sample size. d A 2m by 2m matrix, m being the approximating level. Normalized measures for all 2m by 2m sub-partititons on copula space given by the realized distribution from D-P tree, as returned by DPTreeDensity. Value An array of dimension nsam by 2. The values of PDF of the input D-P tree distribution evaluated at the input points. References <NAME> and <NAME> (2018). “A nonparametric Bayesian approach to copula estimation.” Jour- nal of Statistical Computation and Simulation, 88(6), pp. 1081-1105. doi: 10.1080/00949655.2017.1421194. Examples SampleDPTreeDensity(10, DPTreePMeanDensity(DPTreePrior(m=2, z=1)))
arules
cran
R
Package ‘arules’ March 23, 2023 Version 1.7-6 Date 2023-03-23 Title Mining Association Rules and Frequent Itemsets Description Provides the infrastructure for representing, manipulating and analyzing transaction data and patterns (frequent itemsets and association rules). Also provides C implementations of the association mining algorithms Apriori and Eclat. Hahsler, <NAME> Hornik (2005) <doi:10.18637/jss.v014.i15>. Classification/ACM G.4, H.2.8, I.5.1 URL https://github.com/mhahsler/arules BugReports https://github.com/mhahsler/arules/issues Depends R (>= 4.0.0), Matrix (>= 1.4-0) Imports stats, methods, generics, graphics, utils Suggests pmml, XML, proxy, arulesViz, arulesCBA, testthat License GPL-3 Copyright The source code for Apriori and Eclat was obtained from http://www.borgelt.net/ and is Copyright (C) 1996-2003 <NAME>. All other code is Copyright (C) <NAME>, <NAME>, <NAME> and <NAME>. Encoding UTF-8 RoxygenNote 7.2.3 Collate 'AAADefs.R' 'Adult.R' 'itemMatrix.R' 'associations.R' 'transactions.R' 'tidLists.R' 'itemsets.R' 'rules.R' 'DATAFRAME.R' 'Epub.R' 'Groceries.R' 'Income.R' 'LIST.R' 'Matrix.R' 'Mushroom.R' 'SunBai.R' 'abbreviate.R' 'addComplement.R' 'appearance.R' 'apriori.R' 'c.R' 'check_installed.R' 'confint.R' 'control.R' 'coverage.R' 'crossTable.R' 'discretize.R' 'dissimilarity.R' 'duplicated.R' 'eclat.R' 'extract.R' 'fim4r.R' 'hierarchy.R' 'image.R' 'inspect.R' 'interestMeasures.R' 'is.closed.R' 'is.generator.R' 'is.maximal.R' 'is.redundant.R' 'is.significant.R' 'is.superset.R' 'itemCoding.R' 'itemFrequency.R' 'match.R' 'merge.R' 'parameter.R' 'plot.R' 'pmml.R' 'predict.R' 'random.transactions.R' 'read_write.R' 'ruleInduction.R' 'sample.R' 'sets.R' 'setsItemwise.R' 'size.R' 'sort.R' 'subset.R' 'support.R' 'supportingTransactions.R' 'unique.R' 'warm.R' NeedsCompilation yes Author <NAME> [aut, cre, cph] (<https://orcid.org/0000-0003-2716-1405>), <NAME> [aut, cph], <NAME> [aut, cph], <NAME> [aut, cph] (<https://orcid.org/0000-0003-4198-9911>), <NAME> [ctb, cph], <NAME> [ctb], <NAME> [ctb] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2023-03-23 21:52:04 UTC R topics documented: abbreviat... 4 addComplemen... 5 Adul... 6 affinit... 8 APappearance-clas... 10 aprior... 12 AScontrol-classe... 14 ASparameter-classe... 16 associations-clas... 18 ... 20 confin... 21 coverag... 24 crossTabl... 25 DATAFRAM... 26 discretiz... 27 dissimilarit... 31 duplicate... 34 ecla... 35 Epu... 36 extrac... 37 fim4... 38 Grocerie... 41 hierarch... 41 hit... 44 imag... 46 Incom... 47 inspec... 48 interestMeasur... 50 is.close... 54 is.generato... 55 is.maxima... 57 is.redundan... 58 is.significan... 60 is.superse... 62 itemCodin... 64 itemFrequenc... 68 itemFrequencyPlo... 69 itemMatrix-clas... 72 itemsets-clas... 76 itemwiseSetOp... 79 LIS... 80 matc... 81 merg... 83 Mushroo... 85 pmm... 85 predic... 86 proximity-classe... 88 random.transaction... 88 rea... 91 ruleInductio... 93 rules-clas... 95 sampl... 99 set... 100 siz... 102 sor... 104 subse... 105 SunBa... 106 suppor... 107 supportingTransaction... 109 tidLists-clas... 110 transactions-clas... 113 uniqu... 118 wecla... 120 writ... 122 abbreviate Abbreviate item labels in transactions, itemMatrix and associations Description Provides the generic function and the methods to abbreviate long item labels in transactions, asso- ciations (rules and itemsets) and transaction ID lists. Note that abbreviate() is not a generic and this arules defines a generic with the base::abbreviate() as the default. Usage abbreviate(names.arg, ...) ## S4 method for signature 'itemMatrix' abbreviate(names.arg, minlength = 4, ..., method = "both.sides") ## S4 method for signature 'transactions' abbreviate(names.arg, minlength = 4, ..., method = "both.sides") ## S4 method for signature 'rules' abbreviate(names.arg, minlength = 4, ..., method = "both.sides") ## S4 method for signature 'itemsets' abbreviate(names.arg, minlength = 4, ..., method = "both.sides") ## S4 method for signature 'tidLists' abbreviate(names.arg, minlength = 4, ..., method = "both.sides") Arguments names.arg an object of class transactions, itemMatrix, itemsets, rules or tidLists. ... further arguments passed on to the default abbreviation function. minlength number of characters allowed in abbreviation method apply to level and value (both.sides) Author(s) <NAME> and <NAME> based on code by <NAME>. See Also base::abbreviate() Other associations functions: associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() Other itemMatrix and transactions functions: crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data(Adult) inspect(head(Adult, 1)) Adult_abbr <- abbreviate(Adult, 15) inspect(head(Adult_abbr, 1)) addComplement Add Complement-items to Transactions Description Provides the generic function addComplement() and a method for transactions to add complement items. That is, it adds an artificial item to each transaction which does not contain the original item. Such items are also called negative items (Antonie et al, 2014). Usage addComplement(x, labels, complementLabels = NULL) ## S4 method for signature 'transactions' addComplement(x, labels, complementLabels = NULL) Arguments x an object of class transactions. labels character strings; item labels for which complements should be created. complementLabels character strings; labels for the artificial complement-items. If omitted then the original label is prepended by "!" to form the complement-item label. Value Returns an object of class transactions with complement items added. Author(s) <NAME> References <NAME>., <NAME>., <NAME>. (2014) Negative Association Rules. In: <NAME>., <NAME>. (eds) Frequent Pattern Mining, Springer International Publishing, pp. 135-145. doi:10.1007/9783319- 078212_6 Examples data("Groceries") ## add a complement-items for "whole milk" and "other vegetables" g2 <- addComplement(Groceries, c("whole milk", "other vegetables")) g2 tail(itemInfo(g2)) inspect(head(g2, 3)) ## use a custom label for the complement-item g3 <- addComplement(g2, "coffee", complementLabels = "NO coffee") inspect(head(g2, 3)) ## add complements for all items (this is excessive for this dataset) g4 <- addComplement(Groceries, itemLabels(Groceries)) g4 ## add complements for all items with a minimum support of 0.1 g5 <- addComplement(Groceries, names(which(itemFrequency(Groceries) >= 0.1))) g5 Adult Adult Data Set Description The AdultUCI data set contains the questionnaire data of the Adult database (originally called the Census Income Database) formatted as a data.frame. The Adult data set contains the data already prepared and coerced to transactions for use with arules. Format Adult is an object of class transactions with 48842 transactions and 115 items. See below for details. The AdultUCI data set contains a data frame with 48842 observations on the following 15 variables. age a numeric vector. workclass a factor with levels Federal-gov, Local-gov, Never-worked, Private, Self-emp-inc, Self-emp-not-inc, State-gov, and Without-pay. education an ordered factor with levels Preschool < 1st-4th < 5th-6th < 7th-8th < 9th < 10th < 11th < 12th < HS-grad < Prof-school < Assoc-acdm < Assoc-voc < Some-college < Bachelors < Masters < Doctorate. education-num a numeric vector. marital-status a factor with levels Divorced, Married-AF-spouse, Married-civ-spouse, Married-spouse-absent, Never-married, Separated, and Widowed. occupation a factor with levels Adm-clerical, Armed-Forces, Craft-repair, Exec-managerial, Farming-fishing, Handlers-cleaners, Machine-op-inspct, Other-service, Priv-house-serv, Prof-specialty, Protective-serv, Sales, Tech-support, and Transport-moving. relationship a factor with levels Husband, Not-in-family, Other-relative, Own-child, Unmarried, and Wife. race a factor with levels Amer-Indian-Eskimo, Asian-Pac-Islander, Black, Other, and White. sex a factor with levels Female and Male. capital-gain a numeric vector. capital-loss a numeric vector. fnlwgt a numeric vector. hours-per-week a numeric vector. native-country a factor with levels Cambodia, Canada, China, Columbia, Cuba, Dominican-Republic, Ecuador, El-Salvador, England, France, Germany, Greece, Guatemala, Haiti, Holand-Netherlands, Honduras, Hong, Hungary, India, Iran, Ireland, Italy, Jamaica, Japan, Laos, Mexico, Nicaragua, Outlying-US(Guam-USVI-etc), Peru, Philippines, Poland, Portugal, Puerto-Rico, Scotland, South, Taiwan, Thailand, Trinadad&Tobago, United-States, Vietnam, and Yugoslavia. income an ordered factor with levels small < large. Details The Adult database was extracted from the census bureau database found at https://www.census. gov/ in 1994 by <NAME> and <NAME> (Data Mining and Visualization, Silicon Graph- ics). It was originally used to predict whether income exceeds USD 50K/yr based on census data. We added the attribute income with levels small and large (>50K). We prepared the data set for association mining as shown in the section Examples. We removed the continuous attribute fnlwgt (final weight). We also eliminated education-num because it is just a numeric representation of the attribute education. The other 4 continuous attributes we mapped to ordinal attributes as follows: • age: cut into levels Young (0-25), Middle-aged (26-45), Senior (46-65) and Old (66+) • hours-per-week: cut into levels Part-time (0-25), Full-time (25-40), Over-time (40-60) and Too-much (60+) • capital-gain and capital-loss: each cut into levels None (0), Low (0 < median of the values greater zero < max) and High (>=max) Author(s) <NAME> Source https://www.ics.uci.edu/~mlearn/MLRepository.html References <NAME> & <NAME> (2007): UCI Repository of Machine Learning Databases. Irvine, CA: University of California, Department of Information and Computer Science. The data set was first cited in <NAME>. (1996): Scaling Up the Accuracy of Naive-Bayes Classi- fiers: a Decision-Tree Hybrid. Proceedings of the Second International Conference on Knowledge Discovery and Data Mining. Examples data("AdultUCI") dim(AdultUCI) AdultUCI[1:2, ] ## remove attributes AdultUCI[["fnlwgt"]] <- NULL AdultUCI[["education-num"]] <- NULL ## map metric attributes AdultUCI[["age"]] <- ordered(cut(AdultUCI[["age"]], c(15, 25, 45, 65, 100)), labels = c("Young", "Middle-aged", "Senior", "Old")) AdultUCI[["hours-per-week"]] <- ordered(cut(AdultUCI[["hours-per-week"]], c(0,25,40,60,168)), labels = c("Part-time", "Full-time", "Over-time", "Workaholic")) AdultUCI[["capital-gain"]] <- ordered(cut(AdultUCI[["capital-gain"]], c(-Inf,0,median(AdultUCI[["capital-gain"]][AdultUCI[["capital-gain"]] > 0]), Inf)), labels = c("None", "Low", "High")) AdultUCI[["capital-loss"]] <- ordered(cut(AdultUCI[["capital-loss"]], c(-Inf,0, median(AdultUCI[["capital-loss"]][AdultUCI[["capital-loss"]] > 0]), Inf)), labels = c("None", "Low", "High")) ## create transactions Adult <- transactions(AdultUCI) Adult affinity Computing Affinity Between Items Description Provides the generic function affinity() and methods to compute and return a similarity matrix with the affinities between items for a set itemsets stored in a matrix or in transactions via its superclass itemMatrix. Usage affinity(x) ## S4 method for signature 'matrix' affinity(x) ## S4 method for signature 'itemMatrix' affinity(x) Arguments x a matrix or an object of class itemMatrix or transactions containing itemsets. Details Affinity between the two items i and j is defined by Aggarwal et al. (2002) as supp({i, j}) A(i, j) = , supp({i}) + supp({j}) − supp({i, j}) where supp(.) is the support measure. Note that affinity is equivalent to the Jaccard similarity between items. Value returns an object of class ar_similarity which represents the affinities between items in x. Author(s) <NAME> References <NAME>, <NAME>, and <NAME> (2002) Finding localized associations in market basket data, IEEE Trans. on Knowledge and Data Engineering, 14(1):51–62. See Also Other proximity classes and functions: dissimilarity(), predict(), proximity-classes Examples data("Adult") ## choose a sample, calculate affinities s <- sample(Adult, 500) s a <- affinity(s) image(a) APappearance-class Class APappearance — Specifying the appearance Argument of Apri- ori to Implement Rule Templates Description Specifies the restrictions on the associations mined by apriori(). These restrictions can implement certain aspects of rule templates described by Klemettinen (1994). Details Note that appearance is only supported by the implementation of apriori(). Slots labels character vectors giving the labels of the items which can appear in the specified place (rhs, lhs or both for rules and items for itemsets). none specifies, that the items mentioned there cannot appear anywhere in the rule/itemset. Note that items cannot be specified in more than one place (i.e., you cannot specify an item in lhs and rhs, but have to specify it as both). default one of "both", "lhs", "rhs", "none". Specified the default appearance for all items not explicitly mentioned in the other elements of the list. Leave unspecified and the code will guess the correct setting. set used internally. items used internally. Objects from the Class If appearance restrictions are used, an appearance object will be created automatically within the apriori() function using the information in the named list of the function’s appearance argument. In this case, the item labels used in the list will be automatically matched against the items in the used transactions. Objects can also be created by calls of the form new("APappearance", ...). In this case, item IDs (column numbers of the transactions incidence matrix) have to be used instead of labels. Coercions • as("NULL", "APappearance") • as("list", "APappearance") Author(s) <NAME> and <NAME> References <NAME> (2004) Apriori — Finding Association Rules/Hyperedges with the Apriori Algo- rithm. https://borgelt.net/apriori.html <NAME>, <NAME>, <NAME>, <NAME> and <NAME> (1994). Finding In- teresting Rules from Large Sets of Discovered Association Rules. In Proceedings of the Third International Conference on Information and Knowledge Management, 401–407. See Also Other mining algorithms: AScontrol-classes, ASparameter-classes, apriori(), eclat(), fim4r(), ruleInduction(), weclat() Examples data("Adult") ## find only frequent itemsets which do not contain small or large income is <- apriori(Adult, parameter = list(support= 0.1, target="frequent"), appearance = list(none = c("income=small", "income=large"))) itemFrequency(items(is))["income=small"] itemFrequency(items(is))["income=large"] ## find itemsets that only contain small or large income, or young age is <- apriori(Adult, parameter = list(support= 0.1, target="frequent"), appearance = list(items = c("income=small", "income=large", "age=Young"))) inspect(head(is)) ## find only rules with income-related variables in the right-hand-side. incomeItems <- grep("^income=", itemLabels(Adult), value = TRUE) incomeItems rules <- apriori(Adult, parameter = list(support=0.2, confidence = 0.5), appearance = list(rhs = incomeItems)) inspect(head(rules)) ## Note: For more complicated restrictions you have to mine all rules/itemsets and ## then filter the results afterwards. apriori Mining Associations with the Apriori Algorithm Description Mine frequent itemsets, association rules or association hyperedges using the Apriori algorithm. Usage apriori(data, parameter = NULL, appearance = NULL, control = NULL, ...) Arguments data object of class transactions. Any data structure which can be coerced into trans- actions (e.g., a binary matrix, a data.frame or a tibble) can also be specified and will be internally coerced to transactions. parameter object of class APparameter or named list. The default behavior is to mine rules with minimum support of 0.1, minimum confidence of 0.8, maximum of 10 items (maxlen), and a maximal time for subset checking of 5 seconds (maxtime). appearance object of class APappearance or named list. With this argument item appearance can be restricted (implements rule templates). By default all items can appear unrestricted. control object of class APcontrol or named list. Controls the algorithmic performance of the mining algorithm (item sorting, report progress (verbose), etc.) ... Additional arguments are for convenience added to the parameter list. Details The Apriori algorithm (Agrawal et al, 1993) employs level-wise search for frequent itemsets. The used C implementation of Apriori by Christian Borgelt (2003) includes some improvements (e.g., a prefix tree and item sorting). Warning about automatic conversion of matrices or data.frames to transactions. It is preferred to create transactions manually before calling apriori() to have control over item coding. This is especially important when you are working with multiple datasets or several subsets of the same dataset. To read about item coding, see itemCoding. If a data.frame is specified as x, then the data is automatically converted into transactions by dis- cretizing numeric data using discretizeDF() and then coercion to transactions. The discretization may fail if the data is not well behaved. Apriori only creates rules with one item in the RHS (Consequent). The default value in APpa- rameter for minlen is 1. This meains that rules with only one item (i.e., an empty antecedent/LHS) like {} => {beer} will be created. These rules mean that no matter what other items are involved, the item in the RHS will appear with the probability given by the rule’s confidence (which equals the support). If you want to avoid these rules then use the argument parameter = list(minlen = 2). Notes on run time and memory usage: If the minimum support is chosen too low for the dataset, then the algorithm will try to create an extremely large set of itemsets/rules. This will result in very long run time and eventually the process will run out of memory. To prevent this, the default maximal length of itemsets/rules is restricted to 10 items (via the parameter element maxlen = 10) and the time for checking subsets is limited to 5 seconds (via maxtime = 5). The output will show if you hit these limits in the "checking subsets" line of the output. The time limit is only checked when the subset size increases, so it may run significantly longer than what you specify in maxtime. Setting maxtime = 0 disables the time limit. Interrupting execution with Control-C/Esc is not recommended. Memory cleanup will be pre- vented resulting in a memory leak. Also, interrupts are only checked when the subset size increases, so it may take some time till the execution actually stops. Value Returns an object of class rules or itemsets. Author(s) <NAME> and <NAME> References <NAME>, <NAME>, and <NAME> (1993) Mining association rules between sets of items in large databases. In Proceedings of the ACM SIGMOD International Conference on Management of Data, pages 207–216, Washington D.C. doi:10.1145/170035.170072 <NAME> (2012) Frequent Item Set Mining. Wiley Interdisciplinary Reviews: Data Mining and Knowledge Discovery 2(6):437-456. J. Wiley & Sons, Chichester, United Kingdom 2012. doi:10.1002/widm.1074 <NAME> and <NAME> (2002) Induction of Association Rules: Apriori Implementa- tion. 15th Conference on Computational Statistics (COMPSTAT 2002, Berlin, Germany) Physica Verlag, Heidelberg, Germany. <NAME> (2003) Efficient Implementations of Apriori and Eclat. Workshop of Frequent Item Set Mining Implementations (FIMI 2003, Melbourne, FL, USA). APRIORI Implementation: https://borgelt.net/apriori.html See Also Other mining algorithms: APappearance-class, AScontrol-classes, ASparameter-classes, eclat(), fim4r(), ruleInduction(), weclat() Examples ## Example 1: Create transaction data and mine association rules a_list <- list( c("a","b","c"), c("a","b"), c("a","b","d"), c("c","e"), c("a","b","d","e") ) ## Set transaction names names(a_list) <- paste("Tr",c(1:5), sep = "") a_list ## Use the constructor to create transactions trans1 <- transactions(a_list) trans1 rules <- apriori(trans1) inspect(rules) ## Example 2: Mine association rules from an existing transactions dataset ## using different minimum support and minimum confidence thresholds data("Adult") rules <- apriori(Adult, parameter = list(supp = 0.5, conf = 0.9, target = "rules")) summary(rules) AScontrol-classes Classes AScontrol, APcontrol, ECcontrol — Specifying the control Ar- gument of Apriori and Eclat Description The AScontrol class holds the algorithmic parameters for the used mining algorithms. APcontrol and ECcontrol directly extend AScontrol with additional slots for parameters only suitable for the algorithms Apriori (APcontrol) and Eclat (ECcontrol). Slots sort an integer scalar indicating how to sort items with respect to their frequency: (default: 2) • 1: ascending • -1: descending • 0: do not sort • 2: ascending • -2: descending with respect to transaction size sum verbose a logical indicating whether to report progress filter a numeric scalar indicating how to filter unused items from transactions (default: 0.1) • = 0: do not filter items with respect to. usage in sets • < 0: fraction of removed items for filtering • > 0: take execution times ratio into account tree a logical indicating whether to organize transactions as a prefix tree (default: TRUE) heap a logical indicating whether to use heapsort instead of quicksort to sort the transactions (de- fault: TRUE) memopt a logical indicating whether to minimize memory usage instead of maximize speed (de- fault: FALSE) load a logical indicating whether to load transactions into memory (default: TRUE) sparse a numeric value for the threshold for sparse representation (default: 7) Available Slots by Subclass • APcontrol: filter, tree, heap, memopt, load, sort, verbose • ECcontrol: sparse, sort, verbose Objects from the Class A suitable default control object will be automatically created by the apriori() or the eclat() function. By specifying a named list (names equal to slots) as the control argument for apriori() or eclat(), default values can be replaced with the values in the list. Objects can also be created via coercion. Coercions • as("NULL", "APcontrol") • as("list", "APcontrol") • as("NULL", "ECcontrol") • as("list", "ECcontrol") Author(s) <NAME> and <NAME> References Christian Borgelt (2004) Apriori — Finding Association Rules/Hyperedges with the Apriori Algo- rithm. https://borgelt.net/apriori.html See Also Other mining algorithms: APappearance-class, ASparameter-classes, apriori(), eclat(), fim4r(), ruleInduction(), weclat() ASparameter-classes Classes ASparameter, APparameter, ECparameter — Specifying the parameter Argument of APRIORI and ECLAT Description The ASparameter class holds the mining parameters (e.g., minimum support) for the used mining algorithms. APparameter and ECparameter directly extend ASparameter with additional slots for parameters only suitable for apriori() (APparameter) or eclat() (ECparameter). Slots support a numeric value for the minimal support of an item set (default: 0.1) minlen an integer value for the minimal number of items per item set (default: 1 item) maxlen an integer value for the maximal number of items per item set (default: 10 items) target a character string indicating the type of association mined. Partial names are matched. Available targets are: • "frequent itemsets" • "maximally frequent itemsets" • "generator frequent itemsets" • "closed frequent itemsets" • "rules" only available for apriori; use ruleInduction for eclat. • "hyperedgesets" only available for apriori; see references for the definition of associa- tion hyperedgesets. ext a logical indicating whether to report coverage (i.e., LHS-support) as an extended quality mea- sure (default: TRUE) confidence a numeric value for the minimal confidence of rules/association hyperedges (default: 0.8). For frequent itemsets it is set to NA. smax a numeric value for the maximal support of itemsets/rules/hyperedgesets (default: 1) arem a character string indicating the used additional rule evaluation measure (default: "none") given by one of • "none": no additional evaluation measure • "diff": absolute confidence difference • "quot": difference of confidence quotient to 1 • "aimp": absolute difference of improvement to 1 • "info": information difference to prior • "chi2": normalized χ2 measure Note: The measure is only reported if aval is set to TRUE. Use minval to set minimum thresholds on the measures. aval a logical indicating whether to return the additional rule evaluation measure selected with arem. minval a numeric value for the minimal value of additional evaluation measure selected with arem (default: 0.1) originalSupport a logical indicating whether to use the original definition of minimum support (support of the LHS and RHS of the rule). If set to FALSE then the support of the LHS (also called coverage of the rule) is returned as support. The minimum support threshold is applied to this support. (default: TRUE) maxtime Time limit in seconds for checking subsets. maxtime = 0 disables the time limit. (default: 5 seconds) tidLists a logical indicating whether eclat() should return also a list of supporting transactions IDs. (default: FALSE) Available Slots by Subclass • APparameter: confidence, minval, smax, arem, aval, originalSupport, maxtime, support, minlen, maxlen, target, ext • ECparameter: tidLists, support, minlen, maxlen, target, ext Objects from the Class A suitable default parameter object will be automatically created by apriori() or eclat(). By specifying a named list (names equal to slots) as parameter argument for apriori() or eclat(), the default values can be replaced with the values in the list. Objects can also be created via coercion. Coercions • as("NULL", "APparameter") • as("list", "APparameter") • as("NULL", "ECparameter") • as("list", "ECparameter") Author(s) <NAME> and <NAME> References Christian Borgelt (2004) Apriori — Finding Association Rules/Hyperedges with the Apriori Algo- rithm. https://borgelt.net/apriori.html See Also Other mining algorithms: APappearance-class, AScontrol-classes, apriori(), eclat(), fim4r(), ruleInduction(), weclat() associations-class Class associations — A Set of Associations Description The associations class is a virtual class which is extended to represent mining result (e.g., sets of itemsets or rules). The class defines some common methods for its subclasses. Usage ## S4 method for signature 'associations' quality(x) ## S4 replacement method for signature 'associations' quality(x) <- value ## S4 method for signature 'associations' info(x) ## S4 replacement method for signature 'associations' info(x) <- value ## S4 method for signature 'associations' head(x, n = 6L, by = NULL, decreasing = TRUE, ...) ## S4 method for signature 'associations' tail(x, n = 6L, by = NULL, decreasing = TRUE, ...) ## S4 method for signature 'associations' items(x) ## S4 method for signature 'associations' length(x) ## S4 method for signature 'associations' labels(object) Arguments x, object the object. value the replacement value. n number of elements by sort by this interest measure decreasing sort in decreasing order? ... further arguments. Details The implementations of associations store itemsets (e.g., the LHS and RHS of a rule) as objects of class itemMatrix (i.e., sparse binary matrices). Quality measures (e.g., support) are stored in a data.frame accessible via method quality(). See Sections Functions and See Also to see all available methods. Note: Associations can store multisets with duplicated elements. Duplicated elements can result from combining several sets of associations. Use unique() to remove duplicate associations. Functions • quality(associations): returns the quality data.frame. • quality(associations) <- value: replaces the quality data.frame. The lengths of the vec- tors in the data.frame have to equal the number of associations in the set. • info(associations): returns the info list. • info(associations) <- value: replaces the info list. • head(associations): returns the first n associations. • tail(associations): returns the last n associations. • items(associations): dummy method. This method has to be implemented by all sub- classes of associations and return the items which make up each association as an object of class itemMatrix. • length(associations): dummy method. This method has to be implemented by all sub- classes of associations and return the number of elements in the association. • labels(associations): dummy method. This method has to be implemented by all sub- classes of associations and return a vector of length(object) of labels for the elements in the association. Slots quality a data.frame info a list Objects from the Class A virtual class: No objects may be created from it. Author(s) <NAME> See Also Subclasses: rules, itemsets Other associations functions: abbreviate(), c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() c Combining Association and Transaction Objects Description Provides the methods to combine several associations or transactions objects into a single object. Usage ## S4 method for signature 'itemMatrix' c(x, ..., recursive = FALSE) ## S4 method for signature 'transactions' c(x, ..., recursive = FALSE) ## S4 method for signature 'tidLists' c(x, ..., recursive = FALSE) ## S4 method for signature 'rules' c(x, ..., recursive = FALSE) ## S4 method for signature 'itemsets' c(x, ..., recursive = FALSE) Arguments x first object. ... further objects of the same class as x to be combined. recursive a logical. If recursive = TRUE, the function recursively descends through lists combining all their elements into a vector. Details Combining arules objects is done by combining the rows of itemMatrix objects representing the associations or transactions. Note that c() can result in duplicates. Use union() rather than c() to combine several mined itemsets or rules into a single set without duplicates. Value An object of the same class as x. Author(s) <NAME> See Also Other associations functions: abbreviate(), associations-class, duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() Other itemMatrix and transactions functions: abbreviate(), crossTable(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions() tidLists-class, transactions-class, unique() Examples data("Adult") ## combine transactions a1 <- Adult[1:10] a2 <- Adult[101:110] aComb <- c(a1, a2) summary(aComb) ## combine rules (can contain the same rule multiple times) r1 <- apriori(Adult[1:1000]) r2 <- apriori(Adult[1001:2000]) rComb <- c(r1, r2) rComb ## union of rules (a set with only unique rules: same as unique(rComb)) rUnion <- union(r1,r2) rUnion confint Confidence Intervals for Interest Measures for Association Rules Description Defines a method to compute confidence intervals for interest measures for association rules. Usage ## S3 method for class 'rules' confint( object, parm = "oddsRatio", level = 0.95, measure = NULL, side = c("two.sided", "lower", "upper"), method = NULL, replications = 1000, smoothCounts = 0, transactions = NULL, ... ) Arguments object an object of class rules. parm, measure name of the interest measures (see interestMeasure()). measure can be used instead of parm. level the confidence level required. side Should a two-sided confidence interval or a one-sided limit be returned? Lower returns an interval with only a lower limit and upper returns an interval with only an upper limit. method method to construct the confidence interval. The available methods depends on the measure and the most common method is used by default. replications number of replications for method "simulation". Ignored for other methods. smoothCounts pseudo count for addaptive smoothing (Laplace smoothing). Often a pseudo counts of .5 is used for smoothing (see Detail Section). transactions if the rules object does not contain sufficient quality information, then a set of transactions to calculate the confidence interval for can be specified. ... Additional parameters are ignored with a warning. Details This method creates a contingency table for each rule and then constructs a confidence interval for the specified measures. Fast confidence interval approximations are currently available for the measures "support", "count", "confidence", "lift", "oddsRatio", and "phi". For all other measures, bootstrap sampling from a multinomial distribution is used. Haldan-Anscombe correction (Haldan, 1940; Anscombe, 1956) to avoids issues with zero counts can be specified by smoothCounts = 0.5. Here .5 is added to each count in the contingency table. Value Returns a matrix with with one row for each rule and the two columns named "LL" and "UL" with the interval boundaries. The matrix has the following additional attributes: measure the interest measure. level the confidence level side the confidence level smoothCounts used count smoothing. method name of the method to create the interval desc description of the used method to calculate the confidence interval. The men- tioned references can be found below. Author(s) <NAME> References <NAME>. (1927). "Probable inference, the law of succession, and statistical inference". Journal of the American Statistical Association, 22 (158): 209-212. doi:10.1080/01621459.1927.10502953 <NAME>.; <NAME>. (1934). "The use of confidence or fiducial limits illustrated in the case of the binomial". Biometrika, 26 (4): 404-413. doi:10.1093/biomet/26.4.404 <NAME>. (1935). "The Limiting Distributions of Certain Statistics". Annals of Mathematical Statistics, 6: 160-169. doi:10.1214/aoms/1177732594 <NAME>. (1962). "Confidence limits for a cross-product ratio". Australian Journal of Statistics, 4, 41. <NAME>. (1955). "On estimating the relation between blood group and diseases". Annals of Human Genetics, 19, 251-253. <NAME>. (1940). "The mean and variance of the moments of chi-squared when used as a test of homogeneity, when expectations are small". Biometrika, 29, 133-134. <NAME>. (1956). "On estimating binomial response relations". Biometrika, 43, 461-464. See Also Other interest measures: coverage(), interestMeasure(), is.redundant(), is.significant(), support() Examples data("Income") # mine some rules with the consequent "language in home=english" rules <- apriori(Income, parameter = list(support = 0.5), appearance = list(rhs = "language in home=english")) # calculate the confidence interval for the rules' odds ratios. # note that we use Haldane-Anscombe correction (with smoothCounts = .5) # to avoid issues with 0 counts in the contingency table. ci <- confint(rules, "oddsRatio", smoothCounts = .5) ci # We add the odds ratio (with Haldane-Anscombe correction) # and the confidence intervals to the quality slot of the rules. quality(rules) <- cbind( quality(rules), oddsRatio = interestMeasure(rules, "oddsRatio", smoothCounts = .5), oddsRatio = ci) rules <- sort(rules, by = "oddsRatio") inspect(rules) # use confidence intervals for lift to find rules with a lift significantly larger then 1. # We set the confidence level to 95%, create a one-sided interval and check # if the interval does not cover 1 (i.e., the lower limit is larger than 1). ci <- confint(rules, "lift", level = 0.95, side = "lower") ci inspect(rules[ci[, "LL"] > 1]) coverage Calculate coverage for rules Description Provides the generic function and a method to calculate the coverage (support of the left-hand-side) of rules. Usage coverage(x, transactions = NULL, reuse = TRUE) ## S4 method for signature 'rules' coverage(x, transactions = NULL, reuse = TRUE) Arguments x the set of rules. transactions the data set used to generate x. Only needed if the quality slot of x does not contain support and confidence. reuse reuse support and confidence stored in x or recompute from transactions? Details Coverage (also called cover or LHS-support) is the support of the left-hand-side of the rule X => Y , i.e., supp(X). It represents a measure of to how often the rule can be applied. Coverage can be quickly calculated from the rule’s quality measures (support and confidence) stored in the quality slot. If these values are not present, then the support of the LHS is counted using the data supplied in transactions. Coverage is also one of the measures available via the function interestMeasure(). Value A numeric vector of the same length as x containing the coverage values for the sets in x. Author(s) <NAME> See Also Other interest measures: confint(), interestMeasure(), is.redundant(), is.significant(), support() Examples data("Income") ## find and some rules (we only use 5 rules here) and calculate coverage rules <- apriori(Income)[1:5] quality(rules) <- cbind(quality(rules), coverage = coverage(rules)) inspect(rules) crossTable Cross-tabulate joint occurrences across pairs of items Description Provides the generic function crossTable() and a method to cross-tabulate joint occurrences across all pairs of items. Usage crossTable(x, ...) ## S4 method for signature 'itemMatrix' crossTable( x, measure = c("count", "support", "probability", "lift"), sort = FALSE ) Arguments x object to be cross-tabulated (transactions or itemMatrix). ... additional arguments. measure measure to return. Default is co-occurrence counts. sort sort the items by support. Value A symmetric matrix of n x n, where n is the number of items times in x. The matrix contains the co-occurrence counts between pairs of items. Author(s) <NAME> See Also Other itemMatrix and transactions functions: abbreviate(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data("Groceries") ct <- crossTable(Groceries, sort = TRUE) ct[1:5, 1:5] sp <- crossTable(Groceries, measure = "support", sort = TRUE) sp[1:5, 1:5] lift <- crossTable(Groceries, measure = "lift", sort = TRUE) lift[1:5, 1:5] DATAFRAME Data.frame Representation for arules Objects Description Provides the generic function DATAFRAME() and the methods to create a data.frame representation from some arules objects. These methods are used for the coercion to a data.frame, but offer more control over the coercion process (item separators, etc.). Usage DATAFRAME(from, ...) ## S4 method for signature 'rules' DATAFRAME(from, separate = TRUE, ...) ## S4 method for signature 'itemsets' DATAFRAME(from, ...) ## S4 method for signature 'itemMatrix' DATAFRAME(from, ...) Arguments from the object to be converted into a data.frame. ... further arguments are passed on to the labels() method defined for the object in from. separate logical; separate LHS and RHS in separate columns? (only for rules) Details Using DATAFRAME() is equivalent to the standard coercion as(x, "data.frame"). However, for rules, the argument separate = TRUE will produce separate columns for the LHS and the RHS of the rule. Furthermore, the arguments itemSep, setStart, setEnd (and ruleSep for separate = FALSE) will be passed on to the labels() method for the object specified in from. Value a data.frame. Author(s) <NAME> See Also Other import/export: LIST(), pmml, read, write() Examples data(Adult) DATAFRAME(head(Adult)) DATAFRAME(head(Adult), setStart = '', itemSep = ' + ', setEnd = '') rules <- apriori(Adult, parameter = list(supp = 0.5, conf = 0.9, target = "rules")) rules <- head(rules, by = "conf") ### default coercions (same as as(rules, "data.frame")) DATAFRAME(rules) DATAFRAME(rules, separate = TRUE) DATAFRAME(rules, separate = TRUE, setStart = '', itemSep = ' + ', setEnd = '') discretize Convert a Continuous Variable into a Categorical Variable Description This function implements several basic unsupervised methods to convert a continuous variable into a categorical variable (factor) using different binning strategies. For convenience, a whole data.frame can be discretized (i.e., all numeric columns are discretized). Usage discretize( x, method = "frequency", breaks = 3, labels = NULL, include.lowest = TRUE, right = FALSE, dig.lab = 3, ordered_result = FALSE, infinity = FALSE, onlycuts = FALSE, categories = NULL, ... ) discretizeDF(df, methods = NULL, default = NULL) Arguments x a numeric vector (continuous variable). method discretization method. Available are: "interval" (equal interval width), "frequency" (equal frequency), "cluster" (k-means clustering) and "fixed" (categories specifies interval boundaries). Note that equal frequency does not achieve per- fect equally sized groups if the data contains duplicated values. breaks, categories either number of categories or a vector with boundaries for discretization (all values outside the boundaries will be set to NA). categories is deprecated, use breaks instead. labels character vector; labels for the levels of the resulting category. By default, la- bels are constructed using "(a,b]" interval notation. If labels = FALSE, simple integer codes are returned instead of a factor.. include.lowest logical; should the first interval be closed to the left? right logical; should the intervals be closed on the right (and open on the left) or vice versa? dig.lab integer; number of digits used to create labels. ordered_result logical; return a ordered factor? infinity logical; should the first/last break boundary changed to +/-Inf? onlycuts logical; return only computed interval boundaries? ... for method "cluster" further arguments are passed on to kmeans. df data.frame; each numeric column in the data.frame is discretized. methods named list of lists or a data.frame; the named list contains lists of discretization parameters (see parameters of discretize()) for each numeric column (see de- tails). If no discretization is specified for a column, then the default settings for discretize() are used. Note: the names have to match exactly. If a data.frame is specified, then the discretization breaks in this data.frame are applied to df. default named list; parameters for discretize() used for all columns not specified in methods. Details Discretize calculates breaks between intervals using various methods and then uses base::cut() to convert the numeric values into intervals represented as a factor. Discretization may fail for several reasons. Some reasons are • A variable contains only a single value. In this case, the variable should be dropped or directly converted into a factor with a single level (see factor). • Some calculated breaks are not unique. This can happen for method frequency with very skewed data (e.g., a large portion of the values is 0). In this case, non-unique breaks are dropped with a warning. It would be probably better to look at the histogram of the data and decide on breaks for the method fixed. discretize only implements unsupervised discretization. See arulesCBA::discretizeDF.supervised() in package arulesCBA for supervised discretization. discretizeDF() applies discretization to each numeric column. Individual discretization parame- ters can be specified in the form: methods = list(column_name1 = list(method = ,...), column_name2 = list(...)). If no discretization method is specified for a column, then the discretization in de- fault is applied (NULL invokes the default method in discretize()). The special method "none" can be specified to suppress discretization for a column. Value discretize() returns a factor representing the categorized continuous variable with attribute "discretized:breaks" indicating the used breaks or and "discretized:method" giving the used method. If onlycuts = TRUE is used, a vector with the calculated interval boundaries is returned. discretizeDF() returns a discretized data.frame. Author(s) <NAME> See Also base::cut(), arulesCBA::discretizeDF.supervised(). Other preprocessing: hierarchy, itemCoding, merge(), sample() Examples data(iris) x <- iris[,1] ### look at the distribution before discretizing hist(x, breaks = 20, main = "Data") def.par <- par(no.readonly = TRUE) # save default layout(mat = rbind(1:2,3:4)) ### convert continuous variables into categories (there are 3 types of flowers) ### the default method is equal frequency table(discretize(x, breaks = 3)) hist(x, breaks = 20, main = "Equal Frequency") abline(v = discretize(x, breaks = 3, onlycuts = TRUE), col = "red") # Note: the frequencies are not exactly equal because of ties in the data ### equal interval width table(discretize(x, method = "interval", breaks = 3)) hist(x, breaks = 20, main = "Equal Interval length") abline(v = discretize(x, method = "interval", breaks = 3, onlycuts = TRUE), col = "red") ### k-means clustering table(discretize(x, method = "cluster", breaks = 3)) hist(x, breaks = 20, main = "K-Means") abline(v = discretize(x, method = "cluster", breaks = 3, onlycuts = TRUE), col = "red") ### user-specified (with labels) table(discretize(x, method = "fixed", breaks = c(-Inf, 6, Inf), labels = c("small", "large"))) hist(x, breaks = 20, main = "Fixed") abline(v = discretize(x, method = "fixed", breaks = c(-Inf, 6, Inf), onlycuts = TRUE), col = "red") par(def.par) # reset to default ### prepare the iris data set for association rule mining ### use default discretization irisDisc <- discretizeDF(iris) head(irisDisc) ### discretize all numeric columns differently irisDisc <- discretizeDF(iris, default = list(method = "interval", breaks = 2, labels = c("small", "large"))) head(irisDisc) ### specify discretization for the petal columns and don't discretize the others irisDisc <- discretizeDF(iris, methods = list( Petal.Length = list(method = "frequency", breaks = 3, labels = c("short", "medium", "long")), Petal.Width = list(method = "frequency", breaks = 2, labels = c("narrow", "wide")) ), default = list(method = "none") ) head(irisDisc) ### discretize new data using the same discretization scheme as the ### data.frame supplied in methods. Note: NAs may occure if a new ### value falls outside the range of values observed in the ### originally discretized table (use argument infinity = TRUE in ### discretize to prevent this case.) discretizeDF(iris[sample(1:nrow(iris), 5),], methods = irisDisc) dissimilarity Dissimilarity Matrix Computation for Associations and Transactions Description Provides the generic function dissimilarity() and the methods to compute and returns distances for binary data in a matrix, transactions or associations which can be used for grouping and clus- tering. See Hahsler (2016) for an introduction to distance-based clustering of association rules. Usage dissimilarity(x, y = NULL, method = NULL, args = NULL, ...) ## S4 method for signature 'matrix' dissimilarity(x, y = NULL, method = NULL, args = NULL) ## S4 method for signature 'itemMatrix' dissimilarity(x, y = NULL, method = NULL, args = NULL, which = "transactions") ## S4 method for signature 'associations' dissimilarity(x, y = NULL, method = NULL, args = NULL, which = "associations") Arguments x the set of elements (e.g., matrix, itemMatrix, transactions, itemsets, rules). y NULL or a second set to calculate cross dissimilarities. method the distance measure to be used. Implemented measures are (defaults to "jaccard"): • "affinity": measure based on the affinity(), a similarity measure be- tween items. It is defined as the average affinity between the items in two transactions (see Aggarwal et al. (2002)). If x is not the full trans- action set args needs to contain either precalculated affinities as element "affinities" or the transaction set as element "transactions". • "cosine": the Cosine distance. • "dice": Dice’s coefficient defined by Dice (1945). Similar to Jaccard but gives double the weight to agreeing items. • "euclidean": the Euclidean distance. • "jaccard": the number of items which occur in both elements divided by the total number of items in the elements (Sneath, 1957). This measure is often also called: binary, asymmetric binary, etc. • "matching": the matching coefficient defined by Sokal and Michener (1958). This coefficient gives the same weight to presents and absence of items. • "pearson" A distance calculated by 1 − r if r > 1 and 1 otherwise, where r is the Pearson’s correlation coefficient. • "phi": same as "pearson". Pearson’s correlation coefficient reduces to the phi coefficient for the 2x2 contingency tables used here. • "toivonen": Method described in Toivonen et al. (1995). For rules this measure is only defined between rules with the same consequent. The dis- tance between two rules is defined as the number of transactions which is covered by only one of the two rules. The transactions used to mine the associations has to be passed on via args as element "transactions". • "gupta": Method described in Gupta et al. (1999). The distance between two rules is defined as 1 minus the proportion of transactions which are covered by both rules in the transactions covered by each rule individually. The transactions used to mine the associations has to be passed on via args as element "transactions". args a list of additional arguments for the methods. ... further arguments. which a character string indicating if the dissimilarity should be calculated between transactions/associations (default) or items (use "items"). Value returns an object of class dist. Author(s) <NAME> References <NAME>., <NAME>, and <NAME>. (2002) Finding localized associations in market basket data. IEEE Trans. on Knowledge and Data Engineering 14(1):51–62. <NAME>. (1945) Measures of the amount of ecologic association between species. Ecology 26, pages 297–302. <NAME>., <NAME>., and <NAME>. (1999) Distance based clustering of association rules. In Intelligent Engineering Systems Through Artificial Neural Networks (Proceedings of ANNIE 1999), pages 759-764. ASME Press. <NAME>. (2016) Grouping association rules using lift. In <NAME>, <NAME>, and <NAME>, editors, 11th INFORMS Workshop on Data Mining and Decision Analytics (DM-DA 2016). <NAME>. (1957) Some thoughts on bacterial classification. Journal of General Microbiology 17, pages 184–200. <NAME>. and <NAME>. (1958) A statistical method for evaluating systematic relationships. University of Kansas Science Bulletin 38, pages 1409–1438. <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>. (1995) Pruning and grouping discovered association rules. In Proceedings of KDD’95. See Also Other proximity classes and functions: affinity(), predict(), proximity-classes Examples ## cluster items in Groceries with support > 5% data("Groceries") s <- Groceries[, itemFrequency(Groceries) > 0.05] d_jaccard <- dissimilarity(s, which = "items") plot(hclust(d_jaccard, method = "ward.D2"), main = "Dendrogram for items") ## cluster transactions for a sample of Adult data("Adult") s <- sample(Adult, 500) ## calculate Jaccard distances and do hclust d_jaccard <- dissimilarity(s) hc <- hclust(d_jaccard, method = "ward.D2") plot(hc, labels = FALSE, main = "Dendrogram for Transactions (Jaccard)") ## get 20 clusters and look at the difference of the item frequencies (bars) ## for the top 20 items) in cluster 1 compared to the data (line) assign <- cutree(hc, 20) itemFrequencyPlot(s[assign == 1], population = s, topN = 20) ## calculate affinity-based distances between transactions and do hclust d_affinity <- dissimilarity(s, method = "affinity") hc <- hclust(d_affinity, method = "ward.D2") plot(hc, labels = FALSE, main = "Dendrogram for Transactions (Affinity)") ## cluster association rules rules <- apriori(Adult, parameter = list(support = 0.3)) rules <- subset(rules, subset = lift > 2) ## use affinity to cluster rules ## Note: we need to supply the transactions (or affinities) from the ## dataset (sample). d_affinity <- dissimilarity(rules, method = "affinity", args = list(transactions = s)) hc <- hclust(d_affinity, method = "ward.D2") plot(hc, main = "Dendrogram for Rules (Affinity)") ## create 4 groups and inspect the rules in the first group. assign <- cutree(hc, k = 3) inspect(rules[assign == 1]) duplicated Find Duplicated Elements Description Provides the generic function duplicated() and the methods to find duplicated elements in item- Matrix, associations and their subclasses. Usage duplicated(x, incomparables = FALSE, ...) ## S4 method for signature 'itemMatrix' duplicated(x, incomparables = FALSE) ## S4 method for signature 'rules' duplicated(x, incomparables = FALSE) ## S4 method for signature 'itemsets' duplicated(x, incomparables = FALSE) Arguments x an object of class itemMatrix or associations. incomparables argument currently unused. ... further arguments (currently unused). Value A logical vector indicating duplicated elements. Author(s) <NAME> See Also Other associations functions: abbreviate(), associations-class, c(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data("Adult") r1 <- apriori(Adult[1:1000], parameter = list(support = 0.5)) r2 <- apriori(Adult[1001:2000], parameter = list(support = 0.5)) ## Note this creates a collection of rules from two sets of rules r_comb <- c(r1, r2) duplicated(r_comb) eclat Mining Associations with Eclat Description Mine frequent itemsets with the Eclat algorithm. This algorithm uses simple intersection operations for equivalence class clustering along with bottom-up lattice traversal. Usage eclat(data, parameter = NULL, control = NULL, ...) Arguments data object of class transactions or any data structure which can be coerced into trans- actions (e.g., binary matrix, data.frame). parameter object of class ECparameter or named list (default values are: support 0.1 and maxlen 5) control object of class ECcontrol or named list for algorithmic controls. ... Additional arguments are added for convenience to the parameter list. Details Calls the C implementation of the Eclat algorithm by <NAME> for mining frequent itemsets. Eclat can also return the transaction IDs for each found itemset using tidLists = TRUE as a param- eter and the result can be retrieved as a tidLists object with method tidLists() for class itemsets. Note that storing transaction ID lists is very memory intensive, creating transaction ID lists only works for minimum support values which create a relatively small number of itemsets. See also supportingTransactions(). ruleInduction() can be used to generate rules from the found itemsets. A weighted version of ECLAT is available as function weclat(). This version can be used to perform weighted association rule mining (WARM). Value Returns an object of class itemsets. Author(s) <NAME> and <NAME> References <NAME>, <NAME>, <NAME>, and <NAME>. (1997) New algo- rithms for fast discovery of association rules. KDD’97: Proceedings of the Third International Conference on Knowledge Discovery and Data Mining, August 1997, Pages 283-286. <NAME> (2003) Efficient Implementations of Apriori and Eclat. Workshop of Frequent Item Set Mining Implementations (FIMI 2003, Melbourne, FL, USA). ECLAT Implementation: https://borgelt.net/eclat.html See Also Other mining algorithms: APappearance-class, AScontrol-classes, ASparameter-classes, apriori(), fim4r(), ruleInduction(), weclat() Examples data("Adult") ## Mine itemsets with minimum support of 0.1 and 5 or less items itemsets <- eclat(Adult, parameter = list(supp = 0.1, maxlen = 5)) itemsets ## Create rules from the frequent itemsets rules <- ruleInduction(itemsets, confidence = .9) rules Epub The Epub Transactions Data Set Description The Epub data set contains the download history of documents from the electronic publication plat- form of the Vienna University of Economics and Business Administration. The data was recorded between Jan 2003 and Dec 2008. Format Object of class transactions with 15729 transactions and 936 items. Item labels are document IDs of the form "doc_11d". Session IDs and time stamps for transactions are also provided as transaction information. Author(s) <NAME> Source Provided by Michael Hahsler from the custom information system ePub-WU at https://epub. wu-wien.ac.at (which has been replaced by eprint). Examples data(Epub) inspect(head(Epub)) extract Methods for "[": Extraction or Subsetting arules Objects Description Methods for "[", i.e., extraction or subsetting for arules objects. Usage ## S4 method for signature 'itemMatrix,ANY,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'transactions,ANY,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'tidLists,ANY,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'rules,ANY,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'itemsets,ANY,ANY,ANY' x[i, j, ..., drop = TRUE] Arguments x an object of class itemMatrix, transactions or associations. i select rows/sets using an integer vector containing row numbers or a logical vector. j select columns/items using an integer vector containing column numbers (i.e., item IDs), a logical vector or a vector of strings containing parts of item labels. ... further arguments are ignored. drop ignored. Author(s) <NAME> See Also Other associations functions: abbreviate(), associations-class, c(), duplicated(), inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions() tidLists-class, transactions-class, unique() Examples data(Adult) Adult ## select first 10 transactions Adult[1:10] ## select first 10 items for first 100 transactions Adult[1:100, 1:10] ## select the first 100 transactions for the items containing ## "income" or "age=Young" in their labels Adult[1:100, c("income=small", "income=large" ,"age=Young")] fim4r Interface to Mining Algorithms from fim4r Description Interfaces the algorithms implemented in fim4r. The algorithms include: Apriori, Eclat, FPgrowth, Carpenter, IsTa, RElim and SaM. Usage fim4r( transactions, method = NULL, support = 0.1, confidence = 0.8, target = "frequent", originalSupport = TRUE, appear = NULL, report = NULL, verbose = TRUE, ... ) Arguments transactions a transactions object method the algorithm to be used. One of: • "apriori", "eclat", "fpgrowth" can mine itemsets and rules. • "relim", "sam" can mine itemsets. • "carpenter", "ista" can only mine closed itemset. support a numeric value for the minimal support in the range [0, 1]. confidence a numeric value for the minimal confidence of rules in the range [0, 1]. target the target type. One of: "frequent", "closed", "maximal", "generators" or "rules". originalSupport logical; Use the support threshold on the support of the whole rule (LHS and RHS). If FALSE, then LHS support (i.e., coverage) is used by the support thresh- old. appear Specify item appearance in rules (only for apriori, eclat, fpgrowth and the target "rules") Specify a list with two vectors (item labels and appearance modifiers) of the same length. Appearance modifiers are: • "-" (may not appear), • "a" (only in rule antecedent/LHS), • "c" (only in rule consequent/RHS) and • "x" (may appear anywhere). report cannot be used via the interface. verbose logical; print used parameters? ... further arguments are passed on to the function fim4r.x() in package fim4r (x is the specified method). Details Installation: The package fim4r is not available via CRAN. If needed, the fim4r() function down- loads and installs the current version of the package automatically. Additional Notes: • Support and confidence are specified here in the range [0, 1]. This is different from the use in fim4r package where supp and conf have the range [0, 100]. arules::fim4r() automati- cally converts confidence internally. • fim4r methods also return the empty itemset while arules methods do not. • Type ? fim4r::fim4r for help on additional available arguments. This is only available after package fim4r is installed. • Algorithm descriptions and references can be found on the web page in the References Sec- tion. Value An object of class itemsets or rules. References <NAME>, fimi4r: Frequent Item Set Mining and Association Rule Induction for R. https: //borgelt.net/fim4r.html See Also Other mining algorithms: APappearance-class, AScontrol-classes, ASparameter-classes, apriori(), eclat(), ruleInduction(), weclat() Examples ## Not run: data(Adult) # list available algorithms fim4r() # mine association rules with FPgrowth r <- fim4r(Adult, method = "fpgrowth", target = "rules", supp = .7, conf = .8) r inspect(head(r, by = "lift")) # mine closed itemsets with Carpenter or IsTa closed <- fim4r(Adult, method = "carpenter", target = "closed", supp = .7) closed fim4r(Adult, method = "ista", target = "closed", supp = .7) # mine frequent itemset of length 2 (zmin and zmax = 2) freq_2 <- fim4r(Adult, method = "relim", target = "frequent", supp = .7, zmin = 2, zmax = 2) inspect(freq_2) # mine maximal frequent itemsets mfis <- fim4r(Adult, method = "sam", target = "maximal", supp = .7) inspect(mfis) # use item appearance. We first mine all rules and then restrict # the appearance of the item capital-gain=None rules_all <- fim4r(Adult, method = "fpgrowth", target = "rules", supp = .9, conf = .9, zmin = 2) inspect(rules_all) rules_no_gain <- fim4r(Adult, method = "fpgrowth", target = "rules", supp = .9, conf = .9, zmin = 2, appear = list(c("capital-gain=None"), c("-")) ) inspect(rules_no_gain) ## End(Not run) Groceries The Groceries Transactions Data Set Description The Groceries data set contains 1 month (30 days) of real-world point-of-sale transaction data from a typical local grocery outlet. The data set contains 9835 transactions and the items are aggregated to 169 categories. Format Object of class transactions. Details If you use this data set in your paper, please cite to the paper in the References Section. Author(s) <NAME> Source The data set is provided for arules by <NAME>, <NAME> and <NAME>. References <NAME>, <NAME>, and <NAME> (2006) Implications of probabilistic data modeling for mining association rules. In <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, editors, From Data and Information Analysis to Knowledge Engineering, Studies in Classification, Data Analysis, and Knowledge Organization, pages 598–605. Springer-Verlag. hierarchy Support for Item Hierarchies Description Functions to use item hierarchies to aggregate items at different group levels, to perform multi-level transaction analysis. Usage addAggregate(x, by, postfix = "*") filterAggregate(x) aggregate(x, ...) ## S4 method for signature 'itemMatrix' aggregate(x, by) ## S4 method for signature 'itemsets' aggregate(x, by) ## S4 method for signature 'rules' aggregate(x, by) Arguments x an transactions, itemsets or rules object. by name of a field (hierarchy level) available in itemInfo of x or a grouping vector of the same length as items in x by which should be aggregated. Items with the same group label in by will be aggregated into a single with that name. Note that the grouping vector will be coerced to factor before use. postfix characters added to mark group-level items. ... further arguments. Details Often an item hierarchy is available for transactions used for association rule mining. For example in a supermarket dataset items like "bread" and "beagle" might belong to the item group (category) "baked goods." Transactions can store item hierarchies as additional columns in the itemInfo data.frame ("labels" cannot be used since it is reserved for the item labels). Aggregation: To perform analysis at a group level of the item hierarchy, aggregate() produces a new object with items aggregated to a given group level. A group-level item is present if one or more of the items in the group are present in the original object. If rules are aggregated, and the aggregation would lead to the same aggregated group item in the lhs and in the rhs, then that group item is removed from the lhs. Rules or itemsets, which are not unique after the aggregation, are also removed. Note also that the quality measures are not applicable to the new rules and thus are removed. If these measures are required, then aggregate the transactions before mining rules. Multi-level analysis: To analyze relationships between individual items and item groups at the same time, addAggregate() can be used to create a new transactions object which contains both, the original items and group-level items (marked with a given postfix). In association rule mining, all items are handled the same, which means that we will produce a large number of rules of the type: item A => group of item A with a confidence of 1. This will also happen if you mine itemsets. filterAggregate() can be used to filter these spurious rules or itemsets. Value aggregate() returns an object of the same class as x encoded with a number of items equal to the number of unique values in by. Note that for associations (itemsets and rules) the number of associations in the returned set will most likely be reduced since several associations might map to the same aggregated association and aggregate returns a unique set. If several associations map to a single aggregated association then the quality measures of one of the original associations is randomly chosen. addAggregate() returns a new transactions object with the original items and the group-items added. filterAggregateRules() returns a new rules object with the spurious rules remove. Author(s) <NAME> See Also Other preprocessing: discretize(), itemCoding, merge(), sample() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data("Groceries") Groceries ## Groceries contains a hierarchy stored in itemInfo head(itemInfo(Groceries)) ## Example 1: Aggregate items using an existing hierarchy stored in itemInfo. ## We aggregate to level2 stored in Groceries. All items with the same level2 label ## will become a single item with that name. ## Note that the number of items is therefore reduced to 55 Groceries_level2 <- aggregate(Groceries, by = "level2") Groceries_level2 head(itemInfo(Groceries_level2)) ## labels are alphabetically sorted! ## compare original and aggregated transactions inspect(head(Groceries, 2)) inspect(head(Groceries_level2, 2)) ## Example 2: Aggregate using a character vector. ## We create here labels manually to organize items by their first letter. mylevels <- toupper(substr(itemLabels(Groceries), 1, 1)) head(mylevels) Groceries_alpha <- aggregate(Groceries, by = mylevels) Groceries_alpha inspect(head(Groceries_alpha, 2)) ## Example 3: Aggregate rules ## Note: You could also directly mine rules from aggregated transactions to ## get support, lift and support rules <- apriori(Groceries, parameter = list(supp = 0.005, conf = 0.5)) rules inspect(rules[1]) rules_level2 <- aggregate(rules, by = "level2") inspect(rules_level2[1]) ## Example 4: Mine multi-level rules. ## (1) Add aggregate items. These items will have labels ending with a * Groceries_multilevel <- addAggregate(Groceries, "level2") summary(Groceries_multilevel) inspect(head(Groceries_multilevel)) rules <- apriori(Groceries_multilevel, parameter = list(support = 0.01, conf = .9)) inspect(head(rules, by = "lift")) ## Note that this contains many spurious rules of type 'item X => aggregate of item X' ## with a confidence of 1 and high lift. We can filter spurious rules resulting from ## the aggregation rules <- filterAggregate(rules) inspect(head(rules, by = "lift")) hits Computing Transaction Weights With HITS Description Compute the hub transaction weights for a collection of transactions using the HITS (hubs and authorities) algorithm. Usage hits( data, iter = 16L, tol = NULL, type = c("normed", "relative", "absolute"), verbose = FALSE ) Arguments data an object of or coercible to class transactions. iter an integer value specifying the maximum number of iterations to use. tol convergence tolerance (default FLT_EPSILON). type a string value specifying the norming of the hub weights. For "normed" scale the weights to unit length (L2 norm), and for "relative" to unit sum. verbose a logical specifying if progress and runtime information should be displayed. Details Model a collection of transactions as a bipartite graph of hubs (transactions) and authorities (items) with unit arcs and free node weights. That is, a transaction weight is the sum of the (normalized) weights of the items and vice versa. The weights are estimated by iterating the model to a steady- state using a builtin convergence tolerance of FLT_EPSILON for (the change in) the norm of the vector of authorities. Value A numeric vector with transaction weights for data. Author(s) <NAME> References <NAME> and <NAME> (2008). Mining Weighted Association Rules without Preassigned Weights. IEEE Transactions on Knowledge and Data Engineering, 4 (30), 489–495. See Also Other weighted association mining functions: SunBai, weclat() Examples data(SunBai) ## calculate transaction weigths w <- hits(SunBai) w ## add transaction weight to the dataset transactionInfo(SunBai)[["weight"]] <- w transactionInfo(SunBai) ## calulate regular item frequencies itemFrequency(SunBai, weighted = FALSE) ## calulate weighted item frequencies itemFrequency(SunBai, weighted = TRUE) image Visual Inspection of Binary Incidence Matrices Description Provides image() methods to generate level plots to visually inspect binary incidence matrices, i.e., objects based on itemMatrix (e.g., transactions, tidLists, items in itemsets or rhs/lhs in rules). These plots can be used to identify problems in a data set (e.g., recording problems with some transactions containing all items). Usage ## S4 method for signature 'itemMatrix' image(x, xlab = "Items (Columns)", ylab = "Elements (Rows)", ...) ## S4 method for signature 'transactions' image(x, xlab = "Items (Columns)", ylab = "Transactions (Rows)", ...) ## S4 method for signature 'tidLists' image(x, xlab = "Transactions (Columns)", ylab = "Items/itemsets (Rows)", ...) Arguments x the object (itemMatrix, transactions or tidLists). xlab, ylab labels for the plot. ... further arguments passed on to image() in package Matrix which in turn are passed on to levelplot() in lattice. Author(s) <NAME> See Also image() in package Matrix Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions() tidLists-class, transactions-class, unique() Examples data("Epub") ## in this data set we can see that not all ## items were available from the beginning. image(Epub[1:1000]) Income The Income Data Set Description Survey example data from the book The Elements of Statistical Learning. Format The data is provided in two formats: 1. Income is an object of class transactions with 6876 transactions (complete cases) and 50 items. See below for details. 2. IncomeESL is a data frame with 8993 observations on the following 14 variables: income an ordered factor with levels [0,10) < [10,15) < [15,20) < [20,25) < [25,30) < [30,40) < [40,50) < [50,75) < 75+ sex a factor with levels male female marital status a factor with levels married cohabitation divorced widowed single age an ordered factor with levels 14-17 < 18-24 < 25-34 < 35-44 < 45-54 < 55-64 < 65+ education an ordered factor with levels grade <9 < grades 9-11 < high school graduate < college (1-3 years) < college graduate < graduate study occupation a factor with levels professional/managerial sales laborer clerical/service homemaker student military retired unemployed years in bay area an ordered factor with levels <1 < 1-3 < 4-6 < 7-10 < >10 dual incomes a factor with levels not married yes no number in household an ordered factor with levels 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9+ number of children an ordered factor with levels 0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9+ householder status a factor with levels own rent live with parents/family type of home a factor with levels house condominium apartment mobile Home other ethnic classification a factor with levels american indian asian black east indian hispanic pacific islander white other language in home a factor with levels english spanish other Details The IncomeESL data set originates from an example in the book The Elements of Statistical Learn- ing (see Section source). The data set is an extract from this survey. It consists of 8993 instances (obtained from the original data set with 9409 instances, by removing those observations with the annual income missing) with 14 demographic attributes. The data set is a good mixture of cate- gorical and continuous variables with a lot of missing data. This is characteristic of data mining applications. The Income data set contains the data already prepared and coerced to transactions. To create transactions for Income, the original data frame in IncomeESL is prepared in a similar way as described in The Elements of Statistical Learning. We removed cases with missing values and cut each ordinal variable (age, education, income, years in bay area, number in household, and number of children) at its median into two values (see Section examples). Author(s) <NAME> Source Impact Resources, Inc., Columbus, OH (1987). Obtained from the web site of the book: <NAME>., <NAME>. & <NAME>. (2001) The Elements of Statistical Learning. Springer-Verlag. Examples data("IncomeESL") IncomeESL[1:3, ] ## remove incomplete cases IncomeESL <- IncomeESL[complete.cases(IncomeESL), ] ## preparing the data set IncomeESL[["income"]] <- factor((as.numeric(IncomeESL[["income"]]) > 6) +1, levels = 1 : 2 , labels = c("$0-$40,000", "$40,000+")) IncomeESL[["age"]] <- factor((as.numeric(IncomeESL[["age"]]) > 3) +1, levels = 1 : 2 , labels = c("14-34", "35+")) IncomeESL[["education"]] <- factor((as.numeric(IncomeESL[["education"]]) > 4) +1, levels = 1 : 2 , labels = c("no college graduate", "college graduate")) IncomeESL[["years in bay area"]] <- factor( (as.numeric(IncomeESL[["years in bay area"]]) > 4) +1, levels = 1 : 2 , labels = c("1-9", "10+")) IncomeESL[["number in household"]] <- factor( (as.numeric(IncomeESL[["number in household"]]) > 3) +1, levels = 1 : 2 , labels = c("1", "2+")) IncomeESL[["number of children"]] <- factor( (as.numeric(IncomeESL[["number of children"]]) > 1) +0, levels = 0 : 1 , labels = c("0", "1+")) ## creating transactions Income <- transactions(IncomeESL) Income inspect Display Associations and Transactions in Readable Form Description Provides the generic function inspect() and methods to display associations and transactions plus additional information formatted for online inspection. Usage inspect(x, ...) ## S4 method for signature 'itemsets' inspect(x, itemSep = ", ", setStart = "{", setEnd = "}", linebreak = NULL, ...) ## S4 method for signature 'rules' inspect( x, itemSep = ", ", setStart = "{", setEnd = "}", ruleSep = "=>", linebreak = NULL, ... ) ## S4 method for signature 'transactions' inspect(x, itemSep = ", ", setStart = "{", setEnd = "}", linebreak = NULL, ...) ## S4 method for signature 'itemMatrix' inspect(x, itemSep = ", ", setStart = "{", setEnd = "}", linebreak = NULL, ...) ## S4 method for signature 'tidLists' inspect(x, ...) Arguments x a set of associations or transactions or an itemMatrix. ... additional arguments. can be used to customize the output: itemSep item separator setStart set start symbol setEnd set end symbol linebreak print only one element per line in case the output lines get very long? ruleSep rule separator Details inspect() prints the results directly. If you need to create a data.frame with a human readable version, then you can use DATAFRAME(). Value Nothing is returned (see the Details Section). Author(s) <NAME> and <NAME> See Also Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data("Adult") rules <- apriori(Adult) ## display some rules inspect(rules[1000:1001]) inspect(rules[1000:1001], ruleSep = "~~>", itemSep = " + ", setStart = "", setEnd = "", linebreak = FALSE) ## to get rules in readable format, use coercion or DATAFRAME with additional parameters. as(rules[1000:1001], "data.frame") DATAFRAME(rules[1000:1001]) DATAFRAME(rules[1000:1001], separate = TRUE, setStart = "", setEnd = "") interestMeasure Calculate Additional Interest Measures Description Provides the generic function interestMeasure() and the methods to calculate various additional interest measures for existing sets of itemsets or rules. Usage interestMeasure(x, measure, transactions = NULL, reuse = TRUE, ...) ## S4 method for signature 'itemsets' interestMeasure(x, measure, transactions = NULL, reuse = TRUE, ...) ## S4 method for signature 'rules' interestMeasure(x, measure, transactions = NULL, reuse = TRUE, ...) Arguments x a set of itemsets or rules. measure name or vector of names of the desired interest measures (see the Details section for available measures). If measure is missing then all available measures are calculated. transactions the transactions used to mine the associations or a set of different transactions to calculate interest measures from (Note: you need to set reuse = FALSE in the later case). reuse logical indicating if information in the quality slot should be reuse for calculat- ing the measures. This speeds up the process significantly since only very little (or no) transaction counting is necessary if support, confidence and lift are al- ready available. Use reuse = FALSE to force counting (might be very slow but is necessary if you use a different set of transactions than was used for mining). ... further arguments for the measure calculation. Many measures are based on con- tingency table counts and zero counts can produce NaN values (division by zero). This issue can be resolved by using the additional parameter smoothCounts which performs additive smoothing by adds a "pseudo count" of smoothCounts to each cell in the contingency table. Use smoothCounts = 1 or larger values for Laplace smoothing. Use smoothCounts = .5 for Haldane-Anscombe cor- rection (Haldan, 1940; Anscombe, 1956) which is often used for chi-squared, phi correlation and related measures. Details A searchable list of definitions, equations and references for all available interest measures can be found at https://mhahsler.github.io/arules/docs/measures. The descriptions are also linked in the list below. The following measures are implemented for itemsets: • "support": Support. • "count": Support Count. • "allConfidence": All-Confidence. • "crossSupportRatio": Cross-Support Ratio. • "lift": Lift. The following measures are implemented for rules: • "support": Support. • "confidence": Confidence. • "lift": Lift. • "count": Support Count. • "addedValue": Added Value. • "boost": Confidence Boost. • "casualConfidence": Casual Confidence. • "casualSupport": Casual Support. • "centeredConfidence": Centered Confidence. • "certainty": Certainty Factor. • "chiSquared": Chi-Squared. Additional parameters are: significance = TRUE returns the p-value of the test for independence instead of the chi-squared statistic. For p-values, substi- tution effects (the occurrence of one item makes the occurrence of another item less likely) can be tested using the parameter complements = FALSE. Note: Correction for multiple com- parisons can be done using stats::p.adjust(). • "collectiveStrength": Collective Strength. • "confirmedConfidence": Descriptive Confirmed Confidence. • "conviction": Conviction. • "cosine": Cosine. • "counterexample": Example and Counter-Example Rate. • "coverage": Coverage. • "doc": Difference of Confidence. • "fishersExactTest": Fisher’s Exact Test. By default complementary effects are mined, substi- tutes can be found by using the parameter complements = FALSE. Note that Fisher’s exact test is equal to hyper-confidence with significance = TRUE. Correction for multiple comparisons can be done using stats::p.adjust(). • "gini": Gini Index. • "hyperConfidence": Hyper-Confidence. Reports the confidence level by default and the sig- nificance level if significance = TRUE is used. By default complementary effects are mined, substitutes (too low co-occurrence counts) can be found by using the parameter complements = FALSE. • "hyperLift": Hyper-Lift. The used quantile can be changed using parameter level (default: level = 0.99). • "imbalance": Imbalance Ratio. • "implicationIndex": Implication Index. • "importance": Importance. • "improvement": Improvement. • "jaccard": Jaccard Coefficient. • "jMeasure": J-Measure. • "kappa": Kappa. • "kulczynski": Kulczynski. • "lambda": Lambda. • "laplace": Laplace Corrected Confidence. Parameter k can be used to specify the number of classes (default is 2). • "leastContradiction": Least Contradiction. • "lerman": Lerman Similarity. • "leverage": Leverage. • "maxconfidence": MaxConfidence. • "mutualInformation": Mutual Information. • "oddsRatio": Odds Ratio. • "phi": Phi Correlation Coefficient. • "ralambondrainy": Ralambondrainy. • "relativeRisk": Relative Risk. • "rhsSupport": Right-Hand-Side Support. • "RLD": Relative Linkage Disequilibrium. • "rulePowerFactor": Rule Power Factor. • "sebag": Sebag-Schoenauer. • "stdLift": Standardized Lift. • "table": Contingency Table. Returns the four counts for the contingency table. The entries are labeled n11, n01, n10, and n00 (the first subscript is for X and the second is for Y; 1 indicated presence and 0 indicates absence). If several measures are specified, then the counts have the prefix table. • "varyingLiaison": Varying Rates Liaison. • "yuleQ": Yule’s Q. • "yuleY": Yule’s Y. Value If only one measure is used, the function returns a numeric vector containing the values of the interest measure for each association in the set of associations x. If more than one measures are specified, the result is a data.frame containing the different measures for each association as columns. NA is returned for rules/itemsets for which a certain measure is not defined. Author(s) <NAME> References Hahsler, Michael (2015). A Probabilistic Comparison of Commonly Used Interest Measures for Association Rules, 2015, URL: https://mhahsler.github.io/arules/docs/measures. <NAME>. (1940). "The mean and variance of the moments of chi-squared when used as a test of homogeneity, when expectations are small". Biometrika, 29, 133-134. <NAME>. (1956). "On estimating binomial response relations". Biometrika, 43, 461-464. See Also itemsets, rules Other interest measures: confint(), coverage(), is.redundant(), is.significant(), support() Examples data("Income") rules <- apriori(Income) ## calculate a single measure and add it to the quality slot quality(rules) <- cbind(quality(rules), hyperConfidence = interestMeasure(rules, measure = "hyperConfidence", transactions = Income)) inspect(head(rules, by = "hyperConfidence")) ## calculate several measures m <- interestMeasure(rules, c("confidence", "oddsRatio", "leverage"), transactions = Income) inspect(head(rules)) head(m) ## calculate all available measures for the first 5 rules and show them as a ## table with the measures as rows t(interestMeasure(head(rules, 5), transactions = Income)) ## calculate measures on a different set of transactions (I use a sample here) ## Note: reuse = TRUE (default) would just return the stored support on the ## data set used for mining newTrans <- sample(Income, 100) m2 <- interestMeasure(rules, "support", transactions = newTrans, reuse = FALSE) head(m2) ## calculate all available measures for the 5 frequent itemsets with highest support its <- apriori(Income, parameter = list(target = "frequent itemsets")) its <- head(its, 5, by = "support") inspect(its) interestMeasure(its, transactions = Income) is.closed Find Closed Itemsets Description Provides the generic function and the method is.closed() for finding closed itemsets. Closed itemsets are used as a concise representation of frequent itemsets. The closure of an itemset is its largest proper superset which has the same support (is contained in exactly the same transactions). An itemset is closed, if it is its own closure (Pasquier et al. 1999). Usage is.closed(x) ## S4 method for signature 'itemsets' is.closed(x) Arguments x a set of itemsets. Details Closed frequent itemsets can also be mined directly using apriori() or eclat() with target "closed frequent itemsets". Value a logical vector with the same length as x indicating for each element in x if it is a closed itemset. Author(s) <NAME> References <NAME>, <NAME>, <NAME>, and <NAME> (1999). Discovering frequent closed itemsets for association rules. In Proceeding of the 7th International Conference on Database Theory, Lecture Notes In Computer Science (LNCS 1540), pages 398–416. Springer, 1999. See Also Other postprocessing: is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset() Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() is.generator Find Generator Itemsets Description Provides the generic function and the method ‘is.generator() for finding generator itemsets. Gen- erators are part of concise representations for frequent itemsets. A generator in a set of itemsets is an itemset that has no subset with the same support (Liu et al, 2008). Note that the empty set is by definition a generator, but it is typically not stored in the itemsets in arules. Usage is.generator(x) ## S4 method for signature 'itemsets' is.generator(x) Arguments x a set of itemsets. Value a logical vector with the same length as x indicating for each element in x if it is a generator itemset. Author(s) <NAME> References <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (2000). Mining Mini- mal Non-redundant Association Rules Using Frequent Closed Itemsets. In International Confer- ence on Computational Logic, Lecture Notes in Computer Science (LNCS 1861). pages 972–986. doi:10.1007/3540449574_65 <NAME>, <NAME>, <NAME> (2008). A new concise representation of frequent item- sets using generators and a positive border. Knowledge and Information Systems 17(1):35-56. doi:10.1007/s1011500701115 See Also Other postprocessing: is.closed(), is.maximal(), is.redundant(), is.significant(), is.superset() Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() Examples # Example from Liu et al (2008) trans_list <- list( t1 = c("a","b","c"), t2 = c("a","b", "c", "d"), t3 = c("a","d"), t4 = c("a","c") ) trans <- transactions(trans_list) its <- apriori(trans, support = 1/4, target = "frequent itemsets") is.generator(its) is.maximal Find Maximal Itemsets Description Provides the generic function is.maximal() and methods for finding maximal itemsets. Maximal frequent itemsets are used as a concise representation of frequent itemsets. An itemset is maximal in a set if no proper superset of the itemset is contained in the set (Zaki et al., 1997). Usage is.maximal(x, ...) ## S4 method for signature 'itemMatrix' is.maximal(x) ## S4 method for signature 'itemsets' is.maximal(x) ## S4 method for signature 'rules' is.maximal(x) Arguments x the set of itemsets, rules or an itemMatrix object. ... further arguments. Details Maximally frequent itemsets can also be mined directly using apriori() or eclat() with target "maximally frequent itemsets". We define here maximal rules, as the rules generated by maximal itemsets. Value a logical vector with the same length as x indicating for each element in x if it is a maximal itemset. Author(s) <NAME> References <NAME>, <NAME>, <NAME>, and <NAME> (1997). New algo- rithms for fast discovery of association rules. Technical Report 651, Computer Science Department, University of Rochester, Rochester, NY 14627. See Also Other postprocessing: is.closed(), is.generator(), is.redundant(), is.significant(), is.superset() Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() is.redundant Find Redundant Rules Description Provides the generic function is.redundant() and the method to find redundant rules. Usage is.redundant(x, ...) ## S4 method for signature 'rules' is.redundant( x, measure = "confidence", confint = FALSE, level = 0.95, smoothCounts = 1, ... ) Arguments x a set of rules. ... additional arguments are passed on to interestMeasure(), or, for confint = TRUE to confint(). measure measure used to check for redundancy. confint should confidence intervals be used to the redundancy check? level confidence level for the confidence interval. Only used when confint = TRUE. smoothCounts adds a "pseudo count" to each count in the used contingency table. This im- plements addaptive smoothing (Laplace smoothing) for counts and avoids zero counts. Details Simple improvement-based redundancy: (confint = FALSE) A rule can be defined as redundant if a more general rules with the same or a higher confidence exists. That is, a more specific rule is redundant if it is only equally or even less predictive than a more general rule. A rule is more general if it has the same RHS but one or more items removed from the LHS. Formally, a rule X ⇒ Y is redundant if ∃X 0 ⊂ X conf (X 0 ⇒ Y ) ≥ conf (X ⇒ Y ). This is equivalent to a negative or zero improvement as defined by Bayardo et al. (2000). The idea of improvement can be extended other measures besides confidence. Any other measure available for function interestMeasure() (e.g., lift or the odds ratio) can be specified in measure. Confidence interval-based redundancy: (confint = TRUE) Li et al (2014) propose to use the confidence interval (CI) of the odds ratio (OR) of rules to define redundancy. A more specific rule is redundant if it does not provide a significantly higher OR than any more general rule. Using confidence intervals as error bounds, a more specific rule is redundant if its OR CI overlaps with the CI of any more general rule (i.e., the lower bound of the more specific rule’s CI is lower than the upper bound of any more general rule’s CI). This type of redundancy detection is more powerful than improvement since it takes differences in counts due to randomness in the dataset into account. The odds ratio and the CI are based on counts which can be zero and which leads to numeri- cal problems. In addition to the method described by Li et al (2014), we use additive smooth- ing (Laplace smoothing) to alleviate this problem. The default setting adds 1 to each count (see confint()). A different pseudocount (smoothing parameter) can be defined using the additional parameter smoothCounts. Smoothing can be disabled using smoothCounts = 0. Confidence interval-based redundancy checks can also be used for other measures with a confidence interval like confidence (see confint()). Value returns a logical vector indicating which rules are redundant. Author(s) <NAME> and <NAME> References <NAME>. , <NAME>, and <NAME> (2000). Constraint-based rule mining in large, dense databases. Data Mining and Knowledge Discovery, 4(2/3):217–240. <NAME>., <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> (2014). Discovering statistically non-redundant subgroups. Knowledge-Based Systems. 67 (September, 2014), 315– 327. doi:10.1016/j.knosys.2014.04.030 See Also Other postprocessing: is.closed(), is.generator(), is.maximal(), is.significant(), is.superset() Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() Other interest measures: confint(), coverage(), interestMeasure(), is.significant(), support() Examples data("Income") ## mine some rules with the consequent "language in home=english" rules <- apriori(Income, parameter = list(support = 0.5), appearance = list(rhs = "language in home=english")) ## for better comparison we add Bayado's improvement and sort by improvement quality(rules)$improvement <- interestMeasure(rules, measure = "improvement") rules <- sort(rules, by = "improvement") inspect(rules) is.redundant(rules) ## find non-redundant rules using improvement of confidence ## Note: a few rules have a very small improvement over the rule {} => {language in home=english} rules_non_redundant <- rules[!is.redundant(rules)] inspect(rules_non_redundant) ## use non-overlapping confidence intervals for the confidence measure instead ## Note: fewer rules have a significantly higher confidence inspect(rules[!is.redundant(rules, measure = "confidence", confint = TRUE, level = 0.95)]) ## find non-redundant rules using improvement of the odds ratio. quality(rules)$oddsRatio <- interestMeasure(rules, measure = "oddsRatio", smoothCounts = .5) inspect(rules[!is.redundant(rules, measure = "oddsRatio")]) ## use the confidence interval for the odds ratio. ## We see that no rule has a significantly better odds ratio than the most general rule. inspect(rules[!is.redundant(rules, measure = "oddsRatio", confint = TRUE, level = 0.95)]) ## use the confidence interval for lift inspect(rules[!is.redundant(rules, measure = "lift", confint = TRUE, level = 0.95)]) is.significant Find Significant Rules Description Provides the generic functions is.significant() and the method to find significant rules. Usage is.significant( x, transactions, method = "fisher", alpha = 0.01, adjust = "bonferroni" ) ## S4 method for signature 'rules' is.significant( x, transactions, method = "fisher", alpha = 0.01, adjust = "bonferroni" ) Arguments x a set of rules. transactions set of transactions used to mine the rules. method test to use. Options are "fisher", "chisq". Note that the contingency table is likely to have cells with low expected values and that thus Fisher’s Exact Test might be more appropriate than the chi-squared test. alpha required significance level. adjust method to adjust for multiple comparisons. Options are "none", "bonferroni", "holm", "fdr", etc. (see stats::p.adjust()) Details The implementation for association rules uses Fisher’s exact test with correction for multiple com- parisons to test the null hypothesis that the LHS and the RHS of the rule are independent. Significant rules have a p-value less then the specified significance level alpha (the null hypothesis of indepen- dence is rejected). See Hahsler and Hornik (2007) for details. Value returns a logical vector indicating which rules are significant. Author(s) <NAME> References Hahsler, Michael and <NAME> (2007). New probabilistic interest measures for association rules. Intelligent Data Analysis, 11(5):437–455. doi:10.3233/IDA200711502 See Also stats::p.adjust() Other interest measures: confint(), coverage(), interestMeasure(), is.redundant(), support() Other postprocessing: is.closed(), is.generator(), is.maximal(), is.redundant(), is.superset() Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() Examples data("Income") rules <- apriori(Income, parameter = list(support = 0.5)) is.significant(rules, Income) inspect(rules[is.significant(rules, Income)]) is.superset Find Super and Subsets Description Provides the generic functions is.subset() and is.superset(), and the methods for finding super or subsets in associations and itemMatrix objects. Usage is.superset(x, y = NULL, proper = FALSE, sparse = TRUE, ...) is.subset(x, y = NULL, proper = FALSE, sparse = TRUE, ...) ## S4 method for signature 'itemMatrix' is.superset(x, y = NULL, proper = FALSE, sparse = TRUE) ## S4 method for signature 'associations' is.superset(x, y = NULL, proper = FALSE, sparse = TRUE) ## S4 method for signature 'itemMatrix' is.subset(x, y = NULL, proper = FALSE, sparse = TRUE) ## S4 method for signature 'associations' is.subset(x, y = NULL, proper = FALSE, sparse = TRUE) Arguments x, y associations or itemMatrix objects. If y = NULL, the super or subset structure within set x is calculated. proper a logical indicating if all or just proper super or subsets. sparse a logical indicating if a sparse ngCMatrix rather than a dense logical matrix should be returned. Sparse computation requires a significantly smaller amount of memory and is much faster for large sets. ... currently unused. Details Determines for each element in x which elements in y are supersets or subsets. Note that the method can be very slow and memory intensive if x and/or y are very dense (contain many items). For rules, the union of lhs and rhs is used a the set of items. Value returns a logical matrix or a sparse ngCMatrix with length(x) rows and length(y) columns. Each logical row vector represents which elements in y are supersets (subsets) of the corresponding element in x. If either x or y have length zero, NULL is returned instead of a matrix. Author(s) <NAME> and <NAME> See Also Other postprocessing: is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant() Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), itemsets-class, match(), rules-class, sample(), sets, size(), sort(), unique() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data("Adult") set <- eclat(Adult, parameter = list(supp = 0.8)) ### find the supersets of each itemset in set is.superset(set, set) is.superset(set, set, sparse = FALSE) itemCoding Item Coding — Conversion between Item Labels and Column IDs Description The order in which items are stored in an itemMatrix is called the item coding. The following generic functions and methods are used to translate between the representation in the itemMatrix format (used in transactions, rules and itemsets), item labels and numeric item IDs (i.e., the column numbers in the itemMatrix representation). Usage decode(x, ...) ## S4 method for signature 'numeric' decode(x, itemLabels) ## S4 method for signature 'list' decode(x, itemLabels) encode(x, ...) ## S4 method for signature 'character' encode(x, itemLabels, itemMatrix = TRUE) ## S4 method for signature 'numeric' encode(x, itemLabels, itemMatrix = TRUE) ## S4 method for signature 'list' encode(x, itemLabels, itemMatrix = TRUE) recode(x, ...) ## S4 method for signature 'itemMatrix' recode(x, itemLabels = NULL, match = NULL) ## S4 method for signature 'itemsets' recode(x, itemLabels = NULL, match = NULL) ## S4 method for signature 'rules' recode(x, itemLabels = NULL, match = NULL) compatible(x, y) ## S4 method for signature 'itemMatrix' compatible(x, y) ## S4 method for signature 'associations' compatible(x, y) Arguments x a vector or a list of vectors of character strings (for encode() or of numeric (for decode()), or an object of class itemMatrix (for recode()). ... further arguments. itemLabels a vector of character strings used for coding where the position of an item label in the vector gives the item’s column ID. Alternatively, a itemMatrix, transac- tions or associations object can be specified and the item labels or these objects are used. itemMatrix return an object of class itemMatrix otherwise an object of the same class as x is returned. match deprecated: used itemLabels instead. y an object of class itemMatrix, transactions or associations to compare item cod- ing to x. Details Item coding compatibility: When working with several datasets or different subsets of the same dataset, combining or compare the found itemsets or rules requires a compatible item coding. That is, the sparse matrices representing the items (the itemMatrix objects) have columns for the same items in exactly the same order. The coercion to transactions with transactions() or as(x, "transactions") will create the item coding by adding items in the order they are encountered in the dataset. This can lead to different item codings (different order, missing items) for even only slightly different datasets or versions of a dataset. Method compatible() can be used to check if two sets have the same item coding. Defining a common item coding: When working with many sets, then first a common item cod- ing should be defined by creating a vector with all possible item labels and then specify them as itemLabels to create transactions with transactions(). Compatible itemMatrix objects can be created using encode(). Recoding and Decoding: Two incompatible objects can be made compatible using recode(). Recode one object by specifying the other object in itemLabels. decode() converts from the column IDs used in the itemMatrix representation to item labels. decode() is used by LIST(). Value recode() always returns an object of the same class as x. For encode() with itemMatrix = TRUE an object of class itemMatrix is returned. Otherwise the result is of the same type as x, e.g., a list or a vector. Author(s) <NAME> See Also LIST(), associations, itemMatrix Other preprocessing: discretize(), hierarchy, merge(), sample() Examples data("Adult") ## Example 1: Manual decoding ## Extract the item coding as a vector of item labels. iLabels <- itemLabels(Adult) head(iLabels) ## get undecoded list (itemIDs) list <- LIST(Adult[1:5], decode = FALSE) list ## decode itemIDs by replacing them with the appropriate item label decode(list, itemLabels = iLabels) ## Example 2: Manually create an itemMatrix using iLabels as the common item coding data <- list( c("income=small", "age=Young"), c("income=large", "age=Middle-aged") ) # Option a: encode to match the item coding in Adult iM <- encode(data, itemLabels = Adult) iM inspect(iM) compatible(iM, Adult) # Option b: coercion plus recode to make it compatible to Adult # (note: the coding has 115 item columns after recode) iM <- as(data, "itemMatrix") iM compatible(iM, Adult) iM <- recode(iM, itemLabels = Adult) iM compatible(iM, Adult) ## Example 3: use recode to make itemMatrices compatible ## select first 100 transactions and all education-related items sub <- Adult[1:100, itemInfo(Adult)$variables == "education"] itemLabels(sub) image(sub) ## After choosing only a subset of items (columns), the item coding is now ## no longer compatible with the Adult dataset compatible(sub, Adult) ## recode to match Adult again sub.recoded <- recode(sub, itemLabels = Adult) image(sub.recoded) ## Example 4: manually create 2 new transaction for the Adult data set ## Note: check itemLabels(Adult) to see the available labels for items twoTransactions <- as( encode(list( c("age=Young", "relationship=Unmarried"), c("age=Senior") ), itemLabels = Adult), "transactions") twoTransactions inspect(twoTransactions) ## the same using the transactions constructor function instead twoTransactions <- transactions( list( c("age=Young", "relationship=Unmarried"), c("age=Senior") ), itemLabels = Adult) twoTransactions inspect(twoTransactions) ## Example 5: Use a common item coding # Creation of transactions separately will produce different item codings trans1 <- transactions( list( c("age=Young", "relationship=Unmarried"), c("age=Senior") )) trans1 trans2 <- transactions( list( c("age=Middle-aged", "relationship=Married"), c("relationship=Unmarried", "age=Young") )) trans2 compatible(trans1, trans2) # produce common item coding (all item labels in the two sets) commonItemLabels <- union(itemLabels(trans1), itemLabels(trans2)) commonItemLabels trans1 <- recode(trans1, itemLabels = commonItemLabels) trans1 trans2 <- recode(trans2, itemLabels = commonItemLabels) trans2 compatible(trans1, trans2) ## Example 6: manually create a rule using the item coding in Adult ## and calculate interest measures aRule <- new("rules", lhs = encode(list(c("age=Young", "relationship=Unmarried")), itemLabels = Adult), rhs = encode(list(c("income=small")), itemLabels = Adult) ) ## shorter version using the rules constructor aRule <- rules( lhs = list(c("age=Young", "relationship=Unmarried")), rhs = list(c("income=small")), itemLabels = Adult ) quality(aRule) <- interestMeasure(aRule, measure = c("support", "confidence", "lift"), transactions = Adult) inspect(aRule) itemFrequency Getting Frequency/Support for Single Items Description Provides the generic function itemFrequency() and methods to get the frequency/support for all single items in an objects based on itemMatrix. For example, it is used to get the single item support from an object of class transactions without mining. Usage itemFrequency(x, ...) ## S4 method for signature 'itemMatrix' itemFrequency(x, type = c("relative", "absolute"), weighted = FALSE) ## S4 method for signature 'tidLists' itemFrequency(x, type = c("relative", "absolute")) Arguments x an object of class itemMatrix or tidLists. ... further arguments are passed on. type a character string specifying if "relative" frequency/support or "absolute" frequency/support (item counts) is returned. (default: "relative"). weighted should support be weighted by transactions weights stored as column "weight" in transactionInfo? Value itemFrequency returns a named numeric vector. Each element is the frequency/support of the corresponding item in object x. The items appear in the vector in the same order as in the binary matrix in x. Author(s) <NAME> See Also itemFrequencyPlot() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data("Adult") itemFrequency(Adult, type = "relative") itemFrequencyPlot Creating a Item Frequencies/Support Bar Plot Description Provides the generic function itemFrequencyPlot() and the method to create an item frequency bar plot for inspecting the item frequency distribution for objects based on itemMatrix (e.g., trans- actions, or items in itemsets and rules). Usage itemFrequencyPlot(x, ...) ## S4 method for signature 'itemMatrix' itemFrequencyPlot( x, type = c("relative", "absolute"), weighted = FALSE, support = NULL, topN = NULL, population = NULL, popCol = "black", popLwd = 1, lift = FALSE, horiz = FALSE, names = TRUE, cex.names = graphics::par("cex.axis"), xlab = NULL, ylab = NULL, mai = NULL, ... ) Arguments x the object to be plotted. ... further arguments are passed on (see graphics::barplot() from possible ar- guments). type a character string indicating whether item frequencies should be displayed rela- tive of absolute. weighted should support be weighted by transactions weights stored as column "weight" in transactionInfo? support a numeric value. Only display items which have a support of at least support. If no population is given, support is calculated from x otherwise from the pop- ulation. Support is interpreted relative or absolute according to the setting of type. topN a integer value. Only plot the topN items with the highest item frequency or lift (if lift = TRUE). The items are plotted ordered by descending support. population object of same class as x; if x is a segment of a population, the population mean frequency for each item can be shown as a line in the plot. popCol plotting color for population. popLwd line width for population. lift a logical indicating whether to plot the lift ratio between instead of frequencies. The lift ratio is gives how many times an item is more frequent in x than in population. horiz a logical. If horiz = FALSE (default), the bars are drawn vertically. If TRUE, the bars are drawn horizontally. names a logical indicating if the names (bar labels) should be displayed? cex.names a numeric value for the expansion factor for axis names (bar labels). xlab a character string with the label for the x axis (use an empty string to force no label). ylab a character string with the label for the y axis (see xlab). mai a numerical vector giving the plots margin sizes in inches (see ‘? par’). Value A numeric vector with the midpoints of the drawn bars; useful for adding to the graph. Author(s) <NAME> See Also itemFrequency() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data(Adult) ## the following example compares the item frequencies ## of people with a large income (boxes) with the average in the data set Adult.largeIncome <- Adult[Adult %in% "income=large"] ## simple plot itemFrequencyPlot(Adult.largeIncome) ## plot with the averages of the population plotted as a line ## (for first 72 variables/items) itemFrequencyPlot(Adult.largeIncome[, 1:72], population = Adult[, 1:72]) ## plot lift ratio (frequency in x / frequency in population) ## for items with a support of 20% in the population itemFrequencyPlot(Adult.largeIncome, population = Adult, support = 0.2, lift = TRUE, horiz = TRUE) itemMatrix-class Class itemMatrix — Sparse Binary Incidence Matrix to Represent Sets of Items Description The itemMatrix class is the basic building block for transactions, and associations. The class contains a sparse Matrix representation of a set of itemsets and the corresponding item labels. Usage ## S4 method for signature 'itemMatrix' summary(object, maxsum = 6, ...) ## S4 method for signature 'itemMatrix' dim(x) nitems(x, ...) ## S4 method for signature 'itemMatrix' nitems(x) ## S4 method for signature 'itemMatrix' length(x) toLongFormat(from, ...) ## S4 method for signature 'itemMatrix' toLongFormat(from, cols = c("ID", "item"), decode = TRUE) ## S4 method for signature 'itemMatrix' labels(object, itemSep = ",", setStart = "{", setEnd = "}") itemLabels(object, ...) itemLabels(object) <- value ## S4 method for signature 'itemMatrix' itemLabels(object) ## S4 replacement method for signature 'itemMatrix' itemLabels(object) <- value itemInfo(object) itemInfo(object) <- value ## S4 method for signature 'itemMatrix' itemInfo(object) ## S4 replacement method for signature 'itemMatrix' itemInfo(object) <- value itemsetInfo(object) itemsetInfo(object) <- value ## S4 method for signature 'itemMatrix' itemsetInfo(object) ## S4 replacement method for signature 'itemMatrix' itemsetInfo(object) <- value ## S4 method for signature 'itemMatrix' dimnames(x) ## S4 replacement method for signature 'itemMatrix,list' dimnames(x) <- value Arguments object, x, from the object. maxsum integer, how many items should be shown for the summary? ... further parameters cols columns for the long format. decode decode item IDs to item labels. itemSep item separator symbol. setStart set start symbol. setEnd set end symbol. value replacement value Details Representation Sets of itemsets are represented as a compressed sparse binary matrix. Conceptually, columns represent items and rows are the sets/transactions. In the compressed form, each itemset is a vector of column indices (called item IDs) representing the items. Warning: Ideally, we would store the matrix as a row-oriented sparse matrix (ngRMatrix), but the Matrix package provides better support for column-oriented sparse classes (ngCMatrix). The matrix is therefore internally stored in transposed form. Working with several itemMatrix objects If you work with several itemMatrix objects at the same time (e.g., several transaction sets, lhs and rhs of a rule, etc.), then the encoding (itemLabes and order of the items in the binary matrix) in the different itemMatrices is important and needs to conform. See itemCoding to learn how to encode and recode itemMatrix objects. Functions • summary(itemMatrix): show a summary. • dim(itemMatrix): returns the number of rows (itemsets) and columns (items in the encod- ing). • nitems(itemMatrix): returns the number of items in the encoding. • length(itemMatrix): returns the number of itemsets (rows) in the matrix. • toLongFormat(itemMatrix): convert the sets to long format (a data.frame with two columns, ID and item). Column names can be specified as a character vector of length 2 called cols. • labels(itemMatrix): returns labels for the itemsets. The following arguments can be used to customize the representation of the labels: itemSep, setStart and setEnd. • itemLabels(itemMatrix): returns the item labels used for encoding as a character vector. • itemLabels(itemMatrix) <- value: replaces the item labels used for encoding. • itemInfo(itemMatrix): returns the whole item/column information data.frame including labels. • itemInfo(itemMatrix) <- value: replaces the item/column info by a data.frame. • itemsetInfo(itemMatrix): returns the item set/row information data.frame. • itemsetInfo(itemMatrix) <- value: replaces the item set/row info by a data.frame. • dimnames(itemMatrix): returns a list with the dimname vectors. • dimnames(x = itemMatrix) <- value: replace the dimnames. Slots data a sparse matrix of class ngCMatrix representing the itemsets. Warning: the matrix is stored in transposed form for efficiency reasons!. itemInfo a data.frame itemsetInfo a data.frame Objects from the Class Objects can be created by calls of the form new("itemMatrix", ...). However, most of the time objects will be created by coercion from a matrix, list or data.frame. Coercions • as("matrix", "itemMatrix") • as("itemMatrix", "matrix") • as("list", "itemMatrix") • as("itemMatrix", "list") • as("itemMatrix", "ngCMatrix") • as("ngCMatrix", "itemMatrix") Warning: the ngCMatrix representation is transposed! Author(s) <NAME> See Also Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples set.seed(1234) ## Generate a logical matrix with 5000 random itemsets for 20 items m <- matrix(runif(5000 * 20) > 0.8, ncol = 20, dimnames = list(NULL, paste("item", c(1:20), sep = ""))) head(m) ## Coerce the logical matrix into an itemMatrix object imatrix <- as(m, "itemMatrix") imatrix ## An itemMatrix contains a set of itemsets (each row is an itemset). ## The length of the set is the number of rows. length(imatrix) ## The sparese matrix also has regular matrix dimensions. dim(imatrix) nrow(imatrix) ncol(imatrix) ## Subsetting: Get first 5 elements (rows) of the itemMatrix. This can be done in ## several ways. imatrix[1:5] ### get elements 1:5 imatrix[1:5, ] ### Matrix subsetting for rows 1:5 head(imatrix, n = 5) ### head() ## Get first 5 elements (rows) of the itemMatrix as list. as(imatrix[1:5], "list") ## Get first 5 elements (rows) of the itemMatrix as matrix. as(imatrix[1:5], "matrix") ## Get first 5 elements (rows) of the itemMatrix as sparse ngCMatrix. ## **Warning:** For efficiency reasons, the ngCMatrix is transposed! You ## can transpose it again to get the expected format. as(imatrix[1:5], "ngCMatrix") t(as(imatrix[1:5], "ngCMatrix")) ## Get labels for the first 5 itemsets (first default and then with ## custom formating) labels(imatrix[1:5]) labels(imatrix[1:5], itemSep = " + ", setStart = "", setEnd = "") ## Create itemsets manually from an itemMatrix. Itemsets contain items in the form of ## an itemMatrix and additional quality measures (not supplied in the example). is <- new("itemsets", items = imatrix) is inspect(head(is, n = 3)) ## Create rules manually. I use imatrix[4:6] for the lhs of the rules and ## imatrix[1:3] for the rhs. Rhs and lhs cannot share items so I use ## itemSetdiff here. I also assign missing values for the quality measures support ## and confidence. rules <- new("rules", lhs = itemSetdiff(imatrix[4:6], imatrix[1:3]), rhs = imatrix[1:3], quality = data.frame(support = c(NA, NA, NA), confidence = c(NA, NA, NA) )) rules inspect(rules) ## Manually create a itemMatrix with an item encoding that matches imatrix (20 items in order ## item1, item2, ..., item20) itemset_list <- list(c("item1","item2"), c("item3")) imatrix_new <- encode(itemset_list, itemLabels = imatrix) imatrix_new compatible(imatrix_new, imatrix) itemsets-class Class itemsets — A Set of Itemsets Description The itemsets class represents a set of itemsets and the associated quality measures. Usage itemsets(items, itemLabels = NULL, quality = data.frame()) ## S4 method for signature 'itemsets' summary(object, ...) ## S4 method for signature 'itemsets' length(x) ## S4 method for signature 'itemsets' nitems(x) ## S4 method for signature 'itemsets' labels(object, ...) ## S4 method for signature 'itemsets' itemLabels(object) ## S4 replacement method for signature 'itemsets' itemLabels(object) <- value ## S4 method for signature 'itemsets' itemInfo(object) ## S4 method for signature 'itemsets' items(x) ## S4 replacement method for signature 'itemsets' items(x) <- value ## S4 method for signature 'itemsets' tidLists(x) Arguments items an itemMatrix or an object that can be converted using encode(). itemLabels item labels used for encode(). quality a data.frame with quality information (one row per itemset). object, x the object ... further argments value replacement value Details Itemsets are usually created by calling an association rule mining algorithm like apriori(). To cre- ate itemsets manually, the itemMatrix for the items of the itemsets can be created using itemCoding. An example is in the Example section below. Mined itemsets sets contain several interest measures accessible with the quality() method. Ad- ditional measures can be calculated via interestMeasure(). Functions • summary(itemsets): create a summary • length(itemsets): get the number of itemsets. • nitems(itemsets): get the number of items (columns) in the current encoding. • labels(itemsets): get the itemset labels. • itemLabels(itemsets): get the item labels. • itemLabels(itemsets) <- value: replace the item labels. • itemInfo(itemsets): get item info data.frame. • items(itemsets): get items as an itemMatrix. • items(itemsets) <- value: with a different itemMatrix. • tidLists(itemsets): get tidLists stored in the object (if any). Slots items an itemMatrix object representing the itemsets. tidLists a tidLists or NULL. quality a data.frame with quality information info a list with mining information. Objects from the Class Objects are the result of calling the functions apriori() (e.g., with target = "frequent itemsets" in the parameter list) or eclat(). Objects can also be created by calls of the form new("itemsets", ...) or by using the constructor function itemsets(). Coercions • as("itemsets", "data.frame") Author(s) <NAME> See Also Superclass: associations Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), match(), rules-class, sample(), sets, size(), sort(), unique() Examples data("Adult") ## Mine frequent itemsets with Eclat. fsets <- eclat(Adult, parameter = list(supp = 0.5)) ## Display the 5 itemsets with the highest support. fsets.top5 <- sort(fsets)[1:5] inspect(fsets.top5) ## Get the itemsets as a list as(items(fsets.top5), "list") ## Get the itemsets as a binary matrix as(items(fsets.top5), "matrix") ## Get the itemsets as a sparse matrix, a ngCMatrix from package Matrix. ## Warning: for efficiency reasons, the ngCMatrix you get is transposed as(items(fsets.top5), "ngCMatrix") ## Manually create itemsets with the item coding in the Adult dataset ## and calculate some interest measures twoitemsets <- itemsets( items = list( c("age=Young", "relationship=Unmarried"), c("age=Old") ), itemLabels = Adult) quality(twoitemsets) <- data.frame(support = interestMeasure(twoitemsets, measure = c("support"), transactions = Adult)) inspect(twoitemsets) itemwiseSetOps Itemwise Set Operations Description Provides the generic functions and the methods for itemwise set operations on items in an item- Matrix. The regular set operations regard each itemset in an itemMatrix as an element. Itemwise operations regard each item as an element and operate on the items of pairs of corresponding item- sets (first itemset in x with first itemset in y, second with second, etc.). Usage itemUnion(x, y) itemSetdiff(x, y) itemIntersect(x, y) ## S4 method for signature 'itemMatrix,itemMatrix' itemUnion(x, y) ## S4 method for signature 'itemMatrix,itemMatrix' itemSetdiff(x, y) ## S4 method for signature 'itemMatrix,itemMatrix' itemIntersect(x, y) Arguments x, y two itemMatrix objects with the same number of rows (itemsets). Value An object of class itemMatrix is returned. Author(s) <NAME> Examples data("Adult") fsets <- eclat(Adult, parameter = list(supp = 0.5)) inspect(fsets[1:4]) inspect(itemUnion(items(fsets[1:2]), items(fsets[3:4]))) inspect(itemSetdiff(items(fsets[1:2]), items(fsets[3:4]))) inspect(itemIntersect(items(fsets[1:2]), items(fsets[3:4]))) LIST List Representation for Objects Based on Class itemMatrix Description Provides the generic function LIST() and the methods to create a list representation from objects of the classes itemMatrix, transactions, and tidLists. Usage LIST(from, ...) ## S4 method for signature 'itemMatrix' LIST(from, decode = TRUE) ## S4 method for signature 'transactions' LIST(from, decode = TRUE) ## S4 method for signature 'tidLists' LIST(from, decode = TRUE) Arguments from the object to be converted into a list. ... further arguments. decode a logical controlling whether the items/transactions are decoded from the col- umn numbers internally used by itemMatrix to the names stored in the object from. The default behavior is to decode. Details Using LIST() with decode = TRUE is equivalent to the standard coercion as(x, "list"). LIST returns the object from as a list of vectors. Each vector represents one row of the itemMatrix (e.g., items in a transaction). Value a list primitive. Author(s) <NAME> See Also Other import/export: DATAFRAME(), pmml, read, write() Examples data(Adult) ### default coercion (same as as(Adult[1:5], "list")) LIST(Adult[1:5]) ### coercion without item decoding LIST(Adult[1:5], decode = FALSE) match Value Matching Description Provides the generic function match() and the methods for associations, transactions and itemMa- trix objects. match() returns a vector of the positions of (first) matches of its first argument in its second. Usage match(x, table, nomatch = NA_integer_, incomparables = NULL) ## S4 method for signature 'itemMatrix,itemMatrix' match(x, table, nomatch = NA_integer_, incomparables = NULL) ## S4 method for signature 'rules,rules' match(x, table, nomatch = NA_integer_, incomparables = NULL) ## S4 method for signature 'itemsets,itemsets' match(x, table, nomatch = NA_integer_, incomparables = NULL) ## S4 method for signature 'itemMatrix,itemMatrix' x %in% table ## S4 method for signature 'itemMatrix,character' x %in% table ## S4 method for signature 'associations,associations' x %in% table ## S4 method for signature 'itemMatrix,character' x %pin% table ## S4 method for signature 'itemMatrix,character' x %ain% table ## S4 method for signature 'itemMatrix,character' x %oin% table Arguments x an object of class itemMatrix, transactions or associations. table a set of associations or transactions to be matched against. nomatch the value to be returned in the case when no match is found. incomparables not implemented. Details %in% is a more intuitive interface as a binary operator, which returns a logical vector indicating if there is a match or not for the items in the itemsets (left operand) with the items in the table (right operand). arules defines additional binary operators for matching itemsets: %pin% uses partial matching on the table; %ain% itemsets have to match/include all items in the table; %oin% itemsets can only match/include the items in the table. The binary matching operators or often used in subset(). Value match: An integer vector of the same length as x giving the position in table of the first match if there is a match, otherwise nomatch. %in%, %pin%, %ain%, %oin%: A logical vector, indicating if a match was located for each element of x. Author(s) <NAME> See Also Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, rules-class, sample(), sets, size(), sort(), unique() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, merge(), random.transactions(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data("Adult") ## get unique transactions, count frequency of unique transactions ## and plot frequency of unique transactions vals <- unique(Adult) cnts <- tabulate(match(Adult, vals)) plot(sort(cnts, decreasing=TRUE)) ## find all transactions which are equal to transaction 10 in Adult which(Adult %in% Adult[10]) ## for transactions we can also match directly with itemLabels. ## Find in the first 10 transactions the ones which ## contain age=Middle-aged (see help page for class itemMatrix) Adult[1:10] %in% "age=Middle-aged" ## find all transactions which contain items that partially match "age=" (all here). Adult[1:10] %pin% "age=" ## find all transactions that only include the item "age=Middle-aged" (none here). Adult[1:10] %oin% "age=Middle-aged" ## find al transaction which contain both items "age=Middle-aged" and "sex=Male" Adult[1:10] %ain% c("age=Middle-aged", "sex=Male") merge Adding Items to Data Description Provides the generic function merge() and the methods for itemMatrix and transactions to add new items to existing data. Usage merge(x, y, ...) ## S4 method for signature 'itemMatrix' merge(x, y, ...) ## S4 method for signature 'transactions' merge(x, y, ...) Arguments x an object of class itemMatrix or transactions. y an object of the same class as x (or something which can be coerced to that class). ... further arguments; unused. Value Returns a new object of the same class as x with the items in y added. Author(s) <NAME> See Also Other preprocessing: discretize(), hierarchy, itemCoding, sample() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), random.transactions(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data("Groceries") ## create a random item as a matrix randomItem <- sample(c(TRUE, FALSE), size = length(Groceries),replace = TRUE) randomItem <- as.matrix(randomItem) colnames(randomItem) <- "random item" head(randomItem, 3) ## add the random item to Groceries g2 <- merge(Groceries, randomItem) nitems(Groceries) nitems(g2) inspect(head(g2, 3)) Mushroom The Mushroom Data Set as Transactions Description The Mushroom transactions data set includes descriptions of hypothetical samples corresponding to 23 species of gilled mushrooms in the Agaricus and Lepiota Family. Format Object of class transactions with 8124 transactions and 114 items. Details The transaction set contains information about 8124 mushrooms (transactions). 4208 (51.8%) are edible and 3916 (48.2%) are poisonous. The data contains 22 nominal features plus the class at- tribute (edible or not). These features were translated into 114 items. Author(s) <NAME> Source The data set was obtained from the UCI Machine Learning Repository at https://archive.ics. uci.edu/ml/datasets/Mushroom. References <NAME> (1981). Mushroom records drawn from The Audubon Society Field Guide to North American Mushrooms. G. H. Lincoff (Pres.), New York. pmml Read and Write PMML Description This function reads and writes PMML representations (version 4.1) of associations (itemsets and rules). Write delegates to package pmml. Usage write.PMML(x, file) read.PMML(file) Arguments x a rules or itemsets object. file name of the PMML file (for read.PMML() also a XML root node can be sup- plied). Author(s) <NAME> References PMML 4.4 - Association Rules. https://dmg.org/pmml/v4-4/AssociationRules.html See Also pmml::pmml(). Other import/export: DATAFRAME(), LIST(), read, write() Examples data("Groceries") rules <- apriori(Groceries, parameter = list(support = 0.001)) rules <- head(rules, by = "lift") rules ### save rules as PMML write.PMML(rules, file = "rules.xml") ### read rules back rules2 <- read.PMML("rules.xml") rules2 ### compare rules inspect(rules[1]) inspect(rules2[1]) ### clean up unlink("rules.xml") predict Model Predictions Description Provides the method predict() for itemMatrix (e.g., transactions). Predicts the membership (near- est neighbor) of new data to clusters represented by medoids or labeled examples. Usage predict(object, ...) ## S4 method for signature 'itemMatrix' predict(object, newdata, labels = NULL, blocksize = 200, ...) Arguments object clustered examples as an itemMatrix with cluster label specified in labels or medoids as an itemMatrix (use labels = NULL). ... further arguments passed on to dissimilarity(). E.g., method. newdata an itemMatrix containing the objects to predict labels for. labels an integer vector containing the labels for the examples in object. The cluster labels need to be contiguous integers starting with 1. blocksize a numeric scalar indicating how much memory predict can use for big x and/or y (approx. in MB). 200 is only a crude approximation for 32-bit machines (64- bit architectures need double the blocksize in memory) and using the default Jaccard method for dissimilarity calculation. In general, reducing blocksize will decrease the memory usage but will increase the run-time. Value An integer vector of the same length as newdata containing the predicted labels for each element. Author(s) <NAME> See Also Other proximity classes and functions: affinity(), dissimilarity(), proximity-classes Examples data("Adult") ## sample small <- sample(Adult, 500) large <- sample(Adult, 5000) ## cluster a small sample and extract the cluster lael vector d_jaccard <- dissimilarity(small) hc <- hclust(d_jaccard) l <- cutree(hc, k=4) ## predict labels for a larger sample labels <- predict(small, large, l) ## plot the profile of the 1. cluster itemFrequencyPlot(large[labels == 1, itemFrequency(large) > 0.1]) proximity-classes Classes dist, ar_cross_dissimilarity and ar_similarity — Proximity Matrices Description Simple classes to represent proximity matrices. Details For compatibility with clustering functions in R, we represent dissimilarities as the S3 class dist. For cross-dissimilarities and similarities, we provide the S4 classes ar_cross_dissimilarities and ar_similarities. Objects from the Class dist objects are the result of calling the method dissimilarity() with one argument or any R function returning a S3 dist object. ar_cross_dissimilarity objects are the result of calling the method dissimilarity() with two arguments, by calls of the form new("similarity", ...), or by coercion from matrix. ar_similarity objects are the result of calling the method affinity(), by calls of the form new("similarity", ...), or by coercion from matrix. Author(s) <NAME> See Also stats::dist(), proxy::dist() Other proximity classes and functions: affinity(), dissimilarity(), predict() random.transactions Simulate a Random Transactions Description Simulate random transactions using different methods. Usage random.transactions( nItems, nTrans, method = "independent", ..., verbose = FALSE ) random.patterns( nItems, nPats = 2000, method = NULL, lPats = 4, corr = 0.5, cmean = 0.5, cvar = 0.1, iWeight = NULL, verbose = FALSE ) Arguments nItems an integer. Number of items to simulate nTrans an integer. Number of transactions to simulate method name of the simulation method used (see Details Section). ... further arguments used for the specific simulation method (see details). verbose report progress? nPats number of patterns (potential maximal frequent itemsets) used. lPats average length of patterns. corr correlation between consecutive patterns. cmean mean of the corruption level (normal distribution). cvar variance of the corruption level. iWeight item selection weights to build patterns. Details Currently two simulation methods are implemented: • "independent" (Hahsler et al, 2006): All items are treated as independent. The transaction size is determined by rpois(lambda - 1) + 1, where lambda can be specified (defaults to 3). Note that one subtracted from lambda and added to the size to avoid empty transactions. The items in the transactions are randomly chosen using the numeric probability vector iProb of length nItems (default: 0.01 for each item). • "agrawal" (see Agrawal and Srikant, 1994): This method creates transactions with correlated items using random.patters(). The simulation is a two-stage process. First, a set of nPats patterns (potential maximal frequent itemsets) is generated. The length of the patterns is Poisson distributed with mean lPats and consecutive patterns share some items controlled by the correlation parameter corr. For later use, for each pattern a pattern weight is generated by drawing from an exponential distribution with a mean of 1 and a corruption level is chosen from a normal distribution with mean cmean and variance cvar. The function returns the patterns as an itemsets objects which can be supplied to random.transactions() as the argument patterns. If no argument patterns is supplied, the default values given above are used. In the second step, the transactions are generated using the patterns. The length the trans- actions follows a Poisson distribution with mean lPats. For each transaction, patterns are randomly chosen using the pattern weights till the transaction length is reached. For each chosen pattern, the associated corruption level is used to drop some items before adding the pattern to the transaction. Value Returns a ntrans x nitems transactions object. Author(s) <NAME> References <NAME>, <NAME>, and <NAME> (2006). Implications of probabilistic data modeling for mining association rules. In <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, editors, From Data and Information Analysis to Knowledge Engineering, Studies in Classification, Data Analysis, and Knowledge Organization, pages 598–605. Springer-Verlag. <NAME> and <NAME> (1994). Fast algorithms for mining association rules in large databases. In <NAME>, <NAME>, and <NAME>, editors, Proceedings of the 20th International Conference on Very Large Data Bases, VLDB, pages 487–499, Santiago, Chile. See Also Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), sample(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples ## generate random 1000 transactions for 200 items with ## a success probability decreasing from 0.2 to 0.0001 ## using the method described in Hahsler et al. (2006). trans <- random.transactions(nItems = 200, nTrans = 1000, lambda = 5, iProb = seq(0.2,0.0001, length=200)) ## size distribution summary(size(trans)) ## display random data set image(trans) ## use the method by Agrawal and Srikant (1994) to simulate transactions ## which contains correlated items. This should create data similar to ## T10I4D100K (we just create 100 transactions here to speed things up). patterns <- random.patterns(nItems = 1000) summary(patterns) trans2 <- random.transactions(nItems = 1000, nTrans = 100, method = "agrawal", patterns = patterns) image(trans2) ## plot data with items ordered by item frequency image(trans2[,order(itemFrequency(trans2), decreasing=TRUE)]) read Read Transaction Data Description Reads transaction data from a file and creates a transactions object. Usage read.transactions( file, format = c("basket", "single"), header = FALSE, sep = "", cols = NULL, rm.duplicates = FALSE, quote = "\"'", skip = 0, encoding = "unknown" ) Arguments file the file name or a connection. format a character string indicating the format of the data set. One of "basket" or "single", can be abbreviated. header a logical value indicating whether the file contains the names of the variables as its first line. sep a character string specifying how fields are separated in the data file. The default ("") splits at whitespaces. cols For the single format, cols is a numeric or character vector of length two giving the numbers or names of the columns (fields) with the transaction and item ids, respectively. If character, the first line of file is assumed to be a header with column names. For the basket format, cols can be a numeric scalar giving the number of the column (field) with the transaction ids. If cols = NULL, the data do not contain transaction ids. rm.duplicates a logical value specifying if duplicate items should be removed from the trans- actions. quote a list of characters used as quotes when reading. skip number of lines to skip in the file before start reading data. encoding character string indicating the encoding which is passed to readLines() or scan() (see Encoding for character encoding). Details For basket format, each line in the transaction data file represents a transaction where the items (item labels) are separated by the characters specified by sep. For single format, each line corresponds to a single item, containing at least ids for the transaction and the item. Value Returns an object of class transactions. Author(s) <NAME> and <NAME> See Also Other import/export: DATAFRAME(), LIST(), pmml, write() Examples ## create a demo file using basket format for the example data <- paste( "# this is some test data", "item1, item2", "item1", "item2, item3", sep="\n") cat(data) write(data, file = "demo_basket.txt") ## read demo data (skip the comment in the first line) tr <- read.transactions("demo_basket.txt", format = "basket", sep = ",", skip = 1) inspect(tr) ## make always sure that the items were properly separated itemLabels(tr) ## create a demo file using single format for the example ## column 1 contains the transaction ID and column 2 contains one item data <- paste( "trans1 item1", "trans2 item1", "trans2 item2", sep ="\n") cat(data) write(data, file = "demo_single.txt") ## read demo data tr <- read.transactions("demo_single.txt", format = "single", cols = c(1,2)) inspect(tr) ## create a demo file using single format with column headers data <- paste( "item_id;trans_id", "item1;trans1", "item1;trans2", "item2;trans2", sep ="\n") cat(data) write(data, file = "demo_single.txt") ## read demo data tr <- read.transactions("demo_single.txt", format = "single", header = TRUE, sep = ";", cols = c("trans_id", "item_id")) inspect(tr) ## tidy up unlink("demo_basket.txt") unlink("demo_single.txt") ruleInduction Association Rule Induction from Itemsets Description Provides the generic function ruleInduction() and the method to induce all association rules which can be generated by the given set of itemsets from a transactions dataset. Usage ruleInduction(x, ...) ## S4 method for signature 'itemsets' ruleInduction( x, transactions = NULL, confidence = 0.8, method = c("ptree", "apriori"), reduce = FALSE, verbose = FALSE, ... ) Arguments x the set of itemsets from which rules will be induced. ... further arguments. transactions the transactions used to mine the itemsets. Can be omitted for method "ptree", if x contains a (complete set) of frequent itemsets together with their support counts. confidence a numeric value between 0 and 1 giving the minimum confidence threshold for the rules. method "ptree" or "apriori" reduce remove unused items to speed up the counting process? verbose report progress? Details All rules that can be created using the supplied itemsets and that surpass the specified minimum confidence threshold are returned. ruleInduction() can be used to produce closed association rules defined by Pei et al. (2000) as rules X => Y where both X and Y are closed frequent itemsets. See the code example in the Example section. Rule induction implements several induction methods. The default method is "ptree" • "ptree" method without transactions: No transactions are need to be specified if x contains a complete set of frequent or itemsets. The itemsets’ support counts are stored in a ptree and then retrieved to create rules and calculate rules confidence. This is very fast, but fails because of missing support values if x is not a complete set of frequent itemsets. • "ptree" method with transactions: If transactions are specified then all transactions are counted into a prefix tree and later retrieved to create rules from the itemsets and calculate confidence values. This is slower, but necessary if x is not a complete set of frequent itemsets. To improve speed, unused items are removed from the transaction data before creating the prefix tree (this behavior can be changed using the argument reduce). This might be slower for large transaction data sets. However, this is highly recommended as the items are also reordered to reduce the counting time. • "apriori" method (always needs transactions): All association rules are mined from the transactions data set using apriori() with the smallest support found in the itemsets. In a second step, all rules which cannot be generated from one of the itemsets are removed. This procedure is very slow, especially for itemsets with many elements or very low support. Value An object of class rules. Author(s) <NAME> and <NAME> References <NAME>, <NAME>, and <NAME>. Selective association rule generation. Com- putational Statistics, 23(2):303-315, April 2008. <NAME>, <NAME>, <NAME>. CLOSET: An Efficient Algorithm for Mining Frequent Closed Itemsets. ACM SIGMOD Workshop on Research Issues in Data Mining and Knowledge Discovery (DMKD 2000). See Also Other mining algorithms: APappearance-class, AScontrol-classes, ASparameter-classes, apriori(), eclat(), fim4r(), weclat() Examples data("Adult") ## find all closed frequent itemsets closed_is <- apriori(Adult, target = "closed frequent itemsets", support = 0.4) closed_is ## use rule induction to produce all closed association rules closed_rules <- ruleInduction(closed_is, transactions = Adult, verbose = TRUE) ## inspect the resulting closed rules summary(closed_rules) inspect(head(closed_rules, by = "lift")) ## get rules from frequent itemsets. Here, transactions does not need to be ## specified for rule induction. frequent_is <- eclat(Adult, support = 0.4) assoc_rules <- ruleInduction(frequent_is) assoc_rules inspect(head(assoc_rules)) ## for itemsets that are not a complete set of frequent itemsets, ## transactions need to be specified. some_is <- sample(frequent_is, 10) some_rules <- ruleInduction(some_is, transactions = Adult) some_rules rules-class Class rules — A Set of Rules Description Defines the rules class to represent a set of association rules and methods to work with rules. Usage rules(rhs, lhs, itemLabels = NULL, quality = data.frame()) ## S4 method for signature 'rules' summary(object, ...) ## S4 method for signature 'rules' length(x) ## S4 method for signature 'rules' nitems(x) ## S4 method for signature 'rules' labels(object, ruleSep = " => ", ...) ## S4 method for signature 'rules' itemLabels(object) ## S4 replacement method for signature 'rules' itemLabels(object) <- value ## S4 method for signature 'rules' itemInfo(object) lhs(x) ## S4 method for signature 'rules' lhs(x) lhs(x) <- value ## S4 replacement method for signature 'rules' lhs(x) <- value rhs(x) rhs(x) <- value ## S4 replacement method for signature 'rules' rhs(x) <- value ## S4 method for signature 'rules' rhs(x) ## S4 method for signature 'rules' items(x) generatingItemsets(x) ## S4 method for signature 'rules' generatingItemsets(x) Arguments rhs, lhs itemMatrix objects or objects that can be converted using encode(). itemLabels a vector of all possible item labels (character) or a transactions object to copy the item coding used for encode() (see itemCoding for details). quality a data.frame with quality information (one row per rule). object, x the object ... further arguments ruleSep rule separation symbol value replacement value Details Mined rule sets typically contain several interest measures accessible with the quality() method. Additional measures can be calculated via interestMeasure(). To create rules manually, the itemMatrix for the LHS and the RHS of the rules need to be compati- ble. See itemCoding for details. Functions • summary(rules): create a summary • length(rules): returns the number of rules. • nitems(rules): returns the number of items used in the current encoding. • labels(rules): labels for the rules. • itemLabels(rules): returns item labels for the current encoding. • itemLabels(rules) <- value: change the item labels in the current encoding. • itemInfo(rules): returns the item info data.frame. • lhs(rules): returns the LHS of the rules as an itemMatrix. • lhs(rules) <- value: replaces the LHS of the rules with an itemMatrix. • rhs(rules) <- value: replaces the RHS of the rules with an itemMatrix. • rhs(rules): returns the RHS of the rules as an itemMatrix. • items(rules): returns all items in a rule (LHS and RHS) an itemMatrix. • generatingItemsets(rules): returns a collection of the itemsets which generated the rules, one itemset for each rule. Note that the collection can be a multiset and contain duplicated elements. Use unique() to remove duplicates and obtain a proper set. This method produces the same as the result as calling items(), but wrapped into an itemsets object with support information. Slots lhs,rhs itemMatrix representing the left-hand-side and right-hand-side of the rules. quality the quality data.frame info a list with mining information. Objects from the Class Objects are the result of calling the function apriori(). Objects can also be created by calls of the form new("rules", ...) or by using the constructor function rules(). Coercions • as("rules", "data.frame") Author(s) <NAME> See Also Superclass: associations Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), sample(), sets, size(), sort(), unique() Examples data("Adult") ## Mine rules rules <- apriori(Adult, parameter = list(support = 0.3)) rules ## Select a subset of rules using partial matching on the items ## in the right-hand-side and a quality measure rules.sub <- subset(rules, subset = rhs %pin% "sex" & lift > 1.3) ## Display the top 3 support rules inspect(head(rules.sub, n = 3, by = "support")) ## Display the first 3 rules inspect(rules.sub[1:3]) ## Get labels for the first 3 rules labels(rules.sub[1:3]) labels(rules.sub[1:3], itemSep = " + ", setStart = "", setEnd="", ruleSep = " ---> ") ## Manually create rules using the item coding in Adult and calculate some interest measures twoRules <- rules( lhs = list( c("age=Young", "relationship=Unmarried"), c("age=Old") ), rhs = list( c("income=small"), c("income=large") ), itemLabels = Adult ) quality(twoRules) <- interestMeasure(twoRules, measure = c("support", "confidence", "lift"), transactions = Adult) inspect(twoRules) sample Random Samples and Permutations Description Provides the generic function sample() and methods to sample from transactions and associations. Usage ## S4 method for signature 'itemMatrix' sample(x, size, replace = FALSE, prob = NULL, ...) ## S4 method for signature 'associations' sample(x, size, replace = FALSE, prob = NULL, ...) Arguments x object to be sampled from (a set of associations or transactions). size sample size. replace a logical. Sample with replacement? prob a numeric vector of probability weights. ... further arguments. Value An object of the same class as x. Author(s) <NAME> See Also Other preprocessing: discretize(), hierarchy, itemCoding, merge() Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sets, size(), sort(), unique() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sets, size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data("Adult") ## sample with replacement s <- sample(Adult, 500, replace = TRUE) s sets Set Operations Description Provides the generic functions and the methods for the set operations union(), intersect(), setequal(), setdiff() and is.element() on sets of associations (e.g., rules, itemsets) and item- Matrix. Usage ## S3 method for class 'itemMatrix' union(x, y, ...) ## S3 method for class 'associations' union(x, y, ...) ## S4 method for signature 'associations' union(x, y, ...) ## S4 method for signature 'itemMatrix' union(x, y, ...) ## S3 method for class 'itemMatrix' intersect(x, y, ...) ## S3 method for class 'associations' intersect(x, y, ...) ## S4 method for signature 'associations' intersect(x, y, ...) ## S4 method for signature 'itemMatrix' intersect(x, y, ...) ## S3 method for class 'itemMatrix' setequal(x, y, ...) ## S3 method for class 'associations' setequal(x, y, ...) ## S4 method for signature 'associations' setequal(x, y, ...) ## S4 method for signature 'itemMatrix' setequal(x, y, ...) ## S3 method for class 'itemMatrix' setdiff(x, y, ...) ## S3 method for class 'associations' setdiff(x, y, ...) ## S4 method for signature 'associations' setdiff(x, y, ...) ## S4 method for signature 'itemMatrix' setdiff(x, y, ...) ## S3 method for class 'itemMatrix' is.element(el, set, ...) ## S3 method for class 'associations' is.element(el, set, ...) ## S4 method for signature 'associations' is.element(el, set, ...) ## S4 method for signature 'itemMatrix' is.element(el, set, ...) Arguments x, y, el, set sets of associations or itemMatrix objects. ... Other arguments are unused. Details Technical note: All S4 methods for set operations are defined for the class name "ANY" in the signature, so they should work for all S4 classes for which the following methods are available: match(), length() and unique(). Value union(), intersect(), setequal() and setdiff() return an object of the same class as x and y. is.element() returns a logic vector of length el indicating for each element if it is included in set. Author(s) <NAME> See Also Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), size(), sort(), unique() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), size(), supportingTransactions(), tidLists-class, transactions-class, unique() Examples data("Adult") ## mine some rules r <- apriori(Adult) ## take 2 subsets r1 <- r[1:10] r2 <- r[6:15] union(r1, r2) intersect(r1, r2) setequal(r1, r2) size Number of Items in Sets Description Provides the generic function size() and methods to get the size of each itemset in an itemMatrix or associations. For example, size() can be used to get a vector with the number of items in each transaction. Usage size(x, ...) ## S4 method for signature 'itemMatrix' size(x) ## S4 method for signature 'tidLists' size(x) ## S4 method for signature 'itemsets' size(x) ## S4 method for signature 'rules' size(x) Arguments x an object. ... further (unused) arguments. Value returns a numeric vector of length length(x). Each element is the size of the corresponding ele- ment (row in the itemMatrix) in object x. For rules, size() returns the sum of the number of items in the LHS and the RHS. Author(s) <NAME> See Also Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, supportingTransactions(), tidLists-class, transactions-class, unique() Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, sort(), unique() Examples data("Adult") summary(size(Adult)) sort Sort Associations Description Provides the method sort to sort elements in class associations (e.g., itemsets or rules) according to the value of measures stored in the association’s slot quality (e.g., support). Usage ## S4 method for signature 'associations' sort(x, decreasing = TRUE, na.last = NA, by = "support", order = FALSE, ...) Arguments x an object to be sorted. decreasing a logical. Should the sort be increasing or decreasing? (default is decreasing) na.last na.last is not supported for associations. NAs are always put last. by a character string specifying the quality measure stored in x to be used to sort x. If a vector of character strings is specified then the additional strings are used to sort x in case of ties. order should a order vector (a permutation like order()) be returned instead of the sorted associations? ... Further arguments are ignored. Details sort is relatively slow for large sets of associations since it has to copy and rearrange a large data structure. With order = TRUE an integer vector with the order is returned instead of the reordered associations. If only the top n associations are needed then head() using by performs this faster than calling sort() and then head() since it does it without copying and rearranging all the data. tail() works in the same way. Value An object of the same class as x or a permutation vector. Author(s) <NAME> See Also Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), unique() Examples data("Adult") ## Mine rules with Apriori rules <- apriori(Adult, parameter = list(supp = 0.6)) rules_by_lift <- sort(rules, by = "lift") inspect(head(rules)) inspect(head(rules_by_lift)) ## A faster/less memory consuming way to get the top 5 rules according to lift ## (see Details section) inspect(head(rules, n = 5, by = "lift")) subset Subsetting Itemsets, Rules and Transactions Description Provides the generic function subset() and methods to subset associations or transactions (item- Matrix) which meet certain conditions (e.g., contains certain items or satisfies a minimum lift). Usage subset(x, ...) ## S4 method for signature 'itemMatrix' subset(x, subset, ...) ## S4 method for signature 'itemsets' subset(x, subset, ...) ## S4 method for signature 'rules' subset(x, subset, ...) Arguments x object to be subsetted. ... further arguments to be passed to or from other methods. subset logical expression indicating elements to keep. Details subset() finds the rows/itemsets/rules of x that match the expression given in subset. Parts of x like items, lhs, rhs and the columns in the quality data.frame (e.g., support and lift) can be directly referred to by their names in subset. Important operators to select itemsets containing items specified by their labels are • %in%: select itemsets matching any given item • %ain%: select only itemsets matching all given item • %oin%: select only itemsets matching only the given item • %pin%: %in% with partial matching Value An object of the same class as x containing only the elements which satisfy the conditions. Author(s) <NAME> Examples data("Adult") rules <- apriori(Adult) ## select all rules with item "marital-status=Never-married" in ## the right-hand-side and lift > 2 rules.sub <- subset(rules, subset = rhs %in% "marital-status=Never-married" & lift > 2) ## use partial matching for all items corresponding to the variable ## "marital-status" rules.sub <- subset(rules, subset = rhs %pin% "marital-status=") ## select only rules with items "age=Young" and "workclass=Private" in ## the left-hand-side rules.sub <- subset(rules, subset = lhs %ain% c("age=Young", "workclass=Private")) SunBai The SunBai Weighted Transactions Data Set Description A small example database for weighted association rule mining provided as an object of class trans- actions. Format Object of class transactions with 6 transactions and 8 items. Weights are stored as transaction information. Details The data set contains the example database described in the paper by <NAME> and F.Bai for illustra- tion of the concepts of weighted association rule mining. weight stored as transaction information denotes the transaction weights obtained using the HITS algorithm. Source <NAME> and <NAME> (2008). Mining Weighted Association Rules without Preassigned Weights. IEEE Transactions on Knowledge and Data Engineering, 4 (30), 489–495. See Also Other weighted association mining functions: hits(), weclat() Examples data(SunBai) summary(SunBai) inspect(SunBai) transactionInfo(SunBai) support Support Counting for Itemsets Description Provides the generic function support() and the methods to count support for given itemMatrix and associations in a given transactions data. Usage support(x, transactions, ...) ## S4 method for signature 'itemMatrix' support( x, transactions, type = c("relative", "absolute"), method = c("ptree", "tidlists"), reduce = FALSE, weighted = FALSE, verbose = FALSE, ... ) ## S4 method for signature 'associations' support( x, transactions, type = c("relative", "absolute"), method = c("ptree", "tidlists"), reduce = FALSE, weighted = FALSE, verbose = FALSE, ... ) Arguments x the set of itemsets for which support should be counted. transactions the transaction data set used for mining. ... further arguments. type a character string specifying if "relative" support or "absolute" support (counts) are returned for the itemsets in x. (default: "relative") method use "ptree" or "tidlists". See Details Section. reduce should unused items are removed before counting? weighted should support be weighted by transactions weights stored as column "weight" in transactionInfo? verbose report progress? Details Normally, the support of frequent itemsets is very efficiently counted during mining process using a set minimum support. However, if only the support for specific itemsets (maybe itemsets with very low support) is needed, or the support of a set of itemsets needs to be recalculated on different transactions than they were mined on, then support() can be used. Several methods for support counting are available: • "ptree" (default method): The counters for the itemsets are organized in a prefix tree. The transactions are sequentially processed and the corresponding counters in the prefix tree are incremented (see Hahsler et al, 2008). This method is used by default since it is typically significantly faster than transaction ID list intersection. • "tidlists": support is counted using transaction ID list intersection which is used by several fast mining algorithms (e.g., by Eclat). However, Support is determined for each itemset individually which is slow for a large number of long itemsets in dense data. To speed up counting, reduce = TRUE can be specified in control. Unused items are removed from the transactions before counting. Value A numeric vector of the same length as x containing the support values for the sets in x. Author(s) <NAME> and <NAME> References <NAME>, <NAME>, and <NAME>. Selective association rule generation. Com- putational Statistics, 23(2):303-315, April 2008. See Also Other interest measures: confint(), coverage(), interestMeasure(), is.redundant(), is.significant() Examples data("Income") ## find and some frequent itemsets itemsets <- eclat(Income)[1:5] ## inspect the support returned by eclat inspect(itemsets) ## count support in the database support(items(itemsets), Income) supportingTransactions Supporting Transactions Description Find for each itemset in an associations object which transactions support (i.e., contains all items in the itemset) it. The information is returned as a tidLists object. Usage supportingTransactions(x, transactions, ...) ## S4 method for signature 'associations' supportingTransactions(x, transactions) Arguments x a set of associations (itemsets, rules, etc.) transactions an object of class transactions used to mine the associations in x. ... currently unused. Value An object of class tidLists containing one transaction ID list per association in x. Author(s) <NAME> See Also Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), tidLists-class, transactions-class, unique() Examples data <- list( c("a","b","c"), c("a","b"), c("a","b","d"), c("b","e"), c("b","c","e"), c("a","d","e"), c("a","c"), c("a","b","d"), c("c","e"), c("a","b","d","e") ) data <- as(data, "transactions") ## mine itemsets f <- eclat(data, parameter = list(support = .2, minlen = 3)) inspect(f) ## find supporting Transactions st <- supportingTransactions(f, data) st as(st, "list") tidLists-class Class tidLists — Transaction ID Lists for Items/Itemsets Description Class to represent transaction ID lists and associated methods. Usage tidLists(x) ## S4 method for signature 'tidLists' summary(object, maxsum = 6, ...) ## S4 method for signature 'tidLists' dim(x) ## S4 method for signature 'tidLists' dimnames(x) ## S4 replacement method for signature 'tidLists,list' dimnames(x) <- value ## S4 method for signature 'tidLists' length(x) ## S4 method for signature 'tidLists' t(x) ## S4 method for signature 'tidLists' transactionInfo(x) ## S4 replacement method for signature 'tidLists' transactionInfo(x) <- value ## S4 method for signature 'tidLists' itemInfo(object) ## S4 replacement method for signature 'tidLists' itemInfo(object) <- value ## S4 method for signature 'tidLists' itemLabels(object) ## S4 method for signature 'tidLists' labels(object) Arguments x, object the object maxsum maximum numbers of itemsets shown in the summary ... further arguments value replacement value Details Transaction ID lists contains a set of lists. Each list is associated with an item/itemset and stores the IDs of the transactions which support the item/itemset. tidLists uses the class Matrix::ngCMatrix to efficiently store the transaction ID lists as a sparse matrix. Each column in the matrix represents one transaction ID list. tidLists can be used for different purposes. For some operations (e.g., support counting) it is efficient to coerce a transactions database into tidLists where each list contains the transaction IDs for an item (and the support is given by the length of the list). The implementation of the Eclat mining algorithm (which uses transaction ID list intersection) can also produce transaction ID lists for the found itemsets as part of the returned itemsets object. These lists can then be used for further computation. Functions • summary(tidLists): create a summary • dim(tidLists): get dimensions. The rows represent the itemsets and the columns are the transactions. • dimnames(tidLists): get dimnames • dimnames(x = tidLists) <- value: replace dimnames • length(tidLists): get the number of itemsets. • t(tidLists): this object is not transposable. t() results in an error. • transactionInfo(tidLists): get the transaction info data.frame • transactionInfo(tidLists) <- value: replace the the transaction info data.frame • itemInfo(tidLists): get the item info data.frame • itemInfo(tidLists) <- value: replace the item info data.frame • itemLabels(tidLists): get the item labels • labels(tidLists): convert the tid lists into a text representation. Slots data an object of class ngCMatrix from package Matrix. itemInfo a data.frame transactionInfo a data.frame Objects from the Class Objects are created • as part of the itemsets mined by eclat() with tidLists = TRUE in the ECparameter object. • by supportingTransactions(). • by coercion from an object of class transactions. • by calls of the form new("tidLists", ...). Coercions • as("tidLists", "list") • as("list", "tidLists") • as("tidLists", "ngCMatrix") • as("tidLists", "transactions") • as("transactions", "tidLists") • as("tidLists", "itemMatrix") • as("itemMatrix", "tidLists") Author(s) <NAME> See Also Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions() transactions-class, unique() Examples ## Create transaction data set. data <- list( c("a","b","c"), c("a","b"), c("a","b","d"), c("b","e"), c("b","c","e"), c("a","d","e"), c("a","c"), c("a","b","d"), c("c","e"), c("a","b","d","e") ) data <- as(data, "transactions") data ## convert transactions to transaction ID lists tl <- as(data, "tidLists") tl inspect(tl) dim(tl) dimnames(tl) ## inspect visually image(tl) ## mine itemsets with transaction ID lists f <- eclat(data, parameter = list(support = 0, tidLists = TRUE)) tl2 <- tidLists(f) inspect(tl2) transactions-class Class transactions — Binary Incidence Matrix for Transactions Description The transactions class is a subclass of itemMatrix and represents transaction data used for mining associations. Usage transactions( x, itemLabels = NULL, transactionInfo = NULL, format = "wide", cols = NULL ) ## S4 method for signature 'transactions' summary(object) ## S4 method for signature 'transactions' toLongFormat(from, cols = c("TID", "item"), decode = TRUE) ## S4 method for signature 'transactions' items(x) transactionInfo(x) ## S4 method for signature 'transactions' transactionInfo(x) transactionInfo(x) <- value ## S4 replacement method for signature 'transactions' transactionInfo(x) <- value ## S4 method for signature 'transactions' dimnames(x) ## S4 replacement method for signature 'transactions,list' dimnames(x) <- value Arguments x, object, from the object itemLabels a vector with labels for the items transactionInfo a transaction information data.frame with one row per transaction. format "wide" or "long" format? Format wide is a regular data.frame where each row contains an object. Format "long" is a data.frame with one column with transaction IDs and one with an item (see cols below). cols a numeric or character vector of length two giving the index or names of the columns (fields) with the transaction and item ids in the long format. decode translate item IDs to item labels? value replacement value Details Transactions store the presence of items in each individual transaction as binary matrix where rows represent the transactions and columns represent the items. transactions direct extends class itemMatrix to store the sparse binary incidence matrix, item labels, and optionally transaction IDs and user IDs. If you work with several transaction sets at the same time, then the encoding (order of the items in the binary matrix) in the different sets is important. See itemCoding to learn how to encode and recode transaction sets. Data Preparation Data typically starts as a data.frame or a matrix and needs to be prepared before it can be converted into transactions (see coercion methods in the Methods Section and the Example Section below for details on the needed format). Columns need to represent items which is different depending on the data type of the column: • Continuous variables: Continuous variables cannot directly be represented as items and need to be discretized first. An item resulting from discretization might be age>18 and the column contains only TRUE or FALSE. Alternatively, it can be a factor with levels age<=18, 50=>age>18 and age>50. These will be automatically converted into 3 items, one for each level. Discretiza- tion is described in functions discretize() and discretizeDF(). • Logical variables: A logical variable describing a person could be tall indicating if the person is tall using the values TRUE and FALSE. The fact that the person is tall would be encoded in the transaction containing the item tall while not tall persons would not have this item. Therefore, for logical variables, the TRUE value is converted into an item with the name of the variable and for the FALSE values no item is created. • Factors: Columns with nominal values (i.e., factor, ordered) are translated into a series of binary items (one for each level constructed as variable name = level). Items cannot represent order and this ordered factors lose the order information. Note that nominal variables need to be encoded as factors (and not characters or numbers). This can be done with data[,"a_nominal_var"] <- factor(data[,"a_nominal_var"]). Complete examples for how to prepare data can be found in the man pages for Income and Adult. Functions • summary(transactions): produce a summary • toLongFormat(transactions): convert the transactions to long format (a data.frame with two columns, tid and item). Column names can be specified as a character vector of length 2 called cols. • items(transactions): get the transactions as an itemMatrix • transactionInfo(transactions): get the transaction info data.frame • transactionInfo(transactions) <- value: replace the transaction info data.frame • dimnames(transactions): get the dimnames • dimnames(x = transactions) <- value: set the dimnames Slots Slots are inherited from itemMatrix. Objects from the Class Objects are created by: • coercion from objects of other classes. itemLabels and transactionInfo are by default created from information in x (e.g., from row and column names). • the constructor function transactions() • by calling new("transactions", ...). See Examples Section for creating transactions from data. Coercions • as("transactions", "matrix") • as("matrix", "transactions") • as("list", "transactions") • as("transactions", "list") • as("data.frame", "transactions") • as("transactions", "data.frame") • as("ngCMatrix", "transactions") Author(s) <NAME> See Also Superclass: itemMatrix Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions() tidLists-class, unique() Examples ## Example 1: creating transactions form a list (each element is a transaction) a_list <- list( c("a","b","c"), c("a","b"), c("a","b","d"), c("c","e"), c("a","b","d","e") ) ## Set transaction names names(a_list) <- paste("Tr", c(1:5), sep = "") a_list ## Use the constructor to create transactions ## Note: S4 coercion does the same trans1 <- as(a_list, "transactions") trans1 <- transactions(a_list) trans1 ## Analyze the transactions summary(trans1) image(trans1) ## Example 2: creating transactions from a 0-1 matrix with 5 transactions (rows) and ## 5 items (columns) a_matrix <- matrix( c(1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1), ncol = 5) ## Set item names (columns) and transaction labels (rows) colnames(a_matrix) <- c("a", "b", "c", "d", "e") rownames(a_matrix) <- paste("Tr", c(1:5), sep = "") a_matrix ## Create transactions trans2 <- transactions(a_matrix) trans2 inspect(trans2) ## Example 3: creating transactions from data.frame (wide format) a_df <- data.frame( age = as.factor(c( 6, 8, NA, 9, 16)), grade = as.factor(c("A", "C", "F", NA, "C")), pass = c(TRUE, TRUE, FALSE, TRUE, TRUE)) ## Note: factors are translated differently than logicals and NAs are ignored a_df ## Create transactions trans3 <- transactions(a_df) inspect(trans3) ## Note that coercing the transactions back to a data.frame does not recreate the ## original data.frame, but represents the transactions as sets of items as(trans3, "data.frame") ## Example 4: creating transactions from a data.frame with ## transaction IDs and items (long format) a_df3 <- data.frame( TID = c( 1, 1, 2, 2, 2, 3 ), item = c("a", "b", "a", "b", "c", "b") ) a_df3 trans4 <- transactions(a_df3, format = "long", cols = c("TID", "item")) trans4 inspect(trans4) ## convert transactions back into long format. toLongFormat(trans4) ## Example 5: create transactions from a dataset with numeric variables ## using discretization. data(iris) irisDisc <- discretizeDF(iris) head(irisDisc) trans5 <- transactions(irisDisc) trans5 inspect(head(trans5)) ## Note, creating transactions without discretizing numeric variables will apply the ## default discretization and also create a warning. ## Example 6: create transactions manually (with the same item coding as in trans5) trans6 <- transactions( list( c("Sepal.Length=[4.3,5.4)", "Species=setosa"), c("Sepal.Length=[4.3,5.4)", "Species=setosa") ), itemLabels = trans5) trans6 inspect(trans6) unique Remove Duplicated Elements from a Collection Description Provides the generic function unique() and the methods for itemMatrix transactions, and associa- tions. Usage unique(x, incomparables = FALSE, ...) ## S4 method for signature 'itemMatrix' unique(x, incomparables = FALSE) ## S4 method for signature 'associations' unique(x, incomparables = FALSE, ...) Arguments x an object of class itemMatrix or associations. incomparables currently unused. ... further arguments (currently unused). Details unique() uses duplicated() to return an object with the duplicate elements removed. Value An object of the same class as x with duplicated elements removed. Author(s) <NAME> See Also Other associations functions: abbreviate(), associations-class, c(), duplicated(), extract, inspect(), is.closed(), is.generator(), is.maximal(), is.redundant(), is.significant(), is.superset(), itemsets-class, match(), rules-class, sample(), sets, size(), sort() Other itemMatrix and transactions functions: abbreviate(), crossTable(), c(), duplicated(), extract, hierarchy, image(), inspect(), is.superset(), itemFrequencyPlot(), itemFrequency(), itemMatrix-class, match(), merge(), random.transactions(), sample(), sets, size(), supportingTransactions() tidLists-class, transactions-class Examples data("Adult") r1 <- apriori(Adult[1:1000], parameter = list(support = 0.5)) r2 <- apriori(Adult[1001:2000], parameter = list(support = 0.5)) ## Note that this produces a collection of rules from two sets r_comb <- c(r1, r2) r_comb <- unique(r_comb) r_comb weclat Mining Associations from Weighted Transaction Data with Eclat (WARM) Description Find frequent itemsets with the Eclat algorithm. This implementation uses optimized transaction ID list joins and transaction weights to implement weighted association rule mining (WARM). Usage weclat(data, parameter = NULL, control = NULL) Arguments data an object that can be coerced into an object of class transactions. parameter an object of class ASparameter (default values: support = 0.1, minlen = 1L, and maxlen = 5L) or a named list with corresponding components. control an object of class AScontrol (default values: verbose = TRUE) or a named list with corresponding components. Details Transaction weights are stored in the transactions as a column called weight in transactionInfo. The weighted support of an itemset is the sum of the weights of the transactions that contain the itemset. An itemset is frequent if its weighted support is equal or greater than the threshold specified by support (assuming that the weights sum to one). Note that Eclat only mines (weighted) frequent itemsets. Weighted association rules can be created using ruleInduction(). Value Returns an object of class itemsets. Note that weighted support is returned in quality as column support. Note The C code can be interrupted by CTRL-C. This is convenient but comes at the price that the code cannot clean up its internal memory. Author(s) <NAME> References <NAME>, <NAME>, and <NAME> (1998). Weighted Association Rules: Model and Algorithm, Proceedings of ACM SIGKDD. See Also Other mining algorithms: APappearance-class, AScontrol-classes, ASparameter-classes, apriori(), eclat(), fim4r(), ruleInduction() Other weighted association mining functions: SunBai, hits() Examples ## Example 1: SunBai data data(SunBai) SunBai ## weights are stored in transactionInfo transactionInfo(SunBai) ## mine weighted support itemsets using transaction support in SunBai s <- weclat(SunBai, parameter = list(support = 0.3), control = list(verbose = TRUE)) inspect(sort(s)) ## create rules using weighted support (satisfying a minimum ## weighted confidence of 90%). r <- ruleInduction(s, confidence = .9) inspect(r) ## Example 2: Find association rules in weighted data trans <- list( c("A", "B", "C", "D", "E"), c("C", "F", "G"), c("A", "B"), c("A"), c("C", "F", "G", "H"), c("A", "G", "H") ) weight <- c(5, 10, 6, 7, 5, 1) ## convert list to transactions trans <- transactions(trans) ## add weight information transactionInfo(trans) <- data.frame(weight = weight) inspect(trans) ## mine weighed support itemsets s <- weclat(trans, parameter = list(support = 0.3), control = list(verbose = TRUE)) inspect(sort(s)) ## create association rules r <- ruleInduction(s, confidence = .5) inspect(r) write Write Transactions or Associations to a File Description Provides the generic function write() and the methods to write transactions or associations to a file. Usage write(x, file = "", ...) ## S4 method for signature 'transactions' write( x, file = "", format = c("basket", "single"), sep = " ", quote = TRUE, ... ) ## S4 method for signature 'associations' write(x, file = "", sep = " ", quote = TRUE, ...) Arguments x the transactions or associations (rules, itemsets, etc.) object. file either a character string naming a file or a connection open for writing. ’""’ indicates output to the console. ... further arguments passed on to write.table(). Use fileEncoding to set the encoding used for writing the file. format format to write transactions. sep the field separator string. Values within each row of x are separated by this string. Use quote = TRUE and sep = "," for saving data as in csv format. quote a logical value. Quote fields? Details For associations (rules and itemsets) write() first uses coercion to data.frame to obtain a printable form of x and then uses utils::write.table() to write the data to disk. Transactions can be saved in basket (one line per transaction) or in single (one line per item) format. Note: To save and load associations in compact form, use save() and load() from the base pack- age. Alternatively, association can be written to disk in PMML (Predictive Model Markup Lan- guage) via write.PMML(). This requires package pmml. Author(s) <NAME> See Also Other import/export: DATAFRAME(), LIST(), pmml, read Examples data("Epub") ## write the formated transactions to screen (basket format) write(head(Epub)) ## write the formated transactions to screen (single format) write(head(Epub), format="single") ## write the formated result to file in CSV format write(Epub, file = "data.csv", format = "single", sep = ",") ## write rules in CSV format rules <- apriori(Epub, parameter=list(support = 0.0005, conf = 0.8)) write(rules, file = "data.csv", sep = ",") unlink("data.csv") # tidy up
dLagM
cran
R
Package ‘dLagM’ October 2, 2023 Type Package Title Time Series Regression Models with Distributed Lag Models Version 1.1.13 Date 2023-10-02 Author <NAME> [aut, cre, cph] (<https://orcid.org/0000-0002-8565-4710>) Maintainer <NAME> <<EMAIL>> Description Provides time series regression models with one predictor using finite dis- tributed lag models, polynomial (Almon) distributed lag models, geometric distributed lag mod- els with Koyck transformation, and autoregressive distributed lag models. It also con- sists of functions for computation of h-step ahead forecasts from these mod- els. See Demirhan (2020)(<doi:10.1371/journal.pone.0228812>) and Balt- agi (2011)(<doi:10.1007/978-3-642-20059-5>) for more information. Depends graphics, stats, nardl, dynlm, R (>= 3.6.0) Imports AER, formula.tools, plyr , lmtest, strucchange, wavethresh, MASS, roll, sandwich License GPL-3 RoxygenNote 7.2.3 NeedsCompilation no Repository CRAN Date/Publication 2023-10-02 06:30:02 UTC R topics documented: dLagM-packag... 2 ardlBoun... 3 ardlBoundOrder... 6 ardlDl... 7 dl... 9 finiteDLMaut... 13 forecas... 14 Go... 17 grainProductio... 19 koyckDl... 20 polyDl... 22 rolCorPlo... 23 sdPercentile... 25 seaLevelTempSO... 26 sortScor... 27 sunspotTem... 28 warmin... 29 whea... 29 dLagM-package Implementation of Time Series Regression Models with Distributed Lag Models Description Provides time series regression models with one predictor using finite distributed lag models, poly- nomial (Almon) distributed lag models, geometric distributed lag models with Koyck transforma- tion, and autoregressive distributed lag models. It also consists of functions for computation of h- step ahead forecasts from these models. See Demirhan (2020)(<doi:10.1371/journal.pone.0228812>) and Baltagi (2011)(<doi:10.1007/978-3-642-20059-5>) for more information. Details Package: dLagM Type: Package Version: 1.1.13 Date: 2023-10-02 License: GPL-3 To implement time series regression with finite distributed lag models, use dlm function. To implement time series regression with polynomial distributed lag models, use polyDlm function. To implement time series regression with geometric distributed lag models with Koyck transforma- tion, use koyckDlm function. To implement time series regression with autoregressive distributed lag models, use ardlDlm func- tion. To implement ARDL Bounds test, use ardlBound function. To produce forecasts for any of the models, use forecast function. To summarise the results of a model fitting, use summary function. Author(s) <NAME> (https://orcid.org/0000-0002-8565-4710) Maintainer: <NAME> <<EMAIL>> Acknowledgements: The author acknowledges the testing effort of of Dr. Rogerio Porto (https://orcid.org/0000- 0002-6663-9531) on forecasting function. References <NAME>. Econometrics, Fifth Ed. Springer, 2011. <NAME>. dLagM: An R package for distributed lag models and ARDL bounds testing. PLoS ONE, 15(2): e0228812, 2020. DOI: 10.1371/journal.pone.0228812. <NAME>, <NAME>, <NAME>. Undergraduate Econometrics. Wiley, 2000. <NAME>, <NAME>. "pss: Perform bounds test for cointegration and perform dynamic simula- tions." <NAME>. The Saving and Investment Nexus for China: Evidence from cointegration tests. Applied Economics 37(17):1979-1990, 2005. <NAME>, <NAME>, <NAME>. Bounds testing approaches to the analysis of level rela- tionships. Journal of Applied Econometrics 16(3):289-326, 2001. See Also dlm, polyDlm, koyckDlm, ardlDlm Examples # --- For examples, please refer to specific functions --- ardlBound Implement ARDL bounds test Description Applies ARDL bounds test with the approach of Pesaran et al. (2001). Usage ardlBound(data = NULL, formula = NULL, case = 3, p = NULL, remove = NULL, autoOrder = FALSE, HAC = FALSE, ic = c("AIC", "BIC", "MASE", "GMRAE"), max.p = 15, max.q = 15, ECM = TRUE, stability = TRUE) Arguments data A data.frame including all dependent and independent series. Column names this data.frame must match the variable names in formula. formula A formula object showing the dependent and independent series. case An integer up to 5 showing the case number. See details. p An integer representing the order of short-run response or a data.frame to spec- ify a different order of short-run response for each variable. remove A list showing the elements to be removed from the model. It includes elements p as a list and q as a vector. See details. autoOrder If TRUE, the order of ARDL will be found by the ardlBounOrders function. HAC If TRUE, the Newey-West estimate of variance-covariance function is used in testing. ic Information criterion to be used in the search for optimal orders. max.p Maximum order for the short-run coefficients. max.q Maximum auto-regressive order. ECM If TRUE, the error correction model corresponding to the case is also fitted and included in the outputs. stability If both ECM and stability are TRUE, the CUSUM, CUSUM of squares, and MOSUM charts are generated over recursive residuals using the package strucchange. Details The argument case takes the values 1 for "no intercept, no trend", 2 for "restricted intercept, no trend", 3 for "unrestricted intercept, no trend", 4 for "unrestricted intercept, restricted trend", and 5 for "unrestricted intercept, unrestricted trend." If the argument p is entered as an integer, the same value is used to specify the order of short-run response for all variables. We follow the formulation of Pesaran et al. (2001). So, the upper limit of summations in the model formulation goes up to (p-1). User should consider this while setting the value(s) of p. The names of the element p of remove must match with those in the model. For example, to remove lags 2 and 4 of the first differences of X1 and X2 and remove the lags 2 and 5 of the dependent series, remove should be defined as remove = list( p = list(dX1 = c(2,4), dX2 = c(2,4)), q = c(2,5) ). Breusch-Godfrey and Ljung-Box tests are applied to test against the existence of autocorrelations in residuals and Breusch-Pagan test is applied to detect heteroskedasticity in residuals as a part of the bounds testing procedure. Ramsey’s RESET test is conducted for correctness of functional form of the model. The recursive CUSUM chart is plotted by epf function from the strucchange package. The re- cursive CUSUM of squares plot is plotted by the ardlBound function using the recursive residuals generated by recresid function of strucchange package. The testing limits on the recursive CUSUM of squares plot are calculated as described by Brown et al. (1975) based in Table 1 of Durbin (1969). The recursive MOSUM chart is plotted when there is no NA MOSUM values are calculated. Value model An object including the fitted model under the null and alternative hypotheses. F.stat The value of F-statistic coming out of the Wald test. p p-orders in the lag structure. k The number of independent series. bg Breusch-Godfrey test results. Returns NULL if skipped. lb Ljung-Box test results. Returns NULL if skipped. bp Breusch-Pagan test results. Returns NULL if skipped. sp Shapiro-Wilk test results. Returns NULL if skipped. ECM A list including the error correction series in the element EC.t, the fitted error correction model in the element EC.model, and the coefficient of error correction part in the element EC.beta. ARDL.model A model object including the fitted ARDL model. Use this model object to display the long-run coefficients. To see the significance test results for the logn-run coefficients, use summary() function. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>> References <NAME>, <NAME>, <NAME>. Techniques for testing the constancy of regression relationships over time. Journal of the Royal Statistical Society - Series B, 37, 2, 149-192. <NAME>, <NAME>, <NAME>. MOSUM tests for parameter constancy. Biometrika, 82, 603-617, 1995. <NAME>. Tests for serial correlation in regression analysis based on the periodogram of Least- Squares residuals. Biometrika, 56, 1, 1-15. <NAME>. The Saving and Investment Nexus for China: Evidence from Cointegration Tests. Applied Economics 37(17):1979-1990, 2005. <NAME>, <NAME>, <NAME>. Bounds testing approaches to the analysis of level rela- tionships. Journal of Applied Econometrics 16(3):289-326, 2001. <NAME>. Tests for specification error in classical linear Least Squares regression analysis. Journal of the Royal Statistical Society - Series B, 31, 350-371, 1969. <NAME>, <NAME>. "pss: Perform bounds test for cointegration and perform dynamic simula- tions." <NAME>, <NAME>, <NAME>, <NAME>. strucchange: An R package for testing for structural change in linear regression models. Journal of Statistical Software, 7, 1-38, 2002. Examples ## Not run: data(M1Germany) data <- M1Germany[1:144,] model <- ardlBound(data = data , formula = logprice ~ interest + logm1 , case = 2 , p = 2) # Let ardlBoundOrders() function find the orders model <- ardlBound(data = data , formula = logprice ~ interest + logm1 , case = 2 , max.p = 3, max.q = 3) ## End(Not run) ardlBoundOrders Find optimal orders (lag structure) for ARDL bounds test Description Computes optimal orders (lag structure) for the short-run relationships and autoregressive part of the ARDL model prior to ARDL bounds test with the approach of Pesaran et al. (2001). Usage ardlBoundOrders(data = NULL , formula = NULL, ic = c("AIC", "BIC", "MASE", "GMRAE"), max.p = 15, max.q = 15, FullSearch = FALSE ) Arguments data A data.frame including all dependent and independent series. Column names this data.frame must match the variable names in formula. formula A formula object showing the dependent and independent series. ic Information criterion to be used in the serach for optimal orders. max.p Maximum order for the short-run coefficients. max.q Maximum auto-regressive order. FullSearch If TURE, a search over all possbilble models is implemented. See the details. Details If FullSearch = FALSE, this function first assumes that all p-orders are equal for the short-run relationships and finds the optimal p-order and autoregressive orders. Then, it finds the best subset of p-orders allowing them to change for each series in the short-run relationship part of the ARDL model under alternative hypothesis of ARDL bounds test. Value p An integer or data.frame object including p-orders for the short-run relation- ship part. q The autoregressive order. Stat.table The selected statistic of all the considered models where all short-run relation- ship orders (p-orders) are equal. Stat.p The selected statistic of all possible combinations of short-run relationship or- ders (p-orders). The reported lag structure is the one that gives the minimum value to the chosen statistic among these combinations. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>> ardlDlm Implement finite autoregressive distributed lag model Description Applies autoregressive distributed lag models of order (p , q) with one predictor. Usage ardlDlm(formula = NULL , data = NULL , x = NULL , y = NULL , p = 1 , q = 1 , remove = NULL , type = NULL ) Arguments formula A formula object for the model to be fitted. In the case of multiple predictor series, the model should be entered via a formula object. data A data.frame including all dependent and independent series. In the case of multiple predictor series, the data should be entered via the data argument. x A vector including the observations of predictor time series. This is not re- stricted to ts objects. y A vector including the observations of dependent time series. This is not re- stricted to ts objects. p An integer representing finite lag length. q An integer representing the order of autoregressive process. remove A list object having two elements showing the lags of independent series with p and the autoregressive lags with q to be removed from the full model for each independent series. Please see the details for the construction of this argument. type An integer taking 1 if only x and y vectors are entered, 2 if a formula and data matrix is entered. It can be left NULL since the correct value is checked and fixed by the code. Details The autoregressive DLM is a flexible and parsimonious infinite distributed lag model. The model ARDL(p, q) is written as Yt = µ + β0 Xt + β1 Xt−1 + · · · + βp Xt−p + γ1 Yt−1 + · · · + γq Yt−q + et . When there is only one predictor series, both of model and formula objects can be used. But when they are supplied, both x and y arguments should be NULL. The variable names in formula must match with the names of variables in data argument and it must be in the form of a generic formula for R functions. The argument data contains dependent series and independent series. The argument remove = list(p = list() , q = c()) is used to specify which lags of each inde- pendent series and the autoregressive lags of dependent series will be removed from the full model. Each element of the list p shows particular lags that will be removed from each independent series. To remove the main series from the model or to fit a model ARDL(0,q), include 0 within the ele- ments of p. The element q is just a vector showing the autoregressive lags of dependent series to be removed. To remove the intercept from the model, if a formula is entered, just include "-1" in the model formula. Otherwise, include "-1" in the element q of the list remove. See the examples below for implementation details. The standard function summary() prints model summary for the model of interest. Value model An object of class lm. See the details of lm function. order A vector composed of p and q orders. removed.p A list or vector showing the lags of independent series to be removed from the full model. removed.q A vector showing the autoregressive lags to be removed from the full model. formula Model formula of the fitted model. This is returned if multiple independent series are entered. data A data.frame including all dependent and independent series. This is returned if multiple independent series are entered. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>> References <NAME>. Econometrics, Fifth Ed. Springer, 2011. <NAME>, <NAME>, <NAME>. Undergraduate Econometrics. Wiley, 2000. Examples # Only one independent series data(seaLevelTempSOI) model.ardl = ardlDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, p = 1 , q = 1 ) summary(model.ardl) # residuals(model.ardl) # coef(model.ardl) # fitted(model.ardl) # Remove some lags rem.p = c(0,1) # 0 removes the main effect of X.t rem.q = c(1,3) remove = list(p = rem.p , q = rem.q) model.ardl = ardlDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, p = 2 , q = 3 , remove = remove) summary(model.ardl) # To remove intercept as well rem.q = c(1,3,-1) remove = list(p = rem.p , q = rem.q) model.ardl = ardlDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, p = 2 , q = 3 , remove = remove) summary(model.ardl) # Multiple independent series data(M1Germany) data = M1Germany[1:144,] model.ardlDlm = ardlDlm(formula = logprice ~ interest + logm1, data = data.frame(data) , p = 2 , q = 1 ) summary(model.ardlDlm) # To remove intercept as well model.ardlDlm = ardlDlm(formula = logprice ~ -1 + interest + logm1, data = data.frame(data) , p = 2 , q = 1 ) summary(model.ardlDlm) rem.p = list(interest = c(0,2) , logm1 = c(0)) # Remove the main series of interest and logm1 and the secont lag of # interest from the model rem.q = c(1) remove = list(p = rem.p , q = rem.q) remove model.ardlDlm = ardlDlm(formula = logprice ~ interest + logm1, data = data.frame(data) , p = 2 , q = 2 , remove = remove) summary(model.ardlDlm) dlm Implement finite distributed lag model Description Applies distributed lag models with one or multiple predictor(s). Usage dlm(formula , data , x , y , q , remove , type) Arguments formula A formula object for the model to be fitted. In the case of multiple predictor series, the model should be entered via a formula object. data A data.frame including all dependent and independent series. In the case of multiple predictor series, the data should be entered via the data argument. x A vector including the observations of predictor time series. This is not re- stricted to ts objects. If the series are supplied by data y A vector including the observations of dependent time series. This is not re- stricted to ts objects. q An integer representing finite lag length. remove A list object showing the lags to be removed from the model for each indepen- dent series in its elements. Please see the details for the construction of this argument. type An integer taking 1 if only x and y vectors are entered, 2 if a formula and data matrix is entered. It can be left NULL since the correct value is checked and fixed by the code. Details When a decision made on a variable, some of the related variables would be effected through time. For example, when income tax rate is increased, this would reduce expenditures of consumers on goods and services, which reduces profits of suppliers, which reduces the demand for productive inputs, which reduces the profits of the input suppliers, and so on (Judge and Griffiths, 2000). These effects occur over the future time periods; hence, they are distributed across the time. In a distributed-lag model, the effect of an independent variable X on a dependent variable Y occurs over the time. Therefore, DLMs are dynamic models. A linear finite DLM with one independent variable is written as follows: Xq Yt = α + βs Xt−s + t , where t is a stationary error term with E(t ) = 0, V ar(t ) = σ 2 , Cov(t , s ) = 0. When there is only one predictor series, both of model and formula objects can be used. But when they are supplied, both x and y arguments should be NULL. The variable names in formula must match with the names of variables in data argument and it must be in the form of a generic formula for R functions. The argument data contains dependent series and independent series. Required lags of dependent series are generated by the dlm function automatically. The argument remove = list() is used to specify which lags will be removed from the full model. Each element of the list remove shows particular lags that will be removed from each independent series. Notice that it is possible to fit a model with different lag lengths for each independent series by removing the appropriate lags of independent series with remove argument. To remove the main series from the model include 0 within the elements of remove. To remove the intercept from the model, if a formula is entered, just include "-1" in the model formula. Otherwise, include "-1" in the element remove of the list remove. See the examples below for implementation details. The standard function summary() prints model summary for the model of interest. Value model An object of class lm. designMatrix The design matrix composed of transformed z-variables. k The number of independent series. This is returned if multiple independent series are entered. q The lag length. removed A list or vector showing the removed lags from the model for independent series. Returns NULL if the fitted model is full. formula Model formula of the fitted model. This is returned if multiple independent series are entered. data A data.frame including all dependent and independent series. This is returned if multiple independent series are entered. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>> References <NAME>. Econometrics, Fifth Ed. Springer, 2011. <NAME>, <NAME>, <NAME>. Undergraduate Econometrics. Wiley, 2000. Examples # Only one independent series data(seaLevelTempSOI) model.dlm = dlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL , q = 5) summary(model.dlm) residuals(model.dlm) coef(model.dlm) fitted(model.dlm) removed = list(x = c(1)) model.dlm = dlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL , q = 5, remove = removed) summary(model.dlm) # Remove intercept as well removed = list(x = c(1,-1)) model.dlm = dlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL , q = 5, remove = removed) summary(model.dlm) removed = list(x = c(0,1)) model.dlm = dlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL , q = 5, remove = removed) summary(model.dlm) model.dlm = dlm(formula = GMSL ~ LandOcean , data = seaLevelTempSOI , q = 5) summary(model.dlm) removed = list(x = c(0,1)) model.dlm = dlm(formula = GMSL ~ LandOcean , data = seaLevelTempSOI , q = 5, remove = removed) summary(model.dlm) # Remove intercept as well removed = list(x = c(0,-1)) model.dlm = dlm(formula = GMSL ~ LandOcean , data = seaLevelTempSOI , q = 2, remove = removed) summary(model.dlm) # Multiple independent series data(M1Germany) data = M1Germany[1:144,] model.dlm = dlm(formula = logprice ~ interest + logm1, data = data.frame(data) , q = 4) summary(model.dlm) removed = list(interest = c(1,3), logm1 = c(2)) removed model.dlm = dlm(formula = logprice ~ interest + logm1, data = data.frame(data) , q = 4 , remove = removed) summary(model.dlm) removed = list(interest = c(0,1,3), logm1 = c(0,2)) removed model.dlm = dlm(formula = logprice ~ interest + logm1, data = data.frame(data) , q = 4 , remove = removed) summary(model.dlm) removed = list( logm1 = c(1,2)) removed model.dlm = dlm(formula = logprice ~ interest + logm1, data = data.frame(data) , q = 4 , remove = removed) summary(model.dlm) finiteDLMauto Find the optimal lag length for finite DLMs Description Fits finite DLMs for a range of lag lengths and orders the fitted models according to a desired measure. Usage finiteDLMauto(formula , data, x, y, q.min = 1, q.max = 10, k.order = NULL, model.type = c("dlm","poly"), error.type = c("MASE","AIC", "BIC","GMRAE", "MBRAE", "radj"), trace = FALSE , type) Arguments formula A formula object for the model to be fitted. In the case of multiple predictor series, the model should be entered via a formula object. data A data.frame including all dependent and independent series. In the case of multiple predictor series, the data should be entered via the data argument. x A vector including the observations of predictor time series. This is not re- stricted to ts objects. y A vector including the observations of dependent time series. This is not re- stricted to ts objects. q.min An integer representing the lower limit of the range of lag lengths to be consid- ered. If missing, it will be set to 1. q.max An integer representing the upper limit of the range of lag lengths to be consid- ered. If missing, it will be set to 10. k.order An integer representing order of polynomial distributed lags. model.type The type of model to be fitted. If set to dlm, finite distributed lag models are fitted. If set to poly, polynomial distributed lag models are fitted. error.type The type of goodness-of-fit measure to be used for the selection of optimal lag length. The optimal lag length is determined according to desired goodness-of- fit measure. trace If TRUE, prints all of the goodness-of-fit measures for all fitted models. type An integer taking 1 if only x and y vectors are entered, 2 if a formula and data matrix is entered. It can be left NULL since the correct value is checked and fixed by the code. Details When there is only one predictor series, both of model and formula objects can be used. But when they are supplied, both x and y arguments should be NULL. The variable names in formula must match with the names of variables in data argument and it must be in the form of a generic formula for R functions. The argument data contains dependent series and independent series. Required lags of dependent series are generated by the dlm function automatically. If q.max is entered greater than the length of the series, its value will be adjusted to have the length of the series for fitting the regression model. Value Returns a data.frame including the values of goodness-of-fit measures and corresponding lag lengths. Author(s) <NAME> <<EMAIL>>, <NAME> Maintainer: <NAME> <<EMAIL>> Examples ## Not run: library(dLagM) # Multiple independent series data(M1Germany) data = M1Germany[1:44,] # Run the search over finite DLMs according to AIC values finiteDLMauto(formula = logprice ~ interest + logm1, data = data.frame(data), q.min = 2, q.max = 5, model.type = "dlm", error.type = "AIC", trace = FALSE) ## End(Not run) forecast Compute forecasts for distributed lag models Description Computes forecasts for the finite distributed lag models, autoregressive distributed lag models, Koyck transformation of distributed lag models, and polynomial distributed lag models. Usage forecast(model , x , h = 1 , interval = FALSE, level = 0.95 , nSim = 500) Arguments model A fitted model by one of dlm(), koyckDlm(), ployDlm() or ardlDlm func- tions. x A vector or matrix including the new observations of independent time series. This is not restricted to ts objects. Please see the details for construction of this argument. h The number of ahead forecasts. interval If TRUE, (1 − α)% prediction intervals for forecasts are displayed along with forecasts. level Confidence level of prediction interval. nSim An integer showing the number of Monte Carlo simulations used to compute prediction intervals for forecasts. Details This function directly uses the model formula and estimates of model coefficients to find forecast one-by-one starting from the one-step ahead forecast. Prediction intervals are found by the Monte Carlo approach using a Gaussian error distribution with zero mean and empirical variance of the dependent series. When the model argument includes multiple independent series, x must be entered as a matrix including the new observations of each independent series in its rows. The number of columns of x must be equal to the forecast horizon h and the rows of x must match with the independent series in the order they appear in the data. When x and y are used to fit the model and some elements of the model are removed, you must use model and formula instead of x and y to fit the model and send the new data as a matrix into the forecast() function. This function can still be used when some of the lags of independent series are removed from the model. Value forecasts A vector including forecasts. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>> Examples ## Not run: # Only one independent series data(seaLevelTempSOI) #--- ARDL dlm --- model.ardl = ardlDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, p = 1 , q = 1 ) forecast(model = model.ardl , x = c(0.15, 0.45) , h = 2 , interval = FALSE) forecast(model = model.ardl , x = c(0.15, 0.45, 0.20) , h = 3 , interval = FALSE) # Multiple independent series data(M1Germany) data = M1Germany[1:144,] model.ardlDlm1 = ardlDlm(formula = logprice ~ interest + logm1, data = data.frame(data) , p = 2 , q = 1 ) x.new = matrix(c(0.07 , 9.06 , 0.071 , 9.09, 0.08, 9.2), ncol = 3, nrow = 2) forecast(model = model.ardlDlm1 , x = x.new , h = 3 , interval = TRUE, nSim = 100) rem.p = list(interest = c(1,2)) rem.q = c(1) remove = list(p = rem.p , q = rem.q) model.ardlDlm2 = ardlDlm(formula = logprice ~ interest + logm1, data = data.frame(data) , p = 2 , q = 2 , remove = remove) forecast(model = model.ardlDlm2 , x = x.new , h = 2 , interval = FALSE) #--- Finite dlm --- model.dlm = dlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, q = 2) forecast(model = model.dlm , x = c(0.15, 0.45, 0.20) , h = 3) # Multiple independent series model.dlm = dlm(formula = logprice ~ interest + logm1, data = data.frame(data) , q = 4) x.new = matrix(c(0.07 , 9.06 , 0.071 , 9.09), ncol = 2, nrow = 2) forecast(model = model.dlm , x = x.new , h = 2 , interval = FALSE) # Some lags are removed: # Remove lags 0 and 2 from "interest" and # lags 1 and 3 from "logm1" removed = list(interest = c(0,2), logm1 = c(1,3)) removed model.dlm = dlm(formula = logprice ~ interest + logm1 -1, data = data.frame(data) , q = 4 , remove = removed) x.new = matrix(c(0.07 , 9.06 , 0.071 , 9.09 , 0.079 , 9.19 , 0.069 , 9.21) , ncol = 4, nrow = 2) forecast(model = model.dlm , x = x.new , h = 4 , interval = FALSE) forecast(model = model.dlm , x = x.new , h = 4 , interval = FALSE) x.new = matrix(c(0.07 , 9.06 , 0.071 , 9.09, 0.08 , 9.12), ncol = 3, nrow = 2) forecast(model = model.dlm , x = x.new , h = 3, interval = FALSE) #--- Koyck dlm --- model.koyck = koyckDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL) forecast(model = model.koyck , x = c(0.15, 0.45, 0.20), h = 3 , interval = FALSE) #--- Polynomial dlm --- model.poly = polyDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, q = 2 , k = 2 , show.beta = TRUE) forecast(model = model.poly , x = c(0.15, 0.45) , h = 1 , interval = FALSE) ## End(Not run) GoF Compute goodness-of-fit measures for DLMs Description Computes mean absolute error (MAE), mean squared error (MSE), mean percentage error (MPE), symmetric mean absolute percentage error (sMAPE), mean absolute percentage error (MAPE), mean absolute scaled error (MASE), mean relative absolute error (MRAE), geometric mean rela- tive absolute error (GMRAE), mean bounded relative absolute error (MBRAE), unscaled MBRAE (UMBRAE) for distributed lag models. Usage GoF(model, ...) MASE(model, ...) sMAPE(model, ...) MAPE(model, ...) MRAE(model, ...) GMRAE(model, ...) MBRAE(model, ...) Arguments model Model object fitted for time series data. ... Optionally, more fitted models. Details See Chen et al. (2017) for the definitions of MSE, MAE, MAPE, sMAPE, MRAE, GMRAE, MBRAE, UMBMRAE. Let et = Yt − Ŷt be the one-step-ahead forecast error. Then, a scaled error is defined as et qt = 1 Pn , n−1 i=2 |Yi − Yi−1 | which is independent of the scale of the data. Mean absolute scaled error is defined as M ASE = mean(|qt |) (Hyndman and Koehler, 2006). Fitted models would be finite, polynomial, Koyck, ARDL DLMs, or linear model fitted with lm() function. This function also computes MASE values of multiple models when fed at the same time. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>> References <NAME>., <NAME>., <NAME>. (2017). A new accuracy measure based on bounded relative error for time series forecasting. PLoS ONE, 12(3), e0174202. <NAME>. and <NAME>. (2006). Another look at measures of forecast accuracy. Interna- tional Journal of Forecasting, 22, 679-688. Examples ## Not run: data(seaLevelTempSOI) # Fit a bunch of polynomial DLMs model.poly1 = polyDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, q = 2 , k = 2 , show.beta = TRUE) model.poly2 = polyDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, q = 3 , k = 2 , show.beta = TRUE) model.poly3 = polyDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, q = 4 , k = 2 , show.beta = TRUE) MASE(model.poly1, model.poly2, model.poly3) # Fit a bunch of finite DLMs model.dlm1 = dlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, q =2) model.dlm2 = dlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, q =3) model.dlm3 = dlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, q =4) MASE(model.dlm1, model.dlm2, model.dlm3) MBRAE(model.dlm1, model.dlm2, model.dlm3) GoF(model.dlm1, model.dlm2, model.dlm3) # Fit a linear model model.lm = lm(GMSL ~ LandOcean , data = seaLevelTempSOI) MASE(model.lm) GoF(model.lm) # Fit a Koyck model model.koyck = koyckDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL) MASE(model.koyck) GoF(model.koyck) # Fit a bunch of ARDLs model.ardl1 = ardlDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, p=1, q=2) model.ardl2 = ardlDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, p=2, q=2) model.ardl3 = ardlDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL, p=3, q=2) MASE(model.ardl1 , model.ardl2 , model.ardl3) GoF(model.ardl1 , model.ardl2 , model.ardl3) # Find MASEs of different model objects MASE(model.ardl1 , model.dlm1 , model.poly1, model.lm) GoF(model.ardl1 , model.dlm1 , model.poly1, model.lm) ## End(Not run) grainProduction World oats, corn, rice, wheat production, CO2 emissions, temperature anomalies, cropland data Description This data set is composed of annual world total CO2 emissions, oats, corn, rice, and wheat produc- tion, cropland area, and annual average temperature anomalies series between 1961 and 2018. Usage data(grainProduction) Format Multiple time series CO2(Tons) column shows the global mean annual carbon dioxide (CO2) emissions measured in tons. Land-OceanTempIndex(C) column shows the land-ocean temperature index without smoothing. Cropland(1Mha) column shows the annual cropland area in the world scale in million hectares. Oats(1Mt) column shows the annual world oats production in million tons. Corn(1Mt) column shows the annual world corn production in million tons. Rice(1Mt) column shows the annual world rice production in million tons. Wheat(1Mt) column shows the annual world wheat production in million tons. Source CO2 emissions data: Hannah Ritchie and <NAME> (2020) - "CO2 and Greenhouse Gas Emis- sions". Published online at OurWorldInData.org. Temperature anomalies data: NASA Grain production data: United States Department of Agriculture, Foreign Agricultural Service Cropland data: Food and Agriculture Organization of United Nations References CO2 emissions data: https://ourworldindata.org/co2-and-other-greenhouse-gas-emissions Temperature anomalies: https://climate.nasa.gov/vital-signs/global-temperature/ Grain production data: psd_grains_pulses.csv from https://apps.fas.usda.gov/psdonline/app/index.html#/app/downloads Cropland data: https://www.fao.org/faostat/en/#data/RL/visualize Examples data(grainProduction) oatsProduction.ts = ts(grainProduction[,5], start = 1961) plot(oatsProduction.ts, main="Time series plot of world oats production series.") koyckDlm Implement distributed lag models with Koyck transformation Description Applies distributed lag models with Koyck transformation with one predictor. Usage koyckDlm(x , y , intercept) Arguments x A vector including the observations of predictor time series. This is not re- stricted to ts objects. y A vector including the observations of dependent time series. This is not re- stricted to ts objects. intercept Set to TRUE to inclue intercept in the model. Details To deal with infinite DLMs, we can use the Koyck transformation. When we apply Koyck transfor- mation, we get the following: Yt − φYt−1 = α(1 − φ) + βXt + (t − φt−1 ). When we solve this equation for Yt , we obtain Koyck DLM as follows: Yt = δ1 + δ2 Yt−1 + δ3 Xt + νt , where δ1 = α(1 − φ), δ2 = φ, δ3 = β and the random error after the transformation is νt = (t − φt−1 ) (Judge and Griffiths, 2000). Then, instrumental variables estimation is employed to fit the model. The standard function summary() prints model summary for the model of interest. AIC/BIC of a fitted KOyck model is displayed by setting the class attribute of model to lm. See the example. Value model An object of class ivreg. See the details of ivreg function. geometric.coefficients A vector composed of corresponding geometric distributed lag model coeffi- cients. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>> References <NAME>. Econometrics, Fifth Ed. Springer, 2011. <NAME>, <NAME>, <NAME>. Undergraduate Econometrics. Wiley, 2000. Examples data(seaLevelTempSOI) model.koyck = koyckDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL) summary(model.koyck, diagnostics = TRUE) residuals(model.koyck) coef(model.koyck) fitted(model.koyck) AIC(model.koyck) BIC(model.koyck) polyDlm Implement finite polynomial distributed lag model Description Applies polynomial distributed lag models with one predictor. Usage polyDlm(x , y , q , k , show.beta = TRUE) Arguments x A vector including the observations of predictor time series. This is not re- stricted to ts objects. y A vector including the observations of dependent time series. This is not re- stricted to ts objects. q An integer representing finite lag length. k An integer representing order of polynomial distributed lags. show.beta If TRUE, generates original beta parameters and associated t-tests and prints the results. Details Finite distributed lag models, in general, suffer from the multicollinearity due to inclusion of the lags of the same variable in the model. To reduce the impact of this multicollinearity, a polynomial shape is imposed on the lag distribution (Judge and Griffiths, 2000). The resulting model is called Polynomial Distributed Lag model or Almond Distributed Lag Model. Imposing a polynomial pattern on the lag distribution is equivalent to representing β parameters with another $k$th order polynomial model of time. So, the effect of change in Xt−s on the ex- pected value of Yt is represented as follows: ∂E(Yt ) = βs = γ0 + γ1 s + γ2 s2 + · · · + γk sk ∂Xt−s where s = 0, . . . , q (Judge and Griffiths, 2000). Then the model becomes: Yt = α + γ0 Zt0 + γ1 Zt1 + γ2 Zt2 + · · · + γk Ztk + t . The standard function summary() prints model summary for the model of interest. Value model An object of class lm. designMatrix The design matrix composed of transformed z-variables. designMatrix.x The design matrix composed of original x-variables. beta.coefficients Estimates and t-tests of original beta coefficients. This will be generated if show.beta is set to TRUE. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>> References <NAME>. Econometrics, Fifth Ed. Springer, 2011. <NAME>, <NAME>, <NAME>. Undergraduate Econometrics. Wiley, 2000. Examples data(seaLevelTempSOI) model.poly = polyDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL , q = 4 , k = 2 , show.beta = TRUE) summary(model.poly) residuals(model.poly) coef(model.poly) fitted(model.poly) rolCorPlot PLot the rolling correlations Description Plots the rolling correlations along with other required statistics to visualise the approach of Ger- shunov et al. (2001) to test the significance of signal from rolling correlation analysis. Usage rolCorPlot(x , y , width, level = 0.95, main = NULL, SDtest = TRUE, N = 500) Arguments x A ts object. y A ts object. width A numeric vector of window lengths of the rolling correlation analysis. level Confidence level for intervals. main The main title of the plot. SDtest Set to TRUE to run test the significance of signal from rolling correlation analysis along with plotting. N An integer showing the number of series to be generated in Monte Carlo simu- lation. Value rolCor A matrix showing rolling correlations for each width on its columns. rolcCor.avr.filtered A vector showing average rolling correlations filtered by running median non- linear filter against outliers. rolcCor.avr.raw A vector showing unfiltered average rolling correlations. rolCor.sd A vector showing standard deviations of rolling correlations for each width. rawCor Pearson correlation between two series. sdPercentiles Percentiles of MC distribution of standard deviations of rolling correlations as the test limits. test A data frame showing the standard deviations of rolling correlations for each width along with level and (1-level) limits. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>> References <NAME>., <NAME>., <NAME>. (2001). Low-Frequency Modulation of the ENSO-Indian Monsoon Rainfall Relationship: Signal or Noise? Journal of Climate, 14, 2486 - 2492. Examples ## Not run: data(wheat) prod.ts <-ts(wheat[,5], start = 1960) CO2.ts <- ts(wheat[,2], start = 1960) rolCorPlot(x = prod.ts, y = CO2.ts , width = c(7, 11, 15), level = 0.95, N = 50) ## End(Not run) sdPercentiles Test the significance of signal from rolling correlation analysis Description Implements the approach of Gershunov et al. (2001) to test the significance of signal from rolling correlation analysis. Usage sdPercentiles(n = 150, cor = 0.5, width = 5, N = 500, percentiles = c(.05, .95)) Arguments n The length of the series in the rolling correlation analysis. cor The magnitude of raw correaltion betweeen two time series in the rolling corre- lation analysis. width Window length of the rolling correlation analysis. N Number of Monte Carlo replications for simulations. percentiles Percentiles to be reported for the Monte Carlo distribution of standard deviations of rolling correlations for the given window width. Details N samples of correlated white noise series are generated with a magnitude of cor; rolling corre- lations analysis is applied with the window length of width; Monte Carlo distribution of standard deviations of rolling correlations are generated; and desired percentiles of the MC distribution of standard deviations are reported (Gershunov et al. 2001). Value rollCorSd.limits Percentiles of MC distribution of standard deviations of rolling correlations as the test limits. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>> References <NAME>., <NAME>., <NAME>. (2001). Low-Frequency Modulation of the ENSO-Indian Monsoon Rainfall Relationship: Signal or Noise? Journal of Climate, 14, 2486 - 2492. Examples # sdPercentiles(n = 50, cor = 0.5, width = 5, N = 50, # percentiles = c(.025, .975)) seaLevelTempSOI Global mean sea level (GMSL), mean land and ocean temperature anomalies, and Southern Oscillation Index (SOI) data Description This data set is composed of monthly global mean sea level (compared to 1993-2008 average) series by CSIRO, land ocean temperature anomalies (1951-1980 as a baseline period) by GISS, NASA, and monthly Southern Oscillation Index (SOI) by Australian Government Bureau of Meteorology (BOM) between July 1885 and June 2013. GMSL and temperature anomalies series are smoothed and seasonally adjusted. Usage data(seaLevelTempSOI) Format Multiple time series Source Goddard Institute for Space Studies, NASA, US. Marine and Atmospheric Research, CSIRO, Aus- tralia. Australian Government Bureau of Meteorology (BOM). References Church, <NAME>. and <NAME> (2011), Sea-level rise from the late 19th to the early 21st Century. Surveys in Geophysics, doi:10.1007/s10712-011-9119-1. https://www.cmar.csiro.au/sealevel/sl_data_cmar.html https://data.giss.nasa.gov/gistemp/graphs_v4/ https://www.bom.gov.au/climate/current/soihtm1.shtml Examples data(seaLevelTempSOI) level.ts <- ts(seaLevelTempSOI[,1], start = c(1880,7), freq = 12) temp.ts <- ts(seaLevelTempSOI[,2], start = c(1880,7), freq = 12) plot(level.ts, main="Time series plot of GMSL series.") sortScore Sort AIC, BIC, MASE, MAPE, sMAPE, MRAE, GMRAE, or MBRAE scores Description Displays sorted AIC, BIC, and MASE scores. Usage sortScore(x, score = c("bic", "aic", "mase", "smape", "mape", "mrae", "gmrae", "mbrae")) Arguments x A vector of AIC, BIC, MASE, MAPE, sMAPE, MRAE, GMRAE, or MBRAE values. score The type of scores to be sorted. Details This function sorts the AIC, BIC, MASE, MAPE, sMAPE, MRAE, GMRAE, or MBRAE scores to display the smallest one at the top of a bunch of AIC, BIC, MASE, MAPE, sMAPE, MRAE, GMRAE, or MBRAE scores. Author(s) <NAME> Maintainer: <NAME> <<EMAIL>> Examples ## Not run: data(seaLevelTempSOI) model.poly1 = polyDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL , q = 2 , k = 2 , show.beta = TRUE) model.poly2 = polyDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL , q = 3 , k = 2 , show.beta = TRUE) model.poly3 = polyDlm(x = seaLevelTempSOI$LandOcean, y = seaLevelTempSOI$GMSL , q = 4 , k = 2 , show.beta = TRUE) aic = AIC(model.poly1$model, model.poly2$model, model.poly3$model) bic = BIC(model.poly1$model, model.poly2$model, model.poly3$model) mase = MASE(model.poly1$model, model.poly2$model, model.poly3$model) mbrae = MBRAE(model.poly1$model, model.poly2$model, model.poly3$model) sortScore(aic , score = "aic") sortScore(bic , score = "bic") sortScore(mase , score = "mase") sortScore(mbrae , score = "mbrae") ## End(Not run) sunspotTemp Sunspot numbers and mean temperature anomalies data Description This data set is composed of monthly mean global surface temperature series by GISS NASA and sunspot numbers recorded by SWPC Space Weather Operations (SWO) between January 1991 and November 2019. Usage data(sunspotTemp) Format Multiple time series Source Goddard Institute for Space Studies, NASA, US. Space Weather Prediction Center National Oceanic and Atmospheric Administration, US. References https://data.giss.nasa.gov/gistemp/graphs_v4/ ftp://ftp.swpc.noaa.gov/pub/weekly/RecentIndices.txt Examples data(sunspotTemp) sunspots.ts <- ts(sunspotTemp[,3], start = c(1991,1), freq = 12) temp.ts <- ts(sunspotTemp[,4], start = c(1991,1), freq = 12) plot(sunspots.ts, main="Time series plots of sunspot numbers series.") warming Global warming and vehicle production data Description This data set is composed of annual mean global warming series between 1997 and 2016 showing the change in global surface temperature relative to 1951-1980 average temperatures and the number of vehicles produced (in millions) within the same time span over the globe. Usage data(warming) Format Multiple time series Source Global Climate Center, NASA Organisation Internationale des Constructeurs d’Automobiles (OICA) References https://climate.nasa.gov/vital-signs/global-temperature/ https://www.oica.net/category/production-statistics/ Examples data(warming) vehicleWarming.ts = ts(warming[,2:3], start = 1997) plot(vehicleWarming.ts, main="Time series plots of global warming and the nuber of produced motor vehciles series.") wheat World wheat production, CO2 emissions, and temperature anomalies data Description This data set is composed of annual world total CO2 emissions, wheat production, harvested area, wheat production per hectare, and annual average temperature anomalies series between 1960 and 2017. Usage data(wheat) Format Multiple time series CO2..ppm. column shows the global mean annual concentration of carbon dioxide (CO2) measured in parts per million (ppm). CO2..tons column shows the global mean annual carbon dioxide (CO2) emissions measured in tons. HarvestedArea..million.ha. column shows the annual harvested area in the world scale in mil- lion hectare. Production..Mt. column shows the annual world wheat production in million tons. ProducationPerArea column shows the annual wheat production per hectare in tons. TempAnomaly..C.degrees. column shows the land-ocean temperature index without smoothing. Source Australian Government Department of Agriculture and Water Services, ABARES CO2 and other Greenhouse Gas Emissions by <NAME> and <NAME> References https://www.agriculture.gov.au/abares/research-topics/agricultural-commodities/agricultural-commodities- trade-data#australian-crop-report-data https://www.agriculture.gov.au/abares/research-topics/agricultural-outlook/data https://ourworldindata.org/co2-and-other-greenhouse-gas-emissions#annual-co2-emissions https://climate.nasa.gov/vital-signs/global-temperature/ Examples data(wheat) wheatProduction.ts = ts(wheat[,4], start = 1960) plot(wheatProduction.ts, main="Time series plot of world wheat production series.")
subniche
cran
R
Package ‘subniche’ October 14, 2022 Title Within Outlying Mean Indexes: Refining the OMI Analysis Version 1.5 Date 2022-07-14 BugReports https://github.com/KarasiewiczStephane/WitOMI/issues Description Complementary indexes calculation to the Outlying Mean Index analysis to ex- plore niche shift of a community and biological constraint within an Euclidean space, with graph- ical displays. For details see Karasiewicz et al. (2017) <doi:10.7717/Peerj.3364>. Suggests adegraphics, ape, CircStats, deldir, lattice, maptools, MASS, pixmap, spdep, splancs, waveslim Depends ade4, SIBER, polyclip, wordcloud License GPL (>= 2) RoxygenNote 7.2.0 NeedsCompilation no LazyData true Author <NAME> [aut, cre] (<https://orcid.org/0000-0003-1652-9921>) Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2022-07-15 12:50:02 UTC R topics documented: ardechein... 2 drom... 3 eigenba... 3 plot.subnich... 5 plot_dy... 8 plot_dym_s... 10 plot_N... 13 plot_NR_s... 15 sep.factor.ro... 17 subare... 18 subnich... 19 subplo... 22 subplot_... 25 subplot_s... 27 ardecheinv Temporal data Description The ardecheinv data are the temporal example used as an ecological application of the WitOMI calculations in Karasiewicz et al. (2017). Usage data(ardecheinv) Format The ardecheinv is a list of 3 components. env is a dataframe of 67 rows with 5 environmental tables, collected in spring and autumn. Invertebrates is a dataframe of 67 rows and 57 species of invertebrates. code is a dataframe with 57 rows and 2 columns, the species scientific name and their respective code. Source <NAME>. and <NAME>. (2004). Hydraulic requirements of stream communities: A case study on invertebrates. Freshwater Biology, 49(5), 600-613. doi:10.1111/j.13652427.2004.01214.x. References <NAME>.,<NAME>.and <NAME>. (2017). Within outlying mean indexes: refining the OMI analysis for the realized niche decomposition. PeerJ 5:e3364. doi:10.7717/peerj.3364. drome Spatial data Description The drome data are the spatial example used as an ecological application of the WitOMI calculations in Karasiewicz et al. (2017). Usage data(drome) Format The drome is a list of 3 components. env is a dataframe with 64 rows with 6 environmental tables, collected in 10 different rivers. fish is a dataframe with 64 rows and 13 columns (12 fish species, including young and older trouts). code is a dataframe with 13 rows and 2 columns, the species, common and scientific, name and their respective code. Source <NAME>., <NAME>. and <NAME>. (2000). Niche separation in community analysis: a new method. Ecology,81(10), 2914-1927.doi:10.2307/177351. References <NAME>.,<NAME>.and <NAME>. (2017). Within outlying mean indexes: refining the OMI analysis for the realized niche decomposition. PeerJ 5:e3364.doi:10.7717/peerj.3364. eigenbar The eigenvalue of the OMI analysis Description The function plot the eigenvalues of the OMI analysis Usage eigenbar( subnic, col.sel = "black", col.unsel = "grey", ylab = "Eigen values in %", names.arg = NULL, main = NA, ... ) Arguments subnic an object of class subniche. col.sel the color of the selected axes col.unsel the color of the other axes ylab label for y-axis, see title for more details. names.arg a vector of names to be plotted below each bar or group of bars. If this argument is omitted, then the names are taken from the names attribute of height if this is a vector, or the column names if it is a matrix. main a main title for the plot, see title for more details. ... further arguments passed to or from other methods see barplot Details The black bars represents the selected axes for the OMI analysis See doi:10.7717/peerj.3364 for more details on the subniche concept. Examples library(subniche) data(doubs) dudi1 <- dudi.pca(doubs$env, scale = TRUE, scan = FALSE, nf = 3) nic1 <- niche(dudi1, doubs$fish, scann = FALSE) # number of sites N <- dim(nic1$ls)[1] #Create a factor which defines the subsets fact <- factor(c(rep(1,N/2),rep(2,N/2))) # nic1 will be use as reference and fact will be use to define the subniches environment subnic1 <- subniche(nic1, fact) eigenbar(subnic1) plot.subniche Summarizes the results of the species subniche Description The function plot the resulting species subniche of the WitOMI calculation. Usage ## S3 method for class 'subniche' plot( x, xax = 1, yax = 2, ax.angle.arrow = 20, ax.col.arrow = "black", ax.length.arrow = 0.1, ax.lwd.arrow = 1, ax.leg.posi = "bottomleft", ax.leg.cex = 1.2, eig.col.chos = "black", eig.col.left = "gray", eig.leg.posi = "topright", eig.leg.cex = 1.2, su.leg.posi = "bottomleft", su.leg.cex = 1.2, col.axis = "azure3", lty.axis = 2, lwd.axis = 2, var.col.arrow = "black", var.length.arrow = 0.1, var.lwd.arrow = 1, var.angle.arrow = 20, var.leg.posi = "bottomleft", var.leg.cex = 1.2, fac.var.lab = 1.2, col.var = "black", col.su = "black", col.G_k = "red", nic.leg.posi = "bottomleft", nic.leg.cex = 1.2, sub.leg.cex = 1.2, sub.leg.posi = "bottomleft", pch.su = 16, cex.su = 1, border.E = "#92c5de", col.E = "#92c5de", lty.E = 1, border.K = "black", col.K = "#2c7fb8", lty.K = 1, show.lines = F, ... ) Arguments x an object of class subniche. xax column for abscissas. yax column for ordinate. ax.angle.arrow arrow angle head for plot labeled "Axes", see arrows for more details. ax.col.arrow arrow color for plot labeled "Axes", see arrows for more details. ax.length.arrow arrow head length for plot labeled "Axes", see arrows for more details. ax.lwd.arrow arrow width for plot labeled "Axes", see arrows for more details. ax.leg.posi legend position for plot labeled "Axes", see legend for more details. ax.leg.cex legend size label for plot labeled "Axes", see legend for more details. eig.col.chos bar color for the selected components for plot labeled "Eigenvalues". eig.col.left bar color for the component leftover for plot labeled "Eigenvalues". eig.leg.posi legend position for plot labeled "Eigenvalues", see legend for more details. eig.leg.cex legend size label for plot labeled "Eigenvalues"", see legend for more details. su.leg.posi legend position for plot labeled "SU", see legend for more details. su.leg.cex legend size label for plot labeled "SU", see legend for more details. col.axis axis color, see par for more details. lty.axis axis line type, see par for more details. lwd.axis axis width, see par for more details. var.col.arrow variables arrow color for plot labeled "Variables and Species", see arrows for more details. var.length.arrow variables arrow length of the edges of the arrow head (in inches). var.lwd.arrow variables arrow width for plot labeled "Variables and Species", see arrows for more details. var.angle.arrow variables arrow angle head for plot labeled "Variables and Species", see arrows for more details. var.leg.posi legend position for plot labeled "Variables and Species", see legend for more details. var.leg.cex legend size label for plot labeled "Variables and Species", see legend for more details. fac.var.lab factor for moving the variable labels from its original coordinates for clarity, by defaults they are multiply 1.2 col.var color variables labels, see textplot for more details. col.su color of sampling units, see points for more details. col.G_k color label G_k, see textplot for more details. nic.leg.posi legend position for plot labeled "Niches", see legend for more details. nic.leg.cex legend size label for plot labeled "Niches", see legend for more details. sub.leg.cex legend size label for plot labeled "Subsets"", see legend for more details. sub.leg.posi legend position for plot labeled "Subsets", see legend for more details. pch.su type of the points representing the sampling units (SU), see points for more details. cex.su size of the points representing the sampling units (SU), see points for more de- tails. border.E color border of E polygon, see polygon for more details. col.E inside color of E polygon, see polygon for more details. lty.E line type for the E border, see polygon for more details. border.K color border of K polygon, see polygon for more details. col.K inside color of K polygon, see polygon for more details. lty.K line type for the K border, see polygon for more details. show.lines if true, then lines are plotted between x,y and the word, for those words not covering their x,y coordinates. See textplot for more details. ... further arguments passed to or from other methods. Details The function illustrate the results of subniche calculation with a great deal of customization param- eters. Examples library(subniche) data(doubs) dudi1 <- dudi.pca(doubs$env, scale = TRUE, scan = FALSE, nf = 3) nic1 <- niche(dudi1, doubs$fish, scann = FALSE) # number of sites N <- dim(nic1$ls)[1] #Create a factor which defines the subsets fact <- factor(c(rep(1,N/2),rep(2,N/2))) # nic1 will be use as reference and fact will be use to define the subniches environment subnic1 <- subniche(nic1, fact) plot(subnic1) plot_dym Communities subniches dynamic Description The function represents the species’ subniches SR position within the environmental space E. Usage plot_dym( subnic, sig = NULL, sig_thres = 0.05, xlab = NULL, ylab = NULL, main = NA, col.axis = "azure3", lty.axis = 2, lwd.axis = 2, border.E = "black", col.E = "#92c5de", lty.E = 1, lwd.E = 1, pch.SR.pos = 21, cex.SR.pos = 1, col.SR.pos = "#ffa600", col.SR.pt = "black", col.SR.lab = "black", cex.SR.lab = NA, fac.SR.lab = 1.2, col.arrow = "black", angle.arrow = 20, lwd.arrow = 2, length.arrow = 0.1, font.sp = 2, leg = T, posi.leg = "topleft", bty.leg = "n", ... ) Arguments subnic an object of class subniche. sig a factor defining the significance species, default NULL. sig_thres value for minimum significance, default 0.05 xlab label for x-axis, see title for more details. ylab label for y-axis, see title for more details. main a main title for the plot, see title for more details. col.axis axis color, see par for more details. lty.axis axis line type, see par for more details. lwd.axis axis width, see par for more details. border.E color border of E polygon, see polygon for more details. col.E inside color of E polygon, see polygon for more details. lty.E line type for the E border, see polygon for more details. lwd.E line width for the E border, see polygon for more details. pch.SR.pos type of points representing the SR position, see points for more details. cex.SR.pos size of points representing the SR position, see points for more details. col.SR.pos color of points representing the SR position, see points for more details. col.SR.pt point color contour if pch=21:25. col.SR.lab color of the species labels, see see text for more details. cex.SR.lab size of the species labels defautls NA for no labels, see see text for more details. fac.SR.lab factor for moving the SR labels from its original coordinates for clarity, by de- faults they are multiply 1.2 col.arrow arrow color, see arrows for more details. angle.arrow arrow angle head, see arrows for more details. lwd.arrow arrow width, see arrows for more details. length.arrow arrow head length, see arrows for more details. font.sp An integer which specifies which font to use for species label. 1 corresponds to plain text (the default), 2 to bold face, 3 to italic and 4 to bold italic, see par for more details. leg a logical option for legend to be plotted or not, default leg=T. posi.leg setting legend positions with the following keywords "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right" and "center", see legend for more details. bty.leg the type of box to be drawn around the legend. The allowed values are "o" (the default) and "n", see legend for more details. ... further arguments passed to or from other methods. Details The convex hulls measured is E is the environmental space. The arrows represent the species’ sub- niche marginality from the origin G. See doi:10.7717/peerj.3364 for more details on the subniche concept. Examples library(subniche) data(doubs) dudi1 <- dudi.pca(doubs$env, scale = TRUE, scan = FALSE, nf = 3) nic1 <- niche(dudi1, doubs$fish, scann = FALSE) # number of sites N <- dim(nic1$ls)[1] #Create a factor which defines the subsets fact <- factor(c(rep(1,N/2),rep(2,N/2))) # nic1 will be use as reference and fact will be use to define the subniches environment subnic1 <- subniche(nic1, fact) sigg <- rtestrefor(subnic1,10) sig = c(sigg$`1`$witomigtest$subni.pvalue[-28],sigg$`2`$witomigtest$subni.pvalue[-28]) plot_dym(subnic1, sig=sig, sig_thres= 0.1) plot_dym_sp Species subniches dynamic Description The function represents the species’ subniches SR within its realized niche NR. Usage plot_dym_sp( subnic, sp, xlab = NULL, ylab = NULL, main = NA, col.axis = "azure3", lty.axis = 2, lwd.axis = 2, border.E = "black", col.E = "#92c5de", lty.E = 1, lwd.E = 1, col.NR = "#fdb462", border.NR = "black", lty.NR = 1, lwd.NR = 1, col.NR.lab = "black", cex.NR.lab = 0.7, pch.NR.pos = 21, col.NR.pos = "black", col.NR.pt = "black", cex.NR.pos = 1, border.SR = "black", col.SR = "#a1d99b", lty.SR = 1, lwd.SR = 1, col.SR.lab = "black", cex.SR.lab = 0.7, fac.SR.lab = 1.2, pch.SR.pos = 21, col.SR.pos = "#ffa600", col.SR.pt = "black", cex.SR.pos = 1, col.arrow = "black", angle.arrow = 20, lwd.arrow = 2, length.arrow = 0.1, font.sp = 2, leg = T, posi.leg = "topleft", bty.leg = "n", ... ) Arguments subnic an object of class subniche. sp a character string of the species name. xlab label for x-axis, see title for more details. ylab label for y-axis, see title for more details. main a main title for the plot, see title for more details. col.axis axis color, see par for more details. lty.axis axis line type, see par for more details. lwd.axis axis width, see par for more details. border.E color border of E polygon, see polygon for more details. col.E inside color of E polygon, see polygon for more details. lty.E line type for the E border, see polygon for more details. lwd.E line width for the E border, see polygon for more details. col.NR inside color of NR polygon, see polygon for more details. border.NR color border of NR polygon, see polygon for more details. lty.NR line type for the NR border, see polygon for more details. lwd.NR line width for the NR border, see polygon for more details. col.NR.lab color of the species label representing the NR position, see textplot for more details. cex.NR.lab size of the species label representing the NR position, see textplot for more details. pch.NR.pos the type of points representing the NR position, see points for more details. col.NR.pos the color of points representing the NR position, see points for more details. col.NR.pt point color contour if pch=21:25. cex.NR.pos size of points representing the SR position, see points for more details. border.SR color border of SR polygon, see polygon for more details. col.SR inside color of SR polygon, see polygon for more details. lty.SR line type for the SR border, see polygon for more details. lwd.SR line width for the SR border, see polygon for more details. col.SR.lab color of the species label representing the SR position, see text for more details. cex.SR.lab size of the species label representing the SR position, see text for more details. fac.SR.lab factor for moving the SR labels from its original coordinates for clarity, by de- faults they are multiply 1.2 pch.SR.pos type of points representing the SR position, see points for more details. col.SR.pos color of points representing the SR position, see points for more details. col.SR.pt point color contour if pch=21:25. cex.SR.pos size of points representing the SR position, see points for more details. col.arrow arrow color, see arrows for more details. angle.arrow arrow angle head, see arrows for more details. lwd.arrow arrow width, see arrows for more details. length.arrow arrow head length, see arrows for more details. font.sp An integer which specifies which font to use for species label. 1 corresponds to plain text (the default), 2 to bold face, 3 to italic and 4 to bold italic, see par for more details. leg a logical option for legend to be plotted or not, default leg=T. posi.leg setting legend positions with the following keywords "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right" and "center", see legend for more details. bty.leg the type of box to be drawn around the legend. The allowed values are "o" (the default) and "n", see legend for more details. ... further arguments passed to or from other methods. Details The convex hulls measured are : 1. E is the environmental space. 2. NR the realized subniche. 3. SR the species realized subniche. The arrows represent the species’ subniche marginality from the origin G. See doi:10.7717/peerj.3364 for more details on the subniche concept. Examples library(subniche) data(doubs) dudi1 <- dudi.pca(doubs$env, scale = TRUE, scan = FALSE, nf = 3) nic1 <- niche(dudi1, doubs$fish, scann = FALSE) # number of sites N <- dim(nic1$ls)[1] #Create a factor which defines the subsets fact <- factor(c(rep(1,N/2),rep(2,N/2))) # nic1 will be use as reference and fact will be use to define the subniches environment subnic1 <- subniche(nic1, fact) plot_dym_sp(subnic1, "Neba") plot_NR Community niche distribution Description The function represents the species’ niche NR position within the environmental space E. Usage plot_NR( subnic, sig = NULL, sig_thres = 0.05, xlab = NULL, ylab = NULL, main = NA, col.axis = "azure3", lty.axis = 2, lwd.axis = 2, border.E = "black", col.E = "#92c5de", lty.E = 1, lwd.E = 1, pch.NR.pos = 21, cex.NR.pos = 1, col.NR.pos = "#a1d99b", col.NR.pt = "black", col.NR.lab = "black", cex.NR.lab = NA, fac.NR.lab = 1.2, col.arrow = "black", angle.arrow = 20, lwd.arrow = 2, length.arrow = 0.1, font.sp = 2, leg = T, posi.leg = "topleft", bty.leg = "n", ... ) Arguments subnic an object of class subniche. sig a factor defining the significance species, default NULL. sig_thres value for minimum significance, default 0.05 xlab label for x-axis, see title for more details. ylab label for y-axis, see title for more details. main a main title for the plot, see title for more details. col.axis axis color, see par for more details. lty.axis axis line type, see par for more details. lwd.axis axis width, see par for more details. border.E color border of E polygon, see polygon for more details. col.E inside color of E polygon, see polygon for more details. lty.E line type for the E border, see polygon for more details. lwd.E line width for the E border, see polygon for more details. pch.NR.pos type of points representing the NR position, see points for more details. cex.NR.pos size of points representing the NR position, see points for more details. col.NR.pos color of points representing the NR position, see points for more details. col.NR.pt point color contour if pch=21:25. col.NR.lab color of the species labels, see see text for more details. cex.NR.lab size of the species labels defautls NA for no labels, see see text for more details. fac.NR.lab factor for moving the NR labels from its original coordinates for clarity, by defaults they are multiply 1.2 col.arrow arrow color, see arrows for more details. angle.arrow arrow angle head, see arrows for more details. lwd.arrow arrow width, see arrows for more details. length.arrow arrow head length, see arrows for more details. font.sp An integer which specifies which font to use for species label. 1 corresponds to plain text (the default), 2 to bold face, 3 to italic and 4 to bold italic, see par for more details. leg a logical option for legend to be plotted or not, default leg=T. posi.leg setting legend positions with the following keywords "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right" and "center", see legend for more details. bty.leg the type of box to be drawn around the legend. The allowed values are "o" (the default) and "n", see legend for more details. ... further arguments passed to or from other methods. Details The convex hulls measured is E is the environmental space. The arrows represent the species’ NR marginality from the origin G. See doi:10.7717/peerj.3364 for more details on the subniche concept. Examples library(subniche) data(doubs) dudi1 <- dudi.pca(doubs$env, scale = TRUE, scan = FALSE, nf = 3) nic1 <- niche(dudi1, doubs$fish, scann = FALSE) # number of sites N <- dim(nic1$ls)[1] #Create a factor which defines the subsets fact <- factor(c(rep(1,N/2),rep(2,N/2))) # nic1 will be use as reference and fact will be use to define the subniches environment subnic1 <- subniche(nic1, fact) sigi <- rtest(nic1,10) M <- length(sigi$pvalue) plot_NR(subnic1, sig=sigi$pvalue[-M], sig_thres= 0.1) plot_NR_sp Species niche Description The function represents the species’ niche NR within the environmental space E. Usage plot_NR_sp( subnic, sp, xlab = NULL, ylab = NULL, main = NA, col.axis = "azure3", lty.axis = 2, lwd.axis = 2, border.E = "black", col.E = "#92c5de", lty.E = 1, lwd.E = 1, border.NR = "black", col.NR = "#fdb462", lty.NR = 1, lwd.NR = 1, pch.NR.pos = 21, cex.NR.pos = 1, col.NR.pos = "#a1d99b", col.NR.pt = "black", col.NR.lab = "black", cex.NR.lab = NA, fac.NR.lab = 1.2, col.arrow = "black", angle.arrow = 20, lwd.arrow = 2, length.arrow = 0.1, font.sp = 2, leg = T, posi.leg = "topleft", bty.leg = "n", ... ) Arguments subnic an object of class subniche. sp a character string of the species name, default rownames(subnic$li) xlab label for x-axis, see title for more details. ylab label for y-axis, see title for more details. main a main title for the plot, see title for more details. col.axis axis color, see par for more details. lty.axis axis line type, see par for more details. lwd.axis axis width, see par for more details. border.E color border of E polygon, see polygon for more details. col.E inside color of E polygon, see polygon for more details. lty.E line type for the E border, see polygon for more details. lwd.E line width for the E border, see polygon for more details. border.NR color border of NR polygon, see polygon for more details. col.NR inside color of NR polygon, see polygon for more details. lty.NR line type for the NR border, see polygon for more details. lwd.NR line width for the NR border, see polygon for more details. pch.NR.pos type of points representing the NR position, see points for more details. cex.NR.pos size of points representing the NR position, see points for more details. col.NR.pos color of points representing the NR position, see points for more details. col.NR.pt point color contour if pch=21:25. col.NR.lab color of the species labels, see see text for more details. cex.NR.lab size of the species labels defaults NA for no labels, see see text for more details. fac.NR.lab factor for moving the NR labels from its original coordinates for clarity, by defaults they are multiply 1.2 col.arrow arrow color, see arrows for more details. angle.arrow arrow angle head, see arrows for more details. lwd.arrow arrow width, see arrows for more details. length.arrow arrow head length, see arrows for more details. font.sp An integer which specifies which font to use for species label. 1 corresponds to plain text (the default), 2 to bold face, 3 to italic and 4 to bold italic, see par for more details. leg a logical option for legend to be plotted or not, default leg=T. posi.leg setting legend positions with the following keywords "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right" and "center", see legend for more details. bty.leg the type of box to be drawn around the legend. The allowed values are "o" (the default) and "n", see legend for more details. ... further arguments passed to or from other methods. Details The convex hulls measured is E is the environmental space. The arrows represent the species’ NR marginality from the origin G. See doi:10.7717/peerj.3364 for more details on the subniche concept. Examples library(subniche) data(doubs) dudi1 <- dudi.pca(doubs$env, scale = TRUE, scan = FALSE, nf = 3) nic1 <- niche(dudi1, doubs$fish, scann = FALSE) # number of sites N <- dim(nic1$ls)[1] #Create a factor which defines the subsets fact <- factor(c(rep(1,N/2),rep(2,N/2))) # nic1 will be use as reference and fact will be use to define the subniches environment subnic1 <- subniche(nic1, fact) plot_NR_sp(subnic1, "Neba") sep.factor.row A function to seperate a matrix, by row, into submatrices. Description separate matrix by rows into submatrices Usage sep.factor.row (x,factor) Arguments x a matrix. factor a factor of the same length as the number of row in the matrix. Value list of submatrices subarea Convex hull decomposition Description The function is used to calculate the coordinates and area of each convex hull from E environmental space to SR subniche. Usage subarea(subnic) Arguments subnic an object of class subniche. Details The convex hulls measured are : 1. E is the environmental space. 2. K the sub-environmental space. 3. NR the realized subniche. 4. SP the existing fundamental subniche. 5. SB the area of the biological constraint reducing SP. 6. SR the species realized subniche. See doi:10.7717/peerj.3364 for more details on the subniche concept. Value A list containing the coordinates and area of each convex hulls References <NAME>.,<NAME>.and <NAME>. (2017). Within outlying mean indexes: refining the OMI analysis for the realized niche decomposition. PeerJ 5:e3364. doi:10.7717/peerj.3364. Examples library(subniche) data(doubs) dudi1 <- dudi.pca(doubs$env, scale = TRUE, scan = FALSE, nf = 3) nic1 <- niche(dudi1, doubs$fish, scann = FALSE) # number of sites N <- dim(nic1$ls)[1] #Create a factor which defines the subsets fact <- factor(c(rep(1,N/2),rep(2,N/2))) # nic1 will be use as reference and fact will be use to define the subniches environment subnic1 <- subniche(nic1, fact) area_sub <- subarea(subnic1) subniche The Within Outlying Mean Indexes calculation Description The indexes allows to divide the niche, estimated from the niche function in the ade4 package into subniches defined by a factor, which creates the subsets. See details for more information. Usage subniche(nic, factor) ## S3 method for class 'subkrandtest' print(x, ...) ## S3 method for class 'subnikrandtest' print(x, ...) ## S3 method for class 'subniche' print(x, ...) ## S3 method for class 'subniche' summary(object, ...) refparam(x) ## S3 method for class 'subniche' rtest(xtest, nrepet = 99, ...) subparam.refor(x) rtestrefor(x, nrepet) subparam.subor(x) rtestsubor(x, nrepet) subkrandtest( sim, obs, alter = "greater", call = match.call(), names = colnames(sim), p.adjust.method = "none" ) subnikrandtest( sim, obs, alter = "greater", subpvalue, call = match.call(), names = colnames(sim), p.adjust.method = "none" ) Arguments nic an object of class niche. factor a factor which will defined the subsets within which the subniches will be cal- culated (the same length of the number of sites) x an object of class subniche. ... further arguments passed to or from other methods object an object of class subniche. xtest an object of class subniche. nrepet the number of permutations for the testing procedure sim a numeric vector of simulated values obs a numeric vector of an observed value alter a character string specifying the alternative hypothesis, must be one of "greater" (default), "less" or "two-sided".he length must be equal to the length of the vec- tor obs, values are recycled if shorter. call a call order names a vector of names for tests p.adjust.method a string indicating a method for multiple adjustment, see p.adjust.methods for possible choices. subpvalue the subset pvalue resulting from subkrandtest function Details The Within Outlying Mean Index analysis is a statistical exploratory niche analysis which pro- vides observation of niche shift and/or conservatism, of an entire community,at different subcales (temporal ,spatial and/or finer biological organisation level), and comparable under the same envi- ronmental gradients. This hindcasting multivariate analysis is based on the OMI analysis (Doledec et al. 2000) which is used as reference. The niches refinement is inspired by the K-select (Calenge et al. 2005) which emphasizes the limiting factors in habitat use in design II and III (Thomas and Taylor, 1990).The different estimations should help understand: 1. the environmental factors defining a species’ reference niche, under on the full scale, within a community. 2. the environmental factors defining a species’ subniches, under each subsets, within a community. The subniches parameters can be calculated from both the reference origin,G, which corresponds to the reference plan origin, and from G_k, which corresponds to the suborigins. G is the graphical representation of the mean environmental conditions encountered over the full scale of the data. G_k is the mean environmental conditions encountered at a subset defined by the factor. They are complementary has you can compare: 1. a single species’ subniches to G. 2. the community’ subniches to G_k at a specific subset. The subniches of a single species can only be compared to G as it is the common origin to all subsets. Whereas G_k is only common to the species found within the subset. So comparing different subniches of one species, found within different subsets, is only relevant to G. The community’s subniches can be compared to both G and G_k, but G, being the mean environmental conditions found within the full scale, will not express the specificity of the environmental conditions that the species encountered at the subset. G_k, being the mean environmental conditions of the subset, will reflect the atypical value of the environmental condition, making the comparison of the community’s subniches parameters more relevant. More information on the ecological concept can be found in Karasiewicz et al. 2017. For more details description on the package use:https://github.com/KarasiewiczStephane/ WitOMI. Value Adds items in the niche list and changing the class into subniche containing: factor the factor use to divide the environmental and species matrix into submatrices. G_k a dataframe with the sub-origins, G_k. sub a dataframe with the species subniche coordinates Author(s) <NAME>, <<EMAIL>> References <NAME>.,<NAME>.and <NAME>. (2017). Within outlying mean indexes: refining the OMI analysis for the realized niche decomposition. PeerJ 5:e3364. doi:10.7717/peerj.3364. <NAME>., <NAME>. and <NAME>. (2005). K-select analysis: a new method to analyze habitat selection in radio-tracking studies. Ecological modelling, 186, 143-153. doi:10.1016/ j.ecolmodel.2004.12.005. <NAME>., <NAME>. and <NAME>. (2000). Niche separation in community analysis: a new method. Ecology,81, 2914-1927. doi:10.2307/177351 <NAME>., <NAME>. (1990). Study Designs and Tests for Comparing Resource Use and Availability II. Natl. Widl. 54(2), 322-330. See Also niche niche.param Examples library(subniche) data(doubs) dudi1 <- dudi.pca(doubs$env, scale = TRUE, scan = FALSE, nf = 3) nic1 <- niche(dudi1, doubs$fish, scann = FALSE) # number of sites N <- dim(nic1$ls)[1] #Create a factor which defines the subsets fact <- factor(c(rep(1,N/2),rep(2,N/2))) # nic1 will be use as reference and fact will be use to define the subniches environment subnic1 <- subniche(nic1, fact) # the following two functions do the same display, plot.refniche is adapted to subniche objects plot(nic1) plot(subnic1) #Display the marginality vector of the suborigins and the species subniche #Display the subset's polygon, found within the overall environment's chull, #and the corresponding species positions subplot(subnic1) # The following two functions do the same display, refparam is adapted to subniche objects niche.param(nic1) refparam(subnic1) # The following two functions do the same display, rtest is adapted to subniche objects rtest(nic1,10) rtest(subnic1,10) #Calculates the subniches' parameters from G with the corresponding rtest subparam.refor(subnic1) rtestrefor(subnic1,10) #Calculates the subniches' parameters from G_k with the corresponding rtest subparam.subor(subnic1) rtestsubor(subnic1,10) subplot Sub-community plot under each sub-environmental space K Description The function to represent the community subniche position under each subenvironment K with their respective marginality from Gk. Usage subplot( subnic, main = NULL, sig = NULL, sig_thres = 0.05, xlab = NULL, ylab = NULL, col.axis = "azure3", lty.axis = 2, lwd.axis = 2, pch.SR.pos = 21, cex.SR.pos = 1, col.SR.pt = "black", col.SR.pos = "#ffa600", col.SR.lab = "black", cex.SR.lab = NA, fac.SR.lab = 1.2, border.E = "black", col.E = "#92c5de", lty.E = 1, lwd.E = 1, border.K = "black", col.K = "#2c7fb8", lty.K = 1, lwd.K = 1, col.arrow = "black", angle.arrow = 20, lwd.arrow = 2, length.arrow = 0.1, col.Gk.pos = "red", col.Gk.pt = "black", cex.Gk.pos = 1, pch.Gk.pos = 21, col.su = "#b35806", pt.su = "black", cex.su = 0.7, pch.su = 1, font.sp = 2, leg = T, posi.leg = "topleft", bty.leg = "n", ... ) Arguments subnic an object of class subniche. main a main title for the plot, see title for more details. sig a factor defining the significance species, default NULL. sig_thres value for minimum significance, default 0.05 xlab a label for the x axis, defaults to a description of x, see title for more details. ylab a label for the y axis, defaults to a description of y, see title for more details. col.axis axis color, see par for more details. lty.axis axis line type, see par for more details. lwd.axis axis width, see par for more details. pch.SR.pos type of the point representing SR position, see points for more details. cex.SR.pos size of the point representing SR position, see points for more details. col.SR.pt point color contour if pch=21:25. col.SR.pos color of the point representing SR position, see points for more details. col.SR.lab color of the species labels, see see text for more details. cex.SR.lab size of the species labels defautls NA for no labels, see see text for more details. fac.SR.lab factor for moving the SR labels from its original coordinates for clarity, by de- faults they are multiply 1.2 border.E color border of E polygon, see polygon for more details. col.E inside color of E polygon, see polygon for more details. lty.E line type for the E border, see polygon for more details. lwd.E line width for the E border, see polygon for more details. border.K color border of K polygon, see polygon for more details. col.K inside color of K polygon, see polygon for more details. lty.K line type for the K border, see polygon for more details. lwd.K line width for the K border, see polygon for more details. col.arrow arrow color, see arrows for more details. angle.arrow arrow angle head, see arrows for more details. lwd.arrow arrow width, see arrows for more details. length.arrow arrow head length, see arrows for more details. col.Gk.pos color of the point representing Gk, see points for more details. col.Gk.pt point color contour if pch=21:25. cex.Gk.pos size of the point representing Gk, see points for more details. pch.Gk.pos type of the point representing Gk, see points for more details. col.su color of the points representing the sampling units (SU), see points for more details. pt.su point color contour if pch=21:25. cex.su size of the points representing the sampling units (SU), see points for more de- tails. pch.su type of the points representing the sampling units (SU), see points for more details. font.sp font of the species labels, see see text for more details. leg a logical option for legend to be plotted or not, default leg=T. posi.leg legend location in the graph, see legend for more details. bty.leg the type of box to be drawn around the legends. The allowed values are "o" (the default) and "n". See legend for more details ... further arguments passed to or from other methods. Examples library(subniche) data(doubs) dudi1 <- dudi.pca(doubs$env, scale = TRUE, scan = FALSE, nf = 3) nic1 <- niche(dudi1, doubs$fish, scann = FALSE) # number of sites N <- dim(nic1$ls)[1] #Create a factor which defines the subsets fact <- factor(c(rep(1,N/2),rep(2,N/2))) # nic1 will be use as reference and fact will be use to define the subniches environment subnic1 <- subniche(nic1, fact) #Two graphs are drawn one after the other siggk <- rtestsubor(subnic1,10) sig = c(siggk$`1`$witomigktest$subni.pvalue[-28],siggk$`2`$witomigktest$subni.pvalue[-28]) subplot(subnic1, sig = sig, sig_thres= 0.1) subplot_K Plot sub-environmental space K in E Description The function to represent the sub-environment K in E. Usage subplot_K( subnic, main = NULL, xlab = NULL, ylab = NULL, col.axis = "azure3", lty.axis = 2, lwd.axis = 2, border.E = "black", col.E = "#92c5de", lty.E = 1, lwd.E = 1, border.K = "black", col.K = "#2c7fb8", lty.K = 1, lwd.K = 1, col.Gk.pos = "red", col.Gk.pt = "black", cex.Gk.pos = 1, pch.Gk.pos = 21, col.Gk.lab = "black", cex.Gk.lab = 0.8, fac.Gk.lab = 1.5, col.su = "#b35806", pt.su = "black", cex.su = 0.7, pch.su = 1, leg = T, posi.leg = "topleft", bty.leg = "n", ... ) Arguments subnic an object of class subniche. main a main title for the plot, see title for more details. xlab label for x-axis, see title for more details. ylab label for y-axis, see title for more details. col.axis axis color, see par for more details. lty.axis axis line type, see par for more details. lwd.axis axis width, see par for more details. border.E color border of E polygon, see polygon for more details. col.E inside color of E polygon, see polygon for more details. lty.E line type for the E border, see polygon for more details. lwd.E line width for the E border, see polygon for more details. border.K color border of K polygon, see polygon for more details. col.K inside color of K polygon, see polygon for more details. lty.K line type for the K border, see polygon for more details. lwd.K line width for the K border, see polygon for more details. col.Gk.pos color of the point representing Gk, see points for more details. col.Gk.pt point color contour if pch=21:25. cex.Gk.pos size of the point representing Gk, see points for more details. pch.Gk.pos type of the point representing Gk, see points for more details. col.Gk.lab color of the Gk labels, see see text for more details. cex.Gk.lab size of the Gk labels defaults NA for no labels, see see text for more details. fac.Gk.lab factor for moving the Gk labels from its original coordinates for clarity, by de- faults they are multiply 1.2 col.su color of the points representing the sampling units (SU), see points for more details. pt.su point color contour if pch=21:25. cex.su size of the points representing the sampling units (SU), see points for more de- tails. pch.su type of the points representing the sampling units (SU), see points for more details. leg a logical option for legend to be plotted or not, default leg=T. posi.leg legend location in the graph, see legend for more details. bty.leg the type of box to be drawn around the legends. The allowed values are "o" (the default) and "n". See legend for more details ... further arguments passed to or from other methods. Examples library(subniche) data(doubs) dudi1 <- dudi.pca(doubs$env, scale = TRUE, scan = FALSE, nf = 3) nic1 <- niche(dudi1, doubs$fish, scann = FALSE) # number of sites N <- dim(nic1$ls)[1] #Create a factor which defines the subsets fact <- factor(c(rep(1,N/2),rep(2,N/2))) # nic1 will be use as reference and fact will be use to define the subniches environment subnic1 <- subniche(nic1, fact) #Plot K in E subplot_K(subnic1) subplot_sp Plot a species subniche under each sub-environmental space K Description The function to represent the species subniche under each subenvironment K with their respective marginality from G_K. 28 subplot_sp Usage subplot_sp( subnic, sp, main = NULL, col.axis = "azure3", lty.axis = 2, lwd.axis = 2, xlab = NULL, ylab = NULL, border.E = "black", col.E = "#92c5de", lty.E = 1, lwd.E = 1, border.K = "black", lwd.K = 1, col.K = "#2c7fb8", lty.K = 1, col.Gk.pos = "red", col.Gk.pt = "black", cex.Gk.pos = 1, pch.Gk.pos = 21, border.SP = "#bc5090", col.SB = "#ffff99", lty.SP = 1, lwd.SP = 2, border.NR = "#fdb462", col.NR = NA, lty.NR = 1, lwd.NR = 2, border.SR = "#a1d99b", col.SR = "#a1d99b", lty.SR = 1, lwd.SR = 1, pch.SR.pos = 19, cex.SR.pos = 1, col.SR.pt = "black", col.SR.pos = "black", cex.SR.lab = 0.7, col.SR.lab = "black", fac.SR.lab = 1.2, font.sp = 2, col.arrow = "black", angle.arrow = 20, lwd.arrow = 2, length.arrow = 0.1, leg = T, posi.leg = "topleft", bty.leg = "n", ... ) Arguments subnic an object of class subniche. sp a character string of the species name. main a main title for the plot, see title for more details. col.axis axis color, see par for more details. lty.axis axis line type, see par for more details. lwd.axis axis width, see par for more details. xlab label for x-axis, see title for more details. ylab label for y-axis, see title for more details. border.E color border of E polygon, see polygon for more details. col.E inside color of E polygon, see polygon for more details. lty.E line type for the E border, see polygon for more details. lwd.E line width for the E border, see polygon for more details. border.K color border of K polygon, see polygon for more details. lwd.K line width for the K border, see polygon for more details. col.K inside color of K polygon, see polygon for more details. lty.K line type for the K border, see polygon for more details. col.Gk.pos color of the point representing G_k, see points for more details. col.Gk.pt point color contour if pch=21:25. cex.Gk.pos size of the point representing G_k, see points for more details. pch.Gk.pos type of the point representing G_k, see points for more details. border.SP color border of species subniche polygon, see polygon for more details. col.SB color of the SB area. lty.SP line type for the SP border, see polygon for more details. lwd.SP line width for the SP border, see polygon for more details. border.NR color border of NR polygon, see polygon for more details. col.NR inside color of NR polygon, see polygon for more details. lty.NR line type for the NR border, see polygon for more details. lwd.NR line width for the NR border, see polygon for more details. border.SR color border of SR polygon, see polygon for more details. col.SR inside color of SR polygon, see polygon for more details. lty.SR line type for the SR border, see polygon for more details. lwd.SR line width for the SR border, see polygon for more details. pch.SR.pos type of points representing the SR position, see points for more details. cex.SR.pos size of points representing the SR position, see points for more details. col.SR.pt point color contour if pch=21:25. col.SR.pos color of points representing the SR position, see points for more details. cex.SR.lab size of the species label representing the SR position, see text for more details. col.SR.lab color of the species label representing the SR position, see text for more details. fac.SR.lab factor for moving the SR labels from its original coordinates for clarity, by de- faults they are multiply 1.2 font.sp An integer which specifies which font to use for species label. 1 corresponds to plain text (the default), 2 to bold face, 3 to italic and 4 to bold italic, see par for more details. col.arrow arrow color, see arrows for more details. angle.arrow arrow angle head, see arrows for more details. lwd.arrow arrow width, see arrows for more details. length.arrow arrow head length, see arrows for more details. leg a logical option for legend to be plotted or not, default leg=T. posi.leg legend location in the graph, see legend for more details. bty.leg the type of box to be drawn around the legends. The allowed values are "o" (the default) and "n". See legend for more details ... further arguments passed to or from other methods. Examples library(subniche) data(doubs) dudi1 <- dudi.pca(doubs$env, scale = TRUE, scan = FALSE, nf = 3) nic1 <- niche(dudi1, doubs$fish, scann = FALSE) # number of sites N <- dim(nic1$ls)[1] #Create a factor which defines the subsets fact <- factor(c(rep(1,N/2),rep(2,N/2))) # nic1 will be use as reference and fact will be use to define the subniches environment subnic1 <- subniche(nic1, fact) eig <- round(subnic1$eig/sum(subnic1$eig)*100,2)[1:2] #Two graphs are drawn one after the other subplot_sp(subnic1,"Neba")
github.com/neal1991/gshark
go
Go
README [¶](#section-readme) --- ![GgShark logo](https://s1.ax1x.com/2018/10/17/idhZvj.png) ### GShark Scan for sensitive information easily and effectively. ### GShark [Go Report Card](https://goreportcard.com/report/github.com/madneal/gshark) The project is based on go with vue to build a management system for sensitive information detection. This is the total fresh version, you can refer the [old version](https://github.com/madneal/gshark/blob/gin/OLD_README.md) here. ### Features * Support multi platform, including Gitlab, Github, Searchcode * Flexible menu and API permission setting * Flexible rules and filter rules * Utilize gobuster to brute force subdomain * Easily used management system ### Quick start ![GShark](https://user-images.githubusercontent.com/12164075/114326875-58e1da80-9b69-11eb-82a5-b2e3751a2304.png) #### Deployment For the deployment, it's suggested to install nginx. Place the `dist` folder under `html`, modify the `nginx.conf` to reverse proxy the backend service. I have also made a video for the deployment in [bilibili](https://www.bilibili.com/video/BV1Py4y1s7ap/) and [youtube](https://youtu.be/bFrKm5t4M54). ``` location /api/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; rewrite ^/api/(.*)$ /$1 break; proxy_pass http://127.0.0.1:8888; } ``` The deployment work is very easy. Find the corresponding binary zip file from [releases](https://github.com/madneal/gshark/releases). Unzip and run. Remember to copy the files inside `dist` to `html` folder of nginx. ##### Web service ``` ./gshark web ``` ##### Scan service ``` ./gshark scan ``` #### Development ##### Server side ``` git clone https://github.com/madneal/gshark.git cd server go mod tidy mv config-temp.yaml config.yaml go build ./gshark web ``` If you want to set up the scan service, please run: ``` ./gshark scan ``` ##### Web side ``` cd ../web npm install npm run serve ``` #### Run ``` USAGE: gshark [global options] command [command options] [arguments...] COMMANDS: web Startup a web Service scan Start to scan github leak info help, h Show a list of commands or help for one command GLOBAL OPTIONS: --debug, -d Debug Mode --host value, -H value web listen address (default: "0.0.0.0") --port value, -p value web listen port (default: 8000) --time value, -t value scan interval(second) (default: 900) --help, -h show help --version, -v print the version ``` ##### Add Token To execute `./gshark scan`, you need to add a Github token for crawl information in github. You can generate a token in [tokens](https://github.com/settings/tokens). Most access scopes are enough. For Gitlab search, remember to add token too. [![iR2TMt.md.png](https://s1.ax1x.com/2018/10/31/iR2TMt.md.png)](https://imgchr.com/i/iR2TMt) #### FAQ 1. Default username and password to login gshark/gshark 1. `go get ./... connection error` It's suggested to enable goproxy(refer this [article](https://madneal.com/post/gproxy/) for golang upgrade): ``` go env -w GOPROXY=https://goproxy.cn,direct go env -w GO111MODULE=on ``` #### Reference * [gin-vue-admin](https://github.com/flipped-aurora/gin-vue-admin) #### Wechat If you would like to join wechat group, you can add my wechat `mmadneal` with the message `gshark`. #### License [Apache License 2.0](https://github.com/madneal/gshark/raw/master/LICENSE) #### 404StarLink 2.0 - Galaxy ![](https://github.com/knownsec/404StarLink-Project/raw/master/logo.png) GShark 是 404Team [星链计划2.0](https://github.com/knownsec/404StarLink2.0-Galaxy)中的一环,如果对 GShark 有任何疑问又或是想要找小伙伴交流,可以参考星链计划的加群方式。 * <https://github.com/knownsec/404StarLink2.0-Galaxy#communityNone
icm20689_driver_rs
rust
Rust
Struct icm20689_driver_rs::ICM20689 === ``` pub struct ICM20689<I>where I: Write + Read,{ pub accel_measurement: Measurement, pub gyro_measurement: Measurement, /* private fields */ } ``` Fields --- `accel_measurement: Measurement``gyro_measurement: Measurement`Implementations --- ### impl<I> ICM20689<I>where I: Write + Read + WriteRead, #### pub fn new(i2c: I, icm_address: u8) -> Self #### pub fn init<D>(&mut self, delay: &mut D) -> Result<(), ICMError>where D: DelayMs<u16>, #### pub fn set_accel_range(&mut self, range: AccelConfig) -> Result<(), ICMError#### pub fn set_gyro_range(&mut self, range: GyroConfig) -> Result<(), ICMError#### pub fn set_dlpf_bandwidth( &mut self, bandwidth: DLPFBandwidth ) -> Result<(), ICMError#### pub fn set_srd(&mut self, srd: u8) -> Result<(), ICMError#### pub fn read_sensor(&mut self) -> Result<(), ICMError#### pub fn calibrate_gyro<D>(&mut self, delay: &mut D) -> Result<(), ICMError>where D: DelayMs<u16>, #### pub fn calibrate_accel<D>(&mut self, delay: &mut D) -> Result<(), ICMError>where D: DelayMs<u16>, #### pub fn read_accelerometer(&mut self) -> Measurement #### pub fn read_gyroscope(&mut self) -> Measurement #### pub fn whoami(&mut self) -> Result<u8, ICMErrorAuto Trait Implementations --- ### impl<I> RefUnwindSafe for ICM20689<I>where I: RefUnwindSafe, ### impl<I> Send for ICM20689<I>where I: Send, ### impl<I> Sync for ICM20689<I>where I: Sync, ### impl<I> Unpin for ICM20689<I>where I: Unpin, ### impl<I> UnwindSafe for ICM20689<I>where I: UnwindSafe, Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct icm20689_driver_rs::Measurement === ``` pub struct Measurement { pub values: [f64; 3], /* private fields */ } ``` Fields --- `values: [f64; 3]`Trait Implementations --- ### impl Clone for Measurement #### fn clone(&self) -> Measurement Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn default() -> Measurement Returns the “default value” for a type. Auto Trait Implementations --- ### impl RefUnwindSafe for Measurement ### impl Send for Measurement ### impl Sync for Measurement ### impl Unpin for Measurement ### impl UnwindSafe for Measurement Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum icm20689_driver_rs::AccelConfig === ``` #[repr(u8)] pub enum AccelConfig { ACCEL_RANGE_2G, ACCEL_RANGE_4G, ACCEL_RANGE_8G, ACCEL_RANGE_16G, } ``` Variants --- ### ACCEL_RANGE_2G ### ACCEL_RANGE_4G ### ACCEL_RANGE_8G ### ACCEL_RANGE_16G Trait Implementations --- ### impl Clone for AccelConfig #### fn clone(&self) -> AccelConfig Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Auto Trait Implementations --- ### impl RefUnwindSafe for AccelConfig ### impl Send for AccelConfig ### impl Sync for AccelConfig ### impl Unpin for AccelConfig ### impl UnwindSafe for AccelConfig Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum icm20689_driver_rs::DLPFBandwidth === ``` pub enum DLPFBandwidth { DLPF_BANDWIDTH_MAX, DLPF_BANDWIDTH_218HZ, DLPF_BANDWIDTH_99HZ, DLPF_BANDWIDTH_45HZ, DLPF_BANDWIDTH_21HZ, DLPF_BANDWIDTH_10HZ, DLPF_BANDWIDTH_5HZ, } ``` Variants --- ### DLPF_BANDWIDTH_MAX ### DLPF_BANDWIDTH_218HZ ### DLPF_BANDWIDTH_99HZ ### DLPF_BANDWIDTH_45HZ ### DLPF_BANDWIDTH_21HZ ### DLPF_BANDWIDTH_10HZ ### DLPF_BANDWIDTH_5HZ Trait Implementations --- ### impl Clone for DLPFBandwidth #### fn clone(&self) -> DLPFBandwidth Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Auto Trait Implementations --- ### impl RefUnwindSafe for DLPFBandwidth ### impl Send for DLPFBandwidth ### impl Sync for DLPFBandwidth ### impl Unpin for DLPFBandwidth ### impl UnwindSafe for DLPFBandwidth Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum icm20689_driver_rs::GyroConfig === ``` #[repr(u8)] pub enum GyroConfig { GYRO_RANGE_250DPS, GYRO_RANGE_500DPS, GYRO_RANGE_1000DPS, GYRO_RANGE_2000DPS, } ``` Variants --- ### GYRO_RANGE_250DPS ### GYRO_RANGE_500DPS ### GYRO_RANGE_1000DPS ### GYRO_RANGE_2000DPS Trait Implementations --- ### impl Clone for GyroConfig #### fn clone(&self) -> GyroConfig Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Auto Trait Implementations --- ### impl RefUnwindSafe for GyroConfig ### impl Send for GyroConfig ### impl Sync for GyroConfig ### impl Unpin for GyroConfig ### impl UnwindSafe for GyroConfig Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum icm20689_driver_rs::ICMError === ``` pub enum ICMError { I2cReadError, I2cWriteError, ICMIDError, } ``` Variants --- ### I2cReadError ### I2cWriteError ### ICMIDError Trait Implementations --- ### impl Debug for ICMError #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for ICMError ### impl Send for ICMError ### impl Sync for ICMError ### impl Unpin for ICMError ### impl UnwindSafe for ICMError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum icm20689_driver_rs::Operation === ``` pub enum Operation<'a> { Read(&'a mut [u8]), Write(&'a [u8]), } ``` Transactional I2C operation. Several operations can be combined as part of a transaction. Variants --- ### Read(&'a mut [u8]) Read data into the provided buffer ### Write(&'a [u8]) Write data from the provided buffer Trait Implementations --- ### impl<'a> Debug for Operation<'a#### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<'a> StructuralPartialEq for Operation<'aAuto Trait Implementations --- ### impl<'a> RefUnwindSafe for Operation<'a### impl<'a> Send for Operation<'a### impl<'a> Sync for Operation<'a### impl<'a> Unpin for Operation<'a### impl<'a> !UnwindSafe for Operation<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Trait icm20689_driver_rs::AddressMode === ``` pub trait AddressMode: Sealed { } ``` Address mode (7-bit / 10-bit) Note: This trait is sealed and should not be implemented outside of this crate. Implementations on Foreign Types --- ### impl AddressMode for u16 ### impl AddressMode for u8 Implementors --- Trait icm20689_driver_rs::Read === ``` pub trait Read<A = u8>where A: AddressMode,{ type Error; // Required method fn read(&mut self, address: A, buffer: &mut [u8]) -> Result<(), Self::Error>; } ``` Blocking read Required Associated Types --- #### type Error Error type Required Methods --- #### fn read(&mut self, address: A, buffer: &mut [u8]) -> Result<(), Self::ErrorReads enough bytes from slave with `address` to fill `buffer` ##### I2C Events (contract) ``` Master: ST SAD+R MAK MAK ... NMAK SP Slave: SAK B0 B1 ... BN ``` Where * `ST` = start condition * `SAD+R` = slave address followed by bit 1 to indicate reading * `SAK` = slave acknowledge * `Bi` = ith byte of data * `MAK` = master acknowledge * `NMAK` = master no acknowledge * `SP` = stop condition Implementors --- Trait icm20689_driver_rs::Transactional === ``` pub trait Transactional<A = u8>where A: AddressMode,{ type Error; // Required method fn exec<'a>( &mut self, address: A, operations: &mut [Operation<'a>] ) -> Result<(), Self::Error>; } ``` Transactional I2C interface. This allows combining operations within an I2C transaction. Required Associated Types --- #### type Error Error type Required Methods --- #### fn exec<'a>( &mut self, address: A, operations: &mut [Operation<'a>] ) -> Result<(), Self::ErrorExecute the provided operations on the I2C bus. Transaction contract: * Before executing the first operation an ST is sent automatically. This is followed by SAD+R/W as appropriate. * Data from adjacent operations of the same type are sent after each other without an SP or SR. * Between adjacent operations of a different type an SR and SAD+R/W is sent. * After executing the last operation an SP is sent automatically. * If the last operation is a `Read` the master does not send an acknowledge for the last byte. * `ST` = start condition * `SAD+R/W` = slave address followed by bit 1 to indicate reading or 0 to indicate writing * `SR` = repeated start condition * `SP` = stop condition Implementors --- Trait icm20689_driver_rs::TransactionalIter === ``` pub trait TransactionalIter<A = u8>where A: AddressMode,{ type Error; // Required method fn exec_iter<'a, O>( &mut self, address: A, operations: O ) -> Result<(), Self::Error> where O: IntoIterator<Item = Operation<'a>>; } ``` Transactional I2C interface (iterator version). This allows combining operation within an I2C transaction. Required Associated Types --- #### type Error Error type Required Methods --- #### fn exec_iter<'a, O>( &mut self, address: A, operations: O ) -> Result<(), Self::Error>where O: IntoIterator<Item = Operation<'a>>, Execute the provided operations on the I2C bus (iterator version). Transaction contract: * Before executing the first operation an ST is sent automatically. This is followed by SAD+R/W as appropriate. * Data from adjacent operations of the same type are sent after each other without an SP or SR. * Between adjacent operations of a different type an SR and SAD+R/W is sent. * After executing the last operation an SP is sent automatically. * If the last operation is a `Read` the master does not send an acknowledge for the last byte. * `ST` = start condition * `SAD+R/W` = slave address followed by bit 1 to indicate reading or 0 to indicate writing * `SR` = repeated start condition * `SP` = stop condition Implementors --- Trait icm20689_driver_rs::Write === ``` pub trait Write<A = u8>where A: AddressMode,{ type Error; // Required method fn write(&mut self, address: A, bytes: &[u8]) -> Result<(), Self::Error>; } ``` Blocking write Required Associated Types --- #### type Error Error type Required Methods --- #### fn write(&mut self, address: A, bytes: &[u8]) -> Result<(), Self::ErrorWrites bytes to slave with address `address` ##### I2C Events (contract) ``` Master: ST SAD+W B0 B1 ... BN SP Slave: SAK SAK SAK ... SAK ``` Where * `ST` = start condition * `SAD+W` = slave address followed by bit 0 to indicate writing * `SAK` = slave acknowledge * `Bi` = ith byte of data * `SP` = stop condition Implementors --- Trait icm20689_driver_rs::WriteIter === ``` pub trait WriteIter<A = u8>where A: AddressMode,{ type Error; // Required method fn write<B>(&mut self, address: A, bytes: B) -> Result<(), Self::Error> where B: IntoIterator<Item = u8>; } ``` Blocking write (iterator version) Required Associated Types --- #### type Error Error type Required Methods --- #### fn write<B>(&mut self, address: A, bytes: B) -> Result<(), Self::Error>where B: IntoIterator<Item = u8>, Writes bytes to slave with address `address` ##### I2C Events (contract) Same as `Write` Implementors --- Trait icm20689_driver_rs::WriteIterRead === ``` pub trait WriteIterRead<A = u8>where A: AddressMode,{ type Error; // Required method fn write_iter_read<B>( &mut self, address: A, bytes: B, buffer: &mut [u8] ) -> Result<(), Self::Error> where B: IntoIterator<Item = u8>; } ``` Blocking write (iterator version) + read Required Associated Types --- #### type Error Error type Required Methods --- #### fn write_iter_read<B>( &mut self, address: A, bytes: B, buffer: &mut [u8] ) -> Result<(), Self::Error>where B: IntoIterator<Item = u8>, Writes bytes to slave with address `address` and then reads enough bytes to fill `buffer` *in a single transaction* ##### I2C Events (contract) Same as the `WriteRead` trait Implementors --- Trait icm20689_driver_rs::WriteRead === ``` pub trait WriteRead<A = u8>where A: AddressMode,{ type Error; // Required method fn write_read( &mut self, address: A, bytes: &[u8], buffer: &mut [u8] ) -> Result<(), Self::Error>; } ``` Blocking write + read Required Associated Types --- #### type Error Error type Required Methods --- #### fn write_read( &mut self, address: A, bytes: &[u8], buffer: &mut [u8] ) -> Result<(), Self::ErrorWrites bytes to slave with address `address` and then reads enough bytes to fill `buffer` *in a single transaction* ##### I2C Events (contract) ``` Master: ST SAD+W O0 O1 ... OM SR SAD+R MAK MAK ... NMAK SP Slave: SAK SAK SAK ... SAK SAK I0 I1 ... IN ``` Where * `ST` = start condition * `SAD+W` = slave address followed by bit 0 to indicate writing * `SAK` = slave acknowledge * `Oi` = ith outgoing byte of data * `SR` = repeated start condition * `SAD+R` = slave address followed by bit 1 to indicate reading * `Ii` = ith incoming byte of data * `MAK` = master acknowledge * `NMAK` = master no acknowledge * `SP` = stop condition Implementors --- Type Definition icm20689_driver_rs::SevenBitAddress === ``` pub type SevenBitAddress = u8; ``` 7-bit address mode type Type Definition icm20689_driver_rs::TenBitAddress === ``` pub type TenBitAddress = u16; ``` 10-bit address mode type
rusoto_cloudsearch
rust
Rust
Crate rusoto_cloudsearch === Amazon CloudSearch Configuration Service You use the Amazon CloudSearch configuration service to create, configure, and manage search domains. Configuration service requests are submitted using the AWS Query protocol. AWS Query requests are HTTP or HTTPS requests submitted via HTTP GET or POST with a query parameter named Action. The endpoint for configuration service requests is region-specific: cloudsearch.*region*.amazonaws.com. For example, cloudsearch.us-east-1.amazonaws.com. For a current list of supported regions and endpoints, see Regions and Endpoints. If you’re using the service, you’re probably looking for CloudSearchClient and CloudSearch. Structs --- AccessPoliciesStatusThe configured access rules for the domain's document and search endpoints, and the current status of those rules. AnalysisOptionsSynonyms, stopwords, and stemming options for an analysis scheme. Includes tokenization dictionary for Japanese. AnalysisSchemeConfiguration information for an analysis scheme. Each analysis scheme has a unique name and specifies the language of the text to be processed. The following options can be configured for an analysis scheme: `Synonyms`, `Stopwords`, `StemmingDictionary`, `JapaneseTokenizationDictionary` and `AlgorithmicStemming`. AnalysisSchemeStatusThe status and configuration of an `AnalysisScheme`. AvailabilityOptionsStatusThe status and configuration of the domain's availability options. BuildSuggestersRequestContainer for the parameters to the `BuildSuggester` operation. Specifies the name of the domain you want to update. BuildSuggestersResponseThe result of a `BuildSuggester` request. Contains a list of the fields used for suggestions. CloudSearchClientA client for the Amazon CloudSearch API. CreateDomainRequestContainer for the parameters to the `CreateDomain` operation. Specifies a name for the new search domain. CreateDomainResponseThe result of a `CreateDomainRequest`. Contains the status of a newly created domain. DateArrayOptionsOptions for a field that contains an array of dates. Present if `IndexFieldType` specifies the field is of type `date-array`. All options are enabled by default. DateOptionsOptions for a date field. Dates and times are specified in UTC (Coordinated Universal Time) according to IETF RFC3339: yyyy-mm-ddT00:00:00Z. Present if `IndexFieldType` specifies the field is of type `date`. All options are enabled by default. DefineAnalysisSchemeRequestContainer for the parameters to the `DefineAnalysisScheme` operation. Specifies the name of the domain you want to update and the analysis scheme configuration. DefineAnalysisSchemeResponseThe result of a `DefineAnalysisScheme` request. Contains the status of the newly-configured analysis scheme. DefineExpressionRequestContainer for the parameters to the `DefineExpression` operation. Specifies the name of the domain you want to update and the expression you want to configure. DefineExpressionResponseThe result of a `DefineExpression` request. Contains the status of the newly-configured expression. DefineIndexFieldRequestContainer for the parameters to the `DefineIndexField` operation. Specifies the name of the domain you want to update and the index field configuration. DefineIndexFieldResponseThe result of a `DefineIndexField` request. Contains the status of the newly-configured index field. DefineSuggesterRequestContainer for the parameters to the `DefineSuggester` operation. Specifies the name of the domain you want to update and the suggester configuration. DefineSuggesterResponseThe result of a `DefineSuggester` request. Contains the status of the newly-configured suggester. DeleteAnalysisSchemeRequestContainer for the parameters to the `DeleteAnalysisScheme` operation. Specifies the name of the domain you want to update and the analysis scheme you want to delete. DeleteAnalysisSchemeResponseThe result of a `DeleteAnalysisScheme` request. Contains the status of the deleted analysis scheme. DeleteDomainRequestContainer for the parameters to the `DeleteDomain` operation. Specifies the name of the domain you want to delete. DeleteDomainResponseThe result of a `DeleteDomain` request. Contains the status of a newly deleted domain, or no status if the domain has already been completely deleted. DeleteExpressionRequestContainer for the parameters to the `DeleteExpression` operation. Specifies the name of the domain you want to update and the name of the expression you want to delete. DeleteExpressionResponseThe result of a `DeleteExpression` request. Specifies the expression being deleted. DeleteIndexFieldRequestContainer for the parameters to the `DeleteIndexField` operation. Specifies the name of the domain you want to update and the name of the index field you want to delete. DeleteIndexFieldResponseThe result of a `DeleteIndexField` request. DeleteSuggesterRequestContainer for the parameters to the `DeleteSuggester` operation. Specifies the name of the domain you want to update and name of the suggester you want to delete. DeleteSuggesterResponseThe result of a `DeleteSuggester` request. Contains the status of the deleted suggester. DescribeAnalysisSchemesRequestContainer for the parameters to the `DescribeAnalysisSchemes` operation. Specifies the name of the domain you want to describe. To limit the response to particular analysis schemes, specify the names of the analysis schemes you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. DescribeAnalysisSchemesResponseThe result of a `DescribeAnalysisSchemes` request. Contains the analysis schemes configured for the domain specified in the request. DescribeAvailabilityOptionsRequestContainer for the parameters to the `DescribeAvailabilityOptions` operation. Specifies the name of the domain you want to describe. To show the active configuration and exclude any pending changes, set the Deployed option to `true`. DescribeAvailabilityOptionsResponseThe result of a `DescribeAvailabilityOptions` request. Indicates whether or not the Multi-AZ option is enabled for the domain specified in the request. DescribeDomainEndpointOptionsRequestContainer for the parameters to the `DescribeDomainEndpointOptions` operation. Specify the name of the domain you want to describe. To show the active configuration and exclude any pending changes, set the Deployed option to `true`. DescribeDomainEndpointOptionsResponseThe result of a `DescribeDomainEndpointOptions` request. Contains the status and configuration of a search domain's endpoint options. DescribeDomainsRequestContainer for the parameters to the `DescribeDomains` operation. By default shows the status of all domains. To restrict the response to particular domains, specify the names of the domains you want to describe. DescribeDomainsResponseThe result of a `DescribeDomains` request. Contains the status of the domains specified in the request or all domains owned by the account. DescribeExpressionsRequestContainer for the parameters to the `DescribeDomains` operation. Specifies the name of the domain you want to describe. To restrict the response to particular expressions, specify the names of the expressions you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. DescribeExpressionsResponseThe result of a `DescribeExpressions` request. Contains the expressions configured for the domain specified in the request. DescribeIndexFieldsRequestContainer for the parameters to the `DescribeIndexFields` operation. Specifies the name of the domain you want to describe. To restrict the response to particular index fields, specify the names of the index fields you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. DescribeIndexFieldsResponseThe result of a `DescribeIndexFields` request. Contains the index fields configured for the domain specified in the request. DescribeScalingParametersRequestContainer for the parameters to the `DescribeScalingParameters` operation. Specifies the name of the domain you want to describe. DescribeScalingParametersResponseThe result of a `DescribeScalingParameters` request. Contains the scaling parameters configured for the domain specified in the request. DescribeServiceAccessPoliciesRequestContainer for the parameters to the `DescribeServiceAccessPolicies` operation. Specifies the name of the domain you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. DescribeServiceAccessPoliciesResponseThe result of a `DescribeServiceAccessPolicies` request. DescribeSuggestersRequestContainer for the parameters to the `DescribeSuggester` operation. Specifies the name of the domain you want to describe. To restrict the response to particular suggesters, specify the names of the suggesters you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. DescribeSuggestersResponseThe result of a `DescribeSuggesters` request. DocumentSuggesterOptionsOptions for a search suggester. DomainEndpointOptionsThe domain's endpoint options. DomainEndpointOptionsStatusThe configuration and status of the domain's endpoint options. DomainStatusThe current status of the search domain. DoubleArrayOptionsOptions for a field that contains an array of double-precision 64-bit floating point values. Present if `IndexFieldType` specifies the field is of type `double-array`. All options are enabled by default. DoubleOptionsOptions for a double-precision 64-bit floating point field. Present if `IndexFieldType` specifies the field is of type `double`. All options are enabled by default. ExpressionA named expression that can be evaluated at search time. Can be used to sort the search results, define other expressions, or return computed information in the search results. ExpressionStatusThe value of an `Expression` and its current status. IndexDocumentsRequestContainer for the parameters to the `IndexDocuments` operation. Specifies the name of the domain you want to re-index. IndexDocumentsResponseThe result of an `IndexDocuments` request. Contains the status of the indexing operation, including the fields being indexed. IndexFieldConfiguration information for a field in the index, including its name, type, and options. The supported options depend on the `IndexFieldType`. IndexFieldStatusThe value of an `IndexField` and its current status. IntArrayOptionsOptions for a field that contains an array of 64-bit signed integers. Present if `IndexFieldType` specifies the field is of type `int-array`. All options are enabled by default. IntOptionsOptions for a 64-bit signed integer field. Present if `IndexFieldType` specifies the field is of type `int`. All options are enabled by default. LatLonOptionsOptions for a latlon field. A latlon field contains a location stored as a latitude and longitude value pair. Present if `IndexFieldType` specifies the field is of type `latlon`. All options are enabled by default. LimitsListDomainNamesResponseThe result of a `ListDomainNames` request. Contains a list of the domains owned by an account. LiteralArrayOptionsOptions for a field that contains an array of literal strings. Present if `IndexFieldType` specifies the field is of type `literal-array`. All options are enabled by default. LiteralOptionsOptions for literal field. Present if `IndexFieldType` specifies the field is of type `literal`. All options are enabled by default. OptionStatusThe status of domain configuration option. ScalingParametersThe desired instance type and desired number of replicas of each index partition. ScalingParametersStatusThe status and configuration of a search domain's scaling parameters. ServiceEndpointThe endpoint to which service requests can be submitted. SuggesterConfiguration information for a search suggester. Each suggester has a unique name and specifies the text field you want to use for suggestions. The following options can be configured for a suggester: `FuzzyMatching`, `SortExpression`. SuggesterStatusThe value of a `Suggester` and its current status. TextArrayOptionsOptions for a field that contains an array of text strings. Present if `IndexFieldType` specifies the field is of type `text-array`. A `text-array` field is always searchable. All options are enabled by default. TextOptionsOptions for text field. Present if `IndexFieldType` specifies the field is of type `text`. A `text` field is always searchable. All options are enabled by default. UpdateAvailabilityOptionsRequestContainer for the parameters to the `UpdateAvailabilityOptions` operation. Specifies the name of the domain you want to update and the Multi-AZ availability option. UpdateAvailabilityOptionsResponseThe result of a `UpdateAvailabilityOptions` request. Contains the status of the domain's availability options. UpdateDomainEndpointOptionsRequestContainer for the parameters to the `UpdateDomainEndpointOptions` operation. Specifies the name of the domain you want to update and the domain endpoint options. UpdateDomainEndpointOptionsResponseThe result of a `UpdateDomainEndpointOptions` request. Contains the configuration and status of the domain's endpoint options. UpdateScalingParametersRequestContainer for the parameters to the `UpdateScalingParameters` operation. Specifies the name of the domain you want to update and the scaling parameters you want to configure. UpdateScalingParametersResponseThe result of a `UpdateScalingParameters` request. Contains the status of the newly-configured scaling parameters. UpdateServiceAccessPoliciesRequestContainer for the parameters to the `UpdateServiceAccessPolicies` operation. Specifies the name of the domain you want to update and the access rules you want to configure. UpdateServiceAccessPoliciesResponseThe result of an `UpdateServiceAccessPolicies` request. Contains the new access policies. Enums --- BuildSuggestersErrorErrors returned by BuildSuggesters CreateDomainErrorErrors returned by CreateDomain DefineAnalysisSchemeErrorErrors returned by DefineAnalysisScheme DefineExpressionErrorErrors returned by DefineExpression DefineIndexFieldErrorErrors returned by DefineIndexField DefineSuggesterErrorErrors returned by DefineSuggester DeleteAnalysisSchemeErrorErrors returned by DeleteAnalysisScheme DeleteDomainErrorErrors returned by DeleteDomain DeleteExpressionErrorErrors returned by DeleteExpression DeleteIndexFieldErrorErrors returned by DeleteIndexField DeleteSuggesterErrorErrors returned by DeleteSuggester DescribeAnalysisSchemesErrorErrors returned by DescribeAnalysisSchemes DescribeAvailabilityOptionsErrorErrors returned by DescribeAvailabilityOptions DescribeDomainEndpointOptionsErrorErrors returned by DescribeDomainEndpointOptions DescribeDomainsErrorErrors returned by DescribeDomains DescribeExpressionsErrorErrors returned by DescribeExpressions DescribeIndexFieldsErrorErrors returned by DescribeIndexFields DescribeScalingParametersErrorErrors returned by DescribeScalingParameters DescribeServiceAccessPoliciesErrorErrors returned by DescribeServiceAccessPolicies DescribeSuggestersErrorErrors returned by DescribeSuggesters IndexDocumentsErrorErrors returned by IndexDocuments ListDomainNamesErrorErrors returned by ListDomainNames UpdateAvailabilityOptionsErrorErrors returned by UpdateAvailabilityOptions UpdateDomainEndpointOptionsErrorErrors returned by UpdateDomainEndpointOptions UpdateScalingParametersErrorErrors returned by UpdateScalingParameters UpdateServiceAccessPoliciesErrorErrors returned by UpdateServiceAccessPolicies Traits --- CloudSearchTrait representing the capabilities of the Amazon CloudSearch API. Amazon CloudSearch clients implement this trait. Crate rusoto_cloudsearch === Amazon CloudSearch Configuration Service You use the Amazon CloudSearch configuration service to create, configure, and manage search domains. Configuration service requests are submitted using the AWS Query protocol. AWS Query requests are HTTP or HTTPS requests submitted via HTTP GET or POST with a query parameter named Action. The endpoint for configuration service requests is region-specific: cloudsearch.*region*.amazonaws.com. For example, cloudsearch.us-east-1.amazonaws.com. For a current list of supported regions and endpoints, see Regions and Endpoints. If you’re using the service, you’re probably looking for CloudSearchClient and CloudSearch. Structs --- AccessPoliciesStatusThe configured access rules for the domain's document and search endpoints, and the current status of those rules. AnalysisOptionsSynonyms, stopwords, and stemming options for an analysis scheme. Includes tokenization dictionary for Japanese. AnalysisSchemeConfiguration information for an analysis scheme. Each analysis scheme has a unique name and specifies the language of the text to be processed. The following options can be configured for an analysis scheme: `Synonyms`, `Stopwords`, `StemmingDictionary`, `JapaneseTokenizationDictionary` and `AlgorithmicStemming`. AnalysisSchemeStatusThe status and configuration of an `AnalysisScheme`. AvailabilityOptionsStatusThe status and configuration of the domain's availability options. BuildSuggestersRequestContainer for the parameters to the `BuildSuggester` operation. Specifies the name of the domain you want to update. BuildSuggestersResponseThe result of a `BuildSuggester` request. Contains a list of the fields used for suggestions. CloudSearchClientA client for the Amazon CloudSearch API. CreateDomainRequestContainer for the parameters to the `CreateDomain` operation. Specifies a name for the new search domain. CreateDomainResponseThe result of a `CreateDomainRequest`. Contains the status of a newly created domain. DateArrayOptionsOptions for a field that contains an array of dates. Present if `IndexFieldType` specifies the field is of type `date-array`. All options are enabled by default. DateOptionsOptions for a date field. Dates and times are specified in UTC (Coordinated Universal Time) according to IETF RFC3339: yyyy-mm-ddT00:00:00Z. Present if `IndexFieldType` specifies the field is of type `date`. All options are enabled by default. DefineAnalysisSchemeRequestContainer for the parameters to the `DefineAnalysisScheme` operation. Specifies the name of the domain you want to update and the analysis scheme configuration. DefineAnalysisSchemeResponseThe result of a `DefineAnalysisScheme` request. Contains the status of the newly-configured analysis scheme. DefineExpressionRequestContainer for the parameters to the `DefineExpression` operation. Specifies the name of the domain you want to update and the expression you want to configure. DefineExpressionResponseThe result of a `DefineExpression` request. Contains the status of the newly-configured expression. DefineIndexFieldRequestContainer for the parameters to the `DefineIndexField` operation. Specifies the name of the domain you want to update and the index field configuration. DefineIndexFieldResponseThe result of a `DefineIndexField` request. Contains the status of the newly-configured index field. DefineSuggesterRequestContainer for the parameters to the `DefineSuggester` operation. Specifies the name of the domain you want to update and the suggester configuration. DefineSuggesterResponseThe result of a `DefineSuggester` request. Contains the status of the newly-configured suggester. DeleteAnalysisSchemeRequestContainer for the parameters to the `DeleteAnalysisScheme` operation. Specifies the name of the domain you want to update and the analysis scheme you want to delete. DeleteAnalysisSchemeResponseThe result of a `DeleteAnalysisScheme` request. Contains the status of the deleted analysis scheme. DeleteDomainRequestContainer for the parameters to the `DeleteDomain` operation. Specifies the name of the domain you want to delete. DeleteDomainResponseThe result of a `DeleteDomain` request. Contains the status of a newly deleted domain, or no status if the domain has already been completely deleted. DeleteExpressionRequestContainer for the parameters to the `DeleteExpression` operation. Specifies the name of the domain you want to update and the name of the expression you want to delete. DeleteExpressionResponseThe result of a `DeleteExpression` request. Specifies the expression being deleted. DeleteIndexFieldRequestContainer for the parameters to the `DeleteIndexField` operation. Specifies the name of the domain you want to update and the name of the index field you want to delete. DeleteIndexFieldResponseThe result of a `DeleteIndexField` request. DeleteSuggesterRequestContainer for the parameters to the `DeleteSuggester` operation. Specifies the name of the domain you want to update and name of the suggester you want to delete. DeleteSuggesterResponseThe result of a `DeleteSuggester` request. Contains the status of the deleted suggester. DescribeAnalysisSchemesRequestContainer for the parameters to the `DescribeAnalysisSchemes` operation. Specifies the name of the domain you want to describe. To limit the response to particular analysis schemes, specify the names of the analysis schemes you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. DescribeAnalysisSchemesResponseThe result of a `DescribeAnalysisSchemes` request. Contains the analysis schemes configured for the domain specified in the request. DescribeAvailabilityOptionsRequestContainer for the parameters to the `DescribeAvailabilityOptions` operation. Specifies the name of the domain you want to describe. To show the active configuration and exclude any pending changes, set the Deployed option to `true`. DescribeAvailabilityOptionsResponseThe result of a `DescribeAvailabilityOptions` request. Indicates whether or not the Multi-AZ option is enabled for the domain specified in the request. DescribeDomainEndpointOptionsRequestContainer for the parameters to the `DescribeDomainEndpointOptions` operation. Specify the name of the domain you want to describe. To show the active configuration and exclude any pending changes, set the Deployed option to `true`. DescribeDomainEndpointOptionsResponseThe result of a `DescribeDomainEndpointOptions` request. Contains the status and configuration of a search domain's endpoint options. DescribeDomainsRequestContainer for the parameters to the `DescribeDomains` operation. By default shows the status of all domains. To restrict the response to particular domains, specify the names of the domains you want to describe. DescribeDomainsResponseThe result of a `DescribeDomains` request. Contains the status of the domains specified in the request or all domains owned by the account. DescribeExpressionsRequestContainer for the parameters to the `DescribeDomains` operation. Specifies the name of the domain you want to describe. To restrict the response to particular expressions, specify the names of the expressions you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. DescribeExpressionsResponseThe result of a `DescribeExpressions` request. Contains the expressions configured for the domain specified in the request. DescribeIndexFieldsRequestContainer for the parameters to the `DescribeIndexFields` operation. Specifies the name of the domain you want to describe. To restrict the response to particular index fields, specify the names of the index fields you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. DescribeIndexFieldsResponseThe result of a `DescribeIndexFields` request. Contains the index fields configured for the domain specified in the request. DescribeScalingParametersRequestContainer for the parameters to the `DescribeScalingParameters` operation. Specifies the name of the domain you want to describe. DescribeScalingParametersResponseThe result of a `DescribeScalingParameters` request. Contains the scaling parameters configured for the domain specified in the request. DescribeServiceAccessPoliciesRequestContainer for the parameters to the `DescribeServiceAccessPolicies` operation. Specifies the name of the domain you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. DescribeServiceAccessPoliciesResponseThe result of a `DescribeServiceAccessPolicies` request. DescribeSuggestersRequestContainer for the parameters to the `DescribeSuggester` operation. Specifies the name of the domain you want to describe. To restrict the response to particular suggesters, specify the names of the suggesters you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. DescribeSuggestersResponseThe result of a `DescribeSuggesters` request. DocumentSuggesterOptionsOptions for a search suggester. DomainEndpointOptionsThe domain's endpoint options. DomainEndpointOptionsStatusThe configuration and status of the domain's endpoint options. DomainStatusThe current status of the search domain. DoubleArrayOptionsOptions for a field that contains an array of double-precision 64-bit floating point values. Present if `IndexFieldType` specifies the field is of type `double-array`. All options are enabled by default. DoubleOptionsOptions for a double-precision 64-bit floating point field. Present if `IndexFieldType` specifies the field is of type `double`. All options are enabled by default. ExpressionA named expression that can be evaluated at search time. Can be used to sort the search results, define other expressions, or return computed information in the search results. ExpressionStatusThe value of an `Expression` and its current status. IndexDocumentsRequestContainer for the parameters to the `IndexDocuments` operation. Specifies the name of the domain you want to re-index. IndexDocumentsResponseThe result of an `IndexDocuments` request. Contains the status of the indexing operation, including the fields being indexed. IndexFieldConfiguration information for a field in the index, including its name, type, and options. The supported options depend on the `IndexFieldType`. IndexFieldStatusThe value of an `IndexField` and its current status. IntArrayOptionsOptions for a field that contains an array of 64-bit signed integers. Present if `IndexFieldType` specifies the field is of type `int-array`. All options are enabled by default. IntOptionsOptions for a 64-bit signed integer field. Present if `IndexFieldType` specifies the field is of type `int`. All options are enabled by default. LatLonOptionsOptions for a latlon field. A latlon field contains a location stored as a latitude and longitude value pair. Present if `IndexFieldType` specifies the field is of type `latlon`. All options are enabled by default. LimitsListDomainNamesResponseThe result of a `ListDomainNames` request. Contains a list of the domains owned by an account. LiteralArrayOptionsOptions for a field that contains an array of literal strings. Present if `IndexFieldType` specifies the field is of type `literal-array`. All options are enabled by default. LiteralOptionsOptions for literal field. Present if `IndexFieldType` specifies the field is of type `literal`. All options are enabled by default. OptionStatusThe status of domain configuration option. ScalingParametersThe desired instance type and desired number of replicas of each index partition. ScalingParametersStatusThe status and configuration of a search domain's scaling parameters. ServiceEndpointThe endpoint to which service requests can be submitted. SuggesterConfiguration information for a search suggester. Each suggester has a unique name and specifies the text field you want to use for suggestions. The following options can be configured for a suggester: `FuzzyMatching`, `SortExpression`. SuggesterStatusThe value of a `Suggester` and its current status. TextArrayOptionsOptions for a field that contains an array of text strings. Present if `IndexFieldType` specifies the field is of type `text-array`. A `text-array` field is always searchable. All options are enabled by default. TextOptionsOptions for text field. Present if `IndexFieldType` specifies the field is of type `text`. A `text` field is always searchable. All options are enabled by default. UpdateAvailabilityOptionsRequestContainer for the parameters to the `UpdateAvailabilityOptions` operation. Specifies the name of the domain you want to update and the Multi-AZ availability option. UpdateAvailabilityOptionsResponseThe result of a `UpdateAvailabilityOptions` request. Contains the status of the domain's availability options. UpdateDomainEndpointOptionsRequestContainer for the parameters to the `UpdateDomainEndpointOptions` operation. Specifies the name of the domain you want to update and the domain endpoint options. UpdateDomainEndpointOptionsResponseThe result of a `UpdateDomainEndpointOptions` request. Contains the configuration and status of the domain's endpoint options. UpdateScalingParametersRequestContainer for the parameters to the `UpdateScalingParameters` operation. Specifies the name of the domain you want to update and the scaling parameters you want to configure. UpdateScalingParametersResponseThe result of a `UpdateScalingParameters` request. Contains the status of the newly-configured scaling parameters. UpdateServiceAccessPoliciesRequestContainer for the parameters to the `UpdateServiceAccessPolicies` operation. Specifies the name of the domain you want to update and the access rules you want to configure. UpdateServiceAccessPoliciesResponseThe result of an `UpdateServiceAccessPolicies` request. Contains the new access policies. Enums --- BuildSuggestersErrorErrors returned by BuildSuggesters CreateDomainErrorErrors returned by CreateDomain DefineAnalysisSchemeErrorErrors returned by DefineAnalysisScheme DefineExpressionErrorErrors returned by DefineExpression DefineIndexFieldErrorErrors returned by DefineIndexField DefineSuggesterErrorErrors returned by DefineSuggester DeleteAnalysisSchemeErrorErrors returned by DeleteAnalysisScheme DeleteDomainErrorErrors returned by DeleteDomain DeleteExpressionErrorErrors returned by DeleteExpression DeleteIndexFieldErrorErrors returned by DeleteIndexField DeleteSuggesterErrorErrors returned by DeleteSuggester DescribeAnalysisSchemesErrorErrors returned by DescribeAnalysisSchemes DescribeAvailabilityOptionsErrorErrors returned by DescribeAvailabilityOptions DescribeDomainEndpointOptionsErrorErrors returned by DescribeDomainEndpointOptions DescribeDomainsErrorErrors returned by DescribeDomains DescribeExpressionsErrorErrors returned by DescribeExpressions DescribeIndexFieldsErrorErrors returned by DescribeIndexFields DescribeScalingParametersErrorErrors returned by DescribeScalingParameters DescribeServiceAccessPoliciesErrorErrors returned by DescribeServiceAccessPolicies DescribeSuggestersErrorErrors returned by DescribeSuggesters IndexDocumentsErrorErrors returned by IndexDocuments ListDomainNamesErrorErrors returned by ListDomainNames UpdateAvailabilityOptionsErrorErrors returned by UpdateAvailabilityOptions UpdateDomainEndpointOptionsErrorErrors returned by UpdateDomainEndpointOptions UpdateScalingParametersErrorErrors returned by UpdateScalingParameters UpdateServiceAccessPoliciesErrorErrors returned by UpdateServiceAccessPolicies Traits --- CloudSearchTrait representing the capabilities of the Amazon CloudSearch API. Amazon CloudSearch clients implement this trait. Struct rusoto_cloudsearch::CloudSearchClient === ``` pub struct CloudSearchClient { /* private fields */ } ``` A client for the Amazon CloudSearch API. Implementations --- source### impl CloudSearchClient source#### pub fn new(region: Region) -> CloudSearchClient Creates a client backed by the default tokio event loop. The client will use the default credentials provider and tls client. source#### pub fn new_with<P, D>(    request_dispatcher: D,     credentials_provider: P,     region: Region) -> CloudSearchClient where    P: ProvideAwsCredentials + Send + Sync + 'static,    D: DispatchSignedRequest + Send + Sync + 'static, source#### pub fn new_with_client(client: Client, region: Region) -> CloudSearchClient Trait Implementations --- source### impl Clone for CloudSearchClient source#### fn clone(&self) -> CloudSearchClient Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl CloudSearch for CloudSearchClient source#### fn build_suggesters<'life0, 'async_trait>(    &'life0 self,     input: BuildSuggestersRequest) -> Pin<Box<dyn Future<Output = Result<BuildSuggestersResponse, RusotoError<BuildSuggestersError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Indexes the search suggestions. For more information, see Configuring Suggesters in the *Amazon CloudSearch Developer Guide*. source#### fn create_domain<'life0, 'async_trait>(    &'life0 self,     input: CreateDomainRequest) -> Pin<Box<dyn Future<Output = Result<CreateDomainResponse, RusotoError<CreateDomainError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Creates a new search domain. For more information, see Creating a Search Domain in the *Amazon CloudSearch Developer Guide*. source#### fn define_analysis_scheme<'life0, 'async_trait>(    &'life0 self,     input: DefineAnalysisSchemeRequest) -> Pin<Box<dyn Future<Output = Result<DefineAnalysisSchemeResponse, RusotoError<DefineAnalysisSchemeError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures an analysis scheme that can be applied to a `text` or `text-array` field to define language-specific text processing options. For more information, see Configuring Analysis Schemes in the *Amazon CloudSearch Developer Guide*. source#### fn define_expression<'life0, 'async_trait>(    &'life0 self,     input: DefineExpressionRequest) -> Pin<Box<dyn Future<Output = Result<DefineExpressionResponse, RusotoError<DefineExpressionError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures an `Expression` for the search domain. Used to create new expressions and modify existing ones. If the expression exists, the new configuration replaces the old one. For more information, see Configuring Expressions in the *Amazon CloudSearch Developer Guide*. source#### fn define_index_field<'life0, 'async_trait>(    &'life0 self,     input: DefineIndexFieldRequest) -> Pin<Box<dyn Future<Output = Result<DefineIndexFieldResponse, RusotoError<DefineIndexFieldError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures an `IndexField` for the search domain. Used to create new fields and modify existing ones. You must specify the name of the domain you are configuring and an index field configuration. The index field configuration specifies a unique name, the index field type, and the options you want to configure for the field. The options you can specify depend on the `IndexFieldType`. If the field exists, the new configuration replaces the old one. For more information, see Configuring Index Fields in the *Amazon CloudSearch Developer Guide*. source#### fn define_suggester<'life0, 'async_trait>(    &'life0 self,     input: DefineSuggesterRequest) -> Pin<Box<dyn Future<Output = Result<DefineSuggesterResponse, RusotoError<DefineSuggesterError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures a suggester for a domain. A suggester enables you to display possible matches before users finish typing their queries. When you configure a suggester, you must specify the name of the text field you want to search for possible matches and a unique name for the suggester. For more information, see Getting Search Suggestions in the *Amazon CloudSearch Developer Guide*. source#### fn delete_analysis_scheme<'life0, 'async_trait>(    &'life0 self,     input: DeleteAnalysisSchemeRequest) -> Pin<Box<dyn Future<Output = Result<DeleteAnalysisSchemeResponse, RusotoError<DeleteAnalysisSchemeError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Deletes an analysis scheme. For more information, see Configuring Analysis Schemes in the *Amazon CloudSearch Developer Guide*. source#### fn delete_domain<'life0, 'async_trait>(    &'life0 self,     input: DeleteDomainRequest) -> Pin<Box<dyn Future<Output = Result<DeleteDomainResponse, RusotoError<DeleteDomainError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Permanently deletes a search domain and all of its data. Once a domain has been deleted, it cannot be recovered. For more information, see Deleting a Search Domain in the *Amazon CloudSearch Developer Guide*. source#### fn delete_expression<'life0, 'async_trait>(    &'life0 self,     input: DeleteExpressionRequest) -> Pin<Box<dyn Future<Output = Result<DeleteExpressionResponse, RusotoError<DeleteExpressionError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Removes an `Expression` from the search domain. For more information, see Configuring Expressions in the *Amazon CloudSearch Developer Guide*. source#### fn delete_index_field<'life0, 'async_trait>(    &'life0 self,     input: DeleteIndexFieldRequest) -> Pin<Box<dyn Future<Output = Result<DeleteIndexFieldResponse, RusotoError<DeleteIndexFieldError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Removes an `IndexField` from the search domain. For more information, see Configuring Index Fields in the *Amazon CloudSearch Developer Guide*. source#### fn delete_suggester<'life0, 'async_trait>(    &'life0 self,     input: DeleteSuggesterRequest) -> Pin<Box<dyn Future<Output = Result<DeleteSuggesterResponse, RusotoError<DeleteSuggesterError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Deletes a suggester. For more information, see Getting Search Suggestions in the *Amazon CloudSearch Developer Guide*. source#### fn describe_analysis_schemes<'life0, 'async_trait>(    &'life0 self,     input: DescribeAnalysisSchemesRequest) -> Pin<Box<dyn Future<Output = Result<DescribeAnalysisSchemesResponse, RusotoError<DescribeAnalysisSchemesError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets the analysis schemes configured for a domain. An analysis scheme defines language-specific text processing options for a `text` field. Can be limited to specific analysis schemes by name. By default, shows all analysis schemes and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Configuring Analysis Schemes in the *Amazon CloudSearch Developer Guide*. source#### fn describe_availability_options<'life0, 'async_trait>(    &'life0 self,     input: DescribeAvailabilityOptionsRequest) -> Pin<Box<dyn Future<Output = Result<DescribeAvailabilityOptionsResponse, RusotoError<DescribeAvailabilityOptionsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets the availability options configured for a domain. By default, shows the configuration with any pending changes. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Configuring Availability Options in the *Amazon CloudSearch Developer Guide*. source#### fn describe_domain_endpoint_options<'life0, 'async_trait>(    &'life0 self,     input: DescribeDomainEndpointOptionsRequest) -> Pin<Box<dyn Future<Output = Result<DescribeDomainEndpointOptionsResponse, RusotoError<DescribeDomainEndpointOptionsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Returns the domain's endpoint options, specifically whether all requests to the domain must arrive over HTTPS. For more information, see Configuring Domain Endpoint Options in the *Amazon CloudSearch Developer Guide*. source#### fn describe_domains<'life0, 'async_trait>(    &'life0 self,     input: DescribeDomainsRequest) -> Pin<Box<dyn Future<Output = Result<DescribeDomainsResponse, RusotoError<DescribeDomainsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets information about the search domains owned by this account. Can be limited to specific domains. Shows all domains by default. To get the number of searchable documents in a domain, use the console or submit a `matchall` request to your domain's search endpoint: `q=matchall&amp;q.parser=structured&amp;size=0`. For more information, see Getting Information about a Search Domain in the *Amazon CloudSearch Developer Guide*. source#### fn describe_expressions<'life0, 'async_trait>(    &'life0 self,     input: DescribeExpressionsRequest) -> Pin<Box<dyn Future<Output = Result<DescribeExpressionsResponse, RusotoError<DescribeExpressionsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets the expressions configured for the search domain. Can be limited to specific expressions by name. By default, shows all expressions and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Configuring Expressions in the *Amazon CloudSearch Developer Guide*. source#### fn describe_index_fields<'life0, 'async_trait>(    &'life0 self,     input: DescribeIndexFieldsRequest) -> Pin<Box<dyn Future<Output = Result<DescribeIndexFieldsResponse, RusotoError<DescribeIndexFieldsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets information about the index fields configured for the search domain. Can be limited to specific fields by name. By default, shows all fields and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Getting Domain Information in the *Amazon CloudSearch Developer Guide*. source#### fn describe_scaling_parameters<'life0, 'async_trait>(    &'life0 self,     input: DescribeScalingParametersRequest) -> Pin<Box<dyn Future<Output = Result<DescribeScalingParametersResponse, RusotoError<DescribeScalingParametersError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets the scaling parameters configured for a domain. A domain's scaling parameters specify the desired search instance type and replication count. For more information, see Configuring Scaling Options in the *Amazon CloudSearch Developer Guide*. source#### fn describe_service_access_policies<'life0, 'async_trait>(    &'life0 self,     input: DescribeServiceAccessPoliciesRequest) -> Pin<Box<dyn Future<Output = Result<DescribeServiceAccessPoliciesResponse, RusotoError<DescribeServiceAccessPoliciesError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets information about the access policies that control access to the domain's document and search endpoints. By default, shows the configuration with any pending changes. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Configuring Access for a Search Domain in the *Amazon CloudSearch Developer Guide*. source#### fn describe_suggesters<'life0, 'async_trait>(    &'life0 self,     input: DescribeSuggestersRequest) -> Pin<Box<dyn Future<Output = Result<DescribeSuggestersResponse, RusotoError<DescribeSuggestersError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets the suggesters configured for a domain. A suggester enables you to display possible matches before users finish typing their queries. Can be limited to specific suggesters by name. By default, shows all suggesters and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Getting Search Suggestions in the *Amazon CloudSearch Developer Guide*. source#### fn index_documents<'life0, 'async_trait>(    &'life0 self,     input: IndexDocumentsRequest) -> Pin<Box<dyn Future<Output = Result<IndexDocumentsResponse, RusotoError<IndexDocumentsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Tells the search domain to start indexing its documents using the latest indexing options. This operation must be invoked to activate options whose OptionStatus is `RequiresIndexDocuments`. source#### fn list_domain_names<'life0, 'async_trait>(    &'life0 self) -> Pin<Box<dyn Future<Output = Result<ListDomainNamesResponse, RusotoError<ListDomainNamesError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Lists all search domains owned by an account. source#### fn update_availability_options<'life0, 'async_trait>(    &'life0 self,     input: UpdateAvailabilityOptionsRequest) -> Pin<Box<dyn Future<Output = Result<UpdateAvailabilityOptionsResponse, RusotoError<UpdateAvailabilityOptionsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures the availability options for a domain. Enabling the Multi-AZ option expands an Amazon CloudSearch domain to an additional Availability Zone in the same Region to increase fault tolerance in the event of a service disruption. Changes to the Multi-AZ option can take about half an hour to become active. For more information, see Configuring Availability Options in the *Amazon CloudSearch Developer Guide*. source#### fn update_domain_endpoint_options<'life0, 'async_trait>(    &'life0 self,     input: UpdateDomainEndpointOptionsRequest) -> Pin<Box<dyn Future<Output = Result<UpdateDomainEndpointOptionsResponse, RusotoError<UpdateDomainEndpointOptionsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Updates the domain's endpoint options, specifically whether all requests to the domain must arrive over HTTPS. For more information, see Configuring Domain Endpoint Options in the *Amazon CloudSearch Developer Guide*. source#### fn update_scaling_parameters<'life0, 'async_trait>(    &'life0 self,     input: UpdateScalingParametersRequest) -> Pin<Box<dyn Future<Output = Result<UpdateScalingParametersResponse, RusotoError<UpdateScalingParametersError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures scaling parameters for a domain. A domain's scaling parameters specify the desired search instance type and replication count. Amazon CloudSearch will still automatically scale your domain based on the volume of data and traffic, but not below the desired instance type and replication count. If the Multi-AZ option is enabled, these values control the resources used per Availability Zone. For more information, see Configuring Scaling Options in the *Amazon CloudSearch Developer Guide*. source#### fn update_service_access_policies<'life0, 'async_trait>(    &'life0 self,     input: UpdateServiceAccessPoliciesRequest) -> Pin<Box<dyn Future<Output = Result<UpdateServiceAccessPoliciesResponse, RusotoError<UpdateServiceAccessPoliciesError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures the access rules that control access to the domain's document and search endpoints. For more information, see Configuring Access for an Amazon CloudSearch Domain. Auto Trait Implementations --- ### impl !RefUnwindSafe for CloudSearchClient ### impl Send for CloudSearchClient ### impl Sync for CloudSearchClient ### impl Unpin for CloudSearchClient ### impl !UnwindSafe for CloudSearchClient Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Trait rusoto_cloudsearch::CloudSearch === ``` pub trait CloudSearch { fn build_suggesters<'life0, 'async_trait>(         &'life0 self,         input: BuildSuggestersRequest     ) -> Pin<Box<dyn Future<Output = Result<BuildSuggestersResponse, RusotoError<BuildSuggestersError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn create_domain<'life0, 'async_trait>(         &'life0 self,         input: CreateDomainRequest     ) -> Pin<Box<dyn Future<Output = Result<CreateDomainResponse, RusotoError<CreateDomainError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn define_analysis_scheme<'life0, 'async_trait>(         &'life0 self,         input: DefineAnalysisSchemeRequest     ) -> Pin<Box<dyn Future<Output = Result<DefineAnalysisSchemeResponse, RusotoError<DefineAnalysisSchemeError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn define_expression<'life0, 'async_trait>(         &'life0 self,         input: DefineExpressionRequest     ) -> Pin<Box<dyn Future<Output = Result<DefineExpressionResponse, RusotoError<DefineExpressionError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn define_index_field<'life0, 'async_trait>(         &'life0 self,         input: DefineIndexFieldRequest     ) -> Pin<Box<dyn Future<Output = Result<DefineIndexFieldResponse, RusotoError<DefineIndexFieldError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn define_suggester<'life0, 'async_trait>(         &'life0 self,         input: DefineSuggesterRequest     ) -> Pin<Box<dyn Future<Output = Result<DefineSuggesterResponse, RusotoError<DefineSuggesterError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn delete_analysis_scheme<'life0, 'async_trait>(         &'life0 self,         input: DeleteAnalysisSchemeRequest     ) -> Pin<Box<dyn Future<Output = Result<DeleteAnalysisSchemeResponse, RusotoError<DeleteAnalysisSchemeError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn delete_domain<'life0, 'async_trait>(         &'life0 self,         input: DeleteDomainRequest     ) -> Pin<Box<dyn Future<Output = Result<DeleteDomainResponse, RusotoError<DeleteDomainError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn delete_expression<'life0, 'async_trait>(         &'life0 self,         input: DeleteExpressionRequest     ) -> Pin<Box<dyn Future<Output = Result<DeleteExpressionResponse, RusotoError<DeleteExpressionError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn delete_index_field<'life0, 'async_trait>(         &'life0 self,         input: DeleteIndexFieldRequest     ) -> Pin<Box<dyn Future<Output = Result<DeleteIndexFieldResponse, RusotoError<DeleteIndexFieldError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn delete_suggester<'life0, 'async_trait>(         &'life0 self,         input: DeleteSuggesterRequest     ) -> Pin<Box<dyn Future<Output = Result<DeleteSuggesterResponse, RusotoError<DeleteSuggesterError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn describe_analysis_schemes<'life0, 'async_trait>(         &'life0 self,         input: DescribeAnalysisSchemesRequest     ) -> Pin<Box<dyn Future<Output = Result<DescribeAnalysisSchemesResponse, RusotoError<DescribeAnalysisSchemesError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn describe_availability_options<'life0, 'async_trait>(         &'life0 self,         input: DescribeAvailabilityOptionsRequest     ) -> Pin<Box<dyn Future<Output = Result<DescribeAvailabilityOptionsResponse, RusotoError<DescribeAvailabilityOptionsError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn describe_domain_endpoint_options<'life0, 'async_trait>(         &'life0 self,         input: DescribeDomainEndpointOptionsRequest     ) -> Pin<Box<dyn Future<Output = Result<DescribeDomainEndpointOptionsResponse, RusotoError<DescribeDomainEndpointOptionsError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn describe_domains<'life0, 'async_trait>(         &'life0 self,         input: DescribeDomainsRequest     ) -> Pin<Box<dyn Future<Output = Result<DescribeDomainsResponse, RusotoError<DescribeDomainsError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn describe_expressions<'life0, 'async_trait>(         &'life0 self,         input: DescribeExpressionsRequest     ) -> Pin<Box<dyn Future<Output = Result<DescribeExpressionsResponse, RusotoError<DescribeExpressionsError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn describe_index_fields<'life0, 'async_trait>(         &'life0 self,         input: DescribeIndexFieldsRequest     ) -> Pin<Box<dyn Future<Output = Result<DescribeIndexFieldsResponse, RusotoError<DescribeIndexFieldsError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn describe_scaling_parameters<'life0, 'async_trait>(         &'life0 self,         input: DescribeScalingParametersRequest     ) -> Pin<Box<dyn Future<Output = Result<DescribeScalingParametersResponse, RusotoError<DescribeScalingParametersError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn describe_service_access_policies<'life0, 'async_trait>(         &'life0 self,         input: DescribeServiceAccessPoliciesRequest     ) -> Pin<Box<dyn Future<Output = Result<DescribeServiceAccessPoliciesResponse, RusotoError<DescribeServiceAccessPoliciesError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn describe_suggesters<'life0, 'async_trait>(         &'life0 self,         input: DescribeSuggestersRequest     ) -> Pin<Box<dyn Future<Output = Result<DescribeSuggestersResponse, RusotoError<DescribeSuggestersError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn index_documents<'life0, 'async_trait>(         &'life0 self,         input: IndexDocumentsRequest     ) -> Pin<Box<dyn Future<Output = Result<IndexDocumentsResponse, RusotoError<IndexDocumentsError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn list_domain_names<'life0, 'async_trait>(         &'life0 self     ) -> Pin<Box<dyn Future<Output = Result<ListDomainNamesResponse, RusotoError<ListDomainNamesError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn update_availability_options<'life0, 'async_trait>(         &'life0 self,         input: UpdateAvailabilityOptionsRequest     ) -> Pin<Box<dyn Future<Output = Result<UpdateAvailabilityOptionsResponse, RusotoError<UpdateAvailabilityOptionsError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn update_domain_endpoint_options<'life0, 'async_trait>(         &'life0 self,         input: UpdateDomainEndpointOptionsRequest     ) -> Pin<Box<dyn Future<Output = Result<UpdateDomainEndpointOptionsResponse, RusotoError<UpdateDomainEndpointOptionsError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn update_scaling_parameters<'life0, 'async_trait>(         &'life0 self,         input: UpdateScalingParametersRequest     ) -> Pin<Box<dyn Future<Output = Result<UpdateScalingParametersResponse, RusotoError<UpdateScalingParametersError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; fn update_service_access_policies<'life0, 'async_trait>(         &'life0 self,         input: UpdateServiceAccessPoliciesRequest     ) -> Pin<Box<dyn Future<Output = Result<UpdateServiceAccessPoliciesResponse, RusotoError<UpdateServiceAccessPoliciesError>>> + Send + 'async_trait>    where         'life0: 'async_trait,         Self: 'async_trait; } ``` Trait representing the capabilities of the Amazon CloudSearch API. Amazon CloudSearch clients implement this trait. Required Methods --- source#### fn build_suggesters<'life0, 'async_trait>(    &'life0 self,     input: BuildSuggestersRequest) -> Pin<Box<dyn Future<Output = Result<BuildSuggestersResponse, RusotoError<BuildSuggestersError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Indexes the search suggestions. For more information, see Configuring Suggesters in the *Amazon CloudSearch Developer Guide*. source#### fn create_domain<'life0, 'async_trait>(    &'life0 self,     input: CreateDomainRequest) -> Pin<Box<dyn Future<Output = Result<CreateDomainResponse, RusotoError<CreateDomainError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Creates a new search domain. For more information, see Creating a Search Domain in the *Amazon CloudSearch Developer Guide*. source#### fn define_analysis_scheme<'life0, 'async_trait>(    &'life0 self,     input: DefineAnalysisSchemeRequest) -> Pin<Box<dyn Future<Output = Result<DefineAnalysisSchemeResponse, RusotoError<DefineAnalysisSchemeError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures an analysis scheme that can be applied to a `text` or `text-array` field to define language-specific text processing options. For more information, see Configuring Analysis Schemes in the *Amazon CloudSearch Developer Guide*. source#### fn define_expression<'life0, 'async_trait>(    &'life0 self,     input: DefineExpressionRequest) -> Pin<Box<dyn Future<Output = Result<DefineExpressionResponse, RusotoError<DefineExpressionError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures an `Expression` for the search domain. Used to create new expressions and modify existing ones. If the expression exists, the new configuration replaces the old one. For more information, see Configuring Expressions in the *Amazon CloudSearch Developer Guide*. source#### fn define_index_field<'life0, 'async_trait>(    &'life0 self,     input: DefineIndexFieldRequest) -> Pin<Box<dyn Future<Output = Result<DefineIndexFieldResponse, RusotoError<DefineIndexFieldError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures an `IndexField` for the search domain. Used to create new fields and modify existing ones. You must specify the name of the domain you are configuring and an index field configuration. The index field configuration specifies a unique name, the index field type, and the options you want to configure for the field. The options you can specify depend on the `IndexFieldType`. If the field exists, the new configuration replaces the old one. For more information, see Configuring Index Fields in the *Amazon CloudSearch Developer Guide*. source#### fn define_suggester<'life0, 'async_trait>(    &'life0 self,     input: DefineSuggesterRequest) -> Pin<Box<dyn Future<Output = Result<DefineSuggesterResponse, RusotoError<DefineSuggesterError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures a suggester for a domain. A suggester enables you to display possible matches before users finish typing their queries. When you configure a suggester, you must specify the name of the text field you want to search for possible matches and a unique name for the suggester. For more information, see Getting Search Suggestions in the *Amazon CloudSearch Developer Guide*. source#### fn delete_analysis_scheme<'life0, 'async_trait>(    &'life0 self,     input: DeleteAnalysisSchemeRequest) -> Pin<Box<dyn Future<Output = Result<DeleteAnalysisSchemeResponse, RusotoError<DeleteAnalysisSchemeError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Deletes an analysis scheme. For more information, see Configuring Analysis Schemes in the *Amazon CloudSearch Developer Guide*. source#### fn delete_domain<'life0, 'async_trait>(    &'life0 self,     input: DeleteDomainRequest) -> Pin<Box<dyn Future<Output = Result<DeleteDomainResponse, RusotoError<DeleteDomainError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Permanently deletes a search domain and all of its data. Once a domain has been deleted, it cannot be recovered. For more information, see Deleting a Search Domain in the *Amazon CloudSearch Developer Guide*. source#### fn delete_expression<'life0, 'async_trait>(    &'life0 self,     input: DeleteExpressionRequest) -> Pin<Box<dyn Future<Output = Result<DeleteExpressionResponse, RusotoError<DeleteExpressionError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Removes an `Expression` from the search domain. For more information, see Configuring Expressions in the *Amazon CloudSearch Developer Guide*. source#### fn delete_index_field<'life0, 'async_trait>(    &'life0 self,     input: DeleteIndexFieldRequest) -> Pin<Box<dyn Future<Output = Result<DeleteIndexFieldResponse, RusotoError<DeleteIndexFieldError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Removes an `IndexField` from the search domain. For more information, see Configuring Index Fields in the *Amazon CloudSearch Developer Guide*. source#### fn delete_suggester<'life0, 'async_trait>(    &'life0 self,     input: DeleteSuggesterRequest) -> Pin<Box<dyn Future<Output = Result<DeleteSuggesterResponse, RusotoError<DeleteSuggesterError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Deletes a suggester. For more information, see Getting Search Suggestions in the *Amazon CloudSearch Developer Guide*. source#### fn describe_analysis_schemes<'life0, 'async_trait>(    &'life0 self,     input: DescribeAnalysisSchemesRequest) -> Pin<Box<dyn Future<Output = Result<DescribeAnalysisSchemesResponse, RusotoError<DescribeAnalysisSchemesError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets the analysis schemes configured for a domain. An analysis scheme defines language-specific text processing options for a `text` field. Can be limited to specific analysis schemes by name. By default, shows all analysis schemes and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Configuring Analysis Schemes in the *Amazon CloudSearch Developer Guide*. source#### fn describe_availability_options<'life0, 'async_trait>(    &'life0 self,     input: DescribeAvailabilityOptionsRequest) -> Pin<Box<dyn Future<Output = Result<DescribeAvailabilityOptionsResponse, RusotoError<DescribeAvailabilityOptionsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets the availability options configured for a domain. By default, shows the configuration with any pending changes. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Configuring Availability Options in the *Amazon CloudSearch Developer Guide*. source#### fn describe_domain_endpoint_options<'life0, 'async_trait>(    &'life0 self,     input: DescribeDomainEndpointOptionsRequest) -> Pin<Box<dyn Future<Output = Result<DescribeDomainEndpointOptionsResponse, RusotoError<DescribeDomainEndpointOptionsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Returns the domain's endpoint options, specifically whether all requests to the domain must arrive over HTTPS. For more information, see Configuring Domain Endpoint Options in the *Amazon CloudSearch Developer Guide*. source#### fn describe_domains<'life0, 'async_trait>(    &'life0 self,     input: DescribeDomainsRequest) -> Pin<Box<dyn Future<Output = Result<DescribeDomainsResponse, RusotoError<DescribeDomainsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets information about the search domains owned by this account. Can be limited to specific domains. Shows all domains by default. To get the number of searchable documents in a domain, use the console or submit a `matchall` request to your domain's search endpoint: `q=matchall&amp;q.parser=structured&amp;size=0`. For more information, see Getting Information about a Search Domain in the *Amazon CloudSearch Developer Guide*. source#### fn describe_expressions<'life0, 'async_trait>(    &'life0 self,     input: DescribeExpressionsRequest) -> Pin<Box<dyn Future<Output = Result<DescribeExpressionsResponse, RusotoError<DescribeExpressionsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets the expressions configured for the search domain. Can be limited to specific expressions by name. By default, shows all expressions and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Configuring Expressions in the *Amazon CloudSearch Developer Guide*. source#### fn describe_index_fields<'life0, 'async_trait>(    &'life0 self,     input: DescribeIndexFieldsRequest) -> Pin<Box<dyn Future<Output = Result<DescribeIndexFieldsResponse, RusotoError<DescribeIndexFieldsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets information about the index fields configured for the search domain. Can be limited to specific fields by name. By default, shows all fields and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Getting Domain Information in the *Amazon CloudSearch Developer Guide*. source#### fn describe_scaling_parameters<'life0, 'async_trait>(    &'life0 self,     input: DescribeScalingParametersRequest) -> Pin<Box<dyn Future<Output = Result<DescribeScalingParametersResponse, RusotoError<DescribeScalingParametersError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets the scaling parameters configured for a domain. A domain's scaling parameters specify the desired search instance type and replication count. For more information, see Configuring Scaling Options in the *Amazon CloudSearch Developer Guide*. source#### fn describe_service_access_policies<'life0, 'async_trait>(    &'life0 self,     input: DescribeServiceAccessPoliciesRequest) -> Pin<Box<dyn Future<Output = Result<DescribeServiceAccessPoliciesResponse, RusotoError<DescribeServiceAccessPoliciesError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets information about the access policies that control access to the domain's document and search endpoints. By default, shows the configuration with any pending changes. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Configuring Access for a Search Domain in the *Amazon CloudSearch Developer Guide*. source#### fn describe_suggesters<'life0, 'async_trait>(    &'life0 self,     input: DescribeSuggestersRequest) -> Pin<Box<dyn Future<Output = Result<DescribeSuggestersResponse, RusotoError<DescribeSuggestersError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Gets the suggesters configured for a domain. A suggester enables you to display possible matches before users finish typing their queries. Can be limited to specific suggesters by name. By default, shows all suggesters and includes any pending changes to the configuration. Set the `Deployed` option to `true` to show the active configuration and exclude pending changes. For more information, see Getting Search Suggestions in the *Amazon CloudSearch Developer Guide*. source#### fn index_documents<'life0, 'async_trait>(    &'life0 self,     input: IndexDocumentsRequest) -> Pin<Box<dyn Future<Output = Result<IndexDocumentsResponse, RusotoError<IndexDocumentsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Tells the search domain to start indexing its documents using the latest indexing options. This operation must be invoked to activate options whose OptionStatus is `RequiresIndexDocuments`. source#### fn list_domain_names<'life0, 'async_trait>(    &'life0 self) -> Pin<Box<dyn Future<Output = Result<ListDomainNamesResponse, RusotoError<ListDomainNamesError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Lists all search domains owned by an account. source#### fn update_availability_options<'life0, 'async_trait>(    &'life0 self,     input: UpdateAvailabilityOptionsRequest) -> Pin<Box<dyn Future<Output = Result<UpdateAvailabilityOptionsResponse, RusotoError<UpdateAvailabilityOptionsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures the availability options for a domain. Enabling the Multi-AZ option expands an Amazon CloudSearch domain to an additional Availability Zone in the same Region to increase fault tolerance in the event of a service disruption. Changes to the Multi-AZ option can take about half an hour to become active. For more information, see Configuring Availability Options in the *Amazon CloudSearch Developer Guide*. source#### fn update_domain_endpoint_options<'life0, 'async_trait>(    &'life0 self,     input: UpdateDomainEndpointOptionsRequest) -> Pin<Box<dyn Future<Output = Result<UpdateDomainEndpointOptionsResponse, RusotoError<UpdateDomainEndpointOptionsError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Updates the domain's endpoint options, specifically whether all requests to the domain must arrive over HTTPS. For more information, see Configuring Domain Endpoint Options in the *Amazon CloudSearch Developer Guide*. source#### fn update_scaling_parameters<'life0, 'async_trait>(    &'life0 self,     input: UpdateScalingParametersRequest) -> Pin<Box<dyn Future<Output = Result<UpdateScalingParametersResponse, RusotoError<UpdateScalingParametersError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures scaling parameters for a domain. A domain's scaling parameters specify the desired search instance type and replication count. Amazon CloudSearch will still automatically scale your domain based on the volume of data and traffic, but not below the desired instance type and replication count. If the Multi-AZ option is enabled, these values control the resources used per Availability Zone. For more information, see Configuring Scaling Options in the *Amazon CloudSearch Developer Guide*. source#### fn update_service_access_policies<'life0, 'async_trait>(    &'life0 self,     input: UpdateServiceAccessPoliciesRequest) -> Pin<Box<dyn Future<Output = Result<UpdateServiceAccessPoliciesResponse, RusotoError<UpdateServiceAccessPoliciesError>>> + Send + 'async_trait>> where    'life0: 'async_trait,    Self: 'async_trait, Configures the access rules that control access to the domain's document and search endpoints. For more information, see Configuring Access for an Amazon CloudSearch Domain. Implementors --- source### impl CloudSearch for CloudSearchClient Struct rusoto_cloudsearch::AccessPoliciesStatus === ``` pub struct AccessPoliciesStatus { pub options: String, pub status: OptionStatus, } ``` The configured access rules for the domain's document and search endpoints, and the current status of those rules. Fields --- `options: String``status: OptionStatus`Trait Implementations --- source### impl Clone for AccessPoliciesStatus source#### fn clone(&self) -> AccessPoliciesStatus Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for AccessPoliciesStatus source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for AccessPoliciesStatus source#### fn default() -> AccessPoliciesStatus Returns the “default value” for a type. Read more source### impl PartialEq<AccessPoliciesStatus> for AccessPoliciesStatus source#### fn eq(&self, other: &AccessPoliciesStatus) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &AccessPoliciesStatus) -> bool This method tests for `!=`. source### impl StructuralPartialEq for AccessPoliciesStatus Auto Trait Implementations --- ### impl RefUnwindSafe for AccessPoliciesStatus ### impl Send for AccessPoliciesStatus ### impl Sync for AccessPoliciesStatus ### impl Unpin for AccessPoliciesStatus ### impl UnwindSafe for AccessPoliciesStatus Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::AnalysisOptions === ``` pub struct AnalysisOptions { pub algorithmic_stemming: Option<String>, pub japanese_tokenization_dictionary: Option<String>, pub stemming_dictionary: Option<String>, pub stopwords: Option<String>, pub synonyms: Option<String>, } ``` Synonyms, stopwords, and stemming options for an analysis scheme. Includes tokenization dictionary for Japanese. Fields --- `algorithmic_stemming: Option<String>`The level of algorithmic stemming to perform: `none`, `minimal`, `light`, or `full`. The available levels vary depending on the language. For more information, see Language Specific Text Processing Settings in the *Amazon CloudSearch Developer Guide* `japanese_tokenization_dictionary: Option<String>`A JSON array that contains a collection of terms, tokens, readings and part of speech for Japanese Tokenizaiton. The Japanese tokenization dictionary enables you to override the default tokenization for selected terms. This is only valid for Japanese language fields. `stemming_dictionary: Option<String>`A JSON object that contains a collection of string:value pairs that each map a term to its stem. For example, `{"term1": "stem1", "term2": "stem2", "term3": "stem3"}`. The stemming dictionary is applied in addition to any algorithmic stemming. This enables you to override the results of the algorithmic stemming to correct specific cases of overstemming or understemming. The maximum size of a stemming dictionary is 500 KB. `stopwords: Option<String>`A JSON array of terms to ignore during indexing and searching. For example, `["a", "an", "the", "of"]`. The stopwords dictionary must explicitly list each word you want to ignore. Wildcards and regular expressions are not supported. `synonyms: Option<String>`A JSON object that defines synonym groups and aliases. A synonym group is an array of arrays, where each sub-array is a group of terms where each term in the group is considered a synonym of every other term in the group. The aliases value is an object that contains a collection of string:value pairs where the string specifies a term and the array of values specifies each of the aliases for that term. An alias is considered a synonym of the specified term, but the term is not considered a synonym of the alias. For more information about specifying synonyms, see Synonyms in the *Amazon CloudSearch Developer Guide*. Trait Implementations --- source### impl Clone for AnalysisOptions source#### fn clone(&self) -> AnalysisOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for AnalysisOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for AnalysisOptions source#### fn default() -> AnalysisOptions Returns the “default value” for a type. Read more source### impl PartialEq<AnalysisOptions> for AnalysisOptions source#### fn eq(&self, other: &AnalysisOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &AnalysisOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for AnalysisOptions Auto Trait Implementations --- ### impl RefUnwindSafe for AnalysisOptions ### impl Send for AnalysisOptions ### impl Sync for AnalysisOptions ### impl Unpin for AnalysisOptions ### impl UnwindSafe for AnalysisOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::AnalysisScheme === ``` pub struct AnalysisScheme { pub analysis_options: Option<AnalysisOptions>, pub analysis_scheme_language: String, pub analysis_scheme_name: String, } ``` Configuration information for an analysis scheme. Each analysis scheme has a unique name and specifies the language of the text to be processed. The following options can be configured for an analysis scheme: `Synonyms`, `Stopwords`, `StemmingDictionary`, `JapaneseTokenizationDictionary` and `AlgorithmicStemming`. Fields --- `analysis_options: Option<AnalysisOptions>``analysis_scheme_language: String``analysis_scheme_name: String`Trait Implementations --- source### impl Clone for AnalysisScheme source#### fn clone(&self) -> AnalysisScheme Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for AnalysisScheme source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for AnalysisScheme source#### fn default() -> AnalysisScheme Returns the “default value” for a type. Read more source### impl PartialEq<AnalysisScheme> for AnalysisScheme source#### fn eq(&self, other: &AnalysisScheme) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &AnalysisScheme) -> bool This method tests for `!=`. source### impl StructuralPartialEq for AnalysisScheme Auto Trait Implementations --- ### impl RefUnwindSafe for AnalysisScheme ### impl Send for AnalysisScheme ### impl Sync for AnalysisScheme ### impl Unpin for AnalysisScheme ### impl UnwindSafe for AnalysisScheme Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::AnalysisSchemeStatus === ``` pub struct AnalysisSchemeStatus { pub options: AnalysisScheme, pub status: OptionStatus, } ``` The status and configuration of an `AnalysisScheme`. Fields --- `options: AnalysisScheme``status: OptionStatus`Trait Implementations --- source### impl Clone for AnalysisSchemeStatus source#### fn clone(&self) -> AnalysisSchemeStatus Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for AnalysisSchemeStatus source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for AnalysisSchemeStatus source#### fn default() -> AnalysisSchemeStatus Returns the “default value” for a type. Read more source### impl PartialEq<AnalysisSchemeStatus> for AnalysisSchemeStatus source#### fn eq(&self, other: &AnalysisSchemeStatus) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &AnalysisSchemeStatus) -> bool This method tests for `!=`. source### impl StructuralPartialEq for AnalysisSchemeStatus Auto Trait Implementations --- ### impl RefUnwindSafe for AnalysisSchemeStatus ### impl Send for AnalysisSchemeStatus ### impl Sync for AnalysisSchemeStatus ### impl Unpin for AnalysisSchemeStatus ### impl UnwindSafe for AnalysisSchemeStatus Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::AvailabilityOptionsStatus === ``` pub struct AvailabilityOptionsStatus { pub options: bool, pub status: OptionStatus, } ``` The status and configuration of the domain's availability options. Fields --- `options: bool`The availability options configured for the domain. `status: OptionStatus`Trait Implementations --- source### impl Clone for AvailabilityOptionsStatus source#### fn clone(&self) -> AvailabilityOptionsStatus Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for AvailabilityOptionsStatus source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for AvailabilityOptionsStatus source#### fn default() -> AvailabilityOptionsStatus Returns the “default value” for a type. Read more source### impl PartialEq<AvailabilityOptionsStatus> for AvailabilityOptionsStatus source#### fn eq(&self, other: &AvailabilityOptionsStatus) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &AvailabilityOptionsStatus) -> bool This method tests for `!=`. source### impl StructuralPartialEq for AvailabilityOptionsStatus Auto Trait Implementations --- ### impl RefUnwindSafe for AvailabilityOptionsStatus ### impl Send for AvailabilityOptionsStatus ### impl Sync for AvailabilityOptionsStatus ### impl Unpin for AvailabilityOptionsStatus ### impl UnwindSafe for AvailabilityOptionsStatus Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::BuildSuggestersRequest === ``` pub struct BuildSuggestersRequest { pub domain_name: String, } ``` Container for the parameters to the `BuildSuggester` operation. Specifies the name of the domain you want to update. Fields --- `domain_name: String`Trait Implementations --- source### impl Clone for BuildSuggestersRequest source#### fn clone(&self) -> BuildSuggestersRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for BuildSuggestersRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for BuildSuggestersRequest source#### fn default() -> BuildSuggestersRequest Returns the “default value” for a type. Read more source### impl PartialEq<BuildSuggestersRequest> for BuildSuggestersRequest source#### fn eq(&self, other: &BuildSuggestersRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &BuildSuggestersRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for BuildSuggestersRequest Auto Trait Implementations --- ### impl RefUnwindSafe for BuildSuggestersRequest ### impl Send for BuildSuggestersRequest ### impl Sync for BuildSuggestersRequest ### impl Unpin for BuildSuggestersRequest ### impl UnwindSafe for BuildSuggestersRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::BuildSuggestersResponse === ``` pub struct BuildSuggestersResponse { pub field_names: Option<Vec<String>>, } ``` The result of a `BuildSuggester` request. Contains a list of the fields used for suggestions. Fields --- `field_names: Option<Vec<String>>`Trait Implementations --- source### impl Clone for BuildSuggestersResponse source#### fn clone(&self) -> BuildSuggestersResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for BuildSuggestersResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for BuildSuggestersResponse source#### fn default() -> BuildSuggestersResponse Returns the “default value” for a type. Read more source### impl PartialEq<BuildSuggestersResponse> for BuildSuggestersResponse source#### fn eq(&self, other: &BuildSuggestersResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &BuildSuggestersResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for BuildSuggestersResponse Auto Trait Implementations --- ### impl RefUnwindSafe for BuildSuggestersResponse ### impl Send for BuildSuggestersResponse ### impl Sync for BuildSuggestersResponse ### impl Unpin for BuildSuggestersResponse ### impl UnwindSafe for BuildSuggestersResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::CreateDomainRequest === ``` pub struct CreateDomainRequest { pub domain_name: String, } ``` Container for the parameters to the `CreateDomain` operation. Specifies a name for the new search domain. Fields --- `domain_name: String`A name for the domain you are creating. Allowed characters are a-z (lower-case letters), 0-9, and hyphen (-). Domain names must start with a letter or number and be at least 3 and no more than 28 characters long. Trait Implementations --- source### impl Clone for CreateDomainRequest source#### fn clone(&self) -> CreateDomainRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for CreateDomainRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for CreateDomainRequest source#### fn default() -> CreateDomainRequest Returns the “default value” for a type. Read more source### impl PartialEq<CreateDomainRequest> for CreateDomainRequest source#### fn eq(&self, other: &CreateDomainRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &CreateDomainRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for CreateDomainRequest Auto Trait Implementations --- ### impl RefUnwindSafe for CreateDomainRequest ### impl Send for CreateDomainRequest ### impl Sync for CreateDomainRequest ### impl Unpin for CreateDomainRequest ### impl UnwindSafe for CreateDomainRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::CreateDomainResponse === ``` pub struct CreateDomainResponse { pub domain_status: Option<DomainStatus>, } ``` The result of a `CreateDomainRequest`. Contains the status of a newly created domain. Fields --- `domain_status: Option<DomainStatus>`Trait Implementations --- source### impl Clone for CreateDomainResponse source#### fn clone(&self) -> CreateDomainResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for CreateDomainResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for CreateDomainResponse source#### fn default() -> CreateDomainResponse Returns the “default value” for a type. Read more source### impl PartialEq<CreateDomainResponse> for CreateDomainResponse source#### fn eq(&self, other: &CreateDomainResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &CreateDomainResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for CreateDomainResponse Auto Trait Implementations --- ### impl RefUnwindSafe for CreateDomainResponse ### impl Send for CreateDomainResponse ### impl Sync for CreateDomainResponse ### impl Unpin for CreateDomainResponse ### impl UnwindSafe for CreateDomainResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DateArrayOptions === ``` pub struct DateArrayOptions { pub default_value: Option<String>, pub facet_enabled: Option<bool>, pub return_enabled: Option<bool>, pub search_enabled: Option<bool>, pub source_fields: Option<String>, } ``` Options for a field that contains an array of dates. Present if `IndexFieldType` specifies the field is of type `date-array`. All options are enabled by default. Fields --- `default_value: Option<String>`A value to use for the field if the field isn't specified for a document. `facet_enabled: Option<bool>`Whether facet information can be returned for the field. `return_enabled: Option<bool>`Whether the contents of the field can be returned in the search results. `search_enabled: Option<bool>`Whether the contents of the field are searchable. `source_fields: Option<String>`A list of source fields to map to the field. Trait Implementations --- source### impl Clone for DateArrayOptions source#### fn clone(&self) -> DateArrayOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DateArrayOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DateArrayOptions source#### fn default() -> DateArrayOptions Returns the “default value” for a type. Read more source### impl PartialEq<DateArrayOptions> for DateArrayOptions source#### fn eq(&self, other: &DateArrayOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DateArrayOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DateArrayOptions Auto Trait Implementations --- ### impl RefUnwindSafe for DateArrayOptions ### impl Send for DateArrayOptions ### impl Sync for DateArrayOptions ### impl Unpin for DateArrayOptions ### impl UnwindSafe for DateArrayOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DateOptions === ``` pub struct DateOptions { pub default_value: Option<String>, pub facet_enabled: Option<bool>, pub return_enabled: Option<bool>, pub search_enabled: Option<bool>, pub sort_enabled: Option<bool>, pub source_field: Option<String>, } ``` Options for a date field. Dates and times are specified in UTC (Coordinated Universal Time) according to IETF RFC3339: yyyy-mm-ddT00:00:00Z. Present if `IndexFieldType` specifies the field is of type `date`. All options are enabled by default. Fields --- `default_value: Option<String>`A value to use for the field if the field isn't specified for a document. `facet_enabled: Option<bool>`Whether facet information can be returned for the field. `return_enabled: Option<bool>`Whether the contents of the field can be returned in the search results. `search_enabled: Option<bool>`Whether the contents of the field are searchable. `sort_enabled: Option<bool>`Whether the field can be used to sort the search results. `source_field: Option<String>`Trait Implementations --- source### impl Clone for DateOptions source#### fn clone(&self) -> DateOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DateOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DateOptions source#### fn default() -> DateOptions Returns the “default value” for a type. Read more source### impl PartialEq<DateOptions> for DateOptions source#### fn eq(&self, other: &DateOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DateOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DateOptions Auto Trait Implementations --- ### impl RefUnwindSafe for DateOptions ### impl Send for DateOptions ### impl Sync for DateOptions ### impl Unpin for DateOptions ### impl UnwindSafe for DateOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DefineAnalysisSchemeRequest === ``` pub struct DefineAnalysisSchemeRequest { pub analysis_scheme: AnalysisScheme, pub domain_name: String, } ``` Container for the parameters to the `DefineAnalysisScheme` operation. Specifies the name of the domain you want to update and the analysis scheme configuration. Fields --- `analysis_scheme: AnalysisScheme``domain_name: String`Trait Implementations --- source### impl Clone for DefineAnalysisSchemeRequest source#### fn clone(&self) -> DefineAnalysisSchemeRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DefineAnalysisSchemeRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DefineAnalysisSchemeRequest source#### fn default() -> DefineAnalysisSchemeRequest Returns the “default value” for a type. Read more source### impl PartialEq<DefineAnalysisSchemeRequest> for DefineAnalysisSchemeRequest source#### fn eq(&self, other: &DefineAnalysisSchemeRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineAnalysisSchemeRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineAnalysisSchemeRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DefineAnalysisSchemeRequest ### impl Send for DefineAnalysisSchemeRequest ### impl Sync for DefineAnalysisSchemeRequest ### impl Unpin for DefineAnalysisSchemeRequest ### impl UnwindSafe for DefineAnalysisSchemeRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DefineAnalysisSchemeResponse === ``` pub struct DefineAnalysisSchemeResponse { pub analysis_scheme: AnalysisSchemeStatus, } ``` The result of a `DefineAnalysisScheme` request. Contains the status of the newly-configured analysis scheme. Fields --- `analysis_scheme: AnalysisSchemeStatus`Trait Implementations --- source### impl Clone for DefineAnalysisSchemeResponse source#### fn clone(&self) -> DefineAnalysisSchemeResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DefineAnalysisSchemeResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DefineAnalysisSchemeResponse source#### fn default() -> DefineAnalysisSchemeResponse Returns the “default value” for a type. Read more source### impl PartialEq<DefineAnalysisSchemeResponse> for DefineAnalysisSchemeResponse source#### fn eq(&self, other: &DefineAnalysisSchemeResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineAnalysisSchemeResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineAnalysisSchemeResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DefineAnalysisSchemeResponse ### impl Send for DefineAnalysisSchemeResponse ### impl Sync for DefineAnalysisSchemeResponse ### impl Unpin for DefineAnalysisSchemeResponse ### impl UnwindSafe for DefineAnalysisSchemeResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DefineExpressionRequest === ``` pub struct DefineExpressionRequest { pub domain_name: String, pub expression: Expression, } ``` Container for the parameters to the `DefineExpression` operation. Specifies the name of the domain you want to update and the expression you want to configure. Fields --- `domain_name: String``expression: Expression`Trait Implementations --- source### impl Clone for DefineExpressionRequest source#### fn clone(&self) -> DefineExpressionRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DefineExpressionRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DefineExpressionRequest source#### fn default() -> DefineExpressionRequest Returns the “default value” for a type. Read more source### impl PartialEq<DefineExpressionRequest> for DefineExpressionRequest source#### fn eq(&self, other: &DefineExpressionRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineExpressionRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineExpressionRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DefineExpressionRequest ### impl Send for DefineExpressionRequest ### impl Sync for DefineExpressionRequest ### impl Unpin for DefineExpressionRequest ### impl UnwindSafe for DefineExpressionRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DefineExpressionResponse === ``` pub struct DefineExpressionResponse { pub expression: ExpressionStatus, } ``` The result of a `DefineExpression` request. Contains the status of the newly-configured expression. Fields --- `expression: ExpressionStatus`Trait Implementations --- source### impl Clone for DefineExpressionResponse source#### fn clone(&self) -> DefineExpressionResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DefineExpressionResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DefineExpressionResponse source#### fn default() -> DefineExpressionResponse Returns the “default value” for a type. Read more source### impl PartialEq<DefineExpressionResponse> for DefineExpressionResponse source#### fn eq(&self, other: &DefineExpressionResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineExpressionResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineExpressionResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DefineExpressionResponse ### impl Send for DefineExpressionResponse ### impl Sync for DefineExpressionResponse ### impl Unpin for DefineExpressionResponse ### impl UnwindSafe for DefineExpressionResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DefineIndexFieldRequest === ``` pub struct DefineIndexFieldRequest { pub domain_name: String, pub index_field: IndexField, } ``` Container for the parameters to the `DefineIndexField` operation. Specifies the name of the domain you want to update and the index field configuration. Fields --- `domain_name: String``index_field: IndexField`The index field and field options you want to configure. Trait Implementations --- source### impl Clone for DefineIndexFieldRequest source#### fn clone(&self) -> DefineIndexFieldRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DefineIndexFieldRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DefineIndexFieldRequest source#### fn default() -> DefineIndexFieldRequest Returns the “default value” for a type. Read more source### impl PartialEq<DefineIndexFieldRequest> for DefineIndexFieldRequest source#### fn eq(&self, other: &DefineIndexFieldRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineIndexFieldRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineIndexFieldRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DefineIndexFieldRequest ### impl Send for DefineIndexFieldRequest ### impl Sync for DefineIndexFieldRequest ### impl Unpin for DefineIndexFieldRequest ### impl UnwindSafe for DefineIndexFieldRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DefineIndexFieldResponse === ``` pub struct DefineIndexFieldResponse { pub index_field: IndexFieldStatus, } ``` The result of a `DefineIndexField` request. Contains the status of the newly-configured index field. Fields --- `index_field: IndexFieldStatus`Trait Implementations --- source### impl Clone for DefineIndexFieldResponse source#### fn clone(&self) -> DefineIndexFieldResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DefineIndexFieldResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DefineIndexFieldResponse source#### fn default() -> DefineIndexFieldResponse Returns the “default value” for a type. Read more source### impl PartialEq<DefineIndexFieldResponse> for DefineIndexFieldResponse source#### fn eq(&self, other: &DefineIndexFieldResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineIndexFieldResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineIndexFieldResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DefineIndexFieldResponse ### impl Send for DefineIndexFieldResponse ### impl Sync for DefineIndexFieldResponse ### impl Unpin for DefineIndexFieldResponse ### impl UnwindSafe for DefineIndexFieldResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DefineSuggesterRequest === ``` pub struct DefineSuggesterRequest { pub domain_name: String, pub suggester: Suggester, } ``` Container for the parameters to the `DefineSuggester` operation. Specifies the name of the domain you want to update and the suggester configuration. Fields --- `domain_name: String``suggester: Suggester`Trait Implementations --- source### impl Clone for DefineSuggesterRequest source#### fn clone(&self) -> DefineSuggesterRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DefineSuggesterRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DefineSuggesterRequest source#### fn default() -> DefineSuggesterRequest Returns the “default value” for a type. Read more source### impl PartialEq<DefineSuggesterRequest> for DefineSuggesterRequest source#### fn eq(&self, other: &DefineSuggesterRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineSuggesterRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineSuggesterRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DefineSuggesterRequest ### impl Send for DefineSuggesterRequest ### impl Sync for DefineSuggesterRequest ### impl Unpin for DefineSuggesterRequest ### impl UnwindSafe for DefineSuggesterRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DefineSuggesterResponse === ``` pub struct DefineSuggesterResponse { pub suggester: SuggesterStatus, } ``` The result of a `DefineSuggester` request. Contains the status of the newly-configured suggester. Fields --- `suggester: SuggesterStatus`Trait Implementations --- source### impl Clone for DefineSuggesterResponse source#### fn clone(&self) -> DefineSuggesterResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DefineSuggesterResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DefineSuggesterResponse source#### fn default() -> DefineSuggesterResponse Returns the “default value” for a type. Read more source### impl PartialEq<DefineSuggesterResponse> for DefineSuggesterResponse source#### fn eq(&self, other: &DefineSuggesterResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineSuggesterResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineSuggesterResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DefineSuggesterResponse ### impl Send for DefineSuggesterResponse ### impl Sync for DefineSuggesterResponse ### impl Unpin for DefineSuggesterResponse ### impl UnwindSafe for DefineSuggesterResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DeleteAnalysisSchemeRequest === ``` pub struct DeleteAnalysisSchemeRequest { pub analysis_scheme_name: String, pub domain_name: String, } ``` Container for the parameters to the `DeleteAnalysisScheme` operation. Specifies the name of the domain you want to update and the analysis scheme you want to delete. Fields --- `analysis_scheme_name: String`The name of the analysis scheme you want to delete. `domain_name: String`Trait Implementations --- source### impl Clone for DeleteAnalysisSchemeRequest source#### fn clone(&self) -> DeleteAnalysisSchemeRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DeleteAnalysisSchemeRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DeleteAnalysisSchemeRequest source#### fn default() -> DeleteAnalysisSchemeRequest Returns the “default value” for a type. Read more source### impl PartialEq<DeleteAnalysisSchemeRequest> for DeleteAnalysisSchemeRequest source#### fn eq(&self, other: &DeleteAnalysisSchemeRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteAnalysisSchemeRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteAnalysisSchemeRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteAnalysisSchemeRequest ### impl Send for DeleteAnalysisSchemeRequest ### impl Sync for DeleteAnalysisSchemeRequest ### impl Unpin for DeleteAnalysisSchemeRequest ### impl UnwindSafe for DeleteAnalysisSchemeRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DeleteAnalysisSchemeResponse === ``` pub struct DeleteAnalysisSchemeResponse { pub analysis_scheme: AnalysisSchemeStatus, } ``` The result of a `DeleteAnalysisScheme` request. Contains the status of the deleted analysis scheme. Fields --- `analysis_scheme: AnalysisSchemeStatus`The status of the analysis scheme being deleted. Trait Implementations --- source### impl Clone for DeleteAnalysisSchemeResponse source#### fn clone(&self) -> DeleteAnalysisSchemeResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DeleteAnalysisSchemeResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DeleteAnalysisSchemeResponse source#### fn default() -> DeleteAnalysisSchemeResponse Returns the “default value” for a type. Read more source### impl PartialEq<DeleteAnalysisSchemeResponse> for DeleteAnalysisSchemeResponse source#### fn eq(&self, other: &DeleteAnalysisSchemeResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteAnalysisSchemeResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteAnalysisSchemeResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteAnalysisSchemeResponse ### impl Send for DeleteAnalysisSchemeResponse ### impl Sync for DeleteAnalysisSchemeResponse ### impl Unpin for DeleteAnalysisSchemeResponse ### impl UnwindSafe for DeleteAnalysisSchemeResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DeleteDomainRequest === ``` pub struct DeleteDomainRequest { pub domain_name: String, } ``` Container for the parameters to the `DeleteDomain` operation. Specifies the name of the domain you want to delete. Fields --- `domain_name: String`The name of the domain you want to permanently delete. Trait Implementations --- source### impl Clone for DeleteDomainRequest source#### fn clone(&self) -> DeleteDomainRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DeleteDomainRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DeleteDomainRequest source#### fn default() -> DeleteDomainRequest Returns the “default value” for a type. Read more source### impl PartialEq<DeleteDomainRequest> for DeleteDomainRequest source#### fn eq(&self, other: &DeleteDomainRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteDomainRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteDomainRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteDomainRequest ### impl Send for DeleteDomainRequest ### impl Sync for DeleteDomainRequest ### impl Unpin for DeleteDomainRequest ### impl UnwindSafe for DeleteDomainRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DeleteDomainResponse === ``` pub struct DeleteDomainResponse { pub domain_status: Option<DomainStatus>, } ``` The result of a `DeleteDomain` request. Contains the status of a newly deleted domain, or no status if the domain has already been completely deleted. Fields --- `domain_status: Option<DomainStatus>`Trait Implementations --- source### impl Clone for DeleteDomainResponse source#### fn clone(&self) -> DeleteDomainResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DeleteDomainResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DeleteDomainResponse source#### fn default() -> DeleteDomainResponse Returns the “default value” for a type. Read more source### impl PartialEq<DeleteDomainResponse> for DeleteDomainResponse source#### fn eq(&self, other: &DeleteDomainResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteDomainResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteDomainResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteDomainResponse ### impl Send for DeleteDomainResponse ### impl Sync for DeleteDomainResponse ### impl Unpin for DeleteDomainResponse ### impl UnwindSafe for DeleteDomainResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DeleteExpressionRequest === ``` pub struct DeleteExpressionRequest { pub domain_name: String, pub expression_name: String, } ``` Container for the parameters to the `DeleteExpression` operation. Specifies the name of the domain you want to update and the name of the expression you want to delete. Fields --- `domain_name: String``expression_name: String`The name of the `Expression` to delete. Trait Implementations --- source### impl Clone for DeleteExpressionRequest source#### fn clone(&self) -> DeleteExpressionRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DeleteExpressionRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DeleteExpressionRequest source#### fn default() -> DeleteExpressionRequest Returns the “default value” for a type. Read more source### impl PartialEq<DeleteExpressionRequest> for DeleteExpressionRequest source#### fn eq(&self, other: &DeleteExpressionRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteExpressionRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteExpressionRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteExpressionRequest ### impl Send for DeleteExpressionRequest ### impl Sync for DeleteExpressionRequest ### impl Unpin for DeleteExpressionRequest ### impl UnwindSafe for DeleteExpressionRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DeleteExpressionResponse === ``` pub struct DeleteExpressionResponse { pub expression: ExpressionStatus, } ``` The result of a `DeleteExpression` request. Specifies the expression being deleted. Fields --- `expression: ExpressionStatus`The status of the expression being deleted. Trait Implementations --- source### impl Clone for DeleteExpressionResponse source#### fn clone(&self) -> DeleteExpressionResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DeleteExpressionResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DeleteExpressionResponse source#### fn default() -> DeleteExpressionResponse Returns the “default value” for a type. Read more source### impl PartialEq<DeleteExpressionResponse> for DeleteExpressionResponse source#### fn eq(&self, other: &DeleteExpressionResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteExpressionResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteExpressionResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteExpressionResponse ### impl Send for DeleteExpressionResponse ### impl Sync for DeleteExpressionResponse ### impl Unpin for DeleteExpressionResponse ### impl UnwindSafe for DeleteExpressionResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DeleteIndexFieldRequest === ``` pub struct DeleteIndexFieldRequest { pub domain_name: String, pub index_field_name: String, } ``` Container for the parameters to the `DeleteIndexField` operation. Specifies the name of the domain you want to update and the name of the index field you want to delete. Fields --- `domain_name: String``index_field_name: String`The name of the index field your want to remove from the domain's indexing options. Trait Implementations --- source### impl Clone for DeleteIndexFieldRequest source#### fn clone(&self) -> DeleteIndexFieldRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DeleteIndexFieldRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DeleteIndexFieldRequest source#### fn default() -> DeleteIndexFieldRequest Returns the “default value” for a type. Read more source### impl PartialEq<DeleteIndexFieldRequest> for DeleteIndexFieldRequest source#### fn eq(&self, other: &DeleteIndexFieldRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteIndexFieldRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteIndexFieldRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteIndexFieldRequest ### impl Send for DeleteIndexFieldRequest ### impl Sync for DeleteIndexFieldRequest ### impl Unpin for DeleteIndexFieldRequest ### impl UnwindSafe for DeleteIndexFieldRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DeleteIndexFieldResponse === ``` pub struct DeleteIndexFieldResponse { pub index_field: IndexFieldStatus, } ``` The result of a `DeleteIndexField` request. Fields --- `index_field: IndexFieldStatus`The status of the index field being deleted. Trait Implementations --- source### impl Clone for DeleteIndexFieldResponse source#### fn clone(&self) -> DeleteIndexFieldResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DeleteIndexFieldResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DeleteIndexFieldResponse source#### fn default() -> DeleteIndexFieldResponse Returns the “default value” for a type. Read more source### impl PartialEq<DeleteIndexFieldResponse> for DeleteIndexFieldResponse source#### fn eq(&self, other: &DeleteIndexFieldResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteIndexFieldResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteIndexFieldResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteIndexFieldResponse ### impl Send for DeleteIndexFieldResponse ### impl Sync for DeleteIndexFieldResponse ### impl Unpin for DeleteIndexFieldResponse ### impl UnwindSafe for DeleteIndexFieldResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DeleteSuggesterRequest === ``` pub struct DeleteSuggesterRequest { pub domain_name: String, pub suggester_name: String, } ``` Container for the parameters to the `DeleteSuggester` operation. Specifies the name of the domain you want to update and name of the suggester you want to delete. Fields --- `domain_name: String``suggester_name: String`Specifies the name of the suggester you want to delete. Trait Implementations --- source### impl Clone for DeleteSuggesterRequest source#### fn clone(&self) -> DeleteSuggesterRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DeleteSuggesterRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DeleteSuggesterRequest source#### fn default() -> DeleteSuggesterRequest Returns the “default value” for a type. Read more source### impl PartialEq<DeleteSuggesterRequest> for DeleteSuggesterRequest source#### fn eq(&self, other: &DeleteSuggesterRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteSuggesterRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteSuggesterRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteSuggesterRequest ### impl Send for DeleteSuggesterRequest ### impl Sync for DeleteSuggesterRequest ### impl Unpin for DeleteSuggesterRequest ### impl UnwindSafe for DeleteSuggesterRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DeleteSuggesterResponse === ``` pub struct DeleteSuggesterResponse { pub suggester: SuggesterStatus, } ``` The result of a `DeleteSuggester` request. Contains the status of the deleted suggester. Fields --- `suggester: SuggesterStatus`The status of the suggester being deleted. Trait Implementations --- source### impl Clone for DeleteSuggesterResponse source#### fn clone(&self) -> DeleteSuggesterResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DeleteSuggesterResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DeleteSuggesterResponse source#### fn default() -> DeleteSuggesterResponse Returns the “default value” for a type. Read more source### impl PartialEq<DeleteSuggesterResponse> for DeleteSuggesterResponse source#### fn eq(&self, other: &DeleteSuggesterResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteSuggesterResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteSuggesterResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteSuggesterResponse ### impl Send for DeleteSuggesterResponse ### impl Sync for DeleteSuggesterResponse ### impl Unpin for DeleteSuggesterResponse ### impl UnwindSafe for DeleteSuggesterResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeAnalysisSchemesRequest === ``` pub struct DescribeAnalysisSchemesRequest { pub analysis_scheme_names: Option<Vec<String>>, pub deployed: Option<bool>, pub domain_name: String, } ``` Container for the parameters to the `DescribeAnalysisSchemes` operation. Specifies the name of the domain you want to describe. To limit the response to particular analysis schemes, specify the names of the analysis schemes you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. Fields --- `analysis_scheme_names: Option<Vec<String>>`The analysis schemes you want to describe. `deployed: Option<bool>`Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`. `domain_name: String`The name of the domain you want to describe. Trait Implementations --- source### impl Clone for DescribeAnalysisSchemesRequest source#### fn clone(&self) -> DescribeAnalysisSchemesRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeAnalysisSchemesRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeAnalysisSchemesRequest source#### fn default() -> DescribeAnalysisSchemesRequest Returns the “default value” for a type. Read more source### impl PartialEq<DescribeAnalysisSchemesRequest> for DescribeAnalysisSchemesRequest source#### fn eq(&self, other: &DescribeAnalysisSchemesRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeAnalysisSchemesRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeAnalysisSchemesRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeAnalysisSchemesRequest ### impl Send for DescribeAnalysisSchemesRequest ### impl Sync for DescribeAnalysisSchemesRequest ### impl Unpin for DescribeAnalysisSchemesRequest ### impl UnwindSafe for DescribeAnalysisSchemesRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeAnalysisSchemesResponse === ``` pub struct DescribeAnalysisSchemesResponse { pub analysis_schemes: Vec<AnalysisSchemeStatus>, } ``` The result of a `DescribeAnalysisSchemes` request. Contains the analysis schemes configured for the domain specified in the request. Fields --- `analysis_schemes: Vec<AnalysisSchemeStatus>`The analysis scheme descriptions. Trait Implementations --- source### impl Clone for DescribeAnalysisSchemesResponse source#### fn clone(&self) -> DescribeAnalysisSchemesResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeAnalysisSchemesResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeAnalysisSchemesResponse source#### fn default() -> DescribeAnalysisSchemesResponse Returns the “default value” for a type. Read more source### impl PartialEq<DescribeAnalysisSchemesResponse> for DescribeAnalysisSchemesResponse source#### fn eq(&self, other: &DescribeAnalysisSchemesResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeAnalysisSchemesResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeAnalysisSchemesResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeAnalysisSchemesResponse ### impl Send for DescribeAnalysisSchemesResponse ### impl Sync for DescribeAnalysisSchemesResponse ### impl Unpin for DescribeAnalysisSchemesResponse ### impl UnwindSafe for DescribeAnalysisSchemesResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeAvailabilityOptionsRequest === ``` pub struct DescribeAvailabilityOptionsRequest { pub deployed: Option<bool>, pub domain_name: String, } ``` Container for the parameters to the `DescribeAvailabilityOptions` operation. Specifies the name of the domain you want to describe. To show the active configuration and exclude any pending changes, set the Deployed option to `true`. Fields --- `deployed: Option<bool>`Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`. `domain_name: String`The name of the domain you want to describe. Trait Implementations --- source### impl Clone for DescribeAvailabilityOptionsRequest source#### fn clone(&self) -> DescribeAvailabilityOptionsRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeAvailabilityOptionsRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeAvailabilityOptionsRequest source#### fn default() -> DescribeAvailabilityOptionsRequest Returns the “default value” for a type. Read more source### impl PartialEq<DescribeAvailabilityOptionsRequest> for DescribeAvailabilityOptionsRequest source#### fn eq(&self, other: &DescribeAvailabilityOptionsRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeAvailabilityOptionsRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeAvailabilityOptionsRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeAvailabilityOptionsRequest ### impl Send for DescribeAvailabilityOptionsRequest ### impl Sync for DescribeAvailabilityOptionsRequest ### impl Unpin for DescribeAvailabilityOptionsRequest ### impl UnwindSafe for DescribeAvailabilityOptionsRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeAvailabilityOptionsResponse === ``` pub struct DescribeAvailabilityOptionsResponse { pub availability_options: Option<AvailabilityOptionsStatus>, } ``` The result of a `DescribeAvailabilityOptions` request. Indicates whether or not the Multi-AZ option is enabled for the domain specified in the request. Fields --- `availability_options: Option<AvailabilityOptionsStatus>`The availability options configured for the domain. Indicates whether Multi-AZ is enabled for the domain. Trait Implementations --- source### impl Clone for DescribeAvailabilityOptionsResponse source#### fn clone(&self) -> DescribeAvailabilityOptionsResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeAvailabilityOptionsResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeAvailabilityOptionsResponse source#### fn default() -> DescribeAvailabilityOptionsResponse Returns the “default value” for a type. Read more source### impl PartialEq<DescribeAvailabilityOptionsResponse> for DescribeAvailabilityOptionsResponse source#### fn eq(&self, other: &DescribeAvailabilityOptionsResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeAvailabilityOptionsResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeAvailabilityOptionsResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeAvailabilityOptionsResponse ### impl Send for DescribeAvailabilityOptionsResponse ### impl Sync for DescribeAvailabilityOptionsResponse ### impl Unpin for DescribeAvailabilityOptionsResponse ### impl UnwindSafe for DescribeAvailabilityOptionsResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeDomainEndpointOptionsRequest === ``` pub struct DescribeDomainEndpointOptionsRequest { pub deployed: Option<bool>, pub domain_name: String, } ``` Container for the parameters to the `DescribeDomainEndpointOptions` operation. Specify the name of the domain you want to describe. To show the active configuration and exclude any pending changes, set the Deployed option to `true`. Fields --- `deployed: Option<bool>`Whether to retrieve the latest configuration (which might be in a Processing state) or the current, active configuration. Defaults to `false`. `domain_name: String`A string that represents the name of a domain. Trait Implementations --- source### impl Clone for DescribeDomainEndpointOptionsRequest source#### fn clone(&self) -> DescribeDomainEndpointOptionsRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeDomainEndpointOptionsRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeDomainEndpointOptionsRequest source#### fn default() -> DescribeDomainEndpointOptionsRequest Returns the “default value” for a type. Read more source### impl PartialEq<DescribeDomainEndpointOptionsRequest> for DescribeDomainEndpointOptionsRequest source#### fn eq(&self, other: &DescribeDomainEndpointOptionsRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeDomainEndpointOptionsRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeDomainEndpointOptionsRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeDomainEndpointOptionsRequest ### impl Send for DescribeDomainEndpointOptionsRequest ### impl Sync for DescribeDomainEndpointOptionsRequest ### impl Unpin for DescribeDomainEndpointOptionsRequest ### impl UnwindSafe for DescribeDomainEndpointOptionsRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeDomainEndpointOptionsResponse === ``` pub struct DescribeDomainEndpointOptionsResponse { pub domain_endpoint_options: Option<DomainEndpointOptionsStatus>, } ``` The result of a `DescribeDomainEndpointOptions` request. Contains the status and configuration of a search domain's endpoint options. Fields --- `domain_endpoint_options: Option<DomainEndpointOptionsStatus>`The status and configuration of a search domain's endpoint options. Trait Implementations --- source### impl Clone for DescribeDomainEndpointOptionsResponse source#### fn clone(&self) -> DescribeDomainEndpointOptionsResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeDomainEndpointOptionsResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeDomainEndpointOptionsResponse source#### fn default() -> DescribeDomainEndpointOptionsResponse Returns the “default value” for a type. Read more source### impl PartialEq<DescribeDomainEndpointOptionsResponse> for DescribeDomainEndpointOptionsResponse source#### fn eq(&self, other: &DescribeDomainEndpointOptionsResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeDomainEndpointOptionsResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeDomainEndpointOptionsResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeDomainEndpointOptionsResponse ### impl Send for DescribeDomainEndpointOptionsResponse ### impl Sync for DescribeDomainEndpointOptionsResponse ### impl Unpin for DescribeDomainEndpointOptionsResponse ### impl UnwindSafe for DescribeDomainEndpointOptionsResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeDomainsRequest === ``` pub struct DescribeDomainsRequest { pub domain_names: Option<Vec<String>>, } ``` Container for the parameters to the `DescribeDomains` operation. By default shows the status of all domains. To restrict the response to particular domains, specify the names of the domains you want to describe. Fields --- `domain_names: Option<Vec<String>>`The names of the domains you want to include in the response. Trait Implementations --- source### impl Clone for DescribeDomainsRequest source#### fn clone(&self) -> DescribeDomainsRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeDomainsRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeDomainsRequest source#### fn default() -> DescribeDomainsRequest Returns the “default value” for a type. Read more source### impl PartialEq<DescribeDomainsRequest> for DescribeDomainsRequest source#### fn eq(&self, other: &DescribeDomainsRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeDomainsRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeDomainsRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeDomainsRequest ### impl Send for DescribeDomainsRequest ### impl Sync for DescribeDomainsRequest ### impl Unpin for DescribeDomainsRequest ### impl UnwindSafe for DescribeDomainsRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeDomainsResponse === ``` pub struct DescribeDomainsResponse { pub domain_status_list: Vec<DomainStatus>, } ``` The result of a `DescribeDomains` request. Contains the status of the domains specified in the request or all domains owned by the account. Fields --- `domain_status_list: Vec<DomainStatus>`Trait Implementations --- source### impl Clone for DescribeDomainsResponse source#### fn clone(&self) -> DescribeDomainsResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeDomainsResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeDomainsResponse source#### fn default() -> DescribeDomainsResponse Returns the “default value” for a type. Read more source### impl PartialEq<DescribeDomainsResponse> for DescribeDomainsResponse source#### fn eq(&self, other: &DescribeDomainsResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeDomainsResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeDomainsResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeDomainsResponse ### impl Send for DescribeDomainsResponse ### impl Sync for DescribeDomainsResponse ### impl Unpin for DescribeDomainsResponse ### impl UnwindSafe for DescribeDomainsResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeExpressionsRequest === ``` pub struct DescribeExpressionsRequest { pub deployed: Option<bool>, pub domain_name: String, pub expression_names: Option<Vec<String>>, } ``` Container for the parameters to the `DescribeDomains` operation. Specifies the name of the domain you want to describe. To restrict the response to particular expressions, specify the names of the expressions you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. Fields --- `deployed: Option<bool>`Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`. `domain_name: String`The name of the domain you want to describe. `expression_names: Option<Vec<String>>`Limits the `DescribeExpressions` response to the specified expressions. If not specified, all expressions are shown. Trait Implementations --- source### impl Clone for DescribeExpressionsRequest source#### fn clone(&self) -> DescribeExpressionsRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeExpressionsRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeExpressionsRequest source#### fn default() -> DescribeExpressionsRequest Returns the “default value” for a type. Read more source### impl PartialEq<DescribeExpressionsRequest> for DescribeExpressionsRequest source#### fn eq(&self, other: &DescribeExpressionsRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeExpressionsRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeExpressionsRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeExpressionsRequest ### impl Send for DescribeExpressionsRequest ### impl Sync for DescribeExpressionsRequest ### impl Unpin for DescribeExpressionsRequest ### impl UnwindSafe for DescribeExpressionsRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeExpressionsResponse === ``` pub struct DescribeExpressionsResponse { pub expressions: Vec<ExpressionStatus>, } ``` The result of a `DescribeExpressions` request. Contains the expressions configured for the domain specified in the request. Fields --- `expressions: Vec<ExpressionStatus>`The expressions configured for the domain. Trait Implementations --- source### impl Clone for DescribeExpressionsResponse source#### fn clone(&self) -> DescribeExpressionsResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeExpressionsResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeExpressionsResponse source#### fn default() -> DescribeExpressionsResponse Returns the “default value” for a type. Read more source### impl PartialEq<DescribeExpressionsResponse> for DescribeExpressionsResponse source#### fn eq(&self, other: &DescribeExpressionsResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeExpressionsResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeExpressionsResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeExpressionsResponse ### impl Send for DescribeExpressionsResponse ### impl Sync for DescribeExpressionsResponse ### impl Unpin for DescribeExpressionsResponse ### impl UnwindSafe for DescribeExpressionsResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeIndexFieldsRequest === ``` pub struct DescribeIndexFieldsRequest { pub deployed: Option<bool>, pub domain_name: String, pub field_names: Option<Vec<String>>, } ``` Container for the parameters to the `DescribeIndexFields` operation. Specifies the name of the domain you want to describe. To restrict the response to particular index fields, specify the names of the index fields you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. Fields --- `deployed: Option<bool>`Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`. `domain_name: String`The name of the domain you want to describe. `field_names: Option<Vec<String>>`A list of the index fields you want to describe. If not specified, information is returned for all configured index fields. Trait Implementations --- source### impl Clone for DescribeIndexFieldsRequest source#### fn clone(&self) -> DescribeIndexFieldsRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeIndexFieldsRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeIndexFieldsRequest source#### fn default() -> DescribeIndexFieldsRequest Returns the “default value” for a type. Read more source### impl PartialEq<DescribeIndexFieldsRequest> for DescribeIndexFieldsRequest source#### fn eq(&self, other: &DescribeIndexFieldsRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeIndexFieldsRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeIndexFieldsRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeIndexFieldsRequest ### impl Send for DescribeIndexFieldsRequest ### impl Sync for DescribeIndexFieldsRequest ### impl Unpin for DescribeIndexFieldsRequest ### impl UnwindSafe for DescribeIndexFieldsRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeIndexFieldsResponse === ``` pub struct DescribeIndexFieldsResponse { pub index_fields: Vec<IndexFieldStatus>, } ``` The result of a `DescribeIndexFields` request. Contains the index fields configured for the domain specified in the request. Fields --- `index_fields: Vec<IndexFieldStatus>`The index fields configured for the domain. Trait Implementations --- source### impl Clone for DescribeIndexFieldsResponse source#### fn clone(&self) -> DescribeIndexFieldsResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeIndexFieldsResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeIndexFieldsResponse source#### fn default() -> DescribeIndexFieldsResponse Returns the “default value” for a type. Read more source### impl PartialEq<DescribeIndexFieldsResponse> for DescribeIndexFieldsResponse source#### fn eq(&self, other: &DescribeIndexFieldsResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeIndexFieldsResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeIndexFieldsResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeIndexFieldsResponse ### impl Send for DescribeIndexFieldsResponse ### impl Sync for DescribeIndexFieldsResponse ### impl Unpin for DescribeIndexFieldsResponse ### impl UnwindSafe for DescribeIndexFieldsResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeScalingParametersRequest === ``` pub struct DescribeScalingParametersRequest { pub domain_name: String, } ``` Container for the parameters to the `DescribeScalingParameters` operation. Specifies the name of the domain you want to describe. Fields --- `domain_name: String`Trait Implementations --- source### impl Clone for DescribeScalingParametersRequest source#### fn clone(&self) -> DescribeScalingParametersRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeScalingParametersRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeScalingParametersRequest source#### fn default() -> DescribeScalingParametersRequest Returns the “default value” for a type. Read more source### impl PartialEq<DescribeScalingParametersRequest> for DescribeScalingParametersRequest source#### fn eq(&self, other: &DescribeScalingParametersRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeScalingParametersRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeScalingParametersRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeScalingParametersRequest ### impl Send for DescribeScalingParametersRequest ### impl Sync for DescribeScalingParametersRequest ### impl Unpin for DescribeScalingParametersRequest ### impl UnwindSafe for DescribeScalingParametersRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeScalingParametersResponse === ``` pub struct DescribeScalingParametersResponse { pub scaling_parameters: ScalingParametersStatus, } ``` The result of a `DescribeScalingParameters` request. Contains the scaling parameters configured for the domain specified in the request. Fields --- `scaling_parameters: ScalingParametersStatus`Trait Implementations --- source### impl Clone for DescribeScalingParametersResponse source#### fn clone(&self) -> DescribeScalingParametersResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeScalingParametersResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeScalingParametersResponse source#### fn default() -> DescribeScalingParametersResponse Returns the “default value” for a type. Read more source### impl PartialEq<DescribeScalingParametersResponse> for DescribeScalingParametersResponse source#### fn eq(&self, other: &DescribeScalingParametersResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeScalingParametersResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeScalingParametersResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeScalingParametersResponse ### impl Send for DescribeScalingParametersResponse ### impl Sync for DescribeScalingParametersResponse ### impl Unpin for DescribeScalingParametersResponse ### impl UnwindSafe for DescribeScalingParametersResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeServiceAccessPoliciesRequest === ``` pub struct DescribeServiceAccessPoliciesRequest { pub deployed: Option<bool>, pub domain_name: String, } ``` Container for the parameters to the `DescribeServiceAccessPolicies` operation. Specifies the name of the domain you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. Fields --- `deployed: Option<bool>`Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`. `domain_name: String`The name of the domain you want to describe. Trait Implementations --- source### impl Clone for DescribeServiceAccessPoliciesRequest source#### fn clone(&self) -> DescribeServiceAccessPoliciesRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeServiceAccessPoliciesRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeServiceAccessPoliciesRequest source#### fn default() -> DescribeServiceAccessPoliciesRequest Returns the “default value” for a type. Read more source### impl PartialEq<DescribeServiceAccessPoliciesRequest> for DescribeServiceAccessPoliciesRequest source#### fn eq(&self, other: &DescribeServiceAccessPoliciesRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeServiceAccessPoliciesRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeServiceAccessPoliciesRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeServiceAccessPoliciesRequest ### impl Send for DescribeServiceAccessPoliciesRequest ### impl Sync for DescribeServiceAccessPoliciesRequest ### impl Unpin for DescribeServiceAccessPoliciesRequest ### impl UnwindSafe for DescribeServiceAccessPoliciesRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeServiceAccessPoliciesResponse === ``` pub struct DescribeServiceAccessPoliciesResponse { pub access_policies: AccessPoliciesStatus, } ``` The result of a `DescribeServiceAccessPolicies` request. Fields --- `access_policies: AccessPoliciesStatus`The access rules configured for the domain specified in the request. Trait Implementations --- source### impl Clone for DescribeServiceAccessPoliciesResponse source#### fn clone(&self) -> DescribeServiceAccessPoliciesResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeServiceAccessPoliciesResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeServiceAccessPoliciesResponse source#### fn default() -> DescribeServiceAccessPoliciesResponse Returns the “default value” for a type. Read more source### impl PartialEq<DescribeServiceAccessPoliciesResponse> for DescribeServiceAccessPoliciesResponse source#### fn eq(&self, other: &DescribeServiceAccessPoliciesResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeServiceAccessPoliciesResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeServiceAccessPoliciesResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeServiceAccessPoliciesResponse ### impl Send for DescribeServiceAccessPoliciesResponse ### impl Sync for DescribeServiceAccessPoliciesResponse ### impl Unpin for DescribeServiceAccessPoliciesResponse ### impl UnwindSafe for DescribeServiceAccessPoliciesResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeSuggestersRequest === ``` pub struct DescribeSuggestersRequest { pub deployed: Option<bool>, pub domain_name: String, pub suggester_names: Option<Vec<String>>, } ``` Container for the parameters to the `DescribeSuggester` operation. Specifies the name of the domain you want to describe. To restrict the response to particular suggesters, specify the names of the suggesters you want to describe. To show the active configuration and exclude any pending changes, set the `Deployed` option to `true`. Fields --- `deployed: Option<bool>`Whether to display the deployed configuration (`true`) or include any pending changes (`false`). Defaults to `false`. `domain_name: String`The name of the domain you want to describe. `suggester_names: Option<Vec<String>>`The suggesters you want to describe. Trait Implementations --- source### impl Clone for DescribeSuggestersRequest source#### fn clone(&self) -> DescribeSuggestersRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeSuggestersRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeSuggestersRequest source#### fn default() -> DescribeSuggestersRequest Returns the “default value” for a type. Read more source### impl PartialEq<DescribeSuggestersRequest> for DescribeSuggestersRequest source#### fn eq(&self, other: &DescribeSuggestersRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeSuggestersRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeSuggestersRequest Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeSuggestersRequest ### impl Send for DescribeSuggestersRequest ### impl Sync for DescribeSuggestersRequest ### impl Unpin for DescribeSuggestersRequest ### impl UnwindSafe for DescribeSuggestersRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DescribeSuggestersResponse === ``` pub struct DescribeSuggestersResponse { pub suggesters: Vec<SuggesterStatus>, } ``` The result of a `DescribeSuggesters` request. Fields --- `suggesters: Vec<SuggesterStatus>`The suggesters configured for the domain specified in the request. Trait Implementations --- source### impl Clone for DescribeSuggestersResponse source#### fn clone(&self) -> DescribeSuggestersResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DescribeSuggestersResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DescribeSuggestersResponse source#### fn default() -> DescribeSuggestersResponse Returns the “default value” for a type. Read more source### impl PartialEq<DescribeSuggestersResponse> for DescribeSuggestersResponse source#### fn eq(&self, other: &DescribeSuggestersResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeSuggestersResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeSuggestersResponse Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeSuggestersResponse ### impl Send for DescribeSuggestersResponse ### impl Sync for DescribeSuggestersResponse ### impl Unpin for DescribeSuggestersResponse ### impl UnwindSafe for DescribeSuggestersResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DocumentSuggesterOptions === ``` pub struct DocumentSuggesterOptions { pub fuzzy_matching: Option<String>, pub sort_expression: Option<String>, pub source_field: String, } ``` Options for a search suggester. Fields --- `fuzzy_matching: Option<String>`The level of fuzziness allowed when suggesting matches for a string: `none`, `low`, or `high`. With none, the specified string is treated as an exact prefix. With low, suggestions must differ from the specified string by no more than one character. With high, suggestions can differ by up to two characters. The default is none. `sort_expression: Option<String>`An expression that computes a score for each suggestion to control how they are sorted. The scores are rounded to the nearest integer, with a floor of 0 and a ceiling of 2^31-1. A document's relevance score is not computed for suggestions, so sort expressions cannot reference the `_score` value. To sort suggestions using a numeric field or existing expression, simply specify the name of the field or expression. If no expression is configured for the suggester, the suggestions are sorted with the closest matches listed first. `source_field: String`The name of the index field you want to use for suggestions. Trait Implementations --- source### impl Clone for DocumentSuggesterOptions source#### fn clone(&self) -> DocumentSuggesterOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DocumentSuggesterOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DocumentSuggesterOptions source#### fn default() -> DocumentSuggesterOptions Returns the “default value” for a type. Read more source### impl PartialEq<DocumentSuggesterOptions> for DocumentSuggesterOptions source#### fn eq(&self, other: &DocumentSuggesterOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DocumentSuggesterOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DocumentSuggesterOptions Auto Trait Implementations --- ### impl RefUnwindSafe for DocumentSuggesterOptions ### impl Send for DocumentSuggesterOptions ### impl Sync for DocumentSuggesterOptions ### impl Unpin for DocumentSuggesterOptions ### impl UnwindSafe for DocumentSuggesterOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DomainEndpointOptions === ``` pub struct DomainEndpointOptions { pub enforce_https: Option<bool>, pub tls_security_policy: Option<String>, } ``` The domain's endpoint options. Fields --- `enforce_https: Option<bool>`Whether the domain is HTTPS only enabled. `tls_security_policy: Option<String>`The minimum required TLS version Trait Implementations --- source### impl Clone for DomainEndpointOptions source#### fn clone(&self) -> DomainEndpointOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DomainEndpointOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DomainEndpointOptions source#### fn default() -> DomainEndpointOptions Returns the “default value” for a type. Read more source### impl PartialEq<DomainEndpointOptions> for DomainEndpointOptions source#### fn eq(&self, other: &DomainEndpointOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DomainEndpointOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DomainEndpointOptions Auto Trait Implementations --- ### impl RefUnwindSafe for DomainEndpointOptions ### impl Send for DomainEndpointOptions ### impl Sync for DomainEndpointOptions ### impl Unpin for DomainEndpointOptions ### impl UnwindSafe for DomainEndpointOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DomainEndpointOptionsStatus === ``` pub struct DomainEndpointOptionsStatus { pub options: DomainEndpointOptions, pub status: OptionStatus, } ``` The configuration and status of the domain's endpoint options. Fields --- `options: DomainEndpointOptions`The domain endpoint options configured for the domain. `status: OptionStatus`The status of the configured domain endpoint options. Trait Implementations --- source### impl Clone for DomainEndpointOptionsStatus source#### fn clone(&self) -> DomainEndpointOptionsStatus Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DomainEndpointOptionsStatus source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DomainEndpointOptionsStatus source#### fn default() -> DomainEndpointOptionsStatus Returns the “default value” for a type. Read more source### impl PartialEq<DomainEndpointOptionsStatus> for DomainEndpointOptionsStatus source#### fn eq(&self, other: &DomainEndpointOptionsStatus) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DomainEndpointOptionsStatus) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DomainEndpointOptionsStatus Auto Trait Implementations --- ### impl RefUnwindSafe for DomainEndpointOptionsStatus ### impl Send for DomainEndpointOptionsStatus ### impl Sync for DomainEndpointOptionsStatus ### impl Unpin for DomainEndpointOptionsStatus ### impl UnwindSafe for DomainEndpointOptionsStatus Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DomainStatus === ``` pub struct DomainStatus { pub arn: Option<String>, pub created: Option<bool>, pub deleted: Option<bool>, pub doc_service: Option<ServiceEndpoint>, pub domain_id: String, pub domain_name: String, pub limits: Option<Limits>, pub processing: Option<bool>, pub requires_index_documents: bool, pub search_instance_count: Option<i64>, pub search_instance_type: Option<String>, pub search_partition_count: Option<i64>, pub search_service: Option<ServiceEndpoint>, } ``` The current status of the search domain. Fields --- `arn: Option<String>``created: Option<bool>`True if the search domain is created. It can take several minutes to initialize a domain when CreateDomain is called. Newly created search domains are returned from DescribeDomains with a false value for Created until domain creation is complete. `deleted: Option<bool>`True if the search domain has been deleted. The system must clean up resources dedicated to the search domain when DeleteDomain is called. Newly deleted search domains are returned from DescribeDomains with a true value for IsDeleted for several minutes until resource cleanup is complete. `doc_service: Option<ServiceEndpoint>`The service endpoint for updating documents in a search domain. `domain_id: String``domain_name: String``limits: Option<Limits>``processing: Option<bool>`True if processing is being done to activate the current domain configuration. `requires_index_documents: bool`True if IndexDocuments needs to be called to activate the current domain configuration. `search_instance_count: Option<i64>`The number of search instances that are available to process search requests. `search_instance_type: Option<String>`The instance type that is being used to process search requests. `search_partition_count: Option<i64>`The number of partitions across which the search index is spread. `search_service: Option<ServiceEndpoint>`The service endpoint for requesting search results from a search domain. Trait Implementations --- source### impl Clone for DomainStatus source#### fn clone(&self) -> DomainStatus Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DomainStatus source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DomainStatus source#### fn default() -> DomainStatus Returns the “default value” for a type. Read more source### impl PartialEq<DomainStatus> for DomainStatus source#### fn eq(&self, other: &DomainStatus) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DomainStatus) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DomainStatus Auto Trait Implementations --- ### impl RefUnwindSafe for DomainStatus ### impl Send for DomainStatus ### impl Sync for DomainStatus ### impl Unpin for DomainStatus ### impl UnwindSafe for DomainStatus Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DoubleArrayOptions === ``` pub struct DoubleArrayOptions { pub default_value: Option<f64>, pub facet_enabled: Option<bool>, pub return_enabled: Option<bool>, pub search_enabled: Option<bool>, pub source_fields: Option<String>, } ``` Options for a field that contains an array of double-precision 64-bit floating point values. Present if `IndexFieldType` specifies the field is of type `double-array`. All options are enabled by default. Fields --- `default_value: Option<f64>`A value to use for the field if the field isn't specified for a document. `facet_enabled: Option<bool>`Whether facet information can be returned for the field. `return_enabled: Option<bool>`Whether the contents of the field can be returned in the search results. `search_enabled: Option<bool>`Whether the contents of the field are searchable. `source_fields: Option<String>`A list of source fields to map to the field. Trait Implementations --- source### impl Clone for DoubleArrayOptions source#### fn clone(&self) -> DoubleArrayOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DoubleArrayOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DoubleArrayOptions source#### fn default() -> DoubleArrayOptions Returns the “default value” for a type. Read more source### impl PartialEq<DoubleArrayOptions> for DoubleArrayOptions source#### fn eq(&self, other: &DoubleArrayOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DoubleArrayOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DoubleArrayOptions Auto Trait Implementations --- ### impl RefUnwindSafe for DoubleArrayOptions ### impl Send for DoubleArrayOptions ### impl Sync for DoubleArrayOptions ### impl Unpin for DoubleArrayOptions ### impl UnwindSafe for DoubleArrayOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::DoubleOptions === ``` pub struct DoubleOptions { pub default_value: Option<f64>, pub facet_enabled: Option<bool>, pub return_enabled: Option<bool>, pub search_enabled: Option<bool>, pub sort_enabled: Option<bool>, pub source_field: Option<String>, } ``` Options for a double-precision 64-bit floating point field. Present if `IndexFieldType` specifies the field is of type `double`. All options are enabled by default. Fields --- `default_value: Option<f64>`A value to use for the field if the field isn't specified for a document. This can be important if you are using the field in an expression and that field is not present in every document. `facet_enabled: Option<bool>`Whether facet information can be returned for the field. `return_enabled: Option<bool>`Whether the contents of the field can be returned in the search results. `search_enabled: Option<bool>`Whether the contents of the field are searchable. `sort_enabled: Option<bool>`Whether the field can be used to sort the search results. `source_field: Option<String>`The name of the source field to map to the field. Trait Implementations --- source### impl Clone for DoubleOptions source#### fn clone(&self) -> DoubleOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DoubleOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for DoubleOptions source#### fn default() -> DoubleOptions Returns the “default value” for a type. Read more source### impl PartialEq<DoubleOptions> for DoubleOptions source#### fn eq(&self, other: &DoubleOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DoubleOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DoubleOptions Auto Trait Implementations --- ### impl RefUnwindSafe for DoubleOptions ### impl Send for DoubleOptions ### impl Sync for DoubleOptions ### impl Unpin for DoubleOptions ### impl UnwindSafe for DoubleOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::Expression === ``` pub struct Expression { pub expression_name: String, pub expression_value: String, } ``` A named expression that can be evaluated at search time. Can be used to sort the search results, define other expressions, or return computed information in the search results. Fields --- `expression_name: String``expression_value: String`Trait Implementations --- source### impl Clone for Expression source#### fn clone(&self) -> Expression Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for Expression source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for Expression source#### fn default() -> Expression Returns the “default value” for a type. Read more source### impl PartialEq<Expression> for Expression source#### fn eq(&self, other: &Expression) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &Expression) -> bool This method tests for `!=`. source### impl StructuralPartialEq for Expression Auto Trait Implementations --- ### impl RefUnwindSafe for Expression ### impl Send for Expression ### impl Sync for Expression ### impl Unpin for Expression ### impl UnwindSafe for Expression Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::ExpressionStatus === ``` pub struct ExpressionStatus { pub options: Expression, pub status: OptionStatus, } ``` The value of an `Expression` and its current status. Fields --- `options: Expression`The expression that is evaluated for sorting while processing a search request. `status: OptionStatus`Trait Implementations --- source### impl Clone for ExpressionStatus source#### fn clone(&self) -> ExpressionStatus Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for ExpressionStatus source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for ExpressionStatus source#### fn default() -> ExpressionStatus Returns the “default value” for a type. Read more source### impl PartialEq<ExpressionStatus> for ExpressionStatus source#### fn eq(&self, other: &ExpressionStatus) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &ExpressionStatus) -> bool This method tests for `!=`. source### impl StructuralPartialEq for ExpressionStatus Auto Trait Implementations --- ### impl RefUnwindSafe for ExpressionStatus ### impl Send for ExpressionStatus ### impl Sync for ExpressionStatus ### impl Unpin for ExpressionStatus ### impl UnwindSafe for ExpressionStatus Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::IndexDocumentsRequest === ``` pub struct IndexDocumentsRequest { pub domain_name: String, } ``` Container for the parameters to the `IndexDocuments` operation. Specifies the name of the domain you want to re-index. Fields --- `domain_name: String`Trait Implementations --- source### impl Clone for IndexDocumentsRequest source#### fn clone(&self) -> IndexDocumentsRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for IndexDocumentsRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for IndexDocumentsRequest source#### fn default() -> IndexDocumentsRequest Returns the “default value” for a type. Read more source### impl PartialEq<IndexDocumentsRequest> for IndexDocumentsRequest source#### fn eq(&self, other: &IndexDocumentsRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &IndexDocumentsRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for IndexDocumentsRequest Auto Trait Implementations --- ### impl RefUnwindSafe for IndexDocumentsRequest ### impl Send for IndexDocumentsRequest ### impl Sync for IndexDocumentsRequest ### impl Unpin for IndexDocumentsRequest ### impl UnwindSafe for IndexDocumentsRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::IndexDocumentsResponse === ``` pub struct IndexDocumentsResponse { pub field_names: Option<Vec<String>>, } ``` The result of an `IndexDocuments` request. Contains the status of the indexing operation, including the fields being indexed. Fields --- `field_names: Option<Vec<String>>`The names of the fields that are currently being indexed. Trait Implementations --- source### impl Clone for IndexDocumentsResponse source#### fn clone(&self) -> IndexDocumentsResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for IndexDocumentsResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for IndexDocumentsResponse source#### fn default() -> IndexDocumentsResponse Returns the “default value” for a type. Read more source### impl PartialEq<IndexDocumentsResponse> for IndexDocumentsResponse source#### fn eq(&self, other: &IndexDocumentsResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &IndexDocumentsResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for IndexDocumentsResponse Auto Trait Implementations --- ### impl RefUnwindSafe for IndexDocumentsResponse ### impl Send for IndexDocumentsResponse ### impl Sync for IndexDocumentsResponse ### impl Unpin for IndexDocumentsResponse ### impl UnwindSafe for IndexDocumentsResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::IndexField === ``` pub struct IndexField { pub date_array_options: Option<DateArrayOptions>, pub date_options: Option<DateOptions>, pub double_array_options: Option<DoubleArrayOptions>, pub double_options: Option<DoubleOptions>, pub index_field_name: String, pub index_field_type: String, pub int_array_options: Option<IntArrayOptions>, pub int_options: Option<IntOptions>, pub lat_lon_options: Option<LatLonOptions>, pub literal_array_options: Option<LiteralArrayOptions>, pub literal_options: Option<LiteralOptions>, pub text_array_options: Option<TextArrayOptions>, pub text_options: Option<TextOptions>, } ``` Configuration information for a field in the index, including its name, type, and options. The supported options depend on the `IndexFieldType`. Fields --- `date_array_options: Option<DateArrayOptions>``date_options: Option<DateOptions>``double_array_options: Option<DoubleArrayOptions>``double_options: Option<DoubleOptions>``index_field_name: String`A string that represents the name of an index field. CloudSearch supports regular index fields as well as dynamic fields. A dynamic field's name defines a pattern that begins or ends with a wildcard. Any document fields that don't map to a regular index field but do match a dynamic field's pattern are configured with the dynamic field's indexing options. Regular field names begin with a letter and can contain the following characters: a-z (lowercase), 0-9, and _ (underscore). Dynamic field names must begin or end with a wildcard (*). The wildcard can also be the only character in a dynamic field name. Multiple wildcards, and wildcards embedded within a string are not supported. The name `score` is reserved and cannot be used as a field name. To reference a document's ID, you can use the name `_id`. `index_field_type: String``int_array_options: Option<IntArrayOptions>``int_options: Option<IntOptions>``lat_lon_options: Option<LatLonOptions>``literal_array_options: Option<LiteralArrayOptions>``literal_options: Option<LiteralOptions>``text_array_options: Option<TextArrayOptions>``text_options: Option<TextOptions>`Trait Implementations --- source### impl Clone for IndexField source#### fn clone(&self) -> IndexField Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for IndexField source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for IndexField source#### fn default() -> IndexField Returns the “default value” for a type. Read more source### impl PartialEq<IndexField> for IndexField source#### fn eq(&self, other: &IndexField) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &IndexField) -> bool This method tests for `!=`. source### impl StructuralPartialEq for IndexField Auto Trait Implementations --- ### impl RefUnwindSafe for IndexField ### impl Send for IndexField ### impl Sync for IndexField ### impl Unpin for IndexField ### impl UnwindSafe for IndexField Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::IndexFieldStatus === ``` pub struct IndexFieldStatus { pub options: IndexField, pub status: OptionStatus, } ``` The value of an `IndexField` and its current status. Fields --- `options: IndexField``status: OptionStatus`Trait Implementations --- source### impl Clone for IndexFieldStatus source#### fn clone(&self) -> IndexFieldStatus Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for IndexFieldStatus source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for IndexFieldStatus source#### fn default() -> IndexFieldStatus Returns the “default value” for a type. Read more source### impl PartialEq<IndexFieldStatus> for IndexFieldStatus source#### fn eq(&self, other: &IndexFieldStatus) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &IndexFieldStatus) -> bool This method tests for `!=`. source### impl StructuralPartialEq for IndexFieldStatus Auto Trait Implementations --- ### impl RefUnwindSafe for IndexFieldStatus ### impl Send for IndexFieldStatus ### impl Sync for IndexFieldStatus ### impl Unpin for IndexFieldStatus ### impl UnwindSafe for IndexFieldStatus Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::IntArrayOptions === ``` pub struct IntArrayOptions { pub default_value: Option<i64>, pub facet_enabled: Option<bool>, pub return_enabled: Option<bool>, pub search_enabled: Option<bool>, pub source_fields: Option<String>, } ``` Options for a field that contains an array of 64-bit signed integers. Present if `IndexFieldType` specifies the field is of type `int-array`. All options are enabled by default. Fields --- `default_value: Option<i64>`A value to use for the field if the field isn't specified for a document. `facet_enabled: Option<bool>`Whether facet information can be returned for the field. `return_enabled: Option<bool>`Whether the contents of the field can be returned in the search results. `search_enabled: Option<bool>`Whether the contents of the field are searchable. `source_fields: Option<String>`A list of source fields to map to the field. Trait Implementations --- source### impl Clone for IntArrayOptions source#### fn clone(&self) -> IntArrayOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for IntArrayOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for IntArrayOptions source#### fn default() -> IntArrayOptions Returns the “default value” for a type. Read more source### impl PartialEq<IntArrayOptions> for IntArrayOptions source#### fn eq(&self, other: &IntArrayOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &IntArrayOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for IntArrayOptions Auto Trait Implementations --- ### impl RefUnwindSafe for IntArrayOptions ### impl Send for IntArrayOptions ### impl Sync for IntArrayOptions ### impl Unpin for IntArrayOptions ### impl UnwindSafe for IntArrayOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::IntOptions === ``` pub struct IntOptions { pub default_value: Option<i64>, pub facet_enabled: Option<bool>, pub return_enabled: Option<bool>, pub search_enabled: Option<bool>, pub sort_enabled: Option<bool>, pub source_field: Option<String>, } ``` Options for a 64-bit signed integer field. Present if `IndexFieldType` specifies the field is of type `int`. All options are enabled by default. Fields --- `default_value: Option<i64>`A value to use for the field if the field isn't specified for a document. This can be important if you are using the field in an expression and that field is not present in every document. `facet_enabled: Option<bool>`Whether facet information can be returned for the field. `return_enabled: Option<bool>`Whether the contents of the field can be returned in the search results. `search_enabled: Option<bool>`Whether the contents of the field are searchable. `sort_enabled: Option<bool>`Whether the field can be used to sort the search results. `source_field: Option<String>`The name of the source field to map to the field. Trait Implementations --- source### impl Clone for IntOptions source#### fn clone(&self) -> IntOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for IntOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for IntOptions source#### fn default() -> IntOptions Returns the “default value” for a type. Read more source### impl PartialEq<IntOptions> for IntOptions source#### fn eq(&self, other: &IntOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &IntOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for IntOptions Auto Trait Implementations --- ### impl RefUnwindSafe for IntOptions ### impl Send for IntOptions ### impl Sync for IntOptions ### impl Unpin for IntOptions ### impl UnwindSafe for IntOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::LatLonOptions === ``` pub struct LatLonOptions { pub default_value: Option<String>, pub facet_enabled: Option<bool>, pub return_enabled: Option<bool>, pub search_enabled: Option<bool>, pub sort_enabled: Option<bool>, pub source_field: Option<String>, } ``` Options for a latlon field. A latlon field contains a location stored as a latitude and longitude value pair. Present if `IndexFieldType` specifies the field is of type `latlon`. All options are enabled by default. Fields --- `default_value: Option<String>`A value to use for the field if the field isn't specified for a document. `facet_enabled: Option<bool>`Whether facet information can be returned for the field. `return_enabled: Option<bool>`Whether the contents of the field can be returned in the search results. `search_enabled: Option<bool>`Whether the contents of the field are searchable. `sort_enabled: Option<bool>`Whether the field can be used to sort the search results. `source_field: Option<String>`Trait Implementations --- source### impl Clone for LatLonOptions source#### fn clone(&self) -> LatLonOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for LatLonOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for LatLonOptions source#### fn default() -> LatLonOptions Returns the “default value” for a type. Read more source### impl PartialEq<LatLonOptions> for LatLonOptions source#### fn eq(&self, other: &LatLonOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &LatLonOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for LatLonOptions Auto Trait Implementations --- ### impl RefUnwindSafe for LatLonOptions ### impl Send for LatLonOptions ### impl Sync for LatLonOptions ### impl Unpin for LatLonOptions ### impl UnwindSafe for LatLonOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::Limits === ``` pub struct Limits { pub maximum_partition_count: i64, pub maximum_replication_count: i64, } ``` Fields --- `maximum_partition_count: i64``maximum_replication_count: i64`Trait Implementations --- source### impl Clone for Limits source#### fn clone(&self) -> Limits Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for Limits source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for Limits source#### fn default() -> Limits Returns the “default value” for a type. Read more source### impl PartialEq<Limits> for Limits source#### fn eq(&self, other: &Limits) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &Limits) -> bool This method tests for `!=`. source### impl StructuralPartialEq for Limits Auto Trait Implementations --- ### impl RefUnwindSafe for Limits ### impl Send for Limits ### impl Sync for Limits ### impl Unpin for Limits ### impl UnwindSafe for Limits Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::ListDomainNamesResponse === ``` pub struct ListDomainNamesResponse { pub domain_names: Option<HashMap<String, String>>, } ``` The result of a `ListDomainNames` request. Contains a list of the domains owned by an account. Fields --- `domain_names: Option<HashMap<String, String>>`The names of the search domains owned by an account. Trait Implementations --- source### impl Clone for ListDomainNamesResponse source#### fn clone(&self) -> ListDomainNamesResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for ListDomainNamesResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for ListDomainNamesResponse source#### fn default() -> ListDomainNamesResponse Returns the “default value” for a type. Read more source### impl PartialEq<ListDomainNamesResponse> for ListDomainNamesResponse source#### fn eq(&self, other: &ListDomainNamesResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &ListDomainNamesResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for ListDomainNamesResponse Auto Trait Implementations --- ### impl RefUnwindSafe for ListDomainNamesResponse ### impl Send for ListDomainNamesResponse ### impl Sync for ListDomainNamesResponse ### impl Unpin for ListDomainNamesResponse ### impl UnwindSafe for ListDomainNamesResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::LiteralArrayOptions === ``` pub struct LiteralArrayOptions { pub default_value: Option<String>, pub facet_enabled: Option<bool>, pub return_enabled: Option<bool>, pub search_enabled: Option<bool>, pub source_fields: Option<String>, } ``` Options for a field that contains an array of literal strings. Present if `IndexFieldType` specifies the field is of type `literal-array`. All options are enabled by default. Fields --- `default_value: Option<String>`A value to use for the field if the field isn't specified for a document. `facet_enabled: Option<bool>`Whether facet information can be returned for the field. `return_enabled: Option<bool>`Whether the contents of the field can be returned in the search results. `search_enabled: Option<bool>`Whether the contents of the field are searchable. `source_fields: Option<String>`A list of source fields to map to the field. Trait Implementations --- source### impl Clone for LiteralArrayOptions source#### fn clone(&self) -> LiteralArrayOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for LiteralArrayOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for LiteralArrayOptions source#### fn default() -> LiteralArrayOptions Returns the “default value” for a type. Read more source### impl PartialEq<LiteralArrayOptions> for LiteralArrayOptions source#### fn eq(&self, other: &LiteralArrayOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &LiteralArrayOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for LiteralArrayOptions Auto Trait Implementations --- ### impl RefUnwindSafe for LiteralArrayOptions ### impl Send for LiteralArrayOptions ### impl Sync for LiteralArrayOptions ### impl Unpin for LiteralArrayOptions ### impl UnwindSafe for LiteralArrayOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::LiteralOptions === ``` pub struct LiteralOptions { pub default_value: Option<String>, pub facet_enabled: Option<bool>, pub return_enabled: Option<bool>, pub search_enabled: Option<bool>, pub sort_enabled: Option<bool>, pub source_field: Option<String>, } ``` Options for literal field. Present if `IndexFieldType` specifies the field is of type `literal`. All options are enabled by default. Fields --- `default_value: Option<String>`A value to use for the field if the field isn't specified for a document. `facet_enabled: Option<bool>`Whether facet information can be returned for the field. `return_enabled: Option<bool>`Whether the contents of the field can be returned in the search results. `search_enabled: Option<bool>`Whether the contents of the field are searchable. `sort_enabled: Option<bool>`Whether the field can be used to sort the search results. `source_field: Option<String>`Trait Implementations --- source### impl Clone for LiteralOptions source#### fn clone(&self) -> LiteralOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for LiteralOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for LiteralOptions source#### fn default() -> LiteralOptions Returns the “default value” for a type. Read more source### impl PartialEq<LiteralOptions> for LiteralOptions source#### fn eq(&self, other: &LiteralOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &LiteralOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for LiteralOptions Auto Trait Implementations --- ### impl RefUnwindSafe for LiteralOptions ### impl Send for LiteralOptions ### impl Sync for LiteralOptions ### impl Unpin for LiteralOptions ### impl UnwindSafe for LiteralOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::OptionStatus === ``` pub struct OptionStatus { pub creation_date: String, pub pending_deletion: Option<bool>, pub state: String, pub update_date: String, pub update_version: Option<i64>, } ``` The status of domain configuration option. Fields --- `creation_date: String`A timestamp for when this option was created. `pending_deletion: Option<bool>`Indicates that the option will be deleted once processing is complete. `state: String`The state of processing a change to an option. Possible values: * `RequiresIndexDocuments`: the option's latest value will not be deployed until IndexDocuments has been called and indexing is complete. * `Processing`: the option's latest value is in the process of being activated. * `Active`: the option's latest value is completely deployed. * `FailedToValidate`: the option value is not compatible with the domain's data and cannot be used to index the data. You must either modify the option value or update or remove the incompatible documents. `update_date: String`A timestamp for when this option was last updated. `update_version: Option<i64>`A unique integer that indicates when this option was last updated. Trait Implementations --- source### impl Clone for OptionStatus source#### fn clone(&self) -> OptionStatus Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for OptionStatus source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for OptionStatus source#### fn default() -> OptionStatus Returns the “default value” for a type. Read more source### impl PartialEq<OptionStatus> for OptionStatus source#### fn eq(&self, other: &OptionStatus) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &OptionStatus) -> bool This method tests for `!=`. source### impl StructuralPartialEq for OptionStatus Auto Trait Implementations --- ### impl RefUnwindSafe for OptionStatus ### impl Send for OptionStatus ### impl Sync for OptionStatus ### impl Unpin for OptionStatus ### impl UnwindSafe for OptionStatus Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::ScalingParameters === ``` pub struct ScalingParameters { pub desired_instance_type: Option<String>, pub desired_partition_count: Option<i64>, pub desired_replication_count: Option<i64>, } ``` The desired instance type and desired number of replicas of each index partition. Fields --- `desired_instance_type: Option<String>`The instance type that you want to preconfigure for your domain. For example, `search.m1.small`. `desired_partition_count: Option<i64>`The number of partitions you want to preconfigure for your domain. Only valid when you select `m2.2xlarge` as the desired instance type. `desired_replication_count: Option<i64>`The number of replicas you want to preconfigure for each index partition. Trait Implementations --- source### impl Clone for ScalingParameters source#### fn clone(&self) -> ScalingParameters Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for ScalingParameters source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for ScalingParameters source#### fn default() -> ScalingParameters Returns the “default value” for a type. Read more source### impl PartialEq<ScalingParameters> for ScalingParameters source#### fn eq(&self, other: &ScalingParameters) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &ScalingParameters) -> bool This method tests for `!=`. source### impl StructuralPartialEq for ScalingParameters Auto Trait Implementations --- ### impl RefUnwindSafe for ScalingParameters ### impl Send for ScalingParameters ### impl Sync for ScalingParameters ### impl Unpin for ScalingParameters ### impl UnwindSafe for ScalingParameters Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::ScalingParametersStatus === ``` pub struct ScalingParametersStatus { pub options: ScalingParameters, pub status: OptionStatus, } ``` The status and configuration of a search domain's scaling parameters. Fields --- `options: ScalingParameters``status: OptionStatus`Trait Implementations --- source### impl Clone for ScalingParametersStatus source#### fn clone(&self) -> ScalingParametersStatus Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for ScalingParametersStatus source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for ScalingParametersStatus source#### fn default() -> ScalingParametersStatus Returns the “default value” for a type. Read more source### impl PartialEq<ScalingParametersStatus> for ScalingParametersStatus source#### fn eq(&self, other: &ScalingParametersStatus) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &ScalingParametersStatus) -> bool This method tests for `!=`. source### impl StructuralPartialEq for ScalingParametersStatus Auto Trait Implementations --- ### impl RefUnwindSafe for ScalingParametersStatus ### impl Send for ScalingParametersStatus ### impl Sync for ScalingParametersStatus ### impl Unpin for ScalingParametersStatus ### impl UnwindSafe for ScalingParametersStatus Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::ServiceEndpoint === ``` pub struct ServiceEndpoint { pub endpoint: Option<String>, } ``` The endpoint to which service requests can be submitted. Fields --- `endpoint: Option<String>`Trait Implementations --- source### impl Clone for ServiceEndpoint source#### fn clone(&self) -> ServiceEndpoint Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for ServiceEndpoint source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for ServiceEndpoint source#### fn default() -> ServiceEndpoint Returns the “default value” for a type. Read more source### impl PartialEq<ServiceEndpoint> for ServiceEndpoint source#### fn eq(&self, other: &ServiceEndpoint) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &ServiceEndpoint) -> bool This method tests for `!=`. source### impl StructuralPartialEq for ServiceEndpoint Auto Trait Implementations --- ### impl RefUnwindSafe for ServiceEndpoint ### impl Send for ServiceEndpoint ### impl Sync for ServiceEndpoint ### impl Unpin for ServiceEndpoint ### impl UnwindSafe for ServiceEndpoint Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::Suggester === ``` pub struct Suggester { pub document_suggester_options: DocumentSuggesterOptions, pub suggester_name: String, } ``` Configuration information for a search suggester. Each suggester has a unique name and specifies the text field you want to use for suggestions. The following options can be configured for a suggester: `FuzzyMatching`, `SortExpression`. Fields --- `document_suggester_options: DocumentSuggesterOptions``suggester_name: String`Trait Implementations --- source### impl Clone for Suggester source#### fn clone(&self) -> Suggester Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for Suggester source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for Suggester source#### fn default() -> Suggester Returns the “default value” for a type. Read more source### impl PartialEq<Suggester> for Suggester source#### fn eq(&self, other: &Suggester) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &Suggester) -> bool This method tests for `!=`. source### impl StructuralPartialEq for Suggester Auto Trait Implementations --- ### impl RefUnwindSafe for Suggester ### impl Send for Suggester ### impl Sync for Suggester ### impl Unpin for Suggester ### impl UnwindSafe for Suggester Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::SuggesterStatus === ``` pub struct SuggesterStatus { pub options: Suggester, pub status: OptionStatus, } ``` The value of a `Suggester` and its current status. Fields --- `options: Suggester``status: OptionStatus`Trait Implementations --- source### impl Clone for SuggesterStatus source#### fn clone(&self) -> SuggesterStatus Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for SuggesterStatus source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for SuggesterStatus source#### fn default() -> SuggesterStatus Returns the “default value” for a type. Read more source### impl PartialEq<SuggesterStatus> for SuggesterStatus source#### fn eq(&self, other: &SuggesterStatus) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &SuggesterStatus) -> bool This method tests for `!=`. source### impl StructuralPartialEq for SuggesterStatus Auto Trait Implementations --- ### impl RefUnwindSafe for SuggesterStatus ### impl Send for SuggesterStatus ### impl Sync for SuggesterStatus ### impl Unpin for SuggesterStatus ### impl UnwindSafe for SuggesterStatus Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::TextArrayOptions === ``` pub struct TextArrayOptions { pub analysis_scheme: Option<String>, pub default_value: Option<String>, pub highlight_enabled: Option<bool>, pub return_enabled: Option<bool>, pub source_fields: Option<String>, } ``` Options for a field that contains an array of text strings. Present if `IndexFieldType` specifies the field is of type `text-array`. A `text-array` field is always searchable. All options are enabled by default. Fields --- `analysis_scheme: Option<String>`The name of an analysis scheme for a `text-array` field. `default_value: Option<String>`A value to use for the field if the field isn't specified for a document. `highlight_enabled: Option<bool>`Whether highlights can be returned for the field. `return_enabled: Option<bool>`Whether the contents of the field can be returned in the search results. `source_fields: Option<String>`A list of source fields to map to the field. Trait Implementations --- source### impl Clone for TextArrayOptions source#### fn clone(&self) -> TextArrayOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for TextArrayOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for TextArrayOptions source#### fn default() -> TextArrayOptions Returns the “default value” for a type. Read more source### impl PartialEq<TextArrayOptions> for TextArrayOptions source#### fn eq(&self, other: &TextArrayOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &TextArrayOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for TextArrayOptions Auto Trait Implementations --- ### impl RefUnwindSafe for TextArrayOptions ### impl Send for TextArrayOptions ### impl Sync for TextArrayOptions ### impl Unpin for TextArrayOptions ### impl UnwindSafe for TextArrayOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::TextOptions === ``` pub struct TextOptions { pub analysis_scheme: Option<String>, pub default_value: Option<String>, pub highlight_enabled: Option<bool>, pub return_enabled: Option<bool>, pub sort_enabled: Option<bool>, pub source_field: Option<String>, } ``` Options for text field. Present if `IndexFieldType` specifies the field is of type `text`. A `text` field is always searchable. All options are enabled by default. Fields --- `analysis_scheme: Option<String>`The name of an analysis scheme for a `text` field. `default_value: Option<String>`A value to use for the field if the field isn't specified for a document. `highlight_enabled: Option<bool>`Whether highlights can be returned for the field. `return_enabled: Option<bool>`Whether the contents of the field can be returned in the search results. `sort_enabled: Option<bool>`Whether the field can be used to sort the search results. `source_field: Option<String>`Trait Implementations --- source### impl Clone for TextOptions source#### fn clone(&self) -> TextOptions Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for TextOptions source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for TextOptions source#### fn default() -> TextOptions Returns the “default value” for a type. Read more source### impl PartialEq<TextOptions> for TextOptions source#### fn eq(&self, other: &TextOptions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &TextOptions) -> bool This method tests for `!=`. source### impl StructuralPartialEq for TextOptions Auto Trait Implementations --- ### impl RefUnwindSafe for TextOptions ### impl Send for TextOptions ### impl Sync for TextOptions ### impl Unpin for TextOptions ### impl UnwindSafe for TextOptions Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::UpdateAvailabilityOptionsRequest === ``` pub struct UpdateAvailabilityOptionsRequest { pub domain_name: String, pub multi_az: bool, } ``` Container for the parameters to the `UpdateAvailabilityOptions` operation. Specifies the name of the domain you want to update and the Multi-AZ availability option. Fields --- `domain_name: String``multi_az: bool`You expand an existing search domain to a second Availability Zone by setting the Multi-AZ option to true. Similarly, you can turn off the Multi-AZ option to downgrade the domain to a single Availability Zone by setting the Multi-AZ option to `false`. Trait Implementations --- source### impl Clone for UpdateAvailabilityOptionsRequest source#### fn clone(&self) -> UpdateAvailabilityOptionsRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for UpdateAvailabilityOptionsRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for UpdateAvailabilityOptionsRequest source#### fn default() -> UpdateAvailabilityOptionsRequest Returns the “default value” for a type. Read more source### impl PartialEq<UpdateAvailabilityOptionsRequest> for UpdateAvailabilityOptionsRequest source#### fn eq(&self, other: &UpdateAvailabilityOptionsRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateAvailabilityOptionsRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateAvailabilityOptionsRequest Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateAvailabilityOptionsRequest ### impl Send for UpdateAvailabilityOptionsRequest ### impl Sync for UpdateAvailabilityOptionsRequest ### impl Unpin for UpdateAvailabilityOptionsRequest ### impl UnwindSafe for UpdateAvailabilityOptionsRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::UpdateAvailabilityOptionsResponse === ``` pub struct UpdateAvailabilityOptionsResponse { pub availability_options: Option<AvailabilityOptionsStatus>, } ``` The result of a `UpdateAvailabilityOptions` request. Contains the status of the domain's availability options. Fields --- `availability_options: Option<AvailabilityOptionsStatus>`The newly-configured availability options. Indicates whether Multi-AZ is enabled for the domain. Trait Implementations --- source### impl Clone for UpdateAvailabilityOptionsResponse source#### fn clone(&self) -> UpdateAvailabilityOptionsResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for UpdateAvailabilityOptionsResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for UpdateAvailabilityOptionsResponse source#### fn default() -> UpdateAvailabilityOptionsResponse Returns the “default value” for a type. Read more source### impl PartialEq<UpdateAvailabilityOptionsResponse> for UpdateAvailabilityOptionsResponse source#### fn eq(&self, other: &UpdateAvailabilityOptionsResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateAvailabilityOptionsResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateAvailabilityOptionsResponse Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateAvailabilityOptionsResponse ### impl Send for UpdateAvailabilityOptionsResponse ### impl Sync for UpdateAvailabilityOptionsResponse ### impl Unpin for UpdateAvailabilityOptionsResponse ### impl UnwindSafe for UpdateAvailabilityOptionsResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::UpdateDomainEndpointOptionsRequest === ``` pub struct UpdateDomainEndpointOptionsRequest { pub domain_endpoint_options: DomainEndpointOptions, pub domain_name: String, } ``` Container for the parameters to the `UpdateDomainEndpointOptions` operation. Specifies the name of the domain you want to update and the domain endpoint options. Fields --- `domain_endpoint_options: DomainEndpointOptions`Whether to require that all requests to the domain arrive over HTTPS. We recommend Policy-Min-TLS-1-2-2019-07 for TLSSecurityPolicy. For compatibility with older clients, the default is Policy-Min-TLS-1-0-2019-07. `domain_name: String`A string that represents the name of a domain. Trait Implementations --- source### impl Clone for UpdateDomainEndpointOptionsRequest source#### fn clone(&self) -> UpdateDomainEndpointOptionsRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for UpdateDomainEndpointOptionsRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for UpdateDomainEndpointOptionsRequest source#### fn default() -> UpdateDomainEndpointOptionsRequest Returns the “default value” for a type. Read more source### impl PartialEq<UpdateDomainEndpointOptionsRequest> for UpdateDomainEndpointOptionsRequest source#### fn eq(&self, other: &UpdateDomainEndpointOptionsRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateDomainEndpointOptionsRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateDomainEndpointOptionsRequest Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateDomainEndpointOptionsRequest ### impl Send for UpdateDomainEndpointOptionsRequest ### impl Sync for UpdateDomainEndpointOptionsRequest ### impl Unpin for UpdateDomainEndpointOptionsRequest ### impl UnwindSafe for UpdateDomainEndpointOptionsRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::UpdateDomainEndpointOptionsResponse === ``` pub struct UpdateDomainEndpointOptionsResponse { pub domain_endpoint_options: Option<DomainEndpointOptionsStatus>, } ``` The result of a `UpdateDomainEndpointOptions` request. Contains the configuration and status of the domain's endpoint options. Fields --- `domain_endpoint_options: Option<DomainEndpointOptionsStatus>`The newly-configured domain endpoint options. Trait Implementations --- source### impl Clone for UpdateDomainEndpointOptionsResponse source#### fn clone(&self) -> UpdateDomainEndpointOptionsResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for UpdateDomainEndpointOptionsResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for UpdateDomainEndpointOptionsResponse source#### fn default() -> UpdateDomainEndpointOptionsResponse Returns the “default value” for a type. Read more source### impl PartialEq<UpdateDomainEndpointOptionsResponse> for UpdateDomainEndpointOptionsResponse source#### fn eq(&self, other: &UpdateDomainEndpointOptionsResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateDomainEndpointOptionsResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateDomainEndpointOptionsResponse Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateDomainEndpointOptionsResponse ### impl Send for UpdateDomainEndpointOptionsResponse ### impl Sync for UpdateDomainEndpointOptionsResponse ### impl Unpin for UpdateDomainEndpointOptionsResponse ### impl UnwindSafe for UpdateDomainEndpointOptionsResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::UpdateScalingParametersRequest === ``` pub struct UpdateScalingParametersRequest { pub domain_name: String, pub scaling_parameters: ScalingParameters, } ``` Container for the parameters to the `UpdateScalingParameters` operation. Specifies the name of the domain you want to update and the scaling parameters you want to configure. Fields --- `domain_name: String``scaling_parameters: ScalingParameters`Trait Implementations --- source### impl Clone for UpdateScalingParametersRequest source#### fn clone(&self) -> UpdateScalingParametersRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for UpdateScalingParametersRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for UpdateScalingParametersRequest source#### fn default() -> UpdateScalingParametersRequest Returns the “default value” for a type. Read more source### impl PartialEq<UpdateScalingParametersRequest> for UpdateScalingParametersRequest source#### fn eq(&self, other: &UpdateScalingParametersRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateScalingParametersRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateScalingParametersRequest Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateScalingParametersRequest ### impl Send for UpdateScalingParametersRequest ### impl Sync for UpdateScalingParametersRequest ### impl Unpin for UpdateScalingParametersRequest ### impl UnwindSafe for UpdateScalingParametersRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::UpdateScalingParametersResponse === ``` pub struct UpdateScalingParametersResponse { pub scaling_parameters: ScalingParametersStatus, } ``` The result of a `UpdateScalingParameters` request. Contains the status of the newly-configured scaling parameters. Fields --- `scaling_parameters: ScalingParametersStatus`Trait Implementations --- source### impl Clone for UpdateScalingParametersResponse source#### fn clone(&self) -> UpdateScalingParametersResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for UpdateScalingParametersResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for UpdateScalingParametersResponse source#### fn default() -> UpdateScalingParametersResponse Returns the “default value” for a type. Read more source### impl PartialEq<UpdateScalingParametersResponse> for UpdateScalingParametersResponse source#### fn eq(&self, other: &UpdateScalingParametersResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateScalingParametersResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateScalingParametersResponse Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateScalingParametersResponse ### impl Send for UpdateScalingParametersResponse ### impl Sync for UpdateScalingParametersResponse ### impl Unpin for UpdateScalingParametersResponse ### impl UnwindSafe for UpdateScalingParametersResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::UpdateServiceAccessPoliciesRequest === ``` pub struct UpdateServiceAccessPoliciesRequest { pub access_policies: String, pub domain_name: String, } ``` Container for the parameters to the `UpdateServiceAccessPolicies` operation. Specifies the name of the domain you want to update and the access rules you want to configure. Fields --- `access_policies: String`The access rules you want to configure. These rules replace any existing rules. `domain_name: String`Trait Implementations --- source### impl Clone for UpdateServiceAccessPoliciesRequest source#### fn clone(&self) -> UpdateServiceAccessPoliciesRequest Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for UpdateServiceAccessPoliciesRequest source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for UpdateServiceAccessPoliciesRequest source#### fn default() -> UpdateServiceAccessPoliciesRequest Returns the “default value” for a type. Read more source### impl PartialEq<UpdateServiceAccessPoliciesRequest> for UpdateServiceAccessPoliciesRequest source#### fn eq(&self, other: &UpdateServiceAccessPoliciesRequest) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateServiceAccessPoliciesRequest) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateServiceAccessPoliciesRequest Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateServiceAccessPoliciesRequest ### impl Send for UpdateServiceAccessPoliciesRequest ### impl Sync for UpdateServiceAccessPoliciesRequest ### impl Unpin for UpdateServiceAccessPoliciesRequest ### impl UnwindSafe for UpdateServiceAccessPoliciesRequest Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Struct rusoto_cloudsearch::UpdateServiceAccessPoliciesResponse === ``` pub struct UpdateServiceAccessPoliciesResponse { pub access_policies: AccessPoliciesStatus, } ``` The result of an `UpdateServiceAccessPolicies` request. Contains the new access policies. Fields --- `access_policies: AccessPoliciesStatus`The access rules configured for the domain. Trait Implementations --- source### impl Clone for UpdateServiceAccessPoliciesResponse source#### fn clone(&self) -> UpdateServiceAccessPoliciesResponse Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for UpdateServiceAccessPoliciesResponse source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for UpdateServiceAccessPoliciesResponse source#### fn default() -> UpdateServiceAccessPoliciesResponse Returns the “default value” for a type. Read more source### impl PartialEq<UpdateServiceAccessPoliciesResponse> for UpdateServiceAccessPoliciesResponse source#### fn eq(&self, other: &UpdateServiceAccessPoliciesResponse) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateServiceAccessPoliciesResponse) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateServiceAccessPoliciesResponse Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateServiceAccessPoliciesResponse ### impl Send for UpdateServiceAccessPoliciesResponse ### impl Sync for UpdateServiceAccessPoliciesResponse ### impl Unpin for UpdateServiceAccessPoliciesResponse ### impl UnwindSafe for UpdateServiceAccessPoliciesResponse Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) 🔬 This is a nightly-only experimental API. (`toowned_clone_into`)Uses borrowed data to replace owned data, usually by cloning. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::BuildSuggestersError === ``` pub enum BuildSuggestersError { Base(String), Internal(String), ResourceNotFound(String), } ``` Errors returned by BuildSuggesters Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl BuildSuggestersError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<BuildSuggestersErrorTrait Implementations --- source### impl Debug for BuildSuggestersError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for BuildSuggestersError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for BuildSuggestersError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<BuildSuggestersError> for BuildSuggestersError source#### fn eq(&self, other: &BuildSuggestersError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &BuildSuggestersError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for BuildSuggestersError Auto Trait Implementations --- ### impl RefUnwindSafe for BuildSuggestersError ### impl Send for BuildSuggestersError ### impl Sync for BuildSuggestersError ### impl Unpin for BuildSuggestersError ### impl UnwindSafe for BuildSuggestersError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::CreateDomainError === ``` pub enum CreateDomainError { Base(String), Internal(String), LimitExceeded(String), ResourceAlreadyExists(String), Validation(String), } ``` Errors returned by CreateDomain Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `LimitExceeded(String)` The request was rejected because a resource limit has already been met. ### `ResourceAlreadyExists(String)` The request was rejected because it attempted to create a resource that already exists. ### `Validation(String)` The request was rejected because it has invalid parameters. Implementations --- source### impl CreateDomainError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<CreateDomainErrorTrait Implementations --- source### impl Debug for CreateDomainError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for CreateDomainError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for CreateDomainError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<CreateDomainError> for CreateDomainError source#### fn eq(&self, other: &CreateDomainError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &CreateDomainError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for CreateDomainError Auto Trait Implementations --- ### impl RefUnwindSafe for CreateDomainError ### impl Send for CreateDomainError ### impl Sync for CreateDomainError ### impl Unpin for CreateDomainError ### impl UnwindSafe for CreateDomainError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DefineAnalysisSchemeError === ``` pub enum DefineAnalysisSchemeError { Base(String), Internal(String), InvalidType(String), LimitExceeded(String), ResourceNotFound(String), } ``` Errors returned by DefineAnalysisScheme Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `LimitExceeded(String)` The request was rejected because a resource limit has already been met. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DefineAnalysisSchemeError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DefineAnalysisSchemeErrorTrait Implementations --- source### impl Debug for DefineAnalysisSchemeError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DefineAnalysisSchemeError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DefineAnalysisSchemeError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DefineAnalysisSchemeError> for DefineAnalysisSchemeError source#### fn eq(&self, other: &DefineAnalysisSchemeError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineAnalysisSchemeError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineAnalysisSchemeError Auto Trait Implementations --- ### impl RefUnwindSafe for DefineAnalysisSchemeError ### impl Send for DefineAnalysisSchemeError ### impl Sync for DefineAnalysisSchemeError ### impl Unpin for DefineAnalysisSchemeError ### impl UnwindSafe for DefineAnalysisSchemeError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DefineExpressionError === ``` pub enum DefineExpressionError { Base(String), Internal(String), InvalidType(String), LimitExceeded(String), ResourceNotFound(String), } ``` Errors returned by DefineExpression Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `LimitExceeded(String)` The request was rejected because a resource limit has already been met. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DefineExpressionError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DefineExpressionErrorTrait Implementations --- source### impl Debug for DefineExpressionError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DefineExpressionError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DefineExpressionError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DefineExpressionError> for DefineExpressionError source#### fn eq(&self, other: &DefineExpressionError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineExpressionError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineExpressionError Auto Trait Implementations --- ### impl RefUnwindSafe for DefineExpressionError ### impl Send for DefineExpressionError ### impl Sync for DefineExpressionError ### impl Unpin for DefineExpressionError ### impl UnwindSafe for DefineExpressionError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DefineIndexFieldError === ``` pub enum DefineIndexFieldError { Base(String), Internal(String), InvalidType(String), LimitExceeded(String), ResourceNotFound(String), } ``` Errors returned by DefineIndexField Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `LimitExceeded(String)` The request was rejected because a resource limit has already been met. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DefineIndexFieldError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DefineIndexFieldErrorTrait Implementations --- source### impl Debug for DefineIndexFieldError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DefineIndexFieldError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DefineIndexFieldError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DefineIndexFieldError> for DefineIndexFieldError source#### fn eq(&self, other: &DefineIndexFieldError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineIndexFieldError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineIndexFieldError Auto Trait Implementations --- ### impl RefUnwindSafe for DefineIndexFieldError ### impl Send for DefineIndexFieldError ### impl Sync for DefineIndexFieldError ### impl Unpin for DefineIndexFieldError ### impl UnwindSafe for DefineIndexFieldError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DefineSuggesterError === ``` pub enum DefineSuggesterError { Base(String), Internal(String), InvalidType(String), LimitExceeded(String), ResourceNotFound(String), } ``` Errors returned by DefineSuggester Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `LimitExceeded(String)` The request was rejected because a resource limit has already been met. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DefineSuggesterError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DefineSuggesterErrorTrait Implementations --- source### impl Debug for DefineSuggesterError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DefineSuggesterError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DefineSuggesterError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DefineSuggesterError> for DefineSuggesterError source#### fn eq(&self, other: &DefineSuggesterError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DefineSuggesterError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DefineSuggesterError Auto Trait Implementations --- ### impl RefUnwindSafe for DefineSuggesterError ### impl Send for DefineSuggesterError ### impl Sync for DefineSuggesterError ### impl Unpin for DefineSuggesterError ### impl UnwindSafe for DefineSuggesterError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DeleteAnalysisSchemeError === ``` pub enum DeleteAnalysisSchemeError { Base(String), Internal(String), InvalidType(String), ResourceNotFound(String), } ``` Errors returned by DeleteAnalysisScheme Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DeleteAnalysisSchemeError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DeleteAnalysisSchemeErrorTrait Implementations --- source### impl Debug for DeleteAnalysisSchemeError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DeleteAnalysisSchemeError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DeleteAnalysisSchemeError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DeleteAnalysisSchemeError> for DeleteAnalysisSchemeError source#### fn eq(&self, other: &DeleteAnalysisSchemeError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteAnalysisSchemeError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteAnalysisSchemeError Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteAnalysisSchemeError ### impl Send for DeleteAnalysisSchemeError ### impl Sync for DeleteAnalysisSchemeError ### impl Unpin for DeleteAnalysisSchemeError ### impl UnwindSafe for DeleteAnalysisSchemeError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DeleteDomainError === ``` pub enum DeleteDomainError { Base(String), Internal(String), } ``` Errors returned by DeleteDomain Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. Implementations --- source### impl DeleteDomainError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DeleteDomainErrorTrait Implementations --- source### impl Debug for DeleteDomainError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DeleteDomainError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DeleteDomainError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DeleteDomainError> for DeleteDomainError source#### fn eq(&self, other: &DeleteDomainError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteDomainError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteDomainError Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteDomainError ### impl Send for DeleteDomainError ### impl Sync for DeleteDomainError ### impl Unpin for DeleteDomainError ### impl UnwindSafe for DeleteDomainError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DeleteExpressionError === ``` pub enum DeleteExpressionError { Base(String), Internal(String), InvalidType(String), ResourceNotFound(String), } ``` Errors returned by DeleteExpression Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DeleteExpressionError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DeleteExpressionErrorTrait Implementations --- source### impl Debug for DeleteExpressionError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DeleteExpressionError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DeleteExpressionError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DeleteExpressionError> for DeleteExpressionError source#### fn eq(&self, other: &DeleteExpressionError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteExpressionError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteExpressionError Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteExpressionError ### impl Send for DeleteExpressionError ### impl Sync for DeleteExpressionError ### impl Unpin for DeleteExpressionError ### impl UnwindSafe for DeleteExpressionError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DeleteIndexFieldError === ``` pub enum DeleteIndexFieldError { Base(String), Internal(String), InvalidType(String), ResourceNotFound(String), } ``` Errors returned by DeleteIndexField Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DeleteIndexFieldError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DeleteIndexFieldErrorTrait Implementations --- source### impl Debug for DeleteIndexFieldError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DeleteIndexFieldError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DeleteIndexFieldError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DeleteIndexFieldError> for DeleteIndexFieldError source#### fn eq(&self, other: &DeleteIndexFieldError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteIndexFieldError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteIndexFieldError Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteIndexFieldError ### impl Send for DeleteIndexFieldError ### impl Sync for DeleteIndexFieldError ### impl Unpin for DeleteIndexFieldError ### impl UnwindSafe for DeleteIndexFieldError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DeleteSuggesterError === ``` pub enum DeleteSuggesterError { Base(String), Internal(String), InvalidType(String), ResourceNotFound(String), } ``` Errors returned by DeleteSuggester Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DeleteSuggesterError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DeleteSuggesterErrorTrait Implementations --- source### impl Debug for DeleteSuggesterError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DeleteSuggesterError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DeleteSuggesterError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DeleteSuggesterError> for DeleteSuggesterError source#### fn eq(&self, other: &DeleteSuggesterError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DeleteSuggesterError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DeleteSuggesterError Auto Trait Implementations --- ### impl RefUnwindSafe for DeleteSuggesterError ### impl Send for DeleteSuggesterError ### impl Sync for DeleteSuggesterError ### impl Unpin for DeleteSuggesterError ### impl UnwindSafe for DeleteSuggesterError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DescribeAnalysisSchemesError === ``` pub enum DescribeAnalysisSchemesError { Base(String), Internal(String), ResourceNotFound(String), } ``` Errors returned by DescribeAnalysisSchemes Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DescribeAnalysisSchemesError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DescribeAnalysisSchemesErrorTrait Implementations --- source### impl Debug for DescribeAnalysisSchemesError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DescribeAnalysisSchemesError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DescribeAnalysisSchemesError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DescribeAnalysisSchemesError> for DescribeAnalysisSchemesError source#### fn eq(&self, other: &DescribeAnalysisSchemesError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeAnalysisSchemesError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeAnalysisSchemesError Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeAnalysisSchemesError ### impl Send for DescribeAnalysisSchemesError ### impl Sync for DescribeAnalysisSchemesError ### impl Unpin for DescribeAnalysisSchemesError ### impl UnwindSafe for DescribeAnalysisSchemesError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DescribeAvailabilityOptionsError === ``` pub enum DescribeAvailabilityOptionsError { Base(String), DisabledOperation(String), Internal(String), InvalidType(String), LimitExceeded(String), ResourceNotFound(String), } ``` Errors returned by DescribeAvailabilityOptions Variants --- ### `Base(String)` An error occurred while processing the request. ### `DisabledOperation(String)` The request was rejected because it attempted an operation which is not enabled. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `LimitExceeded(String)` The request was rejected because a resource limit has already been met. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DescribeAvailabilityOptionsError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DescribeAvailabilityOptionsErrorTrait Implementations --- source### impl Debug for DescribeAvailabilityOptionsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DescribeAvailabilityOptionsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DescribeAvailabilityOptionsError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DescribeAvailabilityOptionsError> for DescribeAvailabilityOptionsError source#### fn eq(&self, other: &DescribeAvailabilityOptionsError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeAvailabilityOptionsError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeAvailabilityOptionsError Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeAvailabilityOptionsError ### impl Send for DescribeAvailabilityOptionsError ### impl Sync for DescribeAvailabilityOptionsError ### impl Unpin for DescribeAvailabilityOptionsError ### impl UnwindSafe for DescribeAvailabilityOptionsError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DescribeDomainEndpointOptionsError === ``` pub enum DescribeDomainEndpointOptionsError { Base(String), DisabledOperation(String), Internal(String), LimitExceeded(String), ResourceNotFound(String), } ``` Errors returned by DescribeDomainEndpointOptions Variants --- ### `Base(String)` An error occurred while processing the request. ### `DisabledOperation(String)` The request was rejected because it attempted an operation which is not enabled. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `LimitExceeded(String)` The request was rejected because a resource limit has already been met. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DescribeDomainEndpointOptionsError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DescribeDomainEndpointOptionsErrorTrait Implementations --- source### impl Debug for DescribeDomainEndpointOptionsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DescribeDomainEndpointOptionsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DescribeDomainEndpointOptionsError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DescribeDomainEndpointOptionsError> for DescribeDomainEndpointOptionsError source#### fn eq(&self, other: &DescribeDomainEndpointOptionsError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeDomainEndpointOptionsError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeDomainEndpointOptionsError Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeDomainEndpointOptionsError ### impl Send for DescribeDomainEndpointOptionsError ### impl Sync for DescribeDomainEndpointOptionsError ### impl Unpin for DescribeDomainEndpointOptionsError ### impl UnwindSafe for DescribeDomainEndpointOptionsError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DescribeDomainsError === ``` pub enum DescribeDomainsError { Base(String), Internal(String), } ``` Errors returned by DescribeDomains Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. Implementations --- source### impl DescribeDomainsError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DescribeDomainsErrorTrait Implementations --- source### impl Debug for DescribeDomainsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DescribeDomainsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DescribeDomainsError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DescribeDomainsError> for DescribeDomainsError source#### fn eq(&self, other: &DescribeDomainsError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeDomainsError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeDomainsError Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeDomainsError ### impl Send for DescribeDomainsError ### impl Sync for DescribeDomainsError ### impl Unpin for DescribeDomainsError ### impl UnwindSafe for DescribeDomainsError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DescribeExpressionsError === ``` pub enum DescribeExpressionsError { Base(String), Internal(String), ResourceNotFound(String), } ``` Errors returned by DescribeExpressions Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DescribeExpressionsError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DescribeExpressionsErrorTrait Implementations --- source### impl Debug for DescribeExpressionsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DescribeExpressionsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DescribeExpressionsError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DescribeExpressionsError> for DescribeExpressionsError source#### fn eq(&self, other: &DescribeExpressionsError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeExpressionsError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeExpressionsError Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeExpressionsError ### impl Send for DescribeExpressionsError ### impl Sync for DescribeExpressionsError ### impl Unpin for DescribeExpressionsError ### impl UnwindSafe for DescribeExpressionsError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DescribeIndexFieldsError === ``` pub enum DescribeIndexFieldsError { Base(String), Internal(String), ResourceNotFound(String), } ``` Errors returned by DescribeIndexFields Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DescribeIndexFieldsError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DescribeIndexFieldsErrorTrait Implementations --- source### impl Debug for DescribeIndexFieldsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DescribeIndexFieldsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DescribeIndexFieldsError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DescribeIndexFieldsError> for DescribeIndexFieldsError source#### fn eq(&self, other: &DescribeIndexFieldsError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeIndexFieldsError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeIndexFieldsError Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeIndexFieldsError ### impl Send for DescribeIndexFieldsError ### impl Sync for DescribeIndexFieldsError ### impl Unpin for DescribeIndexFieldsError ### impl UnwindSafe for DescribeIndexFieldsError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DescribeScalingParametersError === ``` pub enum DescribeScalingParametersError { Base(String), Internal(String), ResourceNotFound(String), } ``` Errors returned by DescribeScalingParameters Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DescribeScalingParametersError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DescribeScalingParametersErrorTrait Implementations --- source### impl Debug for DescribeScalingParametersError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DescribeScalingParametersError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DescribeScalingParametersError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DescribeScalingParametersError> for DescribeScalingParametersError source#### fn eq(&self, other: &DescribeScalingParametersError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeScalingParametersError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeScalingParametersError Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeScalingParametersError ### impl Send for DescribeScalingParametersError ### impl Sync for DescribeScalingParametersError ### impl Unpin for DescribeScalingParametersError ### impl UnwindSafe for DescribeScalingParametersError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DescribeServiceAccessPoliciesError === ``` pub enum DescribeServiceAccessPoliciesError { Base(String), Internal(String), ResourceNotFound(String), } ``` Errors returned by DescribeServiceAccessPolicies Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DescribeServiceAccessPoliciesError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DescribeServiceAccessPoliciesErrorTrait Implementations --- source### impl Debug for DescribeServiceAccessPoliciesError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DescribeServiceAccessPoliciesError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DescribeServiceAccessPoliciesError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DescribeServiceAccessPoliciesError> for DescribeServiceAccessPoliciesError source#### fn eq(&self, other: &DescribeServiceAccessPoliciesError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeServiceAccessPoliciesError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeServiceAccessPoliciesError Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeServiceAccessPoliciesError ### impl Send for DescribeServiceAccessPoliciesError ### impl Sync for DescribeServiceAccessPoliciesError ### impl Unpin for DescribeServiceAccessPoliciesError ### impl UnwindSafe for DescribeServiceAccessPoliciesError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::DescribeSuggestersError === ``` pub enum DescribeSuggestersError { Base(String), Internal(String), ResourceNotFound(String), } ``` Errors returned by DescribeSuggesters Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl DescribeSuggestersError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<DescribeSuggestersErrorTrait Implementations --- source### impl Debug for DescribeSuggestersError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for DescribeSuggestersError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for DescribeSuggestersError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<DescribeSuggestersError> for DescribeSuggestersError source#### fn eq(&self, other: &DescribeSuggestersError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DescribeSuggestersError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for DescribeSuggestersError Auto Trait Implementations --- ### impl RefUnwindSafe for DescribeSuggestersError ### impl Send for DescribeSuggestersError ### impl Sync for DescribeSuggestersError ### impl Unpin for DescribeSuggestersError ### impl UnwindSafe for DescribeSuggestersError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::IndexDocumentsError === ``` pub enum IndexDocumentsError { Base(String), Internal(String), ResourceNotFound(String), } ``` Errors returned by IndexDocuments Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl IndexDocumentsError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<IndexDocumentsErrorTrait Implementations --- source### impl Debug for IndexDocumentsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for IndexDocumentsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for IndexDocumentsError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<IndexDocumentsError> for IndexDocumentsError source#### fn eq(&self, other: &IndexDocumentsError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &IndexDocumentsError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for IndexDocumentsError Auto Trait Implementations --- ### impl RefUnwindSafe for IndexDocumentsError ### impl Send for IndexDocumentsError ### impl Sync for IndexDocumentsError ### impl Unpin for IndexDocumentsError ### impl UnwindSafe for IndexDocumentsError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::ListDomainNamesError === ``` pub enum ListDomainNamesError { Base(String), } ``` Errors returned by ListDomainNames Variants --- ### `Base(String)` An error occurred while processing the request. Implementations --- source### impl ListDomainNamesError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<ListDomainNamesErrorTrait Implementations --- source### impl Debug for ListDomainNamesError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for ListDomainNamesError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for ListDomainNamesError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<ListDomainNamesError> for ListDomainNamesError source#### fn eq(&self, other: &ListDomainNamesError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &ListDomainNamesError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for ListDomainNamesError Auto Trait Implementations --- ### impl RefUnwindSafe for ListDomainNamesError ### impl Send for ListDomainNamesError ### impl Sync for ListDomainNamesError ### impl Unpin for ListDomainNamesError ### impl UnwindSafe for ListDomainNamesError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::UpdateAvailabilityOptionsError === ``` pub enum UpdateAvailabilityOptionsError { Base(String), DisabledOperation(String), Internal(String), InvalidType(String), LimitExceeded(String), ResourceNotFound(String), Validation(String), } ``` Errors returned by UpdateAvailabilityOptions Variants --- ### `Base(String)` An error occurred while processing the request. ### `DisabledOperation(String)` The request was rejected because it attempted an operation which is not enabled. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `LimitExceeded(String)` The request was rejected because a resource limit has already been met. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. ### `Validation(String)` The request was rejected because it has invalid parameters. Implementations --- source### impl UpdateAvailabilityOptionsError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<UpdateAvailabilityOptionsErrorTrait Implementations --- source### impl Debug for UpdateAvailabilityOptionsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for UpdateAvailabilityOptionsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for UpdateAvailabilityOptionsError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<UpdateAvailabilityOptionsError> for UpdateAvailabilityOptionsError source#### fn eq(&self, other: &UpdateAvailabilityOptionsError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateAvailabilityOptionsError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateAvailabilityOptionsError Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateAvailabilityOptionsError ### impl Send for UpdateAvailabilityOptionsError ### impl Sync for UpdateAvailabilityOptionsError ### impl Unpin for UpdateAvailabilityOptionsError ### impl UnwindSafe for UpdateAvailabilityOptionsError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::UpdateDomainEndpointOptionsError === ``` pub enum UpdateDomainEndpointOptionsError { Base(String), DisabledOperation(String), Internal(String), InvalidType(String), LimitExceeded(String), ResourceNotFound(String), Validation(String), } ``` Errors returned by UpdateDomainEndpointOptions Variants --- ### `Base(String)` An error occurred while processing the request. ### `DisabledOperation(String)` The request was rejected because it attempted an operation which is not enabled. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `LimitExceeded(String)` The request was rejected because a resource limit has already been met. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. ### `Validation(String)` The request was rejected because it has invalid parameters. Implementations --- source### impl UpdateDomainEndpointOptionsError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<UpdateDomainEndpointOptionsErrorTrait Implementations --- source### impl Debug for UpdateDomainEndpointOptionsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for UpdateDomainEndpointOptionsError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for UpdateDomainEndpointOptionsError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<UpdateDomainEndpointOptionsError> for UpdateDomainEndpointOptionsError source#### fn eq(&self, other: &UpdateDomainEndpointOptionsError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateDomainEndpointOptionsError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateDomainEndpointOptionsError Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateDomainEndpointOptionsError ### impl Send for UpdateDomainEndpointOptionsError ### impl Sync for UpdateDomainEndpointOptionsError ### impl Unpin for UpdateDomainEndpointOptionsError ### impl UnwindSafe for UpdateDomainEndpointOptionsError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::UpdateScalingParametersError === ``` pub enum UpdateScalingParametersError { Base(String), Internal(String), InvalidType(String), LimitExceeded(String), ResourceNotFound(String), } ``` Errors returned by UpdateScalingParameters Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `LimitExceeded(String)` The request was rejected because a resource limit has already been met. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl UpdateScalingParametersError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<UpdateScalingParametersErrorTrait Implementations --- source### impl Debug for UpdateScalingParametersError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for UpdateScalingParametersError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for UpdateScalingParametersError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<UpdateScalingParametersError> for UpdateScalingParametersError source#### fn eq(&self, other: &UpdateScalingParametersError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateScalingParametersError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateScalingParametersError Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateScalingParametersError ### impl Send for UpdateScalingParametersError ### impl Sync for UpdateScalingParametersError ### impl Unpin for UpdateScalingParametersError ### impl UnwindSafe for UpdateScalingParametersError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more Enum rusoto_cloudsearch::UpdateServiceAccessPoliciesError === ``` pub enum UpdateServiceAccessPoliciesError { Base(String), Internal(String), InvalidType(String), LimitExceeded(String), ResourceNotFound(String), } ``` Errors returned by UpdateServiceAccessPolicies Variants --- ### `Base(String)` An error occurred while processing the request. ### `Internal(String)` An internal error occurred while processing the request. If this problem persists, report an issue from the Service Health Dashboard. ### `InvalidType(String)` The request was rejected because it specified an invalid type definition. ### `LimitExceeded(String)` The request was rejected because a resource limit has already been met. ### `ResourceNotFound(String)` The request was rejected because it attempted to reference a resource that does not exist. Implementations --- source### impl UpdateServiceAccessPoliciesError source#### pub fn from_response(    res: BufferedHttpResponse) -> RusotoError<UpdateServiceAccessPoliciesErrorTrait Implementations --- source### impl Debug for UpdateServiceAccessPoliciesError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for UpdateServiceAccessPoliciesError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for UpdateServiceAccessPoliciesError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source### impl PartialEq<UpdateServiceAccessPoliciesError> for UpdateServiceAccessPoliciesError source#### fn eq(&self, other: &UpdateServiceAccessPoliciesError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &UpdateServiceAccessPoliciesError) -> bool This method tests for `!=`. source### impl StructuralPartialEq for UpdateServiceAccessPoliciesError Auto Trait Implementations --- ### impl RefUnwindSafe for UpdateServiceAccessPoliciesError ### impl Send for UpdateServiceAccessPoliciesError ### impl Sync for UpdateServiceAccessPoliciesError ### impl Unpin for UpdateServiceAccessPoliciesError ### impl UnwindSafe for UpdateServiceAccessPoliciesError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T> Instrument for T source#### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more source#### fn in_current_span(self) -> Instrumented<SelfInstruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. source### impl<T> Same<T> for T #### type Output = T Should always be `Self` source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. source### impl<T> WithSubscriber for T source#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where    S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more source#### fn with_current_subscriber(self) -> WithDispatch<SelfAttaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more
aws-insight
ruby
Ruby
Terraforming === [![Build Status](https://travis-ci.org/dtan4/terraforming.svg?branch=master)](https://travis-ci.org/dtan4/terraforming) [![Code Climate](https://codeclimate.com/github/dtan4/terraforming/badges/gpa.svg)](https://codeclimate.com/github/dtan4/terraforming) [![Coverage Status](https://coveralls.io/repos/github/dtan4/terraforming/badge.svg?branch=increase-test-cov-160528)](https://coveralls.io/github/dtan4/terraforming) [![Dependency Status](https://gemnasium.com/dtan4/terraforming.svg)](https://gemnasium.com/dtan4/terraforming) [![Gem Version](https://badge.fury.io/rb/terraforming.svg)](http://badge.fury.io/rb/terraforming) [![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](LICENSE) [![Docker Repository on Quay.io](https://quay.io/repository/dtan4/terraforming/status "Docker Repository on Quay.io")](https://quay.io/repository/dtan4/terraforming) [![Join the chat at https://gitter.im/dtan4/terraforming](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/dtan4/terraforming?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) Export existing AWS resources to [Terraform](https://terraform.io/) style (tf, tfstate) * [Supported version](#supported-version) * [Installation](#installation) * [Prerequisites](#prerequisites) * [Usage](#usage) + [Export tf](#export-tf) + [Export tfstate](#export-tfstate) + [Example: Export all](#example-export-all) * [Run as Docker container](#run-as-docker-container-) * [Development](#development) * [Contributing](#contributing) * [License](#license) Supported version --- Ruby 2.1 or higher Installation --- Add this line to your application's Gemfile: ``` gem 'terraforming' ``` And then execute: ``` $ bundle ``` Or install it yourself as: ``` $ gem install terraforming ``` Prerequisites --- You need to set AWS credentials. ``` export AWS_ACCESS_KEY_ID=<KEY>XXXX export AWS_SECRET_ACCESS_KEY=<KEY>xxxxxxxx export AWS_REGION=xx-yyyy-0 ``` You can also specify credential profile in `~/.aws/credentials` by `--profile` option. ``` $ cat ~/.aws/credentials [hoge] aws_access_key_id = Hoge aws_secret_access_key = FugaFuga # Pass profile name by --profile option $ terraforming s3 --profile hoge ``` You can force the AWS SDK to utilize the CA certificate that is bundled with the SDK for systems where the default OpenSSL certificate is not installed (e.g. Windows) by utilizing the `--use-bundled-cert` option. ``` PS C:\> terraforming ec2 --use-bundled-cert ``` Usage --- ``` $ terraforming Commands: terraforming alb # ALB terraforming asg # AutoScaling Group terraforming cwa # CloudWatch Alarm terraforming dbpg # Database Parameter Group terraforming dbsg # Database Security Group terraforming dbsn # Database Subnet Group terraforming ec2 # EC2 terraforming ecc # ElastiCache Cluster terraforming ecsn # ElastiCache Subnet Group terraforming efs # EFS File System terraforming eip # EIP terraforming elb # ELB terraforming help [COMMAND] # Describe available commands or one specific command terraforming iamg # IAM Group terraforming iamgm # IAM Group Membership terraforming iamgp # IAM Group Policy terraforming iamip # IAM Instance Profile terraforming iamp # IAM Policy terraforming iampa # IAM Policy Attachment terraforming iamr # IAM Role terraforming iamrp # IAM Role Policy terraforming iamu # IAM User terraforming iamup # IAM User Policy terraforming igw # Internet Gateway terraforming kmsa # KMS Key Alias terraforming kmsk # KMS Key terraforming lc # Launch Configuration terraforming nacl # Network ACL terraforming nat # NAT Gateway terraforming nif # Network Interface terraforming r53r # Route53 Record terraforming r53z # Route53 Hosted Zone terraforming rds # RDS terraforming rs # Redshift terraforming rt # Route Table terraforming rta # Route Table Association terraforming s3 # S3 terraforming sg # Security Group terraforming sn # Subnet terraforming snst # SNS Topic terraforming snss # SNS Subscription terraforming sqs # SQS terraforming vgw # VPN Gateway terraforming vpc # VPC Options: [--merge=MERGE] # tfstate file to merge [--overwrite], [--no-overwrite] # Overwrite existng tfstate [--tfstate], [--no-tfstate] # Generate tfstate [--profile=PROFILE] # AWS credentials profile [--region=REGION] # AWS region [--use-bundled-cert], [--no-use-bundled-cert] # Use the bundled CA certificate from AWS SDK ``` ### Export tf ``` $ terraforming <resource> [--profile PROFILE] ``` (e.g. S3 buckets): ``` $ terraforming s3 ``` ``` resource "aws_s3_bucket" "hoge" { bucket = "hoge" acl = "private" } resource "aws_s3_bucket" "fuga" { bucket = "fuga" acl = "private" } ``` ### Export tfstate ``` $ terraforming <resource> --tfstate [--merge TFSTATE_PATH] [--overwrite] [--profile PROFILE] ``` (e.g. S3 buckets): ``` $ terraforming s3 --tfstate ``` ``` { "version": 1, "serial": 1, "modules": { "path": [ "root" ], "outputs": { }, "resources": { "aws_s3_bucket.hoge": { "type": "aws_s3_bucket", "primary": { "id": "hoge", "attributes": { "acl": "private", "bucket": "hoge", "id": "hoge" } } }, "aws_s3_bucket.fuga": { "type": "aws_s3_bucket", "primary": { "id": "fuga", "attributes": { "acl": "private", "bucket": "fuga", "id": "fuga" } } } } } } ``` If you want to merge exported tfstate to existing `terraform.tfstate`, specify `--tfstate --merge=/path/to/terraform.tfstate` option. You can overwrite existing `terraform.tfstate` by specifying `--overwrite` option together. Existing `terraform.tfstate`: ``` # /path/to/terraform.tfstate { "version": 1, "serial": 88, "remote": { "type": "s3", "config": { "bucket": "terraforming-tfstate", "key": "tf" } }, "modules": { "path": [ "root" ], "outputs": { }, "resources": { "aws_elb.hogehoge": { "type": "aws_elb", "primary": { "id": "hogehoge", "attributes": { "availability_zones.#": "2", "connection_draining": "true", "connection_draining_timeout": "300", "cross_zone_load_balancing": "true", "dns_name": "hoge-12345678.ap-northeast-1.elb.amazonaws.com", "health_check.#": "1", "id": "hogehoge", "idle_timeout": "60", "instances.#": "1", "listener.#": "1", "name": "hoge", "security_groups.#": "2", "source_security_group": "default", "subnets.#": "2" } } } } } } ``` To generate merged tfstate: ``` $ terraforming s3 --tfstate --merge=/path/to/tfstate ``` ``` { "version": 1, "serial": 89, "remote": { "type": "s3", "config": { "bucket": "terraforming-tfstate", "key": "tf" } }, "modules": { "path": [ "root" ], "outputs": { }, "resources": { "aws_elb.hogehoge": { "type": "aws_elb", "primary": { "id": "hogehoge", "attributes": { "availability_zones.#": "2", "connection_draining": "true", "connection_draining_timeout": "300", "cross_zone_load_balancing": "true", "dns_name": "hoge-12345678.ap-northeast-1.elb.amazonaws.com", "health_check.#": "1", "id": "hogehoge", "idle_timeout": "60", "instances.#": "1", "listener.#": "1", "name": "hoge", "security_groups.#": "2", "source_security_group": "default", "subnets.#": "2" } } }, "aws_s3_bucket.hoge": { "type": "aws_s3_bucket", "primary": { "id": "hoge", "attributes": { "acl": "private", "bucket": "hoge", "id": "hoge" } } }, "aws_s3_bucket.fuga": { "type": "aws_s3_bucket", "primary": { "id": "fuga", "attributes": { "acl": "private", "bucket": "fuga", "id": "fuga" } } } } } } ``` After writing exported tf and tfstate to files, execute `terraform plan` and check the result. There should be no diff. ``` $ terraform plan No changes. Infrastructure is up-to-date. This means that Terraform could not detect any differences between your configuration and the real physical resources that exist. As a result, Terraform doesn't need to do anything. ``` #### Example: Export all Example assuming you want to export everything from us-west-2 and you are using ~/.aws/credentials with a `default` profile ``` export AWS_REGION=us-west-2 terraforming help | grep terraforming | grep -v help | awk '{print "terraforming", $2, "--profile", "default", ">", $2".tf";}' | bash # find files that only have 1 empty line (likely nothing in AWS) find . -type f -name '*.tf' | xargs wc -l | grep ' 1 .' ``` Run as Docker container [Docker Repository on Quay.io](https://quay.io/repository/dtan4/terraforming) --- Terraforming Docker Image is available at [quay.io/dtan4/terraforming](https://quay.io/repository/dtan4/terraforming) and developed at [dtan4/dockerfile-terraforming](https://github.com/dtan4/dockerfile-terraforming). Pull the Docker image: ``` $ docker pull quay.io/dtan4/terraforming:latest ``` And then run Terraforming as a Docker container: ``` $ docker run \ --rm \ --name terraforming \ -e AWS_ACCESS_KEY_ID=<KEY> \ -e AWS_SECRET_ACCESS_KEY=<KEY> \ -e AWS_REGION=xx-yyyy-0 \ quay.io/dtan4/terraforming:latest \ terraforming s3 ``` Development --- After checking out the repo, run `script/setup` to install dependencies. Then, run `script/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). Contributing --- Please read [Contribution Guide](CONTRIBUTING.md) at first. 1. Fork it ( <https://github.com/dtan4/terraforming/fork> ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request License --- [![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](LICENSE)
github.com/appscode/chartify
go
Go
README [¶](#section-readme) --- [Website](https://appscode.com) • [Slack](https://slack.appscode.com) • [Twitter](https://twitter.com/AppsCodeHQ) ### chartify Generate Helm Charts from Kubernetes api objects #### Installation ``` go get -u kubepack.dev/chartify ``` #### Usage You can provide Kubernetes objects as YAML/JSON files in a directory using --kube-dir flag. Or, you can read Kubernetes objects from a cluster. Chartify will read objects from the current context of your local kubeconfig file. You can use this as a standalone cli or a Helm plugin. ``` chartify create NAME [FLAGS] ``` ##### Options ``` --chart-dir string Specify the location where charts will be created (default "charts") --configmaps stringSlice Specify the names of configmaps(configmap@namespace) to include in chart --daemons stringSlice Specify the names of daemons(daemon@namespace) to include in chart --deployments stringSlice Specify the names of deployments(deployments@namespace) to include in chart --jobs stringSlice Specify the names of jobs(job@namespace) to include in chart --kube-dir string Specify the directory of the yaml files for Kubernetes objects --pods stringSlice Specify the names of pods(pod@namespace) to include in chart --pvcs stringSlice Specify the names of persistent volume claims(pvc@namespace) to include in chart --pvs stringSlice Specify the names of persistent volumes(pv@namespace) to include in chart --rcs stringSlice Specify the names of replication cotrollers(rc@namespace) to include in chart --replicasets stringSlice Specify the names of replica sets(rs@namespace) to include in chart --secrets stringSlice Specify the names of secrets(secret@namespace) to include in chart --services stringSlice Specify the names of services(service@namespace) to include in chart --statefulsets stringSlice Specify the names of statefulsets(statefulset@namespace) to include in chart --storageclasses stringSlice Specify the names of storageclasses(storageclass@namespace) to include in chart --preserve-name bool Specify if you want to preserve resources name from input yaml true/false (default: false) ``` ##### Issues Please file an issue if you think you've found a bug. Be sure to describe * How can it be reproduced? * What did you expect? * What actually occurred? * Kubernetes version, Helm version, Go version, platform, etc. if possibly relevant. Documentation [¶](#section-documentation) --- ![The Go Gopher](/static/shared/gopher/airplane-1200x945.svg) There is no documentation for this package.
elfgen
cran
R
Package ‘elfgen’ October 13, 2022 Title Ecological Limit Function Model Generation and Analysis Toolkit Version 2.3.3 Maintainer <NAME> <<EMAIL>> Description A toolset for generating Ecological Limit Function (ELF) models and evaluating poten- tial species loss resulting from flow change, based on the 'elfgen' framework. ELFs de- scribe the relation between aquatic species richness (fish or benthic macroinverte- brates) and stream size characteristics (streamflow or drainage area). Journal publica- tions are available outlining framework methodology (Kleiner et al. (2020) <doi:10.1111/1752- 1688.12876>) and application (Rapp et al. (2020) <doi:10.1111/1752-1688.12877>). Imports utils, stringr, quantreg, stats, ggplot2, testit, scales, sqldf, curl, sbtools, nhdplusTools License MIT + file LICENSE URL https://github.com/HARPgroup/elfgen RoxygenNote 7.1.2 Suggests testthat (>= 2.1.0) NeedsCompilation no Author <NAME> [aut, cre] (<https://orcid.org/0000-0003-4837-7678>) Repository CRAN Date/Publication 2022-08-23 09:10:02 UTC R topics documented: bkpt_pwi... 2 bkpt_yma... 3 clean_vahydr... 3 elfchang... 4 elfdat... 5 elfdata_vahydr... 6 elfge... 7 richness_chang... 8 bkpt_pwit Identify breakpoint location with PWIT Description This applies the Piecewise Iterative elfgen method. This approach uses an iterative algorithm to identify shifts in the relation between maximum richness and stream size. A user specifies a "quan- tile" for isolating an upper subset of the data. A user also identifies a bounding range between two x-values ("blo" = "bound low", "bhi" = "bound high") in which the upper subest of data is believed to contain a breakpoint. (Note: Small datasets may not contain a breakpoint) Usage bkpt_pwit(watershed.df, quantile, blo, bhi) Arguments watershed.df A dataframe of sites with ecological and hydrologic data quantile Specified value for the quantile of interest - 0.95 refers to the 95th percentile blo A "bound low" value, or the lower bound of the piecewise range bhi A "bound high" value, or the upper bound of the piecewise range Details See: Lemoine, N. 2012. "R for Ecologists: Putting Together a Piecewise Regression." https://www.r- bloggers.com/r-for-ecologists-putting-together-a-piecewise-regression/ The R Book, Second Edi- tion. <NAME>. 2013 John Wiley & Sons, Ltd. Published 2013 by John Wiley & Sons, Ltd. Value Breakpoint value is returned Examples # We don't run this example by R CMD check, because it takes >10s watershed.df <- elfdata(watershed.code = '0208020104', ichthy.localpath = tempdir()) bkpt_pwit(watershed.df,0.85,100,300) bkpt_ymax Identify breakpoint location with Ymax Description This applies the Ymax elfgen method. This approach treats the maximum observed species richness value as the breakpoint. This function begins by locating the point with the highest y-value in the full dataset, then utilizing the associated x-value as the breakpoint. Usage bkpt_ymax(watershed.df) Arguments watershed.df A dataframe of sites with ecological and hydrologic data Value Breakpoint value is returned Examples # We don't run this example by R CMD check, because it takes >10s watershed.df <- elfdata(watershed.code = '0208020104', ichthy.localpath = tempdir()) bkpt_ymax(watershed.df) clean_vahydro Clean dataset of ecological and hydrologic data Description Given a dataframe of flow metric and richness metric data (Typically retrieved from the DEQ VAHy- dro database), removes all sites where the ratio of Drainage Area:Mean Annual Flow is greater than 1000, also aggregates to the maximum richness value at each x-metric value Usage clean_vahydro(watershed.df) Arguments watershed.df A dataframe of sites with ecological and hydrologic data Value A cleaned dataframe of sites with ecological and hydrologic data Examples # We don't run this example by R CMD check, because it takes >10s # Retrieve dataset of interest watershed.df <- data.frame( MAF = c(100, 200, 300, 400, 526, 600, 700, 800, 400, 900, 1000, 100, 100), NT.TOTAL.UNIQUE = c(10, 20, 30, 40, 50, 40, 30 , 20, 50, 10, 10,99999,87), watershed.code = "test_testcode", hydrocode = c("t1","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11","t12","t13"), DA_SQMI = c(110, 220000, 280, 360, 530, 604, 712, 698, 40000, 905, 1087, 98, 87), x.metric = c(100, 200, 300, 400, 526, 600, 700, 800, 400, 900, 1000, 100, 100) ) # Clean the dataset clean_vahydro(watershed.df) elfchange Plot percent richness change for various percent flow reductions Description Calculates and plots percent richness change resulting from streamflow reductions Usage elfchange(stats, yaxis_thresh, xlabel = FALSE, ylabel = FALSE) Arguments stats A dataframe of ELF statistics yaxis_thresh Value used for specifying y-axis max limit xlabel Used to overwrite default x-axis label ylabel Used to overwrite default y-axis label Value Plot of percent decreases in richness from flow reductions Examples # We don't run this example by R CMD check, because it takes >10s # Generate plot of percent richness change for various percent flow reductions watershed.df <- elfdata(watershed.code = '0208020104', ichthy.localpath = tempdir()) breakpt <- 500 elf <- elfgen( "watershed.df" = watershed.df, "quantile" = 0.95, "breakpt" = breakpt, "xlabel" = "Mean Annual Flow (ft3/s)", "ylabel" = "Fish Species Richness" ) elfchange(elf$stats, "yaxis_thresh" = 25) elfdata Retrieve and format data for ELF generation Description Given a HUC code, provides a dataframe of all contained nhdplus segments and their individual NT Total and Mean Annual Flow MAF values Usage elfdata(watershed.code, ichthy.localpath) Arguments watershed.code Hydrologic unit code, either HUC6, HUC8, HUC10, or HUC12 (e.g. HUC10 code ’0208020101’). ichthy.localpath Local file path for storing downloaded ichthy data. Defaults to a temp directory. Value A dataframe of nhdplus segments containing species richness data (NT Total values) and mean annual flow (MAF) data. Examples # We don't run this example by R CMD check, because it takes >10s # Retrieve dataset of interest # You may enter either a 6, 8, 10, or 12-digit HUC code. # By default the ichthy dataset is downloaded to a temp directory, however this may be overridden by # supplying a local path of interest using the input parameter 'ichthy.localpath' watershed.df <- elfdata(watershed.code = '0208020104', ichthy.localpath = tempdir()) head(watershed.df) elfdata_vahydro Retrieve data from DEQ VAHydro database and format data for ELF generation. Contact Virginia DEQ Office of Water Supply to request access to the VAHydro database. Description Given a set of VAHydro input parameters, outputs a dataframe of flow metric and richness metric data for hydrologic unit supplied Usage elfdata_vahydro( watershed.code, watershed.bundle, watershed.ftype, x.metric, y.metric, y.sampres, datasite, EDAS.localpath = tempdir() ) Arguments watershed.code Hydrologic unit code, either HUC6, HUC8, HUC10, or HUC12 (e.g. HUC10 code ’0208020101’). watershed.bundle dH bundle of hydrologic unit watershed.ftype dH ftype of hydrologic unit x.metric x-metric, i.e. streamflow or drainage area y.metric y-metric, most commonly species richness y.sampres Sample resolution of y.metric (e.g. ’species’) datasite VAHydro database URL EDAS.localpath Local file path for storing downloaded EDAS data. Defaults to a temp directory. Value A dataframe of sites containing species richness data (NT Total values) and mean annual flow (MAF) data. Examples # We don't run this example by R CMD check, because it takes >10s # Retrieve dataset of interest watershed.df <- elfdata_vahydro( 'nhd_huc8_02080201', 'watershed', 'nhd_huc8', 'nhdp_drainage_sqmi', 'aqbio_nt_total', 'species' ) elfdata_vahydro(watershed.df) elfgen Generate Ecological Limit Function (ELF) Description Generate ELF models by supplying a dataframe of richness and stream size data (streamflow or drainage area), a quantile for evaluating the ecological limit, and a breakpoint threshold. Usage elfgen( watershed.df, quantile, breakpt, yaxis_thresh, xlabel = FALSE, ylabel = FALSE ) Arguments watershed.df A dataframe of sites with ecological and hydrologic data quantile A specified value for the quantile of interest - 0.95 equals the 95th percentile breakpt A breakpoint - either user-supplied fixed value or derived using elfgen break- point functions bkpt_pwit() or bkpt_ymax yaxis_thresh Value used for specifying y-axis max limit xlabel Used to overwrite default x-axis label ylabel Used to overwrite default y-axis label Value Object containing plot image and dataframe of ELF statistics Examples # We don't run this example by R CMD check, because it takes >10s watershed.df <- elfdata(watershed.code = '0208020104', ichthy.localpath = tempdir()) breakpt <- 500 elfgen( "watershed.df" = watershed.df, "quantile" = 0.80, "breakpt" = breakpt, "xlabel" = "Mean Annual Flow (ft3/s)", "ylabel" = "Fish Species Richness" ) richness_change Calculate change in richness resulting from a percent reduction in flow Description Calculates absolute or percent richness change from streamflow reduction Usage richness_change(stats, pctchg, xval = FALSE) Arguments stats A dataframe of ELF statistics pctchg Decrease in flow as a percent (e.g. 10 equals 10 percent reduction in flow). xval x-axis value for assessing percent change in richness. When supplied, the func- tion will calculate percent change in richness at a specific stream size (e.g. 50 equals a stream size with mean annual flow of 50 cfs). Value Richness change value is returned Examples # We don't run this example by R CMD check, because it takes >10s watershed.df <- elfdata(watershed.code = '0208020104', ichthy.localpath = tempdir()) breakpt <- 500 elf <- elfgen( "watershed.df" = watershed.df, "quantile" = 0.95, "breakpt" = breakpt, "xlabel" = "Mean Annual Flow (ft3/s)", "ylabel" = "Fish Species Richness" ) # Calculate absolute richness change richness_change(elf$stats, "pctchg" = 10) # Calculate percent richness change at a specific stream size richness_change(elf$stats, "pctchg" = 10, "xval" = 50)
cocoaPods_Kuery.jsonl
personal_doc
Unknown
## Issues list EXC_BAD_ACCESS appending parameter pack to array when generic class has more than 1 type parameter bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labels' #69317 openedb'Oct 21, 2023 by twof' by twof Can Swift invoke C++ library directly? featureb'A feature request or implementationtriage needed' triage needed b'This issue needs more specific labels' #69316 openedb'Oct 21, 2023 by MarcSteven' by MarcSteven Windows missing pdata for $ss22_ContiguousArrayBufferV19firstElementAddressSpyxGvgyp_Tg5 #69315 openedb'Oct 21, 2023 by jaykrell' by jaykrell Methods on parameter packed generic types specialized with zero types cannot be used without crashing the compiler bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labels' #69313 openedb'Oct 21, 2023 by twof' by twof Swift / C build error related to missing definition ofb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.c interop' c interop b'Feature: Interoperability with Cclang importer' clang importer b'Area &#8594; compiler: The clang importer' `fds_bits` . bug #69311 openedb'Oct 20, 2023 by fibrechannelscsi' by fibrechannelscsi Compiler crash when accessing keyPath on protocol with associated type bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labels' #69303 openedb'Oct 20, 2023 by Finnvoor' by Finnvoor Testing macros on Windows results in linking errors bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labels' #69302 openedb'Oct 20, 2023 by MarSe32m' by MarSe32m Type checker crash when pattern matching against duplicated enum case bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labels' #69295 openedb'Oct 20, 2023 by kaascevich' by kaascevich Closure as repetition pattern in pack expansion not allowed bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.closures' closures b'Feature: closurescompiler' compiler b'The Swift compiler in itselfexpressions' expressions b'Feature: expressionsgenerics' generics b'Feature: generic declarations and typespack expansions' pack expansions b'Feature &#8594; expressions: Pack expansion expressionsswift 5.11 type checker' swift 5.11 type checker b'Area &#8594; compiler: Semantic analysisunexpected error' unexpected error b'Bug: Unexpected errorvariadic generics' variadic generics b'Feature &#8594; generics: Variadic generics' #69282 openedb'Oct 19, 2023 by AnthonyLatsis' by AnthonyLatsis [Source compatibility suite] swift-testing failing to build on ubuntu bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.source compatibility suite triage needed' source compatibility suite triage needed b'This issue needs more specific labels' #69279 openedb'Oct 19, 2023 by justice-adams-apple' by justice-adams-apple [Source compatibility suite] swift-testing failing to build on MacOs with 5.10 & 5.9 bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.source compatibility suite triage needed' source compatibility suite triage needed b'This issue needs more specific labels' #69278 openedb'Oct 19, 2023 by justice-adams-apple' by justice-adams-apple Compiler and runtime crashes when combining result builders with memberwise initializer bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.crash' crash b'Bug: A crash, i.e., an abnormal termination of softwareIRGen' IRGen b'LLVM IR generationswift 5.9' swift 5.9 #69272 openedb'Oct 19, 2023 by lassejansen' by lassejansen Explicit calling convention specifier on imported C functions are ignored bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.c interop' c interop b'Feature: Interoperability with C' #69264 openedb'Oct 19, 2023 by kateinoigakukun' by kateinoigakukun Be able to cancel a request when using async await functions of URLSession featureb'A feature request or implementationtriage needed' triage needed b'This issue needs more specific labels' #69261 openedb'Oct 19, 2023 by KaMagno' by KaMagno String encoding/decoding is a mess bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.standard library' standard library b'Area: Standard library umbrellaString' String b'Area &#8594; standard library: The `String` typetriage needed' triage needed b'This issue needs more specific labelsUnicode' Unicode b'Area &#8594; standard library: Unicode processing APIs' #69253 openedb'Oct 18, 2023 by dabrahams' by dabrahams Usingb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labels' `borrowing` On String Causes Compiler Error bug #69252 openedb'Oct 18, 2023 by thecoolwinter' by thecoolwinter actor isolation breakable by passing actor member in lazy initializer bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labels' #69251 openedb'Oct 18, 2023 by johnkassebaum' by johnkassebaum Sema crash when passingb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.compiler' compiler b'The Swift compiler in itselfcrash' crash b'Bug: A crash, i.e., an abnormal termination of softwaregenerics' generics b'Feature: generic declarations and typesswift 5.11 tuple types' swift 5.11 tuple types b'Feature &#8594; types: Tuple typestype checker' type checker b'Area &#8594; compiler: Semantic analysistypes' types b'Feature: typesvariadic generics' variadic generics b'Feature &#8594; generics: Variadic generics' `repeat each t` arg to `(repeat each T)` param bug #69245 openedb'Oct 18, 2023 by AnthonyLatsis' by AnthonyLatsis Incorrect location of 'async' for protocol in actor's fix suggestion actorb'Feature &#8594; concurrency: `actor` declarationsbug' bug b'A deviation from expected or documented behavior. Also: expected but undesirable behavior.compiler' compiler b'The Swift compiler in itselfconcurrency' concurrency b'Feature: umbrella label for concurrency language featuresconformances' conformances b'Feature &#8594; protocol: protocol conformancesdiagnostics QoI' diagnostics QoI b'Bug: Diagnostics Quality of Implementationfix-its' fix-its b'Feature: diagnostic fix-itsgood first issue' good first issue b'Good for newcomersswift 5.11 type checker' swift 5.11 type checker b'Area &#8594; compiler: Semantic analysis' #69244 openedb'Oct 18, 2023 by dancamarotto' by dancamarotto [Autodiff] EXC_BAD_ACCESS when running ab'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labels' `@differentiable` function in the context of an XCTest. AutoDiff bug #69234 openedb'Oct 17, 2023 by hyp' by hyp Swift-to-C++: generateb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.c++ interop' c++ interop b'Feature: Interoperability with C++compiler' compiler b'The Swift compiler in itselfswift to c++' swift to c++ b'Feature &#8594; c++ interop: swift to c++swift 5.11 unexpected error' swift 5.11 unexpected error b'Bug: Unexpected error' `include` directives that reference used C++ declarations in the generated header bug #69233 openedb'Oct 17, 2023 by hyp' by hyp Compiler crash value pack of pairs assertion failureb'Bug &#8594; crash: An assertion failurebug' bug b'A deviation from expected or documented behavior. Also: expected but undesirable behavior.compiler' compiler b'The Swift compiler in itselfcrash' crash b'Bug: A crash, i.e., an abnormal termination of softwaregenerics' generics b'Feature: generic declarations and typesSILGen' SILGen b'Area &#8594; compiler: The SIL generation stageswift 5.11 tuple types' swift 5.11 tuple types b'Feature &#8594; types: Tuple typestypes' types b'Feature: typesvariadic generics' variadic generics b'Feature &#8594; generics: Variadic generics' #69232 openedb'Oct 17, 2023 by DmT021' by DmT021 Mutating a mutable value pack is error bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labels' #69231 openedb'Oct 17, 2023 by DmT021' by DmT021 Member macro unable to add additional enum case when conforming to a raw value bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labels' #69216 openedb'Oct 16, 2023 by LePips' by LePips Previous Next ProTip! Adding no:label will show everything without a label. # Can Swift invoke C++ library directly? #69316 I know Swift can invoke C directly, but when invoked C++ library, it always need bridge head file using Objective-C, I know someone is doing this job, but two years was passed, I reviewed the blog about the release , cannot find the feature . Solution Alternatives considered # Windows missing pdata for $ss22_ContiguousArrayBufferV19firstElementAddressSpyxGvgyp_Tg5 #69315 Stepping through hello world on Windows with cdb I see missing pdata. I build codeview and have a pdb, but that isn't relevant. pdata is a runtime non-optional feature for stackwalk, independent of symbols. C:\s\sw1>more sw1.swift print("hello") 0:000> .fnent . No function entry for 00007ffd`1cf987c6 0:000> k Child-SP RetAddr Call Site 00000058`c618f830 00000000`00000000 swiftSwiftOnoneSupport!$ss22_ContiguousArrayBufferV19firstElementAddressSpyxGvgyp_Tg5+0x16 The problem is not universal by far. Many other functions I stepped through do have pdata and xdata. Open twof opened this issueb'Oct 21, 2023&#183; 0 comments' · 0 comments Open Contributor ### twof commented b'Oct 21, 2023' twof added bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labelslabels' labels b'Oct 21, 2023' twof changed the title~~Methods on parameter packed generic types with specialized with zero types cannot be used without crashing the compiler~~ b'Oct 21, 2023' # Swift / C build error related to missing definition of fds_bits . #69311 # Swift / C build error related to missing definition of `fds_bits` . #69311 Labels bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.c interop' c interop b'Feature: Interoperability with Cclang importer' clang importer b'Area &#8594; compiler: The clang importer' Open Finnvoor opened this issueb'Oct 20, 2023&#183; 0 comments' · 0 comments Open ### Finnvoor commented b'Oct 20, 2023' # Testing macros on Windows results in linking errors #69302 Description Compiling and using macros works as expected but testing macros on Windows results in a duplicate symbol linking error. Steps to reproduce Create a macro using the SPM template: swift package init --type macro and then test the package with swift test. Expected behavior Tests should run and pass. Actual behavior Actual output: C:\Dev\SwiftProjects\test-macros>swift test Building for debugging... lld-link: error: duplicate symbol: main >>> defined at C:\Dev\SwiftProjects\test-macros\.build\x86_64-unknown-windows-msvc\debug\test_macrosMacros.build\test_macrosMacro.swift.o >>> defined at C:\Dev\SwiftProjects\test-macros\.build\x86_64-unknown-windows-msvc\debug\test_macrosPackageTests.build\runner.swift.o clang: error: linker command failed with exit code 1 (use -v to see invocation) [31/32] Linking C:\Dev\SwiftProjects\test-macros\.build\x86_64-unknown-windows-msvc\debug\test-macrosPackageTests.xctest error: fatalError Swift compiler version info Swift version 5.9.1 (swift-5.9.1-RELEASE) Target: x86_64-unknown-windows-msvc Deployment target: Windows 11 Labels bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.closures' closures b'Feature: closurescompiler' compiler b'The Swift compiler in itselfexpressions' expressions b'Feature: expressionsgenerics' generics b'Feature: generic declarations and typespack expansions' pack expansions b'Feature &#8594; expressions: Pack expansion expressionsswift 5.11 type checker' swift 5.11 type checker b'Area &#8594; compiler: Semantic analysisunexpected error' unexpected error b'Bug: Unexpected errorvariadic generics' variadic generics b'Feature &#8594; generics: Variadic generics' b'Oct 19, 2023&#8226;' • Author b'Oct 19, 2023' MaxDesiatov added crashb'Bug: A crash, i.e., an abnormal termination of softwareswift 5.9 IRGen' swift 5.9 IRGen b'LLVM IR generationand removed triage needed' and removed triage needed b'This issue needs more specific labelslabels' labels b'Oct 19, 2023' # Explicit calling convention specifier on imported C functions are ignored #69264 Description swift-atomics has a C header imported by Swift, and it contains a C function declaration with SwiftCC. https://github.com/apple/swift-atomics/blob/cd142fd2f64be2100422d658e7411e39489da985/Sources/_AtomicsShims/include/_AtomicsShims.h#L25 However, the caller side of the function does not use SwiftCC, and it causes calling convention violation. Here is a lit test case to reproduce the issue // RUN: %empty-directory(%t) // RUN: split-file %s %t // RUN: %target-swift-frontend -I%t %t/caller.swift -emit-ir | %FileCheck %s //--- c_funcs.h __attribute__((swiftcall)) extern void with_swiftcc(void); //--- module.modulemap module c_funcs { header "c_funcs.h" } //--- caller.swift import c_funcs func test() { // CHECK: call swiftcc void @with_swiftcc() with_swiftcc() } // CHECK: declare swiftcc void @with_swiftcc() test() No branches or pull requests # Be able to cancel a request when using async await functions of URLSession #69261 Motivation When changing to use async await functions from URLSession I noticed that we lost access to URLSessionDataTask which is necessary when we need to cancel a request. And we need this kind of function especially when working with Feed screens and things alike. Solution We already can create an URLSessionDataTask but we don't have an async await function to perform it so my solution would be to add a function that performs URLSessionDataTask and the result would be the same (Data, Response) tulple Alternatives considered Another solution would be to add this perform async await function at the URLSessionDataTask as the resume function that it already has but in this case, would be an async await function Labels bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.standard library' standard library b'Area: Standard library umbrellaString' String b'Area &#8594; standard library: The `String` typetriage needed' triage needed b'This issue needs more specific labelsUnicode' Unicode b'Area &#8594; standard library: Unicode processing APIs' # Using borrowing On String Causes Compiler Error #69252 # Using `borrowing` On String Causes Compiler Error #69252 Labels bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labels' # Sema crash when passing repeat each t arg to (repeat each T) param #69245 `repeat each t` arg to `(repeat each T)` param #69245 Open AnthonyLatsis opened this issueb'Oct 18, 2023&#183; 0 comments' · 0 comments Open `repeat each t` arg to `(repeat each T)` param #69245 AnthonyLatsis opened this issueb'Oct 18, 2023&#183; 0 comments' · 0 comments Labels bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.compiler' compiler b'The Swift compiler in itselfcrash' crash b'Bug: A crash, i.e., an abnormal termination of softwaregenerics' generics b'Feature: generic declarations and typesswift 5.11 tuple types' swift 5.11 tuple types b'Feature &#8594; types: Tuple typestype checker' type checker b'Area &#8594; compiler: Semantic analysistypes' types b'Feature: typesvariadic generics' variadic generics b'Feature &#8594; generics: Variadic generics' AnthonyLatsis added bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.compiler' compiler b'The Swift compiler in itselftype checker' type checker b'Area &#8594; compiler: Semantic analysisgenerics' generics b'Feature: generic declarations and typescrash' crash b'Bug: A crash, i.e., an abnormal termination of softwarevariadic generics' variadic generics b'Feature &#8594; generics: Variadic genericstypes' types b'Feature: typesswift 5.11 tuple types' swift 5.11 tuple types b'Feature &#8594; types: Tuple typeslabels' labels b'Oct 18, 2023' Labels actorb'Feature &#8594; concurrency: `actor` declarationsbug' bug b'A deviation from expected or documented behavior. Also: expected but undesirable behavior.compiler' compiler b'The Swift compiler in itselfconcurrency' concurrency b'Feature: umbrella label for concurrency language featuresconformances' conformances b'Feature &#8594; protocol: protocol conformancesdiagnostics QoI' diagnostics QoI b'Bug: Diagnostics Quality of Implementationfix-its' fix-its b'Feature: diagnostic fix-itsgood first issue' good first issue b'Good for newcomersswift 5.11 type checker' swift 5.11 type checker b'Area &#8594; compiler: Semantic analysis' d7e754e # [Autodiff] EXC_BAD_ACCESS when running a @differentiable function in the context of an XCTest. #69238 #69238 ### fibrechannelscsi commented b'Oct 17, 2023' # Swift-to-C++: getTypeMetadata inline helpers that refer to C++ type metadata are annotated as used for debug compilations, causing linker errors #69234 # Swift-to-C++: # Swift-to-C++: generate include directives that reference used C++ declarations in the generated header #69233 # Swift-to-C++: generate `include` directives that reference used C++ declarations in the generated header #69233 Labels bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.c++ interop' c++ interop b'Feature: Interoperability with C++compiler' compiler b'The Swift compiler in itselfswift to c++' swift to c++ b'Feature &#8594; c++ interop: swift to c++swift 5.11 unexpected error' swift 5.11 unexpected error b'Bug: Unexpected error' Open DmT021 opened this issueb'Oct 17, 2023&#183; 1 comment' · 1 comment Labels assertion failureb'Bug &#8594; crash: An assertion failurebug' bug b'A deviation from expected or documented behavior. Also: expected but undesirable behavior.compiler' compiler b'The Swift compiler in itselfcrash' crash b'Bug: A crash, i.e., an abnormal termination of softwaregenerics' generics b'Feature: generic declarations and typesSILGen' SILGen b'Area &#8594; compiler: The SIL generation stageswift 5.11 tuple types' swift 5.11 tuple types b'Feature &#8594; types: Tuple typestypes' types b'Feature: typesvariadic generics' variadic generics b'Feature &#8594; generics: Variadic generics' ### DmT021 commented b'Oct 17, 2023&#8226;' • DmT021 added bugb'A deviation from expected or documented behavior. Also: expected but undesirable behavior.triage needed' triage needed b'This issue needs more specific labelslabels' labels b'Oct 17, 2023' AnthonyLatsis added compilerb'The Swift compiler in itselfSILGen' SILGen b'Area &#8594; compiler: The SIL generation stagegenerics' generics b'Feature: generic declarations and typescrash' crash b'Bug: A crash, i.e., an abnormal termination of softwarevariadic generics' variadic generics b'Feature &#8594; generics: Variadic genericsassertion failure' assertion failure b'Bug &#8594; crash: An assertion failureswift 5.11 tuples' swift 5.11 tuples b'Feature: tuplestuple types' tuple types b'Feature &#8594; types: Tuple typestypes' types b'Feature: typesand removed triage needed' and removed triage needed b'This issue needs more specific labelstuples' tuples b'Feature: tupleslabels' labels b'Oct 18, 2023' # Mutating a mutable value pack is error #69231 Description Let x be a mutable value pack. var x: (repeat each T), where T is a whatever type pack. (each x) doesn't preserve mutability of x. Attempt to invoke a mutating func on it or pass in as an inout argument is an error of violation immutability. structValueIsNil: Error{} extensionOptional { funcunwrap() throws-> Wrapped { guardletselfelse { throwValueIsNil() } returnself } } structZipSequence<eachSeq: Sequence>: Sequence{ structIterator: IteratorProtocol{ typealiasElement= (repeat (each Seq).Element) var iter: (repeat (each Seq).Iterator) var isExhausted =falsemutatingfuncnext() ->Element? { guard!isExhausted else { returnnil } do { return ( repeattry (each iter) .next() // Cannot use mutating member on immutable value of type 'τ_1_0.Iterator' .unwrap() ) } catch { isExhausted =truereturnnil } } } typealiasElement= (repeat (each Seq).Element) var seq: (repeat each Seq) init(seq: (repeat each Seq)) { self.seq= (repeat each seq) } funcmakeIterator() ->Iterator { returnIterator(iter: (repeat (each seq).makeIterator())) } } funczip<eachSeq>(_seq: repeat each Seq) -> ZipSequence<repeat each Seq> { ZipSequence(seq: (repeat each seq)) } Expected behavior Elements of a value pack are as mutable as the pack. Swift compiler version info swift-driver version: 1.87.1 Apple Swift version 5.9 (swiftlang-5.9.0.128.108 clang-1500.0.40.1) Xcode version info 15.0 Deployment target: iOS 17 Open LePips opened this issueb'Oct 16, 2023&#183; 0 comments' · 0 comments Open ### LePips commented b'Oct 16, 2023'
facemap
readthedoc
Unknown
Facemap Release 1.0.2 <NAME> & <NAME> Sep 22, 2023 BASICS: 1.1 Common installation issue... 3 1.2 Dependencie... 3 1.3 MATLAB package installatio... 4 2.1 Starting the GU... 5 2.2 Command line usag... 5 2.3 Using the GU... 6 2.3.1 Pose tracking (GUI... 6 2.3.2 SVD processing and ROI... 8 2.3.3 Neural activity predictio... 11 3.1 Processing multiple movie... 13 3.2 Batch processin... 14 3.3 Data acquisition inf... 14 3.3.1 IR illuminatio... 14 3.3.2 Camera... 14 4.1 ROI and SVD processin... 15 4.1.1 Loading output... 16 4.2 Keypoints processin... 16 4.3 Neural activity prediction outpu... 17 6.1 Pose estimatio... 21 6.2 SVD processin... 22 6.3 Transform... 23 i ii Facemap, Release 1.0.2 Facemap is a framework for predicting neural activity from mouse orofacial movements. It includes a pose estimation model for tracking distinct keypoints on the mouse face, a neural network model for predicting neural activity using the pose estimates, and also can be used compute the singular value decomposition (SVD) of behavioral videos. For more details, please see our paper and twitter thread. Facemap, Release 1.0.2 2 BASICS: CHAPTER ONE INSTALLATION Please see the Github readme for the latest installation instructions 1.1 Common installation issues • If you have pip issues, there might be some interaction between pre-installed dependencies and the required Facemap dependencies. Please upgrade pip as follows: python -m pip install --upgrade pip • While running python -m facemap, if you receive the error: No module named PyQt5.sip, then try unin- stalling and reinstalling pyqt5 as follows: pip uninstall pyqt5 pyqt5-tools pip install pyqt5 pyqt5-tools pyqt5.sip • If you are on Yosemite Mac OS, PyQt doesn’t work, and you won’t be able to install Facemap. More recent versions of Mac OS are supported. The software has been heavily tested on Ubuntu 18.04, and less well tested on Windows 10 and Mac OS. Please post an issue if you have installation problems. 1.2 Dependencies Facemap (python package) relies on these awesome packages: • pyqtgraph • pyqt6 • numpy (>=1.13.0) • scipy • opencv • numba • natsort • pytorch • matplotlib • tqdm • UMAP Facemap, Release 1.0.2 1.3 MATLAB package installation The matlab version supports SVD processing only and does not include the orofacial tracker. The package can be downloaded/cloned from github (no install required). It works in Matlab 2014b and above. The Image Processing Toolbox is necessary to use the GUI. For GPU functionality, the Parallel Processing Toolbox is required. If you don’t have the Parallel Processing Toolbox, uncheck the box next to “use GPU” in the GUI before processing. Note this version is no longer supported. CHAPTER TWO GUI 2.1 Starting the GUI The quickest way to start is to open the GUI from a command line terminal: python -m facemap 2.2 Command line usage Run python -m facemap --help to see usage of the following optional parameters: -h, --help show this help message and exit --ops options --movie Absolute path to video(s) --keypoints Absolute path to keypoints file (*.h5) --proc_npy Absolute path to proc file (*_proc.npy) --neural_activity Absolute path to neural activity file (*.npy) --neural_prediction Absolute path to neural prediction file (*.npy) --tneural Absolute path to neural timestamps file (*.npy) --tbehavior Absolute path to behavior timestamps file (*.npy) --savedir save directory --autoload_keypoints Automatically load keypoints in the same directory as the movie --autoload_proc Automatically load *_proc.npy in the same directory as the movie Facemap, Release 1.0.2 2.3 Using the GUI The GUI can be used for the processing keypoints and SVD of mouse behavioral videos. The GUI can also be used for predicting neural activity using the behavioral data. For more details on each feature, see the following tutorials: 2.3.1 Pose tracking (GUI) The latest python version is integrated with Facemap network for tracking 14 distinct keypoints on mouse face and an additional point for tracking paw. The keypoints can be tracked from different camera views (see examples). Generate keypoints Follow the steps below to generate keypoints for your videos: 1. Load video • Select File from the menu bar • For processing single video, select Load video. Alternatively, for processing multiple videos, select Load multiple videos to select the folder containing the videos. (Note: Pose estimation for multipl videos is only supported for videos recorded simultaneously i.e. have the same time duration and frame rate). (Optional) Set output folder • Use the file menu to Set output folder. • The processed keypoints (*.h5) and metadata (*.pkl) will be saved in the selected output folder or folder containing the video (by default). 2. Process video(s) • Check Keypoints for pose tracking. • Click process. • Note: The first time facemap runs for processing keypoints it downloads the latest available trained model weights from our website. 3. Set ROI/bounding box for face region • A dialog box for selecting a bounding box for the face will appear. Drag the red rectangle to select region of interest on the frame where the keypoints will be tracked. Please ensure that the bouding box is focused on the face where all the keypoints will be visible. See example frames here. If a ‘Face (pose)’ ROI has already been added then this step will be skipped. • Click Done to process video. Alternatively, click Skip to use the entire frame region. Monitor progress bar at the bottom of the window for updates. 4. View keypoints • Keypoints will be automatically loaded after processing. • Processed keypoints file will be saved as [videoname]_FacemapPose.h5 in the selected output folder. Facemap, Release 1.0.2 Visualize keypoints To load keypoints (*.h5) for a video generated using Facemap or other software in the same format (such as DeepLabCut and SLEAP), follow the steps below: 1. Load video • Select File from the menu bar • Select Load video 2. Load keypoints • Select Pose from the menu bar • Select Load keypoints • Select the keypoints (*.h5) file 3. View keypoints • Use the “Keypoints” checkbox to toggle the visibility of keypoints. • Change value of “Threshold (%)” under pose settings to filter keypoints with lower confidence estimates. Higher threshold will show keypoints with higher confidence estimates. Finetune model to refine keypoints for a video To improve keypoints predictions for a video, follow the steps below: 1. Load video • Select File from the menu bar • Select Load video 2. Set finetuned model’s output folder • Select Pose from the menu bar • Select Finetune model • Set output folder path for finetuned model 3. Select training data and set training parameters • Set Initial model to use for training. By default, Facemap’s base model trained on our dataset will be used for fine-tuning. Alternatively, you can select a model previously finetuned on your own dataset. • Set Output model name for the finetuned model. • Choose Yes/No to refine keypoints prediction for the video loaded and set # Frames to use for training. You can also choose proportion of random vs. outlier frames to use for training. The outlier frames are se- lected using the Difficulty threshold (percentile), which determines the percentile of confidence scores to use as the threshold for selecting frames with the highest error. • Choose Yes/No to add previously refined keypoints to the training set. • Set training parameters or use default values. • Click Next 4. Refine keypoints • If a ROI/bounding box was not added, then a dialog box for selecting a bounding box for the face will appear. Drag the red rectangle to select region of interest on the frame where the keypoints will be tracked. Facemap, Release 1.0.2 • Click Done to process video. Alternatively, click Skip to use the entire frame region. Monitor progress bar at the bottom of the window for updates. • Drag keypoints to refine predictions. Use Shift+D to delete a keypoint. Right click to add a deleted keypoint. Use Previous and Next buttons to change frame. Click Help for more details. • Click Train model to start training. A progress bar will appear for training updates. 5. Evaluate training • View predicted keypoints for test frames from the video loaded. For further refinement, Click Continue training that will repeat steps 3-5. • Click Save model to save the finetuned model. The finetuned model will be saved as *.pt in the selected output folder. 6. Generate keypoints using the finetuned model • Use the Pose model dropdown menu to set the finetuned model to use for generating keypoints predictions. • (Optional) Change “Batch size” under pose settings. • Click Process to generate keypoints predictions. See Generate keypoints for more details. 2.3.2 SVD processing and ROIs Choose a type of ROI to add and then click “add ROI” to add it to the view. The pixels in the ROI will show up in the right window (with different processing depending on the ROI type - see below). You can move it and resize the ROI anytime. You can delete the ROI with “right-click” and selecting “remove”. You can change the saturation of the ROI with the upper right saturation bar. You can also just click on the ROI at any time to see what it looks like in the right view. By default, the “multivideo” box is unchecked. If you check it, then the motion SVD or movie SVD is computed across ALL videos - all videos are concatenated at each timepoint, and the SVD of this matrix of ALL_PIXELS x timepoints is computed. If you have just one video acquired at a time, then it is the SVD of the full video. To compute motion SVD and/or movie SVD, please check one or both boxes in the GUI before hitting process. If you want to open the GUI with a movie file specified and/or save path specified, the following command will allow this: ~~~ python -m facemap –movie ‘/home/carsen/movie.avi’ –savedir ‘/media/carsen/SSD/’ ~~~ Note this will only work if you only have one file that you need to load (can’t have multiple in series / multiple views). ROI types Motion SVD The motion/movie SVDs (small ROIs / multivideo) are computed on the movie downsampled in space by the spatial downsampling input box in the GUI (default 4 pixels). Note the saturation set in this window is NOT used for any processing. The motion M is defined as the abs(current_frame - previous_frame), and the average motion energy across frames is computed using a subset of frames (avgmot) (at least 1000 frames). Then the singular vectors of the motion energy are computed on chunks of data, also from a subset of frames (15 chunks of 1000 frames each): uMotMask. These are the motion masks that are then projected onto the video at all timepoints (done in chunks of size nt=500): Example motion masks uMotMask and traces motSVD: Facemap, Release 1.0.2 2.3. Using the GUI 9 Facemap, Release 1.0.2 The SVDs can be computed on the motion or on the raw movie, please check the corresponding box for “motion SVD” and/or “movie SVD” before hitting process to compute one or both of these. We found that these extracted singular vectors explained up to half of the total explainable variance in neural activity in visual cortex and in other forebrain areas. See our paper for more details. We also compute the average of M across all pixels in each motion ROI and that is returned as the motion. The first motion field is non-empty if “multivideo SVD” is on, and in that case it is the average motion energy across all pixels in all views. Pupil computation The minimum pixel value is subtracted from the ROI. Use the saturation bar to reduce the background of the eye. The algorithm zeros out any pixels less than the saturation level (I recommend a very low value - so most pixels are white in the GUI). Next it finds the pixel with the largest magnitude. It draws a box around that area (1/2 the size of the ROI) and then finds the center-of-mass of that region. It then centers the box on that area. It fits a multivariate gaussian to the pixels in the box using maximum likelihood (see pupil.py). After a Gaussian is fit, it zeros out pixels whose squared distance from the center (normalized by the standard deviation of the Gaussian fit) is greater than 2 * sigma^2 where sigma is set by the user in the GUI (default sigma = 2.5). It now performs the fit again with these points erased, and repeats this process 4 more times. The pupil is then defined as an ellipse sigma standard deviations away from the center-of-mass of the gaussian. This is plotted with ‘+’ around the ellipse and with one ‘+’ at the center. If there are reflections on the mouse’s eye, then you can draw ellipses to account for this “corneal reflection” (plotted in black). You can add as many of these per pupil ROI as needed. The algorithm fills in these areas of the image with the predicted values, which allows for smooth transitions between big and small pupils. This raw pupil area trace is post-processed. The trace is median filtered with a window of 30 timeframes. At each timepoint, the difference between the raw trace and the median filtered trace is computed. If the difference at a given point exceeds half the standard deviation of the raw trace, then the raw value is replaced by the median filtered value. Facemap, Release 1.0.2 Blink computation You may want to ignore frames in which the animal is blinking if you are looking at pupil size. The blink area is defined the number of pixels above the saturation level that you set (all non-white pixels). Running computation The phase-correlation between consecutive frames (in running ROI) are computed in the fourier domain (see run- ning.py). The XY position of maximal correlation gives the amount of shift between the two consecutive frames. Depending on how fast the movement is frame-to-frame you may want at least a 50x50 pixel ROI to compute this. 2.3.3 Neural activity prediction This tutorial shows how to use the deep neural network encoding model to predict neural activity based on mouse orofacial behavior. To process neural activity prediction using pose estimates extracted using the keypoint tracker: 1. Load or process keypoints (see pose tracking tutorial). 2. Select Neural activity from file menu. 3. Click on Launch neural activity window. 4. Select Load neural activity (2D-array stored in *.npy) and (optionally) timestamps for neural and behav- ioral data (1D-arrays stored in*.npy) then click Done. 5. Once the neural data is loaded, click on Run neural predictions. 6. Select Keypoints as input data and select one of the options for output of the model’s prediction, which can be Neural PCs or neural activity. CLick on Help button for more information. 7. The predicted neural activity (*.npy) file will be saved in the selected output folder. To predict neural activity using SVDs from Facemap: 1. Load or process SVDs for the video. (see SVD tutorial). 2. Follow steps 2-5 above. Note: a linear model is used for prediction using SVDs. Predicted neural activity will be plotted in the neural activity window. Toggle Highlight test data to highlight time segments not used for training i.e. test data. Further information about neural prediction, including variance explained can be found in the saved neural prediction file (*.npy). Facemap, Release 1.0.2 12 Chapter 2. GUI CHAPTER THREE INPUTS Facemap supports grayscale and RGB movies. The software can process multi-camera videos for pose tracking and SVD analysis. Movie file extensions supported include: ‘.mj2’,’.mp4’,’.mkv’,’.avi’,’.mpeg’,’.mpg’,’.asf’ Here are some example movies. 3.1 Processing multiple movies Please note: • simultaneous videos: user can load videos of different dimensions but must have the number of frames for each video • sequential videos: user can load videos with varying number of frames but the dimensions of the frames/videos must match If you load multiple videos, the GUI will ask “are you processing multiple videos taken simultaneously?”. If you say yes, then the script will look if across movies the FIRST FOUR letters of the filename vary. If the first four letters of two movies are the same, then the GUI assumed that they were acquired sequentially not simultaneously. Example file list: + cam1_G7c1_1.avi + cam1_G7c1_2.avi + cam2_G7c1_1.avi + cam2_G7c1_2.avi + cam3_G7c1_1.avi + cam3_G7c1_2.avi “are you processing multiple videos taken simultaneously?” ANSWER: Yes Then the GUIs assume {cam1_G7c1_1.avi, cam2_G7c1_1.avi, cam3_G7c1_1.avi} were acquired simultaneously and {cam1_G7c1_2.avi, cam2_G7c1_2.avi, cam3_G7c1_2.avi} were acquired simultaneously. They will be processed in alphabetical order (1 before 2) and the results from the videos will be concatenated in time. If one of these files was missing, then the GUI will error and you will have to choose file folders again. Also you will get errors if the files acquired at the same time aren’t the same frame length (e.g. {cam1_G7c1_1.avi, cam2_G7c1_1.avi, cam3_G7c1_1.avi} should all have the same number of frames). Note: if you have many simultaneous videos / overall pixels (e.g. 2000 x 2000) you will need around 32GB of RAM to compute the full SVD motion masks. You will be able to see all the videos that were simultaneously collected at once. However, you can only draw ROIs that are within ONE video. Only the “multivideo SVD” is computed over all videos. Facemap, Release 1.0.2 3.2 Batch processing Load a video or a set of videos and draw your ROIs and choose your processing settings. Then click “save ROIs”. This will save a *_proc.npy file in the output folder. Default output folder is the same folder as the video. Use file menu to change path of the output folder. The name of saved proc file will be listed below “process batch” (this button will also activate). You can then repeat this process: load the video(s), draw ROIs, choose settings, and click “save ROIs”. Then to process all the listed *_proc.npy files click “process batch”. 3.3 Data acquisition info 3.3.1 IR illumination For recording in darkness we use IR illumination at 850nm, which works well with 2p imaging at 970nm and even 920nm. Depending on your needs, you might want to choose a different wavelength, which changes all the filters below as well. 950nm works just as well, and probably so does 750nm, which still outside of the visible range for rodents. If you want to focus the illumination on the mouse eye or face, you will need a different, more expensive system. Here is an example, courtesy of <NAME> from the Carandini lab: driver, power supply, LED, lens, and lens tube, and another lens tube. 3.3.2 Cameras We use ptgrey cameras. The software we use for simultaneous acquisition from multiple cameras is BIAS software. A basic lens that works for zoomed out views here. To see the pupil well you might need a better zoom lens 10x here. For 2p imaging, you’ll need a tighter filter around 850nm so you don’t see the laser shining through the mouse’s eye/head, for example this. Depending on your lenses you’ll need to figure out the right adapter(s) for such a filter. For our 10x lens above, you might need all of these: adapter1, adapter2, adapter3, adapter4. CHAPTER FOUR OUTPUTS 4.1 ROI and SVD processing SVD processing saves two outputs: a *.npy file and a *.mat file. The output file contains the following variables: • filenames: A 2D list of video filenames - a list within the 2D list consists of videos recorded simultaneously whereas sequential videos are stored as a separate list • Ly, Lx: list of frame length in y-dim (Ly) and x-dim (Lx) for each video taken simultaneously • sbin: spatial bin size for SVDs • Lybin, Lxbin: list of number of pixels binned by sbin in Y (Ly) and X (Lx) for each video taken simultaneously • sybin, sxbin: coordinates of multivideo (for plotting/reshaping ONLY) • LYbin, LXbin: full-size of all videos embedded in rectangle (binned) • fullSVD: bool flag indicating whether “multivideo SVD” is computed • save_mat: bool flag indicating whether to save proc as *.mat file • avgframe: list of average frames for each video from a subset of frames (binned by sbin) • avgframe_reshape: average frame reshaped to size y-pixels by x-pixels • avgmotion: list of average motion computed for each video from a subset of frames (binned by sbin) • avgmotion_reshape: average motion reshaped to size y-pixels by x-pixels • iframes: an array containing the number of frames in each consecutive video • motion: list of absolute motion energies across time - first is “multivideo” motion energy (empty if not computed) • motSVD: list of motion SVDs - first is “multivideo SVD” (empty if not computed) - each is of size number of frames by number of components (500) • motMask: list of motion masks for each motion SVD - each motMask is pixels x components • motMask_reshape: motion masks reshaped to: y-pixels x x-pixels x components • motSv: array containing singular values for motSVD • movSv: array containing singular values for movSVD • pupil: list of pupil ROI outputs - each is a dict with ‘area’, ‘area_smooth’, and ‘com’ (center-of-mass) • blink: list of blink ROI outputs - each is nframes, the blink area on each frame • running: list of running ROI outputs - each is nframes x 2, for X and Y motion on each frame • rois: ROIs that were drawn and computed: Facemap, Release 1.0.2 – rind: type of ROI in number – rtype: what type of ROI (‘motion SVD’, ‘pupil’, ‘blink’, ‘running’) – ivid: in which video is the ROI – color: color of ROI – yrange: y indices of ROI – xrange: x indices of ROI – saturation: saturation of ROI (0-255) – pupil_sigma: number of stddevs used to compute pupil radius (for pupil ROIs) – yrange_bin: binned indices in y (if motion SVD) – xrange_bin: binned indices in x (if motion SVD) 4.1.1 Loading outputs The *.npy saved is a dict which can be loaded in python as follows: import numpy as np proc = np.load('filename_proc.npy', allow_pickle=True).item() print(proc.keys()) motion = proc['motion'] These *_proc.npy* files can be loaded in the GUI (and is automatically loaded after processing). The checkboxes on the lower left panel of the GUI can be used to toggle display of different traces/variables. 4.2 Keypoints processing Keypoints processing saves two outputs: a *.h5 and a *metadata.pkl file. • *.h5 file contains: Keypoints stored as a 3D array of shape (3, number of bodyparts, number of frames). The first dimension of size 3 is in the order: (x, y, likelihood). For more details on using/loading the *.h5 file in python see this tutorial. • *metadata.pkl file: contains a dictionary consisting of the following variables: – batch_size: batch size used for inference – image_size: frame size – bbox: bounding box for cropping the video [x1, x2, y1, y2] – total_frames: number of frames – bodyparts: names of bodyparts – inference_speed: processing speed To load the pkl file in python, use the following code: import pickle with open('filename_metadata.pkl', 'rb') as f: metadata = pickle.load(f) (continues on next page) Facemap, Release 1.0.2 (continued from previous page) print(metadata.keys()) print(metadata['bodyparts']) 4.3 Neural activity prediction output The output of neural activity prediction is saved in *.npy file and optionally in *.mat file. The output contains a dictionary with the following keys: • predictions: a 2D array containing the predicted neural activity of shape (number of features x time) • test_indices: a list of indices indicating sections of data used as test data for computing variance explained by the model • variance_explained: variance explained by the model for test data • plot_extent: extent of the plot used for plotting the predicted neural activity in the order [x1, y1, x2, y2] Facemap, Release 1.0.2 18 Chapter 4. Outputs CHAPTER FIVE TUTORIALS See example tutorials for processing keypoints and refining keypoints model. Facemap, Release 1.0.2 20 Chapter 5. Tutorials CHAPTER SIX FACEMAP API GUIDE 6.1 Pose estimation class facemap.pose.pose.Pose(filenames=None, bbox=[], bbox_set=False, resize=False, add_padding=False, gui=None, GUIobject=None, net=None, model_name=None) Pose estimation for single video processing Parameters • filenames (2D-list) – List of filenames to be processed. • bbox (list) – Bounding box for cropping the video [x1, x2, y1, y2]. If not set, the entire frame is used. • bbox_set (bool) – Flag to indicate whether the bounding box has been set. Default is False. • resize (bool) – Flag to indicate whether the video needs to be resized • add_padding (bool) – Flag to indicate whether the video needs to be padded. Default is False. • gui (object) – GUI object. • GUIobject (object) – GUI mainwindow object. • net (object) – PyTorch model object. • model_name (str) – Name of the model to be used for pose estimation. Default is None which uses the pre-trained model. load_model() Load model for keypoints prediction. Uses default model unless set_model is used to update the model name and load the model state. predict_landmarks(video_id, frame_ind=None) Predict keypoints/landmarks for all frames in video and save output as .h5 file. If frame_ind is specified, only predict keypoints/landmarks for those frames. :param video_id: Index of video in filenames list to be used for prediction. :type video_id: int :param frame_ind: List of frame indices for keypoints/landmarks prediction. :type frame_ind: list save_data_to_hdf5(data, video_id, selected_frame_ind=None) save_data_to_hdf5: Save data to an HDF5 file Parameters • data (2D-array) – Data to save (nframes x nbodyparts x 3) • selected_frame_ind (list) – Indices of selected frames Facemap, Release 1.0.2 save_dict_to_hdf5(h5file, path, data_dict) Saves dictionary to an HDF5 file. Adapted from https://github.com/talmolab/sleap/blob/ 391bc0421fe3820ddd6b5d07e31311d60b129fe3/sleap/util.py#L116 Calls itself recursively if items in dictionary are not np.ndarray, np.int64, np.float64, str, or bytes. Objects must be iterable. :param h5file: The HDF5 filename object to save the data to. Assume it is open. Parameters • path – The path to group save the dict under. • data_dict – The dict containing data to save. Raises ValueError – If type for item in dict cannot be saved. Returns None save_model(model_filepath) Save model to file :param model_filepath: Path to save model weights :type model_filepath: str set_model(model_selected=None) Set model to use for pose estimation Parameters model_selected (str, optional) – Path of trained model weights to use. Default value of None sets the model_name to Base model/facemap_model_state which uses pre-trained weights. train(image_data, keypoints_data, num_epochs, batch_size, learning_rate, weight_decay, bbox) Train the model :param image_data: Array of images of shape (nframes, Ly, Lx) :type image_data: ND- array :param keypoints_data: Array of keypoints of shape (nframes, nkeypoints, 2) :type keypoints_data: ND-array :param num_epochs: Number of epochs for training :type num_epochs: int :param batch_size: Batch size for training :type batch_size: int :param learning_rate: Learning rate for training :type learn- ing_rate: float :param weight_decay: Weight decay for training :type weight_decay: float Returns model – Trained/finetuned model Return type torch.nn.Module 6.2 SVD processing Copright © 2023 <NAME> Medical Institute, Authored by <NAME> and <NAME>. facemap.process.process_blink_ROIs(t, nt0, img, ivid, rois, blind, blinks) docstring facemap.process.process_pupil_ROIs(t, nt1, img, ivid, rois, pupind, pups, pupreflector) docstring facemap.process.process_running(t, n, nt1, img, ivid, rois, runind, runs, rend) docstring Facemap, Release 1.0.2 facemap.process.run(filenames, sbin=1, motSVD=True, movSVD=False, GUIobject=None, parent=None, proc=None, savepath=None) Process video files using SVD computation of motion and/or raw movie data. :param filenames: List of video files to process. Each element of the list is a list of filenames for video(s) recorded simultaneously. For example, if two videos were recorded simultane- ously, the list would be: [[‘video1.avi’, ‘video2.avi’]], and if the videos were recorded sequentially, the list would be: [[‘video1.avi’], [‘video2.avi’]]. Parameters • sbin (int) – Spatial binning factor. If sbin > 1, the movie will be spatially binned by a factor of sbin. • motSVD (bool) – If True, compute SVD of motion in the video i.e. the difference between consecutive frames. • movSVD (bool) – If True, compute SVD of raw movie data. • GUIobject (GUI object) – GUI object to update progress bar. If None, no progress bar will be updated. • parent (GUI object) – Parent GUI object to update progress bar. If None, no progress bar will be updated. • proc (dict) – Dictionary containing previously processed data. If provided, parameters from the saved data, such as sbin, rois, sy, sx, etc. will be used. • savepath (str) – Path to save processed data. If None, the processed data will be saved in the same directory as the first video file. Returns savename – Path to saved processed data. Return type str 6.3 Transforms Copright © 2023 <NAME> Medical Institute, Authored by <NAME> and <NAME>. facemap.pose.transforms.adjust_bbox(prev_bbox, img_yx, div=16, extra=1) Takes a bounding box as an input and the original image size. Adjusts bounding box to be square instead of a rect- angle. Uses longest dimension of prev_bbox for final image size that cannot exceed img_yx :param prev_bbox: bounding box positions in order x1, x2, y1, y2 :type prev_bbox: tuple of size (4,) :param img_yx: image size for y and x dimensions :type img_yx: tuple of size (2,) Returns bbox – bounding box positions in order x1, x2, y1, y2 Return type tuple of size (4,) facemap.pose.transforms.adjust_keypoints(xlabels, ylabels, crop_xy, padding, current_size, desired_size) Adjust raw keypoints (x,y coordinates) obtained from model to plot on original image :param xlabels: x coordi- nates of keypoints :type xlabels: ND-array :param ylabels: y coordinates of keypoints :type ylabels: ND-array :param crop_xy: initial coordinates of bounding box (x1,y1) for cropping :type crop_xy: tuple of size (2,) :param padding: padding values for bounding box (x1,x2,y1,y2) :type padding: tuple of size (4,) Facemap, Release 1.0.2 Returns • xlabels (ND-array) – x coordinates of keypoints • ylabels (ND-array) – y coordinates of keypoints facemap.pose.transforms.adjust_keypoints_for_padding(xlabels, ylabels, pads) Adjust keypoints for padding. Adds padding to the top and left of the image only. :param xlabels: x coordinates of keypoints :type xlabels: ND-array :param ylabels: y coordinates of keypoints :type ylabels: ND-array :param pads: padding values for bounding box (y1,y2,x1,x2) :type pads: tuple of size (4,) Returns • xlabels (ND-array) – x coordinates of keypoints after padding • ylabels (ND-array) – y coordinates of keypoints after padding facemap.pose.transforms.augment_data(image, keypoints, scale=False, scale_range=0.5, rotation=False, Augments data by randomly scaling, rotating, flipping, and adjusting contrast :param image: image of size nchan x Ly x Lx :type image: ND-array :param keypoints: keypoints of size nkeypoints x 2 :type keypoints: ND-array :param scale: whether to scale the image :type scale: bool :param scale_range: range of scaling factor :type scale_range: float :param rotation: whether to rotate the image :type rotation: bool :param rotation_range: range of rotation angle :type rotation_range: float :param flip: whether to flip the image horizontally :type flip: bool :param contrast_adjust: whether to adjust contrast of image :type contrast_adjust: bool Returns • image (ND-array) – image of size nchan x Ly x Lx • keypoints (ND-array) – keypoints of size nkeypoints x 2 facemap.pose.transforms.crop_image(im, bbox=None) Crop image to bounding box. :param im: image of size [(Lz) x Ly x Lx] :type im: ND-array :param bbox: bounding box positions in order x1, x2, y1, y2 :type bbox: tuple of size (4,) Returns im – cropped image of size [1 x Ly x Lx] Return type ND-array facemap.pose.transforms.get_crop_resize_params(img, x_dims, y_dims, xy=(256, 256)) Get cropped and resized image dimensions Input:- img: image x_dims: min,max x pos y_dims: min,max y pos xy: final (desired) image size Output:- x1: (int) x dim start pos x2: (int) x dim stop pos y1: (int) y dim start pos y2: (int) y dim stop pos resize: (bool) whether to resize image facemap.pose.transforms.get_cropped_imgs(imgs, bbox) Preproccesing of image involves: conversion to float32 in range0-1, normalize99, and padding image size to be compatible with UNet model input :param imgs: images of size [batch_size x nchan x Ly x Lx] :type imgs: ND-array :param bbox: bounding box positions in order x1, x2, y1, y2 :type bbox: tuple of size (4,) Returns cropped_imgs – images of size [batch_size x nchan x Ly’ x Lx’] where Ly’ = y2-y1 and Lx’=x2- x1 Facemap, Release 1.0.2 Return type ND-array facemap.pose.transforms.get_random_factor(factor_range) Get a random factor within the range provided. :param factor_range: factor range in order min, max :type factor_range: tuple of size (2,) Returns factor – random factor Return type float facemap.pose.transforms.pad_img_to_square(img, bbox=None) Pad image to square. :param im: image of size [c x h x w] :type im: ND-array :param bbox: bounding box positions in order x1, x2, y1, y2 used for cropping image :type bbox: tuple of size (4,) Returns • im (ND-array) – padded image of size [c x h x w] • (pad_w, pad_h) (tuple of int) – padding values for width and height facemap.pose.transforms.pad_keypoints(keypoints, pad_h, pad_w) Pad keypoints using padding values for width and height. :param keypoints: keypoints of size [N x 2] :type keypoints: ND-array :param pad_h: height padding :type pad_h: int :param pad_w: width padding :type pad_w: int Returns keypoints – padded keypoints of size [N x 2] Return type ND-array facemap.pose.transforms.preprocess_img(im, bbox, add_padding, resize, device=None) Preproccesing of image involves: 1. Conversion to float32 and normalize99 2. Cropping image to select bounding box (bbox) region 3. padding image size to be square 4. Resize image to 256x256 for model input Parameters bbox: tuple of size (4,) bounding box positions in order x1, x2, y1, y2 add_padding: bool whether to add padding to image resize: bool whether to resize image Returns postpad_shape: tuple of size (2,) shape of padded image Facemap, Release 1.0.2 pads: tuple of size (4,) padding values for (pad_y_top, pad_y_bottom, pad_x_left, pad_x_right) facemap.pose.transforms.randomize_bbox_coordinates(bbox, im_shape, random_factor_range=(0.1, Randomize bounding box by a random amount to increase/expand the bounding box region while staying within the image region. :param bbox: bounding box positions in order x1, x2, y1, y2 :type bbox: tuple of size (4,) :param im_shape: image shape in order Ly, Lx :type im_shape: tuple of size (2,) :param random_factor_range: range of random factor to use for expaning bounding box :type random_factor_range: tuple of size (2,) Returns bbox – randomized bounding box positions in order x1, x2, y1, y2 Return type tuple of size (4,) facemap.pose.transforms.rescale_keypoints(xlabels, ylabels, current_size, desired_size) Rescale keypoints to original image size :param xlabels: x coordinates of keypoints :type xlabels: ND-array :param ylabels: y coordinates of keypoints :type ylabels: ND-array :param current_size: current size of image (h,w) :type current_size: tuple of size (2,) :param desired_size: desired size of image (h,w) :type desired_size: tuple of size (2,) Returns • xlabels (ND-array) – x coordinates of keypoints • ylabels (ND-array) – y coordinates of keypoints facemap.pose.transforms.resize_image(im, resize_shape) Resize image to given height and width. :param im: image of size [Ly x Lx] :type im: ND-array :param re- size_shape: desired shape of image :type resize_shape: tuple of size (2,) Returns im – resized image of size [h x w] Return type ND-array facemap.pose.transforms.resize_keypoints(keypoints, desired_shape, original_shape) Resize keypoints to desired shape. :param keypoints: keypoints of size [batch x N x 2] :type keypoints: ND-array :param desired_shape: desired shape of image :type desired_shape: tuple of size (2,) :param original_shape: original shape of image :type original_shape: tuple of size (2,) Returns keypoints – keypoints of size [batch x N x 2] Return type ND-array PYTHON MODULE INDEX f facemap.pose.transforms, 23 facemap.process, 22 27 Facemap, Release 1.0.2 28 Python Module Index INDEX A predict_landmarks() (facemap.pose.pose.Pose adjust_bbox() (in module facemap.pose.transforms), method), 21 23 preprocess_img() (in module adjust_keypoints() (in module facemap.pose.transforms), 25 facemap.pose.transforms), 23 process_blink_ROIs() (in module facemap.process), adjust_keypoints_for_padding() (in module 22 facemap.pose.transforms), 24 process_pupil_ROIs() (in module facemap.process), augment_data() (in module facemap.pose.transforms), 22 24 process_running() (in module facemap.process), 22 C R crop_image() (in module facemap.pose.transforms), 24 randomize_bbox_coordinates() (in module F rescale_keypoints() (in module facemap.pose.transforms facemap.pose.transforms), 26 module, 23 resize_image() (in module facemap.pose.transforms), facemap.process 26 module, 22 resize_keypoints() (in module get_crop_resize_params() (in module facemap.pose.transforms), 24 S get_cropped_imgs() (in module save_data_to_hdf5() (facemap.pose.pose.Pose facemap.pose.transforms), 24 method), 21 get_random_factor() (in module save_dict_to_hdf5() (facemap.pose.pose.Pose facemap.pose.transforms), 25 method), 21 load_model() (facemap.pose.pose.Pose method), 21 T module facemap.pose.transforms, 23 facemap.process, 22 P pad_img_to_square() (in module facemap.pose.transforms), 25 pad_keypoints() (in module facemap.pose.transforms), 25 Pose (class in facemap.pose.pose), 21
nephro
cran
R
Package ‘nephro’ October 13, 2022 Type Package Title Utilities for Nephrology Version 1.3 Date 2022-05-01 Author <NAME>, <NAME> Maintainer <NAME> <<EMAIL>> Description Set of functions to estimate kidney function and other phenotypes of interest in nephrol- ogy based on different biomechimal traits. MDRD, CKD-EPI, and Virga equations are com- pared in Pattaro (2013) <doi:10.1159/000351043>, where the respective refer- ences are given. In addition, the software in- cludes Stevens (2008) <doi:10.1053/j.ajkd.2007.11.018> and Cock- roft (1976) <doi:10.1159/000180580> formulas. The race-free CKD-EPI equa- tions (2021) <doi:10.1056/NEJMoa2102953> are also implemented from ver.1.3. License GPL (>= 3) NeedsCompilation no Repository CRAN Date/Publication 2022-05-06 13:30:02 UTC R topics documented: nephro-packag... 2 C... 4 CKDEpi.crea... 5 CKDEpi.creat.cy... 6 CKDEpi.creat.cys.r... 7 CKDEpi.creat.r... 8 CKDEpi.cy... 8 MDRD... 9 MDRD... 10 Stevens.creat.cy... 11 Stevens.cys... 12 Stevens.cys... 12 Virg... 13 nephro-package Biostatistics utilities for nephrology Description This package contains a set of tools for the estimation of kidney function. Kidney function is assessed by means of the Glomerular Filtration Rate (GFR), which can be estimated using differ- ent biomarkers. The most commonly used ones are serum or plasma creatinine and cystatin C. Included in this package are the following GFR estimating functions: the Modification of Diet in Renal Disease (MDRD) study equation based on four (MDRD4) or six (MDRD6) parameters (see Levey 1999, 2006); the CKD-Epi equations for creatinine (CKDEpi.creat, CKDEpi.creat.rf), cystatin C (CKDEpi.cys), and a combination of creatinine and cystatin C (CKDEpi.creat.cys, CKDEpi.creat.cys.rf) (see Inker 2012 & Inker 2021); the three equations proposed by Stevens 2008 based on cystatin C only (Stevens.cys1), age- and sex-weighted cystatin C (Stevens.cys2), and a combination of cystatin C and creatinine (Stevens.creat.cys); the classic Cockroft and Gault 1976 equation for creatinine clearance estimation (CG); and the recent equation by Virga (2007) (Virga). A comparative description of several functions included in the package can be found in Pattaro (2013). An extensive literature does exist that compares the methods described. Details Package: nephro Type: Package Version: 1.3 Date: 2022-05-01 License: GPLv3 Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> Acknowledgements: Max Plischke (contributed examples and bug reporting) References Citing this package: - P<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Estimating the glomerular filtration rate in the general population using different equations: effects on classification and asso- ciation. Nephron Clin Pract 2013; 123(1-2):102-11. Formulas: - Cockroft DW, Gault MH. Prediction of creatinine clearance from serum creatinine. Nephron 1976; 16: 31-41. - Inker LA, et al. Estimating glomerular filtration rate from serum creatinine and cystatin C. N Engl J Med 2012; 367: 20-9. - Inker LA, et al. New Creatinine- and Cystatin C-based Equations to Estimate GFR without Race. N Engl J Med 2021; 385: 1737-1749. - Levey AS, et al. A more accurate method to estimate glomerular filtration rate from serum crea- tinine: a new prediction equation. Modification of Diet in Renal Disease Study Group. Ann Intern Med. 1999; 130(6): 461-70. - Levey AS, et al. Using standardized serum creatinine values in the modification of diet in renal disease study equation for estimating glomerular filtration rate. Ann Intern Med. 2006; 145: 247- 54. - Stevens LA, et al. Estimating GFR using serum cystatin C alone and in combination with serum creatinine: a pooled analysis of 3,418 individuals with CKD. Am J Kidney Dis 2008; 51: 395-406. - Virga G, et al. A new equation for estimating renal function using age, body weight and serum creatinine. Nephron Clin Pract 2007; 105: c43-53. On IDMS calibration: - <NAME>, et al. Expressing the Modification of Diet in Renal Disease Study equation for es- timating glomerular filtration rate with standardized serum creatinine values. Clin Chem 2007; 53:766-72. - <NAME>, et al. Comparison of risk prediction using the CKD-EPI equation and the MDRD study equation for estimated glomerular filtration rate. J Am Med Assoc 2012; 307:1941-51. - <NAME>, et al. Prognostic assessment of estimated glomerular filtration rate by the new Chronic Kidney Disease Epidemiology Collaboration equation in comparison with the Modification of Diet in Renal Disease Study equation. Am Heart J 2011; 162:548-54. Examples # Comparison between different equations creat <- c(0.8, 0.9, 1.0, 1.1, 1.2, 1.3) cyst <- c(1.1, 0.95, 1.1, 1.0, 1.3, 1.2) sex <- c(1, 1, 1, 0, 0, 0) age <- c(60, 65, 43, 82, 71, 55) ethn <- round(runif(6)) wt <- c(70, 80, 60, 55, 87, 71) eGFR <- data.frame(creat, cyst) eGFR$MDRD4 <- MDRD4(creat, sex, age, ethn, 'IDMS') eGFR$CKDEpi.creat <- CKDEpi.creat(creat, sex, age, ethn) eGFR$CKDEpi.creat.rf <- CKDEpi.creat.rf(creat, sex, age) eGFR$CKDEpi.cys <- CKDEpi.cys(cyst, sex, age) eGFR$CKDEpi.creat.cys <- CKDEpi.creat.cys(creat, cyst, sex, age, ethn) eGFR$CKDEpi.creat.cys.rf <- CKDEpi.creat.cys.rf(creat, cyst, sex, age) eGFR$Stevens.cys1 <- Stevens.cys1(cyst) eGFR$Stevens.cys2 <- Stevens.cys2(cyst, sex, age, ethn) eGFR$Stevens.creat.cys <- Stevens.creat.cys(creat, cyst, sex, age, ethn) eGFR$cg <- CG(creat, sex, age, wt) eGFR$virga <- Virga(creat, sex, age, wt) pairs(eGFR[,3:13]) # For use with non-IDMS calibrated creatinine # several authors (see references) suggested # a 5% creatinine adjustment creat <- c(0.8, 0.9, 1.0, 1.1, 1.2, 1.3) sex <- c(1, 1, 1, 0, 0, 0) age <- c(60, 65, 43, 82, 71, 55) ethn <- round(runif(6)) gfr <- CKDEpi.creat(0.95*creat, sex, age, ethn) CG Cockroft and Gault equation Description Creatinine clearance is estimated with the Cockroft and Gault formula. Usage CG(creatinine, sex, age, wt) Arguments creatinine Numeric vector with serum or plasma creatinine values in mg/dl sex Numeric vector with 0 for females and 1 for males age Numeric vector with age in years wt Numeric vector with weight in kg Value A numeric vector with eGFR values in ml/min/1.73 m2 . Author(s) <NAME> References Cockroft DW, Gault MH. Prediction of creatinine clearance from serum creatinine. Nephron 1976; 16: 31-41. See Also CKDEpi.creat, MDRD4, Virga CKDEpi.creat CKD-EPI equation for serum creatinine Description GFR is estimated with the CKD-EPI Study equation based on IDMS serum or plasma creatinine. Usage CKDEpi.creat(creatinine, sex, age, ethnicity) Arguments creatinine Numeric vector with serum or plasma creatinine values in mg/dl sex Numeric vector with 0 for females and 1 for males age Numeric vector with age in years ethnicity Numeric vector with 0 for non-Black and 1 for Black individuals Value A numeric vector with eGFR values in ml/min/1.73 m2 . Author(s) <NAME> References Inker LA, et al. Estimating glomerular filtration rate from serum creatinine and cystatin C. N Engl J Med 2012; 367: 20-29. See Also CKDEpi.creat.cys, CKDEpi.cys, CKDEpi.creat.rf, CKDEpi.creat.cys.rf CKDEpi.creat.cys CKD-EPI equation for creatinine and cystatin C Description CKD-EPI equation to estimate GFR based on a combination of creatinine and cystatin C Usage CKDEpi.creat.cys(creatinine, cystatin, sex, age, ethnicity) Arguments creatinine Numeric vector with serum or plasma creatinine values in mg/dl cystatin Numeric vector with serum or plasma cystatin C values in mg/dl sex Numeric vector with 0 for females and 1 for males age Numeric vector with age in years ethnicity Numeric vector with 0 for non-Black and 1 for Black individuals Value A numeric vector with eGFR values in ml/min/1.73 m2 . Author(s) <NAME> References Inker LA, et al. Estimating glomerular filtration rate from serum creatinine and cystatin C. N Engl J Med 2012; 367: 20-29. See Also CKDEpi.creat, CKDEpi.cys, CKDEpi.creat.rf, CKDEpi.creat.cys.rf CKDEpi.creat.cys.rf CKD-EPI equation for serum creatinine and cystatin C without race coefficient Description CKD-EPI equation to estimate GFR based on a combination of creatinine and cystatin C without race coefficient Usage CKDEpi.creat.cys.rf(creatinine, cystatin, sex, age) Arguments creatinine Numeric vector with serum or plasma creatinine values in mg/dl cystatin Numeric vector with serum or plasma cystatin C values in mg/l sex Numeric vector with 0 for females and 1 for males age Numeric vector with age in years Value A numeric vector with eGFR values in ml/min/1.73 m2 . Author(s) <NAME> References Inker LA, et al. New creatinine- and cystatin C-based equations to estimate GFR without race. N Engl J Med 2021; 385: 1737-1749. See Also CKDEpi.creat, CKDEpi.creat.cys, CKDEpi.cys, CKDEpi.creat.rf CKDEpi.creat.rf CKD-EPI equation for serum creatinine without race coefficient Description GFR is estimated with the CKD-EPI Study equation based on serum creatinine without race coeffi- cient. Usage CKDEpi.creat.rf(creatinine, sex, age) Arguments creatinine Numeric vector with serum or plasma creatinine values in mg/dl sex Numeric vector with 0 for females and 1 for males age Numeric vector with age in years Value A numeric vector with eGFR values in ml/min/1.73 m2 . Author(s) <NAME> References Inker LA, et al. New creatinine- and cystatin C-based equations to estimate GFR without race. N Engl J Med 2021; 385: 1737-1749. See Also CKDEpi.creat, CKDEpi.creat.cys, CKDEpi.cys, CKDEpi.creat.cys.rf CKDEpi.cys CKD-EPI equation for cystatin C Description GFR is estimated with the CKD-EPI equation for cystatin C proposed by Inker et al., N Engl J Med 2012 Usage CKDEpi.cys(cystatin, sex, age) Arguments cystatin Numeric vector with serum or plasma cystatin C values in mg/l sex Numeric vector with 0 for females and 1 for males age Numeric vector with age in years Value The function returns a numeric vector with eGFR values in ml/min/1.73 m2 . Author(s) <NAME> References Inker LA, et al. Estimating glomerular filtration rate from serum creatinine and cystatin C. N Engl J Med 2012; 367: 20-29. See Also CKDEpi.creat, CKDEpi.creat.cys, CKDEpi.creat.rf, CKDEpi.creat.cys.rf MDRD4 Four-parameter MDRD study equation Description GFR is estimated with the 4-parameter Modification of Diet in Renal Disease (MDRD) study equa- tion. Usage MDRD4(creatinine, sex, age, ethnicity, method = "IDMS") Arguments creatinine Numeric vector with serum or plasma creatinine values in mg/dl sex Numeric vector with 0 for females and 1 for males age Numeric vector with age in years ethnicity Numeric vector with 0 for non-Black and 1 for Black individuals method Defaults is ’IDMS’ for IDMS-traceable creatinine; write ’other’ if not IDMS Value A numeric vector with eGFR values in ml/min/1.73 m2 . Author(s) <NAME> References Levey AS, et al. A more accurate method to estimate glomerular filtration rate from serum creati- nine: a new prediction equation. Modification of Diet in Renal Disease Study Group. Ann Intern Med. 1999; 130(6): 461-70. Levey AS, et al. Using standardized serum creatinine values in the modification of diet in renal dis- ease study equation for estimating glomerular filtration rate. Ann Intern Med. 2006; 145: 247-254. See Also CKDEpi.creat, MDRD6, CG MDRD6 Six-parameter MDRD study equation Description GFR is estimated with the 6-parameter Modification of Diet in Renal Disease (MDRD) study equa- tion. Usage MDRD6(creatinine, sex, age, albumin, BUN, ethnicity, method = 'IDMS') Arguments creatinine Numeric vector with serum or plasma creatinine values in mg/dl sex Numeric vector with 0 for females and 1 for males age Numeric vector with age in years albumin Numeric vector with serum or plasma albumin in g/dl BUN Numeric vector with blood urea nitrogen levels in mg/dl ethnicity Numeric vector with 0 for non-Black and 1 for Black individuals method Defaults is ’IDMS’ for IDMS-traceable creatinine; write ’other’ if not IDMS Value A numeric vector with eGFR values in ml/min/1.73 m2 . Author(s) <NAME> References Levey AS, et al. A more accurate method to estimate glomerular filtration rate from serum creati- nine: a new prediction equation. Modification of Diet in Renal Disease Study Group. Ann Intern Med. 1999; 130(6): 461-70. Levey AS, et al. Using standardized serum creatinine values in the modification of diet in renal dis- ease study equation for estimating glomerular filtration rate. Ann Intern Med. 2006; 145: 247-254. See Also MDRD4 Stevens.creat.cys Stevens’ formula for a combination of serum creatinine and cystatin C Description GFR estimation using the 3rd formula proposed by Stevens et al. (Am J Kidney Dis 2008), which combines creatinine and cystatin C Usage Stevens.creat.cys(creatinine, cystatin, sex, age, ethnicity) Arguments creatinine Numeric vector with serum or plasma creatinine values in mg/dl cystatin Numeric vector with serum or plasma cystatin C values in mg/l sex Numeric vector with 0 for females and 1 for males age Numeric vector with age in years ethnicity Numeric vector with 0 for non-Black and 1 for Black individuals Value The function returns a numeric vector with eGFR values in ml/min/1.73 m2 . Author(s) <NAME> References Stevens LA, et al. Estimating GFR using serum cystatin C alone and in combination with serum creatinine: a pooled analysis of 3,418 individuals with CKD. Am J Kidney Dis 2008; 51: 395-406. See Also CKDEpi.creat.cys Stevens.cys1 GFR estimation using serum cystatin C Description GFR is estimated with the 1st formula proposed by Stevens et al. (Am J Kidney Dis 2008), i.e.: as a simple transformation of cystatin C, without using any other information Usage Stevens.cys1(cystatin) Arguments cystatin Numeric vector with serum or plasma cystatin C values in mg/l Value A numeric vector with eGFR values in ml/min/1.73 m2 . Author(s) <NAME> References Stevens LA, et al. Estimating GFR using serum cystatin C alone and in combination with serum creatinine: a pooled analysis of 3,418 individuals with CKD. Am J Kidney Dis 2008; 51: 395-406. See Also Stevens.cys2, Stevens.creat.cys, CKDEpi.cys Stevens.cys2 Stevens’ formula for serum cystatin C, age, and sex Description GFR is estimated with the 2nd formula proposed by Stevens et al. (Am J Kidney Dis 2008), where cystatin C is weighted by sex and age Usage Stevens.cys2(cystatin, sex, age, ethnicity) Arguments cystatin Numeric vector with serum or plasma cystatin C values in mg/l sex Numeric vector with 0 for females and 1 for males age Numeric vector with age in years ethnicity Numeric vector with 0 for non-Black and 1 for Black individuals Value A numeric vector with eGFR values in ml/min/1.73 m2 . Author(s) <NAME> References Stevens LA, et al. Estimating GFR using serum cystatin C alone and in combination with serum creatinine: a pooled analysis of 3,418 individuals with CKD. Am J Kidney Dis 2008; 51: 395-406. See Also Stevens.cys1, Stevens.creat.cys, CKDEpi.cys Virga Virga’s formula Description Virga’s formula is based on serum creatinine, sex, age, and body weight. Usage Virga(creatinine, sex, age, wt) Arguments creatinine Numeric vector with serum or plasma creatinine values in mg/dl sex Numeric 0/1 vector: 0 for females, 1 for males age Numeric vector with age in years wt Numeric vector with weight in kg Value A numeric vector with eGFR values in ml/min/1.73 m^2 Author(s) <NAME> References <NAME>, et al. A new equation for estimating renal function using age, body weight and serum creatinine. Nephron Clin Pract 2007; 105: c43-53. See Also CG, MDRD4
@aws-sdk/client-controltower
npm
JavaScript
[@aws-sdk/client-controltower](#aws-sdkclient-controltower) === [Description](#description) --- AWS SDK for JavaScript ControlTower Client for Node.js, Browser and React Native. These interfaces allow you to apply the AWS library of pre-defined *controls* to your organizational units, programmatically. In AWS Control Tower, the terms "control" and "guardrail" are synonyms. . To call these APIs, you'll need to know: * the `controlIdentifier` for the control--or guardrail--you are targeting. * the ARN associated with the target organizational unit (OU), which we call the `targetIdentifier`. **To get the `controlIdentifier` for your AWS Control Tower control:** The `controlIdentifier` is an ARN that is specified for each control. You can view the `controlIdentifier` in the console on the **Control details** page, as well as in the documentation. The `controlIdentifier` is unique in each AWS Region for each control. You can find the `controlIdentifier` for each Region and control in the [Tables of control metadata](https://docs.aws.amazon.com/controltower/latest/userguide/control-metadata-tables.html) in the *AWS Control Tower User Guide.* A quick-reference list of control identifers for the AWS Control Tower legacy *Strongly recommended* and *Elective* controls is given in [Resource identifiers for APIs and guardrails](https://docs.aws.amazon.com/controltower/latest/userguide/control-identifiers.html.html) in the [Controls reference guide section](https://docs.aws.amazon.com/controltower/latest/userguide/control-identifiers.html) of the *AWS Control Tower User Guide*. Remember that *Mandatory* controls cannot be added or removed. **ARN format:** `arn:aws:controltower:{REGION}::control/{CONTROL_NAME}` **Example:** `arn:aws:controltower:us-west-2::control/AWS-GR_AUTOSCALING_LAUNCH_CONFIG_PUBLIC_IP_DISABLED` **To get the `targetIdentifier`:** The `targetIdentifier` is the ARN for an OU. In the AWS Organizations console, you can find the ARN for the OU on the **Organizational unit details** page associated with that OU. **OU ARN format:** `arn:${Partition}:organizations::${MasterAccountId}:ou/o-${OrganizationId}/ou-${OrganizationalUnitId}` **Details and examples** * [Control API input and output examples with CLI](https://docs.aws.amazon.com/controltower/latest/userguide/control-api-examples-short.html) * [Enable controls with CloudFormation](https://docs.aws.amazon.com/controltower/latest/userguide/enable-controls.html) * [Control metadata tables](https://docs.aws.amazon.com/controltower/latest/userguide/control-metadata-tables.html) * [List of identifiers for legacy controls](https://docs.aws.amazon.com/controltower/latest/userguide/control-identifiers.html) * [Controls reference guide](https://docs.aws.amazon.com/controltower/latest/userguide/controls.html) * [Controls library groupings](https://docs.aws.amazon.com/controltower/latest/userguide/controls-reference.html) * [Creating AWS Control Tower resources with AWS CloudFormation](https://docs.aws.amazon.com/controltower/latest/userguide/creating-resources-with-cloudformation.html) To view the open source resource repository on GitHub, see [aws-cloudformation/aws-cloudformation-resource-providers-controltower](https://github.com/aws-cloudformation/aws-cloudformation-resource-providers-controltower) **Recording API Requests** AWS Control Tower supports AWS CloudTrail, a service that records AWS API calls for your AWS account and delivers log files to an Amazon S3 bucket. By using information collected by CloudTrail, you can determine which requests the AWS Control Tower service received, who made the request and when, and so on. For more about AWS Control Tower and its support for CloudTrail, see [Logging AWS Control Tower Actions with AWS CloudTrail](https://docs.aws.amazon.com/controltower/latest/userguide/logging-using-cloudtrail.html) in the AWS Control Tower User Guide. To learn more about CloudTrail, including how to turn it on and find your log files, see the AWS CloudTrail User Guide. [Installing](#installing) --- To install the this package, simply type add or install @aws-sdk/client-controltower using your favorite package manager: * `npm install @aws-sdk/client-controltower` * `yarn add @aws-sdk/client-controltower` * `pnpm add @aws-sdk/client-controltower` [Getting Started](#getting-started) --- ### [Import](#import) The AWS SDK is modulized by clients and commands. To send a request, you only need to import the `ControlTowerClient` and the commands you need, for example `ListEnabledControlsCommand`: ``` // ES5 example const { ControlTowerClient, ListEnabledControlsCommand } = require("@aws-sdk/client-controltower"); ``` ``` // ES6+ example import { ControlTowerClient, ListEnabledControlsCommand } from "@aws-sdk/client-controltower"; ``` ### [Usage](#usage) To send a request, you: * Initiate client with configuration (e.g. credentials, region). * Initiate command with input parameters. * Call `send` operation on client with command object as input. * If you are using a custom http handler, you may call `destroy()` to close open connections. ``` // a client can be shared by different commands. const client = new ControlTowerClient({ region: "REGION" }); const params = { /** input parameters */ }; const command = new ListEnabledControlsCommand(params); ``` #### [Async/await](#asyncawait) We recommend using [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) operator to wait for the promise returned by send operation as follows: ``` // async/await. try { const data = await client.send(command); // process data. } catch (error) { // error handling. } finally { // finally. } ``` Async-await is clean, concise, intuitive, easy to debug and has better error handling as compared to using Promise chains or callbacks. #### [Promises](#promises) You can also use [Promise chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining) to execute send operation. ``` client.send(command).then( (data) => { // process data. }, (error) => { // error handling. } ); ``` Promises can also be called using `.catch()` and `.finally()` as follows: ``` client .send(command) .then((data) => { // process data. }) .catch((error) => { // error handling. }) .finally(() => { // finally. }); ``` #### [Callbacks](#callbacks) We do not recommend using callbacks because of [callback hell](http://callbackhell.com/), but they are supported by the send operation. ``` // callbacks. client.send(command, (err, data) => { // process err and data. }); ``` #### [v2 compatible style](#v2-compatible-style) The client can also send requests using v2 compatible style. However, it results in a bigger bundle size and may be dropped in next major version. More details in the blog post on [modular packages in AWS SDK for JavaScript](https://aws.amazon.com/blogs/developer/modular-packages-in-aws-sdk-for-javascript/) ``` import * as AWS from "@aws-sdk/client-controltower"; const client = new AWS.ControlTower({ region: "REGION" }); // async/await. try { const data = await client.listEnabledControls(params); // process data. } catch (error) { // error handling. } // Promises. client .listEnabledControls(params) .then((data) => { // process data. }) .catch((error) => { // error handling. }); // callbacks. client.listEnabledControls(params, (err, data) => { // process err and data. }); ``` ### [Troubleshooting](#troubleshooting) When the service returns an exception, the error will include the exception information, as well as response metadata (e.g. request id). ``` try { const data = await client.send(command); // process data. } catch (error) { const { requestId, cfId, extendedRequestId } = error.$$metadata; console.log({ requestId, cfId, extendedRequestId }); /** * The keys within exceptions are also parsed. * You can access them by specifying exception names: * if (error.name === 'SomeServiceException') { * const value = error.specialKeyInException; * } */ } ``` [Getting Help](#getting-help) --- Please use these community resources for getting help. We use the GitHub issues for tracking bugs and feature requests, but have limited bandwidth to address them. * Visit [Developer Guide](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html) or [API Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html). * Check out the blog posts tagged with [`aws-sdk-js`](https://aws.amazon.com/blogs/developer/tag/aws-sdk-js/) on AWS Developer Blog. * Ask a question on [StackOverflow](https://stackoverflow.com/questions/tagged/aws-sdk-js) and tag it with `aws-sdk-js`. * Join the AWS JavaScript community on [gitter](https://gitter.im/aws/aws-sdk-js-v3). * If it turns out that you may have found a bug, please [open an issue](https://github.com/aws/aws-sdk-js-v3/issues/new/choose). To test your universal JavaScript code in Node.js, browser and react-native environments, visit our [code samples repo](https://github.com/aws-samples/aws-sdk-js-tests). [Contributing](#contributing) --- This client code is generated automatically. Any modifications will be overwritten the next time the `@aws-sdk/client-controltower` package is updated. To contribute to client you can check our [generate clients scripts](https://github.com/aws/aws-sdk-js-v3/tree/main/scripts/generate-clients). [License](#license) --- This SDK is distributed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0), see LICENSE for more information. [Client Commands (Operations List)](#client-commands-operations-list) --- DisableControl [Command API Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/classes/disablecontrolcommand.html) / [Input](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/interfaces/disablecontrolcommandinput.html) / [Output](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/interfaces/disablecontrolcommandoutput.html) EnableControl [Command API Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/classes/enablecontrolcommand.html) / [Input](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/interfaces/enablecontrolcommandinput.html) / [Output](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/interfaces/enablecontrolcommandoutput.html) GetControlOperation [Command API Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/classes/getcontroloperationcommand.html) / [Input](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/interfaces/getcontroloperationcommandinput.html) / [Output](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/interfaces/getcontroloperationcommandoutput.html) GetEnabledControl [Command API Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/classes/getenabledcontrolcommand.html) / [Input](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/interfaces/getenabledcontrolcommandinput.html) / [Output](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/interfaces/getenabledcontrolcommandoutput.html) ListEnabledControls [Command API Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/classes/listenabledcontrolscommand.html) / [Input](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/interfaces/listenabledcontrolscommandinput.html) / [Output](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-controltower/interfaces/listenabledcontrolscommandoutput.html) Readme --- ### Keywords none
util
hex
Erlang
Erlang Utility Modules === [![build](https://github.com/saleyn/util/actions/workflows/erlang.yml/badge.svg)](https://github.com/saleyn/util/actions/workflows/erlang.yml) **Author** <NAME> <serge(at)gmail.com[installation](#installation) Installation --- * Add dependency in `rebar.config`: ``` {deps, [% ... {util, "~> 1.0"} ]}. ``` [content](#content) Content --- | Module | Description | | --- | --- | | decompiler | decompiles modules and functions (useful for verifying accuracy of code generation) | | csv | CSV parsing and loading data to MySQL | | env | environment variables substitution, path normalization | | file_log_reader | Periodically read an append-only log file and parse newly added data | | iif | Ternery if function including `iif/3`, `iif/4`, `ife/3`, `ife/4` parse transforms | | io_lib_pretty_limited | Print term to binary by constraining the output size | | gin | Convenient parse transform for `in(Value, [A,B,C])` type of guards | | hex | Hex to bin conversion | | listx | Miscelaneous list handling functions | | osx | Execution of os commands with returned stdout and exit status | | pcap | reader/writer of packet capture files (tcpdump, wireshark) | | restrict_remsh_mod | to be used for remote shells to restrict `q()`, [`init:stop/0`](https://www.erlang.org/doc/man/init.html#stop-0), [`erlang:halt/0`](https://www.erlang.org/doc/man/erlang.html#halt-0), etc. | | smtp | SMTP client supporting tcp and ssl protocols | | sntp | simple SNTP client | | str | stringification functions including `str/1` and `str/2` parse transforms | | stringx | miscelaneous string functions | | throttle | implements a rate limitting algorithm | | user_default | extending shell with useful debugging and profiling commands | | build-aux/md-to-edoc.awk | AWK script for converting `README.md` files to `overview.edoc` | Additionally, the following Elixir modules are included: | Module | File | Description | | --- | --- | --- | | CompileTime | compile_time.ex | Evaluate lambdas at compile time | [documentation](#documentation) Documentation --- * See [project documentation](https://saleyn.github.io/util) This project implements an extension of `EDoc` documentation by using the color scheme similar to `GitHub`, and generate the `overview.edoc` from the `README.md`. In order to use this feature, modify your `Makefile` to include: ``` -include build-aux/docs-addon.mk build-aux/docs-addon.mk: @echo "Fetching build-aux/docs-addon.mk" && \ mkdir -p build-aux && \ curl -s -o build-aux/docs-addon.mk https://raw.githubusercontent.com/saleyn/util/master/build-aux/docs-addon.mk ``` Also in your `rebar.config` add: ``` {edoc_opts, [{overview, "build-aux/overview.edoc"}, {stylesheet_file, "build-aux/edoc.css"}, {title, "Project title used by rebar and also inserted as title to the index.html"}, {keywords, "HTML meta keywords (comma-delimited) for search engine crawlers"}, ...]}. ``` NOTE: the `keywords` option is not specific to `EDoc` but used by the HTML reformatting make file `docs-addon.mk`. This will add the following targets to your `Makefile`: * `docs` - Make documentation from source code * `gh-pages` - Create GitHub pages for the current project * `get-version` - Show application release version from the `*.app.src` and `rebar.config` * `set-version` - Set the version number for the above `(make set-version version=X.Y.Z)` * `clean-docs` - Remove the generated files in the `doc` directory [elixir](#elixir) Elixir --- To add functions from `user_default.erl` to Elixir's `iex` shell, add `~/.iex.exs` file containing: ``` import :user_default ``` [download](#download) Download --- * [GitHub](http://saleyn.github.io/util) [API Reference](api-reference.html) [Next Page → License](license.html) CompileTime === [Link to this section](#summary) Summary === [Functions](#functions) --- [eval(f)](#eval/1) Evaluate a function at compile time. [Link to this section](#functions) Functions === alias === Creation of module aliases [Link to this section](#summary) Summary === [Functions](#functions) --- [create(Alias, OrigMod)](#create/2) Create a module `Alias` for the given `OrigMod` module. This function is useful for creating in-memory Elixir wrapper modules without needing to maintain persistent files with such wrappers. `IncFuns` argument can be `all` or a list of `{Fun, Arity}` values which only export a subset of functions from the `OrigMod`. [create(Alias, OrigMod, IncFuns)](#create/3) [Link to this section](#functions) Functions === base32 === [Link to this section](#summary) Summary === [Functions](#functions) --- [decode(Bin)](#decode/1) [decode(Bin, Opts)](#decode/2) [encode(Bin)](#encode/1) [encode(Bin, Opts)](#encode/2) [Link to this section](#functions) Functions === cipher === [Link to this section](#summary) Summary === [Functions](#functions) --- [decrypt(Encrypted, Key)](#decrypt/2) [decrypt_base64(EncryptedBase64, KeyBase64)](#decrypt_base64/2) [encrypt(Text, KeyPlainText)](#encrypt/2) [encrypt_base64(Text, KeyBase64)](#encrypt_base64/2) [gpg_key_decode(File)](#gpg_key_decode/1) Decode PGP public key [make_key(PlainKey)](#make_key/1) [make_key_base64(PlainKey)](#make_key_base64/1) [Link to this section](#functions) Functions === csv === CSV file parsing functions [Link to this section](#summary) Summary === [Types](#types) --- [load_options/0](#t:load_options/0) Options for loading data to a database.{load_type, Type}Type of loading to perform. `recreate` will replace the table by atomically dropping the old one, creating/loading the new one, and replacing the table. `replace` will do an insert by using `REPLACE INTO` statement. `ignore_dups` will use `INSERT IGNORE INTO` statement to ignore records with duplicate keys. `update_dups` will do an `INSERT INTO` and `ON DUPLICATE KEY UPDATE`, so that the old records are updated and the new ones are inserted.{create_table, Allow}Allow to create a table if it doesn't exist{col_types, Map}Types of data for all or some columens. The Map is in the format: `ColName::binary() => ColInfo`, where ColInfo is `ColType | {ColType, ColLen::integer()}`, and `ColType` is: `date | datetime | integer | float | blob | number`.{transforms, Map}Value transformation function for columns. The Map is in the format: `ColName::binary() => fun((Value::term()) -> term())`.{batch_size, Size}Number of records per SQL insert/update/replace call{blob_size, Size}Threshold in number of bytes at which a VARCHAR field is defined as BLOB{save_create_sql_to_file, Filename::string()}Save CREATE TABLE sql statement to a fileguess_typesWhen specified, the function will try to guess the type of data in columns instead of treating all data as string fields. The possible data typed guessed: integer, float, date, datetime, number, string{guess_limit_rows, Limit}Limit the number of rows for guessing the column data types{max_nulls_pcnt, Percent}A percentage threshold of permissible NULLs in a column (0-100), above which the column data type is forced to be treated as `string`{primary_key, Fields}Names of primary key fields in the created table{drop_temp_table, boolean()}When true (default), temp table is dropped.{encoding, Encoding}The name of the encoding to use for storing data. For the list of permissible values [see this link](https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-sets.html)verbosePrint additional details to stdout [parse_options/0](#t:parse_options/0) CSV Parsing Options.fix_lengthsif a record has a column count greater than what's found in the header row, those extra columns will be dropped, and if a row has fewer columns, empty columns will be added.binaryReturn fields as binaries (default)listReturn fields as lists{open, list()}Options given to file:open/2{columns, Names}Return data only in given columns{converters, [{Col, fun((ColName, Value) -> NewValue)| {rex, RegEx, Replace}]}Data format converter. If `Col` is `all`, the same converting function is used for all columns. If the converter is a `{rex, RegEx, Replace}` then the regular expression replacement will be run on a value in the requested column. [Functions](#functions) --- [guess_data_type(S)](#guess_data_type/1) Guess the type of data by its value [guess_data_types(HasHeaderRow, Rows)](#guess_data_types/2) Guess data types of fields in the given CSV list of rows obtained by parsing a CSV file with `parse(File,[fix_lengths])`. The function returns a list of tuples `{Type, MaxFieldLen, NumOfNulls}`, where the `Type` is a field type, `MaxFieldLen` is the max length of data in this column, and `NumOfNulls` is the number of rows with empty values in this column. [load_to_mysql(File, Tab, MySqlPid, Opts)](#load_to_mysql/4) Load CSV data from a `File` to a `MySQL` database. `Tab` is the name of a table where to load data. `MySqlPid` is the pid of a MySQL database connection returned by `mysql:start_link/1`. The data in the table is replaced according to `{import_type, Type}`:* `recreate` - The table is entirely replaced with the data from file. The data from the file is loaded atomically - i.e. either the whole file loading succeeds or fails. This is accomplished by first loading data to a temporary table, and then using the database's ACID properties to replace the target table with the temporary table. * `replace` - Use "REPLACE INTO" instead of "INSERT INTO" existing table * `ignore_dups` - The insert in the existing table is performed and the records with duplicate keys are ignored * `update_dups` - The insert in the existing table is performed and the records with duplicate keys are updated * `upsert` - The insert/update in the existing table is performed without creating a temporary table NOTE: this function requires <https://github.com/mysql-otp/mysql-otp.git[max_field_lengths(HasHeaderRow, Rows)](#max_field_lengths/2) Get max field lengths for a list obtained by parsing a CSV file with `parse_csv_file(File,[fix_lengths])`. [parse(File)](#parse/1) Parse a CSV file using default options. [parse(File, Opts)](#parse/2) Parse a given CSV file. [parse_line(Line)](#parse_line/1) Parse a CSV line [Link to this section](#types) Types === [Link to this section](#functions) Functions === decompiler === Module and function decompiler [Link to this section](#summary) Summary === [Functions](#functions) --- [fun_src(Fun)](#fun_src/1) Decompile a function to its source text [fun_src(Fun, Options)](#fun_src/2) Decompile a function to its source text [run(BeamFName)](#run/1) Decompile a beam file [run(BeamFName, Options)](#run/2) Decompile a beam file and optionally save it to disk [Link to this section](#functions) Functions === env === Environment utils [Link to this section](#summary) Summary === [Functions](#functions) --- [get_env(App, Key, Default)](#get_env/3) Get application configuration [home_dir()](#home_dir/0) [normalize_path(Path)](#normalize_path/1) [replace_env_vars(OsPath)](#replace_env_vars/1) Perform replacement of environment variable values in the OsPath. ``` Example: env:replace_env_vars("~/app") -> "/home/cuser/app" env:replace_env_vars("${HOME}/app") -> "/home/cuser/app" env:replace_env_vars("$USER/app") -> "cuser/app" ``` *See also:* [os:getenv/1](https://www.erlang.org/doc/man/os.html#getenv-1). [replace_env_vars(OsPath, Bindings)](#replace_env_vars/2) Perform replacement of environment variable values in the OsPath. This function also allows to provide a list of `Bindings` that override the environment (they are checked before environment variables are looked up). ``` Example: env:replace_env_vars("~/", [{"HOME", "/home/cu"}]) -> "/home/cu/" env:replace_env_vars("~/", [{home, "/home/cu"}]) -> "/home/cu/" env:replace_env_vars("$A/", [{a, "/aaa"}]) -> "/aaa/" env:replace_env_vars("${A}/",[{a, "/aaa"}]) -> "/aaa/" ``` *See also:* [os:getenv/1](https://www.erlang.org/doc/man/os.html#getenv-1). [subst_env_path(OsPath)](#subst_env_path/1) [subst_env_path(OsPath, Bindings)](#subst_env_path/2) [Link to this section](#functions) Functions === erlang_scan === [Link to this section](#summary) Summary === [Functions](#functions) --- [format_error(_)](#format_error/1) [reserved_word(_)](#reserved_word/1) [string(Ics)](#string/1) [string(Ics, L0)](#string/2) [token(Cont, Chars)](#token/2) [token(Cont, Chars, Line)](#token/3) [tokens(Cont, Chars)](#tokens/2) [tokens(Cont, Chars, Line)](#tokens/3) [Link to this section](#functions) Functions === file_log_reader === Periodically read an append-only log file and parse newly added data. The user controls the interval in msec how often to check for file modifications. When new data is appended to file it triggers invocation of the user-defined parsing function that deliminates the file, and the result is delivered to the consumer by calling the consumer callback function. The log reader can be started as a `gen_server` or can be controlled synchronously by using [`init/3`](#init/3), [`run/1`](#run/1), and [`close/1`](#close/1) methods. [Link to this section](#summary) Summary === [Types](#types) --- [consumer/0](#t:consumer/0) [options/0](#t:options/0) Details:posStart reading from this position (default: 0)end_posRead until this position and stop. If provided and file position reaches `end_pos`, the consumer() callback given to the reader will be called as: `Consumer({'$end_of_file', Filename::string(), Result}, Pos::integer(), State)` where `Result` is `ok` or `{error|exit|exception, Error::any(), StackTrace}` if an error occured.max_sizeMaximum chunk size to read from file in a single pass (default: 32M).timeoutNumber of milliseconds between successive file scanning (default: 1000)retry_secNumber of seconds between successive retries upon failure to open the market data file passed to one of the `start*/{3,4}` functions (default: 15). The value of 0 means that the file must exist or else the process won't start.parserIs the function to be called when the next chunk is read from file. The function must return:`{ok, Msg, Tail, State}`invoke `Consumer` callback passing it the parsed message `Msg`, and continue parsing the `Tail` binary`{incomplete, State}`the data contains no complete messages - wait until there's more`{skip, Tail, State}`disregard input and continue parsing `Tail` without calling `Consumer` callbackpstateInitial value of the parser state or a functor `fun((File::string() Consumer::consumer(), Options::options()) -> PState::any())`pstate_updateUpdate function of the parser state. Called when the user invokes [`update_pstate/3`](#update_pstate/3) [Functions](#functions) --- [close(State)](#close/1) Close file processor (use this method when not using gen_server) [init(File, Consumer, Options)](#init/3) When using file processor without gen_server, use this function to initialize the state, and then call run/1. [position(Pid)](#position/1) Report last processed file position/size. [pstate(Pid)](#pstate/1) Return current parser state (`{pstate, any()}` initialization option). [run(State)](#run/1) Process file from given position `Pos` to `EndPos` (or `eof`). [start(File, Consumer, Options)](#start/3) [start(RegName, File, Consumer, Options)](#start/4) Start the server outside of supervision tree. [start_link(File, Consumer, Options)](#start_link/3) Process `File` by calling `Consumer` callback on every delimited message. Message delimination is handled by the `{parser, Parser}` option. `Consumer` function gets called iteratively with the following arguments:(Msg, Pos::integer(), State)`Msg` is what the parser function returned. `Pos` is current file position following the `Msg`. `State` is current value of parser state that is initialized by `{pstate, PState}` option given to the `start_link/{3,4}` function({'$end_of_file', Filename::string(), Result}, Pos::integer(), PState)This call happens when end of file condition is reached (see definition of `consumer()` type)`Consumer` can end processing normally without reaching the end of file by throwing `{eof, PState}` exception. [start_link(RegName, File, Consumer, Options)](#start_link/4) To be called by the supervisor in order to start the server. If init/1 fails with Reason, the function returns `{error,Reason}`. If init/1 returns `{stop,Reason}` or ignore, the process is terminated and the function returns `{error,Reason}` or ignore, respectively.*See also:* [start_link/3](#start_link/3). [stop(Pid)](#stop/1) Stop the server. [update_pstate(Pid, Option, Value)](#update_pstate/3) Update parser state. [Link to this section](#types) Types === [Link to this section](#functions) Functions === gin === Guard in [Link to this section](#summary) Summary === [Functions](#functions) --- [parse_transform(Forms, Options)](#parse_transform/2) [Link to this section](#functions) Functions === hex === Hexadecimal conversion functions [Link to this section](#summary) Summary === [Functions](#functions) --- [dehex(C)](#dehex/1) Convert a hex digit in range [$0..$9,$a..$f,$A..$F] to integer. [hex(C)](#hex/1) Convert an integer to a hex digit in range [0..15]. [to_bin(Bin)](#to_bin/1) Convert a hex string to binary. [to_hex(I)](#to_hex/1) Convert an iolist to a hex string. [to_int(S)](#to_int/1) Convert a hex string/binary to integer. [Link to this section](#functions) Functions === io_lib_pretty_limited === [Link to this section](#summary) Summary === [Functions](#functions) --- [error_formatter_test()](#error_formatter_test/0) [print(Term, Limit)](#print/2) [Link to this section](#functions) Functions === listx === Miscelaneous list functions [Link to this section](#summary) Summary === [Functions](#functions) --- [copy_tuple_except(Ignore, I, N, TS, TT)](#copy_tuple_except/5) Copy every element of tuple TS to tuple TT ignoring the item at Ignore position [group(Pos, List)](#group/2) Group elements in the `List` by element at position `Pos`. [sum(ListOfTuples)](#sum/1) Add every positional element of each tuple in the list. E.g. `sum([{1,2}, {3,4}, {5,6}]) -> {9,12}.` [sum(Tuple1, Tuple2)](#sum/2) Add every positional element of two tuples. E.g. `sum({1,2}, {3,4}) -> {3,6}.` [zip_record(Fields, State)](#zip_record/2) Convert a record/tuple to a list of `{Name,Value}` pairs, where `Name` is a field name taken from the `Fields` list. [Link to this section](#functions) Functions === osx === OS supporting commands [Link to this section](#summary) Summary === [Functions](#functions) --- [command(Cmd)](#command/1) [command(Cmd, Fun)](#command/2) [command(Cmd, Opt, Fun)](#command/3) [normalpath(S)](#normalpath/1) Return a path where the use of ".." to indicate parent directory has been resolved. Currently does not accept relative paths. [realpath(Path)](#realpath/1) Return a canonicalized pathname, having resolved symlinks to their destination. Modelled on realpath(3). [status(Status)](#status/1) [Link to this section](#functions) Functions === pcap === PCAP file reader/writer. [Link to this section](#summary) Summary === [Functions](#functions) --- [replay(Filename)](#replay/1) [replay(Filename, Address)](#replay/2) [replay(Filename, Address, Port, FromN, ToN)](#replay/5) [replay_range(Filename, FromN, ToN)](#replay_range/3) [replay_range(Filename, Address, FromN, ToN)](#replay_range/4) [write(Filename, Packet)](#write/2) [Link to this section](#functions) Functions === pmap === Parallel map and multicall. [Link to this section](#summary) Summary === [Functions](#functions) --- [multicall(PidMsgs, Timeout)](#multicall/2) Send messages to pids and wait for replies. Each Pid would get a message in the form: `{{FromPid, Ref}, Msg}` and would have to reply with: `FromPid ! {{self(), Ref}, Reply}`. The function aggregates all replies into `Success` and `Error` lists. The error list is in the form: `{Pid, ErrorReason}`. [pmap(F, List)](#pmap/2) Evaluate the `MultiArgs` list by calling `F` on each argument in the list concurrently.*See also:* [pmap/3](#pmap/3). [pmap(F, Args, Timeout)](#pmap/3) Evaluate the `MultiArgs` list by calling `F` on each argument in the list concurrently. Same as pmap/2 but has a `Timeout` option. [reply(_, Reply)](#reply/2) Send a reply back to sender. [Link to this section](#functions) Functions === prof === Profiling functions [Link to this section](#summary) Summary === [Functions](#functions) --- [apply(Fun, Args)](#apply/2) Run a function analysis and save it to `"fprof-apply.analysis"`. [apply(M, F, Args)](#apply/3) Run a function analysis and save it to `"fprof-apply.analysis"`. [start(Pids)](#start/1) Begin profiling a list of pids [stop()](#stop/0) Finish profiling a list of pids and save results to a file called `"fprof.analysis"`. [Link to this section](#functions) Functions === restrict_remsh_mod === Sample restricted remote shell module disabling `c:q/0` and `init:stop/{0,1}` commands. The shell introduces a replacement command to stop remote node: [`remote_node_stop/1`](#remote_node_stop/1) equivalent to [`init:stop/1`](https://www.erlang.org/doc/man/init.html#stop-1). To activate restricted shell, run the server node like this: `erl -sname node@host +Bi -shell restricted_shell restrict_remsh_mod` Then you can connect to it with: `erl -sname a@myhost -remsh node@host` See: <http://www.erlang.org/doc/man/shell.html#start_restricted-1[Link to this section](#summary) Summary === [Types](#types) --- [funspec/0](#t:funspec/0) [Functions](#functions) --- [remote_node_stop(Status)](#remote_node_stop/1) Replaces [`init:stop/1`](https://www.erlang.org/doc/man/init.html#stop-1) with [`remote_node_stop/1`](#remote_node_stop/1) to avoid accidental exit of remote shell. [Link to this section](#types) Types === [Link to this section](#functions) Functions === smerl === Simple Metaprogramming for Erlang [Link to this section](#summary) Summary === [Types](#types) --- [args/0](#t:args/0) [error_t/1](#t:error_t/1) [export/0](#t:export/0) [exports/0](#t:exports/0) A list of `export()`s. [func_form/0](#t:func_form/0) The abstract form for the function, as described in the ERTS Users' manual. [func_forms/0](#t:func_forms/0) A list of `func_form()`s. [meta_mod/0](#t:meta_mod/0) A data structure holding the abstract representation for a module. [ok_t/1](#t:ok_t/1) [result/1](#t:result/1) [result/2](#t:result/2) [Functions](#functions) --- [add_func(MetaMod, Form)](#add_func/2) Equivalent to [add_func(MetaMod, Form, true)](#add_func/3). [add_func(MetaMod, Func, Export)](#add_func/3) Add `Function` to `MetaMod` and return the new `meta_mod()`. If `Export` is `true`, add `Function` to `MetaMod`'s `exports`. [compile(MetaMod)](#compile/1) Equivalent to [compile(MetaMod, [])](#compile/2). [compile(MetaMod, Options)](#compile/2) Equivalent to [compile(MetaMod, [report_errprs, report_warnings, return_errors])](#compile/2). [curry(Form, Args)](#curry/2) Get the curried form for `Form` with `Args`. Here, "currying" involves replacing one or more of the function's leading arguments with predefined values. [curry(Module, Function, Arity, Args)](#curry/4) Curry `Module`:`Function`/`Arity` with the given `Args`. [curry(Module, Function, Arity, Args, NewName)](#curry/5) Curry `Module`:`Function`/`Arity`with the given `Args`, renaming it to `NewName` and return the renamed form. [curry_add(MetaMod, Form, Args)](#curry_add/3) Add `Form` curried with `Args` to `MetaMod`. [curry_add(MetaMod, Function, Arity, Args)](#curry_add/4) Add `Function`/`Arity` curried with `Args` to `MetaMod`. [curry_add(MetaMod, Function, Arity, Args, NewName)](#curry_add/5) Curry `MetaMod`:`Function`/`Arity` and add it to `MetaMod` as `NewName`. [curry_add(MetaMod, Module, Function, Arity, Args, NewName)](#curry_add/6) Curry `Module`:`Function`/`Arity` and add it to `MetaMod` as `NewName`. [curry_replace(MetaMod, Form, Args)](#curry_replace/3) Replace the function represented by `Form` in `MetaMod` with its curried form. [curry_replace(MetaMod, Function, Arity, Args)](#curry_replace/4) Replace `Function`/`Arity` in `MetaMod` with its curried form. [embed_all(MetaMod, Values)](#embed_all/2) Apply [`embed_args/2`](#embed_args/2) with `Values` to all forms in `MetaMod`. `exports` for functions whose arities change are preserved. [embed_args(Form, Vals)](#embed_args/2) Replace the arguments of the function represented by `Form`, where the argument's `Name` matches an element from `Vals` with the corresponding `Value`. [embed_args(MetaMod, Function, Arity, Values)](#embed_args/4) Equivalent to [embed_args(MetaMod, Name, Arity, Values, Name)](#embed_args/5). [embed_args(MetaMod, Function, Arity, Values, NewName)](#embed_args/5) Apply [`embed_args/2`](#embed_args/2) to `MetaMod`:`Function`/`Arity` and add the resulting function to `MetMod`, after renaming it to `NewName`.*See also:* [rename/2](#rename/2). [extend(Parent, Child)](#extend/2) Add aliases for `Parent`'s functions missing from `Child` to `Child`. The new functions in `Child` are shallow, i.e. they have the name and arity of the corresponding functions in `Parent`, but instead of implementing their logic they call the `Parent` functions. [extend(Parent, Child, ArityDiff)](#extend/3) Similar to [`extend/2`](#extend/2), with the addition of `ArityDiff`, which indicates the difference in arities *Smerl* should use when figuring out which functions to generate based on the modules' exports. This is sometimes useful when calling [`extend/3`](#extend/3) followed by [`embed_all/2`](#embed_all/2). [extend(Parent, Child, ArityDiff, Options)](#extend/4) [for_file(SrcFilePath)](#for_file/1) Equivalent to [for_file(SrcFilePath, [])](#for_file/2). [for_file(SrcFilePath, IncludePaths)](#for_file/2) Equivalent to [for_file(SrcFilePath, IncludePaths, [])](#for_file/3). [for_file(SrcFilePath, IncludePaths, Macros)](#for_file/3) Create a meta_mod for a module from its source file. [for_module(ModuleName)](#for_module/1) Equivalent to [for_module(ModuleName, [])](#for_module/2). [for_module(ModuleName, IncludePaths)](#for_module/2) Equivalent to [for_module(ModuleName, IncludePaths, [])](#for_module/3). [for_module(ModuleName, IncludePaths, Macros)](#for_module/3) Create a meta_mod tuple for an existing module. If ModuleName is a string, it is interpreted as a file name (this is the same as calling [`for_file/3`](#for_file/3)). If ModuleName is an atom, *Smerl* attempts to find its abstract represtation either from its source file or from its .beam file directly (if it has been compiled with debug_info). If the abstract representation can't be found, this function returns an error. [get_attribute(MetaMod, Key)](#get_attribute/2) Get the value of `MetaMod`'s `Key` attribute. [get_export_all(MetaMod)](#get_export_all/1) Get the `export_all` value for `MetaMod`. [get_exports(MetaMod)](#get_exports/1) Return the list of exports in the meta_mod. [get_forms(MetaMod)](#get_forms/1) Return the list of function forms in the meta_mod. [get_func(MetaMod, Function, Arity)](#get_func/3) Attempt to get the `func_form()` for `MetaMod`:`Function`/`Arity`. [get_module(MetaMod)](#get_module/1) Return the module name for the meta_mod. [has_func(MetaMod, Function, Arity)](#has_func/3) Check whether `MetaMod` has a function `Function`/`Arity`. [new(Module)](#new/1) Create a new meta_mod for a module with the given name. [remove_export(MetaMod, Function, Arity)](#remove_export/3) Remove an export `{Function, Arity}` from the list of `exports` in `MetaMod`. [remove_func(MetaMod, Function, Arity)](#remove_func/3) Try to remove `Function` from `MetaMod`. If the function exists, return the new `meta_mod()`. Otherwise, return `MetaMod`. [rename(Form, NewName)](#rename/2) Change the name of the function represented by `Form` to `NewName`. [replace_func(MetaMod, Function)](#replace_func/2) Replace an existing function with a new one. If a matching function doesn't exist, add `Function` to `MetaMod`. This is tantamount to calling [`remove_func/3`](#remove_func/3) followed by [`add_func/2`](#add_func/2). [set_export_all(MetaMod, Value)](#set_export_all/2) Set the `export_all` value for `MetaMod`. [set_exports(MetaMod, Exports)](#set_exports/2) Set the `MetaMod`'s export list to `Exports`. [set_forms(MetaMod, Forms)](#set_forms/2) [set_module(MetaMod, NewName)](#set_module/2) Set the meta_mod's module name. [to_src(MetaMod)](#to_src/1) Return the pretty-printed source code for `MetaMod`. [to_src(MetaMod, Filename)](#to_src/2) Equivalent to [file:write_file(Filename, to_src(MetaMod))](https://www.erlang.org/doc/man/file.html#write_file-2). [Link to this section](#types) Types === [Link to this section](#functions) Functions === smtp === SMTP mail client. This module can sent emails to one or more recipients, using primary/backup SMTP servers. Messages can contain attachments. ``` Example: % Send a message to two recipients with a file attachment using % SSL protocol at mail server "mail.bevemyr.com": smtp:send(ssl, "Alex <<EMAIL>>", ["<EMAIL>","<EMAIL>"], "Test Subject", "My Message", [{server, "mail.bevemyr.com"}, {username, "alex"}, {password, "secret"}, {attachments, ["file1.txt"]}]). % Send a message to a recipient with a file attachment given custom % MIME type using localhost mail server smtp:send(tcp, "<EMAIL>", ["<EMAIL>"], "Test Subject", "My Message", [{server, "mail.bevemyr.com"}, {username, "alex"}, {password, "secret"}, {attachments, [{"file1.bin","application/custom_MIME"}]}]). % Send a message to two recipients with an attachment given as list smtp:send(tcp, "<EMAIL>", ["<EMAIL>","<EMAIL>"], "Test Subject", "My Message", [{"file1.txt","text/plain","Attachment past as list"}]). ``` [Link to this section](#summary) Summary === [Types](#types) --- [proto/0](#t:proto/0) Protocol type. [smtp_options/0](#t:smtp_options/0) SNMP Options* Server - server to connect to (no MX lookup) * Relay - domain to do MX lookup of list of servers * Port - optional port number (ssl def: 465; tcp def: 25) * Auth - controls mandatory / optional authentication * Tls - controls enabling of TLS protocol * Domain - name of the domain to include in the HELO handshake * Timeout - timeout to use (default 10000) * Verbose - controls debugging printout * Attachments - list of files to attach * SSLOpts - additional SSL options if using SSL protocol [Functions](#functions) --- [domain()](#domain/0) Get domain that this host belongs to. [send(Proto, From, To, Subj, Msg)](#send/5) Send a message to a list of `To` receipients using `localhost`. Error is thrown if unable to send a message. Use inet:format_error/1 to decode the Reason if it is an atom. [send(Proto, From, To, Subj, Msg, Opts)](#send/6) Send a message to a list of recipients by connecting to an SMTP server Server. The message can contain attachments in the Attachments list. See examples on the top of this page. Error is thrown if unable to send a message. [Link to this section](#types) Types === [Link to this section](#functions) Functions === sntp === Implements SNTP query logic. SNTP - Simple Network Time Protocol (RFC-2030). [Link to this section](#summary) Summary === [Functions](#functions) --- [avg_time()](#avg_time/0) Query NTP time sources from `"/etc/ntp.conf"` and return min/max/avg offset of current host from given time sources.*See also:* [avg_time/1](#avg_time/1). [avg_time(ServerAddresses)](#avg_time/1) Query `ServerAddress` NTP time sources and return min/max/avg offset of current host from given time sources. [time(ServerAddress)](#time/1) Query `ServerAddress` time source to find out server time and current host's offset from time source. [time_servers()](#time_servers/0) Return a list of default NTP time servers for this host. [time_servers(Resolve)](#time_servers/1) Return a list of default NTP time servers for this host. If `Resolve` is true, the list will contain IP addresses or else host names. [Link to this section](#functions) Functions === ssh_sign === [Link to this section](#summary) Summary === [Functions](#functions) --- [public_identity_key(Alg, Opts)](#public_identity_key/2) [sign(Data)](#sign/1) [verify(Data, Sig)](#verify/2) [Link to this section](#functions) Functions === ssh_tunnel === [Link to this section](#summary) Summary === [Types](#types) --- [location/0](#t:location/0) [Functions](#functions) --- [connect()](#connect/0) Module for creating SSH tunnels using `ssh`. <https://github.com/drowzy/ssh_tunnel[connect(Host, Port, Opts)](#connect/3) Create a connetion to a remote host with the provided options. This function is mostly used as convenience wrapper around [`ssh:connect/3`](https://www.erlang.org/doc/man/ssh.html#connect-3) and does not support all options. returns: `{ok, Connection}` or `{error, Reason}`. <https://manpages.debian.org/stretch/erlang-manpages/ssh.3erl.en.html[direct_stream_local(Pid, SocketPath)](#direct_stream_local/2) Creates a ssh stream local-forward channel to a remote unix domain socket. It sends the request that the server make a connection to its local Unix domain socket. The returned channel together with a ssh connection reference (returned from [`ssh:connect/4`](https://www.erlang.org/doc/man/ssh.html#connect-4)) can be used to send messages with [`ssh_connection:send/3`](https://www.erlang.org/doc/man/ssh_connection.html#send-3). returns: `{ok, Channel}` or `{error, Reason}`. Ex: ``` msg = "GET /images/json HTTP/1.1\r\nHost: /var/run/docker.sock\r\nAccept: */*\r\n\r\n" {ok, Pid} = ssh_tunnel:connect("192.168.90.15", 22), {ok, Ch} = ssh_tunnel:direct_stream_local(Pid, "/var/run/docker.sock"), ok = ssh_connection:send(Pid, Ch, Msg) ``` [direct_tcpip(Pid, From, To)](#direct_tcpip/3) Creates a ssh directtcp-ip forwarded channel to a remote port. The returned channel together with a ssh connection reference (returned from [`ssh:connect/4`](https://www.erlang.org/doc/man/ssh.html#connect-4)) can be used to send messages with [`ssh_connection:send/3`](https://www.erlang.org/doc/man/ssh_connection.html#send-3) returns: `{ok, channel}` or `{error, reason}`. ## Examples: msg = "GET / HTTP/1.1\r\nHost: localhost:8080\r\nUser-Agent: curl/7.47.0\r\nAccept: */*\r\n\r\n" {ok, Pid} = ssh_tunnel:connect("192.168.1.10", 22), {ok, Ch} = ssh_tunnel:direct_tcpip(Pid, {"127.0.0.1", 8080}, {"192.168.1.10", 80}), ok = ssh_connection:send(Pid, Ch, Msg), recieve do {ssh_cm, _, {data, Channel, _, Data}} -> io:format("Data: ~p\n", [Data]) end [open_channel(Pid, Type, Msg, WindowSize, MaxPktSz, Timeout)](#open_channel/6) [start_tunnel(Pid, Transport, To)](#start_tunnel/3) Starts a SSHTunnel.Tunnel process. The tunnel will listen to either a local port or local path and handle passing messages between the TCP client and ssh connection. ## Examples {ok, SSH} = ssh_tunnel:connect("sshserver.example.com", 22), {ok, Pid} = ssh_tunnel:start_tunnel(Pid, tcp, {8080, {"192.168.90.15", 80}}) # Send a TCP message %HTTPoison.Response{body: body} = HTTPoison.get!("127.0.0.1:8080") IO.puts("Received body: #{body}) [Link to this section](#types) Types === [Link to this section](#functions) Functions === stringx === Implements miscelaneous string functions [Link to this section](#summary) Summary === [Types](#types) --- [ccy_sym/0](#t:ccy_sym/0) [decimals/0](#t:decimals/0) see types for erlang:float_to_binary/2 [format_number_opts/0](#t:format_number_opts/0) [formatted_number/0](#t:formatted_number/0) [precision/0](#t:precision/0) [pretty_print_opts/0](#t:pretty_print_opts/0) [Functions](#functions) --- [align_rows(Rows)](#align_rows/1) [align_rows(Rows, Options)](#align_rows/2) Align rows of terms by stringifying them to uniform column width. If some row doesn't need to be aligned, pass its value as a binary. `Options` can be [aligned_format(Fmt, Rows)](#aligned_format/2) [aligned_format(Fmt, Rows, Directions)](#aligned_format/3) [batch_split(N, L)](#batch_split/2) Split a list into batches of N items [binary_join(Tail, Sep)](#binary_join/2) [format(Fmt, Args)](#format/2) Convert format and arguments to binary/list shortening . This function can be used by Elixir, which is missing the equivalent of `io_lib.format/2` [format_binary(Fmt, Args)](#format_binary/2) Convert format and arguments to binary/list shortening . This function can be used by Elixir, which is missing the equivalent of `io_lib.format/2` [format_integer(Integer)](#format_integer/1) [format_integer(Integer, Opts)](#format_integer/2) [format_number(N, Precision, Decimals)](#format_number/3) The same as uef_format:format_number/4 with #{} as the forth argument.*See also:* [format_number/4](#format_number/4). [format_number(Number, Precision, Decimals, Opts)](#format_number/4) Formats Number by adding thousands separator between each set of 3 digits to the left of the decimal point, substituting Decimals for the decimal point, and rounding to the specified Precision. Returns a binary value. [format_price(Number)](#format_price/1) Formats Number in price-like style. Returns a binary containing FormattedPrice formatted with a precision of 2 and decimal digits of 2. The same as format_price/2 with a precision of 2 as the second argument. See uef_format:format_price/2 docs. [format_price(Number, Precision)](#format_price/2) Formats Number in price-like style. Returns a binary containing FormattedPrice formatted with a specified precision as the second argument and decimal digits of 2. The same as uef_format:format_price/3 with #{} as the third argument.*See also:* [format_price/3](#format_price/3). [format_price(Number, Precision, CcySymbol_OR_Options)](#format_price/3) Formats Number in price-like style. Returns a binary containing FormattedPrice formatted with a specified precision as the second argument, decimal digits of 2, and with ccy symbol (or options) as the third argument. If CcySymbol_OR_Options is a map the functions works as format_number/4 with decimal digits of 2 as the third argument and with options as the forth one. If CcySymbol_OR_Options is a binary or a string, the corresponding ccy symbol is added to the left. [parse_csv(File)](#parse_csv/1) Parse a given CSV file. [parse_csv(File, Opts)](#parse_csv/2) Parse a given CSV file. [pretty_print_table(LofMaps0)](#pretty_print_table/1) Pretty print table of lists/tuples/maps to list. The following options control formatting behavior:number_padLeading padding character used for numbersth_dirTable header row padding direction (both|leading|trailing)td_dirTable row padding direction (both|leading|trailing)td_startDon't print columns less than this (e.g. use 2 for records)td_excluldeList of column ID's (starting with 1) or names to excludetd_padA map containing column padding directions `#{Col::integer() => both|leading|trailing`.td_sepColumn separator (default `" | "`)tr_sepRow separator (default `"-"`)tr_sep_tdColumn delimiter used in separating rows (`"+"`)prefixPrepend each row with this stringtd_formatsA tuple containing column formats. Each value is either a format string passed to [`io_lib:format/2`](https://www.erlang.org/doc/man/io_lib.html#format-2) or a function taking either one argument `fun(Value) -> {number|string, FormattedValue::string()}` or three arguments `fun(Key,Value,Row::tuple()|map()) -> {number|string, FormattedValue::string()}`. This three argument function can perform calculation of the field value based on values of other fields in the `Row`.unicodeUse unicode outline charactersoutlineDraw top, left and line box outline (by default only the bottom one is drawn). Values:* `none` - on outline box * `full` - outline box on all 4 sides * `[top, left, bottom, right]` - outline box on given sides Example: ``` 1> stringx:pretty_print_table( {a,b,c,d}, [{a, 10, ccc}, {bxxx, 200.00123, 'Done'}, {abc, 100.0, xx}], #opts{td_dir=both, td_exclude=[d], td_formats= {undefined, fun(V) when is_integer(V) -> {number, integer_to_list(V)}; (V) when is_float(V) -> {number, float_to_list(V, [{decimals, 5}])} end, "~w"}}). a | b | c ---+---+--- a | 10 | ccc bxxx | 200.00123 | 'Done' ---+---+--- ``` [pretty_print_table(HeaderRowKeys, Rows)](#pretty_print_table/2) [pretty_print_table(HeaderRowKeys, Rows, Opts)](#pretty_print_table/3) [pretty_table(LofMaps0)](#pretty_table/1) Pretty print list of maps to list.*See also:* [pretty_table/3](#pretty_table/3). [pretty_table(HeaderRowKeys, Rows)](#pretty_table/2) Pretty print table of lists/tuples/maps to list.*See also:* [pretty_table/3](#pretty_table/3). [pretty_table(HeaderRowKeys, Rows, Opts)](#pretty_table/3) [round_number(Number, Precision)](#round_number/2) Rounds the number to the specified precision. [round_price(Number)](#round_price/1) Rounds the number to the precision of 2. [titlecase(S)](#titlecase/1) Convert words in a string to capitalize first letter of each word. [wordwrap(S, Margin)](#wordwrap/2) Wrap words words in a string [wordwrap(Words, Margin, Word)](#wordwrap/3) Wrap words words in a string to multiple lines that fit the margin Example: `1> stringx:wordwrap(["abc", "efg", "exdf"], 8, ","). ["abc,efg,","exdf"]` [Link to this section](#types) Types === [Link to this section](#functions) Functions === sup_bridge behaviour === [Link to this section](#summary) Summary === [Functions](#functions) --- [behaviour_info(Other)](#behaviour_info/1) [code_change(OldVsn, State, Extra)](#code_change/3) [get_child_pid(Name)](#get_child_pid/1) [handle_call(Req, From, State)](#handle_call/3) [handle_cast(Req, State)](#handle_cast/2) [handle_info(Req, State)](#handle_info/2) [init(_)](#init/1) [start_link(Mod, StartArgs)](#start_link/2) [start_link(Name, Mod, StartArgs)](#start_link/3) [terminate(Reason, State)](#terminate/2) [Link to this section](#functions) Functions === throttle === Throttle given rate over a number of seconds. Implementation uses time spacing reservation algorithm where each allocation of samples reserves a fraction of space in the throttling window. The reservation gets freed as the time goes by. No more than the `Rate` number of samples are allowed to fit in the milliseconds `Window`. This is an Erlang implementation of the throttling algorithm from the utxx library found at this URL: <https://github.com/saleyn/utxx/blob/master/include/utxx/rate_throttler.hpp[Link to this section](#summary) Summary === [Types](#types) --- [throttle/0](#t:throttle/0) [throttle_opts/0](#t:throttle_opts/0) `retries` - number of retries. `retry_delay` - delay in milliseconds between successive retries. `blocking` - instructs to block the call if throttled. [throttle_result/0](#t:throttle_result/0) [time/0](#t:time/0) [Functions](#functions) --- [add(T)](#add/1) Add one sample to the throttle [add(T, Samples)](#add/2) Add `Samples` to the throttle [add(Throttle, Samples, Now)](#add/3) Add `Samples` to the throtlle. Return `{FitSamples, State}`, where `FitSamples` are the number of samples that fit in the throttling window. 0 means that the throttler is fully congested, and more time needs to elapse before the throttles gets reset to accept more samples. [available(T)](#available/1) *See also:* [available/2](#available/2). [available(Throttle, Now)](#available/2) Return the number of available samples given `Now` current time. [call(T, F)](#call/2) Call the lambda `F`, ensuring that it's not called more frequently than the throttle would allow. [call(Throttle, F, Opts)](#call/3) Call the lambda `F`, ensuring that it's not called more often then the throttle would allow. `Opts` are a map of options. When `{retries, R}` option is given and `R` is greater than 0, the throttler will call the function `F()` up to `R` times if the `F()` raises an exception. The delay between retries is controlled by the `{retry_delay, D}` options, expressed in milliseconds (default: `1`) between successive executions of `F()`. If `F()` still raises an exception after the R's retry, that exception would be reraised and it would be the responsibility of the caller to handle it. [call(T, M, F, A)](#call/4) Call M,F,A, ensuring that it's not called more frequently than the throttle would allow. [call(T, M, F, A, Now)](#call/5) Call M,F,A, ensuring that it's not called more frequently than the throttle would allow. [curr_rps(T)](#curr_rps/1) *See also:* [curr_rps/2](#curr_rps/2). [curr_rps(Throttle, Now)](#curr_rps/2) Return currently used rate per second. [new(Rate)](#new/1) Create a new throttle given the `Rate` per second. [new(Rate, Window)](#new/2) *See also:* [new/3](#new/3). [new(Rate, Window, Now)](#new/3) Create a new throttle given the `Rate` per `Window` milliseconds. `Now` is expressesed in microseconds since epoch using [`now/0`](#now/0). [next_timeout(T)](#next_timeout/1) Return the number of milliseconds to wait until the throttling threshold is satisfied to fit another sample. [now()](#now/0) [reset(Throttle)](#reset/1) *See also:* [reset/2](#reset/2). [reset(Throttle, Now)](#reset/2) Reset the throttle request counter [used(T)](#used/1) *See also:* [used/2](#used/2). [used(Throttle, Now)](#used/2) Return the number of used samples given `a_now` current time. [Link to this section](#types) Types === [Link to this section](#functions) Functions === trunc_io === Module to print out terms for logging. Limits by length rather than depth. The resulting string may be slightly larger than the limit; the intention is to provide predictable CPU and memory consumption for formatting terms, not produce precise string lengths. Typical use: trunc_io:print(Term, 500). Source license: Erlang Public License. Original author: <NAME>, `<EMAIL>` [Link to this section](#summary) Summary === [Functions](#functions) --- [fprint(T, Max)](#fprint/2) Returns an flattened list containing the ASCII representation of the given term. [perf1()](#perf1/0) [perf()](#perf/0) [perf(M, F, Reps)](#perf/3) [print(Tuple, Max)](#print/2) Returns {List, Length} [safe(What, Len)](#safe/2) Same as print, but never crashes. [test()](#test/0) [test(Mod, Func)](#test/2) [Link to this section](#functions) Functions === ttl_map === Map with TTL key/value eviction. An insert of a Key/Value pair in the map will store the timestamp of the maybe_add. Additionally a queue of maybe_adds is maintained by this container, which is checked on each insert and the expired Key/Value pairs are evicted from the map. [Link to this section](#summary) Summary === [Types](#types) --- [ttl_map/0](#t:ttl_map/0) [Functions](#functions) --- [evict(TTLMap, Now)](#evict/2) Evict stale items from the map given the current timestamp `Now`. [evict(TTLMap, Now, Limit)](#evict/3) Evict stale items (up to the `Limit`) from the map given the current timestamp `Now`. [new(TTL)](#new/1) Create a new map with a given TTL time for inserted items [new(TTL, Opts)](#new/2) Create a new map with a given TTL time for inserted items. `Opts` is a list of options:nameThe name of the ETS table (defaults to `undefined`)accessThe access level of the ETS table (defaults to `private`) [now()](#now/0) Get the current timestamp in microseconds since Unix epoch. [size(Ttl_map)](#size/1) Get the number of items in the map. [try_add(TTLMap, Key, Value, Now)](#try_add/4) Try to add a `Key/Value` pair to the map. If more than TTL time elapsed since the last insert of the `Key` or the `Key` is not found in the map, the value is inserted, otherwise no insertion is made. [Link to this section](#types) Types === [Link to this section](#functions) Functions === user_default === This is an extension of the shell commands to do all the work! Either place this file in the path accessible to Erlang (via ERL_LIBS) or add this line to the ~/.erlang file: `code:load_abs(os:getenv("HOME") ++ "/.erlang/user_default").` [Link to this section](#summary) Summary === [Functions](#functions) --- [dbgadd(Module)](#dbgadd/1) [dbgadd(Module, Fun)](#dbgadd/2) [dbgdel(Module)](#dbgdel/1) [dbgdel(Module, Fun)](#dbgdel/2) [dbgoff()](#dbgoff/0) [dbgon(Modules)](#dbgon/1) [dbgon(Module, Fun)](#dbgon/2) [dbgtc(File)](#dbgtc/1) [debug()](#debug/0) [help()](#help/0) [nl()](#nl/0) Load all changed modules on all visible nodes [p(Term)](#p/1) Term printer [saveh(File)](#saveh/1) Save command history to file [tc(N, F)](#tc/2) [tc(N, M, F, A)](#tc/4) [Link to this section](#functions) Functions === util_log_color_formatter === Implementation of coloring handler for the Erlang's logger. See <https://github.com/hauleth/logger_colorful>. ### [options](#module-options) Options * `formatter` - parent formatter which will be used for message formatting * `colors` - map of `logger:log_level()` and colors in form atom describing color name, or 2-ary or 3-ary tuple with 1 or 2 modifiers for the color Available colors: * `black` * `red` * `green` * `yellow` * `blue` * `magenta` * `cyan` * `white` Available modifiers: * `fg` - set foreground color * `bg` - set background color * `bright` - use bright color [Link to this section](#summary) Summary === [Functions](#functions) --- [check_config(Config0)](#check_config/1) [format(Event, Config0)](#format/2) [Link to this section](#functions) Functions === util_log_formatter === Log formatter Derived from //kernel/logger/logger_formatter This implementation is copied from logger_fomatter.erl and adds the following features:time_offset = nonewhen provided, no time zone offset will be written to the log.time_unit = second | millisecond | microsecondcontrols time stamp granularity in the log.report_prefix = string()inserts given prefix before `msg` for logging a report (default: "\n").report_term_depth = integer()max depth of terms included in the reports. Use `infinity` for unlimited (default: 50)Report printing is modified to align keys in a report to the right. Additional template formatting atoms:levprints "[X]" to the log to indicate the log level, where `X` is the first capitalized letter of the log level.</dd> <dt>LEVEL</dt><dd>same as`level' but is printed in upper case.modlineprints 'Module:Line' to the log.regpidprints:`*`if the registered name of the caller's pid matches caller's module name.`RegisteredName`of the calling process`X.Y.Z`pid of the caller with leading `0.` stripped.regnameprints `<RegisteredName>` of the process or its pid if the process is not registered [Link to this section](#summary) Summary === [Types](#types) --- [config/0](#t:config/0) [metakey/0](#t:metakey/0) [template/0](#t:template/0) [Functions](#functions) --- [check_config(Config)](#check_config/1) [format(LogEvent, Config)](#format/2) [Link to this section](#types) Types === [Link to this section](#functions) Functions === xmltree === Parse XML into a hierarchical Erlang term ``` % Example xml: <?xml version="1.0" encoding="UTF-8" ?> <root id="1"> <ele id="2"/> <ele id="3">vvv\nxxx\n</ele> </root # Usage example 1> xmltree:file(L). {root,[{id,<<"1">>}], [{ele,[{id,<<"2">>}],[]}, {ele,[{id,<<"3">>}],<<"vvv\nxxx\n">>}]} 2> Rules = {root, [{id,integer}], [{ele, [{id,integer}], string}]}, 2> xmltree:string(L, Rules). {root,[{id,1}], [{ele,[{id,2}],[]},{ele,[{id,3}],"vvv\nxxx\n"}]} ``` [Link to this section](#summary) Summary === [Functions](#functions) --- [file(Filename)](#file/1) [file(Filename, RulesFile)](#file/2) [string(XmlS)](#string/1) [string(XmlS, Rules)](#string/2) [xml(XmlElement)](#xml/1) [xml(XmlElement, ChildRules)](#xml/2) [Link to this section](#functions) Functions === xref_test === [Link to this section](#summary) Summary === [Functions](#functions) --- [run()](#run/0) [run(Dirs)](#run/1) [run(Dirs, AddAnalysis)](#run/2) [run_shell()](#run_shell/0) [Link to this section](#functions) Functions ===
telegram
cran
R
Package ‘telegram.bot’ October 14, 2022 Type Package Title Develop a 'Telegram Bot' with R Version 3.0.0 Description Provides a pure interface for the 'Telegram Bot API' <http://core.telegram.org/bots/api>. In addition to the pure API implementation, it features a number of tools to make the development of 'Telegram' bots with R easy and straightforward, providing an easy-to-use interface that takes some work off the programmer. URL https://github.com/ebeneditos/telegram.bot BugReports https://github.com/ebeneditos/telegram.bot/issues Depends R (>= 3.1.0) Imports curl, httpuv, httr, jsonlite, openssl, R6 Suggests covr, devtools, knitr, promises, rmarkdown, testthat License GPL-3 Encoding UTF-8 RoxygenNote 7.2.1 VignetteBuilder knitr NeedsCompilation no Author <NAME> [aut, cre], <NAME> [ctb] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2022-09-07 15:40:02 UTC R topics documented: +.TelegramObjec... 3 add_error_handle... 4 add_handle... 5 answerCallbackQuer... 6 answerInlineQuer... 6 BaseFilte... 8 Bo... 9 bot_toke... 11 CallbackQueryHandle... 11 check_updat... 12 clean_update... 12 CommandHandle... 13 deleteMessag... 14 deleteWebhoo... 14 Dispatche... 15 editMessageCaptio... 15 editMessageReplyMarku... 16 editMessageTex... 17 effective_cha... 18 effective_messag... 18 effective_use... 19 ErrorHandle... 19 filtersLogi... 20 ForceRepl... 20 forwardMessag... 21 from_chat_i... 22 from_user_i... 22 getFil... 22 getM... 23 getUpdate... 23 getUserProfilePhoto... 24 getWebhookInf... 25 Handle... 26 handle_updat... 27 InlineKeyboardButto... 28 InlineKeyboardMarku... 29 InlineQueryResul... 30 KeyboardButto... 31 leaveCha... 31 MessageFilter... 32 MessageHandle... 33 ReplyKeyboardMarku... 33 ReplyKeyboardRemov... 35 runnin... 36 sendAnimatio... 36 sendAudi... 38 sendChatActio... 39 sendDocumen... 40 sendLocatio... 41 sendMessag... 43 sendPhot... 44 sendSticke... 45 sendVide... 46 sendVideoNot... 48 sendVoic... 49 setWebhoo... 51 set_toke... 52 start_pollin... 52 start_serve... 53 stop_pollin... 54 stop_serve... 55 TelegramObjec... 55 Updat... 56 Update... 57 user_i... 59 Webhoo... 59 +.TelegramObject Constructing an Updater Description With + you can add any kind of Handler to an Updater’s Dispatcher (or directly to a Dispatcher). Usage ## S3 method for class 'TelegramObject' e1 + e2 Arguments e1 An object of class Updater or Dispatcher. e2 An object of class Handler. Details See add_handler for further information. Examples ## Not run: # You can chain multiple handlers start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } echo <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = update$message$text ) } updater <- Updater("TOKEN") + CommandHandler("start", start) + MessageHandler(echo, MessageFilters$text) # And keep adding... caps <- function(bot, update, args) { if (length(args > 0L)) { text_caps <- toupper(paste(args, collapse = " ")) bot$sendMessage( chat_id = update$message$chat_id, text = text_caps ) } } updater <- updater + CommandHandler("caps", caps, pass_args = TRUE) # Give it a try! updater$start_polling() # Send '/start' to the bot, '/caps foo' or just a simple text ## End(Not run) add_error_handler Add an error handler Description Registers an error handler in the Dispatcher. Usage add_error_handler(callback) Arguments callback A function that takes (bot, error) as arguments. Details You can also use add_handler to register error handlers if the handler is of type ErrorHandler. Examples ## Not run: updater <- Updater(token = "TOKEN") # Create error callback error_callback <- function(bot, error) { warning(simpleWarning(conditionMessage(error), call = "Updates polling")) } # Register it to the updater's dispatcher updater$dispatcher$add_error_handler(error_callback) # or updater$dispatcher$add_handler(ErrorHandler(error_callback)) # or updater <- updater + ErrorHandler(error_callback) ## End(Not run) add_handler Add a handler Description Register a handler. A handler must be an instance of a subclass of Handler. All handlers are organized in groups with a numeric value. The default group is 1. All groups will be evaluated for handling an update, but only 0 or 1 handler per group will be used. Usage add_handler(handler, group = 1L) Arguments handler A Handler instance. group The group identifier, must be higher or equal to 1. Default is 1. Details You can use the add (+) operator instead. The priority/order of handlers is determined as follows: 1. Priority of the group (lower group number = higher priority) 2. The first handler in a group which should handle an update will be used. Other handlers from the group will not be used. The order in which handlers were added to the group defines the priority (the first handler added in a group has the highest priority). answerCallbackQuery Send answers to callback queries Description Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, TRUE is returned. Usage answerCallbackQuery( callback_query_id, text = NULL, show_alert = FALSE, url = NULL, cache_time = NULL ) Arguments callback_query_id Unique identifier for the query to be answered. text (Optional). Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters. show_alert (Optional). If TRUE, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to FALSE. url (Optional). URL that will be opened by the user’s client. cache_time (Optional). The maximum amount of time in seconds that the result of the call- back query may be cached client-side. Telegram apps will support caching start- ing in version 3.14. Defaults to 0. Details You can also use it’s snake_case equivalent answer_callback_query. answerInlineQuery Send answers to an inline query Description Use this method to send answers to an inline query. No more than 50 results per query are allowed. Usage answerInlineQuery( inline_query_id, results, cache_time = 300L, is_personal = NULL, next_offset = NULL, switch_pm_text = NULL, switch_pm_parameter = NULL ) Arguments inline_query_id Unique identifier for the answered query. results A list of InlineQueryResult for the inline query. cache_time (Optional). The maximum amount of time in seconds that the result of the inline query may be cached on the server. is_personal (Optional). Pass TRUE, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query. next_offset (Optional). Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don’t support pagination. Offset length can’t exceed 64 bytes. switch_pm_text (Optional). If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter. switch_pm_parameter (Optional). Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed. Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a ’Connect your YouTube account’ button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an auth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot’s inline capabilities. Details To enable this option, send the /setinline command to @BotFather and provide the placeholder text that the user will see in the input field after typing your bot’s name. You can also use it’s snake_case equivalent answer_inline_query. BaseFilter The base of all filters Description Base class for all Message Filters. Usage BaseFilter(filter) as.BaseFilter(x, ...) is.BaseFilter(x) Arguments filter If you want to create your own filters you can call this generator passing by a filter function that takes a message as input and returns a boolean: TRUE if the message should be handled, FALSE otherwise. x Object to be coerced or tested. ... Further arguments passed to or from other methods. Details See filtersLogic to know more about combining filter functions. Examples ## Not run: # Create a filter function text_or_command <- function(message) !is.null(message$text) # Make it an instance of BaseFilter with its generator: text_or_command <- BaseFilter(filter = text_or_command) # Or by coercing it with as.BaseFilter: text_or_command <- as.BaseFilter(function(message) !is.null(message$text)) ## End(Not run) Bot Creating a Bot Description This object represents a Telegram Bot. Usage Bot(token, base_url = NULL, base_file_url = NULL, request_config = NULL) is.Bot(x) Arguments token The bot’s token given by the BotFather. base_url (Optional). Telegram Bot API service URL. base_file_url (Optional). Telegram Bot API file URL. request_config (Optional). Additional configuration settings to be passed to the bot’s POST requests. See the config parameter from ?httr::POST for further details. The request_config settings are very useful for the advanced users who would like to control the default timeouts and/or control the proxy used for HTTP com- munication. x Object to be tested. Format An R6Class object. Details To take full advantage of this library take a look at Updater. You can also use its methods snake_case equivalent. API Methods answerCallbackQuery Send answers to callback queries answerInlineQuery Send answers to an inline query deleteMessage Delete a message deleteWebhook Remove webhook integration editMessageText Edit a text message editMessageCaption Edit a caption editMessageReplyMarkup Edit the reply markup of a message forwardMessage Forward messages of any kind getFile Prepare a file for downloading getMe Check your bot’s information getUpdates Receive incoming updates getUserProfilePhotos Get a user’s profile photos getWebhookInfo Get current webhook status leaveChat Leave a chat sendAnimation Send animation files sendAudio Send audio files sendChatAction Send a chat action sendDocument Send general files sendLocation Send point on the map sendMessage Send text messages sendPhoto Send image files sendSticker Send a sticker sendVideo Send a video sendVideoNote Send video messages sendVoice Send voice files setWebhook Set a webhook Other Methods clean_updates Clean any pending updates set_token Change your bot’s auth token Examples ## Not run: bot <- Bot(token = "TOKEN") # In case you want to set a proxy (see ?httr:use_proxy) bot <- Bot( token = "TOKEN", request_config = httr::use_proxy(...) ) ## End(Not run) bot_token Get a token from environment Description Obtain token from system variables (in .Renviron) set according to the naming convention R_TELEGRAM_BOT_X where X is the bot’s name. Usage bot_token(bot_name) Arguments bot_name The bot’s name. Examples ## Not run: # Open the `.Renviron` file file.edit(path.expand(file.path("~", ".Renviron"))) # Add the line (uncomment and replace <bot-token> by your bot TOKEN): # R_TELEGRAM_BOT_RTelegramBot=<bot-token> # Save and restart R bot_token("RTelegramBot") ## End(Not run) CallbackQueryHandler Handling callback queries Description Handler class to handle Telegram callback queries. Optionally based on a regex. Usage CallbackQueryHandler(callback, pattern = NULL) Arguments callback The callback function for this handler. See Handler for information about this function. pattern (Optional). Regex pattern to test. Format An R6Class object. check_update Check an update Description This method is called to determine if an update should be handled by this handler instance. It should always be overridden (see Handler). Usage check_update(update) Arguments update The update to be tested. clean_updates Clean any pending updates Description Use this method to clean any pending updates on Telegram servers. Requires no parameters. Usage clean_updates() CommandHandler Handling commands Description Handler class to handle Telegram commands. Usage CommandHandler( command, callback, filters = NULL, pass_args = FALSE, username = NULL ) Arguments command The command or vector of commands this handler should listen for. callback The callback function for this handler. See Handler for information about this function. filters (Optional). Only allow updates with these filters. See MessageFilters for a full list of all available filters. pass_args (Optional). Determines whether the handler should be passed args, received as a vector, split on spaces. username (Optional). Bot’s username, you can retrieve it from bot$getMe()$username. If this parameter is passed, then the CommandHandler will also listen to the command /command@username, as bot commands are often called this way. Format An R6Class object. Examples ## Not run: # Initialize bot bot <- Bot("TOKEN") username <- bot$getMe()$username updater <- Updater(bot = bot) # Add a command start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = "Hi, I am a bot!" ) } updater <- updater + CommandHandler("start", start, username = username) ## End(Not run) deleteMessage Delete a message Description Use this method to delete a message. A message can only be deleted if it was sent less than 48 hours ago. Any such recently sent outgoing message may be deleted. Additionally, if the bot is an administrator in a group chat, it can delete any message. If the bot is an administrator in a supergroup, it can delete messages from any other user and service messages about people joining or leaving the group (other types of service messages may only be removed by the group creator). In channels, bots can only remove their own messages. Usage deleteMessage(chat_id, message_id) Arguments chat_id Unique identifier for the target chat or username of the target channel. message_id Identifier of the message to delete. Details You can also use it’s snake_case equivalent delete_message. deleteWebhook Remove webhook integration Description Use this method to remove webhook integration if you decide to switch back to getUpdates. Re- quires no parameters. Usage deleteWebhook() Details You can also use it’s snake_case equivalent delete_webhook. Dispatcher The dispatcher of all updates Description This class dispatches all kinds of updates to its registered handlers. Usage Dispatcher(bot) is.Dispatcher(x) Arguments bot The bot object that should be passed to the handlers. x Object to be tested. Format An R6Class object. Methods add_handler Registers a handler in the Dispatcher. add_error_handler Registers an error handler in the Dispatcher. editMessageCaption Edit a caption Description Use this method to edit captions of messages. Usage editMessageCaption( chat_id = NULL, message_id = NULL, inline_message_id = NULL, caption = NULL, parse_mode = NULL, reply_markup = NULL ) Arguments chat_id (Optional). Unique identifier for the target chat or username of the target chan- nel. message_id (Optional). Required if inline_message_id is not specified. Identifier of the sent message. inline_message_id (Optional). Required if chat_id and message_id are not specified. Identifier of the inline message. caption (Optional). New caption of the message. parse_mode (Optional). Send ’Markdown’ or ’HTML’, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot’s message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply Details You can also use it’s snake_case equivalent edit_message_caption. editMessageReplyMarkup Edit a reply markup Description Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). Usage editMessageReplyMarkup( chat_id = NULL, message_id = NULL, inline_message_id = NULL, reply_markup = NULL ) Arguments chat_id (Optional). Unique identifier for the target chat or username of the target chan- nel. message_id (Optional). Required if inline_message_id is not specified. Identifier of the sent message. inline_message_id (Optional). Required if chat_id and message_id are not specified. Identifier of the inline message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply Details You can also use it’s snake_case equivalent edit_message_reply_markup. editMessageText Edit a text message Description Use this method to edit text messages. Usage editMessageText( chat_id = NULL, message_id = NULL, inline_message_id = NULL, text, parse_mode = NULL, disable_web_page_preview = NULL, reply_markup = NULL ) Arguments chat_id (Optional). Unique identifier for the target chat or username of the target chan- nel. message_id (Optional). Required if inline_message_id is not specified. Identifier of the sent message. inline_message_id (Optional). Required if chat_id and message_id are not specified. Identifier of the inline message. text New text of the message. parse_mode (Optional). Send ’Markdown’ or ’HTML’, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot’s message. disable_web_page_preview (Optional). Disables link previews for links in this message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply Details You can also use it’s snake_case equivalent edit_message_text. effective_chat Get the effective chat Description The chat that this update was sent in, no matter what kind of update this is. Will be None for inline_query, chosen_inline_result, callback_query from inline messages, shipping_query and pre_checkout_query. Usage effective_chat() effective_message Get the effective message Description The message included in this update, no matter what kind of update this is. Will be None for inline_query, chosen_inline_result, callback_query from inline messages, shipping_query and pre_checkout_query. Usage effective_message() effective_user Get the effective user Description The user that sent this update, no matter what kind of update this is. Will be NULL for channel_post. Usage effective_user() ErrorHandler Handling errors Description Handler class to handle errors in the Dispatcher. Usage ErrorHandler(callback) is.ErrorHandler(x) Arguments callback A function that takes (bot, error) as arguments. x Object to be tested. Format An R6Class object. Examples ## Not run: updater <- Updater(token = "TOKEN") # Create error callback error_callback <- function(bot, error) { warning(simpleWarning(conditionMessage(error), call = "Updates polling")) } # Register it to the updater's dispatcher updater$dispatcher$add_handler(ErrorHandler(error_callback)) # or updater <- updater + ErrorHandler(error_callback) ## End(Not run) filtersLogic Combining filters Description Creates a function which returns the corresponding logical operation between what f and g return. Usage ## S3 method for class 'BaseFilter' !f ## S3 method for class 'BaseFilter' f & g ## S3 method for class 'BaseFilter' f | g Arguments f, g Arbitrary BaseFilter class functions. Details See BaseFilter and MessageFilters for further details. Examples not_command <- !MessageFilters$command text_and_reply <- MessageFilters$text & MessageFilters$reply audio_or_video <- MessageFilters$audio | MessageFilters$video ForceReply Display a reply Description Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot’s message and tapped ’Reply’). Usage ForceReply(force_reply = TRUE, selective = NULL) Arguments force_reply Shows reply interface to the user, as if they manually selected the bot’s message and tapped ’Reply’. Defaults to TRUE. selective (Optional). Use this parameter if you want to show the keyboard to specific users only. Examples ## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Set input parameters text <- "Don't forget to send me the answer!" # Send reply message bot$sendMessage(chat_id, text, reply_markup = ForceReply()) ## End(Not run) forwardMessage Forward messages of any kind Description Use this method to forward messages of any kind. Usage forwardMessage(chat_id, from_chat_id, message_id, disable_notification = FALSE) Arguments chat_id Unique identifier for the target chat or username of the target channel. from_chat_id Unique identifier for the chat where the original message was sent. message_id Message identifier in the chat specified in from_chat_id. disable_notification (Optional). Sends the message silently. Users will receive a notification with no sound. Details You can also use it’s snake_case equivalent forward_message. from_chat_id Get an update’s chat ID Description Get the id from the Update’s effective chat. Usage from_chat_id() from_user_id Get an update’s user ID Description Get the id from the Update’s effective user. Usage from_user_id() getFile Prepare a file for downloading Description Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again. Usage getFile(file_id, destfile = NULL, ...) Arguments file_id The file identifier. destfile (Optional). If you want to save the file, pass by a character string with the name where the downloaded file is saved. See the destfile parameter from ?curl::curl_download for further details. ... (Optional). Additional parameters to be passed to curl_download. It is not used if destfile is NULL. Details You can also use it’s snake_case equivalent get_file. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") photos <- bot$getUserProfilePhotos(chat_id = chat_id) # Download user profile photo file_id <- photos$photos[[1L]][[1L]]$file_id bot$getFile(file_id, destfile = "photo.jpg") ## End(Not run) getMe Check your bot’s information Description A simple method for testing your bot’s auth token. Requires no parameters. Usage getMe() Details You can also use it’s snake_case equivalent get_me. getUpdates Receive incoming updates Description Use this method to receive incoming updates. It returns a list of Update objects. Usage getUpdates(offset = NULL, limit = 100L, timeout = 0L, allowed_updates = NULL) Arguments offset (Optional). Identifier of the first update to be returned. limit (Optional). Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. timeout (Optional). Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only. allowed_updates (Optional). String or vector of strings with the types of updates you want your bot to receive. For example, specify c("message", "edited_channel_post", "callback_query") to only receive updates of these types. See Update for a complete list of available update types. Specify an empty string to receive all updates regardless of type (default). If not specified, the previous setting will be used. Please note that this parameter doesn’t affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time. Details 1. This method will not work if an outgoing webhook is set up. 2. In order to avoid getting duplicate updates, recalculate offset after each server response or use Bot method clean_updates. 3. To take full advantage of this library take a look at Updater. You can also use it’s snake_case equivalent get_updates. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) updates <- bot$getUpdates() ## End(Not run) getUserProfilePhotos Get a user’s profile photos Description Use this method to get a list of profile pictures for a user. Usage getUserProfilePhotos(user_id, offset = NULL, limit = 100L) Arguments user_id Unique identifier of the target user. offset (Optional). Sequential number of the first photo to be returned. By default, all photos are returned. limit (Optional). Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100. Details You can also use it’s snake_case equivalent get_user_profile_photos. See getFile to know how to download files. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") photos <- bot$getUserProfilePhotos(chat_id = chat_id) ## End(Not run) getWebhookInfo Get current webhook status Description Use this method to get current webhook status. Requires no parameters. Usage getWebhookInfo() Details If the bot is using getUpdates, will return an object with the url field empty. You can also use it’s snake_case equivalent get_webhook_info. Handler The base of all handlers Description The base class for all update handlers. Create custom handlers by inheriting from it. Usage Handler( callback, check_update = NULL, handle_update = NULL, handlername = NULL ) is.Handler(x) Arguments callback The callback function for this handler. Its inputs will be (bot, update), where bot is a Bot instance and update an Update class. check_update Function that will override the default check_update method. Use it if you want to create your own Handler. handle_update Function that will override the default handle_update method. Use it if you want to create your own Handler. handlername Name of the customized class, which will inherit from Handler. If NULL (de- fault) it will create a Handler class. x Object to be tested. Format An R6Class object. Methods check_update Called to determine if an update should be handled by this handler instance. handle_update Called if it was determined that an update should indeed be handled by this in- stance. Sub-classes MessageHandler To handle Telegram messages. CommandHandler To handle Telegram commands. CallbackQueryHandler To handle Telegram callback queries. ErrorHandler To handle errors while polling for updates. Examples ## Not run: # Example of a Handler callback_method <- function(bot, update) { chat_id <- update$effective_chat()$id bot$sendMessage(chat_id = chat_id, text = "Hello") } hello_handler <- Handler(callback_method) # Customizing Handler check_update <- function(update) { TRUE } handle_update <- function(update, dispatcher) { self$callback(dispatcher$bot, update) } foo_handler <- Handler(callback_method, check_update = check_update, handle_update = handle_update, handlername = "FooHandler" ) ## End(Not run) handle_update Handle an update Description This method is called if it was determined that an update should indeed be handled by this instance. It should also be overridden (see Handler). Usage handle_update(update, dispatcher) Arguments update The update to be handled. dispatcher The dispatcher to collect optional arguments. Details In most cases self$callback(dispatcher$bot, update) can be called, possibly along with op- tional arguments. InlineKeyboardButton Create an inline keyboard button Description This object represents one button of an inline keyboard. You must use exactly one of the optional fields. If all optional fields are NULL, by defect it will generate callback_data with same data as in text. Usage InlineKeyboardButton( text, url = NULL, callback_data = NULL, switch_inline_query = NULL, switch_inline_query_current_chat = NULL ) is.InlineKeyboardButton(x) Arguments text Label text on the button. url (Optional). HTTP url to be opened when button is pressed. callback_data (Optional). Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes. switch_inline_query (Optional). If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot’s username and the specified inline query in the input field. Can be empty, in which case just the bot’s username will be inserted. switch_inline_query_current_chat (Optional). If set, pressing the button will insert the bot’s username and the specified inline query in the current chat’s input field. Can be empty, in which case only the bot’s username will be inserted. x Object to be tested. Details Note: After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery. It is, therefore, necessary to react by calling answerCallbackQuery even if no notification to the user is needed (e.g., without specifying any of the optional parameters). InlineKeyboardMarkup Create an inline keyboard markup Description This object represents an inline keyboard that appears right next to the message it belongs to. Usage InlineKeyboardMarkup(inline_keyboard) Arguments inline_keyboard List of button rows, each represented by a list of InlineKeyboardButton ob- jects. Details Note: After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery. It is, therefore, necessary to react by calling answerCallbackQuery even if no notification to the user is needed (e.g., without specifying any of the optional parameters). Examples ## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Create Inline Keyboard text <- "Could you type their phone number, please?" IKM <- InlineKeyboardMarkup( inline_keyboard = list( list( InlineKeyboardButton(1), InlineKeyboardButton(2), InlineKeyboardButton(3) ), list( InlineKeyboardButton(4), InlineKeyboardButton(5), InlineKeyboardButton(6) ), list( InlineKeyboardButton(7), InlineKeyboardButton(8), InlineKeyboardButton(9) ), list( InlineKeyboardButton("*"), InlineKeyboardButton(0), InlineKeyboardButton("#") ) ) ) # Send Inline Keyboard bot$sendMessage(chat_id, text, reply_markup = IKM) ## End(Not run) InlineQueryResult The base of inline query results Description Baseclass for the InlineQueryResult* classes. Usage InlineQueryResult(type, id, ...) is.InlineQueryResult(x) Arguments type Type of the result. See the documentation for a list of supported types. id Unique identifier for this result, 1-64 Bytes. ... Additional parameters for the selected type. See the documentation for the de- scription of the parameters depending on the InlineQueryResult type. x Object to be tested. Examples ## Not run: document_url <- paste0( "https://github.com/ebeneditos/telegram.bot/raw/gh-pages/docs/", "telegram.bot.pdf" ) result <- InlineQueryResult( type = "document", id = 1, title = "Documentation", document_url = document_url, mime_type = "application/pdf" ) ## End(Not run) KeyboardButton Create a keyboard button Description This object represents one button of the reply keyboard. Optional fields are mutually exclusive. Usage KeyboardButton(text, request_contact = NULL, request_location = NULL) is.KeyboardButton(x) Arguments text Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed. request_contact (Optional). If TRUE, the user’s phone number will be sent as a contact when the button is pressed. Available in private chats only. request_location (Optional). If TRUE, the user’s current location will be sent when the button is pressed. Available in private chats only. x Object to be tested. Details Note: request_contact and request_location options will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. leaveChat Leave a chat Description Use this method for your bot to leave a group, supergroup or channel. Usage leaveChat(chat_id) Arguments chat_id Unique identifier for the target chat or username of the target channel. Details You can also use it’s snake_case equivalent leave_chat. MessageFilters Filter message updates Description Predefined filters for use as the filter argument of class MessageHandler. Usage MessageFilters Format A list with filtering functions. Details See BaseFilter and filtersLogic for advanced filters. Functions • all: All Messages. • text: Text Messages. • command: Messages starting with /. • reply: Messages that are a reply to another message. • audio: Messages that contain audio. • document: Messages that contain document. • photo: Messages that contain photo. • sticker: Messages that contain sticker. • video: Messages that contain video. • voice: Messages that contain voice. • contact: Messages that contain contact. • location: Messages that contain location. • venue: Messages that are forwarded. • game: Messages that contain game. Examples ## Not run: # Use to filter all video messages video_handler <- MessageHandler(callback_method, MessageFilters$video) # To filter all contacts, etc. contact_handler <- MessageHandler(callback_method, MessageFilters$contact) ## End(Not run) MessageHandler Handling messages Description Handler class to handle Telegram messages. They might contain text, media or status updates. Usage MessageHandler(callback, filters = NULL) Arguments callback The callback function for this handler. See Handler for information about this function. filters (Optional). Only allow updates with these filters. Use NULL (default) or MessageFilters$all for no filtering. See MessageFilters for a full list of all available filters. Format An R6Class object. Examples ## Not run: callback_method <- function(bot, update) { chat_id <- update$message$chat_id bot$sendMessage(chat_id = chat_id, text = "Hello") } # No filtering message_handler <- MessageHandler(callback_method, MessageFilters$all) ## End(Not run) ReplyKeyboardMarkup Create a keyboard markup Description This object represents a custom keyboard with reply options. Usage ReplyKeyboardMarkup( keyboard, resize_keyboard = NULL, one_time_keyboard = NULL, selective = NULL ) Arguments keyboard List of button rows, each represented by a list of KeyboardButton objects. resize_keyboard (Optional). Requests clients to resize the keyboard vertically for optimal fit. Defaults to FALSE, in which case the custom keyboard is always of the same height as the app’s standard keyboard. one_time_keyboard (Optional). Requests clients to hide the keyboard as soon as it’s been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat - the user can press a special button in the input field to see the custom keyboard again. Defaults to FALSE. selective (Optional). Use this parameter if you want to show the keyboard to specific users only. Examples ## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Create Custom Keyboard text <- "Aren't those custom keyboards cool?" RKM <- ReplyKeyboardMarkup( keyboard = list( list(KeyboardButton("Yes, they certainly are!")), list(KeyboardButton("I'm not quite sure")), list(KeyboardButton("No...")) ), resize_keyboard = FALSE, one_time_keyboard = TRUE ) # Send Custom Keyboard bot$sendMessage(chat_id, text, reply_markup = RKM) ## End(Not run) ReplyKeyboardRemove Remove a keyboard Description Upon receiving a message with this object, Telegram clients will remove the current custom key- board and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup). Usage ReplyKeyboardRemove(remove_keyboard = TRUE, selective = NULL) Arguments remove_keyboard Requests clients to remove the custom keyboard. (user will not be able to sum- mon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in ReplyKeyboardMarkup). Defaults to TRUE. selective (Optional). Use this parameter if you want to show the keyboard to specific users only. Examples ## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Create Custom Keyboard text <- "Don't forget to send me the answer!" RKM <- ReplyKeyboardMarkup( keyboard = list( list(KeyboardButton("Yes, they certainly are!")), list(KeyboardButton("I'm not quite sure")), list(KeyboardButton("No...")) ), resize_keyboard = FALSE, one_time_keyboard = FALSE ) # Send Custom Keyboard bot$sendMessage(chat_id, text, reply_markup = RKM) # Remove Keyboard bot$sendMessage( chat_id, "Okay, thanks!", reply_markup = ReplyKeyboardRemove() ) ## End(Not run) running Retrieve the status of the Webhook. Description Returns TRUE when listening for updates. Usage running() sendAnimation Send animation files Description Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). Usage sendAnimation( chat_id, animation, duration = NULL, width = NULL, height = NULL, caption = NULL, parse_mode = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL ) Arguments chat_id Unique identifier for the target chat or username of the target channel. animation Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a local file by passing a file path. duration (Optional). Duration of sent audio in seconds. width (Optional). Video width. height (Optional). Video height. caption (Optional). Animation caption, 0-1024 characters. parse_mode (Optional). Send ’Markdown’ or ’HTML’, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot’s message. disable_notification (Optional). Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (Optional). If the message is a reply, ID of the original message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply Details You can also use it’s snake_case equivalent send_animation. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") animation_url <- "http://techslides.com/demos/sample-videos/small.mp4" bot$sendAnimation( chat_id = chat_id, animation = animation_url ) ## End(Not run) sendAudio Send audio files Description Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. For sending voice messages, use the sendVoice method instead. Usage sendAudio( chat_id, audio, duration = NULL, performer = NULL, title = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL ) Arguments chat_id Unique identifier for the target chat or username of the target channel. audio Audio file to send. Pass a file_id as String to send an audio that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio from the Internet, or upload a local audio file by passing a file path. duration (Optional). Duration of sent audio in seconds. performer (Optional). Performer. title (Optional). Track name. caption (Optional). Audio caption, 0-1024 characters. disable_notification (Optional). Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (Optional). If the message is a reply, ID of the original message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply parse_mode (Optional). Send ’Markdown’ or ’HTML’, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot’s message. Details You can also use it’s snake_case equivalent send_audio. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") audio_url <- "http://www.largesound.com/ashborytour/sound/brobob.mp3" bot$sendAudio( chat_id = chat_id, audio = audio_url ) ## End(Not run) sendChatAction Send a chat action Description Use this method when you need to tell the user that something is happening on the bot’s side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Usage sendChatAction(chat_id, action) Arguments chat_id Unique identifier for the target chat or username of the target channel. action Type of action to broadcast. Choose one, depending on what the user is about to receive: • typing for text messages • upload_photo for photos • upload_video for videos • record_video for video recording • upload_audio for audio files • record_audio for audio file recording • upload_document for general files • find_location for location data • upload_video_note for video notes • record_video_note for video note recording Details You can also use it’s snake_case equivalent send_chat_action. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") bot$sendChatAction( chat_id = chat_id, action = "typing" ) ## End(Not run) sendDocument Send general files Description Use this method to send general files. Usage sendDocument( chat_id, document, filename = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL ) Arguments chat_id Unique identifier for the target chat or username of the target channel. document File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a local file by passing a file path filename (Optional). File name that shows in telegram message. caption (Optional). Document caption, 0-1024 characters. disable_notification (Optional). Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (Optional). If the message is a reply, ID of the original message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply parse_mode (Optional). Send ’Markdown’ or ’HTML’, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot’s message. Details You can also use it’s snake_case equivalent send_document. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") document_url <- paste0( "https://github.com/ebeneditos/telegram.bot/raw/gh-pages/docs/", "telegram.bot.pdf" ) bot$sendDocument( chat_id = chat_id, document = document_url ) ## End(Not run) sendLocation Send point on the map Description Use this method to send point on the map. Usage sendLocation( chat_id, latitude, longitude, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL ) Arguments chat_id Unique identifier for the target chat or username of the target channel. latitude Latitude of location. longitude Longitude of location. disable_notification (Optional). Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (Optional). If the message is a reply, ID of the original message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply Details You can also use it’s snake_case equivalent send_location. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") bot$sendLocation( chat_id = chat_id, latitude = 51.521727, longitude = -0.117255 ) ## End(Not run) sendMessage Send text messages Description Use this method to send text messages. Usage sendMessage( chat_id, text, parse_mode = NULL, disable_web_page_preview = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL ) Arguments chat_id Unique identifier for the target chat or username of the target channel. text Text of the message to be sent. parse_mode (Optional). Send ’Markdown’ or ’HTML’, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot’s message. disable_web_page_preview (Optional). Disables link previews for links in this message. disable_notification (Optional). Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (Optional). If the message is a reply, ID of the original message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply Details You can also use it’s snake_case equivalent send_message. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") bot$sendMessage( chat_id = chat_id, text = "foo *bold* _italic_", parse_mode = "Markdown" ) ## End(Not run) sendPhoto Send image files Description Use this method to send photos. Usage sendPhoto( chat_id, photo, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL ) Arguments chat_id Unique identifier for the target chat or username of the target channel. photo Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a local photo by passing a file path. caption (Optional). Photo caption (may also be used when re-sending photos by file_id), 0-1024 characters. disable_notification (Optional). Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (Optional). If the message is a reply, ID of the original message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply parse_mode (Optional). Send ’Markdown’ or ’HTML’, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot’s message. Details You can also use it’s snake_case equivalent send_photo. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") photo_url <- "https://telegram.org/img/t_logo.png" bot$sendPhoto( chat_id = chat_id, photo = photo_url, caption = "Telegram Logo" ) ## End(Not run) sendSticker Send a sticker Description Use this method to send .webp stickers. Usage sendSticker( chat_id, sticker, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL ) Arguments chat_id Unique identifier for the target chat or username of the target channel. sticker Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a local one by passing a file path. disable_notification (Optional). Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (Optional). If the message is a reply, ID of the original message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply Details You can also use it’s snake_case equivalent send_sticker. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") sticker_url <- "https://www.gstatic.com/webp/gallery/1.webp" bot$sendSticker( chat_id = chat_id, sticker = sticker_url ) ## End(Not run) sendVideo Send a video Description Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). Usage sendVideo( chat_id, video, duration = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, width = NULL, height = NULL, parse_mode = NULL, supports_streaming = NULL ) Arguments chat_id Unique identifier for the target chat or username of the target channel. video Video file to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a local video file by passing a file path. duration (Optional). Duration of sent audio in seconds. caption (Optional). Video caption, 0-1024 characters. disable_notification (Optional). Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (Optional). If the message is a reply, ID of the original message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply width (Optional). Video width. height (Optional). Video height. parse_mode (Optional). Send ’Markdown’ or ’HTML’, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot’s message. supports_streaming (Optional). Pass TRUE, if the uploaded video is suitable for streaming. Details You can also use it’s snake_case equivalent send_video. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") video_url <- "http://techslides.com/demos/sample-videos/small.mp4" bot$sendVideo( chat_id = chat_id, video = video_url ) ## End(Not run) sendVideoNote Send video messages Description Use this method to send video messages. Usage sendVideoNote( chat_id, video_note, duration = NULL, length = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL ) Arguments chat_id Unique identifier for the target chat or username of the target channel. video_note Video note file to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video note from the Internet, or upload a local video note file by passing a file path. duration (Optional). Duration of sent audio in seconds. length (Optional). Video width and height. disable_notification (Optional). Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (Optional). If the message is a reply, ID of the original message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply Details You can also use it’s snake_case equivalent send_video_note. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") video_note_url <- "http://techslides.com/demos/sample-videos/small.mp4" bot$sendVideoNote( chat_id = chat_id, video_note = video_note_url ) ## End(Not run) sendVoice Send voice files Description Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent with sendAudio or sendDocument). Usage sendVoice( chat_id, voice, duration = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL ) Arguments chat_id Unique identifier for the target chat or username of the target channel. voice Voice file to send. Pass a file_id as String to send a voice file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a voice file from the Internet, or upload a local voice file file by passing a file path. duration (Optional). Duration of sent audio in seconds. caption (Optional). Voice message caption, 0-1024 characters. disable_notification (Optional). Sends the message silently. Users will receive a notification with no sound. reply_to_message_id (Optional). If the message is a reply, ID of the original message. reply_markup (Optional). A Reply Markup parameter object, it can be either: • ReplyKeyboardMarkup • InlineKeyboardMarkup • ReplyKeyboardRemove • ForceReply parse_mode (Optional). Send ’Markdown’ or ’HTML’, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot’s message. Details You can also use it’s snake_case equivalent send_voice. Examples ## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") ogg_url <- "https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg" bot$sendVoice( chat_id = chat_id, voice = ogg_url ) ## End(Not run) setWebhook Set a webhook Description Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. Usage setWebhook( url = NULL, certificate = NULL, max_connections = 40L, allowed_updates = NULL, ip_address = NULL, drop_pending_updates = FALSE, secret_token = NULL ) Arguments url HTTPS url to send updates to. Use an empty string to remove webhook integra- tion. certificate (Optional). Upload your public key certificate so that the root certificate in use can be checked. See Telegram’s self-signed guide for details. max_connections (Optional). Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot’s server, and higher values to increase your bot’s throughput. allowed_updates (Optional). String or vector of strings with the types of updates you want your bot to receive. For example, specify c("message", "edited_channel_post", "callback_query") to only receive updates of these types. See Update for a complete list of available update types. Specify an empty string to receive all updates regardless of type (default). If not specified, the previous setting will be used. Please note that this parameter doesn’t affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. ip_address (Optional). The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS. drop_pending_updates (Optional). Pass True to drop all pending updates. secret_token (Optional). A secret token to be sent in a header X-Telegram-Bot-Api-Secret-Token in every webhook request, 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you. Details If you’d like to make sure that the webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/<token>. You can also use it’s snake_case equivalent set_webhook. set_token Change your bot’s auth token Description Use this method to change your bot’s auth token. Usage set_token(token) Arguments token The bot’s token given by the BotFather. start_polling Start polling Description Starts polling updates from Telegram. You can stop the polling either by using the the interrupt R command in the session menu or with the stop_polling method. Usage start_polling( timeout = 10L, clean = FALSE, allowed_updates = NULL, verbose = FALSE ) Arguments timeout (Optional). Passed to getUpdates. Default is 10. clean (Optional). Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is FALSE. allowed_updates (Optional). Passed to getUpdates. verbose (Optional). If TRUE, prints status of the polling. Default is FALSE. Examples ## Not run: # Start polling example start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } updater <- Updater("TOKEN") + CommandHandler("start", start) updater$start_polling(verbose = TRUE) ## End(Not run) start_server Start the webhook server. Description Starts the webhook for updates from Telegram. You can stop listening either by using the RStudio’s interrupt R command in the session menu or with the stop_server method. Usage start_server(host = "127.0.0.1", port = 5001, clean = FALSE, blocking = TRUE) Arguments host a string that is a valid IPv4 or IPv6 address that is owned by this server, which the application will listen on. "0.0.0.0" represents all IPv4 addresses and "::/0" represents all IPv6 addresses. Default is "127.0.0.1". port a number or integer that indicates the server port that should be listened on. Note that on most Unix-like systems including Linux and Mac OS X, port numbers smaller than 1025 require root privileges. Default is 5001. clean (Optional). Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is FALSE. blocking (Optional). Determines whether the method blocks whilst listening for updates from Telegram. Default is TRUE. Examples ## Not run: # Start webhook example start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } webhook <- Webhook("https://example.com/webhook", "TOKEN") + CommandHandler("start", start) webhook$start_server() ## End(Not run) stop_polling Stop polling Description Stops the polling. Requires no parameters. Usage stop_polling() Examples ## Not run: # Example of a 'kill' command kill <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = "Bye!" ) # Clean 'kill' update bot$getUpdates(offset = update$update_id + 1) # Stop the updater polling updater$stop_polling() } updater <<- updater + CommandHandler("kill", kill) updater$start_polling(verbose = TRUE) # Send '/kill' to the bot ## End(Not run) stop_server Stop the webhook server. Description Stops listening on the webhook. Requires no parameters. Usage stop_server() Examples ## Not run: # Example of a 'kill' command kill <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = "Bye!" ) # Stop the webhook webhook$stop_server() } webhook <- Webhook("https://example.com/webhook", "TOKEN") + CommandHandler("start", start) webhook$start_server() ## End(Not run) TelegramObject The base of telegram.bot objects Description Base class for most telegram objects. Usage is.TelegramObject(x) Arguments x Object to be tested. Format An R6Class generator object. Methods Public methods: • TelegramObject$clone() Method clone(): The objects of this class are cloneable with this method. Usage: TelegramObject$clone(deep = FALSE) Arguments: deep Whether to make a deep clone. Update Represent an update Description This object represents an incoming Update. Usage Update(data) is.Update(x) Arguments data Data of the update. x Object to be tested. Format An R6Class object. Methods from_chat_id To get the id from the update’s effective chat. from_user_id To get the id from the update’s effective user. effective_chat To get the chat that this update was sent in, no matter what kind of update this is. effective_user To get the user that sent this update, no matter what kind of update this is. effective_message To get the message included in this update, no matter what kind of update this is. Updater Building a Telegram Bot with Update Polling Description This class, which employs the class Dispatcher, provides a front-end to class Bot to the program- mer, so you can focus on coding the bot. Its purpose is to receive the updates from Telegram and to deliver them to said dispatcher. The dispatcher supports Handler classes for different kinds of data: Updates from Telegram, basic text commands and even arbitrary types. See add (+) to learn more about building your Updater. Usage Updater( token = NULL, base_url = NULL, base_file_url = NULL, request_config = NULL, bot = NULL ) is.Updater(x) Arguments token (Optional). The bot’s token given by the BotFather. base_url (Optional). Telegram Bot API service URL. base_file_url (Optional). Telegram Bot API file URL. request_config (Optional). Additional configuration settings to be passed to the bot’s POST requests. See the config parameter from ?httr::POST for further details. The request_config settings are very useful for the advanced users who would like to control the default timeouts and/or control the proxy used for HTTP com- munication. bot (Optional). A pre-initialized Bot instance. x Object to be tested. Format An R6Class object. Details Note: You must supply either a bot or a token argument. Methods start_polling Starts polling updates from Telegram. stop_polling Stops the polling. References Bots: An introduction for developers and Telegram Bot API Examples ## Not run: updater <- Updater(token = "TOKEN") # In case you want to set a proxy (see ?httr:use_proxy) updater <- Updater( token = "TOKEN", request_config = httr::use_proxy(...) ) # Add a handler start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } updater <- updater + CommandHandler("start", start) # Start polling updater$start_polling(verbose = TRUE) # Send '/start' to the bot ## End(Not run) user_id Get a user from environment Description Obtain Telegram user id from system variables (in .Renviron) set according to the naming conven- tion R_TELEGRAM_USER_X where X is the user’s name. Usage user_id(user_name) Arguments user_name The user’s name. Examples ## Not run: # Open the `.Renviron` file file.edit(path.expand(file.path("~", ".Renviron"))) # Add the line (uncomment and replace <user-id> by your Telegram user ID): # R_TELEGRAM_USER_Me=<user-id> # Save and restart R user_id("Me") ## End(Not run) Webhook Building a Telegram Bot with a Webhook Description This class, which employs the class Dispatcher, provides a front-end to class Bot to the pro- grammer, so you can focus on coding the bot. Its purpose is to receive updates via webhook from Telegram and to deliver them to said dispatcher. The dispatcher supports Handler classes for dif- ferent kinds of data: Updates from Telegram, basic text commands and even arbitrary types. See add (+) to learn more about building your Webhook. Usage Webhook( webhook_url, token = NULL, base_url = NULL, base_file_url = NULL, request_config = NULL, certificate = NULL, max_connections = NULL, allowed_updates = NULL, ip_address = NULL, drop_pending_updates = FALSE, verbose = FALSE, bot = NULL ) is.Webhook(x) Arguments webhook_url Webhook HTTPS url to send updates to. The url is conventionally suffixed with the /webhook path. Note: The url must be publicly accessible, since Telegram will need to make HTTP POST requests to the end-point for each update. For example, if you are deploying to Heroku, you can use the app’s hostname, such as https://[name of app].herokuapp.com/webhook, or a custom host- name for a domain that belongs to you, such as https://app.yourcustomdomain.com/webhook. token (Optional). The bot’s token given by the BotFather. base_url (Optional). Telegram Bot API service URL. base_file_url (Optional). Telegram Bot API file URL. request_config (Optional). Additional configuration settings to be passed to the bot’s POST requests. See the config parameter from httr::POST for further details. The request_config settings are very useful for the advanced users who would like to control the default timeouts and/or control the proxy used for HTTP com- munication. certificate (Optional). Upload your public key certificate so that the root certificate in use can be checked. See Telegram’s self-signed guide for details. max_connections (Optional). Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot’s server, and higher values to increase your bot’s throughput. allowed_updates (Optional). String or vector of strings with the types of updates you want your bot to receive. For example, specify c("message", "edited_channel_post", "callback_query") to only receive updates of these types. See Update for a complete list of available update types. Specify an empty string to receive all updates regardless of type (default). If not specified, the previous setting will be used. Please note that this parameter doesn’t affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. ip_address (Optional). The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS. drop_pending_updates (Optional). Pass True to drop all pending updates. verbose (Optional). If TRUE, prints status of the polling. Default is FALSE. bot (Optional). A pre-initialized Bot instance. x Object to be tested. Format An R6Class object. Details You must supply the webhook_url and either a bot or a token argument. The webhook_url must be publicly accessible, since Telegram will need to make HTTP POST re- quests to the end-point for each update. Security Note: Webhook encapsulates generating a secret_token which is used to validate that the request comes from a webhook set by you. Methods start_server Starts listening for updates from Telegram. stop_server Stops listening for updates. running Returns TRUE when listening for updates. References Bots: An introduction for developers, Telegram Bot API and Marvin’s Marvellous Guide to All Things Webhook Examples ## Not run: webhook <- Webhook("https://example.com/webhook", "TOKEN") # In case you want to set a proxy webhook <- Webhook( webhook_url = "https://example.com/webhook", token = "TOKEN", request_config = httr::use_proxy(...), verbose = TRUE ) # Add a handler start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } webhook <- webhook + CommandHandler("start", start) # Start polling webhook$start_server() # Send '/start' to the bot ## End(Not run)
opnfv-edgecloud
readthedoc
Unknown
EDGECLOUD Release Latest Nov 29, 2019 Contents 4.1 Resource optimized contro... 7 4.2 Remote provisionin... 7 4.3 Resource diversit... 7 4.4 Hardware/Software acceleratio... 7 5.1 Small Edg... 9 5.2 Medium Edg... 10 5.3 Large Edg... 11 7.1 Hardwar... 15 7.2 Acceleratio... 15 7.3 OpenStac... 15 7.4 SD... 17 7.5 Orchestration & Managemen... 17 7.6 Containe... 17 i ii CHAPTER 1 Introduction This Edge Cloud Requirement Document is used for eliciting telecom network Edge Cloud Requirements of OPNFV, where telecom network edge clouds are edge clouds deployed into the telecommunication infrastructure. Edge clouds deployed beyond the borders of telecommunication networks are outside of the scope of this document. This document will define high-level telecom network edge cloud goals, including service reqirements, sites conditions, and translate them into detailed requirements on edge cloud infrastructure components. Moreover, this document can be used as reference for edge cloud testing scenario design. EDGECLOUD, Release Latest 2 Chapter 1. Introduction CHAPTER 2 Definitions & Terminologies The following terminologies will be used in this document: Core site(s): Sites that are far away from end users/ base stations, completely virtualized, and mainly host control domain services (e.g. telco services: HSS, MME, IMS, EPC, etc). Edge site(s): Sites that are closer to end users/ base stations, and mainly host control and compute services. E2E delay: time of the transmission process between the user equipment and the edge cloud site. It contains four parts: time of radio transmission, time of optical fiber transmission, time of GW forwarding, and time of VM forwarding. BBU: Building Baseband Unit. It’s a centralized processing unit of radio signals. Together with RRU (Remote Radio Unit), it forms the distirbuted base station architecture. For example, a large stadium is usually separated into different districts. Each district would be provided with a RRU, which is close to user, to provide radio access. All RRUs would be linked to a BBU, which is located inside a remote site away from user and provide signal processing, using optical fiber. BRAS: Broadband Remote Access Server. An Ethernet-centric IP edge router, and the aggregation point for the user traffic. It performs Ethernet aggregation and packets forwarding via IP/MPLS, and supports user management, access protocols termination, QoS and policy management, etc. UPF: User Plane Function, which is a user plane gateway for user data transmission. SAE-GW: SAE stands for System Architecture Evolution, which is the core network architecture of 3GPP’s LTE wireless communication standard. SAE-GW includes Serving Gateway and PDN Gateway. Serving Gateway (SGW) routes and forwards user data packets,and also acts as the mobility anchor for LTE and other 3GPP technologies. PDN Gateway (PGW) provides connectivity from the UE to external packet data networks by being the point of exit and entry of traffic for the UE. SAE-GW related definition link: https://en.wikipedia.org/wiki/System_Architecture_Evolution CPE: In telecommunications, a customer-premises equipment or customer-provided equipment (CPE) is any terminal and associated equipment located at a subscriber’s premises and connected with a carrier’s telecommunication circuit. CPE generally refers to devices such as telephones, routers, network switches, residential gateways (RG), home net- working adapters and Internet access gateways that enable consumers to access communications service providers’ services and distribute them around their house via a local area network (LAN). CPE definition: https://en.wikipedia.org/wiki/Customer-premises_equipment EDGECLOUD, Release Latest enterprise vCPE: Usually CPE provides a number of network functions such as firewall, access control, policy man- agement and discovering/connecting devices at home. enterprise vCPE stands for virtual CPE for enterprise, which is a software framework that virtualizes several CPE funcitons. CHAPTER 3 Telco related Edge Use Cases RAN Services: CRAN-CU CRAN OPNFV project link: https://wiki.opnfv.org/pages/viewpage.action?pageId=20743420 CRAN stands for Cloud Radio Access Network or Centralized Radio Access Network. The basic concept is to con- solidate compute resources to run some radio access functions virtually and remotely in a datacenter, rather than in a base station. CU stands for Centralized Unit, which holds the non-real-time protocol processing function of BBU (refer to Definitions & Terminologies) and supports the deployment of some functions of core networks. Its generic requirements are listed below: • CRAN-CU has strict timing and performance requirements for signal processing to be compliant with RAN standards. The E2E delay should be less than 3ms. • Required bandwidth of CRAN-CU is around 50 GB/s • Acceleration technologies are recommended. Different technologies would be used under different deployment scenarios, different use cases and etc. • No external storage is needed by CRAN-CU. Local disk is enough. Gateways: UPF, SAE-GW, enterprise vCPE (refer to Definitions & Terminologies) Gateway services like UPF, SAE-GW and enterprise vCPE used to be deployed in core sites. They usually do not have strict latency requirements. Latency requirements of UPF and SAE-GW are both 10ms. Minimum latency required by enterprise vCPE is around 50ms when transmitting video and voice data. The number is over a second if transmitting email. So latency requirements can always be satisfied theoretically. However, as these gateways usually serve over millions of users (every enterprise vCPE serves more than a thousand enterprise-level users), they have high throughput requirements: bandwidth (BW) of UPF > 300 GB/s, BW of SAE-GW is around 50 GB/s, BW of enterprise vCPE > 40 GB/s. Deploying these services separately in edge sites will help to achieve local data flow transmission, offload traffic flows from core networks, and reduce footprints of transmission resources and core computing resources. Access technology independent service: edge CDN According to China Mobile’s data, every CDN unit can serve over 10 thousand customers and it requires bandwidth over one hundred GB. In order to reduce footprints of transmission resources and burden of the network, CDN is recommended to be deployed in edge sites, but not too close to users if taking deployment cost into consideration. It also requires fast compute ability to generate content distribution strategy quickly. EDGECLOUD, Release Latest One edge CDN unit does not need to communicate with other edge CDN units at the same level, but need to be connected with CDN units at higher level for policy distribution and resource downloading. MEC/Edge Computing Services Besides requiring low-latency, high-bandwidth, and high reliability, newly generated edge computing services require the local deployment environment to be capable of doing fast computing to support some intelligence functions like real-time data analysis and optimal path calculation of services like V2X. The deployment of MEC and third-party applications running on it mainly depends on latency requirements. uRLLC requires E2E delay less than 3ms, which means it should be deployed at edge sites close to base station. eMBB requires E2E delay less than 10ms, which leads to more flexible deployment location. Unlike traditional telco services which have relatively stable on-line and update cycle, MEC and the third-party appli- cations have more flexible lifecycle, which means a more flexible infrastructure should be used such as container. The table below summarizes the latency and bandwidth requirements of several typical telco related services:( x in table stands for 1~5) Service CND enterprise SAE-GW 5G-UPF MEC CRAN- vCPE CU E2E 10 ms 50 ms 10 ms 10ms URLLC < 3 ms, eMBB < 10 3 ms delay ms Band- >100 10 * x GB/s 10 * x >300 10 * x GB/s 10 * x width GB/s GB/s GB/s GB/s CHAPTER 4 Features of Edge 4.1 Resource optimized control As space and power resources are limited in edge sites and edge usually has fewer number of servers (the number varies from a few to several dozens), it is unnecessary to deploy orchestrator or VNFM. The depolyed VIM (e.g.: OpenStack or Kubernetes) and SDN would be optimized for low resource usage to save resources for services. Resource opti- misation of VIM and SDN have not been discussed yet, but basic functions such as VM lifecycle management and automatic network management should be persisted. 4.2 Remote provisioning As there is no professional maintenance staff at edge, remote provisioning should be provided so that virtual resources of distributed edge sites can obtain unified orchestration and maintenance. Orchestrator together with OSS/BSS, EMS and VNFM should be deployed remotely in some central offices to reduce the difficulty and cost of management as well as increasing edge resource utilization ratio. Multi region OpenStack could be considered as one of the VIM solution. 4.3 Resource diversity With various applications running on edge, diverse resources, including VM, container and bare-metal could co-exist and form diverse resource pool. These resources should be managed by edge management components as well as core orchestration/management components. 4.4 Hardware/Software acceleration Edge services usually require strict low latency, high bandwidth, and fast computing and processing ability. Acceler- ation technology should be used in edge to maintain good service performance. OpenStack should fully expose these EDGECLOUD, Release Latest acceleration capabilities to services. The usage of different acceleration technologies (including DPDK, SR-IOV, GPU, Smart NIC, FPGA and etc.) varies from service to service. Related project about acceleration: https://wiki.openstack.org/wiki/Cyborg CHAPTER 5 Edge Sites Conditions/ Deployment Scenarios Latency and distance to customer are taken as two main characters to separate different sites. The following figure shows three different sites. 5.1 Small Edge • Distance to base station: around 10 km, closest site to end users / base station • E2E delay(from UE to site): around 2 ms • Maximum bandwidth can provide: 50 GB/s • Minimum hardware specs: 1 unit of – 4 cores (two ARM or Xeon-D processors) – 8 GB RAM (4 DIMM) – 1 * 240 GB SSD (2 * 2.5) • Maximum hardware specs: 5 unit of – 16 cores EDGECLOUD, Release Latest – 64 GB RAM – 1 * 1 TB storage • Power for a site: < 10 kW • Physical access of maintainer: Rare, maintenance staff may only show up in this kind of site when machines initialize for the first time or a machine is down. Maintenance staff is skilled in mechanical engineering and not in IT. • Physical security: none (Optionally secure booting is needed) • Expected frequency of updates to hardware: 3-4 year refresh cycle • Expected frequency of updates to firmware: 6-12 months • Expected frequency of updates to control systems (e.g. OpenStack or Kubernetes controllers): ~ 12 - 24 months, has to be possible from remote management • Physical size: 482.6 mm (19 inch) witdth rack. Not all the sites will have 1000 mm (36 inch) depth capability. Some sites might be limited to 600 mm (12 inch) depth. • Cooling: front cooling • Access / cabling: front • NEBS 3 compliant • Number of edge cloud instances: depends on demands (3000+) • Services might be deployed here: MEC, or other services which have strict requirements on latency. Services deployed in this kind of sites have huge regional deference • Remote network connection reliability: No 100% uptime and variable connectivity expected. • Orchestration: no orchestration component. MANO deployed in core site provide remote orchestration • Degree of virtualization: it is possible that no virtualization technology would be used in small edge site if virtualization increases structure/network complexity, reduces service performance, or costs more resources. Bare-metal is common in small edge sites. Container would also be a future choice if virtualization was needed • Smart NICs are supported • Storage: mainly local storage. 5.2 Medium Edge • Distance to base station: around 50 km • E2E delay (from UE to site): less than 2.5 ms • Maximum bandwidth can provide: 100 GB/s • Minimum hardware specs: 2 Rack Unit (RU) • Maximum hardware specs: 20 Rack Unit • Power for a site: 10 - 20 10 kW • Physical access of maintainer: Rare. Maintenance staff is skilled in mechanical engineering and not in IT. • Physical security: Medium, probably not in a secure data center, probably in a semi-physically secure envi- ronment; each device has some authentication (such as certificate) to verify it’s a legitimate piece of hardware deployed by operator; network access is all through security enhanced methods (vpn, connected back to dmz); VPN itself is not considered secure, so other mechanism such as https should be employed as well) EDGECLOUD, Release Latest • Expected frequency of updates to hardware: 5-7 years • Expected frequency of updates to firmware: Never unless required to fix blocker/critical bug(s) • Expected frequency of updates to control systems (e.g. OpenStack or Kubernetes controllers): 12 - 24 months • Physical size: TBD • Cooling: front cooling • Access / cabling: front • NEBS 3 compliant • Number of edge cloud instances: 3000+ • Services might be deployed here: MEC, RAN, CPE, etc. • Remote network connection reliability: 24/7 (high uptime but connectivity is variable), 100% uptime expected • Orchestration: no orchestration component. MANO deployed in core site provide remote orchestration. • Degree of virtualization: depends on site conditions and service requirements. VM, container may form hybrid virtualization layer. Bare-metal is possible in middle sites • Smart NICs are supported • Storage: local storage and distributed storage, which depends on site conditions and services’ needs 5.3 Large Edge • Distance to base station: 80 - 300 km • E2E delay: around 4 ms • Maximum bandwidth can provide: 200 GB/s • Minimum hardware specs: N/A • Maximum hardware specs: 100+ servers • Power for a site: 20 - 90 kW • Physical access of maintainer: professional maintainer will monitor the site. Maintenance staff is skilled in mechanical engineering and not in IT. • Physical security: High • Expected frequency of updates to hardware: 36 month • Expected frequency of updates to firmware: Never unless required to fix blocker/critical bug(s) • Expected frequency of updates to control systems (e.g. OpenStack or Kubernetes controllers): 12 - 24 months • Physical size: same as a normal DC • Cooling: front cooling • Access / cabling: front • NEBS 3 compliant • Number of edge cloud instances: 600+ • Services might be deployed here: CDN, SAE-GW, UPF, CPE and etc., which have large bandwidth requirements and relatively low latency requirements EDGECLOUD, Release Latest • Remote network connection reliability: reliable and stable • Orchestration: no orchestration component. MANO deployed in core site provide remote orchestration • Degree of virtualization: almost completely virtualized in the form of VMs (if take CDN into consideration, which may not be virtualized, the virtualization degree would decrease in sites with CDN deployment) • Smart NICs are supported • Storage: distributed storage 12 Chapter 5. Edge Sites Conditions/ Deployment Scenarios CHAPTER 6 Edge Structure Based on requirements of telco related use cases and edge sites conditions, the edge structure has been summarized as the figure below. EDGECLOUD, Release Latest 14 Chapter 6. Edge Structure CHAPTER 7 Requirements & Features on NFV Components 7.1 Hardware Customized server would be possible for edge because of limited space, power, temperature, vibration and etc. But if there were custom enclosures that can provide environmental controls, then non-customized server can be used, which is a cost tradeoff. More derails: TBD 7.2 Acceleration Hardware acceleration resources and acceleration software would be necessary for edge. More details:TBD 7.3 OpenStack Edge OpenStack would be in hierarchical structure. Remote provisioning like multi-region OpenStack would exist in large edge sites with professional maintenance staff and provide remote management on several middle/small edge sites. Middle and small edge sites would not only have their own resource management components to provide local resource and network management, but also under the remote provisioning of OpenStack in large edge sites. Optionally for large edge sites, OpenStack would be fully deployed. Its Keystone and Horizon would provide unified tenant and UI management for both itself and remote middle and small edge sites. In this case middle edge sites would have OpenStack with neccessary services like Nova, Neutron and Glance. While small edge site would use resource optimized weight OpenStack. Other option is to use different instances of the same resource optimized OpenStack to control both large, medium and small edge sites. More detalis: TBD EDGECLOUD, Release Latest 16 Chapter 7. Requirements & Features on NFV Components EDGECLOUD, Release Latest 7.4 SDN TBD 7.5 Orchestration & Management Orchestration and VNF lifecycle management: NFVO, VNFM, EMS exist in core cloud and provide remote lifecycle management. More details: TBD 7.6 Container VM, container and bare-metal would exist as three different types of infrastructure resources. Which type of resources to use depends on services’ requirements and sites conditions. The introduction of container would be a future topic.
autogl
readthedoc
Unknown
AutoGL Release v0.2.0rc0 THUMNLab/aglteam Jul 11, 2021 TUTORIAL 2.1 Requirement... 3 2.2 Installatio... 3 3.1 Quick Star... 5 3.2 AutoGL Datase... 7 3.3 AutoGL Feature Engineerin... 9 3.4 AutoGL Mode... 11 3.5 AutoGL Traine... 16 3.6 Hyper Parameter Optimizatio... 20 3.7 Neural Architecture Searc... 23 3.8 Ensembl... 28 3.9 AutoGL Solve... 29 3.10 autogl.dat... 33 3.11 autogl.dataset... 38 3.12 autogl.module.featur... 38 3.13 autogl.module.mode... 38 3.14 autogl.module.trai... 38 3.15 autogl.module.hp... 38 3.16 autogl.module.na... 38 3.17 autogl.module.ensembl... 38 3.18 autogl.solve... 38 i ii CHAPTER ONE AUTOGL Actively under development by @THUMNLab AutoGL is developed for researchers and developers to quickly conduct autoML on the graph datasets & tasks. The workflow below shows the overall framework of AutoGL. AutoGL uses AutoGL Dataset to maintain datasets for graph-based machine learning, which is based on the dataset in PyTorch Geometric with some support added to corporate with the auto solver framework. Different graph-based machine learning tasks are solved by different AutoGL Solvers , which make use of four main modules to automatically solve given tasks, namely Auto Feature Engineer, Auto Model, Neural Architecture Search, HyperParameter Optimization, and Auto Ensemble. AutoGL, Release v0.2.0rc0 2 Chapter 1. AutoGL CHAPTER TWO INSTALLATION 2.1 Requirements Please make sure you meet the following requirements before installing AutoGL. 1. Python >= 3.6.0 2. PyTorch (>=1.6.0) see PyTorch for installation. 3. PyTorch Geometric (>=1.7.0) see PyTorch Geometric for installation. 2.2 Installation 2.2.1 Install from pip & conda Run the following command to install this package through pip. pip install autogl 2.2.2 Install from source Run the following command to install this package from the source. git clone https://github.com/THUMNLab/AutoGL.git cd AutoGL python setup.py install AutoGL, Release v0.2.0rc0 2.2.3 Install for development If you are a developer of the AutoGL project, please use the following command to create a soft link, then you can modify the local package without installation again. pip install -e . CHAPTER THREE MODULES In AutoGL, the tasks are solved by corresponding solvers, which in general do the following things: 1. Preprocess and feature engineer the given datasets. This is done by the module named auto feature engineer, which can automatically add/delete useful/useless attributes in the given datasets. Some topological features may also be extracted & combined to form stronger features for current tasks. 2. Find the best suitable model architectures through neural architecture search. This is done by modules named nas. AutoGL provides several search spaces, algorithms and estimators for finding the best architectures. 2. Automatically train and tune popular models specified by users. This is done by modules named auto model and hyperparameter optimization. In the auto model, several commonly used graph deep models are pro- vided, together with their hyperparameter spaces. These kinds of models can be tuned using hyperparameter optimization module to find the best hyperparameter for the current task. 3. Find the best way to ensemble models found and trained in the last step. This is done by the module named auto ensemble. The suitable models available are ensembled here to form a more powerful learner. 3.1 Quick Start This tutorial will help you quickly go through the concepts and usages of important classes in AutoGL. In this tutorial, you will conduct a quick auto graph learning on dataset Cora. 3.1.1 AutoGL Learning Based on the concept of autoML, auto graph learning aims at automatically solve tasks with data represented by graphs. Unlike conventional learning frameworks, auto graph learning, like autoML, does not need humans inside the experiment loop. You only need to provide the datasets and tasks to the AutoGL solver. This framework will automatically find suitable methods and hyperparameters for you. The diagram below describes the workflow of AutoGL framework. To reach the aim of autoML, our proposed auto graph learning framework is organized as follows. We have dataset to maintain the graph datasets given by users. A solver object needs to be built for specifying the target tasks. Inside solver, there are five submodules to help complete the auto graph tasks, namely auto feature engineer, auto model, neural architecture search, hyperparameter optimization and auto ensemble, which will au- tomatically preprocess/enhance your data, choose and optimize deep models and ensemble them in the best way for you. Let’s say you want to conduct an auto graph learning on dataset Cora. First, you can easily get the Cora dataset using the dataset module: AutoGL, Release v0.2.0rc0 from autogl.datasets import build_dataset_from_name cora_dataset = build_dataset_from_name('cora') The dataset will be automatically downloaded for you. Please refer to AutoGL Dataset or autogl.datasets for more details of dataset constructions, available datasets, add local datasets, etc. After deriving the dataset, you can build a node classification solver to handle auto training process: import torch device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') from autogl.solver import AutoNodeClassifier solver = AutoNodeClassifier( feature_module='deepgl', graph_models=['gcn', 'gat'], hpo_module='anneal', ensemble_module='voting', device=device ) In this way, we build a node classification solver, which will use deepgl as its feature engineer, and use anneal hyperparameter optimizer to optimize the given three models ['gcn','gat']. The derived models will then be ensembled using voting ensembler. Please refer to the corresponding tutorials or documentation to see the definition and usages of available submodules. Then, you can fit the solver and then check the leaderboard: solver.fit(cora_dataset, time_limit=3600) solver.get_leaderboard().show() The time_limit is set to 3600 so that the whole auto graph process will not exceed 1 hour. solver.show() will present the models maintained by solver, with their performances on the validation dataset. Then, you can make the predictions and evaluate the results using the evaluation functions provided: from autogl.module.train import Acc predicted = solver.predict_proba() print('Test accuracy: ', Acc.evaluate(predicted, cora_dataset.data.y[cora_dataset.data.test_mask].cpu().numpy())) Note: You don’t need to pass the cora_dataset again when predicting, since the dataset is remembered by the solver and will be reused when no dataset is passed at predicting. However, you can also pass a new dataset when predicting, and the new dataset will be used instead of the remembered one. Please refer to AutoGL Solver or au- togl.solver for more details. AutoGL, Release v0.2.0rc0 3.2 AutoGL Dataset We import the module of datasets from CogDL and PyTorch Geometric and add support for datasets from OGB. One can refer to the usage of creating and building datasets via the tutorial of CogDL, PyTorch Geometric, and OGB. 3.2.1 Supporting datasets AutoGL now supports the following benchmarks for different tasks: Semi-supervised node classification: Cora, Citeseer, Pubmed, Amazon Computers*, Amazon Photo*, Coauthor CS*, Coauthor Physics*, Reddit *: using utils.random_splits_mask_class for splitting dataset is recommended.). For detailed information for supporting datasets, please kindly refer to PyTorch Geometric Dataset. Dataset PyG CogDL x y edge_index edge_attr | train/val/test train/val/test node mask Cora X X X X X X Citeseer X X X X X X Pubmed X X X X X X Amazon Com- X X X X X puters Amazon Photo X X X X X Coauthor CS X X X X X Coauthor Physics X X X X X Reddit X X X X X X Graph classification: MUTAG, IMDB-B, IMDB-M, PROTEINS, COLLAB Dataset PyG CogDL x y edge_index edge_attr MUTAG X X X X X IMDB-B X X X IMDB-M X X X PROTEINS X X X X COLLAB X X X TODO: Supporting all datasets from PyTorch Geometric. 3.2.2 OGB datasets AutoGL also supports the popular benchmark on OGB for node classification and graph classification tasks. For the summary of OGB datasets, please kindly refer to the their docs. Since the loss and evaluation metric used for OGB datasets vary among different tasks, we also add string properties of datasets for identification: AutoGL, Release v0.2.0rc0 Dataset dataset.metric datasets.loss ogbn-products Accuracy nll_loss ogbn-proteins ROC-AUC BCEWithLogitsLoss ogbn-arxiv Accuracy nll_loss ogbn-papers100M Accuracy nll_loss ogbn-mag Accuracy nll_loss ogbg-molhiv ROC-AUC BCEWithLogitsLoss ogbg-molpcba AP BCEWithLogitsLoss ogbg-ppa Accuracy CrossEntropyLoss ogbg-code F1 score CrossEntropyLoss 3.2.3 Create a dataset via URL If your dataset is the same as the ‘ppi’ dataset, which contains two matrices: ‘network’ and ‘group’, you can register your dataset directly use the above code. The default root for downloading dataset is ~/.cache-autogl, you can also specify the root by passing the string to the path in build_dataset(args, path) or build_dataset_from_name(dataset, path). # following code-snippet is from autogl/datasets/matlab_matrix.py @register_dataset("ppi") class PPIDataset(MatlabMatrix): def __init__(self, path): dataset, filename = "ppi", "Homo_sapiens" url = "http://snap.stanford.edu/node2vec/" super(PPIDataset, self).__init__(path, filename, url) You should declare the name of the dataset, the name of the file, and the URL, where our script can download the resource. Then you can use either build_dataset(args, path) or build_dataset_from_name(dataset, path) in your task to build a dataset with corresponding parameters. 3.2.4 Create a dataset locally If you want to test your local dataset, we recommend you to refer to the docs on creating PyTorch Geometric dataset. You can simply inherit from torch_geometric.data.InMemoryDataset to create an empty dataset, then create some torch_geometric.data.Data objects for your data and pass a regular python list holding them, then pass them to torch_geometric.data.Dataset or torch_geometric.data.DataLoader. Let’s see this process in a simplified example: from typing import Iterable from torch_geometric.data.data import Data from autogl.datasets import build_dataset_from_name from torch_geometric.data import InMemoryDataset class MyDataset(InMemoryDataset): def __init__(self, datalist) -> None: super().__init__() self.data, self.slices = self.collate(datalist) # Create your own Data objects (continues on next page) AutoGL, Release v0.2.0rc0 (continued from previous page) # for example, if you have edge_index, features and labels # you can create a Data as follows # See pytorch geometric more info of Data data = Data() data.edge_index = edge_index data.x = features data.y = labels # create a list of Data object data_list = [data, Data(...), ..., Data(...)] # Initialize AutoGL Dataset with your own data myData = MyDataset(data_list) 3.3 AutoGL Feature Engineering We provide a series of node and graph feature engineers for you to compose within a feature engineering pipeline. An automatic feature engineering algorithm is also provided. 3.3.1 Quick Start # 1. Choose a dataset. from autogl.datasets import build_dataset_from_name data = build_dataset_from_name('cora') # 2. Compose a feature engineering pipeline from autogl.module.feature import BaseFeature,AutoFeatureEngineer from autogl.module.feature.generators import GeEigen from autogl.module.feature.selectors import SeGBDT from autogl.module.feature.graph import SgNetLSD # you may compose feature engineering bases through BaseFeature.compose fe = BaseFeature.compose([ GeEigen(size=32) , SeGBDT(fixlen=100), SgNetLSD() ]) # or just through '&' operator fe = fe & AutoFeatureEngineer(fixlen=200,max_epoch=3) # 3. Fit and transform the data fe.fit(data) data1=fe.transform(data,inplace=False) AutoGL, Release v0.2.0rc0 3.3.2 List of FE base names Now three kinds of feature engineering bases are supported,namely generators, selectors , graph.You can import bases from according module as is mentioned in the Quick Start part. Or you may want to just list names of bases in configurations or as arguments of the autogl solver. 1. generators Base Description graphlet concatenate local graphlet numbers as features. eigen concatenate Eigen features. pagerank concatenate Pagerank scores. PYGLocalDegreeProfile concatenate Local Degree Profile features. PYGNormalizeFeatures Normalize all node features PYGOneHotDegree concatenate degree one-hot encoding. onehot concatenate node id one-hot encoding. 2. selectors Base Description SeFilterConstant delete all constant and one-hot encoding node features. gbdt select top-k important node features ranked by Gradient Descent Decision Tree. 3. graph netlsd is a graph feature generation method. please refer to the according document. A set of graph feature extractors implemented in NetworkX are wrapped, please re- fer to NetworkX for details. (NxLargeCliqueSize, NxAverageClusteringApproximate, NxDegreeAssortativityCoefficient, NxDegreePearsonCorrelationCoefficient, NxHasBridge ,``Nx- GraphCliqueNumber``, NxGraphNumberOfCliques, NxTransitivity, NxAverageClustering, NxIsConnected, NxNumberConnectedComponents, NxIsDistanceRegular, NxLocalEfficiency, NxGlobalEfficiency, NxIsEulerian) The taxonomy of base types is based on the way of transforming features. generators concatenate the original features with ones newly generated or just overwrite the original ones. Instead of generating new features , selectors try to select useful features and keep learned selecting methods in the base itself. The former two types of bases can be exploited in node or edge level (modification upon each node or edge feature) ,while graph focuses on feature engineering in graph level (modification upon each graph feature). For your convenience in further development,you may want to design a new item by inheriting one of them. Of course, you can directly inherit the BaseFeature as well. 3.3.3 Create Your Own FE You can create your own feature engineering object by simply inheriting one of feature engineering base types ,namely generators, selectors , graph, and overloading methods _fit and _transform. # for example : create a node one-hot feature. from autogl.module.feature.generators.base import BaseGenerator import numpy as np class GeOnehot(BaseGenerator): def __init__(self): super(GeOnehot,self).__init__(data_t='np',multigraph=True,subgraph=False) # data type in mid is 'numpy', # and it can be used for multigraph, (continues on next page) AutoGL, Release v0.2.0rc0 (continued from previous page) # but not suitable for subgraph feature extraction. def _fit(self): pass # nothing to train or memorize def _transform(self, data): fe=np.eye(data.x.shape[0]) data.x=np.concatenate([data.x,fe],axis=1) return data 3.4 AutoGL Model In AutoGL, we use model and automodel to define the logic of graph nerual networks and make it compatible with hyper parameter optimization. Currently we support the following models for given tasks. Tasks Models Node Classification gcn, gat, sage Graph Classification gin, topk Link Prediction gcn, gat, sage 3.4.1 Lazy Initialization In current AutoGL pipeline, some important hyper-parameters related with model cannot be set outside before the pipeline (e.g. input dimensions, which can only be caluclated during running after feature engineered). Therefore, in automodel, we use lazy initialization to initialize the core model. When the automodel initialization method __init__() is called with argument init be False, only (part of) the hyper-parameters will be set. The automodel will have its core model only after initialize() is explicitly called, which will be done automatically in solver and from_hyper_parameter(), after all the hyper-parameters are set properly. 3.4.2 Define your own model and automodel We highly recommend you to define both model and automodel, although you only need your automodel to commu- nicate with solver and trainer. The model will be responsible for the parameters initialization and forward logic declaration, while the automodel will be responsible for the hyper-parameter definiton and organization. General customization Let’s say you want to implement a simple MLP for node classification and want to let AutoGL find the best hyper- parameters for you. You can first define the logics assuming all the hyper-parameters are given. import torch # define mlp model, need to inherit from torch.nn.Module class MyMLP(torch.nn.Module): # assume you already get all the hyper-parameters def __init__(self, in_channels, num_classes, layer_num, dim): super().__init__() (continues on next page) AutoGL, Release v0.2.0rc0 (continued from previous page) if layer_num == 1: ops = [torch.nn.Linear(in_channels, num_classes)] else: ops = [torch.nn.Linear(in_channels, dim)] for i in range(layer_num - 2): ops.append(torch.nn.Linear(dim, dim)) ops.append(torch.nn.Linear(dim, num_classes)) self.core = torch.nn.Sequential(*ops) # this method is required def forward(self, data): # data: torch_geometric.data.Data assert hasattr(data, 'x'), 'MLP only support graph data with features' x = data.x return torch.nn.functional.log_softmax(self.core(x)) After you define the logic of model, you can now define your automodel to manage the hyper-parameters. from autogl.module.model import BaseModel # define your automodel, need to inherit from BaseModel class MyAutoMLP(BaseModel): def __init__(self): # (required) make sure you call __init__ of super with init argument properly␣ ˓→set. # if you do not want to initialize inside __init__, please pass False. super().__init__(init=False) # (required) define the search space self.space = [ {'parameterName': 'layer_num', 'type': 'INTEGER', 'minValue': 1, 'maxValue':␣ ˓→5, 'scalingType': 'LINEAR'}, {'parameterName': 'dim', 'type': 'INTEGER', 'minValue': 64, 'maxValue': 128, ˓→'scalingType': 'LINEAR'} ] # set default hyper-parameters self.layer_num = 2 self.dim = 72 # for the hyper-parameters that are related with dataset, you can just set them␣ ˓→to None self.num_classes = None self.num_features = None # (required) since we don't know the num_classes and num_features until we see␣ ˓→the dataset, # we cannot initialize the models when instantiated. the initialized will be set␣ ˓→to False. self.initialized = False (continues on next page) AutoGL, Release v0.2.0rc0 (continued from previous page) # (required) set the device of current auto model self.device = torch.device('cuda') # (required) get current hyper-parameters of this automodel # need to return a dictionary whose keys are the same with self.space def get_hyper_parameter(self): return { 'layer_num': self.layer_num, 'dim': self.dim } # (required) override to interact with num_classes def get_num_classes(self): return self.num_classes # (required) override to interact with num_classes def set_num_classes(self, n_classes): self.num_classes = n_classes # (required) override to interact with num_features def get_num_features(self): return self.num_features # (required) override to interact with num_features def set_num_features(self, n_features): self.num_features = n_features # (required) instantiate the core MLP model using corresponding hyper-parameters def initialize(self): # (required) you need to make sure the core model is named as `self.model` self.model = MyMLP( in_channels = self.num_features, num_classes = self.num_classes, layer_num = self.layer_num, dim = self.dim ).to(self.device) self.initialized = True # (required) override to create a copy of model using provided hyper-parameters def from_hyper_parameter(self, hp): # hp is a dictionary that contains keys and values corrsponding to your self. ˓→space # in this case, it will be in form {'layer_num': XX, 'dim': XX} # create a new instance ret = self.__class__() # set the hyper-parameters related to dataset and device ret.num_classes = self.num_classes ret.num_features = self.num_features ret.device = self.device (continues on next page) AutoGL, Release v0.2.0rc0 (continued from previous page) # set the hyper-parameters according to hp ret.layer_num = hp['layer_num'] ret.dim = hp['dim'] # initialize it before returning ret.initialize() return ret Then, you can use this node classification model as part of AutoNodeClassifier solver. from autogl.solver import AutoNodeClassifier solver = AutoNodeClassifier(graph_models=(MyAutoMLP(),)) The model for graph classification is generally the same, except that you can now also re- ceive the num_graph_features (the dimension of the graph-level feature) through overriding set_num_graph_features(self, n_graph_features) of BaseModel. Also, please remember to return graph-level logits instead of node-level one in forward() of model. Model for link prediction For link prediction, the definition of model is a bit different with the common forward definition. You need to implement the lp_encode(self, data) and lp_decode(self, x, pos_edge_index, neg_edge_index) to interact with LinkPredictionTrainer and AutoLinkPredictor. Taking the class MyMLP defined above for example, if you want to perform link prediction: class MyMLPForLP(torch.nn.Module): # num_classes is removed since it is invalid for link prediction def __init__(self, in_channels, layer_num, dim): super().__init__() ops = [torch.nn.Linear(in_channels, dim)] for i in range(layer_num - 1): ops.append(torch.nn.Linear(dim, dim)) self.core = torch.nn.Sequential(*ops) # (required) for interaction with link prediction trainer and solver def lp_encode(self, data): return self.core(data.x) # (required) for interaction with link prediction trainer and solver def lp_decode(self, x, pos_edge_index, neg_edge_index): # first, get all the edge_index need calculated edge_index = torch.cat([pos_edge_index, neg_edge_index], dim=-1) # then, use dot-products to calculate logits, you can use whatever decode method␣ ˓→you want logits = (x[edge_index[0]] * x[edge_index[1]]).sum(dim=-1) return logits class MyAutoMLPForLP(MyAutoMLP): (continues on next page) AutoGL, Release v0.2.0rc0 (continued from previous page) def initialize(self): # init MyMLPForLP instead of MyMLP self.model = MyMLPForLP( in_channels = self.num_features, layer_num = self.layer_num, dim = self.dim ).to(self.device) self.initialized = True Model with sampling support Towards efficient representation learning on large-scale graph, AutoGL currently support node classification using sampling techniques including node-wise sampling, layer-wise sampling, and graph-wise sampling. See more about sampling in AutoGL Trainer. In order to conduct node classification using sampling technique with your custom model, further adaptation and mod- ification are generally required. According to the Message Passing mechanism of Graph Neural Network (GNN), numerous nodes in the multi-hop neighborhood of evaluation set or test set are potentially involved to evaluate the GNN model on large-scale graph dataset. As the representations for those numerous nodes are likely to occupy large amount of computational resource, the common forwarding process is generally infeasible for model evaluation on large-scale graph. An iterative representation learning mechanism is a practical and feasible way to evaluate Sequen- tial Model, which only consists of multiple sequential layers, with each layer taking a Data aggregate as input. The input Data has the same functionality with torch_geometric.data.Data, which conventionally provides properties x, edge_index, and optional edge_weight. If your custom model is composed of concatenated layers, you would bet- ter make your model inherit ClassificationSupportedSequentialModel to utilize the layer-wise representation learning mechanism to efficiently conduct representation learning for your custom sequential model. import autogl from autogl.module.model.base import ClassificationSupportedSequentialModel # override Linear so that it can take graph data as input class Linear(torch.nn.Linear): def forward(self, data): return super().forward(data.x) class MyMLPSampling(ClassificationSupportedSequentialModel): def __init__(self, in_channels, num_classes, layer_num, dim): super().__init__() if layer_num == 1: ops = [Linear(in_channels, num_classes)] else: ops = [Linear(in_channels, dim)] for i in range(layer_num - 2): ops.append(Linear(dim, dim)) ops.append(Linear(dim, num_classes)) self.core = torch.nn.ModuleList(ops) # (required) override sequential_encoding_layers property to interact with sampling @property (continues on next page) AutoGL, Release v0.2.0rc0 (continued from previous page) def sequential_encoding_layers(self) -> torch.nn.ModuleList: return self.core # (required) define the encode logic of classification for sampling def cls_encode(self, data): # if you use sampling, the data will be passed in two possible ways, # you can judge it use following rules if hasattr(data, 'edge_indexes'): # the edge_indexes are a list of edge_index, one for each layer edge_indexes = data.edge_indexes edge_weights = [None] * len(self.core) if getattr(data, 'edge_weights',␣ ˓→None) is None else data.edge_weights else: # the edge_index and edge_weight will stay the same as default edge_indexes = [data.edge_index] * len(self.core) edge_weights = [getattr(data, 'edge_weight', None)] * len(self.core) x = data.x for i in range(len(self.core)): data = autogl.data.Data(x=x, edge_index=edge_indexes[i]) data.edge_weight = edge_weights[i] x = self.sequential_encoding_layers[i](data) return x # (required) define the decode logic of classification for sampling def cls_decode(self, x): return torch.nn.functional.log_softmax(x) 3.5 AutoGL Trainer AutoGL project use trainer to handle the auto-training of tasks. Currently, we support the following tasks: • NodeClassificationTrainer for semi-supervised node classification • GraphClassificationTrainer for supervised graph classification • LinkPredictionTrainer for link prediction 3.5.1 Lazy Initialization Similar reason to :ref:model, we also use lazy initialization for all trainers. Only (part of) the hyper-parameters will be set when __init__() is called. The trainer will have its core model only after initialize() is explicitly called, which will be done automatically in solver and duplicate_from_hyper_parameter(), after all the hyper- parameters are set properly. AutoGL, Release v0.2.0rc0 3.5.2 Train and Predict After initializing a trainer, you can train it on the given datasets. We have given the training and testing functions for the tasks of node classification, graph classification, and link prediction up to now. You can also create your tasks following the similar patterns with ours. For training, you need to define train_only() and use it in train(). For testing, you need to define predict_proba() and use it in predict(). The evaluation function is defined in evaluate(), you can use your our evaluation metrics and methods. 3.5.3 Node Classification with Sampling According to various present studies, training with spatial sampling has been demonstrated as an efficient technique for representation learning on large-scale graph. We provide implementations for various representative sampling mechanisms including Neighbor Sampling, Layer Dependent Importance Sampling (LADIES), and GraphSAINT. With the leverage of various efficient sampling mechanisms, users can utilize this library on large-scale graph dataset, e.g. Reddit. Specifically, as various sampling techniques generally require model to support some layer-wise processing in forward- ing, now only the provided GCN and GraphSAGE models are ready for Node-wise Sampling (Neighbor Sampling) and Layer-wise Sampling (LADIES). More models and more tasks are scheduled to support sampling in future version. • Node-wise Sampling (GraphSAGE) Both GCN and GraphSAGE models are supported. • Layer-wise Sampling (Layer Dependent Importance Sampling) Only the GCN model is supported in current version. • Subgraph-wise Sampling (GraphSAINT) As The GraphSAINT sampling technique have no specific require- ments for model to adopt, most of the available models are feasible for adopting GraphSAINT technique. However, the prediction process is a potential bottleneck or even obstacle when the GraphSAINT tech- nique is actually applied on large-scale graph, thus the the model to adopt is better to support layer-wise prediction, and the provided GCN model already meet that enhanced requirement. According to empirical experiments, the implementation of GraphSAINT now has the leverage to support an integral graph smaller than the Flickr graph data. The sampling techniques can be utilized by adopting corresponding trainer NodeClassificationGraphSAINTTrainer, NodeClassificationLayerDependentImportanceSamplingTrainer, and NodeClassificationNeighborSamplingTrainer. You can either specify the corresponding name of trainer in YAML configuration file or instantiate the solver AutoNodeClassifier with the instance of specific trainer. However, please make sure to manange some key hyper-paramters properly inside the hyper-parameter space. Specifically: For NodeClassificationLayerDependentImportanceSamplingTrainer, you need to set the hyper-parameter sampled_node_sizes properly. The space of sampled_node_sizes should be a list of the same size with your Sequential Model. For example, if you have a model with layer number 4, you need to pass the hyper-parameter space properly: solver = AutoNodeClassifier( graph_models=(A_MODEL_WITH_4_LAYERS,), default_trainer='NodeClassificationLayerDependentImportanceSamplingTrainer', trainer_hp_space=[ # (required) you need to set the trainer_hp_space properly. { 'parameterName': 'sampled_node_sizes', 'type': 'NUMERICAL_LIST', (continues on next page) AutoGL, Release v0.2.0rc0 (continued from previous page) "numericalType": "INTEGER", "length": 4, # same with the layer number of your model "minValue": [200,200,200,200], "maxValue": [1000,1000,1000,1000], "scalingType": "LOG" }, ... ] ) If the layer number of your model is a searchable hyper-parameters, you can also set the cutPara and cutFunc properly, to make it connected with your layer number hyper-parameters of model. ''' Suppose the layer number of your model is of the following forms: { 'parameterName': 'layer_number', 'type': 'INTEGER', 'minValue': 2, 'maxValue': 4, 'scalingType': 'LOG' } ''' solver = AutoNodeClassifier( graph_models=(A_MODEL_WITH_DYNAMIC_LAYERS,), default_trainer='NodeClassificationLayerDependentImportanceSamplingTrainer', trainer_hp_space=[ # (required) you need to set the trainer_hp_space properly. { 'parameterName': 'sampled_node_sizes', 'type': 'NUMERICAL_LIST', "numericalType": "INTEGER", "length": 4, # max length "cutPara": ("layer_number", ), # link with layer_number "cutFunc": lambda x:x[0], # link with layer_number "minValue": [200,200,200,200], "maxValue": [1000,1000,1000,1000], "scalingType": "LOG" }, ... ] ) Similarly, if you want to use NodeClassificationNeighborSamplingTrainer, you need to make sure setting the hyper-parameter sampling_sizes the same length as the layer number of your model. For example: ''' Suppose the layer number of your model is of the following forms: { 'parameterName': 'layer_number', 'type': 'INTEGER', (continues on next page) AutoGL, Release v0.2.0rc0 (continued from previous page) 'minValue': 2, 'maxValue': 4, 'scalingType': 'LOG' } ''' solver = AutoNodeClassifier( graph_models=(A_MODEL_WITH_DYNAMIC_LAYERS,), default_trainer='NodeClassificationNeighborSamplingTrainer', trainer_hp_space=[ # (required) you need to set the trainer_hp_space properly. { 'parameterName': 'sampling_sizes', 'type': 'NUMERICAL_LIST', "numericalType": "INTEGER", "length": 4, # max length "cutPara": ("layer_number", ), # link with layer_number "cutFunc": lambda x:x[0], # link with layer_number "minValue": [20,20,20,20], "maxValue": [100,100,100,100], "scalingType": "LOG" }, ... ] ) You can also pass a trainer inside model list directly. A brief example is demonstrated as follows: ladies_sampling_trainer = NodeClassificationLayerDependentImportanceSamplingTrainer( model='gcn', num_features=dataset.num_features, num_classes=dataset.num_classes, ... ) ladies_sampling_trainer.hyper_parameter_space = [ # (required) you need to set the trainer_hp_space properly. { 'parameterName': 'sampled_node_sizes', 'type': 'NUMERICAL_LIST', "numericalType": "INTEGER", "length": 4, # max length "cutPara": ("num_layers", ), # link with layer_number "cutFunc": lambda x:x[0], # link with layer_number "minValue": [200,200,200,200], "maxValue": [1000,1000,1000,1000], "scalingType": "LOG" }, ... ] AutoNodeClassifier(graph_models=(ladies_sampling_trainer,), ...) AutoGL, Release v0.2.0rc0 3.6 Hyper Parameter Optimization We support black box hyper parameter optimization in variant search space. 3.6.1 Search Space Three types of search space are supported, use dict in python to define your search space. For numerical list search space. You can either assign a fixed length for the list, if so, you need not provide cutPara and cutFunc. Or you can let HPO cut the list to a certain length which is dependent on other parameters. You should provide those parameters’ names in curPara and the function to calculate the cut length in “cutFunc”. # numerical search space: { "parameterName": "xxx", "type": "DOUBLE" / "INTEGER", "minValue": xx, "maxValue": xx, "scalingType": "LINEAR" / "LOG" } # numerical list search space: { "parameterName": "xxx", "type": "NUMERICAL_LIST", "numericalType": "DOUBLE" / "INTEGER", "length": 3, "cutPara": ("para_a", "para_b"), "cutFunc": lambda x: x[0] - 1, "minValue": [xx,xx,xx], "maxValue": [xx,xx,xx], "scalingType": "LINEAR" / "LOG" } # categorical search space: { "parameterName": xxx, "type": "CATEGORICAL" "feasiblePoints": [a,b,c] } # fixed parameter as search space: { "parameterName": xxx, "type": "FIXED", "value": xxx } How given HPO algorithms support search space is listed as follows: AutoGL, Release v0.2.0rc0 Algorithm numerical numerical list categorical fixed Grid X X Random X X X X Anneal X X X X Bayes X X X X TPE1 X X X X CMAES2 X X X X MOCMAES3 X X X X Quasi random4 X X X X AutoNE5 X X X X 3.6.2 Add Your HPOptimizer If you want to add your own HPOptimizer, the only thing you should do is finishing optimize function in you HPOp- timizer: # For example, create a random HPO by yourself import random from autogl.module.hpo.base import BaseHPOptimizer class RandomOptimizer(BaseHPOptimizer): # Get essential parameters at initialization def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.max_evals = kwargs.get("max_evals", 2) # The most important thing you should do is completing optimization function def optimize(self, trainer, dataset, time_limit=None, memory_limit=None): # 1. Get the search space from trainer. space = trainer.hyper_parameter_space + trainer.model.hyper_parameter_space # optional: use self._encode_para (in BaseOptimizer) to pretreat the space # If you use _encode_para, the NUMERICAL_LIST will be spread to DOUBLE or␣ ˓→INTEGER, LOG scaling type will be changed to LINEAR, feasible points in CATEGORICAL␣ ˓→will be changed to discrete numbers. # You should also use _decode_para to transform the types of parameters back. current_space = self._encode_para(space) # 2. Define your function to get the performance. def fn(dset, para): current_trainer = trainer.duplicate_from_hyper_parameter(para) current_trainer.train(dset) loss, self.is_higher_better = current_trainer.get_valid_score(dset) # For convenience, we change the score which is higher better to negative,␣ ˓→then we should only minimize the score. (continues on next page) 1 Bergstra, <NAME>., et al. “Algorithms for hyper-parameter optimization.” Advances in neural information processing systems. 2011. 2 Arnold, <NAME>., and <NAME>. “Active covariance matrix adaptation for the (1+ 1)-CMA-ES.” Proceedings of the 12th annual confer- ence on Genetic and evolutionary computation. 2010. 3 <NAME>, <NAME>, and <NAME>. “Improved step size adaptation for the MO-CMA-ES.” Proceedings of the 12th annual conference on Genetic and evolutionary computation. 2010. 4 Bratley, Paul, <NAME>, and <NAME>. “Programs to generate Niederreiter’s low-discrepancy sequences.” ACM Transactions on Mathematical Software (TOMS) 20.4 (1994): 494-495. 5 Tu, Ke, et al. “Autone: Hyperparameter optimization for massive network embedding.” Proceedings of the 25th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining. 2019. AutoGL, Release v0.2.0rc0 (continued from previous page) if self.is_higher_better: loss = -loss return current_trainer, loss # 3. Define the how to get HP suggestions, it should return a parameter dict.␣ ˓→You can use history trials to give new suggestions def get_random(history_trials): hps = {} for para in current_space: # Because we use _encode_para function before, we should only deal with␣ ˓→DOUBLE, INTEGER and DISCRETE if para["type"] == "DOUBLE" or para["type"] == "INTEGER": hp = random.random() * (para["maxValue"] - para["minValue"]) + para[ ˓→"minValue"] if para["type"] == "INTEGER": hp = round(hp) hps[para["parameterName"]] = hp elif para["type"] == "DISCRETE": feasible_points = para["feasiblePoints"].split(",") hps[para["parameterName"]] = random.choice(feasible_points) return hps # 4. Run your algorithm. For each turn, get a set of parameters according to␣ ˓→history information and evaluate it. best_trainer, best_para, best_perf = None, None, None self.trials = [] for i in range(self.max_evals): # in this example, we don't need history trails. Since we pass None to␣ ˓→history_trails new_hp = get_random(None) # optional: if you use _encode_para, use _decode_para as well. para_for_ ˓→trainer undos all transformation in _encode_para, and turns double parameter to␣ ˓→interger if needed. para_for_hpo only turns double parameter to interger. para_for_trainer, para_for_hpo = self._decode_para(new_hp) current_trainer, perf = fn(dataset, para_for_trainer) self.trials.append((para_for_hpo, perf)) if not best_perf or perf < best_perf: best_perf = perf best_trainer = current_trainer best_para = para_for_trainer # 5. Return the best trainer and parameter. return best_trainer, best_para AutoGL, Release v0.2.0rc0 3.7 Neural Architecture Search We support different neural architecture search algorithm in variant search space. To be more flexible, we modulize NAS process with three part: algorithm, space and estimator. Different models in different parts can be composed in some certain constrains. If you want to design your own NAS process, you can change any of those parts according to your demand. 3.7.1 Usage You can directly enable architecture search for node classification tasks by passing the algorithms, spaces and estimators to solver. Following shows an example: # Use graphnas to solve cora from autogl.datasets import build_dataset_from_name from autogl.solver import AutoNodeClassifier solver = AutoNodeClassifier( feature = 'PYGNormalizeFeatures', graph_models = (), hpo = 'tpe', ensemble = None, nas_algorithms='rl', nas_spaces='graphnasmacro', nas_estimators='scratch' ) cora = build_dataset_from_name('cora') solver.fit(cora) The code above will first find the best architecture in space graphnasmacro using rl search algorithm. Then the searched architecture will be further optimized through hyperparameter-optimization tpe. Note: The graph_models argument is not conflict with nas module. You can set graph_models to other hand- crafted models beside the ones found by nas. Once the architectures are derived from nas module, they act in the same way as hand-crafted models directly passed through graph_models. 3.7.2 Search Space The space definition is base on mutable fashion used in NNI, which is defined as a model inheriting BaseSpace There are mainly two ways to define your search space, one can be performed with one-shot fashion while the other cannot. Currently, we support following search space: Space Description singlepath4 Architectures with several sequential layers with each layer choosing only one path graphnas1 The graph nas micro search space designed for fully supervised node classification models graphnasmacro1 The graph nas macro search space designed for semi-superwised node classification models 4 <NAME>, et al. “Single Path One-Shot Neural Architecture Search with Uniform Sampling.” European Conference on Computer Vision, 2019, pp. 544–560. 1 <NAME>, et al. “Graph neural architecture search.” IJCAI. Vol. 20. 2020. AutoGL, Release v0.2.0rc0 You can also define your own nas search space. If you need one-shot fashion, you should use the function setLayerChoice and setInputChoice to construct the super network. Here is an example. # For example, create an NAS search space by yourself from autogl.module.nas.space.base import BaseSpace from autogl.module.nas.space.operation import gnn_map class YourOneShotSpace(BaseSpace): # Get essential parameters at initialization def __init__(self, input_dim = None, output_dim = None): super().__init__() # must contain input_dim and output_dim in space, or you can initialize these␣ ˓→two parameters in function `instantiate` self.input_dim = input_dim self.output_dim = output_dim # Instantiate the super network def instantiate(self, input_dim, output_dim): # must call super in this function super().instantiate() self.input_dim = input_dim or self.input_dim self.output_dim = output_dim or self.output_dim # define two layers with order 0 and 1 self.layer0 = self.setLayerChoice(0, [gnn_map(op,self.input_dim,self.output_ ˓→dim)for op in ['gcn', 'gat']]) self.layer1 = self.setLayerChoice(1, [gnn_map(op,self.input_dim,self.output_ ˓→dim)for op in ['gcn', 'gat']]) # define an input choice two choose from the result of the two layer self.input_layer = self.setInputChoice(2, n_candidates = 2) # Define the forward process def forward(self, data): x, edges = data.x, data.edge_index x_0 = self.layer0(x, edges) x_1 = self.layer1(x, edges) y = self.input_layer([x_0, x_1]) return y # For one-shot fashion, you can directly use following scheme in ``parse_model`` def parse_model(self, selection, device) -> BaseModel: return self.wrap(device).fix(selection) Also, you can use the way which does not support one shot fashion. In this way, you can directly copy you model with few changes. But you can only use sample-based search strategy. # For example, create an NAS search space by yourself from autogl.module.nas.space.base import BaseSpace, map_nn from autogl.module.nas.space.operation import gnn_map # here we search from three types of graph convolution with `head` as a parameter # we should search `heads` at the same time with the convolution from torch_geometric.nn import GATConv, FeaStConv, TransformerConv class YourNonOneShotSpace(BaseSpace): # Get essential parameters at initialization def __init__(self, input_dim = None, output_dim = None): super().__init__() (continues on next page) AutoGL, Release v0.2.0rc0 (continued from previous page) # must contain input_dim and output_dim in space, or you can initialize these␣ ˓→two parameters in function `instantiate` self.input_dim = input_dim self.output_dim = output_dim # Instantiate the super network def instantiate(self, input_dim, output_dim): # must call super in this function super().instantiate() self.input_dim = input_dim or self.input_dim self.output_dim = output_dim or self.output_dim # set your choices as LayerChoices self.choice0 = self.setLayerChoice(0, map_nn(["gat", "feast", "transformer"]),␣ ˓→key="conv") self.choice1 = self.setLayerChoice(1, map_nn([1, 2, 4, 8]), key="head") # You do not need to define forward process here # For non-one-shot fashion, you can directly return your model based on the choices # ``YourModel`` must inherit BaseSpace. def parse_model(self, selection, device) -> BaseModel: model = YourModel(selection, self.input_dim, self.output_dim).wrap(device) return model # YourModel can be defined as follows class YourModel(BaseSpace): def __init__(self, selection, input_dim, output_dim): self.input_dim = input_dim self.output_dim = output_dim if selection["conv"] == "gat": conv = GATConv elif selection["conv"] == "feast": conv = FeaStConv elif selection["conv"] == "transformer": conv = TransformerConv self.layer = conv(input_dim, output_dim, selection["head"]) def forward(self, data): x, edges = data.x, data.edge_index y = self.layer(x, edges) return y 3.7.3 Performance Estimator The performance estimator estimates the performance of an architecture. Currently we support following estimators: Estimator Description oneshot Directly evaluating the given models without training scratch Train the models from scratch and then evaluate them You can also write your own estimator. Here is an example of estimating an architecture without training (used in one-shot space). AutoGL, Release v0.2.0rc0 # For example, create an NAS estimator by yourself from autogl.module.nas.estimator.base import BaseEstimator class YourOneShotEstimator(BaseEstimator): # The only thing you should do is defining ``infer`` function def infer(self, model: BaseSpace, dataset, mask="train"): device = next(model.parameters()).device dset = dataset[0].to(device) # Forward the architecture pred = model(dset)[getattr(dset, f"{mask}_mask")] y = dset.y[getattr(dset, f'{mask}_mask')] # Use default loss function and metrics to evaluate the architecture loss = getattr(F, self.loss_f)(pred, y) probs = F.softmax(pred, dim = 1) metrics = [eva.evaluate(probs, y) for eva in self.evaluation] return metrics, loss 3.7.4 Search Strategy The space strategy defines how to find an architecture. We currently support following search strategies: Strategy Description random Random search by uniform sampling rl? Use rl as architecture generator agent enas2 efficient neural architecture search darts3 differentiable neural architecture search Sample-based strategy without weight sharing is simpler than strategies with weight sharing. We show how to define your strategy here with DFS as an example. If you want to define more complex strategy, you can refer to Darts, Enas or other strategies in NNI. from autogl.module.nas.algorithm.base import BaseNAS class RandomSearch(BaseNAS): # Get the number of samples at initialization def __init__(self, n_sample): super().__init__() self.n_sample = n_sample # The key process in NAS algorithm, search for an architecture given space, dataset␣ ˓→and estimator def search(self, space: BaseSpace, dset, estimator): self.estimator=estimator self.dataset=dset self.space=space self.nas_modules = [] k2o = get_module_order(self.space) # collect all mutables in the space replace_layer_choice(self.space, PathSamplingLayerChoice, self.nas_modules) (continues on next page) 2 Pham, Hieu, et al. “Efficient neural architecture search via parameters sharing.” International Conference on Machine Learning. PMLR, 2018. 3 Liu, Hanxiao, <NAME>, and <NAME>. “DARTS: Differentiable Architecture Search.” International Conference on Learning Rep- resentations. 2018. AutoGL, Release v0.2.0rc0 (continued from previous page) replace_input_choice(self.space, PathSamplingInputChoice, self.nas_modules) # sort all mutables with given orders self.nas_modules = sort_replaced_module(k2o, self.nas_modules) # get a dict cantaining all chioces selection_range={} for k,v in self.nas_modules: selection_range[k]=len(v) self.selection_dict=selection_range arch_perfs=[] # define DFS process self.selection = {} last_k = list(self.selection_dict.keys())[-1] def dfs(): for k,v in self.selection_dict.items(): if not k in self.selection: for i in range(v): self.selection[k] = i if k == last_k: # evaluate an architecture self.arch=space.parse_model(self.selection,self.device) metric,loss=self._infer(mask='val') arch_perfs.append([metric, self.selection.copy()]) else: dfs() del self.selection[k] break dfs() # get the architecture with the best performance selection=arch_perfs[np.argmax([x[0] for x in arch_perfs])][1] arch=space.parse_model(selection,self.device) return arch Different search strategies should be combined with different search spaces and estimators in usage. Sapce single path GraphNAS[1] GraphNAS-macro[1] Random X X X RL X X X GraphNAS? X X X ENAS? X DARTSPage 26, 3 X Estimator one-shot Train Random X RL X GraphNAS? X ENAS? X DARTSPage 26, 3 X AutoGL, Release v0.2.0rc0 3.8 Ensemble We currently support voting and stacking methods. 3.8.1 Voting A voter essentially constructs a weighted sum of the predictions of base learners. Given an evaluation metric, the weights of base learners are specified in some way to maximize the validation score. We adopt Rich Caruana’s method for weight specification. This method first finds a collection of (possibly redundant) base learners with equal weights via a greedy search, then specifies the weights in the voter by the number of occurrence in the collection. You can customize your own weight specification method by overwriting the _specify_weights method. # An example : use equal weights for all base learners. class EqualWeightVoting(Voting): def _specify_weights(self, predictions, label, feval): return np.ones(self.n_models)/self.n_models # just allocate the same weight for each base learner 3.8.2 Stacking A stacker trains a meta-model with the predictions of base learners as input to find an optimal combination of these base learners. Currently we support generalized linear model (GLM) and gradient boosting model (GBM) as the meta-model. 3.8.3 Create a New Ensembler You can create your own ensembler by inheriting the base ensembler, and overloading methods fit and ensemble. # An example : use the currently available best model. from autogl.module.ensemble.base import BaseEnsembler import numpy as np class BestModel(BaseEnsembler): def fit(self, predictions, label, identifiers, feval): if not isinstance(feval, list): feval = [feval] scores = np.array([feval[0].evaluate(pred, label) for pred in predictions]) * (1␣ ˓→if feval[0].is_higher_better else -1) self.scores = dict(zip(identifiers, scores)) # record validation score of base␣ ˓→learners ensemble_pred = predictions[np.argmax(scores)] return [fx.evaluate(ensemble_pred, label) for fx in feval] def ensemble(self, predictions, identifiers): best_idx = np.argmax([self.scores[model_name] for model_name in identifiers]) #␣ ˓→choose the currently best model in the identifiers return predictions[best_idx] AutoGL, Release v0.2.0rc0 3.9 AutoGL Solver AutoGL project use solver to handle the auto-solvation of tasks. Currently, we support the following tasks: • AutoNodeClassifier for semi-supervised node classification • AutoGraphClassifier for supervised graph classification • AutoLinkPredictor for link prediction 3.9.1 Initialization A solver can either be initialized from its __init__() or from a config dictionary or file. Initialize from __init__() If you want to build a solver by __init__(), you need to pass the key modules to it. You can either pass the keywords of corresponding modules or the initialized instances: from autogl.solver import AutoNodeClassifier # 1. initialize from keywords solver = AutoNodeClassifier( feature_module='deepgl', graph_models=['gat','gcn'], hpo_module='anneal', ensemble_module='voting', device='auto' ) # 2. initialize using instances from autogl.module import AutoFeatureEngineer, AutoGCN, AutoGAT, AnnealAdvisorHPO, Voting solver = AutoNodeClassifier( feature_module=AutoFeatureEngineer(), graph_models=[AutoGCN(device='cuda'), AutoGAT(device='cuda')], hpo_module=AnnealAdvisorHPO(max_evals=10), ensemble_module=Voting(size=2), device='cuda' ) Where, the argument device means where to perform the training and searching, by setting to auto, the cuda is used when it is available. If you want to disable one module, you can set it to None: solver = AutoNodeClassifier(feature_module=None, hpo_module=None, ensemble_module=None) You can also pass some important arguments of modules directly to solver, which will automatically be set for you: solver = AutoNodeClassifier(hpo_module='anneal', max_evals=10) Refer to autogl.solver for more details of argument default value or important argument lists. AutoGL, Release v0.2.0rc0 Initialize from config dictionary or file You can also initialize a solver directly from a config dictionary or file. Currently, the AutoGL solver supports config file type of yaml or json. You need to use from_config() when you want to initialize in this way: # initialize from config file path_to_config = 'your/path/to/config' solver = AutoNodeClassifier.from_config(path_to_config) # initialize from a dictionary config = { 'models':{'gcn': None, 'gat': None}, 'hpo': {'name': 'tpe', 'max_evals': 10}, 'ensemble': {'name': 'voting', 'size': 2} } solver = AutoNodeClassifier.from_config(config) Refer to the config dictionary description Config structure for more details. 3.9.2 Optimization After initializing a solver, you can optimize it on the given datasets (please refer to AutoGL Dataset and autogl.datasets for creating datasets). You can use fit() or fit_predict() to perform optimization, which shares similar argument lists: # load your dataset here dataset = some_dataset() solver.fit(dataset, inplace=True) The inplace argument is used for saving memory if set to True. It will modify your dataset in an inplace manner during feature engineering. You can also specify the train_split and val_split arguments to let solver auto-split the given dataset. If these arguments are given, the split dataset will be used instead of the default split specified by the dataset provided. All the models will be trained on train dataset. Their hyperparameters will be optimized based on the performance of valid dataset, as well as the final ensemble method. For example: # split 0.2 of total nodes/graphs for train and 0.4 of nodes/graphs for validation, # the rest 0.4 is left for test. solver.fit(dataset, train_split=0.2, val_split=0.4) # split 600 nodes/graphs for train and 400 nodes/graphs for validation, # the rest nodes are left for test. solver.fit(dataset, train_split=600, val_split=400) For the node classification problem, we also support balanced sampling of train and valid: force the number of sampled nodes in different classes to be the same. The balanced mode can be turned on by setting balanced=True in fit(), which is by default set to True. Note: Solver will maintain the models with the best hyper-parameter of each model architecture you pass to solver (the graph_models argument when initialized). The maintained models will then be ensembled by ensemble module. AutoGL, Release v0.2.0rc0 After fit(), solver maintains the performances of every single model and the ensemble model in one leaderboard instance. You can output the performances on valid dataset by: # get current leaderboard of the solver lb = solver.get_leaderboard() # show the leaderboard info lb.show() You can refer to the leaderboard documentation in autogl.solver for more usage. 3.9.3 Prediction After optimized on the given dataset, you can make predictions using the fitted solver. Prediction using ensemble You can use the ensemble model constructed by solver to make the prediction, which is recommended and is the default choice: solver.predict() If you do not pass any dataset, the dataset during fitting will be used to give the prediction. You can also pass the dataset when predicting, please make sure the inplaced argument is properly set. solver.predict(dataset, inplaced=True, inplace=True) The predict() function also has inplace argument, which is the same as the one in fit(). As for the inplaced, it means whether the passed dataset is already modified inplace or not (probably by fit() function). If you use fit() before, please make the inplaced of predict() stay the same with inplace in fit(). Prediction using one single model You can also make the prediction using the best single model the solver maintains by: solver.predict(use_ensemble=False, use_best=True) Also, you can name the single model maintained by solver to make predictions. solver.predict(use_ensemble=False, use_best=False, name=the_name_of_model) The names of models can be derived by calling solver.trained_models.keys(), which is the same as the names maintained by the leaderboard of solver. Note: By default, solver will only make predictions on the test split of given datasets. Please make sure the passed dataset has the test split when making predictions. You can also change the default prediction split by setting argument mask to train or valid. AutoGL, Release v0.2.0rc0 3.9.4 Appendix Config structure The structure of the config file or config is introduced here. The config should be a dict, with five optional keys, namely feature, models, trainer, hpo and ensemble. You can simply do not add one field if you want to use the default option. The default value of each module is the same as the one in __init__(). For key feature, hpo and ensemble, their corresponding values are all dictionaries, which contains one must key name and other arguments when initializing the corresponding modules. The value of key name specifies which algorithm should be used, where None can be passed if you do not want to enable the module. Other arguments are used to initialize the specified algorithm. For key trainer, you should specify the hyperparameter space of trainer. See AutoGL Trainer or autogl.module.train for the detailed hyperparameter space of different trainers. For key models, the value is another dictionary with its keys being models that need optimized and the corresponding values being the hyperparameter space of that model. See AutoGL Model or autogl.module.model for the detailed hyperparameter space of different models. Below shows some examples of the config dictionary. config_for_node_classification = { 'feature': { 'name': 'deepgl', # name of auto feature module # following are the deepgl specified auto feature engineer arguments 'fixlen': 100, 'max_epoch': 5 }, 'models': { 'gcn': # specify the hp space of gcn [ {'parameterName': 'num_layers', 'type': 'DISCRETE', 'feasiblePoints': '2,3,4 ˓→'}, {'parameterName': 'hidden', 'type': 'NUMERICAL_LIST', 'numericalType': ˓→'INTEGER', 'length': 3, 'minValue': [8, 8, 8], 'maxValue': [64, 64, 64], 'scalingType': 'LOG'}, {'parameterName': 'dropout', 'type': 'DOUBLE', 'maxValue': 0.9, 'minValue':␣ ˓→0.1, 'scalingType': 'LINEAR'}, {'parameterName': 'act', 'type': 'CATEGORICAL', 'feasiblePoints': ['leaky_ ˓→relu', 'relu', 'elu', 'tanh']} ], 'gat': None, # set to None to use default hp space 'gin': None } 'trainer': [ # trainer hp space {'parameterName': 'max_epoch', 'type': 'INTEGER', 'maxValue': 300, 'minValue':␣ ˓→10, 'scalingType': 'LINEAR'}, {'parameterName': 'early_stopping_round', 'type': 'INTEGER', 'maxValue': 30, ˓→'minValue': 10, 'scalingType': 'LINEAR'}, {'parameterName': 'lr', 'type': 'DOUBLE', 'maxValue': 0.001, 'minValue': 0.0001, ˓→'scalingType': 'LOG'}, {'parameterName': 'weight_decay', 'type': 'DOUBLE', 'maxValue': 0.005, 'minValue ˓→': 0.0005, 'scalingType': 'LOG'} (continues on next page) AutoGL, Release v0.2.0rc0 (continued from previous page) ], 'hpo': { 'name': 'autone', # name of hpo module # following are the autone specified auto hpo arguments 'max_evals': 10, 'subgraphs': 10, 'sub_evals': 5 }, 'ensemble': { 'name': 'voting', # name of ensemble module # following are the voting specified auto ensemble arguments 'size': 2 } } config_for_graph_classification = { 'feature': None, # set to None to disable this module # do not add field `model` to use default settings of solver 'trainer': [ # trainer hp space {'parameterName': 'max_epoch', 'type': 'INTEGER', 'maxValue': 300, 'minValue':␣ ˓→10, 'scalingType': 'LINEAR'}, {'parameterName': 'batch_size', 'type': 'INTEGER', 'maxValue': 128, 'minValue':␣ ˓→32, 'scalingType': 'LOG'}, {'parameterName': 'early_stopping_round', 'type': 'INTEGER', 'maxValue': 30, ˓→'minValue': 10, 'scalingType': 'LINEAR'}, {'parameterName': 'lr', 'type': 'DOUBLE', 'maxValue': 1e-3, 'minValue': 1e-4, ˓→'scalingType': 'LOG'}, {'parameterName': 'weight_decay', 'type': 'DOUBLE', 'maxValue': 5e-3, 'minValue ˓→': 5e-4, 'scalingType': 'LOG'}, ], 'hpo': { 'name': 'random', # name of hpo module # following are the random specified auto hpo arguments 'max_evals': 10 }, 'ensemble': None # set to None to disable this module } 3.10 autogl.data class autogl.data.Batch(batch=None, **kwargs) A plain old python object modeling a batch of graphs as one big (dicconnected) graph. With cogdl.data.Data being the base class, all its methods can also be used here. In addition, single graphs can be reconstructed via the assignment vector batch, which maps each node to its respective graph identifier. cumsum(key, item) If True, the attribute key with content item should be added up cumulatively before concatenated together. Note: This method is for internal use only, and should only be overridden if the batch concatenation AutoGL, Release v0.2.0rc0 process is corrupted for a specific data attribute. static from_data_list(data_list, follow_batch=[]) Constructs a batch object from a python list holding torch_geometric.data.Data objects. The assign- ment vector batch is created on the fly. Additionally, creates assignment batch vectors for each key in follow_batch. property num_graphs Returns the number of graphs in the batch. to_data_list() Reconstructs the list of torch_geometric.data.Data objects from the batch object. The batch object must have been created via from_data_list() in order to be able reconstruct the initial objects. class autogl.data.Data(x=None, edge_index=None, edge_attr=None, y=None, pos=None) A plain old python object modeling a single graph with various (optional) attributes: Parameters • x (Tensor, optional) – Node feature matrix with shape [num_nodes, num_node_features]. (default: None) • edge_index (LongTensor, optional) – Graph connectivity in COO format with shape [2, num_edges]. (default: None) • edge_attr (Tensor, optional) – Edge feature matrix with shape [num_edges, num_edge_features]. (default: None) • y (Tensor, optional) – Graph or node targets with arbitrary shape. (default: None) • pos (Tensor, optional) – Node position matrix with shape [num_nodes, num_dimensions]. (default: None) The data object is not restricted to these attributes and can be extented by any other additional data. __call__(*keys) Iterates over all attributes *keys in the data, yielding their attribute names and content. If *keys is not given this method will iterative over all present attributes. __contains__(key) Returns True, if the attribute key is present in the data. __getitem__(key) Gets the data of the attribute key. __inc__(key, value) “Returns the incremental count to cumulatively increase the value of the next attribute of key when creating batches. Note: This method is for internal use only, and should only be overridden if the batch concatenation process is corrupted for a specific data attribute. __iter__() Iterates over all present attributes in the data, yielding their attribute names and content. __len__() Returns the number of all present attributes. __setitem__(key, value) Sets the attribute key to value. AutoGL, Release v0.2.0rc0 apply(func, *keys) Applies the function func to all attributes *keys. If *keys is not given, func is applied to all present attributes. cat_dim(key, value) Returns the dimension in which the attribute key with content value gets concatenated when creating batches. Note: This method is for internal use only, and should only be overridden if the batch concatenation process is corrupted for a specific data attribute. contiguous(*keys) Ensures a contiguous memory layout for all attributes *keys. If *keys is not given, all present attributes are ensured to have a contiguous memory layout. static from_dict(dictionary) Creates a data object from a python dictionary. get_label_number() Get the number of labels in this dataset as dict. is_coalesced() Returns True, if edge indices are ordered and do not contain duplicate entries. property keys Returns all names of graph attributes. property num_edges Returns the number of edges in the graph. property num_features Returns the number of features per node in the graph. random_splits_mask(train_ratio, val_ratio, seed=None) If the data has masks for train/val/test, return the splits with specific ratio. Parameters • train_ratio (float) – the portion of data that used for training. • val_ratio (float) – the portion of data that used for validation. • seed (int) – random seed for splitting dataset. random_splits_mask_class(num_train_per_class, num_val, num_test, seed=None) If the data has masks for train/val/test, return the splits with specific number of samples from every class for training. Parameters • num_train_per_class (int) – the number of samples from every class used for training. • num_val (int) – the total number of nodes that used for validation. • num_test (int) – the total number of nodes that used for testing. • seed (int) – random seed for splitting dataset. random_splits_nodes(train_ratio, val_ratio, seed=None) If the data uses id of nodes for train/val/test, return the splits with specific ratio. Parameters AutoGL, Release v0.2.0rc0 • train_ratio (float) – the portion of data that used for training. • val_ratio (float) – the portion of data that used for validation. • seed (int) – random seed for splitting dataset. random_splits_nodes_class(num_train_per_class, num_val, num_test, seed=None) If the data uses id of nodes for train/val/test, return the splits with specific number of samples from every class for training. Parameters • num_train_per_class (int) – the number of samples from every class used for training. • num_val (int) – the total number of nodes that used for validation. • num_test (int) – the total number of nodes that used for testing. • seed (int) – random seed for splitting dataset. to(device, *keys) Performs tensor dtype and/or device conversion to all attributes *keys. If *keys is not given, the conver- sion is applied to all present attributes. class autogl.data.DataListLoader(dataset, batch_size=1, shuffle=True, **kwargs) Data loader which merges data objects from a cogdl.data.dataset to a python list. Note: This data loader should be used for multi-gpu support via cogdl.nn.DataParallel. Parameters • dataset (Dataset) – The dataset from which to load the data. • batch_size (int, optional) – How may samples per batch to load. (default: 1) • shuffle (bool, optional) – If set to True, the data will be reshuffled at every epoch (default: True) class autogl.data.DataLoader(dataset, batch_size=1, shuffle=True, **kwargs) Data loader which merges data objects from a cogdl.data.dataset to a mini-batch. Parameters • dataset (Dataset) – The dataset from which to load the data. • batch_size (int, optional) – How may samples per batch to load. (default: 1) • shuffle (bool, optional) – If set to True, the data will be reshuffled at every epoch (default: True) class autogl.data.Dataset(root, transform=None, pre_transform=None, pre_filter=None) Dataset base class for creating graph datasets. See here for the accompanying tutorial. Parameters • root (string) – Root directory where the dataset should be saved. • transform (callable, optional) – A function/transform that takes in an cogdl.data. Data object and returns a transformed version. The data object will be transformed before every access. (default: None) AutoGL, Release v0.2.0rc0 • pre_transform (callable, optional) – A function/transform that takes in an cogdl. data.Data object and returns a transformed version. The data object will be transformed before being saved to disk. (default: None) • pre_filter (callable, optional) – A function that takes in an cogdl.data.Data ob- ject and returns a boolean value, indicating whether the data object should be included in the final dataset. (default: None) __getitem__(idx) Gets the data object at index idx and transforms it (in case a self.transform is given). __len__() The number of examples in the dataset. download() Downloads the dataset to the self.raw_dir folder. get(idx) Gets the data object at index idx. property get_label_number Get the number of labels in this dataset as dict. property num_features Returns the number of features per node in the graph. process() Processes the dataset to the self.processed_dir folder. property processed_file_names The name of the files to find in the self.processed_dir folder in order to skip the processing. property processed_paths The filepaths to find in the self.processed_dir folder in order to skip the processing. property raw_file_names The name of the files to find in the self.raw_dir folder in order to skip the download. property raw_paths The filepaths to find in order to skip the download. class autogl.data.DenseDataLoader(dataset, batch_size=1, shuffle=True, **kwargs) Data loader which merges data objects from a cogdl.data.dataset to a mini-batch. Note: To make use of this data loader, all graphs in the dataset needs to have the same shape for each its attributes. Therefore, this data loader should only be used when working with dense adjacency matrices. Parameters • dataset (Dataset) – The dataset from which to load the data. • batch_size (int, optional) – How may samples per batch to load. (default: 1) • shuffle (bool, optional) – If set to True, the data will be reshuffled at every epoch (default: True) autogl.data.download_url(url, folder, name=None, log=True) Downloads the content of an URL to a specific folder. Parameters AutoGL, Release v0.2.0rc0 • url (string) – The url. • folder (string) – The folder. • log (bool, optional) – If False, will not print anything to the console. (default: True) autogl.data.extract_tar(path, folder, mode='r:gz', log=True) Extracts a tar archive to a specific folder. Parameters • path (string) – The path to the tar archive. • folder (string) – The folder. • mode (string, optional) – The compression mode. (default: "r:gz") • log (bool, optional) – If False, will not print anything to the console. (default: True) autogl.data.extract_zip(path, folder, log=True) Extracts a zip archive to a specific folder. Parameters • path (string) – The path to the tar archive. • folder (string) – The folder. • log (bool, optional) – If False, will not print anything to the console. (default: True) 3.11 autogl.datasets We integrate the datasets from PyTorch Geometric, CogDL and OGB. We also list some datasets from CogDL for simplicity. 3.12 autogl.module.feature Several feature engineering operations are collected manually, or from PyTorch Geometric, NetworkX, etc. 3.13 autogl.module.model 3.14 autogl.module.train 3.15 autogl.module.hpo 3.16 autogl.module.nas 3.17 autogl.module.ensemble 3.18 autogl.solver CHAPTER FOUR INDICES AND TABLES • genindex • modindex • search 39 AutoGL, Release v0.2.0rc0 40 Chapter 4. Indices and tables PYTHON MODULE INDEX a autogl.data, 33 41 AutoGL, Release v0.2.0rc0 42 Python Module Index INDEX Symbols G __call__() (autogl.data.Data method), 34 get() (autogl.data.Dataset method), 37 __contains__() (autogl.data.Data method), 34 get_label_number (autogl.data.Dataset property), 37 __getitem__() (autogl.data.Data method), 34 get_label_number() (autogl.data.Data method), 35 __getitem__() (autogl.data.Dataset method), 37 __inc__() (autogl.data.Data method), 34 I __iter__() (autogl.data.Data method), 34 is_coalesced() (autogl.data.Data method), 35 __len__() (autogl.data.Data method), 34 __len__() (autogl.data.Dataset method), 37 K __setitem__() (autogl.data.Data method), 34 keys (autogl.data.Data property), 35 A M apply() (autogl.data.Data method), 34 module autogl.data autogl.data, 33 module, 33 B N Batch (class in autogl.data), 33 num_features (autogl.data.Data property), 35 cat_dim() (autogl.data.Data method), 35 contiguous() (autogl.data.Data method), 35 P cumsum() (autogl.data.Batch method), 33 process() (autogl.data.Dataset method), 37 processed_file_names (autogl.data.Dataset prop- Data (class in autogl.data), 34 processed_paths (autogl.data.Dataset property), 37 DataListLoader (class in autogl.data), 36 DataLoader (class in autogl.data), 36 R Dataset (class in autogl.data), 36 random_splits_mask() (autogl.data.Data method), 35 DenseDataLoader (class in autogl.data), 37 random_splits_mask_class() (autogl.data.Data download() (autogl.data.Dataset method), 37 method), 35 download_url() (in module autogl.data), 37 random_splits_nodes() (autogl.data.Data method), E random_splits_nodes_class() (autogl.data.Data extract_tar() (in module autogl.data), 38 method), 36 extract_zip() (in module autogl.data), 38 raw_file_names (autogl.data.Dataset property), 37 F from_data_list() (autogl.data.Batch static method), T 34 to() (autogl.data.Data method), 36 from_dict() (autogl.data.Data static method), 35 to_data_list() (autogl.data.Batch method), 34
ueberauth_weixin
hex
Erlang
Überauth Weixin === Wechat OAuth2 strategies for Überauth. Includes: * `:weixin` - Wechat open platform (https://open.weixin.qq.com) * `:wechat` - Wechat official accounts platform (https://mp.weixin.qq.com) Installation --- ``` def deps do {:ueberauth_weixin, "~> 1.0"} end ``` Usage --- ### Config router.ex in Phoenix project ``` scope "/auth", MyAppWeb do pipe_through :browser get "/:provider", AuthController, :request get "/:provider/callback", AuthController, :callback end ``` ### Config strategies * Wechat open platform ``` config :ueberauth, Ueberauth, providers: [ weixin: {Ueberauth.Strategy.Weixin, [uid_field: :unionid]} ] config :ueberauth, Ueberauth.Strategy.Weixin, client_id: "YOUR_APPID", client_secret: "YOUR_SECRET" ``` * Wechat official accounts platform ``` config :ueberauth, Ueberauth, providers: [ wechat: {Ueberauth.Strategy.Wechat, [uid_field: :unionid]} ] config :ueberauth, Ueberauth.Strategy.Wechat, client_id: "YOUR_APPID", client_secret: "YOUR_SECRET" ``` > Option `uid_field` has two values: `:openid` and `:unionid`. Default: `:openid`. > `uid` in `%Ueberauth.Auth{}`depends on this option. Workflow --- 1. Visit `/auth/:provider` to start the OAuth2 workflow 2. If authorization succeeds, it will redirect user back to `/auth/:provider/callback` with the `%Ueberauth.Auth{}` struct ``` def callback(%Plug.Conn{assigns: %{ueberauth_auth: auth}} = conn, _params) do %Ueberauth.Auth{provider: provider, uid: uid} = auth # other logic end ``` 3. If authorization fails, it will not redirect the user back. Ueberauth.Auth struct for :weixin strategy --- ``` %Ueberauth.Auth{ credentials: %Ueberauth.Auth.Credentials{ expires: true, expires_at: 1554813400, other: %{ "openid" => "o<KEY>hn5sPypKvep9zyds", "unionid" => "o2oUsuOUzgNL-JSLtIp8b3FzkI-M" }, refresh_token: "<KEY>", scopes: ["snsapi_login"], secret: nil, token: "<KEY>", token_type: "Bearer" }, extra: %Ueberauth.Auth.Extra{ raw_info: %{ "city" => "Baoshan", "country" => "CN", "headimgurl" => "http://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaELP0QPmPFD06qDibHBwWmEzibV3lr9PJufl0JDpeFicV2vg2uw2FLj7728KiaJeribZXWXIaM0WOpFlicAg/132", "language" => "zh_CN", "nickname" => "yejun.su", "openid" => "<KEY>", "privilege" => [], "province" => "Shanghai", "sex" => 1, "unionid" => "o2oUsuOUzgNL-JSLtIp8b3FzkI-M" } }, info: %Ueberauth.Auth.Info{ description: nil, email: nil, first_name: nil, image: "http://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaELP0QPmPFD06qDibHBwWmEzibV3lr9PJufl0JDpeFicV2vg2uw2FLj7728KiaJeribZXWXIaM0WOpFlicAg/132", last_name: nil, location: nil, name: "yejun.su", nickname: "yejun.su", phone: nil, urls: %{} }, provider: :weixin, strategy: Ueberauth.Strategy.Weixin, uid: "o2oUsuOUzgNL-JSLtIp8b3FzkI-M" } ``` Ueberauth.Auth struct for :wechat strategy --- ``` %Ueberauth.Auth{ credentials: %Ueberauth.Auth.Credentials{ expires: true, expires_at: 1555289733, other: %{"openid" => "oi00OuKAhA8bm5okpaIDs7WmUZr4"}, refresh_token: "<KEY>", scopes: ["snsapi_userinfo"], secret: nil, token: "<KEY>", token_type: "Bearer" }, extra: %Ueberauth.Auth.Extra{ raw_info: %{ "city" => "Baoshan", "country" => "CN", "headimgurl" => "http://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaELbibcX7pqYNlNy97Ipgu4B7E3FzxIcEnOKnPM1AOBEicqZq0l4xqque9iboicc9lbDictrGCCxzW3fgUg/132", "language" => "zh_CN", "nickname" => "yejun.su", "openid" => "oi00OuKAhA8bm5okpaIDs7WmUZr4", "privilege" => [], "province" => "Shanghai", "sex" => 1 } }, info: %Ueberauth.Auth.Info{ description: nil, email: nil, first_name: nil, image: "http://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaELbibcX7pqYNlNy97Ipgu4B7E3FzxIcEnOKnPM1AOBEicqZq0l4xqque9iboicc9lbDictrGCCxzW3fgUg/132", last_name: nil, location: nil, name: "yejun.su", nickname: "yejun.su", phone: nil, urls: %{} }, provider: :wechat, strategy: Ueberauth.Strategy.Wechat, uid: "oi00OuKAhA8bm5okpaIDs7WmUZr4" } ``` Ueberauth.Strategy.Wechat === OAuth2 login for https://mp.weixin.qq.com. Summary === [Functions](#functions) --- [auth(conn)](#auth/1) [authorize_url!(params \\ [])](#authorize_url!/1) [default_options()](#default_options/0) [get_token!(params \\ [], headers \\ [])](#get_token!/2) [Link to this section](#functions) Functions === Ueberauth.Strategy.Weixin === OAuth2 login for https://open.weixin.qq.com. Summary === [Functions](#functions) --- [auth(conn)](#auth/1) [authorize_url!(params \\ [])](#authorize_url!/1) [default_options()](#default_options/0) [get_token!(params \\ [], headers \\ [])](#get_token!/2) [Link to this section](#functions) Functions ===
sh
readthedoc
Python
# Usage sh Usage Passing Arguments Keyword Arguments Exit Codes & Exceptions Signals Redirection Filename File-like Object Function Callback Asynchronous Execution AsyncIO Incremental Iteration Background Processes Output Callbacks Interactive callbacks Done Callbacks Baking Piping Basic Advanced Sub-commands Default Arguments Environments Input via STDIN ‘With’ Contexts * Special Kwargs * Controlling Output * Execution * Communication * TTYs * Performance & Optimization * Program Arguments * Misc * Architecture Overview * API * Command Class * RunningCommand Class ``` RunningCommand.wait() ``` ``` RunningCommand.process ``` ``` RunningCommand.stdout ``` ``` RunningCommand.stderr ``` ``` RunningCommand.exit_code ``` * `RunningCommand.pid` * `RunningCommand.sid` * `RunningCommand.pgid` * `RunningCommand.ctty` * ``` RunningCommand.signal() ``` ``` RunningCommand.signal_group() ``` ``` RunningCommand.terminate() ``` ``` RunningCommand.kill() ``` ``` RunningCommand.kill_group() ``` ``` RunningCommand.is_alive() ``` * OProc Class * Exceptions * Helper Functions Contrib is an sh sub-module that provides friendly wrappers to useful commands. Typically, the commands being wrapped are unintuitive, and the contrib version makes them intuitive. Note Contrib commands should be considered generally unstable. They will grow and change as the community figures out the best interface for them. ## Commands ### Sudo Allows you to enter your password from the terminal at runtime, or as a string in your script. * sudo(password=None, *args, **kwargs) * Call sudo with `password` , if specified, else ask the executing user for a password at runtime via `getpass.getpass()` . See also ### Git Many git commands use a pager for output, which can cause an unexpected behavior when run through sh. To account for this, the contrib version sets `_tty_out=False` for all git commands. * git(*args, **kwargs) * Call git with STDOUT connected to a pipe, instead of a TTY. ``` from sh.contrib import git repo_log = git.log() ``` ### SSH New in version 1.13.0. SSH password-based logins can be a pain. This contrib command performs all of the ugly setup and provides a clean interface to using SSH. * ssh(interact=None, password=None, prompt_match=None, login_success=None, *args, **kwargs) * interact – A callback to handle SSH session interaction after login is successful. Required. * password – A password string or a function that returns a password string. Optional. If not provided, `getpass.getpass()` is used. * prompt_match – The string to match in order to determine when to provide SSH with the password. Or a function that matches on the output. Optional. * login_success – A function to determine if SSH login is successful. Optional. The `interact` parameter takes a callback with a signature that is slightly different to the function callbacks for redirection: * fn(content, stdin_queue) * content – An instance of an ephemeral SessionContent class whose job is to hold the characters that the SSH session has written to STDOUT. * stdin_queue – A `queue.Queue` object to communicate with STDIN programmatically. `password` can be simply a string that will be used to type the password. If it’s not provided, it will be read from STDIN at runtime via `getpass.getpass()` . It can also be a callable that returns the password string. `prompt_match` is a string to match before the contrib command will provide the SSH process with the password. It is optional, and if left unspecified, will default to “password: “. It can also be a callable that is called on a SessionContent instance and returns `True` or `False` for a match. `login_success` is a function that takes a SessionContent object and returns a boolean for whether or not a successful login occurred. It is optional, and if unspecified, simply evaluates to `True` , meaning any password submission results in a successful login (obviously not always correct). It is recommended that you specify this. * class SessionContent * This class contains a record lines and characters written to the SSH processes’s STDOUT. It should be all you need from the callbacks to determine how to interact with the SSH process. * SessionContent.chars * The previous 50,000 characters. * SessionContent.lines * The previous 5,000 lines. ## Extending For developers. To extend contrib, simply decorate a function in sh with the `@contrib` decorator, and pass in the name of the command you wish to shadow to the decorator. This method must return an instance of Command: ``` @contrib("ls") def my_ls(original): ls = original.bake("-l") return ls ``` Now you can run your custom contrib command from your scripts, and you’ll be using the command returned from your decorated function: ``` from sh.contrib import ls # executing: ls -l print(ls("/")) ``` For even more flexibility, you can design your contrib command to rewrite its options based on executed arguments. For example, say you only wish to set a command’s argument if another argument is set. You can accomplish it like this: ``` @contrib("ls") def my_ls(original): def process(args, kwargs): if "-a" in args: args.append("-L") return args, kwargs ls = original.bake("-l") return ls, process ``` Returning a process function along with the command will tell sh to use that function to preprocess the arguments at execution time using the _arg_preprocess special kwarg. There are 3 ways of using `sudo` to execute commands in your script. These are listed in order of usefulness and security. In most cases, you should just use a variation of sh.contrib.sudo. ## sh.contrib.sudo Because `sudo` is so frequently used, we have added a contrib version of the command to make sudo usage more intuitive. This contrib version is simply a wrapper around the sh.sudo raw command, but we bake in some special keyword argument to make it well-behaved. In particular, the contrib version allows you to specify your password at execution time via terminal input, or as a string in your script. ### Terminal Input Via a with context: with sh.contrib.sudo: print(ls("/root")) ``` Or alternatively via subcommands: ``` import sh print(sh.contrib.sudo.ls("/root")) ``` Output: ``` [sudo] password for youruser: ************* your_root_files.txt ``` In the above example, `sh.contrib.sudo` automatically asks you for a password using `getpass.getpass()` under the hood. This method is the most secure, because it lowers the chances of doing something insecure, like including your password in your python script, or by saying that a particular user can execute anything inside of a particular script (the NOPASSWD method). Note `sh.contrib.sudo` does not do password caching like the sudo binary does. Thie means that each time a sudo command is run in your script, you will be asked to type in a password. ### String Input You may also specify your password to `sh.contrib.sudo` as a string: password = get_your_password() with sh.contrib.sudo(password=password, _with=True): print(ls("/root")) ``` Warning This method is less secure because it becomes tempting to hard-code your password into the python script, and that’s a bad idea. However, it is more flexible, because it allows you to obtain your password from another source, so long as the end result is a string. ## /etc/sudoers NOPASSWD With this method, you can use the raw `sh.sudo` command directly, because you’re being guaranteed that the system will not ask you for a password. It first requires you set up your user to have root execution privileges Edit your sudoers file: `$> sudo visudo` Add or edit the line describing your user’s permissions: ``` yourusername ALL = (root) NOPASSWD: /path/to/your/program ``` This says `yourusername` on `ALL` hosts will be able to run as root, but only root `(root)` (no other users), and that no password `NOPASSWD` will be asked of ``` /path/to/your/program ``` . Warning This method can be insecure if an unprivileged user can edit your script, because the entire script will be exited as a privileged user. A malicious user could put something bad in this script. ## sh.sudo Using the raw command `sh.sudo` (which resolves directly to the system’s `sudo` binary) without NOPASSWD is possible, provided you wire up the special keyword arguments on your own to make it behave correctly. This method is discussed generally for educational purposes; if you take the time to wire up `sh.sudo` on your own, then you have in essence just recreated sh.contrib.sudo. # password must end in a newline my_password = "password\n" # -S says "get the password from stdin" my_sudo = sh.sudo.bake("-S", _in=my_password) print(my_sudo.ls("root")) ``` ## _fg=True Another less-obvious way of using sudo is by executing the raw `sh.sudo` command but also putting it in the foreground. This way, sudo will work correctly automatically, by hooking up stdin/out/err automatically, and by asking you for a password if it requires one. The downsides of using _fg=True, however, are that you cannot capture its output – everything is just printed to your terminal as if you ran it from a shell. ``` import sh sh.sudo.ls("/root", _fg=True) ``` # Tutorials sh Tutorials Tailing a real-time log file Entering an SSH password SSH Contrib command How you should REALLY be using SSH ## How do I execute a bash builtin? sh.bash("-c", "your_builtin") ``` Or builtins = sh.bash.bake("-c") builtins("your_builtin") ``` ## Will Windows be supported? There are no plans to support Windows. ## How do I append output to a file? Use a file object opened in the mode you desire: h = open("/tmp/output", "a") sh.ls("/dir1", _out=h) sh.ls("/dir2", _out=h) ``` ## Why does my command’s output have color? Typically the reason for this is that your program detected that its STDOUT was connected to a TTY, and therefore decided to print color escape sequences in its output. The typical solution is to use _tty_out=False, which will force a pipe to be connected to STDOUT, and probably change the behavior of the program. Git is one of the programs that makes extensive use of terminal colors (as well as pagers) in its output, so we added a contrib version for convenience. ## Why is _tty_out=True the default? This was a design decision made for two reasons: To make programs behave in the same way as seen on the commandline. * To provide better buffering control than pipes allow. For #1, we want sh to produce output that is identical to what the user sees from the commandline, because that’s typically the only output they ever see from their command. This makes the output easy to understand. For #2, using a TTY for STDOUT allows us to precisely control the buffering of a command’s output to sh’s internal code. Of course, there are some gotchas with TTY STDOUT. One of them is commands that use a pager, for example: This will sometimes raise a ``` SignalException_SIGPIPE ``` . The reason is because `git log` detects a TTY STDOUT and forks the system’s pager (typically `less` ) to handle the output. The pager checks for a controlling terminal, and, finding none, exits with exit code 1. The exit of the pager means no more readers on `git log` ’s output, and thus a `SIGPIPE` is received. One solution to the `git log` problem above is simply to use `_tty_out=False` . Another option, specifically for git, is to use the `git --no-pager` option: ``` import sh print(sh.git('--no-pager', 'log')) ``` ## Why doesn’t “*” work as a command argument? Glob expansion is a feature of a shell, like Bash, and is performed by the shell before passing the results to the program to be exec’d. Because sh is not a shell, but rather tool to execute programs directly, we do not handle glob expansion like a shell would. So in order to use `"*"` like you would on the commandline, pass it into `glob.glob()` first: ``` import sh import glob sh.ls(glob.glob("*.py")) ``` ## How do I call a program that isn’t in `$PATH` ? Use the `Command()` constructor to instantiate an instance of Command directly, then execute that: ``` import sh cmd = sh.Command("/path/to/command") cmd("-v", "arg1") ``` ## How do I execute a program with a dash in its name? If it’s in your `$PATH` , substitute the dash for an underscore: The above will run ``` google-chrome http://google.com ``` Note If a program named `google_chrome` exists on your system, that will be called instead. In that case, in order to execute the program with a dash in the name, you’ll have to use the method described here. ## How do I execute a program with a special character in its name? Programs with non-alphanumeric, non-dash characters in their names cannot be executed directly as an attribute on the sh module. For example, this will not work: ``` import sh sh.mkfs.ext4() ``` The reason should be fairly obvious. In Python, characters like `.` have special meaning, in this case, attribute access. What sh is trying to do in the above example is find the program “mkfs” (which may or may not exist) and then perform a subcommand lookup with the name “ext4”. In other words, it will try to call `mkfs` with the argument `ext4` , which is probably not what you want. The workaround is instantiating the Command Class with the string of the program you’re looking for: ``` import sh mkfsext4 = sh.Command("mkfs.ext4") mkfsext4() # run it ``` ## Why not use `|` to pipe commands? I prefer the syntax of sh to resemble function composition instead of a pipeline. One of the goals of sh is to make executing processes more like calling functions, not making function calls more like Bash. ## Why isn’t piping asynchronous by default? There is a non-obvious reason why async piping is not possible by default. Consider the following example: sh.cat(sh.echo("test\n1\n2\n3\n")) ``` When this is run, `sh.echo` executes and finishes, then the entire output string is fed into `sh.cat` . What we would really like is each newline-delimited chunk to flow to `sh.cat` incrementally. But for this example to flow data asynchronously from echo to cat, the echo command would need to not block. But how can the inner command know the context of its execution, to know to block sometimes but not other times? It can’t know that without something explicit. This is why the _piped special kwarg was introduced. By default, commands executed block until they are finished, so in order for an inner command to not block, `_piped=True` signals to the inner command that it should not block. This way, the inner command starts running, then very shortly after, the outer command starts running, and both are running simultaneously. Data can then flow from the inner command to the outer command asynchronously: sh.cat(sh.echo("test\n1\n2\n3\n", _piped=True)) ``` Again, this example is contrived – a better example would be a long-running command that produces a lot of output that you wish to pipe through another program incrementally. ## How do I run a command and connect it to sys.stdout and sys.stdin? There are two ways to do this See also You can use `sys.stdin` , `sys.stdout` , and `sys.stderr` as arguments to _in, _out, _err, respectively, and it should mostly work as expected: ``` import sh import sys sh.your_command(_in=sys.stdin, _out=sys.stdout) ``` There are a few reasons why this probably won’t work. The first reason is that `sys.stdin` is probably a controlling TTY (attached to the shell that launched the python process), and probably not set in raw mode termios(3), which means that, among other things, input is buffered by newlines. The real solution is to use _fg=True: ## Why do my arguments need to be separate strings? This confuses many new sh users. They want to do something like this and expect it to just work: ``` from sh import tar tar("cvf /tmp/test.tar /my/home/directory") ``` But instead they’ll get a confusing error message: ``` RAN: '/bin/tar cvf /tmp/test.tar /my/home/directory' STDOUT: STDERR: /bin/tar: Old option 'f' requires an argument. Try '/bin/tar --help' or '/bin/tar --usage' for more information. ``` The reason why they expect it to work is because shells, like Bash, automatically parse your commandline and break up arguments for you, before sending them to the binary. They have a complex set of rules (some of which are represented by `shlex` ) to take a single string of a command and arguments and separate them. Even if we wanted to implement this in sh (which we don’t), it would hurt the ability for users to parameterize parts of their arguments. They would have to use string interpolation, which would be ugly and error prone: ``` from sh import tar tar("cvf %s %s" % ("/tmp/tar1.tar", "/home/oh no a space") ``` In the above example, `"/home/oh"` , `"no"` , `"a"` , and `"space"` would all be separate arguments to tar, causing the program to behave unexpectedly. Basically every command with parameterized arguments would need to expect characters that could break the parser. ## How do I order keyword arguments? Typically this question gets asked when a user is trying to execute something like the following commandline: ``` my-command --arg1=val1 arg2 --arg3=val3 ``` This is usually the first attempt that they make: ``` sh.my_command(arg1="val1", "arg2", arg3="val3") ``` This doesn’t work because, in Python, position arguments, like `arg2` cannot come after keyword arguments. Furthermore, it is entirely possible that `--arg3=val3` comes before `--arg1=val1` . The reason for this is that a function’s `**kwargs` is an unordered mapping, and so key-value pairs are not guaranteed to resolve to a specific order. So the solution here is to forego the usage of the keyword argument convenience, and just use raw ordered arguments: ``` sh.my_command("--arg1=val1", "arg2", "--arg3=val3") ``` ## How to disable pylint E1101 no-member errors? Pylint complains with E1101 no-member to almost all `sh.command` invocations, because it doesn’t know, that these members are generated dynamically. Starting with Pylint 1.6 these messages can be suppressed using generated-members option. Just add following lines to `pylintrc` : ``` [TYPECHECK] generated-members=sh ``` ## How do I patch sh in my tests? sh can be patched in your tests the typical way, with ``` unittest.mock.patch() ``` : def get_something(): return sh.pwd() @patch("sh.pwd", create=True) def test_something(pwd): pwd.return_value = "/" assert get_something() == "/" ``` The important thing to note here is that `create=True` is set. This is required because sh is a bit magical and `patch` will fail to find the `pwd` command as an attribute on the sh module. You may also patch the `Command` class: def get_something(): pwd = sh.Command("pwd") return pwd() @patch("sh.Command") def test_something(Command): Command().return_value = "/" assert get_something() == "/" ``` Notice here we do not need `create=True` , because `Command` is not an automatically generated object on the sh module (it actually exists). ## Why is sh just a single file? When sh was first written, the design decision was made to make it a single-file module. This has pros and cons: Cons: Auditing the code is more challenging * Without file-enforced structure, adding more features and abstractions makes the code harder to follow * Cognitively, it feels cluttered Pros: Can be used easily on systems without Python package managers * Can be embedded/bundled together with other software more easily * Cognitively, it feels more self-contained In my mind, because the primary target audience of sh users is generally more scrappy devops, systems people, or people just trying to stitch together some clunky system programs, the listed pros weigh a little more heavily than the cons. Sacrificing some development advantages to give those users a more flexible tool is a win to me. Down the road, the development disadvantages of a single file can be solved with additional development tools, for example, with a tool that compiles multiple modules into the single sh.py file. Realistically, though, sh is pretty mature, so I don’t see it growing much more in complexity or code size. ## How do I see the commands sh is running? Use logging: logging.basicConfig(level=logging.INFO) sh.ls() ``` ``` INFO:sh.command:<Command '/bin/ls'>: starting process INFO:sh.command:<Command '/bin/ls', pid 32394>: process started INFO:sh.command:<Command '/bin/ls', pid 32394>: process completed ... ```
lomb
cran
R
Package ‘lomb’ October 13, 2022 Type Package Title Lomb-Scargle Periodogram Version 2.1.0 Date 2022-02-22 Author <NAME>, partially based on C original by Press et al. (Numeri- cal Recipes) and the Python module Astropy. Maintainer <NAME> <<EMAIL>> Description Computes the Lomb-Scargle Periodogram for unevenly sampled time series. In- cludes a randomization procedure to obtain exact p-values. License GPL (>= 3) Encoding UTF-8 LazyData true Imports ggplot2, gridExtra, plotly, pracma RoxygenNote 7.1.2 NeedsCompilation no Repository CRAN Date/Publication 2022-02-22 11:10:02 UTC R topics documented: lomb-packag... 2 getpeak... 3 ggamm... 4 ibe... 5 levop... 5 ls... 6 pbalue... 9 persho... 10 plot.ls... 10 randls... 11 summary.ls... 14 summary.randls... 15 theme_ls... 16 lomb-package Lomb-Scargle Periodogram Description The Lomb-Scargle periodogram is the most widely used method to detect even weak periodic com- ponents in unequally sampled time series. It can also be used for equally sampled time series. Details Package: lomb Type: Package Version: 2.1.0 Date: 2022-02-22 License: GPL-3 Function lsp computes the Lomb-Scargle periodogram for unevenly sampled times series (e.g., series with missing data). P-values for the highest peak in the periodogram are computed from the exponential distribution. Alternatively, function randlsp computes a p-value for the largest peak in the periodogram by repeatedly randomising the time-series sequence. Both functions allow setting the range of frequencies to be inspected, as well as the stepsize (oversampling factor) used for frequency scanning. Author(s) <NAME> Department of Interdisciplinary Life Sciences, University of Veterinary Medicine, Vienna, Austria Maintainer: <NAME> <<EMAIL>> References Ruf, T. (1999) The Lomb-Scargle Periodogram in Biological Rhythm Research: Analysis of In- complete and Unequally Spaced Time-Series. Biological Rhythm Research 30: 178–201 Examples data(lynx) lsp(lynx) getpeaks Retrieve periodogram peaks Description Retrieves and displays the npeaks largest peaks in the periodogram- Usage getpeaks(object,npeaks,plotit) Arguments object object must be of class "lsp" npeaks number of peaks to get plotit if TRUE show plot Value Returns a list with data A dataframe with times an heights of peaks plot An annotated periodogram Author(s) <NAME> <<EMAIL>> See Also show Examples per=lsp(lynx,ofac=5) getpeaks(per,6) # obtain the 6 largest peaks ggamma Utility function called by pbaluev() Description From astropy.timeseries Usage ggamma(N) Arguments N A positive number Value sqrt(2 / N) * exp(lgamma(N / 2) - lgamma((N - 1) / 2)) Author(s) <NAME> <<EMAIL>>. References VanderPlas, J. & <NAME>. (2015) Periodograms for Multiband Astronomical Time Series.The As- trophysical Journal 812.1:18 See Also pbaluev Examples ggamma(3) ibex Rumen Temperature In An Alpine Ibex Description Telemetric measurements of rumen temperature in a free-living alpine ibex (Capra ibex) measured at unequal time intervals. Usage data(ibex) Format A data frame with 1201 observations on 3 variables. date a character variable giving date and time of measurements. hours a numerical variable giving hours elapsed since the first measurement. temp a numerical variable giving rumen (stomach) temperature in degrees Celsius. Source A subset of data from <NAME>., <NAME>., <NAME>. (2011) Functional Ecology 25: 537-547. Examples data(ibex) datetime <- as.POSIXlt(ibex$date) plot(datetime,ibex$temp,pch=19,cex=0.3) levopt compute level Description utility function to determine deviation from p-value Usage levopt(x, alpha, fmax, tm) Arguments x alpha fmax tm Value (log(prob)-log(alpha))^2 Author(s) <NAME> <<EMAIL>>. lsp Lomb-Scargle Periodogram Description Computes the Lomb-Scargle periodogram for a time series with irregular (or regular) sampling intervals. Allows selecting a frequency range to be inspected, as well as the spacing of frequencies scanned. Usage lsp(x, times = NULL, from = NULL, to = NULL, type = c("frequency", "period"), ofac = 1, alpha = 0.01, normalize=c("standard","press"), plot = TRUE, ...) Arguments x The data to be analysed. x can be either a two-column numerical dataframe or matrix, with sampling times in column 1 and measurements in column 2, a single numerical vector containing measurements, or a single vector ts object (which will be converted to a numerical vector). times If x is a single vector, times can be provided as a numerical vector of equal length containing sampling times. If x is a vector and times is NULL, the data are assumed to be equally sampled and times is set to 1:length(x). from The starting frequency (or period, depending on type) to begin scanning for periodic components. to The highest frequency (or period, depending on type) to scan. type Either “frequency” (the default) or “period”. Determines the type of the peri- odogram x-axis. ofac The oversampling factor. Must be an integer>=1. Larger values of ofac lead to finer scanning of frequencies but may be time-consuming for large datasets and/or large frequency ranges (from...to). alpha The significance level. The periodogram plot shows a horizontal dashed line. Periodogram peaks exceeding this line can be considered significant at alpha. Defaults to 0.01. Only used if plot=TRUE. normalize The type of normalization used, either “standard” or “press”. If normalization is standard (the default) the periodogram is confined to the interval 0-1, and the statistical significance of the largest peak in the periodogram is computed according to Baluev (2008).if normalization is set to “press” the periodogram will be normalized using the factor 1/(2 * var(y)) and the p-value for the signif- icance of the largest peak in the periodogram is computed from the exponential distribution, as outlined in Press et al. (1994), see below plot Logical. If plot=TRUE the periodogram is plotted. ... Further graphical parameters affecting the periodogram plot. Details For a more robust - but potentially time-consuming estimation of p-values (when n is large) see randlsp. Significance levels in both lsp and randlsp increase with the number of frequencies inspected. Therefore, if the frequency-range of interest can be narrowed down a priori, use arguments “from” and “to” to do so. Value A named list with the following components: normalize The type of normalization used. scanned A vector containing the frequencies/periods scanned. power A vector containing the normalised power corresponding to scanned frequen- cies/periods. data Names of the data vectors analysed. n The length of the data vector. type The periodogram type used, either "frequency" or "period". ofac The oversampling factor used. n.out The length of the output (powers). This can be >n if ofac >1. alpha The false alarm probability used. sig.level Powers > sig.level can be considered significant peaks at p=alpha. peak The maximum power in the frequency/period interval inspected. peak.at The frequency/period at which the maximum peak occurred. p.value The probability that the maximum peak occurred by chance. Note For a description of the properties of the Lomb-Scargle Periodogram, its computation and compar- ison with other methods see <NAME>. (1999). Function lsp uses the algorithm given by Press et al (1994). The Lomb-Scargle Periodogram was originally proposed by Lomb N.R. (1976) and further extended by Scargle J.D. (1982). An improved method for assessing the statistical significance of candidate periodicities by Baluev (2008), based on extreme value theory, is also implemented. This implementation uses code modified from the astropy.timeseries Python package (VanderPlas et al. 2012, 2015). Author(s) <NAME> <<EMAIL>> based on code by Press et al (1994). References <NAME>. (2008). Assessing the statistical significance of periodogram peaks. Monthly Notices of the Royal Astronomical Society, 385(3), 1279-1285. Lomb N.R. (1976) Least-squares frequency analysis of unequally spaced data. Astrophysics and Space Science 39:447–462 Press W.H., <NAME>., <NAME>., <NAME>. (1994) Numerical recipes in C: the art of scientific computing.2nd edition. Cambridge University Press, Cambridge, 994pp. <NAME>. (1999) The Lomb-Scargle Periodogram in Biological Rhythm Research: Analysis of In- complete and Unequally Spaced Time-Series. Biological Rhythm Research 30: 178–201. Scargle J.D. (1982) Studies in astronomical time series. II. Statistical aspects of spectral analysis of unevenly spaced data. The Astrophysical Journal 302: 757–763. <NAME>., <NAME>. <NAME>. & <NAME>. (2012) Introduction to astroML: Machine learn- ing for astrophysics. Proceedings of the Conference on Intelligent Data Understanding VanderPlas, J. & <NAME>. (2015) Periodograms for Multiband Astronomical Time Series.The As- trophysical Jounal 812.1:18 See Also randlsp summary.lsp Examples # ibex contains an unevenly sampled time series data(ibex) lsp(ibex[,2:3],ofac=5) lsp(ibex$temp,times=ibex$hours,type='period',ofac=5) # lynx contains evenly sampled data lsp(lynx) lynx.spec <- lsp(lynx,type='period',from=2,to=20,ofac=5) summary(lynx.spec) # generate unevenly sampled data time=(runif(200,1,1000)) y=2*cos(time/6)+rnorm(200,0,4) lsp(y,times=time,ofac=10, to=0.3) pbaluev False alarm probability Description Computes the statistical significance of peaks (range 0-1) in the standardized perodogram. Typically not called by the user. Usage pbaluev(Z,fmax,tm) Arguments Z the height of a periodogram peak fmax the highest frequency inspected tm a vector with measurement timepoints Details Based on results in extreme value theory, improved analytic estimations of false alarm probabilities are given. Value Returns the significance of the largest peak in the periodogram. Note Code based on astropy.timeseries Author(s) <NAME> <<EMAIL>>. References Baluev, <NAME>. (2008). Assessing the statistical significance of periodogram peaks. Monthly Notices of the Royal Astronomical Society, 385(3), 1279-1285. See Also summary.lsp Examples pbaluev(0.19,2.0,1:100) pershow show periodogram Description Shows a periodogram in browser window as line and dot plot. When moving the cursor close to dots times an peak-heights of the periodogram are shown. Usage pershow(object) # object of class "lsp" Arguments object Author(s) <NAME> <<EMAIL>> See Also getpeaks Examples per=lsp(lynx,ofac=5) pershow(per) plot.lsp Plot Lomb-Scargle Periodogram Description Plots the normalised power as a function of frequency (or period, depending on type in function lsp). Usage ## S3 method for class 'lsp' plot(x, main = "Lomb-Scargle Periodogram", xlabel = NULL, ylabel = "normalized power", level = TRUE, plot=TRUE, ...) Arguments x Object of class lsp as returned from function lsp. main Character. Main title of the periodogram plot. Defaults to “Lomb-Sargle Peri- odogram”. xlabel Character. X-axis label of the periodogram plot. ylabel Character. Y-axis label of the periodogram plot. level Logical. If TRUE, the significance level is displayed as a dashed line. plot If TRUE, the periodogram is plotted. ... Additional graphics parameters Details Usually, this function is only called by function lsp. It maybe called by the user for some control of the output. For better control, plot results from lsp ($scanned, $power) as desired. Value Invisibly returns the object of class lsp it is called with. Author(s) <NAME> <<EMAIL>> See Also lsp Examples data(ibex) ibex.spec <- lsp(ibex[,2:3],type='period', from=12,to=36,ofac=10, plot=FALSE) plot.lsp(ibex.spec, main="Tb in Capra ibex",xlabel="Period (h)",ylabel="Power",level=FALSE) randlsp Randomise Lomb-Scargle Periodogram Description randlsp is used to obtain robust p-values for the significance of the largest peak in a Lomb-Scargle periodogram by randomisation. The data sequence is scrambled repeatedly and the probability of random peaks reaching or exceeding the peak in the original (unscrambled) periodogram is com- puted. Usage randlsp(repeats=1000,x, times = NULL, from = NULL, to = NULL, type = c("frequency", "period"), ofac = 1, alpha = 0.01, plot = TRUE, trace = TRUE, ...) Arguments repeats An integer determining the number of repeated randomisations. Large numbers (>=1000) are better but can make the procedure time-consuming. x The data to be analysed. x can be either a two-column numerical dataframe or matrix, with sampling times in columnn 1 and measurements in column 2, a single numerical vector containing measurements, or a single vector ts object (which will be converted to a numerical vector). times If x is a single vector, times can be provided as a numerical vector of equal length containing sampling times. If x is a vector and times is NULL, the data are assumed to be equally sampled and times is set to 1:length(x). from The starting frequency (or period, depending on type) to begin scanning for periodic components. to The highest frequency (or period, depending on type) to scan. type Either “frequency” (the default) or “period”. Determines the type of the peri- odogram x-axis. ofac The oversampling factor. Must be an integer >=1. Larger values of ofac lead to finer scanning of frequencies but may be time-consuming for large datasets and/or large frequency ranges (from...to). alpha The significance level. The periodogram plot shows a horizontal dashed line. Periodogram peaks exceeding this line can be considered significant at alpha. Defaults to 0.01. Only used if plot=TRUE. plot Logical. If TRUE, two plots are displayed (i) The periodogram of the original (unscrambled) data (ii) A histogram of peaks occurring by chance during se- quence randomisation. A vertical line is drawn at the height of the peak in a periodogram of the original data. trace Logical. If TRUE, information about the progress of the randomisation proce- dure is printed during the running of randlsp. ... Additional graphical parameters affecting the histogram plot. Details Function randlsp preserves the actual measurement intervals, which may affect the periodogram (see Nemec & Nemec 1985, below). Hence, this is a conservative randomisation procedure. P-values from both randlsp and lsp increase with the number of frequencies inspected. Therefore, if the frequency-range of interest can be narrowed down a priori, use arguments “from” and “to” to do so. Value A named list with the following items: scanned A vector containing the frequencies/periods scanned. power A vector containing the normalised power corresponding to scanned frequen- cies/periods. data Names of the data vectors analysed. n The length of the data vector. type The periodogram type used, either “frequency” or “period”. ofac The oversampling factor used. n.out The length of the output (powers). This can be >n if ofac >1. peak The maximum power in the frequency/period interval inspected. peak.at The frequency/period at which the maximum peak occurred. random.peaks A vector of peaks (with length=repeats) of maximum power values computed from randomised data. repeats The number of randomisations. p.value The probability that the peak in the original data occurred by chance, computed from randomising the data sequence. Author(s) <NAME> <<EMAIL>> References Nemec A.F.L, Nemec J.M. (1985) A test of significance for periods derived using phase-dispersion- miminimization techniques. The Astronomical Journal 90:2317–2320 See Also lsp Examples data(lynx) set.seed(444) rand.times <- sample(1:length(lynx),30) # select a random vector of sampling times randlsp(repeats=1000,lynx[rand.times],times=rand.times) summary.lsp Summarise Lomb-Scargle Periodogram Results Description Summary method for class lsp. Usage ## S3 method for class 'lsp' summary(object,...) Arguments object an object of class lsp. ... currently, no other arguments are required. Value summary.lsp returns a one column data.frame with results from function lsp. Row names and con- tents are as follows: Time Name of the sampling time variable. Data Name of the measured variable. Type either “frequency” or “period”. Oversampling factor The degree of oversampling (>=1). From The lowest frequency (or period, depending on type) inspected. To The highest frequency (or period, depending on type) inspected. # frequencies The number of frequencies (or periods, depending on type) inspected. PNmax The peak normalised power in the periodogram. At frequency The frequency at which PNmax occurred. At period The period at which PNmax occurred. P-value (PNmax) The probability that PNmax occurred by chance, computed from the exponential distribution. Author(s) <NAME> <<EMAIL>> See Also lsp Examples data(lynx) summary(lsp(lynx)) summary.randlsp Summarise Randomised Lomb-Scargle Periodogram Results Description Summary method for class randlsp. Usage ## S3 method for class 'randlsp' summary(object,...) Arguments object an object of class randlsp. ... currently, no other arguments are required. Value summary.randlsp returns a one column data.frame with results from function randlsp. Row names and contents are as follows: Time Name of the sampling time variable. Data Name of the measured variable. Type either “frequency” or “period”. Oversampling The degree of oversampling (>=1). From The lowest frequency (or period, depending on type) inspected. To The highest frequency (or period, depending on type) inspected. # frequencies The number of frequencies (or periods, depending on type) inspected. PNmax The peak normalised power in the periodogram. At frequency The frequency at which PNmax occurred. At period The period at which PNmax occurred. Repeats The number of randomisations. P-value (PNmax) The probability that PNmax occurred by chance, computed from randomising the data sequence. Author(s) <NAME> <<EMAIL>> See Also randlsp Examples data(lynx) summary(randlsp(repeats=500,lynx)) theme_lsp lsp theme for ggplot2 Description Import lsp ggplot2 theme. It builds on theme_bw. Usage theme_lsp(bs=18) Arguments bs basesize of font Value A theme element Examples plot(lsp(lynx))+theme_lsp(25)